1
-import { Effect, Option, Schedule } from 'effect';
1
+import { Effect, Match, Option, Schedule, pipe } from 'effect';
2
import type { ComposioClientShape } from '@composio/client/effect';
3
import open from 'open';
4
import { commandInputError } from 'src/commands/errors';
17
import { ComposioClientSingleton } from 'src/services/composio-clients';
18
import { getSessionInfoByUserApiKey } from 'src/services/composio-account';
19
import { linkApolloIdentityForAnalytics } from 'src/analytics/dispatch';
20
-import { resolveCommandProject } from 'src/services/command-project';
20
+import { resolveCommandProject, type ResolvedCommandProject } from 'src/services/command-project';
21
import {
22
invalidateConsumerConnectedToolkitsCache,
23
writeConsumerConnectedToolkitsCache,
24
} from 'src/services/consumer-short-term-cache';
25
import { appendCliSessionHistory } from 'src/services/cli-session-artifacts';
26
-import { formatConnectedAccountsTable } from '../format';
26
import {
27
groupCachedConnectedAccountsByToolkit,
28
resolveDefaultConnectedAccountsByToolkit,
36
ConnectionPollingError,
37
MissingLinkUserIdError,
38
} from './connected-accounts.link.errors';
40
-
39
+import {
40
+ AUTH_CONFIG_SCOPE_MESSAGE,
41
+ BROWSE_AUTH_CONFIGS_HINT,
42
+ BROWSE_TOOLKITS_HINT,
43
+ INCOMPLETE_LINK_RESPONSE_MESSAGE,
44
+ LIST_REQUIRES_TOOLKIT_MESSAGE,
45
+ LIST_WITH_AUTH_CONFIG_MESSAGE,
46
+ ROOT_AUTH_CONFIG_MESSAGE,
47
+ TOOLKIT_AND_AUTH_CONFIG_MESSAGE,
48
+ activeConnectionMessage,
49
+ dashboardConnectUrl,
50
+ formatActiveLinkJson,
51
+ formatConnectedAccountsListJson,
52
+ formatPendingLinkJson,
53
+ missingArgumentMessage,
54
+ showAliasConflict,
55
+ showConnectedAccounts,
56
+ showExistingAccounts,
57
+ showRedirectUrl,
58
+ unmanagedAuthMessage,
59
+ type ExistingAccountLabel,
60
+ type LinkTarget,
61
+} from './connected-accounts.link.format';
62
+
63
+/**
64
+ * The flags of `link` on both trees. The `dev` group's `--user-id` and `--project-name` come
65
+ * from `CommandSurface`, not from here.
66
+ */
67
export type ConnectedAccountsLinkParams = {
68
readonly toolkit: Option.Option<string>;
69
readonly authConfig: Option.Option<string>;
73
readonly list: boolean;
74
};
75
50
-const invalidOptionValue = commandInputError('link');
51
-
52
-const showRedirectUrl = (
53
- ui: TerminalUI,
54
- redirectUrl: string,
55
- options?: { readonly emitRaw?: boolean; readonly manual?: boolean }
56
-) =>
57
- Effect.gen(function* () {
58
- yield* ui.log.step(
59
- options?.manual
60
- ? 'Open this URL in your browser to authorize'
61
- : 'Redirecting you to the authorization page'
62
- );
63
- yield* ui.note(redirectUrl, 'Redirect URL');
64
- if (options?.emitRaw) {
65
- yield* ui.output(redirectUrl);
66
- }
67
- });
68
-
69
-const waitForActiveConnection = (
70
- ui: TerminalUI,
71
- client: ComposioClientShape,
72
- connectedAccountId: string,
73
- redirectUrl: string,
74
- noBrowser: boolean
75
-) =>
76
- Effect.gen(function* () {
77
- yield* showRedirectUrl(ui, redirectUrl, { manual: noBrowser });
78
-
79
- const parsedUrl = Option.liftThrowable((value: string) => new URL(value))(redirectUrl);
80
- const urlSchemeValid = Option.exists(
81
- parsedUrl,
82
- parsed => parsed.protocol === 'https:' || parsed.protocol === 'http:'
83
- );
84
-
85
- if (!urlSchemeValid) {
86
- yield* ui.log.warn(`Redirect URL has an unexpected scheme: ${redirectUrl}`);
87
- yield* ui.log.info('Open the URL manually if you trust the source.');
88
- } else if (!noBrowser) {
89
- yield* Effect.tryPromise({
90
- try: () => open(redirectUrl, { wait: false }),
91
- catch: cause => new BrowserOpenError({ message: 'Failed to open the browser.', cause }),
92
- }).pipe(
93
- Effect.catchTag('commands/BrowserOpenError', error =>
94
- Effect.gen(function* () {
95
- yield* Effect.logDebug('Failed to open browser:', error);
96
- yield* ui.log.warn('Could not open the browser automatically.');
97
- yield* ui.log.info('Open the URL above manually.');
98
- })
99
- )
100
- );
101
- }
76
+/** The three things `link` does; the flags pick one. */
77
+type LinkFlow = 'list' | 'legacy' | 'tool-router';
78
103
- yield* ui.useMakeSpinner('Waiting for authentication...', spinner =>
104
- Effect.retry(
105
- Effect.gen(function* () {
106
- const account = yield* client.connectedAccounts
107
- .retrieve(connectedAccountId, idempotent)
108
- .pipe(
109
- failedWith(
110
- ConnectedAccountsRequestError,
111
- `Failed to fetch connected account "${connectedAccountId}".`
112
- )
113
- );
114
- if (account.status === 'ACTIVE') {
115
- return account;
116
- }
117
- return yield* new ConnectionPollingError({
118
- message: `Connection status is still '${account.status}', waiting for 'ACTIVE'`,
119
- connectedAccountId,
120
- status: account.status,
121
- });
122
- }),
123
- // Retries with the max delay of a 0.3s exponential ramp and a flat 5s spacing,
124
- // capped at 15 attempts.
125
- Schedule.max([Schedule.exponential('0.3 seconds'), Schedule.spaced('5 seconds')]).pipe(
126
- Schedule.upTo({ times: 15 })
127
- )
128
- ).pipe(
129
- Effect.tap(account => {
130
- const message = `Connected account "${account.id}" is now ACTIVE (toolkit: ${account.toolkit.slug}).`;
131
- return Effect.all([
132
- spinner.stop('Connection successful'),
133
- ui.log.success(message),
134
- ui.output(
135
- JSON.stringify(
136
- {
137
- status: 'success',
138
- message,
139
- connected_account_id: account.id,
140
- toolkit: account.toolkit.slug,
141
- redirect_url: redirectUrl,
142
- },
143
- null,
144
- 2
145
- )
146
- ),
147
- ]);
148
- }),
149
- Effect.tapError(() => spinner.error('Connection timed out. Please try again.'))
150
- )
151
- );
152
- });
153
-
154
-const validateLinkResponse = (
155
- ui: TerminalUI,
156
- linkResponse: {
157
- connected_account_id?: string | null;
158
- redirect_url?: string | null;
159
- }
160
-) =>
161
- Effect.gen(function* () {
162
- const connectedAccountId = linkResponse.connected_account_id;
163
- const redirectUrl = linkResponse.redirect_url;
164
-
165
- if (!connectedAccountId || !redirectUrl) {
166
- yield* ui.log.error(
167
- 'The API returned an incomplete link response (missing connected_account_id or redirect_url).'
168
- );
169
- yield* Effect.logDebug('Link response:', linkResponse);
170
- return Option.none();
171
- }
172
-
173
- return Option.some({
174
- connectedAccountId,
175
- redirectUrl,
176
- });
177
- });
178
-
179
-const handleNoManagedAuth = (ui: TerminalUI, toolkitSlug: string, noBrowser: boolean) =>
180
- Effect.gen(function* () {
181
- const userContext = yield* ComposioUserContext;
182
- const webURL = userContext.data.webURL.replace(/\/+$/, '');
183
- const apiKey = Option.getOrUndefined(userContext.data.apiKey);
184
-
185
- let orgName = '~';
186
- if (apiKey) {
187
- const sessionInfo = yield* getSessionInfoByUserApiKey({
188
- userApiKey: apiKey,
189
- orgId: Option.getOrUndefined(userContext.data.orgId),
190
- }).pipe(Effect.catch(() => Effect.succeed(null)));
191
-
192
- if (sessionInfo) {
193
- yield* linkApolloIdentityForAnalytics(sessionInfo.org_member.id, apiKey);
194
- }
195
-
196
- if (sessionInfo?.project.org.name) {
197
- orgName = sessionInfo.project.org.name;
198
- }
199
- }
200
-
201
- // Encode path segments so special characters in org names (spaces, @, etc.)
202
- // don't corrupt the URL structure — without this, `?open=true` can get
203
- // baked into the path as `%3Fopen%3Dtrue`, causing 404s on the dashboard.
204
- const dashboardUrl = `${webURL}/${encodeURIComponent(orgName)}/~/connect/apps/${encodeURIComponent(toolkitSlug)}?open=true`;
205
-
206
- yield* ui.log.warn(
207
- `Composio does not manage auth for "${toolkitSlug}" — ${noBrowser ? 'open the dashboard' : 'opening the dashboard'} to connect manually.`
208
- );
209
-
210
- if (!noBrowser) {
211
- yield* Effect.tryPromise({
212
- try: () => open(dashboardUrl, { wait: false }),
213
- catch: cause => new BrowserOpenError({ message: 'Failed to open the browser.', cause }),
214
- }).pipe(
215
- Effect.catchTag('commands/BrowserOpenError', () =>
216
- ui.log.warn('Could not open the browser automatically.')
217
- )
218
- );
219
- }
220
-
221
- yield* ui.note(dashboardUrl, 'Dashboard URL');
222
- yield* ui.output(dashboardUrl);
223
- });
79
+const invalidOptionValue = commandInputError('link');
80
225
-const getConsumerCacheScope = (resolvedProject: {
226
- readonly orgId: string;
227
- readonly projectId: string;
228
- readonly projectType: 'CONSUMER' | 'DEVELOPER';
229
- readonly consumerUserId?: string;
230
-}) =>
231
- resolvedProject.projectType === 'CONSUMER' && resolvedProject.consumerUserId
232
- ? {
233
- orgId: resolvedProject.orgId,
234
- projectId: resolvedProject.projectId,
235
- consumerUserId: resolvedProject.consumerUserId,
236
- }
237
- : undefined;
81
+// --- shared steps -----------------------------------------------------------------------------
82
+
83
+const projectScope = (project: ResolvedCommandProject) => ({
84
+ orgId: project.orgId,
85
+ projectId: project.projectId,
86
+});
87
+
88
+/**
89
+ * The consumer scope of a project, for the caches and session history that are consumer-only:
90
+ * some for a `CONSUMER` project with a consumer user, none for a developer project.
91
+ */
92
+const consumerScope = (project: ResolvedCommandProject) =>
93
+ pipe(
94
+ Option.fromNullishOr(project.consumerUserId),
95
+ Option.filter(() => project.projectType === 'CONSUMER'),
96
+ Option.map(consumerUserId => ({
97
+ orgId: project.orgId,
98
+ projectId: project.projectId,
99
+ consumerUserId,
100
+ }))
101
+ );
102
239
-const normalizeAlias = (rawAlias: string) => rawAlias.trim();
103
+/** The directory's project keys, or none when the directory is not initialized or unreadable. */
104
+const directoryProject = Effect.gen(function* () {
105
+ const projectContext = yield* ProjectContext;
106
+ return yield* projectContext.resolve.pipe(Effect.option, Effect.map(Option.flatten));
107
+});
108
109
+/** `--alias` trimmed, or a usage error when it is blank. */
110
const resolveNormalizedAliasOption = (alias: Option.Option<string>) =>
242
- Effect.gen(function* () {
243
- if (Option.isNone(alias)) {
244
- return Option.none<string>();
245
- }
246
-
247
- const normalizedAlias = normalizeAlias(alias.value);
248
- if (normalizedAlias.length === 0) {
249
- return yield* Effect.fail(invalidOptionValue('`--alias` cannot be empty.', '--alias'));
250
- }
251
-
252
- return Option.some(normalizedAlias);
253
- });
111
+ Effect.transposeOption(
112
+ Option.map(alias, rawAlias =>
113
+ Effect.fromOption(
114
+ Option.liftPredicate(rawAlias.trim(), trimmed => trimmed.length > 0),
115
+ () => invalidOptionValue('`--alias` cannot be empty.', '--alias')
116
+ )
117
+ )
118
+ );
119
120
+/** The user's active accounts in a toolkit or an auth config, up to one page of 100. */
121
const listActiveConnectedAccounts = (params: {
122
readonly client: ComposioClientShape;
123
readonly userId: string;
135
idempotent
136
);
137
272
-const formatExistingAccountLabels = (
273
- items: ReadonlyArray<{
274
- readonly id: string;
275
- readonly alias?: string | null;
276
- readonly word_id?: string | null;
277
- }>
278
-) =>
279
- items
280
- .map(item => {
281
- const labels = [item.alias, item.word_id].filter(
282
- (value): value is string => typeof value === 'string' && value.trim().length > 0
283
- );
284
- return labels.length > 0 ? `${item.id} (${labels.join(', ')})` : item.id;
285
- })
286
- .join(', ');
287
-
288
-const showAliasConflictGuidance = (params: {
289
- readonly ui: TerminalUI;
290
- readonly alias: string;
291
- readonly executeCommand: string;
292
- readonly listCommand: string;
293
-}) =>
294
- params.ui.note(
295
- [
296
- `Use the existing alias: ${params.executeCommand} <TOOL_SLUG> --account ${params.alias} -d '{ ... }'`,
297
- `List connected accounts: ${params.listCommand}`,
298
- ].join('\n'),
299
- 'Tips'
138
+/**
139
+ * The accounts that power the `--alias` hints. This fetch is auxiliary: a transient list
140
+ * failure must not abort the link flow, so it answers with no accounts.
141
+ */
142
+const existingAccountsForHints = (params: Parameters<typeof listActiveConnectedAccounts>[0]) =>
143
+ listActiveConnectedAccounts(params).pipe(
144
+ Effect.map((response): ReadonlyArray<ExistingAccountLabel> => response.items),
145
+ Effect.catch(() => Effect.succeed<ReadonlyArray<ExistingAccountLabel>>([]))
146
);
147
148
+/**
149
+ * True when no existing account already carries `alias` (compared case-insensitively); false
150
+ * after explaining the conflict and how to use the existing account.
151
+ */
152
const ensureAliasIsAvailable = (params: {
153
readonly ui: TerminalUI;
154
readonly alias: Option.Option<string>;
305
- readonly existingAccounts: ReadonlyArray<{
306
- readonly id: string;
307
- readonly alias?: string | null;
308
- }>;
155
+ readonly existingAccounts: ReadonlyArray<ExistingAccountLabel>;
156
readonly executeCommand: string;
157
readonly listCommand: string;
158
}) =>
312
- Effect.gen(function* () {
313
- if (Option.isNone(params.alias)) return true as const;
314
-
315
- const normalizedAlias = params.alias.value.toLowerCase();
316
- const existing = params.existingAccounts.find(
317
- item => item.alias?.trim().toLowerCase() === normalizedAlias
318
- );
319
- if (!existing) return true as const;
320
-
321
- yield* params.ui.log.error(
322
- `Alias "${params.alias.value}" is already in use by connected account "${existing.id}".`
323
- );
324
- yield* showAliasConflictGuidance({
325
- ui: params.ui,
326
- alias: params.alias.value,
327
- executeCommand: params.executeCommand,
328
- listCommand: params.listCommand,
329
- });
330
- return false as const;
331
- });
159
+ Option.match(
160
+ Option.flatMap(params.alias, alias =>
161
+ Option.map(
162
+ Option.fromNullishOr(
163
+ params.existingAccounts.find(
164
+ item => item.alias?.trim().toLowerCase() === alias.toLowerCase()
165
+ )
166
+ ),
167
+ existing => ({ alias, existing })
168
+ )
169
+ ),
170
+ {
171
+ onNone: () => Effect.succeed(true),
172
+ onSome: ({ alias, existing }) =>
173
+ showAliasConflict(params.ui, {
174
+ alias,
175
+ existingId: existing.id,
176
+ executeCommand: params.executeCommand,
177
+ listCommand: params.listCommand,
178
+ }).pipe(Effect.as(false)),
179
+ }
180
+ );
181
182
+/**
183
+ * True when the new link may proceed: an alias was given, no account exists yet in the scope,
184
+ * or the link reuses an existing account. False after listing the accounts that block it.
185
+ */
186
const ensureAliasForAdditionalAccount = (params: {
187
readonly ui: TerminalUI;
188
readonly alias: Option.Option<string>;
189
readonly connectedAccountId: string;
337
- readonly existingAccounts: {
338
- readonly items: ReadonlyArray<{
339
- readonly id: string;
340
- readonly alias?: string | null;
341
- readonly word_id?: string | null;
342
- }>;
343
- };
190
+ readonly existingAccounts: ReadonlyArray<ExistingAccountLabel>;
191
readonly scopeDescription: string;
345
-}) =>
346
- Effect.gen(function* () {
347
- if (Option.isSome(params.alias)) {
348
- return true;
349
- }
192
+}) => {
193
+ const blocked =
194
+ Option.isNone(params.alias) &&
195
+ params.existingAccounts.length > 0 &&
196
+ !params.existingAccounts.some(item => item.id === params.connectedAccountId);
197
+ return blocked
198
+ ? showExistingAccounts(params.ui, params.scopeDescription, params.existingAccounts).pipe(
199
+ Effect.as(false)
200
+ )
201
+ : Effect.succeed(true);
202
+};
203
351
- const existingIds = new Set(params.existingAccounts.items.map(item => item.id));
352
- if (params.existingAccounts.items.length === 0 || existingIds.has(params.connectedAccountId)) {
353
- return true;
204
+/** A response field that is present and not blank. */
205
+const nonEmpty = (value: string | null | undefined) =>
206
+ Option.filter(Option.fromNullishOr(value), text => text.length > 0);
207
+
208
+/** The link the API answered with, or none after reporting an incomplete response. */
209
+const validateLinkResponse = (
210
+ ui: TerminalUI,
211
+ linkResponse: {
212
+ readonly connected_account_id?: string | null;
213
+ readonly redirect_url?: string | null;
214
+ }
215
+) =>
216
+ Option.match(
217
+ Option.zipWith(
218
+ nonEmpty(linkResponse.connected_account_id),
219
+ nonEmpty(linkResponse.redirect_url),
220
+ (connectedAccountId, redirectUrl): LinkTarget => ({ connectedAccountId, redirectUrl })
221
+ ),
222
+ {
223
+ onSome: target => Effect.succeedSome(target),
224
+ onNone: () =>
225
+ Effect.gen(function* () {
226
+ yield* ui.log.error(INCOMPLETE_LINK_RESPONSE_MESSAGE);
227
+ yield* Effect.logDebug('Link response:', linkResponse);
228
+ return Option.none<LinkTarget>();
229
+ }),
230
}
231
+ );
232
356
- yield* params.ui.log.error(
357
- `A connected account already exists for ${params.scopeDescription}. Pass --alias to create another one.`
358
- );
359
- yield* params.ui.note(
360
- formatExistingAccountLabels(params.existingAccounts.items),
361
- 'Existing accounts'
362
- );
363
- return false;
233
+const openBrowser = (url: string) =>
234
+ Effect.tryPromise({
235
+ try: () => open(url, { wait: false }),
236
+ catch: cause => new BrowserOpenError({ message: 'Failed to open the browser.', cause }),
237
});
238
366
-const resolveLinkUserId = (params: {
367
- readonly resolvedProject: {
368
- readonly projectType: 'CONSUMER' | 'DEVELOPER';
369
- readonly consumerUserId?: string;
370
- };
371
- readonly requestedUserId: Option.Option<string>;
372
- /** The project `--project-name` resolved to, or none without the flag. */
373
- readonly namedProjectId: Option.Option<string>;
374
- readonly projectContext: {
375
- readonly resolve: Effect.Effect<
376
- Option.Option<{ readonly projectId: string; readonly testUserId: Option.Option<string> }>,
377
- unknown
378
- >;
379
- };
380
- readonly userContext: {
381
- readonly data: {
382
- readonly testUserId: Option.Option<string>;
383
- };
384
- };
385
-}) =>
239
+/** Polls the account until it is `ACTIVE`: a 0.3s exponential ramp capped at 5s, 15 attempts. */
240
+const pollUntilActive = (client: ComposioClientShape, connectedAccountId: string) =>
241
+ Effect.retry(
242
+ Effect.gen(function* () {
243
+ const account = yield* client.connectedAccounts
244
+ .retrieve(connectedAccountId, idempotent)
245
+ .pipe(
246
+ failedWith(
247
+ ConnectedAccountsRequestError,
248
+ `Failed to fetch connected account "${connectedAccountId}".`
249
+ )
250
+ );
251
+ if (account.status === 'ACTIVE') {
252
+ return account;
253
+ }
254
+ return yield* new ConnectionPollingError({
255
+ message: `Connection status is still '${account.status}', waiting for 'ACTIVE'`,
256
+ connectedAccountId,
257
+ status: account.status,
258
+ });
259
+ }),
260
+ Schedule.max([Schedule.exponential('0.3 seconds'), Schedule.spaced('5 seconds')]).pipe(
261
+ Schedule.upTo({ times: 15 })
262
+ )
263
+ );
264
+
265
+/** Opens the authorization page unless `noBrowser`, then waits for the account to turn `ACTIVE`. */
266
+const waitForActiveConnection = (
267
+ ui: TerminalUI,
268
+ client: ComposioClientShape,
269
+ target: LinkTarget,
270
+ noBrowser: boolean
271
+) =>
272
Effect.gen(function* () {
387
- const resolvedProjectContext = yield* params.projectContext.resolve.pipe(
388
- Effect.option,
389
- Effect.map(Option.flatten)
273
+ yield* showRedirectUrl(ui, target.redirectUrl, { manual: noBrowser });
274
+
275
+ const urlSchemeValid = Option.exists(
276
+ Option.liftThrowable((value: string) => new URL(value))(target.redirectUrl),
277
+ parsed => parsed.protocol === 'https:' || parsed.protocol === 'http:'
278
);
391
- const localTestUserId = directoryTestUserId(resolvedProjectContext, params.namedProjectId);
392
-
393
- const resolvedUserId =
394
- params.resolvedProject.projectType === 'CONSUMER'
395
- ? Option.fromNullishOr(params.resolvedProject.consumerUserId)
396
- : Option.match(params.requestedUserId, {
397
- onSome: value => Option.some(value),
398
- onNone: () => Option.orElse(localTestUserId, () => params.userContext.data.testUserId),
399
- });
279
+ if (!urlSchemeValid) {
280
+ yield* ui.log.warn(`Redirect URL has an unexpected scheme: ${target.redirectUrl}`);
281
+ yield* ui.log.info('Open the URL manually if you trust the source.');
282
+ } else if (!noBrowser) {
283
+ yield* openBrowser(target.redirectUrl).pipe(
284
+ Effect.catchTag('commands/BrowserOpenError', error =>
285
+ Effect.gen(function* () {
286
+ yield* Effect.logDebug('Failed to open browser:', error);
287
+ yield* ui.log.warn('Could not open the browser automatically.');
288
+ yield* ui.log.info('Open the URL above manually.');
289
+ })
290
+ )
291
+ );
292
+ }
293
401
- return {
402
- resolvedUserId,
403
- resolvedProjectContext,
404
- localTestUserId,
405
- };
294
+ yield* ui.useMakeSpinner('Waiting for authorization...', spinner =>
295
+ pollUntilActive(client, target.connectedAccountId).pipe(
296
+ Effect.tap(account =>
297
+ Effect.all([
298
+ spinner.stop('Connection successful'),
299
+ ui.log.success(activeConnectionMessage(account)),
300
+ ui.output(formatActiveLinkJson({ account, redirectUrl: target.redirectUrl })),
301
+ ])
302
+ ),
303
+ Effect.tapError(() =>
304
+ spinner.error('Timed out waiting for authorization. Run the command again.')
305
+ )
306
+ )
307
+ );
308
});
309
408
-const handleListConnectedAccounts = (params: {
409
- readonly toolkit: Option.Option<string>;
410
- readonly authConfig: Option.Option<string>;
411
- readonly tree: CommandTree;
412
- readonly projectName: Option.Option<string>;
413
- readonly userId: Option.Option<string>;
310
+/** Prints the `--no-wait` payload, or opens the page and waits, after a link was created. */
311
+const finishLink = (params: {
312
readonly ui: TerminalUI;
415
- readonly clientSingleton: {
416
- readonly getFor: (params: {
417
- readonly orgId: string;
418
- readonly projectId: string;
419
- }) => Effect.Effect<ComposioClientShape, unknown>;
420
- };
421
- readonly projectContext: {
422
- readonly resolve: Effect.Effect<
423
- Option.Option<{ readonly projectId: string; readonly testUserId: Option.Option<string> }>,
424
- unknown
425
- >;
426
- };
427
- readonly userContext: {
428
- readonly data: {
429
- readonly testUserId: Option.Option<string>;
430
- };
431
- };
313
+ readonly client: ComposioClientShape;
314
+ readonly target: LinkTarget;
315
+ readonly toolkit: Option.Option<string>;
316
+ readonly projectType: ResolvedCommandProject['projectType'];
317
+ readonly noWait: boolean;
318
+ readonly noBrowser: boolean;
319
}) =>
320
+ params.noWait
321
+ ? Effect.gen(function* () {
322
+ yield* showRedirectUrl(params.ui, params.target.redirectUrl, { manual: true });
323
+ yield* params.ui.output(
324
+ formatPendingLinkJson({
325
+ target: params.target,
326
+ toolkit: params.toolkit,
327
+ projectType: params.projectType,
328
+ }),
329
+ { force: true }
330
+ );
331
+ })
332
+ : waitForActiveConnection(params.ui, params.client, params.target, params.noBrowser);
333
+
334
+/**
335
+ * Composio does not manage auth for the toolkit: send the user to the dashboard page that
336
+ * connects it, naming the org of the active membership when the session info answers.
337
+ */
338
+const handleNoManagedAuth = (ui: TerminalUI, toolkitSlug: string, noBrowser: boolean) =>
339
Effect.gen(function* () {
340
+ const userContext = yield* ComposioUserContext;
341
+ const orgName = yield* Option.match(userContext.data.apiKey, {
342
+ onNone: () => Effect.succeed('~'),
343
+ onSome: userApiKey =>
344
+ Effect.gen(function* () {
345
+ const sessionInfo = yield* getSessionInfoByUserApiKey({
346
+ userApiKey,
347
+ orgId: Option.getOrUndefined(userContext.data.orgId),
348
+ }).pipe(Effect.option);
349
+ yield* Effect.transposeOption(
350
+ Option.map(sessionInfo, info =>
351
+ linkApolloIdentityForAnalytics(info.org_member.id, userApiKey)
352
+ )
353
+ );
354
+ return pipe(
355
+ sessionInfo,
356
+ Option.map(info => info.project.org.name),
357
+ Option.filter(name => name.length > 0),
358
+ Option.getOrElse(() => '~')
359
+ );
360
+ }),
361
+ });
362
+ const dashboardUrl = dashboardConnectUrl(userContext.data.webURL, orgName, toolkitSlug);
363
+
364
+ yield* ui.log.warn(unmanagedAuthMessage(toolkitSlug, noBrowser));
365
+ yield* noBrowser
366
+ ? Effect.void
367
+ : openBrowser(dashboardUrl).pipe(
368
+ Effect.catchTag('commands/BrowserOpenError', () =>
369
+ ui.log.warn('Could not open the browser automatically.')
370
+ )
371
+ );
372
+ yield* ui.note(dashboardUrl, 'Dashboard URL');
373
+ yield* ui.output(dashboardUrl);
374
+ });
375
+
376
+// --- the three flows --------------------------------------------------------------------------
377
+
378
+/**
379
+ * `link <toolkit> --list`: the user's active accounts in the toolkit, as a table on stderr and
380
+ * JSON on stdout. Resolves the consumer project on both trees; `dev --project-name` names a
381
+ * developer project instead, whose user comes from `--user-id` or a test user id.
382
+ */
383
+export const handleListConnectedAccounts = (params: ConnectedAccountsLinkParams) =>
384
+ Effect.gen(function* () {
385
+ const ui = yield* TerminalUI;
386
if (Option.isNone(params.toolkit)) {
435
- yield* params.ui.log.error(
436
- '`--list` requires a toolkit slug, e.g. `composio link gmail --list`.'
437
- );
438
- return;
387
+ return yield* ui.log.error(LIST_REQUIRES_TOOLKIT_MESSAGE);
388
}
389
if (Option.isSome(params.authConfig)) {
441
- yield* params.ui.log.error('`--list` cannot be combined with `--auth-config`.');
442
- return;
390
+ return yield* ui.log.error(LIST_WITH_AUTH_CONFIG_MESSAGE);
391
}
444
-
392
const toolkitSlug = params.toolkit.value;
393
+
394
+ const { userId, projectName } = yield* CommandSurface;
395
+ const clientSingleton = yield* ComposioClientSingleton;
396
+ const userContext = yield* ComposioUserContext;
397
const resolvedProject = yield* resolveCommandProject({
398
mode: 'consumer',
448
- projectName: Option.getOrUndefined(params.projectName),
449
- });
450
- const client = yield* params.clientSingleton.getFor({
451
- orgId: resolvedProject.orgId,
452
- projectId: resolvedProject.projectId,
453
- });
454
- const { resolvedUserId } = yield* resolveLinkUserId({
455
- resolvedProject,
456
- requestedUserId: params.userId,
457
- namedProjectId: Option.as(params.projectName, resolvedProject.projectId),
458
- projectContext: params.projectContext,
459
- userContext: params.userContext,
399
+ projectName: Option.getOrUndefined(projectName),
400
});
401
+ const client = yield* clientSingleton.getFor(projectScope(resolvedProject));
402
+ const localTestUserId = directoryTestUserId(
403
+ yield* directoryProject,
404
+ Option.as(projectName, resolvedProject.projectId)
405
+ );
406
+ const resolvedUserId = yield* pipe(
407
+ resolvedProject.projectType === 'CONSUMER'
408
+ ? Option.fromNullishOr(resolvedProject.consumerUserId)
409
+ : Option.orElse(userId, () =>
410
+ Option.orElse(localTestUserId, () => userContext.data.testUserId)
411
+ ),
412
+ Effect.fromOption(
413
+ () =>
414
+ new MissingLinkUserIdError({
415
+ message: missingUserIdMessage(
416
+ projectName,
417
+ 'Missing user id. Provide --user-id, or run composio dev init or composio login first.'
418
+ ),
419
+ flow: 'list',
420
+ })
421
+ )
422
+ );
423
462
- if (Option.isNone(resolvedUserId)) {
463
- return yield* new MissingLinkUserIdError({
464
- message: missingUserIdMessage(
465
- params.projectName,
466
- 'Missing user id. Provide --user-id or run composio dev init/login first.'
467
- ),
468
- flow: 'list',
469
- });
470
- }
471
-
472
- const accounts = yield* params.ui.withSpinner(
424
+ const accounts = yield* ui.withSpinner(
425
`Listing connected accounts for "${toolkitSlug}"...`,
426
client.connectedAccounts
427
.list(
428
{
429
toolkit_slugs: [toolkitSlug],
478
- user_ids: [resolvedUserId.value],
430
+ user_ids: [resolvedUserId],
431
statuses: ['ACTIVE'],
432
limit: 100,
433
},
450
)
451
);
452
501
- if (resolvedProject.projectType === 'CONSUMER' && resolvedProject.consumerUserId) {
502
- yield* writeConsumerConnectedToolkitsCache({
503
- orgId: resolvedProject.orgId,
504
- consumerUserId: resolvedProject.consumerUserId,
505
- toolkits: [toolkitSlug],
506
- toolRouterConnectedAccounts: {
507
- connectedAccounts: resolveDefaultConnectedAccountsByToolkit(connectedAccounts),
508
- availableConnectedAccounts: groupCachedConnectedAccountsByToolkit(connectedAccounts),
509
- },
510
- }).pipe(Effect.ignore);
511
- }
512
-
513
- if (connectedAccounts.length === 0) {
514
- yield* params.ui.log.warn(`No active connected accounts found for "${toolkitSlug}".`);
515
- yield* params.ui.output(
516
- JSON.stringify({ toolkit: toolkitSlug, items: [], total: 0 }, null, 2),
517
- { force: true }
518
- );
519
- return;
520
- }
521
-
522
- yield* params.ui.note(
523
- formatConnectedAccountsTable(connectedAccounts),
524
- `${toolkitSlug}: connected accounts`
525
- );
526
- yield* params.ui.output(
527
- JSON.stringify(
528
- {
529
- toolkit: toolkitSlug,
530
- total: connectedAccounts.length,
531
- items: connectedAccounts,
532
- },
533
- null,
534
- 2
535
- ),
536
- { force: true }
453
+ yield* Effect.transposeOption(
454
+ Option.map(consumerScope(resolvedProject), scope =>
455
+ writeConsumerConnectedToolkitsCache({
456
+ orgId: scope.orgId,
457
+ consumerUserId: scope.consumerUserId,
458
+ toolkits: [toolkitSlug],
459
+ toolRouterConnectedAccounts: {
460
+ connectedAccounts: resolveDefaultConnectedAccountsByToolkit(connectedAccounts),
461
+ availableConnectedAccounts: groupCachedConnectedAccountsByToolkit(connectedAccounts),
462
+ },
463
+ }).pipe(Effect.ignore)
464
+ )
465
);
466
+
467
+ yield* showConnectedAccounts(ui, toolkitSlug, connectedAccounts);
468
+ yield* ui.output(formatConnectedAccountsListJson(toolkitSlug, connectedAccounts), {
469
+ force: true,
470
+ });
471
});
472
540
-const handleLegacyAuthConfigLink = (params: {
541
- readonly authConfigId: string;
542
- readonly requestedUserId: Option.Option<string>;
543
- readonly projectName: Option.Option<string>;
544
- readonly noWait: boolean;
545
- readonly noBrowser: boolean;
546
- readonly alias: Option.Option<string>;
547
- readonly ui: TerminalUI;
548
- readonly clientSingleton: {
549
- readonly getFor: (params: {
550
- readonly orgId: string;
551
- readonly projectId: string;
552
- }) => Effect.Effect<ComposioClientShape, unknown>;
553
- };
554
- readonly projectContext: {
555
- readonly resolve: Effect.Effect<
556
- Option.Option<{ readonly projectId: string; readonly testUserId: Option.Option<string> }>,
557
- unknown
558
- >;
559
- };
560
- readonly userContext: {
561
- readonly data: {
562
- readonly testUserId: Option.Option<string>;
563
- };
564
- };
565
-}) =>
473
+/**
474
+ * `dev connected-accounts link --auth-config <id>`: the legacy flow against a developer
475
+ * project, without the Tool Router. The project is `--project-name` or the directory's; the
476
+ * user is `--user-id`, then the directory's test user, then the global one.
477
+ */
478
+export const handleLegacyAuthConfigLink = (params: ConnectedAccountsLinkParams) =>
479
Effect.gen(function* () {
567
- const resolvedProjectContext = yield* params.projectContext.resolve.pipe(
568
- Effect.option,
569
- Effect.map(Option.flatten)
570
- );
480
+ const ui = yield* TerminalUI;
481
+ const { tree, userId, projectName } = yield* CommandSurface;
482
+ // The dispatcher never gets here without --auth-config. This narrows it for direct callers.
483
+ if (Option.isNone(params.authConfig)) {
484
+ return yield* ui.log.error(missingArgumentMessage(tree));
485
+ }
486
+ const authConfigId = params.authConfig.value;
487
+
488
+ const clientSingleton = yield* ComposioClientSingleton;
489
+ const userContext = yield* ComposioUserContext;
490
+ const resolvedProjectContext = yield* directoryProject;
491
// A named project is looked up first: its id decides whether the directory's test user applies.
492
const namedResolvedProject = yield* Effect.transposeOption(
573
- Option.map(params.projectName, projectName =>
574
- resolveCommandProject({ mode: 'developer', projectName })
493
+ Option.map(projectName, name =>
494
+ resolveCommandProject({ mode: 'developer', projectName: name })
495
)
496
);
497
const localTestUserId = directoryTestUserId(
498
resolvedProjectContext,
499
Option.map(namedResolvedProject, project => project.projectId)
500
);
581
- const globalTestUserId = params.userContext.data.testUserId;
582
- const resolvedUserId = Option.match(params.requestedUserId, {
583
- onSome: value => Option.some(value),
584
- onNone: () => Option.orElse(localTestUserId, () => globalTestUserId),
585
- });
586
-
587
- if (Option.isNone(resolvedUserId)) {
588
- return yield* new MissingLinkUserIdError({
589
- message: missingUserIdMessage(
590
- params.projectName,
591
- 'Missing user id. Provide --user-id or run composio dev init to set test_user_id.'
592
- ),
593
- flow: 'legacy',
594
- });
595
- }
596
- if (Option.isNone(params.projectName) && Option.isNone(resolvedProjectContext)) {
597
- yield* params.ui.log.error(
598
- '`--auth-config` is developer-project scoped. Pass `--project-name <name>` or run from a directory initialized with `composio dev init`.'
599
- );
600
- return;
601
- }
602
- if (Option.isNone(params.requestedUserId) && Option.isSome(localTestUserId)) {
603
- yield* params.ui.log.warn(`Using test user id "${localTestUserId.value}"`);
604
- } else if (Option.isNone(params.requestedUserId) && Option.isSome(globalTestUserId)) {
605
- yield* params.ui.log.warn(`Using global test user id "${globalTestUserId.value}"`);
501
+ const globalTestUserId = userContext.data.testUserId;
502
+ const resolvedUserId = yield* pipe(
503
+ Option.orElse(userId, () => Option.orElse(localTestUserId, () => globalTestUserId)),
504
+ Effect.fromOption(
505
+ () =>
506
+ new MissingLinkUserIdError({
507
+ message: missingUserIdMessage(
508
+ projectName,
509
+ 'Missing user id. Provide --user-id or run composio dev init to set test_user_id.'
510
+ ),
511
+ flow: 'legacy',
512
+ })
513
+ )
514
+ );
515
+ if (Option.isNone(projectName) && Option.isNone(resolvedProjectContext)) {
516
+ return yield* ui.log.error(AUTH_CONFIG_SCOPE_MESSAGE);
517
}
518
+ // Without --user-id, say which test user stands in.
519
+ yield* Option.isSome(userId)
520
+ ? Effect.void
521
+ : Option.match(localTestUserId, {
522
+ onSome: testUserId => ui.log.warn(`Using test user id "${testUserId}"`),
523
+ onNone: () =>
524
+ Effect.transposeOption(
525
+ Option.map(globalTestUserId, testUserId =>
526
+ ui.log.warn(`Using global test user id "${testUserId}"`)
527
+ )
528
+ ),
529
+ });
530
531
const resolvedProject = yield* Option.match(namedResolvedProject, {
532
onSome: Effect.succeed,
533
onNone: () => resolveCommandProject({ mode: 'developer' }),
534
});
612
- const client = yield* params.clientSingleton.getFor({
613
- orgId: resolvedProject.orgId,
614
- projectId: resolvedProject.projectId,
615
- });
535
+ const client = yield* clientSingleton.getFor(projectScope(resolvedProject));
536
const normalizedAlias = yield* resolveNormalizedAliasOption(params.alias);
617
- const existingAccounts = yield* listActiveConnectedAccounts({
537
+ const existingAccounts = yield* existingAccountsForHints({
538
client,
619
- userId: resolvedUserId.value,
620
- authConfigId: params.authConfigId,
621
- }).pipe(
622
- // Auxiliary fetch powering the --alias hint only: a transient list
623
- // failure must not abort the link flow.
624
- Effect.catch(() => Effect.succeed({ items: [] }))
625
- );
539
+ userId: resolvedUserId,
540
+ authConfigId,
541
+ });
542
const aliasAvailable = yield* ensureAliasIsAvailable({
627
- ui: params.ui,
543
+ ui,
544
alias: normalizedAlias,
629
- existingAccounts: existingAccounts.items,
545
+ existingAccounts,
546
executeCommand: 'composio dev playground-execute',
547
listCommand: 'composio dev connected-accounts list',
548
});
549
if (!aliasAvailable) return;
550
635
- const linkOpt = yield* params.ui
551
+ const linkOpt = yield* ui
552
.withSpinner(
553
'Creating link session...',
554
client.link.create({
639
- auth_config_id: params.authConfigId,
640
- user_id: resolvedUserId.value,
555
+ auth_config_id: authConfigId,
556
+ user_id: resolvedUserId,
557
...(Option.isSome(normalizedAlias) && { alias: normalizedAlias.value }),
558
})
559
)
561
Effect.asSome,
562
Effect.catch(error =>
563
Effect.gen(function* () {
648
- const message =
649
- extractMessage(error) ||
650
- `Failed to create link for auth config "${params.authConfigId}".`;
651
- yield* params.ui.log.error(message);
652
- yield* params.ui.log.step(
653
- 'Browse available auth configs:\n> composio dev auth-configs list'
564
+ yield* ui.log.error(
565
+ extractMessage(error) || `Failed to create link for auth config "${authConfigId}".`
566
);
567
+ yield* ui.log.step(BROWSE_AUTH_CONFIGS_HINT);
568
return Option.none();
569
})
570
)
571
);
659
-
572
if (Option.isNone(linkOpt)) return;
573
662
- const validatedLink = yield* validateLinkResponse(params.ui, linkOpt.value);
663
- if (Option.isNone(validatedLink)) return;
574
+ const target = yield* validateLinkResponse(ui, linkOpt.value);
575
+ if (Option.isNone(target)) return;
576
665
- const { connectedAccountId, redirectUrl } = validatedLink.value;
577
const canContinue = yield* ensureAliasForAdditionalAccount({
667
- ui: params.ui,
578
+ ui,
579
alias: normalizedAlias,
669
- connectedAccountId,
580
+ connectedAccountId: target.value.connectedAccountId,
581
existingAccounts,
671
- scopeDescription: `user "${resolvedUserId.value}" in auth config "${params.authConfigId}"`,
582
+ scopeDescription: `user "${resolvedUserId}" in auth config "${authConfigId}"`,
583
});
584
if (!canContinue) return;
585
675
- if (params.noWait) {
676
- yield* showRedirectUrl(params.ui, redirectUrl, { manual: true });
677
- yield* params.ui.output(
678
- JSON.stringify(
679
- {
680
- status: 'pending',
681
- message: 'Complete authorization by opening the URL',
682
- connected_account_id: connectedAccountId,
683
- redirect_url: redirectUrl,
684
- project_type: resolvedProject.projectType,
685
- },
686
- null,
687
- 2
688
- ),
689
- { force: true }
690
- );
691
- return;
692
- }
693
-
694
- yield* waitForActiveConnection(
695
- params.ui,
586
+ yield* finishLink({
587
+ ui,
588
client,
697
- connectedAccountId,
698
- redirectUrl,
699
- params.noBrowser
700
- );
589
+ target: target.value,
590
+ toolkit: Option.none(),
591
+ projectType: resolvedProject.projectType,
592
+ noWait: params.noWait,
593
+ noBrowser: params.noBrowser,
594
+ });
595
});
596
703
-export const runConnectedAccountsLink = (params: ConnectedAccountsLinkParams) =>
597
+/**
598
+ * `link <toolkit>`: the Tool Router flow against the consumer project (or the developer
599
+ * project `dev --project-name` names). Records the link in the session history.
600
+ */
601
+export const handleToolRouterLink = (params: ConnectedAccountsLinkParams) =>
602
Effect.gen(function* () {
705
- const normalizedAliasOption = yield* resolveNormalizedAliasOption(params.alias);
706
-
603
const ui = yield* TerminalUI;
708
- const clientSingleton = yield* ComposioClientSingleton;
709
- const projectContext = yield* ProjectContext;
710
- const userContext = yield* ComposioUserContext;
604
const { tree, userId, projectName } = yield* CommandSurface;
712
-
713
- if (tree === 'root') {
714
- if (Option.isSome(params.authConfig)) {
715
- return yield* Effect.fail(
716
- invalidOptionValue(
717
- 'Top-level `composio link` is consumer-only and does not accept `--auth-config`. Use `composio dev connected-accounts link --auth-config ...` for developer-scoped usage.',
718
- '--auth-config'
719
- )
720
- );
721
- }
722
- }
723
-
724
- if (Option.isSome(params.toolkit) && Option.isSome(params.authConfig)) {
725
- yield* ui.log.error(
726
- 'Cannot use both <toolkit> and --auth-config. Choose one:\n' +
727
- ' Tool Router: composio dev connected-accounts link <toolkit>\n' +
728
- ' Legacy: composio dev connected-accounts link --auth-config <id>'
729
- );
730
- return;
731
- }
732
-
733
- if (Option.isNone(params.toolkit) && Option.isNone(params.authConfig)) {
734
- yield* ui.log.error(
735
- tree === 'root'
736
- ? 'Missing argument. Provide a toolkit slug:\n composio link github'
737
- : 'Missing argument. Provide a toolkit slug or --auth-config:\n' +
738
- ' composio dev connected-accounts link github\n' +
739
- ' composio dev connected-accounts link --auth-config "ac_..."'
740
- );
741
- return;
742
- }
743
-
744
- if (params.list) {
745
- yield* handleListConnectedAccounts({
746
- toolkit: params.toolkit,
747
- authConfig: params.authConfig,
748
- tree,
749
- projectName: projectName,
750
- userId: userId,
751
- ui,
752
- clientSingleton,
753
- projectContext,
754
- userContext,
755
- });
756
- return;
757
- }
758
-
759
- if (Option.isSome(params.authConfig)) {
760
- yield* handleLegacyAuthConfigLink({
761
- authConfigId: params.authConfig.value,
762
- requestedUserId: userId,
763
- projectName: projectName,
764
- noWait: params.noWait,
765
- noBrowser: params.noBrowser,
766
- alias: params.alias,
767
- ui,
768
- clientSingleton,
769
- projectContext,
770
- userContext,
771
- });
772
- return;
605
+ // The dispatcher never gets here without a toolkit. This narrows it for direct callers.
606
+ if (Option.isNone(params.toolkit)) {
607
+ return yield* ui.log.error(missingArgumentMessage(tree));
608
}
774
-
775
- if (Option.isNone(params.toolkit)) return;
609
const toolkitSlug = params.toolkit.value;
610
+
611
+ const normalizedAlias = yield* resolveNormalizedAliasOption(params.alias);
612
+ const clientSingleton = yield* ComposioClientSingleton;
613
+ const userContext = yield* ComposioUserContext;
614
const resolvedProject = yield* resolveCommandProject({
615
mode: 'consumer',
616
projectName: Option.getOrUndefined(projectName),
617
});
781
- const resolvedUserId =
618
+ const resolvedUserId = yield* pipe(
619
resolvedProject.projectType === 'CONSUMER'
620
? Option.fromNullishOr(resolvedProject.consumerUserId)
784
- : Option.match(userId, {
785
- onSome: value => Option.some(value),
786
- onNone: () => userContext.data.testUserId,
787
- });
788
- if (Option.isNone(resolvedUserId)) {
789
- return yield* new MissingLinkUserIdError({
790
- message:
791
- 'Missing user id. Provide --user-id or run composio login to set global test_user_id.',
792
- flow: 'tool-router',
793
- });
794
- }
795
- const client = yield* clientSingleton.getFor({
796
- orgId: resolvedProject.orgId,
797
- projectId: resolvedProject.projectId,
798
- });
799
- const existingAccounts = yield* listActiveConnectedAccounts({
621
+ : Option.orElse(userId, () => userContext.data.testUserId),
622
+ Effect.fromOption(
623
+ () =>
624
+ new MissingLinkUserIdError({
625
+ message:
626
+ 'Missing user id. Provide --user-id or run composio login to set global test_user_id.',
627
+ flow: 'tool-router',
628
+ })
629
+ )
630
+ );
631
+ const client = yield* clientSingleton.getFor(projectScope(resolvedProject));
632
+ const existingAccounts = yield* existingAccountsForHints({
633
client,
801
- userId: resolvedUserId.value,
634
+ userId: resolvedUserId,
635
toolkitSlug,
803
- }).pipe(
804
- // Auxiliary fetch powering the --alias hint only: a transient list
805
- // failure must not abort the link flow.
806
- Effect.catch(() => Effect.succeed({ items: [] }))
807
- );
636
+ });
637
const aliasAvailable = yield* ensureAliasIsAvailable({
638
ui,
810
- alias: normalizedAliasOption,
811
- existingAccounts: existingAccounts.items,
639
+ alias: normalizedAlias,
640
+ existingAccounts,
641
executeCommand: 'composio execute',
642
listCommand: `composio connections list --toolkit ${toolkitSlug}`,
643
});
644
if (!aliasAvailable) return;
645
646
+ const scope = consumerScope(resolvedProject);
647
const linkOpt = yield* ui
648
.withSpinner(
649
`Linking ${toolkitSlug}...`,
650
Effect.gen(function* () {
821
- const { sessionId } = yield* resolveToolRouterSession(client, resolvedUserId.value, {
651
+ const { sessionId } = yield* resolveToolRouterSession(client, resolvedUserId, {
652
manageConnections: true,
823
- cacheScope: getConsumerCacheScope(resolvedProject),
653
+ cacheScope: Option.getOrUndefined(scope),
654
excludeConnectedAccountsForToolkits: [toolkitSlug],
825
- multiAccount: Option.isSome(normalizedAliasOption)
826
- ? {
827
- enable: true,
828
- }
829
- : undefined,
655
+ multiAccount: Option.isSome(normalizedAlias) ? { enable: true } : undefined,
656
});
657
return yield* client.toolRouter.session
658
.link(sessionId, {
659
toolkit: toolkitSlug,
834
- ...(Option.isSome(normalizedAliasOption) && {
835
- alias: normalizedAliasOption.value,
836
- }),
660
+ ...(Option.isSome(normalizedAlias) && { alias: normalizedAlias.value }),
661
})
662
.pipe(
663
failedWith(
671
Effect.asSome,
672
Effect.catch(error =>
673
Effect.gen(function* () {
850
- const slug = extractApiErrorDetails(error)?.slug;
851
-
852
- if (slug === 'ToolRouterV2_NoManagedAuth') {
674
+ if (extractApiErrorDetails(error)?.slug === 'ToolRouterV2_NoManagedAuth') {
675
yield* handleNoManagedAuth(ui, toolkitSlug, params.noBrowser);
676
return Option.none();
677
}
856
-
857
- const message =
858
- extractMessage(error) ?? `Failed to create link for toolkit "${toolkitSlug}".`;
859
- yield* ui.log.error(message);
678
+ yield* ui.log.error(
679
+ extractMessage(error) ?? `Failed to create link for toolkit "${toolkitSlug}".`
680
+ );
681
yield* Effect.logDebug('Link error:', error);
861
- yield* ui.log.step('Browse available toolkits:\n> composio dev toolkits list');
682
+ yield* ui.log.step(BROWSE_TOOLKITS_HINT);
683
return Option.none();
684
})
685
),
686
Effect.tap(() => invalidateConsumerConnectedToolkitsCache().pipe(Effect.ignore))
687
);
867
-
688
if (Option.isNone(linkOpt)) return;
689
870
- const validatedLink = yield* validateLinkResponse(ui, linkOpt.value);
871
- if (Option.isNone(validatedLink)) return;
690
+ const target = yield* validateLinkResponse(ui, linkOpt.value);
691
+ if (Option.isNone(target)) return;
692
873
- const { connectedAccountId: connAccountId, redirectUrl } = validatedLink.value;
693
const canContinue = yield* ensureAliasForAdditionalAccount({
694
ui,
876
- alias: normalizedAliasOption,
877
- connectedAccountId: connAccountId,
695
+ alias: normalizedAlias,
696
+ connectedAccountId: target.value.connectedAccountId,
697
existingAccounts,
879
- scopeDescription: `user "${resolvedUserId.value}" in toolkit "${toolkitSlug}"`,
698
+ scopeDescription: `user "${resolvedUserId}" in toolkit "${toolkitSlug}"`,
699
});
700
if (!canContinue) return;
701
883
- if (params.noWait) {
884
- yield* showRedirectUrl(ui, redirectUrl, { manual: true });
885
- yield* ui.output(
886
- JSON.stringify(
887
- {
888
- status: 'pending',
889
- message: 'Complete authorization by opening the URL',
890
- connected_account_id: connAccountId,
891
- redirect_url: redirectUrl,
892
- toolkit: toolkitSlug,
893
- project_type: resolvedProject.projectType,
894
- },
895
- null,
896
- 2
702
+ yield* finishLink({
703
+ ui,
704
+ client,
705
+ target: target.value,
706
+ toolkit: Option.some(toolkitSlug),
707
+ projectType: resolvedProject.projectType,
708
+ noWait: params.noWait,
709
+ noBrowser: params.noBrowser,
710
+ });
711
+ yield* appendCliSessionHistory({
712
+ orgId: Option.getOrUndefined(Option.map(scope, s => s.orgId)),
713
+ consumerUserId: Option.getOrUndefined(Option.map(scope, s => s.consumerUserId)),
714
+ entry: {
715
+ command: 'link',
716
+ status: params.noWait ? 'pending' : 'active',
717
+ toolkit: toolkitSlug,
718
+ connectedAccountId: target.value.connectedAccountId,
719
+ redirectUrl: target.value.redirectUrl,
720
+ },
721
+ }).pipe(Effect.ignore);
722
+ });
723
+
724
+// --- dispatch -----------------------------------------------------------------------------------
725
+
726
+/**
727
+ * Which flow the flags select, or none after reporting a usage mistake the parser cannot see.
728
+ * A blank `--alias` and a root `--auth-config` (the root tree is consumer-only) are usage errors
729
+ * that exit 1. The other mistakes print a message and exit 0.
730
+ */
731
+const selectLinkFlow = (params: ConnectedAccountsLinkParams, tree: CommandTree) =>
732
+ Effect.gen(function* () {
733
+ yield* resolveNormalizedAliasOption(params.alias);
734
+ const ui = yield* TerminalUI;
735
+ const reject = (message: string) =>
736
+ ui.log.error(message).pipe(Effect.as(Option.none<LinkFlow>()));
737
+ const select = (flow: LinkFlow) => Effect.succeedSome(flow);
738
+ return yield* Match.value({
739
+ tree,
740
+ toolkit: Option.isSome(params.toolkit),
741
+ authConfig: Option.isSome(params.authConfig),
742
+ list: params.list,
743
+ }).pipe(
744
+ Match.when({ tree: 'root', authConfig: true }, () =>
745
+ Effect.fail(invalidOptionValue(ROOT_AUTH_CONFIG_MESSAGE, '--auth-config'))
746
+ ),
747
+ Match.when({ toolkit: true, authConfig: true }, () =>
748
+ reject(TOOLKIT_AND_AUTH_CONFIG_MESSAGE)
749
+ ),
750
+ Match.when({ toolkit: false, authConfig: false }, () => reject(missingArgumentMessage(tree))),
751
+ Match.when({ list: true }, () => select('list')),
752
+ Match.when({ authConfig: true }, () => select('legacy')),
753
+ Match.orElse(() => select('tool-router'))
754
+ );
755
+ });
756
+
757
+/** `link` on either tree: validates the flag combination, then runs the flow it selects. */
758
+export const runConnectedAccountsLink = (params: ConnectedAccountsLinkParams) =>
759
+ Effect.gen(function* () {
760
+ const { tree } = yield* CommandSurface;
761
+ const flow = yield* selectLinkFlow(params, tree);
762
+ yield* Option.match(flow, {
763
+ onNone: () => Effect.void,
764
+ onSome: selected =>
765
+ Match.value(selected).pipe(
766
+ Match.when('list', () => handleListConnectedAccounts(params)),
767
+ Match.when('legacy', () => handleLegacyAuthConfigLink(params)),
768
+ Match.when('tool-router', () => handleToolRouterLink(params)),
769
+ Match.exhaustive
770
),
898
- { force: true }
899
- );
900
- yield* appendCliSessionHistory({
901
- orgId: resolvedProject.projectType === 'CONSUMER' ? resolvedProject.orgId : undefined,
902
- consumerUserId:
903
- resolvedProject.projectType === 'CONSUMER' ? resolvedProject.consumerUserId : undefined,
904
- entry: {
905
- command: 'link',
906
- status: 'pending',
907
- toolkit: toolkitSlug,
908
- connectedAccountId: connAccountId,
909
- redirectUrl,
910
- },
911
- }).pipe(Effect.ignore);
912
- } else {
913
- yield* waitForActiveConnection(ui, client, connAccountId, redirectUrl, params.noBrowser);
914
- yield* appendCliSessionHistory({
915
- orgId: resolvedProject.projectType === 'CONSUMER' ? resolvedProject.orgId : undefined,
916
- consumerUserId:
917
- resolvedProject.projectType === 'CONSUMER' ? resolvedProject.consumerUserId : undefined,
918
- entry: {
919
- command: 'link',
920
- status: 'active',
921
- toolkit: toolkitSlug,
922
- connectedAccountId: connAccountId,
923
- redirectUrl,
924
- },
925
- }).pipe(Effect.ignore);
926
- }
771
+ });
772
});