@devries-cameron20 / composio-1 / commits / c3e7f264d
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.

fix(cli): generate help and parse flags through Effect (#4725)

This PR: - generates nested help from the actual command tree: `dev connected-accounts link --help` now documents `--auth-config` and `--user-id`, and `login`, `search`, and `listen` expose their real flags. - moves examples into `Command.withExamples`, derives `help <command>` aliases from the same tree, and removes the curated pages, help levels, prefix matching, and nonexistent `files` topic. - registers diagnostics as hidden commands and debug switches as hidden global settings, preserving bare version output and keeping parser errors on stderr. - routes parallel execution through the framework before handling tool/data groups and parses `run` script operands through native `--` and `Argument.variadic`. Two small syntax normalizers preserve bare `listen --stream` and undelimited scripts; the separate script-argument service is removed. - identifies commands after leading shared flags for telemetry and shares the minted run ID with child scripts. Process tests confirm help/version emit success events and invalid help emits failure events. - scopes `--dangerously-allow` to `dev triggers disable` and returns failures when developer commands are disabled or destructive-command acknowledgement is missing. - breaking: replaces `--install-skill` and its typo alias with `composio setup skill <claude|codex|openclaw> [--name skill-name]`; removes help verbosity levels. Documentation and the CLI changelog include the migration. `execute <slug> --help` now shows command options; use `execute <slug> --get-schema` for the tool input schema JSON, as the generated examples and guide explain. ## How Has This Been Tested? - CLI suite: **1,434 passed, 1 skipped** across 131 test files, with CLI skill and lint-boundary validators. Ran the package-local Vitest executable to use the same Vitest instance as `@effect/vitest`. - `pnpm typecheck`: all 14 workspace tasks passed. CLI module and native binary rebuilt with `pnpm --filter @composio/cli build` and `pnpm --filter @composio/cli build:binary` after building workspace dependencies. - Rebuilt binary: **196 process invocations and 136 assertions** with isolated configuration and no credentials. Compared help and aliases across all **77 command paths**, captured before/after help, and checked native flags, version aliases, diagnostic refusals, developer/destructive-command exit codes, skill-target validation, parallel help, inline/file argument forwarding, and child exit status 7. - Cleanup compatibility: all 77 help snapshots are unchanged; a differential check verified equivalent argument handling and idempotent normalization for 150 invocations. Script flag forwarding passed with delimiters before or after inline source and without a delimiter. - CLI lint and repository agent-skills/skill-routing validators passed. Lint retains existing warnings, including an unused import in `src/effects/app-config.ts`. - Updated documentation routing tests passed (2 tests). The broader docs routing suite encountered 3 unrelated failures from generated Fumadocs code importing missing `content/kb/guide/toolkits-strava.mdx`. ## Type of change - [x] Bug fix - [x] Refactor/Chore - [x] Documentation - [x] Breaking change ## Checklist - [x] Ran relevant local tests and validators; limitations are documented above - [x] Updated documentation and added regressions for changed public behavior - [x] Updated the CLI changelog; no Changeset because the CLI is excluded from Changesets - [ ] Author has reviewed the full diff Merged the current `next` and retained both CLI changelog entries. The no-retry execute/proxy changes are preserved.

Alberto Schiabel committed Oct 6, 2026 at 02:27 UTC c3e7f264d63d1a0ab8f530db5566d4011847266a
49 files changed +1236 -3519
docs/content/docs/agent-plugins.mdx
+2 -2
@@ -82,8 +82,8 @@ The plugin includes a Composio CLI skill that teaches your agent how to search f
82 If you want the skill without the plugin, install it for your agent directly:
83
84 ```bash
85 -composio --install-skill composio-cli claude
86 -composio --install-skill composio-cli codex
85 +composio setup skill claude
86 +composio setup skill codex
87 ```
88
89 ## Choose another setup
docs/content/docs/cli.mdx
+9 -6
@@ -43,8 +43,8 @@ Setup asks before changing local files. Add `--yes` when you run it from an agen
43 If you explicitly need the standalone skill without the native plugin, install it manually for the agent host:
44
45 ```bash
46 -composio --install-skill composio-cli claude
47 -composio --install-skill composio-cli codex
46 +composio setup skill claude
47 +composio setup skill codex
48 ```
49
50 ### Install with options
@@ -240,6 +240,9 @@ composio execute GMAIL_FETCH_EMAILS \
240 -d '{ query: "is:unread newer_than:1d", max_results: 10 }'
241 ```
242
243 +Use `composio execute <slug> --get-schema` to print the tool's input schema as JSON.
244 +`composio execute <slug> --help` now shows command options and examples.
245 +
246 The commands you'll reach for most:
247
248 | Command | Use it for |
@@ -446,8 +449,8 @@ Use `--help` on the root command or any subcommand:
449
450 ```bash
451 composio --help
449 -composio --help full
450 -composio execute --help full
451 -composio run --help full
452 -composio dev --help full
452 +composio help
453 +composio execute --help
454 +composio run --help
455 +composio dev projects switch --help
456 ```
docs/tests/static/start-routing.test.ts
+2 -2
@@ -35,8 +35,8 @@ describe('getting-started routing policy', () => {
35 expect(plugins).toContain('composio search');
36 expect(plugins).toContain('composio link');
37 expect(plugins).toContain('composio execute');
38 - expect(plugins).toContain('composio --install-skill composio-cli claude');
39 - expect(plugins).toContain('composio --install-skill composio-cli codex');
38 + expect(plugins).toContain('composio setup skill claude');
39 + expect(plugins).toContain('composio setup skill codex');
40 expect(plugins).toContain('composio setup --target auto --yes');
41 expect(plugins).toContain('### Codex');
42 expect(plugins).toContain('### Claude Code');
ts/packages/cli/AGENTS.md
+4 -4
@@ -14,16 +14,16 @@ The CLI is built on the **Effect.ts ecosystem** and runs on **Bun**. Service-ori
14
15 ### Entry Point — `src/bin.ts` / `src/cli-main.ts`
16
17 -`bin.ts` is a thin bootstrap: it strips the internal `--telemetry-debug` flag, routes background-worker invocations (analytics dispatch) through a minimal layer set, and otherwise dynamically imports `cli-main.ts`, which composes the full Effect layer stack and drives the root command through `effect/unstable/cli`'s `Command.runWith`, run via `BunRuntime.runMain()`. Key layers (see `cli-main.ts` for the complete list):
17 +`bin.ts` is a thin bootstrap: it routes background-worker invocations (analytics dispatch) through a minimal layer set and otherwise passes argv unchanged to the dynamically imported `cli-main.ts`, which composes the full Effect layer stack and drives the root command through `effect/unstable/cli`'s `Command.runWith`, run via `BunRuntime.runMain()`. Key layers (see `cli-main.ts` for the complete list):
18
19 -- `CliConfigLive` — `effect/unstable/cli` `CliConfig` restricted to `builtIns: [GlobalFlag.Help]` (see Configuration below); the only `CliConfig` customization Composio makes — no custom `CliOutput.Formatter` is provided, so `Command.runWith` renders help and parse errors with v4's own defaults
19 +- `CliConfigLive` — `effect/unstable/cli` `CliConfig` restricted to `builtIns: [Help, GlobalFlag.Version]` (see Configuration below); a small `CliOutput.Formatter` keeps versions bare and appends a short root overview; Effect generates command help and parse errors
20 - `ComposioUserContextLive` — User authentication state from `~/.composio/`
21 - `ComposioSessionRepositoryLive` — OAuth2 session management
22 - `ComposioToolkitsRepositoryCachedLive` — Cached API client for toolkits/tools
23 - `UpgradeBinaryLive` — Self-update from GitHub releases
24 - `BunFileSystem.layer`, `BunPath.layer`, `BunServices.layer`, `FetchHttpClient.layer` — Bun runtime integration (`@effect/platform-bun`'s `BunContext` no longer exists in v4; `BunServices.layer` is the aggregate replacement)
25
26 -`Command.runWith` renders help text and parse/validation errors itself (to the right stream) before re-failing with `CliError.ShowHelp`, which carries `[Runtime.errorReported] = false` (suppresses `runMain`'s automatic error log) and `[Runtime.errorExitCode]` (0 for a bare `--help`, 1 alongside parse errors). `cli-main.ts`'s sandboxed catch-all re-fails `ShowHelp` with its original `Cause` via `Effect.failCause` instead of swallowing it, and its custom `teardown` reads `Runtime.getErrorExitCode` off the squashed failure — so this module never prints for `ShowHelp`, it just lets the error's own contract drive `runMain`. See the module docstring at the top of `cli-main.ts` for the full rationale (argv-prefix contract with `src/commands/index.ts` included).
26 +Explicit help and version actions complete successfully. `Command.runWith` renders parse/validation errors and contextual help itself before re-failing with `CliError.ShowHelp`, which carries `[Runtime.errorReported] = false` (suppresses `runMain`'s automatic error log) and `[Runtime.errorExitCode]` (1 alongside parse errors). `cli-main.ts`'s sandboxed catch-all re-fails `ShowHelp` with its original `Cause` via `Effect.failCause` instead of swallowing it, and its custom `teardown` reads `Runtime.getErrorExitCode` off the squashed failure. This preserves failing exit codes without duplicate error output. See the module docstring at the top of `cli-main.ts` for the argv-prefix contract with `src/commands/index.ts`.
27
28 Errors are captured via the custom `effect-errors/` module (source-mapped stack traces, Effect span timelines, formatted output).
29
@@ -103,7 +103,7 @@ Steps 3–4 (and the TypeScript compiler they need) ship as the `generation-runt
103
104 ### Configuration
105
106 -- CLI: `cli-config.ts` defines `ComposioCliConfig` (`builtIns: [GlobalFlag.Help]`, `effect/unstable/cli`'s `CliConfig.Service` shrank to just that one field in v4) — the only `CliConfig` customization Composio makes, wired into `cli-main.ts`'s layer stack as `CliConfigLive`. v3's `autoCorrectLimit`/`isCaseSensitive` have no v4 config equivalent, and neither is reproduced anymore: "Did you mean?" suggestions on `UnrecognizedOption`/`UnknownSubcommand` now render as v4's parser always computes them (no config knob exists to disable them, and Composio wants them), and v4's parser performs no case-folding at all, so case-sensitivity needs no knob. `cli-main.ts` provides no custom `CliOutput.Formatter` — `Command.runWith` uses v4's own `CliOutput.defaultFormatter()`. `GlobalFlag.Version` is deliberately not enabled: `composio --version`, `composio -v`, and the `composio version` command all print the same bare `pkg.version` via `ui.output()`, because `src/commands/index.ts` rewrites the flag spellings to the `version` command before parsing (`normalizeVersionFlag`).
106 +- CLI: `cli-config.ts` enables help and version global actions. `commands/root-help.ts` derives the native `help` command tree and delegates documents to Effect. The formatter keeps version output bare and appends a short root overview. Hidden debug settings use `Flag.withHidden`; the diagnostic group uses `Command.unlisted` (the pinned framework's hidden-command API). `commands/argv-compat.ts` preserves optional `listen --stream` values and inserts the native `--` boundary for legacy undelimited `run` script arguments. Effect parses the script tail through `Argument.variadic`; never strip its flags. `setup skill` installs agent skills; `--dangerously-allow` is local to `dev triggers disable`.
107 - Constants: `constants.ts` — env prefixes (`COMPOSIO_`, `DEBUG_OVERRIDE_`)
108 - User config: `~/.composio/user-config.json`
109 - Cache files: `toolkits.json`, `tools.json`, `tools-as-enums.json`, `trigger-types.json`
ts/packages/cli/CHANGELOG.md
+10
@@ -4,6 +4,16 @@
4
5 ### Patch Changes
6
7 +- Generate help from the command definitions, including every supported flag and
8 + nested command. Remove help levels and the nonexistent `files` help topic.
9 + Install agent skills with `composio setup skill <claude|codex|openclaw>`
10 + (optionally `--name <skill-name>`) instead of `--install-skill`.
11 + Internal diagnostics are hidden framework commands. `--dangerously-allow`
12 + applies only to `dev triggers disable`; refused developer commands exit nonzero.
13 + Debug flags after the `run` script boundary now reach the script unchanged.
14 + `composio execute <slug> --help` now shows command options. Use
15 + `composio execute <slug> --get-schema` to print that tool's input schema as JSON.
16 +
17 - `composio execute` (including meta tools) and `composio proxy` are never
18 retried, so a request that timed out or failed after the backend already
19 acted cannot repeat a side effect such as sending the same email twice.
ts/packages/cli/README.md
+5 -2
@@ -22,7 +22,7 @@ composio [--log-level All|Trace|Debug|Info|Warn|Error|Fatal|None]
22 ### Optional Flags
23
24 - `--log-level`: Set the log verbosity level. Accepted values (case-sensitive): All, Trace, Debug, Info, Warn, Error, Fatal, None
25 -- `--install-skill [skill-name] <claude|codex|openclaw>`: Manually install the composio skill for a supported agent when automatic installation fails. `--instal-skill` is still accepted as a backward-compatible alias.
25 +- `composio setup skill <claude|codex|openclaw> [--name skill-name]`: Install the CLI skill for an agent host.
26
27 ## 🧭 Commands
28
@@ -46,7 +46,10 @@ composio [--log-level All|Trace|Debug|Info|Warn|Error|Fatal|None]
46 - `composio generate py [-o, --output-dir <directory>] [--toolkits <toolkit>]`: Generate Python type stubs for toolkits, tools, and triggers from the Composio API.
47 - `composio generate ts [-o, --output-dir <directory>] [--compact] [--transpiled] [--type-tools] [--toolkits <toolkit>]`: Generate TypeScript types for toolkits, tools, and triggers from the Composio API.
48 - `composio upgrade [--beta]`: Self-update the Composio CLI from the stable channel, or from the beta channel with `--beta`.
49 -- `composio --install-skill [skill-name] <claude|codex|openclaw>`: Manually install the composio skill for Claude, Codex, or OpenClaw.
49 +- `composio setup skill <claude|codex|openclaw> [--name skill-name]`: Manually install the composio skill for Claude, Codex, or OpenClaw.
50 +
51 +Use `composio execute <slug> --get-schema` to print a tool's input schema as JSON.
52 +`composio execute <slug> --help` now shows command options and examples.
53
54 ## Configuration
55
ts/packages/cli/src/analytics/events.ts
+20 -18
@@ -7,6 +7,7 @@ import type { CliInvocationContext } from 'src/services/runtime-cli-context';
7 import { SetupCommandError } from 'src/services/setup-command-error';
8 import { ToolInputValidationError } from 'src/services/tool-input-validation';
9 import { guessToolkitFromToolSlug } from 'src/utils/toolkit-from-tool-slug';
10 +import { rootCommandIndex } from 'src/utils/cli-args';
11
12 export const CLI_ANALYTICS_EVENTS = {
13 CLI_COMMAND_INVOKED: 'CLI_COMMAND_INVOKED',
@@ -208,8 +209,8 @@ const TOOL_VALIDATION_CODES: ReadonlySet<number> = new Set([
209
210 const extractCommandPath = (argv: ReadonlyArray<string>): string => {
211 const commandTokens: string[] = [];
211 -
212 - for (const token of argv.slice(2)) {
212 + const args = argv.slice(2);
213 + for (const token of args.slice(rootCommandIndex(args))) {
214 if (!token || token.startsWith('-') || !KNOWN_COMMAND_TOKENS.has(token)) {
215 break;
216 }
@@ -291,7 +292,8 @@ const getFlagValue = (argv: ReadonlyArray<string>, ...flags: string[]): string |
292 const getTrailingPositionals = (context: CliCommandTelemetryContext): ReadonlyArray<string> => {
293 const commandTokenCount =
294 context.commandPath === 'composio' ? 0 : context.commandPath.split(' ').length;
294 - const args = context.argv.slice(2 + commandTokenCount);
295 + const rootArgs = context.argv.slice(2);
296 + const args = rootArgs.slice(rootCommandIndex(rootArgs) + commandTokenCount);
297 const positionals: string[] = [];
298
299 for (let index = 0; index < args.length; index += 1) {
@@ -505,21 +507,21 @@ export const createCliCommandTelemetryContext = (
507 cliVersion: string,
508 terminal: { readonly stdoutIsTTY: boolean; readonly stderrIsTTY: boolean },
509 invocation: CliInvocationContext
508 -): CliCommandTelemetryContext => ({
509 - argv,
510 - cliVersion,
511 - invocationOrigin: invocation.invocationOrigin,
512 - parentRunId: invocation.parentRunId,
513 - commandPath: extractCommandPath(argv),
514 - flagNames: extractFlagNames(argv),
515 - stdoutIsTTY: terminal.stdoutIsTTY,
516 - stderrIsTTY: terminal.stderrIsTTY,
517 - startedAt: Date.now(),
518 - runId:
519 - extractCommandPath(argv) === 'run'
520 - ? (invocation.parentRunId ?? crypto.randomUUID())
521 - : undefined,
522 -});
510 +): CliCommandTelemetryContext => {
511 + const commandPath = extractCommandPath(argv);
512 + return {
513 + argv,
514 + cliVersion,
515 + invocationOrigin: invocation.invocationOrigin,
516 + parentRunId: invocation.parentRunId,
517 + commandPath,
518 + flagNames: extractFlagNames(argv),
519 + stdoutIsTTY: terminal.stdoutIsTTY,
520 + stderrIsTTY: terminal.stderrIsTTY,
521 + startedAt: Date.now(),
522 + runId: commandPath === 'run' ? (invocation.parentRunId ?? crypto.randomUUID()) : undefined,
523 + };
524 +};
525
526 const getCliCommandInvokedEvent = (context: CliCommandTelemetryContext): TrackEvent =>
527 buildEvent(CLI_ANALYTICS_EVENTS.CLI_COMMAND_INVOKED, {
ts/packages/cli/src/bin.ts
+7 -9
@@ -7,10 +7,10 @@ import * as BunRuntime from '@effect/platform-bun/BunRuntime';
7 import { isBackgroundWorkerInvocation, runBackgroundWorkerFromArgv } from 'src/analytics/dispatch';
8 import { NodeOs } from 'src/services/node-os';
9 import { TerminalUILive } from 'src/services/terminal-ui';
10 -import { stripTelemetryDebugFlag, telemetryDebugModeLayer } from 'src/services/runtime-flags';
10 +import { readTelemetryDebugOverride, telemetryDebugModeLayer } from 'src/services/runtime-flags';
11
12 -// The one `process.argv` read: every later consumer receives this normalized argv explicitly.
13 -const bootstrap = stripTelemetryDebugFlag(process.argv);
12 +// Read process.argv once and pass it unchanged to the worker or command framework.
13 +const argv = process.argv;
14
15 const workerLayers = Layer.mergeAll(
16 BunFileSystem.layer,
@@ -20,10 +20,10 @@ const workerLayers = Layer.mergeAll(
20 TerminalUILive
21 );
22
23 -if (isBackgroundWorkerInvocation(bootstrap.argv)) {
24 - runBackgroundWorkerFromArgv(bootstrap.argv).pipe(
23 +if (isBackgroundWorkerInvocation(argv)) {
24 + runBackgroundWorkerFromArgv(argv).pipe(
25 Effect.provide(
26 - bootstrap.telemetryDebug
26 + readTelemetryDebugOverride(argv) === true
27 ? Layer.merge(workerLayers, telemetryDebugModeLayer(true))
28 : workerLayers
29 ),
@@ -34,7 +34,5 @@ if (isBackgroundWorkerInvocation(bootstrap.argv)) {
34 })
35 );
36 } else {
37 - void import('./cli-main').then(({ runCli }) =>
38 - runCli({ argv: bootstrap.argv, telemetryDebug: bootstrap.telemetryDebug })
39 - );
37 + void import('./cli-main').then(({ runCli }) => runCli({ argv }));
38 }
ts/packages/cli/src/cli-config.ts
+3 -33
@@ -1,37 +1,7 @@
1 +import { Help } from 'src/commands/root-help';
2 import { GlobalFlag, type CliConfig } from 'effect/unstable/cli';
3
3 -/**
4 - * Composio's `effect/unstable/cli` runner configuration.
5 - *
6 - * v4's `CliConfig.Service` shape shrank to a single field: `builtIns`, the
7 - * ordered list of built-in global flags (`--help`/`-h`, `--version`/`-v`,
8 - * `--wizard`, `--completions`, `--log-level`) that `Command.runWith` accepts
9 - * at every command in the tree. Composio only wants `--help`/`-h`, so every
10 - * other built-in is dropped by omitting it here (this is the v4 equivalent of
11 - * v3's `showBuiltIns: false`, scoped down to exactly the flag we still want).
12 - *
13 - * `GlobalFlag.Version` is deliberately absent: `composio --version` and
14 - * `composio -v` must print byte-identical output to the `composio version`
15 - * *command* (a bare semver via `ui.output()`, see `commands/version.cmd.ts`),
16 - * so `src/commands/index.ts` rewrites those spellings to the `version` command
17 - * before parsing (`normalizeVersionFlag`). Leaving the built-in active would let
18 - * `composio <subcommand> --version` reach v4's `<name> v<version>` banner
19 - * instead — a second, different rendering of the same value.
20 - *
21 - * This is the *only* CliConfig customization Composio makes. Everything else
22 - * — "Did you mean?" suggestions on `UnrecognizedOption`/`UnknownSubcommand`
23 - * and help rendering — uses v4's own `CliOutput.defaultFormatter()`
24 - * deliberately: suggestions are useful UX.
25 - *
26 - * v3's `autoCorrectLimit` and `isCaseSensitive` have no v4 counterpart:
27 - * - "Did you mean?" suggestions are computed unconditionally by the parser
28 - * (`internal/auto-suggest.ts`) and attached to `CliError.UnrecognizedOption`
29 - * / `CliError.UnknownSubcommand`. There is no config knob to disable them,
30 - * and Composio no longer wants to — they render as-is.
31 - * - Flag and subcommand name matching in v4's parser is always exact-match
32 - * (no case-folding is performed), so no config is needed to keep
33 - * Composio's case-sensitive behavior.
34 - */
4 +// Help and version use the framework parser. The help formatter keeps version output bare.
5 export const ComposioCliConfig = {
36 - builtIns: [GlobalFlag.Help],
6 + builtIns: [Help, GlobalFlag.Version],
7 } satisfies Partial<CliConfig.CliConfig.Service>;
ts/packages/cli/src/cli-main.ts
+9 -94
@@ -1,74 +1,7 @@
1 /**
2 - * Composio CLI runner: composes the top-level Effect layers and drives the
3 - * root command through `effect/unstable/cli`'s `Command.runWith`.
4 - *
5 - * ## v4 runner design (read before touching this file)
6 - *
7 - * v3's `@effect/cli` `Command.run`/`runWith` returned a `ValidationError` on
8 - * parse/validation failure and left rendering (help text, "did you mean"
9 - * tips) entirely to the caller. This module used to inspect
10 - * `ValidationError.error` (a `HelpDoc`), render it by hand, and separately
11 - * look up help text for the resolved command via `root-help.ts`.
12 - *
13 - * v4's `Command.runWith` (see
14 - * `ts/vendor/effect/packages/effect/src/unstable/cli/Command.ts`,
15 - * `runWith`/`showHelp`) is different in a load-bearing way: it *renders
16 - * help and errors itself* — `Console.log`ing the formatted `HelpDoc` and
17 - * `Console.error`ing formatted `CliError`s for the resolved `commandPath` —
18 - * and only then re-fails with a `CliError.ShowHelp`. By the time that
19 - * failure reaches this module, the correct output (respecting whatever
20 - * command tree/visibility was passed to `Command.runWith`, using v4's own
21 - * `CliOutput.defaultFormatter()` — see `cli-config.ts` for why Composio no
22 - * longer overrides it) has already been printed once, to the correct
23 - * stream.
24 - *
25 - * `CliError.ShowHelp` (see `ts/vendor/.../unstable/cli/CliError.ts`) carries
26 - * two `effect/Runtime` markers set on the class itself:
27 - * `[Runtime.errorExitCode] = errors.length ? 1 : 0` and
28 - * `[Runtime.errorReported] = false`. Those markers are how `ShowHelp` tells
29 - * the runtime "I already printed my own output; don't log me again, and here
30 - * is the exit code to use." Consequently, this module's job for `ShowHelp`
31 - * is to do *nothing* — not render, not intercept — and simply let it
32 - * propagate to `BunRuntime.runMain`: `errorReported = false` suppresses
33 - * `runMain`'s automatic `Effect.logError(cause)` (see `Runtime.makeRunMain`),
34 - * and the custom `teardown` below reads `errorExitCode` off the squashed
35 - * error to pick the process exit code (0 for a bare `--help`/`--version`
36 - * request, 1 when help was shown alongside parse/validation errors). The
37 - * sandboxed catch-all handler further down special-cases `ShowHelp` for
38 - * exactly this reason: it re-fails with the original `Cause` via
39 - * `Effect.failCause` instead of swallowing it like every other error.
40 - * `collectValueOptionNames` and the "Tip: --flag requires a value" logic
41 - * that used to run in a dedicated `ShowHelp` branch here are gone for a
42 - * related reason: v4's `CliError.InvalidValue` already renders that exact
43 - * tip natively ("Missing value for flag --x. Expected: ...") as part of
44 - * `Command.runWith`'s own error output.
45 - *
46 - * `matchCommandFromArgv` / `getCommandHelpText` are still used lower down,
47 - * in the catch-all defect handler — that is a genuinely different path
48 - * (real command-handler failures captured by `effect-errors`, not CLI
49 - * parse/validation failures), and `Command.runWith` never renders anything
50 - * for it, so appending the resolved command's help text there is not a
51 - * double-print.
52 - *
53 - * v3's `CliConfig` also configured `autoCorrectLimit: 0` and
54 - * `isCaseSensitive: true`. Neither has a v4 config equivalent, and neither
55 - * is reproduced anymore: v4's parser is always exact-match (no case-folding,
56 - * so `isCaseSensitive` needs no knob), and "Did you mean?" suggestions on
57 - * `UnrecognizedOption`/`UnknownSubcommand` now render as-is — see
58 - * `cli-config.ts` for the full rationale. `CliConfigLive` below narrows the
59 - * active built-in global flags to just `--help`/`-h` and `--version`/root
60 - * `-v`, per `ComposioCliConfig`; that narrowing is the only `CliConfig`
61 - * customization left.
62 - *
63 - * `runWithConfig` (from `src/commands`) still receives the *full*
64 - * `process.argv`, including the node/bun executable and script path
65 - * prefix, exactly as before. That module slices the prefix off internally
66 - * for its own routing/help logic. The `effect/unstable/cli` `Command.runWith`
67 - * (unlike v3's `Command.run`) expects args *without* that prefix, so
68 - * whatever `commands/index.ts` binds as its own `run` helper is
69 - * responsible for slicing `argv.slice(2)` immediately before invoking
70 - * `Command.runWith` — this module does not do that slicing itself, so the
71 - * contract at the `runWithConfig` boundary must not change.
2 + * Composes the CLI layers and runs Effect's command parser. Command.runWith renders
3 + * help and parse errors once; preserve ShowHelp so its runtime markers control logging
4 + * and the exit code. runWithConfig accepts full argv and removes the executable prefix.
5 */
6 import process from 'node:process';
7 import { Cause, ConfigProvider, Effect, Exit, Layer, Logger, Predicate, Runtime } from 'effect';
@@ -80,7 +13,6 @@ import * as BunRuntime from '@effect/platform-bun/BunRuntime';
13 import * as BunFileSystem from '@effect/platform-bun/BunFileSystem';
14 import * as BunPath from '@effect/platform-bun/BunPath';
15 import { runWithConfig, type RootCommandBootstrap } from 'src/commands';
83 -import { matchCommandFromArgv, getCommandHelpText } from 'src/commands/root-help';
16 import * as constants from 'src/constants';
17 import { ComposioCliConfig } from 'src/cli-config';
18 import { getBaseConfigProvider, ConfigLive, extendConfigProvider } from 'src/services/config';
@@ -93,7 +25,7 @@ import { ComposioToolkitsRepositoryCached } from 'src/services/composio-clients-
25 import { NodeOs } from 'src/services/node-os';
26 import { NodeProcess } from 'src/services/node-process';
27 import { JsPackageManagerDetector } from 'src/services/js-package-manager-detector';
96 -import { ComposioCliUserConfigLive, ComposioCliUserConfig } from 'src/services/cli-user-config';
28 +import { ComposioCliUserConfigLive } from 'src/services/cli-user-config';
29 import { ComposioUserContextLive as _ComposioUserContextLive } from 'src/services/user-context';
30 import { UpgradeBinary } from 'src/services/upgrade-binary';
31 import { TerminalUI, TerminalUILive } from 'src/services/terminal-ui';
@@ -123,7 +55,8 @@ import { SetupCommandError } from 'src/services/setup-command-error';
55 import { ShellSetupAbortError } from 'src/commands/install.cmd';
56 import { MissingRunSourceError } from 'src/commands/run.cmd';
57 import { cliInvocationContext } from 'src/services/runtime-cli-context';
126 -import { telemetryDebugModeLayer } from 'src/services/runtime-flags';
58 +import { readTelemetryDebugOverride, telemetryDebugModeLayer } from 'src/services/runtime-flags';
59 +import { normalizeRunScriptArgs } from 'src/commands/argv-compat';
60
61 // Layer is contravariant in ROut and covariant in E, so `never`/`unknown` accept any
62 // produced context and error type while still pinning the requirements (RIn) to `never`.
@@ -304,10 +237,8 @@ const runWithTelemetry = (argv: ReadonlyArray<string>) =>
237 * Values `src/bin.ts` resolved before the Effect runtime existed and hands to it here.
238 */
239 export type CliBootstrapOptions = {
307 - /** The full process argv (executable and script included) with `--telemetry-debug` stripped. */
240 + /** The full, unchanged process argv (executable and script included). */
241 readonly argv: ReadonlyArray<string>;
309 - /** `--telemetry-debug` was on the command line, and was stripped from argv before parsing. */
310 - readonly telemetryDebug: boolean;
242 };
243
244 const cliProgram = (argv: ReadonlyArray<string>) =>
@@ -394,21 +325,6 @@ const cliProgram = (argv: ReadonlyArray<string>) =>
325 if (message.length > 0) {
326 const ui = yield* TerminalUI;
327 yield* ui.error(message);
397 - const cliUserConfig = yield* ComposioCliUserConfig;
398 - const visibility = {
399 - isDevModeEnabled: cliUserConfig.isDevModeEnabled(),
400 - isExperimentalFeatureEnabled: (feature: string) =>
401 - cliUserConfig.isExperimentalFeatureEnabled(feature),
402 - };
403 - // This handles genuine command-execution failures (business errors captured by
404 - // effect-errors), a different path from the `ShowHelp` branch above: those are CLI
405 - // parse/validation failures that `Command.runWith` already rendered itself. Appending
406 - // the resolved command's help text here is not a double-print of that.
407 - const cmdName = matchCommandFromArgv(argv, visibility);
408 - const helpText = cmdName ? getCommandHelpText(cmdName, visibility) : undefined;
409 - if (helpText) {
410 - yield* ui.error(helpText);
411 - }
328 process.exitCode = 1;
329 }
330 }
@@ -421,11 +337,10 @@ const cliProgram = (argv: ReadonlyArray<string>) =>
337 );
338
339 export const runCli = (options: CliBootstrapOptions): void => {
340 + const debug = readTelemetryDebugOverride(normalizeRunScriptArgs(options.argv));
341 cliProgram(options.argv).pipe(
425 - // Only provided when the flag was actually present: without it telemetry debugging falls back
426 - // to `COMPOSIO_CLI_TELEMETRY_DEBUG`.
342 effect =>
428 - options.telemetryDebug ? Effect.provide(effect, telemetryDebugModeLayer(true)) : effect,
343 + debug === undefined ? effect : Effect.provide(effect, telemetryDebugModeLayer(debug)),
344 BunRuntime.runMain({ teardown })
345 );
346 };
ts/packages/cli/src/commands/$default.cmd.ts
+10 -2
@@ -24,8 +24,16 @@ const logLevel = Flag.Literals('log-level', LogLevel.values).pipe(
24 export const $defaultCmd = Command.make('composio').pipe(
25 Command.withSharedFlags({ logLevel }),
26 Command.withDescription(
27 - `Composio CLI - A tool for managing Python and TypeScript composio.dev projects.`
28 - )
27 + `Connect AI agents to external tools. Start with search, execute, and link.`
28 + ),
29 + Command.withExamples([
30 + { command: 'composio search "send an email"', description: 'Find tools for a task.' },
31 + { command: 'composio link gmail', description: 'Connect an app account.' },
32 + {
33 + command: 'composio execute GMAIL_SEND_EMAIL --get-schema',
34 + description: 'Inspect tool inputs.',
35 + },
36 + ])
37 );
38
39 /**
ts/packages/cli/src/commands/argv-compat.ts new
+52
@@ -0,0 +1,52 @@
1 +import { Array as Arr } from 'effect';
2 +import { RUN_KNOWN_BOOLEAN_FLAGS, RUN_KNOWN_VALUE_FLAGS } from './run.cmd';
3 +import { rootCommandIndex } from 'src/utils/cli-args';
4 +
5 +export const normalizeListenStreamFlag = (argv: ReadonlyArray<string>): ReadonlyArray<string> => {
6 + const head = Arr.take(argv, 2);
7 + const args = Arr.drop(argv, 2);
8 + const isListen = args[rootCommandIndex(args)] === 'listen';
9 + if (!isListen) {
10 + return argv;
11 + }
12 +
13 + // Effect string flags require a value. An empty path means stream the whole payload.
14 + return Arr.appendAll(
15 + head,
16 + Arr.flatMap(args, (token, index) => {
17 + const next = args[index + 1];
18 + return token === '--stream' && (next === undefined || next.startsWith('-'))
19 + ? ['--stream', '']
20 + : [token];
21 + })
22 + );
23 +};
24 +
25 +// Preserve the legacy undelimited script syntax by inserting Effect's native `--`
26 +// before the script tail. The framework then parses every operand itself.
27 +export const normalizeRunScriptArgs = (argv: ReadonlyArray<string>): ReadonlyArray<string> => {
28 + const commandIndex = 2 + rootCommandIndex(argv.slice(2));
29 + if (argv[commandIndex] !== 'run') return argv;
30 +
31 + let index = commandIndex + 1;
32 + while (index < argv.length) {
33 + const token = argv[index];
34 + const equalsIndex = token.indexOf('=');
35 + const flagName = equalsIndex === -1 ? token : token.slice(0, equalsIndex);
36 + if (RUN_KNOWN_VALUE_FLAGS.has(flagName)) {
37 + index += equalsIndex === -1 ? 2 : 1;
38 + } else if (RUN_KNOWN_BOOLEAN_FLAGS.has(flagName)) {
39 + index += 1;
40 + } else {
41 + break;
42 + }
43 + }
44 + if (index >= argv.length) return argv;
45 +
46 + const tail = argv.slice(index);
47 + // The first user delimiter marks the script boundary; subsequent delimiters
48 + // are script arguments. Move that boundary ahead of all script operands.
49 + const separator = tail.indexOf('--');
50 + if (separator !== -1) tail.splice(separator, 1);
51 + return [...argv.slice(0, index), '--', ...tail];
52 +};
ts/packages/cli/src/commands/config/config.experimental.cmd.ts
+6 -1
@@ -145,5 +145,10 @@ export const configExperimentalCmd = Command.make(
145 '',
146 `Known features: ${knownFeatures.join(', ')}`,
147 ].join('\n')
148 - )
148 + ),
149 + Command.withExamples([
150 + { command: 'composio config experimental' },
151 + { command: 'composio config experimental listen on' },
152 + { command: 'composio config experimental listen off' },
153 + ])
154 );
ts/packages/cli/src/commands/connected-accounts/commands/connected-accounts.link.cmd.ts
+28 -27
@@ -999,6 +999,18 @@ const runConnectedAccountsLink = (params: {
999 }
1000 });
1001
1002 +const linkExamples = [
1003 + {
1004 + command: 'composio link github',
1005 + },
1006 + {
1007 + command: 'composio link gmail --alias work',
1008 + },
1009 + {
1010 + command: 'composio link github --list',
1011 + },
1012 +];
1013 +
1014 export const connectedAccountsCmd$Link = Command.make(
1015 'link',
1016 { toolkit, authConfig, userId, projectName, noWait, noBrowser, alias, list },
@@ -1016,19 +1028,16 @@ export const connectedAccountsCmd$Link = Command.make(
1028 })
1029 ).pipe(
1030 Command.withDescription(
1019 - [
1020 - 'Connect an external account (GitHub, Gmail, Slack, etc.) so tools can act on your behalf.',
1021 - 'Opens a browser for OAuth authorization and waits for confirmation.',
1022 - '',
1023 - 'Examples:',
1024 - ' composio link github',
1025 - ' composio link gmail --alias work',
1026 - ' composio link github --list',
1027 - '',
1028 - 'See also:',
1029 - ' composio search "<query>" Find tools to use after linking',
1030 - " composio execute <slug> -d '{ ... }' Execute a tool with your connected account",
1031 - ].join('\n')
1031 + 'Connect an external account (GitHub, Gmail, Slack, etc.) so tools can act on your behalf.\nOpens a browser for OAuth authorization and waits for confirmation.'
1032 + ),
1033 + Command.withShortDescription(
1034 + 'Connect an external account (GitHub, Gmail, Slack, etc.) so tools can act on your behalf.'
1035 + ),
1036 + Command.withExamples(
1037 + linkExamples.map(example => ({
1038 + ...example,
1039 + command: example.command.replace('composio link', 'composio dev connected-accounts link'),
1040 + }))
1041 )
1042 );
1043
@@ -1049,18 +1058,10 @@ export const rootConnectedAccountsCmd$Link = Command.make(
1058 })
1059 ).pipe(
1060 Command.withDescription(
1052 - [
1053 - 'Connect an external account (GitHub, Gmail, Slack, etc.) so tools can act on your behalf.',
1054 - 'Opens a browser for OAuth authorization and waits for confirmation.',
1055 - '',
1056 - 'Examples:',
1057 - ' composio link github',
1058 - ' composio link gmail --alias work',
1059 - ' composio link github --list',
1060 - '',
1061 - 'See also:',
1062 - ' composio search "<query>" Find tools to use after linking',
1063 - " composio execute <slug> -d '{ ... }' Execute a tool with your connected account",
1064 - ].join('\n')
1065 - )
1061 + 'Connect an external account (GitHub, Gmail, Slack, etc.) so tools can act on your behalf.\nOpens a browser for OAuth authorization and waits for confirmation.'
1062 + ),
1063 + Command.withShortDescription(
1064 + 'Connect an external account (GitHub, Gmail, Slack, etc.) so tools can act on your behalf.'
1065 + ),
1066 + Command.withExamples(linkExamples)
1067 );
ts/packages/cli/src/commands/connections/commands/connections.list.cmd.ts
+9 -1
@@ -118,5 +118,13 @@ export const connectionsCmd$List = Command.make('list', { toolkit }, ({ toolkit
118 ).pipe(
119 Command.withDescription(
120 'List connection statuses as JSON. Includes aliases for duplicate toolkits and word_ids when available.'
121 - )
121 + ),
122 + Command.withExamples([
123 + {
124 + command: 'composio connections list',
125 + },
126 + {
127 + command: 'composio connections list --toolkit gmail',
128 + },
129 + ])
130 );
ts/packages/cli/src/commands/connections/commands/connections.remove.cmd.ts
+12 -1
@@ -170,5 +170,16 @@ export const connectionsCmd$Remove = Command.make('remove', { account }, ({ acco
170 ).pipe(
171 Command.withDescription(
172 'Interactively remove a connection by toolkit slug, alias, word_id, or connected account ID.'
173 - )
173 + ),
174 + Command.withExamples([
175 + {
176 + command: 'composio connections remove gmail',
177 + },
178 + {
179 + command: 'composio connections remove work',
180 + },
181 + {
182 + command: 'composio connections remove castle',
183 + },
184 + ])
185 );
ts/packages/cli/src/commands/debug.cmd.ts new
+74
@@ -0,0 +1,74 @@
1 +import { Command } from 'effect/unstable/cli';
2 +import { Data, Effect, Option } from 'effect';
3 +import { TerminalUI } from 'src/services/terminal-ui';
4 +import { renderCommandHintGraph } from 'src/services/command-hints';
5 +import { ComposioUserContext } from 'src/services/user-context';
6 +import { detectMasterFromHost } from 'src/services/master-detector';
7 +import {
8 + formatResolveCommandProjectError,
9 + resolveCommandProject,
10 +} from 'src/services/command-project';
11 +
12 +class DebugCommandError extends Data.TaggedError('commands/DebugCommandError')<{
13 + readonly message: string;
14 +}> {}
15 +
16 +const printCommandHintGraph = Effect.suspend(() =>
17 + Effect.flatMap(TerminalUI, ui =>
18 + ui.output(JSON.stringify(renderCommandHintGraph(), null, 2), { force: true })
19 + )
20 +);
21 +
22 +const printDebugApiInfo = Effect.gen(function* () {
23 + const ui = yield* TerminalUI;
24 + const confirmed = yield* ui.confirm(
25 + 'This will print your current CLI API key and scoped identifiers to stdout. Continue?',
26 + { defaultValue: false }
27 + );
28 + if (!confirmed) {
29 + return yield* new DebugCommandError({ message: 'Aborted printing API credentials.' });
30 + }
31 + const ctx = yield* ComposioUserContext;
32 + const apiKey = Option.getOrUndefined(ctx.data.apiKey);
33 + if (!apiKey) {
34 + return yield* new DebugCommandError({
35 + message: 'No user API key found in the current CLI session.',
36 + });
37 + }
38 + const orgId = Option.getOrUndefined(ctx.data.orgId);
39 + const consumerProject = yield* resolveCommandProject({ mode: 'consumer' }).pipe(
40 + Effect.mapError(formatResolveCommandProjectError),
41 + Effect.option
42 + );
43 + return yield* ui.output(
44 + JSON.stringify(
45 + {
46 + apiKey,
47 + orgId: orgId ?? null,
48 + consumerUserId:
49 + Option.isSome(consumerProject) && consumerProject.value.projectType === 'CONSUMER'
50 + ? (consumerProject.value.consumerUserId ?? null)
51 + : null,
52 + },
53 + null,
54 + 2
55 + ),
56 + { force: true }
57 + );
58 +});
59 +
60 +const printDetectedMaster = Effect.gen(function* () {
61 + const ui = yield* TerminalUI;
62 + const master = yield* detectMasterFromHost;
63 + yield* ui.output(JSON.stringify({ master }, null, 2), { force: true });
64 +});
65 +
66 +export const debugCmd = Command.make('debug').pipe(
67 + Command.unlisted,
68 + Command.withDescription('Internal CLI diagnostics.'),
69 + Command.withSubcommands([
70 + Command.make('generate-graph', {}, () => printCommandHintGraph).pipe(Command.unlisted),
71 + Command.make('api-info', {}, () => printDebugApiInfo).pipe(Command.unlisted),
72 + Command.make('who-is-my-master', {}, () => printDetectedMaster).pipe(Command.unlisted),
73 + ])
74 +);
ts/packages/cli/src/commands/dev.cmd.ts
+12 -6
@@ -1,5 +1,5 @@
1 import { Command, Flag } from 'effect/unstable/cli';
2 -import { Effect, Option } from 'effect';
2 +import { Data, Effect, Option } from 'effect';
3 import { initCmd } from './init.cmd';
4 import { triggersCmd$Listen } from './triggers/commands/triggers.listen.cmd';
5 import { logsCmd } from './logs-cmd/logs.cmd';
@@ -31,6 +31,10 @@ export const devSubcommands = [
31 projectsCmd,
32 ] as const;
33
34 +export class DeveloperModeError extends Data.TaggedError('commands/DeveloperModeError')<{
35 + readonly message: string;
36 +}> {}
37 +
38 const describeCurrentMode = (enabled: boolean) =>
39 enabled
40 ? 'Developer mode is on. Developer subcommands are available.'
@@ -50,11 +54,9 @@ const applyDeveloperModeChange = (enabled: boolean) =>
54 if (enabled) {
55 if (!stdin.isTTY()) {
56 const configPath = yield* resolveCliConfigPath;
53 - yield* ui.log.error('Enabling developer mode requires an interactive terminal.');
54 - yield* ui.log.step(
55 - `Set "developer.enabled": true manually in ${configPath} if you really want to enable it outside an interactive session.`
56 - );
57 - return;
57 + return yield* new DeveloperModeError({
58 + message: `Enabling developer mode requires an interactive terminal. Set "developer.enabled": true in ${configPath} to enable it outside an interactive session.`,
59 + });
60 }
61
62 yield* ui.note(
@@ -129,6 +131,10 @@ export const buildDevCommand = (visibility: CommandVisibility) => {
131 ? 'Developer workflows: init, playground execution, logs, projects, toolkits, accounts, and triggers.'
132 : 'Developer mode controls access to developer-only workflows. When off, only `composio dev --mode on|off` is available.'
133 ),
134 + Command.withExamples([
135 + { command: 'composio dev --mode on' },
136 + { command: 'composio dev --mode off' },
137 + ]),
138 Command.withHandler(({ devMode }) =>
139 Option.match(devMode, {
140 onNone: () => promptForDeveloperMode(),
ts/packages/cli/src/commands/feature-tags.ts
+2 -34
@@ -1,10 +1,8 @@
1 export type CliFeatureTag = string;
2 -export type HelpLevel = 'simple' | 'default' | 'full';
2
3 export type TaggedValue<T> = {
4 readonly value: T;
5 readonly tags?: ReadonlyArray<CliFeatureTag>;
7 - readonly helpLevel?: HelpLevel;
6 };
7
8 export type CommandVisibility = {
@@ -17,34 +15,11 @@ export const tagged = <T>(value: T, tags?: ReadonlyArray<CliFeatureTag>): Tagged
15 tags,
16 });
17
20 -export const simple = <T>(value: T, tags?: ReadonlyArray<CliFeatureTag>): TaggedValue<T> => ({
21 - value,
22 - tags,
23 - helpLevel: 'simple',
24 -});
25 -
26 -export const full = <T>(value: T, tags?: ReadonlyArray<CliFeatureTag>): TaggedValue<T> => ({
27 - value,
28 - tags,
29 - helpLevel: 'full',
30 -});
31 -
18 export const experimental = <T>(feature: string, value: T): TaggedValue<T> => ({
19 value,
20 tags: [feature],
21 });
22
37 -const HELP_LEVEL_ORDER: Record<HelpLevel, number> = {
38 - simple: 0,
39 - default: 1,
40 - full: 2,
41 -};
42 -
43 -export const isTaggedValueVisibleForHelpLevel = <T>(
44 - entry: TaggedValue<T>,
45 - helpLevel: HelpLevel = 'default'
46 -): boolean => HELP_LEVEL_ORDER[helpLevel] >= HELP_LEVEL_ORDER[entry.helpLevel ?? 'default'];
47 -
23 export const isTaggedValueVisible = <T>(
24 entry: TaggedValue<T>,
25 visibility: CommandVisibility
@@ -58,13 +33,6 @@ export const isTaggedValueVisible = <T>(
33
34 export const visibleValues = <T>(
35 entries: ReadonlyArray<TaggedValue<T>>,
61 - visibility: CommandVisibility,
62 - helpLevel: HelpLevel = 'default'
36 + visibility: CommandVisibility
37 ): Array<T> =>
64 - entries
65 - .filter(
66 - entry =>
67 - isTaggedValueVisible(entry, visibility) &&
68 - isTaggedValueVisibleForHelpLevel(entry, helpLevel)
69 - )
70 - .map(entry => entry.value);
38 + entries.filter(entry => isTaggedValueVisible(entry, visibility)).map(entry => entry.value);
ts/packages/cli/src/commands/index.ts
+41 -556
@@ -1,5 +1,5 @@
1 -import { Array as Arr, Console, Data, Effect, HashSet, Layer, Option } from 'effect';
2 -import { Command } from 'effect/unstable/cli';
1 +import { Array as Arr, Console, Effect, Layer } from 'effect';
2 +import { CliOutput, Command } from 'effect/unstable/cli';
3 import { $defaultCmd, withRootLogLevel } from './$default.cmd';
4 import { getVersion } from 'src/effects/version';
5 import { versionCmd } from './version.cmd';
@@ -10,27 +10,19 @@ import { signupCmd } from './signup.cmd';
10 import { setupCmd } from './setup.cmd';
11 import { listenCmd } from './listen.cmd';
12 import { logoutCmd } from './logout.cmd';
13 -import {
14 - RUN_KNOWN_BOOLEAN_FLAGS,
15 - RUN_KNOWN_VALUE_FLAGS,
16 - RunPassthroughArgs,
17 - runCmd,
18 -} from './run.cmd';
13 +import { runCmd } from './run.cmd';
14 import { proxyCmd } from './proxy.cmd';
15 import { artifactsCmd } from './artifacts.cmd';
16 import { installCmd } from './install.cmd';
17 import { generateCmd } from './generate/generate.cmd';
18 import { buildDevCommand } from './dev.cmd';
19 +import { ExecuteInvocationArgs } from './tools/commands/tools.execute.cmd';
20 import {
25 - runParallelToolsExecuteFromArgv,
26 - showToolsExecuteInputHelp,
27 - TOOLS_EXECUTE_VALUE_OPTIONS,
28 -} from './tools/commands/tools.execute.cmd';
29 -import {
30 - printRootHelp,
31 - matchSubcommandHelp,
32 - parseHelpLevel,
33 - printSubcommandHelp,
21 + buildHelpCommand,
22 + RootHelpMarker,
23 + helpFormatter,
24 + RootHelpContext,
25 + showCommandHelp,
26 } from './root-help';
27 import { rootToolsCmd$Search } from './tools/commands/tools.search.cmd';
28 import { rootToolsCmd$Execute } from './tools/commands/tools.execute.cmd';
@@ -41,24 +33,18 @@ import { orgsCmd } from './orgs/orgs.cmd';
33 import { configCmd } from './config/config.cmd';
34 import { rootConnectionsCmd } from './connections/connections.cmd';
35 import { agentCmd } from './agent/agent.cmd';
44 -import { renderCommandHintGraph } from 'src/services/command-hints';
45 -import { cliDebugFlagsLayer, type CliDebugFlagOverrides } from 'src/services/runtime-flags';
36 +import { cliDebugFlagsLayer, CLI_DEBUG_GLOBAL_FLAGS } from 'src/services/runtime-flags';
37 import { cliRunIdLayer } from 'src/services/runtime-cli-context';
38 import { ComposioCliUserConfig } from 'src/services/cli-user-config';
48 -import { ComposioUserContext } from 'src/services/user-context';
49 -import { TerminalUI } from 'src/services/terminal-ui';
50 -import { detectMasterFromHost } from 'src/services/master-detector';
51 -import {
52 - formatResolveCommandProjectError,
53 - resolveCommandProject,
54 -} from 'src/services/command-project';
39 import { CLI_EXPERIMENTAL_FEATURES } from 'src/constants';
56 -import { installSkill, type SkillInstallTarget } from 'src/effects/install-skill';
40 import { experimental, type CommandVisibility, tagged, visibleValues } from './feature-tags';
41 import { withBackgroundUpdateCheck } from './background-update-check';
42 +import { debugCmd } from './debug.cmd';
43 +import { normalizeListenStreamFlag, normalizeRunScriptArgs } from './argv-compat';
44 import { configureCliAnalyticsReleaseVersion } from 'src/analytics/events';
45
46 const ROOT_COMMANDS = [
47 + tagged(debugCmd),
48 tagged(versionCmd),
49 tagged(upgradeCmd),
50 tagged(whoamiCmd),
@@ -91,422 +77,21 @@ const getVisibleRootCommands = (visibility: CommandVisibility) => {
77 );
78 };
79
94 -export const buildRootCommand = (visibility: CommandVisibility) =>
95 - $defaultCmd.pipe(Command.withSubcommands(getVisibleRootCommands(visibility)), withRootLogLevel);
96 -
97 -const ROOT_INSTALL_SKILL_FLAGS = HashSet.make('--install-skill', '--instal-skill');
98 -const SKILL_INSTALL_TARGETS: ReadonlyArray<SkillInstallTarget> = ['claude', 'codex', 'openclaw'];
99 -
100 -class RootCommandError extends Data.TaggedError('commands/RootCommandError')<{
101 - readonly message: string;
102 -}> {}
103 -
104 -type RootInstallSkillRequest = {
105 - readonly skillName?: string;
106 - readonly target: SkillInstallTarget;
107 -};
108 -
109 -const isSkillInstallTarget = (value: string): value is SkillInstallTarget =>
110 - SKILL_INSTALL_TARGETS.some(target => target === value);
111 -
112 -const rootCommandError = (message: string) => Effect.fail(new RootCommandError({ message }));
113 -
114 -const findRootInstallSkillValues = (
115 - args: ReadonlyArray<string>
116 -): Option.Option<ReadonlyArray<string>> =>
117 - Arr.matchLeft(args, {
118 - onEmpty: Option.none,
119 - onNonEmpty: (token, tail) => {
120 - if (HashSet.has(ROOT_INSTALL_SKILL_FLAGS, token)) {
121 - return Option.some(Arr.takeWhile(tail, value => !value.startsWith('-')));
122 - }
123 - if (token === '--log-level') {
124 - return findRootInstallSkillValues(Arr.drop(tail, 1));
125 - }
126 - if (token.startsWith('--log-level=') || token.startsWith('-')) {
127 - return findRootInstallSkillValues(tail);
128 - }
129 - return Option.none();
130 - },
131 - });
132 -
133 -const parseRootInstallSkillValues = (
134 - rawValues: ReadonlyArray<string>
135 -): Effect.Effect<RootInstallSkillRequest, RootCommandError> =>
136 - Arr.match(rawValues, {
137 - onEmpty: () =>
138 - rootCommandError(
139 - 'Missing target for --install-skill. Usage: composio --install-skill [skill-name] <claude|codex|openclaw>'
140 - ),
141 - onNonEmpty: ([first, second, ...rest]) => {
142 - if (rest.length > 0) {
143 - return rootCommandError(
144 - 'Too many arguments for --install-skill. Usage: composio --install-skill [skill-name] <claude|codex|openclaw>'
145 - );
146 - }
147 - const target = second ?? first;
148 - if (!isSkillInstallTarget(target)) {
149 - return rootCommandError(
150 - 'Invalid target for --install-skill. Expected one of: claude, codex, openclaw.'
151 - );
152 - }
153 - return Effect.succeed(second === undefined ? { target } : { skillName: first, target });
154 - },
155 - });
156 -
157 -export const parseRootInstallSkillRequest = (
158 - argv: ReadonlyArray<string>
159 -): Effect.Effect<Option.Option<RootInstallSkillRequest>, RootCommandError> =>
160 - Option.match(findRootInstallSkillValues(Arr.drop(argv, 2)), {
161 - onNone: () => Effect.succeed(Option.none()),
162 - onSome: values => Effect.map(parseRootInstallSkillValues(values), Option.some),
163 - });
164 -
165 -// v4 note: v3 pre-flight parsed `argv` to rewrite `ValidationError.CommandMismatch` messages
166 -// (`scopeCommandMismatch` / `refineRootCommandMismatch`) before `Command.run` rendered them, using
167 -// the private `CommandDescriptor` tree. `effect/unstable/cli`'s
168 -// `Command.runWith` renders its own unknown-subcommand messaging (naming the resolved command's
169 -// actual subcommands) internally before re-failing with `CliError.ShowHelp`, so `routeRootCommand`
170 -// below now always delegates straight to `run` instead of pre-flight parsing and rewriting errors.
171 -
172 -export const parseExecuteInputHelpSlug = (argv: ReadonlyArray<string>): string | undefined => {
173 - const args = Arr.drop(argv, 2);
174 - const isRootExecute = args[0] === 'execute';
175 - const isDevExecute = args[0] === 'dev' && args[1] === 'playground-execute';
176 - if (!isRootExecute && !isDevExecute) return undefined;
177 -
178 - const hasHelp = args.includes('--help') || args.includes('-h');
179 - if (!hasHelp) return undefined;
180 -
181 - const findSlug = (tail: ReadonlyArray<string>): string | undefined =>
182 - Arr.matchLeft(tail, {
183 - onEmpty: () => undefined,
184 - onNonEmpty: (token, rest) => {
185 - if (token === '--') {
186 - return Option.getOrUndefined(
187 - Option.filter(Arr.head(rest), candidate => !candidate.startsWith('-'))
188 - );
189 - }
190 - if (token === '--help' || token === '-h') {
191 - return findSlug(rest);
192 - }
193 - if (HashSet.has(TOOLS_EXECUTE_VALUE_OPTIONS, token)) {
194 - return findSlug(Arr.drop(rest, 1));
195 - }
196 - if (token.startsWith('-')) {
197 - return findSlug(rest);
198 - }
199 - return token;
200 - },
201 - });
202 -
203 - return findSlug(Arr.drop(args, isRootExecute ? 1 : 2));
204 -};
205 -
206 -const VERSION_FLAGS: ReadonlySet<string> = new Set(['--version', '-v']);
207 -
208 -/**
209 - * `composio --version` and `composio -v` are spellings of the `version` command: the flag is
210 - * rewritten before parsing so all three share one handler and print byte-identical output,
211 - * independent of how the CLI framework renders its own built-in version flag.
212 - */
213 -const normalizeVersionFlag = (argv: ReadonlyArray<string>): ReadonlyArray<string> => {
214 - const [first, ...rest] = argv.slice(2);
215 - return first !== undefined && VERSION_FLAGS.has(first)
216 - ? [...argv.slice(0, 2), 'version', ...rest]
217 - : argv;
218 -};
219 -
220 -const normalizeListenStreamFlag = (argv: ReadonlyArray<string>): ReadonlyArray<string> => {
221 - const head = Arr.take(argv, 2);
222 - const args = Arr.drop(argv, 2);
223 - const isListen = args[0] === 'listen';
224 - if (!isListen) {
225 - return argv;
226 - }
227 -
228 - // `--stream` is documented as taking an optional value, but @effect/cli text options always
229 - // require one. A bare `--stream` therefore has to be rewritten. `--stream=` cannot be used for
230 - // that: @effect/cli only recognizes `--flag=value` when the value is non-empty, so `--stream=`
231 - // surfaces as "Received unknown argument". Passing an explicit empty string as the next token
232 - // parses cleanly and the listen command treats an empty path as "stream the whole payload".
233 - return Arr.appendAll(
234 - head,
235 - Arr.flatMap(args, (token, index) => {
236 - const next = args[index + 1];
237 - return token === '--stream' && (next === undefined || next.startsWith('-'))
238 - ? ['--stream', '']
239 - : [token];
240 - })
241 - );
242 -};
243 -
244 -// `composio run` forwards arbitrary flag-looking tokens straight through to
245 -// the user's script (`composio run 'code' --flag value`, or
246 -// `--file s.ts -- --flag value`), but v4's CLI lexer
247 -// (`effect/unstable/cli/internal/lexer.ts`) treats every `-`-prefixed token
248 -// as an option candidate unless it follows a literal `--`, and (see
249 -// `internal/parser.ts`'s `parseArgs`) that `--` split is computed once for
250 -// the whole argv and only reaches the *first* command level parsed — a
251 -// subcommand's own recursive `parseArgs` call is always given
252 -// `trailingOperands: []`, so trailing operands after `--` never reach a
253 -// subcommand's `Argument.variadic()` no matter how the tokens are escaped.
254 -//
255 -// So rather than smuggle passthrough tokens through the parser, the split
256 -// below removes them from the argv handed to the CLI parser entirely and
257 -// returns them out-of-band as `tail`. `runWithConfig` provides `tail` to
258 -// `run.cmd.ts`'s `RunPassthroughArgs` reference for the scope of a single
259 -// invocation; the `run` handler reads it directly instead of relying on its
260 -// own `Argument.variadic()`, which never sees these tokens for a real CLI
261 -// invocation. Only direct programmatic/test invocations that bypass this
262 -// front door fall back to the parsed value (see `RunPassthroughArgs`'s doc
263 -// comment in `run.cmd.ts`).
264 -
265 -type RunPassthroughSplit = {
266 - readonly argv: ReadonlyArray<string>;
267 - readonly tail: ReadonlyArray<string> | undefined;
268 -};
269 -
270 -const splitRunPassthroughArgs = (argv: ReadonlyArray<string>): RunPassthroughSplit => {
271 - const args = Arr.drop(argv, 2);
272 - if (args[0] !== 'run') {
273 - return { argv, tail: undefined };
274 - }
275 -
276 - const normalized: Array<string> = [];
277 - const tail: Array<string> = [];
278 - let sawPositional = false;
279 - let droppedSeparator = false;
280 - let index = 1;
281 - while (index < args.length) {
282 - const token = args[index];
283 - if (!sawPositional) {
284 - // A `--flag=value` token must be recognized by its name, not the whole
285 - // token: `--file=script.ts` is a `run` option, and treating it as the
286 - // first positional would demote every later flag (including safety
287 - // flags like `--dry-run`) to the passthrough tail.
288 - const equalsIndex = token.indexOf('=');
289 - const flagName = equalsIndex === -1 ? token : token.slice(0, equalsIndex);
290 - if (RUN_KNOWN_VALUE_FLAGS.has(flagName)) {
291 - normalized.push(token);
292 - if (equalsIndex === -1) {
293 - const value = args[index + 1];
294 - if (value !== undefined) {
295 - normalized.push(value);
296 - }
297 - index += 2;
298 - continue;
299 - }
300 - index += 1;
301 - continue;
302 - }
303 - if (RUN_KNOWN_BOOLEAN_FLAGS.has(flagName)) {
304 - normalized.push(token);
305 - index += 1;
306 - continue;
307 - }
308 - // First token that isn't a `run`-recognized flag: everything from here
309 - // on is the passthrough tail, not a `run` option. A literal `--` here
310 - // is just the (now unnecessary) boundary marker itself.
311 - sawPositional = true;
312 - if (token === '--') {
313 - droppedSeparator = true;
314 - } else {
315 - tail.push(token);
316 - }
317 - index += 1;
318 - continue;
319 - }
320 - if (token === '--') {
321 - // Only the first `--` is the run/script boundary; later ones are script
322 - // arguments and must reach the script verbatim (matches v3's
323 - // forwarding behavior).
324 - if (!droppedSeparator) {
325 - droppedSeparator = true;
326 - index += 1;
327 - continue;
328 - }
329 - tail.push('--');
330 - index += 1;
331 - continue;
332 - }
333 - tail.push(token);
334 - index += 1;
335 - }
336 -
337 - return { argv: [...Arr.take(argv, 2), 'run', ...normalized], tail };
338 -};
339 -
340 -const parseBooleanFlag = (argument: string, name: string): Option.Option<boolean> => {
341 - if (argument === name || argument === `${name}=true`) {
342 - return Option.some(true);
343 - }
344 - return argument === `${name}=false` ? Option.some(false) : Option.none();
345 -};
346 -
347 -/**
348 - * Splits the hidden debug flags off argv and returns their parsed values.
349 - *
350 - * The values are inputs to the command that follows — `src/commands/index.ts` provides them as
351 - * `CliDebugFlags` — rather than process-wide state, so an explicit `--perf-debug=false` on one
352 - * invocation cannot leak into the next.
353 - */
354 -const normalizeHiddenDebugFlags = (
355 - argv: ReadonlyArray<string>
356 -): { readonly argv: ReadonlyArray<string>; readonly overrides: CliDebugFlagOverrides } => {
357 - const retainedArgs: Array<string> = [];
358 - let perfDebug: boolean | undefined;
359 - let toolDebug: boolean | undefined;
360 - let acpOnly: boolean | undefined;
361 -
362 - for (const argument of Arr.drop(argv, 2)) {
363 - const parsedPerfDebug = Option.getOrUndefined(parseBooleanFlag(argument, '--perf-debug'));
364 - if (parsedPerfDebug !== undefined) {
365 - perfDebug = parsedPerfDebug;
366 - continue;
367 - }
368 - const parsedToolDebug = Option.getOrUndefined(parseBooleanFlag(argument, '--tool-debug'));
369 - if (parsedToolDebug !== undefined) {
370 - toolDebug = parsedToolDebug;
371 - continue;
372 - }
373 - const parsedAcpOnly = Option.getOrUndefined(parseBooleanFlag(argument, '--acp-only'));
374 - if (parsedAcpOnly !== undefined) {
375 - acpOnly = parsedAcpOnly;
376 - continue;
377 - }
378 - retainedArgs.push(argument);
379 - }
380 -
381 - return {
382 - argv: Arr.appendAll(Arr.take(argv, 2), retainedArgs),
383 - overrides: { perfDebug, toolDebug, acpOnly },
384 - };
385 -};
386 -
387 -const isRootHelp = (argv: ReadonlyArray<string>): boolean => {
388 - const args = argv.slice(2);
389 - return (
390 - args.length === 0 ||
391 - (args.length >= 1 &&
392 - args.length <= 2 &&
393 - (args[0] === '--help' || args[0] === '-h') &&
394 - (args.length === 1 || parseHelpLevel(args[1]) !== undefined))
80 +export const buildRootCommand = (visibility: CommandVisibility) => {
81 + const commands = getVisibleRootCommands(visibility);
82 + return withBackgroundUpdateCheck($defaultCmd.pipe(Command.withHandler(() => showCommandHelp())), [
83 + ...commands,
84 + buildHelpCommand(commands),
85 + ]).pipe(
86 + Command.annotate(RootHelpMarker, true),
87 + Command.withGlobalFlags(CLI_DEBUG_GLOBAL_FLAGS),
88 + withRootLogLevel
89 );
90 };
91
398 -const isGenerateGraph = (argv: ReadonlyArray<string>): boolean => {
399 - const args = argv.slice(2);
400 - return args.length === 2 && args[0] === 'debug' && args[1] === 'generate-graph';
401 -};
402 -
403 -const isDebugApiInfo = (argv: ReadonlyArray<string>): boolean => {
404 - const args = argv.slice(2);
405 - return args.length === 2 && args[0] === 'debug' && args[1] === 'api-info';
406 -};
407 -
408 -const isDebugWhoIsMyMaster = (argv: ReadonlyArray<string>): boolean => {
409 - const args = argv.slice(2);
410 - return args.length === 2 && args[0] === 'debug' && args[1] === 'who-is-my-master';
411 -};
412 -
413 -const normalizeDangerouslyAllowFlag = (argv: ReadonlyArray<string>) => {
414 - const retainedArgs: Array<string> = [];
415 - let dangerouslyAllow = false;
416 - for (const argument of Arr.drop(argv, 2)) {
417 - if (argument === '--dangerously-allow') {
418 - dangerouslyAllow = true;
419 - } else {
420 - retainedArgs.push(argument);
421 - }
422 - }
423 -
424 - return {
425 - argv: Arr.appendAll(Arr.take(argv, 2), retainedArgs),
426 - dangerouslyAllow,
427 - };
428 -};
429 -
430 -const isHelpRequest = (args: ReadonlyArray<string>) =>
431 - args.includes('--help') || args.includes('-h');
432 -
433 -const isDevModeOnlyInvocation = (args: ReadonlyArray<string>) => {
434 - if (args[0] !== 'dev') return false;
435 - if (isHelpRequest(args)) return true;
436 - if (args.length === 1) return true;
437 - if (args.length === 2 && (args[1] === '--mode' || args[1].startsWith('--mode='))) return true;
438 - if (args.length === 3 && args[1] === '--mode') return true;
439 - return false;
440 -};
441 -
442 -const isDangerousDevCommand = (args: ReadonlyArray<string>): boolean => {
443 - if (args[0] !== 'dev' || isHelpRequest(args)) return false;
444 -
445 - if (args[1] === 'triggers') {
446 - return args[2] === 'disable';
447 - }
448 -
449 - return false;
450 -};
451 -
452 -const printCommandHintGraph = Effect.suspend(() =>
453 - Effect.flatMap(TerminalUI, ui =>
454 - ui.output(JSON.stringify(renderCommandHintGraph(), null, 2), { force: true })
455 - )
456 -);
457 -
458 -const printDebugApiInfo = Effect.gen(function* () {
459 - const ui = yield* TerminalUI;
460 - const confirmed = yield* ui.confirm(
461 - 'This will print your current CLI API key and scoped identifiers to stdout. Continue?',
462 - { defaultValue: false }
463 - );
464 - if (!confirmed) {
465 - return yield* rootCommandError('Aborted printing API credentials.');
466 - }
467 - const ctx = yield* ComposioUserContext;
468 - const apiKey = Option.getOrUndefined(ctx.data.apiKey);
469 - if (!apiKey) {
470 - return yield* rootCommandError('No user API key found in the current CLI session.');
471 - }
472 - const orgId = Option.getOrUndefined(ctx.data.orgId);
473 - const consumerProject = yield* resolveCommandProject({ mode: 'consumer' }).pipe(
474 - Effect.mapError(formatResolveCommandProjectError),
475 - Effect.option
476 - );
477 - return yield* ui.output(
478 - JSON.stringify(
479 - {
480 - apiKey,
481 - orgId: orgId ?? null,
482 - consumerUserId:
483 - Option.isSome(consumerProject) && consumerProject.value.projectType === 'CONSUMER'
484 - ? (consumerProject.value.consumerUserId ?? null)
485 - : null,
486 - },
487 - null,
488 - 2
489 - ),
490 - { force: true }
491 - );
492 -});
493 -
494 -const printDetectedMaster = Effect.gen(function* () {
495 - const ui = yield* TerminalUI;
496 - const master = yield* detectMasterFromHost;
497 - yield* ui.output(JSON.stringify({ master }, null, 2), { force: true });
498 -});
499 -
500 -const printDevModeDisabled = Effect.gen(function* () {
501 - const ui = yield* TerminalUI;
502 - yield* ui.log.error('Developer mode is off.');
503 - yield* ui.log.step('Run `composio dev --mode on` in an interactive terminal to enable it.');
504 -});
505 -
92 /**
93 * Values the CLI bootstrap resolved before the root command runs and that the command tree needs
508 - * as an input. Empty for callers that drive the root command on their own (tests, `--install-skill`
509 - * style entry points), which is why every field is optional.
94 + * as an input. Optional for callers that drive the root command directly in tests.
95 */
96 export type RootCommandBootstrap = {
97 /** Run id minted for a `composio run` invocation, shared with its telemetry events. */
@@ -521,29 +106,19 @@ export const runWithConfig = Effect.gen(function* () {
106 };
107 const version = yield* getVersion;
108 configureCliAnalyticsReleaseVersion(version);
524 - const rootCommand = withRootLogLevel(
525 - withBackgroundUpdateCheck($defaultCmd, getVisibleRootCommands(visibility))
526 - );
109 + const rootCommand = buildRootCommand(visibility);
110 // v4's `Command.runWith` (unlike v3's `Command.run`) takes explicit arguments rather than
111 // pulling them from `Stdio`, and expects them *without* the node/bun executable + script path
112 // prefix — see `cli-main.ts` module docs for the full contract at this boundary.
530 - const run = Command.runWith(rootCommand, { version });
113 + const run = (args: ReadonlyArray<string>) => {
114 + return Command.runWith(rootCommand, { version })(args).pipe(
115 + Effect.provideService(RootHelpContext, { command: rootCommand, version }),
116 + Effect.provideService(CliOutput.Formatter, helpFormatter())
117 + );
118 + };
119
532 - // `Command.runWith` renders the help document for a failed parse through the
533 - // ambient Console's `log` (stdout) before re-failing with `ShowHelp` (see
534 - // the vendored `Command.ts` `showHelp`, ~line 1453). Verified this Console
535 - // swap is the best available seam, not just the easiest: v4's
536 - // `CliOutput.Formatter` only formats to strings and cannot choose a stream,
537 - // and `showHelp` hardcodes `Console.log` with no parameter to override it,
538 - // so the only alternative would be reimplementing `runWith` itself.
539 - // Composio's output contract reserves stdout for data: help belongs there
540 - // only when the user explicitly asked for it (`--help`/`-h`; `--version`/`-v`
541 - // never reach the parser, `normalizeVersionFlag` rewrites them to the
542 - // `version` command). For every other invocation the framework's rendering is
543 - // decoration, so the runner gets a Console whose `log` writes through
544 - // `error`. No CLI code emits data via the Effect Console service (handlers
545 - // write through `TerminalUI`), so this only affects the framework's own
546 - // help/error rendering.
120 + // Effect renders help through Console.log. Route implicit help to stderr so stdout
121 + // stays available for command data; explicit help and version requests use stdout.
122 const runWithDecorationOnStderr = (args: ReadonlyArray<string>) =>
123 Effect.gen(function* () {
124 const base = yield* Console.Console;
@@ -556,109 +131,19 @@ export const runWithConfig = Effect.gen(function* () {
131 });
132 });
133
559 - const EXPLICIT_STDOUT_FLAGS: ReadonlySet<string> = new Set(['--help', '-h']);
134 + const EXPLICIT_STDOUT_FLAGS: ReadonlySet<string> = new Set(['--help', '-h', '--version', '-v']);
135
136 const runCli = (args: ReadonlyArray<string>) =>
562 - args.some(arg => EXPLICIT_STDOUT_FLAGS.has(arg)) ? run(args) : runWithDecorationOnStderr(args);
563 -
564 - const routeRootCommand = (normalizedArgv: ReadonlyArray<string>, dangerouslyAllow: boolean) => {
565 - const args = normalizedArgv.slice(2);
566 - if (isRootHelp(normalizedArgv)) {
567 - return printRootHelp(visibility, parseHelpLevel(normalizedArgv[3]) ?? 'default');
568 - }
569 - // `composio help [command] [level]` — the framework has no builtin help command, so
570 - // route it through the same curated pages as `composio <command> --help`.
571 - if (args[0] === 'help') {
572 - // `help` already asks for help, so a redundant `--help`/`-h` (`composio help --help`,
573 - // `composio help orgs full --help`) must not reach the framework parser.
574 - const rest = args.slice(1).filter(arg => !EXPLICIT_STDOUT_FLAGS.has(arg));
575 - const last = rest[rest.length - 1];
576 - const helpLevel = parseHelpLevel(last) ?? 'default';
577 - const cmdParts = parseHelpLevel(last) !== undefined ? rest.slice(0, -1) : rest;
578 - if (cmdParts.length === 0) {
579 - return printRootHelp(visibility, helpLevel);
580 - }
581 - // Resolve with the same longest-prefix scan the `--help` spelling uses, so
582 - // `composio help dev toolkits` renders the curated dev page instead of an
583 - // unknown-command line for a path that exists. `matchSubcommandHelp` reads a
584 - // full argv with a trailing --help token, hence the synthetic prefix.
585 - const subHelp = matchSubcommandHelp(
586 - ['composio', 'composio', ...cmdParts, '--help'],
587 - visibility
588 - );
589 - if (subHelp) {
590 - return printSubcommandHelp(subHelp, visibility, helpLevel);
591 - }
592 - // Unknown target: fall through to the framework parser so the failure
593 - // matches every other unknown command (stderr rendering, "Did you mean?",
594 - // exit 1) instead of an exit-0 stdout line scripts would read as success. The
595 - // `help` token is dropped so the error and suggestion name the mistyped command.
596 - return runCli(cmdParts);
597 - }
598 - const subHelp = matchSubcommandHelp(normalizedArgv, visibility);
599 - if (subHelp) {
600 - const helpLevel = parseHelpLevel(normalizedArgv[normalizedArgv.length - 1]) ?? 'default';
601 - return printSubcommandHelp(subHelp, visibility, helpLevel);
602 - }
603 - const parallelExecute = runParallelToolsExecuteFromArgv(normalizedArgv);
604 - if (parallelExecute) {
605 - return parallelExecute;
606 - }
607 - if (isGenerateGraph(normalizedArgv)) {
608 - return printCommandHintGraph;
609 - }
610 - if (isDebugApiInfo(normalizedArgv)) {
611 - return printDebugApiInfo;
612 - }
613 - if (isDebugWhoIsMyMaster(normalizedArgv)) {
614 - return printDetectedMaster;
615 - }
616 - const executeHelpSlug = parseExecuteInputHelpSlug(normalizedArgv);
617 - if (executeHelpSlug) {
618 - return showToolsExecuteInputHelp(executeHelpSlug);
619 - }
620 - if (!visibility.isDevModeEnabled && args[0] === 'dev' && !isDevModeOnlyInvocation(args)) {
621 - return printDevModeDisabled;
622 - }
623 - if (isDangerousDevCommand(args)) {
624 - return Effect.gen(function* () {
625 - const ui = yield* TerminalUI;
626 - if (!cliUserConfig.areDeveloperDangerousCommandsEnabled()) {
627 - yield* ui.log.error('This developer command is disabled by config.');
628 - yield* ui.log.step(
629 - 'Set `developer.destructive_actions` to `true` in `~/.composio/config.json` to allow dangerous developer commands.'
630 - );
631 - return;
632 - }
633 - if (!dangerouslyAllow) {
634 - yield* ui.log.error('This developer command requires explicit acknowledgement.');
635 - yield* ui.log.step('Re-run the command with `--dangerously-allow`.');
636 - return;
637 - }
638 - return yield* runCli(args);
639 - });
640 - }
641 - return runCli(args);
642 - };
137 + args.length === 0 ||
138 + Arr.takeWhile(args, arg => arg !== '--').some(arg => EXPLICIT_STDOUT_FLAGS.has(arg))
139 + ? run(args)
140 + : runWithDecorationOnStderr(args);
141
142 return (argv: ReadonlyArray<string>, bootstrap: RootCommandBootstrap = {}) => {
645 - const { argv: argvWithoutDangerouslyAllow, dangerouslyAllow } =
646 - normalizeDangerouslyAllowFlag(argv);
647 - const { argv: argvWithoutDebugFlags, overrides } = normalizeHiddenDebugFlags(
648 - normalizeListenStreamFlag(normalizeVersionFlag(argvWithoutDangerouslyAllow))
649 - );
650 - const { argv: normalizedArgv, tail: runPassthroughTail } =
651 - splitRunPassthroughArgs(argvWithoutDebugFlags);
652 -
653 - return parseRootInstallSkillRequest(normalizedArgv).pipe(
654 - Effect.flatMap(
655 - Option.match({
656 - onNone: () => routeRootCommand(normalizedArgv, dangerouslyAllow),
657 - onSome: installSkill,
658 - })
659 - ),
660 - Effect.provide(Layer.merge(cliDebugFlagsLayer(overrides), cliRunIdLayer(bootstrap.runId))),
661 - Effect.provideService(RunPassthroughArgs, runPassthroughTail)
143 + const parsedArgv = normalizeRunScriptArgs(normalizeListenStreamFlag(argv));
144 + return runCli(parsedArgv.slice(2)).pipe(
145 + Effect.provideService(ExecuteInvocationArgs, parsedArgv.slice(2)),
146 + Effect.provide(Layer.merge(cliDebugFlagsLayer(), cliRunIdLayer(bootstrap.runId)))
147 );
148 };
149 });
ts/packages/cli/src/commands/listen.cmd.ts
+25 -1
@@ -724,5 +724,29 @@ export const listenCmd = Command.make(
724 ).pipe(
725 Command.withDescription(
726 'Listen to consumer-project realtime events. Trigger slugs create a temporary trigger; top-level composio.* event types subscribe directly.'
727 - )
727 + ),
728 + Command.withExamples([
729 + {
730 + command: 'composio listen GMAIL_NEW_GMAIL_MESSAGE',
731 + },
732 + {
733 + command: 'composio listen GMAIL_NEW_GMAIL_MESSAGE -p @trigger.json --max-events 5',
734 + },
735 + {
736 + command: 'composio listen GMAIL_NEW_GMAIL_MESSAGE --account work --timeout 5m',
737 + },
738 + {
739 + command: "composio listen GMAIL_NEW_GMAIL_MESSAGE --timeout 1hr --stream '.data.threadId'",
740 + },
741 + {
742 + command:
743 + 'composio listen SLACK_CHANNEL_MESSAGE_RECEIVED -p \'{ trigger_config: { channel_id: "C123" } }\'',
744 + },
745 + {
746 + command: 'composio listen GMAIL_NEW_GMAIL_MESSAGE -p @trigger.json --stream',
747 + },
748 + {
749 + command: "composio listen GMAIL_NEW_GMAIL_MESSAGE -p @trigger.json --stream '.data.threadId'",
750 + },
751 + ])
752 );
ts/packages/cli/src/commands/proxy.cmd.ts
+14 -14
@@ -266,21 +266,21 @@ export const proxyCmd = Command.make('proxy', {
266 skipConnectionCheck,
267 }).pipe(
268 Command.withDescription(
269 - [
270 - 'curl-like access to any toolkit API through Composio using your connected account.',
271 - 'Composio handles authentication — just provide the full URL and toolkit.',
272 - '',
273 - 'Examples:',
274 - ' composio proxy https://gmail.googleapis.com/gmail/v1/users/me/profile --toolkit gmail',
275 - ' composio proxy https://gmail.googleapis.com/gmail/v1/users/me/profile --toolkit gmail --account work',
276 - ` composio proxy https://gmail.googleapis.com/gmail/v1/users/me/drafts --toolkit gmail \\`,
277 - ` -X POST -H 'content-type: application/json' -d '{"message":{"raw":"..."}}'`,
278 - '',
279 - 'See also:',
280 - ' composio link <toolkit> Connect an account before calling proxy',
281 - ' composio run \'const f = await proxy("gmail"); ...\' Use proxy in a script',
282 - ].join('\n')
269 + 'curl-like access to any toolkit API through Composio using your connected account.\nComposio handles authentication — just provide the full URL and toolkit.'
270 ),
271 + Command.withShortDescription(
272 + 'curl-like access to any toolkit API through Composio using your connected account.'
273 + ),
274 + Command.withExamples([
275 + {
276 + command:
277 + 'composio proxy https://gmail.googleapis.com/gmail/v1/users/me/profile --toolkit gmail --account work',
278 + },
279 + {
280 + command:
281 + 'composio proxy https://gmail.googleapis.com/gmail/v1/users/me/drafts --toolkit gmail \\\n -X POST -H \'content-type: application/json\' -d \'{"message":{"raw":"..."}}\'',
282 + },
283 + ]),
284 Command.withHandler(options =>
285 Effect.gen(function* () {
286 const { endpoint, toolkit, account, method, headers, data, skipConnectionCheck } = options;
ts/packages/cli/src/commands/root-help.ts
+74 -1638
@@ -1,1650 +1,86 @@
1 -import { Effect, Option } from 'effect';
2 -import { CLI_EXPERIMENTAL_FEATURES } from 'src/constants';
3 -import { TerminalUI } from 'src/services/terminal-ui';
4 -import { bold, dim, gray } from 'src/ui/colors';
5 -import {
6 - type CommandVisibility,
7 - experimental,
8 - type HelpLevel,
9 - full,
10 - isTaggedValueVisible,
11 - isTaggedValueVisibleForHelpLevel,
12 - simple,
13 - tagged,
14 - visibleValues,
15 - type TaggedValue,
16 -} from './feature-tags';
1 +import { Console, Context, Effect } from 'effect';
2 +import { CliConfig, CliOutput, Command, GlobalFlag } from 'effect/unstable/cli';
3
18 -type DetailedCommand = {
19 - name: string;
20 - description: string;
21 - usage: string;
22 - options?: ReadonlyArray<{ name: string; description: string }>;
23 -};
24 -
25 -type CompactCommand = {
26 - name: string;
27 - description: string;
28 -};
29 -
30 -// ── Core workflow commands ──────────────────────────────────────────────
31 -
32 -const CORE_COMMANDS: ReadonlyArray<TaggedValue<DetailedCommand>> = [
33 - simple({
34 - name: 'search',
35 - description: 'Find tools by use case across all toolkits/apps.',
36 - usage: 'search <query...> [--toolkits text] [--limit integer] [--human]',
37 - options: [
38 - {
39 - name: '<query...>',
40 - description: 'One or more semantic use-case queries (e.g. "send emails" "github issues")',
41 - },
42 - { name: '--toolkits', description: 'Filter by toolkit slugs, comma-separated' },
43 - { name: '--limit', description: 'Maximum number of results (1-1000)' },
44 - { name: '--human', description: 'Show formatted output instead of default JSON' },
45 - ],
46 - }),
47 - simple({
48 - name: 'execute',
49 - description:
50 - 'Execute a tool. Validates inputs and connections automatically; use it aggressively.',
51 - usage:
52 - 'execute <slug> [-d, --data text] [--account selector] [--file path] [--dry-run] [--get-schema] | execute -p <slug> -d <text> <slug> -d <text> ...',
53 - options: [
54 - { name: '<slug>', description: 'Tool slug (e.g. "GITHUB_CREATE_ISSUE")' },
55 - {
56 - name: '-d, --data',
57 - description:
58 - 'JSON or JS-style object arguments, e.g. -d \'{ repo: "foo" }\', @file, or - for stdin',
59 - },
60 - {
61 - name: '-p, --parallel',
62 - description: 'Execute repeated <slug> -d <text> pairs concurrently',
63 - },
64 - {
65 - name: '--account',
66 - description: 'Select a connected account by alias, word_id, or account ID',
67 - },
68 - {
69 - name: '--file',
70 - description: 'Inject a local file path into the single file_uploadable input',
71 - },
72 - { name: '--dry-run', description: 'Validate and preview the tool call without executing it' },
73 - { name: '--get-schema', description: 'Fetch and print the CLI-facing input schema' },
74 - ],
75 - }),
76 - simple({
77 - name: 'link',
78 - description: 'Connect your account for a toolkit/app.',
79 - usage: 'link [<toolkit>] [--alias text]',
80 - options: [
81 - { name: '<toolkit>', description: 'Toolkit slug to link (e.g. "github", "gmail")' },
82 - { name: '--alias', description: 'Alias for this connected account' },
83 - ],
84 - }),
85 - tagged({
86 - name: 'run',
87 - description:
88 - 'Run inline TS/JS code with shimmed CLI commands; injected execute(), search(), proxy(), experimental_subAgent(), and z (zod).',
89 - usage: 'run <code> [-- ...args] | run [-f, --file text] [-- ...args] [--dry-run]',
90 - options: [
91 - { name: '<code>', description: 'Inline Bun ESNext code to evaluate' },
92 - { name: '-f, --file', description: 'Run a TS/JS file instead of inline code' },
93 - { name: '--dry-run', description: 'Preview execute() calls without running remote actions' },
94 - ],
95 - }),
96 - experimental(CLI_EXPERIMENTAL_FEATURES.LISTEN, {
97 - name: 'listen',
98 - description:
99 - 'Create a temporary subscription for consumer-project events and persist each payload into the session artifact folder.',
100 - usage:
101 - 'listen <slug> [-p, --params text] [--account selector] [--max-events integer] [--timeout text] [--stream [text]]',
102 - options: [
103 - { name: '<slug>', description: 'Trigger slug (e.g. "GMAIL_NEW_GMAIL_MESSAGE")' },
104 - {
105 - name: '-p, --params',
106 - description:
107 - "Trigger create params as JSON or JS-style object, e.g. -p '{ trigger_config: { ... } }'.",
108 - },
109 - {
110 - name: '--account',
111 - description: 'Select a connected account by alias, word_id, or account ID',
112 - },
113 - {
114 - name: '--max-events',
115 - description: 'Stop after receiving N events, then disable the temporary trigger',
116 - },
117 - {
118 - name: '--timeout',
119 - description:
120 - 'Stop after a duration such as 30s, 5m, or 1hr, then disable the temporary trigger',
121 - },
122 - {
123 - name: '--stream',
124 - description:
125 - 'Also print each payload inline as a single-line stream value. Optionally pass a jq-like path such as ".thread.id".',
126 - },
127 - ],
128 - }),
129 - tagged({
130 - name: 'proxy',
131 - description:
132 - 'curl-like access to any toolkit API through Composio using your connected account.',
133 - usage: 'proxy <url> --toolkit text [--account selector] [-X method] [-H header]... [-d data]',
134 - options: [
135 - { name: '<url>', description: 'Full API endpoint URL' },
136 - { name: '--toolkit', description: 'Toolkit slug whose connected account should be used' },
137 - { name: '--account', description: 'Connected account alias, word_id, or account ID' },
138 - { name: '-X, --method', description: 'HTTP method (GET, POST, PUT, DELETE, PATCH)' },
139 - { name: '-H, --header', description: 'Header in "Name: value" format. Repeat for multiple.' },
140 - { name: '-d, --data', description: 'Request body as raw text, JSON, @file, or - for stdin' },
141 - ],
142 - }),
143 -];
144 -
145 -// ── Developer commands ─────────────────────────────────────────────────
146 -
147 -const OTHER_COMMANDS: ReadonlyArray<TaggedValue<CompactCommand>> = [
148 - tagged({
149 - name: 'composio tools info <slug>',
150 - description: 'Print tool summary and cache its schema',
151 - }),
152 - tagged({
153 - name: 'composio tools list <toolkit>',
154 - description: 'List tools available in a toolkit',
155 - }),
156 - tagged({
157 - name: 'composio triggers info <slug>',
158 - description: 'Print trigger type details and schema summaries',
159 - }),
160 - tagged({
161 - name: 'composio triggers list <toolkit>',
162 - description: 'List available trigger types in a toolkit',
163 - }),
164 - tagged({
165 - name: 'composio artifacts cwd',
166 - description: 'Print the cwd-scoped session artifact directory',
167 - }),
168 -];
169 -
170 -const GENERATE_COMMAND: TaggedValue<CompactCommand> = tagged({
171 - name: 'generate',
172 - description: 'Generate type stubs for toolkits, tools, and triggers (TypeScript | Python).',
4 +export const RootHelpMarker = Context.Reference<boolean>('commands/RootHelpMarker', {
5 + defaultValue: () => false,
6 });
7
175 -// ── Account commands ───────────────────────────────────────────────────
176 -
177 -const ACCOUNT_COMMANDS: ReadonlyArray<TaggedValue<CompactCommand>> = [
178 - tagged({ name: 'setup', description: 'Install or uninstall agent plugins' }),
179 - tagged({ name: 'login', description: 'Log in to Composio' }),
180 - tagged({ name: 'logout', description: 'Log out from Composio' }),
181 - tagged({ name: 'whoami', description: 'Show current account info' }),
182 - tagged({ name: 'orgs', description: 'Manage default global organization/project context.' }),
183 - tagged({ name: 'version', description: 'Display CLI version' }),
184 - tagged({ name: 'upgrade', description: 'Upgrade CLI to the latest version' }),
185 - tagged({ name: 'config', description: 'View and manage CLI configuration' }),
186 -];
187 -
188 -const FULL_COMMANDS: ReadonlyArray<TaggedValue<CompactCommand>> = [
189 - full({
190 - name: 'files',
191 - description: 'Show where CLI config, cache, and session artifacts live',
192 - }),
193 - full({ name: 'tools list', description: 'List tools for a toolkit with query/tag filters' }),
194 - full({ name: 'tools info', description: 'Inspect a tool summary and cached schema details' }),
195 - full({ name: 'triggers list', description: 'List trigger types for a toolkit' }),
196 - full({ name: 'triggers info', description: 'Inspect a trigger type and schema summary' }),
197 - full({ name: 'connections list', description: 'Print toolkit connection statuses as JSON' }),
198 - full({ name: 'connections remove', description: 'Interactively remove a toolkit connection' }),
199 - full({ name: 'generate ts', description: 'Generate TypeScript stubs for selected toolkits' }),
200 - full({ name: 'generate py', description: 'Generate Python stubs for selected toolkits' }),
201 - full({
202 - name: 'dev init',
203 - description: 'Initialize a developer project in the current directory',
204 - }),
205 - full({
206 - name: 'dev playground-execute',
207 - description: 'Execute tools against developer playground users and auth configs',
208 - }),
209 - full({
210 - name: 'dev listen',
211 - description: 'Stream developer-project realtime trigger events with optional forwarding',
212 - }),
213 -];
214 -
215 -// ── Render helpers ─────────────────────────────────────────────────────
216 -
217 -function renderDetailedCommands(name: string, commands: ReadonlyArray<DetailedCommand>): string[] {
218 - const lines: string[] = [];
219 - for (const cmd of commands) {
220 - lines.push(` ${bold(cmd.name)}`);
221 - lines.push(` ${cmd.description}`);
222 - lines.push(` ${dim('Usage:')} ${name} ${cmd.usage}`);
223 - if (cmd.options && cmd.options.length > 0) {
224 - for (const opt of cmd.options) {
225 - lines.push(` ${dim(opt.name.padEnd(20))}${opt.description}`);
226 - }
227 - }
228 - lines.push('');
229 - }
230 - return lines;
231 -}
232 -
233 -function renderCompactCommands(commands: ReadonlyArray<CompactCommand>): string[] {
234 - const maxLen = Math.max(...commands.map(c => c.name.length));
235 - return commands.map(cmd => ` ${cmd.name.padEnd(maxLen + 2)}${cmd.description}`);
236 -}
237 -
238 -function renderDevHelp(visibility: CommandVisibility, helpLevel: HelpLevel = 'default'): string {
239 - const lines: string[] = [
240 - '',
241 - bold('USAGE'),
242 - visibility.isDevModeEnabled
243 - ? ' composio dev [--mode on|off] <command> [options]'
244 - : ' composio dev [--mode on|off]',
245 - '',
246 - bold('DESCRIPTION'),
247 - visibility.isDevModeEnabled
248 - ? ' Developer workflows for local project setup, playground execution, logs, and developer-scoped management.'
249 - : ' Developer mode is off. Only mode switching is available until you turn it back on.',
250 - '',
251 - bold('MODE'),
252 - ' --mode <on|off> Turn developer mode on or off.',
253 - '',
254 - ];
255 -
256 - if (!visibility.isDevModeEnabled) {
257 - if (helpLevel !== 'simple') {
258 - lines.push(bold('EXAMPLES'));
259 - lines.push(' composio dev --mode on');
260 - lines.push(' composio dev --mode off');
261 - lines.push('');
262 - lines.push(bold('NOTE'));
263 - lines.push(
264 - ' Developer mode is for engineers building with the CLI. It unlocks more advanced commands like creating or updating auth configs and connected accounts.'
265 - );
266 - lines.push('');
267 - }
268 - return lines.join('\n');
269 - }
270 -
271 - lines.push(bold('PROJECT'));
272 - lines.push(' dev init Initialize this directory with a developer project');
273 - lines.push('');
274 -
275 - lines.push(bold('EXECUTION'));
276 - lines.push(' dev playground-execute Execute a tool against a developer playground user');
277 - lines.push(' dev listen Listen to developer-project trigger events');
278 - lines.push(' dev logs tools Browse tool logs');
279 - lines.push(' dev logs triggers Browse trigger logs');
280 - lines.push('');
281 -
282 - lines.push(bold('TOOLKITS'));
283 - lines.push(' dev toolkits list Browse available toolkits');
284 - lines.push(' dev toolkits info Inspect a toolkit');
285 - lines.push(' dev toolkits search Search toolkits');
286 - lines.push(' dev toolkits version Inspect toolkit versions');
287 - lines.push('');
288 -
289 - lines.push(bold('AUTH CONFIGS'));
290 - lines.push(' dev auth-configs list List auth configs');
291 - lines.push(' dev auth-configs info View one auth config');
292 - lines.push(' dev auth-configs create Create an auth config');
293 - lines.push('');
294 -
295 - lines.push(bold('CONNECTED ACCOUNTS'));
296 - lines.push(' dev connected-accounts link Link a connected account');
297 - lines.push(' dev connected-accounts list List connected accounts');
298 - lines.push(' dev connected-accounts info View one connected account');
299 - lines.push(' dev connected-accounts whoami Resolve an account identity');
300 - lines.push('');
301 -
302 - lines.push(bold('TRIGGERS'));
303 - lines.push(' dev triggers list List trigger types');
304 - lines.push(' dev triggers info View one trigger type');
305 - lines.push(' dev triggers status Inspect trigger instances');
306 - lines.push(' dev triggers create Create a trigger instance');
307 - lines.push(' dev triggers enable Enable a trigger instance');
308 - lines.push(' dev triggers disable Disable a trigger instance [guarded]');
309 - lines.push('');
310 -
311 - lines.push(bold('PROJECTS'));
312 - lines.push(' dev projects list List projects');
313 - lines.push(' dev projects switch Switch default project');
314 - lines.push('');
315 -
316 - lines.push(bold('GUARDED'));
317 - lines.push(' dev triggers disable Disable a trigger instance');
318 - lines.push(
319 - ' This requires `developer.destructive_actions: true` in `~/.composio/config.json` and `--dangerously-allow` on the command line.'
320 - );
321 - lines.push('');
322 - if (helpLevel !== 'simple') {
323 - lines.push(bold('EXAMPLES'));
324 - lines.push(' composio dev --mode off');
325 - lines.push(' composio dev toolkits list');
326 - lines.push(
327 - ' composio dev playground-execute GMAIL_SEND_EMAIL --dangerously-allow -d \'{ recipient_email: "a@b.com" }\''
328 - );
329 - lines.push('');
330 - }
331 - return lines.join('\n');
332 -}
333 -export const HELP_LEVELS = [
334 - 'simple',
335 - 'default',
336 - 'full',
337 -] as const satisfies ReadonlyArray<HelpLevel>;
338 -
339 -export const parseHelpLevel = (token: string | undefined): HelpLevel | undefined => {
340 - if (!token) {
341 - return undefined;
342 - }
343 - if (token === 'verbose') {
344 - return 'full';
345 - }
346 - return HELP_LEVELS.find(level => level === token);
347 -};
348 -
349 -const splitTrailingHelpLevel = (
350 - args: ReadonlyArray<string>
351 -): { args: ReadonlyArray<string>; helpLevel: HelpLevel } => {
352 - const trailingLevel = parseHelpLevel(args[args.length - 1]);
353 - if (!trailingLevel) {
354 - return { args, helpLevel: 'default' };
8 +export class RootHelpContext extends Context.Service<
9 + RootHelpContext,
10 + {
11 + readonly command: Command.Command.Any;
12 + readonly version: string;
13 }
14 +>()('commands/RootHelpContext') {}
15
16 +/** Keep a short root overview; the framework generates every usage, flag, and subcommand. */
17 +export const helpFormatter = () => {
18 + const formatter = CliOutput.defaultFormatter();
19 return {
358 - args: args.slice(0, -1),
359 - helpLevel: trailingLevel,
360 - };
361 -};
362 -
363 -// ── Subcommand help definitions ────────────────────────────────────────
364 -
365 -type SubcommandHelp = {
366 - usage: string;
367 - description: string;
368 - args?: ReadonlyArray<{ name: string; description: string }>;
369 - options?: ReadonlyArray<{ name: string; description: string }>;
370 - flags?: ReadonlyArray<{ name: string; description: string }>;
371 - injectedHelpers?: ReadonlyArray<{ name: string; description: string }>;
372 - examples?: ReadonlyArray<string>;
373 - seeAlso?: ReadonlyArray<string>;
374 -};
375 -
376 -const SUBCOMMAND_HELP: Record<string, SubcommandHelp | TaggedValue<SubcommandHelp>> = {
377 - search: {
378 - usage: 'composio search <query...> [--toolkits text] [--limit integer] [--human]',
379 - description:
380 - 'Find tools by use case. Defaults to JSON output; use --human for formatted output.',
381 - args: [
382 - {
383 - name: '<query...>',
384 - description:
385 - 'One or more semantic use-case queries (e.g. "send an email", "create github issue")',
386 - },
387 - ],
388 - options: [
389 - { name: '--toolkits <text>', description: 'Filter by toolkit slugs, comma-separated' },
390 - { name: '--limit <integer>', description: 'Maximum number of results (1-1000)' },
391 - { name: '--human', description: 'Show formatted human-readable search output' },
392 - ],
393 - examples: [
394 - '# Find tools for a use case',
395 - 'composio search "send an email"',
396 - 'composio search "send an email" "create github issue"',
397 - 'composio search "my emails" "my github issues" --toolkits gmail,github',
398 - 'composio search "create issue" --toolkits github',
399 - 'composio search "send an email" --human',
400 - '',
401 - '# Cross-app workflow discovery',
402 - 'composio search "post a message to a slack channel"',
403 - 'composio search "add a row to google sheet"',
404 - '',
405 - '# Narrow results to a specific toolkit',
406 - 'composio search "list calendar events" --toolkits google_calendar --limit 5',
407 - ],
408 - seeAlso: [
409 - "composio execute <slug> -d '{ ... }' Run a tool from the results",
410 - "composio tools info <slug> Inspect a tool's full schema",
411 - 'composio link <toolkit> Connect an account if execute tells you to',
412 - ],
413 - },
414 - execute: {
415 - usage:
416 - 'composio execute <slug> [-d, --data text] [--account selector] [--file path] [--dry-run] [--get-schema] [--parallel]',
417 - description:
418 - 'Execute a tool by slug. Validates inputs against cached schemas and checks connections automatically — just try it and it will tell you what to fix.',
419 - args: [
420 - {
421 - name: '<slug>',
422 - description:
423 - 'Tool slug for single execute, or repeated <slug> -d <text> pairs when using -p/--parallel',
424 - },
425 - ],
426 - options: [
427 - {
428 - name: '-d, --data <text>',
429 - description:
430 - 'JSON or JS-style object arguments, e.g. -d \'{ repo: "foo" }\', @file, or - for stdin',
431 - },
432 - {
433 - name: '-p, --parallel',
434 - description: 'Execute repeated TOOL_SLUG -d <text> groups concurrently',
435 - },
436 - {
437 - name: '--account <selector>',
438 - description: 'Select a connected account by alias, word_id, or connected account ID',
439 - },
440 - {
441 - name: '--file <path>',
442 - description: 'Inject a local file path into the single file_uploadable input',
443 - },
444 - {
445 - name: '--get-schema',
446 - description: 'Fetch and print the CLI-facing input schema without executing',
447 - },
448 - {
449 - name: '--dry-run',
450 - description: 'Validate and preview the tool call without executing',
451 - },
452 - ],
453 - flags: [
454 - { name: '--skip-connection-check', description: 'Skip the connected-account check' },
455 - {
456 - name: '--skip-tool-params-check',
457 - description: 'Skip input validation against cached schema',
458 - },
459 - { name: '--skip-checks', description: 'Skip both checks above' },
460 - ],
461 - examples: [
462 - '# Send an email',
463 - `composio execute GMAIL_SEND_EMAIL -d '{ recipient_email: "a@b.com", subject: "Hello", body: "World" }'`,
464 - '',
465 - '# Create a GitHub issue with a named account',
466 - `composio execute GITHUB_CREATE_ISSUE --account work -d '{ owner: "acme", repo: "app", title: "Bug report", body: "Steps to reproduce..." }'`,
467 - '',
468 - '# Preview what a tool call would send without executing',
469 - `composio execute SLACK_SEND_MESSAGE --dry-run -d '{ channel: "general", markdown_text: "Hello team" }'`,
470 - '',
471 - '# Check what inputs a tool needs',
472 - 'composio execute GMAIL_SEND_EMAIL --get-schema',
473 - '',
474 - '# Read arguments from a file',
475 - 'composio execute GITHUB_CREATE_ISSUE -d @issue.json',
476 - '',
477 - '# Execute multiple tools concurrently',
478 - `composio execute -p GMAIL_SEND_EMAIL -d '{ recipient_email: "a@b.com" }' GITHUB_CREATE_AN_ISSUE -d '{ owner: "acme", repo: "app", title: "Bug" }'`,
479 - ],
480 - seeAlso: [
481 - 'composio search "<query>" Find tool slugs by use case',
482 - 'composio tools info <slug> Schema summary with jq hints',
483 - 'composio link <toolkit> Connect an account for a toolkit',
484 - 'composio artifacts cwd Print the current session artifact directory',
485 - ],
486 - },
487 - listen: experimental(CLI_EXPERIMENTAL_FEATURES.LISTEN, {
488 - usage:
489 - 'composio listen <slug> [-p, --params text] [--account selector] [--max-events integer] [--timeout text] [--stream [text]]',
490 - description:
491 - 'Create a temporary subscription for consumer-project events so background agents can easily consume new emails, Slack messages, and other trigger payloads from artifacts.',
492 - args: [{ name: '<slug>', description: 'Trigger slug to create and listen to' }],
493 - options: [
494 - {
495 - name: '-p, --params <text>',
496 - description:
497 - 'Trigger create params as JSON/JS object, @file, or - for stdin. Pass optional trigger config fields only.',
498 - },
499 - {
500 - name: '--account <selector>',
501 - description: 'Select a connected account by alias, word_id, or connected account ID',
502 - },
503 - {
504 - name: '--max-events <integer>',
505 - description: 'Stop after N events for this temporary trigger and disable it',
506 - },
507 - {
508 - name: '--timeout <text>',
509 - description: 'Stop after a duration such as "30s", "5m", or "1hr" and disable the trigger',
510 - },
511 - {
512 - name: '--stream [text]',
513 - description:
514 - 'Also print each event payload inline. Optionally pass a jq-like path such as ".thread.id" or ".data[0].id".',
515 - },
516 - ],
517 - examples: [
518 - 'composio listen GMAIL_NEW_GMAIL_MESSAGE',
519 - 'composio listen GMAIL_NEW_GMAIL_MESSAGE -p @trigger.json --max-events 5',
520 - 'composio listen GMAIL_NEW_GMAIL_MESSAGE --account work --timeout 5m',
521 - "composio listen GMAIL_NEW_GMAIL_MESSAGE --timeout 1hr --stream '.data.threadId'",
522 - 'composio listen SLACK_CHANNEL_MESSAGE_RECEIVED -p \'{ trigger_config: { channel_id: "C123" } }\'',
523 - 'composio listen GMAIL_NEW_GMAIL_MESSAGE -p @trigger.json --stream',
524 - "composio listen GMAIL_NEW_GMAIL_MESSAGE -p @trigger.json --stream '.data.threadId'",
525 - ],
526 - seeAlso: [
527 - 'composio artifacts cwd Print the current session artifact directory',
528 - 'composio triggers info <slug> Inspect trigger type details before listening',
529 - 'composio link <toolkit> Connect the required account before creating the trigger',
530 - ],
531 - }),
532 - link: {
533 - usage: 'composio link [<toolkit>] [--no-wait] [--no-browser] [--alias text] [--list]',
534 - description:
535 - 'Connect an external account (GitHub, Gmail, Slack, etc.) so tools can act on your behalf. Opens a browser for OAuth authorization and waits for confirmation.',
536 - args: [{ name: '<toolkit>', description: 'Toolkit slug to link (e.g. "github", "gmail")' }],
537 - options: [
538 - {
539 - name: '--alias <text>',
540 - description:
541 - 'Alias for the connected account. Required when creating an additional account for the same toolkit',
542 - },
543 - ],
544 - flags: [
545 - {
546 - name: '--no-wait',
547 - description: 'Print link info and exit without waiting for authorization',
548 - },
549 - {
550 - name: '--no-browser',
551 - description: 'Do not open the browser automatically; print the URL to open manually',
552 - },
553 - {
554 - name: '--list',
555 - description:
556 - 'List existing connected accounts for the toolkit instead of creating a new link',
557 - },
558 - ],
559 - examples: [
560 - 'composio link github',
561 - 'composio link gmail --alias work',
562 - 'composio link github --list',
563 - ],
564 - seeAlso: [
565 - 'composio search "<query>" Find tools to use after linking',
566 - "composio execute <slug> --account <alias> -d '{ ... }' Use a named account",
567 - 'composio connections list --toolkit <toolkit> List account selectors',
568 - ],
569 - },
570 - connections: {
571 - usage: 'composio connections <subcommand>',
572 - description: 'View and manage Composio connected accounts.',
573 - seeAlso: ['composio connections list', 'composio connections remove'],
574 - },
575 - 'connections list': {
576 - usage: 'composio connections list [--toolkit <text>]',
577 - description:
578 - 'Print connected toolkit statuses as JSON. Adds aliases when a toolkit has multiple connections.',
579 - options: [{ name: '--toolkit <text>', description: 'Filter to a single toolkit slug' }],
580 - examples: ['composio connections list', 'composio connections list --toolkit gmail'],
581 - seeAlso: [
582 - 'composio link <toolkit> Connect a new account for a toolkit',
583 - 'composio dev connected-accounts list Inspect the full connected-account table',
584 - ],
585 - },
586 - 'connections remove': {
587 - usage: 'composio connections remove <account>',
588 - description:
589 - 'Interactively remove a connected toolkit account. The command prompts for confirmation and defaults to No.',
590 - args: [
591 - {
592 - name: '<account>',
593 - description: 'Toolkit slug, alias, word_id, or connected account ID',
594 - },
595 - ],
596 - examples: [
597 - 'composio connections remove gmail',
598 - 'composio connections remove work',
599 - 'composio connections remove castle',
600 - ],
601 - seeAlso: [
602 - 'composio connections list Find connection selectors',
603 - 'composio link <toolkit> Reconnect a toolkit account',
604 - ],
605 - },
606 - run: {
607 - usage: 'composio run <code> [-- ...args] | run -f <file> [-- ...args]',
608 - description:
609 - 'Run inline TS/JS code or a file with injected Composio helpers that behave like their CLI counterparts.',
610 - args: [{ name: '<code>', description: 'Inline Bun ESNext code to evaluate' }],
611 - options: [
612 - { name: '-f, --file <text>', description: 'Run a TS/JS file instead of inline code' },
613 - { name: '--dry-run', description: 'Preview execute() calls without running them' },
614 - { name: '--debug', description: 'Log helper steps while the script runs' },
615 - {
616 - name: '--logs-off',
617 - description: 'Hide the always-on experimental_subAgent streaming logs',
618 - },
619 - ],
620 - flags: [
621 - { name: '--skip-connection-check', description: 'Skip the connected-account check' },
622 - {
623 - name: '--skip-tool-params-check',
624 - description: 'Skip input validation against cached schema',
625 - },
626 - { name: '--skip-checks', description: 'Skip both checks above' },
627 - ],
628 - injectedHelpers: [
629 - {
630 - name: 'execute(slug, data?)',
631 - description: 'Run a tool — same as `composio execute`, returns parsed JSON',
632 - },
633 - { name: 'search(query, opts?)', description: 'Find tools — same as `composio search`' },
634 - { name: 'proxy(toolkit)', description: 'Returns a fetch() bound to your connected account' },
635 - {
636 - name: 'experimental_subAgent(prompt, opts?)',
637 - description: 'Experimental sub-agent helper (Claude/Codex) with optional structured output',
638 - },
639 - {
640 - name: 'result.prompt()',
641 - description: 'Serialize any helper result into an LLM-friendly string',
642 - },
643 - { name: 'z', description: 'Global from zod for defining structured output schemas' },
644 - ],
645 - examples: [
646 - `composio run '`,
647 - ` // execute(slug, data?) — run a tool, returns parsed JSON`,
648 - ` const me = await execute("GITHUB_GET_THE_AUTHENTICATED_USER");`,
649 - ` console.log(me);`,
650 - `'`,
651 - '',
652 - `composio run '`,
653 - ` // search(query, opts?) — find tools by use case`,
654 - ` const tools = await search("send email");`,
655 - ` console.log(tools);`,
656 - `'`,
657 - '',
658 - '# Sequential: chain tool outputs across services',
659 - `composio run '`,
660 - ` const issue = await execute("GITHUB_CREATE_ISSUE", { owner: "acme", repo: "app", title: "Deploy v2" });`,
661 - ` await execute("SLACK_SEND_MESSAGE", { channel: "eng", markdown_text: "Created: " + issue.data.html_url });`,
662 - `'`,
663 - '',
664 - '# Parallel: fetch from multiple services at once with Promise.all',
665 - `composio run '`,
666 - ` const [emails, issues, events] = await Promise.all([`,
667 - ` execute("GMAIL_FETCH_EMAILS", { max_results: 5 }),`,
668 - ` execute("GITHUB_LIST_REPOSITORY_ISSUES", { owner: "composiohq", repo: "composio", state: "open" }),`,
669 - ` execute("GOOGLECALENDAR_FIND_EVENT", { calendar_id: "primary" }),`,
670 - ` ]);`,
671 - ` console.log({ emails: emails.data, issues: issues.data, events: events.data });`,
672 - `'`,
673 - '',
674 - '# Bulk: fan out with Promise.all + .map()',
675 - `composio run '`,
676 - ` const issues = [101, 102, 103, 104];`,
677 - ` await Promise.all(issues.map(n =>`,
678 - ` execute("GITHUB_ADD_LABELS_TO_ISSUE", { owner: "acme", repo: "app", issue_number: n, labels: ["priority"] })`,
679 - ` ));`,
680 - `'`,
681 - '',
682 - '# proxy(toolkit) — returns a fetch() bound to your connected account',
683 - `composio run '`,
684 - ` const f = await proxy("gmail");`,
685 - ` console.log(await f("https://gmail.googleapis.com/gmail/v1/users/me/profile"));`,
686 - `'`,
687 - '',
688 - '# experimental_subAgent + z + result.prompt() — structured output from a sub-agent',
689 - `composio run '`,
690 - ` const [emails, issues] = await Promise.all([`,
691 - ` execute("GMAIL_FETCH_EMAILS", { max_results: 5 }),`,
692 - ` execute("GITHUB_LIST_REPOSITORY_ISSUES", { owner: "composiohq", repo: "composio", state: "open" }),`,
693 - ` ]);`,
694 - ` // result.prompt() serializes helper output for LLM consumption`,
695 - ` // z is a global from zod for defining structured output schemas`,
696 - ` const brief = await experimental_subAgent(`,
697 - ` \`Summarize these emails and issues.\\n\\n\${emails.prompt()}\\n\\n\${issues.prompt()}\`,`,
698 - ` { schema: z.object({ summary: z.string(), urgent: z.array(z.string()) }) }`,
699 - ` );`,
700 - ` console.log(brief.structuredOutput);`,
701 - `'`,
702 - '',
703 - '# Run from a file',
704 - 'composio run --file ./workflow.ts -- --repo acme/app',
705 - ],
706 - seeAlso: [
707 - 'composio search "<query>" Discover tool slugs before scripting',
708 - 'composio link <toolkit> Connect accounts before scripting',
709 - 'composio execute <slug> --get-schema Inspect tool inputs before scripting',
710 - 'composio artifacts cwd Print the current session artifact directory',
711 - ],
712 - },
713 - proxy: {
714 - usage:
715 - 'composio proxy <url> --toolkit <text> [--account <selector>] [-X method] [-H header]... [-d data]',
716 - description:
717 - 'curl-like access to any toolkit API through Composio using your connected account. Composio handles authentication — just provide the full URL and toolkit.',
718 - args: [{ name: '<url>', description: 'Full API endpoint URL' }],
719 - options: [
720 - {
721 - name: '-t, --toolkit <text>',
722 - description: 'Toolkit slug whose connected account should be used',
723 - },
724 - {
725 - name: '--account <selector>',
726 - description: 'Select a connected account by alias, word_id, or connected account ID',
727 - },
728 - { name: '-X, --method <text>', description: 'HTTP method (GET, POST, PUT, DELETE, PATCH)' },
729 - {
730 - name: '-H, --header <text>',
731 - description: 'Header in "Name: value" format. Repeat for multiple.',
732 - },
733 - {
734 - name: '-d, --data <text>',
735 - description: 'Request body as raw text, JSON, @file, or - for stdin',
736 - },
737 - ],
738 - flags: [{ name: '--skip-connection-check', description: 'Skip the connected-account check' }],
739 - examples: [
740 - 'composio proxy https://gmail.googleapis.com/gmail/v1/users/me/profile --toolkit gmail --account work',
741 - `composio proxy https://gmail.googleapis.com/gmail/v1/users/me/drafts --toolkit gmail \\`,
742 - ` -X POST -H 'content-type: application/json' -d '{"message":{"raw":"..."}}'`,
743 - ],
744 - seeAlso: [
745 - 'composio link <toolkit> Connect an account first',
746 - `composio run 'const f = await proxy("gmail"); ...' Use proxy in a script`,
747 - ],
748 - },
749 -
750 - // ── Account commands ──────────────────────────────────────────────────
751 -
752 - agent: {
753 - usage: 'composio agent <subcommand>',
754 - description: 'Manage Composio agent identity, inbox, and handoff.',
755 - seeAlso: [
756 - 'composio agent signup',
757 - 'composio agent login',
758 - 'composio agent whoami',
759 - 'composio agent inbox',
760 - 'composio agent claim',
761 - ],
762 - },
763 - 'agent signup': {
764 - usage: 'composio agent signup [-f, --force] [--no-wait] [--no-login]',
765 - description: 'Sign up and optionally log in as a Composio agent.',
766 - options: [
767 - {
768 - name: '-f, --force',
769 - description: 'Create a new agent identity even if ~/.composio/agent.json already exists',
770 - },
771 - {
772 - name: '--no-wait',
773 - description: 'Start agent signup and exit without waiting for credentials',
774 - },
775 - {
776 - name: '--no-login',
777 - description: 'Create or verify the agent identity without logging the CLI in',
778 - },
779 - ],
780 - },
781 - 'agent login': {
782 - usage: 'composio agent login <composio_agent_key>',
783 - description: 'Log in with an existing Composio agent key.',
784 - args: [
785 - {
786 - name: '<composio_agent_key>',
787 - description: 'Composio agent key for an existing agent identity',
788 - },
789 - ],
790 - },
791 - 'agent whoami': {
792 - usage: 'composio agent whoami',
793 - description: 'Show the stored Composio agent identity.',
794 - },
795 - 'agent inbox': {
796 - usage: 'composio agent inbox [--limit integer]',
797 - description: 'Read the stored Composio agent inbox.',
798 - options: [
799 - {
800 - name: '--limit <integer>',
801 - description: 'Maximum number of inbox messages to fetch (default: 50)',
802 - },
803 - ],
804 - },
805 - 'agent claim': {
806 - usage: 'composio agent claim <email>',
807 - description: 'Invite a human admin to claim this agent org.',
808 - args: [
809 - {
810 - name: '<email>',
811 - description: 'Human email address to invite as an admin for this agent org',
812 - },
813 - ],
814 - },
815 - signup: {
816 - usage: 'composio signup [-f, --force] [--no-wait] [--no-login]',
817 - description: 'Sign up and optionally log in as a Composio agent.',
818 - options: [
819 - {
820 - name: '-f, --force',
821 - description: 'Create a new agent identity even if ~/.composio/agent.json already exists',
822 - },
823 - {
824 - name: '--no-wait',
825 - description: 'Start agent signup and exit without waiting for credentials',
826 - },
827 - {
828 - name: '--no-login',
829 - description: 'Create or verify the agent identity without logging the CLI in',
830 - },
831 - ],
832 - },
833 - login: {
834 - usage:
835 - 'composio login [--no-browser] [--poll] [--no-wait] [--key text] [--user-api-key text] [--org text] [-y, --yes] [--no-skill-install]',
836 - description:
837 - 'Log in to the Composio CLI session. By default, also installs the composio-cli skill for Claude Code.',
838 - options: [
839 - {
840 - name: '--key <text>',
841 - description: 'Poll and complete login using the session key from composio login',
842 - },
843 - {
844 - name: '--user-api-key <text>',
845 - description: 'Log in directly with a Composio user API key',
846 - },
847 - {
848 - name: '--org <text>',
849 - description: 'Current organization ID or name to store for CLI commands',
850 - },
851 - ],
852 - flags: [
853 - { name: '--no-browser', description: 'Login without browser interaction' },
854 - {
855 - name: '--poll',
856 - description: 'Poll the cached pending login key for up to 10 minutes',
857 - },
858 - { name: '--no-wait', description: 'Print login URL and session info, then exit' },
859 - { name: '-y, --yes', description: 'Skip org picker; use current org' },
860 - {
861 - name: '--no-skill-install',
862 - description: 'Skip installing the composio-cli skill for Claude Code',
863 - },
864 - ],
865 - },
866 - logout: {
867 - usage: 'composio logout',
868 - description: 'Log out from the Composio CLI session.',
869 - },
870 - whoami: {
871 - usage: 'composio whoami',
872 - description: 'Display your account information.',
873 - },
874 - orgs: {
875 - usage: 'composio orgs <subcommand>',
876 - description: 'Manage default global organization/project context.',
877 - seeAlso: ['composio orgs list', 'composio orgs switch'],
878 - },
879 - 'orgs list': {
880 - usage: 'composio orgs list [--limit integer]',
881 - description: 'List organizations and show current global selection.',
882 - options: [
883 - {
884 - name: '--limit <integer>',
885 - description: 'Max organizations to fetch from API (default: 50)',
886 - },
887 - ],
888 - },
889 - 'orgs switch': {
890 - usage: 'composio orgs switch [--org-id text] [--limit integer]',
891 - description: 'Switch current organization context.',
892 - options: [
893 - { name: '--org-id <text>', description: 'Organization ID to use as global default' },
894 - {
895 - name: '--limit <integer>',
896 - description: 'Max orgs to fetch from API (default: 50)',
897 - },
898 - ],
899 - },
900 - setup: {
901 - usage: 'composio setup [--target auto|claude|codex|all] [--uninstall] [--yes] [--if-present]',
902 - description: 'Install or uninstall plugins for supported agent hosts.',
903 - examples: [
904 - 'composio setup',
905 - 'composio setup --target auto --yes',
906 - 'composio setup --uninstall --target auto --yes',
907 - 'composio setup --target all',
908 - ],
909 - options: [
910 - { name: '--target <target>', description: 'auto, claude, codex, or all' },
911 - { name: '-y, --yes', description: 'Accept setup changes without prompting' },
912 - {
913 - name: '--uninstall',
914 - description: 'Uninstall Composio plugins instead of installing them',
915 - },
916 - {
917 - name: '--if-present',
918 - description: 'Exit successfully when automatic detection finds no supported host',
919 - },
920 - ],
921 - },
922 - version: {
923 - usage: 'composio version',
924 - description: 'Display the current Composio CLI version.',
925 - },
926 - upgrade: {
927 - usage: 'composio upgrade',
928 - description: 'Upgrade your Composio CLI to the latest available version.',
929 - },
930 - files: {
931 - usage: 'composio files',
932 - description: 'Where the Composio CLI stores data on disk.',
933 - examples: [
934 - '~/.composio/',
935 - ' CLI configuration and cache directory.',
936 - ' user_data.json Your auth state (API key, org, base URL)',
937 - ' toolkits.json Cached toolkit list from the API',
938 - ' tools.json Cached tool definitions',
939 - ' trigger-types.json Cached trigger type definitions',
940 - ' consumer-short-term-cache.json Per-org connected toolkits cache (15-min TTL)',
941 - ' analytics.json Anonymous install ID for telemetry',
942 - '',
943 - ' All caches are safe to delete — they will be re-fetched on next use.',
944 - '',
945 - '$TMPDIR/composio/ (or COMPOSIO_SESSION_DIR / COMPOSIO_CACHE_DIR)',
946 - ' Session artifacts directory. Each CLI session gets a unique subdirectory',
947 - ' scoped to your working directory. Stores session history and files',
948 - ' created during `run` and `execute` (e.g. large tool outputs).',
949 - ' Use `composio artifacts cwd` to print the current session path.',
950 - '',
951 - '.composio/ (per-project, optional)',
952 - ' Per-directory project config. Scoped to the nearest parent that has one.',
953 - ' .env Allows COMPOSIO_ORG_ID and COMPOSIO_PROJECT_ID overrides',
954 - ' project.json Project context (org, project binding)',
955 - '',
956 - 'Environment variables that control paths:',
957 - ' COMPOSIO_SESSION_DIR Override session artifacts root',
958 - ' COMPOSIO_CACHE_DIR Override cache directory (also used for artifacts fallback)',
959 - ' COMPOSIO_CACHE_DIR is useful in sandboxed environments where ~/.composio or',
960 - ' $TMPDIR may not be writable.',
961 - ],
962 - },
963 -
964 - artifacts: {
965 - usage: 'composio artifacts <subcommand>',
966 - description: 'Inspect session artifact directories.',
967 - seeAlso: ['composio artifacts cwd'],
968 - },
969 - 'artifacts cwd': {
970 - usage: 'composio artifacts cwd',
971 - description: 'Print the cwd-scoped session artifact directory.',
972 - },
973 - install: {
974 - usage: 'composio install [--completions] [--shell zsh|bash|fish]',
975 - description:
976 - 'Set up shell integration (PATH and completions). Set COMPOSIO_BIN_DIR to choose the directory added to PATH; it otherwise defaults to ~/.local/bin when that holds this executable, and to the directory of the running binary.',
977 - options: [
978 - { name: '--completions', description: 'Also install shell completions (skipped by default)' },
979 - {
980 - name: '--shell <shell>',
981 - description: 'Override automatic shell detection: zsh, bash, or fish',
982 - },
983 - {
984 - name: '--no-completions',
985 - description: 'Deprecated: shell completions are skipped by default',
986 - },
987 - ],
988 - },
989 -
990 - // ── Tools commands ──────────────────────────────────────────────────────
991 -
992 - tools: {
993 - usage: 'composio tools <command>',
994 - description: 'Browse and inspect tools before executing them.',
995 - examples: ['composio tools list gmail', 'composio tools info GMAIL_SEND_EMAIL'],
996 - seeAlso: [
997 - 'composio search "<query>" Find tools by use case',
998 - "composio execute <slug> -d '{ ... }' Execute a tool directly",
999 - ],
1000 - },
1001 - 'tools list': {
1002 - usage: 'composio tools list <toolkit> [--query text] [--tags text] [--limit integer]',
1003 - description: 'List available tools for a toolkit.',
1004 - args: [{ name: '<toolkit>', description: 'Toolkit slug to list tools for (e.g. "gmail")' }],
1005 - options: [
1006 - { name: '--query <text>', description: 'Text search by name, slug, or description' },
1007 - { name: '--tags <text>', description: 'Filter by tags (e.g. "important")' },
1008 - { name: '--limit <integer>', description: 'Maximum number of results (1-1000)' },
1009 - ],
1010 - },
1011 - 'tools info': {
1012 - usage: 'composio tools info [<slug>]',
1013 - description:
1014 - 'View a brief summary of a tool and show the CLI-facing schema used by `composio execute --get-schema`.',
1015 - args: [{ name: '<slug>', description: 'Tool slug (e.g. "GMAIL_SEND_EMAIL")' }],
1016 - },
1017 - triggers: {
1018 - usage: 'composio triggers <subcommand>',
1019 - description: 'Inspect and subscribe to trigger events.',
1020 - seeAlso: ['composio triggers list', 'composio triggers info'],
1021 - },
1022 - 'triggers list': {
1023 - usage: 'composio triggers list <toolkit> [--limit integer]',
1024 - description: 'List available trigger types for a toolkit.',
1025 - args: [
1026 - { name: '<toolkit>', description: 'Toolkit slug to list trigger types for (e.g. "gmail")' },
1027 - ],
1028 - options: [{ name: '--limit <integer>', description: 'Number of results' }],
1029 - },
1030 - 'triggers info': {
1031 - usage: 'composio triggers info [<slug>]',
1032 - description: 'View details of a specific trigger type.',
1033 - args: [{ name: '<slug>', description: 'Trigger slug' }],
1034 - },
1035 -
1036 - // ── Generate commands ─────────────────────────────────────────────────
1037 -
1038 - generate: {
1039 - usage: 'composio generate [--output-dir dir] [--type-tools] --toolkits text...',
1040 - description:
1041 - 'Generate type stubs for toolkits, tools, and triggers, auto-detecting project language (TypeScript | Python).',
1042 - options: [
1043 - { name: '-o, --output-dir <dir>', description: 'Output directory for type stubs' },
1044 - {
1045 - name: '--toolkits <text>... (required)',
1046 - description: 'Toolkits to generate for (repeat for multiple)',
1047 - },
1048 - ],
1049 - flags: [
1050 - {
1051 - name: '--type-tools',
1052 - description: 'Generate typed input/output schemas for each tool (slower)',
1053 - },
1054 - ],
1055 - },
1056 - 'generate ts': {
1057 - usage:
1058 - 'composio generate ts [--output-dir dir] [--compact] [--transpiled] [--type-tools] --toolkits text...',
1059 - description: 'Generate TypeScript type stubs for toolkits, tools, and triggers.',
1060 - options: [
1061 - {
1062 - name: '-o, --output-dir <dir>',
1063 - description: 'Output directory for generated TypeScript stubs',
1064 - },
1065 - {
1066 - name: '--toolkits <text>... (required)',
1067 - description: 'Toolkits to generate for (repeat for multiple)',
1068 - },
1069 - ],
1070 - flags: [
1071 - { name: '--compact', description: 'Emit a single TypeScript file' },
1072 - {
1073 - name: '--transpiled',
1074 - description: 'Emit transpiled JavaScript alongside TypeScript files',
1075 - },
1076 - {
1077 - name: '--type-tools',
1078 - description: 'Generate typed input/output schemas for each tool (slower)',
1079 - },
1080 - ],
1081 - },
1082 - 'generate py': {
1083 - usage: 'composio generate py [--output-dir dir] --toolkits text...',
1084 - description: 'Generate Python type stubs for toolkits, tools, and triggers.',
1085 - options: [
1086 - {
1087 - name: '-o, --output-dir <dir>',
1088 - description: 'Output directory for generated Python stubs',
1089 - },
1090 - {
1091 - name: '--toolkits <text>... (required)',
1092 - description: 'Toolkits to generate for (repeat for multiple)',
1093 - },
1094 - ],
1095 - },
1096 -
1097 - // ── Dev commands ──────────────────────────────────────────────────────
1098 -
1099 - 'dev init': {
1100 - usage: 'composio dev init [--no-browser] [-y, --yes]',
1101 - description: 'Initialize this directory with a developer project.',
1102 - flags: [
1103 - { name: '--no-browser', description: 'Login without browser interaction' },
1104 - { name: '-y, --yes', description: 'Auto-select the current org project' },
1105 - ],
1106 - },
1107 - 'dev playground-execute': {
1108 - usage:
1109 - 'composio dev playground-execute <slug> [-d, --data text] [--file path] [--user-id text] [--project-name text] [--dry-run] [--get-schema]',
1110 - description:
1111 - 'Test tool executions against playground users using your developer project auth configs.',
1112 - args: [{ name: '<slug>', description: 'Tool slug (e.g. "GITHUB_CREATE_ISSUE")' }],
1113 - options: [
1114 - { name: '-d, --data <text>', description: 'JSON arguments, @file, or - for stdin' },
1115 - {
1116 - name: '--file <path>',
1117 - description: 'Inject a local file path into the single file_uploadable input',
1118 - },
1119 - { name: '--user-id <text>', description: 'Developer-project user ID override' },
1120 - { name: '--project-name <text>', description: 'Developer project name override' },
1121 - {
1122 - name: '--get-schema',
1123 - description: 'Fetch and print the CLI-facing input schema without executing',
1124 - },
1125 - { name: '--dry-run', description: 'Validate and preview without executing' },
1126 - ],
1127 - flags: [
1128 - { name: '--skip-connection-check', description: 'Skip the connected-account check' },
1129 - {
1130 - name: '--skip-tool-params-check',
1131 - description: 'Skip input validation against cached schema',
1132 - },
1133 - { name: '--skip-checks', description: 'Skip both checks above' },
1134 - ],
1135 - },
1136 - 'dev listen': {
1137 - usage:
1138 - 'composio dev listen [--toolkits text] [--trigger-slug text] [--json] [--table] [--max-events int] [--forward url] [--out file]',
1139 - description:
1140 - 'Listen to realtime trigger events for your developer project and optionally forward them.',
1141 - options: [
1142 - { name: '--toolkits <text>', description: 'Filter by toolkit slugs, comma-separated' },
1143 - { name: '--trigger-id <text>', description: 'Filter by trigger id' },
1144 - { name: '--connected-account-id <text>', description: 'Filter by connected account id' },
1145 - { name: '--trigger-slug <text>', description: 'Filter by trigger slug, comma-separated' },
1146 - { name: '--user-id <text>', description: 'Filter by user id' },
1147 - { name: '--max-events <int>', description: 'Stop after receiving N matching events' },
1148 - { name: '--forward <url>', description: 'Forward each event to the given URL' },
1149 - { name: '--out <file>', description: 'Append each event to this file' },
1150 - ],
1151 - flags: [
1152 - { name: '--json', description: 'Show raw event payload as JSON' },
1153 - { name: '--table', description: 'Show compact table rows' },
1154 - ],
1155 - },
1156 - // ── Dev admin commands ─────────────────────────────────────────────────
1157 -
1158 - 'dev toolkits list': {
1159 - usage:
1160 - 'composio dev toolkits list [--query text] [--limit integer] [--connected] [--user-id text]',
1161 - description: 'List available toolkits with connection status.',
1162 - options: [
1163 - { name: '--query <text>', description: 'Text search by name, slug, or description' },
1164 - { name: '--limit <integer>', description: 'Maximum number of results (1-1000)' },
1165 - { name: '--user-id <text>', description: 'User ID override' },
1166 - ],
1167 - flags: [{ name: '--connected', description: 'Show only connected toolkits' }],
1168 - },
1169 - 'dev toolkits info': {
1170 - usage: 'composio dev toolkits info [--user-id text] [-a, --all] [<slug>]',
1171 - description: 'View details of a specific toolkit.',
1172 - args: [{ name: '<slug>', description: 'Toolkit slug (e.g. "github")' }],
1173 - flags: [{ name: '-a, --all', description: 'Show all details' }],
1174 - },
1175 - 'dev toolkits search': {
1176 - usage: 'composio dev toolkits search <query> [--limit integer]',
1177 - description: 'Search toolkits by use case.',
1178 - args: [{ name: '<query>', description: 'Search query' }],
1179 - options: [{ name: '--limit <integer>', description: 'Number of results' }],
1180 - },
1181 - 'dev toolkits version': {
1182 - usage: 'composio dev toolkits version <slug>',
1183 - description: 'Show latest and recent versions for a toolkit.',
1184 - args: [{ name: '<slug>', description: 'Toolkit slug' }],
1185 - },
1186 - 'dev auth-configs list': {
1187 - usage: 'composio dev auth-configs list [--toolkits text] [--query text] [--limit integer]',
1188 - description: 'List auth configs.',
1189 - options: [
1190 - { name: '--toolkits <text>', description: 'Filter by toolkit slugs' },
1191 - { name: '--query <text>', description: 'Search text' },
1192 - { name: '--limit <integer>', description: 'Number of results' },
1193 - ],
1194 - },
1195 - 'dev auth-configs info': {
1196 - usage: 'composio dev auth-configs info [<id>]',
1197 - description: 'View details of a specific auth config.',
1198 - args: [{ name: '<id>', description: 'Auth config ID' }],
1199 - },
1200 - 'dev auth-configs create': {
1201 - usage:
1202 - 'composio dev auth-configs create --toolkit text [--auth-scheme text] [--scopes text] [--custom-credentials text] [<name>]',
1203 - description: 'Create a new auth config.',
1204 - args: [{ name: '<name>', description: 'Auth config name' }],
1205 - options: [
1206 - { name: '--toolkit <text>', description: 'Toolkit slug' },
1207 - { name: '--auth-scheme <text>', description: 'Authentication scheme' },
1208 - { name: '--scopes <text>', description: 'Comma-separated scopes' },
1209 - { name: '--custom-credentials <text>', description: 'Custom credentials JSON' },
1210 - ],
1211 - },
1212 - 'dev connected-accounts list': {
1213 - usage:
1214 - 'composio dev connected-accounts list [--toolkits text] [--user-id text] [--status text] [--limit integer]',
1215 - description: 'List connected accounts.',
1216 - options: [
1217 - { name: '--toolkits <text>', description: 'Filter by toolkit slugs' },
1218 - { name: '--user-id <text>', description: 'Filter by user id' },
1219 - { name: '--status <text>', description: 'Filter by status (ACTIVE, FAILED, EXPIRED, etc.)' },
1220 - { name: '--limit <integer>', description: 'Number of results' },
1221 - ],
1222 - },
1223 - 'dev connected-accounts info': {
1224 - usage: 'composio dev connected-accounts info [<id>]',
1225 - description: 'View details of a specific connected account.',
1226 - args: [{ name: '<id>', description: 'Connected account ID' }],
1227 - },
1228 - 'dev connected-accounts whoami': {
1229 - usage: 'composio dev connected-accounts whoami [<id>]',
1230 - description: 'Show the external account profile for a connected account.',
1231 - args: [{ name: '<id>', description: 'Connected account ID' }],
1232 - },
1233 - 'dev triggers list': {
1234 - usage: 'composio dev triggers list <toolkit> [--limit integer]',
1235 - description: 'List available trigger types for a toolkit.',
1236 - args: [
1237 - { name: '<toolkit>', description: 'Toolkit slug to list trigger types for (e.g. "gmail")' },
1238 - ],
1239 - options: [{ name: '--limit <integer>', description: 'Number of results' }],
1240 - },
1241 - 'dev triggers info': {
1242 - usage: 'composio dev triggers info [<slug>]',
1243 - description: 'View details of a specific trigger type.',
1244 - args: [{ name: '<slug>', description: 'Trigger slug' }],
1245 - },
1246 - 'dev triggers status': {
1247 - usage:
1248 - 'composio dev triggers status [--user-ids text] [--toolkits text] [--trigger-ids text] [--show-disabled] [--limit integer]',
1249 - description: 'Show active triggers with optional filters.',
1250 - options: [
1251 - { name: '--user-ids <text>', description: 'Filter by user IDs' },
1252 - { name: '--connected-account-ids <text>', description: 'Filter by connected account IDs' },
1253 - { name: '--toolkits <text>', description: 'Filter by toolkit slugs' },
1254 - { name: '--trigger-ids <text>', description: 'Filter by trigger IDs' },
1255 - { name: '--trigger-names <text>', description: 'Filter by trigger names' },
1256 - { name: '--limit <integer>', description: 'Number of results' },
1257 - ],
1258 - flags: [{ name: '--show-disabled', description: 'Include disabled triggers' }],
1259 - },
1260 - 'dev triggers create': {
1261 - usage:
1262 - 'composio dev triggers create [--connected-account-id text] [--trigger-config text] [<trigger-name>]',
1263 - description: 'Create a new trigger instance.',
1264 - args: [{ name: '<trigger-name>', description: 'Trigger type slug' }],
1265 - options: [
1266 - { name: '--connected-account-id <text>', description: 'Connected account to use' },
1267 - { name: '--trigger-config <text>', description: 'Trigger configuration JSON' },
1268 - ],
1269 - },
1270 - 'dev triggers enable': {
1271 - usage: 'composio dev triggers enable [<id>]',
1272 - description: 'Enable a trigger instance.',
1273 - args: [{ name: '<id>', description: 'Trigger instance ID' }],
1274 - },
1275 - 'dev triggers disable': {
1276 - usage: 'composio dev triggers disable [<id>]',
1277 - description: 'Disable a trigger instance.',
1278 - args: [{ name: '<id>', description: 'Trigger instance ID' }],
1279 - },
1280 - 'dev projects list': {
1281 - usage: 'composio dev projects list [--org-id text] [--limit integer]',
1282 - description: 'List developer projects for the current organization.',
1283 - options: [
1284 - { name: '--org-id <text>', description: 'Organization ID override' },
1285 - { name: '--limit <integer>', description: 'Number of results' },
1286 - ],
1287 - },
1288 -
1289 - // ── Dev logs commands ─────────────────────────────────────────────────
1290 -
1291 - 'dev logs tools': {
1292 - usage:
1293 - 'composio dev logs tools [--toolkit text] [--tool text] [--status text] [--limit integer] [<log_id>]',
1294 - description: 'List tool execution logs, or pass a log_id to fetch a specific log.',
1295 - args: [{ name: '<log_id>', description: 'Specific log ID to fetch' }],
1296 - options: [
1297 - { name: '--toolkit <text>', description: 'Filter by toolkit slug' },
1298 - { name: '--tool <text>', description: 'Filter by tool slug' },
1299 - { name: '--status <text>', description: 'Filter by status' },
1300 - { name: '--user-id <text>', description: 'Filter by user id' },
1301 - { name: '--limit <integer>', description: 'Number of results' },
1302 - { name: '--from <integer>', description: 'Start timestamp (epoch ms)' },
1303 - { name: '--to <integer>', description: 'End timestamp (epoch ms)' },
1304 - ],
1305 - flags: [{ name: '--case-sensitive', description: 'Case-sensitive filtering' }],
1306 - },
1307 - config: {
1308 - usage: 'composio config <subcommand>',
1309 - description: 'View and manage CLI configuration.',
1310 - seeAlso: ['composio config experimental'],
1311 - },
1312 - 'config experimental': {
1313 - usage: 'composio config experimental [<feature>] [on|off]',
1314 - description: 'View or toggle experimental feature flags.',
1315 - args: [
1316 - { name: '<feature>', description: 'Feature name (e.g., listen)' },
1317 - { name: 'on|off', description: 'Enable or disable the feature' },
1318 - ],
1319 - examples: [
1320 - 'composio config experimental # List all features',
1321 - 'composio config experimental listen # Show current state',
1322 - 'composio config experimental listen on # Enable listen',
1323 - ],
1324 - },
1325 - 'dev logs triggers': {
1326 - usage:
1327 - 'composio dev logs triggers [--trigger text] [--trigger-id text] [--limit integer] [--time 5m|30m|6h|1d|1w] [<log_id>]',
1328 - description: 'List trigger logs.',
1329 - args: [{ name: '<log_id>', description: 'Specific log ID to fetch' }],
1330 - options: [
1331 - { name: '--trigger <text>', description: 'Filter by trigger slug' },
1332 - { name: '--trigger-id <text>', description: 'Filter by trigger id' },
1333 - { name: '--user-id <text>', description: 'Filter by user id' },
1334 - { name: '--connected-account-id <text>', description: 'Filter by connected account id' },
1335 - { name: '--limit <integer>', description: 'Number of results' },
1336 - { name: '--time <period>', description: 'Time window (5m, 30m, 6h, 1d, 1w, 1month, 1y)' },
1337 - { name: '--search <text>', description: 'Search in log content' },
1338 - ],
1339 - flags: [{ name: '--include-payload', description: 'Include full event payload' }],
1340 - },
1341 -};
1342 -
1343 -const getVisibleSubcommandHelp = (
1344 - cmd: string,
1345 - visibility: CommandVisibility,
1346 - helpLevel: HelpLevel = 'default'
1347 -): Option.Option<SubcommandHelp> => {
1348 - if (cmd === 'dev') {
1349 - return Option.some({
1350 - usage: 'composio dev [--mode on|off]',
1351 - description: 'Developer mode and developer-scoped workflows.',
1352 - });
1353 - }
1354 -
1355 - if (cmd.startsWith('dev ') && !visibility.isDevModeEnabled) {
1356 - return Option.none();
1357 - }
1358 -
1359 - const entry = SUBCOMMAND_HELP[cmd];
1360 - if (!entry) {
1361 - return Option.none();
1362 - }
1363 -
1364 - if (!('value' in entry)) {
1365 - return Option.some(entry);
1366 - }
1367 -
1368 - return isTaggedValueVisible(entry, visibility) &&
1369 - isTaggedValueVisibleForHelpLevel(entry, helpLevel)
1370 - ? Option.some(entry.value)
1371 - : Option.none();
20 + ...formatter,
21 + formatVersion: (_name: string, version: string) => version,
22 + formatHelpDoc: (doc: Parameters<typeof formatter.formatHelpDoc>[0]) => {
23 + const text = formatter.formatHelpDoc(doc);
24 + return Context.get(doc.annotations, RootHelpMarker)
25 + ? `${text}\n\nUse \`composio <command> --help\` for command details.\nDocumentation: https://docs.composio.dev`
26 + : text;
27 + },
28 + } satisfies CliOutput.Formatter;
29 };
30
1374 -function renderSubcommandHelp(cmd: SubcommandHelp, helpLevel: HelpLevel): string {
1375 - const lines: string[] = [
1376 - '',
1377 - bold('USAGE'),
1378 - ` ${cmd.usage}`,
1379 - '',
1380 - bold('DESCRIPTION'),
1381 - ` ${cmd.description}`,
1382 - '',
1383 - ];
1384 -
1385 - if (cmd.args && cmd.args.length > 0) {
1386 - lines.push(bold('ARGUMENTS'));
1387 - for (const arg of cmd.args) {
1388 - lines.push(` ${dim(arg.name.padEnd(24))}${arg.description}`);
1389 - }
1390 - lines.push('');
1391 - }
1392 -
1393 - if (cmd.options && cmd.options.length > 0) {
1394 - lines.push(bold('OPTIONS'));
1395 - for (const opt of cmd.options) {
1396 - lines.push(` ${dim(opt.name.padEnd(24))}${opt.description}`);
1397 - }
1398 - lines.push('');
1399 - }
1400 -
1401 - if (cmd.flags && cmd.flags.length > 0) {
1402 - lines.push(bold('FLAGS'));
1403 - for (const flag of cmd.flags) {
1404 - lines.push(` ${dim(flag.name.padEnd(28))}${flag.description}`);
1405 - }
1406 - lines.push('');
1407 - }
1408 -
1409 - if (helpLevel !== 'simple' && cmd.injectedHelpers && cmd.injectedHelpers.length > 0) {
1410 - lines.push(bold('INJECTED HELPERS'));
1411 - const maxLen = Math.max(...cmd.injectedHelpers.map(h => h.name.length));
1412 - for (const helper of cmd.injectedHelpers) {
1413 - lines.push(` ${dim(helper.name.padEnd(maxLen + 2))}${helper.description}`);
1414 - }
1415 - lines.push('');
1416 - }
1417 -
1418 - if (helpLevel !== 'simple' && cmd.examples && cmd.examples.length > 0) {
1419 - lines.push(bold('EXAMPLES'));
1420 - for (const ex of cmd.examples) {
1421 - lines.push(` ${ex}`);
1422 - }
1423 - lines.push('');
1424 - }
1425 -
1426 - if (helpLevel !== 'simple' && cmd.seeAlso && cmd.seeAlso.length > 0) {
1427 - lines.push(bold('SEE ALSO'));
1428 - for (const sa of cmd.seeAlso) {
1429 - lines.push(` ${sa}`);
1430 - }
1431 - lines.push('');
1432 - }
1433 -
1434 - return lines.join('\n');
1435 -}
1436 -
1437 -/**
1438 - * Check if argv is `composio <subcommand> --help` for a command we have custom help for.
1439 - * Returns the command name if matched, undefined otherwise.
1440 - */
1441 -export function matchSubcommandHelp(
1442 - argv: ReadonlyArray<string>,
1443 - visibility: CommandVisibility
1444 -): string | undefined {
1445 - const { args } = splitTrailingHelpLevel(argv.slice(2));
1446 - if (args.length < 2) return undefined;
1447 - const last = args[args.length - 1];
1448 - if (last !== '--help' && last !== '-h') return undefined;
1449 -
1450 - const cmdParts = args.slice(0, -1);
1451 - // Try longest match first: "dev toolkits list" → "dev toolkits" → "dev"
1452 - for (let len = cmdParts.length; len > 0; len--) {
1453 - const key = cmdParts.slice(0, len).join(' ');
1454 - if (Option.isSome(getVisibleSubcommandHelp(key, visibility))) return key;
1455 - }
1456 - return undefined;
1457 -}
1458 -
1459 -export function printSubcommandHelp(
1460 - cmd: string,
1461 - visibility: CommandVisibility,
1462 - helpLevel: HelpLevel = 'default'
1463 -): Effect.Effect<void, never, TerminalUI> {
1464 - if (cmd === 'dev') {
1465 - return Effect.flatMap(TerminalUI, ui =>
1466 - ui.output(renderDevHelp(visibility, helpLevel), { force: true })
31 +export const showCommandHelp = (parts: ReadonlyArray<string> = []) =>
32 + Effect.gen(function* () {
33 + const { command, version } = yield* RootHelpContext;
34 + const { builtIns } = yield* CliConfig.CliConfig;
35 + const console = yield* Console.Console;
36 + yield* GlobalFlag.Help.run(true, {
37 + command,
38 + commandPath: [command.name, ...parts],
39 + version,
40 + builtIns,
41 + }).pipe(
42 + Effect.provideService(Console.Console, {
43 + ...console,
44 + log: (...args) => console.info(...args),
45 + })
46 );
1468 - }
1469 - const help = getVisibleSubcommandHelp(cmd, visibility, helpLevel);
1470 - if (Option.isNone(help)) {
1471 - return Effect.flatMap(TerminalUI, ui => ui.output(`Unknown command: ${cmd}`, { force: true }));
1472 - }
1473 - return Effect.flatMap(TerminalUI, ui =>
1474 - ui.output(renderSubcommandHelp(help.value, helpLevel), { force: true })
1475 - );
1476 -}
1477 -
1478 -/**
1479 - * Match the command name from argv without requiring --help at the end.
1480 - * Used to print contextual help alongside error messages.
1481 - */
1482 -export function matchCommandFromArgv(
1483 - argv: ReadonlyArray<string>,
1484 - visibility: CommandVisibility
1485 -): string | undefined {
1486 - const { args: helpArgs } = splitTrailingHelpLevel(argv.slice(2));
1487 - const args = helpArgs.filter(a => a !== '--help' && a !== '-h' && !a.startsWith('--'));
1488 - // Try longest match first: "dev toolkits list" → "dev toolkits" → "dev"
1489 - for (let len = Math.min(args.length, 3); len > 0; len--) {
1490 - const key = args.slice(0, len).join(' ');
1491 - if (Option.isSome(getVisibleSubcommandHelp(key, visibility))) return key;
1492 - }
1493 - return undefined;
1494 -}
1495 -
1496 -/**
1497 - * Get rendered help text for a command, or undefined if not found.
1498 - */
1499 -export function getCommandHelpText(cmd: string, visibility: CommandVisibility): string | undefined {
1500 - if (cmd === 'dev') return renderDevHelp(visibility);
1501 - return Option.match(getVisibleSubcommandHelp(cmd, visibility), {
1502 - onNone: () => undefined,
1503 - onSome: help => renderSubcommandHelp(help, 'default'),
47 });
1505 -}
1506 -
1507 -// ── Main help output ───────────────────────────────────────────────────
48
1509 -/**
1510 - * Prints the root-level help output.
1511 - * Core workflow commands are shown first with full usage/options.
1512 - * Housekeeping and developer commands are shown compactly at the bottom.
1513 - */
1514 -export function printRootHelp(
1515 - visibility: CommandVisibility,
1516 - helpLevel: HelpLevel = 'default'
1517 -): Effect.Effect<void, never, TerminalUI> {
1518 - const name = 'composio';
1519 - const developerCommands: ReadonlyArray<CompactCommand> = [
1520 - {
1521 - name: 'dev',
1522 - description: visibility.isDevModeEnabled
1523 - ? 'Developer workflows and management: init, logs, projects, toolkits, accounts, and triggers.'
1524 - : 'Developer mode toggle. Use `composio dev --mode on` to enable developer workflows.',
1525 - },
1526 - GENERATE_COMMAND.value,
1527 - ];
1528 - const coreCommands = visibleValues(CORE_COMMANDS, visibility, helpLevel);
1529 - const otherCommands = visibleValues(OTHER_COMMANDS, visibility, helpLevel);
1530 - const accountCommands = visibleValues(ACCOUNT_COMMANDS, visibility, helpLevel);
1531 - const fullCommands = visibleValues(FULL_COMMANDS, visibility, helpLevel);
1532 - const exampleLines =
1533 - helpLevel === 'simple'
1534 - ? [
1535 - ` ${dim('# Find tools')}`,
1536 - ` ${name} search "send an email"`,
1537 - '',
1538 - ` ${dim('# Execute a tool')}`,
1539 - ` ${name} execute GITHUB_CREATE_ISSUE -d '{ owner: "acme", repo: "app", title: "Bug" }'`,
1540 - '',
1541 - ` ${dim('# Connect an account when execute tells you to')}`,
1542 - ` ${name} link github`,
1543 - '',
1544 - ]
1545 - : [
1546 - ` ${dim('# Find tools — supports multiple queries at once')}`,
1547 - ` ${name} search "send an email" "create github issue"`,
1548 - ` ${name} search "list calendar events" --toolkits google_calendar --limit 5`,
1549 - '',
1550 - ` ${dim('# Connect your account for a toolkit')}`,
1551 - ` ${name} link github`,
1552 - '',
1553 - ` ${dim('# Execute a tool')}`,
1554 - ` ${name} execute GITHUB_CREATE_ISSUE -d '{ owner: "acme", repo: "app", title: "Bug" }'`,
1555 - '',
1556 - ` ${dim('# Execute multiple tools in parallel')}`,
1557 - ` ${name} execute -p GMAIL_SEND_EMAIL -d '{ recipient_email: "a@b.com", subject: "Hi" }' \\`,
1558 - ` SLACK_SEND_MESSAGE -d '{ channel: "general", markdown_text: "Hello" }'`,
1559 - '',
1560 - ` ${dim('# Call an API directly through proxy')}`,
1561 - ` ${name} proxy https://gmail.googleapis.com/gmail/v1/users/me/profile --toolkit gmail`,
1562 - '',
1563 - ` ${dim('# Run a script with injected helpers')}`,
1564 - ` ${name} run 'const me = await execute("GITHUB_GET_THE_AUTHENTICATED_USER"); console.log(me)'`,
1565 - '',
1566 - ` ${dim('# Manually install the composio skill when auto-install fails')}`,
1567 - ` ${name} --install-skill claude`,
1568 - ` ${name} --install-skill composio-cli codex`,
1569 - '',
1570 - ` ${dim('# Run a multi-step script with Promise.all')}`,
1571 - ` ${name} run '`,
1572 - ` const [emails, issues] = await Promise.all([`,
1573 - ` execute("GMAIL_FETCH_EMAILS", { max_results: 5 }),`,
1574 - ` execute("GITHUB_LIST_REPOSITORY_ISSUES", { owner: "acme", repo: "app", state: "open" }),`,
1575 - ` ]);`,
1576 - ` const brief = await experimental_subAgent(\`Summarize:\\n\${emails.prompt()}\\n\${issues.prompt()}\`);`,
1577 - ` console.log(brief);`,
1578 - ` '`,
1579 - '',
1580 - ];
1581 -
1582 - const lines: string[] = [
1583 - '',
1584 - `Connect AI agents to external tools. ${bold('search')}, ${bold('execute')}, ${bold('link')}, ${bold('proxy')}, and ${bold('run')} let you`,
1585 - 'take actions across 1000+ apps directly; if you can describe it, it is probably supported.',
1586 - `Try ${bold('execute')} sooner than you'd think — it validates inputs, checks connections, and tells`,
1587 - 'you what to fix.',
1588 - '',
1589 - visibility.isDevModeEnabled
1590 - ? `Use ${bold('dev')} when you are building an agent with Composio's SDK and want scaffolding,`
1591 - : `Use ${bold('dev')} to control access to developer-only workflows.`,
1592 - visibility.isDevModeEnabled
1593 - ? 'playground execution, logs, and developer-scoped management commands.'
1594 - : 'Developer mode is currently off.',
1595 - '',
1596 - bold('USAGE'),
1597 - ` ${name} <command> [options]`,
1598 - ` ${name} --help [simple|default|full]`,
1599 - '',
1600 - bold('MODE'),
1601 - ` ${helpLevel} help`,
1602 - '',
1603 - bold('CORE COMMANDS'),
1604 - ...renderDetailedCommands(name, coreCommands),
1605 - gray(' Typical flow: search → execute (link and tools when needed)'),
1606 - '',
1607 - ...(otherCommands.length > 0
1608 - ? [bold('TOOLS'), ...renderCompactCommands(otherCommands), '']
1609 - : []),
1610 - '',
1611 - bold('EXAMPLES'),
1612 - ...exampleLines,
1613 - ...(developerCommands.length > 0
1614 - ? [bold('DEVELOPER COMMANDS'), ...renderCompactCommands(developerCommands), '']
1615 - : []),
1616 - ...(accountCommands.length > 0
1617 - ? [bold('ACCOUNT'), ...renderCompactCommands(accountCommands), '']
1618 - : []),
1619 - ...(fullCommands.length > 0
1620 - ? [bold('MORE COMMANDS'), ...renderCompactCommands(fullCommands), '']
1621 - : []),
1622 - bold('FILES') + dim(' (composio files --help)'),
1623 - ` ${bold('~/.composio/')}`,
1624 - ` CLI configuration and cache directory. Contains your auth state`,
1625 - ` (user_data.json), runtime settings (config.json), cached tool definitions`,
1626 - ` (tools.json, toolkits.json),`,
1627 - ` trigger types, and per-org consumer caches. These caches speed up`,
1628 - ` repeated commands — safe to delete, they will be re-fetched on next use.`,
1629 - '',
1630 - ` ${bold('/tmp/composio/')}`,
1631 - ` Session artifacts directory. Each CLI session gets a unique subdirectory`,
1632 - ` scoped to your working directory. Stores session history and files`,
1633 - ` created during ${bold('run')} and ${bold('execute')} commands (e.g. downloaded attachments,`,
1634 - ` generated outputs). Use \`${name} artifacts cwd\` to print the path for`,
1635 - ` the current directory's session.`,
1636 - '',
1637 - bold('FLAGS'),
1638 - ' -h, --help [mode] Show help for command (simple, default, full)',
1639 - ` --version Show ${name} version`,
1640 - ' --install-skill [skill-name] <claude|codex|openclaw>',
1641 - ' Manually install the composio skill for a supported agent',
1642 - '',
1643 - bold('LEARN MORE'),
1644 - ` Use \`${name} <command> --help\` for more information about a command.`,
1645 - ` Documentation: https://docs.composio.dev`,
1646 - '',
1647 - ];
49 +/** Derive help aliases from the real command tree, letting Effect validate names and suggest fixes. */
50 +export const buildHelpCommand = (commands: ReadonlyArray<Command.Command.Any>) => {
51 + const makeHelpCommand = (
52 + name: string,
53 + path: ReadonlyArray<string>,
54 + subcommands: ReadonlyArray<Command.Command.Any>,
55 + description: string | undefined
56 + ): Command.Command<string, Record<never, never>, Record<never, never>, never, RootHelpContext> =>
57 + Command.make(name, {}, () => showCommandHelp(path)).pipe(
58 + Command.withDescription(description ?? 'Show command help.'),
59 + Command.withSubcommands(
60 + subcommands.map(child => {
61 + const help = makeHelpCommand(
62 + child.name,
63 + [...path, child.name],
64 + child.subcommands.flatMap(group => group.commands),
65 + child.description
66 + );
67 + const aliased = child.alias ? help.pipe(Command.withAlias(child.alias)) : help;
68 + return child.unlisted ? aliased.pipe(Command.unlisted) : aliased;
69 + })
70 + )
71 + );
72 + return makeHelpCommand('help', [], commands, 'Show help for a command.');
73 +};
74
1649 - return Effect.flatMap(TerminalUI, ui => ui.output(lines.join('\n'), { force: true }));
1650 -}
75 +/** A help flag on the help alias describes the requested command. */
76 +export const Help = GlobalFlag.Action({
77 + flag: GlobalFlag.Help.flag,
78 + run: (value, context) =>
79 + GlobalFlag.Help.run(value, {
80 + ...context,
81 + commandPath:
82 + context.commandPath[1] === 'help'
83 + ? [context.commandPath[0], ...context.commandPath.slice(2)]
84 + : context.commandPath,
85 + }),
86 +});
ts/packages/cli/src/commands/run.cmd.ts
+89 -99
@@ -3,7 +3,7 @@ import { Argument, Command, Flag } from 'effect/unstable/cli';
3 import * as FileSystem from 'effect/FileSystem';
4 import * as Path from 'effect/Path';
5 import { ChildProcess, ChildProcessSpawner } from 'effect/unstable/process';
6 -import { Context, Data, Deferred, Duration, Effect, MutableRef, Option, Result } from 'effect';
6 +import { Data, Deferred, Duration, Effect, MutableRef, Option, Result } from 'effect';
7 import { APP_VERSION } from 'src/constants';
8 import { loadGenerationRuntime } from 'src/effects/generation-runtime';
9 import { APP_CONFIG, UNPREFIXED_CONFIG } from 'src/effects/app-config';
@@ -12,6 +12,7 @@ import { type RunHelperContext } from 'src/services/run-helpers-runtime';
12 import { warmToolInputDefinitions } from 'src/services/tool-input-validation';
13 import { ComposioUserContext } from 'src/services/user-context';
14 import {
15 + CLI_DEBUG_FLAG_NAMES,
16 debugFlagsToChildEnv,
17 isAcpOnlyEnabled,
18 isPerfDebugEnabled,
@@ -34,55 +35,69 @@ import { loadHostConfig } from 'src/services/config';
35 import { resolveCliConfigPath } from 'src/services/cli-user-config';
36 import { NodeOs } from 'src/services/node-os';
37
37 -const file = Flag.String('file').pipe(
38 +const RUN_FLAG_NAMES = {
39 + file: 'file',
40 + dryRun: 'dry-run',
41 + debug: 'debug',
42 + logsOff: 'logs-off',
43 + skipConnectionCheck: 'skip-connection-check',
44 + skipToolParamsCheck: 'skip-tool-params-check',
45 + skipChecks: 'skip-checks',
46 +} as const;
47 +
48 +const file = Flag.String(RUN_FLAG_NAMES.file).pipe(
49 Flag.withAlias('f'),
50 Flag.withDescription('Run a TS/JS file instead of inline code'),
51 Flag.optional
52 );
53
43 -const dryRun = Flag.Boolean('dry-run').pipe(
54 +const dryRun = Flag.Boolean(RUN_FLAG_NAMES.dryRun).pipe(
55 Flag.withDescription('Preview execute() calls without running them'),
56 Flag.withDefault(false)
57 );
47 -const debug = Flag.Boolean('debug').pipe(
58 +const debug = Flag.Boolean(RUN_FLAG_NAMES.debug).pipe(
59 Flag.withDescription('Log helper steps while the script runs'),
60 Flag.withDefault(false)
61 );
51 -const logsOff = Flag.Boolean('logs-off').pipe(
62 +const logsOff = Flag.Boolean(RUN_FLAG_NAMES.logsOff).pipe(
63 Flag.withDescription('Hide helper streaming logs; keep them only in the run log file.'),
64 Flag.withDefault(false)
65 );
55 -const skipConnectionCheck = Flag.Boolean('skip-connection-check').pipe(
66 +const skipConnectionCheck = Flag.Boolean(RUN_FLAG_NAMES.skipConnectionCheck).pipe(
67 Flag.withDescription('Skip the connected-account check'),
68 Flag.withDefault(false)
69 );
59 -const skipToolParamsCheck = Flag.Boolean('skip-tool-params-check').pipe(
70 +const skipToolParamsCheck = Flag.Boolean(RUN_FLAG_NAMES.skipToolParamsCheck).pipe(
71 Flag.withDescription('Skip input validation against cached schema'),
72 Flag.withDefault(false)
73 );
63 -const skipChecks = Flag.Boolean('skip-checks').pipe(
74 +const skipChecks = Flag.Boolean(RUN_FLAG_NAMES.skipChecks).pipe(
75 Flag.withDescription('Skip both connection and input validation checks'),
76 Flag.withDefault(false)
77 );
78
68 -/**
69 - * Flag surface of the `run` command as raw argv tokens, consumed by
70 - * `commands/index.ts`'s passthrough normalizer. Kept adjacent to the `Flag`
71 - * definitions above: adding, renaming, or aliasing a `run` flag MUST update
72 - * these sets, or the normalizer will demote the new flag (and everything
73 - * after it) to passthrough script arguments.
74 - */
75 -export const RUN_KNOWN_BOOLEAN_FLAGS: ReadonlySet<string> = new Set([
76 - '--dry-run',
77 - '--debug',
78 - '--logs-off',
79 - '--skip-connection-check',
80 - '--skip-tool-params-check',
81 - '--skip-checks',
79 +const runFlags = {
80 + file,
81 + dryRun,
82 + debug,
83 + logsOff,
84 + skipConnectionCheck,
85 + skipToolParamsCheck,
86 + skipChecks,
87 +};
88 +
89 +/** Share names with the passthrough adapter; the framework owns parsing the flag values. */
90 +export const RUN_KNOWN_VALUE_FLAGS = new Set([`--${RUN_FLAG_NAMES.file}`, '-f', '--log-level']);
91 +export const RUN_KNOWN_BOOLEAN_FLAGS = new Set([
92 + ...Object.values(RUN_FLAG_NAMES)
93 + .filter(name => name !== RUN_FLAG_NAMES.file)
94 + .map(name => `--${name}`),
95 + ...CLI_DEBUG_FLAG_NAMES.flatMap(name => [`--${name}`, `--no-${name}`]),
96 '--help',
97 '-h',
98 + '--version',
99 + '-v',
100 ]);
85 -export const RUN_KNOWN_VALUE_FLAGS: ReadonlySet<string> = new Set(['--file', '-f']);
101
102 const args = Argument.String('arg').pipe(
103 Argument.variadic(),
@@ -91,20 +106,6 @@ const args = Argument.String('arg').pipe(
106
107 const withArgDelimiter = (args: ReadonlyArray<string>) => (args.length > 0 ? ['--', ...args] : []);
108
94 -/**
95 - * Out-of-band passthrough tail for `run`'s script arguments. See
96 - * `splitRunPassthroughArgs` in `src/commands/index.ts` for the full
97 - * mechanism this exists for (lexer/parser facts + the handoff); that
98 - * function provides this reference for the scope of a single CLI
99 - * invocation. `undefined` here means no front door provided it (direct
100 - * programmatic/test invocations of this command), so the handler below
101 - * falls back to the parsed `Argument.variadic()` value.
102 - */
103 -export const RunPassthroughArgs = Context.Reference<ReadonlyArray<string> | undefined>(
104 - 'composio/cli/run/RunPassthroughArgs',
105 - { defaultValue: () => undefined }
106 -);
107 -
109 /**
110 * The source rewrites need the TypeScript compiler, which ships in the
111 * `generation-runtime` companion module next to the executable rather than in
@@ -449,69 +450,60 @@ const forwardSignalsToChild = (child: ChildProcessSpawner.ChildProcessHandle) =>
450 });
451
452 export const runCmd = Command.make('run', {
452 - file,
453 - dryRun,
454 - debug,
455 - logsOff,
456 - skipConnectionCheck,
457 - skipToolParamsCheck,
458 - skipChecks,
453 + ...runFlags,
454 args,
455 }).pipe(
456 Command.withDescription(
462 - [
463 - 'Run inline TS/JS code or a file with injected Composio helpers that behave like their CLI counterparts.',
464 - '',
465 - 'Examples:',
466 - ` composio run 'const issue = await execute("GITHUB_CREATE_ISSUE", { owner: "composiohq", repo: "composio", title: "Bug report" }); console.log(issue)'`,
467 - ` composio run --dry-run 'await execute("GMAIL_SEND_EMAIL", { recipient_email: "a@b.com", body: "Hello" })'`,
468 - ` composio run --debug 'const me = await execute("GITHUB_GET_THE_AUTHENTICATED_USER"); console.log(me)'`,
469 - ` composio run '`,
470 - ` const [emails, issues] = await Promise.all([`,
471 - ` execute("GMAIL_FETCH_EMAILS", { max_results: 5 }),`,
472 - ` execute("GITHUB_LIST_REPOSITORY_ISSUES", { owner: "composiohq", repo: "composio", state: "open" }),`,
473 - ` ]);`,
474 - ` const brief = await experimental_subAgent(`,
475 - ` \`Create a morning brief from these emails and issues.\\n\\n\${emails.prompt()}\\n\\n\${issues.prompt()}\`,`,
476 - ` {`,
477 - ` schema: z.object({`,
478 - ` brief: z.string(),`,
479 - ` urgentEmails: z.array(z.string()),`,
480 - ` urgentIssues: z.array(z.string()),`,
481 - ` }),`,
482 - ` }`,
483 - ` );`,
484 - ` brief.structuredOutput;`,
485 - ` '`,
486 - ' composio run --file ./script.ts -- hello world',
487 - '',
488 - 'Injected helpers (behave like their CLI counterparts):',
489 - ' execute(slug, data?) Same as `composio execute` — returns parsed JSON',
490 - ' search(query, options?) Same as `composio search` — returns matching tools',
491 - ' experimental_subAgent(prompt, options?) Experimental helper to spawn a powerful sub-agent from the same agent family as your current main agent',
492 - ' (Codex -> Codex, Claude -> Claude) with optional Zod structured output',
493 - ' result.prompt() Prompt-safe serialization of a helper result, ideal for experimental_subAgent(...)',
494 - ' const f = await proxy(toolkit) Same as `composio proxy` — returns a fetch function',
495 - ' Example: const f = await proxy("gmail")',
496 - ' const me = await f("https://gmail.googleapis.com/gmail/v1/users/me/profile")',
497 - ' z Injected global from `zod` for structured output schemas',
498 - '',
499 - 'All helpers reuse your CLI auth state and connected accounts.',
500 - '',
501 - 'Flags:',
502 - ' --debug Log helper steps while the script runs',
503 - ' --dry-run Preview execute() calls without running them',
504 - ' --logs-off Hide the always-on experimental_subAgent streaming logs',
505 - ' --skip-connection-check Skip the connected-account check',
506 - ' --skip-tool-params-check Skip input validation against cached schema',
507 - ' --skip-checks Skip both checks above',
508 - '',
509 - 'See also:',
510 - ' composio search "<query>" Discover tool slugs before scripting',
511 - ' composio link <toolkit> Connect accounts before scripting',
512 - ' composio execute <slug> --get-schema Inspect tool inputs before scripting',
513 - ].join('\n')
457 + 'Run inline TS/JS code or a file with injected Composio helpers that behave like their CLI counterparts.\n\nInjected helpers (behave like their CLI counterparts):\n execute(slug, data?) Same as `composio execute` — returns parsed JSON\n search(query, options?) Same as `composio search` — returns matching tools\n experimental_subAgent(prompt, options?) Experimental helper to spawn a powerful sub-agent from the same agent family as your current main agent\n (Codex -> Codex, Claude -> Claude) with optional Zod structured output\n result.prompt() Prompt-safe serialization of a helper result, ideal for experimental_subAgent(...)\n const f = await proxy(toolkit) Same as `composio proxy` — returns a fetch function\n Example: const f = await proxy("gmail")\n const me = await f("https://gmail.googleapis.com/gmail/v1/users/me/profile")\n z Injected global from `zod` for structured output schemas\n\nAll helpers reuse your CLI auth state and connected accounts.\n\nUse composio search "<query>" to discover tools and composio execute <slug> --get-schema to inspect inputs.'
458 + ),
459 + Command.withShortDescription(
460 + 'Run inline TS/JS code or a file with injected Composio helpers that behave like their CLI counterparts.'
461 ),
462 + Command.withExamples([
463 + {
464 + command:
465 + 'composio run \'\n // execute(slug, data?) — run a tool, returns parsed JSON\n const me = await execute("GITHUB_GET_THE_AUTHENTICATED_USER");\n console.log(me);\n\'',
466 + },
467 + {
468 + command:
469 + 'composio run \'\n // search(query, opts?) — find tools by use case\n const tools = await search("send email");\n console.log(tools);\n\'',
470 + },
471 + {
472 + command:
473 + 'composio run \'\n const issue = await execute("GITHUB_CREATE_ISSUE", { owner: "acme", repo: "app", title: "Deploy v2" });\n await execute("SLACK_SEND_MESSAGE", { channel: "eng", markdown_text: "Created: " + issue.data.html_url });\n\'',
474 + description: 'Sequential: chain tool outputs across services',
475 + },
476 + {
477 + command:
478 + 'composio run \'\n const [emails, issues, events] = await Promise.all([\n execute("GMAIL_FETCH_EMAILS", { max_results: 5 }),\n execute("GITHUB_LIST_REPOSITORY_ISSUES", { owner: "composiohq", repo: "composio", state: "open" }),\n execute("GOOGLECALENDAR_FIND_EVENT", { calendar_id: "primary" }),\n ]);\n console.log({ emails: emails.data, issues: issues.data, events: events.data });\n\'',
479 + description: 'Parallel: fetch from multiple services at once with Promise.all',
480 + },
481 + {
482 + command:
483 + 'composio run \'\n const issues = [101, 102, 103, 104];\n await Promise.all(issues.map(n =>\n execute("GITHUB_ADD_LABELS_TO_ISSUE", { owner: "acme", repo: "app", issue_number: n, labels: ["priority"] })\n ));\n\'',
484 + description: 'Bulk: fan out with Promise.all + .map()',
485 + },
486 + {
487 + command:
488 + 'composio run \'\n const f = await proxy("gmail");\n console.log(await f("https://gmail.googleapis.com/gmail/v1/users/me/profile"));\n\'',
489 + description: 'proxy(toolkit) — returns a fetch() bound to your connected account',
490 + },
491 + {
492 + command:
493 + 'composio run \'\n const [emails, issues] = await Promise.all([\n execute("GMAIL_FETCH_EMAILS", { max_results: 5 }),\n execute("GITHUB_LIST_REPOSITORY_ISSUES", { owner: "composiohq", repo: "composio", state: "open" }),\n ]);\n // result.prompt() serializes helper output for LLM consumption\n // z is a global from zod for defining structured output schemas\n const brief = await experimental_subAgent(\n `Summarize these emails and issues.\\n\\n${emails.prompt()}\\n\\n${issues.prompt()}`,\n { schema: z.object({ summary: z.string(), urgent: z.array(z.string()) }) }\n );\n console.log(brief.structuredOutput);\n\'',
494 + description:
495 + 'experimental_subAgent + z + result.prompt() — structured output from a sub-agent',
496 + },
497 + {
498 + command: 'composio run --file ./workflow.ts -- --repo acme/app',
499 + description: 'Run from a file',
500 + },
501 + {
502 + command:
503 + 'composio run \'\n const [emails, issues] = await Promise.all([\n execute("GMAIL_FETCH_EMAILS", { max_results: 5 }),\n execute("GITHUB_LIST_REPOSITORY_ISSUES", { owner: "composiohq", repo: "composio", state: "open" }),\n ]);\n const brief = await experimental_subAgent(\n `Create a morning brief from these emails and issues.\\n\\n${emails.prompt()}\\n\\n${issues.prompt()}`,\n {\n schema: z.object({\n brief: z.string(),\n urgentEmails: z.array(z.string()),\n urgentIssues: z.array(z.string()),\n }),\n }\n );\n brief.structuredOutput;\n\'',
504 + description: 'Create a structured brief with an injected sub-agent.',
505 + },
506 + ]),
507 Command.withHandler(
508 ({
509 file,
@@ -521,11 +513,9 @@ export const runCmd = Command.make('run', {
513 skipConnectionCheck,
514 skipToolParamsCheck,
515 skipChecks,
524 - args: rawArgs,
516 + args,
517 }) =>
518 Effect.gen(function* () {
527 - const passthroughTail = yield* RunPassthroughArgs;
528 - const args = passthroughTail ?? rawArgs;
519 // Checked before any setup work so a bare `composio run` neither creates a run-artifacts
520 // directory nor advertises a log file for a script that will never start.
521 if (Option.isNone(file) && !args[0]) {
ts/packages/cli/src/commands/setup-skill.cmd.ts new
+21
@@ -0,0 +1,21 @@
1 +import { Argument, Command, Flag } from 'effect/unstable/cli';
2 +import { Option } from 'effect';
3 +import { installSkill } from 'src/effects/install-skill';
4 +
5 +export const setupSkillCmd = Command.make(
6 + 'skill',
7 + {
8 + target: Argument.Literals('target', ['claude', 'codex', 'openclaw']),
9 + name: Flag.String('name').pipe(
10 + Flag.optional,
11 + Flag.withDescription('Installed skill name (default: composio-cli)')
12 + ),
13 + },
14 + ({ target, name }) => installSkill({ target, skillName: Option.getOrUndefined(name) })
15 +).pipe(
16 + Command.withDescription('Install the Composio CLI skill for an agent host.'),
17 + Command.withExamples([
18 + { command: 'composio setup skill claude' },
19 + { command: 'composio setup skill codex --name composio-cli' },
20 + ])
21 +);
ts/packages/cli/src/commands/setup.cmd.ts
+17 -1
@@ -1,3 +1,4 @@
1 +import { setupSkillCmd } from './setup-skill.cmd';
2 import { Command, Flag } from 'effect/unstable/cli';
3 import { Effect, Predicate } from 'effect';
4 import { trackCliEventEffect } from 'src/analytics/dispatch';
@@ -311,5 +312,20 @@ const setupBaseCmd = Command.make(
312 );
313
314 export const setupCmd = setupBaseCmd.pipe(
314 - Command.withDescription('Install or uninstall Composio plugins for supported agent hosts.')
315 + Command.withDescription('Install or uninstall Composio plugins for supported agent hosts.'),
316 + Command.withExamples([
317 + {
318 + command: 'composio setup',
319 + },
320 + {
321 + command: 'composio setup --target auto --yes',
322 + },
323 + {
324 + command: 'composio setup --uninstall --target auto --yes',
325 + },
326 + {
327 + command: 'composio setup --target all',
328 + },
329 + ]),
330 + Command.withSubcommands([setupSkillCmd])
331 );
ts/packages/cli/src/commands/toolkits/commands/toolkits.list.cmd.ts
+4 -1
@@ -203,4 +203,7 @@ export const toolkitsCmd$List = Command.make(
203 })
204 )
205 )
206 -).pipe(Command.withDescription('List available toolkits with connection status.'));
206 +).pipe(
207 + Command.withDescription('List available toolkits with connection status.'),
208 + Command.withExamples([{ command: 'composio dev toolkits list' }])
209 +);
ts/packages/cli/src/commands/tools/commands/tools.execute.cmd.ts
+168 -179
@@ -1,6 +1,6 @@
1 import { Argument, Command, Flag } from 'effect/unstable/cli';
2 import util from 'node:util';
3 -import { Cause, Data, Effect, Exit, Fiber, HashSet, Option, Result } from 'effect';
3 +import { Cause, Context, Data, Effect, Exit, Fiber, Option, Result } from 'effect';
4 import { redact } from 'src/ui/redact';
5 import { parseJsonRecord, isPlainRecord } from 'src/utils/parse-json';
6 import { toolkitFromToolSlug } from 'src/effects/toolkit-from-tool-slug';
@@ -19,10 +19,7 @@ import { TerminalUI } from 'src/services/terminal-ui';
19 import { logToolDebug, makePerfDebugLogger } from 'src/services/runtime-debug-logger';
20 import { ToolsExecutor, detectInBandWarning } from 'src/services/tools-executor';
21 import type { ToolExecuteParams, ToolExecuteResponse } from 'src/services/tools-executor';
22 -import {
23 - ComposioToolkitsRepository,
24 - type ToolkitProjectScope,
25 -} from 'src/services/composio-clients';
22 +import type { ToolkitProjectScope } from 'src/services/composio-clients';
23 import { ComposioUserContext } from 'src/services/user-context';
24 import { ProjectContext } from 'src/services/project-context';
25 import { trackCliCodactFailureEffect, trackCliEventEffect } from 'src/analytics/dispatch';
@@ -34,8 +31,6 @@ import {
31 isMaybeToolValidationError,
32 isMaybeToolNotFoundError,
33 } from 'src/analytics/events';
37 -import { handleHttpServerError } from 'src/effects/handle-http-error';
38 -import { formatToolInputParameters } from '../format';
34 import { ComposioClientSingleton } from 'src/services/composio-clients';
35 import {
36 resolveCommandProject,
@@ -60,11 +55,27 @@ import {
55 } from 'src/services/composio-error-overrides';
56 import * as constants from 'src/constants';
57 import { APP_CONFIG } from 'src/effects/app-config';
58 +import { CLI_DEBUG_FLAG_NAMES } from 'src/services/runtime-flags';
59 +
60 +export const ExecuteInvocationArgs = Context.Reference<ReadonlyArray<string>>(
61 + 'commands/ExecuteInvocationArgs',
62 + { defaultValue: () => [] }
63 +);
64
65 const slug = Argument.String('slug').pipe(
66 Argument.withDescription('Tool slug (e.g. "GITHUB_CREATE_ISSUE")')
67 );
68
69 +const additionalSlugs = Argument.String('additional-slugs').pipe(
70 + Argument.variadic(),
71 + Argument.withDescription('Additional tool slugs for --parallel')
72 +);
73 +const parallel = Flag.Boolean('parallel').pipe(
74 + Flag.withAlias('p'),
75 + Flag.withDefault(false),
76 + Flag.withDescription('Execute repeated tool slug/data groups concurrently')
77 +);
78 +
79 const data = Flag.String('data').pipe(
80 Flag.withAlias('d'),
81 Flag.withDescription('JSON arguments, @file, or - for stdin'),
@@ -81,15 +92,6 @@ const accountOption = Flag.String('account').pipe(
92 Flag.optional
93 );
94
84 -export const TOOLS_EXECUTE_VALUE_OPTIONS = HashSet.make(
85 - '--data',
86 - '-d',
87 - '--file',
88 - '--account',
89 - '--user-id',
90 - '--project-name'
91 -);
92 -
95 const userId = Flag.String('user-id').pipe(
96 Flag.optional,
97 Flag.withDescription('Developer-project user ID override')
@@ -647,50 +649,6 @@ const emitExecuteFailureTelemetry = (params: {
649
650 const writeExecuteStdout = (ui: TerminalUI, data: string) => ui.output(data, { force: true });
651
650 -export const showToolsExecuteInputHelp = (toolSlug: string) =>
651 - Effect.gen(function* () {
652 - if (!(yield* requireAuth)) return;
653 -
654 - const ui = yield* TerminalUI;
655 - const repo = yield* ComposioToolkitsRepository;
656 -
657 - const toolOpt = yield* ui
658 - .withSpinner(`Fetching input parameters for "${toolSlug}"...`, repo.getToolDetailed(toolSlug))
659 - .pipe(
660 - Effect.asSome,
661 - Effect.catchTag(
662 - 'services/HttpServerError',
663 - handleHttpServerError(ui, {
664 - fallbackMessage: `Tool "${toolSlug}" not found.`,
665 - hint: [
666 - commandHintStep('Browse available toolkits', 'dev.toolkits.list'),
667 - commandHintStep('Then list tools', 'root.tools.list'),
668 - ].join('\n'),
669 - fallbackValue: Option.none(),
670 - searchForSuggestions: () =>
671 - repo.searchTools({ search: toolSlug, limit: 3 }).pipe(
672 - Effect.map(r =>
673 - r.items.map(s => ({
674 - label: `${s.slug} — ${s.description}`,
675 - command: `> composio execute "${s.slug}" --help`,
676 - }))
677 - )
678 - ),
679 - })
680 - )
681 - );
682 -
683 - if (Option.isNone(toolOpt)) return;
684 - const tool = toolOpt.value;
685 -
686 - yield* ui.note(formatToolInputParameters(tool), `Execute Help: ${tool.slug}`);
687 - yield* ui.log.step(`Run:\n> composio execute "${tool.slug}" -d '{"key":"value"}'`);
688 - yield* writeExecuteStdout(
689 - ui,
690 - JSON.stringify({ slug: tool.slug, input_parameters: tool.input_parameters }, null, 2)
691 - );
692 - });
693 -
652 const handleExecutionError = (
653 ui: TerminalUI,
654 error: unknown,
@@ -1616,6 +1574,28 @@ export const parseParallelExecuteArgs = (
1574 const token = args[i];
1575 if (!token) continue;
1576
1577 + const flagName = token.split('=')[0];
1578 + if (
1579 + CLI_DEBUG_FLAG_NAMES.some(name => flagName === `--${name}` || flagName === `--no-${name}`)
1580 + )
1581 + continue;
1582 + if (flagName === '--log-level') {
1583 + if (!token.includes('=')) i += 1;
1584 + continue;
1585 + }
1586 + // The framework supplies these values; this parser only preserves tool/data grouping.
1587 + if (
1588 + [
1589 + 'parallel',
1590 + 'get-schema',
1591 + 'dry-run',
1592 + 'skip-connection-check',
1593 + 'skip-tool-params-check',
1594 + 'skip-checks',
1595 + ].some(name => flagName === `--${name}` || flagName === `--no-${name}`) &&
1596 + (token !== flagName || flagName.startsWith('--no-'))
1597 + )
1598 + continue;
1599 if (token === '--parallel' || token === '-p') {
1600 continue;
1601 }
@@ -1736,40 +1716,6 @@ export const parseParallelExecuteArgs = (
1716 } satisfies ParsedParallelExecuteArgs;
1717 });
1718
1739 -type ParallelExecuteCommand = {
1740 - readonly matched: boolean;
1741 - readonly tail: ReadonlyArray<string>;
1742 - readonly surface: 'root' | 'dev';
1743 - readonly projectMode: 'consumer' | 'developer';
1744 - readonly allowUserId: boolean;
1745 - readonly allowProjectName: boolean;
1746 -};
1747 -
1748 -const isParallelExecuteCommand = (argv: ReadonlyArray<string>): ParallelExecuteCommand | null => {
1749 - const args = argv.slice(2);
1750 - if (args[0] === 'execute') {
1751 - return {
1752 - matched: args.includes('--parallel') || args.includes('-p'),
1753 - tail: args.slice(1),
1754 - surface: 'root',
1755 - projectMode: 'consumer',
1756 - allowUserId: false,
1757 - allowProjectName: false,
1758 - };
1759 - }
1760 - if (args[0] === 'dev' && args[1] === 'playground-execute') {
1761 - return {
1762 - matched: args.includes('--parallel') || args.includes('-p'),
1763 - tail: args.slice(2),
1764 - surface: 'dev',
1765 - projectMode: 'developer',
1766 - allowUserId: true,
1767 - allowProjectName: true,
1768 - };
1769 - }
1770 - return null;
1771 -};
1772 -
1719 const checkConnectedToolkitOrFail = (params: {
1720 readonly slug: string;
1721 readonly resolvedProject: ResolvedExecuteContext['resolvedProject'];
@@ -2086,24 +2032,64 @@ const runParallelToolsExecuteFromParsed = (params: ParsedParallelExecuteArgs) =>
2032 }
2033 });
2034
2089 -export const runParallelToolsExecuteFromArgv = (argv: ReadonlyArray<string>) => {
2090 - const command = isParallelExecuteCommand(argv);
2091 - if (!command?.matched) {
2092 - return null;
2093 - }
2035 +const runParallelFromCommand = (config: {
2036 + readonly surface: 'root' | 'dev';
2037 + readonly projectMode: 'consumer' | 'developer';
2038 + readonly getSchema: boolean;
2039 + readonly dryRun: boolean;
2040 + readonly skipConnectionCheck: boolean;
2041 + readonly skipToolParamsCheck: boolean;
2042 + readonly skipChecks: boolean;
2043 +}) =>
2044 + Effect.gen(function* () {
2045 + const argv = yield* ExecuteInvocationArgs;
2046 + const name = config.surface === 'root' ? 'execute' : 'playground-execute';
2047 + const tail = argv.slice(argv.indexOf(name) + 1);
2048 + const parsed = yield* parseParallelExecuteArgs(tail, {
2049 + ...config,
2050 + allowUserId: config.surface === 'dev',
2051 + allowProjectName: config.surface === 'dev',
2052 + });
2053 + return yield* runParallelToolsExecuteFromParsed({ ...parsed, ...config });
2054 + });
2055
2095 - return parseParallelExecuteArgs(command.tail, {
2096 - surface: command.surface,
2097 - projectMode: command.projectMode,
2098 - allowUserId: command.allowUserId,
2099 - allowProjectName: command.allowProjectName,
2100 - }).pipe(Effect.flatMap(runParallelToolsExecuteFromParsed));
2101 -};
2056 +const executeExamples = [
2057 + {
2058 + command:
2059 + 'composio execute GMAIL_SEND_EMAIL -d \'{ recipient_email: "a@b.com", subject: "Hello", body: "World" }\'',
2060 + description: 'Send an email',
2061 + },
2062 + {
2063 + command:
2064 + 'composio execute GITHUB_CREATE_ISSUE --account work -d \'{ owner: "acme", repo: "app", title: "Bug report", body: "Steps to reproduce..." }\'',
2065 + description: 'Create a GitHub issue with a named account',
2066 + },
2067 + {
2068 + command:
2069 + 'composio execute SLACK_SEND_MESSAGE --dry-run -d \'{ channel: "general", markdown_text: "Hello team" }\'',
2070 + description: 'Preview what a tool call would send without executing',
2071 + },
2072 + {
2073 + command: 'composio execute GMAIL_SEND_EMAIL --get-schema',
2074 + description: 'Print the tool input schema as JSON (--help shows command options)',
2075 + },
2076 + {
2077 + command: 'composio execute GITHUB_CREATE_ISSUE -d @issue.json',
2078 + description: 'Read arguments from a file',
2079 + },
2080 + {
2081 + command:
2082 + 'composio execute -p GMAIL_SEND_EMAIL -d \'{ recipient_email: "a@b.com" }\' GITHUB_CREATE_AN_ISSUE -d \'{ owner: "acme", repo: "app", title: "Bug" }\'',
2083 + description: 'Execute multiple tools concurrently',
2084 + },
2085 +];
2086
2087 export const rootToolsCmd$Execute = Command.make(
2088 'execute',
2089 {
2090 slug,
2091 + additionalSlugs,
2092 + parallel,
2093 data,
2094 file,
2095 account: accountOption,
@@ -2115,6 +2101,8 @@ export const rootToolsCmd$Execute = Command.make(
2101 },
2102 ({
2103 slug,
2104 + additionalSlugs,
2105 + parallel,
2106 data,
2107 file,
2108 account,
@@ -2124,55 +2112,49 @@ export const rootToolsCmd$Execute = Command.make(
2112 skipToolParamsCheck,
2113 skipChecks,
2114 }) =>
2127 - runToolsExecute({
2128 - slug,
2129 - data,
2130 - file,
2131 - account,
2132 - userId: Option.none(),
2133 - projectName: Option.none(),
2134 - surface: 'root',
2135 - projectMode: 'consumer',
2136 - getSchema,
2137 - dryRun,
2138 - skipConnectionCheck,
2139 - skipToolParamsCheck,
2140 - skipChecks,
2141 - })
2115 + parallel
2116 + ? runParallelFromCommand({
2117 + surface: 'root',
2118 + projectMode: 'consumer',
2119 + getSchema,
2120 + dryRun,
2121 + skipConnectionCheck,
2122 + skipToolParamsCheck,
2123 + skipChecks,
2124 + })
2125 + : additionalSlugs.length > 0
2126 + ? Effect.fail(invalidArguments('Additional tool slugs require --parallel.'))
2127 + : runToolsExecute({
2128 + slug,
2129 + data,
2130 + file,
2131 + account,
2132 + userId: Option.none(),
2133 + projectName: Option.none(),
2134 + surface: 'root',
2135 + projectMode: 'consumer',
2136 + getSchema,
2137 + dryRun,
2138 + skipConnectionCheck,
2139 + skipToolParamsCheck,
2140 + skipChecks,
2141 + })
2142 ).pipe(
2143 Command.withDescription(
2144 - [
2145 - 'Execute a tool by slug. Validates inputs against cached schemas and checks connections',
2146 - 'automatically — just try it and it will tell you what to fix.',
2147 - '',
2148 - 'Examples:',
2149 - ' composio execute GMAIL_SEND_EMAIL -d \'{ recipient_email: "a@b.com", body: "Hello" }\'',
2150 - ' composio execute GMAIL_SEND_EMAIL --account default -d \'{ recipient_email: "a@b.com" }\'',
2151 - ' composio execute SLACK_UPLOAD_OR_CREATE_A_FILE_IN_SLACK --file ./image.png -d \'{ channels: "C123" }\'',
2152 - ' composio execute --parallel GMAIL_SEND_EMAIL -d \'{ recipient_email: "a@b.com" }\' GITHUB_CREATE_AN_ISSUE -d \'{ owner: "acme", repo: "app", title: "Bug" }\'',
2153 - " composio execute GMAIL_SEND_EMAIL --dry-run -d '{ ... }' Preview without executing",
2154 - ' composio execute GMAIL_SEND_EMAIL --get-schema Fetch and print the input schema',
2155 - '',
2156 - 'Flags:',
2157 - ' --file <path> Inject a local file path into the single file_uploadable input',
2158 - ' --account <selector> Select connected account by alias, word_id, or account id',
2159 - ' -p, --parallel Execute repeated TOOL_SLUG -d <json> groups concurrently',
2160 - ' --skip-connection-check Skip the connected-account check',
2161 - ' --skip-tool-params-check Skip input validation against cached schema',
2162 - ' --skip-checks Skip both checks above',
2163 - '',
2164 - 'See also:',
2165 - ' composio search "<query>" Find tool slugs by use case',
2166 - ' composio tools info <slug> Schema summary with jq hints',
2167 - ' composio link <toolkit> Connect an account for a toolkit',
2168 - ].join('\n')
2169 - )
2144 + 'Execute a tool by slug. Validates inputs against cached schemas and checks connections\nautomatically — just try it and it will tell you what to fix.'
2145 + ),
2146 + Command.withShortDescription(
2147 + 'Execute a tool by slug. Validates inputs against cached schemas and checks connections'
2148 + ),
2149 + Command.withExamples(executeExamples)
2150 );
2151
2152 export const devToolsCmd$Execute = Command.make(
2153 'playground-execute',
2154 {
2155 slug,
2156 + additionalSlugs,
2157 + parallel,
2158 data,
2159 file,
2160 account: accountOption,
@@ -2186,6 +2168,8 @@ export const devToolsCmd$Execute = Command.make(
2168 },
2169 ({
2170 slug,
2171 + additionalSlugs,
2172 + parallel,
2173 data,
2174 file,
2175 account,
@@ -2197,39 +2181,44 @@ export const devToolsCmd$Execute = Command.make(
2181 skipToolParamsCheck,
2182 skipChecks,
2183 }) =>
2200 - runToolsExecute({
2201 - slug,
2202 - data,
2203 - file,
2204 - account,
2205 - userId,
2206 - projectName,
2207 - surface: 'dev',
2208 - projectMode: 'developer',
2209 - getSchema,
2210 - dryRun,
2211 - skipConnectionCheck,
2212 - skipToolParamsCheck,
2213 - skipChecks,
2214 - })
2184 + parallel
2185 + ? runParallelFromCommand({
2186 + surface: 'dev',
2187 + projectMode: 'developer',
2188 + getSchema,
2189 + dryRun,
2190 + skipConnectionCheck,
2191 + skipToolParamsCheck,
2192 + skipChecks,
2193 + })
2194 + : additionalSlugs.length > 0
2195 + ? Effect.fail(invalidArguments('Additional tool slugs require --parallel.'))
2196 + : runToolsExecute({
2197 + slug,
2198 + data,
2199 + file,
2200 + account,
2201 + userId,
2202 + projectName,
2203 + surface: 'dev',
2204 + projectMode: 'developer',
2205 + getSchema,
2206 + dryRun,
2207 + skipConnectionCheck,
2208 + skipToolParamsCheck,
2209 + skipChecks,
2210 + })
2211 ).pipe(
2212 Command.withDescription(
2217 - [
2218 - 'Test tool executions against playground users using your developer project auth configs.',
2219 - 'Uses --user-id when provided, otherwise falls back to your local or global playground test user id.',
2220 - 'Arguments are validated against cached tool schemas in `~/.composio/tool_definitions/` when available.',
2221 - '',
2222 - 'Examples:',
2223 - ' composio dev playground-execute GMAIL_SEND_EMAIL -d \'{ recipient_email: "a@b.com", body: "Hello" }\'',
2224 - ' composio dev playground-execute GMAIL_SEND_EMAIL --account default -d \'{ recipient_email: "a@b.com" }\'',
2225 - ' composio dev playground-execute SLACK_UPLOAD_OR_CREATE_A_FILE_IN_SLACK --file ./image.png -d \'{ channels: "C123" }\'',
2226 - ' composio dev playground-execute GMAIL_SEND_EMAIL --dry-run -d \'{ recipient_email: "a@b.com", body: "Hello" }\'',
2227 - ' composio dev playground-execute GMAIL_SEND_EMAIL --get-schema',
2228 - '',
2229 - 'Flags:',
2230 - ' --file <path> Inject a local file path into the single file_uploadable input',
2231 - ' --account <selector> Select connected account by alias, word_id, or account id',
2232 - ' -p, --parallel Execute repeated TOOL_SLUG -d <json> groups concurrently',
2233 - ].join('\n')
2213 + 'Test tool executions against playground users using your developer project auth configs.\nUses --user-id when provided, otherwise falls back to your local or global playground test user id.\nArguments are validated against cached tool schemas in `~/.composio/tool_definitions/` when available.'
2214 + ),
2215 + Command.withShortDescription(
2216 + 'Test tool executions against playground users using your developer project auth configs.'
2217 + ),
2218 + Command.withExamples(
2219 + executeExamples.map(example => ({
2220 + ...example,
2221 + command: example.command.replace('composio execute', 'composio dev playground-execute'),
2222 + }))
2223 )
2224 );
ts/packages/cli/src/commands/tools/commands/tools.search.cmd.ts
+34 -16
@@ -571,20 +571,38 @@ export const rootToolsCmd$Search = Command.make(
571 })
572 ).pipe(
573 Command.withDescription(
574 - [
575 - 'Find tools by use case. Defaults to full JSON output; use `--human` for formatted output.',
576 - '',
577 - 'Examples:',
578 - ' composio search "send an email"',
579 - ' composio search "send an email" "create a github issue"',
580 - ' composio search "create issue" --toolkits github',
581 - ' composio search "send an email" --human',
582 - ' composio search "list calendar events" --limit 5',
583 - '',
584 - 'Next steps:',
585 - ' composio link <toolkit> Connect an account before executing tools',
586 - " composio execute <slug> -d '{ ... }' Run a tool from the results",
587 - " composio tools info <slug> Inspect a tool's schema before executing",
588 - ].join('\n')
589 - )
574 + 'Find tools by use case. Defaults to full JSON output; use `--human` for formatted output.'
575 + ),
576 + Command.withShortDescription(
577 + 'Find tools by use case. Defaults to full JSON output; use `--human` for formatted output.'
578 + ),
579 + Command.withExamples([
580 + {
581 + command: 'composio search "send an email"',
582 + description: 'Find tools for a use case',
583 + },
584 + {
585 + command: 'composio search "send an email" "create github issue"',
586 + },
587 + {
588 + command: 'composio search "my emails" "my github issues" --toolkits gmail,github',
589 + },
590 + {
591 + command: 'composio search "create issue" --toolkits github',
592 + },
593 + {
594 + command: 'composio search "send an email" --human',
595 + },
596 + {
597 + command: 'composio search "post a message to a slack channel"',
598 + description: 'Cross-app workflow discovery',
599 + },
600 + {
601 + command: 'composio search "add a row to google sheet"',
602 + },
603 + {
604 + command: 'composio search "list calendar events" --toolkits google_calendar --limit 5',
605 + description: 'Narrow results to a specific toolkit',
606 + },
607 + ])
608 );
ts/packages/cli/src/commands/tools/format.ts
-53
@@ -58,39 +58,6 @@ function formatSchemaProperties(schema: Record<string, unknown>): string {
58 .join('\n');
59 }
60
61 -/**
62 - * Format JSON Schema properties using a detailed field layout, similar to trigger info.
63 - */
64 -function formatSchemaPropertiesDetailed(schema: Record<string, unknown>): string {
65 - const entries = extractSchemaProperties(schema);
66 - if (entries.length === 0) {
67 - return ' (none)';
68 - }
69 -
70 - const typeWidth = Math.max(...entries.map(e => e.type.length));
71 - const labelWidth = Math.max(...entries.map(e => e.label.length));
72 - const metadataLabels = ['description:', 'type:', 'required:', 'default:'] as const;
73 - const metadataLabelWidth = Math.max(...metadataLabels.map(label => label.length));
74 -
75 - return entries
76 - .map(e => {
77 - const lines: string[] = [];
78 - lines.push(` ${bold(e.name)}`);
79 - lines.push(
80 - ` ${'description:'.padEnd(metadataLabelWidth)} ${e.description ? gray(truncate(e.description, 70)) : '-'}`
81 - );
82 - lines.push(` ${'type:'.padEnd(metadataLabelWidth)} ${e.type.padEnd(typeWidth)}`);
83 - lines.push(` ${'required:'.padEnd(metadataLabelWidth)} ${e.label.padEnd(labelWidth)}`);
84 - if (e.hasDefault) {
85 - lines.push(
86 - ` ${'default:'.padEnd(metadataLabelWidth)} ${gray(truncate(JSON.stringify(e.defaultValue), 40))}`
87 - );
88 - }
89 - return lines.join('\n');
90 - })
91 - .join('\n\n');
92 -}
93 -
61 /**
62 * Format a detailed tool for interactive display.
63 */
@@ -126,23 +93,3 @@ export function formatToolInfo(tool: ToolRetrieveResponse): string {
93
94 return lines.join('\n');
95 }
129 -
130 -/**
131 - * Format only tool input parameters for execute-help flows.
132 - */
133 -export function formatToolInputParameters(tool: ToolRetrieveResponse): string {
134 - const lines: string[] = [];
135 - lines.push(`${bold('Name:')} ${tool.name}`);
136 - lines.push(`${bold('Slug:')} ${tool.slug}`);
137 - lines.push(`${bold('Description:')} ${tool.description || '(none)'}`);
138 -
139 - if (tool.toolkit.slug) {
140 - lines.push(`${bold('Toolkit:')} ${tool.toolkit.name} (${tool.toolkit.slug})`);
141 - }
142 -
143 - lines.push('');
144 - lines.push(gray('------------------------------'));
145 - lines.push(bold('Data Parameters:'));
146 - lines.push(formatSchemaPropertiesDetailed(tool.input_parameters as Record<string, unknown>));
147 - return lines.join('\n');
148 -}
ts/packages/cli/src/commands/tools/tools.cmd.ts
+8
@@ -4,5 +4,13 @@ import { toolsCmd$Info } from './commands/tools.info.cmd';
4
5 export const rootToolsCmd = Command.make('tools').pipe(
6 Command.withDescription('Browse and inspect tools before executing them.'),
7 + Command.withExamples([
8 + {
9 + command: 'composio tools list gmail',
10 + },
11 + {
12 + command: 'composio tools info GMAIL_SEND_EMAIL',
13 + },
14 + ]),
15 Command.withSubcommands([toolsCmd$List, toolsCmd$Info])
16 );
ts/packages/cli/src/commands/triggers/commands/triggers.disable.cmd.ts
+62 -36
@@ -1,8 +1,9 @@
1 -import { Argument, Command } from 'effect/unstable/cli';
2 -import { Effect, Option } from 'effect';
1 +import { Argument, Command, Flag } from 'effect/unstable/cli';
2 +import { Data, Effect, Option } from 'effect';
3 import { requireAuth } from 'src/effects/require-auth';
4 import { handleHttpServerError } from 'src/effects/handle-http-error';
5 import { ComposioToolkitsRepository } from 'src/services/composio-clients';
6 +import { ComposioCliUserConfig } from 'src/services/cli-user-config';
7 import { TerminalUI } from 'src/services/terminal-ui';
8
9 const id = Argument.String('id').pipe(
@@ -10,41 +11,66 @@ const id = Argument.String('id').pipe(
11 Argument.optional
12 );
13
14 +export class DangerousDeveloperCommandError extends Data.TaggedError(
15 + 'commands/DangerousDeveloperCommandError'
16 +)<{ readonly message: string }> {}
17 +
18 +const dangerouslyAllow = Flag.Boolean('dangerously-allow').pipe(
19 + Flag.withDescription('Acknowledge disabling this trigger instance'),
20 + Flag.withDefault(false)
21 +);
22 +
23 /**
24 * Disable an existing trigger instance.
25 */
16 -export const triggersCmd$Disable = Command.make('disable', { id }, ({ id }) =>
17 - Effect.gen(function* () {
18 - if (!(yield* requireAuth)) return;
19 -
20 - const ui = yield* TerminalUI;
21 - const repo = yield* ComposioToolkitsRepository;
22 -
23 - if (Option.isNone(id)) {
24 - yield* ui.log.warn('Missing required argument: <id>');
25 - yield* ui.log.step(
26 - 'Try specifying a trigger ID, e.g.:\n> composio dev triggers disable "trg_123"\n\nTo find trigger IDs:\n> composio dev triggers status'
27 - );
28 - return;
29 - }
30 -
31 - const idValue = id.value;
32 - const disabled = yield* ui
33 - .withSpinner(`Disabling trigger "${idValue}"...`, repo.disableTrigger(idValue))
34 - .pipe(
35 - Effect.as(true),
36 - Effect.catchTag(
37 - 'services/HttpServerError',
38 - handleHttpServerError(ui, {
39 - fallbackMessage: `Failed to disable trigger "${idValue}".`,
40 - hint: 'Browse available triggers:\n> composio dev triggers status',
41 - fallbackValue: false,
42 - })
43 - )
44 - );
45 -
46 - if (!disabled) return;
47 -
48 - yield* ui.log.success(`Trigger "${idValue}" disabled.`);
49 - })
26 +export const triggersCmd$Disable = Command.make(
27 + 'disable',
28 + { id, dangerouslyAllow },
29 + ({ id, dangerouslyAllow }) =>
30 + Effect.gen(function* () {
31 + const config = yield* ComposioCliUserConfig;
32 + if (!config.areDeveloperDangerousCommandsEnabled()) {
33 + return yield* new DangerousDeveloperCommandError({
34 + message:
35 + 'This developer command is disabled by config. Set developer.destructive_actions to true in ~/.composio/config.json to allow it.',
36 + });
37 + }
38 + if (!dangerouslyAllow) {
39 + return yield* new DangerousDeveloperCommandError({
40 + message:
41 + 'This developer command requires explicit acknowledgement. Re-run with --dangerously-allow.',
42 + });
43 + }
44 + if (!(yield* requireAuth)) return;
45 +
46 + const ui = yield* TerminalUI;
47 + const repo = yield* ComposioToolkitsRepository;
48 +
49 + if (Option.isNone(id)) {
50 + yield* ui.log.warn('Missing required argument: <id>');
51 + yield* ui.log.step(
52 + 'Try specifying a trigger ID, e.g.:\n> composio dev triggers disable "trg_123"\n\nTo find trigger IDs:\n> composio dev triggers status'
53 + );
54 + return;
55 + }
56 +
57 + const idValue = id.value;
58 + const disabled = yield* ui
59 + .withSpinner(`Disabling trigger "${idValue}"...`, repo.disableTrigger(idValue))
60 + .pipe(
61 + Effect.as(true),
62 + Effect.catchTag(
63 + 'services/HttpServerError',
64 + handleHttpServerError(ui, {
65 + fallbackMessage: `Failed to disable trigger "${idValue}".`,
66 + hint: 'Browse available triggers:\n> composio dev triggers status',
67 + fallbackValue: false,
68 + })
69 + )
70 + );
71 +
72 + if (!disabled) return;
73 +
74 + yield* ui.log.success(`Trigger "${idValue}" disabled.`);
75 + })
76 ).pipe(Command.withDescription('Disable a trigger instance.'));
ts/packages/cli/src/services/runtime-flags.ts
+44 -51
@@ -1,40 +1,22 @@
1 import { Context, Effect, Layer, Option } from 'effect';
2 +import { Flag, GlobalFlag } from 'effect/unstable/cli';
3 import { APP_CONFIG, UNPREFIXED_CONFIG } from 'src/effects/app-config';
4 import { loadHostConfig } from 'src/services/config';
5
6 export const TELEMETRY_DEBUG_FLAG = '--telemetry-debug';
7
7 -export type StrippedTelemetryDebugArgv = {
8 - readonly argv: ReadonlyArray<string>;
9 - readonly telemetryDebug: boolean;
10 -};
11 -
8 /**
13 - * Removes `--telemetry-debug` from the CLI's own arguments and reports whether it was there.
14 - *
15 - * Only arguments before the first `--` are considered: everything after the delimiter belongs to
16 - * the process `composio run` spawns, so `composio run -- my-agent --telemetry-debug` has to reach
17 - * `my-agent` untouched.
18 - *
19 - * `src/bin.ts` runs this before the Effect runtime exists, which is why the answer travels into
20 - * the runtime as the `TelemetryDebugMode` service instead of module state.
9 + * Read telemetry debugging before constructing services that emit lifecycle events.
10 + * The caller excludes the run script tail. Effect still validates this hidden global flag;
11 + * bootstrap never removes it from argv.
12 */
22 -export const stripTelemetryDebugFlag = (
23 - argv: ReadonlyArray<string>
24 -): StrippedTelemetryDebugArgv => {
25 - const delimiterIndex = argv.indexOf('--');
26 - const searchEnd = delimiterIndex < 0 ? argv.length : delimiterIndex;
27 - const flagIndex = argv.findIndex(
28 - (token, index) => index < searchEnd && token === TELEMETRY_DEBUG_FLAG
29 - );
30 - if (flagIndex < 0) {
31 - return { argv, telemetryDebug: false };
13 +export const readTelemetryDebugOverride = (argv: ReadonlyArray<string>): boolean | undefined => {
14 + for (const token of argv) {
15 + if (token === '--') break;
16 + if (token === TELEMETRY_DEBUG_FLAG || token === `${TELEMETRY_DEBUG_FLAG}=true`) return true;
17 + if (token === '--no-telemetry-debug' || token === `${TELEMETRY_DEBUG_FLAG}=false`) return false;
18 }
33 -
34 - return {
35 - argv: [...argv.slice(0, flagIndex), ...argv.slice(flagIndex + 1)],
36 - telemetryDebug: true,
37 - };
19 + return undefined;
20 };
21
22 /**
@@ -58,9 +40,8 @@ export const NO_CLI_DEBUG_FLAG_OVERRIDES: CliDebugFlagOverrides = {
40 /**
41 * Hidden debug flags of the current invocation.
42 *
61 - * `src/commands/index.ts` parses them out of argv in one place and provides this service for the
62 - * command it then routes to, so every reader takes the values as an input instead of reaching for
63 - * process-wide state.
43 + * The command framework parses global settings without rewriting argv. This service supplies
44 + * overrides for direct Effect callers that do not run through the command parser.
45 */
46 export class CliDebugFlags extends Context.Service<CliDebugFlags, CliDebugFlagOverrides>()(
47 'services/CliDebugFlags'
@@ -70,26 +51,44 @@ export const cliDebugFlagsLayer = (
51 overrides: CliDebugFlagOverrides = NO_CLI_DEBUG_FLAG_OVERRIDES
52 ): Layer.Layer<CliDebugFlags> => Layer.succeed(CliDebugFlags, overrides);
53
73 -const debugFlagOr = (
54 +const debugSetting = <const Name extends string>(name: Name) =>
55 + GlobalFlag.Setting(name)({ flag: Flag.Boolean(name).pipe(Flag.optional, Flag.withHidden) });
56 +
57 +const debugSettings = {
58 + 'perf-debug': debugSetting('perf-debug'),
59 + 'tool-debug': debugSetting('tool-debug'),
60 + 'acp-only': debugSetting('acp-only'),
61 + 'telemetry-debug': debugSetting('telemetry-debug'),
62 +};
63 +export const CLI_DEBUG_FLAG_NAMES = Object.keys(debugSettings);
64 +export const CLI_DEBUG_GLOBAL_FLAGS = Object.values(debugSettings);
65 +
66 +const debugFlagOr = <const Name extends string>(
67 + setting: GlobalFlag.Setting<Name, Option.Option<boolean>>,
68 select: (overrides: CliDebugFlagOverrides) => boolean | undefined,
69 configured: Effect.Effect<boolean, never, never>
70 ): Effect.Effect<boolean, never, CliDebugFlags> =>
77 - Effect.map(
78 - Effect.all([CliDebugFlags, configured]),
79 - ([overrides, configuredValue]) => select(overrides) ?? configuredValue
80 - );
71 + Effect.gen(function* () {
72 + const parsed = Option.flatten(yield* Effect.serviceOption(setting));
73 + if (Option.isSome(parsed)) return parsed.value;
74 + const overrides = yield* CliDebugFlags;
75 + return select(overrides) ?? (yield* configured);
76 + });
77
78 export const isPerfDebugEnabled = debugFlagOr(
79 + debugSettings['perf-debug'],
80 overrides => overrides.perfDebug,
81 Effect.orDie(APP_CONFIG.PERF_DEBUG)
82 );
83
84 export const isToolDebugEnabled = debugFlagOr(
85 + debugSettings['tool-debug'],
86 overrides => overrides.toolDebug,
87 Effect.orDie(APP_CONFIG.TOOL_DEBUG)
88 );
89
90 export const isAcpOnlyEnabled = debugFlagOr(
91 + debugSettings['acp-only'],
92 overrides => overrides.acpOnly,
93 Effect.orDie(APP_CONFIG.RUN_ACP_ONLY)
94 );
@@ -116,14 +115,7 @@ export const debugFlagsToChildEnv = (flags: ChildProcessDebugFlags): Record<stri
115 COMPOSIO_CLI_TELEMETRY_DEBUG: flags.telemetryDebug ? '1' : '0',
116 });
117
119 -/**
120 - * Set when `--telemetry-debug` was found on the command line.
121 - *
122 - * The flag is stripped in `src/bin.ts` before the Effect runtime exists, so its value is handed to
123 - * the runtime as this service. Telemetry dispatch runs from service constructors and from the
124 - * detached worker process, where a hard requirement could not be satisfied, so readers resolve it
125 - * with `Effect.serviceOption` and fall back to `COMPOSIO_CLI_TELEMETRY_DEBUG`.
126 - */
118 +/** Telemetry debug override for service construction and internal worker invocations. */
119 export class TelemetryDebugMode extends Context.Service<TelemetryDebugMode, boolean>()(
120 'services/TelemetryDebugMode'
121 ) {}
@@ -131,10 +123,11 @@ export class TelemetryDebugMode extends Context.Service<TelemetryDebugMode, bool
123 export const telemetryDebugModeLayer = (enabled: boolean): Layer.Layer<TelemetryDebugMode> =>
124 Layer.succeed(TelemetryDebugMode, enabled);
125
134 -export const isTelemetryDebugEnabled: Effect.Effect<boolean> = Effect.flatMap(
135 - Effect.serviceOption(TelemetryDebugMode),
136 - Option.match({
137 - onNone: () => loadHostConfig(UNPREFIXED_CONFIG.TELEMETRY_DEBUG),
138 - onSome: Effect.succeed,
139 - })
140 -);
126 +export const isTelemetryDebugEnabled: Effect.Effect<boolean> = Effect.gen(function* () {
127 + const parsed = Option.flatten(yield* Effect.serviceOption(debugSettings['telemetry-debug']));
128 + if (Option.isSome(parsed)) return parsed.value;
129 + const bootstrap = yield* Effect.serviceOption(TelemetryDebugMode);
130 + return Option.isSome(bootstrap)
131 + ? bootstrap.value
132 + : yield* loadHostConfig(UNPREFIXED_CONFIG.TELEMETRY_DEBUG);
133 +});
ts/packages/cli/src/utils/cli-args.ts new
+9
@@ -0,0 +1,9 @@
1 +/** Locate the root command after shared options, leaving the original argv intact. */
2 +export const rootCommandIndex = (args: ReadonlyArray<string>): number => {
3 + let index = 0;
4 + while (index < args.length && args[index].startsWith('-')) {
5 + if (args[index] === '--') return index;
6 + index += args[index] === '--log-level' ? 2 : 1;
7 + }
8 + return index;
9 +};
ts/packages/cli/test/src/analytics.events.test.ts
+25
@@ -631,6 +631,31 @@ describe('CLI analytics journey taxonomy', () => {
631 });
632 });
633
634 + it.each([
635 + { flags: ['--telemetry-debug'] },
636 + { flags: ['--telemetry-debug=false'] },
637 + { flags: ['--no-telemetry-debug'] },
638 + { flags: ['--tool-debug', '--perf-debug'] },
639 + { flags: ['--log-level', 'Debug'] },
640 + { flags: ['--log-level=Debug', '--telemetry-debug'] },
641 + ])('identifies run and execute after shared options: $flags', ({ flags }) => {
642 + const runArgs = [...flags, 'run', 'console.log("hi")'];
643 + const run = contextFor(runArgs);
644 + expect(run.argv).toEqual(['bun', 'composio', ...runArgs]);
645 + expect(run.commandPath).toBe('run');
646 + expect(run.runId).toEqual(expect.any(String));
647 + expect(getPrimaryLifecycleInvokedEvent(run)).toMatchObject({
648 + name: CLI_ANALYTICS_EVENTS.CLI_RUN_INVOKED,
649 + properties: { run_id: run.runId, command_path: 'run' },
650 + });
651 +
652 + const execute = contextFor([...flags, 'execute', 'GMAIL_SEND_EMAIL', '--get-schema']);
653 + expect(getPrimaryLifecycleInvokedEvent(execute)).toMatchObject({
654 + name: CLI_ANALYTICS_EVENTS.CLI_EXECUTE_INVOKED,
655 + properties: { command_path: 'execute', tool_slug: 'GMAIL_SEND_EMAIL' },
656 + });
657 + });
658 +
659 it('uses the configured parent run id for nested run telemetry', () => {
660 const context = contextFor(['run', 'console.log("hi")'], {
661 invocationOrigin: 'run',
ts/packages/cli/test/src/cli-main.test.ts
+22
@@ -5,6 +5,28 @@ import { describe, expect, it } from 'vitest';
5 import * as tempy from 'tempy';
6
7 describe('CLI process error handling', () => {
8 + it('records help and version as successes and invalid help as a failure', () => {
9 + const configDirectory = tempy.temporaryDirectory();
10 + for (const args of [[], ['help'], ['--help'], ['--version'], ['help', 'orgz']]) {
11 + const result = spawnSync('bun', ['run', 'src/bin.ts', ...args], {
12 + cwd: process.cwd(),
13 + encoding: 'utf8',
14 + env: {
15 + ...process.env,
16 + CI: '1',
17 + NO_COLOR: '1',
18 + COMPOSIO_CACHE_DIR: configDirectory,
19 + COMPOSIO_CLI_TELEMETRY_DISABLED: '1',
20 + COMPOSIO_CLI_TELEMETRY_DEBUG: '1',
21 + },
22 + });
23 + const invalid = args.includes('orgz');
24 + expect(result.status).toBe(invalid ? 1 : 0);
25 + expect(result.stderr).toContain(invalid ? 'CLI_COMMAND_FAILED' : 'CLI_COMMAND_SUCCEEDED');
26 + expect(result.stderr).not.toContain(invalid ? 'CLI_COMMAND_SUCCEEDED' : 'CLI_COMMAND_FAILED');
27 + }
28 + });
29 +
30 it('prints unreported typed execute failures and exits non-zero', () => {
31 const configDirectory = tempy.temporaryDirectory();
32 fs.writeFileSync(
ts/packages/cli/test/src/commands/$default.cmd.test.ts
+3 -34
@@ -51,7 +51,7 @@ describe('CLI: composio', () => {
51 yield* cli([]);
52 const lines = yield* MockConsole.getLines({ stripAnsi: true });
53 const output = lines.join('\n');
54 - expect(output).toContain('Usage:');
54 + expect(output).toContain('USAGE');
55 expect(output).toContain('composio');
56 expect(output).not.toContain('composio connections list');
57 })
@@ -66,43 +66,12 @@ describe('CLI: composio', () => {
66 const lines = yield* MockConsole.getLines({ stripAnsi: true });
67 const output = lines.join('\n');
68 expect(output.trim().length).toBeGreaterThan(0);
69 - expect(output).toContain('config.json');
69 + expect(output).toContain('Documentation:');
70 expect(output).not.toContain('connections list');
71 })
72 );
73 });
74
75 - layer(TestLive())(it => {
76 - it.effect('[Given] --help simple [Then] prints the compact root help mode', () =>
77 - Effect.gen(function* () {
78 - yield* cli(['--help', 'simple']);
79 - const lines = yield* MockConsole.getLines({ stripAnsi: true });
80 - const output = lines.join('\n');
81 -
82 - expect(output).toContain('simple help');
83 - expect(output).toContain('composio --help [simple|default|full]');
84 - expect(output).not.toContain('composio run');
85 - expect(output).not.toContain('MORE COMMANDS');
86 - })
87 - );
88 - });
89 -
90 - layer(TestLive())(it => {
91 - it.effect('[Given] --help full [Then] prints the expanded root help mode', () =>
92 - Effect.gen(function* () {
93 - yield* cli(['--help', 'full']);
94 - const lines = yield* MockConsole.getLines({ stripAnsi: true });
95 - const output = lines.join('\n');
96 -
97 - expect(output).toContain('full help');
98 - expect(output).toContain('MORE COMMANDS');
99 - expect(output).toContain('dev playground-execute');
100 - expect(output).toContain('generate ts');
101 - expect(output).toContain('connections list');
102 - })
103 - );
104 - });
105 -
75 layer(TestLive())(it => {
76 it.effect('[Given] --version or -v [Then] prints exactly what `composio version` prints', () =>
77 Effect.gen(function* () {
@@ -110,7 +79,7 @@ describe('CLI: composio', () => {
79 const linesFor = (args: ReadonlyArray<string>) =>
80 Effect.gen(function* () {
81 yield* cli(args);
113 - return yield* MockConsole.getLines();
82 + return yield* MockConsole.getLines({ stream: 'stdout' });
83 }).pipe(Effect.provide(TestLive()));
84
85 const expected = yield* linesFor(['version']);
ts/packages/cli/test/src/commands/auth-configs/auth-configs.create.cmd.test.ts
+5 -37
@@ -21,14 +21,7 @@ describe('CLI: composio dev auth-configs create', () => {
21 it => {
22 it.effect('creates successfully', () =>
23 Effect.gen(function* () {
24 - yield* cli([
25 - 'dev',
26 - 'auth-configs',
27 - 'create',
28 - '--toolkit',
29 - 'gmail',
30 - '--dangerously-allow',
31 - ]);
24 + yield* cli(['dev', 'auth-configs', 'create', '--toolkit', 'gmail']);
25 const lines = yield* MockConsole.getLines({ stripAnsi: true });
26 const output = lines.join('\n');
27
@@ -45,15 +38,7 @@ describe('CLI: composio dev auth-configs create', () => {
38 it => {
39 it.effect('creates with name successfully', () =>
40 Effect.gen(function* () {
48 - yield* cli([
49 - 'dev',
50 - 'auth-configs',
51 - 'create',
52 - 'my-config',
53 - '--toolkit',
54 - 'gmail',
55 - '--dangerously-allow',
56 - ]);
41 + yield* cli(['dev', 'auth-configs', 'create', 'my-config', '--toolkit', 'gmail']);
42 const lines = yield* MockConsole.getLines({ stripAnsi: true });
43 const output = lines.join('\n');
44
@@ -77,7 +62,6 @@ describe('CLI: composio dev auth-configs create', () => {
62 'gmail',
63 '--auth-scheme',
64 'OAUTH2',
80 - '--dangerously-allow',
65 ]);
66 const lines = yield* MockConsole.getLines({ stripAnsi: true });
67 const output = lines.join('\n');
@@ -102,7 +86,7 @@ describe('CLI: composio dev auth-configs create', () => {
86 )('[Given] custom create response [Then] shows correct details', it => {
87 it.effect('shows custom response data', () =>
88 Effect.gen(function* () {
105 - yield* cli(['dev', 'auth-configs', 'create', '--toolkit', 'slack', '--dangerously-allow']);
89 + yield* cli(['dev', 'auth-configs', 'create', '--toolkit', 'slack']);
90 const lines = yield* MockConsole.getLines({ stripAnsi: true });
91 const output = lines.join('\n');
92
@@ -128,7 +112,6 @@ describe('CLI: composio dev auth-configs create', () => {
112 'OAUTH2',
113 '--custom-credentials',
114 '{invalid json}',
131 - '--dangerously-allow',
115 ]);
116 const lines = yield* MockConsole.getLines({ stripAnsi: true });
117 const output = lines.join('\n');
@@ -144,14 +127,7 @@ describe('CLI: composio dev auth-configs create', () => {
127 it => {
128 it.effect('warns user to login', () =>
129 Effect.gen(function* () {
147 - yield* cli([
148 - 'dev',
149 - 'auth-configs',
150 - 'create',
151 - '--toolkit',
152 - 'gmail',
153 - '--dangerously-allow',
154 - ]);
130 + yield* cli(['dev', 'auth-configs', 'create', '--toolkit', 'gmail']);
131 const lines = yield* MockConsole.getLines({ stripAnsi: true });
132 const output = lines.join('\n');
133
@@ -166,14 +142,7 @@ describe('CLI: composio dev auth-configs create', () => {
142 it => {
143 it.effect('shows next step hint', () =>
144 Effect.gen(function* () {
169 - yield* cli([
170 - 'dev',
171 - 'auth-configs',
172 - 'create',
173 - '--toolkit',
174 - 'gmail',
175 - '--dangerously-allow',
176 - ]);
145 + yield* cli(['dev', 'auth-configs', 'create', '--toolkit', 'gmail']);
146 const lines = yield* MockConsole.getLines({ stripAnsi: true });
147 const output = lines.join('\n');
148
@@ -218,7 +187,6 @@ describe('CLI: composio dev auth-configs create', () => {
187 '{"client_id":"my_client_id","client_secret":"my_client_secret"}',
188 '--scopes',
189 'read_products, write_products',
221 - '--dangerously-allow',
190 ]);
191
192 expect(capturedCreateAuthConfig).toStrictEqual({
ts/packages/cli/test/src/commands/dev.cmd.test.ts
+14 -14
@@ -9,14 +9,14 @@ const testConfigProvider = ConfigProvider.fromEnv({
9
10 describe('CLI: composio dev', () => {
11 layer(TestLive({ baseConfigProvider: testConfigProvider }))(it => {
12 - it.effect('renders custom help when developer mode is on', () =>
12 + it.effect('renders generated help when developer mode is on', () =>
13 Effect.gen(function* () {
14 yield* cli(['dev', '--help']);
15 const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
16
17 - expect(output).toContain('PROJECT');
18 - expect(output).toContain('GUARDED');
19 - expect(output).toContain('--mode <on|off>');
17 + expect(output).toContain('projects');
18 + expect(output).toContain('triggers');
19 + expect(output).toContain('--mode');
20 })
21 );
22 });
@@ -32,18 +32,18 @@ describe('CLI: composio dev', () => {
32 yield* cli(['dev', '--help']);
33 const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
34
35 - expect(output).toContain('Developer mode is off');
35 + expect(output).toContain('When off');
36 expect(output).toContain('composio dev --mode on');
37 - expect(output).not.toContain('PROJECT');
37 + expect(output).not.toContain('projects');
38 })
39 );
40
41 it.effect('blocks dev subcommands when developer mode is off', () =>
42 Effect.gen(function* () {
43 - yield* cli(['dev', 'init']);
43 + expect((yield* Effect.result(cli(['dev', 'init'])))._tag).toBe('Failure');
44 const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
45
46 - expect(output).toContain('Developer mode is off');
46 + expect(output).toContain('When off');
47 expect(output).toContain('composio dev --mode on');
48 })
49 );
@@ -53,11 +53,11 @@ describe('CLI: composio dev', () => {
53 it.effect('persists mode changes through the config service', () =>
54 Effect.gen(function* () {
55 yield* cli(['dev', '--mode', 'off']);
56 - yield* cli(['dev', 'init']);
56 + expect((yield* Effect.result(cli(['dev', 'init'])))._tag).toBe('Failure');
57 const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
58
59 expect(output).toContain('Developer mode disabled');
60 - expect(output).toContain('Developer mode is off');
60 + expect(output).toContain('When off');
61 })
62 );
63 });
@@ -65,8 +65,8 @@ describe('CLI: composio dev', () => {
65 layer(TestLive({ baseConfigProvider: testConfigProvider }))(it => {
66 it.effect('blocks destructive dev commands until config enables them', () =>
67 Effect.gen(function* () {
68 - yield* cli(['dev', 'triggers', 'disable', 'trg_123']);
69 - const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
68 + const error = yield* Effect.flip(cli(['dev', 'triggers', 'disable', 'trg_123']));
69 + const output = String(error);
70
71 expect(output).toContain('disabled by config');
72 expect(output).toContain('developer.destructive_actions');
@@ -82,8 +82,8 @@ describe('CLI: composio dev', () => {
82 )(it => {
83 it.effect('requires --dangerously-allow for destructive dev commands', () =>
84 Effect.gen(function* () {
85 - yield* cli(['dev', 'triggers', 'disable', 'trg_123']);
86 - const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
85 + const error = yield* Effect.flip(cli(['dev', 'triggers', 'disable', 'trg_123']));
86 + const output = String(error);
87
88 expect(output).toContain('requires explicit acknowledgement');
89 expect(output).toContain('--dangerously-allow');
ts/packages/cli/test/src/commands/feature-visibility.test.ts
+24 -70
@@ -2,79 +2,33 @@ import { layer } from '@effect/vitest';
2 import { Effect } from 'effect';
3 import { describe, expect, it } from 'vitest';
4 import { buildRootCommand } from 'src/commands';
5 -import {
6 - getCommandHelpText,
7 - matchCommandFromArgv,
8 - matchSubcommandHelp,
9 - printSubcommandHelp,
10 -} from 'src/commands/root-help';
11 -import { MockConsole, TestLive } from 'test/__utils__';
5 +import { cli, MockConsole, TestLive } from 'test/__utils__';
6
13 -const stableVisibility = {
14 - isDevModeEnabled: true,
15 - isExperimentalFeatureEnabled: () => false,
16 -};
17 -
18 -const betaVisibility = {
19 - isDevModeEnabled: true,
20 - isExperimentalFeatureEnabled: () => true,
21 -};
22 -
23 -const getSubcommandNames = (visibility: typeof stableVisibility) =>
24 - buildRootCommand(visibility).subcommands.flatMap(group => group.commands.map(cmd => cmd.name));
7 +const rootNames = (experimental: boolean) =>
8 + buildRootCommand({
9 + isDevModeEnabled: true,
10 + isExperimentalFeatureEnabled: () => experimental,
11 + }).subcommands.flatMap(group => group.commands.map(cmd => cmd.name));
12
13 describe('CLI experimental feature visibility', () => {
27 - it('hides experimental root commands from the stable root command graph', () => {
28 - expect(getSubcommandNames(stableVisibility)).not.toContain('listen');
29 - expect(getSubcommandNames(betaVisibility)).toContain('listen');
30 - });
31 -
32 - it('hides listen help when the feature is disabled', () => {
33 - expect(matchSubcommandHelp(['bun', 'composio', 'listen', '--help'], stableVisibility)).toBe(
34 - undefined
35 - );
36 - expect(matchSubcommandHelp(['bun', 'composio', 'listen', '--help'], betaVisibility)).toBe(
37 - 'listen'
38 - );
14 + it('keeps experimental commands out of the stable command tree', () => {
15 + expect(rootNames(false)).not.toContain('listen');
16 + expect(rootNames(true)).toContain('listen');
17 });
18
41 - it('hides contextual experimental help when the feature is disabled', () => {
42 - expect(matchCommandFromArgv(['bun', 'composio', 'listen'], stableVisibility)).toBe(undefined);
43 - expect(matchCommandFromArgv(['bun', 'composio', 'listen'], betaVisibility)).toBe('listen');
44 - expect(getCommandHelpText('listen', stableVisibility)).toBe(undefined);
45 - expect(getCommandHelpText('listen', betaVisibility)).toContain('composio listen');
46 - });
47 -
48 - it('shows stable account selection for execute and proxy', () => {
49 - expect(getCommandHelpText('execute', stableVisibility)).toContain('--account <selector>');
50 - expect(getCommandHelpText('proxy', stableVisibility)).toContain('--account <selector>');
51 - expect(getCommandHelpText('link', stableVisibility)).not.toContain(
52 - 'multi_account experimental feature'
53 - );
54 - });
55 -
56 - it('accepts help mode suffixes when matching subcommand help', () => {
57 - expect(
58 - matchSubcommandHelp(['bun', 'composio', 'search', '--help', 'simple'], stableVisibility)
59 - ).toBe('search');
60 - expect(
61 - matchSubcommandHelp(['bun', 'composio', 'search', '--help', 'full'], stableVisibility)
62 - ).toBe('search');
63 - });
64 -});
65 -
66 -describe('CLI help levels', () => {
67 - layer(TestLive())(it => {
68 - it.effect('renders compact subcommand help in simple mode', () =>
69 - Effect.gen(function* () {
70 - yield* printSubcommandHelp('run', stableVisibility, 'simple');
71 - const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
72 -
73 - expect(output).toContain('USAGE');
74 - expect(output).toContain('DESCRIPTION');
75 - expect(output).not.toContain('EXAMPLES');
76 - expect(output).not.toContain('INJECTED HELPERS');
77 - })
78 - );
79 - });
19 + for (const enabled of [false, true]) {
20 + layer(TestLive({ cliUserConfig: { experimentalFeatures: { listen: enabled } } }))(it => {
21 + it.effect(`uses the same visibility for root help and help aliases (listen=${enabled})`, () =>
22 + Effect.gen(function* () {
23 + yield* cli(['--help']);
24 + const output = (yield* MockConsole.getLines({ stripAnsi: true, stream: 'stdout' })).join(
25 + '\n'
26 + );
27 + expect(output.includes('listen')).toBe(enabled);
28 + const result = yield* Effect.result(cli(['help', 'listen']));
29 + expect(result._tag === 'Success').toBe(enabled);
30 + })
31 + );
32 + });
33 + }
34 });
ts/packages/cli/test/src/commands/index.test.ts deleted
-36
@@ -1,36 +0,0 @@
1 -import { describe, expect, it } from 'vitest';
2 -import { parseExecuteInputHelpSlug } from 'src/commands';
3 -
4 -describe('execute input-help routing', () => {
5 - it('does not mistake value-taking option values for the slug', () => {
6 - expect(
7 - parseExecuteInputHelpSlug([
8 - 'bun',
9 - 'composio',
10 - 'execute',
11 - '--account',
12 - 'default',
13 - '--file',
14 - './input.txt',
15 - 'GMAIL_SEND_EMAIL',
16 - '--help',
17 - ])
18 - ).toBe('GMAIL_SEND_EMAIL');
19 - });
20 -
21 - it('does not treat the parallel flag as a value-taking option', () => {
22 - expect(
23 - parseExecuteInputHelpSlug([
24 - 'bun',
25 - 'composio',
26 - 'execute',
27 - '--parallel',
28 - 'GMAIL_SEND_EMAIL',
29 - '-d',
30 - '{}',
31 - 'GITHUB_CREATE_AN_ISSUE',
32 - '--help',
33 - ])
34 - ).toBe('GMAIL_SEND_EMAIL');
35 - });
36 -});
ts/packages/cli/test/src/commands/install-skill-root-flag.test.ts deleted
-98
@@ -1,98 +0,0 @@
1 -import { describe, expect, it } from '@effect/vitest';
2 -import { Effect, Option } from 'effect';
3 -import { parseRootInstallSkillRequest } from 'src/commands';
4 -
5 -describe('CLI: --install-skill', () => {
6 - it.effect('parses the default skill name when only a target is provided', () =>
7 - Effect.gen(function* () {
8 - const request = yield* parseRootInstallSkillRequest([
9 - 'node',
10 - 'composio',
11 - '--install-skill',
12 - 'claude',
13 - ]);
14 - expect(Option.getOrUndefined(request)).toEqual({ target: 'claude' });
15 - })
16 - );
17 -
18 - it.effect('parses an explicit skill name and target', () =>
19 - Effect.gen(function* () {
20 - const request = yield* parseRootInstallSkillRequest([
21 - 'node',
22 - 'composio',
23 - '--install-skill',
24 - 'composio-cli',
25 - 'codex',
26 - ]);
27 - expect(Option.getOrUndefined(request)).toEqual({
28 - skillName: 'composio-cli',
29 - target: 'codex',
30 - });
31 - })
32 - );
33 -
34 - it.effect('accepts the legacy --instal-skill alias', () =>
35 - Effect.gen(function* () {
36 - const request = yield* parseRootInstallSkillRequest([
37 - 'node',
38 - 'composio',
39 - '--instal-skill',
40 - 'openclaw',
41 - ]);
42 - expect(Option.getOrUndefined(request)).toEqual({
43 - target: 'openclaw',
44 - });
45 - })
46 - );
47 -
48 - it.effect('accepts the root flag after leading global options', () =>
49 - Effect.gen(function* () {
50 - const request = yield* parseRootInstallSkillRequest([
51 - 'node',
52 - 'composio',
53 - '--log-level',
54 - 'debug',
55 - '--install-skill',
56 - 'claude',
57 - ]);
58 - expect(Option.getOrUndefined(request)).toEqual({
59 - target: 'claude',
60 - });
61 - })
62 - );
63 -
64 - it.effect('does not intercept subcommand flags after a positional command', () =>
65 - Effect.gen(function* () {
66 - const request = yield* parseRootInstallSkillRequest([
67 - 'node',
68 - 'composio',
69 - 'upgrade',
70 - '--install-skill',
71 - 'claude',
72 - ]);
73 - expect(Option.isNone(request)).toBe(true);
74 - })
75 - );
76 -
77 - it.effect('returns a helpful error when the target is missing', () =>
78 - Effect.gen(function* () {
79 - const error = yield* Effect.flip(
80 - parseRootInstallSkillRequest(['node', 'composio', '--install-skill'])
81 - );
82 - expect(error.message).toBe(
83 - 'Missing target for --install-skill. Usage: composio --install-skill [skill-name] <claude|codex|openclaw>'
84 - );
85 - })
86 - );
87 -
88 - it.effect('returns a helpful error for invalid targets', () =>
89 - Effect.gen(function* () {
90 - const error = yield* Effect.flip(
91 - parseRootInstallSkillRequest(['node', 'composio', '--install-skill', 'cursor'])
92 - );
93 - expect(error.message).toBe(
94 - 'Invalid target for --install-skill. Expected one of: claude, codex, openclaw.'
95 - );
96 - })
97 - );
98 -});
ts/packages/cli/test/src/commands/projects/projects.switch.cmd.test.ts
+1 -3
@@ -6,9 +6,7 @@ describe('CLI: composio dev projects switch', () => {
6 layer(TestLive({ cliUserConfig: { developerDangerousCommandsEnabled: true } }))(it => {
7 it.effect('[Then] it reports global developer project switching is deprecated', () =>
8 Effect.gen(function* () {
9 - yield* cli(['dev', 'projects', 'switch', '--dangerously-allow']).pipe(
10 - Effect.catch(() => Effect.void)
11 - );
9 + yield* cli(['dev', 'projects', 'switch']).pipe(Effect.catch(() => Effect.void));
10 const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
11 expect(output).toMatch(/composio dev init/);
12 })
ts/packages/cli/test/src/commands/root-help-consistency.test.ts
+117 -245
@@ -1,31 +1,11 @@
1 -import { layer } from '@effect/vitest';
1 +import { describe, expect, layer } from '@effect/vitest';
2 import { Effect } from 'effect';
3 -import { teardown } from 'src/cli-main';
4 -import { afterEach, describe, expect, it } from 'vitest';
3 +import { afterEach } from 'vitest';
4 import { buildRootCommand } from 'src/commands';
6 -import {
7 - getCommandHelpText,
8 - matchSubcommandHelp,
9 - printSubcommandHelp,
10 -} from 'src/commands/root-help';
5 +import { teardown } from 'src/cli-main';
6 import { cli, MockConsole, TestLive } from 'test/__utils__';
7
13 -const stableVisibility = {
14 - isDevModeEnabled: true,
15 - isExperimentalFeatureEnabled: () => false,
16 -};
17 -
18 -// Beta builds expose experimental commands, so the registry check covers that surface too.
19 -const allFeaturesVisibility = {
20 - isDevModeEnabled: true,
21 - isExperimentalFeatureEnabled: () => true,
22 -};
23 -
24 -const getVisibleRootCommandNames = (visibility: typeof stableVisibility) =>
25 - buildRootCommand(visibility).subcommands.flatMap(group => group.commands.map(cmd => cmd.name));
26 -
27 -/** Runs the CLI and returns the exit code `cli-main` would hand the process, plus split streams. */
28 -const runCapturingExit = (args: ReadonlyArray<string>) =>
8 +const capture = (args: ReadonlyArray<string>) =>
9 Effect.gen(function* () {
10 const exit = yield* Effect.exit(cli(args));
11 let exitCode = 0;
@@ -35,250 +15,142 @@ const runCapturingExit = (args: ReadonlyArray<string>) =>
15 const stdout = (yield* MockConsole.getLines({ stripAnsi: true, stream: 'stdout' })).join('\n');
16 const stderr = (yield* MockConsole.getLines({ stripAnsi: true, stream: 'stderr' })).join('\n');
17 return { exitCode, stdout, stderr };
38 - });
18 + }).pipe(Effect.provide(TestLive()));
19 +
20 +const commandPaths = (
21 + command: ReturnType<typeof buildRootCommand> | import('effect/unstable/cli').Command.Command.Any,
22 + prefix: ReadonlyArray<string> = []
23 +): ReadonlyArray<ReadonlyArray<string>> =>
24 + command.subcommands
25 + .flatMap(group => group.commands)
26 + .filter(child => child.name !== 'help' && !child.unlisted)
27 + .flatMap(child => {
28 + const path = [...prefix, child.name];
29 + return [path, ...commandPaths(child, path)];
30 + });
31
40 -describe('subcommand help registry consistency', () => {
32 +describe('framework command help', () => {
33 afterEach(() => {
34 process.exitCode = undefined;
35 });
36
45 - it.each([
46 - ['stable', stableVisibility],
47 - ['all experimental features', allFeaturesVisibility],
48 - ])('has a curated help entry for every visible root command (%s)', (_, visibility) => {
49 - for (const name of getVisibleRootCommandNames(visibility)) {
50 - const matched = matchSubcommandHelp(['bun', 'composio', name, '--help'], visibility);
51 - expect(matched, `missing curated help for \`composio ${name}\``).toBe(name);
52 - }
53 - });
54 -
55 - it('matches every orgs family invocation', () => {
56 - expect(matchSubcommandHelp(['bun', 'composio', 'orgs', '--help'], stableVisibility)).toBe(
57 - 'orgs'
37 + layer(TestLive())(it => {
38 + it.effect('renders every visible command from the same definitions used by parsing', () =>
39 + Effect.gen(function* () {
40 + const root = buildRootCommand({
41 + isDevModeEnabled: true,
42 + isExperimentalFeatureEnabled: () => true,
43 + });
44 + for (const path of commandPaths(root)) {
45 + // Experimental commands in the test config must be enabled independently of the graph.
46 + if (path[0] === 'listen') continue;
47 + const flag = yield* capture([...path, '--help']);
48 + const alias = yield* capture(['help', ...path]);
49 + expect(flag.exitCode, path.join(' ')).toBe(0);
50 + expect(alias.exitCode, path.join(' ')).toBe(0);
51 + expect(alias.stdout, path.join(' ')).toBe(flag.stdout);
52 + expect(flag.stdout).toContain('USAGE');
53 + expect(flag.stderr).toBe('');
54 + expect(alias.stderr).toBe('');
55 + }
56 + })
57 );
59 - expect(
60 - matchSubcommandHelp(['bun', 'composio', 'orgs', 'list', '--help'], stableVisibility)
61 - ).toBe('orgs list');
62 - expect(
63 - matchSubcommandHelp(['bun', 'composio', 'orgs', 'switch', '--help'], stableVisibility)
64 - ).toBe('orgs switch');
65 - expect(
66 - matchSubcommandHelp(['bun', 'composio', 'orgs', '--help', 'full'], stableVisibility)
67 - ).toBe('orgs');
68 - });
58
70 - it('matches every agent family invocation', () => {
71 - expect(matchSubcommandHelp(['bun', 'composio', 'agent', '--help'], stableVisibility)).toBe(
72 - 'agent'
59 + it.effect('includes flags previously missing from the hand-written pages', () =>
60 + Effect.gen(function* () {
61 + expect((yield* capture(['version', '--help'])).stdout).toContain('--check');
62 + const run = yield* capture(['run', '--help']);
63 + expect(run.stdout).toContain('--skip-checks');
64 + expect(run.stdout).toContain('--logs-off');
65 + expect(run.stdout).not.toContain('--perf-debug');
66 + })
67 );
74 - for (const child of ['signup', 'login', 'whoami', 'inbox', 'claim']) {
75 - expect(
76 - matchSubcommandHelp(['bun', 'composio', 'agent', child, '--help'], stableVisibility),
77 - `missing curated help for \`composio agent ${child}\``
78 - ).toBe(`agent ${child}`);
79 - }
80 - });
68
82 - it('uses the current orgs description in contextual help', () => {
83 - expect(getCommandHelpText('orgs', stableVisibility)).toContain(
84 - 'Manage default global organization/project context.'
69 + it.effect('keeps errors and suggestions on stderr with a failing exit code', () =>
70 + Effect.gen(function* () {
71 + for (const args of [
72 + ['help', 'frobnicate'],
73 + ['help', 'orgz'],
74 + ['tools', 'frobnicate'],
75 + ]) {
76 + const output = yield* capture(args);
77 + expect(output.exitCode).toBe(1);
78 + expect(output.stdout).toBe('');
79 + expect(output.stderr).toContain('Unknown subcommand');
80 + }
81 + expect((yield* capture(['help', 'orgz'])).stderr).toContain('Did you mean');
82 + })
83 );
86 - });
84
88 - layer(TestLive())(it => {
89 - it.effect('renders the curated orgs page', () =>
85 + it.effect('supports bare help, help aliases, and redundant help flags', () =>
86 Effect.gen(function* () {
91 - yield* printSubcommandHelp('orgs', stableVisibility);
92 - const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
93 -
94 - expect(output).toContain('USAGE');
95 - expect(output).toContain('composio orgs <subcommand>');
96 - expect(output).toContain('SEE ALSO');
97 - expect(output).toContain('composio orgs list');
98 - expect(output).toContain('composio orgs switch');
87 + for (const args of [[], ['help'], ['help', '--help'], ['--help'], ['-h']]) {
88 + const output = yield* capture(args);
89 + expect(output.exitCode).toBe(0);
90 + expect(output.stdout).toContain('Documentation:');
91 + expect(output.stderr).toBe('');
92 + }
93 })
94 );
101 - });
95
103 - layer(TestLive())(it => {
104 - it.effect('renders curated pages for formerly raw-fallback groups', () =>
96 + it.effect('documents the actual flags on previously unreachable nested pages', () =>
97 Effect.gen(function* () {
106 - for (const cmd of ['connections', 'triggers', 'tools', 'artifacts', 'install']) {
107 - // MockConsole accumulates across renders; inspect only this page's lines.
108 - const before = (yield* MockConsole.getLines()).length;
109 - yield* printSubcommandHelp(cmd, stableVisibility);
110 - const output = (yield* MockConsole.getLines({ stripAnsi: true }))
111 - .slice(before)
112 - .join('\n');
113 - expect(output, `\`composio ${cmd}\` help page`).toContain('USAGE');
114 - expect(output, `\`composio ${cmd}\` help page`).toContain(`composio ${cmd}`);
98 + for (const [path, flags] of [
99 + [['login'], ['--agent']],
100 + [['search'], ['--json']],
101 + [
102 + ['dev', 'connected-accounts', 'link'],
103 + ['--auth-config', '--user-id'],
104 + ],
105 + [
106 + ['dev', 'triggers', 'listen'],
107 + ['--user-id', '--forward', '--max-events'],
108 + ],
109 + [['dev', 'triggers', 'disable'], ['--dangerously-allow']],
110 + ] as const) {
111 + const output = yield* capture([...path, '--help']);
112 + expect(output.exitCode).toBe(0);
113 + for (const flag of flags) expect(output.stdout, path.join(' ')).toContain(flag);
114 }
115 + const projectSwitch = yield* capture(['dev', 'projects', 'switch', '--help']);
116 + expect(projectSwitch.stdout).toContain('composio dev projects switch');
117 + expect(projectSwitch.stdout).toContain('Switch the developer project');
118 + const root = yield* capture(['--help']);
119 + expect(root.stdout).not.toContain('composio files');
120 + expect(root.stdout).not.toContain('MODE');
121 + expect(root.stdout).not.toContain('api-info');
122 + expect(root.stdout).not.toContain('--tool-debug');
123 })
124 );
118 - });
125
120 - layer(TestLive())(it => {
121 - it.effect('renders the curated agent signup page', () =>
126 + it.effect('renders parallel help through the framework before executing any tools', () =>
127 Effect.gen(function* () {
123 - yield* printSubcommandHelp('agent signup', stableVisibility);
124 - const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
125 -
126 - expect(output).toContain('USAGE');
127 - expect(output).toContain('composio agent signup');
128 - expect(output).toContain('--no-wait');
129 - expect(output).toContain('Sign up and optionally log in as a Composio agent.');
128 + for (const path of [['execute'], ['dev', 'playground-execute']]) {
129 + const help = yield* capture([
130 + ...path,
131 + '--parallel',
132 + 'GMAIL_SEND_EMAIL',
133 + '-d',
134 + '{}',
135 + 'GITHUB_CREATE_ISSUE',
136 + '--help',
137 + ]);
138 + expect(help.exitCode).toBe(0);
139 + expect(help.stdout).toContain('--parallel');
140 + expect(help.stdout).toContain('--get-schema');
141 + expect(help.stderr).toBe('');
142 + }
143 })
144 );
132 - });
133 -
134 - describe('composio help routing', () => {
135 - layer(TestLive())(it => {
136 - it.effect('bare `composio help` prints the root help page', () =>
137 - Effect.gen(function* () {
138 - yield* cli(['help']);
139 - const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
140 -
141 - expect(output).toContain('USAGE');
142 - expect(output).toContain('LEARN MORE');
143 - })
144 - );
145 - });
146 -
147 - layer(TestLive())(it => {
148 - it.effect('`composio help orgs` matches `composio orgs --help`', () =>
149 - Effect.gen(function* () {
150 - yield* cli(['help', 'orgs']);
151 - const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
145
153 - expect(output).toContain('USAGE');
154 - expect(output).toContain('composio orgs <subcommand>');
155 - expect(output).toContain('composio orgs list');
156 - })
157 - );
158 - });
159 -
160 - layer(TestLive())(it => {
161 - it.effect('`composio help orgs list` prints the orgs list page', () =>
162 - Effect.gen(function* () {
163 - yield* cli(['help', 'orgs', 'list']);
164 - const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
165 -
166 - expect(output).toContain('composio orgs list [--limit integer]');
167 - })
168 - );
169 - });
170 -
171 - layer(TestLive())(it => {
172 - it.effect('`composio help agent signup` prints the agent signup page', () =>
173 - Effect.gen(function* () {
174 - yield* cli(['help', 'agent', 'signup']);
175 - const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
176 -
177 - expect(output).toContain('composio agent signup');
178 - expect(output).toContain('--no-wait');
179 - })
180 - );
181 - });
182 -
183 - layer(TestLive())(it => {
184 - it.effect('`composio help orgs simple` applies the simple level', () =>
185 - Effect.gen(function* () {
186 - yield* cli(['help', 'orgs', 'simple']);
187 - const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
188 -
189 - expect(output).toContain('USAGE');
190 - expect(output).not.toContain('SEE ALSO');
191 - })
192 - );
193 - });
194 -
195 - layer(TestLive())(it => {
196 - it.effect('`composio help orgs full` applies the full level', () =>
197 - Effect.gen(function* () {
198 - yield* cli(['help', 'orgs', 'full']);
199 - const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
200 -
201 - expect(output).toContain('composio orgs <subcommand>');
202 - expect(output).toContain('SEE ALSO');
203 - })
204 - );
205 - });
206 -
207 - layer(TestLive())(it => {
208 - it.effect('`composio help orgs --help` tolerates a trailing help flag', () =>
209 - Effect.gen(function* () {
210 - yield* cli(['help', 'orgs', '--help']);
211 - const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
212 -
213 - expect(output).toContain('composio orgs <subcommand>');
214 - })
215 - );
216 - });
217 -
218 - layer(TestLive())(it => {
219 - it.effect('`composio help dev toolkits` falls back to the curated dev page', () =>
220 - Effect.gen(function* () {
221 - yield* cli(['help', 'dev', 'toolkits']);
222 - const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
223 -
224 - expect(output).toContain('GUARDED');
225 - })
226 - );
227 - });
228 -
229 - layer(TestLive())(it => {
230 - it.effect('`composio help <unknown>` fails like any unknown command', () =>
231 - Effect.gen(function* () {
232 - const { exitCode, stdout, stderr } = yield* runCapturingExit(['help', 'frobnicate']);
233 -
234 - // The framework renders its unknown-subcommand failure (stderr channel,
235 - // "Did you mean?", exit 1 via CliError.ShowHelp) instead of an exit-0
236 - // "Unknown command" line on the stdout data channel.
237 - expect(exitCode).toBe(1);
238 - expect(stdout).toBe('');
239 - expect(stderr).toContain('generate');
240 - expect(stderr).toContain('Unknown subcommand "frobnicate"');
241 - expect(stderr).not.toContain('Unknown subcommand "help"');
242 - })
243 - );
244 - });
245 -
246 - layer(TestLive())(it => {
247 - it.effect('`composio help <typo>` suggests the closest command', () =>
248 - Effect.gen(function* () {
249 - const { exitCode, stdout, stderr } = yield* runCapturingExit(['help', 'orgz']);
250 -
251 - expect(exitCode).toBe(1);
252 - expect(stdout).toBe('');
253 - expect(stderr).toContain('Unknown subcommand "orgz"');
254 - expect(stderr).toContain('Did you mean this?');
255 - })
256 - );
257 - });
258 -
259 - layer(TestLive())(it => {
260 - it.effect('`composio help --help` renders the curated root help', () =>
261 - Effect.gen(function* () {
262 - const { exitCode, stdout, stderr } = yield* runCapturingExit(['help', '--help']);
263 -
264 - expect(exitCode).toBe(0);
265 - expect(stdout).toContain('LEARN MORE');
266 - expect(stdout).not.toContain('--log-level');
267 - expect(stderr).not.toContain('Unknown subcommand');
268 - })
269 - );
270 - });
271 -
272 - layer(TestLive())(it => {
273 - it.effect('`composio help orgs full --help` keeps the requested level', () =>
274 - Effect.gen(function* () {
275 - yield* cli(['help', 'orgs', 'full', '--help']);
276 - const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
277 -
278 - expect(output).toContain('composio orgs <subcommand>');
279 - expect(output).toContain('SEE ALSO');
280 - })
281 - );
282 - });
146 + it.effect('preserves native help after a value-taking option', () =>
147 + Effect.gen(function* () {
148 + const output = yield* capture(['orgs', '--log-level', 'Debug', 'list', '--help']);
149 + expect(output.exitCode).toBe(0);
150 + expect(output.stdout).toContain('composio orgs list');
151 + expect(output.stdout).toContain('--limit');
152 + expect(output.stderr).toBe('');
153 + })
154 + );
155 });
156 });
ts/packages/cli/test/src/commands/run.cmd.test.ts
+38 -7
@@ -127,7 +127,7 @@ describe('CLI: composio run', () => {
127 it.effect('[Given] a root run telemetry id [Then] the child receives the same run id', () =>
128 Effect.gen(function* () {
129 const telemetryContext = createCliCommandTelemetryContext(
130 - ['bun', 'composio', 'run', 'console.log("hi")'],
130 + ['bun', 'composio', '--telemetry-debug', 'run', 'console.log("hi")'],
131 '0.0.0-test',
132 { stdoutIsTTY: false, stderrIsTTY: false },
133 { invocationOrigin: DEFAULT_CLI_INVOCATION_ORIGIN, parentRunId: undefined }
@@ -143,7 +143,7 @@ describe('CLI: composio run', () => {
143
144 // The bootstrap hands the run id it minted for telemetry to the command, the way
145 // `cli-main.ts` does, instead of publishing it through process-wide state.
146 - yield* cli(['run', 'console.log("hi")'], { runId });
146 + yield* cli(['--telemetry-debug', 'run', 'console.log("hi")'], { runId });
147
148 expect(commandRuns).toHaveBeenCalledTimes(1);
149 })
@@ -484,6 +484,40 @@ describe('CLI: composio run', () => {
484 );
485 });
486
487 + layer(RunTestLive())(it => {
488 + it.effect(
489 + 'forwards script flags with or without a delimiter without enabling them in the CLI',
490 + () =>
491 + Effect.gen(function* () {
492 + const script = 'console.log("hi")';
493 + const tail = [
494 + '--perf-debug',
495 + '--tool-debug',
496 + '--acp-only',
497 + '--telemetry-debug',
498 + '--help',
499 + '--version',
500 + ];
501 + for (const args of [
502 + [script, ...tail],
503 + [script, '--', ...tail],
504 + ['--', script, ...tail],
505 + ]) {
506 + yield* cli(['--perf-debug=false', 'run', ...args]);
507 + const spawned = inspectRunCommand(commandRuns.mock.calls.at(-1)![0]);
508 + expect(spawned.cmd.slice(5)).toEqual(['--', ...tail]);
509 + expect(spawned.env).toMatchObject({
510 + COMPOSIO_PERF_DEBUG: '0',
511 + COMPOSIO_TOOL_DEBUG: '0',
512 + COMPOSIO_RUN_ACP_ONLY: '0',
513 + COMPOSIO_CLI_TELEMETRY_DEBUG: '0',
514 + });
515 + }
516 + expect(commandRuns).toHaveBeenCalledTimes(3);
517 + })
518 + );
519 + });
520 +
521 layer(RunTestLive())(it => {
522 it.effect(
523 '[Given] a second literal -- in passthrough args [Then] it is forwarded to the script',
@@ -506,9 +540,6 @@ describe('CLI: composio run', () => {
540 '[Given] a script arg literally starting with the old escape-marker string [Then] it reaches the script untouched',
541 () =>
542 Effect.gen(function* () {
509 - // The passthrough tail is now handed off out-of-band instead of being
510 - // smuggled through the parser with a marker string, so a user token
511 - // that happens to look like the old marker is never mangled.
543 yield* cli(['run', 'console.log("hi")', '@@composio-run-raw@@literal']);
544
545 expect(commandRuns).toHaveBeenCalledTimes(1);
@@ -536,8 +567,8 @@ describe('CLI: composio run', () => {
567 expect(output).toContain('--logs-off');
568 expect(output).toContain('experimental_subAgent');
569 expect(output).toContain('schema: z.object');
539 - expect(output).toContain('INJECTED HELPERS');
540 - expect(output).toContain('Global from zod');
570 + expect(output).toContain('Injected helpers');
571 + expect(output).toContain('Injected global from `zod`');
572 expect(output).toContain('composio search "<query>"');
573 expect(output).toContain('composio execute <slug> --get-schema');
574 expect(output).not.toContain('--acp-only');
ts/packages/cli/test/src/commands/setup-skill.cmd.test.ts new
+42
@@ -0,0 +1,42 @@
1 +import { describe, expect, layer } from '@effect/vitest';
2 +import { Effect } from 'effect';
3 +import { afterEach, vi } from 'vitest';
4 +import { installSkill } from 'src/effects/install-skill';
5 +import { cli, TestLive } from 'test/__utils__';
6 +
7 +vi.mock('src/effects/install-skill', async original => ({
8 + ...(await original<typeof import('src/effects/install-skill')>()),
9 + installSkill: vi.fn(() => Effect.void),
10 +}));
11 +
12 +describe('composio setup skill', () => {
13 + afterEach(() => vi.clearAllMocks());
14 + layer(TestLive())(it => {
15 + it.effect('passes the selected target and optional name to the installer', () =>
16 + Effect.gen(function* () {
17 + yield* cli(['setup', 'skill', 'claude']);
18 + expect(installSkill).toHaveBeenLastCalledWith({ target: 'claude', skillName: undefined });
19 + yield* cli(['setup', 'skill', 'codex', '--name', 'custom-skill']);
20 + expect(installSkill).toHaveBeenLastCalledWith({
21 + target: 'codex',
22 + skillName: 'custom-skill',
23 + });
24 + yield* cli(['setup', 'skill', 'openclaw']);
25 + expect(installSkill).toHaveBeenLastCalledWith({ target: 'openclaw', skillName: undefined });
26 + })
27 + );
28 + it.effect('rejects invalid targets and missing names before installation', () =>
29 + Effect.gen(function* () {
30 + for (const args of [
31 + ['setup', 'skill'],
32 + ['setup', 'skill', 'cursor'],
33 + ['setup', 'skill', 'claude', '--name'],
34 + ]) {
35 + const exit = yield* Effect.result(cli(args));
36 + expect(exit._tag).toBe('Failure');
37 + }
38 + expect(installSkill).not.toHaveBeenCalled();
39 + })
40 + );
41 + });
42 +});
ts/packages/cli/test/src/commands/tools/tools.execute.cmd.test.ts
+42 -50
@@ -18,7 +18,6 @@ import { liveEnvConfigProvider } from 'test/__utils__/live-env-config-provider';
18 import type { TestLiveInput } from 'test/__utils__/services/test-layer';
19 import {
20 parseParallelExecuteArgs,
21 - showToolsExecuteInputHelp,
21 type ParallelExecuteArgumentError,
22 } from 'src/commands/tools/commands/tools.execute.cmd';
23 import { ComposioCliUserConfig } from 'src/services/cli-user-config';
@@ -530,6 +529,41 @@ describe('CLI: composio execute', () => {
529 );
530 })
531 );
532 +
533 + it.effect('keeps every repeated --data and --account with its own parallel tool', () =>
534 + Effect.gen(function* () {
535 + yield* cli([
536 + 'execute',
537 + '--parallel',
538 + '--skip-checks',
539 + 'GMAIL_SEND_EMAIL',
540 + '-d',
541 + '{"recipient":"repeat-first@example.com"}',
542 + '--account',
543 + 'forest',
544 + 'GMAIL_SEND_EMAIL',
545 + '-d',
546 + '{"recipient":"repeat-second@example.com"}',
547 + '--account',
548 + 'castle',
549 + ]);
550 +
551 + // Read this invocation's own aggregate: the console is shared with the
552 + // sibling tests in this layer.
553 + const lines = yield* MockConsole.getLines({ stripAnsi: true });
554 + const output = parseLastJson(lines) as unknown as {
555 + results: Array<{ data: { arguments: Record<string, unknown> } }>;
556 + };
557 + expect(output.results.map(result => result.data.arguments)).toEqual([
558 + { recipient: 'repeat-first@example.com' },
559 + { recipient: 'repeat-second@example.com' },
560 + ]);
561 + expect(recordedSessionCreateParams.map(params => params.connected_accounts)).toEqual(
562 + expect.arrayContaining([{ gmail: 'con_gmail_secondary' }, { gmail: 'con_gmail_default' }])
563 + );
564 + expect(recordedSessionCreateParams).toHaveLength(2);
565 + })
566 + );
567 });
568
569 layer(
@@ -1438,8 +1472,11 @@ describe('CLI: composio execute', () => {
1472 it.effect('aggregates results from multiple tool calls', () =>
1473 Effect.gen(function* () {
1474 yield* cli([
1475 + '--tool-debug=false',
1476 'execute',
1477 '--parallel',
1478 + '--log-level',
1479 + 'Info',
1480 '--skip-checks',
1481 'GMAIL_SEND_EMAIL',
1482 '-d',
@@ -2286,51 +2323,6 @@ describe('CLI: composio execute', () => {
2323 }
2324 );
2325
2289 - layer(
2290 - TestLive({
2291 - baseConfigProvider: testConfigProvider,
2292 - toolkitsData: {
2293 - tools: [
2294 - {
2295 - name: 'Send Email',
2296 - slug: 'GMAIL_SEND_EMAIL',
2297 - description: 'Send an email',
2298 - tags: ['email'],
2299 - available_versions: ['20260101_00'],
2300 - input_parameters: {
2301 - type: 'object',
2302 - required: ['recipient'],
2303 - properties: {
2304 - recipient: { type: 'string', description: 'Recipient email' },
2305 - subject: { type: 'string', description: 'Subject line' },
2306 - },
2307 - },
2308 - output_parameters: {
2309 - type: 'object',
2310 - properties: {
2311 - message_id: { type: 'string' },
2312 - },
2313 - },
2314 - },
2315 - ],
2316 - } satisfies TestLiveInput['toolkitsData'],
2317 - stdin: { isTTY: true, data: '' },
2318 - })
2319 - )('[Given] execute-help helper [Then] prints input parameters only', it => {
2320 - it.effect('prints execute input schema help for the provided slug', () =>
2321 - Effect.gen(function* () {
2322 - yield* showToolsExecuteInputHelp('GMAIL_SEND_EMAIL');
2323 - const lines = yield* MockConsole.getLines({ stripAnsi: true });
2324 - const output = lines.join('\n');
2325 -
2326 - expect(output).toContain('Data Parameters:');
2327 - expect(output).toContain('recipient');
2328 - expect(output).toContain('subject');
2329 - expect(output).not.toContain('Output Parameters:');
2330 - })
2331 - );
2332 - });
2333 -
2326 layer(
2327 TestLive({
2328 baseConfigProvider: testConfigProvider,
@@ -2369,12 +2361,12 @@ describe('CLI: composio execute', () => {
2361 const output = lines.join('\n');
2362
2363 expect(output).toContain('USAGE');
2372 - expect(output).toContain(
2373 - 'composio execute <slug> [-d, --data text] [--account selector] [--file path] [--dry-run] [--get-schema] [--parallel]'
2374 - );
2364 + expect(output).toContain('composio execute');
2365 + expect(output).toContain('--get-schema');
2366 + expect(output).not.toContain('Fetching input parameters');
2367 expect(output).toContain('composio execute GMAIL_SEND_EMAIL --get-schema');
2368 expect(output).toContain('--parallel');
2377 - expect(output).toContain('--account <selector>');
2369 + expect(output).toContain('--account');
2370 expect(output).toContain('GITHUB_CREATE_AN_ISSUE');
2371 })
2372 );
ts/packages/cli/test/src/commands/triggers/triggers.mutations.cmd.test.ts
+2 -6
@@ -25,7 +25,6 @@ describe('CLI: composio dev triggers mutations', () => {
25 'GMAIL_NEW_GMAIL_MESSAGE',
26 '--connected-account-id',
27 'con_123',
28 - '--dangerously-allow',
28 ]);
29 const lines = yield* MockConsole.getLines({ stripAnsi: true });
30 const output = lines.join('\n');
@@ -49,7 +48,6 @@ describe('CLI: composio dev triggers mutations', () => {
48 'GMAIL_NEW_GMAIL_MESSAGE',
49 '--trigger-config',
50 '{',
52 - '--dangerously-allow',
51 ]);
52 const lines = yield* MockConsole.getLines({ stripAnsi: true });
53 const output = lines.join('\n');
@@ -63,7 +61,7 @@ describe('CLI: composio dev triggers mutations', () => {
61 layer(TestLive(dangerousDevConfig))('[Given] enable with ID [Then] enables trigger', it => {
62 it.effect('enables trigger successfully', () =>
63 Effect.gen(function* () {
66 - yield* cli(['dev', 'triggers', 'enable', 'trg_123', '--dangerously-allow']);
64 + yield* cli(['dev', 'triggers', 'enable', 'trg_123']);
65 const lines = yield* MockConsole.getLines({ stripAnsi: true });
66 const output = lines.join('\n');
67 expect(output).toContain('enabled');
@@ -94,7 +92,6 @@ describe('CLI: composio dev triggers mutations', () => {
92 'GMAIL_NEW_GMAIL_MESSAGE',
93 '--trigger-config',
94 '[1,2,3]',
97 - '--dangerously-allow',
95 ]);
96 const lines = yield* MockConsole.getLines({ stripAnsi: true });
97 const output = lines.join('\n');
@@ -112,7 +109,6 @@ describe('CLI: composio dev triggers mutations', () => {
109 'GMAIL_NEW_GMAIL_MESSAGE',
110 '--trigger-config',
111 '42',
115 - '--dangerously-allow',
112 ]);
113 const lines = yield* MockConsole.getLines({ stripAnsi: true });
114 const output = lines.join('\n');
@@ -128,7 +124,7 @@ describe('CLI: composio dev triggers mutations', () => {
124 it => {
125 it.effect('shows missing id warning', () =>
126 Effect.gen(function* () {
131 - yield* cli(['dev', 'triggers', 'enable', '--dangerously-allow']);
127 + yield* cli(['dev', 'triggers', 'enable']);
128 const lines = yield* MockConsole.getLines({ stripAnsi: true });
129 const output = lines.join('\n');
130 expect(output).toContain('Missing required argument');
ts/packages/cli/test/src/services/runtime-flags.test.ts
+15 -32
@@ -9,7 +9,7 @@ import {
9 isTelemetryDebugEnabled,
10 isToolDebugEnabled,
11 NO_CLI_DEBUG_FLAG_OVERRIDES,
12 - stripTelemetryDebugFlag,
12 + readTelemetryDebugOverride,
13 telemetryDebugModeLayer,
14 TELEMETRY_DEBUG_FLAG,
15 } from 'src/services/runtime-flags';
@@ -34,41 +34,24 @@ describe('debugFlagsToChildEnv', () => {
34 });
35 });
36
37 -describe('stripTelemetryDebugFlag', () => {
38 - it('[Given] the flag before the delimiter [Then] it is removed and reported', () => {
39 - expect(stripTelemetryDebugFlag(['bun', 'composio', TELEMETRY_DEBUG_FLAG, 'whoami'])).toEqual({
40 - argv: ['bun', 'composio', 'whoami'],
41 - telemetryDebug: true,
42 - });
37 +describe('telemetry debug bootstrap', () => {
38 + it('reads an override without rewriting argv', () => {
39 + const argv = ['bun', 'composio', TELEMETRY_DEBUG_FLAG, 'whoami'];
40 + expect(readTelemetryDebugOverride(argv)).toBe(true);
41 + expect(argv).toEqual(['bun', 'composio', TELEMETRY_DEBUG_FLAG, 'whoami']);
42 });
44 -
45 - it('[Given] the flag after a `--` delimiter [Then] it belongs to the child and survives', () => {
46 - const argv = ['bun', 'composio', 'run', 'my-agent', '--', TELEMETRY_DEBUG_FLAG];
47 -
48 - expect(stripTelemetryDebugFlag(argv)).toEqual({ argv, telemetryDebug: false });
43 + it('ignores arguments after the delimiter', () => {
44 + expect(
45 + readTelemetryDebugOverride(['bun', 'composio', 'run', '--', TELEMETRY_DEBUG_FLAG])
46 + ).toBeUndefined();
47 });
50 -
51 - it('[Given] the flag on both sides of `--` [Then] only the CLI-side one is consumed', () => {
48 + it('supports an explicit false override', () => {
49 expect(
53 - stripTelemetryDebugFlag([
54 - 'bun',
55 - 'composio',
56 - TELEMETRY_DEBUG_FLAG,
57 - 'run',
58 - 'my-agent',
59 - '--',
60 - TELEMETRY_DEBUG_FLAG,
61 - ])
62 - ).toEqual({
63 - argv: ['bun', 'composio', 'run', 'my-agent', '--', TELEMETRY_DEBUG_FLAG],
64 - telemetryDebug: true,
65 - });
50 + readTelemetryDebugOverride(['bun', 'composio', '--telemetry-debug=false', 'whoami'])
51 + ).toBe(false);
52 });
67 -
68 - it('[Given] no flag [Then] argv is reported unchanged', () => {
69 - const argv = ['bun', 'composio', 'whoami'];
70 -
71 - expect(stripTelemetryDebugFlag(argv)).toEqual({ argv, telemetryDebug: false });
53 + it('leaves absent overrides to configuration', () => {
54 + expect(readTelemetryDebugOverride(['bun', 'composio', 'whoami'])).toBeUndefined();
55 });
56 });
57