Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

next
ts 678 lines 24.6 KB
Raw
1 import { Effect, Match, Option, pipe } from 'effect';
2 import { authorizationPollSchedule } from 'src/effects/authorization-poll';
3 import type { ComposioClientShape } from '@composio/client/effect';
4 import open from 'open';
5 import { commandInputError } from 'src/commands/errors';
6 import { actingUser, CommandSurface, type CommandTree } from 'src/commands/surface';
7 import { ComposioUserContext } from 'src/services/user-context';
8 import { TerminalUI } from 'src/services/terminal-ui';
9 import { failedWith } from 'src/effects/request-error';
10 import { reportFailure } from 'src/effects/report-failure';
11 import { resolveToolRouterSession } from 'src/effects/create-tool-router-session';
12 import { extractApiErrorDetails, extractMessage } from 'src/utils/api-error-extraction';
13 import { ProjectContext } from 'src/services/project-context';
14 import { ComposioClientSingleton } from 'src/services/composio-clients';
15 import { getSessionInfoByUserApiKey } from 'src/services/composio-account';
16 import { linkApolloIdentityForAnalytics } from 'src/analytics/dispatch';
17 import type { ResolvedCommandProject } from 'src/services/command-project';
18 import {
19 invalidateConsumerConnectedToolkitsCache,
20 writeConsumerConnectedToolkitsCache,
21 } from 'src/services/consumer-short-term-cache';
22 import { appendCliSessionHistory } from 'src/services/cli-session-artifacts';
23 import {
24 groupCachedConnectedAccountsByToolkit,
25 resolveDefaultConnectedAccountsByToolkit,
26 } from 'src/services/connected-account-selection';
27 import { decodeConnectedAccountItems } from 'src/effects/decode-connected-account-list';
28 import { idempotent } from 'src/services/composio-request';
29 import { listAllConnectedAccounts } from 'src/services/list-all-connected-accounts';
30 import {
31 BrowserOpenError,
32 ConnectedAccountsDecodeError,
33 ConnectedAccountsRequestError,
34 ConnectionPollingError,
35 } from './connected-accounts.link.errors';
36 import {
37 AUTH_CONFIG_SCOPE_MESSAGE,
38 BROWSE_AUTH_CONFIGS_HINT,
39 BROWSE_TOOLKITS_HINT,
40 INCOMPLETE_LINK_RESPONSE_MESSAGE,
41 LIST_REQUIRES_TOOLKIT_MESSAGE,
42 LIST_WITH_AUTH_CONFIG_MESSAGE,
43 ROOT_AUTH_CONFIG_MESSAGE,
44 TOOLKIT_AND_AUTH_CONFIG_MESSAGE,
45 activeConnectionMessage,
46 dashboardConnectUrl,
47 formatActiveLinkJson,
48 formatConnectedAccountsListJson,
49 formatPendingLinkJson,
50 missingArgumentMessage,
51 showAliasConflict,
52 showConnectedAccounts,
53 showExistingAccounts,
54 showRedirectUrl,
55 unmanagedAuthMessage,
56 type ExistingAccountLabel,
57 type LinkTarget,
58 } from './connected-accounts.link.format';
59
60 /**
61 * The flags of `link` on both trees. The `dev` group's `--user-id` and `--project-name` come
62 * from `CommandSurface`, not from here.
63 */
64 export type ConnectedAccountsLinkParams = {
65 readonly toolkit: Option.Option<string>;
66 readonly authConfig: Option.Option<string>;
67 readonly noWait: boolean;
68 readonly noBrowser: boolean;
69 readonly alias: Option.Option<string>;
70 readonly list: boolean;
71 };
72
73 /** The three things `link` does; the flags pick one. */
74 type LinkFlow = 'list' | 'legacy' | 'tool-router';
75
76 /** The command path a usage error carries, per tree: `dev connected-accounts link` under `dev`. */
77 const invalidOptionValueFor = (tree: CommandTree) =>
78 commandInputError(tree === 'dev' ? 'dev connected-accounts link' : 'link');
79
80 // --- shared steps -----------------------------------------------------------------------------
81
82 const projectScope = (project: ResolvedCommandProject) => ({
83 orgId: project.orgId,
84 projectId: project.projectId,
85 });
86
87 /**
88 * The consumer scope of a project, for the caches and session history that are consumer-only:
89 * some for a `CONSUMER` project with a consumer user, none for a developer project.
90 */
91 const consumerScope = (project: ResolvedCommandProject) =>
92 pipe(
93 Option.fromNullishOr(project.consumerUserId),
94 Option.filter(() => project.projectType === 'CONSUMER'),
95 Option.map(consumerUserId => ({
96 orgId: project.orgId,
97 projectId: project.projectId,
98 consumerUserId,
99 }))
100 );
101
102 /** The directory's project keys, or none when the directory is not initialized or unreadable. */
103 const directoryProject = Effect.gen(function* () {
104 const projectContext = yield* ProjectContext;
105 return yield* projectContext.resolve.pipe(Effect.option, Effect.map(Option.flatten));
106 });
107
108 /** `--alias` trimmed, or a usage error when it is blank. */
109 const resolveNormalizedAliasOption = (alias: Option.Option<string>, tree: CommandTree) =>
110 Effect.transposeOption(
111 Option.map(alias, rawAlias =>
112 Effect.fromOption(
113 Option.liftPredicate(rawAlias.trim(), trimmed => trimmed.length > 0),
114 () => invalidOptionValueFor(tree)('`--alias` cannot be empty.', '--alias')
115 )
116 )
117 );
118
119 /** Every active account in the user's toolkit or auth config. */
120 const listActiveConnectedAccounts = (params: {
121 readonly client: ComposioClientShape;
122 readonly userId: string;
123 readonly toolkitSlug?: string;
124 readonly authConfigId?: string;
125 }) =>
126 listAllConnectedAccounts(params.client, {
127 user_ids: [params.userId],
128 toolkit_slugs: params.toolkitSlug ? [params.toolkitSlug] : undefined,
129 auth_config_ids: params.authConfigId ? [params.authConfigId] : undefined,
130 statuses: ['ACTIVE'],
131 });
132
133 /**
134 * The accounts that power the `--alias` hints. This fetch is auxiliary: a transient list
135 * failure must not abort the link flow, so it answers with no accounts.
136 */
137 const existingAccountsForHints = (params: Parameters<typeof listActiveConnectedAccounts>[0]) =>
138 listActiveConnectedAccounts(params).pipe(
139 Effect.catch(() => Effect.succeed<ReadonlyArray<ExistingAccountLabel>>([]))
140 );
141
142 /**
143 * Succeeds when no existing account already carries `alias` (compared case-insensitively); fails
144 * already reported after explaining the conflict and how to use the existing account.
145 */
146 const ensureAliasIsAvailable = (params: {
147 readonly ui: TerminalUI;
148 readonly alias: Option.Option<string>;
149 readonly existingAccounts: ReadonlyArray<ExistingAccountLabel>;
150 readonly executeCommand: string;
151 readonly listCommand: string;
152 }) =>
153 Option.match(
154 Option.flatMap(params.alias, alias =>
155 Option.map(
156 Option.fromNullishOr(
157 params.existingAccounts.find(
158 item => item.alias?.trim().toLowerCase() === alias.toLowerCase()
159 )
160 ),
161 existing => ({ alias, existing })
162 )
163 ),
164 {
165 onNone: () => Effect.void,
166 onSome: ({ alias, existing }) =>
167 showAliasConflict(params.ui, {
168 alias,
169 existingId: existing.id,
170 executeCommand: params.executeCommand,
171 listCommand: params.listCommand,
172 }),
173 }
174 );
175
176 /**
177 * Succeeds when the new link may proceed: an alias was given, no account exists yet in the
178 * scope, or the link reuses an existing account. Fails already reported after listing the
179 * accounts that block it.
180 */
181 const ensureAliasForAdditionalAccount = (params: {
182 readonly ui: TerminalUI;
183 readonly alias: Option.Option<string>;
184 readonly connectedAccountId: string;
185 readonly existingAccounts: ReadonlyArray<ExistingAccountLabel>;
186 readonly scopeDescription: string;
187 }) => {
188 const blocked =
189 Option.isNone(params.alias) &&
190 params.existingAccounts.length > 0 &&
191 !params.existingAccounts.some(item => item.id === params.connectedAccountId);
192 return blocked
193 ? showExistingAccounts(params.ui, params.scopeDescription, params.existingAccounts)
194 : Effect.void;
195 };
196
197 /** A response field that is present and not blank. */
198 const nonEmpty = (value: string | null | undefined) =>
199 Option.filter(Option.fromNullishOr(value), text => text.length > 0);
200
201 /** The link the API answered with; an incomplete response is reported and fails (exit 1). */
202 const validateLinkResponse = (
203 ui: TerminalUI,
204 linkResponse: {
205 readonly connected_account_id?: string | null;
206 readonly redirect_url?: string | null;
207 }
208 ) =>
209 Option.match(
210 Option.zipWith(
211 nonEmpty(linkResponse.connected_account_id),
212 nonEmpty(linkResponse.redirect_url),
213 (connectedAccountId, redirectUrl): LinkTarget => ({ connectedAccountId, redirectUrl })
214 ),
215 {
216 onSome: target => Effect.succeed(target),
217 onNone: () =>
218 Effect.gen(function* () {
219 yield* Effect.logDebug('Link response:', linkResponse);
220 return yield* reportFailure(ui, INCOMPLETE_LINK_RESPONSE_MESSAGE);
221 }),
222 }
223 );
224
225 const openBrowser = (url: string) =>
226 Effect.tryPromise({
227 try: () => open(url, { wait: false }),
228 catch: cause => new BrowserOpenError({ message: 'Failed to open the browser.', cause }),
229 });
230
231 /** Polls the account until it is `ACTIVE`, on `authorizationPollSchedule` (ten minutes at most). */
232 const pollUntilActive = (client: ComposioClientShape, connectedAccountId: string) =>
233 Effect.retry(
234 Effect.gen(function* () {
235 const account = yield* client.connectedAccounts
236 .retrieve(connectedAccountId, idempotent)
237 .pipe(
238 failedWith(
239 ConnectedAccountsRequestError,
240 `Failed to fetch connected account "${connectedAccountId}".`
241 )
242 );
243 if (account.status === 'ACTIVE') {
244 return account;
245 }
246 return yield* new ConnectionPollingError({
247 message: `Connection status is still '${account.status}', waiting for 'ACTIVE'`,
248 connectedAccountId,
249 status: account.status,
250 });
251 }),
252 authorizationPollSchedule
253 );
254
255 /** Opens the authorization page unless `noBrowser`, then waits for the account to turn `ACTIVE`. */
256 const waitForActiveConnection = (
257 ui: TerminalUI,
258 client: ComposioClientShape,
259 target: LinkTarget,
260 noBrowser: boolean
261 ) =>
262 Effect.gen(function* () {
263 yield* showRedirectUrl(ui, target.redirectUrl, { manual: noBrowser, waiting: true });
264
265 const urlSchemeValid = Option.exists(
266 Option.liftThrowable((value: string) => new URL(value))(target.redirectUrl),
267 parsed => parsed.protocol === 'https:' || parsed.protocol === 'http:'
268 );
269 if (!urlSchemeValid) {
270 yield* ui.log.warn(`Redirect URL has an unexpected scheme: ${target.redirectUrl}`);
271 yield* ui.log.info('Open the URL manually if you trust the source.');
272 } else if (!noBrowser) {
273 yield* openBrowser(target.redirectUrl).pipe(
274 Effect.catchTag('commands/BrowserOpenError', error =>
275 Effect.gen(function* () {
276 yield* Effect.logDebug('Failed to open browser:', error);
277 yield* ui.log.warn('Could not open the browser automatically.');
278 yield* ui.log.info('Open the URL above manually.');
279 })
280 )
281 );
282 }
283
284 yield* ui.useMakeSpinner('Waiting for authorization...', spinner =>
285 pollUntilActive(client, target.connectedAccountId).pipe(
286 Effect.tap(account =>
287 Effect.all([
288 spinner.stop('Connection successful'),
289 ui.log.success(activeConnectionMessage(account)),
290 ui.output(formatActiveLinkJson({ account, redirectUrl: target.redirectUrl })),
291 ])
292 ),
293 Effect.tapError(() =>
294 spinner.error('Timed out waiting for authorization. Run the command again.')
295 )
296 )
297 );
298 });
299
300 /** Prints the `--no-wait` payload, or opens the page and waits, after a link was created. */
301 const finishLink = (params: {
302 readonly ui: TerminalUI;
303 readonly client: ComposioClientShape;
304 readonly target: LinkTarget;
305 readonly toolkit: Option.Option<string>;
306 readonly projectType: ResolvedCommandProject['projectType'];
307 readonly noWait: boolean;
308 readonly noBrowser: boolean;
309 }) =>
310 params.noWait
311 ? Effect.gen(function* () {
312 yield* showRedirectUrl(params.ui, params.target.redirectUrl, {
313 manual: true,
314 waiting: false,
315 });
316 yield* params.ui.output(
317 formatPendingLinkJson({
318 target: params.target,
319 toolkit: params.toolkit,
320 projectType: params.projectType,
321 }),
322 { force: true }
323 );
324 })
325 : waitForActiveConnection(params.ui, params.client, params.target, params.noBrowser);
326
327 /**
328 * Composio does not manage auth for the toolkit: send the user to the dashboard page that
329 * connects it, naming the org of the active membership when the session info answers.
330 */
331 const handleNoManagedAuth = (ui: TerminalUI, toolkitSlug: string, noBrowser: boolean) =>
332 Effect.gen(function* () {
333 const userContext = yield* ComposioUserContext;
334 const orgName = yield* Option.match(userContext.data.apiKey, {
335 onNone: () => Effect.succeed('~'),
336 onSome: userApiKey =>
337 Effect.gen(function* () {
338 const sessionInfo = yield* getSessionInfoByUserApiKey({
339 userApiKey,
340 orgId: Option.getOrUndefined(userContext.data.orgId),
341 }).pipe(Effect.option);
342 yield* Effect.transposeOption(
343 Option.map(sessionInfo, info =>
344 linkApolloIdentityForAnalytics(info.org_member.id, userApiKey)
345 )
346 );
347 return pipe(
348 sessionInfo,
349 Option.map(info => info.project.org.name),
350 Option.filter(name => name.length > 0),
351 Option.getOrElse(() => '~')
352 );
353 }),
354 });
355 const dashboardUrl = dashboardConnectUrl(userContext.data.webURL, orgName, toolkitSlug);
356
357 yield* ui.log.warn(unmanagedAuthMessage(toolkitSlug, noBrowser));
358 yield* noBrowser
359 ? Effect.void
360 : openBrowser(dashboardUrl).pipe(
361 Effect.catchTag('commands/BrowserOpenError', () =>
362 ui.log.warn('Could not open the browser automatically.')
363 )
364 );
365 yield* ui.note(dashboardUrl, 'Dashboard URL');
366 yield* ui.output(dashboardUrl);
367 });
368
369 // --- the three flows --------------------------------------------------------------------------
370
371 /**
372 * `link <toolkit> --list`: the acting user's active accounts in the toolkit, as a table on
373 * stderr and JSON on stdout.
374 */
375 export const handleListConnectedAccounts = (params: ConnectedAccountsLinkParams) =>
376 Effect.gen(function* () {
377 const ui = yield* TerminalUI;
378 const { tree } = yield* CommandSurface;
379 if (Option.isNone(params.toolkit)) {
380 return yield* Effect.fail(
381 invalidOptionValueFor(tree)(LIST_REQUIRES_TOOLKIT_MESSAGE, '--list')
382 );
383 }
384 if (Option.isSome(params.authConfig)) {
385 return yield* Effect.fail(
386 invalidOptionValueFor(tree)(LIST_WITH_AUTH_CONFIG_MESSAGE, '--list')
387 );
388 }
389 const toolkitSlug = params.toolkit.value;
390
391 const clientSingleton = yield* ComposioClientSingleton;
392 const { userId: resolvedUserId, project: resolvedProject } = yield* actingUser();
393 const client = yield* clientSingleton.getFor(projectScope(resolvedProject));
394
395 const accounts = yield* ui.withSpinner(
396 `Listing connected accounts for "${toolkitSlug}"...`,
397 listAllConnectedAccounts(client, {
398 toolkit_slugs: [toolkitSlug],
399 user_ids: [resolvedUserId],
400 statuses: ['ACTIVE'],
401 }).pipe(
402 failedWith(
403 ConnectedAccountsRequestError,
404 `Failed to list connected accounts for "${toolkitSlug}".`
405 )
406 )
407 );
408 const connectedAccounts = yield* decodeConnectedAccountItems(accounts).pipe(
409 Effect.mapError(
410 cause =>
411 new ConnectedAccountsDecodeError({
412 message: 'The API returned invalid connected account data.',
413 cause,
414 })
415 )
416 );
417
418 yield* Effect.transposeOption(
419 Option.map(consumerScope(resolvedProject), scope =>
420 writeConsumerConnectedToolkitsCache({
421 orgId: scope.orgId,
422 consumerUserId: scope.consumerUserId,
423 toolkits: [toolkitSlug],
424 toolRouterConnectedAccounts: {
425 connectedAccounts: resolveDefaultConnectedAccountsByToolkit(connectedAccounts),
426 availableConnectedAccounts: groupCachedConnectedAccountsByToolkit(connectedAccounts),
427 },
428 }).pipe(Effect.ignore)
429 )
430 );
431
432 yield* showConnectedAccounts(ui, toolkitSlug, connectedAccounts);
433 yield* ui.output(formatConnectedAccountsListJson(toolkitSlug, connectedAccounts), {
434 force: true,
435 });
436 });
437
438 /**
439 * `dev connected-accounts link --auth-config <id>`: the legacy flow against a developer
440 * project, without the Tool Router, as the acting user. A missing project is reported before a
441 * missing user.
442 */
443 export const handleLegacyAuthConfigLink = (params: ConnectedAccountsLinkParams) =>
444 Effect.gen(function* () {
445 const ui = yield* TerminalUI;
446 const { tree, projectName } = yield* CommandSurface;
447 // The dispatcher never gets here without --auth-config. This narrows it for direct callers.
448 if (Option.isNone(params.authConfig)) {
449 return yield* Effect.fail(
450 invalidOptionValueFor(tree)(missingArgumentMessage(tree), '--auth-config')
451 );
452 }
453 const authConfigId = params.authConfig.value;
454
455 const clientSingleton = yield* ComposioClientSingleton;
456 if (Option.isNone(projectName) && Option.isNone(yield* directoryProject)) {
457 return yield* Effect.fail(
458 invalidOptionValueFor(tree)(AUTH_CONFIG_SCOPE_MESSAGE, '--auth-config')
459 );
460 }
461 const acting = yield* actingUser();
462 const { userId: resolvedUserId, project: resolvedProject } = acting;
463
464 const client = yield* clientSingleton.getFor(projectScope(resolvedProject));
465 const normalizedAlias = yield* resolveNormalizedAliasOption(params.alias, tree);
466 const existingAccounts = yield* existingAccountsForHints({
467 client,
468 userId: resolvedUserId,
469 authConfigId,
470 });
471 yield* ensureAliasIsAvailable({
472 ui,
473 alias: normalizedAlias,
474 existingAccounts,
475 executeCommand: 'composio dev playground-execute',
476 listCommand: 'composio dev connected-accounts list',
477 });
478
479 const link = yield* ui
480 .withSpinner(
481 'Creating link session...',
482 client.link.create({
483 auth_config_id: authConfigId,
484 user_id: resolvedUserId,
485 ...(Option.isSome(normalizedAlias) && { alias: normalizedAlias.value }),
486 })
487 )
488 .pipe(
489 Effect.catch(error =>
490 reportFailure(
491 ui,
492 extractMessage(error) || `Failed to create link for auth config "${authConfigId}".`,
493 BROWSE_AUTH_CONFIGS_HINT
494 )
495 )
496 );
497
498 const target = yield* validateLinkResponse(ui, link);
499
500 yield* ensureAliasForAdditionalAccount({
501 ui,
502 alias: normalizedAlias,
503 connectedAccountId: target.connectedAccountId,
504 existingAccounts,
505 scopeDescription: `user "${resolvedUserId}" in auth config "${authConfigId}"`,
506 });
507
508 yield* finishLink({
509 ui,
510 client,
511 target,
512 toolkit: Option.none(),
513 projectType: resolvedProject.projectType,
514 noWait: params.noWait,
515 noBrowser: params.noBrowser,
516 });
517 });
518
519 /**
520 * `link <toolkit>`: the Tool Router flow as the acting user, against the consumer project on the
521 * root tree and the developer project on the dev tree. Records the link in the session history.
522 */
523 export const handleToolRouterLink = (params: ConnectedAccountsLinkParams) =>
524 Effect.gen(function* () {
525 const ui = yield* TerminalUI;
526 const { tree } = yield* CommandSurface;
527 // The dispatcher never gets here without a toolkit. This narrows it for direct callers.
528 if (Option.isNone(params.toolkit)) {
529 return yield* Effect.fail(
530 invalidOptionValueFor(tree)(missingArgumentMessage(tree), '<toolkit>')
531 );
532 }
533 const toolkitSlug = params.toolkit.value;
534
535 const normalizedAlias = yield* resolveNormalizedAliasOption(params.alias, tree);
536 const clientSingleton = yield* ComposioClientSingleton;
537 const { userId: resolvedUserId, project: resolvedProject } = yield* actingUser();
538 const client = yield* clientSingleton.getFor(projectScope(resolvedProject));
539 const existingAccounts = yield* existingAccountsForHints({
540 client,
541 userId: resolvedUserId,
542 toolkitSlug,
543 });
544 yield* ensureAliasIsAvailable({
545 ui,
546 alias: normalizedAlias,
547 existingAccounts,
548 ...(tree === 'dev'
549 ? {
550 executeCommand: 'composio dev playground-execute',
551 listCommand: `composio dev connected-accounts list --toolkits ${toolkitSlug}`,
552 }
553 : {
554 executeCommand: 'composio execute',
555 listCommand: `composio connections list --toolkit ${toolkitSlug}`,
556 }),
557 });
558
559 const scope = consumerScope(resolvedProject);
560 const linkOpt = yield* ui
561 .withSpinner(
562 `Linking ${toolkitSlug}...`,
563 Effect.gen(function* () {
564 const { sessionId } = yield* resolveToolRouterSession(client, resolvedUserId, {
565 manageConnections: true,
566 cacheScope: Option.getOrUndefined(scope),
567 excludeConnectedAccountsForToolkits: [toolkitSlug],
568 multiAccount: Option.isSome(normalizedAlias) ? { enable: true } : undefined,
569 });
570 return yield* client.toolRouter.session
571 .link(sessionId, {
572 toolkit: toolkitSlug,
573 ...(Option.isSome(normalizedAlias) && { alias: normalizedAlias.value }),
574 })
575 .pipe(
576 failedWith(
577 ConnectedAccountsRequestError,
578 `Failed to create link for toolkit "${toolkitSlug}".`
579 )
580 );
581 })
582 )
583 .pipe(
584 Effect.asSome,
585 Effect.catch(error =>
586 Effect.gen(function* () {
587 if (extractApiErrorDetails(error)?.slug === 'ToolRouterV2_NoManagedAuth') {
588 yield* handleNoManagedAuth(ui, toolkitSlug, params.noBrowser);
589 return Option.none();
590 }
591 yield* Effect.logDebug('Link error:', error);
592 return yield* reportFailure(
593 ui,
594 extractMessage(error) ?? `Failed to create link for toolkit "${toolkitSlug}".`,
595 BROWSE_TOOLKITS_HINT
596 );
597 })
598 ),
599 // On every outcome, a reported failure included.
600 Effect.ensuring(invalidateConsumerConnectedToolkitsCache().pipe(Effect.ignore))
601 );
602 if (Option.isNone(linkOpt)) return;
603
604 const target = yield* validateLinkResponse(ui, linkOpt.value);
605
606 yield* ensureAliasForAdditionalAccount({
607 ui,
608 alias: normalizedAlias,
609 connectedAccountId: target.connectedAccountId,
610 existingAccounts,
611 scopeDescription: `user "${resolvedUserId}" in toolkit "${toolkitSlug}"`,
612 });
613
614 yield* finishLink({
615 ui,
616 client,
617 target,
618 toolkit: Option.some(toolkitSlug),
619 projectType: resolvedProject.projectType,
620 noWait: params.noWait,
621 noBrowser: params.noBrowser,
622 });
623 yield* appendCliSessionHistory({
624 orgId: Option.getOrUndefined(Option.map(scope, s => s.orgId)),
625 consumerUserId: Option.getOrUndefined(Option.map(scope, s => s.consumerUserId)),
626 entry: {
627 command: 'link',
628 status: params.noWait ? 'pending' : 'active',
629 toolkit: toolkitSlug,
630 connectedAccountId: target.connectedAccountId,
631 redirectUrl: target.redirectUrl,
632 },
633 }).pipe(Effect.ignore);
634 });
635
636 // --- dispatch -----------------------------------------------------------------------------------
637
638 /**
639 * Which flow the flags select. A usage mistake the parser cannot see fails with a
640 * `CommandInputError`, so it reaches stderr and exits 1 even when stderr is not a TTY.
641 */
642 const selectLinkFlow = (params: ConnectedAccountsLinkParams, tree: CommandTree) =>
643 Effect.gen(function* () {
644 yield* resolveNormalizedAliasOption(params.alias, tree);
645 const select = (flow: LinkFlow) => Effect.succeed(flow);
646 return yield* Match.value({
647 tree,
648 toolkit: Option.isSome(params.toolkit),
649 authConfig: Option.isSome(params.authConfig),
650 list: params.list,
651 }).pipe(
652 Match.when({ tree: 'root', authConfig: true }, () =>
653 Effect.fail(invalidOptionValueFor(tree)(ROOT_AUTH_CONFIG_MESSAGE, '--auth-config'))
654 ),
655 Match.when({ toolkit: true, authConfig: true }, () =>
656 Effect.fail(invalidOptionValueFor(tree)(TOOLKIT_AND_AUTH_CONFIG_MESSAGE, '--auth-config'))
657 ),
658 Match.when({ toolkit: false, authConfig: false }, () =>
659 Effect.fail(invalidOptionValueFor(tree)(missingArgumentMessage(tree), '<toolkit>'))
660 ),
661 Match.when({ list: true }, () => select('list')),
662 Match.when({ authConfig: true }, () => select('legacy')),
663 Match.orElse(() => select('tool-router'))
664 );
665 });
666
667 /** `link` on either tree: validates the flag combination, then runs the flow it selects. */
668 export const runConnectedAccountsLink = (params: ConnectedAccountsLinkParams) =>
669 Effect.gen(function* () {
670 const { tree } = yield* CommandSurface;
671 const flow = yield* selectLinkFlow(params, tree);
672 yield* Match.value(flow).pipe(
673 Match.when('list', () => handleListConnectedAccounts(params)),
674 Match.when('legacy', () => handleLegacyAuthConfigLink(params)),
675 Match.when('tool-router', () => handleToolRouterLink(params)),
676 Match.exhaustive
677 );
678 });