@devries-cameron20 / composio-1 / commits / 250563013
Fork 0

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

refactor(cli): use Effect's exit-code markers instead of process.exitCode (#5128)

This PR: - targets `next` now that its former base, #5126, has been merged - makes errors that are already on screen declare `[Runtime.errorReported] = false` / `[Runtime.errorExitCode]`, and runs `BunRuntime.runMain` with `Runtime.defaultTeardown`, so nothing in `src/` assigns `process.exitCode` any more (`NodeProcess.setExitCode` and the custom `teardown` are gone) - `reportFailure` prints, then fails with the new `ReportedFailure`; `printFailure` covers commands that print more (an outro, `[]` on stdout, a note) before failing - `ReportedToolExecutionError`, `ReportedProxyCommandError`, `ShellSetupAbortError` and `SetupCommandError` declare the markers; `setup` renders its own failure and outro, and `cli-main.ts` drops their `catchIf` branches, the `'ReportedToolExecutionError'` string filter, and its imports of command files - `composio run` fails with `ChildProcessExited { code }` (exit code = the script's code), recorded as `CLI_RUN_FAILED` with `failure_reason_code: "child_exit"` - stdout and stderr stay the same. Two changes are intended: commands that report their own failure are now recorded as failed in telemetry, and Ctrl-C/SIGTERM now exits 130 for every command (`defaultTeardown`), not only for `composio run`. Both are in `CHANGELOG.md` - tests read exit codes through `Runtime.defaultTeardown` (`test/__utils__/exit-code.ts`), covering child exit-code passthrough, interrupted run → 130, the `ReportedFailure` markers, `child_exit` telemetry, and a reported request failure recorded as `CLI_COMMAND_FAILED` from the real binary - `handleClientApiError` drops its `fallbackValue` option, which it never returned: it now has type `Effect<never, ReportedFailure>`, and its 10 command callers drop their `Option`/boolean fallback branches and read the result straight through. Output is unchanged ## Verification - `pnpm typecheck` - `pnpm --filter @composio/cli run lint:effect`: 0 errors - `pnpm --filter @composio/cli test` (includes `validate:boundaries`, `validate:command-tests`): 209 files, 2429 passed - `./node_modules/.bin/oxlint ts/packages/cli`: no errors - `pnpm validate:agent-skills`, `pnpm validate:skill-routing`, `node .agents/skills/effect-v4/scripts/check-examples.mjs` - Manual runs of `bun src/bin.ts`: `run 'process.exit(3)'` exits 3 with `CLI_RUN_FAILED`; SIGINT during `run` exits 130; `dev toolkits list` against an unreachable backend prints the error and `[]`, exits 1, and records `CLI_COMMAND_FAILED` --------- Co-authored-by: Vinayak Agarwal <vinayak@composio.dev> Co-authored-by: manobhisriram <manobhisriram@gmail.com>

