@devries-cameron20 / composio Mirror · read-only / commits / 83e442e6b
Fork 0

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

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

Synced Nov 21, 07:15 UTC

refactor(cli): run hooks and the login gate from command metadata (#5135)

This PR: - runs the update notice, plugin hint, backend mismatch warning and background update check when the selected command begins (`CommandInvocation.begin`), for its identity, instead of before parsing from argv; they run before the invoked event, so the backend mismatch warning still precedes the toolkit lookup that `execute`'s invoked event makes; `HookInvocation` now carries that `CommandIdentity` and no argv - adds `hooks` to `CommandMeta`: a per-hook policy (`false`, or a predicate over the parsed input; subcommands inherit a boolean, while a predicate applies only to the registration that declares it), declared next to the telemetry families in `src/commands/index.ts`: `upgrade` skips the notice and the background check, `version --check` the background check, `setup` (and `setup skill`) the plugin hint, `help …` everything - runs no hooks for a group run without a subcommand when its own handler only shows its help (`composio tools`, `composio orgs`, `composio dev triggers`, the bare root), like `--help`: `withRegisteredSubcommands` begins that handler with no parsed input unless the group passes `{ ownAction: true }`, as `dev` (the developer-mode toggle), `setup` and `generate` do. `effect/cli` does not expose whether a command has a handler, so the group declares it; the option sits on the registration call, not in `CommandMeta`, so subcommands do not inherit it. This replaces a path check for the root in the invocation - turns the background update check into a hook service (`BackgroundUpdateCheck`), forked with `Effect.forkDetach` instead of a separate `Effect.runPromiseExit` and deletes `withBackgroundUpdateCheck`, `findRootCommandName` and the argv `upgrade` check in `showUpdateNotice` - replaces the `requireLogin` combinator with a plain `withCommandMeta({ requiresLogin: true })` at its 18 call sites (and in the CLI `AGENTS.md` and the `cli-command` skill); the login is still checked right after `begin`, now after the hooks - moves `CLI_PLUGIN_HINT_SHOWN` behind `CommandLifecycleTelemetry` (`pluginHintShown`), which records the full command path - corrects the Effect version stated in the CLI `AGENTS.md` and the `effect-v4`, `typescript-testing` and `cli-command` skills (the workspace locks 4.0.5) ## Context Based on `next` now that #5134 (command identity after parse) is merged. User-visible change (CHANGELOG, Patch): `--help`, `--version`, `composio help …`, a bare `composio`, a bare group that only prints its help (`composio tools`, `composio orgs`) and a typo or other parse failure no longer print the update notice, the plugin tip or the backend mismatch warning, and no longer start the background release check. Telemetry: `CLI_PLUGIN_HINT_SHOWN.command_path` is the full path (`dev triggers list`) instead of the first argv word. `dev triggers list` without a login records `parse_error`, not `NotLoggedInError`: `<toolkit>` is a required argument, and parsing fails before any command begins. With the argument (`dev triggers list gmail`) it records `commands/NotLoggedInError` for `dev triggers list`. Manual check (`bun src/bin.ts`, `CLAUDECODE=1`, isolated `COMPOSIO_CACHE_DIR` and `CLAUDE_CONFIG_DIR`, logged out), first stderr lines: | Invocation | Before | After | | --- | --- | --- | | `--help` | plugin tip | nothing | | `upgrade --help` | plugin tip | nothing | | `whoamii` (typo) | plugin tip, then help | help | | `composio` (bare) | plugin tip | nothing | | `help tools` | plugin tip | nothing | | `whoami` | plugin tip, `You are not logged in yet…` | same | | `version` | plugin tip | same | | `dev triggers list gmail` | plugin tip, `You are not logged in yet…` | same | | `setup skill --help` | nothing | nothing | | `tools` (bare group) | plugin tip, `You are not logged in yet…` | `You are not logged in yet…` | | `orgs` (bare group) | plugin tip, `You are not logged in yet…` | `You are not logged in yet…` | | `dev triggers` (dev mode on) | plugin tip, `You are not logged in yet…` | `You are not logged in yet…` | | `dev`, `dev --mode off` (dev mode on or off) | plugin tip | same (the group's own action) | | `tools list gmail` | plugin tip, `You are not logged in yet…` | same | A bare login-gated group still checks the login before its help, as on `next`. Tests: `test/src/invocation/invocation-hooks.test.ts` pins hooks before the invoked event and the login check (`NotLoggedInError` for `tools list`), no hooks for help, version, typos, a missing argument, the bare root, bare groups (`tools`, `orgs`, `dev triggers`) and `help`, hooks for `dev` and `dev --mode off` (a group's own action), the opt-out table (9 commands × 4 hooks), and that a group's hook predicate is not inherited by its subcommands. The plugin hint's event is asserted through the real `CommandLifecycleTelemetry`. Verification: `pnpm typecheck`, `pnpm --filter @composio/cli run lint:effect`, `pnpm --filter @composio/cli test` (220 files, 2862 passed, 1 skipped), `./node_modules/.bin/oxlint ts/packages/cli` (no errors).

Alberto Schiabel committed Oct 28, 2026 at 18:42 UTC 83e442e6b68566c8a75885b7d5ddd6f600074e4f
56 files changed +757 -519
.agents/skills/cli-command/references/implementation.md
+2 -2
@@ -17,13 +17,13 @@ test/src/commands/<group>/<name>/<group>.<name>.handler.test.ts handler-level
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; 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`.
20 +- A command that needs a login declares `withCommandMeta({ requiresLogin: true })` (`src/invocation/command-identity.ts`) on itself or on its group entry; the selected command checks it right after it began, and 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.
23
24 ## Effect Patterns
25
26 -The CLI is on `effect@4.0.3` (exact pin) plus `@effect/platform-bun`/`@effect/vitest` at the same version. `@effect/cli` and `@effect/platform` no longer exist as separate deps — their functionality is consolidated into `effect`'s barrel and `effect/*` submodules.
26 +The CLI is on `effect@4.0.5` (exact pin) plus `@effect/platform-bun`/`@effect/vitest` at the same version. `@effect/cli` and `@effect/platform` no longer exist as separate deps — their functionality is consolidated into `effect`'s barrel and `effect/*` submodules.
27
28 Common shape. The command file declares the surface and passes the handler to the three-argument `Command.make`:
29
.agents/skills/effect-v4/SKILL.md
+3 -3
@@ -1,6 +1,6 @@
1 ---
2 name: effect-v4
3 -description: Write, review, or upgrade Effect v4 code in the Composio CLI, cli-keyring, and json-schema-to-effect-schema packages, all pinned exactly to effect@4.0.3 — Context.Service and explicit layers, Schema.TaggedError and typed recovery, the effect/cli command surface, and the vendored effect source oracle. Use when writing or reviewing Effect v4 code, answering a v4 API question, working in effect/cli, defining a Context.Service service, modeling an error with Schema.TaggedError, bumping the Effect pins, or verifying an unfamiliar API against ts/vendor/effect. Do not use for CLI command UX/wiring design (use cli-command) or CLI E2E tests (use cli-e2e).
3 +description: Write, review, or upgrade Effect v4 code in the Composio CLI, cli-keyring, and json-schema-to-effect-schema packages, all pinned exactly to effect@4.0.5 — Context.Service and explicit layers, Schema.TaggedError and typed recovery, the effect/cli command surface, and the vendored effect source oracle. Use when writing or reviewing Effect v4 code, answering a v4 API question, working in effect/cli, defining a Context.Service service, modeling an error with Schema.TaggedError, bumping the Effect pins, or verifying an unfamiliar API against ts/vendor/effect. Do not use for CLI command UX/wiring design (use cli-command) or CLI E2E tests (use cli-e2e).
4 ---
5
6 # Effect v4
@@ -11,7 +11,7 @@ Effect v4. Every claim below is grounded in the migrated source, not memory of v
11 ## Exact version matrix
12
13 `effect`, `@effect/platform-bun`, and `@effect/vitest`
14 -are pinned to the **same exact** `4.0.3` — never `^`, `@next`, or a mismatched
14 +are pinned to the **same exact** `4.0.5` — never `^`, `@next`, or a mismatched
15 version across packages. `@effect/cli` and `@effect/platform` no longer exist as
16 dependencies; their surfaces are consolidated into `effect` and `effect/*`.
17 See [versions.json](versions.json) for the full matrix (also `typescript`, `vitest`).
@@ -53,7 +53,7 @@ trust the file and fix the reference.
53 ESLint bans them in `ts/packages/cli/src`.
54 - Treat every remembered v3 package name and API as wrong until verified against
55 `ts/vendor/effect` (read-only source oracle — never edit or import from it) and the
56 - installed `effect@4.0.3` typings. Source may be ahead of the published package;
56 + installed `effect@4.0.5` typings. Source may be ahead of the published package;
57 the compiler is the compatibility gate.
58
59 ## Verification
.agents/skills/effect-v4/versions.json
+3 -3
@@ -1,7 +1,7 @@
1 {
2 - "effect": "4.0.3",
3 - "@effect/platform-bun": "4.0.3",
4 - "@effect/vitest": "4.0.3",
2 + "effect": "4.0.5",
3 + "@effect/platform-bun": "4.0.5",
4 + "@effect/vitest": "4.0.5",
5 "@types/node": "26.6.4",
6 "typescript": "6.0.2",
7 "vitest": "5.0.3"
.agents/skills/typescript-testing/SKILL.md
+1 -1
@@ -1,6 +1,6 @@
1 ---
2 name: typescript-testing
3 -description: Select and run TypeScript SDK verification for packages, examples, type checks, linting, builds, Vitest suites, Effect v4 CLI tests, and runtime E2E tests. Use when adding tests, diagnosing TypeScript CI, choosing a focused test command, validating TypeScript package changes, or writing/porting CLI tests against effect@4.0.3 and @effect/vitest. Do not use for Python-only checks.
3 +description: Select and run TypeScript SDK verification for packages, examples, type checks, linting, builds, Vitest suites, Effect v4 CLI tests, and runtime E2E tests. Use when adding tests, diagnosing TypeScript CI, choosing a focused test command, validating TypeScript package changes, or writing/porting CLI tests against effect@4.0.5 and @effect/vitest. Do not use for Python-only checks.
4 ---
5
6 # TypeScript Testing
.agents/skills/typescript-testing/references/effect-v4-cli.md
+2 -2
@@ -1,7 +1,7 @@
1 # Effect v4 CLI testing
2
3 -The CLI test suite (`ts/packages/cli/test/`) runs on `effect@4.0.3` and
4 -`@effect/vitest@4.0.3` (pinned exactly, matching `ts/packages/cli/package.json` and the
3 +The CLI test suite (`ts/packages/cli/test/`) runs on `effect@4.0.5` and
4 +`@effect/vitest@4.0.5` (pinned exactly, matching `ts/packages/cli/package.json` and the
5 workspace catalog in `pnpm-workspace.yaml`). `@effect/cli` and `@effect/platform` no longer exist
6 as dependencies — their functionality moved into `effect`/`effect/*`. Read
7 `ts/packages/cli/test/__utils__/services/test-layer.ts` before writing a new test suite; it is the
.agents/skills/typescript-testing/references/test-commands.md
+1 -1
@@ -39,7 +39,7 @@ pnpm --filter @composio/<provider> typecheck
39
40 ## CLI Effect v4 tests
41
42 -`ts/packages/cli` tests run on `effect@4.0.3` and a matching `@effect/vitest` (both pinned
42 +`ts/packages/cli` tests run on `effect@4.0.5` and a matching `@effect/vitest` (both pinned
43 exactly in `pnpm-workspace.yaml`). Read [effect-v4-cli.md](effect-v4-cli.md) before writing or
44 porting a CLI test — it covers `it.effect`/`layer(...)` usage, explicit per-service test layers
45 (v4's `Context.Service` has no auto-generated `.Default` the way v3's `Effect.Service` did), and
ts/packages/cli/AGENTS.md
+21 -20
@@ -31,7 +31,7 @@ Signals belong to the runner, the one place that installs SIGINT, SIGTERM and SI
31
32 Errors are captured via the custom `effect-errors/` module (source-mapped stack traces, Effect span timelines, formatted output).
33
34 -The invocation learns which command it runs after `effect/cli` parsed argv, never from argv itself ([ADR 0001](docs/adr/0001-command-identity-after-parse.md)). A command's identity (`src/invocation/command-identity.ts`) is its command registration: the command path from the root plus the `CommandMeta` it declares (one `Command.annotate` key, set with `withCommandMeta`: the lifecycle `telemetryFamily`, and `requiresLogin`, which `requireLogin` sets and subcommands inherit). Every group registers its subcommands with `withRegisteredSubcommands` (`src/commands/registration.ts`), which provides each registration's identity around its dispatch; only the selected command's handler calls `CommandInvocation.begin`, which reports the invoked event, then checks a required login. `--help` and `--version` (the `Help` and `Version` actions in `root-help.ts`) and a parse failure (`CliError.ShowHelp.commandPath`, canonical names only, `failure_reason_code: "parse_error"`) begin the command `effect/cli` names. `test/src/commands/registration.test.ts` pins the handler composition order this relies on. Telemetry families are declared on root registrations in `src/commands/index.ts`; `dev` commands report the generic family.
34 +The invocation learns which command it runs after `effect/cli` parsed argv, never from argv itself ([ADR 0001](docs/adr/0001-command-identity-after-parse.md)). A command's identity (`src/invocation/command-identity.ts`) is its command registration: the command path from the root plus the `CommandMeta` it declares (one `Command.annotate` key, set with `withCommandMeta`: the lifecycle `telemetryFamily`; `requiresLogin`; and `hooks`, the invocation hooks the command turns off, by name, with `false` or a predicate over its parsed input; subcommands inherit the last two, except a hook predicate, which applies only where it is declared). Every group registers its subcommands with `withRegisteredSubcommands` (`src/commands/registration.ts`), which provides each registration's identity around its dispatch; only the selected command's handler calls `CommandInvocation.begin`, which runs the command's invocation hooks and then reports the invoked event (whose toolkit lookup for `execute` is a backend request, so the backend mismatch warning comes first), then the command checks a required login. `--help` and `--version` (the `Help` and `Version` actions in `root-help.ts`) and a parse failure (`CliError.ShowHelp.commandPath`, canonical names only, `failure_reason_code: "parse_error"`) begin the command `effect/cli` names, with no parsed input and so no hooks. So does a group run with no subcommand, whose own handler only shows its help (the bare root command included), unless the group declares that handler an action of its own (`withRegisteredSubcommands(subcommands, { ownAction: true })`: `dev`, `setup`, `generate`); `help …` turns every hook off in its `CommandMeta`. `test/src/commands/registration.test.ts` pins the handler composition order this relies on. Telemetry families and hook opt-outs are declared on root registrations in `src/commands/index.ts`; `dev` commands report the generic family.
35
36 ### Commands — `src/commands/`
37
@@ -94,7 +94,7 @@ Rules:
94 - A handler that acts as a user gets it, and the project it was resolved against, from `actingUser` (fails with `MissingActingUserError`, an expected failure whose message fits the tree) or `actingUserOption` (for a command that also runs without one) in `surface.ts`; both name a fallback test user on stderr. A handler never reads `--user-id` or a test user id to resolve one itself, never prints that notice, and lets `MissingActingUserError` through instead of wrapping it in its own error (its tag is the `error_name` telemetry reports). An empty consumer user id counts as none. A `--user-id` that only filters results (`dev logs`, `dev triggers listen`, `dev connected-accounts list`) stays a raw flag.
95 - Logic shared across groups belongs in `src/effects/` or `src/services/`, never in another command's directory.
96 - A group registers its subcommands with `withRegisteredSubcommands` (`src/commands/registration.ts`), never `Command.withSubcommands`, so each subcommand gets its command identity.
97 -- A command that needs a logged-in user pipes `requireLogin` (`src/effects/require-auth.ts`) on itself or on its group entry; it declares `requiresLogin` in `CommandMeta`, which the selected command checks right after recording its identity. Handlers never check `apiKey` or print a login hint; a missing login fails with `NotLoggedInError` and exits 1. Project context comes from `resolveCommandProject`, which fails with `ProjectResolutionError`; never flatten it into a plain `Error`.
97 +- A command that needs a logged-in user pipes `withCommandMeta({ requiresLogin: true })` on itself or on its group entry, and the selected command checks it right after it began (`assertLoggedIn` in `src/effects/require-auth.ts`). Handlers never check `apiKey` or print a login hint; a missing login fails with `NotLoggedInError` and exits 1. Project context comes from `resolveCommandProject`, which fails with `ProjectResolutionError`; never flatten it into a plain `Error`.
98 - A group entry is recognised by its place in the tree: `<dir>/<dir>.cmd.ts` or `<dir>/root-<dir>.cmd.ts` with other `.cmd.ts` files below `<dir>/`. The same name with nothing below it (`logout/logout.cmd.ts`) is a top-level command. Every command needs a test; a group entry does not, though one with a default action (`generate`) still gets one.
99
100 Legacy shape still present while commands migrate: `<group>/commands/<group>.<name>.cmd.ts` holding flags, handler, helpers, and errors in one file, and top-level `<name>.cmd.ts` doing the same. Migrate a command to the directory shape when you touch it for more than a one-line fix, one command per PR.
@@ -114,33 +114,34 @@ test/src/commands/<group>/<shared-module>.test.ts group helper
114
115 ### Services — `src/services/`
116
117 -| Service | Purpose |
118 -| ---------------------------------- | -------------------------------------------------------------------------------------------------- |
119 -| `ComposioUserContext` | Auth state — reads/writes `~/.composio/user-config.json`, merges env vars |
120 -| `ComposioClientSingleton` | Builds an `@composio/client/effect` client per lookup for a key, org, and project; counts requests |
121 -| `ComposioSessionRepository` | Creates OAuth2 sessions, polls until `linked` state |
122 -| `ComposioToolkitsRepository` | API client — fetches toolkits, tools, trigger types; validates versions |
123 -| `ComposioToolkitsRepositoryCached` | Decorator over base repository with file-based caching and graceful fallback |
124 -| `NodeOs` | OS abstraction (`homedir`, `platform`, `arch`) |
125 -| `JsPackageManagerDetector` | Detects npm/pnpm/yarn/bun for install instructions |
126 -| `UpgradeBinary` | Fetches latest release from GitHub, downloads and replaces binary |
127 -| `DashboardToolExecution` | Sends consumer `composio execute` calls to the Composio Dashboard and decodes its reply |
128 -| `BackendMismatchWarning` | Warns before a command when an env var sends the stored key to a backend other than its issuer |
129 -| `UpdateNotice` | Prints the cached "update available" hint before a command, except `upgrade` |
130 -| `PluginHint` | Prints the Composio agent plugin hint under Claude Code or Codex, at most once a day |
131 -| `CommandLifecycleTelemetry` | Tracks the running command's invoked (once it began), succeeded, and failed events |
117 +| Service | Purpose |
118 +| ---------------------------------- | --------------------------------------------------------------------------------------------------------------- |
119 +| `ComposioUserContext` | Auth state — reads/writes `~/.composio/user-config.json`, merges env vars |
120 +| `ComposioClientSingleton` | Builds an `@composio/client/effect` client per lookup for a key, org, and project; counts requests |
121 +| `ComposioSessionRepository` | Creates OAuth2 sessions, polls until `linked` state |
122 +| `ComposioToolkitsRepository` | API client — fetches toolkits, tools, trigger types; validates versions |
123 +| `ComposioToolkitsRepositoryCached` | Decorator over base repository with file-based caching and graceful fallback |
124 +| `NodeOs` | OS abstraction (`homedir`, `platform`, `arch`) |
125 +| `JsPackageManagerDetector` | Detects npm/pnpm/yarn/bun for install instructions |
126 +| `UpgradeBinary` | Fetches latest release from GitHub, downloads and replaces binary |
127 +| `DashboardToolExecution` | Sends consumer `composio execute` calls to the Composio Dashboard and decodes its reply |
128 +| `BackendMismatchWarning` | Warns before a command when an env var sends the stored key to a backend other than its issuer |
129 +| `UpdateNotice` | Prints the cached "update available" hint before a command |
130 +| `PluginHint` | Prints the Composio agent plugin hint under Claude Code or Codex, at most once a day |
131 +| `BackgroundUpdateCheck` | Starts refreshing the cached latest release in the background, at most once a day |
132 +| `CommandLifecycleTelemetry` | Tracks the running command's invoked (once it began), succeeded, and failed events, and the plugin hint's event |
133
134 Every Composio API request goes through an Effect client from `@composio/client/effect`, obtained from `ComposioClientSingleton` (`src/services/composio-clients.ts`). Clients are built with `make`, which never reads the ambient environment: the user key and base URL come from the CLI's own configuration. Each client is built with the CLI's `identity` (`cliClientIdentity()` in `client-provenance.ts`, from which the client sends the provenance headers and which makes it refuse them in `defaultHeaders` and per-call `headers`), `auth` (`Auth.user` with the user key, `Auth.project` when a caller passes `projectApiKey`, `Auth.none()` before login), `scope` (the org and project, when both are known), `x-cli-session-id` as the one default header (read once per process), and a counting `fetch` (`composio-client-metrics.ts`) provided as the transport's `FetchHttpClient.Fetch`. Explicitly configured HTTP base URLs remain supported without an additional environment flag. The client's deprecation notices, which CLI users cannot act on, are dropped by the root logger (`withoutClientNotices`, `src/effects/without-client-notices.ts`, through the client's `isDeprecationNotice`). `composio-clients.ts` holds client construction, the two repositories, and the `collectAll` and `sortBySlug` helpers the catalog fetches share. The repository's auth-config, connected-account, trigger-instance, search, and single-item methods live in `src/services/composio-resource-operations.ts`; the account helpers (`listOrganizations`, `getSessionInfo*`, `resolveConsumerProject`, `createProjectApiKey`, `getLatestToolVersion`, …) in `src/services/composio-account.ts`; toolkit version validation and its errors (`InvalidToolkitsError`, `InvalidToolkitVersionsError`) in `src/services/toolkit-version-validation.ts`; the shared error types (`ClientError`, `HttpDecodingError`, `ComposioClientConfigurationError`) in `src/services/composio-errors.ts`; and the shared `decode` helper and `validated` request option in `src/services/composio-request.ts`. There is no CLI error wrapper around a request: the client's tagged errors (`@composio/client/NotFoundError`, `APIConnectionError`, `DecodeError`, …) flow to callers, which recover with `Effect.catchTag` or the client's `isAPIError` guard. Commands that report an API failure with a hint and exit 1 share one handler, `handleClientApiError` (`src/effects/handle-http-error.ts`), applied with `Effect.catchTag(CLIENT_API_ERROR_TAGS, …)`; it never succeeds, so the command reads the request's result straight through; the tag list lives in `src/services/composio-errors.ts`. Endpoints the client does not type use the raw `client.get`/`client.post`; `src/services/tool-permissions.ts` reaches them through its own `requestJson`, which raises `services/ToolPermissionsRequestError` because its callers fail closed on that tag. Do not add a raw `fetch` to the Composio backend from `src/commands`, `src/effects`, or `src/services` — the one sanctioned exception is the bundled companion runtime (`run-helpers-runtime.ts`), which runs in the user's spawned process outside the Effect runtime. (`src/services/agents.ts` also calls `fetch`, against the agents service at agents.composio.dev rather than the Composio backend.) The Composio Dashboard (`ComposioUserContext.data.webURL`) is the one first-party host the CLI calls without `@composio/client`: `src/services/dashboard-tool-execution.ts` sends consumer `composio execute` calls (tool and meta-tool executions) to it over `HttpClient` from `effect/http`, once, with no retry, no redirect following and one 15-minute deadline, only to an `https:` base URL (or loopback `http:`) that carries no credentials, query or fragment, and fails a relayed backend failure with the client's own status error (`@composio/client/PermissionDeniedError`, …) so the classification below still applies. While telemetry is enabled, those requests (and only those) also carry the stored analytics install ID as `x-cli-install-id`, read through `readInstallIdWhenTelemetryEnabled` in `src/analytics/dispatch.ts`, which never creates an ID and never fails; do not add the header to backend requests or to `cliRequestHeaders()`. Everything else on the execute path (connection lookups, the permission gate, file uploads) and `dev playground-execute` stay on the backend client. Do not route other commands through the Dashboard, and do not add a second raw-HTTP host, without updating this paragraph. oxlint rejects value imports of the `@composio/client` root and `@composio/client/pagination` from CLI `src/`; type-only imports are allowed. The CLI's clients send every request once. A call that is safe to repeat — a read, or a call whose repeat changes nothing on the server — passes the `idempotent` request option (`src/services/composio-request.ts`) and is retried by the client after a connection failure, a timeout, or a 408, 409, 429 or 5xx response; combine it with `validated` as `{ ...idempotent, ...validated }`. Creates, updates, deletes, links, sessions, tool executions and proxied calls never pass it, because a request that failed in flight may already have acted. It also rejects importing `make` or the client layers from `@composio/client/effect` anywhere but `composio-clients.ts`, and `getFor` takes an org and a project together or neither, because the two headers are only sent as a pair. Every `getFor` builds a new client, so never key a memo on a client instance: `clientScopeKey(client)` gives its auth mode, a SHA-256 fingerprint of its credential (never the key), org, and project (`listActiveConnectedAccounts` keys on it and the user id). While a client has `auth` and `scope`, a per-call `x-api-key`, `x-user-api-key`, `x-org-api-key`, `x-org-id` or `x-project-id` header fails the call before it is sent; an org or project known alone goes on an unscoped client's request, as `orgScopedOptions` and `getLatestToolVersion` do. Client errors are classified for display by `src/utils/api-error-extraction.ts`.
135
136 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.
137
137 -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.
138 +The invocation runs `BackendMismatchWarning`, `UpdateNotice`, `PluginHint`, and `BackgroundUpdateCheck` (each an `InvocationHookShape` from `src/services/invocation-hook.ts`, taking a `HookInvocation` that carries the selected command's identity) in that order when the selected command begins, before its invoked event, skipping those its `CommandMeta` turns off (`INVOCATION_HOOKS` and `runsHook` in `src/invocation/command-identity.ts`), and reports the command's lifecycle through `CommandLifecycleTelemetry`. A hook never reads argv and never fails the command. `TestLive` replaces all five 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.
139
140 OS credential storage uses the sibling package `@composio/cli-keyring` (macOS Keychain / Linux Secret Service).
141
142 ### Effects — `src/effects/`
143
143 -Reusable Effect computations: `require-auth` (`requireLogin`, the login gate for commands and groups), `setup-cache-dir`, `toolkit-version-overrides` (maps `COMPOSIO_TOOLKIT_VERSION_<NAME>=<ver>` pins to toolkit slugs), `validate-toolkit-versions`, `with-log-level`, `find-composio-core-generated`, `version`, `compare-semver`, `log-metrics`, `capture-services` (`captureServices`, for a layer whose methods provide services it captured).
144 +Reusable Effect computations: `require-auth` (`assertLoggedIn`, the login check behind `requiresLogin`), `setup-cache-dir`, `toolkit-version-overrides` (maps `COMPOSIO_TOOLKIT_VERSION_<NAME>=<ver>` pins to toolkit slugs), `validate-toolkit-versions`, `with-log-level`, `find-composio-core-generated`, `version`, `compare-semver`, `log-metrics`, `capture-services` (`captureServices`, for a layer whose methods provide services it captured).
145
146 ### Models — `src/models/`
147
@@ -168,7 +169,7 @@ Steps 3–4 (and the TypeScript compiler they need) ship as the `generation-runt
169
170 ### Key Dependencies
171
171 -`effect` (pinned `4.0.3`; `@effect/cli` and `@effect/platform` no longer exist as separate packages — folded into `effect`'s barrel and `effect/{cli,http,process}`), `@effect/platform-bun`, `@effect/vitest` (same exact pin), `@clack/prompts` (terminal UI — stderr by default), `picocolors`, `@composio/client` (owned Composio API client, `2.0.0-rc.22` via the workspace catalog; the CLI calls it through the `@composio/client/effect` entry point and imports only types from the rest of the package), `@composio/core` (types), `@composio/ts-builders` (AST gen), `@composio/cli-keyring` (OS credential store), `@composio/json-schema-to-effect-schema`, `semver`, `open`, `extract-zip`.
172 +`effect` (pinned exactly to `4.0.5` through the workspace catalog; `@effect/cli` and `@effect/platform` no longer exist as separate packages — folded into `effect`'s barrel and `effect/{cli,http,process}`), `@effect/platform-bun`, `@effect/vitest` (same exact pin), `@clack/prompts` (terminal UI — stderr by default), `picocolors`, `@composio/client` (owned Composio API client, `2.0.0-rc.22` via the workspace catalog; the CLI calls it through the `@composio/client/effect` entry point and imports only types from the rest of the package), `@composio/core` (types), `@composio/ts-builders` (AST gen), `@composio/cli-keyring` (OS credential store), `@composio/json-schema-to-effect-schema`, `semver`, `open`, `extract-zip`.
173
174 ## Output Conventions: Composable CLI Output
175
ts/packages/cli/CHANGELOG.md
+12
@@ -84,6 +84,18 @@
84 `""`. `composio run` starts the script without the consumer user's context,
85 as it does when there is no consumer user.
86
87 +- The update notice, the Composio plugin tip, the backend mismatch warning,
88 + and the daily background check for a newer release now run only for a
89 + command that runs. `--help`, `--version`, `composio help …`, a bare
90 + `composio` or command group that only prints its help (`composio tools`,
91 + `composio orgs`), and a mistyped command or flag no longer print them or
92 + start the check; a group with an action of its own (`composio dev`,
93 + `composio setup`, `composio generate`) still does. `composio upgrade` still
94 + skips the notice and the check, `composio version --check` the check, and
95 + `composio setup` the plugin tip.
96 + The `CLI_PLUGIN_HINT_SHOWN` event now records the full command path
97 + (`dev triggers list`) instead of the first word.
98 +
99 - CLI telemetry now records the command `effect/cli` parsed instead of guessing
100 it from argv. `composio signup`, `agent …`, `connections …`, `config …`,
101 `debug …` and `help …` were recorded as `composio`, `composio dev init` as
ts/packages/cli/docs/adr/0001-command-identity-after-parse.md
+1 -1
@@ -28,7 +28,7 @@ Industry practice agrees: gh, the Stripe CLI, cobra and commander based CLIs, Tu
28 - Parse failures still emit the invoked and failed pair, so current dashboards keep working. The path comes from `ShowHelp`, uses canonical command names, never raw user tokens, and the reason is `parse_error`. A separate rejected event (as the Stripe CLI does) was considered and deferred; adopting it means migrating funnels on purpose.
29 - The design depends on the order in which effect/cli (`effect` 4.0.5, the version the workspace locks) composes handlers in `withSubcommands`, which is undocumented. A contract test (`test/src/commands/registration.test.ts`) pins it (nested providers, guards, bare groups, reused registrations, root shortcuts), so an `effect` upgrade that changes it fails there first.
30 - Group-level guards such as `requireLogin` can run before the selected handler, so they would fire without an identity. They become command metadata, enforced right after identity is recorded.
31 -- Invocation hooks (update notice, plugin hint) still run before parsing, so `--help`, `--version`, and typos can still show them.
31 +- Hooks that ran before parse (update notice, plugin hint) run only for a selected command, so `--help`, `--version`, typos, and a group that only shows its help no longer show them. A group's own handler that is an action (`composio dev --mode`) still runs them; the group declares it, since effect/cli does not expose whether a command has a handler.
32
33 ## Revisit when
34
ts/packages/cli/src/commands/auth-configs/auth-configs.cmd.ts
+2 -2
@@ -1,4 +1,4 @@
1 -import { requireLogin } from 'src/effects/require-auth';
1 +import { withCommandMeta } from 'src/invocation/command-identity';
2 import { Command } from 'effect/cli';
3 import { authConfigsCmd$List } from './list/auth-configs.list.cmd';
4 import { authConfigsCmd$Info } from './info/auth-configs.info.cmd';
@@ -16,5 +16,5 @@ import { withRegisteredSubcommands } from 'src/commands/registration';
16 export const authConfigsCmd = Command.make('auth-configs').pipe(
17 Command.withDescription('View and manage Composio auth configs.'),
18 withRegisteredSubcommands([authConfigsCmd$List, authConfigsCmd$Info, authConfigsCmd$Create]),
19 - requireLogin
19 + withCommandMeta({ requiresLogin: true })
20 );
ts/packages/cli/src/commands/background-update-check.ts deleted
-49
@@ -1,49 +0,0 @@
1 -import { Effect, Predicate } from 'effect';
2 -import { Command } from 'effect/cli';
3 -import { versionCmd } from './version.cmd';
4 -import { upgradeCmd } from './upgrade/upgrade.cmd';
5 -import { checkForUpdateInBackground } from 'src/services/update-check';
6 -import { withRegisteredSubcommands } from 'src/commands/registration';
7 -
8 -const isExplicitVersionCheck = (commandName: string, input: unknown): boolean =>
9 - commandName === versionCmd.name && Predicate.hasProperty(input, 'check') && input.check === true;
10 -
11 -/** `composio upgrade` resolves releases itself and records a live stable result in the cache. */
12 -const resolvesReleasesItself = (commandName: string, input: unknown): boolean =>
13 - commandName === upgradeCmd.name || isExplicitVersionCheck(commandName, input);
14 -
15 -/**
16 - * Builds the root command so the background update request starts only after the CLI has parsed
17 - * the selected command, and never for an explicit `composio version --check` or `composio upgrade`.
18 - *
19 - * `effect/cli` keeps the selected subcommand private to the parent's dispatcher, so the
20 - * hook is attached per subcommand (each sees its own parsed input) plus the root itself for the
21 - * no-subcommand path, before the tree is assembled with `withRegisteredSubcommands`, which also
22 - * registers each subcommand under the root.
23 - */
24 -export const withBackgroundUpdateCheck = <
25 - const Name extends string,
26 - Input,
27 - ContextInput,
28 - E,
29 - R,
30 - const Subcommands extends ReadonlyArray<Command.Command.Any>,
31 ->(
32 - root: Command.Command<Name, Input, ContextInput, E, R>,
33 - subcommands: Subcommands,
34 - start: () => void = checkForUpdateInBackground
35 -) => {
36 - const startInBackground = Effect.sync(start);
37 - const guarded = subcommands.map(subcommand =>
38 - subcommand.pipe(
39 - Command.provideEffectDiscard((input: unknown) =>
40 - resolvesReleasesItself(subcommand.name, input) ? Effect.void : startInBackground
41 - )
42 - )
43 - ) as unknown as Subcommands;
44 -
45 - return root.pipe(
46 - Command.provideEffectDiscard(startInBackground),
47 - withRegisteredSubcommands(guarded)
48 - );
49 -};
ts/packages/cli/src/commands/connected-accounts/connected-accounts.cmd.ts
+2 -2
@@ -1,4 +1,4 @@
1 -import { requireLogin } from 'src/effects/require-auth';
1 +import { withCommandMeta } from 'src/invocation/command-identity';
2 import { Command } from 'effect/cli';
3 import { rejectsSharedFlags } from 'src/commands/surface';
4 import { connectedAccountsCmd$List } from './list/connected-accounts.list.cmd';
@@ -23,5 +23,5 @@ export const connectedAccountsCmd = Command.make('connected-accounts').pipe(
23 connectedAccountsCmd$Info.pipe(rejectsSharedFlags('dev connected-accounts info')),
24 connectedAccountsCmd$Whoami.pipe(rejectsSharedFlags('dev connected-accounts whoami')),
25 ]),
26 - requireLogin
26 + withCommandMeta({ requiresLogin: true })
27 );
ts/packages/cli/src/commands/connected-accounts/link/connected-accounts.link.cmd.ts
+2 -2
@@ -1,5 +1,5 @@
1 import { Argument, Command, Flag } from 'effect/cli';
2 -import { requireLogin } from 'src/effects/require-auth';
2 +import { withCommandMeta } from 'src/invocation/command-identity';
3 import { runConnectedAccountsLink } from './connected-accounts.link.handler';
4
5 const toolkit = Argument.String('toolkit').pipe(
@@ -60,5 +60,5 @@ export const connectedAccountsCmd$Link = Command.make(
60 'Connect an external account (GitHub, Gmail, Slack, etc.) so tools can act on your behalf.'
61 ),
62 Command.withExamples(linkExamples),
63 - requireLogin
63 + withCommandMeta({ requiresLogin: true })
64 );
ts/packages/cli/src/commands/connections/connections.cmd.ts
+2 -2
@@ -1,4 +1,4 @@
1 -import { requireLogin } from 'src/effects/require-auth';
1 +import { withCommandMeta } from 'src/invocation/command-identity';
2 import { Command } from 'effect/cli';
3 import { connectionsCmd$List } from './list/connections.list.cmd';
4 import { connectionsCmd$Remove } from './remove/connections.remove.cmd';
@@ -7,5 +7,5 @@ import { withRegisteredSubcommands } from 'src/commands/registration';
7 export const rootConnectionsCmd = Command.make('connections').pipe(
8 Command.withDescription('Inspect and remove connected toolkit accounts.'),
9 withRegisteredSubcommands([connectionsCmd$List, connectionsCmd$Remove]),
10 - requireLogin
10 + withCommandMeta({ requiresLogin: true })
11 );
ts/packages/cli/src/commands/dev.cmd.ts
+3 -3
@@ -1,4 +1,4 @@
1 -import { requireLogin } from 'src/effects/require-auth';
1 +import { withCommandMeta } from 'src/invocation/command-identity';
2 import { Command, Flag } from 'effect/cli';
3 import { Effect, Option } from 'effect';
4 import { CommandInputError } from './errors';
@@ -43,7 +43,7 @@ const projectName = Flag.String('project-name').pipe(
43 export const devSubcommands = [
44 initCmd.pipe(rejectsSharedFlags('dev init')),
45 devToolsCmd$Execute,
46 - triggersCmd$Listen.pipe(requireLogin),
46 + triggersCmd$Listen.pipe(withCommandMeta({ requiresLogin: true })),
47 logsCmd.pipe(rejectsSharedFlags('dev logs', ['--project-name'])),
48 toolkitsCmd,
49 authConfigsCmd.pipe(rejectsSharedFlags('dev auth-configs')),
@@ -181,7 +181,7 @@ export const buildDevCommand = (visibility: CommandVisibility) =>
181 Effect.andThen(developerModeHandler(input))
182 )
183 ).pipe(
184 - withRegisteredSubcommands([...devSubcommands]),
184 + withRegisteredSubcommands([...devSubcommands], { ownAction: true }),
185 Command.withSharedFlags({ userId, projectName }),
186 Command.provide(({ userId, projectName }) => CommandSurface.dev({ userId, projectName }))
187 )
ts/packages/cli/src/commands/generate/generate.cmd.ts
+1 -1
@@ -45,5 +45,5 @@ export const generateCmd = Command.make(
45 Command.withDescription(
46 'Generate type stubs for toolkits, tools, and triggers, auto-detecting project language (TypeScript | Python)'
47 ),
48 - withRegisteredSubcommands([generateCmd$Py, generateCmd$Ts])
48 + withRegisteredSubcommands([generateCmd$Py, generateCmd$Ts], { ownAction: true })
49 );
ts/packages/cli/src/commands/index.ts
+34 -10
@@ -1,7 +1,11 @@
1 -import { Array as Arr, Console, Effect } from 'effect';
1 +import { Array as Arr, Console, Effect, Schema } from 'effect';
2 import { CliError, CliOutput, Command } from 'effect/cli';
3 import type { TelemetryFamily } from 'src/analytics/types';
4 -import { beginAtCommandPath, withCommandMeta } from 'src/invocation/command-identity';
4 +import {
5 + beginAtCommandPath,
6 + type CommandMetaShape,
7 + withCommandMeta,
8 +} from 'src/invocation/command-identity';
9 import { $defaultCmd, withRootLogLevel } from './$default.cmd';
10 import { getVersion } from 'src/effects/version';
11 import { versionCmd } from './version.cmd';
@@ -39,7 +43,7 @@ import { cliDebugFlagsLayer, CLI_DEBUG_GLOBAL_FLAGS } from 'src/services/runtime
43 import { ComposioCliUserConfig } from 'src/services/cli-user-config';
44 import { CLI_EXPERIMENTAL_FEATURES } from 'src/constants';
45 import { experimental, type CommandVisibility, tagged, visibleValues } from './feature-tags';
42 -import { withBackgroundUpdateCheck } from './background-update-check';
46 +import { withRegisteredSubcommands } from './registration';
47 import { debugCmd } from './debug/debug.cmd';
48 import { normalizeListenStreamFlag, normalizeRunScriptArgs } from './argv-compat';
49 import { configureCliAnalyticsReleaseVersion } from 'src/analytics/events';
@@ -50,14 +54,35 @@ import { CommandSurface } from './surface';
54 // generic `CLI_COMMAND_*` events.
55 const family = (telemetryFamily: TelemetryFamily) => withCommandMeta({ telemetryFamily });
56
57 +// Every invocation hook runs for every selected command (`src/invocation/invocation.ts`) except
58 +// where a root registration below turns one off; its subcommands inherit that.
59 +const hooks = (policies: NonNullable<CommandMetaShape['hooks']>) =>
60 + withCommandMeta({ hooks: policies });
61 +
62 +/** `composio version --check` resolves releases itself, like `composio upgrade`. */
63 +const isExplicitVersionCheck = Schema.is(Schema.Struct({ check: Schema.Literal(true) }));
64 +
65 +/** `composio help …` only prints help, like `--help`. */
66 +const NO_HOOKS = {
67 + backendMismatch: false,
68 + updateNotice: false,
69 + pluginHint: false,
70 + backgroundUpdateCheck: false,
71 +} as const;
72 +
73 const ROOT_COMMANDS = [
74 tagged(debugCmd),
55 - tagged(versionCmd),
56 - tagged(upgradeCmd),
75 + tagged(
76 + versionCmd.pipe(hooks({ backgroundUpdateCheck: input => !isExplicitVersionCheck(input) }))
77 + ),
78 + // `composio upgrade` resolves the latest release live and records it in the cache, so a cached
79 + // notice could only repeat or contradict it.
80 + tagged(upgradeCmd.pipe(hooks({ updateNotice: false, backgroundUpdateCheck: false }))),
81 tagged(whoamiCmd),
82 tagged(loginCmd.pipe(family('login'))),
83 tagged(signupCmd),
60 - tagged(setupCmd.pipe(family('setup'))),
84 + // `composio setup` installs the plugin the hint asks for.
85 + tagged(setupCmd.pipe(family('setup'), hooks({ pluginHint: false }))),
86 tagged(agentCmd),
87 experimental(CLI_EXPERIMENTAL_FEATURES.LISTEN, listenCmd),
88 tagged(logoutCmd.pipe(family('logout'))),
@@ -86,10 +111,9 @@ const getVisibleRootCommands = (visibility: CommandVisibility) => {
111
112 export const buildRootCommand = (visibility: CommandVisibility) => {
113 const commands = getVisibleRootCommands(visibility);
89 - return withBackgroundUpdateCheck($defaultCmd.pipe(Command.withHandler(() => showCommandHelp())), [
90 - ...commands,
91 - buildHelpCommand(commands),
92 - ]).pipe(
114 + return $defaultCmd.pipe(
115 + Command.withHandler(() => showCommandHelp()),
116 + withRegisteredSubcommands([...commands, buildHelpCommand(commands).pipe(hooks(NO_HOOKS))]),
117 Command.annotate(RootHelpMarker, true),
118 Command.withGlobalFlags(CLI_DEBUG_GLOBAL_FLAGS),
119 withRootLogLevel,
ts/packages/cli/src/commands/listen.cmd.ts
+2 -2
@@ -1,4 +1,4 @@
1 -import { requireLogin } from 'src/effects/require-auth';
1 +import { withCommandMeta } from 'src/invocation/command-identity';
2 import { reportFailure } from 'src/effects/report-failure';
3 import { eventCount, finishAcceptedEvents, makeSinkFailures } from './triggers/sink-failures';
4 import { commandInputError } from 'src/commands/errors';
@@ -740,5 +740,5 @@ export const listenCmd = Command.make(
740 command: "composio listen GMAIL_NEW_GMAIL_MESSAGE -p @trigger.json --stream '.data.threadId'",
741 },
742 ]),
743 - requireLogin
743 + withCommandMeta({ requiresLogin: true })
744 );
ts/packages/cli/src/commands/logs/logs.cmd.ts
+2 -2
@@ -1,5 +1,5 @@
1 import { Command } from 'effect/cli';
2 -import { requireLogin } from 'src/effects/require-auth';
2 +import { withCommandMeta } from 'src/invocation/command-identity';
3 import { logsCmd$Tools } from './tools/logs.tools.cmd';
4 import { logsCmd$Triggers } from './triggers/logs.triggers.cmd';
5 import { withRegisteredSubcommands } from 'src/commands/registration';
@@ -15,5 +15,5 @@ import { withRegisteredSubcommands } from 'src/commands/registration';
15 export const logsCmd = Command.make('logs').pipe(
16 Command.withDescription('Inspect trigger and tool execution logs.'),
17 withRegisteredSubcommands([logsCmd$Triggers, logsCmd$Tools]),
18 - requireLogin
18 + withCommandMeta({ requiresLogin: true })
19 );
ts/packages/cli/src/commands/orgs/list/orgs.list.handler.ts
+1 -1
@@ -25,7 +25,7 @@ export const runOrgsList = ({ limit }: OrgsListParams) =>
25 Effect.gen(function* () {
26 const ui = yield* TerminalUI;
27 const ctx = yield* ComposioUserContext;
28 - // `requireLogin` on the `orgs` group has already proven the key is there.
28 + // `requiresLogin` on the `orgs` group has already proven the key is there.
29 const apiKey = yield* Effect.fromOption(ctx.data.apiKey, notLoggedIn);
30 const currentOrgId = ctx.data.orgId;
31
ts/packages/cli/src/commands/orgs/orgs.cmd.ts
+2 -2
@@ -1,4 +1,4 @@
1 -import { requireLogin } from 'src/effects/require-auth';
1 +import { withCommandMeta } from 'src/invocation/command-identity';
2 import { Command } from 'effect/cli';
3 import { orgsCmd$List } from './list/orgs.list.cmd';
4 import { orgsCmd$Switch } from './switch/orgs.switch.cmd';
@@ -10,5 +10,5 @@ import { withRegisteredSubcommands } from 'src/commands/registration';
10 export const orgsCmd = Command.make('orgs').pipe(
11 Command.withDescription('Manage default global organization/project context.'),
12 withRegisteredSubcommands([orgsCmd$List, orgsCmd$Switch]),
13 - requireLogin
13 + withCommandMeta({ requiresLogin: true })
14 );
ts/packages/cli/src/commands/orgs/switch/orgs.switch.handler.ts
+2 -2
@@ -28,8 +28,8 @@ export const runOrgsSwitch = ({ orgId, limit }: OrgsSwitchParams) =>
28 Effect.gen(function* () {
29 const ui = yield* TerminalUI;
30 const ctx = yield* ComposioUserContext;
31 - // `requireLogin` on the `orgs` group has already proven the key is there; the
32 - // filter also fails a stored empty key, which `requireLogin` counts as present.
31 + // `requiresLogin` on the `orgs` group has already proven the key is there; the
32 + // filter also fails a stored empty key, which the login check counts as present.
33 const apiKey = yield* Effect.fromOption(
34 Option.filter(ctx.data.apiKey, key => key.length > 0),
35 notLoggedIn
ts/packages/cli/src/commands/projects/list/projects.list.cmd.ts
+2 -2
@@ -1,5 +1,5 @@
1 import { Command, Flag } from 'effect/cli';
2 -import { requireLogin } from 'src/effects/require-auth';
2 +import { withCommandMeta } from 'src/invocation/command-identity';
3 import { runProjectsList } from './projects.list.handler';
4
5 const orgId = Flag.String('org-id').pipe(
@@ -14,5 +14,5 @@ const limit = Flag.Int('limit').pipe(
14
15 export const projectsCmd$List = Command.make('list', { orgId, limit }, runProjectsList).pipe(
16 Command.withDescription('List developer projects for the current organization.'),
17 - requireLogin
17 + withCommandMeta({ requiresLogin: true })
18 );
ts/packages/cli/src/commands/projects/list/projects.list.handler.ts
+1 -1
@@ -34,7 +34,7 @@ export const runProjectsList = ({ orgId, limit }: ProjectsListParams) =>
34 Effect.gen(function* () {
35 const ui = yield* TerminalUI;
36 const ctx = yield* ComposioUserContext;
37 - // `requireLogin` on the command has already proven the key is there.
37 + // `requiresLogin` on the command has already proven the key is there.
38 const apiKey = yield* Effect.fromOption(ctx.data.apiKey, notLoggedIn);
39
40 yield* ui.intro(PROJECTS_LIST_INTRO);
ts/packages/cli/src/commands/proxy.cmd.ts
+2 -2
@@ -1,4 +1,4 @@
1 -import { requireLogin } from 'src/effects/require-auth';
1 +import { withCommandMeta } from 'src/invocation/command-identity';
2 import { Argument, Command, Flag } from 'effect/cli';
3 import { Data, Effect, Result, Option, Runtime } from 'effect';
4 import type {
@@ -432,5 +432,5 @@ export const proxyCmd = Command.make('proxy', {
432 }
433 })
434 ),
435 - requireLogin
435 + withCommandMeta({ requiresLogin: true })
436 );
ts/packages/cli/src/commands/registration.ts
+29 -11
@@ -21,15 +21,16 @@ import {
21 import type { ComposioUserContext } from 'src/services/user-context';
22
23 /**
24 - * Records the running registration as the command this invocation runs, then enforces what its
25 - * `CommandMeta` requires: a login fails after the identity is recorded, so `NotLoggedInError`
26 - * is reported against the command the user ran.
24 + * Records the running registration as the command this invocation runs, with the input
25 + * `effect/cli` parsed for it (none for a group that only shows its help, so, like `--help`, it
26 + * runs no invocation hook), then enforces what its `CommandMeta` requires: a login fails after
27 + * the identity is recorded, so `NotLoggedInError` is reported against the command the user ran.
28 */
28 -const beginSelected = (input: unknown) =>
29 +const beginSelected = (input: Option.Option<unknown>) =>
30 Effect.gen(function* () {
31 const identity = yield* CommandRegistration;
32 const invocation = yield* CommandInvocation;
32 - yield* invocation.begin(identity, Option.some(input));
33 + yield* invocation.begin(identity, input);
34 if (identity.meta.requiresLogin) {
35 yield* assertLoggedIn;
36 }
@@ -49,7 +50,7 @@ const registerSubcommand = <C extends Command.Command.Any>(child: C): Registered
50 const command = child as unknown as Command.Command<string, unknown, unknown, unknown, unknown>;
51 const begun =
52 command.subcommands.length === 0
52 - ? Command.provideEffectDiscard(command, beginSelected)
53 + ? Command.provideEffectDiscard(command, (input: unknown) => beginSelected(Option.some(input)))
54 : command;
55 return Command.provideEffect(
56 begun,
@@ -63,19 +64,36 @@ const registerSubcommand = <C extends Command.Command.Any>(child: C): Registered
64 ) as unknown as Registered<C>;
65 };
66
67 +/** What a group declares about its own handler, the one that runs when no subcommand is selected. */
68 +export interface GroupOptions {
69 + /**
70 + * Whether that handler is an action of its own (`composio dev --mode on`, `composio setup`)
71 + * rather than the group's help. Off by default: a group made without a handler shows the help
72 + * `effect/cli` prints for it, and the root shows its overview. Only an action runs the
73 + * invocation hooks; help, like `--help`, runs none. `effect/cli` does not expose whether a
74 + * command has a handler, so the group says so here.
75 + */
76 + readonly ownAction?: boolean;
77 +}
78 +
79 /**
80 * `Command.withSubcommands` for the command tree: registers each subcommand under `self` with
68 - * its own identity, and begins `self`'s own handler (a group's default action, or the help
69 - * `effect/cli` shows for a bare group) when no subcommand is selected. Every group in the tree
70 - * registers its subcommands with it.
81 + * its own identity, and begins `self`'s own handler when no subcommand is selected: as the
82 + * selected command with its input when it is an action (`GroupOptions.ownAction`), else as the
83 + * group's help. Every group in the tree registers its subcommands with it.
84 */
85 export const withRegisteredSubcommands =
73 - <const Subcommands extends ReadonlyArray<Command.Command.Any>>(subcommands: Subcommands) =>
86 + <const Subcommands extends ReadonlyArray<Command.Command.Any>>(
87 + subcommands: Subcommands,
88 + options: GroupOptions = {}
89 + ) =>
90 <const Name extends string, Input, ContextInput, E, R>(
91 self: Command.Command<Name, Input, ContextInput, E, R>
92 ) =>
93 Command.withSubcommands(
78 - Command.provideEffectDiscard(self, beginSelected),
94 + Command.provideEffectDiscard(self, (input: Input) =>
95 + beginSelected(options.ownAction === true ? Option.some(input) : Option.none())
96 + ),
97 subcommands.map(child =>
98 registerSubcommand<Subcommands[number]>(child)
99 ) satisfies ReadonlyArray<Registered<Subcommands[number]>>
ts/packages/cli/src/commands/setup.cmd.ts
+1 -1
@@ -352,5 +352,5 @@ export const setupCmd = setupBaseCmd.pipe(
352 command: 'composio setup --target all',
353 },
354 ]),
355 - withRegisteredSubcommands([setupSkillCmd])
355 + withRegisteredSubcommands([setupSkillCmd], { ownAction: true })
356 );
ts/packages/cli/src/commands/toolkits/toolkits.cmd.ts
+2 -2
@@ -1,4 +1,4 @@
1 -import { requireLogin } from 'src/effects/require-auth';
1 +import { withCommandMeta } from 'src/invocation/command-identity';
2 import { Command } from 'effect/cli';
3 import { rejectsSharedFlags } from 'src/commands/surface';
4 import { toolkitsCmd$List } from './list/toolkits.list.cmd';
@@ -23,5 +23,5 @@ export const toolkitsCmd = Command.make('toolkits').pipe(
23 toolkitsCmd$Search.pipe(rejectsSharedFlags('dev toolkits search')),
24 toolkitsCmd$Version.pipe(rejectsSharedFlags('dev toolkits version')),
25 ]),
26 - requireLogin
26 + withCommandMeta({ requiresLogin: true })
27 );
ts/packages/cli/src/commands/tools/commands/tools.execute.cmd.ts
+3 -3
@@ -1,4 +1,4 @@
1 -import { requireLogin } from 'src/effects/require-auth';
1 +import { withCommandMeta } from 'src/invocation/command-identity';
2 import { actingUser, CommandSurface } from 'src/commands/surface';
3 import { commandInputError } from 'src/commands/errors';
4 import { ExpectedFailure } from 'src/effects/expected-failure';
@@ -2016,7 +2016,7 @@ export const rootToolsCmd$Execute = Command.make(
2016 'Execute a tool by slug. Validates inputs against cached schemas and checks connections'
2017 ),
2018 Command.withExamples(executeExamples),
2019 - requireLogin
2019 + withCommandMeta({ requiresLogin: true })
2020 );
2021
2022 export const devToolsCmd$Execute = Command.make(
@@ -2091,5 +2091,5 @@ export const devToolsCmd$Execute = Command.make(
2091 command: example.command.replace('composio execute', 'composio dev playground-execute'),
2092 }))
2093 ),
2094 - requireLogin
2094 + withCommandMeta({ requiresLogin: true })
2095 );
ts/packages/cli/src/commands/tools/search/tools.search.cmd.ts
+2 -2
@@ -1,5 +1,5 @@
1 import { Argument, Command, Flag } from 'effect/cli';
2 -import { requireLogin } from 'src/effects/require-auth';
2 +import { withCommandMeta } from 'src/invocation/command-identity';
3 import { runToolsSearch } from './tools.search.handler';
4
5 const query = Argument.String('query').pipe(
@@ -69,5 +69,5 @@ export const toolsCmd$Search = Command.make(
69 description: 'Narrow results to a specific toolkit',
70 },
71 ]),
72 - requireLogin
72 + withCommandMeta({ requiresLogin: true })
73 );
ts/packages/cli/src/commands/tools/tools.cmd.ts
+2 -2
@@ -1,4 +1,4 @@
1 -import { requireLogin } from 'src/effects/require-auth';
1 +import { withCommandMeta } from 'src/invocation/command-identity';
2 import { Command } from 'effect/cli';
3 import { toolsCmd$List } from './list/tools.list.cmd';
4 import { toolsCmd$Info } from './info/tools.info.cmd';
@@ -15,5 +15,5 @@ export const rootToolsCmd = Command.make('tools').pipe(
15 },
16 ]),
17 withRegisteredSubcommands([toolsCmd$List, toolsCmd$Info]),
18 - requireLogin
18 + withCommandMeta({ requiresLogin: true })
19 );
ts/packages/cli/src/commands/triggers/commands/triggers.listen.cmd.ts
+2 -2
@@ -1,4 +1,4 @@
1 -import { requireLogin } from 'src/effects/require-auth';
1 +import { withCommandMeta } from 'src/invocation/command-identity';
2 import { reportFailure } from 'src/effects/report-failure';
3 import { eventCount, finishAcceptedEvents, makeSinkFailures } from '../sink-failures';
4 import { Command, Flag } from 'effect/cli';
@@ -404,5 +404,5 @@ export const triggersCmd$Listen = Command.make(
404 Command.withDescription(
405 'Listen to realtime trigger events for your developer project and optionally forward them into your local dev environment.'
406 ),
407 - requireLogin
407 + withCommandMeta({ requiresLogin: true })
408 );
ts/packages/cli/src/commands/triggers/root-triggers.cmd.ts
+2 -2
@@ -1,4 +1,4 @@
1 -import { requireLogin } from 'src/effects/require-auth';
1 +import { withCommandMeta } from 'src/invocation/command-identity';
2 import { Command } from 'effect/cli';
3 import { triggersCmd$Info } from './info/triggers.info.cmd';
4 import { triggersCmd$List } from './list/triggers.list.cmd';
@@ -7,5 +7,5 @@ import { withRegisteredSubcommands } from 'src/commands/registration';
7 export const rootTriggersCmd = Command.make('triggers').pipe(
8 Command.withDescription('Browse and inspect trigger types before creating subscriptions.'),
9 withRegisteredSubcommands([triggersCmd$List, triggersCmd$Info]),
10 - requireLogin
10 + withCommandMeta({ requiresLogin: true })
11 );
ts/packages/cli/src/commands/triggers/triggers.cmd.ts
+2 -2
@@ -1,4 +1,4 @@
1 -import { requireLogin } from 'src/effects/require-auth';
1 +import { withCommandMeta } from 'src/invocation/command-identity';
2 import { Command } from 'effect/cli';
3 import { rejectsSharedFlags } from 'src/commands/surface';
4 import { triggersCmd$Info } from './info/triggers.info.cmd';
@@ -29,5 +29,5 @@ export const triggersCmd = Command.make('triggers').pipe(
29 triggersCmd$Enable.pipe(rejectsSharedFlags('dev triggers enable')),
30 triggersCmd$Disable.pipe(rejectsSharedFlags('dev triggers disable')),
31 ]),
32 - requireLogin
32 + withCommandMeta({ requiresLogin: true })
33 );
ts/packages/cli/src/effects/require-auth.ts
+5 -11
@@ -1,21 +1,15 @@
1 import { Effect } from 'effect';
2 import { notLoggedIn } from 'src/commands/errors';
3 -import { withCommandMeta } from 'src/invocation/command-identity';
3 import { ComposioUserContext } from 'src/services/user-context';
4
6 -/** Fails with `NotLoggedInError` when `~/.composio` holds no API key. */
5 +/**
6 + * Fails with `NotLoggedInError` when `~/.composio` holds no API key. A command never calls it
7 + * itself: it declares `withCommandMeta({ requiresLogin: true })`, and the registration that runs
8 + * it checks the login right after the command began (`src/commands/registration.ts`).
9 + */
10 export const assertLoggedIn = Effect.gen(function* () {
11 const ctx = yield* ComposioUserContext;
12 if (!ctx.isLoggedIn()) {
13 return yield* notLoggedIn();
14 }
15 });
13 -
14 -/**
15 - * Makes a command, or a group entry and every subcommand under it, require a logged-in user.
16 - * It declares `requiresLogin` in the command's `CommandMeta`; the registration that runs the
17 - * command checks the login right after recording the command's identity
18 - * (`src/commands/registration.ts`), so `NotLoggedInError` names the command the user ran. The
19 - * handler then never checks `apiKey` or prints a login hint.
20 - */
21 -export const requireLogin = withCommandMeta({ requiresLogin: true });
ts/packages/cli/src/invocation/command-identity.ts
+72 -10
@@ -9,14 +9,35 @@
9 * `--version`, and parse failures have no selected handler; they resolve the identity from the
10 * command path `effect/cli` hands them (`identityAt`).
11 */
12 -import { Array as Arr, Context, Effect, Option } from 'effect';
12 +import { Array as Arr, Context, Effect, Option, Predicate, Record as EffectRecord } from 'effect';
13 import { Command } from 'effect/cli';
14 import type { TelemetryFamily } from 'src/analytics/types';
15
16 +/**
17 + * The hooks the invocation runs for the selected command (`src/invocation/invocation.ts`), in
18 + * this order, when the command begins: before its invoked event and its login check.
19 + */
20 +export const INVOCATION_HOOKS = [
21 + 'backendMismatch',
22 + 'updateNotice',
23 + 'pluginHint',
24 + 'backgroundUpdateCheck',
25 +] as const;
26 +
27 +export type InvocationHookName = (typeof INVOCATION_HOOKS)[number];
28 +
29 +/**
30 + * Whether a hook runs for a command: always (`true`), never (`false`), or as the input
31 + * `effect/cli` parsed for the command decides (`composio version --check`). Subcommands inherit
32 + * a boolean; a predicate applies only to the registration that declares it, since a
33 + * subcommand's input has another shape, and its subcommands run the hook.
34 + */
35 +export type HookPolicy = boolean | ((input: unknown) => boolean);
36 +
37 /**
38 * What a command declares about itself, under one annotation key (`Command.annotate`, or
18 - * `withCommandMeta` in `src/commands/registration.ts`). Every field is optional; what an
19 - * absent field means is set once, in `resolveCommandMeta`.
39 + * `withCommandMeta`). Every field is optional; what an absent field means is set once, in
40 + * `resolveCommandMeta`.
41 */
42 export interface CommandMetaShape {
43 /**
@@ -25,10 +46,17 @@ export interface CommandMetaShape {
46 */
47 readonly telemetryFamily?: TelemetryFamily;
48 /**
28 - * Whether the command needs a logged-in user (`requireLogin`). Inherited: a group's
29 - * subcommands need one too.
49 + * Whether the command needs a logged-in user. Inherited: a group's subcommands need one too.
50 + * The selected command checks it right after it began (`src/commands/registration.ts`), so
51 + * `NotLoggedInError` names the command the user ran.
52 */
53 readonly requiresLogin?: boolean;
54 + /**
55 + * Which invocation hooks run for the command. Every hook runs unless the command, or a group
56 + * above it, says otherwise; a boolean policy is inherited per hook, a predicate is not (see
57 + * `HookPolicy`).
58 + */
59 + readonly hooks?: Partial<Readonly<Record<InvocationHookName, HookPolicy>>>;
60 }
61
62 export const CommandMeta = Context.Reference<CommandMetaShape>('commands/CommandMeta', {
@@ -39,8 +67,20 @@ export const CommandMeta = Context.Reference<CommandMetaShape>('commands/Command
67 export interface ResolvedCommandMeta {
68 readonly telemetryFamily: TelemetryFamily;
69 readonly requiresLogin: boolean;
70 + readonly hooks: Readonly<Record<InvocationHookName, HookPolicy>>;
71 }
72
73 +const EVERY_HOOK: ResolvedCommandMeta['hooks'] = {
74 + backendMismatch: true,
75 + updateNotice: true,
76 + pluginHint: true,
77 + backgroundUpdateCheck: true,
78 +};
79 +
80 +/** The hook policies a subcommand inherits from `hooks`: the booleans; a predicate runs the hook. */
81 +const inheritedHooks = (hooks: ResolvedCommandMeta['hooks']): ResolvedCommandMeta['hooks'] =>
82 + EffectRecord.map(hooks, policy => (Predicate.isBoolean(policy) ? policy : true));
83 +
84 /** Resolves what a command declares (`own`) under a parent registration's resolved meta. */
85 export const resolveCommandMeta = (
86 parent: ResolvedCommandMeta | undefined,
@@ -48,19 +88,40 @@ export const resolveCommandMeta = (
88 ): ResolvedCommandMeta => ({
89 telemetryFamily: own.telemetryFamily ?? 'command',
90 requiresLogin: own.requiresLogin ?? parent?.requiresLogin ?? false,
91 + hooks: { ...(parent === undefined ? EVERY_HOOK : inheritedHooks(parent.hooks)), ...own.hooks },
92 });
93
94 +/** Whether `hook` runs for a command with `meta`, given the input `effect/cli` parsed for it. */
95 +export const runsHook = (
96 + meta: ResolvedCommandMeta,
97 + hook: InvocationHookName,
98 + input: unknown
99 +): boolean => {
100 + const policy = meta.hooks[hook];
101 + return Predicate.isBoolean(policy) ? policy : policy(input);
102 +};
103 +
104 /** The meta `command` declares on itself. */
105 export const commandMetaOf = (command: Command.Command.Any): CommandMetaShape =>
106 Context.get(command.annotations, CommandMeta);
107
57 -/** Adds `meta` to what `self` already declares in its `CommandMeta` annotation. */
108 +/**
109 + * Adds `meta` to what `self` already declares in its `CommandMeta` annotation; a hook policy
110 + * replaces only that hook's. `withCommandMeta({ requiresLogin: true })` makes a command, or a
111 + * group entry and every subcommand under it, require a logged-in user.
112 + */
113 export const withCommandMeta =
114 (meta: CommandMetaShape) =>
115 <const Name extends string, Input, ContextInput, E, R>(
116 self: Command.Command<Name, Input, ContextInput, E, R>
62 - ): Command.Command<Name, Input, ContextInput, E, R> =>
63 - Command.annotate(self, CommandMeta, { ...commandMetaOf(self), ...meta });
117 + ): Command.Command<Name, Input, ContextInput, E, R> => {
118 + const current = commandMetaOf(self);
119 + return Command.annotate(self, CommandMeta, {
120 + ...current,
121 + ...meta,
122 + hooks: { ...current.hooks, ...meta.hooks },
123 + });
124 + };
125
126 /** One command registration: where a command sits in the tree and what applies to it there. */
127 export interface CommandIdentity {
@@ -135,8 +196,9 @@ export const CommandRegistration = Context.Reference<CommandIdentity>(
196 export interface CommandInvocationShape {
197 /**
198 * Records `identity` as the command this invocation runs, with the input `effect/cli` parsed
138 - * for it (none for help, version, and parse failures), and reports that it started. Only the
139 - * first call counts. Never fails.
199 + * for it (none for help, version, parse failures, and a group that only shows its help), and
200 + * reports that it started; with parsed input, first runs the invocation hooks its
201 + * `CommandMeta` keeps. Only the first call counts. Never fails.
202 */
203 readonly begin: (identity: CommandIdentity, input: Option.Option<unknown>) => Effect.Effect<void>;
204 /**
ts/packages/cli/src/invocation/invocation.ts
+42 -22
@@ -1,7 +1,7 @@
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
2 + * One CLI invocation, from argv to a finished command: the command's lifecycle telemetry,
3 + * `effect/cli`'s parser and the selected command, the hooks the selected command runs, and the one
4 + * place 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
@@ -29,19 +29,22 @@ import {
29 type CommandIdentity,
30 CommandInvocation,
31 type CommandInvocationShape,
32 + INVOCATION_HOOKS,
33 + type InvocationHookName,
34 ROOT_IDENTITY,
35 + runsHook,
36 } from 'src/invocation/command-identity';
37 import { BackendMismatchWarning } from 'src/services/backend-mismatch-warning';
38 import { CommandLifecycleTelemetry } from 'src/services/command-lifecycle-telemetry';
39 import type { ComposioToolkitsRepository } from 'src/services/composio-clients';
40 import { mapOnlyComposioOverrideError } from 'src/services/composio-error-overrides';
38 -import type { HookInvocation } from 'src/services/invocation-hook';
41 +import type { InvocationHookShape } from 'src/services/invocation-hook';
42 import { PluginHint } from 'src/services/plugin-hint';
43 import { cliInvocationContext } from 'src/services/runtime-cli-context';
44 import type { ShutdownSignal } from 'src/services/shutdown-signal';
45 import { TerminalUI } from 'src/services/terminal-ui';
46 import type { ToolkitSlugCatalog } from 'src/services/toolkit-slug-catalog';
44 -import { UpdateNotice } from 'src/services/update-check';
47 +import { BackgroundUpdateCheck, UpdateNotice } from 'src/services/update-check';
48 import { extractMessage } from 'src/utils/api-error-extraction';
49 import type { InvocationLive } from './live';
50
@@ -65,9 +68,10 @@ const runWithArgs = (argv: ReadonlyArray<string>) =>
68 * Runs the command `effect/cli` selects for `argv` under its lifecycle telemetry. The command's
69 * identity is known only once the parser selected it: the selected registration calls
70 * `CommandInvocation.begin` (`src/commands/registration.ts`), and so do `--help`, `--version`,
68 - * and a parse failure, for the command path `effect/cli` gives them. `begin` reports the invoked
69 - * event; the outcome is reported for the same command. A failure before any `begin` (a group-level
70 - * check) is reported against the deepest registration whose dispatch started.
71 + * and a parse failure, for the command path `effect/cli` gives them. `begin` runs the selected
72 + * command's invocation hooks, then reports the invoked event; the outcome is reported for the
73 + * same command. A failure before any `begin` (a group-level check) is reported against the
74 + * deepest registration whose dispatch started.
75 */
76 const runWithTelemetry = (argv: ReadonlyArray<string>) =>
77 Effect.gen(function* () {
@@ -100,6 +104,7 @@ const runWithTelemetry = (argv: ReadonlyArray<string>) =>
104 return { ...context, toolkitSlug };
105 });
106
107 + const runHooks = yield* invocationHooks;
108 const started = yield* Ref.make(Option.none<CliCommandTelemetryContext>());
109 const entered = yield* Ref.make(ROOT_IDENTITY);
110 const start = (identity: CommandIdentity, input: Option.Option<unknown>) =>
@@ -109,11 +114,18 @@ const runWithTelemetry = (argv: ReadonlyArray<string>) =>
114 );
115 const invocation: CommandInvocationShape = {
116 // Only the first command to begin counts: the bare group whose help ended in `ShowHelp`.
117 + // A selected command (one with parsed input) runs its hooks first, so the backend mismatch
118 + // warning precedes the toolkit lookup an `execute` invoked event makes; help (`--help`, a
119 + // bare group), version, and parse failures run none.
120 begin: (identity, input) =>
121 Effect.flatMap(Ref.get(started), current =>
122 Option.match(current, {
123 onSome: () => Effect.void,
116 - onNone: () => Effect.asVoid(start(identity, input)),
124 + onNone: () =>
125 + Option.match(input, {
126 + onNone: () => Effect.void,
127 + onSome: parsed => runHooks(identity, parsed),
128 + }).pipe(Effect.andThen(start(identity, input))),
129 })
130 ),
131 enter: identity => Ref.set(entered, identity),
@@ -144,16 +156,25 @@ const runWithTelemetry = (argv: ReadonlyArray<string>) =>
156 );
157 });
158
147 -/** Runs the hooks every invocation gets before its command, in order, on stderr. */
148 -const runInvocationHooks = (invocation: HookInvocation) =>
149 - Effect.gen(function* () {
150 - const backendMismatchWarning = yield* BackendMismatchWarning;
151 - const updateNotice = yield* UpdateNotice;
152 - const pluginHint = yield* PluginHint;
153 - yield* backendMismatchWarning.run(invocation);
154 - yield* updateNotice.run(invocation);
155 - yield* pluginHint.run(invocation);
156 - });
159 +/**
160 + * Runs, in order and on stderr, the invocation hooks the selected command's `CommandMeta` keeps,
161 + * for the input `effect/cli` parsed for it. A group that only shows its help (the bare root
162 + * included) begins with no input, like `--help`, so it never gets here.
163 + */
164 +const invocationHooks = Effect.gen(function* () {
165 + const hooks: Readonly<Record<InvocationHookName, InvocationHookShape>> = {
166 + backendMismatch: yield* BackendMismatchWarning,
167 + updateNotice: yield* UpdateNotice,
168 + pluginHint: yield* PluginHint,
169 + backgroundUpdateCheck: yield* BackgroundUpdateCheck,
170 + };
171 + return (identity: CommandIdentity, input: unknown): Effect.Effect<void> =>
172 + Effect.forEach(
173 + INVOCATION_HOOKS.filter(hook => runsHook(identity.meta, hook, input)),
174 + hook => hooks[hook].run({ identity }),
175 + { discard: true }
176 + );
177 +});
178
179 /**
180 * Whether `reason` has nothing for this module to print: a failure already on screen, or an
@@ -214,15 +235,14 @@ export const reportInvocationFailure = (cause: Cause.Cause<unknown>) =>
235
236 /**
237 * Runs one invocation of the CLI for the full process `argv` (executable and script included):
217 - * the invocation hooks (before parsing), then the command under lifecycle telemetry.
238 + * the command under lifecycle telemetry, with the invocation hooks when it begins.
239 *
240 * Fails with the command's own cause once it is on screen; an interruption alone is not printed.
241 */
242 export const runInvocation = (
243 argv: ReadonlyArray<string>
244 ): Effect.Effect<void, unknown, InvocationServices> =>
224 - runInvocationHooks({ argv }).pipe(
225 - Effect.andThen(runWithTelemetry(argv)),
245 + runWithTelemetry(argv).pipe(
246 Effect.withSpan('composio-cli', {
247 attributes: {
248 name: constants.APP_NAME,
ts/packages/cli/src/invocation/live.ts
+14 -7
@@ -33,7 +33,7 @@ import { ProjectEnvironmentDetector } from 'src/services/project-environment-det
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';
36 +import { BackgroundUpdateCheck, 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';
@@ -123,6 +123,11 @@ export const BackendMismatchWarningLive = Layer.provide(
123 Layer.mergeAll(ComposioUserContextLive, TerminalUILive)
124 ) satisfies RequiredLayer;
125
126 +export const CommandLifecycleTelemetryLive = Layer.provide(
127 + CommandLifecycleTelemetry.Default,
128 + Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOs.Default, TerminalUILive)
129 +) satisfies RequiredLayer;
130 +
131 // `Path.layer`, not `BunPath.layer`: the update notice and the plugin hint have always resolved
132 // their state files with Effect's own path implementation.
133 export const UpdateNoticeLive = Layer.provide(
@@ -132,12 +137,13 @@ export const UpdateNoticeLive = Layer.provide(
137
138 export const PluginHintLive = Layer.provide(
139 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)
140 + Layer.mergeAll(
141 + TerminalUILive,
142 + CommandLifecycleTelemetryLive,
143 + BunFileSystem.layer,
144 + Path.layer,
145 + NodeOs.Default
146 + )
147 ) satisfies RequiredLayer;
148
149 export const InvocationLive = Layer.mergeAll(
@@ -167,6 +173,7 @@ export const InvocationLive = Layer.mergeAll(
173 TerminalUILive,
174 BackendMismatchWarningLive,
175 UpdateNoticeLive,
176 + BackgroundUpdateCheck.Default,
177 PluginHintLive,
178 CommandLifecycleTelemetryLive,
179 Layer.merge(
ts/packages/cli/src/services/command-lifecycle-telemetry.ts
+19 -3
@@ -4,17 +4,29 @@ import { Cause, Context, Effect, Layer } from 'effect';
4 import { trackCliEventEffect } from 'src/analytics/dispatch';
5 import { captureServices } from 'src/effects/capture-services';
6 import {
7 + getPluginHintShownEvent,
8 getPrimaryLifecycleFailedEvent,
9 getPrimaryLifecycleInvokedEvent,
10 getPrimaryLifecycleSucceededEvent,
11 } from 'src/analytics/events';
12 import type { CliCommandTelemetryContext, TrackEvent } from 'src/analytics/types';
13 +import { APP_VERSION } from 'src/constants';
14 +import type { AgentHost } from './agent-host';
15 import { NodeOs } from './node-os';
16 import { TerminalUI } from './terminal-ui';
17
18 +/** The plugin hint (`src/services/plugin-hint.ts`) was printed for a command. */
19 +export interface PluginHintShown {
20 + readonly invocationOrigin: string;
21 + /** The command the hint was printed for, as `commandPathOf` gives it. */
22 + readonly commandPath: string;
23 + readonly agentHost: AgentHost;
24 +}
25 +
26 /**
16 - * Where an invocation reports its command's lifecycle: once when the command starts, then once
17 - * when it succeeds or fails. Every method is best-effort and never fails.
27 + * Where an invocation reports its command's lifecycle, once when the command starts and once
28 + * when it succeeds or fails, and what its invocation hooks showed. Every method is best-effort
29 + * and never fails.
30 */
31 export interface CommandLifecycleTelemetryShape {
32 readonly invoked: (context: CliCommandTelemetryContext) => Effect.Effect<void>;
@@ -23,11 +35,13 @@ export interface CommandLifecycleTelemetryShape {
35 context: CliCommandTelemetryContext,
36 cause: Cause.Cause<unknown>
37 ) => Effect.Effect<void>;
38 + /** Tracks `CLI_PLUGIN_HINT_SHOWN`. */
39 + readonly pluginHintShown: (shown: PluginHintShown) => Effect.Effect<void>;
40 }
41
42 /**
43 * Tracks the command's primary lifecycle events (its family's events, or the generic
30 - * `CLI_COMMAND_*` ones) through the analytics dispatcher.
44 + * `CLI_COMMAND_*` ones) and the plugin hint's event through the analytics dispatcher.
45 */
46 export class CommandLifecycleTelemetry extends Context.Service<
47 CommandLifecycleTelemetry,
@@ -48,6 +62,8 @@ export class CommandLifecycleTelemetry extends Context.Service<
62 succeeded: context => track(getPrimaryLifecycleSucceededEvent(context)),
63 failed: (context, cause) =>
64 track(getPrimaryLifecycleFailedEvent(context, Cause.squash(cause))),
65 + pluginHintShown: shown =>
66 + track(getPluginHintShownEvent({ ...shown, cliVersion: APP_VERSION })),
67 });
68 })
69 );
ts/packages/cli/src/services/invocation-hook.ts
+9 -10
@@ -1,20 +1,19 @@
1 import type { Effect } from 'effect';
2 +import type { CommandIdentity } from 'src/invocation/command-identity';
3
4 /**
4 - * What a hook knows about the invocation it runs for.
5 - *
6 - * Hooks run before the root command is parsed, so today this is only the process argv. Anything
7 - * a hook later learns about the selected command belongs here, not in a hook's own argv parsing.
5 + * What a hook knows about the invocation it runs for: the command `effect/cli` selected. A hook
6 + * never reads argv; anything it needs to know about the command belongs in its `CommandMeta`.
7 */
8 export interface HookInvocation {
10 - /** The full, unchanged process argv (executable and script included). */
11 - readonly argv: ReadonlyArray<string>;
9 + readonly identity: CommandIdentity;
10 }
11
12 /**
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.
13 + * A hook the invocation (`src/invocation/invocation.ts`) runs once for the selected command,
14 + * when the command begins and before any request it makes, unless the command's `CommandMeta`
15 + * turns it off. Its output goes to stderr; it never fails the command.
16 */
18 -export interface InvocationHookShape<E = never> {
19 - readonly run: (invocation: HookInvocation) => Effect.Effect<void, E>;
17 +export interface InvocationHookShape {
18 + readonly run: (invocation: HookInvocation) => Effect.Effect<void>;
19 }
ts/packages/cli/src/services/plugin-hint.ts
+36 -47
@@ -1,14 +1,16 @@
1 import * as FileSystem from 'effect/FileSystem';
2 import * as Path from 'effect/Path';
3 -import { type Config, Context, Effect, Exit, Layer, Option, Schema } from 'effect';
4 -import { trackCliEventEffect } from 'src/analytics/dispatch';
5 -import { getPluginHintShownEvent } from 'src/analytics/events';
3 +import { Context, Effect, Exit, Layer, Option, Schema } from 'effect';
4 import { APP_CONFIG } from 'src/config';
5 import { captureServices } from 'src/effects/capture-services';
6 import { setupCacheDir } from 'src/effects/setup-cache-dir';
9 -import { APP_VERSION } from 'src/constants';
7 +import { commandPathOf } from 'src/invocation/command-identity';
8 import { AGENT_HOST_LABELS, COMPOSIO_AGENT_PLUGIN_ID, type AgentHost } from './agent-host';
9 import { detectPluginHost, hostConfigDirectory, rawHostEnvironment } from './agent-host-env';
10 +import {
11 + CommandLifecycleTelemetry,
12 + type CommandLifecycleTelemetryShape,
13 +} from './command-lifecycle-telemetry';
14 import { NodeOs } from './node-os';
15 import type { InvocationHookShape } from './invocation-hook';
16 import { DEFAULT_CLI_INVOCATION_ORIGIN } from './runtime-cli-context';
@@ -18,7 +20,8 @@ import { TerminalUI } from './terminal-ui';
20 * One-line acquisition hint for the Composio agent plugin.
21 *
22 * The primary audience is the agent driving the CLI through a non-TTY shell,
21 - * so this line is intentionally not gated on stderr being a TTY.
23 + * so this line is intentionally not gated on stderr being a TTY. `composio setup`, which
24 + * installs the plugin, turns it off in its `CommandMeta`.
25 */
26
27 const HINT_INTERVAL_MS = 24 * 60 * 60 * 1000;
@@ -33,7 +36,8 @@ export interface PluginHintConfig {
36 readonly stateDirectory: string;
37 readonly host: AgentHost | undefined;
38 readonly invocationOrigin: string | undefined;
36 - readonly commandName: string | undefined;
39 + /** The command the hint is shown for, as telemetry records it (`commandPathOf`). */
40 + readonly commandPath: string;
41 readonly claudeInstalledPluginsFile: string;
42 readonly codexConfigFile: string;
43 readonly hintIntervalMs: number;
@@ -106,14 +110,13 @@ export function createPluginHint(config: PluginHintConfig) {
110 codex: codexPluginAbsent,
111 };
112
109 - function showPluginHint(terminal: Pick<TerminalUI, 'error'>) {
113 + function showPluginHint(
114 + terminal: Pick<TerminalUI, 'error'>,
115 + telemetry: Pick<CommandLifecycleTelemetryShape, 'pluginHintShown'>
116 + ) {
117 return Effect.gen(function* () {
118 const host = config.host;
112 - if (
113 - host === undefined ||
114 - config.invocationOrigin === 'run' ||
115 - config.commandName === 'setup'
116 - ) {
119 + if (host === undefined || config.invocationOrigin === 'run') {
120 return;
121 }
122 if (!(yield* pluginAbsentByHost[host])) return;
@@ -121,7 +124,7 @@ export function createPluginHint(config: PluginHintConfig) {
124 // The stamp must not outlive a failed delivery: if printing the hint
125 // does not succeed, release the claim so the next invocation can
126 // retry instead of staying muted for the full interval. Tracking
124 - // below is best-effort by contract (trackCliEventEffect never
127 + // below is best-effort by contract (the telemetry sink never
128 // fails), so a delivered hint with a lost event is accepted.
129 const printed = yield* Effect.exit(
130 terminal.error(
@@ -132,37 +135,18 @@ export function createPluginHint(config: PluginHintConfig) {
135 yield* releaseHint(host);
136 return;
137 }
135 - yield* trackCliEventEffect(
136 - getPluginHintShownEvent({
137 - invocationOrigin: config.invocationOrigin ?? DEFAULT_CLI_INVOCATION_ORIGIN,
138 - cliVersion: APP_VERSION,
139 - commandPath: config.commandName ?? 'composio',
140 - agentHost: host,
141 - })
142 - );
138 + yield* telemetry.pluginHintShown({
139 + invocationOrigin: config.invocationOrigin ?? DEFAULT_CLI_INVOCATION_ORIGIN,
140 + commandPath: config.commandPath,
141 + agentHost: host,
142 + });
143 }).pipe(Effect.ignore);
144 }
145
146 return { showPluginHint };
147 }
148
149 -export function findRootCommandName(argv: ReadonlyArray<string>): string | undefined {
150 - const args = argv.slice(2);
151 - for (let index = 0; index < args.length; index += 1) {
152 - const token = args[index];
153 - if (token === '--log-level') {
154 - index += 1;
155 - continue;
156 - }
157 - if (token?.startsWith('--log-level=') || token?.startsWith('-')) {
158 - continue;
159 - }
160 - return token;
161 - }
162 - return undefined;
163 -}
164 -
165 -export const resolvePluginHintConfig = (argv: ReadonlyArray<string>) =>
149 +export const resolvePluginHintConfig = (commandPath: string) =>
150 Effect.gen(function* () {
151 const path = yield* Path.Path;
152 const cacheDir = yield* setupCacheDir;
@@ -174,18 +158,18 @@ export const resolvePluginHintConfig = (argv: ReadonlyArray<string>) =>
158 stateDirectory: path.join(cacheDir, 'plugin-hints'),
159 host: detectPluginHost(env),
160 invocationOrigin,
177 - commandName: findRootCommandName(argv),
161 + commandPath,
162 claudeInstalledPluginsFile: path.join(claudeConfigDir, 'plugins', 'installed_plugins.json'),
163 codexConfigFile: path.join(codexConfigDir, 'config.toml'),
164 hintIntervalMs: HINT_INTERVAL_MS,
165 } satisfies PluginHintConfig;
166 });
167
184 -export type PluginHintShape = InvocationHookShape<Config.ConfigError>;
168 +export type PluginHintShape = InvocationHookShape;
169
170 /**
187 - * Prints the plugin acquisition hint when eligible, and records that it was shown. Never fails
188 - * past reading its configuration, never blocks on network.
171 + * Prints the plugin acquisition hint when eligible, and reports that it was shown through
172 + * `CommandLifecycleTelemetry`. Never fails, never blocks on network.
173 */
174 export class PluginHint extends Context.Service<PluginHint, PluginHintShape>()(
175 'services/PluginHint'
@@ -193,18 +177,23 @@ export class PluginHint extends Context.Service<PluginHint, PluginHintShape>()(
177 static readonly Default: Layer.Layer<
178 PluginHint,
179 never,
196 - TerminalUI | FileSystem.FileSystem | Path.Path | NodeOs
180 + TerminalUI | CommandLifecycleTelemetry | FileSystem.FileSystem | Path.Path | NodeOs
181 > = Layer.effect(
182 PluginHint,
183 Effect.gen(function* () {
184 const terminal = yield* TerminalUI;
185 + const telemetry = yield* CommandLifecycleTelemetry;
186 const services = yield* captureServices(FileSystem.FileSystem, Path.Path, NodeOs, TerminalUI);
187 return PluginHint.of({
203 - run: ({ argv }) =>
188 + run: ({ identity }) =>
189 Effect.gen(function* () {
205 - const config = yield* resolvePluginHintConfig(argv);
206 - yield* createPluginHint(config).showPluginHint(terminal);
207 - }).pipe(Effect.provideContext(services)),
190 + const config = yield* resolvePluginHintConfig(commandPathOf(identity));
191 + yield* createPluginHint(config).showPluginHint(terminal, telemetry);
192 + }).pipe(
193 + Effect.provideContext(services),
194 + // The hint is advisory: a configuration it cannot read shows no hint.
195 + Effect.ignore
196 + ),
197 });
198 })
199 );
ts/packages/cli/src/services/update-check.ts
+40 -39
@@ -6,7 +6,6 @@ import semver from 'semver';
6 import { bold, cyanBright, dim } from 'src/ui/colors';
7 import { GITHUB_CONFIG } from 'src/config';
8 import { captureServices } from 'src/effects/capture-services';
9 -import { rootCommandIndex } from 'src/utils/cli-args';
9 import { APP_VERSION } from '../constants';
10 import type { InvocationHookShape } from './invocation-hook';
11 import { NodeOs, type NodeOsShape } from './node-os';
@@ -16,11 +15,11 @@ import { TerminalUI } from './terminal-ui';
15 /**
16 * Background update check for @composio/cli.
17 *
19 - * Two entry points, both called from the invocation BEFORE the root command's
20 - * Effect runtime boots — they must never block or throw:
18 + * Two invocation hooks, both run for the selected command before its handler — they must never
19 + * block or fail. A command opts out of either in its `CommandMeta` (`src/commands/index.ts`):
20 *
22 - * UpdateNotice — reads a tiny cached JSON file (~1 ms)
23 - * checkForUpdateInBackground() — fire-and-forget fetch, no await
21 + * UpdateNotice — reads a tiny cached JSON file (~1 ms)
22 + * BackgroundUpdateCheck — fire-and-forget fetch, no await
23 *
24 * Strategy:
25 * Uses GitHub's releases API and only considers stable @composio/cli releases
@@ -30,12 +29,6 @@ import { TerminalUI } from './terminal-ui';
29
30 const CHECK_INTERVAL_MS = 24 * 60 * 60 * 1000; // 24 hours
31
33 -/**
34 - * `composio upgrade` resolves the latest release live, so a cached hint printed before it runs
35 - * could only repeat that answer or contradict it with an older version.
36 - */
37 -const UPGRADE_COMMAND_NAME = 'upgrade';
38 -
32 /** Matches `@composio/cli@<semver>` — excludes prereleases. */
33 const CLI_RELEASE_TAG_RE = /^@composio\/cli@(\d+\.\d+\.\d+)$/;
34
@@ -205,15 +198,10 @@ export function createUpdateChecker(config: UpdateCheckConfig) {
198
199 /**
200 * If a cached newer version is known, print a one-line hint to stderr.
208 - * Reads a tiny JSON file and does a semver compare. Skipped for `composio upgrade`.
201 + * Reads a tiny JSON file and does a semver compare.
202 */
210 - function showUpdateNotice(
211 - terminal: Pick<TerminalUI, 'capabilities' | 'error'>,
212 - commandName?: string
213 - ) {
203 + function showUpdateNotice(terminal: Pick<TerminalUI, 'capabilities' | 'error'>) {
204 return Effect.gen(function* () {
215 - if (commandName === UPGRADE_COMMAND_NAME) return;
216 -
205 // `terminal.error` writes even when stderr is redirected, so gate this
206 // advisory notice explicitly while leaving stdout out of the decision.
207 const { canDecorate } = yield* terminal.capabilities;
@@ -353,8 +341,9 @@ const DefaultConfigLayers = Layer.mergeAll(Path.layer, NodeOs.Default, BunFileSy
341 export type UpdateNoticeShape = InvocationHookShape;
342
343 /**
356 - * Prints the upgrade hint to stderr if a newer version is cached, unless the invocation runs
357 - * `composio upgrade`. Reads the cache under the home directory `NodeOs` reports; never fetches.
344 + * Prints the upgrade hint to stderr if a newer version is cached. Reads the cache under the home
345 + * directory `NodeOs` reports; never fetches. `composio upgrade` turns it off: it resolves the
346 + * latest release live, so a cached hint could only repeat that answer or contradict it.
347 */
348 export class UpdateNotice extends Context.Service<UpdateNotice, UpdateNoticeShape>()(
349 'services/UpdateNotice'
@@ -369,21 +358,46 @@ export class UpdateNotice extends Context.Service<UpdateNotice, UpdateNoticeShap
358 const terminal = yield* TerminalUI;
359 const services = yield* captureServices(FileSystem.FileSystem, Path.Path, NodeOs);
360 return UpdateNotice.of({
372 - run: ({ argv }) =>
361 + run: () =>
362 Effect.gen(function* () {
363 const stateFile = yield* defaultStateFile;
364 const config = yield* defaultConfig(stateFile);
376 - const args = argv.slice(2);
377 - yield* createUpdateChecker(config).showUpdateNotice(
378 - terminal,
379 - args[rootCommandIndex(args)]
380 - );
365 + yield* createUpdateChecker(config).showUpdateNotice(terminal);
366 }).pipe(Effect.provideContext(services)),
367 });
368 })
369 );
370 }
371
372 +/**
373 + * Refreshes the release cache from GitHub if it is stale; `checkForUpdate` swallows its own
374 + * failures. `BackgroundUpdateCheck` forks it detached, so the command that started it neither
375 + * waits for it nor interrupts it when it ends. A successful run still ends when the event loop
376 + * drains (`src/run-main.ts`), so the request can finish; any other exit ends the process at once.
377 + */
378 +const refreshReleaseCache = Effect.gen(function* () {
379 + const stateFile = yield* defaultStateFile;
380 + const config = yield* defaultConfig(stateFile);
381 + yield* createUpdateChecker(config).checkForUpdate;
382 +}).pipe(Effect.provide(DefaultConfigLayers));
383 +
384 +export type BackgroundUpdateCheckShape = InvocationHookShape;
385 +
386 +/**
387 + * Starts refreshing the release cache in the background (at most once per check interval) and
388 + * returns at once. `composio upgrade` and `composio version --check` turn it off: they resolve
389 + * releases themselves.
390 + */
391 +export class BackgroundUpdateCheck extends Context.Service<
392 + BackgroundUpdateCheck,
393 + BackgroundUpdateCheckShape
394 +>()('services/BackgroundUpdateCheck') {
395 + static readonly Default: Layer.Layer<BackgroundUpdateCheck> = Layer.succeed(
396 + BackgroundUpdateCheck,
397 + BackgroundUpdateCheck.of({ run: () => Effect.asVoid(Effect.forkDetach(refreshReleaseCache)) })
398 + );
399 +}
400 +
401 /**
402 * Record a live-resolved latest stable release (e.g. `@composio/cli@0.5.0`) as the cached update
403 * check, so later hints agree with what `composio upgrade` just saw. Tags that are not a stable
@@ -410,16 +424,3 @@ export const getUpdateStatus: Effect.Effect<UpdateStatus> = Effect.gen(function*
424 const config = yield* defaultConfig(stateFile);
425 return yield* createUpdateChecker(config).getUpdateStatus;
426 }).pipe(Effect.provide(DefaultConfigLayers));
413 -
414 -/** Fire-and-forget background fetch to GitHub. */
415 -export function checkForUpdateInBackground(): void {
416 - // Uses a detached runtime so short-lived command handlers do not interrupt the refresh.
417 - // runPromiseExit never throws into the caller, and checkForUpdate swallows its own failures.
418 - void Effect.runPromiseExit(
419 - Effect.gen(function* () {
420 - const stateFile = yield* defaultStateFile;
421 - const config = yield* defaultConfig(stateFile);
422 - yield* createUpdateChecker(config).checkForUpdate;
423 - }).pipe(Effect.provide(DefaultConfigLayers))
424 - );
425 -}
ts/packages/cli/test/__utils__/command-identity.ts new
+11
@@ -0,0 +1,11 @@
1 +import {
2 + type CommandIdentity,
3 + type CommandMetaShape,
4 + resolveCommandMeta,
5 +} from 'src/invocation/command-identity';
6 +
7 +/** The identity of a root registration at `path` that declares `meta`. */
8 +export const commandIdentity = (
9 + path: ReadonlyArray<string>,
10 + meta: CommandMetaShape = {}
11 +): CommandIdentity => ({ path, meta: resolveCommandMeta(undefined, meta) });
ts/packages/cli/test/__utils__/layers/invocation-hooks.ts
+20 -3
@@ -1,15 +1,19 @@
1 import { type Cause, Context, Effect, Layer, Ref } from 'effect';
2 import type { CliCommandTelemetryContext } from 'src/analytics/types';
3 import { BackendMismatchWarning } from 'src/services/backend-mismatch-warning';
4 -import { CommandLifecycleTelemetry } from 'src/services/command-lifecycle-telemetry';
4 +import {
5 + CommandLifecycleTelemetry,
6 + type PluginHintShown,
7 +} from 'src/services/command-lifecycle-telemetry';
8 import type { HookInvocation } from 'src/services/invocation-hook';
9 import { PluginHint } from 'src/services/plugin-hint';
7 -import { UpdateNotice } from 'src/services/update-check';
10 +import { BackgroundUpdateCheck, UpdateNotice } from 'src/services/update-check';
11
12 /** One call to an invocation hook or to the lifecycle telemetry sink, in call order. */
13 export type RecordedInvocationCall =
14 | {
12 - readonly service: 'BackendMismatchWarning' | 'UpdateNotice' | 'PluginHint';
15 + readonly service:
16 + 'BackendMismatchWarning' | 'UpdateNotice' | 'PluginHint' | 'BackgroundUpdateCheck';
17 readonly invocation: HookInvocation;
18 }
19 | {
@@ -22,6 +26,11 @@ export type RecordedInvocationCall =
26 readonly event: 'failed';
27 readonly context: CliCommandTelemetryContext;
28 readonly cause: Cause.Cause<unknown>;
29 + }
30 + | {
31 + readonly service: 'CommandLifecycleTelemetry';
32 + readonly event: 'pluginHintShown';
33 + readonly shown: PluginHintShown;
34 };
35
36 /** Reads what the recording doubles of `InvocationHooksTest` were called with. */
@@ -76,6 +85,12 @@ export const InvocationHooksTest = Layer.unwrap(
85 PluginHint,
86 PluginHint.of({ run: invocation => record({ service: 'PluginHint', invocation }) })
87 ),
88 + Layer.succeed(
89 + BackgroundUpdateCheck,
90 + BackgroundUpdateCheck.of({
91 + run: invocation => record({ service: 'BackgroundUpdateCheck', invocation }),
92 + })
93 + ),
94 Layer.succeed(
95 CommandLifecycleTelemetry,
96 CommandLifecycleTelemetry.of({
@@ -85,6 +100,8 @@ export const InvocationHooksTest = Layer.unwrap(
100 record({ service: 'CommandLifecycleTelemetry', event: 'succeeded', context }),
101 failed: (context, cause) =>
102 record({ service: 'CommandLifecycleTelemetry', event: 'failed', context, cause }),
103 + pluginHintShown: shown =>
104 + record({ service: 'CommandLifecycleTelemetry', event: 'pluginHintShown', shown }),
105 })
106 )
107 );
ts/packages/cli/test/__utils__/telemetry-context.ts
+2 -1
@@ -1,6 +1,7 @@
1 import { Option } from 'effect';
2 import { createCliCommandTelemetryContext } from 'src/analytics/events';
3 import type { TelemetryFamily } from 'src/analytics/types';
4 +import { resolveCommandMeta } from 'src/invocation/command-identity';
5 import {
6 DEFAULT_CLI_INVOCATION_ORIGIN,
7 type CliInvocationContext,
@@ -32,7 +33,7 @@ export const commandTelemetryContext = (
33 },
34 identity: {
35 path: options.path,
35 - meta: { telemetryFamily: options.family ?? 'command', requiresLogin: false },
36 + meta: resolveCommandMeta(undefined, { telemetryFamily: options.family ?? 'command' }),
37 },
38 input: options.input === undefined ? Option.none() : Option.some(options.input),
39 startedAt: Date.now(),
ts/packages/cli/test/src/cli-main.test.ts
+11 -11
@@ -78,12 +78,15 @@ describe('CLI backend of a stored login', () => {
78
79 it('warns on stderr only when an env var sends the stored key to another backend', () => {
80 const configDirectory = storedLogin(STAGING_BASE_URL);
81 + const run = (args: ReadonlyArray<string>, env: Record<string, string> = {}) =>
82 + spawnSync('bun', ['run', 'src/bin.ts', ...args], {
83 + cwd: process.cwd(),
84 + encoding: 'utf8',
85 + env: cliEnv(configDirectory, env),
86 + });
87 + const mismatched = { COMPOSIO_BASE_URL: 'http://127.0.0.1:9' };
88
82 - const result = spawnSync('bun', ['run', 'src/bin.ts', '--version'], {
83 - cwd: process.cwd(),
84 - encoding: 'utf8',
85 - env: cliEnv(configDirectory, { COMPOSIO_BASE_URL: 'http://127.0.0.1:9' }),
86 - });
89 + const result = run(['version'], mismatched);
90
91 expect(result.status).toBe(0);
92 const warning =
@@ -91,12 +94,9 @@ describe('CLI backend of a stored login', () => {
94 expect(result.stderr.split(warning)).toHaveLength(2);
95 expect(result.stdout).not.toContain('COMPOSIO_BASE_URL');
96
94 - const unset = spawnSync('bun', ['run', 'src/bin.ts', '--version'], {
95 - cwd: process.cwd(),
96 - encoding: 'utf8',
97 - env: cliEnv(configDirectory),
98 - });
99 - expect(unset.stderr).not.toContain('sends your stored API key');
97 + expect(run(['version']).stderr).not.toContain('sends your stored API key');
98 + // `--version` runs no command, so no invocation hook.
99 + expect(run(['--version'], mismatched).stderr).not.toContain('sends your stored API key');
100 });
101
102 it('sends requests to the stored backend and explains a rejected key', async () => {
ts/packages/cli/test/src/commands/background-update-check.test.ts deleted
-69
@@ -1,69 +0,0 @@
1 -import { describe, expect, layer, vi } from '@effect/vitest';
2 -import { Effect } from 'effect';
3 -import { Command } from 'effect/cli';
4 -import { $defaultCmd } from 'src/commands/$default.cmd';
5 -import { withBackgroundUpdateCheck } from 'src/commands/background-update-check';
6 -import { upgradeCmd } from 'src/commands/upgrade/upgrade.cmd';
7 -import { versionCmd } from 'src/commands/version.cmd';
8 -import { TestLive } from 'test/__utils__';
9 -
10 -const makeRunner = (start: () => void) => {
11 - const version = versionCmd.pipe(Command.withHandler(() => Effect.void));
12 - const upgrade = upgradeCmd.pipe(Command.withHandler(() => Effect.void));
13 - const other = Command.make('other').pipe(Command.withHandler(() => Effect.void));
14 - const root = withBackgroundUpdateCheck($defaultCmd, [version, upgrade, other], start);
15 -
16 - return Command.runWith(root, { version: '0.0.0-test' });
17 -};
18 -
19 -describe('withBackgroundUpdateCheck', () => {
20 - layer(TestLive())(it => {
21 - it.effect('skips the background request for an explicit version check', () =>
22 - Effect.gen(function* () {
23 - const start = vi.fn();
24 -
25 - yield* makeRunner(start)(['version', '--check']);
26 -
27 - expect(start).not.toHaveBeenCalled();
28 - })
29 - );
30 -
31 - it.effect('uses parsed root options when identifying an explicit version check', () =>
32 - Effect.gen(function* () {
33 - const start = vi.fn();
34 - const run = makeRunner(start);
35 -
36 - yield* run(['--log-level', 'Debug', 'version', '--check']);
37 - yield* run(['--log-level=Debug', 'version', '--check']);
38 -
39 - expect(start).not.toHaveBeenCalled();
40 - })
41 - );
42 -
43 - it.effect(
44 - 'skips the background request for composio upgrade, which resolves releases live',
45 - () =>
46 - Effect.gen(function* () {
47 - const start = vi.fn();
48 - const run = makeRunner(start);
49 -
50 - yield* run(['upgrade']);
51 - yield* run(['--log-level', 'Debug', 'upgrade', '--beta']);
52 -
53 - expect(start).not.toHaveBeenCalled();
54 - })
55 - );
56 -
57 - it.effect('starts the background request for other parsed commands', () =>
58 - Effect.gen(function* () {
59 - const start = vi.fn();
60 - const run = makeRunner(start);
61 -
62 - yield* run(['version']);
63 - yield* run(['other']);
64 -
65 - expect(start).toHaveBeenCalledTimes(2);
66 - })
67 - );
68 - });
69 -});
ts/packages/cli/test/src/commands/registration.test.ts
+13 -13
@@ -8,17 +8,17 @@ import { Effect, Exit, Option, Ref } from 'effect';
8 import { CliError, Command } from 'effect/cli';
9 import { NotLoggedInError } from 'src/commands/errors';
10 import { withRegisteredSubcommands } from 'src/commands/registration';
11 -import { requireLogin } from 'src/effects/require-auth';
11 import { CommandInvocation, commandPathOf, withCommandMeta } from 'src/invocation/command-identity';
12 import { TestLive } from 'test/__utils__';
13
14 class GuardFailed extends CliError.UserError {}
15
16 /**
18 - * A tree shaped like the CLI's: `app` (own handler) registers `outer` (own handler), a root
19 - * shortcut to `link` with its own family, a login-gated group, and a group whose own guard fails.
20 - * `outer` registers `inner` (no handler, aliased `in`) and the same `link` value again. Every
21 - * provider, registration, `begin`, and handler appends to the trace.
17 + * A tree shaped like the CLI's: `app` (whose own handler shows help, like the root's overview)
18 + * registers `outer` (whose own handler is an action), a root shortcut to `link` with its own
19 + * family, a login-gated group, and a group whose own guard fails. `outer` registers `inner` (no
20 + * handler, aliased `in`) and the same `link` value again. Every provider, registration, `begin`,
21 + * and handler appends to the trace.
22 */
23 const traced = (args: ReadonlyArray<string>) =>
24 Effect.gen(function* () {
@@ -40,12 +40,12 @@ const traced = (args: ReadonlyArray<string>) =>
40 provider('inner')
41 );
42 const outer = Command.make('outer', {}, handler('outer')).pipe(
43 - withRegisteredSubcommands([inner, link]),
43 + withRegisteredSubcommands([inner, link], { ownAction: true }),
44 provider('outer')
45 );
46 const gated = Command.make('gated').pipe(
47 withRegisteredSubcommands([Command.make('leaf', {}, handler('gated leaf'))]),
48 - requireLogin
48 + withCommandMeta({ requiresLogin: true })
49 );
50 const guarded = Command.make('guarded').pipe(
51 withRegisteredSubcommands([Command.make('leaf', {}, handler('guarded leaf'))]),
@@ -112,7 +112,7 @@ describe('effect/cli handler composition', () => {
112 ],
113 },
114 {
115 - name: 'a bare group with a handler runs its own handler, no subcommand',
115 + name: 'a bare group with its own action begins it with its input, no subcommand',
116 args: ['outer'],
117 trace: [
118 'provider app',
@@ -123,9 +123,9 @@ describe('effect/cli handler composition', () => {
123 ],
124 },
125 {
126 - name: 'the root with no subcommand runs its own handler',
126 + name: 'the root with no subcommand begins as help, then runs its own handler',
127 args: [],
128 - trace: ['provider app', 'begin composio command', 'handler app'],
128 + trace: ['provider app', 'begin composio command unparsed', 'handler app'],
129 },
130 {
131 name: 'a root shortcut is its own registration, with its own meta',
@@ -152,7 +152,7 @@ describe('effect/cli handler composition', () => {
152 })
153 );
154
155 - it.effect('a bare group without a handler begins, then shows its help', () =>
155 + it.effect('a bare group without a handler begins as help, then shows its help', () =>
156 Effect.gen(function* () {
157 const { exit, trace } = yield* traced(['outer', 'inner']);
158 expect(trace).toEqual([
@@ -161,7 +161,7 @@ describe('effect/cli handler composition', () => {
161 'provider outer',
162 'enter outer inner',
163 'provider inner',
164 - 'begin outer inner command',
164 + 'begin outer inner command unparsed',
165 ]);
166 expect(failureOf(exit)).toMatchObject({
167 _tag: 'ShowHelp',
@@ -185,7 +185,7 @@ describe('effect/cli handler composition', () => {
185 );
186
187 // A guard a group pipes on itself wraps its whole dispatch, so it runs before the selected
188 - // command is reached: only the registrations entered so far are known. `requireLogin` is
188 + // command is reached: only the registrations entered so far are known. A required login is
189 // `CommandMeta` for this reason; the `dev` group's `rejectsSharedFlags` guards are not yet.
190 it.effect('a group-level guard runs before the selected command begins', () =>
191 Effect.gen(function* () {
ts/packages/cli/test/src/commands/run.cmd.test.ts
+3 -1
@@ -162,7 +162,9 @@ describe('CLI: composio run', () => {
162 call => call.service === 'CommandLifecycleTelemetry' && call.event === 'invoked'
163 );
164 const runId =
165 - invoked?.service === 'CommandLifecycleTelemetry' ? invoked.context.runId : undefined;
165 + invoked?.service === 'CommandLifecycleTelemetry' && invoked.event === 'invoked'
166 + ? invoked.context.runId
167 + : undefined;
168 assertDefined(runId);
169 expect(childRunId).toBe(runId);
170 })
ts/packages/cli/test/src/invocation/command-identity.test.ts
+1 -1
@@ -126,7 +126,7 @@ const lifecycleOf = (args: ReadonlyArray<string>) =>
126 yield* cliExit(args);
127 const calls = yield* recordedInvocationCalls;
128 return calls.flatMap(call =>
129 - call.service === 'CommandLifecycleTelemetry'
129 + call.service === 'CommandLifecycleTelemetry' && call.event !== 'pluginHintShown'
130 ? [{ event: call.event, path: call.context.commandPath, family: call.context.family, call }]
131 : []
132 );
ts/packages/cli/test/src/invocation/invocation-hooks.test.ts new
+197
@@ -0,0 +1,197 @@
1 +/**
2 + * Which invocation hooks a command runs, and when: only for a command `effect/cli` selected,
3 + * when it begins (before its invoked event) and before it checks a login, minus what its
4 + * `CommandMeta` turns off.
5 + */
6 +import { describe, expect, it, layer } from '@effect/vitest';
7 +import { Cause, Effect, Exit, Option, Schema } from 'effect';
8 +import { Command } from 'effect/cli';
9 +import { buildRootCommand } from 'src/commands';
10 +import { NotLoggedInError } from 'src/commands/errors';
11 +import { withRegisteredSubcommands } from 'src/commands/registration';
12 +import {
13 + commandPathOf,
14 + identityAt,
15 + INVOCATION_HOOKS,
16 + type InvocationHookName,
17 + runsHook,
18 + withCommandMeta,
19 +} from 'src/invocation/command-identity';
20 +import { cliExit, recordedInvocationCalls, resetInvocationCalls, TestLive } from 'test/__utils__';
21 +
22 +const HOOK_SERVICES: Readonly<Record<InvocationHookName, string>> = {
23 + backendMismatch: 'BackendMismatchWarning',
24 + updateNotice: 'UpdateNotice',
25 + pluginHint: 'PluginHint',
26 + backgroundUpdateCheck: 'BackgroundUpdateCheck',
27 +};
28 +
29 +/** The hook services and lifecycle events `cli(args)` recorded, in order. */
30 +const sequenceOf = (args: ReadonlyArray<string>) =>
31 + Effect.gen(function* () {
32 + // Suites share one recorder.
33 + yield* resetInvocationCalls;
34 + const result = yield* cliExit(args);
35 + const calls = yield* recordedInvocationCalls;
36 + return {
37 + ...result,
38 + sequence: calls.map(call =>
39 + call.service === 'CommandLifecycleTelemetry' ? call.event : call.service
40 + ),
41 + hooked: calls.flatMap(call =>
42 + call.service === 'CommandLifecycleTelemetry'
43 + ? []
44 + : [commandPathOf(call.invocation.identity)]
45 + ),
46 + };
47 + });
48 +
49 +describe('invocation hooks', () => {
50 + layer(TestLive())('when they run', it => {
51 + it.effect(
52 + '[Given] a selected command [Then] its hooks run before its invoked event, for its identity',
53 + () =>
54 + Effect.gen(function* () {
55 + const { exitCode, sequence, hooked } = yield* sequenceOf(['version']);
56 +
57 + expect(exitCode).toBe(0);
58 + expect(sequence).toEqual([
59 + ...INVOCATION_HOOKS.map(hook => HOOK_SERVICES[hook]),
60 + 'invoked',
61 + 'succeeded',
62 + ]);
63 + expect(hooked).toEqual(INVOCATION_HOOKS.map(() => 'version'));
64 + })
65 + );
66 +
67 + it.effect(
68 + '[Given] a login-gated command without a login [Then] the hooks run, then it fails with NotLoggedInError for its own path',
69 + () =>
70 + Effect.gen(function* () {
71 + const { exit, sequence, hooked } = yield* sequenceOf(['tools', 'list', 'gmail']);
72 + const calls = yield* recordedInvocationCalls;
73 +
74 + expect(
75 + Exit.isFailure(exit) &&
76 + Option.exists(
77 + Cause.findErrorOption(exit.cause),
78 + error => error instanceof NotLoggedInError
79 + )
80 + ).toBe(true);
81 + expect(sequence).toEqual([
82 + ...INVOCATION_HOOKS.map(hook => HOOK_SERVICES[hook]),
83 + 'invoked',
84 + 'failed',
85 + ]);
86 + expect(hooked).toEqual(INVOCATION_HOOKS.map(() => 'tools list'));
87 + expect(
88 + calls.flatMap(call =>
89 + call.service === 'CommandLifecycleTelemetry' && call.event === 'failed'
90 + ? [call.context.commandPath]
91 + : []
92 + )
93 + ).toEqual(['tools list']);
94 + })
95 + );
96 +
97 + it.effect.each([
98 + { name: '--help', args: ['--help'] },
99 + { name: 'a subcommand --help', args: ['upgrade', '--help'] },
100 + { name: '--version', args: ['--version'] },
101 + { name: 'a typo', args: ['whoamii'] },
102 + { name: 'a missing argument', args: ['dev', 'triggers', 'list'] },
103 + { name: 'the bare root', args: [] },
104 + { name: 'a bare group (`tools`)', args: ['tools'] },
105 + { name: 'a bare group (`orgs`)', args: ['orgs'] },
106 + { name: 'a bare nested group (`dev triggers`)', args: ['dev', 'triggers'] },
107 + { name: '`help`', args: ['help'] },
108 + { name: '`help <command>`', args: ['help', 'tools'] },
109 + ])('[Given] $name [Then] no hook runs', ({ args }) =>
110 + Effect.gen(function* () {
111 + const { hooked } = yield* sequenceOf(args);
112 + expect(hooked).toEqual([]);
113 + })
114 + );
115 +
116 + // `dev`'s own handler is the developer-mode toggle, an action of its own, not its help.
117 + it.effect.each([
118 + { name: 'dev --mode off', args: ['dev', '--mode', 'off'] },
119 + { name: 'dev', args: ['dev'] },
120 + ])("[Given] a group's own action (`$name`) [Then] its hooks run, for the group", ({ args }) =>
121 + Effect.gen(function* () {
122 + const { hooked } = yield* sequenceOf(args);
123 + expect(hooked).toEqual(INVOCATION_HOOKS.map(() => 'dev'));
124 + })
125 + );
126 + });
127 +});
128 +
129 +describe('hook opt-outs from CommandMeta', () => {
130 + const root = buildRootCommand({
131 + isDevModeEnabled: true,
132 + isExperimentalFeatureEnabled: () => true,
133 + });
134 +
135 + /** Commands that turn hooks off (and some that do not), with the input `effect/cli` parses. */
136 + const COMMANDS: ReadonlyArray<{
137 + readonly name: string;
138 + readonly path: ReadonlyArray<string>;
139 + readonly input: unknown;
140 + readonly off: ReadonlyArray<InvocationHookName>;
141 + }> = [
142 + { name: 'version', path: ['version'], input: { check: false }, off: [] },
143 + {
144 + name: 'version --check',
145 + path: ['version'],
146 + input: { check: true },
147 + off: ['backgroundUpdateCheck'],
148 + },
149 + {
150 + name: 'upgrade',
151 + path: ['upgrade'],
152 + input: {},
153 + off: ['updateNotice', 'backgroundUpdateCheck'],
154 + },
155 + { name: 'setup', path: ['setup'], input: {}, off: ['pluginHint'] },
156 + { name: 'setup skill', path: ['setup', 'skill'], input: {}, off: ['pluginHint'] },
157 + { name: 'help', path: ['help'], input: {}, off: INVOCATION_HOOKS },
158 + { name: 'help tools', path: ['help', 'tools'], input: {}, off: INVOCATION_HOOKS },
159 + { name: 'whoami', path: ['whoami'], input: {}, off: [] },
160 + { name: 'dev triggers list', path: ['dev', 'triggers', 'list'], input: {}, off: [] },
161 + ];
162 +
163 + const cases = COMMANDS.flatMap(command =>
164 + INVOCATION_HOOKS.map(hook => ({ ...command, hook, runs: !command.off.includes(hook) }))
165 + );
166 +
167 + it.each(cases)('`composio $name` runs $hook: $runs', ({ path, input, hook, runs }) => {
168 + const identity = identityAt(root, ['composio', ...path]);
169 + expect(identity.path).toEqual(path);
170 + expect(runsHook(identity.meta, hook, input)).toBe(runs);
171 + });
172 +
173 + it('a subcommand inherits a boolean policy, never a predicate over its group input', () => {
174 + const groupInput = Schema.is(Schema.Struct({ quiet: Schema.Literal(true) }));
175 + const seen: Array<unknown> = [];
176 + const group = Command.make('group').pipe(
177 + withRegisteredSubcommands([Command.make('leaf', {}, () => Effect.void)]),
178 + withCommandMeta({
179 + hooks: {
180 + updateNotice: false,
181 + pluginHint: input => {
182 + seen.push(input);
183 + return !groupInput(input);
184 + },
185 + },
186 + })
187 + );
188 + const tree = Command.make('app').pipe(withRegisteredSubcommands([group]));
189 + const groupMeta = identityAt(tree, ['app', 'group']).meta;
190 + const leafMeta = identityAt(tree, ['app', 'group', 'leaf']).meta;
191 +
192 + expect(runsHook(groupMeta, 'pluginHint', { quiet: true })).toBe(false);
193 + expect(runsHook(leafMeta, 'pluginHint', { quiet: true })).toBe(true);
194 + expect(runsHook(leafMeta, 'updateNotice', {})).toBe(false);
195 + expect(seen).toEqual([{ quiet: true }]);
196 + });
197 +});
ts/packages/cli/test/src/invocation/invocation.test.ts
+11 -10
@@ -46,14 +46,15 @@ const recordedSequence = Effect.map(recordedInvocationCalls, calls =>
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' },
49 + { args: ['version'], exitCode: 0, outcome: 'succeeded', hooks: true },
50 + { args: [], exitCode: 0, outcome: 'succeeded', hooks: false },
51 + { args: ['help'], exitCode: 0, outcome: 'succeeded', hooks: false },
52 + { args: ['--help'], exitCode: 0, outcome: 'succeeded', hooks: false },
53 + { args: ['--version'], exitCode: 0, outcome: 'succeeded', hooks: false },
54 + { args: ['help', 'orgz'], exitCode: 1, outcome: 'failed', hooks: false },
55 ])(
55 - '[Given] `composio $args` [Then] runs the hooks, then records the command as $outcome',
56 - ({ args, exitCode, outcome }) =>
56 + '[Given] `composio $args` [Then] records the command as $outcome, with hooks: $hooks',
57 + ({ args, exitCode, outcome, hooks }) =>
58 Effect.gen(function* () {
59 // The suite shares one recorder.
60 yield* resetInvocationCalls;
@@ -62,9 +63,9 @@ describe('runInvocation', () => {
63
64 expect(result.exitCode).toBe(exitCode);
65 expect(yield* recordedSequence).toEqual([
65 - 'BackendMismatchWarning',
66 - 'UpdateNotice',
67 - 'PluginHint',
66 + ...(hooks
67 + ? ['BackendMismatchWarning', 'UpdateNotice', 'PluginHint', 'BackgroundUpdateCheck']
68 + : []),
69 'CommandLifecycleTelemetry.invoked',
70 `CommandLifecycleTelemetry.${outcome}`,
71 ]);
ts/packages/cli/test/src/services/backend-mismatch-warning.test.ts
+2 -1
@@ -4,6 +4,7 @@ import type { BackendMismatch } from 'src/config/backend';
4 import { BackendMismatchWarning } from 'src/services/backend-mismatch-warning';
5 import { getTerminalCapabilities, TerminalUI } from 'src/services/terminal-ui';
6 import { ComposioUserContext } from 'src/services/user-context';
7 +import { commandIdentity } from 'test/__utils__/command-identity';
8 import { terminalUITestImpl } from 'test/__utils__/services/terminal-ui-test';
9
10 const MISMATCH: BackendMismatch = {
@@ -80,7 +81,7 @@ describe('BackendMismatchWarning', () => {
81 const terminal = recordingTerminal(stderrIsTTY);
82 return Effect.gen(function* () {
83 const warning = yield* BackendMismatchWarning;
83 - yield* warning.run({ argv: ['bun', 'composio', 'whoami'] });
84 + yield* warning.run({ identity: commandIdentity(['whoami']) });
85 expect(terminal.written).toEqual(expected);
86 }).pipe(
87 Effect.provide(
ts/packages/cli/test/src/services/invocation-hooks-test-layer.test.ts
+12 -2
@@ -5,13 +5,14 @@ import { commandTelemetryContext } from 'test/__utils__/telemetry-context';
5 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';
8 +import { BackgroundUpdateCheck, UpdateNotice } from 'src/services/update-check';
9 import {
10 MockConsole,
11 recordedInvocationCalls,
12 resetInvocationCalls,
13 TestLive,
14 } from 'test/__utils__';
15 +import { commandIdentity } from 'test/__utils__/command-identity';
16 import { trackedEvents } from 'test/__utils__/tracked-events';
17
18 // Records instead of dispatching, so a double that reached the real sink would show up below.
@@ -27,25 +28,34 @@ describe('TestLive invocation hooks and telemetry sink', () => {
28 layer(TestLive())(it => {
29 it.effect('[Given] every hook and lifecycle event [Then] records each call, in order', () =>
30 Effect.gen(function* () {
30 - const invocation = { argv: ['/bin/bun', '/cli/bin.ts', 'whoami'] };
31 + const invocation = { identity: commandIdentity(['whoami']) };
32 const context = commandTelemetryContext(['whoami'], { path: ['whoami'], input: {} });
33 const cause = Cause.fail(new TypeError('boom'));
34 + const shown = {
35 + invocationOrigin: 'cli',
36 + commandPath: 'whoami',
37 + agentHost: 'claude',
38 + } as const;
39
40 yield* (yield* BackendMismatchWarning).run(invocation);
41 yield* (yield* UpdateNotice).run(invocation);
42 yield* (yield* PluginHint).run(invocation);
43 + yield* (yield* BackgroundUpdateCheck).run(invocation);
44 const telemetry = yield* CommandLifecycleTelemetry;
45 yield* telemetry.invoked(context);
46 yield* telemetry.succeeded(context);
47 yield* telemetry.failed(context, cause);
48 + yield* telemetry.pluginHintShown(shown);
49
50 expect(yield* recordedInvocationCalls).toEqual([
51 { service: 'BackendMismatchWarning', invocation },
52 { service: 'UpdateNotice', invocation },
53 { service: 'PluginHint', invocation },
54 + { service: 'BackgroundUpdateCheck', invocation },
55 { service: 'CommandLifecycleTelemetry', event: 'invoked', context },
56 { service: 'CommandLifecycleTelemetry', event: 'succeeded', context },
57 { service: 'CommandLifecycleTelemetry', event: 'failed', context, cause },
58 + { service: 'CommandLifecycleTelemetry', event: 'pluginHintShown', shown },
59 ]);
60 // The doubles are no-ops: nothing reaches the console or the analytics dispatcher.
61 expect(yield* MockConsole.getLines()).toEqual([]);
ts/packages/cli/test/src/services/plugin-hint.test.ts
+73 -82
@@ -8,17 +8,21 @@ import { dirname, join } from 'node:path';
8 import { Writable } from 'node:stream';
9 import { HOST_CONFIG } from 'src/config';
10 import { APP_VERSION } from 'src/constants';
11 +import {
12 + CommandLifecycleTelemetry,
13 + type PluginHintShown,
14 +} from 'src/services/command-lifecycle-telemetry';
15 import { defaultNodeOs, NodeOs } from 'src/services/node-os';
16 import { NodeProcess } from 'src/services/node-process';
17 import { detectPluginHost } from 'src/services/agent-host-env';
18 import {
19 createPluginHint,
16 - findRootCommandName,
20 PluginHint,
21 resolvePluginHintConfig,
22 type PluginHintConfig,
23 } from 'src/services/plugin-hint';
24 import { makeTerminalUI, TerminalUI } from 'src/services/terminal-ui';
25 +import { commandIdentity } from 'test/__utils__/command-identity';
26 import { terminalUITestImpl } from 'test/__utils__/services/terminal-ui-test';
27 import { trackedEvents } from 'test/__utils__/tracked-events';
28
@@ -33,8 +37,14 @@ vi.mock('src/analytics/dispatch', async importOriginal => {
37 const DAY_MS = 24 * 60 * 60 * 1000;
38
39 let tempDir: string;
40 +/** What the hint reported through `telemetry` in the current test. */
41 +let shownEvents: PluginHintShown[];
42 +const telemetry = {
43 + pluginHintShown: (shown: PluginHintShown) => Effect.sync(() => shownEvents.push(shown)),
44 +};
45 beforeEach(() => {
46 tempDir = mkdtempSync(join(tmpdir(), 'plugin-hint-test-'));
47 + shownEvents = [];
48 });
49 afterEach(() => {
50 vi.useRealTimers();
@@ -56,7 +66,7 @@ function makeConfig(overrides?: Partial<PluginHintConfig>): PluginHintConfig {
66 stateDirectory: join(tempDir, '.composio', 'plugin-hints'),
67 host: 'claude',
68 invocationOrigin: undefined,
59 - commandName: 'version',
69 + commandPath: 'version',
70 claudeInstalledPluginsFile: join(tempDir, '.claude', 'plugins', 'installed_plugins.json'),
71 codexConfigFile: join(tempDir, '.codex', 'config.toml'),
72 hintIntervalMs: DAY_MS,
@@ -117,11 +127,11 @@ describe('resolvePluginHintConfig', () => {
127 vi.stubEnv('CLAUDECODE', '1');
128
129 return Effect.gen(function* () {
120 - const config = yield* resolvePluginHintConfig(['/bin/bun', '/cli/bin.ts', 'version']);
130 + const config = yield* resolvePluginHintConfig('version');
131
132 expect(config.stateDirectory).toBe(join(cacheDir, 'plugin-hints'));
133 expect(config.host).toBe('claude');
124 - expect(config.commandName).toBe('version');
134 + expect(config.commandPath).toBe('version');
135 }).pipe(
136 Effect.provideService(ConfigProvider.ConfigProvider, ConfigProvider.fromEnv()),
137 Effect.provide(hintLayers())
@@ -133,7 +143,7 @@ describe('resolvePluginHintConfig', () => {
143 vi.stubEnv('CODEX_HOME', ' ');
144
145 return Effect.gen(function* () {
136 - const config = yield* resolvePluginHintConfig(['/bin/bun', '/cli/bin.ts', 'version']);
146 + const config = yield* resolvePluginHintConfig('version');
147
148 expect(config.claudeInstalledPluginsFile).toBe(
149 join(tempDir, '.claude', 'plugins', 'installed_plugins.json')
@@ -152,7 +162,7 @@ describe('resolvePluginHintConfig', () => {
162 vi.stubEnv('CODEX_HOME', codexHome);
163
164 return Effect.gen(function* () {
155 - const config = yield* resolvePluginHintConfig(['/bin/bun', '/cli/bin.ts', 'version']);
165 + const config = yield* resolvePluginHintConfig('version');
166
167 expect(config.claudeInstalledPluginsFile).toBe(
168 join(claudeConfigDir, 'plugins', 'installed_plugins.json')
@@ -169,7 +179,7 @@ describe('resolvePluginHintConfig', () => {
179 vi.stubEnv('CODEX_HOME', 'codex-relative');
180
181 return Effect.gen(function* () {
172 - const config = yield* resolvePluginHintConfig(['/bin/bun', '/cli/bin.ts', 'version']);
182 + const config = yield* resolvePluginHintConfig('version');
183
184 expect(config.claudeInstalledPluginsFile).toBe(
185 join(tempDir, 'claude-relative', 'plugins', 'installed_plugins.json')
@@ -182,18 +192,6 @@ describe('resolvePluginHintConfig', () => {
192 });
193 });
194
185 -describe('findRootCommandName', () => {
186 - it('skips root log-level flags before the subcommand', () => {
187 - expect(findRootCommandName(['/bin/bun', '/cli/bin.ts', 'setup'])).toBe('setup');
188 - expect(findRootCommandName(['/bin/bun', '/cli/bin.ts', '--log-level', 'debug', 'setup'])).toBe(
189 - 'setup'
190 - );
191 - expect(findRootCommandName(['/bin/bun', '/cli/bin.ts', '--log-level=debug', 'setup'])).toBe(
192 - 'setup'
193 - );
194 - });
195 -});
196 -
195 describe('showPluginHint', () => {
196 let output: string[];
197
@@ -205,11 +203,11 @@ describe('showPluginHint', () => {
203 Effect.gen(function* () {
204 const claudeConfig = makeConfig();
205 writeClaudePlugins(claudeConfig, { 'other@marketplace': [{ scope: 'user' }] });
208 - yield* createPluginHint(claudeConfig).showPluginHint(makeTerminal(output));
206 + yield* createPluginHint(claudeConfig).showPluginHint(makeTerminal(output), telemetry);
207
208 const codexConfig = makeConfig({ host: 'codex' });
209 writeFileAt(codexConfig.codexConfigFile, '[plugins."glen@glen"]\nenabled = true\n');
212 - yield* createPluginHint(codexConfig).showPluginHint(makeTerminal(output));
210 + yield* createPluginHint(codexConfig).showPluginHint(makeTerminal(output), telemetry);
211
212 expect(output).toEqual([
213 "Tip: running under Claude Code without the Composio plugin — 'composio setup --yes' installs it.",
@@ -222,36 +220,30 @@ describe('showPluginHint', () => {
220 Effect.gen(function* () {
221 const config = makeConfig();
222
225 - yield* createPluginHint(config).showPluginHint({
226 - error: () => Effect.die(new Error('EPIPE')),
227 - });
223 + yield* createPluginHint(config).showPluginHint(
224 + { error: () => Effect.die(new Error('EPIPE')) },
225 + telemetry
226 + );
227 expect(existsSync(join(config.stateDirectory, 'claude.stamp'))).toBe(false);
228
230 - yield* createPluginHint(config).showPluginHint(makeTerminal(output));
229 + yield* createPluginHint(config).showPluginHint(makeTerminal(output), telemetry);
230 expect(output).toHaveLength(1);
231 }).pipe(Effect.provide(hintLayers()))
232 );
233
235 - it.effect('tracks CLI_PLUGIN_HINT_SHOWN once per printed hint', () =>
234 + it.effect('reports the hint to the telemetry service once per printed hint', () =>
235 Effect.gen(function* () {
237 - const config = makeConfig({ invocationOrigin: 'installer', commandName: 'whoami' });
236 + const config = makeConfig({ invocationOrigin: 'installer', commandPath: 'whoami' });
237
239 - yield* createPluginHint(config).showPluginHint(makeTerminal(output));
240 - yield* createPluginHint(config).showPluginHint(makeTerminal(output));
238 + yield* createPluginHint(config).showPluginHint(makeTerminal(output), telemetry);
239 + yield* createPluginHint(config).showPluginHint(makeTerminal(output), telemetry);
240
241 expect(output).toHaveLength(1);
243 - expect(trackedEvents).toEqual([
244 - {
245 - name: 'CLI_PLUGIN_HINT_SHOWN',
246 - properties: expect.objectContaining({
247 - source: 'cli',
248 - invocation_origin: 'installer',
249 - cli_version: APP_VERSION,
250 - command_path: 'whoami',
251 - agent_host: 'claude',
252 - }),
253 - },
242 + expect(shownEvents).toEqual([
243 + { invocationOrigin: 'installer', commandPath: 'whoami', agentHost: 'claude' },
244 ]);
245 + // The hint tracks nothing itself.
246 + expect(trackedEvents).toEqual([]);
247 }).pipe(Effect.provide(hintLayers()))
248 );
249
@@ -259,11 +251,11 @@ describe('showPluginHint', () => {
251 Effect.gen(function* () {
252 const claudeConfig = makeConfig();
253 writeClaudePlugins(claudeConfig, { 'composio@composio': [{ scope: 'user' }] });
262 - yield* createPluginHint(claudeConfig).showPluginHint(makeTerminal(output));
254 + yield* createPluginHint(claudeConfig).showPluginHint(makeTerminal(output), telemetry);
255
256 const codexConfig = makeConfig({ host: 'codex' });
257 writeFileAt(codexConfig.codexConfigFile, '[plugins."composio@composio"]\nenabled = true\n');
266 - yield* createPluginHint(codexConfig).showPluginHint(makeTerminal(output));
258 + yield* createPluginHint(codexConfig).showPluginHint(makeTerminal(output), telemetry);
259
260 expect(output).toEqual([]);
261 expect(existsSync(claudeConfig.stateDirectory)).toBe(false);
@@ -275,27 +267,25 @@ describe('showPluginHint', () => {
267 const config = makeConfig();
268 writeFileAt(config.claudeInstalledPluginsFile, 'not json{');
269
278 - yield* createPluginHint(config).showPluginHint(makeTerminal(output));
270 + yield* createPluginHint(config).showPluginHint(makeTerminal(output), telemetry);
271
272 expect(output).toEqual([]);
273 }).pipe(Effect.provide(hintLayers()))
274 );
275
284 - it.effect('stays silent outside a host, in run children, and for setup', () =>
276 + // `composio setup` turns the hint off in its `CommandMeta`; see
277 + // `test/src/invocation/invocation-hooks.test.ts`.
278 + it.effect('stays silent outside a host and in run children', () =>
279 Effect.gen(function* () {
286 - const configs = [
287 - makeConfig({ host: undefined }),
288 - makeConfig({ invocationOrigin: 'run' }),
289 - makeConfig({ commandName: 'setup' }),
290 - ];
280 + const configs = [makeConfig({ host: undefined }), makeConfig({ invocationOrigin: 'run' })];
281
282 yield* Effect.forEach(configs, config =>
293 - createPluginHint(config).showPluginHint(makeTerminal(output))
283 + createPluginHint(config).showPluginHint(makeTerminal(output), telemetry)
284 );
285
286 expect(output).toEqual([]);
297 - expect(trackedEvents).toEqual([]);
298 - expect(existsSync(configs[2]!.stateDirectory)).toBe(false);
287 + expect(shownEvents).toEqual([]);
288 + expect(existsSync(configs[1]!.stateDirectory)).toBe(false);
289 }).pipe(Effect.provide(hintLayers()))
290 );
291
@@ -305,7 +295,7 @@ describe('showPluginHint', () => {
295
296 yield* Effect.all(
297 Array.from({ length: 20 }, () =>
308 - createPluginHint(config).showPluginHint(makeTerminal(output))
298 + createPluginHint(config).showPluginHint(makeTerminal(output), telemetry)
299 ),
300 { concurrency: 'unbounded' }
301 );
@@ -320,10 +310,10 @@ describe('showPluginHint', () => {
310 const claudeConfig = makeConfig({ host: 'claude' });
311 const codexConfig = makeConfig({ host: 'codex' });
312
323 - yield* createPluginHint(claudeConfig).showPluginHint(makeTerminal(output));
324 - yield* createPluginHint(codexConfig).showPluginHint(makeTerminal(output));
325 - yield* createPluginHint(claudeConfig).showPluginHint(makeTerminal(output));
326 - yield* createPluginHint(codexConfig).showPluginHint(makeTerminal(output));
313 + yield* createPluginHint(claudeConfig).showPluginHint(makeTerminal(output), telemetry);
314 + yield* createPluginHint(codexConfig).showPluginHint(makeTerminal(output), telemetry);
315 + yield* createPluginHint(claudeConfig).showPluginHint(makeTerminal(output), telemetry);
316 + yield* createPluginHint(codexConfig).showPluginHint(makeTerminal(output), telemetry);
317
318 expect(output).toHaveLength(2);
319 }).pipe(Effect.provide(hintLayers()))
@@ -339,7 +329,7 @@ describe('showPluginHint', () => {
329 const stale = new Date('2026-07-27T00:00:00.000Z');
330 utimesSync(stamp, stale, stale);
331
342 - yield* createPluginHint(config).showPluginHint(makeTerminal(output));
332 + yield* createPluginHint(config).showPluginHint(makeTerminal(output), telemetry);
333
334 expect(output).toHaveLength(1);
335 }).pipe(Effect.provide(hintLayers()))
@@ -361,7 +351,7 @@ describe('showPluginHint', () => {
351 stderr: Object.assign(capture, { isTTY: false }),
352 });
353
364 - yield* createPluginHint(config).showPluginHint(terminal);
354 + yield* createPluginHint(config).showPluginHint(terminal, telemetry);
355
356 expect(chunks.join('')).toContain('composio setup');
357 }).pipe(Effect.provide(hintLayers()))
@@ -369,16 +359,21 @@ describe('showPluginHint', () => {
359 });
360
361 describe('PluginHint', () => {
372 - /** `PluginHint.Default` with every path under `tempDir` and a recording stderr. */
373 - const pluginHintLayer = (output: string[]) =>
374 - Layer.provide(
362 + /**
363 + * `PluginHint.Default` over the real `CommandLifecycleTelemetry` (its dispatcher mocked above),
364 + * with every path under `tempDir` and a recording stderr.
365 + */
366 + const pluginHintLayer = (output: string[]) => {
367 + const services = Layer.mergeAll(
368 + BunServices.layer,
369 + Layer.succeed(NodeOs, defaultNodeOs({ homedir: tempDir })),
370 + Layer.succeed(TerminalUI, TerminalUI.of({ ...terminalUITestImpl, ...makeTerminal(output) }))
371 + );
372 + return Layer.provide(
373 PluginHint.Default,
376 - Layer.mergeAll(
377 - BunServices.layer,
378 - Layer.succeed(NodeOs, defaultNodeOs({ homedir: tempDir })),
379 - Layer.succeed(TerminalUI, TerminalUI.of({ ...terminalUITestImpl, ...makeTerminal(output) }))
380 - )
374 + Layer.merge(services, Layer.provide(CommandLifecycleTelemetry.Default, services))
375 );
376 + };
377
378 /** Runs under Claude Code, which has no Composio plugin installed. */
379 const underClaudeCode = Effect.provideService(
@@ -387,13 +382,14 @@ describe('PluginHint', () => {
382 );
383
384 it.effect(
390 - '[Given] Claude Code without the plugin [Then] prints and tracks the hint once per interval',
385 + '[Given] Claude Code without the plugin [Then] prints the hint once per interval and tracks it through the telemetry service',
386 () => {
387 const output: string[] = [];
388 + const identity = commandIdentity(['dev', 'triggers', 'list']);
389 return Effect.gen(function* () {
390 const hint = yield* PluginHint;
395 - yield* hint.run({ argv: ['/bin/bun', '/cli/bin.ts', 'whoami'] });
396 - yield* hint.run({ argv: ['/bin/bun', '/cli/bin.ts', 'whoami'] });
391 + yield* hint.run({ identity });
392 + yield* hint.run({ identity });
393
394 expect(output).toEqual([
395 "Tip: running under Claude Code without the Composio plugin — 'composio setup --yes' installs it.",
@@ -401,21 +397,16 @@ describe('PluginHint', () => {
397 expect(trackedEvents).toEqual([
398 {
399 name: 'CLI_PLUGIN_HINT_SHOWN',
404 - properties: expect.objectContaining({ command_path: 'whoami', agent_host: 'claude' }),
400 + properties: expect.objectContaining({
401 + source: 'cli',
402 + invocation_origin: 'cli',
403 + cli_version: APP_VERSION,
404 + command_path: 'dev triggers list',
405 + agent_host: 'claude',
406 + }),
407 },
408 ]);
409 }).pipe(underClaudeCode, Effect.provide(pluginHintLayer(output)));
410 }
411 );
410 -
411 - it.effect('[Given] `composio setup` [Then] prints and tracks nothing', () => {
412 - const output: string[] = [];
413 - return Effect.gen(function* () {
414 - const hint = yield* PluginHint;
415 - yield* hint.run({ argv: ['/bin/bun', '/cli/bin.ts', 'setup'] });
416 -
417 - expect(output).toEqual([]);
418 - expect(trackedEvents).toEqual([]);
419 - }).pipe(underClaudeCode, Effect.provide(pluginHintLayer(output)));
420 - });
412 });
ts/packages/cli/test/src/services/update-check.test.ts
+13 -31
@@ -8,6 +8,7 @@ import { Effect, Fiber, Layer } from 'effect';
8 import { withHttpServerEffect } from 'test/__utils__/http-server';
9 import { defaultNodeOs, NodeOs } from 'src/services/node-os';
10 import { getTerminalCapabilities, TerminalUI } from 'src/services/terminal-ui';
11 +import { commandIdentity } from 'test/__utils__/command-identity';
12 import { terminalUITestImpl } from 'test/__utils__/services/terminal-ui-test';
13 import {
14 createUpdateChecker,
@@ -224,21 +225,6 @@ describe('showUpdateNotice', () => {
225 }).pipe(Effect.provide(PlatformLayers))
226 );
227
227 - it.effect('skips the cached hint for composio upgrade but keeps it for other commands', () =>
228 - Effect.gen(function* () {
229 - const config = makeConfig({ currentVersion: '0.4.2' });
230 - writeState(config, { lastChecked: new Date().toISOString(), latestVersion: '0.4.5' });
231 - const { showUpdateNotice } = createUpdateChecker(config);
232 -
233 - yield* showUpdateNotice(makeTerminal(output), 'upgrade');
234 - expect(output).toEqual([]);
235 -
236 - yield* showUpdateNotice(makeTerminal(output), 'tools');
237 - expect(output).toHaveLength(1);
238 - expect(output[0]).toContain('0.4.5');
239 - }).pipe(Effect.provide(PlatformLayers))
240 - );
241 -
228 it.effect('does not print upgrade hint when stderr is captured', () =>
229 Effect.gen(function* () {
230 const config = makeConfig({ currentVersion: '0.2.0' });
@@ -321,27 +307,23 @@ describe('UpdateNotice', () => {
307 const writeCachedLatest = (latestVersion: string) =>
308 writeState(makeConfig(), { lastChecked: new Date().toISOString(), latestVersion });
309
324 - it.effect.each([
325 - { command: 'tools', printed: true },
326 - { command: 'upgrade', printed: false },
327 - ])(
328 - '[Given] a newer cached release and `composio $command` [Then] prints the notice: $printed',
329 - ({ command, printed }) => {
330 - const output: string[] = [];
331 - writeCachedLatest('999.0.0');
332 - return Effect.gen(function* () {
333 - const notice = yield* UpdateNotice;
334 - yield* notice.run({ argv: ['/bin/bun', '/cli/bin.ts', command] });
335 - expect(output.some(line => line.includes('999.0.0'))).toBe(printed);
336 - }).pipe(Effect.provide(noticeLayer(output)));
337 - }
338 - );
310 + // Which commands run it is their `CommandMeta`'s business: see
311 + // `test/src/invocation/invocation-hooks.test.ts`.
312 + it.effect('[Given] a newer cached release [Then] prints the notice', () => {
313 + const output: string[] = [];
314 + writeCachedLatest('999.0.0');
315 + return Effect.gen(function* () {
316 + const notice = yield* UpdateNotice;
317 + yield* notice.run({ identity: commandIdentity(['tools', 'list']) });
318 + expect(output.some(line => line.includes('999.0.0'))).toBe(true);
319 + }).pipe(Effect.provide(noticeLayer(output)));
320 + });
321
322 it.effect('[Given] no cached release [Then] prints nothing', () => {
323 const output: string[] = [];
324 return Effect.gen(function* () {
325 const notice = yield* UpdateNotice;
344 - yield* notice.run({ argv: ['/bin/bun', '/cli/bin.ts', 'tools'] });
326 + yield* notice.run({ identity: commandIdentity(['tools', 'list']) });
327 expect(output).toEqual([]);
328 }).pipe(Effect.provide(noticeLayer(output)));
329 });