@devries-cameron20 / composio Mirror · read-only / commits / 632d49b71
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): validate API responses only where a call asks for it (#4856)

This PR: - is rebased onto `next` after https://github.com/ComposioHQ/composio/pull/4855 and https://github.com/ComposioHQ/composio/pull/4898 merged; its two own commits remain - makes client response validation opt-in: a read passes the `validated` request option (`src/services/composio-request.ts`) when the command uses the response through the client's types; every other call sends nothing extra - gives the client its full `schemaLoaders` table and deletes the hand-kept `composio-schema-loaders.ts`, its test, about 45 `decode: false` opt-outs, and the test-client guard that mirrored the client's pre-dispatch check - keeps validation on exactly the reads `next` validates since https://github.com/ComposioHQ/composio/pull/4878: `org.list`, `org.consumer.listConnectedToolkits` and `cli.realtime.credentials`; the drift-tolerant reads that PR made lenient (`logs.tools.*`, `logs.triggers.*`, `tools.list`, `tools.retrieve`, `org.project.list`, `toolRouter.session.search`, `toolRouter.session.toolkits`, `connectedAccounts.list`, `triggerInstances.listActive`) stay lenient, now by passing nothing - makes `getFor` take an org and a project together or neither (`ClientScope`); a scope with only an org used to compile and silently send no org header - adds lint bans on importing `make` or the client layers from `@composio/client/effect` outside `composio-clients.ts`, and on the `.js`/`.mjs` spellings of `@composio/client/pagination` - updates the contributor guidance in `ts/packages/cli/AGENTS.md` - adds `optionalParams` (`src/utils/optional-params.ts`), which turns a record of optional flags into request parameters in one call; the two `logs` list calls use it (review feedback) ## Context Adding an API call used to need one of two things nobody would guess: a new entry in a loader table, or `decode: false`, with a failure before dispatch when both were missing. Now a call needs neither, and validation is one visible word at the call sites that want it. Cost of shipping the full schema table, measured on the built binary: about +3 ms startup and +198 KB. No output change: after the rebase onto `next`, `pnpm typecheck` passes, the CLI suite passes (151 files, 1668 passed, 1 skipped; 18 exemptions), and `oxlint` is clean. Before this rebase, a live run of 23 read-only commands matched the pre-refactor baseline (22 byte-identical, 1 differing only in a request id). ## Unapplied review findings From a full code review of the rebased head (run `20261015-185607-0daee430`, seven reviewers, validator confirmed all four). Left for a decision because each goes beyond the rebase this round owns: - [ ] P2 — `ts/packages/cli/src/commands/listen.cmd.ts:709` (and `triggers/commands/triggers.listen.cmd.ts:339`) — the new AGENTS.md sentence says a `DecodeError` reaches the user with the operation, request id and upgrade hint, but the listen path wraps the validated `cli.realtime.credentials` failure in `TriggerRealtimeSubscriptionError` and prints only the network/login hint. Pre-existing path; either report `describeDecodeError(error.cause)` there or narrow the sentence. - [ ] P2 — `ts/packages/cli/src/services/composio-clients.ts:511` — two of the three validated reads (`cli.realtime.credentials`, `org.consumer.listConnectedToolkits`) have no test that a misshapen body fails with `DecodeError`; dropping `validated` from either would pass the suite. Mirror the `org.list` case in `composio-clients.test.ts:175-194`. - [ ] P2 — `ts/packages/cli/test/__utils__/services/test-layer.ts:1234` — with the pre-dispatch guard gone, a shadow ignores `decode: true`, so a `validated` added to a drift-tolerant read is decodable in production but invisible to `TestLayer` suites; the comment at :1222-1223 still claims `decode` is honoured. Make the shadow run the operation's `schemaLoaders` entry when `decode === true`, or drop the comment. - [ ] P3 — `.oxlintrc.json:261` — the `tool-input-validation.ts` override re-declares `no-restricted-imports` without the new `@composio/client/effect` `importNames` and `pagination.js/.mjs` entries, so the ban the AGENTS.md sentence calls "anywhere but `composio-clients.ts`" has one gap (no violation today). Applied during the review round: prettier on `create-tool-router-session.ts` and `tool-file-uploads.ts`, and the unused `Predicate` import in `test-layer.ts` (all three were rebase artifacts).

Alberto Schiabel committed Oct 15, 2026 at 20:32 UTC 632d49b71f1b4794ce7f62de4504db5d5a6df388
37 files changed +346 -431
.oxlintrc.json
+15
@@ -166,6 +166,21 @@
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 + "name": "@composio/client/pagination.js",
172 + "allowTypeImports": true,
173 + "message": "Call the API through the client from @composio/client/effect, obtained from ComposioClientSingleton. Type-only imports are allowed."
174 + },
175 + {
176 + "name": "@composio/client/pagination.mjs",
177 + "allowTypeImports": true,
178 + "message": "Call the API through the client from @composio/client/effect, obtained from ComposioClientSingleton. Type-only imports are allowed."
179 + },
180 + {
181 + "name": "@composio/client/effect",
182 + "importNames": ["make", "layer", "layerConfig", "layerFetch"],
183 + "message": "Get the client from ComposioClientSingleton, which scopes it to the user, org and project and counts its requests."
184 }
185 ],
186 "patterns": [
ts/packages/cli/AGENTS.md
+2 -2
@@ -116,7 +116,7 @@ test/src/commands/<group>/<shared-module>.test.ts group helper
116 | `JsPackageManagerDetector` | Detects npm/pnpm/yarn/bun for install instructions |
117 | `UpgradeBinary` | Fetches latest release from GitHub, downloads and replaces binary |
118
119 -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 client construction, the two repositories, and the `collectAll` and `sortBySlug` helpers the catalog fetches share. 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, `handleClientApiError` (`src/effects/handle-http-error.ts`), applied with `Effect.catchTag(CLIENT_API_ERROR_TAGS, …)`; the tag list lives in `src/services/composio-errors.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. (`src/services/agents.ts` also calls `fetch`, against the agents service at agents.composio.dev rather than the Composio backend.) 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`.
119 +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 client construction, the two repositories, and the `collectAll` and `sortBySlug` helpers the catalog fetches share. 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 `validated` 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, `handleClientApiError` (`src/effects/handle-http-error.ts`), applied with `Effect.catchTag(CLIENT_API_ERROR_TAGS, …)`; the tag list lives in `src/services/composio-errors.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. (`src/services/agents.ts` also calls `fetch`, against the agents service at agents.composio.dev rather than the Composio backend.) oxlint rejects value imports of the `@composio/client` root and `@composio/client/pagination` from CLI `src/`; type-only imports are allowed. It also rejects importing `make` or the client layers from `@composio/client/effect` anywhere but `composio-clients.ts`, and `getFor` takes an org and a project together or neither, because the two headers are only sent as a pair. Client errors are classified for display by `src/utils/api-error-extraction.ts`.
120
121 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.
122
@@ -211,7 +211,7 @@ Each `Arr.bind` adds one independent axis to the generated cases.
211
212 - 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.
213 - 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.
214 -- 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 a read only where the CLI consumes the whole response through the client's types and no field of it may drift: `cli.realtime.credentials` (every field feeds the realtime connection), `org.list` (organization ids and names for login), and `org.consumer.listConnectedToolkits` (a list of slugs). Those three are the loader table in `src/services/composio-schema-loaders.ts`; a mismatch fails with the client's `DecodeError`. Every other typed call passes `undecoded` (`decode: false`): calls that are not reads, because failing after the server acted would invite a retry that repeats the side effect; reads the CLI validates with its own schema; and reads that must tolerate drift because the CLI consumes a few fields of a response whose client schema fixes enums or requires fields the CLI never reads (`logs.tools.*`, `logs.triggers.*`, `tools.list`, `tools.retrieve`, `org.project.list`, `toolRouter.session.search`, `toolRouter.session.toolkits`, `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 and saying in its doc comment why the CLI cannot tolerate drift there. 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).
214 +- 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 decode with the CLI schema, failing with `services/HttpDecodingError`. The client validates a response against its own generated schema only when the call passes the `validated` request option (`src/services/composio-request.ts`); a mismatch fails with the client's `DecodeError`, which the CLI reports with the operation, the request id, and an upgrade hint. Pass `validated` only on a read the CLI consumes whole through the client's types, where no field may drift: `cli.realtime.credentials` (every field feeds the realtime connection), `org.list` (organization ids and names for login), and `org.consumer.listConnectedToolkits` (a list of slugs). Every other typed call leaves it off: calls that are not reads, because failing after the server acted would invite a retry that repeats the side effect; reads the CLI validates with its own schema; and reads that must tolerate drift because the CLI consumes a few fields of a response whose client schema fixes enums or requires fields the CLI never reads (`logs.tools.*`, `logs.triggers.*`, `tools.list`, `tools.retrieve`, `org.project.list`, `toolRouter.session.search`, `toolRouter.session.toolkits`, `connectedAccounts.list`, which tolerates unknown statuses, and `triggerInstances.listActive`, whose page counts the CLI defaults). Adding a validated read means saying in its doc comment why the CLI cannot tolerate drift there. 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).
215 - 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 — handler-level validation raises `CommandInputError` from `src/commands/errors.ts` (built with `commandInputError('<command>')`, carrying `command`, `message`, and the `option` at fault), not a hand-built `CliError`. It, `NotLoggedInError`, and `ProjectResolutionError` are the `UsageFailure` union (`isUsageFailure` in `errors.ts`): `cli-main.ts` prints the message as one line and exits 1, with no defect banner.
216 - 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.
217
ts/packages/cli/lint-boundaries.json
+7
@@ -1,4 +1,11 @@
1 {
2 + "src/services/composio-clients.ts": [
3 + {
4 + "rule": "no-restricted-imports",
5 + "reason": "this module is the one place the client is built",
6 + "target": "make as makeComposioClient,"
7 + }
8 + ],
9 "src/services/detached-process.ts": [
10 {
11 "rule": "no-restricted-imports",
ts/packages/cli/src/commands/connected-accounts/commands/connected-accounts.link.cmd.ts
+25 -38
@@ -154,7 +154,7 @@ const waitForActiveConnection = (
154 Effect.retry(
155 Effect.gen(function* () {
156 const account = yield* client.connectedAccounts
157 - .retrieve(connectedAccountId, { decode: false })
157 + .retrieve(connectedAccountId)
158 .pipe(
159 failedWith(
160 ConnectedAccountsRequestError,
@@ -308,16 +308,13 @@ const listActiveConnectedAccounts = (params: {
308 readonly toolkitSlug?: string;
309 readonly authConfigId?: string;
310 }) =>
311 - params.client.connectedAccounts.list(
312 - {
313 - user_ids: [params.userId],
314 - toolkit_slugs: params.toolkitSlug ? [params.toolkitSlug] : undefined,
315 - auth_config_ids: params.authConfigId ? [params.authConfigId] : undefined,
316 - statuses: ['ACTIVE'],
317 - limit: 100,
318 - },
319 - { decode: false }
320 - );
311 + params.client.connectedAccounts.list({
312 + user_ids: [params.userId],
313 + toolkit_slugs: params.toolkitSlug ? [params.toolkitSlug] : undefined,
314 + auth_config_ids: params.authConfigId ? [params.authConfigId] : undefined,
315 + statuses: ['ACTIVE'],
316 + limit: 100,
317 + });
318
319 const formatExistingAccountLabels = (
320 items: ReadonlyArray<{
@@ -516,15 +513,12 @@ const handleListConnectedAccounts = (params: {
513 const accounts = yield* params.ui.withSpinner(
514 `Listing connected accounts for "${toolkitSlug}"...`,
515 client.connectedAccounts
519 - .list(
520 - {
521 - toolkit_slugs: [toolkitSlug],
522 - user_ids: [resolvedUserId.value],
523 - statuses: ['ACTIVE'],
524 - limit: 100,
525 - },
526 - { decode: false }
527 - )
516 + .list({
517 + toolkit_slugs: [toolkitSlug],
518 + user_ids: [resolvedUserId.value],
519 + statuses: ['ACTIVE'],
520 + limit: 100,
521 + })
522 .pipe(
523 failedWith(
524 ConnectedAccountsRequestError,
@@ -667,14 +661,11 @@ const handleLegacyAuthConfigLink = (params: {
661 const linkOpt = yield* params.ui
662 .withSpinner(
663 'Creating link session...',
670 - client.link.create(
671 - {
672 - auth_config_id: params.authConfigId,
673 - user_id: resolvedUserId.value,
674 - ...(Option.isSome(normalizedAlias) && { alias: normalizedAlias.value }),
675 - },
676 - { decode: false }
677 - )
664 + client.link.create({
665 + auth_config_id: params.authConfigId,
666 + user_id: resolvedUserId.value,
667 + ...(Option.isSome(normalizedAlias) && { alias: normalizedAlias.value }),
668 + })
669 )
670 .pipe(
671 Effect.asSome,
@@ -873,16 +864,12 @@ const runConnectedAccountsLink = (params: {
864 : undefined,
865 });
866 return yield* client.toolRouter.session
876 - .link(
877 - sessionId,
878 - {
879 - toolkit: toolkitSlug,
880 - ...(Option.isSome(normalizedAliasOption) && {
881 - alias: normalizedAliasOption.value,
882 - }),
883 - },
884 - { decode: false }
885 - )
867 + .link(sessionId, {
868 + toolkit: toolkitSlug,
869 + ...(Option.isSome(normalizedAliasOption) && {
870 + alias: normalizedAliasOption.value,
871 + }),
872 + })
873 .pipe(
874 failedWith(
875 ConnectedAccountsRequestError,
ts/packages/cli/src/commands/connected-accounts/commands/connected-accounts.list.cmd.ts
+6 -9
@@ -70,15 +70,12 @@ export const connectedAccountsCmd$List = Command.make(
70 const rawResult = yield* ui.withSpinner(
71 'Fetching connected accounts...',
72 client.connectedAccounts
73 - .list(
74 - {
75 - toolkit_slugs: toolkitSlugs,
76 - user_ids: Option.isSome(userId) ? [userId.value] : undefined,
77 - statuses: Option.isSome(status) ? [status.value] : undefined,
78 - limit: clampLimit(limit),
79 - },
80 - { decode: false }
81 - )
73 + .list({
74 + toolkit_slugs: toolkitSlugs,
75 + user_ids: Option.isSome(userId) ? [userId.value] : undefined,
76 + statuses: Option.isSome(status) ? [status.value] : undefined,
77 + limit: clampLimit(limit),
78 + })
79 .pipe(failedWith(ConnectedAccountsListRequestError, 'Failed to list connected accounts.'))
80 );
81 const result = yield* decodeConnectedAccountListWithFallback(rawResult);
ts/packages/cli/src/commands/connections/commands/connections.list.cmd.ts
+5 -8
@@ -76,14 +76,11 @@ export const connectionsCmd$List = Command.make('list', { toolkit }, ({ toolkit
76 projectId: resolvedProject.projectId,
77 });
78 const rawResult = yield* client.connectedAccounts
79 - .list(
80 - {
81 - toolkit_slugs: toolkitSlug ? [toolkitSlug] : undefined,
82 - user_ids: [consumerUserId],
83 - limit: 1000,
84 - },
85 - { decode: false }
86 - )
79 + .list({
80 + toolkit_slugs: toolkitSlug ? [toolkitSlug] : undefined,
81 + user_ids: [consumerUserId],
82 + limit: 1000,
83 + })
84 .pipe(failedWith(ConnectionsListRequestError, 'Failed to list connections.'));
85 const result = yield* decodeConnectedAccountListWithFallback(rawResult);
86 const permissionSnapshot = yield* getConsumerPermissionSnapshot({
ts/packages/cli/src/commands/connections/commands/connections.remove.cmd.ts
+2 -2
@@ -110,7 +110,7 @@ export const connectionsCmd$Remove = Command.make('remove', { account }, ({ acco
110 const rawResult = yield* ui.withSpinner(
111 'Fetching connections...',
112 client.connectedAccounts
113 - .list({ user_ids: [consumerUserId], limit: 1000 }, { decode: false })
113 + .list({ user_ids: [consumerUserId], limit: 1000 })
114 .pipe(failedWith(ConnectionsRemovalRequestError, 'Failed to list connections.'))
115 );
116 const result = yield* decodeConnectedAccountListWithFallback(rawResult);
@@ -137,7 +137,7 @@ export const connectionsCmd$Remove = Command.make('remove', { account }, ({ acco
137 yield* ui.withSpinner(
138 `Removing ${resolved.toolkit.slug} connection...`,
139 client.connectedAccounts
140 - .delete(resolved.id, undefined, { decode: false })
140 + .delete(resolved.id)
141 .pipe(
142 failedWith(
143 ConnectionsRemovalRequestError,
ts/packages/cli/src/commands/listen.cmd.ts
+22 -27
@@ -100,22 +100,20 @@ const disableTemporaryTrigger = (params: {
100 slug: string;
101 triggerId: string;
102 }) =>
103 - params.client.triggerInstances.manage
104 - .update(params.triggerId, { status: 'disable' }, { decode: false })
105 - .pipe(
106 - Effect.mapError(
107 - cause =>
108 - new ListenCommandError({
109 - reason: 'disable_trigger',
110 - // "Error: " is how these messages have always introduced the client's failure.
111 - message: `Failed to disable temporary trigger "${params.triggerId}": Error: ${cause.message}`,
112 - slug: params.slug,
113 - cause,
114 - })
115 - ),
116 - Effect.tapError(error => params.ui.log.warn(error.message)),
117 - Effect.ignore
118 - );
103 + params.client.triggerInstances.manage.update(params.triggerId, { status: 'disable' }).pipe(
104 + Effect.mapError(
105 + cause =>
106 + new ListenCommandError({
107 + reason: 'disable_trigger',
108 + // "Error: " is how these messages have always introduced the client's failure.
109 + message: `Failed to disable temporary trigger "${params.triggerId}": Error: ${cause.message}`,
110 + slug: params.slug,
111 + cause,
112 + })
113 + ),
114 + Effect.tapError(error => params.ui.log.warn(error.message)),
115 + Effect.ignore
116 + );
117
118 const isProjectEventType = (value: string): boolean => value.startsWith('composio.');
119
@@ -160,7 +158,7 @@ const assertTriggerTypeExists = (params: {
158 slug: string;
159 toolkitSlug?: string;
160 }) =>
163 - params.client.triggersTypes.retrieve(params.slug, undefined, { decode: false }).pipe(
161 + params.client.triggersTypes.retrieve(params.slug).pipe(
162 Effect.catchTag(
163 '@composio/client/NotFoundError',
164 cause =>
@@ -197,15 +195,12 @@ const resolveConnectedAccountIdForTrigger = (params: {
195 }
196
197 const connectedAccounts = yield* params.client.connectedAccounts
200 - .list(
201 - {
202 - toolkit_slugs: [toolkitSlug],
203 - user_ids: [params.consumerUserId],
204 - statuses: ['ACTIVE'],
205 - limit: 100,
206 - },
207 - { decode: false }
208 - )
198 + .list({
199 + toolkit_slugs: [toolkitSlug],
200 + user_ids: [params.consumerUserId],
201 + statuses: ['ACTIVE'],
202 + limit: 100,
203 + })
204 .pipe(
205 Effect.mapError(
206 cause =>
@@ -542,7 +537,7 @@ export const listenCmd = Command.make(
537 yield* Effect.acquireUseRelease(
538 listeningToProjectEvent
539 ? Effect.succeed<null | { trigger_id: string }>(null)
545 - : client.triggerInstances.upsert(slug, createParams, { decode: false }).pipe(
540 + : client.triggerInstances.upsert(slug, createParams).pipe(
541 Effect.mapError(
542 cause =>
543 new ListenCommandError({
ts/packages/cli/src/commands/logs/commands/logs.tools.cmd.ts
+9 -13
@@ -3,8 +3,8 @@ import { Effect, Option } from 'effect';
3 import { failedWith, requestError } from 'src/effects/request-error';
4 import { TerminalUI } from 'src/services/terminal-ui';
5 import { ComposioClientSingleton } from 'src/services/composio-clients';
6 -import { undecoded } from 'src/services/composio-request';
6 import { clampLimit } from 'src/ui/clamp-limit';
7 +import { optionalParams } from 'src/utils/optional-params';
8 import { parseCsv } from 'src/commands/triggers/parse-csv';
9 import { formatToolLogInfo, formatToolLogsTable } from '../format';
10 import { commandHintStep } from 'src/services/command-hints';
@@ -187,7 +187,7 @@ export const logsCmd$Tools = Command.make(
187 const toolLog = yield* ui.withSpinner(
188 `Fetching tool log "${toolLogId}"...`,
189 client.logs.tools
190 - .retrieve(toolLogId, undecoded)
190 + .retrieve(toolLogId)
191 .pipe(failedWith(ToolLogsRequestError, `Failed to fetch tool log "${toolLogId}".`))
192 );
193
@@ -201,17 +201,13 @@ export const logsCmd$Tools = Command.make(
201 const response = yield* ui.withSpinner(
202 'Fetching tool logs...',
203 client.logs.tools
204 - .list(
205 - {
206 - cursor: Option.getOrUndefined(cursor) ?? null,
207 - from: Option.getOrUndefined(from),
208 - to: Option.getOrUndefined(to),
209 - limit: clampedLimit,
210 - case_sensitive: caseSensitive,
211 - search_params: shorthandSearchParams.length > 0 ? shorthandSearchParams : undefined,
212 - },
213 - undecoded
214 - )
204 + .list({
205 + ...optionalParams({ from, to }),
206 + cursor: Option.getOrUndefined(cursor) ?? null,
207 + limit: clampedLimit,
208 + case_sensitive: caseSensitive,
209 + search_params: shorthandSearchParams.length > 0 ? shorthandSearchParams : undefined,
210 + })
211 .pipe(failedWith(ToolLogsRequestError, 'Failed to fetch tool logs.'))
212 );
213
ts/packages/cli/src/commands/logs/commands/logs.triggers.cmd.ts
+8 -15
@@ -3,8 +3,8 @@ import { Effect, Option } from 'effect';
3 import { failedWith, requestError } from 'src/effects/request-error';
4 import { TerminalUI } from 'src/services/terminal-ui';
5 import { ComposioClientSingleton } from 'src/services/composio-clients';
6 -import { undecoded } from 'src/services/composio-request';
6 import { clampLimit } from 'src/ui/clamp-limit';
7 +import { optionalParams } from 'src/utils/optional-params';
8 import { parseCsv } from 'src/commands/triggers/parse-csv';
9 import { formatTriggerLogInfo, formatTriggerLogsTable } from '../format';
10 import { decodeTriggerLogRecord } from '../trigger-log-record';
@@ -152,7 +152,7 @@ export const logsCmd$Triggers = Command.make(
152 const triggerLog = yield* ui.withSpinner(
153 `Fetching trigger log "${triggerLogId}"...`,
154 client.logs.triggers
155 - .retrieve(triggerLogId, undecoded)
155 + .retrieve(triggerLogId)
156 .pipe(
157 failedWith(TriggerLogsRequestError, `Failed to fetch trigger log "${triggerLogId}".`)
158 )
@@ -170,19 +170,12 @@ export const logsCmd$Triggers = Command.make(
170 const response = yield* ui.withSpinner(
171 'Fetching trigger logs...',
172 client.logs.triggers
173 - .list(
174 - {
175 - cursor: Option.getOrUndefined(cursor),
176 - from: Option.getOrUndefined(from),
177 - to: Option.getOrUndefined(to),
178 - limit: clampedLimit,
179 - time: Option.getOrUndefined(time),
180 - search: Option.getOrUndefined(search),
181 - include_payload: includePayload,
182 - search_params: shorthandSearchParams.length > 0 ? shorthandSearchParams : undefined,
183 - },
184 - undecoded
185 - )
173 + .list({
174 + ...optionalParams({ cursor, from, to, time, search }),
175 + limit: clampedLimit,
176 + include_payload: includePayload,
177 + search_params: shorthandSearchParams.length > 0 ? shorthandSearchParams : undefined,
178 + })
179 .pipe(failedWith(TriggerLogsRequestError, 'Failed to fetch trigger logs.'))
180 );
181
ts/packages/cli/src/commands/proxy.cmd.ts
+1 -1
@@ -365,7 +365,7 @@ export const proxyCmd = Command.make('proxy', {
365 // Never retry a proxied call: a retry after the upstream API
366 // already acted duplicates the side effect. The response is not
367 // validated either, for the same reason.
368 - { maxRetries: 0, decode: false }
368 + { maxRetries: 0 }
369 )
370 .pipe(
371 Effect.mapError(failed),
ts/packages/cli/src/commands/toolkits/commands/toolkits.info.cmd.ts
+1 -2
@@ -3,7 +3,6 @@ import { Effect, Option } from 'effect';
3 import { ComposioClientSingleton, ComposioToolkitsRepository } from 'src/services/composio-clients';
4 import { TerminalUI } from 'src/services/terminal-ui';
5 import { failedWith, requestError } from 'src/effects/request-error';
6 -import { undecoded } from 'src/services/composio-request';
6 import { resolveToolRouterSession } from 'src/effects/create-tool-router-session';
7 import { extractMessage } from 'src/utils/api-error-extraction';
8 import { ProjectContext } from 'src/services/project-context';
@@ -91,7 +90,7 @@ export const toolkitsCmd$Info = Command.make(
90 const { sessionId } = yield* resolveToolRouterSession(client, resolvedUserId.value);
91 const sessionToolkits = yield* client.toolRouter.session
92 // Only the first item is read, and only a few of its fields.
94 - .toolkits(sessionId, { toolkits: [slugValue] }, undecoded)
93 + .toolkits(sessionId, { toolkits: [slugValue] })
94 .pipe(
95 failedWith(ToolkitsInfoRequestError, `Failed to fetch toolkit "${slugValue}".`)
96 );
ts/packages/cli/src/commands/toolkits/commands/toolkits.list.cmd.ts
+5 -10
@@ -4,7 +4,6 @@ import { Effect, Option } from 'effect';
4 import { TerminalUI } from 'src/services/terminal-ui';
5 import { resolveToolRouterSession } from 'src/effects/create-tool-router-session';
6 import { ComposioClientSingleton, ComposioToolkitsRepository } from 'src/services/composio-clients';
7 -import { undecoded } from 'src/services/composio-request';
7 import { ProjectContext } from 'src/services/project-context';
8 import { ComposioUserContext } from 'src/services/user-context';
9 import { clampLimit } from 'src/ui/clamp-limit';
@@ -126,15 +125,11 @@ export const toolkitsCmd$List = Command.make(
125 // The session items only add connection status to the catalog rows,
126 // and a failed read is already a silent fallback.
127 sessionItems = yield* client.toolRouter.session
129 - .toolkits(
130 - sessionId,
131 - {
132 - search: Option.getOrUndefined(query),
133 - limit: clampedLimit,
134 - is_connected: Option.getOrUndefined(connected),
135 - },
136 - undecoded
137 - )
128 + .toolkits(sessionId, {
129 + search: Option.getOrUndefined(query),
130 + limit: clampedLimit,
131 + is_connected: Option.getOrUndefined(connected),
132 + })
133 .pipe(
134 Effect.map(r => r.items),
135 Effect.catch(error =>
ts/packages/cli/src/commands/toolkits/commands/toolkits.version.cmd.ts
+1 -1
@@ -24,7 +24,7 @@ export const toolkitsCmd$Version = Command.make('version', { slug }, ({ slug })
24 `Fetching versions for toolkit "${slug}"...`,
25 // Only the name, slug and version list are read, so a toolkit that
26 // lacks other catalog fields still prints its versions.
27 - client.toolkits.retrieve(slug, undefined, { decode: false })
27 + client.toolkits.retrieve(slug)
28 )
29 .pipe(
30 Effect.asSome,
ts/packages/cli/src/commands/tools/commands/tools.search.cmd.ts
+5 -10
@@ -13,7 +13,6 @@ import { formatToolsTable } from '../format';
13 import type { Tool } from 'src/models/tools';
14 import { ComposioUserContext } from 'src/services/user-context';
15 import { ComposioClientSingleton } from 'src/services/composio-clients';
16 -import { undecoded } from 'src/services/composio-request';
16 import { resolveCommandProject } from 'src/services/command-project';
17 import { commandHintExample, commandHintStep } from 'src/services/command-hints';
18 import { isRemoteCustomToolSlug } from 'src/utils/remote-custom-toolkit';
@@ -365,7 +364,7 @@ const runToolsSearch = (params: {
364 // The command reads a few of the search response's fields; the rest, enums
365 // among them, may change without this version of the CLI noticing.
366 const searchResponse = yield* client.toolRouter.session
368 - .search(sessionId, searchPayload, undecoded)
367 + .search(sessionId, searchPayload)
368 .pipe(failedWith(ToolsSearchRequestError, 'Failed to search tools.'));
369 const customToolSlugsMissingSchemas = Object.entries(searchResponse.tool_schemas)
370 .filter(([slug, schema]) => isRemoteCustomToolSlug(slug) && !schema.input_schema)
@@ -380,14 +379,10 @@ const runToolsSearch = (params: {
379 cause,
380 });
381 const schemaResponse = yield* client.toolRouter.session
383 - .executeMeta(
384 - sessionId,
385 - {
386 - slug: 'COMPOSIO_GET_TOOL_SCHEMAS',
387 - arguments: { tool_slugs: customToolSlugsMissingSchemas },
388 - },
389 - { decode: false }
390 - )
382 + .executeMeta(sessionId, {
383 + slug: 'COMPOSIO_GET_TOOL_SCHEMAS',
384 + arguments: { tool_slugs: customToolSlugsMissingSchemas },
385 + })
386 .pipe(Effect.mapError(schemasFailed));
387 if (schemaResponse.result_type === 'input_required') {
388 return yield* schemasFailed(
ts/packages/cli/src/effects/create-tool-router-session.ts
+18 -21
@@ -167,27 +167,24 @@ export const createToolRouterSessionContext = (
167 })
168 : undefined;
169 return yield* client.toolRouter.session
170 - .create(
171 - {
172 - user_id: userId,
173 - auth_configs: connectionContext.authConfigs,
174 - connected_accounts: connectionContext.connectedAccounts,
175 - manage_connections: { enable: options?.manageConnections ?? false },
176 - multi_account: options?.multiAccount
177 - ? {
178 - enable: options.multiAccount.enable,
179 - max_accounts_per_toolkit: options.multiAccount.maxAccountsPerToolkit,
180 - require_explicit_selection: options.multiAccount.requireExplicitSelection,
181 - }
182 - : undefined,
183 - toolkits: requestedToolkits.length > 0 ? { enable: [...requestedToolkits] } : undefined,
184 - instant: { return_instant_charge: true },
185 - experimental: permissionSnapshot?.enhancedControlsEnabled
186 - ? { link_url_overwrite: ENHANCED_LINK_URL_OVERWRITE }
187 - : undefined,
188 - },
189 - { decode: false }
190 - )
170 + .create({
171 + user_id: userId,
172 + auth_configs: connectionContext.authConfigs,
173 + connected_accounts: connectionContext.connectedAccounts,
174 + manage_connections: { enable: options?.manageConnections ?? false },
175 + multi_account: options?.multiAccount
176 + ? {
177 + enable: options.multiAccount.enable,
178 + max_accounts_per_toolkit: options.multiAccount.maxAccountsPerToolkit,
179 + require_explicit_selection: options.multiAccount.requireExplicitSelection,
180 + }
181 + : undefined,
182 + toolkits: requestedToolkits.length > 0 ? { enable: [...requestedToolkits] } : undefined,
183 + instant: { return_instant_charge: true },
184 + experimental: permissionSnapshot?.enhancedControlsEnabled
185 + ? { link_url_overwrite: ENHANCED_LINK_URL_OVERWRITE }
186 + : undefined,
187 + })
188 .pipe(
189 Effect.mapError(
190 cause =>
ts/packages/cli/src/services/composio-account.ts
+24 -23
@@ -9,7 +9,7 @@ import type { SessionRetrieveInfoResponse } from '@composio/client/resources/aut
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';
12 +import { decode, validated } from './composio-request';
13
14 /**
15 * Account, session-info, and consumer helpers
@@ -94,7 +94,7 @@ export const listOrganizations = (params: {
94 Effect.gen(function* () {
95 const clientSingleton = yield* ComposioClientSingleton;
96 const client = yield* clientSingleton.getFor({ userApiKey: params.apiKey });
97 - const response = yield* client.org.list({ limit: params.limit ?? 50 });
97 + const response = yield* client.org.list({ limit: params.limit ?? 50 }, validated);
98 const organizations = response.organizations.map(
99 (organization: OrgListResponse.Organization) =>
100 ({ id: organization.id, name: organization.name }) satisfies OrganizationSummary
@@ -123,7 +123,7 @@ export const listOrganizationProjects = (params: {
123 const client = yield* clientSingleton.getFor({ userApiKey: params.apiKey });
124 const response = yield* client.org.project.list(
125 { limit: params.limit ?? 50 },
126 - { ...undecoded, ...orgScopedOptions(params.orgId) }
126 + orgScopedOptions(params.orgId)
127 );
128 const projects = response.data.map(
129 (project: OrgProject) =>
@@ -153,7 +153,7 @@ export const listOrgProjects = (params: {
153 const client = yield* clientSingleton.getFor({ userApiKey: params.apiKey });
154 return yield* client.org.project.list(
155 { list_all_org_projects: true, limit: params.limit ?? 50 },
156 - { ...undecoded, ...orgScopedOptions(params.orgId) }
156 + orgScopedOptions(params.orgId)
157 );
158 });
159
@@ -174,7 +174,7 @@ export const getSessionInfo = (params: {
174 });
175 // Read through a few fields only, and called after login has already
176 // linked the session: drift in a field the CLI never reads must not fail it.
177 - const info = yield* client.auth.session.retrieveInfo(undecoded);
177 + const info = yield* client.auth.session.retrieveInfo();
178 return yield* requireSessionProject(info);
179 });
180
@@ -196,10 +196,7 @@ export const getSessionInfoByUserApiKey = (params: {
196 Effect.gen(function* () {
197 const clientSingleton = yield* ComposioClientSingleton;
198 const client = yield* clientSingleton.getFor({ userApiKey: params.userApiKey });
199 - const info = yield* client.auth.session.retrieveInfo({
200 - ...orgScopedOptions(params.orgId),
201 - ...undecoded,
202 - });
199 + const info = yield* client.auth.session.retrieveInfo(orgScopedOptions(params.orgId));
200 return yield* requireSessionProject(info);
201 });
202
@@ -278,10 +275,10 @@ export const resolveConsumerProject = (params: {
275 Effect.gen(function* () {
276 const clientSingleton = yield* ComposioClientSingleton;
277 const client = yield* clientSingleton.getFor({ userApiKey: params.apiKey });
281 - return yield* client.org.consumer.project.resolve(
282 - { 'x-user-api-key': params.apiKey, 'x-org-id': params.orgId },
283 - undecoded
284 - );
278 + return yield* client.org.consumer.project.resolve({
279 + 'x-user-api-key': params.apiKey,
280 + 'x-org-id': params.orgId,
281 + });
282 });
283
284 /**
@@ -305,11 +302,12 @@ export const getLatestToolVersion = (params: {
302 ...(params.orgId ? { 'x-org-id': params.orgId } : {}),
303 ...(params.projectId ? { 'x-project-id': params.projectId } : {}),
304 };
308 - const client = yield* clientSingleton.getFor({
309 - userApiKey: params.apiKey,
310 - orgId: params.orgId,
311 - projectId: params.projectId,
312 - });
305 + // The headers above carry whichever of the org and project is known.
306 + const client = yield* clientSingleton.getFor(
307 + params.orgId && params.projectId
308 + ? { userApiKey: params.apiKey, orgId: params.orgId, projectId: params.projectId }
309 + : { userApiKey: params.apiKey }
310 + );
311 const payload = yield* client.get(
312 `/api/v3/tools/${encodeURIComponent(params.toolSlug)}/get_latest_version`,
313 { headers }
@@ -325,11 +323,14 @@ export const getConsumerConnectedToolkits = (params: {
323 Effect.gen(function* () {
324 const clientSingleton = yield* ComposioClientSingleton;
325 const client = yield* clientSingleton.getFor({ userApiKey: params.apiKey });
328 - return yield* client.org.consumer.listConnectedToolkits({
329 - user_id: params.consumerUserId,
330 - 'x-user-api-key': params.apiKey,
331 - 'x-org-id': params.orgId,
332 - });
326 + return yield* client.org.consumer.listConnectedToolkits(
327 + {
328 + user_id: params.consumerUserId,
329 + 'x-user-api-key': params.apiKey,
330 + 'x-org-id': params.orgId,
331 + },
332 + validated
333 + );
334 });
335
336 export class DeveloperProjectNotFoundError extends Data.TaggedError(
ts/packages/cli/src/services/composio-clients.ts
+39 -35
@@ -14,6 +14,7 @@ import * as Str from 'effect/String';
14 import type { Cause } from 'effect';
15 import { FetchHttpClient, HttpClient } from 'effect/http';
16 import {
17 + // eslint-disable-next-line no-restricted-imports -- this module is the one place the client is built
18 make as makeComposioClient,
19 VERSION as clientLibraryVersion,
20 type ComposioClientShape,
@@ -35,9 +36,9 @@ import { ProjectContext } from './project-context';
36 import { makeClientMetricsCollector, type ClientMetricsCollector } from './composio-client-metrics';
37 import { ComposioClientConfigurationError, type ClientError } from './composio-errors';
38 import { isClientConfigurationError } from 'src/utils/api-error-extraction';
38 -import { MAX_CONCURRENT_REQUESTS_PER_ENDPOINT, decode, undecoded } from './composio-request';
39 +import { MAX_CONCURRENT_REQUESTS_PER_ENDPOINT, decode, validated } from './composio-request';
40 import { lookupOperations, resourceOperations } from './composio-resource-operations';
40 -import { composioSchemaLoaders } from './composio-schema-loaders';
41 +import { schemaLoaders } from '@composio/client/effect/schemas';
42 import {
43 InvalidToolkitsError,
44 invalidToolkitOn404,
@@ -109,6 +110,15 @@ const buildDefaultHeaders = (params: {
110 return defaultHeaders;
111 };
112
113 +/**
114 + * Whose requests a client sends. The org and project headers are only sent
115 + * together, so a scope names both or neither.
116 + */
117 +export type ClientScope = { readonly userApiKey?: string } & (
118 + | { readonly orgId: string; readonly projectId: string }
119 + | { readonly orgId?: undefined; readonly projectId?: undefined }
120 +);
121 +
122 /**
123 * Shape exposed by {@link ComposioClientSingleton}.
124 */
@@ -121,11 +131,9 @@ export interface ComposioClientSingletonShape {
131 /**
132 * The client for an explicit scope. `userApiKey` defaults to the user's key.
133 */
124 - readonly getFor: (params: {
125 - userApiKey?: string;
126 - orgId?: string;
127 - projectId?: string;
128 - }) => Effect.Effect<ComposioClientShape, ClientBuildError | NoSuchElementError>;
134 + readonly getFor: (
135 + params: ClientScope
136 + ) => Effect.Effect<ComposioClientShape, ClientBuildError | NoSuchElementError>;
137 /**
138 * Returns a snapshot of the accumulated metrics (total bytes received and
139 * request count) across every client this singleton built.
@@ -143,11 +151,11 @@ export interface ComposioClientSingletonShape {
151 export type ClientBuildError = ConfigurationError | ComposioClientConfigurationError;
152
153 /**
146 - * The scope a client is built for. A plain record is compared and hashed
147 - * structurally by `Equal` and `Hash`, so two lookups with the same fields
148 - * resolve to the same cache entry.
154 + * The scope a client is built for, with the user key resolved. A plain record
155 + * is compared and hashed structurally by `Equal` and `Hash`, so two lookups
156 + * with the same fields resolve to the same cache entry.
157 */
150 -interface ClientScope {
158 +interface ResolvedClientScope {
159 readonly userApiKey: string | undefined;
160 readonly orgId: string | undefined;
161 readonly projectId: string | undefined;
@@ -170,14 +178,14 @@ const makeComposioClientSingleton = (metrics: ClientMetricsCollector) =>
178 const projectContextOpt = yield* Effect.serviceOption(ProjectContext);
179 const httpClient = yield* HttpClient.HttpClient;
180
173 - const buildClient = (scope: ClientScope) =>
181 + const buildClient = (scope: ResolvedClientScope) =>
182 Effect.gen(function* () {
183 const cliSessionId = yield* getCurrentCwdSessionId();
184
185 return yield* Effect.try({
186 try: () =>
179 - // Responses are validated against the CLI's loader table unless a
180 - // call passes `decode: false`.
187 + // A call that passes `decode: true` has its response validated
188 + // against the client's schema for that operation.
189 makeComposioClient(
190 {
191 apiKey: null,
@@ -193,8 +201,7 @@ const makeComposioClientSingleton = (metrics: ClientMetricsCollector) =>
201 projectId: scope.projectId,
202 cliSessionId,
203 }),
196 - decode: true,
197 - schemas: composioSchemaLoaders,
204 + schemas: schemaLoaders,
205 },
206 httpClient
207 ),
@@ -222,7 +229,7 @@ const makeComposioClientSingleton = (metrics: ClientMetricsCollector) =>
229
230 // `ctx.data` is read per call: a login or logout changes the user key,
231 // and with it the scope.
225 - const getFor = (params?: { userApiKey?: string; orgId?: string; projectId?: string }) =>
232 + const getFor = (params?: ClientScope) =>
233 Effect.suspend(() =>
234 Cache.get(clients, {
235 userApiKey: normalizeApiKey(params?.userApiKey ?? Option.getOrUndefined(ctx.data.apiKey)),
@@ -247,11 +254,7 @@ const makeComposioClientSingleton = (metrics: ClientMetricsCollector) =>
254 }),
255 });
256 }),
250 - getFor: Effect.fn(function* (params: {
251 - userApiKey?: string;
252 - orgId?: string;
253 - projectId?: string;
254 - }) {
257 + getFor: Effect.fn(function* (params: ClientScope) {
258 return yield* getFor(params);
259 }),
260 getMetrics: metrics.getMetrics,
@@ -299,12 +302,12 @@ const makeComposioToolkitsRepository = Effect.gen(function* () {
302
303 const listToolkits = (managedBy?: 'project', scope?: ToolkitProjectScope) =>
304 collectAll(scope ? clientSingleton.getFor(scope) : client, c =>
302 - c.toolkits.listStream({ limit: MAX_PAGE_SIZE, managed_by: managedBy }, undecoded)
305 + c.toolkits.listStream({ limit: MAX_PAGE_SIZE, managed_by: managedBy })
306 ).pipe(Effect.flatMap(decode(Toolkits)), Effect.map(sortBySlug));
307
308 const getToolkitDetailed = (slug: string) =>
309 client.pipe(
307 - Effect.flatMap(c => c.toolkits.retrieve(slug, undefined, undecoded)),
310 + Effect.flatMap(c => c.toolkits.retrieve(slug)),
311 Effect.flatMap(decode(ToolkitDetailed))
312 );
313
@@ -341,7 +344,7 @@ const makeComposioToolkitsRepository = Effect.gen(function* () {
344 ).pipe(Effect.map(sortBySlug));
345
346 const listTools = (query: { toolkit_slug?: string; toolkit_versions: string }) =>
344 - collectAll(client, c => c.tools.listStream({ ...query, limit: MAX_PAGE_SIZE }, undecoded)).pipe(
347 + collectAll(client, c => c.tools.listStream({ ...query, limit: MAX_PAGE_SIZE })).pipe(
348 Effect.flatMap(decode(Tools))
349 );
350
@@ -355,7 +358,7 @@ const makeComposioToolkitsRepository = Effect.gen(function* () {
358 */
359 getToolsAsEnums: () =>
360 client.pipe(
358 - Effect.flatMap(c => c.tools.retrieveEnum(undecoded)),
361 + Effect.flatMap(c => c.tools.retrieveEnum()),
362 Effect.flatMap(decode(ToolsAsEnums))
363 ),
364 /**
@@ -385,7 +388,7 @@ const makeComposioToolkitsRepository = Effect.gen(function* () {
388 */
389 getTriggerTypesAsEnums: () =>
390 client.pipe(
388 - Effect.flatMap(c => c.triggersTypes.retrieveEnum(undecoded)),
391 + Effect.flatMap(c => c.triggersTypes.retrieveEnum()),
392 Effect.flatMap(decode(TriggerTypesAsEnums))
393 ),
394 /**
@@ -395,10 +398,10 @@ const makeComposioToolkitsRepository = Effect.gen(function* () {
398 */
399 getTriggerTypes: (toolkitSlugs?: ReadonlyArray<string>) =>
400 collectAll(client, c =>
398 - c.triggersTypes.listStream(
399 - { limit: MAX_PAGE_SIZE, toolkit_slugs: toolkitSlugs ? [...toolkitSlugs] : undefined },
400 - undecoded
401 - )
401 + c.triggersTypes.listStream({
402 + limit: MAX_PAGE_SIZE,
403 + toolkit_slugs: toolkitSlugs ? [...toolkitSlugs] : undefined,
404 + })
405 ).pipe(Effect.flatMap(decode(TriggerTypes)), Effect.map(sortBySlug)),
406 /**
407 * Validates that the given toolkit slugs are valid by comparing them against the list
@@ -493,7 +496,7 @@ const makeComposioSessionRepository = Effect.gen(function* () {
496 */
497 createSession: (params?: { scope?: 'user' | 'project' }) =>
498 client.pipe(
496 - Effect.flatMap(c => c.cli.createSession({ scope: params?.scope ?? 'user' }, undecoded)),
499 + Effect.flatMap(c => c.cli.createSession({ scope: params?.scope ?? 'user' })),
500 Effect.flatMap(decode(Session))
501 ),
502 /**
@@ -501,12 +504,13 @@ const makeComposioSessionRepository = Effect.gen(function* () {
504 */
505 getSession: (session: { id: string }) =>
506 client.pipe(
504 - Effect.flatMap(c => c.cli.getSession({ id: session.id }, undecoded)),
507 + Effect.flatMap(c => c.cli.getSession({ id: session.id })),
508 Effect.flatMap(decode(RetrievedSession))
509 ),
507 - getRealtimeCredentials: () => Effect.flatMap(client, c => c.cli.realtime.credentials()),
510 + getRealtimeCredentials: () =>
511 + Effect.flatMap(client, c => c.cli.realtime.credentials(validated)),
512 authRealtimeChannel: (params: { channel_name: string; socket_id: string }) =>
509 - Effect.flatMap(client, c => c.cli.realtime.auth(params, undecoded)),
513 + Effect.flatMap(client, c => c.cli.realtime.auth(params)),
514 };
515 });
516
ts/packages/cli/src/services/composio-request.ts
+10 -6
@@ -6,13 +6,17 @@ import { HttpDecodingError } from './composio-errors';
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.
9 + * Request options that make the client validate the response against its own
10 + * schema for the operation, so a response in an unexpected shape fails the
11 + * call with a `DecodeError` instead of surfacing later as a missing field.
12 + *
13 + * Pass it on a read whose fields the command uses through the client's types.
14 + * Leave it off when the CLI decodes the response with a schema it owns, when
15 + * the endpoint is read leniently on purpose, and on every call that is not a
16 + * read: failing after the server acted would invite a retry that repeats the
17 + * side effect.
18 */
15 -export const undecoded = { decode: false } satisfies RequestOptions;
19 +export const validated = { decode: true } satisfies RequestOptions;
20
21 /**
22 * Decodes a payload against a CLI-owned contract.
ts/packages/cli/src/services/composio-resource-operations.ts
+39 -55
@@ -15,7 +15,7 @@ import { Toolkits, type ToolkitSearchResult } from 'src/models/toolkits';
15 import { TriggerInstanceItems } from 'src/models/triggers';
16 import { TriggerType } from 'src/models/trigger-types';
17 import type { ClientError } from './composio-errors';
18 -import { decode, undecoded } from './composio-request';
18 +import { decode } from './composio-request';
19
20 /**
21 * Auth config, connected account, and trigger instance operations: single-page
@@ -34,15 +34,12 @@ export const resourceOperations = (client: Effect.Effect<ComposioClientShape, Cl
34 }) =>
35 client.pipe(
36 Effect.flatMap(c =>
37 - c.authConfigs.list(
38 - {
39 - search: params.search,
40 - toolkit_slug: params.toolkit_slug,
41 - limit: params.limit,
42 - show_disabled: params.show_disabled ?? true,
43 - },
44 - undecoded
45 - )
37 + c.authConfigs.list({
38 + search: params.search,
39 + toolkit_slug: params.toolkit_slug,
40 + limit: params.limit,
41 + show_disabled: params.show_disabled ?? true,
42 + })
43 ),
44 Effect.flatMap(decode(AuthConfigListResponse))
45 ),
@@ -52,7 +49,7 @@ export const resourceOperations = (client: Effect.Effect<ComposioClientShape, Cl
49 */
50 getAuthConfig: (nanoid: string) =>
51 client.pipe(
55 - Effect.flatMap(c => c.authConfigs.retrieve(nanoid, undecoded)),
52 + Effect.flatMap(c => c.authConfigs.retrieve(nanoid)),
53 Effect.flatMap(decode(AuthConfigItem))
54 ),
55 /**
@@ -61,7 +58,7 @@ export const resourceOperations = (client: Effect.Effect<ComposioClientShape, Cl
58 */
59 createAuthConfig: (params: AuthConfigCreateParams) =>
60 client.pipe(
64 - Effect.flatMap(c => c.authConfigs.create(params, undecoded)),
61 + Effect.flatMap(c => c.authConfigs.create(params)),
62 Effect.flatMap(decode(AuthConfigCreateResponse))
63 ),
64 /**
@@ -70,7 +67,7 @@ export const resourceOperations = (client: Effect.Effect<ComposioClientShape, Cl
67 */
68 getConnectedAccount: (nanoid: string) =>
69 client.pipe(
73 - Effect.flatMap(c => c.connectedAccounts.retrieve(nanoid, undecoded)),
70 + Effect.flatMap(c => c.connectedAccounts.retrieve(nanoid)),
71 Effect.flatMap(decode(ConnectedAccountItem))
72 ),
73 /**
@@ -80,18 +77,15 @@ export const resourceOperations = (client: Effect.Effect<ComposioClientShape, Cl
77 listActiveTriggers: (params: TriggerInstanceListActiveParams) =>
78 client.pipe(
79 Effect.flatMap(c =>
83 - c.triggerInstances.listActive(
84 - {
85 - user_ids: params.user_ids,
86 - connected_account_ids: params.connected_account_ids,
87 - auth_config_ids: params.auth_config_ids,
88 - trigger_ids: params.trigger_ids,
89 - trigger_names: params.trigger_names,
90 - show_disabled: params.show_disabled,
91 - limit: params.limit,
92 - },
93 - undecoded
94 - )
80 + c.triggerInstances.listActive({
81 + user_ids: params.user_ids,
82 + connected_account_ids: params.connected_account_ids,
83 + auth_config_ids: params.auth_config_ids,
84 + trigger_ids: params.trigger_ids,
85 + trigger_names: params.trigger_names,
86 + show_disabled: params.show_disabled,
87 + limit: params.limit,
88 + })
89 ),
90 Effect.flatMap(response =>
91 decode(TriggerInstanceItems)(response.items).pipe(
@@ -109,15 +103,11 @@ export const resourceOperations = (client: Effect.Effect<ComposioClientShape, Cl
103 )
104 ),
105 createTrigger: (triggerSlug: string, params?: TriggerInstanceUpsertParams) =>
112 - Effect.flatMap(client, c => c.triggerInstances.upsert(triggerSlug, params, undecoded)),
106 + Effect.flatMap(client, c => c.triggerInstances.upsert(triggerSlug, params)),
107 enableTrigger: (triggerId: string) =>
114 - Effect.flatMap(client, c =>
115 - c.triggerInstances.manage.update(triggerId, { status: 'enable' }, undecoded)
116 - ),
108 + Effect.flatMap(client, c => c.triggerInstances.manage.update(triggerId, { status: 'enable' })),
109 disableTrigger: (triggerId: string) =>
118 - Effect.flatMap(client, c =>
119 - c.triggerInstances.manage.update(triggerId, { status: 'disable' }, undecoded)
120 - ),
110 + Effect.flatMap(client, c => c.triggerInstances.manage.update(triggerId, { status: 'disable' })),
111 });
112
113 /**
@@ -136,15 +126,12 @@ export const lookupOperations = (client: Effect.Effect<ComposioClientShape, Clie
126 cursor?: string;
127 }): Effect.Effect<ToolkitSearchResult, ClientError> =>
128 Effect.flatMap(client, c =>
139 - c.toolkits.list(
140 - {
141 - search: params.search,
142 - category: params.category,
143 - limit: params.limit,
144 - cursor: params.cursor,
145 - },
146 - undecoded
147 - )
129 + c.toolkits.list({
130 + search: params.search,
131 + category: params.category,
132 + limit: params.limit,
133 + cursor: params.cursor,
134 + })
135 ).pipe(
136 Effect.flatMap(response =>
137 decode(Toolkits)(response.items).pipe(
@@ -176,35 +163,32 @@ export const lookupOperations = (client: Effect.Effect<ComposioClientShape, Clie
163 cursor?: string;
164 }) =>
165 Effect.flatMap(client, c =>
179 - c.tools.list(
180 - {
181 - search: params.search,
182 - toolkit_slug: params.toolkit_slug,
183 - tags: params.tags ? params.tags.split(',').map(t => t.trim()) : undefined,
184 - limit: params.limit,
185 - cursor: params.cursor,
186 - toolkit_versions: 'latest',
187 - },
188 - undecoded
189 - )
166 + c.tools.list({
167 + search: params.search,
168 + toolkit_slug: params.toolkit_slug,
169 + tags: params.tags ? params.tags.split(',').map(t => t.trim()) : undefined,
170 + limit: params.limit,
171 + cursor: params.cursor,
172 + toolkit_versions: 'latest',
173 + })
174 ),
175 /**
176 * Retrieves detailed info about a single tool by slug.
177 * @param slug - Tool slug (e.g. "GMAIL_SEND_EMAIL")
178 *
195 - * Not client-decoded: `execute` treats a failed lookup as "no cached
179 + * Not validated by the client: `execute` treats a failed lookup as "no cached
180 * definition" and would skip input validation and file uploads on drift
181 * in a field it never reads.
182 */
183 getToolDetailed: (slug: string) =>
200 - Effect.flatMap(client, c => c.tools.retrieve(slug, { toolkit_versions: 'latest' }, undecoded)),
184 + Effect.flatMap(client, c => c.tools.retrieve(slug, { toolkit_versions: 'latest' })),
185 /**
186 * Retrieves detailed info about a single trigger type by slug.
187 * @param slug - Trigger type slug (e.g. "GMAIL_NEW_GMAIL_MESSAGE")
188 */
189 getTriggerTypeDetailed: (slug: string) =>
190 client.pipe(
207 - Effect.flatMap(c => c.triggersTypes.retrieve(slug, undefined, undecoded)),
191 + Effect.flatMap(c => c.triggersTypes.retrieve(slug)),
192 Effect.flatMap(decode(TriggerType))
193 ),
194 });
ts/packages/cli/src/services/composio-schema-loaders.ts deleted
-22
@@ -1,22 +0,0 @@
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 - 'org.consumer.listConnectedToolkits': async () =>
18 - (await import('@composio/client/effect/schemas/org/consumer/list-connected-toolkits'))
19 - .ConsumerListConnectedToolkitsResponse,
20 - 'org.list': async () =>
21 - (await import('@composio/client/effect/schemas/org/list')).OrgListResponse,
22 -} satisfies SchemaLoaders;
ts/packages/cli/src/services/connected-account-selection.ts
+11 -17
@@ -173,14 +173,11 @@ export const listActiveConnectedAccounts = memoizeInProcess({
173 keyOf: (input: { readonly client: ComposioClientShape; readonly userId: string }) =>
174 `${clientId(input.client)}\u0000${input.userId}`,
175 make: ({ client, userId }) =>
176 - client.connectedAccounts.list(
177 - {
178 - user_ids: [userId],
179 - statuses: ['ACTIVE'],
180 - limit: ACTIVE_ACCOUNTS_PAGE_SIZE,
181 - },
182 - { decode: false }
183 - ),
176 + client.connectedAccounts.list({
177 + user_ids: [userId],
178 + statuses: ['ACTIVE'],
179 + limit: ACTIVE_ACCOUNTS_PAGE_SIZE,
180 + }),
181 });
182
183 const TOOLKIT_ACCOUNTS_PAGE_SIZE = 100;
@@ -194,15 +191,12 @@ const fetchConnectedAccountsForToolkit = (params: {
191 readonly toolkitSlug: string;
192 }) =>
193 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,
203 - },
204 - { decode: false }
205 - )
194 + .list({
195 + toolkit_slugs: [params.toolkitSlug],
196 + user_ids: [params.userId],
197 + statuses: ['ACTIVE'],
198 + limit: TOOLKIT_ACCOUNTS_PAGE_SIZE,
199 + })
200 .pipe(Effect.map(response => response.items));
201
202 /**
ts/packages/cli/src/services/tool-file-uploads.ts
+7 -10
@@ -283,16 +283,13 @@ const uploadFile = (params: {
283 // eslint-disable-next-line no-restricted-imports -- MD5 for the presigned-upload checksum is not available in Web Crypto
284 const { createHash } = yield* Effect.promise(() => import('node:crypto'));
285 const md5 = createHash('md5').update(fileData.bytes).digest('hex');
286 - const presigned = yield* params.client.files.createPresignedURL(
287 - {
288 - filename: fileData.fileName,
289 - mimetype: fileData.mimeType,
290 - md5,
291 - tool_slug: params.toolSlug,
292 - toolkit_slug: params.toolkitSlug,
293 - },
294 - { decode: false }
295 - );
286 + const presigned = yield* params.client.files.createPresignedURL({
287 + filename: fileData.fileName,
288 + mimetype: fileData.mimeType,
289 + md5,
290 + tool_slug: params.toolSlug,
291 + toolkit_slug: params.toolkitSlug,
292 + });
293
294 const { ssrfSafeFetch } = yield* loadSsrfSafeFetch;
295 const uploadResponse = yield* Effect.tryPromise({
ts/packages/cli/src/services/tool-router-session-connections.ts
+6 -9
@@ -57,15 +57,12 @@ const listConnectedAccountsForToolkits = (
57 userId: string,
58 toolkits: ReadonlyArray<string>
59 ) =>
60 - client.connectedAccounts.list(
61 - {
62 - user_ids: [userId],
63 - statuses: ['ACTIVE'],
64 - toolkit_slugs: [...toolkits],
65 - limit: 1000,
66 - },
67 - { decode: false }
68 - );
60 + client.connectedAccounts.list({
61 + user_ids: [userId],
62 + statuses: ['ACTIVE'],
63 + toolkit_slugs: [...toolkits],
64 + limit: 1000,
65 + });
66
67 export const resolveToolRouterSessionConnections = (
68 client: ComposioClientShape,
ts/packages/cli/src/services/tools-executor.ts
+2 -2
@@ -261,12 +261,12 @@ export const ToolsExecutorLive = Layer.effect(
261 ? resolvedClient.toolRouter.session.executeMeta(
262 sessionId,
263 { slug, arguments: normalizedArguments },
264 - { maxRetries: 0, decode: false }
264 + { maxRetries: 0 }
265 )
266 : resolvedClient.toolRouter.session.execute(
267 sessionId,
268 { tool_slug: slug, arguments: normalizedArguments },
269 - { maxRetries: 0, decode: false }
269 + { maxRetries: 0 }
270 );
271 if (raw.result_type === 'input_required') {
272 return yield* toolInputRequiredError(`Tool ${slug}`, raw);
ts/packages/cli/src/services/triggers-realtime.ts
+3 -2
@@ -15,6 +15,7 @@ import type {
15 RealtimeCredentialsResponse as CliRealtimeCredentialsResponse,
16 } from '@composio/client/resources/cli';
17 import { ComposioClientSingleton, ComposioSessionRepository } from 'src/services/composio-clients';
18 +import { validated } from 'src/services/composio-request';
19
20 const RawRealtimeEvent = JsonRecordSchema;
21 type RawRealtimeEvent = typeof RawRealtimeEvent.Type;
@@ -297,11 +298,11 @@ const makeTriggersRealtime = Effect.gen(function* () {
298 return yield* listenWith({
299 getRealtimeCredentials: () =>
300 client.cli.realtime
300 - .credentials()
301 + .credentials(validated)
302 .pipe(Effect.mapError(subscriptionError('Failed to fetch realtime credentials'))),
303 authRealtimeChannel: params =>
304 client.cli.realtime
304 - .auth(params, { decode: false })
305 + .auth(params)
306 .pipe(Effect.mapError(subscriptionError('Failed to authorize the realtime channel'))),
307 onEvent,
308 });
ts/packages/cli/src/utils/optional-params.ts new
+21
@@ -0,0 +1,21 @@
1 +import { Option, Record as EffectRecord } from 'effect';
2 +
3 +/**
4 + * The request parameters a record of optional flags turns into: each present
5 + * flag keeps its value and each absent one becomes `undefined`, which the client
6 + * leaves out of the query string.
7 + */
8 +export type OptionalParams<R extends Readonly<Record<string, Option.Option<unknown>>>> = {
9 + readonly [K in keyof R]: R[K] extends Option.Option<infer A> ? A | undefined : never;
10 +};
11 +
12 +/**
13 + * Turns optional flags into request parameters in one place, instead of an
14 + * `Option.getOrUndefined` per field at the call site.
15 + *
16 + * @example
17 + * client.logs.triggers.list({ ...optionalParams({ cursor, from, to }), limit })
18 + */
19 +export const optionalParams = <const R extends Readonly<Record<string, Option.Option<unknown>>>>(
20 + flags: R
21 +): OptionalParams<R> => EffectRecord.map(flags, Option.getOrUndefined) as OptionalParams<R>;
ts/packages/cli/test/__utils__/services/stub-composio-client.ts
+5 -6
@@ -2,7 +2,7 @@ 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';
5 +import { schemaLoaders } from '@composio/client/effect/schemas';
6
7 /** One request as it reached the stub transport. */
8 export interface StubRequest {
@@ -14,9 +14,9 @@ export interface StubRequest {
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.
17 + * The Effect client the CLI builds in production, over a transport that
18 + * records each request and answers it with `respond`. Retries, status errors,
19 + * and the validation a call asks for 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.
@@ -46,8 +46,7 @@ export const stubComposioClient = (
46 orgApiKey: null,
47 baseURL: 'https://stub.invalid',
48 deprecationNotices: 'off',
49 - decode: true,
50 - schemas: composioSchemaLoaders,
49 + schemas: schemaLoaders,
50 },
51 httpClient
52 );
ts/packages/cli/test/__utils__/services/test-layer.ts
+2 -26
@@ -31,7 +31,6 @@ import {
31 Layer,
32 Option,
33 Path,
34 - Predicate,
34 References,
35 Schedule,
36 String,
@@ -52,7 +51,6 @@ import {
51 ComposioToolkitsRepository,
52 type ToolkitProjectScope,
53 } from 'src/services/composio-clients';
55 -import { composioSchemaLoaders } from 'src/services/composio-schema-loaders';
54 import {
55 InvalidToolkitsError,
56 InvalidToolkitVersionsError,
@@ -1219,41 +1217,19 @@ export const TestLayer = (input?: TestLiveInput) =>
1217 Effect.die(new Error(`unexpected network call from the mock Composio client: ${request.url}`))
1218 );
1219
1222 - // The real client refuses, before sending, a typed call that neither has a
1223 - // response schema loader nor passes `decode: false`. A shadow replaces the
1224 - // call, so it repeats that check; the raw `get`/`post` methods are exempt.
1225 - const isUndecodedCall = (args: ReadonlyArray<unknown>): boolean => {
1226 - const options = args.at(-1);
1227 - return Predicate.hasProperty(options, 'decode') && options.decode === false;
1228 - };
1229 - const hasSchemaLoader = (operation: string): boolean =>
1230 - operation.replace(/Stream$/, '') in composioSchemaLoaders;
1231 -
1220 // Each shadow answers with an Effect or a promise; a rejection becomes
1221 // the call's failure as it is. A shadow ignores the request options
1222 // (`signal`, `maxRetries`, headers beyond `decode`), and the
1223 // `connectedAccounts.list` shadow never pages (`next_cursor` is null):
1224 // pagination, retries, and abort are covered by `stubComposioClient`,
1225 // the real `make` over a recording transport.
1238 - const withShadows = <Resources extends object>(
1239 - base: Resources,
1240 - shadows: object,
1241 - chain: ReadonlyArray<string> = []
1242 - ): Resources => {
1226 + const withShadows = <Resources extends object>(base: Resources, shadows: object): Resources => {
1227 const shadowed = { ...base } as Record<string, unknown>;
1228 for (const [key, shadow] of Object.entries(shadows) as Array<[string, unknown]>) {
1245 - const operation = [...chain, key].join('.');
1229 shadowed[key] =
1230 typeof shadow === 'function'
1231 ? (...args: ReadonlyArray<unknown>) =>
1232 Effect.suspend(() => {
1250 - if (chain.length > 0 && !isUndecodedCall(args) && !hasSchemaLoader(operation)) {
1251 - return Effect.die(
1252 - new Error(
1253 - `'${operation}' has no response schema loader and was called without decode: false`
1254 - )
1255 - );
1256 - }
1233 const answer: unknown = shadow(...args);
1234 return Effect.isEffect(answer)
1235 ? answer
@@ -1262,7 +1238,7 @@ export const TestLayer = (input?: TestLiveInput) =>
1238 catch: cause => cause,
1239 });
1240 })
1265 - : withShadows((shadowed[key] ?? {}) as object, shadow as object, [...chain, key]);
1241 + : withShadows((shadowed[key] ?? {}) as object, shadow as object);
1242 }
1243 return shadowed as Resources;
1244 };
ts/packages/cli/test/src/commands/connected-accounts/connected-accounts.link.cmd.test.ts
+5 -7
@@ -500,14 +500,12 @@ describe('CLI: composio dev connected-accounts link', () => {
500 max_accounts_per_toolkit: undefined,
501 require_explicit_selection: undefined,
502 },
503 - }),
504 - { decode: false }
505 - );
506 - expect(toolRouterLinkSpy).toHaveBeenCalledWith(
507 - 'trs_test_session',
508 - { toolkit: 'gmail', alias: 'work' },
509 - { decode: false }
503 + })
504 );
505 + expect(toolRouterLinkSpy).toHaveBeenCalledWith('trs_test_session', {
506 + toolkit: 'gmail',
507 + alias: 'work',
508 + });
509 })
510 );
511 });
ts/packages/cli/test/src/commands/proxy.cmd.test.ts
+1 -1
@@ -191,7 +191,7 @@ describe('CLI: composio proxy', () => {
191 });
192 // A proxied call is never retried: a retry after the upstream API
193 // already acted would duplicate the side effect.
194 - expect(proxyOptions).toEqual({ maxRetries: 0, decode: false });
194 + expect(proxyOptions).toEqual({ maxRetries: 0 });
195
196 expect(output).toContain('Status: 200');
197 expect(output).toContain('"ok": true');
ts/packages/cli/test/src/commands/tools/tools.execute.cmd.test.ts
+2 -2
@@ -434,7 +434,7 @@ describe('CLI: composio execute', () => {
434 });
435 // An execution is never retried, and its response never validated: a
436 // retry after the backend already acted would duplicate the side effect.
437 - expect(recordedExecuteOptions.at(-1)).toEqual({ maxRetries: 0, decode: false });
437 + expect(recordedExecuteOptions.at(-1)).toEqual({ maxRetries: 0 });
438 })
439 );
440
@@ -442,7 +442,7 @@ describe('CLI: composio execute', () => {
442 Effect.gen(function* () {
443 yield* cli(['execute', 'COMPOSIO_SEARCH_TOOLS', '-d', '{"query":"email"}']);
444
445 - expect(recordedExecuteOptions).toEqual([{ maxRetries: 0, decode: false }]);
445 + expect(recordedExecuteOptions).toEqual([{ maxRetries: 0 }]);
446 })
447 );
448
ts/packages/cli/test/src/services/composio-client-interrupt.test.ts
+1 -4
@@ -110,10 +110,7 @@ describe('interrupting a single-shot client request', () => {
110 const client = yield* Effect.flatMap(ComposioClientSingleton, singleton => singleton.get());
111
112 const fiber = yield* Effect.forkChild(
113 - client.connectedAccounts.list(
114 - { user_ids: ['default'], statuses: ['ACTIVE'] },
115 - { decode: false }
116 - )
113 + client.connectedAccounts.list({ user_ids: ['default'], statuses: ['ACTIVE'] })
114 );
115 const requestSignal = yield* pending.signal;
116 expect(requestSignal.aborted).toBe(false);
ts/packages/cli/test/src/services/composio-client-singleton.test.ts
+16 -17
@@ -4,11 +4,12 @@ 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, Logger } from 'effect';
7 +import { ConfigProvider, Effect, Exit, 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 { validated } from 'src/services/composio-request';
13 import { APP_VERSION } from 'src/constants';
14 import { defaultNodeOs, NodeOs } from 'src/services/node-os';
15
@@ -80,10 +81,8 @@ const writeCliSessionCache = (
81 );
82 });
83
83 -// The canned responses here are not a tools page, so the call opts out of
84 -// client decoding.
84 const listTools = (client: ComposioClientShape) =>
86 - client.tools.list({ limit: 1, toolkit_versions: 'latest' }, { decode: false });
85 + client.tools.list({ limit: 1, toolkit_versions: 'latest' });
86
87 describe('ComposioClientSingleton headers', () => {
88 afterEach(() => {
@@ -261,7 +260,7 @@ describe('ComposioClientSingleton headers', () => {
260 const client = yield* clientSingleton.get();
261 // `auth.session.retrieveInfo` is an operation where the client would
262 // attach its own `userApiKey` credential; the caller-placed header wins.
264 - yield* client.auth.session.retrieveInfo({ decode: false });
263 + yield* client.auth.session.retrieveInfo();
264
265 const [input, init] = fetchSpy.mock.calls[0]!;
266 expect(String(input)).toContain('/api/v3.1/auth/session/info');
@@ -396,15 +395,13 @@ describe('ComposioClientSingleton client', () => {
395 }).pipe(Effect.provide(singletonLayer(baseConfig())));
396 });
397
399 - it.effect('omits the org header when the scope has no project', () => {
398 + it.effect('rejects a scope with an org and no project, and would send neither header', () => {
399 const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(okResponse());
400
401 return Effect.gen(function* () {
402 const clientSingleton = yield* ComposioClientSingleton;
404 - const client = yield* clientSingleton.getFor({
405 - userApiKey: 'uak_scope',
406 - orgId: 'org_a',
407 - });
403 + // @ts-expect-error a scope names the org and the project together
404 + const client = yield* clientSingleton.getFor({ userApiKey: 'uak_scope', orgId: 'org_a' });
405 yield* listTools(client);
406
407 const headers = sentHeaders(fetchSpy.mock.calls[0]!);
@@ -528,7 +525,7 @@ describe('ComposioClientSingleton client', () => {
525 const clientSingleton = yield* ComposioClientSingleton;
526 const client = yield* clientSingleton.get();
527
531 - expect(yield* client.tools.retrieveEnum({ decode: false })).toEqual(['GITHUB_CREATE_ISSUE']);
528 + expect(yield* client.tools.retrieveEnum()).toEqual(['GITHUB_CREATE_ISSUE']);
529 expect((yield* clientSingleton.getMetrics()).requests).toBe(2);
530 }).pipe(Effect.provide(singletonLayer(baseConfig([['COMPOSIO_USER_API_KEY', 'uak_retry']]))));
531 });
@@ -593,17 +590,19 @@ describe('ComposioClientSingleton client', () => {
590 );
591 });
592
596 - it.effect('rejects an undecodable typed call before sending it', () => {
597 - const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(okResponse());
593 + it.effect('validates a response only for a call that asks for it', () => {
594 + // `okResponse` is not a toolkits page.
595 + vi.spyOn(globalThis, 'fetch').mockImplementation(() => Promise.resolve(okResponse()));
596
597 return Effect.gen(function* () {
598 const clientSingleton = yield* ComposioClientSingleton;
599 const client = yield* clientSingleton.get();
602 - // No opt-out, and `toolkits.list` has no entry in the CLI's loader table.
603 - const error = yield* Effect.flip(client.toolkits.list({ limit: 1 }));
600
605 - expect(error._tag).toBe('@composio/client/ConfigurationError');
606 - expect(fetchSpy).not.toHaveBeenCalled();
601 + const lenient = yield* Effect.exit(client.toolkits.list({ limit: 1 }));
602 + const strict = yield* Effect.flip(client.toolkits.list({ limit: 1 }, validated));
603 +
604 + expect(Exit.isSuccess(lenient)).toBe(true);
605 + expect(strict._tag).toBe('@composio/client/DecodeError');
606 }).pipe(Effect.provide(singletonLayer(baseConfig([['COMPOSIO_USER_API_KEY', 'uak_strict']]))));
607 });
608
ts/packages/cli/test/src/services/composio-schema-loaders.test.ts deleted
-25
@@ -1,25 +0,0 @@
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/tool-file-uploads.test.ts
-3
@@ -14,7 +14,6 @@ import {
14 ComposioSensitiveFilePathBlockedError,
15 MAX_URL_UPLOAD_SIZE_BYTES,
16 } from '@composio/core';
17 -import { composioSchemaLoaders } from 'src/services/composio-schema-loaders';
17 import {
18 schemaHasFileUploadable,
19 ToolFileUploadError,
@@ -235,8 +234,6 @@ describe('uploadToolInputFiles — presigned-URL request', () => {
234 orgApiKey: null,
235 baseURL: 'https://stub.invalid',
236 deprecationNotices: 'off',
238 - decode: true,
239 - schemas: composioSchemaLoaders,
237 },
238 HttpClient.make(() =>
239 Effect.sync(() => reached.resolve()).pipe(
ts/packages/cli/test/src/utils/optional-params.test.ts new
+20
@@ -0,0 +1,20 @@
1 +import { describe, expect, it } from '@effect/vitest';
2 +import { Option } from 'effect';
3 +import { optionalParams } from 'src/utils/optional-params';
4 +
5 +describe('optionalParams', () => {
6 + it('keeps the value of a present flag and turns an absent one into undefined', () => {
7 + const params = optionalParams({
8 + cursor: Option.some('c_1'),
9 + from: Option.none<string>(),
10 + limit: Option.some(30),
11 + });
12 +
13 + expect(params).toEqual({ cursor: 'c_1', from: undefined, limit: 30 });
14 + expect(Object.keys(params)).toEqual(['cursor', 'from', 'limit']);
15 + });
16 +
17 + it('returns an empty record for no flags', () => {
18 + expect(optionalParams({})).toEqual({});
19 + });
20 +});