1
-import { Command, Options } from '@effect/cli';
1
+import { Args, Command, Options } from '@effect/cli';
2
import { Effect, Option, Schedule } from 'effect';
3
import open from 'open';
4
-import { ComposioToolkitsRepository } from 'src/services/composio-clients';
4
+import { ComposioClientSingleton, ComposioToolkitsRepository } from 'src/services/composio-clients';
5
import { TerminalUI } from 'src/services/terminal-ui';
6
import { requireAuth } from 'src/effects/require-auth';
7
import { handleHttpServerError } from 'src/effects/handle-http-error';
8
+import { createToolRouterSession } from 'src/effects/create-tool-router-session';
9
+
10
+const toolkit = Args.text({ name: 'toolkit' }).pipe(
11
+ Args.withDescription('Toolkit slug to link (e.g. "github", "gmail")'),
12
+ Args.optional
13
+);
14
15
const authConfig = Options.text('auth-config').pipe(
10
- Options.withDescription('Auth config ID (e.g. "ac_...")')
16
+ Options.withDescription('Auth config ID (e.g. "ac_..."). Uses legacy flow (no Tool Router).'),
17
+ Options.optional
18
);
19
20
const userId = Options.text('user-id').pipe(
28
);
29
30
/**
24
- * Link an external account by creating an OAuth redirect session.
31
+ * Open the browser and poll until the connected account becomes ACTIVE.
32
+ */
33
+const waitForActiveConnection = (
34
+ ui: TerminalUI,
35
+ repo: ComposioToolkitsRepository,
36
+ connectedAccountId: string,
37
+ redirectUrl: string,
38
+ noBrowser: boolean
39
+) =>
40
+ Effect.gen(function* () {
41
+ // Display the redirect URL
42
+ yield* ui.note(redirectUrl, 'Redirect URL');
43
+ yield* ui.output(redirectUrl);
44
+
45
+ if (!noBrowser) {
46
+ yield* Effect.tryPromise(() => open(redirectUrl, { wait: false })).pipe(
47
+ Effect.catchAll(error =>
48
+ Effect.gen(function* () {
49
+ yield* Effect.logDebug('Failed to open browser:', error);
50
+ yield* ui.log.warn('Could not open the browser automatically.');
51
+ yield* ui.log.info('Tip: try using `--no-browser` and open the URL manually.');
52
+ })
53
+ )
54
+ );
55
+ }
56
+
57
+ // Poll until the connected account becomes ACTIVE
58
+ yield* ui.useMakeSpinner('Waiting for authentication...', spinner =>
59
+ Effect.retry(
60
+ Effect.gen(function* () {
61
+ const account = yield* repo.getConnectedAccount(connectedAccountId);
62
+
63
+ if (account.status === 'ACTIVE') {
64
+ return account;
65
+ }
66
+
67
+ return yield* Effect.fail(
68
+ new Error(`Connection status is still '${account.status}', waiting for 'ACTIVE'`)
69
+ );
70
+ }),
71
+ // Exponential backoff: start with 0.3s, max 5s, up to 15 retries
72
+ Schedule.exponential('0.3 seconds').pipe(
73
+ Schedule.intersect(Schedule.recurs(15)),
74
+ Schedule.intersect(Schedule.spaced('5 seconds'))
75
+ )
76
+ ).pipe(
77
+ Effect.tap(account => {
78
+ return Effect.all([
79
+ spinner.stop('Connection successful'),
80
+ ui.log.success(
81
+ `Connected account "${account.id}" is now ACTIVE (toolkit: ${account.toolkit.slug}).`
82
+ ),
83
+ ]);
84
+ }),
85
+ Effect.tapError(() => spinner.error('Connection timed out. Please try again.'))
86
+ )
87
+ );
88
+ });
89
+
90
+/**
91
+ * Link an external account via OAuth redirect.
92
*
26
- * Opens the browser to the redirect URL and polls until the connection
27
- * becomes ACTIVE.
93
+ * Two modes:
94
+ * - **Tool Router** (default): `composio connected-accounts link <toolkit>`
95
+ * - **Legacy**: `composio connected-accounts link --auth-config <id>`
96
*
97
* @example
98
* ```bash
99
+ * composio connected-accounts link github
100
+ * composio connected-accounts link gmail --user-id "alice"
101
* composio connected-accounts link --auth-config "ac_..." --user-id "default"
32
- * composio connected-accounts link --auth-config "ac_..." --no-browser
102
* ```
103
*/
104
export const connectedAccountsCmd$Link = Command.make(
105
'link',
37
- { authConfig, userId, noBrowser },
38
- ({ authConfig, userId, noBrowser }) =>
106
+ { toolkit, authConfig, userId, noBrowser },
107
+ ({ toolkit, authConfig, userId, noBrowser }) =>
108
Effect.gen(function* () {
109
if (!(yield* requireAuth)) return;
110
111
const ui = yield* TerminalUI;
112
const repo = yield* ComposioToolkitsRepository;
113
45
- // Create the link session
46
- const linkOpt = yield* ui
47
- .withSpinner(
48
- 'Creating link session...',
49
- repo.createConnectedAccountLink({
50
- auth_config_id: authConfig,
51
- user_id: userId,
52
- })
53
- )
54
- .pipe(
55
- Effect.asSome,
56
- Effect.catchTag(
57
- 'services/HttpServerError',
58
- handleHttpServerError(ui, {
59
- fallbackMessage: `Failed to create link for auth config "${authConfig}".`,
60
- hint: 'Browse available auth configs:\n> composio auth-configs list',
61
- fallbackValue: Option.none(),
62
- })
63
- )
114
+ // Validate: exactly one of <toolkit> or --auth-config must be provided
115
+ if (Option.isSome(toolkit) && Option.isSome(authConfig)) {
116
+ yield* ui.log.error(
117
+ 'Cannot use both <toolkit> and --auth-config. Choose one:\n' +
118
+ ' Tool Router: composio connected-accounts link <toolkit>\n' +
119
+ ' Legacy: composio connected-accounts link --auth-config <id>'
120
);
121
+ return;
122
+ }
123
66
- if (Option.isNone(linkOpt)) {
124
+ if (Option.isNone(toolkit) && Option.isNone(authConfig)) {
125
+ yield* ui.log.error(
126
+ 'Missing argument. Provide a toolkit slug or --auth-config:\n' +
127
+ ' composio connected-accounts link github\n' +
128
+ ' composio connected-accounts link --auth-config "ac_..."'
129
+ );
130
return;
131
}
132
70
- const { connected_account_id, redirect_url } = linkOpt.value;
133
+ if (Option.isSome(authConfig)) {
134
+ // Path A: Legacy flow — use existing client.link.create()
135
+ const linkOpt = yield* ui
136
+ .withSpinner(
137
+ 'Creating link session...',
138
+ repo.createConnectedAccountLink({
139
+ auth_config_id: authConfig.value,
140
+ user_id: userId,
141
+ })
142
+ )
143
+ .pipe(
144
+ Effect.asSome,
145
+ Effect.catchTag(
146
+ 'services/HttpServerError',
147
+ handleHttpServerError(ui, {
148
+ fallbackMessage: `Failed to create link for auth config "${authConfig.value}".`,
149
+ hint: 'Browse available auth configs:\n> composio auth-configs list',
150
+ fallbackValue: Option.none(),
151
+ })
152
+ )
153
+ );
154
72
- // Display the redirect URL
73
- yield* ui.note(redirect_url, 'Redirect URL');
74
- yield* ui.output(redirect_url);
155
+ if (Option.isNone(linkOpt)) {
156
+ return;
157
+ }
158
+
159
+ yield* waitForActiveConnection(
160
+ ui,
161
+ repo,
162
+ linkOpt.value.connected_account_id,
163
+ linkOpt.value.redirect_url,
164
+ noBrowser
165
+ );
166
+ } else {
167
+ // Path B: Tool Router flow — toolkit is guaranteed Some (validated above)
168
+ const toolkitSlug = Option.getOrThrow(toolkit);
169
+ const clientSingleton = yield* ComposioClientSingleton;
170
+ const client = yield* clientSingleton.get();
171
76
- if (!noBrowser) {
77
- yield* Effect.tryPromise(() => open(redirect_url, { wait: false })).pipe(
78
- Effect.catchAll(error =>
172
+ const linkOpt = yield* ui
173
+ .withSpinner(
174
+ `Linking ${toolkitSlug}...`,
175
Effect.gen(function* () {
80
- yield* Effect.logDebug('Failed to open browser:', error);
81
- yield* ui.log.warn('Could not open the browser automatically.');
82
- yield* ui.log.info('Tip: try using `--no-browser` and open the URL manually.');
176
+ const sessionId = yield* createToolRouterSession(client, userId, {
177
+ manageConnections: true,
178
+ });
179
+ return yield* Effect.tryPromise(() =>
180
+ client.toolRouter.session.link(sessionId, { toolkit: toolkitSlug })
181
+ );
182
})
183
)
184
+ .pipe(
185
+ Effect.asSome,
186
+ Effect.catchAll(error =>
187
+ Effect.gen(function* () {
188
+ // Surface the API error message when available
189
+ const message =
190
+ error instanceof Error
191
+ ? error.message
192
+ : typeof error === 'object' && error !== null && 'message' in error
193
+ ? String((error as { message: unknown }).message)
194
+ : `Failed to create link for toolkit "${toolkitSlug}".`;
195
+
196
+ yield* ui.log.error(message);
197
+ yield* Effect.logDebug('Link error:', error);
198
+ yield* ui.log.step('Browse available toolkits:\n> composio toolkits list');
199
+ return Option.none();
200
+ })
201
+ )
202
+ );
203
+
204
+ if (Option.isNone(linkOpt)) {
205
+ return;
206
+ }
207
+
208
+ yield* waitForActiveConnection(
209
+ ui,
210
+ repo,
211
+ linkOpt.value.connected_account_id,
212
+ linkOpt.value.redirect_url,
213
+ noBrowser
214
);
215
}
87
-
88
- // Poll until the connected account becomes ACTIVE
89
- yield* ui.useMakeSpinner('Waiting for authentication...', spinner =>
90
- Effect.retry(
91
- Effect.gen(function* () {
92
- const account = yield* repo.getConnectedAccount(connected_account_id);
93
-
94
- if (account.status === 'ACTIVE') {
95
- return account;
96
- }
97
-
98
- return yield* Effect.fail(
99
- new Error(`Connection status is still '${account.status}', waiting for 'ACTIVE'`)
100
- );
101
- }),
102
- // Exponential backoff: start with 0.3s, max 5s, up to 15 retries
103
- Schedule.exponential('0.3 seconds').pipe(
104
- Schedule.intersect(Schedule.recurs(15)),
105
- Schedule.intersect(Schedule.spaced('5 seconds'))
106
- )
107
- ).pipe(
108
- Effect.tap(account => {
109
- return Effect.all([
110
- spinner.stop('Connection successful'),
111
- ui.log.success(
112
- `Connected account "${account.id}" is now ACTIVE (toolkit: ${account.toolkit.slug}).`
113
- ),
114
- ]);
115
- }),
116
- Effect.tapError(() => spinner.error('Connection timed out. Please try again.'))
117
- )
118
- );
216
})
217
).pipe(Command.withDescription('Link an external account via OAuth redirect.'));