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

feat(cli): add proxy execute (#2995)

## Summary - Adds a new `composio proxy` command plus `run`/consumer flow updates to make local execution and debugging easier. - Improves CLI UX across root help, command hints, input validation, and hidden debug handling. - Introduces experimental custom tools and toolkits support in the TypeScript SDK, with docs and examples. - Refreshes release metadata, changelog, and related docs for the new CLI and SDK behavior. - Updates tests and snapshots to cover the new command flows and validation paths. ## Testing - Not run (changes reviewed from diff and existing test coverage updated in the branch). - Updated/added CLI tests for `proxy`, `run`, `tools.execute`, `tools.info`, `tools.list`, `tools.search`, and related command flows. - Updated snapshot coverage for root help and command output changes. --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

Rahul Tarak committed Mar 23, 2026 at 22:03 UTC ae08b37f91034ac0fb0bdb4e6deaf0bd0276bc3b
27 files changed +3237 -726
.changeset/vast-showers-lose.md new
+10
@@ -0,0 +1,10 @@
1 +---
2 +'@composio/cli': patch
3 +---
4 +
5 +- Make top-level `composio search`, `composio link`, and `composio execute` consumer-only
6 +- Keep developer-scoped usage under `composio manage ...`
7 +- Remove developer-only flags from root help and add short related-command hints
8 +- Use `consumer_user_id` from consumer project resolve for consumer flows
9 +- Execute: Default to empty object `{}` when no -d/--data or piped stdin provided
10 +- Search CTA: Use `-d "{}"` for tools with no schema properties (shell-safe)
pnpm-lock.yaml
+17 -66
@@ -703,16 +703,16 @@ importers:
703 version: link:../../packages/providers/llamaindex
704 '@llamaindex/openai':
705 specifier: ^0.4.20
706 - version: 0.4.22(@llamaindex/core@0.6.22)(@llamaindex/env@0.1.30)(ws@8.19.0)(zod@3.25.76)
706 + version: 0.4.22(@llamaindex/core@0.6.22)(@llamaindex/env@0.1.30)(ws@8.19.0)(zod@4.3.6)
707 '@llamaindex/workflow':
708 specifier: ^1.1.24
709 - version: 1.1.24(@llamaindex/core@0.6.22)(@llamaindex/env@0.1.30)(@modelcontextprotocol/sdk@1.26.0(@cfworker/json-schema@4.1.1)(zod@3.25.76))(hono@4.11.9)(zod@3.25.76)
709 + version: 1.1.24(@llamaindex/core@0.6.22)(@llamaindex/env@0.1.30)(@modelcontextprotocol/sdk@1.26.0(@cfworker/json-schema@4.1.1)(zod@4.3.6))(hono@4.11.9)(zod@4.3.6)
710 dotenv:
711 specifier: ^16.4.1
712 version: 16.6.1
713 llamaindex:
714 specifier: ^0.12.0
715 - version: 0.12.1(@modelcontextprotocol/sdk@1.26.0(@cfworker/json-schema@4.1.1)(zod@3.25.76))(hono@4.11.9)(tree-sitter@0.22.4)(web-tree-sitter@0.24.7)(zod@3.25.76)
715 + version: 0.12.1(@modelcontextprotocol/sdk@1.26.0(@cfworker/json-schema@4.1.1)(zod@4.3.6))(hono@4.11.9)(tree-sitter@0.22.4)(web-tree-sitter@0.24.7)(zod@4.3.6)
716 devDependencies:
717 '@types/bun':
718 specifier: ^1.2.9
@@ -1109,6 +1109,9 @@ importers:
1109 ts-morph:
1110 specifier: ^26.0.0
1111 version: 26.0.0
1112 + zod:
1113 + specifier: 'catalog:'
1114 + version: 4.3.6
1115 devDependencies:
1116 '@effect/eslint-plugin':
1117 specifier: 'catalog:'
@@ -1324,7 +1327,7 @@ importers:
1327 dependencies:
1328 llamaindex:
1329 specifier: ^0.12.0
1327 - version: 0.12.1(tree-sitter@0.22.4)(web-tree-sitter@0.24.7)(zod@4.3.6)
1330 + version: 0.12.1(@modelcontextprotocol/sdk@1.26.0(@cfworker/json-schema@4.1.1)(zod@4.3.6))(hono@4.11.9)(tree-sitter@0.22.4)(web-tree-sitter@0.24.7)(zod@4.3.6)
1331 devDependencies:
1332 '@composio/core':
1333 specifier: workspace:*
@@ -7563,43 +7566,26 @@ snapshots:
7566 tree-sitter: 0.22.4
7567 web-tree-sitter: 0.24.7
7568
7566 - '@llamaindex/openai@0.4.22(@llamaindex/core@0.6.22)(@llamaindex/env@0.1.30)(ws@8.19.0)(zod@3.25.76)':
7569 + '@llamaindex/openai@0.4.22(@llamaindex/core@0.6.22)(@llamaindex/env@0.1.30)(ws@8.19.0)(zod@4.3.6)':
7570 dependencies:
7571 '@llamaindex/core': 0.6.22
7572 '@llamaindex/env': 0.1.30
7570 - openai: 5.23.2(ws@8.19.0)(zod@3.25.76)
7573 + openai: 5.23.2(ws@8.19.0)(zod@4.3.6)
7574 transitivePeerDependencies:
7575 - ws
7576 - zod
7577
7575 - '@llamaindex/workflow-core@1.3.3(@modelcontextprotocol/sdk@1.26.0(@cfworker/json-schema@4.1.1)(zod@3.25.76))(hono@4.11.9)(zod@3.25.76)':
7578 + '@llamaindex/workflow-core@1.3.3(@modelcontextprotocol/sdk@1.26.0(@cfworker/json-schema@4.1.1)(zod@4.3.6))(hono@4.11.9)(zod@4.3.6)':
7579 optionalDependencies:
7577 - '@modelcontextprotocol/sdk': 1.26.0(@cfworker/json-schema@4.1.1)(zod@3.25.76)
7580 + '@modelcontextprotocol/sdk': 1.26.0(@cfworker/json-schema@4.1.1)(zod@4.3.6)
7581 hono: 4.11.9
7579 - zod: 3.25.76
7580 -
7581 - '@llamaindex/workflow-core@1.3.3(zod@4.3.6)':
7582 - optionalDependencies:
7582 zod: 4.3.6
7583
7585 - '@llamaindex/workflow@1.1.24(@llamaindex/core@0.6.22)(@llamaindex/env@0.1.30)(@modelcontextprotocol/sdk@1.26.0(@cfworker/json-schema@4.1.1)(zod@3.25.76))(hono@4.11.9)(zod@3.25.76)':
7584 + '@llamaindex/workflow@1.1.24(@llamaindex/core@0.6.22)(@llamaindex/env@0.1.30)(@modelcontextprotocol/sdk@1.26.0(@cfworker/json-schema@4.1.1)(zod@4.3.6))(hono@4.11.9)(zod@4.3.6)':
7585 dependencies:
7586 '@llamaindex/core': 0.6.22
7587 '@llamaindex/env': 0.1.30
7589 - '@llamaindex/workflow-core': 1.3.3(@modelcontextprotocol/sdk@1.26.0(@cfworker/json-schema@4.1.1)(zod@3.25.76))(hono@4.11.9)(zod@3.25.76)
7590 - transitivePeerDependencies:
7591 - - '@modelcontextprotocol/sdk'
7592 - - hono
7593 - - next
7594 - - p-retry
7595 - - rxjs
7596 - - zod
7597 -
7598 - '@llamaindex/workflow@1.1.24(@llamaindex/core@0.6.22)(@llamaindex/env@0.1.30)(zod@4.3.6)':
7599 - dependencies:
7600 - '@llamaindex/core': 0.6.22
7601 - '@llamaindex/env': 0.1.30
7602 - '@llamaindex/workflow-core': 1.3.3(zod@4.3.6)
7588 + '@llamaindex/workflow-core': 1.3.3(@modelcontextprotocol/sdk@1.26.0(@cfworker/json-schema@4.1.1)(zod@4.3.6))(hono@4.11.9)(zod@4.3.6)
7589 transitivePeerDependencies:
7590 - '@modelcontextprotocol/sdk'
7591 - hono
@@ -8533,14 +8519,6 @@ snapshots:
8519 optionalDependencies:
8520 vite: 7.3.1(@types/node@22.19.11)(tsx@4.21.0)(yaml@2.8.2)
8521
8536 - '@vitest/mocker@3.2.4(vite@7.3.1(@types/node@24.10.13)(tsx@4.21.0)(yaml@2.8.2))':
8537 - dependencies:
8538 - '@vitest/spy': 3.2.4
8539 - estree-walker: 3.0.3
8540 - magic-string: 0.30.21
8541 - optionalDependencies:
8542 - vite: 7.3.1(@types/node@24.10.13)(tsx@4.21.0)(yaml@2.8.2)
8543 -
8522 '@vitest/pretty-format@3.2.4':
8523 dependencies:
8524 tinyrainbow: 2.0.0
@@ -8570,7 +8548,7 @@ snapshots:
8548 sirv: 3.0.2
8549 tinyglobby: 0.2.15
8550 tinyrainbow: 2.0.0
8573 - vitest: 3.2.4(@types/node@24.10.13)(@vitest/ui@3.2.4)(tsx@4.21.0)(yaml@2.8.2)
8551 + vitest: 3.2.4(@types/node@22.19.11)(@vitest/ui@3.2.4)(tsx@4.21.0)(yaml@2.8.2)
8552
8553 '@vitest/utils@3.2.4':
8554 dependencies:
@@ -9937,34 +9915,12 @@ snapshots:
9915 rfdc: 1.4.1
9916 wrap-ansi: 9.0.2
9917
9940 - llamaindex@0.12.1(@modelcontextprotocol/sdk@1.26.0(@cfworker/json-schema@4.1.1)(zod@3.25.76))(hono@4.11.9)(tree-sitter@0.22.4)(web-tree-sitter@0.24.7)(zod@3.25.76):
9941 - dependencies:
9942 - '@llamaindex/core': 0.6.22
9943 - '@llamaindex/env': 0.1.30
9944 - '@llamaindex/node-parser': 2.0.22(@llamaindex/core@0.6.22)(@llamaindex/env@0.1.30)(tree-sitter@0.22.4)(web-tree-sitter@0.24.7)
9945 - '@llamaindex/workflow': 1.1.24(@llamaindex/core@0.6.22)(@llamaindex/env@0.1.30)(@modelcontextprotocol/sdk@1.26.0(@cfworker/json-schema@4.1.1)(zod@3.25.76))(hono@4.11.9)(zod@3.25.76)
9946 - '@types/lodash': 4.17.23
9947 - '@types/node': 24.10.13
9948 - lodash: 4.17.23
9949 - magic-bytes.js: 1.13.0
9950 - transitivePeerDependencies:
9951 - - '@huggingface/transformers'
9952 - - '@modelcontextprotocol/sdk'
9953 - - gpt-tokenizer
9954 - - hono
9955 - - next
9956 - - p-retry
9957 - - rxjs
9958 - - tree-sitter
9959 - - web-tree-sitter
9960 - - zod
9961 -
9962 - llamaindex@0.12.1(tree-sitter@0.22.4)(web-tree-sitter@0.24.7)(zod@4.3.6):
9918 + llamaindex@0.12.1(@modelcontextprotocol/sdk@1.26.0(@cfworker/json-schema@4.1.1)(zod@4.3.6))(hono@4.11.9)(tree-sitter@0.22.4)(web-tree-sitter@0.24.7)(zod@4.3.6):
9919 dependencies:
9920 '@llamaindex/core': 0.6.22
9921 '@llamaindex/env': 0.1.30
9922 '@llamaindex/node-parser': 2.0.22(@llamaindex/core@0.6.22)(@llamaindex/env@0.1.30)(tree-sitter@0.22.4)(web-tree-sitter@0.24.7)
9967 - '@llamaindex/workflow': 1.1.24(@llamaindex/core@0.6.22)(@llamaindex/env@0.1.30)(zod@4.3.6)
9923 + '@llamaindex/workflow': 1.1.24(@llamaindex/core@0.6.22)(@llamaindex/env@0.1.30)(@modelcontextprotocol/sdk@1.26.0(@cfworker/json-schema@4.1.1)(zod@4.3.6))(hono@4.11.9)(zod@4.3.6)
9924 '@types/lodash': 4.17.23
9925 '@types/node': 24.10.13
9926 lodash: 4.17.23
@@ -10244,11 +10200,6 @@ snapshots:
10200 is-inside-container: 1.0.0
10201 wsl-utils: 0.1.0
10202
10247 - openai@5.23.2(ws@8.19.0)(zod@3.25.76):
10248 - optionalDependencies:
10249 - ws: 8.19.0
10250 - zod: 3.25.76
10251 -
10203 openai@5.23.2(ws@8.19.0)(zod@4.3.6):
10204 optionalDependencies:
10205 ws: 8.19.0
@@ -11346,7 +11297,7 @@ snapshots:
11297 dependencies:
11298 '@types/chai': 5.2.3
11299 '@vitest/expect': 3.2.4
11349 - '@vitest/mocker': 3.2.4(vite@7.3.1(@types/node@24.10.13)(tsx@4.21.0)(yaml@2.8.2))
11300 + '@vitest/mocker': 3.2.4(vite@7.3.1(@types/node@22.19.11)(tsx@4.21.0)(yaml@2.8.2))
11301 '@vitest/pretty-format': 3.2.4
11302 '@vitest/runner': 3.2.4
11303 '@vitest/snapshot': 3.2.4
ts/packages/cli/package.json
+2 -1
@@ -88,7 +88,8 @@
88 "semver": "^7.7.2",
89 "source-map-js": "^1.2.1",
90 "superjson": "^2.2.2",
91 - "ts-morph": "^26.0.0"
91 + "ts-morph": "^26.0.0",
92 + "zod": "catalog:"
93 },
94 "gitHead": "4fae6e54d5c150fba955cc5fa314281da5a1e064",
95 "module": "./dist/bin.mjs",
ts/packages/cli/src/bin.ts
+4
@@ -28,6 +28,7 @@ import { ProjectEnvironmentDetector } from 'src/services/project-environment-det
28 import { CommandRunner } from 'src/services/command-runner';
29 import { StdinLive } from 'src/services/stdin';
30 import { showUpdateNotice, checkForUpdateInBackground } from 'src/services/update-check';
31 +import { mapOnlyComposioOverrideError } from 'src/services/composio-error-overrides';
32
33 /**
34 * Concrete Effect layer compositions for the Composio CLI runtime.
@@ -188,6 +189,9 @@ checkForUpdateInBackground();
189 */
190 runWithArgs.pipe(
191 Effect.scoped,
192 + Effect.mapError(error =>
193 + ValidationError.isValidationError(error) ? error : mapOnlyComposioOverrideError({ error })
194 + ),
195 // @effect/cli already prints validation errors (missing args, invalid flags, etc.)
196 // via its own printDocs before re-failing. Swallow the re-thrown error to avoid
197 // routing it through the generic error box which would dump raw JSON.
ts/packages/cli/src/commands/artifacts.cmd.ts new
+23
@@ -0,0 +1,23 @@
1 +import process from 'node:process';
2 +import { Command } from '@effect/cli';
3 +import { Effect, Option } from 'effect';
4 +import { resolveCliSessionArtifacts } from 'src/services/cli-session-artifacts';
5 +
6 +const cwdCmd = Command.make('cwd').pipe(
7 + Command.withDescription('Print the current cwd-scoped session artifact directory.'),
8 + Command.withHandler(() =>
9 + Effect.gen(function* () {
10 + const artifacts = yield* resolveCliSessionArtifacts();
11 + const directoryPath = Option.match(artifacts, {
12 + onNone: () => '/tmp/composio',
13 + onSome: value => value.directoryPath,
14 + });
15 + process.stdout.write(`${directoryPath}\n`);
16 + })
17 + )
18 +);
19 +
20 +export const artifactsCmd = Command.make('artifacts').pipe(
21 + Command.withDescription('Inspect session artifact directories.'),
22 + Command.withSubcommands([cwdCmd])
23 +);
ts/packages/cli/src/commands/connected-accounts/commands/connected-accounts.link.cmd.ts
+43 -8
@@ -14,6 +14,7 @@ import {
14 formatResolveCommandProjectError,
15 } from 'src/services/command-project';
16 import { invalidateConsumerConnectedToolkitsCache } from 'src/services/consumer-short-term-cache';
17 +import { appendCliSessionHistory } from 'src/services/cli-session-artifacts';
18
19 const toolkit = Args.text({ name: 'toolkit' }).pipe(
20 Args.withDescription('Toolkit slug to link (e.g. "github", "gmail")'),
@@ -357,8 +358,32 @@ const runConnectedAccountsLink = (params: {
358 2
359 )
360 );
361 + yield* appendCliSessionHistory({
362 + orgId: resolvedProject.projectType === 'CONSUMER' ? resolvedProject.orgId : undefined,
363 + consumerUserId:
364 + resolvedProject.projectType === 'CONSUMER' ? resolvedProject.consumerUserId : undefined,
365 + entry: {
366 + command: 'link',
367 + status: 'pending',
368 + toolkit: toolkitSlug,
369 + connectedAccountId: connAccountId,
370 + redirectUrl,
371 + },
372 + }).pipe(Effect.catchAll(() => Effect.void));
373 } else {
374 yield* waitForActiveConnection(ui, repo, connAccountId, redirectUrl, params.noBrowser);
375 + yield* appendCliSessionHistory({
376 + orgId: resolvedProject.projectType === 'CONSUMER' ? resolvedProject.orgId : undefined,
377 + consumerUserId:
378 + resolvedProject.projectType === 'CONSUMER' ? resolvedProject.consumerUserId : undefined,
379 + entry: {
380 + command: 'link',
381 + status: 'active',
382 + toolkit: toolkitSlug,
383 + connectedAccountId: connAccountId,
384 + redirectUrl,
385 + },
386 + }).pipe(Effect.catchAll(() => Effect.void));
387 }
388 });
389
@@ -378,11 +403,16 @@ export const connectedAccountsCmd$Link = Command.make(
403 ).pipe(
404 Command.withDescription(
405 [
381 - 'Link an external account via OAuth redirect.',
406 + 'Connect an external account (GitHub, Gmail, Slack, etc.) so tools can act on your behalf.',
407 + 'Opens a browser for OAuth authorization and waits for confirmation.',
408 '',
383 - 'Related:',
384 - ' composio search "<query>"',
385 - " composio execute <slug> -d '{}'",
409 + 'Examples:',
410 + ' composio link github',
411 + ' composio link gmail --no-browser Print the auth URL instead of opening it',
412 + '',
413 + 'See also:',
414 + ' composio search "<query>" Find tools to use after linking',
415 + " composio execute <slug> -d '{ ... }' Execute a tool with your linked account",
416 ].join('\n')
417 )
418 );
@@ -403,11 +433,16 @@ export const rootConnectedAccountsCmd$Link = Command.make(
433 ).pipe(
434 Command.withDescription(
435 [
406 - 'Link an external account via OAuth redirect.',
436 + 'Connect an external account (GitHub, Gmail, Slack, etc.) so tools can act on your behalf.',
437 + 'Opens a browser for OAuth authorization and waits for confirmation.',
438 + '',
439 + 'Examples:',
440 + ' composio link github',
441 + ' composio link gmail --no-browser Print the auth URL instead of opening it',
442 '',
408 - 'Related:',
409 - ' composio search "<query>"',
410 - " composio execute <slug> -d '{}'",
443 + 'See also:',
444 + ' composio search "<query>" Find tools to use after linking',
445 + " composio execute <slug> -d '{ ... }' Execute a tool with your linked account",
446 ].join('\n')
447 )
448 );
ts/packages/cli/src/commands/index.ts
+20 -1
@@ -10,12 +10,14 @@ import { whoamiCmd } from './whoami.cmd';
10 import { loginCmd } from './login.cmd';
11 import { logoutCmd } from './logout.cmd';
12 import { runCmd } from './run.cmd';
13 +import { proxyCmd } from './proxy.cmd';
14 +import { artifactsCmd } from './artifacts.cmd';
15 import { installCmd } from './install.cmd';
16 import { generateCmd } from './generate/generate.cmd';
17 import { manageCmd } from './manage/manage.cmd';
18 import { devCmd } from './dev.cmd';
19 import { showToolsExecuteInputHelp } from './tools/commands/tools.execute.cmd';
18 -import { printRootHelp } from './root-help';
20 +import { printRootHelp, matchSubcommandHelp, printSubcommandHelp } from './root-help';
21 import { rootToolsCmd$Search } from './tools/commands/tools.search.cmd';
22 import { rootToolsCmd$Execute } from './tools/commands/tools.execute.cmd';
23 import { rootToolsCmd } from './tools/tools.cmd';
@@ -24,6 +26,7 @@ import { renderCommandHintGraph } from 'src/services/command-hints';
26 import { resetRuntimeDebugFlags, setRuntimeDebugFlags } from 'src/services/runtime-debug-flags';
27 import { ComposioUserContext } from 'src/services/user-context';
28 import { TerminalUI } from 'src/services/terminal-ui';
29 +import { detectMaster } from 'src/services/master-detector';
30 import {
31 formatResolveCommandProjectError,
32 resolveCommandProject,
@@ -37,6 +40,8 @@ const $cmd = $defaultCmd.pipe(
40 loginCmd,
41 logoutCmd,
42 runCmd,
43 + proxyCmd,
44 + artifactsCmd,
45 installCmd,
46 devCmd,
47 rootToolsCmd,
@@ -171,6 +176,11 @@ const isDebugApiInfo = (argv: ReadonlyArray<string>): boolean => {
176 return args.length === 2 && args[0] === 'debug' && args[1] === 'api-info';
177 };
178
179 +const isDebugWhoIsMyMaster = (argv: ReadonlyArray<string>): boolean => {
180 + const args = argv.slice(2);
181 + return args.length === 2 && args[0] === 'debug' && args[1] === 'who-is-my-master';
182 +};
183 +
184 export const runWithConfig = Effect.gen(function* () {
185 const version = yield* getVersion;
186 const run = Command.run($cmd, {
@@ -184,6 +194,10 @@ export const runWithConfig = Effect.gen(function* () {
194 if (isRootHelp(normalizedArgv)) {
195 return printRootHelp();
196 }
197 + const subHelp = matchSubcommandHelp(normalizedArgv);
198 + if (subHelp) {
199 + return printSubcommandHelp(subHelp);
200 + }
201 if (isGenerateGraph(normalizedArgv)) {
202 return Effect.sync(() => {
203 process.stdout.write(`${JSON.stringify(renderCommandHintGraph(), null, 2)}\n`);
@@ -227,6 +241,11 @@ export const runWithConfig = Effect.gen(function* () {
241 });
242 });
243 }
244 + if (isDebugWhoIsMyMaster(normalizedArgv)) {
245 + return Effect.sync(() => {
246 + process.stdout.write(`${JSON.stringify({ master: detectMaster() }, null, 2)}\n`);
247 + });
248 + }
249 const executeHelpSlug = parseExecuteInputHelpSlug(normalizedArgv);
250 if (executeHelpSlug) {
251 return showToolsExecuteInputHelp(executeHelpSlug);
ts/packages/cli/src/commands/proxy.cmd.ts new
+350
@@ -0,0 +1,350 @@
1 +import { Args, Command, Options } from '@effect/cli';
2 +import { Effect, Option } from 'effect';
3 +import type {
4 + SessionProxyExecuteParams,
5 + SessionProxyExecuteResponse,
6 +} from '@composio/client/resources/tool-router/session';
7 +import { requireAuth } from 'src/effects/require-auth';
8 +import { resolveOptionalTextInput } from 'src/effects/resolve-optional-text-input';
9 +import { resolveToolRouterSession } from 'src/effects/create-tool-router-session';
10 +import {
11 + getFreshConsumerConnectedToolkitsFromCache,
12 + refreshConsumerConnectedToolkitsCache,
13 +} from 'src/services/consumer-short-term-cache';
14 +import { TerminalUI } from 'src/services/terminal-ui';
15 +import { ComposioClientSingleton } from 'src/services/composio-clients';
16 +import {
17 + resolveCommandProject,
18 + formatResolveCommandProjectError,
19 +} from 'src/services/command-project';
20 +import {
21 + ComposioNoActiveConnectionError,
22 + mapComposioError,
23 +} from 'src/services/composio-error-overrides';
24 +import { parseJsonIsh } from 'src/utils/parse-json-ish';
25 +
26 +const endpoint = Args.text({ name: 'url' }).pipe(
27 + Args.withDescription('Absolute or relative API endpoint to call through proxy execute.')
28 +);
29 +
30 +const toolkit = Options.text('toolkit').pipe(
31 + Options.withAlias('t'),
32 + Options.withDescription('Toolkit slug whose connected account should be used')
33 +);
34 +
35 +const method = Options.text('method').pipe(
36 + Options.withAlias('X'),
37 + Options.withDefault('GET'),
38 + Options.withDescription('HTTP method, curl-style (GET, POST, PUT, DELETE, PATCH)')
39 +);
40 +
41 +const headers = Options.text('header').pipe(
42 + Options.withAlias('H'),
43 + Options.withDescription('Header in "Name: value" format. Repeat for multiple headers.'),
44 + Options.repeated
45 +);
46 +
47 +const data = Options.text('data').pipe(
48 + Options.withAlias('d'),
49 + Options.withDescription('Request body as raw text, JSON, @file, or - for stdin'),
50 + Options.optional
51 +);
52 +
53 +const skipConnectionCheck = Options.boolean('skip-connection-check').pipe(
54 + Options.withDefault(false),
55 + Options.withDescription(
56 + 'Skip the short-lived linked-account fail-fast check if you just connected an account'
57 + )
58 +);
59 +
60 +type ProxyMethod = Extract<
61 + SessionProxyExecuteParams['method'],
62 + 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH'
63 +>;
64 +
65 +const SUPPORTED_PROXY_METHODS = [
66 + 'GET',
67 + 'POST',
68 + 'PUT',
69 + 'DELETE',
70 + 'PATCH',
71 +] as const satisfies ReadonlyArray<ProxyMethod>;
72 +
73 +export const normalizeProxyMethod = (value: string): ProxyMethod => {
74 + const normalized = value.trim().toUpperCase();
75 + if (!SUPPORTED_PROXY_METHODS.includes(normalized as ProxyMethod)) {
76 + throw new Error('Unsupported method. Use one of GET, POST, PUT, DELETE, PATCH.');
77 + }
78 + return normalized as ProxyMethod;
79 +};
80 +
81 +export const parseProxyHeader = (value: string): { name: string; value: string } => {
82 + const idx = value.indexOf(':');
83 + if (idx <= 0) {
84 + throw new Error(`Invalid header "${value}". Use "Name: value".`);
85 + }
86 +
87 + const name = value.slice(0, idx).trim();
88 + const headerValue = value.slice(idx + 1).trim();
89 + if (!name) {
90 + throw new Error(`Invalid header "${value}". Missing header name.`);
91 + }
92 + return { name, value: headerValue };
93 +};
94 +
95 +const resolveBodyInput = (input: Option.Option<string>) => resolveOptionalTextInput(input);
96 +
97 +export const parseProxyBody = (raw: string): unknown => {
98 + try {
99 + return parseJsonIsh(raw);
100 + } catch {
101 + return raw;
102 + }
103 +};
104 +
105 +const formatProxyOutput = (
106 + result: Pick<SessionProxyExecuteResponse, 'status' | 'data' | 'headers' | 'binary_data'>
107 +) => {
108 + if (result.binary_data) {
109 + return JSON.stringify(
110 + {
111 + status: result.status ?? null,
112 + headers: result.headers ?? {},
113 + binary_data: result.binary_data,
114 + },
115 + null,
116 + 2
117 + );
118 + }
119 +
120 + if (typeof result.data === 'string') {
121 + return result.data;
122 + }
123 +
124 + if (result.data === undefined || result.data === null) {
125 + return '';
126 + }
127 +
128 + return JSON.stringify(result.data, null, 2);
129 +};
130 +
131 +const formatProxyErrorOutput = (params: {
132 + readonly error: string;
133 + readonly toolkit: string;
134 + readonly endpoint: string;
135 + readonly slug?: string;
136 +}) =>
137 + JSON.stringify(
138 + {
139 + successful: false,
140 + error: params.error,
141 + toolkit: params.toolkit,
142 + endpoint: params.endpoint,
143 + slug: params.slug ?? null,
144 + },
145 + null,
146 + 2
147 + );
148 +
149 +const handleProxyExecutionError = (params: {
150 + readonly ui: TerminalUI;
151 + readonly error: unknown;
152 + readonly toolkit: string;
153 + readonly endpoint: string;
154 +}) =>
155 + Effect.gen(function* () {
156 + const mapped = mapComposioError({
157 + error: params.error,
158 + toolkit: params.toolkit,
159 + });
160 +
161 + if (mapped.normalized instanceof ComposioNoActiveConnectionError) {
162 + yield* params.ui.log.error(mapped.message);
163 + yield* params.ui.note(
164 + [
165 + `Link the toolkit first: composio link ${params.toolkit}`,
166 + 'Then retry the proxy call.',
167 + ].join('\n'),
168 + 'Tips'
169 + );
170 + const output = formatProxyErrorOutput({
171 + error: mapped.message,
172 + toolkit: params.toolkit,
173 + endpoint: params.endpoint,
174 + slug: mapped.slugValue,
175 + });
176 + yield* params.ui.output(output);
177 + return yield* Effect.fail(mapped.normalized);
178 + }
179 +
180 + yield* params.ui.log.error(mapped.message);
181 + const output = formatProxyErrorOutput({
182 + error: mapped.message,
183 + toolkit: params.toolkit,
184 + endpoint: params.endpoint,
185 + slug: mapped.slugValue,
186 + });
187 + yield* params.ui.output(output);
188 + return yield* Effect.fail(mapped.normalized);
189 + });
190 +
191 +const runProxyConnectedToolkitFailFast = (params: {
192 + readonly toolkit: string;
193 + readonly ui: TerminalUI;
194 + readonly resolvedProject: {
195 + readonly projectType: 'CONSUMER' | 'DEVELOPER';
196 + readonly orgId: string;
197 + };
198 + readonly resolvedUserId: string;
199 + readonly endpoint: string;
200 + readonly skipConnectionCheck: boolean;
201 +}) =>
202 + Effect.gen(function* () {
203 + if (params.skipConnectionCheck) return;
204 + if (params.resolvedProject.projectType !== 'CONSUMER') return;
205 +
206 + yield* refreshConsumerConnectedToolkitsCache({
207 + orgId: params.resolvedProject.orgId,
208 + consumerUserId: params.resolvedUserId,
209 + }).pipe(
210 + Effect.catchAll(() => Effect.void),
211 + Effect.forkDaemon,
212 + Effect.asVoid
213 + );
214 +
215 + const cachedToolkits = yield* getFreshConsumerConnectedToolkitsFromCache({
216 + orgId: params.resolvedProject.orgId,
217 + consumerUserId: params.resolvedUserId,
218 + });
219 +
220 + if (Option.isSome(cachedToolkits) && !cachedToolkits.value.includes(params.toolkit)) {
221 + const message = `Toolkit "${params.toolkit}" is not connected for this user (cached within the last 5 minutes). If you just connected the account, use --skip-connection-check.`;
222 + yield* params.ui.log.error(message);
223 + yield* params.ui.note(
224 + [
225 + `Link the toolkit first: composio link ${params.toolkit}`,
226 + 'Then retry the proxy call.',
227 + ].join('\n'),
228 + 'Tips'
229 + );
230 + yield* params.ui.output(
231 + JSON.stringify(
232 + {
233 + successful: false,
234 + error: message,
235 + toolkit: params.toolkit,
236 + endpoint: params.endpoint,
237 + },
238 + null,
239 + 2
240 + )
241 + );
242 + return yield* Effect.fail(new Error(message));
243 + }
244 + });
245 +
246 +export const proxyCmd = Command.make('proxy', {
247 + endpoint,
248 + toolkit,
249 + method,
250 + headers,
251 + data,
252 + skipConnectionCheck,
253 +}).pipe(
254 + Command.withDescription(
255 + [
256 + 'curl-like access to any toolkit API through Composio using your linked account.',
257 + 'Composio handles authentication — just provide the full URL and toolkit.',
258 + '',
259 + 'Examples:',
260 + ' composio proxy https://gmail.googleapis.com/gmail/v1/users/me/profile --toolkit gmail',
261 + ` composio proxy https://gmail.googleapis.com/gmail/v1/users/me/drafts --toolkit gmail \\`,
262 + ` -X POST -H 'content-type: application/json' -d '{"message":{"raw":"..."}}'`,
263 + '',
264 + 'See also:',
265 + ' composio link <toolkit> Connect an account before calling proxy',
266 + ' composio run \'const f = await proxy("gmail"); ...\' Use proxy in a script',
267 + ].join('\n')
268 + ),
269 + Command.withHandler(({ endpoint, toolkit, method, headers, data, skipConnectionCheck }) =>
270 + Effect.gen(function* () {
271 + if (!(yield* requireAuth)) return;
272 +
273 + const ui = yield* TerminalUI;
274 + const clientSingleton = yield* ComposioClientSingleton;
275 + const resolvedProject = yield* resolveCommandProject({ mode: 'consumer' }).pipe(
276 + Effect.mapError(formatResolveCommandProjectError)
277 + );
278 +
279 + if (resolvedProject.projectType !== 'CONSUMER' || !resolvedProject.consumerUserId) {
280 + return yield* Effect.fail(
281 + new Error('No consumer project user is available for proxy execution in this context.')
282 + );
283 + }
284 + const consumerUserId = resolvedProject.consumerUserId;
285 + const normalizedToolkit = toolkit.toLowerCase();
286 +
287 + yield* runProxyConnectedToolkitFailFast({
288 + toolkit: normalizedToolkit,
289 + ui,
290 + resolvedProject,
291 + resolvedUserId: consumerUserId,
292 + endpoint,
293 + skipConnectionCheck,
294 + });
295 +
296 + const normalizedMethod = normalizeProxyMethod(method);
297 + const headerParameters = headers.map(header => {
298 + const parsed = parseProxyHeader(header);
299 + return {
300 + name: parsed.name,
301 + type: 'header' as const,
302 + value: parsed.value,
303 + };
304 + });
305 + const rawBody = yield* resolveBodyInput(data);
306 + const parsedBody = rawBody === undefined ? undefined : parseProxyBody(rawBody);
307 +
308 + const result = yield* ui.withSpinner(
309 + `Proxying ${normalizedMethod} ${endpoint} via ${normalizedToolkit}...`,
310 + Effect.gen(function* () {
311 + const client = yield* clientSingleton.getFor({
312 + orgId: resolvedProject.orgId,
313 + projectId: resolvedProject.projectId,
314 + });
315 + const { sessionId } = yield* resolveToolRouterSession(client, consumerUserId, {
316 + toolkits: [normalizedToolkit],
317 + });
318 +
319 + const resultEither = yield* Effect.tryPromise(() =>
320 + client.toolRouter.session.proxyExecute(sessionId, {
321 + toolkit_slug: normalizedToolkit,
322 + endpoint,
323 + method: normalizedMethod,
324 + ...(parsedBody !== undefined ? { body: parsedBody } : {}),
325 + ...(headerParameters.length > 0 ? { parameters: headerParameters } : {}),
326 + })
327 + ).pipe(Effect.either);
328 +
329 + if (resultEither._tag === 'Left') {
330 + return yield* handleProxyExecutionError({
331 + ui,
332 + error: resultEither.left,
333 + toolkit: normalizedToolkit,
334 + endpoint,
335 + });
336 + }
337 +
338 + return resultEither.right;
339 + })
340 + );
341 +
342 + const output = formatProxyOutput(result);
343 + yield* ui.log.info(`Status: ${String(result.status ?? 'unknown')}`);
344 + if (output) {
345 + yield* ui.note(output, 'Proxy Response');
346 + yield* ui.output(output);
347 + }
348 + })
349 + )
350 +);
ts/packages/cli/src/commands/root-help.ts
+849 -131
@@ -1,218 +1,936 @@
1 import { Console, Effect } from 'effect';
2 -import { bold } from 'src/ui/colors';
2 +import { bold, dim, gray } from 'src/ui/colors';
3
4 -type BasicCommand = {
4 +type DetailedCommand = {
5 name: string;
6 description: string;
7 usage: string;
8 options?: ReadonlyArray<{ name: string; description: string }>;
9 };
10
11 -const BASIC_COMMANDS: ReadonlyArray<BasicCommand> = [
11 +type CompactCommand = {
12 + name: string;
13 + description: string;
14 +};
15 +
16 +// ── Core workflow commands ──────────────────────────────────────────────
17 +
18 +const CORE_COMMANDS: ReadonlyArray<DetailedCommand> = [
19 {
13 - name: 'version',
14 - description: 'Display the current Composio CLI version.',
15 - usage: 'version',
20 + name: 'search',
21 + description: 'Find tools by use case across all toolkits/apps.',
22 + usage: 'search <query> [--toolkits text] [--limit integer]',
23 + options: [
24 + { name: '<query>', description: 'Semantic use-case query (e.g. "send emails")' },
25 + { name: '--toolkits', description: 'Filter by toolkit slugs, comma-separated' },
26 + { name: '--limit', description: 'Number of results per page (1-1000)' },
27 + ],
28 },
29 {
18 - name: 'upgrade',
19 - description: 'Upgrade your Composio CLI to the latest available version.',
20 - usage: 'upgrade',
30 + name: 'execute',
31 + description:
32 + 'Execute a tool. Validates inputs and connections automatically; use it aggressively.',
33 + usage: 'execute <slug> [-d, --data text] [--dry-run] [--get-schema]',
34 + options: [
35 + { name: '<slug>', description: 'Tool slug (e.g. "GITHUB_CREATE_ISSUE")' },
36 + {
37 + name: '-d, --data',
38 + description:
39 + 'JSON or JS-style object arguments, e.g. -d \'{ repo: "foo" }\', @file, or - for stdin',
40 + },
41 + { name: '--dry-run', description: 'Validate and preview the tool call without executing it' },
42 + { name: '--get-schema', description: 'Fetch and print the raw tool schema' },
43 + ],
44 },
45 {
23 - name: 'whoami',
24 - description: 'Display your account information.',
25 - usage: 'whoami',
46 + name: 'link',
47 + description: 'Connect your account for a toolkit/app.',
48 + usage: 'link [<toolkit>] [--no-browser]',
49 + options: [{ name: '<toolkit>', description: 'Toolkit slug to link (e.g. "github", "gmail")' }],
50 },
51 {
28 - name: 'login',
29 - description: 'Log in to the Composio CLI session.',
30 - usage: 'login [--no-browser] [--no-wait] [--key text] [-y, --yes]',
52 + name: 'run',
53 + description:
54 + 'Run inline TS/JS code with shimmed CLI commands; injected execute(), search(), proxy(), subAgent(), and z (zod).',
55 + usage: 'run <code> [-- ...args] | run [-f, --file text] [-- ...args] [--dry-run]',
56 options: [
32 - { name: '--no-browser', description: 'Login without browser interaction' },
33 - {
34 - name: '--no-wait',
35 - description: 'Print login URL and session info, then exit (no browser, no waiting)',
36 - },
37 - {
38 - name: '--key',
39 - description: 'Complete login using session key from --no-wait',
40 - },
41 - { name: '-y, --yes', description: 'Skip org picker; use session default org' },
57 + { name: '<code>', description: 'Inline Bun ESNext code to evaluate' },
58 + { name: '-f, --file', description: 'Run a TS/JS file instead of inline code' },
59 + { name: '--dry-run', description: 'Preview execute() calls without running remote actions' },
60 ],
61 },
62 {
45 - name: 'logout',
46 - description: 'Log out from the Composio CLI session.',
47 - usage: 'logout',
63 + name: 'proxy',
64 + description: 'curl-like access to any toolkit API through Composio using your linked account.',
65 + usage: 'proxy <url> --toolkit text [-X method] [-H header]... [-d data]',
66 + options: [
67 + { name: '<url>', description: 'Full API endpoint URL' },
68 + { name: '--toolkit', description: 'Toolkit slug whose connected account should be used' },
69 + { name: '-X, --method', description: 'HTTP method (GET, POST, PUT, DELETE, PATCH)' },
70 + { name: '-H, --header', description: 'Header in "Name: value" format. Repeat for multiple.' },
71 + { name: '-d, --data', description: 'Request body as raw text, JSON, @file, or - for stdin' },
72 + ],
73 },
74 {
50 - name: 'run',
51 - description: 'Run inline ESNext TS/JS code or a file with Bun and injected Composio helpers.',
52 - usage:
53 - 'run <code> [-- ...args] | run [-f, --file text] [-- ...args] [--dry-run] [--skip-connection-check] [--skip-tool-params-check] [--no-verify]',
75 + name: 'artifacts',
76 + description: 'Inspect the cwd-scoped session artifact directory and history.',
77 + usage: 'artifacts cwd',
78 + options: [{ name: 'cwd', description: 'Print the current session artifact directory path' }],
79 + },
80 +];
81 +
82 +// ── Developer commands ─────────────────────────────────────────────────
83 +
84 +const OTHER_COMMANDS: ReadonlyArray<CompactCommand> = [
85 + { name: 'tools info <slug>', description: 'Print tool summary and cache its schema' },
86 + { name: 'tools list <toolkit>', description: 'List tools available in a toolkit' },
87 + { name: 'artifacts cwd', description: 'Print the cwd-scoped session artifact directory' },
88 +];
89 +
90 +const DEVELOPER_COMMANDS: ReadonlyArray<CompactCommand> = [
91 + {
92 + name: 'dev',
93 + description: 'Developer workflows: init, playground execution, triggers, and logs.',
94 + },
95 + {
96 + name: 'generate',
97 + description: 'Generate type stubs for toolkits, tools, and triggers (TypeScript | Python).',
98 + },
99 + {
100 + name: 'manage',
101 + description: 'Manage orgs, toolkits, connected accounts, triggers, auth configs, and projects.',
102 + },
103 +];
104 +
105 +// ── Account commands ───────────────────────────────────────────────────
106 +
107 +const ACCOUNT_COMMANDS: ReadonlyArray<CompactCommand> = [
108 + { name: 'login', description: 'Log in to Composio' },
109 + { name: 'logout', description: 'Log out from Composio' },
110 + { name: 'whoami', description: 'Show current account info' },
111 + { name: 'version', description: 'Display CLI version' },
112 + { name: 'upgrade', description: 'Upgrade CLI to the latest version' },
113 +];
114 +
115 +// ── Render helpers ─────────────────────────────────────────────────────
116 +
117 +function renderDetailedCommands(name: string, commands: ReadonlyArray<DetailedCommand>): string[] {
118 + const lines: string[] = [];
119 + for (const cmd of commands) {
120 + lines.push(` ${bold(cmd.name)}`);
121 + lines.push(` ${cmd.description}`);
122 + lines.push(` ${dim('Usage:')} ${name} ${cmd.usage}`);
123 + if (cmd.options && cmd.options.length > 0) {
124 + for (const opt of cmd.options) {
125 + lines.push(` ${dim(opt.name.padEnd(20))}${opt.description}`);
126 + }
127 + }
128 + lines.push('');
129 + }
130 + return lines;
131 +}
132 +
133 +function renderCompactCommands(commands: ReadonlyArray<CompactCommand>): string[] {
134 + const maxLen = Math.max(...commands.map(c => c.name.length));
135 + return commands.map(cmd => ` ${cmd.name.padEnd(maxLen + 2)}${cmd.description}`);
136 +}
137 +
138 +// ── Subcommand help definitions ────────────────────────────────────────
139 +
140 +type SubcommandHelp = {
141 + usage: string;
142 + description: string;
143 + args?: ReadonlyArray<{ name: string; description: string }>;
144 + options?: ReadonlyArray<{ name: string; description: string }>;
145 + flags?: ReadonlyArray<{ name: string; description: string }>;
146 + injectedHelpers?: ReadonlyArray<{ name: string; description: string }>;
147 + examples?: ReadonlyArray<string>;
148 + seeAlso?: ReadonlyArray<string>;
149 +};
150 +
151 +const SUBCOMMAND_HELP: Record<string, SubcommandHelp> = {
152 + search: {
153 + usage: 'composio search <query> [--toolkits text] [--limit integer]',
154 + description:
155 + 'Find tools by use case. Returns matching tools with slugs you can pass directly to execute.',
156 + args: [
157 + {
158 + name: '<query>',
159 + description: 'Semantic use-case query (e.g. "send an email", "create github issue")',
160 + },
161 + ],
162 + options: [
163 + { name: '--toolkits <text>', description: 'Filter by toolkit slugs, comma-separated' },
164 + { name: '--limit <integer>', description: 'Number of results per page (1-1000)' },
165 + ],
166 + examples: [
167 + '# Find tools for a use case',
168 + 'composio search "send an email"',
169 + 'composio search "create issue" --toolkits github',
170 + '',
171 + '# Cross-app workflow discovery',
172 + 'composio search "post a message to a slack channel"',
173 + 'composio search "add a row to google sheet"',
174 + '',
175 + '# Narrow results to a specific toolkit',
176 + 'composio search "list calendar events" --toolkits google_calendar --limit 5',
177 + ],
178 + seeAlso: [
179 + "composio execute <slug> -d '{ ... }' Run a tool from the results",
180 + "composio tools info <slug> Inspect a tool's full schema",
181 + 'composio link <toolkit> Connect an account if execute tells you to',
182 + ],
183 + },
184 + execute: {
185 + usage: 'composio execute <slug> [-d, --data text] [--dry-run] [--get-schema]',
186 + description:
187 + '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.',
188 + args: [{ name: '<slug>', description: 'Tool slug (e.g. "GITHUB_CREATE_ISSUE")' }],
189 options: [
190 {
56 - name: '<code>',
191 + name: '-d, --data <text>',
192 description:
58 - 'Inline Bun ESNext code with injected execute(slug, data?) and search(query, options?) helpers',
193 + 'JSON or JS-style object arguments, e.g. -d \'{ repo: "foo" }\', @file, or - for stdin',
194 },
195 {
61 - name: '-f, --file',
62 - description: 'Run a TS/JS file with the Bun runtime instead of inline code',
196 + name: '--get-schema',
197 + description: 'Fetch and print the raw tool schema without executing',
198 },
199 {
200 name: '--dry-run',
66 - description: 'Preview execute(...) calls without running remote actions',
201 + description: 'Validate and preview the tool call without executing',
202 },
203 + ],
204 + flags: [
205 + { name: '--skip-connection-check', description: 'Skip the linked-account check' },
206 {
69 - name: '--skip-connection-check',
70 - description:
71 - 'Skip the short-lived linked-account fail-fast check if you just connected an account',
207 + name: '--skip-tool-params-check',
208 + description: 'Skip input validation against cached schema',
209 },
210 + { name: '--no-verify', description: 'Skip both checks above' },
211 + ],
212 + examples: [
213 + '# Send an email',
214 + `composio execute GMAIL_SEND_EMAIL -d '{ recipient_email: "a@b.com", subject: "Hello", body: "World" }'`,
215 + '',
216 + '# Create a GitHub issue',
217 + `composio execute GITHUB_CREATE_ISSUE -d '{ owner: "acme", repo: "app", title: "Bug report", body: "Steps to reproduce..." }'`,
218 + '',
219 + '# Preview what a tool call would send without executing',
220 + `composio execute SLACK_SEND_A_MESSAGE_TO_A_SLACK_CHANNEL --dry-run -d '{ channel: "general", text: "Hello team" }'`,
221 + '',
222 + '# Check what inputs a tool needs',
223 + 'composio execute GMAIL_SEND_EMAIL --get-schema',
224 + '',
225 + '# Read arguments from a file',
226 + 'composio execute GITHUB_CREATE_ISSUE -d @issue.json',
227 + ],
228 + seeAlso: [
229 + 'composio search "<query>" Find tool slugs by use case',
230 + 'composio tools info <slug> Schema summary with jq hints',
231 + 'composio link <toolkit> Connect an account for a toolkit',
232 + 'composio artifacts cwd Print the current session artifact directory',
233 + ],
234 + },
235 + link: {
236 + usage: 'composio link [<toolkit>] [--no-browser] [--no-wait]',
237 + description:
238 + '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.',
239 + args: [{ name: '<toolkit>', description: 'Toolkit slug to link (e.g. "github", "gmail")' }],
240 + flags: [
241 + { name: '--no-browser', description: 'Print the auth URL instead of opening a browser' },
242 + {
243 + name: '--no-wait',
244 + description: 'Print link info and exit without waiting for authorization',
245 + },
246 + ],
247 + examples: ['composio link github', 'composio link gmail --no-browser'],
248 + seeAlso: [
249 + 'composio search "<query>" Find tools to use after linking',
250 + "composio execute <slug> -d '{ ... }' Execute a tool with your linked account",
251 + ],
252 + },
253 + run: {
254 + usage: 'composio run <code> [-- ...args] | run -f <file> [-- ...args]',
255 + description:
256 + 'Run inline TS/JS code or a file with injected Composio helpers that behave like their CLI counterparts.',
257 + args: [{ name: '<code>', description: 'Inline Bun ESNext code to evaluate' }],
258 + options: [
259 + { name: '-f, --file <text>', description: 'Run a TS/JS file instead of inline code' },
260 + { name: '--dry-run', description: 'Preview execute() calls without running them' },
261 + { name: '--debug', description: 'Log helper steps while the script runs' },
262 + ],
263 + flags: [
264 + { name: '--skip-connection-check', description: 'Skip the linked-account check' },
265 {
266 name: '--skip-tool-params-check',
75 - description: 'Skip the local tool parameter/schema validation check',
267 + description: 'Skip input validation against cached schema',
268 },
269 + { name: '--no-verify', description: 'Skip both checks above' },
270 + ],
271 + injectedHelpers: [
272 {
78 - name: '--no-verify',
79 - description:
80 - 'Skip both the linked-account fail-fast check and the local tool parameter check',
273 + name: 'execute(slug, data?)',
274 + description: 'Run a tool — same as `composio execute`, returns parsed JSON',
275 },
276 + { name: 'search(query, opts?)', description: 'Find tools — same as `composio search`' },
277 + { name: 'proxy(toolkit)', description: 'Returns a fetch() bound to your linked account' },
278 + {
279 + name: 'subAgent(prompt, opts?)',
280 + description: 'Spawn a sub-agent (Claude/Codex) with optional structured output',
281 + },
282 + {
283 + name: 'result.prompt()',
284 + description: 'Serialize any helper result into an LLM-friendly string',
285 + },
286 + { name: 'z', description: 'Global from zod for defining structured output schemas' },
287 + ],
288 + examples: [
289 + `composio run '`,
290 + ` // execute(slug, data?) — run a tool, returns parsed JSON`,
291 + ` const me = await execute("GITHUB_GET_THE_AUTHENTICATED_USER");`,
292 + ` console.log(me);`,
293 + `'`,
294 + '',
295 + `composio run '`,
296 + ` // search(query, opts?) — find tools by use case`,
297 + ` const tools = await search("send email");`,
298 + ` console.log(tools);`,
299 + `'`,
300 + '',
301 + '# Sequential: chain tool outputs across services',
302 + `composio run '`,
303 + ` const issue = await execute("GITHUB_CREATE_ISSUE", { owner: "acme", repo: "app", title: "Deploy v2" });`,
304 + ` await execute("SLACK_SEND_A_MESSAGE_TO_A_SLACK_CHANNEL", { channel: "eng", text: "Created: " + issue.data.html_url });`,
305 + `'`,
306 + '',
307 + '# Parallel: fetch from multiple services at once with Promise.all',
308 + `composio run '`,
309 + ` const [emails, issues, events] = await Promise.all([`,
310 + ` execute("GMAIL_FETCH_EMAILS", { max_results: 5 }),`,
311 + ` execute("GITHUB_LIST_REPOSITORY_ISSUES", { owner: "composiohq", repo: "composio", state: "open" }),`,
312 + ` execute("GOOGLECALENDAR_FIND_EVENT", { calendar_id: "primary" }),`,
313 + ` ]);`,
314 + ` console.log({ emails: emails.data, issues: issues.data, events: events.data });`,
315 + `'`,
316 + '',
317 + '# Bulk: fan out with Promise.all + .map()',
318 + `composio run '`,
319 + ` const issues = [101, 102, 103, 104];`,
320 + ` await Promise.all(issues.map(n =>`,
321 + ` execute("GITHUB_ADD_LABELS_TO_ISSUE", { owner: "acme", repo: "app", issue_number: n, labels: ["priority"] })`,
322 + ` ));`,
323 + `'`,
324 + '',
325 + '# proxy(toolkit) — returns a fetch() bound to your linked account',
326 + `composio run '`,
327 + ` const f = await proxy("gmail");`,
328 + ` console.log(await f("https://gmail.googleapis.com/gmail/v1/users/me/profile"));`,
329 + `'`,
330 + '',
331 + '# subAgent + z + result.prompt() — structured output from a sub-agent',
332 + `composio run '`,
333 + ` const [emails, issues] = await Promise.all([`,
334 + ` execute("GMAIL_FETCH_EMAILS", { max_results: 5 }),`,
335 + ` execute("GITHUB_LIST_REPOSITORY_ISSUES", { owner: "composiohq", repo: "composio", state: "open" }),`,
336 + ` ]);`,
337 + ` // result.prompt() serializes helper output for LLM consumption`,
338 + ` // z is a global from zod for defining structured output schemas`,
339 + ` const brief = await subAgent(`,
340 + ` \`Summarize these emails and issues.\\n\\n\${emails.prompt()}\\n\\n\${issues.prompt()}\`,`,
341 + ` { schema: z.object({ summary: z.string(), urgent: z.array(z.string()) }) }`,
342 + ` );`,
343 + ` console.log(brief.structuredOutput);`,
344 + `'`,
345 + '',
346 + '# Run from a file',
347 + 'composio run --file ./workflow.ts -- --repo acme/app',
348 + ],
349 + seeAlso: [
350 + 'composio search "<query>" Discover tool slugs before scripting',
351 + 'composio link <toolkit> Connect accounts before scripting',
352 + 'composio execute <slug> --get-schema Inspect tool inputs before scripting',
353 + 'composio artifacts cwd Print the current session artifact directory',
354 ],
355 },
84 - {
85 - name: 'search',
86 - description: 'Semantic search for tools by use case across all toolkits/apps.',
87 - usage: 'search <query> [--toolkits text] [--limit integer]',
356 + proxy: {
357 + usage: 'composio proxy <url> --toolkit <text> [-X method] [-H header]... [-d data]',
358 + description:
359 + 'curl-like access to any toolkit API through Composio using your linked account. Composio handles authentication — just provide the full URL and toolkit.',
360 + args: [{ name: '<url>', description: 'Full API endpoint URL' }],
361 options: [
89 - { name: '<query>', description: 'Semantic use-case query (e.g. "send emails")' },
90 - { name: '--toolkits', description: 'Filter by toolkit slugs, comma-separated' },
91 - { name: '--limit', description: 'Number of results per page (1-1000)' },
362 + {
363 + name: '-t, --toolkit <text>',
364 + description: 'Toolkit slug whose connected account should be used',
365 + },
366 + { name: '-X, --method <text>', description: 'HTTP method (GET, POST, PUT, DELETE, PATCH)' },
367 + {
368 + name: '-H, --header <text>',
369 + description: 'Header in "Name: value" format. Repeat for multiple.',
370 + },
371 + {
372 + name: '-d, --data <text>',
373 + description: 'Request body as raw text, JSON, @file, or - for stdin',
374 + },
375 + ],
376 + flags: [{ name: '--skip-connection-check', description: 'Skip the linked-account check' }],
377 + examples: [
378 + 'composio proxy https://gmail.googleapis.com/gmail/v1/users/me/profile --toolkit gmail',
379 + `composio proxy https://gmail.googleapis.com/gmail/v1/users/me/drafts --toolkit gmail \\`,
380 + ` -X POST -H 'content-type: application/json' -d '{"message":{"raw":"..."}}'`,
381 + ],
382 + seeAlso: [
383 + 'composio link <toolkit> Connect an account first',
384 + `composio run 'const f = await proxy("gmail"); ...' Use proxy in a script`,
385 ],
386 },
94 - {
95 - name: 'tools',
96 - description: 'List tools for one toolkit, or inspect a cached schema-backed summary.',
97 - usage: 'tools list <toolkit> [--query text] | tools info <slug>',
387 +
388 + // ── Account commands ──────────────────────────────────────────────────
389 +
390 + login: {
391 + usage: 'composio login [--no-browser] [--no-wait] [--key text] [-y, --yes]',
392 + description: 'Log in to the Composio CLI session.',
393 options: [
394 {
100 - name: 'list <toolkit>',
101 - description: 'Non-semantic per-toolkit listing; use this when you already know the toolkit',
395 + name: '--key <text>',
396 + description: 'Complete login using session key from composio login --no-wait',
397 },
398 + ],
399 + flags: [
400 + { name: '--no-browser', description: 'Login without browser interaction' },
401 + { name: '--no-wait', description: 'Print login URL and session info, then exit' },
402 + { name: '-y, --yes', description: 'Skip org picker; use session default org' },
403 + ],
404 + },
405 + logout: {
406 + usage: 'composio logout',
407 + description: 'Log out from the Composio CLI session.',
408 + },
409 + whoami: {
410 + usage: 'composio whoami',
411 + description: 'Display your account information.',
412 + },
413 + version: {
414 + usage: 'composio version',
415 + description: 'Display the current Composio CLI version.',
416 + },
417 + upgrade: {
418 + usage: 'composio upgrade',
419 + description: 'Upgrade your Composio CLI to the latest available version.',
420 + },
421 +
422 + // ── Tools commands ────────────────────────────────────────────────────
423 +
424 + 'tools list': {
425 + usage: 'composio tools list <toolkit> [--query text] [--tags text] [--limit integer]',
426 + description: 'List available tools for a toolkit.',
427 + args: [{ name: '<toolkit>', description: 'Toolkit slug to list tools for (e.g. "gmail")' }],
428 + options: [
429 + { name: '--query <text>', description: 'Text search by name, slug, or description' },
430 + { name: '--tags <text>', description: 'Filter by tags (e.g. "important")' },
431 + { name: '--limit <integer>', description: 'Number of results per page (1-1000)' },
432 + ],
433 + },
434 + 'tools info': {
435 + usage: 'composio tools info [<slug>]',
436 + description:
437 + 'View a brief summary of a tool and cache the raw schema used by `composio execute --get-schema`.',
438 + args: [{ name: '<slug>', description: 'Tool slug (e.g. "GMAIL_SEND_EMAIL")' }],
439 + },
440 +
441 + // ── Generate commands ─────────────────────────────────────────────────
442 +
443 + generate: {
444 + usage: 'composio generate [--output-dir dir] [--type-tools] --toolkits text...',
445 + description:
446 + 'Generate type stubs for toolkits, tools, and triggers, auto-detecting project language (TypeScript | Python).',
447 + options: [
448 + { name: '-o, --output-dir <dir>', description: 'Output directory for type stubs' },
449 {
104 - name: 'info <slug>',
105 - description:
106 - 'Print a brief summary and cache the same raw schema used by execute --get-schema',
450 + name: '--toolkits <text>...',
451 + description: 'Toolkits to generate for (repeat for multiple)',
452 + },
453 + ],
454 + flags: [
455 + {
456 + name: '--type-tools',
457 + description: 'Generate typed input/output schemas for each tool (slower)',
458 },
459 ],
460 },
110 - {
111 - name: 'execute',
112 - description: 'Execute a tool, preview it with --dry-run, or fetch its input schema.',
461 + 'generate ts': {
462 usage:
114 - 'execute <slug> [-d, --data text] [--dry-run] [--get-schema] [--skip-connection-check] [--skip-tool-params-check] [--no-verify]',
463 + 'composio generate ts [--output-dir dir] [--compact] [--transpiled] [--type-tools] --toolkits text...',
464 + description: 'Generate TypeScript type stubs for toolkits, tools, and triggers.',
465 options: [
116 - { name: '<slug>', description: 'Tool slug (e.g. "GITHUB_CREATE_ISSUE")' },
466 {
118 - name: '-d, --data',
119 - description:
120 - 'JSON or JS-style object arguments, e.g. -d \'{ repo: "foo" }\', @file, or - for stdin',
467 + name: '-o, --output-dir <dir>',
468 + description: 'Output directory for generated TypeScript stubs',
469 },
122 - { name: '--dry-run', description: 'Validate and preview the tool call without executing it' },
470 {
124 - name: '--get-schema',
125 - description:
126 - 'Fetch and print the raw cached schema; tools info shows the same schema with a brief summary',
471 + name: '--toolkits <text>...',
472 + description: 'Toolkits to generate for (repeat for multiple)',
473 },
474 + ],
475 + flags: [
476 + { name: '--compact', description: 'Emit a single TypeScript file' },
477 {
129 - name: '--skip-connection-check',
130 - description:
131 - 'Skip the short-lived linked-account fail-fast check if you just connected an account',
478 + name: '--transpiled',
479 + description: 'Emit transpiled JavaScript alongside TypeScript files',
480 },
481 {
134 - name: '--skip-tool-params-check',
135 - description: 'Skip the local tool parameter/schema validation check',
136 - },
137 - {
138 - name: '--no-verify',
139 - description:
140 - 'Skip both the linked-account fail-fast check and the local tool parameter check',
482 + name: '--type-tools',
483 + description: 'Generate typed input/output schemas for each tool (slower)',
484 },
485 ],
486 },
144 - {
145 - name: 'link',
146 - description: 'Connect a user account for a toolkit/app.',
147 - usage: 'link [<toolkit>] [--no-browser]',
487 + 'generate py': {
488 + usage: 'composio generate py [--output-dir dir] --toolkits text...',
489 + description: 'Generate Python type stubs for toolkits, tools, and triggers.',
490 options: [
149 - { name: '<toolkit>', description: 'Toolkit slug to link (e.g. "github", "gmail")' },
150 - { name: '--no-browser', description: 'Skip auto-opening the browser' },
491 + {
492 + name: '-o, --output-dir <dir>',
493 + description: 'Output directory for generated Python stubs',
494 + },
495 + {
496 + name: '--toolkits <text>...',
497 + description: 'Toolkits to generate for (repeat for multiple)',
498 + },
499 ],
500 },
153 -];
501
155 -const ADVANCED_COMMANDS: ReadonlyArray<{ name: string; description: string }> = [
156 - {
157 - name: 'dev',
158 - description:
159 - 'Developer workflows: init a local project, execute tools with playground users, listen for triggers, and inspect logs.',
502 + // ── Dev commands ──────────────────────────────────────────────────────
503 +
504 + 'dev init': {
505 + usage: 'composio dev init [--no-browser] [-y, --yes]',
506 + description: 'Initialize this directory with a developer project.',
507 + flags: [
508 + { name: '--no-browser', description: 'Login without browser interaction' },
509 + { name: '-y, --yes', description: 'Auto-select the default org project' },
510 + ],
511 },
161 - {
162 - name: 'generate',
512 + 'dev execute': {
513 + usage:
514 + 'composio dev execute <slug> [-d, --data text] [--user-id text] [--project-name text] [--dry-run] [--get-schema]',
515 description:
164 - 'Generate type stubs for toolkits, tools, and triggers, auto-detecting project language (TypeScript | Python)',
516 + 'Execute a tool with your playground test user against your developer project auth configs.',
517 + args: [{ name: '<slug>', description: 'Tool slug (e.g. "GITHUB_CREATE_ISSUE")' }],
518 + options: [
519 + { name: '-d, --data <text>', description: 'JSON arguments, @file, or - for stdin' },
520 + { name: '--user-id <text>', description: 'Developer-project user ID override' },
521 + { name: '--project-name <text>', description: 'Developer project name override' },
522 + {
523 + name: '--get-schema',
524 + description: 'Fetch and print the raw tool schema without executing',
525 + },
526 + { name: '--dry-run', description: 'Validate and preview without executing' },
527 + ],
528 + flags: [
529 + { name: '--skip-connection-check', description: 'Skip the linked-account check' },
530 + {
531 + name: '--skip-tool-params-check',
532 + description: 'Skip input validation against cached schema',
533 + },
534 + { name: '--no-verify', description: 'Skip both checks above' },
535 + ],
536 },
166 - {
167 - name: 'manage',
537 + 'dev listen': {
538 + usage:
539 + 'composio dev listen [--toolkits text] [--trigger-slug text] [--json] [--table] [--max-events int] [--forward url] [--out file]',
540 description:
169 - 'Manage your developer orgs, toolkits, connected accounts, triggers, auth configs, and projects.',
541 + 'Listen to realtime trigger events for your developer project and optionally forward them.',
542 + options: [
543 + { name: '--toolkits <text>', description: 'Filter by toolkit slugs, comma-separated' },
544 + { name: '--trigger-id <text>', description: 'Filter by trigger id' },
545 + { name: '--connected-account-id <text>', description: 'Filter by connected account id' },
546 + { name: '--trigger-slug <text>', description: 'Filter by trigger slug, comma-separated' },
547 + { name: '--user-id <text>', description: 'Filter by user id' },
548 + { name: '--max-events <int>', description: 'Stop after receiving N matching events' },
549 + { name: '--forward <url>', description: 'Forward each event to the given URL' },
550 + { name: '--out <file>', description: 'Append each event to this file' },
551 + ],
552 + flags: [
553 + { name: '--json', description: 'Show raw event payload as JSON' },
554 + { name: '--table', description: 'Show compact table rows' },
555 + ],
556 },
171 -];
557
173 -/**
174 - * Prints the root-level help output in gh-style format.
175 - * Shows only top-level commands, not nested subcommands.
176 - * Basic commands include full usage and options.
177 - */
178 -export function printRootHelp(): Effect.Effect<void> {
179 - const name = 'composio';
180 - const allCommands = [
181 - ...BASIC_COMMANDS.map(c => ({ name: c.name, description: c.description })),
182 - ...ADVANCED_COMMANDS,
558 + // ── Manage commands ───────────────────────────────────────────────────
559 +
560 + 'manage toolkits list': {
561 + usage:
562 + 'composio manage toolkits list [--query text] [--limit integer] [--connected] [--user-id text]',
563 + description: 'List available toolkits with connection status.',
564 + options: [
565 + { name: '--query <text>', description: 'Text search by name, slug, or description' },
566 + { name: '--limit <integer>', description: 'Number of results per page (1-1000)' },
567 + { name: '--user-id <text>', description: 'User ID override' },
568 + ],
569 + flags: [{ name: '--connected', description: 'Show only connected toolkits' }],
570 + },
571 + 'manage toolkits info': {
572 + usage: 'composio manage toolkits info [--user-id text] [-a, --all] [<slug>]',
573 + description: 'View details of a specific toolkit.',
574 + args: [{ name: '<slug>', description: 'Toolkit slug (e.g. "github")' }],
575 + flags: [{ name: '-a, --all', description: 'Show all details' }],
576 + },
577 + 'manage toolkits search': {
578 + usage: 'composio manage toolkits search <query> [--limit integer]',
579 + description: 'Search toolkits by use case.',
580 + args: [{ name: '<query>', description: 'Search query' }],
581 + options: [{ name: '--limit <integer>', description: 'Number of results' }],
582 + },
583 + 'manage toolkits version': {
584 + usage: 'composio manage toolkits version <slug>',
585 + description: 'Show latest and recent versions for a toolkit.',
586 + args: [{ name: '<slug>', description: 'Toolkit slug' }],
587 + },
588 + 'manage auth-configs list': {
589 + usage: 'composio manage auth-configs list [--toolkits text] [--query text] [--limit integer]',
590 + description: 'List auth configs.',
591 + options: [
592 + { name: '--toolkits <text>', description: 'Filter by toolkit slugs' },
593 + { name: '--query <text>', description: 'Search text' },
594 + { name: '--limit <integer>', description: 'Number of results' },
595 + ],
596 + },
597 + 'manage auth-configs info': {
598 + usage: 'composio manage auth-configs info [<id>]',
599 + description: 'View details of a specific auth config.',
600 + args: [{ name: '<id>', description: 'Auth config ID' }],
601 + },
602 + 'manage auth-configs create': {
603 + usage:
604 + 'composio manage auth-configs create --toolkit text [--auth-scheme text] [--scopes text] [--custom-credentials text] [<name>]',
605 + description: 'Create a new auth config.',
606 + args: [{ name: '<name>', description: 'Auth config name' }],
607 + options: [
608 + { name: '--toolkit <text>', description: 'Toolkit slug' },
609 + { name: '--auth-scheme <text>', description: 'Authentication scheme' },
610 + { name: '--scopes <text>', description: 'Comma-separated scopes' },
611 + { name: '--custom-credentials <text>', description: 'Custom credentials JSON' },
612 + ],
613 + },
614 + 'manage auth-configs delete': {
615 + usage: 'composio manage auth-configs delete [-y, --yes] [<id>]',
616 + description: 'Delete an auth config.',
617 + args: [{ name: '<id>', description: 'Auth config ID' }],
618 + flags: [{ name: '-y, --yes', description: 'Skip confirmation prompt' }],
619 + },
620 + 'manage connected-accounts list': {
621 + usage:
622 + 'composio manage connected-accounts list [--toolkits text] [--user-id text] [--status text] [--limit integer]',
623 + description: 'List connected accounts.',
624 + options: [
625 + { name: '--toolkits <text>', description: 'Filter by toolkit slugs' },
626 + { name: '--user-id <text>', description: 'Filter by user id' },
627 + { name: '--status <text>', description: 'Filter by status (ACTIVE, FAILED, EXPIRED, etc.)' },
628 + { name: '--limit <integer>', description: 'Number of results' },
629 + ],
630 + },
631 + 'manage connected-accounts info': {
632 + usage: 'composio manage connected-accounts info [<id>]',
633 + description: 'View details of a specific connected account.',
634 + args: [{ name: '<id>', description: 'Connected account ID' }],
635 + },
636 + 'manage connected-accounts whoami': {
637 + usage: 'composio manage connected-accounts whoami [<id>]',
638 + description: 'Show the external account profile for a connected account.',
639 + args: [{ name: '<id>', description: 'Connected account ID' }],
640 + },
641 + 'manage connected-accounts delete': {
642 + usage: 'composio manage connected-accounts delete [-y, --yes] [<id>]',
643 + description: 'Delete a connected account.',
644 + args: [{ name: '<id>', description: 'Connected account ID' }],
645 + flags: [{ name: '-y, --yes', description: 'Skip confirmation prompt' }],
646 + },
647 + 'manage connected-accounts link': {
648 + usage:
649 + 'composio manage connected-accounts link [--auth-config text] [--user-id text] [--project-name text] [--no-browser] [--no-wait] [<toolkit>]',
650 + description: 'Connect an external account so tools can act on your behalf.',
651 + args: [{ name: '<toolkit>', description: 'Toolkit slug to link (e.g. "github", "gmail")' }],
652 + options: [
653 + { name: '--auth-config <text>', description: 'Auth config ID to use' },
654 + { name: '--user-id <text>', description: 'User ID override' },
655 + { name: '--project-name <text>', description: 'Project name override' },
656 + ],
657 + flags: [
658 + { name: '--no-browser', description: 'Print the auth URL instead of opening a browser' },
659 + { name: '--no-wait', description: 'Print link info and exit without waiting' },
660 + ],
661 + },
662 + 'manage triggers list': {
663 + usage: 'composio manage triggers list [--toolkits text] [--limit integer]',
664 + description: 'List available trigger types.',
665 + options: [
666 + { name: '--toolkits <text>', description: 'Filter by toolkit slugs' },
667 + { name: '--limit <integer>', description: 'Number of results' },
668 + ],
669 + },
670 + 'manage triggers info': {
671 + usage: 'composio manage triggers info [<slug>]',
672 + description: 'View details of a specific trigger type.',
673 + args: [{ name: '<slug>', description: 'Trigger slug' }],
674 + },
675 + 'manage triggers listen': {
676 + usage:
677 + 'composio manage triggers listen [--toolkits text] [--trigger-slug text] [--json] [--table] [--max-events int] [--forward url] [--out file]',
678 + description: 'Listen to realtime trigger events and optionally forward them.',
679 + options: [
680 + { name: '--toolkits <text>', description: 'Filter by toolkit slugs, comma-separated' },
681 + { name: '--trigger-id <text>', description: 'Filter by trigger id' },
682 + { name: '--connected-account-id <text>', description: 'Filter by connected account id' },
683 + { name: '--trigger-slug <text>', description: 'Filter by trigger slug, comma-separated' },
684 + { name: '--user-id <text>', description: 'Filter by user id' },
685 + { name: '--max-events <int>', description: 'Stop after receiving N events' },
686 + { name: '--forward <url>', description: 'Forward each event to the given URL' },
687 + { name: '--out <file>', description: 'Append each event to this file' },
688 + ],
689 + flags: [
690 + { name: '--json', description: 'Show raw event payload as JSON' },
691 + { name: '--table', description: 'Show compact table rows' },
692 + ],
693 + },
694 + 'manage triggers status': {
695 + usage:
696 + 'composio manage triggers status [--user-ids text] [--toolkits text] [--trigger-ids text] [--show-disabled] [--limit integer]',
697 + description: 'Show active triggers with optional filters.',
698 + options: [
699 + { name: '--user-ids <text>', description: 'Filter by user IDs' },
700 + { name: '--connected-account-ids <text>', description: 'Filter by connected account IDs' },
701 + { name: '--toolkits <text>', description: 'Filter by toolkit slugs' },
702 + { name: '--trigger-ids <text>', description: 'Filter by trigger IDs' },
703 + { name: '--trigger-names <text>', description: 'Filter by trigger names' },
704 + { name: '--limit <integer>', description: 'Number of results' },
705 + ],
706 + flags: [{ name: '--show-disabled', description: 'Include disabled triggers' }],
707 + },
708 + 'manage triggers create': {
709 + usage:
710 + 'composio manage triggers create [--connected-account-id text] [--trigger-config text] [<trigger-name>]',
711 + description: 'Create a new trigger instance.',
712 + args: [{ name: '<trigger-name>', description: 'Trigger type slug' }],
713 + options: [
714 + { name: '--connected-account-id <text>', description: 'Connected account to use' },
715 + { name: '--trigger-config <text>', description: 'Trigger configuration JSON' },
716 + ],
717 + },
718 + 'manage triggers enable': {
719 + usage: 'composio manage triggers enable [<id>]',
720 + description: 'Enable a trigger instance.',
721 + args: [{ name: '<id>', description: 'Trigger instance ID' }],
722 + },
723 + 'manage triggers disable': {
724 + usage: 'composio manage triggers disable [<id>]',
725 + description: 'Disable a trigger instance.',
726 + args: [{ name: '<id>', description: 'Trigger instance ID' }],
727 + },
728 + 'manage triggers delete': {
729 + usage: 'composio manage triggers delete [-y, --yes] [<id>]',
730 + description: 'Delete a trigger instance.',
731 + args: [{ name: '<id>', description: 'Trigger instance ID' }],
732 + flags: [{ name: '-y, --yes', description: 'Skip confirmation prompt' }],
733 + },
734 + 'manage orgs list': {
735 + usage: 'composio manage orgs list [--limit integer]',
736 + description: 'List organizations and show current global selection.',
737 + options: [{ name: '--limit <integer>', description: 'Number of results' }],
738 + },
739 + 'manage orgs switch': {
740 + usage: 'composio manage orgs switch [--org-id text] [--limit integer]',
741 + description: 'Switch default organization context.',
742 + options: [
743 + { name: '--org-id <text>', description: 'Organization ID to switch to' },
744 + { name: '--limit <integer>', description: 'Number of orgs to show in picker' },
745 + ],
746 + },
747 + 'manage projects list': {
748 + usage: 'composio manage projects list [--org-id text] [--limit integer]',
749 + description: 'List developer projects for the current organization.',
750 + options: [
751 + { name: '--org-id <text>', description: 'Organization ID override' },
752 + { name: '--limit <integer>', description: 'Number of results' },
753 + ],
754 + },
755 +
756 + // ── Dev logs commands ─────────────────────────────────────────────────
757 +
758 + 'dev logs tools': {
759 + usage:
760 + 'composio dev logs tools [--toolkit text] [--tool text] [--status text] [--limit integer] [<log_id>]',
761 + description: 'List tool execution logs, or pass a log_id to fetch a specific log.',
762 + args: [{ name: '<log_id>', description: 'Specific log ID to fetch' }],
763 + options: [
764 + { name: '--toolkit <text>', description: 'Filter by toolkit slug' },
765 + { name: '--tool <text>', description: 'Filter by tool slug' },
766 + { name: '--status <text>', description: 'Filter by status' },
767 + { name: '--user-id <text>', description: 'Filter by user id' },
768 + { name: '--limit <integer>', description: 'Number of results' },
769 + { name: '--from <integer>', description: 'Start timestamp (epoch ms)' },
770 + { name: '--to <integer>', description: 'End timestamp (epoch ms)' },
771 + ],
772 + flags: [{ name: '--case-sensitive', description: 'Case-sensitive filtering' }],
773 + },
774 + 'dev logs triggers': {
775 + usage:
776 + 'composio dev logs triggers [--trigger text] [--trigger-id text] [--limit integer] [--time 5m|30m|6h|1d|1w] [<log_id>]',
777 + description: 'List trigger logs.',
778 + args: [{ name: '<log_id>', description: 'Specific log ID to fetch' }],
779 + options: [
780 + { name: '--trigger <text>', description: 'Filter by trigger slug' },
781 + { name: '--trigger-id <text>', description: 'Filter by trigger id' },
782 + { name: '--user-id <text>', description: 'Filter by user id' },
783 + { name: '--connected-account-id <text>', description: 'Filter by connected account id' },
784 + { name: '--limit <integer>', description: 'Number of results' },
785 + { name: '--time <period>', description: 'Time window (5m, 30m, 6h, 1d, 1w, 1month, 1y)' },
786 + { name: '--search <text>', description: 'Search in log content' },
787 + ],
788 + flags: [{ name: '--include-payload', description: 'Include full event payload' }],
789 + },
790 +};
791 +
792 +function renderSubcommandHelp(cmd: SubcommandHelp): string {
793 + const lines: string[] = [
794 + '',
795 + bold('USAGE'),
796 + ` ${cmd.usage}`,
797 + '',
798 + bold('DESCRIPTION'),
799 + ` ${cmd.description}`,
800 + '',
801 ];
184 - const maxNameLen = Math.max(...allCommands.map(c => c.name.length), 10);
802
186 - const basicLines: string[] = [];
187 - for (const cmd of BASIC_COMMANDS) {
188 - basicLines.push(` ${cmd.name}`);
189 - basicLines.push(` ${cmd.description}`);
190 - basicLines.push(` Usage: ${name} ${cmd.usage}`);
191 - if (cmd.options && cmd.options.length > 0) {
192 - basicLines.push(' Options:');
193 - for (const opt of cmd.options) {
194 - basicLines.push(` ${opt.name.padEnd(20)} ${opt.description}`);
195 - }
803 + if (cmd.args && cmd.args.length > 0) {
804 + lines.push(bold('ARGUMENTS'));
805 + for (const arg of cmd.args) {
806 + lines.push(` ${dim(arg.name.padEnd(24))}${arg.description}`);
807 + }
808 + lines.push('');
809 + }
810 +
811 + if (cmd.options && cmd.options.length > 0) {
812 + lines.push(bold('OPTIONS'));
813 + for (const opt of cmd.options) {
814 + lines.push(` ${dim(opt.name.padEnd(24))}${opt.description}`);
815 }
197 - basicLines.push('');
816 + lines.push('');
817 }
818
819 + if (cmd.flags && cmd.flags.length > 0) {
820 + lines.push(bold('FLAGS'));
821 + for (const flag of cmd.flags) {
822 + lines.push(` ${dim(flag.name.padEnd(28))}${flag.description}`);
823 + }
824 + lines.push('');
825 + }
826 +
827 + if (cmd.injectedHelpers && cmd.injectedHelpers.length > 0) {
828 + lines.push(bold('INJECTED HELPERS'));
829 + const maxLen = Math.max(...cmd.injectedHelpers.map(h => h.name.length));
830 + for (const helper of cmd.injectedHelpers) {
831 + lines.push(` ${dim(helper.name.padEnd(maxLen + 2))}${helper.description}`);
832 + }
833 + lines.push('');
834 + }
835 +
836 + if (cmd.examples && cmd.examples.length > 0) {
837 + lines.push(bold('EXAMPLES'));
838 + for (const ex of cmd.examples) {
839 + lines.push(` ${ex}`);
840 + }
841 + lines.push('');
842 + }
843 +
844 + if (cmd.seeAlso && cmd.seeAlso.length > 0) {
845 + lines.push(bold('SEE ALSO'));
846 + for (const sa of cmd.seeAlso) {
847 + lines.push(` ${sa}`);
848 + }
849 + lines.push('');
850 + }
851 +
852 + return lines.join('\n');
853 +}
854 +
855 +/**
856 + * Check if argv is `composio <subcommand> --help` for a command we have custom help for.
857 + * Returns the command name if matched, undefined otherwise.
858 + */
859 +export function matchSubcommandHelp(argv: ReadonlyArray<string>): string | undefined {
860 + const args = argv.slice(2);
861 + if (args.length < 2) return undefined;
862 + const last = args[args.length - 1];
863 + if (last !== '--help' && last !== '-h') return undefined;
864 +
865 + const cmdParts = args.slice(0, -1);
866 + // Try longest match first: "manage toolkits list" → "manage toolkits" → "manage"
867 + for (let len = cmdParts.length; len > 0; len--) {
868 + const key = cmdParts.slice(0, len).join(' ');
869 + if (key in SUBCOMMAND_HELP) return key;
870 + }
871 + return undefined;
872 +}
873 +
874 +export function printSubcommandHelp(cmd: string): Effect.Effect<void> {
875 + const help = SUBCOMMAND_HELP[cmd];
876 + if (!help) return Console.log(`Unknown command: ${cmd}`);
877 + return Console.log(renderSubcommandHelp(help));
878 +}
879 +
880 +// ── Main help output ───────────────────────────────────────────────────
881 +
882 +/**
883 + * Prints the root-level help output.
884 + * Core workflow commands are shown first with full usage/options.
885 + * Housekeeping and developer commands are shown compactly at the bottom.
886 + */
887 +export function printRootHelp(): Effect.Effect<void> {
888 + const name = 'composio';
889 +
890 const lines: string[] = [
891 '',
202 - 'Connect AI agents to external tools. `search`, `link`, `execute`, and `run` let you take actions across 1000+ apps directly; if you can describe it, it is probably supported.',
203 - "Try `execute` sooner than you'd think. It parses inputs, validates them against cached schemas when available, and will usually tell you whether you need to fix arguments, inspect schema, or `link` an account.",
204 - 'Use `dev` when you are building with Composio and want scaffolding, playground execution, triggers, and logs.',
892 + `Connect AI agents to external tools. ${bold('search')}, ${bold('execute')}, ${bold('link')}, ${bold('proxy')}, and ${bold('run')} let you`,
893 + 'take actions across 1000+ apps directly; if you can describe it, it is probably supported.',
894 + `Try ${bold('execute')} sooner than you'd think — it validates inputs, checks connections, and tells`,
895 + 'you what to fix.',
896 + '',
897 + `Use ${bold('dev')} when you are building an agent with Composio's SDK and want scaffolding,`,
898 + 'playground execution, triggers, and logs.',
899 '',
900 bold('USAGE'),
901 ` ${name} <command> [options]`,
902 '',
209 - bold('BASIC COMMANDS'),
210 - ...basicLines,
211 - bold('ADVANCED COMMANDS'),
212 - ...ADVANCED_COMMANDS.map(cmd => ` ${cmd.name.padEnd(maxNameLen)} ${cmd.description}`),
903 + bold('CORE COMMANDS'),
904 + ...renderDetailedCommands(name, CORE_COMMANDS),
905 + gray(' Typical flow: search → execute (link and tools when needed)'),
906 + '',
907 + bold('TOOLS'),
908 + ...renderCompactCommands(OTHER_COMMANDS),
909 + '',
910 + bold('EXAMPLES'),
911 + ` ${dim('# Find a tool')}`,
912 + ` ${name} search "create github issue"`,
913 + '',
914 + ` ${dim('# Connect your GitHub account')}`,
915 + ` ${name} link github`,
916 + '',
917 + ` ${dim('# Execute a tool')}`,
918 + ` ${name} execute GITHUB_CREATE_ISSUE -d '{ repo: "owner/repo", title: "Bug" }'`,
919 + '',
920 + ` ${dim('# Call an API directly through proxy')}`,
921 + ` ${name} proxy https://gmail.googleapis.com/gmail/v1/users/me/profile --toolkit gmail`,
922 + '',
923 + ` ${dim('# Run a script with injected helpers')}`,
924 + ` ${name} run 'const me = await execute("GITHUB_GET_THE_AUTHENTICATED_USER"); console.log(me)'`,
925 + '',
926 + bold('DEVELOPER COMMANDS'),
927 + ...renderCompactCommands(DEVELOPER_COMMANDS),
928 + '',
929 + bold('ACCOUNT'),
930 + ...renderCompactCommands(ACCOUNT_COMMANDS),
931 '',
932 bold('FLAGS'),
215 - ` -h, --help Show help for command`,
933 + ' -h, --help Show help for command',
934 ` --version Show ${name} version`,
935 '',
936 bold('LEARN MORE'),
ts/packages/cli/src/commands/run.cmd.ts
+733 -136
@@ -9,6 +9,11 @@ import { resolveCommandProject } from 'src/services/command-project';
9 import { warmToolInputDefinitions } from 'src/services/tool-input-validation';
10 import { ComposioUserContext } from 'src/services/user-context';
11 import { isPerfDebugEnabled, isToolDebugEnabled } from 'src/services/runtime-debug-flags';
12 +import { detectMaster, type MasterKind } from 'src/services/master-detector';
13 +import {
14 + appendCliSessionHistory,
15 + resolveCliSessionArtifacts,
16 +} from 'src/services/cli-session-artifacts';
17
18 const file = Options.text('file').pipe(
19 Options.withAlias('f'),
@@ -16,14 +21,26 @@ const file = Options.text('file').pipe(
21 Options.optional
22 );
23
19 -const dryRun = Options.boolean('dry-run').pipe(Options.withDefault(false));
24 +const dryRun = Options.boolean('dry-run').pipe(
25 + Options.withDescription('Preview execute() calls without running them'),
26 + Options.withDefault(false)
27 +);
28 +const debug = Options.boolean('debug').pipe(
29 + Options.withDescription('Log helper steps while the script runs'),
30 + Options.withDefault(false)
31 +);
32 const skipConnectionCheck = Options.boolean('skip-connection-check').pipe(
33 + Options.withDescription('Skip the linked-account check'),
34 Options.withDefault(false)
35 );
36 const skipToolParamsCheck = Options.boolean('skip-tool-params-check').pipe(
37 + Options.withDescription('Skip input validation against cached schema'),
38 + Options.withDefault(false)
39 +);
40 +const noVerify = Options.boolean('no-verify').pipe(
41 + Options.withDescription('Skip both connection and input validation checks'),
42 Options.withDefault(false)
43 );
26 -const noVerify = Options.boolean('no-verify').pipe(Options.withDefault(false));
44
45 const args = Args.repeated(Args.text({ name: 'arg' })).pipe(
46 Args.withDescription('Inline code followed by arguments, or just arguments when using --file')
@@ -64,6 +81,59 @@ export const extractInlineExecuteToolSlugs = (source: string): ReadonlyArray<str
81 return [...slugs];
82 };
83
84 +export const wrapInlineCodeForRun = (source: string): string => {
85 + const parsed = ts.createSourceFile(
86 + 'composio-run-inline.ts',
87 + source,
88 + ts.ScriptTarget.Latest,
89 + true,
90 + ts.ScriptKind.TSX
91 + );
92 + const statements = [...parsed.statements];
93 + if (statements.length === 0) {
94 + return source;
95 + }
96 +
97 + const lastStatement = statements.at(-1);
98 + if (!lastStatement || !ts.isExpressionStatement(lastStatement)) {
99 + return source;
100 + }
101 +
102 + const prefix = source.slice(0, lastStatement.getFullStart());
103 + const suffix = source.slice(lastStatement.getEnd());
104 + const expressionText = lastStatement.expression.getText(parsed);
105 + return `${prefix}return (${expressionText});${suffix}`;
106 +};
107 +
108 +export const wrapFileSourceForRun = (source: string): string => {
109 + const parsed = ts.createSourceFile(
110 + 'composio-run-file.ts',
111 + source,
112 + ts.ScriptTarget.Latest,
113 + true,
114 + ts.ScriptKind.TSX
115 + );
116 + const statements = [...parsed.statements];
117 + const firstNonImportIndex = statements.findIndex(statement => !ts.isImportDeclaration(statement));
118 + if (firstNonImportIndex === -1) {
119 + return source;
120 + }
121 +
122 + const bodyStart = statements[firstNonImportIndex]!.getFullStart();
123 + const importPrefix = source.slice(0, bodyStart);
124 + const body = source.slice(bodyStart);
125 + return [
126 + importPrefix,
127 + 'const __composioResult = await (async () => {',
128 + wrapInlineCodeForRun(body),
129 + '})();',
130 + 'if (__composioResult !== undefined) {',
131 + ' console.log(__composioResult);',
132 + '}',
133 + '',
134 + ].join('\n');
135 +};
136 +
137 export const inferCliInvocationPrefix = (
138 argv: ReadonlyArray<string> = process.argv
139 ): ReadonlyArray<string> => {
@@ -99,114 +169,554 @@ type RunHelperContext = {
169 readonly skipConnectionCheck?: boolean;
170 readonly skipToolParamsCheck?: boolean;
171 readonly noVerify?: boolean;
172 + readonly master?: MasterKind;
173 + readonly debug?: boolean;
174 + readonly runOutputDir?: string;
175 };
176
177 +// eslint-disable-next-line max-lines-per-function
178 +const buildRunBaseHelpersSource = (): ReadonlyArray<string> => [
179 + 'globalThis.z = z;',
180 + 'globalThis.zod = z;',
181 + 'const perfDebugEnabled = helperContext.perfDebug === true || process.env.COMPOSIO_PERF_DEBUG === "1";',
182 + 'const toolDebugEnabled = helperContext.toolDebug === true || process.env.COMPOSIO_TOOL_DEBUG === "1";',
183 + 'const perfDebugStart = Date.now();',
184 + 'let perfDebugSeq = 0;',
185 + 'const proxySessionCache = new Map();',
186 + 'const composioBaseURL = (helperContext.baseURL || "https://backend.composio.dev").replace(/\\/$/, "");',
187 + 'const subAgentSchema = {',
188 + ' type: "function",',
189 + ' description: "Prompt a sub-agent from the same agent family as the current main agent (Codex -> Codex, Claude -> Claude) and return its final response.",',
190 + ' parameters: {',
191 + ' type: "object",',
192 + ' additionalProperties: false,',
193 + ' required: ["prompt"],',
194 + ' properties: {',
195 + ' prompt: { type: "string", description: "The prompt to send to the agent CLI." },',
196 + ' target: { type: "string", enum: ["claude", "codex", "user"], description: "Optional master override. Defaults to the detected current master." },',
197 + ' model: { type: "string", description: "Optional model override passed through to the agent CLI." },',
198 + ' schema: { description: "Optional structured-output schema. Accepts a Zod schema or raw JSON Schema object." },',
199 + ' jsonSchema: { description: "Optional JSON Schema requesting structured output from the agent." },',
200 + ' },',
201 + ' },',
202 + ' returns: {',
203 + ' type: "object",',
204 + ' additionalProperties: false,',
205 + ' required: ["master", "target", "result", "structuredOutput"],',
206 + ' properties: {',
207 + ' master: { type: "string", enum: ["claude", "codex", "user"] },',
208 + ' target: { type: "string", enum: ["claude", "codex"] },',
209 + ' result: { description: "Final plain-text result when available." },',
210 + ' structuredOutput: { description: "Structured output when jsonSchema was requested." },',
211 + ' },',
212 + ' },',
213 + '};',
214 + 'const proxySchema = {',
215 + ' type: "function",',
216 + ' description: "Call proxy(toolkit) to get a fetch-compatible function bound to that toolkit\'s connected account.",',
217 + ' parameters: {',
218 + ' type: "object",',
219 + ' additionalProperties: false,',
220 + ' required: ["toolkit"],',
221 + ' properties: {',
222 + ' toolkit: { type: "string", description: "Toolkit slug whose connected account should be used" },',
223 + ' },',
224 + ' },',
225 + ' returns: {',
226 + ' type: "function",',
227 + ' signature: "fetch(input, init?) => Promise<Response>",',
228 + ' requestInit: {',
229 + ' type: "object",',
230 + ' additionalProperties: true,',
231 + ' properties: {',
232 + ' method: { type: "string", enum: ["GET", "POST", "PUT", "DELETE", "PATCH"] },',
233 + ' headers: { description: "Standard fetch headers init" },',
234 + ' body: { description: "String, JSON-ish value, Blob, ArrayBuffer, or Uint8Array" },',
235 + ' },',
236 + ' },',
237 + ' },',
238 + '};',
239 + 'const perfDebugLog = (phase, label, details = {}) => {',
240 + ' if (!perfDebugEnabled) return;',
241 + ' const elapsedMs = Date.now() - perfDebugStart;',
242 + ' const payload = { phase, label, elapsedMs, ...details };',
243 + ' console.error(`[perf] ${JSON.stringify(payload)}`);',
244 + '};',
245 + 'const helperDebugEnabled = helperContext.debug === true;',
246 + 'const sharedRunOutputDir = typeof helperContext.runOutputDir === "string" && helperContext.runOutputDir.length > 0 ? helperContext.runOutputDir : null;',
247 + 'const helperDebugLog = (step, details = {}) => {',
248 + ' if (!helperDebugEnabled) return;',
249 + ' const elapsedMs = Date.now() - perfDebugStart;',
250 + ' console.error(`[run:debug] ${JSON.stringify({ step, elapsedMs, ...details })}`);',
251 + '};',
252 + 'const parseJson = (text) => {',
253 + ' const value = text.trim();',
254 + ' if (!value) return undefined;',
255 + ' try {',
256 + ' return JSON.parse(value);',
257 + ' } catch {',
258 + ' return value;',
259 + ' }',
260 + '};',
261 + 'const stringifyForPrompt = (value) => {',
262 + ' if (value === undefined) return "undefined";',
263 + ' if (value === null) return "null";',
264 + ' if (typeof value === "string") return value;',
265 + ' if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") {',
266 + ' return String(value);',
267 + ' }',
268 + ' try {',
269 + ' return JSON.stringify(value, null, 2);',
270 + ' } catch {',
271 + ' return String(value);',
272 + ' }',
273 + '};',
274 + 'const attachPromptMethod = (value) => {',
275 + ' if (!value || typeof value !== "object" || Array.isArray(value)) return value;',
276 + ' if (typeof value.prompt === "function") return value;',
277 + ' Object.defineProperty(value, "prompt", {',
278 + ' value: () => stringifyForPrompt("data" in value ? value.data : value),',
279 + ' enumerable: false,',
280 + ' });',
281 + ' return value;',
282 + '};',
283 + 'const maybeLoadStoredCliResult = (result) => {',
284 + ' if (!result || typeof result !== "object" || result.storedInFile !== true) {',
285 + ' return attachPromptMethod(result);',
286 + ' }',
287 + ' helperDebugLog("cli.result.stored_in_file", { outputFilePath: result.outputFilePath ?? null, tokenCount: result.tokenCount ?? null });',
288 + ' const outputFilePath = typeof result.outputFilePath === "string" ? result.outputFilePath : null;',
289 + ' return attachPromptMethod({',
290 + ' ...result,',
291 + ' data: {',
292 + ' storedInFilePath: outputFilePath !== null,',
293 + ' outputFilePath,',
294 + ' },',
295 + ' });',
296 + '};',
297 + 'const describeDebugValue = (value) => {',
298 + ' if (Array.isArray(value)) return { type: "array", length: value.length };',
299 + ' if (value && typeof value === "object") return { type: "object", keys: Object.keys(value).slice(0, 20) };',
300 + ' return { type: typeof value, value: typeof value === "string" ? value.slice(0, 200) : value ?? null };',
301 + '};',
302 + 'const logCliResultPreview = (requestId, result) => {',
303 + ' if (!helperDebugEnabled) return;',
304 + ' if (!result || typeof result !== "object") {',
305 + ' helperDebugLog("cli.result", { requestId, result: describeDebugValue(result) });',
306 + ' return;',
307 + ' }',
308 + ' helperDebugLog("cli.result", {',
309 + ' requestId,',
310 + ' successful: result.successful ?? null,',
311 + ' storedInFile: result.storedInFile ?? false,',
312 + ' outputFilePath: result.outputFilePath ?? null,',
313 + ' error: result.error ?? null,',
314 + ' topLevelKeys: Object.keys(result).slice(0, 20),',
315 + ' data: "data" in result ? describeDebugValue(result.data) : null,',
316 + ' });',
317 + '};',
318 + 'const detectInvokeAgentMaster = () => {',
319 + ' if (helperContext.master === "claude" || helperContext.master === "codex" || helperContext.master === "user") {',
320 + ' return helperContext.master;',
321 + ' }',
322 + ' const envKeys = Object.keys(process.env || {});',
323 + ' if (envKeys.some((key) => key.startsWith("CODEX_"))) return "codex";',
324 + ' if (envKeys.some((key) => key.startsWith("CLAUDE_"))) return "claude";',
325 + ' return "user";',
326 + '};',
327 + 'const resolveInvokeAgentTarget = (requestedTarget) => {',
328 + ' if (requestedTarget === "claude" || requestedTarget === "codex") return requestedTarget;',
329 + ' const detected = requestedTarget === "user" ? "user" : detectInvokeAgentMaster();',
330 + ' if (detected === "codex" || detected === "claude") return detected;',
331 + ' if (typeof Bun.which === "function" && Bun.which("codex")) return "codex";',
332 + ' if (typeof Bun.which === "function" && Bun.which("claude")) return "claude";',
333 + ' throw new Error("subAgent() could not determine an agent CLI. Current master is user; install codex or claude, or pass { target: \\"codex\\" | \\"claude\\" }.");',
334 + '};',
335 + 'const normalizeInvokeAgentOptions = (options = {}) => {',
336 + ' if (options == null || typeof options !== "object" || Array.isArray(options)) {',
337 + ' throw new Error("subAgent() options must be an object when provided.");',
338 + ' }',
339 + ' if (options.schema !== undefined && options.jsonSchema !== undefined) {',
340 + ' throw new Error("subAgent() accepts either options.schema or options.jsonSchema, not both.");',
341 + ' }',
342 + ' const inputSchema = options.schema ?? options.jsonSchema;',
343 + ' let structuredSchema;',
344 + ' if (inputSchema !== undefined) {',
345 + ' if (inputSchema && typeof inputSchema.safeParse === "function" && inputSchema._def) {',
346 + ' if (typeof z.toJSONSchema !== "function") {',
347 + ' throw new Error("subAgent() requires Zod 4 with z.toJSONSchema() when using options.schema.");',
348 + ' }',
349 + ' structuredSchema = z.toJSONSchema(inputSchema);',
350 + ' } else if (typeof inputSchema === "object" && inputSchema !== null && !Array.isArray(inputSchema)) {',
351 + ' structuredSchema = inputSchema;',
352 + ' } else {',
353 + ' throw new Error("subAgent() schema must be a Zod schema or JSON Schema object.");',
354 + ' }',
355 + ' }',
356 + ' return { ...options, structuredSchema };',
357 + '};',
358 + 'const runExternalCommandText = async (cmd, spawnOptions = {}) => {',
359 + ' helperDebugLog("agent.spawn", { command: cmd[0], args: cmd.slice(1) });',
360 + ' const child = Bun.spawn({',
361 + ' cmd,',
362 + ' env: { ...process.env, ...(sharedRunOutputDir ? { COMPOSIO_RUN_OUTPUT_DIR: sharedRunOutputDir } : {}), ...(spawnOptions.env || {}) },',
363 + ' cwd: spawnOptions.cwd || process.cwd(),',
364 + ' stdio: ["pipe", "pipe", "pipe"],',
365 + ' });',
366 + ' const stdout = child.stdout ? await new Response(child.stdout).text() : "";',
367 + ' const stderr = child.stderr ? await new Response(child.stderr).text() : "";',
368 + ' const exitCode = await child.exited;',
369 + ' if (exitCode !== 0) {',
370 + ' const details = stderr.trim() || stdout.trim();',
371 + ' const suffix = details ? `: ${details}` : "";',
372 + ' helperDebugLog("agent.error", { command: cmd[0], exitCode, stderr: stderr.trim() || undefined });',
373 + ' throw new Error(`${cmd[0]} failed with exit code ${exitCode}${suffix}`);',
374 + ' }',
375 + ' helperDebugLog("agent.done", { command: cmd[0], exitCode, stdoutBytes: stdout.length, stderrBytes: stderr.length });',
376 + ' return { stdout, stderr, exitCode };',
377 + '};',
378 + 'const requireConsumerProxyContext = () => {',
379 + ' if (!helperContext.apiKey) {',
380 + ' throw new Error("proxy() requires an authenticated Composio user session.");',
381 + ' }',
382 + ' if (!helperContext.orgId || !helperContext.consumerProjectId || !helperContext.consumerUserId) {',
383 + ' throw new Error("proxy() requires a consumer project context so it can use the consumer project credentials.");',
384 + ' }',
385 + ' return {',
386 + ' apiKey: helperContext.apiKey,',
387 + ' orgId: helperContext.orgId,',
388 + ' projectId: helperContext.consumerProjectId,',
389 + ' userId: helperContext.consumerUserId,',
390 + ' };',
391 + '};',
392 + 'const normalizeProxyToolkit = (toolkit) => {',
393 + ' if (typeof toolkit !== "string" || toolkit.trim().length === 0) {',
394 + ' throw new Error("proxy() requires a non-empty toolkit string.");',
395 + ' }',
396 + ' return toolkit.trim();',
397 + '};',
398 + 'const normalizeFetchHeaders = (headers) => {',
399 + ' if (!headers) return [];',
400 + ' return Array.from(new Headers(headers).entries()).map(([name, value]) => ({',
401 + ' name,',
402 + ' type: "header",',
403 + ' value,',
404 + ' }));',
405 + '};',
406 + 'const normalizeFetchBody = async (body) => {',
407 + ' if (body === undefined || body === null) return undefined;',
408 + ' if (typeof body === "string") return body;',
409 + ' if (typeof body === "number" || typeof body === "boolean") return body;',
410 + ' if (typeof Blob !== "undefined" && body instanceof Blob) {',
411 + ' return await body.text();',
412 + ' }',
413 + ' if (body instanceof ArrayBuffer) {',
414 + ' return Buffer.from(body).toString("base64");',
415 + ' }',
416 + ' if (ArrayBuffer.isView(body)) {',
417 + ' return Buffer.from(body.buffer, body.byteOffset, body.byteLength).toString("base64");',
418 + ' }',
419 + ' return body;',
420 + '};',
421 + 'const normalizeFetchInput = async (input, init = {}) => {',
422 + ' if (typeof Request !== "undefined" && input instanceof Request) {',
423 + ' throw new Error("proxy() does not support passing a Request instance yet. Pass a URL string and init instead.");',
424 + ' }',
425 + ' const endpoint = input instanceof URL ? input.toString() : input;',
426 + ' if (typeof endpoint !== "string" || endpoint.trim().length === 0) {',
427 + ' throw new Error("proxy fetch requires a non-empty URL string or URL object.");',
428 + ' }',
429 + ' const method = typeof init.method === "string" ? init.method.toUpperCase() : "GET";',
430 + ' if (!["GET", "POST", "PUT", "DELETE", "PATCH"].includes(method)) {',
431 + ' throw new Error("proxy fetch only supports GET, POST, PUT, DELETE, PATCH.");',
432 + ' }',
433 + ' return {',
434 + ' endpoint: endpoint.trim(),',
435 + ' method,',
436 + ' parameters: normalizeFetchHeaders(init.headers),',
437 + ' body: await normalizeFetchBody(init.body),',
438 + ' };',
439 + '};',
440 + 'const fetchComposioJson = async (pathname, body) => {',
441 + ' const auth = requireConsumerProxyContext();',
442 + ' const response = await fetch(`${composioBaseURL}${pathname}`, {',
443 + ' method: "POST",',
444 + ' headers: {',
445 + ' "content-type": "application/json",',
446 + ' "x-user-api-key": auth.apiKey,',
447 + ' "x-org-id": auth.orgId,',
448 + ' "x-project-id": auth.projectId,',
449 + ' },',
450 + ' body: JSON.stringify(body),',
451 + ' });',
452 + ' const raw = await response.text();',
453 + ' const parsed = parseJson(raw);',
454 + ' if (!response.ok) {',
455 + ' const detail = typeof parsed === "string" ? parsed : (parsed?.message || parsed?.error || raw.trim() || undefined);',
456 + ' const error = new Error(`Composio proxy request failed with status ${response.status}${detail ? `: ${detail}` : ""}`);',
457 + ' Object.assign(error, { status: response.status, response: parsed ?? raw });',
458 + ' throw error;',
459 + ' }',
460 + ' return parsed;',
461 + '};',
462 + 'const getProxySessionId = async (toolkit) => {',
463 + ' const cached = proxySessionCache.get(toolkit);',
464 + ' if (cached) return cached;',
465 + ' const auth = requireConsumerProxyContext();',
466 + ' const created = await fetchComposioJson("/api/v3/tool_router/session", {',
467 + ' user_id: auth.userId,',
468 + ' manage_connections: { enable: false },',
469 + ' toolkits: { enable: [toolkit] },',
470 + ' });',
471 + ' const sessionId = created?.session_id;',
472 + ' if (typeof sessionId !== "string" || sessionId.length === 0) {',
473 + ' throw new Error("Composio proxy session creation returned no session_id.");',
474 + ' }',
475 + ' proxySessionCache.set(toolkit, sessionId);',
476 + ' return sessionId;',
477 + '};',
478 + '',
479 + 'const runCliJson = async (args) => {',
480 + ' const requestId = `${args[0] ?? "cli"}#${++perfDebugSeq}`;',
481 + ' helperDebugLog("cli.start", { requestId, args });',
482 + ' const env = {',
483 + ' ...process.env,',
484 + ' ...(helperContext.apiKey ? { COMPOSIO_USER_API_KEY: helperContext.apiKey } : {}),',
485 + ' ...(helperContext.baseURL ? { COMPOSIO_BASE_URL: helperContext.baseURL } : {}),',
486 + ' ...(helperContext.webURL ? { COMPOSIO_WEB_URL: helperContext.webURL } : {}),',
487 + ' ...(sharedRunOutputDir ? { COMPOSIO_RUN_OUTPUT_DIR: sharedRunOutputDir } : {}),',
488 + ' ...(perfDebugEnabled ? { COMPOSIO_PERF_DEBUG: "1" } : {}),',
489 + ' ...(toolDebugEnabled ? { COMPOSIO_TOOL_DEBUG: "1" } : {}),',
490 + ' };',
491 + ' delete env.BUN_BE_BUN;',
492 + ' perfDebugLog("start", requestId, { cmd: args });',
493 + ' const child = Bun.spawn({',
494 + ' cmd: [...cliPrefix, ...args],',
495 + ' env,',
496 + " stdio: ['inherit', 'pipe', perfDebugEnabled || toolDebugEnabled ? 'inherit' : 'pipe'],",
497 + ' });',
498 + ' const stdout = child.stdout ? await new Response(child.stdout).text() : "";',
499 + ' const stderr = child.stderr ? await new Response(child.stderr).text() : "";',
500 + ' const result = maybeLoadStoredCliResult(parseJson(stdout));',
501 + ' const exitCode = await child.exited;',
502 + ' if (exitCode !== 0) {',
503 + ' perfDebugLog("error", requestId, { exitCode, stderr: stderr.trim() || undefined });',
504 + ' helperDebugLog("cli.error", { requestId, exitCode, stderr: stderr.trim() || undefined });',
505 + ' const error = new Error(`composio ${args.join(" ")} failed with exit code ${exitCode}`);',
506 + ' Object.assign(error, { exitCode, result, stderr: stderr.trim() || undefined });',
507 + ' throw error;',
508 + ' }',
509 + ' if (result === undefined) {',
510 + ' const details = stderr.trim();',
511 + ' const suffix = details ? `: ${details}` : "";',
512 + ' perfDebugLog("error", requestId, { exitCode, stderr: details || undefined, noJson: true });',
513 + ' helperDebugLog("cli.error", { requestId, exitCode, stderr: details || undefined, noJson: true });',
514 + ' const error = new Error(`composio ${args.join(" ")} returned no JSON output${suffix}`);',
515 + ' Object.assign(error, { exitCode, result, stderr: details || undefined });',
516 + ' throw error;',
517 + ' }',
518 + ' perfDebugLog("end", requestId, { exitCode, stdoutBytes: stdout.length, stderrBytes: stderr.length });',
519 + ' logCliResultPreview(requestId, result);',
520 + ' helperDebugLog("cli.done", { requestId, exitCode });',
521 + ' return result;',
522 + '};',
523 + '',
524 + 'globalThis.search = async (query, options = {}) => {',
525 + ' helperDebugLog("search.prepare", { query, options });',
526 + ' const args = ["search", query];',
527 + ' if (Array.isArray(options.toolkits) && options.toolkits.length > 0) {',
528 + ' args.push("--toolkits", options.toolkits.join(","));',
529 + ' } else if (typeof options.toolkits === "string" && options.toolkits.trim().length > 0) {',
530 + ' args.push("--toolkits", options.toolkits);',
531 + ' }',
532 + ' if (typeof options.limit === "number") {',
533 + ' args.push("--limit", String(options.limit));',
534 + ' }',
535 + ' return runCliJson(args);',
536 + '};',
537 + '',
538 + 'globalThis.execute = async (slug, data = {}) => {',
539 + ' helperDebugLog("execute.prepare", { slug, hasData: data !== undefined });',
540 + ' const args = ["execute", slug];',
541 + ' if (helperContext.dryRun === true) {',
542 + ' args.push("--dry-run");',
543 + ' }',
544 + ' if (helperContext.skipConnectionCheck === true) {',
545 + ' args.push("--skip-connection-check");',
546 + ' }',
547 + ' if (helperContext.skipToolParamsCheck === true) {',
548 + ' args.push("--skip-tool-params-check");',
549 + ' }',
550 + ' if (helperContext.noVerify === true) {',
551 + ' args.push("--no-verify");',
552 + ' }',
553 + ' if (data !== undefined) {',
554 + ' const serialized = typeof data === "string" ? data : JSON.stringify(data);',
555 + ' args.push("--data", serialized);',
556 + ' }',
557 + ' const result = await runCliJson(args);',
558 + ' if (result && typeof result === "object" && result.successful === false) {',
559 + ' const message = typeof result.error === "string" && result.error.trim().length > 0',
560 + ' ? result.error.trim()',
561 + ' : `composio execute ${slug} failed`;',
562 + ' const error = new Error(message);',
563 + ' Object.assign(error, { result, slug });',
564 + ' throw error;',
565 + ' }',
566 + ' return result;',
567 + '};',
568 + '',
569 +];
570 +
571 +const buildRunInvokeAgentHelpersSource = (): ReadonlyArray<string> => [
572 + 'const toInvokeAgentResponse = (master, target, payload = {}) => ({',
573 + ' master,',
574 + ' target,',
575 + ' result: payload.result ?? null,',
576 + ' structuredOutput: payload.structuredOutput ?? null,',
577 + '});',
578 + 'const invokeClaudeAgent = async (prompt, options) => {',
579 + ' helperDebugLog("subAgent.prepare", { target: "claude", hasSchema: options.structuredSchema !== undefined });',
580 + ' const args = ["claude", "--bare", "-p", "--output-format", "json"];',
581 + ' if (typeof options.model === "string" && options.model.trim().length > 0) {',
582 + ' args.push("--model", options.model.trim());',
583 + ' }',
584 + ' if (options.structuredSchema !== undefined) {',
585 + ' args.push("--json-schema", JSON.stringify(options.structuredSchema));',
586 + ' }',
587 + ' args.push(prompt);',
588 + ' const result = await runExternalCommandText(args);',
589 + ' const parsed = parseJson(result.stdout.trim());',
590 + ' if (!parsed || typeof parsed !== "object") {',
591 + ' throw new Error("claude returned non-JSON output in subAgent().");',
592 + ' }',
593 + ' return toInvokeAgentResponse(detectInvokeAgentMaster(), "claude", {',
594 + ' result: typeof parsed.result === "string" ? parsed.result : null,',
595 + ' structuredOutput: parsed.structured_output ?? null,',
596 + ' });',
597 + '};',
598 + 'const invokeCodexAgent = async (prompt, options) => {',
599 + ' const fs = await import("node:fs");',
600 + ' const os = await import("node:os");',
601 + ' const path = await import("node:path");',
602 + ' const tempDir = sharedRunOutputDir',
603 + ' ? fs.mkdtempSync(path.join(sharedRunOutputDir, "invoke-agent-"))',
604 + ' : fs.mkdtempSync(path.join(os.tmpdir(), "composio-invoke-agent-"));',
605 + ' const outputPath = path.join(tempDir, "last-message.txt");',
606 + ' const args = ["codex", "exec", "--skip-git-repo-check", "--sandbox", "read-only", "-o", outputPath];',
607 + ' try {',
608 + ' helperDebugLog("subAgent.prepare", { target: "codex", hasSchema: options.structuredSchema !== undefined });',
609 + ' if (typeof options.model === "string" && options.model.trim().length > 0) {',
610 + ' args.push("--model", options.model.trim());',
611 + ' }',
612 + ' if (options.structuredSchema !== undefined) {',
613 + ' const schemaPath = path.join(tempDir, "schema.json");',
614 + ' fs.writeFileSync(schemaPath, JSON.stringify(options.structuredSchema), "utf8");',
615 + ' args.push("--output-schema", schemaPath);',
616 + ' }',
617 + ' args.push(prompt);',
618 + ' await runExternalCommandText(args);',
619 + ' const text = fs.readFileSync(outputPath, "utf8").trim();',
620 + ' const parsed = options.structuredSchema ? parseJson(text) : null;',
621 + ' return toInvokeAgentResponse(detectInvokeAgentMaster(), "codex", {',
622 + ' result: options.structuredSchema ? null : text,',
623 + ' structuredOutput: options.structuredSchema ? parsed : null,',
624 + ' });',
625 + ' } finally {',
626 + ' fs.rmSync(tempDir, { recursive: true, force: true });',
627 + ' }',
628 + '};',
629 + 'const subAgentImpl = async (prompt, options = {}) => {',
630 + ' if (typeof prompt !== "string" || prompt.trim().length === 0) {',
631 + ' throw new Error("subAgent() requires a non-empty prompt string.");',
632 + ' }',
633 + ' const normalizedOptions = normalizeInvokeAgentOptions(options);',
634 + ' const target = resolveInvokeAgentTarget(normalizedOptions.target);',
635 + ' helperDebugLog("subAgent.target", { requestedTarget: normalizedOptions.target ?? null, resolvedTarget: target });',
636 + ' if (target === "claude") {',
637 + ' return invokeClaudeAgent(prompt.trim(), normalizedOptions);',
638 + ' }',
639 + ' return invokeCodexAgent(prompt.trim(), normalizedOptions);',
640 + '};',
641 + 'globalThis.subAgent = subAgentImpl;',
642 + 'Object.defineProperty(globalThis.subAgent, "schema", { value: subAgentSchema });',
643 + 'globalThis.invokeAgent = subAgentImpl;',
644 + 'Object.defineProperty(globalThis.invokeAgent, "schema", { value: subAgentSchema });',
645 + '',
646 +];
647 +
648 +const buildRunProxyHelpersSource = (): ReadonlyArray<string> => [
649 + 'const toProxyResponse = async (result) => {',
650 + ' const headers = new Headers(result?.headers || {});',
651 + ' if (result?.binary_data?.url) {',
652 + ' const binaryResponse = await fetch(result.binary_data.url);',
653 + ' binaryResponse.headers.forEach((value, key) => {',
654 + ' if (!headers.has(key)) headers.set(key, value);',
655 + ' });',
656 + ' return new Response(binaryResponse.body, {',
657 + ' status: result.status ?? binaryResponse.status,',
658 + ' headers,',
659 + ' });',
660 + ' }',
661 + ' if (result?.data === undefined || result?.data === null) {',
662 + ' return new Response(null, { status: result?.status ?? 200, headers });',
663 + ' }',
664 + ' if (typeof result.data === "string") {',
665 + ' if (!headers.has("content-type")) headers.set("content-type", "text/plain; charset=utf-8");',
666 + ' return new Response(result.data, { status: result.status ?? 200, headers });',
667 + ' }',
668 + ' if (!headers.has("content-type")) headers.set("content-type", "application/json; charset=utf-8");',
669 + ' return new Response(JSON.stringify(result.data), { status: result.status ?? 200, headers });',
670 + '};',
671 + 'globalThis.proxy = async (toolkit) => {',
672 + ' const normalizedToolkit = normalizeProxyToolkit(toolkit);',
673 + ' helperDebugLog("proxy.session", { toolkit: normalizedToolkit, cached: proxySessionCache.has(normalizedToolkit) });',
674 + ' const sessionId = await getProxySessionId(normalizedToolkit);',
675 + ' const proxyFetch = async (input, init = {}) => {',
676 + ' const request = await normalizeFetchInput(input, init);',
677 + ' helperDebugLog("proxy.request", { toolkit: normalizedToolkit, method: request.method, endpoint: request.endpoint });',
678 + ' const result = await fetchComposioJson(`/api/v3/tool_router/session/${sessionId}/proxy_execute`, {',
679 + ' toolkit_slug: normalizedToolkit,',
680 + ' endpoint: request.endpoint,',
681 + ' method: request.method,',
682 + ' ...(request.body !== undefined ? { body: request.body } : {}),',
683 + ' ...(request.parameters?.length',
684 + ' ? {',
685 + ' parameters: request.parameters.map((parameter) => ({',
686 + ' name: parameter.name,',
687 + ' type: parameter.type,',
688 + ' value: String(parameter.value),',
689 + ' })),',
690 + ' }',
691 + ' : {}),',
692 + ' });',
693 + ' return toProxyResponse(result);',
694 + ' };',
695 + ' Object.defineProperty(proxyFetch, "toolkit", { value: normalizedToolkit });',
696 + ' return proxyFetch;',
697 + '};',
698 + 'Object.defineProperty(globalThis.proxy, "schema", { value: proxySchema });',
699 + '',
700 + 'Object.defineProperty(globalThis, "__composioConsumerContext", {',
701 + ' value: helperContext,',
702 + ' configurable: true,',
703 + '});',
704 + '',
705 +];
706 +
707 export const buildRunHelpersSource = (
708 cliPrefix: ReadonlyArray<string>,
709 context: RunHelperContext = {}
710 ): string =>
711 [
712 + 'import { z } from "zod";',
713 + '',
714 `const cliPrefix = ${JSON.stringify(cliPrefix)};`,
715 `const helperContext = ${JSON.stringify(context)};`,
716 '',
112 - 'const perfDebugEnabled = helperContext.perfDebug === true || process.env.COMPOSIO_PERF_DEBUG === "1";',
113 - 'const toolDebugEnabled = helperContext.toolDebug === true || process.env.COMPOSIO_TOOL_DEBUG === "1";',
114 - 'const perfDebugStart = Date.now();',
115 - 'let perfDebugSeq = 0;',
116 - 'const perfDebugLog = (phase, label, details = {}) => {',
117 - ' if (!perfDebugEnabled) return;',
118 - ' const elapsedMs = Date.now() - perfDebugStart;',
119 - ' const payload = { phase, label, elapsedMs, ...details };',
120 - ' console.error(`[perf] ${JSON.stringify(payload)}`);',
121 - '};',
122 - 'const parseJson = (text) => {',
123 - ' const value = text.trim();',
124 - ' if (!value) return undefined;',
125 - ' try {',
126 - ' return JSON.parse(value);',
127 - ' } catch {',
128 - ' return value;',
129 - ' }',
130 - '};',
131 - '',
132 - 'const runCliJson = async (args) => {',
133 - ' const requestId = `${args[0] ?? "cli"}#${++perfDebugSeq}`;',
134 - ' const env = {',
135 - ' ...process.env,',
136 - ' ...(helperContext.apiKey ? { COMPOSIO_USER_API_KEY: helperContext.apiKey } : {}),',
137 - ' ...(helperContext.baseURL ? { COMPOSIO_BASE_URL: helperContext.baseURL } : {}),',
138 - ' ...(helperContext.webURL ? { COMPOSIO_WEB_URL: helperContext.webURL } : {}),',
139 - ' ...(perfDebugEnabled ? { COMPOSIO_PERF_DEBUG: "1" } : {}),',
140 - ' ...(toolDebugEnabled ? { COMPOSIO_TOOL_DEBUG: "1" } : {}),',
141 - ' };',
142 - ' delete env.BUN_BE_BUN;',
143 - ' perfDebugLog("start", requestId, { cmd: args });',
144 - ' const child = Bun.spawn({',
145 - ' cmd: [...cliPrefix, ...args],',
146 - ' env,',
147 - " stdio: ['inherit', 'pipe', perfDebugEnabled || toolDebugEnabled ? 'inherit' : 'pipe'],",
148 - ' });',
149 - ' const stdout = child.stdout ? await new Response(child.stdout).text() : "";',
150 - ' const stderr = child.stderr ? await new Response(child.stderr).text() : "";',
151 - ' const result = parseJson(stdout);',
152 - ' const exitCode = await child.exited;',
153 - ' if (exitCode !== 0) {',
154 - ' perfDebugLog("error", requestId, { exitCode, stderr: stderr.trim() || undefined });',
155 - ' const error = new Error(`composio ${args.join(" ")} failed with exit code ${exitCode}`);',
156 - ' Object.assign(error, { exitCode, result, stderr: stderr.trim() || undefined });',
157 - ' throw error;',
158 - ' }',
159 - ' if (result === undefined) {',
160 - ' const details = stderr.trim();',
161 - ' const suffix = details ? `: ${details}` : "";',
162 - ' perfDebugLog("error", requestId, { exitCode, stderr: details || undefined, noJson: true });',
163 - ' const error = new Error(`composio ${args.join(" ")} returned no JSON output${suffix}`);',
164 - ' Object.assign(error, { exitCode, result, stderr: details || undefined });',
165 - ' throw error;',
166 - ' }',
167 - ' perfDebugLog("end", requestId, { exitCode, stdoutBytes: stdout.length, stderrBytes: stderr.length });',
168 - ' return result;',
169 - '};',
170 - '',
171 - 'globalThis.search = async (query, options = {}) => {',
172 - ' const args = ["search", query];',
173 - ' if (Array.isArray(options.toolkits) && options.toolkits.length > 0) {',
174 - ' args.push("--toolkits", options.toolkits.join(","));',
175 - ' } else if (typeof options.toolkits === "string" && options.toolkits.trim().length > 0) {',
176 - ' args.push("--toolkits", options.toolkits);',
177 - ' }',
178 - ' if (typeof options.limit === "number") {',
179 - ' args.push("--limit", String(options.limit));',
180 - ' }',
181 - ' return runCliJson(args);',
182 - '};',
183 - '',
184 - 'globalThis.execute = async (slug, data = {}) => {',
185 - ' const args = ["execute", slug];',
186 - ' if (helperContext.dryRun === true) {',
187 - ' args.push("--dry-run");',
188 - ' }',
189 - ' if (helperContext.skipConnectionCheck === true) {',
190 - ' args.push("--skip-connection-check");',
191 - ' }',
192 - ' if (helperContext.skipToolParamsCheck === true) {',
193 - ' args.push("--skip-tool-params-check");',
194 - ' }',
195 - ' if (helperContext.noVerify === true) {',
196 - ' args.push("--no-verify");',
197 - ' }',
198 - ' if (data !== undefined) {',
199 - ' const serialized = typeof data === "string" ? data : JSON.stringify(data);',
200 - ' args.push("--data", serialized);',
201 - ' }',
202 - ' return runCliJson(args);',
203 - '};',
204 - '',
205 - 'Object.defineProperty(globalThis, "__composioConsumerContext", {',
206 - ' value: helperContext,',
207 - ' configurable: true,',
208 - '});',
209 - '',
717 + ...buildRunBaseHelpersSource(),
718 + ...buildRunInvokeAgentHelpersSource(),
719 + ...buildRunProxyHelpersSource(),
720 ].join('\n');
721
722 const createRunHelpersPreloadFile = (
@@ -215,27 +725,67 @@ const createRunHelpersPreloadFile = (
725 ) => {
726 const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'composio-run-'));
727 const preloadPath = path.join(directory, 'globals.mjs');
218 - fs.writeFileSync(preloadPath, buildRunHelpersSource(cliPrefix, context), 'utf8');
219 - return { directory, preloadPath };
728 + const runOutputDir =
729 + typeof context.runOutputDir === 'string' && context.runOutputDir.length > 0
730 + ? context.runOutputDir
731 + : path.join(directory, 'artifacts');
732 + fs.mkdirSync(runOutputDir, { recursive: true });
733 + fs.writeFileSync(
734 + preloadPath,
735 + buildRunHelpersSource(cliPrefix, { ...context, runOutputDir }),
736 + 'utf8'
737 + );
738 + return { directory, preloadPath, runOutputDir };
739 };
740
741 export const buildRunCommand = ({
742 file,
743 args,
744 preloadPath,
745 + preloadDirectory,
746 }: {
747 file: Option.Option<string>;
748 args: ReadonlyArray<string>;
749 preloadPath: string;
750 + preloadDirectory: string;
751 }) => {
752 + // Use process.execPath directly — the child is spawned with BUN_BE_BUN=1
753 + // which makes compiled Bun binaries act as a plain Bun runtime.
754 + // Avoid the `run` subcommand entirely since Bun intercepts it as its own
755 + // built-in; `bun --preload <file> <script>` works without it.
756 const base = [process.execPath, '--preload', preloadPath];
757 if (Option.isSome(file)) {
233 - return [...base, 'run', file.value, ...withArgDelimiter(args)];
758 + const filePath = path.resolve(file.value);
759 + const wrapperFilePath = path.join(
760 + path.dirname(filePath),
761 + `.composio-run-${path.basename(preloadDirectory)}${path.extname(filePath) || '.ts'}`
762 + );
763 + fs.writeFileSync(
764 + wrapperFilePath,
765 + wrapFileSourceForRun(fs.readFileSync(filePath, 'utf8')),
766 + 'utf8'
767 + );
768 + return {
769 + cmd: [...base, wrapperFilePath, ...withArgDelimiter(args)],
770 + cleanupPaths: [wrapperFilePath],
771 + };
772 }
773
774 const [inlineCode, ...scriptArgs] = args;
775 if (inlineCode) {
238 - return [...base, '--eval', inlineCode, ...withArgDelimiter(scriptArgs)];
776 + const wrappedInlineCode = [
777 + '(async () => {',
778 + wrapInlineCodeForRun(inlineCode),
779 + '})().then((__composioResult) => {',
780 + ' if (__composioResult !== undefined) {',
781 + ' console.log(__composioResult);',
782 + ' }',
783 + '});',
784 + ].join('\n');
785 + return {
786 + cmd: [...base, '--eval', wrappedInlineCode, ...withArgDelimiter(scriptArgs)],
787 + cleanupPaths: [],
788 + };
789 }
790
791 throw new Error('Provide inline code or use --file to run a script file.');
@@ -267,12 +817,19 @@ const resolveRunHelperContext = () =>
817 consumerUserId: consumerProject.value.consumerUserId,
818 consumerProjectId: consumerProject.value.projectId,
819 consumerProjectName: consumerProject.value.projectName,
820 + runOutputDir: Option.getOrUndefined(
821 + yield* resolveCliSessionArtifacts({
822 + orgId,
823 + consumerUserId: consumerProject.value.consumerUserId,
824 + }).pipe(Effect.map(Option.map(artifacts => artifacts.directoryPath)))
825 + ),
826 } satisfies RunHelperContext;
827 });
828
829 export const runCmd = Command.make('run', {
830 file,
831 dryRun,
832 + debug,
833 skipConnectionCheck,
834 skipToolParamsCheck,
835 noVerify,
@@ -280,43 +837,59 @@ export const runCmd = Command.make('run', {
837 }).pipe(
838 Command.withDescription(
839 [
283 - 'Run inline TS/JS code or a file with the embedded Bun runtime.',
284 - 'Use this for programmatic multi-step tool workflows when you want to stay in code and not orchestrate everything through bash.',
285 - '',
286 - 'Usage:',
287 - " composio run '<code>' [-- ...args]",
288 - ' composio run --file ./script.ts [-- ...args]',
840 + 'Run inline TS/JS code or a file with injected Composio helpers that behave like their CLI counterparts.',
841 '',
842 'Examples:',
291 - ` composio run 'const issue = await execute("GITHUB_CREATE_ISSUE", { owner: "acme", repo: "app", title: "Bug report" }); console.log(issue)'`,
292 - ` composio run --skip-connection-check 'const email = await execute("GMAIL_SEND_EMAIL", { recipient_email: "a@b.com", body: "Hello" }); console.log(email)'`,
293 - ` composio run --skip-tool-params-check 'const email = await execute("GMAIL_SEND_EMAIL", { recipient_email: "a@b.com", body: "Hello" }); console.log(email)'`,
294 - ` composio run --no-verify 'const email = await execute("GMAIL_SEND_EMAIL", { recipient_email: "a@b.com", body: "Hello" }); console.log(email)'`,
295 - ` composio run --dry-run 'const email = await execute("GMAIL_SEND_EMAIL", { recipient_email: "a@b.com", body: "Hello" }); console.log(email)'`,
843 + ` composio run 'const issue = await execute("GITHUB_CREATE_ISSUE", { owner: "composiohq", repo: "composio", title: "Bug report" }); console.log(issue)'`,
844 + ` composio run --dry-run 'await execute("GMAIL_SEND_EMAIL", { recipient_email: "a@b.com", body: "Hello" })'`,
845 + ` composio run --debug 'const me = await execute("GITHUB_GET_THE_AUTHENTICATED_USER"); console.log(me)'`,
846 + ` composio run '`,
847 + ` const [emails, issues] = await Promise.all([`,
848 + ` execute("GMAIL_FETCH_EMAILS", { max_results: 5 }),`,
849 + ` execute("GITHUB_LIST_REPOSITORY_ISSUES", { owner: "composiohq", repo: "composio", state: "open" }),`,
850 + ` ]);`,
851 + ` const brief = await subAgent(`,
852 + ` \`Create a morning brief from these emails and issues.\\n\\n\${emails.prompt()}\\n\\n\${issues.prompt()}\`,`,
853 + ` {`,
854 + ` schema: z.object({`,
855 + ` brief: z.string(),`,
856 + ` urgentEmails: z.array(z.string()),`,
857 + ` urgentIssues: z.array(z.string()),`,
858 + ` }),`,
859 + ` }`,
860 + ` );`,
861 + ` brief.structuredOutput;`,
862 + ` '`,
863 ' composio run --file ./script.ts -- hello world',
864 '',
298 - 'Injected globals:',
299 - ' await execute(slug, data?)',
300 - ' Primary helper. Wraps `composio execute` and returns parsed JSON output quickly.',
301 - ' It validates arguments against cached tool schemas in `~/.composio/tool_definitions/` when available.',
302 - ' await search(query, { toolkits?: string[] | string, limit?: number })',
303 - ' Secondary discovery helper. Wraps `composio search` and returns parsed JSON stdout.',
304 - ' Both helpers automatically reuse your top level `execute` and `search` auth states, using the toolkits and apps you have already authorized.',
865 + 'Injected helpers (behave like their CLI counterparts):',
866 + ' execute(slug, data?) Same as `composio execute` — returns parsed JSON',
867 + ' search(query, options?) Same as `composio search` — returns matching tools',
868 + ' subAgent(prompt, options?) Spawn a powerful sub-agent from the same agent family as your current main agent',
869 + ' (Codex -> Codex, Claude -> Claude) with optional Zod structured output',
870 + ' result.prompt() Prompt-safe serialization of a helper result, ideal for subAgent(...)',
871 + ' const f = await proxy(toolkit) Same as `composio proxy` — returns a fetch function',
872 + ' Example: const f = await proxy("gmail")',
873 + ' const me = await f("https://gmail.googleapis.com/gmail/v1/users/me/profile")',
874 + ' z Injected global from `zod` for structured output schemas',
875 + '',
876 + 'All helpers reuse your CLI auth state and linked accounts.',
877 '',
306 - 'Hints:',
307 - ' Use `composio search "<query>"` outside `run` to discover tool slugs before writing a script.',
308 - ' Use `composio link <toolkit>` outside `run` to authenticate apps up front before calling `execute(...)`.',
309 - ' Use `composio execute <slug> --get-schema` if you want to inspect tool inputs before scripting.',
310 - ' Since execute responses are parsed back into code almost instantly, it is usually fine to just try `execute(...)` directly in a script.',
311 - ' Treat `run` as the place to compose many tool calls once discovery and auth are already handled.',
878 + 'Flags:',
879 + ' --debug Log helper steps while the script runs',
880 + ' --dry-run Preview execute() calls without running them',
881 + ' --skip-connection-check Skip the linked-account check',
882 + ' --skip-tool-params-check Skip input validation against cached schema',
883 + ' --no-verify Skip both checks above',
884 '',
313 - 'Advanced:',
314 - ' import { $ } from "bun"',
315 - ' await $`${process.execPath} manage toolkits list`',
885 + 'See also:',
886 + ' composio search "<query>" Discover tool slugs before scripting',
887 + ' composio link <toolkit> Connect accounts before scripting',
888 + ' composio execute <slug> --get-schema Inspect tool inputs before scripting',
889 ].join('\n')
890 ),
891 Command.withHandler(
319 - ({ file, dryRun, skipConnectionCheck, skipToolParamsCheck, noVerify, args }) =>
892 + ({ file, dryRun, debug, skipConnectionCheck, skipToolParamsCheck, noVerify, args }) =>
893 Effect.gen(function* () {
894 const perfDebug = isPerfDebugEnabled();
895 const toolDebug = isToolDebugEnabled();
@@ -331,18 +904,40 @@ export const runCmd = Command.make('run', {
904 }
905 }
906
334 - const preload = createRunHelpersPreloadFile(inferCliInvocationPrefix(), {
907 + const helperContext: RunHelperContext = {
908 ...(yield* resolveRunHelperContext()),
909 + master: detectMaster(),
910 perfDebug,
911 toolDebug,
912 + debug,
913 dryRun,
914 skipConnectionCheck,
915 skipToolParamsCheck,
916 noVerify,
342 - });
917 + };
918 + const preload = createRunHelpersPreloadFile(inferCliInvocationPrefix(), helperContext);
919 + let cleanupPaths: ReadonlyArray<string> = [];
920 try {
921 + yield* appendCliSessionHistory({
922 + orgId: helperContext.orgId,
923 + consumerUserId: helperContext.consumerUserId,
924 + entry: {
925 + command: 'run',
926 + status: 'start',
927 + file: Option.getOrUndefined(file),
928 + args,
929 + debug,
930 + },
931 + }).pipe(Effect.catchAll(() => Effect.void));
932 + const runCommand = buildRunCommand({
933 + file,
934 + args,
935 + preloadPath: preload.preloadPath,
936 + preloadDirectory: preload.directory,
937 + });
938 + cleanupPaths = runCommand.cleanupPaths;
939 const child = Bun.spawn({
345 - cmd: buildRunCommand({ file, args, preloadPath: preload.preloadPath }),
940 + cmd: runCommand.cmd,
941 env: {
942 ...process.env,
943 BUN_BE_BUN: '1',
@@ -353,9 +948,11 @@ export const runCmd = Command.make('run', {
948 });
949
950 const exitCode = yield* Effect.promise(() => child.exited);
356 - fs.rmSync(preload.directory, { recursive: true, force: true });
951 process.exit(exitCode);
952 } finally {
953 + for (const cleanupPath of cleanupPaths) {
954 + fs.rmSync(cleanupPath, { force: true });
955 + }
956 fs.rmSync(preload.directory, { recursive: true, force: true });
957 }
958 })
ts/packages/cli/src/commands/tools/commands/tools.execute.cmd.ts
+192 -187
@@ -1,14 +1,11 @@
1 import { Args, Command, Options } from '@effect/cli';
2 -import * as fs from 'node:fs';
3 -import * as path from 'node:path';
2 import util from 'node:util';
3 import { Effect, Option, Either, Exit, Fiber, Cause } from 'effect';
6 -import { FileSystem } from '@effect/platform';
7 -import { parse as parseJsonWithComments } from 'comment-json';
4 import { encodingForModel } from 'js-tiktoken';
5 import { redact } from 'src/ui/redact';
10 -import { readStdin, readStdinIfPiped } from 'src/effects/read-stdin';
6 +import { parseJsonIsh } from 'src/utils/parse-json-ish';
7 import { requireAuth } from 'src/effects/require-auth';
8 +import { resolveOptionalTextInput } from 'src/effects/resolve-optional-text-input';
9 import {
10 getCachedToolInputDefinition,
11 getOrFetchToolInputDefinition,
@@ -19,19 +16,11 @@ import {
16 validateToolInputArgumentsWithDefinition,
17 } from 'src/services/tool-input-validation';
18 import { TerminalUI } from 'src/services/terminal-ui';
22 -import {
23 - ActionExecuteConnectedAccountNotFoundError,
24 - ToolsExecutor,
25 -} from 'src/services/tools-executor';
19 +import { ToolsExecutor } from 'src/services/tools-executor';
20 import type { ToolExecuteParams, ToolExecuteResponse } from 'src/services/tools-executor';
21 import { ComposioToolkitsRepository } from 'src/services/composio-clients';
22 import { ComposioUserContext } from 'src/services/user-context';
23 import { ProjectContext } from 'src/services/project-context';
30 -import {
31 - extractApiErrorDetails,
32 - extractMessage,
33 - extractSlug,
34 -} from 'src/utils/api-error-extraction';
24 import { handleHttpServerError } from 'src/effects/handle-http-error';
25 import { formatToolInputParameters } from '../format';
26 import { ComposioClientSingleton } from 'src/services/composio-clients';
@@ -45,6 +34,15 @@ import {
34 getFreshConsumerConnectedToolkitsFromCache,
35 refreshConsumerConnectedToolkitsCache,
36 } from 'src/services/consumer-short-term-cache';
37 +import {
38 + appendCliSessionHistory,
39 + resolveCliSessionArtifacts,
40 +} from 'src/services/cli-session-artifacts';
41 +import { storeCliSessionArtifact } from 'src/services/cli-session-artifacts';
42 +import {
43 + ComposioNoActiveConnectionError,
44 + mapComposioError,
45 +} from 'src/services/composio-error-overrides';
46
47 const slug = Args.text({ name: 'slug' }).pipe(
48 Args.withDescription('Tool slug (e.g. "GITHUB_CREATE_ISSUE")')
@@ -66,58 +64,37 @@ const projectName = Options.text('project-name').pipe(
64 Options.withDescription('Developer project name override for this command')
65 );
66
69 -const getSchema = Options.boolean('get-schema').pipe(Options.withDefault(false));
70 -const dryRun = Options.boolean('dry-run').pipe(Options.withDefault(false));
67 +const getSchema = Options.boolean('get-schema').pipe(
68 + Options.withDescription('Fetch and print the raw tool schema without executing'),
69 + Options.withDefault(false)
70 +);
71 +const dryRun = Options.boolean('dry-run').pipe(
72 + Options.withDescription('Validate and preview the tool call without executing'),
73 + Options.withDefault(false)
74 +);
75 const skipConnectionCheck = Options.boolean('skip-connection-check').pipe(
76 + Options.withDescription('Skip the linked-account check'),
77 Options.withDefault(false)
78 );
79 const skipToolParamsCheck = Options.boolean('skip-tool-params-check').pipe(
80 + Options.withDescription('Skip input validation against cached schema'),
81 + Options.withDefault(false)
82 +);
83 +const noVerify = Options.boolean('no-verify').pipe(
84 + Options.withDescription('Skip both connection and input validation checks'),
85 Options.withDefault(false)
86 );
77 -const noVerify = Options.boolean('no-verify').pipe(Options.withDefault(false));
87
88 const resolveInput = (input: Option.Option<string>) =>
80 - Effect.gen(function* () {
81 - const fs = yield* FileSystem.FileSystem;
82 -
83 - if (Option.isSome(input)) {
84 - const value = input.value.trim();
85 - if (value === '-') {
86 - return yield* readStdin;
87 - }
88 - if (value.startsWith('@')) {
89 - const filePath = value.slice(1).trim();
90 - if (!filePath) {
91 - return yield* Effect.fail(new Error('Missing file path after "@" in --data'));
92 - }
93 - return yield* fs.readFileString(filePath, 'utf-8');
94 - }
95 - return value;
96 - }
97 -
98 - const piped = yield* readStdinIfPiped;
99 - if (Option.isSome(piped)) {
100 - return piped.value;
101 - }
102 -
89 + resolveOptionalTextInput(input, {
90 // Default to empty object when no data provided (e.g. tools with no required args)
104 - return '{}';
91 + missingValue: '{}',
92 });
93
94 const parseArguments = (raw: string) =>
95 Effect.gen(function* () {
96 const parsed = yield* Effect.try({
110 - try: () => {
111 - try {
112 - return JSON.parse(raw) as unknown;
113 - } catch {
114 - try {
115 - return parseJsonWithComments(raw, undefined, true) as unknown;
116 - } catch {
117 - return Function(`"use strict"; return (${raw});`)() as unknown;
118 - }
119 - }
120 - },
97 + try: () => parseJsonIsh(raw),
98 catch: () =>
99 new Error(
100 'Invalid JSON input. Provide JSON or a JS-style object literal, e.g. -d \'{ "key": "value" }\''
@@ -162,17 +139,6 @@ const connectionTips = (toolSlug: string, surface: 'root' | 'manage' | 'dev') =>
139 ].join('\n');
140 };
141
165 -const isNoActiveConnectionError = (details: { code?: number; slug?: string } | undefined) =>
166 - details?.code === 4302 || details?.slug === 'ToolRouterV2_NoActiveConnection';
167 -
168 -const noActiveConnectionMessage = (toolSlug: string) => {
169 - const toolkit = toolkitFromToolSlug(toolSlug);
170 - if (!toolkit) {
171 - return 'No active connection found for this tool call. Link the required toolkit/app, then retry.';
172 - }
173 - return `No active connection found for toolkit "${toolkit}". Run \`composio link ${toolkit}\`, then retry.`;
174 -};
175 -
142 const ciRedactReplacer = (_key: string, value: unknown): unknown => {
143 if (typeof value !== 'string') return value;
144 if (_key === 'logId') return redact({ value, prefix: 'log_' });
@@ -227,85 +193,65 @@ type StoredExecuteOutputSummary = {
193 const serializeExecuteOutput = (result: unknown): string =>
194 JSON.stringify(result, ciRedactReplacer, 2);
195
230 -const randomToken = (length = 16) => crypto.randomUUID().replace(/-/g, '').slice(0, length);
231 -
232 -const persistLargeExecuteOutput = (json: string): StoredExecuteOutputSummary => {
233 - const directoryPath = path.join('/tmp/composio', randomToken());
234 - const outputHash = randomToken();
235 - const outputFilePath = path.join(directoryPath, `output-${outputHash}.json`);
236 - fs.mkdirSync(directoryPath, { recursive: true });
237 - fs.writeFileSync(outputFilePath, json, 'utf8');
196 +const persistLargeExecuteOutput = (toolSlug: string, json: string, sharedDirectory?: string) =>
197 + Effect.gen(function* () {
198 + const outputFilePath = yield* storeCliSessionArtifact({
199 + contents: json,
200 + name: `${toolSlug}_OUTPUT`,
201 + extension: 'json',
202 + directoryPath: sharedDirectory?.trim() || process.env.COMPOSIO_RUN_OUTPUT_DIR?.trim(),
203 + });
204
239 - return {
240 - successful: true,
241 - error: null,
242 - logId: '',
243 - storedInFile: true,
244 - tokenCount: getExecuteOutputEncoder().encode(json).length,
245 - outputFilePath,
246 - };
247 -};
205 + return {
206 + successful: true,
207 + error: null,
208 + logId: '',
209 + storedInFile: true,
210 + tokenCount: getExecuteOutputEncoder().encode(json).length,
211 + outputFilePath,
212 + } satisfies StoredExecuteOutputSummary;
213 + });
214
215 const perfDebugEpoch = Date.now();
216 const perfDebugLog = (label: string, details: Record<string, unknown> = {}) => {
217 if (!isPerfDebugEnabled()) return;
252 - console.error(
218 + process.stderr.write(
219 `[perf] ${JSON.stringify({
220 phase: 'event',
221 label,
222 elapsedMs: Date.now() - perfDebugEpoch,
223 ...details,
258 - })}`
224 + })}\n`
225 );
226 };
227 const toolDebugLog = (label: string, details: Record<string, unknown> = {}) => {
228 if (!isToolDebugEnabled()) return;
263 - console.error(`[tool-debug] ${JSON.stringify({ label, ...details })}`);
229 + process.stderr.write(`[tool-debug] ${JSON.stringify({ label, ...details })}\n`);
230 };
231
266 -const prepareExecuteOutput = (result: ToolExecuteResponse) => {
267 - const json = serializeExecuteOutput(result);
268 - const tokenCount = getExecuteOutputEncoder().encode(json).length;
269 - if (tokenCount <= EXECUTE_INLINE_OUTPUT_TOKEN_THRESHOLD) {
270 - return {
271 - kind: 'inline' as const,
272 - json,
273 - };
274 - }
275 -
276 - return {
277 - kind: 'file' as const,
278 - summary: {
279 - ...persistLargeExecuteOutput(json),
280 - logId: result.logId,
281 - } satisfies StoredExecuteOutputSummary,
282 - };
283 -};
284 -
285 -const normalizeError = (error: unknown): unknown => {
286 - let current: unknown = error;
287 - const seen = new Set<unknown>();
288 -
289 - while (current && typeof current === 'object' && !seen.has(current)) {
290 - seen.add(current);
291 -
292 - if (current instanceof Error) {
293 - return current;
294 - }
295 -
296 - if ('error' in current) {
297 - current = (current as { error?: unknown }).error;
298 - continue;
299 - }
300 - if ('cause' in current) {
301 - current = (current as { cause?: unknown }).cause;
302 - continue;
232 +const prepareExecuteOutput = (
233 + toolSlug: string,
234 + result: ToolExecuteResponse,
235 + sharedDirectory?: string
236 +) =>
237 + Effect.gen(function* () {
238 + const json = serializeExecuteOutput(result);
239 + const tokenCount = getExecuteOutputEncoder().encode(json).length;
240 + if (tokenCount <= EXECUTE_INLINE_OUTPUT_TOKEN_THRESHOLD) {
241 + return {
242 + kind: 'inline' as const,
243 + json,
244 + };
245 }
304 - break;
305 - }
246
307 - return current;
308 -};
247 + return {
248 + kind: 'file' as const,
249 + summary: {
250 + ...(yield* persistLargeExecuteOutput(toolSlug, json, sharedDirectory)),
251 + logId: result.logId,
252 + } satisfies StoredExecuteOutputSummary,
253 + };
254 + });
255
256 export const showToolsExecuteInputHelp = (toolSlug: string) =>
257 Effect.gen(function* () {
@@ -356,7 +302,8 @@ const handleExecutionError = (
302 context: { toolSlug: string; surface: 'root' | 'manage' | 'dev' }
303 ) =>
304 Effect.gen(function* () {
359 - const normalized = normalizeError(error);
305 + const mapped = mapComposioError({ error, toolSlug: context.toolSlug });
306 + const normalized = mapped.normalized;
307 if (normalized instanceof ToolInputValidationError) {
308 yield* ui.log.error(`Input validation failed for ${context.toolSlug}`);
309 yield* ui.note(
@@ -368,48 +315,25 @@ const handleExecutionError = (
315 return { error: normalized.message, slug: context.toolSlug };
316 }
317
371 - const connAccountDetails =
372 - normalized instanceof ActionExecuteConnectedAccountNotFoundError
373 - ? normalized.details
374 - : undefined;
375 -
376 - const apiDetails =
377 - extractApiErrorDetails(error) ??
378 - extractApiErrorDetails(normalized) ??
379 - extractApiErrorDetails(connAccountDetails);
380 - const slugValue = apiDetails?.slug ?? extractSlug(error) ?? extractSlug(connAccountDetails);
381 - const noActiveConnection =
382 - normalized instanceof ActionExecuteConnectedAccountNotFoundError ||
383 - isNoActiveConnectionError(apiDetails);
384 - const message = extractMessage(apiDetails) ?? extractMessage(normalized) ?? 'Unknown error';
385 -
386 - if (noActiveConnection) {
387 - const rewrittenMessage = noActiveConnectionMessage(context.toolSlug);
388 - yield* ui.log.error(rewrittenMessage);
318 + const apiDetails = mapped.apiDetails;
319 + const slugValue = mapped.slugValue;
320 +
321 + if (normalized instanceof ComposioNoActiveConnectionError) {
322 + yield* ui.log.error(mapped.message);
323 if (toolkitFromToolSlug(context.toolSlug)) {
324 yield* ui.note(connectionTips(context.toolSlug, context.surface), 'Tips');
325 }
392 - return { error: rewrittenMessage, slug: slugValue ?? context.toolSlug };
326 + return { error: mapped.message, slug: slugValue ?? context.toolSlug };
327 }
328
395 - yield* ui.log.error(message);
329 + yield* ui.log.error(mapped.message);
330
397 - const detailsObject =
398 - apiDetails ??
399 - (normalized instanceof ActionExecuteConnectedAccountNotFoundError &&
400 - normalized.details &&
401 - typeof normalized.details === 'object'
402 - ? (normalized.details as object)
403 - : undefined);
331 + const detailsObject = apiDetails;
332 if (detailsObject) {
333 yield* ui.note(formatUnknownObject(redactRequestId(detailsObject)), 'Error details');
334 }
335
408 - if (normalized instanceof ActionExecuteConnectedAccountNotFoundError) {
409 - yield* ui.note(connectionTips(context.toolSlug, context.surface), 'Tips');
410 - }
411 -
412 - return { error: message, slug: slugValue };
336 + return { error: mapped.message, slug: slugValue };
337 });
338
339 class ToolExecutionError {
@@ -592,6 +516,7 @@ type ResolvedExecuteContext = {
516 readonly args: Record<string, unknown>;
517 readonly resolvedUserId: string;
518 readonly executeParams: ToolExecuteParams;
519 + readonly executeOutputDir?: string;
520 };
521
522 const emitCachedSchema = (
@@ -634,7 +559,7 @@ const resolveExecuteContext = (params: RunToolsExecuteParams) =>
559 const userContext = yield* ComposioUserContext;
560 const projectContext = yield* ProjectContext;
561
637 - const input = yield* resolveInput(params.data);
562 + const input = (yield* resolveInput(params.data)) ?? '{}';
563 const args = yield* parseArguments(input);
564 const localProjectContext = yield* projectContext.resolve.pipe(
565 Effect.catchAll(() => Effect.succeed(Option.none()))
@@ -662,6 +587,15 @@ const resolveExecuteContext = (params: RunToolsExecuteParams) =>
587 orgId: resolvedProject.orgId,
588 projectId: resolvedProject.projectId,
589 });
590 + const executeOutputDir =
591 + process.env.COMPOSIO_RUN_OUTPUT_DIR?.trim() ||
592 + Option.getOrUndefined(
593 + yield* resolveCliSessionArtifacts({
594 + orgId: resolvedProject.projectType === 'CONSUMER' ? resolvedProject.orgId : undefined,
595 + consumerUserId:
596 + resolvedProject.projectType === 'CONSUMER' ? resolvedProject.consumerUserId : undefined,
597 + }).pipe(Effect.map(Option.map(artifacts => artifacts.directoryPath)))
598 + );
599
600 return {
601 ui,
@@ -669,6 +603,7 @@ const resolveExecuteContext = (params: RunToolsExecuteParams) =>
603 resolvedProject,
604 args,
605 resolvedUserId: resolvedUserId.value,
606 + executeOutputDir,
607 executeParams: {
608 userId: resolvedUserId.value,
609 arguments: args,
@@ -784,6 +719,7 @@ const runExecuteWithSpinner = (params: {
719 readonly args: Record<string, unknown>;
720 readonly resolvedUserId: string;
721 readonly executeParams: ToolExecuteParams;
722 + readonly executeOutputDir?: string;
723 readonly skipToolParamsCheck: boolean;
724 readonly noVerify: boolean;
725 }) =>
@@ -843,6 +779,22 @@ const runExecuteWithSpinner = (params: {
779 : 'No tool was executed. Arguments were validated locally only.'
780 );
781 yield* params.ui.output(JSON.stringify(summary, ciRedactReplacer, 2));
782 + yield* appendCliSessionHistory({
783 + orgId:
784 + params.resolvedProject.projectType === 'CONSUMER'
785 + ? params.resolvedProject.orgId
786 + : undefined,
787 + consumerUserId:
788 + params.resolvedProject.projectType === 'CONSUMER'
789 + ? params.resolvedProject.consumerUserId
790 + : undefined,
791 + entry: {
792 + command: 'execute',
793 + status: 'dry-run',
794 + slug: params.slug,
795 + arguments: params.args,
796 + },
797 + }).pipe(Effect.catchAll(() => Effect.void));
798 return;
799 }
800
@@ -872,6 +824,23 @@ const runExecuteWithSpinner = (params: {
824 yield* params.ui.output(
825 JSON.stringify({ successful: false, ...summary }, ciRedactReplacer, 2)
826 );
827 + yield* appendCliSessionHistory({
828 + orgId:
829 + params.resolvedProject.projectType === 'CONSUMER'
830 + ? params.resolvedProject.orgId
831 + : undefined,
832 + consumerUserId:
833 + params.resolvedProject.projectType === 'CONSUMER'
834 + ? params.resolvedProject.consumerUserId
835 + : undefined,
836 + entry: {
837 + command: 'execute',
838 + status: 'error',
839 + slug: params.slug,
840 + arguments: params.args,
841 + error: summary.error,
842 + },
843 + }).pipe(Effect.catchAll(() => Effect.void));
844 return yield* Effect.fail(new ToolExecutionError(summary.error));
845 }
846
@@ -906,17 +875,55 @@ const runExecuteWithSpinner = (params: {
875 ? ` (logId: ${redact({ value: result.logId, prefix: 'log_' })})`
876 : '';
877 yield* spinner.stop(`Execution successful${logId}`);
909 - const output = prepareExecuteOutput(result);
878 + const output = yield* prepareExecuteOutput(params.slug, result, params.executeOutputDir);
879 if (output.kind === 'file') {
880 yield* params.ui.log.message(
881 `Response stored in ${output.summary.outputFilePath} (${output.summary.tokenCount} tokens)`
882 );
883 yield* params.ui.output(JSON.stringify(output.summary, ciRedactReplacer, 2));
884 + yield* appendCliSessionHistory({
885 + orgId:
886 + params.resolvedProject.projectType === 'CONSUMER'
887 + ? params.resolvedProject.orgId
888 + : undefined,
889 + consumerUserId:
890 + params.resolvedProject.projectType === 'CONSUMER'
891 + ? params.resolvedProject.consumerUserId
892 + : undefined,
893 + entry: {
894 + command: 'execute',
895 + status: 'success',
896 + slug: params.slug,
897 + arguments: params.args,
898 + storedInFile: true,
899 + outputFilePath: output.summary.outputFilePath,
900 + tokenCount: output.summary.tokenCount,
901 + logId: result.logId,
902 + },
903 + }).pipe(Effect.catchAll(() => Effect.void));
904 return;
905 }
906
907 yield* params.ui.log.message(`Response\n${output.json}`);
908 yield* params.ui.output(output.json);
909 + yield* appendCliSessionHistory({
910 + orgId:
911 + params.resolvedProject.projectType === 'CONSUMER'
912 + ? params.resolvedProject.orgId
913 + : undefined,
914 + consumerUserId:
915 + params.resolvedProject.projectType === 'CONSUMER'
916 + ? params.resolvedProject.consumerUserId
917 + : undefined,
918 + entry: {
919 + command: 'execute',
920 + status: 'success',
921 + slug: params.slug,
922 + arguments: params.args,
923 + storedInFile: false,
924 + logId: result.logId,
925 + },
926 + }).pipe(Effect.catchAll(() => Effect.void));
927 })
928 );
929 });
@@ -1011,24 +1018,23 @@ export const toolsCmd$Execute = Command.make(
1018 ).pipe(
1019 Command.withDescription(
1020 [
1014 - 'Execute a tool by slug with JSON arguments, or preview it locally with --dry-run.',
1015 - 'Arguments are validated against cached tool schemas in `~/.composio/tool_definitions/` when available.',
1016 - 'Use `--get-schema` to fetch the latest raw input schema into the cache and print it without executing the tool.',
1017 - 'Use `composio tools info <slug>` for the same schema plus a short human summary and jq hints.',
1018 - 'Successful execute responses are parsed immediately, and failed calls validate inputs against cached schemas when available, so it is often fastest to just try the real call first before inspecting schema.',
1021 + 'Execute a tool by slug. Validates inputs against cached schemas and checks connections',
1022 + 'automatically — just try it and it will tell you what to fix.',
1023 '',
1024 'Examples:',
1025 ' composio execute GMAIL_SEND_EMAIL -d \'{ recipient_email: "a@b.com", body: "Hello" }\'',
1022 - ' composio execute GMAIL_SEND_EMAIL --skip-connection-check -d \'{ recipient_email: "a@b.com", body: "Hello" }\'',
1023 - ' composio execute GMAIL_SEND_EMAIL --skip-tool-params-check -d \'{ recipient_email: "a@b.com", body: "Hello" }\'',
1024 - ' composio execute GMAIL_SEND_EMAIL --no-verify -d \'{ recipient_email: "a@b.com", body: "Hello" }\'',
1025 - ' composio execute GMAIL_SEND_EMAIL --dry-run -d \'{ recipient_email: "a@b.com", body: "Hello" }\'',
1026 - ' composio execute GMAIL_SEND_EMAIL --get-schema',
1026 + " composio execute GMAIL_SEND_EMAIL --dry-run -d '{ ... }' Preview without executing",
1027 + ' composio execute GMAIL_SEND_EMAIL --get-schema Fetch and print the input schema',
1028 + '',
1029 + 'Flags:',
1030 + ' --skip-connection-check Skip the linked-account check',
1031 + ' --skip-tool-params-check Skip input validation against cached schema',
1032 + ' --no-verify Skip both checks above',
1033 '',
1028 - 'Related:',
1029 - ' composio run \'const first = await execute("TOOL_SLUG", { ... }); const second = await execute("OTHER_TOOL", { ... }); console.log({ first, second })\'',
1030 - ' composio search "<query>"',
1031 - ' composio link <toolkit>',
1034 + 'See also:',
1035 + ' composio search "<query>" Find tool slugs by use case',
1036 + ' composio tools info <slug> Schema summary with jq hints',
1037 + ' composio link <toolkit> Connect an account for a toolkit',
1038 ].join('\n')
1039 )
1040 );
@@ -1053,24 +1059,23 @@ export const rootToolsCmd$Execute = Command.make(
1059 ).pipe(
1060 Command.withDescription(
1061 [
1056 - 'Execute a tool by slug with JSON arguments, or preview it locally with --dry-run.',
1057 - 'Arguments are validated against cached tool schemas in `~/.composio/tool_definitions/` when available.',
1058 - 'Use `--get-schema` to fetch the latest raw input schema into the cache and print it without executing the tool.',
1059 - 'Use `composio tools info <slug>` for the same schema plus a short human summary and jq hints.',
1060 - 'Successful execute responses are parsed immediately, and failed calls validate inputs against cached schemas when available, so it is often fastest to just try the real call first before inspecting schema.',
1062 + 'Execute a tool by slug. Validates inputs against cached schemas and checks connections',
1063 + 'automatically — just try it and it will tell you what to fix.',
1064 '',
1065 'Examples:',
1066 ' composio execute GMAIL_SEND_EMAIL -d \'{ recipient_email: "a@b.com", body: "Hello" }\'',
1064 - ' composio execute GMAIL_SEND_EMAIL --skip-connection-check -d \'{ recipient_email: "a@b.com", body: "Hello" }\'',
1065 - ' composio execute GMAIL_SEND_EMAIL --skip-tool-params-check -d \'{ recipient_email: "a@b.com", body: "Hello" }\'',
1066 - ' composio execute GMAIL_SEND_EMAIL --no-verify -d \'{ recipient_email: "a@b.com", body: "Hello" }\'',
1067 - ' composio execute GMAIL_SEND_EMAIL --dry-run -d \'{ recipient_email: "a@b.com", body: "Hello" }\'',
1068 - ' composio execute GMAIL_SEND_EMAIL --get-schema',
1067 + " composio execute GMAIL_SEND_EMAIL --dry-run -d '{ ... }' Preview without executing",
1068 + ' composio execute GMAIL_SEND_EMAIL --get-schema Fetch and print the input schema',
1069 + '',
1070 + 'Flags:',
1071 + ' --skip-connection-check Skip the linked-account check',
1072 + ' --skip-tool-params-check Skip input validation against cached schema',
1073 + ' --no-verify Skip both checks above',
1074 '',
1070 - 'Related:',
1071 - ' composio run \'const first = await execute("TOOL_SLUG", { ... }); const second = await execute("OTHER_TOOL", { ... }); console.log({ first, second })\'',
1072 - ' composio search "<query>"',
1073 - ' composio link <toolkit>',
1075 + 'See also:',
1076 + ' composio search "<query>" Find tool slugs by use case',
1077 + ' composio tools info <slug> Schema summary with jq hints',
1078 + ' composio link <toolkit> Connect an account for a toolkit',
1079 ].join('\n')
1080 )
1081 );
ts/packages/cli/src/commands/tools/commands/tools.search.cmd.ts
+48 -12
@@ -15,6 +15,7 @@ import {
15 } from 'src/services/command-project';
16 import { commandHintExample, commandHintStep } from 'src/services/command-hints';
17 import { primeConsumerConnectedToolkitsCacheInBackground } from 'src/services/consumer-short-term-cache';
18 +import { appendCliSessionHistory } from 'src/services/cli-session-artifacts';
19
20 const query = Args.text({ name: 'query' }).pipe(
21 Args.withDescription(
@@ -66,7 +67,7 @@ const runToolsSearch = (params: {
67 .filter(Boolean)
68 : undefined;
69
69 - const searchResponse = yield* ui.withSpinner(
70 + const searchResult = yield* ui.withSpinner(
71 `Searching tools for "${params.query}"...`,
72 Effect.gen(function* () {
73 const resolvedProject = yield* resolveCommandProject({
@@ -101,13 +102,25 @@ const runToolsSearch = (params: {
102 const { sessionId } = yield* resolveToolRouterSession(client, resolvedUserId.value, {
103 toolkits: toolkitList,
104 });
104 - return yield* Effect.tryPromise(() =>
105 + const searchResponse = yield* Effect.tryPromise(() =>
106 client.toolRouter.session.search(sessionId, {
107 queries: [{ use_case: params.query }],
108 })
109 );
110 + return {
111 + searchResponse,
112 + historyScope:
113 + resolvedProject.projectType === 'CONSUMER'
114 + ? {
115 + orgId: resolvedProject.orgId,
116 + consumerUserId: resolvedUserId.value,
117 + toolRouterSessionId: sessionId,
118 + }
119 + : undefined,
120 + };
121 })
122 );
123 + const searchResponse = searchResult.searchResponse;
124
125 const toolkitSet = toolkitList && toolkitList.length > 0 ? new Set(toolkitList) : undefined;
126
@@ -228,6 +241,19 @@ const runToolsSearch = (params: {
241 ...searchResponse,
242 CTA: cta,
243 };
244 + yield* appendCliSessionHistory({
245 + orgId: searchResult.historyScope?.orgId,
246 + consumerUserId: searchResult.historyScope?.consumerUserId,
247 + entry: {
248 + command: 'search',
249 + query: params.query,
250 + toolkitFilter: toolkitList ?? [],
251 + limit: clampedLimit,
252 + resultCount: toolsList.length,
253 + toolRouterSessionId: searchResult.historyScope?.toolRouterSessionId,
254 + nextSteps: searchResponse.next_steps_guidance,
255 + },
256 + }).pipe(Effect.catchAll(() => Effect.void));
257 yield* ui.output(JSON.stringify(outputForJq, null, 2));
258 });
259
@@ -239,12 +265,17 @@ export const toolsCmd$Search = Command.make(
265 ).pipe(
266 Command.withDescription(
267 [
242 - 'Semantically search tools by use case; returns best-fit tools plus recommended usage guidance.',
268 + 'Find tools by use case. Returns matching tools with slugs you can pass directly to `execute`.',
269 '',
244 - 'Related:',
245 - ' composio run \'const result = await execute("TOOL_SLUG", { ... }); console.log(result)\'',
246 - ' composio link <toolkit>',
247 - " composio execute <slug> -d '{}'",
270 + 'Examples:',
271 + ' composio search "send an email"',
272 + ' composio search "create issue" --toolkits github',
273 + ' composio search "list calendar events" --limit 5',
274 + '',
275 + 'Next steps:',
276 + " composio execute <slug> -d '{ ... }' Run a tool from the results",
277 + " composio tools info <slug> Inspect a tool's schema before executing",
278 + ' composio link <toolkit> Connect an account if execute tells you to',
279 ].join('\n')
280 )
281 );
@@ -264,12 +295,17 @@ export const rootToolsCmd$Search = Command.make(
295 ).pipe(
296 Command.withDescription(
297 [
267 - 'Semantically search tools by use case; returns best-fit tools plus recommended usage guidance.',
298 + 'Find tools by use case. Returns matching tools with slugs you can pass directly to `execute`.',
299 + '',
300 + 'Examples:',
301 + ' composio search "send an email"',
302 + ' composio search "create issue" --toolkits github',
303 + ' composio search "list calendar events" --limit 5',
304 '',
269 - 'Related:',
270 - ' composio run \'const result = await execute("TOOL_SLUG", { ... }); console.log(result)\'',
271 - ' composio link <toolkit>',
272 - " composio execute <slug> -d '{}'",
305 + 'Next steps:',
306 + " composio execute <slug> -d '{ ... }' Run a tool from the results",
307 + " composio tools info <slug> Inspect a tool's schema before executing",
308 + ' composio link <toolkit> Connect an account if execute tells you to',
309 ].join('\n')
310 )
311 );
ts/packages/cli/src/effects/resolve-optional-text-input.ts new
+38
@@ -0,0 +1,38 @@
1 +import { FileSystem } from '@effect/platform';
2 +import { Effect, Option } from 'effect';
3 +
4 +import { readStdin, readStdinIfPiped } from 'src/effects/read-stdin';
5 +
6 +type ResolveOptionalTextInputOptions = {
7 + readonly missingValue?: string;
8 +};
9 +
10 +export const resolveOptionalTextInput = (
11 + input: Option.Option<string>,
12 + options: ResolveOptionalTextInputOptions = {}
13 +) =>
14 + Effect.gen(function* () {
15 + const fs = yield* FileSystem.FileSystem;
16 +
17 + if (Option.isSome(input)) {
18 + const value = input.value.trim();
19 + if (value === '-') {
20 + return yield* readStdin;
21 + }
22 + if (value.startsWith('@')) {
23 + const filePath = value.slice(1).trim();
24 + if (!filePath) {
25 + return yield* Effect.fail(new Error('Missing file path after "@" in --data'));
26 + }
27 + return yield* fs.readFileString(filePath, 'utf-8');
28 + }
29 + return value;
30 + }
31 +
32 + const piped = yield* readStdinIfPiped;
33 + if (Option.isSome(piped)) {
34 + return piped.value;
35 + }
36 +
37 + return options.missingValue;
38 + });
ts/packages/cli/src/services/cli-session-artifacts.ts new
+88
@@ -0,0 +1,88 @@
1 +import fs from 'node:fs';
2 +import path from 'node:path';
3 +import { Effect, Option } from 'effect';
4 +import { getOrCreateProbablyMyCliSessionIdForCurrentCwd } from 'src/services/consumer-short-term-cache';
5 +
6 +const CLI_SESSION_ARTIFACTS_ROOT = '/tmp/composio';
7 +const SESSION_HISTORY_FILE = 'session-history.jsonl';
8 +
9 +export type CliSessionArtifacts = {
10 + readonly sessionId: string;
11 + readonly directoryPath: string;
12 + readonly historyFilePath: string;
13 +};
14 +
15 +const randomToken = (length = 8) => crypto.randomUUID().replace(/-/g, '').slice(0, length);
16 +
17 +const sanitizeArtifactName = (value: string): string =>
18 + value.replace(/[^A-Z0-9_]+/gi, '_').replace(/^_+|_+$/g, '') || 'ARTIFACT';
19 +
20 +export const resolveCliSessionArtifacts = (params?: {
21 + readonly orgId?: string;
22 + readonly consumerUserId?: string;
23 +}) =>
24 + Effect.gen(function* () {
25 + const sessionIdOption = yield* getOrCreateProbablyMyCliSessionIdForCurrentCwd(params);
26 + if (Option.isNone(sessionIdOption)) {
27 + return Option.none<CliSessionArtifacts>();
28 + }
29 +
30 + const directoryPath = path.join(CLI_SESSION_ARTIFACTS_ROOT, sessionIdOption.value);
31 + fs.mkdirSync(directoryPath, { recursive: true });
32 + return Option.some({
33 + sessionId: sessionIdOption.value,
34 + directoryPath,
35 + historyFilePath: path.join(directoryPath, SESSION_HISTORY_FILE),
36 + } satisfies CliSessionArtifacts);
37 + });
38 +
39 +export const appendCliSessionHistory = (params: {
40 + readonly entry: Record<string, unknown>;
41 + readonly orgId?: string;
42 + readonly consumerUserId?: string;
43 +}) =>
44 + Effect.gen(function* () {
45 + const artifactsOption = yield* resolveCliSessionArtifacts({
46 + orgId: params.orgId,
47 + consumerUserId: params.consumerUserId,
48 + });
49 + if (Option.isNone(artifactsOption)) {
50 + return;
51 + }
52 +
53 + const line = JSON.stringify({
54 + timestamp: new Date().toISOString(),
55 + sessionId: artifactsOption.value.sessionId,
56 + ...params.entry,
57 + });
58 + fs.appendFileSync(artifactsOption.value.historyFilePath, `${line}\n`, 'utf8');
59 + });
60 +
61 +export const storeCliSessionArtifact = (params: {
62 + readonly contents: string;
63 + readonly name: string;
64 + readonly extension?: string;
65 + readonly directoryPath?: string;
66 + readonly orgId?: string;
67 + readonly consumerUserId?: string;
68 +}) =>
69 + Effect.gen(function* () {
70 + const directoryPath =
71 + params.directoryPath ||
72 + Option.getOrUndefined(
73 + yield* resolveCliSessionArtifacts({
74 + orgId: params.orgId,
75 + consumerUserId: params.consumerUserId,
76 + }).pipe(Effect.map(Option.map(artifacts => artifacts.directoryPath)))
77 + ) ||
78 + path.join(CLI_SESSION_ARTIFACTS_ROOT, `adhoc_${randomToken(12)}`);
79 +
80 + fs.mkdirSync(directoryPath, { recursive: true });
81 + const extension = (params.extension ?? 'json').replace(/^\.+/, '') || 'json';
82 + const filePath = path.join(
83 + directoryPath,
84 + `${sanitizeArtifactName(params.name)}_${randomToken()}.${extension}`
85 + );
86 + fs.writeFileSync(filePath, params.contents, 'utf8');
87 + return filePath;
88 + });
ts/packages/cli/src/services/composio-error-overrides.ts new
+185
@@ -0,0 +1,185 @@
1 +import {
2 + extractApiErrorDetails,
3 + extractMessage,
4 + extractSlug,
5 + type ApiErrorDetails,
6 +} from 'src/utils/api-error-extraction';
7 +
8 +const NO_CONNECTION_SLUGS: ReadonlySet<string> = new Set([
9 + 'ActionExecute_ConnectedAccountNotFound',
10 + 'ToolRouterV2_NoActiveConnection',
11 +]);
12 +
13 +const extractNestedDetails = (value: unknown): unknown => {
14 + let current: unknown = value;
15 + const seen = new Set<unknown>();
16 +
17 + while (current && typeof current === 'object' && !seen.has(current)) {
18 + seen.add(current);
19 +
20 + if ('details' in current) {
21 + const details = (current as { details?: unknown }).details;
22 + if (details !== undefined) {
23 + return details;
24 + }
25 + }
26 +
27 + if ('error' in current) {
28 + current = (current as { error?: unknown }).error;
29 + continue;
30 + }
31 + if ('cause' in current) {
32 + current = (current as { cause?: unknown }).cause;
33 + continue;
34 + }
35 + break;
36 + }
37 +
38 + return undefined;
39 +};
40 +
41 +export const normalizeCliError = (error: unknown): unknown => {
42 + let current: unknown = error;
43 + const seen = new Set<unknown>();
44 +
45 + while (current && typeof current === 'object' && !seen.has(current)) {
46 + seen.add(current);
47 +
48 + if (current instanceof Error) {
49 + return current;
50 + }
51 +
52 + if ('error' in current) {
53 + current = (current as { error?: unknown }).error;
54 + continue;
55 + }
56 + if ('cause' in current) {
57 + current = (current as { cause?: unknown }).cause;
58 + continue;
59 + }
60 + break;
61 + }
62 +
63 + return current;
64 +};
65 +
66 +export const isNoConnectionSlug = (slug: string | undefined | null): boolean =>
67 + slug != null && NO_CONNECTION_SLUGS.has(slug);
68 +
69 +export const isNoActiveConnectionApiError = (
70 + details: { code?: number; slug?: string } | undefined
71 +): boolean => details?.code === 4302 || isNoConnectionSlug(details?.slug);
72 +
73 +export const buildNoActiveConnectionMessage = (params: {
74 + readonly toolkit?: string;
75 + readonly toolSlug?: string;
76 +}) => {
77 + if (params.toolkit) {
78 + return `No active connection found for toolkit "${params.toolkit}". Run \`composio link ${params.toolkit}\`, then retry.`;
79 + }
80 + if (params.toolSlug) {
81 + const idx = params.toolSlug.indexOf('_');
82 + const toolkit =
83 + idx <= 0 ? params.toolSlug.toLowerCase() : params.toolSlug.slice(0, idx).toLowerCase();
84 + if (toolkit !== 'composio') {
85 + return `No active connection found for toolkit "${toolkit}". Run \`composio link ${toolkit}\`, then retry.`;
86 + }
87 + }
88 + return 'No active connection found for this tool call. Link the required toolkit/app, then retry.';
89 +};
90 +
91 +export class ComposioNoActiveConnectionError extends Error {
92 + readonly details: unknown;
93 + readonly apiDetails?: ApiErrorDetails;
94 + readonly toolkit?: string;
95 + readonly toolSlug?: string;
96 +
97 + constructor(params: {
98 + readonly details: unknown;
99 + readonly apiDetails?: ApiErrorDetails;
100 + readonly toolkit?: string;
101 + readonly toolSlug?: string;
102 + }) {
103 + super(
104 + buildNoActiveConnectionMessage({
105 + toolkit: params.toolkit,
106 + toolSlug: params.toolSlug,
107 + })
108 + );
109 + this.name = 'ComposioNoActiveConnectionError';
110 + this.details = params.details;
111 + this.apiDetails = params.apiDetails;
112 + this.toolkit = params.toolkit;
113 + this.toolSlug = params.toolSlug;
114 + }
115 +}
116 +
117 +export const mapComposioError = (params: {
118 + readonly error: unknown;
119 + readonly toolkit?: string;
120 + readonly toolSlug?: string;
121 +}) => {
122 + const normalized = normalizeCliError(params.error);
123 + const nestedDetails = extractNestedDetails(params.error) ?? extractNestedDetails(normalized);
124 + const apiDetails =
125 + extractApiErrorDetails(params.error) ??
126 + extractApiErrorDetails(nestedDetails) ??
127 + extractApiErrorDetails(normalized) ??
128 + (normalized instanceof ComposioNoActiveConnectionError ? normalized.apiDetails : undefined);
129 + const slugValue =
130 + apiDetails?.slug ??
131 + extractSlug(nestedDetails) ??
132 + extractSlug(params.error) ??
133 + extractSlug(normalized) ??
134 + (normalized instanceof ComposioNoActiveConnectionError
135 + ? normalized.apiDetails?.slug
136 + : undefined);
137 +
138 + if (
139 + normalized instanceof ComposioNoActiveConnectionError ||
140 + isNoActiveConnectionApiError(apiDetails) ||
141 + isNoConnectionSlug(slugValue)
142 + ) {
143 + const mapped =
144 + normalized instanceof ComposioNoActiveConnectionError
145 + ? normalized
146 + : new ComposioNoActiveConnectionError({
147 + details: apiDetails ?? params.error,
148 + apiDetails,
149 + toolkit: params.toolkit,
150 + toolSlug: params.toolSlug,
151 + });
152 +
153 + return {
154 + normalized: mapped,
155 + apiDetails,
156 + slugValue,
157 + message: mapped.message,
158 + override: {
159 + kind: 'no_active_connection' as const,
160 + error: mapped,
161 + },
162 + };
163 + }
164 +
165 + return {
166 + normalized,
167 + apiDetails,
168 + slugValue,
169 + message:
170 + extractMessage(apiDetails) ??
171 + extractMessage(nestedDetails) ??
172 + extractMessage(normalized) ??
173 + 'Unknown error',
174 + override: null,
175 + };
176 +};
177 +
178 +export const mapOnlyComposioOverrideError = (params: {
179 + readonly error: unknown;
180 + readonly toolkit?: string;
181 + readonly toolSlug?: string;
182 +}): unknown => {
183 + const mapped = mapComposioError(params);
184 + return mapped.override ? mapped.normalized : params.error;
185 +};
ts/packages/cli/src/services/consumer-short-term-cache.ts
+38 -2
@@ -11,8 +11,8 @@ import { resolveCommandProject } from 'src/services/command-project';
11 import { ComposioUserContext } from 'src/services/user-context';
12
13 const CACHE_FILE = 'consumer-short-term-cache.json';
14 -const CACHE_TTL_MS = 5 * 60 * 1000;
15 -const SEARCH_SESSION_EXTENSION_MS = 2 * 60 * 1000;
14 +const CACHE_TTL_MS = 15 * 60 * 1000;
15 +const SEARCH_SESSION_EXTENSION_MS = 5 * 60 * 1000;
16
17 type CacheEntry = {
18 readonly toolkits: ReadonlyArray<string>;
@@ -220,3 +220,39 @@ export const primeConsumerConnectedToolkitsCacheInBackground = (params?: {
220 Effect.forkDaemon,
221 Effect.asVoid
222 );
223 +
224 +export const getOrCreateProbablyMyCliSessionIdForCurrentCwd = (params?: {
225 + readonly orgId?: string;
226 + readonly consumerUserId?: string;
227 +}) =>
228 + Effect.gen(function* () {
229 + const scope = yield* resolveConsumerScope(params);
230 + if (!scope?.consumerUserId) {
231 + return Option.none<string>();
232 + }
233 +
234 + const proc = yield* NodeProcess;
235 + const state = yield* readCache();
236 + const key = cacheKey(scope.orgId, scope.consumerUserId);
237 + const currentEntry = state[key];
238 + const searchSessionFields = resolveSearchSessionMetadata({
239 + currentEntry,
240 + cwd: proc.cwd,
241 + });
242 + const currentCwdHash = cwdHash(proc.cwd);
243 + const session = searchSessionFields.probablyMyCliSessionsByCwdHash[currentCwdHash];
244 + if (!session) {
245 + return Option.none<string>();
246 + }
247 +
248 + yield* writeCache({
249 + ...state,
250 + [key]: {
251 + toolkits: currentEntry?.toolkits ?? [],
252 + expiresAt: currentEntry?.expiresAt ?? new Date(Date.now() + CACHE_TTL_MS).toISOString(),
253 + ...searchSessionFields,
254 + },
255 + });
256 +
257 + return Option.some(session.id);
258 + });
ts/packages/cli/src/services/master-detector.ts new
+14
@@ -0,0 +1,14 @@
1 +export type MasterKind = 'claude' | 'codex' | 'user';
2 +
3 +const hasEnvPrefix = (env: NodeJS.ProcessEnv, prefix: string): boolean =>
4 + Object.keys(env).some(key => key.startsWith(prefix));
5 +
6 +export const detectMaster = (env: NodeJS.ProcessEnv = process.env): MasterKind => {
7 + if (hasEnvPrefix(env, 'CODEX_')) {
8 + return 'codex';
9 + }
10 + if (hasEnvPrefix(env, 'CLAUDE_')) {
11 + return 'claude';
12 + }
13 + return 'user';
14 +};
ts/packages/cli/src/services/tools-executor.ts
+6 -30
@@ -8,30 +8,9 @@ import type {
8 import { ComposioClientSingleton } from 'src/services/composio-clients';
9 import { createToolRouterSession } from 'src/effects/create-tool-router-session';
10 import {
11 - extractMessage,
12 - extractSlug,
13 - extractApiErrorDetails,
14 -} from 'src/utils/api-error-extraction';
15 -
16 -/** Error slugs that indicate a missing connected account / no active connection. */
17 -const NO_CONNECTION_SLUGS: ReadonlySet<string> = new Set([
18 - 'ActionExecute_ConnectedAccountNotFound',
19 - 'ToolRouterV2_NoActiveConnection',
20 -]);
21 -
22 -export const isNoConnectionSlug = (slug: string | undefined | null): boolean =>
23 - slug != null && NO_CONNECTION_SLUGS.has(slug);
24 -
25 -export class ActionExecuteConnectedAccountNotFoundError extends Error {
26 - readonly details: unknown;
27 -
28 - constructor(details: unknown) {
29 - const message = extractMessage(details) ?? 'No connected account found for this user/toolkit.';
30 - super(message);
31 - this.name = 'ActionExecuteConnectedAccountNotFoundError';
32 - this.details = details;
33 - }
34 -}
11 + ComposioNoActiveConnectionError,
12 + mapComposioError,
13 +} from 'src/services/composio-error-overrides';
14
15 /**
16 * Parameters accepted by the Tool Router-based executor.
@@ -133,12 +112,9 @@ export const ToolsExecutorLive = Layer.effect(
112 return normalizeResponse(raw);
113 }).pipe(
114 Effect.catchAll((error): Effect.Effect<never, unknown> => {
136 - const apiDetails = extractApiErrorDetails(error);
137 - const slugValue = apiDetails?.slug ?? extractSlug(error);
138 - if (isNoConnectionSlug(slugValue)) {
139 - return Effect.fail(
140 - new ActionExecuteConnectedAccountNotFoundError(apiDetails ?? error)
141 - );
115 + const mapped = mapComposioError({ error, toolSlug: slug });
116 + if (mapped.normalized instanceof ComposioNoActiveConnectionError) {
117 + return Effect.fail(mapped.normalized);
118 }
119 return Effect.fail(error);
120 })
ts/packages/cli/src/utils/parse-json-ish.ts new
+13
@@ -0,0 +1,13 @@
1 +import { parse as parseJsonWithComments } from 'comment-json';
2 +
3 +export const parseJsonIsh = (raw: string): unknown => {
4 + try {
5 + return JSON.parse(raw) as unknown;
6 + } catch {
7 + try {
8 + return parseJsonWithComments(raw, undefined, true) as unknown;
9 + } catch {
10 + return Function(`"use strict"; return (${raw});`)() as unknown;
11 + }
12 + }
13 +};
ts/packages/cli/test/__utils__/services/test-layer.ts
+20
@@ -51,10 +51,12 @@ import type {
51 SessionLinkResponse,
52 SessionSearchResponse,
53 SessionToolkitsResponse,
54 + SessionProxyExecuteResponse,
55 SessionCreateParams,
56 SessionExecuteParams,
57 SessionExecuteMetaParams,
58 SessionLinkParams,
59 + SessionProxyExecuteParams,
60 SessionSearchParams,
61 SessionToolkitsParams,
62 } from '@composio/client/resources/tool-router';
@@ -164,6 +166,11 @@ export interface TestLiveInput {
166 ) => Promise<SessionExecuteMetaResponse>;
167 /** Override `session.link`. Receives sessionId and params. */
168 link?: (sessionId: string, params: SessionLinkParams) => Promise<SessionLinkResponse>;
169 + /** Override `session.proxyExecute`. Receives sessionId and params. */
170 + proxyExecute?: (
171 + sessionId: string,
172 + params: SessionProxyExecuteParams
173 + ) => Promise<SessionProxyExecuteResponse>;
174 /** Override `session.search`. Receives sessionId and params. */
175 search?: (sessionId: string, params: SessionSearchParams) => Promise<SessionSearchResponse>;
176 /** Override `session.toolkits`. Receives sessionId and optional params. */
@@ -987,6 +994,19 @@ export const TestLayer = (input?: TestLiveInput) =>
994 link_token: 'lt_test_token',
995 redirect_url: 'https://app.composio.dev/link?token=lt_test_token',
996 })),
997 + proxyExecute:
998 + toolRouterOverrides?.proxyExecute ??
999 + (async (_sessionId: string, params: SessionProxyExecuteParams) => ({
1000 + status: 200,
1001 + data: {
1002 + toolkit_slug: params.toolkit_slug,
1003 + endpoint: params.endpoint,
1004 + method: params.method,
1005 + body: params.body ?? null,
1006 + parameters: params.parameters ?? [],
1007 + },
1008 + headers: {},
1009 + })),
1010 search: toolRouterOverrides?.search ?? defaultSearchHandler,
1011 toolkits: toolRouterOverrides?.toolkits ?? defaultToolkitsHandler,
1012 tools: async () => ({
ts/packages/cli/test/src/commands/$default.cmd.test.ts
+51 -3
@@ -2,9 +2,13 @@ import { describe, expect, layer } from '@effect/vitest';
2 import { Effect } from 'effect';
3 import { ValidationError, HelpDoc } from '@effect/cli';
4 import { cli, pkg, TestLive, MockConsole } from 'test/__utils__';
5 -import { sanitize } from 'test/__utils__/sanitize';
5 +import { afterEach, vi } from 'vitest';
6
7 describe('CLI: composio', () => {
8 + afterEach(() => {
9 + vi.unstubAllEnvs();
10 + });
11 +
12 layer(TestLive())(it => {
13 it.scoped('[Given] unknown argument [Then] print error message', () =>
14 Effect.gen(function* () {
@@ -15,7 +19,7 @@ describe('CLI: composio', () => {
19 expect(result).toEqual(
20 ValidationError.commandMismatch(
21 HelpDoc.p(
18 - "Invalid subcommand for composio - use one of 'version', 'upgrade', 'whoami', 'login', 'logout', 'run', 'install', 'dev', 'tools', 'search', 'link', 'execute', 'generate', 'manage'"
22 + "Invalid subcommand for composio - use one of 'version', 'upgrade', 'whoami', 'login', 'logout', 'run', 'proxy', 'artifacts', 'install', 'dev', 'tools', 'search', 'link', 'execute', 'generate', 'manage'"
23 )
24 )
25 );
@@ -30,7 +34,16 @@ describe('CLI: composio', () => {
34 yield* cli(args);
35 const lines = yield* MockConsole.getLines({ stripAnsi: true });
36 const output = lines.join('\n');
33 - expect(yield* sanitize(output)).toMatchSnapshot();
37 + expect(output).toContain('CORE COMMANDS');
38 + expect(output).toContain('composio search <query>');
39 + expect(output).toContain('composio execute <slug>');
40 + expect(output).toContain('composio link [<toolkit>]');
41 + expect(output).toContain('composio run <code>');
42 + expect(output).toContain('composio proxy <url> --toolkit text');
43 + expect(output).toContain('composio artifacts cwd');
44 + expect(output).toContain('DEVELOPER COMMANDS');
45 + expect(output).toContain('ACCOUNT');
46 + expect(output).toContain('Documentation: https://docs.composio.dev');
47 })
48 );
49 });
@@ -58,4 +71,39 @@ describe('CLI: composio', () => {
71 })
72 );
73 });
74 +
75 + layer(TestLive())(it => {
76 + it.scoped('[Given] debug who-is-my-master [Then] it prints the detected master as json', () =>
77 + Effect.gen(function* () {
78 + vi.stubEnv('CODEX_THREAD_ID', 'thread_123');
79 + vi.stubEnv('CLAUDE_CODE_ENTRYPOINT', 'sdk-ts');
80 + const write = vi
81 + .spyOn(process.stdout, 'write')
82 + .mockImplementation((() => true) as typeof process.stdout.write);
83 +
84 + yield* cli(['debug', 'who-is-my-master']);
85 + const output = write.mock.calls.map(call => String(call[0])).join('\n');
86 +
87 + expect(output).toContain('"master": "codex"');
88 + })
89 + );
90 + });
91 +
92 + layer(TestLive())(it => {
93 + it.scoped('[Given] artifacts cwd [Then] it prints the current session artifact directory', () =>
94 + Effect.gen(function* () {
95 + const write = vi
96 + .spyOn(process.stdout, 'write')
97 + .mockImplementation((() => true) as typeof process.stdout.write);
98 +
99 + yield* cli(['artifacts', 'cwd']);
100 + const output = write.mock.calls
101 + .map(call => String(call[0]))
102 + .join('\n')
103 + .trim();
104 +
105 + expect(output).toContain('/tmp/composio');
106 + })
107 + );
108 + });
109 });
ts/packages/cli/test/src/commands/__snapshots__/$default.cmd.test.ts.snap deleted
-96
@@ -1,96 +0,0 @@
1 -// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
2 -
3 -exports[`CLI: composio > [Given] --help flag [Then] prints help message 1`] = `
4 -"
5 -Connect AI agents to external tools. \`search\`, \`link\`, \`execute\`, and \`run\` let you take actions across 1000+ apps directly; if you can describe it, it is probably supported.
6 -Try \`execute\` sooner than you'd think. It parses inputs, validates them against cached schemas when available, and will usually tell you whether you need to fix arguments, inspect schema, or \`link\` an account.
7 -Use \`dev\` when you are building with Composio and want scaffolding, playground execution, triggers, and logs.
8 -
9 -USAGE
10 - composio <command> [options]
11 -
12 -BASIC COMMANDS
13 - version
14 - Display the current Composio CLI version.
15 - Usage: composio version
16 -
17 - upgrade
18 - Upgrade your Composio CLI to the latest available version.
19 - Usage: composio upgrade
20 -
21 - whoami
22 - Display your account information.
23 - Usage: composio whoami
24 -
25 - login
26 - Log in to the Composio CLI session.
27 - Usage: composio login [--no-browser] [--no-wait] [--key text] [-y, --yes]
28 - Options:
29 - --no-browser Login without browser interaction
30 - --no-wait Print login URL and session info, then exit (no browser, no waiting)
31 - --key Complete login using session key from --no-wait
32 - -y, --yes Skip org picker; use session default org
33 -
34 - logout
35 - Log out from the Composio CLI session.
36 - Usage: composio logout
37 -
38 - run
39 - Run inline ESNext TS/JS code or a file with Bun and injected Composio helpers.
40 - Usage: composio run <code> [-- ...args] | run [-f, --file text] [-- ...args] [--dry-run] [--skip-connection-check] [--skip-tool-params-check] [--no-verify]
41 - Options:
42 - <code> Inline Bun ESNext code with injected execute(slug, data?) and search(query, options?) helpers
43 - -f, --file Run a TS/JS file with the Bun runtime instead of inline code
44 - --dry-run Preview execute(...) calls without running remote actions
45 - --skip-connection-check Skip the short-lived linked-account fail-fast check if you just connected an account
46 - --skip-tool-params-check Skip the local tool parameter/schema validation check
47 - --no-verify Skip both the linked-account fail-fast check and the local tool parameter check
48 -
49 - search
50 - Semantic search for tools by use case across all toolkits/apps.
51 - Usage: composio search <query> [--toolkits text] [--limit integer]
52 - Options:
53 - <query> Semantic use-case query (e.g. "send emails")
54 - --toolkits Filter by toolkit slugs, comma-separated
55 - --limit Number of results per page (1-1000)
56 -
57 - tools
58 - List tools for one toolkit, or inspect a cached schema-backed summary.
59 - Usage: composio tools list <toolkit> [--query text] | tools info <slug>
60 - Options:
61 - list <toolkit> Non-semantic per-toolkit listing; use this when you already know the toolkit
62 - info <slug> Print a brief summary and cache the same raw schema used by execute --get-schema
63 -
64 - execute
65 - Execute a tool, preview it with --dry-run, or fetch its input schema.
66 - Usage: composio execute <slug> [-d, --data text] [--dry-run] [--get-schema] [--skip-connection-check] [--skip-tool-params-check] [--no-verify]
67 - Options:
68 - <slug> Tool slug (e.g. "GITHUB_CREATE_ISSUE")
69 - -d, --data JSON or JS-style object arguments, e.g. -d '{ repo: "foo" }', @file, or - for stdin
70 - --dry-run Validate and preview the tool call without executing it
71 - --get-schema Fetch and print the raw cached schema; tools info shows the same schema with a brief summary
72 - --skip-connection-check Skip the short-lived linked-account fail-fast check if you just connected an account
73 - --skip-tool-params-check Skip the local tool parameter/schema validation check
74 - --no-verify Skip both the linked-account fail-fast check and the local tool parameter check
75 -
76 - link
77 - Connect a user account for a toolkit/app.
78 - Usage: composio link [<toolkit>] [--no-browser]
79 - Options:
80 - <toolkit> Toolkit slug to link (e.g. "github", "gmail")
81 - --no-browser Skip auto-opening the browser
82 -
83 -ADVANCED COMMANDS
84 - dev Developer workflows: init a local project, execute tools with playground users, listen for triggers, and inspect logs.
85 - generate Generate type stubs for toolkits, tools, and triggers, auto-detecting project language (TypeScript | Python)
86 - manage Manage your developer orgs, toolkits, connected accounts, triggers, auth configs, and projects.
87 -
88 -FLAGS
89 - -h, --help Show help for command
90 - --version Show composio version
91 -
92 -LEARN MORE
93 - Use \`composio <command> --help\` for more information about a command.
94 - Documentation: https://docs.composio.dev
95 -"
96 -`;
ts/packages/cli/test/src/commands/proxy.cmd.test.ts new
+215
@@ -0,0 +1,215 @@
1 +import { describe, expect, layer } from '@effect/vitest';
2 +import { ConfigProvider, Effect, Option } from 'effect';
3 +import { afterEach, it, vi } from 'vitest';
4 +import type {
5 + SessionCreateParams,
6 + SessionProxyExecuteParams,
7 +} from '@composio/client/resources/tool-router';
8 +import { extendConfigProvider } from 'src/services/config';
9 +import { normalizeProxyMethod, parseProxyBody, parseProxyHeader } from 'src/commands/proxy.cmd';
10 +import * as consumerShortTermCache from 'src/services/consumer-short-term-cache';
11 +import { cli, MockConsole, TestLive } from 'test/__utils__';
12 +
13 +const testConfigProvider = ConfigProvider.fromMap(
14 + new Map([['COMPOSIO_USER_API_KEY', 'test_api_key']])
15 +).pipe(extendConfigProvider);
16 +
17 +describe('CLI: composio proxy', () => {
18 + afterEach(() => {
19 + vi.restoreAllMocks();
20 + });
21 +
22 + it('parses curl-style header values', () => {
23 + expect(parseProxyHeader('content-type: application/json')).toEqual({
24 + name: 'content-type',
25 + value: 'application/json',
26 + });
27 + });
28 +
29 + it('normalizes HTTP methods', () => {
30 + expect(normalizeProxyMethod('post')).toBe('POST');
31 + });
32 +
33 + it('parses JSON-like request bodies when possible', () => {
34 + expect(parseProxyBody('{ foo: "bar" }')).toEqual({ foo: 'bar' });
35 + expect(parseProxyBody('plain text')).toBe('plain text');
36 + });
37 +
38 + layer(TestLive({ baseConfigProvider: testConfigProvider, fixture: 'global-test-user-id' }))(
39 + '[Given] curl-like proxy flags [Then] it creates a scoped session and forwards proxy_execute',
40 + it => {
41 + it.scoped('forwards proxy execute params and prints the response', () =>
42 + Effect.gen(function* () {
43 + let createParams: SessionCreateParams | undefined;
44 + let proxyParams:
45 + | {
46 + sessionId: string;
47 + params: SessionProxyExecuteParams;
48 + }
49 + | undefined;
50 +
51 + const live = TestLive({
52 + baseConfigProvider: testConfigProvider,
53 + fixture: 'global-test-user-id',
54 + toolRouter: {
55 + create: async (params: SessionCreateParams) => {
56 + createParams = params;
57 + return {
58 + session_id: 'trs_proxy_test',
59 + config: { user_id: params.user_id },
60 + mcp: { type: 'http' as const, url: 'https://mcp.test.composio.dev' },
61 + tool_router_tools: [],
62 + };
63 + },
64 + proxyExecute: async (sessionId: string, params: SessionProxyExecuteParams) => {
65 + proxyParams = { sessionId, params };
66 + return {
67 + status: 200,
68 + data: {
69 + ok: true,
70 + endpoint: params.endpoint,
71 + method: params.method,
72 + },
73 + headers: { 'content-type': 'application/json' },
74 + };
75 + },
76 + },
77 + });
78 +
79 + yield* cli([
80 + 'proxy',
81 + 'https://gmail.googleapis.com/gmail/v1/users/me/drafts',
82 + '--toolkit',
83 + 'gmail',
84 + '-X',
85 + 'post',
86 + '-H',
87 + 'content-type: application/json',
88 + '-d',
89 + '{ "message": { "raw": "abc" } }',
90 + ]).pipe(Effect.provide(live));
91 +
92 + expect(createParams).toEqual({
93 + user_id: 'consumer-user-org_test',
94 + manage_connections: { enable: false },
95 + toolkits: { enable: ['gmail'] },
96 + });
97 + expect(proxyParams).toEqual({
98 + sessionId: 'trs_proxy_test',
99 + params: {
100 + toolkit_slug: 'gmail',
101 + endpoint: 'https://gmail.googleapis.com/gmail/v1/users/me/drafts',
102 + method: 'POST',
103 + body: { message: { raw: 'abc' } },
104 + parameters: [
105 + {
106 + name: 'content-type',
107 + type: 'header',
108 + value: 'application/json',
109 + },
110 + ],
111 + },
112 + });
113 +
114 + const lines = yield* MockConsole.getLines({ stripAnsi: true });
115 + const output = lines.join('\n');
116 + expect(output).toContain('Status: 200');
117 + expect(output).toContain('"ok": true');
118 + })
119 + );
120 + }
121 + );
122 +
123 + layer(TestLive({ baseConfigProvider: testConfigProvider, fixture: 'global-test-user-id' }))(
124 + '[Given] cached missing toolkit [Then] proxy fails fast before session creation',
125 + it => {
126 + it.scoped('uses the connected toolkit cache keyed by toolkit', () =>
127 + Effect.gen(function* () {
128 + const refreshSpy = vi
129 + .spyOn(consumerShortTermCache, 'refreshConsumerConnectedToolkitsCache')
130 + .mockReturnValue(Effect.void);
131 + const getFreshSpy = vi
132 + .spyOn(consumerShortTermCache, 'getFreshConsumerConnectedToolkitsFromCache')
133 + .mockReturnValue(Effect.succeed(Option.some(['slack'])));
134 +
135 + let createCalled = false;
136 + const live = TestLive({
137 + baseConfigProvider: testConfigProvider,
138 + fixture: 'global-test-user-id',
139 + toolRouter: {
140 + create: async (_params: SessionCreateParams) => {
141 + createCalled = true;
142 + return {
143 + session_id: 'trs_proxy_test',
144 + config: { user_id: 'global_test_user_id' },
145 + mcp: { type: 'http' as const, url: 'https://mcp.test.composio.dev' },
146 + tool_router_tools: [],
147 + };
148 + },
149 + },
150 + });
151 +
152 + yield* cli([
153 + 'proxy',
154 + 'https://gmail.googleapis.com/gmail/v1/users/me/profile',
155 + '--toolkit',
156 + 'gmail',
157 + ]).pipe(
158 + Effect.provide(live),
159 + Effect.catchAll(() => Effect.void)
160 + );
161 +
162 + expect(createCalled).toBe(false);
163 +
164 + const lines = yield* MockConsole.getLines({ stripAnsi: true });
165 + const output = lines.join('\n');
166 + expect(output).toContain('Toolkit "gmail" is not connected for this user');
167 + expect(output).toContain('composio link gmail');
168 + expect(refreshSpy).toHaveBeenCalled();
169 + expect(getFreshSpy).toHaveBeenCalled();
170 + })
171 + );
172 + }
173 + );
174 +
175 + layer(TestLive({ baseConfigProvider: testConfigProvider, fixture: 'global-test-user-id' }))(
176 + '[Given] backend 4302 no-connection error [Then] proxy rewrites it to link guidance',
177 + it => {
178 + it.scoped('translates proxy_execute connection errors like execute does', () =>
179 + Effect.gen(function* () {
180 + const live = TestLive({
181 + baseConfigProvider: testConfigProvider,
182 + fixture: 'global-test-user-id',
183 + toolRouter: {
184 + proxyExecute: async () => {
185 + throw {
186 + message: 'raw backend error',
187 + details: {
188 + code: 4302,
189 + slug: 'ToolRouterV2_NoActiveConnection',
190 + message: 'No active connection',
191 + },
192 + };
193 + },
194 + },
195 + });
196 +
197 + const exit = yield* cli([
198 + 'proxy',
199 + 'https://gmail.googleapis.com/gmail/v1/users/me/profile',
200 + '--toolkit',
201 + 'gmail',
202 + '--skip-connection-check',
203 + ]).pipe(Effect.provide(live), Effect.exit);
204 +
205 + expect(exit._tag).toBe('Failure');
206 +
207 + const lines = yield* MockConsole.getLines({ stripAnsi: true });
208 + const output = lines.join('\n');
209 + expect(output).toContain('No active connection found for toolkit "gmail"');
210 + expect(output).toContain('composio link gmail');
211 + })
212 + );
213 + }
214 + );
215 +});
ts/packages/cli/test/src/commands/run.cmd.test.ts
+124 -37
@@ -1,3 +1,6 @@
1 +import * as fs from 'node:fs';
2 +import * as os from 'node:os';
3 +import * as path from 'node:path';
4 import { describe, expect, layer } from '@effect/vitest';
5 import { Effect } from 'effect';
6 import { afterEach, it, vi } from 'vitest';
@@ -5,6 +8,7 @@ import {
8 buildRunHelpersSource,
9 extractInlineExecuteToolSlugs,
10 inferCliInvocationPrefix,
11 + wrapInlineCodeForRun,
12 } from 'src/commands/run.cmd';
13 import { cli, MockConsole, TestLive } from 'test/__utils__';
14
@@ -34,13 +38,11 @@ describe('CLI: composio run', () => {
38 expect(spawnConfig.cmd[0]).toBe(process.execPath);
39 expect(spawnConfig.cmd[1]).toBe('--preload');
40 expect(spawnConfig.cmd[2]).toMatch(/globals\.mjs$/);
37 - expect(spawnConfig.cmd.slice(3)).toEqual([
38 - '--eval',
39 - 'console.log("hi")',
40 - '--',
41 - '--flag',
42 - 'value',
43 - ]);
41 + expect(spawnConfig.cmd[3]).toBe('--eval');
42 + expect(spawnConfig.cmd[4]).toContain('(async () => {');
43 + expect(spawnConfig.cmd[4]).toContain('return (console.log("hi"));');
44 + expect(spawnConfig.cmd[4]).toContain('if (__composioResult !== undefined) {');
45 + expect(spawnConfig.cmd.slice(5)).toEqual(['--', '--flag', 'value']);
46 expect(spawnConfig.env).toEqual(
47 expect.objectContaining({
48 ...process.env,
@@ -56,30 +58,39 @@ describe('CLI: composio run', () => {
58 layer(TestLive())(it => {
59 it.scoped('[Given] --file [Then] it forwards file execution to the embedded Bun runtime', () =>
60 Effect.gen(function* () {
61 + const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'composio-run-test-'));
62 + const scriptPath = path.join(tempDir, 'script.ts');
63 + fs.writeFileSync(scriptPath, 'const value = 1 + 1;\nvalue * 2;\n', 'utf8');
64 const spawn = vi.fn(() => ({ exited: Promise.resolve(0) }));
65 const exit = vi.spyOn(process, 'exit').mockImplementation((() => undefined) as never);
66 vi.stubGlobal('Bun', { spawn });
67
63 - yield* cli(['run', '--file', './script.ts', '--', 'hello']);
68 + try {
69 + yield* cli(['run', '--file', scriptPath, '--', 'hello']);
70
65 - expect(spawn).toHaveBeenCalledTimes(1);
66 - const spawnConfig = (spawn as any).mock.calls[0][0] as {
67 - cmd: string[];
68 - env: unknown;
69 - stdio: string[];
70 - };
71 - expect(spawnConfig.cmd[0]).toBe(process.execPath);
72 - expect(spawnConfig.cmd[1]).toBe('--preload');
73 - expect(spawnConfig.cmd[2]).toMatch(/globals\.mjs$/);
74 - expect(spawnConfig.cmd.slice(3)).toEqual(['run', './script.ts', '--', 'hello']);
75 - expect(spawnConfig.env).toEqual(
76 - expect.objectContaining({
77 - ...process.env,
78 - BUN_BE_BUN: '1',
79 - })
80 - );
81 - expect(spawnConfig.stdio).toEqual(['inherit', 'inherit', 'inherit']);
82 - expect(exit).toHaveBeenCalledWith(0);
71 + expect(spawn).toHaveBeenCalledTimes(1);
72 + const spawnConfig = (spawn as any).mock.calls[0][0] as {
73 + cmd: string[];
74 + env: unknown;
75 + stdio: string[];
76 + };
77 + expect(spawnConfig.cmd[0]).toBe(process.execPath);
78 + expect(spawnConfig.cmd[1]).toBe('--preload');
79 + expect(spawnConfig.cmd[2]).toMatch(/globals\.mjs$/);
80 + expect(spawnConfig.cmd[3]).toMatch(/\.composio-run-.*\.ts$/);
81 + expect(spawnConfig.cmd[4]).toBe('--');
82 + expect(spawnConfig.cmd[5]).toBe('hello');
83 + expect(spawnConfig.env).toEqual(
84 + expect.objectContaining({
85 + ...process.env,
86 + BUN_BE_BUN: '1',
87 + })
88 + );
89 + expect(spawnConfig.stdio).toEqual(['inherit', 'inherit', 'inherit']);
90 + expect(exit).toHaveBeenCalledWith(0);
91 + } finally {
92 + fs.rmSync(tempDir, { recursive: true, force: true });
93 + }
94 })
95 );
96 });
@@ -94,17 +105,26 @@ describe('CLI: composio run', () => {
105 });
106
107 layer(TestLive())(it => {
97 - it.scoped('[Given] run help [Then] it documents injected search and execute helpers', () =>
98 - Effect.gen(function* () {
99 - yield* cli(['run', '--help']);
100 - const lines = yield* MockConsole.getLines({ stripAnsi: true });
101 - const output = lines.join('\n');
102 - expect(output).toContain('await search(query');
103 - expect(output).toContain('await execute(slug, data?)');
104 - expect(output).toContain('import { $ } from "bun"');
105 - expect(output).toContain('top level `execute` and `search` auth states');
106 - expect(output).toContain('tool_definitions');
107 - })
108 + it.scoped(
109 + '[Given] run help [Then] it documents injected execute, search, proxy, subAgent, and z helpers',
110 + () =>
111 + Effect.gen(function* () {
112 + yield* cli(['run', '--help']);
113 + const lines = yield* MockConsole.getLines({ stripAnsi: true });
114 + const output = lines.join('\n');
115 + expect(output).toContain(
116 + 'Run inline TS/JS code or a file with injected Composio helpers that behave like their CLI counterparts.'
117 + );
118 + expect(output).toContain('--skip-connection-check');
119 + expect(output).toContain('--skip-tool-params-check');
120 + expect(output).toContain('--no-verify');
121 + expect(output).toContain('subAgent');
122 + expect(output).toContain('schema: z.object');
123 + expect(output).toContain('INJECTED HELPERS');
124 + expect(output).toContain('Global from zod');
125 + expect(output).toContain('composio search "<query>"');
126 + expect(output).toContain('composio execute <slug> --get-schema');
127 + })
128 );
129 });
130 });
@@ -120,9 +140,65 @@ describe('buildRunHelpersSource', () => {
140 dryRun: true,
141 });
142
143 + expect(source).toContain('import { z } from "zod";');
144 + expect(source).toContain('globalThis.z = z;');
145 + expect(source).toContain('globalThis.zod = z;');
146 + expect(source).toContain('const stringifyForPrompt = (value) => {');
147 + expect(source).toContain('const attachPromptMethod = (value) => {');
148 + expect(source).toContain('typeof value.prompt === "function"');
149 + expect(source).toContain(
150 + 'value: () => stringifyForPrompt("data" in value ? value.data : value),'
151 + );
152 + expect(source).toContain(
153 + 'const sharedRunOutputDir = typeof helperContext.runOutputDir === "string"'
154 + );
155 + expect(source).toContain('COMPOSIO_RUN_OUTPUT_DIR');
156 + expect(source).toContain('fs.mkdtempSync(path.join(sharedRunOutputDir, "invoke-agent-"))');
157 + expect(source).toContain('const maybeLoadStoredCliResult = (result) => {');
158 + expect(source).toContain('storedInFilePath: outputFilePath !== null,');
159 + expect(source).toContain('outputFilePath,');
160 + expect(source).toContain('const logCliResultPreview = (requestId, result) => {');
161 + expect(source).toContain('helperDebugLog("cli.result", {');
162 + expect(source).toContain('helperDebugLog("cli.result.stored_in_file"');
163 expect(source).toContain('COMPOSIO_USER_API_KEY');
164 expect(source).toContain('"consumerUserId":"consumer_user_test"');
165 expect(source).toContain('__composioConsumerContext');
166 + expect(source).toContain('globalThis.execute = async (slug, data = {}) => {');
167 + expect(source).toContain(
168 + 'if (result && typeof result === "object" && result.successful === false) {'
169 + );
170 + expect(source).toContain('Object.assign(error, { result, slug });');
171 + expect(source).toContain('globalThis.subAgent = subAgentImpl;');
172 + expect(source).toContain(
173 + 'Object.defineProperty(globalThis.subAgent, "schema", { value: subAgentSchema });'
174 + );
175 + expect(source).toContain('globalThis.invokeAgent = subAgentImpl;');
176 + expect(source).toContain('const toInvokeAgentResponse = (master, target, payload = {}) => ({');
177 + expect(source).toContain('const invokeClaudeAgent = async (prompt, options) => {');
178 + expect(source).toContain('const invokeCodexAgent = async (prompt, options) => {');
179 + expect(source).toContain('const detectInvokeAgentMaster = () => {');
180 + expect(source).toContain(
181 + 'throw new Error("subAgent() accepts either options.schema or options.jsonSchema, not both.");'
182 + );
183 + expect(source).toContain('const inputSchema = options.schema ?? options.jsonSchema;');
184 + expect(source).toContain('if (typeof z.toJSONSchema !== "function") {');
185 + expect(source).toContain(
186 + 'subAgent() requires Zod 4 with z.toJSONSchema() when using options.schema.'
187 + );
188 + expect(source).toContain('structuredSchema = z.toJSONSchema(inputSchema);');
189 + expect(source).toContain(
190 + '["codex", "exec", "--skip-git-repo-check", "--sandbox", "read-only", "-o", outputPath]'
191 + );
192 + expect(source).toContain('["claude", "--bare", "-p", "--output-format", "json"]');
193 + expect(source).toContain('structuredOutput: parsed.structured_output ?? null');
194 + expect(source).toContain('globalThis.proxy = async (toolkit) => {');
195 + expect(source).toContain('const proxyFetch = async (input, init = {}) => {');
196 + expect(source).toContain('return toProxyResponse(result);');
197 + expect(source).toContain(
198 + 'Object.defineProperty(globalThis.proxy, "schema", { value: proxySchema });'
199 + );
200 + expect(source).toContain('`/api/v3/tool_router/session/${sessionId}/proxy_execute`');
201 + expect(source).toContain('"proxy() requires a consumer project context');
202 expect(source).toContain('returned no JSON output');
203 expect(source).toContain('args.push("--dry-run");');
204 expect(source).toContain('args.push("--skip-connection-check");');
@@ -152,3 +228,14 @@ describe('extractInlineExecuteToolSlugs', () => {
228 ).toEqual(['GMAIL_SEND_EMAIL', 'GITHUB_CREATE_ISSUE']);
229 });
230 });
231 +
232 +describe('wrapInlineCodeForRun', () => {
233 + it('[Given] inline code ending in an expression [Then] it rewrites the last expression to a return', () => {
234 + expect(
235 + wrapInlineCodeForRun(`
236 + const value = 1 + 1;
237 + value * 2;
238 + `)
239 + ).toContain('return (value * 2);');
240 + });
241 +});
ts/packages/cli/test/src/commands/tools/tools.execute.cmd.test.ts
+43 -16
@@ -1,11 +1,12 @@
1 import * as fs from 'node:fs';
2 import { describe, expect, layer } from '@effect/vitest';
3 import { vi, beforeEach, afterEach } from 'vitest';
4 -import { ConfigProvider, Effect } from 'effect';
4 +import { ConfigProvider, Effect, Option } from 'effect';
5 import { extendConfigProvider } from 'src/services/config';
6 -import { ActionExecuteConnectedAccountNotFoundError } from 'src/services/tools-executor';
6 +import { ComposioNoActiveConnectionError } from 'src/services/composio-error-overrides';
7 import { setupCacheDir } from 'src/effects/setup-cache-dir';
8 import { getOrFetchToolInputDefinition } from 'src/services/tool-input-validation';
9 +import * as consumerShortTermCache from 'src/services/consumer-short-term-cache';
10 import * as redactModule from 'src/ui/redact';
11 import { cli, TestLive, MockConsole } from 'test/__utils__';
12 import type { TestLiveInput } from 'test/__utils__/services/test-layer';
@@ -41,8 +42,15 @@ describe('CLI: composio execute', () => {
42 beforeEach(() => {
43 savedCI = process.env.CI;
44 delete process.env.CI;
45 + vi.spyOn(consumerShortTermCache, 'getFreshConsumerConnectedToolkitsFromCache').mockReturnValue(
46 + Effect.succeed(Option.some(['gmail', 'github']))
47 + );
48 + vi.spyOn(consumerShortTermCache, 'refreshConsumerConnectedToolkitsCache').mockImplementation(
49 + () => Effect.succeed(['gmail', 'github'])
50 + );
51 });
52 afterEach(() => {
53 + vi.restoreAllMocks();
54 if (savedCI !== undefined) process.env.CI = savedCI;
55 });
56
@@ -55,7 +63,13 @@ describe('CLI: composio execute', () => {
63 )('[Given] -d inline JSON [Then] executes via Tool Router with defaults', it => {
64 it.scoped('executes via Tool Router with defaults', () =>
65 Effect.gen(function* () {
58 - yield* cli(['execute', 'GMAIL_SEND_EMAIL', '-d', '{"recipient":"a"}']);
66 + yield* cli([
67 + 'execute',
68 + 'GMAIL_SEND_EMAIL',
69 + '--skip-connection-check',
70 + '-d',
71 + '{"recipient":"a"}',
72 + ]);
73 const lines = yield* MockConsole.getLines({ stripAnsi: true });
74 const output = parseLastJson(lines);
75
@@ -419,12 +433,17 @@ describe('CLI: composio execute', () => {
433 expect(output.storedInFile).toBe(true);
434 expect(output.logId).toBe('log_large_output');
435 expect(output.tokenCount).toBeGreaterThan(10_000);
422 - expect(output.outputFilePath).toMatch(/^\/tmp\/composio\/[^/]+\/output-[^.]+\.json$/);
436 + expect(output.outputFilePath).toMatch(
437 + /^\/tmp\/composio\/[^/]+\/GMAIL_SEND_EMAIL_OUTPUT_[^.]+\.json$/
438 + );
439 expect(fs.existsSync(output.outputFilePath)).toBe(true);
440 const storedJson = fs.readFileSync(output.outputFilePath, 'utf8');
441 expect(storedJson).toContain('token token token');
442
427 - fs.rmSync(output.outputFilePath.split('/output-')[0]!, { recursive: true, force: true });
443 + fs.rmSync(output.outputFilePath.slice(0, output.outputFilePath.lastIndexOf('/')), {
444 + recursive: true,
445 + force: true,
446 + });
447 })
448 );
449 });
@@ -734,16 +753,18 @@ describe('CLI: composio execute', () => {
753 } satisfies TestLiveInput['toolkitsData'],
754 stdin: { isTTY: true, data: '' },
755 })
737 - )('[Given] execute-help with options before slug [Then] resolves correct slug', it => {
738 - it.scoped('resolves root execute help slug correctly', () =>
756 + )('[Given] execute --help with a slug [Then] it shows command help', it => {
757 + it.scoped('shows the root execute help text', () =>
758 Effect.gen(function* () {
759 yield* cli(['execute', 'GMAIL_SEND_EMAIL', '--help']);
760 const lines = yield* MockConsole.getLines({ stripAnsi: true });
761 const output = lines.join('\n');
762
744 - expect(output).toContain('Slug: GMAIL_SEND_EMAIL');
745 - expect(output).toContain('Data Parameters:');
746 - expect(output).toContain('recipient');
763 + expect(output).toContain('USAGE');
764 + expect(output).toContain(
765 + 'composio execute <slug> [-d, --data text] [--dry-run] [--get-schema]'
766 + );
767 + expect(output).toContain('composio execute GMAIL_SEND_EMAIL --get-schema');
768 })
769 );
770 });
@@ -774,9 +795,12 @@ describe('CLI: composio execute', () => {
795 fixture: 'global-test-user-id',
796 stdin: { isTTY: true, data: '' },
797 toolsExecutor: {
777 - failWith: new ActionExecuteConnectedAccountNotFoundError({
778 - slug: 'ActionExecute_ConnectedAccountNotFound',
779 - message: 'No connected account found for entity ID default for toolkit gmail',
798 + failWith: new ComposioNoActiveConnectionError({
799 + details: {
800 + slug: 'ActionExecute_ConnectedAccountNotFound',
801 + message: 'No connected account found for entity ID default for toolkit gmail',
802 + },
803 + toolSlug: 'GMAIL_CREATE_EMAIL_DRAFT',
804 }),
805 },
806 })
@@ -1009,9 +1033,12 @@ describe('CLI: composio execute', () => {
1033 fixture: 'global-test-user-id',
1034 stdin: { isTTY: true, data: '' },
1035 toolsExecutor: {
1012 - failWith: new ActionExecuteConnectedAccountNotFoundError({
1013 - slug: 'ToolRouterV2_NoActiveConnection',
1014 - message: 'No active connection found for toolkit(s) in this session',
1036 + failWith: new ComposioNoActiveConnectionError({
1037 + details: {
1038 + slug: 'ToolRouterV2_NoActiveConnection',
1039 + message: 'No active connection found for toolkit(s) in this session',
1040 + },
1041 + toolSlug: 'COMPOSIO_SEARCH_TOOLS',
1042 }),
1043 },
1044 })
ts/packages/cli/test/src/services/composio-error-overrides.test.ts new
+77
@@ -0,0 +1,77 @@
1 +import { describe, expect, it } from 'vitest';
2 +
3 +import {
4 + ComposioNoActiveConnectionError,
5 + mapComposioError,
6 + mapOnlyComposioOverrideError,
7 +} from 'src/services/composio-error-overrides';
8 +
9 +describe('composio-error-overrides', () => {
10 + it('rewrites tool-router no-active-connection errors by toolkit', () => {
11 + const result = mapComposioError({
12 + toolkit: 'gmail',
13 + error: {
14 + details: {
15 + code: 4302,
16 + slug: 'ToolRouterV2_NoActiveConnection',
17 + message: 'No active connection',
18 + },
19 + },
20 + });
21 +
22 + expect(result.normalized).toBeInstanceOf(ComposioNoActiveConnectionError);
23 + expect(result.message).toBe(
24 + 'No active connection found for toolkit "gmail". Run `composio link gmail`, then retry.'
25 + );
26 + });
27 +
28 + it('rewrites execute no-connection errors by tool slug', () => {
29 + const result = mapComposioError({
30 + toolSlug: 'SLACK_SEND_MESSAGE',
31 + error: {
32 + error: {
33 + slug: 'ActionExecute_ConnectedAccountNotFound',
34 + message: 'Missing connected account',
35 + },
36 + },
37 + });
38 +
39 + expect(result.normalized).toBeInstanceOf(ComposioNoActiveConnectionError);
40 + expect(result.message).toBe(
41 + 'No active connection found for toolkit "slack". Run `composio link slack`, then retry.'
42 + );
43 + });
44 +
45 + it('passes through unrelated errors', () => {
46 + const error = new Error('Something else broke');
47 +
48 + const result = mapComposioError({ error });
49 +
50 + expect(result.normalized).toBe(error);
51 + expect(result.override).toBeNull();
52 + expect(result.message).toBe('Something else broke');
53 + });
54 +
55 + it('preserves original generic errors for top-level CLI handling', () => {
56 + const error = {
57 + _tag: 'ToolExecutionError',
58 + error: new Error('inner'),
59 + };
60 +
61 + expect(mapOnlyComposioOverrideError({ error })).toBe(error);
62 + });
63 +
64 + it('still rewrites override-class Composio errors at the top level', () => {
65 + const mapped = mapOnlyComposioOverrideError({
66 + toolkit: 'gmail',
67 + error: {
68 + details: {
69 + code: 4302,
70 + slug: 'ToolRouterV2_NoActiveConnection',
71 + },
72 + },
73 + });
74 +
75 + expect(mapped).toBeInstanceOf(ComposioNoActiveConnectionError);
76 + });
77 +});
ts/packages/cli/test/src/services/master-detector.test.ts new
+34
@@ -0,0 +1,34 @@
1 +import { describe, expect, it } from 'vitest';
2 +
3 +import { detectMaster } from 'src/services/master-detector';
4 +
5 +describe('master-detector', () => {
6 + it('detects codex when codex env markers are present', () => {
7 + expect(
8 + detectMaster({
9 + CODEX_THREAD_ID: 'thread_123',
10 + })
11 + ).toBe('codex');
12 + });
13 +
14 + it('detects claude when claude env markers are present without codex markers', () => {
15 + expect(
16 + detectMaster({
17 + CLAUDE_CODE_ENTRYPOINT: 'sdk-ts',
18 + })
19 + ).toBe('claude');
20 + });
21 +
22 + it('prefers codex when both codex and claude markers are present', () => {
23 + expect(
24 + detectMaster({
25 + CLAUDE_CODE_ENTRYPOINT: 'sdk-ts',
26 + CODEX_THREAD_ID: 'thread_123',
27 + })
28 + ).toBe('codex');
29 + });
30 +
31 + it('falls back to user when no known agent markers are present', () => {
32 + expect(detectMaster({})).toBe('user');
33 + });
34 +});