Alberto Schiabel committed Oct 28, 2026 at 13:15 UTC 250563013f1aadbe12f5aa0cebd114a39d099c0d
90 files changed +884 -780
.agents/skills/cli-command/references/design.md
+1 -1
@@ -26,7 +26,7 @@
26 - Runtime config is read from environment variables via `effect/Config`. Every variable the CLI reads is declared, under its full name, in one of the catalogs in `src/config` (`APP_CONFIG` for user-facing `COMPOSIO_*` settings, `DEBUG_CONFIG`, `TELEMETRY_CONFIG`, `HOST_CONFIG`, `GITHUB_CONFIG`); add new variables there, never inline. Tests inject `ConfigProvider.fromEnvRecord({...})`.
27 - Persistent user/auth state lives in `~/.composio/user-config.json`; `ComposioUserContext` merges environment variables over the stored file, so an env var overrides the stored value.
28 - Project-scoped data uses a project-local `.composio/` directory.
29 -- Exit `0` on success and non-zero (`1`) on failure; interrupts are not treated as failures (`src/cli-main.ts` teardown via `BunRuntime.runMain`). There is no distinct "invalid usage" exit code — do not invent one.
29 +- Exit `0` on success, `1` on failure, and `130` on interruption (Ctrl-C, SIGTERM); `composio run` exits with its script's code. Never assign `process.exitCode`: an error declares `[Runtime.errorExitCode]` / `[Runtime.errorReported]` (effect `Runtime`), and `Runtime.defaultTeardown`, run by `BunRuntime.runMain` in `src/cli-main.ts`, picks the code. There is no distinct "invalid usage" exit code — do not invent one.
30
31 ## References
32
.agents/skills/effect-v4/references/cli-surface.md
+16 -13
@@ -95,19 +95,22 @@ Those markers _are_ the contract: "I already printed my own output; don't log me
95 `Runtime.defaultTeardown` reads `errorExitCode` the same way — see
96 `ts/vendor/effect/packages/effect/src/Runtime.ts`'s `getErrorReported`/`getErrorExitCode`.
97
98 -Consequently `ts/packages/cli/src/cli-main.ts` does **not** intercept `ShowHelp` to
99 -derive an exit code by hand anymore. Its sandboxed catch-all handler special-cases
100 -`ShowHelp` (via `CliError.isCliError(squashed) && Predicate.isTagged(squashed,
101 -'ShowHelp')`, never a direct `._tag ===` check) and re-fails with the original `Cause`
102 -via `Effect.failCause(cause)` instead of swallowing it like every other error — that lets
103 -the failure reach `BunRuntime.runMain` untouched, where `errorReported`/`errorExitCode`
104 -take over. The custom `teardown` in the same file reads `Runtime.getErrorExitCode` off
105 -the squashed failure for exactly this case, falling back to `Number(process.exitCode ??
106 -1)` otherwise. If you add rendering anywhere in this path, you will double-print — this
107 -is the single most important rule when touching the runner. The separate catch-all
108 -defect handler further down (genuine command-handler failures captured via
109 -`effect-errors`) is a different path that `Command.runWith` never renders, so appending
110 -help text there is not a double-print.
98 +The CLI's own errors use the same contract. A failure a command already printed
99 +(`ReportedFailure` from `src/effects/report-failure.ts`, `ReportedToolExecutionError`,
100 +`ShellSetupAbortError`, `SetupCommandError`, …) or that carries a custom code
101 +(`ChildProcessExited` from `composio run`) declares the markers as getters, and
102 +`ts/packages/cli/src/cli-main.ts` runs with `Runtime.defaultTeardown`, which exits 0 on
103 +success, 130 on interruption alone, and otherwise with the squashed failure's
104 +`errorExitCode` (1 when unset). Nothing in `src/` assigns `process.exitCode`.
105 +
106 +`cli-main.ts`'s sandboxed catch-all handler drops every failure whose `errorReported` is
107 +false (`ShowHelp` included) from the cause; when nothing is left it re-fails with the
108 +original `Cause` via `Effect.failCause(cause)`, so the failure reaches
109 +`BunRuntime.runMain` untouched and the markers take over. If you add rendering anywhere in
110 +this path, you will double-print — this is the single most important rule when touching
111 +the runner. Whatever is left is a genuine defect, captured via `effect-errors`, printed,
112 +and re-failed as a `ReportedFailure`; `Command.runWith` never renders that path, so
113 +appending help text there is not a double-print.
114
115 ## argv preprocessing and the executable-prefix contract
116
ts/packages/cli/AGENTS.md
+3 -3
@@ -25,7 +25,7 @@ The CLI is built on the **Effect.ts ecosystem** and runs on **Bun**. Service-ori
25 - `UpgradeBinaryLive` — Self-update from GitHub releases
26 - `BunFileSystem.layer`, `BunPath.layer`, `BunServices.layer`, `FetchHttpClient.layer` — Bun runtime integration (`@effect/platform-bun`'s `BunContext` no longer exists in v4; `BunServices.layer` is the aggregate replacement)
27
28 -Explicit help and version actions complete successfully. `Command.runWith` renders parse/validation errors and contextual help itself before re-failing with `CliError.ShowHelp`, which carries `[Runtime.errorReported] = false` (suppresses `runMain`'s automatic error log) and `[Runtime.errorExitCode]` (1 alongside parse errors). `cli-main.ts`'s sandboxed catch-all re-fails `ShowHelp` with its original `Cause` via `Effect.failCause` instead of swallowing it, and its custom `teardown` reads `Runtime.getErrorExitCode` off the squashed failure. This preserves failing exit codes without duplicate error output. See the module docstring at the top of `cli-main.ts` for the argv-prefix contract with `src/commands/index.ts`.
28 +Explicit help and version actions complete successfully. `Command.runWith` renders parse/validation errors and contextual help itself before re-failing with `CliError.ShowHelp`, which carries `[Runtime.errorReported] = false` (suppresses `runMain`'s automatic error log) and `[Runtime.errorExitCode]` (1 alongside parse errors). `cli-main.ts`'s sandboxed catch-all re-fails every failure already on screen (`[Runtime.errorReported] = false`, `ShowHelp` included) with its original `Cause` via `Effect.failCause` instead of printing it, and `BunRuntime.runMain` runs with `Runtime.defaultTeardown`: exit 0 on success, 130 on interruption (Ctrl-C, SIGTERM), otherwise the squashed failure's `[Runtime.errorExitCode]`, or 1 without one. This preserves failing exit codes without duplicate error output. Never assign `process.exitCode`; an error that needs a code other than 1 declares it (`ChildProcessExited` in `src/effects/child-process-exited.ts`, which `composio run` fails with when its script exits non-zero). See the module docstring at the top of `cli-main.ts` for the argv-prefix contract with `src/commands/index.ts`.
29
30 Errors are captured via the custom `effect-errors/` module (source-mapped stack traces, Effect span timelines, formatted output).
31
@@ -121,7 +121,7 @@ test/src/commands/<group>/<shared-module>.test.ts group helper
121 | `UpgradeBinary` | Fetches latest release from GitHub, downloads and replaces binary |
122 | `DashboardToolExecution` | Sends consumer `composio execute` calls to the Composio Dashboard and decodes its reply |
123
124 -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 the CLI's `identity` (`cliClientIdentity()` in `client-provenance.ts`, from which the client sends the provenance headers and which makes it refuse them in `defaultHeaders` and per-call `headers`), `auth` (`Auth.user` with the user key, `Auth.project` when a caller passes `projectApiKey`, `Auth.none()` before login), `scope` (the org and project, when both are known), `x-cli-session-id` as the one default header (read once per process), 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. The client's deprecation notices, which CLI users cannot act on, are dropped by the root logger (`withoutClientNotices`, `src/effects/without-client-notices.ts`, through the client's `isDeprecationNotice`). `composio-clients.ts` holds client construction, the two repositories, and the `collectAll` and `sortBySlug` helpers the catalog fetches share. The repository's auth-config, connected-account, trigger-instance, search, and single-item methods live in `src/services/composio-resource-operations.ts`; the account helpers (`listOrganizations`, `getSessionInfo*`, `resolveConsumerProject`, `createProjectApiKey`, `getLatestToolVersion`, …) in `src/services/composio-account.ts`; toolkit version validation and its errors (`InvalidToolkitsError`, `InvalidToolkitVersionsError`) in `src/services/toolkit-version-validation.ts`; the shared error types (`ClientError`, `HttpDecodingError`, `ComposioClientConfigurationError`) in `src/services/composio-errors.ts`; and the shared `decode` helper and `validated` request option in `src/services/composio-request.ts`. There is no CLI error wrapper around a request: the client's tagged errors (`@composio/client/NotFoundError`, `APIConnectionError`, `DecodeError`, …) flow to callers, which recover with `Effect.catchTag` or the client's `isAPIError` guard. Commands that report an API failure and continue with a fallback share one handler, `handleClientApiError` (`src/effects/handle-http-error.ts`), applied with `Effect.catchTag(CLIENT_API_ERROR_TAGS, …)`; the tag list lives in `src/services/composio-errors.ts`. Endpoints the client does not type use the raw `client.get`/`client.post`; `src/services/tool-permissions.ts` reaches them through its own `requestJson`, which raises `services/ToolPermissionsRequestError` because its callers fail closed on that tag. Do not add a raw `fetch` to the Composio backend from `src/commands`, `src/effects`, or `src/services` — the one sanctioned exception is the bundled companion runtime (`run-helpers-runtime.ts`), which runs in the user's spawned process outside the Effect runtime. (`src/services/agents.ts` also calls `fetch`, against the agents service at agents.composio.dev rather than the Composio backend.) The Composio Dashboard (`ComposioUserContext.data.webURL`) is the one first-party host the CLI calls without `@composio/client`: `src/services/dashboard-tool-execution.ts` sends consumer `composio execute` calls (tool and meta-tool executions) to it over `HttpClient` from `effect/http`, once, with no retry, no redirect following and one 15-minute deadline, only to an `https:` base URL (or loopback `http:`) that carries no credentials, query or fragment, and fails a relayed backend failure with the client's own status error (`@composio/client/PermissionDeniedError`, …) so the classification below still applies. While telemetry is enabled, those requests (and only those) also carry the stored analytics install ID as `x-cli-install-id`, read through `readInstallIdWhenTelemetryEnabled` in `src/analytics/dispatch.ts`, which never creates an ID and never fails; do not add the header to backend requests or to `cliRequestHeaders()`. Everything else on the execute path (connection lookups, the permission gate, file uploads) and `dev playground-execute` stay on the backend client. Do not route other commands through the Dashboard, and do not add a second raw-HTTP host, without updating this paragraph. oxlint rejects value imports of the `@composio/client` root and `@composio/client/pagination` from CLI `src/`; type-only imports are allowed. The CLI's clients send every request once. A call that is safe to repeat — a read, or a call whose repeat changes nothing on the server — passes the `idempotent` request option (`src/services/composio-request.ts`) and is retried by the client after a connection failure, a timeout, or a 408, 409, 429 or 5xx response; combine it with `validated` as `{ ...idempotent, ...validated }`. Creates, updates, deletes, links, sessions, tool executions and proxied calls never pass it, because a request that failed in flight may already have acted. It also rejects importing `make` or the client layers from `@composio/client/effect` anywhere but `composio-clients.ts`, and `getFor` takes an org and a project together or neither, because the two headers are only sent as a pair. Every `getFor` builds a new client, so never key a memo on a client instance: `clientScopeKey(client)` gives its auth mode, a SHA-256 fingerprint of its credential (never the key), org, and project (`listActiveConnectedAccounts` keys on it and the user id). While a client has `auth` and `scope`, a per-call `x-api-key`, `x-user-api-key`, `x-org-api-key`, `x-org-id` or `x-project-id` header fails the call before it is sent; an org or project known alone goes on an unscoped client's request, as `orgScopedOptions` and `getLatestToolVersion` do. Client errors are classified for display by `src/utils/api-error-extraction.ts`.
124 +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 the CLI's `identity` (`cliClientIdentity()` in `client-provenance.ts`, from which the client sends the provenance headers and which makes it refuse them in `defaultHeaders` and per-call `headers`), `auth` (`Auth.user` with the user key, `Auth.project` when a caller passes `projectApiKey`, `Auth.none()` before login), `scope` (the org and project, when both are known), `x-cli-session-id` as the one default header (read once per process), 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. The client's deprecation notices, which CLI users cannot act on, are dropped by the root logger (`withoutClientNotices`, `src/effects/without-client-notices.ts`, through the client's `isDeprecationNotice`). `composio-clients.ts` holds client construction, the two repositories, and the `collectAll` and `sortBySlug` helpers the catalog fetches share. The repository's auth-config, connected-account, trigger-instance, search, and single-item methods live in `src/services/composio-resource-operations.ts`; the account helpers (`listOrganizations`, `getSessionInfo*`, `resolveConsumerProject`, `createProjectApiKey`, `getLatestToolVersion`, …) in `src/services/composio-account.ts`; toolkit version validation and its errors (`InvalidToolkitsError`, `InvalidToolkitVersionsError`) in `src/services/toolkit-version-validation.ts`; the shared error types (`ClientError`, `HttpDecodingError`, `ComposioClientConfigurationError`) in `src/services/composio-errors.ts`; and the shared `decode` helper and `validated` request option in `src/services/composio-request.ts`. There is no CLI error wrapper around a request: the client's tagged errors (`@composio/client/NotFoundError`, `APIConnectionError`, `DecodeError`, …) flow to callers, which recover with `Effect.catchTag` or the client's `isAPIError` guard. Commands that report an API failure with a hint and exit 1 share one handler, `handleClientApiError` (`src/effects/handle-http-error.ts`), applied with `Effect.catchTag(CLIENT_API_ERROR_TAGS, …)`; it never succeeds, so the command reads the request's result straight through; the tag list lives in `src/services/composio-errors.ts`. Endpoints the client does not type use the raw `client.get`/`client.post`; `src/services/tool-permissions.ts` reaches them through its own `requestJson`, which raises `services/ToolPermissionsRequestError` because its callers fail closed on that tag. Do not add a raw `fetch` to the Composio backend from `src/commands`, `src/effects`, or `src/services` — the one sanctioned exception is the bundled companion runtime (`run-helpers-runtime.ts`), which runs in the user's spawned process outside the Effect runtime. (`src/services/agents.ts` also calls `fetch`, against the agents service at agents.composio.dev rather than the Composio backend.) The Composio Dashboard (`ComposioUserContext.data.webURL`) is the one first-party host the CLI calls without `@composio/client`: `src/services/dashboard-tool-execution.ts` sends consumer `composio execute` calls (tool and meta-tool executions) to it over `HttpClient` from `effect/http`, once, with no retry, no redirect following and one 15-minute deadline, only to an `https:` base URL (or loopback `http:`) that carries no credentials, query or fragment, and fails a relayed backend failure with the client's own status error (`@composio/client/PermissionDeniedError`, …) so the classification below still applies. While telemetry is enabled, those requests (and only those) also carry the stored analytics install ID as `x-cli-install-id`, read through `readInstallIdWhenTelemetryEnabled` in `src/analytics/dispatch.ts`, which never creates an ID and never fails; do not add the header to backend requests or to `cliRequestHeaders()`. Everything else on the execute path (connection lookups, the permission gate, file uploads) and `dev playground-execute` stay on the backend client. Do not route other commands through the Dashboard, and do not add a second raw-HTTP host, without updating this paragraph. oxlint rejects value imports of the `@composio/client` root and `@composio/client/pagination` from CLI `src/`; type-only imports are allowed. The CLI's clients send every request once. A call that is safe to repeat — a read, or a call whose repeat changes nothing on the server — passes the `idempotent` request option (`src/services/composio-request.ts`) and is retried by the client after a connection failure, a timeout, or a 408, 409, 429 or 5xx response; combine it with `validated` as `{ ...idempotent, ...validated }`. Creates, updates, deletes, links, sessions, tool executions and proxied calls never pass it, because a request that failed in flight may already have acted. It also rejects importing `make` or the client layers from `@composio/client/effect` anywhere but `composio-clients.ts`, and `getFor` takes an org and a project together or neither, because the two headers are only sent as a pair. Every `getFor` builds a new client, so never key a memo on a client instance: `clientScopeKey(client)` gives its auth mode, a SHA-256 fingerprint of its credential (never the key), org, and project (`listActiveConnectedAccounts` keys on it and the user id). While a client has `auth` and `scope`, a per-call `x-api-key`, `x-user-api-key`, `x-org-api-key`, `x-org-id` or `x-project-id` header fails the call before it is sent; an org or project known alone goes on an unscoped client's request, as `orgScopedOptions` and `getLatestToolVersion` do. Client errors are classified for display by `src/utils/api-error-extraction.ts`.
125
126 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.
127
@@ -222,7 +222,7 @@ Each nested `Arr.flatMap` adds one independent axis; the innermost `Arr.map` bui
222 - Never branch on an Effect value's internal tag field directly. Use the owning module's public refinement or matcher (`Option`, `Result`, `Exit`, `Cause`, `CliError`), `Match.valueTags` for exhaustive unions, or `Predicate.isTagged` for a single narrowing guard.
223 - Do not wrap a plain `Error` in `Effect.fail` for expected failures. Give the failure a meaningful `Data.TaggedError` type with structured fields and a preserved cause, then recover with `catchTag` / `catchTags`. Reserve `Effect.die` and `Effect.dieMessage` for impossible invariants.
224 - Treat `unknown`, JSON, and persisted state as trust boundaries. Decode them with `effect/Schema` or narrow them with `Predicate`; an `as` assertion is not validation, and hand-rolled structural guards (`'x' in obj` / `typeof` chains) are not a substitute for a schema. Each typed API response is validated at most once. The CLI's own schema validates a response the CLI transforms, filters for stdout, or writes to a cache file: the catalog models (`src/models/toolkits.ts`, `tools.ts`, `trigger-types.ts`), the auth-config and connected-account allowlists that keep credential-bearing fields off stdout (including the list responses and the `auth-configs create` response in `src/models/auth-configs.ts` and `connected-accounts.ts`), the `ToolkitSlug` path-safety check, the `Session` `DateTime` transform, and `TriggerInstanceItems`. Those calls decode with the CLI schema, failing with `services/HttpDecodingError`. The client validates a response against its own generated schema only when the call passes the `validated` request option (`src/services/composio-request.ts`); a mismatch fails with the client's `DecodeError`, which the CLI reports with the operation, the request id, and an upgrade hint. Pass `validated` only on a read the CLI consumes whole through the client's types, where no field may drift: `cli.realtime.credentials` (every field feeds the realtime connection), `org.list` (organization ids and names for login), and `org.consumer.listConnectedToolkits` (a list of slugs). Every other typed call leaves it off: calls that are not reads, because failing after the server acted would invite a retry that repeats the side effect; reads the CLI validates with its own schema; and reads that must tolerate drift because the CLI consumes a few fields of a response whose client schema fixes enums or requires fields the CLI never reads (`logs.tools.*`, `logs.triggers.*`, `tools.list`, `tools.retrieve`, `org.project.list`, `toolRouter.session.search`, `toolRouter.session.toolkits`, `connectedAccounts.list`, which tolerates unknown statuses, and `triggerInstances.listActive`, whose page counts the CLI defaults). Adding a validated read means saying in its doc comment why the CLI cannot tolerate drift there. Responses fetched with the raw `client.get`/`client.post` are untyped and always need a CLI schema (`LatestToolVersionResponse` in `src/models/tools.ts`, and the consumer config and permission payloads in `tool-permissions.ts`). `effect/Schema` is the CLI's schema tool — do not introduce zod here (zod is the convention in the SDK packages and docs).
225 -- Do not inspect private `effect/cli` internals (parser state, `HelpDoc` string shapes, `CliError` suggestion machinery). `Command.runWith` renders help and parse/validation errors itself — see the entry-point section above — so command-tree introspection must stay on the public `Command.Any` surface (`name`, `alias`, `subcommands`). `CliError.InvalidValue` takes structured `{ option, value, expected, kind }` fields, not a free-form message — handler-level validation raises `CommandInputError` from `src/commands/errors.ts` (built with `commandInputError('<command>')`, carrying `command`, `message`, and the `option` at fault), not a hand-built `CliError`. It, `NotLoggedInError`, `ProjectResolutionError`, `ConnectedAccountResolutionError` (an `--account` selector that matches no connected account, or the account lookup behind it failing), and the other expected failures (a missing user id, login, or SDK install; an unknown org, toolkit, or version) declare `get [ExpectedFailure]() { return true; }` from `src/effects/expected-failure.ts` where the class is defined; `isUsageFailure` in `errors.ts` checks that marker, and `cli-main.ts` prints the message and exits 1, with no defect banner. A new expected error opts in the same way, with no central list to update; a defect stays unmarked. A failure the command already printed (on stderr and as `{ "successful": false }` on stdout) fails with a `Reported*` error instead, which `cli-main.ts` turns into exit 1 without printing more.
225 +- Do not inspect private `effect/cli` internals (parser state, `HelpDoc` string shapes, `CliError` suggestion machinery). `Command.runWith` renders help and parse/validation errors itself — see the entry-point section above — so command-tree introspection must stay on the public `Command.Any` surface (`name`, `alias`, `subcommands`). `CliError.InvalidValue` takes structured `{ option, value, expected, kind }` fields, not a free-form message — handler-level validation raises `CommandInputError` from `src/commands/errors.ts` (built with `commandInputError('<command>')`, carrying `command`, `message`, and the `option` at fault), not a hand-built `CliError`. It, `NotLoggedInError`, `ProjectResolutionError`, `ConnectedAccountResolutionError` (an `--account` selector that matches no connected account, or the account lookup behind it failing), and the other expected failures (a missing user id, login, or SDK install; an unknown org, toolkit, or version) declare `get [ExpectedFailure]() { return true; }` from `src/effects/expected-failure.ts` where the class is defined; `isUsageFailure` in `errors.ts` checks that marker, and `cli-main.ts` prints the message and exits 1, with no defect banner. A new expected error opts in the same way, with no central list to update; a defect stays unmarked. A failure the command prints itself fails already reported: `reportFailure` (`src/effects/report-failure.ts`) prints a message and hint, then fails with `ReportedFailure`; a command that prints more after the message calls `printFailure`, prints the rest, then fails with `ReportedFailure`. A command-specific error the command already printed (`ReportedToolExecutionError` and `ReportedProxyCommandError`, whose result is on stdout as `{ "successful": false }`, `ShellSetupAbortError`, `SetupCommandError`) declares `get [Runtime.errorReported]() { return false; }` and `get [Runtime.errorExitCode]() { return 1; }` where the class is defined. Either way the runtime prints nothing more and exits 1, and telemetry records the command as failed.
226 - Prefer `Effect.mapError`, `Effect.matchEffect`, and typed recovery over `Effect.catch` blocks (the v4 name for what was `Effect.catchAll`) that flatten distinct failures into one message-only error.
227
228 ### Effect Boundary Policy
ts/packages/cli/CHANGELOG.md
+9
@@ -68,6 +68,15 @@
68 `""`. `composio run` starts the script without the consumer user's context,
69 as it does when there is no consumer user.
70
71 +- Stopping any command with Ctrl-C (SIGINT) or SIGTERM now exits 130, as
72 + `composio run` already did. Other commands, `composio listen` among them,
73 + used to exit 0, so a wrapper or `set -e` script read a cancelled command as a
74 + successful one. CLI telemetry now records a command that prints its own
75 + failure and exits 1 (a failed API request, an alias conflict on
76 + `composio link`, a `--fail-fast` listener stop) as failed instead of
77 + succeeded, and a `composio run` whose script exits non-zero as
78 + `CLI_RUN_FAILED` with `failure_reason_code: "child_exit"`.
79 +
80 - `composio execute` now exits 1 when an argument names a file on your machine
81 but the tool does not accept file uploads for that input, such as `file` in
82 `TRELLO_ADD_CARDS_ATTACHMENTS_BY_ID_CARD`. It used to send the path text to
ts/packages/cli/src/analytics/events.ts
+2
@@ -4,6 +4,7 @@ import { APP_VERSION } from 'src/constants';
4 import { inferSkillReleaseChannel } from 'src/effects/install-skill';
5 import type { AgentHost } from 'src/services/agent-host';
6 import type { CliInvocationContext } from 'src/services/runtime-cli-context';
7 +import { ChildProcessExited } from 'src/effects/child-process-exited';
8 import { SetupCommandError } from 'src/services/setup-command-error';
9 import { ToolInputValidationError } from 'src/services/tool-input-validation';
10 import { guessToolkitFromToolSlug } from 'src/utils/toolkit-from-tool-slug';
@@ -262,6 +263,7 @@ const errorNameOf = (error: unknown): string =>
263
264 const failureReasonProperties = (error: unknown) => {
265 if (error instanceof SetupCommandError) return { failure_reason_code: error.reasonCode };
266 + if (error instanceof ChildProcessExited) return { failure_reason_code: 'child_exit' };
267 return {};
268 };
269
ts/packages/cli/src/cli-main.ts
+57 -125
@@ -1,20 +1,14 @@
1 /**
2 * Composes the CLI layers and runs Effect's command parser. Command.runWith renders
3 - * help and parse errors once; preserve ShowHelp so its runtime markers control logging
4 - * and the exit code. runWithConfig accepts full argv and removes the executable prefix.
3 + * help and parse errors once. runWithConfig accepts full argv and removes the executable prefix.
4 + *
5 + * Exit codes come from Effect's runtime markers, never `process.exitCode`: a failure that is
6 + * already on screen (ShowHelp, a command's own report, or a message printed here) carries
7 + * `[Runtime.errorReported] = false`, so `BunRuntime.runMain` logs nothing, and
8 + * `Runtime.defaultTeardown` exits with its `[Runtime.errorExitCode]` (1 when unset), 0 on
9 + * success, and 130 on interruption.
10 */
6 -import process from 'node:process';
7 -import {
8 - Cause,
9 - ConfigProvider,
10 - Effect,
11 - Exit,
12 - Layer,
13 - Logger,
14 - Option,
15 - Predicate,
16 - Runtime,
17 -} from 'effect';
11 +import { Cause, ConfigProvider, Effect, Layer, Logger, Option, Runtime } from 'effect';
12 import { captureErrors, prettyPrintFromCapturedErrors } from 'effect-errors/index';
13 import { CliConfig, CliError } from 'effect/cli';
14 import { FetchHttpClient } from 'effect/http';
@@ -70,11 +64,8 @@ import { toolkitFromToolSlug } from 'src/effects/toolkit-from-tool-slug';
64 import { mapOnlyComposioOverrideError } from 'src/services/composio-error-overrides';
65 import { SetupSkillInstaller } from 'src/services/setup-skill-installer';
66 import { PendingLoginSession } from 'src/services/pending-login-session';
73 -import { SetupCommandError } from 'src/services/setup-command-error';
74 -import { ShellSetupAbortError } from 'src/commands/install/install.errors';
75 -import { ReportedProxyCommandError } from 'src/commands/proxy.cmd';
76 -import { ReportedToolExecutionError } from 'src/commands/tools/commands/tools.execute.cmd';
77 -import { isUsageFailure, type UsageFailure } from 'src/commands/errors';
67 +import { isExpectedFailure, type ExpectedFailure } from 'src/effects/expected-failure';
68 +import { ReportedFailure } from 'src/effects/report-failure';
69 import { cliInvocationContext } from 'src/services/runtime-cli-context';
70 import { readTelemetryDebugOverride, telemetryDebugModeLayer } from 'src/services/runtime-flags';
71 import { normalizeRunScriptArgs } from 'src/commands/argv-compat';
@@ -188,28 +179,45 @@ const layers = Layer.mergeAll(
179 )
180 ) satisfies RequiredLayer;
181
191 -export const teardown: Runtime.Teardown = <E, A>(
192 - exit: Exit.Exit<E, A>,
193 - onExit: (code: number) => void
194 -) => {
195 - if (Exit.isFailure(exit) && !Cause.hasInterruptsOnly(exit.cause)) {
196 - const squashed = Cause.squash(exit.cause);
197 - // `ShowHelp` carries its own `[Runtime.errorExitCode]` (0 for bare
198 - // help/version, 1 alongside parse/validation errors, see the module docs
199 - // above); prefer that over the generic fallback whenever it applies.
200 - const exitCode =
201 - CliError.isCliError(squashed) && Predicate.isTagged(squashed, 'ShowHelp')
202 - ? Runtime.getErrorExitCode(squashed)
203 - : Number(process.exitCode ?? 1);
204 - onExit(exitCode);
205 - return;
182 +/**
183 + * Whether `reason` has nothing for the catch-all to print: a failure already on screen, or an
184 + * interruption, which must reach `Runtime.defaultTeardown` untouched to exit 130.
185 + */
186 +const hasNothingToPrint = (reason: Cause.Reason<unknown>): boolean =>
187 + Cause.isInterruptReason(reason) ||
188 + (Cause.isFailReason(reason) && !Runtime.getErrorReported(reason.error));
189 +
190 +/**
191 + * Prints the parts of `cause` nobody reported yet and fails with `ReportedFailure`. A cause with
192 + * nothing to print (a failure already on screen — `ShowHelp`, which `Command.runWith` printed
193 + * with any parse/validation errors, a command's own report, or a message printed in
194 + * `cliProgram` — or an interruption) is re-failed untouched: its `[Runtime.errorReported]` is
195 + * false, so `BunRuntime.runMain` logs nothing, and `Runtime.defaultTeardown` exits with its
196 + * `[Runtime.errorExitCode]`, or 130 for interruptions alone. Nothing here may print it, or
197 + * output doubles.
198 + */
199 +export const reportUnreportedCause = Effect.fn(function* (cause: Cause.Cause<unknown>) {
200 + const unreported = Cause.fromReasons(cause.reasons.filter(reason => !hasNothingToPrint(reason)));
201 + if (unreported.reasons.length > 0) {
202 + const captured = yield* captureErrors(unreported, { stripCwd: true });
203 + const message =
204 + captured.errors.length > 0
205 + ? prettyPrintFromCapturedErrors(captured, {
206 + hideStackTrace: true,
207 + stripCwd: true,
208 + enabled: true,
209 + }).trim()
210 + : '';
211 + if (message.length > 0) {
212 + const ui = yield* TerminalUI;
213 + yield* ui.error(message);
214 + return yield* new ReportedFailure({ message });
215 + }
216 }
207 - // A command that proxies another process (`composio run`) reports its status by assigning
208 - // `process.exitCode`, so honor that on every path. It matters most on interrupt: the runtime
209 - // force-exits with whatever code teardown yields once a signal has been received, which would
210 - // otherwise turn a cancelled run into a success.
211 - onExit(Number(process.exitCode ?? 0));
212 -};
217 + // Nothing printable: keep the original cause so its exit code survives and `runMain` logs
218 + // whatever is still unreported, instead of exiting 0.
219 + return yield* Effect.failCause(cause);
220 +});
221
222 // `runWithConfig`'s root command tree (built from every `.cmd.ts` subcommand in
223 // `src/commands`) is deep and wide enough that TypeScript's inference collapses its
@@ -301,34 +309,16 @@ const cliProgram = (argv: ReadonlyArray<string>) =>
309 Effect.andThen(showUpdateNotice(argv)),
310 Effect.andThen(showPluginAcquisitionHint(argv)),
311 Effect.andThen(runWithTelemetry(argv)),
304 - Effect.catchIf(
305 - (error): error is SetupCommandError => error instanceof SetupCommandError,
306 - error =>
307 - Effect.gen(function* () {
308 - const ui = yield* TerminalUI;
309 - const summary =
310 - error.operation === 'uninstall'
311 - ? 'Composio plugin uninstall was unsuccessful.'
312 - : 'Composio setup was unsuccessful.';
313 - if ((yield* ui.capabilities).canDecorate) {
314 - yield* ui.log.error(error.message);
315 - yield* ui.outro(summary);
316 - } else {
317 - yield* ui.error(`${summary} ${error.message}`);
318 - }
319 - process.exitCode = 1;
320 - })
321 - ),
312 // A usage mistake, a missing setup or login, or a failure a remote service reported clearly
323 - // (see `UsageFailure`) is not a broken invariant: print the message and exit non-zero
324 - // instead of routing it through the defect reporter below.
313 + // (see `ExpectedFailure`) is not a broken invariant: print the message and exit 1 instead of
314 + // routing it through the defect reporter below.
315 Effect.catchIf(
326 - (error): error is UsageFailure => isUsageFailure(error),
316 + (error): error is ExpectedFailure => isExpectedFailure(error),
317 error =>
318 Effect.gen(function* () {
319 const ui = yield* TerminalUI;
320 yield* ui.error(error.message);
331 - process.exitCode = 1;
321 + return yield* new ReportedFailure({ message: error.message });
322 })
323 ),
324 // A rejected user API key gets the backend's message and the way to log in again, from
@@ -336,32 +326,12 @@ const cliProgram = (argv: ReadonlyArray<string>) =>
326 Effect.catchIf(isRejectedUserApiKey, error =>
327 Effect.gen(function* () {
328 const ui = yield* TerminalUI;
339 - yield* ui.error(extractMessage(error) ?? 'The user API key was rejected.');
329 + const message = extractMessage(error) ?? 'The user API key was rejected.';
330 + yield* ui.error(message);
331 yield* ui.error(yield* rejectedUserApiKeyHint);
341 - process.exitCode = 1;
332 + return yield* new ReportedFailure({ message });
333 })
334 ),
344 - // `composio execute` and `composio proxy` already printed the failure, and the failed result
345 - // as JSON on stdout; the typed failure only exists so scripts and agents see a non-zero exit
346 - // code.
347 - Effect.catchIf(
348 - (error): error is ReportedToolExecutionError | ReportedProxyCommandError =>
349 - error instanceof ReportedToolExecutionError || error instanceof ReportedProxyCommandError,
350 - () =>
351 - Effect.sync(() => {
352 - process.exitCode = 1;
353 - })
354 - ),
355 - Effect.catchIf(
356 - (error): error is ShellSetupAbortError => error instanceof ShellSetupAbortError,
357 - // `composio install` already printed the abort reason; the typed failure
358 - // only exists so the process exits non-zero and install.sh runs its
359 - // guarded inline PATH fallback instead of reporting a green install.
360 - () =>
361 - Effect.sync(() => {
362 - process.exitCode = 1;
363 - })
364 - ),
335 Effect.withSpan('composio-cli', {
336 attributes: {
337 name: constants.APP_NAME,
@@ -369,45 +339,7 @@ const cliProgram = (argv: ReadonlyArray<string>) =>
339 },
340 }),
341 Effect.sandbox,
372 - Effect.catch(
373 - Effect.fn(function* (cause) {
374 - const squashed = Cause.squash(cause);
375 - if (CliError.isCliError(squashed) && Predicate.isTagged(squashed, 'ShowHelp')) {
376 - // `Command.runWith` already printed help and any parse/validation
377 - // errors to the correct stream (see the module docs above) before
378 - // re-failing with `ShowHelp`. Re-failing with the original `cause`
379 - // here — instead of swallowing it like every other error below —
380 - // lets it reach `BunRuntime.runMain` untouched: `ShowHelp`'s
381 - // `[Runtime.errorReported] = false` suppresses `runMain`'s automatic
382 - // error log, and `teardown` reads its `[Runtime.errorExitCode]` to
383 - // pick the process exit code. Nothing here may print, or output
384 - // doubles.
385 - return yield* Effect.failCause(cause);
386 - }
387 -
388 - const captured = yield* captureErrors(cause, {
389 - stripCwd: true,
390 - });
391 - const filteredErrors = captured.errors.filter(
392 - error => error.errorType !== 'ReportedToolExecutionError'
393 - );
394 - if (captured.interrupted || filteredErrors.length > 0) {
395 - const message = prettyPrintFromCapturedErrors(
396 - { ...captured, errors: filteredErrors },
397 - {
398 - hideStackTrace: true,
399 - stripCwd: true,
400 - enabled: true,
401 - }
402 - ).trim();
403 - if (message.length > 0) {
404 - const ui = yield* TerminalUI;
405 - yield* ui.error(message);
406 - process.exitCode = 1;
407 - }
408 - }
409 - })
410 - ),
342 + Effect.catch(reportUnreportedCause),
343 Effect.provide(layers),
344 // Built per invocation, never at module scope: `ConfigProvider.fromEnv()` snapshots
345 // `process.env` when constructed, and the ambient `ConfigProvider` reference caches its
@@ -422,6 +354,6 @@ export const runCli = (options: CliBootstrapOptions): void => {
354 cliProgram(options.argv).pipe(
355 effect =>
356 debug === undefined ? effect : Effect.provide(effect, telemetryDebugModeLayer(debug)),
425 - BunRuntime.runMain({ teardown })
357 + BunRuntime.runMain({ teardown: Runtime.defaultTeardown })
358 );
359 };
ts/packages/cli/src/commands/auth-configs/create/auth-configs.create.handler.ts
+1 -9
@@ -111,26 +111,18 @@ export const runAuthConfigsCreate = ({
111 customCredentials: parsedCustomCredentials.success,
112 });
113
114 - const resultOpt = yield* ui
114 + const result = yield* ui
115 .withSpinner('Creating auth config...', repo.createAuthConfig(request))
116 .pipe(
117 - Effect.asSome,
117 Effect.catchTag(
118 CLIENT_API_ERROR_TAGS,
119 handleClientApiError(ui, {
120 fallbackMessage: 'Failed to create auth config.',
121 hint: `Check available auth schemes for "${toolkit}":\n> composio dev toolkits info "${toolkit}"`,
123 - fallbackValue: Option.none(),
122 })
123 )
124 );
125
128 - if (Option.isNone(resultOpt)) {
129 - return;
130 - }
131 -
132 - const result = resultOpt.value;
133 -
126 yield* ui.log.success('Auth config created.');
127 yield* ui.note(formatAuthConfigCreated(result), 'New Auth Config');
128
ts/packages/cli/src/commands/auth-configs/info/auth-configs.info.handler.ts
+1 -9
@@ -31,26 +31,18 @@ export const runAuthConfigsInfo = ({ id }: AuthConfigsInfoParams) =>
31 const idValue = id.value;
32
33 // Auth config IDs are opaque nanoids — "Did you mean?" suggestions would not be useful
34 - const itemOpt = yield* ui
34 + const item = yield* ui
35 .withSpinner(`Fetching auth config "${idValue}"...`, repo.getAuthConfig(idValue))
36 .pipe(
37 - Effect.asSome,
37 Effect.catchTag(
38 CLIENT_API_ERROR_TAGS,
39 handleClientApiError(ui, {
40 fallbackMessage: `Failed to fetch auth config "${idValue}".`,
41 hint: 'Browse available auth configs:\n> composio dev auth-configs list',
43 - fallbackValue: Option.none(),
42 })
43 )
44 );
45
48 - if (Option.isNone(itemOpt)) {
49 - return;
50 - }
51 -
52 - const item = itemOpt.value;
53 -
46 yield* ui.note(formatAuthConfigInfo(item), `Auth Config: ${item.name}`);
47
48 yield* ui.output(JSON.stringify(item, null, 2));
ts/packages/cli/src/commands/connected-accounts/info/connected-accounts.info.handler.ts
+3 -11
@@ -28,28 +28,20 @@ const showConnectedAccount = (id: string) =>
28 const ui = yield* TerminalUI;
29 const repo = yield* ComposioToolkitsRepository;
30
31 - const item = yield* ui
31 + const account = yield* ui
32 .withSpinner(fetchingConnectedAccountMessage(id), repo.getConnectedAccount(id))
33 .pipe(
34 - Effect.asSome,
34 Effect.catchTag(
35 CLIENT_API_ERROR_TAGS,
36 handleClientApiError(ui, {
37 fallbackMessage: `Failed to fetch connected account "${id}".`,
38 hint: BROWSE_CONNECTED_ACCOUNTS_HINT,
40 - fallbackValue: Option.none(),
39 })
40 )
41 );
42
45 - yield* Option.match(item, {
46 - onNone: () => Effect.void,
47 - onSome: account =>
48 - Effect.gen(function* () {
49 - yield* ui.note(formatConnectedAccountInfo(account), connectedAccountInfoTitle(account));
50 - yield* ui.output(formatConnectedAccountInfoJson(account));
51 - }),
52 - });
43 + yield* ui.note(formatConnectedAccountInfo(account), connectedAccountInfoTitle(account));
44 + yield* ui.output(formatConnectedAccountInfoJson(account));
45 });
46
47 /**
ts/packages/cli/src/commands/connected-accounts/link/connected-accounts.link.format.ts
+7 -9
@@ -1,7 +1,7 @@
1 import { Array as Arr, Effect, Option } from 'effect';
2 import type { CommandTree } from 'src/commands/surface';
3 import { BROWSE_TOOLKITS_HINT } from 'src/commands/toolkits/format';
4 -import { reportFailure } from 'src/effects/report-failure';
4 +import { printFailure, ReportedFailure } from 'src/effects/report-failure';
5 import type { ConnectedAccountItem } from 'src/models/connected-accounts';
6 import type { CliProjectType } from 'src/services/command-project';
7 import type { TerminalUI } from 'src/services/terminal-ui';
@@ -100,11 +100,10 @@ export const showExistingAccounts = (
100 items: ReadonlyArray<ExistingAccountLabel>
101 ) =>
102 Effect.gen(function* () {
103 - yield* reportFailure(
104 - ui,
105 - `A connected account already exists for ${scopeDescription}. Pass --alias to create another one.`
106 - );
103 + const message = `A connected account already exists for ${scopeDescription}. Pass --alias to create another one.`;
104 + yield* printFailure(ui, message);
105 yield* ui.note(formatExistingAccountLabels(items), 'Existing accounts');
106 + return yield* new ReportedFailure({ message });
107 });
108
109 /**
@@ -121,10 +120,8 @@ export const showAliasConflict = (
120 }
121 ) =>
122 Effect.gen(function* () {
124 - yield* reportFailure(
125 - ui,
126 - `Alias "${params.alias}" is already in use by connected account "${params.existingId}".`
127 - );
123 + const message = `Alias "${params.alias}" is already in use by connected account "${params.existingId}".`;
124 + yield* printFailure(ui, message);
125 yield* ui.note(
126 [
127 `Use the existing alias: ${params.executeCommand} <TOOL_SLUG> --account ${params.alias} -d '{ ... }'`,
@@ -132,6 +129,7 @@ export const showAliasConflict = (
129 ].join('\n'),
130 'Tips'
131 );
132 + return yield* new ReportedFailure({ message });
133 });
134
135 /** The table of a toolkit's active accounts as a note, or a warning when there are none. */
ts/packages/cli/src/commands/connected-accounts/link/connected-accounts.link.handler.ts
+32 -45
@@ -143,8 +143,8 @@ const existingAccountsForHints = (params: Parameters<typeof listActiveConnectedA
143 );
144
145 /**
146 - * True when no existing account already carries `alias` (compared case-insensitively); false
147 - * after explaining the conflict and how to use the existing account.
146 + * Succeeds when no existing account already carries `alias` (compared case-insensitively); fails
147 + * already reported after explaining the conflict and how to use the existing account.
148 */
149 const ensureAliasIsAvailable = (params: {
150 readonly ui: TerminalUI;
@@ -165,20 +165,21 @@ const ensureAliasIsAvailable = (params: {
165 )
166 ),
167 {
168 - onNone: () => Effect.succeed(true),
168 + onNone: () => Effect.void,
169 onSome: ({ alias, existing }) =>
170 showAliasConflict(params.ui, {
171 alias,
172 existingId: existing.id,
173 executeCommand: params.executeCommand,
174 listCommand: params.listCommand,
175 - }).pipe(Effect.as(false)),
175 + }),
176 }
177 );
178
179 /**
180 - * True when the new link may proceed: an alias was given, no account exists yet in the scope,
181 - * or the link reuses an existing account. False after listing the accounts that block it.
180 + * Succeeds when the new link may proceed: an alias was given, no account exists yet in the
181 + * scope, or the link reuses an existing account. Fails already reported after listing the
182 + * accounts that block it.
183 */
184 const ensureAliasForAdditionalAccount = (params: {
185 readonly ui: TerminalUI;
@@ -192,17 +193,15 @@ const ensureAliasForAdditionalAccount = (params: {
193 params.existingAccounts.length > 0 &&
194 !params.existingAccounts.some(item => item.id === params.connectedAccountId);
195 return blocked
195 - ? showExistingAccounts(params.ui, params.scopeDescription, params.existingAccounts).pipe(
196 - Effect.as(false)
197 - )
198 - : Effect.succeed(true);
196 + ? showExistingAccounts(params.ui, params.scopeDescription, params.existingAccounts)
197 + : Effect.void;
198 };
199
200 /** A response field that is present and not blank. */
201 const nonEmpty = (value: string | null | undefined) =>
202 Option.filter(Option.fromNullishOr(value), text => text.length > 0);
203
205 -/** The link the API answered with, or none after reporting an incomplete response (exit 1). */
204 +/** The link the API answered with; an incomplete response is reported and fails (exit 1). */
205 const validateLinkResponse = (
206 ui: TerminalUI,
207 linkResponse: {
@@ -217,12 +216,11 @@ const validateLinkResponse = (
216 (connectedAccountId, redirectUrl): LinkTarget => ({ connectedAccountId, redirectUrl })
217 ),
218 {
220 - onSome: target => Effect.succeedSome(target),
219 + onSome: target => Effect.succeed(target),
220 onNone: () =>
221 Effect.gen(function* () {
222 yield* Effect.logDebug('Link response:', linkResponse);
224 - yield* reportFailure(ui, INCOMPLETE_LINK_RESPONSE_MESSAGE);
225 - return Option.none<LinkTarget>();
223 + return yield* reportFailure(ui, INCOMPLETE_LINK_RESPONSE_MESSAGE);
224 }),
225 }
226 );
@@ -478,16 +476,15 @@ export const handleLegacyAuthConfigLink = (params: ConnectedAccountsLinkParams)
476 userId: resolvedUserId,
477 authConfigId,
478 });
481 - const aliasAvailable = yield* ensureAliasIsAvailable({
479 + yield* ensureAliasIsAvailable({
480 ui,
481 alias: normalizedAlias,
482 existingAccounts,
483 executeCommand: 'composio dev playground-execute',
484 listCommand: 'composio dev connected-accounts list',
485 });
488 - if (!aliasAvailable) return;
486
490 - const linkOpt = yield* ui
487 + const link = yield* ui
488 .withSpinner(
489 'Creating link session...',
490 client.link.create({
@@ -497,36 +494,29 @@ export const handleLegacyAuthConfigLink = (params: ConnectedAccountsLinkParams)
494 })
495 )
496 .pipe(
500 - Effect.asSome,
497 Effect.catch(error =>
502 - Effect.gen(function* () {
503 - yield* reportFailure(
504 - ui,
505 - extractMessage(error) || `Failed to create link for auth config "${authConfigId}".`,
506 - BROWSE_AUTH_CONFIGS_HINT
507 - );
508 - return Option.none();
509 - })
498 + reportFailure(
499 + ui,
500 + extractMessage(error) || `Failed to create link for auth config "${authConfigId}".`,
501 + BROWSE_AUTH_CONFIGS_HINT
502 + )
503 )
504 );
512 - if (Option.isNone(linkOpt)) return;
505
514 - const target = yield* validateLinkResponse(ui, linkOpt.value);
515 - if (Option.isNone(target)) return;
506 + const target = yield* validateLinkResponse(ui, link);
507
517 - const canContinue = yield* ensureAliasForAdditionalAccount({
508 + yield* ensureAliasForAdditionalAccount({
509 ui,
510 alias: normalizedAlias,
520 - connectedAccountId: target.value.connectedAccountId,
511 + connectedAccountId: target.connectedAccountId,
512 existingAccounts,
513 scopeDescription: `user "${resolvedUserId}" in auth config "${authConfigId}"`,
514 });
524 - if (!canContinue) return;
515
516 yield* finishLink({
517 ui,
518 client,
529 - target: target.value,
519 + target,
520 toolkit: Option.none(),
521 projectType: resolvedProject.projectType,
522 noWait: params.noWait,
@@ -559,7 +549,7 @@ export const handleToolRouterLink = (params: ConnectedAccountsLinkParams) =>
549 userId: resolvedUserId,
550 toolkitSlug,
551 });
562 - const aliasAvailable = yield* ensureAliasIsAvailable({
552 + yield* ensureAliasIsAvailable({
553 ui,
554 alias: normalizedAlias,
555 existingAccounts,
@@ -573,7 +563,6 @@ export const handleToolRouterLink = (params: ConnectedAccountsLinkParams) =>
563 listCommand: `composio connections list --toolkit ${toolkitSlug}`,
564 }),
565 });
576 - if (!aliasAvailable) return;
566
567 const scope = consumerScope(resolvedProject);
568 const linkOpt = yield* ui
@@ -608,34 +597,32 @@ export const handleToolRouterLink = (params: ConnectedAccountsLinkParams) =>
597 return Option.none();
598 }
599 yield* Effect.logDebug('Link error:', error);
611 - yield* reportFailure(
600 + return yield* reportFailure(
601 ui,
602 extractMessage(error) ?? `Failed to create link for toolkit "${toolkitSlug}".`,
603 BROWSE_TOOLKITS_HINT
604 );
616 - return Option.none();
605 })
606 ),
619 - Effect.tap(() => invalidateConsumerConnectedToolkitsCache().pipe(Effect.ignore))
607 + // On every outcome, a reported failure included.
608 + Effect.ensuring(invalidateConsumerConnectedToolkitsCache().pipe(Effect.ignore))
609 );
610 if (Option.isNone(linkOpt)) return;
611
612 const target = yield* validateLinkResponse(ui, linkOpt.value);
624 - if (Option.isNone(target)) return;
613
626 - const canContinue = yield* ensureAliasForAdditionalAccount({
614 + yield* ensureAliasForAdditionalAccount({
615 ui,
616 alias: normalizedAlias,
629 - connectedAccountId: target.value.connectedAccountId,
617 + connectedAccountId: target.connectedAccountId,
618 existingAccounts,
619 scopeDescription: `user "${resolvedUserId}" in toolkit "${toolkitSlug}"`,
620 });
633 - if (!canContinue) return;
621
622 yield* finishLink({
623 ui,
624 client,
638 - target: target.value,
625 + target,
626 toolkit: Option.some(toolkitSlug),
627 projectType: resolvedProject.projectType,
628 noWait: params.noWait,
@@ -648,8 +635,8 @@ export const handleToolRouterLink = (params: ConnectedAccountsLinkParams) =>
635 command: 'link',
636 status: params.noWait ? 'pending' : 'active',
637 toolkit: toolkitSlug,
651 - connectedAccountId: target.value.connectedAccountId,
652 - redirectUrl: target.value.redirectUrl,
638 + connectedAccountId: target.connectedAccountId,
639 + redirectUrl: target.redirectUrl,
640 },
641 }).pipe(Effect.ignore);
642 });
ts/packages/cli/src/commands/connected-accounts/whoami/connected-accounts.whoami.handler.ts
+6 -17
@@ -29,34 +29,23 @@ const showConnectedAccountProfile = (id: string) =>
29 const ui = yield* TerminalUI;
30 const repo = yield* ComposioToolkitsRepository;
31
32 - const item = yield* ui
32 + const account = yield* ui
33 .withSpinner(fetchingConnectedAccountMessage(id), repo.getConnectedAccount(id))
34 .pipe(
35 - Effect.asSome,
35 Effect.catchTag(
36 CLIENT_API_ERROR_TAGS,
37 handleClientApiError(ui, {
38 fallbackMessage: `Failed to fetch connected account "${id}".`,
39 hint: BROWSE_CONNECTED_ACCOUNTS_HINT,
41 - fallbackValue: Option.none(),
40 })
41 )
42 );
43
46 - yield* Option.match(item, {
47 - onNone: () => Effect.void,
48 - onSome: account =>
49 - Effect.gen(function* () {
50 - if (account.status !== 'ACTIVE') {
51 - yield* ui.log.warn(inactiveStatusMessage(account.status));
52 - }
53 - yield* ui.note(
54 - formatConnectedAccountWhoami(account),
55 - connectedAccountWhoamiTitle(account)
56 - );
57 - yield* ui.output(formatConnectedAccountWhoamiJson(account));
58 - }),
59 - });
44 + if (account.status !== 'ACTIVE') {
45 + yield* ui.log.warn(inactiveStatusMessage(account.status));
46 + }
47 + yield* ui.note(formatConnectedAccountWhoami(account), connectedAccountWhoamiTitle(account));
48 + yield* ui.output(formatConnectedAccountWhoamiJson(account));
49 });
50
51 /**
ts/packages/cli/src/commands/init.cmd.ts
+5 -4
@@ -22,7 +22,7 @@ import { browserLogin } from 'src/effects/browser-login';
22 import { setupCacheDir } from 'src/effects/setup-cache-dir';
23 import { CLIENT_API_ERROR_TAGS } from 'src/services/composio-errors';
24 import { commandInputError } from 'src/commands/errors';
25 -import { reportFailure } from 'src/effects/report-failure';
25 +import { printFailure, ReportedFailure } from 'src/effects/report-failure';
26 import {
27 describeDecodeError,
28 isClientConnectionError,
@@ -327,13 +327,14 @@ const initInteractiveFlow = (params: { composioDir: string; noBrowser: boolean;
327 );
328
329 if (orgProjects.data.length === 0) {
330 - yield* reportFailure(
330 + const message = 'No projects found for your organization.';
331 + yield* printFailure(
332 ui,
332 - 'No projects found for your organization.',
333 + message,
334 'Create a project at https://platform.composio.dev, then run `composio dev init` again.'
335 );
336 yield* ui.outro('');
336 - return;
337 + return yield* new ReportedFailure({ message });
338 }
339
340 // 3. Select a developer project
ts/packages/cli/src/commands/install/install.errors.ts
+12 -4
@@ -1,12 +1,20 @@
1 -import { Data } from 'effect';
1 +import { Data, Runtime } from 'effect';
2
3 /**
4 * Aborted shell setup must fail the process: install.sh only runs its guarded
5 * inline PATH fallback when `composio install` exits non-zero, so a successful
6 * exit here would leave the user with no PATH setup and a green install. The
7 - * abort reason is already printed before this error is raised; cli-main.ts
8 - * maps it to exit code 1 without printing anything further.
7 + * abort reason is already printed before this error is raised, so the runtime
8 + * prints nothing further (`[Runtime.errorReported]` is false) and exits 1.
9 */
10 export class ShellSetupAbortError extends Data.TaggedError('commands/ShellSetupAbortError')<{
11 readonly message: string;
12 -}> {}
12 +}> {
13 + get [Runtime.errorReported]() {
14 + return false;
15 + }
16 +
17 + get [Runtime.errorExitCode]() {
18 + return 1;
19 + }
20 +}
ts/packages/cli/src/commands/proxy.cmd.ts
+12 -4
@@ -1,6 +1,6 @@
1 import { requireLogin } from 'src/effects/require-auth';
2 import { Argument, Command, Flag } from 'effect/cli';
3 -import { Data, Effect, Result, Option } from 'effect';
3 +import { Data, Effect, Result, Option, Runtime } from 'effect';
4 import type {
5 SessionProxyExecuteParams,
6 SessionProxyExecuteResponse,
@@ -80,8 +80,8 @@ const SUPPORTED_PROXY_METHODS: ReadonlyArray<ProxyMethod> = [
80
81 /**
82 * A proxy call refused before sending it because the toolkit is not connected, already reported
83 - * on stderr and as `{ "successful": false, ... }` on stdout. `cli-main.ts` prints nothing more
84 - * and exits 1.
83 + * on stderr and as `{ "successful": false, ... }` on stdout. The runtime prints nothing more
84 + * (`[Runtime.errorReported]` is false) and exits 1.
85 */
86 export class ReportedProxyCommandError extends Data.TaggedError(
87 'commands/ReportedProxyCommandError'
@@ -89,7 +89,15 @@ export class ReportedProxyCommandError extends Data.TaggedError(
89 readonly message: string;
90 readonly toolkit: string;
91 readonly endpoint: string;
92 -}> {}
92 +}> {
93 + get [Runtime.errorReported]() {
94 + return false;
95 + }
96 +
97 + get [Runtime.errorExitCode]() {
98 + return 1;
99 + }
100 +}
101
102 class ProxyRequestError extends requestError('commands/ProxyRequestError') {}
103
ts/packages/cli/src/commands/run.cmd.ts
+7 -9
@@ -6,6 +6,7 @@ import * as Path from 'effect/Path';
6 import { ChildProcess, ChildProcessSpawner } from 'effect/process';
7 import { Data, Deferred, Duration, Effect, MutableRef, Option, Result } from 'effect';
8 import { APP_VERSION } from 'src/constants';
9 +import { ChildProcessExited } from 'src/effects/child-process-exited';
10 import { loadGenerationRuntime } from 'src/effects/generation-runtime';
11 import { actingUser } from 'src/commands/surface';
12 import { type RunHelperContext } from 'src/services/run-helpers-runtime';
@@ -558,17 +559,14 @@ export const runCmd = Command.make('run', {
559 // into a failure, which is what the previous `Effect.orDie` did.
560 Effect.ignore
561 )
561 - ),
562 - // Interruption (Ctrl-C) skips the assignment below, and the default teardown reports
563 - // an interrupt-only exit as success. Report the conventional 128+SIGINT instead so
564 - // wrappers and `set -e` scripts do not read a cancelled run as a passing one.
565 - Effect.onInterrupt(() =>
566 - Effect.sync(() => {
567 - process.exitCode = 130;
568 - })
562 )
563 );
571 - process.exitCode = exitCode;
564 + // The process exits with the child's code. An interrupted run (Ctrl-C) never gets here:
565 + // `Runtime.defaultTeardown` exits 130 for it, so wrappers and `set -e` scripts do not
566 + // read a cancelled run as a passing one.
567 + if (exitCode !== 0) {
568 + return yield* new ChildProcessExited({ code: exitCode });
569 + }
570 }).pipe(Effect.scoped)
571 )
572 );
ts/packages/cli/src/commands/setup.cmd.ts
+18 -1
@@ -66,6 +66,22 @@ const setupCommandError = (
66 ...(cause === undefined ? {} : { cause }),
67 });
68
69 +/** Prints why setup failed and closes the session; the command then fails already reported. */
70 +const renderSetupFailure = (error: SetupCommandError) =>
71 + Effect.gen(function* () {
72 + const ui = yield* TerminalUI;
73 + const summary =
74 + error.operation === 'uninstall'
75 + ? 'Composio plugin uninstall was unsuccessful.'
76 + : 'Composio setup was unsuccessful.';
77 + if ((yield* ui.capabilities).canDecorate) {
78 + yield* ui.log.error(error.message);
79 + yield* ui.outro(summary);
80 + } else {
81 + yield* ui.error(`${summary} ${error.message}`);
82 + }
83 + });
84 +
85 // Only a host that is present but unsupported has a reason to report.
86 const unsupportedReasonCodeOf = (
87 detection: SetupTargetDetection
@@ -314,7 +330,8 @@ const setupBaseCmd = Command.make(
330 'unknown',
331 error
332 );
317 - })
333 + }),
334 + Effect.tapError(renderSetupFailure)
335 )
336 );
337
ts/packages/cli/src/commands/toolkits/info/toolkits.info.handler.ts
+3 -11
@@ -55,7 +55,7 @@ export const runToolkitsInfo = ({ slug, allDetails }: ToolkitsInfoParams) =>
55 );
56 }
57
58 - const resultOpt = yield* ui
58 + const result = yield* ui
59 .withSpinner(
60 `Fetching toolkit "${slugValue}"...`,
61 Effect.gen(function* () {
@@ -94,22 +94,15 @@ export const runToolkitsInfo = ({ slug, allDetails }: ToolkitsInfoParams) =>
94 })
95 )
96 .pipe(
97 - Effect.asSome,
97 Effect.catch(error =>
98 Effect.gen(function* () {
99 const message = extractMessage(error) ?? `Failed to fetch toolkit "${slugValue}".`;
100 yield* Effect.logDebug('Toolkit info error:', error);
102 - yield* reportFailure(ui, message, BROWSE_TOOLKITS_HINT);
103 - return Option.none();
101 + return yield* reportFailure(ui, message, BROWSE_TOOLKITS_HINT);
102 })
103 )
104 );
105
108 - if (Option.isNone(resultOpt)) {
109 - return;
110 - }
111 -
112 - const result = resultOpt.value;
106 const toolkit = result.toolkit;
107 const detailedToolkit = Option.getOrUndefined(result.detailedToolkitOpt);
108
@@ -129,8 +122,7 @@ export const runToolkitsInfo = ({ slug, allDetails }: ToolkitsInfoParams) =>
122 const hint = first
123 ? `Did you mean?\n${suggestions.map(s => ` ${s.label}`).join('\n')}\n\n${first.command}`
124 : BROWSE_TOOLKITS_HINT;
132 - yield* reportFailure(ui, `Toolkit "${slugValue}" not found.`, hint);
133 - return;
125 + return yield* reportFailure(ui, `Toolkit "${slugValue}" not found.`, hint);
126 }
127
128 yield* ui.log.message(
ts/packages/cli/src/commands/toolkits/list/toolkits.list.handler.ts
+4 -5
@@ -4,7 +4,7 @@ import { actingUserOption, fallbackNotice } from 'src/commands/surface';
4 import { resolveToolRouterSession } from 'src/effects/create-tool-router-session';
5 import { ComposioClientSingleton, ComposioToolkitsRepository } from 'src/services/composio-clients';
6 import { idempotent } from 'src/services/composio-request';
7 -import { reportFailure } from 'src/effects/report-failure';
7 +import { printFailure, ReportedFailure } from 'src/effects/report-failure';
8 import { TerminalUI } from 'src/services/terminal-ui';
9 import { clampLimit } from 'src/ui/clamp-limit';
10 import { extractMessage } from 'src/utils/api-error-extraction';
@@ -168,11 +168,10 @@ export const runToolkitsList = ({ query, limit, connected }: ToolkitsListParams)
168 Effect.catch(error =>
169 Effect.gen(function* () {
170 const ui = yield* TerminalUI;
171 - yield* reportFailure(
172 - ui,
173 - extractMessage(error) ?? 'An error occurred while fetching toolkits.'
174 - );
171 + const message = extractMessage(error) ?? 'An error occurred while fetching toolkits.';
172 + yield* printFailure(ui, message);
173 yield* ui.output('[]');
174 + return yield* new ReportedFailure({ message });
175 })
176 )
177 );
ts/packages/cli/src/commands/toolkits/search/toolkits.search.handler.ts
+4 -5
@@ -1,6 +1,6 @@
1 import { Effect } from 'effect';
2 import { ComposioToolkitsRepository } from 'src/services/composio-clients';
3 -import { reportFailure } from 'src/effects/report-failure';
3 +import { printFailure, ReportedFailure } from 'src/effects/report-failure';
4 import { TerminalUI } from 'src/services/terminal-ui';
5 import { clampLimit } from 'src/ui/clamp-limit';
6 import { extractMessage } from 'src/utils/api-error-extraction';
@@ -50,11 +50,10 @@ export const runToolkitsSearch = ({ query, limit }: ToolkitsSearchParams) =>
50 Effect.catch(error =>
51 Effect.gen(function* () {
52 const ui = yield* TerminalUI;
53 - yield* reportFailure(
54 - ui,
55 - extractMessage(error) ?? 'An error occurred while searching toolkits.'
56 - );
53 + const message = extractMessage(error) ?? 'An error occurred while searching toolkits.';
54 + yield* printFailure(ui, message);
55 yield* ui.output('[]');
56 + return yield* new ReportedFailure({ message });
57 })
58 )
59 );
ts/packages/cli/src/commands/toolkits/version/toolkits.version.handler.ts
+5 -8
@@ -49,28 +49,25 @@ export const runToolkitsVersion = ({ slug }: ToolkitsVersionParams) =>
49 const clientSingleton = yield* ComposioClientSingleton;
50 const client = yield* clientSingleton.get();
51
52 - const toolkitOpt = yield* ui
52 + const versions = yield* ui
53 .withSpinner(
54 `Fetching versions for toolkit "${slug}"...`,
55 client.toolkits.retrieve(slug, undefined, idempotent)
56 )
57 .pipe(
58 - Effect.map(toolkit => Option.some(toolkitVersionsOf(toolkit))),
58 + Effect.map(toolkitVersionsOf),
59 Effect.catch(error =>
60 Effect.gen(function* () {
61 yield* Effect.logDebug('Toolkit version error:', error);
62 - yield* reportFailure(
62 + return yield* reportFailure(
63 ui,
64 extractMessage(error) ?? `Failed to fetch version info for toolkit "${slug}".`,
65 BROWSE_TOOLKITS_HINT
66 );
67 - return Option.none<ToolkitVersions>();
67 })
68 )
69 );
70
72 - if (Option.isNone(toolkitOpt)) return;
73 -
74 - yield* ui.log.message(formatToolkitVersions(toolkitOpt.value));
75 - yield* ui.output(formatToolkitVersionsJson(toolkitOpt.value));
71 + yield* ui.log.message(formatToolkitVersions(versions));
72 + yield* ui.output(formatToolkitVersionsJson(versions));
73 });
ts/packages/cli/src/commands/tools/commands/tools.execute.cmd.ts
+11 -3
@@ -4,7 +4,7 @@ import { commandInputError } from 'src/commands/errors';
4 import { ExpectedFailure } from 'src/effects/expected-failure';
5 import { Argument, Command, Flag } from 'effect/cli';
6 import util from 'node:util';
7 -import { Data, Effect, Context, Option, Result } from 'effect';
7 +import { Data, Effect, Context, Option, Result, Runtime } from 'effect';
8 import * as FileSystem from 'effect/FileSystem';
9 import * as Path from 'effect/Path';
10 import { redact } from 'src/ui/redact';
@@ -152,13 +152,21 @@ export class ToolExecutionError extends Data.TaggedError('ToolExecutionError')<{
152
153 /**
154 * A failed execution whose result is already on stdout as `{ "successful": false, ... }`.
155 - * `cli-main.ts` prints nothing more for it and exits 1.
155 + * The runtime prints nothing more for it (`[Runtime.errorReported]` is false) and exits 1.
156 */
157 export class ReportedToolExecutionError extends Data.TaggedError('ReportedToolExecutionError')<{
158 readonly reason: 'connection_check' | 'execution_failed' | 'parallel_failed';
159 readonly message: string;
160 readonly toolSlug?: string;
161 -}> {}
161 +}> {
162 + get [Runtime.errorReported]() {
163 + return false;
164 + }
165 +
166 + get [Runtime.errorExitCode]() {
167 + return 1;
168 + }
169 +}
170
171 const parseArguments = (raw: string) =>
172 Effect.fromResult(
ts/packages/cli/src/commands/tools/info/tools.info.handler.ts
+3 -12
@@ -32,15 +32,14 @@ const invalidInput = commandInputError('tools info');
32 const missingSlug = () => invalidInput(`${MISSING_SLUG_MESSAGE}\n${MISSING_SLUG_HINT}`, '<slug>');
33
34 /**
35 - * Fetches the tool, or reports the API failure with "did you mean" suggestions, sets exit
36 - * code 1, and yields nothing.
35 + * Fetches the tool, or reports the API failure with "did you mean" suggestions and fails
36 + * already reported (exit 1).
37 */
38 const fetchTool = (slug: string) =>
39 Effect.gen(function* () {
40 const ui = yield* TerminalUI;
41 const repo = yield* ComposioToolkitsRepository;
42 return yield* ui.withSpinner(fetchingToolMessage(slug), repo.getToolDetailed(slug)).pipe(
43 - Effect.asSome,
43 Effect.catchTag(
44 CLIENT_API_ERROR_TAGS,
45 handleClientApiError(ui, {
@@ -49,7 +48,6 @@ const fetchTool = (slug: string) =>
48 commandHintStep('Browse available toolkits', 'dev.toolkits.list'),
49 commandHintStep('Then list tools', 'root.tools.list'),
50 ].join('\n'),
52 - fallbackValue: Option.none<ToolRetrieveResponse>(),
51 searchForSuggestions: () =>
52 repo
53 .searchTools({ search: slug, limit: 3 })
@@ -85,13 +83,6 @@ export const runToolsInfo = ({ slug }: ToolsInfoParams) =>
83 return yield* Option.match(slug, {
84 onNone: () => Effect.fail(missingSlug()),
85 onSome: slugValue =>
88 - fetchTool(slugValue).pipe(
89 - Effect.flatMap(
90 - Option.match({
91 - onNone: () => Effect.void,
92 - onSome: tool => showTool(slugValue, tool),
93 - })
94 - )
95 - ),
86 + fetchTool(slugValue).pipe(Effect.flatMap(tool => showTool(slugValue, tool))),
87 });
88 });
ts/packages/cli/src/commands/triggers/commands/triggers.listen.cmd.ts
+9 -2
@@ -376,8 +376,15 @@ export const triggersCmd$Listen = Command.make(
376 }).pipe(
377 Effect.scoped,
378 // An onExit finalizer, so the summaries print on every stop — including the
379 - // interruption by Ctrl+C or SIGTERM, where the code after this block would not run.
380 - Effect.onExit(() => Effect.andThen(forwardFailures.report, outputWriteFailures.report)),
379 + // interruption by Ctrl+C or SIGTERM, where the code after this block would not run. With
380 + // --fail-fast a summary fails the command, so the second one still prints after it.
381 + Effect.onExit(() =>
382 + Effect.gen(function* () {
383 + const forwarded = yield* Effect.exit(forwardFailures.report);
384 + yield* outputWriteFailures.report;
385 + yield* forwarded;
386 + })
387 + ),
388 Effect.catchTag('services/TriggerRealtimeSubscriptionError', error =>
389 reportFailure(
390 ui,
ts/packages/cli/src/commands/triggers/create/triggers.create.handler.ts
+1 -8
@@ -77,7 +77,7 @@ export const runTriggersCreate = ({
77 const acting = yield* actingUserOption();
78 const resolvedUserId = Option.map(acting, found => found.userId);
79
80 - const createdOpt = yield* ui
80 + const created = yield* ui
81 .withSpinner(
82 `Creating trigger "${triggerName.value}"...`,
83 repo.createTrigger(triggerName.value, {
@@ -87,22 +87,15 @@ export const runTriggersCreate = ({
87 })
88 )
89 .pipe(
90 - Effect.asSome,
90 Effect.catchTag(
91 CLIENT_API_ERROR_TAGS,
92 handleClientApiError(ui, {
93 fallbackMessage: `Failed to create trigger "${triggerName.value}".`,
94 hint: 'List available trigger types with:\n> composio dev triggers list',
96 - fallbackValue: Option.none(),
95 })
96 )
97 );
98
101 - if (Option.isNone(createdOpt)) {
102 - return;
103 - }
104 -
105 - const created = createdOpt.value;
99 yield* ui.log.success(`Trigger created: ${created.trigger_id}`);
100 yield* ui.log.step(
101 `To check status:\n> composio dev triggers status --trigger-ids "${created.trigger_id}"`
ts/packages/cli/src/commands/triggers/disable/triggers.disable.handler.ts
+9 -15
@@ -49,21 +49,15 @@ export const runTriggersDisable = ({ id, dangerouslyAllow }: TriggersDisablePara
49 }
50
51 const idValue = id.value;
52 - const disabled = yield* ui
53 - .withSpinner(`Disabling trigger "${idValue}"...`, repo.disableTrigger(idValue))
54 - .pipe(
55 - Effect.as(true),
56 - Effect.catchTag(
57 - CLIENT_API_ERROR_TAGS,
58 - handleClientApiError(ui, {
59 - fallbackMessage: `Failed to disable trigger "${idValue}".`,
60 - hint: 'Browse available triggers:\n> composio dev triggers status',
61 - fallbackValue: false,
62 - })
63 - )
64 - );
65 -
66 - if (!disabled) return;
52 + yield* ui.withSpinner(`Disabling trigger "${idValue}"...`, repo.disableTrigger(idValue)).pipe(
53 + Effect.catchTag(
54 + CLIENT_API_ERROR_TAGS,
55 + handleClientApiError(ui, {
56 + fallbackMessage: `Failed to disable trigger "${idValue}".`,
57 + hint: 'Browse available triggers:\n> composio dev triggers status',
58 + })
59 + )
60 + );
61
62 yield* ui.log.success(`Trigger "${idValue}" disabled.`);
63 });
ts/packages/cli/src/commands/triggers/enable/triggers.enable.handler.ts
+9 -15
@@ -33,21 +33,15 @@ export const runTriggersEnable = ({ id }: TriggersEnableParams) =>
33 }
34
35 const idValue = id.value;
36 - const enabled = yield* ui
37 - .withSpinner(`Enabling trigger "${idValue}"...`, repo.enableTrigger(idValue))
38 - .pipe(
39 - Effect.as(true),
40 - Effect.catchTag(
41 - CLIENT_API_ERROR_TAGS,
42 - handleClientApiError(ui, {
43 - fallbackMessage: `Failed to enable trigger "${idValue}".`,
44 - hint: 'Browse available triggers:\n> composio dev triggers status --show-disabled',
45 - fallbackValue: false,
46 - })
47 - )
48 - );
49 -
50 - if (!enabled) return;
36 + yield* ui.withSpinner(`Enabling trigger "${idValue}"...`, repo.enableTrigger(idValue)).pipe(
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 + })
43 + )
44 + );
45
46 yield* ui.log.success(`Trigger "${idValue}" enabled.`);
47 });
ts/packages/cli/src/commands/triggers/info/triggers.info.handler.ts
+1 -7
@@ -51,24 +51,18 @@ export const runTriggersInfo = ({ slug }: TriggersInfoParams) =>
51
52 const slugValue = slug.value;
53
54 - const triggerTypeOpt = yield* ui
54 + const triggerType = yield* ui
55 .withSpinner('Fetching trigger type details...', repo.getTriggerTypeDetailed(slugValue))
56 .pipe(
57 - Effect.asSome,
57 Effect.catchTag(
58 CLIENT_API_ERROR_TAGS,
59 handleClientApiError(ui, {
60 fallbackMessage: `Trigger "${slugValue}" not found.`,
61 hint: `Browse available trigger types:\n> ${listCommandPlaceholder}`,
63 - fallbackValue: Option.none(),
62 })
63 )
64 );
65
68 - if (Option.isNone(triggerTypeOpt)) return;
69 -
70 - const triggerType = triggerTypeOpt.value;
71 -
66 yield* ui.note(formatTriggerTypeInfo(triggerType), `Trigger: ${triggerType.name}`);
67
68 const toolkitSlug = triggerType.toolkit?.slug?.toLowerCase();
ts/packages/cli/src/commands/triggers/status/triggers.status.handler.ts
+15 -22
@@ -94,36 +94,29 @@ export const runTriggersStatus = ({
94 })
95 )
96 .pipe(
97 - Effect.asSome,
97 Effect.catchTag(
98 CLIENT_API_ERROR_TAGS,
99 handleClientApiError(ui, {
100 fallbackMessage: 'Failed to fetch trigger status.',
101 hint: 'Retry with:\n> composio dev triggers status --show-disabled',
103 - fallbackValue: Option.none(),
102 })
103 )
104 );
105
108 - yield* Option.match(page, {
109 - onNone: () => Effect.void,
110 - onSome: result => {
111 - const { items, total } = filterByToolkits(result, toolkitFilter);
112 - return Arr.match(items, {
113 - onEmpty: () =>
114 - ui.log.warn(
115 - showDisabled
116 - ? 'No triggers found for the provided filters.'
117 - : 'No active triggers found for the provided filters.'
118 - ),
119 - onNonEmpty: shown =>
120 - Effect.gen(function* () {
121 - yield* ui.log.info(
122 - `Listing ${shown.length} of ${total} triggers\n\n${formatTriggersStatusTable(shown)}`
123 - );
124 - yield* ui.output(formatTriggersStatusJson(shown));
125 - }),
126 - });
127 - },
106 + const { items, total } = filterByToolkits(page, toolkitFilter);
107 + yield* Arr.match(items, {
108 + onEmpty: () =>
109 + ui.log.warn(
110 + showDisabled
111 + ? 'No triggers found for the provided filters.'
112 + : 'No active triggers found for the provided filters.'
113 + ),
114 + onNonEmpty: shown =>
115 + Effect.gen(function* () {
116 + yield* ui.log.info(
117 + `Listing ${shown.length} of ${total} triggers\n\n${formatTriggersStatusTable(shown)}`
118 + );
119 + yield* ui.output(formatTriggersStatusJson(shown));
120 + }),
121 });
122 });
ts/packages/cli/src/effects/child-process-exited.ts new
+18
@@ -0,0 +1,18 @@
1 +import { Data, Runtime } from 'effect';
2 +
3 +/**
4 + * A child process the command proxies (`composio run`) exited with a non-zero `code`. The child
5 + * already wrote its own output, so `BunRuntime.runMain` logs nothing (`[Runtime.errorReported]`
6 + * is false) and `Runtime.defaultTeardown` exits with the child's code.
7 + */
8 +export class ChildProcessExited extends Data.TaggedError('effects/ChildProcessExited')<{
9 + readonly code: number;
10 +}> {
11 + get [Runtime.errorReported]() {
12 + return false;
13 + }
14 +
15 + get [Runtime.errorExitCode]() {
16 + return this.code;
17 + }
18 +}
ts/packages/cli/src/effects/handle-agent-auth-error.ts
+1 -1
@@ -11,7 +11,7 @@ export const handleAgentAuthError = <E, R>(effect: Effect.Effect<void, E | Agent
11 error =>
12 Effect.gen(function* () {
13 const ui = yield* TerminalUI;
14 - yield* reportFailure(
14 + return yield* reportFailure(
15 ui,
16 error.message,
17 error.nextSteps.length > 0
ts/packages/cli/src/effects/handle-http-error.ts
+13 -16
@@ -2,7 +2,7 @@ import { isAPIError } from '@composio/client/effect';
2 import { Effect } from 'effect';
3 import type { ClientApiError } from 'src/services/composio-errors';
4 import type { TerminalUI } from 'src/services/terminal-ui';
5 -import { reportFailure } from 'src/effects/report-failure';
5 +import { reportFailure, type ReportedFailure } from 'src/effects/report-failure';
6 import { describeDecodeError, isClientDecodeError } from 'src/utils/api-error-extraction';
7 import { isRejectedUserApiKey, rejectedUserApiKeyHint } from 'src/effects/rejected-user-api-key';
8
@@ -13,10 +13,9 @@ export interface Suggestion {
13
14 const noSuggestions: ReadonlyArray<Suggestion> = [];
15
16 -export interface HandleClientApiErrorOptions<A> {
16 +export interface HandleClientApiErrorOptions {
17 readonly fallbackMessage: string;
18 readonly hint: string;
19 - readonly fallbackValue: A;
19 readonly searchForSuggestions?: () => Effect.Effect<ReadonlyArray<Suggestion>, unknown, never>;
20 }
21
@@ -39,19 +38,20 @@ const reportOf = (e: ClientApiError): Effect.Effect<ErrorReport> => {
38
39 /**
40 * Create a handler for a client API error that logs the structured error
42 - * details (or a fallback message) and a contextual hint, then returns a
43 - * fallback value.
41 + * details (or a fallback message) and a contextual hint, then fails.
42 *
43 * The final rendering is `reportFailure`'s (`src/effects/report-failure.ts`):
46 - * the exit code is set to 1 so callers such as scripts and agents can detect
47 - * the failure, and the message and hint reach stderr as plain lines when it is
48 - * not a TTY.
44 + * the message and hint reach stderr as plain lines when it is not a TTY, and
45 + * the handler fails with a `ReportedFailure`, so the process exits 1 and
46 + * callers such as scripts and agents can detect the failure. The handler never
47 + * succeeds, so the recovered effect keeps the request's own success type and
48 + * the caller reads the result straight through.
49 *
50 * Used by info/delete/create commands that share the same error-handling shape.
51 *
52 * When `searchForSuggestions` is provided, the handler will attempt to find
53 * similar items and display "Did you mean?" suggestions instead of the generic hint.
54 - * Suggestion search failures are silently swallowed — the handler always completes.
54 + * Suggestion search failures are silently swallowed.
55 *
56 * A response that failed client decoding is reported by operation and request
57 * id with an upgrade hint, in place of the fallback message and the hint.
@@ -68,15 +68,14 @@ const reportOf = (e: ClientApiError): Effect.Effect<ErrorReport> => {
68 * handleClientApiError(ui, {
69 * fallbackMessage: `Failed to fetch auth config "${id}".`,
70 * hint: 'Browse available auth configs:\n> composio dev auth-configs list',
71 - * fallbackValue: Option.none(),
71 * })
72 * )
73 * )
74 * ```
75 */
76 export const handleClientApiError =
78 - <A>(ui: TerminalUI, opts: HandleClientApiErrorOptions<A>) =>
79 - (e: ClientApiError) =>
77 + (ui: TerminalUI, opts: HandleClientApiErrorOptions) =>
78 + (e: ClientApiError): Effect.Effect<never, ReportedFailure> =>
79 Effect.gen(function* () {
80 const report = yield* reportOf(e);
81 const message = report.message ?? opts.fallbackMessage;
@@ -94,15 +93,13 @@ export const handleClientApiError =
93 const [first] = suggestions;
94 if (first) {
95 const lines = suggestions.map(s => ` ${s.label}`).join('\n');
97 - yield* reportFailure(
96 + return yield* reportFailure(
97 ui,
98 message,
99 withHint(`Did you mean?\n${lines}\n\n${first.command}`)
100 );
102 - return opts.fallbackValue;
101 }
102 }
103
106 - yield* reportFailure(ui, message, withHint(hint));
107 - return opts.fallbackValue;
104 + return yield* reportFailure(ui, message, withHint(hint));
105 });
ts/packages/cli/src/effects/report-failure.ts
+38 -9
@@ -1,20 +1,34 @@
1 -import { Effect } from 'effect';
2 -import { NodeProcess } from 'src/services/node-process';
1 +import { Data, Effect, Runtime } from 'effect';
2 import type { TerminalUI } from 'src/services/terminal-ui';
3
4 /**
6 - * Reports a failure the command recovers from instead of failing: sets the exit code to 1 and
7 - * prints `message`, then `hint` when there is one, on stderr. On a terminal they render as a
5 + * A failure already shown to the user. It only makes the command fail: `BunRuntime.runMain` does
6 + * not log it (`[Runtime.errorReported]` is false) and `Runtime.defaultTeardown` exits 1.
7 + *
8 + * The markers are getters, like `ExpectedFailure`, so they stay off the instance's own properties.
9 + */
10 +export class ReportedFailure extends Data.TaggedError('effects/ReportedFailure')<{
11 + readonly message: string;
12 +}> {
13 + get [Runtime.errorReported]() {
14 + return false;
15 + }
16 +
17 + get [Runtime.errorExitCode]() {
18 + return 1;
19 + }
20 +}
21 +
22 +/**
23 + * Prints `message`, then `hint` when there is one, on stderr. On a terminal they render as a
24 * decorated error and step; otherwise as plain lines, since `ui.log.*` decoration is dropped
25 * when stderr is not a TTY and scripts, CI and agents would see nothing.
26 *
11 - * A usage mistake fails with a `CommandInputError` instead; see `src/commands/errors.ts`.
27 + * Use it directly only when the command prints more before it fails with a `ReportedFailure`;
28 + * otherwise use `reportFailure`.
29 */
13 -export const reportFailure = (ui: TerminalUI, message: string, hint?: string) =>
30 +export const printFailure = (ui: TerminalUI, message: string, hint?: string) =>
31 Effect.gen(function* () {
15 - const proc = yield* NodeProcess;
16 - yield* proc.setExitCode(1);
17 -
32 const { canDecorate } = yield* ui.capabilities;
33 const [error, step] = canDecorate ? [ui.log.error, ui.log.step] : [ui.error, ui.error];
34 yield* error(message);
@@ -22,3 +36,18 @@ export const reportFailure = (ui: TerminalUI, message: string, hint?: string) =>
36 yield* step(hint);
37 }
38 });
39 +
40 +/**
41 + * Reports a failure the command handles itself: prints it like `printFailure`, then fails with a
42 + * `ReportedFailure`, so the process exits 1 without printing more.
43 + *
44 + * A usage mistake fails with a `CommandInputError` instead; see `src/commands/errors.ts`.
45 + */
46 +export const reportFailure = (
47 + ui: TerminalUI,
48 + message: string,
49 + hint?: string
50 +): Effect.Effect<never, ReportedFailure> =>
51 + printFailure(ui, message, hint).pipe(
52 + Effect.andThen(Effect.fail(new ReportedFailure({ message })))
53 + );
ts/packages/cli/src/services/node-process.ts
+1 -10
@@ -1,16 +1,11 @@
1 import process from 'node:process';
2 -import { Context, Effect, Layer } from 'effect';
2 +import { Context, 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>;
9 }
10
11 // Service that wraps `node:process`, for testing purposes.
@@ -22,9 +17,5 @@ export class NodeProcess extends Context.Service<NodeProcess, NodeProcessShape>(
17 execPath: process.execPath,
18 platform: process.platform,
19 arch: process.arch,
25 - setExitCode: code =>
26 - Effect.sync(() => {
27 - process.exitCode = code;
28 - }),
20 }));
21 }
ts/packages/cli/src/services/setup-command-error.ts
+14 -2
@@ -1,4 +1,4 @@
1 -import { Data } from 'effect';
1 +import { Data, Runtime } from 'effect';
2
3 export type SetupFailureReasonCode =
4 | 'all_requires_both_hosts'
@@ -9,9 +9,21 @@ export type SetupFailureReasonCode =
9 | 'marketplace_conflict'
10 | 'unknown';
11
12 +/**
13 + * Why `composio setup` failed. The `setup` command renders it, with its outro, before failing, so
14 + * the runtime prints nothing more (`[Runtime.errorReported]` is false) and exits 1.
15 + */
16 export class SetupCommandError extends Data.TaggedError('services/SetupCommandError')<{
17 readonly message: string;
18 readonly operation: 'setup' | 'uninstall';
19 readonly reasonCode: SetupFailureReasonCode;
20 readonly cause?: unknown;
17 -}> {}
21 +}> {
22 + get [Runtime.errorReported]() {
23 + return false;
24 + }
25 +
26 + get [Runtime.errorExitCode]() {
27 + return 1;
28 + }
29 +}
ts/packages/cli/test/__utils__/exit-code.ts new
+17
@@ -0,0 +1,17 @@
1 +import { Runtime, type Exit } from 'effect';
2 +
3 +/**
4 + * The code the CLI process exits with for `exit`, as `Runtime.defaultTeardown` (the teardown
5 + * `BunRuntime.runMain` runs) picks it: 0 on success, 130 on interruption alone, otherwise the
6 + * failure's `[Runtime.errorExitCode]`, or 1 without one.
7 + */
8 +export const exitCodeOf = (exit: Exit.Exit<unknown, unknown>): number => {
9 + let code: number | undefined;
10 + Runtime.defaultTeardown(exit, exitCode => {
11 + code = exitCode;
12 + });
13 + if (code === undefined) {
14 + throw new Error('Runtime.defaultTeardown did not report an exit code.');
15 + }
16 + return code;
17 +};
ts/packages/cli/test/__utils__/layers/agents.ts
-5
@@ -121,11 +121,6 @@ export const AgentHandlerTest = (fixture: AgentHandlerFixture = {}) => {
121 execPath: `${homedir}/composio`,
122 platform: 'darwin',
123 arch: 'arm64',
124 - // Agent handler tests read the exit code off the real process.
125 - setExitCode: code =>
126 - Effect.sync(() => {
127 - process.exitCode = code;
128 - }),
124 })
125 ),
126 ConfigProvider.layer(hostOnlyEnvConfigProvider)
ts/packages/cli/test/__utils__/layers/auth-configs.ts
+3 -7
@@ -5,7 +5,6 @@ import {
5 } from 'src/services/composio-clients';
6 import { TerminalUI } from 'src/services/terminal-ui';
7 import * as MockConsole from '../services/mock-console';
8 -import { recordingNodeProcess } from '../services/node-process-test';
8 import { makeToolkitsRepositoryStub } from '../services/toolkits-repository-stub';
9 import {
10 authConfigRepositoryMethods,
@@ -24,13 +23,11 @@ export interface AuthConfigsHandlerFixture {
23
24 /**
25 * What an `auth-configs` handler needs without argv or `TestLive`: a headless terminal whose
27 - * stdout payloads land in `outputs` (decoration goes to `MockConsole`), a `NodeProcess` that
28 - * records the exit code, and a repository serving only the auth-config methods. Any other
29 - * repository method dies.
26 + * stdout payloads land in `outputs` (decoration goes to `MockConsole`), and a repository
27 + * serving only the auth-config methods. Any other repository method dies.
28 */
29 export const AuthConfigsHandlerTest = (fixture: AuthConfigsHandlerFixture = {}) => {
30 const outputs: Array<string> = [];
33 - const proc = recordingNodeProcess();
31 const layer = Layer.mergeAll(
32 Layer.effect(Console.Console, MockConsole.make),
33 Layer.succeed(
@@ -43,7 +40,6 @@ export const AuthConfigsHandlerTest = (fixture: AuthConfigsHandlerFixture = {})
40 }),
41 })
42 ),
46 - proc.layer,
43 Layer.succeed(
44 ComposioToolkitsRepository,
45 makeToolkitsRepositoryStub({
@@ -54,5 +50,5 @@ export const AuthConfigsHandlerTest = (fixture: AuthConfigsHandlerFixture = {})
50 })
51 )
52 );
57 - return { layer, outputs, exitCode: proc.exitCode };
53 + return { layer, outputs };
54 };
ts/packages/cli/test/__utils__/services/node-process-test.ts deleted
-24
@@ -1,24 +0,0 @@
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
@@ -424,11 +424,6 @@ export const TestLayer = (input?: TestLiveInput) =>
424 execPath: input?.execPath ? path.resolve(cwd, input.execPath) : path.join(cwd, 'composio'),
425 platform: 'darwin',
426 arch: 'arm64',
427 - // Command tests read the exit code off the real process.
428 - setExitCode: code =>
429 - Effect.sync(() => {
430 - process.exitCode = code;
431 - }),
427 })
428 );
429
ts/packages/cli/test/src/analytics.events.test.ts
+21
@@ -37,6 +37,7 @@ import {
37 DEFAULT_CLI_INVOCATION_ORIGIN,
38 type CliInvocationContext,
39 } from 'src/services/runtime-cli-context';
40 +import { ChildProcessExited } from 'src/effects/child-process-exited';
41 import { SetupCommandError } from 'src/services/setup-command-error';
42 import { ToolInputValidationError } from 'src/services/tool-input-validation';
43 import { resolveInstalledCliVersion } from 'src/services/run-companion-modules';
@@ -441,6 +442,26 @@ describe('CLI analytics setup runtime-context events', () => {
442 ).not.toHaveProperty('failure_reason_code');
443 });
444
445 + it('records a run whose child exited non-zero as failed with reason child_exit', () => {
446 + const context = createCliCommandTelemetryContext(
447 + ['bun', 'composio', 'run', 'process.exit(3)'],
448 + APP_VERSION,
449 + { stdoutIsTTY: false, stderrIsTTY: false },
450 + CLI_INVOCATION
451 + );
452 +
453 + const event = getPrimaryLifecycleFailedEvent(context, new ChildProcessExited({ code: 3 }));
454 +
455 + expect(event?.name).toBe(CLI_ANALYTICS_EVENTS.CLI_RUN_FAILED);
456 + expect(event?.properties).toMatchObject({
457 + error_name: 'effects/ChildProcessExited',
458 + failure_reason_code: 'child_exit',
459 + });
460 + expect(
461 + getPrimaryLifecycleFailedEvent(context, new Error('boom'))?.properties
462 + ).not.toHaveProperty('failure_reason_code');
463 + });
464 +
465 it('tracks an unsupported host with a normalized reason code', () => {
466 expect(
467 getSetupHostDetectedEvent({
ts/packages/cli/test/src/cli-main.report-unreported-cause.test.ts new
+62
@@ -0,0 +1,62 @@
1 +import { describe, expect, it } from '@effect/vitest';
2 +import { Cause, Console, Effect, Exit, Layer } from 'effect';
3 +import * as BunFileSystem from '@effect/platform-bun/BunFileSystem';
4 +import * as BunPath from '@effect/platform-bun/BunPath';
5 +import { reportUnreportedCause } from 'src/cli-main';
6 +import { ReportedFailure } from 'src/effects/report-failure';
7 +import { MockConsole } from 'test/__utils__';
8 +import { exitCodeOf } from 'test/__utils__/exit-code';
9 +import { TerminalUITest } from 'test/__utils__/services/terminal-ui-test';
10 +
11 +// A fresh console per test, so one test's output never shows up in another's lines.
12 +const TestLayer = Layer.mergeAll(
13 + Layer.effect(Console.Console, MockConsole.make),
14 + TerminalUITest,
15 + BunFileSystem.layer,
16 + BunPath.layer
17 +);
18 +
19 +const report = (cause: Cause.Cause<unknown>) =>
20 + Effect.gen(function* () {
21 + const exit = yield* Effect.exit(reportUnreportedCause(cause));
22 + const stderr = yield* MockConsole.getLines({ stream: 'stderr' });
23 + return { exit, stderr };
24 + }).pipe(Effect.provide(TestLayer));
25 +
26 +const failureOf = (exit: Exit.Exit<unknown, unknown>) =>
27 + Exit.isFailure(exit) ? Cause.squash(exit.cause) : undefined;
28 +
29 +describe('reportUnreportedCause', () => {
30 + it.effect('[Given] an interruption alone [Then] it stays an interruption and exits 130', () =>
31 + Effect.gen(function* () {
32 + const { exit, stderr } = yield* report(Cause.interrupt());
33 +
34 + expect(Exit.hasInterrupts(exit)).toBe(true);
35 + expect(exitCodeOf(exit)).toBe(130);
36 + expect(stderr).toEqual([]);
37 + })
38 + );
39 +
40 + it.effect('[Given] a failure already on screen [Then] it is re-failed without printing', () =>
41 + Effect.gen(function* () {
42 + const failure = new ReportedFailure({ message: 'already shown' });
43 +
44 + const { exit, stderr } = yield* report(Cause.fail(failure));
45 +
46 + expect(failureOf(exit)).toBe(failure);
47 + expect(exitCodeOf(exit)).toBe(1);
48 + expect(stderr).toEqual([]);
49 + })
50 + );
51 +
52 + it.effect('[Given] an unreported defect [Then] it is printed once and exits 1', () =>
53 + Effect.gen(function* () {
54 + const { exit, stderr } = yield* report(Cause.die(new Error('boom')));
55 +
56 + expect(failureOf(exit)).toBeInstanceOf(ReportedFailure);
57 + expect(exitCodeOf(exit)).toBe(1);
58 + expect(stderr).toHaveLength(1);
59 + expect(stderr[0]).toContain('boom');
60 + })
61 + );
62 +});
ts/packages/cli/test/src/cli-main.test.ts
+22
@@ -579,6 +579,28 @@ describe('reported tool execution failures', () => {
579 );
580 });
581
582 +describe('failures a command reports itself', () => {
583 + it(
584 + '[Given] a request failure the command reports [Then] prints it once, exits 1, and records the command as failed',
585 + () =>
586 + withHttpServer(
587 + (_req, res) => sendJson(res, 503, { error: { message: 'Service unavailable' } }),
588 + async baseUrl => {
589 + const result = await runCliAgainst(baseUrl, ['dev', 'toolkits', 'list'], {
590 + env: { COMPOSIO_CLI_TELEMETRY_DEBUG: '1' },
591 + });
592 +
593 + expect(result.status).toBe(1);
594 + expect(result.stdout).toBe('[]\n');
595 + expect(result.stderr).toContain('CLI_COMMAND_FAILED');
596 + expect(result.stderr).not.toContain('CLI_COMMAND_SUCCEEDED');
597 + expect(result.stderr).not.toContain('ReportedFailure');
598 + }
599 + ),
600 + 30_000
601 + );
602 +});
603 +
604 describe('account selection errors', () => {
605 it(
606 '[Given] an `--account` that matches no connected account [Then] prints the message as one line and exits 1',
ts/packages/cli/test/src/commands/agent/claim/agent.claim.cmd.test.ts
+3 -2
@@ -4,6 +4,7 @@ import { afterEach, vi } from 'vitest';
4 import { writeStoredAgentIdentity } from 'src/services/agents';
5 import { cli, MockConsole, TestLive } from 'test/__utils__';
6 import { agentsJsonResponse, makeAgentIdentity } from 'test/__utils__/models/agent';
7 +import { exitCodeOf } from 'test/__utils__/exit-code';
8
9 describe('CLI: composio agent claim', () => {
10 afterEach(() => {
@@ -46,11 +47,11 @@ describe('CLI: composio agent claim', () => {
47 Effect.gen(function* () {
48 const fetchSpy = vi.spyOn(globalThis, 'fetch');
49
49 - yield* cli(['agent', 'claim', 'boss@example.com']);
50 + const exit = yield* Effect.exit(cli(['agent', 'claim', 'boss@example.com']));
51 const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
52
53 expect(output).toContain('currently signed in to Composio as a regular user');
53 - expect(process.exitCode).toBe(1);
54 + expect(exitCodeOf(exit)).toBe(1);
55 expect(fetchSpy).not.toHaveBeenCalled();
56 })
57 );
ts/packages/cli/test/src/commands/agent/claim/agent.claim.handler.test.ts
+3 -2
@@ -6,6 +6,7 @@ import { writeStoredAgentIdentity } from 'src/services/agents';
6 import { MockConsole } from 'test/__utils__';
7 import { AgentHandlerTest } from 'test/__utils__/layers/agents';
8 import { agentsJsonResponse, makeAgentIdentity } from 'test/__utils__/models/agent';
9 +import { exitCodeOf } from 'test/__utils__/exit-code';
10
11 describe('runAgentClaim', () => {
12 afterEach(() => {
@@ -83,13 +84,13 @@ describe('runAgentClaim', () => {
84 return Effect.gen(function* () {
85 const fetchSpy = vi.spyOn(globalThis, 'fetch');
86
86 - yield* runAgentClaim({ email: 'boss@example.com' });
87 + const exit = yield* Effect.exit(runAgentClaim({ email: 'boss@example.com' }));
88
89 expect(yield* MockConsole.getLines({ stream: 'stderr', stripAnsi: true })).toEqual([
90 'No Composio agent identity is saved on this machine.',
91 expect.stringMatching(/^Next steps:\n/),
92 ]);
92 - expect(process.exitCode).toBe(1);
93 + expect(exitCodeOf(exit)).toBe(1);
94 expect(fetchSpy).not.toHaveBeenCalled();
95 expect(outputs).toEqual([]);
96 }).pipe(Effect.provide(layer));
ts/packages/cli/test/src/commands/agent/inbox/agent.inbox.handler.test.ts
+3 -2
@@ -6,6 +6,7 @@ import { writeStoredAgentIdentity } from 'src/services/agents';
6 import { MockConsole } from 'test/__utils__';
7 import { AgentHandlerTest } from 'test/__utils__/layers/agents';
8 import { agentsJsonResponse, makeAgentIdentity } from 'test/__utils__/models/agent';
9 +import { exitCodeOf } from 'test/__utils__/exit-code';
10
11 const inbox = {
12 count: 1,
@@ -59,13 +60,13 @@ describe('runAgentInbox', () => {
60 yield* writeStoredAgentIdentity(makeAgentIdentity());
61 const fetchSpy = vi.spyOn(globalThis, 'fetch');
62
62 - yield* runAgentInbox({ limit: 50 });
63 + const exit = yield* Effect.exit(runAgentInbox({ limit: 50 }));
64
65 expect(yield* MockConsole.getLines({ stream: 'stderr', stripAnsi: true })).toEqual([
66 'This CLI is currently signed in to Composio as a regular user, not an agent.',
67 expect.stringMatching(/^Next steps:\n/),
68 ]);
68 - expect(process.exitCode).toBe(1);
69 + expect(exitCodeOf(exit)).toBe(1);
70 expect(fetchSpy).not.toHaveBeenCalled();
71 expect(outputs).toEqual([]);
72 }).pipe(Effect.provide(layer));
ts/packages/cli/test/src/commands/agent/login/agent.login.cmd.test.ts
+5 -4
@@ -6,6 +6,7 @@ import { afterEach, vi } from 'vitest';
6 import { setupCacheDir } from 'src/effects/setup-cache-dir';
7 import { ComposioUserContext } from 'src/services/user-context';
8 import { cli, MockConsole, TestLive } from 'test/__utils__';
9 +import { exitCodeOf } from 'test/__utils__/exit-code';
10
11 const existingAgent = {
12 status: 'READY',
@@ -112,12 +113,12 @@ describe('CLI: composio agent login', () => {
113 jsonResponse({ ...existingAgent, status: 'PENDING', composio: undefined })
114 );
115
115 - yield* cli(['agent', 'login', 'cak_existing']);
116 + const exit = yield* Effect.exit(cli(['agent', 'login', 'cak_existing']));
117
118 const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
119 expect(output).toContain('Agent identity is not ready yet.');
120 expect(output).not.toContain('"logged_in":true');
120 - expect(process.exitCode).toBe(1);
121 + expect(exitCodeOf(exit)).toBe(1);
122 const ctx = yield* ComposioUserContext;
123 expect(Option.getOrUndefined(ctx.data.apiKey)).toBeUndefined();
124 })
@@ -129,12 +130,12 @@ describe('CLI: composio agent login', () => {
130 Effect.gen(function* () {
131 const fetchSpy = vi.spyOn(globalThis, 'fetch');
132
132 - yield* cli(['agent', 'login', 'cak_existing']);
133 + const exit = yield* Effect.exit(cli(['agent', 'login', 'cak_existing']));
134 const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
135
136 expect(output).toContain('currently signed in to Composio as a regular user');
137 expect(output).toContain('composio logout');
137 - expect(process.exitCode).toBe(1);
138 + expect(exitCodeOf(exit)).toBe(1);
139 expect(fetchSpy).not.toHaveBeenCalled();
140 })
141 );
ts/packages/cli/test/src/commands/agent/login/agent.login.handler.test.ts
+3 -3
@@ -6,6 +6,7 @@ import { readStoredAgentIdentity, writeStoredAgentIdentity } from 'src/services/
6 import { MockConsole } from 'test/__utils__';
7 import { AgentHandlerTest } from 'test/__utils__/layers/agents';
8 import { agentsJsonResponse, makeAgentIdentity } from 'test/__utils__/models/agent';
9 +import { exitCodeOf } from 'test/__utils__/exit-code';
10
11 describe('runAgentLogin', () => {
12 afterEach(() => {
@@ -59,7 +60,6 @@ describe('runAgentLogin', () => {
60 yield* runAgentLogin({ composioAgentKey: 'cak_test_agent' });
61
62 expect(logins).toEqual([{ apiKey: 'uak_agent', orgId: 'org_agent' }]);
62 - expect(process.exitCode).toBeUndefined();
63 }).pipe(Effect.provide(layer));
64 });
65
@@ -68,13 +68,13 @@ describe('runAgentLogin', () => {
68 return Effect.gen(function* () {
69 const fetchSpy = vi.spyOn(globalThis, 'fetch');
70
71 - yield* runAgentLogin({ composioAgentKey: 'cak_existing' });
71 + const exit = yield* Effect.exit(runAgentLogin({ composioAgentKey: 'cak_existing' }));
72
73 expect(yield* MockConsole.getLines({ stream: 'stderr', stripAnsi: true })).toEqual([
74 'This CLI is currently signed in to Composio as a regular user, not an agent.',
75 expect.stringMatching(/^Next steps:\n/),
76 ]);
77 - expect(process.exitCode).toBe(1);
77 + expect(exitCodeOf(exit)).toBe(1);
78 expect(fetchSpy).not.toHaveBeenCalled();
79 expect(logins).toEqual([]);
80 expect(outputs).toEqual([]);
ts/packages/cli/test/src/commands/agent/signup/agent.signup.cmd.test.ts
+3 -2
@@ -8,6 +8,7 @@ import { setupCacheDir } from 'src/effects/setup-cache-dir';
8 import { ComposioUserContext } from 'src/services/user-context';
9 import { cli, MockConsole, TestLive } from 'test/__utils__';
10 import { agentsJsonResponse, makeAgentIdentity } from 'test/__utils__/models/agent';
11 +import { exitCodeOf } from 'test/__utils__/exit-code';
12
13 describe('CLI: composio agent signup', () => {
14 afterEach(() => {
@@ -86,12 +87,12 @@ describe('CLI: composio agent signup', () => {
87 layer(TestLive({ fixture: 'user-config-example' }))(it => {
88 it.effect('agent signup shows a soft auth warning when signed in as a human user', () =>
89 Effect.gen(function* () {
89 - yield* cli(['agent', 'signup']);
90 + const exit = yield* Effect.exit(cli(['agent', 'signup']));
91 const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
92
93 expect(output).toContain('currently signed in to Composio as a regular user');
94 expect(output).toContain('composio signup');
94 - expect(process.exitCode).toBe(1);
95 + expect(exitCodeOf(exit)).toBe(1);
96 })
97 );
98 });
ts/packages/cli/test/src/commands/agent/signup/agent.signup.handler.test.ts
+3 -2
@@ -9,6 +9,7 @@ import { readStoredAgentIdentity, writeStoredAgentIdentity } from 'src/services/
9 import { MockConsole } from 'test/__utils__';
10 import { AgentHandlerTest } from 'test/__utils__/layers/agents';
11 import { agentsJsonResponse, makeAgentIdentity } from 'test/__utils__/models/agent';
12 +import { exitCodeOf } from 'test/__utils__/exit-code';
13
14 const params = (overrides: Partial<AgentSignupParams> = {}): AgentSignupParams => ({
15 noWait: false,
@@ -199,13 +200,13 @@ describe('runAgentSignup', () => {
200 return Effect.gen(function* () {
201 const fetchSpy = vi.spyOn(globalThis, 'fetch');
202
202 - yield* runAgentSignup(params());
203 + const exit = yield* Effect.exit(runAgentSignup(params()));
204
205 expect(yield* MockConsole.getLines({ stream: 'stderr', stripAnsi: true })).toEqual([
206 'This CLI is currently signed in to Composio as a regular user, not an agent.',
207 expect.stringMatching(/^Next steps:\n/),
208 ]);
208 - expect(process.exitCode).toBe(1);
209 + expect(exitCodeOf(exit)).toBe(1);
210 expect(fetchSpy).not.toHaveBeenCalled();
211 expect(logins).toEqual([]);
212 expect(outputs).toEqual([]);
ts/packages/cli/test/src/commands/agent/whoami/agent.whoami.cmd.test.ts
+3 -2
@@ -4,6 +4,7 @@ import { afterEach, vi } from 'vitest';
4 import { writeStoredAgentIdentity } from 'src/services/agents';
5 import { cli, MockConsole, TestLive } from 'test/__utils__';
6 import { agentsJsonResponse, makeAgentIdentity } from 'test/__utils__/models/agent';
7 +import { exitCodeOf } from 'test/__utils__/exit-code';
8
9 describe('CLI: composio agent whoami', () => {
10 afterEach(() => {
@@ -36,12 +37,12 @@ describe('CLI: composio agent whoami', () => {
37 layer(TestLive({ fixture: 'user-config-example' }))(it => {
38 it.effect('[Given] the CLI is signed in as a human user [Then] shows a soft auth warning', () =>
39 Effect.gen(function* () {
39 - yield* cli(['agent', 'whoami']);
40 + const exit = yield* Effect.exit(cli(['agent', 'whoami']));
41 const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
42
43 expect(output).toContain('currently signed in to Composio as a regular user');
44 expect(output).toContain('composio agent login <composio_agent_key>');
44 - expect(process.exitCode).toBe(1);
45 + expect(exitCodeOf(exit)).toBe(1);
46 })
47 );
48 });
ts/packages/cli/test/src/commands/agent/whoami/agent.whoami.handler.test.ts
+3 -3
@@ -6,6 +6,7 @@ import { readStoredAgentIdentity, writeStoredAgentIdentity } from 'src/services/
6 import { MockConsole } from 'test/__utils__';
7 import { AgentHandlerTest } from 'test/__utils__/layers/agents';
8 import { agentsJsonResponse, makeAgentIdentity } from 'test/__utils__/models/agent';
9 +import { exitCodeOf } from 'test/__utils__/exit-code';
10
11 const decoration = Effect.map(MockConsole.getLines({ stripAnsi: true }), lines => lines.join('\n'));
12
@@ -65,7 +66,6 @@ describe('runAgentWhoami', () => {
66 force: false,
67 },
68 ]);
68 - expect(process.exitCode).toBeUndefined();
69 }).pipe(Effect.provide(layer));
70 }
71 );
@@ -124,12 +124,12 @@ describe('runAgentWhoami', () => {
124 yield* Effect.forEach(Option.toArray(stored), writeStoredAgentIdentity);
125 const fetchSpy = vi.spyOn(globalThis, 'fetch');
126
127 - yield* runAgentWhoami();
127 + const exit = yield* Effect.exit(runAgentWhoami());
128
129 // Plain lines on stderr: a headless terminal drops `ui.log.*` decoration.
130 const stderr = yield* MockConsole.getLines({ stream: 'stderr', stripAnsi: true });
131 expect(stderr).toEqual([message, expect.stringMatching(/^Next steps:\n/)]);
132 - expect(process.exitCode).toBe(1);
132 + expect(exitCodeOf(exit)).toBe(1);
133 expect(fetchSpy).not.toHaveBeenCalled();
134 expect(outputs).toEqual([]);
135 }).pipe(Effect.provide(layer));
ts/packages/cli/test/src/commands/auth-configs/create/auth-configs.create.handler.test.ts
+6 -7
@@ -8,6 +8,7 @@ import {
8 } from 'src/commands/auth-configs/create/auth-configs.create.handler';
9 import { isUsageFailure } from 'src/commands/errors';
10 import { MockConsole } from 'test/__utils__';
11 +import { exitCodeOf } from 'test/__utils__/exit-code';
12 import { AuthConfigsHandlerTest } from 'test/__utils__/layers/auth-configs';
13 import { notFoundError } from 'test/__utils__/layers/not-found';
14
@@ -108,7 +109,7 @@ describe('buildAuthConfigCreateRequest', () => {
109
110 describe('runAuthConfigsCreate', () => {
111 it.effect('[Given] a successful create [Then] prints the API response JSON to stdout', () => {
111 - const { layer, outputs, exitCode } = AuthConfigsHandlerTest({
112 + const { layer, outputs } = AuthConfigsHandlerTest({
113 authConfigsData: { createResponse },
114 });
115 return Effect.gen(function* () {
@@ -118,7 +119,6 @@ describe('runAuthConfigsCreate', () => {
119 const decoration = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
120 expect(decoration).toContain('Auth config created.');
121 expect(decoration).toContain('[New Auth Config]');
121 - expect(exitCode()).toBeUndefined();
122 }).pipe(Effect.provide(layer));
123 });
124
@@ -128,7 +128,7 @@ describe('runAuthConfigsCreate', () => {
128 ])(
129 '[Given] $name in --custom-credentials [Then] fails with a usage error before any request',
130 ({ customCredentials }) => {
131 - const { layer, outputs, exitCode } = AuthConfigsHandlerTest({
131 + const { layer, outputs } = AuthConfigsHandlerTest({
132 repository: { createAuthConfig: () => Effect.die('createAuthConfig must not be called') },
133 });
134 return Effect.gen(function* () {
@@ -150,19 +150,18 @@ describe('runAuthConfigsCreate', () => {
150 expect(isUsageFailure(failure)).toBe(true);
151 expect(yield* MockConsole.getLines()).toEqual([]);
152 expect(outputs).toEqual([]);
153 - expect(exitCode()).toBeUndefined();
153 }).pipe(Effect.provide(layer));
154 }
155 );
156
157 it.effect('[Given] the API rejects the create [Then] hints at the toolkit and exits 1', () => {
159 - const { layer, outputs, exitCode } = AuthConfigsHandlerTest({
158 + const { layer, outputs } = AuthConfigsHandlerTest({
159 repository: {
160 createAuthConfig: () => Effect.fail(notFoundError('Toolkit not found')),
161 },
162 });
163 return Effect.gen(function* () {
165 - yield* runAuthConfigsCreate({ ...params, toolkit: 'nope' });
164 + const exit = yield* Effect.exit(runAuthConfigsCreate({ ...params, toolkit: 'nope' }));
165
166 const stderr = (yield* MockConsole.getLines({ stream: 'stderr', stripAnsi: true })).join(
167 '\n'
@@ -172,7 +171,7 @@ describe('runAuthConfigsCreate', () => {
171 'Check available auth schemes for "nope":\n> composio dev toolkits info "nope"'
172 );
173 expect(outputs).toEqual([]);
175 - expect(exitCode()).toBe(1);
174 + expect(exitCodeOf(exit)).toBe(1);
175 }).pipe(Effect.provide(layer));
176 });
177 });
ts/packages/cli/test/src/commands/auth-configs/info/auth-configs.info.cmd.test.ts
+3 -1
@@ -1,6 +1,7 @@
1 import { describe, expect, layer } from '@effect/vitest';
2 import { ConfigProvider, Effect } from 'effect';
3 import { cli, TestLive, MockConsole } from 'test/__utils__';
4 +import { exitCodeOf } from 'test/__utils__/exit-code';
5 import type { TestLiveInput } from 'test/__utils__/services/test-layer';
6 import type { AuthConfigItem } from 'src/models/auth-configs';
7
@@ -72,12 +73,13 @@ describe('CLI: composio dev auth-configs info', () => {
73 it => {
74 it.effect('shows not found error', () =>
75 Effect.gen(function* () {
75 - yield* cli(['dev', 'auth-configs', 'info', 'ac_nonexistent']);
76 + const exit = yield* Effect.exit(cli(['dev', 'auth-configs', 'info', 'ac_nonexistent']));
77 const lines = yield* MockConsole.getLines({ stripAnsi: true });
78 const output = lines.join('\n');
79
80 expect(output).toContain('not found');
81 expect(output).toContain('composio dev auth-configs list');
82 + expect(exitCodeOf(exit)).toBe(1);
83 })
84 );
85 }
ts/packages/cli/test/src/commands/auth-configs/info/auth-configs.info.handler.test.ts
+6 -7
@@ -3,6 +3,7 @@ import { Effect, Option } from 'effect';
3 import { runAuthConfigsInfo } from 'src/commands/auth-configs/info/auth-configs.info.handler';
4 import { isUsageFailure } from 'src/commands/errors';
5 import { MockConsole } from 'test/__utils__';
6 +import { exitCodeOf } from 'test/__utils__/exit-code';
7 import { AuthConfigsHandlerTest } from 'test/__utils__/layers/auth-configs';
8 import { makeAuthConfigItem } from 'test/__utils__/models/auth-configs';
9
@@ -10,7 +11,7 @@ const gmail = makeAuthConfigItem();
11
12 describe('runAuthConfigsInfo', () => {
13 it.effect('[Given] a known ID [Then] prints the auth config JSON to stdout', () => {
13 - const { layer, outputs, exitCode } = AuthConfigsHandlerTest({
14 + const { layer, outputs } = AuthConfigsHandlerTest({
15 authConfigsData: { items: [gmail] },
16 });
17 return Effect.gen(function* () {
@@ -20,13 +21,12 @@ describe('runAuthConfigsInfo', () => {
21 const decoration = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
22 expect(decoration).toContain('[Auth Config: Gmail Default]');
23 expect(decoration).toContain('Tool Router: Enabled');
23 - expect(exitCode()).toBeUndefined();
24 }).pipe(Effect.provide(layer));
25 });
26
27 it.effect('[Given] no ID [Then] fails with a usage error before any request', () => {
28 // The stub repository dies on any call, so reaching the API fails the test.
29 - const { layer, outputs, exitCode } = AuthConfigsHandlerTest({
29 + const { layer, outputs } = AuthConfigsHandlerTest({
30 repository: { getAuthConfig: () => Effect.die('getAuthConfig must not be called') },
31 });
32 return Effect.gen(function* () {
@@ -44,18 +44,17 @@ describe('runAuthConfigsInfo', () => {
44 expect(isUsageFailure(failure)).toBe(true);
45 expect(yield* MockConsole.getLines()).toEqual([]);
46 expect(outputs).toEqual([]);
47 - expect(exitCode()).toBeUndefined();
47 }).pipe(Effect.provide(layer));
48 });
49
50 it.effect(
51 '[Given] an unknown ID [Then] reports the API error with the list hint and exits 1',
52 () => {
54 - const { layer, outputs, exitCode } = AuthConfigsHandlerTest({
53 + const { layer, outputs } = AuthConfigsHandlerTest({
54 authConfigsData: { items: [gmail] },
55 });
56 return Effect.gen(function* () {
58 - yield* runAuthConfigsInfo({ id: Option.some('ac_missing') });
57 + const exit = yield* Effect.exit(runAuthConfigsInfo({ id: Option.some('ac_missing') }));
58
59 const stderr = (yield* MockConsole.getLines({ stream: 'stderr', stripAnsi: true })).join(
60 '\n'
@@ -65,7 +64,7 @@ describe('runAuthConfigsInfo', () => {
64 'Browse available auth configs:\n> composio dev auth-configs list'
65 );
66 expect(outputs).toEqual([]);
68 - expect(exitCode()).toBe(1);
67 + expect(exitCodeOf(exit)).toBe(1);
68 }).pipe(Effect.provide(layer));
69 }
70 );
ts/packages/cli/test/src/commands/auth-configs/list/auth-configs.list.handler.test.ts
+2 -4
@@ -24,7 +24,7 @@ const params = {
24
25 describe('runAuthConfigsList', () => {
26 it.effect('[Given] auth configs [Then] prints their summary JSON to stdout', () => {
27 - const { layer, outputs, exitCode } = AuthConfigsHandlerTest({
27 + const { layer, outputs } = AuthConfigsHandlerTest({
28 authConfigsData: { items: [gmail, slack] },
29 });
30 return Effect.gen(function* () {
@@ -59,7 +59,6 @@ describe('runAuthConfigsList', () => {
59 expect(decoration).toContain(
60 `To view details of an auth config:\n> composio dev auth-configs info "${redact({ value: 'ac_gmail_default', prefix: 'ac_' })}"`
61 );
62 - expect(exitCode()).toBeUndefined();
62 }).pipe(Effect.provide(layer));
63 });
64
@@ -102,7 +101,7 @@ describe('runAuthConfigsList', () => {
101 ])(
102 '[Given] no matches and $name [Then] warns and prints nothing to stdout',
103 ({ toolkits, warning }) => {
105 - const { layer, outputs, exitCode } = AuthConfigsHandlerTest({
104 + const { layer, outputs } = AuthConfigsHandlerTest({
105 authConfigsData: { items: [gmail] },
106 });
107 return Effect.gen(function* () {
@@ -112,7 +111,6 @@ describe('runAuthConfigsList', () => {
111 warning,
112 ]);
113 expect(outputs).toEqual([]);
115 - expect(exitCode()).toBeUndefined();
114 }).pipe(Effect.provide(layer));
115 }
116 );
ts/packages/cli/test/src/commands/connected-accounts/info/connected-accounts.info.cmd.test.ts
+5 -1
@@ -1,6 +1,7 @@
1 import { describe, expect, layer } from '@effect/vitest';
2 import { ConfigProvider, Effect } from 'effect';
3 import { cli, TestLive, MockConsole } from 'test/__utils__';
4 +import { exitCodeOf } from 'test/__utils__/exit-code';
5 import type { TestLiveInput } from 'test/__utils__/services/test-layer';
6 import type { ConnectedAccountItem } from 'src/models/connected-accounts';
7
@@ -56,12 +57,15 @@ describe('CLI: composio dev connected-accounts info', () => {
57 it => {
58 it.effect('shows error for nonexistent account', () =>
59 Effect.gen(function* () {
59 - yield* cli(['dev', 'connected-accounts', 'info', 'con_nonexistent']);
60 + const exit = yield* Effect.exit(
61 + cli(['dev', 'connected-accounts', 'info', 'con_nonexistent'])
62 + );
63 const lines = yield* MockConsole.getLines({ stripAnsi: true });
64 const output = lines.join('\n');
65
66 expect(output).toContain('not found');
67 expect(output).toContain('composio dev connected-accounts list');
68 + expect(exitCodeOf(exit)).toBe(1);
69 })
70 );
71 }
ts/packages/cli/test/src/commands/connected-accounts/info/connected-accounts.info.handler.test.ts
+10 -26
@@ -4,10 +4,10 @@ import { runConnectedAccountsInfo } from 'src/commands/connected-accounts/info/c
4 import { MISSING_ID_MESSAGE, missingIdHint } from 'src/commands/connected-accounts/format';
5 import { isUsageFailure } from 'src/commands/errors';
6 import type { ConnectedAccountItem } from 'src/models/connected-accounts';
7 -import { NodeProcess } from 'src/services/node-process';
7 import { TerminalUI } from 'src/services/terminal-ui';
8 import { redact } from 'src/ui/redact';
9 import { ConnectedAccountsTest, MockConsole } from 'test/__utils__';
10 +import { exitCodeOf } from 'test/__utils__/exit-code';
11 import { terminalUITestImpl } from 'test/__utils__/services/terminal-ui-test';
12
13 const EXPIRED_ACCOUNT: ConnectedAccountItem = {
@@ -31,12 +31,11 @@ const EXPIRED_ACCOUNT: ConnectedAccountItem = {
31 };
32
33 /**
34 - * What `runConnectedAccountsInfo` reads: the connected-account repository, a headless terminal
35 - * whose stdout data lands in `outputs`, and a process whose exit codes land in `exitCodes`.
34 + * What `runConnectedAccountsInfo` reads: the connected-account repository and a headless
35 + * terminal whose stdout data lands in `outputs`.
36 */
37 const infoTest = (items: ReadonlyArray<ConnectedAccountItem> = [EXPIRED_ACCOUNT]) => {
38 const outputs: Array<string> = [];
39 - const exitCodes: Array<number> = [];
39 const layer = Layer.mergeAll(
40 Layer.effect(Console.Console, MockConsole.make),
41 Layer.succeed(
@@ -49,22 +48,9 @@ const infoTest = (items: ReadonlyArray<ConnectedAccountItem> = [EXPIRED_ACCOUNT]
48 }),
49 })
50 ),
52 - ConnectedAccountsTest({ connectedAccountsData: { items: [...items] } }),
53 - Layer.succeed(
54 - NodeProcess,
55 - NodeProcess.of({
56 - cwd: '/tmp',
57 - execPath: '/tmp/composio',
58 - platform: 'darwin',
59 - arch: 'arm64',
60 - setExitCode: code =>
61 - Effect.sync(() => {
62 - exitCodes.push(code);
63 - }),
64 - })
65 - )
51 + ConnectedAccountsTest({ connectedAccountsData: { items: [...items] } })
52 );
67 - return { layer, outputs, exitCodes };
53 + return { layer, outputs };
54 };
55
56 const stdoutLines = MockConsole.getLines({ stream: 'stdout', stripAnsi: true });
@@ -72,12 +58,11 @@ const stderrLines = MockConsole.getLines({ stream: 'stderr', stripAnsi: true });
58
59 describe('runConnectedAccountsInfo', () => {
60 it.effect('[Given] an existing id [Then] prints the whole account as JSON on stdout', () => {
75 - const { layer, outputs, exitCodes } = infoTest();
61 + const { layer, outputs } = infoTest();
62 return Effect.gen(function* () {
63 yield* runConnectedAccountsInfo({ id: Option.some('con_github_expired') });
64
65 expect(outputs.map(output => JSON.parse(output))).toEqual([EXPIRED_ACCOUNT]);
80 - expect(exitCodes).toEqual([]);
66 }).pipe(Effect.provide(layer));
67 });
68
@@ -106,7 +91,7 @@ describe('runConnectedAccountsInfo', () => {
91 );
92
93 it.effect('[Given] no id [Then] fails with a usage error before any request', () => {
109 - const { layer, outputs, exitCodes } = infoTest();
94 + const { layer, outputs } = infoTest();
95 return Effect.gen(function* () {
96 const failure = yield* runConnectedAccountsInfo({ id: Option.none() }).pipe(Effect.flip);
97
@@ -121,20 +106,19 @@ describe('runConnectedAccountsInfo', () => {
106 expect(yield* stderrLines).toEqual([]);
107 expect(yield* stdoutLines).toEqual([]);
108 expect(outputs).toEqual([]);
124 - expect(exitCodes).toEqual([]);
109 }).pipe(Effect.provide(layer));
110 });
111
112 it.effect('[Given] an unknown id [Then] reports it, prints no data, and exits 1', () => {
129 - const { layer, outputs, exitCodes } = infoTest();
113 + const { layer, outputs } = infoTest();
114 return Effect.gen(function* () {
131 - yield* runConnectedAccountsInfo({ id: Option.some('con_missing') });
115 + const exit = yield* Effect.exit(runConnectedAccountsInfo({ id: Option.some('con_missing') }));
116 const stderr = (yield* stderrLines).join('\n');
117
118 expect(stderr).toContain('Connected account "con_missing" not found.');
119 expect(stderr).toContain('composio dev connected-accounts list');
120 expect(outputs).toEqual([]);
137 - expect(exitCodes).toEqual([1]);
121 + expect(exitCodeOf(exit)).toBe(1);
122 }).pipe(Effect.provide(layer));
123 });
124 });
ts/packages/cli/test/src/commands/connected-accounts/link/connected-accounts.link.client.cmd.test.ts
+20 -11
@@ -1,6 +1,7 @@
1 import { describe, expect, layer } from '@effect/vitest';
2 import { ConfigProvider, Effect } from 'effect';
3 import { cli, MockConsole, TestLive } from 'test/__utils__';
4 +import { exitCodeOf } from 'test/__utils__/exit-code';
5 import { routeRequests, stubClientResources } from 'test/__utils__/services/stub-composio-client';
6
7 const testLayer = TestLive({
@@ -39,9 +40,13 @@ describe('CLI: composio link over the API client', () => {
40 })
41 )
42 );
42 - yield* cli(['link', 'gmail', '--no-wait']).pipe(Effect.provide(stub.layer));
43 + const exit = yield* Effect.exit(
44 + cli(['link', 'gmail', '--no-wait']).pipe(Effect.provide(stub.layer))
45 + );
46 const lines = yield* MockConsole.getLines({ stripAnsi: true });
47
48 + expect(exitCodeOf(exit)).toBe(1);
49 +
50 expect(lines).toEqual([
51 'Toolkit gmail is disabled for this project',
52 'Browse available toolkits:\n> composio dev toolkits list',
@@ -61,18 +66,22 @@ describe('CLI: composio link over the API client', () => {
66 const stub = stubClientResources(['link'], () =>
67 rejection(404, 'Auth config ac_missing not found', 'AuthConfig_NotFound')
68 );
64 - yield* cli([
65 - 'dev',
66 - 'connected-accounts',
67 - 'link',
68 - '--auth-config',
69 - 'ac_missing',
70 - '--user-id',
71 - 'user_1',
72 - '--no-wait',
73 - ]).pipe(Effect.provide(stub.layer));
69 + const exit = yield* Effect.exit(
70 + cli([
71 + 'dev',
72 + 'connected-accounts',
73 + 'link',
74 + '--auth-config',
75 + 'ac_missing',
76 + '--user-id',
77 + 'user_1',
78 + '--no-wait',
79 + ]).pipe(Effect.provide(stub.layer))
80 + );
81 const lines = yield* MockConsole.getLines({ stripAnsi: true });
82
83 + expect(exitCodeOf(exit)).toBe(1);
84 +
85 expect(lines).toEqual([
86 'Auth config ac_missing not found',
87 'Browse available auth configs:\n> composio dev auth-configs list',
ts/packages/cli/test/src/commands/connected-accounts/link/connected-accounts.link.cmd.test.ts
+9 -4
@@ -2,6 +2,7 @@ import { BadRequestError } from '@composio/client/effect';
2 import { describe, expect, layer } from '@effect/vitest';
3 import { ConfigProvider, Console, Effect } from 'effect';
4 import { cli, TestLive, MockConsole } from 'test/__utils__';
5 +import { exitCodeOf } from 'test/__utils__/exit-code';
6 import { makeSessionInfo } from 'test/__utils__/models/account';
7 import type { MockRequestScope } from 'test/__utils__/services/test-layer';
8 import type { TestLiveInput } from 'test/__utils__/services/test-layer';
@@ -472,13 +473,15 @@ describe('CLI: composio dev connected-accounts link', () => {
473 Effect.gen(function* () {
474 // Redirected streams, as under a script: only plain stderr lines and stdout data show.
475 const terminal = redirectedTerminalUI();
475 - yield* cli(['link', 'gmail']).pipe(Effect.provide(terminal.layer));
476 + const exit = yield* Effect.exit(
477 + cli(['link', 'gmail']).pipe(Effect.provide(terminal.layer))
478 + );
479
480 expect(terminal.stderr()).toBe(
481 'The link response from the API is missing `connected_account_id` or `redirect_url`.\n'
482 );
483 expect(terminal.stdout()).toBe('');
481 - expect(process.exitCode).toBe(1);
484 + expect(exitCodeOf(exit)).toBe(1);
485 })
486 );
487 });
@@ -562,10 +565,11 @@ describe('CLI: composio dev connected-accounts link', () => {
565 it => {
566 it.effect('fails locally and tells the user to pass --alias', () =>
567 Effect.gen(function* () {
565 - yield* cli(['link', 'gmail']);
568 + const exit = yield* Effect.exit(cli(['link', 'gmail']));
569 const lines = yield* MockConsole.getLines({ stripAnsi: true });
570 const output = lines.join('\n');
571
572 + expect(exitCodeOf(exit)).toBe(1);
573 expect(output).toContain('Pass --alias to create another one');
574 expect(output).toContain('con_test_link');
575 expect(output).not.toContain('"status"');
@@ -586,10 +590,11 @@ describe('CLI: composio dev connected-accounts link', () => {
590 )('[Given] a duplicate alias [Then] link explains how to use the existing account', it => {
591 it.effect('detects the exact existing alias before creating a link', () =>
592 Effect.gen(function* () {
589 - yield* cli(['link', 'gmail', '--alias', 'work']);
593 + const exit = yield* Effect.exit(cli(['link', 'gmail', '--alias', 'work']));
594 const lines = yield* MockConsole.getLines({ stripAnsi: true });
595 const output = lines.join('\n');
596
597 + expect(exitCodeOf(exit)).toBe(1);
598 expect(output).toContain('Alias "work" is already in use');
599 expect(output).toContain('composio execute <TOOL_SLUG> --account work');
600 expect(output).toContain('composio connections list --toolkit gmail');
ts/packages/cli/test/src/commands/connected-accounts/link/connected-accounts.link.handler.test.ts
+49 -38
@@ -31,6 +31,7 @@ import type { ProjectKeys } from 'src/models/project-keys';
31 import { ComposioCliUserConfig } from 'src/services/cli-user-config';
32 import { ComposioClientSingleton } from 'src/services/composio-clients';
33 import { NodeOs } from 'src/services/node-os';
34 +import { NodeProcess } from 'src/services/node-process';
35 import type { TerminalUI } from 'src/services/terminal-ui';
36 import { ProjectContext } from 'src/services/project-context';
37 import { ComposioUserContext } from 'src/services/user-context';
@@ -42,7 +43,7 @@ import {
43 } from 'test/__utils__/layers/connected-accounts';
44 import { hostOnlyEnvConfigProvider } from 'test/__utils__/live-env-config-provider';
45 import { makeOrgProject } from 'test/__utils__/models/account';
45 -import { recordingNodeProcess } from 'test/__utils__/services/node-process-test';
46 +import { exitCodeOf } from 'test/__utils__/exit-code';
47 import { redirectedTerminalUI } from 'test/__utils__/services/redirected-terminal-ui';
48 import { TerminalUITest } from 'test/__utils__/services/terminal-ui-test';
49 import open from 'open';
@@ -166,8 +167,7 @@ const cliUserConfig = ComposioCliUserConfig.of({
167 /**
168 * What a link handler needs and nothing more: the account and connected-account families of
169 * the mock client (`test/__utils__/layers`), a Tool Router session that answers, and doubles
169 - * for the user, the directory, and the platform. `requests` records every link request, and
170 - * `exitCode` the exit code a handler sets.
170 + * for the user, the directory, and the platform. `requests` records every link request.
171 */
172 const linkHandlerTest = (fixture: LinkFixture = {}) => {
173 const requests: Array<LinkRequest> = [];
@@ -239,7 +239,6 @@ const linkHandlerTest = (fixture: LinkFixture = {}) => {
239 }) as unknown as ComposioClientShape;
240
241 const dir = tempy.temporaryDirectory({ prefix: 'link-handler' });
242 - const proc = recordingNodeProcess(dir);
242 const layer = Layer.mergeAll(
243 Layer.effect(Console.Console, MockConsole.make),
244 fixture.terminal ?? TerminalUITest,
@@ -281,15 +280,25 @@ const linkHandlerTest = (fixture: LinkFixture = {}) => {
280 NodeOs,
281 NodeOs.of({ homedir: dir, tmpdir: dir, arch: 'arm64', platform: 'darwin' })
282 ),
284 - proc.layer,
283 + Layer.succeed(
284 + NodeProcess,
285 + NodeProcess.of({ cwd: dir, execPath: `${dir}/composio`, platform: 'darwin', arch: 'arm64' })
286 + ),
287 Layer.succeed(ComposioCliUserConfig, cliUserConfig),
288 ConfigProvider.layer(hostOnlyEnvConfigProvider)
289 );
288 - return { layer, requests, sessionUsers, exitCode: proc.exitCode };
290 + return { layer, requests, sessionUsers };
291 };
292
293 const lines = MockConsole.getLines({ stripAnsi: true });
294
295 +/** Runs `handler` to its exit, then reads the lines it printed. */
296 +const exitAndLines = <A, E, R>(handler: Effect.Effect<A, E, R>) =>
297 + Effect.gen(function* () {
298 + const exit = yield* Effect.exit(handler);
299 + return { exit, output: yield* lines };
300 + });
301 +
302 /** The command's JSON result: `ui.output` prints it as the last console line. */
303 const lastJson = lines.pipe(Effect.map(all => JSON.parse(String(all.at(-1))) as unknown));
304
@@ -758,17 +767,17 @@ describe('connected-accounts link handler: handleLegacyAuthConfigLink', () => {
767 '[Given] the link request fails [Then] reports the message and the auth-config hint, and exits 1',
768 () =>
769 Effect.gen(function* () {
761 - const { layer, requests, exitCode } = linkHandlerTest({
770 + const { layer, requests } = linkHandlerTest({
771 surface: devSurface({ userId: 'user_1' }),
772 directoryProject: directory(Option.none()),
773 legacyLinkCreate: () => Effect.fail(new Error('quota exhausted')),
774 });
766 - const output = yield* handleLegacyAuthConfigLink(
767 - params({ authConfig: Option.some('ac_gmail') })
768 - ).pipe(Effect.andThen(lines), Effect.provide(layer));
775 + const { exit, output } = yield* exitAndLines(
776 + handleLegacyAuthConfigLink(params({ authConfig: Option.some('ac_gmail') }))
777 + ).pipe(Effect.provide(layer));
778
779 expect(output).toEqual(['quota exhausted', BROWSE_AUTH_CONFIGS_HINT]);
771 - expect(exitCode()).toBe(1);
780 + expect(exitCodeOf(exit)).toBe(1);
781 expect(requests).toEqual([
782 {
783 operation: 'link.create',
@@ -782,20 +791,22 @@ describe('connected-accounts link handler: handleLegacyAuthConfigLink', () => {
791 '[Given] an alias already in use [Then] points at the dev commands, sends nothing, and exits 1',
792 () =>
793 Effect.gen(function* () {
785 - const { layer, requests, exitCode } = linkHandlerTest({
794 + const { layer, requests } = linkHandlerTest({
795 surface: devSurface({ userId: 'user_1' }),
796 directoryProject: directory(Option.none()),
797 accounts: [account({ user_id: 'user_1', alias: 'Work' })],
798 });
790 - const output = yield* handleLegacyAuthConfigLink(
791 - params({ authConfig: Option.some('ac_gmail'), alias: Option.some(' work ') })
792 - ).pipe(Effect.andThen(lines), Effect.provide(layer));
799 + const { exit, output } = yield* exitAndLines(
800 + handleLegacyAuthConfigLink(
801 + params({ authConfig: Option.some('ac_gmail'), alias: Option.some(' work ') })
802 + )
803 + ).pipe(Effect.provide(layer));
804
805 expect(output).toEqual([
806 'Alias "work" is already in use by connected account "con_existing".',
807 "[Tips] Use the existing alias: composio dev playground-execute <TOOL_SLUG> --account work -d '{ ... }'\nList connected accounts: composio dev connected-accounts list",
808 ]);
798 - expect(exitCode()).toBe(1);
809 + expect(exitCodeOf(exit)).toBe(1);
810 expect(requests).toEqual([]);
811 })
812 );
@@ -825,7 +836,7 @@ describe('connected-accounts link handler: handleToolRouterLink', () => {
836 );
837
838 it.effect(
828 - '[Given] dev and an alias already in use [Then] points at the dev commands and sends nothing',
839 + '[Given] dev and an alias already in use [Then] points at the dev commands, sends nothing, and exits 1',
840 () =>
841 Effect.gen(function* () {
842 const { layer, requests } = linkHandlerTest({
@@ -833,14 +844,17 @@ describe('connected-accounts link handler: handleToolRouterLink', () => {
844 directoryProject: directory(Option.none()),
845 accounts: [account({ user_id: 'user_1', alias: 'Work' })],
846 });
836 - const output = yield* handleToolRouterLink(
837 - params({ toolkit: Option.some('gmail'), alias: Option.some('work') })
838 - ).pipe(Effect.andThen(lines), Effect.provide(layer));
847 + const { exit, output } = yield* exitAndLines(
848 + handleToolRouterLink(
849 + params({ toolkit: Option.some('gmail'), alias: Option.some('work') })
850 + )
851 + ).pipe(Effect.provide(layer));
852
853 expect(output).toEqual([
854 'Alias "work" is already in use by connected account "con_existing".',
855 "[Tips] Use the existing alias: composio dev playground-execute <TOOL_SLUG> --account work -d '{ ... }'\nList connected accounts: composio dev connected-accounts list --toolkits gmail",
856 ]);
857 + expect(exitCodeOf(exit)).toBe(1);
858 expect(requests).toEqual([]);
859 })
860 );
@@ -849,7 +863,7 @@ describe('connected-accounts link handler: handleToolRouterLink', () => {
863 '[Given] the consumer project and --alias [Then] links with the alias and prints the pending link',
864 () =>
865 Effect.gen(function* () {
852 - const { layer, requests, exitCode } = linkHandlerTest({ accounts: [account()] });
866 + const { layer, requests } = linkHandlerTest({ accounts: [account()] });
867 const output = yield* handleToolRouterLink(
868 params({ toolkit: Option.some('gmail'), alias: Option.some(' work ') })
869 ).pipe(Effect.andThen(lines), Effect.provide(layer));
@@ -861,7 +875,6 @@ describe('connected-accounts link handler: handleToolRouterLink', () => {
875 },
876 ]);
877 expect(String(output.at(-1))).toBe(toolRouterPendingJson());
864 - expect(exitCode()).toBeUndefined();
878 })
879 );
880
@@ -925,35 +938,34 @@ describe('connected-accounts link handler: handleToolRouterLink', () => {
938 it.effect('[Given] the link request fails [Then] reports the cause and the browse hint', () =>
939 Effect.gen(function* () {
940 const terminal = redirectedTerminalUI();
928 - const { layer, exitCode } = linkHandlerTest({
941 + const { layer } = linkHandlerTest({
942 toolRouterLink: () => Effect.fail(new Error('offline')),
943 terminal: terminal.layer,
944 });
932 - yield* handleToolRouterLink(params({ toolkit: Option.some('gmail') })).pipe(
933 - Effect.provide(layer)
945 + const exit = yield* Effect.exit(
946 + handleToolRouterLink(params({ toolkit: Option.some('gmail') })).pipe(Effect.provide(layer))
947 );
948
949 // `failedWith` keeps the client error in `.cause`, and the message prefers it. Plain
950 // lines, so a script, CI or an agent reading a redirected stderr sees them.
951 expect(terminal.stderr()).toBe(`offline\n${BROWSE_TOOLKITS_HINT}\n`);
952 expect(terminal.stdout()).toBe('');
940 - expect(exitCode()).toBe(1);
953 + expect(exitCodeOf(exit)).toBe(1);
954 })
955 );
956
957 it.effect('[Given] an incomplete link response [Then] reports it and exits 1', () =>
958 Effect.gen(function* () {
946 - const { layer, exitCode } = linkHandlerTest({
959 + const { layer } = linkHandlerTest({
960 toolRouterLink: () =>
961 Effect.succeed({ connected_account_id: 'con_new', link_token: 'lt', redirect_url: '' }),
962 });
950 - const output = yield* handleToolRouterLink(params({ toolkit: Option.some('gmail') })).pipe(
951 - Effect.andThen(lines),
952 - Effect.provide(layer)
953 - );
963 + const { exit, output } = yield* exitAndLines(
964 + handleToolRouterLink(params({ toolkit: Option.some('gmail') }))
965 + ).pipe(Effect.provide(layer));
966
967 expect(output).toEqual(['Linking gmail...', INCOMPLETE_LINK_RESPONSE_MESSAGE]);
956 - expect(exitCode()).toBe(1);
968 + expect(exitCodeOf(exit)).toBe(1);
969 })
970 );
971
@@ -1098,17 +1110,16 @@ describe('connected-accounts link handler: handleToolRouterLink', () => {
1110 '[Given] an active account and no --alias [Then] lists it, prints no link, and exits 1',
1111 () =>
1112 Effect.gen(function* () {
1101 - const { layer, exitCode } = linkHandlerTest({ accounts: [account({ alias: 'default' })] });
1102 - const output = yield* handleToolRouterLink(params({ toolkit: Option.some('gmail') })).pipe(
1103 - Effect.andThen(lines),
1104 - Effect.provide(layer)
1105 - );
1113 + const { layer } = linkHandlerTest({ accounts: [account({ alias: 'default' })] });
1114 + const { exit, output } = yield* exitAndLines(
1115 + handleToolRouterLink(params({ toolkit: Option.some('gmail') }))
1116 + ).pipe(Effect.provide(layer));
1117
1118 expect(output.slice(-2)).toEqual([
1119 `A connected account already exists for user "${CONSUMER_USER_ID}" in toolkit "gmail". Pass --alias to create another one.`,
1120 '[Existing accounts] con_existing (default, castle)',
1121 ]);
1111 - expect(exitCode()).toBe(1);
1122 + expect(exitCodeOf(exit)).toBe(1);
1123 })
1124 );
1125 });
ts/packages/cli/test/src/commands/connected-accounts/whoami/connected-accounts.whoami.cmd.test.ts
+5 -1
@@ -1,6 +1,7 @@
1 import { describe, expect, layer } from '@effect/vitest';
2 import { ConfigProvider, Effect } from 'effect';
3 import { cli, TestLive, MockConsole } from 'test/__utils__';
4 +import { exitCodeOf } from 'test/__utils__/exit-code';
5 import type { TestLiveInput } from 'test/__utils__/services/test-layer';
6 import type { ConnectedAccountItem } from 'src/models/connected-accounts';
7
@@ -90,12 +91,15 @@ describe('CLI: composio dev connected-accounts whoami', () => {
91 it => {
92 it.effect('shows error for nonexistent account', () =>
93 Effect.gen(function* () {
93 - yield* cli(['dev', 'connected-accounts', 'whoami', 'con_nonexistent']);
94 + const exit = yield* Effect.exit(
95 + cli(['dev', 'connected-accounts', 'whoami', 'con_nonexistent'])
96 + );
97 const lines = yield* MockConsole.getLines({ stripAnsi: true });
98 const output = lines.join('\n');
99
100 expect(output).toContain('not found');
101 expect(output).toContain('composio dev connected-accounts list');
102 + expect(exitCodeOf(exit)).toBe(1);
103 })
104 );
105 }
ts/packages/cli/test/src/commands/connected-accounts/whoami/connected-accounts.whoami.handler.test.ts
+12 -27
@@ -5,9 +5,9 @@ import { inactiveStatusMessage } from 'src/commands/connected-accounts/whoami/co
5 import { MISSING_ID_MESSAGE, missingIdHint } from 'src/commands/connected-accounts/format';
6 import { isUsageFailure } from 'src/commands/errors';
7 import type { ConnectedAccountItem } from 'src/models/connected-accounts';
8 -import { NodeProcess } from 'src/services/node-process';
8 import { TerminalUI } from 'src/services/terminal-ui';
9 import { ConnectedAccountsTest, MockConsole } from 'test/__utils__';
10 +import { exitCodeOf } from 'test/__utils__/exit-code';
11 import { terminalUITestImpl } from 'test/__utils__/services/terminal-ui-test';
12
13 const account = (overrides: Partial<ConnectedAccountItem> = {}): ConnectedAccountItem => ({
@@ -35,13 +35,11 @@ const ACTIVE_ACCOUNT = account();
35 const EXPIRED_ACCOUNT = account({ id: 'con_gmail_expired', status: 'EXPIRED' });
36
37 /**
38 - * What `runConnectedAccountsWhoami` reads: the connected-account repository, a headless
39 - * terminal whose stdout data lands in `outputs`, and a process whose exit codes land in
40 - * `exitCodes`.
38 + * What `runConnectedAccountsWhoami` reads: the connected-account repository and a headless
39 + * terminal whose stdout data lands in `outputs`.
40 */
41 const whoamiTest = () => {
42 const outputs: Array<string> = [];
44 - const exitCodes: Array<number> = [];
43 const layer = Layer.mergeAll(
44 Layer.effect(Console.Console, MockConsole.make),
45 Layer.succeed(
@@ -54,22 +52,9 @@ const whoamiTest = () => {
52 }),
53 })
54 ),
57 - ConnectedAccountsTest({ connectedAccountsData: { items: [ACTIVE_ACCOUNT, EXPIRED_ACCOUNT] } }),
58 - Layer.succeed(
59 - NodeProcess,
60 - NodeProcess.of({
61 - cwd: '/tmp',
62 - execPath: '/tmp/composio',
63 - platform: 'darwin',
64 - arch: 'arm64',
65 - setExitCode: code =>
66 - Effect.sync(() => {
67 - exitCodes.push(code);
68 - }),
69 - })
70 - )
55 + ConnectedAccountsTest({ connectedAccountsData: { items: [ACTIVE_ACCOUNT, EXPIRED_ACCOUNT] } })
56 );
72 - return { layer, outputs, exitCodes };
57 + return { layer, outputs };
58 };
59
60 const stdoutLines = MockConsole.getLines({ stream: 'stdout', stripAnsi: true });
@@ -77,7 +62,7 @@ const stderrLines = MockConsole.getLines({ stream: 'stderr', stripAnsi: true });
62
63 describe('runConnectedAccountsWhoami', () => {
64 it.effect('[Given] an active account [Then] prints its profile fields as JSON on stdout', () => {
80 - const { layer, outputs, exitCodes } = whoamiTest();
65 + const { layer, outputs } = whoamiTest();
66 return Effect.gen(function* () {
67 yield* runConnectedAccountsWhoami({ id: Option.some('con_gmail_active') });
68
@@ -94,7 +79,6 @@ describe('runConnectedAccountsWhoami', () => {
79 },
80 ]);
81 expect(yield* stderrLines).toEqual([]);
97 - expect(exitCodes).toEqual([]);
82 }).pipe(Effect.provide(layer));
83 });
84
@@ -110,7 +94,7 @@ describe('runConnectedAccountsWhoami', () => {
94 });
95
96 it.effect('[Given] no id [Then] fails with a usage error before any request', () => {
113 - const { layer, outputs, exitCodes } = whoamiTest();
97 + const { layer, outputs } = whoamiTest();
98 return Effect.gen(function* () {
99 const failure = yield* runConnectedAccountsWhoami({ id: Option.none() }).pipe(Effect.flip);
100
@@ -125,20 +109,21 @@ describe('runConnectedAccountsWhoami', () => {
109 expect(yield* stderrLines).toEqual([]);
110 expect(yield* stdoutLines).toEqual([]);
111 expect(outputs).toEqual([]);
128 - expect(exitCodes).toEqual([]);
112 }).pipe(Effect.provide(layer));
113 });
114
115 it.effect('[Given] an unknown id [Then] reports it, prints no data, and exits 1', () => {
133 - const { layer, outputs, exitCodes } = whoamiTest();
116 + const { layer, outputs } = whoamiTest();
117 return Effect.gen(function* () {
135 - yield* runConnectedAccountsWhoami({ id: Option.some('con_missing') });
118 + const exit = yield* Effect.exit(
119 + runConnectedAccountsWhoami({ id: Option.some('con_missing') })
120 + );
121
122 expect((yield* stderrLines).join('\n')).toContain(
123 'Connected account "con_missing" not found.'
124 );
125 expect(outputs).toEqual([]);
141 - expect(exitCodes).toEqual([1]);
126 + expect(exitCodeOf(exit)).toBe(1);
127 }).pipe(Effect.provide(layer));
128 });
129 });
ts/packages/cli/test/src/commands/connections/remove/connections.remove.cmd.test.ts
+1 -3
@@ -183,10 +183,9 @@ describe('CLI: composio connections remove', () => {
183
184 expect(deniedDeleteCalls).toEqual([]);
185
186 - // Declining is not a failure: the line says nothing changed, and the exit code stays 0.
186 + // Declining is not a failure: the command succeeds and the line says nothing changed.
187 const lines = yield* MockConsole.getLines({ stripAnsi: true });
188 expect(lines.at(-1)).toBe('No connection removed.');
189 - expect(process.exitCode).toBeUndefined();
189 })
190 );
191 });
@@ -286,7 +285,6 @@ describe('CLI: composio connections remove', () => {
285 yield* cli(['connections', 'remove', 'gmail', '--yes']);
286
287 expect(headlessDeleteCalls).toEqual(['con_gmail_active']);
289 - expect(process.exitCode).toBeUndefined();
288 })
289 );
290
ts/packages/cli/test/src/commands/init.cmd.test.ts
+5 -2
@@ -2,6 +2,7 @@ import { afterEach } from 'vitest';
2 import { describe, expect, layer } from '@effect/vitest';
3 import { Effect } from 'effect';
4 import { cli, TestLive, MockConsole } from 'test/__utils__';
5 +import { exitCodeOf } from 'test/__utils__/exit-code';
6 import { makeOrgProject } from 'test/__utils__/models/account';
7 import { redirectedTerminalUI } from 'test/__utils__/services/redirected-terminal-ui';
8
@@ -49,13 +50,15 @@ describe('CLI: composio dev init', () => {
50 it.effect('[Given] no projects [Then] says so on a redirected stderr and exits 1', () =>
51 Effect.gen(function* () {
52 const terminal = redirectedTerminalUI();
52 - yield* cli(['dev', 'init', '--yes']).pipe(Effect.provide(terminal.layer));
53 + const exit = yield* Effect.exit(
54 + cli(['dev', 'init', '--yes']).pipe(Effect.provide(terminal.layer))
55 + );
56
57 expect(terminal.stderr()).toBe(
58 'No projects found for your organization.\nCreate a project at https://platform.composio.dev, then run `composio dev init` again.\n'
59 );
60 expect(terminal.stdout()).toBe('');
58 - expect(process.exitCode).toBe(1);
61 + expect(exitCodeOf(exit)).toBe(1);
62 })
63 );
64 }
ts/packages/cli/test/src/commands/install/install.handler.test.ts
-1
@@ -87,7 +87,6 @@ const installTest = (
87 execPath: params.execPath ?? `${BIN_DIR}/composio`,
88 platform: 'linux',
89 arch: 'x64',
90 - setExitCode: () => Effect.void,
90 })
91 ),
92 uiLayer,
ts/packages/cli/test/src/commands/listen.cmd.test.ts
+14 -10
@@ -10,6 +10,7 @@ import { ComposioCliUserConfig } from 'src/services/cli-user-config';
10 import { ComposioUserContext } from 'src/services/user-context';
11 import { TriggerRealtimeSubscriptionError, TriggersRealtime } from 'src/services/triggers-realtime';
12 import { cli, MockConsole, TestLive } from 'test/__utils__';
13 +import { exitCodeOf } from 'test/__utils__/exit-code';
14 import { failingFileWrites } from 'test/__utils__/services/failing-file-writes';
15 import { redirectedTerminalUI } from 'test/__utils__/services/redirected-terminal-ui';
16
@@ -48,14 +49,16 @@ describe('CLI: composio listen', () => {
49 Effect.gen(function* () {
50 yield* enableListen;
51 const terminal = redirectedTerminalUI();
51 - yield* cli(['listen', 'composio.connected_account.expired', '--max-events', '1']).pipe(
52 - Effect.provide(Layer.merge(failingRealtime, terminal.layer))
52 + const exit = yield* Effect.exit(
53 + cli(['listen', 'composio.connected_account.expired', '--max-events', '1']).pipe(
54 + Effect.provide(Layer.merge(failingRealtime, terminal.layer))
55 + )
56 );
57
58 expect(terminal.stderr()).toContain(
59 'Could not subscribe to realtime trigger events: socket closed. Check your network connection or run `composio login`.\n'
60 );
58 - expect(process.exitCode).toBe(1);
61 + expect(exitCodeOf(exit)).toBe(1);
62 })
63 );
64 }
@@ -193,7 +196,6 @@ describe('CLI: composio listen', () => {
196 );
197
198 expect(terminal.stderr()).toContain('1 event failed to write while listening.');
196 - expect(process.exitCode).toBeUndefined();
199 })
200 );
201
@@ -202,12 +204,14 @@ describe('CLI: composio listen', () => {
204 Effect.gen(function* () {
205 yield* enableListen;
206 const terminal = redirectedTerminalUI();
205 - yield* cli(['listen', 'composio.connected_account.expired', '--fail-fast']).pipe(
206 - Effect.provide(Layer.merge(payloadWritesFail, terminal.layer))
207 + const exit = yield* Effect.exit(
208 + cli(['listen', 'composio.connected_account.expired', '--fail-fast']).pipe(
209 + Effect.provide(Layer.merge(payloadWritesFail, terminal.layer))
210 + )
211 );
212
213 expect(terminal.stderr()).toContain('1 event failed to write while listening.');
210 - expect(process.exitCode).toBe(1);
214 + expect(exitCodeOf(exit)).toBe(1);
215 })
216 );
217
@@ -220,8 +224,6 @@ describe('CLI: composio listen', () => {
224 yield* Fiber.join(fiber);
225
226 expect(terminal.stderr()).toContain('1 event failed to write while listening.');
223 - // Recovered per-event failures, not a failed command.
224 - expect(process.exitCode).toBeUndefined();
227 })
228 );
229
@@ -233,9 +235,11 @@ describe('CLI: composio listen', () => {
235 const { fiber, terminal } = yield* listenUntilWriteFails([]);
236
237 yield* Fiber.interrupt(fiber);
238 + const exit = yield* Fiber.await(fiber);
239
240 expect(terminal.stderr()).toContain('1 event failed to write while listening.');
238 - expect(process.exitCode).toBeUndefined();
241 + // Interrupted, not failed: the summary alone does not fail the command.
242 + expect(exitCodeOf(exit)).toBe(130);
243 })
244 );
245 });
ts/packages/cli/test/src/commands/login/login.handler.test.ts
-1
@@ -259,7 +259,6 @@ const loginHandlerTest = (fixture: LoginFixture = {}) => {
259 execPath: `${dir}/composio`,
260 platform: 'darwin',
261 arch: 'arm64',
262 - setExitCode: () => Effect.void,
262 })
263 ),
264 ConfigProvider.layer(hostOnlyEnvConfigProvider)
ts/packages/cli/test/src/commands/logout.cmd.test.ts
-2
@@ -125,8 +125,6 @@ describe('CLI: composio logout', () => {
125 expect(output).toContain('Agent Logout Warning');
126 expect(output).toContain('composio_agent_key');
127 expect(output).toContain('Agent logout cancelled');
128 - // Declining is not a failure.
129 - expect(process.exitCode).toBeUndefined();
128 expect(ctx.isLoggedIn()).toBeTruthy();
129 expect(agentConfigExists).toBe(true);
130 })
ts/packages/cli/test/src/commands/request-failures.client.test.ts
+7 -3
@@ -4,6 +4,7 @@ import { TestClock } from 'effect/testing';
4 import type { ComposioClientShape } from '@composio/client/effect';
5 import { extractErrorDetails } from 'src/effect-errors/logic/errors/extract-error-details';
6 import { cli, MockConsole, TestLive } from 'test/__utils__';
7 +import { exitCodeOf } from 'test/__utils__/exit-code';
8 import {
9 routeRequests,
10 stubClientResources,
@@ -167,15 +168,17 @@ describe('CLI: a rejected request the command recovers from', () => {
168 ['toolRouter'],
169 routeRequests([{ method: 'GET', path: SESSION_TOOLKITS, respond: toolkits }], session)
170 );
170 - yield* cli(['dev', 'toolkits', 'info', 'gmail']).pipe(Effect.provide(stub.layer));
171 + const exit = yield* Effect.exit(
172 + cli(['dev', 'toolkits', 'info', 'gmail']).pipe(Effect.provide(stub.layer))
173 + );
174 const lines = yield* MockConsole.getLines({ stripAnsi: true });
172 - return { lines, lastPath: stub.requests.at(-1)?.path };
175 + return { lines, lastPath: stub.requests.at(-1)?.path, exitCode: exitCodeOf(exit) };
176 });
177
178 layer(testLayer())('[Given] composio dev toolkits info and rejected session toolkits', it => {
179 it.effect('[Then] the API message and the browse hint are printed', () =>
180 Effect.gen(function* () {
178 - const { lines, lastPath } = yield* toolkitsInfo(forbidden);
181 + const { lines, lastPath, exitCode } = yield* toolkitsInfo(forbidden);
182
183 expect(lines).toEqual([
184 'Using global test user id "global-default"',
@@ -183,6 +186,7 @@ describe('CLI: a rejected request the command recovers from', () => {
186 'Browse available toolkits:\n> composio dev toolkits list',
187 ]);
188 expect(lastPath).toBe(SESSION_TOOLKITS);
189 + expect(exitCode).toBe(1);
190 })
191 );
192 });
ts/packages/cli/test/src/commands/root-help-consistency.test.ts
+2 -6
@@ -2,16 +2,12 @@ import { describe, expect, layer } from '@effect/vitest';
2 import { Effect } from 'effect';
3 import { afterEach } from 'vitest';
4 import { buildRootCommand } from 'src/commands';
5 -import { teardown } from 'src/cli-main';
5 import { cli, MockConsole, TestLive } from 'test/__utils__';
6 +import { exitCodeOf } from 'test/__utils__/exit-code';
7
8 const capture = (args: ReadonlyArray<string>) =>
9 Effect.gen(function* () {
10 - const exit = yield* Effect.exit(cli(args));
11 - let exitCode = 0;
12 - teardown(exit, code => {
13 - exitCode = code;
14 - });
10 + const exitCode = exitCodeOf(yield* Effect.exit(cli(args)));
11 const stdout = (yield* MockConsole.getLines({ stripAnsi: true, stream: 'stdout' })).join('\n');
12 const stderr = (yield* MockConsole.getLines({ stripAnsi: true, stream: 'stderr' })).join('\n');
13 return { exitCode, stdout, stderr };
ts/packages/cli/test/src/commands/run.cmd.test.ts
+48 -8
@@ -7,7 +7,7 @@ import { describe, expect, layer } from '@effect/vitest';
7 import { assertDefined } from '@effect/vitest/utils';
8 import * as BunServices from '@effect/platform-bun/BunServices';
9 import * as Path from 'effect/Path';
10 -import { ConfigProvider, Effect, Layer, Sink, Stream } from 'effect';
10 +import { ConfigProvider, Deferred, Effect, Fiber, Layer, Runtime, Sink, Stream } from 'effect';
11 import { ChildProcess, ChildProcessSpawner } from 'effect/process';
12 import { afterEach, it, vi } from 'vitest';
13 import { createCliCommandTelemetryContext } from 'src/analytics/events';
@@ -26,7 +26,9 @@ import {
26 import { telemetryDebugModeLayer } from 'src/services/runtime-flags';
27 import { DEFAULT_CLI_INVOCATION_ORIGIN } from 'src/services/runtime-cli-context';
28 import { cli, MockConsole, TestLive } from 'test/__utils__';
29 +import { exitCodeOf } from 'test/__utils__/exit-code';
30 import { CommandRunner } from 'src/services/command-runner';
31 +import { ChildProcessExited } from 'src/effects/child-process-exited';
32
33 const enabledRuntimeFlagsConfigProvider = ConfigProvider.fromEnvRecord({
34 COMPOSIO_RUN_ACP_ONLY: '1',
@@ -191,9 +193,11 @@ describe('CLI: composio run', () => {
193 Effect.gen(function* () {
194 commandRuns.mockImplementation(() => Effect.succeed(ChildProcessSpawner.ExitCode(7)));
195
194 - yield* cli(['run', 'console.log("hi")', '--flag', 'value']);
196 + const exit = yield* Effect.exit(cli(['run', 'console.log("hi")', '--flag', 'value']));
197 const output = yield* MockConsole.getLines();
198
199 + // The process exits with the child's code.
200 + expect(exitCodeOf(exit)).toBe(7);
201 expect(commandRuns).toHaveBeenCalledTimes(1);
202 const spawnConfig = inspectRunCommand(commandRuns.mock.calls[0]![0]);
203 expect(spawnConfig.cmd[0]).toBe(process.execPath);
@@ -217,11 +221,52 @@ describe('CLI: composio run', () => {
221 );
222 expect(fs.existsSync(runLogPath)).toBe(true);
223 fs.rmSync(path.dirname(runLogPath), { recursive: true, force: true });
220 - expect(process.exitCode).toBe(7);
224 })
225 );
226 });
227
228 + layer(RunTestLive())(it => {
229 + it.effect(
230 + '[Given] a child that exits non-zero [Then] it fails with ChildProcessExited, which the runtime does not log',
231 + () =>
232 + Effect.gen(function* () {
233 + commandRuns.mockImplementation(() => Effect.succeed(ChildProcessSpawner.ExitCode(3)));
234 +
235 + const failure = yield* cli(['run', 'console.log("hi")']).pipe(Effect.flip);
236 +
237 + expect(failure).toBeInstanceOf(ChildProcessExited);
238 + expect(failure).toMatchObject({ code: 3 });
239 + // The child already wrote its own output; `BunRuntime.runMain` must not add a log.
240 + expect(Runtime.getErrorReported(failure)).toBe(false);
241 + })
242 + );
243 +
244 + it.effect('[Given] a child that exits 0 [Then] the run succeeds', () =>
245 + Effect.gen(function* () {
246 + const exit = yield* Effect.exit(cli(['run', 'console.log("hi")']));
247 +
248 + expect(exitCodeOf(exit)).toBe(0);
249 + })
250 + );
251 +
252 + // Ctrl-C interrupts the run while the child is still running: the process exits 130, not 0,
253 + // so wrappers and `set -e` scripts do not read a cancelled run as a passing one.
254 + it.effect('[Given] the run is interrupted [Then] the process exits 130', () =>
255 + Effect.gen(function* () {
256 + const started = yield* Deferred.make<void>();
257 + commandRuns.mockImplementation(() =>
258 + Deferred.succeed(started, undefined).pipe(Effect.andThen(Effect.never))
259 + );
260 +
261 + const fiber = yield* Effect.forkChild(cli(['run', 'console.log("hi")']));
262 + yield* Deferred.await(started);
263 + yield* Fiber.interrupt(fiber);
264 +
265 + expect(exitCodeOf(yield* Fiber.await(fiber))).toBe(130);
266 + })
267 + );
268 + });
269 +
270 layer(RunTestLive())(it => {
271 it.effect('[Given] a run [Then] the preload context carries no sub-agent inputs', () =>
272 Effect.gen(function* () {
@@ -430,7 +475,6 @@ describe('CLI: composio run', () => {
475 expect(spawnConfig.cmd[4]).toContain('console.log(JSON.stringify(issue));');
476 expect(spawnConfig.cmd[4]).toContain('return (console.log(JSON.stringify(issue.data)));');
477 expect(spawnConfig.cmd[4]).not.toContain('"Do not run terminal\n');
433 - expect(process.exitCode).toBe(0);
478 })
479 );
480 });
@@ -454,7 +498,6 @@ describe('CLI: composio run', () => {
498 expect(spawnConfig.stdio).toEqual(['inherit', 'inherit', 'inherit']);
499 expect(fs.existsSync(spawnConfig.cmd[2]!)).toBe(false);
500 expect(fs.existsSync(spawnConfig.cmd[3]!)).toBe(false);
457 - expect(process.exitCode).toBe(0);
501 })
502 );
503 });
@@ -493,7 +536,6 @@ describe('CLI: composio run', () => {
536 // leak into the forwarded script arguments.
537 expect(spawnConfig.cmd[3]).toMatch(/\.composio-run-.*\.ts$/);
538 expect(spawnConfig.cmd).not.toContain('--dry-run');
496 - expect(process.exitCode).toBe(0);
539 })
540 );
541 });
@@ -531,7 +573,6 @@ describe('CLI: composio run', () => {
573 // First `--` is the run/script boundary; the second is a script
574 // argument and must reach the script verbatim (v3 behavior).
575 expect(spawnConfig.cmd.slice(5)).toEqual(['--', 'alpha', '--', 'beta']);
534 - expect(process.exitCode).toBe(0);
576 })
577 );
578 });
@@ -546,7 +587,6 @@ describe('CLI: composio run', () => {
587 expect(commandRuns).toHaveBeenCalledTimes(1);
588 const spawnConfig = inspectRunCommand(commandRuns.mock.calls[0]![0]);
589 expect(spawnConfig.cmd.slice(5)).toEqual(['--', '@@composio-run-raw@@literal']);
549 - expect(process.exitCode).toBe(0);
590 })
591 );
592 });
ts/packages/cli/test/src/commands/signup/signup.cmd.test.ts
+3 -2
@@ -8,6 +8,7 @@ import { setupCacheDir } from 'src/effects/setup-cache-dir';
8 import type { AgentIdentity } from 'src/services/agents';
9 import { ComposioUserContext } from 'src/services/user-context';
10 import { cli, MockConsole, TestLive } from 'test/__utils__';
11 +import { exitCodeOf } from 'test/__utils__/exit-code';
12
13 const readyIdentity: AgentIdentity = {
14 status: 'READY',
@@ -125,11 +126,11 @@ describe('CLI: composio signup', () => {
126 Effect.gen(function* () {
127 const fetchSpy = vi.spyOn(globalThis, 'fetch');
128
128 - yield* cli(['signup']);
129 + const exit = yield* Effect.exit(cli(['signup']));
130
131 const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
132 expect(output).toContain('currently signed in to Composio as a regular user');
132 - expect(process.exitCode).toBe(1);
133 + expect(exitCodeOf(exit)).toBe(1);
134 expect(fetchSpy).not.toHaveBeenCalled();
135 })
136 );
ts/packages/cli/test/src/commands/surface.test.ts
+4 -2
@@ -8,6 +8,7 @@ import type { ConnectedAccountItem } from 'src/models/connected-accounts';
8 import { NodeProcess } from 'src/services/node-process';
9 import { ComposioUserContext } from 'src/services/user-context';
10 import { cli, MockConsole, TestLive } from 'test/__utils__';
11 +import { exitCodeOf } from 'test/__utils__/exit-code';
12 import { makeOrgProject } from 'test/__utils__/models/account';
13
14 const SHARED_PROJECT_DESCRIPTION =
@@ -188,16 +189,17 @@ describe('CommandSurface: toolkits list reports the named project it cannot find
189 accountData: { projects: [] },
190 })
191 )(it => {
191 - // `toolkits list` reports every failure on stderr and exits 1 rather than failing.
192 + // `toolkits list` prints every failure on stderr itself, then fails already reported.
193 it.effect('looks the named project up', () =>
194 Effect.gen(function* () {
195 const userContext = yield* ComposioUserContext;
196 yield* userContext.login('test_api_key', 'org_test');
196 - yield* cli(['dev', 'toolkits', 'list', '--project-name', 'nope']);
197 + const exit = yield* Effect.exit(cli(['dev', 'toolkits', 'list', '--project-name', 'nope']));
198 const stderr = (yield* MockConsole.getLines({ stripAnsi: true, stream: 'stderr' })).join(
199 '\n'
200 );
201 expect(stderr).toContain('Developer project "nope" was not found in org "org_test"');
202 + expect(exitCodeOf(exit)).toBe(1);
203 })
204 );
205 });
ts/packages/cli/test/src/commands/toolkits/info/toolkits.info.cmd.test.ts
+12 -7
@@ -2,6 +2,7 @@ import { afterEach } from 'vitest';
2 import { describe, expect, layer } from '@effect/vitest';
3 import { ConfigProvider, DateTime, Effect, Layer } from 'effect';
4 import { cli, TestLive, MockConsole } from 'test/__utils__';
5 +import { exitCodeOf } from 'test/__utils__/exit-code';
6 import { redirectedTerminalUI } from 'test/__utils__/services/redirected-terminal-ui';
7 import { stubClientResources } from 'test/__utils__/services/stub-composio-client';
8 import type { TestLiveInput } from 'test/__utils__/services/test-layer';
@@ -225,11 +226,13 @@ describe('CLI: composio dev toolkits info', () => {
226 it.effect('prints the error on a redirected stderr and exits 1', () =>
227 Effect.gen(function* () {
228 const terminal = redirectedTerminalUI();
228 - yield* cli(['dev', 'toolkits', 'info', 'gmal']).pipe(Effect.provide(terminal.layer));
229 + const exit = yield* Effect.exit(
230 + cli(['dev', 'toolkits', 'info', 'gmal']).pipe(Effect.provide(terminal.layer))
231 + );
232
233 expect(terminal.stderr()).toContain('Toolkit "gmal" not found.\n');
234 expect(terminal.stdout()).toBe('');
232 - expect(process.exitCode).toBe(1);
235 + expect(exitCodeOf(exit)).toBe(1);
236 })
237 );
238 }
@@ -240,13 +243,13 @@ describe('CLI: composio dev toolkits info', () => {
243 it => {
244 it.effect('shows error with hint and exits 1', () =>
245 Effect.gen(function* () {
243 - yield* cli(['dev', 'toolkits', 'info', 'gma']);
246 + const exit = yield* Effect.exit(cli(['dev', 'toolkits', 'info', 'gma']));
247 const lines = yield* MockConsole.getLines({ stripAnsi: true });
248 const output = lines.join('\n');
249
250 expect(output).toContain('Toolkit "gma" not found');
251 expect(output).toContain('composio dev toolkits info "gmail"');
249 - expect(process.exitCode).toBe(1);
252 + expect(exitCodeOf(exit)).toBe(1);
253 })
254 );
255 }
@@ -294,15 +297,17 @@ describe('CLI: composio dev toolkits info', () => {
297 Response.json({ error: { message: 'Tool Router is down' } }, { status: 500 })
298 );
299 const terminal = redirectedTerminalUI();
297 - yield* cli(['dev', 'toolkits', 'info', 'gmail']).pipe(
298 - Effect.provide(Layer.mergeAll(stub.layer, terminal.layer))
300 + const exit = yield* Effect.exit(
301 + cli(['dev', 'toolkits', 'info', 'gmail']).pipe(
302 + Effect.provide(Layer.mergeAll(stub.layer, terminal.layer))
303 + )
304 );
305
306 expect(terminal.stderr()).toBe(
307 'Tool Router is down\nBrowse available toolkits:\n> composio dev toolkits list\n'
308 );
309 expect(terminal.stdout()).toBe('');
305 - expect(process.exitCode).toBe(1);
310 + expect(exitCodeOf(exit)).toBe(1);
311 })
312 );
313 });
ts/packages/cli/test/src/commands/toolkits/list/toolkits.list.cmd.test.ts
+6 -5
@@ -5,7 +5,7 @@ import type { TestLiveInput } from 'test/__utils__/services/test-layer';
5 import type { Toolkits } from 'src/models/toolkits';
6 import { ComposioToolkitsRepository } from 'src/services/composio-clients';
7 import { notFoundError } from 'test/__utils__/layers/not-found';
8 -import { recordingNodeProcess } from 'test/__utils__/services/node-process-test';
8 +import { exitCodeOf } from 'test/__utils__/exit-code';
9 import { redirectedTerminalUI } from 'test/__utils__/services/redirected-terminal-ui';
10 import { routeRequests, stubClientResources } from 'test/__utils__/services/stub-composio-client';
11 import { makeToolkitsRepositoryStub } from 'test/__utils__/services/toolkits-repository-stub';
@@ -356,7 +356,6 @@ describe('CLI: composio dev toolkits list', () => {
356 it => {
357 it.effect('[Then] prints the error, writes `[]` to stdout and exits 1', () =>
358 Effect.gen(function* () {
359 - const proc = recordingNodeProcess();
359 const repository = Layer.succeed(
360 ComposioToolkitsRepository,
361 makeToolkitsRepositoryStub({
@@ -365,13 +364,15 @@ describe('CLI: composio dev toolkits list', () => {
364 );
365 // Redirected streams, as under a script: only plain stderr lines and stdout data show.
366 const terminal = redirectedTerminalUI();
368 - yield* cli(['dev', 'toolkits', 'list']).pipe(
369 - Effect.provide(Layer.mergeAll(repository, proc.layer, terminal.layer))
367 + const exit = yield* Effect.exit(
368 + cli(['dev', 'toolkits', 'list']).pipe(
369 + Effect.provide(Layer.mergeAll(repository, terminal.layer))
370 + )
371 );
372
373 expect(terminal.stderr()).toBe('Catalog unavailable\n');
374 expect(terminal.stdout()).toBe('[]\n');
374 - expect(proc.exitCode()).toBe(1);
375 + expect(exitCodeOf(exit)).toBe(1);
376 })
377 );
378 }
ts/packages/cli/test/src/commands/toolkits/search/toolkits.search.cmd.test.ts
+6 -5
@@ -5,7 +5,7 @@ import type { TestLiveInput } from 'test/__utils__/services/test-layer';
5 import type { Toolkits } from 'src/models/toolkits';
6 import { ComposioToolkitsRepository } from 'src/services/composio-clients';
7 import { notFoundError } from 'test/__utils__/layers/not-found';
8 -import { recordingNodeProcess } from 'test/__utils__/services/node-process-test';
8 +import { exitCodeOf } from 'test/__utils__/exit-code';
9 import { redirectedTerminalUI } from 'test/__utils__/services/redirected-terminal-ui';
10 import { makeToolkitsRepositoryStub } from 'test/__utils__/services/toolkits-repository-stub';
11
@@ -147,7 +147,6 @@ describe('CLI: composio dev toolkits search', () => {
147 it => {
148 it.effect('[Then] prints the error, writes `[]` to stdout and exits 1', () =>
149 Effect.gen(function* () {
150 - const proc = recordingNodeProcess();
150 const repository = Layer.succeed(
151 ComposioToolkitsRepository,
152 makeToolkitsRepositoryStub({
@@ -156,13 +155,15 @@ describe('CLI: composio dev toolkits search', () => {
155 );
156 // Redirected streams, as under a script: only plain stderr lines and stdout data show.
157 const terminal = redirectedTerminalUI();
159 - yield* cli(['dev', 'toolkits', 'search', 'email']).pipe(
160 - Effect.provide(Layer.mergeAll(repository, proc.layer, terminal.layer))
158 + const exit = yield* Effect.exit(
159 + cli(['dev', 'toolkits', 'search', 'email']).pipe(
160 + Effect.provide(Layer.mergeAll(repository, terminal.layer))
161 + )
162 );
163
164 expect(terminal.stderr()).toBe('Search unavailable\n');
165 expect(terminal.stdout()).toBe('[]\n');
165 - expect(proc.exitCode()).toBe(1);
166 + expect(exitCodeOf(exit)).toBe(1);
167 })
168 );
169 }
ts/packages/cli/test/src/commands/toolkits/version/toolkits.version.client.cmd.test.ts
+5 -1
@@ -1,6 +1,7 @@
1 import { describe, expect, layer } from '@effect/vitest';
2 import { ConfigProvider, Effect } from 'effect';
3 import { cli, MockConsole, TestLive } from 'test/__utils__';
4 +import { exitCodeOf } from 'test/__utils__/exit-code';
5 import { stubClientResources } from 'test/__utils__/services/stub-composio-client';
6
7 const testLayer = TestLive({
@@ -24,13 +25,16 @@ describe('CLI: composio dev toolkits version over the API client', () => {
25 { status: 404 }
26 )
27 );
27 - yield* cli(['dev', 'toolkits', 'version', 'unknown']).pipe(Effect.provide(stub.layer));
28 + const exit = yield* Effect.exit(
29 + cli(['dev', 'toolkits', 'version', 'unknown']).pipe(Effect.provide(stub.layer))
30 + );
31 const lines = yield* MockConsole.getLines({ stripAnsi: true });
32
33 expect(lines).toEqual([
34 'Toolkit unknown not found',
35 'Browse available toolkits:\n> composio dev toolkits list',
36 ]);
37 + expect(exitCodeOf(exit)).toBe(1);
38 expect(stub.requests).toEqual([{ method: 'GET', path: '/api/v3.1/toolkits/unknown' }]);
39 })
40 );
ts/packages/cli/test/src/commands/toolkits/version/toolkits.version.cmd.test.ts
+4 -3
@@ -2,6 +2,7 @@ import { afterEach } from 'vitest';
2 import { describe, expect, layer } from '@effect/vitest';
3 import { ConfigProvider, DateTime, Effect } from 'effect';
4 import { cli, TestLive, MockConsole } from 'test/__utils__';
5 +import { exitCodeOf } from 'test/__utils__/exit-code';
6 import { redirectedTerminalUI } from 'test/__utils__/services/redirected-terminal-ui';
7 import type { TestLiveInput } from 'test/__utils__/services/test-layer';
8 import type { Toolkits, ToolkitDetailed } from 'src/models/toolkits';
@@ -94,8 +95,8 @@ describe('CLI: composio dev toolkits version', () => {
95 it.effect('prints fetch failure and browse hint on a redirected stderr and exits 1', () =>
96 Effect.gen(function* () {
97 const terminal = redirectedTerminalUI();
97 - yield* cli(['dev', 'toolkits', 'version', 'unknown']).pipe(
98 - Effect.provide(terminal.layer)
98 + const exit = yield* Effect.exit(
99 + cli(['dev', 'toolkits', 'version', 'unknown']).pipe(Effect.provide(terminal.layer))
100 );
101
102 expect(terminal.stderr()).toContain('Toolkit "unknown" not found');
@@ -103,7 +104,7 @@ describe('CLI: composio dev toolkits version', () => {
104 'Browse available toolkits:\n> composio dev toolkits list\n'
105 );
106 expect(terminal.stdout()).toBe('');
106 - expect(process.exitCode).toBe(1);
107 + expect(exitCodeOf(exit)).toBe(1);
108 })
109 );
110 }
ts/packages/cli/test/src/commands/tools/info/tools.info.cmd.test.ts
+6 -5
@@ -1,6 +1,7 @@
1 import { afterEach, describe, expect, layer } from '@effect/vitest';
2 import { ConfigProvider, Effect } from 'effect';
3 import { cli, TestLive, MockConsole } from 'test/__utils__';
4 +import { exitCodeOf } from 'test/__utils__/exit-code';
5 import type { TestLiveInput } from 'test/__utils__/services/test-layer';
6 import type { Tools } from 'src/models/tools';
7
@@ -154,7 +155,7 @@ describe('CLI: composio tools info', () => {
155 it => {
156 it.effect('shows not found with suggestions', () =>
157 Effect.gen(function* () {
157 - yield* cli(['tools', 'info', 'NONEXISTENT_TOOL']);
158 + yield* Effect.exit(cli(['tools', 'info', 'NONEXISTENT_TOOL']));
159 const lines = yield* MockConsole.getLines({ stripAnsi: true });
160 const output = lines.join('\n');
161
@@ -164,19 +165,19 @@ describe('CLI: composio tools info', () => {
165
166 it.effect('exits non-zero and reports the missing tool', () =>
167 Effect.gen(function* () {
167 - yield* cli(['tools', 'info', 'NONEXISTENT_TOOL']);
168 + const exit = yield* Effect.exit(cli(['tools', 'info', 'NONEXISTENT_TOOL']));
169 const lines = yield* MockConsole.getLines({ stripAnsi: true });
170
171 expect(lines.join('\n')).toContain('Tool "NONEXISTENT_TOOL" not found.');
171 - expect(process.exitCode).toBe(1);
172 + expect(exitCodeOf(exit)).toBe(1);
173 })
174 );
175
176 it.effect('keeps a zero exit code for a valid slug', () =>
177 Effect.gen(function* () {
177 - yield* cli(['tools', 'info', 'GMAIL_SEND_EMAIL']);
178 + const exit = yield* Effect.exit(cli(['tools', 'info', 'GMAIL_SEND_EMAIL']));
179
179 - expect(process.exitCode).toBeUndefined();
180 + expect(exitCodeOf(exit)).toBe(0);
181 })
182 );
183 }
ts/packages/cli/test/src/commands/tools/info/tools.info.handler.test.ts
+3 -4
@@ -11,6 +11,7 @@ import type { Tools } from 'src/models/tools';
11 import { ComposioToolkitsRepository } from 'src/services/composio-clients';
12 import { TerminalUI } from 'src/services/terminal-ui';
13 import { MockConsole, TestLive } from 'test/__utils__';
14 +import { exitCodeOf } from 'test/__utils__/exit-code';
15 import { terminalUITestImpl } from 'test/__utils__/services/terminal-ui-test';
16 import { makeToolkitsRepositoryStub } from 'test/__utils__/services/toolkits-repository-stub';
17
@@ -76,7 +77,6 @@ describe('runToolsInfo', () => {
77 expect(isUsageFailure(failure)).toBe(true);
78 expect(yield* MockConsole.getLines()).toEqual([]);
79 expect(outputs).toEqual([]);
79 - expect(process.exitCode).toBeUndefined();
80 }).pipe(Effect.provide(layer));
81 });
82
@@ -104,7 +104,6 @@ describe('runToolsInfo', () => {
104 inputSchema: TOOLS[0]?.input_parameters,
105 });
106 expect(printed.schemaPath).toMatch(/\/tool_definitions\/GMAIL_SEND_EMAIL\.json$/);
107 - expect(process.exitCode).toBeUndefined();
107 }).pipe(Effect.provide(layer));
108 });
109
@@ -113,13 +112,13 @@ describe('runToolsInfo', () => {
112 () => {
113 const { layer, outputs } = toolsInfoTest();
114 return Effect.gen(function* () {
116 - yield* runToolsInfo({ slug: Option.some('GMAIL_SEND') });
115 + const exit = yield* Effect.exit(runToolsInfo({ slug: Option.some('GMAIL_SEND') }));
116 const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
117
118 expect(output).toContain(toolNotFoundMessage('GMAIL_SEND'));
119 expect(output).toContain('> composio tools info "GMAIL_SEND_EMAIL"');
120 expect(outputs).toEqual([]);
122 - expect(process.exitCode).toBe(1);
121 + expect(exitCodeOf(exit)).toBe(1);
122 }).pipe(Effect.provide(layer));
123 }
124 );
ts/packages/cli/test/src/commands/triggers/create/triggers.create.cmd.test.ts
+4 -5
@@ -8,7 +8,7 @@ import { ProjectContext } from 'src/services/project-context';
8 import { ComposioUserContext } from 'src/services/user-context';
9 import { cli, MockConsole, TestLive } from 'test/__utils__';
10 import { notFoundError } from 'test/__utils__/layers/not-found';
11 -import { recordingNodeProcess } from 'test/__utils__/services/node-process-test';
11 +import { exitCodeOf } from 'test/__utils__/exit-code';
12 import { makeToolkitsRepositoryStub } from 'test/__utils__/services/toolkits-repository-stub';
13
14 const testConfigProvider = ConfigProvider.fromEnv({
@@ -253,22 +253,21 @@ describe('CLI: composio dev triggers create', () => {
253 it => {
254 it.effect('prints the fallback message and the list hint', () =>
255 Effect.gen(function* () {
256 - const proc = recordingNodeProcess();
256 const repository = Layer.succeed(
257 ComposioToolkitsRepository,
258 makeToolkitsRepositoryStub({
259 createTrigger: () => Effect.fail(notFoundError('Trigger type not found')),
260 })
261 );
263 - yield* cli(['dev', 'triggers', 'create', 'UNKNOWN_TRIGGER']).pipe(
264 - Effect.provide(Layer.merge(repository, proc.layer))
262 + const exit = yield* Effect.exit(
263 + cli(['dev', 'triggers', 'create', 'UNKNOWN_TRIGGER']).pipe(Effect.provide(repository))
264 );
265 const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
266
267 expect(output).toContain('Failed to create trigger "UNKNOWN_TRIGGER".');
268 expect(output).toContain('composio dev triggers list');
269 expect(output).not.toContain('Trigger created');
271 - expect(proc.exitCode()).toBe(1);
270 + expect(exitCodeOf(exit)).toBe(1);
271 })
272 );
273 }
ts/packages/cli/test/src/commands/triggers/disable/triggers.disable.cmd.test.ts
+6 -5
@@ -3,7 +3,7 @@ import { ConfigProvider, Effect, Layer } from 'effect';
3 import { ComposioToolkitsRepository } from 'src/services/composio-clients';
4 import { cli, MockConsole, TestLive } from 'test/__utils__';
5 import { notFoundError } from 'test/__utils__/layers/not-found';
6 -import { recordingNodeProcess } from 'test/__utils__/services/node-process-test';
6 +import { exitCodeOf } from 'test/__utils__/exit-code';
7 import { makeToolkitsRepositoryStub } from 'test/__utils__/services/toolkits-repository-stub';
8
9 const testConfigProvider = ConfigProvider.fromEnv({
@@ -94,22 +94,23 @@ describe('CLI: composio dev triggers disable', () => {
94 it => {
95 it.effect('prints the fallback message and the status hint', () =>
96 Effect.gen(function* () {
97 - const proc = recordingNodeProcess();
97 const repository = Layer.succeed(
98 ComposioToolkitsRepository,
99 makeToolkitsRepositoryStub({
100 disableTrigger: () => Effect.fail(notFoundError('Trigger not found')),
101 })
102 );
104 - yield* cli(['dev', 'triggers', 'disable', 'trg_missing', '--dangerously-allow']).pipe(
105 - Effect.provide(Layer.merge(repository, proc.layer))
103 + const exit = yield* Effect.exit(
104 + cli(['dev', 'triggers', 'disable', 'trg_missing', '--dangerously-allow']).pipe(
105 + Effect.provide(repository)
106 + )
107 );
108 const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
109
110 expect(output).toContain('Failed to disable trigger "trg_missing".');
111 expect(output).toContain('composio dev triggers status');
112 expect(output).not.toContain('Trigger "trg_missing" disabled.');
112 - expect(proc.exitCode()).toBe(1);
113 + expect(exitCodeOf(exit)).toBe(1);
114 })
115 );
116 }
ts/packages/cli/test/src/commands/triggers/enable/triggers.enable.cmd.test.ts
+4 -5
@@ -4,7 +4,7 @@ import { isUsageFailure } from 'src/commands/errors';
4 import { ComposioToolkitsRepository } from 'src/services/composio-clients';
5 import { cli, MockConsole, TestLive } from 'test/__utils__';
6 import { notFoundError } from 'test/__utils__/layers/not-found';
7 -import { recordingNodeProcess } from 'test/__utils__/services/node-process-test';
7 +import { exitCodeOf } from 'test/__utils__/exit-code';
8 import { makeToolkitsRepositoryStub } from 'test/__utils__/services/toolkits-repository-stub';
9
10 const testConfigProvider = ConfigProvider.fromEnv({
@@ -64,22 +64,21 @@ describe('CLI: composio dev triggers enable', () => {
64 it => {
65 it.effect('prints the fallback message and the status hint', () =>
66 Effect.gen(function* () {
67 - const proc = recordingNodeProcess();
67 const repository = Layer.succeed(
68 ComposioToolkitsRepository,
69 makeToolkitsRepositoryStub({
70 enableTrigger: () => Effect.fail(notFoundError('Trigger not found')),
71 })
72 );
74 - yield* cli(['dev', 'triggers', 'enable', 'trg_missing']).pipe(
75 - Effect.provide(Layer.merge(repository, proc.layer))
73 + const exit = yield* Effect.exit(
74 + cli(['dev', 'triggers', 'enable', 'trg_missing']).pipe(Effect.provide(repository))
75 );
76 const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
77
78 expect(output).toContain('Failed to enable trigger "trg_missing".');
79 expect(output).toContain('composio dev triggers status --show-disabled');
80 expect(output).not.toContain('Trigger "trg_missing" enabled.');
82 - expect(proc.exitCode()).toBe(1);
81 + expect(exitCodeOf(exit)).toBe(1);
82 })
83 );
84 }
ts/packages/cli/test/src/commands/triggers/info/triggers.info.cmd.test.ts
+3 -2
@@ -1,6 +1,7 @@
1 import { afterEach, describe, expect, layer } from '@effect/vitest';
2 import { ConfigProvider, Effect } from 'effect';
3 import { cli, MockConsole, TestLive } from 'test/__utils__';
4 +import { exitCodeOf } from 'test/__utils__/exit-code';
5 import type { TriggerTypes } from 'src/models/trigger-types';
6 import type { TestLiveInput } from 'test/__utils__/services/test-layer';
7
@@ -135,7 +136,7 @@ describe('CLI: composio dev triggers info', () => {
136 it => {
137 it.effect('shows not found fallback hint', () =>
138 Effect.gen(function* () {
138 - yield* cli(['dev', 'triggers', 'info', 'NONEXISTENT_TRIGGER']);
139 + const exit = yield* Effect.exit(cli(['dev', 'triggers', 'info', 'NONEXISTENT_TRIGGER']));
140 const lines = yield* MockConsole.getLines({ stripAnsi: true });
141 const output = lines.join('\n');
142
@@ -146,7 +147,7 @@ describe('CLI: composio dev triggers info', () => {
147 'Trigger "NONEXISTENT_TRIGGER" not found.',
148 'Browse available trigger types:\n> composio dev triggers list "<toolkit>"',
149 ]);
149 - expect(process.exitCode).toBe(1);
150 + expect(exitCodeOf(exit)).toBe(1);
151 })
152 );
153 }
ts/packages/cli/test/src/commands/triggers/status/triggers.status.handler.test.ts
+6 -9
@@ -10,7 +10,7 @@ import { ComposioToolkitsRepository } from 'src/services/composio-clients';
10 import { TerminalUI } from 'src/services/terminal-ui';
11 import { MockConsole } from 'test/__utils__';
12 import { notFoundError } from 'test/__utils__/layers/not-found';
13 -import { recordingNodeProcess } from 'test/__utils__/services/node-process-test';
13 +import { exitCodeOf } from 'test/__utils__/exit-code';
14 import { terminalUITestImpl } from 'test/__utils__/services/terminal-ui-test';
15 import { makeToolkitsRepositoryStub } from 'test/__utils__/services/toolkits-repository-stub';
16
@@ -56,11 +56,9 @@ const triggersStatusTest = (fixture: TriggersStatusFixture = {}) => {
56 const outputs: Array<string> = [];
57 const requests: Array<TriggerInstanceListActiveParams> = [];
58 const items = [...(fixture.items ?? [GMAIL, SLACK])];
59 - const proc = recordingNodeProcess();
59
60 const layer = Layer.mergeAll(
61 Layer.effect(Console.Console, MockConsole.make),
63 - proc.layer,
62 Layer.succeed(
63 TerminalUI,
64 TerminalUI.of({
@@ -90,7 +88,7 @@ const triggersStatusTest = (fixture: TriggersStatusFixture = {}) => {
88 })
89 )
90 );
93 - return { layer, outputs, requests, exitCode: proc.exitCode };
91 + return { layer, outputs, requests };
92 };
93
94 const stderr = MockConsole.getLines({ stream: 'stderr', stripAnsi: true });
@@ -218,13 +216,12 @@ describe('runTriggersStatus', () => {
216 ])(
217 '[Given] nothing matches and showDisabled $showDisabled [Then] warns and outputs nothing',
218 ({ showDisabled, message }) => {
221 - const { layer, outputs, exitCode } = triggersStatusTest({ items: [] });
219 + const { layer, outputs } = triggersStatusTest({ items: [] });
220 return Effect.gen(function* () {
221 yield* runTriggersStatus({ ...noFilters, showDisabled });
222
223 expect(outputs).toEqual([]);
224 expect(yield* stderr).toEqual([message]);
227 - expect(exitCode()).toBeUndefined();
225 }).pipe(Effect.provide(layer));
226 }
227 );
@@ -242,12 +239,12 @@ describe('runTriggersStatus', () => {
239 it.effect(
240 '[Given] the API fails [Then] reports the fallback message, outputs nothing and exits 1',
241 () => {
245 - const { layer, outputs, exitCode } = triggersStatusTest({ fails: true });
242 + const { layer, outputs } = triggersStatusTest({ fails: true });
243 return Effect.gen(function* () {
247 - yield* runTriggersStatus(noFilters);
244 + const exit = yield* Effect.exit(runTriggersStatus(noFilters));
245
246 expect(outputs).toEqual([]);
250 - expect(exitCode()).toBe(1);
247 + expect(exitCodeOf(exit)).toBe(1);
248 expect(yield* stderr).toContain('Failed to fetch trigger status.');
249 expect((yield* allLines).join('\n')).toContain(
250 'Retry with:\n> composio dev triggers status --show-disabled'
ts/packages/cli/test/src/commands/triggers/triggers.listen.cmd.test.ts
+19 -20
@@ -5,6 +5,7 @@ import { ConfigProvider, Effect, Fiber, Latch, Layer } from 'effect';
5 import { ComposioCliUserConfig } from 'src/services/cli-user-config';
6 import { TriggerRealtimeSubscriptionError, TriggersRealtime } from 'src/services/triggers-realtime';
7 import { cli, TestLive } from 'test/__utils__';
8 +import { exitCodeOf } from 'test/__utils__/exit-code';
9 import { withHttpServerEffect } from 'test/__utils__/http-server';
10 import { failingFileWrites } from 'test/__utils__/services/failing-file-writes';
11 import { redirectedTerminalUI } from 'test/__utils__/services/redirected-terminal-ui';
@@ -44,14 +45,16 @@ describe('CLI: composio dev listen', () => {
45 Effect.gen(function* () {
46 yield* enableListen;
47 const terminal = redirectedTerminalUI();
47 - yield* cli(['dev', 'listen', '--max-events', '1']).pipe(
48 - Effect.provide(Layer.merge(failingRealtime, terminal.layer))
48 + const exit = yield* Effect.exit(
49 + cli(['dev', 'listen', '--max-events', '1']).pipe(
50 + Effect.provide(Layer.merge(failingRealtime, terminal.layer))
51 + )
52 );
53
54 expect(terminal.stderr()).toContain(
55 'Could not subscribe to realtime trigger events: socket closed. Check your network connection or run `composio login`.\n'
56 );
54 - expect(process.exitCode).toBe(1);
57 + expect(exitCodeOf(exit)).toBe(1);
58 })
59 );
60 }
@@ -95,8 +98,6 @@ describe('CLI: composio dev listen', () => {
98 expect(terminal.stderr()).toContain(
99 '1 event failed to forward to http://127.0.0.1:9/composio while listening.'
100 );
98 - // Recovered per-event failures, not a failed command.
99 - expect(process.exitCode).toBeUndefined();
101 })
102 );
103
@@ -105,18 +106,16 @@ describe('CLI: composio dev listen', () => {
106 Effect.gen(function* () {
107 yield* enableListen;
108 const terminal = redirectedTerminalUI();
108 - yield* cli([
109 - 'dev',
110 - 'listen',
111 - '--forward',
112 - 'http://127.0.0.1:9/composio',
113 - '--fail-fast',
114 - ]).pipe(Effect.provide(terminal.layer));
109 + const exit = yield* Effect.exit(
110 + cli(['dev', 'listen', '--forward', 'http://127.0.0.1:9/composio', '--fail-fast']).pipe(
111 + Effect.provide(terminal.layer)
112 + )
113 + );
114
115 expect(terminal.stderr()).toContain(
116 '1 event failed to forward to http://127.0.0.1:9/composio while listening.'
117 );
119 - expect(process.exitCode).toBe(1);
118 + expect(exitCodeOf(exit)).toBe(1);
119 })
120 );
121
@@ -137,8 +136,6 @@ describe('CLI: composio dev listen', () => {
136 expect(terminal.stderr()).toContain(
137 `1 event failed to append to ${outFile} while listening.`
138 );
140 - // Recovered per-event failures, not a failed command.
141 - expect(process.exitCode).toBeUndefined();
139 })
140 );
141
@@ -160,12 +157,13 @@ describe('CLI: composio dev listen', () => {
157
158 yield* forwardFailed.await;
159 yield* Fiber.interrupt(fiber);
160 + const exit = yield* Fiber.await(fiber);
161
162 expect(terminal.stderr()).toContain(
163 '1 event failed to forward to http:// while listening.'
164 );
167 - // Recovered per-event failures, not a failed command.
168 - expect(process.exitCode).toBeUndefined();
165 + // Recovered per-event failures, not a failed command: interrupted, so 130.
166 + expect(exitCodeOf(exit)).toBe(130);
167 })
168 );
169 });
@@ -288,7 +286,7 @@ describe('CLI: composio dev listen', () => {
286 const terminal = redirectedTerminalUI();
287 const held: Array<ServerResponse> = [];
288 let requests = 0;
291 - yield* withHttpServerEffect(
289 + const exit = yield* withHttpServerEffect(
290 (_req, res) => {
291 requests += 1;
292 if (requests === 1) res.end();
@@ -298,14 +296,15 @@ describe('CLI: composio dev listen', () => {
296 url =>
297 cli(['dev', 'listen', '--forward', url, '--max-events', '3', '--fail-fast']).pipe(
298 Effect.provide(terminal.layer),
301 - Effect.ensuring(Effect.sync(() => held.forEach(res => res.end())))
299 + Effect.ensuring(Effect.sync(() => held.forEach(res => res.end()))),
300 + Effect.exit
301 )
302 );
303
304 expect(terminal.stderr()).toMatch(
305 /1 event failed to forward to http:\/\/127\.0\.0\.1:\d+ while listening\./
306 );
308 - expect(process.exitCode).toBe(1);
307 + expect(exitCodeOf(exit)).toBe(1);
308 })
309 );
310 });
ts/packages/cli/test/src/effects/handle-http-error.test.ts
+33 -36
@@ -9,9 +9,10 @@ import {
9 import { describe, expect, it } from '@effect/vitest';
10 import { Effect } from 'effect';
11 import { handleClientApiError } from 'src/effects/handle-http-error';
12 +import { ReportedFailure } from 'src/effects/report-failure';
13 import { CLIENT_API_ERROR_TAGS } from 'src/services/composio-errors';
14 import { TerminalUI } from 'src/services/terminal-ui';
14 -import { recordingNodeProcess } from 'test/__utils__/services/node-process-test';
15 +import { exitCodeOf } from 'test/__utils__/exit-code';
16 import { terminalUITestImpl } from 'test/__utils__/services/terminal-ui-test';
17
18 const envelope = {
@@ -50,12 +51,10 @@ const clientDecodeError = new ClientDecodeError({
51 const options = {
52 fallbackMessage: 'Failed to fetch auth config "ac_missing".',
53 hint: 'Browse available auth configs:\n> composio dev auth-configs list',
53 - fallbackValue: 'fallback' as const,
54 };
55
56 // A TerminalUI whose stderr is not a TTY, recording every line the handler
57 -// writes together with the channel it went to, and a NodeProcess recording
58 -// the exit code it sets.
57 +// writes together with the channel it went to.
58 const recordingUI = () => {
59 const lines: Array<string> = [];
60 const record = (channel: string) => (message: string) =>
@@ -67,23 +66,21 @@ const recordingUI = () => {
66 error: record('stderr'),
67 log: { ...terminalUITestImpl.log, error: record('log.error'), step: record('log.step') },
68 });
70 - const proc = recordingNodeProcess();
71 - return { ui, lines, exitCode: proc.exitCode, provide: Effect.provide(proc.layer) };
69 + return { ui, lines };
70 };
71
72 describe('handleClientApiError', () => {
73 it.effect('prints the envelope message and the suggested fix, and fails the process', () =>
74 Effect.gen(function* () {
77 - const { ui, lines, exitCode, provide } = recordingUI();
75 + const { ui, lines } = recordingUI();
76
79 - const result = yield* handleClientApiError(ui, options)(clientStatusError).pipe(provide);
77 + const exit = yield* Effect.exit(handleClientApiError(ui, options)(clientStatusError));
78
81 - expect(result).toBe('fallback');
79 expect(lines).toStrictEqual([
80 'stderr: Auth config "ac_missing" was not found',
81 'stderr: Check the auth config id\n\nBrowse available auth configs:\n> composio dev auth-configs list',
82 ]);
86 - expect(exitCode()).toBe(1);
83 + expect(exitCodeOf(exit)).toBe(1);
84 })
85 );
86
@@ -98,41 +95,41 @@ describe('handleClientApiError', () => {
95 new ClientAPIConnectionTimeoutError({ message: 'Request timed out.', method: 'GET', url }),
96 ])('prints the fallback message for $_tag', error =>
97 Effect.gen(function* () {
101 - const { ui, lines, exitCode, provide } = recordingUI();
98 + const { ui, lines } = recordingUI();
99
103 - const result = yield* handleClientApiError(ui, options)(error).pipe(provide);
100 + const exit = yield* Effect.exit(handleClientApiError(ui, options)(error));
101
105 - expect(result).toBe('fallback');
102 expect(lines).toStrictEqual([
103 'stderr: Failed to fetch auth config "ac_missing".',
104 'stderr: Browse available auth configs:\n> composio dev auth-configs list',
105 ]);
110 - expect(exitCode()).toBe(1);
106 + expect(exitCodeOf(exit)).toBe(1);
107 })
108 );
109
110 it.effect('names the operation and request id of a decode failure and suggests an upgrade', () =>
111 Effect.gen(function* () {
116 - const { ui, lines, exitCode, provide } = recordingUI();
117 -
118 - const result = yield* handleClientApiError(ui, {
119 - ...options,
120 - searchForSuggestions: () =>
121 - Effect.succeed([{ label: 'ac_similar', command: '> composio dev auth-configs info' }]),
122 - })(clientDecodeError).pipe(provide);
112 + const { ui, lines } = recordingUI();
113 +
114 + const exit = yield* Effect.exit(
115 + handleClientApiError(ui, {
116 + ...options,
117 + searchForSuggestions: () =>
118 + Effect.succeed([{ label: 'ac_similar', command: '> composio dev auth-configs info' }]),
119 + })(clientDecodeError)
120 + );
121
124 - expect(result).toBe('fallback');
122 expect(lines).toStrictEqual([
123 "stderr: The API response for 'authConfigs.retrieve' is not in the shape this version of the CLI expects (request id: req_decode).",
124 'stderr: Upgrade the CLI, then retry:\n> composio upgrade',
125 ]);
129 - expect(exitCode()).toBe(1);
126 + expect(exitCodeOf(exit)).toBe(1);
127 })
128 );
129
130 it.effect('replaces the hint with suggestions when the search finds some', () =>
131 Effect.gen(function* () {
135 - const { ui, lines, provide } = recordingUI();
132 + const { ui, lines } = recordingUI();
133
134 yield* handleClientApiError(ui, {
135 ...options,
@@ -140,7 +137,7 @@ describe('handleClientApiError', () => {
137 Effect.succeed([
138 { label: 'ac_similar', command: '> composio dev auth-configs info "ac_similar"' },
139 ]),
143 - })(clientStatusError).pipe(provide);
140 + })(clientStatusError).pipe(Effect.flip);
141
142 expect(lines.at(-1)).toBe(
143 'stderr: Check the auth config id\n\nDid you mean?\n ac_similar\n\n> composio dev auth-configs info "ac_similar"'
@@ -161,36 +158,36 @@ describe('Effect.catchTag(CLIENT_API_ERROR_TAGS, handleClientApiError(...))', ()
158 description: 'fetch failed',
159 }),
160 new ClientAPIConnectionTimeoutError({ message: 'Request timed out.', method: 'GET', url }),
164 - ])('recovers from $_tag with the fallback value', error =>
161 + ])('reports $_tag and fails already reported', error =>
162 Effect.gen(function* () {
166 - const { ui, lines, exitCode, provide } = recordingUI();
163 + const { ui, lines } = recordingUI();
164
168 - // The tag list recovers from the client's whole error union.
169 - const result = yield* Effect.fail<ComposioError>(error).pipe(
170 - Effect.catchTag(CLIENT_API_ERROR_TAGS, handleClientApiError(ui, options)),
171 - provide
165 + // The tag list catches the client's whole error union.
166 + const exit = yield* Effect.exit(
167 + Effect.fail<ComposioError>(error).pipe(
168 + Effect.catchTag(CLIENT_API_ERROR_TAGS, handleClientApiError(ui, options))
169 + )
170 );
171 + const failure = yield* Effect.flip(exit);
172
174 - expect(result).toBe('fallback');
173 + expect(failure).toBeInstanceOf(ReportedFailure);
174 expect(lines).not.toStrictEqual([]);
176 - expect(exitCode()).toBe(1);
175 + expect(exitCodeOf(exit)).toBe(1);
176 })
177 );
178
179 it.effect('leaves other failures alone', () =>
180 Effect.gen(function* () {
182 - const { ui, lines, exitCode, provide } = recordingUI();
181 + const { ui, lines } = recordingUI();
182 const error = new ClientConfigurationError({ message: 'No credential.' });
183
184 const failure = yield* Effect.fail<ComposioError>(error).pipe(
185 Effect.catchTag(CLIENT_API_ERROR_TAGS, handleClientApiError(ui, options)),
187 - provide,
186 Effect.flip
187 );
188
189 expect(failure).toBe(error);
190 expect(lines).toStrictEqual([]);
193 - expect(exitCode()).toBeUndefined();
191 })
192 );
193 });
ts/packages/cli/test/src/effects/report-failure.test.ts
+43 -15
@@ -1,8 +1,8 @@
1 import { describe, expect, it } from '@effect/vitest';
2 -import { Effect } from 'effect';
3 -import { reportFailure } from 'src/effects/report-failure';
2 +import { Effect, Runtime } from 'effect';
3 +import { printFailure, reportFailure, ReportedFailure } from 'src/effects/report-failure';
4 import { getTerminalCapabilities, TerminalUI } from 'src/services/terminal-ui';
5 -import { recordingNodeProcess } from 'test/__utils__/services/node-process-test';
5 +import { exitCodeOf } from 'test/__utils__/exit-code';
6 import { redirectedTerminalUI } from 'test/__utils__/services/redirected-terminal-ui';
7 import { terminalUITestImpl } from 'test/__utils__/services/terminal-ui-test';
8
@@ -33,45 +33,73 @@ describe('reportFailure', () => {
33 '[Given] a redirected stderr [Then] prints the message and hint plainly and exits 1',
34 () => {
35 const terminal = redirectedTerminalUI();
36 - const proc = recordingNodeProcess();
36 return Effect.gen(function* () {
37 const ui = yield* TerminalUI;
38
40 - yield* reportFailure(ui, 'Failed to fetch toolkit "gmail".', 'Browse available toolkits');
39 + const exit = yield* Effect.exit(
40 + reportFailure(ui, 'Failed to fetch toolkit "gmail".', 'Browse available toolkits')
41 + );
42
43 expect(terminal.stderr()).toBe(
44 'Failed to fetch toolkit "gmail".\nBrowse available toolkits\n'
45 );
46 expect(terminal.stdout()).toBe('');
46 - expect(proc.exitCode()).toBe(1);
47 - }).pipe(Effect.provide(terminal.layer), Effect.provide(proc.layer));
47 + expect(exitCodeOf(exit)).toBe(1);
48 + }).pipe(Effect.provide(terminal.layer));
49 }
50 );
51
52 it.effect('[Given] no hint [Then] prints only the message', () => {
53 const terminal = redirectedTerminalUI();
53 - const proc = recordingNodeProcess();
54 return Effect.gen(function* () {
55 const ui = yield* TerminalUI;
56
57 - yield* reportFailure(ui, 'The link response is incomplete.');
57 + const exit = yield* Effect.exit(reportFailure(ui, 'The link response is incomplete.'));
58
59 expect(terminal.stderr()).toBe('The link response is incomplete.\n');
60 - expect(proc.exitCode()).toBe(1);
61 - }).pipe(Effect.provide(terminal.layer), Effect.provide(proc.layer));
60 + expect(exitCodeOf(exit)).toBe(1);
61 + }).pipe(Effect.provide(terminal.layer));
62 });
63
64 it.effect('[Given] a terminal [Then] renders a decorated error and step, once', () => {
65 const { ui, lines } = decoratingUI();
66 - const proc = recordingNodeProcess();
66 return Effect.gen(function* () {
68 - yield* reportFailure(ui, 'Failed to fetch toolkit "gmail".', 'Browse available toolkits');
67 + const exit = yield* Effect.exit(
68 + reportFailure(ui, 'Failed to fetch toolkit "gmail".', 'Browse available toolkits')
69 + );
70
71 expect(lines).toEqual([
72 'log.error: Failed to fetch toolkit "gmail".',
73 'log.step: Browse available toolkits',
74 ]);
74 - expect(proc.exitCode()).toBe(1);
75 - }).pipe(Effect.provide(proc.layer));
75 + expect(exitCodeOf(exit)).toBe(1);
76 + });
77 + });
78 +
79 + // `BunRuntime.runMain` logs a failure unless it carries `[Runtime.errorReported] = false`, so
80 + // the marker is what keeps the report from printing twice.
81 + it.effect('[Given] a report [Then] fails with a ReportedFailure the runtime does not log', () => {
82 + const { ui } = decoratingUI();
83 + return Effect.gen(function* () {
84 + const failure = yield* Effect.flip(reportFailure(ui, 'Toolkit "gmail" not found.'));
85 +
86 + expect(failure).toBeInstanceOf(ReportedFailure);
87 + expect(failure.message).toBe('Toolkit "gmail" not found.');
88 + expect(Runtime.getErrorReported(failure)).toBe(false);
89 + expect(Runtime.getErrorExitCode(failure)).toBe(1);
90 + });
91 + });
92 +});
93 +
94 +describe('printFailure', () => {
95 + it.effect('[Given] a failure [Then] prints it like reportFailure and succeeds', () => {
96 + const terminal = redirectedTerminalUI();
97 + return Effect.gen(function* () {
98 + const ui = yield* TerminalUI;
99 +
100 + yield* printFailure(ui, 'Failed to fetch toolkits.', 'Retry later');
101 +
102 + expect(terminal.stderr()).toBe('Failed to fetch toolkits.\nRetry later\n');
103 + }).pipe(Effect.provide(terminal.layer));
104 });
105 });
ts/packages/cli/test/src/services/composio-clients.test.ts
+8 -8
@@ -22,7 +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';
25 +import { exitCodeOf } from 'test/__utils__/exit-code';
26
27 // Exercise real user-context/config resolution without opening the OS credential store.
28 vi.mock('@composio/cli-keyring/effect', async importOriginal => {
@@ -590,18 +590,18 @@ describe('composio-clients', () => {
590 step: message => Effect.sync(() => void steps.push(message)),
591 },
592 });
593 - const proc = recordingNodeProcess();
594 - yield* handleClientApiError(ui, {
595 - fallbackMessage: 'fallback',
596 - hint: 'hint',
597 - fallbackValue: undefined,
598 - })(error).pipe(Effect.provide(proc.layer));
593 + const exit = yield* Effect.exit(
594 + handleClientApiError(ui, {
595 + fallbackMessage: 'fallback',
596 + hint: 'hint',
597 + })(error)
598 + );
599
600 // On a non-TTY the failure is two plain stderr lines: the message, then the hint.
601 expect(plain).toEqual(['Bad input', 'hint']);
602 expect(errors).toEqual([]);
603 expect(steps).toEqual([]);
604 - expect(proc.exitCode()).toBe(1);
604 + expect(exitCodeOf(exit)).toBe(1);
605 }).pipe(Effect.provide(withRepository))
606 );
607