@devries-cameron20 / composio Mirror · read-only / commits / 7cf693c5c
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): apply Effect v4 idioms to the client migration (#4877)

This PR: - builds on top of https://github.com/ComposioHQ/composio/pull/4853 (merged) - builds the per-scope client through `Cache.makeWith` keyed on a structural `ClientScope` record, so concurrent first callers share one in-flight build and a failed build is not memoized; the mutable `Map` and the raw API key in a JSON key are gone - memoizes `getProjectToolkits` per scope with a `Cache` instead of `Effect.runSync(Effect.cached(...))` over a module-level `Map` - composes the counting transport as `Layer.fresh(FetchHttpClient.layer)` provided to the singleton layer instead of extracting `HttpClient` out of a `local: true` provide whose scope closes immediately - keeps the client's own `ConfigurationError` when `make` refuses its options (`ClientBuildError`) and drops the `String` import shadowing - exports `CLIENT_API_ERROR_TAGS` and recovers with `Effect.catchTag(CLIENT_API_ERROR_TAGS, ...)` at the command call sites, in `init` and in toolkit version validation, replacing `catchIf` refinements with explicit type arguments; `listen` reports an unknown trigger slug through `catchTag` instead of `Effect.result` plus a tag check - keeps the `SchemaError` as the structured `cause` of `HttpDecodingError`, and sets the exit code through the `NodeProcess` service instead of `node:process` - runs tool file uploads in the calling fiber: `uploadToolInputFiles` is an Effect, so interrupting an execution now aborts the presigned-URL request too, and the detached `Effect.runPromiseExit` boundary is gone ## Context Review of https://github.com/ComposioHQ/composio/pull/4853 against the Effect v4 patterns in `.agents/skills/effect-v4`. Command output is unchanged; the only user-visible difference is that an invalid base URL now fails with `@composio/client/ConfigurationError` instead of the CLI's wrapper. New tests cover the shared in-flight build, the retry after a failed build, the counting transport staying separate from an application-level `FetchHttpClient.layer`, the exit code through `NodeProcess`, and interruption of an upload. Verified locally: `pnpm typecheck`, the CLI suite (145 files, 1483 passed, 1 skipped), `oxlint` on `ts/packages/cli`, `validate:boundaries`.

Alberto Schiabel committed Oct 15, 2026 at 15:12 UTC 7cf693c5c64b9acefe7647440f5974012e279556
31 files changed +899 -621
ts/packages/cli/AGENTS.md
+1 -1
@@ -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 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`.
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, `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. 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
ts/packages/cli/lint-boundaries.json
+1 -1
@@ -24,7 +24,7 @@
24 {
25 "rule": "no-restricted-imports",
26 "reason": "MD5 for the presigned-upload checksum is not available in Web Crypto",
27 - "target": "const { createHash } = await import('node:crypto');"
27 + "target": "const { createHash } = yield* Effect.promise(() => import('node:crypto'));"
28 }
29 ]
30 }
ts/packages/cli/src/commands/auth-configs/commands/auth-configs.create.cmd.ts
+10 -6
@@ -5,7 +5,8 @@ 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 { catchClientApiError } from 'src/effects/handle-http-error';
8 +import { handleClientApiError } from 'src/effects/handle-http-error';
9 +import { CLIENT_API_ERROR_TAGS } from 'src/services/composio-errors';
10 import { redact } from 'src/ui/redact';
11 import { formatAuthConfigCreated } from '../format';
12
@@ -117,11 +118,14 @@ export const authConfigsCmd$Create = Command.make(
118 .withSpinner('Creating auth config...', repo.createAuthConfig(params))
119 .pipe(
120 Effect.asSome,
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 - })
121 + Effect.catchTag(
122 + CLIENT_API_ERROR_TAGS,
123 + handleClientApiError(ui, {
124 + fallbackMessage: 'Failed to create auth config.',
125 + hint: `Check available auth schemes for "${toolkit}":\n> composio dev toolkits info "${toolkit}"`,
126 + fallbackValue: Option.none(),
127 + })
128 + )
129 );
130
131 if (Option.isNone(resultOpt)) {
ts/packages/cli/src/commands/auth-configs/commands/auth-configs.info.cmd.ts
+10 -6
@@ -3,7 +3,8 @@ 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 { catchClientApiError } from 'src/effects/handle-http-error';
6 +import { handleClientApiError } from 'src/effects/handle-http-error';
7 +import { CLIENT_API_ERROR_TAGS } from 'src/services/composio-errors';
8 import { formatAuthConfigInfo } from '../format';
9
10 const id = Argument.String('id').pipe(
@@ -42,11 +43,14 @@ export const authConfigsCmd$Info = Command.make('info', { id }, ({ id }) =>
43 .withSpinner(`Fetching auth config "${idValue}"...`, repo.getAuthConfig(idValue))
44 .pipe(
45 Effect.asSome,
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 - })
46 + Effect.catchTag(
47 + CLIENT_API_ERROR_TAGS,
48 + handleClientApiError(ui, {
49 + fallbackMessage: `Failed to fetch auth config "${idValue}".`,
50 + hint: 'Browse available auth configs:\n> composio dev auth-configs list',
51 + fallbackValue: Option.none(),
52 + })
53 + )
54 );
55
56 if (Option.isNone(itemOpt)) {
ts/packages/cli/src/commands/connected-accounts/commands/connected-accounts.info.cmd.ts
+10 -6
@@ -3,7 +3,8 @@ 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 { catchClientApiError } from 'src/effects/handle-http-error';
6 +import { handleClientApiError } from 'src/effects/handle-http-error';
7 +import { CLIENT_API_ERROR_TAGS } from 'src/services/composio-errors';
8 import { formatConnectedAccountInfo } from '../format';
9
10 const id = Argument.String('id').pipe(
@@ -41,11 +42,14 @@ export const connectedAccountsCmd$Info = Command.make('info', { id }, ({ id }) =
42 .withSpinner(`Fetching connected account "${idValue}"...`, repo.getConnectedAccount(idValue))
43 .pipe(
44 Effect.asSome,
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 - })
45 + Effect.catchTag(
46 + CLIENT_API_ERROR_TAGS,
47 + handleClientApiError(ui, {
48 + fallbackMessage: `Failed to fetch connected account "${idValue}".`,
49 + hint: 'Browse available connected accounts:\n> composio dev connected-accounts list',
50 + fallbackValue: Option.none(),
51 + })
52 + )
53 );
54
55 if (Option.isNone(itemOpt)) {
ts/packages/cli/src/commands/connected-accounts/commands/connected-accounts.whoami.cmd.ts
+10 -6
@@ -3,7 +3,8 @@ 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 { catchClientApiError } from 'src/effects/handle-http-error';
6 +import { handleClientApiError } from 'src/effects/handle-http-error';
7 +import { CLIENT_API_ERROR_TAGS } from 'src/services/composio-errors';
8 import { formatConnectedAccountWhoami } from '../format';
9
10 const id = Argument.String('id').pipe(
@@ -45,11 +46,14 @@ export const connectedAccountsCmd$Whoami = Command.make('whoami', { id }, ({ id
46 .withSpinner(`Fetching connected account "${idValue}"...`, repo.getConnectedAccount(idValue))
47 .pipe(
48 Effect.asSome,
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 - })
49 + Effect.catchTag(
50 + CLIENT_API_ERROR_TAGS,
51 + handleClientApiError(ui, {
52 + fallbackMessage: `Failed to fetch connected account "${idValue}".`,
53 + hint: 'Browse available connected accounts:\n> composio dev connected-accounts list',
54 + fallbackValue: Option.none(),
55 + })
56 + )
57 );
58
59 if (Option.isNone(itemOpt)) {
ts/packages/cli/src/commands/init.cmd.ts
+3 -3
@@ -20,9 +20,9 @@ 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 { CLIENT_API_ERROR_TAGS } from 'src/services/composio-errors';
24 import {
25 describeDecodeError,
25 - isClientApiError,
26 isClientConnectionError,
27 isClientDecodeError,
28 type ClientApiError,
@@ -293,7 +293,7 @@ const initInteractiveFlow = (params: { composioDir: string; noBrowser: boolean;
293 apiKey: globalApiKey,
294 orgId: orgIdValue,
295 }).pipe(
296 - Effect.catchIf(isClientApiError, e =>
296 + Effect.catchTag(CLIENT_API_ERROR_TAGS, 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.');
@@ -356,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(
359 - Effect.catchIf(isClientApiError, e =>
359 + Effect.catchTag(CLIENT_API_ERROR_TAGS, 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
+17 -20
@@ -164,26 +164,23 @@ const assertTriggerTypeExists = (params: {
164 slug: string;
165 toolkitSlug?: string;
166 }) =>
167 - Effect.gen(function* () {
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>\`.`,
179 - slug: params.slug,
180 - toolkitSlug: params.toolkitSlug,
181 - cause: lookup.failure,
182 - });
183 - }
184 - // A found trigger type, or any failure other than 404, is inconclusive here: fall through to
185 - // the caller's own error.
186 - });
167 + params.client.triggersTypes.retrieve(params.slug, undefined, { decode: false }).pipe(
168 + Effect.catchTag(
169 + '@composio/client/NotFoundError',
170 + cause =>
171 + new ListenCommandError({
172 + reason: 'unknown_trigger',
173 + message: `Unknown trigger slug "${params.slug}". List available slugs with \`composio triggers list <toolkit>\`.`,
174 + slug: params.slug,
175 + toolkitSlug: params.toolkitSlug,
176 + cause,
177 + }),
178 + // A found trigger type, or any failure other than 404, is inconclusive here: fall through to
179 + // the caller's own error.
180 + () => Effect.void
181 + ),
182 + Effect.asVoid
183 + );
184
185 const resolveConnectedAccountIdForTrigger = (params: {
186 client: ComposioClientShape;
ts/packages/cli/src/commands/tools/commands/tools.info.cmd.ts
+22 -18
@@ -3,7 +3,8 @@ 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 { catchClientApiError } from 'src/effects/handle-http-error';
6 +import { handleClientApiError } from 'src/effects/handle-http-error';
7 +import { CLIENT_API_ERROR_TAGS } from 'src/services/composio-errors';
8 import { getOrFetchToolInputDefinition } from 'src/services/tool-input-validation';
9 import { normalizeFileUploadSchema } from 'src/services/tool-file-uploads';
10 import { bold } from 'src/ui/colors';
@@ -44,23 +45,26 @@ export const toolsCmd$Info = Command.make('info', { slug }, ({ slug }) =>
45 .withSpinner(`Fetching tool "${slugValue}"...`, repo.getToolDetailed(slugValue))
46 .pipe(
47 Effect.asSome,
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 - })
48 + Effect.catchTag(
49 + CLIENT_API_ERROR_TAGS,
50 + handleClientApiError(ui, {
51 + fallbackMessage: `Tool "${slugValue}" not found.`,
52 + hint: [
53 + commandHintStep('Browse available toolkits', 'dev.toolkits.list'),
54 + commandHintStep('Then list tools', 'root.tools.list'),
55 + ].join('\n'),
56 + fallbackValue: Option.none(),
57 + searchForSuggestions: () =>
58 + repo.searchTools({ search: slugValue, limit: 3 }).pipe(
59 + Effect.map(r =>
60 + r.items.map(s => ({
61 + label: `${s.slug} — ${s.description}`,
62 + command: `> composio tools info "${s.slug}"`,
63 + }))
64 + )
65 + ),
66 + })
67 + )
68 );
69
70 if (Option.isNone(toolOpt)) {
ts/packages/cli/src/commands/triggers/commands/triggers.create.cmd.ts
+10 -6
@@ -2,7 +2,8 @@ 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 { catchClientApiError } from 'src/effects/handle-http-error';
5 +import { handleClientApiError } from 'src/effects/handle-http-error';
6 +import { CLIENT_API_ERROR_TAGS } from 'src/services/composio-errors';
7 import { ComposioToolkitsRepository } from 'src/services/composio-clients';
8 import { TerminalUI } from 'src/services/terminal-ui';
9
@@ -71,11 +72,14 @@ export const triggersCmd$Create = Command.make(
72 )
73 .pipe(
74 Effect.asSome,
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 - })
75 + Effect.catchTag(
76 + CLIENT_API_ERROR_TAGS,
77 + handleClientApiError(ui, {
78 + fallbackMessage: `Failed to create trigger "${triggerName.value}".`,
79 + hint: 'List available trigger types with:\n> composio dev triggers list',
80 + fallbackValue: Option.none(),
81 + })
82 + )
83 );
84
85 if (Option.isNone(createdOpt)) {
ts/packages/cli/src/commands/triggers/commands/triggers.disable.cmd.ts
+10 -6
@@ -1,7 +1,8 @@
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 { catchClientApiError } from 'src/effects/handle-http-error';
4 +import { handleClientApiError } from 'src/effects/handle-http-error';
5 +import { CLIENT_API_ERROR_TAGS } from 'src/services/composio-errors';
6 import { ComposioToolkitsRepository } from 'src/services/composio-clients';
7 import { ComposioCliUserConfig } from 'src/services/cli-user-config';
8 import { TerminalUI } from 'src/services/terminal-ui';
@@ -59,11 +60,14 @@ export const triggersCmd$Disable = Command.make(
60 .withSpinner(`Disabling trigger "${idValue}"...`, repo.disableTrigger(idValue))
61 .pipe(
62 Effect.as(true),
62 - catchClientApiError(ui, {
63 - fallbackMessage: `Failed to disable trigger "${idValue}".`,
64 - hint: 'Browse available triggers:\n> composio dev triggers status',
65 - fallbackValue: false,
66 - })
63 + Effect.catchTag(
64 + CLIENT_API_ERROR_TAGS,
65 + handleClientApiError(ui, {
66 + fallbackMessage: `Failed to disable trigger "${idValue}".`,
67 + hint: 'Browse available triggers:\n> composio dev triggers status',
68 + fallbackValue: false,
69 + })
70 + )
71 );
72
73 if (!disabled) return;
ts/packages/cli/src/commands/triggers/commands/triggers.enable.cmd.ts
+10 -6
@@ -1,7 +1,8 @@
1 import { Argument, Command } from 'effect/cli';
2 import { Effect, Option } from 'effect';
3 import { requireAuth } from 'src/effects/require-auth';
4 -import { catchClientApiError } from 'src/effects/handle-http-error';
4 +import { handleClientApiError } from 'src/effects/handle-http-error';
5 +import { CLIENT_API_ERROR_TAGS } from 'src/services/composio-errors';
6 import { ComposioToolkitsRepository } from 'src/services/composio-clients';
7 import { TerminalUI } from 'src/services/terminal-ui';
8
@@ -33,11 +34,14 @@ export const triggersCmd$Enable = Command.make('enable', { id }, ({ id }) =>
34 .withSpinner(`Enabling trigger "${idValue}"...`, repo.enableTrigger(idValue))
35 .pipe(
36 Effect.as(true),
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 - })
37 + Effect.catchTag(
38 + CLIENT_API_ERROR_TAGS,
39 + handleClientApiError(ui, {
40 + fallbackMessage: `Failed to enable trigger "${idValue}".`,
41 + hint: 'Browse available triggers:\n> composio dev triggers status --show-disabled',
42 + fallbackValue: false,
43 + })
44 + )
45 );
46
47 if (!enabled) return;
ts/packages/cli/src/commands/triggers/commands/triggers.info.cmd.ts
+10 -6
@@ -1,7 +1,8 @@
1 import { Argument, Command } from 'effect/cli';
2 import { Effect, Option } from 'effect';
3 import { requireAuth } from 'src/effects/require-auth';
4 -import { catchClientApiError } from 'src/effects/handle-http-error';
4 +import { handleClientApiError } from 'src/effects/handle-http-error';
5 +import { CLIENT_API_ERROR_TAGS } from 'src/services/composio-errors';
6 import { ComposioToolkitsRepository } from 'src/services/composio-clients';
7 import { TerminalUI } from 'src/services/terminal-ui';
8 import { formatTriggerTypeInfo } from '../format';
@@ -51,11 +52,14 @@ const makeTriggersInfoCommand = ({
52 .withSpinner('Fetching trigger type details...', repo.getTriggerTypeDetailed(slugValue))
53 .pipe(
54 Effect.asSome,
54 - catchClientApiError(ui, {
55 - fallbackMessage: `Trigger "${slugValue}" not found.`,
56 - hint: `Browse available trigger types:\n> ${listCommandPlaceholder}`,
57 - fallbackValue: Option.none(),
58 - })
55 + Effect.catchTag(
56 + CLIENT_API_ERROR_TAGS,
57 + handleClientApiError(ui, {
58 + fallbackMessage: `Trigger "${slugValue}" not found.`,
59 + hint: `Browse available trigger types:\n> ${listCommandPlaceholder}`,
60 + fallbackValue: Option.none(),
61 + })
62 + )
63 );
64
65 if (Option.isNone(triggerTypeOpt)) return;
ts/packages/cli/src/commands/triggers/commands/triggers.status.cmd.ts
+10 -6
@@ -1,6 +1,7 @@
1 import { Command, Flag } from 'effect/cli';
2 import { Effect, Option } from 'effect';
3 -import { catchClientApiError } from 'src/effects/handle-http-error';
3 +import { handleClientApiError } from 'src/effects/handle-http-error';
4 +import { CLIENT_API_ERROR_TAGS } from 'src/services/composio-errors';
5 import { requireAuth } from 'src/effects/require-auth';
6 import { ComposioToolkitsRepository } from 'src/services/composio-clients';
7 import { TerminalUI } from 'src/services/terminal-ui';
@@ -91,11 +92,14 @@ export const triggersCmd$Status = Command.make(
92 )
93 .pipe(
94 Effect.asSome,
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 - })
95 + Effect.catchTag(
96 + CLIENT_API_ERROR_TAGS,
97 + handleClientApiError(ui, {
98 + fallbackMessage: 'Failed to fetch trigger status.',
99 + hint: 'Retry with:\n> composio dev triggers status --show-disabled',
100 + fallbackValue: Option.none(),
101 + })
102 + )
103 );
104
105 if (Option.isNone(resultOpt)) {
ts/packages/cli/src/effects/handle-http-error.ts
+11 -36
@@ -1,13 +1,9 @@
1 -import process from 'node:process';
1 import { isAPIError } from '@composio/client/effect';
2 import { Effect } from 'effect';
3 +import type { ClientApiError } from 'src/services/composio-errors';
4 +import { NodeProcess } from 'src/services/node-process';
5 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';
6 +import { describeDecodeError, isClientDecodeError } from 'src/utils/api-error-extraction';
7
8 export interface Suggestion {
9 readonly label: string;
@@ -56,10 +52,15 @@ const reportOf = (e: ClientApiError): ErrorReport => {
52 * A response that failed client decoding is reported by operation and request
53 * id with an upgrade hint, in place of the fallback message and the hint.
54 *
55 + * Recover from every client API error (a non-success status, a connection
56 + * failure, a timeout, or a response that failed decoding) with
57 + * `Effect.catchTag(CLIENT_API_ERROR_TAGS, ...)`; every other failure passes
58 + * through. A single tag narrows the recovery to that status.
59 + *
60 * @example
61 * ```ts
62 * .pipe(
62 - * Effect.catchTag('@composio/client/NotFoundError',
63 + * Effect.catchTag(CLIENT_API_ERROR_TAGS,
64 * handleClientApiError(ui, {
65 * fallbackMessage: `Failed to fetch auth config "${id}".`,
66 * hint: 'Browse available auth configs:\n> composio dev auth-configs list',
@@ -73,7 +74,8 @@ export const handleClientApiError =
74 <A>(ui: TerminalUI, opts: HandleClientApiErrorOptions<A>) =>
75 (e: ClientApiError) =>
76 Effect.gen(function* () {
76 - process.exitCode = 1;
77 + const proc = yield* NodeProcess;
78 + yield* proc.setExitCode(1);
79
80 const report = reportOf(e);
81 const message = report.message ?? opts.fallbackMessage;
@@ -106,30 +108,3 @@ export const handleClientApiError =
108 yield* ui.log.step(hint);
109 return opts.fallbackValue;
110 });
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/validate-toolkit-versions.ts
+12 -10
@@ -1,9 +1,9 @@
1 -import { isComposioError } from '@composio/client/effect';
1 import { Data, Effect } from 'effect';
2 import colors from 'picocolors';
3 import { S_BAR, unicodeOr } from '@clack/prompts';
4 import { TerminalUI } from 'src/services/terminal-ui';
5 import type { ComposioToolkitsRepositoryShape } from 'src/services/composio-clients';
6 +import { CLIENT_API_ERROR_TAGS } from 'src/services/composio-errors';
7 import type { InvalidVersionDetail } from 'src/services/toolkit-version-validation';
8 import type { ToolkitVersionOverrides } from './toolkit-version-overrides';
9
@@ -188,7 +188,7 @@ export const validateToolkitVersionOverrides = ({
188 })
189 )
190 ),
191 - Effect.catchIf(isComposioError, error =>
191 + Effect.catchTag(CLIENT_API_ERROR_TAGS, error =>
192 Effect.fail(
193 new ToolkitVersionValidationError({
194 cause: error,
@@ -214,14 +214,16 @@ export const validateToolkitVersionOverrides = ({
214 })
215 )
216 ),
217 - Effect.catchTag('services/ComposioClientConfigurationError', error =>
218 - Effect.fail(
219 - new ToolkitVersionValidationError({
220 - cause: error,
221 - message: error.message,
222 - reason: 'client-unavailable',
223 - })
224 - )
217 + Effect.catchTag(
218 + ['services/ComposioClientConfigurationError', '@composio/client/ConfigurationError'],
219 + error =>
220 + Effect.fail(
221 + new ToolkitVersionValidationError({
222 + cause: error,
223 + message: error.message,
224 + reason: 'client-unavailable',
225 + })
226 + )
227 )
228 );
229
ts/packages/cli/src/services/composio-clients-cached.ts
+19 -16
@@ -1,4 +1,4 @@
1 -import { Effect, Option, Schema, Layer, Array as Arr } from 'effect';
1 +import { Cache, Effect, Option, Schema, Layer, Array as Arr } from 'effect';
2 import * as FileSystem from 'effect/FileSystem';
3 import * as Path from 'effect/Path';
4 import * as BunFileSystem from '@effect/platform-bun/BunFileSystem';
@@ -195,22 +195,25 @@ export const ComposioToolkitsRepositoryCached = Layer.effect(
195 // still reaches the API, and a failure only costs toolkit resolution its
196 // fallback guess.
197 //
198 - // The list depends on the project it is asked for, so each scope gets its
199 - // own memo (the unscoped call is one more key), with the same
200 - // failure-is-final semantics as `cachedGetToolkits`. The memo is created
201 - // synchronously so that concurrent first callers share it.
202 - const projectToolkitsByScope = new Map<
203 - string,
204 - ReturnType<typeof underlyingRepository.getProjectToolkits>
205 - >();
198 + // The list depends on the project it is asked for, so each scope is one
199 + // cache entry (the unscoped call is one more key), with the same
200 + // failure-is-final semantics as `cachedGetToolkits`: an entry never
201 + // expires, whichever way the fetch ended. Concurrent first callers of a
202 + // scope share its in-flight fetch. The key is a plain record, which
203 + // `Equal` and `Hash` compare structurally.
204 + const projectToolkitsByScope = yield* Cache.make({
205 + capacity: 64,
206 + lookup: (scope: { readonly orgId?: string; readonly projectId?: string }) =>
207 + underlyingRepository.getProjectToolkits(
208 + scope.orgId !== undefined && scope.projectId !== undefined
209 + ? { orgId: scope.orgId, projectId: scope.projectId }
210 + : undefined
211 + ),
212 + });
213 const cachedGetProjectToolkits = (scope?: ToolkitProjectScope) =>
207 - Effect.suspend(() => {
208 - const key = scope ? JSON.stringify([scope.orgId, scope.projectId]) : '';
209 - const memo =
210 - projectToolkitsByScope.get(key) ??
211 - Effect.runSync(Effect.cached(underlyingRepository.getProjectToolkits(scope)));
212 - projectToolkitsByScope.set(key, memo);
213 - return memo;
214 + Cache.get(projectToolkitsByScope, {
215 + orgId: scope?.orgId,
216 + projectId: scope?.projectId,
217 });
218
219 // Create the cached implementation that wraps the original implementation
ts/packages/cli/src/services/composio-clients.ts
+145 -109
@@ -1,12 +1,23 @@
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';
1 +import {
2 + Cache,
3 + Context,
4 + Duration,
5 + Effect,
6 + Exit,
7 + Layer,
8 + Option,
9 + Stream,
10 + Array,
11 + Order,
12 +} from 'effect';
13 +import * as Str from 'effect/String';
14 import type { Cause } from 'effect';
15 import { FetchHttpClient, HttpClient } from 'effect/http';
16 import {
17 make as makeComposioClient,
18 VERSION as clientLibraryVersion,
19 type ComposioClientShape,
20 + type ConfigurationError,
21 } from '@composio/client/effect';
22 import { Toolkit, Toolkits, ToolkitDetailed } from 'src/models/toolkits';
23 import { ToolsAsEnums, Tools } from 'src/models/tools';
@@ -21,12 +32,12 @@ import { cliRequestHeaders } from './client-provenance';
32 import { getCurrentCwdSessionId } from 'src/analytics/dispatch';
33 import { ComposioUserContext, ComposioUserContextLive } from './user-context';
34 import { ProjectContext } from './project-context';
24 -import { makeClientMetricsCollector } from './composio-client-metrics';
35 +import { makeClientMetricsCollector, type ClientMetricsCollector } from './composio-client-metrics';
36 import { ComposioClientConfigurationError, type ClientError } from './composio-errors';
37 +import { isClientConfigurationError } from 'src/utils/api-error-extraction';
38 import { MAX_CONCURRENT_REQUESTS_PER_ENDPOINT, decode, undecoded } from './composio-request';
39 import { lookupOperations, resourceOperations } from './composio-resource-operations';
40 import { composioSchemaLoaders } from './composio-schema-loaders';
29 -import { NodeOs } from './node-os';
41 import {
42 InvalidToolkitsError,
43 invalidToolkitOn404,
@@ -106,10 +117,7 @@ export interface ComposioClientSingletonShape {
117 * The client for the user's key and, when the working directory resolves to
118 * a project, that project's org and project.
119 */
109 - readonly get: () => Effect.Effect<
110 - ComposioClientShape,
111 - ComposioClientConfigurationError | NoSuchElementError
112 - >;
120 + readonly get: () => Effect.Effect<ComposioClientShape, ClientBuildError | NoSuchElementError>;
121 /**
122 * The client for an explicit scope. `userApiKey` defaults to the user's key.
123 */
@@ -117,7 +125,7 @@ export interface ComposioClientSingletonShape {
125 userApiKey?: string;
126 orgId?: string;
127 projectId?: string;
120 - }) => Effect.Effect<ComposioClientShape, ComposioClientConfigurationError | NoSuchElementError>;
128 + }) => Effect.Effect<ComposioClientShape, ClientBuildError | NoSuchElementError>;
129 /**
130 * Returns a snapshot of the accumulated metrics (total bytes received and
131 * request count) across every client this singleton built.
@@ -128,6 +136,23 @@ export interface ComposioClientSingletonShape {
136 }>;
137 }
138
139 +/**
140 + * Why a client could not be built: the client's own `ConfigurationError`
141 + * (a base URL it refuses, say) or a failure the CLI only knows as a thrown value.
142 + */
143 +export type ClientBuildError = ConfigurationError | ComposioClientConfigurationError;
144 +
145 +/**
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.
149 + */
150 +interface ClientScope {
151 + readonly userApiKey: string | undefined;
152 + readonly orgId: string | undefined;
153 + readonly projectId: string | undefined;
154 +}
155 +
156 /**
157 * Singleton service that lazily accesses `Config` only when needed, which is used to build and provide
158 * a Composio client instance from `@composio/client/effect`.
@@ -139,103 +164,99 @@ export interface ComposioClientSingletonShape {
164 * bytes on every operation; it is also passed as `userApiKey`, while the
165 * caller-placed header still wins at dispatch.
166 */
142 -const makeComposioClientSingleton = Effect.gen(function* () {
143 - const ctx = yield* ComposioUserContext;
144 - const projectContextOpt = yield* Effect.serviceOption(ProjectContext);
145 - const fs = yield* FileSystem.FileSystem;
146 - const path = yield* Path.Path;
147 - const os = yield* NodeOs;
148 - const metrics = makeClientMetricsCollector();
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* () {
161 - const apiKey = normalizeApiKey(params?.userApiKey ?? Option.getOrUndefined(ctx.data.apiKey));
162 - const cacheKey = JSON.stringify({
163 - apiKey: apiKey ?? null,
164 - orgId: params?.orgId ?? null,
165 - projectId: params?.projectId ?? null,
166 - });
167 - const cached = cache.get(cacheKey);
168 - if (cached) {
169 - return cached;
170 - }
171 -
172 - const cliSessionId = yield* getCurrentCwdSessionId().pipe(
173 - Effect.provideService(FileSystem.FileSystem, fs),
174 - Effect.provideService(Path.Path, path),
175 - Effect.provideService(NodeOs, os)
176 - );
167 +const makeComposioClientSingleton = (metrics: ClientMetricsCollector) =>
168 + Effect.gen(function* () {
169 + const ctx = yield* ComposioUserContext;
170 + const projectContextOpt = yield* Effect.serviceOption(ProjectContext);
171 + const httpClient = yield* HttpClient.HttpClient;
172
178 - const client = yield* Effect.try({
179 - try: () =>
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,
186 - orgApiKey: null,
187 - baseURL: ctx.data.baseURL,
188 - // Preserve support for explicitly configured HTTP backends.
189 - allowInsecureHTTP: true,
190 - deprecationNotices: 'off',
191 - defaultHeaders: buildDefaultHeaders({
192 - userApiKey: apiKey,
193 - orgId: params?.orgId,
194 - projectId: params?.projectId,
195 - cliSessionId,
196 - }),
197 - decode: true,
198 - schemas: composioSchemaLoaders,
199 - },
200 - httpClient
201 - ),
202 - catch: cause =>
203 - new ComposioClientConfigurationError({
204 - message: cause instanceof Error ? cause.message : global.String(cause),
205 - cause,
206 - }),
173 + const buildClient = (scope: ClientScope) =>
174 + Effect.gen(function* () {
175 + const cliSessionId = yield* getCurrentCwdSessionId();
176 +
177 + return yield* Effect.try({
178 + try: () =>
179 + // Responses are validated against the CLI's loader table unless a
180 + // call passes `decode: false`.
181 + makeComposioClient(
182 + {
183 + apiKey: null,
184 + userApiKey: scope.userApiKey ?? null,
185 + orgApiKey: null,
186 + baseURL: ctx.data.baseURL,
187 + // Preserve support for explicitly configured HTTP backends.
188 + allowInsecureHTTP: true,
189 + deprecationNotices: 'off',
190 + defaultHeaders: buildDefaultHeaders({
191 + userApiKey: scope.userApiKey,
192 + orgId: scope.orgId,
193 + projectId: scope.projectId,
194 + cliSessionId,
195 + }),
196 + decode: true,
197 + schemas: composioSchemaLoaders,
198 + },
199 + httpClient
200 + ),
201 + // The client's own error is kept as it is; anything else thrown is
202 + // reported as the CLI's configuration error.
203 + catch: (cause): ClientBuildError =>
204 + isClientConfigurationError(cause)
205 + ? cause
206 + : new ComposioClientConfigurationError({
207 + message: cause instanceof Error ? cause.message : String(cause),
208 + cause,
209 + }),
210 + });
211 });
212
209 - cache.set(cacheKey, client);
210 - return client;
213 + // One client per scope, built once: concurrent first callers share the
214 + // in-flight build. The lookup reads the session id from disk with the
215 + // services captured here. A failed build is not kept (its entry's time to
216 + // live is zero), so the next caller builds again instead of replaying a
217 + // configuration error that a later login may have fixed.
218 + const clients = yield* Cache.makeWith(buildClient, {
219 + capacity: 64,
220 + timeToLive: exit => (Exit.isSuccess(exit) ? Duration.infinity : Duration.zero),
221 });
222
213 - return {
214 - get: Effect.fn(function* () {
215 - const resolvedProjectContext = yield* Option.match(projectContextOpt, {
216 - onNone: () => Effect.succeed(Option.none()),
217 - onSome: projectContext =>
218 - projectContext.resolve.pipe(Effect.catch(() => Effect.succeed(Option.none()))),
219 - });
220 - return yield* Option.match(resolvedProjectContext, {
221 - onNone: () => getFor(),
222 - onSome: keys =>
223 - getFor({
224 - orgId: keys.orgId,
225 - projectId: keys.projectId,
226 - }),
227 - });
228 - }),
229 - getFor: Effect.fn(function* (params: {
230 - userApiKey?: string;
231 - orgId?: string;
232 - projectId?: string;
233 - }) {
234 - return yield* getFor(params);
235 - }),
236 - getMetrics: metrics.getMetrics,
237 - } satisfies ComposioClientSingletonShape;
238 -});
223 + // `ctx.data` is read per call: a login or logout changes the user key,
224 + // and with it the scope.
225 + const getFor = (params?: { userApiKey?: string; orgId?: string; projectId?: string }) =>
226 + Effect.suspend(() =>
227 + Cache.get(clients, {
228 + userApiKey: normalizeApiKey(params?.userApiKey ?? Option.getOrUndefined(ctx.data.apiKey)),
229 + orgId: params?.orgId,
230 + projectId: params?.projectId,
231 + })
232 + );
233 +
234 + return {
235 + get: Effect.fn(function* () {
236 + const resolvedProjectContext = yield* Option.match(projectContextOpt, {
237 + onNone: () => Effect.succeed(Option.none()),
238 + onSome: projectContext =>
239 + projectContext.resolve.pipe(Effect.catch(() => Effect.succeed(Option.none()))),
240 + });
241 + return yield* Option.match(resolvedProjectContext, {
242 + onNone: () => getFor(),
243 + onSome: keys =>
244 + getFor({
245 + orgId: keys.orgId,
246 + projectId: keys.projectId,
247 + }),
248 + });
249 + }),
250 + getFor: Effect.fn(function* (params: {
251 + userApiKey?: string;
252 + orgId?: string;
253 + projectId?: string;
254 + }) {
255 + return yield* getFor(params);
256 + }),
257 + getMetrics: metrics.getMetrics,
258 + } satisfies ComposioClientSingletonShape;
259 + });
260
261 /**
262 * The org/project a project-scoped request is made for, as a command resolved it.
@@ -249,9 +270,24 @@ export class ComposioClientSingleton extends Context.Service<
270 ComposioClientSingleton,
271 ComposioClientSingletonShape
272 >()('services/ComposioClientSingleton') {
252 - static readonly Default = Layer.effect(ComposioClientSingleton, makeComposioClientSingleton).pipe(
253 - Layer.provide(ComposioUserContextLive)
254 - );
273 + // The singleton and its transport share one metrics collector, created
274 + // when the layer is built. The transport is a fresh `FetchHttpClient.layer`
275 + // rather than the memoized one an application may already have built
276 + // (`cli-main.ts` provides its own), because that one calls
277 + // `globalThis.fetch` directly and counts nothing; this one is built over
278 + // the counting `fetch`.
279 + static readonly Default = Layer.unwrap(
280 + Effect.sync(() => {
281 + const metrics = makeClientMetricsCollector();
282 + return Layer.effect(ComposioClientSingleton, makeComposioClientSingleton(metrics)).pipe(
283 + Layer.provide(
284 + Layer.fresh(FetchHttpClient.layer).pipe(
285 + Layer.provide(Layer.succeed(FetchHttpClient.Fetch, metrics.fetch))
286 + )
287 + )
288 + );
289 + })
290 + ).pipe(Layer.provide(ComposioUserContextLive));
291 }
292 /**
293 * Repositories
@@ -374,11 +410,11 @@ const makeComposioToolkitsRepository = Effect.gen(function* () {
410 ): Effect.Effect<ReadonlyArray<string>, InvalidToolkitsError | ClientError> =>
411 Effect.gen(function* () {
412 // Normalize input slugs to lowercase for comparison
377 - const normalizedInputSlugs = toolkitSlugs.map(slug => String.toLowerCase(slug));
413 + const normalizedInputSlugs = toolkitSlugs.map(slug => Str.toLowerCase(slug));
414
415 // Fetch all available toolkits
416 const allToolkits = yield* getToolkits();
381 - const availableSlugs = allToolkits.map(toolkit => String.toLowerCase(toolkit.slug));
417 + const availableSlugs = allToolkits.map(toolkit => Str.toLowerCase(toolkit.slug));
418
419 // Find invalid slugs
420 const invalidSlugs = normalizedInputSlugs.filter(slug => !availableSlugs.includes(slug));
@@ -403,8 +439,8 @@ const makeComposioToolkitsRepository = Effect.gen(function* () {
439 toolkits: ReadonlyArray<Toolkit>,
440 toolkitSlugs: ReadonlyArray<string>
441 ): ReadonlyArray<Toolkit> => {
406 - const normalizedSlugs = new Set(toolkitSlugs.map(slug => String.toLowerCase(slug)));
407 - return toolkits.filter(toolkit => normalizedSlugs.has(String.toLowerCase(toolkit.slug)));
442 + const normalizedSlugs = new Set(toolkitSlugs.map(slug => Str.toLowerCase(slug)));
443 + return toolkits.filter(toolkit => normalizedSlugs.has(Str.toLowerCase(toolkit.slug)));
444 },
445 /**
446 * Validates that the requested toolkit versions exist in the API's available_versions.
ts/packages/cli/src/services/composio-errors.ts
+28 -1
@@ -1,6 +1,6 @@
1 import { Data } from 'effect';
2 import type { Cause } from 'effect';
3 -import type { ComposioError } from '@composio/client/effect';
3 +import type { ComposioError, ConfigurationError } from '@composio/client/effect';
4
5 type NoSuchElementError = Cause.NoSuchElementError;
6
@@ -23,6 +23,33 @@ export class HttpDecodingError extends Data.TaggedError('services/HttpDecodingEr
23
24 export type HttpError = ComposioError | HttpDecodingError;
25
26 +/**
27 + * A failure of a request made through the Effect client: a non-success status,
28 + * a transport failure, a timeout, or a response body that failed decoding.
29 + * `ConfigurationError` is the one client error that is not a request failure.
30 + */
31 +export type ClientApiError = Exclude<ComposioError, ConfigurationError>;
32 +
33 +/**
34 + * The tags of {@link ClientApiError}, for `Effect.catchTag`.
35 + */
36 +export const CLIENT_API_ERROR_TAGS = [
37 + '@composio/client/BadRequestError',
38 + '@composio/client/AuthenticationError',
39 + '@composio/client/PermissionDeniedError',
40 + '@composio/client/NotFoundError',
41 + '@composio/client/ConflictError',
42 + '@composio/client/UnprocessableEntityError',
43 + '@composio/client/RateLimitError',
44 + '@composio/client/InternalServerError',
45 + '@composio/client/APIError',
46 + '@composio/client/APIConnectionError',
47 + '@composio/client/APIConnectionTimeoutError',
48 + '@composio/client/DecodeError',
49 +] as const satisfies ReadonlyArray<ClientApiError['_tag']>;
50 +
51 +export type ClientApiErrorTag = (typeof CLIENT_API_ERROR_TAGS)[number];
52 +
53 /**
54 * Every failure a client call can produce: the request itself, as the client's
55 * own tagged error, decoding a CLI-owned contract, or obtaining a client from
ts/packages/cli/src/services/composio-request.ts
+1 -7
@@ -21,11 +21,5 @@ 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 - )
24 + Effect.catchTag('SchemaError', cause => new HttpDecodingError({ cause }))
25 );
ts/packages/cli/src/services/node-process.ts
+10 -1
@@ -1,11 +1,16 @@
1 import process from 'node:process';
2 -import { Context, Layer } from 'effect';
2 +import { Context, Effect, Layer } from 'effect';
3
4 export interface NodeProcessShape {
5 readonly cwd: string;
6 readonly execPath: string;
7 readonly platform: NodeJS.Platform;
8 readonly arch: string;
9 + /**
10 + * Sets the code the process exits with once it ends on its own, so a
11 + * command can report a failure it recovered from.
12 + */
13 + readonly setExitCode: (code: number) => Effect.Effect<void>;
14 }
15
16 // Service that wraps `node:process`, for testing purposes.
@@ -17,5 +22,9 @@ export class NodeProcess extends Context.Service<NodeProcess, NodeProcessShape>(
22 execPath: process.execPath,
23 platform: process.platform,
24 arch: process.arch,
25 + setExitCode: code =>
26 + Effect.sync(() => {
27 + process.exitCode = code;
28 + }),
29 }));
30 }
ts/packages/cli/src/services/tool-file-uploads.ts
+210 -181
@@ -1,12 +1,12 @@
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.
1 +// The upload pipeline runs in the caller's fiber: the FileSystem read and the
2 +// presigned-URL request are effects of their own, and the core SDK's
3 +// promise-based helpers (the path and URL guards, the body reader, the upload
4 +// transport) are wrapped at each call. The caller resolves the platform
5 +// services and the Composio client and passes the instances in as parameters.
6 import type * as FileSystem from 'effect/FileSystem';
7 import type * as Path from 'effect/Path';
8 -import type { ComposioClientShape } from '@composio/client/effect';
9 -import { Cause, Data, Effect, Exit, Predicate } from 'effect';
8 +import type { ComposioClientShape, ComposioError } from '@composio/client/effect';
9 +import { Data, Effect, Predicate } from 'effect';
10 import { guessToolkitFromToolSlug } from 'src/utils/toolkit-from-tool-slug';
11
12 type JsonSchema = Record<string, unknown>;
@@ -15,8 +15,8 @@ type JsonSchema = Record<string, unknown>;
15 // a file input, so they are imported on that path rather than at module scope:
16 // `@composio/core`'s root entry evaluates the whole SDK, which every command
17 // would otherwise pay for at startup. The module registry memoizes the import.
18 -const loadCoreFileUploadHelpers = () => import('@composio/core');
19 -const loadSsrfSafeFetch = () => import('@composio/core/utils/ssrf-guard');
18 +const loadCoreFileUploadHelpers = Effect.promise(() => import('@composio/core'));
19 +const loadSsrfSafeFetch = Effect.promise(() => import('@composio/core/utils/ssrf-guard'));
20
21 export class ToolFileUploadError extends Data.TaggedError('services/ToolFileUploadError')<{
22 readonly cause?: unknown;
@@ -25,6 +25,28 @@ export class ToolFileUploadError extends Data.TaggedError('services/ToolFileUplo
25 readonly status?: number;
26 }> {}
27
28 +/**
29 + * Every failure of {@link uploadToolInputFiles}: reading or uploading a file,
30 + * or the presigned-URL request, as the client's own error.
31 + */
32 +export type ToolInputUploadError = ToolFileUploadError | ComposioError;
33 +
34 +// What a thrown value from the core SDK's helpers, or a platform error of the
35 +// local read, becomes: the file could not be read as a source. An error this
36 +// module raised itself passes through.
37 +const asSourceReadError = (cause: unknown): ToolFileUploadError =>
38 + cause instanceof ToolFileUploadError
39 + ? cause
40 + : new ToolFileUploadError({
41 + cause,
42 + message: cause instanceof Error ? cause.message : String(cause),
43 + reason: 'source-read',
44 + });
45 +
46 +// Releases a body this module does not read, ignoring a cancellation failure.
47 +const discardBody = (response: Response) =>
48 + Effect.ignore(Effect.tryPromise(() => response.body?.cancel() ?? Promise.resolve()));
49 +
50 const isFileLike = (value: unknown): value is File =>
51 typeof File !== 'undefined' && value instanceof File;
52
@@ -149,88 +171,85 @@ export const findFileUploadablePaths = (
171 });
172 };
173
152 -const readFileFromUrl = async (path: Path.Path, url: string) => {
153 - const { ssrfSafeFetch } = await loadSsrfSafeFetch();
154 - const response = await ssrfSafeFetch(url);
155 - if (!response.ok) {
156 - await response.body?.cancel().catch(() => undefined);
157 - throw new ToolFileUploadError({
158 - message: `Failed to fetch file: ${response.statusText}`,
159 - reason: 'source-fetch',
160 - status: response.status,
174 +const readFileFromUrl = (path: Path.Path, url: string) =>
175 + Effect.gen(function* () {
176 + const { ssrfSafeFetch } = yield* loadSsrfSafeFetch;
177 + const response = yield* Effect.tryPromise({
178 + try: signal => ssrfSafeFetch(url, { signal }),
179 + catch: asSourceReadError,
180 });
162 - }
163 -
164 - // Same cap as the core SDK's URL uploads: a remote server must not be able
165 - // to exhaust memory with an oversized or never-ending body. Copied into a
166 - // fresh ArrayBuffer-backed view for the same reason as readFileFromDisk.
167 - const { readResponseBodyWithLimit } = await loadCoreFileUploadHelpers();
168 - const bytes = new Uint8Array(await readResponseBodyWithLimit(response));
169 - const parsedUrl = new URL(url);
170 - const fileName = path.basename(parsedUrl.pathname) || `file-${Date.now()}`;
171 -
172 - return {
173 - bytes,
174 - fileName,
175 - mimeType: response.headers.get('content-type') || 'application/octet-stream',
176 - };
177 -};
181 + if (!response.ok) {
182 + yield* discardBody(response);
183 + return yield* new ToolFileUploadError({
184 + message: `Failed to fetch file: ${response.statusText}`,
185 + reason: 'source-fetch',
186 + status: response.status,
187 + });
188 + }
189
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, {
186 - onFailure: cause => Promise.reject<A>(Cause.squash(cause)),
187 - onSuccess: value => Promise.resolve(value),
188 - })
189 - );
190 + // Same cap as the core SDK's URL uploads: a remote server must not be able
191 + // to exhaust memory with an oversized or never-ending body. Copied into a
192 + // fresh ArrayBuffer-backed view for the same reason as readFileFromDisk.
193 + const { readResponseBodyWithLimit } = yield* loadCoreFileUploadHelpers;
194 + const body = yield* Effect.tryPromise({
195 + try: () => readResponseBodyWithLimit(response),
196 + catch: asSourceReadError,
197 + });
198 + const bytes = new Uint8Array(body);
199 + const parsedUrl = new URL(url);
200 + const fileName = path.basename(parsedUrl.pathname) || `file-${Date.now()}`;
201
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
197 - // is the single canonical guard shared with `@composio/core`; without it the
198 - // CLI's upload path would silently exfiltrate ~/.ssh/id_rsa, ~/.aws/credentials,
199 - // .env files, etc. (issue #3746 / GHSA-hp3h-89pf-5q58). URLs and File objects
200 - // are intentionally not path-checked, matching the core SDK.
201 - //
202 - // The CLI intentionally exposes NO opt-out for this guard (unlike the core/Python
203 - // SDKs' `sensitiveFileUploadProtection` flag): the primary attack vector is an
204 - // agent that has been prompt-injected into supplying its own tool arguments, so a
205 - // `--force`/env override would hand that attacker a trivial bypass. Pass a
206 - // CLI-appropriate remediation so the error does not advertise an SDK-only opt-out.
207 - const { assertSafeFileUploadPath } = await loadCoreFileUploadHelpers();
208 - assertSafeFileUploadPath(filePath, {
209 - remediation:
210 - 'The Composio CLI always enforces this denylist and has no opt-out. To upload this ' +
211 - 'file, copy it to a location outside sensitive directories (e.g. ~/.ssh, ~/.aws) and ' +
212 - 'pass the copy instead.',
202 + return {
203 + bytes,
204 + fileName,
205 + mimeType: response.headers.get('content-type') || 'application/octet-stream',
206 + };
207 });
214 - return {
215 - // Copy into a fresh ArrayBuffer-backed view: `fetch` bodies reject the
216 - // wider ArrayBufferLike-backed Uint8Array that FileSystem returns.
217 - bytes: new Uint8Array(await readLocalFileBytes(fs, filePath)),
218 - fileName: path.basename(filePath),
219 - mimeType: 'application/octet-stream',
220 - };
221 -};
208
223 -const readUploadSource = async (
224 - fs: FileSystem.FileSystem,
225 - path: Path.Path,
226 - file: string | File
227 -) => {
228 - if (isFileLike(file)) {
209 +const readFileFromDisk = (fs: FileSystem.FileSystem, path: Path.Path, filePath: string) =>
210 + Effect.gen(function* () {
211 + // Enforce the sensitive-path denylist at the lowest-level local read, so any
212 + // caller of this reader (not just `uploadToolInputFiles`) is protected. This
213 + // is the single canonical guard shared with `@composio/core`; without it the
214 + // CLI's upload path would silently exfiltrate ~/.ssh/id_rsa, ~/.aws/credentials,
215 + // .env files, etc. (issue #3746 / GHSA-hp3h-89pf-5q58). URLs and File objects
216 + // are intentionally not path-checked, matching the core SDK.
217 + //
218 + // The CLI intentionally exposes NO opt-out for this guard (unlike the core/Python
219 + // SDKs' `sensitiveFileUploadProtection` flag): the primary attack vector is an
220 + // agent that has been prompt-injected into supplying its own tool arguments, so a
221 + // `--force`/env override would hand that attacker a trivial bypass. Pass a
222 + // CLI-appropriate remediation so the error does not advertise an SDK-only opt-out.
223 + const { assertSafeFileUploadPath } = yield* loadCoreFileUploadHelpers;
224 + yield* Effect.try({
225 + try: () =>
226 + assertSafeFileUploadPath(filePath, {
227 + remediation:
228 + 'The Composio CLI always enforces this denylist and has no opt-out. To upload this ' +
229 + 'file, copy it to a location outside sensitive directories (e.g. ~/.ssh, ~/.aws) and ' +
230 + 'pass the copy instead.',
231 + }),
232 + catch: asSourceReadError,
233 + });
234 + const bytes = yield* fs.readFile(filePath).pipe(Effect.mapError(asSourceReadError));
235 return {
230 - bytes: new Uint8Array(await file.arrayBuffer()),
231 - fileName: file.name || `file-${Date.now()}`,
232 - mimeType: file.type || 'application/octet-stream',
236 + // Copy into a fresh ArrayBuffer-backed view: `fetch` bodies reject the
237 + // wider ArrayBufferLike-backed Uint8Array that FileSystem returns.
238 + bytes: new Uint8Array(bytes),
239 + fileName: path.basename(filePath),
240 + mimeType: 'application/octet-stream',
241 };
242 + });
243 +
244 +const readUploadSource = (fs: FileSystem.FileSystem, path: Path.Path, file: string | File) => {
245 + if (isFileLike(file)) {
246 + return Effect.tryPromise({ try: () => file.arrayBuffer(), catch: asSourceReadError }).pipe(
247 + Effect.map(buffer => ({
248 + bytes: new Uint8Array(buffer),
249 + fileName: file.name || `file-${Date.now()}`,
250 + mimeType: file.type || 'application/octet-stream',
251 + }))
252 + );
253 }
254
255 if (typeof file === 'string' && /^https?:\/\//i.test(file)) {
@@ -241,26 +260,28 @@ const readUploadSource = async (
260 return readFileFromDisk(fs, path, file);
261 }
262
244 - throw new ToolFileUploadError({
245 - message: 'Unsupported upload source',
246 - reason: 'unsupported-source',
247 - });
263 + return Effect.fail(
264 + new ToolFileUploadError({
265 + message: 'Unsupported upload source',
266 + reason: 'unsupported-source',
267 + })
268 + );
269 };
270
250 -const uploadFile = async (params: {
271 +const uploadFile = (params: {
272 readonly fs: FileSystem.FileSystem;
273 readonly path: Path.Path;
274 readonly file: string | File;
275 readonly toolSlug: string;
276 readonly toolkitSlug: string;
277 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');
262 - const presigned = await runToPromise(
263 - params.client.files.createPresignedURL(
278 +}) =>
279 + Effect.gen(function* () {
280 + const fileData = yield* readUploadSource(params.fs, params.path, params.file);
281 + // eslint-disable-next-line no-restricted-imports -- MD5 for the presigned-upload checksum is not available in Web Crypto
282 + const { createHash } = yield* Effect.promise(() => import('node:crypto'));
283 + const md5 = createHash('md5').update(fileData.bytes).digest('hex');
284 + const presigned = yield* params.client.files.createPresignedURL(
285 {
286 filename: fileData.fileName,
287 mimetype: fileData.mimeType,
@@ -269,37 +290,40 @@ const uploadFile = async (params: {
290 toolkit_slug: params.toolkitSlug,
291 },
292 { decode: false }
272 - )
273 - );
274 -
275 - const { ssrfSafeFetch } = await loadSsrfSafeFetch();
276 - const uploadResponse = await ssrfSafeFetch(presigned.new_presigned_url, {
277 - method: 'PUT',
278 - body: fileData.bytes,
279 - headers: {
280 - 'Content-Type': fileData.mimeType,
281 - 'Content-Length': fileData.bytes.byteLength.toString(),
282 - },
283 - });
293 + );
294
285 - if (!uploadResponse.ok) {
286 - await uploadResponse.body?.cancel().catch(() => undefined);
287 - throw new ToolFileUploadError({
288 - message: `Failed to upload file to S3: ${uploadResponse.statusText}`,
289 - reason: 'upload',
290 - status: uploadResponse.status,
295 + const { ssrfSafeFetch } = yield* loadSsrfSafeFetch;
296 + const uploadResponse = yield* Effect.tryPromise({
297 + try: signal =>
298 + ssrfSafeFetch(presigned.new_presigned_url, {
299 + method: 'PUT',
300 + body: fileData.bytes,
301 + headers: {
302 + 'Content-Type': fileData.mimeType,
303 + 'Content-Length': fileData.bytes.byteLength.toString(),
304 + },
305 + signal,
306 + }),
307 + catch: asSourceReadError,
308 });
292 - }
293 - await uploadResponse.body?.cancel().catch(() => undefined);
309
295 - return {
296 - name: fileData.fileName,
297 - mimetype: fileData.mimeType,
298 - s3key: presigned.key,
299 - };
300 -};
310 + yield* discardBody(uploadResponse);
311 + if (!uploadResponse.ok) {
312 + return yield* new ToolFileUploadError({
313 + message: `Failed to upload file to S3: ${uploadResponse.statusText}`,
314 + reason: 'upload',
315 + status: uploadResponse.status,
316 + });
317 + }
318
302 -const hydrateFileUploads = async (
319 + return {
320 + name: fileData.fileName,
321 + mimetype: fileData.mimeType,
322 + s3key: presigned.key,
323 + };
324 + });
325 +
326 +const hydrateFileUploads = (
327 value: unknown,
328 schema: JsonSchema | undefined,
329 ctx: {
@@ -309,60 +333,64 @@ const hydrateFileUploads = async (
333 readonly toolkitSlug: string;
334 readonly client: ComposioClientShape;
335 }
312 -): Promise<unknown> => {
313 - if (schema?.file_uploadable === true) {
314 - if (typeof value !== 'string' && !isFileLike(value)) {
315 - return value;
316 - }
336 +): Effect.Effect<unknown, ToolInputUploadError> =>
337 + Effect.gen(function* () {
338 + if (schema?.file_uploadable === true) {
339 + if (typeof value !== 'string' && !isFileLike(value)) {
340 + return value;
341 + }
342
318 - return uploadFile({
319 - fs: ctx.fs,
320 - path: ctx.path,
321 - file: value,
322 - toolSlug: ctx.toolSlug,
323 - toolkitSlug: ctx.toolkitSlug,
324 - client: ctx.client,
325 - });
326 - }
343 + return yield* uploadFile({
344 + fs: ctx.fs,
345 + path: ctx.path,
346 + file: value,
347 + toolSlug: ctx.toolSlug,
348 + toolkitSlug: ctx.toolkitSlug,
349 + client: ctx.client,
350 + });
351 + }
352
328 - const uploadableVariants = getSchemaVariants(schema).filter(schemaHasFileUploadable);
329 - if (uploadableVariants.length > 0) {
330 - let nextValue = value;
331 - for (const variant of uploadableVariants) {
332 - nextValue = await hydrateFileUploads(nextValue, variant, ctx);
353 + const uploadableVariants = getSchemaVariants(schema).filter(schemaHasFileUploadable);
354 + if (uploadableVariants.length > 0) {
355 + let nextValue = value;
356 + for (const variant of uploadableVariants) {
357 + nextValue = yield* hydrateFileUploads(nextValue, variant, ctx);
358 + }
359 + return nextValue;
360 }
334 - return nextValue;
335 - }
361
337 - if (isSchemaRecord(schema?.properties) && Predicate.isObject(value)) {
338 - const properties = schema.properties;
339 - const entries = await Promise.all(
340 - Object.entries(value).map(async ([key, entryValue]) => [
341 - key,
342 - await hydrateFileUploads(
343 - entryValue,
344 - isSchemaRecord(properties[key]) ? properties[key] : undefined,
345 - ctx
362 + if (isSchemaRecord(schema?.properties) && Predicate.isObject(value)) {
363 + const properties = schema.properties;
364 + const entries = yield* Effect.all(
365 + Object.entries(value).map(([key, entryValue]) =>
366 + hydrateFileUploads(
367 + entryValue,
368 + isSchemaRecord(properties[key]) ? properties[key] : undefined,
369 + ctx
370 + ).pipe(Effect.map(hydrated => [key, hydrated] as const))
371 ),
347 - ])
348 - );
349 - return Object.fromEntries(entries);
350 - }
372 + { concurrency: 'unbounded' }
373 + );
374 + return Object.fromEntries(entries);
375 + }
376
352 - if (schema?.type === 'array' && Array.isArray(value) && schema.items) {
353 - const itemSchema = Array.isArray(schema.items)
354 - ? schema.items.find(isSchemaRecord)
355 - : isSchemaRecord(schema.items)
356 - ? schema.items
357 - : undefined;
377 + if (schema?.type === 'array' && Array.isArray(value) && schema.items) {
378 + const itemSchema = Array.isArray(schema.items)
379 + ? schema.items.find(isSchemaRecord)
380 + : isSchemaRecord(schema.items)
381 + ? schema.items
382 + : undefined;
383
359 - return Promise.all(value.map(item => hydrateFileUploads(item, itemSchema, ctx)));
360 - }
384 + return yield* Effect.all(
385 + value.map(item => hydrateFileUploads(item, itemSchema, ctx)),
386 + { concurrency: 'unbounded' }
387 + );
388 + }
389
362 - return value;
363 -};
390 + return value;
391 + });
392
365 -export const uploadToolInputFiles = async (params: {
393 +export const uploadToolInputFiles = (params: {
394 readonly fs: FileSystem.FileSystem;
395 readonly path: Path.Path;
396 readonly toolSlug: string;
@@ -370,18 +398,19 @@ export const uploadToolInputFiles = async (params: {
398 readonly inputSchema: JsonSchema;
399 readonly client: ComposioClientShape;
400 readonly toolkitSlug?: string;
373 -}): Promise<Record<string, unknown>> => {
374 - if (!schemaHasFileUploadable(params.inputSchema)) {
375 - return params.arguments_;
376 - }
401 +}): Effect.Effect<Record<string, unknown>, ToolInputUploadError> =>
402 + Effect.gen(function* () {
403 + if (!schemaHasFileUploadable(params.inputSchema)) {
404 + return params.arguments_;
405 + }
406
378 - const hydrated = await hydrateFileUploads(params.arguments_, params.inputSchema, {
379 - fs: params.fs,
380 - path: params.path,
381 - toolSlug: params.toolSlug,
382 - toolkitSlug: params.toolkitSlug ?? guessToolkitFromToolSlug(params.toolSlug) ?? 'unknown',
383 - client: params.client,
384 - });
407 + const hydrated = yield* hydrateFileUploads(params.arguments_, params.inputSchema, {
408 + fs: params.fs,
409 + path: params.path,
410 + toolSlug: params.toolSlug,
411 + toolkitSlug: params.toolkitSlug ?? guessToolkitFromToolSlug(params.toolSlug) ?? 'unknown',
412 + client: params.client,
413 + });
414
386 - return Predicate.isObject(hydrated) ? hydrated : params.arguments_;
387 -};
415 + return Predicate.isObject(hydrated) ? hydrated : params.arguments_;
416 + });
ts/packages/cli/src/services/tools-executor.ts
+23 -21
@@ -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 { ComposioClientShape } from '@composio/client/effect';
4 +import { isComposioError, type ComposioClientShape } from '@composio/client/effect';
5 import type {
6 SessionExecuteResponse,
7 SessionExecuteMetaResponse,
@@ -203,26 +203,28 @@ export const ToolsExecutorLive = Layer.effect(
203 return Effect.succeed(params.arguments);
204 }
205
206 - return Effect.tryPromise({
207 - try: () =>
208 - uploadToolInputFiles({
209 - fs,
210 - path,
211 - toolSlug: slug,
212 - toolkitSlug,
213 - arguments_: params.arguments,
214 - inputSchema: definition.schema,
215 - client: resolvedClient,
216 - }),
217 - catch: cause =>
218 - cause instanceof ToolFileUploadError
219 - ? cause
220 - : new ToolFileUploadError({
221 - cause,
222 - message: cause instanceof Error ? cause.message : String(cause),
223 - reason: 'source-read',
224 - }),
225 - });
206 + // A presigned-URL request the API refused is reported as
207 + // an upload failure of the source, with the client's error
208 + // as its cause.
209 + return uploadToolInputFiles({
210 + fs,
211 + path,
212 + toolSlug: slug,
213 + toolkitSlug,
214 + arguments_: params.arguments,
215 + inputSchema: definition.schema,
216 + client: resolvedClient,
217 + }).pipe(
218 + Effect.catchIf(
219 + isComposioError,
220 + cause =>
221 + new ToolFileUploadError({
222 + cause,
223 + message: cause.message,
224 + reason: 'source-read',
225 + })
226 + )
227 + );
228 })
229 );
230
ts/packages/cli/src/utils/api-error-extraction.ts
+9 -8
@@ -14,21 +14,22 @@ import {
14 isAPIError,
15 isComposioError,
16 type APIConnectionError,
17 - type APIConnectionTimeoutError,
17 type APIStatusError,
18 + type ConfigurationError,
19 type DecodeError,
20 } from '@composio/client/effect';
21 import { Predicate } from 'effect';
22 +import { CLIENT_API_ERROR_TAGS, type ClientApiError } from 'src/services/composio-errors';
23
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;
24 +export type { ClientApiError };
25 +
26 +const clientApiErrorTags: ReadonlySet<string> = new Set(CLIENT_API_ERROR_TAGS);
27
28 export const isClientApiError = (value: unknown): value is ClientApiError =>
31 - isComposioError(value) && !Predicate.isTagged(value, '@composio/client/ConfigurationError');
29 + isComposioError(value) && clientApiErrorTags.has(value._tag);
30 +
31 +export const isClientConfigurationError = (value: unknown): value is ConfigurationError =>
32 + isComposioError(value) && Predicate.isTagged(value, '@composio/client/ConfigurationError');
33
34 export const isClientConnectionError = (value: unknown): value is APIConnectionError =>
35 isComposioError(value) && Predicate.isTagged(value, '@composio/client/APIConnectionError');
ts/packages/cli/test/__utils__/services/node-process-test.ts new
+24
@@ -0,0 +1,24 @@
1 +import { Effect, Layer } from 'effect';
2 +import { NodeProcess } from 'src/services/node-process';
3 +
4 +/**
5 + * A `NodeProcess` that records the exit code a handler sets instead of
6 + * touching the real process, so a test can assert it.
7 + */
8 +export const recordingNodeProcess = (cwd = '/tmp') => {
9 + let exitCode: number | undefined;
10 + const layer = Layer.succeed(
11 + NodeProcess,
12 + NodeProcess.of({
13 + cwd,
14 + execPath: `${cwd}/composio`,
15 + platform: 'darwin',
16 + arch: 'arm64',
17 + setExitCode: code =>
18 + Effect.sync(() => {
19 + exitCode = code;
20 + }),
21 + })
22 + );
23 + return { layer, exitCode: () => exitCode };
24 +};
ts/packages/cli/test/__utils__/services/test-layer.ts
+5
@@ -911,6 +911,11 @@ export const TestLayer = (input?: TestLiveInput) =>
911 execPath: input?.execPath ? path.resolve(cwd, input.execPath) : path.join(cwd, 'composio'),
912 platform: 'darwin',
913 arch: 'arm64',
914 + // Command tests read the exit code off the real process.
915 + setExitCode: code =>
916 + Effect.sync(() => {
917 + process.exitCode = code;
918 + }),
919 })
920 );
921
ts/packages/cli/test/src/effects/handle-http-error.test.ts
+34 -32
@@ -4,12 +4,14 @@ import {
4 BadRequestError as ClientBadRequestError,
5 ConfigurationError as ClientConfigurationError,
6 DecodeError as ClientDecodeError,
7 + type ComposioError,
8 } from '@composio/client/effect';
9 import { describe, expect, it } from '@effect/vitest';
10 import { Effect } from 'effect';
10 -import { afterEach } from 'vitest';
11 -import { catchClientApiError, handleClientApiError } from 'src/effects/handle-http-error';
11 +import { handleClientApiError } from 'src/effects/handle-http-error';
12 +import { CLIENT_API_ERROR_TAGS } from 'src/services/composio-errors';
13 import { TerminalUI } from 'src/services/terminal-ui';
14 +import { recordingNodeProcess } from 'test/__utils__/services/node-process-test';
15 import { terminalUITestImpl } from 'test/__utils__/services/terminal-ui-test';
16
17 const envelope = {
@@ -52,7 +54,8 @@ const options = {
54 };
55
56 // A TerminalUI whose stderr is not a TTY, recording every line the handler
55 -// writes together with the channel it went to.
57 +// writes together with the channel it went to, and a NodeProcess recording
58 +// the exit code it sets.
59 const recordingUI = () => {
60 const lines: Array<string> = [];
61 const record = (channel: string) => (message: string) =>
@@ -64,19 +67,16 @@ const recordingUI = () => {
67 error: record('stderr'),
68 log: { ...terminalUITestImpl.log, error: record('log.error'), step: record('log.step') },
69 });
67 - return { ui, lines };
70 + const proc = recordingNodeProcess();
71 + return { ui, lines, exitCode: proc.exitCode, provide: Effect.provide(proc.layer) };
72 };
73
74 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();
77 + const { ui, lines, exitCode, provide } = recordingUI();
78
79 - const result = yield* handleClientApiError(ui, options)(clientStatusError);
79 + const result = yield* handleClientApiError(ui, options)(clientStatusError).pipe(provide);
80
81 expect(result).toBe('fallback');
82 expect(lines).toStrictEqual([
@@ -86,7 +86,7 @@ describe('handleClientApiError', () => {
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);
89 + expect(exitCode()).toBe(1);
90 })
91 );
92
@@ -101,9 +101,9 @@ describe('handleClientApiError', () => {
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();
104 + const { ui, lines, exitCode, provide } = recordingUI();
105
106 - const result = yield* handleClientApiError(ui, options)(error);
106 + const result = yield* handleClientApiError(ui, options)(error).pipe(provide);
107
108 expect(result).toBe('fallback');
109 expect(lines).toStrictEqual([
@@ -112,19 +112,19 @@ describe('handleClientApiError', () => {
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);
115 + expect(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();
121 + const { ui, lines, exitCode, provide } = 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);
127 + })(clientDecodeError).pipe(provide);
128
129 expect(result).toBe('fallback');
130 expect(lines).toStrictEqual([
@@ -133,13 +133,13 @@ describe('handleClientApiError', () => {
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);
136 + expect(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();
142 + const { ui, lines, provide } = recordingUI();
143
144 yield* handleClientApiError(ui, {
145 ...options,
@@ -147,7 +147,7 @@ describe('handleClientApiError', () => {
147 Effect.succeed([
148 { label: 'ac_similar', command: '> composio dev auth-configs info "ac_similar"' },
149 ]),
150 - })(clientStatusError);
150 + })(clientStatusError).pipe(provide);
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"'
@@ -156,11 +156,7 @@ describe('handleClientApiError', () => {
156 );
157 });
158
159 -describe('catchClientApiError', () => {
160 - afterEach(() => {
161 - process.exitCode = undefined;
162 - });
163 -
159 +describe('Effect.catchTag(CLIENT_API_ERROR_TAGS, handleClientApiError(...))', () => {
160 it.effect.each([
161 clientStatusError,
162 clientDecodeError,
@@ -174,28 +170,34 @@ describe('catchClientApiError', () => {
170 new ClientAPIConnectionTimeoutError({ message: 'Request timed out.', method: 'GET', url }),
171 ])('recovers from $_tag with the fallback value', error =>
172 Effect.gen(function* () {
177 - const { ui, lines } = recordingUI();
173 + const { ui, lines, exitCode, provide } = recordingUI();
174
179 - const result = yield* Effect.fail(error).pipe(catchClientApiError(ui, options));
175 + // The tag list recovers from the client's whole error union.
176 + const result = yield* Effect.fail<ComposioError>(error).pipe(
177 + Effect.catchTag(CLIENT_API_ERROR_TAGS, handleClientApiError(ui, options)),
178 + provide
179 + );
180
181 expect(result).toBe('fallback');
182 expect(lines).not.toStrictEqual([]);
183 - expect(process.exitCode).toBe(1);
183 + expect(exitCode()).toBe(1);
184 })
185 );
186
187 it.effect('leaves other failures alone', () =>
188 Effect.gen(function* () {
189 - const { ui, lines } = recordingUI();
189 + const { ui, lines, exitCode, provide } = 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);
192 + const failure = yield* Effect.fail<ComposioError>(error).pipe(
193 + Effect.catchTag(CLIENT_API_ERROR_TAGS, handleClientApiError(ui, options)),
194 + provide,
195 + Effect.flip
196 + );
197
198 expect(failure).toBe(error);
199 expect(lines).toStrictEqual([]);
198 - expect(process.exitCode).toBeUndefined();
200 + expect(exitCode()).toBeUndefined();
201 })
202 );
203 });
ts/packages/cli/test/src/services/composio-client-singleton.test.ts
+59 -2
@@ -430,6 +430,50 @@ describe('ComposioClientSingleton client', () => {
430 }).pipe(Effect.provide(singletonLayer(baseConfig())))
431 );
432
433 + it.effect('hands concurrent first callers of a scope the same client', () =>
434 + Effect.gen(function* () {
435 + const clientSingleton = yield* ComposioClientSingleton;
436 + const scope = { userApiKey: 'uak_a', orgId: 'org_a', projectId: 'proj_a' };
437 +
438 + const [first, second, third] = yield* Effect.all(
439 + [
440 + clientSingleton.getFor(scope),
441 + clientSingleton.getFor({ ...scope }),
442 + clientSingleton.getFor(scope),
443 + ],
444 + { concurrency: 'unbounded' }
445 + );
446 +
447 + expect(second).toBe(first);
448 + expect(third).toBe(first);
449 + }).pipe(Effect.provide(singletonLayer(baseConfig())))
450 + );
451 +
452 + it.effect('counts requests on its own transport beside an application FetchHttpClient', () => {
453 + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(okResponse());
454 +
455 + return Effect.gen(function* () {
456 + const clientSingleton = yield* ComposioClientSingleton;
457 + const client = yield* clientSingleton.getFor({ userApiKey: 'uak_scope' });
458 + yield* listTools(client);
459 +
460 + expect(fetchSpy).toHaveBeenCalledOnce();
461 + expect((yield* clientSingleton.getMetrics()).requests).toBe(1);
462 + }).pipe(
463 + // The application's transport is built first, so a memoized
464 + // `FetchHttpClient.layer` would be the one that counts nothing.
465 + Effect.provide(
466 + Layer.provide(
467 + ComposioClientSingleton.Default,
468 + Layer.merge(
469 + withConfigLayer(baseConfig(), tempy.temporaryDirectory()),
470 + FetchHttpClient.layer
471 + )
472 + )
473 + )
474 + );
475 + });
476 +
477 it.effect('ignores ambient COMPOSIO_API_KEY and COMPOSIO_BASE_URL', () => {
478 const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(okResponse());
479 vi.stubEnv('COMPOSIO_API_KEY', 'ak_ambient');
@@ -565,12 +609,25 @@ describe('ComposioClientSingleton client', () => {
609 }).pipe(Effect.provide(singletonLayer(baseConfig([['COMPOSIO_USER_API_KEY', 'uak_strict']]))));
610 });
611
568 - it.effect('reports an invalid base URL as a configuration error', () =>
612 + it.effect("reports an invalid base URL as the client's own configuration error", () =>
613 Effect.gen(function* () {
614 const clientSingleton = yield* ComposioClientSingleton;
615 const error = yield* Effect.flip(clientSingleton.getFor({ userApiKey: 'uak_a' }));
616
573 - expect(error._tag).toBe('services/ComposioClientConfigurationError');
617 + expect(error._tag).toBe('@composio/client/ConfigurationError');
618 + }).pipe(Effect.provide(singletonLayer(new Map([['COMPOSIO_BASE_URL', 'not a url']]))))
619 + );
620 +
621 + it.effect('does not keep a client that could not be built', () =>
622 + Effect.gen(function* () {
623 + const clientSingleton = yield* ComposioClientSingleton;
624 + const scope = { userApiKey: 'uak_a' };
625 +
626 + const first = yield* Effect.flip(clientSingleton.getFor(scope));
627 + const second = yield* Effect.flip(clientSingleton.getFor(scope));
628 +
629 + expect(first._tag).toBe('@composio/client/ConfigurationError');
630 + expect(second).not.toBe(first);
631 }).pipe(Effect.provide(singletonLayer(new Map([['COMPOSIO_BASE_URL', 'not a url']]))))
632 );
633 });
ts/packages/cli/test/src/services/composio-clients-cached.test.ts
+33
@@ -239,6 +239,39 @@ describe('ComposioToolkitsRepositoryCached', () => {
239 )
240 );
241
242 + it.effect('shares one in-flight project fetch between concurrent first callers', () =>
243 + withCountingRepository(
244 + () => Effect.die('the project lookup should not read the catalog'),
245 + ({ projectCalls }) =>
246 + Effect.gen(function* () {
247 + const repository = yield* ComposioToolkitsRepository;
248 + const scope = { orgId: 'org_a', projectId: 'pr_a' };
249 +
250 + const results = yield* Effect.all(
251 + [
252 + repository.getProjectToolkits(scope),
253 + repository.getProjectToolkits({ ...scope }),
254 + repository.getProjectToolkits(scope),
255 + ],
256 + { concurrency: 'unbounded' }
257 + );
258 +
259 + expect(results.map(toolkits => toolkits.map(t => t.slug))).toEqual([
260 + ['custom_pr_a'],
261 + ['custom_pr_a'],
262 + ['custom_pr_a'],
263 + ]);
264 + expect(projectCalls()).toBe(1);
265 + }),
266 + [],
267 + // The fetch yields before answering, so every caller is waiting on it.
268 + scope =>
269 + Effect.yieldNow.pipe(
270 + Effect.as([makeToolkitFixture(`custom_${scope?.projectId ?? 'unscoped'}`)])
271 + )
272 + )
273 + );
274 +
275 it.effect('passes an uncached method straight through to the underlying repository', () =>
276 Effect.gen(function* () {
277 const searchTools = vi.fn(() =>
ts/packages/cli/test/src/services/composio-clients.test.ts
+4 -3
@@ -22,6 +22,7 @@ import { TerminalUI } from 'src/services/terminal-ui';
22 import { makeOrgProject, makeSessionInfo } from 'test/__utils__/models/account';
23 import { makeToolkitFixture } from 'test/__utils__/models/toolkits';
24 import { terminalUITestImpl } from 'test/__utils__/services/terminal-ui-test';
25 +import { recordingNodeProcess } from 'test/__utils__/services/node-process-test';
26
27 // Exercise real user-context/config resolution without opening the OS credential store.
28 vi.mock('@composio/cli-keyring/effect', async importOriginal => {
@@ -521,16 +522,16 @@ describe('composio-clients', () => {
522 step: message => Effect.sync(() => void steps.push(message)),
523 },
524 });
524 - const previousExitCode = process.exitCode;
525 + const proc = recordingNodeProcess();
526 yield* handleClientApiError(ui, {
527 fallbackMessage: 'fallback',
528 hint: 'hint',
529 fallbackValue: undefined,
529 - })(error);
530 - process.exitCode = previousExitCode;
530 + })(error).pipe(Effect.provide(proc.layer));
531
532 expect(errors).toEqual(['Bad input']);
533 expect(steps).toEqual(['hint']);
534 + expect(proc.exitCode()).toBe(1);
535 }).pipe(Effect.provide(withRepository))
536 );
537
ts/packages/cli/test/src/services/tool-file-uploads.test.ts
+138 -97
@@ -6,14 +6,20 @@ import * as FileSystem from 'effect/FileSystem';
6 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 { BadRequestError } from '@composio/client/effect';
9 +import { Effect, Fiber, Layer } from 'effect';
10 +import { HttpClient } from 'effect/http';
11 +import { BadRequestError, make } from '@composio/client/effect';
12 import {
13 ComposioBlockedInternalUrlError,
14 ComposioSensitiveFilePathBlockedError,
15 MAX_URL_UPLOAD_SIZE_BYTES,
16 } from '@composio/core';
16 -import { schemaHasFileUploadable, uploadToolInputFiles } from 'src/services/tool-file-uploads';
17 +import { composioSchemaLoaders } from 'src/services/composio-schema-loaders';
18 +import {
19 + schemaHasFileUploadable,
20 + ToolFileUploadError,
21 + uploadToolInputFiles,
22 +} from 'src/services/tool-file-uploads';
23 import { stubComposioClient } from 'test/__utils__/services/stub-composio-client';
24
25 // Schema with a single `file_uploadable` attachment field — mirrors tools like
@@ -55,19 +61,20 @@ describe('uploadToolInputFiles — sensitive-path guard (issue #3746)', () => {
61 const pathApi = yield* Path.Path;
62 const { client, requests } = makeClient();
63
58 - yield* Effect.promise(() =>
59 - expect(
60 - uploadToolInputFiles({
61 - fs: fsApi,
62 - path: pathApi,
63 - toolSlug: 'GMAIL_SEND_EMAIL',
64 - arguments_: { attachment: path.join(os.homedir(), '.ssh', 'id_rsa') },
65 - inputSchema,
66 - client,
67 - })
68 - ).rejects.toBeInstanceOf(ComposioSensitiveFilePathBlockedError)
64 + const failure = yield* Effect.flip(
65 + uploadToolInputFiles({
66 + fs: fsApi,
67 + path: pathApi,
68 + toolSlug: 'GMAIL_SEND_EMAIL',
69 + arguments_: { attachment: path.join(os.homedir(), '.ssh', 'id_rsa') },
70 + inputSchema,
71 + client,
72 + })
73 );
74
75 + expect(failure).toBeInstanceOf(ToolFileUploadError);
76 + expect(failure).toMatchObject({ reason: 'source-read' });
77 + expect(failure.cause).toBeInstanceOf(ComposioSensitiveFilePathBlockedError);
78 // The guard must fire BEFORE any network round-trip: no presigned URL, no upload.
79 expect(requests).toEqual([]);
80 }).pipe(Effect.provide(Layer.mergeAll(BunFileSystem.layer, BunPath.layer)))
@@ -83,31 +90,19 @@ describe('uploadToolInputFiles — sensitive-path guard (issue #3746)', () => {
90
91 // The CLI has no `sensitiveFileUploadProtection` opt-out (by design), so the
92 // error must not point users at that non-existent knob (issue #3763 review #2/#3).
86 - yield* Effect.promise(() =>
87 - expect(
88 - uploadToolInputFiles({
89 - fs: fsApi,
90 - path: pathApi,
91 - toolSlug: 'GMAIL_SEND_EMAIL',
92 - arguments_: { attachment: path.join(os.homedir(), '.ssh', 'id_rsa') },
93 - inputSchema,
94 - client,
95 - })
96 - ).rejects.toThrowError(/has no opt-out/i)
93 + const failure = yield* Effect.flip(
94 + uploadToolInputFiles({
95 + fs: fsApi,
96 + path: pathApi,
97 + toolSlug: 'GMAIL_SEND_EMAIL',
98 + arguments_: { attachment: path.join(os.homedir(), '.ssh', 'id_rsa') },
99 + inputSchema,
100 + client,
101 + })
102 );
103
99 - yield* Effect.promise(() =>
100 - expect(
101 - uploadToolInputFiles({
102 - fs: fsApi,
103 - path: pathApi,
104 - toolSlug: 'GMAIL_SEND_EMAIL',
105 - arguments_: { attachment: path.join(os.homedir(), '.ssh', 'id_rsa') },
106 - inputSchema,
107 - client,
108 - })
109 - ).rejects.not.toThrowError(/sensitiveFileUploadProtection/)
110 - );
104 + expect(failure.message).toMatch(/has no opt-out/i);
105 + expect(failure.message).not.toMatch(/sensitiveFileUploadProtection/);
106 }).pipe(Effect.provide(Layer.mergeAll(BunFileSystem.layer, BunPath.layer)))
107 );
108
@@ -117,18 +112,18 @@ describe('uploadToolInputFiles — sensitive-path guard (issue #3746)', () => {
112 const pathApi = yield* Path.Path;
113 const { client, requests } = makeClient();
114
120 - yield* Effect.promise(() =>
121 - expect(
122 - uploadToolInputFiles({
123 - fs: fsApi,
124 - path: pathApi,
125 - toolSlug: 'GMAIL_SEND_EMAIL',
126 - arguments_: { attachment: path.join(os.tmpdir(), '.env') },
127 - inputSchema,
128 - client,
129 - })
130 - ).rejects.toBeInstanceOf(ComposioSensitiveFilePathBlockedError)
115 + const failure = yield* Effect.flip(
116 + uploadToolInputFiles({
117 + fs: fsApi,
118 + path: pathApi,
119 + toolSlug: 'GMAIL_SEND_EMAIL',
120 + arguments_: { attachment: path.join(os.tmpdir(), '.env') },
121 + inputSchema,
122 + client,
123 + })
124 );
125 +
126 + expect(failure.cause).toBeInstanceOf(ComposioSensitiveFilePathBlockedError);
127 expect(requests).toEqual([]);
128 }).pipe(Effect.provide(Layer.mergeAll(BunFileSystem.layer, BunPath.layer)))
129 );
@@ -145,16 +140,14 @@ describe('uploadToolInputFiles — sensitive-path guard (issue #3746)', () => {
140 return Effect.gen(function* () {
141 const fsApi = yield* FileSystem.FileSystem;
142 const pathApi = yield* Path.Path;
148 - const result = yield* Effect.promise(() =>
149 - uploadToolInputFiles({
150 - fs: fsApi,
151 - path: pathApi,
152 - toolSlug: 'GMAIL_SEND_EMAIL',
153 - arguments_: { attachment: file },
154 - inputSchema,
155 - client,
156 - })
157 - );
143 + const result = yield* uploadToolInputFiles({
144 + fs: fsApi,
145 + path: pathApi,
146 + toolSlug: 'GMAIL_SEND_EMAIL',
147 + arguments_: { attachment: file },
148 + inputSchema,
149 + client,
150 + });
151
152 expect(requests).toEqual([
153 {
@@ -188,7 +181,7 @@ describe('uploadToolInputFiles — presigned-URL request', () => {
181 vi.restoreAllMocks();
182 });
183
191 - it.effect('rejects with the API failure, worded as before, when the request is refused', () => {
184 + it.effect('fails with the API failure, worded as before, when the request is refused', () => {
185 const root = mkdtempSync(path.join(os.tmpdir(), 'composio-upload-'));
186 const file = path.join(root, 'document.pdf');
187 writeFileSync(file, 'hello');
@@ -202,7 +195,7 @@ describe('uploadToolInputFiles — presigned-URL request', () => {
195 const fsApi = yield* FileSystem.FileSystem;
196 const pathApi = yield* Path.Path;
197
205 - const failure = yield* Effect.promise(() =>
198 + const failure = yield* Effect.flip(
199 uploadToolInputFiles({
200 fs: fsApi,
201 path: pathApi,
@@ -210,10 +203,7 @@ describe('uploadToolInputFiles — presigned-URL request', () => {
203 arguments_: { attachment: file },
204 inputSchema,
205 client,
213 - }).then(
214 - () => undefined,
215 - (cause: unknown) => cause
216 - )
206 + })
207 );
208
209 expect(failure).toBeInstanceOf(BadRequestError);
@@ -229,6 +219,60 @@ describe('uploadToolInputFiles — presigned-URL request', () => {
219 Effect.ensuring(Effect.sync(() => rmSync(root, { recursive: true, force: true })))
220 );
221 });
222 +
223 + it.effect('interrupting the caller interrupts the request', () => {
224 + const root = mkdtempSync(path.join(os.tmpdir(), 'composio-upload-'));
225 + const file = path.join(root, 'document.pdf');
226 + writeFileSync(file, 'hello');
227 + // A transport that never answers, reporting when the request reaches it
228 + // and when it is interrupted.
229 + const reached = Promise.withResolvers<void>();
230 + let interrupted = false;
231 + const client = make(
232 + {
233 + apiKey: 'test',
234 + userApiKey: null,
235 + orgApiKey: null,
236 + baseURL: 'https://stub.invalid',
237 + deprecationNotices: 'off',
238 + decode: true,
239 + schemas: composioSchemaLoaders,
240 + },
241 + HttpClient.make(() =>
242 + Effect.sync(() => reached.resolve()).pipe(
243 + Effect.andThen(Effect.never),
244 + Effect.onInterrupt(() =>
245 + Effect.sync(() => {
246 + interrupted = true;
247 + })
248 + )
249 + )
250 + )
251 + );
252 +
253 + return Effect.gen(function* () {
254 + const fsApi = yield* FileSystem.FileSystem;
255 + const pathApi = yield* Path.Path;
256 +
257 + const fiber = yield* Effect.forkChild(
258 + uploadToolInputFiles({
259 + fs: fsApi,
260 + path: pathApi,
261 + toolSlug: 'GMAIL_SEND_EMAIL',
262 + arguments_: { attachment: file },
263 + inputSchema,
264 + client,
265 + })
266 + );
267 + yield* Effect.promise(() => reached.promise);
268 + yield* Fiber.interrupt(fiber);
269 +
270 + expect(interrupted).toBe(true);
271 + }).pipe(
272 + Effect.provide(Layer.mergeAll(BunFileSystem.layer, BunPath.layer)),
273 + Effect.ensuring(Effect.sync(() => rmSync(root, { recursive: true, force: true })))
274 + );
275 + });
276 });
277
278 describe('uploadToolInputFiles — URL SSRF boundary', () => {
@@ -244,19 +288,18 @@ describe('uploadToolInputFiles — URL SSRF boundary', () => {
288 const { client, requests } = makeClient();
289 const sourceUrl = 'http://169.254.169.254/latest/meta-data/credentials';
290
247 - yield* Effect.promise(() =>
248 - expect(
249 - uploadToolInputFiles({
250 - fs: fsApi,
251 - path: pathApi,
252 - toolSlug: 'GMAIL_SEND_EMAIL',
253 - arguments_: { attachment: sourceUrl },
254 - inputSchema,
255 - client,
256 - })
257 - ).rejects.toBeInstanceOf(ComposioBlockedInternalUrlError)
291 + const failure = yield* Effect.flip(
292 + uploadToolInputFiles({
293 + fs: fsApi,
294 + path: pathApi,
295 + toolSlug: 'GMAIL_SEND_EMAIL',
296 + arguments_: { attachment: sourceUrl },
297 + inputSchema,
298 + client,
299 + })
300 );
301
302 + expect(failure.cause).toBeInstanceOf(ComposioBlockedInternalUrlError);
303 expect(requests).toEqual([]);
304 }).pipe(Effect.provide(Layer.mergeAll(BunFileSystem.layer, BunPath.layer)))
305 );
@@ -275,19 +318,18 @@ describe('uploadToolInputFiles — URL SSRF boundary', () => {
318 const fsApi = yield* FileSystem.FileSystem;
319 const pathApi = yield* Path.Path;
320
278 - yield* Effect.promise(() =>
279 - expect(
280 - uploadToolInputFiles({
281 - fs: fsApi,
282 - path: pathApi,
283 - toolSlug: 'GMAIL_SEND_EMAIL',
284 - arguments_: { attachment: file },
285 - inputSchema,
286 - client,
287 - })
288 - ).rejects.toBeInstanceOf(ComposioBlockedInternalUrlError)
321 + const failure = yield* Effect.flip(
322 + uploadToolInputFiles({
323 + fs: fsApi,
324 + path: pathApi,
325 + toolSlug: 'GMAIL_SEND_EMAIL',
326 + arguments_: { attachment: file },
327 + inputSchema,
328 + client,
329 + })
330 );
331
332 + expect(failure.cause).toBeInstanceOf(ComposioBlockedInternalUrlError);
333 expect(requests).toHaveLength(1);
334 expect(fetchSpy).not.toHaveBeenCalled();
335 }).pipe(
@@ -321,19 +363,18 @@ describe('uploadToolInputFiles — URL download size cap', () => {
363 const fsApi = yield* FileSystem.FileSystem;
364 const pathApi = yield* Path.Path;
365
324 - yield* Effect.promise(() =>
325 - expect(
326 - uploadToolInputFiles({
327 - fs: fsApi,
328 - path: pathApi,
329 - toolSlug: 'GMAIL_SEND_EMAIL',
330 - arguments_: { attachment: 'https://1.1.1.1/large.bin' },
331 - inputSchema,
332 - client,
333 - })
334 - ).rejects.toThrow(/exceeds maximum allowed size/)
366 + const failure = yield* Effect.flip(
367 + uploadToolInputFiles({
368 + fs: fsApi,
369 + path: pathApi,
370 + toolSlug: 'GMAIL_SEND_EMAIL',
371 + arguments_: { attachment: 'https://1.1.1.1/large.bin' },
372 + inputSchema,
373 + client,
374 + })
375 );
376
377 + expect(failure.message).toMatch(/exceeds maximum allowed size/);
378 expect(requests).toEqual([]);
379 }).pipe(Effect.provide(Layer.mergeAll(BunFileSystem.layer, BunPath.layer)));
380 });