5
import { ComposioUserContext } from 'src/services/user-context';
6
import { TerminalUI } from 'src/services/terminal-ui';
7
import { requireAuth } from 'src/effects/require-auth';
8
-import { handleHttpServerError } from 'src/effects/handle-http-error';
8
import { resolveToolRouterSession } from 'src/effects/create-tool-router-session';
9
import { extractMessage } from 'src/utils/api-error-extraction';
10
import { ProjectContext } from 'src/services/project-context';
11
+import { ComposioClientSingleton } from 'src/services/composio-clients';
12
+import {
13
+ resolveCommandProject,
14
+ formatResolveCommandProjectError,
15
+} from 'src/services/command-project';
16
17
const toolkit = Args.text({ name: 'toolkit' }).pipe(
18
Args.withDescription('Toolkit slug to link (e.g. "github", "gmail")'),
25
);
26
27
const userId = Options.text('user-id').pipe(
24
- Options.withDescription('User ID for the connection (falls back to project test_user_id)'),
28
+ Options.withDescription('Developer-project user ID override'),
29
Options.optional
30
);
31
32
+const projectName = Options.text('project-name').pipe(
33
+ Options.optional,
34
+ Options.withDescription('Developer project name override for this command')
35
+);
36
+
37
const noBrowser = Options.boolean('no-browser').pipe(
38
Options.withDefault(false),
39
Options.withDescription('Skip auto-opening the browser')
44
Options.withDescription('Do not wait for authorization; only print link info')
45
);
46
38
-/**
39
- * Open the browser and poll until the connected account becomes ACTIVE.
40
- * On success, outputs valid JSON to stdout for piping (e.g. to jq).
41
- */
47
const waitForActiveConnection = (
48
ui: TerminalUI,
49
repo: ComposioToolkitsRepository,
52
noBrowser: boolean
53
) =>
54
Effect.gen(function* () {
50
- // Display the redirect URL (interactive only)
55
yield* ui.note(redirectUrl, 'Redirect URL');
56
57
if (!noBrowser) {
54
- // Validate URL scheme before opening — prevent non-HTTPS redirects
58
let urlSchemeValid = false;
59
try {
60
const parsed = new URL(redirectUrl);
61
urlSchemeValid = parsed.protocol === 'https:' || parsed.protocol === 'http:';
62
} catch {
60
- // Malformed URL — fall through to the warning below
63
+ // ignore
64
}
65
66
if (!urlSchemeValid) {
79
}
80
}
81
79
- // Poll until the connected account becomes ACTIVE
82
yield* ui.useMakeSpinner('Waiting for authentication...', spinner =>
83
Effect.retry(
84
Effect.gen(function* () {
85
const account = yield* repo.getConnectedAccount(connectedAccountId);
84
-
86
if (account.status === 'ACTIVE') {
87
return account;
88
}
88
-
89
return yield* Effect.fail(
90
new Error(`Connection status is still '${account.status}', waiting for 'ACTIVE'`)
91
);
92
}),
93
- // Exponential backoff: start with 0.3s, max 5s, up to 15 retries
93
Schedule.exponential('0.3 seconds').pipe(
94
Schedule.intersect(Schedule.recurs(15)),
95
Schedule.intersect(Schedule.spaced('5 seconds'))
120
);
121
});
122
124
-/**
125
- * Link an external account via OAuth redirect.
126
- *
127
- * Two modes:
128
- * - **Tool Router** (default): `composio manage connected-accounts link <toolkit>`
129
- * - **Legacy**: `composio manage connected-accounts link --auth-config <id>`
130
- *
131
- * @example
132
- * ```bash
133
- * composio manage connected-accounts link github
134
- * composio manage connected-accounts link gmail --user-id "alice"
135
- * composio manage connected-accounts link --auth-config "ac_..." --user-id "default"
136
- * ```
137
- */
138
-export const connectedAccountsCmd$Link = Command.make(
139
- 'link',
140
- { toolkit, authConfig, userId, noBrowser, noWait },
141
- ({ toolkit, authConfig, userId, noBrowser, noWait }) =>
142
- Effect.gen(function* () {
143
- if (!(yield* requireAuth)) return;
123
+const validateLinkResponse = (
124
+ ui: TerminalUI,
125
+ linkResponse: {
126
+ connected_account_id?: string | null;
127
+ redirect_url?: string | null;
128
+ }
129
+) =>
130
+ Effect.gen(function* () {
131
+ const connectedAccountId = linkResponse.connected_account_id;
132
+ const redirectUrl = linkResponse.redirect_url;
133
145
- const ui = yield* TerminalUI;
146
- const repo = yield* ComposioToolkitsRepository;
147
- const projectContext = yield* ProjectContext;
148
- const userContext = yield* ComposioUserContext;
149
- const resolvedProjectContext = yield* projectContext.resolve;
150
- const testUserId = Option.flatMap(resolvedProjectContext, keys => keys.testUserId);
134
+ if (!connectedAccountId || !redirectUrl) {
135
+ yield* ui.log.error(
136
+ 'The API returned an incomplete link response (missing connected_account_id or redirect_url).'
137
+ );
138
+ yield* Effect.logDebug('Link response:', linkResponse);
139
+ return Option.none();
140
+ }
141
+
142
+ return Option.some({
143
+ connectedAccountId,
144
+ redirectUrl,
145
+ });
146
+ });
147
+
148
+const runConnectedAccountsLink = (params: {
149
+ toolkit: Option.Option<string>;
150
+ authConfig: Option.Option<string>;
151
+ userId: Option.Option<string>;
152
+ projectName: Option.Option<string>;
153
+ noBrowser: boolean;
154
+ noWait: boolean;
155
+ rootOnly: boolean;
156
+}) =>
157
+ Effect.gen(function* () {
158
+ if (!(yield* requireAuth)) return;
159
+
160
+ const ui = yield* TerminalUI;
161
+ const repo = yield* ComposioToolkitsRepository;
162
+ const clientSingleton = yield* ComposioClientSingleton;
163
+ const projectContext = yield* ProjectContext;
164
+ const userContext = yield* ComposioUserContext;
165
+
166
+ if (params.rootOnly) {
167
+ if (Option.isSome(params.authConfig)) {
168
+ return yield* Effect.fail(
169
+ new Error(
170
+ 'Top-level `composio link` is consumer-only and does not accept `--auth-config`. Use `composio manage connected-accounts link --auth-config ...` for developer-scoped usage.'
171
+ )
172
+ );
173
+ }
174
+ }
175
+
176
+ if (Option.isSome(params.toolkit) && Option.isSome(params.authConfig)) {
177
+ yield* ui.log.error(
178
+ 'Cannot use both <toolkit> and --auth-config. Choose one:\n' +
179
+ ' Tool Router: composio manage connected-accounts link <toolkit>\n' +
180
+ ' Legacy: composio manage connected-accounts link --auth-config <id>'
181
+ );
182
+ return;
183
+ }
184
+
185
+ if (Option.isNone(params.toolkit) && Option.isNone(params.authConfig)) {
186
+ yield* ui.log.error(
187
+ params.rootOnly
188
+ ? 'Missing argument. Provide a toolkit slug:\n composio link github'
189
+ : 'Missing argument. Provide a toolkit slug or --auth-config:\n' +
190
+ ' composio manage connected-accounts link github\n' +
191
+ ' composio manage connected-accounts link --auth-config "ac_..."'
192
+ );
193
+ return;
194
+ }
195
+
196
+ if (Option.isSome(params.authConfig)) {
197
+ const authConfigId = params.authConfig.value;
198
+ const resolvedProjectContext = yield* projectContext.resolve.pipe(
199
+ Effect.catchAll(() => Effect.succeed(Option.none()))
200
+ );
201
+ const localTestUserId = Option.flatMap(resolvedProjectContext, keys => keys.testUserId);
202
const globalTestUserId = userContext.data.testUserId;
152
- const resolvedUserId = Option.match(userId, {
203
+ const resolvedUserId = Option.match(params.userId, {
204
onSome: value => Option.some(value),
154
- onNone: () => Option.orElse(testUserId, () => globalTestUserId),
205
+ onNone: () => Option.orElse(localTestUserId, () => globalTestUserId),
206
});
207
if (Option.isNone(resolvedUserId)) {
208
return yield* Effect.fail(
209
new Error('Missing user id. Provide --user-id or run composio init to set test_user_id.')
210
);
211
}
161
- if (Option.isNone(userId) && Option.isSome(testUserId)) {
162
- yield* ui.log.warn(`Using test user id "${testUserId.value}"`);
163
- } else if (Option.isNone(userId) && Option.isSome(globalTestUserId)) {
164
- yield* ui.log.warn(`Using global test user id "${globalTestUserId.value}"`);
165
- }
166
-
167
- // Validate: exactly one of <toolkit> or --auth-config must be provided
168
- if (Option.isSome(toolkit) && Option.isSome(authConfig)) {
212
+ if (Option.isNone(params.projectName) && Option.isNone(resolvedProjectContext)) {
213
yield* ui.log.error(
170
- 'Cannot use both <toolkit> and --auth-config. Choose one:\n' +
171
- ' Tool Router: composio manage connected-accounts link <toolkit>\n' +
172
- ' Legacy: composio manage connected-accounts link --auth-config <id>'
214
+ '`--auth-config` is developer-project scoped. Pass `--project-name <name>` or run from a directory initialized with `composio init`.'
215
);
216
return;
217
}
176
-
177
- if (Option.isNone(toolkit) && Option.isNone(authConfig)) {
178
- yield* ui.log.error(
179
- 'Missing argument. Provide a toolkit slug or --auth-config:\n' +
180
- ' composio manage connected-accounts link github\n' +
181
- ' composio manage connected-accounts link --auth-config "ac_..."'
182
- );
183
- return;
218
+ if (Option.isNone(params.userId) && Option.isSome(localTestUserId)) {
219
+ yield* ui.log.warn(`Using test user id "${localTestUserId.value}"`);
220
+ } else if (Option.isNone(params.userId) && Option.isSome(globalTestUserId)) {
221
+ yield* ui.log.warn(`Using global test user id "${globalTestUserId.value}"`);
222
}
185
-
186
- if (Option.isSome(authConfig)) {
187
- // Path A: Legacy flow — use existing client.link.create()
188
- const linkOpt = yield* ui
189
- .withSpinner(
190
- 'Creating link session...',
191
- repo.createConnectedAccountLink({
192
- auth_config_id: authConfig.value,
223
+ const resolvedProject = yield* resolveCommandProject({
224
+ mode: 'developer',
225
+ projectName: Option.getOrUndefined(params.projectName),
226
+ }).pipe(Effect.mapError(formatResolveCommandProjectError));
227
+ const client = yield* clientSingleton.getFor({
228
+ orgId: resolvedProject.orgId,
229
+ projectId: resolvedProject.projectId,
230
+ });
231
+ const linkOpt = yield* ui
232
+ .withSpinner(
233
+ 'Creating link session...',
234
+ Effect.tryPromise(() =>
235
+ client.link.create({
236
+ auth_config_id: authConfigId,
237
user_id: resolvedUserId.value,
238
})
239
)
196
- .pipe(
197
- Effect.asSome,
198
- Effect.catchTag(
199
- 'services/HttpServerError',
200
- handleHttpServerError(ui, {
201
- fallbackMessage: `Failed to create link for auth config "${authConfig.value}".`,
202
- hint: 'Browse available auth configs:\n> composio manage auth-configs list',
203
- fallbackValue: Option.none(),
204
- })
205
- )
206
- );
240
+ )
241
+ .pipe(
242
+ Effect.asSome,
243
+ Effect.catchAll(error =>
244
+ Effect.gen(function* () {
245
+ const message =
246
+ extractMessage(error) ?? `Failed to create link for auth config "${authConfigId}".`;
247
+ yield* ui.log.error(message);
248
+ yield* ui.log.step(
249
+ 'Browse available auth configs:\n> composio manage auth-configs list'
250
+ );
251
+ return Option.none();
252
+ })
253
+ )
254
+ );
255
208
- if (Option.isNone(linkOpt)) {
209
- return;
210
- }
256
+ if (Option.isNone(linkOpt)) return;
257
212
- const { connected_account_id: connId, redirect_url: redirectUrl } = linkOpt.value;
258
+ const validatedLink = yield* validateLinkResponse(ui, linkOpt.value);
259
+ if (Option.isNone(validatedLink)) return;
260
214
- if (noWait) {
215
- yield* ui.note(redirectUrl, 'Redirect URL');
216
- yield* ui.output(
217
- JSON.stringify(
218
- {
219
- status: 'pending',
220
- message: 'Complete authorization by opening the URL',
221
- connected_account_id: connId,
222
- redirect_url: redirectUrl,
223
- },
224
- null,
225
- 2
226
- )
227
- );
228
- } else {
229
- yield* waitForActiveConnection(ui, repo, connId, redirectUrl, noBrowser);
230
- }
261
+ const { connectedAccountId: connId, redirectUrl } = validatedLink.value;
262
+ if (params.noWait) {
263
+ yield* ui.note(redirectUrl, 'Redirect URL');
264
+ yield* ui.output(
265
+ JSON.stringify(
266
+ {
267
+ status: 'pending',
268
+ message: 'Complete authorization by opening the URL',
269
+ connected_account_id: connId,
270
+ redirect_url: redirectUrl,
271
+ project_type: resolvedProject.projectType,
272
+ },
273
+ null,
274
+ 2
275
+ )
276
+ );
277
} else {
232
- // Path B: Tool Router flow — toolkit is guaranteed Some (validated above)
233
- const toolkitSlug = Option.getOrThrow(toolkit);
278
+ yield* waitForActiveConnection(ui, repo, connId, redirectUrl, params.noBrowser);
279
+ }
280
+ return;
281
+ }
282
235
- const linkOpt = yield* ui
236
- .withSpinner(
237
- `Linking ${toolkitSlug}...`,
238
- Effect.gen(function* () {
239
- const { client, sessionId } = yield* resolveToolRouterSession(resolvedUserId.value, {
240
- manageConnections: true,
241
- });
242
- return yield* Effect.tryPromise(() =>
243
- client.toolRouter.session.link(sessionId, { toolkit: toolkitSlug })
244
- );
245
- })
246
- )
247
- .pipe(
248
- Effect.asSome,
249
- Effect.catchAll(error =>
250
- Effect.gen(function* () {
251
- const message =
252
- extractMessage(error) ?? `Failed to create link for toolkit "${toolkitSlug}".`;
253
- yield* ui.log.error(message);
254
- yield* Effect.logDebug('Link error:', error);
255
- yield* ui.log.step('Browse available toolkits:\n> composio manage toolkits list');
256
- return Option.none();
257
- })
258
- )
283
+ const toolkitSlug = Option.getOrThrow(params.toolkit);
284
+ const resolvedProject = yield* resolveCommandProject({
285
+ mode: 'consumer',
286
+ projectName: params.rootOnly ? undefined : Option.getOrUndefined(params.projectName),
287
+ }).pipe(Effect.mapError(formatResolveCommandProjectError));
288
+ const resolvedUserId =
289
+ resolvedProject.projectType === 'CONSUMER'
290
+ ? Option.fromNullable(resolvedProject.consumerUserId)
291
+ : Option.match(params.userId, {
292
+ onSome: value => Option.some(value),
293
+ onNone: () => userContext.data.testUserId,
294
+ });
295
+ if (Option.isNone(resolvedUserId)) {
296
+ return yield* Effect.fail(
297
+ new Error(
298
+ 'Missing user id. Provide --user-id or run composio login to set global test_user_id.'
299
+ )
300
+ );
301
+ }
302
+ const client = yield* clientSingleton.getFor({
303
+ orgId: resolvedProject.orgId,
304
+ projectId: resolvedProject.projectId,
305
+ });
306
+
307
+ const linkOpt = yield* ui
308
+ .withSpinner(
309
+ `Linking ${toolkitSlug}...`,
310
+ Effect.gen(function* () {
311
+ const { sessionId } = yield* resolveToolRouterSession(client, resolvedUserId.value, {
312
+ manageConnections: true,
313
+ });
314
+ return yield* Effect.tryPromise(() =>
315
+ client.toolRouter.session.link(sessionId, { toolkit: toolkitSlug })
316
);
317
+ })
318
+ )
319
+ .pipe(
320
+ Effect.asSome,
321
+ Effect.catchAll(error =>
322
+ Effect.gen(function* () {
323
+ const message =
324
+ extractMessage(error) ?? `Failed to create link for toolkit "${toolkitSlug}".`;
325
+ yield* ui.log.error(message);
326
+ yield* Effect.logDebug('Link error:', error);
327
+ yield* ui.log.step('Browse available toolkits:\n> composio manage toolkits list');
328
+ return Option.none();
329
+ })
330
+ )
331
+ );
332
261
- if (Option.isNone(linkOpt)) {
262
- return;
263
- }
333
+ if (Option.isNone(linkOpt)) return;
334
265
- const { connected_account_id: connAccountId, redirect_url: redirectUrl } = linkOpt.value;
266
- if (!connAccountId || !redirectUrl) {
267
- yield* ui.log.error(
268
- 'The API returned an incomplete link response (missing connected_account_id or redirect_url).'
269
- );
270
- yield* Effect.logDebug('Link response:', linkOpt.value);
271
- return;
272
- }
335
+ const validatedLink = yield* validateLinkResponse(ui, linkOpt.value);
336
+ if (Option.isNone(validatedLink)) return;
337
274
- if (noWait) {
275
- yield* ui.note(redirectUrl, 'Redirect URL');
276
- yield* ui.output(
277
- JSON.stringify(
278
- {
279
- status: 'pending',
280
- message: 'Complete authorization by opening the URL',
281
- connected_account_id: connAccountId,
282
- redirect_url: redirectUrl,
283
- toolkit: toolkitSlug,
284
- },
285
- null,
286
- 2
287
- )
288
- );
289
- } else {
290
- yield* waitForActiveConnection(ui, repo, connAccountId, redirectUrl, noBrowser);
291
- }
292
- }
338
+ const { connectedAccountId: connAccountId, redirectUrl } = validatedLink.value;
339
+
340
+ if (params.noWait) {
341
+ yield* ui.note(redirectUrl, 'Redirect URL');
342
+ yield* ui.output(
343
+ JSON.stringify(
344
+ {
345
+ status: 'pending',
346
+ message: 'Complete authorization by opening the URL',
347
+ connected_account_id: connAccountId,
348
+ redirect_url: redirectUrl,
349
+ toolkit: toolkitSlug,
350
+ project_type: resolvedProject.projectType,
351
+ },
352
+ null,
353
+ 2
354
+ )
355
+ );
356
+ } else {
357
+ yield* waitForActiveConnection(ui, repo, connAccountId, redirectUrl, params.noBrowser);
358
+ }
359
+ });
360
+
361
+export const connectedAccountsCmd$Link = Command.make(
362
+ 'link',
363
+ { toolkit, authConfig, userId, projectName, noBrowser, noWait },
364
+ ({ toolkit, authConfig, userId, projectName, noBrowser, noWait }) =>
365
+ runConnectedAccountsLink({
366
+ toolkit,
367
+ authConfig,
368
+ userId,
369
+ projectName,
370
+ noBrowser,
371
+ noWait,
372
+ rootOnly: false,
373
})
294
-).pipe(Command.withDescription('Link an external account via OAuth redirect.'));
374
+).pipe(
375
+ Command.withDescription(
376
+ [
377
+ 'Link an external account via OAuth redirect.',
378
+ '',
379
+ 'Related:',
380
+ ' composio search "<query>"',
381
+ " composio execute <slug> -d '{}'",
382
+ ].join('\n')
383
+ )
384
+);
385
+
386
+export const rootConnectedAccountsCmd$Link = Command.make(
387
+ 'link',
388
+ { toolkit, noBrowser, noWait },
389
+ ({ toolkit, noBrowser, noWait }) =>
390
+ runConnectedAccountsLink({
391
+ toolkit,
392
+ authConfig: Option.none(),
393
+ userId: Option.none(),
394
+ projectName: Option.none(),
395
+ noBrowser,
396
+ noWait,
397
+ rootOnly: true,
398
+ })
399
+).pipe(
400
+ Command.withDescription(
401
+ [
402
+ 'Link an external account via OAuth redirect.',
403
+ '',
404
+ 'Related:',
405
+ ' composio search "<query>"',
406
+ " composio execute <slug> -d '{}'",
407
+ ].join('\n')
408
+ )
409
+);