@devries-cameron20 / composio-1 / commits / d5aa9f67a
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): run argv tests through the full invocation (#5132)

This PR: - builds on top of https://github.com/ComposioHQ/composio/pull/5129, now merged; rebased onto `next` - moves the invocation pipeline out of `cli-main.ts` into `src/invocation/invocation.ts` (`runInvocation(argv)`) and the production layers into `src/invocation/live.ts` (`InvocationLive`); `runCli` keeps the runner, `ShutdownSignal`, and `ConfigProvider` wiring - `runInvocation` prints every failure once and then fails with the command's own cause; `forRunner` / `runnerCause` mark what it printed as reported for the runner, so binary output and exit codes stay the same - keeps the interrupt handling from https://github.com/ComposioHQ/composio/pull/5128 in `reportInvocationFailure`, the catch-all `runInvocation` ends with: an interruption alone is not printed and reaches the runner untouched (130, or 128 + n after a signal), and a cause with nothing to print fails as it came instead of succeeding. Its test moves to `test/src/invocation/report-invocation-failure.test.ts` - `cli()` now runs the full invocation (hooks, lifecycle telemetry, the command, failure printing) and still fails with the typed error; `cliExit(args)` returns `{ exit, exitCode }`, and `exitCodeOf` uses the runner's own mapping (`runnerExit`, then `exitActionFor`) - adds `resetInvocationCalls` to the TestLive recorder and removes the 26 test files' `process.exitCode = undefined` resets - 15 argv tests that asserted an empty stderr after an expected failure now expect the one line the invocation prints. `dev init` with the API unreachable shows the defect report after its guidance, and `execute`'s first toolkit lookup is the unscoped one telemetry makes - moves the help/version telemetry, missing login/org, usage error, and bare `run` cases from the spawned `test/src/cli-main.test.ts` (805 → 584 lines) to the in-process `test/src/invocation/invocation.test.ts`; the bootstrap, stored-login backend, HTTP, and signal cases still spawn ## Context The two test findings in the last bullet are current production behavior, now visible to argv tests. This PR does not change either one. Verification: `pnpm typecheck`, `pnpm --filter @composio/cli run lint:effect`, `pnpm --filter @composio/cli test` (218 files, 2641 passed, 1 skipped), `oxlint ts/packages/cli`, the skill validators and `check-examples.mjs`. For `whoami`, `help orgz`, `--version`, `run`, and `tools list`, `bun run src/bin.ts` gives the same stdout, stderr, and exit codes as the base branch.

Alberto Schiabel committed Oct 28, 2026 at 17:17 UTC d5aa9f67a17b0dedca3ba434e270ffb72d363814
70 files changed +819 -781
.agents/skills/cli-command/references/implementation.md
+1 -1
@@ -16,7 +16,7 @@ test/src/commands/<group>/<name>/<group>.<name>.handler.test.ts handler-level
16
17 - Top-level commands use the same shape without a group: `src/commands/<name>/<name>.cmd.ts`.
18 - Register new commands through `src/commands/index.ts` or the nearest group entry.
19 -- A usage mistake the parser cannot see (flag combination, business rule, missing input) raises `CommandInputError` via `commandInputError('<command>')` from `src/commands/errors.ts`, with the `option` at fault; `cli-main.ts` prints the message and exits 1. Do not add a per-command message-only error class.
19 +- A usage mistake the parser cannot see (flag combination, business rule, missing input) raises `CommandInputError` via `commandInputError('<command>')` from `src/commands/errors.ts`, with the `option` at fault; the invocation (`src/invocation/invocation.ts`) prints the message and exits 1. Do not add a per-command message-only error class.
20 - A command that needs a login pipes `requireLogin` from `src/effects/require-auth.ts` on itself or on its group entry after `Command.withSubcommands`; the handler never checks `apiKey`. `resolveCommandProject` fails with `ProjectResolutionError` and `resolveConnectedAccountForToolkit` with `ConnectedAccountResolutionError`; let them flow, they print and exit 1 like `CommandInputError`.
21 - A command still in the legacy single-file shape (`<group>/commands/<group>.<name>.cmd.ts`, or top-level `<name>.cmd.ts`) is migrated in the PR that next changes it substantively, one command per PR.
22 - `pnpm run validate:command-tests` (in `pnpm test`) fails on a command without its mirrored `.cmd.test.ts`, on an orphan `.cmd.test.ts`, and on a stale exemption. Add the test with the command; do not add exemptions.
.agents/skills/effect-v4/references/cli-surface.md
+13 -12
@@ -4,8 +4,8 @@
4 `Command`, `Flag` (was `Options`), `Argument` (was `Args`), `GlobalFlag` (was
5 `BuiltInOptions`), `CliConfig`, `CliOutput`, `CliError` (was `ValidationError`/
6 `HelpDoc`). Ground truth for this reference is
7 -`ts/packages/cli/src/cli-config.ts` and `ts/packages/cli/src/cli-main.ts` — read their
8 -full module docstrings before touching the runner, not just the excerpts below.
7 +`ts/packages/cli/src/cli-config.ts`, `ts/packages/cli/src/cli-main.ts`, and
8 +`ts/packages/cli/src/invocation/invocation.ts` — read their full module docstrings before touching the runner, not just the excerpts below.
9
10 ## Command shape
11
@@ -59,7 +59,7 @@ longer reproduces either behavior:
59 exact, so case-sensitivity needs no config.
60
61 `ComposioCliConfig`'s `builtIns` narrowing is the _only_ `CliConfig` customization
62 -Composio makes. There is no custom `CliOutput.Formatter` — `cli-main.ts` provides no
62 +Composio makes. There is no custom `CliOutput.Formatter` — `InvocationLive` provides no
63 `CliOutput.layer(...)` at all, so `Command.runWith` uses v4's own
64 `CliOutput.defaultFormatter()` for everything: suggestions render as-is. An earlier revision of this file
65 wrapped `defaultFormatter()` to strip suggestions and flatten `formatVersion` back to a
@@ -104,20 +104,21 @@ through `Runtime.defaultTeardown`: 0 on success, and otherwise with the squashed
104 `errorExitCode` (1 when unset). An exit made of interruptions alone after a signal is 128 + the
105 signal's number instead (130, 143, 129). Nothing in `src/` assigns `process.exitCode`.
106
107 -`cli-main.ts`'s sandboxed catch-all handler drops every failure whose `errorReported` is
108 -false (`ShowHelp` included) from the cause; when nothing is left it re-fails with the
109 -original `Cause` via `Effect.failCause(cause)`, so the failure reaches
110 -the runner untouched and the markers take over. If you add rendering anywhere in
111 -this path, you will double-print — this is the single most important rule when touching
112 -the runner. Whatever is left is a genuine defect, captured via `effect-errors`, printed,
113 -and re-failed as a `ReportedFailure`; `Command.runWith` never renders that path, so
114 -appending help text there is not a double-print.
107 +`runInvocation` (`src/invocation/invocation.ts`) skips every failure whose `errorReported`
108 +is false (`ShowHelp` included); when nothing is left it prints nothing. If you add rendering
109 +anywhere in this path, you will double-print — this is the single most important rule when
110 +touching the runner. It prints an expected failure's message, a rejected key's hint, or, for
111 +whatever else is left, the defect report captured via `effect-errors`, then re-fails with the
112 +original `Cause`, so tests still match the typed error. `forRunner` (in `cli-main.ts`'s
113 +pipeline) turns what the invocation printed into a `ReportedFailure` and passes failures
114 +already on screen untouched, so the markers take over. `Command.runWith` never renders the
115 +defect path, so appending help text there is not a double-print.
116
117 ## argv preprocessing and the executable-prefix contract
118
119 `Command.runWith(rootCommand, { version })` expects argv **without** the node/bun
120 executable and script path prefix — unlike v3's `Command.run`, which stripped that
120 -prefix internally. `cli-main.ts` still passes the _full_ `process.argv` into
121 +prefix internally. `runInvocation` still passes the _full_ `process.argv` into
122 `runWithConfig` (from `src/commands`); that module is responsible for slicing
123 `argv.slice(2)` immediately before calling `Command.runWith`. Do not change this
124 boundary without updating both sides together.
.agents/skills/effect-v4/references/core-patterns.md
+1 -1
@@ -45,7 +45,7 @@ own class before writing `.Default` or `.layer`** — the two names are not
45 interchangeable and picking the wrong one is a real compile error, not a style nit.
46
47 For services with dependencies, compose the layer where it is consumed rather than
48 -inside the class, e.g. `ts/packages/cli/src/cli-main.ts`:
48 +inside the class, e.g. `ts/packages/cli/src/invocation/live.ts`:
49
50 ```ts
51 import * as BunFileSystem from '@effect/platform-bun/BunFileSystem';
ts/packages/cli/AGENTS.md
+6 -6
@@ -14,9 +14,9 @@ This package pins its `typescript` dependency to TypeScript 6 (`catalog:ts6` in
14
15 The CLI is built on the **Effect.ts ecosystem** and runs on **Bun**. Service-oriented architecture with dependency injection via Effect layers, generator-based control flow (`Effect.gen`), and structured error handling.
16
17 -### Entry Point — `src/bin.ts` / `src/cli-main.ts`
17 +### Entry Point — `src/bin.ts` / `src/cli-main.ts` / `src/invocation/`
18
19 -`bin.ts` is a thin bootstrap: it routes background-worker invocations (analytics dispatch) through a minimal layer set and otherwise passes argv unchanged to the dynamically imported `cli-main.ts`, which composes the full Effect layer stack and drives the root command through `effect/cli`'s `Command.runWith`, run by the CLI's own runner (`makeCliRunMain` in `src/run-main.ts`, built on `Runtime.makeRunMain`). Key layers (see `cli-main.ts` for the complete list):
19 +`bin.ts` is a thin bootstrap: it routes background-worker invocations (analytics dispatch) through a minimal layer set and otherwise passes argv unchanged to the dynamically imported `cli-main.ts`. `cli-main.ts` runs one invocation (`runInvocation` in `src/invocation/invocation.ts`: the invocation hooks, lifecycle telemetry, `effect/cli`'s `Command.runWith` and the selected command, and the one place a failure is put on screen) over the production layer stack (`InvocationLive` in `src/invocation/live.ts`), run by the CLI's own runner (`makeCliRunMain` in `src/run-main.ts`, built on `Runtime.makeRunMain`). Tests enter the same `runInvocation` through `cli()` over `TestLive`. Key layers (see `src/invocation/live.ts` for the complete list):
20
21 - `CliConfigLive` — `effect/cli` `CliConfig` restricted to `builtIns: [Help, GlobalFlag.Version]` (see Configuration below); a small `CliOutput.Formatter` keeps versions bare and appends a short root overview; Effect generates command help and parse errors
22 - `ComposioUserContextLive` — User authentication state from `~/.composio/`
@@ -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 the runner'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 the runner exits through `Runtime.defaultTeardown`: 0 on success, 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`.
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 the runner's automatic error log) and `[Runtime.errorExitCode]` (1 alongside parse errors). `runInvocation` prints every failure not yet on screen (an expected failure's message, a rejected key, or the defect report), never one already on screen (`[Runtime.errorReported] = false`, `ShowHelp` included), and fails with the command's own `Cause`, so tests can match its typed error. `forRunner` hands that to the runner with what it printed marked reported (`ReportedFailure`), keeping the markers of failures already on screen, and the runner exits through `Runtime.defaultTeardown`: 0 on success, 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`. In tests, `cliExit(args)` returns `{ exit, exitCode }` and `exitCodeOf(exit)` the code, both mapped the way `runCli` maps them (`runnerExit`, then the runner's `exitActionFor`).
29
30 Signals belong to the runner, the one place that installs SIGINT, SIGTERM and SIGHUP handlers; never add `process.on` for them elsewhere. It hands the first signal to the invocation's `ShutdownSignal` service (`src/services/shutdown-signal.ts`). A command that registered with `cooperate` for that signal stops by itself and ends normally: `listen` and `dev triggers listen` register `LISTENER_STOP` (SIGINT, SIGTERM) once Pusher confirms the subscription, through `TriggersRealtime`'s `onSubscribed`, and exit 0; `run` registers every signal, forwards it to its script's process group, and mirrors how the script ended (its code, or `ChildProcessSignaled`, whose signal the runner re-raises; when the CLI's own SIGTERM/SIGKILL escalation ended the script, the first signal instead). Every other command is interrupted, and an exit made of interruptions alone after a signal is 128 + its number: 130 (SIGINT), 143 (SIGTERM), 129 (SIGHUP). A second signal, or a stop longer than `SHUTDOWN_DEADLINE` (10 seconds), forces the exit: 128 + n, or for `run`, kill the script's group and re-raise.
31
@@ -101,7 +101,7 @@ Legacy shape still present while commands migrate: `<group>/commands/<group>.<na
101 Tests mirror `src/commands/` under `test/src/commands/`, with the legacy `commands/` path segment removed:
102
103 ```
104 -test/src/commands/<group>/<name>/<group>.<name>.cmd.test.ts argv-level: cli([...]) over TestLive
104 +test/src/commands/<group>/<name>/<group>.<name>.cmd.test.ts argv-level: cli([...]) (the full invocation) over TestLive
105 test/src/commands/<group>/<name>/<group>.<name>.handler.test.ts handler-level: Service.of doubles, no argv
106 test/src/commands/<group>/<name>/<group>.<name>.<aspect>.cmd.test.ts extra suite for one aspect (.client. for API-shape coverage)
107 test/src/commands/<group>/<shared-module>.test.ts group helper tests (triggers/format.test.ts)
@@ -131,7 +131,7 @@ Every Composio API request goes through an Effect client from `@composio/client/
131
132 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.
133
134 -`cli-main.ts` runs `BackendMismatchWarning`, `UpdateNotice`, and `PluginHint` (each an `InvocationHookShape` from `src/services/invocation-hook.ts`, taking a `HookInvocation`) in that order before parsing, and reports the command's lifecycle through `CommandLifecycleTelemetry`. `TestLive` provides recording no-op doubles of all four (`test/__utils__/layers/invocation-hooks.ts`); `recordedInvocationCalls` returns what they were called with.
134 +The invocation runs `BackendMismatchWarning`, `UpdateNotice`, and `PluginHint` (each an `InvocationHookShape` from `src/services/invocation-hook.ts`, taking a `HookInvocation`) in that order before parsing, and reports the command's lifecycle through `CommandLifecycleTelemetry`. `TestLive` replaces all four with recording no-op doubles (`test/__utils__/layers/invocation-hooks.ts`), so a test's output is its command's own; `recordedInvocationCalls` returns what they were called with, and `resetInvocationCalls` clears them between tests that share a layer.
135
136 OS credential storage uses the sibling package `@composio/cli-keyring` (macOS Keychain / Linux Secret Service).
137
@@ -230,7 +230,7 @@ Each nested `Arr.flatMap` adds one independent axis; the innermost `Arr.map` bui
230 - 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.
231 - 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.
232 - 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).
233 -- 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.
233 +- 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 the invocation 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.
234 - 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.
235
236 ### Effect Boundary Policy
ts/packages/cli/src/cli-main.ts
+19 -340
@@ -1,298 +1,23 @@
1 /**
2 - * Composes the CLI layers and runs Effect's command parser. Command.runWith renders
3 - * help and parse errors once. runWithConfig accepts full argv and removes the executable prefix.
2 + * Runs one invocation (`src/invocation/invocation.ts`) as the process: over the production
3 + * services (`InvocationLive`), under the CLI's own runner. The invocation takes the full argv;
4 + * `runWithConfig` removes the executable prefix before `Command.runWith` parses it.
5 *
6 * 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 the runner logs nothing, and `Runtime.defaultTeardown`
8 - * exits with its `[Runtime.errorExitCode]` (1 when unset), or 0 on success. Signals are the
9 - * runner's (`src/run-main.ts`): a command a signal cancelled exits 128 + its number.
7 + * already on screen (ShowHelp, a command's own report, or a message the invocation printed)
8 + * reaches the runner with `[Runtime.errorReported] = false` (`forRunner`), so the runner logs
9 + * nothing, and `Runtime.defaultTeardown` exits with its `[Runtime.errorExitCode]` (1 when unset),
10 + * or 0 on success. Signals are the runner's (`src/run-main.ts`): a command a signal cancelled
11 + * exits 128 + its number.
12 */
11 -import { Cause, ConfigProvider, Effect, Layer, Logger, Runtime } from 'effect';
12 -import * as Path from 'effect/Path';
13 -import { captureErrors, prettyPrintFromCapturedErrors } from 'effect-errors/index';
14 -import { CliConfig, CliError } from 'effect/cli';
15 -import { FetchHttpClient } from 'effect/http';
16 -import * as BunServices from '@effect/platform-bun/BunServices';
17 -import * as BunFileSystem from '@effect/platform-bun/BunFileSystem';
18 -import * as BunPath from '@effect/platform-bun/BunPath';
19 -import { runWithConfig, type RootCommandBootstrap } from 'src/commands';
20 -import { withoutClientNotices } from 'src/effects/without-client-notices';
21 -import * as constants from 'src/constants';
22 -import { ComposioCliConfig } from 'src/cli-config';
23 -import {
24 - ComposioClientSingleton,
25 - ComposioSessionRepository,
26 - ComposioToolkitsRepository,
27 -} from 'src/services/composio-clients';
28 -import { ComposioToolkitsRepositoryCached } from 'src/services/composio-clients-cached';
29 -import { NodeOs } from 'src/services/node-os';
30 -import { NodeProcess } from 'src/services/node-process';
31 -import { JsPackageManagerDetector } from 'src/services/js-package-manager-detector';
32 -import { ComposioCliUserConfigLive } from 'src/services/cli-user-config';
33 -import { ComposioUserContextLive as _ComposioUserContextLive } from 'src/services/user-context';
34 -import { isRejectedUserApiKey, rejectedUserApiKeyHint } from 'src/effects/rejected-user-api-key';
35 -import { extractMessage } from 'src/utils/api-error-extraction';
36 -import { UpgradeBinary } from 'src/services/upgrade-binary';
37 -import { TerminalUI, TerminalUILive } from 'src/services/terminal-ui';
38 -import { TriggersRealtime } from 'src/services/triggers-realtime';
39 -import { ToolsExecutorLive as _ToolsExecutorLive } from 'src/services/tools-executor';
40 -import { DashboardToolExecution } from 'src/services/dashboard-tool-execution';
41 -import { ToolkitSlugCatalog } from 'src/services/toolkit-slug-catalog';
42 -import { ProjectContext } from 'src/services/project-context';
43 -import { ProjectEnvironmentDetector } from 'src/services/project-environment-detector';
44 -import { CommandRunner } from 'src/services/command-runner';
45 -import { StdinLive } from 'src/services/stdin';
46 -import { PluginHint } from 'src/services/plugin-hint';
47 -import { UpdateNotice } from 'src/services/update-check';
48 -import { BackendMismatchWarning } from 'src/services/backend-mismatch-warning';
49 -import type { HookInvocation } from 'src/services/invocation-hook';
50 -import { CommandLifecycleTelemetry } from 'src/services/command-lifecycle-telemetry';
51 -import {
52 - configureCliAnalyticsReleaseVersion,
53 - createCliCommandTelemetryContext,
54 - getExecuteCommandToolSlug,
55 -} from 'src/analytics/events';
56 -import { getVersion } from 'src/effects/version';
57 -import { LogLevelFromConfigLive } from 'src/effects/with-log-level';
58 -import { toolkitFromToolSlug } from 'src/effects/toolkit-from-tool-slug';
59 -import { mapOnlyComposioOverrideError } from 'src/services/composio-error-overrides';
60 -import { SetupSkillInstaller } from 'src/services/setup-skill-installer';
61 -import { PendingLoginSession } from 'src/services/pending-login-session';
62 -import { isExpectedFailure, type ExpectedFailure } from 'src/effects/expected-failure';
63 -import { ReportedFailure } from 'src/effects/report-failure';
64 -import { cliInvocationContext } from 'src/services/runtime-cli-context';
13 +import { ConfigProvider, Effect } from 'effect';
14 +import { forRunner, runInvocation } from 'src/invocation/invocation';
15 +import { InvocationLive } from 'src/invocation/live';
16 import { readTelemetryDebugOverride, telemetryDebugModeLayer } from 'src/services/runtime-flags';
17 import { normalizeRunScriptArgs } from 'src/commands/argv-compat';
18 import { makeShutdownController, ShutdownSignal } from 'src/services/shutdown-signal';
19 import { makeCliRunMain } from 'src/run-main';
20
70 -// Layer is contravariant in ROut and covariant in E, so `never`/`unknown` accept any
71 -// produced context and error type while still pinning the requirements (RIn) to `never`.
72 -type RequiredLayer = Layer.Layer<never, unknown, never>;
73 -
74 -export const CliConfigLive = CliConfig.layer(ComposioCliConfig) satisfies RequiredLayer;
75 -
76 -export const ComposioUserContextLive = Layer.provide(
77 - _ComposioUserContextLive,
78 - Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOs.Default)
79 -) satisfies RequiredLayer;
80 -
81 -export const ComposioCliUserConfigLayer = Layer.provide(
82 - ComposioCliUserConfigLive,
83 - Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOs.Default)
84 -);
85 -
86 -export const ComposioSessionRepositoryLive = Layer.provide(
87 - ComposioSessionRepository.Default,
88 - Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOs.Default)
89 -) satisfies RequiredLayer;
90 -
91 -export const ComposioToolkitsRepositoryLive = Layer.provide(
92 - ComposioToolkitsRepository.Default,
93 - Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOs.Default, LogLevelFromConfigLive)
94 -) satisfies RequiredLayer;
95 -
96 -export const ComposioToolkitsRepositoryCachedLive = Layer.provide(
97 - ComposioToolkitsRepositoryCached,
98 - ComposioToolkitsRepositoryLive
99 -) satisfies RequiredLayer;
100 -
101 -export const UpgradeBinaryLive = Layer.provide(
102 - UpgradeBinary.Default,
103 - Layer.mergeAll(BunFileSystem.layer, FetchHttpClient.layer)
104 -) satisfies RequiredLayer;
105 -
106 -export const TriggersRealtimeLive = Layer.provide(
107 - TriggersRealtime.Default,
108 - Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOs.Default)
109 -) satisfies RequiredLayer;
110 -
111 -export const ComposioClientSingletonLive = Layer.provide(
112 - ComposioClientSingleton.Default,
113 - Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOs.Default, LogLevelFromConfigLive)
114 -) satisfies RequiredLayer;
115 -
116 -// Fed the cached repository so that the staleness refresh behind it shares the
117 -// one catalog fetch a run is allowed, rather than starting a second.
118 -export const ToolkitSlugCatalogLive = Layer.provide(
119 - ToolkitSlugCatalog.Default,
120 - ComposioToolkitsRepositoryCachedLive
121 -) satisfies RequiredLayer;
122 -
123 -export const DashboardToolExecutionLive = Layer.provide(
124 - DashboardToolExecution.Default,
125 - Layer.mergeAll(ComposioUserContextLive, FetchHttpClient.layer)
126 -);
127 -
128 -export const ToolsExecutorLive = Layer.provide(
129 - _ToolsExecutorLive,
130 - Layer.mergeAll(ComposioClientSingletonLive, ToolkitSlugCatalogLive, DashboardToolExecutionLive)
131 -) satisfies RequiredLayer;
132 -
133 -export const ProjectContextLive = Layer.provide(
134 - ProjectContext.Default,
135 - Layer.mergeAll(BunFileSystem.layer, NodeOs.Default, NodeProcess.Default)
136 -) satisfies RequiredLayer;
137 -
138 -export const SetupSkillInstallerLive = Layer.provide(
139 - SetupSkillInstaller.Default,
140 - Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOs.Default)
141 -) satisfies RequiredLayer;
142 -
143 -export const PendingLoginSessionLive = Layer.provide(
144 - PendingLoginSession.Default,
145 - Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOs.Default)
146 -) satisfies RequiredLayer;
147 -
148 -export const BackendMismatchWarningLive = Layer.provide(
149 - BackendMismatchWarning.Default,
150 - Layer.mergeAll(ComposioUserContextLive, TerminalUILive)
151 -) satisfies RequiredLayer;
152 -
153 -// `Path.layer`, not `BunPath.layer`: the update notice and the plugin hint have always resolved
154 -// their state files with Effect's own path implementation.
155 -export const UpdateNoticeLive = Layer.provide(
156 - UpdateNotice.Default,
157 - Layer.mergeAll(TerminalUILive, BunFileSystem.layer, Path.layer, NodeOs.Default)
158 -) satisfies RequiredLayer;
159 -
160 -export const PluginHintLive = Layer.provide(
161 - PluginHint.Default,
162 - Layer.mergeAll(TerminalUILive, BunFileSystem.layer, Path.layer, NodeOs.Default)
163 -) satisfies RequiredLayer;
164 -
165 -export const CommandLifecycleTelemetryLive = Layer.provide(
166 - CommandLifecycleTelemetry.Default,
167 - Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOs.Default, TerminalUILive)
168 -) satisfies RequiredLayer;
169 -
170 -const layers = Layer.mergeAll(
171 - CliConfigLive.pipe(Layer.provide(LogLevelFromConfigLive)),
172 - NodeOs.Default,
173 - NodeProcess.Default,
174 - UpgradeBinaryLive,
175 - ComposioCliUserConfigLayer,
176 - ComposioUserContextLive,
177 - ComposioSessionRepositoryLive,
178 - ComposioClientSingletonLive,
179 - ComposioToolkitsRepositoryCachedLive,
180 - ToolkitSlugCatalogLive,
181 - ToolsExecutorLive,
182 - JsPackageManagerDetector.Default,
183 - ProjectEnvironmentDetector.Default,
184 - CommandRunner.Default,
185 - SetupSkillInstallerLive,
186 - TriggersRealtimeLive,
187 - ProjectContextLive,
188 - PendingLoginSessionLive,
189 - BunServices.layer,
190 - BunFileSystem.layer,
191 - BunPath.layer,
192 - FetchHttpClient.layer,
193 - StdinLive,
194 - TerminalUILive,
195 - BackendMismatchWarningLive,
196 - UpdateNoticeLive,
197 - PluginHintLive,
198 - CommandLifecycleTelemetryLive,
199 - Layer.merge(
200 - Logger.layer([withoutClientNotices(Logger.consolePretty())]),
201 - Layer.succeed(Logger.LogToStderr, true)
202 - )
203 -) satisfies RequiredLayer;
204 -
205 -/**
206 - * Whether `reason` has nothing for the catch-all to print: a failure already on screen, or an
207 - * interruption, which must reach the runner untouched: 128 + n after a signal, else 130 from
208 - * `Runtime.defaultTeardown`.
209 - */
210 -const hasNothingToPrint = (reason: Cause.Reason<unknown>): boolean =>
211 - Cause.isInterruptReason(reason) ||
212 - (Cause.isFailReason(reason) && !Runtime.getErrorReported(reason.error));
213 -
214 -/**
215 - * Prints the parts of `cause` nobody reported yet and fails with `ReportedFailure`. A cause with
216 - * nothing to print (a failure already on screen — `ShowHelp`, which `Command.runWith` printed
217 - * with any parse/validation errors, a command's own report, or a message printed in
218 - * `cliProgram` — or an interruption) is re-failed untouched: its `[Runtime.errorReported]` is
219 - * false, so the runner logs nothing, and `Runtime.defaultTeardown` exits with its
220 - * `[Runtime.errorExitCode]`; interruptions alone exit 128 + n after a signal, else 130. Nothing
221 - * here may print it, or output doubles.
222 - */
223 -export const reportUnreportedCause = Effect.fn(function* (cause: Cause.Cause<unknown>) {
224 - const unreported = Cause.fromReasons(cause.reasons.filter(reason => !hasNothingToPrint(reason)));
225 - if (unreported.reasons.length > 0) {
226 - const captured = yield* captureErrors(unreported, { stripCwd: true });
227 - const message =
228 - captured.errors.length > 0
229 - ? prettyPrintFromCapturedErrors(captured, {
230 - hideStackTrace: true,
231 - stripCwd: true,
232 - enabled: true,
233 - }).trim()
234 - : '';
235 - if (message.length > 0) {
236 - const ui = yield* TerminalUI;
237 - yield* ui.error(message);
238 - return yield* new ReportedFailure({ message });
239 - }
240 - }
241 - // Nothing printable: keep the original cause so its exit code survives and the runner logs
242 - // whatever is still unreported, instead of exiting 0.
243 - return yield* Effect.failCause(cause);
244 -});
245 -
246 -// `runWithConfig`'s root command tree (built from every `.cmd.ts` subcommand in
247 -// `src/commands`) is deep and wide enough that TypeScript's inference collapses its
248 -// requirement (`R`) type to `any` rather than the precise union of service tags. That
249 -// `any` is otherwise infectious through the rest of this pipeline (defeating the
250 -// `Effect.provide(layers)` / `RequiredLayer` checks below), so it is pinned here to the
251 -// same service union `layers` actually provides — this changes nothing at runtime, it
252 -// only restores the precise static type that inference failed to produce on its own.
253 -const runWithArgs = (argv: ReadonlyArray<string>, bootstrap: RootCommandBootstrap) =>
254 - Effect.flatMap(runWithConfig, run => run(argv, bootstrap)) as Effect.Effect<
255 - void,
256 - unknown,
257 - Layer.Success<typeof layers> | ShutdownSignal
258 - >;
259 -
260 -const runWithTelemetry = (argv: ReadonlyArray<string>) =>
261 - Effect.gen(function* () {
262 - const ui = yield* TerminalUI;
263 - const terminal = yield* ui.capabilities;
264 -
265 - const version = yield* getVersion;
266 - configureCliAnalyticsReleaseVersion(version);
267 - const baseTelemetryContext = createCliCommandTelemetryContext(
268 - argv,
269 - version,
270 - terminal,
271 - yield* cliInvocationContext
272 - );
273 - const executeToolSlug = getExecuteCommandToolSlug(baseTelemetryContext);
274 - const commandTelemetryContext =
275 - executeToolSlug === undefined
276 - ? baseTelemetryContext
277 - : { ...baseTelemetryContext, toolkitSlug: yield* toolkitFromToolSlug(executeToolSlug) };
278 - // `composio run` mints its run id here so the lifecycle events and the id the spawned script
279 - // inherits are the same value; every other command leaves it unset.
280 - const bootstrap: RootCommandBootstrap =
281 - commandTelemetryContext.commandPath === 'run' && commandTelemetryContext.runId
282 - ? { runId: commandTelemetryContext.runId }
283 - : {};
284 - const telemetry = yield* CommandLifecycleTelemetry;
285 - return yield* telemetry.invoked(commandTelemetryContext).pipe(
286 - Effect.andThen(runWithArgs(argv, bootstrap)),
287 - Effect.scoped,
288 - Effect.mapError(error =>
289 - CliError.isCliError(error) ? error : mapOnlyComposioOverrideError({ error })
290 - ),
291 - Effect.tap(() => telemetry.succeeded(commandTelemetryContext)),
292 - Effect.tapCause(cause => telemetry.failed(commandTelemetryContext, cause))
293 - );
294 - });
295 -
21 /**
22 * Values `src/bin.ts` resolved before the Effect runtime existed and hands to it here.
23 */
@@ -301,65 +26,19 @@ export type CliBootstrapOptions = {
26 readonly argv: ReadonlyArray<string>;
27 };
28
304 -/** Runs the hooks every invocation gets before its command, in order, on stderr. */
305 -const runInvocationHooks = (invocation: HookInvocation) =>
306 - Effect.gen(function* () {
307 - const backendMismatchWarning = yield* BackendMismatchWarning;
308 - const updateNotice = yield* UpdateNotice;
309 - const pluginHint = yield* PluginHint;
310 - yield* backendMismatchWarning.run(invocation);
311 - yield* updateNotice.run(invocation);
312 - yield* pluginHint.run(invocation);
313 - });
314 -
315 -const cliProgram = (argv: ReadonlyArray<string>) =>
316 - runInvocationHooks({ argv }).pipe(
317 - Effect.andThen(runWithTelemetry(argv)),
318 - // A usage mistake, a missing setup or login, or a failure a remote service reported clearly
319 - // (see `ExpectedFailure`) is not a broken invariant: print the message and exit 1 instead of
320 - // routing it through the defect reporter below.
321 - Effect.catchIf(
322 - (error): error is ExpectedFailure => isExpectedFailure(error),
323 - error =>
324 - Effect.gen(function* () {
325 - const ui = yield* TerminalUI;
326 - yield* ui.error(error.message);
327 - return yield* new ReportedFailure({ message: error.message });
328 - })
329 - ),
330 - // A rejected user API key gets the backend's message and the way to log in again, from
331 - // whichever command it escaped.
332 - Effect.catchIf(isRejectedUserApiKey, error =>
333 - Effect.gen(function* () {
334 - const ui = yield* TerminalUI;
335 - const message = extractMessage(error) ?? 'The user API key was rejected.';
336 - yield* ui.error(message);
337 - yield* ui.error(yield* rejectedUserApiKeyHint);
338 - return yield* new ReportedFailure({ message });
339 - })
340 - ),
341 - Effect.withSpan('composio-cli', {
342 - attributes: {
343 - name: constants.APP_NAME,
344 - filename: 'src/bin.ts',
345 - },
346 - }),
347 - Effect.sandbox,
348 - Effect.catch(reportUnreportedCause),
349 - Effect.provide(layers),
29 +export const runCli = (options: CliBootstrapOptions): void => {
30 + const debug = readTelemetryDebugOverride(normalizeRunScriptArgs(options.argv));
31 + // One per invocation: the runner reports the process's signals to the command through it.
32 + const shutdown = makeShutdownController();
33 + runInvocation(options.argv).pipe(
34 + forRunner,
35 + Effect.provide(InvocationLive),
36 // Built per invocation, never at module scope: `ConfigProvider.fromEnv()` snapshots
37 // `process.env` when constructed, and the ambient `ConfigProvider` reference caches its
38 // default snapshot process-wide on first use. A fresh provider here means every config read
39 // of this invocation observes the environment as it is now (`vi.stubEnv` in tests, any
40 // in-process mutation before `runCli`).
355 - Effect.provide(ConfigProvider.layer(ConfigProvider.fromEnv()))
356 - );
357 -
358 -export const runCli = (options: CliBootstrapOptions): void => {
359 - const debug = readTelemetryDebugOverride(normalizeRunScriptArgs(options.argv));
360 - // One per invocation: the runner reports the process's signals to the command through it.
361 - const shutdown = makeShutdownController();
362 - cliProgram(options.argv).pipe(
41 + Effect.provide(ConfigProvider.layer(ConfigProvider.fromEnv())),
42 Effect.provideService(ShutdownSignal, shutdown.service),
43 effect =>
44 debug === undefined ? effect : Effect.provide(effect, telemetryDebugModeLayer(debug)),
ts/packages/cli/src/commands/debug/api-info/debug.api-info.handler.ts
+1 -1
@@ -22,7 +22,7 @@ export const consumerUserIdOf = (project: Option.Option<ResolvedCommandProject>)
22
23 /**
24 * The consumer project, when there is one. A project the user has not set up yet is a legitimate
25 - * "none" here; a failed lookup is not, and keeps its typed error so cli-main prints it and exits
25 + * "none" here; a failed lookup is not, and keeps its typed error so the invocation prints it and exits
26 * non-zero.
27 */
28 const resolveConsumerProject = resolveCommandProject({ mode: 'consumer' }).pipe(
ts/packages/cli/src/commands/errors.ts
+3 -3
@@ -5,8 +5,8 @@ import { ExpectedFailure, isExpectedFailure } from 'src/effects/expected-failure
5 * A usage mistake the parser cannot see: a flag combination, a value that fails a business
6 * rule, a missing input, or an environment the command cannot run in. `effect/cli`'s
7 * `CliError.InvalidValue` is a fixed option-and-value struct built only by the parser, so
8 - * handler-level validation raises this instead. `cli-main.ts` prints `message` as one line
9 - * and exits 1, with no defect banner.
8 + * handler-level validation raises this instead. The invocation (`src/invocation/invocation.ts`)
9 + * prints `message` as one line and exits 1, with no defect banner.
10 */
11 export class CommandInputError extends Data.TaggedError('commands/CommandInputError')<{
12 /** The command path without `composio`, e.g. `login` or `dev triggers disable`. */
@@ -35,7 +35,7 @@ export const notLoggedIn = (): NotLoggedInError =>
35 /**
36 * Failures the user fixes by changing the invocation or their setup, or that a remote service
37 * reported clearly, not defects: any error whose class declares `ExpectedFailure` (see
38 - * `src/effects/expected-failure.ts`). `cli-main.ts` prints the message on stderr and exits 1,
38 + * `src/effects/expected-failure.ts`). The invocation prints the message on stderr and exits 1,
39 * with no defect banner.
40 */
41 export type UsageFailure = ExpectedFailure;
ts/packages/cli/src/commands/tools/commands/tools.execute.cmd.ts
+2 -2
@@ -137,8 +137,8 @@ const invalidArguments = commandInputError('execute');
137
138 /**
139 * `composio execute` cannot run the tool as invoked: a `--file` the tool cannot take, or (with
140 - * `--parallel`) a toolkit the user has not connected. An expected
141 - * failure: `cli-main.ts` prints the message and exits 1.
140 + * `--parallel`) a toolkit the user has not connected. An expected failure: the invocation prints
141 + * the message and exits 1.
142 */
143 export class ToolExecutionError extends Data.TaggedError('ToolExecutionError')<{
144 readonly reason: 'file_input' | 'connection_check';
ts/packages/cli/src/effects/expected-failure.ts
+2 -2
@@ -2,7 +2,7 @@ import { Predicate } from 'effect';
2
3 /**
4 * Marks an error class as an expected failure: the user fixes it by changing the invocation or
5 - * their setup, or a remote service reported it clearly. `cli-main.ts` prints its `message` on
5 + * their setup, or a remote service reported it clearly. the invocation (`src/invocation/invocation.ts`) prints its `message` on
6 * stderr and exits 1, with no defect banner. Anything unmarked is a defect.
7 *
8 * An error class opts in where it is defined, with a getter, so no central list needs updating:
@@ -24,7 +24,7 @@ import { Predicate } from 'effect';
24 */
25 export const ExpectedFailure: unique symbol = Symbol.for('@composio/cli/ExpectedFailure');
26
27 -/** An error `cli-main.ts` prints as its message alone. */
27 +/** An error the invocation prints as its message alone. */
28 export interface ExpectedFailure {
29 readonly [ExpectedFailure]: boolean;
30 readonly message: string;
ts/packages/cli/src/effects/report-failure.ts
+2 -2
@@ -2,8 +2,8 @@ import { Data, Effect, Runtime } from 'effect';
2 import type { TerminalUI } from 'src/services/terminal-ui';
3
4 /**
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.
5 + * A failure already shown to the user. It only makes the command fail: the runner does not
6 + * 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 */
ts/packages/cli/src/invocation/invocation.ts new
+197
@@ -0,0 +1,197 @@
1 +/**
2 + * One CLI invocation, from argv to a finished command: the hooks every invocation runs, the
3 + * command's lifecycle telemetry, `effect/cli`'s parser and the selected command, and the one place
4 + * a failure is put on screen. `runCli` (`src/cli-main.ts`) runs it for the binary over
5 + * `InvocationLive`; tests run it through `cli()` over `TestLive`.
6 + *
7 + * Every failure leaves `runInvocation` on screen exactly once: printed by `Command.runWith` (help
8 + * and parse errors, `CliError.ShowHelp`), by the command itself (`[Runtime.errorReported] = false`),
9 + * or here (an expected failure's message, a rejected key, or the defect report). It leaves with
10 + * its own cause, so a caller can still match its typed error; `forRunner` turns it into what the
11 + * runner needs to print nothing more and exit with the right code.
12 + */
13 +import { Cause, Effect, Exit, Option, Runtime, type Layer } from 'effect';
14 +import { CliError } from 'effect/cli';
15 +import { captureErrors, prettyPrintFromCapturedErrors } from 'effect-errors/index';
16 +import {
17 + configureCliAnalyticsReleaseVersion,
18 + createCliCommandTelemetryContext,
19 + getExecuteCommandToolSlug,
20 +} from 'src/analytics/events';
21 +import { runWithConfig, type RootCommandBootstrap } from 'src/commands';
22 +import * as constants from 'src/constants';
23 +import { isExpectedFailure } from 'src/effects/expected-failure';
24 +import { isRejectedUserApiKey, rejectedUserApiKeyHint } from 'src/effects/rejected-user-api-key';
25 +import { ReportedFailure } from 'src/effects/report-failure';
26 +import { toolkitFromToolSlug } from 'src/effects/toolkit-from-tool-slug';
27 +import { getVersion } from 'src/effects/version';
28 +import { BackendMismatchWarning } from 'src/services/backend-mismatch-warning';
29 +import { CommandLifecycleTelemetry } from 'src/services/command-lifecycle-telemetry';
30 +import { mapOnlyComposioOverrideError } from 'src/services/composio-error-overrides';
31 +import type { HookInvocation } from 'src/services/invocation-hook';
32 +import { PluginHint } from 'src/services/plugin-hint';
33 +import { cliInvocationContext } from 'src/services/runtime-cli-context';
34 +import type { ShutdownSignal } from 'src/services/shutdown-signal';
35 +import { TerminalUI } from 'src/services/terminal-ui';
36 +import { UpdateNotice } from 'src/services/update-check';
37 +import { extractMessage } from 'src/utils/api-error-extraction';
38 +import type { InvocationLive } from './live';
39 +
40 +/** The services an invocation runs with: `InvocationLive` in the binary, `TestLive` in tests. */
41 +export type InvocationServices = Layer.Success<typeof InvocationLive> | ShutdownSignal;
42 +
43 +// `runWithConfig`'s root command tree (built from every `.cmd.ts` subcommand in
44 +// `src/commands`) is deep and wide enough that TypeScript's inference collapses its
45 +// requirement (`R`) type to `any` rather than the precise union of service tags. That
46 +// `any` is otherwise infectious through the rest of this pipeline, so it is pinned here to the
47 +// services an invocation is given — this changes nothing at runtime, it only restores the
48 +// precise static type that inference failed to produce on its own.
49 +const runWithArgs = (argv: ReadonlyArray<string>, bootstrap: RootCommandBootstrap) =>
50 + Effect.flatMap(runWithConfig, run => run(argv, bootstrap)) as Effect.Effect<
51 + void,
52 + unknown,
53 + InvocationServices
54 + >;
55 +
56 +const runWithTelemetry = (argv: ReadonlyArray<string>) =>
57 + Effect.gen(function* () {
58 + const ui = yield* TerminalUI;
59 + const terminal = yield* ui.capabilities;
60 +
61 + const version = yield* getVersion;
62 + configureCliAnalyticsReleaseVersion(version);
63 + const baseTelemetryContext = createCliCommandTelemetryContext(
64 + argv,
65 + version,
66 + terminal,
67 + yield* cliInvocationContext
68 + );
69 + const executeToolSlug = getExecuteCommandToolSlug(baseTelemetryContext);
70 + const commandTelemetryContext =
71 + executeToolSlug === undefined
72 + ? baseTelemetryContext
73 + : { ...baseTelemetryContext, toolkitSlug: yield* toolkitFromToolSlug(executeToolSlug) };
74 + // `composio run` mints its run id here so the lifecycle events and the id the spawned script
75 + // inherits are the same value; every other command leaves it unset.
76 + const bootstrap: RootCommandBootstrap =
77 + commandTelemetryContext.commandPath === 'run' && commandTelemetryContext.runId
78 + ? { runId: commandTelemetryContext.runId }
79 + : {};
80 + const telemetry = yield* CommandLifecycleTelemetry;
81 + return yield* telemetry.invoked(commandTelemetryContext).pipe(
82 + Effect.andThen(runWithArgs(argv, bootstrap)),
83 + Effect.scoped,
84 + Effect.mapError(error =>
85 + CliError.isCliError(error) ? error : mapOnlyComposioOverrideError({ error })
86 + ),
87 + Effect.tap(() => telemetry.succeeded(commandTelemetryContext)),
88 + Effect.tapCause(cause => telemetry.failed(commandTelemetryContext, cause))
89 + );
90 + });
91 +
92 +/** Runs the hooks every invocation gets before its command, in order, on stderr. */
93 +const runInvocationHooks = (invocation: HookInvocation) =>
94 + Effect.gen(function* () {
95 + const backendMismatchWarning = yield* BackendMismatchWarning;
96 + const updateNotice = yield* UpdateNotice;
97 + const pluginHint = yield* PluginHint;
98 + yield* backendMismatchWarning.run(invocation);
99 + yield* updateNotice.run(invocation);
100 + yield* pluginHint.run(invocation);
101 + });
102 +
103 +/**
104 + * Whether `reason` has nothing for this module to print: a failure already on screen, or an
105 + * interruption, which must reach the runner untouched: 128 + n after a signal, else 130 from
106 + * `Runtime.defaultTeardown`.
107 + */
108 +const hasNothingToPrint = (reason: Cause.Reason<unknown>): boolean =>
109 + Cause.isInterruptReason(reason) ||
110 + (Cause.isFailReason(reason) && !Runtime.getErrorReported(reason.error));
111 +
112 +/** Puts the failure `cause` on screen unless it already is, or is an interruption alone. */
113 +const report = (cause: Cause.Cause<unknown>) =>
114 + Effect.gen(function* () {
115 + const ui = yield* TerminalUI;
116 + const error = Cause.findErrorOption(cause);
117 + // A usage mistake, a missing setup or login, or a failure a remote service reported clearly
118 + // (see `ExpectedFailure`) is not a broken invariant: its message alone, no defect report.
119 + const expected = Option.filter(error, isExpectedFailure);
120 + if (Option.isSome(expected)) {
121 + yield* ui.error(expected.value.message);
122 + return;
123 + }
124 + // A rejected user API key gets the backend's message and the way to log in again, from
125 + // whichever command it escaped.
126 + const rejectedKey = Option.filter(error, isRejectedUserApiKey);
127 + if (Option.isSome(rejectedKey)) {
128 + yield* ui.error(extractMessage(rejectedKey.value) ?? 'The user API key was rejected.');
129 + yield* ui.error(yield* rejectedUserApiKeyHint);
130 + return;
131 + }
132 + // A failure already on screen — `ShowHelp` (`Command.runWith` printed help and any
133 + // parse/validation errors before failing with it), or a command's own report — must not be
134 + // printed again, or output doubles. An interruption is no failure to report.
135 + const unreported = Cause.fromReasons(
136 + cause.reasons.filter(reason => !hasNothingToPrint(reason))
137 + );
138 + if (unreported.reasons.length === 0) {
139 + return;
140 + }
141 + const captured = yield* captureErrors(unreported, { stripCwd: true });
142 + const message = prettyPrintFromCapturedErrors(captured, {
143 + hideStackTrace: true,
144 + stripCwd: true,
145 + enabled: true,
146 + }).trim();
147 + if (message.length > 0) {
148 + yield* ui.error(message);
149 + }
150 + });
151 +
152 +/**
153 + * Puts the failure `cause` on screen once (see {@link report}), then fails with `cause`
154 + * untouched: a caller can still match its typed error, and an interruption alone stays one, so
155 + * the runner exits 130 (or 128 + n after a signal) instead of 1.
156 + */
157 +export const reportInvocationFailure = (cause: Cause.Cause<unknown>) =>
158 + Effect.andThen(report(cause), Effect.failCause(cause));
159 +
160 +/**
161 + * Runs one invocation of the CLI for the full process `argv` (executable and script included):
162 + * the invocation hooks (before parsing), then the command under lifecycle telemetry.
163 + *
164 + * Fails with the command's own cause once it is on screen; an interruption alone is not printed.
165 + */
166 +export const runInvocation = (
167 + argv: ReadonlyArray<string>
168 +): Effect.Effect<void, unknown, InvocationServices> =>
169 + runInvocationHooks({ argv }).pipe(
170 + Effect.andThen(runWithTelemetry(argv)),
171 + Effect.withSpan('composio-cli', {
172 + attributes: {
173 + name: constants.APP_NAME,
174 + filename: 'src/bin.ts',
175 + },
176 + }),
177 + Effect.catchCause(reportInvocationFailure)
178 + );
179 +
180 +/**
181 + * The cause the runner receives for a failed invocation. A failure `runInvocation` put on screen
182 + * becomes a `ReportedFailure`: the runner logs nothing and exits 1. A failure that was on screen
183 + * before (`ShowHelp`, a command's own report, `ChildProcessExited`) keeps its markers and its
184 + * exit code, and an interruption stays one, so a signal still decides the exit.
185 + */
186 +export const runnerCause = (cause: Cause.Cause<unknown>): Cause.Cause<unknown> =>
187 + cause.reasons.every(hasNothingToPrint)
188 + ? cause
189 + : Cause.fail(new ReportedFailure({ message: Cause.pretty(cause) }));
190 +
191 +/** `exit` as the runner receives it; see {@link runnerCause}. */
192 +export const runnerExit = <A>(exit: Exit.Exit<A, unknown>): Exit.Exit<A, unknown> =>
193 + Exit.isSuccess(exit) ? exit : Exit.failCause(runnerCause(exit.cause));
194 +
195 +/** Hands `runInvocation`'s result to the runner; see {@link runnerCause}. */
196 +export const forRunner = <A, R>(self: Effect.Effect<A, unknown, R>): Effect.Effect<A, unknown, R> =>
197 + Effect.catchCause(self, cause => Effect.failCause(runnerCause(cause)));
ts/packages/cli/src/invocation/live.ts new
+176
@@ -0,0 +1,176 @@
1 +/**
2 + * The production services of an invocation: every layer `runInvocation` needs, built on Bun.
3 + * `cli-main.ts` provides it; tests provide `TestLive` instead.
4 + */
5 +import { Layer, Logger } from 'effect';
6 +import * as Path from 'effect/Path';
7 +import { CliConfig } from 'effect/cli';
8 +import { FetchHttpClient } from 'effect/http';
9 +import * as BunServices from '@effect/platform-bun/BunServices';
10 +import * as BunFileSystem from '@effect/platform-bun/BunFileSystem';
11 +import * as BunPath from '@effect/platform-bun/BunPath';
12 +import { withoutClientNotices } from 'src/effects/without-client-notices';
13 +import { ComposioCliConfig } from 'src/cli-config';
14 +import {
15 + ComposioClientSingleton,
16 + ComposioSessionRepository,
17 + ComposioToolkitsRepository,
18 +} from 'src/services/composio-clients';
19 +import { ComposioToolkitsRepositoryCached } from 'src/services/composio-clients-cached';
20 +import { NodeOs } from 'src/services/node-os';
21 +import { NodeProcess } from 'src/services/node-process';
22 +import { JsPackageManagerDetector } from 'src/services/js-package-manager-detector';
23 +import { ComposioCliUserConfigLive } from 'src/services/cli-user-config';
24 +import { ComposioUserContextLive as _ComposioUserContextLive } from 'src/services/user-context';
25 +import { UpgradeBinary } from 'src/services/upgrade-binary';
26 +import { TerminalUILive } from 'src/services/terminal-ui';
27 +import { TriggersRealtime } from 'src/services/triggers-realtime';
28 +import { ToolsExecutorLive as _ToolsExecutorLive } from 'src/services/tools-executor';
29 +import { DashboardToolExecution } from 'src/services/dashboard-tool-execution';
30 +import { ToolkitSlugCatalog } from 'src/services/toolkit-slug-catalog';
31 +import { ProjectContext } from 'src/services/project-context';
32 +import { ProjectEnvironmentDetector } from 'src/services/project-environment-detector';
33 +import { CommandRunner } from 'src/services/command-runner';
34 +import { StdinLive } from 'src/services/stdin';
35 +import { PluginHint } from 'src/services/plugin-hint';
36 +import { UpdateNotice } from 'src/services/update-check';
37 +import { BackendMismatchWarning } from 'src/services/backend-mismatch-warning';
38 +import { CommandLifecycleTelemetry } from 'src/services/command-lifecycle-telemetry';
39 +import { LogLevelFromConfigLive } from 'src/effects/with-log-level';
40 +import { SetupSkillInstaller } from 'src/services/setup-skill-installer';
41 +import { PendingLoginSession } from 'src/services/pending-login-session';
42 +
43 +// Layer is contravariant in ROut and covariant in E, so `never`/`unknown` accept any
44 +// produced context and error type while still pinning the requirements (RIn) to `never`.
45 +type RequiredLayer = Layer.Layer<never, unknown, never>;
46 +
47 +export const CliConfigLive = CliConfig.layer(ComposioCliConfig) satisfies RequiredLayer;
48 +
49 +export const ComposioUserContextLive = Layer.provide(
50 + _ComposioUserContextLive,
51 + Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOs.Default)
52 +) satisfies RequiredLayer;
53 +
54 +export const ComposioCliUserConfigLayer = Layer.provide(
55 + ComposioCliUserConfigLive,
56 + Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOs.Default)
57 +);
58 +
59 +export const ComposioSessionRepositoryLive = Layer.provide(
60 + ComposioSessionRepository.Default,
61 + Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOs.Default)
62 +) satisfies RequiredLayer;
63 +
64 +export const ComposioToolkitsRepositoryLive = Layer.provide(
65 + ComposioToolkitsRepository.Default,
66 + Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOs.Default, LogLevelFromConfigLive)
67 +) satisfies RequiredLayer;
68 +
69 +export const ComposioToolkitsRepositoryCachedLive = Layer.provide(
70 + ComposioToolkitsRepositoryCached,
71 + ComposioToolkitsRepositoryLive
72 +) satisfies RequiredLayer;
73 +
74 +export const UpgradeBinaryLive = Layer.provide(
75 + UpgradeBinary.Default,
76 + Layer.mergeAll(BunFileSystem.layer, FetchHttpClient.layer)
77 +) satisfies RequiredLayer;
78 +
79 +export const TriggersRealtimeLive = Layer.provide(
80 + TriggersRealtime.Default,
81 + Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOs.Default)
82 +) satisfies RequiredLayer;
83 +
84 +export const ComposioClientSingletonLive = Layer.provide(
85 + ComposioClientSingleton.Default,
86 + Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOs.Default, LogLevelFromConfigLive)
87 +) satisfies RequiredLayer;
88 +
89 +// Fed the cached repository so that the staleness refresh behind it shares the
90 +// one catalog fetch a run is allowed, rather than starting a second.
91 +export const ToolkitSlugCatalogLive = Layer.provide(
92 + ToolkitSlugCatalog.Default,
93 + ComposioToolkitsRepositoryCachedLive
94 +) satisfies RequiredLayer;
95 +
96 +export const DashboardToolExecutionLive = Layer.provide(
97 + DashboardToolExecution.Default,
98 + Layer.mergeAll(ComposioUserContextLive, FetchHttpClient.layer)
99 +);
100 +
101 +export const ToolsExecutorLive = Layer.provide(
102 + _ToolsExecutorLive,
103 + Layer.mergeAll(ComposioClientSingletonLive, ToolkitSlugCatalogLive, DashboardToolExecutionLive)
104 +) satisfies RequiredLayer;
105 +
106 +export const ProjectContextLive = Layer.provide(
107 + ProjectContext.Default,
108 + Layer.mergeAll(BunFileSystem.layer, NodeOs.Default, NodeProcess.Default)
109 +) satisfies RequiredLayer;
110 +
111 +export const SetupSkillInstallerLive = Layer.provide(
112 + SetupSkillInstaller.Default,
113 + Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOs.Default)
114 +) satisfies RequiredLayer;
115 +
116 +export const PendingLoginSessionLive = Layer.provide(
117 + PendingLoginSession.Default,
118 + Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOs.Default)
119 +) satisfies RequiredLayer;
120 +
121 +export const BackendMismatchWarningLive = Layer.provide(
122 + BackendMismatchWarning.Default,
123 + Layer.mergeAll(ComposioUserContextLive, TerminalUILive)
124 +) satisfies RequiredLayer;
125 +
126 +// `Path.layer`, not `BunPath.layer`: the update notice and the plugin hint have always resolved
127 +// their state files with Effect's own path implementation.
128 +export const UpdateNoticeLive = Layer.provide(
129 + UpdateNotice.Default,
130 + Layer.mergeAll(TerminalUILive, BunFileSystem.layer, Path.layer, NodeOs.Default)
131 +) satisfies RequiredLayer;
132 +
133 +export const PluginHintLive = Layer.provide(
134 + PluginHint.Default,
135 + Layer.mergeAll(TerminalUILive, BunFileSystem.layer, Path.layer, NodeOs.Default)
136 +) satisfies RequiredLayer;
137 +
138 +export const CommandLifecycleTelemetryLive = Layer.provide(
139 + CommandLifecycleTelemetry.Default,
140 + Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOs.Default, TerminalUILive)
141 +) satisfies RequiredLayer;
142 +
143 +export const InvocationLive = Layer.mergeAll(
144 + CliConfigLive.pipe(Layer.provide(LogLevelFromConfigLive)),
145 + NodeOs.Default,
146 + NodeProcess.Default,
147 + UpgradeBinaryLive,
148 + ComposioCliUserConfigLayer,
149 + ComposioUserContextLive,
150 + ComposioSessionRepositoryLive,
151 + ComposioClientSingletonLive,
152 + ComposioToolkitsRepositoryCachedLive,
153 + ToolkitSlugCatalogLive,
154 + ToolsExecutorLive,
155 + JsPackageManagerDetector.Default,
156 + ProjectEnvironmentDetector.Default,
157 + CommandRunner.Default,
158 + SetupSkillInstallerLive,
159 + TriggersRealtimeLive,
160 + ProjectContextLive,
161 + PendingLoginSessionLive,
162 + BunServices.layer,
163 + BunFileSystem.layer,
164 + BunPath.layer,
165 + FetchHttpClient.layer,
166 + StdinLive,
167 + TerminalUILive,
168 + BackendMismatchWarningLive,
169 + UpdateNoticeLive,
170 + PluginHintLive,
171 + CommandLifecycleTelemetryLive,
172 + Layer.merge(
173 + Logger.layer([withoutClientNotices(Logger.consolePretty())]),
174 + Layer.succeed(Logger.LogToStderr, true)
175 + )
176 +) satisfies RequiredLayer;
ts/packages/cli/src/services/command-project.ts
+1 -1
@@ -29,7 +29,7 @@ export interface ResolvedCommandProject {
29
30 /**
31 * The command's project could not be determined from the CLI's state and flags. The message
32 - * names the command that fixes it; `cli-main.ts` prints it as one line and exits 1.
32 + * names the command that fixes it; the invocation prints it as one line and exits 1.
33 */
34 export class ProjectResolutionError extends Data.TaggedError('services/ProjectResolutionError')<{
35 readonly reason:
ts/packages/cli/src/services/composio-clients.ts
+1 -1
@@ -282,7 +282,7 @@ export class ComposioClientSingleton extends Context.Service<
282 // The singleton and its transport share one metrics collector, created
283 // when the layer is built. The transport is a fresh `FetchHttpClient.layer`
284 // rather than the memoized one an application may already have built
285 - // (`cli-main.ts` provides its own), because that one calls
285 + // (`InvocationLive` provides its own), because that one calls
286 // `globalThis.fetch` directly and counts nothing; this one is built over
287 // the counting `fetch`.
288 static readonly Default = Layer.unwrap(
ts/packages/cli/src/services/invocation-hook.ts
+2 -2
@@ -12,8 +12,8 @@ export interface HookInvocation {
12 }
13
14 /**
15 - * A hook `cli-main.ts` runs once per invocation, before the command. Its output goes to stderr;
16 - * it fails the invocation only with the errors `E` names.
15 + * A hook the invocation (`src/invocation/invocation.ts`) runs once, before the command. Its
16 + * output goes to stderr; it fails the invocation only with the errors `E` names.
17 */
18 export interface InvocationHookShape<E = never> {
19 readonly run: (invocation: HookInvocation) => Effect.Effect<void, E>;
ts/packages/cli/src/services/runtime-cli-context.ts
+1 -1
@@ -29,7 +29,7 @@ export const cliInvocationContext: Effect.Effect<CliInvocationContext> = Effect.
29 /**
30 * Run id the bootstrap resolved for a `composio run` invocation.
31 *
32 - * `cli-main.ts` mints it while building the run's telemetry context and hands it to the command,
32 + * The invocation (`src/invocation/invocation.ts`) mints it while building the run's telemetry context and hands it to the command,
33 * so the `CLI_RUN_*` events and the `COMPOSIO_CLI_PARENT_RUN_ID` the script's child process
34 * inherits carry the same id. `None` for every other command, and for callers that drive the root
35 * command directly.
ts/packages/cli/src/services/update-check.ts
+1 -1
@@ -16,7 +16,7 @@ import { TerminalUI } from './terminal-ui';
16 /**
17 * Background update check for @composio/cli.
18 *
19 - * Two entry points, both called from cli-main BEFORE the root command's
19 + * Two entry points, both called from the invocation BEFORE the root command's
20 * Effect runtime boots — they must never block or throw:
21 *
22 * UpdateNotice — reads a tiny cached JSON file (~1 ms)
ts/packages/cli/test/__utils__/cli.ts
+12 -5
@@ -1,7 +1,14 @@
1 import { Effect } from 'effect';
2 -import * as Cli from 'src/commands';
2 +import { runInvocation } from 'src/invocation/invocation';
3 +import { exitCodeOf } from './exit-code';
4
4 -// Run CLI in test environment. `bootstrap` stands in for the values `cli-main.ts` resolves before
5 -// routing the root command (currently the `composio run` id).
6 -export const cli = (args: ReadonlyArray<string>, bootstrap?: Cli.RootCommandBootstrap) =>
7 - Effect.flatMap(Cli.runWithConfig, run => run(['node', '<CMD>', ...args], bootstrap));
5 +/**
6 + * Runs the CLI with `args` (no executable prefix) through the full invocation, the one the binary
7 + * runs: invocation hooks, lifecycle telemetry, the command, and its failure on stderr. Fails with
8 + * the command's own error, so `Effect.flip` and tag matching see it.
9 + */
10 +export const cli = (args: ReadonlyArray<string>) => runInvocation(['node', '<CMD>', ...args]);
11 +
12 +/** Runs `cli(args)` and reports how it ended, with the code the process would exit with. */
13 +export const cliExit = (args: ReadonlyArray<string>) =>
14 + Effect.map(Effect.exit(cli(args)), exit => ({ exit, exitCode: exitCodeOf(exit) }));
ts/packages/cli/test/__utils__/exit-code.ts
+13 -13
@@ -1,17 +1,17 @@
1 -import { Runtime, type Exit } from 'effect';
1 +import { Option, type Exit } from 'effect';
2 +import { runnerExit } from 'src/invocation/invocation';
3 +import { ExitAction, exitActionFor } from 'src/run-main';
4 +import { signalExitCode } from 'src/services/shutdown-signal';
5
6 /**
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 + * The code the CLI process exits with when an invocation ends with `exit` and no signal arrived,
8 + * mapped the way `runCli` maps it: `forRunner`, then the runner's `exitActionFor` (by way of
9 + * `Runtime.defaultTeardown`). 0 on success, otherwise the failure's `[Runtime.errorExitCode]`,
10 + * or 1 without one; a child `composio run` a signal ended reports 128 + its number, as a shell
11 + * would for the re-raised signal.
12 */
8 -export const exitCodeOf = (exit: Exit.Exit<unknown, unknown>): number => {
9 - let code: number | undefined;
10 - Runtime.defaultTeardown(exit, exitCode => {
11 - code = exitCode;
13 +export const exitCodeOf = (exit: Exit.Exit<unknown, unknown>): number =>
14 + ExitAction.$match(exitActionFor(runnerExit(exit), Option.none()), {
15 + ExitWith: ({ code }) => code,
16 + Reraise: ({ signal }) => signalExitCode(signal),
17 });
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__/index.ts
+3 -1
@@ -10,6 +10,7 @@ export {
10 InvocationHooksTest,
11 InvocationRecorder,
12 recordedInvocationCalls,
13 + resetInvocationCalls,
14 type RecordedInvocationCall,
15 } from './layers/invocation-hooks';
16 export { SetupTest } from './layers/setup';
@@ -19,7 +20,8 @@ export {
20 dashboardProcedureResult,
21 type DashboardTestRequest,
22 } from './layers/dashboard';
22 -export { cli } from './cli';
23 +export { cli, cliExit } from './cli';
24 +export { exitCodeOf } from './exit-code';
25 export { pkg };
26 export { withHttpServer } from './http-server';
27 export { hostOnlyEnvConfigProvider, liveEnvConfigProvider } from './live-env-config-provider';
ts/packages/cli/test/__utils__/layers/invocation-hooks.ts
+17 -2
@@ -27,7 +27,10 @@ export type RecordedInvocationCall =
27 /** Reads what the recording doubles of `InvocationHooksTest` were called with. */
28 export class InvocationRecorder extends Context.Service<
29 InvocationRecorder,
30 - { readonly calls: Effect.Effect<ReadonlyArray<RecordedInvocationCall>> }
30 + {
31 + readonly calls: Effect.Effect<ReadonlyArray<RecordedInvocationCall>>;
32 + readonly reset: Effect.Effect<void>;
33 + }
34 >()('test/InvocationRecorder') {}
35
36 /** Every call the recording doubles received so far, oldest first. */
@@ -36,6 +39,15 @@ export const recordedInvocationCalls = Effect.gen(function* () {
39 return yield* recorder.calls;
40 });
41
42 +/**
43 + * Forgets every call recorded so far. Tests that share one `TestLive` (`layer(TestLive())`)
44 + * record into one recorder; reset it before the invocation a test asserts on.
45 + */
46 +export const resetInvocationCalls = Effect.gen(function* () {
47 + const recorder = yield* InvocationRecorder;
48 + yield* recorder.reset;
49 +});
50 +
51 /**
52 * Recording no-op doubles for the invocation hooks and the lifecycle telemetry sink: they print
53 * nothing and track nothing, so a test's stderr and analytics stay its command's own, and
@@ -46,7 +58,10 @@ export const InvocationHooksTest = Layer.unwrap(
58 const calls = yield* Ref.make<ReadonlyArray<RecordedInvocationCall>>([]);
59 const record = (call: RecordedInvocationCall) => Ref.update(calls, all => [...all, call]);
60 return Layer.mergeAll(
49 - Layer.succeed(InvocationRecorder, InvocationRecorder.of({ calls: Ref.get(calls) })),
61 + Layer.succeed(
62 + InvocationRecorder,
63 + InvocationRecorder.of({ calls: Ref.get(calls), reset: Ref.set(calls, []) })
64 + ),
65 Layer.succeed(
66 BackendMismatchWarning,
67 BackendMismatchWarning.of({
ts/packages/cli/test/__utils__/services/test-layer.ts
+2 -2
@@ -886,7 +886,7 @@ export const TestLayer = (input?: TestLiveInput) =>
886 const layers = Layer.mergeAll(
887 Layer.succeed(Console.Console, _console),
888 CliConfigLive,
889 - // Mirror cli-main: no custom `CliOutput.Formatter` is provided here either
889 + // Mirror `InvocationLive`: no custom `CliOutput.Formatter` is provided here either
890 // — `CliOutput.Formatter` is a `Context.Reference` that falls back to v4's
891 // own `CliOutput.defaultFormatter()`, so `Command.runWith` renders help,
892 // errors, and `--version` identically to production.
@@ -913,7 +913,7 @@ export const TestLayer = (input?: TestLiveInput) =>
913 FetchHttpClient.layer,
914 StdinTest,
915 TerminalUILayer,
916 - // Recording no-op doubles of the hooks and telemetry sink `cli-main.ts` runs around a
916 + // Recording no-op doubles of the hooks and telemetry sink the invocation runs around a
917 // command; read their calls with `recordedInvocationCalls`.
918 InvocationHooksTest,
919 // `src/commands/index.ts` provides these for real invocations; direct-effect tests that
ts/packages/cli/test/src/cli-main.test.ts
+3 -224
@@ -7,230 +7,9 @@ import { describe, expect, it } from 'vitest';
7 import * as tempy from 'tempy';
8 import { withHttpServer } from 'test/__utils__/http-server';
9
10 -describe('CLI process error handling', () => {
11 - it.each([
12 - { args: [], status: 0, recorded: 'CLI_COMMAND_SUCCEEDED', absent: 'CLI_COMMAND_FAILED' },
13 - { args: ['help'], status: 0, recorded: 'CLI_COMMAND_SUCCEEDED', absent: 'CLI_COMMAND_FAILED' },
14 - {
15 - args: ['--help'],
16 - status: 0,
17 - recorded: 'CLI_COMMAND_SUCCEEDED',
18 - absent: 'CLI_COMMAND_FAILED',
19 - },
20 - {
21 - args: ['--version'],
22 - status: 0,
23 - recorded: 'CLI_COMMAND_SUCCEEDED',
24 - absent: 'CLI_COMMAND_FAILED',
25 - },
26 - {
27 - args: ['help', 'orgz'],
28 - status: 1,
29 - recorded: 'CLI_COMMAND_FAILED',
30 - absent: 'CLI_COMMAND_SUCCEEDED',
31 - },
32 - ])(
33 - 'records help and version as successes and invalid help as a failure: `composio $args` is $recorded',
34 - ({ args, status, recorded, absent }) => {
35 - const configDirectory = tempy.temporaryDirectory();
36 - const result = spawnSync('bun', ['run', 'src/bin.ts', ...args], {
37 - cwd: process.cwd(),
38 - encoding: 'utf8',
39 - env: {
40 - ...process.env,
41 - CI: '1',
42 - NO_COLOR: '1',
43 - COMPOSIO_CACHE_DIR: configDirectory,
44 - COMPOSIO_CLI_TELEMETRY_DISABLED: '1',
45 - COMPOSIO_CLI_TELEMETRY_DEBUG: '1',
46 - },
47 - });
48 - expect(result.status).toBe(status);
49 - expect(result.stderr).toContain(recorded);
50 - expect(result.stderr).not.toContain(absent);
51 - }
52 - );
53 -
54 - it('prints unreported typed execute failures and exits non-zero', () => {
55 - const configDirectory = tempy.temporaryDirectory();
56 - fs.writeFileSync(
57 - path.join(configDirectory, 'user_data.json'),
58 - JSON.stringify({
59 - api_key: 'test-api-key',
60 - base_url: 'https://backend.composio.dev',
61 - web_url: 'https://platform.composio.dev',
62 - org_id: null,
63 - test_user_id: null,
64 - })
65 - );
66 -
67 - const result = spawnSync(
68 - 'bun',
69 - ['run', 'src/bin.ts', 'execute', 'GITHUB_GET_THE_AUTHENTICATED_USER', '-d', '[]'],
70 - {
71 - cwd: process.cwd(),
72 - encoding: 'utf8',
73 - env: {
74 - ...process.env,
75 - CI: '1',
76 - NO_COLOR: '1',
77 - COMPOSIO_CACHE_DIR: configDirectory,
78 - },
79 - }
80 - );
81 -
82 - expect(result.status).toBe(1);
83 - expect(`${result.stdout}\n${result.stderr}`).toContain(
84 - 'Expected a JSON object for tool arguments'
85 - );
86 - });
87 -
88 - it('reports a missing login as one line and exits non-zero without a defect dump', () => {
89 - const configDirectory = tempy.temporaryDirectory();
90 -
91 - const result = spawnSync('bun', ['run', 'src/bin.ts', 'tools', 'list', 'gmail'], {
92 - cwd: process.cwd(),
93 - encoding: 'utf8',
94 - env: {
95 - ...process.env,
96 - CI: '1',
97 - NO_COLOR: '1',
98 - COMPOSIO_CACHE_DIR: configDirectory,
99 - },
100 - });
101 -
102 - expect(result.status).toBe(1);
103 - expect(result.stdout).toBe('');
104 - expect(result.stderr).toContain('You are not logged in yet. Please run `composio login`.');
105 - expect(result.stderr).not.toContain('NotLoggedInError');
106 - expect(result.stderr).not.toContain('Sources');
107 - });
108 -
109 - it('reports an unresolved project as one line and exits non-zero without a defect dump', () => {
110 - const configDirectory = tempy.temporaryDirectory();
111 - fs.writeFileSync(
112 - path.join(configDirectory, 'user_data.json'),
113 - JSON.stringify({
114 - api_key: 'test-api-key',
115 - base_url: 'https://backend.composio.dev',
116 - web_url: 'https://platform.composio.dev',
117 - org_id: null,
118 - test_user_id: null,
119 - })
120 - );
121 -
122 - const result = spawnSync('bun', ['run', 'src/bin.ts', 'connections', 'list'], {
123 - cwd: process.cwd(),
124 - encoding: 'utf8',
125 - env: {
126 - ...process.env,
127 - CI: '1',
128 - NO_COLOR: '1',
129 - COMPOSIO_CACHE_DIR: configDirectory,
130 - },
131 - });
132 -
133 - expect(result.status).toBe(1);
134 - expect(result.stdout).toBe('');
135 - expect(result.stderr).toContain(
136 - 'No current org configured. Run `composio login` or `composio dev orgs switch`.'
137 - );
138 - expect(result.stderr).not.toContain('ProjectResolutionError');
139 - expect(result.stderr).not.toContain('Sources');
140 - });
141 -
142 - // Each of these used to print its message only to a terminal and exit 0, so a script, CI or
143 - // an agent saw nothing and a successful exit; `connections remove` used to answer its own
144 - // confirmation prompt with "no".
145 - it.each([
146 - {
147 - command: 'whoami',
148 - args: ['whoami'],
149 - loggedIn: false,
150 - message: 'You are not logged in yet. Please run `composio login`.',
151 - },
152 - {
153 - command: 'dev connected-accounts info',
154 - args: ['dev', 'connected-accounts', 'info'],
155 - loggedIn: true,
156 - message: 'Missing required argument: <id>',
157 - },
158 - {
159 - command: 'triggers info',
160 - args: ['triggers', 'info'],
161 - loggedIn: true,
162 - message: 'Missing required argument: <slug>',
163 - },
164 - {
165 - command: 'connections remove gmail',
166 - args: ['connections', 'remove', 'gmail'],
167 - loggedIn: true,
168 - message: '`composio connections remove` needs --yes when not running interactively.',
169 - },
170 - {
171 - command: 'dev projects list',
172 - args: ['dev', 'projects', 'list'],
173 - loggedIn: true,
174 - message: 'No current org is configured.',
175 - },
176 - ])(
177 - 'reports `composio $command` on a redirected stderr and exits 1',
178 - ({ args, loggedIn, message }) => {
179 - const configDirectory = tempy.temporaryDirectory();
180 - if (loggedIn) {
181 - fs.writeFileSync(
182 - path.join(configDirectory, 'user_data.json'),
183 - JSON.stringify({
184 - api_key: 'test-api-key',
185 - base_url: 'https://backend.composio.dev',
186 - web_url: 'https://platform.composio.dev',
187 - org_id: null,
188 - test_user_id: null,
189 - })
190 - );
191 - }
192 -
193 - const result = spawnSync('bun', ['run', 'src/bin.ts', ...args], {
194 - cwd: process.cwd(),
195 - encoding: 'utf8',
196 - env: {
197 - ...process.env,
198 - CI: '1',
199 - NO_COLOR: '1',
200 - COMPOSIO_CACHE_DIR: configDirectory,
201 - },
202 - });
203 -
204 - expect(result.status).toBe(1);
205 - expect(result.stdout).toBe('');
206 - expect(result.stderr).toContain(message);
207 - expect(result.stderr).not.toContain('CommandInputError');
208 - }
209 - );
210 -
211 - it('reports a bare `composio run` as a usage error without a defect dump', () => {
212 - const configDirectory = tempy.temporaryDirectory();
213 -
214 - const result = spawnSync('bun', ['run', 'src/bin.ts', 'run'], {
215 - cwd: process.cwd(),
216 - encoding: 'utf8',
217 - env: {
218 - ...process.env,
219 - CI: '1',
220 - NO_COLOR: '1',
221 - COMPOSIO_CACHE_DIR: configDirectory,
222 - },
223 - });
224 -
225 - const output = `${result.stdout}\n${result.stderr}`;
226 - expect(result.status).toBe(1);
227 - expect(output).toContain('Provide inline code or use --file to run a script file.');
228 - // No defect banner, no source-mapped stack, and no run artifacts for a script that never ran.
229 - expect(output).not.toContain('MissingRunSourceError');
230 - expect(output).not.toContain('Sources');
231 - expect(output).not.toContain('RUN_LOG_FILE=');
232 - });
233 -
10 +// Cases that run in-process go through `cli()` (test/src/invocation/invocation.test.ts); these need
11 +// the real process: the bootstrap, the stored login a spawned CLI reads, real HTTP, and signals.
12 +describe('CLI bootstrap', () => {
13 it('normalizes telemetry debug before dispatching a background worker', () => {
14 const configDirectory = tempy.temporaryDirectory();
15 const encodedPayload = Buffer.from(
ts/packages/cli/test/src/commands/$default.cmd.test.ts
+2 -2
@@ -12,8 +12,8 @@ describe('CLI: composio', () => {
12
13 // v4 migration note: v3's `Command.run` returned a `ValidationError.CommandMismatch` for the
14 // caller to render by hand. `effect/cli`'s `Command.runWith` renders parse/validation
15 - // errors itself (see `src/cli-main.ts` module docs) before re-failing with `CliError.ShowHelp`,
16 - // so these tests now assert on the printed `MockConsole` output instead of inspecting the error
15 + // errors itself (see `src/invocation/invocation.ts` module docs) before re-failing with
16 + // `CliError.ShowHelp`, so these tests now assert on the printed `MockConsole` output instead of inspecting the error
17 // value directly.
18 layer(TestLive())(it => {
19 it.effect('[Given] unknown argument [Then] print error message', () =>
ts/packages/cli/test/src/commands/agent/agent.cmd.test.ts
-1
@@ -11,7 +11,6 @@ import { makeAgentIdentity } from 'test/__utils__/models/agent';
11 describe('CLI: composio agent', () => {
12 afterEach(() => {
13 vi.restoreAllMocks();
14 - process.exitCode = undefined;
14 });
15
16 layer(TestLive())(it => {
ts/packages/cli/test/src/commands/agent/claim/agent.claim.cmd.test.ts
-1
@@ -9,7 +9,6 @@ import { exitCodeOf } from 'test/__utils__/exit-code';
9 describe('CLI: composio agent claim', () => {
10 afterEach(() => {
11 vi.restoreAllMocks();
12 - process.exitCode = undefined;
12 });
13
14 layer(TestLive())(it => {
ts/packages/cli/test/src/commands/agent/claim/agent.claim.handler.test.ts
-1
@@ -11,7 +11,6 @@ import { exitCodeOf } from 'test/__utils__/exit-code';
11 describe('runAgentClaim', () => {
12 afterEach(() => {
13 vi.restoreAllMocks();
14 - process.exitCode = undefined;
14 });
15
16 it.effect(
ts/packages/cli/test/src/commands/agent/inbox/agent.inbox.cmd.test.ts
-1
@@ -11,7 +11,6 @@ import { agentsJsonResponse, makeAgentIdentity } from 'test/__utils__/models/age
11 describe('CLI: composio agent inbox', () => {
12 afterEach(() => {
13 vi.restoreAllMocks();
14 - process.exitCode = undefined;
14 });
15
16 layer(TestLive())(it => {
ts/packages/cli/test/src/commands/agent/inbox/agent.inbox.handler.test.ts
-1
@@ -25,7 +25,6 @@ const inbox = {
25 describe('runAgentInbox', () => {
26 afterEach(() => {
27 vi.restoreAllMocks();
28 - process.exitCode = undefined;
28 });
29
30 it.effect(
ts/packages/cli/test/src/commands/agent/login/agent.login.cmd.test.ts
-1
@@ -33,7 +33,6 @@ const agentConfigPath = Effect.map(setupCacheDir, cacheDir => path.join(cacheDir
33 describe('CLI: composio agent login', () => {
34 afterEach(() => {
35 vi.restoreAllMocks();
36 - process.exitCode = undefined;
36 });
37
38 layer(TestLive())(it => {
ts/packages/cli/test/src/commands/agent/login/agent.login.handler.test.ts
-1
@@ -11,7 +11,6 @@ import { exitCodeOf } from 'test/__utils__/exit-code';
11 describe('runAgentLogin', () => {
12 afterEach(() => {
13 vi.restoreAllMocks();
14 - process.exitCode = undefined;
14 });
15
16 it.effect(
ts/packages/cli/test/src/commands/agent/signup/agent.signup.cmd.test.ts
-1
@@ -13,7 +13,6 @@ import { exitCodeOf } from 'test/__utils__/exit-code';
13 describe('CLI: composio agent signup', () => {
14 afterEach(() => {
15 vi.restoreAllMocks();
16 - process.exitCode = undefined;
16 });
17
18 layer(TestLive())(it => {
ts/packages/cli/test/src/commands/agent/signup/agent.signup.handler.test.ts
-1
@@ -57,7 +57,6 @@ const summaryJson = (identity: ReturnType<typeof makeAgentIdentity>, loggedIn: b
57 describe('runAgentSignup', () => {
58 afterEach(() => {
59 vi.restoreAllMocks();
60 - process.exitCode = undefined;
60 });
61
62 it.effect(
ts/packages/cli/test/src/commands/agent/whoami/agent.whoami.cmd.test.ts
-1
@@ -9,7 +9,6 @@ import { exitCodeOf } from 'test/__utils__/exit-code';
9 describe('CLI: composio agent whoami', () => {
10 afterEach(() => {
11 vi.restoreAllMocks();
12 - process.exitCode = undefined;
12 });
13
14 layer(TestLive())(it => {
ts/packages/cli/test/src/commands/agent/whoami/agent.whoami.handler.test.ts
-1
@@ -13,7 +13,6 @@ const decoration = Effect.map(MockConsole.getLines({ stripAnsi: true }), lines =
13 describe('runAgentWhoami', () => {
14 afterEach(() => {
15 vi.restoreAllMocks();
16 - process.exitCode = undefined;
16 });
17
18 it.effect(
ts/packages/cli/test/src/commands/auth-configs/create/auth-configs.create.cmd.test.ts
+5 -2
@@ -1,4 +1,5 @@
1 -import { describe, expect, layer } from '@effect/vitest';
1 +import { assert, describe, expect, layer } from '@effect/vitest';
2 +import { isUsageFailure } from 'src/commands/errors';
3 import type { AuthConfigCreateParams } from '@composio/client/resources/auth-configs';
4 import { ConfigProvider, Effect } from 'effect';
5 import { cli, TestLive, MockConsole } from 'test/__utils__';
@@ -118,7 +119,9 @@ describe('CLI: composio dev auth-configs create', () => {
119 option: '--custom-credentials',
120 message: expect.stringContaining('Invalid JSON in --custom-credentials'),
121 });
121 - expect(yield* MockConsole.getLines()).toEqual([]);
122 + // The invocation prints the message on stderr, and nothing else.
123 + assert(isUsageFailure(failure));
124 + expect(yield* MockConsole.getLines()).toEqual([failure.message]);
125 })
126 );
127 }
ts/packages/cli/test/src/commands/auth-configs/create/auth-configs.create.handler.test.ts
+1 -1
@@ -146,7 +146,7 @@ describe('runAuthConfigsCreate', () => {
146 /^Invalid JSON in --custom-credentials\. Please provide valid JSON\.\nExample:\n> composio dev auth-configs create /
147 ),
148 });
149 - // `cli-main.ts` prints a usage failure on stderr and exits 1.
149 + // The invocation prints a usage failure on stderr and exits 1.
150 expect(isUsageFailure(failure)).toBe(true);
151 expect(yield* MockConsole.getLines()).toEqual([]);
152 expect(outputs).toEqual([]);
ts/packages/cli/test/src/commands/auth-configs/info/auth-configs.info.cmd.test.ts
+5 -2
@@ -1,4 +1,5 @@
1 -import { describe, expect, layer } from '@effect/vitest';
1 +import { assert, describe, expect, layer } from '@effect/vitest';
2 +import { isUsageFailure } from 'src/commands/errors';
3 import { ConfigProvider, Effect } from 'effect';
4 import { cli, TestLive, MockConsole } from 'test/__utils__';
5 import { exitCodeOf } from 'test/__utils__/exit-code';
@@ -62,7 +63,9 @@ describe('CLI: composio dev auth-configs info', () => {
63 option: '<id>',
64 message: expect.stringContaining('Missing required argument: <id>'),
65 });
65 - expect(yield* MockConsole.getLines()).toEqual([]);
66 + // The invocation prints the message on stderr, and nothing else.
67 + assert(isUsageFailure(failure));
68 + expect(yield* MockConsole.getLines()).toEqual([failure.message]);
69 })
70 );
71 }
ts/packages/cli/test/src/commands/auth-configs/info/auth-configs.info.handler.test.ts
+1 -1
@@ -40,7 +40,7 @@ describe('runAuthConfigsInfo', () => {
40 /^Missing required argument: <id>\n[\s\S]*> composio dev auth-configs list$/
41 ),
42 });
43 - // `cli-main.ts` prints a usage failure on stderr and exits 1.
43 + // The invocation prints a usage failure on stderr and exits 1.
44 expect(isUsageFailure(failure)).toBe(true);
45 expect(yield* MockConsole.getLines()).toEqual([]);
46 expect(outputs).toEqual([]);
ts/packages/cli/test/src/commands/connected-accounts/info/connected-accounts.info.cmd.test.ts
+5 -2
@@ -1,4 +1,5 @@
1 -import { describe, expect, layer } from '@effect/vitest';
1 +import { assert, describe, expect, layer } from '@effect/vitest';
2 +import { isUsageFailure } from 'src/commands/errors';
3 import { ConfigProvider, Effect } from 'effect';
4 import { cli, TestLive, MockConsole } from 'test/__utils__';
5 import { exitCodeOf } from 'test/__utils__/exit-code';
@@ -85,7 +86,9 @@ describe('CLI: composio dev connected-accounts info', () => {
86 /^Missing required argument: <id>\n[^]*composio dev connected-accounts info /
87 ),
88 });
88 - expect(yield* MockConsole.getLines()).toEqual([]);
89 + // The invocation prints the message on stderr, and nothing else.
90 + assert(isUsageFailure(failure));
91 + expect(yield* MockConsole.getLines()).toEqual([failure.message]);
92 })
93 );
94 }
ts/packages/cli/test/src/commands/connected-accounts/info/connected-accounts.info.handler.test.ts
+1 -1
@@ -101,7 +101,7 @@ describe('runConnectedAccountsInfo', () => {
101 option: '<id>',
102 message: `${MISSING_ID_MESSAGE}\n${missingIdHint('info')}`,
103 });
104 - // `cli-main.ts` prints a usage failure on stderr and exits 1.
104 + // The invocation prints a usage failure on stderr and exits 1.
105 expect(isUsageFailure(failure)).toBe(true);
106 expect(yield* stderrLines).toEqual([]);
107 expect(yield* stdoutLines).toEqual([]);
ts/packages/cli/test/src/commands/connected-accounts/link/connected-accounts.link.cmd.test.ts
-1
@@ -131,7 +131,6 @@ describe('CLI: composio dev connected-accounts link', () => {
131 afterEach(() => {
132 vi.restoreAllMocks();
133 vi.clearAllMocks();
134 - process.exitCode = undefined;
134 });
135
136 layer(
ts/packages/cli/test/src/commands/connected-accounts/whoami/connected-accounts.whoami.cmd.test.ts
+5 -2
@@ -1,4 +1,5 @@
1 -import { describe, expect, layer } from '@effect/vitest';
1 +import { assert, describe, expect, layer } from '@effect/vitest';
2 +import { isUsageFailure } from 'src/commands/errors';
3 import { ConfigProvider, Effect } from 'effect';
4 import { cli, TestLive, MockConsole } from 'test/__utils__';
5 import { exitCodeOf } from 'test/__utils__/exit-code';
@@ -119,7 +120,9 @@ describe('CLI: composio dev connected-accounts whoami', () => {
120 /^Missing required argument: <id>\n[^]*composio dev connected-accounts whoami /
121 ),
122 });
122 - expect(yield* MockConsole.getLines()).toEqual([]);
123 + // The invocation prints the message on stderr, and nothing else.
124 + assert(isUsageFailure(failure));
125 + expect(yield* MockConsole.getLines()).toEqual([failure.message]);
126 })
127 );
128 }
ts/packages/cli/test/src/commands/connected-accounts/whoami/connected-accounts.whoami.handler.test.ts
+1 -1
@@ -104,7 +104,7 @@ describe('runConnectedAccountsWhoami', () => {
104 option: '<id>',
105 message: `${MISSING_ID_MESSAGE}\n${missingIdHint('whoami')}`,
106 });
107 - // `cli-main.ts` prints a usage failure on stderr and exits 1.
107 + // The invocation prints a usage failure on stderr and exits 1.
108 expect(isUsageFailure(failure)).toBe(true);
109 expect(yield* stderrLines).toEqual([]);
110 expect(yield* stdoutLines).toEqual([]);
ts/packages/cli/test/src/commands/connections/remove/connections.remove.cmd.test.ts
+6 -9
@@ -1,5 +1,5 @@
1 -import { afterEach } from 'vitest';
2 -import { describe, expect, layer } from '@effect/vitest';
1 +import { assert, describe, expect, layer } from '@effect/vitest';
2 +import { isUsageFailure } from 'src/commands/errors';
3 import { ConfigProvider, Effect } from 'effect';
4 import { extractErrorDetails } from 'src/effect-errors/logic/errors/extract-error-details';
5 import type { ConnectedAccountItem } from 'src/models/connected-accounts';
@@ -82,10 +82,6 @@ const testConfigProvider = ConfigProvider.fromEnv({
82 });
83
84 describe('CLI: composio connections remove', () => {
85 - afterEach(() => {
86 - process.exitCode = undefined;
87 - });
88 -
85 const confirmedDeleteCalls: string[] = [];
86 layer(
87 TestLive({
@@ -261,7 +257,6 @@ describe('CLI: composio connections remove', () => {
257 yield* userContext.login('test_api_key', 'org_test');
258 const failure = yield* cli(['connections', 'remove', 'gmail']).pipe(Effect.flip);
259
264 - // `cli-main.ts` prints the message on stderr and exits 1.
260 expect(failure).toMatchObject({
261 _tag: 'commands/CommandInputError',
262 command: 'connections remove',
@@ -270,7 +265,9 @@ describe('CLI: composio connections remove', () => {
265 });
266 expect(headlessDeleteCalls).toEqual([]);
267 // Not even the connection list is fetched.
273 - expect(yield* MockConsole.getLines()).toEqual([]);
268 + // The invocation prints the message on stderr, and nothing else.
269 + assert(isUsageFailure(failure));
270 + expect(yield* MockConsole.getLines()).toEqual([failure.message]);
271 })
272 );
273
@@ -300,7 +297,7 @@ describe('CLI: composio connections remove', () => {
297 Effect.flip
298 );
299
303 - // `cli-main.ts` prints the message on stderr and exits 1.
300 + // The invocation prints the message on stderr and exits 1.
301 expect(failure).toMatchObject({
302 _tag: 'commands/CommandInputError',
303 command: 'connections remove',
ts/packages/cli/test/src/commands/init.cmd.test.ts
+4 -7
@@ -1,4 +1,3 @@
1 -import { afterEach } from 'vitest';
1 import { describe, expect, layer } from '@effect/vitest';
2 import { Effect } from 'effect';
3 import { cli, TestLive, MockConsole } from 'test/__utils__';
@@ -7,10 +6,6 @@ import { makeOrgProject } from 'test/__utils__/models/account';
6 import { redirectedTerminalUI } from 'test/__utils__/services/redirected-terminal-ui';
7
8 describe('CLI: composio dev init', () => {
10 - afterEach(() => {
11 - process.exitCode = undefined;
12 - });
13 -
9 describe('dev init --help', () => {
10 layer(TestLive({ fixture: 'typescript-project' }))(it => {
11 it.effect('[Then] shows --no-browser and --yes, no --org-id or --project-id', () =>
@@ -33,7 +28,6 @@ describe('CLI: composio dev init', () => {
28 Effect.gen(function* () {
29 const failure = yield* cli(['dev', 'init', '--yes']).pipe(Effect.flip);
30
36 - // `cli-main.ts` prints the message on stderr and exits 1.
31 expect(failure).toMatchObject({
32 _tag: 'commands/CommandInputError',
33 command: 'dev init',
@@ -76,7 +70,7 @@ describe('CLI: composio dev init', () => {
70 const lines = yield* MockConsole.getLines({ stripAnsi: true });
71
72 expect(result._tag).toBe('Failure');
79 - expect(lines).toEqual([
73 + expect(lines.slice(0, -1)).toEqual([
74 '-- composio dev init --',
75 'Could not fetch projects from the server.',
76 projectGuidance,
@@ -85,6 +79,9 @@ describe('CLI: composio dev init', () => {
79 projectGuidance,
80 '-- --',
81 ]);
82 + // The command fails with the client's error after its guidance, which the invocation
83 + // reports as a defect.
84 + expect(lines.at(-1)).toContain('@composio/client/APIConnectionError');
85 })
86 );
87 });
ts/packages/cli/test/src/commands/listen.cmd.test.ts
-5
@@ -1,4 +1,3 @@
1 -import { afterEach } from 'vitest';
1 import { describe, expect, layer } from '@effect/vitest';
2 import { ConfigProvider, Effect, Fiber, Latch, Layer } from 'effect';
3 import { TestClock } from 'effect/testing';
@@ -43,10 +42,6 @@ const failingRealtime = Layer.succeed(
42 );
43
44 describe('CLI: composio listen', () => {
46 - afterEach(() => {
47 - process.exitCode = undefined;
48 - });
49 -
45 layer(TestLive({ baseConfigProvider: testConfigProvider, fixture: 'global-test-user-id' }))(
46 '[Given] the realtime subscription fails',
47 it => {
ts/packages/cli/test/src/commands/logout.cmd.test.ts
+5 -8
@@ -1,5 +1,5 @@
1 -import { afterEach } from 'vitest';
2 -import { describe, expect, layer } from '@effect/vitest';
1 +import { assert, describe, expect, layer } from '@effect/vitest';
2 +import { isUsageFailure } from 'src/commands/errors';
3 import * as FileSystem from 'effect/FileSystem';
4 import { ConfigProvider, Effect, Option } from 'effect';
5 import path from 'node:path';
@@ -39,10 +39,6 @@ const setupLoggedInAgent = Effect.gen(function* () {
39 });
40
41 describe('CLI: composio logout', () => {
42 - afterEach(() => {
43 - process.exitCode = undefined;
44 - });
45 -
42 describe('[When] logged out', () => {
43 layer(TestLive())(it => {
44 it.effect('[Then] it is idempotent', () =>
@@ -138,7 +134,6 @@ describe('CLI: composio logout', () => {
134
135 const failure = yield* cli(['logout']).pipe(Effect.flip);
136
141 - // `cli-main.ts` prints the message on stderr and exits 1.
137 expect(failure).toMatchObject({
138 _tag: 'commands/CommandInputError',
139 command: 'logout',
@@ -146,7 +141,9 @@ describe('CLI: composio logout', () => {
141 message:
142 '`composio logout` needs --yes when not running interactively: it removes the stored Composio agent key.',
143 });
149 - expect(yield* MockConsole.getLines()).toEqual([]);
144 + // The invocation prints the message on stderr, and nothing else.
145 + assert(isUsageFailure(failure));
146 + expect(yield* MockConsole.getLines()).toEqual([failure.message]);
147 expect(ctx.isLoggedIn()).toBeTruthy();
148 expect(yield* agentConfigExists).toBe(true);
149 })
ts/packages/cli/test/src/commands/projects/list/projects.list.cmd.test.ts
+4 -1
@@ -131,7 +131,10 @@ describe('CLI: composio dev projects list', () => {
131 const stderr = yield* MockConsole.getLines({ stream: 'stderr', stripAnsi: true });
132 expect(noOrgRequests).toEqual([]);
133 expect(stdout).toEqual([]);
134 - expect(stderr).toEqual(['-- composio dev projects list --']);
134 + expect(stderr).toEqual([
135 + '-- composio dev projects list --',
136 + 'No current org is configured.\nHint: run `composio orgs switch` first, or pass `--org-id`.',
137 + ]);
138 })
139 );
140 });
ts/packages/cli/test/src/commands/projects/list/projects.list.handler.test.ts
+1 -1
@@ -126,7 +126,7 @@ describe('runProjectsList', () => {
126 option: '--org-id',
127 message: `${NO_CURRENT_ORG_MESSAGE}\n${NO_CURRENT_ORG_OUTRO}`,
128 });
129 - // `cli-main.ts` prints a usage failure on stderr and exits 1.
129 + // The invocation prints a usage failure on stderr and exits 1.
130 expect(isUsageFailure(failure)).toBe(true);
131 expect(requests).toEqual([]);
132 expect(outputs).toEqual([]);
ts/packages/cli/test/src/commands/root-help-consistency.test.ts
-5
@@ -1,6 +1,5 @@
1 import { describe, expect, layer } from '@effect/vitest';
2 import { Effect } from 'effect';
3 -import { afterEach } from 'vitest';
3 import { buildRootCommand } from 'src/commands';
4 import { cli, MockConsole, TestLive } from 'test/__utils__';
5 import { exitCodeOf } from 'test/__utils__/exit-code';
@@ -33,10 +32,6 @@ const visibleCommandPaths = commandPaths(
32 .map(path => ({ path, command: path.join(' ') }));
33
34 describe('framework command help', () => {
36 - afterEach(() => {
37 - process.exitCode = undefined;
38 - });
39 -
35 layer(TestLive())(it => {
36 it.effect.each(visibleCommandPaths)(
37 'renders $command from the same definitions used by parsing',
ts/packages/cli/test/src/commands/run.cmd.test.ts
+22 -24
@@ -24,7 +24,6 @@ import {
24 import { TestClock } from 'effect/testing';
25 import { ChildProcess, ChildProcessSpawner } from 'effect/process';
26 import { afterEach, beforeEach, it, vi } from 'vitest';
27 -import { createCliCommandTelemetryContext } from 'src/analytics/events';
27 import { buildRunHelpersSource, inferCliInvocationPrefix } from 'src/commands/run.cmd';
28 import {
29 extractInlineExecuteToolSlugs,
@@ -38,8 +37,7 @@ import {
37 writeInstalledReleaseTag,
38 } from 'src/services/run-companion-modules';
39 import { telemetryDebugModeLayer } from 'src/services/runtime-flags';
41 -import { DEFAULT_CLI_INVOCATION_ORIGIN } from 'src/services/runtime-cli-context';
42 -import { cli, MockConsole, TestLive } from 'test/__utils__';
40 +import { cli, MockConsole, recordedInvocationCalls, TestLive } from 'test/__utils__';
41 import { exitCodeOf } from 'test/__utils__/exit-code';
42 import { CommandRunner } from 'src/services/command-runner';
43 import { ChildProcessExited, ChildProcessSignaled } from 'src/effects/child-process-exited';
@@ -136,7 +134,6 @@ const inspectRunCommand = (command: ChildProcess.Command) => {
134
135 describe('CLI: composio run', () => {
136 afterEach(() => {
139 - process.exitCode = undefined;
137 commandRuns
138 .mockReset()
139 .mockImplementation(() => Effect.succeed(ChildProcessSpawner.ExitCode(0)));
@@ -146,28 +143,29 @@ describe('CLI: composio run', () => {
143 });
144
145 layer(RunTestLive())(it => {
149 - it.effect('[Given] a root run telemetry id [Then] the child receives the same run id', () =>
150 - Effect.gen(function* () {
151 - const telemetryContext = createCliCommandTelemetryContext(
152 - ['bun', 'composio', '--telemetry-debug', 'run', 'console.log("hi")'],
153 - '0.0.0-test',
154 - { stdoutIsTTY: false, stderrIsTTY: false },
155 - { invocationOrigin: DEFAULT_CLI_INVOCATION_ORIGIN, parentRunId: undefined }
156 - );
157 - const runId = telemetryContext.runId;
158 - assertDefined(runId);
159 -
160 - commandRuns.mockImplementation(command => {
161 - expect(inspectRunCommand(command).env.COMPOSIO_CLI_PARENT_RUN_ID).toBe(runId);
162 - return Effect.succeed(ChildProcessSpawner.ExitCode(0));
163 - });
146 + it.effect(
147 + '[Given] a root run [Then] the child receives the run id its telemetry recorded',
148 + () =>
149 + Effect.gen(function* () {
150 + let childRunId: string | undefined;
151 + commandRuns.mockImplementation(command => {
152 + childRunId = inspectRunCommand(command).env.COMPOSIO_CLI_PARENT_RUN_ID;
153 + return Effect.succeed(ChildProcessSpawner.ExitCode(0));
154 + });
155
165 - // The bootstrap hands the run id it minted for telemetry to the command, the way
166 - // `cli-main.ts` does, instead of publishing it through process-wide state.
167 - yield* cli(['--telemetry-debug', 'run', 'console.log("hi")'], { runId });
156 + // The invocation mints the run id for its telemetry and hands it to the command, instead
157 + // of publishing it through process-wide state.
158 + yield* cli(['--telemetry-debug', 'run', 'console.log("hi")']);
159
169 - expect(commandRuns).toHaveBeenCalledTimes(1);
170 - })
160 + expect(commandRuns).toHaveBeenCalledTimes(1);
161 + const invoked = (yield* recordedInvocationCalls).find(
162 + call => call.service === 'CommandLifecycleTelemetry' && call.event === 'invoked'
163 + );
164 + const runId =
165 + invoked?.service === 'CommandLifecycleTelemetry' ? invoked.context.runId : undefined;
166 + assertDefined(runId);
167 + expect(childRunId).toBe(runId);
168 + })
169 );
170 });
171
ts/packages/cli/test/src/commands/setup.cmd.test.ts
-9
@@ -234,7 +234,6 @@ describe('CLI: composio setup', () => {
234 afterEach(() => {
235 vi.restoreAllMocks();
236 vi.unstubAllEnvs();
237 - process.exitCode = undefined;
237 });
238
239 const freshClaude = makeFakeHosts({ claude: { available: true } });
@@ -1250,10 +1249,6 @@ const REASON_CODE_CASES: ReadonlyArray<{
1249 ];
1250
1251 describe('CLI: composio setup failure reason codes', () => {
1253 - afterEach(() => {
1254 - process.exitCode = undefined;
1255 - });
1256 -
1252 describe.each(REASON_CODE_CASES)('$hosts', ({ hosts, cases }) => {
1253 layer(TestLive({ commandRunner: REASON_CODE_FIXTURES[hosts]().runner }))(it => {
1254 it.effect.each(cases)('codes `setup $args` as $expected', ({ args, expected }) =>
@@ -1269,10 +1264,6 @@ describe('CLI: composio setup failure reason codes', () => {
1264 });
1265
1266 describe('CLI: composio setup rerun hints stay non-interactive safe', () => {
1272 - afterEach(() => {
1273 - process.exitCode = undefined;
1274 - });
1275 -
1267 layer(TestLive({ commandRunner: REASON_CODE_FIXTURES['only Claude Code installed']().runner }))(
1268 'targeted host missing',
1269 it => {
ts/packages/cli/test/src/commands/setup.telemetry.cmd.test.ts
-1
@@ -173,7 +173,6 @@ describe('CLI: composio setup telemetry', () => {
173
174 afterEach(() => {
175 vi.unstubAllEnvs();
176 - process.exitCode = undefined;
176 });
177
178 const hostSignals = makeFakeHosts({ claude: { available: true } });
ts/packages/cli/test/src/commands/signup/signup.cmd.test.ts
-1
@@ -42,7 +42,6 @@ const stubAgentsApi = (body: AgentIdentity) =>
42 describe('CLI: composio signup', () => {
43 afterEach(() => {
44 vi.restoreAllMocks();
45 - process.exitCode = undefined;
45 });
46
47 layer(TestLive())('[Given] no login', it => {
ts/packages/cli/test/src/commands/toolkits/info/toolkits.info.cmd.test.ts
+5 -7
@@ -1,5 +1,5 @@
1 -import { afterEach } from 'vitest';
2 -import { describe, expect, layer } from '@effect/vitest';
1 +import { assert, describe, expect, layer } from '@effect/vitest';
2 +import { isUsageFailure } from 'src/commands/errors';
3 import { ConfigProvider, DateTime, Effect, Layer } from 'effect';
4 import { cli, TestLive, MockConsole } from 'test/__utils__';
5 import { exitCodeOf } from 'test/__utils__/exit-code';
@@ -133,10 +133,6 @@ const testConfigProvider = ConfigProvider.fromEnv({
133 });
134
135 describe('CLI: composio dev toolkits info', () => {
136 - afterEach(() => {
137 - process.exitCode = undefined;
138 - });
139 -
136 layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))(
137 '[Given] valid slug "gmail"',
138 it => {
@@ -269,7 +265,9 @@ describe('CLI: composio dev toolkits info', () => {
265 message:
266 'Missing required argument: <slug>\nTry specifying a toolkit slug, e.g.:\n> composio dev toolkits info "gmail"',
267 });
272 - expect(yield* MockConsole.getLines()).toEqual([]);
268 + // The invocation prints the message on stderr, and nothing else.
269 + assert(isUsageFailure(failure));
270 + expect(yield* MockConsole.getLines()).toEqual([failure.message]);
271 })
272 );
273 }
ts/packages/cli/test/src/commands/toolkits/version/toolkits.version.cmd.test.ts
-5
@@ -1,4 +1,3 @@
1 -import { afterEach } from 'vitest';
1 import { describe, expect, layer } from '@effect/vitest';
2 import { ConfigProvider, DateTime, Effect } from 'effect';
3 import { cli, TestLive, MockConsole } from 'test/__utils__';
@@ -62,10 +61,6 @@ const testConfigProvider = ConfigProvider.fromEnv({
61 });
62
63 describe('CLI: composio dev toolkits version', () => {
65 - afterEach(() => {
66 - process.exitCode = undefined;
67 - });
68 -
64 layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))(
65 '[Given] valid slug [Then] shows latest and last 20 versions',
66 it => {
ts/packages/cli/test/src/commands/tools/info/tools.info.cmd.test.ts
+5 -6
@@ -1,4 +1,5 @@
1 -import { afterEach, describe, expect, layer } from '@effect/vitest';
1 +import { assert, describe, expect, layer } from '@effect/vitest';
2 +import { isUsageFailure } from 'src/commands/errors';
3 import { ConfigProvider, Effect } from 'effect';
4 import { cli, TestLive, MockConsole } from 'test/__utils__';
5 import { exitCodeOf } from 'test/__utils__/exit-code';
@@ -76,10 +77,6 @@ const testConfigProvider = ConfigProvider.fromEnv({
77 });
78
79 describe('CLI: composio tools info', () => {
79 - afterEach(() => {
80 - process.exitCode = undefined;
81 - });
82 -
80 layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))(
81 '[Given] valid slug [Then] displays tool info',
82 it => {
@@ -144,7 +141,9 @@ describe('CLI: composio tools info', () => {
141 option: '<slug>',
142 message: expect.stringContaining('Missing required argument: <slug>'),
143 });
147 - expect(yield* MockConsole.getLines()).toEqual([]);
144 + // The invocation prints the message on stderr, and nothing else.
145 + assert(isUsageFailure(failure));
146 + expect(yield* MockConsole.getLines()).toEqual([failure.message]);
147 })
148 );
149 }
ts/packages/cli/test/src/commands/tools/info/tools.info.handler.test.ts
+2 -6
@@ -1,4 +1,4 @@
1 -import { afterEach, describe, expect, it } from '@effect/vitest';
1 +import { describe, expect, it } from '@effect/vitest';
2 import { ConfigProvider, Effect, Layer, Option } from 'effect';
3 import { isUsageFailure } from 'src/commands/errors';
4 import { runToolsInfo } from 'src/commands/tools/info/tools.info.handler';
@@ -54,10 +54,6 @@ const toolsInfoTest = () => {
54 };
55
56 describe('runToolsInfo', () => {
57 - afterEach(() => {
58 - process.exitCode = undefined;
59 - });
60 -
57 it.effect('[Given] no slug [Then] fails with a usage error before any request', () => {
58 const { layer, outputs } = toolsInfoTest();
59 return Effect.gen(function* () {
@@ -73,7 +69,7 @@ describe('runToolsInfo', () => {
69 option: '<slug>',
70 message: `${MISSING_SLUG_MESSAGE}\n${MISSING_SLUG_HINT}`,
71 });
76 - // `cli-main.ts` prints a usage failure on stderr and exits 1.
72 + // The invocation prints a usage failure on stderr and exits 1.
73 expect(isUsageFailure(failure)).toBe(true);
74 expect(yield* MockConsole.getLines()).toEqual([]);
75 expect(outputs).toEqual([]);
ts/packages/cli/test/src/commands/tools/tools.execute.cmd.test.ts
+8 -5
@@ -931,11 +931,14 @@ describe('CLI: composio execute', () => {
931 ]);
932
933 expect(recordedExecuteParams[0]?.account).toBe('ca_1');
934 - // Every lookup — account selection, the permission gate, error
935 - // mapping — must ask for the project execute resolved.
936 - expect(recordedProjectToolkitScopes.length).toBeGreaterThan(0);
937 - expect(recordedProjectToolkitScopes).toEqual(
938 - recordedProjectToolkitScopes.map(() => ({
934 + // The invocation's telemetry resolves the tool's toolkit first, before execute knows
935 + // its project. Every lookup execute makes after it — account selection, the
936 + // permission gate, error mapping — must ask for the project execute resolved.
937 + const [telemetryScope, ...executeScopes] = recordedProjectToolkitScopes;
938 + expect(telemetryScope).toBeUndefined();
939 + expect(executeScopes.length).toBeGreaterThan(0);
940 + expect(executeScopes).toEqual(
941 + executeScopes.map(() => ({
942 orgId: 'org_test',
943 projectId: 'consumer_project_test',
944 }))
ts/packages/cli/test/src/commands/triggers/create/triggers.create.cmd.test.ts
+5 -4
@@ -1,4 +1,4 @@
1 -import { describe, expect, layer } from '@effect/vitest';
1 +import { assert, describe, expect, layer } from '@effect/vitest';
2 import { ConfigProvider, Effect, Layer, Option } from 'effect';
3 import type { TriggerInstanceUpsertParams } from '@composio/client/resources/trigger-instances';
4 import { isUsageFailure } from 'src/commands/errors';
@@ -240,9 +240,10 @@ describe('CLI: composio dev triggers create', () => {
240 option,
241 message: expect.stringMatching(message),
242 });
243 - // `cli-main.ts` prints a usage failure on stderr and exits 1.
244 - expect(isUsageFailure(failure)).toBe(true);
245 - expect(yield* MockConsole.getLines()).toEqual([]);
243 + // The invocation prints the message on stderr, and nothing else. The suite shares one
244 + // console, so this case's line is the last one.
245 + assert(isUsageFailure(failure));
246 + expect((yield* MockConsole.getLines()).at(-1)).toBe(failure.message);
247 })
248 );
249 }
ts/packages/cli/test/src/commands/triggers/disable/triggers.disable.cmd.test.ts
+5 -2
@@ -1,4 +1,5 @@
1 -import { describe, expect, layer } from '@effect/vitest';
1 +import { assert, describe, expect, layer } from '@effect/vitest';
2 +import { isUsageFailure } from 'src/commands/errors';
3 import { ConfigProvider, Effect, Layer } from 'effect';
4 import { ComposioToolkitsRepository } from 'src/services/composio-clients';
5 import { cli, MockConsole, TestLive } from 'test/__utils__';
@@ -44,7 +45,9 @@ describe('CLI: composio dev triggers disable', () => {
45 /^Missing required argument: <id>\nTry specifying a trigger ID, e\.g\.:\n> composio dev triggers disable "trg_123"/
46 ),
47 });
47 - expect(yield* MockConsole.getLines()).toEqual([]);
48 + // The invocation prints the message on stderr, and nothing else.
49 + assert(isUsageFailure(failure));
50 + expect(yield* MockConsole.getLines()).toEqual([failure.message]);
51 })
52 );
53 }
ts/packages/cli/test/src/commands/triggers/enable/triggers.enable.cmd.test.ts
+4 -4
@@ -1,4 +1,4 @@
1 -import { describe, expect, layer } from '@effect/vitest';
1 +import { assert, describe, expect, layer } from '@effect/vitest';
2 import { ConfigProvider, Effect, Layer } from 'effect';
3 import { isUsageFailure } from 'src/commands/errors';
4 import { ComposioToolkitsRepository } from 'src/services/composio-clients';
@@ -51,9 +51,9 @@ describe('CLI: composio dev triggers enable', () => {
51 /^Missing required argument: <id>\n[\s\S]*> composio dev triggers status --show-disabled$/
52 ),
53 });
54 - // `cli-main.ts` prints a usage failure on stderr and exits 1.
55 - expect(isUsageFailure(failure)).toBe(true);
56 - expect(yield* MockConsole.getLines()).toEqual([]);
54 + // The invocation prints the message on stderr, and nothing else.
55 + assert(isUsageFailure(failure));
56 + expect(yield* MockConsole.getLines()).toEqual([failure.message]);
57 })
58 );
59 }
ts/packages/cli/test/src/commands/triggers/info/triggers.info.cmd.test.ts
+5 -6
@@ -1,4 +1,5 @@
1 -import { afterEach, describe, expect, layer } from '@effect/vitest';
1 +import { assert, describe, expect, layer } from '@effect/vitest';
2 +import { isUsageFailure } from 'src/commands/errors';
3 import { ConfigProvider, Effect } from 'effect';
4 import { cli, MockConsole, TestLive } from 'test/__utils__';
5 import { exitCodeOf } from 'test/__utils__/exit-code';
@@ -55,10 +56,6 @@ const testConfigProvider = ConfigProvider.fromEnv({
56 });
57
58 describe('CLI: composio dev triggers info', () => {
58 - afterEach(() => {
59 - process.exitCode = undefined;
60 - });
61 -
59 layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))(
60 '[Given] root triggers info [Then] displays trigger info with root-level hint',
61 it => {
@@ -113,7 +110,9 @@ describe('CLI: composio dev triggers info', () => {
110 message:
111 'Missing required argument: <slug>\nTry specifying a trigger slug, e.g.:\n> composio dev triggers info "GMAIL_NEW_GMAIL_MESSAGE"',
112 });
116 - expect(yield* MockConsole.getLines()).toEqual([]);
113 + // The invocation prints the message on stderr, and nothing else.
114 + assert(isUsageFailure(failure));
115 + expect(yield* MockConsole.getLines()).toEqual([failure.message]);
116 })
117 );
118
ts/packages/cli/test/src/commands/triggers/triggers.listen.cmd.test.ts
-5
@@ -1,5 +1,4 @@
1 import type { ServerResponse } from 'node:http';
2 -import { afterEach } from 'vitest';
2 import { describe, expect, layer } from '@effect/vitest';
3 import { ConfigProvider, Effect, Fiber, Latch, Layer } from 'effect';
4 import { ComposioCliUserConfig } from 'src/services/cli-user-config';
@@ -35,10 +34,6 @@ const failingRealtime = Layer.succeed(
34 );
35
36 describe('CLI: composio dev listen', () => {
38 - afterEach(() => {
39 - process.exitCode = undefined;
40 - });
41 -
37 layer(TestLive({ baseConfigProvider: testConfigProvider, fixture: 'global-test-user-id' }))(
38 '[Given] the realtime subscription fails',
39 it => {
ts/packages/cli/test/src/commands/whoami.cmd.test.ts
+6 -4
@@ -1,20 +1,22 @@
1 -import { describe, expect, layer } from '@effect/vitest';
1 +import { assert, describe, expect, layer } from '@effect/vitest';
2 +import { isUsageFailure } from 'src/commands/errors';
3 import { ConfigProvider, Effect } from 'effect';
4 import { cli, TestLive, MockConsole } from 'test/__utils__';
5 import { makeSessionInfo } from 'test/__utils__/models/account';
6
7 describe('CLI: composio whoami', () => {
8 layer(TestLive())('without a login', it => {
8 - it.effect('[Given] no API key [Then] fails with NotLoggedInError and prints nothing', () =>
9 + it.effect('[Given] no API key [Then] fails with NotLoggedInError and prints its message', () =>
10 Effect.gen(function* () {
11 const failure = yield* cli(['whoami']).pipe(Effect.flip);
12
12 - // `cli-main.ts` prints the message on stderr and exits 1.
13 expect(failure).toMatchObject({
14 _tag: 'commands/NotLoggedInError',
15 message: 'You are not logged in yet. Please run `composio login`.',
16 });
17 - expect(yield* MockConsole.getLines()).toEqual([]);
17 + // The invocation prints the message on stderr, and nothing else.
18 + assert(isUsageFailure(failure));
19 + expect(yield* MockConsole.getLines()).toEqual([failure.message]);
20 })
21 );
22 });
ts/packages/cli/test/src/invocation/invocation.test.ts new
+210
@@ -0,0 +1,210 @@
1 +import { describe, expect, it, layer } from '@effect/vitest';
2 +import { Cause, ConfigProvider, Data, Effect, Exit, Layer, Runtime } from 'effect';
3 +import { ExpectedFailure } from 'src/effects/expected-failure';
4 +import { ReportedFailure } from 'src/effects/report-failure';
5 +import { runnerCause } from 'src/invocation/invocation';
6 +import { ComposioToolkitsRepository } from 'src/services/composio-clients';
7 +import {
8 + cliExit,
9 + exitCodeOf,
10 + MockConsole,
11 + recordedInvocationCalls,
12 + resetInvocationCalls,
13 + TestLive,
14 +} from 'test/__utils__';
15 +import type { TestLiveInput } from 'test/__utils__/services/test-layer';
16 +import { makeToolkitsRepositoryStub } from 'test/__utils__/services/toolkits-repository-stub';
17 +
18 +/** Logged in through the environment, with no current org stored. */
19 +const loggedInWithoutOrg: TestLiveInput = {
20 + baseConfigProvider: ConfigProvider.fromEnvRecord({ COMPOSIO_USER_API_KEY: 'uak_test' }),
21 +};
22 +
23 +/**
24 + * Runs `args` over a fresh `TestLive`, with `overrides` replacing its services, and returns its
25 + * exit code and output.
26 + */
27 +const invoke = (
28 + args: ReadonlyArray<string>,
29 + input?: TestLiveInput,
30 + overrides: Layer.Layer<never> = Layer.empty
31 +) =>
32 + Effect.gen(function* () {
33 + const { exit, exitCode } = yield* cliExit(args).pipe(Effect.provide(overrides));
34 + const stdout = yield* MockConsole.getLines({ stream: 'stdout', stripAnsi: true });
35 + const stderr = yield* MockConsole.getLines({ stream: 'stderr', stripAnsi: true });
36 + return { exit, exitCode, stdout, stderr };
37 + }).pipe(Effect.provide(TestLive(input)));
38 +
39 +/** The services the recording doubles saw, and the lifecycle event names, in order. */
40 +const recordedSequence = Effect.map(recordedInvocationCalls, calls =>
41 + calls.map(call =>
42 + call.service === 'CommandLifecycleTelemetry' ? `${call.service}.${call.event}` : call.service
43 + )
44 +);
45 +
46 +describe('runInvocation', () => {
47 + layer(TestLive())('lifecycle', it => {
48 + it.effect.each([
49 + { args: [], exitCode: 0, outcome: 'succeeded' },
50 + { args: ['help'], exitCode: 0, outcome: 'succeeded' },
51 + { args: ['--help'], exitCode: 0, outcome: 'succeeded' },
52 + { args: ['--version'], exitCode: 0, outcome: 'succeeded' },
53 + { args: ['help', 'orgz'], exitCode: 1, outcome: 'failed' },
54 + ])(
55 + '[Given] `composio $args` [Then] runs the hooks, then records the command as $outcome',
56 + ({ args, exitCode, outcome }) =>
57 + Effect.gen(function* () {
58 + // The suite shares one recorder.
59 + yield* resetInvocationCalls;
60 +
61 + const result = yield* cliExit(args);
62 +
63 + expect(result.exitCode).toBe(exitCode);
64 + expect(yield* recordedSequence).toEqual([
65 + 'BackendMismatchWarning',
66 + 'UpdateNotice',
67 + 'PluginHint',
68 + 'CommandLifecycleTelemetry.invoked',
69 + `CommandLifecycleTelemetry.${outcome}`,
70 + ]);
71 + })
72 + );
73 + });
74 +
75 + // Each of these used to print its message only to a terminal and exit 0, so a script, CI or
76 + // an agent saw nothing and a successful exit; `connections remove` used to answer its own
77 + // confirmation prompt with "no".
78 + it.effect.each([
79 + {
80 + name: 'whoami without a login',
81 + args: ['whoami'],
82 + input: {},
83 + message: 'You are not logged in yet. Please run `composio login`.',
84 + },
85 + {
86 + name: 'tools list without a login',
87 + args: ['tools', 'list', 'gmail'],
88 + input: {},
89 + message: 'You are not logged in yet. Please run `composio login`.',
90 + },
91 + {
92 + name: 'connections list without a current org',
93 + args: ['connections', 'list'],
94 + input: loggedInWithoutOrg,
95 + message: 'No current org configured. Run `composio login` or `composio dev orgs switch`.',
96 + },
97 + {
98 + name: 'dev connected-accounts info without an id',
99 + args: ['dev', 'connected-accounts', 'info'],
100 + input: loggedInWithoutOrg,
101 + message: 'Missing required argument: <id>',
102 + },
103 + {
104 + name: 'triggers info without a slug',
105 + args: ['triggers', 'info'],
106 + input: loggedInWithoutOrg,
107 + message: 'Missing required argument: <slug>',
108 + },
109 + {
110 + name: 'connections remove without --yes',
111 + args: ['connections', 'remove', 'gmail'],
112 + input: { fixture: 'user-config-with-global-context' },
113 + message: '`composio connections remove` needs --yes when not running interactively.',
114 + },
115 + {
116 + name: 'dev projects list without a current org',
117 + args: ['dev', 'projects', 'list'],
118 + input: loggedInWithoutOrg,
119 + message: 'No current org is configured.',
120 + },
121 + {
122 + name: 'a bare run',
123 + args: ['run'],
124 + input: {},
125 + message: 'Provide inline code or use --file to run a script file.',
126 + },
127 + {
128 + name: 'execute with arguments that are not an object',
129 + args: ['execute', 'GITHUB_GET_THE_AUTHENTICATED_USER', '-d', '[]'],
130 + input: { fixture: 'user-config-with-global-context' },
131 + message: 'Expected a JSON object for tool arguments',
132 + },
133 + ])(
134 + '[Given] $name [Then] prints the message alone on stderr and exits 1',
135 + ({ args, input, message }) =>
136 + Effect.gen(function* () {
137 + const { exit, exitCode, stdout, stderr } = yield* invoke(args, input);
138 +
139 + expect(exitCode).toBe(1);
140 + // The command's own error, not one the invocation made up.
141 + expect(Exit.isFailure(exit) && Cause.hasFails(exit.cause)).toBe(true);
142 + expect(stdout).toEqual([]);
143 + expect(stderr.at(-1)).toContain(message);
144 + const output = stderr.join('\n');
145 + expect(output).not.toContain('Error');
146 + expect(output).not.toContain('Sources');
147 + expect(output).not.toContain('RUN_LOG_FILE=');
148 + })
149 + );
150 +
151 + it.effect('[Given] a defect [Then] prints the defect report once and exits 1', () =>
152 + Effect.gen(function* () {
153 + const { exit, exitCode, stderr } = yield* invoke(
154 + ['dev', 'toolkits', 'list'],
155 + { fixture: 'user-config-with-global-context' },
156 + // Every repository method dies.
157 + Layer.succeed(ComposioToolkitsRepository, makeToolkitsRepositoryStub({}))
158 + );
159 +
160 + expect(exitCode).toBe(1);
161 + expect(Exit.isFailure(exit) && Cause.hasDies(exit.cause)).toBe(true);
162 + expect(stderr.filter(line => line.includes('💥'))).toHaveLength(1);
163 + })
164 + );
165 +});
166 +
167 +class UsageMistake extends Data.TaggedError('test/UsageMistake')<{ readonly message: string }> {
168 + get [ExpectedFailure]() {
169 + return true;
170 + }
171 +}
172 +
173 +class PrintedWithCode extends Data.TaggedError('test/PrintedWithCode')<{}> {
174 + get [Runtime.errorReported]() {
175 + return false;
176 + }
177 +
178 + get [Runtime.errorExitCode]() {
179 + return 7;
180 + }
181 +}
182 +
183 +describe('runnerCause', () => {
184 + it('[Given] a failure the invocation printed [Then] the runner gets it already reported', () => {
185 + const cause = runnerCause(Cause.fail(new UsageMistake({ message: 'no' })));
186 +
187 + const error = Cause.squash(cause);
188 + expect(error).toBeInstanceOf(ReportedFailure);
189 + expect(Runtime.getErrorReported(error)).toBe(false);
190 + expect(exitCodeOf(Exit.fail(new UsageMistake({ message: 'no' })))).toBe(1);
191 + });
192 +
193 + it('[Given] a defect [Then] the runner gets it already reported', () => {
194 + expect(Cause.squash(runnerCause(Cause.die(new Error('boom'))))).toBeInstanceOf(ReportedFailure);
195 + });
196 +
197 + it('[Given] a failure already on screen [Then] it keeps its markers and exit code', () => {
198 + const cause = Cause.fail(new PrintedWithCode());
199 +
200 + expect(runnerCause(cause)).toBe(cause);
201 + expect(exitCodeOf(Exit.failCause(cause))).toBe(7);
202 + });
203 +
204 + it('[Given] an interruption [Then] it stays one, so a signal can still decide the code', () => {
205 + const cause = Cause.interrupt();
206 +
207 + expect(runnerCause(cause)).toBe(cause);
208 + expect(exitCodeOf(Exit.failCause(cause))).toBe(130);
209 + });
210 +});
ts/packages/cli/test/src/invocation/report-invocation-failure.test.ts renamed
+7 -5
@@ -2,8 +2,8 @@ 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';
5 import { ReportedFailure } from 'src/effects/report-failure';
6 +import { reportInvocationFailure } from 'src/invocation/invocation';
7 import { MockConsole } from 'test/__utils__';
8 import { exitCodeOf } from 'test/__utils__/exit-code';
9 import { TerminalUITest } from 'test/__utils__/services/terminal-ui-test';
@@ -18,7 +18,7 @@ const TestLayer = Layer.mergeAll(
18
19 const report = (cause: Cause.Cause<unknown>) =>
20 Effect.gen(function* () {
21 - const exit = yield* Effect.exit(reportUnreportedCause(cause));
21 + const exit = yield* Effect.exit(reportInvocationFailure(cause));
22 const stderr = yield* MockConsole.getLines({ stream: 'stderr' });
23 return { exit, stderr };
24 }).pipe(Effect.provide(TestLayer));
@@ -26,7 +26,7 @@ const report = (cause: Cause.Cause<unknown>) =>
26 const failureOf = (exit: Exit.Exit<unknown, unknown>) =>
27 Exit.isFailure(exit) ? Cause.squash(exit.cause) : undefined;
28
29 -describe('reportUnreportedCause', () => {
29 +describe('reportInvocationFailure', () => {
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());
@@ -51,9 +51,11 @@ describe('reportUnreportedCause', () => {
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')));
54 + const defect = new Error('boom');
55
56 - expect(failureOf(exit)).toBeInstanceOf(ReportedFailure);
56 + const { exit, stderr } = yield* report(Cause.die(defect));
57 +
58 + expect(failureOf(exit)).toBe(defect);
59 expect(exitCodeOf(exit)).toBe(1);
60 expect(stderr).toHaveLength(1);
61 expect(stderr[0]).toContain('boom');
ts/packages/cli/test/src/services/invocation-hooks-test-layer.test.ts
+9 -1
@@ -6,7 +6,12 @@ import { BackendMismatchWarning } from 'src/services/backend-mismatch-warning';
6 import { CommandLifecycleTelemetry } from 'src/services/command-lifecycle-telemetry';
7 import { PluginHint } from 'src/services/plugin-hint';
8 import { UpdateNotice } from 'src/services/update-check';
9 -import { MockConsole, recordedInvocationCalls, TestLive } from 'test/__utils__';
9 +import {
10 + MockConsole,
11 + recordedInvocationCalls,
12 + resetInvocationCalls,
13 + TestLive,
14 +} from 'test/__utils__';
15 import { trackedEvents } from 'test/__utils__/tracked-events';
16
17 // Records instead of dispatching, so a double that reached the real sink would show up below.
@@ -50,6 +55,9 @@ describe('TestLive invocation hooks and telemetry sink', () => {
55 // The doubles are no-ops: nothing reaches the console or the analytics dispatcher.
56 expect(yield* MockConsole.getLines()).toEqual([]);
57 expect(trackedEvents).toEqual([]);
58 +
59 + yield* resetInvocationCalls;
60 + expect(yield* recordedInvocationCalls).toEqual([]);
61 })
62 );
63 });
ts/packages/cli/test/src/services/update-check.test.ts
+1 -1
@@ -303,7 +303,7 @@ describe('showUpdateNotice', () => {
303 );
304 });
305
306 -// ── UpdateNotice (the service cli-main runs) ────────────────────────────
306 +// ── UpdateNotice (the service the invocation runs) ────────────────────────────
307
308 describe('UpdateNotice', () => {
309 /** `UpdateNotice.Default` over a home directory in `tempDir` and a recording, decorating stderr. */