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

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

refactor(cli): put invocation hooks and telemetry behind services (#5129)

This PR: - builds on top of https://github.com/ComposioHQ/composio/pull/5131 (`fix/cli-signal-handling`), merged in rather than rebased; https://github.com/ComposioHQ/composio/pull/5128 below it is merged - puts the hooks `cli-main.ts` runs before every command behind `Context.Service`s with explicit `Default` layers: `BackendMismatchWarning`, `UpdateNotice`, `PluginHint` (each an `InvocationHookShape`, `run(invocation: HookInvocation)`) - puts the invoked/succeeded/failed lifecycle events behind `CommandLifecycleTelemetry` (`invoked`, `succeeded`, `failed(context, cause)`) - adds the production layers to cli-main's layer stack; the hooks still run before parsing, in the same order, with the same output and events - `TestLive` provides recording no-op doubles of all four; `recordedInvocationCalls` returns their calls in order, so existing stderr assertions are unchanged - removes `showUpdateNotice(argv)` and `showPluginAcquisitionHint(argv)`; `UpdateNotice` and `PluginHint` now take `FileSystem`/`Path`/`NodeOs` from their layer, so tests can point them at a temp home ## Context `HookInvocation` carries only the argv today. A later change can add the command resolved after parsing to it without touching each hook's shape. Verification: `pnpm typecheck`, `pnpm --filter @composio/cli run lint:effect`, `pnpm --filter @composio/cli test` (217 files, 2636 passed, 1 skipped), `oxlint ts/packages/cli`. I also compared stderr/stdout of `bun run src/bin.ts` before and after this change for `whoami`, `version`, `upgrade --help`, and `tools list gmail`, under Claude Code with a backend mismatch and telemetry debug on. The output is identical except for one stack-trace line number in `cli-main.ts`. --------- Co-authored-by: Vinayak Agarwal <vinayak@composio.dev> Co-authored-by: manobhisriram <manobhisriram@gmail.com>

Alberto Schiabel committed Oct 28, 2026 at 14:56 UTC f7ff653a87ced4df74280d5b143bc35cb1aabb61
16 files changed +690 -67
ts/packages/cli/AGENTS.md
+7 -1
@@ -122,16 +122,22 @@ test/src/commands/<group>/<shared-module>.test.ts group helper
122 | `JsPackageManagerDetector` | Detects npm/pnpm/yarn/bun for install instructions |
123 | `UpgradeBinary` | Fetches latest release from GitHub, downloads and replaces binary |
124 | `DashboardToolExecution` | Sends consumer `composio execute` calls to the Composio Dashboard and decodes its reply |
125 +| `BackendMismatchWarning` | Warns before a command when an env var sends the stored key to a backend other than its issuer |
126 +| `UpdateNotice` | Prints the cached "update available" hint before a command, except `upgrade` |
127 +| `PluginHint` | Prints the Composio agent plugin hint under Claude Code or Codex, at most once a day |
128 +| `CommandLifecycleTelemetry` | Tracks the running command's invoked, succeeded, and failed events |
129
130 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`.
131
132 Services are `Context.Service` classes that export a `<Name>Shape` type and an explicit `static readonly Default` layer (`Layer.effect` / `Layer.sync`, dependencies provided with `Layer.provide`). Build a test double with `Service.of({ ... })`; there are no generated accessors or constructors.
133
134 +`cli-main.ts` runs `BackendMismatchWarning`, `UpdateNotice`, and `PluginHint` (each an `InvocationHookShape` from `src/services/invocation-hook.ts`, taking a `HookInvocation`) in that order before parsing, and reports the command's lifecycle through `CommandLifecycleTelemetry`. `TestLive` provides recording no-op doubles of all four (`test/__utils__/layers/invocation-hooks.ts`); `recordedInvocationCalls` returns what they were called with.
135 +
136 OS credential storage uses the sibling package `@composio/cli-keyring` (macOS Keychain / Linux Secret Service).
137
138 ### Effects — `src/effects/`
139
134 -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`.
140 +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).
141
142 ### Models — `src/models/`
143
ts/packages/cli/src/cli-main.ts
+47 -43
@@ -8,7 +8,8 @@
8 * exits with its `[Runtime.errorExitCode]` (1 when unset), or 0 on success. Signals are the
9 * runner's (`src/run-main.ts`): a command a signal cancelled exits 128 + its number.
10 */
11 -import { Cause, ConfigProvider, Effect, Layer, Logger, Option, Runtime } from 'effect';
11 +import { Cause, ConfigProvider, Effect, Layer, Logger, Runtime } from 'effect';
12 +import * as Path from 'effect/Path';
13 import { captureErrors, prettyPrintFromCapturedErrors } from 'effect-errors/index';
14 import { CliConfig, CliError } from 'effect/cli';
15 import { FetchHttpClient } from 'effect/http';
@@ -29,11 +30,7 @@ import { NodeOs } from 'src/services/node-os';
30 import { NodeProcess } from 'src/services/node-process';
31 import { JsPackageManagerDetector } from 'src/services/js-package-manager-detector';
32 import { ComposioCliUserConfigLive } from 'src/services/cli-user-config';
32 -import {
33 - ComposioUserContext,
34 - ComposioUserContextLive as _ComposioUserContextLive,
35 -} from 'src/services/user-context';
36 -import { formatBackendMismatch } from 'src/config/backend';
33 +import { ComposioUserContextLive as _ComposioUserContextLive } from 'src/services/user-context';
34 import { isRejectedUserApiKey, rejectedUserApiKeyHint } from 'src/effects/rejected-user-api-key';
35 import { extractMessage } from 'src/utils/api-error-extraction';
36 import { UpgradeBinary } from 'src/services/upgrade-binary';
@@ -46,17 +43,16 @@ import { ProjectContext } from 'src/services/project-context';
43 import { ProjectEnvironmentDetector } from 'src/services/project-environment-detector';
44 import { CommandRunner } from 'src/services/command-runner';
45 import { StdinLive } from 'src/services/stdin';
49 -import { showPluginAcquisitionHint } from 'src/services/plugin-hint';
50 -import { showUpdateNotice } from 'src/services/update-check';
46 +import { PluginHint } from 'src/services/plugin-hint';
47 +import { UpdateNotice } from 'src/services/update-check';
48 +import { BackendMismatchWarning } from 'src/services/backend-mismatch-warning';
49 +import type { HookInvocation } from 'src/services/invocation-hook';
50 +import { CommandLifecycleTelemetry } from 'src/services/command-lifecycle-telemetry';
51 import {
52 configureCliAnalyticsReleaseVersion,
53 createCliCommandTelemetryContext,
54 getExecuteCommandToolSlug,
55 - getPrimaryLifecycleFailedEvent,
56 - getPrimaryLifecycleInvokedEvent,
57 - getPrimaryLifecycleSucceededEvent,
55 } from 'src/analytics/events';
59 -import { trackCliEventEffect } from 'src/analytics/dispatch';
56 import { getVersion } from 'src/effects/version';
57 import { LogLevelFromConfigLive } from 'src/effects/with-log-level';
58 import { toolkitFromToolSlug } from 'src/effects/toolkit-from-tool-slug';
@@ -149,6 +145,28 @@ export const PendingLoginSessionLive = Layer.provide(
145 Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOs.Default)
146 ) satisfies RequiredLayer;
147
148 +export const BackendMismatchWarningLive = Layer.provide(
149 + BackendMismatchWarning.Default,
150 + Layer.mergeAll(ComposioUserContextLive, TerminalUILive)
151 +) satisfies RequiredLayer;
152 +
153 +// `Path.layer`, not `BunPath.layer`: the update notice and the plugin hint have always resolved
154 +// their state files with Effect's own path implementation.
155 +export const UpdateNoticeLive = Layer.provide(
156 + UpdateNotice.Default,
157 + Layer.mergeAll(TerminalUILive, BunFileSystem.layer, Path.layer, NodeOs.Default)
158 +) satisfies RequiredLayer;
159 +
160 +export const PluginHintLive = Layer.provide(
161 + PluginHint.Default,
162 + Layer.mergeAll(TerminalUILive, BunFileSystem.layer, Path.layer, NodeOs.Default)
163 +) satisfies RequiredLayer;
164 +
165 +export const CommandLifecycleTelemetryLive = Layer.provide(
166 + CommandLifecycleTelemetry.Default,
167 + Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOs.Default, TerminalUILive)
168 +) satisfies RequiredLayer;
169 +
170 const layers = Layer.mergeAll(
171 CliConfigLive.pipe(Layer.provide(LogLevelFromConfigLive)),
172 NodeOs.Default,
@@ -174,6 +192,10 @@ const layers = Layer.mergeAll(
192 FetchHttpClient.layer,
193 StdinLive,
194 TerminalUILive,
195 + BackendMismatchWarningLive,
196 + UpdateNoticeLive,
197 + PluginHintLive,
198 + CommandLifecycleTelemetryLive,
199 Layer.merge(
200 Logger.layer([withoutClientNotices(Logger.consolePretty())]),
201 Layer.succeed(Logger.LogToStderr, true)
@@ -259,22 +281,15 @@ const runWithTelemetry = (argv: ReadonlyArray<string>) =>
281 commandTelemetryContext.commandPath === 'run' && commandTelemetryContext.runId
282 ? { runId: commandTelemetryContext.runId }
283 : {};
262 - return yield* trackCliEventEffect(
263 - getPrimaryLifecycleInvokedEvent(commandTelemetryContext)
264 - ).pipe(
284 + const telemetry = yield* CommandLifecycleTelemetry;
285 + return yield* telemetry.invoked(commandTelemetryContext).pipe(
286 Effect.andThen(runWithArgs(argv, bootstrap)),
287 Effect.scoped,
288 Effect.mapError(error =>
289 CliError.isCliError(error) ? error : mapOnlyComposioOverrideError({ error })
290 ),
270 - Effect.tap(() =>
271 - trackCliEventEffect(getPrimaryLifecycleSucceededEvent(commandTelemetryContext))
272 - ),
273 - Effect.tapCause(cause =>
274 - trackCliEventEffect(
275 - getPrimaryLifecycleFailedEvent(commandTelemetryContext, Cause.squash(cause))
276 - )
277 - )
291 + Effect.tap(() => telemetry.succeeded(commandTelemetryContext)),
292 + Effect.tapCause(cause => telemetry.failed(commandTelemetryContext, cause))
293 );
294 });
295
@@ -286,30 +301,19 @@ export type CliBootstrapOptions = {
301 readonly argv: ReadonlyArray<string>;
302 };
303
289 -/** Writes `message` to stderr: as a decorated warning on a terminal, as plain text otherwise. */
290 -const warn = (message: string) =>
304 +/** Runs the hooks every invocation gets before its command, in order, on stderr. */
305 +const runInvocationHooks = (invocation: HookInvocation) =>
306 Effect.gen(function* () {
292 - const ui = yield* TerminalUI;
293 - if ((yield* ui.capabilities).canDecorate) {
294 - yield* ui.log.warn(message);
295 - } else {
296 - yield* ui.error(`Warning: ${message}`);
297 - }
307 + const backendMismatchWarning = yield* BackendMismatchWarning;
308 + const updateNotice = yield* UpdateNotice;
309 + const pluginHint = yield* PluginHint;
310 + yield* backendMismatchWarning.run(invocation);
311 + yield* updateNotice.run(invocation);
312 + yield* pluginHint.run(invocation);
313 });
314
300 -/** Warns, before any request, when an env var sends the stored key to another backend. */
301 -const warnOnBackendMismatch = Effect.gen(function* () {
302 - const ctx = yield* ComposioUserContext;
303 - yield* Option.match(ctx.backendMismatch, {
304 - onNone: () => Effect.void,
305 - onSome: mismatch => warn(formatBackendMismatch(mismatch)),
306 - });
307 -});
308 -
315 const cliProgram = (argv: ReadonlyArray<string>) =>
310 - warnOnBackendMismatch.pipe(
311 - Effect.andThen(showUpdateNotice(argv)),
312 - Effect.andThen(showPluginAcquisitionHint(argv)),
316 + runInvocationHooks({ argv }).pipe(
317 Effect.andThen(runWithTelemetry(argv)),
318 // A usage mistake, a missing setup or login, or a failure a remote service reported clearly
319 // (see `ExpectedFailure`) is not a broken invariant: print the message and exit 1 instead of
ts/packages/cli/src/effects/capture-services.ts new
+10
@@ -0,0 +1,10 @@
1 +import { Context, Effect } from 'effect';
2 +
3 +/**
4 + * Captures the given services from the current context, for a layer whose methods provide them
5 + * later. Only those services: providing the whole context would also replace the caller's
6 + * `ConfigProvider`.
7 + */
8 +export const captureServices = <const S extends ReadonlyArray<Context.Key<unknown, unknown>>>(
9 + ...services: S
10 +) => Effect.map(Effect.context<Context.Service.Identifier<S[number]>>(), Context.pick(...services));
ts/packages/cli/src/services/backend-mismatch-warning.ts new
+48
@@ -0,0 +1,48 @@
1 +import { Context, Effect, Layer, Option } from 'effect';
2 +import { formatBackendMismatch } from 'src/config/backend';
3 +import type { InvocationHookShape } from './invocation-hook';
4 +import { TerminalUI } from './terminal-ui';
5 +import { ComposioUserContext } from './user-context';
6 +
7 +export type BackendMismatchWarningShape = InvocationHookShape;
8 +
9 +/**
10 + * Warns, before any request, when an env var sends the stored key to another backend: as a
11 + * decorated warning on a terminal, as a plain `Warning:` line on a redirected stderr.
12 + */
13 +export class BackendMismatchWarning extends Context.Service<
14 + BackendMismatchWarning,
15 + BackendMismatchWarningShape
16 +>()('services/BackendMismatchWarning') {
17 + static readonly Default: Layer.Layer<
18 + BackendMismatchWarning,
19 + never,
20 + ComposioUserContext | TerminalUI
21 + > = Layer.effect(
22 + BackendMismatchWarning,
23 + Effect.gen(function* () {
24 + const ctx = yield* ComposioUserContext;
25 + const ui = yield* TerminalUI;
26 +
27 + const warn = (message: string) =>
28 + Effect.gen(function* () {
29 + if ((yield* ui.capabilities).canDecorate) {
30 + yield* ui.log.warn(message);
31 + } else {
32 + yield* ui.error(`Warning: ${message}`);
33 + }
34 + });
35 +
36 + return BackendMismatchWarning.of({
37 + // `backendMismatch` is read per run: it reflects the environment and stored login now.
38 + run: () =>
39 + Effect.suspend(() =>
40 + Option.match(ctx.backendMismatch, {
41 + onNone: () => Effect.void,
42 + onSome: mismatch => warn(formatBackendMismatch(mismatch)),
43 + })
44 + ),
45 + });
46 + })
47 + );
48 +}
ts/packages/cli/src/services/command-lifecycle-telemetry.ts new
+54
@@ -0,0 +1,54 @@
1 +import * as FileSystem from 'effect/FileSystem';
2 +import * as Path from 'effect/Path';
3 +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 + getPrimaryLifecycleFailedEvent,
8 + getPrimaryLifecycleInvokedEvent,
9 + getPrimaryLifecycleSucceededEvent,
10 +} from 'src/analytics/events';
11 +import type { CliCommandTelemetryContext, TrackEvent } from 'src/analytics/types';
12 +import { NodeOs } from './node-os';
13 +import { TerminalUI } from './terminal-ui';
14 +
15 +/**
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.
18 + */
19 +export interface CommandLifecycleTelemetryShape {
20 + readonly invoked: (context: CliCommandTelemetryContext) => Effect.Effect<void>;
21 + readonly succeeded: (context: CliCommandTelemetryContext) => Effect.Effect<void>;
22 + readonly failed: (
23 + context: CliCommandTelemetryContext,
24 + cause: Cause.Cause<unknown>
25 + ) => Effect.Effect<void>;
26 +}
27 +
28 +/**
29 + * Tracks the command's primary lifecycle events (its family's events, or the generic
30 + * `CLI_COMMAND_*` ones) through the analytics dispatcher.
31 + */
32 +export class CommandLifecycleTelemetry extends Context.Service<
33 + CommandLifecycleTelemetry,
34 + CommandLifecycleTelemetryShape
35 +>()('services/CommandLifecycleTelemetry') {
36 + static readonly Default: Layer.Layer<
37 + CommandLifecycleTelemetry,
38 + never,
39 + FileSystem.FileSystem | Path.Path | NodeOs | TerminalUI
40 + > = Layer.effect(
41 + CommandLifecycleTelemetry,
42 + Effect.gen(function* () {
43 + const services = yield* captureServices(FileSystem.FileSystem, Path.Path, NodeOs, TerminalUI);
44 + const track = (event: TrackEvent) =>
45 + trackCliEventEffect(event).pipe(Effect.provideContext(services));
46 + return CommandLifecycleTelemetry.of({
47 + invoked: context => track(getPrimaryLifecycleInvokedEvent(context)),
48 + succeeded: context => track(getPrimaryLifecycleSucceededEvent(context)),
49 + failed: (context, cause) =>
50 + track(getPrimaryLifecycleFailedEvent(context, Cause.squash(cause))),
51 + });
52 + })
53 + );
54 +}
ts/packages/cli/src/services/invocation-hook.ts new
+20
@@ -0,0 +1,20 @@
1 +import type { Effect } from 'effect';
2 +
3 +/**
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.
8 + */
9 +export interface HookInvocation {
10 + /** The full, unchanged process argv (executable and script included). */
11 + readonly argv: ReadonlyArray<string>;
12 +}
13 +
14 +/**
15 + * A hook `cli-main.ts` runs once per invocation, before the command. Its output goes to stderr;
16 + * it fails the invocation only with the errors `E` names.
17 + */
18 +export interface InvocationHookShape<E = never> {
19 + readonly run: (invocation: HookInvocation) => Effect.Effect<void, E>;
20 +}
ts/packages/cli/src/services/plugin-hint.ts
+31 -11
@@ -1,15 +1,16 @@
1 import * as FileSystem from 'effect/FileSystem';
2 import * as Path from 'effect/Path';
3 -import * as BunFileSystem from '@effect/platform-bun/BunFileSystem';
4 -import { Effect, Exit, Layer, Option, Schema } from 'effect';
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';
6 import { APP_CONFIG } from 'src/config';
7 +import { captureServices } from 'src/effects/capture-services';
8 import { setupCacheDir } from 'src/effects/setup-cache-dir';
9 import { APP_VERSION } from 'src/constants';
10 import { AGENT_HOST_LABELS, COMPOSIO_AGENT_PLUGIN_ID, type AgentHost } from './agent-host';
11 import { detectPluginHost, hostConfigDirectory, rawHostEnvironment } from './agent-host-env';
12 import { NodeOs } from './node-os';
13 +import type { InvocationHookShape } from './invocation-hook';
14 import { DEFAULT_CLI_INVOCATION_ORIGIN } from './runtime-cli-context';
15 import { TerminalUI } from './terminal-ui';
16
@@ -145,8 +146,6 @@ export function createPluginHint(config: PluginHintConfig) {
146 return { showPluginHint };
147 }
148
148 -const DefaultConfigLayers = Layer.mergeAll(Path.layer, NodeOs.Default, BunFileSystem.layer);
149 -
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) {
@@ -182,10 +181,31 @@ export const resolvePluginHintConfig = (argv: ReadonlyArray<string>) =>
181 } satisfies PluginHintConfig;
182 });
183
185 -/** Print the plugin acquisition hint when eligible. Never fails, never blocks on network. */
186 -export const showPluginAcquisitionHint = (argv: ReadonlyArray<string>) =>
187 - Effect.gen(function* () {
188 - const terminal = yield* TerminalUI;
189 - const config = yield* resolvePluginHintConfig(argv);
190 - yield* createPluginHint(config).showPluginHint(terminal);
191 - }).pipe(Effect.provide(DefaultConfigLayers));
184 +export type PluginHintShape = InvocationHookShape<Config.ConfigError>;
185 +
186 +/**
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.
189 + */
190 +export class PluginHint extends Context.Service<PluginHint, PluginHintShape>()(
191 + 'services/PluginHint'
192 +) {
193 + static readonly Default: Layer.Layer<
194 + PluginHint,
195 + never,
196 + TerminalUI | FileSystem.FileSystem | Path.Path | NodeOs
197 + > = Layer.effect(
198 + PluginHint,
199 + Effect.gen(function* () {
200 + const terminal = yield* TerminalUI;
201 + const services = yield* captureServices(FileSystem.FileSystem, Path.Path, NodeOs, TerminalUI);
202 + return PluginHint.of({
203 + run: ({ argv }) =>
204 + Effect.gen(function* () {
205 + const config = yield* resolvePluginHintConfig(argv);
206 + yield* createPluginHint(config).showPluginHint(terminal);
207 + }).pipe(Effect.provideContext(services)),
208 + });
209 + })
210 + );
211 +}
ts/packages/cli/src/services/update-check.ts
+37 -11
@@ -1,12 +1,14 @@
1 import * as FileSystem from 'effect/FileSystem';
2 import * as Path from 'effect/Path';
3 import * as BunFileSystem from '@effect/platform-bun/BunFileSystem';
4 -import { Data, Effect, Layer, Option, Predicate, Schema } from 'effect';
4 +import { Context, Data, Effect, Layer, Option, Predicate, Schema } from 'effect';
5 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';
10 import { APP_VERSION } from '../constants';
11 +import type { InvocationHookShape } from './invocation-hook';
12 import { NodeOs, type NodeOsShape } from './node-os';
13 import { resolveRunningCliVersion } from './run-companion-modules';
14 import { TerminalUI } from './terminal-ui';
@@ -17,7 +19,7 @@ import { TerminalUI } from './terminal-ui';
19 * Two entry points, both called from cli-main BEFORE the root command's
20 * Effect runtime boots — they must never block or throw:
21 *
20 - * showUpdateNotice — reads a tiny cached JSON file (~1 ms)
22 + * UpdateNotice — reads a tiny cached JSON file (~1 ms)
23 * checkForUpdateInBackground() — fire-and-forget fetch, no await
24 *
25 * Strategy:
@@ -348,15 +350,39 @@ export function createUpdateChecker(config: UpdateCheckConfig) {
350
351 const DefaultConfigLayers = Layer.mergeAll(Path.layer, NodeOs.Default, BunFileSystem.layer);
352
351 -/** Print upgrade hint to stderr if a newer version is cached, unless argv runs `composio upgrade`. */
352 -export const showUpdateNotice = (argv: ReadonlyArray<string>) =>
353 - Effect.gen(function* () {
354 - const terminal = yield* TerminalUI;
355 - const stateFile = yield* defaultStateFile;
356 - const config = yield* defaultConfig(stateFile);
357 - const args = argv.slice(2);
358 - yield* createUpdateChecker(config).showUpdateNotice(terminal, args[rootCommandIndex(args)]);
359 - }).pipe(Effect.provide(DefaultConfigLayers));
353 +export type UpdateNoticeShape = InvocationHookShape;
354 +
355 +/**
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.
358 + */
359 +export class UpdateNotice extends Context.Service<UpdateNotice, UpdateNoticeShape>()(
360 + 'services/UpdateNotice'
361 +) {
362 + static readonly Default: Layer.Layer<
363 + UpdateNotice,
364 + never,
365 + TerminalUI | FileSystem.FileSystem | Path.Path | NodeOs
366 + > = Layer.effect(
367 + UpdateNotice,
368 + Effect.gen(function* () {
369 + const terminal = yield* TerminalUI;
370 + const services = yield* captureServices(FileSystem.FileSystem, Path.Path, NodeOs);
371 + return UpdateNotice.of({
372 + run: ({ argv }) =>
373 + Effect.gen(function* () {
374 + const stateFile = yield* defaultStateFile;
375 + const config = yield* defaultConfig(stateFile);
376 + const args = argv.slice(2);
377 + yield* createUpdateChecker(config).showUpdateNotice(
378 + terminal,
379 + args[rootCommandIndex(args)]
380 + );
381 + }).pipe(Effect.provideContext(services)),
382 + });
383 + })
384 + );
385 +}
386
387 /**
388 * Record a live-resolved latest stable release (e.g. `@composio/cli@0.5.0`) as the cached update
ts/packages/cli/test/__utils__/index.ts
+6
@@ -6,6 +6,12 @@ export { TestLayer as TestLive } from './services/test-layer';
6 export { ToolkitsTest } from './layers/toolkits';
7 export { ConnectedAccountsTest } from './layers/connected-accounts';
8 export { CommandRunnerTest } from './layers/command-runner';
9 +export {
10 + InvocationHooksTest,
11 + InvocationRecorder,
12 + recordedInvocationCalls,
13 + type RecordedInvocationCall,
14 +} from './layers/invocation-hooks';
15 export { SetupTest } from './layers/setup';
16 export {
17 DashboardToolExecutionTest,
ts/packages/cli/test/__utils__/layers/invocation-hooks.ts new
+77
@@ -0,0 +1,77 @@
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';
5 +import type { HookInvocation } from 'src/services/invocation-hook';
6 +import { PluginHint } from 'src/services/plugin-hint';
7 +import { UpdateNotice } from 'src/services/update-check';
8 +
9 +/** One call to an invocation hook or to the lifecycle telemetry sink, in call order. */
10 +export type RecordedInvocationCall =
11 + | {
12 + readonly service: 'BackendMismatchWarning' | 'UpdateNotice' | 'PluginHint';
13 + readonly invocation: HookInvocation;
14 + }
15 + | {
16 + readonly service: 'CommandLifecycleTelemetry';
17 + readonly event: 'invoked' | 'succeeded';
18 + readonly context: CliCommandTelemetryContext;
19 + }
20 + | {
21 + readonly service: 'CommandLifecycleTelemetry';
22 + readonly event: 'failed';
23 + readonly context: CliCommandTelemetryContext;
24 + readonly cause: Cause.Cause<unknown>;
25 + };
26 +
27 +/** Reads what the recording doubles of `InvocationHooksTest` were called with. */
28 +export class InvocationRecorder extends Context.Service<
29 + InvocationRecorder,
30 + { readonly calls: Effect.Effect<ReadonlyArray<RecordedInvocationCall>> }
31 +>()('test/InvocationRecorder') {}
32 +
33 +/** Every call the recording doubles received so far, oldest first. */
34 +export const recordedInvocationCalls = Effect.gen(function* () {
35 + const recorder = yield* InvocationRecorder;
36 + return yield* recorder.calls;
37 +});
38 +
39 +/**
40 + * Recording no-op doubles for the invocation hooks and the lifecycle telemetry sink: they print
41 + * nothing and track nothing, so a test's stderr and analytics stay its command's own, and
42 + * `InvocationRecorder` exposes what they were called with.
43 + */
44 +export const InvocationHooksTest = Layer.unwrap(
45 + Effect.gen(function* () {
46 + const calls = yield* Ref.make<ReadonlyArray<RecordedInvocationCall>>([]);
47 + const record = (call: RecordedInvocationCall) => Ref.update(calls, all => [...all, call]);
48 + return Layer.mergeAll(
49 + Layer.succeed(InvocationRecorder, InvocationRecorder.of({ calls: Ref.get(calls) })),
50 + Layer.succeed(
51 + BackendMismatchWarning,
52 + BackendMismatchWarning.of({
53 + run: invocation => record({ service: 'BackendMismatchWarning', invocation }),
54 + })
55 + ),
56 + Layer.succeed(
57 + UpdateNotice,
58 + UpdateNotice.of({ run: invocation => record({ service: 'UpdateNotice', invocation }) })
59 + ),
60 + Layer.succeed(
61 + PluginHint,
62 + PluginHint.of({ run: invocation => record({ service: 'PluginHint', invocation }) })
63 + ),
64 + Layer.succeed(
65 + CommandLifecycleTelemetry,
66 + CommandLifecycleTelemetry.of({
67 + invoked: context =>
68 + record({ service: 'CommandLifecycleTelemetry', event: 'invoked', context }),
69 + succeeded: context =>
70 + record({ service: 'CommandLifecycleTelemetry', event: 'succeeded', context }),
71 + failed: (context, cause) =>
72 + record({ service: 'CommandLifecycleTelemetry', event: 'failed', context, cause }),
73 + })
74 + )
75 + );
76 + })
77 +);
ts/packages/cli/test/__utils__/services/test-layer.ts
+4
@@ -83,6 +83,7 @@ import { notFoundError } from '../layers/not-found';
83 import { DEFAULT_PAGE_LIMIT } from '../layers/page';
84 import { CommandRunnerTest } from '../layers/command-runner';
85 import { SetupSkillInstallerTest } from '../layers/setup';
86 +import { InvocationHooksTest } from '../layers/invocation-hooks';
87 import {
88 resolveToolkitsTestData,
89 toolkitCatalogMethods,
@@ -912,6 +913,9 @@ export const TestLayer = (input?: TestLiveInput) =>
913 FetchHttpClient.layer,
914 StdinTest,
915 TerminalUILayer,
916 + // Recording no-op doubles of the hooks and telemetry sink `cli-main.ts` runs around a
917 + // command; read their calls with `recordedInvocationCalls`.
918 + InvocationHooksTest,
919 // `src/commands/index.ts` provides these for real invocations; direct-effect tests that
920 // never route through the root command still need the "no CLI flag override" default.
921 cliDebugFlagsLayer(),
ts/packages/cli/test/src/services/backend-mismatch-warning.test.ts new
+95
@@ -0,0 +1,95 @@
1 +import { describe, expect, it } from '@effect/vitest';
2 +import { Effect, Layer, Option } from 'effect';
3 +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 { terminalUITestImpl } from 'test/__utils__/services/terminal-ui-test';
8 +
9 +const MISMATCH: BackendMismatch = {
10 + variable: 'COMPOSIO_BASE_URL',
11 + issuedBy: 'https://backend.composio.dev',
12 + selected: 'https://staging.composio.dev',
13 +};
14 +
15 +const MESSAGE =
16 + 'COMPOSIO_BASE_URL sends your stored API key to https://staging.composio.dev, but it was issued by https://backend.composio.dev. ' +
17 + 'Unset COMPOSIO_BASE_URL to use the backend you logged in to, or run `composio logout && composio login` to log in to https://staging.composio.dev instead.';
18 +
19 +const userContext = (backendMismatch: Option.Option<BackendMismatch>) =>
20 + Layer.succeed(
21 + ComposioUserContext,
22 + ComposioUserContext.of({
23 + data: {
24 + apiKey: Option.some('uak_test'),
25 + baseURL: 'https://staging.composio.dev',
26 + webURL: 'https://platform.composio.dev',
27 + orgId: Option.none(),
28 + projectId: Option.none(),
29 + testUserId: Option.none(),
30 + },
31 + backendMismatch,
32 + isLoggedIn: () => true,
33 + logout: Effect.void,
34 + login: () => Effect.void,
35 + update: () => Effect.void,
36 + })
37 + );
38 +
39 +/** A terminal whose stderr is (or is not) a TTY, recording warnings and plain stderr lines. */
40 +const recordingTerminal = (stderrIsTTY: boolean) => {
41 + const written: Array<{ readonly via: 'log.warn' | 'error'; readonly text: string }> = [];
42 + const layer = Layer.succeed(
43 + TerminalUI,
44 + TerminalUI.of({
45 + ...terminalUITestImpl,
46 + capabilities: Effect.succeed(
47 + getTerminalCapabilities({
48 + stdin: { isTTY: false },
49 + stdout: { isTTY: false },
50 + stderr: { isTTY: stderrIsTTY },
51 + })
52 + ),
53 + error: text => Effect.sync(() => void written.push({ via: 'error', text })),
54 + log: {
55 + ...terminalUITestImpl.log,
56 + warn: text => Effect.sync(() => void written.push({ via: 'log.warn', text })),
57 + },
58 + })
59 + );
60 + return { layer, written };
61 +};
62 +
63 +const cases = [Option.none<BackendMismatch>(), Option.some(MISMATCH)].flatMap(backendMismatch =>
64 + [true, false].map(stderrIsTTY => ({
65 + backendMismatch,
66 + situation: Option.isNone(backendMismatch) ? 'no mismatch' : 'a mismatch',
67 + stderrIsTTY,
68 + expected: Option.isNone(backendMismatch)
69 + ? []
70 + : stderrIsTTY
71 + ? [{ via: 'log.warn', text: MESSAGE }]
72 + : [{ via: 'error', text: `Warning: ${MESSAGE}` }],
73 + }))
74 +);
75 +
76 +describe('BackendMismatchWarning', () => {
77 + it.effect.each(cases)(
78 + '[Given] $situation, stderr TTY $stderrIsTTY [Then] warns only on a mismatch, in the form stderr supports',
79 + ({ backendMismatch, stderrIsTTY, expected }) => {
80 + const terminal = recordingTerminal(stderrIsTTY);
81 + return Effect.gen(function* () {
82 + const warning = yield* BackendMismatchWarning;
83 + yield* warning.run({ argv: ['bun', 'composio', 'whoami'] });
84 + expect(terminal.written).toEqual(expected);
85 + }).pipe(
86 + Effect.provide(
87 + Layer.provide(
88 + BackendMismatchWarning.Default,
89 + Layer.mergeAll(userContext(backendMismatch), terminal.layer)
90 + )
91 + )
92 + );
93 + }
94 + );
95 +});
ts/packages/cli/test/src/services/command-lifecycle-telemetry.test.ts new
+97
@@ -0,0 +1,97 @@
1 +import { describe, expect, it } from '@effect/vitest';
2 +import { afterEach, vi } from 'vitest';
3 +import * as BunFileSystem from '@effect/platform-bun/BunFileSystem';
4 +import * as BunPath from '@effect/platform-bun/BunPath';
5 +import { Cause, Effect, Layer } from 'effect';
6 +import { createCliCommandTelemetryContext } from 'src/analytics/events';
7 +import { ChildProcessExited } from 'src/effects/child-process-exited';
8 +import {
9 + CommandLifecycleTelemetry,
10 + type CommandLifecycleTelemetryShape,
11 +} from 'src/services/command-lifecycle-telemetry';
12 +import { NodeOs } from 'src/services/node-os';
13 +import { TerminalUITest } from 'test/__utils__/services/terminal-ui-test';
14 +import { trackedEvents } from 'test/__utils__/tracked-events';
15 +
16 +vi.mock('src/analytics/dispatch', async importOriginal => {
17 + const { recordTrackedEvent } = await import('test/__utils__/tracked-events');
18 + return {
19 + ...(await importOriginal<typeof import('src/analytics/dispatch')>()),
20 + trackCliEventEffect: recordTrackedEvent,
21 + };
22 +});
23 +
24 +afterEach(() => {
25 + trackedEvents.length = 0;
26 +});
27 +
28 +const TelemetryLive = Layer.provide(
29 + CommandLifecycleTelemetry.Default,
30 + Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOs.Default, TerminalUITest)
31 +);
32 +
33 +const contextFor = (args: ReadonlyArray<string>) =>
34 + createCliCommandTelemetryContext(
35 + ['/bin/bun', '/cli/bin.ts', ...args],
36 + '1.2.3',
37 + { stdoutIsTTY: false, stderrIsTTY: false },
38 + { invocationOrigin: 'cli', parentRunId: undefined }
39 + );
40 +
41 +const report = (
42 + telemetry: CommandLifecycleTelemetryShape,
43 + outcome: 'invoked' | 'succeeded' | 'failed',
44 + args: ReadonlyArray<string>
45 +) => {
46 + const context = contextFor(args);
47 + switch (outcome) {
48 + case 'invoked':
49 + return telemetry.invoked(context);
50 + case 'succeeded':
51 + return telemetry.succeeded(context);
52 + case 'failed':
53 + return telemetry.failed(context, Cause.fail(new TypeError('boom')));
54 + }
55 +};
56 +
57 +const cases = [
58 + { args: ['whoami'], family: 'CLI_COMMAND' },
59 + { args: ['execute', 'GITHUB_GET_THE_AUTHENTICATED_USER'], family: 'CLI_EXECUTE' },
60 +].flatMap(({ args, family }) =>
61 + (['invoked', 'succeeded', 'failed'] as const).map(outcome => ({
62 + args,
63 + command: args[0],
64 + outcome,
65 + event: `${family}_${outcome.toUpperCase()}`,
66 + }))
67 +);
68 +
69 +describe('CommandLifecycleTelemetry', () => {
70 + it.effect.each(cases)(
71 + '[Given] `composio $command` $outcome [Then] tracks $event',
72 + ({ args, outcome, event }) =>
73 + Effect.gen(function* () {
74 + const telemetry = yield* CommandLifecycleTelemetry;
75 + yield* report(telemetry, outcome, args);
76 + expect(trackedEvents.map(tracked => tracked.name)).toEqual([event]);
77 + }).pipe(Effect.provide(TelemetryLive))
78 + );
79 +
80 + it.effect('[Given] a failure cause [Then] tracks the squashed error', () =>
81 + Effect.gen(function* () {
82 + const telemetry = yield* CommandLifecycleTelemetry;
83 + yield* telemetry.failed(
84 + contextFor(['run', 'script.ts']),
85 + Cause.fail(new ChildProcessExited({ code: 3 }))
86 + );
87 + expect(trackedEvents).toEqual([
88 + {
89 + name: 'CLI_RUN_FAILED',
90 + properties: expect.objectContaining({
91 + failure_reason_code: 'child_exit',
92 + }),
93 + },
94 + ]);
95 + }).pipe(Effect.provide(TelemetryLive))
96 + );
97 +});
ts/packages/cli/test/src/services/invocation-hooks-test-layer.test.ts new
+56
@@ -0,0 +1,56 @@
1 +import { describe, expect, layer } from '@effect/vitest';
2 +import { vi } from 'vitest';
3 +import { Cause, Effect } from 'effect';
4 +import { createCliCommandTelemetryContext } from 'src/analytics/events';
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';
9 +import { MockConsole, recordedInvocationCalls, TestLive } from 'test/__utils__';
10 +import { trackedEvents } from 'test/__utils__/tracked-events';
11 +
12 +// Records instead of dispatching, so a double that reached the real sink would show up below.
13 +vi.mock('src/analytics/dispatch', async importOriginal => {
14 + const { recordTrackedEvent } = await import('test/__utils__/tracked-events');
15 + return {
16 + ...(await importOriginal<typeof import('src/analytics/dispatch')>()),
17 + trackCliEventEffect: recordTrackedEvent,
18 + };
19 +});
20 +
21 +describe('TestLive invocation hooks and telemetry sink', () => {
22 + layer(TestLive())(it => {
23 + it.effect('[Given] every hook and lifecycle event [Then] records each call, in order', () =>
24 + Effect.gen(function* () {
25 + const invocation = { argv: ['/bin/bun', '/cli/bin.ts', 'whoami'] };
26 + const context = createCliCommandTelemetryContext(
27 + invocation.argv,
28 + '1.2.3',
29 + { stdoutIsTTY: false, stderrIsTTY: false },
30 + { invocationOrigin: 'cli', parentRunId: undefined }
31 + );
32 + const cause = Cause.fail(new TypeError('boom'));
33 +
34 + yield* (yield* BackendMismatchWarning).run(invocation);
35 + yield* (yield* UpdateNotice).run(invocation);
36 + yield* (yield* PluginHint).run(invocation);
37 + const telemetry = yield* CommandLifecycleTelemetry;
38 + yield* telemetry.invoked(context);
39 + yield* telemetry.succeeded(context);
40 + yield* telemetry.failed(context, cause);
41 +
42 + expect(yield* recordedInvocationCalls).toEqual([
43 + { service: 'BackendMismatchWarning', invocation },
44 + { service: 'UpdateNotice', invocation },
45 + { service: 'PluginHint', invocation },
46 + { service: 'CommandLifecycleTelemetry', event: 'invoked', context },
47 + { service: 'CommandLifecycleTelemetry', event: 'succeeded', context },
48 + { service: 'CommandLifecycleTelemetry', event: 'failed', context, cause },
49 + ]);
50 + // The doubles are no-ops: nothing reaches the console or the analytics dispatcher.
51 + expect(yield* MockConsole.getLines()).toEqual([]);
52 + expect(trackedEvents).toEqual([]);
53 + })
54 + );
55 + });
56 +});
ts/packages/cli/test/src/services/plugin-hint.test.ts
+53
@@ -14,6 +14,7 @@ import { detectPluginHost } from 'src/services/agent-host-env';
14 import {
15 createPluginHint,
16 findRootCommandName,
17 + PluginHint,
18 resolvePluginHintConfig,
19 type PluginHintConfig,
20 } from 'src/services/plugin-hint';
@@ -366,3 +367,55 @@ describe('showPluginHint', () => {
367 }).pipe(Effect.provide(hintLayers()))
368 );
369 });
370 +
371 +describe('PluginHint', () => {
372 + /** `PluginHint.Default` with every path under `tempDir` and a recording stderr. */
373 + const pluginHintLayer = (output: string[]) =>
374 + Layer.provide(
375 + 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 + )
381 + );
382 +
383 + /** Runs under Claude Code, which has no Composio plugin installed. */
384 + const underClaudeCode = Effect.provideService(
385 + ConfigProvider.ConfigProvider,
386 + ConfigProvider.fromEnvRecord({ CLAUDECODE: '1' })
387 + );
388 +
389 + it.effect(
390 + '[Given] Claude Code without the plugin [Then] prints and tracks the hint once per interval',
391 + () => {
392 + const output: string[] = [];
393 + return Effect.gen(function* () {
394 + 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'] });
397 +
398 + expect(output).toEqual([
399 + "Tip: running under Claude Code without the Composio plugin — 'composio setup --yes' installs it.",
400 + ]);
401 + expect(trackedEvents).toEqual([
402 + {
403 + name: 'CLI_PLUGIN_HINT_SHOWN',
404 + properties: expect.objectContaining({ command_path: 'whoami', agent_host: 'claude' }),
405 + },
406 + ]);
407 + }).pipe(underClaudeCode, Effect.provide(pluginHintLayer(output)));
408 + }
409 + );
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 + });
421 +});
ts/packages/cli/test/src/services/update-check.test.ts
+48 -1
@@ -6,9 +6,12 @@ import * as BunFileSystem from '@effect/platform-bun/BunFileSystem';
6 import * as BunPath from '@effect/platform-bun/BunPath';
7 import { Effect, Fiber, Layer } from 'effect';
8 import { withHttpServerEffect } from 'test/__utils__/http-server';
9 -import { getTerminalCapabilities, type TerminalUI } from 'src/services/terminal-ui';
9 +import { defaultNodeOs, NodeOs } from 'src/services/node-os';
10 +import { getTerminalCapabilities, TerminalUI } from 'src/services/terminal-ui';
11 +import { terminalUITestImpl } from 'test/__utils__/services/terminal-ui-test';
12 import {
13 createUpdateChecker,
14 + UpdateNotice,
15 parseLatestVersionFromReleases,
16 type UpdateCheckConfig,
17 type UpdateCheckState,
@@ -300,6 +303,50 @@ describe('showUpdateNotice', () => {
303 );
304 });
305
306 +// ── UpdateNotice (the service cli-main runs) ────────────────────────────
307 +
308 +describe('UpdateNotice', () => {
309 + /** `UpdateNotice.Default` over a home directory in `tempDir` and a recording, decorating stderr. */
310 + const noticeLayer = (output: string[]) =>
311 + Layer.provide(
312 + UpdateNotice.Default,
313 + Layer.mergeAll(
314 + PlatformLayers,
315 + Layer.succeed(NodeOs, defaultNodeOs({ homedir: tempDir })),
316 + Layer.succeed(TerminalUI, TerminalUI.of({ ...terminalUITestImpl, ...makeTerminal(output) }))
317 + )
318 + );
319 +
320 + // `makeConfig()`'s state file is where the service looks under that home directory.
321 + const writeCachedLatest = (latestVersion: string) =>
322 + writeState(makeConfig(), { lastChecked: new Date().toISOString(), latestVersion });
323 +
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 + );
339 +
340 + it.effect('[Given] no cached release [Then] prints nothing', () => {
341 + const output: string[] = [];
342 + return Effect.gen(function* () {
343 + const notice = yield* UpdateNotice;
344 + yield* notice.run({ argv: ['/bin/bun', '/cli/bin.ts', 'tools'] });
345 + expect(output).toEqual([]);
346 + }).pipe(Effect.provide(noticeLayer(output)));
347 + });
348 +});
349 +
350 // ── getUpdateStatus ─────────────────────────────────────────────────────
351
352 describe('getUpdateStatus', () => {