@devries-cameron20 / composio Mirror · read-only / commits / 7633445b4
Fork 0

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

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

Synced Nov 22, 02:00 UTC

feat(cli): improve consumer command UX and hinting (#2979)

## Summary This PR continues the consumer CLI work by making the top-level workflow more coherent around `search`, `link`, `tools`, `execute`, and `run`, while moving developer-oriented workflows under a dedicated `dev` namespace. The main theme is to make the CLI easier for an agent or user to use directly: - discover tools semantically with `search` - inspect toolkit-specific tools with `tools` - try `execute` earlier, with fast schema-aware failure messages - use `run` for programmatic multi-step flows without dropping into bash - keep developer/project scaffolding under `dev` ## What Changed ### Consumer command UX - added top-level `run` for inline Bun ESNext TS/JS or file execution - added injected global helpers inside `run` - `execute(slug, data?)` - `search(query, options?)` - updated root help text to better explain the intended flow and encourage trying `execute` early - clarified `search` as semantic search across toolkits/apps - moved `tools list` and `tools info` to top level - made `tools list` explicitly per-toolkit and non-semantic - updated `tools info` to give a short summary plus a cached schema reference instead of dumping raw detail - cleaned up stale help/hints that still referenced removed command paths ### New `dev` namespace - introduced `composio dev ...` for developer/project workflows - moved developer-focused flows under `dev`, including: - local init - playground-user execution - trigger listening - logs - updated help copy so `manage` no longer claims to own `tools` or `logs` - reframed `dev` as the place for local scaffolding and project-building workflows ### Execute improvements - added schema-aware validation for `execute` - cached tool definitions under `~/.composio/tool_definitions/` - stored resolved version metadata with cached schemas - added version freshness checks and stale-cache refresh behavior - added a 12-hour version-check window to avoid refetching every invocation - invalidated stale cache entries when execution failures indicate the schema may no longer be trustworthy - improved validation errors to point at the cached schema file and give more actionable guidance - added `--get-schema` to fetch/cache the schema and print a compact inspection hint - added `--dry-run` to validate/preview execute calls without running the remote action - allowed `-d/--data` to accept JSON, JS-style object literals, `@file`, or stdin - added large-output handling that spills very large tool responses to `/tmp/composio/...` and returns a file reference ### `run` improvements - defaulted `run` to inline code, with `-f/--file` for file mode - clarified in help that `run` uses Bun ESNext TS/JS, not Node/CJS assumptions - documented the injected helpers and when to use them - made `run --dry-run` forward preview behavior through injected `execute(...)` - wired `run` to reuse consumer auth state and resolved consumer user context for helper calls - added AST-aware execute prewarming so static `execute("TOOL", ...)` calls can prime schema/cache work ### Hint graph and debug tooling - centralized command hints/examples in a shared registry - added linked command relationships so hints can be maintained as a graph instead of scattered hardcoded strings - added support for variant nodes such as `root.execute.getSchema` - added a hidden graph dump path for local iteration: - `composio debug generate-graph` - hid local-only debug controls from help output while keeping them usable: - `--perf-debug` - `--tool-debug` ### Internal cleanup - updated many runtime hints to point at current commands instead of removed paths - aligned login/whoami/project/toolkit/log output hints with the new command structure - refreshed tests and snapshots for the new top-level layout and command descriptions ## Verification Ran: - `pnpm --dir ts/packages/cli build:binary` - `pnpm --dir ts/packages/cli typecheck` - `./ts/packages/cli/dist/composio --help` ## Notes This PR is intentionally focused on the CLI flow and help/hint surface. It sets up a cleaner split between consumer-facing actions and developer/project workflows, while also making `execute` and `run` much more usable for agents.

Rahul Tarak committed Mar 23, 2026 at 18:06 UTC 7633445b479612c6498fa04157b89782931a7c48
43 files changed +3384 -444
pnpm-lock.yaml
+69 -14
@@ -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@4.3.6)
706 + version: 0.4.22(@llamaindex/core@0.6.22)(@llamaindex/env@0.1.30)(ws@8.19.0)(zod@3.25.76)
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@4.3.6))(hono@4.11.9)(zod@4.3.6)
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)
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@4.3.6))(hono@4.11.9)(tree-sitter@0.22.4)(web-tree-sitter@0.24.7)(zod@4.3.6)
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)
716 devDependencies:
717 '@types/bun':
718 specifier: ^1.2.9
@@ -1082,6 +1082,9 @@ importers:
1082 indent-string:
1083 specifier: ^5.0.0
1084 version: 5.0.0
1085 + js-tiktoken:
1086 + specifier: ^1.0.21
1087 + version: 1.0.21
1088 open:
1089 specifier: ^10.2.0
1090 version: 10.2.0
@@ -1321,7 +1324,7 @@ importers:
1324 dependencies:
1325 llamaindex:
1326 specifier: ^0.12.0
1324 - 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)
1327 + version: 0.12.1(tree-sitter@0.22.4)(web-tree-sitter@0.24.7)(zod@4.3.6)
1328 devDependencies:
1329 '@composio/core':
1330 specifier: workspace:*
@@ -7560,26 +7563,43 @@ snapshots:
7563 tree-sitter: 0.22.4
7564 web-tree-sitter: 0.24.7
7565
7563 - '@llamaindex/openai@0.4.22(@llamaindex/core@0.6.22)(@llamaindex/env@0.1.30)(ws@8.19.0)(zod@4.3.6)':
7566 + '@llamaindex/openai@0.4.22(@llamaindex/core@0.6.22)(@llamaindex/env@0.1.30)(ws@8.19.0)(zod@3.25.76)':
7567 dependencies:
7568 '@llamaindex/core': 0.6.22
7569 '@llamaindex/env': 0.1.30
7567 - openai: 5.23.2(ws@8.19.0)(zod@4.3.6)
7570 + openai: 5.23.2(ws@8.19.0)(zod@3.25.76)
7571 transitivePeerDependencies:
7572 - ws
7573 - zod
7574
7572 - '@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)':
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)':
7576 optionalDependencies:
7574 - '@modelcontextprotocol/sdk': 1.26.0(@cfworker/json-schema@4.1.1)(zod@4.3.6)
7577 + '@modelcontextprotocol/sdk': 1.26.0(@cfworker/json-schema@4.1.1)(zod@3.25.76)
7578 hono: 4.11.9
7579 + zod: 3.25.76
7580 +
7581 + '@llamaindex/workflow-core@1.3.3(zod@4.3.6)':
7582 + optionalDependencies:
7583 zod: 4.3.6
7584
7578 - '@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 + '@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)':
7586 dependencies:
7587 '@llamaindex/core': 0.6.22
7588 '@llamaindex/env': 0.1.30
7582 - '@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 + '@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)
7603 transitivePeerDependencies:
7604 - '@modelcontextprotocol/sdk'
7605 - hono
@@ -8513,6 +8533,14 @@ snapshots:
8533 optionalDependencies:
8534 vite: 7.3.1(@types/node@22.19.11)(tsx@4.21.0)(yaml@2.8.2)
8535
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 +
8544 '@vitest/pretty-format@3.2.4':
8545 dependencies:
8546 tinyrainbow: 2.0.0
@@ -8542,7 +8570,7 @@ snapshots:
8570 sirv: 3.0.2
8571 tinyglobby: 0.2.15
8572 tinyrainbow: 2.0.0
8545 - vitest: 3.2.4(@types/node@22.19.11)(@vitest/ui@3.2.4)(tsx@4.21.0)(yaml@2.8.2)
8573 + vitest: 3.2.4(@types/node@24.10.13)(@vitest/ui@3.2.4)(tsx@4.21.0)(yaml@2.8.2)
8574
8575 '@vitest/utils@3.2.4':
8576 dependencies:
@@ -9909,12 +9937,34 @@ snapshots:
9937 rfdc: 1.4.1
9938 wrap-ansi: 9.0.2
9939
9912 - 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):
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)
9917 - '@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)
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):
9963 + dependencies:
9964 + '@llamaindex/core': 0.6.22
9965 + '@llamaindex/env': 0.1.30
9966 + '@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)
9968 '@types/lodash': 4.17.23
9969 '@types/node': 24.10.13
9970 lodash: 4.17.23
@@ -10194,6 +10244,11 @@ snapshots:
10244 is-inside-container: 1.0.0
10245 wsl-utils: 0.1.0
10246
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 +
10252 openai@5.23.2(ws@8.19.0)(zod@4.3.6):
10253 optionalDependencies:
10254 ws: 8.19.0
@@ -11291,7 +11346,7 @@ snapshots:
11346 dependencies:
11347 '@types/chai': 5.2.3
11348 '@vitest/expect': 3.2.4
11294 - '@vitest/mocker': 3.2.4(vite@7.3.1(@types/node@22.19.11)(tsx@4.21.0)(yaml@2.8.2))
11349 + '@vitest/mocker': 3.2.4(vite@7.3.1(@types/node@24.10.13)(tsx@4.21.0)(yaml@2.8.2))
11350 '@vitest/pretty-format': 3.2.4
11351 '@vitest/runner': 3.2.4
11352 '@vitest/snapshot': 3.2.4
ts/packages/cli/package.json
+1
@@ -80,6 +80,7 @@
80 "decompress": "^4.2.1",
81 "effect": "catalog:",
82 "indent-string": "^5.0.0",
83 + "js-tiktoken": "^1.0.21",
84 "open": "^10.2.0",
85 "openapi-typescript": "^7.8.0",
86 "picocolors": "^1.1.1",
ts/packages/cli/src/commands/connected-accounts/commands/connected-accounts.link.cmd.ts
+6 -2
@@ -13,6 +13,7 @@ import {
13 resolveCommandProject,
14 formatResolveCommandProjectError,
15 } from 'src/services/command-project';
16 +import { invalidateConsumerConnectedToolkitsCache } from 'src/services/consumer-short-term-cache';
17
18 const toolkit = Args.text({ name: 'toolkit' }).pipe(
19 Args.withDescription('Toolkit slug to link (e.g. "github", "gmail")'),
@@ -206,12 +207,14 @@ const runConnectedAccountsLink = (params: {
207 });
208 if (Option.isNone(resolvedUserId)) {
209 return yield* Effect.fail(
209 - new Error('Missing user id. Provide --user-id or run composio init to set test_user_id.')
210 + new Error(
211 + 'Missing user id. Provide --user-id or run composio dev init to set test_user_id.'
212 + )
213 );
214 }
215 if (Option.isNone(params.projectName) && Option.isNone(resolvedProjectContext)) {
216 yield* ui.log.error(
214 - '`--auth-config` is developer-project scoped. Pass `--project-name <name>` or run from a directory initialized with `composio init`.'
217 + '`--auth-config` is developer-project scoped. Pass `--project-name <name>` or run from a directory initialized with `composio dev init`.'
218 );
219 return;
220 }
@@ -336,6 +339,7 @@ const runConnectedAccountsLink = (params: {
339 if (Option.isNone(validatedLink)) return;
340
341 const { connectedAccountId: connAccountId, redirectUrl } = validatedLink.value;
342 + yield* invalidateConsumerConnectedToolkitsCache().pipe(Effect.catchAll(() => Effect.void));
343
344 if (params.noWait) {
345 yield* ui.note(redirectUrl, 'Redirect URL');
ts/packages/cli/src/commands/dev.cmd.ts new
+12
@@ -0,0 +1,12 @@
1 +import { Command } from '@effect/cli';
2 +import { initCmd } from './init.cmd';
3 +import { triggersCmd$Listen } from './triggers/commands/triggers.listen.cmd';
4 +import { logsCmd } from './logs-cmd/logs.cmd';
5 +import { devToolsCmd$Execute } from './tools/commands/tools.execute.cmd';
6 +
7 +export const devCmd = Command.make('dev').pipe(
8 + Command.withDescription(
9 + 'Developer workflows: initialize a local project, execute tools with playground users, listen for triggers, and inspect logs.'
10 + ),
11 + Command.withSubcommands([initCmd, devToolsCmd$Execute, triggersCmd$Listen, logsCmd])
12 +);
ts/packages/cli/src/commands/index.ts
+113 -6
@@ -1,4 +1,5 @@
1 -import { Effect } from 'effect';
1 +import process from 'node:process';
2 +import { Effect, Option } from 'effect';
3 import { Command } from '@effect/cli';
4 import * as constants from 'src/constants';
5 import { $defaultCmd } from './$default.cmd';
@@ -8,16 +9,25 @@ import { upgradeCmd } from './upgrade.cmd';
9 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 { installCmd } from './install.cmd';
12 -import { initCmd } from './init.cmd';
14 import { generateCmd } from './generate/generate.cmd';
15 import { manageCmd } from './manage/manage.cmd';
16 +import { devCmd } from './dev.cmd';
17 import { showToolsExecuteInputHelp } from './tools/commands/tools.execute.cmd';
18 import { printRootHelp } from './root-help';
19 import { rootToolsCmd$Search } from './tools/commands/tools.search.cmd';
20 import { rootToolsCmd$Execute } from './tools/commands/tools.execute.cmd';
21 +import { rootToolsCmd } from './tools/tools.cmd';
22 import { rootConnectedAccountsCmd$Link } from './connected-accounts/commands/connected-accounts.link.cmd';
20 -import { triggersCmd$Listen } from './triggers/commands/triggers.listen.cmd';
23 +import { renderCommandHintGraph } from 'src/services/command-hints';
24 +import { resetRuntimeDebugFlags, setRuntimeDebugFlags } from 'src/services/runtime-debug-flags';
25 +import { ComposioUserContext } from 'src/services/user-context';
26 +import { TerminalUI } from 'src/services/terminal-ui';
27 +import {
28 + formatResolveCommandProjectError,
29 + resolveCommandProject,
30 +} from 'src/services/command-project';
31
32 const $cmd = $defaultCmd.pipe(
33 Command.withSubcommands([
@@ -26,12 +36,13 @@ const $cmd = $defaultCmd.pipe(
36 whoamiCmd,
37 loginCmd,
38 logoutCmd,
39 + runCmd,
40 installCmd,
30 - initCmd,
41 + devCmd,
42 + rootToolsCmd,
43 rootToolsCmd$Search,
44 rootConnectedAccountsCmd$Link,
45 rootToolsCmd$Execute,
34 - triggersCmd$Listen,
46 generateCmd,
47 manageCmd,
48 ])
@@ -102,11 +113,64 @@ const normalizeVersionShortFlag = (argv: ReadonlyArray<string>): ReadonlyArray<s
113 return argv;
114 };
115
116 +const normalizeHiddenDebugFlags = (argv: ReadonlyArray<string>): ReadonlyArray<string> => {
117 + const normalized: string[] = [...argv.slice(0, 2)];
118 + const args = argv.slice(2);
119 + let perfDebug: boolean | undefined;
120 + let toolDebug: boolean | undefined;
121 +
122 + for (const arg of args) {
123 + if (arg === '--perf-debug') {
124 + perfDebug = true;
125 + continue;
126 + }
127 + if (arg === '--tool-debug') {
128 + toolDebug = true;
129 + continue;
130 + }
131 + if (arg === '--perf-debug=false') {
132 + perfDebug = false;
133 + continue;
134 + }
135 + if (arg === '--tool-debug=false') {
136 + toolDebug = false;
137 + continue;
138 + }
139 + if (arg === '--perf-debug=true') {
140 + perfDebug = true;
141 + continue;
142 + }
143 + if (arg === '--tool-debug=true') {
144 + toolDebug = true;
145 + continue;
146 + }
147 + normalized.push(arg);
148 + }
149 +
150 + resetRuntimeDebugFlags();
151 + setRuntimeDebugFlags({
152 + ...(perfDebug === undefined ? {} : { perfDebug }),
153 + ...(toolDebug === undefined ? {} : { toolDebug }),
154 + });
155 +
156 + return normalized;
157 +};
158 +
159 const isRootHelp = (argv: ReadonlyArray<string>): boolean => {
160 const args = argv.slice(2);
161 return args.length === 1 && (args[0] === '--help' || args[0] === '-h');
162 };
163
164 +const isGenerateGraph = (argv: ReadonlyArray<string>): boolean => {
165 + const args = argv.slice(2);
166 + return args.length === 2 && args[0] === 'debug' && args[1] === 'generate-graph';
167 +};
168 +
169 +const isDebugApiInfo = (argv: ReadonlyArray<string>): boolean => {
170 + const args = argv.slice(2);
171 + return args.length === 2 && args[0] === 'debug' && args[1] === 'api-info';
172 +};
173 +
174 export const runWithConfig = Effect.gen(function* () {
175 const version = yield* getVersion;
176 const run = Command.run($cmd, {
@@ -116,10 +180,53 @@ export const runWithConfig = Effect.gen(function* () {
180 });
181
182 return (argv: ReadonlyArray<string>) => {
119 - const normalizedArgv = normalizeVersionShortFlag(argv);
183 + const normalizedArgv = normalizeHiddenDebugFlags(normalizeVersionShortFlag(argv));
184 if (isRootHelp(normalizedArgv)) {
185 return printRootHelp();
186 }
187 + if (isGenerateGraph(normalizedArgv)) {
188 + return Effect.sync(() => {
189 + process.stdout.write(`${JSON.stringify(renderCommandHintGraph(), null, 2)}\n`);
190 + });
191 + }
192 + if (isDebugApiInfo(normalizedArgv)) {
193 + return Effect.gen(function* () {
194 + const ui = yield* TerminalUI;
195 + const confirmed = yield* ui.confirm(
196 + 'This will print your current CLI API key and scoped identifiers to stdout. Continue?',
197 + { defaultValue: false }
198 + );
199 + if (!confirmed) {
200 + return yield* Effect.fail(new Error('Aborted printing API credentials.'));
201 + }
202 + const ctx = yield* ComposioUserContext;
203 + const apiKey = Option.getOrUndefined(ctx.data.apiKey);
204 + if (!apiKey) {
205 + return yield* Effect.fail(new Error('No user API key found in the current CLI session.'));
206 + }
207 + const orgId = Option.getOrUndefined(ctx.data.orgId);
208 + const consumerProject = yield* resolveCommandProject({ mode: 'consumer' }).pipe(
209 + Effect.mapError(formatResolveCommandProjectError),
210 + Effect.option
211 + );
212 + return yield* Effect.sync(() => {
213 + process.stdout.write(
214 + `${JSON.stringify(
215 + {
216 + apiKey,
217 + orgId: orgId ?? null,
218 + consumerUserId:
219 + Option.isSome(consumerProject) && consumerProject.value.projectType === 'CONSUMER'
220 + ? (consumerProject.value.consumerUserId ?? null)
221 + : null,
222 + },
223 + null,
224 + 2
225 + )}\n`
226 + );
227 + });
228 + });
229 + }
230 const executeHelpSlug = parseExecuteInputHelpSlug(normalizedArgv);
231 if (executeHelpSlug) {
232 return showToolsExecuteInputHelp(executeHelpSlug);
ts/packages/cli/src/commands/init.cmd.ts
+4 -4
@@ -230,7 +230,7 @@ export const initCmd = CliCommand.make(
230 const ui = yield* TerminalUI;
231 const proc = yield* NodeProcess;
232
233 - yield* ui.intro('composio init');
233 + yield* ui.intro('composio dev init');
234
235 const composioDir = path.join(proc.cwd, constants.PROJECT_COMPOSIO_DIR);
236
@@ -276,7 +276,7 @@ const initInteractiveFlow = (params: { composioDir: string; noBrowser: boolean;
276 yield* Effect.logDebug('Failed to list org projects:', e);
277 yield* ui.log.warn('Could not fetch projects from the server.');
278 yield* ui.log.info(
279 - 'Create a project at https://platform.composio.dev, then run `composio init` again.'
279 + 'Create a project at https://platform.composio.dev, then run `composio dev init` again.'
280 );
281 yield* ui.outro('');
282 return yield* Effect.fail(e);
@@ -287,7 +287,7 @@ const initInteractiveFlow = (params: { composioDir: string; noBrowser: boolean;
287 yield* Effect.logDebug('Failed to decode org projects response:', e);
288 yield* ui.log.warn('Unexpected response from the server.');
289 yield* ui.log.info(
290 - 'Create a project at https://platform.composio.dev, then run `composio init` again.'
290 + 'Create a project at https://platform.composio.dev, then run `composio dev init` again.'
291 );
292 yield* ui.outro('');
293 return yield* Effect.fail(e);
@@ -298,7 +298,7 @@ const initInteractiveFlow = (params: { composioDir: string; noBrowser: boolean;
298 if (orgProjects.data.length === 0) {
299 yield* ui.log.warn('No projects found for your organization.');
300 yield* ui.log.info(
301 - 'Create a project at https://platform.composio.dev, then run `composio init` again.'
301 + 'Create a project at https://platform.composio.dev, then run `composio dev init` again.'
302 );
303 yield* ui.outro('');
304 return;
ts/packages/cli/src/commands/login.cmd.ts
+17 -12
@@ -9,7 +9,9 @@ import {
9 } from 'src/services/composio-clients';
10 import { ComposioUserContext } from 'src/services/user-context';
11 import { TerminalUI } from 'src/services/terminal-ui';
12 +import { commandHintStep } from 'src/services/command-hints';
13 import { runOrgSelection } from 'src/effects/select-org-project';
14 +import { primeConsumerConnectedToolkitsCacheInBackground } from 'src/services/consumer-short-term-cache';
15
16 export const noBrowser = Options.boolean('no-browser').pipe(
17 Options.withDefault(false),
@@ -104,14 +106,15 @@ const storeCredentials = (params: {
106 }
107
108 yield* ctx.login(uakApiKey, orgId, testUserId);
109 + yield* primeConsumerConnectedToolkitsCacheInBackground({
110 + orgId,
111 + });
112
113 const email = sessionInfo?.org_member.email || fallbackEmail || undefined;
114 yield* ui.log.success(email ? `Logged in as ${email}` : 'Logged in successfully');
115 if (!skipHints) {
111 - yield* ui.log.info(
112 - 'Run `composio init` in your project directory to set up project context.'
113 - );
114 - yield* ui.log.info('To switch your default org later, run `composio manage orgs switch`.');
116 + yield* ui.log.info(commandHintStep('Set up developer project context', 'dev.init'));
117 + yield* ui.log.info(commandHintStep('Switch your default org later', 'manage.orgs.switch'));
118 }
119
120 // Emit structured JSON for piped/scripted consumption (agent-native)
@@ -228,6 +231,9 @@ const loginWithKey = (params: { key: string; noWait: boolean; skipOrgProjectPick
231 result.id,
232 testUserId ?? Option.getOrUndefined(ctx.data.testUserId)
233 );
234 + yield* primeConsumerConnectedToolkitsCacheInBackground({
235 + orgId: result.id,
236 + });
237 yield* ui.log.success(`Default org set to "${result.name}".`);
238 }
239 const finalOrgId = result?.id ?? xOrgId;
@@ -239,10 +245,8 @@ const loginWithKey = (params: { key: string; noWait: boolean; skipOrgProjectPick
245 org_name: finalOrgName,
246 })
247 );
242 - yield* ui.log.info(
243 - 'Run `composio init` in your project directory to set up project context.'
244 - );
245 - yield* ui.log.info('To switch your default org later, run `composio manage orgs switch`.');
248 + yield* ui.log.info(commandHintStep('Set up developer project context', 'dev.init'));
249 + yield* ui.log.info(commandHintStep('Switch your default org later', 'manage.orgs.switch'));
250 yield* ui.outro("You're all set!");
251 }
252 });
@@ -387,6 +391,9 @@ export const browserLogin = (params: {
391 result.id,
392 testUserId ?? Option.getOrUndefined(ctx.data.testUserId)
393 );
394 + yield* primeConsumerConnectedToolkitsCacheInBackground({
395 + orgId: result.id,
396 + });
397 yield* ui.log.success(`Default org set to "${result.name}".`);
398 }
399 const finalOrgId = result?.id ?? xOrgId;
@@ -398,10 +405,8 @@ export const browserLogin = (params: {
405 org_name: finalOrgName,
406 })
407 );
401 - yield* ui.log.info(
402 - 'Run `composio init` in your project directory to set up project context.'
403 - );
404 - yield* ui.log.info('To switch your default org later, run `composio manage orgs switch`.');
408 + yield* ui.log.info(commandHintStep('Set up developer project context', 'dev.init'));
409 + yield* ui.log.info(commandHintStep('Switch your default org later', 'manage.orgs.switch'));
410 yield* ui.outro("You're all set!");
411 }
412 });
ts/packages/cli/src/commands/logs-cmd/commands/logs.tools.cmd.ts
+4 -1
@@ -6,6 +6,7 @@ import { ComposioClientSingleton } from 'src/services/composio-clients';
6 import { clampLimit } from 'src/ui/clamp-limit';
7 import { parseCsv } from 'src/commands/triggers/parse-csv';
8 import { formatToolLogInfo, formatToolLogsTable } from '../format';
9 +import { commandHintStep } from 'src/services/command-hints';
10 import { toSearchParam } from '../utils';
11
12 type ToolLogFilterInput = {
@@ -223,7 +224,9 @@ export const logsCmd$Tools = Command.make(
224 const firstLogId = logs[0]?.id;
225 if (firstLogId) {
226 yield* ui.log.step(
226 - `To view full details for a log:\n> composio manage logs tools "${firstLogId}"`
227 + commandHintStep('To view full details for a log', 'dev.logs.tools', {
228 + logId: firstLogId,
229 + })
230 );
231 }
232
ts/packages/cli/src/commands/logs-cmd/commands/logs.triggers.cmd.ts
+4 -1
@@ -6,6 +6,7 @@ import { ComposioClientSingleton } from 'src/services/composio-clients';
6 import { clampLimit } from 'src/ui/clamp-limit';
7 import { parseCsv } from 'src/commands/triggers/parse-csv';
8 import { formatTriggerLogInfo, formatTriggerLogsTable } from '../format';
9 +import { commandHintStep } from 'src/services/command-hints';
10 import { toSearchParam } from '../utils';
11
12 const cursor = Options.text('cursor').pipe(
@@ -193,7 +194,9 @@ export const logsCmd$Triggers = Command.make(
194 const firstLogId = logs[0]?.id;
195 if (firstLogId) {
196 yield* ui.log.step(
196 - `To view full details for a log:\n> composio manage logs triggers "${firstLogId}"`
197 + commandHintStep('To view full details for a log', 'dev.logs.triggers', {
198 + logId: firstLogId,
199 + })
200 );
201 }
202
ts/packages/cli/src/commands/manage/manage.cmd.ts
+4 -8
@@ -1,37 +1,33 @@
1 import { Command } from '@effect/cli';
2 import { toolkitsCmd } from '../toolkits/toolkits.cmd';
3 -import { toolsCmd } from '../tools/tools.cmd';
3 import { authConfigsCmd } from '../auth-configs/auth-configs.cmd';
4 import { connectedAccountsCmd } from '../connected-accounts/connected-accounts.cmd';
5 import { triggersCmd } from '../triggers/triggers.cmd';
7 -import { logsCmd } from '../logs-cmd/logs.cmd';
6 import { orgsCmd } from '../orgs/orgs.cmd';
7 import { projectsCmd } from '../projects/projects.cmd';
8
9 /**
12 - * CLI entry point for management commands.
10 + * CLI entry point for developer management commands.
11 *
14 - * Groups toolkits, tools, auth-configs, connected-accounts, triggers, logs, orgs, and projects
12 + * Groups orgs, toolkits, connected-accounts, triggers, auth-configs, and projects
13 * under a single `composio manage` namespace.
14 *
15 * @example
16 * ```bash
17 * composio manage <command>
18 * composio manage toolkits list
21 - * composio manage tools search "send email"
19 + * composio manage projects list
20 * ```
21 */
22 export const manageCmd = Command.make('manage').pipe(
23 Command.withDescription(
26 - 'Developer/admin workflows: orgs, toolkits, tools, accounts, triggers, logs, auth configs, and deprecated project commands.'
24 + 'Manage your developer orgs, toolkits, connected accounts, triggers, auth configs, and projects.'
25 ),
26 Command.withSubcommands([
27 toolkitsCmd,
30 - toolsCmd,
28 authConfigsCmd,
29 connectedAccountsCmd,
30 triggersCmd,
34 - logsCmd,
31 orgsCmd,
32 projectsCmd,
33 ])
ts/packages/cli/src/commands/orgs/commands/orgs.switch.cmd.ts
+1 -1
@@ -31,7 +31,7 @@ export const orgsCmd$Switch = Command.make('switch', { orgId, limit }, ({ orgId,
31 }
32
33 yield* ui.note(
34 - 'This updates your default org for CLI commands. Use `composio init` for local developer project setup.',
34 + 'This updates your default org for CLI commands. Use `composio dev init` for local developer project setup.',
35 'Global defaults'
36 );
37
ts/packages/cli/src/commands/projects/commands/projects.list.cmd.ts
+2 -2
@@ -54,7 +54,7 @@ export const projectsCmd$List = Command.make('list', { orgId, limit }, ({ orgId,
54 if (projects.data.length === 0) {
55 yield* ui.log.warn('No projects found.');
56 yield* ui.outro(
57 - 'Hint: run `composio init` in a directory to bind it to a developer project.'
57 + 'Hint: run `composio dev init` in a directory to bind it to a developer project.'
58 );
59 return;
60 }
@@ -65,7 +65,7 @@ export const projectsCmd$List = Command.make('list', { orgId, limit }, ({ orgId,
65 yield* ui.log.step(lines.join('\n'));
66 yield* ui.outro(
67 [
68 - 'Hint: run `composio init` in a directory to bind it to a developer project.',
68 + 'Hint: run `composio dev init` in a directory to bind it to a developer project.',
69 'Run `composio manage orgs switch` to change your default org.',
70 ].join('\n')
71 );
ts/packages/cli/src/commands/projects/commands/projects.switch.cmd.ts
+1 -1
@@ -8,7 +8,7 @@ export const projectsCmd$Switch = Command.make('switch', {}).pipe(
8 Effect.gen(function* () {
9 const ui = yield* TerminalUI;
10 yield* ui.log.error(
11 - 'Global developer project switching is no longer supported. Run `composio init` in a directory to bind it to a developer project.'
11 + 'Global developer project switching is no longer supported. Run `composio dev init` in a directory to bind it to a developer project.'
12 );
13 })
14 )
ts/packages/cli/src/commands/projects/projects.cmd.ts
+1 -1
@@ -6,6 +6,6 @@ import { projectsCmd$Switch } from './commands/projects.switch.cmd';
6 * CLI entry point for project context commands.
7 */
8 export const projectsCmd = Command.make('projects').pipe(
9 - Command.withDescription('Manage default global project context.'),
9 + Command.withDescription('Inspect developer projects and project context helpers.'),
10 Command.withSubcommands([projectsCmd$List, projectsCmd$Switch])
11 );
ts/packages/cli/src/commands/root-help.ts
+85 -30
@@ -47,17 +47,43 @@ const BASIC_COMMANDS: ReadonlyArray<BasicCommand> = [
47 usage: 'logout',
48 },
49 {
50 - name: 'init',
51 - description: 'Initialize this directory with a developer project.',
52 - usage: 'init [--no-browser] [-y, --yes]',
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]',
54 options: [
54 - { name: '--no-browser', description: 'Skip opening browser for auth' },
55 - { name: '-y, --yes', description: 'Auto-select the default developer project' },
55 + {
56 + name: '<code>',
57 + description:
58 + 'Inline Bun ESNext code with injected execute(slug, data?) and search(query, options?) helpers',
59 + },
60 + {
61 + name: '-f, --file',
62 + description: 'Run a TS/JS file with the Bun runtime instead of inline code',
63 + },
64 + {
65 + name: '--dry-run',
66 + description: 'Preview execute(...) calls without running remote actions',
67 + },
68 + {
69 + name: '--skip-connection-check',
70 + description:
71 + 'Skip the short-lived linked-account fail-fast check if you just connected an account',
72 + },
73 + {
74 + name: '--skip-tool-params-check',
75 + description: 'Skip the local tool parameter/schema validation check',
76 + },
77 + {
78 + name: '--no-verify',
79 + description:
80 + 'Skip both the linked-account fail-fast check and the local tool parameter check',
81 + },
82 ],
83 },
84 {
85 name: 'search',
60 - description: 'Search tools by use case across toolkits/apps.',
86 + description: 'Semantic search for tools by use case across all toolkits/apps.',
87 usage: 'search <query> [--toolkits text] [--limit integer]',
88 options: [
89 { name: '<query>', description: 'Semantic use-case query (e.g. "send emails")' },
@@ -65,13 +91,54 @@ const BASIC_COMMANDS: ReadonlyArray<BasicCommand> = [
91 { name: '--limit', description: 'Number of results per page (1-1000)' },
92 ],
93 },
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>',
98 + options: [
99 + {
100 + name: 'list <toolkit>',
101 + description: 'Non-semantic per-toolkit listing; use this when you already know the toolkit',
102 + },
103 + {
104 + name: 'info <slug>',
105 + description:
106 + 'Print a brief summary and cache the same raw schema used by execute --get-schema',
107 + },
108 + ],
109 + },
110 {
111 name: 'execute',
70 - description: 'Execute a tool.',
71 - usage: 'execute <slug> [-d, --data text]',
112 + description: 'Execute a tool, preview it with --dry-run, or fetch its input schema.',
113 + usage:
114 + 'execute <slug> [-d, --data text] [--dry-run] [--get-schema] [--skip-connection-check] [--skip-tool-params-check] [--no-verify]',
115 options: [
116 { name: '<slug>', description: 'Tool slug (e.g. "GITHUB_CREATE_ISSUE")' },
74 - { name: '-d, --data', description: 'JSON arguments, @file, or - for stdin' },
117 + {
118 + name: '-d, --data',
119 + description:
120 + 'JSON or JS-style object arguments, e.g. -d \'{ repo: "foo" }\', @file, or - for stdin',
121 + },
122 + { name: '--dry-run', description: 'Validate and preview the tool call without executing it' },
123 + {
124 + name: '--get-schema',
125 + description:
126 + 'Fetch and print the raw cached schema; tools info shows the same schema with a brief summary',
127 + },
128 + {
129 + name: '--skip-connection-check',
130 + description:
131 + 'Skip the short-lived linked-account fail-fast check if you just connected an account',
132 + },
133 + {
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',
141 + },
142 ],
143 },
144 {
@@ -83,28 +150,14 @@ const BASIC_COMMANDS: ReadonlyArray<BasicCommand> = [
150 { name: '--no-browser', description: 'Skip auto-opening the browser' },
151 ],
152 },
86 - {
87 - name: 'listen',
88 - description: 'Listen for trigger events.',
89 - usage:
90 - 'listen [--toolkits text] [--trigger-id text] [--user-id text] [--max-events integer] [--forward text] [--out text]',
91 - options: [
92 - { name: '--toolkits', description: 'Filter by toolkit slugs, comma-separated' },
93 - { name: '--trigger-id', description: 'Filter by trigger id' },
94 - { name: '--user-id', description: 'Filter by user id' },
95 - { name: '--max-events', description: 'Stop after N matching events' },
96 - {
97 - name: '--forward',
98 - description: 'Forward events to URL (signed with COMPOSIO_WEBHOOK_SECRET)',
99 - },
100 - { name: '--out', description: 'Append events to file' },
101 - { name: '--json', description: 'Show raw event payload as JSON' },
102 - { name: '--table', description: 'Show compact table rows' },
103 - ],
104 - },
153 ];
154
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.',
160 + },
161 {
162 name: 'generate',
163 description:
@@ -113,7 +166,7 @@ const ADVANCED_COMMANDS: ReadonlyArray<{ name: string; description: string }> =
166 {
167 name: 'manage',
168 description:
116 - 'Developer/admin workflows: orgs, toolkits, triggers, auth configs, logs, and deprecated project commands.',
169 + 'Manage your developer orgs, toolkits, connected accounts, triggers, auth configs, and projects.',
170 },
171 ];
172
@@ -146,7 +199,9 @@ export function printRootHelp(): Effect.Effect<void> {
199
200 const lines: string[] = [
201 '',
149 - 'Connect AI agents to external tools. `search`, `link`, and `execute` use your org consumer project by default. `init`, `listen`, and `manage` use developer project context.',
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.',
205 '',
206 bold('USAGE'),
207 ` ${name} <command> [options]`,
ts/packages/cli/src/commands/run.cmd.ts new
+363
@@ -0,0 +1,363 @@
1 +import * as fs from 'node:fs';
2 +import * as os from 'node:os';
3 +import * as path from 'node:path';
4 +import process from 'node:process';
5 +import { Args, Command, Options } from '@effect/cli';
6 +import { Effect, Option } from 'effect';
7 +import { ts } from 'ts-morph';
8 +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 +
13 +const file = Options.text('file').pipe(
14 + Options.withAlias('f'),
15 + Options.withDescription('Run a TS/JS file instead of inline code'),
16 + Options.optional
17 +);
18 +
19 +const dryRun = Options.boolean('dry-run').pipe(Options.withDefault(false));
20 +const skipConnectionCheck = Options.boolean('skip-connection-check').pipe(
21 + Options.withDefault(false)
22 +);
23 +const skipToolParamsCheck = Options.boolean('skip-tool-params-check').pipe(
24 + Options.withDefault(false)
25 +);
26 +const noVerify = Options.boolean('no-verify').pipe(Options.withDefault(false));
27 +
28 +const args = Args.repeated(Args.text({ name: 'arg' })).pipe(
29 + Args.withDescription('Inline code followed by arguments, or just arguments when using --file')
30 +);
31 +
32 +const withArgDelimiter = (args: ReadonlyArray<string>) => (args.length > 0 ? ['--', ...args] : []);
33 +
34 +export const extractInlineExecuteToolSlugs = (source: string): ReadonlyArray<string> => {
35 + if (!source.trim()) {
36 + return [];
37 + }
38 +
39 + const parsed = ts.createSourceFile(
40 + 'composio-run-inline.ts',
41 + source,
42 + ts.ScriptTarget.Latest,
43 + true,
44 + ts.ScriptKind.TSX
45 + );
46 + const slugs = new Set<string>();
47 +
48 + const visit = (node: ts.Node) => {
49 + if (
50 + ts.isCallExpression(node) &&
51 + ts.isIdentifier(node.expression) &&
52 + node.expression.text === 'execute'
53 + ) {
54 + const [slugArg] = node.arguments;
55 + if (slugArg && ts.isStringLiteralLike(slugArg)) {
56 + slugs.add(slugArg.text);
57 + }
58 + }
59 +
60 + ts.forEachChild(node, visit);
61 + };
62 +
63 + visit(parsed);
64 + return [...slugs];
65 +};
66 +
67 +export const inferCliInvocationPrefix = (
68 + argv: ReadonlyArray<string> = process.argv
69 +): ReadonlyArray<string> => {
70 + const entrypoint = argv[1];
71 + if (!entrypoint) {
72 + return [process.execPath];
73 + }
74 +
75 + // Compiled Bun binaries report an internal $bunfs entrypoint which cannot be
76 + // re-executed as a real filesystem path. In that case the binary itself is
77 + // the CLI entrypoint.
78 + if (entrypoint.startsWith('/$bunfs/')) {
79 + return [process.execPath];
80 + }
81 +
82 + const resolvedEntrypoint = path.resolve(entrypoint);
83 + return fs.existsSync(resolvedEntrypoint)
84 + ? [process.execPath, resolvedEntrypoint]
85 + : [process.execPath];
86 +};
87 +
88 +type RunHelperContext = {
89 + readonly apiKey?: string;
90 + readonly baseURL?: string;
91 + readonly webURL?: string;
92 + readonly orgId?: string;
93 + readonly consumerUserId?: string;
94 + readonly consumerProjectId?: string;
95 + readonly consumerProjectName?: string;
96 + readonly perfDebug?: boolean;
97 + readonly toolDebug?: boolean;
98 + readonly dryRun?: boolean;
99 + readonly skipConnectionCheck?: boolean;
100 + readonly skipToolParamsCheck?: boolean;
101 + readonly noVerify?: boolean;
102 +};
103 +
104 +export const buildRunHelpersSource = (
105 + cliPrefix: ReadonlyArray<string>,
106 + context: RunHelperContext = {}
107 +): string =>
108 + [
109 + `const cliPrefix = ${JSON.stringify(cliPrefix)};`,
110 + `const helperContext = ${JSON.stringify(context)};`,
111 + '',
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 + '',
210 + ].join('\n');
211 +
212 +const createRunHelpersPreloadFile = (
213 + cliPrefix: ReadonlyArray<string>,
214 + context: RunHelperContext
215 +) => {
216 + const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'composio-run-'));
217 + const preloadPath = path.join(directory, 'globals.mjs');
218 + fs.writeFileSync(preloadPath, buildRunHelpersSource(cliPrefix, context), 'utf8');
219 + return { directory, preloadPath };
220 +};
221 +
222 +export const buildRunCommand = ({
223 + file,
224 + args,
225 + preloadPath,
226 +}: {
227 + file: Option.Option<string>;
228 + args: ReadonlyArray<string>;
229 + preloadPath: string;
230 +}) => {
231 + const base = [process.execPath, '--preload', preloadPath];
232 + if (Option.isSome(file)) {
233 + return [...base, 'run', file.value, ...withArgDelimiter(args)];
234 + }
235 +
236 + const [inlineCode, ...scriptArgs] = args;
237 + if (inlineCode) {
238 + return [...base, '--eval', inlineCode, ...withArgDelimiter(scriptArgs)];
239 + }
240 +
241 + throw new Error('Provide inline code or use --file to run a script file.');
242 +};
243 +
244 +const resolveRunHelperContext = () =>
245 + Effect.gen(function* () {
246 + const userContext = yield* ComposioUserContext;
247 + const apiKey = Option.getOrUndefined(userContext.data.apiKey);
248 + const orgId = Option.getOrUndefined(userContext.data.orgId);
249 + const baseContext = {
250 + apiKey,
251 + baseURL: userContext.data.baseURL,
252 + webURL: userContext.data.webURL,
253 + orgId,
254 + } satisfies RunHelperContext;
255 +
256 + if (!apiKey || !orgId) {
257 + return baseContext;
258 + }
259 +
260 + const consumerProject = yield* resolveCommandProject({ mode: 'consumer' }).pipe(Effect.option);
261 + if (Option.isNone(consumerProject) || consumerProject.value.projectType !== 'CONSUMER') {
262 + return baseContext;
263 + }
264 +
265 + return {
266 + ...baseContext,
267 + consumerUserId: consumerProject.value.consumerUserId,
268 + consumerProjectId: consumerProject.value.projectId,
269 + consumerProjectName: consumerProject.value.projectName,
270 + } satisfies RunHelperContext;
271 + });
272 +
273 +export const runCmd = Command.make('run', {
274 + file,
275 + dryRun,
276 + skipConnectionCheck,
277 + skipToolParamsCheck,
278 + noVerify,
279 + args,
280 +}).pipe(
281 + Command.withDescription(
282 + [
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]',
289 + '',
290 + '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)'`,
296 + ' composio run --file ./script.ts -- hello world',
297 + '',
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.',
305 + '',
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.',
312 + '',
313 + 'Advanced:',
314 + ' import { $ } from "bun"',
315 + ' await $`${process.execPath} manage toolkits list`',
316 + ].join('\n')
317 + ),
318 + Command.withHandler(
319 + ({ file, dryRun, skipConnectionCheck, skipToolParamsCheck, noVerify, args }) =>
320 + Effect.gen(function* () {
321 + const perfDebug = isPerfDebugEnabled();
322 + const toolDebug = isToolDebugEnabled();
323 + if (Option.isNone(file)) {
324 + const [inlineCode] = args;
325 + const preloadSlugs = extractInlineExecuteToolSlugs(inlineCode ?? '');
326 + if (preloadSlugs.length > 0) {
327 + yield* warmToolInputDefinitions(preloadSlugs).pipe(
328 + Effect.catchAll(() => Effect.void),
329 + Effect.forkDaemon
330 + );
331 + }
332 + }
333 +
334 + const preload = createRunHelpersPreloadFile(inferCliInvocationPrefix(), {
335 + ...(yield* resolveRunHelperContext()),
336 + perfDebug,
337 + toolDebug,
338 + dryRun,
339 + skipConnectionCheck,
340 + skipToolParamsCheck,
341 + noVerify,
342 + });
343 + try {
344 + const child = Bun.spawn({
345 + cmd: buildRunCommand({ file, args, preloadPath: preload.preloadPath }),
346 + env: {
347 + ...process.env,
348 + BUN_BE_BUN: '1',
349 + ...(perfDebug ? { COMPOSIO_PERF_DEBUG: '1' } : {}),
350 + ...(toolDebug ? { COMPOSIO_TOOL_DEBUG: '1' } : {}),
351 + },
352 + stdio: ['inherit', 'inherit', 'inherit'],
353 + });
354 +
355 + const exitCode = yield* Effect.promise(() => child.exited);
356 + fs.rmSync(preload.directory, { recursive: true, force: true });
357 + process.exit(exitCode);
358 + } finally {
359 + fs.rmSync(preload.directory, { recursive: true, force: true });
360 + }
361 + })
362 + )
363 +);
ts/packages/cli/src/commands/toolkits/commands/toolkits.info.cmd.ts
+1 -1
@@ -163,7 +163,7 @@ export const toolkitsCmd$Info = Command.make(
163
164 // Next step hint
165 yield* ui.log.step(
166 - `To list tools in this toolkit:\n> composio manage tools list --toolkits "${toolkit.slug}"`
166 + `To list tools in this toolkit:\n> composio tools list "${toolkit.slug}"`
167 );
168
169 yield* ui.output(formatToolkitInfoJson(toolkit, detailedToolkit, allDetails));
ts/packages/cli/src/commands/toolkits/commands/toolkits.list.cmd.ts
+1 -1
@@ -83,7 +83,7 @@ export const toolkitsCmd$List = Command.make(
83
84 if (Option.isSome(connected) && Option.isNone(resolvedUserId)) {
85 yield* ui.log.warn(
86 - '`--connected` requires a user id. Use `--user-id` or run `composio init`.'
86 + '`--connected` requires a user id. Use `--user-id` or run `composio dev init`.'
87 );
88 }
89
ts/packages/cli/src/commands/tools/commands/tools.execute.cmd.ts
+806 -64
@@ -1,25 +1,37 @@
1 import { Args, Command, Options } from '@effect/cli';
2 +import * as fs from 'node:fs';
3 +import * as path from 'node:path';
4 import util from 'node:util';
3 -import { Effect, Option, Either } from 'effect';
5 +import { Effect, Option, Either, Exit, Fiber, Cause } from 'effect';
6 import { FileSystem } from '@effect/platform';
5 -import { JSONParse } from 'src/effects/json';
7 +import { parse as parseJsonWithComments } from 'comment-json';
8 +import { encodingForModel } from 'js-tiktoken';
9 import { redact } from 'src/ui/redact';
10 import { readStdin, readStdinIfPiped } from 'src/effects/read-stdin';
11 import { requireAuth } from 'src/effects/require-auth';
12 +import {
13 + getCachedToolInputDefinition,
14 + getOrFetchToolInputDefinition,
15 + invalidateToolInputDefinition,
16 + refreshToolInputDefinitionIfVersionChanged,
17 + ToolInputValidationError,
18 + validateToolInputArguments,
19 + validateToolInputArgumentsWithDefinition,
20 +} from 'src/services/tool-input-validation';
21 import { TerminalUI } from 'src/services/terminal-ui';
22 import {
23 ActionExecuteConnectedAccountNotFoundError,
24 ToolsExecutor,
25 } from 'src/services/tools-executor';
14 -import type { ToolExecuteParams } from 'src/services/tools-executor';
26 +import type { ToolExecuteParams, ToolExecuteResponse } from 'src/services/tools-executor';
27 import { ComposioToolkitsRepository } from 'src/services/composio-clients';
28 import { ComposioUserContext } from 'src/services/user-context';
29 +import { ProjectContext } from 'src/services/project-context';
30 import {
31 extractApiErrorDetails,
32 extractMessage,
33 extractSlug,
34 } from 'src/utils/api-error-extraction';
22 -import { bold } from 'src/ui/colors';
35 import { handleHttpServerError } from 'src/effects/handle-http-error';
36 import { formatToolInputParameters } from '../format';
37 import { ComposioClientSingleton } from 'src/services/composio-clients';
@@ -27,6 +39,12 @@ import {
39 resolveCommandProject,
40 formatResolveCommandProjectError,
41 } from 'src/services/command-project';
42 +import { commandHintStep } from 'src/services/command-hints';
43 +import { isPerfDebugEnabled, isToolDebugEnabled } from 'src/services/runtime-debug-flags';
44 +import {
45 + getFreshConsumerConnectedToolkitsFromCache,
46 + refreshConsumerConnectedToolkitsCache,
47 +} from 'src/services/consumer-short-term-cache';
48
49 const slug = Args.text({ name: 'slug' }).pipe(
50 Args.withDescription('Tool slug (e.g. "GITHUB_CREATE_ISSUE")')
@@ -48,6 +66,16 @@ const projectName = Options.text('project-name').pipe(
66 Options.withDescription('Developer project name override for this command')
67 );
68
69 +const getSchema = Options.boolean('get-schema').pipe(Options.withDefault(false));
70 +const dryRun = Options.boolean('dry-run').pipe(Options.withDefault(false));
71 +const skipConnectionCheck = Options.boolean('skip-connection-check').pipe(
72 + Options.withDefault(false)
73 +);
74 +const skipToolParamsCheck = Options.boolean('skip-tool-params-check').pipe(
75 + Options.withDefault(false)
76 +);
77 +const noVerify = Options.boolean('no-verify').pipe(Options.withDefault(false));
78 +
79 const resolveInput = (input: Option.Option<string>) =>
80 Effect.gen(function* () {
81 const fs = yield* FileSystem.FileSystem;
@@ -78,15 +106,26 @@ const resolveInput = (input: Option.Option<string>) =>
106
107 const parseArguments = (raw: string) =>
108 Effect.gen(function* () {
81 - const parsed = (yield* JSONParse(raw).pipe(
82 - Effect.mapError(
83 - () =>
84 - new Error('Invalid JSON input. Provide a JSON object, e.g. -d "{\\"key\\":\\"value\\"}"')
85 - )
86 - )) as unknown;
109 + 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 + },
121 + catch: () =>
122 + new Error(
123 + 'Invalid JSON input. Provide JSON or a JS-style object literal, e.g. -d \'{ "key": "value" }\''
124 + ),
125 + });
126 if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
127 return yield* Effect.fail(
89 - new Error('Expected a JSON object for tool arguments, e.g. -d "{\\"key\\":\\"value\\"}"')
128 + new Error('Expected a JSON object for tool arguments, e.g. -d \'{ "key": "value" }\'')
129 );
130 }
131 return parsed as Record<string, unknown>;
@@ -100,25 +139,40 @@ const toolkitFromToolSlug = (toolSlug: string): string | undefined => {
139 return prefix;
140 };
141
103 -const connectionTips = (toolSlug: string, surface: 'root' | 'manage') => {
142 +const connectionTips = (toolSlug: string, surface: 'root' | 'manage' | 'dev') => {
143 const toolkit = toolkitFromToolSlug(toolSlug);
144 + const executeStep =
145 + surface === 'dev'
146 + ? commandHintStep('Retry', 'dev.execute', {
147 + slug: toolSlug,
148 + userId: '<user-id>',
149 + data: '...',
150 + })
151 + : commandHintStep('Retry', 'root.execute', { slug: toolSlug, data: '...' });
152 if (!toolkit) {
106 - return `Retry: ${bold(`composio execute ${toolSlug} ...`)}`;
153 + return executeStep;
154 }
155 return [
109 - `Link the toolkit first: ${bold(
110 - surface === 'root'
111 - ? `composio link ${toolkit}`
112 - : `composio manage connected-accounts link ${toolkit} --user-id "<user-id>"`
113 - )}`,
114 - `Then retry: ${bold(
115 - surface === 'root'
116 - ? `composio execute ${toolSlug} ...`
117 - : `composio manage tools execute ${toolSlug} ...`
118 - )}`,
156 + commandHintStep(
157 + 'Link the toolkit first',
158 + surface === 'dev' ? 'manage.connectedAccounts.link' : 'root.link',
159 + surface === 'dev' ? { toolkit, userId: '<user-id>' } : { toolkit }
160 + ),
161 + executeStep.replace('Retry:', 'Then retry:'),
162 ].join('\n');
163 };
164
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 +
176 const ciRedactReplacer = (_key: string, value: unknown): unknown => {
177 if (typeof value !== 'string') return value;
178 if (_key === 'logId') return redact({ value, prefix: 'log_' });
@@ -151,6 +205,83 @@ const redactRequestId = (value: object): object => {
205 };
206 };
207
208 +const EXECUTE_INLINE_OUTPUT_TOKEN_THRESHOLD = 10_000;
209 +let executeOutputEncoder: ReturnType<typeof encodingForModel> | undefined;
210 +
211 +const getExecuteOutputEncoder = () => {
212 + if (!executeOutputEncoder) {
213 + executeOutputEncoder = encodingForModel('gpt-4o');
214 + }
215 + return executeOutputEncoder;
216 +};
217 +
218 +type StoredExecuteOutputSummary = {
219 + readonly successful: true;
220 + readonly error: null;
221 + readonly logId: string;
222 + readonly storedInFile: true;
223 + readonly tokenCount: number;
224 + readonly outputFilePath: string;
225 +};
226 +
227 +const serializeExecuteOutput = (result: unknown): string =>
228 + JSON.stringify(result, ciRedactReplacer, 2);
229 +
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');
238 +
239 + return {
240 + successful: true,
241 + error: null,
242 + logId: '',
243 + storedInFile: true,
244 + tokenCount: getExecuteOutputEncoder().encode(json).length,
245 + outputFilePath,
246 + };
247 +};
248 +
249 +const perfDebugEpoch = Date.now();
250 +const perfDebugLog = (label: string, details: Record<string, unknown> = {}) => {
251 + if (!isPerfDebugEnabled()) return;
252 + console.error(
253 + `[perf] ${JSON.stringify({
254 + phase: 'event',
255 + label,
256 + elapsedMs: Date.now() - perfDebugEpoch,
257 + ...details,
258 + })}`
259 + );
260 +};
261 +const toolDebugLog = (label: string, details: Record<string, unknown> = {}) => {
262 + if (!isToolDebugEnabled()) return;
263 + console.error(`[tool-debug] ${JSON.stringify({ label, ...details })}`);
264 +};
265 +
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>();
@@ -191,7 +322,10 @@ export const showToolsExecuteInputHelp = (toolSlug: string) =>
322 'services/HttpServerError',
323 handleHttpServerError(ui, {
324 fallbackMessage: `Tool "${toolSlug}" not found.`,
194 - hint: 'Browse available tools:\n> composio manage tools list',
325 + hint: [
326 + commandHintStep('Browse available toolkits', 'manage.toolkits.list'),
327 + commandHintStep('Then list tools', 'root.tools.list'),
328 + ].join('\n'),
329 fallbackValue: Option.none(),
330 searchForSuggestions: () =>
331 repo.searchTools({ search: toolSlug, limit: 3 }).pipe(
@@ -219,10 +353,21 @@ export const showToolsExecuteInputHelp = (toolSlug: string) =>
353 const handleExecutionError = (
354 ui: TerminalUI,
355 error: unknown,
222 - context: { toolSlug: string; surface: 'root' | 'manage' }
356 + context: { toolSlug: string; surface: 'root' | 'manage' | 'dev' }
357 ) =>
358 Effect.gen(function* () {
359 const normalized = normalizeError(error);
360 + if (normalized instanceof ToolInputValidationError) {
361 + yield* ui.log.error(`Input validation failed for ${context.toolSlug}`);
362 + yield* ui.note(
363 + [`Schema: ${normalized.schemaPath}`, ...normalized.issues.map(issue => `- ${issue}`)].join(
364 + '\n'
365 + ),
366 + 'Tool schema validation'
367 + );
368 + return { error: normalized.message, slug: context.toolSlug };
369 + }
370 +
371 const connAccountDetails =
372 normalized instanceof ActionExecuteConnectedAccountNotFoundError
373 ? normalized.details
@@ -233,8 +378,20 @@ const handleExecutionError = (
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);
389 + if (toolkitFromToolSlug(context.toolSlug)) {
390 + yield* ui.note(connectionTips(context.toolSlug, context.surface), 'Tips');
391 + }
392 + return { error: rewrittenMessage, slug: slugValue ?? context.toolSlug };
393 + }
394 +
395 yield* ui.log.error(message);
396
397 const detailsObject =
@@ -260,81 +417,488 @@ class ToolExecutionError {
417 constructor(readonly message: string) {}
418 }
419
263 -const runToolsExecute = (params: {
420 +type CachedValidationDecision =
421 + | { readonly status: 'valid' | 'stale' }
422 + | { readonly status: 'fail'; readonly error: unknown };
423 +
424 +type ValidationState = {
425 + readonly cacheHit: boolean;
426 + readonly validationGuard: Effect.Effect<never, unknown>;
427 + readonly awaitCachedValidationDecision: Effect.Effect<CachedValidationDecision, never> | null;
428 +};
429 +
430 +type CachedDefinition = {
431 + readonly schemaPath: string;
432 + readonly schema: Record<string, unknown>;
433 + readonly version: string | null;
434 +} | null;
435 +
436 +const validationGuardFromFiber = (validationFiber: Fiber.RuntimeFiber<unknown, unknown>) =>
437 + Fiber.await(validationFiber).pipe(
438 + Effect.flatMap(
439 + Exit.match({
440 + onFailure: cause => {
441 + const defect = Cause.failureOption(cause);
442 + if (Option.isSome(defect) && defect.value instanceof ToolInputValidationError) {
443 + return Effect.failCause(cause);
444 + }
445 + return Effect.never;
446 + },
447 + onSuccess: () => Effect.never,
448 + })
449 + )
450 + );
451 +
452 +const spawnBackgroundValidationGuard = (params: {
453 + readonly slug: string;
454 + readonly args: Record<string, unknown>;
455 + readonly resolvedProject: {
456 + readonly orgId: string;
457 + readonly projectId: string;
458 + };
459 +}) =>
460 + Effect.gen(function* () {
461 + perfDebugLog('execute.validation.background_spawn', { slug: params.slug });
462 + const validationFiber = yield* validateToolInputArguments(params.slug, params.args, {
463 + orgId: params.resolvedProject.orgId,
464 + projectId: params.resolvedProject.projectId,
465 + }).pipe(Effect.forkDaemon);
466 + perfDebugLog('execute.validation.background_spawned', { slug: params.slug });
467 + return validationGuardFromFiber(validationFiber);
468 + });
469 +
470 +const initializeValidationState = (params: {
471 + readonly slug: string;
472 + readonly args: Record<string, unknown>;
473 + readonly cachedDefinition: CachedDefinition;
474 + readonly resolvedProject: {
475 + readonly orgId: string;
476 + readonly projectId: string;
477 + };
478 +}) =>
479 + Effect.gen(function* () {
480 + if (!params.cachedDefinition) {
481 + perfDebugLog('execute.validation.cache_miss', { slug: params.slug });
482 + return {
483 + cacheHit: false,
484 + validationGuard: Effect.never,
485 + awaitCachedValidationDecision: null,
486 + } satisfies ValidationState;
487 + }
488 + const cachedDefinition = params.cachedDefinition;
489 +
490 + perfDebugLog('execute.validation.cache_hit', {
491 + slug: params.slug,
492 + cachedVersion: cachedDefinition.version,
493 + });
494 + const versionCheckFiber = yield* refreshToolInputDefinitionIfVersionChanged(
495 + params.slug,
496 + cachedDefinition.version,
497 + {
498 + orgId: params.resolvedProject.orgId,
499 + projectId: params.resolvedProject.projectId,
500 + }
501 + ).pipe(
502 + Effect.tap(result =>
503 + Effect.sync(() =>
504 + perfDebugLog('execute.validation.version_check_done', {
505 + slug: params.slug,
506 + cachedVersion: cachedDefinition.version,
507 + latestVersion: result.latestVersion,
508 + isStale: result.isStale,
509 + })
510 + )
511 + ),
512 + Effect.either,
513 + Effect.forkDaemon
514 + );
515 + const cachedValidationDecisionFiber = yield* Effect.gen(function* () {
516 + perfDebugLog('execute.validation.cached_start', { slug: params.slug });
517 + const result = yield* validateToolInputArgumentsWithDefinition(
518 + params.slug,
519 + params.args,
520 + cachedDefinition
521 + ).pipe(Effect.either);
522 + perfDebugLog('execute.validation.cached_end', {
523 + slug: params.slug,
524 + successful: Either.isRight(result),
525 + });
526 + if (Either.isRight(result)) {
527 + return { status: 'valid' as const };
528 + }
529 +
530 + const freshnessEither = yield* Fiber.join(versionCheckFiber);
531 + const isStale = Either.isRight(freshnessEither) && freshnessEither.right.isStale;
532 + perfDebugLog('execute.validation.cached_failed', {
533 + slug: params.slug,
534 + cacheStillCurrent: !isStale,
535 + });
536 + return isStale
537 + ? { status: 'stale' as const }
538 + : { status: 'fail' as const, error: result.left };
539 + }).pipe(Effect.forkDaemon);
540 + const awaitCachedValidationDecision = Fiber.join(
541 + cachedValidationDecisionFiber
542 + ) as Effect.Effect<CachedValidationDecision, never>;
543 +
544 + return {
545 + cacheHit: true,
546 + awaitCachedValidationDecision,
547 + validationGuard: awaitCachedValidationDecision.pipe(
548 + Effect.flatMap(decision => {
549 + if (decision.status === 'fail') {
550 + return Effect.fail(decision.error);
551 + }
552 +
553 + return Effect.never;
554 + })
555 + ),
556 + } satisfies ValidationState;
557 + });
558 +
559 +type DryRunSummary = {
560 + readonly successful: true;
561 + readonly dryRun: true;
562 + readonly slug: string;
563 + readonly arguments: Record<string, unknown>;
564 + readonly userId: string;
565 + readonly schemaPath?: string;
566 + readonly schemaVersion?: string | null;
567 +};
568 +
569 +type RunToolsExecuteParams = {
570 slug: string;
571 data: Option.Option<string>;
572 userId: Option.Option<string>;
573 projectName: Option.Option<string>;
268 - rootOnly: boolean;
269 -}) =>
574 + surface: 'root' | 'manage' | 'dev';
575 + projectMode: 'consumer' | 'developer';
576 + getSchema: boolean;
577 + dryRun: boolean;
578 + skipConnectionCheck: boolean;
579 + skipToolParamsCheck: boolean;
580 + noVerify: boolean;
581 +};
582 +
583 +type ResolvedExecuteContext = {
584 + readonly ui: TerminalUI;
585 + readonly executor: ToolsExecutor;
586 + readonly resolvedProject: {
587 + readonly orgId: string;
588 + readonly projectId: string;
589 + readonly projectType: 'CONSUMER' | 'DEVELOPER';
590 + readonly consumerUserId?: string;
591 + };
592 + readonly args: Record<string, unknown>;
593 + readonly resolvedUserId: string;
594 + readonly executeParams: ToolExecuteParams;
595 +};
596 +
597 +const emitCachedSchema = (
598 + ui: TerminalUI,
599 + slug: string,
600 + definition: {
601 + readonly version: string | null;
602 + readonly schemaPath: string;
603 + readonly schema: Record<string, unknown>;
604 + }
605 +) =>
606 Effect.gen(function* () {
271 - if (!(yield* requireAuth)) return;
607 + yield* ui.log.message(
608 + `Schema saved, inspect keys like: jq '{required: (.inputSchema.required // []), keys: (.inputSchema.properties | keys)}' ${definition.schemaPath}`
609 + );
610 + yield* ui.output(
611 + JSON.stringify(
612 + {
613 + slug,
614 + version: definition.version,
615 + schemaPath: definition.schemaPath,
616 + inputSchema: definition.schema,
617 + },
618 + null,
619 + 2
620 + )
621 + );
622 + });
623
624 +const resolveExecuteContext = (params: RunToolsExecuteParams) =>
625 + Effect.gen(function* () {
626 + const resolvedProject = yield* resolveCommandProject({
627 + mode: params.projectMode,
628 + projectName:
629 + params.surface === 'root' ? undefined : Option.getOrUndefined(params.projectName),
630 + }).pipe(Effect.mapError(formatResolveCommandProjectError));
631 const ui = yield* TerminalUI;
632 const executor = yield* ToolsExecutor;
633 const clientSingleton = yield* ComposioClientSingleton;
634 const userContext = yield* ComposioUserContext;
635 + const projectContext = yield* ProjectContext;
636
637 const input = yield* resolveInput(params.data);
638 const args = yield* parseArguments(input);
280 - const resolvedProject = yield* resolveCommandProject({
281 - mode: 'consumer',
282 - projectName: params.rootOnly ? undefined : Option.getOrUndefined(params.projectName),
283 - }).pipe(Effect.mapError(formatResolveCommandProjectError));
639 + const localProjectContext = yield* projectContext.resolve.pipe(
640 + Effect.catchAll(() => Effect.succeed(Option.none()))
641 + );
642 + const localTestUserId = Option.flatMap(localProjectContext, keys => keys.testUserId);
643 const resolvedUserId =
644 resolvedProject.projectType === 'CONSUMER'
645 ? Option.fromNullable(resolvedProject.consumerUserId)
646 : Option.match(params.userId, {
647 onSome: value => Option.some(value),
289 - onNone: () => userContext.data.testUserId,
648 + onNone: () => Option.orElse(localTestUserId, () => userContext.data.testUserId),
649 });
650 +
651 if (Option.isNone(resolvedUserId)) {
652 return yield* Effect.fail(
653 new Error(
294 - 'Missing user id. Provide --user-id or run composio login to set global test_user_id.'
654 + params.projectMode === 'developer'
655 + ? 'Missing user id. Provide --user-id or run `composio dev init` to set a playground test user id.'
656 + : 'Missing user id. Provide --user-id or run composio login to set global test_user_id.'
657 )
658 );
659 }
660 +
661 const client = yield* clientSingleton.getFor({
662 orgId: resolvedProject.orgId,
663 projectId: resolvedProject.projectId,
664 });
665
303 - const executeParams: ToolExecuteParams = {
304 - userId: resolvedUserId.value,
305 - arguments: args,
306 - client,
307 - };
666 + return {
667 + ui,
668 + executor,
669 + resolvedProject,
670 + args,
671 + resolvedUserId: resolvedUserId.value,
672 + executeParams: {
673 + userId: resolvedUserId.value,
674 + arguments: args,
675 + client,
676 + },
677 + } satisfies ResolvedExecuteContext;
678 + });
679
309 - yield* ui.useMakeSpinner(`Executing tool "${params.slug}"...`, spinner =>
680 +const runConnectedToolkitFailFast = (params: {
681 + readonly slug: string;
682 + readonly surface: 'root' | 'manage' | 'dev';
683 + readonly ui: TerminalUI;
684 + readonly resolvedProject: ResolvedExecuteContext['resolvedProject'];
685 + readonly resolvedUserId: string;
686 + readonly skipConnectionCheck: boolean;
687 + readonly noVerify: boolean;
688 +}) =>
689 + Effect.gen(function* () {
690 + if (params.skipConnectionCheck || params.noVerify) {
691 + perfDebugLog('execute.connected_toolkits.skipped', {
692 + slug: params.slug,
693 + reason: params.noVerify ? 'no-verify' : 'skip-connection-check',
694 + });
695 + return;
696 + }
697 + if (params.resolvedProject.projectType !== 'CONSUMER') return;
698 +
699 + perfDebugLog('execute.connected_toolkits.refresh_start', {
700 + slug: params.slug,
701 + orgId: params.resolvedProject.orgId,
702 + consumerUserId: params.resolvedUserId,
703 + });
704 + yield* refreshConsumerConnectedToolkitsCache({
705 + orgId: params.resolvedProject.orgId,
706 + consumerUserId: params.resolvedUserId,
707 + }).pipe(
708 + Effect.tap(() =>
709 + Effect.sync(() =>
710 + perfDebugLog('execute.connected_toolkits.refresh_end', {
711 + slug: params.slug,
712 + orgId: params.resolvedProject.orgId,
713 + consumerUserId: params.resolvedUserId,
714 + successful: true,
715 + })
716 + )
717 + ),
718 + Effect.catchAll(() =>
719 + Effect.sync(() =>
720 + perfDebugLog('execute.connected_toolkits.refresh_end', {
721 + slug: params.slug,
722 + orgId: params.resolvedProject.orgId,
723 + consumerUserId: params.resolvedUserId,
724 + successful: false,
725 + })
726 + )
727 + ),
728 + Effect.forkDaemon,
729 + Effect.asVoid
730 + );
731 +
732 + const toolkit = toolkitFromToolSlug(params.slug);
733 + if (!toolkit) return;
734 +
735 + const cachedToolkits = yield* getFreshConsumerConnectedToolkitsFromCache({
736 + orgId: params.resolvedProject.orgId,
737 + consumerUserId: params.resolvedUserId,
738 + });
739 + perfDebugLog(
740 + Option.isSome(cachedToolkits)
741 + ? 'execute.connected_toolkits.cache_hit'
742 + : 'execute.connected_toolkits.cache_miss',
743 + {
744 + slug: params.slug,
745 + toolkit,
746 + orgId: params.resolvedProject.orgId,
747 + consumerUserId: params.resolvedUserId,
748 + cachedToolkits: Option.isSome(cachedToolkits) ? cachedToolkits.value : undefined,
749 + }
750 + );
751 +
752 + if (Option.isSome(cachedToolkits) && !cachedToolkits.value.includes(toolkit)) {
753 + perfDebugLog('execute.connected_toolkits.fail_fast', {
754 + slug: params.slug,
755 + toolkit,
756 + orgId: params.resolvedProject.orgId,
757 + consumerUserId: params.resolvedUserId,
758 + });
759 + const message = `Toolkit "${toolkit}" is not connected for this user (cached within the last 5 minutes). If you just connected the account, use --skip-connection-check.`;
760 + yield* params.ui.log.error(message);
761 + yield* params.ui.note(connectionTips(params.slug, params.surface), 'Tips');
762 + yield* params.ui.output(
763 + JSON.stringify(
764 + {
765 + successful: false,
766 + error: message,
767 + slug: params.slug,
768 + },
769 + ciRedactReplacer,
770 + 2
771 + )
772 + );
773 + return yield* Effect.fail(new ToolExecutionError(message));
774 + }
775 + });
776 +
777 +const runExecuteWithSpinner = (params: {
778 + readonly slug: string;
779 + readonly surface: 'root' | 'manage' | 'dev';
780 + readonly dryRun: boolean;
781 + readonly ui: TerminalUI;
782 + readonly executor: ToolsExecutor;
783 + readonly resolvedProject: ResolvedExecuteContext['resolvedProject'];
784 + readonly args: Record<string, unknown>;
785 + readonly resolvedUserId: string;
786 + readonly executeParams: ToolExecuteParams;
787 + readonly skipToolParamsCheck: boolean;
788 + readonly noVerify: boolean;
789 +}) =>
790 + Effect.gen(function* () {
791 + const verificationDisabled = params.noVerify || params.skipToolParamsCheck;
792 + const cachedDefinition = verificationDisabled
793 + ? null
794 + : yield* getCachedToolInputDefinition(params.slug);
795 + const validationState = verificationDisabled
796 + ? ({
797 + cacheHit: false,
798 + validationGuard: Effect.never,
799 + awaitCachedValidationDecision: null,
800 + } satisfies ValidationState)
801 + : yield* initializeValidationState({
802 + slug: params.slug,
803 + args: params.args,
804 + cachedDefinition,
805 + resolvedProject: params.resolvedProject,
806 + });
807 +
808 + yield* params.ui.useMakeSpinner(`Executing tool "${params.slug}"...`, spinner =>
809 Effect.gen(function* () {
311 - const resultEither = yield* executor
312 - .execute(params.slug, executeParams)
810 + let validationGuard = validationState.validationGuard;
811 + if (!verificationDisabled && !validationState.cacheHit) {
812 + validationGuard = yield* spawnBackgroundValidationGuard({
813 + slug: params.slug,
814 + args: params.args,
815 + resolvedProject: params.resolvedProject,
816 + });
817 + }
818 +
819 + if (params.dryRun) {
820 + const definition = verificationDisabled
821 + ? null
822 + : (cachedDefinition ??
823 + (yield* getOrFetchToolInputDefinition(params.slug, {
824 + orgId: params.resolvedProject.orgId,
825 + projectId: params.resolvedProject.projectId,
826 + })));
827 + if (definition) {
828 + yield* validateToolInputArgumentsWithDefinition(params.slug, params.args, definition);
829 + }
830 + const summary: DryRunSummary = {
831 + successful: true,
832 + dryRun: true,
833 + slug: params.slug,
834 + arguments: params.args,
835 + userId: params.resolvedUserId,
836 + schemaPath: definition?.schemaPath,
837 + schemaVersion: definition?.version,
838 + };
839 + yield* spinner.stop('Dry run successful');
840 + yield* params.ui.log.message(
841 + verificationDisabled
842 + ? 'No tool was executed. Local validation was skipped.'
843 + : 'No tool was executed. Arguments were validated locally only.'
844 + );
845 + yield* params.ui.output(JSON.stringify(summary, ciRedactReplacer, 2));
846 + return;
847 + }
848 +
849 + perfDebugLog('execute.tool_call.start', { slug: params.slug });
850 + const resultEither = yield* params.executor
851 + .execute(params.slug, params.executeParams)
852 + .pipe(Effect.raceFirst(validationGuard))
853 .pipe(Effect.either);
854 + toolDebugLog('execute_result', {
855 + slug: params.slug,
856 + result: Either.isRight(resultEither) ? resultEither.right : resultEither.left,
857 + });
858 + perfDebugLog('execute.tool_call.end', {
859 + slug: params.slug,
860 + successful: Either.isRight(resultEither),
861 + });
862
863 if (Either.isLeft(resultEither)) {
864 + yield* invalidateToolInputDefinition(params.slug).pipe(
865 + Effect.catchAll(() => Effect.void)
866 + );
867 yield* spinner.error();
317 - const summary = yield* handleExecutionError(ui, resultEither.left, {
868 + const summary = yield* handleExecutionError(params.ui, resultEither.left, {
869 toolSlug: params.slug,
319 - surface: params.rootOnly ? 'root' : 'manage',
870 + surface: params.surface,
871 });
321 - yield* ui.output(JSON.stringify({ successful: false, ...summary }, ciRedactReplacer, 2));
872 + yield* params.ui.output(
873 + JSON.stringify({ successful: false, ...summary }, ciRedactReplacer, 2)
874 + );
875 return yield* Effect.fail(new ToolExecutionError(summary.error));
876 }
877
878 const result = resultEither.right;
879 + if (validationState.awaitCachedValidationDecision) {
880 + const decision = yield* validationState.awaitCachedValidationDecision;
881 + if (decision.status === 'fail') {
882 + perfDebugLog('execute.validation.post_success_failure_ignored', {
883 + slug: params.slug,
884 + });
885 + }
886 + }
887
888 if (!result.successful) {
889 + yield* invalidateToolInputDefinition(params.slug).pipe(
890 + Effect.catchAll(() => Effect.void)
891 + );
892 const logId = result.logId
893 ? ` (logId: ${redact({ value: result.logId, prefix: 'log_' })})`
894 : '';
895 yield* spinner.error(`Execution failed${logId}`);
896
333 - const summary = yield* handleExecutionError(ui, result.error ?? result, {
897 + const summary = yield* handleExecutionError(params.ui, result.error ?? result, {
898 toolSlug: params.slug,
335 - surface: params.rootOnly ? 'root' : 'manage',
899 + surface: params.surface,
900 });
337 - yield* ui.output(JSON.stringify(result, ciRedactReplacer, 2));
901 + yield* params.ui.output(JSON.stringify(result, ciRedactReplacer, 2));
902 return yield* Effect.fail(new ToolExecutionError(summary.error));
903 }
904
@@ -342,45 +906,223 @@ const runToolsExecute = (params: {
906 ? ` (logId: ${redact({ value: result.logId, prefix: 'log_' })})`
907 : '';
908 yield* spinner.stop(`Execution successful${logId}`);
345 - yield* ui.log.message(`Response\n${JSON.stringify(result, ciRedactReplacer, 2)}`);
346 - yield* ui.output(JSON.stringify(result, ciRedactReplacer, 2));
909 + const output = prepareExecuteOutput(result);
910 + if (output.kind === 'file') {
911 + yield* params.ui.log.message(
912 + `Response stored in ${output.summary.outputFilePath} (${output.summary.tokenCount} tokens)`
913 + );
914 + yield* params.ui.output(JSON.stringify(output.summary, ciRedactReplacer, 2));
915 + return;
916 + }
917 +
918 + yield* params.ui.log.message(`Response\n${output.json}`);
919 + yield* params.ui.output(output.json);
920 })
921 );
922 });
923
924 +const runToolsExecute = (params: RunToolsExecuteParams) =>
925 + Effect.gen(function* () {
926 + if (!(yield* requireAuth)) return;
927 +
928 + const context = yield* resolveExecuteContext(params);
929 + if (params.getSchema) {
930 + const definition = yield* getOrFetchToolInputDefinition(params.slug, {
931 + orgId: context.resolvedProject.orgId,
932 + projectId: context.resolvedProject.projectId,
933 + });
934 + yield* emitCachedSchema(context.ui, params.slug, definition);
935 + return;
936 + }
937 +
938 + yield* runConnectedToolkitFailFast({
939 + slug: params.slug,
940 + surface: params.surface,
941 + ui: context.ui,
942 + resolvedProject: context.resolvedProject,
943 + resolvedUserId: context.resolvedUserId,
944 + skipConnectionCheck: params.skipConnectionCheck,
945 + noVerify: params.noVerify,
946 + });
947 + toolDebugLog('execute_params', {
948 + slug: params.slug,
949 + userId: context.resolvedUserId,
950 + arguments: context.args,
951 + projectId: context.resolvedProject.projectId,
952 + orgId: context.resolvedProject.orgId,
953 + });
954 + perfDebugLog('execute.prepare', {
955 + slug: params.slug,
956 + surface: params.surface,
957 + projectMode: params.projectMode,
958 + });
959 + yield* runExecuteWithSpinner({
960 + slug: params.slug,
961 + surface: params.surface,
962 + dryRun: params.dryRun,
963 + ui: context.ui,
964 + executor: context.executor,
965 + resolvedProject: context.resolvedProject,
966 + args: context.args,
967 + resolvedUserId: context.resolvedUserId,
968 + executeParams: context.executeParams,
969 + skipToolParamsCheck: params.skipToolParamsCheck,
970 + noVerify: params.noVerify,
971 + });
972 + });
973 +
974 export const toolsCmd$Execute = Command.make(
975 'execute',
353 - { slug, data, userId, projectName },
354 - ({ slug, data, userId, projectName }) =>
355 - runToolsExecute({ slug, data, userId, projectName, rootOnly: false })
976 + {
977 + slug,
978 + data,
979 + userId,
980 + projectName,
981 + getSchema,
982 + dryRun,
983 + skipConnectionCheck,
984 + skipToolParamsCheck,
985 + noVerify,
986 + },
987 + ({
988 + slug,
989 + data,
990 + userId,
991 + projectName,
992 + getSchema,
993 + dryRun,
994 + skipConnectionCheck,
995 + skipToolParamsCheck,
996 + noVerify,
997 + }) =>
998 + runToolsExecute({
999 + slug,
1000 + data,
1001 + userId,
1002 + projectName,
1003 + surface: 'manage',
1004 + projectMode: 'consumer',
1005 + getSchema,
1006 + dryRun,
1007 + skipConnectionCheck,
1008 + skipToolParamsCheck,
1009 + noVerify,
1010 + })
1011 ).pipe(
1012 Command.withDescription(
1013 [
359 - 'Execute a tool by slug with JSON arguments.',
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.',
1019 + '',
1020 + 'Examples:',
1021 + ' 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',
1027 '',
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>',
1032 ].join('\n')
1033 )
1034 );
1035
368 -export const rootToolsCmd$Execute = Command.make('execute', { slug, data }, ({ slug, data }) =>
369 - runToolsExecute({
370 - slug,
371 - data,
372 - userId: Option.none(),
373 - projectName: Option.none(),
374 - rootOnly: true,
375 - })
1036 +export const rootToolsCmd$Execute = Command.make(
1037 + 'execute',
1038 + { slug, data, getSchema, dryRun, skipConnectionCheck, skipToolParamsCheck, noVerify },
1039 + ({ slug, data, getSchema, dryRun, skipConnectionCheck, skipToolParamsCheck, noVerify }) =>
1040 + runToolsExecute({
1041 + slug,
1042 + data,
1043 + userId: Option.none(),
1044 + projectName: Option.none(),
1045 + surface: 'root',
1046 + projectMode: 'consumer',
1047 + getSchema,
1048 + dryRun,
1049 + skipConnectionCheck,
1050 + skipToolParamsCheck,
1051 + noVerify,
1052 + })
1053 ).pipe(
1054 Command.withDescription(
1055 [
379 - 'Execute a tool by slug with JSON arguments.',
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.',
1061 + '',
1062 + 'Examples:',
1063 + ' 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',
1069 '',
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>',
1074 ].join('\n')
1075 )
1076 );
1077 +
1078 +export const devToolsCmd$Execute = Command.make(
1079 + 'execute',
1080 + {
1081 + slug,
1082 + data,
1083 + userId,
1084 + projectName,
1085 + getSchema,
1086 + dryRun,
1087 + skipConnectionCheck,
1088 + skipToolParamsCheck,
1089 + noVerify,
1090 + },
1091 + ({
1092 + slug,
1093 + data,
1094 + userId,
1095 + projectName,
1096 + getSchema,
1097 + dryRun,
1098 + skipConnectionCheck,
1099 + skipToolParamsCheck,
1100 + noVerify,
1101 + }) =>
1102 + runToolsExecute({
1103 + slug,
1104 + data,
1105 + userId,
1106 + projectName,
1107 + surface: 'dev',
1108 + projectMode: 'developer',
1109 + getSchema,
1110 + dryRun,
1111 + skipConnectionCheck,
1112 + skipToolParamsCheck,
1113 + noVerify,
1114 + })
1115 +).pipe(
1116 + Command.withDescription(
1117 + [
1118 + 'Execute a tool with your playground test user id against your developer project auth configs.',
1119 + 'Uses --user-id when provided, otherwise falls back to your local or global playground test user id.',
1120 + 'Arguments are validated against cached tool schemas in `~/.composio/tool_definitions/` when available.',
1121 + '',
1122 + 'Examples:',
1123 + ' composio dev execute GMAIL_SEND_EMAIL -d \'{ recipient_email: "a@b.com", body: "Hello" }\'',
1124 + ' composio dev execute GMAIL_SEND_EMAIL --dry-run -d \'{ recipient_email: "a@b.com", body: "Hello" }\'',
1125 + ' composio dev execute GMAIL_SEND_EMAIL --get-schema',
1126 + ].join('\n')
1127 + )
1128 +);
ts/packages/cli/src/commands/tools/commands/tools.info.cmd.ts
+47 -18
@@ -4,7 +4,9 @@ import { ComposioToolkitsRepository } from 'src/services/composio-clients';
4 import { TerminalUI } from 'src/services/terminal-ui';
5 import { requireAuth } from 'src/effects/require-auth';
6 import { handleHttpServerError } from 'src/effects/handle-http-error';
7 -import { formatToolInfo } from '../format';
7 +import { getOrFetchToolInputDefinition } from 'src/services/tool-input-validation';
8 +import { bold } from 'src/ui/colors';
9 +import { commandHintExample, commandHintStep } from 'src/services/command-hints';
10
11 const slug = Args.text({ name: 'slug' }).pipe(
12 Args.withDescription('Tool slug (e.g. "GMAIL_SEND_EMAIL")'),
@@ -16,7 +18,7 @@ const slug = Args.text({ name: 'slug' }).pipe(
18 *
19 * @example
20 * ```bash
19 - * composio manage tools info "GMAIL_SEND_EMAIL"
21 + * composio tools info "GMAIL_SEND_EMAIL"
22 * ```
23 */
24 export const toolsCmd$Info = Command.make('info', { slug }, ({ slug }) =>
@@ -29,9 +31,7 @@ export const toolsCmd$Info = Command.make('info', { slug }, ({ slug }) =>
31 // Missing slug guard
32 if (Option.isNone(slug)) {
33 yield* ui.log.warn('Missing required argument: <slug>');
32 - yield* ui.log.step(
33 - 'Try specifying a tool slug, e.g.:\n> composio manage tools info "GMAIL_SEND_EMAIL"'
34 - );
34 + yield* ui.log.step('Try specifying a tool slug, e.g.:\n> composio tools info "GMAIL_SEND_EMAIL"');
35 return;
36 }
37
@@ -45,14 +45,17 @@ export const toolsCmd$Info = Command.make('info', { slug }, ({ slug }) =>
45 'services/HttpServerError',
46 handleHttpServerError(ui, {
47 fallbackMessage: `Tool "${slugValue}" not found.`,
48 - hint: 'Browse available tools:\n> composio manage tools list',
48 + hint: [
49 + commandHintStep('Browse available toolkits', 'manage.toolkits.list'),
50 + commandHintStep('Then list tools', 'root.tools.list'),
51 + ].join('\n'),
52 fallbackValue: Option.none(),
53 searchForSuggestions: () =>
54 repo.searchTools({ search: slugValue, limit: 3 }).pipe(
55 Effect.map(r =>
56 r.items.map(s => ({
57 label: `${s.slug} — ${s.description}`,
55 - command: `> composio manage tools info "${s.slug}"`,
58 + command: `> composio tools info "${s.slug}"`,
59 }))
60 )
61 ),
@@ -65,17 +68,43 @@ export const toolsCmd$Info = Command.make('info', { slug }, ({ slug }) =>
68 }
69
70 const tool = toolOpt.value;
71 + const definition = yield* getOrFetchToolInputDefinition(slugValue);
72
69 - yield* ui.note(formatToolInfo(tool), `Tool: ${tool.name}`);
73 + const summary = [
74 + `${bold('Slug:')} ${tool.slug}`,
75 + `${bold('Name:')} ${tool.name}`,
76 + `${bold('Toolkit:')} ${tool.toolkit.slug}`,
77 + `${bold('Version:')} ${definition.version ?? '-'}`,
78 + `${bold('Description:')} ${tool.description}`,
79 + `${bold('Schema Cache:')} ${definition.schemaPath}`,
80 + ].join('\n');
81
71 - // Next step hint
72 - const toolkitSlug = tool.toolkit.slug;
73 - if (toolkitSlug) {
74 - yield* ui.log.step(
75 - `To list more tools in this toolkit:\n> composio manage tools list --toolkits "${toolkitSlug}"`
76 - );
77 - }
78 -
79 - yield* ui.output(JSON.stringify(tool, null, 2));
82 + yield* ui.note(summary, `Tool: ${tool.name}`);
83 + yield* ui.log.step(
84 + `Inspect schema with jq:\n> jq '{required: (.inputSchema.required // []), keys: (.inputSchema.properties | keys)}' "${definition.schemaPath}"`
85 + );
86 + yield* ui.log.step(
87 + `Then execute it:\n> ${commandHintExample('root.execute', {
88 + slug: tool.slug,
89 + })} --dry-run`
90 + );
91 + yield* ui.output(
92 + JSON.stringify(
93 + {
94 + slug: tool.slug,
95 + name: tool.name,
96 + description: tool.description,
97 + toolkit: tool.toolkit.slug,
98 + version: definition.version,
99 + schemaPath: definition.schemaPath,
100 + },
101 + null,
102 + 2
103 + )
104 + );
105 })
81 -).pipe(Command.withDescription('View details of a specific tool.'));
106 +).pipe(
107 + Command.withDescription(
108 + 'View a brief summary of a tool and cache the same raw schema used by `composio execute --get-schema`.'
109 + )
110 +);
ts/packages/cli/src/commands/tools/commands/tools.list.cmd.ts
+17 -23
@@ -1,4 +1,4 @@
1 -import { Command, Options } from '@effect/cli';
1 +import { Args, Command, Options } from '@effect/cli';
2 import { Effect, Option } from 'effect';
3 import { ComposioToolkitsRepository } from 'src/services/composio-clients';
4 import { TerminalUI } from 'src/services/terminal-ui';
@@ -6,15 +6,12 @@ import { requireAuth } from 'src/effects/require-auth';
6 import { clampLimit } from 'src/ui/clamp-limit';
7 import { formatToolsTable, formatToolsJson } from '../format';
8
9 -const query = Options.text('query').pipe(
10 - Options.withDescription('Text search by name, slug, or description'),
11 - Options.optional
9 +const toolkit = Args.text({ name: 'toolkit' }).pipe(
10 + Args.withDescription('Toolkit slug to list tools for (e.g. "gmail")')
11 );
12
14 -const toolkits = Options.text('toolkits').pipe(
15 - Options.withDescription(
16 - 'Filter by toolkit slugs, comma-separated (e.g. "gmail" or "gmail,slack")'
17 - ),
13 +const query = Options.text('query').pipe(
14 + Options.withDescription('Text search by name, slug, or description'),
15 Options.optional
16 );
17
@@ -29,19 +26,19 @@ const limit = Options.integer('limit').pipe(
26 );
27
28 /**
32 - * List available tools with optional filters.
29 + * List available tools for a toolkit with optional filters.
30 *
31 * @example
32 * ```bash
36 - * composio manage tools list --toolkits "gmail"
37 - * composio manage tools list --query "send email" --toolkits "gmail"
38 - * composio manage tools list --tags "important" --limit 10
33 + * composio tools list gmail
34 + * composio tools list gmail --query "send email"
35 + * composio tools list gmail --tags "important" --limit 10
36 * ```
37 */
38 export const toolsCmd$List = Command.make(
39 'list',
43 - { query, toolkits, tags, limit },
44 - ({ query, toolkits, tags, limit }) =>
40 + { toolkit, query, tags, limit },
41 + ({ toolkit, query, tags, limit }) =>
42 Effect.gen(function* () {
43 if (!(yield* requireAuth)) return;
44
@@ -54,17 +51,16 @@ export const toolsCmd$List = Command.make(
51 'Fetching tools...',
52 repo.searchTools({
53 search: Option.getOrUndefined(query),
57 - toolkit_slug: Option.getOrUndefined(toolkits),
54 + toolkit_slug: toolkit,
55 tags: Option.getOrUndefined(tags),
56 limit: clampedLimit,
57 })
58 );
59
60 if (result.items.length === 0) {
64 - const hint = Option.isSome(toolkits)
65 - ? `No tools found in toolkit "${toolkits.value}". Verify the toolkit slug with:\n> composio manage toolkits list`
66 - : 'No tools found. Try broadening your search.';
67 - yield* ui.log.warn(hint);
61 + yield* ui.log.warn(
62 + `No tools found in toolkit "${toolkit}". Verify the toolkit slug with:\n> composio manage toolkits list`
63 + );
64 return;
65 }
66
@@ -80,11 +76,9 @@ export const toolsCmd$List = Command.make(
76 // Next step hint
77 const firstSlug = result.items[0]?.slug;
78 if (firstSlug) {
83 - yield* ui.log.step(
84 - `To view details of a tool:\n> composio manage tools info "${firstSlug}"`
85 - );
79 + yield* ui.log.step(`To inspect a tool:\n> composio tools info "${firstSlug}"`);
80 }
81
82 yield* ui.output(formatToolsJson(result.items));
83 })
90 -).pipe(Command.withDescription('List available tools.'));
84 +).pipe(Command.withDescription('List available tools for a toolkit.'));
ts/packages/cli/src/commands/tools/commands/tools.search.cmd.ts
+36 -9
@@ -13,6 +13,8 @@ import {
13 resolveCommandProject,
14 formatResolveCommandProjectError,
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
19 const query = Args.text({ name: 'query' }).pipe(
20 Args.withDescription(
@@ -90,6 +92,12 @@ const runToolsSearch = (params: {
92 orgId: resolvedProject.orgId,
93 projectId: resolvedProject.projectId,
94 });
95 + if (resolvedProject.projectType === 'CONSUMER') {
96 + yield* primeConsumerConnectedToolkitsCacheInBackground({
97 + orgId: resolvedProject.orgId,
98 + consumerUserId: resolvedUserId.value,
99 + });
100 + }
101 const { sessionId } = yield* resolveToolRouterSession(client, resolvedUserId.value, {
102 toolkits: toolkitList,
103 });
@@ -169,12 +177,22 @@ const runToolsSearch = (params: {
177
178 if (firstSlug) {
179 const executeHint = params.rootOnly
172 - ? `> composio execute "${firstSlug}" ${firstDataArg}`
173 - : `> composio manage tools execute "${firstSlug}" --user-id "<user-id>" ${firstDataArg}`;
180 + ? commandHintStep('Execute a tool', 'root.execute', {
181 + slug: firstSlug,
182 + data: firstDataArg,
183 + })
184 + : commandHintStep('Execute a tool', 'dev.execute', {
185 + slug: firstSlug,
186 + userId: '<user-id>',
187 + data: firstDataArg,
188 + });
189 const linkHint = params.rootOnly
175 - ? `> composio link <toolkit>`
176 - : `> composio manage connected-accounts link <toolkit> --user-id "<user-id>"`;
177 - yield* ui.log.step(['Hints:', executeHint, linkHint].join('\n'));
190 + ? commandHintStep('Link an account', 'root.link', { toolkit: '<toolkit>' })
191 + : commandHintStep('Link an account', 'manage.connectedAccounts.link', {
192 + toolkit: '<toolkit>',
193 + userId: '<user-id>',
194 + });
195 + yield* ui.log.step([executeHint, linkHint].join('\n'));
196 }
197
198 if (searchResponse.error) {
@@ -186,16 +204,23 @@ const runToolsSearch = (params: {
204 cta.push({
205 action: 'Execute a tool',
206 command: params.rootOnly
189 - ? `composio execute "${firstSlug}" ${firstDataArg}`
190 - : `composio manage tools execute "${firstSlug}" --user-id "<user-id>" ${firstDataArg}`,
207 + ? commandHintExample('root.execute', { slug: firstSlug, data: firstDataArg })
208 + : commandHintExample('dev.execute', {
209 + slug: firstSlug,
210 + userId: '<user-id>',
211 + data: firstDataArg,
212 + }),
213 });
214 }
215 if (firstToolkit) {
216 cta.push({
217 action: 'Connect a user account',
218 command: params.rootOnly
197 - ? `composio link ${String(firstToolkit).toLowerCase()}`
198 - : `composio manage connected-accounts link ${String(firstToolkit).toLowerCase()} --user-id "<user-id>"`,
219 + ? commandHintExample('root.link', { toolkit: String(firstToolkit).toLowerCase() })
220 + : commandHintExample('manage.connectedAccounts.link', {
221 + toolkit: String(firstToolkit).toLowerCase(),
222 + userId: '<user-id>',
223 + }),
224 });
225 }
226
@@ -217,6 +242,7 @@ export const toolsCmd$Search = Command.make(
242 'Semantically search tools by use case; returns best-fit tools plus recommended usage guidance.',
243 '',
244 'Related:',
245 + ' composio run \'const result = await execute("TOOL_SLUG", { ... }); console.log(result)\'',
246 ' composio link <toolkit>',
247 " composio execute <slug> -d '{}'",
248 ].join('\n')
@@ -241,6 +267,7 @@ export const rootToolsCmd$Search = Command.make(
267 'Semantically search tools by use case; returns best-fit tools plus recommended usage guidance.',
268 '',
269 'Related:',
270 + ' composio run \'const result = await execute("TOOL_SLUG", { ... }); console.log(result)\'',
271 ' composio link <toolkit>',
272 " composio execute <slug> -d '{}'",
273 ].join('\n')
ts/packages/cli/src/commands/tools/tools.cmd.ts
+3 -13
@@ -1,18 +1,8 @@
1 import { Command } from '@effect/cli';
2 import { toolsCmd$List } from './commands/tools.list.cmd';
3 import { toolsCmd$Info } from './commands/tools.info.cmd';
4 -import { toolsCmd$Search } from './commands/tools.search.cmd';
5 -import { toolsCmd$Execute } from './commands/tools.execute.cmd';
4
7 -/**
8 - * CLI entry point for tool discovery commands.
9 - *
10 - * @example
11 - * ```bash
12 - * composio manage tools <command>
13 - * ```
14 - */
15 -export const toolsCmd = Command.make('tools').pipe(
16 - Command.withDescription('Discover and inspect Composio tools.'),
17 - Command.withSubcommands([toolsCmd$List, toolsCmd$Info, toolsCmd$Search, toolsCmd$Execute])
5 +export const rootToolsCmd = Command.make('tools').pipe(
6 + Command.withDescription('Browse and inspect tools before executing them.'),
7 + Command.withSubcommands([toolsCmd$List, toolsCmd$Info])
8 );
ts/packages/cli/src/commands/triggers/commands/triggers.listen.cmd.ts
+5 -1
@@ -340,4 +340,8 @@ export const triggersCmd$Listen = Command.make(
340 yield* Effect.raceFirst(listenEffect, Deferred.await(stopWhenDone));
341 yield* ui.outro(`Stopped after receiving ${matchingEvents} matching events.`);
342 })
343 -).pipe(Command.withDescription('Listen to realtime trigger events for your project.'));
343 +).pipe(
344 + Command.withDescription(
345 + 'Listen to realtime trigger events for your developer project and optionally forward them into your local dev environment.'
346 + )
347 +);
ts/packages/cli/src/commands/whoami.cmd.ts
+3 -2
@@ -2,6 +2,7 @@ import { Command } from '@effect/cli';
2 import { Effect, Option } from 'effect';
3 import { ComposioUserContext } from 'src/services/user-context';
4 import { TerminalUI } from 'src/services/terminal-ui';
5 +import { commandHintStep } from 'src/services/command-hints';
6
7 /**
8 * CLI command to display your account information.
@@ -36,8 +37,8 @@ export const whoamiCmd = Command.make('whoami', {}).pipe(
37 );
38 yield* ui.log.step(
39 [
39 - 'To switch orgs:\n> composio manage orgs switch',
40 - 'To get API keys:\n> composio init (in your project)',
40 + commandHintStep('To switch orgs', 'manage.orgs.switch'),
41 + commandHintStep('To set up developer project context', 'dev.init'),
42 ].join('\n\n')
43 );
44 yield* ui.output(
ts/packages/cli/src/services/command-hints.ts new
+118
@@ -0,0 +1,118 @@
1 +type HintParams = Readonly<Record<string, string | undefined>>;
2 +
3 +const getParam = (params: HintParams | undefined, key: string, fallback: string) =>
4 + params?.[key]?.trim() ? params[key]! : fallback;
5 +
6 +export type CommandHintId =
7 + | 'root.search'
8 + | 'root.tools.list'
9 + | 'root.tools.info'
10 + | 'root.execute'
11 + | 'root.execute.getSchema'
12 + | 'root.link'
13 + | 'dev.init'
14 + | 'dev.execute'
15 + | 'dev.execute.getSchema'
16 + | 'dev.logs.tools'
17 + | 'dev.logs.triggers'
18 + | 'manage.orgs.switch'
19 + | 'manage.projects.list'
20 + | 'manage.toolkits.list'
21 + | 'manage.connectedAccounts.link'
22 + | 'manage.authConfigs.list';
23 +
24 +type CommandHintNode = {
25 + readonly example: (params?: HintParams) => string;
26 + readonly links?: ReadonlyArray<CommandHintId>;
27 +};
28 +
29 +export const COMMAND_HINTS: Record<CommandHintId, CommandHintNode> = {
30 + 'root.search': {
31 + example: params => `composio search "${getParam(params, 'query', '<query>')}"`,
32 + links: ['root.execute', 'root.link', 'root.tools.list'],
33 + },
34 + 'root.tools.list': {
35 + example: params => `composio tools list "${getParam(params, 'toolkit', '<toolkit>')}"`,
36 + links: ['root.tools.info', 'root.execute'],
37 + },
38 + 'root.tools.info': {
39 + example: params => `composio tools info "${getParam(params, 'slug', '<slug>')}"`,
40 + links: ['root.execute.getSchema', 'root.execute'],
41 + },
42 + 'root.execute': {
43 + example: params =>
44 + `composio execute "${getParam(params, 'slug', '<slug>')}" ${getParam(params, 'data', "-d '{}'")}`.trim(),
45 + links: ['root.link', 'root.execute.getSchema'],
46 + },
47 + 'root.execute.getSchema': {
48 + example: params => `composio execute "${getParam(params, 'slug', '<slug>')}" --get-schema`,
49 + links: ['root.execute', 'root.tools.info'],
50 + },
51 + 'root.link': {
52 + example: params => `composio link ${getParam(params, 'toolkit', '<toolkit>')}`,
53 + links: ['root.execute'],
54 + },
55 + 'dev.init': {
56 + example: () => 'composio dev init',
57 + links: ['dev.execute', 'dev.logs.tools', 'dev.logs.triggers'],
58 + },
59 + 'dev.execute': {
60 + example: params =>
61 + `composio dev execute "${getParam(params, 'slug', '<slug>')}" --user-id "${getParam(params, 'userId', '<user-id>')}" ${getParam(params, 'data', "-d '{}'")}`.trim(),
62 + links: ['manage.connectedAccounts.link', 'dev.init', 'dev.execute.getSchema'],
63 + },
64 + 'dev.execute.getSchema': {
65 + example: params =>
66 + `composio dev execute "${getParam(params, 'slug', '<slug>')}" --get-schema`,
67 + links: ['dev.execute'],
68 + },
69 + 'dev.logs.tools': {
70 + example: params =>
71 + `composio dev logs tools "${getParam(params, 'logId', '<log_id>')}"`,
72 + },
73 + 'dev.logs.triggers': {
74 + example: params =>
75 + `composio dev logs triggers "${getParam(params, 'logId', '<log_id>')}"`,
76 + },
77 + 'manage.orgs.switch': {
78 + example: () => 'composio manage orgs switch',
79 + links: ['dev.init', 'manage.projects.list'],
80 + },
81 + 'manage.projects.list': {
82 + example: () => 'composio manage projects list',
83 + links: ['dev.init'],
84 + },
85 + 'manage.toolkits.list': {
86 + example: () => 'composio manage toolkits list',
87 + links: ['root.tools.list', 'manage.connectedAccounts.link'],
88 + },
89 + 'manage.connectedAccounts.link': {
90 + example: params =>
91 + `composio manage connected-accounts link ${getParam(params, 'toolkit', '<toolkit>')} --user-id "${getParam(params, 'userId', '<user-id>')}"`,
92 + links: ['dev.execute'],
93 + },
94 + 'manage.authConfigs.list': {
95 + example: () => 'composio manage auth-configs list',
96 + links: ['manage.connectedAccounts.link'],
97 + },
98 +};
99 +
100 +export const commandHintExample = (id: CommandHintId, params?: HintParams): string =>
101 + COMMAND_HINTS[id].example(params);
102 +
103 +export const commandHintStep = (
104 + label: string,
105 + id: CommandHintId,
106 + params?: HintParams
107 +): string => `${label}:\n> ${commandHintExample(id, params)}`;
108 +
109 +export const commandHintLinks = (id: CommandHintId): ReadonlyArray<CommandHintId> =>
110 + COMMAND_HINTS[id].links ?? [];
111 +
112 +export const renderCommandHintGraph = () => ({
113 + nodes: (Object.keys(COMMAND_HINTS) as CommandHintId[]).map(id => ({
114 + id,
115 + example: commandHintExample(id),
116 + links: [...commandHintLinks(id)],
117 + })),
118 +});
ts/packages/cli/src/services/command-project.ts
+4 -2
@@ -134,11 +134,13 @@ export const formatResolveCommandProjectError = (error: unknown): Error => {
134 );
135 }
136 if (error instanceof MissingDeveloperProjectError) {
137 - return new Error('No developer project configured for this directory. Run `composio init`.');
137 + return new Error(
138 + 'No developer project configured for this directory. Run `composio dev init`.'
139 + );
140 }
141 if (error instanceof DeveloperProjectNotFoundError) {
142 return new Error(
141 - `Developer project "${error.projectName}" was not found in org "${error.orgId}". Run \`composio init\` or \`composio manage projects list\`.`
143 + `Developer project "${error.projectName}" was not found in org "${error.orgId}". Run \`composio dev init\` or \`composio manage projects list\`.`
144 );
145 }
146 if (error instanceof AmbiguousDeveloperProjectNameError) {
ts/packages/cli/src/services/composio-clients.ts
+104
@@ -744,6 +744,19 @@ export type ConsumerProjectResolveResponse = Schema.Schema.Type<
744 typeof ConsumerProjectResolveResponse
745 >;
746
747 +export const LatestToolVersionResponse = Schema.Struct({
748 + tool_slug: Schema.String,
749 + version: Schema.String,
750 +}).annotations({ identifier: 'LatestToolVersionResponse' });
751 +export type LatestToolVersionResponse = Schema.Schema.Type<typeof LatestToolVersionResponse>;
752 +
753 +export const ConsumerConnectedToolkitsResponse = Schema.Struct({
754 + toolkits: Schema.Array(Schema.String),
755 +}).annotations({ identifier: 'ConsumerConnectedToolkitsResponse' });
756 +export type ConsumerConnectedToolkitsResponse = Schema.Schema.Type<
757 + typeof ConsumerConnectedToolkitsResponse
758 +>;
759 +
760 const extractArrayPayload = (json: unknown): ReadonlyArray<unknown> => {
761 if (Array.isArray(json)) return json;
762 if (json && typeof json === 'object') {
@@ -1136,6 +1149,97 @@ export const resolveConsumerProject = (params: {
1149 );
1150 });
1151
1152 +export const getLatestToolVersion = (params: {
1153 + baseURL: string;
1154 + apiKey: string;
1155 + toolSlug: string;
1156 + orgId?: string;
1157 + projectId?: string;
1158 + projectApiKey?: string;
1159 +}): Effect.Effect<LatestToolVersionResponse, HttpServerError | HttpDecodingError> =>
1160 + Effect.gen(function* () {
1161 + const response = yield* Effect.tryPromise({
1162 + try: () =>
1163 + fetch(
1164 + `${params.baseURL}/api/v3/tools/${encodeURIComponent(params.toolSlug)}/get_latest_version`,
1165 + {
1166 + method: 'GET',
1167 + redirect: 'error',
1168 + headers: {
1169 + ...(params.projectApiKey
1170 + ? ({ 'x-api-key': params.projectApiKey } satisfies Record<string, string>)
1171 + : ({ 'x-user-api-key': params.apiKey } satisfies Record<string, string>)),
1172 + ...(params.orgId ? { 'x-org-id': params.orgId } : {}),
1173 + ...(params.projectId ? { 'x-project-id': params.projectId } : {}),
1174 + 'User-Agent': '@composio/cli',
1175 + Accept: 'application/json',
1176 + 'Content-Type': 'application/json',
1177 + },
1178 + }
1179 + ),
1180 + catch: error => new HttpServerError({ cause: error }),
1181 + });
1182 +
1183 + if (!response.ok) {
1184 + return yield* handleHttpErrorResponse(response);
1185 + }
1186 +
1187 + const { json } = yield* streamResponseWithByteCount(response);
1188 +
1189 + return yield* pipe(
1190 + Schema.decodeUnknown(LatestToolVersionResponse)(json),
1191 + Effect.catchTag('ParseError', e => {
1192 + const message = ParseResult.TreeFormatter.formatErrorSync(e);
1193 + return new HttpDecodingError({
1194 + cause: `ParseError\n ${message}`,
1195 + });
1196 + })
1197 + );
1198 + });
1199 +
1200 +export const getConsumerConnectedToolkits = (params: {
1201 + baseURL: string;
1202 + apiKey: string;
1203 + orgId: string;
1204 + consumerUserId: string;
1205 +}): Effect.Effect<ConsumerConnectedToolkitsResponse, HttpServerError | HttpDecodingError> =>
1206 + Effect.gen(function* () {
1207 + const response = yield* Effect.tryPromise({
1208 + try: () =>
1209 + fetch(
1210 + `${params.baseURL}/api/v3/org/consumer/connected_toolkits?user_id=${encodeURIComponent(params.consumerUserId)}`,
1211 + {
1212 + method: 'GET',
1213 + redirect: 'error',
1214 + headers: {
1215 + 'x-user-api-key': params.apiKey,
1216 + 'x-org-id': params.orgId,
1217 + 'User-Agent': '@composio/cli',
1218 + Accept: 'application/json',
1219 + 'Content-Type': 'application/json',
1220 + },
1221 + }
1222 + ),
1223 + catch: error => new HttpServerError({ cause: error }),
1224 + });
1225 +
1226 + if (!response.ok) {
1227 + return yield* handleHttpErrorResponse(response);
1228 + }
1229 +
1230 + const { json } = yield* streamResponseWithByteCount(response);
1231 +
1232 + return yield* pipe(
1233 + Schema.decodeUnknown(ConsumerConnectedToolkitsResponse)(json),
1234 + Effect.catchTag('ParseError', e => {
1235 + const message = ParseResult.TreeFormatter.formatErrorSync(e);
1236 + return new HttpDecodingError({
1237 + cause: `ParseError\n ${message}`,
1238 + });
1239 + })
1240 + );
1241 + });
1242 +
1243 export class DeveloperProjectNotFoundError extends Data.TaggedError(
1244 'services/DeveloperProjectNotFoundError'
1245 )<{
ts/packages/cli/src/services/consumer-short-term-cache.ts new
+222
@@ -0,0 +1,222 @@
1 +import path from 'node:path';
2 +import { FileSystem } from '@effect/platform';
3 +import { Effect, Option } from 'effect';
4 +import { setupCacheDir } from 'src/effects/setup-cache-dir';
5 +import { NodeProcess } from 'src/services/node-process';
6 +import {
7 + getConsumerConnectedToolkits,
8 + resolveConsumerProject,
9 +} from 'src/services/composio-clients';
10 +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;
16 +
17 +type CacheEntry = {
18 + readonly toolkits: ReadonlyArray<string>;
19 + readonly expiresAt: string;
20 + readonly probablyMyCliSessionsByCwdHash?: Record<
21 + string,
22 + {
23 + readonly id: string;
24 + readonly expiresAt: string;
25 + }
26 + >;
27 +};
28 +
29 +type CacheState = Record<string, CacheEntry>;
30 +
31 +const cacheKey = (orgId: string, consumerUserId: string) => `${orgId}:${consumerUserId}`;
32 +
33 +const cachePath = (cacheDir: string) => path.join(cacheDir, CACHE_FILE);
34 +
35 +const cwdHash = (cwd: string): string => {
36 + let hash = 5381;
37 + for (let i = 0; i < cwd.length; i += 1) {
38 + hash = (hash * 33) ^ cwd.charCodeAt(i);
39 + }
40 + return Math.abs(hash >>> 0).toString(36);
41 +};
42 +
43 +const createProbablyMyCliSessionId = (cwd: string): string => {
44 + const random = crypto.randomUUID().replace(/-/g, '').slice(0, 10);
45 + return `cli_s_${cwdHash(cwd)}_${random}`;
46 +};
47 +
48 +const resolveSearchSessionMetadata = (params: {
49 + readonly currentEntry?: CacheEntry;
50 + readonly cwd: string;
51 +}) => {
52 + const now = Date.now();
53 + const currentCwdHash = cwdHash(params.cwd);
54 + const previousMap = {
55 + ...(params.currentEntry?.probablyMyCliSessionsByCwdHash ?? {}),
56 + };
57 +
58 + const probablyMyCliSessionsByCwdHash = Object.fromEntries(
59 + Object.entries(previousMap).filter(([, session]) => {
60 + const expiresAtMs = Date.parse(session.expiresAt);
61 + return Number.isFinite(expiresAtMs) && expiresAtMs > now;
62 + })
63 + );
64 +
65 + const currentSession = probablyMyCliSessionsByCwdHash[currentCwdHash];
66 + if (currentSession) {
67 + probablyMyCliSessionsByCwdHash[currentCwdHash] = {
68 + id: currentSession.id,
69 + expiresAt: new Date(
70 + Math.max(now, Date.parse(currentSession.expiresAt)) + SEARCH_SESSION_EXTENSION_MS
71 + ).toISOString(),
72 + };
73 + } else {
74 + probablyMyCliSessionsByCwdHash[currentCwdHash] = {
75 + id: createProbablyMyCliSessionId(params.cwd),
76 + expiresAt: new Date(now + CACHE_TTL_MS).toISOString(),
77 + };
78 + }
79 +
80 + return {
81 + probablyMyCliSessionsByCwdHash,
82 + };
83 +};
84 +
85 +const readCache = () =>
86 + Effect.gen(function* () {
87 + const fs = yield* FileSystem.FileSystem;
88 + const cacheDir = yield* setupCacheDir;
89 + const filePath = cachePath(cacheDir);
90 + if (!(yield* fs.exists(filePath))) {
91 + return {} satisfies CacheState;
92 + }
93 + const raw = yield* fs.readFileString(filePath, 'utf8');
94 + return yield* Effect.sync(() => JSON.parse(raw) as CacheState).pipe(
95 + Effect.catchAll(() => Effect.succeed({} satisfies CacheState))
96 + );
97 + });
98 +
99 +const writeCache = (state: CacheState) =>
100 + Effect.gen(function* () {
101 + const fs = yield* FileSystem.FileSystem;
102 + const cacheDir = yield* setupCacheDir;
103 + yield* fs.makeDirectory(cacheDir, { recursive: true });
104 + yield* fs.writeFileString(cachePath(cacheDir), JSON.stringify(state, null, 2));
105 + });
106 +
107 +export const getFreshConsumerConnectedToolkitsFromCache = (params: {
108 + orgId: string;
109 + consumerUserId: string;
110 +}) =>
111 + Effect.gen(function* () {
112 + const state = yield* readCache();
113 + const entry = state[cacheKey(params.orgId, params.consumerUserId)];
114 + if (!entry) {
115 + return Option.none<ReadonlyArray<string>>();
116 + }
117 + const expiresAtMs = Date.parse(entry.expiresAt);
118 + if (!Number.isFinite(expiresAtMs) || expiresAtMs <= Date.now()) {
119 + return Option.none<ReadonlyArray<string>>();
120 + }
121 + return Option.some(entry.toolkits);
122 + });
123 +
124 +export const invalidateConsumerConnectedToolkitsCache = () =>
125 + Effect.gen(function* () {
126 + const fs = yield* FileSystem.FileSystem;
127 + const cacheDir = yield* setupCacheDir;
128 + const filePath = cachePath(cacheDir);
129 + if (yield* fs.exists(filePath)) {
130 + yield* fs.remove(filePath);
131 + }
132 + });
133 +
134 +const resolveConsumerScope = (params?: {
135 + readonly orgId?: string;
136 + readonly consumerUserId?: string;
137 +}) =>
138 + Effect.gen(function* () {
139 + if (params?.orgId && params.consumerUserId) {
140 + return {
141 + orgId: params.orgId,
142 + consumerUserId: params.consumerUserId,
143 + };
144 + }
145 +
146 + const project = yield* resolveCommandProject({ mode: 'consumer' }).pipe(Effect.option);
147 + if (Option.isSome(project) && project.value.projectType === 'CONSUMER') {
148 + return {
149 + orgId: project.value.orgId,
150 + consumerUserId: project.value.consumerUserId ?? '',
151 + };
152 + }
153 +
154 + const userContext = yield* ComposioUserContext;
155 + const apiKey = Option.getOrUndefined(userContext.data.apiKey);
156 + const orgId = Option.getOrUndefined(userContext.data.orgId);
157 + if (!apiKey || !orgId) {
158 + return null;
159 + }
160 + const consumerProject = yield* resolveConsumerProject({
161 + baseURL: userContext.data.baseURL,
162 + apiKey,
163 + orgId,
164 + }).pipe(Effect.option);
165 + if (Option.isNone(consumerProject)) {
166 + return null;
167 + }
168 + return {
169 + orgId,
170 + consumerUserId: consumerProject.value.consumer_user_id,
171 + };
172 + });
173 +
174 +export const refreshConsumerConnectedToolkitsCache = (params?: {
175 + readonly orgId?: string;
176 + readonly consumerUserId?: string;
177 +}) =>
178 + Effect.gen(function* () {
179 + const scope = yield* resolveConsumerScope(params);
180 + if (!scope?.consumerUserId) {
181 + return;
182 + }
183 +
184 + const userContext = yield* ComposioUserContext;
185 + const apiKey = Option.getOrUndefined(userContext.data.apiKey);
186 + if (!apiKey) {
187 + return;
188 + }
189 +
190 + const response = yield* getConsumerConnectedToolkits({
191 + baseURL: userContext.data.baseURL,
192 + apiKey,
193 + orgId: scope.orgId,
194 + consumerUserId: scope.consumerUserId,
195 + });
196 + const state = yield* readCache();
197 + const key = cacheKey(scope.orgId, scope.consumerUserId);
198 + const currentEntry = state[key];
199 + const proc = yield* NodeProcess;
200 + const searchSessionFields = resolveSearchSessionMetadata({
201 + currentEntry,
202 + cwd: proc.cwd,
203 + });
204 + yield* writeCache({
205 + ...state,
206 + [key]: {
207 + toolkits: response.toolkits.map(toolkit => toolkit.toLowerCase()),
208 + expiresAt: new Date(Date.now() + CACHE_TTL_MS).toISOString(),
209 + ...searchSessionFields,
210 + },
211 + });
212 + });
213 +
214 +export const primeConsumerConnectedToolkitsCacheInBackground = (params?: {
215 + readonly orgId?: string;
216 + readonly consumerUserId?: string;
217 +}) =>
218 + refreshConsumerConnectedToolkitsCache(params).pipe(
219 + Effect.catchAll(() => Effect.void),
220 + Effect.forkDaemon,
221 + Effect.asVoid
222 + );
ts/packages/cli/src/services/runtime-debug-flags.ts new
+29
@@ -0,0 +1,29 @@
1 +type RuntimeDebugFlags = {
2 + readonly perfDebug: boolean;
3 + readonly toolDebug: boolean;
4 +};
5 +
6 +let runtimeDebugFlags: RuntimeDebugFlags = {
7 + perfDebug: false,
8 + toolDebug: false,
9 +};
10 +
11 +export const setRuntimeDebugFlags = (flags: Partial<RuntimeDebugFlags>) => {
12 + runtimeDebugFlags = {
13 + perfDebug: flags.perfDebug ?? runtimeDebugFlags.perfDebug,
14 + toolDebug: flags.toolDebug ?? runtimeDebugFlags.toolDebug,
15 + };
16 +};
17 +
18 +export const resetRuntimeDebugFlags = () => {
19 + runtimeDebugFlags = {
20 + perfDebug: false,
21 + toolDebug: false,
22 + };
23 +};
24 +
25 +export const isPerfDebugEnabled = () =>
26 + runtimeDebugFlags.perfDebug || process.env.COMPOSIO_PERF_DEBUG === '1';
27 +
28 +export const isToolDebugEnabled = () =>
29 + runtimeDebugFlags.toolDebug || process.env.COMPOSIO_TOOL_DEBUG === '1';
ts/packages/cli/src/services/tool-input-validation.ts new
+429
@@ -0,0 +1,429 @@
1 +import path from 'node:path';
2 +import { FileSystem } from '@effect/platform';
3 +import { Effect, Option } from 'effect';
4 +import { jsonSchemaToZodSchema } from '@composio/core';
5 +import { z } from 'zod/v3';
6 +import { setupCacheDir } from 'src/effects/setup-cache-dir';
7 +import { ComposioToolkitsRepository, getLatestToolVersion } from 'src/services/composio-clients';
8 +import { isToolDebugEnabled } from 'src/services/runtime-debug-flags';
9 +import { ComposioUserContext } from 'src/services/user-context';
10 +
11 +const TOOL_DEFINITIONS_DIR = 'tool_definitions';
12 +
13 +type CachedToolInputDefinition = {
14 + readonly version: string | null;
15 + readonly inputSchema: Record<string, unknown>;
16 +};
17 +
18 +const sanitizeToolSlug = (slug: string) => slug.replace(/[^A-Za-z0-9_.-]/g, '_');
19 +
20 +const toolDefinitionPath = (cacheDir: string, slug: string) =>
21 + path.join(cacheDir, TOOL_DEFINITIONS_DIR, `${sanitizeToolSlug(slug)}.json`);
22 +
23 +const ensureToolDefinitionsDir = (fs: FileSystem.FileSystem, cacheDir: string) =>
24 + fs.makeDirectory(path.join(cacheDir, TOOL_DEFINITIONS_DIR), { recursive: true });
25 +
26 +const parseSchemaFile = (raw: string, schemaPath: string) =>
27 + Effect.try({
28 + try: () => JSON.parse(raw) as Record<string, unknown>,
29 + catch: () => new Error(`Cached tool schema at ${schemaPath} is not valid JSON.`),
30 + });
31 +
32 +const isRecord = (value: unknown): value is Record<string, unknown> =>
33 + typeof value === 'object' && value !== null && !Array.isArray(value);
34 +
35 +const PLACEHOLDER_TOOL_VERSION = '00000000_00';
36 +
37 +const selectLatestVersion = (versions: ReadonlyArray<string> | undefined): string | null => {
38 + if (!versions || versions.length === 0) {
39 + return null;
40 + }
41 +
42 + for (const version of versions) {
43 + if (
44 + typeof version === 'string' &&
45 + version.trim().length > 0 &&
46 + version !== PLACEHOLDER_TOOL_VERSION
47 + ) {
48 + return version;
49 + }
50 + }
51 +
52 + return versions.find(version => typeof version === 'string' && version.trim().length > 0) ?? null;
53 +};
54 +
55 +const resolveLatestAvailableVersion = (params: {
56 + readonly toolLatestVersion: string | null;
57 + readonly toolkitLatestVersion: string | null;
58 +}): string | null => {
59 + if (
60 + params.toolLatestVersion &&
61 + params.toolLatestVersion.trim().length > 0 &&
62 + params.toolLatestVersion !== PLACEHOLDER_TOOL_VERSION
63 + ) {
64 + return params.toolLatestVersion;
65 + }
66 +
67 + return params.toolkitLatestVersion;
68 +};
69 +
70 +const toolDebugLog = (label: string, details: Record<string, unknown>) => {
71 + if (!isToolDebugEnabled()) return;
72 + console.error(`[tool-debug] ${JSON.stringify({ label, ...details })}`);
73 +};
74 +
75 +const parseCachedToolDefinition = (parsed: Record<string, unknown>): CachedToolInputDefinition => {
76 + const inputSchema = parsed.inputSchema;
77 + if (isRecord(inputSchema)) {
78 + return {
79 + version: typeof parsed.version === 'string' ? parsed.version : null,
80 + inputSchema,
81 + };
82 + }
83 +
84 + // Backward compatibility for previously cached bare-schema files.
85 + return {
86 + version: null,
87 + inputSchema: parsed,
88 + };
89 +};
90 +
91 +const serializeCachedToolDefinition = (definition: CachedToolInputDefinition): string =>
92 + JSON.stringify(
93 + {
94 + version: definition.version,
95 + inputSchema: definition.inputSchema,
96 + },
97 + null,
98 + 2
99 + );
100 +
101 +export const getCachedToolInputDefinition = (slug: string) =>
102 + Effect.gen(function* () {
103 + const fs = yield* FileSystem.FileSystem;
104 + const cacheDir = yield* setupCacheDir;
105 + const schemaPath = toolDefinitionPath(cacheDir, slug);
106 +
107 + if (!(yield* fs.exists(schemaPath))) {
108 + return null;
109 + }
110 +
111 + const raw = yield* fs.readFileString(schemaPath, 'utf8');
112 + const parsed = yield* parseSchemaFile(raw, schemaPath);
113 + const cached = parseCachedToolDefinition(parsed);
114 + return {
115 + schemaPath,
116 + schema: cached.inputSchema,
117 + version: cached.version,
118 + };
119 + });
120 +
121 +export const getToolDefinitionCachePath = (slug: string) =>
122 + Effect.gen(function* () {
123 + const cacheDir = yield* setupCacheDir;
124 + return toolDefinitionPath(cacheDir, slug);
125 + });
126 +
127 +export const invalidateToolInputDefinition = (slug: string) =>
128 + Effect.gen(function* () {
129 + const fs = yield* FileSystem.FileSystem;
130 + const cacheDir = yield* setupCacheDir;
131 + const schemaPath = toolDefinitionPath(cacheDir, slug);
132 + if (yield* fs.exists(schemaPath)) {
133 + yield* fs.remove(schemaPath);
134 + }
135 + });
136 +
137 +const fetchResolvedLatestToolVersion = (
138 + slug: string,
139 + params?: { readonly orgId?: string; readonly projectId?: string }
140 +) =>
141 + Effect.gen(function* () {
142 + const userContext = yield* ComposioUserContext;
143 + const apiKey = Option.getOrUndefined(userContext.data.apiKey);
144 + if (!apiKey) {
145 + return null;
146 + }
147 +
148 + const latest = yield* getLatestToolVersion({
149 + baseURL: userContext.data.baseURL,
150 + apiKey,
151 + toolSlug: slug,
152 + orgId: params?.orgId,
153 + projectId: params?.projectId,
154 + });
155 + toolDebugLog('latest_tool_version', {
156 + slug,
157 + orgId: params?.orgId,
158 + projectId: params?.projectId,
159 + response: latest,
160 + });
161 + return latest.version;
162 + });
163 +
164 +const fetchAndCacheToolInputDefinition = (
165 + slug: string,
166 + params?: { readonly orgId?: string; readonly projectId?: string }
167 +) =>
168 + Effect.gen(function* () {
169 + const fs = yield* FileSystem.FileSystem;
170 + const repo = yield* ComposioToolkitsRepository;
171 + const cacheDir = yield* setupCacheDir;
172 + const schemaPath = toolDefinitionPath(cacheDir, slug);
173 + yield* ensureToolDefinitionsDir(fs, cacheDir);
174 +
175 + const tool = yield* repo.getToolDetailed(slug);
176 + toolDebugLog('tool_detail', {
177 + slug,
178 + tool,
179 + });
180 + const schema = (tool.input_parameters ?? {}) as Record<string, unknown>;
181 + const version =
182 + (yield* fetchResolvedLatestToolVersion(slug, params).pipe(
183 + Effect.catchAll(() => Effect.succeed(null))
184 + )) ??
185 + resolveLatestAvailableVersion({
186 + toolLatestVersion: selectLatestVersion(tool.available_versions),
187 + toolkitLatestVersion: null,
188 + });
189 + toolDebugLog('resolved_tool_version', {
190 + slug,
191 + resolvedVersion: version,
192 + cachePath: schemaPath,
193 + });
194 + yield* fs.writeFileString(
195 + schemaPath,
196 + serializeCachedToolDefinition({
197 + version,
198 + inputSchema: schema,
199 + })
200 + );
201 +
202 + return { schemaPath, schema, version };
203 + });
204 +
205 +export const getOrFetchToolInputDefinition = (
206 + slug: string,
207 + params?: { readonly orgId?: string; readonly projectId?: string }
208 +) =>
209 + Effect.gen(function* () {
210 + const cached = yield* getCachedToolInputDefinition(slug);
211 + if (!cached) {
212 + return yield* fetchAndCacheToolInputDefinition(slug, params);
213 + }
214 +
215 + const freshness = yield* refreshToolInputDefinitionIfVersionChanged(
216 + slug,
217 + cached.version,
218 + params
219 + ).pipe(
220 + Effect.catchAll(() =>
221 + Effect.succeed({
222 + isStale: false,
223 + latestVersion: cached.version,
224 + skipped: false as const,
225 + })
226 + )
227 + );
228 +
229 + if (!freshness.isStale) {
230 + return cached;
231 + }
232 +
233 + const refreshed = yield* getCachedToolInputDefinition(slug);
234 + return refreshed ?? (yield* fetchAndCacheToolInputDefinition(slug, params));
235 + });
236 +
237 +export const refreshToolInputDefinitionIfVersionChanged = (
238 + slug: string,
239 + cachedVersion: string | null,
240 + params?: { readonly orgId?: string; readonly projectId?: string }
241 +) =>
242 + Effect.gen(function* () {
243 + const latestVersion = yield* fetchResolvedLatestToolVersion(slug, params);
244 + toolDebugLog('resolved_tool_version', {
245 + slug,
246 + mode: 'refresh',
247 + cachedVersion,
248 + resolvedVersion: latestVersion,
249 + orgId: params?.orgId,
250 + projectId: params?.projectId,
251 + });
252 + const isStale = latestVersion !== cachedVersion;
253 +
254 + if (isStale) {
255 + yield* fetchAndCacheToolInputDefinition(slug, params);
256 + }
257 +
258 + return { isStale, latestVersion, skipped: false as const };
259 + });
260 +
261 +export class ToolInputValidationError extends Error {
262 + readonly _tag = 'ToolInputValidationError';
263 +
264 + constructor(
265 + readonly toolSlug: string,
266 + readonly schemaPath: string,
267 + readonly issues: ReadonlyArray<string>,
268 + options?: ErrorOptions
269 + ) {
270 + super(
271 + [
272 + `Input validation failed for ${toolSlug}.`,
273 + `Schema: ${schemaPath}`,
274 + ...issues.map(issue => `- ${issue}`),
275 + ].join('\n'),
276 + options
277 + );
278 + }
279 +}
280 +
281 +const getObjectSchemaProperties = (schema: Record<string, unknown>): ReadonlyArray<string> => {
282 + const properties = schema.properties;
283 + if (!properties || typeof properties !== 'object' || Array.isArray(properties)) {
284 + return [];
285 + }
286 +
287 + return Object.keys(properties as Record<string, unknown>);
288 +};
289 +
290 +const normalizeKey = (value: string) => value.toLowerCase().replace(/[^a-z0-9]/g, '');
291 +
292 +const levenshteinDistance = (left: string, right: string): number => {
293 + if (left === right) return 0;
294 + if (left.length === 0) return right.length;
295 + if (right.length === 0) return left.length;
296 +
297 + const previous = Array.from({ length: right.length + 1 }, (_, index) => index);
298 + const current = new Array<number>(right.length + 1);
299 +
300 + for (let i = 0; i < left.length; i += 1) {
301 + current[0] = i + 1;
302 + for (let j = 0; j < right.length; j += 1) {
303 + const cost = left[i] === right[j] ? 0 : 1;
304 + current[j + 1] = Math.min(current[j]! + 1, previous[j + 1]! + 1, previous[j]! + cost);
305 + }
306 + for (let j = 0; j <= right.length; j += 1) {
307 + previous[j] = current[j]!;
308 + }
309 + }
310 +
311 + return previous[right.length]!;
312 +};
313 +
314 +const findClosestSchemaKey = (
315 + unknownKey: string,
316 + allowedKeys: ReadonlyArray<string>
317 +): string | undefined => {
318 + const normalizedUnknownKey = normalizeKey(unknownKey);
319 + const candidates = allowedKeys
320 + .map(key => ({
321 + key,
322 + normalized: normalizeKey(key),
323 + }))
324 + .map(candidate => {
325 + const distance = levenshteinDistance(normalizedUnknownKey, candidate.normalized);
326 + const containsBonus =
327 + candidate.normalized.includes(normalizedUnknownKey) ||
328 + normalizedUnknownKey.includes(candidate.normalized)
329 + ? -2
330 + : 0;
331 + return {
332 + key: candidate.key,
333 + score: distance + containsBonus,
334 + };
335 + })
336 + .sort((left, right) => left.score - right.score);
337 +
338 + const best = candidates[0];
339 + if (!best) {
340 + return undefined;
341 + }
342 +
343 + const threshold = Math.max(3, Math.ceil(normalizedUnknownKey.length * 0.6));
344 + return best.score <= threshold ? best.key : undefined;
345 +};
346 +
347 +const formatUnknownKeyIssue = (
348 + unknownKeys: ReadonlyArray<string>,
349 + allowedKeys: ReadonlyArray<string>
350 +): ReadonlyArray<string> => {
351 + const allowedList = allowedKeys.join(', ');
352 + return unknownKeys.map(key => {
353 + const suggestion = findClosestSchemaKey(key, allowedKeys);
354 + const lines = [`<root>: Unknown key "${key}".`];
355 + if (suggestion) {
356 + lines.push(`Use "${suggestion}" instead.`);
357 + }
358 + if (allowedList) {
359 + lines.push(`Allowed top-level keys: ${allowedList}`);
360 + }
361 + return lines.join(' ');
362 + });
363 +};
364 +
365 +export const validateToolInputArgumentsWithDefinition = (
366 + slug: string,
367 + args: Record<string, unknown>,
368 + definition: {
369 + readonly schemaPath: string;
370 + readonly schema: Record<string, unknown>;
371 + }
372 +) =>
373 + Effect.gen(function* () {
374 + const { schemaPath, schema } = definition;
375 + const allowedKeys = getObjectSchemaProperties(schema);
376 +
377 + const zodSchema = yield* Effect.try({
378 + try: () => jsonSchemaToZodSchema<z.ZodTypeAny>(schema),
379 + catch: error =>
380 + new ToolInputValidationError(
381 + slug,
382 + schemaPath,
383 + ['Could not compile the cached JSON schema into a Zod validator.'],
384 + { cause: error }
385 + ),
386 + });
387 +
388 + const parsed = zodSchema.safeParse(args);
389 + if (parsed.success) {
390 + return { schemaPath, schema };
391 + }
392 +
393 + const issues = parsed.error.issues.flatMap(issue => {
394 + if (issue.code === 'unrecognized_keys') {
395 + return formatUnknownKeyIssue(issue.keys, allowedKeys);
396 + }
397 + const location = issue.path.length > 0 ? issue.path.join('.') : '<root>';
398 + return [`${location}: ${issue.message}`];
399 + });
400 +
401 + return yield* Effect.fail(new ToolInputValidationError(slug, schemaPath, issues));
402 + });
403 +
404 +export const validateToolInputArgumentsIfCached = (slug: string, args: Record<string, unknown>) =>
405 + Effect.gen(function* () {
406 + const cached = yield* getCachedToolInputDefinition(slug);
407 + if (!cached) {
408 + return false as const;
409 + }
410 +
411 + yield* validateToolInputArgumentsWithDefinition(slug, args, cached);
412 + return true as const;
413 + });
414 +
415 +export const validateToolInputArguments = (
416 + slug: string,
417 + args: Record<string, unknown>,
418 + params?: { readonly orgId?: string; readonly projectId?: string }
419 +) =>
420 + Effect.gen(function* () {
421 + const definition = yield* getOrFetchToolInputDefinition(slug, params);
422 + return yield* validateToolInputArgumentsWithDefinition(slug, args, definition);
423 + });
424 +
425 +export const warmToolInputDefinitions = (slugs: ReadonlyArray<string>) =>
426 + Effect.forEach([...new Set(slugs)].filter(Boolean), slug => getOrFetchToolInputDefinition(slug), {
427 + concurrency: 'unbounded',
428 + discard: true,
429 + });
ts/packages/cli/test/src/commands/$default.cmd.test.ts
+1 -1
@@ -15,7 +15,7 @@ describe('CLI: composio', () => {
15 expect(result).toEqual(
16 ValidationError.commandMismatch(
17 HelpDoc.p(
18 - "Invalid subcommand for composio - use one of 'version', 'upgrade', 'whoami', 'login', 'logout', 'install', 'init', 'search', 'link', 'execute', 'listen', 'generate', 'manage'"
18 + "Invalid subcommand for composio - use one of 'version', 'upgrade', 'whoami', 'login', 'logout', 'run', 'install', 'dev', 'tools', 'search', 'link', 'execute', 'generate', 'manage'"
19 )
20 )
21 );
ts/packages/cli/test/src/commands/__snapshots__/$default.cmd.test.ts.snap
+30 -24
@@ -2,7 +2,9 @@
2
3 exports[`CLI: composio > [Given] --help flag [Then] prints help message 1`] = `
4 "
5 -Connect AI agents to external tools. \`search\`, \`link\`, and \`execute\` use your org consumer project by default. \`init\`, \`listen\`, and \`manage\` use developer project context.
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]
@@ -33,27 +35,43 @@ BASIC COMMANDS
35 Log out from the Composio CLI session.
36 Usage: composio logout
37
36 - init
37 - Initialize this directory with a developer project.
38 - Usage: composio init [--no-browser] [-y, --yes]
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:
40 - --no-browser Skip opening browser for auth
41 - -y, --yes Auto-select the default developer project
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
44 - Search tools by use case across toolkits/apps.
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
52 - Execute a tool.
53 - Usage: composio execute <slug> [-d, --data text]
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")
56 - -d, --data JSON arguments, @file, or - for stdin
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.
@@ -62,22 +80,10 @@ BASIC COMMANDS
80 <toolkit> Toolkit slug to link (e.g. "github", "gmail")
81 --no-browser Skip auto-opening the browser
82
65 - listen
66 - Listen for trigger events.
67 - Usage: composio listen [--toolkits text] [--trigger-id text] [--user-id text] [--max-events integer] [--forward text] [--out text]
68 - Options:
69 - --toolkits Filter by toolkit slugs, comma-separated
70 - --trigger-id Filter by trigger id
71 - --user-id Filter by user id
72 - --max-events Stop after N matching events
73 - --forward Forward events to URL (signed with COMPOSIO_WEBHOOK_SECRET)
74 - --out Append events to file
75 - --json Show raw event payload as JSON
76 - --table Show compact table rows
77 -
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)
80 - manage Developer/admin workflows: orgs, toolkits, triggers, auth configs, logs, and deprecated project commands.
86 + manage Manage your developer orgs, toolkits, connected accounts, triggers, auth configs, and projects.
87
88 FLAGS
89 -h, --help Show help for command
ts/packages/cli/test/src/commands/init.cmd.test.ts
+3 -3
@@ -2,12 +2,12 @@ import { describe, expect, layer } from '@effect/vitest';
2 import { Effect } from 'effect';
3 import { cli, TestLive, MockConsole } from 'test/__utils__';
4
5 -describe('CLI: composio init', () => {
6 - describe('init --help', () => {
5 +describe('CLI: composio dev init', () => {
6 + describe('dev init --help', () => {
7 layer(TestLive({ fixture: 'typescript-project' }))(it => {
8 it.scoped('[Then] shows --no-browser and --yes, no --org-id or --project-id', () =>
9 Effect.gen(function* () {
10 - yield* cli(['init', '--help']);
10 + yield* cli(['dev', 'init', '--help']);
11 const lines = yield* MockConsole.getLines({ stripAnsi: true });
12 const output = lines.join('\n');
13 expect(output).toContain('--no-browser');
ts/packages/cli/test/src/commands/projects/projects.list.cmd.test.ts
+1 -1
@@ -41,7 +41,7 @@ describe('CLI: composio manage projects list', () => {
41 expect(output).toContain(' Project One (project_1)');
42 expect(output).toContain(' Project Two (project_2)');
43 expect(output).toContain(
44 - 'Hint: run `composio init` in a directory to bind it to a developer project.'
44 + 'Hint: run `composio dev init` in a directory to bind it to a developer project.'
45 );
46 expect(output).toContain('Run `composio manage orgs switch` to change your default org.');
47 })
ts/packages/cli/test/src/commands/projects/projects.switch.cmd.test.ts
+1 -1
@@ -9,7 +9,7 @@ describe('CLI: composio manage projects switch', () => {
9 yield* cli(['manage', 'projects', 'switch']).pipe(Effect.catchAll(() => Effect.void));
10 const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
11 expect(output).toContain('Global developer project switching is no longer supported');
12 - expect(output).toContain('composio init');
12 + expect(output).toContain('composio dev init');
13 })
14 );
15 });
ts/packages/cli/test/src/commands/run.cmd.test.ts new
+154
@@ -0,0 +1,154 @@
1 +import { describe, expect, layer } from '@effect/vitest';
2 +import { Effect } from 'effect';
3 +import { afterEach, it, vi } from 'vitest';
4 +import {
5 + buildRunHelpersSource,
6 + extractInlineExecuteToolSlugs,
7 + inferCliInvocationPrefix,
8 +} from 'src/commands/run.cmd';
9 +import { cli, MockConsole, TestLive } from 'test/__utils__';
10 +
11 +describe('CLI: composio run', () => {
12 + afterEach(() => {
13 + vi.unstubAllGlobals();
14 + vi.restoreAllMocks();
15 + });
16 +
17 + layer(TestLive())(it => {
18 + it.scoped(
19 + '[Given] inline code and args [Then] it forwards them to the embedded Bun runtime',
20 + () =>
21 + Effect.gen(function* () {
22 + const spawn = vi.fn(() => ({ exited: Promise.resolve(7) }));
23 + const exit = vi.spyOn(process, 'exit').mockImplementation((() => undefined) as never);
24 + vi.stubGlobal('Bun', { spawn });
25 +
26 + yield* cli(['run', 'console.log("hi")', '--flag', 'value']);
27 +
28 + expect(spawn).toHaveBeenCalledTimes(1);
29 + const spawnConfig = (spawn as any).mock.calls[0][0] as {
30 + cmd: string[];
31 + env: unknown;
32 + stdio: string[];
33 + };
34 + expect(spawnConfig.cmd[0]).toBe(process.execPath);
35 + expect(spawnConfig.cmd[1]).toBe('--preload');
36 + 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 + ]);
44 + expect(spawnConfig.env).toEqual(
45 + expect.objectContaining({
46 + ...process.env,
47 + BUN_BE_BUN: '1',
48 + })
49 + );
50 + expect(spawnConfig.stdio).toEqual(['inherit', 'inherit', 'inherit']);
51 + expect(exit).toHaveBeenCalledWith(7);
52 + })
53 + );
54 + });
55 +
56 + layer(TestLive())(it => {
57 + it.scoped('[Given] --file [Then] it forwards file execution to the embedded Bun runtime', () =>
58 + Effect.gen(function* () {
59 + const spawn = vi.fn(() => ({ exited: Promise.resolve(0) }));
60 + const exit = vi.spyOn(process, 'exit').mockImplementation((() => undefined) as never);
61 + vi.stubGlobal('Bun', { spawn });
62 +
63 + yield* cli(['run', '--file', './script.ts', '--', 'hello']);
64 +
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);
83 + })
84 + );
85 + });
86 +
87 + layer(TestLive())(it => {
88 + it.scoped('[Given] no inline code and no --file [Then] it fails with a clear error', () =>
89 + Effect.gen(function* () {
90 + const exit = yield* cli(['run']).pipe(Effect.exit);
91 + expect(exit._tag).toBe('Failure');
92 + })
93 + );
94 + });
95 +
96 + 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 + );
109 + });
110 +});
111 +
112 +describe('buildRunHelpersSource', () => {
113 + it('[Given] consumer context [Then] it embeds auth and consumer metadata in the helper source', () => {
114 + const source = buildRunHelpersSource(['/tmp/composio'], {
115 + apiKey: 'test_api_key',
116 + baseURL: 'https://api.example.test',
117 + webURL: 'https://app.example.test',
118 + orgId: 'org_test',
119 + consumerUserId: 'consumer_user_test',
120 + dryRun: true,
121 + });
122 +
123 + expect(source).toContain('COMPOSIO_USER_API_KEY');
124 + expect(source).toContain('"consumerUserId":"consumer_user_test"');
125 + expect(source).toContain('__composioConsumerContext');
126 + expect(source).toContain('returned no JSON output');
127 + expect(source).toContain('args.push("--dry-run");');
128 + expect(source).toContain('args.push("--skip-connection-check");');
129 + expect(source).toContain('args.push("--skip-tool-params-check");');
130 + expect(source).toContain('args.push("--no-verify");');
131 + expect(source).toContain(
132 + "stdio: ['inherit', 'pipe', perfDebugEnabled || toolDebugEnabled ? 'inherit' : 'pipe']"
133 + );
134 + });
135 +});
136 +
137 +describe('inferCliInvocationPrefix', () => {
138 + it('[Given] a compiled bunfs entrypoint [Then] it falls back to the binary path only', () => {
139 + expect(inferCliInvocationPrefix(['node', '/$bunfs/root/composio'])).toEqual([process.execPath]);
140 + });
141 +});
142 +
143 +describe('extractInlineExecuteToolSlugs', () => {
144 + it('[Given] inline run source [Then] it finds static execute slugs from the AST', () => {
145 + expect(
146 + extractInlineExecuteToolSlugs(`
147 + const first = await execute("GMAIL_SEND_EMAIL", { to: "a@b.com" });
148 + const dynamic = await execute(slug, payload);
149 + execute('GITHUB_CREATE_ISSUE', { owner: 'acme' });
150 + execute("GMAIL_SEND_EMAIL", { to: "b@c.com" });
151 + `)
152 + ).toEqual(['GMAIL_SEND_EMAIL', 'GITHUB_CREATE_ISSUE']);
153 + });
154 +});
ts/packages/cli/test/src/commands/tools/tools.execute.cmd.test.ts
+590 -132
@@ -1,12 +1,16 @@
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';
5 import { extendConfigProvider } from 'src/services/config';
6 import { ActionExecuteConnectedAccountNotFoundError } from 'src/services/tools-executor';
7 +import { setupCacheDir } from 'src/effects/setup-cache-dir';
8 +import { getOrFetchToolInputDefinition } from 'src/services/tool-input-validation';
9 import * as redactModule from 'src/ui/redact';
10 import { cli, TestLive, MockConsole } from 'test/__utils__';
11 import type { TestLiveInput } from 'test/__utils__/services/test-layer';
12 import { showToolsExecuteInputHelp } from 'src/commands/tools/commands/tools.execute.cmd';
13 +import type { ToolkitDetailed } from 'src/models/toolkits';
14
15 const testConfigProvider = ConfigProvider.fromMap(
16 new Map([['COMPOSIO_USER_API_KEY', 'test_api_key']])
@@ -30,7 +34,7 @@ const parseLastJson = (lines: ReadonlyArray<string>) => {
34 throw new Error('Expected JSON output but none found');
35 };
36
33 -describe('CLI: composio manage tools execute', () => {
37 +describe('CLI: composio execute', () => {
38 // Disable CI redaction so tests see raw values.
39 // The explicit CI-redaction test overrides via vi.spyOn and is unaffected.
40 let savedCI: string | undefined;
@@ -51,16 +55,7 @@ describe('CLI: composio manage tools execute', () => {
55 )('[Given] -d inline JSON [Then] executes via Tool Router with defaults', it => {
56 it.scoped('executes via Tool Router with defaults', () =>
57 Effect.gen(function* () {
54 - yield* cli([
55 - 'manage',
56 - 'tools',
57 - 'execute',
58 - 'GMAIL_SEND_EMAIL',
59 - '--user-id',
60 - 'default',
61 - '-d',
62 - '{"recipient":"a"}',
63 - ]);
58 + yield* cli(['execute', 'GMAIL_SEND_EMAIL', '-d', '{"recipient":"a"}']);
59 const lines = yield* MockConsole.getLines({ stripAnsi: true });
60 const output = parseLastJson(lines);
61
@@ -73,13 +68,374 @@ describe('CLI: composio manage tools execute', () => {
68 );
69 });
70
71 + layer(
72 + TestLive({
73 + baseConfigProvider: testConfigProvider,
74 + toolkitsData: {
75 + tools: [
76 + {
77 + name: 'Send Email',
78 + slug: 'GMAIL_SEND_EMAIL',
79 + description: 'Send an email',
80 + tags: ['email'],
81 + available_versions: ['20260115_00', '20260101_00'],
82 + input_parameters: {
83 + type: 'object',
84 + properties: {
85 + recipient_email: { type: 'string' },
86 + },
87 + },
88 + output_parameters: {
89 + type: 'object',
90 + properties: {
91 + message_id: { type: 'string' },
92 + },
93 + },
94 + },
95 + ],
96 + detailedToolkits: [
97 + {
98 + name: 'Gmail',
99 + slug: 'gmail',
100 + is_local_toolkit: false,
101 + composio_managed_auth_schemes: ['OAUTH2'],
102 + no_auth: false,
103 + meta: {
104 + description: 'Email service',
105 + categories: [],
106 + created_at: new Date('2024-05-03T11:44:32.061Z') as any,
107 + updated_at: new Date('2024-05-03T11:44:32.061Z') as any,
108 + available_versions: ['20260115_00', '20260101_00'],
109 + tools_count: 36,
110 + triggers_count: 2,
111 + },
112 + auth_config_details: [],
113 + },
114 + ] satisfies ToolkitDetailed[],
115 + } satisfies TestLiveInput['toolkitsData'],
116 + })
117 + )(
118 + '[Given] a cache miss [Then] the stored schema file includes the latest available version',
119 + it => {
120 + it.scoped('writes version metadata at the top of the cache file', () =>
121 + Effect.gen(function* () {
122 + const definition = yield* getOrFetchToolInputDefinition('GMAIL_SEND_EMAIL');
123 + const raw = fs.readFileSync(definition.schemaPath, 'utf8');
124 + const parsed = JSON.parse(raw) as {
125 + version: string | null;
126 + inputSchema: Record<string, unknown>;
127 + };
128 +
129 + expect(parsed.version).toBe('20260115_00');
130 + expect(parsed.inputSchema).toEqual({
131 + type: 'object',
132 + properties: {
133 + recipient_email: { type: 'string' },
134 + },
135 + });
136 + })
137 + );
138 + }
139 + );
140 +
141 + layer(
142 + TestLive({
143 + baseConfigProvider: testConfigProvider,
144 + toolkitsData: {
145 + tools: [
146 + {
147 + name: 'Send Email',
148 + slug: 'GMAIL_SEND_EMAIL',
149 + description: 'Send an email',
150 + tags: ['email'],
151 + available_versions: ['00000000_00'],
152 + input_parameters: {
153 + type: 'object',
154 + properties: {
155 + recipient_email: { type: 'string' },
156 + },
157 + },
158 + output_parameters: {
159 + type: 'object',
160 + properties: {
161 + message_id: { type: 'string' },
162 + },
163 + },
164 + },
165 + ],
166 + detailedToolkits: [
167 + {
168 + name: 'Gmail',
169 + slug: 'gmail',
170 + is_local_toolkit: false,
171 + composio_managed_auth_schemes: ['OAUTH2'],
172 + no_auth: false,
173 + meta: {
174 + description: 'Email service',
175 + categories: [],
176 + created_at: new Date('2024-05-03T11:44:32.061Z') as any,
177 + updated_at: new Date('2024-05-03T11:44:32.061Z') as any,
178 + available_versions: ['20260316_00'],
179 + tools_count: 36,
180 + triggers_count: 2,
181 + },
182 + auth_config_details: [],
183 + },
184 + ] satisfies ToolkitDetailed[],
185 + } satisfies TestLiveInput['toolkitsData'],
186 + })
187 + )(
188 + '[Given] a placeholder tool version [Then] it stores the toolkit latest version instead',
189 + it => {
190 + it.scoped('prefers toolkit latest version over 00000000_00', () =>
191 + Effect.gen(function* () {
192 + const definition = yield* getOrFetchToolInputDefinition('GMAIL_SEND_EMAIL');
193 + const raw = fs.readFileSync(definition.schemaPath, 'utf8');
194 + const parsed = JSON.parse(raw) as {
195 + version: string | null;
196 + inputSchema: Record<string, unknown>;
197 + };
198 +
199 + expect(parsed.version).toBe(null);
200 + })
201 + );
202 + }
203 + );
204 +
205 + layer(
206 + TestLive({
207 + baseConfigProvider: testConfigProvider,
208 + fixture: 'global-test-user-id',
209 + stdin: { isTTY: true, data: '' },
210 + toolsExecutor: {
211 + respondWith: {
212 + data: {
213 + ok: true,
214 + },
215 + error: null,
216 + successful: true,
217 + logId: 'log_stale_cache',
218 + },
219 + },
220 + toolkitsData: {
221 + tools: [
222 + {
223 + name: 'Send Email',
224 + slug: 'GMAIL_SEND_EMAIL',
225 + description: 'Send an email',
226 + tags: ['email'],
227 + available_versions: ['20260115_00', '20260101_00'],
228 + input_parameters: {
229 + type: 'object',
230 + properties: {
231 + recipient_email: { type: 'string' },
232 + subject: { type: 'string' },
233 + body: { type: 'string' },
234 + },
235 + },
236 + output_parameters: {
237 + type: 'object',
238 + properties: {
239 + message_id: { type: 'string' },
240 + },
241 + },
242 + },
243 + ],
244 + detailedToolkits: [
245 + {
246 + name: 'Gmail',
247 + slug: 'gmail',
248 + is_local_toolkit: false,
249 + composio_managed_auth_schemes: ['OAUTH2'],
250 + no_auth: false,
251 + meta: {
252 + description: 'Email service',
253 + categories: [],
254 + created_at: new Date('2024-05-03T11:44:32.061Z') as any,
255 + updated_at: new Date('2024-05-03T11:44:32.061Z') as any,
256 + available_versions: ['20260115_00', '20260101_00'],
257 + tools_count: 36,
258 + triggers_count: 2,
259 + },
260 + auth_config_details: [],
261 + },
262 + ] satisfies ToolkitDetailed[],
263 + } satisfies TestLiveInput['toolkitsData'],
264 + })
265 + )(
266 + '[Given] a stale cached schema [Then] it does not block execution and refreshes the cache',
267 + it => {
268 + it.scoped('uses tool execution instead of stale validation failure', () =>
269 + Effect.gen(function* () {
270 + const cacheDir = yield* setupCacheDir;
271 + const schemaPath = `${cacheDir}/tool_definitions/GMAIL_SEND_EMAIL.json`;
272 + fs.mkdirSync(`${cacheDir}/tool_definitions`, { recursive: true });
273 + fs.writeFileSync(
274 + schemaPath,
275 + JSON.stringify({
276 + version: '20260101_00',
277 + inputSchema: {
278 + type: 'object',
279 + properties: {
280 + to: { type: 'string' },
281 + },
282 + },
283 + }),
284 + 'utf8'
285 + );
286 +
287 + yield* cli([
288 + 'execute',
289 + 'GMAIL_SEND_EMAIL',
290 + '-d',
291 + '{"recipient_email":"karan@composio.dev","subject":"Hi","body":"Hello"}',
292 + ]);
293 +
294 + const lines = yield* MockConsole.getLines({ stripAnsi: true });
295 + const output = parseLastJson(lines);
296 + expect(output.successful).toBe(true);
297 + expect(output.logId).toBe('log_stale_cache');
298 +
299 + const refreshed = JSON.parse(fs.readFileSync(schemaPath, 'utf8')) as {
300 + version: string | null;
301 + inputSchema: Record<string, unknown>;
302 + };
303 + expect(['20260101_00', '20260115_00']).toContain(refreshed.version);
304 + expect(refreshed.inputSchema.type).toBe('object');
305 + const propertyKeys = Object.keys(
306 + (refreshed.inputSchema.properties ?? {}) as Record<string, unknown>
307 + );
308 + expect(propertyKeys.some(key => key === 'recipient_email' || key === 'to')).toBe(true);
309 + })
310 + );
311 + }
312 + );
313 +
314 + layer(
315 + TestLive({
316 + baseConfigProvider: testConfigProvider,
317 + fixture: 'global-test-user-id',
318 + stdin: { isTTY: true, data: '' },
319 + toolkitsData: {
320 + tools: [
321 + {
322 + name: 'Send Email',
323 + slug: 'GMAIL_SEND_EMAIL',
324 + description: 'Send an email',
325 + tags: ['email'],
326 + available_versions: ['20260101_00'],
327 + input_parameters: {
328 + type: 'object',
329 + required: ['recipient'],
330 + properties: {
331 + recipient: { type: 'string', description: 'Recipient email' },
332 + },
333 + },
334 + output_parameters: {
335 + type: 'object',
336 + properties: {
337 + message_id: { type: 'string' },
338 + },
339 + },
340 + },
341 + ],
342 + } satisfies TestLiveInput['toolkitsData'],
343 + })
344 + )('[Given] invalid tool input [Then] it fails fast with the cached schema path', it => {
345 + it.scoped('prints validation issues and writes the schema to tool_definitions', () =>
346 + Effect.gen(function* () {
347 + const cacheDir = yield* setupCacheDir;
348 + const schemaPath = `${cacheDir}/tool_definitions/GMAIL_SEND_EMAIL.json`;
349 + fs.mkdirSync(`${cacheDir}/tool_definitions`, { recursive: true });
350 + fs.writeFileSync(
351 + schemaPath,
352 + JSON.stringify({
353 + version: '20260101_00',
354 + inputSchema: {
355 + type: 'object',
356 + required: ['recipient_email'],
357 + properties: {
358 + recipient_email: { type: 'string', description: 'Recipient email' },
359 + subject: { type: 'string' },
360 + body: { type: 'string' },
361 + },
362 + },
363 + }),
364 + 'utf8'
365 + );
366 +
367 + const failure = yield* cli([
368 + 'execute',
369 + 'GMAIL_SEND_EMAIL',
370 + '--dry-run',
371 + '-d',
372 + '{"recipient":42}',
373 + ]).pipe(
374 + Effect.flip,
375 + Effect.map(error => (error instanceof Error ? error.message : String(error)))
376 + );
377 +
378 + expect(failure).toContain('Input validation failed for GMAIL_SEND_EMAIL');
379 + expect(failure).toContain(schemaPath);
380 + expect(failure).toContain('Unknown key "recipient"');
381 + expect(failure).toContain('Use "recipient_email" instead.');
382 + expect(failure).toContain('Allowed top-level keys: recipient_email, subject, body');
383 + expect(fs.existsSync(schemaPath)).toBe(true);
384 + })
385 + );
386 + });
387 +
388 + layer(
389 + TestLive({
390 + baseConfigProvider: testConfigProvider,
391 + fixture: 'global-test-user-id',
392 + stdin: { isTTY: true, data: '' },
393 + toolsExecutor: {
394 + respondWith: {
395 + data: {
396 + content: 'token '.repeat(20_000),
397 + },
398 + error: null,
399 + successful: true,
400 + logId: 'log_large_output',
401 + },
402 + },
403 + })
404 + )('[Given] a large execution response [Then] it stores the payload in a temp file', it => {
405 + it.scoped('returns a file reference instead of the full inline payload', () =>
406 + Effect.gen(function* () {
407 + yield* cli(['execute', 'GMAIL_SEND_EMAIL', '-d', '{"recipient":"a"}']);
408 + const lines = yield* MockConsole.getLines({ stripAnsi: true });
409 + const output = parseLastJson(lines) as unknown as {
410 + successful: boolean;
411 + error: string | null;
412 + logId: string;
413 + storedInFile: boolean;
414 + tokenCount: number;
415 + outputFilePath: string;
416 + };
417 +
418 + expect(output.successful).toBe(true);
419 + expect(output.storedInFile).toBe(true);
420 + expect(output.logId).toBe('log_large_output');
421 + expect(output.tokenCount).toBeGreaterThan(10_000);
422 + expect(output.outputFilePath).toMatch(/^\/tmp\/composio\/[^/]+\/output-[^.]+\.json$/);
423 + expect(fs.existsSync(output.outputFilePath)).toBe(true);
424 + const storedJson = fs.readFileSync(output.outputFilePath, 'utf8');
425 + expect(storedJson).toContain('token token token');
426 +
427 + fs.rmSync(output.outputFilePath.split('/output-')[0]!, { recursive: true, force: true });
428 + })
429 + );
430 + });
431 +
432 layer(
433 TestLive({
434 baseConfigProvider: testConfigProvider,
435 fixture: 'global-test-user-id',
436 stdin: { isTTY: true, data: '' },
437 })
82 - )('[Given] composio execute alias [Then] works like composio manage tools execute', it => {
438 + )('[Given] composio execute [Then] it works for the consumer flow', it => {
439 it.scoped('root execute works for consumer flow without developer-only flags', () =>
440 Effect.gen(function* () {
441 yield* cli(['execute', 'GMAIL_SEND_EMAIL', '-d', '{"recipient":"a"}']);
@@ -93,6 +449,192 @@ describe('CLI: composio manage tools execute', () => {
449 );
450 });
451
452 + layer(
453 + TestLive({
454 + baseConfigProvider: testConfigProvider,
455 + fixture: 'global-test-user-id',
456 + stdin: { isTTY: true, data: '' },
457 + toolkitsData: {
458 + tools: [
459 + {
460 + name: 'Send Email',
461 + slug: 'GMAIL_SEND_EMAIL',
462 + description: 'Send an email',
463 + tags: ['email'],
464 + available_versions: ['20260316_00'],
465 + input_parameters: {
466 + type: 'object',
467 + properties: {
468 + recipient_email: { type: 'string' },
469 + body: { type: 'string' },
470 + },
471 + },
472 + output_parameters: {
473 + type: 'object',
474 + properties: {
475 + message_id: { type: 'string' },
476 + },
477 + },
478 + },
479 + ],
480 + } satisfies TestLiveInput['toolkitsData'],
481 + })
482 + )('[Given] composio execute --dry-run [Then] it validates without executing the tool', it => {
483 + it.scoped('returns a dry-run summary instead of calling the tool', () =>
484 + Effect.gen(function* () {
485 + yield* cli([
486 + 'execute',
487 + 'GMAIL_SEND_EMAIL',
488 + '--dry-run',
489 + '-d',
490 + '{ recipient_email: "a@b.com", body: "Hello" }',
491 + ]);
492 + const lines = yield* MockConsole.getLines({ stripAnsi: true });
493 + const output = parseLastJson(lines) as unknown as {
494 + successful: boolean;
495 + dryRun: boolean;
496 + slug: string;
497 + schemaPath: string;
498 + schemaVersion: string | null;
499 + arguments: Record<string, unknown>;
500 + };
501 +
502 + expect(output.successful).toBe(true);
503 + expect(output.dryRun).toBe(true);
504 + expect(output.slug).toBe('GMAIL_SEND_EMAIL');
505 + expect(output.schemaVersion).toBeTruthy();
506 + expect(output.arguments).toEqual({ recipient_email: 'a@b.com', body: 'Hello' });
507 + expect(output.schemaPath).toContain('/tool_definitions/GMAIL_SEND_EMAIL.json');
508 + })
509 + );
510 + });
511 +
512 + layer(
513 + TestLive({
514 + baseConfigProvider: testConfigProvider,
515 + fixture: 'global-test-user-id',
516 + toolkitsData: {
517 + tools: [
518 + {
519 + name: 'Send Email',
520 + slug: 'GMAIL_SEND_EMAIL',
521 + description: 'Send an email',
522 + tags: ['email'],
523 + available_versions: ['20260316_00'],
524 + input_parameters: {
525 + type: 'object',
526 + properties: {
527 + recipient_email: { type: 'string' },
528 + body: { type: 'string' },
529 + },
530 + },
531 + output_parameters: {
532 + type: 'object',
533 + properties: {
534 + message_id: { type: 'string' },
535 + },
536 + },
537 + },
538 + ],
539 + detailedToolkits: [
540 + {
541 + name: 'Gmail',
542 + slug: 'gmail',
543 + is_local_toolkit: false,
544 + composio_managed_auth_schemes: ['OAUTH2'],
545 + no_auth: false,
546 + meta: {
547 + description: 'Email service',
548 + categories: [],
549 + created_at: new Date('2024-05-03T11:44:32.061Z') as any,
550 + updated_at: new Date('2024-05-03T11:44:32.061Z') as any,
551 + available_versions: ['20260316_00'],
552 + tools_count: 36,
553 + triggers_count: 2,
554 + },
555 + auth_config_details: [],
556 + },
557 + ] satisfies ToolkitDetailed[],
558 + } satisfies TestLiveInput['toolkitsData'],
559 + })
560 + )('[Given] composio execute --get-schema [Then] it caches and prints the input schema', it => {
561 + it.scoped('fetches schema without executing the tool', () =>
562 + Effect.gen(function* () {
563 + const cacheDir = yield* setupCacheDir;
564 + const schemaPath = `${cacheDir}/tool_definitions/GMAIL_SEND_EMAIL.json`;
565 +
566 + yield* cli(['execute', 'GMAIL_SEND_EMAIL', '--get-schema']);
567 + const lines = yield* MockConsole.getLines({ stripAnsi: true });
568 + const output = parseLastJson(lines) as unknown as {
569 + slug: string;
570 + version: string | null;
571 + schemaPath: string;
572 + inputSchema: Record<string, unknown>;
573 + };
574 +
575 + expect(output.slug).toBe('GMAIL_SEND_EMAIL');
576 + expect(output.version).toBe('20260316_00');
577 + expect(output.schemaPath).toBe(schemaPath);
578 + expect(output.inputSchema).toEqual({
579 + type: 'object',
580 + properties: {
581 + recipient_email: { type: 'string' },
582 + body: { type: 'string' },
583 + },
584 + });
585 + expect(fs.existsSync(schemaPath)).toBe(true);
586 + })
587 + );
588 + });
589 +
590 + layer(
591 + TestLive({
592 + baseConfigProvider: testConfigProvider,
593 + fixture: 'global-test-user-id',
594 + stdin: { isTTY: true, data: '' },
595 + })
596 + )(
597 + '[Given] composio execute with a JS-style object literal [Then] it parses and executes successfully',
598 + it => {
599 + it.scoped('accepts object literal syntax for -d input', () =>
600 + Effect.gen(function* () {
601 + yield* cli(['execute', 'GMAIL_SEND_EMAIL', '-d', '{ recipient: "a", subject: "Hello" }']);
602 + const lines = yield* MockConsole.getLines({ stripAnsi: true });
603 + const output = parseLastJson(lines);
604 +
605 + expect(output.successful).toBe(true);
606 + expect(output.data.tool_slug).toBe('GMAIL_SEND_EMAIL');
607 + expect(output.data.arguments).toEqual({ recipient: 'a', subject: 'Hello' });
608 + })
609 + );
610 + }
611 + );
612 +
613 + layer(
614 + TestLive({
615 + baseConfigProvider: testConfigProvider,
616 + fixture: 'global-test-user-id',
617 + stdin: { isTTY: true, data: '' },
618 + })
619 + )('[Given] composio execute --perf-debug [Then] it is accepted on the root command', it => {
620 + it.scoped('parses and executes with perf debug enabled', () =>
621 + Effect.gen(function* () {
622 + yield* cli(['execute', '--perf-debug', 'GMAIL_SEND_EMAIL', '-d', '{"recipient":"a"}']);
623 + const lines = yield* MockConsole.getLines({ stripAnsi: true });
624 + const output = parseLastJson(lines);
625 +
626 + expect(output.successful).toBe(true);
627 + expect(output.data.tool_slug).toBe('GMAIL_SEND_EMAIL');
628 + }).pipe(
629 + Effect.ensuring(
630 + Effect.sync(() => {
631 + delete process.env.COMPOSIO_PERF_DEBUG;
632 + })
633 + )
634 + )
635 + );
636 + });
637 +
638 layer(
639 TestLive({
640 baseConfigProvider: testConfigProvider,
@@ -104,7 +646,7 @@ describe('CLI: composio manage tools execute', () => {
646 it => {
647 it.scoped('executes without printing global test user diagnostics', () =>
648 Effect.gen(function* () {
107 - yield* cli(['manage', 'tools', 'execute', 'GMAIL_SEND_EMAIL', '-d', '{"recipient":"a"}']);
649 + yield* cli(['execute', 'GMAIL_SEND_EMAIL', '-d', '{"recipient":"a"}']);
650 const lines = yield* MockConsole.getLines({ stripAnsi: true });
651 const output = parseLastJson(lines);
652 const text = lines.join('\n');
@@ -215,7 +757,7 @@ describe('CLI: composio manage tools execute', () => {
757 )('[Given] stdin is piped [Then] reads input from stdin', it => {
758 it.scoped('reads stdin input', () =>
759 Effect.gen(function* () {
218 - yield* cli(['manage', 'tools', 'execute', 'GITHUB_GET_REPOS', '--user-id', 'default']);
760 + yield* cli(['execute', 'GITHUB_GET_REPOS']);
761 const lines = yield* MockConsole.getLines({ stripAnsi: true });
762 const output = parseLastJson(lines);
763
@@ -242,23 +784,18 @@ describe('CLI: composio manage tools execute', () => {
784 it.scoped('prints connected account tips for legacy slug', () =>
785 Effect.gen(function* () {
786 yield* cli([
245 - 'manage',
246 - 'tools',
787 'execute',
788 'GMAIL_CREATE_EMAIL_DRAFT',
249 - '--user-id',
250 - 'default',
789 '-d',
790 '{\"recipient\":\"to@example.com\"}',
791 ]).pipe(Effect.catchAll(() => Effect.void));
792 const lines = yield* MockConsole.getLines({ stripAnsi: true });
793 const output = lines.join('\n');
794
257 - expect(output).toContain('No connected account found');
795 + expect(output).toContain('Run `composio link gmail`, then retry.');
796 expect(output).toContain('Tips');
259 - expect(output).toContain(
260 - 'composio manage connected-accounts link gmail --user-id "<user-id>"'
261 - );
797 + expect(output).toContain('composio link gmail');
798 + expect(output).not.toContain('COMPOSIO_MANAGE_CONNECTIONS');
799 })
800 );
801 });
@@ -288,23 +825,18 @@ describe('CLI: composio manage tools execute', () => {
825 it.scoped('prints connection tips with toolkit name derived from tool slug', () =>
826 Effect.gen(function* () {
827 yield* cli([
291 - 'manage',
292 - 'tools',
828 'execute',
829 'GMAIL_CREATE_EMAIL_DRAFT',
295 - '--user-id',
296 - 'default',
830 '-d',
831 '{"recipient":"to@example.com"}',
832 ]).pipe(Effect.catchAll(() => Effect.void));
833 const lines = yield* MockConsole.getLines({ stripAnsi: true });
834 const output = lines.join('\n');
835
303 - expect(output).toContain('No active connection');
836 + expect(output).toContain('Run `composio link gmail`, then retry.');
837 expect(output).toContain('Tips');
305 - expect(output).toContain(
306 - 'composio manage connected-accounts link gmail --user-id "<user-id>"'
307 - );
838 + expect(output).toContain('composio link gmail');
839 + expect(output).not.toContain('COMPOSIO_MANAGE_CONNECTIONS');
840 })
841 );
842 });
@@ -325,16 +857,7 @@ describe('CLI: composio manage tools execute', () => {
857 )('[Given] custom Tool Router execute mock [Then] returns custom response', it => {
858 it.scoped('flows through real ToolsExecutorLive with custom mock', () =>
859 Effect.gen(function* () {
328 - yield* cli([
329 - 'manage',
330 - 'tools',
331 - 'execute',
332 - 'GITHUB_STAR_REPO',
333 - '--user-id',
334 - 'default',
335 - '-d',
336 - '{"owner":"composio","repo":"composio"}',
337 - ]);
860 + yield* cli(['execute', 'GITHUB_STAR_REPO', '-d', '{"owner":"composio","repo":"composio"}']);
861 const lines = yield* MockConsole.getLines({ stripAnsi: true });
862 const output = parseLastJson(lines);
863
@@ -363,12 +886,8 @@ describe('CLI: composio manage tools execute', () => {
886 it.scoped('prints actionable error details', () =>
887 Effect.gen(function* () {
888 yield* cli([
366 - 'manage',
367 - 'tools',
889 'execute',
890 'GMAIL_CREATE_EMAIL_DRAFT',
370 - '--user-id',
371 - 'default',
891 '-d',
892 '{\"recipient\":\"to@example.com\"}',
893 ]).pipe(Effect.catchAll(() => Effect.void));
@@ -393,12 +912,8 @@ describe('CLI: composio manage tools execute', () => {
912 it.scoped('prints object error message and details', () =>
913 Effect.gen(function* () {
914 yield* cli([
396 - 'manage',
397 - 'tools',
915 'execute',
916 'GMAIL_CREATE_EMAIL_DRAFT',
400 - '--user-id',
401 - 'default',
917 '-d',
918 '{\"recipient\":\"to@example.com\"}',
919 ]).pipe(Effect.catchAll(() => Effect.void));
@@ -432,12 +947,8 @@ describe('CLI: composio manage tools execute', () => {
947 it.scoped('shows error and logId for soft failure', () =>
948 Effect.gen(function* () {
949 yield* cli([
435 - 'manage',
436 - 'tools',
950 'execute',
951 'GMAIL_CREATE_EMAIL_DRAFT',
439 - '--user-id',
440 - 'default',
952 '-d',
953 '{\"recipient\":\"to@example.com\"}',
954 ]).pipe(Effect.catchAll(() => Effect.void));
@@ -472,12 +983,8 @@ describe('CLI: composio manage tools execute', () => {
983 it.scoped('shows error without logId for soft failure', () =>
984 Effect.gen(function* () {
985 yield* cli([
475 - 'manage',
476 - 'tools',
986 'execute',
987 'GMAIL_CREATE_EMAIL_DRAFT',
479 - '--user-id',
480 - 'default',
988 '-d',
989 '{\"recipient\":\"to@example.com\"}',
990 ]).pipe(Effect.catchAll(() => Effect.void));
@@ -511,22 +1018,16 @@ describe('CLI: composio manage tools execute', () => {
1018 )('[Given] meta tool NoActiveConnection error [Then] does not suggest "link composio"', it => {
1019 it.scoped('omits connection tips for meta tool slugs', () =>
1020 Effect.gen(function* () {
514 - yield* cli([
515 - 'manage',
516 - 'tools',
517 - 'execute',
518 - 'COMPOSIO_SEARCH_TOOLS',
519 - '--user-id',
520 - 'default',
521 - '-d',
522 - '{"query":"email"}',
523 - ]).pipe(Effect.catchAll(() => Effect.void));
1021 + yield* cli(['execute', 'COMPOSIO_SEARCH_TOOLS', '-d', '{"query":"email"}']).pipe(
1022 + Effect.catchAll(() => Effect.void)
1023 + );
1024 const lines = yield* MockConsole.getLines({ stripAnsi: true });
1025 const output = lines.join('\n');
1026
527 - expect(output).toContain('No active connection');
1027 + expect(output).toContain('Link the required toolkit/app, then retry.');
1028 // Should NOT produce a misleading tip like "link composio"
1029 expect(output).not.toContain('link composio');
1030 + expect(output).not.toContain('COMPOSIO_MANAGE_CONNECTIONS');
1031 })
1032 );
1033 });
@@ -536,26 +1037,17 @@ describe('CLI: composio manage tools execute', () => {
1037 layer(
1038 TestLive({
1039 baseConfigProvider: testConfigProvider,
1040 + fixture: 'global-test-user-id',
1041 stdin: { isTTY: true, data: '' },
1042 })
1043 )('[Given] -d with invalid JSON [Then] fails with parse error', it => {
1044 it.scoped('fails with invalid JSON error', () =>
1045 Effect.gen(function* () {
544 - const result = yield* cli([
545 - 'manage',
546 - 'tools',
547 - 'execute',
548 - 'GMAIL_SEND_EMAIL',
549 - '--user-id',
550 - 'default',
551 - '-d',
552 - 'not-valid-json',
553 - ]).pipe(Effect.catchAll(e => Effect.succeed(e)));
554 -
555 - expect(result).toBeDefined();
556 - expect(result instanceof Error ? result.message : String(result)).toContain(
557 - 'Invalid JSON input'
1046 + const failure = yield* cli(['execute', 'GMAIL_SEND_EMAIL', '-d', 'not-valid-json']).pipe(
1047 + Effect.flip,
1048 + Effect.map(error => (error instanceof Error ? error.message : String(error)))
1049 );
1050 + expect(failure).toContain('Invalid JSON input');
1051 })
1052 );
1053 });
@@ -563,26 +1055,17 @@ describe('CLI: composio manage tools execute', () => {
1055 layer(
1056 TestLive({
1057 baseConfigProvider: testConfigProvider,
1058 + fixture: 'global-test-user-id',
1059 stdin: { isTTY: true, data: '' },
1060 })
1061 )('[Given] -d with JSON array [Then] fails with expected-object error', it => {
1062 it.scoped('fails with expected object error', () =>
1063 Effect.gen(function* () {
571 - const result = yield* cli([
572 - 'manage',
573 - 'tools',
574 - 'execute',
575 - 'GMAIL_SEND_EMAIL',
576 - '--user-id',
577 - 'default',
578 - '-d',
579 - '[1,2,3]',
580 - ]).pipe(Effect.catchAll(e => Effect.succeed(e)));
581 -
582 - expect(result).toBeDefined();
583 - expect(result instanceof Error ? result.message : String(result)).toContain(
584 - 'Expected a JSON object'
1064 + const failure = yield* cli(['execute', 'GMAIL_SEND_EMAIL', '-d', '[1,2,3]']).pipe(
1065 + Effect.flip,
1066 + Effect.map(error => (error instanceof Error ? error.message : String(error)))
1067 );
1068 + expect(failure).toContain('Expected a JSON object');
1069 })
1070 );
1071 });
@@ -590,26 +1073,17 @@ describe('CLI: composio manage tools execute', () => {
1073 layer(
1074 TestLive({
1075 baseConfigProvider: testConfigProvider,
1076 + fixture: 'global-test-user-id',
1077 stdin: { isTTY: true, data: '' },
1078 })
1079 )('[Given] -d with JSON string [Then] fails with expected-object error', it => {
1080 it.scoped('fails with expected object error for string', () =>
1081 Effect.gen(function* () {
598 - const result = yield* cli([
599 - 'manage',
600 - 'tools',
601 - 'execute',
602 - 'GMAIL_SEND_EMAIL',
603 - '--user-id',
604 - 'default',
605 - '-d',
606 - '"just a string"',
607 - ]).pipe(Effect.catchAll(e => Effect.succeed(e)));
608 -
609 - expect(result).toBeDefined();
610 - expect(result instanceof Error ? result.message : String(result)).toContain(
611 - 'Expected a JSON object'
1082 + const failure = yield* cli(['execute', 'GMAIL_SEND_EMAIL', '-d', '"just a string"']).pipe(
1083 + Effect.flip,
1084 + Effect.map(error => (error instanceof Error ? error.message : String(error)))
1085 );
1086 + expect(failure).toContain('Expected a JSON object');
1087 })
1088 );
1089 });
@@ -631,7 +1105,7 @@ describe('CLI: composio manage tools execute', () => {
1105 )('[Given] no -d and TTY stdin [Then] defaults to empty object and executes', it => {
1106 it.scoped('defaults to {} when no data provided', () =>
1107 Effect.gen(function* () {
634 - yield* cli(['manage', 'tools', 'execute', 'GMAIL_SEND_EMAIL', '--user-id', 'default']);
1108 + yield* cli(['execute', 'GMAIL_SEND_EMAIL']);
1109 const lines = yield* MockConsole.getLines({ stripAnsi: true });
1110 const output = lines.join('\n');
1111
@@ -644,24 +1118,17 @@ describe('CLI: composio manage tools execute', () => {
1118 layer(
1119 TestLive({
1120 baseConfigProvider: testConfigProvider,
1121 + fixture: 'global-test-user-id',
1122 stdin: { isTTY: false, data: '' },
1123 })
1124 )('[Given] empty piped stdin [Then] fails with parse error', it => {
1125 it.scoped('fails with error for empty stdin', () =>
1126 Effect.gen(function* () {
652 - const result = yield* cli([
653 - 'manage',
654 - 'tools',
655 - 'execute',
656 - 'GMAIL_SEND_EMAIL',
657 - '--user-id',
658 - 'default',
659 - ]).pipe(Effect.catchAll(e => Effect.succeed(e)));
660 -
661 - expect(result).toBeDefined();
662 - expect(result instanceof Error ? result.message : String(result)).toContain(
663 - 'Invalid JSON input'
1127 + const failure = yield* cli(['execute', 'GMAIL_SEND_EMAIL']).pipe(
1128 + Effect.flip,
1129 + Effect.map(error => (error instanceof Error ? error.message : String(error)))
1130 );
1131 + expect(failure).toContain('Invalid JSON input');
1132 })
1133 );
1134 });
@@ -697,16 +1164,7 @@ describe('CLI: composio manage tools execute', () => {
1164 );
1165
1166 try {
700 - yield* cli([
701 - 'manage',
702 - 'tools',
703 - 'execute',
704 - 'GMAIL_SEND_EMAIL',
705 - '--user-id',
706 - 'default',
707 - '-d',
708 - '{"recipient_email":"to@example.com"}',
709 - ]);
1167 + yield* cli(['execute', 'GMAIL_SEND_EMAIL', '-d', '{"recipient_email":"to@example.com"}']);
1168 const lines = yield* MockConsole.getLines({ stripAnsi: true });
1169 const output = parseLastJson(lines) as unknown as {
1170 data: { id: string; labelIds: string[]; threadId: string };
ts/packages/cli/test/src/commands/tools/tools.info.cmd.test.ts
+13 -13
@@ -49,25 +49,25 @@ const testConfigProvider = ConfigProvider.fromMap(
49 new Map([['COMPOSIO_USER_API_KEY', 'test_api_key']])
50 ).pipe(extendConfigProvider);
51
52 -describe('CLI: composio manage tools info', () => {
52 +describe('CLI: composio tools info', () => {
53 layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))(
54 '[Given] valid slug [Then] displays tool info',
55 it => {
56 - it.scoped('shows tool details with input/output schemas', () =>
56 + it.scoped('shows brief tool details and cached schema path', () =>
57 Effect.gen(function* () {
58 - yield* cli(['manage', 'tools', 'info', 'GMAIL_SEND_EMAIL']);
58 + yield* cli(['tools', 'info', 'GMAIL_SEND_EMAIL']);
59 const lines = yield* MockConsole.getLines({ stripAnsi: true });
60 const output = lines.join('\n');
61
62 expect(output).toContain('Send Email');
63 expect(output).toContain('GMAIL_SEND_EMAIL');
64 - expect(output).toContain('Input Parameters');
65 - expect(output).toContain('recipient');
66 - expect(output).toContain('required');
67 - expect(output).toContain('Output Parameters');
68 - expect(output).toContain('message_id');
69 - // Verify next-step hint includes derived toolkit slug
70 - expect(output).toContain('composio manage tools list --toolkits "gmail"');
64 + expect(output).toContain('Schema Cache');
65 + expect(output).toContain('/tool_definitions/GMAIL_SEND_EMAIL.json');
66 + expect(output).toContain(
67 + "jq '{required: (.inputSchema.required // []), keys: (.inputSchema.properties | keys)}'"
68 + );
69 + expect(output).toContain('composio execute "GMAIL_SEND_EMAIL" -d');
70 + expect(output).toContain('--dry-run');
71 })
72 );
73 }
@@ -78,7 +78,7 @@ describe('CLI: composio manage tools info', () => {
78 it => {
79 it.scoped('shows missing argument warning', () =>
80 Effect.gen(function* () {
81 - yield* cli(['manage', 'tools', 'info']);
81 + yield* cli(['tools', 'info']);
82 const lines = yield* MockConsole.getLines({ stripAnsi: true });
83 const output = lines.join('\n');
84
@@ -93,7 +93,7 @@ describe('CLI: composio manage tools info', () => {
93 it => {
94 it.scoped('shows not found with suggestions', () =>
95 Effect.gen(function* () {
96 - yield* cli(['manage', 'tools', 'info', 'NONEXISTENT_TOOL']);
96 + yield* cli(['tools', 'info', 'NONEXISTENT_TOOL']);
97 const lines = yield* MockConsole.getLines({ stripAnsi: true });
98 const output = lines.join('\n');
99
@@ -106,7 +106,7 @@ describe('CLI: composio manage tools info', () => {
106 layer(TestLive())('[Given] no API key [Then] warns user to login', it => {
107 it.scoped('warns user to login', () =>
108 Effect.gen(function* () {
109 - yield* cli(['manage', 'tools', 'info', 'GMAIL_SEND_EMAIL']);
109 + yield* cli(['tools', 'info', 'GMAIL_SEND_EMAIL']);
110 const lines = yield* MockConsole.getLines({ stripAnsi: true });
111 const output = lines.join('\n');
112
ts/packages/cli/test/src/commands/tools/tools.list.cmd.test.ts
+15 -15
@@ -55,30 +55,31 @@ const testConfigProvider = ConfigProvider.fromMap(
55 new Map([['COMPOSIO_USER_API_KEY', 'test_api_key']])
56 ).pipe(extendConfigProvider);
57
58 -describe('CLI: composio manage tools list', () => {
58 +describe('CLI: composio tools list', () => {
59 layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))(
60 - '[Given] no flags [Then] lists all tools',
60 + '[Given] toolkit "gmail" [Then] lists gmail tools',
61 it => {
62 it.scoped('lists all tools', () =>
63 Effect.gen(function* () {
64 - yield* cli(['manage', 'tools', 'list']);
64 + yield* cli(['tools', 'list', 'gmail']);
65 const lines = yield* MockConsole.getLines({ stripAnsi: true });
66 const output = lines.join('\n');
67
68 expect(output).toContain('GMAIL_SEND_EMAIL');
69 - expect(output).toContain('SLACK_SEND_MESSAGE');
70 - expect(output).toContain('Listing 3 tools');
69 + expect(output).toContain('GMAIL_CREATE_DRAFT');
70 + expect(output).not.toContain('SLACK_SEND_MESSAGE');
71 + expect(output).toContain('Listing 2 tools');
72 })
73 );
74 }
75 );
76
77 layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))(
77 - '[Given] --toolkits "gmail" [Then] lists only gmail tools',
78 + '[Given] toolkit "gmail" [Then] lists only gmail tools',
79 it => {
80 it.scoped('filters by toolkit', () =>
81 Effect.gen(function* () {
81 - yield* cli(['manage', 'tools', 'list', '--toolkits', 'gmail']);
82 + yield* cli(['tools', 'list', 'gmail']);
83 const lines = yield* MockConsole.getLines({ stripAnsi: true });
84 const output = lines.join('\n');
85
@@ -96,12 +97,11 @@ describe('CLI: composio manage tools list', () => {
97 it => {
98 it.scoped('filters by search query', () =>
99 Effect.gen(function* () {
99 - yield* cli(['manage', 'tools', 'list', '--query', 'send']);
100 + yield* cli(['tools', 'list', 'gmail', '--query', 'send']);
101 const lines = yield* MockConsole.getLines({ stripAnsi: true });
102 const output = lines.join('\n');
103
104 expect(output).toContain('GMAIL_SEND_EMAIL');
104 - expect(output).toContain('SLACK_SEND_MESSAGE');
105 expect(output).not.toContain('GMAIL_CREATE_DRAFT');
106 })
107 );
@@ -113,7 +113,7 @@ describe('CLI: composio manage tools list', () => {
113 it => {
114 it.scoped('respects limit', () =>
115 Effect.gen(function* () {
116 - yield* cli(['manage', 'tools', 'list', '--limit', '2']);
116 + yield* cli(['tools', 'list', 'gmail', '--limit', '2']);
117 const lines = yield* MockConsole.getLines({ stripAnsi: true });
118 const output = lines.join('\n');
119
@@ -126,7 +126,7 @@ describe('CLI: composio manage tools list', () => {
126 layer(TestLive())('[Given] no API key [Then] warns user to login', it => {
127 it.scoped('warns user to login', () =>
128 Effect.gen(function* () {
129 - yield* cli(['manage', 'tools', 'list']);
129 + yield* cli(['tools', 'list', 'gmail']);
130 const lines = yield* MockConsole.getLines({ stripAnsi: true });
131 const output = lines.join('\n');
132
@@ -140,7 +140,7 @@ describe('CLI: composio manage tools list', () => {
140 it => {
141 it.scoped('shows no tools found', () =>
142 Effect.gen(function* () {
143 - yield* cli(['manage', 'tools', 'list']);
143 + yield* cli(['tools', 'list', 'gmail']);
144 const lines = yield* MockConsole.getLines({ stripAnsi: true });
145 const output = lines.join('\n');
146
@@ -155,7 +155,7 @@ describe('CLI: composio manage tools list', () => {
155 it => {
156 it.scoped('filters by tag', () =>
157 Effect.gen(function* () {
158 - yield* cli(['manage', 'tools', 'list', '--tags', 'email']);
158 + yield* cli(['tools', 'list', 'gmail', '--tags', 'email']);
159 const lines = yield* MockConsole.getLines({ stripAnsi: true });
160 const output = lines.join('\n');
161
@@ -168,11 +168,11 @@ describe('CLI: composio manage tools list', () => {
168 );
169
170 layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))(
171 - '[Given] --toolkits "nonexistent" [Then] shows no tools found with hint',
171 + '[Given] toolkit "nonexistent" [Then] shows no tools found with hint',
172 it => {
173 it.scoped('shows hint about verifying toolkit slug', () =>
174 Effect.gen(function* () {
175 - yield* cli(['manage', 'tools', 'list', '--toolkits', 'nonexistent']);
175 + yield* cli(['tools', 'list', 'nonexistent']);
176 const lines = yield* MockConsole.getLines({ stripAnsi: true });
177 const output = lines.join('\n');
178
ts/packages/cli/test/src/commands/tools/tools.search.cmd.test.ts
+22 -34
@@ -53,11 +53,11 @@ const testLiveOptions = {
53 fixture: 'global-test-user-id' as const,
54 };
55
56 -describe('CLI: composio manage tools search', () => {
56 +describe('CLI: composio search', () => {
57 layer(TestLive(testLiveOptions))('[Given] query "send" [Then] returns matching tools', it => {
58 it.scoped('returns matching tools', () =>
59 Effect.gen(function* () {
60 - yield* cli(['manage', 'tools', 'search', 'send']);
60 + yield* cli(['search', 'send']);
61 const lines = yield* MockConsole.getLines({ stripAnsi: true });
62 const output = lines.join('\n');
63
@@ -74,7 +74,7 @@ describe('CLI: composio manage tools search', () => {
74 it => {
75 it.scoped('shows not found message', () =>
76 Effect.gen(function* () {
77 - yield* cli(['manage', 'tools', 'search', 'nonexistent_query']);
77 + yield* cli(['search', 'nonexistent_query']);
78 const lines = yield* MockConsole.getLines({ stripAnsi: true });
79 const output = lines.join('\n');
80
@@ -89,7 +89,7 @@ describe('CLI: composio manage tools search', () => {
89 it => {
90 it.scoped('scopes search to toolkit', () =>
91 Effect.gen(function* () {
92 - yield* cli(['manage', 'tools', 'search', 'send', '--toolkits', 'gmail']);
92 + yield* cli(['search', 'send', '--toolkits', 'gmail']);
93 const lines = yield* MockConsole.getLines({ stripAnsi: true });
94 const output = lines.join('\n');
95 const humanOutput = output.split('\n{')[0] ?? output;
@@ -107,7 +107,7 @@ describe('CLI: composio manage tools search', () => {
107 it => {
108 it.scoped('prints full search response with CTA for jq', () =>
109 Effect.gen(function* () {
110 - yield* cli(['manage', 'tools', 'search', 'send']);
110 + yield* cli(['search', 'send']);
111 const lines = yield* MockConsole.getLines({ stripAnsi: true });
112 const output = lines.join('\n');
113
@@ -119,8 +119,8 @@ describe('CLI: composio manage tools search', () => {
119 expect(output).toContain('"CTA"');
120 expect(output).toContain('"Execute a tool"');
121 expect(output).toContain('"Connect a user account"');
122 - expect(output).toContain('composio manage tools execute');
123 - expect(output).toContain('composio manage connected-accounts link gmail');
122 + expect(output).toContain('composio execute');
123 + expect(output).toContain('composio link gmail');
124 })
125 );
126 }
@@ -157,7 +157,7 @@ describe('CLI: composio manage tools search', () => {
157 },
158 });
159
160 - yield* cli(['manage', 'tools', 'search', 'send']).pipe(Effect.provide(live));
160 + yield* cli(['search', 'send']).pipe(Effect.provide(live));
161 const lines = yield* MockConsole.getLines({ stripAnsi: true });
162 const output = lines.join('\n');
163
@@ -168,16 +168,12 @@ describe('CLI: composio manage tools search', () => {
168
169 const executeCta = cta.find(c => c.action === 'Execute a tool');
170 expect(executeCta).toBeTruthy();
171 - expect(executeCta!.command).toContain(
172 - 'composio manage tools execute "GMAIL_SEND_EMAIL" --user-id "<user-id>"'
173 - );
171 + expect(executeCta!.command).toContain('composio execute "GMAIL_SEND_EMAIL"');
172 expect(executeCta!.command).toMatch(/-d '\{"to":"","subject":"","body":""\}'/);
173
174 const linkCta = cta.find(c => c.action === 'Connect a user account');
175 expect(linkCta).toBeTruthy();
178 - expect(linkCta!.command).toBe(
179 - 'composio manage connected-accounts link gmail --user-id "<user-id>"'
180 - );
176 + expect(linkCta!.command).toBe('composio link gmail');
177 })
178 );
179 }
@@ -188,7 +184,7 @@ describe('CLI: composio manage tools search', () => {
184 it => {
185 it.scoped('CTA uses -d "{}" when no schema properties', () =>
186 Effect.gen(function* () {
191 - yield* cli(['manage', 'tools', 'search', 'send']);
187 + yield* cli(['search', 'send']);
188 const lines = yield* MockConsole.getLines({ stripAnsi: true });
189 const output = lines.join('\n');
190
@@ -275,9 +271,7 @@ describe('CLI: composio manage tools search', () => {
271 },
272 });
273
278 - yield* cli(['manage', 'tools', 'search', 'send', '--toolkits', 'gmail,outlook']).pipe(
279 - Effect.provide(live)
280 - );
274 + yield* cli(['search', 'send', '--toolkits', 'gmail,outlook']).pipe(Effect.provide(live));
275
276 expect(createParams?.toolkits).toEqual({ enable: ['gmail', 'outlook'] });
277 expect(searchParams?.queries[0]?.use_case).toBe('send');
@@ -342,19 +336,15 @@ describe('CLI: composio manage tools search', () => {
336 },
337 });
338
345 - yield* cli(['manage', 'tools', 'search', 'send email']).pipe(Effect.provide(live));
339 + yield* cli(['search', 'send email']).pipe(Effect.provide(live));
340 const lines = yield* MockConsole.getLines({ stripAnsi: true });
341 const output = lines.join('\n');
342
343 expect(output).toContain('Plan:');
344 expect(output).toContain('1. Collect recipient details');
351 - expect(output).toContain('Hints:');
352 - expect(output).toContain(
353 - `composio manage tools execute "GMAIL_SEND_EMAIL" --user-id "<user-id>" -d "{}"`
354 - );
355 - expect(output).toContain(
356 - `composio manage connected-accounts link <toolkit> --user-id "<user-id>"`
357 - );
345 + expect(output).toContain('Execute a tool:');
346 + expect(output).toContain(`composio execute "GMAIL_SEND_EMAIL" -d "{}"`);
347 + expect(output).toContain(`composio link <toolkit>`);
348 })
349 );
350 }
@@ -363,7 +353,7 @@ describe('CLI: composio manage tools search', () => {
353 layer(TestLive())('[Given] no API key [Then] warns user to login', it => {
354 it.scoped('warns user to login', () =>
355 Effect.gen(function* () {
366 - yield* cli(['manage', 'tools', 'search', 'send']);
356 + yield* cli(['search', 'send']);
357 const lines = yield* MockConsole.getLines({ stripAnsi: true });
358 const output = lines.join('\n');
359
@@ -373,7 +363,7 @@ describe('CLI: composio manage tools search', () => {
363 });
364
365 layer(TestLive(testLiveOptions))(
376 - '[Given] consumer search with explicit --user-id [Then] it still uses resolved consumer user id',
366 + '[Given] consumer search [Then] it uses the resolved consumer user id',
367 it => {
368 it.scoped('uses consumer user id from the resolved project context', () =>
369 Effect.gen(function* () {
@@ -393,9 +383,7 @@ describe('CLI: composio manage tools search', () => {
383 },
384 });
385
396 - yield* cli(['manage', 'tools', 'search', 'send', '--user-id', 'alice']).pipe(
397 - Effect.provide(live)
398 - );
386 + yield* cli(['search', 'send']).pipe(Effect.provide(live));
387
388 expect(createParams?.user_id).toBe('consumer-user-org_test');
389 })
@@ -412,7 +400,7 @@ describe('CLI: composio manage tools search', () => {
400 )('[Given] no explicit --user-id [Then] consumer search does not require one', it => {
401 it.scoped('runs without printing global test user diagnostics', () =>
402 Effect.gen(function* () {
415 - yield* cli(['manage', 'tools', 'search', 'send']);
403 + yield* cli(['search', 'send']);
404 const lines = yield* MockConsole.getLines({ stripAnsi: true });
405 const output = lines.join('\n');
406
@@ -423,9 +411,9 @@ describe('CLI: composio manage tools search', () => {
411 });
412
413 layer(TestLive(testLiveOptions))(
426 - '[Given] composio search alias [Then] works like composio manage tools search',
414 + '[Given] composio search [Then] runs the root search flow',
415 it => {
428 - it.scoped('alias expands to tools search', () =>
416 + it.scoped('search returns matching tools', () =>
417 Effect.gen(function* () {
418 yield* cli(['search', 'send']);
419 const lines = yield* MockConsole.getLines({ stripAnsi: true });
ts/packages/cli/test/src/commands/triggers/triggers.listen.cmd.test.ts
+3 -3
@@ -139,10 +139,10 @@ describe('CLI: composio manage triggers listen', () => {
139 events: [mockV3TriggerEvent],
140 },
141 })
142 - )('[Given] composio listen alias [Then] works like composio manage triggers listen', it => {
143 - it.scoped('alias expands to triggers listen', () =>
142 + )('[Given] composio dev listen [Then] works like composio manage triggers listen', it => {
143 + it.scoped('dev listen expands to triggers listen', () =>
144 Effect.gen(function* () {
145 - yield* cli(['listen', '--max-events', '1']);
145 + yield* cli(['dev', 'listen', '--max-events', '1']);
146 const lines = yield* MockConsole.getLines({ stripAnsi: true });
147 const output = lines.join('\n');
148
ts/packages/cli/test/src/services/command-hints.test.ts new
+39
@@ -0,0 +1,39 @@
1 +import { describe, expect, it } from 'vitest';
2 +import {
3 + COMMAND_HINTS,
4 + commandHintExample,
5 + commandHintLinks,
6 + renderCommandHintGraph,
7 + type CommandHintId,
8 +} from 'src/services/command-hints';
9 +
10 +describe('command-hints', () => {
11 + it('has no dangling linked command ids', () => {
12 + const ids = new Set(Object.keys(COMMAND_HINTS) as CommandHintId[]);
13 +
14 + for (const id of ids) {
15 + for (const linkedId of commandHintLinks(id)) {
16 + expect(ids.has(linkedId)).toBe(true);
17 + }
18 + }
19 + });
20 +
21 + it('renders examples from the registry', () => {
22 + expect(commandHintExample('root.tools.list')).toContain('composio tools list');
23 + expect(commandHintExample('root.execute', { slug: 'GMAIL_SEND_EMAIL' })).toContain(
24 + 'GMAIL_SEND_EMAIL'
25 + );
26 + expect(commandHintExample('root.execute.getSchema', { slug: 'GMAIL_SEND_EMAIL' })).toContain(
27 + '--get-schema'
28 + );
29 + expect(commandHintExample('dev.logs.tools', { logId: 'log_123' })).toContain('log_123');
30 + });
31 +
32 + it('serializes the graph with nodes and links', () => {
33 + const graph = renderCommandHintGraph();
34 + expect(graph.nodes.length).toBeGreaterThan(0);
35 + expect(graph.nodes.find(node => node.id === 'root.execute')).toMatchObject({
36 + id: 'root.execute',
37 + });
38 + });
39 +});