@devries-cameron20 / composio Mirror · read-only / commits / 1d24846e5
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.

Mirrored from https://github.com/Camo67/composio.git

Synced Nov 21, 09:45 UTC

refactor(cli): call the API through `@composio/client/effect` (#4853)

This PR: - builds on top of https://github.com/ComposioHQ/composio/pull/4850 - makes every Composio API request in the CLI go through the Effect client from `@composio/client/effect`, one cached client per (user key, org, project) built with `make`; the promise client is gone from CLI source and tests - lets the client's tagged errors (`@composio/client/NotFoundError`, `APIConnectionError`, `DecodeError`, …) flow to callers and removes `services/HttpServerError`; commands that report an API failure share `catchClientApiError` - replaces the pagination helper with the client's cursor streams - turns on client response decoding for the reads the CLI consumes through client types, backed by a CLI-local schema loader table; calls pass `decode: false` when the CLI validates with its own schema, when the call is not a read, and on reads the CLI must tolerate drift in (`connectedAccounts.list`, `triggerInstances.listActive`, session info, tool detail) - reduces `src/services/composio-clients.ts` from 1,397 to 487 lines by moving the account helpers, toolkit version validation, resource operations, shared errors and CLI-owned response schemas to their own modules - adds an oxlint rule that rejects value imports of `@composio/client` and `@composio/client/pagination` from CLI `src/` (type-only imports stay allowed) - updates the CLI agent guidance to describe the new design ## Context Command output is meant to be unchanged. The deliberate differences: - A response that fails client decoding prints the operation, the request id and a `composio upgrade` hint, and never the response content. These responses were not validated before. - An API error that no command catches shows the client's tag as its title (for example `@composio/client/NotFoundError`) where it showed `services/HttpServerError`. - Connection failures print the transport description (for example `fetch failed: connect ECONNREFUSED 127.0.0.1:1`) where some paths printed `Error: Connection error.` - A request the client refuses to build (for example a `..` path parameter) reaches the top-level error printer instead of the command's fallback message. - Interrupting a tool execution, session creation or account listing now aborts the HTTP request. The promise client's root module is still in the compiled binary: `tool-file-uploads.ts` lazily imports `@composio/core`, whose root entry imports it. Removing that needs a `@composio/core` subpath export and is out of scope here. Verified locally: `pnpm typecheck`, the CLI suite (144 files, 1478 passed, 1 skipped), `oxlint` on `ts/packages/cli`, `validate:boundaries`, `validate:agent-skills`, `validate:skill-routing`. Checked against the live API with Bun scripts (`source .envrc && bun <script>`): - 23 read-only commands (success and not-found paths across `tools`, `triggers`, `search`, `connections`, `orgs`, `dev toolkits`, `dev auth-configs`, `dev connected-accounts`, `dev projects`, `dev logs`) run before and after: 22 are byte-identical in stdout, stderr and exit code. The other differs only in the request id and a stack-trace path on a 401. - The client-decoded operations reachable with a project key (`tools.list`, `logs.triggers.list`, `cli.realtime.credentials`) and through the CLI (`org.list`, `org.project.list`, `logs.tools.list`, `logs.tools.retrieve`, `toolRouter.session.search`, `toolRouter.session.toolkits`) validated with no decode failure. `logs.triggers.retrieve` and `org.consumer.listConnectedToolkits` were not exercised live. - `composio --version` on the compiled binary: 102.4 ms before, 102.5 ms after (median of 40 runs); the binary grew by 66 KB. ```mermaid flowchart TB CMD[Commands and effects] --> REPO[Toolkits and session repositories] CMD --> SVC[Services that hold a client] CMD --> ACCT[Account helpers] REPO --> FACTORY[ComposioClientSingleton: one client per scope] SVC --> FACTORY ACCT --> FACTORY FACTORY --> CLIENT[Effect client] CLIENT --> LOADERS[CLI schema loader table] CLIENT --> FETCH[Counting fetch] CLIENT -->|tagged errors| CMD ```

Alberto Schiabel committed Oct 15, 2026 at 15:02 UTC 1d24846e56e341ba9e99117a4bd76034008dc781
95 files changed +5429 -2851
.agents/skills/effect-v4/references/core-patterns.md
+1 -1
@@ -86,7 +86,7 @@ The established convention in this repo — stated in `ts/packages/cli/AGENTS.md
86 `Effect.fail` for an expected failure; give it a `Data.TaggedError` with structured
87 fields and a preserved cause, then recover with `catchTag`/`catchTags`. This is
88 unchanged from v3 and is what nearly every error in `src/services/*.ts` uses, e.g.
89 -`ts/packages/cli/src/services/composio-clients.ts`:
89 +`ts/packages/cli/src/services/toolkit-version-validation.ts`:
90
91 ```ts
92 import { Data } from 'effect';
.oxlintrc.json
+20
@@ -156,6 +156,16 @@
156 {
157 "name": "@effect/platform-bun",
158 "message": "Import the module by subpath, e.g. @effect/platform-bun/BunFileSystem; the package barrel is not part of the Effect v4 layout."
159 + },
160 + {
161 + "name": "@composio/client",
162 + "allowTypeImports": true,
163 + "message": "Call the API through the client from @composio/client/effect, obtained from ComposioClientSingleton. Type-only imports are allowed."
164 + },
165 + {
166 + "name": "@composio/client/pagination",
167 + "allowTypeImports": true,
168 + "message": "Call the API through the client from @composio/client/effect, obtained from ComposioClientSingleton. Type-only imports are allowed."
169 }
170 ],
171 "patterns": [
@@ -273,6 +283,16 @@
283 "name": "@effect/platform-bun",
284 "message": "Import the module by subpath, e.g. @effect/platform-bun/BunFileSystem; the package barrel is not part of the Effect v4 layout."
285 },
286 + {
287 + "name": "@composio/client",
288 + "allowTypeImports": true,
289 + "message": "Call the API through the client from @composio/client/effect, obtained from ComposioClientSingleton. Type-only imports are allowed."
290 + },
291 + {
292 + "name": "@composio/client/pagination",
293 + "allowTypeImports": true,
294 + "message": "Call the API through the client from @composio/client/effect, obtained from ComposioClientSingleton. Type-only imports are allowed."
295 + },
296 { "name": "zod", "message": "Use Schema from effect for tool input validation." }
297 ],
298 "patterns": [
ts/packages/cli/AGENTS.md
+4 -4
@@ -66,7 +66,7 @@ Named options use `Flag.String()`, `Flag.Boolean()`, `Flag.Int()`, `Flag.Literal
66 | Service | Purpose |
67 | ---------------------------------- | ---------------------------------------------------------------------------------------------- |
68 | `ComposioUserContext` | Auth state — reads/writes `~/.composio/user-config.json`, merges env vars |
69 -| `ComposioClientSingleton` | Builds and caches `@composio/client` instances per key, org, and project; owns request metrics |
69 +| `ComposioClientSingleton` | Builds and caches `@composio/client/effect` clients per key, org, and project; counts requests |
70 | `ComposioSessionRepository` | Creates OAuth2 sessions, polls until `linked` state |
71 | `ComposioToolkitsRepository` | API client — fetches toolkits, tools, trigger types; validates versions |
72 | `ComposioToolkitsRepositoryCached` | Decorator over base repository with file-based caching and graceful fallback |
@@ -74,7 +74,7 @@ Named options use `Flag.String()`, `Flag.Boolean()`, `Flag.Int()`, `Flag.Literal
74 | `JsPackageManagerDetector` | Detects npm/pnpm/yarn/bun for install instructions |
75 | `UpgradeBinary` | Fetches latest release from GitHub, downloads and replaces binary |
76
77 -Every Composio API request goes through a `@composio/client` instance from `ComposioClientSingleton` (`src/services/composio-clients.ts`). Clients are built with `Composio.fromEnv({}, …)` so the ambient environment is never read, with `logLevel: 'off'`, the CLI's own `defaultHeaders` (`x-user-api-key`, plus `x-org-id`/`x-project-id` when both are known), and a counting `fetch` (`composio-client-metrics.ts`). Explicitly configured HTTP base URLs remain supported without an additional environment flag. Repository methods and the account helpers (`listOrganizations`, `getSessionInfo*`, `resolveConsumerProject`, …) run client calls through one module-private `request` helper that maps `APIError` to `services/HttpServerError` with `status`, `details`, and `requestId`. Endpoints the client does not type yet use `client.get`/`client.post`; inside `composio-clients.ts` those go through the same `request` helper, while `src/services/tool-permissions.ts` reaches them through its own `requestJson`, which raises `services/ToolPermissionsRequestError` because its callers fail closed on that tag. Do not add a raw `fetch` to the Composio backend from `src/commands`, `src/effects`, or `src/services` — the one sanctioned exception is the bundled companion runtime (`run-helpers-runtime.ts`), which runs in the user's spawned process outside the Effect runtime. Tool-execution and proxy errors are classified from `APIError.details` by `src/utils/api-error-extraction.ts`.
77 +Every Composio API request goes through an Effect client from `@composio/client/effect`, obtained from `ComposioClientSingleton` (`src/services/composio-clients.ts`). Clients are built with `make`, which never reads the ambient environment: the user key and base URL come from the CLI's own configuration. Each client is built with `deprecationNotices: 'off'`, the CLI's own `defaultHeaders` (provenance headers, `x-user-api-key`, plus `x-org-id`/`x-project-id` when both are known), and a counting `fetch` (`composio-client-metrics.ts`) provided as the transport's `FetchHttpClient.Fetch`. Explicitly configured HTTP base URLs remain supported without an additional environment flag. `composio-clients.ts` holds only client construction and the two repositories. The repository's auth-config, connected-account, trigger-instance, search, and single-item methods live in `src/services/composio-resource-operations.ts`; the account helpers (`listOrganizations`, `getSessionInfo*`, `resolveConsumerProject`, `createProjectApiKey`, `getLatestToolVersion`, …) in `src/services/composio-account.ts`; toolkit version validation and its errors (`InvalidToolkitsError`, `InvalidToolkitVersionsError`) in `src/services/toolkit-version-validation.ts`; the shared error types (`ClientError`, `HttpDecodingError`, `ComposioClientConfigurationError`) in `src/services/composio-errors.ts`; and the shared `decode` helper and `undecoded` request option in `src/services/composio-request.ts`. There is no CLI error wrapper around a request: the client's tagged errors (`@composio/client/NotFoundError`, `APIConnectionError`, `DecodeError`, …) flow to callers, which recover with `Effect.catchTag` or the client's `isAPIError` guard. Commands that report an API failure and continue with a fallback share one handler, `catchClientApiError` (`src/effects/handle-http-error.ts`). Endpoints the client does not type use the raw `client.get`/`client.post`; `src/services/tool-permissions.ts` reaches them through its own `requestJson`, which raises `services/ToolPermissionsRequestError` because its callers fail closed on that tag. Do not add a raw `fetch` to the Composio backend from `src/commands`, `src/effects`, or `src/services` — the one sanctioned exception is the bundled companion runtime (`run-helpers-runtime.ts`), which runs in the user's spawned process outside the Effect runtime. oxlint rejects value imports of the `@composio/client` root and `@composio/client/pagination` from CLI `src/`; type-only imports are allowed. Client errors are classified for display by `src/utils/api-error-extraction.ts`.
78
79 Services are `Context.Service` classes that export a `<Name>Shape` type and an explicit `static readonly Default` layer (`Layer.effect` / `Layer.sync`, dependencies provided with `Layer.provide`). Build a test double with `Service.of({ ... })`; there are no generated accessors or constructors.
80
@@ -110,7 +110,7 @@ Steps 3–4 (and the TypeScript compiler they need) ship as the `generation-runt
110
111 ### Key Dependencies
112
113 -`effect` (pinned `4.0.3`; `@effect/cli` and `@effect/platform` no longer exist as separate packages — folded into `effect`'s barrel and `effect/{cli,http,process}`), `@effect/platform-bun`, `@effect/vitest` (same exact pin), `@clack/prompts` (terminal UI — stderr by default), `picocolors`, `@composio/client` (owned Composio API client, `2.0.0-rc.14` via the workspace catalog), `@composio/core` (types), `@composio/ts-builders` (AST gen), `@composio/cli-keyring` (OS credential store), `@composio/json-schema-to-effect-schema`, `semver`, `open`, `extract-zip`.
113 +`effect` (pinned `4.0.3`; `@effect/cli` and `@effect/platform` no longer exist as separate packages — folded into `effect`'s barrel and `effect/{cli,http,process}`), `@effect/platform-bun`, `@effect/vitest` (same exact pin), `@clack/prompts` (terminal UI — stderr by default), `picocolors`, `@composio/client` (owned Composio API client, `2.0.0-rc.14` via the workspace catalog; the CLI calls it through the `@composio/client/effect` entry point and imports only types from the rest of the package), `@composio/core` (types), `@composio/ts-builders` (AST gen), `@composio/cli-keyring` (OS credential store), `@composio/json-schema-to-effect-schema`, `semver`, `open`, `extract-zip`.
114
115 ## Output Conventions: Composable CLI Output
116
@@ -169,7 +169,7 @@ Each `Arr.bind` adds one independent axis to the generated cases.
169
170 - Never branch on an Effect value's internal tag field directly. Use the owning module's public refinement or matcher (`Option`, `Result`, `Exit`, `Cause`, `CliError`), `Match.valueTags` for exhaustive unions, or `Predicate.isTagged` for a single narrowing guard.
171 - Do not wrap a plain `Error` in `Effect.fail` for expected failures. Give the failure a meaningful `Data.TaggedError` type with structured fields and a preserved cause, then recover with `catchTag` / `catchTags`. Reserve `Effect.die` and `Effect.dieMessage` for impossible invariants.
172 -- Treat `unknown`, JSON, and persisted state as trust boundaries. Decode them with `effect/Schema` or narrow them with `Predicate`; an `as` assertion is not validation, and hand-rolled structural guards (`'x' in obj` / `typeof` chains) are not a substitute for a schema. A Composio API response that `@composio/client` types is already a contract the CLI owns end to end, so trust it the way `@composio/core` does rather than re-decoding it. Keep `effect/Schema` for the payloads the client does not type for you: the persisted catalog cache files (`src/models/toolkits.ts`, `tools.ts`, `trigger-types.ts`), anything printed to stdout that must exclude credential-bearing fields (the auth-config and connected-account allowlists, including the `auth-configs create` response), the `ToolkitSlug` path-safety check, the `Session` `DateTime` transform, `TriggerInstanceItems`, and every escape-hatch response fetched with `client.get`/`client.post` (`LatestToolVersionResponse`, and the consumer config and permission payloads in `tool-permissions.ts`). `effect/Schema` is the CLI's schema tool — do not introduce zod here (zod is the convention in the SDK packages and docs).
172 +- Treat `unknown`, JSON, and persisted state as trust boundaries. Decode them with `effect/Schema` or narrow them with `Predicate`; an `as` assertion is not validation, and hand-rolled structural guards (`'x' in obj` / `typeof` chains) are not a substitute for a schema. Each typed API response is validated at most once. The CLI's own schema validates a response the CLI transforms, filters for stdout, or writes to a cache file: the catalog models (`src/models/toolkits.ts`, `tools.ts`, `trigger-types.ts`), the auth-config and connected-account allowlists that keep credential-bearing fields off stdout (including the list responses and the `auth-configs create` response in `src/models/auth-configs.ts` and `connected-accounts.ts`), the `ToolkitSlug` path-safety check, the `Session` `DateTime` transform, and `TriggerInstanceItems`. Those calls pass `decode: false` and decode with the CLI schema, failing with `services/HttpDecodingError`. The client's generated schema validates every other read, through the loader table in `src/services/composio-schema-loaders.ts`; a mismatch fails with the client's `DecodeError`. Calls that are not reads pass `decode: false`, because failing after the server acted would invite a retry that repeats the side effect, and so do the two endpoints the CLI reads leniently on purpose (`connectedAccounts.list`, which tolerates unknown statuses, and `triggerInstances.listActive`, whose page counts the CLI defaults). A typed call with no loader and no `decode: false` fails before it is sent, so adding a client-decoded read means adding its loader to the table. Responses fetched with the raw `client.get`/`client.post` are untyped and always need a CLI schema (`LatestToolVersionResponse` in `src/models/tools.ts`, and the consumer config and permission payloads in `tool-permissions.ts`). `effect/Schema` is the CLI's schema tool — do not introduce zod here (zod is the convention in the SDK packages and docs).
173 - Do not inspect private `effect/cli` internals (parser state, `HelpDoc` string shapes, `CliError` suggestion machinery). `Command.runWith` renders help and parse/validation errors itself — see the entry-point section above — so command-tree introspection must stay on the public `Command.Any` surface (`name`, `alias`, `subcommands`). `CliError.InvalidValue` takes structured `{ option, value, expected, kind }` fields, not a free-form message — commands that need a custom validation message raise a local `Data.TaggedError` instead (see `src/commands/login.cmd.ts`'s `LoginOptionError`) and let it flow through the existing `effect-errors` pretty-printer, not a hand-built `CliError`.
174 - Prefer `Effect.mapError`, `Effect.matchEffect`, and typed recovery over `Effect.catch` blocks (the v4 name for what was `Effect.catchAll`) that flatten distinct failures into one message-only error.
175
ts/packages/cli/src/commands/auth-configs/commands/auth-configs.create.cmd.ts
+6 -9
@@ -5,7 +5,7 @@ import { parseJsonRecord } from 'src/utils/parse-json';
5 import { ComposioToolkitsRepository } from 'src/services/composio-clients';
6 import { TerminalUI } from 'src/services/terminal-ui';
7 import { requireAuth } from 'src/effects/require-auth';
8 -import { handleHttpServerError } from 'src/effects/handle-http-error';
8 +import { catchClientApiError } from 'src/effects/handle-http-error';
9 import { redact } from 'src/ui/redact';
10 import { formatAuthConfigCreated } from '../format';
11
@@ -117,14 +117,11 @@ export const authConfigsCmd$Create = Command.make(
117 .withSpinner('Creating auth config...', repo.createAuthConfig(params))
118 .pipe(
119 Effect.asSome,
120 - Effect.catchTag(
121 - 'services/HttpServerError',
122 - handleHttpServerError(ui, {
123 - fallbackMessage: 'Failed to create auth config.',
124 - hint: `Check available auth schemes for "${toolkit}":\n> composio dev toolkits info "${toolkit}"`,
125 - fallbackValue: Option.none(),
126 - })
127 - )
120 + catchClientApiError(ui, {
121 + fallbackMessage: 'Failed to create auth config.',
122 + hint: `Check available auth schemes for "${toolkit}":\n> composio dev toolkits info "${toolkit}"`,
123 + fallbackValue: Option.none(),
124 + })
125 );
126
127 if (Option.isNone(resultOpt)) {
ts/packages/cli/src/commands/auth-configs/commands/auth-configs.info.cmd.ts
+6 -9
@@ -3,7 +3,7 @@ import { Argument, Command } from 'effect/cli';
3 import { ComposioToolkitsRepository } from 'src/services/composio-clients';
4 import { TerminalUI } from 'src/services/terminal-ui';
5 import { requireAuth } from 'src/effects/require-auth';
6 -import { handleHttpServerError } from 'src/effects/handle-http-error';
6 +import { catchClientApiError } from 'src/effects/handle-http-error';
7 import { formatAuthConfigInfo } from '../format';
8
9 const id = Argument.String('id').pipe(
@@ -42,14 +42,11 @@ export const authConfigsCmd$Info = Command.make('info', { id }, ({ id }) =>
42 .withSpinner(`Fetching auth config "${idValue}"...`, repo.getAuthConfig(idValue))
43 .pipe(
44 Effect.asSome,
45 - Effect.catchTag(
46 - 'services/HttpServerError',
47 - handleHttpServerError(ui, {
48 - fallbackMessage: `Failed to fetch auth config "${idValue}".`,
49 - hint: 'Browse available auth configs:\n> composio dev auth-configs list',
50 - fallbackValue: Option.none(),
51 - })
52 - )
45 + catchClientApiError(ui, {
46 + fallbackMessage: `Failed to fetch auth config "${idValue}".`,
47 + hint: 'Browse available auth configs:\n> composio dev auth-configs list',
48 + fallbackValue: Option.none(),
49 + })
50 );
51
52 if (Option.isNone(itemOpt)) {
ts/packages/cli/src/commands/connected-accounts/commands/connected-accounts.info.cmd.ts
+6 -9
@@ -3,7 +3,7 @@ import { Effect, Option } from 'effect';
3 import { ComposioToolkitsRepository } from 'src/services/composio-clients';
4 import { TerminalUI } from 'src/services/terminal-ui';
5 import { requireAuth } from 'src/effects/require-auth';
6 -import { handleHttpServerError } from 'src/effects/handle-http-error';
6 +import { catchClientApiError } from 'src/effects/handle-http-error';
7 import { formatConnectedAccountInfo } from '../format';
8
9 const id = Argument.String('id').pipe(
@@ -41,14 +41,11 @@ export const connectedAccountsCmd$Info = Command.make('info', { id }, ({ id }) =
41 .withSpinner(`Fetching connected account "${idValue}"...`, repo.getConnectedAccount(idValue))
42 .pipe(
43 Effect.asSome,
44 - Effect.catchTag(
45 - 'services/HttpServerError',
46 - handleHttpServerError(ui, {
47 - fallbackMessage: `Failed to fetch connected account "${idValue}".`,
48 - hint: 'Browse available connected accounts:\n> composio dev connected-accounts list',
49 - fallbackValue: Option.none(),
50 - })
51 - )
44 + catchClientApiError(ui, {
45 + fallbackMessage: `Failed to fetch connected account "${idValue}".`,
46 + hint: 'Browse available connected accounts:\n> composio dev connected-accounts list',
47 + fallbackValue: Option.none(),
48 + })
49 );
50
51 if (Option.isNone(itemOpt)) {
ts/packages/cli/src/commands/connected-accounts/commands/connected-accounts.link.cmd.ts
+79 -54
@@ -1,6 +1,6 @@
1 import { Argument, Command, Flag } from 'effect/cli';
2 import { Data, Effect, Option, Schedule } from 'effect';
3 -import type { Composio as RawComposioClient } from '@composio/client';
3 +import type { ComposioClientShape } from '@composio/client/effect';
4 import open from 'open';
5 import { ComposioUserContext } from 'src/services/user-context';
6 import { TerminalUI } from 'src/services/terminal-ui';
@@ -8,7 +8,8 @@ import { requireAuth } from 'src/effects/require-auth';
8 import { resolveToolRouterSession } from 'src/effects/create-tool-router-session';
9 import { extractApiErrorDetails, extractMessage } from 'src/utils/api-error-extraction';
10 import { ProjectContext } from 'src/services/project-context';
11 -import { ComposioClientSingleton, getSessionInfoByUserApiKey } from 'src/services/composio-clients';
11 +import { ComposioClientSingleton } from 'src/services/composio-clients';
12 +import { getSessionInfoByUserApiKey } from 'src/services/composio-account';
13 import { linkApolloIdentityForAnalytics } from 'src/analytics/dispatch';
14 import {
15 formatResolveCommandProjectError,
@@ -137,7 +138,7 @@ const showRedirectUrl = (
138
139 const waitForActiveConnection = (
140 ui: TerminalUI,
140 - client: RawComposioClient,
141 + client: ComposioClientShape,
142 connectedAccountId: string,
143 redirectUrl: string,
144 noBrowser: boolean
@@ -172,14 +173,17 @@ const waitForActiveConnection = (
173 yield* ui.useMakeSpinner('Waiting for authentication...', spinner =>
174 Effect.retry(
175 Effect.gen(function* () {
175 - const account = yield* Effect.tryPromise({
176 - try: () => client.connectedAccounts.retrieve(connectedAccountId),
177 - catch: cause =>
178 - new ConnectedAccountsRequestError({
179 - message: `Failed to fetch connected account "${connectedAccountId}".`,
180 - cause,
181 - }),
182 - });
176 + const account = yield* client.connectedAccounts
177 + .retrieve(connectedAccountId, { decode: false })
178 + .pipe(
179 + Effect.mapError(
180 + cause =>
181 + new ConnectedAccountsRequestError({
182 + message: `Failed to fetch connected account "${connectedAccountId}".`,
183 + cause,
184 + })
185 + )
186 + );
187 if (account.status === 'ACTIVE') {
188 return account;
189 }
@@ -322,26 +326,31 @@ const resolveNormalizedAliasOption = (alias: Option.Option<string>) =>
326 });
327
328 const listActiveConnectedAccounts = (params: {
325 - readonly client: RawComposioClient;
329 + readonly client: ComposioClientShape;
330 readonly userId: string;
331 readonly toolkitSlug?: string;
332 readonly authConfigId?: string;
333 }) =>
330 - Effect.tryPromise({
331 - try: () =>
332 - params.client.connectedAccounts.list({
334 + params.client.connectedAccounts
335 + .list(
336 + {
337 user_ids: [params.userId],
338 toolkit_slugs: params.toolkitSlug ? [params.toolkitSlug] : undefined,
339 auth_config_ids: params.authConfigId ? [params.authConfigId] : undefined,
340 statuses: ['ACTIVE'],
341 limit: 100,
338 - }),
339 - catch: cause =>
340 - new ConnectedAccountsRequestError({
341 - message: `Failed to list connected accounts for user "${params.userId}".`,
342 - cause,
343 - }),
344 - });
342 + },
343 + { decode: false }
344 + )
345 + .pipe(
346 + Effect.mapError(
347 + cause =>
348 + new ConnectedAccountsRequestError({
349 + message: `Failed to list connected accounts for user "${params.userId}".`,
350 + cause,
351 + })
352 + )
353 + );
354
355 const formatExistingAccountLabels = (
356 items: ReadonlyArray<{
@@ -488,7 +497,7 @@ const handleListConnectedAccounts = (params: {
497 readonly getFor: (params: {
498 readonly orgId: string;
499 readonly projectId: string;
491 - }) => Effect.Effect<RawComposioClient, unknown>;
500 + }) => Effect.Effect<ComposioClientShape, unknown>;
501 };
502 readonly projectContext: {
503 readonly resolve: Effect.Effect<
@@ -539,20 +548,25 @@ const handleListConnectedAccounts = (params: {
548
549 const accounts = yield* params.ui.withSpinner(
550 `Listing connected accounts for "${toolkitSlug}"...`,
542 - Effect.tryPromise({
543 - try: () =>
544 - client.connectedAccounts.list({
551 + client.connectedAccounts
552 + .list(
553 + {
554 toolkit_slugs: [toolkitSlug],
555 user_ids: [resolvedUserId.value],
556 statuses: ['ACTIVE'],
557 limit: 100,
549 - }),
550 - catch: cause =>
551 - new ConnectedAccountsRequestError({
552 - message: `Failed to list connected accounts for "${toolkitSlug}".`,
553 - cause,
554 - }),
555 - })
558 + },
559 + { decode: false }
560 + )
561 + .pipe(
562 + Effect.mapError(
563 + cause =>
564 + new ConnectedAccountsRequestError({
565 + message: `Failed to list connected accounts for "${toolkitSlug}".`,
566 + cause,
567 + })
568 + )
569 + )
570 );
571 const connectedAccounts = yield* decodeConnectedAccountItems(accounts.items).pipe(
572 Effect.mapError(
@@ -615,7 +629,7 @@ const handleLegacyAuthConfigLink = (params: {
629 readonly getFor: (params: {
630 readonly orgId: string;
631 readonly projectId: string;
618 - }) => Effect.Effect<RawComposioClient, unknown>;
632 + }) => Effect.Effect<ComposioClientShape, unknown>;
633 };
634 readonly projectContext: {
635 readonly resolve: Effect.Effect<
@@ -689,19 +703,24 @@ const handleLegacyAuthConfigLink = (params: {
703 const linkOpt = yield* params.ui
704 .withSpinner(
705 'Creating link session...',
692 - Effect.tryPromise({
693 - try: () =>
694 - client.link.create({
706 + client.link
707 + .create(
708 + {
709 auth_config_id: params.authConfigId,
710 user_id: resolvedUserId.value,
711 ...(Option.isSome(normalizedAlias) && { alias: normalizedAlias.value }),
698 - }),
699 - catch: cause =>
700 - new ConnectedAccountsRequestError({
701 - message: `Failed to create link for auth config "${params.authConfigId}".`,
702 - cause,
703 - }),
704 - })
712 + },
713 + { decode: false }
714 + )
715 + .pipe(
716 + Effect.mapError(
717 + cause =>
718 + new ConnectedAccountsRequestError({
719 + message: `Failed to create link for auth config "${params.authConfigId}".`,
720 + cause,
721 + })
722 + )
723 + )
724 )
725 .pipe(
726 Effect.asSome,
@@ -900,20 +919,26 @@ const runConnectedAccountsLink = (params: {
919 }
920 : undefined,
921 });
903 - return yield* Effect.tryPromise({
904 - try: () =>
905 - client.toolRouter.session.link(sessionId, {
922 + return yield* client.toolRouter.session
923 + .link(
924 + sessionId,
925 + {
926 toolkit: toolkitSlug,
927 ...(Option.isSome(normalizedAliasOption) && {
928 alias: normalizedAliasOption.value,
929 }),
910 - }),
911 - catch: cause =>
912 - new ConnectedAccountsRequestError({
913 - message: `Failed to create link for toolkit "${toolkitSlug}".`,
914 - cause,
915 - }),
916 - });
930 + },
931 + { decode: false }
932 + )
933 + .pipe(
934 + Effect.mapError(
935 + cause =>
936 + new ConnectedAccountsRequestError({
937 + message: `Failed to create link for toolkit "${toolkitSlug}".`,
938 + cause,
939 + })
940 + )
941 + );
942 })
943 )
944 .pipe(
ts/packages/cli/src/commands/connected-accounts/commands/connected-accounts.list.cmd.ts
+15 -10
@@ -77,20 +77,25 @@ export const connectedAccountsCmd$List = Command.make(
77
78 const rawResult = yield* ui.withSpinner(
79 'Fetching connected accounts...',
80 - Effect.tryPromise({
81 - try: () =>
82 - client.connectedAccounts.list({
80 + client.connectedAccounts
81 + .list(
82 + {
83 toolkit_slugs: toolkitSlugs,
84 user_ids: Option.isSome(userId) ? [userId.value] : undefined,
85 statuses: Option.isSome(status) ? [status.value] : undefined,
86 limit: clampLimit(limit),
87 - }),
88 - catch: cause =>
89 - new ConnectedAccountsListRequestError({
90 - message: 'Failed to list connected accounts.',
91 - cause,
92 - }),
93 - })
87 + },
88 + { decode: false }
89 + )
90 + .pipe(
91 + Effect.mapError(
92 + cause =>
93 + new ConnectedAccountsListRequestError({
94 + message: 'Failed to list connected accounts.',
95 + cause,
96 + })
97 + )
98 + )
99 );
100 const result = yield* decodeConnectedAccountListWithFallback(rawResult);
101
ts/packages/cli/src/commands/connected-accounts/commands/connected-accounts.whoami.cmd.ts
+6 -9
@@ -3,7 +3,7 @@ import { Effect, Option } from 'effect';
3 import { ComposioToolkitsRepository } from 'src/services/composio-clients';
4 import { TerminalUI } from 'src/services/terminal-ui';
5 import { requireAuth } from 'src/effects/require-auth';
6 -import { handleHttpServerError } from 'src/effects/handle-http-error';
6 +import { catchClientApiError } from 'src/effects/handle-http-error';
7 import { formatConnectedAccountWhoami } from '../format';
8
9 const id = Argument.String('id').pipe(
@@ -45,14 +45,11 @@ export const connectedAccountsCmd$Whoami = Command.make('whoami', { id }, ({ id
45 .withSpinner(`Fetching connected account "${idValue}"...`, repo.getConnectedAccount(idValue))
46 .pipe(
47 Effect.asSome,
48 - Effect.catchTag(
49 - 'services/HttpServerError',
50 - handleHttpServerError(ui, {
51 - fallbackMessage: `Failed to fetch connected account "${idValue}".`,
52 - hint: 'Browse available connected accounts:\n> composio dev connected-accounts list',
53 - fallbackValue: Option.none(),
54 - })
55 - )
48 + catchClientApiError(ui, {
49 + fallbackMessage: `Failed to fetch connected account "${idValue}".`,
50 + hint: 'Browse available connected accounts:\n> composio dev connected-accounts list',
51 + fallbackValue: Option.none(),
52 + })
53 );
54
55 if (Option.isNone(itemOpt)) {
ts/packages/cli/src/commands/connections/commands/connections.list.cmd.ts
+15 -10
@@ -83,19 +83,24 @@ export const connectionsCmd$List = Command.make('list', { toolkit }, ({ toolkit
83 orgId: resolvedProject.orgId,
84 projectId: resolvedProject.projectId,
85 });
86 - const rawResult = yield* Effect.tryPromise({
87 - try: () =>
88 - client.connectedAccounts.list({
86 + const rawResult = yield* client.connectedAccounts
87 + .list(
88 + {
89 toolkit_slugs: toolkitSlug ? [toolkitSlug] : undefined,
90 user_ids: [consumerUserId],
91 limit: 1000,
92 - }),
93 - catch: cause =>
94 - new ConnectionsListRequestError({
95 - message: 'Failed to list connections.',
96 - cause,
97 - }),
98 - });
92 + },
93 + { decode: false }
94 + )
95 + .pipe(
96 + Effect.mapError(
97 + cause =>
98 + new ConnectionsListRequestError({
99 + message: 'Failed to list connections.',
100 + cause,
101 + })
102 + )
103 + );
104 const result = yield* decodeConnectedAccountListWithFallback(rawResult);
105 const permissionSnapshot = yield* getConsumerPermissionSnapshot({
106 orgId: resolvedProject.orgId,
ts/packages/cli/src/commands/connections/commands/connections.remove.cmd.ts
+20 -20
@@ -117,18 +117,17 @@ export const connectionsCmd$Remove = Command.make('remove', { account }, ({ acco
117 });
118 const rawResult = yield* ui.withSpinner(
119 'Fetching connections...',
120 - Effect.tryPromise({
121 - try: () =>
122 - client.connectedAccounts.list({
123 - user_ids: [consumerUserId],
124 - limit: 1000,
125 - }),
126 - catch: cause =>
127 - new ConnectionsRemovalRequestError({
128 - message: 'Failed to list connections.',
129 - cause,
130 - }),
131 - })
120 + client.connectedAccounts
121 + .list({ user_ids: [consumerUserId], limit: 1000 }, { decode: false })
122 + .pipe(
123 + Effect.mapError(
124 + cause =>
125 + new ConnectionsRemovalRequestError({
126 + message: 'Failed to list connections.',
127 + cause,
128 + })
129 + )
130 + )
131 );
132 const result = yield* decodeConnectedAccountListWithFallback(rawResult);
133 const resolved = resolveAccount({ accounts: result.items, selector: account });
@@ -153,14 +152,15 @@ export const connectionsCmd$Remove = Command.make('remove', { account }, ({ acco
152
153 yield* ui.withSpinner(
154 `Removing ${resolved.toolkit.slug} connection...`,
156 - Effect.tryPromise({
157 - try: () => client.connectedAccounts.delete(resolved.id),
158 - catch: cause =>
159 - new ConnectionsRemovalRequestError({
160 - message: `Failed to remove connected account "${resolved.id}".`,
161 - cause,
162 - }),
163 - }),
155 + client.connectedAccounts.delete(resolved.id, undefined, { decode: false }).pipe(
156 + Effect.mapError(
157 + cause =>
158 + new ConnectionsRemovalRequestError({
159 + message: `Failed to remove connected account "${resolved.id}".`,
160 + cause,
161 + })
162 + )
163 + ),
164 {
165 successMessage: `Removed ${resolved.toolkit.slug} connection.`,
166 errorMessage: `Failed to remove ${resolved.toolkit.slug} connection.`,
ts/packages/cli/src/commands/init.cmd.ts
+34 -16
@@ -1,3 +1,4 @@
1 +import { isAPIError } from '@composio/client/effect';
2 import { Command as CliCommand, Flag } from 'effect/cli';
3 import { Effect, Option } from 'effect';
4 import * as FileSystem from 'effect/FileSystem';
@@ -13,12 +14,19 @@ import {
14 sessionProjectApiKeyOf,
15 sessionUserIdOf,
16 type OrgProject,
16 -} from 'src/services/composio-clients';
17 +} from 'src/services/composio-account';
18 import { linkApolloIdentityForAnalytics } from 'src/analytics/dispatch';
19 import * as constants from 'src/constants';
20 import { TerminalUI } from 'src/services/terminal-ui';
21 import { browserLogin, noBrowser as noBrowserOpt } from 'src/commands/login.cmd';
22 import { setupCacheDir } from 'src/effects/setup-cache-dir';
23 +import {
24 + describeDecodeError,
25 + isClientApiError,
26 + isClientConnectionError,
27 + isClientDecodeError,
28 + type ClientApiError,
29 +} from 'src/utils/api-error-extraction';
30
31 /**
32 * `composio init` — Initialize a developer project in the current directory.
@@ -166,23 +174,33 @@ const ensureProjectApiKeyInEnv = (params: { cwd: string; selected: ProjectKeys }
174 }
175 });
176
169 -const logEnvCreationHttpError =
170 - (ui: TerminalUI) =>
171 - (e: { status?: number; details?: { message: string; suggestedFix?: string }; cause?: unknown }) =>
172 - Effect.gen(function* () {
173 - yield* ui.log.warn('Could not create .env.local from session info.');
174 - if (e.status) {
175 - yield* ui.log.error(`HTTP ${e.status}`);
176 - }
177 +const logEnvCreationHttpError = (ui: TerminalUI) => (e: ClientApiError) =>
178 + Effect.gen(function* () {
179 + yield* ui.log.warn('Could not create .env.local from session info.');
180 + if (isClientDecodeError(e)) {
181 + const { message, hint } = describeDecodeError(e);
182 + yield* ui.log.error(message);
183 + yield* ui.log.step(hint);
184 + return;
185 + }
186 + if (isAPIError(e)) {
187 + yield* ui.log.error(`HTTP ${e.status}`);
188 if (e.details) {
189 yield* ui.log.error(e.details.message);
179 - if (e.details.suggestedFix !== undefined) {
180 - yield* ui.log.step(e.details.suggestedFix);
190 + if (e.details.suggested_fix !== undefined) {
191 + yield* ui.log.step(e.details.suggested_fix);
192 }
182 - } else if (e.cause) {
183 - yield* ui.log.error(String(e.cause));
193 + return;
194 }
185 - });
195 + }
196 + // A connection failure names what the transport reported; every other
197 + // failure keeps the line it had as a stringified error.
198 + yield* ui.log.error(
199 + isClientConnectionError(e) && e.description !== undefined
200 + ? e.description
201 + : `Error: ${e.message}`
202 + );
203 + });
204
205 const logEnvCreationDecodingError = (ui: TerminalUI) => (e: { cause?: unknown }) =>
206 Effect.gen(function* () {
@@ -275,7 +293,7 @@ const initInteractiveFlow = (params: { composioDir: string; noBrowser: boolean;
293 apiKey: globalApiKey,
294 orgId: orgIdValue,
295 }).pipe(
278 - Effect.catchTag('services/HttpServerError', e =>
296 + Effect.catchIf(isClientApiError, e =>
297 Effect.gen(function* () {
298 yield* Effect.logDebug('Failed to list org projects:', e);
299 yield* ui.log.warn('Could not fetch projects from the server.');
@@ -338,7 +356,7 @@ const initInteractiveFlow = (params: { composioDir: string; noBrowser: boolean;
356 // 4. Write project config
357 yield* writeProjectConfig(composioDir, selected);
358 yield* ensureProjectApiKeyInEnv({ cwd: proc.cwd, selected }).pipe(
341 - Effect.catchTag('services/HttpServerError', e =>
359 + Effect.catchIf(isClientApiError, e =>
360 Effect.gen(function* () {
361 yield* Effect.logDebug('Failed to resolve project API key from session/info:', e);
362 yield* logEnvCreationHttpError(ui)(e);
ts/packages/cli/src/commands/listen.cmd.ts
+58 -49
@@ -1,7 +1,7 @@
1 import { Argument, Command, Flag } from 'effect/cli';
2 import * as FileSystem from 'effect/FileSystem';
3 import * as Path from 'effect/Path';
4 -import { NotFoundError, type Composio as RawComposioClient } from '@composio/client';
4 +import type { ComposioClientShape } from '@composio/client/effect';
5 import { Data, Deferred, Effect, Result, Option, Predicate } from 'effect';
6 import { requireAuth } from 'src/effects/require-auth';
7 import { resolveOptionalTextInput } from 'src/effects/resolve-optional-text-input';
@@ -27,7 +27,7 @@ import { parseTriggerListenEvent } from './triggers/parse';
27 import { decodeConnectedAccountItems } from 'src/effects/decode-connected-account-list';
28
29 type TriggerCreateParams = NonNullable<
30 - Parameters<RawComposioClient['triggerInstances']['upsert']>[1]
30 + Parameters<ComposioClientShape['triggerInstances']['upsert']>[1]
31 >;
32
33 export class ListenCommandError extends Data.TaggedError('commands/ListenCommandError')<{
@@ -101,25 +101,27 @@ const sanitizePathPart = (value: string): string =>
101 value.replace(/[^A-Z0-9._-]+/gi, '-').replace(/^-+|-+$/g, '') || 'unknown';
102
103 const disableTemporaryTrigger = (params: {
104 - client: RawComposioClient;
104 + client: ComposioClientShape;
105 ui: TerminalUI;
106 slug: string;
107 triggerId: string;
108 }) =>
109 - Effect.tryPromise({
110 - try: () =>
111 - params.client.triggerInstances.manage.update(params.triggerId, { status: 'disable' }),
112 - catch: cause =>
113 - new ListenCommandError({
114 - reason: 'disable_trigger',
115 - message: `Failed to disable temporary trigger "${params.triggerId}": ${String(cause)}`,
116 - slug: params.slug,
117 - cause,
118 - }),
119 - }).pipe(
120 - Effect.tapError(error => params.ui.log.warn(error.message)),
121 - Effect.ignore
122 - );
109 + params.client.triggerInstances.manage
110 + .update(params.triggerId, { status: 'disable' }, { decode: false })
111 + .pipe(
112 + Effect.mapError(
113 + cause =>
114 + new ListenCommandError({
115 + reason: 'disable_trigger',
116 + // "Error: " is how these messages have always introduced the client's failure.
117 + message: `Failed to disable temporary trigger "${params.triggerId}": Error: ${cause.message}`,
118 + slug: params.slug,
119 + cause,
120 + })
121 + ),
122 + Effect.tapError(error => params.ui.log.warn(error.message)),
123 + Effect.ignore
124 + );
125
126 const isProjectEventType = (value: string): boolean => value.startsWith('composio.');
127
@@ -158,17 +160,19 @@ const assertSupportedListenParams = (params: {
160 * failure. Neither call site is on the happy path, which makes no additional request.
161 */
162 const assertTriggerTypeExists = (params: {
161 - client: RawComposioClient;
163 + client: ComposioClientShape;
164 slug: string;
165 toolkitSlug?: string;
166 }) =>
167 Effect.gen(function* () {
166 - const lookup = yield* Effect.tryPromise({
167 - try: () => params.client.triggersTypes.retrieve(params.slug),
168 - catch: cause => cause,
169 - }).pipe(Effect.result);
170 -
171 - if (Result.isFailure(lookup) && lookup.failure instanceof NotFoundError) {
168 + const lookup = yield* params.client.triggersTypes
169 + .retrieve(params.slug, undefined, { decode: false })
170 + .pipe(Effect.result);
171 +
172 + if (
173 + Result.isFailure(lookup) &&
174 + Predicate.isTagged(lookup.failure, '@composio/client/NotFoundError')
175 + ) {
176 return yield* new ListenCommandError({
177 reason: 'unknown_trigger',
178 message: `Unknown trigger slug "${params.slug}". List available slugs with \`composio triggers list <toolkit>\`.`,
@@ -182,7 +186,7 @@ const assertTriggerTypeExists = (params: {
186 });
187
188 const resolveConnectedAccountIdForTrigger = (params: {
185 - client: RawComposioClient;
189 + client: ComposioClientShape;
190 slug: string;
191 consumerUserId: string;
192 account: Option.Option<string>;
@@ -198,23 +202,28 @@ const resolveConnectedAccountIdForTrigger = (params: {
202 );
203 }
204
201 - const connectedAccounts = yield* Effect.tryPromise({
202 - try: () =>
203 - params.client.connectedAccounts.list({
205 + const connectedAccounts = yield* params.client.connectedAccounts
206 + .list(
207 + {
208 toolkit_slugs: [toolkitSlug],
209 user_ids: [params.consumerUserId],
210 statuses: ['ACTIVE'],
211 limit: 100,
208 - }),
209 - catch: cause =>
210 - new ListenCommandError({
211 - reason: 'connected_accounts',
212 - message: `Failed to list connected accounts for "${toolkitSlug}": ${String(cause)}`,
213 - slug: params.slug,
214 - toolkitSlug,
215 - cause,
216 - }),
217 - });
212 + },
213 + { decode: false }
214 + )
215 + .pipe(
216 + Effect.mapError(
217 + cause =>
218 + new ListenCommandError({
219 + reason: 'connected_accounts',
220 + message: `Failed to list connected accounts for "${toolkitSlug}": Error: ${cause.message}`,
221 + slug: params.slug,
222 + toolkitSlug,
223 + cause,
224 + })
225 + )
226 + );
227 const selectableAccounts = yield* decodeConnectedAccountItems(connectedAccounts.items).pipe(
228 Effect.mapError(
229 cause =>
@@ -404,7 +413,7 @@ const resolveListenSetup = (params: {
413 readonly stream: Option.Option<string>;
414 readonly maxEvents: Option.Option<number>;
415 readonly account: Option.Option<string>;
407 - readonly client: RawComposioClient;
416 + readonly client: ComposioClientShape;
417 readonly resolvedProject: {
418 readonly orgId: string;
419 readonly projectId: string;
@@ -545,16 +554,16 @@ export const listenCmd = Command.make(
554 yield* Effect.acquireUseRelease(
555 listeningToProjectEvent
556 ? Effect.succeed<null | { trigger_id: string }>(null)
548 - : Effect.tryPromise({
549 - try: () => client.triggerInstances.upsert(slug, createParams),
550 - catch: cause =>
551 - new ListenCommandError({
552 - reason: 'create_trigger',
553 - message: `Failed to create temporary trigger "${slug}": ${String(cause)}`,
554 - slug,
555 - cause,
556 - }),
557 - }).pipe(
557 + : client.triggerInstances.upsert(slug, createParams, { decode: false }).pipe(
558 + Effect.mapError(
559 + cause =>
560 + new ListenCommandError({
561 + reason: 'create_trigger',
562 + message: `Failed to create temporary trigger "${slug}": Error: ${cause.message}`,
563 + slug,
564 + cause,
565 + })
566 + ),
567 // An active account for the inferred toolkit skips the lookup in
568 // resolveConnectedAccountIdForTrigger, so a mistyped slug with a valid toolkit prefix
569 // only surfaces here. The lookup's unknown_trigger failure replaces the create_trigger
ts/packages/cli/src/commands/login.cmd.ts
+2 -2
@@ -3,15 +3,15 @@ import * as FileSystem from 'effect/FileSystem';
3 import * as Path from 'effect/Path';
4 import { Data, DateTime, Effect, Option, Schedule, Schema } from 'effect';
5 import open from 'open';
6 +import { ComposioSessionRepository } from 'src/services/composio-clients';
7 import {
7 - ComposioSessionRepository,
8 getSessionInfo,
9 getSessionInfoByUserApiKey,
10 listOrganizations,
11 sessionUserIdOf,
12 type OrganizationSummary,
13 type SessionInfoResponse,
14 -} from 'src/services/composio-clients';
14 +} from 'src/services/composio-account';
15 import { ComposioUserContext } from 'src/services/user-context';
16 import { TerminalUI } from 'src/services/terminal-ui';
17 import { commandHintStep } from 'src/services/command-hints';
ts/packages/cli/src/commands/logs-cmd/commands/logs.tools.cmd.ts
+27 -24
@@ -190,14 +190,15 @@ export const logsCmd$Tools = Command.make(
190 if (toolLogId) {
191 const toolLog = yield* ui.withSpinner(
192 `Fetching tool log "${toolLogId}"...`,
193 - Effect.tryPromise({
194 - try: () => client.logs.tools.retrieve(toolLogId),
195 - catch: cause =>
196 - new ToolLogsRequestError({
197 - message: `Failed to fetch tool log "${toolLogId}".`,
198 - cause,
199 - }),
200 - })
193 + client.logs.tools.retrieve(toolLogId).pipe(
194 + Effect.mapError(
195 + cause =>
196 + new ToolLogsRequestError({
197 + message: `Failed to fetch tool log "${toolLogId}".`,
198 + cause,
199 + })
200 + )
201 + )
202 );
203
204 yield* ui.log.info(
@@ -209,22 +210,24 @@ export const logsCmd$Tools = Command.make(
210
211 const response = yield* ui.withSpinner(
212 'Fetching tool logs...',
212 - Effect.tryPromise({
213 - try: () =>
214 - client.logs.tools.list({
215 - cursor: Option.getOrUndefined(cursor) ?? null,
216 - from: Option.getOrUndefined(from),
217 - to: Option.getOrUndefined(to),
218 - limit: clampedLimit,
219 - case_sensitive: caseSensitive,
220 - search_params: shorthandSearchParams.length > 0 ? shorthandSearchParams : undefined,
221 - }),
222 - catch: cause =>
223 - new ToolLogsRequestError({
224 - message: 'Failed to fetch tool logs.',
225 - cause,
226 - }),
227 - })
213 + client.logs.tools
214 + .list({
215 + cursor: Option.getOrUndefined(cursor) ?? null,
216 + from: Option.getOrUndefined(from),
217 + to: Option.getOrUndefined(to),
218 + limit: clampedLimit,
219 + case_sensitive: caseSensitive,
220 + search_params: shorthandSearchParams.length > 0 ? shorthandSearchParams : undefined,
221 + })
222 + .pipe(
223 + Effect.mapError(
224 + cause =>
225 + new ToolLogsRequestError({
226 + message: 'Failed to fetch tool logs.',
227 + cause,
228 + })
229 + )
230 + )
231 );
232
233 const logs = response.data ?? [];
ts/packages/cli/src/commands/logs-cmd/commands/logs.triggers.cmd.ts
+25 -18
@@ -3,6 +3,7 @@ import { Data, Effect, Option } from 'effect';
3 import { requireAuth } from 'src/effects/require-auth';
4 import { TerminalUI } from 'src/services/terminal-ui';
5 import { ComposioClientSingleton } from 'src/services/composio-clients';
6 +import { undecoded } from 'src/services/composio-request';
7 import { clampLimit } from 'src/ui/clamp-limit';
8 import { parseCsv } from 'src/commands/triggers/parse-csv';
9 import { formatTriggerLogInfo, formatTriggerLogsTable } from '../format';
@@ -155,14 +156,15 @@ export const logsCmd$Triggers = Command.make(
156 if (triggerLogId) {
157 const triggerLog = yield* ui.withSpinner(
158 `Fetching trigger log "${triggerLogId}"...`,
158 - Effect.tryPromise({
159 - try: () => client.logs.triggers.retrieve(triggerLogId),
160 - catch: cause =>
161 - new TriggerLogsRequestError({
162 - message: `Failed to fetch trigger log "${triggerLogId}".`,
163 - cause,
164 - }),
165 - })
159 + client.logs.triggers.retrieve(triggerLogId, undecoded).pipe(
160 + Effect.mapError(
161 + cause =>
162 + new TriggerLogsRequestError({
163 + message: `Failed to fetch trigger log "${triggerLogId}".`,
164 + cause,
165 + })
166 + )
167 + )
168 );
169 const record = decodeTriggerLogRecord(triggerLog);
170
@@ -176,9 +178,9 @@ export const logsCmd$Triggers = Command.make(
178
179 const response = yield* ui.withSpinner(
180 'Fetching trigger logs...',
179 - Effect.tryPromise({
180 - try: () =>
181 - client.logs.triggers.list({
181 + client.logs.triggers
182 + .list(
183 + {
184 cursor: Option.getOrUndefined(cursor),
185 from: Option.getOrUndefined(from),
186 to: Option.getOrUndefined(to),
@@ -187,13 +189,18 @@ export const logsCmd$Triggers = Command.make(
189 search: Option.getOrUndefined(search),
190 include_payload: includePayload,
191 search_params: shorthandSearchParams.length > 0 ? shorthandSearchParams : undefined,
190 - }),
191 - catch: cause =>
192 - new TriggerLogsRequestError({
193 - message: 'Failed to fetch trigger logs.',
194 - cause,
195 - }),
196 - })
192 + },
193 + undecoded
194 + )
195 + .pipe(
196 + Effect.mapError(
197 + cause =>
198 + new TriggerLogsRequestError({
199 + message: 'Failed to fetch trigger logs.',
200 + cause,
201 + })
202 + )
203 + )
204 );
205
206 const logs = response.data ?? [];
ts/packages/cli/src/commands/orgs/commands/orgs.list.cmd.ts
+1 -1
@@ -2,7 +2,7 @@ import { Command, Flag } from 'effect/cli';
2 import { Effect, Option } from 'effect';
3 import { requireAuth } from 'src/effects/require-auth';
4 import { TerminalUI } from 'src/services/terminal-ui';
5 -import { listOrganizations } from 'src/services/composio-clients';
5 +import { listOrganizations } from 'src/services/composio-account';
6 import { ComposioUserContext } from 'src/services/user-context';
7 import { clampLimit } from 'src/ui/clamp-limit';
8
ts/packages/cli/src/commands/projects/commands/projects.list.cmd.ts
+1 -1
@@ -2,7 +2,7 @@ import { Command, Flag } from 'effect/cli';
2 import { Effect, Option } from 'effect';
3 import { requireAuth } from 'src/effects/require-auth';
4 import { TerminalUI } from 'src/services/terminal-ui';
5 -import { listOrganizationProjects } from 'src/services/composio-clients';
5 +import { listOrganizationProjects } from 'src/services/composio-account';
6 import { ComposioUserContext } from 'src/services/user-context';
7 import { clampLimit } from 'src/ui/clamp-limit';
8
ts/packages/cli/src/commands/proxy.cmd.ts
+47 -39
@@ -22,7 +22,7 @@ import {
22 mapComposioError,
23 } from 'src/services/composio-error-overrides';
24 import { parseJsonRecord } from 'src/utils/parse-json';
25 -import { assertNotInputRequired } from 'src/utils/tool-input-required';
25 +import { toolInputRequiredError } from 'src/utils/tool-input-required';
26 import { resolveConnectedAccountForToolkit } from 'src/services/connected-account-selection';
27
28 const endpoint = Argument.String('url').pipe(
@@ -355,44 +355,52 @@ export const proxyCmd = Command.make('proxy', {
355 },
356 });
357
358 - return yield* Effect.tryPromise({
359 - try: async () => {
360 - const response = await client.toolRouter.session.proxyExecute(
361 - sessionId,
362 - {
363 - toolkit_slug: normalizedToolkit,
364 - endpoint,
365 - method: normalizedMethod,
366 - ...(parsedBody !== undefined ? { body: parsedBody } : {}),
367 - ...(headerParameters.length > 0 ? { parameters: headerParameters } : {}),
368 - },
369 - // Never retry a proxied call: a retry after the upstream API
370 - // already acted duplicates the side effect.
371 - { maxRetries: 0 }
372 - );
373 - assertNotInputRequired(
374 - `${normalizedMethod} proxy call via "${normalizedToolkit}"`,
375 - response
376 - );
377 - return response;
378 - },
379 - catch: cause =>
380 - new ProxyRequestError({
381 - message: `Failed to proxy ${normalizedMethod} ${endpoint} via "${normalizedToolkit}".`,
382 - cause,
383 - }),
384 - }).pipe(
385 - Effect.matchEffect({
386 - onFailure: error =>
387 - handleProxyExecutionError({
388 - ui,
389 - error,
390 - toolkit: normalizedToolkit,
391 - endpoint,
392 - }),
393 - onSuccess: Effect.succeed,
394 - })
395 - );
358 + const failed = (cause: unknown) =>
359 + new ProxyRequestError({
360 + message: `Failed to proxy ${normalizedMethod} ${endpoint} via "${normalizedToolkit}".`,
361 + cause,
362 + });
363 +
364 + return yield* client.toolRouter.session
365 + .proxyExecute(
366 + sessionId,
367 + {
368 + toolkit_slug: normalizedToolkit,
369 + endpoint,
370 + method: normalizedMethod,
371 + ...(parsedBody !== undefined ? { body: parsedBody } : {}),
372 + ...(headerParameters.length > 0 ? { parameters: headerParameters } : {}),
373 + },
374 + // Never retry a proxied call: a retry after the upstream API
375 + // already acted duplicates the side effect. The response is not
376 + // validated either, for the same reason.
377 + { maxRetries: 0, decode: false }
378 + )
379 + .pipe(
380 + Effect.mapError(failed),
381 + Effect.flatMap(response =>
382 + response.result_type === 'input_required'
383 + ? Effect.fail(
384 + failed(
385 + toolInputRequiredError(
386 + `${normalizedMethod} proxy call via "${normalizedToolkit}"`,
387 + response
388 + )
389 + )
390 + )
391 + : Effect.succeed(response)
392 + ),
393 + Effect.matchEffect({
394 + onFailure: error =>
395 + handleProxyExecutionError({
396 + ui,
397 + error,
398 + toolkit: normalizedToolkit,
399 + endpoint,
400 + }),
401 + onSuccess: Effect.succeed,
402 + })
403 + );
404 })
405 );
406
ts/packages/cli/src/commands/toolkits/commands/toolkits.info.cmd.ts
+11 -8
@@ -93,14 +93,17 @@ export const toolkitsCmd$Info = Command.make(
93 if (Option.isSome(resolvedUserId)) {
94 const client = yield* clientSingleton.get();
95 const { sessionId } = yield* resolveToolRouterSession(client, resolvedUserId.value);
96 - const sessionToolkits = yield* Effect.tryPromise({
97 - try: () => client.toolRouter.session.toolkits(sessionId, { toolkits: [slugValue] }),
98 - catch: cause =>
99 - new ToolkitsInfoRequestError({
100 - message: `Failed to fetch toolkit "${slugValue}".`,
101 - cause,
102 - }),
103 - });
96 + const sessionToolkits = yield* client.toolRouter.session
97 + .toolkits(sessionId, { toolkits: [slugValue] })
98 + .pipe(
99 + Effect.mapError(
100 + cause =>
101 + new ToolkitsInfoRequestError({
102 + message: `Failed to fetch toolkit "${slugValue}".`,
103 + cause,
104 + })
105 + )
106 + );
107 return { toolkit: sessionToolkits.items[0], detailedToolkitOpt };
108 }
109
ts/packages/cli/src/commands/toolkits/commands/toolkits.list.cmd.ts
+25 -23
@@ -101,7 +101,8 @@ export const toolkitsCmd$List = Command.make(
101 const sessionContextEffect = Option.isSome(resolvedUserId)
102 ? Effect.gen(function* () {
103 const client = yield* clientSingleton.get();
104 - return yield* resolveToolRouterSession(client, resolvedUserId.value);
104 + const { sessionId } = yield* resolveToolRouterSession(client, resolvedUserId.value);
105 + return { client, sessionId };
106 }).pipe(
107 Effect.catch(error =>
108 Effect.logDebug('Failed to create session:', error).pipe(Effect.as(undefined))
@@ -129,30 +130,31 @@ export const toolkitsCmd$List = Command.make(
130 let sessionFailed = false;
131 if (sessionContext) {
132 const { client, sessionId } = sessionContext;
132 - sessionItems = yield* Effect.tryPromise({
133 - try: () =>
134 - client.toolRouter.session.toolkits(sessionId, {
135 - search: Option.getOrUndefined(query),
136 - limit: clampedLimit,
137 - is_connected: Option.getOrUndefined(connected),
138 - }),
139 - catch: cause =>
140 - new ToolkitsListRequestError({
141 - message: 'Failed to fetch session toolkits.',
142 - cause,
143 - }),
144 - }).pipe(
145 - Effect.map(r => r.items),
146 - Effect.catchTag('commands/ToolkitsListRequestError', error =>
147 - Effect.logDebug('Failed to fetch session toolkits:', error).pipe(
148 - Effect.as(
149 - [] as ReadonlyArray<
150 - import('@composio/client/resources/tool-router').SessionToolkitsResponse.Item
151 - >
133 + sessionItems = yield* client.toolRouter.session
134 + .toolkits(sessionId, {
135 + search: Option.getOrUndefined(query),
136 + limit: clampedLimit,
137 + is_connected: Option.getOrUndefined(connected),
138 + })
139 + .pipe(
140 + Effect.mapError(
141 + cause =>
142 + new ToolkitsListRequestError({
143 + message: 'Failed to fetch session toolkits.',
144 + cause,
145 + })
146 + ),
147 + Effect.map(r => r.items),
148 + Effect.catchTag('commands/ToolkitsListRequestError', error =>
149 + Effect.logDebug('Failed to fetch session toolkits:', error).pipe(
150 + Effect.as(
151 + [] as ReadonlyArray<
152 + import('@composio/client/resources/tool-router').SessionToolkitsResponse.Item
153 + >
154 + )
155 )
156 )
154 - )
155 - );
157 + );
158 if (sessionItems.length === 0) {
159 sessionFailed = true;
160 sessionItems = undefined;
ts/packages/cli/src/commands/toolkits/commands/toolkits.version.cmd.ts
+3 -4
@@ -25,10 +25,9 @@ export const toolkitsCmd$Version = Command.make('version', { slug }, ({ slug })
25 const toolkitOpt = yield* ui
26 .withSpinner(
27 `Fetching versions for toolkit "${slug}"...`,
28 - Effect.tryPromise({
29 - try: () => client.toolkits.retrieve(slug),
30 - catch: error => (error instanceof Error ? error : new Error(String(error))),
31 - })
28 + // Only the name, slug and version list are read, so a toolkit that
29 + // lacks other catalog fields still prints its versions.
30 + client.toolkits.retrieve(slug, undefined, { decode: false })
31 )
32 .pipe(
33 Effect.asSome,
ts/packages/cli/src/commands/tools/commands/tools.info.cmd.ts
+18 -21
@@ -3,7 +3,7 @@ import { Effect, Option } from 'effect';
3 import { ComposioToolkitsRepository } from 'src/services/composio-clients';
4 import { TerminalUI } from 'src/services/terminal-ui';
5 import { requireAuth } from 'src/effects/require-auth';
6 -import { handleHttpServerError } from 'src/effects/handle-http-error';
6 +import { catchClientApiError } from 'src/effects/handle-http-error';
7 import { getOrFetchToolInputDefinition } from 'src/services/tool-input-validation';
8 import { normalizeFileUploadSchema } from 'src/services/tool-file-uploads';
9 import { bold } from 'src/ui/colors';
@@ -44,26 +44,23 @@ export const toolsCmd$Info = Command.make('info', { slug }, ({ slug }) =>
44 .withSpinner(`Fetching tool "${slugValue}"...`, repo.getToolDetailed(slugValue))
45 .pipe(
46 Effect.asSome,
47 - Effect.catchTag(
48 - 'services/HttpServerError',
49 - handleHttpServerError(ui, {
50 - fallbackMessage: `Tool "${slugValue}" not found.`,
51 - hint: [
52 - commandHintStep('Browse available toolkits', 'dev.toolkits.list'),
53 - commandHintStep('Then list tools', 'root.tools.list'),
54 - ].join('\n'),
55 - fallbackValue: Option.none(),
56 - searchForSuggestions: () =>
57 - repo.searchTools({ search: slugValue, limit: 3 }).pipe(
58 - Effect.map(r =>
59 - r.items.map(s => ({
60 - label: `${s.slug} — ${s.description}`,
61 - command: `> composio tools info "${s.slug}"`,
62 - }))
63 - )
64 - ),
65 - })
66 - )
47 + catchClientApiError(ui, {
48 + fallbackMessage: `Tool "${slugValue}" not found.`,
49 + hint: [
50 + commandHintStep('Browse available toolkits', 'dev.toolkits.list'),
51 + commandHintStep('Then list tools', 'root.tools.list'),
52 + ].join('\n'),
53 + fallbackValue: Option.none(),
54 + searchForSuggestions: () =>
55 + repo.searchTools({ search: slugValue, limit: 3 }).pipe(
56 + Effect.map(r =>
57 + r.items.map(s => ({
58 + label: `${s.slug} — ${s.description}`,
59 + command: `> composio tools info "${s.slug}"`,
60 + }))
61 + )
62 + ),
63 + })
64 );
65
66 if (Option.isNone(toolOpt)) {
ts/packages/cli/src/commands/tools/commands/tools.search.cmd.ts
+44 -35
@@ -17,7 +17,7 @@ import {
17 } from 'src/services/command-project';
18 import { commandHintExample, commandHintStep } from 'src/services/command-hints';
19 import { isRemoteCustomToolSlug } from 'src/utils/remote-custom-toolkit';
20 -import { assertNotInputRequired } from 'src/utils/tool-input-required';
20 +import { toolInputRequiredError } from 'src/utils/tool-input-required';
21 import {
22 primeConsumerConnectedToolkitsCacheInBackground,
23 writeConsumerConnectedToolkitsCache,
@@ -374,49 +374,58 @@ const runToolsSearch = (params: {
374 const searchPayload = {
375 queries: queries.map(query => ({ use_case: query })),
376 };
377 - const searchResponse = yield* Effect.tryPromise({
378 - try: () => client.toolRouter.session.search(sessionId, searchPayload),
379 - catch: cause =>
380 - new ToolsSearchRequestError({
381 - message: 'Failed to search tools.',
382 - cause,
383 - }),
384 - });
377 + const searchResponse = yield* client.toolRouter.session.search(sessionId, searchPayload).pipe(
378 + Effect.mapError(
379 + cause =>
380 + new ToolsSearchRequestError({
381 + message: 'Failed to search tools.',
382 + cause,
383 + })
384 + )
385 + );
386 const customToolSlugsMissingSchemas = Object.entries(searchResponse.tool_schemas)
387 .filter(([slug, schema]) => isRemoteCustomToolSlug(slug) && !schema.input_schema)
388 .map(([slug]) => slug);
389 const hydratedSearchResponse =
390 customToolSlugsMissingSchemas.length === 0
391 ? searchResponse
391 - : yield* Effect.tryPromise({
392 - try: async () => {
393 - const schemaResponse = await client.toolRouter.session.executeMeta(sessionId, {
394 - slug: 'COMPOSIO_GET_TOOL_SCHEMAS',
395 - arguments: { tool_slugs: customToolSlugsMissingSchemas },
396 - });
397 - assertNotInputRequired('COMPOSIO_GET_TOOL_SCHEMAS', schemaResponse);
398 - if (schemaResponse.error) {
399 - throw new Error(schemaResponse.error);
400 - }
401 -
402 - const resolvedSchemas = schemaResponse.data.tool_schemas;
403 - if (!resolvedSchemas || typeof resolvedSchemas !== 'object') {
404 - throw new Error('Tool Router returned no tool schemas.');
405 - }
406 -
407 - return {
408 - ...searchResponse,
409 - tool_schemas: {
410 - ...searchResponse.tool_schemas,
411 - ...(resolvedSchemas as Record<string, SearchToolSchema>),
412 - },
413 - };
414 - },
415 - catch: cause =>
392 + : yield* Effect.gen(function* () {
393 + const schemasFailed = (cause: unknown) =>
394 new ToolsSearchRequestError({
395 message: 'Failed to fetch custom tool schemas.',
396 cause,
419 - }),
397 + });
398 + const schemaResponse = yield* client.toolRouter.session
399 + .executeMeta(
400 + sessionId,
401 + {
402 + slug: 'COMPOSIO_GET_TOOL_SCHEMAS',
403 + arguments: { tool_slugs: customToolSlugsMissingSchemas },
404 + },
405 + { decode: false }
406 + )
407 + .pipe(Effect.mapError(schemasFailed));
408 + if (schemaResponse.result_type === 'input_required') {
409 + return yield* schemasFailed(
410 + toolInputRequiredError('COMPOSIO_GET_TOOL_SCHEMAS', schemaResponse)
411 + );
412 + }
413 + if (schemaResponse.error) {
414 + return yield* schemasFailed(new Error(schemaResponse.error));
415 + }
416 +
417 + const resolvedSchemas = schemaResponse.data.tool_schemas;
418 + if (!resolvedSchemas || typeof resolvedSchemas !== 'object') {
419 + return yield* schemasFailed(new Error('Tool Router returned no tool schemas.'));
420 + }
421 +
422 + return {
423 + ...searchResponse,
424 + tool_schemas: {
425 + ...searchResponse.tool_schemas,
426 + ...(resolvedSchemas as Record<string, SearchToolSchema>),
427 + },
428 + };
429 });
430 return {
431 searchResponse: hydratedSearchResponse,
ts/packages/cli/src/commands/triggers/commands/triggers.create.cmd.ts
+6 -9
@@ -2,7 +2,7 @@ import { Argument, Command, Flag } from 'effect/cli';
2 import { Effect, Option, Result } from 'effect';
3 import { parseJsonRecord } from 'src/utils/parse-json';
4 import { requireAuth } from 'src/effects/require-auth';
5 -import { handleHttpServerError } from 'src/effects/handle-http-error';
5 +import { catchClientApiError } from 'src/effects/handle-http-error';
6 import { ComposioToolkitsRepository } from 'src/services/composio-clients';
7 import { TerminalUI } from 'src/services/terminal-ui';
8
@@ -71,14 +71,11 @@ export const triggersCmd$Create = Command.make(
71 )
72 .pipe(
73 Effect.asSome,
74 - Effect.catchTag(
75 - 'services/HttpServerError',
76 - handleHttpServerError(ui, {
77 - fallbackMessage: `Failed to create trigger "${triggerName.value}".`,
78 - hint: 'List available trigger types with:\n> composio dev triggers list',
79 - fallbackValue: Option.none(),
80 - })
81 - )
74 + catchClientApiError(ui, {
75 + fallbackMessage: `Failed to create trigger "${triggerName.value}".`,
76 + hint: 'List available trigger types with:\n> composio dev triggers list',
77 + fallbackValue: Option.none(),
78 + })
79 );
80
81 if (Option.isNone(createdOpt)) {
ts/packages/cli/src/commands/triggers/commands/triggers.disable.cmd.ts
+6 -9
@@ -1,7 +1,7 @@
1 import { Argument, Command, Flag } from 'effect/cli';
2 import { Data, Effect, Option } from 'effect';
3 import { requireAuth } from 'src/effects/require-auth';
4 -import { handleHttpServerError } from 'src/effects/handle-http-error';
4 +import { catchClientApiError } from 'src/effects/handle-http-error';
5 import { ComposioToolkitsRepository } from 'src/services/composio-clients';
6 import { ComposioCliUserConfig } from 'src/services/cli-user-config';
7 import { TerminalUI } from 'src/services/terminal-ui';
@@ -59,14 +59,11 @@ export const triggersCmd$Disable = Command.make(
59 .withSpinner(`Disabling trigger "${idValue}"...`, repo.disableTrigger(idValue))
60 .pipe(
61 Effect.as(true),
62 - Effect.catchTag(
63 - 'services/HttpServerError',
64 - handleHttpServerError(ui, {
65 - fallbackMessage: `Failed to disable trigger "${idValue}".`,
66 - hint: 'Browse available triggers:\n> composio dev triggers status',
67 - fallbackValue: false,
68 - })
69 - )
62 + catchClientApiError(ui, {
63 + fallbackMessage: `Failed to disable trigger "${idValue}".`,
64 + hint: 'Browse available triggers:\n> composio dev triggers status',
65 + fallbackValue: false,
66 + })
67 );
68
69 if (!disabled) return;
ts/packages/cli/src/commands/triggers/commands/triggers.enable.cmd.ts
+6 -9
@@ -1,7 +1,7 @@
1 import { Argument, Command } from 'effect/cli';
2 import { Effect, Option } from 'effect';
3 import { requireAuth } from 'src/effects/require-auth';
4 -import { handleHttpServerError } from 'src/effects/handle-http-error';
4 +import { catchClientApiError } from 'src/effects/handle-http-error';
5 import { ComposioToolkitsRepository } from 'src/services/composio-clients';
6 import { TerminalUI } from 'src/services/terminal-ui';
7
@@ -33,14 +33,11 @@ export const triggersCmd$Enable = Command.make('enable', { id }, ({ id }) =>
33 .withSpinner(`Enabling trigger "${idValue}"...`, repo.enableTrigger(idValue))
34 .pipe(
35 Effect.as(true),
36 - Effect.catchTag(
37 - 'services/HttpServerError',
38 - handleHttpServerError(ui, {
39 - fallbackMessage: `Failed to enable trigger "${idValue}".`,
40 - hint: 'Browse available triggers:\n> composio dev triggers status --show-disabled',
41 - fallbackValue: false,
42 - })
43 - )
36 + catchClientApiError(ui, {
37 + fallbackMessage: `Failed to enable trigger "${idValue}".`,
38 + hint: 'Browse available triggers:\n> composio dev triggers status --show-disabled',
39 + fallbackValue: false,
40 + })
41 );
42
43 if (!enabled) return;
ts/packages/cli/src/commands/triggers/commands/triggers.info.cmd.ts
+6 -9
@@ -1,7 +1,7 @@
1 import { Argument, Command } from 'effect/cli';
2 import { Effect, Option } from 'effect';
3 import { requireAuth } from 'src/effects/require-auth';
4 -import { handleHttpServerError } from 'src/effects/handle-http-error';
4 +import { catchClientApiError } from 'src/effects/handle-http-error';
5 import { ComposioToolkitsRepository } from 'src/services/composio-clients';
6 import { TerminalUI } from 'src/services/terminal-ui';
7 import { formatTriggerTypeInfo } from '../format';
@@ -51,14 +51,11 @@ const makeTriggersInfoCommand = ({
51 .withSpinner('Fetching trigger type details...', repo.getTriggerTypeDetailed(slugValue))
52 .pipe(
53 Effect.asSome,
54 - Effect.catchTag(
55 - 'services/HttpServerError',
56 - handleHttpServerError(ui, {
57 - fallbackMessage: `Trigger "${slugValue}" not found.`,
58 - hint: `Browse available trigger types:\n> ${listCommandPlaceholder}`,
59 - fallbackValue: Option.none(),
60 - })
61 - )
54 + catchClientApiError(ui, {
55 + fallbackMessage: `Trigger "${slugValue}" not found.`,
56 + hint: `Browse available trigger types:\n> ${listCommandPlaceholder}`,
57 + fallbackValue: Option.none(),
58 + })
59 );
60
61 if (Option.isNone(triggerTypeOpt)) return;
ts/packages/cli/src/commands/triggers/commands/triggers.status.cmd.ts
+6 -9
@@ -1,6 +1,6 @@
1 import { Command, Flag } from 'effect/cli';
2 import { Effect, Option } from 'effect';
3 -import { handleHttpServerError } from 'src/effects/handle-http-error';
3 +import { catchClientApiError } from 'src/effects/handle-http-error';
4 import { requireAuth } from 'src/effects/require-auth';
5 import { ComposioToolkitsRepository } from 'src/services/composio-clients';
6 import { TerminalUI } from 'src/services/terminal-ui';
@@ -91,14 +91,11 @@ export const triggersCmd$Status = Command.make(
91 )
92 .pipe(
93 Effect.asSome,
94 - Effect.catchTag(
95 - 'services/HttpServerError',
96 - handleHttpServerError(ui, {
97 - fallbackMessage: 'Failed to fetch trigger status.',
98 - hint: 'Retry with:\n> composio dev triggers status --show-disabled',
99 - fallbackValue: Option.none(),
100 - })
101 - )
94 + catchClientApiError(ui, {
95 + fallbackMessage: 'Failed to fetch trigger status.',
96 + hint: 'Retry with:\n> composio dev triggers status --show-disabled',
97 + fallbackValue: Option.none(),
98 + })
99 );
100
101 if (Option.isNone(resultOpt)) {
ts/packages/cli/src/commands/whoami.cmd.ts
+1 -1
@@ -1,6 +1,6 @@
1 import { Command } from 'effect/cli';
2 import { Effect, Option } from 'effect';
3 -import { getSessionInfoByUserApiKey } from 'src/services/composio-clients';
3 +import { getSessionInfoByUserApiKey } from 'src/services/composio-account';
4 import { linkApolloIdentityForAnalytics } from 'src/analytics/dispatch';
5 import { ComposioUserContext } from 'src/services/user-context';
6 import { TerminalUI } from 'src/services/terminal-ui';
ts/packages/cli/src/effect-errors/logic/errors/extract-error-details.ts
+33
@@ -1,4 +1,11 @@
1 import { hasProperty, isFunction } from 'effect/Predicate';
2 +import {
3 + describeDecodeError,
4 + isClientApiError,
5 + isClientConnectionError,
6 + isClientDecodeError,
7 + type ClientApiError,
8 +} from 'src/utils/api-error-extraction';
9
10 interface ErrorDetails {
11 isPlainString: boolean;
@@ -6,6 +13,17 @@ interface ErrorDetails {
13 message: unknown;
14 }
15
16 +// A client error has no cause chain: its own message is the status line and
17 +// response body, and a connection error's description is the transport's text.
18 +// A response that failed decoding is reported by operation and request id.
19 +const clientApiErrorDetail = (error: ClientApiError): string => {
20 + if (isClientDecodeError(error)) {
21 + const { message, hint } = describeDecodeError(error);
22 + return `${message}\n${hint}`;
23 + }
24 + return isClientConnectionError(error) ? (error.description ?? error.message) : error.message;
25 +};
26 +
27 // Wrappers like UpgradeBinaryError carry the actionable specifics (a
28 // ParseError path, an HTTP body) in `cause`; surface the deepest message so
29 // the rendered error is debuggable, not just the wrapper's summary line.
@@ -20,6 +38,8 @@ const causeDetail = (cause: unknown): string | undefined => {
38 seen.add(current);
39 }
40
41 + if (isClientApiError(current)) return clientApiErrorDetail(current);
42 +
43 if (typeof current === 'string' && current.length > 0) {
44 detail = current;
45 } else if (
@@ -41,6 +61,11 @@ const withCauseDetail = (message: string, cause: unknown): string => {
61 return detail !== undefined && detail !== message ? `${message}\nCaused by: ${detail}` : message;
62 };
63
64 +const clientApiErrorMessage = (error: ClientApiError): string =>
65 + isClientDecodeError(error)
66 + ? clientApiErrorDetail(error)
67 + : withCauseDetail('', clientApiErrorDetail(error));
68 +
69 export const extractErrorDetails = (error: unknown): ErrorDetails => {
70 if (typeof error === 'string') {
71 return {
@@ -49,6 +74,14 @@ export const extractErrorDetails = (error: unknown): ErrorDetails => {
74 };
75 }
76
77 + if (isClientApiError(error)) {
78 + return {
79 + isPlainString: false,
80 + type: error.name,
81 + message: clientApiErrorMessage(error),
82 + };
83 + }
84 +
85 const isTaggedErrorWithCause =
86 error instanceof Error && hasProperty(error, 'cause') && hasProperty(error, '_tag');
87 if (isTaggedErrorWithCause) {
ts/packages/cli/src/effects/create-tool-router-session.ts
+27 -23
@@ -1,5 +1,5 @@
1 import { Data, Effect, Option } from 'effect';
2 -import type { Composio } from '@composio/client';
2 +import type { ComposioClientShape } from '@composio/client/effect';
3 import {
4 getFreshConsumerToolRouterAuthConfigsFromCache,
5 getFreshConsumerToolRouterConnectedAccountsFromCache,
@@ -61,7 +61,7 @@ export class ToolRouterSessionCreateError extends Data.TaggedError(
61 * Used by `ToolsExecutorLive` which already holds the client reference.
62 */
63 export const createToolRouterSessionContext = (
64 - client: Composio,
64 + client: ComposioClientShape,
65 userId: string,
66 options?: CreateToolRouterSessionOptions
67 ) =>
@@ -166,9 +166,9 @@ export const createToolRouterSessionContext = (
166 connectedAccountIds,
167 })
168 : undefined;
169 - return yield* Effect.tryPromise({
170 - try: () =>
171 - client.toolRouter.session.create({
169 + return yield* client.toolRouter.session
170 + .create(
171 + {
172 user_id: userId,
173 auth_configs: connectionContext.authConfigs,
174 connected_accounts: connectionContext.connectedAccounts,
@@ -184,28 +184,32 @@ export const createToolRouterSessionContext = (
184 experimental: permissionSnapshot?.enhancedControlsEnabled
185 ? { link_url_overwrite: ENHANCED_LINK_URL_OVERWRITE }
186 : undefined,
187 - }),
188 - catch: cause =>
189 - new ToolRouterSessionCreateError({
190 - message: 'Failed to create a Tool Router session.',
191 - cause,
192 - }),
193 - }).pipe(
194 - Effect.map((session): CreatedToolRouterSession => ({
195 - sessionId: session.session_id,
196 - permissionSnapshot,
197 - connectedAccounts: connectionContext.connectedAccounts,
198 - connectedAccountWordIds: resolveConnectedAccountWordIds(
199 - connectionContext.connectedAccounts,
200 - connectionContext.availableConnectedAccounts
187 + },
188 + { decode: false }
189 + )
190 + .pipe(
191 + Effect.mapError(
192 + cause =>
193 + new ToolRouterSessionCreateError({
194 + message: 'Failed to create a Tool Router session.',
195 + cause,
196 + })
197 ),
202 - }))
203 - );
198 + Effect.map((session): CreatedToolRouterSession => ({
199 + sessionId: session.session_id,
200 + permissionSnapshot,
201 + connectedAccounts: connectionContext.connectedAccounts,
202 + connectedAccountWordIds: resolveConnectedAccountWordIds(
203 + connectionContext.connectedAccounts,
204 + connectionContext.availableConnectedAccounts
205 + ),
206 + }))
207 + );
208 });
209
210 /** Backward-compatible helper for callers that only need the session id. */
211 export const createToolRouterSession = (
208 - client: Composio,
212 + client: ComposioClientShape,
213 userId: string,
214 options?: CreateToolRouterSessionOptions
215 ) =>
@@ -219,7 +223,7 @@ export const createToolRouterSession = (
223 * (resolve singleton, get client, create session) repeated across commands.
224 */
225 export const resolveToolRouterSession = (
222 - client: Composio,
226 + client: ComposioClientShape,
227 userId: string,
228 options?: CreateToolRouterSessionOptions
229 ) =>
ts/packages/cli/src/effects/decode-connected-account-list.ts
+1 -1
@@ -6,7 +6,7 @@ import {
6 import {
7 ConnectedAccountListResponse,
8 type ConnectedAccountListResponse as ConnectedAccountListResponseType,
9 -} from 'src/services/composio-clients';
9 +} from 'src/models/connected-accounts';
10 import { TerminalUI } from 'src/services/terminal-ui';
11
12 /**
ts/packages/cli/src/effects/handle-http-error.ts
+78 -31
@@ -1,7 +1,13 @@
1 import process from 'node:process';
2 +import { isAPIError } from '@composio/client/effect';
3 import { Effect } from 'effect';
3 -import type { HttpServerError } from 'src/services/composio-clients';
4 import type { TerminalUI } from 'src/services/terminal-ui';
5 +import {
6 + describeDecodeError,
7 + isClientApiError,
8 + isClientDecodeError,
9 + type ClientApiError,
10 +} from 'src/utils/api-error-extraction';
11
12 export interface Suggestion {
13 readonly label: string;
@@ -10,9 +16,32 @@ export interface Suggestion {
16
17 const noSuggestions: ReadonlyArray<Suggestion> = [];
18
19 +export interface HandleClientApiErrorOptions<A> {
20 + readonly fallbackMessage: string;
21 + readonly hint: string;
22 + readonly fallbackValue: A;
23 + readonly searchForSuggestions?: () => Effect.Effect<ReadonlyArray<Suggestion>, unknown, never>;
24 +}
25 +
26 +interface ErrorReport {
27 + readonly message?: string;
28 + readonly suggestedFix?: string;
29 + // Set when the failure has its own remedy, which replaces the caller's hint.
30 + readonly hint?: string;
31 +}
32 +
33 +const reportOf = (e: ClientApiError): ErrorReport => {
34 + if (isClientDecodeError(e)) return describeDecodeError(e);
35 + if (isAPIError(e)) {
36 + return { message: e.details?.message, suggestedFix: e.details?.suggested_fix };
37 + }
38 + return {};
39 +};
40 +
41 /**
14 - * Create an HttpServerError handler that logs the structured error details
15 - * (or a fallback message) and a contextual hint, then returns a fallback value.
42 + * Create a handler for a client API error that logs the structured error
43 + * details (or a fallback message) and a contextual hint, then returns a
44 + * fallback value.
45 *
46 * The process exit code is set to 1 so callers such as scripts and agents can
47 * detect the failure. Decorated logs only render when stderr is a TTY, so the
@@ -24,11 +53,14 @@ const noSuggestions: ReadonlyArray<Suggestion> = [];
53 * similar items and display "Did you mean?" suggestions instead of the generic hint.
54 * Suggestion search failures are silently swallowed — the handler always completes.
55 *
56 + * A response that failed client decoding is reported by operation and request
57 + * id with an upgrade hint, in place of the fallback message and the hint.
58 + *
59 * @example
60 * ```ts
61 * .pipe(
30 - * Effect.catchTag('services/HttpServerError',
31 - * handleHttpServerError(ui, {
62 + * Effect.catchTag('@composio/client/NotFoundError',
63 + * handleClientApiError(ui, {
64 * fallbackMessage: `Failed to fetch auth config "${id}".`,
65 * hint: 'Browse available auth configs:\n> composio dev auth-configs list',
66 * fallbackValue: Option.none(),
@@ -37,40 +69,28 @@ const noSuggestions: ReadonlyArray<Suggestion> = [];
69 * )
70 * ```
71 */
40 -export const handleHttpServerError =
41 - <A>(
42 - ui: TerminalUI,
43 - opts: {
44 - readonly fallbackMessage: string;
45 - readonly hint: string;
46 - readonly fallbackValue: A;
47 - readonly searchForSuggestions?: () => Effect.Effect<
48 - ReadonlyArray<Suggestion>,
49 - unknown,
50 - never
51 - >;
52 - }
53 - ) =>
54 - (e: HttpServerError) =>
72 +export const handleClientApiError =
73 + <A>(ui: TerminalUI, opts: HandleClientApiErrorOptions<A>) =>
74 + (e: ClientApiError) =>
75 Effect.gen(function* () {
76 process.exitCode = 1;
77
78 + const report = reportOf(e);
79 + const message = report.message ?? opts.fallbackMessage;
80 + const hint = report.hint ?? opts.hint;
81 +
82 const { canDecorate } = yield* ui.capabilities;
83 if (!canDecorate) {
60 - yield* ui.error(e.details ? e.details.message : opts.fallbackMessage);
61 - yield* ui.error(opts.hint);
84 + yield* ui.error(message);
85 + yield* ui.error(hint);
86 }
87
64 - if (e.details) {
65 - yield* ui.log.error(e.details.message);
66 - if (e.details.suggestedFix !== undefined) {
67 - yield* ui.log.step(e.details.suggestedFix);
68 - }
69 - } else {
70 - yield* ui.log.error(opts.fallbackMessage);
88 + yield* ui.log.error(message);
89 + if (report.suggestedFix !== undefined) {
90 + yield* ui.log.step(report.suggestedFix);
91 }
92
73 - if (opts.searchForSuggestions) {
93 + if (opts.searchForSuggestions && report.hint === undefined) {
94 const suggestions = yield* opts
95 .searchForSuggestions()
96 .pipe(Effect.catch(() => Effect.succeed(noSuggestions)));
@@ -83,6 +103,33 @@ export const handleHttpServerError =
103 }
104 }
105
86 - yield* ui.log.step(opts.hint);
106 + yield* ui.log.step(hint);
107 return opts.fallbackValue;
108 });
109 +
110 +/**
111 + * Recover from any client API error (a non-success status, a connection
112 + * failure, a timeout, or a response that failed decoding) with
113 + * `handleClientApiError`. Every other failure passes through.
114 + *
115 + * @example
116 + * ```ts
117 + * .pipe(
118 + * catchClientApiError(ui, {
119 + * fallbackMessage: `Failed to fetch auth config "${id}".`,
120 + * hint: 'Browse available auth configs:\n> composio dev auth-configs list',
121 + * fallbackValue: Option.none(),
122 + * })
123 + * )
124 + * ```
125 + */
126 +export const catchClientApiError =
127 + <B>(ui: TerminalUI, opts: HandleClientApiErrorOptions<B>) =>
128 + <A, E, R>(
129 + self: Effect.Effect<A, E, R>
130 + ): Effect.Effect<A | B, Exclude<E, Extract<E, ClientApiError>>, R> =>
131 + Effect.catchIf<A, E, R, Extract<E, ClientApiError>, B, never, never>(
132 + self,
133 + (e): e is Extract<E, ClientApiError> => isClientApiError(e),
134 + handleClientApiError(ui, opts)
135 + );
ts/packages/cli/src/effects/link-analytics-identity.ts
+1 -1
@@ -3,7 +3,7 @@ import {
3 analyticsIdentityLinkingEnabled,
4 linkApolloIdentityForAnalytics,
5 } from 'src/analytics/dispatch';
6 -import { getSessionInfoByUserApiKey } from 'src/services/composio-clients';
6 +import { getSessionInfoByUserApiKey } from 'src/services/composio-account';
7
8 type KnownOrgIdentity = {
9 readonly orgId: string;
ts/packages/cli/src/effects/select-org-project.ts
+1 -1
@@ -1,6 +1,6 @@
1 import { Effect } from 'effect';
2 import { TerminalUI } from 'src/services/terminal-ui';
3 -import { listOrganizations, type OrganizationSummary } from 'src/services/composio-clients';
3 +import { listOrganizations, type OrganizationSummary } from 'src/services/composio-account';
4 import { clampLimit } from 'src/ui/clamp-limit';
5
6 const DEFAULT_LIMIT = 50;
ts/packages/cli/src/effects/validate-toolkit-versions.ts
+4 -5
@@ -1,11 +1,10 @@
1 +import { isComposioError } from '@composio/client/effect';
2 import { Data, Effect } from 'effect';
3 import colors from 'picocolors';
4 import { S_BAR, unicodeOr } from '@clack/prompts';
5 import { TerminalUI } from 'src/services/terminal-ui';
5 -import type {
6 - ComposioToolkitsRepositoryShape,
7 - InvalidVersionDetail,
8 -} from 'src/services/composio-clients';
6 +import type { ComposioToolkitsRepositoryShape } from 'src/services/composio-clients';
7 +import type { InvalidVersionDetail } from 'src/services/toolkit-version-validation';
8 import type { ToolkitVersionOverrides } from './toolkit-version-overrides';
9
10 /**
@@ -189,7 +188,7 @@ export const validateToolkitVersionOverrides = ({
188 })
189 )
190 ),
192 - Effect.catchTag('services/HttpServerError', error =>
191 + Effect.catchIf(isComposioError, error =>
192 Effect.fail(
193 new ToolkitVersionValidationError({
194 cause: error,
ts/packages/cli/src/models/auth-configs.ts
+27
@@ -30,3 +30,30 @@ export type AuthConfigItem = Schema.Schema.Type<typeof AuthConfigItem>;
30
31 export const AuthConfigItems = Schema.Array(AuthConfigItem);
32 export type AuthConfigItems = Schema.Schema.Type<typeof AuthConfigItems>;
33 +
34 +// Auth config list response (single page with total_items for "Listing X of Y" display)
35 +export const AuthConfigListResponse = Schema.Struct({
36 + items: AuthConfigItems,
37 + total_items: Schema.Int,
38 + total_pages: Schema.Int,
39 + current_page: Schema.Int,
40 + next_cursor: Schema.NullOr(Schema.String).pipe(
41 + Schema.withDecodingDefaultType(Effect.succeed(null))
42 + ),
43 +}).annotate({ identifier: 'AuthConfigListResponse' });
44 +export type AuthConfigListResponse = Schema.Schema.Type<typeof AuthConfigListResponse>;
45 +
46 +// `auth-configs create` prints this response to stdout, so it stays an
47 +// allowlist rather than the client's full type: a field the API adds later
48 +// must not reach a pipe without a decision here.
49 +export const AuthConfigCreateResponse = Schema.Struct({
50 + auth_config: Schema.Struct({
51 + id: Schema.String,
52 + auth_scheme: Schema.String,
53 + is_composio_managed: Schema.Boolean,
54 + }),
55 + toolkit: Schema.Struct({
56 + slug: Schema.String,
57 + }),
58 +}).annotate({ identifier: 'AuthConfigCreateResponse' });
59 +export type AuthConfigCreateResponse = Schema.Schema.Type<typeof AuthConfigCreateResponse>;
ts/packages/cli/src/models/connected-accounts.ts
+12
@@ -63,3 +63,15 @@ export type ConnectedAccountItem = Schema.Schema.Type<typeof ConnectedAccountIte
63
64 export const ConnectedAccountItems = Schema.Array(ConnectedAccountItem);
65 export type ConnectedAccountItems = Schema.Schema.Type<typeof ConnectedAccountItems>;
66 +
67 +// Connected account list response (single page with total_items for "Listing X of Y" display)
68 +export const ConnectedAccountListResponse = Schema.Struct({
69 + items: ConnectedAccountItems,
70 + total_items: Schema.Int,
71 + total_pages: Schema.Int,
72 + current_page: Schema.Int,
73 + next_cursor: Schema.NullOr(Schema.String).pipe(
74 + Schema.withDecodingDefaultType(Effect.succeed(null))
75 + ),
76 +}).annotate({ identifier: 'ConnectedAccountListResponse' });
77 +export type ConnectedAccountListResponse = Schema.Schema.Type<typeof ConnectedAccountListResponse>;
ts/packages/cli/src/models/tools.ts
+8
@@ -63,3 +63,11 @@ export type Tools = Schema.Schema.Type<typeof Tools>;
63 export const ToolsJSON = JSONTransformSchema(Tools);
64 export const ToolsFromJSON = Schema.decodeEffect(ToolsJSON);
65 export const ToolsToJSON = Schema.encodeEffect(ToolsJSON);
66 +
67 +// The client does not type the latest-version endpoint, so the CLI owns its
68 +// response contract.
69 +export const LatestToolVersionResponse = Schema.Struct({
70 + tool_slug: Schema.String,
71 + version: Schema.String,
72 +}).annotate({ identifier: 'LatestToolVersionResponse' });
73 +export type LatestToolVersionResponse = Schema.Schema.Type<typeof LatestToolVersionResponse>;
ts/packages/cli/src/services/agents.ts
+1 -1
@@ -7,7 +7,7 @@ import { JsonRecordSchema } from 'src/effects/json';
7 import { setupCacheDir } from 'src/effects/setup-cache-dir';
8 import { atomicWritePrivateFileString, ensurePrivateFileMode } from 'src/utils/atomic-write';
9 import { ComposioUserContext } from 'src/services/user-context';
10 -import { getSessionInfoByUserApiKey } from 'src/services/composio-clients';
10 +import { getSessionInfoByUserApiKey } from 'src/services/composio-account';
11 import { primeConsumerConnectedToolkitsCacheInBackground } from 'src/services/consumer-short-term-cache';
12 import { linkApolloIdentityForAnalytics } from 'src/analytics/dispatch';
13
ts/packages/cli/src/services/client-provenance.ts
+1 -1
@@ -1,4 +1,4 @@
1 -import { VERSION as clientLibraryVersion } from '@composio/client';
1 +import { VERSION as clientLibraryVersion } from '@composio/client/effect';
2 import { APP_VERSION } from 'src/constants';
3
4 const runtime = () =>
ts/packages/cli/src/services/command-project.ts
+1 -1
@@ -6,7 +6,7 @@ import {
6 findDeveloperProjectByName,
7 DeveloperProjectNotFoundError,
8 AmbiguousDeveloperProjectNameError,
9 -} from './composio-clients';
9 +} from './composio-account';
10
11 export type ProjectMode = 'consumer' | 'developer';
12
ts/packages/cli/src/services/composio-account.ts new
+406
@@ -0,0 +1,406 @@
1 +import { Data, Effect, Predicate, String } from 'effect';
2 +import type { RequestOptions } from '@composio/client/effect';
3 +import type { OrgListResponse, ProjectListResponse } from '@composio/client/resources/org';
4 +import type {
5 + ConsumerListConnectedToolkitsResponse,
6 + ProjectResolveResponse,
7 +} from '@composio/client/resources/org/consumer';
8 +import type { SessionRetrieveInfoResponse } from '@composio/client/resources/auth';
9 +import { LatestToolVersionResponse } from 'src/models/tools';
10 +import { ComposioClientSingleton } from './composio-clients';
11 +import { HttpDecodingError, type ClientError } from './composio-errors';
12 +import { decode, undecoded } from './composio-request';
13 +
14 +/**
15 + * Account, session-info, and consumer helpers
16 + *
17 + * Standalone functions rather than repository methods: they take explicit
18 + * credentials and scope, and callers already run inside layers that provide
19 + * `ComposioClientSingleton`.
20 + */
21 +
22 +/**
23 + * Session info as the CLI consumes it: the client's response with `project`
24 + * present. The endpoint answers `project: null` for org-level credentials,
25 + * which every caller here treats as an unusable session.
26 + */
27 +export type SessionInfoResponse = SessionRetrieveInfoResponse & {
28 + readonly project: NonNullable<SessionRetrieveInfoResponse['project']>;
29 +};
30 +
31 +const requireSessionProject = (
32 + info: SessionRetrieveInfoResponse
33 +): Effect.Effect<SessionInfoResponse, HttpDecodingError> =>
34 + info.project === null
35 + ? Effect.fail(
36 + new HttpDecodingError({
37 + cause: 'Session info response has no project (org-level credentials)',
38 + })
39 + )
40 + : Effect.succeed({ ...info, project: info.project });
41 +
42 +/**
43 + * The org member's user id, falling back to the member id. The backend still
44 + * sends `org_member.user_id` although the v3.1 spec omits it, and the persisted
45 + * test user id derives from it, so it is read defensively.
46 + */
47 +export const sessionUserIdOf = (info: SessionInfoResponse): string => {
48 + const member: object = info.org_member;
49 + return Predicate.hasProperty(member, 'user_id') && Predicate.isString(member.user_id)
50 + ? member.user_id
51 + : info.org_member.id;
52 +};
53 +
54 +/**
55 + * The project API key carried by a session, or null. The v3.1 spec names the
56 + * field `key`, and older responses spell it `api_key`; reading both keeps
57 + * `composio dev init` from minting a second key when the backend sends the
58 + * older spelling.
59 + */
60 +export const sessionProjectApiKeyOf = (info: SessionInfoResponse): string | null => {
61 + const apiKey: object | null = info.api_key;
62 + if (apiKey === null) return null;
63 + if (Predicate.hasProperty(apiKey, 'api_key') && Predicate.isString(apiKey.api_key)) {
64 + return apiKey.api_key;
65 + }
66 + return info.api_key?.key ?? null;
67 +};
68 +
69 +/**
70 + * A single project entry returned by GET /api/v3.1/org/project/list.
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 +
79 +export interface OrganizationSummary {
80 + readonly id: string;
81 + readonly name: string;
82 +}
83 +
84 +export interface OrganizationListResponse {
85 + readonly data: ReadonlyArray<OrganizationSummary>;
86 + readonly total_items: number;
87 +}
88 +
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 +
102 +const orgScopedOptions = (orgId: string | undefined): RequestOptions | undefined =>
103 + orgId ? { headers: { 'x-org-id': orgId } } : undefined;
104 +
105 +/**
106 + * Lists organizations available to the current user API key.
107 + */
108 +export const listOrganizations = (params: {
109 + apiKey: string;
110 + limit?: number;
111 +}): Effect.Effect<OrganizationListResponse, ClientError, ComposioClientSingleton> =>
112 + Effect.gen(function* () {
113 + const clientSingleton = yield* ComposioClientSingleton;
114 + const client = yield* clientSingleton.getFor({ userApiKey: params.apiKey });
115 + const response = yield* client.org.list({ limit: params.limit ?? 50 });
116 + const organizations = response.organizations.map(
117 + (organization: OrgListResponse.Organization) =>
118 + ({ id: organization.id, name: organization.name }) satisfies OrganizationSummary
119 + );
120 +
121 + return {
122 + data: organizations,
123 + total_items: organizations.length,
124 + };
125 + });
126 +
127 +/**
128 + * Lists projects for a specific organization.
129 + */
130 +export const listOrganizationProjects = (params: {
131 + apiKey: string;
132 + orgId: string;
133 + limit?: number;
134 +}): Effect.Effect<OrganizationProjectListResponse, ClientError, ComposioClientSingleton> =>
135 + Effect.gen(function* () {
136 + const clientSingleton = yield* ComposioClientSingleton;
137 + const client = yield* clientSingleton.getFor({ userApiKey: params.apiKey });
138 + const response = yield* client.org.project.list(
139 + { limit: params.limit ?? 50 },
140 + orgScopedOptions(params.orgId)
141 + );
142 + const projects = response.data.map(
143 + (project: OrgProject) =>
144 + ({ id: project.id, name: project.name }) satisfies OrganizationProjectSummary
145 + );
146 +
147 + return {
148 + data: projects,
149 + total_items: projects.length,
150 + };
151 + });
152 +
153 +/**
154 + * Lists all projects for the logged-in user's organization.
155 + *
156 + * @param params.apiKey - UAK (sent as `x-user-api-key`)
157 + * @param params.orgId - Organization ID (sent as `x-org-id`)
158 + * @param params.limit - Max projects to return (default 50)
159 + */
160 +export const listOrgProjects = (params: {
161 + apiKey: string;
162 + orgId: string;
163 + limit?: number;
164 +}): Effect.Effect<OrgProjectListResponse, ClientError, ComposioClientSingleton> =>
165 + Effect.gen(function* () {
166 + const clientSingleton = yield* ComposioClientSingleton;
167 + const client = yield* clientSingleton.getFor({ userApiKey: params.apiKey });
168 + return yield* client.org.project.list(
169 + { list_all_org_projects: true, limit: params.limit ?? 50 },
170 + orgScopedOptions(params.orgId)
171 + );
172 + });
173 +
174 +/**
175 + * Calls GET /api/v3.1/auth/session/info with the full layered auth headers.
176 + */
177 +export const getSessionInfo = (params: {
178 + apiKey: string;
179 + orgId: string;
180 + projectId: string;
181 +}): Effect.Effect<SessionInfoResponse, ClientError, ComposioClientSingleton> =>
182 + Effect.gen(function* () {
183 + const clientSingleton = yield* ComposioClientSingleton;
184 + const client = yield* clientSingleton.getFor({
185 + userApiKey: params.apiKey,
186 + orgId: params.orgId,
187 + projectId: params.projectId,
188 + });
189 + // Read through a few fields only, and called after login has already
190 + // linked the session: drift in a field the CLI never reads must not fail it.
191 + const info = yield* client.auth.session.retrieveInfo(undecoded);
192 + return yield* requireSessionProject(info);
193 + });
194 +
195 +/**
196 + * Calls GET /api/v3.1/auth/session/info using the x-user-api-key header.
197 + * Unlike getSessionInfo which requires both org AND project IDs, this variant
198 + * resolves session metadata from the UAK alone — useful during login before
199 + * org/project context is known.
200 + *
201 + * When `orgId` is provided, it is forwarded as `x-org-id` so the backend
202 + * resolves the session against the caller's currently-selected global org
203 + * (set via `composio orgs switch`). Without it, the backend falls back to the
204 + * API key's home org, which makes the response ignore any org switch.
205 + */
206 +export const getSessionInfoByUserApiKey = (params: {
207 + userApiKey: string;
208 + orgId?: string;
209 +}): Effect.Effect<SessionInfoResponse, ClientError, ComposioClientSingleton> =>
210 + Effect.gen(function* () {
211 + const clientSingleton = yield* ComposioClientSingleton;
212 + const client = yield* clientSingleton.getFor({ userApiKey: params.userApiKey });
213 + const info = yield* client.auth.session.retrieveInfo({
214 + ...orgScopedOptions(params.orgId),
215 + ...undecoded,
216 + });
217 + return yield* requireSessionProject(info);
218 + });
219 +
220 +// The create-api-key response shape is not documented in the client. Walk the
221 +// body for the first `uak_`/`ak_`-prefixed string under a key-like name.
222 +const getApiKeyFromPayload = (payload: unknown): string | undefined => {
223 + const candidates = new Set<string>(['api_key', 'apiKey', 'key', 'token']);
224 + const keyPrefixes = ['uak_', 'ak_'];
225 + const queue: unknown[] = [payload];
226 +
227 + while (queue.length > 0) {
228 + const current = queue.shift();
229 + if (!current || typeof current !== 'object') continue;
230 +
231 + if (Array.isArray(current)) {
232 + queue.push(...current);
233 + continue;
234 + }
235 +
236 + const entries = Object.entries(current as Record<string, unknown>);
237 + for (const [key, value] of entries) {
238 + if (
239 + typeof value === 'string' &&
240 + candidates.has(key) &&
241 + keyPrefixes.some(prefix => value.startsWith(prefix))
242 + ) {
243 + return value;
244 + }
245 + if (value && typeof value === 'object') {
246 + queue.push(value);
247 + }
248 + }
249 + }
250 +
251 + return undefined;
252 +};
253 +
254 +/**
255 + * Mints a project API key. Never retried: a retry after a timed-out create
256 + * would mint a second key the caller never sees.
257 + */
258 +export const createProjectApiKey = (params: {
259 + apiKey: string;
260 + orgId: string;
261 + projectId: string;
262 + name: string;
263 +}): Effect.Effect<string, ClientError, ComposioClientSingleton> =>
264 + Effect.gen(function* () {
265 + const clientSingleton = yield* ComposioClientSingleton;
266 + const client = yield* clientSingleton.getFor({
267 + userApiKey: params.apiKey,
268 + orgId: params.orgId,
269 + projectId: params.projectId,
270 + });
271 + const payload = yield* client.post(`/api/v3/org/project/${params.projectId}/api_keys/create`, {
272 + body: { name: params.name },
273 + maxRetries: 0,
274 + });
275 + const createdApiKey = getApiKeyFromPayload(payload);
276 +
277 + if (!createdApiKey) {
278 + return yield* Effect.fail(
279 + new HttpDecodingError({
280 + cause: 'Create API key response did not contain an API key',
281 + })
282 + );
283 + }
284 +
285 + return createdApiKey;
286 + });
287 +
288 +export const resolveConsumerProject = (params: {
289 + apiKey: string;
290 + orgId: string;
291 +}): Effect.Effect<ConsumerProjectResolveResponse, ClientError, ComposioClientSingleton> =>
292 + Effect.gen(function* () {
293 + const clientSingleton = yield* ComposioClientSingleton;
294 + const client = yield* clientSingleton.getFor({ userApiKey: params.apiKey });
295 + return yield* client.org.consumer.project.resolve(
296 + { 'x-user-api-key': params.apiKey, 'x-org-id': params.orgId },
297 + undecoded
298 + );
299 + });
300 +
301 +/**
302 + * Resolves the latest version of a tool. When `projectApiKey` is given the
303 + * request carries `x-api-key` instead of the user key, so exactly one
304 + * credential is sent.
305 + */
306 +export const getLatestToolVersion = (params: {
307 + apiKey: string;
308 + toolSlug: string;
309 + orgId?: string;
310 + projectId?: string;
311 + projectApiKey?: string;
312 +}): Effect.Effect<LatestToolVersionResponse, ClientError, ComposioClientSingleton> =>
313 + Effect.gen(function* () {
314 + const clientSingleton = yield* ComposioClientSingleton;
315 + const headers = {
316 + ...(params.projectApiKey
317 + ? { 'x-api-key': params.projectApiKey, 'x-user-api-key': null }
318 + : {}),
319 + ...(params.orgId ? { 'x-org-id': params.orgId } : {}),
320 + ...(params.projectId ? { 'x-project-id': params.projectId } : {}),
321 + };
322 + const client = yield* clientSingleton.getFor({
323 + userApiKey: params.apiKey,
324 + orgId: params.orgId,
325 + projectId: params.projectId,
326 + });
327 + const payload = yield* client.get(
328 + `/api/v3/tools/${encodeURIComponent(params.toolSlug)}/get_latest_version`,
329 + { headers }
330 + );
331 + return yield* decode(LatestToolVersionResponse)(payload);
332 + });
333 +
334 +export const getConsumerConnectedToolkits = (params: {
335 + apiKey: string;
336 + orgId: string;
337 + consumerUserId: string;
338 +}): Effect.Effect<ConsumerConnectedToolkitsResponse, ClientError, ComposioClientSingleton> =>
339 + Effect.gen(function* () {
340 + const clientSingleton = yield* ComposioClientSingleton;
341 + const client = yield* clientSingleton.getFor({ userApiKey: params.apiKey });
342 + return yield* client.org.consumer.listConnectedToolkits({
343 + user_id: params.consumerUserId,
344 + 'x-user-api-key': params.apiKey,
345 + 'x-org-id': params.orgId,
346 + });
347 + });
348 +
349 +export class DeveloperProjectNotFoundError extends Data.TaggedError(
350 + 'services/DeveloperProjectNotFoundError'
351 +)<{
352 + readonly orgId: string;
353 + readonly projectName: string;
354 +}> {}
355 +
356 +export class AmbiguousDeveloperProjectNameError extends Data.TaggedError(
357 + 'services/AmbiguousDeveloperProjectNameError'
358 +)<{
359 + readonly orgId: string;
360 + readonly projectName: string;
361 + readonly matches: ReadonlyArray<OrganizationProjectSummary>;
362 +}> {}
363 +
364 +export const findDeveloperProjectByName = (params: {
365 + apiKey: string;
366 + orgId: string;
367 + name: string;
368 + limit?: number;
369 +}): Effect.Effect<
370 + OrganizationProjectSummary,
371 + DeveloperProjectNotFoundError | AmbiguousDeveloperProjectNameError | ClientError,
372 + ComposioClientSingleton
373 +> =>
374 + Effect.gen(function* () {
375 + const projects = yield* listOrgProjects({
376 + apiKey: params.apiKey,
377 + orgId: params.orgId,
378 + limit: params.limit,
379 + });
380 +
381 + const normalizedName = String.toLowerCase(params.name.trim());
382 + const matches = projects.data.filter(
383 + project => String.toLowerCase(project.name) === normalizedName
384 + );
385 +
386 + if (matches.length === 0) {
387 + return yield* Effect.fail(
388 + new DeveloperProjectNotFoundError({
389 + orgId: params.orgId,
390 + projectName: params.name,
391 + })
392 + );
393 + }
394 +
395 + if (matches.length > 1) {
396 + return yield* Effect.fail(
397 + new AmbiguousDeveloperProjectNameError({
398 + orgId: params.orgId,
399 + projectName: params.name,
400 + matches,
401 + })
402 + );
403 + }
404 +
405 + return matches[0];
406 + });
ts/packages/cli/src/services/composio-clients-cached.ts
+2 -5
@@ -5,11 +5,8 @@ import * as BunFileSystem from '@effect/platform-bun/BunFileSystem';
5 import { setupCacheDir } from 'src/effects/setup-cache-dir';
6 import { DEBUG_CONFIG } from 'src/config';
7 import { writeFileAtomic } from 'src/effects/write-file-atomic';
8 -import {
9 - ComposioToolkitsRepository,
10 - InvalidToolkitsError,
11 - type ToolkitProjectScope,
12 -} from './composio-clients';
8 +import { ComposioToolkitsRepository, type ToolkitProjectScope } from './composio-clients';
9 +import { InvalidToolkitsError } from './toolkit-version-validation';
10 import { NodeOs } from './node-os';
11 import { toolkitsFromJSON, toolkitsToJSON, type Toolkits } from 'src/models/toolkits';
12 import {
ts/packages/cli/src/services/composio-clients.ts
+83 -993
@@ -1,32 +1,14 @@
1 -import {
2 - Context,
3 - Data,
4 - Effect,
5 - Layer,
6 - Option,
7 - Predicate,
8 - Schema,
9 - Array,
10 - Order,
11 - String,
12 -} from 'effect';
1 +import { Context, Effect, Layer, Option, Stream, Array, Order, String } from 'effect';
2 import * as FileSystem from 'effect/FileSystem';
3 import * as Path from 'effect/Path';
4 import type { Cause } from 'effect';
16 -import { Composio as _RawComposioClient, APIError, type RequestOptions } from '@composio/client';
17 -import { paginate, type CursorPage } from '@composio/client/pagination';
18 -import type { AuthConfigCreateParams } from '@composio/client/resources/auth-configs';
19 -import type { ConnectedAccountListParams } from '@composio/client/resources/connected-accounts';
20 -import type { OrgListResponse, ProjectListResponse } from '@composio/client/resources/org';
21 -import type {
22 - ConsumerListConnectedToolkitsResponse,
23 - ProjectResolveResponse,
24 -} from '@composio/client/resources/org/consumer';
25 -import type { SessionRetrieveInfoResponse } from '@composio/client/resources/auth';
26 -import { Toolkit, Toolkits, ToolkitDetailed, type ToolkitSearchResult } from 'src/models/toolkits';
27 -import { AuthConfigItem, AuthConfigItems } from 'src/models/auth-configs';
28 -import { ConnectedAccountItem, ConnectedAccountItems } from 'src/models/connected-accounts';
29 -import { TriggerInstanceItems } from 'src/models/triggers';
5 +import { FetchHttpClient, HttpClient } from 'effect/http';
6 +import {
7 + make as makeComposioClient,
8 + VERSION as clientLibraryVersion,
9 + type ComposioClientShape,
10 +} from '@composio/client/effect';
11 +import { Toolkit, Toolkits, ToolkitDetailed } from 'src/models/toolkits';
12 import { ToolsAsEnums, Tools } from 'src/models/tools';
13 import {
14 groupByVersion,
@@ -34,95 +16,26 @@ import {
16 type ToolkitVersionOverrides,
17 } from 'src/effects/toolkit-version-overrides';
18 import { Session, RetrievedSession } from 'src/models/session';
37 -import { TriggerType, TriggerTypes, TriggerTypesAsEnums } from 'src/models/trigger-types';
38 -import { VERSION as clientLibraryVersion } from '@composio/client';
19 +import { TriggerTypes, TriggerTypesAsEnums } from 'src/models/trigger-types';
20 import { cliRequestHeaders } from './client-provenance';
21 import { getCurrentCwdSessionId } from 'src/analytics/dispatch';
22 import { ComposioUserContext, ComposioUserContextLive } from './user-context';
23 import { ProjectContext } from './project-context';
24 import { makeClientMetricsCollector } from './composio-client-metrics';
25 +import { ComposioClientConfigurationError, type ClientError } from './composio-errors';
26 +import { MAX_CONCURRENT_REQUESTS_PER_ENDPOINT, decode, undecoded } from './composio-request';
27 +import { lookupOperations, resourceOperations } from './composio-resource-operations';
28 +import { composioSchemaLoaders } from './composio-schema-loaders';
29 import { NodeOs } from './node-os';
30 +import {
31 + InvalidToolkitsError,
32 + invalidToolkitOn404,
33 + validateToolkitVersionsImpl,
34 + type InvalidToolkitVersionsError,
35 +} from './toolkit-version-validation';
36
37 type NoSuchElementError = Cause.NoSuchElementError;
38
48 -/**
49 - * Error types
50 - */
51 -
52 -/**
53 - * Structured error details from the Composio API error envelope.
54 - */
55 -export interface HttpErrorDetails {
56 - readonly message: string;
57 - readonly suggestedFix?: string;
58 - readonly code: number;
59 -}
60 -
61 -/**
62 - * Error thrown when a HTTP request fails.
63 - *
64 - * `status`, `details`, and `requestId` are populated from the client's
65 - * `APIError` when the failure is an API response; a connection failure or an
66 - * unexpected rejection carries only `cause`.
67 - */
68 -export class HttpServerError extends Data.TaggedError('services/HttpServerError')<{
69 - readonly cause?: unknown;
70 - readonly status?: number;
71 - readonly details?: HttpErrorDetails;
72 - readonly requestId?: string;
73 -}> {}
74 -
75 -/**
76 - * Error thrown when a client cannot be constructed from the current configuration.
77 - */
78 -export class ComposioClientConfigurationError extends Data.TaggedError(
79 - 'services/ComposioClientConfigurationError'
80 -)<{
81 - readonly message: string;
82 - readonly cause: unknown;
83 -}> {}
84 -
85 -/**
86 - * Error thrown when one or more toolkit slugs are invalid.
87 - */
88 -export class InvalidToolkitsError extends Data.TaggedError('services/InvalidToolkitsError')<{
89 - readonly invalidToolkits: ReadonlyArray<string>;
90 - readonly availableToolkits: ReadonlyArray<string>;
91 -}> {}
92 -
93 -/**
94 - * Details about a single invalid version override.
95 - */
96 -export interface InvalidVersionDetail {
97 - readonly toolkit: string;
98 - readonly requestedVersion: string;
99 - readonly availableVersions: ReadonlyArray<string>;
100 -}
101 -
102 -/**
103 - * Error thrown when one or more toolkit version overrides are invalid.
104 - */
105 -export class InvalidToolkitVersionsError extends Data.TaggedError(
106 - 'services/InvalidToolkitVersionsError'
107 -)<{
108 - readonly invalidVersions: ReadonlyArray<InvalidVersionDetail>;
109 -}> {}
110 -
111 -/**
112 - * Error thrown when a HTTP response doesn't match the expected response schema.
113 - */
114 -export class HttpDecodingError extends Data.TaggedError('services/HttpDecodingError')<{
115 - readonly cause?: unknown;
116 -}> {}
117 -
118 -export type HttpError = HttpServerError | HttpDecodingError;
119 -
120 -/**
121 - * Every failure a client call can produce: the request itself, decoding a
122 - * CLI-owned contract, or obtaining a client from the singleton.
123 - */
124 -export type ClientError = HttpError | ComposioClientConfigurationError | NoSuchElementError;
125 -
39 /**
40 * Request helpers
41 */
@@ -130,71 +43,16 @@ export type ClientError = HttpError | ComposioClientConfigurationError | NoSuchE
43 // Maximum items per page allowed by the server
44 const MAX_PAGE_SIZE = 1000;
45
133 -// Maximum concurrent requests per each endpoint
134 -const MAX_CONCURRENT_REQUESTS_PER_ENDPOINT = 4;
135 -
136 -const toHttpServerError = (cause: unknown): HttpServerError => {
137 - if (cause instanceof APIError) {
138 - const details = cause.details;
139 - return new HttpServerError({
140 - cause,
141 - status: cause.status,
142 - requestId: cause.requestId,
143 - details: details
144 - ? { message: details.message, code: details.code, suggestedFix: details.suggested_fix }
145 - : undefined,
146 - });
147 - }
148 - return new HttpServerError({ cause });
149 -};
150 -
46 /**
152 - * Runs one client call. The client parses JSON and rejects on non-2xx, so the
153 - * only work left is mapping its rejection onto `HttpServerError`.
47 + * Runs a paginated listing to exhaustion and returns every item. A page is
48 + * requested only once the one before it arrived, so interrupting the listing
49 + * sends no further request.
50 */
155 -const request = <A, E>(
156 - client: Effect.Effect<_RawComposioClient, E>,
157 - call: (client: _RawComposioClient, signal: AbortSignal) => PromiseLike<A>
158 -): Effect.Effect<A, E | HttpServerError> =>
159 - client.pipe(
160 - Effect.flatMap(resolved =>
161 - Effect.tryPromise({ try: signal => call(resolved, signal), catch: toHttpServerError })
162 - )
163 - );
164 -
165 -/**
166 - * Runs a paginated client call to exhaustion and returns every item, asking
167 - * for `MAX_PAGE_SIZE` items per page.
168 - */
169 -const requestAll = <Page extends CursorPage<unknown>, E>(
170 - client: Effect.Effect<_RawComposioClient, E>,
171 - fetchPage: (
172 - client: _RawComposioClient,
173 - page: { readonly cursor: string | undefined; readonly limit: number },
174 - signal: AbortSignal
175 - ) => PromiseLike<Page>
176 -) =>
177 - request(client, (resolved, signal) =>
178 - paginate<Page>(({ cursor }) =>
179 - fetchPage(resolved, { cursor, limit: MAX_PAGE_SIZE }, signal)
180 - ).toArray()
181 - );
182 -
183 -/**
184 - * Decodes a payload against a CLI-owned contract.
185 - */
186 -const decode =
187 - <S extends Schema.Top>(schema: S) =>
188 - (input: unknown): Effect.Effect<S['Type'], HttpDecodingError, S['DecodingServices']> =>
189 - Schema.decodeUnknownEffect(schema)(input).pipe(
190 - Effect.catchTag(
191 - 'SchemaError',
192 - e =>
193 - new HttpDecodingError({
194 - cause: `SchemaError\n ${e.message}`,
195 - })
196 - )
197 - );
51 +const collectAll = <A, E, E2>(
52 + client: Effect.Effect<ComposioClientShape, E>,
53 + list: (client: ComposioClientShape) => Stream.Stream<A, E2>
54 +): Effect.Effect<Array<A>, E | E2> =>
55 + Effect.flatMap(client, resolved => Stream.runCollect(list(resolved)));
56
57 // Sort items by slug.
58 // TODO: make sure this happens on the server-side.
@@ -206,286 +64,6 @@ const sortBySlug = <T extends { readonly slug: string }>(
64 Order.mapInput(Order.String, (item: T) => item.slug)
65 );
66
209 -/**
210 - * Converts a 404 from a toolkit lookup into `InvalidToolkitsError` naming
211 - * that slug; every other failure propagates unchanged.
212 - */
213 -const invalidToolkitOn404 = <A>(slug: string, toolkit: Effect.Effect<A, ClientError>) =>
214 - Effect.catchTag(
215 - toolkit,
216 - 'services/HttpServerError',
217 - (e): Effect.Effect<never, InvalidToolkitsError | HttpServerError> =>
218 - e.status === 404
219 - ? Effect.fail(
220 - new InvalidToolkitsError({
221 - invalidToolkits: [slug],
222 - availableToolkits: [],
223 - })
224 - )
225 - : Effect.fail(e)
226 - );
227 -
228 -const validateToolkitVersionsImpl = (
229 - retrieveToolkit: (slug: string) => Effect.Effect<Toolkit, ClientError, never>,
230 - overrides: ToolkitVersionOverrides,
231 - relevantToolkits?: ReadonlyArray<string>
232 -): Effect.Effect<
233 - {
234 - validatedOverrides: ToolkitVersionOverrides;
235 - warnings: ReadonlyArray<string>;
236 - },
237 - InvalidToolkitVersionsError | InvalidToolkitsError | ClientError
238 -> =>
239 - Effect.gen(function* () {
240 - const determineOverridesToValidate = (
241 - overrides: ToolkitVersionOverrides,
242 - relevantToolkits?: ReadonlyArray<string>
243 - ): {
244 - overridesToValidate: Array<[toolkit: string, requestedVersion: string]>;
245 - warnings: Array<string>;
246 - } => {
247 - const warnings: string[] = [];
248 - const overridesToValidate: Array<[toolkit: string, requestedVersion: string]> = [];
249 -
250 - if (relevantToolkits) {
251 - const relevantSet = new Set(relevantToolkits.map(s => String.toLowerCase(s)));
252 -
253 - for (const [toolkit, version] of overrides) {
254 - if (relevantSet.has(toolkit)) {
255 - overridesToValidate.push([toolkit, version]);
256 - } else {
257 - warnings.push(
258 - `Version override for "${toolkit}" will be ignored (toolkit not in --toolkits filter)`
259 - );
260 - }
261 - }
262 - } else {
263 - overridesToValidate.push(...overrides.entries());
264 - }
265 -
266 - return { overridesToValidate, warnings };
267 - };
268 -
269 - const fetchToolkitVersionValidationResults = (
270 - overridesToValidate: ReadonlyArray<[toolkit: string, requestedVersion: string]>
271 - ): Effect.Effect<
272 - ReadonlyArray<{
273 - toolkit: string;
274 - requestedVersion: string;
275 - availableVersions: ReadonlyArray<string>;
276 - isValid: boolean;
277 - }>,
278 - InvalidToolkitsError | ClientError
279 - > =>
280 - Effect.all(
281 - overridesToValidate.map(([toolkit, requestedVersion]) =>
282 - invalidToolkitOn404(
283 - toolkit,
284 - retrieveToolkit(toolkit).pipe(
285 - Effect.map(toolkitData => ({
286 - toolkit,
287 - requestedVersion,
288 - availableVersions: toolkitData.meta.available_versions,
289 - isValid: toolkitData.meta.available_versions.includes(requestedVersion),
290 - }))
291 - )
292 - )
293 - ),
294 - { concurrency: MAX_CONCURRENT_REQUESTS_PER_ENDPOINT }
295 - );
296 -
297 - const collectInvalidVersions = (
298 - validationResults: ReadonlyArray<{
299 - toolkit: string;
300 - requestedVersion: string;
301 - availableVersions: ReadonlyArray<string>;
302 - isValid: boolean;
303 - }>
304 - ): ReadonlyArray<InvalidVersionDetail> =>
305 - validationResults
306 - .filter(result => !result.isValid)
307 - .map(result => ({
308 - toolkit: result.toolkit,
309 - requestedVersion: result.requestedVersion,
310 - availableVersions: result.availableVersions,
311 - }));
312 -
313 - if (overrides.size === 0) {
314 - return { validatedOverrides: overrides, warnings: [] as ReadonlyArray<string> };
315 - }
316 -
317 - const { overridesToValidate, warnings } = determineOverridesToValidate(
318 - overrides,
319 - relevantToolkits
320 - );
321 -
322 - if (overridesToValidate.length === 0) {
323 - return {
324 - validatedOverrides: new Map() as ToolkitVersionOverrides,
325 - warnings: warnings as ReadonlyArray<string>,
326 - };
327 - }
328 -
329 - const validationResults = yield* fetchToolkitVersionValidationResults(overridesToValidate);
330 - const invalidVersions = collectInvalidVersions(validationResults);
331 -
332 - if (invalidVersions.length > 0) {
333 - return yield* Effect.fail(new InvalidToolkitVersionsError({ invalidVersions }));
334 - }
335 -
336 - const validatedOverrides = new Map(overridesToValidate) as ToolkitVersionOverrides;
337 - return { validatedOverrides, warnings: warnings as ReadonlyArray<string> };
338 - });
339 -
340 -/**
341 - * CLI-owned response contracts
342 - *
343 - * Response types otherwise come from `@composio/client`. A schema stays here
344 - * only where the CLI owns the contract: output allowlists that keep
345 - * credential-bearing fields off stdout, and the single escape-hatch endpoint
346 - * the client does not type.
347 - */
348 -
349 -// Auth config list response (single page with total_items for "Listing X of Y" display)
350 -export const AuthConfigListResponse = Schema.Struct({
351 - items: AuthConfigItems,
352 - total_items: Schema.Int,
353 - total_pages: Schema.Int,
354 - current_page: Schema.Int,
355 - next_cursor: Schema.NullOr(Schema.String).pipe(
356 - Schema.withDecodingDefaultType(Effect.succeed(null))
357 - ),
358 -}).annotate({ identifier: 'AuthConfigListResponse' });
359 -export type AuthConfigListResponse = Schema.Schema.Type<typeof AuthConfigListResponse>;
360 -
361 -// Connected account list response (single page with total_items for "Listing X of Y" display)
362 -export const ConnectedAccountListResponse = Schema.Struct({
363 - items: ConnectedAccountItems,
364 - total_items: Schema.Int,
365 - total_pages: Schema.Int,
366 - current_page: Schema.Int,
367 - next_cursor: Schema.NullOr(Schema.String).pipe(
368 - Schema.withDecodingDefaultType(Effect.succeed(null))
369 - ),
370 -}).annotate({ identifier: 'ConnectedAccountListResponse' });
371 -export type ConnectedAccountListResponse = Schema.Schema.Type<typeof ConnectedAccountListResponse>;
372 -
373 -// `auth-configs create` prints this response to stdout, so it stays an
374 -// allowlist rather than the client's full type: a field the API adds later
375 -// must not reach a pipe without a decision here.
376 -export const AuthConfigCreateResponse = Schema.Struct({
377 - auth_config: Schema.Struct({
378 - id: Schema.String,
379 - auth_scheme: Schema.String,
380 - is_composio_managed: Schema.Boolean,
381 - }),
382 - toolkit: Schema.Struct({
383 - slug: Schema.String,
384 - }),
385 -}).annotate({ identifier: 'AuthConfigCreateResponse' });
386 -export type AuthConfigCreateResponse = Schema.Schema.Type<typeof AuthConfigCreateResponse>;
387 -
388 -export const LatestToolVersionResponse = Schema.Struct({
389 - tool_slug: Schema.String,
390 - version: Schema.String,
391 -}).annotate({ identifier: 'LatestToolVersionResponse' });
392 -export type LatestToolVersionResponse = Schema.Schema.Type<typeof LatestToolVersionResponse>;
393 -
394 -/**
395 - * Session info as the CLI consumes it: the client's response with `project`
396 - * present. The endpoint answers `project: null` for org-level credentials,
397 - * which every caller here treats as an unusable session.
398 - */
399 -export type SessionInfoResponse = SessionRetrieveInfoResponse & {
400 - readonly project: NonNullable<SessionRetrieveInfoResponse['project']>;
401 -};
402 -
403 -const requireSessionProject = (
404 - info: SessionRetrieveInfoResponse
405 -): Effect.Effect<SessionInfoResponse, HttpDecodingError> =>
406 - info.project === null
407 - ? Effect.fail(
408 - new HttpDecodingError({
409 - cause: 'Session info response has no project (org-level credentials)',
410 - })
411 - )
412 - : Effect.succeed({ ...info, project: info.project });
413 -
414 -/**
415 - * The org member's user id, falling back to the member id. The backend still
416 - * sends `org_member.user_id` although the v3.1 spec omits it, and the persisted
417 - * test user id derives from it, so it is read defensively.
418 - */
419 -export const sessionUserIdOf = (info: SessionInfoResponse): string => {
420 - const member: object = info.org_member;
421 - return Predicate.hasProperty(member, 'user_id') && Predicate.isString(member.user_id)
422 - ? member.user_id
423 - : info.org_member.id;
424 -};
425 -
426 -/**
427 - * The project API key carried by a session, or null. The v3.1 spec names the
428 - * field `key`, and older responses spell it `api_key`; reading both keeps
429 - * `composio dev init` from minting a second key when the backend sends the
430 - * older spelling.
431 - */
432 -export const sessionProjectApiKeyOf = (info: SessionInfoResponse): string | null => {
433 - const apiKey: object | null = info.api_key;
434 - if (apiKey === null) return null;
435 - if (Predicate.hasProperty(apiKey, 'api_key') && Predicate.isString(apiKey.api_key)) {
436 - return apiKey.api_key;
437 - }
438 - return info.api_key?.key ?? null;
439 -};
440 -
441 -/**
442 - * A single project entry returned by GET /api/v3.1/org/project/list.
443 - */
444 -export type OrgProject = ProjectListResponse.Data;
445 -
446 -/**
447 - * Response from GET /api/v3.1/org/project/list.
448 - */
449 -export type OrgProjectListResponse = ProjectListResponse;
450 -
451 -export interface OrganizationSummary {
452 - readonly id: string;
453 - readonly name: string;
454 -}
455 -
456 -export interface OrganizationListResponse {
457 - readonly data: ReadonlyArray<OrganizationSummary>;
458 - readonly total_items: number;
459 -}
460 -
461 -export interface OrganizationProjectSummary {
462 - readonly id: string;
463 - readonly name: string;
464 -}
465 -
466 -export interface OrganizationProjectListResponse {
467 - readonly data: ReadonlyArray<OrganizationProjectSummary>;
468 - readonly total_items: number;
469 -}
470 -
471 -export type ConsumerProjectResolveResponse = ProjectResolveResponse;
472 -export type ConsumerConnectedToolkitsResponse = ConsumerListConnectedToolkitsResponse;
473 -
474 -export interface TriggerInstancesListActiveParams {
475 - user_ids?: string[];
476 - connected_account_ids?: string[];
477 - auth_config_ids?: string[];
478 - trigger_ids?: string[];
479 - trigger_names?: string[];
480 - show_disabled?: boolean;
481 - limit?: number;
482 -}
483 -
484 -export interface TriggerInstanceUpsertParams {
485 - connected_account_id?: string;
486 - trigger_config?: Record<string, unknown>;
487 -}
488 -
67 /**
68 * Client singleton
69 */
@@ -524,15 +102,22 @@ const buildDefaultHeaders = (params: {
102 * Shape exposed by {@link ComposioClientSingleton}.
103 */
104 export interface ComposioClientSingletonShape {
105 + /**
106 + * The client for the user's key and, when the working directory resolves to
107 + * a project, that project's org and project.
108 + */
109 readonly get: () => Effect.Effect<
528 - _RawComposioClient,
110 + ComposioClientShape,
111 ComposioClientConfigurationError | NoSuchElementError
112 >;
113 + /**
114 + * The client for an explicit scope. `userApiKey` defaults to the user's key.
115 + */
116 readonly getFor: (params: {
117 userApiKey?: string;
118 orgId?: string;
119 projectId?: string;
535 - }) => Effect.Effect<_RawComposioClient, ComposioClientConfigurationError | NoSuchElementError>;
120 + }) => Effect.Effect<ComposioClientShape, ComposioClientConfigurationError | NoSuchElementError>;
121 /**
122 * Returns a snapshot of the accumulated metrics (total bytes received and
123 * request count) across every client this singleton built.
@@ -545,11 +130,11 @@ export interface ComposioClientSingletonShape {
130
131 /**
132 * Singleton service that lazily accesses `Config` only when needed, which is used to build and provide
548 - * a raw (uneffectful, Promise-based) Composio client instance.
133 + * a Composio client instance from `@composio/client/effect`.
134 *
550 - * Clients are built with `Composio.fromEnv({}, ...)` so the ambient process
551 - * environment is never consulted: every credential and the base URL come from
552 - * the CLI's own configuration. Custom HTTP base URLs remain supported. The user key is
135 + * Clients are built with `make`, which never consults the ambient process
136 + * environment: every credential and the base URL come from the CLI's own
137 + * configuration. Custom HTTP base URLs remain supported. The user key is
138 * placed in `defaultHeaders` as `x-user-api-key`, which keeps today's wire
139 * bytes on every operation; it is also passed as `userApiKey`, while the
140 * caller-placed header still wins at dispatch.
@@ -561,7 +146,15 @@ const makeComposioClientSingleton = Effect.gen(function* () {
146 const path = yield* Path.Path;
147 const os = yield* NodeOs;
148 const metrics = makeClientMetricsCollector();
564 - const cache = new Map<string, _RawComposioClient>();
149 + // A private memo map: under an application that already built
150 + // `FetchHttpClient.layer`, a shared one would hand back that transport,
151 + // which calls `globalThis.fetch` directly and counts nothing.
152 + const httpClient = yield* Effect.provide(
153 + HttpClient.HttpClient,
154 + Layer.provide(FetchHttpClient.layer, Layer.succeed(FetchHttpClient.Fetch, metrics.fetch)),
155 + { local: true }
156 + );
157 + const cache = new Map<string, ComposioClientShape>();
158
159 const getFor = (params?: { userApiKey?: string; orgId?: string; projectId?: string }) =>
160 Effect.gen(function* () {
@@ -584,9 +177,9 @@ const makeComposioClientSingleton = Effect.gen(function* () {
177
178 const client = yield* Effect.try({
179 try: () =>
587 - // An empty environment prevents implicit env reads, including COMPOSIO_CUSTOM_HEADERS.
588 - _RawComposioClient.fromEnv(
589 - {},
180 + // Responses are validated against the CLI's loader table unless a
181 + // call passes `decode: false`.
182 + makeComposioClient(
183 {
184 apiKey: null,
185 userApiKey: apiKey ?? null,
@@ -594,15 +187,17 @@ const makeComposioClientSingleton = Effect.gen(function* () {
187 baseURL: ctx.data.baseURL,
188 // Preserve support for explicitly configured HTTP backends.
189 allowInsecureHTTP: true,
597 - logLevel: 'off',
190 + deprecationNotices: 'off',
191 defaultHeaders: buildDefaultHeaders({
192 userApiKey: apiKey,
193 orgId: params?.orgId,
194 projectId: params?.projectId,
195 cliSessionId,
196 }),
604 - fetch: metrics.fetch,
605 - }
197 + decode: true,
198 + schemas: composioSchemaLoaders,
199 + },
200 + httpClient
201 ),
202 catch: cause =>
203 new ComposioClientConfigurationError({
@@ -658,465 +253,24 @@ export class ComposioClientSingleton extends Context.Service<
253 Layer.provide(ComposioUserContextLive)
254 );
255 }
661 -
662 -/**
663 - * Account, session-info, and consumer helpers
664 - *
665 - * Standalone functions rather than repository methods: they take explicit
666 - * credentials and scope, and callers already run inside layers that provide
667 - * `ComposioClientSingleton`.
668 - */
669 -
670 -const orgScopedOptions = (orgId: string | undefined): RequestOptions | undefined =>
671 - orgId ? { headers: { 'x-org-id': orgId } } : undefined;
672 -
673 -/**
674 - * Lists organizations available to the current user API key.
675 - */
676 -export const listOrganizations = (params: {
677 - apiKey: string;
678 - limit?: number;
679 -}): Effect.Effect<OrganizationListResponse, ClientError, ComposioClientSingleton> =>
680 - Effect.gen(function* () {
681 - const clientSingleton = yield* ComposioClientSingleton;
682 - const response = yield* request(clientSingleton.getFor({ userApiKey: params.apiKey }), client =>
683 - client.org.list({ limit: params.limit ?? 50 })
684 - );
685 - const organizations = response.organizations.map(
686 - (organization: OrgListResponse.Organization) =>
687 - ({ id: organization.id, name: organization.name }) satisfies OrganizationSummary
688 - );
689 -
690 - return {
691 - data: organizations,
692 - total_items: organizations.length,
693 - };
694 - });
695 -
696 -/**
697 - * Lists projects for a specific organization.
698 - */
699 -export const listOrganizationProjects = (params: {
700 - apiKey: string;
701 - orgId: string;
702 - limit?: number;
703 -}): Effect.Effect<OrganizationProjectListResponse, ClientError, ComposioClientSingleton> =>
704 - Effect.gen(function* () {
705 - const clientSingleton = yield* ComposioClientSingleton;
706 - const response = yield* request(clientSingleton.getFor({ userApiKey: params.apiKey }), client =>
707 - client.org.project.list({ limit: params.limit ?? 50 }, orgScopedOptions(params.orgId))
708 - );
709 - const projects = response.data.map(
710 - (project: OrgProject) =>
711 - ({ id: project.id, name: project.name }) satisfies OrganizationProjectSummary
712 - );
713 -
714 - return {
715 - data: projects,
716 - total_items: projects.length,
717 - };
718 - });
719 -
720 -/**
721 - * Lists all projects for the logged-in user's organization.
722 - *
723 - * @param params.apiKey - UAK (sent as `x-user-api-key`)
724 - * @param params.orgId - Organization ID (sent as `x-org-id`)
725 - * @param params.limit - Max projects to return (default 50)
726 - */
727 -export const listOrgProjects = (params: {
728 - apiKey: string;
729 - orgId: string;
730 - limit?: number;
731 -}): Effect.Effect<OrgProjectListResponse, ClientError, ComposioClientSingleton> =>
732 - Effect.gen(function* () {
733 - const clientSingleton = yield* ComposioClientSingleton;
734 - return yield* request(clientSingleton.getFor({ userApiKey: params.apiKey }), client =>
735 - client.org.project.list(
736 - { list_all_org_projects: true, limit: params.limit ?? 50 },
737 - orgScopedOptions(params.orgId)
738 - )
739 - );
740 - });
741 -
742 -/**
743 - * Calls GET /api/v3.1/auth/session/info with the full layered auth headers.
744 - */
745 -export const getSessionInfo = (params: {
746 - apiKey: string;
747 - orgId: string;
748 - projectId: string;
749 -}): Effect.Effect<SessionInfoResponse, ClientError, ComposioClientSingleton> =>
750 - Effect.gen(function* () {
751 - const clientSingleton = yield* ComposioClientSingleton;
752 - const info = yield* request(
753 - clientSingleton.getFor({
754 - userApiKey: params.apiKey,
755 - orgId: params.orgId,
756 - projectId: params.projectId,
757 - }),
758 - client => client.auth.session.retrieveInfo()
759 - );
760 - return yield* requireSessionProject(info);
761 - });
762 -
763 -/**
764 - * Calls GET /api/v3.1/auth/session/info using the x-user-api-key header.
765 - * Unlike getSessionInfo which requires both org AND project IDs, this variant
766 - * resolves session metadata from the UAK alone — useful during login before
767 - * org/project context is known.
768 - *
769 - * When `orgId` is provided, it is forwarded as `x-org-id` so the backend
770 - * resolves the session against the caller's currently-selected global org
771 - * (set via `composio orgs switch`). Without it, the backend falls back to the
772 - * API key's home org, which makes the response ignore any org switch.
773 - */
774 -export const getSessionInfoByUserApiKey = (params: {
775 - userApiKey: string;
776 - orgId?: string;
777 -}): Effect.Effect<SessionInfoResponse, ClientError, ComposioClientSingleton> =>
778 - Effect.gen(function* () {
779 - const clientSingleton = yield* ComposioClientSingleton;
780 - const info = yield* request(clientSingleton.getFor({ userApiKey: params.userApiKey }), client =>
781 - client.auth.session.retrieveInfo(orgScopedOptions(params.orgId))
782 - );
783 - return yield* requireSessionProject(info);
784 - });
785 -
786 -// The create-api-key response shape is not documented in the client. Walk the
787 -// body for the first `uak_`/`ak_`-prefixed string under a key-like name.
788 -const getApiKeyFromPayload = (payload: unknown): string | undefined => {
789 - const candidates = new Set<string>(['api_key', 'apiKey', 'key', 'token']);
790 - const keyPrefixes = ['uak_', 'ak_'];
791 - const queue: unknown[] = [payload];
792 -
793 - while (queue.length > 0) {
794 - const current = queue.shift();
795 - if (!current || typeof current !== 'object') continue;
796 -
797 - if (Array.isArray(current)) {
798 - queue.push(...current);
799 - continue;
800 - }
801 -
802 - const entries = Object.entries(current as Record<string, unknown>);
803 - for (const [key, value] of entries) {
804 - if (
805 - typeof value === 'string' &&
806 - candidates.has(key) &&
807 - keyPrefixes.some(prefix => value.startsWith(prefix))
808 - ) {
809 - return value;
810 - }
811 - if (value && typeof value === 'object') {
812 - queue.push(value);
813 - }
814 - }
815 - }
816 -
817 - return undefined;
818 -};
819 -
820 -/**
821 - * Mints a project API key. Never retried: a retry after a timed-out create
822 - * would mint a second key the caller never sees.
823 - */
824 -export const createProjectApiKey = (params: {
825 - apiKey: string;
826 - orgId: string;
827 - projectId: string;
828 - name: string;
829 -}): Effect.Effect<string, ClientError, ComposioClientSingleton> =>
830 - Effect.gen(function* () {
831 - const clientSingleton = yield* ComposioClientSingleton;
832 - const payload = yield* request(
833 - clientSingleton.getFor({
834 - userApiKey: params.apiKey,
835 - orgId: params.orgId,
836 - projectId: params.projectId,
837 - }),
838 - client =>
839 - client.post<unknown>(`/api/v3/org/project/${params.projectId}/api_keys/create`, {
840 - body: { name: params.name },
841 - maxRetries: 0,
842 - })
843 - );
844 - const createdApiKey = getApiKeyFromPayload(payload);
845 -
846 - if (!createdApiKey) {
847 - return yield* Effect.fail(
848 - new HttpDecodingError({
849 - cause: 'Create API key response did not contain an API key',
850 - })
851 - );
852 - }
853 -
854 - return createdApiKey;
855 - });
856 -
857 -export const resolveConsumerProject = (params: {
858 - apiKey: string;
859 - orgId: string;
860 -}): Effect.Effect<ConsumerProjectResolveResponse, ClientError, ComposioClientSingleton> =>
861 - Effect.gen(function* () {
862 - const clientSingleton = yield* ComposioClientSingleton;
863 - return yield* request(clientSingleton.getFor({ userApiKey: params.apiKey }), client =>
864 - client.org.consumer.project.resolve({
865 - 'x-user-api-key': params.apiKey,
866 - 'x-org-id': params.orgId,
867 - })
868 - );
869 - });
870 -
871 -/**
872 - * Resolves the latest version of a tool. When `projectApiKey` is given the
873 - * request carries `x-api-key` instead of the user key, so exactly one
874 - * credential is sent.
875 - */
876 -export const getLatestToolVersion = (params: {
877 - apiKey: string;
878 - toolSlug: string;
879 - orgId?: string;
880 - projectId?: string;
881 - projectApiKey?: string;
882 -}): Effect.Effect<LatestToolVersionResponse, ClientError, ComposioClientSingleton> =>
883 - Effect.gen(function* () {
884 - const clientSingleton = yield* ComposioClientSingleton;
885 - const headers = {
886 - ...(params.projectApiKey
887 - ? { 'x-api-key': params.projectApiKey, 'x-user-api-key': null }
888 - : {}),
889 - ...(params.orgId ? { 'x-org-id': params.orgId } : {}),
890 - ...(params.projectId ? { 'x-project-id': params.projectId } : {}),
891 - };
892 - const payload = yield* request(
893 - clientSingleton.getFor({
894 - userApiKey: params.apiKey,
895 - orgId: params.orgId,
896 - projectId: params.projectId,
897 - }),
898 - client =>
899 - client.get<unknown>(
900 - `/api/v3/tools/${encodeURIComponent(params.toolSlug)}/get_latest_version`,
901 - { headers }
902 - )
903 - );
904 - return yield* decode(LatestToolVersionResponse)(payload);
905 - });
906 -
907 -export const getConsumerConnectedToolkits = (params: {
908 - apiKey: string;
909 - orgId: string;
910 - consumerUserId: string;
911 -}): Effect.Effect<ConsumerConnectedToolkitsResponse, ClientError, ComposioClientSingleton> =>
912 - Effect.gen(function* () {
913 - const clientSingleton = yield* ComposioClientSingleton;
914 - return yield* request(clientSingleton.getFor({ userApiKey: params.apiKey }), client =>
915 - client.org.consumer.listConnectedToolkits({
916 - user_id: params.consumerUserId,
917 - 'x-user-api-key': params.apiKey,
918 - 'x-org-id': params.orgId,
919 - })
920 - );
921 - });
922 -
923 -export class DeveloperProjectNotFoundError extends Data.TaggedError(
924 - 'services/DeveloperProjectNotFoundError'
925 -)<{
926 - readonly orgId: string;
927 - readonly projectName: string;
928 -}> {}
929 -
930 -export class AmbiguousDeveloperProjectNameError extends Data.TaggedError(
931 - 'services/AmbiguousDeveloperProjectNameError'
932 -)<{
933 - readonly orgId: string;
934 - readonly projectName: string;
935 - readonly matches: ReadonlyArray<OrganizationProjectSummary>;
936 -}> {}
937 -
938 -export const findDeveloperProjectByName = (params: {
939 - apiKey: string;
940 - orgId: string;
941 - name: string;
942 - limit?: number;
943 -}): Effect.Effect<
944 - OrganizationProjectSummary,
945 - DeveloperProjectNotFoundError | AmbiguousDeveloperProjectNameError | ClientError,
946 - ComposioClientSingleton
947 -> =>
948 - Effect.gen(function* () {
949 - const projects = yield* listOrgProjects({
950 - apiKey: params.apiKey,
951 - orgId: params.orgId,
952 - limit: params.limit,
953 - });
954 -
955 - const normalizedName = String.toLowerCase(params.name.trim());
956 - const matches = projects.data.filter(
957 - project => String.toLowerCase(project.name) === normalizedName
958 - );
959 -
960 - if (matches.length === 0) {
961 - return yield* Effect.fail(
962 - new DeveloperProjectNotFoundError({
963 - orgId: params.orgId,
964 - projectName: params.name,
965 - })
966 - );
967 - }
968 -
969 - if (matches.length > 1) {
970 - return yield* Effect.fail(
971 - new AmbiguousDeveloperProjectNameError({
972 - orgId: params.orgId,
973 - projectName: params.name,
974 - matches,
975 - })
976 - );
977 - }
978 -
979 - return matches[0];
980 - });
981 -
256 /**
257 * Repositories
258 */
259
986 -/**
987 - * Auth config, connected account, and trigger instance operations: single-page
988 - * CRUD with no catalog caching.
989 - */
990 -const resourceOperations = (client: Effect.Effect<_RawComposioClient, ClientError>) => ({
991 - /**
992 - * Lists auth configs with optional filters. Returns a single page of results.
993 - * @param params - Search/filter parameters
994 - */
995 - listAuthConfigs: (params: {
996 - search?: string;
997 - toolkit_slug?: string;
998 - limit?: number;
999 - show_disabled?: boolean;
1000 - }) =>
1001 - request(client, c =>
1002 - c.authConfigs.list({
1003 - search: params.search,
1004 - toolkit_slug: params.toolkit_slug,
1005 - limit: params.limit,
1006 - show_disabled: params.show_disabled ?? true,
1007 - })
1008 - ).pipe(Effect.flatMap(decode(AuthConfigListResponse))),
1009 - /**
1010 - * Retrieves detailed info about a single auth config by its nanoid.
1011 - * @param nanoid - Auth config ID
1012 - */
1013 - getAuthConfig: (nanoid: string) =>
1014 - request(client, c => c.authConfigs.retrieve(nanoid)).pipe(
1015 - Effect.flatMap(decode(AuthConfigItem))
1016 - ),
1017 - /**
1018 - * Creates a new auth config for a toolkit.
1019 - * @param params - Create parameters (discriminated union: use_composio_managed_auth | use_custom_auth)
1020 - */
1021 - createAuthConfig: (params: AuthConfigCreateParams) =>
1022 - request(client, c => c.authConfigs.create(params)).pipe(
1023 - Effect.flatMap(decode(AuthConfigCreateResponse))
1024 - ),
1025 - /**
1026 - * Soft-deletes an auth config by its nanoid.
1027 - * @param nanoid - Auth config ID
1028 - */
1029 - deleteAuthConfig: (nanoid: string) => request(client, c => c.authConfigs.delete(nanoid)),
1030 - /**
1031 - * List connected accounts with optional filters. Returns a single page of results.
1032 - * @param params - Search/filter parameters
1033 - */
1034 - listConnectedAccounts: (params: {
1035 - toolkit_slugs?: string[];
1036 - user_ids?: string[];
1037 - statuses?: ConnectedAccountListParams['statuses'];
1038 - limit?: number;
1039 - }) =>
1040 - request(client, c =>
1041 - c.connectedAccounts.list({
1042 - toolkit_slugs: params.toolkit_slugs,
1043 - user_ids: params.user_ids,
1044 - statuses: params.statuses,
1045 - limit: params.limit,
1046 - })
1047 - ).pipe(Effect.flatMap(decode(ConnectedAccountListResponse))),
1048 - /**
1049 - * Retrieves detailed info about a single connected account by its nanoid.
1050 - * @param nanoid - Connected account ID (e.g. "con_1a2b3c4d5e6f")
1051 - */
1052 - getConnectedAccount: (nanoid: string) =>
1053 - request(client, c => c.connectedAccounts.retrieve(nanoid)).pipe(
1054 - Effect.flatMap(decode(ConnectedAccountItem))
1055 - ),
1056 - /**
1057 - * Soft-deletes a connected account by its nanoid.
1058 - * @param nanoid - Connected account ID
1059 - */
1060 - deleteConnectedAccount: (nanoid: string) =>
1061 - request(client, c => c.connectedAccounts.delete(nanoid)),
1062 - /**
1063 - * Creates a new authentication link session for connecting an external account.
1064 - * @param params - auth_config_id and user_id
1065 - */
1066 - createConnectedAccountLink: (params: { auth_config_id: string; user_id: string }) =>
1067 - request(client, c => c.link.create(params)),
1068 - /**
1069 - * Lists active trigger instances with optional filters.
1070 - * Returns a single page of results.
1071 - */
1072 - listActiveTriggers: (params: TriggerInstancesListActiveParams) =>
1073 - request(client, c =>
1074 - c.triggerInstances.listActive({
1075 - user_ids: params.user_ids,
1076 - connected_account_ids: params.connected_account_ids,
1077 - auth_config_ids: params.auth_config_ids,
1078 - trigger_ids: params.trigger_ids,
1079 - trigger_names: params.trigger_names,
1080 - show_disabled: params.show_disabled,
1081 - limit: params.limit,
1082 - })
1083 - ).pipe(
1084 - Effect.flatMap(response =>
1085 - decode(TriggerInstanceItems)(response.items).pipe(
1086 - // `triggers status` prints `total_items` directly, so a response that
1087 - // omits a count renders as a number rather than `undefined`.
1088 - Effect.map(items => ({
1089 - ...response,
1090 - items,
1091 - total_items: response.total_items ?? items.length,
1092 - total_pages: response.total_pages ?? 1,
1093 - current_page: response.current_page ?? 1,
1094 - next_cursor: response.next_cursor ?? null,
1095 - }))
1096 - )
1097 - )
1098 - ),
1099 - createTrigger: (triggerSlug: string, params?: TriggerInstanceUpsertParams) =>
1100 - request(client, c => c.triggerInstances.upsert(triggerSlug, params)),
1101 - enableTrigger: (triggerId: string) =>
1102 - request(client, c => c.triggerInstances.manage.update(triggerId, { status: 'enable' })),
1103 - disableTrigger: (triggerId: string) =>
1104 - request(client, c => c.triggerInstances.manage.update(triggerId, { status: 'disable' })),
1105 - deleteTrigger: (triggerId: string) =>
1106 - request(client, c => c.triggerInstances.manage.delete(triggerId)),
1107 -});
1108 -
260 const makeComposioToolkitsRepository = Effect.gen(function* () {
261 const clientSingleton = yield* ComposioClientSingleton;
262 const client = clientSingleton.get();
263
264 const listToolkits = (managedBy?: 'project', scope?: ToolkitProjectScope) =>
1114 - requestAll(scope ? clientSingleton.getFor(scope) : client, (c, { cursor, limit }, signal) =>
1115 - c.toolkits.list({ cursor, limit, managed_by: managedBy }, { signal })
265 + collectAll(scope ? clientSingleton.getFor(scope) : client, c =>
266 + c.toolkits.listStream({ limit: MAX_PAGE_SIZE, managed_by: managedBy }, undecoded)
267 ).pipe(Effect.flatMap(decode(Toolkits)), Effect.map(sortBySlug));
268
269 const getToolkitDetailed = (slug: string) =>
1119 - request(client, c => c.toolkits.retrieve(slug)).pipe(Effect.flatMap(decode(ToolkitDetailed)));
270 + client.pipe(
271 + Effect.flatMap(c => c.toolkits.retrieve(slug, undefined, undecoded)),
272 + Effect.flatMap(decode(ToolkitDetailed))
273 + );
274
275 // The retrieve endpoint omits `auth_schemes`; fill it so the result
276 // satisfies the catalog `Toolkit` contract.
@@ -1151,9 +305,9 @@ const makeComposioToolkitsRepository = Effect.gen(function* () {
305 ).pipe(Effect.map(sortBySlug));
306
307 const listTools = (query: { toolkit_slug?: string; toolkit_versions: string }) =>
1154 - requestAll(client, (c, { cursor, limit }, signal) =>
1155 - c.tools.list({ ...query, cursor, limit }, { signal })
1156 - ).pipe(Effect.flatMap(decode(Tools)));
308 + collectAll(client, c => c.tools.listStream({ ...query, limit: MAX_PAGE_SIZE }, undecoded)).pipe(
309 + Effect.flatMap(decode(Tools))
310 + );
311
312 return {
313 getToolkits,
@@ -1164,7 +318,10 @@ const makeComposioToolkitsRepository = Effect.gen(function* () {
318 * Retrieve a list of all available tool enumeration values (tool slugs) for the project.
319 */
320 getToolsAsEnums: () =>
1167 - request(client, c => c.tools.retrieveEnum()).pipe(Effect.flatMap(decode(ToolsAsEnums))),
321 + client.pipe(
322 + Effect.flatMap(c => c.tools.retrieveEnum(undecoded)),
323 + Effect.flatMap(decode(ToolsAsEnums))
324 + ),
325 /**
326 * Fetches tools with optional toolkit filtering, always at the latest
327 * toolkit version. For per-toolkit versions use `getToolsByVersionSpecs`.
@@ -1191,31 +348,20 @@ const makeComposioToolkitsRepository = Effect.gen(function* () {
348 * Retrieves a list of all available trigger type enum values that can be used across the API.
349 */
350 getTriggerTypesAsEnums: () =>
1194 - request(client, c => c.triggersTypes.retrieveEnum()).pipe(
351 + client.pipe(
352 + Effect.flatMap(c => c.triggersTypes.retrieveEnum(undecoded)),
353 Effect.flatMap(decode(TriggerTypesAsEnums))
354 ),
1197 - /**
1198 - * Retrieves detailed info about a single trigger type by slug.
1199 - * @param slug - Trigger type slug (e.g. "GMAIL_NEW_GMAIL_MESSAGE")
1200 - */
1201 - getTriggerTypeDetailed: (slug: string) =>
1202 - request(client, c => c.triggersTypes.retrieve(slug)).pipe(
1203 - Effect.flatMap(decode(TriggerType))
1204 - ),
355 /**
356 * Fetches trigger types with optional toolkit filtering.
357 * When toolkitSlugs is provided, fetches all matching trigger types.
358 * @param toolkitSlugs - Optional array of toolkit slugs to filter by
359 */
360 getTriggerTypes: (toolkitSlugs?: ReadonlyArray<string>) =>
1211 - requestAll(client, (c, { cursor, limit }, signal) =>
1212 - c.triggersTypes.list(
1213 - {
1214 - cursor,
1215 - limit,
1216 - toolkit_slugs: toolkitSlugs ? [...toolkitSlugs] : undefined,
1217 - },
1218 - { signal }
361 + collectAll(client, c =>
362 + c.triggersTypes.listStream(
363 + { limit: MAX_PAGE_SIZE, toolkit_slugs: toolkitSlugs ? [...toolkitSlugs] : undefined },
364 + undecoded
365 )
366 ).pipe(Effect.flatMap(decode(TriggerTypes)), Effect.map(sortBySlug)),
367 /**
@@ -1278,70 +424,12 @@ const makeComposioToolkitsRepository = Effect.gen(function* () {
424 },
425 InvalidToolkitVersionsError | InvalidToolkitsError | ClientError
426 > => validateToolkitVersionsImpl(getToolkit, overrides, relevantToolkits),
1281 - /**
1282 - * Searches toolkits with optional filters. Returns a single page of results.
1283 - * @param params - Search/filter parameters
1284 - */
1285 - searchToolkits: (params: {
1286 - search?: string;
1287 - category?: string;
1288 - limit?: number;
1289 - cursor?: string;
1290 - }): Effect.Effect<ToolkitSearchResult, ClientError> =>
1291 - request(client, c =>
1292 - c.toolkits.list({
1293 - search: params.search,
1294 - category: params.category,
1295 - limit: params.limit,
1296 - cursor: params.cursor,
1297 - })
1298 - ).pipe(
1299 - Effect.flatMap(response =>
1300 - decode(Toolkits)(response.items).pipe(
1301 - Effect.map(
1302 - items =>
1303 - ({
1304 - items,
1305 - total_items: response.total_items,
1306 - total_pages: response.total_pages,
1307 - next_cursor: response.next_cursor ?? null,
1308 - }) satisfies ToolkitSearchResult
1309 - )
1310 - )
1311 - )
1312 - ),
427 /**
428 * Retrieves detailed toolkit info including auth_config_details.
429 * @param slug - Toolkit slug
430 */
431 getToolkitDetailed,
1318 - /**
1319 - * Searches tools with optional filters. Returns a single page of results.
1320 - * @param params - Search/filter parameters
1321 - */
1322 - searchTools: (params: {
1323 - search?: string;
1324 - toolkit_slug?: string;
1325 - tags?: string;
1326 - limit?: number;
1327 - cursor?: string;
1328 - }) =>
1329 - request(client, c =>
1330 - c.tools.list({
1331 - search: params.search,
1332 - toolkit_slug: params.toolkit_slug,
1333 - tags: params.tags ? params.tags.split(',').map(t => t.trim()) : undefined,
1334 - limit: params.limit,
1335 - cursor: params.cursor,
1336 - toolkit_versions: 'latest',
1337 - })
1338 - ),
1339 - /**
1340 - * Retrieves detailed info about a single tool by slug.
1341 - * @param slug - Tool slug (e.g. "GMAIL_SEND_EMAIL")
1342 - */
1343 - getToolDetailed: (slug: string) =>
1344 - request(client, c => c.tools.retrieve(slug, { toolkit_versions: 'latest' })),
432 + ...lookupOperations(client),
433 ...resourceOperations(client),
434 };
435 });
@@ -1368,19 +456,21 @@ const makeComposioSessionRepository = Effect.gen(function* () {
456 * @param params.scope - 'user' for login, 'project' for init (future)
457 */
458 createSession: (params?: { scope?: 'user' | 'project' }) =>
1371 - request(client, c => c.cli.createSession({ scope: params?.scope ?? 'user' })).pipe(
459 + client.pipe(
460 + Effect.flatMap(c => c.cli.createSession({ scope: params?.scope ?? 'user' }, undecoded)),
461 Effect.flatMap(decode(Session))
462 ),
463 /**
464 * Retrieves the current state of a CLI session using either the session ID (UUID) or the 6-character code.
465 */
466 getSession: (session: { id: string }) =>
1378 - request(client, c => c.cli.getSession({ id: session.id })).pipe(
467 + client.pipe(
468 + Effect.flatMap(c => c.cli.getSession({ id: session.id }, undecoded)),
469 Effect.flatMap(decode(RetrievedSession))
470 ),
1381 - getRealtimeCredentials: () => request(client, c => c.cli.realtime.credentials()),
471 + getRealtimeCredentials: () => Effect.flatMap(client, c => c.cli.realtime.credentials()),
472 authRealtimeChannel: (params: { channel_name: string; socket_id: string }) =>
1383 - request(client, c => c.cli.realtime.auth(params)),
473 + Effect.flatMap(client, c => c.cli.realtime.auth(params, undecoded)),
474 };
475 });
476
ts/packages/cli/src/services/composio-errors.ts new
+31
@@ -0,0 +1,31 @@
1 +import { Data } from 'effect';
2 +import type { Cause } from 'effect';
3 +import type { ComposioError } from '@composio/client/effect';
4 +
5 +type NoSuchElementError = Cause.NoSuchElementError;
6 +
7 +/**
8 + * Error thrown when a client cannot be constructed from the current configuration.
9 + */
10 +export class ComposioClientConfigurationError extends Data.TaggedError(
11 + 'services/ComposioClientConfigurationError'
12 +)<{
13 + readonly message: string;
14 + readonly cause: unknown;
15 +}> {}
16 +
17 +/**
18 + * Error thrown when a HTTP response doesn't match the expected response schema.
19 + */
20 +export class HttpDecodingError extends Data.TaggedError('services/HttpDecodingError')<{
21 + readonly cause?: unknown;
22 +}> {}
23 +
24 +export type HttpError = ComposioError | HttpDecodingError;
25 +
26 +/**
27 + * Every failure a client call can produce: the request itself, as the client's
28 + * own tagged error, decoding a CLI-owned contract, or obtaining a client from
29 + * the singleton.
30 + */
31 +export type ClientError = HttpError | ComposioClientConfigurationError | NoSuchElementError;
ts/packages/cli/src/services/composio-request.ts new
+31
@@ -0,0 +1,31 @@
1 +import { Effect, Schema } from 'effect';
2 +import type { RequestOptions } from '@composio/client/effect';
3 +import { HttpDecodingError } from './composio-errors';
4 +
5 +// Maximum concurrent requests per each endpoint
6 +export const MAX_CONCURRENT_REQUESTS_PER_ENDPOINT = 4;
7 +
8 +/**
9 + * The client validates a response against its own schema unless a call opts
10 + * out. A call opts out when the CLI decodes the response with a schema it
11 + * owns, when the endpoint is one the CLI reads leniently on purpose, or when
12 + * the call is not a read: failing after the server acted would invite a retry
13 + * that repeats the side effect.
14 + */
15 +export const undecoded = { decode: false } satisfies RequestOptions;
16 +
17 +/**
18 + * Decodes a payload against a CLI-owned contract.
19 + */
20 +export const decode =
21 + <S extends Schema.Top>(schema: S) =>
22 + (input: unknown): Effect.Effect<S['Type'], HttpDecodingError, S['DecodingServices']> =>
23 + Schema.decodeUnknownEffect(schema)(input).pipe(
24 + Effect.catchTag(
25 + 'SchemaError',
26 + e =>
27 + new HttpDecodingError({
28 + cause: `SchemaError\n ${e.message}`,
29 + })
30 + )
31 + );
ts/packages/cli/src/services/composio-resource-operations.ts new
+259
@@ -0,0 +1,259 @@
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';
5 +import {
6 + AuthConfigCreateResponse,
7 + AuthConfigItem,
8 + AuthConfigListResponse,
9 +} from 'src/models/auth-configs';
10 +import { ConnectedAccountItem, ConnectedAccountListResponse } from 'src/models/connected-accounts';
11 +import { Toolkits, type ToolkitSearchResult } from 'src/models/toolkits';
12 +import { TriggerInstanceItems } from 'src/models/triggers';
13 +import { TriggerType } from 'src/models/trigger-types';
14 +import type { ClientError } from './composio-errors';
15 +import { decode, undecoded } from './composio-request';
16 +
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 +
32 +/**
33 + * Auth config, connected account, and trigger instance operations: single-page
34 + * CRUD with no catalog caching.
35 + */
36 +export const resourceOperations = (client: Effect.Effect<ComposioClientShape, ClientError>) => ({
37 + /**
38 + * Lists auth configs with optional filters. Returns a single page of results.
39 + * @param params - Search/filter parameters
40 + */
41 + listAuthConfigs: (params: {
42 + search?: string;
43 + toolkit_slug?: string;
44 + limit?: number;
45 + show_disabled?: boolean;
46 + }) =>
47 + client.pipe(
48 + Effect.flatMap(c =>
49 + c.authConfigs.list(
50 + {
51 + search: params.search,
52 + toolkit_slug: params.toolkit_slug,
53 + limit: params.limit,
54 + show_disabled: params.show_disabled ?? true,
55 + },
56 + undecoded
57 + )
58 + ),
59 + Effect.flatMap(decode(AuthConfigListResponse))
60 + ),
61 + /**
62 + * Retrieves detailed info about a single auth config by its nanoid.
63 + * @param nanoid - Auth config ID
64 + */
65 + getAuthConfig: (nanoid: string) =>
66 + client.pipe(
67 + Effect.flatMap(c => c.authConfigs.retrieve(nanoid, undecoded)),
68 + Effect.flatMap(decode(AuthConfigItem))
69 + ),
70 + /**
71 + * Creates a new auth config for a toolkit.
72 + * @param params - Create parameters (discriminated union: use_composio_managed_auth | use_custom_auth)
73 + */
74 + createAuthConfig: (params: AuthConfigCreateParams) =>
75 + client.pipe(
76 + Effect.flatMap(c => c.authConfigs.create(params, undecoded)),
77 + Effect.flatMap(decode(AuthConfigCreateResponse))
78 + ),
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 + ),
109 + /**
110 + * Retrieves detailed info about a single connected account by its nanoid.
111 + * @param nanoid - Connected account ID (e.g. "con_1a2b3c4d5e6f")
112 + */
113 + getConnectedAccount: (nanoid: string) =>
114 + client.pipe(
115 + Effect.flatMap(c => c.connectedAccounts.retrieve(nanoid, undecoded)),
116 + Effect.flatMap(decode(ConnectedAccountItem))
117 + ),
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)),
130 + /**
131 + * Lists active trigger instances with optional filters.
132 + * Returns a single page of results.
133 + */
134 + listActiveTriggers: (params: TriggerInstancesListActiveParams) =>
135 + client.pipe(
136 + Effect.flatMap(c =>
137 + c.triggerInstances.listActive(
138 + {
139 + user_ids: params.user_ids,
140 + connected_account_ids: params.connected_account_ids,
141 + auth_config_ids: params.auth_config_ids,
142 + trigger_ids: params.trigger_ids,
143 + trigger_names: params.trigger_names,
144 + show_disabled: params.show_disabled,
145 + limit: params.limit,
146 + },
147 + undecoded
148 + )
149 + ),
150 + Effect.flatMap(response =>
151 + decode(TriggerInstanceItems)(response.items).pipe(
152 + // `triggers status` prints `total_items` directly, so a response that
153 + // omits a count renders as a number rather than `undefined`.
154 + Effect.map(items => ({
155 + ...response,
156 + items,
157 + total_items: response.total_items ?? items.length,
158 + total_pages: response.total_pages ?? 1,
159 + current_page: response.current_page ?? 1,
160 + next_cursor: response.next_cursor ?? null,
161 + }))
162 + )
163 + )
164 + ),
165 + createTrigger: (triggerSlug: string, params?: TriggerInstanceUpsertParams) =>
166 + Effect.flatMap(client, c => c.triggerInstances.upsert(triggerSlug, params, undecoded)),
167 + enableTrigger: (triggerId: string) =>
168 + Effect.flatMap(client, c =>
169 + c.triggerInstances.manage.update(triggerId, { status: 'enable' }, undecoded)
170 + ),
171 + disableTrigger: (triggerId: string) =>
172 + Effect.flatMap(client, c =>
173 + c.triggerInstances.manage.update(triggerId, { status: 'disable' }, undecoded)
174 + ),
175 + deleteTrigger: (triggerId: string) =>
176 + Effect.flatMap(client, c => c.triggerInstances.manage.delete(triggerId, undecoded)),
177 +});
178 +
179 +/**
180 + * Single-page searches and single-item lookups that sit outside the catalog
181 + * fetches: none of them is cached.
182 + */
183 +export const lookupOperations = (client: Effect.Effect<ComposioClientShape, ClientError>) => ({
184 + /**
185 + * Searches toolkits with optional filters. Returns a single page of results.
186 + * @param params - Search/filter parameters
187 + */
188 + searchToolkits: (params: {
189 + search?: string;
190 + category?: string;
191 + limit?: number;
192 + cursor?: string;
193 + }): Effect.Effect<ToolkitSearchResult, ClientError> =>
194 + Effect.flatMap(client, c =>
195 + c.toolkits.list(
196 + {
197 + search: params.search,
198 + category: params.category,
199 + limit: params.limit,
200 + cursor: params.cursor,
201 + },
202 + undecoded
203 + )
204 + ).pipe(
205 + Effect.flatMap(response =>
206 + decode(Toolkits)(response.items).pipe(
207 + Effect.map(
208 + items =>
209 + ({
210 + items,
211 + total_items: response.total_items,
212 + total_pages: response.total_pages,
213 + next_cursor: response.next_cursor ?? null,
214 + }) satisfies ToolkitSearchResult
215 + )
216 + )
217 + )
218 + ),
219 + /**
220 + * Searches tools with optional filters. Returns a single page of results.
221 + * @param params - Search/filter parameters
222 + */
223 + searchTools: (params: {
224 + search?: string;
225 + toolkit_slug?: string;
226 + tags?: string;
227 + limit?: number;
228 + cursor?: string;
229 + }) =>
230 + Effect.flatMap(client, c =>
231 + c.tools.list({
232 + search: params.search,
233 + toolkit_slug: params.toolkit_slug,
234 + tags: params.tags ? params.tags.split(',').map(t => t.trim()) : undefined,
235 + limit: params.limit,
236 + cursor: params.cursor,
237 + toolkit_versions: 'latest',
238 + })
239 + ),
240 + /**
241 + * Retrieves detailed info about a single tool by slug.
242 + * @param slug - Tool slug (e.g. "GMAIL_SEND_EMAIL")
243 + *
244 + * Not client-decoded: `execute` treats a failed lookup as "no cached
245 + * definition" and would skip input validation and file uploads on drift
246 + * in a field it never reads.
247 + */
248 + getToolDetailed: (slug: string) =>
249 + Effect.flatMap(client, c => c.tools.retrieve(slug, { toolkit_versions: 'latest' }, undecoded)),
250 + /**
251 + * Retrieves detailed info about a single trigger type by slug.
252 + * @param slug - Trigger type slug (e.g. "GMAIL_NEW_GMAIL_MESSAGE")
253 + */
254 + getTriggerTypeDetailed: (slug: string) =>
255 + client.pipe(
256 + Effect.flatMap(c => c.triggersTypes.retrieve(slug, undefined, undecoded)),
257 + Effect.flatMap(decode(TriggerType))
258 + ),
259 +});
ts/packages/cli/src/services/composio-schema-loaders.ts new
+36
@@ -0,0 +1,36 @@
1 +import type { SchemaLoaders } from '@composio/client/effect';
2 +
3 +/**
4 + * Response schemas for the API reads the CLI consumes through the client's own
5 + * types, each behind the `import()` that loads it.
6 + *
7 + * This is a subset of the `schemaLoaders` table `@composio/client/effect/schemas`
8 + * exports. That table names every schema module the client ships, so importing
9 + * it would put all of them in the binary. A typed call whose operation is not
10 + * listed here must pass `decode: false`; without it the client fails the call
11 + * before sending anything.
12 + */
13 +export const composioSchemaLoaders = {
14 + 'cli.realtime.credentials': async () =>
15 + (await import('@composio/client/effect/schemas/cli/realtime/credentials'))
16 + .RealtimeCredentialsResponse,
17 + 'logs.tools.list': async () =>
18 + (await import('@composio/client/effect/schemas/logs/tools/list')).ToolListResponse,
19 + 'logs.tools.retrieve': async () =>
20 + (await import('@composio/client/effect/schemas/logs/tools/retrieve')).ToolRetrieveResponse,
21 + 'org.consumer.listConnectedToolkits': async () =>
22 + (await import('@composio/client/effect/schemas/org/consumer/list-connected-toolkits'))
23 + .ConsumerListConnectedToolkitsResponse,
24 + 'org.list': async () =>
25 + (await import('@composio/client/effect/schemas/org/list')).OrgListResponse,
26 + 'org.project.list': async () =>
27 + (await import('@composio/client/effect/schemas/org/project/list')).ProjectListResponse,
28 + 'toolRouter.session.search': async () =>
29 + (await import('@composio/client/effect/schemas/tool-router/session/search'))
30 + .SessionSearchResponse,
31 + 'toolRouter.session.toolkits': async () =>
32 + (await import('@composio/client/effect/schemas/tool-router/session/toolkits'))
33 + .SessionToolkitsResponse,
34 + 'tools.list': async () =>
35 + (await import('@composio/client/effect/schemas/tools/list')).ToolListResponse,
36 +} satisfies SchemaLoaders;
ts/packages/cli/src/services/connected-account-selection.ts
+27 -27
@@ -1,4 +1,4 @@
1 -import type { Composio } from '@composio/client';
1 +import type { ComposioClientShape } from '@composio/client/effect';
2 import { Data, Effect, Option, Schema } from 'effect';
3 import type { ConnectedAccountItem } from 'src/models/connected-accounts';
4 import { decodeConnectedAccountItems } from 'src/effects/decode-connected-account-list';
@@ -138,12 +138,12 @@ export const formatConnectedAccountChoices = (
138 ): ReadonlyArray<string> =>
139 items.filter(isUsableConnectedAccount).sort(compareNewestFirst).map(formatConnectedAccountChoice);
140
141 -// `Composio` clients come from `ComposioClientSingleton`, one instance per
141 +// Clients come from `ComposioClientSingleton`, one instance per
142 // org/project, so identity is a sound cache key. Ids instead of the object
143 // itself keep the memo key a string.
144 -const clientIds = new WeakMap<Composio, number>();
144 +const clientIds = new WeakMap<ComposioClientShape, number>();
145 let nextClientId = 0;
146 -const clientId = (client: Composio): number => {
146 +const clientId = (client: ComposioClientShape): number => {
147 let id = clientIds.get(client);
148 if (id === undefined) {
149 id = nextClientId++;
@@ -164,24 +164,23 @@ const clientId = (client: Composio): number => {
164 * their own `GET /connected_accounts`.
165 *
166 * The page size is the session path's existing one; a user with more active
167 - * accounts than that was already truncated there. Fails with the raw
168 - * rejection; each caller wraps it in its own error.
167 + * accounts than that was already truncated there. Fails with the client's
168 + * error; each caller wraps it in its own error.
169 */
170 const ACTIVE_ACCOUNTS_PAGE_SIZE = 1000;
171
172 export const listActiveConnectedAccounts = memoizeInProcess({
173 - keyOf: (input: { readonly client: Composio; readonly userId: string }) =>
173 + keyOf: (input: { readonly client: ComposioClientShape; readonly userId: string }) =>
174 `${clientId(input.client)}\u0000${input.userId}`,
175 make: ({ client, userId }) =>
176 - Effect.tryPromise({
177 - try: () =>
178 - client.connectedAccounts.list({
179 - user_ids: [userId],
180 - statuses: ['ACTIVE'],
181 - limit: ACTIVE_ACCOUNTS_PAGE_SIZE,
182 - }),
183 - catch: cause => cause,
184 - }),
176 + client.connectedAccounts.list(
177 + {
178 + user_ids: [userId],
179 + statuses: ['ACTIVE'],
180 + limit: ACTIVE_ACCOUNTS_PAGE_SIZE,
181 + },
182 + { decode: false }
183 + ),
184 });
185
186 const TOOLKIT_ACCOUNTS_PAGE_SIZE = 100;
@@ -190,21 +189,21 @@ const TOOLKIT_ACCOUNTS_PAGE_SIZE = 100;
189 // server order. Kept as the fallback so results stay identical when the
190 // shared list cannot stand in for it.
191 const fetchConnectedAccountsForToolkit = (params: {
193 - readonly client: Composio;
192 + readonly client: ComposioClientShape;
193 readonly userId: string;
194 readonly toolkitSlug: string;
195 }) =>
197 - Effect.tryPromise({
198 - try: () =>
199 - params.client.connectedAccounts.list({
196 + params.client.connectedAccounts
197 + .list(
198 + {
199 toolkit_slugs: [params.toolkitSlug],
200 user_ids: [params.userId],
201 statuses: ['ACTIVE'],
202 limit: TOOLKIT_ACCOUNTS_PAGE_SIZE,
204 - }),
205 - // The raw rejection, so the caller's message reads as it always has.
206 - catch: cause => cause,
207 - }).pipe(Effect.map(response => response.items));
203 + },
204 + { decode: false }
205 + )
206 + .pipe(Effect.map(response => response.items));
207
208 /**
209 * The active accounts of one toolkit, derived from the shared per-user list
@@ -226,7 +225,7 @@ const fetchConnectedAccountsForToolkit = (params: {
225 * so a padded `--toolkit` value resolves the same way on both paths.
226 */
227 export const listConnectedAccountsForToolkit = (params: {
229 - readonly client: Composio;
228 + readonly client: ComposioClientShape;
229 readonly userId: string;
230 readonly toolkitSlug: string;
231 }) =>
@@ -257,7 +256,7 @@ export class ConnectedAccountResolutionError extends Data.TaggedError(
256 }> {}
257
258 export const resolveConnectedAccountForToolkit = (params: {
260 - readonly client: Composio;
259 + readonly client: ComposioClientShape;
260 readonly toolkitSlug?: string;
261 readonly userId: string;
262 readonly selector: Option.Option<string>;
@@ -274,7 +273,8 @@ export const resolveConnectedAccountForToolkit = (params: {
273 Effect.mapError(
274 cause =>
275 new ConnectedAccountResolutionError({
277 - message: `Failed to load connected accounts for toolkit "${toolkitSlug}": ${String(cause)}`,
276 + // "Error: " is how this message has always introduced the client's failure.
277 + message: `Failed to load connected accounts for toolkit "${toolkitSlug}": Error: ${cause.message}`,
278 toolkitSlug,
279 cause,
280 })
ts/packages/cli/src/services/consumer-short-term-cache.ts
+2 -3
@@ -5,12 +5,11 @@ import { APP_CONFIG } from 'src/config';
5 import { JsonRecordSchema } from 'src/effects/json';
6 import { setupCacheDir } from 'src/effects/setup-cache-dir';
7 import { NodeProcess } from 'src/services/node-process';
8 +import { ComposioToolkitsRepository, ComposioClientSingleton } from 'src/services/composio-clients';
9 import {
9 - ComposioToolkitsRepository,
10 - ComposioClientSingleton,
10 getConsumerConnectedToolkits,
11 resolveConsumerProject,
13 -} from 'src/services/composio-clients';
12 +} from 'src/services/composio-account';
13 import { resolveCommandProject } from 'src/services/command-project';
14 import { collectDecodedEntries } from 'src/utils/collect-decoded-entries';
15 import { djb2Hash } from 'src/utils/djb2';
ts/packages/cli/src/services/tool-file-uploads.ts
+31 -22
@@ -1,11 +1,11 @@
1 -// This module's upload pipeline is plain async/await around the raw
2 -// @composio/client promise API. The Effect caller resolves the platform
3 -// FileSystem and Path services and passes the instances in as parameters;
4 -// `readLocalFileBytes` below is the single point where a FileSystem effect
1 +// This module's upload pipeline is plain async/await. The Effect caller
2 +// resolves the platform FileSystem and Path services and the Composio client
3 +// and passes the instances in as parameters; `runToPromise` below is the
4 +// single point where an effect (a FileSystem read, the presigned-URL request)
5 // is run to completion inside this promise pipeline.
6 import type * as FileSystem from 'effect/FileSystem';
7 import type * as Path from 'effect/Path';
8 -import type { Composio as RawComposioClient } from '@composio/client';
8 +import type { ComposioClientShape } from '@composio/client/effect';
9 import { Cause, Data, Effect, Exit, Predicate } from 'effect';
10 import { guessToolkitFromToolSlug } from 'src/utils/toolkit-from-tool-slug';
11
@@ -176,17 +176,21 @@ const readFileFromUrl = async (path: Path.Path, url: string) => {
176 };
177 };
178
179 -// Runs the FileSystem read to completion for the plain-async pipeline above.
180 -// A failed read rejects with the underlying platform error (not a FiberFailure
181 -// wrapper), matching this module's throw-based error contract.
182 -const readLocalFileBytes = (fs: FileSystem.FileSystem, filePath: string): Promise<Uint8Array> =>
183 - Effect.runPromiseExit(fs.readFile(filePath)).then(exit =>
179 +// Runs an effect to completion for the plain-async pipeline above. A failure
180 +// rejects with the underlying error (the platform error of a read, the
181 +// client's error of a request), not a FiberFailure wrapper, matching this
182 +// module's throw-based error contract.
183 +const runToPromise = <A, E>(effect: Effect.Effect<A, E>): Promise<A> =>
184 + Effect.runPromiseExit(effect).then(exit =>
185 Exit.match(exit, {
185 - onFailure: cause => Promise.reject<Uint8Array>(Cause.squash(cause)),
186 - onSuccess: bytes => Promise.resolve(bytes),
186 + onFailure: cause => Promise.reject<A>(Cause.squash(cause)),
187 + onSuccess: value => Promise.resolve(value),
188 })
189 );
190
191 +const readLocalFileBytes = (fs: FileSystem.FileSystem, filePath: string): Promise<Uint8Array> =>
192 + runToPromise(fs.readFile(filePath));
193 +
194 const readFileFromDisk = async (fs: FileSystem.FileSystem, path: Path.Path, filePath: string) => {
195 // Enforce the sensitive-path denylist at the lowest-level local read, so any
196 // caller of this reader (not just `uploadToolInputFiles`) is protected. This
@@ -249,19 +253,24 @@ const uploadFile = async (params: {
253 readonly file: string | File;
254 readonly toolSlug: string;
255 readonly toolkitSlug: string;
252 - readonly client: RawComposioClient;
256 + readonly client: ComposioClientShape;
257 }) => {
258 const fileData = await readUploadSource(params.fs, params.path, params.file);
259 // eslint-disable-next-line no-restricted-imports -- MD5 for the presigned-upload checksum is not available in Web Crypto
260 const { createHash } = await import('node:crypto');
261 const md5 = createHash('md5').update(fileData.bytes).digest('hex');
258 - const presigned = await params.client.files.createPresignedURL({
259 - filename: fileData.fileName,
260 - mimetype: fileData.mimeType,
261 - md5,
262 - tool_slug: params.toolSlug,
263 - toolkit_slug: params.toolkitSlug,
264 - });
262 + const presigned = await runToPromise(
263 + params.client.files.createPresignedURL(
264 + {
265 + filename: fileData.fileName,
266 + mimetype: fileData.mimeType,
267 + md5,
268 + tool_slug: params.toolSlug,
269 + toolkit_slug: params.toolkitSlug,
270 + },
271 + { decode: false }
272 + )
273 + );
274
275 const { ssrfSafeFetch } = await loadSsrfSafeFetch();
276 const uploadResponse = await ssrfSafeFetch(presigned.new_presigned_url, {
@@ -298,7 +307,7 @@ const hydrateFileUploads = async (
307 readonly path: Path.Path;
308 readonly toolSlug: string;
309 readonly toolkitSlug: string;
301 - readonly client: RawComposioClient;
310 + readonly client: ComposioClientShape;
311 }
312 ): Promise<unknown> => {
313 if (schema?.file_uploadable === true) {
@@ -359,7 +368,7 @@ export const uploadToolInputFiles = async (params: {
368 readonly toolSlug: string;
369 readonly arguments_: Record<string, unknown>;
370 readonly inputSchema: JsonSchema;
362 - readonly client: RawComposioClient;
371 + readonly client: ComposioClientShape;
372 readonly toolkitSlug?: string;
373 }): Promise<Record<string, unknown>> => {
374 if (!schemaHasFileUploadable(params.inputSchema)) {
ts/packages/cli/src/services/tool-input-validation.ts
+2 -1
@@ -7,7 +7,8 @@ import {
7 } from '@composio/json-schema-to-effect-schema';
8 import { JsonRecordSchema } from 'src/effects/json';
9 import { setupCacheDir } from 'src/effects/setup-cache-dir';
10 -import { ComposioToolkitsRepository, getLatestToolVersion } from 'src/services/composio-clients';
10 +import { ComposioToolkitsRepository } from 'src/services/composio-clients';
11 +import { getLatestToolVersion } from 'src/services/composio-account';
12 import { memoizeInProcess } from 'src/utils/memoize-in-process';
13 import { logToolDebug } from 'src/services/runtime-debug-logger';
14 import { normalizeFileUploadSchema } from 'src/services/tool-file-uploads';
ts/packages/cli/src/services/tool-permissions.ts
+30 -41
@@ -1,7 +1,7 @@
1 import http from 'node:http';
2 import * as FileSystem from 'effect/FileSystem';
3 import * as Path from 'effect/Path';
4 -import type { Composio as RawComposioClient } from '@composio/client';
4 +import type { ComposioClientShape } from '@composio/client/effect';
5 import open from 'open';
6 import {
7 Data,
@@ -22,7 +22,8 @@ import {
22 isInteractivePermissionUiDisabled,
23 type PermissionCallerAgent,
24 } from 'src/services/permission-ui';
25 -import { ComposioClientSingleton, type ClientError } from 'src/services/composio-clients';
25 +import { ComposioClientSingleton } from 'src/services/composio-clients';
26 +import { type ClientError } from 'src/services/composio-errors';
27 import { ComposioUserContext } from 'src/services/user-context';
28
29 export const ENHANCED_LINK_URL_OVERWRITE = 'https://connect.composio.dev/enhanced';
@@ -303,25 +304,29 @@ const readEnhancedControlsFlag = (payload: ConsumerConfigResponse): boolean =>
304
305 // These two consumer endpoints are absent from the v3.1 spec, so they go
306 // through the client's generic escape hatch rather than a typed resource. The
306 -// client still supplies credentials, retries, and redirect handling.
307 -const requestJson = async <S extends Schema.ConstraintDecoder<unknown>>(
307 +// client still supplies credentials, retries, and redirect handling. Every
308 +// failure, of the request or of the decode, is a `ToolPermissionsRequestError`:
309 +// the callers fail closed on that tag.
310 +const requestJson = <S extends Schema.ConstraintDecoder<unknown>>(
311 responseSchema: S,
312 {
313 client,
314 path,
315 method = 'GET',
316 body,
317 + message,
318 }: {
315 - readonly client: RawComposioClient;
319 + readonly client: ComposioClientShape;
320 readonly path: string;
321 readonly method?: 'GET' | 'POST';
322 readonly body?: unknown;
323 + readonly message: string;
324 }
320 -): Promise<S['Type']> => {
321 - const responseBody: unknown =
322 - method === 'GET' ? await client.get(path) : await client.post(path, { body });
323 - return Schema.decodeUnknownPromise(responseSchema)(responseBody);
324 -};
325 +): Effect.Effect<S['Type'], ToolPermissionsRequestError> =>
326 + (method === 'GET' ? client.get(path) : client.post(path, { body })).pipe(
327 + Effect.flatMap(Schema.decodeUnknownEffect(responseSchema)),
328 + Effect.mapError(cause => new ToolPermissionsRequestError({ path, message, cause }))
329 + );
330
331 /**
332 * The client for the caller's org and project, with a failure the permission
@@ -332,7 +337,7 @@ const permissionsClient = (params: {
337 readonly orgId: string;
338 readonly projectId: string;
339 readonly path: string;
335 -}): Effect.Effect<RawComposioClient, ToolPermissionsRequestError, ComposioClientSingleton> =>
340 +}): Effect.Effect<ComposioClientShape, ToolPermissionsRequestError, ComposioClientSingleton> =>
341 Effect.gen(function* () {
342 const clientSingleton = yield* ComposioClientSingleton;
343 return yield* clientSingleton
@@ -353,19 +358,11 @@ const permissionsClient = (params: {
358 );
359 });
360
356 -const fetchConsumerConfig = (client: RawComposioClient) =>
357 - Effect.tryPromise({
358 - try: () =>
359 - requestJson(ConsumerConfigResponseSchema, {
360 - client,
361 - path: ORG_CONSUMER_CONFIG_PATH,
362 - }),
363 - catch: cause =>
364 - new ToolPermissionsRequestError({
365 - path: ORG_CONSUMER_CONFIG_PATH,
366 - message: 'Failed to fetch the org consumer config.',
367 - cause,
368 - }),
361 +const fetchConsumerConfig = (client: ComposioClientShape) =>
362 + requestJson(ConsumerConfigResponseSchema, {
363 + client,
364 + path: ORG_CONSUMER_CONFIG_PATH,
365 + message: 'Failed to fetch the org consumer config.',
366 });
367
368 export const refreshConsumerPermissionSnapshot = (params: {
@@ -401,23 +398,15 @@ export const refreshConsumerPermissionSnapshot = (params: {
398 remoteEnhancedControlsEnabled && platformSupportsEnhancedControls;
399 const resolved =
400 enhancedControlsEnabled && connectedAccountIds.length > 0
404 - ? yield* Effect.tryPromise({
405 - try: () =>
406 - requestJson(PermissionResolveResponseSchema, {
407 - client,
408 - path: CONSUMER_PERMISSIONS_RESOLVE_PATH,
409 - method: 'POST',
410 - body: {
411 - connected_account_ids: connectedAccountIds,
412 - default: 'ask_every_call',
413 - },
414 - }),
415 - catch: cause =>
416 - new ToolPermissionsRequestError({
417 - path: CONSUMER_PERMISSIONS_RESOLVE_PATH,
418 - message: 'Failed to resolve consumer permissions.',
419 - cause,
420 - }),
401 + ? yield* requestJson(PermissionResolveResponseSchema, {
402 + client,
403 + path: CONSUMER_PERMISSIONS_RESOLVE_PATH,
404 + method: 'POST',
405 + body: {
406 + connected_account_ids: connectedAccountIds,
407 + default: 'ask_every_call',
408 + },
409 + message: 'Failed to resolve consumer permissions.',
410 }).pipe(
411 Effect.map(response => ({
412 permissions: response.experimental?.permissions,
ts/packages/cli/src/services/tool-router-session-connections.ts
+18 -13
@@ -1,5 +1,5 @@
1 import { Data, Effect } from 'effect';
2 -import type { Composio } from '@composio/client';
2 +import type { ComposioClientShape } from '@composio/client/effect';
3 import { isKnownConnectedAccountStatus } from 'src/models/connected-accounts';
4 import {
5 compareNewestFirst,
@@ -60,27 +60,32 @@ const isNewerAccount = (candidate: RawConnectedAccount, current: RawConnectedAcc
60 compareNewestFirst(candidate, current) < 0;
61
62 const listConnectedAccountsForToolkits = (
63 - client: Composio,
63 + client: ComposioClientShape,
64 userId: string,
65 toolkits: ReadonlyArray<string>
66 ) =>
67 - Effect.tryPromise({
68 - try: () =>
69 - client.connectedAccounts.list({
67 + client.connectedAccounts
68 + .list(
69 + {
70 user_ids: [userId],
71 statuses: ['ACTIVE'],
72 toolkit_slugs: [...toolkits],
73 limit: 1000,
74 - }),
75 - catch: cause =>
76 - new ToolRouterSessionConnectionsError({
77 - message: `Failed to list connected accounts for user "${userId}".`,
78 - cause,
79 - }),
80 - });
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 + );
86
87 export const resolveToolRouterSessionConnections = (
83 - client: Composio,
88 + client: ComposioClientShape,
89 userId: string,
90 options?: {
91 readonly toolkits?: ReadonlyArray<string>;
ts/packages/cli/src/services/toolkit-version-validation.ts new
+157
@@ -0,0 +1,157 @@
1 +import { Data, Effect, String } from 'effect';
2 +import type { Toolkit } from 'src/models/toolkits';
3 +import type { ToolkitVersionOverrides } from 'src/effects/toolkit-version-overrides';
4 +import type { ClientError } from './composio-errors';
5 +import { MAX_CONCURRENT_REQUESTS_PER_ENDPOINT } from './composio-request';
6 +
7 +/**
8 + * Error thrown when one or more toolkit slugs are invalid.
9 + */
10 +export class InvalidToolkitsError extends Data.TaggedError('services/InvalidToolkitsError')<{
11 + readonly invalidToolkits: ReadonlyArray<string>;
12 + readonly availableToolkits: ReadonlyArray<string>;
13 +}> {}
14 +
15 +/**
16 + * Details about a single invalid version override.
17 + */
18 +export interface InvalidVersionDetail {
19 + readonly toolkit: string;
20 + readonly requestedVersion: string;
21 + readonly availableVersions: ReadonlyArray<string>;
22 +}
23 +
24 +/**
25 + * Error thrown when one or more toolkit version overrides are invalid.
26 + */
27 +export class InvalidToolkitVersionsError extends Data.TaggedError(
28 + 'services/InvalidToolkitVersionsError'
29 +)<{
30 + readonly invalidVersions: ReadonlyArray<InvalidVersionDetail>;
31 +}> {}
32 +
33 +/**
34 + * Converts a 404 from a toolkit lookup into `InvalidToolkitsError` naming
35 + * that slug; every other failure propagates unchanged.
36 + */
37 +export const invalidToolkitOn404 = <A>(slug: string, toolkit: Effect.Effect<A, ClientError>) =>
38 + Effect.catchTag(toolkit, '@composio/client/NotFoundError', () =>
39 + Effect.fail(
40 + new InvalidToolkitsError({
41 + invalidToolkits: [slug],
42 + availableToolkits: [],
43 + })
44 + )
45 + );
46 +
47 +export const validateToolkitVersionsImpl = (
48 + retrieveToolkit: (slug: string) => Effect.Effect<Toolkit, ClientError, never>,
49 + overrides: ToolkitVersionOverrides,
50 + relevantToolkits?: ReadonlyArray<string>
51 +): Effect.Effect<
52 + {
53 + validatedOverrides: ToolkitVersionOverrides;
54 + warnings: ReadonlyArray<string>;
55 + },
56 + InvalidToolkitVersionsError | InvalidToolkitsError | ClientError
57 +> =>
58 + Effect.gen(function* () {
59 + const determineOverridesToValidate = (
60 + overrides: ToolkitVersionOverrides,
61 + relevantToolkits?: ReadonlyArray<string>
62 + ): {
63 + overridesToValidate: Array<[toolkit: string, requestedVersion: string]>;
64 + warnings: Array<string>;
65 + } => {
66 + const warnings: string[] = [];
67 + const overridesToValidate: Array<[toolkit: string, requestedVersion: string]> = [];
68 +
69 + if (relevantToolkits) {
70 + const relevantSet = new Set(relevantToolkits.map(s => String.toLowerCase(s)));
71 +
72 + for (const [toolkit, version] of overrides) {
73 + if (relevantSet.has(toolkit)) {
74 + overridesToValidate.push([toolkit, version]);
75 + } else {
76 + warnings.push(
77 + `Version override for "${toolkit}" will be ignored (toolkit not in --toolkits filter)`
78 + );
79 + }
80 + }
81 + } else {
82 + overridesToValidate.push(...overrides.entries());
83 + }
84 +
85 + return { overridesToValidate, warnings };
86 + };
87 +
88 + const fetchToolkitVersionValidationResults = (
89 + overridesToValidate: ReadonlyArray<[toolkit: string, requestedVersion: string]>
90 + ): Effect.Effect<
91 + ReadonlyArray<{
92 + toolkit: string;
93 + requestedVersion: string;
94 + availableVersions: ReadonlyArray<string>;
95 + isValid: boolean;
96 + }>,
97 + InvalidToolkitsError | ClientError
98 + > =>
99 + Effect.all(
100 + overridesToValidate.map(([toolkit, requestedVersion]) =>
101 + invalidToolkitOn404(
102 + toolkit,
103 + retrieveToolkit(toolkit).pipe(
104 + Effect.map(toolkitData => ({
105 + toolkit,
106 + requestedVersion,
107 + availableVersions: toolkitData.meta.available_versions,
108 + isValid: toolkitData.meta.available_versions.includes(requestedVersion),
109 + }))
110 + )
111 + )
112 + ),
113 + { concurrency: MAX_CONCURRENT_REQUESTS_PER_ENDPOINT }
114 + );
115 +
116 + const collectInvalidVersions = (
117 + validationResults: ReadonlyArray<{
118 + toolkit: string;
119 + requestedVersion: string;
120 + availableVersions: ReadonlyArray<string>;
121 + isValid: boolean;
122 + }>
123 + ): ReadonlyArray<InvalidVersionDetail> =>
124 + validationResults
125 + .filter(result => !result.isValid)
126 + .map(result => ({
127 + toolkit: result.toolkit,
128 + requestedVersion: result.requestedVersion,
129 + availableVersions: result.availableVersions,
130 + }));
131 +
132 + if (overrides.size === 0) {
133 + return { validatedOverrides: overrides, warnings: [] as ReadonlyArray<string> };
134 + }
135 +
136 + const { overridesToValidate, warnings } = determineOverridesToValidate(
137 + overrides,
138 + relevantToolkits
139 + );
140 +
141 + if (overridesToValidate.length === 0) {
142 + return {
143 + validatedOverrides: new Map() as ToolkitVersionOverrides,
144 + warnings: warnings as ReadonlyArray<string>,
145 + };
146 + }
147 +
148 + const validationResults = yield* fetchToolkitVersionValidationResults(overridesToValidate);
149 + const invalidVersions = collectInvalidVersions(validationResults);
150 +
151 + if (invalidVersions.length > 0) {
152 + return yield* Effect.fail(new InvalidToolkitVersionsError({ invalidVersions }));
153 + }
154 +
155 + const validatedOverrides = new Map(overridesToValidate) as ToolkitVersionOverrides;
156 + return { validatedOverrides, warnings: warnings as ReadonlyArray<string> };
157 + });
ts/packages/cli/src/services/tools-executor.ts
+22 -25
@@ -1,7 +1,7 @@
1 import * as FileSystem from 'effect/FileSystem';
2 import * as Path from 'effect/Path';
3 import { Context, Effect, Layer } from 'effect';
4 -import type { Composio } from '@composio/client';
4 +import type { ComposioClientShape } from '@composio/client/effect';
5 import type {
6 SessionExecuteResponse,
7 SessionExecuteMetaResponse,
@@ -19,7 +19,7 @@ import { ToolFileUploadError, uploadToolInputFiles } from 'src/services/tool-fil
19 import { toolkitFromToolSlug } from 'src/effects/toolkit-from-tool-slug';
20 import { ToolkitSlugCatalog } from 'src/services/toolkit-slug-catalog';
21 import { isMetaToolSlug } from 'src/utils/meta-tool-slugs';
22 -import { assertNotInputRequired } from 'src/utils/tool-input-required';
22 +import { toolInputRequiredError } from 'src/utils/tool-input-required';
23 import type { NodeOs } from 'src/services/node-os';
24 import type { NodeProcess } from 'src/services/node-process';
25 import type { ComposioUserContext } from 'src/services/user-context';
@@ -33,7 +33,7 @@ import type { ComposioCliUserConfig } from 'src/services/cli-user-config';
33 export interface ToolExecuteParams {
34 readonly userId: string;
35 readonly arguments: Record<string, unknown>;
36 - readonly client?: Composio;
36 + readonly client?: ComposioClientShape;
37 readonly connectedAccounts?: Record<string, string>;
38 /**
39 * The org/project the command resolved. The executor's tool-schema lookup
@@ -161,7 +161,7 @@ export const ToolsExecutorLive = Layer.effect(
161 Effect.gen(function* () {
162 // Resolve the client singleton at layer construction time.
163 // The `get` instance method is an Effect.fn that lazily initializes
164 - // the raw Composio client on first call — no environment requirements.
164 + // the Composio client on first call — no environment requirements.
165 const clientSingleton = yield* ComposioClientSingleton;
166
167 // Held rather than required per call: which slugs resolve locally is an
@@ -226,28 +226,25 @@ export const ToolsExecutorLive = Layer.effect(
226 })
227 );
228
229 - const raw = yield* Effect.tryPromise({
230 - // Never retry an execution: a retry after the backend already acted
231 - // duplicates the side effect (e.g. sends the same email twice).
232 - try: async () => {
233 - const response: SessionExecuteResponse | SessionExecuteMetaResponse = isMetaToolSlug(
234 - slug
229 + // Never retry an execution: a retry after the backend already acted
230 + // duplicates the side effect (e.g. sends the same email twice). The
231 + // response is not validated either, for the same reason.
232 + const raw: SessionExecuteResponse | SessionExecuteMetaResponse = yield* isMetaToolSlug(
233 + slug
234 + )
235 + ? resolvedClient.toolRouter.session.executeMeta(
236 + sessionId,
237 + { slug, arguments: normalizedArguments },
238 + { maxRetries: 0, decode: false }
239 )
236 - ? await resolvedClient.toolRouter.session.executeMeta(
237 - sessionId,
238 - { slug, arguments: normalizedArguments },
239 - { maxRetries: 0 }
240 - )
241 - : await resolvedClient.toolRouter.session.execute(
242 - sessionId,
243 - { tool_slug: slug, arguments: normalizedArguments },
244 - { maxRetries: 0 }
245 - );
246 - assertNotInputRequired(`Tool ${slug}`, response);
247 - return response;
248 - },
249 - catch: cause => cause,
250 - });
240 + : resolvedClient.toolRouter.session.execute(
241 + sessionId,
242 + { tool_slug: slug, arguments: normalizedArguments },
243 + { maxRetries: 0, decode: false }
244 + );
245 + if (raw.result_type === 'input_required') {
246 + return yield* toolInputRequiredError(`Tool ${slug}`, raw);
247 + }
248
249 return normalizeResponse(raw, permissionGateResult);
250 }).pipe(
ts/packages/cli/src/services/triggers-realtime.ts
+6 -8
@@ -296,15 +296,13 @@ const makeTriggersRealtime = Effect.gen(function* () {
296
297 return yield* listenWith({
298 getRealtimeCredentials: () =>
299 - Effect.tryPromise({
300 - try: () => client.cli.realtime.credentials(),
301 - catch: subscriptionError('Failed to fetch realtime credentials'),
302 - }),
299 + client.cli.realtime
300 + .credentials()
301 + .pipe(Effect.mapError(subscriptionError('Failed to fetch realtime credentials'))),
302 authRealtimeChannel: params =>
304 - Effect.tryPromise({
305 - try: () => client.cli.realtime.auth(params),
306 - catch: subscriptionError('Failed to authorize the realtime channel'),
307 - }),
303 + client.cli.realtime
304 + .auth(params, { decode: false })
305 + .pipe(Effect.mapError(subscriptionError('Failed to authorize the realtime channel'))),
306 onEvent,
307 });
308 });
ts/packages/cli/src/utils/api-error-extraction.ts
+70 -13
@@ -1,18 +1,57 @@
1 /**
2 * Adapters from failures to the Composio API error envelope.
3 *
4 - * `@composio/client` rejects with an `APIError` whose `details` is the parsed
5 - * `{ error: { message, code, slug, ... } }` envelope. Effect wrappers keep the
6 - * original rejection in `.cause`, so the adapter walks that chain to the first
7 - * `APIError`.
4 + * `@composio/client/effect` fails a non-success response with a tagged status
5 + * error whose `details` is the parsed `{ error: { message, code, slug, ... } }`
6 + * envelope. The CLI's own errors keep that failure in `.cause`, so the adapter
7 + * walks that chain to the first status error, recognized by its tag.
8 *
9 * Used by both the `ToolsExecutor` service (for error classification) and the
10 * `tools execute` command (for error display).
11 */
12
13 -import { APIError } from '@composio/client';
13 +import {
14 + isAPIError,
15 + isComposioError,
16 + type APIConnectionError,
17 + type APIConnectionTimeoutError,
18 + type APIStatusError,
19 + type DecodeError,
20 +} from '@composio/client/effect';
21 import { Predicate } from 'effect';
22
23 +/**
24 + * A failure of a request made through the Effect client: a non-success status,
25 + * a transport failure, a timeout, or a response body that failed decoding.
26 + */
27 +export type ClientApiError =
28 + APIStatusError | APIConnectionError | APIConnectionTimeoutError | DecodeError;
29 +
30 +export const isClientApiError = (value: unknown): value is ClientApiError =>
31 + isComposioError(value) && !Predicate.isTagged(value, '@composio/client/ConfigurationError');
32 +
33 +export const isClientConnectionError = (value: unknown): value is APIConnectionError =>
34 + isComposioError(value) && Predicate.isTagged(value, '@composio/client/APIConnectionError');
35 +
36 +export const isClientDecodeError = (value: unknown): value is DecodeError =>
37 + isComposioError(value) && Predicate.isTagged(value, '@composio/client/DecodeError');
38 +
39 +/**
40 + * What the CLI prints when a response failed client decoding. It names the
41 + * request and never quotes the response.
42 + */
43 +export const describeDecodeError = (
44 + error: DecodeError
45 +): { readonly message: string; readonly hint: string } => {
46 + const subject =
47 + error.operation !== undefined ? `'${error.operation}'` : `${error.method} ${error.url}`;
48 + const requestId = error.requestId !== undefined ? ` (request id: ${error.requestId})` : '';
49 + return {
50 + message: `The API response for ${subject} is not in the shape this version of the CLI expects${requestId}.`,
51 + hint: 'Upgrade the CLI, then retry:\n> composio upgrade',
52 + };
53 +};
54 +
55 export interface ApiErrorDetails {
56 readonly message?: string;
57 readonly code?: number;
@@ -23,14 +62,15 @@ export interface ApiErrorDetails {
62 }
63
64 /**
26 - * Returns the first `APIError` along the `.cause` chain, starting at `value`.
65 + * Returns the first client status error along the `.cause` chain, starting at
66 + * `value`.
67 */
28 -export const findApiError = (value: unknown): APIError | undefined => {
68 +export const findApiError = (value: unknown): APIStatusError | undefined => {
69 const seen = new Set<unknown>();
70 let current: unknown = value;
71
72 while (Predicate.isObject(current) && !seen.has(current)) {
33 - if (current instanceof APIError) return current;
73 + if (isAPIError(current)) return current;
74 seen.add(current);
75 current = Predicate.hasProperty(current, 'cause') ? current.cause : undefined;
76 }
@@ -39,7 +79,7 @@ export const findApiError = (value: unknown): APIError | undefined => {
79 };
80
81 /**
42 - * The API error envelope carried by the first `APIError` in the cause chain,
82 + * The API error envelope carried by the first status error in the cause chain,
83 * with the HTTP status and request id. A body that is not the envelope keeps
84 * the status and falls back to the error's own message.
85 */
@@ -66,8 +106,8 @@ export const extractMessage = (value: unknown, seen?: Set<unknown>): string | un
106 if (typeof value === 'string') return value;
107
108 // Walk the .cause / .error chain to find the deepest meaningful message.
69 - // Effect's UnknownException stores the real error in .cause; the Composio SDK
70 - // stores the API response body in .error (which itself has .error.message).
109 + // A wrapper stores the failure it wraps in .cause; an API response body
110 + // stores its envelope in .error (which itself has .error.message).
111 // We prefer the deepest message because outer wrappers often have generic
112 // messages like "An unknown error occurred in Effect.tryPromise".
113 if (Predicate.isObject(value)) {
@@ -75,13 +115,30 @@ export const extractMessage = (value: unknown, seen?: Set<unknown>): string | un
115 if (visited.has(value)) return undefined;
116 visited.add(value);
117
78 - // Try .cause chain first (Effect's UnknownException → real SDK error)
118 + // A client status error keeps the response body in .body.
119 + if (isAPIError(value)) {
120 + return value.details?.message ?? extractMessage(value.body, visited) ?? value.message;
121 + }
122 +
123 + // A response that failed client decoding is reported by operation and
124 + // request id, with the remedy, never by the client's raw message.
125 + if (isClientDecodeError(value)) {
126 + const { message, hint } = describeDecodeError(value);
127 + return `${message}\n${hint}`;
128 + }
129 +
130 + // A client connection error has no cause chain; the transport text is in .description.
131 + if (isClientConnectionError(value)) {
132 + return value.description ?? value.message;
133 + }
134 +
135 + // Try .cause chain first (wrapper → the failure it wraps)
136 if (Predicate.hasProperty(value, 'cause')) {
137 const causeMsg = extractMessage(value.cause, visited);
138 if (causeMsg) return causeMsg;
139 }
140
84 - // Try .error chain (SDK error → API response body → nested .error.message)
141 + // Try .error chain (API response body → nested .error.message)
142 if (Predicate.hasProperty(value, 'error')) {
143 const inner = value.error;
144 const innerMsg = extractMessage(inner, visited);
ts/packages/cli/src/utils/tool-input-required.ts
-13
@@ -37,16 +37,3 @@ export const toolInputRequiredError = (
37 requestState: response.request_state,
38 });
39 };
40 -
41 -/**
42 - * Narrows an execute-family response to the variants that carry a result.
43 - *
44 - * @throws {ToolInputRequiredError} If the call asked for user input instead of running
45 - */
46 -export function assertNotInputRequired<Response extends ExecuteFamilyResponse>(
47 - subject: string,
48 - response: Response
49 -): asserts response is Exclude<Response, InputRequiredResponse> {
50 - if (response.result_type !== 'input_required') return;
51 - throw toolInputRequiredError(subject, response);
52 -}
ts/packages/cli/test/__utils__/models/account.ts
+1 -1
@@ -1,5 +1,5 @@
1 import type { SessionRetrieveInfoResponse } from '@composio/client/resources/auth';
2 -import type { OrgProject } from 'src/services/composio-clients';
2 +import type { OrgProject } from 'src/services/composio-account';
3
4 export const TIMESTAMP = '2026-01-01T00:00:00.000Z';
5
ts/packages/cli/test/__utils__/services/stub-composio-client.ts new
+82
@@ -0,0 +1,82 @@
1 +import { make, type ComposioClientShape } from '@composio/client/effect';
2 +import { Effect, Layer, Result } from 'effect';
3 +import { HttpClient, HttpClientRequest, HttpClientResponse } from 'effect/http';
4 +import { ComposioClientSingleton } from 'src/services/composio-clients';
5 +import { composioSchemaLoaders } from 'src/services/composio-schema-loaders';
6 +
7 +/** One request as it reached the stub transport. */
8 +export interface StubRequest {
9 + readonly method: string;
10 + /** Path and query, without the origin. */
11 + readonly path: string;
12 + /** The JSON body, or `undefined` when the request carried none. */
13 + readonly body: unknown;
14 +}
15 +
16 +/**
17 + * The Effect client the CLI builds in production (response decoding on, the
18 + * CLI's loader table), over a transport that records each request and answers
19 + * it with `respond`. Retries, status errors, and decoding are the client's own.
20 + *
21 + * A retried call sleeps on Effect's clock, so a test whose answer is retryable
22 + * runs under `it.live` and answers with a `retry-after-ms: 0` header.
23 + */
24 +export const stubComposioClient = (
25 + respond: (request: StubRequest) => Response
26 +): { readonly client: ComposioClientShape; readonly requests: ReadonlyArray<StubRequest> } => {
27 + const requests: Array<StubRequest> = [];
28 + const httpClient = HttpClient.make(request =>
29 + Effect.promise(async () => {
30 + const web = Result.getOrThrow(HttpClientRequest.toWebResult(request));
31 + const url = new URL(web.url);
32 + const text = await web.text();
33 + const recorded: StubRequest = {
34 + method: web.method,
35 + path: `${url.pathname}${url.search}`,
36 + body: text === '' ? undefined : (JSON.parse(text) as unknown),
37 + };
38 + requests.push(recorded);
39 + return HttpClientResponse.fromWeb(request, respond(recorded));
40 + })
41 + );
42 + const client = make(
43 + {
44 + apiKey: 'test',
45 + userApiKey: null,
46 + orgApiKey: null,
47 + baseURL: 'https://stub.invalid',
48 + deprecationNotices: 'off',
49 + decode: true,
50 + schemas: composioSchemaLoaders,
51 + },
52 + httpClient
53 + );
54 + return { client, requests };
55 +};
56 +
57 +/**
58 + * A layer over a test layer's `ComposioClientSingleton` that swaps the named
59 + * resources of every client it hands out for those of a client built by
60 + * {@link stubComposioClient}. Calls to those resources go through the real
61 + * client to `respond`; every other resource keeps the test layer's answers.
62 + */
63 +export const stubClientResources = (
64 + resources: ReadonlyArray<keyof ComposioClientShape>,
65 + respond: (request: StubRequest) => Response
66 +) => {
67 + const stub = stubComposioClient(respond);
68 + const overlay = Object.fromEntries(resources.map(resource => [resource, stub.client[resource]]));
69 + const stubbed = (client: ComposioClientShape): ComposioClientShape => ({ ...client, ...overlay });
70 + const layer = Layer.effect(
71 + ComposioClientSingleton,
72 + Effect.gen(function* () {
73 + const base = yield* ComposioClientSingleton;
74 + return ComposioClientSingleton.of({
75 + ...base,
76 + get: () => Effect.map(base.get(), stubbed),
77 + getFor: params => Effect.map(base.getFor(params), stubbed),
78 + });
79 + })
80 + );
81 + return { requests: stub.requests, layer };
82 +};
ts/packages/cli/test/__utils__/services/test-layer.ts
+344 -306
@@ -1,15 +1,16 @@
1 import path from 'node:path';
2 import * as tempy from 'tempy';
3 -import {
4 - APIConnectionError,
5 - Composio as RawComposioClient,
6 - NotFoundError,
7 - type RequestOptions,
8 -} from '@composio/client';
3 import type {
4 AuthConfigCreateParams,
5 AuthConfigCreateResponse,
6 } from '@composio/client/resources/auth-configs';
7 +import {
8 + APIConnectionError,
9 + NotFoundError,
10 + make as makeComposioClient,
11 + type ComposioError,
12 + type RequestOptions,
13 +} from '@composio/client/effect';
14 import type { LinkCreateResponse } from '@composio/client/resources/link';
15 import type { SessionRetrieveInfoResponse } from '@composio/client/resources/auth';
16 import type { ToolRetrieveResponse } from '@composio/client/resources/tools';
@@ -26,6 +27,7 @@ import {
27 Layer,
28 Option,
29 Path,
30 + Predicate,
31 References,
32 Schedule,
33 String,
@@ -44,14 +46,15 @@ import {
46 ComposioClientSingleton,
47 ComposioSessionRepository,
48 ComposioToolkitsRepository,
47 - HttpServerError,
49 + type ToolkitProjectScope,
50 +} from 'src/services/composio-clients';
51 +import { composioSchemaLoaders } from 'src/services/composio-schema-loaders';
52 +import {
53 InvalidToolkitsError,
54 InvalidToolkitVersionsError,
55 type InvalidVersionDetail,
51 - type OrganizationSummary,
52 - type OrgProject,
53 - type ToolkitProjectScope,
54 -} from 'src/services/composio-clients';
56 +} from 'src/services/toolkit-version-validation';
57 +import { type OrganizationSummary, type OrgProject } from 'src/services/composio-account';
58 import type { ToolkitVersionOverrides } from 'src/effects/toolkit-version-overrides';
59 import { JsPackageManagerDetector } from 'src/services/js-package-manager-detector';
60 import type { Tool, Tools } from 'src/models/tools';
@@ -94,9 +97,27 @@ import {
97 SetupSkillInstaller,
98 type SetupSkillInstallerShape,
99 } from 'src/services/setup-skill-installer';
97 -import { FetchHttpClient } from 'effect/http';
100 +import { FetchHttpClient, HttpClient } from 'effect/http';
101 import * as BunServices from '@effect/platform-bun/BunServices';
102
103 +/**
104 + * A 404 as the Effect client reports one, with the API error envelope when the
105 + * scenario has one.
106 + */
107 +const notFoundError = (
108 + message: string,
109 + envelope?: { readonly message: string; readonly suggested_fix: string }
110 +) =>
111 + new NotFoundError({
112 + message,
113 + method: 'GET',
114 + url: 'https://mock.invalid',
115 + status: 404,
116 + requestId: undefined,
117 + details: envelope ? { ...envelope, code: 404, slug: 'Not_Found', status: 404 } : undefined,
118 + body: envelope ? { error: envelope } : undefined,
119 + });
120 +
121 /**
122 * The credentials and scope one mock-client request carries: the parameters
123 * the client was obtained with, overridden by per-request headers.
@@ -188,10 +209,7 @@ export interface TestLiveInput {
209 */
210 accountData?: {
211 sessionInfo?:
191 - | SessionRetrieveInfoResponse
192 - | ((
193 - scope: MockRequestScope
194 - ) => SessionRetrieveInfoResponse | Promise<SessionRetrieveInfoResponse>);
212 + SessionRetrieveInfoResponse | ((scope: MockRequestScope) => SessionRetrieveInfoResponse);
213 organizations?: ReadonlyArray<OrganizationSummary>;
214 projects?: ReadonlyArray<OrgProject>;
215 connectedToolkits?: ReadonlyArray<string>;
@@ -276,39 +294,49 @@ export interface TestLiveInput {
294 * Controls the mock `ComposioClientSingleton`'s `toolRouter.session.*` methods.
295 * Each method can be overridden individually; defaults are provided for all.
296 *
297 + * Each override answers with an Effect, so a test can fail a call with one
298 + * of the client's own errors or route it to a client over a stub transport.
299 + *
300 * When `toolsExecutor` is also set, its mock takes precedence for `tools execute`
301 * (the Tool Router mock is still used by `toolkits list`, `toolkits info`, etc.).
302 */
303 toolRouter?: {
304 /** Override `session.create`. Receives the create params. */
284 - create?: (params: SessionCreateParams) => Promise<SessionCreateResponse>;
305 + create?: (params: SessionCreateParams) => Effect.Effect<SessionCreateResponse, ComposioError>;
306 /** Override `session.execute`. Receives sessionId, params, and request options. */
307 execute?: (
308 sessionId: string,
309 params: SessionExecuteParams,
289 - options?: { maxRetries?: number }
290 - ) => Promise<SessionExecuteResponse>;
310 + options?: RequestOptions
311 + ) => Effect.Effect<SessionExecuteResponse, ComposioError>;
312 /** Override `session.executeMeta`. Receives sessionId, params, and request options. */
313 executeMeta?: (
314 sessionId: string,
315 params: SessionExecuteMetaParams,
295 - options?: { maxRetries?: number }
296 - ) => Promise<SessionExecuteMetaResponse>;
297 - /** Override `session.link`. Receives sessionId and params. */
298 - link?: (sessionId: string, params: SessionLinkParams) => Promise<SessionLinkResponse>;
316 + options?: RequestOptions
317 + ) => Effect.Effect<SessionExecuteMetaResponse, ComposioError>;
318 + /** Override `session.link`. Receives sessionId, params, and request options. */
319 + link?: (
320 + sessionId: string,
321 + params: SessionLinkParams,
322 + options?: RequestOptions
323 + ) => Effect.Effect<SessionLinkResponse, ComposioError>;
324 /** Override `session.proxyExecute`. Receives sessionId, params, and request options. */
325 proxyExecute?: (
326 sessionId: string,
327 params: SessionProxyExecuteParams,
303 - options?: { maxRetries?: number }
304 - ) => Promise<SessionProxyExecuteResponse>;
328 + options?: RequestOptions
329 + ) => Effect.Effect<SessionProxyExecuteResponse, ComposioError>;
330 /** Override `session.search`. Receives sessionId and params. */
306 - search?: (sessionId: string, params: SessionSearchParams) => Promise<SessionSearchResponse>;
331 + search?: (
332 + sessionId: string,
333 + params: SessionSearchParams
334 + ) => Effect.Effect<SessionSearchResponse, ComposioError>;
335 /** Override `session.toolkits`. Receives sessionId and optional params. */
336 toolkits?: (
337 sessionId: string,
338 params?: SessionToolkitsParams | null
311 - ) => Promise<SessionToolkitsResponse>;
339 + ) => Effect.Effect<SessionToolkitsResponse, ComposioError>;
340 };
341
342 /**
@@ -469,9 +497,7 @@ export const TestLayer = (input?: TestLiveInput) =>
497 trigger => trigger.slug.toUpperCase() === slug.toUpperCase()
498 );
499 if (!found) {
472 - return Effect.fail(
473 - new HttpServerError({ cause: `Trigger type "${slug}" not found`, status: 404 })
474 - );
500 + return Effect.fail(notFoundError(`Trigger type "${slug}" not found`));
501 }
502 return Effect.succeed(found);
503 },
@@ -634,9 +660,7 @@ export const TestLayer = (input?: TestLiveInput) =>
660 getToolDetailed: (slug: string) => {
661 const found = toolkitsData.tools.find(t => t.slug.toUpperCase() === slug.toUpperCase());
662 if (!found) {
637 - return Effect.fail(
638 - new HttpServerError({ cause: `Tool "${slug}" not found`, status: 404 })
639 - );
663 + return Effect.fail(notFoundError(`Tool "${slug}" not found`));
664 }
665 return Effect.succeed(toClientTool(found));
666 },
@@ -645,9 +669,7 @@ export const TestLayer = (input?: TestLiveInput) =>
669 t => t.slug.toLowerCase() === slug.toLowerCase()
670 );
671 if (!found) {
648 - return Effect.fail(
649 - new HttpServerError({ cause: `Toolkit "${slug}" not found`, status: 404 })
650 - );
672 + return Effect.fail(notFoundError(`Toolkit "${slug}" not found`));
673 }
674 return Effect.succeed(found);
675 },
@@ -685,14 +707,9 @@ export const TestLayer = (input?: TestLiveInput) =>
707 const found = authConfigsData.items.find(item => item.id === nanoid);
708 if (!found) {
709 return Effect.fail(
688 - new HttpServerError({
689 - cause: `Auth config "${nanoid}" not found`,
690 - status: 404,
691 - details: {
692 - message: `Auth config "${nanoid}" not found.`,
693 - suggestedFix: 'Check the auth config ID and try again.',
694 - code: 404,
695 - },
710 + notFoundError(`Auth config "${nanoid}" not found`, {
711 + message: `Auth config "${nanoid}" not found.`,
712 + suggested_fix: 'Check the auth config ID and try again.',
713 })
714 );
715 }
@@ -711,14 +728,9 @@ export const TestLayer = (input?: TestLiveInput) =>
728 const found = authConfigsData.items.find(item => item.id === nanoid);
729 if (!found) {
730 return Effect.fail(
714 - new HttpServerError({
715 - cause: `Auth config "${nanoid}" not found`,
716 - status: 404,
717 - details: {
718 - message: `Auth config "${nanoid}" not found.`,
719 - suggestedFix: 'Check the auth config ID and try again.',
720 - code: 404,
721 - },
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 }
@@ -761,14 +773,9 @@ export const TestLayer = (input?: TestLiveInput) =>
773 const found = connectedAccountsData.items.find(item => item.id === nanoid);
774 if (!found) {
775 return Effect.fail(
764 - new HttpServerError({
765 - cause: `Connected account "${nanoid}" not found`,
766 - status: 404,
767 - details: {
768 - message: `Connected account "${nanoid}" not found.`,
769 - suggestedFix: 'Check the connected account ID and try again.',
770 - code: 404,
771 - },
776 + notFoundError(`Connected account "${nanoid}" not found`, {
777 + message: `Connected account "${nanoid}" not found.`,
778 + suggested_fix: 'Check the connected account ID and try again.',
779 })
780 );
781 }
@@ -778,14 +785,9 @@ export const TestLayer = (input?: TestLiveInput) =>
785 const found = connectedAccountsData.items.find(item => item.id === nanoid);
786 if (!found) {
787 return Effect.fail(
781 - new HttpServerError({
782 - cause: `Connected account "${nanoid}" not found`,
783 - status: 404,
784 - details: {
785 - message: `Connected account "${nanoid}" not found.`,
786 - suggestedFix: 'Check the connected account ID and try again.',
787 - code: 404,
788 - },
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 }
@@ -1091,257 +1093,290 @@ export const TestLayer = (input?: TestLiveInput) =>
1093 };
1094 };
1095
1094 - const failOnNetworkCall: typeof globalThis.fetch = Object.assign(
1095 - (input: RequestInfo | URL): Promise<Response> => {
1096 - const url =
1097 - typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;
1098 - throw new Error(`unexpected network call from the mock Composio client: ${url}`);
1096 + // What the mock client answers with instead of calling the network.
1097 + const resourceShadows = {
1098 + link: {
1099 + create: async (params: { auth_config_id: string; user_id: string }) => {
1100 + const response = connectedAccountsData.linkResponse ?? {
1101 + connected_account_id: 'con_test_link',
1102 + expires_at: '2026-12-31T23:59:59Z',
1103 + link_token: 'lt_test_token',
1104 + redirect_url: `https://app.composio.dev/link?token=lt_test_token`,
1105 + };
1106 + return response;
1107 + },
1108 },
1100 - { preconnect: () => undefined }
1101 - );
1109 + patch: async (path: string, options?: { body?: Record<string, unknown> }) => {
1110 + connectedAccountsData.onPatch?.({ path, body: options?.body });
1111
1103 - // `fromEnv({}, ...)` is what production uses, so the mock cannot read the
1104 - // developer's COMPOSIO_* variables either. The throwing `fetch` turns a
1105 - // resource this mock forgot to shadow into a named test failure instead of
1106 - // a live request against the real backend.
1107 - const mockComposioClient = Object.assign(
1108 - RawComposioClient.fromEnv(
1109 - {},
1110 - {
1111 - apiKey: 'test',
1112 - userApiKey: null,
1113 - orgApiKey: null,
1114 - baseURL: 'https://mock.invalid',
1115 - logLevel: 'off',
1116 - fetch: failOnNetworkCall,
1112 + const match = path.match(/^\/api\/v3\/connected_accounts\/([^/]+)$/);
1113 + if (!match) {
1114 + throw new Error(`Unhandled PATCH path "${path}"`);
1115 }
1118 - ),
1119 - {
1120 - link: {
1121 - create: async (params: { auth_config_id: string; user_id: string }) => {
1122 - const response = connectedAccountsData.linkResponse ?? {
1123 - connected_account_id: 'con_test_link',
1124 - expires_at: '2026-12-31T23:59:59Z',
1125 - link_token: 'lt_test_token',
1126 - redirect_url: `https://app.composio.dev/link?token=lt_test_token`,
1127 - };
1128 - return response;
1129 - },
1130 - },
1131 - patch: async (path: string, options?: { body?: Record<string, unknown> }) => {
1132 - connectedAccountsData.onPatch?.({ path, body: options?.body });
1116
1134 - const match = path.match(/^\/api\/v3\/connected_accounts\/([^/]+)$/);
1135 - if (!match) {
1136 - throw new Error(`Unhandled PATCH path "${path}"`);
1117 + const connectedAccountId = match[1];
1118 + const account = connectedAccountsData.items.find(item => item.id === connectedAccountId);
1119 + if (!account) {
1120 + throw new Error(`Connected account "${connectedAccountId}" not found`);
1121 + }
1122 +
1123 + if (typeof options?.body?.alias === 'string') {
1124 + Object.assign(account as { alias?: string | null }, {
1125 + alias: options.body.alias,
1126 + });
1127 + }
1128 +
1129 + return account;
1130 + },
1131 + connectedAccounts: {
1132 + list: async (params?: {
1133 + toolkit_slugs?: string[];
1134 + user_ids?: string[];
1135 + statuses?: string[];
1136 + limit?: number;
1137 + }) => {
1138 + let results = [...connectedAccountsData.items];
1139 +
1140 + if (params?.toolkit_slugs && params.toolkit_slugs.length > 0) {
1141 + const slugs = new Set(params.toolkit_slugs.map(slug => slug.toLowerCase()));
1142 + results = results.filter(item => slugs.has(item.toolkit.slug.toLowerCase()));
1143 }
1144
1139 - const connectedAccountId = match[1];
1140 - const account = connectedAccountsData.items.find(item => item.id === connectedAccountId);
1141 - if (!account) {
1142 - throw new Error(`Connected account "${connectedAccountId}" not found`);
1145 + if (params?.user_ids && params.user_ids.length > 0) {
1146 + const userIds = new Set(params.user_ids);
1147 + results = results.filter(item => userIds.has(item.user_id));
1148 }
1149
1145 - if (typeof options?.body?.alias === 'string') {
1146 - Object.assign(account as { alias?: string | null }, {
1147 - alias: options.body.alias,
1148 - });
1150 + if (params?.statuses && params.statuses.length > 0) {
1151 + const statuses = new Set(params.statuses);
1152 + results = results.filter(item => statuses.has(item.status));
1153 }
1154
1151 - return account;
1155 + const limit = params?.limit ?? 30;
1156 + return {
1157 + items: results.slice(0, limit),
1158 + total_items: results.length,
1159 + total_pages: Math.ceil(results.length / limit),
1160 + current_page: 1,
1161 + next_cursor: null,
1162 + };
1163 },
1153 - connectedAccounts: {
1154 - list: async (params?: {
1155 - toolkit_slugs?: string[];
1156 - user_ids?: string[];
1157 - statuses?: string[];
1158 - limit?: number;
1159 - }) => {
1160 - let results = [...connectedAccountsData.items];
1161 -
1162 - if (params?.toolkit_slugs && params.toolkit_slugs.length > 0) {
1163 - const slugs = new Set(params.toolkit_slugs.map(slug => slug.toLowerCase()));
1164 - results = results.filter(item => slugs.has(item.toolkit.slug.toLowerCase()));
1165 - }
1166 -
1167 - if (params?.user_ids && params.user_ids.length > 0) {
1168 - const userIds = new Set(params.user_ids);
1169 - results = results.filter(item => userIds.has(item.user_id));
1170 - }
1171 -
1172 - if (params?.statuses && params.statuses.length > 0) {
1173 - const statuses = new Set(params.statuses);
1174 - results = results.filter(item => statuses.has(item.status));
1175 - }
1176 -
1177 - const limit = params?.limit ?? 30;
1178 - return {
1179 - items: results.slice(0, limit),
1180 - total_items: results.length,
1181 - total_pages: Math.ceil(results.length / limit),
1182 - current_page: 1,
1183 - next_cursor: null,
1184 - };
1185 - },
1186 - retrieve: async (nanoid: string) => {
1187 - const found = connectedAccountsData.items.find(item => item.id === nanoid);
1188 - if (!found) {
1189 - throw new Error(`Connected account "${nanoid}" not found`);
1190 - }
1191 - return found;
1192 - },
1193 - delete: async (nanoid: string) => {
1194 - const found = connectedAccountsData.items.find(item => item.id === nanoid);
1195 - if (!found) {
1196 - throw new Error(`Connected account "${nanoid}" not found`);
1197 - }
1198 - connectedAccountsData.onDelete?.(nanoid);
1199 - return {};
1200 - },
1164 + retrieve: async (nanoid: string) => {
1165 + const found = connectedAccountsData.items.find(item => item.id === nanoid);
1166 + if (!found) {
1167 + throw new Error(`Connected account "${nanoid}" not found`);
1168 + }
1169 + return found;
1170 },
1202 - triggersTypes: {
1203 - retrieve: async (slug: string) => {
1204 - const found = toolkitsData.triggerTypes.find(
1205 - trigger => trigger.slug.toUpperCase() === slug.toUpperCase()
1206 - );
1207 - if (!found) {
1208 - throw new NotFoundError(
1209 - 404,
1210 - { error: { message: `Trigger type "${slug}" not found` } },
1211 - `Trigger type "${slug}" not found`,
1212 - new Headers()
1213 - );
1214 - }
1215 - return found;
1216 - },
1171 + delete: async (nanoid: string) => {
1172 + const found = connectedAccountsData.items.find(item => item.id === nanoid);
1173 + if (!found) {
1174 + throw new Error(`Connected account "${nanoid}" not found`);
1175 + }
1176 + connectedAccountsData.onDelete?.(nanoid);
1177 + return {};
1178 },
1218 - triggerInstances: {
1219 - upsert: async (
1220 - triggerSlug: string,
1221 - params?: {
1222 - connected_account_id?: string;
1223 - trigger_config?: Record<string, unknown>;
1224 - }
1225 - ) => {
1226 - if (
1227 - input?.triggersData?.rejectUnknownTriggerSlugs &&
1228 - !toolkitsData.triggerTypes.some(
1229 - trigger => trigger.slug.toUpperCase() === triggerSlug.toUpperCase()
1230 - )
1231 - ) {
1232 - throw new Error(`Trigger type "${triggerSlug}" not found`);
1233 - }
1234 - return {
1235 - trigger_id: `trg_${triggerSlug.toLowerCase()}_${params?.connected_account_id ?? 'new'}`,
1236 - };
1237 - },
1238 - manage: {
1239 - update: async (triggerId: string, params: { status: 'enable' | 'disable' }) => ({
1240 - trigger_id: triggerId,
1241 - status: params.status,
1242 - }),
1243 - delete: async (triggerId: string) => ({ trigger_id: triggerId }),
1244 - },
1179 + },
1180 + triggersTypes: {
1181 + retrieve: (slug: string) => {
1182 + const found = toolkitsData.triggerTypes.find(
1183 + trigger => trigger.slug.toUpperCase() === slug.toUpperCase()
1184 + );
1185 + return found
1186 + ? Effect.succeed(found)
1187 + : Effect.fail(notFoundError(`Trigger type "${slug}" not found`));
1188 },
1246 - toolkits: {
1247 - retrieve: async (slug: string) => {
1248 - const detailed = toolkitsData.detailedToolkits.find(
1249 - t => t.slug.toLowerCase() === slug.toLowerCase()
1250 - );
1251 - if (detailed) {
1252 - return {
1253 - name: detailed.name,
1254 - slug: detailed.slug,
1255 - is_local_toolkit: detailed.is_local_toolkit,
1256 - composio_managed_auth_schemes: [...detailed.composio_managed_auth_schemes],
1257 - no_auth: detailed.no_auth,
1258 - meta: detailed.meta,
1259 - };
1260 - }
1261 -
1262 - const found = toolkitsData.toolkits.find(
1263 - t => t.slug.toLowerCase() === slug.toLowerCase()
1264 - );
1265 - if (!found) {
1266 - throw new Error(`Toolkit "${slug}" not found`);
1267 - }
1189 + },
1190 + triggerInstances: {
1191 + upsert: async (
1192 + triggerSlug: string,
1193 + params?: {
1194 + connected_account_id?: string;
1195 + trigger_config?: Record<string, unknown>;
1196 + }
1197 + ) => {
1198 + if (
1199 + input?.triggersData?.rejectUnknownTriggerSlugs &&
1200 + !toolkitsData.triggerTypes.some(
1201 + trigger => trigger.slug.toUpperCase() === triggerSlug.toUpperCase()
1202 + )
1203 + ) {
1204 + throw new Error(`Trigger type "${triggerSlug}" not found`);
1205 + }
1206 + return {
1207 + trigger_id: `trg_${triggerSlug.toLowerCase()}_${params?.connected_account_id ?? 'new'}`,
1208 + };
1209 + },
1210 + manage: {
1211 + update: async (triggerId: string, params: { status: 'enable' | 'disable' }) => ({
1212 + trigger_id: triggerId,
1213 + status: params.status,
1214 + }),
1215 + delete: async (triggerId: string) => ({ trigger_id: triggerId }),
1216 + },
1217 + },
1218 + toolkits: {
1219 + retrieve: async (slug: string) => {
1220 + const detailed = toolkitsData.detailedToolkits.find(
1221 + t => t.slug.toLowerCase() === slug.toLowerCase()
1222 + );
1223 + if (detailed) {
1224 return {
1269 - name: found.name,
1270 - slug: found.slug,
1271 - is_local_toolkit: found.is_local_toolkit,
1272 - composio_managed_auth_schemes: [...found.composio_managed_auth_schemes],
1273 - no_auth: found.no_auth,
1274 - meta: found.meta,
1225 + name: detailed.name,
1226 + slug: detailed.slug,
1227 + is_local_toolkit: detailed.is_local_toolkit,
1228 + composio_managed_auth_schemes: [...detailed.composio_managed_auth_schemes],
1229 + no_auth: detailed.no_auth,
1230 + meta: detailed.meta,
1231 };
1276 - },
1232 + }
1233 +
1234 + const found = toolkitsData.toolkits.find(
1235 + t => t.slug.toLowerCase() === slug.toLowerCase()
1236 + );
1237 + if (!found) {
1238 + throw new Error(`Toolkit "${slug}" not found`);
1239 + }
1240 + return {
1241 + name: found.name,
1242 + slug: found.slug,
1243 + is_local_toolkit: found.is_local_toolkit,
1244 + composio_managed_auth_schemes: [...found.composio_managed_auth_schemes],
1245 + no_auth: found.no_auth,
1246 + meta: found.meta,
1247 + };
1248 },
1278 - files: {
1279 - createPresignedURL: async (params: {
1280 - filename: string;
1281 - mimetype: string;
1282 - md5: string;
1283 - tool_slug: string;
1284 - toolkit_slug: string;
1285 - }) => ({
1286 - key: `uploads/${params.filename}`,
1287 - new_presigned_url: 'https://s3.test.composio.dev/upload',
1249 + },
1250 + files: {
1251 + createPresignedURL: async (params: {
1252 + filename: string;
1253 + mimetype: string;
1254 + md5: string;
1255 + tool_slug: string;
1256 + toolkit_slug: string;
1257 + }) => ({
1258 + key: `uploads/${params.filename}`,
1259 + new_presigned_url: 'https://s3.test.composio.dev/upload',
1260 + }),
1261 + },
1262 + toolRouter: {
1263 + session: {
1264 + create:
1265 + toolRouterOverrides?.create ??
1266 + (async (params: SessionCreateParams) => ({
1267 + session_id: 'trs_test_session',
1268 + config: { user_id: params.user_id },
1269 + mcp: { type: 'http' as const, url: 'https://mcp.test.composio.dev' },
1270 + tool_router_tools: ['COMPOSIO_SEARCH_TOOLS', 'COMPOSIO_MANAGE_CONNECTIONS'],
1271 + })),
1272 + execute:
1273 + toolRouterOverrides?.execute ??
1274 + (async (_sessionId: string, params: SessionExecuteParams) => ({
1275 + result_type: 'completed' as const,
1276 + data: { tool_slug: params.tool_slug, arguments: params.arguments },
1277 + error: null,
1278 + log_id: 'log_test',
1279 + })),
1280 + executeMeta:
1281 + toolRouterOverrides?.executeMeta ??
1282 + (async (_sessionId: string, params: SessionExecuteMetaParams) => ({
1283 + result_type: 'completed' as const,
1284 + data: { slug: params.slug, arguments: params.arguments },
1285 + error: null,
1286 + log_id: 'log_test',
1287 + })),
1288 + link:
1289 + toolRouterOverrides?.link ??
1290 + (async () => ({
1291 + connected_account_id: 'con_test_link',
1292 + link_token: 'lt_test_token',
1293 + redirect_url: 'https://app.composio.dev/link?token=lt_test_token',
1294 + account_type: 'PRIVATE' as const,
1295 + })),
1296 + proxyExecute:
1297 + toolRouterOverrides?.proxyExecute ??
1298 + (async (_sessionId: string, params: SessionProxyExecuteParams) => ({
1299 + status: 200,
1300 + data: {
1301 + toolkit_slug: params.toolkit_slug,
1302 + endpoint: params.endpoint,
1303 + method: params.method,
1304 + body: params.body ?? null,
1305 + parameters: params.parameters ?? [],
1306 + },
1307 + headers: {},
1308 + })),
1309 + search: toolRouterOverrides?.search ?? defaultSearchHandler,
1310 + toolkits: toolRouterOverrides?.toolkits ?? defaultToolkitsHandler,
1311 + tools: async () => ({
1312 + items: [],
1313 }),
1314 },
1290 - toolRouter: {
1291 - session: {
1292 - create:
1293 - toolRouterOverrides?.create ??
1294 - (async (params: SessionCreateParams) => ({
1295 - session_id: 'trs_test_session',
1296 - config: { user_id: params.user_id },
1297 - mcp: { type: 'http' as const, url: 'https://mcp.test.composio.dev' },
1298 - tool_router_tools: ['COMPOSIO_SEARCH_TOOLS', 'COMPOSIO_MANAGE_CONNECTIONS'],
1299 - })),
1300 - execute:
1301 - toolRouterOverrides?.execute ??
1302 - (async (_sessionId: string, params: SessionExecuteParams) => ({
1303 - result_type: 'completed' as const,
1304 - data: { tool_slug: params.tool_slug, arguments: params.arguments },
1305 - error: null,
1306 - log_id: 'log_test',
1307 - })),
1308 - executeMeta:
1309 - toolRouterOverrides?.executeMeta ??
1310 - (async (_sessionId: string, params: SessionExecuteMetaParams) => ({
1311 - result_type: 'completed' as const,
1312 - data: { slug: params.slug, arguments: params.arguments },
1313 - error: null,
1314 - log_id: 'log_test',
1315 - })),
1316 - link:
1317 - toolRouterOverrides?.link ??
1318 - (async () => ({
1319 - connected_account_id: 'con_test_link',
1320 - link_token: 'lt_test_token',
1321 - redirect_url: 'https://app.composio.dev/link?token=lt_test_token',
1322 - account_type: 'PRIVATE' as const,
1323 - })),
1324 - proxyExecute:
1325 - toolRouterOverrides?.proxyExecute ??
1326 - (async (_sessionId: string, params: SessionProxyExecuteParams) => ({
1327 - status: 200,
1328 - data: {
1329 - toolkit_slug: params.toolkit_slug,
1330 - endpoint: params.endpoint,
1331 - method: params.method,
1332 - body: params.body ?? null,
1333 - parameters: params.parameters ?? [],
1334 - },
1335 - headers: {},
1336 - })),
1337 - search: toolRouterOverrides?.search ?? defaultSearchHandler,
1338 - toolkits: toolRouterOverrides?.toolkits ?? defaultToolkitsHandler,
1339 - tools: async () => ({
1340 - items: [],
1341 - }),
1342 - },
1343 - },
1315 + },
1316 + };
1317 +
1318 + // A resource the shadows do not cover reaches the transport, which dies
1319 + // with the URL instead of sending a live request.
1320 + const dieOnNetworkCall = HttpClient.make(request =>
1321 + Effect.die(new Error(`unexpected network call from the mock Composio client: ${request.url}`))
1322 + );
1323 +
1324 + // The real client refuses, before sending, a typed call that neither has a
1325 + // response schema loader nor passes `decode: false`. A shadow replaces the
1326 + // call, so it repeats that check; the raw `get`/`post` methods are exempt.
1327 + const isUndecodedCall = (args: ReadonlyArray<unknown>): boolean => {
1328 + const options = args.at(-1);
1329 + return Predicate.hasProperty(options, 'decode') && options.decode === false;
1330 + };
1331 + const hasSchemaLoader = (operation: string): boolean =>
1332 + operation.replace(/Stream$/, '') in composioSchemaLoaders;
1333 +
1334 + // Each shadow answers with an Effect or a promise; a rejection becomes
1335 + // the call's failure as it is.
1336 + const withShadows = <Resources extends object>(
1337 + base: Resources,
1338 + shadows: object,
1339 + chain: ReadonlyArray<string> = []
1340 + ): Resources => {
1341 + const shadowed = { ...base } as Record<string, unknown>;
1342 + for (const [key, shadow] of Object.entries(shadows) as Array<[string, unknown]>) {
1343 + const operation = [...chain, key].join('.');
1344 + shadowed[key] =
1345 + typeof shadow === 'function'
1346 + ? (...args: ReadonlyArray<unknown>) =>
1347 + Effect.suspend(() => {
1348 + if (chain.length > 0 && !isUndecodedCall(args) && !hasSchemaLoader(operation)) {
1349 + return Effect.die(
1350 + new Error(
1351 + `'${operation}' has no response schema loader and was called without decode: false`
1352 + )
1353 + );
1354 + }
1355 + const answer: unknown = shadow(...args);
1356 + return Effect.isEffect(answer)
1357 + ? answer
1358 + : Effect.tryPromise({
1359 + try: () => answer as Promise<unknown>,
1360 + catch: cause => cause,
1361 + });
1362 + })
1363 + : withShadows((shadowed[key] ?? {}) as object, shadow as object, [...chain, key]);
1364 }
1365 + return shadowed as Resources;
1366 + };
1367 +
1368 + const mockComposioClient = withShadows(
1369 + makeComposioClient(
1370 + {
1371 + apiKey: 'test',
1372 + userApiKey: null,
1373 + orgApiKey: null,
1374 + baseURL: 'https://mock.invalid',
1375 + deprecationNotices: 'off',
1376 + },
1377 + dieOnNetworkCall
1378 + ),
1379 + resourceShadows
1380 );
1381
1382 // --- Account, session-info, and consumer endpoints ---
@@ -1349,7 +1384,13 @@ export const TestLayer = (input?: TestLiveInput) =>
1384 // project the real client would have placed in its default headers.
1385 const accountData = input?.accountData ?? {};
1386 const noTestData = (operation: MockAccountRequest['operation']) =>
1352 - new APIConnectionError({ message: `No test data for ${operation}` });
1387 + new APIConnectionError({
1388 + message: `No test data for ${operation}`,
1389 + method: 'GET',
1390 + url: 'https://mock.invalid',
1391 + reason: 'TransportError',
1392 + description: `No test data for ${operation}`,
1393 + });
1394
1395 const scopeOf = (base: MockRequestScope, options?: RequestOptions): MockRequestScope => {
1396 // The CLI only ever passes plain header records.
@@ -1379,7 +1420,7 @@ export const TestLayer = (input?: TestLiveInput) =>
1420 };
1421
1422 return {
1382 - org: Object.assign(Object.create(mockComposioClient.org) as typeof mockComposioClient.org, {
1423 + org: {
1424 list: async (query?: { limit?: number } | null, options?: RequestOptions) => {
1425 record('org.list', options, query);
1426 if (!accountData.organizations) throw noTestData('org.list');
@@ -1438,7 +1479,7 @@ export const TestLayer = (input?: TestLiveInput) =>
1479 return { toolkits: [...accountData.connectedToolkits] };
1480 },
1481 },
1441 - }),
1482 + },
1483 auth: {
1484 session: {
1485 retrieveInfo: async (options?: RequestOptions) => {
@@ -1473,10 +1514,7 @@ export const TestLayer = (input?: TestLiveInput) =>
1514 const key = JSON.stringify([scope.userApiKey, scope.orgId, scope.projectId]);
1515 const cached = scopedClients.get(key);
1516 if (cached) return cached;
1476 - const scoped = Object.assign(
1477 - Object.create(mockComposioClient) as typeof mockComposioClient,
1478 - accountBranches(scope)
1479 - );
1517 + const scoped = withShadows(mockComposioClient, accountBranches(scope));
1518 scopedClients.set(key, scoped);
1519 return scoped;
1520 };
ts/packages/cli/test/src/analytics.events.test.ts
+1 -1
@@ -1,4 +1,4 @@
1 -import { VERSION as clientLibraryVersion } from '@composio/client';
1 +import { VERSION as clientLibraryVersion } from '@composio/client/effect';
2 import { readFileSync, writeFileSync } from 'node:fs';
3 import path from 'node:path';
4 import * as tempy from 'tempy';
ts/packages/cli/test/src/commands/connected-accounts/connected-accounts.link.client.cmd.test.ts new
+80
@@ -0,0 +1,80 @@
1 +import { describe, expect, layer } from '@effect/vitest';
2 +import { ConfigProvider, Effect } from 'effect';
3 +import { cli, MockConsole, TestLive } from 'test/__utils__';
4 +import { stubClientResources } from 'test/__utils__/services/stub-composio-client';
5 +
6 +const testLayer = TestLive({
7 + baseConfigProvider: ConfigProvider.fromEnv({ env: { COMPOSIO_USER_API_KEY: 'test_api_key' } }),
8 + fixture: 'global-test-user-id',
9 +});
10 +
11 +const rejection = (status: number, message: string, slug: string) =>
12 + Response.json({ error: { message, code: 1000 + status, slug, status } }, { status });
13 +
14 +describe('CLI: composio link over the API client', () => {
15 + layer(testLayer)('[Given] the API rejects the link for a toolkit', it => {
16 + it.effect('[Then] the API message and the browse hint are printed', () =>
17 + Effect.gen(function* () {
18 + const stub = stubClientResources(['toolRouter'], request =>
19 + request.path.endsWith('/link')
20 + ? rejection(
21 + 400,
22 + 'Toolkit gmail is disabled for this project',
23 + 'ToolRouterV2_ToolkitDisabled'
24 + )
25 + : Response.json({
26 + session_id: 'trs_stub_session',
27 + config: { user_id: 'consumer-user-org_test' },
28 + mcp: { type: 'http', url: 'https://mcp.stub.invalid' },
29 + tool_router_tools: [],
30 + })
31 + );
32 + yield* cli(['link', 'gmail', '--no-wait']).pipe(Effect.provide(stub.layer));
33 + const lines = yield* MockConsole.getLines({ stripAnsi: true });
34 +
35 + expect(lines).toEqual([
36 + 'Toolkit gmail is disabled for this project',
37 + 'Browse available toolkits:\n> composio dev toolkits list',
38 + ]);
39 + expect(stub.requests.at(-1)).toEqual({
40 + method: 'POST',
41 + path: '/api/v3.1/tool_router/session/trs_stub_session/link',
42 + body: { toolkit: 'gmail' },
43 + });
44 + })
45 + );
46 + });
47 +
48 + layer(testLayer)('[Given] the API rejects the link for an auth config', it => {
49 + it.effect('[Then] the API message and the browse hint are printed', () =>
50 + Effect.gen(function* () {
51 + const stub = stubClientResources(['link'], () =>
52 + rejection(404, 'Auth config ac_missing not found', 'AuthConfig_NotFound')
53 + );
54 + yield* cli([
55 + 'dev',
56 + 'connected-accounts',
57 + 'link',
58 + '--auth-config',
59 + 'ac_missing',
60 + '--user-id',
61 + 'user_1',
62 + '--no-wait',
63 + ]).pipe(Effect.provide(stub.layer));
64 + const lines = yield* MockConsole.getLines({ stripAnsi: true });
65 +
66 + expect(lines).toEqual([
67 + 'Auth config ac_missing not found',
68 + 'Browse available auth configs:\n> composio dev auth-configs list',
69 + ]);
70 + expect(stub.requests).toEqual([
71 + {
72 + method: 'POST',
73 + path: '/api/v3.1/connected_accounts/link',
74 + body: { auth_config_id: 'ac_missing', user_id: 'user_1' },
75 + },
76 + ]);
77 + })
78 + );
79 + });
80 +});
ts/packages/cli/test/src/commands/connected-accounts/connected-accounts.link.cmd.test.ts
+64 -52
@@ -1,4 +1,4 @@
1 -import { APIError } from '@composio/client';
1 +import { BadRequestError } from '@composio/client/effect';
2 import { describe, expect, layer } from '@effect/vitest';
3 import { ConfigProvider, Console, Effect } from 'effect';
4 import { cli, TestLive, MockConsole } from 'test/__utils__';
@@ -54,6 +54,13 @@ const connectedAccountWithCredentialFields = {
54 data: { refresh_token: 'must-not-leak' },
55 };
56
57 +const noManagedAuth = {
58 + message: 'No managed auth',
59 + code: 400,
60 + slug: 'ToolRouterV2_NoManagedAuth',
61 + status: 400,
62 +};
63 +
64 const testConfigProvider = ConfigProvider.fromEnv({
65 env: { COMPOSIO_USER_API_KEY: 'test_api_key' },
66 });
@@ -97,25 +104,29 @@ const RecordingTerminalUI = TerminalUI.of({
104 });
105
106 describe('CLI: composio dev connected-accounts link', () => {
100 - const toolRouterCreateSpy = vi.fn(async () => ({
101 - session_id: 'trs_test_session',
102 - config: {
103 - user_id: 'consumer-user-org_test',
104 - execute: {},
105 - search: {},
106 - preload: { tools: [] },
107 - instant: false as const,
108 - },
109 - config_version: 1,
110 - mcp: { type: 'http' as const, url: 'https://mcp.test.composio.dev' },
111 - tool_router_tools: ['COMPOSIO_SEARCH_TOOLS', 'COMPOSIO_MANAGE_CONNECTIONS'],
112 - }));
113 - const toolRouterLinkSpy = vi.fn(async () => ({
114 - connected_account_id: 'con_test_link',
115 - link_token: 'lt_test_token',
116 - redirect_url: 'https://app.composio.dev/link?token=lt_test_token',
117 - account_type: 'PRIVATE' as const,
118 - }));
107 + const toolRouterCreateSpy = vi.fn(() =>
108 + Effect.succeed({
109 + session_id: 'trs_test_session',
110 + config: {
111 + user_id: 'consumer-user-org_test',
112 + execute: {},
113 + search: {},
114 + preload: { tools: [] },
115 + instant: false as const,
116 + },
117 + config_version: 1,
118 + mcp: { type: 'http' as const, url: 'https://mcp.test.composio.dev' },
119 + tool_router_tools: ['COMPOSIO_SEARCH_TOOLS', 'COMPOSIO_MANAGE_CONNECTIONS'],
120 + })
121 + );
122 + const toolRouterLinkSpy = vi.fn(() =>
123 + Effect.succeed({
124 + connected_account_id: 'con_test_link',
125 + link_token: 'lt_test_token',
126 + redirect_url: 'https://app.composio.dev/link?token=lt_test_token',
127 + account_type: 'PRIVATE' as const,
128 + })
129 + );
130
131 afterEach(() => {
132 vi.restoreAllMocks();
@@ -360,21 +371,18 @@ describe('CLI: composio dev connected-accounts link', () => {
371 connectedAccountsData: makeConnectedAccountsData(),
372 fixture: 'global-test-user-id',
373 toolRouter: {
363 - link: async () => {
364 - throw APIError.generate(
365 - 400,
366 - {
367 - error: {
368 - message: 'No managed auth',
369 - code: 400,
370 - slug: 'ToolRouterV2_NoManagedAuth',
371 - status: 400,
372 - },
373 - },
374 - undefined,
375 - new Headers()
376 - );
377 - },
374 + link: () =>
375 + Effect.fail(
376 + new BadRequestError({
377 + message: `400 ${JSON.stringify({ error: noManagedAuth })}`,
378 + method: 'POST',
379 + url: 'https://mock.invalid/api/v3.1/tool_router/session/{session_id}/link',
380 + status: 400,
381 + requestId: undefined,
382 + details: noManagedAuth,
383 + body: { error: noManagedAuth },
384 + })
385 + ),
386 },
387 accountData: {
388 sessionInfo: scope => {
@@ -432,12 +440,13 @@ describe('CLI: composio dev connected-accounts link', () => {
440 connectedAccountsData: makeConnectedAccountsData(),
441 fixture: 'global-test-user-id',
442 toolRouter: {
435 - link: async () => ({
436 - connected_account_id: '',
437 - link_token: 'lt_test_token',
438 - redirect_url: '',
439 - account_type: 'PRIVATE' as const,
440 - }),
443 + link: () =>
444 + Effect.succeed({
445 + connected_account_id: '',
446 + link_token: 'lt_test_token',
447 + redirect_url: '',
448 + account_type: 'PRIVATE' as const,
449 + }),
450 },
451 })
452 )(
@@ -505,12 +514,14 @@ describe('CLI: composio dev connected-accounts link', () => {
514 max_accounts_per_toolkit: undefined,
515 require_explicit_selection: undefined,
516 },
508 - })
517 + }),
518 + { decode: false }
519 + );
520 + expect(toolRouterLinkSpy).toHaveBeenCalledWith(
521 + 'trs_test_session',
522 + { toolkit: 'gmail', alias: 'work' },
523 + { decode: false }
524 );
510 - expect(toolRouterLinkSpy).toHaveBeenCalledWith('trs_test_session', {
511 - toolkit: 'gmail',
512 - alias: 'work',
513 - });
525 })
526 );
527 });
@@ -520,12 +531,13 @@ describe('CLI: composio dev connected-accounts link', () => {
531 baseConfigProvider: testConfigProvider,
532 connectedAccountsData: makeConnectedAccountsData(),
533 toolRouter: {
523 - link: async () => ({
524 - connected_account_id: 'con_second_link',
525 - link_token: 'lt_test_token',
526 - redirect_url: 'https://app.composio.dev/link?token=lt_test_token',
527 - account_type: 'PRIVATE' as const,
528 - }),
534 + link: () =>
535 + Effect.succeed({
536 + connected_account_id: 'con_second_link',
537 + link_token: 'lt_test_token',
538 + redirect_url: 'https://app.composio.dev/link?token=lt_test_token',
539 + account_type: 'PRIVATE' as const,
540 + }),
541 },
542 fixture: 'global-test-user-id',
543 })
ts/packages/cli/test/src/commands/init.cmd.test.ts
+48
@@ -1,6 +1,7 @@
1 import { describe, expect, layer } from '@effect/vitest';
2 import { Effect } from 'effect';
3 import { cli, TestLive, MockConsole } from 'test/__utils__';
4 +import { makeOrgProject } from 'test/__utils__/models/account';
5
6 describe('CLI: composio dev init', () => {
7 describe('dev init --help', () => {
@@ -18,4 +19,51 @@ describe('CLI: composio dev init', () => {
19 );
20 });
21 });
22 +
23 + describe('dev init with the API unreachable', () => {
24 + const projectGuidance =
25 + 'Create a project at https://platform.composio.dev, then run `composio dev init` again.';
26 +
27 + layer(TestLive({ fixture: 'user-config-with-global-context' }))(it => {
28 + it.effect('[Given] no project list [Then] fails with the project guidance', () =>
29 + Effect.gen(function* () {
30 + const result = yield* Effect.result(cli(['dev', 'init', '--yes']));
31 + const lines = yield* MockConsole.getLines({ stripAnsi: true });
32 +
33 + expect(result._tag).toBe('Failure');
34 + expect(lines).toEqual([
35 + '-- composio dev init --',
36 + 'Could not fetch projects from the server.',
37 + projectGuidance,
38 + '-- --',
39 + 'Unexpected response from the server.',
40 + projectGuidance,
41 + '-- --',
42 + ]);
43 + })
44 + );
45 + });
46 +
47 + layer(
48 + TestLive({
49 + fixture: 'user-config-with-global-context',
50 + accountData: { projects: [makeOrgProject({ id: 'p1', name: 'One' })] },
51 + })
52 + )(it => {
53 + it.effect('[Given] no session info [Then] warns with the transport reason and finishes', () =>
54 + Effect.gen(function* () {
55 + yield* cli(['dev', 'init', '--yes']);
56 + const lines = yield* MockConsole.getLines({ stripAnsi: true });
57 +
58 + expect(lines.slice(0, 4)).toEqual([
59 + '-- composio dev init --',
60 + 'Using developer project "One"',
61 + 'Could not create .env.local from session info.',
62 + 'No test data for auth.session.retrieveInfo',
63 + ]);
64 + expect(lines[4]).toMatch(/^Project initialized in /);
65 + })
66 + );
67 + });
68 + });
69 });
ts/packages/cli/test/src/commands/listen.client.cmd.test.ts new
+180
@@ -0,0 +1,180 @@
1 +import { describe, expect, layer } from '@effect/vitest';
2 +import { Cause, ConfigProvider, Effect, Exit } from 'effect';
3 +import { ComposioCliUserConfig } from 'src/services/cli-user-config';
4 +import { cli, MockConsole, TestLive } from 'test/__utils__';
5 +import {
6 + stubClientResources,
7 + type StubRequest,
8 +} from 'test/__utils__/services/stub-composio-client';
9 +
10 +const testConfigProvider = ConfigProvider.fromEnv({
11 + env: { COMPOSIO_USER_API_KEY: 'test_api_key' },
12 +});
13 +
14 +const enableListen = Effect.gen(function* () {
15 + const config = yield* ComposioCliUserConfig;
16 + yield* config.update({
17 + experimentalFeatures: {
18 + ...config.raw.experimentalFeatures,
19 + listen: true,
20 + },
21 + });
22 +});
23 +
24 +const TRIGGER_ID = 'trg_gmail_new_gmail_message_con_gmail_test';
25 +
26 +const testLayer = TestLive({
27 + baseConfigProvider: testConfigProvider,
28 + fixture: 'global-test-user-id',
29 + connectedAccountsData: {
30 + items: [
31 + {
32 + id: 'con_gmail_test',
33 + status: 'ACTIVE',
34 + status_reason: null,
35 + is_disabled: false,
36 + user_id: 'consumer-user-org_test',
37 + toolkit: { slug: 'gmail' },
38 + auth_config: {
39 + id: 'auth_gmail_test',
40 + auth_scheme: 'OAUTH2',
41 + is_composio_managed: true,
42 + is_disabled: false,
43 + },
44 + created_at: '2026-04-06T17:59:00.000Z',
45 + updated_at: '2026-04-06T18:00:00.000Z',
46 + test_request_endpoint: '',
47 + },
48 + ],
49 + },
50 + realtimeData: {
51 + events: [
52 + {
53 + id: 'evt_trigger_1',
54 + type: 'composio.trigger.message',
55 + timestamp: '2026-04-06T18:00:00.000Z',
56 + metadata: {
57 + log_id: 'log_1',
58 + trigger_slug: 'GMAIL_NEW_GMAIL_MESSAGE',
59 + trigger_id: TRIGGER_ID,
60 + connected_account_id: 'con_gmail_test',
61 + auth_config_id: 'auth_gmail_test',
62 + user_id: 'consumer-user-org_test',
63 + },
64 + data: { threadId: 'thread_123' },
65 + },
66 + ],
67 + },
68 +});
69 +
70 +const invalidConfig = {
71 + error: {
72 + message: 'Invalid trigger config',
73 + code: 1401,
74 + slug: 'Trigger_InvalidConfig',
75 + status: 400,
76 + },
77 +};
78 +const invalidConfigText = `400 ${JSON.stringify(invalidConfig)}`;
79 +
80 +const notFound = {
81 + error: {
82 + message: 'Trigger type not found',
83 + code: 1404,
84 + slug: 'TriggerType_NotFound',
85 + status: 404,
86 + },
87 +};
88 +
89 +const isTriggerTypeLookup = (request: StubRequest) =>
90 + request.method === 'GET' && request.path.includes('/triggers_types/');
91 +
92 +const failureOf = (exit: Exit.Exit<unknown, unknown>) =>
93 + Exit.isFailure(exit) ? Cause.squash(exit.cause) : undefined;
94 +
95 +describe('CLI: composio listen over the API client', () => {
96 + layer(testLayer)('[Given] the API rejects the temporary trigger', it => {
97 + it.effect('[Then] the failure quotes the status and response body', () =>
98 + Effect.gen(function* () {
99 + const stub = stubClientResources(['triggerInstances', 'triggersTypes'], request =>
100 + isTriggerTypeLookup(request)
101 + ? Response.json({ slug: 'GMAIL_NEW_GMAIL_MESSAGE' })
102 + : Response.json(invalidConfig, { status: 400 })
103 + );
104 + yield* enableListen;
105 + const exit = yield* Effect.exit(
106 + cli(['listen', 'GMAIL_NEW_GMAIL_MESSAGE']).pipe(Effect.provide(stub.layer))
107 + );
108 +
109 + expect(failureOf(exit)).toMatchObject({
110 + _tag: 'commands/ListenCommandError',
111 + reason: 'create_trigger',
112 + message: `Failed to create temporary trigger "GMAIL_NEW_GMAIL_MESSAGE": Error: ${invalidConfigText}`,
113 + });
114 + expect(stub.requests.map(request => request.method)).toEqual(['POST', 'GET']);
115 + })
116 + );
117 +
118 + it.effect('[Then] a trigger type the API does not know is reported as unknown', () =>
119 + Effect.gen(function* () {
120 + const stub = stubClientResources(['triggerInstances', 'triggersTypes'], request =>
121 + isTriggerTypeLookup(request)
122 + ? Response.json(notFound, { status: 404 })
123 + : Response.json(invalidConfig, { status: 400 })
124 + );
125 + yield* enableListen;
126 + const exit = yield* Effect.exit(
127 + cli(['listen', 'GMAIL_NEW_GMAIL_MESAGE']).pipe(Effect.provide(stub.layer))
128 + );
129 +
130 + expect(failureOf(exit)).toMatchObject({
131 + _tag: 'commands/ListenCommandError',
132 + reason: 'unknown_trigger',
133 + message:
134 + 'Unknown trigger slug "GMAIL_NEW_GMAIL_MESAGE". List available slugs with `composio triggers list <toolkit>`.',
135 + });
136 + })
137 + );
138 + });
139 +
140 + layer(testLayer)('[Given] the temporary trigger cannot be disabled', it => {
141 + it.effect('[Then] the warning quotes the status and response body', () =>
142 + Effect.gen(function* () {
143 + const stub = stubClientResources(['triggerInstances'], request =>
144 + request.method === 'POST'
145 + ? Response.json({ trigger_id: TRIGGER_ID })
146 + : Response.json(invalidConfig, { status: 400 })
147 + );
148 + yield* enableListen;
149 + yield* cli(['listen', 'GMAIL_NEW_GMAIL_MESSAGE', '--max-events', '1']).pipe(
150 + Effect.provide(stub.layer)
151 + );
152 + const lines = yield* MockConsole.getLines({ stripAnsi: true });
153 +
154 + expect(lines.join('\n')).toContain(
155 + `Failed to disable temporary trigger "${TRIGGER_ID}": Error: ${invalidConfigText}`
156 + );
157 + })
158 + );
159 + });
160 +
161 + layer(testLayer)('[Given] the connected accounts cannot be listed', it => {
162 + it.effect('[Then] the failure quotes the status and response body', () =>
163 + Effect.gen(function* () {
164 + const stub = stubClientResources(['connectedAccounts'], () =>
165 + Response.json(invalidConfig, { status: 400 })
166 + );
167 + yield* enableListen;
168 + const exit = yield* Effect.exit(
169 + cli(['listen', 'GMAIL_NEW_GMAIL_MESSAGE']).pipe(Effect.provide(stub.layer))
170 + );
171 +
172 + expect(failureOf(exit)).toMatchObject({
173 + _tag: 'commands/ListenCommandError',
174 + reason: 'connected_accounts',
175 + message: `Failed to list connected accounts for "gmail": Error: ${invalidConfigText}`,
176 + });
177 + })
178 + );
179 + });
180 +});
ts/packages/cli/test/src/commands/login.cmd.test.ts
+10 -7
@@ -10,7 +10,7 @@ import { setupCacheDir } from 'src/effects/setup-cache-dir';
10 import { getTerminalCapabilities, TerminalUI } from 'src/services/terminal-ui';
11 import { writeStoredAgentIdentity } from 'src/services/agents';
12 import { ComposioUserContext } from 'src/services/user-context';
13 -import { InternalServerError } from '@composio/client';
13 +import { InternalServerError } from '@composio/client/effect';
14 import { ComposioSessionRepository } from 'src/services/composio-clients';
15 import { makeSessionInfo } from 'test/__utils__/models/account';
16 import type { MockAccountRequest } from 'test/__utils__/services/test-layer';
@@ -480,12 +480,15 @@ describe('CLI: composio login', () => {
480 ],
481 sessionInfo: scope => {
482 if (scope.projectId !== undefined) {
483 - throw new InternalServerError(
484 - 500,
485 - { message: 'Selected-org enrichment failed' },
486 - 'Selected-org enrichment failed',
487 - new Headers()
488 - );
483 + throw new InternalServerError({
484 + message: 'Selected-org enrichment failed',
485 + method: 'GET',
486 + url: 'https://mock.invalid/api/v3.1/auth/session/info',
487 + status: 500,
488 + requestId: undefined,
489 + details: undefined,
490 + body: { message: 'Selected-org enrichment failed' },
491 + });
492 }
493 return scope.orgId === undefined
494 ? makeSessionInfo({
ts/packages/cli/test/src/commands/logs-cmd/logs.tools.client.cmd.test.ts new
+120
@@ -0,0 +1,120 @@
1 +import { describe, expect, layer } from '@effect/vitest';
2 +import { Cause, ConfigProvider, Effect, Exit } from 'effect';
3 +import { extractErrorDetails } from 'src/effect-errors/logic/errors/extract-error-details';
4 +import { cli, MockConsole, TestLive } from 'test/__utils__';
5 +import { stubClientResources } from 'test/__utils__/services/stub-composio-client';
6 +
7 +const testLayer = TestLive({
8 + baseConfigProvider: ConfigProvider.fromEnv({ env: { COMPOSIO_USER_API_KEY: 'test_api_key' } }),
9 + fixture: 'global-test-user-id',
10 +});
11 +
12 +const page = {
13 + data: [
14 + {
15 + id: 'log_send_1',
16 + actionKey: 'GMAIL_SEND_EMAIL',
17 + appKey: 'gmail',
18 + app: { icon: 'https://logos.composio.dev/gmail', name: 'Gmail' },
19 + connectedAccountId: 'ca_gmail_1',
20 + entityId: 'user_1',
21 + status: 'success',
22 + executionTime: 412,
23 + minimalResponse: '{"id":"msg_1"}',
24 + createdAt: 1767225600000,
25 + },
26 + {
27 + id: 'log_fetch_2',
28 + actionKey: 'GMAIL_FETCH_EMAILS',
29 + appKey: 'gmail',
30 + app: { icon: 'https://logos.composio.dev/gmail', name: 'Gmail' },
31 + connectedAccountId: 'ca_gmail_1',
32 + entityId: 'user_1',
33 + status: 'failed',
34 + executionTime: 97,
35 + minimalResponse: '{"error":"quota"}',
36 + createdAt: 1767225660000,
37 + },
38 + ],
39 + nextCursor: null,
40 +};
41 +
42 +describe('CLI: composio dev logs tools over the API client', () => {
43 + layer(testLayer)('[Given] a page of tool logs', it => {
44 + it.effect('[Then] the logs are listed as a table and printed as the API returned them', () =>
45 + Effect.gen(function* () {
46 + const stub = stubClientResources(['logs'], () => Response.json(page));
47 + yield* cli(['dev', 'logs', 'tools', '--toolkit', 'gmail']).pipe(Effect.provide(stub.layer));
48 + const lines = yield* MockConsole.getLines({ stripAnsi: true });
49 +
50 + expect(lines).toEqual([
51 + 'Fetching tool logs...',
52 + [
53 + 'Listing 2 tool logs',
54 + '',
55 + 'Created At Log Id Status Toolkit Tool Exec Time Connected Account',
56 + '2026-01-01T00:00:00.000Z log_send_1 success Gmail GMAIL_SEND_EMAIL 412ms ca_gmail_1',
57 + '2026-01-01T00:01:00.000Z log_fetch_2 failed Gmail GMAIL_FETCH_EMAILS 97ms ca_gmail_1',
58 + ].join('\n'),
59 + 'To view full details for a log:\n> composio dev logs tools "log_send_1"',
60 + JSON.stringify(page, null, 2),
61 + ]);
62 + expect(stub.requests).toEqual([
63 + {
64 + method: 'POST',
65 + path: '/api/v3.1/internal/action_execution/logs',
66 + body: {
67 + cursor: null,
68 + limit: 30,
69 + case_sensitive: false,
70 + search_params: [{ field: 'toolkit_key', operation: '==', value: 'gmail' }],
71 + },
72 + },
73 + ]);
74 + })
75 + );
76 + });
77 +
78 + layer(testLayer)('[Given] the API rejects the request', it => {
79 + it.effect('[Then] the command fails with the status and response body as the cause', () =>
80 + Effect.gen(function* () {
81 + const stub = stubClientResources(['logs'], () =>
82 + Response.json(
83 + { error: { message: 'Not allowed', code: 1403, slug: 'Forbidden', status: 403 } },
84 + { status: 403 }
85 + )
86 + );
87 + const exit = yield* cli(['dev', 'logs', 'tools']).pipe(
88 + Effect.provide(stub.layer),
89 + Effect.exit
90 + );
91 + const failure = Exit.isFailure(exit) ? Cause.squash(exit.cause) : undefined;
92 +
93 + expect(failure).toMatchObject({ _tag: 'commands/ToolLogsRequestError' });
94 + expect(extractErrorDetails(failure).message).toBe(
95 + 'Failed to fetch tool logs.\nCaused by: 403 {"error":{"message":"Not allowed","code":1403,"slug":"Forbidden","status":403}}'
96 + );
97 + })
98 + );
99 + });
100 +
101 + layer(testLayer)('[Given] a page in a shape the API contract does not allow', it => {
102 + it.effect('[Then] the command fails naming the operation and suggests an upgrade', () =>
103 + Effect.gen(function* () {
104 + const stub = stubClientResources(['logs'], () =>
105 + // No `nextCursor`, which the API's response schema requires.
106 + Response.json({ data: [] }, { headers: { 'x-request-id': 'req_logs' } })
107 + );
108 + const exit = yield* cli(['dev', 'logs', 'tools']).pipe(
109 + Effect.provide(stub.layer),
110 + Effect.exit
111 + );
112 + const failure = Exit.isFailure(exit) ? Cause.squash(exit.cause) : undefined;
113 +
114 + expect(extractErrorDetails(failure).message).toBe(
115 + "Failed to fetch tool logs.\nCaused by: The API response for 'logs.tools.list' is not in the shape this version of the CLI expects (request id: req_logs).\nUpgrade the CLI, then retry:\n> composio upgrade"
116 + );
117 + })
118 + );
119 + });
120 +});
ts/packages/cli/test/src/commands/logs-cmd/logs.triggers.client.cmd.test.ts new
+53
@@ -0,0 +1,53 @@
1 +import { describe, expect, layer } from '@effect/vitest';
2 +import { ConfigProvider, Effect } from 'effect';
3 +import { cli, MockConsole, TestLive } from 'test/__utils__';
4 +import { stubClientResources } from 'test/__utils__/services/stub-composio-client';
5 +
6 +const testLayer = TestLive({
7 + baseConfigProvider: ConfigProvider.fromEnv({ env: { COMPOSIO_USER_API_KEY: 'test_api_key' } }),
8 + fixture: 'global-test-user-id',
9 +});
10 +
11 +// The API has served trigger logs in snake_case with numeric timestamps and
12 +// without `meta`; the response schema the client ships allows none of that.
13 +const olderLog = {
14 + log_id: 'log_older_1',
15 + trigger_id: 'trigger_1',
16 + trigger_nano_id: 'ti_older_1',
17 + trigger_name: 'SLACK_NEW_MESSAGE',
18 + toolkit_key: 'slack',
19 + connection_id: 'conn_1',
20 + entity_id: 'user_1',
21 + status: 'success',
22 + created_at: 1767225600000,
23 +};
24 +
25 +describe('CLI: composio dev logs triggers over the API client', () => {
26 + layer(testLayer)('[Given] a page of trigger logs in an older response shape', it => {
27 + it.effect('[Then] the logs are listed and printed as the API returned them', () =>
28 + Effect.gen(function* () {
29 + const page = { data: [olderLog] };
30 + const stub = stubClientResources(['logs'], () => Response.json(page));
31 + yield* cli(['dev', 'logs', 'triggers']).pipe(Effect.provide(stub.layer));
32 + const lines = yield* MockConsole.getLines({ stripAnsi: true });
33 +
34 + expect(lines.join('\n')).toContain('ti_older_1');
35 + expect(lines.join('\n')).toContain('SLACK_NEW_MESSAGE');
36 + expect(lines.at(-1)).toBe(JSON.stringify(page, null, 2));
37 + })
38 + );
39 + });
40 +
41 + layer(testLayer)('[Given] one trigger log in an older response shape', it => {
42 + it.effect('[Then] its details are shown and it is printed as the API returned it', () =>
43 + Effect.gen(function* () {
44 + const stub = stubClientResources(['logs'], () => Response.json(olderLog));
45 + yield* cli(['dev', 'logs', 'triggers', 'log_older_1']).pipe(Effect.provide(stub.layer));
46 + const lines = yield* MockConsole.getLines({ stripAnsi: true });
47 +
48 + expect(lines.join('\n')).toContain('SLACK_NEW_MESSAGE');
49 + expect(lines.at(-1)).toBe(JSON.stringify(olderLog, null, 2));
50 + })
51 + );
52 + });
53 +});
ts/packages/cli/test/src/commands/proxy.client.cmd.test.ts new
+131
@@ -0,0 +1,131 @@
1 +import { describe, expect, layer } from '@effect/vitest';
2 +import { Cause, ConfigProvider, Effect, Exit } from 'effect';
3 +import { cli, MockConsole, TestLive } from 'test/__utils__';
4 +import {
5 + stubClientResources,
6 + type StubRequest,
7 +} from 'test/__utils__/services/stub-composio-client';
8 +
9 +const testConfigProvider = ConfigProvider.fromEnv({
10 + env: { COMPOSIO_USER_API_KEY: 'test_api_key' },
11 +});
12 +
13 +const testLayer = TestLive({
14 + baseConfigProvider: testConfigProvider,
15 + fixture: 'global-test-user-id',
16 +});
17 +
18 +const ENDPOINT = 'https://gmail.googleapis.com/gmail/v1/users/me/profile';
19 +const proxyArgs = ['proxy', ENDPOINT, '--toolkit', 'gmail', '--skip-connection-check'];
20 +
21 +const isProxyExecute = (request: StubRequest) => request.path.endsWith('/proxy_execute');
22 +
23 +/** Proxy calls answered by `respond`; the session they run in is created normally. */
24 +const proxyingOver = (respond: () => Response) =>
25 + stubClientResources(['toolRouter'], request =>
26 + isProxyExecute(request)
27 + ? respond()
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 +
36 +const run = (stub: ReturnType<typeof proxyingOver>) =>
37 + Effect.gen(function* () {
38 + const exit = yield* cli(proxyArgs).pipe(Effect.provide(stub.layer), Effect.exit);
39 + const lines = yield* MockConsole.getLines({ stripAnsi: true });
40 + return { exit, output: lines.join('\n') };
41 + });
42 +
43 +describe('CLI: composio proxy over the API client', () => {
44 + layer(testLayer)('[Given] the API rejects the proxied call with an error envelope', it => {
45 + it.effect('[Then] the envelope message and slug are printed and the command fails', () =>
46 + Effect.gen(function* () {
47 + const { exit, output } = yield* run(
48 + proxyingOver(() =>
49 + Response.json(
50 + {
51 + error: {
52 + message: 'The endpoint is not allowed for this toolkit',
53 + code: 4311,
54 + slug: 'ToolRouterV2_ProxyEndpointNotAllowed',
55 + status: 403,
56 + },
57 + },
58 + { status: 403 }
59 + )
60 + )
61 + );
62 +
63 + expect(Exit.isFailure(exit) ? Cause.squash(exit.cause) : undefined).toMatchObject({
64 + _tag: 'commands/ProxyRequestError',
65 + message: `Failed to proxy GET ${ENDPOINT} via "gmail".`,
66 + });
67 + expect(output).toContain('The endpoint is not allowed for this toolkit');
68 + expect(output).toContain(
69 + JSON.stringify(
70 + {
71 + successful: false,
72 + error: 'The endpoint is not allowed for this toolkit',
73 + toolkit: 'gmail',
74 + endpoint: ENDPOINT,
75 + slug: 'ToolRouterV2_ProxyEndpointNotAllowed',
76 + },
77 + null,
78 + 2
79 + )
80 + );
81 + expect(output).not.toContain('Status:');
82 + })
83 + );
84 + });
85 +
86 + layer(testLayer)('[Given] the proxied API answers with a 404', it => {
87 + it.effect('[Then] the status and body are printed and the command succeeds', () =>
88 + Effect.gen(function* () {
89 + const { exit, output } = yield* run(
90 + proxyingOver(() =>
91 + Response.json({
92 + status: 404,
93 + data: { error: { code: 404, message: 'Requested entity was not found.' } },
94 + headers: {},
95 + })
96 + )
97 + );
98 +
99 + expect(Exit.isSuccess(exit)).toBe(true);
100 + expect(output).toContain('Status: 404');
101 + expect(output).toContain('"message": "Requested entity was not found."');
102 + })
103 + );
104 + });
105 +
106 + // On the live clock: a retry waits on the clock, and under the test clock a
107 + // retried call would hang instead of failing this test.
108 + layer(testLayer, { excludeTestServices: true })(
109 + '[Given] the API answers the proxied call with a 500',
110 + it => {
111 + it.effect('[Then] the call is attempted once', () =>
112 + Effect.gen(function* () {
113 + const stub = proxyingOver(() =>
114 + Response.json(
115 + { error: { message: 'Internal error', code: 500, slug: 'Internal', status: 500 } },
116 + // A retry would wait this long, so one that did happen shows up as a second request.
117 + { status: 500, headers: { 'retry-after-ms': '0' } }
118 + )
119 + );
120 + const { exit, output } = yield* run(stub);
121 +
122 + expect(Exit.isFailure(exit)).toBe(true);
123 + expect(output).toContain('Internal error');
124 + expect(stub.requests.filter(isProxyExecute)).toMatchObject([
125 + { method: 'POST', body: { toolkit_slug: 'gmail', endpoint: ENDPOINT, method: 'GET' } },
126 + ]);
127 + })
128 + );
129 + }
130 + );
131 +});
ts/packages/cli/test/src/commands/proxy.cmd.test.ts
+85 -77
@@ -1,4 +1,4 @@
1 -import { APIError } from '@composio/client';
1 +import { BadRequestError, type RequestOptions } from '@composio/client/effect';
2 import { describe, expect, it, layer } from '@effect/vitest';
3 import { ConfigProvider, Effect, Exit, Option } from 'effect';
4 import { afterEach, vi } from 'vitest';
@@ -19,6 +19,13 @@ const testConfigProvider = ConfigProvider.fromEnv({
19 env: { COMPOSIO_USER_API_KEY: 'test_api_key' },
20 });
21
22 +const noActiveConnection = {
23 + code: 4302,
24 + slug: 'ToolRouterV2_NoActiveConnection',
25 + message: 'No active connection',
26 + status: 400,
27 +};
28 +
29 describe('CLI: composio proxy', () => {
30 afterEach(() => {
31 vi.restoreAllMocks();
@@ -46,7 +53,7 @@ describe('CLI: composio proxy', () => {
53 it.effect('forwards proxy execute params and prints the response', () =>
54 Effect.gen(function* () {
55 let createParams: SessionCreateParams | undefined;
49 - let proxyOptions: { maxRetries?: number } | undefined;
56 + let proxyOptions: RequestOptions | undefined;
57 let proxyParams:
58 | {
59 sessionId: string;
@@ -101,40 +108,42 @@ describe('CLI: composio proxy', () => {
108 ],
109 },
110 toolRouter: {
104 - create: async (params: SessionCreateParams) => {
105 - createParams = params;
106 - return {
107 - session_id: 'trs_proxy_test',
108 - config: {
109 - user_id: params.user_id,
110 - execute: {},
111 - search: {},
112 - preload: { tools: [] },
113 - instant: false,
114 - },
115 - config_version: 1,
116 - mcp: { type: 'http' as const, url: 'https://mcp.test.composio.dev' },
117 - tool_router_tools: [],
118 - };
119 - },
120 - proxyExecute: async (
111 + create: (params: SessionCreateParams) =>
112 + Effect.sync(() => {
113 + createParams = params;
114 + return {
115 + session_id: 'trs_proxy_test',
116 + config: {
117 + user_id: params.user_id,
118 + execute: {},
119 + search: {},
120 + preload: { tools: [] },
121 + instant: false,
122 + },
123 + config_version: 1,
124 + mcp: { type: 'http' as const, url: 'https://mcp.test.composio.dev' },
125 + tool_router_tools: [],
126 + };
127 + }),
128 + proxyExecute: (
129 sessionId: string,
130 params: SessionProxyExecuteParams,
123 - options?: { maxRetries?: number }
124 - ) => {
125 - proxyParams = { sessionId, params };
126 - proxyOptions = options;
127 - return {
128 - result_type: 'completed' as const,
129 - status: 200,
130 - data: {
131 - ok: true,
132 - endpoint: params.endpoint,
133 - method: params.method,
134 - },
135 - headers: { 'content-type': 'application/json' },
136 - };
137 - },
131 + options?: RequestOptions
132 + ) =>
133 + Effect.sync(() => {
134 + proxyParams = { sessionId, params };
135 + proxyOptions = options;
136 + return {
137 + result_type: 'completed' as const,
138 + status: 200,
139 + data: {
140 + ok: true,
141 + endpoint: params.endpoint,
142 + method: params.method,
143 + },
144 + headers: { 'content-type': 'application/json' },
145 + };
146 + }),
147 },
148 });
149
@@ -181,7 +190,7 @@ describe('CLI: composio proxy', () => {
190 });
191 // A proxied call is never retried: a retry after the upstream API
192 // already acted would duplicate the side effect.
184 - expect(proxyOptions).toEqual({ maxRetries: 0 });
193 + expect(proxyOptions).toEqual({ maxRetries: 0, decode: false });
194
195 expect(output).toContain('Status: 200');
196 expect(output).toContain('"ok": true');
@@ -207,22 +216,23 @@ describe('CLI: composio proxy', () => {
216 baseConfigProvider: testConfigProvider,
217 fixture: 'global-test-user-id',
218 toolRouter: {
210 - create: async (_params: SessionCreateParams) => {
211 - createCalled = true;
212 - return {
213 - session_id: 'trs_proxy_test',
214 - config: {
215 - user_id: 'global_test_user_id',
216 - execute: {},
217 - search: {},
218 - preload: { tools: [] },
219 - instant: false,
220 - },
221 - config_version: 1,
222 - mcp: { type: 'http' as const, url: 'https://mcp.test.composio.dev' },
223 - tool_router_tools: [],
224 - };
225 - },
219 + create: (_params: SessionCreateParams) =>
220 + Effect.sync(() => {
221 + createCalled = true;
222 + return {
223 + session_id: 'trs_proxy_test',
224 + config: {
225 + user_id: 'global_test_user_id',
226 + execute: {},
227 + search: {},
228 + preload: { tools: [] },
229 + instant: false,
230 + },
231 + config_version: 1,
232 + mcp: { type: 'http' as const, url: 'https://mcp.test.composio.dev' },
233 + tool_router_tools: [],
234 + };
235 + }),
236 },
237 });
238
@@ -262,21 +272,18 @@ describe('CLI: composio proxy', () => {
272 baseConfigProvider: testConfigProvider,
273 fixture: 'global-test-user-id',
274 toolRouter: {
265 - proxyExecute: async () => {
266 - throw APIError.generate(
267 - 400,
268 - {
269 - error: {
270 - code: 4302,
271 - slug: 'ToolRouterV2_NoActiveConnection',
272 - message: 'No active connection',
273 - status: 400,
274 - },
275 - },
276 - undefined,
277 - new Headers()
278 - );
279 - },
275 + proxyExecute: () =>
276 + Effect.fail(
277 + new BadRequestError({
278 + message: `400 ${JSON.stringify({ error: noActiveConnection })}`,
279 + method: 'POST',
280 + url: 'https://mock.invalid/api/v3.1/tool_router/session/{session_id}/proxy_execute',
281 + status: 400,
282 + requestId: undefined,
283 + details: noActiveConnection,
284 + body: { error: noActiveConnection },
285 + })
286 + ),
287 },
288 });
289
@@ -310,18 +317,19 @@ describe('CLI: composio proxy', () => {
317 baseConfigProvider: testConfigProvider,
318 fixture: 'global-test-user-id',
319 toolRouter: {
313 - proxyExecute: async () => ({
314 - result_type: 'input_required' as const,
315 - input_requests: {
316 - approval_1: {
317 - type: 'elicitation' as const,
318 - mode: 'form' as const,
319 - message: 'Allow this request to Gmail?',
320 - requested_schema: { type: 'object' },
320 + proxyExecute: () =>
321 + Effect.succeed({
322 + result_type: 'input_required' as const,
323 + input_requests: {
324 + approval_1: {
325 + type: 'elicitation' as const,
326 + mode: 'form' as const,
327 + message: 'Allow this request to Gmail?',
328 + requested_schema: { type: 'object' },
329 + },
330 },
322 - },
323 - request_state: 'opaque-state-token',
324 - }),
331 + request_state: 'opaque-state-token',
332 + }),
333 },
334 });
335
ts/packages/cli/test/src/commands/toolkits/toolkits.version.client.cmd.test.ts new
+68
@@ -0,0 +1,68 @@
1 +import { describe, expect, layer } from '@effect/vitest';
2 +import { ConfigProvider, Effect } from 'effect';
3 +import { cli, MockConsole, TestLive } from 'test/__utils__';
4 +import { stubClientResources } from 'test/__utils__/services/stub-composio-client';
5 +
6 +const testLayer = TestLive({
7 + baseConfigProvider: ConfigProvider.fromEnv({ env: { COMPOSIO_USER_API_KEY: 'test_api_key' } }),
8 +});
9 +
10 +describe('CLI: composio dev toolkits version over the API client', () => {
11 + layer(testLayer)('[Given] a toolkit the API does not know', it => {
12 + it.effect('[Then] the API message and the browse hint are printed', () =>
13 + Effect.gen(function* () {
14 + const stub = stubClientResources(['toolkits'], () =>
15 + Response.json(
16 + {
17 + error: {
18 + message: 'Toolkit unknown not found',
19 + code: 1803,
20 + slug: 'Toolkit_NotFound',
21 + status: 404,
22 + },
23 + },
24 + { status: 404 }
25 + )
26 + );
27 + yield* cli(['dev', 'toolkits', 'version', 'unknown']).pipe(Effect.provide(stub.layer));
28 + const lines = yield* MockConsole.getLines({ stripAnsi: true });
29 +
30 + expect(lines).toEqual([
31 + 'Toolkit unknown not found',
32 + 'Browse available toolkits:\n> composio dev toolkits list',
33 + ]);
34 + expect(stub.requests).toEqual([{ method: 'GET', path: '/api/v3.1/toolkits/unknown' }]);
35 + })
36 + );
37 + });
38 +
39 + layer(testLayer)('[Given] a toolkit response without the fields the catalog requires', it => {
40 + it.effect('[Then] the versions it does carry are printed', () =>
41 + Effect.gen(function* () {
42 + const stub = stubClientResources(['toolkits'], () =>
43 + Response.json({
44 + slug: 'gmail',
45 + name: 'Gmail',
46 + meta: { available_versions: ['20260101_00', '20260201_00'] },
47 + })
48 + );
49 + yield* cli(['dev', 'toolkits', 'version', 'gmail']).pipe(Effect.provide(stub.layer));
50 + const lines = yield* MockConsole.getLines({ stripAnsi: true });
51 +
52 + expect(lines).toEqual([
53 + 'Fetching versions for toolkit "gmail"...',
54 + 'Toolkit: Gmail (gmail)\nLatest Version: 20260201_00\nLast 2 Available Versions:\n- 20260101_00\n- 20260201_00',
55 + JSON.stringify(
56 + {
57 + slug: 'gmail',
58 + latest_version: '20260201_00',
59 + available_versions_last_20: ['20260101_00', '20260201_00'],
60 + },
61 + null,
62 + 2
63 + ),
64 + ]);
65 + })
66 + );
67 + });
68 +});
ts/packages/cli/test/src/commands/tools/tools.execute.client.cmd.test.ts new
+131
@@ -0,0 +1,131 @@
1 +import { describe, expect, layer } from '@effect/vitest';
2 +import { beforeEach, vi } from 'vitest';
3 +import { ConfigProvider, Effect, Exit } from 'effect';
4 +import { CLI_ANALYTICS_EVENTS } from 'src/analytics/events';
5 +import { cli, TestLive, MockConsole } from 'test/__utils__';
6 +import { stubComposioClient } from 'test/__utils__/services/stub-composio-client';
7 +import { eventsNamed, trackedEvents } from 'test/__utils__/tracked-events';
8 +
9 +vi.mock('src/analytics/dispatch', async importOriginal => {
10 + const { recordTrackedEvent } = await import('test/__utils__/tracked-events');
11 + return {
12 + ...(await importOriginal<typeof import('src/analytics/dispatch')>()),
13 + trackCliEventEffect: recordTrackedEvent,
14 + };
15 +});
16 +
17 +// Disable CI redaction so tests see raw values; `src/ui/redact` reads `CI` once
18 +// at import time.
19 +vi.hoisted(() => {
20 + delete process.env.CI;
21 +});
22 +
23 +const testConfigProvider = ConfigProvider.fromEnv({
24 + env: { COMPOSIO_USER_API_KEY: 'test_api_key' },
25 +});
26 +
27 +const executeArgs = ['execute', 'GITHUB_STAR_REPO', '-d', '{"owner":"composio","repo":"composio"}'];
28 +
29 +/**
30 + * A test layer whose Tool Router execution goes through the real client, with
31 + * the request options the executor chose, to a transport answering `respond`.
32 + */
33 +const executingOver = (respond: () => Response) => {
34 + const stub = stubComposioClient(respond);
35 + const testLayer = TestLive({
36 + baseConfigProvider: testConfigProvider,
37 + fixture: 'global-test-user-id',
38 + stdin: { isTTY: true, data: '' },
39 + toolRouter: {
40 + execute: (sessionId, params, options) =>
41 + stub.client.toolRouter.session.execute(sessionId, params, options),
42 + },
43 + });
44 + return { requests: stub.requests, testLayer };
45 +};
46 +
47 +describe('CLI: composio execute over the API client', () => {
48 + beforeEach(() => {
49 + trackedEvents.length = 0;
50 + });
51 +
52 + const rejected = executingOver(() =>
53 + Response.json(
54 + {
55 + error: {
56 + message: 'The upstream app refused the request',
57 + code: 4310,
58 + slug: 'ToolRouterV2_UpstreamRefused',
59 + status: 400,
60 + },
61 + },
62 + { status: 400, headers: { 'x-request-id': 'req_refused' } }
63 + )
64 + );
65 + layer(rejected.testLayer)('[Given] the API rejects the execution with an error envelope', it => {
66 + it.effect('[Then] the failure is printed and tracked with its status, code and slug', () =>
67 + Effect.gen(function* () {
68 + const exit = yield* cli(executeArgs).pipe(Effect.exit);
69 + const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
70 +
71 + expect(Exit.isFailure(exit)).toBe(true);
72 + expect(output).toContain('The upstream app refused the request');
73 + expect(output).toContain('Error details');
74 + expect(eventsNamed(CLI_ANALYTICS_EVENTS.CLI_TOOL_INVOCATION_FAILED)).toMatchObject([
75 + {
76 + properties: {
77 + tool_slug: 'GITHUB_STAR_REPO',
78 + http_status: 400,
79 + api_error_code: 4310,
80 + error_slug: 'ToolRouterV2_UpstreamRefused',
81 + },
82 + },
83 + ]);
84 + })
85 + );
86 + });
87 +
88 + const unavailable = executingOver(() =>
89 + Response.json(
90 + { error: { message: 'Internal error', code: 500, slug: 'Internal', status: 500 } },
91 + // A retry would wait this long, so one that did happen shows up as a second request.
92 + { status: 500, headers: { 'retry-after-ms': '0' } }
93 + )
94 + );
95 + // On the live clock: a retry waits on the clock, and under the test clock a
96 + // retried call would hang instead of failing this test.
97 + layer(unavailable.testLayer, { excludeTestServices: true })(
98 + '[Given] the API answers the execution with a 500',
99 + it => {
100 + it.effect('[Then] the execution is attempted once', () =>
101 + Effect.gen(function* () {
102 + const exit = yield* cli(executeArgs).pipe(Effect.exit);
103 +
104 + expect(Exit.isFailure(exit)).toBe(true);
105 + expect(unavailable.requests).toMatchObject([
106 + { method: 'POST', body: { tool_slug: 'GITHUB_STAR_REPO' } },
107 + ]);
108 + })
109 + );
110 + }
111 + );
112 +
113 + const incomplete = executingOver(() =>
114 + // No `log_id`, which the API's response schema requires.
115 + Response.json({ result_type: 'completed', data: { starred: true }, error: null })
116 + );
117 + layer(incomplete.testLayer)('[Given] the execution response lacks a required field', it => {
118 + it.effect('[Then] the result is still reported', () =>
119 + Effect.gen(function* () {
120 + yield* cli(executeArgs);
121 + const lines = yield* MockConsole.getLines({ stripAnsi: true });
122 + const result = lines.map(line => line.trim()).findLast(line => line.startsWith('{'));
123 +
124 + expect(JSON.parse(result ?? '')).toMatchObject({
125 + successful: true,
126 + data: { starred: true },
127 + });
128 + })
129 + );
130 + });
131 +});
ts/packages/cli/test/src/commands/tools/tools.execute.cmd.test.ts
+250 -220
@@ -4,13 +4,14 @@ import * as path from 'node:path';
4 import { describe, expect, it, layer } from '@effect/vitest';
5 import { vi, beforeEach, afterEach } from 'vitest';
6 import { Config, ConfigProvider, DateTime, Effect, Exit, Option, Predicate } from 'effect';
7 -import { APIError } from '@composio/client';
7 +import { APIConnectionError, BadRequestError } from '@composio/client/effect';
8 import { ComposioNoActiveConnectionError } from 'src/services/composio-error-overrides';
9 import { setupCacheDir } from 'src/effects/setup-cache-dir';
10 import { getOrFetchToolInputDefinition } from 'src/services/tool-input-validation';
11 import { clearInProcessMemos } from 'src/utils/memoize-in-process';
12 import * as consumerShortTermCache from 'src/services/consumer-short-term-cache';
13 -import * as composioClients from 'src/services/composio-clients';
13 +import * as composioAccount from 'src/services/composio-account';
14 +import type { ToolkitProjectScope } from 'src/services/composio-clients';
15 import * as redactModule from 'src/ui/redact';
16 import { cli, TestLive, MockConsole } from 'test/__utils__';
17 import { liveEnvConfigProvider } from 'test/__utils__/live-env-config-provider';
@@ -39,6 +40,28 @@ const testConfigProvider = ConfigProvider.fromEnv({
40 env: { COMPOSIO_USER_API_KEY: 'test_api_key' },
41 });
42
43 +type ApiErrorEnvelope = NonNullable<BadRequestError['details']>;
44 +
45 +// The client's error for a 400 answered with `envelope`.
46 +const clientBadRequest = (envelope: ApiErrorEnvelope) =>
47 + new BadRequestError({
48 + message: `400 ${JSON.stringify({ error: envelope })}`,
49 + method: 'POST',
50 + url: 'https://mock.invalid/api/v3.1/tool_router/session/{session_id}/execute',
51 + status: 400,
52 + requestId: envelope.request_id,
53 + details: envelope,
54 + body: { error: envelope },
55 + });
56 +
57 +const noActiveConnectionEnvelope: ApiErrorEnvelope = {
58 + message: "No active connection found for toolkit(s) 'gmail' in this session",
59 + code: 4302,
60 + slug: 'ToolRouterV2_NoActiveConnection',
61 + status: 400,
62 + request_id: 'test-request-id',
63 +};
64 +
65 // `testConfigProvider` pins its env, so it bypasses the per-test
66 // `COMPOSIO_CACHE_DIR` stub, and the learned toolkit slugs resolve against the
67 // developer's real `~/.composio`. Suites that assert how a toolkit is learned
@@ -123,8 +146,16 @@ describe('CLI: composio execute', () => {
146 );
147
148 beforeEach(() => {
126 - vi.spyOn(composioClients, 'getLatestToolVersion').mockImplementation(() =>
127 - Effect.fail(new composioClients.HttpServerError({}))
149 + vi.spyOn(composioAccount, 'getLatestToolVersion').mockImplementation(() =>
150 + Effect.fail(
151 + new APIConnectionError({
152 + message: 'Connection error.',
153 + method: 'GET',
154 + url: 'https://backend.composio.dev/api/v3/tools/{tool_slug}/get_latest_version',
155 + reason: 'TransportError',
156 + description: undefined,
157 + })
158 + )
159 );
160 vi.spyOn(consumerShortTermCache, 'getFreshConsumerConnectedToolkitsFromCache').mockReturnValue(
161 Effect.succeed(Option.some(['gmail', 'github']))
@@ -138,8 +169,8 @@ describe('CLI: composio execute', () => {
169 });
170
171 let recordedSessionCreateParams: Array<Record<string, unknown>> = [];
141 - let recordedProjectToolkitScopes: Array<composioClients.ToolkitProjectScope | undefined> = [];
142 - let recordedExecuteOptions: Array<{ maxRetries?: number } | undefined> = [];
172 + let recordedProjectToolkitScopes: Array<ToolkitProjectScope | undefined> = [];
173 + let recordedExecuteOptions: Array<{ maxRetries?: number; decode?: boolean } | undefined> = [];
174 beforeEach(() => {
175 recordedSessionCreateParams = [];
176 recordedProjectToolkitScopes = [];
@@ -320,40 +351,43 @@ describe('CLI: composio execute', () => {
351 ],
352 },
353 toolRouter: {
323 - create: async params => {
324 - recordedSessionCreateParams.push(params as unknown as Record<string, unknown>);
325 - return {
326 - session_id: 'trs_gmail_default_session',
327 - config: {
328 - user_id: params.user_id,
329 - execute: {},
330 - search: {},
331 - preload: { tools: [] },
332 - instant: false,
333 - },
334 - config_version: 1,
335 - mcp: { type: 'http' as const, url: 'https://mcp.test.composio.dev' },
336 - tool_router_tools: ['COMPOSIO_SEARCH_TOOLS', 'COMPOSIO_MANAGE_CONNECTIONS'],
337 - };
338 - },
339 - execute: async (_sessionId, params, options) => {
340 - recordedExecuteOptions.push(options);
341 - return {
342 - result_type: 'completed' as const,
343 - data: { tool_slug: params.tool_slug, arguments: params.arguments },
344 - error: null,
345 - log_id: 'log_gmail_default',
346 - };
347 - },
348 - executeMeta: async (_sessionId, params, options) => {
349 - recordedExecuteOptions.push(options);
350 - return {
351 - result_type: 'completed' as const,
352 - data: { slug: params.slug, arguments: params.arguments },
353 - error: null,
354 - log_id: 'log_meta_default',
355 - };
356 - },
354 + create: params =>
355 + Effect.sync(() => {
356 + recordedSessionCreateParams.push(params as unknown as Record<string, unknown>);
357 + return {
358 + session_id: 'trs_gmail_default_session',
359 + config: {
360 + user_id: params.user_id,
361 + execute: {},
362 + search: {},
363 + preload: { tools: [] },
364 + instant: false,
365 + },
366 + config_version: 1,
367 + mcp: { type: 'http' as const, url: 'https://mcp.test.composio.dev' },
368 + tool_router_tools: ['COMPOSIO_SEARCH_TOOLS', 'COMPOSIO_MANAGE_CONNECTIONS'],
369 + };
370 + }),
371 + execute: (_sessionId, params, options) =>
372 + Effect.sync(() => {
373 + recordedExecuteOptions.push(options);
374 + return {
375 + result_type: 'completed' as const,
376 + data: { tool_slug: params.tool_slug, arguments: params.arguments },
377 + error: null,
378 + log_id: 'log_gmail_default',
379 + };
380 + }),
381 + executeMeta: (_sessionId, params, options) =>
382 + Effect.sync(() => {
383 + recordedExecuteOptions.push(options);
384 + return {
385 + result_type: 'completed' as const,
386 + data: { slug: params.slug, arguments: params.arguments },
387 + error: null,
388 + log_id: 'log_meta_default',
389 + };
390 + }),
391 },
392 })
393 )('[Given] default alias exists [Then] execute pins the default connected account', it => {
@@ -370,9 +404,9 @@ describe('CLI: composio execute', () => {
404 expect(recordedSessionCreateParams[0]?.connected_accounts).toEqual({
405 gmail: 'con_gmail_default',
406 });
373 - // An execution is never retried: a retry after the backend already
374 - // acted would duplicate the side effect.
375 - expect(recordedExecuteOptions.at(-1)).toEqual({ maxRetries: 0 });
407 + // An execution is never retried, and its response never validated: a
408 + // retry after the backend already acted would duplicate the side effect.
409 + expect(recordedExecuteOptions.at(-1)).toEqual({ maxRetries: 0, decode: false });
410 })
411 );
412
@@ -380,14 +414,14 @@ describe('CLI: composio execute', () => {
414 Effect.gen(function* () {
415 yield* cli(['execute', 'COMPOSIO_SEARCH_TOOLS', '-d', '{"query":"email"}']);
416
383 - expect(recordedExecuteOptions).toEqual([{ maxRetries: 0 }]);
417 + expect(recordedExecuteOptions).toEqual([{ maxRetries: 0, decode: false }]);
418 })
419 );
420
421 it.effect('asks for the latest tool version once per execute on a schema cache hit', () =>
422 Effect.gen(function* () {
423 const latestVersion = vi
390 - .spyOn(composioClients, 'getLatestToolVersion')
424 + .spyOn(composioAccount, 'getLatestToolVersion')
425 .mockImplementation(({ toolSlug }) =>
426 Effect.succeed({ tool_slug: toolSlug, version: '20260115_00' })
427 );
@@ -460,28 +494,30 @@ describe('CLI: composio execute', () => {
494 ],
495 },
496 toolRouter: {
463 - create: async params => {
464 - recordedSessionCreateParams.push(params as unknown as Record<string, unknown>);
465 - return {
466 - session_id: 'trs_gmail_explicit_session',
467 - config: {
468 - user_id: params.user_id,
469 - execute: {},
470 - search: {},
471 - preload: { tools: [] },
472 - instant: false,
473 - },
474 - config_version: 1,
475 - mcp: { type: 'http' as const, url: 'https://mcp.test.composio.dev' },
476 - tool_router_tools: ['COMPOSIO_SEARCH_TOOLS', 'COMPOSIO_MANAGE_CONNECTIONS'],
477 - };
478 - },
479 - execute: async (_sessionId, params) => ({
480 - result_type: 'completed' as const,
481 - data: { tool_slug: params.tool_slug, arguments: params.arguments },
482 - error: null,
483 - log_id: 'log_gmail_explicit',
484 - }),
497 + create: params =>
498 + Effect.sync(() => {
499 + recordedSessionCreateParams.push(params as unknown as Record<string, unknown>);
500 + return {
501 + session_id: 'trs_gmail_explicit_session',
502 + config: {
503 + user_id: params.user_id,
504 + execute: {},
505 + search: {},
506 + preload: { tools: [] },
507 + instant: false,
508 + },
509 + config_version: 1,
510 + mcp: { type: 'http' as const, url: 'https://mcp.test.composio.dev' },
511 + tool_router_tools: ['COMPOSIO_SEARCH_TOOLS', 'COMPOSIO_MANAGE_CONNECTIONS'],
512 + };
513 + }),
514 + execute: (_sessionId, params) =>
515 + Effect.succeed({
516 + result_type: 'completed' as const,
517 + data: { tool_slug: params.tool_slug, arguments: params.arguments },
518 + error: null,
519 + log_id: 'log_gmail_explicit',
520 + }),
521 },
522 })
523 )('[Given] --account selector [Then] execute pins the matched connected account', it => {
@@ -623,28 +659,30 @@ describe('CLI: composio execute', () => {
659 ],
660 },
661 toolRouter: {
626 - create: async params => {
627 - recordedSessionCreateParams.push(params as unknown as Record<string, unknown>);
628 - return {
629 - session_id: 'trs_google_analytics_session',
630 - config: {
631 - user_id: params.user_id,
632 - execute: {},
633 - search: {},
634 - preload: { tools: [] },
635 - instant: false,
636 - },
637 - config_version: 1,
638 - mcp: { type: 'http' as const, url: 'https://mcp.test.composio.dev' },
639 - tool_router_tools: ['COMPOSIO_SEARCH_TOOLS', 'COMPOSIO_MANAGE_CONNECTIONS'],
640 - };
641 - },
642 - execute: async (_sessionId, params) => ({
643 - result_type: 'completed' as const,
644 - data: { tool_slug: params.tool_slug, arguments: params.arguments },
645 - error: null,
646 - log_id: 'log_google_analytics',
647 - }),
662 + create: params =>
663 + Effect.sync(() => {
664 + recordedSessionCreateParams.push(params as unknown as Record<string, unknown>);
665 + return {
666 + session_id: 'trs_google_analytics_session',
667 + config: {
668 + user_id: params.user_id,
669 + execute: {},
670 + search: {},
671 + preload: { tools: [] },
672 + instant: false,
673 + },
674 + config_version: 1,
675 + mcp: { type: 'http' as const, url: 'https://mcp.test.composio.dev' },
676 + tool_router_tools: ['COMPOSIO_SEARCH_TOOLS', 'COMPOSIO_MANAGE_CONNECTIONS'],
677 + };
678 + }),
679 + execute: (_sessionId, params) =>
680 + Effect.succeed({
681 + result_type: 'completed' as const,
682 + data: { tool_slug: params.tool_slug, arguments: params.arguments },
683 + error: null,
684 + log_id: 'log_google_analytics',
685 + }),
686 },
687 })
688 )('[Given] a multi-word toolkit [Then] execute resolves it from the known toolkit list', it => {
@@ -724,28 +762,30 @@ describe('CLI: composio execute', () => {
762 ],
763 },
764 toolRouter: {
727 - create: async params => {
728 - recordedSessionCreateParams.push(params as unknown as Record<string, unknown>);
729 - return {
730 - session_id: 'trs_custom_grain_session',
731 - config: {
732 - user_id: params.user_id,
733 - execute: {},
734 - search: {},
735 - preload: { tools: [] },
736 - instant: false,
737 - },
738 - config_version: 1,
739 - mcp: { type: 'http' as const, url: 'https://mcp.test.composio.dev' },
740 - tool_router_tools: ['COMPOSIO_SEARCH_TOOLS', 'COMPOSIO_MANAGE_CONNECTIONS'],
741 - };
742 - },
743 - execute: async (_sessionId, params) => ({
744 - result_type: 'completed' as const,
745 - data: { tool_slug: params.tool_slug, arguments: params.arguments },
746 - error: null,
747 - log_id: 'log_custom_grain',
748 - }),
765 + create: params =>
766 + Effect.sync(() => {
767 + recordedSessionCreateParams.push(params as unknown as Record<string, unknown>);
768 + return {
769 + session_id: 'trs_custom_grain_session',
770 + config: {
771 + user_id: params.user_id,
772 + execute: {},
773 + search: {},
774 + preload: { tools: [] },
775 + instant: false,
776 + },
777 + config_version: 1,
778 + mcp: { type: 'http' as const, url: 'https://mcp.test.composio.dev' },
779 + tool_router_tools: ['COMPOSIO_SEARCH_TOOLS', 'COMPOSIO_MANAGE_CONNECTIONS'],
780 + };
781 + }),
782 + execute: (_sessionId, params) =>
783 + Effect.succeed({
784 + result_type: 'completed' as const,
785 + data: { tool_slug: params.tool_slug, arguments: params.arguments },
786 + error: null,
787 + log_id: 'log_custom_grain',
788 + }),
789 },
790 })
791 )('[Given] a project custom toolkit [Then] execute resolves it from the project list', it => {
@@ -861,28 +901,30 @@ describe('CLI: composio execute', () => {
901 ],
902 },
903 toolRouter: {
864 - create: async params => {
865 - recordedSessionCreateParams.push(params as unknown as Record<string, unknown>);
866 - return {
867 - session_id: 'trs_posthog_test_session',
868 - config: {
869 - user_id: params.user_id,
870 - execute: {},
871 - search: {},
872 - preload: { tools: [] },
873 - instant: false,
874 - },
875 - config_version: 1,
876 - mcp: { type: 'http' as const, url: 'https://mcp.test.composio.dev' },
877 - tool_router_tools: ['COMPOSIO_SEARCH_TOOLS', 'COMPOSIO_MANAGE_CONNECTIONS'],
878 - };
879 - },
880 - execute: async (_sessionId, params) => ({
881 - result_type: 'completed' as const,
882 - data: { tool_slug: params.tool_slug, arguments: params.arguments },
883 - error: null,
884 - log_id: 'log_posthog_test',
885 - }),
904 + create: params =>
905 + Effect.sync(() => {
906 + recordedSessionCreateParams.push(params as unknown as Record<string, unknown>);
907 + return {
908 + session_id: 'trs_posthog_test_session',
909 + config: {
910 + user_id: params.user_id,
911 + execute: {},
912 + search: {},
913 + preload: { tools: [] },
914 + instant: false,
915 + },
916 + config_version: 1,
917 + mcp: { type: 'http' as const, url: 'https://mcp.test.composio.dev' },
918 + tool_router_tools: ['COMPOSIO_SEARCH_TOOLS', 'COMPOSIO_MANAGE_CONNECTIONS'],
919 + };
920 + }),
921 + execute: (_sessionId, params) =>
922 + Effect.succeed({
923 + result_type: 'completed' as const,
924 + data: { tool_slug: params.tool_slug, arguments: params.arguments },
925 + error: null,
926 + log_id: 'log_posthog_test',
927 + }),
928 },
929 })
930 )(
@@ -920,28 +962,30 @@ describe('CLI: composio execute', () => {
962 fixture: 'global-test-user-id',
963 stdin: { isTTY: true, data: '' },
964 toolRouter: {
923 - create: async params => {
924 - recordedSessionCreateParams.push(params as unknown as Record<string, unknown>);
925 - return {
926 - session_id: 'trs_posthog_cached_session',
927 - config: {
928 - user_id: params.user_id,
929 - execute: {},
930 - search: {},
931 - preload: { tools: [] },
932 - instant: false,
933 - },
934 - config_version: 1,
935 - mcp: { type: 'http' as const, url: 'https://mcp.test.composio.dev' },
936 - tool_router_tools: ['COMPOSIO_SEARCH_TOOLS', 'COMPOSIO_MANAGE_CONNECTIONS'],
937 - };
938 - },
939 - execute: async (_sessionId, params) => ({
940 - result_type: 'completed' as const,
941 - data: { tool_slug: params.tool_slug, arguments: params.arguments },
942 - error: null,
943 - log_id: 'log_posthog_cached',
944 - }),
965 + create: params =>
966 + Effect.sync(() => {
967 + recordedSessionCreateParams.push(params as unknown as Record<string, unknown>);
968 + return {
969 + session_id: 'trs_posthog_cached_session',
970 + config: {
971 + user_id: params.user_id,
972 + execute: {},
973 + search: {},
974 + preload: { tools: [] },
975 + instant: false,
976 + },
977 + config_version: 1,
978 + mcp: { type: 'http' as const, url: 'https://mcp.test.composio.dev' },
979 + tool_router_tools: ['COMPOSIO_SEARCH_TOOLS', 'COMPOSIO_MANAGE_CONNECTIONS'],
980 + };
981 + }),
982 + execute: (_sessionId, params) =>
983 + Effect.succeed({
984 + result_type: 'completed' as const,
985 + data: { tool_slug: params.tool_slug, arguments: params.arguments },
986 + error: null,
987 + log_id: 'log_posthog_cached',
988 + }),
989 },
990 })
991 )('[Given] cached auth configs [Then] execute seeds the session from cache', it => {
@@ -1256,7 +1300,7 @@ describe('CLI: composio execute', () => {
1300 }),
1301 'utf8'
1302 );
1259 - vi.spyOn(composioClients, 'getLatestToolVersion').mockImplementation(({ toolSlug }) =>
1303 + vi.spyOn(composioAccount, 'getLatestToolVersion').mockImplementation(({ toolSlug }) =>
1304 Effect.succeed({ tool_slug: toolSlug, version: '20260115_00' })
1305 );
1306
@@ -1398,7 +1442,7 @@ describe('CLI: composio execute', () => {
1442 // so a tool call that does not wait for validation always gets through.
1443 const slowSchemaLookup = () =>
1444 vi
1401 - .spyOn(composioClients, 'getLatestToolVersion')
1445 + .spyOn(composioAccount, 'getLatestToolVersion')
1446 .mockImplementation(({ toolSlug }) =>
1447 Effect.promise(() => new Promise<void>(resolve => setTimeout(resolve, 25))).pipe(
1448 Effect.as({ tool_slug: toolSlug, version: '20260101_00' })
@@ -1668,17 +1712,22 @@ describe('CLI: composio execute', () => {
1712 fixture: 'global-test-user-id',
1713 stdin: { isTTY: true, data: '' },
1714 toolRouter: {
1671 - execute: async (_sessionId, params) => {
1672 - if (params.tool_slug === 'GMAIL_SEND_EMAIL') {
1673 - throw new Error('gmail execution failed');
1674 - }
1675 - return {
1676 - result_type: 'completed' as const,
1677 - data: { tool_slug: params.tool_slug, arguments: params.arguments },
1678 - error: null,
1679 - log_id: 'log_parallel_success',
1680 - };
1681 - },
1715 + execute: (_sessionId, params) =>
1716 + params.tool_slug === 'GMAIL_SEND_EMAIL'
1717 + ? Effect.fail(
1718 + clientBadRequest({
1719 + message: 'gmail execution failed',
1720 + code: 4310,
1721 + slug: 'ToolRouterV2_ExecutionFailed',
1722 + status: 400,
1723 + })
1724 + )
1725 + : Effect.succeed({
1726 + result_type: 'completed' as const,
1727 + data: { tool_slug: params.tool_slug, arguments: params.arguments },
1728 + error: null,
1729 + log_id: 'log_parallel_success',
1730 + }),
1731 },
1732 })
1733 )('[Given] one parallel execution fails [Then] sibling results are retained', it => {
@@ -2579,22 +2628,7 @@ describe('CLI: composio execute', () => {
2628 fixture: 'global-test-user-id',
2629 stdin: { isTTY: true, data: '' },
2630 toolRouter: {
2582 - execute: async () => {
2583 - throw APIError.generate(
2584 - 400,
2585 - {
2586 - error: {
2587 - message: "No active connection found for toolkit(s) 'gmail' in this session",
2588 - code: 4302,
2589 - slug: 'ToolRouterV2_NoActiveConnection',
2590 - status: 400,
2591 - request_id: 'test-request-id',
2592 - },
2593 - },
2594 - undefined,
2595 - new Headers()
2596 - );
2597 - },
2631 + execute: () => Effect.fail(clientBadRequest(noActiveConnectionEnvelope)),
2632 },
2633 })
2634 )('[Given] Tool Router NoActiveConnection error [Then] prints connection tips', it => {
@@ -2623,12 +2657,13 @@ describe('CLI: composio execute', () => {
2657 fixture: 'global-test-user-id',
2658 stdin: { isTTY: true, data: '' },
2659 toolRouter: {
2626 - execute: async (_sessionId, params) => ({
2627 - result_type: 'completed' as const,
2628 - data: { tool_slug: params.tool_slug, custom: 'response' },
2629 - error: null,
2630 - log_id: 'log_custom',
2631 - }),
2660 + execute: (_sessionId, params) =>
2661 + Effect.succeed({
2662 + result_type: 'completed' as const,
2663 + data: { tool_slug: params.tool_slug, custom: 'response' },
2664 + error: null,
2665 + log_id: 'log_custom',
2666 + }),
2667 },
2668 })
2669 )('[Given] custom Tool Router execute mock [Then] returns custom response', it => {
@@ -2652,12 +2687,13 @@ describe('CLI: composio execute', () => {
2687 fixture: 'global-test-user-id',
2688 stdin: { isTTY: true, data: '' },
2689 toolRouter: {
2655 - execute: async () => ({
2656 - result_type: 'failed' as const,
2657 - data: {},
2658 - error: null,
2659 - log_id: 'log_failed',
2660 - }),
2690 + execute: () =>
2691 + Effect.succeed({
2692 + result_type: 'failed' as const,
2693 + data: {},
2694 + error: null,
2695 + log_id: 'log_failed',
2696 + }),
2697 },
2698 })
2699 )('[Given] Tool Router reports a failed execution with no error text', it => {
@@ -2686,18 +2722,19 @@ describe('CLI: composio execute', () => {
2722 fixture: 'global-test-user-id',
2723 stdin: { isTTY: true, data: '' },
2724 toolRouter: {
2689 - execute: async () => ({
2690 - result_type: 'input_required' as const,
2691 - input_requests: {
2692 - approval_1: {
2693 - type: 'elicitation' as const,
2694 - mode: 'form' as const,
2695 - message: 'Allow GITHUB_STAR_REPO to star this repository?',
2696 - requested_schema: { type: 'object', properties: { approved: { type: 'boolean' } } },
2725 + execute: () =>
2726 + Effect.succeed({
2727 + result_type: 'input_required' as const,
2728 + input_requests: {
2729 + approval_1: {
2730 + type: 'elicitation' as const,
2731 + mode: 'form' as const,
2732 + message: 'Allow GITHUB_STAR_REPO to star this repository?',
2733 + requested_schema: { type: 'object', properties: { approved: { type: 'boolean' } } },
2734 + },
2735 },
2698 - },
2699 - request_state: 'opaque-state-token',
2700 - }),
2736 + request_state: 'opaque-state-token',
2737 + }),
2738 },
2739 })
2740 )('[Given] Tool Router asks for user input [Then] execute fails without a result', it => {
@@ -2758,19 +2795,12 @@ describe('CLI: composio execute', () => {
2795 fixture: 'global-test-user-id',
2796 stdin: { isTTY: true, data: '' },
2797 toolsExecutor: {
2761 - failWith: APIError.generate(
2762 - 400,
2763 - {
2764 - error: {
2765 - message: 'API error: invalid input',
2766 - code: 1001,
2767 - slug: 'Validation_Failed',
2768 - status: 400,
2769 - },
2770 - },
2771 - undefined,
2772 - new Headers()
2773 - ),
2798 + failWith: clientBadRequest({
2799 + message: 'API error: invalid input',
2800 + code: 1001,
2801 + slug: 'Validation_Failed',
2802 + status: 400,
2803 + }),
2804 },
2805 })
2806 )('[Given] executor throws an API error [Then] prints message and details', it => {
ts/packages/cli/test/src/commands/tools/tools.search.client.cmd.test.ts new
+177
@@ -0,0 +1,177 @@
1 +import { describe, expect, layer } from '@effect/vitest';
2 +import { Cause, ConfigProvider, Effect, Exit } from 'effect';
3 +import { extractErrorDetails } from 'src/effect-errors/logic/errors/extract-error-details';
4 +import { cli, MockConsole, TestLive } from 'test/__utils__';
5 +import {
6 + stubClientResources,
7 + type StubRequest,
8 +} from 'test/__utils__/services/stub-composio-client';
9 +
10 +const sendEmailInput = {
11 + type: 'object',
12 + properties: { recipient_email: { type: 'string' }, body: { type: 'string' } },
13 + required: ['recipient_email'],
14 +};
15 +
16 +const testLayer = TestLive({
17 + baseConfigProvider: ConfigProvider.fromEnv({ env: { COMPOSIO_USER_API_KEY: 'test_api_key' } }),
18 + fixture: 'global-test-user-id',
19 + toolkitsData: {
20 + tools: [
21 + {
22 + name: 'Send Email',
23 + slug: 'GMAIL_SEND_EMAIL',
24 + description: 'Send an email',
25 + tags: [],
26 + available_versions: ['20260101_00'],
27 + input_parameters: sendEmailInput,
28 + output_parameters: { type: 'object', properties: {} },
29 + },
30 + {
31 + name: 'Create Draft',
32 + slug: 'GMAIL_CREATE_EMAIL_DRAFT',
33 + description: 'Create a draft',
34 + tags: [],
35 + available_versions: ['20260101_00'],
36 + input_parameters: { type: 'object', properties: {} },
37 + output_parameters: { type: 'object', properties: {} },
38 + },
39 + ],
40 + },
41 +});
42 +
43 +const searchResponse = {
44 + success: true,
45 + error: null,
46 + results: [
47 + {
48 + index: 1,
49 + use_case: 'send an email',
50 + difficulty: 'easy',
51 + primary_tool_slugs: ['GMAIL_SEND_EMAIL'],
52 + related_tool_slugs: ['GMAIL_CREATE_EMAIL_DRAFT'],
53 + toolkits: ['gmail'],
54 + },
55 + ],
56 + toolkit_connection_statuses: [
57 + {
58 + toolkit: 'gmail',
59 + description: 'Gmail toolkit',
60 + has_active_connection: true,
61 + status_message: 'Connected',
62 + },
63 + ],
64 + tool_schemas: {
65 + GMAIL_SEND_EMAIL: {
66 + toolkit: 'gmail',
67 + tool_slug: 'GMAIL_SEND_EMAIL',
68 + description: 'Send an email',
69 + hasFullSchema: true,
70 + input_schema: sendEmailInput,
71 + },
72 + GMAIL_CREATE_EMAIL_DRAFT: {
73 + toolkit: 'gmail',
74 + tool_slug: 'GMAIL_CREATE_EMAIL_DRAFT',
75 + description: 'Create a draft',
76 + hasFullSchema: true,
77 + input_schema: { type: 'object', properties: {} },
78 + },
79 + },
80 + time_info: {
81 + current_time_utc: '2026-01-01T00:00:00.000Z',
82 + current_time_utc_epoch_seconds: 1767225600,
83 + message: 'UTC time',
84 + },
85 + session: { id: 'trs_stub_session', generate_id: false, instructions: 'Reuse this session id.' },
86 + next_steps_guidance: [],
87 +};
88 +
89 +const isSearch = (request: StubRequest) => request.path.endsWith('/search');
90 +
91 +/** Searches answered by `respond`; the session they run in is created normally. */
92 +const searchingOver = (respond: () => Response) =>
93 + stubClientResources(['toolRouter'], request =>
94 + isSearch(request)
95 + ? respond()
96 + : Response.json({
97 + session_id: 'trs_stub_session',
98 + config: { user_id: 'consumer-user-org_test' },
99 + mcp: { type: 'http', url: 'https://mcp.stub.invalid' },
100 + tool_router_tools: [],
101 + })
102 + );
103 +
104 +describe('CLI: composio search over the API client', () => {
105 + layer(testLayer)('[Given] a search response', it => {
106 + it.effect('[Then] the JSON payload lists the tools, their schemas and the next steps', () =>
107 + Effect.gen(function* () {
108 + const stub = searchingOver(() => Response.json(searchResponse));
109 + yield* cli(['search', 'send an email']).pipe(Effect.provide(stub.layer));
110 + const lines = yield* MockConsole.getLines({ stripAnsi: true });
111 +
112 + const payload = {
113 + results: [
114 + {
115 + index: 1,
116 + use_case: 'send an email',
117 + difficulty: 'easy',
118 + primary_tool_slugs: ['GMAIL_SEND_EMAIL'],
119 + related_tool_slugs: ['GMAIL_CREATE_EMAIL_DRAFT'],
120 + toolkits: ['gmail'],
121 + },
122 + ],
123 + tool_schemas: {
124 + primary: { GMAIL_SEND_EMAIL: '~/.composio/tool_definitions/GMAIL_SEND_EMAIL.json' },
125 + related_tools_path_format: '~/.composio/tool_definitions/<TOOL_SLUG>.json',
126 + },
127 + connected_toolkits: ['gmail'],
128 + next_steps: {
129 + guidance:
130 + 'You can directly proceed with these steps without waiting for the user to ask. Link accounts first if needed, then execute tools.',
131 + steps: [
132 + { action: 'Link a user account', command: 'composio link gmail' },
133 + {
134 + action: 'Execute a tool',
135 + command: `composio execute "GMAIL_SEND_EMAIL" -d '{"recipient_email":"","body":""}'`,
136 + },
137 + ],
138 + },
139 + };
140 + // Once as the log line and once as the piped output.
141 + expect(lines).toEqual([JSON.stringify(payload, null, 2), JSON.stringify(payload, null, 2)]);
142 + expect(stub.requests.filter(isSearch)).toEqual([
143 + {
144 + method: 'POST',
145 + path: '/api/v3.1/tool_router/session/trs_stub_session/search',
146 + body: { queries: [{ use_case: 'send an email' }] },
147 + },
148 + ]);
149 + })
150 + );
151 + });
152 +
153 + layer(testLayer)('[Given] the API rejects the search', it => {
154 + it.effect('[Then] the command fails with the status and response body as the cause', () =>
155 + Effect.gen(function* () {
156 + const stub = searchingOver(() =>
157 + Response.json(
158 + {
159 + error: { message: 'Query too long', code: 1400, slug: 'Search_Invalid', status: 400 },
160 + },
161 + { status: 400 }
162 + )
163 + );
164 + const exit = yield* cli(['search', 'send an email']).pipe(
165 + Effect.provide(stub.layer),
166 + Effect.exit
167 + );
168 + const failure = Exit.isFailure(exit) ? Cause.squash(exit.cause) : undefined;
169 +
170 + expect(failure).toMatchObject({ _tag: 'commands/ToolsSearchRequestError' });
171 + expect(extractErrorDetails(failure).message).toBe(
172 + 'Failed to search tools.\nCaused by: 400 {"error":{"message":"Query too long","code":1400,"slug":"Search_Invalid","status":400}}'
173 + );
174 + })
175 + );
176 + });
177 +});
ts/packages/cli/test/src/commands/tools/tools.search.cmd.test.ts
+317 -307
@@ -141,45 +141,46 @@ describe('CLI: composio search', () => {
141 TestLive({
142 ...testLiveOptions,
143 toolRouter: {
144 - search: async (_sessionId, params) => ({
145 - success: true,
146 - error: null,
147 - results: [
148 - {
149 - index: 1,
150 - use_case: params.queries[0]?.use_case ?? '',
151 - primary_tool_slugs: [customSlug],
152 - related_tool_slugs: [],
153 - toolkits: ['CUSTOM_DEEPWIKI'],
154 - },
155 - ],
156 - tool_schemas: {
157 - [customSlug]: {
158 - tool_slug: customSlug,
159 - toolkit: 'CUSTOM_DEEPWIKI',
160 - description: 'Read wiki contents',
161 - hasFullSchema: true,
162 - input_schema: {
163 - type: 'object',
164 - properties: { repo: { type: 'string' } },
165 - required: ['repo'],
144 + search: (_sessionId, params) =>
145 + Effect.succeed({
146 + success: true,
147 + error: null,
148 + results: [
149 + {
150 + index: 1,
151 + use_case: params.queries[0]?.use_case ?? '',
152 + primary_tool_slugs: [customSlug],
153 + related_tool_slugs: [],
154 + toolkits: ['CUSTOM_DEEPWIKI'],
155 + },
156 + ],
157 + tool_schemas: {
158 + [customSlug]: {
159 + tool_slug: customSlug,
160 + toolkit: 'CUSTOM_DEEPWIKI',
161 + description: 'Read wiki contents',
162 + hasFullSchema: true,
163 + input_schema: {
164 + type: 'object',
165 + properties: { repo: { type: 'string' } },
166 + required: ['repo'],
167 + },
168 + output_schema: { type: 'object', properties: {} },
169 },
167 - output_schema: { type: 'object', properties: {} },
170 },
169 - },
170 - toolkit_connection_statuses: [],
171 - next_steps_guidance: [],
172 - session: {
173 - id: 'trs_test_session',
174 - generate_id: false,
175 - instructions: 'Reuse this session id for follow-up calls.',
176 - },
177 - time_info: {
178 - current_time_utc: '2026-01-01T00:00:00.000Z',
179 - current_time_utc_epoch_seconds: 1767225600,
180 - message: 'UTC time',
181 - },
182 - }),
171 + toolkit_connection_statuses: [],
172 + next_steps_guidance: [],
173 + session: {
174 + id: 'trs_test_session',
175 + generate_id: false,
176 + instructions: 'Reuse this session id for follow-up calls.',
177 + },
178 + time_info: {
179 + current_time_utc: '2026-01-01T00:00:00.000Z',
180 + current_time_utc_epoch_seconds: 1767225600,
181 + message: 'UTC time',
182 + },
183 + }),
184 },
185 })
186 )('[Given] a remote custom tool schema [Then] search uses the Tool Router schema', it => {
@@ -200,66 +201,68 @@ describe('CLI: composio search', () => {
201 TestLive({
202 ...testLiveOptions,
203 toolRouter: {
203 - search: async (_sessionId, params) => ({
204 - success: true,
205 - error: null,
206 - results: [
207 - {
208 - index: 1,
209 - use_case: params.queries[0]?.use_case ?? '',
210 - primary_tool_slugs: [customSlug],
211 - related_tool_slugs: [],
212 - toolkits: ['CUSTOM_DEEPWIKI'],
213 - },
214 - ],
215 - tool_schemas: {
216 - [customSlug]: {
217 - tool_slug: customSlug,
218 - toolkit: 'CUSTOM_DEEPWIKI',
219 - description: 'Read wiki contents',
220 - hasFullSchema: false,
221 - schemaRef: {
222 - tool: 'COMPOSIO_GET_TOOL_SCHEMAS',
223 - args: { tool_slugs: [customSlug] },
204 + search: (_sessionId, params) =>
205 + Effect.succeed({
206 + success: true,
207 + error: null,
208 + results: [
209 + {
210 + index: 1,
211 + use_case: params.queries[0]?.use_case ?? '',
212 + primary_tool_slugs: [customSlug],
213 + related_tool_slugs: [],
214 + toolkits: ['CUSTOM_DEEPWIKI'],
215 + },
216 + ],
217 + tool_schemas: {
218 + [customSlug]: {
219 + tool_slug: customSlug,
220 + toolkit: 'CUSTOM_DEEPWIKI',
221 + description: 'Read wiki contents',
222 + hasFullSchema: false,
223 + schemaRef: {
224 + tool: 'COMPOSIO_GET_TOOL_SCHEMAS',
225 + args: { tool_slugs: [customSlug] },
226 + },
227 },
228 },
226 - },
227 - toolkit_connection_statuses: [],
228 - next_steps_guidance: [],
229 - session: {
230 - id: 'trs_test_session',
231 - generate_id: false,
232 - instructions: 'Reuse this session id for follow-up calls.',
233 - },
234 - time_info: {
235 - current_time_utc: '2026-01-01T00:00:00.000Z',
236 - current_time_utc_epoch_seconds: 1767225600,
237 - message: 'UTC time',
238 - },
239 - }),
240 - executeMeta: async (_sessionId, params) => {
241 - schemaRequestSlugs = params.arguments?.tool_slugs;
242 - return {
243 - result_type: 'completed' as const,
244 - data: {
245 - success: true,
246 - tool_schemas: {
247 - [customSlug]: {
248 - tool_slug: customSlug,
249 - toolkit: 'CUSTOM_DEEPWIKI',
250 - description: 'Read wiki contents',
251 - input_schema: {
252 - type: 'object',
253 - properties: { repo: { type: 'string' } },
254 - required: ['repo'],
229 + toolkit_connection_statuses: [],
230 + next_steps_guidance: [],
231 + session: {
232 + id: 'trs_test_session',
233 + generate_id: false,
234 + instructions: 'Reuse this session id for follow-up calls.',
235 + },
236 + time_info: {
237 + current_time_utc: '2026-01-01T00:00:00.000Z',
238 + current_time_utc_epoch_seconds: 1767225600,
239 + message: 'UTC time',
240 + },
241 + }),
242 + executeMeta: (_sessionId, params) =>
243 + Effect.sync(() => {
244 + schemaRequestSlugs = params.arguments?.tool_slugs;
245 + return {
246 + result_type: 'completed' as const,
247 + data: {
248 + success: true,
249 + tool_schemas: {
250 + [customSlug]: {
251 + tool_slug: customSlug,
252 + toolkit: 'CUSTOM_DEEPWIKI',
253 + description: 'Read wiki contents',
254 + input_schema: {
255 + type: 'object',
256 + properties: { repo: { type: 'string' } },
257 + required: ['repo'],
258 + },
259 },
260 },
261 },
258 - },
259 - error: null,
260 - log_id: 'log_test',
261 - };
262 - },
262 + error: null,
263 + log_id: 'log_test',
264 + };
265 + }),
266 },
267 })
268 )(
@@ -382,49 +385,50 @@ describe('CLI: composio search', () => {
385 TestLive({
386 ...testLiveOptions,
387 toolRouter: {
385 - search: async (_sessionId, params) => ({
386 - success: true,
387 - error: null,
388 - results: [
389 - {
390 - index: 1,
391 - use_case: params.queries[0]?.use_case ?? '',
392 - primary_tool_slugs: ['GMAIL_SEND_EMAIL'],
393 - related_tool_slugs: [],
394 - toolkits: ['gmail'],
395 - reference_workbench_snippets: [{ description: 'snippet', code: 'print("hi")' }],
388 + search: (_sessionId, params) =>
389 + Effect.succeed({
390 + success: true,
391 + error: null,
392 + results: [
393 + {
394 + index: 1,
395 + use_case: params.queries[0]?.use_case ?? '',
396 + primary_tool_slugs: ['GMAIL_SEND_EMAIL'],
397 + related_tool_slugs: [],
398 + toolkits: ['gmail'],
399 + reference_workbench_snippets: [{ description: 'snippet', code: 'print("hi")' }],
400 + },
401 + ],
402 + tool_schemas: {
403 + GMAIL_SEND_EMAIL: {
404 + tool_slug: 'GMAIL_SEND_EMAIL',
405 + toolkit: 'gmail',
406 + description: 'Sends an email',
407 + hasFullSchema: true,
408 + input_schema: { type: 'object', properties: {} },
409 + output_schema: { type: 'object', properties: {} },
410 + },
411 },
397 - ],
398 - tool_schemas: {
399 - GMAIL_SEND_EMAIL: {
400 - tool_slug: 'GMAIL_SEND_EMAIL',
401 - toolkit: 'gmail',
402 - description: 'Sends an email',
403 - hasFullSchema: true,
404 - input_schema: { type: 'object', properties: {} },
405 - output_schema: { type: 'object', properties: {} },
412 + toolkit_connection_statuses: [
413 + {
414 + toolkit: 'gmail',
415 + description: 'gmail toolkit',
416 + has_active_connection: false,
417 + status_message: 'No active connection',
418 + },
419 + ],
420 + next_steps_guidance: [],
421 + session: {
422 + id: 'trs_test_session',
423 + generate_id: false,
424 + instructions: 'Reuse this session id for follow-up calls.',
425 },
407 - },
408 - toolkit_connection_statuses: [
409 - {
410 - toolkit: 'gmail',
411 - description: 'gmail toolkit',
412 - has_active_connection: false,
413 - status_message: 'No active connection',
426 + time_info: {
427 + current_time_utc: '2026-01-01T00:00:00.000Z',
428 + current_time_utc_epoch_seconds: 1767225600,
429 + message: 'UTC time',
430 },
415 - ],
416 - next_steps_guidance: [],
417 - session: {
418 - id: 'trs_test_session',
419 - generate_id: false,
420 - instructions: 'Reuse this session id for follow-up calls.',
421 - },
422 - time_info: {
423 - current_time_utc: '2026-01-01T00:00:00.000Z',
424 - current_time_utc_epoch_seconds: 1767225600,
425 - message: 'UTC time',
426 - },
427 - }),
431 + }),
432 },
433 })
434 )(
@@ -533,67 +537,69 @@ describe('CLI: composio search', () => {
537 toolkitsData,
538 fixture: 'global-test-user-id',
539 toolRouter: {
536 - create: async params => {
537 - createParams = params;
538 - return {
539 - session_id: 'trs_test_session',
540 - config: {
541 - user_id: params.user_id,
542 - execute: {},
543 - search: {},
544 - preload: { tools: [] },
545 - instant: false,
546 - },
547 - config_version: 1,
548 - mcp: { type: 'http', url: 'https://mcp.test.composio.dev' },
549 - tool_router_tools: ['COMPOSIO_SEARCH_TOOLS'],
550 - };
551 - },
552 - search: async (_sessionId, params) => {
553 - searchParams = params;
554 - return {
555 - success: true,
556 - error: null,
557 - results: [
558 - {
559 - index: 1,
560 - use_case: params.queries[0]?.use_case ?? '',
561 - primary_tool_slugs: ['GMAIL_SEND_EMAIL'],
562 - related_tool_slugs: [],
563 - toolkits: ['gmail'],
540 + create: params =>
541 + Effect.sync(() => {
542 + createParams = params;
543 + return {
544 + session_id: 'trs_test_session',
545 + config: {
546 + user_id: params.user_id,
547 + execute: {},
548 + search: {},
549 + preload: { tools: [] },
550 + instant: false,
551 },
565 - ],
566 - tool_schemas: {
567 - GMAIL_SEND_EMAIL: {
568 - tool_slug: 'GMAIL_SEND_EMAIL',
569 - toolkit: 'gmail',
570 - description: 'Sends an email',
571 - hasFullSchema: true,
572 - input_schema: { type: 'object', properties: {} },
573 - output_schema: { type: 'object', properties: {} },
552 + config_version: 1,
553 + mcp: { type: 'http', url: 'https://mcp.test.composio.dev' },
554 + tool_router_tools: ['COMPOSIO_SEARCH_TOOLS'],
555 + };
556 + }),
557 + search: (_sessionId, params) =>
558 + Effect.sync(() => {
559 + searchParams = params;
560 + return {
561 + success: true,
562 + error: null,
563 + results: [
564 + {
565 + index: 1,
566 + use_case: params.queries[0]?.use_case ?? '',
567 + primary_tool_slugs: ['GMAIL_SEND_EMAIL'],
568 + related_tool_slugs: [],
569 + toolkits: ['gmail'],
570 + },
571 + ],
572 + tool_schemas: {
573 + GMAIL_SEND_EMAIL: {
574 + tool_slug: 'GMAIL_SEND_EMAIL',
575 + toolkit: 'gmail',
576 + description: 'Sends an email',
577 + hasFullSchema: true,
578 + input_schema: { type: 'object', properties: {} },
579 + output_schema: { type: 'object', properties: {} },
580 + },
581 },
575 - },
576 - toolkit_connection_statuses: [
577 - {
578 - toolkit: 'gmail',
579 - description: 'gmail toolkit',
580 - has_active_connection: false,
581 - status_message: 'No active connection',
582 + toolkit_connection_statuses: [
583 + {
584 + toolkit: 'gmail',
585 + description: 'gmail toolkit',
586 + has_active_connection: false,
587 + status_message: 'No active connection',
588 + },
589 + ],
590 + next_steps_guidance: [],
591 + session: {
592 + id: 'trs_test_session',
593 + generate_id: false,
594 + instructions: 'Reuse this session id for follow-up calls.',
595 },
583 - ],
584 - next_steps_guidance: [],
585 - session: {
586 - id: 'trs_test_session',
587 - generate_id: false,
588 - instructions: 'Reuse this session id for follow-up calls.',
589 - },
590 - time_info: {
591 - current_time_utc: '2026-01-01T00:00:00.000Z',
592 - current_time_utc_epoch_seconds: 1767225600,
593 - message: 'UTC time',
594 - },
595 - };
596 - },
596 + time_info: {
597 + current_time_utc: '2026-01-01T00:00:00.000Z',
598 + current_time_utc_epoch_seconds: 1767225600,
599 + message: 'UTC time',
600 + },
601 + };
602 + }),
603 },
604 })
605 )('[Given] --toolkits filter [Then] it is passed to session create as enabled toolkits', it => {
@@ -618,22 +624,23 @@ describe('CLI: composio search', () => {
624 toolkitsData,
625 fixture: 'global-test-user-id',
626 toolRouter: {
621 - create: async params => {
622 - createParams = params;
623 - return {
624 - session_id: 'trs_test_session',
625 - config: {
626 - user_id: params.user_id,
627 - execute: {},
628 - search: {},
629 - preload: { tools: [] },
630 - instant: false,
631 - },
632 - config_version: 1,
633 - mcp: { type: 'http', url: 'https://mcp.test.composio.dev' },
634 - tool_router_tools: ['COMPOSIO_SEARCH_TOOLS'],
635 - };
636 - },
627 + create: params =>
628 + Effect.sync(() => {
629 + createParams = params;
630 + return {
631 + session_id: 'trs_test_session',
632 + config: {
633 + user_id: params.user_id,
634 + execute: {},
635 + search: {},
636 + preload: { tools: [] },
637 + instant: false,
638 + },
639 + config_version: 1,
640 + mcp: { type: 'http', url: 'https://mcp.test.composio.dev' },
641 + tool_router_tools: ['COMPOSIO_SEARCH_TOOLS'],
642 + };
643 + }),
644 },
645 })
646 )(
@@ -662,53 +669,54 @@ describe('CLI: composio search', () => {
669 toolkitsData,
670 fixture: 'global-test-user-id',
671 toolRouter: {
665 - search: async (_sessionId, params) => {
666 - searchParams = params;
667 - return {
668 - success: true,
669 - error: null,
670 - results: params.queries.map((query, index) => ({
671 - index: index + 1,
672 - use_case: query.use_case ?? '',
673 - primary_tool_slugs:
674 - query.use_case === 'create issue'
675 - ? ['GITHUB_CREATE_ISSUE']
676 - : ['GMAIL_SEND_EMAIL'],
677 - related_tool_slugs: [],
678 - toolkits: query.use_case === 'create issue' ? ['github'] : ['gmail'],
679 - })),
680 - tool_schemas: {
681 - GMAIL_SEND_EMAIL: {
682 - tool_slug: 'GMAIL_SEND_EMAIL',
683 - toolkit: 'gmail',
684 - description: 'Sends an email',
685 - hasFullSchema: true,
686 - input_schema: { type: 'object', properties: {} },
687 - output_schema: { type: 'object', properties: {} },
672 + search: (_sessionId, params) =>
673 + Effect.sync(() => {
674 + searchParams = params;
675 + return {
676 + success: true,
677 + error: null,
678 + results: params.queries.map((query, index) => ({
679 + index: index + 1,
680 + use_case: query.use_case ?? '',
681 + primary_tool_slugs:
682 + query.use_case === 'create issue'
683 + ? ['GITHUB_CREATE_ISSUE']
684 + : ['GMAIL_SEND_EMAIL'],
685 + related_tool_slugs: [],
686 + toolkits: query.use_case === 'create issue' ? ['github'] : ['gmail'],
687 + })),
688 + tool_schemas: {
689 + GMAIL_SEND_EMAIL: {
690 + tool_slug: 'GMAIL_SEND_EMAIL',
691 + toolkit: 'gmail',
692 + description: 'Sends an email',
693 + hasFullSchema: true,
694 + input_schema: { type: 'object', properties: {} },
695 + output_schema: { type: 'object', properties: {} },
696 + },
697 + GITHUB_CREATE_ISSUE: {
698 + tool_slug: 'GITHUB_CREATE_ISSUE',
699 + toolkit: 'github',
700 + description: 'Creates a GitHub issue',
701 + hasFullSchema: true,
702 + input_schema: { type: 'object', properties: {} },
703 + output_schema: { type: 'object', properties: {} },
704 + },
705 },
689 - GITHUB_CREATE_ISSUE: {
690 - tool_slug: 'GITHUB_CREATE_ISSUE',
691 - toolkit: 'github',
692 - description: 'Creates a GitHub issue',
693 - hasFullSchema: true,
694 - input_schema: { type: 'object', properties: {} },
695 - output_schema: { type: 'object', properties: {} },
706 + toolkit_connection_statuses: [],
707 + next_steps_guidance: [],
708 + session: {
709 + id: 'trs_test_session',
710 + generate_id: false,
711 + instructions: 'Reuse this session id for follow-up calls.',
712 },
697 - },
698 - toolkit_connection_statuses: [],
699 - next_steps_guidance: [],
700 - session: {
701 - id: 'trs_test_session',
702 - generate_id: false,
703 - instructions: 'Reuse this session id for follow-up calls.',
704 - },
705 - time_info: {
706 - current_time_utc: '2026-01-01T00:00:00.000Z',
707 - current_time_utc_epoch_seconds: 1767225600,
708 - message: 'UTC time',
709 - },
710 - };
711 - },
713 + time_info: {
714 + current_time_utc: '2026-01-01T00:00:00.000Z',
715 + current_time_utc_epoch_seconds: 1767225600,
716 + message: 'UTC time',
717 + },
718 + };
719 + }),
720 },
721 })
722 )(
@@ -734,49 +742,50 @@ describe('CLI: composio search', () => {
742 toolkitsData,
743 fixture: 'global-test-user-id',
744 toolRouter: {
737 - search: async (_sessionId, params) => ({
738 - success: true,
739 - error: null,
740 - results: [
741 - {
742 - index: 1,
743 - use_case: params.queries[0]?.use_case ?? '',
744 - primary_tool_slugs: ['GMAIL_SEND_EMAIL'],
745 - related_tool_slugs: [],
746 - toolkits: ['gmail'],
747 - recommended_plan_steps: ['Collect recipient details', 'Execute send action'],
745 + search: (_sessionId, params) =>
746 + Effect.succeed({
747 + success: true,
748 + error: null,
749 + results: [
750 + {
751 + index: 1,
752 + use_case: params.queries[0]?.use_case ?? '',
753 + primary_tool_slugs: ['GMAIL_SEND_EMAIL'],
754 + related_tool_slugs: [],
755 + toolkits: ['gmail'],
756 + recommended_plan_steps: ['Collect recipient details', 'Execute send action'],
757 + },
758 + ],
759 + tool_schemas: {
760 + GMAIL_SEND_EMAIL: {
761 + tool_slug: 'GMAIL_SEND_EMAIL',
762 + toolkit: 'gmail',
763 + description: 'Sends an email',
764 + hasFullSchema: true,
765 + input_schema: { type: 'object', properties: {} },
766 + output_schema: { type: 'object', properties: {} },
767 + },
768 },
749 - ],
750 - tool_schemas: {
751 - GMAIL_SEND_EMAIL: {
752 - tool_slug: 'GMAIL_SEND_EMAIL',
753 - toolkit: 'gmail',
754 - description: 'Sends an email',
755 - hasFullSchema: true,
756 - input_schema: { type: 'object', properties: {} },
757 - output_schema: { type: 'object', properties: {} },
769 + toolkit_connection_statuses: [
770 + {
771 + toolkit: 'gmail',
772 + description: 'gmail toolkit',
773 + has_active_connection: false,
774 + status_message: 'No active connection',
775 + },
776 + ],
777 + next_steps_guidance: ['Fallback guidance'],
778 + session: {
779 + id: 'trs_test_session',
780 + generate_id: false,
781 + instructions: 'Reuse this session id for follow-up calls.',
782 },
759 - },
760 - toolkit_connection_statuses: [
761 - {
762 - toolkit: 'gmail',
763 - description: 'gmail toolkit',
764 - has_active_connection: false,
765 - status_message: 'No active connection',
783 + time_info: {
784 + current_time_utc: '2026-01-01T00:00:00.000Z',
785 + current_time_utc_epoch_seconds: 1767225600,
786 + message: 'UTC time',
787 },
767 - ],
768 - next_steps_guidance: ['Fallback guidance'],
769 - session: {
770 - id: 'trs_test_session',
771 - generate_id: false,
772 - instructions: 'Reuse this session id for follow-up calls.',
773 - },
774 - time_info: {
775 - current_time_utc: '2026-01-01T00:00:00.000Z',
776 - current_time_utc_epoch_seconds: 1767225600,
777 - message: 'UTC time',
778 - },
779 - }),
788 + }),
789 },
790 })
791 )('[Given] search response with recommended plan [Then] it prints plan and execute hint', it => {
@@ -814,22 +823,23 @@ describe('CLI: composio search', () => {
823 TestLive({
824 ...testLiveOptions,
825 toolRouter: {
817 - create: async params => {
818 - createParams = params;
819 - return {
820 - session_id: 'trs_test_session',
821 - config: {
822 - user_id: params.user_id,
823 - execute: {},
824 - search: {},
825 - preload: { tools: [] },
826 - instant: false,
827 - },
828 - config_version: 1,
829 - mcp: { type: 'http', url: 'https://mcp.test.composio.dev' },
830 - tool_router_tools: ['COMPOSIO_SEARCH_TOOLS'],
831 - };
832 - },
826 + create: params =>
827 + Effect.sync(() => {
828 + createParams = params;
829 + return {
830 + session_id: 'trs_test_session',
831 + config: {
832 + user_id: params.user_id,
833 + execute: {},
834 + search: {},
835 + preload: { tools: [] },
836 + instant: false,
837 + },
838 + config_version: 1,
839 + mcp: { type: 'http', url: 'https://mcp.test.composio.dev' },
840 + tool_router_tools: ['COMPOSIO_SEARCH_TOOLS'],
841 + };
842 + }),
843 },
844 })
845 )('[Given] consumer search [Then] it uses the resolved consumer user id', it => {
ts/packages/cli/test/src/commands/triggers/triggers.info.cmd.test.ts
+7
@@ -124,6 +124,13 @@ describe('CLI: composio dev triggers info', () => {
124
125 expect(output).toContain('not found');
126 expect(output).toContain('composio dev triggers list "<toolkit>"');
127 + // Once plainly for a captured stderr, once through the decorated log.
128 + expect(lines).toEqual([
129 + 'Trigger "NONEXISTENT_TRIGGER" not found.',
130 + 'Browse available trigger types:\n> composio dev triggers list "<toolkit>"',
131 + 'Trigger "NONEXISTENT_TRIGGER" not found.',
132 + 'Browse available trigger types:\n> composio dev triggers list "<toolkit>"',
133 + ]);
134 expect(process.exitCode).toBe(1);
135 })
136 );
ts/packages/cli/test/src/effect-errors/extract-error-details.test.ts
+139
@@ -1,3 +1,9 @@
1 +import {
2 + APIConnectionError as ClientAPIConnectionError,
3 + APIConnectionTimeoutError as ClientAPIConnectionTimeoutError,
4 + DecodeError as ClientDecodeError,
5 + NotFoundError as ClientNotFoundError,
6 +} from '@composio/client/effect';
7 import { describe, expect, it } from 'vitest';
8 import { Data } from 'effect';
9 import { extractErrorDetails } from 'src/effect-errors/logic/errors/extract-error-details';
@@ -62,3 +68,136 @@ describe('extractErrorDetails', () => {
68 });
69 });
70 });
71 +
72 +const notFoundEnvelope = {
73 + error: {
74 + message: 'Toolkit not found',
75 + code: 1803,
76 + slug: 'Toolkit_NotFound',
77 + status: 404,
78 + request_id: 'req_body',
79 + suggested_fix: 'Check the toolkit slug',
80 + },
81 +};
82 +
83 +const notFoundDetail =
84 + '404 {"error":{"message":"Toolkit not found","code":1803,"slug":"Toolkit_NotFound","status":404,"request_id":"req_body","suggested_fix":"Check the toolkit slug"}}';
85 +
86 +describe('extractErrorDetails for an uncaught API failure', () => {
87 + describe('raised as a client error', () => {
88 + const url = 'https://backend.composio.dev/api/v3.1/toolkits/{slug}';
89 +
90 + it('shows the same cause detail for a 404, under the client tag', () => {
91 + const error = new ClientNotFoundError({
92 + message: notFoundDetail,
93 + method: 'GET',
94 + url,
95 + status: 404,
96 + requestId: 'req_header',
97 + details: notFoundEnvelope.error,
98 + body: notFoundEnvelope,
99 + });
100 +
101 + expect(extractErrorDetails(error)).toStrictEqual({
102 + isPlainString: false,
103 + type: '@composio/client/NotFoundError',
104 + message: `\nCaused by: ${notFoundDetail}`,
105 + });
106 + });
107 +
108 + it('shows the transport reason of a connection failure', () => {
109 + const error = new ClientAPIConnectionError({
110 + message: 'Connection error.',
111 + method: 'GET',
112 + url,
113 + reason: 'TransportError',
114 + description: 'fetch failed: connect ECONNREFUSED 127.0.0.1:1',
115 + });
116 +
117 + expect(extractErrorDetails(error).message).toBe(
118 + '\nCaused by: fetch failed: connect ECONNREFUSED 127.0.0.1:1'
119 + );
120 + });
121 +
122 + it('shows the message of a connection failure the transport did not describe', () => {
123 + const error = new ClientAPIConnectionError({
124 + message: 'Too many redirects.',
125 + method: 'GET',
126 + url,
127 + reason: 'TooManyRedirects',
128 + description: undefined,
129 + });
130 +
131 + expect(extractErrorDetails(error).message).toBe('\nCaused by: Too many redirects.');
132 + });
133 +
134 + it('shows a timeout', () => {
135 + const error = new ClientAPIConnectionTimeoutError({
136 + message: 'Request timed out.',
137 + method: 'GET',
138 + url,
139 + });
140 +
141 + expect(extractErrorDetails(error).message).toBe('\nCaused by: Request timed out.');
142 + });
143 +
144 + it('names the operation and request id of a decode failure and suggests an upgrade', () => {
145 + const error = new ClientDecodeError({
146 + message: "The response body does not match the schema of 'toolkits.retrieve'.",
147 + method: 'GET',
148 + url,
149 + status: 200,
150 + requestId: 'req_decode',
151 + operation: 'toolkits.retrieve',
152 + issues: [{ path: ['meta', 'categories'], kind: 'InvalidType' }],
153 + });
154 +
155 + expect(extractErrorDetails(error)).toStrictEqual({
156 + isPlainString: false,
157 + type: '@composio/client/DecodeError',
158 + message:
159 + "The API response for 'toolkits.retrieve' is not in the shape this version of the CLI expects (request id: req_decode).\nUpgrade the CLI, then retry:\n> composio upgrade",
160 + });
161 + });
162 + });
163 +
164 + describe('raised as a command error wrapping a client error', () => {
165 + const url = 'https://backend.composio.dev/api/v3.1/internal/action_execution/logs';
166 +
167 + it('shows the transport reason of a connection failure', () => {
168 + const error = new RequestError({
169 + message: 'Failed to fetch tool logs.',
170 + cause: new ClientAPIConnectionError({
171 + message: 'Connection error.',
172 + method: 'POST',
173 + url,
174 + reason: 'TransportError',
175 + description: 'fetch failed: connect ECONNREFUSED 127.0.0.1:1',
176 + }),
177 + });
178 +
179 + expect(extractErrorDetails(error).message).toBe(
180 + 'Failed to fetch tool logs.\nCaused by: fetch failed: connect ECONNREFUSED 127.0.0.1:1'
181 + );
182 + });
183 +
184 + it('names the operation and request id of a decode failure and suggests an upgrade', () => {
185 + const error = new RequestError({
186 + message: 'Failed to fetch tool logs.',
187 + cause: new ClientDecodeError({
188 + message: "The response body does not match the schema of 'logs.tools.list'.",
189 + method: 'POST',
190 + url,
191 + status: 200,
192 + requestId: 'req_logs',
193 + operation: 'logs.tools.list',
194 + issues: [{ path: ['data', 0, 'status'], kind: 'InvalidValue' }],
195 + }),
196 + });
197 +
198 + expect(extractErrorDetails(error).message).toBe(
199 + "Failed to fetch tool logs.\nCaused by: The API response for 'logs.tools.list' is not in the shape this version of the CLI expects (request id: req_logs).\nUpgrade the CLI, then retry:\n> composio upgrade"
200 + );
201 + });
202 + });
203 +});
ts/packages/cli/test/src/effects/handle-http-error.test.ts new
+201
@@ -0,0 +1,201 @@
1 +import {
2 + APIConnectionError as ClientAPIConnectionError,
3 + APIConnectionTimeoutError as ClientAPIConnectionTimeoutError,
4 + BadRequestError as ClientBadRequestError,
5 + ConfigurationError as ClientConfigurationError,
6 + DecodeError as ClientDecodeError,
7 +} from '@composio/client/effect';
8 +import { describe, expect, it } from '@effect/vitest';
9 +import { Effect } from 'effect';
10 +import { afterEach } from 'vitest';
11 +import { catchClientApiError, handleClientApiError } from 'src/effects/handle-http-error';
12 +import { TerminalUI } from 'src/services/terminal-ui';
13 +import { terminalUITestImpl } from 'test/__utils__/services/terminal-ui-test';
14 +
15 +const envelope = {
16 + error: {
17 + message: 'Auth config "ac_missing" was not found',
18 + code: 1803,
19 + slug: 'AuthConfig_NotFound',
20 + status: 400,
21 + request_id: 'req_body',
22 + suggested_fix: 'Check the auth config id',
23 + },
24 +};
25 +
26 +const url = 'https://backend.composio.dev/api/v3.1/auth_configs/{nanoid}';
27 +
28 +const clientStatusError = new ClientBadRequestError({
29 + message: `400 ${JSON.stringify(envelope)}`,
30 + method: 'GET',
31 + url,
32 + status: 400,
33 + requestId: 'req_header',
34 + details: envelope.error,
35 + body: envelope,
36 +});
37 +
38 +const clientDecodeError = new ClientDecodeError({
39 + message: "The response body does not match the schema of 'authConfigs.retrieve'.",
40 + method: 'GET',
41 + url,
42 + status: 200,
43 + requestId: 'req_decode',
44 + operation: 'authConfigs.retrieve',
45 + issues: [{ path: ['toolkit', 'slug'], kind: 'InvalidType' }],
46 +});
47 +
48 +const options = {
49 + fallbackMessage: 'Failed to fetch auth config "ac_missing".',
50 + hint: 'Browse available auth configs:\n> composio dev auth-configs list',
51 + fallbackValue: 'fallback' as const,
52 +};
53 +
54 +// A TerminalUI whose stderr is not a TTY, recording every line the handler
55 +// writes together with the channel it went to.
56 +const recordingUI = () => {
57 + const lines: Array<string> = [];
58 + const record = (channel: string) => (message: string) =>
59 + Effect.sync(() => {
60 + lines.push(`${channel}: ${message}`);
61 + });
62 + const ui = TerminalUI.of({
63 + ...terminalUITestImpl,
64 + error: record('stderr'),
65 + log: { ...terminalUITestImpl.log, error: record('log.error'), step: record('log.step') },
66 + });
67 + return { ui, lines };
68 +};
69 +
70 +describe('handleClientApiError', () => {
71 + afterEach(() => {
72 + process.exitCode = undefined;
73 + });
74 +
75 + it.effect('prints the envelope message and the suggested fix, and fails the process', () =>
76 + Effect.gen(function* () {
77 + const { ui, lines } = recordingUI();
78 +
79 + const result = yield* handleClientApiError(ui, options)(clientStatusError);
80 +
81 + expect(result).toBe('fallback');
82 + expect(lines).toStrictEqual([
83 + 'stderr: Auth config "ac_missing" was not found',
84 + 'stderr: Browse available auth configs:\n> composio dev auth-configs list',
85 + 'log.error: Auth config "ac_missing" was not found',
86 + 'log.step: Check the auth config id',
87 + 'log.step: Browse available auth configs:\n> composio dev auth-configs list',
88 + ]);
89 + expect(process.exitCode).toBe(1);
90 + })
91 + );
92 +
93 + it.effect.each([
94 + new ClientAPIConnectionError({
95 + message: 'Connection error.',
96 + method: 'GET',
97 + url,
98 + reason: 'TransportError',
99 + description: 'fetch failed',
100 + }),
101 + new ClientAPIConnectionTimeoutError({ message: 'Request timed out.', method: 'GET', url }),
102 + ])('prints the fallback message for $_tag', error =>
103 + Effect.gen(function* () {
104 + const { ui, lines } = recordingUI();
105 +
106 + const result = yield* handleClientApiError(ui, options)(error);
107 +
108 + expect(result).toBe('fallback');
109 + expect(lines).toStrictEqual([
110 + 'stderr: Failed to fetch auth config "ac_missing".',
111 + 'stderr: Browse available auth configs:\n> composio dev auth-configs list',
112 + 'log.error: Failed to fetch auth config "ac_missing".',
113 + 'log.step: Browse available auth configs:\n> composio dev auth-configs list',
114 + ]);
115 + expect(process.exitCode).toBe(1);
116 + })
117 + );
118 +
119 + it.effect('names the operation and request id of a decode failure and suggests an upgrade', () =>
120 + Effect.gen(function* () {
121 + const { ui, lines } = recordingUI();
122 +
123 + const result = yield* handleClientApiError(ui, {
124 + ...options,
125 + searchForSuggestions: () =>
126 + Effect.succeed([{ label: 'ac_similar', command: '> composio dev auth-configs info' }]),
127 + })(clientDecodeError);
128 +
129 + expect(result).toBe('fallback');
130 + expect(lines).toStrictEqual([
131 + "stderr: The API response for 'authConfigs.retrieve' is not in the shape this version of the CLI expects (request id: req_decode).",
132 + 'stderr: Upgrade the CLI, then retry:\n> composio upgrade',
133 + "log.error: The API response for 'authConfigs.retrieve' is not in the shape this version of the CLI expects (request id: req_decode).",
134 + 'log.step: Upgrade the CLI, then retry:\n> composio upgrade',
135 + ]);
136 + expect(process.exitCode).toBe(1);
137 + })
138 + );
139 +
140 + it.effect('replaces the hint with suggestions when the search finds some', () =>
141 + Effect.gen(function* () {
142 + const { ui, lines } = recordingUI();
143 +
144 + yield* handleClientApiError(ui, {
145 + ...options,
146 + searchForSuggestions: () =>
147 + Effect.succeed([
148 + { label: 'ac_similar', command: '> composio dev auth-configs info "ac_similar"' },
149 + ]),
150 + })(clientStatusError);
151 +
152 + expect(lines.at(-1)).toBe(
153 + 'log.step: Did you mean?\n ac_similar\n\n> composio dev auth-configs info "ac_similar"'
154 + );
155 + })
156 + );
157 +});
158 +
159 +describe('catchClientApiError', () => {
160 + afterEach(() => {
161 + process.exitCode = undefined;
162 + });
163 +
164 + it.effect.each([
165 + clientStatusError,
166 + clientDecodeError,
167 + new ClientAPIConnectionError({
168 + message: 'Connection error.',
169 + method: 'GET',
170 + url,
171 + reason: 'TransportError',
172 + description: 'fetch failed',
173 + }),
174 + new ClientAPIConnectionTimeoutError({ message: 'Request timed out.', method: 'GET', url }),
175 + ])('recovers from $_tag with the fallback value', error =>
176 + Effect.gen(function* () {
177 + const { ui, lines } = recordingUI();
178 +
179 + const result = yield* Effect.fail(error).pipe(catchClientApiError(ui, options));
180 +
181 + expect(result).toBe('fallback');
182 + expect(lines).not.toStrictEqual([]);
183 + expect(process.exitCode).toBe(1);
184 + })
185 + );
186 +
187 + it.effect('leaves other failures alone', () =>
188 + Effect.gen(function* () {
189 + const { ui, lines } = recordingUI();
190 + const error = new ClientConfigurationError({ message: 'No credential.' });
191 +
192 + const failure = yield* Effect.fail<ClientConfigurationError | ClientBadRequestError>(
193 + error
194 + ).pipe(catchClientApiError(ui, options), Effect.flip);
195 +
196 + expect(failure).toBe(error);
197 + expect(lines).toStrictEqual([]);
198 + expect(process.exitCode).toBeUndefined();
199 + })
200 + );
201 +});
ts/packages/cli/test/src/effects/toolkit-from-tool-slug.test.ts
+12 -2
@@ -4,9 +4,9 @@ import { ConfigProvider, DateTime, Deferred, Effect, FileSystem, Layer, Schedule
4 import * as tempy from 'tempy';
5 import { toolkitFromToolSlug } from 'src/effects/toolkit-from-tool-slug';
6 import type { Toolkits } from 'src/models/toolkits';
7 +import { InternalServerError } from '@composio/client/effect';
8 import {
9 ComposioToolkitsRepository,
9 - HttpServerError,
10 type ToolkitProjectScope,
11 } from 'src/services/composio-clients';
12 import { KNOWN_TOOLKIT_SLUGS_FILE } from 'src/services/known-toolkit-slugs';
@@ -32,7 +32,17 @@ const UNRELEASED_TOOLKIT = 'acme_analytics';
32 const CUSTOM_TOOLKIT = 'custom_grain';
33
34 const failingFetch = () =>
35 - Effect.fail(new HttpServerError({ cause: 'catalog unavailable', status: 503 }));
35 + Effect.fail(
36 + new InternalServerError({
37 + message: 'catalog unavailable',
38 + method: 'GET',
39 + url: 'https://backend.composio.dev/api/v3.1/toolkits',
40 + status: 503,
41 + requestId: undefined,
42 + details: undefined,
43 + body: undefined,
44 + })
45 + );
46
47 /**
48 * A learned-slugs file recorded `daysAgo` days ago. Anything under a week old
ts/packages/cli/test/src/services/composio-client-singleton.test.ts
+244 -65
@@ -4,8 +4,10 @@ import * as FileSystem from 'effect/FileSystem';
4 import * as Path from 'effect/Path';
5 import * as BunFileSystem from '@effect/platform-bun/BunFileSystem';
6 import * as BunPath from '@effect/platform-bun/BunPath';
7 -import { ConfigProvider, Effect, Layer } from 'effect';
7 +import { ConfigProvider, Effect, Layer, Logger } from 'effect';
8 +import { FetchHttpClient } from 'effect/http';
9 import * as tempy from 'tempy';
10 +import type { ComposioClientShape } from '@composio/client/effect';
11 import { ComposioClientSingleton } from 'src/services/composio-clients';
12 import { APP_VERSION } from 'src/constants';
13 import { defaultNodeOs, NodeOs } from 'src/services/node-os';
@@ -78,6 +80,11 @@ const writeCliSessionCache = (
80 );
81 });
82
83 +// The canned responses here are not a tools page, so the call opts out of
84 +// client decoding.
85 +const listTools = (client: ComposioClientShape) =>
86 + client.tools.list({ limit: 1, toolkit_versions: 'latest' }, { decode: false });
87 +
88 describe('ComposioClientSingleton headers', () => {
89 afterEach(() => {
90 vi.restoreAllMocks();
@@ -96,12 +103,7 @@ describe('ComposioClientSingleton headers', () => {
103 return Effect.gen(function* () {
104 const clientSingleton = yield* ComposioClientSingleton;
105 const client = yield* clientSingleton.get();
99 - yield* Effect.promise(() =>
100 - client.tools
101 - .list({ limit: 1, toolkit_versions: 'latest' })
102 - .then(() => undefined)
103 - .catch(() => undefined)
104 - );
106 + yield* listTools(client);
107
108 expect(fetchSpy).toHaveBeenCalledOnce();
109 const [, init] = fetchSpy.mock.calls[0]!;
@@ -148,12 +150,7 @@ describe('ComposioClientSingleton headers', () => {
150 });
151 const clientSingleton = yield* ComposioClientSingleton;
152 const client = yield* clientSingleton.get();
151 - yield* Effect.promise(() =>
152 - client.tools
153 - .list({ limit: 1, toolkit_versions: 'latest' })
154 - .then(() => undefined)
155 - .catch(() => undefined)
156 - );
153 + yield* listTools(client);
154
155 const [, init] = fetchSpy.mock.calls[0]!;
156 const headers = new Headers((init as RequestInit).headers);
@@ -182,12 +179,7 @@ describe('ComposioClientSingleton headers', () => {
179 });
180 const clientSingleton = yield* ComposioClientSingleton;
181 const client = yield* clientSingleton.get();
185 - yield* Effect.promise(() =>
186 - client.tools
187 - .list({ limit: 1, toolkit_versions: 'latest' })
188 - .then(() => undefined)
189 - .catch(() => undefined)
190 - );
182 + yield* listTools(client);
183
184 const [, init] = fetchSpy.mock.calls[0]!;
185 const headers = new Headers((init as RequestInit).headers);
@@ -210,12 +202,7 @@ describe('ComposioClientSingleton headers', () => {
202 return Effect.gen(function* () {
203 const clientSingleton = yield* ComposioClientSingleton;
204 const client = yield* clientSingleton.get();
213 - yield* Effect.promise(() =>
214 - client.tools
215 - .list({ limit: 1, toolkit_versions: 'latest' })
216 - .then(() => undefined)
217 - .catch(() => undefined)
218 - );
205 + yield* listTools(client);
206
207 expect(fetchSpy).toHaveBeenCalledOnce();
208 const [, init] = fetchSpy.mock.calls[0]!;
@@ -246,12 +233,7 @@ describe('ComposioClientSingleton headers', () => {
233 return Effect.gen(function* () {
234 const clientSingleton = yield* ComposioClientSingleton;
235 const client = yield* clientSingleton.get();
249 - yield* Effect.promise(() =>
250 - client.tools
251 - .list({ limit: 1, toolkit_versions: 'latest' })
252 - .then(() => undefined)
253 - .catch(() => undefined)
254 - );
236 + yield* listTools(client);
237
238 const [, init] = fetchSpy.mock.calls[0]!;
239 const headers = new Headers((init as RequestInit).headers);
@@ -281,12 +263,7 @@ describe('ComposioClientSingleton headers', () => {
263 const client = yield* clientSingleton.get();
264 // `auth.session.retrieveInfo` is an operation where the client would
265 // attach its own `userApiKey` credential; the caller-placed header wins.
284 - yield* Effect.promise(() =>
285 - client.auth.session
286 - .retrieveInfo()
287 - .then(() => undefined)
288 - .catch(() => undefined)
289 - );
266 + yield* client.auth.session.retrieveInfo({ decode: false });
267
268 const [input, init] = fetchSpy.mock.calls[0]!;
269 expect(String(input)).toContain('/api/v3.1/auth/session/info');
@@ -311,7 +288,7 @@ describe('ComposioClientSingleton headers', () => {
288 return Effect.gen(function* () {
289 const clientSingleton = yield* ComposioClientSingleton;
290 const client = yield* clientSingleton.get();
314 - yield* Effect.promise(() => client.tools.list({ limit: 1, toolkit_versions: 'latest' }));
291 + yield* listTools(client);
292
293 expect(fetchSpy).toHaveBeenCalledOnce();
294 const [input, init] = fetchSpy.mock.calls[0]!;
@@ -324,27 +301,6 @@ describe('ComposioClientSingleton headers', () => {
301 );
302 });
303
327 - it.effect('caches one client per key, org, and project', () => {
328 - const homedir = tempy.temporaryDirectory();
329 - const configMap = new Map([['COMPOSIO_BASE_URL', 'https://backend.composio.dev']]);
330 -
331 - return Effect.gen(function* () {
332 - const clientSingleton = yield* ComposioClientSingleton;
333 - const scope = { userApiKey: 'uak_a', orgId: 'org_a', projectId: 'proj_a' };
334 -
335 - const first = yield* clientSingleton.getFor(scope);
336 - const second = yield* clientSingleton.getFor(scope);
337 - const otherProject = yield* clientSingleton.getFor({ ...scope, projectId: 'proj_b' });
338 -
339 - expect(second).toBe(first);
340 - expect(otherProject).not.toBe(first);
341 - }).pipe(
342 - Effect.provide(
343 - Layer.provide(ComposioClientSingleton.Default, withConfigLayer(configMap, homedir))
344 - )
345 - );
346 - });
347 -
304 it.effect('counts requests and response bytes, with or without Content-Length', () => {
305 const homedir = tempy.temporaryDirectory();
306 const configMap = new Map([
@@ -376,14 +332,11 @@ describe('ComposioClientSingleton headers', () => {
332 .mockResolvedValueOnce(sized(10))
333 .mockResolvedValueOnce(sized(20))
334 .mockResolvedValueOnce(unsized());
379 - const list = () =>
380 - Effect.promise(() => client.tools.list({ limit: 1, toolkit_versions: 'latest' }));
381 -
382 - yield* list();
383 - yield* list();
335 + yield* listTools(client);
336 + yield* listTools(client);
337 expect(yield* clientSingleton.getMetrics()).toEqual({ requests: 2, byteSize: 30 });
338
386 - yield* list();
339 + yield* listTools(client);
340 expect(yield* clientSingleton.getMetrics()).toEqual({
341 requests: 3,
342 byteSize: 30 + '{"items":[]}'.length,
@@ -395,3 +348,229 @@ describe('ComposioClientSingleton headers', () => {
348 );
349 });
350 });
351 +
352 +describe('ComposioClientSingleton client', () => {
353 + afterEach(() => {
354 + vi.restoreAllMocks();
355 + vi.unstubAllEnvs();
356 + });
357 +
358 + const baseConfig = (entries: ReadonlyArray<readonly [string, string]> = []) =>
359 + new Map([['COMPOSIO_BASE_URL', 'https://backend.composio.dev'], ...entries]);
360 +
361 + const singletonLayer = (configMap: Map<string, string>) =>
362 + Layer.provide(
363 + ComposioClientSingleton.Default,
364 + withConfigLayer(configMap, tempy.temporaryDirectory())
365 + );
366 +
367 + const sentHeaders = (call: Parameters<typeof globalThis.fetch>) =>
368 + new Headers((call[1] as RequestInit).headers);
369 +
370 + it.effect('sends the scope credentials and the provenance headers, never x-api-key', () => {
371 + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(okResponse());
372 +
373 + return Effect.gen(function* () {
374 + const clientSingleton = yield* ComposioClientSingleton;
375 + const client = yield* clientSingleton.getFor({
376 + userApiKey: 'uak_scope',
377 + orgId: 'org_a',
378 + projectId: 'proj_a',
379 + });
380 + yield* listTools(client);
381 +
382 + expect(fetchSpy).toHaveBeenCalledOnce();
383 + const headers = sentHeaders(fetchSpy.mock.calls[0]!);
384 +
385 + expect(headers.get('x-user-api-key')).toBe('uak_scope');
386 + expect(headers.get('x-org-id')).toBe('org_a');
387 + expect(headers.get('x-project-id')).toBe('proj_a');
388 + expect(headers.has('x-api-key')).toBe(false);
389 + expect(headers.get('x-framework')).toBe('cli');
390 + expect(headers.get('x-source')).toBe('CLI');
391 + expect(headers.get('x-runtime')).toBe('NODEJS');
392 + expect(headers.get('x-client-runtime')).toBe('nodejs');
393 + expect(headers.get('x-runtime-version')).toBe(process.versions.node);
394 + expect(headers.get('x-sdk-version')).toBe(APP_VERSION);
395 + expect(headers.get('x-client-provenance')).toBe('@composio/cli');
396 + expect(headers.get('x-client-version')).toBe(APP_VERSION);
397 + expect(headers.get('x-client-language')).toBe('typescript');
398 + }).pipe(Effect.provide(singletonLayer(baseConfig())));
399 + });
400 +
401 + it.effect('omits the org header when the scope has no project', () => {
402 + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(okResponse());
403 +
404 + return Effect.gen(function* () {
405 + const clientSingleton = yield* ComposioClientSingleton;
406 + const client = yield* clientSingleton.getFor({
407 + userApiKey: 'uak_scope',
408 + orgId: 'org_a',
409 + });
410 + yield* listTools(client);
411 +
412 + const headers = sentHeaders(fetchSpy.mock.calls[0]!);
413 + expect(headers.get('x-user-api-key')).toBe('uak_scope');
414 + expect(headers.has('x-org-id')).toBe(false);
415 + expect(headers.has('x-project-id')).toBe(false);
416 + }).pipe(Effect.provide(singletonLayer(baseConfig())));
417 + });
418 +
419 + it.effect('caches one client per key, org, and project', () =>
420 + Effect.gen(function* () {
421 + const clientSingleton = yield* ComposioClientSingleton;
422 + const scope = { userApiKey: 'uak_a', orgId: 'org_a', projectId: 'proj_a' };
423 +
424 + const first = yield* clientSingleton.getFor(scope);
425 + const second = yield* clientSingleton.getFor(scope);
426 + const otherProject = yield* clientSingleton.getFor({ ...scope, projectId: 'proj_b' });
427 +
428 + expect(second).toBe(first);
429 + expect(otherProject).not.toBe(first);
430 + }).pipe(Effect.provide(singletonLayer(baseConfig())))
431 + );
432 +
433 + it.effect('ignores ambient COMPOSIO_API_KEY and COMPOSIO_BASE_URL', () => {
434 + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(okResponse());
435 + vi.stubEnv('COMPOSIO_API_KEY', 'ak_ambient');
436 + vi.stubEnv('COMPOSIO_BASE_URL', 'https://ambient.invalid');
437 +
438 + return Effect.gen(function* () {
439 + const clientSingleton = yield* ComposioClientSingleton;
440 + const client = yield* clientSingleton.getFor({ userApiKey: 'uak_scope' });
441 + yield* listTools(client);
442 +
443 + const call = fetchSpy.mock.calls[0]!;
444 + expect(String(call[0])).toContain('https://backend.composio.dev/');
445 + const headers = sentHeaders(call);
446 + expect(headers.get('x-user-api-key')).toBe('uak_scope');
447 + expect(headers.has('x-api-key')).toBe(false);
448 + }).pipe(Effect.provide(singletonLayer(baseConfig())));
449 + });
450 +
451 + it.effect('resolves globalThis.fetch on every request', () => {
452 + const firstSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(okResponse());
453 +
454 + return Effect.gen(function* () {
455 + const clientSingleton = yield* ComposioClientSingleton;
456 + const client = yield* clientSingleton.get();
457 + yield* listTools(client);
458 + expect(firstSpy).toHaveBeenCalledOnce();
459 +
460 + firstSpy.mockRestore();
461 + const secondSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(okResponse());
462 + yield* listTools(client);
463 +
464 + expect(secondSpy).toHaveBeenCalledOnce();
465 + }).pipe(Effect.provide(singletonLayer(baseConfig([['COMPOSIO_USER_API_KEY', 'uak_late']]))));
466 + });
467 +
468 + // Live clock: the retry backoff is a real sleep, cut to nothing by the
469 + // `retry-after-ms` response header.
470 + it.live('counts every attempt of a retried call', () => {
471 + vi.spyOn(globalThis, 'fetch')
472 + .mockResolvedValueOnce(
473 + new Response('{}', {
474 + status: 500,
475 + headers: { 'Content-Type': 'application/json', 'retry-after-ms': '0' },
476 + })
477 + )
478 + .mockResolvedValueOnce(
479 + new Response(JSON.stringify(['GITHUB_CREATE_ISSUE']), {
480 + status: 200,
481 + headers: { 'Content-Type': 'application/json' },
482 + })
483 + );
484 +
485 + return Effect.gen(function* () {
486 + const clientSingleton = yield* ComposioClientSingleton;
487 + const client = yield* clientSingleton.get();
488 +
489 + expect(yield* client.tools.retrieveEnum({ decode: false })).toEqual(['GITHUB_CREATE_ISSUE']);
490 + expect((yield* clientSingleton.getMetrics()).requests).toBe(2);
491 + }).pipe(Effect.provide(singletonLayer(baseConfig([['COMPOSIO_USER_API_KEY', 'uak_retry']]))));
492 + });
493 +
494 + it.effect('counts requests when the application already provides a fetch transport', () => {
495 + vi.spyOn(globalThis, 'fetch').mockResolvedValue(okResponse());
496 +
497 + return Effect.gen(function* () {
498 + const clientSingleton = yield* ComposioClientSingleton;
499 + const client = yield* clientSingleton.get();
500 + yield* listTools(client);
501 +
502 + expect((yield* clientSingleton.getMetrics()).requests).toBe(1);
503 + }).pipe(
504 + Effect.provide(
505 + Layer.provide(
506 + ComposioClientSingleton.Default,
507 + Layer.mergeAll(
508 + withConfigLayer(
509 + baseConfig([['COMPOSIO_USER_API_KEY', 'uak_metrics']]),
510 + tempy.temporaryDirectory()
511 + ),
512 + FetchHttpClient.layer
513 + )
514 + )
515 + )
516 + );
517 + });
518 +
519 + it.effect('logs nothing for a response that announces a deprecation', () => {
520 + vi.spyOn(globalThis, 'fetch').mockResolvedValue(
521 + new Response(JSON.stringify({ data: [] }), {
522 + status: 200,
523 + headers: {
524 + 'Content-Type': 'application/json',
525 + Deprecation: 'true',
526 + Sunset: 'Wed, 31 Dec 2027 23:59:59 GMT',
527 + Link: '<https://docs.composio.dev/migration>; rel="deprecation"',
528 + },
529 + })
530 + );
531 + const records: Array<unknown> = [];
532 + const capturingLogger = Logger.layer([
533 + Logger.make<unknown, void>(({ message }) => {
534 + records.push(message);
535 + }),
536 + ]);
537 +
538 + return Effect.gen(function* () {
539 + const clientSingleton = yield* ComposioClientSingleton;
540 + const client = yield* clientSingleton.get();
541 + yield* listTools(client);
542 +
543 + expect(records).toEqual([]);
544 + }).pipe(
545 + Effect.provide(
546 + Layer.merge(
547 + singletonLayer(baseConfig([['COMPOSIO_USER_API_KEY', 'uak_quiet']])),
548 + capturingLogger
549 + )
550 + )
551 + );
552 + });
553 +
554 + it.effect('rejects an undecodable typed call before sending it', () => {
555 + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(okResponse());
556 +
557 + return Effect.gen(function* () {
558 + const clientSingleton = yield* ComposioClientSingleton;
559 + const client = yield* clientSingleton.get();
560 + // No opt-out, and `toolkits.list` has no entry in the CLI's loader table.
561 + const error = yield* Effect.flip(client.toolkits.list({ limit: 1 }));
562 +
563 + expect(error._tag).toBe('@composio/client/ConfigurationError');
564 + expect(fetchSpy).not.toHaveBeenCalled();
565 + }).pipe(Effect.provide(singletonLayer(baseConfig([['COMPOSIO_USER_API_KEY', 'uak_strict']]))));
566 + });
567 +
568 + it.effect('reports an invalid base URL as a configuration error', () =>
569 + Effect.gen(function* () {
570 + const clientSingleton = yield* ComposioClientSingleton;
571 + const error = yield* Effect.flip(clientSingleton.getFor({ userApiKey: 'uak_a' }));
572 +
573 + expect(error._tag).toBe('services/ComposioClientConfigurationError');
574 + }).pipe(Effect.provide(singletonLayer(new Map([['COMPOSIO_BASE_URL', 'not a url']]))))
575 + );
576 +});
ts/packages/cli/test/src/services/composio-clients-cached.test.ts
+14 -3
@@ -1,9 +1,9 @@
1 import { describe, expect, it, vi } from '@effect/vitest';
2 import { ConfigProvider, DateTime, Effect, Layer } from 'effect';
3 import * as tempy from 'tempy';
4 +import { InternalServerError } from '@composio/client/effect';
5 import {
6 ComposioToolkitsRepository,
6 - HttpServerError,
7 type ToolkitProjectScope,
8 } from 'src/services/composio-clients';
9 import * as FileSystem from 'effect/FileSystem';
@@ -23,6 +23,17 @@ import {
23
24 const testToolkits: Toolkits = [makeToolkitFixture('github'), makeToolkitFixture('gmail')];
25
26 +const serviceUnavailable = (message: string) =>
27 + new InternalServerError({
28 + message,
29 + method: 'GET',
30 + url: 'https://backend.composio.dev/api/v3.1/toolkits',
31 + status: 503,
32 + requestId: undefined,
33 + details: undefined,
34 + body: undefined,
35 + });
36 +
37 /**
38 * Cached repository over a counting stub, with the cache directory pointed at a
39 * fresh temp dir so nothing leaks between tests or into the developer's
@@ -111,7 +122,7 @@ describe('ComposioToolkitsRepositoryCached', () => {
122
123 it.effect('surfaces a failed fetch once, and does not retry it', () =>
124 withCountingRepository(
114 - () => Effect.fail(new HttpServerError({ cause: 'network down', status: 503 })),
125 + () => Effect.fail(serviceUnavailable('network down')),
126 ({ calls }) =>
127 Effect.gen(function* () {
128 const repository = yield* ComposioToolkitsRepository;
@@ -192,7 +203,7 @@ describe('ComposioToolkitsRepositoryCached', () => {
203 expect(projectCalls()).toBe(1);
204 }),
205 [],
195 - () => Effect.fail(new HttpServerError({ cause: 'network down', status: 503 }))
206 + () => Effect.fail(serviceUnavailable('network down'))
207 )
208 );
209
ts/packages/cli/test/src/services/composio-clients.test.ts
+194 -35
@@ -1,4 +1,4 @@
1 -import { afterEach, describe, expect, it } from '@effect/vitest';
1 +import { afterEach, assert, describe, expect, it } from '@effect/vitest';
2 import { vi } from 'vitest';
3 import * as BunFileSystem from '@effect/platform-bun/BunFileSystem';
4 import * as BunPath from '@effect/platform-bun/BunPath';
@@ -6,18 +6,17 @@ import { ConfigProvider, Effect, Fiber, Layer } from 'effect';
6 import * as tempy from 'tempy';
7 import {
8 AmbiguousDeveloperProjectNameError,
9 - ComposioClientSingleton,
10 - ComposioToolkitsRepository,
9 createProjectApiKey,
10 findDeveloperProjectByName,
11 getLatestToolVersion,
12 getSessionInfoByUserApiKey,
15 - HttpServerError,
16 - InvalidToolkitsError,
13 listOrganizations,
14 listOrgProjects,
19 -} from 'src/services/composio-clients';
20 -import { handleHttpServerError } from 'src/effects/handle-http-error';
15 +} from 'src/services/composio-account';
16 +import { ComposioClientSingleton, ComposioToolkitsRepository } from 'src/services/composio-clients';
17 +import { InvalidToolkitsError } from 'src/services/toolkit-version-validation';
18 +import { handleClientApiError } from 'src/effects/handle-http-error';
19 +import { isClientApiError } from 'src/utils/api-error-extraction';
20 import { defaultNodeOs, NodeOs } from 'src/services/node-os';
21 import { TerminalUI } from 'src/services/terminal-ui';
22 import { makeOrgProject, makeSessionInfo } from 'test/__utils__/models/account';
@@ -172,6 +171,31 @@ describe('composio-clients', () => {
171 }).pipe(Effect.provide(withSingleton))
172 );
173
174 + it.effect('listOrganizations fails with DecodeError when an organization has no name', () =>
175 + Effect.gen(function* () {
176 + vi.spyOn(globalThis, 'fetch').mockResolvedValue(
177 + jsonResponse(
178 + {
179 + organizations: [{ id: 'org_a', created_at: 'x', updated_at: 'x' }],
180 + total_pages: 1,
181 + current_page: 1,
182 + total_items: 1,
183 + },
184 + 200,
185 + { 'x-request-id': 'req_orgs' }
186 + )
187 + );
188 +
189 + const error = yield* listOrganizations({ apiKey: 'uak_test' }).pipe(Effect.flip);
190 +
191 + expect(error).toMatchObject({
192 + _tag: '@composio/client/DecodeError',
193 + operation: 'org.list',
194 + requestId: 'req_orgs',
195 + });
196 + }).pipe(Effect.provide(withSingleton))
197 + );
198 +
199 it.effect('listOrgProjects asks for every org project, scoped to the org only', () =>
200 Effect.gen(function* () {
201 const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(
@@ -254,12 +278,14 @@ describe('composio-clients', () => {
278 }).pipe(Effect.flip);
279
280 expect(fetchSpy).toHaveBeenCalledOnce();
257 - expect(error).toBeInstanceOf(HttpServerError);
258 - expect((error as HttpServerError).status).toBe(500);
281 + expect(error).toMatchObject({
282 + _tag: '@composio/client/InternalServerError',
283 + status: 500,
284 + });
285 }).pipe(Effect.provide(withSingleton))
286 );
287
262 - it.effect('a connection failure maps to HttpServerError without a status', () =>
288 + it.effect('a connection failure fails with APIConnectionError naming the transport', () =>
289 Effect.gen(function* () {
290 vi.spyOn(globalThis, 'fetch').mockRejectedValue(new TypeError('fetch failed'));
291
@@ -270,18 +296,21 @@ describe('composio-clients', () => {
296 name: 'cli',
297 }).pipe(Effect.flip);
298
273 - expect(error).toBeInstanceOf(HttpServerError);
274 - expect((error as HttpServerError).status).toBeUndefined();
299 + expect(error).toMatchObject({
300 + _tag: '@composio/client/APIConnectionError',
301 + description: 'fetch failed',
302 + });
303 }).pipe(Effect.provide(withSingleton))
304 );
305
278 - it.effect('retries a retryable failure and reports the eventual success', () =>
306 + // Live: the client sleeps between attempts on Effect's clock.
307 + it.live('retries a retryable failure and reports the eventual success', () =>
308 Effect.gen(function* () {
309 // No `x-should-retry: false` here: this scenario is about the retry
310 // the owned client performs and the old hand-rolled fetch did not.
311 const fetchSpy = vi
312 .spyOn(globalThis, 'fetch')
284 - .mockResolvedValueOnce(jsonResponse({ message: 'flaky' }, 500))
313 + .mockResolvedValueOnce(jsonResponse({ message: 'flaky' }, 500, { 'retry-after-ms': '0' }))
314 .mockResolvedValueOnce(jsonResponse(makeSessionInfo({ orgName: 'Retried Org' })));
315
316 const info = yield* getSessionInfoByUserApiKey({ userApiKey: 'uak_test' });
@@ -349,34 +378,62 @@ describe('composio-clients', () => {
378 jsonResponse({
379 items: [toolkitListItem('slack'), toolkitListItem('gmail')],
380 next_cursor: 'page_2',
352 - total_pages: 2,
381 + total_pages: 3,
382 current_page: 1,
354 - total_items: 3,
383 + total_items: 4,
384 + })
385 + )
386 + .mockResolvedValueOnce(
387 + jsonResponse({
388 + items: [toolkitListItem('zoom')],
389 + next_cursor: 'page_3',
390 + total_pages: 3,
391 + current_page: 2,
392 + total_items: 4,
393 })
394 )
395 .mockResolvedValueOnce(
396 jsonResponse({
397 items: [toolkitListItem('asana')],
398 next_cursor: null,
361 - total_pages: 2,
362 - current_page: 2,
363 - total_items: 3,
399 + total_pages: 3,
400 + current_page: 3,
401 + total_items: 4,
402 })
403 );
404 const repository = yield* ComposioToolkitsRepository;
405
406 const toolkits = yield* repository.getToolkits();
407
370 - expect(toolkits.map(t => t.slug)).toEqual(['asana', 'gmail', 'slack']);
371 - expect(fetchSpy).toHaveBeenCalledTimes(2);
372 - expect(requestOf(fetchSpy.mock.calls[0]).url.searchParams.get('limit')).toBe('1000');
373 - expect(requestOf(fetchSpy.mock.calls[1]).url.searchParams.get('cursor')).toBe('page_2');
408 + expect(toolkits.map(t => t.slug)).toEqual(['asana', 'gmail', 'slack', 'zoom']);
409 + expect(fetchSpy).toHaveBeenCalledTimes(3);
410 + const requests = fetchSpy.mock.calls.map(call => requestOf(call).url.searchParams);
411 + expect(requests.map(query => query.get('limit'))).toEqual(['1000', '1000', '1000']);
412 + expect(requests.map(query => query.get('cursor'))).toEqual([null, 'page_2', 'page_3']);
413 const metrics = yield* repository.getMetrics();
375 - expect(metrics.requests).toBe(2);
414 + expect(metrics.requests).toBe(3);
415 expect(metrics.byteSize).toBeGreaterThan(0);
416 }).pipe(Effect.provide(withRepository))
417 );
418
419 + it.effect('a cursor the server repeats fails the listing instead of looping', () =>
420 + Effect.gen(function* () {
421 + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation(async () =>
422 + jsonResponse({
423 + items: [toolkitListItem('gmail')],
424 + next_cursor: 'page_2',
425 + total_pages: 2,
426 + })
427 + );
428 + const repository = yield* ComposioToolkitsRepository;
429 +
430 + const error = yield* repository.getToolkits().pipe(Effect.flip);
431 +
432 + expect(error._tag).toBe('@composio/client/ConfigurationError');
433 + expect(fetchSpy).toHaveBeenCalledTimes(2);
434 + }).pipe(Effect.provide(withRepository))
435 + );
436 +
437 it.effect('a list item that breaks the catalog contract fails with HttpDecodingError', () =>
438 Effect.gen(function* () {
439 const { meta: _meta, ...withoutMeta } = toolkitListItem('gmail');
@@ -391,7 +448,27 @@ describe('composio-clients', () => {
448 }).pipe(Effect.provide(withRepository))
449 );
450
394 - it.effect('an API error envelope maps onto status, details, and suggestedFix', () =>
451 + it.effect('searchTools fails with DecodeError when the page breaks the API contract', () =>
452 + Effect.gen(function* () {
453 + vi.spyOn(globalThis, 'fetch').mockResolvedValue(
454 + // No `total_items`, which the API's response schema requires.
455 + jsonResponse({ items: [], next_cursor: null, total_pages: 1, current_page: 1 }, 200, {
456 + 'x-request-id': 'req_tools',
457 + })
458 + );
459 + const repository = yield* ComposioToolkitsRepository;
460 +
461 + const error = yield* repository.searchTools({ search: 'send' }).pipe(Effect.flip);
462 +
463 + expect(error).toMatchObject({
464 + _tag: '@composio/client/DecodeError',
465 + operation: 'tools.list',
466 + requestId: 'req_tools',
467 + });
468 + }).pipe(Effect.provide(withRepository))
469 + );
470 +
471 + it.effect('an API error envelope arrives as the status error with its details', () =>
472 Effect.gen(function* () {
473 vi.spyOn(globalThis, 'fetch').mockResolvedValue(
474 errorResponse(
@@ -403,10 +480,10 @@ describe('composio-clients', () => {
480
481 const error = yield* repository.getAuthConfig('ac_missing').pipe(Effect.flip);
482
406 - expect(error).toBeInstanceOf(HttpServerError);
483 expect(error).toMatchObject({
484 + _tag: '@composio/client/NotFoundError',
485 status: 404,
409 - details: { message: 'Not found', code: 404, suggestedFix: 'Check the id' },
486 + details: { message: 'Not found', code: 404, suggested_fix: 'Check the id' },
487 });
488 }).pipe(Effect.provide(withRepository))
489 );
@@ -431,9 +508,8 @@ describe('composio-clients', () => {
508 );
509 const repository = yield* ComposioToolkitsRepository;
510 const error = yield* repository.getAuthConfig('ac_1').pipe(Effect.flip);
434 - expect(error).toMatchObject({
435 - details: { message: 'Bad input', code: 1001, suggestedFix: undefined },
436 - });
511 + expect(error).toMatchObject({ details: { message: 'Bad input', code: 1001 } });
512 + assert(isClientApiError(error));
513
514 const errors: string[] = [];
515 const steps: string[] = [];
@@ -446,11 +522,11 @@ describe('composio-clients', () => {
522 },
523 });
524 const previousExitCode = process.exitCode;
449 - yield* handleHttpServerError(ui, {
525 + yield* handleClientApiError(ui, {
526 fallbackMessage: 'fallback',
527 hint: 'hint',
528 fallbackValue: undefined,
453 - })(error as HttpServerError);
529 + })(error);
530 process.exitCode = previousExitCode;
531
532 expect(errors).toEqual(['Bad input']);
@@ -517,6 +593,87 @@ describe('composio-clients', () => {
593 }).pipe(Effect.provide(withRepository))
594 );
595
596 + it.effect(
597 + 'listConnectedAccounts returns an account whose status this build does not know',
598 + () =>
599 + Effect.gen(function* () {
600 + vi.spyOn(globalThis, 'fetch').mockResolvedValue(
601 + jsonResponse({
602 + items: [
603 + {
604 + id: 'con_1',
605 + status: 'QUARANTINED',
606 + status_reason: null,
607 + is_disabled: false,
608 + user_id: 'default',
609 + toolkit: { slug: 'gmail' },
610 + auth_config: {
611 + id: 'ac_1',
612 + auth_scheme: 'OAUTH2',
613 + is_composio_managed: true,
614 + is_disabled: false,
615 + },
616 + created_at: '2026-01-01T00:00:00Z',
617 + updated_at: '2026-01-01T00:00:00Z',
618 + },
619 + ],
620 + total_items: 1,
621 + total_pages: 1,
622 + current_page: 1,
623 + next_cursor: null,
624 + })
625 + );
626 + const repository = yield* ComposioToolkitsRepository;
627 +
628 + const accounts = yield* repository.listConnectedAccounts({});
629 +
630 + expect(accounts.items.map(item => item.status)).toEqual(['QUARANTINED']);
631 + }).pipe(Effect.provide(withRepository))
632 + );
633 +
634 + it.effect('listActiveTriggers defaults the page counts a response leaves out', () =>
635 + Effect.gen(function* () {
636 + vi.spyOn(globalThis, 'fetch').mockResolvedValue(
637 + jsonResponse({ items: [{ id: 'ti_1' }, { id: 'ti_2' }] })
638 + );
639 + const repository = yield* ComposioToolkitsRepository;
640 +
641 + const triggers = yield* repository.listActiveTriggers({});
642 +
643 + expect(triggers).toMatchObject({
644 + total_items: 2,
645 + total_pages: 1,
646 + current_page: 1,
647 + next_cursor: null,
648 + });
649 + expect(triggers.items.map(item => item.id)).toEqual(['ti_1', 'ti_2']);
650 + }).pipe(Effect.provide(withRepository))
651 + );
652 +
653 + it.effect('createAuthConfig returns only the allowlisted fields of the response', () =>
654 + Effect.gen(function* () {
655 + vi.spyOn(globalThis, 'fetch').mockResolvedValue(
656 + jsonResponse({
657 + auth_config: {
658 + id: 'ac_new',
659 + auth_scheme: 'OAUTH2',
660 + is_composio_managed: false,
661 + credentials: { client_secret: 'secret_credentials' },
662 + },
663 + toolkit: { slug: 'gmail' },
664 + })
665 + );
666 + const repository = yield* ComposioToolkitsRepository;
667 +
668 + const created = yield* repository.createAuthConfig({ toolkit: { slug: 'gmail' } });
669 +
670 + expect(created).toEqual({
671 + auth_config: { id: 'ac_new', auth_scheme: 'OAUTH2', is_composio_managed: false },
672 + toolkit: { slug: 'gmail' },
673 + });
674 + }).pipe(Effect.provide(withRepository))
675 + );
676 +
677 it.effect('getToolkitsBySlugs turns a 404 into InvalidToolkitsError naming the slug', () =>
678 Effect.gen(function* () {
679 vi.spyOn(globalThis, 'fetch').mockResolvedValue(
@@ -531,7 +688,7 @@ describe('composio-clients', () => {
688 }).pipe(Effect.provide(withRepository))
689 );
690
534 - it.effect('getToolkitsBySlugs propagates a 500 as HttpServerError', () =>
691 + it.effect('getToolkitsBySlugs propagates a 500 as the client status error', () =>
692 Effect.gen(function* () {
693 vi.spyOn(globalThis, 'fetch').mockResolvedValue(
694 errorResponse(500, errorEnvelope({ message: 'Server error', code: 500 }))
@@ -540,8 +697,10 @@ describe('composio-clients', () => {
697
698 const error = yield* repository.getToolkitsBySlugs(['gmail']).pipe(Effect.flip);
699
543 - expect(error).toBeInstanceOf(HttpServerError);
544 - expect((error as HttpServerError).status).toBe(500);
700 + expect(error).toMatchObject({
701 + _tag: '@composio/client/InternalServerError',
702 + status: 500,
703 + });
704 }).pipe(Effect.provide(withRepository))
705 );
706
ts/packages/cli/test/src/services/composio-error-overrides.test.ts
+44 -16
@@ -1,4 +1,4 @@
1 -import { APIError } from '@composio/client';
1 +import { BadRequestError, InternalServerError } from '@composio/client/effect';
2 import { describe, expect, it } from 'vitest';
3
4 import {
@@ -7,22 +7,27 @@ import {
7 mapOnlyComposioOverrideError,
8 } from 'src/services/composio-error-overrides';
9
10 -const apiError = (
11 - status: number,
12 - envelope: { code: number; slug: string; message: string } | Record<string, unknown>
13 -) =>
14 - APIError.generate(
15 - status,
16 - 'code' in envelope ? { error: { status, ...envelope } } : envelope,
17 - undefined,
18 - new Headers({ 'x-request-id': 'req_test' })
19 - );
10 +const url = 'https://backend.composio.dev/api/v3.1/tools/execute/{tool_slug}';
11 +
12 +// The client's error for a 400 answered with `envelope`.
13 +const apiError = (envelope: { code: number; slug: string; message: string }) => {
14 + const details = { status: 400, ...envelope };
15 + return new BadRequestError({
16 + message: `400 ${JSON.stringify({ error: details })}`,
17 + method: 'POST',
18 + url,
19 + status: 400,
20 + requestId: 'req_test',
21 + details,
22 + body: { error: details },
23 + });
24 +};
25
26 describe('composio-error-overrides', () => {
27 it('rewrites a 4302 API error by toolkit', () => {
28 const result = mapComposioError({
29 toolkit: 'gmail',
25 - error: apiError(400, {
30 + error: apiError({
31 code: 4302,
32 slug: 'SomethingElse',
33 message: 'No active connection',
@@ -39,7 +44,7 @@ describe('composio-error-overrides', () => {
44 it('rewrites an execute no-connection slug by tool slug', () => {
45 const result = mapComposioError({
46 toolSlug: 'SLACK_SEND_MESSAGE',
42 - error: apiError(400, {
47 + error: apiError({
48 code: 1,
49 slug: 'ActionExecute_ConnectedAccountNotFound',
50 message: 'Missing connected account',
@@ -57,7 +62,7 @@ describe('composio-error-overrides', () => {
62 toolkit: 'gmail',
63 error: {
64 _tag: 'UnknownException',
60 - cause: apiError(400, {
65 + cause: apiError({
66 code: 1,
67 slug: 'ToolRouterV2_NoActiveConnection',
68 message: 'No active connection',
@@ -80,7 +85,15 @@ describe('composio-error-overrides', () => {
85 });
86
87 it('keeps a non-envelope API error unmapped, with the error message', () => {
83 - const error = apiError(502, { message: 'Bad gateway' });
88 + const error = new InternalServerError({
89 + message: '502 {"message":"Bad gateway"}',
90 + method: 'POST',
91 + url,
92 + status: 502,
93 + requestId: 'req_test',
94 + details: undefined,
95 + body: { message: 'Bad gateway' },
96 + });
97
98 const result = mapComposioError({ error });
99
@@ -116,7 +129,7 @@ describe('composio-error-overrides', () => {
129 it('still rewrites override-class Composio errors at the top level', () => {
130 const mapped = mapOnlyComposioOverrideError({
131 toolkit: 'gmail',
119 - error: apiError(400, {
132 + error: apiError({
133 code: 4302,
134 slug: 'ToolRouterV2_NoActiveConnection',
135 message: 'No active connection',
@@ -125,4 +138,19 @@ describe('composio-error-overrides', () => {
138
139 expect(mapped).toBeInstanceOf(ComposioNoActiveConnectionError);
140 });
141 +
142 + it('keeps an unrelated API error unmapped, with the envelope message', () => {
143 + const error = apiError({
144 + code: 1803,
145 + slug: 'Tool_NotFound',
146 + message: 'Tool not found',
147 + });
148 +
149 + const result = mapComposioError({ error });
150 +
151 + expect(result.override).toBeNull();
152 + expect(result.normalized).toBe(error);
153 + expect(result.message).toBe('Tool not found');
154 + expect(mapOnlyComposioOverrideError({ error })).toBe(error);
155 + });
156 });
ts/packages/cli/test/src/services/composio-schema-loaders.test.ts new
+25
@@ -0,0 +1,25 @@
1 +import { describe, expect, it } from '@effect/vitest';
2 +import { Effect } from 'effect';
3 +import { schemaLoaders } from '@composio/client/effect/schemas';
4 +import { composioSchemaLoaders } from 'src/services/composio-schema-loaders';
5 +
6 +const clientLoaders: Readonly<Record<string, (() => Promise<unknown>) | undefined>> = schemaLoaders;
7 +const cliLoaders: ReadonlyArray<readonly [string, () => Promise<unknown>]> =
8 + Object.entries(composioSchemaLoaders);
9 +
10 +describe('composioSchemaLoaders', () => {
11 + it('only names operations the client has a response schema for', () => {
12 + const unknown = cliLoaders.map(([key]) => key).filter(key => clientLoaders[key] === undefined);
13 +
14 + expect(unknown).toEqual([]);
15 + });
16 +
17 + it.effect.each(cliLoaders)('loads the response schema of %s', ([key, load]) =>
18 + Effect.gen(function* () {
19 + const expected = yield* Effect.promise(() => clientLoaders[key]!());
20 + const loaded = yield* Effect.promise(load);
21 +
22 + expect(loaded).toBe(expected);
23 + })
24 + );
25 +});
ts/packages/cli/test/src/services/connected-account-selection.test.ts
+48 -25
@@ -1,15 +1,18 @@
1 import { describe, expect, it } from 'vitest';
2 import { it as effectIt } from '@effect/vitest';
3 -import { Effect } from 'effect';
4 -import type { Composio } from '@composio/client';
3 +import { Effect, Option } from 'effect';
4 import {
5 + ConnectedAccountResolutionError,
6 formatConnectedAccountChoices,
7 groupCachedConnectedAccountsByToolkit,
8 listConnectedAccountsForToolkit,
9 + resolveConnectedAccountForToolkit,
10 resolveConnectedAccountSelection,
11 resolveDefaultConnectedAccountsByToolkit,
12 } from 'src/services/connected-account-selection';
13 import type { ConnectedAccountItem } from 'src/models/connected-accounts';
14 +import { stubComposioClient } from 'test/__utils__/services/stub-composio-client';
15 +import { TerminalUITest } from 'test/__utils__/services/terminal-ui-test';
16
17 const makeAccount = (overrides: Partial<ConnectedAccountItem>): ConnectedAccountItem => ({
18 id: 'con_default',
@@ -104,34 +107,31 @@ type ListParams = {
107 readonly limit?: number;
108 };
109
107 -// A stand-in for the SDK client: one page of accounts, plus a log of every
108 -// `connectedAccounts.list` call so a test can see which path ran.
110 +// The client over a transport that serves one page of accounts, plus a log of
111 +// every `GET /connected_accounts` query so a test can see which path ran.
112 const makeListClient = (
113 items: ReadonlyArray<ConnectedAccountItem>,
114 page?: { readonly total_items?: number; readonly next_cursor?: string | null }
115 ) => {
116 const calls: ListParams[] = [];
114 - const client = {
115 - connectedAccounts: {
116 - list: async (params: ListParams) => {
117 - calls.push(params);
118 - const filtered = params.toolkit_slugs
119 - ? items.filter(item =>
120 - params.toolkit_slugs!.some(
121 - slug => slug.trim().toLowerCase() === item.toolkit.slug.trim().toLowerCase()
122 - )
123 - )
124 - : items;
125 - return {
126 - items: filtered.slice(0, params.limit ?? 30),
127 - total_items: page?.total_items ?? filtered.length,
128 - total_pages: 1,
129 - current_page: 1,
130 - next_cursor: page?.next_cursor ?? null,
131 - };
132 - },
133 - },
134 - } as unknown as Composio;
117 + const { client } = stubComposioClient(request => {
118 + const query = new URL(request.path, 'https://stub.invalid').searchParams;
119 + const slugs = query.get('toolkit_slugs')?.split(',');
120 + const limit = Number(query.get('limit') ?? 30);
121 + calls.push({ ...(slugs ? { toolkit_slugs: slugs } : {}), limit });
122 + const filtered = slugs
123 + ? items.filter(item =>
124 + slugs.some(slug => slug.trim().toLowerCase() === item.toolkit.slug.trim().toLowerCase())
125 + )
126 + : items;
127 + return Response.json({
128 + items: filtered.slice(0, limit),
129 + total_items: page?.total_items ?? filtered.length,
130 + total_pages: 1,
131 + current_page: 1,
132 + next_cursor: page?.next_cursor ?? null,
133 + });
134 + });
135 return { client, calls };
136 };
137
@@ -205,3 +205,26 @@ describe('listConnectedAccountsForToolkit', () => {
205 })
206 );
207 });
208 +
209 +describe('resolveConnectedAccountForToolkit', () => {
210 + effectIt.effect('reports a rejected account listing in the wording it has always used', () =>
211 + Effect.gen(function* () {
212 + const body = {
213 + error: { message: 'Invalid user id', code: 301, slug: 'Invalid_UserId', status: 400 },
214 + };
215 + const { client } = stubComposioClient(() => Response.json(body, { status: 400 }));
216 +
217 + const failure = yield* resolveConnectedAccountForToolkit({
218 + client,
219 + toolkitSlug: 'gmail',
220 + userId: 'default',
221 + selector: Option.none(),
222 + }).pipe(Effect.flip, Effect.provide(TerminalUITest));
223 +
224 + expect(failure).toBeInstanceOf(ConnectedAccountResolutionError);
225 + expect(failure.message).toBe(
226 + `Failed to load connected accounts for toolkit "gmail": Error: 400 ${JSON.stringify(body)}`
227 + );
228 + })
229 + );
230 +});
ts/packages/cli/test/src/services/consumer-short-term-cache.test.ts
+2 -2
@@ -4,7 +4,7 @@ import * as FileSystem from 'effect/FileSystem';
4 import { ConfigProvider, DateTime, Effect, Option } from 'effect';
5 import path from 'node:path';
6 import { setupCacheDir } from 'src/effects/setup-cache-dir';
7 -import * as composioClients from 'src/services/composio-clients';
7 +import * as composioAccount from 'src/services/composio-account';
8 import {
9 getFreshConsumerConnectedToolkitsFromCache,
10 getFreshConsumerToolRouterAuthConfigsFromCache,
@@ -112,7 +112,7 @@ describe('consumer short-term cache', () => {
112 )('[Given] no-auth toolkits [Then] refresh caches them as connected', it => {
113 it.effect('stores connected and no-auth toolkit slugs together', () =>
114 Effect.gen(function* () {
115 - vi.spyOn(composioClients, 'getConsumerConnectedToolkits').mockReturnValue(
115 + vi.spyOn(composioAccount, 'getConsumerConnectedToolkits').mockReturnValue(
116 Effect.succeed({ toolkits: ['github'] })
117 );
118
ts/packages/cli/test/src/services/test-layer.test.ts
+2 -4
@@ -2,10 +2,9 @@ import { describe, expect, it, vi } from '@effect/vitest';
2 import { Effect } from 'effect';
3 import {
4 getSessionInfoByUserApiKey,
5 - HttpServerError,
5 listOrganizations,
6 resolveConsumerProject,
8 -} from 'src/services/composio-clients';
7 +} from 'src/services/composio-account';
8 import { TestLive } from 'test/__utils__';
9 import { makeSessionInfo } from 'test/__utils__/models/account';
10
@@ -53,8 +52,7 @@ describe('TestLayer', () => {
52 Effect.flip
53 );
54
56 - expect(error).toBeInstanceOf(HttpServerError);
57 - expect((error as HttpServerError).status).toBeUndefined();
55 + expect(error).toMatchObject({ _tag: '@composio/client/APIConnectionError' });
56 })
57 );
58 });
ts/packages/cli/test/src/services/tool-file-uploads.test.ts
+93 -35
@@ -7,13 +7,14 @@ import * as Path from 'effect/Path';
7 import * as BunFileSystem from '@effect/platform-bun/BunFileSystem';
8 import * as BunPath from '@effect/platform-bun/BunPath';
9 import { Effect, Layer } from 'effect';
10 -import { Composio as RawComposioClient } from '@composio/client';
10 +import { BadRequestError } from '@composio/client/effect';
11 import {
12 ComposioBlockedInternalUrlError,
13 ComposioSensitiveFilePathBlockedError,
14 MAX_URL_UPLOAD_SIZE_BYTES,
15 } from '@composio/core';
16 import { schemaHasFileUploadable, uploadToolInputFiles } from 'src/services/tool-file-uploads';
17 +import { stubComposioClient } from 'test/__utils__/services/stub-composio-client';
18
19 // Schema with a single `file_uploadable` attachment field — mirrors tools like
20 // GMAIL_SEND_EMAIL whose attachment is uploaded from a local path.
@@ -24,10 +25,14 @@ const inputSchema = {
25 },
26 };
27
27 -const makeClient = (createPresignedURL = vi.fn()) =>
28 - Object.assign(new RawComposioClient({ apiKey: 'test' }), {
29 - files: { createPresignedURL },
30 - });
28 +// The client over a transport that answers the presigned-URL request with
29 +// `presigned`, and records each request it receives.
30 +const makeClient = (
31 + presigned: { readonly new_presigned_url: string; readonly key: string } = {
32 + new_presigned_url: 'https://1.1.1.1/put',
33 + key: 's3key-123',
34 + }
35 +) => stubComposioClient(() => Response.json(presigned));
36
37 describe('uploadToolInputFiles — sensitive-path guard (issue #3746)', () => {
38 afterEach(() => {
@@ -48,8 +53,7 @@ describe('uploadToolInputFiles — sensitive-path guard (issue #3746)', () => {
53 Effect.gen(function* () {
54 const fsApi = yield* FileSystem.FileSystem;
55 const pathApi = yield* Path.Path;
51 - const createPresignedURL = vi.fn();
52 - const client = makeClient(createPresignedURL);
56 + const { client, requests } = makeClient();
57
58 yield* Effect.promise(() =>
59 expect(
@@ -65,7 +69,7 @@ describe('uploadToolInputFiles — sensitive-path guard (issue #3746)', () => {
69 );
70
71 // The guard must fire BEFORE any network round-trip: no presigned URL, no upload.
68 - expect(createPresignedURL).not.toHaveBeenCalled();
72 + expect(requests).toEqual([]);
73 }).pipe(Effect.provide(Layer.mergeAll(BunFileSystem.layer, BunPath.layer)))
74 );
75
@@ -75,7 +79,7 @@ describe('uploadToolInputFiles — sensitive-path guard (issue #3746)', () => {
79 Effect.gen(function* () {
80 const fsApi = yield* FileSystem.FileSystem;
81 const pathApi = yield* Path.Path;
78 - const client = makeClient(vi.fn());
82 + const { client } = makeClient();
83
84 // The CLI has no `sensitiveFileUploadProtection` opt-out (by design), so the
85 // error must not point users at that non-existent knob (issue #3763 review #2/#3).
@@ -111,8 +115,7 @@ describe('uploadToolInputFiles — sensitive-path guard (issue #3746)', () => {
115 Effect.gen(function* () {
116 const fsApi = yield* FileSystem.FileSystem;
117 const pathApi = yield* Path.Path;
114 - const createPresignedURL = vi.fn();
115 - const client = makeClient(createPresignedURL);
118 + const { client, requests } = makeClient();
119
120 yield* Effect.promise(() =>
121 expect(
@@ -126,24 +129,18 @@ describe('uploadToolInputFiles — sensitive-path guard (issue #3746)', () => {
129 })
130 ).rejects.toBeInstanceOf(ComposioSensitiveFilePathBlockedError)
131 );
129 - expect(createPresignedURL).not.toHaveBeenCalled();
132 + expect(requests).toEqual([]);
133 }).pipe(Effect.provide(Layer.mergeAll(BunFileSystem.layer, BunPath.layer)))
134 );
135
133 - it.effect('still uploads a normal (non-sensitive) local file', () => {
136 + it.effect('requests one presigned URL for a normal local file and uploads to it', () => {
137 const root = mkdtempSync(path.join(os.tmpdir(), 'composio-upload-'));
138 const file = path.join(root, 'document.pdf');
139 writeFileSync(file, 'hello');
140
138 - const createPresignedURL = vi.fn(async () => ({
139 - new_presigned_url: 'https://1.1.1.1/put',
140 - key: 's3key-123',
141 - }));
142 - const client = makeClient(createPresignedURL);
143 - vi.stubGlobal(
144 - 'fetch',
145 - vi.fn(async () => ({ ok: true, statusText: 'OK' }))
146 - );
141 + const { client, requests } = makeClient();
142 + const uploadFetch = vi.fn(async () => ({ ok: true, statusText: 'OK' }));
143 + vi.stubGlobal('fetch', uploadFetch);
144
145 return Effect.gen(function* () {
146 const fsApi = yield* FileSystem.FileSystem;
@@ -159,9 +156,23 @@ describe('uploadToolInputFiles — sensitive-path guard (issue #3746)', () => {
156 })
157 );
158
162 - expect(createPresignedURL).toHaveBeenCalledTimes(1);
163 - expect(createPresignedURL).toHaveBeenCalledWith(
164 - expect.objectContaining({ md5: '5d41402abc4b2a76b9719d911017c592' })
159 + expect(requests).toEqual([
160 + {
161 + method: 'POST',
162 + path: '/api/v3.1/files/upload/request',
163 + body: {
164 + filename: 'document.pdf',
165 + mimetype: 'application/octet-stream',
166 + md5: '5d41402abc4b2a76b9719d911017c592',
167 + tool_slug: 'GMAIL_SEND_EMAIL',
168 + toolkit_slug: 'gmail',
169 + },
170 + },
171 + ]);
172 + expect(uploadFetch).toHaveBeenCalledTimes(1);
173 + expect(uploadFetch).toHaveBeenCalledWith(
174 + 'https://1.1.1.1/put',
175 + expect.objectContaining({ method: 'PUT' })
176 );
177 expect(result.attachment).toMatchObject({ s3key: 's3key-123', name: 'document.pdf' });
178 }).pipe(
@@ -171,6 +182,55 @@ describe('uploadToolInputFiles — sensitive-path guard (issue #3746)', () => {
182 });
183 });
184
185 +describe('uploadToolInputFiles — presigned-URL request', () => {
186 + afterEach(() => {
187 + vi.unstubAllGlobals();
188 + vi.restoreAllMocks();
189 + });
190 +
191 + it.effect('rejects with the API failure, worded as before, when the request is refused', () => {
192 + const root = mkdtempSync(path.join(os.tmpdir(), 'composio-upload-'));
193 + const file = path.join(root, 'document.pdf');
194 + writeFileSync(file, 'hello');
195 + const body = {
196 + error: { message: 'Unsupported mimetype', code: 1803, slug: 'File_Invalid', status: 400 },
197 + };
198 + const { client, requests } = stubComposioClient(() => Response.json(body, { status: 400 }));
199 + const fetchSpy = vi.spyOn(globalThis, 'fetch');
200 +
201 + return Effect.gen(function* () {
202 + const fsApi = yield* FileSystem.FileSystem;
203 + const pathApi = yield* Path.Path;
204 +
205 + const failure = yield* Effect.promise(() =>
206 + uploadToolInputFiles({
207 + fs: fsApi,
208 + path: pathApi,
209 + toolSlug: 'GMAIL_SEND_EMAIL',
210 + arguments_: { attachment: file },
211 + inputSchema,
212 + client,
213 + }).then(
214 + () => undefined,
215 + (cause: unknown) => cause
216 + )
217 + );
218 +
219 + expect(failure).toBeInstanceOf(BadRequestError);
220 + expect(failure).toMatchObject({
221 + message: `400 ${JSON.stringify(body)}`,
222 + status: 400,
223 + details: body.error,
224 + });
225 + expect(requests).toHaveLength(1);
226 + expect(fetchSpy).not.toHaveBeenCalled();
227 + }).pipe(
228 + Effect.provide(Layer.mergeAll(BunFileSystem.layer, BunPath.layer)),
229 + Effect.ensuring(Effect.sync(() => rmSync(root, { recursive: true, force: true })))
230 + );
231 + });
232 +});
233 +
234 describe('uploadToolInputFiles — URL SSRF boundary', () => {
235 afterEach(() => {
236 vi.unstubAllGlobals();
@@ -181,8 +241,7 @@ describe('uploadToolInputFiles — URL SSRF boundary', () => {
241 Effect.gen(function* () {
242 const fsApi = yield* FileSystem.FileSystem;
243 const pathApi = yield* Path.Path;
184 - const createPresignedURL = vi.fn();
185 - const client = makeClient(createPresignedURL);
244 + const { client, requests } = makeClient();
245 const sourceUrl = 'http://169.254.169.254/latest/meta-data/credentials';
246
247 yield* Effect.promise(() =>
@@ -198,7 +257,7 @@ describe('uploadToolInputFiles — URL SSRF boundary', () => {
257 ).rejects.toBeInstanceOf(ComposioBlockedInternalUrlError)
258 );
259
201 - expect(createPresignedURL).not.toHaveBeenCalled();
260 + expect(requests).toEqual([]);
261 }).pipe(Effect.provide(Layer.mergeAll(BunFileSystem.layer, BunPath.layer)))
262 );
263
@@ -207,10 +266,10 @@ describe('uploadToolInputFiles — URL SSRF boundary', () => {
266 const file = path.join(root, 'document.pdf');
267 writeFileSync(file, 'hello');
268 const fetchSpy = vi.spyOn(globalThis, 'fetch');
210 - const createPresignedURL = vi.fn(async () => ({
269 + const { client, requests } = makeClient({
270 new_presigned_url: 'http://127.0.0.1:8080/upload',
271 key: 's3key-123',
213 - }));
272 + });
273
274 return Effect.gen(function* () {
275 const fsApi = yield* FileSystem.FileSystem;
@@ -224,12 +283,12 @@ describe('uploadToolInputFiles — URL SSRF boundary', () => {
283 toolSlug: 'GMAIL_SEND_EMAIL',
284 arguments_: { attachment: file },
285 inputSchema,
227 - client: makeClient(createPresignedURL),
286 + client,
287 })
288 ).rejects.toBeInstanceOf(ComposioBlockedInternalUrlError)
289 );
290
232 - expect(createPresignedURL).toHaveBeenCalledOnce();
291 + expect(requests).toHaveLength(1);
292 expect(fetchSpy).not.toHaveBeenCalled();
293 }).pipe(
294 Effect.provide(Layer.mergeAll(BunFileSystem.layer, BunPath.layer)),
@@ -245,8 +304,7 @@ describe('uploadToolInputFiles — URL download size cap', () => {
304 });
305
306 it.effect('rejects a remote file that declares a body above the cap before buffering it', () => {
248 - const createPresignedURL = vi.fn();
249 - const client = makeClient(createPresignedURL);
307 + const { client, requests } = makeClient();
308 const oversized = String(MAX_URL_UPLOAD_SIZE_BYTES + 1);
309 vi.stubGlobal(
310 'fetch',
@@ -276,7 +334,7 @@ describe('uploadToolInputFiles — URL download size cap', () => {
334 ).rejects.toThrow(/exceeds maximum allowed size/)
335 );
336
279 - expect(createPresignedURL).not.toHaveBeenCalled();
337 + expect(requests).toEqual([]);
338 }).pipe(Effect.provide(Layer.mergeAll(BunFileSystem.layer, BunPath.layer)));
339 });
340 });
ts/packages/cli/test/src/services/tool-permissions.test.ts
+101 -25
@@ -4,8 +4,7 @@ import * as BunFileSystem from '@effect/platform-bun/BunFileSystem';
4 import * as BunPath from '@effect/platform-bun/BunPath';
5 import { afterEach, beforeEach, describe, expect, it } from '@effect/vitest';
6 import { vi } from 'vitest';
7 -import { Config, ConfigProvider, Effect, Layer, Option } from 'effect';
8 -import { Composio as RawComposioClient } from '@composio/client';
7 +import { Config, ConfigProvider, Effect, Layer, Logger, Option, References } from 'effect';
8
9 // Enhanced controls are disabled on darwin-x64, so pin the platform: these
10 // scenarios are about the transport, not about where the CLI runs.
@@ -20,14 +19,14 @@ import {
19 refreshConsumerPermissionSnapshot,
20 resolveGateState,
21 ToolPermissionDeniedError,
22 + ToolPermissionsRequestError,
23 type ConsumerPermissionSnapshot,
24 } from 'src/services/tool-permissions';
25 import { NodeOs } from 'src/services/node-os';
26 -import {
27 - ComposioClientConfigurationError,
28 - ComposioClientSingleton,
29 -} from 'src/services/composio-clients';
26 +import { ComposioClientConfigurationError } from 'src/services/composio-errors';
27 +import { ComposioClientSingleton } from 'src/services/composio-clients';
28 import { ComposioUserContext } from 'src/services/user-context';
29 +import { stubComposioClient } from 'test/__utils__/services/stub-composio-client';
30
31 // Pinned wall clock for deterministic fixtures. The SUT reads the real
32 // `Date.now()` (snapshot TTL, allow-decision expiry), so every timestamp
@@ -57,29 +56,31 @@ const snapshotFixture = (
56 ...overrides,
57 });
58
59 +// A retried request waits on the clock, so a failing answer asks for no wait.
60 +const serverError = () =>
61 + Response.json(
62 + { error: { message: 'Internal error', code: 500, slug: 'Internal', status: 500 } },
63 + { status: 500, headers: { 'retry-after-ms': '0' } }
64 + );
65 +
66 /**
67 * The consumer endpoints the permission snapshot reads. Both are absent from
68 * the v3.1 spec, so production calls them through the client's generic
63 - * `get`/`post`; the double answers at that same boundary.
69 + * `get`/`post`; the double answers below the client, at its transport. An
70 + * endpoint with no answer responds 500.
71 */
72 const permissionsClientLayer = (responses: {
73 readonly config?: unknown;
74 readonly permissions?: unknown;
75 readonly clientUnavailable?: boolean;
76 }) => {
70 - const paths: string[] = [];
71 - const client = {
72 - get: async (path: string) => {
73 - paths.push(`GET ${path}`);
74 - if (responses.config === undefined) throw new Error(`no stub for GET ${path}`);
75 - return responses.config;
76 - },
77 - post: async (path: string) => {
78 - paths.push(`POST ${path}`);
79 - if (responses.permissions === undefined) throw new Error(`no stub for POST ${path}`);
80 - return responses.permissions;
81 - },
82 - } as unknown as RawComposioClient;
77 + const { client, requests } = stubComposioClient(request => {
78 + const body = request.method === 'GET' ? responses.config : responses.permissions;
79 + return body === undefined ? serverError() : Response.json(body);
80 + });
81 + // Every debug record the permission paths log, which is where they report a
82 + // request failure they recovered from.
83 + const logged: Array<unknown> = [];
84
85 const layer = Layer.mergeAll(
86 Layer.succeed(
@@ -114,10 +115,24 @@ const permissionsClientLayer = (responses: {
115 login: () => Effect.void,
116 update: () => Effect.void,
117 })
117 - )
118 + ),
119 + Logger.layer([
120 + Logger.make<unknown, void>(({ message }) => {
121 + logged.push(...(Array.isArray(message) ? message : [message]));
122 + }),
123 + ]),
124 + Layer.succeed(References.MinimumLogLevel, 'Debug')
125 );
126
120 - return { layer, paths };
127 + return {
128 + layer,
129 + paths: () => requests.map(request => `${request.method} ${request.path}`),
130 + requestErrors: () =>
131 + logged.filter(
132 + (entry): entry is ToolPermissionsRequestError =>
133 + entry instanceof ToolPermissionsRequestError
134 + ),
135 + };
136 };
137
138 const refreshParams = {
@@ -321,7 +336,7 @@ describe('tool permissions', () => {
336 Effect.provide(stub.layer)
337 );
338
324 - expect(stub.paths).toEqual([
339 + expect(stub.paths()).toEqual([
340 'GET /api/v3.1/org/consumer/config',
341 'POST /api/v3.1/consumer/permissions/resolve',
342 ]);
@@ -330,7 +345,7 @@ describe('tool permissions', () => {
345 }).pipe(Effect.provide(ToolPermissionsTest))
346 );
347
333 - it.effect('fails closed to ask_every_call when the policy call fails', () =>
348 + it.live('fails closed to ask_every_call when the policy call fails', () =>
349 Effect.gen(function* () {
350 const stub = permissionsClientLayer({ config: { enhanced_controls: true } });
351
@@ -341,6 +356,67 @@ describe('tool permissions', () => {
356 expect(snapshot?.enhancedControlsEnabled).toBe(true);
357 expect(snapshot?.permissions).toEqual({ default: 'ask_every_call' });
358 expect(resolveGateState({ snapshot, toolSlug: 'GMAIL_SEND_EMAIL' })).toBe('ask_every_call');
359 + expect(stub.requestErrors()).toMatchObject([
360 + {
361 + path: '/api/v3.1/consumer/permissions/resolve',
362 + message: 'Failed to resolve consumer permissions.',
363 + cause: { _tag: '@composio/client/InternalServerError', status: 500 },
364 + },
365 + ]);
366 + }).pipe(Effect.provide(ToolPermissionsTest))
367 + );
368 +
369 + it.effect('fails closed to ask_every_call when the policy does not match its schema', () =>
370 + Effect.gen(function* () {
371 + const stub = permissionsClientLayer({
372 + config: { enhanced_controls: true },
373 + permissions: { experimental: { permissions: { default: 42 } } },
374 + });
375 +
376 + const snapshot = yield* refreshConsumerPermissionSnapshot(refreshParams).pipe(
377 + Effect.provide(stub.layer)
378 + );
379 +
380 + expect(snapshot?.permissions).toEqual({ default: 'ask_every_call' });
381 + expect(stub.requestErrors()).toMatchObject([
382 + { path: '/api/v3.1/consumer/permissions/resolve', cause: { _tag: 'SchemaError' } },
383 + ]);
384 + }).pipe(Effect.provide(ToolPermissionsTest))
385 + );
386 +
387 + it.live('returns no snapshot when the consumer config request fails', () =>
388 + Effect.gen(function* () {
389 + const stub = permissionsClientLayer({});
390 +
391 + const snapshot = yield* refreshConsumerPermissionSnapshot(refreshParams).pipe(
392 + Effect.provide(stub.layer)
393 + );
394 +
395 + expect(snapshot).toBeUndefined();
396 + expect(stub.paths()).not.toContain('POST /api/v3.1/consumer/permissions/resolve');
397 + expect(stub.requestErrors()).toMatchObject([
398 + {
399 + path: '/api/v3.1/org/consumer/config',
400 + message: 'Failed to fetch the org consumer config.',
401 + cause: { _tag: '@composio/client/InternalServerError', status: 500 },
402 + },
403 + ]);
404 + }).pipe(Effect.provide(ToolPermissionsTest))
405 + );
406 +
407 + it.effect('returns no snapshot when the consumer config does not match its schema', () =>
408 + Effect.gen(function* () {
409 + const stub = permissionsClientLayer({ config: { enhanced_controls: 'yes' } });
410 +
411 + const snapshot = yield* refreshConsumerPermissionSnapshot(refreshParams).pipe(
412 + Effect.provide(stub.layer)
413 + );
414 +
415 + expect(snapshot).toBeUndefined();
416 + expect(stub.paths()).toEqual(['GET /api/v3.1/org/consumer/config']);
417 + expect(stub.requestErrors()).toMatchObject([
418 + { path: '/api/v3.1/org/consumer/config', cause: { _tag: 'SchemaError' } },
419 + ]);
420 }).pipe(Effect.provide(ToolPermissionsTest))
421 );
422
@@ -353,7 +429,7 @@ describe('tool permissions', () => {
429 );
430
431 expect(snapshot).toBeUndefined();
356 - expect(stub.paths).toEqual([]);
432 + expect(stub.paths()).toEqual([]);
433 }).pipe(Effect.provide(ToolPermissionsTest))
434 );
435 });
ts/packages/cli/test/src/services/triggers-realtime.listen.test.ts new
+142
@@ -0,0 +1,142 @@
1 +import { afterEach, describe, expect, it } from '@effect/vitest';
2 +import { vi } from 'vitest';
3 +import * as BunFileSystem from '@effect/platform-bun/BunFileSystem';
4 +import * as BunPath from '@effect/platform-bun/BunPath';
5 +import { ConfigProvider, Effect, Fiber, Layer } from 'effect';
6 +import * as tempy from 'tempy';
7 +import { defaultNodeOs, NodeOs } from 'src/services/node-os';
8 +import { TriggersRealtime } from 'src/services/triggers-realtime';
9 +
10 +// Exercise real user-context/config resolution without opening the OS credential store.
11 +vi.mock('@composio/cli-keyring/effect', async importOriginal => {
12 + const actual = await importOriginal<typeof import('@composio/cli-keyring/effect')>();
13 + const { Effect, Layer } = await import('effect');
14 + const { KeyringError } = await import('@composio/cli-keyring');
15 + return {
16 + ...actual,
17 + KeyringLiveWithBackend: () =>
18 + Layer.succeed(actual.KeyringService, {
19 + getPassword: () => Effect.fail(new KeyringError({ kind: 'NoEntry' })),
20 + getSecret: () => Effect.fail(new KeyringError({ kind: 'NoEntry' })),
21 + setPassword: () => Effect.die(new Error('Unexpected credential write')),
22 + setSecret: () => Effect.die(new Error('Unexpected credential write')),
23 + deleteCredential: () => Effect.die(new Error('Unexpected credential deletion')),
24 + isAvailable: Effect.succeed(true),
25 + }),
26 + };
27 +});
28 +
29 +type ChannelAuthorizer = (
30 + params: { readonly channelName: string; readonly socketId: string },
31 + callback: (error: Error | null, data: unknown) => void
32 +) => void;
33 +
34 +interface ConstructedPusher {
35 + readonly key: string;
36 + readonly cluster: string;
37 + readonly authorize: ChannelAuthorizer;
38 +}
39 +
40 +// The realtime client, replaced by one that only records how it was built.
41 +const pusher = vi.hoisted(() => {
42 + let announce: (constructed: ConstructedPusher) => void = () => undefined;
43 + const constructed = new Promise<ConstructedPusher>(resolve => {
44 + announce = resolve;
45 + });
46 + return { constructed, announce: (value: ConstructedPusher) => announce(value) };
47 +});
48 +
49 +vi.mock('pusher-js', () => {
50 + class FakePusher {
51 + constructor(
52 + key: string,
53 + options: {
54 + readonly cluster: string;
55 + readonly channelAuthorization: { readonly customHandler: ChannelAuthorizer };
56 + }
57 + ) {
58 + pusher.announce({
59 + key,
60 + cluster: options.cluster,
61 + authorize: options.channelAuthorization.customHandler,
62 + });
63 + }
64 + subscribe() {
65 + return { bind: () => undefined, unbind_all: () => undefined };
66 + }
67 + unsubscribe() {}
68 + disconnect() {}
69 + }
70 + return { default: FakePusher };
71 +});
72 +
73 +const realtimeLayer = () =>
74 + TriggersRealtime.Default.pipe(
75 + Layer.provide(
76 + Layer.mergeAll(
77 + BunFileSystem.layer,
78 + BunPath.layer,
79 + Layer.succeed(NodeOs, defaultNodeOs({ homedir: tempy.temporaryDirectory() })),
80 + Layer.succeed(
81 + ConfigProvider.ConfigProvider,
82 + ConfigProvider.fromEnv({
83 + env: {
84 + COMPOSIO_USER_API_KEY: 'uak_realtime_test',
85 + COMPOSIO_BASE_URL: 'https://backend.composio.dev',
86 + },
87 + })
88 + )
89 + )
90 + )
91 + );
92 +
93 +describe('TriggersRealtime.listenInProject', () => {
94 + afterEach(() => {
95 + vi.restoreAllMocks();
96 + });
97 +
98 + it.live('authorizes the private channel when the realtime client asks for it', () => {
99 + const requests: Array<{ method: string; path: string; body: unknown }> = [];
100 + vi.spyOn(globalThis, 'fetch').mockImplementation(async (input, init) => {
101 + const request = new Request(input, init);
102 + const path = new URL(request.url).pathname;
103 + const text = await request.text();
104 + requests.push({
105 + method: request.method,
106 + path,
107 + body: text === '' ? undefined : JSON.parse(text),
108 + });
109 + return path.endsWith('/credentials')
110 + ? Response.json({ pusher_key: 'pk_test', pusher_cluster: 'mt1', project_id: 'pr_nano' })
111 + : // `channel_data` only belongs to presence channels.
112 + Response.json({ auth: 'pk_test:signature', channel_data: '{"user_id":"1"}' });
113 + });
114 +
115 + return Effect.gen(function* () {
116 + const realtime = yield* TriggersRealtime;
117 + const listening = yield* Effect.forkChild(
118 + realtime.listenInProject({ orgId: 'org_test', projectId: 'pr_test' }, () => undefined)
119 + );
120 +
121 + const constructed = yield* Effect.promise(() => pusher.constructed);
122 + const authorized = yield* Effect.callback<unknown, Error>(resume => {
123 + constructed.authorize(
124 + { channelName: 'private-cli-pr_nano', socketId: '123.456' },
125 + (error, data) => resume(error ? Effect.fail(error) : Effect.succeed(data))
126 + );
127 + });
128 + yield* Fiber.interrupt(listening);
129 +
130 + expect(constructed).toMatchObject({ key: 'pk_test', cluster: 'mt1' });
131 + expect(authorized).toEqual({ auth: 'pk_test:signature' });
132 + expect(requests).toEqual([
133 + { method: 'GET', path: '/api/v3.1/cli/realtime/credentials', body: undefined },
134 + {
135 + method: 'POST',
136 + path: '/api/v3.1/cli/realtime/auth',
137 + body: { channel_name: 'private-cli-pr_nano', socket_id: '123.456' },
138 + },
139 + ]);
140 + }).pipe(Effect.provide(realtimeLayer()));
141 + });
142 +});
ts/packages/cli/test/src/utils/api-error-extraction.test.ts
+106 -17
@@ -1,6 +1,15 @@
1 -import { APIConnectionError, APIError } from '@composio/client';
1 +import {
2 + APIConnectionError,
3 + DecodeError,
4 + InternalServerError,
5 + RateLimitError,
6 +} from '@composio/client/effect';
7 import { describe, expect, it } from 'vitest';
3 -import { extractApiErrorDetails, findApiError } from 'src/utils/api-error-extraction';
8 +import {
9 + extractApiErrorDetails,
10 + extractMessage,
11 + findApiError,
12 +} from 'src/utils/api-error-extraction';
13
14 const envelope = {
15 error: {
@@ -13,15 +22,45 @@ const envelope = {
22 },
23 };
24
25 +const url = 'https://backend.composio.dev/api/v3.1/toolkits';
26 +
27 +// The client's error for a 429 answered with `envelope`.
28 +const rateLimitError = (requestId: string | undefined) =>
29 + new RateLimitError({
30 + message: `429 ${JSON.stringify(envelope)}`,
31 + method: 'GET',
32 + url,
33 + status: 429,
34 + requestId: requestId ?? envelope.error.request_id,
35 + details: envelope.error,
36 + body: envelope,
37 + });
38 +
39 +const badGatewayError = (body: unknown, message: string) =>
40 + new InternalServerError({
41 + message,
42 + method: 'GET',
43 + url,
44 + status: 502,
45 + requestId: undefined,
46 + details: undefined,
47 + body,
48 + });
49 +
50 +const connectionError = (description: string) =>
51 + new APIConnectionError({
52 + message: 'Connection error.',
53 + method: 'GET',
54 + url,
55 + reason: 'TransportError',
56 + description,
57 + });
58 +
59 describe('extractApiErrorDetails', () => {
17 - it('reads the envelope, status, and header request id from an APIError', () => {
18 - const error = APIError.generate(
19 - 429,
20 - envelope,
21 - undefined,
22 - new Headers({ 'x-request-id': 'req_header' })
23 - );
60 + it('reads the envelope, status, and header request id from a status error', () => {
61 + const error = rateLimitError('req_header');
62
63 + expect(findApiError(error)).toBe(error);
64 expect(extractApiErrorDetails(error)).toEqual({
65 message: 'Rate limited',
66 code: 42901,
@@ -32,8 +71,8 @@ describe('extractApiErrorDetails', () => {
71 });
72 });
73
35 - it('follows the cause chain to the first APIError', () => {
36 - const error = APIError.generate(429, envelope, undefined, new Headers());
74 + it('follows the cause chain to the first status error', () => {
75 + const error = rateLimitError(undefined);
76 const wrapper = Object.assign(new Error('generic wrapper'), {
77 cause: { _tag: 'UnknownException', cause: error },
78 });
@@ -43,7 +82,7 @@ describe('extractApiErrorDetails', () => {
82 });
83
84 it('falls back to the error message when the body is not the envelope', () => {
46 - const error = APIError.generate(502, { message: 'Bad gateway' }, undefined, new Headers());
85 + const error = badGatewayError({ message: 'Bad gateway' }, '502 {"message":"Bad gateway"}');
86
87 expect(extractApiErrorDetails(error)).toMatchObject({
88 message: error.message,
@@ -53,17 +92,67 @@ describe('extractApiErrorDetails', () => {
92 });
93 });
94
56 - it('reports a connection error without a status', () => {
57 - const details = extractApiErrorDetails(new APIConnectionError({ message: 'offline' }));
95 + it('falls back to the status-prefixed message when the body is not JSON', () => {
96 + const error = badGatewayError(undefined, '502 status code (no body)');
97
59 - expect(details?.status).toBeUndefined();
60 - expect(details?.message).toBe('offline');
98 + expect(extractApiErrorDetails(error)).toEqual({
99 + message: '502 status code (no body)',
100 + code: undefined,
101 + slug: undefined,
102 + status: 502,
103 + request_id: undefined,
104 + suggested_fix: undefined,
105 + });
106 + });
107 +
108 + it('reports no details for a connection error', () => {
109 + expect(extractApiErrorDetails(connectionError('fetch failed'))).toBeUndefined();
110 });
111
63 - it('returns undefined when no APIError is in the chain', () => {
112 + it('returns undefined when no status error is in the chain', () => {
113 expect(extractApiErrorDetails({ error: envelope.error })).toBeUndefined();
114 expect(extractApiErrorDetails(new Error('plain'))).toBeUndefined();
115 expect(extractApiErrorDetails(undefined)).toBeUndefined();
116 expect(extractApiErrorDetails('plain string')).toBeUndefined();
117 });
118 });
119 +
120 +describe('extractMessage', () => {
121 + it('reads the envelope message', () => {
122 + expect(extractMessage(rateLimitError(undefined))).toBe('Rate limited');
123 + });
124 +
125 + it('reads the message of a body that is not the envelope', () => {
126 + const error = badGatewayError({ message: 'Bad gateway' }, '502 {"message":"Bad gateway"}');
127 +
128 + expect(extractMessage(error)).toBe('Bad gateway');
129 + });
130 +
131 + it('reports a response that failed decoding by operation and request id, with the remedy', () => {
132 + const clientError = new DecodeError({
133 + message: "The response body does not match the schema of 'toolRouter.session.toolkits'.",
134 + method: 'GET',
135 + url: 'https://backend.composio.dev/api/v3.1/tool_router/session/{session_id}/toolkits',
136 + status: 200,
137 + requestId: 'req_toolkits',
138 + operation: 'toolRouter.session.toolkits',
139 + issues: [{ path: ['items', 0, 'slug'], kind: 'MissingKey' }],
140 + });
141 +
142 + expect(extractMessage({ cause: clientError })).toBe(
143 + "The API response for 'toolRouter.session.toolkits' is not in the shape this version of the CLI expects (request id: req_toolkits).\nUpgrade the CLI, then retry:\n> composio upgrade"
144 + );
145 + });
146 +
147 + it('reads the transport text of a connection error', () => {
148 + const error = connectionError('fetch failed: connect ECONNREFUSED 127.0.0.1:1');
149 +
150 + expect(extractMessage(error)).toBe('fetch failed: connect ECONNREFUSED 127.0.0.1:1');
151 + });
152 +
153 + it('falls back to the status-prefixed message when the body is not JSON', () => {
154 + const error = badGatewayError(undefined, '502 status code (no body)');
155 +
156 + expect(extractMessage(error)).toBe('502 status code (no body)');
157 + });
158 +});