@devries-cameron20 / composio-1 / commits / 1e0aaaab9
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): prune dead client-layer code and unify request errors (#4855)

This PR: - is rebased onto `next` after https://github.com/ComposioHQ/composio/pull/4853, https://github.com/ComposioHQ/composio/pull/4878 and https://github.com/ComposioHQ/composio/pull/4894 merged; the session-info and trigger-log leniency commits dropped out because `next` already has them, and three commits remain - removes repository methods that lost their last caller when commands started calling the client directly (`listConnectedAccounts`, `deleteAuthConfig`, `deleteConnectedAccount`, `createConnectedAccountLink`, `deleteTrigger`), with their fakes and tests - removes unused JSON helpers, type aliases, tool-definition helpers and unreachable test shadows, and takes the trigger parameter types from the client - adds `requestError(tag)` and `failedWith(Class, message)` in `src/effects/request-error.ts` and uses them for the command errors that wrap a client failure with a fixed message (nine error classes across eight command files) - deletes two wrapper errors that were caught before reaching any output (`commands/ToolkitsListRequestError`, `services/ToolRouterSessionConnectionsError`) and two swallowed uses of `commands/ConnectedAccountsRequestError` - makes the top-level error printer reuse the shared message extraction for decode and connection failures ## Context No error tag or message that can reach stderr changes. Sites whose output had no test got a characterization test first; those tests pass on the parent commit and on this one. Source shrinks by 247 lines (+155 / −402). Tests grow by 272 lines (+440 / −168): 157 lines of dead-code tests go, and 430 lines of characterization and helper tests come in. Two small behavior notes: - With `--log-level debug`, `toolkits list` logs the client error directly on a failed session-toolkits fetch, where it logged the removed wrapper. Default-level output is identical. - In `connected-accounts link`, the auth-config link failure falls back to its fixed message when the extracted message is empty (`||` in place of `??`), which is what the wrapper produced before. Left in place on purpose: `ToolkitsInfoRequestError` and the tool-router link error (their catch sites also see non-client errors, so removing the wrapper is not strictly equivalent), `ListenCommandError` (its messages are computed from the cause and it carries extra fields), and `resolveToolRouterSession`, now a one-line alias of `createToolRouterSessionContext` kept to avoid touching five callers here. Rebase notes: - `test/src/services/composio-client-interrupt.test.ts` (from https://github.com/ComposioHQ/composio/pull/4879) exercised `repository.listConnectedAccounts`, which this PR removes; it now forks `client.connectedAccounts.list` directly and asserts the same abort. - The cross-command suite is `test/src/commands/request-failures.client.test.ts`: the `.cmd.test.ts` suffix is reserved by `validate:command-tests` for suites that map to one command. - Its "misshapen session toolkits" scenario is gone: `next` reads `toolRouter.session.toolkits` leniently since https://github.com/ComposioHQ/composio/pull/4878, so a decode failure can no longer occur there. On `next`, a response without `items` makes `dev toolkits info` fail with a `TypeError` on `items[0]` instead; that is pre-existing and not changed here. - `tools.search.cmd.ts` drops its `Data` import, unused once https://github.com/ComposioHQ/composio/pull/4890 removed `ToolsSearchInputError`. Verified locally after the rebase: `pnpm typecheck`, the CLI suite (152 files, 1525 passed, 1 skipped; `validate:command-tests` still reports 18 exemptions), `oxlint` on every touched file, `validate:boundaries`. The 23 read-only commands compared against the live API before the Effect-client change give the same result as on the parent PR: 22 byte-identical, one differing only in a request id and a stack-trace path.

Alberto Schiabel committed Oct 15, 2026 at 19:52 UTC 1e0aaaab9b185d39ef41a93b06ce170c0e1d0c6b
32 files changed +638 -566
ts/packages/cli/AGENTS.md
+1 -1
@@ -128,7 +128,7 @@ Reusable Effect computations: `require-auth` (`requireLogin`, the login gate for
128
129 ### Models — `src/models/`
130
131 -Effect Schema definitions with `fromJSON` / `toJSON` helpers via `JSONTransformSchema()`: `Toolkit`, `Tool`, `TriggerType`, `UserData`, `Session`.
131 +Effect Schema definitions with `fromJSON` / `toJSON` helpers via `JSONTransformSchema()`: `Toolkit`, `Tool`, `TriggerType`, `UserData`. `Session` is a schema only, decoded from the API.
132
133 ### Code Generation — `src/generation/`
134
ts/packages/cli/src/commands/connected-accounts/commands/connected-accounts.link.cmd.ts
+31 -62
@@ -6,6 +6,7 @@ import type { ComposioClientShape } from '@composio/client/effect';
6 import open from 'open';
7 import { ComposioUserContext } from 'src/services/user-context';
8 import { TerminalUI } from 'src/services/terminal-ui';
9 +import { failedWith, requestError } from 'src/effects/request-error';
10 import { resolveToolRouterSession } from 'src/effects/create-tool-router-session';
11 import { extractApiErrorDetails, extractMessage } from 'src/utils/api-error-extraction';
12 import { ProjectContext } from 'src/services/project-context';
@@ -43,12 +44,9 @@ class ConnectedAccountsDecodeError extends Data.TaggedError(
44 readonly cause: unknown;
45 }> {}
46
46 -class ConnectedAccountsRequestError extends Data.TaggedError(
47 +class ConnectedAccountsRequestError extends requestError(
48 'commands/ConnectedAccountsRequestError'
48 -)<{
49 - readonly message: string;
50 - readonly cause: unknown;
51 -}> {}
49 +) {}
50
51 class BrowserOpenError extends Data.TaggedError('commands/BrowserOpenError')<{
52 readonly message: string;
@@ -158,12 +156,9 @@ const waitForActiveConnection = (
156 const account = yield* client.connectedAccounts
157 .retrieve(connectedAccountId, { decode: false })
158 .pipe(
161 - Effect.mapError(
162 - cause =>
163 - new ConnectedAccountsRequestError({
164 - message: `Failed to fetch connected account "${connectedAccountId}".`,
165 - cause,
166 - })
159 + failedWith(
160 + ConnectedAccountsRequestError,
161 + `Failed to fetch connected account "${connectedAccountId}".`
162 )
163 );
164 if (account.status === 'ACTIVE') {
@@ -313,26 +308,16 @@ const listActiveConnectedAccounts = (params: {
308 readonly toolkitSlug?: string;
309 readonly authConfigId?: string;
310 }) =>
316 - params.client.connectedAccounts
317 - .list(
318 - {
319 - user_ids: [params.userId],
320 - toolkit_slugs: params.toolkitSlug ? [params.toolkitSlug] : undefined,
321 - auth_config_ids: params.authConfigId ? [params.authConfigId] : undefined,
322 - statuses: ['ACTIVE'],
323 - limit: 100,
324 - },
325 - { decode: false }
326 - )
327 - .pipe(
328 - Effect.mapError(
329 - cause =>
330 - new ConnectedAccountsRequestError({
331 - message: `Failed to list connected accounts for user "${params.userId}".`,
332 - cause,
333 - })
334 - )
335 - );
311 + params.client.connectedAccounts.list(
312 + {
313 + user_ids: [params.userId],
314 + toolkit_slugs: params.toolkitSlug ? [params.toolkitSlug] : undefined,
315 + auth_config_ids: params.authConfigId ? [params.authConfigId] : undefined,
316 + statuses: ['ACTIVE'],
317 + limit: 100,
318 + },
319 + { decode: false }
320 + );
321
322 const formatExistingAccountLabels = (
323 items: ReadonlyArray<{
@@ -541,12 +526,9 @@ const handleListConnectedAccounts = (params: {
526 { decode: false }
527 )
528 .pipe(
544 - Effect.mapError(
545 - cause =>
546 - new ConnectedAccountsRequestError({
547 - message: `Failed to list connected accounts for "${toolkitSlug}".`,
548 - cause,
549 - })
529 + failedWith(
530 + ConnectedAccountsRequestError,
531 + `Failed to list connected accounts for "${toolkitSlug}".`
532 )
533 )
534 );
@@ -685,31 +667,21 @@ const handleLegacyAuthConfigLink = (params: {
667 const linkOpt = yield* params.ui
668 .withSpinner(
669 'Creating link session...',
688 - client.link
689 - .create(
690 - {
691 - auth_config_id: params.authConfigId,
692 - user_id: resolvedUserId.value,
693 - ...(Option.isSome(normalizedAlias) && { alias: normalizedAlias.value }),
694 - },
695 - { decode: false }
696 - )
697 - .pipe(
698 - Effect.mapError(
699 - cause =>
700 - new ConnectedAccountsRequestError({
701 - message: `Failed to create link for auth config "${params.authConfigId}".`,
702 - cause,
703 - })
704 - )
705 - )
670 + client.link.create(
671 + {
672 + auth_config_id: params.authConfigId,
673 + user_id: resolvedUserId.value,
674 + ...(Option.isSome(normalizedAlias) && { alias: normalizedAlias.value }),
675 + },
676 + { decode: false }
677 + )
678 )
679 .pipe(
680 Effect.asSome,
681 Effect.catch(error =>
682 Effect.gen(function* () {
683 const message =
712 - extractMessage(error) ??
684 + extractMessage(error) ||
685 `Failed to create link for auth config "${params.authConfigId}".`;
686 yield* params.ui.log.error(message);
687 yield* params.ui.log.step(
@@ -912,12 +884,9 @@ const runConnectedAccountsLink = (params: {
884 { decode: false }
885 )
886 .pipe(
915 - Effect.mapError(
916 - cause =>
917 - new ConnectedAccountsRequestError({
918 - message: `Failed to create link for toolkit "${toolkitSlug}".`,
919 - cause,
920 - })
887 + failedWith(
888 + ConnectedAccountsRequestError,
889 + `Failed to create link for toolkit "${toolkitSlug}".`
890 )
891 );
892 })
ts/packages/cli/src/commands/connected-accounts/commands/connected-accounts.list.cmd.ts
+5 -15
@@ -1,19 +1,17 @@
1 import { Command, Flag } from 'effect/cli';
2 -import { Data, Effect, Option } from 'effect';
2 +import { Effect, Option } from 'effect';
3 import { ComposioClientSingleton } from 'src/services/composio-clients';
4 import { TerminalUI } from 'src/services/terminal-ui';
5 import { decodeConnectedAccountListWithFallback } from 'src/effects/decode-connected-account-list';
6 +import { failedWith, requestError } from 'src/effects/request-error';
7 import { clampLimit } from 'src/ui/clamp-limit';
8 import { redact } from 'src/ui/redact';
9 import { resolveCommandProject } from 'src/services/command-project';
10 import { formatConnectedAccountsTable, formatConnectedAccountsJson } from '../format';
11
11 -class ConnectedAccountsListRequestError extends Data.TaggedError(
12 +class ConnectedAccountsListRequestError extends requestError(
13 'commands/ConnectedAccountsListRequestError'
13 -)<{
14 - readonly message: string;
15 - readonly cause: unknown;
16 -}> {}
14 +) {}
15
16 const toolkits = Flag.String('toolkits').pipe(
17 Flag.withDescription('Filter by toolkit slugs, comma-separated (e.g. "gmail" or "gmail,slack")'),
@@ -81,15 +79,7 @@ export const connectedAccountsCmd$List = Command.make(
79 },
80 { decode: false }
81 )
84 - .pipe(
85 - Effect.mapError(
86 - cause =>
87 - new ConnectedAccountsListRequestError({
88 - message: 'Failed to list connected accounts.',
89 - cause,
90 - })
91 - )
92 - )
82 + .pipe(failedWith(ConnectedAccountsListRequestError, 'Failed to list connected accounts.'))
83 );
84 const result = yield* decodeConnectedAccountListWithFallback(rawResult);
85
ts/packages/cli/src/commands/connections/commands/connections.list.cmd.ts
+3 -13
@@ -1,6 +1,7 @@
1 import { Data, Effect, Option } from 'effect';
2 import { Command, Flag } from 'effect/cli';
3 import { decodeConnectedAccountListWithFallback } from 'src/effects/decode-connected-account-list';
4 +import { failedWith, requestError } from 'src/effects/request-error';
5 import type { ConnectedAccountItem } from 'src/models/connected-accounts';
6 import { ComposioClientSingleton } from 'src/services/composio-clients';
7 import { resolveCommandProject } from 'src/services/command-project';
@@ -16,10 +17,7 @@ class MissingConnectionsConsumerUserIdError extends Data.TaggedError(
17 readonly message: string;
18 }> {}
19
19 -class ConnectionsListRequestError extends Data.TaggedError('commands/ConnectionsListRequestError')<{
20 - readonly message: string;
21 - readonly cause: unknown;
22 -}> {}
20 +class ConnectionsListRequestError extends requestError('commands/ConnectionsListRequestError') {}
21
22 const toolkit = Flag.String('toolkit').pipe(
23 Flag.withDescription('Filter by toolkit slug (e.g. "gmail")'),
@@ -86,15 +84,7 @@ export const connectionsCmd$List = Command.make('list', { toolkit }, ({ toolkit
84 },
85 { decode: false }
86 )
89 - .pipe(
90 - Effect.mapError(
91 - cause =>
92 - new ConnectionsListRequestError({
93 - message: 'Failed to list connections.',
94 - cause,
95 - })
96 - )
97 - );
87 + .pipe(failedWith(ConnectionsListRequestError, 'Failed to list connections.'));
88 const result = yield* decodeConnectedAccountListWithFallback(rawResult);
89 const permissionSnapshot = yield* getConsumerPermissionSnapshot({
90 orgId: resolvedProject.orgId,
ts/packages/cli/src/commands/connections/commands/connections.remove.cmd.ts
+12 -23
@@ -1,6 +1,7 @@
1 import { Data, Effect } from 'effect';
2 import { Argument, Command } from 'effect/cli';
3 import { decodeConnectedAccountListWithFallback } from 'src/effects/decode-connected-account-list';
4 +import { failedWith, requestError } from 'src/effects/request-error';
5 import type { ConnectedAccountItem } from 'src/models/connected-accounts';
6 import { ComposioClientSingleton } from 'src/services/composio-clients';
7 import { resolveCommandProject } from 'src/services/command-project';
@@ -14,12 +15,9 @@ class MissingConnectionRemovalConsumerUserIdError extends Data.TaggedError(
15 readonly message: string;
16 }> {}
17
17 -class ConnectionsRemovalRequestError extends Data.TaggedError(
18 +class ConnectionsRemovalRequestError extends requestError(
19 'commands/ConnectionsRemovalRequestError'
19 -)<{
20 - readonly message: string;
21 - readonly cause: unknown;
22 -}> {}
20 +) {}
21
22 const account = Argument.String('account').pipe(
23 Argument.withDescription(
@@ -113,15 +111,7 @@ export const connectionsCmd$Remove = Command.make('remove', { account }, ({ acco
111 'Fetching connections...',
112 client.connectedAccounts
113 .list({ user_ids: [consumerUserId], limit: 1000 }, { decode: false })
116 - .pipe(
117 - Effect.mapError(
118 - cause =>
119 - new ConnectionsRemovalRequestError({
120 - message: 'Failed to list connections.',
121 - cause,
122 - })
123 - )
124 - )
114 + .pipe(failedWith(ConnectionsRemovalRequestError, 'Failed to list connections.'))
115 );
116 const result = yield* decodeConnectedAccountListWithFallback(rawResult);
117 const resolved = resolveAccount({ accounts: result.items, selector: account });
@@ -146,15 +136,14 @@ export const connectionsCmd$Remove = Command.make('remove', { account }, ({ acco
136
137 yield* ui.withSpinner(
138 `Removing ${resolved.toolkit.slug} connection...`,
149 - client.connectedAccounts.delete(resolved.id, undefined, { decode: false }).pipe(
150 - Effect.mapError(
151 - cause =>
152 - new ConnectionsRemovalRequestError({
153 - message: `Failed to remove connected account "${resolved.id}".`,
154 - cause,
155 - })
156 - )
157 - ),
139 + client.connectedAccounts
140 + .delete(resolved.id, undefined, { decode: false })
141 + .pipe(
142 + failedWith(
143 + ConnectionsRemovalRequestError,
144 + `Failed to remove connected account "${resolved.id}".`
145 + )
146 + ),
147 {
148 successMessage: `Removed ${resolved.toolkit.slug} connection.`,
149 errorMessage: `Failed to remove ${resolved.toolkit.slug} connection.`,
ts/packages/cli/src/commands/logs/commands/logs.tools.cmd.ts
+7 -23
@@ -1,5 +1,6 @@
1 import { Argument, Command, Flag } from 'effect/cli';
2 -import { Data, Effect, Option } from 'effect';
2 +import { Effect, Option } from 'effect';
3 +import { failedWith, requestError } from 'src/effects/request-error';
4 import { TerminalUI } from 'src/services/terminal-ui';
5 import { ComposioClientSingleton } from 'src/services/composio-clients';
6 import { undecoded } from 'src/services/composio-request';
@@ -9,10 +10,7 @@ import { formatToolLogInfo, formatToolLogsTable } from '../format';
10 import { commandHintStep } from 'src/services/command-hints';
11 import { toSearchParam } from '../utils';
12
12 -class ToolLogsRequestError extends Data.TaggedError('commands/ToolLogsRequestError')<{
13 - readonly message: string;
14 - readonly cause: unknown;
15 -}> {}
13 +class ToolLogsRequestError extends requestError('commands/ToolLogsRequestError') {}
14
15 type ToolLogFilterInput = {
16 tool?: string;
@@ -188,15 +186,9 @@ export const logsCmd$Tools = Command.make(
186 if (toolLogId) {
187 const toolLog = yield* ui.withSpinner(
188 `Fetching tool log "${toolLogId}"...`,
191 - client.logs.tools.retrieve(toolLogId, undecoded).pipe(
192 - Effect.mapError(
193 - cause =>
194 - new ToolLogsRequestError({
195 - message: `Failed to fetch tool log "${toolLogId}".`,
196 - cause,
197 - })
198 - )
199 - )
189 + client.logs.tools
190 + .retrieve(toolLogId, undecoded)
191 + .pipe(failedWith(ToolLogsRequestError, `Failed to fetch tool log "${toolLogId}".`))
192 );
193
194 yield* ui.log.info(
@@ -220,15 +212,7 @@ export const logsCmd$Tools = Command.make(
212 },
213 undecoded
214 )
223 - .pipe(
224 - Effect.mapError(
225 - cause =>
226 - new ToolLogsRequestError({
227 - message: 'Failed to fetch tool logs.',
228 - cause,
229 - })
230 - )
231 - )
215 + .pipe(failedWith(ToolLogsRequestError, 'Failed to fetch tool logs.'))
216 );
217
218 const logs = response.data ?? [];
ts/packages/cli/src/commands/logs/commands/logs.triggers.cmd.ts
+8 -22
@@ -1,5 +1,6 @@
1 import { Argument, Command, Flag } from 'effect/cli';
2 -import { Data, Effect, Option } from 'effect';
2 +import { Effect, Option } from 'effect';
3 +import { failedWith, requestError } from 'src/effects/request-error';
4 import { TerminalUI } from 'src/services/terminal-ui';
5 import { ComposioClientSingleton } from 'src/services/composio-clients';
6 import { undecoded } from 'src/services/composio-request';
@@ -10,10 +11,7 @@ import { decodeTriggerLogRecord } from '../trigger-log-record';
11 import { commandHintStep } from 'src/services/command-hints';
12 import { toSearchParam } from '../utils';
13
13 -class TriggerLogsRequestError extends Data.TaggedError('commands/TriggerLogsRequestError')<{
14 - readonly message: string;
15 - readonly cause: unknown;
16 -}> {}
14 +class TriggerLogsRequestError extends requestError('commands/TriggerLogsRequestError') {}
15
16 const cursor = Flag.String('cursor').pipe(
17 Flag.withDescription('Cursor for pagination'),
@@ -153,15 +151,11 @@ export const logsCmd$Triggers = Command.make(
151 if (triggerLogId) {
152 const triggerLog = yield* ui.withSpinner(
153 `Fetching trigger log "${triggerLogId}"...`,
156 - client.logs.triggers.retrieve(triggerLogId, undecoded).pipe(
157 - Effect.mapError(
158 - cause =>
159 - new TriggerLogsRequestError({
160 - message: `Failed to fetch trigger log "${triggerLogId}".`,
161 - cause,
162 - })
154 + client.logs.triggers
155 + .retrieve(triggerLogId, undecoded)
156 + .pipe(
157 + failedWith(TriggerLogsRequestError, `Failed to fetch trigger log "${triggerLogId}".`)
158 )
164 - )
159 );
160 const record = decodeTriggerLogRecord(triggerLog);
161
@@ -189,15 +183,7 @@ export const logsCmd$Triggers = Command.make(
183 },
184 undecoded
185 )
192 - .pipe(
193 - Effect.mapError(
194 - cause =>
195 - new TriggerLogsRequestError({
196 - message: 'Failed to fetch trigger logs.',
197 - cause,
198 - })
199 - )
200 - )
186 + .pipe(failedWith(TriggerLogsRequestError, 'Failed to fetch trigger logs.'))
187 );
188
189 const logs = response.data ?? [];
ts/packages/cli/src/commands/proxy.cmd.ts
+2 -4
@@ -5,6 +5,7 @@ import type {
5 SessionProxyExecuteParams,
6 SessionProxyExecuteResponse,
7 } from '@composio/client/resources/tool-router/session';
8 +import { requestError } from 'src/effects/request-error';
9 import { resolveOptionalTextInput } from 'src/effects/resolve-optional-text-input';
10 import { resolveToolRouterSession } from 'src/effects/create-tool-router-session';
11 import {
@@ -83,10 +84,7 @@ export class ProxyCommandError extends Data.TaggedError('commands/ProxyCommandEr
84 readonly endpoint?: string;
85 }> {}
86
86 -class ProxyRequestError extends Data.TaggedError('commands/ProxyRequestError')<{
87 - readonly message: string;
88 - readonly cause: unknown;
89 -}> {}
87 +class ProxyRequestError extends requestError('commands/ProxyRequestError') {}
88
89 export const normalizeProxyMethod = (value: string): ProxyMethod => {
90 const normalized = value.trim().toUpperCase();
ts/packages/cli/src/commands/toolkits/commands/toolkits.info.cmd.ts
+4 -12
@@ -1,7 +1,8 @@
1 import { Argument, Command, Flag } from 'effect/cli';
2 -import { Data, Effect, Option } from 'effect';
2 +import { Effect, Option } from 'effect';
3 import { ComposioClientSingleton, ComposioToolkitsRepository } from 'src/services/composio-clients';
4 import { TerminalUI } from 'src/services/terminal-ui';
5 +import { failedWith, requestError } from 'src/effects/request-error';
6 import { undecoded } from 'src/services/composio-request';
7 import { resolveToolRouterSession } from 'src/effects/create-tool-router-session';
8 import { extractMessage } from 'src/utils/api-error-extraction';
@@ -9,10 +10,7 @@ import { ProjectContext } from 'src/services/project-context';
10 import { ComposioUserContext } from 'src/services/user-context';
11 import { formatToolkitInfo, formatToolkitInfoJson } from '../format';
12
12 -class ToolkitsInfoRequestError extends Data.TaggedError('commands/ToolkitsInfoRequestError')<{
13 - readonly message: string;
14 - readonly cause: unknown;
15 -}> {}
13 +class ToolkitsInfoRequestError extends requestError('commands/ToolkitsInfoRequestError') {}
14
15 const slug = Argument.String('slug').pipe(
16 Argument.withDescription('Toolkit slug (e.g. "gmail")'),
@@ -95,13 +93,7 @@ export const toolkitsCmd$Info = Command.make(
93 // Only the first item is read, and only a few of its fields.
94 .toolkits(sessionId, { toolkits: [slugValue] }, undecoded)
95 .pipe(
98 - Effect.mapError(
99 - cause =>
100 - new ToolkitsInfoRequestError({
101 - message: `Failed to fetch toolkit "${slugValue}".`,
102 - cause,
103 - })
104 - )
96 + failedWith(ToolkitsInfoRequestError, `Failed to fetch toolkit "${slugValue}".`)
97 );
98 return { toolkit: sessionToolkits.items[0], detailedToolkitOpt };
99 }
ts/packages/cli/src/commands/toolkits/commands/toolkits.list.cmd.ts
+2 -14
@@ -1,6 +1,6 @@
1 import process from 'node:process';
2 import { Command, Flag } from 'effect/cli';
3 -import { Data, Effect, Option } from 'effect';
3 +import { Effect, Option } from 'effect';
4 import { TerminalUI } from 'src/services/terminal-ui';
5 import { resolveToolRouterSession } from 'src/effects/create-tool-router-session';
6 import { ComposioClientSingleton, ComposioToolkitsRepository } from 'src/services/composio-clients';
@@ -11,11 +11,6 @@ import { clampLimit } from 'src/ui/clamp-limit';
11 import { extractMessage } from 'src/utils/api-error-extraction';
12 import { mergeToolkitData, formatToolkitsJson, formatToolkitsTable } from '../format';
13
14 -class ToolkitsListRequestError extends Data.TaggedError('commands/ToolkitsListRequestError')<{
15 - readonly message: string;
16 - readonly cause: unknown;
17 -}> {}
18 -
14 const query = Flag.String('query').pipe(
15 Flag.withDescription('Text search by name, slug, or description'),
16 Flag.optional
@@ -141,15 +136,8 @@ export const toolkitsCmd$List = Command.make(
136 undecoded
137 )
138 .pipe(
144 - Effect.mapError(
145 - cause =>
146 - new ToolkitsListRequestError({
147 - message: 'Failed to fetch session toolkits.',
148 - cause,
149 - })
150 - ),
139 Effect.map(r => r.items),
152 - Effect.catchTag('commands/ToolkitsListRequestError', error =>
140 + Effect.catch(error =>
141 Effect.logDebug('Failed to fetch session toolkits:', error).pipe(
142 Effect.as(
143 [] as ReadonlyArray<
ts/packages/cli/src/commands/tools/commands/tools.search.cmd.ts
+4 -14
@@ -2,8 +2,9 @@ import { requireLogin } from 'src/effects/require-auth';
2 import { commandInputError } from 'src/commands/errors';
3 import { Argument, Command, Flag } from 'effect/cli';
4 import type { SessionSearchResponse } from '@composio/client/resources/tool-router';
5 -import { Data, Effect, Option } from 'effect';
5 +import { Effect, Option } from 'effect';
6 import { TerminalUI } from 'src/services/terminal-ui';
7 +import { failedWith, requestError } from 'src/effects/request-error';
8 import { setupCacheDir } from 'src/effects/setup-cache-dir';
9 import { clampLimit } from 'src/ui/clamp-limit';
10 import { resolveToolRouterSession } from 'src/effects/create-tool-router-session';
@@ -73,10 +74,7 @@ type SearchResponseRecord = Pick<
74
75 const invalidSearchInput = commandInputError('search');
76
76 -class ToolsSearchRequestError extends Data.TaggedError('commands/ToolsSearchRequestError')<{
77 - readonly message: string;
78 - readonly cause: unknown;
79 -}> {}
77 +class ToolsSearchRequestError extends requestError('commands/ToolsSearchRequestError') {}
78
79 const stripSearchResultMetadata = <
80 T extends { reference_workbench_snippets?: unknown; plan_id?: unknown },
@@ -368,15 +366,7 @@ const runToolsSearch = (params: {
366 // among them, may change without this version of the CLI noticing.
367 const searchResponse = yield* client.toolRouter.session
368 .search(sessionId, searchPayload, undecoded)
371 - .pipe(
372 - Effect.mapError(
373 - cause =>
374 - new ToolsSearchRequestError({
375 - message: 'Failed to search tools.',
376 - cause,
377 - })
378 - )
379 - );
369 + .pipe(failedWith(ToolsSearchRequestError, 'Failed to search tools.'));
370 const customToolSlugsMissingSchemas = Object.entries(searchResponse.tool_schemas)
371 .filter(([slug, schema]) => isRemoteCustomToolSlug(slug) && !schema.input_schema)
372 .map(([slug]) => slug);
ts/packages/cli/src/effect-errors/logic/errors/extract-error-details.ts
+4 -1
@@ -21,7 +21,10 @@ const clientApiErrorDetail = (error: ClientApiError): string => {
21 const { message, hint } = describeDecodeError(error);
22 return `${message}\n${hint}`;
23 }
24 - return isClientConnectionError(error) ? (error.description ?? error.message) : error.message;
24 + if (isClientConnectionError(error)) {
25 + return error.description ?? error.message;
26 + }
27 + return error.message;
28 };
29
30 // Wrappers like UpgradeBinaryError carry the actionable specifics (a
ts/packages/cli/src/effects/create-tool-router-session.ts
+2 -23
@@ -208,26 +208,5 @@ export const createToolRouterSessionContext = (
208 );
209 });
210
211 -/** Backward-compatible helper for callers that only need the session id. */
212 -export const createToolRouterSession = (
213 - client: ComposioClientShape,
214 - userId: string,
215 - options?: CreateToolRouterSessionOptions
216 -) =>
217 - createToolRouterSessionContext(client, userId, options).pipe(
218 - Effect.map(session => session.sessionId)
219 - );
220 -
221 -/**
222 - * Resolve the Composio client and create a Tool Router session in one step.
223 - * Returns `{ client, sessionId }` — eliminates the 3-step boilerplate
224 - * (resolve singleton, get client, create session) repeated across commands.
225 - */
226 -export const resolveToolRouterSession = (
227 - client: ComposioClientShape,
228 - userId: string,
229 - options?: CreateToolRouterSessionOptions
230 -) =>
231 - createToolRouterSessionContext(client, userId, options).pipe(
232 - Effect.map(session => ({ client, ...session }))
233 - );
211 +/** The name commands create their Tool Router session by. */
212 +export const resolveToolRouterSession = createToolRouterSessionContext;
ts/packages/cli/src/effects/request-error.ts new
+37
@@ -0,0 +1,37 @@
1 +import { Data, Effect, type Cause } from 'effect';
2 +
3 +type RequestErrorFields = {
4 + readonly message: string;
5 + readonly cause: unknown;
6 +};
7 +
8 +/**
9 + * Base class for a command's failure around a client request: the command's
10 + * own message, with the client's error kept in `cause`, which the top-level
11 + * printer renders as `Caused by:`.
12 + *
13 + * @example
14 + * ```ts
15 + * class ToolLogsRequestError extends requestError('commands/ToolLogsRequestError') {}
16 + * ```
17 + */
18 +export const requestError = <Tag extends string>(
19 + tag: Tag
20 +): new (
21 + fields: RequestErrorFields
22 +) => Cause.YieldableError & { readonly _tag: Tag } & RequestErrorFields =>
23 + Data.TaggedError(tag)<RequestErrorFields>;
24 +
25 +/**
26 + * Replaces any failure of an effect with `RequestError` carrying `message`,
27 + * keeping the original failure as its cause.
28 + *
29 + * @example
30 + * ```ts
31 + * client.logs.tools.list(query).pipe(failedWith(ToolLogsRequestError, 'Failed to fetch tool logs.'))
32 + * ```
33 + */
34 +export const failedWith =
35 + <E>(RequestError: new (fields: RequestErrorFields) => E, message: string) =>
36 + <A, R>(self: Effect.Effect<A, unknown, R>): Effect.Effect<A, E, R> =>
37 + Effect.mapError(self, cause => new RequestError({ message, cause }));
ts/packages/cli/src/models/session.ts
-9
@@ -1,5 +1,4 @@
1 import { Schema } from 'effect';
2 -import { JSONTransformSchema } from './utils/json-transform-schema';
2
3 export const Session = Schema.Struct({
4 id: Schema.String,
@@ -9,10 +8,6 @@ export const Session = Schema.Struct({
8 }).annotate({ identifier: 'Session' });
9 export type Session = Schema.Schema.Type<typeof Session>;
10
12 -export const SessionJSON = JSONTransformSchema(Session);
13 -export const sessionFromJSON = Schema.decodeEffect(SessionJSON);
14 -export const sessionToJSON = Schema.encodeEffect(SessionJSON);
15 -
11 const SessionAccount = Schema.Struct({
12 id: Schema.String,
13 email: Schema.String,
@@ -30,7 +25,3 @@ export const RetrievedSession = Schema.Union([
25 }),
26 ]).annotate({ identifier: 'RetrievedSession' });
27 export type RetrievedSession = Schema.Schema.Type<typeof RetrievedSession>;
33 -
34 -export const RetrievedSessionJSON = JSONTransformSchema(RetrievedSession);
35 -export const retrievedSessionFromJSON = Schema.decodeEffect(RetrievedSessionJSON);
36 -export const retrievedSessionToJSON = Schema.encodeEffect(RetrievedSessionJSON);
ts/packages/cli/src/models/tools.ts
+1 -9
@@ -1,4 +1,4 @@
1 -import { Brand, Schema } from 'effect';
1 +import { Schema } from 'effect';
2 import { JSONTransformSchema } from './utils/json-transform-schema';
3
4 export const ToolAsEnum = Schema.String.annotate({ identifier: 'ToolAsEnum' });
@@ -14,14 +14,6 @@ export const ToolsAsEnumsJSON = JSONTransformSchema(ToolsAsEnums);
14 export const toolsAsEnumsFromJSON = Schema.decodeEffect(ToolsAsEnumsJSON);
15 export const toolsAsEnumsToJSON = Schema.encodeEffect(ToolsAsEnumsJSON);
16
17 -// E.g., `SEND_EMAIL`
18 -export type ToolName = string & Brand.Brand<'ToolName'>;
19 -export const ToolName = Brand.nominal<ToolName>();
20 -
21 -// E.g., `GMAIL_SEND_EMAIL`
22 -export type ToolNameWithToolkitPrefix = string & Brand.Brand<'ToolNameWithToolkitPrefix'>;
23 -export const ToolNameWithToolkitPrefix = Brand.nominal<ToolNameWithToolkitPrefix>();
24 -
17 /**
18 * Tool with payload
19 */
ts/packages/cli/src/models/trigger-types.ts
-4
@@ -71,10 +71,6 @@ export const TriggerType = Schema.Struct({
71 }).annotate({ identifier: 'TriggerType' });
72 export type TriggerType = Schema.Schema.Type<typeof TriggerType>;
73
74 -export const TriggerTypeJSON = JSONTransformSchema(TriggerType);
75 -export const TriggerTypeFromJSON = Schema.decodeEffect(TriggerTypeJSON);
76 -export const TriggerTypeToJSON = Schema.encodeEffect(TriggerTypeJSON);
77 -
74 export const TriggerTypes = Schema.Array(TriggerType).annotate({
75 identifier: 'Array<TriggerType>',
76 title: 'TriggerTypes',
ts/packages/cli/src/services/composio-account.ts
+9 -27
@@ -71,34 +71,16 @@ export const sessionProjectApiKeyOf = (info: SessionInfoResponse): string | null
71 */
72 export type OrgProject = ProjectListResponse.Data;
73
74 -/**
75 - * Response from GET /api/v3.1/org/project/list.
76 - */
77 -export type OrgProjectListResponse = ProjectListResponse;
78 -
74 export interface OrganizationSummary {
75 readonly id: string;
76 readonly name: string;
77 }
78
84 -export interface OrganizationListResponse {
79 +interface OrganizationSummaryList {
80 readonly data: ReadonlyArray<OrganizationSummary>;
81 readonly total_items: number;
82 }
83
89 -export interface OrganizationProjectSummary {
90 - readonly id: string;
91 - readonly name: string;
92 -}
93 -
94 -export interface OrganizationProjectListResponse {
95 - readonly data: ReadonlyArray<OrganizationProjectSummary>;
96 - readonly total_items: number;
97 -}
98 -
99 -export type ConsumerProjectResolveResponse = ProjectResolveResponse;
100 -export type ConsumerConnectedToolkitsResponse = ConsumerListConnectedToolkitsResponse;
101 -
84 const orgScopedOptions = (orgId: string | undefined): RequestOptions | undefined =>
85 orgId ? { headers: { 'x-org-id': orgId } } : undefined;
86
@@ -108,7 +90,7 @@ const orgScopedOptions = (orgId: string | undefined): RequestOptions | undefined
90 export const listOrganizations = (params: {
91 apiKey: string;
92 limit?: number;
111 -}): Effect.Effect<OrganizationListResponse, ClientError, ComposioClientSingleton> =>
93 +}): Effect.Effect<OrganizationSummaryList, ClientError, ComposioClientSingleton> =>
94 Effect.gen(function* () {
95 const clientSingleton = yield* ComposioClientSingleton;
96 const client = yield* clientSingleton.getFor({ userApiKey: params.apiKey });
@@ -135,7 +117,7 @@ export const listOrganizationProjects = (params: {
117 apiKey: string;
118 orgId: string;
119 limit?: number;
138 -}): Effect.Effect<OrganizationProjectListResponse, ClientError, ComposioClientSingleton> =>
120 +}): Effect.Effect<OrganizationSummaryList, ClientError, ComposioClientSingleton> =>
121 Effect.gen(function* () {
122 const clientSingleton = yield* ComposioClientSingleton;
123 const client = yield* clientSingleton.getFor({ userApiKey: params.apiKey });
@@ -145,7 +127,7 @@ export const listOrganizationProjects = (params: {
127 );
128 const projects = response.data.map(
129 (project: OrgProject) =>
148 - ({ id: project.id, name: project.name }) satisfies OrganizationProjectSummary
130 + ({ id: project.id, name: project.name }) satisfies OrganizationSummary
131 );
132
133 return {
@@ -165,7 +147,7 @@ export const listOrgProjects = (params: {
147 apiKey: string;
148 orgId: string;
149 limit?: number;
168 -}): Effect.Effect<OrgProjectListResponse, ClientError, ComposioClientSingleton> =>
150 +}): Effect.Effect<ProjectListResponse, ClientError, ComposioClientSingleton> =>
151 Effect.gen(function* () {
152 const clientSingleton = yield* ComposioClientSingleton;
153 const client = yield* clientSingleton.getFor({ userApiKey: params.apiKey });
@@ -292,7 +274,7 @@ export const createProjectApiKey = (params: {
274 export const resolveConsumerProject = (params: {
275 apiKey: string;
276 orgId: string;
295 -}): Effect.Effect<ConsumerProjectResolveResponse, ClientError, ComposioClientSingleton> =>
277 +}): Effect.Effect<ProjectResolveResponse, ClientError, ComposioClientSingleton> =>
278 Effect.gen(function* () {
279 const clientSingleton = yield* ComposioClientSingleton;
280 const client = yield* clientSingleton.getFor({ userApiKey: params.apiKey });
@@ -339,7 +321,7 @@ export const getConsumerConnectedToolkits = (params: {
321 apiKey: string;
322 orgId: string;
323 consumerUserId: string;
342 -}): Effect.Effect<ConsumerConnectedToolkitsResponse, ClientError, ComposioClientSingleton> =>
324 +}): Effect.Effect<ConsumerListConnectedToolkitsResponse, ClientError, ComposioClientSingleton> =>
325 Effect.gen(function* () {
326 const clientSingleton = yield* ComposioClientSingleton;
327 const client = yield* clientSingleton.getFor({ userApiKey: params.apiKey });
@@ -362,7 +344,7 @@ export class AmbiguousDeveloperProjectNameError extends Data.TaggedError(
344 )<{
345 readonly orgId: string;
346 readonly projectName: string;
365 - readonly matches: ReadonlyArray<OrganizationProjectSummary>;
347 + readonly matches: ReadonlyArray<OrganizationSummary>;
348 }> {}
349
350 export const findDeveloperProjectByName = (params: {
@@ -371,7 +353,7 @@ export const findDeveloperProjectByName = (params: {
353 name: string;
354 limit?: number;
355 }): Effect.Effect<
374 - OrganizationProjectSummary,
356 + OrganizationSummary,
357 DeveloperProjectNotFoundError | AmbiguousDeveloperProjectNameError | ClientError,
358 ComposioClientSingleton
359 > =>
ts/packages/cli/src/services/composio-errors.ts
+2 -3
@@ -21,8 +21,6 @@ export class HttpDecodingError extends Data.TaggedError('services/HttpDecodingEr
21 readonly cause?: unknown;
22 }> {}
23
24 -export type HttpError = ComposioError | HttpDecodingError;
25 -
24 /**
25 * A failure of a request made through the Effect client: a non-success status,
26 * a transport failure, a timeout, or a response body that failed decoding.
@@ -55,4 +53,5 @@ export type ClientApiErrorTag = (typeof CLIENT_API_ERROR_TAGS)[number];
53 * own tagged error, decoding a CLI-owned contract, or obtaining a client from
54 * the singleton.
55 */
58 -export type ClientError = HttpError | ComposioClientConfigurationError | NoSuchElementError;
56 +export type ClientError =
57 + ComposioError | HttpDecodingError | ComposioClientConfigurationError | NoSuchElementError;
ts/packages/cli/src/services/composio-resource-operations.ts
+6 -62
@@ -1,34 +1,22 @@
1 import { Effect } from 'effect';
2 import type { ComposioClientShape } from '@composio/client/effect';
3 import type { AuthConfigCreateParams } from '@composio/client/resources/auth-configs';
4 -import type { ConnectedAccountListParams } from '@composio/client/resources/connected-accounts';
4 +import type {
5 + TriggerInstanceListActiveParams,
6 + TriggerInstanceUpsertParams,
7 +} from '@composio/client/resources/trigger-instances';
8 import {
9 AuthConfigCreateResponse,
10 AuthConfigItem,
11 AuthConfigListResponse,
12 } from 'src/models/auth-configs';
10 -import { ConnectedAccountItem, ConnectedAccountListResponse } from 'src/models/connected-accounts';
13 +import { ConnectedAccountItem } from 'src/models/connected-accounts';
14 import { Toolkits, type ToolkitSearchResult } from 'src/models/toolkits';
15 import { TriggerInstanceItems } from 'src/models/triggers';
16 import { TriggerType } from 'src/models/trigger-types';
17 import type { ClientError } from './composio-errors';
18 import { decode, undecoded } from './composio-request';
19
17 -export interface TriggerInstancesListActiveParams {
18 - user_ids?: string[];
19 - connected_account_ids?: string[];
20 - auth_config_ids?: string[];
21 - trigger_ids?: string[];
22 - trigger_names?: string[];
23 - show_disabled?: boolean;
24 - limit?: number;
25 -}
26 -
27 -export interface TriggerInstanceUpsertParams {
28 - connected_account_id?: string;
29 - trigger_config?: Record<string, unknown>;
30 -}
31 -
20 /**
21 * Auth config, connected account, and trigger instance operations: single-page
22 * CRUD with no catalog caching.
@@ -76,36 +64,6 @@ export const resourceOperations = (client: Effect.Effect<ComposioClientShape, Cl
64 Effect.flatMap(c => c.authConfigs.create(params, undecoded)),
65 Effect.flatMap(decode(AuthConfigCreateResponse))
66 ),
79 - /**
80 - * Soft-deletes an auth config by its nanoid.
81 - * @param nanoid - Auth config ID
82 - */
83 - deleteAuthConfig: (nanoid: string) =>
84 - Effect.flatMap(client, c => c.authConfigs.delete(nanoid, undefined, undecoded)),
85 - /**
86 - * List connected accounts with optional filters. Returns a single page of results.
87 - * @param params - Search/filter parameters
88 - */
89 - listConnectedAccounts: (params: {
90 - toolkit_slugs?: string[];
91 - user_ids?: string[];
92 - statuses?: ConnectedAccountListParams['statuses'];
93 - limit?: number;
94 - }) =>
95 - client.pipe(
96 - Effect.flatMap(c =>
97 - c.connectedAccounts.list(
98 - {
99 - toolkit_slugs: params.toolkit_slugs,
100 - user_ids: params.user_ids,
101 - statuses: params.statuses,
102 - limit: params.limit,
103 - },
104 - undecoded
105 - )
106 - ),
107 - Effect.flatMap(decode(ConnectedAccountListResponse))
108 - ),
67 /**
68 * Retrieves detailed info about a single connected account by its nanoid.
69 * @param nanoid - Connected account ID (e.g. "con_1a2b3c4d5e6f")
@@ -115,23 +73,11 @@ export const resourceOperations = (client: Effect.Effect<ComposioClientShape, Cl
73 Effect.flatMap(c => c.connectedAccounts.retrieve(nanoid, undecoded)),
74 Effect.flatMap(decode(ConnectedAccountItem))
75 ),
118 - /**
119 - * Soft-deletes a connected account by its nanoid.
120 - * @param nanoid - Connected account ID
121 - */
122 - deleteConnectedAccount: (nanoid: string) =>
123 - Effect.flatMap(client, c => c.connectedAccounts.delete(nanoid, undefined, undecoded)),
124 - /**
125 - * Creates a new authentication link session for connecting an external account.
126 - * @param params - auth_config_id and user_id
127 - */
128 - createConnectedAccountLink: (params: { auth_config_id: string; user_id: string }) =>
129 - Effect.flatMap(client, c => c.link.create(params, undecoded)),
76 /**
77 * Lists active trigger instances with optional filters.
78 * Returns a single page of results.
79 */
134 - listActiveTriggers: (params: TriggerInstancesListActiveParams) =>
80 + listActiveTriggers: (params: TriggerInstanceListActiveParams) =>
81 client.pipe(
82 Effect.flatMap(c =>
83 c.triggerInstances.listActive(
@@ -172,8 +118,6 @@ export const resourceOperations = (client: Effect.Effect<ComposioClientShape, Cl
118 Effect.flatMap(client, c =>
119 c.triggerInstances.manage.update(triggerId, { status: 'disable' }, undecoded)
120 ),
175 - deleteTrigger: (triggerId: string) =>
176 - Effect.flatMap(client, c => c.triggerInstances.manage.delete(triggerId, undecoded)),
121 });
122
123 /**
ts/packages/cli/src/services/tool-input-validation.ts
-18
@@ -136,13 +136,6 @@ export const getCachedToolInputDefinition = (slug: string) =>
136 };
137 });
138
139 -export const getToolDefinitionCachePath = (slug: string) =>
140 - Effect.gen(function* () {
141 - const path = yield* Path.Path;
142 - const cacheDir = yield* setupCacheDir;
143 - return toolDefinitionPath(path, cacheDir, slug);
144 - });
145 -
139 export const cacheToolInputDefinition = (params: {
140 readonly slug: string;
141 readonly schema: Record<string, unknown>;
@@ -498,17 +491,6 @@ export const validateToolInputArgumentsWithDefinition = (
491 return { schemaPath, schema };
492 });
493
501 -export const validateToolInputArgumentsIfCached = (slug: string, args: Record<string, unknown>) =>
502 - Effect.gen(function* () {
503 - const cached = yield* getCachedToolInputDefinition(slug);
504 - if (!cached) {
505 - return false as const;
506 - }
507 -
508 - yield* validateToolInputArgumentsWithDefinition(slug, args, cached);
509 - return true as const;
510 - });
511 -
494 export const validateToolInputArguments = (
495 slug: string,
496 args: Record<string, unknown>,
ts/packages/cli/src/services/tool-router-session-connections.ts
+11 -36
@@ -1,4 +1,4 @@
1 -import { Data, Effect } from 'effect';
1 +import { Effect } from 'effect';
2 import type { ComposioClientShape } from '@composio/client/effect';
3 import { isKnownConnectedAccountStatus } from 'src/models/connected-accounts';
4 import {
@@ -9,13 +9,6 @@ import {
9 type SelectableConnectedAccount,
10 } from 'src/services/connected-account-selection';
11
12 -export class ToolRouterSessionConnectionsError extends Data.TaggedError(
13 - 'services/ToolRouterSessionConnectionsError'
14 -)<{
15 - readonly message: string;
16 - readonly cause: unknown;
17 -}> {}
18 -
12 type RawConnectedAccount = {
13 readonly id: string;
14 readonly alias?: string | null;
@@ -64,25 +57,15 @@ const listConnectedAccountsForToolkits = (
57 userId: string,
58 toolkits: ReadonlyArray<string>
59 ) =>
67 - client.connectedAccounts
68 - .list(
69 - {
70 - user_ids: [userId],
71 - statuses: ['ACTIVE'],
72 - toolkit_slugs: [...toolkits],
73 - limit: 1000,
74 - },
75 - { decode: false }
76 - )
77 - .pipe(
78 - Effect.mapError(
79 - cause =>
80 - new ToolRouterSessionConnectionsError({
81 - message: `Failed to list connected accounts for user "${userId}".`,
82 - cause,
83 - })
84 - )
85 - );
60 + client.connectedAccounts.list(
61 + {
62 + user_ids: [userId],
63 + statuses: ['ACTIVE'],
64 + toolkit_slugs: [...toolkits],
65 + limit: 1000,
66 + },
67 + { decode: false }
68 + );
69
70 export const resolveToolRouterSessionConnections = (
71 client: ComposioClientShape,
@@ -95,15 +78,7 @@ export const resolveToolRouterSessionConnections = (
78 ? listConnectedAccountsForToolkits(client, userId, options.toolkits)
79 : // The unfiltered list is the one `composio execute` also needs for its
80 // account picker, so it is fetched once per process and shared.
98 - listActiveConnectedAccounts({ client, userId }).pipe(
99 - Effect.mapError(
100 - cause =>
101 - new ToolRouterSessionConnectionsError({
102 - message: `Failed to list connected accounts for user "${userId}".`,
103 - cause,
104 - })
105 - )
106 - )
81 + listActiveConnectedAccounts({ client, userId })
82 ).pipe(
83 Effect.map(response => {
84 const items = (response.items ?? []) as ReadonlyArray<RawConnectedAccount>;
ts/packages/cli/test/__utils__/services/stub-composio-client.ts
+20
@@ -86,3 +86,23 @@ export const stubClientResources = (
86 );
87 return { requests: stub.requests, layer };
88 };
89 +
90 +/** A request the stub answers specially: its method and a prefix of its path. */
91 +export interface StubRoute {
92 + readonly method: string;
93 + readonly path: string;
94 + readonly respond: () => Response;
95 +}
96 +
97 +/**
98 + * A `respond` that answers a request with the first route whose method and
99 + * path prefix match it, and every other request with `otherwise`.
100 + */
101 +export const routeRequests =
102 + (routes: ReadonlyArray<StubRoute>, otherwise: () => Response) =>
103 + (request: StubRequest): Response => {
104 + const route = routes.find(
105 + ({ method, path }) => request.method === method && request.path.startsWith(path)
106 + );
107 + return (route?.respond ?? otherwise)();
108 + };
ts/packages/cli/test/__utils__/services/test-layer.ts
+6 -112
@@ -12,6 +12,10 @@ import {
12 type RequestOptions,
13 } from '@composio/client/effect';
14 import type { LinkCreateResponse } from '@composio/client/resources/link';
15 +import type {
16 + TriggerInstanceListActiveParams,
17 + TriggerInstanceUpsertParams,
18 +} from '@composio/client/resources/trigger-instances';
19 import type { SessionRetrieveInfoResponse } from '@composio/client/resources/auth';
20 import type { ToolRetrieveResponse } from '@composio/client/resources/tools';
21 import { TIMESTAMP } from '../models/account';
@@ -233,7 +237,6 @@ export interface TestLiveInput {
237 connectedAccountsData?: {
238 items?: ConnectedAccountItem[];
239 linkResponse?: LinkCreateResponse;
236 - onPatch?: (params: { path: string; body: Record<string, unknown> | undefined }) => void;
240 onDelete?: (nanoid: string) => void;
241 };
242
@@ -724,51 +727,6 @@ export const TestLayer = (input?: TestLiveInput) =>
727 }
728 );
729 },
727 - deleteAuthConfig: (nanoid: string) => {
728 - const found = authConfigsData.items.find(item => item.id === nanoid);
729 - if (!found) {
730 - return Effect.fail(
731 - notFoundError(`Auth config "${nanoid}" not found`, {
732 - message: `Auth config "${nanoid}" not found.`,
733 - suggested_fix: 'Check the auth config ID and try again.',
734 - })
735 - );
736 - }
737 - return Effect.succeed({ success: true, message: 'Auth config deleted' });
738 - },
739 - listConnectedAccounts: (params: {
740 - toolkit_slugs?: string[];
741 - user_ids?: string[];
742 - statuses?: ReadonlyArray<string> | null;
743 - limit?: number;
744 - }) => {
745 - let results = [...connectedAccountsData.items];
746 -
747 - if (params.toolkit_slugs && params.toolkit_slugs.length > 0) {
748 - const slugs = params.toolkit_slugs.map(s => s.toLowerCase());
749 - results = results.filter(item => slugs.includes(item.toolkit.slug.toLowerCase()));
750 - }
751 -
752 - if (params.user_ids && params.user_ids.length > 0) {
753 - const ids = new Set(params.user_ids);
754 - results = results.filter(item => ids.has(item.user_id));
755 - }
756 -
757 - if (params.statuses && params.statuses.length > 0) {
758 - const statuses = new Set(params.statuses);
759 - results = results.filter(item => statuses.has(item.status));
760 - }
761 -
762 - const limit = params.limit ?? 30;
763 - const items = results.slice(0, limit);
764 - return Effect.succeed({
765 - items,
766 - total_items: results.length,
767 - total_pages: Math.ceil(results.length / limit),
768 - current_page: 1,
769 - next_cursor: null,
770 - });
771 - },
730 getConnectedAccount: (nanoid: string) => {
731 const found = connectedAccountsData.items.find(item => item.id === nanoid);
732 if (!found) {
@@ -781,38 +739,7 @@ export const TestLayer = (input?: TestLiveInput) =>
739 }
740 return Effect.succeed(found);
741 },
784 - deleteConnectedAccount: (nanoid: string) => {
785 - const found = connectedAccountsData.items.find(item => item.id === nanoid);
786 - if (!found) {
787 - return Effect.fail(
788 - notFoundError(`Connected account "${nanoid}" not found`, {
789 - message: `Connected account "${nanoid}" not found.`,
790 - suggested_fix: 'Check the connected account ID and try again.',
791 - })
792 - );
793 - }
794 - return Effect.succeed({ success: true });
795 - },
796 - createConnectedAccountLink: (params: { auth_config_id: string; user_id: string }) => {
797 - if (connectedAccountsData.linkResponse) {
798 - return Effect.succeed(connectedAccountsData.linkResponse);
799 - }
800 - return Effect.succeed({
801 - connected_account_id: 'con_test_link',
802 - expires_at: '2026-12-31T23:59:59Z',
803 - link_token: 'lt_test_token',
804 - redirect_url: `https://app.composio.dev/link?token=lt_test_token`,
805 - } satisfies LinkCreateResponse);
806 - },
807 - listActiveTriggers: (params: {
808 - user_ids?: string[];
809 - connected_account_ids?: string[];
810 - auth_config_ids?: string[];
811 - trigger_ids?: string[];
812 - trigger_names?: string[];
813 - show_disabled?: boolean;
814 - limit?: number;
815 - }) => {
742 + listActiveTriggers: (params: TriggerInstanceListActiveParams) => {
743 let results = [...triggersData.items];
744
745 const userIds = params.user_ids;
@@ -860,19 +787,12 @@ export const TestLayer = (input?: TestLiveInput) =>
787 next_cursor: null,
788 });
789 },
863 - createTrigger: (
864 - triggerSlug: string,
865 - params?: {
866 - connected_account_id?: string;
867 - trigger_config?: Record<string, unknown>;
868 - }
869 - ) =>
790 + createTrigger: (triggerSlug: string, params?: TriggerInstanceUpsertParams) =>
791 Effect.succeed({
792 trigger_id: `trg_${triggerSlug.toLowerCase()}_${params?.connected_account_id ?? 'new'}`,
793 }),
794 enableTrigger: () => Effect.succeed({ status: 'success' as const }),
795 disableTrigger: () => Effect.succeed({ status: 'success' as const }),
875 - deleteTrigger: triggerId => Effect.succeed({ trigger_id: triggerId }),
796 })
797 );
798 const ComposioSessionRepositoryTest = yield* setupComposioSessionRepository();
@@ -1111,28 +1031,6 @@ export const TestLayer = (input?: TestLiveInput) =>
1031 return response;
1032 },
1033 },
1114 - patch: (path: string, options?: { body?: Record<string, unknown> }) => {
1115 - connectedAccountsData.onPatch?.({ path, body: options?.body });
1116 -
1117 - const match = path.match(/^\/api\/v3\/connected_accounts\/([^/]+)$/);
1118 - if (!match) {
1119 - return Effect.die(new Error(`Unhandled PATCH path "${path}"`));
1120 - }
1121 -
1122 - const connectedAccountId = match[1];
1123 - const account = connectedAccountsData.items.find(item => item.id === connectedAccountId);
1124 - if (!account) {
1125 - return Effect.fail(notFoundError(`Connected account "${connectedAccountId}" not found`));
1126 - }
1127 -
1128 - if (typeof options?.body?.alias === 'string') {
1129 - Object.assign(account as { alias?: string | null }, {
1130 - alias: options.body.alias,
1131 - });
1132 - }
1133 -
1134 - return Effect.succeed(account);
1135 - },
1034 connectedAccounts: {
1035 list: async (params?: {
1036 toolkit_slugs?: string[];
@@ -1216,7 +1114,6 @@ export const TestLayer = (input?: TestLiveInput) =>
1114 trigger_id: triggerId,
1115 status: params.status,
1116 }),
1219 - delete: async (triggerId: string) => ({ trigger_id: triggerId }),
1117 },
1118 },
1119 toolkits: {
@@ -1312,9 +1209,6 @@ export const TestLayer = (input?: TestLiveInput) =>
1209 })),
1210 search: toolRouterOverrides?.search ?? defaultSearchHandler,
1211 toolkits: toolRouterOverrides?.toolkits ?? defaultToolkitsHandler,
1315 - tools: async () => ({
1316 - items: [],
1317 - }),
1212 },
1213 },
1214 };
ts/packages/cli/test/__utils__/services/toolkits-repository-stub.ts
-5
@@ -38,16 +38,11 @@ const unusedRepositoryMethods = {
38 listAuthConfigs: notUsed('listAuthConfigs'),
39 getAuthConfig: notUsed('getAuthConfig'),
40 createAuthConfig: notUsed('createAuthConfig'),
41 - deleteAuthConfig: notUsed('deleteAuthConfig'),
42 - listConnectedAccounts: notUsed('listConnectedAccounts'),
41 getConnectedAccount: notUsed('getConnectedAccount'),
44 - deleteConnectedAccount: notUsed('deleteConnectedAccount'),
45 - createConnectedAccountLink: notUsed('createConnectedAccountLink'),
42 listActiveTriggers: notUsed('listActiveTriggers'),
43 createTrigger: notUsed('createTrigger'),
44 enableTrigger: notUsed('enableTrigger'),
45 disableTrigger: notUsed('disableTrigger'),
50 - deleteTrigger: notUsed('deleteTrigger'),
46 } as const;
47
48 export type GetProjectToolkitsError = Effect.Error<
ts/packages/cli/test/src/commands/connections/connections.list.cmd.test.ts
+44
@@ -1,9 +1,11 @@
1 import { describe, expect, layer } from '@effect/vitest';
2 import { ConfigProvider, Console, Effect } from 'effect';
3 +import { extractErrorDetails } from 'src/effect-errors/logic/errors/extract-error-details';
4 import type { ConnectedAccountItem } from 'src/models/connected-accounts';
5 import { getTerminalCapabilities, TerminalUI } from 'src/services/terminal-ui';
6 import { ComposioUserContext } from 'src/services/user-context';
7 import { cli, TestLive, MockConsole } from 'test/__utils__';
8 +import { routeRequests, stubClientResources } from 'test/__utils__/services/stub-composio-client';
9 import type { TestLiveInput } from 'test/__utils__/services/test-layer';
10
11 const parseJsonFromLines = (lines: ReadonlyArray<string>) => {
@@ -270,6 +272,48 @@ describe('CLI: composio connections remove', () => {
272 );
273 });
274
275 + layer(
276 + TestLive({
277 + baseConfigProvider: testConfigProvider,
278 + terminalUI: terminalUIWithConfirm(true),
279 + })
280 + )(it => {
281 + it.effect('[Given] the API rejects the removal [Then] fails naming the connected account', () =>
282 + Effect.gen(function* () {
283 + const stub = stubClientResources(
284 + ['connectedAccounts'],
285 + routeRequests(
286 + [
287 + {
288 + method: 'DELETE',
289 + path: '/api/v3.1/connected_accounts/',
290 + respond: () =>
291 + Response.json(
292 + {
293 + error: { message: 'Not allowed', code: 1403, slug: 'Forbidden', status: 403 },
294 + },
295 + { status: 403 }
296 + ),
297 + },
298 + ],
299 + () => Response.json({ items: testConnections, next_cursor: null })
300 + )
301 + );
302 + const userContext = yield* ComposioUserContext;
303 + yield* userContext.login('test_api_key', 'org_test');
304 + const failure = yield* cli(['connections', 'remove', 'gmail']).pipe(
305 + Effect.provide(stub.layer),
306 + Effect.flip
307 + );
308 +
309 + expect(failure).toMatchObject({ _tag: 'commands/ConnectionsRemovalRequestError' });
310 + expect(extractErrorDetails(failure).message).toBe(
311 + 'Failed to remove connected account "con_gmail_active".\nCaused by: 403 {"error":{"message":"Not allowed","code":1403,"slug":"Forbidden","status":403}}'
312 + );
313 + })
314 + );
315 + });
316 +
317 const deniedDeleteCalls: string[] = [];
318 layer(
319 TestLive({
ts/packages/cli/test/src/commands/request-failures.client.test.ts new
+255
@@ -0,0 +1,255 @@
1 +import { describe, expect, layer } from '@effect/vitest';
2 +import { ConfigProvider, Effect, Fiber } from 'effect';
3 +import { TestClock } from 'effect/testing';
4 +import type { ComposioClientShape } from '@composio/client/effect';
5 +import { extractErrorDetails } from 'src/effect-errors/logic/errors/extract-error-details';
6 +import { cli, MockConsole, TestLive } from 'test/__utils__';
7 +import {
8 + routeRequests,
9 + stubClientResources,
10 + type StubRequest,
11 +} from 'test/__utils__/services/stub-composio-client';
12 +
13 +const testLayer = () =>
14 + TestLive({
15 + baseConfigProvider: ConfigProvider.fromEnv({ env: { COMPOSIO_USER_API_KEY: 'test_api_key' } }),
16 + fixture: 'global-test-user-id',
17 + });
18 +
19 +const forbidden = () =>
20 + Response.json(
21 + { error: { message: 'Not allowed', code: 1403, slug: 'Forbidden', status: 403 } },
22 + { status: 403 }
23 + );
24 +const FORBIDDEN_DETAIL =
25 + '403 {"error":{"message":"Not allowed","code":1403,"slug":"Forbidden","status":403}}';
26 +
27 +const session = () =>
28 + Response.json({
29 + session_id: 'trs_stub_session',
30 + config: { user_id: 'consumer-user-org_test' },
31 + mcp: { type: 'http', url: 'https://mcp.stub.invalid' },
32 + tool_router_tools: [],
33 + });
34 +
35 +const failureOf = (
36 + args: ReadonlyArray<string>,
37 + resources: ReadonlyArray<keyof ComposioClientShape>,
38 + respond: (request: StubRequest) => Response = forbidden
39 +) =>
40 + Effect.gen(function* () {
41 + const stub = stubClientResources(resources, respond);
42 + return yield* cli(args).pipe(Effect.provide(stub.layer), Effect.flip);
43 + });
44 +
45 +const rejectedRequests: ReadonlyArray<{
46 + readonly command: string;
47 + readonly args: ReadonlyArray<string>;
48 + readonly resources: ReadonlyArray<keyof ComposioClientShape>;
49 + readonly tag: string;
50 + readonly message: string;
51 +}> = [
52 + {
53 + command: 'dev logs tools <id>',
54 + args: ['dev', 'logs', 'tools', 'log_1'],
55 + resources: ['logs'],
56 + tag: 'commands/ToolLogsRequestError',
57 + message: 'Failed to fetch tool log "log_1".',
58 + },
59 + {
60 + command: 'dev logs triggers',
61 + args: ['dev', 'logs', 'triggers'],
62 + resources: ['logs'],
63 + tag: 'commands/TriggerLogsRequestError',
64 + message: 'Failed to fetch trigger logs.',
65 + },
66 + {
67 + command: 'dev logs triggers <id>',
68 + args: ['dev', 'logs', 'triggers', 'log_1'],
69 + resources: ['logs'],
70 + tag: 'commands/TriggerLogsRequestError',
71 + message: 'Failed to fetch trigger log "log_1".',
72 + },
73 + {
74 + command: 'connections list',
75 + args: ['connections', 'list'],
76 + resources: ['connectedAccounts'],
77 + tag: 'commands/ConnectionsListRequestError',
78 + message: 'Failed to list connections.',
79 + },
80 + {
81 + command: 'connections remove',
82 + args: ['connections', 'remove', 'gmail'],
83 + resources: ['connectedAccounts'],
84 + tag: 'commands/ConnectionsRemovalRequestError',
85 + message: 'Failed to list connections.',
86 + },
87 + {
88 + command: 'dev connected-accounts list',
89 + args: ['dev', 'connected-accounts', 'list'],
90 + resources: ['connectedAccounts'],
91 + tag: 'commands/ConnectedAccountsListRequestError',
92 + message: 'Failed to list connected accounts.',
93 + },
94 + {
95 + command: 'link <toolkit> --list',
96 + args: ['link', 'gmail', '--list'],
97 + resources: ['connectedAccounts'],
98 + tag: 'commands/ConnectedAccountsRequestError',
99 + message: 'Failed to list connected accounts for "gmail".',
100 + },
101 +];
102 +
103 +describe('CLI: a request the API rejects', () => {
104 + describe.each(rejectedRequests)(
105 + '[Given] composio $command',
106 + ({ args, resources, tag, message }) => {
107 + layer(testLayer())(it => {
108 + it.effect(
109 + '[Then] the command fails with its own message and the response as the cause',
110 + () =>
111 + Effect.gen(function* () {
112 + const failure = yield* failureOf(args, resources);
113 +
114 + expect(failure).toMatchObject({ _tag: tag, message });
115 + expect(extractErrorDetails(failure).message).toBe(
116 + `${message}\nCaused by: ${FORBIDDEN_DETAIL}`
117 + );
118 + })
119 + );
120 + });
121 + }
122 + );
123 +
124 + layer(testLayer())('[Given] composio link while the new account cannot be fetched', it => {
125 + it.effect('[Then] the wait fails with the fetch message once its retries run out', () =>
126 + Effect.gen(function* () {
127 + const stub = stubClientResources(
128 + ['connectedAccounts'],
129 + routeRequests(
130 + [
131 + {
132 + method: 'GET',
133 + path: '/api/v3.1/connected_accounts/con_test_link',
134 + respond: forbidden,
135 + },
136 + ],
137 + () => Response.json({ items: [], total_pages: 1, current_page: 1, total_items: 0 })
138 + )
139 + );
140 + const fiber = yield* cli(['link', 'gmail', '--no-browser']).pipe(
141 + Effect.provide(stub.layer),
142 + Effect.flip,
143 + Effect.forkChild
144 + );
145 + // Each retry waits on the test clock and then on the stub transport's promise.
146 + yield* TestClock.adjust('2 hours').pipe(
147 + Effect.andThen(TestClock.withLive(Effect.sleep('5 millis'))),
148 + Effect.repeat({ times: 40 })
149 + );
150 + const failure = yield* Fiber.join(fiber);
151 +
152 + expect(failure).toMatchObject({ _tag: 'commands/ConnectedAccountsRequestError' });
153 + expect(extractErrorDetails(failure).message).toBe(
154 + `Failed to fetch connected account "con_test_link".\nCaused by: ${FORBIDDEN_DETAIL}`
155 + );
156 + })
157 + );
158 + });
159 +});
160 +
161 +describe('CLI: a rejected request the command recovers from', () => {
162 + const SESSION_TOOLKITS = '/api/v3.1/tool_router/session/trs_stub_session/toolkits?toolkits=gmail';
163 + const toolkitsInfo = (toolkits: () => Response) =>
164 + Effect.gen(function* () {
165 + const stub = stubClientResources(
166 + ['toolRouter'],
167 + routeRequests([{ method: 'GET', path: SESSION_TOOLKITS, respond: toolkits }], session)
168 + );
169 + yield* cli(['dev', 'toolkits', 'info', 'gmail']).pipe(Effect.provide(stub.layer));
170 + const lines = yield* MockConsole.getLines({ stripAnsi: true });
171 + return { lines, lastPath: stub.requests.at(-1)?.path };
172 + });
173 +
174 + layer(testLayer())('[Given] composio dev toolkits info and rejected session toolkits', it => {
175 + it.effect('[Then] the API message and the browse hint are printed', () =>
176 + Effect.gen(function* () {
177 + const { lines, lastPath } = yield* toolkitsInfo(forbidden);
178 +
179 + expect(lines).toEqual([
180 + 'Using global test user id "global-default"',
181 + 'Not allowed',
182 + 'Browse available toolkits:\n> composio dev toolkits list',
183 + ]);
184 + expect(lastPath).toBe(SESSION_TOOLKITS);
185 + })
186 + );
187 + });
188 +
189 + const LISTING = '/api/v3.1/connected_accounts?';
190 + const withoutExistingAccounts = () => stubClientResources(['connectedAccounts'], forbidden);
191 + const redirect = [
192 + 'Open this URL in your browser to authorize',
193 + '[Redirect URL] https://app.composio.dev/link?token=lt_test_token',
194 + ];
195 + const pending = (fields: Record<string, string>) =>
196 + JSON.stringify(
197 + {
198 + status: 'pending',
199 + message: 'Complete authorization by opening the URL',
200 + connected_account_id: 'con_test_link',
201 + redirect_url: 'https://app.composio.dev/link?token=lt_test_token',
202 + ...fields,
203 + },
204 + null,
205 + 2
206 + );
207 +
208 + layer(testLayer())('[Given] composio link <toolkit> and a rejected account listing', it => {
209 + it.effect('[Then] the link is created as if the user had no account yet', () =>
210 + Effect.gen(function* () {
211 + const stub = withoutExistingAccounts();
212 + yield* cli(['link', 'gmail', '--no-wait']).pipe(Effect.provide(stub.layer));
213 + const lines = yield* MockConsole.getLines({ stripAnsi: true });
214 +
215 + expect(lines).toEqual([
216 + 'Linking gmail...',
217 + ...redirect,
218 + pending({ toolkit: 'gmail', project_type: 'CONSUMER' }),
219 + ]);
220 + expect(stub.requests.map(request => request.path)).toEqual([
221 + `${LISTING}user_ids=consumer-user-org_test&toolkit_slugs=gmail&statuses=ACTIVE&limit=100`,
222 + `${LISTING}user_ids=consumer-user-org_test&statuses=ACTIVE&limit=1000`,
223 + ]);
224 + })
225 + );
226 + });
227 +
228 + layer(testLayer())('[Given] composio link --auth-config and a rejected account listing', it => {
229 + it.effect('[Then] the link is created as if the user had no account yet', () =>
230 + Effect.gen(function* () {
231 + const stub = withoutExistingAccounts();
232 + yield* cli([
233 + 'dev',
234 + 'connected-accounts',
235 + 'link',
236 + '--auth-config',
237 + 'ac_1',
238 + '--user-id',
239 + 'user_1',
240 + '--no-wait',
241 + ]).pipe(Effect.provide(stub.layer));
242 + const lines = yield* MockConsole.getLines({ stripAnsi: true });
243 +
244 + expect(lines).toEqual([
245 + 'Creating link session...',
246 + ...redirect,
247 + pending({ project_type: 'DEVELOPER' }),
248 + ]);
249 + expect(stub.requests.map(request => request.path)).toEqual([
250 + `${LISTING}user_ids=user_1&auth_config_ids=ac_1&statuses=ACTIVE&limit=100`,
251 + ]);
252 + })
253 + );
254 + });
255 +});
ts/packages/cli/test/src/commands/toolkits/toolkits.list.cmd.test.ts
+58
@@ -3,6 +3,7 @@ import { ConfigProvider, DateTime, Effect } from 'effect';
3 import { cli, TestLive, MockConsole } from 'test/__utils__';
4 import type { TestLiveInput } from 'test/__utils__/services/test-layer';
5 import type { Toolkits } from 'src/models/toolkits';
6 +import { routeRequests, stubClientResources } from 'test/__utils__/services/stub-composio-client';
7
8 const testToolkits: Toolkits = [
9 {
@@ -158,6 +159,63 @@ describe('CLI: composio dev toolkits list', () => {
159 }
160 );
161
162 + layer(
163 + TestLive({
164 + baseConfigProvider: testConfigProvider,
165 + toolkitsData,
166 + fixture: 'global-test-user-id',
167 + })
168 + )('[Given] the API rejects the session toolkits', it => {
169 + it.effect('[Then] the catalog is listed without connection status and without an error', () =>
170 + Effect.gen(function* () {
171 + const stub = stubClientResources(
172 + ['toolRouter'],
173 + routeRequests(
174 + [
175 + {
176 + method: 'GET',
177 + path: '/api/v3.1/tool_router/session/trs_stub_session/toolkits',
178 + respond: () =>
179 + Response.json(
180 + {
181 + error: { message: 'Not allowed', code: 1403, slug: 'Forbidden', status: 403 },
182 + },
183 + { status: 403 }
184 + ),
185 + },
186 + ],
187 + () =>
188 + Response.json({
189 + session_id: 'trs_stub_session',
190 + config: { user_id: 'global-default' },
191 + mcp: { type: 'http', url: 'https://mcp.stub.invalid' },
192 + tool_router_tools: [],
193 + })
194 + )
195 + );
196 + yield* cli(['dev', 'toolkits', 'list']).pipe(Effect.provide(stub.layer));
197 + const lines = yield* MockConsole.getLines({ stripAnsi: true });
198 +
199 + expect(lines.slice(0, 3)).toEqual([
200 + 'Using global test user id "global-default"',
201 + 'To show status for a specific user, use `--user-id`.',
202 + 'Fetching toolkits...',
203 + ]);
204 + expect(lines[3]).toContain('Listing 3 of 3 toolkits');
205 + expect(lines).toHaveLength(6);
206 + expect(JSON.parse(String(lines.at(-1)))).toEqual([
207 + expect.objectContaining({ slug: 'gmail', latest_version: '20250909', connected: null }),
208 + expect.objectContaining({ slug: 'slack', latest_version: null, connected: null }),
209 + expect.objectContaining({ slug: 'github', latest_version: '20260101', connected: null }),
210 + ]);
211 + expect(stub.requests.map(request => request.path)).toEqual([
212 + '/api/v3.1/tool_router/session',
213 + '/api/v3.1/tool_router/session/trs_stub_session/toolkits?limit=30',
214 + ]);
215 + })
216 + );
217 + });
218 +
219 layer(TestLive())('[Given] no API key', it => {
220 it.effect('warns user to login', () =>
221 Effect.gen(function* () {
ts/packages/cli/test/src/effects/request-error.test.ts new
+62
@@ -0,0 +1,62 @@
1 +import { describe, expect, it } from '@effect/vitest';
2 +import { Effect } from 'effect';
3 +import { extractErrorDetails } from 'src/effect-errors/logic/errors/extract-error-details';
4 +import { failedWith, requestError } from 'src/effects/request-error';
5 +
6 +class WidgetsRequestError extends requestError('commands/WidgetsRequestError') {}
7 +
8 +describe('requestError', () => {
9 + it('names the error by its tag and keeps the message and the cause', () => {
10 + const cause = new TypeError('fetch failed');
11 + const error = new WidgetsRequestError({ message: 'Failed to list widgets.', cause });
12 +
13 + expect(error).toBeInstanceOf(Error);
14 + expect(error._tag).toBe('commands/WidgetsRequestError');
15 + expect(error.name).toBe('commands/WidgetsRequestError');
16 + expect(error.message).toBe('Failed to list widgets.');
17 + expect(error.cause).toBe(cause);
18 + expect(extractErrorDetails(error)).toStrictEqual({
19 + isPlainString: false,
20 + type: 'commands/WidgetsRequestError',
21 + message: 'Failed to list widgets.\nCaused by: fetch failed',
22 + });
23 + });
24 +});
25 +
26 +describe('failedWith', () => {
27 + it.effect('replaces a failure with the error, keeping the failure as its cause', () =>
28 + Effect.gen(function* () {
29 + const cause = new TypeError('fetch failed');
30 +
31 + const error = yield* Effect.fail(cause).pipe(
32 + failedWith(WidgetsRequestError, 'Failed to list widgets.'),
33 + Effect.flip
34 + );
35 +
36 + expect(error).toBeInstanceOf(WidgetsRequestError);
37 + expect(error.message).toBe('Failed to list widgets.');
38 + expect(error.cause).toBe(cause);
39 + })
40 + );
41 +
42 + it.effect('recovers by the tag of the error it raised', () =>
43 + Effect.gen(function* () {
44 + const recovered = yield* Effect.fail('unreachable').pipe(
45 + failedWith(WidgetsRequestError, 'Failed to list widgets.'),
46 + Effect.catchTag('commands/WidgetsRequestError', error => Effect.succeed(error.message))
47 + );
48 +
49 + expect(recovered).toBe('Failed to list widgets.');
50 + })
51 + );
52 +
53 + it.effect('leaves a success as it is', () =>
54 + Effect.gen(function* () {
55 + const value = yield* Effect.succeed(42).pipe(
56 + failedWith(WidgetsRequestError, 'Failed to list widgets.')
57 + );
58 +
59 + expect(value).toBe(42);
60 + })
61 + );
62 +});
ts/packages/cli/test/src/services/composio-client-interrupt.test.ts
+7 -4
@@ -50,7 +50,7 @@ const platformLayer = () =>
50 )
51 );
52
53 -const withRepository = () => Layer.provide(ComposioToolkitsRepository.Default, platformLayer());
53 +const withSingleton = () => Layer.provide(ComposioClientSingleton.Default, platformLayer());
54
55 // The real executor over the real client singleton, plus every service that
56 // `execute` and session creation require, with the credential store mocked above.
@@ -107,10 +107,13 @@ describe('interrupting a single-shot client request', () => {
107 Effect.gen(function* () {
108 const pending = pendingRequest();
109 const fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementationOnce(pending.respond);
110 - const repository = yield* ComposioToolkitsRepository;
110 + const client = yield* Effect.flatMap(ComposioClientSingleton, singleton => singleton.get());
111
112 const fiber = yield* Effect.forkChild(
113 - repository.listConnectedAccounts({ user_ids: ['default'], statuses: ['ACTIVE'] })
113 + client.connectedAccounts.list(
114 + { user_ids: ['default'], statuses: ['ACTIVE'] },
115 + { decode: false }
116 + )
117 );
118 const requestSignal = yield* pending.signal;
119 expect(requestSignal.aborted).toBe(false);
@@ -120,7 +123,7 @@ describe('interrupting a single-shot client request', () => {
123 expect(requestSignal.aborted).toBe(true);
124 expect(fetchSpy).toHaveBeenCalledTimes(1);
125 expect(requestUrl(fetchSpy.mock.calls[0]).pathname).toBe('/api/v3.1/connected_accounts');
123 - }).pipe(Effect.provide(withRepository()))
126 + }).pipe(Effect.provide(withSingleton()))
127 );
128
129 it.effect('tool router session creation aborts the in-flight create request', () =>
ts/packages/cli/test/src/services/composio-clients.test.ts
+4 -50
@@ -587,64 +587,18 @@ describe('composio-clients', () => {
587 };
588 vi.spyOn(globalThis, 'fetch')
589 .mockResolvedValueOnce(jsonResponse(authConfig))
590 - .mockResolvedValueOnce(
591 - jsonResponse({
592 - items: [connectedAccount],
593 - total_items: 1,
594 - total_pages: 1,
595 - current_page: 1,
596 - next_cursor: null,
597 - })
598 - );
590 + .mockResolvedValueOnce(jsonResponse(connectedAccount));
591 const repository = yield* ComposioToolkitsRepository;
592
593 const decodedAuthConfig = yield* repository.getAuthConfig('ac_1');
602 - const accounts = yield* repository.listConnectedAccounts({});
594 + const account = yield* repository.getConnectedAccount('con_1');
595
596 expect(JSON.stringify(decodedAuthConfig)).not.toContain('secret');
605 - expect(JSON.stringify(accounts)).not.toContain('secret');
606 - expect(accounts.items.map(item => item.id)).toEqual(['con_1']);
597 + expect(JSON.stringify(account)).not.toContain('secret');
598 + expect(account.id).toBe('con_1');
599 }).pipe(Effect.provide(withRepository))
600 );
601
610 - it.effect(
611 - 'listConnectedAccounts returns an account whose status this build does not know',
612 - () =>
613 - Effect.gen(function* () {
614 - vi.spyOn(globalThis, 'fetch').mockResolvedValue(
615 - jsonResponse({
616 - items: [
617 - {
618 - id: 'con_1',
619 - status: 'QUARANTINED',
620 - status_reason: null,
621 - is_disabled: false,
622 - user_id: 'default',
623 - toolkit: { slug: 'gmail' },
624 - auth_config: {
625 - id: 'ac_1',
626 - auth_scheme: 'OAUTH2',
627 - is_composio_managed: true,
628 - is_disabled: false,
629 - },
630 - created_at: '2026-01-01T00:00:00Z',
631 - updated_at: '2026-01-01T00:00:00Z',
632 - },
633 - ],
634 - total_items: 1,
635 - total_pages: 1,
636 - current_page: 1,
637 - next_cursor: null,
638 - })
639 - );
640 - const repository = yield* ComposioToolkitsRepository;
641 -
642 - const accounts = yield* repository.listConnectedAccounts({});
643 -
644 - expect(accounts.items.map(item => item.status)).toEqual(['QUARANTINED']);
645 - }).pipe(Effect.provide(withRepository))
646 - );
647 -
602 it.effect('listActiveTriggers defaults the page counts a response leaves out', () =>
603 Effect.gen(function* () {
604 vi.spyOn(globalThis, 'fetch').mockResolvedValue(
ts/packages/cli/test/src/services/tool-router-session-connections.test.ts new
+31
@@ -0,0 +1,31 @@
1 +import { describe, expect, it } from '@effect/vitest';
2 +import { Effect } from 'effect';
3 +import { resolveToolRouterSessionConnections } from 'src/services/tool-router-session-connections';
4 +import { stubComposioClient } from 'test/__utils__/services/stub-composio-client';
5 +
6 +const forbidden = () =>
7 + Response.json(
8 + { error: { message: 'Not allowed', code: 1403, slug: 'Forbidden', status: 403 } },
9 + { status: 403 }
10 + );
11 +
12 +describe('resolveToolRouterSessionConnections', () => {
13 + it.effect.each([
14 + { listing: 'the listing for the requested toolkits', toolkits: ['gmail'] },
15 + { listing: 'the shared listing of every active account', toolkits: undefined },
16 + ])('resolves no connections when the API rejects $listing', ({ toolkits }) =>
17 + Effect.gen(function* () {
18 + const { client, requests } = stubComposioClient(forbidden);
19 +
20 + const context = yield* resolveToolRouterSessionConnections(client, 'user_1', { toolkits });
21 +
22 + expect(context).toEqual({
23 + connectedToolkits: [],
24 + authConfigs: undefined,
25 + connectedAccounts: undefined,
26 + availableConnectedAccounts: undefined,
27 + });
28 + expect(requests).toHaveLength(1);
29 + })
30 + );
31 +});