@devries-cameron20 / composio-1 / commits / 12172ab5d
Fork 0

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

refactor(cli): split the `link` handler into one function per flow (#4921)

This PR: - builds on top of https://github.com/ComposioHQ/composio/pull/4900 (`CommandSurface`) and https://github.com/ComposioHQ/composio/pull/4913 / https://github.com/ComposioHQ/composio/pull/4915 (account and connected-account test layers) - makes `handleListConnectedAccounts`, `handleLegacyAuthConfigLink` and `handleToolRouterLink` exported handlers over the one `ConnectedAccountsLinkParams` type; each reads `--user-id`, `--project-name` and the tree from `CommandSurface` instead of taking them as arguments - reduces `runConnectedAccountsLink` to dispatch: `selectLinkFlow` validates the flag combination with one `Match.value` table, then runs the chosen flow - moves presentation into the new `connected-accounts.link.format.ts`: usage messages, the redirect-URL step, alias-conflict tips, the existing-account labels, the dashboard URL, and the three stdout payloads (pending, active, `--list`), built through one `toStdoutJson` helper; errors stay in `connected-accounts.link.errors.ts` - replaces the if-chains for alias normalization, user-id fallback, link-response validation, consumer scope and empty lists with `Option`, `Effect.fromOption` and `Array.match`; no `Do` notation - rewords the link command's stderr messages (listed below) and adds a `CHANGELOG.md` entry; stdout payloads and exit codes are unchanged - adds `connected-accounts.link.handler.test.ts` (22 tests), which runs the dispatcher and each flow without argv, over the `layers/accounts.ts` and `layers/connected-accounts.ts` resources plus service doubles instead of `TestLive` ## Context Unit U5 of the command-layout series. `runConnectedAccountsLink` used to hold the whole Tool Router flow inline. For it to do only dispatch, that flow had to go somewhere, so it is now a named handler beside the other two. That makes four exported functions rather than three. The structure change keeps behavior. The rewording is the one deliberate user-visible change, made in review in its own commit (74e33d181): | Case | Before | After | | --- | --- | --- | | root `link --auth-config` (exit 1) | 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. | `composio link` does not accept `--auth-config`. To link through a developer project's auth config, run `composio dev connected-accounts link --auth-config <id>`. | | toolkit and `--auth-config` | Cannot use both <toolkit> and --auth-config. Choose one: | Pass a toolkit or `--auth-config`, not both. | | no toolkit (root) | Missing argument. Provide a toolkit slug: | Pass the toolkit to link. | | no toolkit (dev) | Missing argument. Provide a toolkit slug or --auth-config: … `--auth-config "ac_..."` | Pass the toolkit to link, or `--auth-config`. … `--auth-config <id>` | | `--list` without a toolkit | `--list` requires a toolkit slug, e.g. `composio link gmail --list`. | `--list` needs a toolkit, for example `composio link gmail --list`. | | `--auth-config` without a project | `--auth-config` is developer-project scoped. Pass `--project-name <name>` or run from a directory initialized with `composio dev init`. | `--auth-config` needs a developer project. Pass `--project-name <name>`, or run the command in a directory set up with `composio dev init`. | | incomplete link response | The API returned an incomplete link response (missing connected_account_id or redirect_url). | The link response from the API is missing `connected_account_id` or `redirect_url`. | | unmanaged auth | Composio does not manage auth for "gmail" — opening the dashboard to connect manually. | Composio does not manage auth for "gmail". Opening the dashboard to connect it there. | | `--list` with no user | Missing user id. Provide --user-id or run composio dev init/login first. | Missing user id. Provide --user-id, or run composio dev init or composio login first. | | polling spinner and timeout | Waiting for authentication... / Connection timed out. Please try again. | Waiting for authorization... / Timed out waiting for authorization. Run the command again. | The Tool Router "missing user id" message is left as it was, because `execute` and `search` print the same sentence. The `message` fields inside the stdout JSON are data and also stay as they were. Evidence: - **Characterization:** `connected-accounts.link.cmd.test.ts` and `connected-accounts.link.client.cmd.test.ts` (19 tests), and `surface.test.ts`, pass on the structure commits with no change. The rewording commit changes one assertion, the incomplete-response line. - **Stdout payloads:** a direct comparison of the five payload shapes (pending with and without `toolkit`, active, `--list` empty and non-empty) against the pre-PR literals gives identical strings. The tests parse the JSON, so they would not catch a key reorder on their own. - **Dispatch order is kept:** a blank `--alias` is checked first, then root `--auth-config`, then toolkit and `--auth-config` together, then neither, then `--list`, `--auth-config`, toolkit. The handler tests cover each step. - **Mutation check:** sending `--list` to the legacy flow, or inverting the test-user warning, fails the handler tests. - **Binary smoke:** `build` + `build:binary` on this branch and on `origin/next` (dad230be8), with an isolated `HOME`, telemetry off and stdin closed. - It runs 15 invocations, both logged out and with a fake key against an unreachable backend, which lets the handler's checks run before any request. - Help pages, exit codes and stdout match. - The only transcript difference is the root `--auth-config` line from the table. The other reworded lines are decoration, and the smoke suppresses decoration because stderr is not a terminal. The logged-in transcript needs a real account and was not run. Verified locally on the branch tip: | Check | Result | | --- | --- | | `pnpm typecheck` (root) | passes | | `pnpm --filter @composio/cli test` | 155 files, 1841 passed, 1 skipped | | `validate:command-tests` | 16 exemptions, unchanged | | `validate:boundaries` | unchanged | | `lint:effect` | 0 diagnostics | | `oxlint`, prettier on touched files | clean | `analytics.dispatch.test.ts` › "uses one install_id across concurrent first-run events" is flaky under full-suite load. It failed in 2 of 5 full runs on this branch and passed in the other three, including the latest. It passed in 3 of 3 runs on its own and in 1 of 1 full run on `next`. The test races 16 writers against a 500 ms wall-clock lock timeout, and this PR touches nothing on that path. ## Deferred - The `--help` snapshot files the plan mentions for U1 do not exist yet. The help pages are compared through the binary transcripts above instead. - `link --list` still resolves the consumer project on both trees, as before. Moving it onto `resolveSurfaceProject` would change which project `dev … link --list` uses without `--project-name`, so it is out of scope. - The handler test builds its mock client with a shallow spread and one cast. `test-layer.ts` keeps its deep-merging `withShadows` private. Exporting it would remove the cast but changes the shared harness, so it belongs in a U3 extraction. - `JSON.stringify(value, null, 2)` before `ui.output` repeats across about 20 commands. `toStdoutJson` stays local to `link`, and a CLI-wide helper is a separate change. - The agent skills that teach the CLI need a refresh after the series reshapes it, in a follow-up PR. They are the bundled `composio-cli` skill (`ts/packages/cli/skills-src/composio-cli`, checked by `validate:skills`) and the repo's `skills/composio`. None quotes a message this PR rewords, so nothing in them is wrong today. They predate the `dev` group's shared `--user-id` and `--project-name` (#4900), and they do not cover `link --list`, `--auth-config` needing a developer project, or the `--no-wait` JSON.

Alberto Schiabel committed Oct 16, 2026 at 12:38 UTC 12172ab5d6163755d2625107af0f99403ca5961f
6 files changed +1660 -680
ts/packages/cli/CHANGELOG.md
+12
@@ -1,5 +1,17 @@
1 # @composio/cli
2
3 +## Unreleased
4 +
5 +### Patch Changes
6 +
7 +- `composio link` and `composio dev connected-accounts link` reword their usage
8 + and status messages on stderr: the rejected `--auth-config` on the root
9 + command, a toolkit passed together with `--auth-config`, a missing toolkit,
10 + `--list` without a toolkit, a missing user id, `--auth-config` without a
11 + developer project, an incomplete link response, a toolkit whose auth
12 + Composio does not manage, and the waiting and timeout lines shown while a
13 + link is pending. Exit codes and the JSON printed on stdout are unchanged.
14 +
15 ## 0.4.5
16
17 ### Patch Changes
ts/packages/cli/src/commands/connected-accounts/link/connected-accounts.link.format.ts new
+207
@@ -0,0 +1,207 @@
1 +import { Array as Arr, Effect, Option } from 'effect';
2 +import type { CommandTree } from 'src/commands/surface';
3 +import type { ConnectedAccountItem } from 'src/models/connected-accounts';
4 +import type { CliProjectType } from 'src/services/command-project';
5 +import type { TerminalUI } from 'src/services/terminal-ui';
6 +import { formatConnectedAccountsTable } from '../format';
7 +
8 +/** A connected account as the link flows label it: id first, alias and word id when set. */
9 +export interface ExistingAccountLabel {
10 + readonly id: string;
11 + readonly alias?: string | null;
12 + readonly word_id?: string | null;
13 +}
14 +
15 +/** A link the API created: the account it belongs to and the page that authorizes it. */
16 +export interface LinkTarget {
17 + readonly connectedAccountId: string;
18 + readonly redirectUrl: string;
19 +}
20 +
21 +// --- usage messages the parser cannot produce; printed on stderr --------------------------
22 +
23 +export const ROOT_AUTH_CONFIG_MESSAGE =
24 + "`composio link` does not accept `--auth-config`. To link through a developer project's auth config, run `composio dev connected-accounts link --auth-config <id>`.";
25 +
26 +export const TOOLKIT_AND_AUTH_CONFIG_MESSAGE =
27 + 'Pass a toolkit or `--auth-config`, not both.\n' +
28 + ' Tool Router: composio dev connected-accounts link <toolkit>\n' +
29 + ' Legacy: composio dev connected-accounts link --auth-config <id>';
30 +
31 +export const missingArgumentMessage = (tree: CommandTree) =>
32 + tree === 'root'
33 + ? 'Pass the toolkit to link.\n composio link github'
34 + : 'Pass the toolkit to link, or `--auth-config`.\n' +
35 + ' composio dev connected-accounts link github\n' +
36 + ' composio dev connected-accounts link --auth-config <id>';
37 +
38 +export const LIST_REQUIRES_TOOLKIT_MESSAGE =
39 + '`--list` needs a toolkit, for example `composio link gmail --list`.';
40 +
41 +export const LIST_WITH_AUTH_CONFIG_MESSAGE = '`--list` cannot be combined with `--auth-config`.';
42 +
43 +export const AUTH_CONFIG_SCOPE_MESSAGE =
44 + '`--auth-config` needs a developer project. Pass `--project-name <name>`, or run the command in a directory set up with `composio dev init`.';
45 +
46 +export const INCOMPLETE_LINK_RESPONSE_MESSAGE =
47 + 'The link response from the API is missing `connected_account_id` or `redirect_url`.';
48 +
49 +export const BROWSE_TOOLKITS_HINT = 'Browse available toolkits:\n> composio dev toolkits list';
50 +
51 +export const BROWSE_AUTH_CONFIGS_HINT =
52 + 'Browse available auth configs:\n> composio dev auth-configs list';
53 +
54 +// --- human renderers (stderr) ---------------------------------------------------------------
55 +
56 +/**
57 + * Points the user at the authorization page: a step line and the URL as a note. `manual` is
58 + * for a page the CLI does not open itself.
59 + */
60 +export const showRedirectUrl = (
61 + ui: TerminalUI,
62 + redirectUrl: string,
63 + options: { readonly manual: boolean }
64 +) =>
65 + Effect.gen(function* () {
66 + yield* ui.log.step(
67 + options.manual
68 + ? 'Open this URL in your browser to authorize'
69 + : 'Redirecting you to the authorization page'
70 + );
71 + yield* ui.note(redirectUrl, 'Redirect URL');
72 + });
73 +
74 +/** `id (alias, word_id)` per account, comma separated. An account without labels is its id. */
75 +const formatExistingAccountLabels = (items: ReadonlyArray<ExistingAccountLabel>) =>
76 + items
77 + .map(item =>
78 + Arr.match(
79 + [item.alias, item.word_id].filter(
80 + (value): value is string => typeof value === 'string' && value.trim().length > 0
81 + ),
82 + {
83 + onEmpty: () => item.id,
84 + onNonEmpty: labels => `${item.id} (${labels.join(', ')})`,
85 + }
86 + )
87 + )
88 + .join(', ');
89 +
90 +/** Why a second account needs `--alias`, and which accounts already exist for the scope. */
91 +export const showExistingAccounts = (
92 + ui: TerminalUI,
93 + scopeDescription: string,
94 + items: ReadonlyArray<ExistingAccountLabel>
95 +) =>
96 + Effect.gen(function* () {
97 + yield* ui.log.error(
98 + `A connected account already exists for ${scopeDescription}. Pass --alias to create another one.`
99 + );
100 + yield* ui.note(formatExistingAccountLabels(items), 'Existing accounts');
101 + });
102 +
103 +/**
104 + * The alias is taken: which account holds it, and how to use that account or list them all.
105 + * The hint commands differ per tree, so the caller passes them.
106 + */
107 +export const showAliasConflict = (
108 + ui: TerminalUI,
109 + params: {
110 + readonly alias: string;
111 + readonly existingId: string;
112 + readonly executeCommand: string;
113 + readonly listCommand: string;
114 + }
115 +) =>
116 + Effect.gen(function* () {
117 + yield* ui.log.error(
118 + `Alias "${params.alias}" is already in use by connected account "${params.existingId}".`
119 + );
120 + yield* ui.note(
121 + [
122 + `Use the existing alias: ${params.executeCommand} <TOOL_SLUG> --account ${params.alias} -d '{ ... }'`,
123 + `List connected accounts: ${params.listCommand}`,
124 + ].join('\n'),
125 + 'Tips'
126 + );
127 + });
128 +
129 +/** The table of a toolkit's active accounts as a note, or a warning when there are none. */
130 +export const showConnectedAccounts = (
131 + ui: TerminalUI,
132 + toolkitSlug: string,
133 + items: ReadonlyArray<ConnectedAccountItem>
134 +) =>
135 + Arr.match(items, {
136 + onEmpty: () => ui.log.warn(`No active connected accounts found for "${toolkitSlug}".`),
137 + onNonEmpty: accounts =>
138 + ui.note(formatConnectedAccountsTable(accounts), `${toolkitSlug}: connected accounts`),
139 + });
140 +
141 +/**
142 + * The dashboard page that connects a toolkit Composio does not manage auth for. Path segments
143 + * are encoded so an org name with spaces or `@` does not bake `?open=true` into the path.
144 + */
145 +export const dashboardConnectUrl = (webURL: string, orgName: string, toolkitSlug: string) =>
146 + `${webURL.replace(/\/+$/, '')}/${encodeURIComponent(orgName)}/~/connect/apps/${encodeURIComponent(toolkitSlug)}?open=true`;
147 +
148 +/** The warning that precedes the dashboard URL when Composio does not manage a toolkit's auth. */
149 +export const unmanagedAuthMessage = (toolkitSlug: string, noBrowser: boolean) =>
150 + `Composio does not manage auth for "${toolkitSlug}". ${noBrowser ? 'Open the dashboard to connect it there.' : 'Opening the dashboard to connect it there.'}`;
151 +
152 +/** The success line once polling sees the account `ACTIVE`. Also the `message` of its payload. */
153 +export const activeConnectionMessage = (account: {
154 + readonly id: string;
155 + readonly toolkit: { readonly slug: string };
156 +}) => `Connected account "${account.id}" is now ACTIVE (toolkit: ${account.toolkit.slug}).`;
157 +
158 +// --- machine renderers (stdout) ---------------------------------------------------------------
159 +
160 +/**
161 + * A payload as `link` prints it on stdout: indented by two spaces, without a trailing newline,
162 + * since `ui.output` adds one. Key order is part of the output.
163 + */
164 +const toStdoutJson = (payload: object) => JSON.stringify(payload, null, 2);
165 +
166 +/** The `--no-wait` payload: the link to finish by hand. `toolkit` is set by the Tool Router flow. */
167 +export const formatPendingLinkJson = (params: {
168 + readonly target: LinkTarget;
169 + readonly toolkit: Option.Option<string>;
170 + readonly projectType: CliProjectType;
171 +}) =>
172 + toStdoutJson({
173 + status: 'pending',
174 + message: 'Complete authorization by opening the URL',
175 + connected_account_id: params.target.connectedAccountId,
176 + redirect_url: params.target.redirectUrl,
177 + ...Option.match(params.toolkit, { onNone: () => ({}), onSome: toolkit => ({ toolkit }) }),
178 + project_type: params.projectType,
179 + });
180 +
181 +/** The payload once the account is `ACTIVE`. */
182 +export const formatActiveLinkJson = (params: {
183 + readonly account: { readonly id: string; readonly toolkit: { readonly slug: string } };
184 + readonly redirectUrl: string;
185 +}) =>
186 + toStdoutJson({
187 + status: 'success',
188 + message: activeConnectionMessage(params.account),
189 + connected_account_id: params.account.id,
190 + toolkit: params.account.toolkit.slug,
191 + redirect_url: params.redirectUrl,
192 + });
193 +
194 +/**
195 + * The `--list` payload: the toolkit's active accounts, schema-filtered upstream. The empty case
196 + * lists `items` before `total`, the other case after.
197 + */
198 +export const formatConnectedAccountsListJson = (
199 + toolkitSlug: string,
200 + items: ReadonlyArray<ConnectedAccountItem>
201 +) =>
202 + toStdoutJson(
203 + Arr.match(items, {
204 + onEmpty: () => ({ toolkit: toolkitSlug, items: [], total: 0 }),
205 + onNonEmpty: accounts => ({ toolkit: toolkitSlug, total: accounts.length, items: accounts }),
206 + })
207 + );
ts/packages/cli/src/commands/connected-accounts/link/connected-accounts.link.handler.ts
+524 -679
@@ -1,4 +1,4 @@
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,13 +17,12 @@ import { ProjectContext } from 'src/services/project-context';
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,
@@ -37,7 +36,34 @@ import {
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>;
@@ -47,211 +73,51 @@ export type ConnectedAccountsLinkParams = {
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;
@@ -269,213 +135,299 @@ const listActiveConnectedAccounts = (params: {
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 },
@@ -498,146 +450,110 @@ const handleListConnectedAccounts = (params: {
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 )
@@ -645,195 +561,103 @@ const handleLegacyAuthConfigLink = (params: {
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(
@@ -847,81 +671,102 @@ export const runConnectedAccountsLink = (params: ConnectedAccountsLinkParams) =>
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 });
ts/packages/cli/test/src/commands/connected-accounts/link/connected-accounts.link.cmd.test.ts
+1 -1
@@ -444,7 +444,7 @@ describe('CLI: composio dev connected-accounts link', () => {
444
445 expect(lines).toEqual([
446 'Linking gmail...',
447 - 'The API returned an incomplete link response (missing connected_account_id or redirect_url).',
447 + 'The link response from the API is missing `connected_account_id` or `redirect_url`.',
448 ]);
449 })
450 );
ts/packages/cli/test/src/commands/connected-accounts/link/connected-accounts.link.format.test.ts new
+24
@@ -0,0 +1,24 @@
1 +import { describe, expect, it } from 'vitest';
2 +import { dashboardConnectUrl } from 'src/commands/connected-accounts/link/connected-accounts.link.format';
3 +
4 +// The dashboard URL is built from user-controlled segments (the org name comes from the
5 +// session info, the toolkit slug from argv), so the path segments must stay encoded.
6 +describe('connected-accounts link format: dashboardConnectUrl', () => {
7 + it('encodes spaces in the org name and a plain toolkit slug', () => {
8 + expect(dashboardConnectUrl('https://app.composio.dev', 'Acme Inc', 'gmail')).toBe(
9 + 'https://app.composio.dev/Acme%20Inc/~/connect/apps/gmail?open=true'
10 + );
11 + });
12 +
13 + it('encodes `@` and strips the web URL’s trailing slash', () => {
14 + expect(dashboardConnectUrl('https://app.composio.dev/', 'ops@example.com', 'notion')).toBe(
15 + 'https://app.composio.dev/ops%40example.com/~/connect/apps/notion?open=true'
16 + );
17 + });
18 +
19 + it('keeps a subpath base URL and an already-plain org placeholder', () => {
20 + expect(dashboardConnectUrl('https://app.composio.dev/eu', '~', 'linear')).toBe(
21 + 'https://app.composio.dev/eu/~/~/connect/apps/linear?open=true'
22 + );
23 + });
24 +});
ts/packages/cli/test/src/commands/connected-accounts/link/connected-accounts.link.handler.test.ts new
+892
@@ -0,0 +1,892 @@
1 +import { make, type ComposioClientShape } from '@composio/client/effect';
2 +import * as BunFileSystem from '@effect/platform-bun/BunFileSystem';
3 +import * as BunPath from '@effect/platform-bun/BunPath';
4 +import { describe, expect, it } from '@effect/vitest';
5 +import { ConfigProvider, Console, Effect, Fiber, Layer, Option } from 'effect';
6 +import { HttpClient } from 'effect/http';
7 +import { TestClock } from 'effect/testing';
8 +import * as tempy from 'tempy';
9 +import {
10 + handleLegacyAuthConfigLink,
11 + handleListConnectedAccounts,
12 + handleToolRouterLink,
13 + runConnectedAccountsLink,
14 + type ConnectedAccountsLinkParams,
15 +} from 'src/commands/connected-accounts/link/connected-accounts.link.handler';
16 +import {
17 + AUTH_CONFIG_SCOPE_MESSAGE,
18 + BROWSE_AUTH_CONFIGS_HINT,
19 + BROWSE_TOOLKITS_HINT,
20 + LIST_REQUIRES_TOOLKIT_MESSAGE,
21 + LIST_WITH_AUTH_CONFIG_MESSAGE,
22 + ROOT_AUTH_CONFIG_MESSAGE,
23 + TOOLKIT_AND_AUTH_CONFIG_MESSAGE,
24 + missingArgumentMessage,
25 +} from 'src/commands/connected-accounts/link/connected-accounts.link.format';
26 +import { CommandSurface } from 'src/commands/surface';
27 +import { CliUserConfig } from 'src/models/cli-user-config';
28 +import type { ConnectedAccountItem } from 'src/models/connected-accounts';
29 +import type { ProjectKeys } from 'src/models/project-keys';
30 +import { ComposioCliUserConfig } from 'src/services/cli-user-config';
31 +import { ComposioClientSingleton } from 'src/services/composio-clients';
32 +import { NodeOs } from 'src/services/node-os';
33 +import { NodeProcess } from 'src/services/node-process';
34 +import { ProjectContext } from 'src/services/project-context';
35 +import { ComposioUserContext } from 'src/services/user-context';
36 +import { ConnectedAccountsTest, MockConsole } from 'test/__utils__';
37 +import { mockAccountResources, type MockRequestScope } from 'test/__utils__/layers/accounts';
38 +import {
39 + mockConnectedAccountResources,
40 + resolveConnectedAccountsTestData,
41 +} from 'test/__utils__/layers/connected-accounts';
42 +import { hostOnlyEnvConfigProvider } from 'test/__utils__/live-env-config-provider';
43 +import { makeOrgProject } from 'test/__utils__/models/account';
44 +import { TerminalUITest } from 'test/__utils__/services/terminal-ui-test';
45 +import open from 'open';
46 +import { afterEach, vi } from 'vitest';
47 +
48 +vi.mock('open', () => ({
49 + default: vi.fn(async () => undefined),
50 +}));
51 +
52 +afterEach(() => {
53 + vi.clearAllMocks();
54 +});
55 +
56 +// The consumer project the mock client resolves for `org_test`, and its user.
57 +const CONSUMER_USER_ID = 'consumer-user-org_test';
58 +const DEVELOPER_PROJECT = makeOrgProject({ id: 'proj_named', name: 'named', orgId: 'org_test' });
59 +
60 +const account = (overrides: Partial<ConnectedAccountItem> = {}): ConnectedAccountItem => ({
61 + id: 'con_existing',
62 + // `word_id` precedes `alias` to match the model's field order, which is the order the
63 + // decoded items carry into the `--list` payload asserted as a raw string below.
64 + word_id: 'castle',
65 + alias: null,
66 + status: 'ACTIVE',
67 + status_reason: null,
68 + is_disabled: false,
69 + user_id: CONSUMER_USER_ID,
70 + toolkit: { slug: 'gmail' },
71 + auth_config: {
72 + id: 'ac_gmail',
73 + auth_scheme: 'OAUTH2',
74 + is_composio_managed: true,
75 + is_disabled: false,
76 + },
77 + created_at: '2026-01-01T00:00:00Z',
78 + updated_at: '2026-01-01T00:00:00Z',
79 + test_request_endpoint: '',
80 + ...overrides,
81 +});
82 +
83 +const directory = (testUserId: Option.Option<string>): Option.Option<ProjectKeys> =>
84 + Option.some({
85 + orgId: 'org_test',
86 + projectId: 'proj_directory',
87 + projectName: Option.some('directory'),
88 + orgName: Option.none(),
89 + email: Option.none(),
90 + testUserId,
91 + });
92 +
93 +const params = (
94 + overrides: Partial<ConnectedAccountsLinkParams> = {}
95 +): ConnectedAccountsLinkParams => ({
96 + toolkit: Option.none(),
97 + authConfig: Option.none(),
98 + noWait: true,
99 + noBrowser: true,
100 + alias: Option.none(),
101 + list: false,
102 + ...overrides,
103 +});
104 +
105 +interface LinkFixture {
106 + readonly surface?: Layer.Layer<CommandSurface>;
107 + readonly accounts?: ReadonlyArray<ConnectedAccountItem>;
108 + readonly directoryProject?: Option.Option<ProjectKeys>;
109 + readonly globalTestUserId?: Option.Option<string>;
110 + /** Replaces the `link.create` answer, e.g. to fail it. */
111 + readonly legacyLinkCreate?: () => Effect.Effect<unknown, unknown>;
112 + /** Replaces the `toolRouter.session.link` answer, e.g. to fail it or drop a field. */
113 + readonly toolRouterLink?: () => Effect.Effect<unknown, unknown>;
114 + /** Makes `connectedAccounts.list` fail, to prove the alias-hints fetch is auxiliary. */
115 + readonly connectedAccountsListFails?: boolean;
116 + /** Makes the first N `connectedAccounts.retrieve` calls fail, for the polling retries. */
117 + readonly retrieveFailsFirst?: number;
118 +}
119 +
120 +/** A request that creates a link, as the mock client saw it. */
121 +interface LinkRequest {
122 + readonly operation: 'link.create' | 'toolRouter.session.link';
123 + readonly params: unknown;
124 +}
125 +
126 +// A resource neither layer below shadows reaches this transport and dies with its URL.
127 +const baseClient = make(
128 + {
129 + apiKey: 'test',
130 + userApiKey: null,
131 + orgApiKey: null,
132 + baseURL: 'https://mock.invalid',
133 + deprecationNotices: 'off',
134 + },
135 + HttpClient.make(request =>
136 + Effect.die(new Error(`unexpected network call from the link handler test: ${request.url}`))
137 + )
138 +);
139 +
140 +const cliUserConfig = ComposioCliUserConfig.of({
141 + data: {
142 + channel: 'beta',
143 + developerModeEnabled: true,
144 + developerDangerousCommandsEnabled: false,
145 + experimentalFeatures: {},
146 + artifactDirectory: undefined,
147 + security: 'auto',
148 + },
149 + raw: CliUserConfig.make({
150 + developer: { enabled: true, destructiveActions: false },
151 + experimentalFeatures: {},
152 + artifactDirectory: Option.none(),
153 + security: 'auto',
154 + }),
155 + channel: 'beta',
156 + isDevModeEnabled: () => true,
157 + areDeveloperDangerousCommandsEnabled: () => false,
158 + isExperimentalFeatureEnabled: () => true,
159 + update: () => Effect.void,
160 +});
161 +
162 +/**
163 + * What a link handler needs and nothing more: the account and connected-account families of
164 + * the mock client (`test/__utils__/layers`), a Tool Router session that answers, and doubles
165 + * for the user, the directory, and the platform. `requests` records every link request.
166 + */
167 +const linkHandlerTest = (fixture: LinkFixture = {}) => {
168 + const requests: Array<LinkRequest> = [];
169 + const connectedAccounts = mockConnectedAccountResources(
170 + resolveConnectedAccountsTestData({ items: [...(fixture.accounts ?? [])] })
171 + );
172 + let retrieveAttempts = 0;
173 + const connectedAccountsResources = {
174 + ...connectedAccounts,
175 + connectedAccounts: {
176 + ...connectedAccounts.connectedAccounts,
177 + list: fixture.connectedAccountsListFails
178 + ? () => Effect.fail(new Error('connectedAccounts.list is down'))
179 + : connectedAccounts.connectedAccounts.list,
180 + retrieve: (nanoid: string) => {
181 + retrieveAttempts += 1;
182 + return retrieveAttempts <= (fixture.retrieveFailsFirst ?? 0)
183 + ? Effect.fail(new Error(`transient retrieve failure ${retrieveAttempts}`))
184 + : connectedAccounts.connectedAccounts.retrieve(nanoid);
185 + },
186 + },
187 + };
188 + const record = (operation: LinkRequest['operation'], requestParams: unknown) =>
189 + Effect.sync(() => requests.push({ operation, params: requestParams }));
190 + const clientFor = (scope: MockRequestScope): ComposioClientShape =>
191 + // The shadows answer only the fields the handlers read, so they do not satisfy the
192 + // client's full response types; `test-layer.ts` shadows its mock client the same way.
193 + ({
194 + ...baseClient,
195 + ...mockAccountResources({ projects: [DEVELOPER_PROJECT] }, scope),
196 + ...connectedAccountsResources,
197 + link: {
198 + create: (linkParams: { auth_config_id: string; user_id: string }) =>
199 + record('link.create', linkParams).pipe(
200 + Effect.andThen(
201 + fixture.legacyLinkCreate
202 + ? fixture.legacyLinkCreate()
203 + : connectedAccounts.link.create(linkParams)
204 + )
205 + ),
206 + },
207 + toolRouter: {
208 + ...baseClient.toolRouter,
209 + session: {
210 + ...baseClient.toolRouter.session,
211 + create: () => Effect.succeed({ session_id: 'trs_handler_test' }),
212 + link: (sessionId: string, linkParams: { toolkit: string; alias?: string }) =>
213 + record('toolRouter.session.link', { sessionId, ...linkParams }).pipe(
214 + Effect.andThen(
215 + fixture.toolRouterLink
216 + ? fixture.toolRouterLink()
217 + : Effect.succeed({
218 + connected_account_id: 'con_new',
219 + link_token: 'lt_test',
220 + redirect_url: 'https://app.composio.dev/link?token=lt_test',
221 + })
222 + )
223 + ),
224 + },
225 + },
226 + }) as unknown as ComposioClientShape;
227 +
228 + const dir = tempy.temporaryDirectory({ prefix: 'link-handler' });
229 + const layer = Layer.mergeAll(
230 + Layer.effect(Console.Console, MockConsole.make),
231 + TerminalUITest,
232 + fixture.surface ?? CommandSurface.root,
233 + Layer.succeed(
234 + ComposioUserContext,
235 + ComposioUserContext.of({
236 + data: {
237 + apiKey: Option.some('uak_test'),
238 + baseURL: 'https://mock.invalid',
239 + webURL: 'https://platform.mock.invalid',
240 + orgId: Option.some('org_test'),
241 + projectId: Option.none(),
242 + testUserId: fixture.globalTestUserId ?? Option.none(),
243 + },
244 + isLoggedIn: () => true,
245 + logout: Effect.void,
246 + login: () => Effect.void,
247 + update: () => Effect.void,
248 + })
249 + ),
250 + Layer.succeed(
251 + ProjectContext,
252 + ProjectContext.of({ resolve: Effect.succeed(fixture.directoryProject ?? Option.none()) })
253 + ),
254 + Layer.succeed(
255 + ComposioClientSingleton,
256 + ComposioClientSingleton.of({
257 + get: () => Effect.succeed(clientFor({})),
258 + getFor: (scope: MockRequestScope) => Effect.succeed(clientFor(scope)),
259 + getMetrics: () => Effect.succeed({ byteSize: 0, requests: 0 }),
260 + })
261 + ),
262 + ConnectedAccountsTest(),
263 + BunFileSystem.layer,
264 + BunPath.layer,
265 + Layer.succeed(
266 + NodeOs,
267 + NodeOs.of({ homedir: dir, tmpdir: dir, arch: 'arm64', platform: 'darwin' })
268 + ),
269 + Layer.succeed(
270 + NodeProcess,
271 + NodeProcess.of({
272 + cwd: dir,
273 + execPath: `${dir}/composio`,
274 + platform: 'darwin',
275 + arch: 'arm64',
276 + setExitCode: () => Effect.void,
277 + })
278 + ),
279 + Layer.succeed(ComposioCliUserConfig, cliUserConfig),
280 + ConfigProvider.layer(hostOnlyEnvConfigProvider)
281 + );
282 + return { layer, requests };
283 +};
284 +
285 +const lines = MockConsole.getLines({ stripAnsi: true });
286 +
287 +/** The command's JSON result: `ui.output` prints it as the last console line. */
288 +const lastJson = lines.pipe(Effect.map(all => JSON.parse(String(all.at(-1))) as unknown));
289 +
290 +/** The payload as `link` prints it: a `toStdoutJson` string, key order included. */
291 +const toJson = (payload: object) => JSON.stringify(payload, null, 2);
292 +
293 +/** The `link.create` answer of the mock connected-account resources. */
294 +const LEGACY_LINK_TARGET = {
295 + connected_account_id: 'con_test_link',
296 + redirect_url: 'https://app.composio.dev/link?token=lt_test_token',
297 +} as const;
298 +
299 +/** The `toolRouter.session.link` answer of the handler test's client double. */
300 +const TOOL_ROUTER_LINK_TARGET = {
301 + connected_account_id: 'con_new',
302 + redirect_url: 'https://app.composio.dev/link?token=lt_test',
303 +} as const;
304 +
305 +/** The pending payload of a legacy link, byte for byte. */
306 +const legacyPendingJson = () =>
307 + toJson({
308 + status: 'pending',
309 + message: 'Complete authorization by opening the URL',
310 + connected_account_id: LEGACY_LINK_TARGET.connected_account_id,
311 + redirect_url: LEGACY_LINK_TARGET.redirect_url,
312 + project_type: 'DEVELOPER',
313 + });
314 +
315 +/** The pending payload of a Tool Router link, byte for byte. */
316 +const toolRouterPendingJson = () =>
317 + toJson({
318 + status: 'pending',
319 + message: 'Complete authorization by opening the URL',
320 + connected_account_id: TOOL_ROUTER_LINK_TARGET.connected_account_id,
321 + redirect_url: TOOL_ROUTER_LINK_TARGET.redirect_url,
322 + toolkit: 'gmail',
323 + project_type: 'CONSUMER',
324 + });
325 +
326 +/** The payload once polling saw `con_new` ACTIVE, byte for byte. */
327 +const toolRouterActiveJson = () =>
328 + toJson({
329 + status: 'success',
330 + message: 'Connected account "con_new" is now ACTIVE (toolkit: gmail).',
331 + connected_account_id: 'con_new',
332 + toolkit: 'gmail',
333 + redirect_url: TOOL_ROUTER_LINK_TARGET.redirect_url,
334 + });
335 +
336 +/**
337 + * Runs an effect whose context is already provided on the test clock, with a pump fiber that
338 + * keeps advancing the clock while it runs: every pump iteration lets the effect reach its next
339 + * scheduled sleep, then moves the clock past it. Answers what the effect answered once done.
340 + */
341 +const runWithAdvancingClock = <A, E>(effect: Effect.Effect<A, E>) =>
342 + Effect.gen(function* () {
343 + const run = yield* Effect.forkChild(effect);
344 + const pump = yield* Effect.forkChild(
345 + Effect.forever(Effect.andThen(Effect.yieldNow, () => TestClock.adjust('10 seconds')))
346 + );
347 + const result = yield* Fiber.join(run);
348 + yield* Fiber.interrupt(pump);
349 + return result;
350 + });
351 +
352 +const devSurface = (flags: { userId?: string; projectName?: string } = {}) =>
353 + CommandSurface.dev({
354 + userId: Option.fromUndefinedOr(flags.userId),
355 + projectName: Option.fromUndefinedOr(flags.projectName),
356 + });
357 +
358 +describe('connected-accounts link handler: runConnectedAccountsLink', () => {
359 + it.effect.each([
360 + {
361 + name: 'a blank --alias, before any other check',
362 + surface: CommandSurface.root,
363 + input: { alias: Option.some(' '), authConfig: Option.some('ac_1') },
364 + option: '--alias',
365 + message: '`--alias` cannot be empty.',
366 + },
367 + {
368 + name: '--auth-config on the root tree, which is consumer-only',
369 + surface: CommandSurface.root,
370 + input: { toolkit: Option.some('gmail'), authConfig: Option.some('ac_1') },
371 + option: '--auth-config',
372 + message: ROOT_AUTH_CONFIG_MESSAGE,
373 + },
374 + ])('[Given] $name [Then] fails with a CommandInputError and sends nothing', c =>
375 + Effect.gen(function* () {
376 + const { layer, requests } = linkHandlerTest({ surface: c.surface });
377 + const error = yield* runConnectedAccountsLink(params(c.input)).pipe(
378 + Effect.flip,
379 + Effect.provide(layer)
380 + );
381 +
382 + expect(error).toMatchObject({
383 + _tag: 'commands/CommandInputError',
384 + command: 'link',
385 + option: c.option,
386 + message: c.message,
387 + });
388 + expect(requests).toEqual([]);
389 + })
390 + );
391 +
392 + it.effect.each([
393 + {
394 + name: 'a toolkit and --auth-config under dev',
395 + surface: devSurface(),
396 + input: { toolkit: Option.some('gmail'), authConfig: Option.some('ac_1') },
397 + message: TOOLKIT_AND_AUTH_CONFIG_MESSAGE,
398 + },
399 + {
400 + name: 'neither a toolkit nor --auth-config on the root tree',
401 + surface: CommandSurface.root,
402 + input: {},
403 + message: missingArgumentMessage('root'),
404 + },
405 + {
406 + name: 'neither a toolkit nor --auth-config under dev',
407 + surface: devSurface(),
408 + input: {},
409 + message: missingArgumentMessage('dev'),
410 + },
411 + ])('[Given] $name [Then] prints the usage message and exits 0', c =>
412 + Effect.gen(function* () {
413 + const { layer, requests } = linkHandlerTest({ surface: c.surface });
414 + const output = yield* runConnectedAccountsLink(params(c.input)).pipe(
415 + Effect.andThen(lines),
416 + Effect.provide(layer)
417 + );
418 +
419 + expect(output).toEqual([c.message]);
420 + expect(requests).toEqual([]);
421 + })
422 + );
423 +
424 + it.effect.each([
425 + { flow: 'list', input: { toolkit: Option.some('gmail'), list: true } },
426 + { flow: 'legacy', input: { authConfig: Option.some('ac_gmail') } },
427 + { flow: 'tool-router', input: { toolkit: Option.some('gmail') } },
428 + ])('[Given] the flags select the $flow flow [Then] it runs that flow', c =>
429 + Effect.gen(function* () {
430 + const fixtureAccount = account({ alias: 'work' });
431 + const { layer } = linkHandlerTest({
432 + surface: devSurface({ userId: 'user_1' }),
433 + accounts: [fixtureAccount],
434 + directoryProject: directory(Option.none()),
435 + });
436 + const lastLine = yield* runConnectedAccountsLink(
437 + params({ ...c.input, alias: Option.some('second') })
438 + ).pipe(
439 + Effect.andThen(lines),
440 + Effect.map(all => String(all.at(-1))),
441 + Effect.provide(layer)
442 + );
443 +
444 + // The raw string, not JSON.parse, so a key reorder fails here.
445 + expect(lastLine).toBe(
446 + c.flow === 'list'
447 + ? toJson({ toolkit: 'gmail', total: 1, items: [fixtureAccount] })
448 + : c.flow === 'legacy'
449 + ? legacyPendingJson()
450 + : toolRouterPendingJson()
451 + );
452 + })
453 + );
454 +});
455 +
456 +describe('connected-accounts link handler: handleListConnectedAccounts', () => {
457 + it.effect.each([
458 + {
459 + name: 'no toolkit',
460 + input: { list: true, authConfig: Option.some('ac_1') },
461 + message: LIST_REQUIRES_TOOLKIT_MESSAGE,
462 + },
463 + {
464 + name: '--auth-config',
465 + input: { list: true, toolkit: Option.some('gmail'), authConfig: Option.some('ac_1') },
466 + message: LIST_WITH_AUTH_CONFIG_MESSAGE,
467 + },
468 + ])('[Given] $name [Then] prints why --list cannot run', c =>
469 + Effect.gen(function* () {
470 + const { layer } = linkHandlerTest();
471 + const output = yield* handleListConnectedAccounts(params(c.input)).pipe(
472 + Effect.andThen(lines),
473 + Effect.provide(layer)
474 + );
475 +
476 + expect(output).toEqual([c.message]);
477 + })
478 + );
479 +
480 + it.effect('[Given] the consumer project [Then] lists only its user’s active accounts', () =>
481 + Effect.gen(function* () {
482 + const mine = account();
483 + const { layer } = linkHandlerTest({
484 + accounts: [
485 + mine,
486 + account({ id: 'con_other_user', user_id: 'someone-else' }),
487 + account({ id: 'con_inactive', status: 'INITIATED' }),
488 + account({ id: 'con_other_toolkit', toolkit: { slug: 'slack' } }),
489 + ],
490 + });
491 + const result = yield* handleListConnectedAccounts(
492 + params({ toolkit: Option.some('gmail'), list: true })
493 + ).pipe(Effect.andThen(lastJson), Effect.provide(layer));
494 +
495 + expect(result).toStrictEqual({ toolkit: 'gmail', total: 1, items: [mine] });
496 + })
497 + );
498 +
499 + it.effect('[Given] no active account [Then] warns and prints an empty list', () =>
500 + Effect.gen(function* () {
501 + const { layer } = linkHandlerTest();
502 + const output = yield* handleListConnectedAccounts(
503 + params({ toolkit: Option.some('gmail'), list: true })
504 + ).pipe(Effect.andThen(lines), Effect.provide(layer));
505 +
506 + expect(output.at(-2)).toBe('No active connected accounts found for "gmail".');
507 + // The empty case lists `items` before `total`; this pins that order.
508 + expect(String(output.at(-1))).toBe(toJson({ toolkit: 'gmail', items: [], total: 0 }));
509 + })
510 + );
511 +
512 + it.effect.each([
513 + {
514 + name: '--user-id',
515 + surface: devSurface({ projectName: 'named', userId: 'user_flag' }),
516 + directoryProject: directory(Option.some('user_directory')),
517 + expectedUser: 'user_flag',
518 + },
519 + {
520 + name: 'the directory’s test user, for the directory’s own project',
521 + surface: devSurface({ projectName: 'named' }),
522 + directoryProject: Option.map(directory(Option.some('user_directory')), keys => ({
523 + ...keys,
524 + projectId: DEVELOPER_PROJECT.id,
525 + })),
526 + expectedUser: 'user_directory',
527 + },
528 + {
529 + name: 'the global test user, for a project other than the directory’s',
530 + surface: devSurface({ projectName: 'named' }),
531 + directoryProject: directory(Option.some('user_directory')),
532 + expectedUser: 'user_global',
533 + },
534 + ])('[Given] dev --project-name and $name [Then] lists that user’s accounts', c =>
535 + Effect.gen(function* () {
536 + const { layer } = linkHandlerTest({
537 + surface: c.surface,
538 + directoryProject: c.directoryProject,
539 + globalTestUserId: Option.some('user_global'),
540 + accounts: ['user_flag', 'user_directory', 'user_global'].map(userId =>
541 + account({ id: `con_${userId}`, user_id: userId })
542 + ),
543 + });
544 + const result = yield* handleListConnectedAccounts(
545 + params({ toolkit: Option.some('gmail'), list: true })
546 + ).pipe(Effect.andThen(lastJson), Effect.provide(layer));
547 +
548 + expect(result).toMatchObject({ total: 1, items: [{ user_id: c.expectedUser }] });
549 + })
550 + );
551 +
552 + it.effect('[Given] the list request fails [Then] fails with the request error', () =>
553 + Effect.gen(function* () {
554 + const { layer } = linkHandlerTest({ connectedAccountsListFails: true });
555 + const error = yield* handleListConnectedAccounts(
556 + params({ toolkit: Option.some('gmail'), list: true })
557 + ).pipe(Effect.flip, Effect.provide(layer));
558 +
559 + expect(error).toMatchObject({
560 + _tag: 'commands/ConnectedAccountsRequestError',
561 + message: 'Failed to list connected accounts for "gmail".',
562 + });
563 + })
564 + );
565 +
566 + it.effect(
567 + '[Given] dev --project-name and no user anywhere [Then] fails pointing at --user-id',
568 + () =>
569 + Effect.gen(function* () {
570 + const { layer } = linkHandlerTest({ surface: devSurface({ projectName: 'named' }) });
571 + const error = yield* handleListConnectedAccounts(
572 + params({ toolkit: Option.some('gmail'), list: true })
573 + ).pipe(Effect.flip, Effect.provide(layer));
574 +
575 + expect(error).toMatchObject({
576 + _tag: 'commands/MissingLinkUserIdError',
577 + flow: 'list',
578 + message:
579 + 'Missing user id. Provide --user-id, or run `composio login` to store a global test user id.',
580 + });
581 + })
582 + );
583 +});
584 +
585 +describe('connected-accounts link handler: handleLegacyAuthConfigLink', () => {
586 + it.effect(
587 + '[Given] the directory’s test user [Then] links it in the directory’s project and prints the pending link',
588 + () =>
589 + Effect.gen(function* () {
590 + const { layer, requests } = linkHandlerTest({
591 + surface: devSurface(),
592 + directoryProject: directory(Option.some('user_directory')),
593 + });
594 + const output = yield* handleLegacyAuthConfigLink(
595 + params({ authConfig: Option.some('ac_gmail') })
596 + ).pipe(Effect.andThen(lines), Effect.provide(layer));
597 +
598 + expect(output[0]).toBe('Using test user id "user_directory"');
599 + expect(requests).toEqual([
600 + {
601 + operation: 'link.create',
602 + params: { auth_config_id: 'ac_gmail', user_id: 'user_directory' },
603 + },
604 + ]);
605 + expect(String(output.at(-1))).toBe(legacyPendingJson());
606 + })
607 + );
608 +
609 + it.effect('[Given] no user anywhere [Then] fails pointing at dev init', () =>
610 + Effect.gen(function* () {
611 + const { layer } = linkHandlerTest({
612 + surface: devSurface(),
613 + directoryProject: directory(Option.none()),
614 + });
615 + const error = yield* handleLegacyAuthConfigLink(
616 + params({ authConfig: Option.some('ac_gmail') })
617 + ).pipe(Effect.flip, Effect.provide(layer));
618 +
619 + expect(error).toMatchObject({
620 + _tag: 'commands/MissingLinkUserIdError',
621 + flow: 'legacy',
622 + message: 'Missing user id. Provide --user-id or run composio dev init to set test_user_id.',
623 + });
624 + })
625 + );
626 +
627 + it.effect('[Given] no developer project [Then] explains the scope and sends nothing', () =>
628 + Effect.gen(function* () {
629 + const { layer, requests } = linkHandlerTest({ surface: devSurface({ userId: 'user_1' }) });
630 + const output = yield* handleLegacyAuthConfigLink(
631 + params({ authConfig: Option.some('ac_gmail') })
632 + ).pipe(Effect.andThen(lines), Effect.provide(layer));
633 +
634 + expect(output).toEqual([AUTH_CONFIG_SCOPE_MESSAGE]);
635 + expect(requests).toEqual([]);
636 + })
637 + );
638 +
639 + it.effect(
640 + '[Given] the link request fails [Then] reports the message and the auth-config hint',
641 + () =>
642 + Effect.gen(function* () {
643 + const { layer, requests } = linkHandlerTest({
644 + surface: devSurface({ userId: 'user_1' }),
645 + directoryProject: directory(Option.none()),
646 + legacyLinkCreate: () => Effect.fail(new Error('quota exhausted')),
647 + });
648 + const output = yield* handleLegacyAuthConfigLink(
649 + params({ authConfig: Option.some('ac_gmail') })
650 + ).pipe(Effect.andThen(lines), Effect.provide(layer));
651 +
652 + expect(output).toEqual(['quota exhausted', BROWSE_AUTH_CONFIGS_HINT]);
653 + expect(requests).toEqual([
654 + {
655 + operation: 'link.create',
656 + params: { auth_config_id: 'ac_gmail', user_id: 'user_1' },
657 + },
658 + ]);
659 + })
660 + );
661 +
662 + it.effect(
663 + '[Given] an alias already in use [Then] points at the dev commands and sends nothing',
664 + () =>
665 + Effect.gen(function* () {
666 + const { layer, requests } = linkHandlerTest({
667 + surface: devSurface({ userId: 'user_1' }),
668 + directoryProject: directory(Option.none()),
669 + accounts: [account({ user_id: 'user_1', alias: 'Work' })],
670 + });
671 + const output = yield* handleLegacyAuthConfigLink(
672 + params({ authConfig: Option.some('ac_gmail'), alias: Option.some(' work ') })
673 + ).pipe(Effect.andThen(lines), Effect.provide(layer));
674 +
675 + expect(output).toEqual([
676 + 'Alias "work" is already in use by connected account "con_existing".',
677 + "[Tips] Use the existing alias: composio dev playground-execute <TOOL_SLUG> --account work -d '{ ... }'\nList connected accounts: composio dev connected-accounts list",
678 + ]);
679 + expect(requests).toEqual([]);
680 + })
681 + );
682 +});
683 +
684 +describe('connected-accounts link handler: handleToolRouterLink', () => {
685 + it.effect(
686 + '[Given] the consumer project and --alias [Then] links with the alias and prints the pending link',
687 + () =>
688 + Effect.gen(function* () {
689 + const { layer, requests } = linkHandlerTest({ accounts: [account()] });
690 + const output = yield* handleToolRouterLink(
691 + params({ toolkit: Option.some('gmail'), alias: Option.some(' work ') })
692 + ).pipe(Effect.andThen(lines), Effect.provide(layer));
693 +
694 + expect(requests).toEqual([
695 + {
696 + operation: 'toolRouter.session.link',
697 + params: { sessionId: 'trs_handler_test', toolkit: 'gmail', alias: 'work' },
698 + },
699 + ]);
700 + expect(String(output.at(-1))).toBe(toolRouterPendingJson());
701 + })
702 + );
703 +
704 + it.effect(
705 + '[Given] no --no-wait [Then] polls the account to ACTIVE and prints the active payload',
706 + () =>
707 + Effect.gen(function* () {
708 + // `retrieve('con_new')` answers from the fixture, so polling succeeds on its first try.
709 + const { layer } = linkHandlerTest({
710 + accounts: [
711 + account({ id: 'con_new', user_id: 'poll-source', alias: null, word_id: null }),
712 + ],
713 + });
714 + const output = yield* handleToolRouterLink(
715 + params({ toolkit: Option.some('gmail'), noWait: false })
716 + ).pipe(Effect.andThen(lines), Effect.provide(layer));
717 +
718 + expect(output).toContain('Connection successful');
719 + expect(String(output.at(-1))).toBe(toolRouterActiveJson());
720 + })
721 + );
722 +
723 + it.effect(
724 + '[Given] the link returns the existing account [Then] no --alias is needed to reuse it',
725 + () =>
726 + Effect.gen(function* () {
727 + // The fixture account is both the hints entry and the link answer, so the
728 + // additional-account guard lets the same account through.
729 + const { layer } = linkHandlerTest({ accounts: [account({ id: 'con_new' })] });
730 + const lastLine = yield* handleToolRouterLink(
731 + params({ toolkit: Option.some('gmail') })
732 + ).pipe(
733 + Effect.andThen(lines),
734 + Effect.map(all => String(all.at(-1))),
735 + Effect.provide(layer)
736 + );
737 +
738 + expect(lastLine).toBe(toolRouterPendingJson());
739 + })
740 + );
741 +
742 + it.effect('[Given] the alias-hints list request fails [Then] the link still runs', () =>
743 + Effect.gen(function* () {
744 + const { layer, requests } = linkHandlerTest({ connectedAccountsListFails: true });
745 + const lastLine = yield* handleToolRouterLink(params({ toolkit: Option.some('gmail') })).pipe(
746 + Effect.andThen(lines),
747 + Effect.map(all => String(all.at(-1))),
748 + Effect.provide(layer)
749 + );
750 +
751 + expect(requests).toEqual([
752 + {
753 + operation: 'toolRouter.session.link',
754 + params: { sessionId: 'trs_handler_test', toolkit: 'gmail' },
755 + },
756 + ]);
757 + expect(lastLine).toBe(toolRouterPendingJson());
758 + })
759 + );
760 +
761 + it.effect('[Given] the link request fails [Then] reports the cause and the browse hint', () =>
762 + Effect.gen(function* () {
763 + const { layer } = linkHandlerTest({
764 + toolRouterLink: () => Effect.fail(new Error('offline')),
765 + });
766 + const output = yield* handleToolRouterLink(params({ toolkit: Option.some('gmail') })).pipe(
767 + Effect.andThen(lines),
768 + Effect.provide(layer)
769 + );
770 +
771 + // `failedWith` keeps the client error in `.cause`, and the message prefers it.
772 + expect(output).toEqual(['offline', BROWSE_TOOLKITS_HINT]);
773 + })
774 + );
775 +
776 + it.effect('[Given] a redirect URL without an http scheme [Then] warns and still waits', () =>
777 + Effect.gen(function* () {
778 + const { layer } = linkHandlerTest({
779 + accounts: [account({ id: 'con_new', user_id: 'poll-source', alias: null, word_id: null })],
780 + toolRouterLink: () =>
781 + Effect.succeed({ connected_account_id: 'con_new', redirect_url: 'notaurl' }),
782 + });
783 + const output = yield* handleToolRouterLink(
784 + params({ toolkit: Option.some('gmail'), noWait: false })
785 + ).pipe(Effect.andThen(lines), Effect.provide(layer));
786 +
787 + expect(output).toEqual([
788 + 'Linking gmail...',
789 + 'Open this URL in your browser to authorize',
790 + '[Redirect URL] notaurl',
791 + 'Redirect URL has an unexpected scheme: notaurl',
792 + 'Open the URL manually if you trust the source.',
793 + 'Connection successful',
794 + 'Connected account "con_new" is now ACTIVE (toolkit: gmail).',
795 + toJson({
796 + status: 'success',
797 + message: 'Connected account "con_new" is now ACTIVE (toolkit: gmail).',
798 + connected_account_id: 'con_new',
799 + toolkit: 'gmail',
800 + redirect_url: 'notaurl',
801 + }),
802 + ]);
803 + expect(vi.mocked(open)).not.toHaveBeenCalled();
804 + })
805 + );
806 +
807 + it.effect('[Given] the browser fails to open [Then] points at the URL and still waits', () =>
808 + Effect.gen(function* () {
809 + vi.mocked(open).mockRejectedValueOnce(new Error('no browser'));
810 + const { layer } = linkHandlerTest({
811 + accounts: [account({ id: 'con_new', user_id: 'poll-source', alias: null, word_id: null })],
812 + });
813 + const output = yield* handleToolRouterLink(
814 + params({ toolkit: Option.some('gmail'), noWait: false, noBrowser: false })
815 + ).pipe(Effect.andThen(lines), Effect.provide(layer));
816 +
817 + expect(vi.mocked(open)).toHaveBeenCalledWith(TOOL_ROUTER_LINK_TARGET.redirect_url, {
818 + wait: false,
819 + });
820 + expect(output).toEqual([
821 + 'Linking gmail...',
822 + 'Redirecting you to the authorization page',
823 + `[Redirect URL] ${TOOL_ROUTER_LINK_TARGET.redirect_url}`,
824 + 'Could not open the browser automatically.',
825 + 'Open the URL above manually.',
826 + 'Connection successful',
827 + 'Connected account "con_new" is now ACTIVE (toolkit: gmail).',
828 + toolRouterActiveJson(),
829 + ]);
830 + })
831 + );
832 +
833 + it.effect('[Given] one failed poll [Then] retries and still reaches ACTIVE', () =>
834 + Effect.gen(function* () {
835 + const { layer } = linkHandlerTest({
836 + accounts: [account({ id: 'con_new', user_id: 'poll-source', alias: null, word_id: null })],
837 + retrieveFailsFirst: 1,
838 + });
839 + const lastLine = yield* runWithAdvancingClock(
840 + handleToolRouterLink(params({ toolkit: Option.some('gmail'), noWait: false })).pipe(
841 + Effect.andThen(lines),
842 + Effect.map(all => String(all.at(-1))),
843 + Effect.provide(layer)
844 + )
845 + );
846 +
847 + expect(lastLine).toBe(toolRouterActiveJson());
848 + })
849 + );
850 +
851 + it.effect('[Given] the account never turns ACTIVE [Then] gives up and reports the timeout', () =>
852 + Effect.gen(function* () {
853 + const { layer } = linkHandlerTest({
854 + accounts: [account({ id: 'con_new', user_id: 'poll-source', status: 'INITIATED' })],
855 + });
856 + const error = yield* runWithAdvancingClock(
857 + Effect.gen(function* () {
858 + const error = yield* Effect.flip(
859 + handleToolRouterLink(params({ toolkit: Option.some('gmail'), noWait: false }))
860 + );
861 + const output = yield* lines;
862 + return { error, output };
863 + }).pipe(Effect.provide(layer))
864 + );
865 +
866 + expect(error.error).toMatchObject({
867 + _tag: 'commands/ConnectionPollingError',
868 + connectedAccountId: 'con_new',
869 + status: 'INITIATED',
870 + });
871 + expect(error.output).not.toContain('Connection successful');
872 + expect(String(error.output.at(-1))).toBe(
873 + 'Timed out waiting for authorization. Run the command again.'
874 + );
875 + })
876 + );
877 +
878 + it.effect('[Given] an active account and no --alias [Then] lists it and prints no link', () =>
879 + Effect.gen(function* () {
880 + const { layer } = linkHandlerTest({ accounts: [account({ alias: 'default' })] });
881 + const output = yield* handleToolRouterLink(params({ toolkit: Option.some('gmail') })).pipe(
882 + Effect.andThen(lines),
883 + Effect.provide(layer)
884 + );
885 +
886 + expect(output.slice(-2)).toEqual([
887 + `A connected account already exists for user "${CONSUMER_USER_ID}" in toolkit "gmail". Pass --alias to create another one.`,
888 + '[Existing accounts] con_existing (default, castle)',
889 + ]);
890 + })
891 + );
892 +});