Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
TypeScript agentic-aiagentsaiai-agentsaiagentsdeveloper-toolsfunction-callinggpt-4javascriptjsllmllmopsmcppythonremote-mcp-serverssetypescript
feat(cli): improve consumer command UX and hinting (#2979)
Rahul Tarak7633445b4796
diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex d9687fe16..23cf01095 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -703,16 +703,16 @@ importers:version: link:../../packages/providers/llamaindex'@llamaindex/openai':specifier: ^0.4.20- version: 0.4.22(@llamaindex/[email protected])(@llamaindex/[email protected])([email protected])([email protected])+ version: 0.4.22(@llamaindex/[email protected])(@llamaindex/[email protected])([email protected])([email protected])'@llamaindex/workflow':specifier: ^1.1.24- version: 1.1.24(@llamaindex/[email protected])(@llamaindex/[email protected])(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])([email protected])+ version: 1.1.24(@llamaindex/[email protected])(@llamaindex/[email protected])(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])([email protected])dotenv:specifier: ^16.4.1version: 16.6.1llamaindex:specifier: ^0.12.0- version: 0.12.1(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])([email protected])([email protected])([email protected])+ version: 0.12.1(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])([email protected])([email protected])([email protected])devDependencies:'@types/bun':specifier: ^1.2.9@@ -1082,6 +1082,9 @@ importers:indent-string:specifier: ^5.0.0version: 5.0.0+ js-tiktoken:+ specifier: ^1.0.21+ version: 1.0.21open:specifier: ^10.2.0version: 10.2.0@@ -1321,7 +1324,7 @@ importers:dependencies:llamaindex:specifier: ^0.12.0- version: 0.12.1(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])([email protected])([email protected])([email protected])devDependencies:'@composio/core':specifier: workspace:*@@ -7560,26 +7563,43 @@ snapshots:tree-sitter: 0.22.4web-tree-sitter: 0.24.7- '@llamaindex/[email protected](@llamaindex/[email protected])(@llamaindex/[email protected])([email protected])([email protected])':+ '@llamaindex/[email protected](@llamaindex/[email protected])(@llamaindex/[email protected])([email protected])([email protected])':dependencies:'@llamaindex/core': 0.6.22'@llamaindex/env': 0.1.30- openai: 5.23.2([email protected])([email protected])+ openai: 5.23.2([email protected])([email protected])transitivePeerDependencies:- ws- zod- '@llamaindex/[email protected](@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])([email protected])':+ '@llamaindex/[email protected](@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])([email protected])':optionalDependencies:- '@modelcontextprotocol/sdk': 1.26.0(@cfworker/[email protected])([email protected])+ '@modelcontextprotocol/sdk': 1.26.0(@cfworker/[email protected])([email protected])hono: 4.11.9+ zod: 3.25.76++ '@llamaindex/[email protected]([email protected])':+ optionalDependencies:zod: 4.3.6- '@llamaindex/[email protected](@llamaindex/[email protected])(@llamaindex/[email protected])(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])([email protected])':+ '@llamaindex/[email protected](@llamaindex/[email protected])(@llamaindex/[email protected])(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])([email protected])':dependencies:'@llamaindex/core': 0.6.22'@llamaindex/env': 0.1.30- '@llamaindex/workflow-core': 1.3.3(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])([email protected])+ '@llamaindex/workflow-core': 1.3.3(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])([email protected])+ transitivePeerDependencies:+ - '@modelcontextprotocol/sdk'+ - hono+ - next+ - p-retry+ - rxjs+ - zod++ '@llamaindex/[email protected](@llamaindex/[email protected])(@llamaindex/[email protected])([email protected])':+ dependencies:+ '@llamaindex/core': 0.6.22+ '@llamaindex/env': 0.1.30+ '@llamaindex/workflow-core': 1.3.3([email protected])transitivePeerDependencies:- '@modelcontextprotocol/sdk'- hono@@ -8513,6 +8533,14 @@ snapshots:optionalDependencies:+ '@vitest/[email protected]([email protected](@types/[email protected])([email protected])([email protected]))':+ dependencies:+ '@vitest/spy': 3.2.4+ estree-walker: 3.0.3+ magic-string: 0.30.21+ optionalDependencies:+'@vitest/[email protected]':dependencies:tinyrainbow: 2.0.0@@ -8542,7 +8570,7 @@ snapshots:sirv: 3.0.2tinyglobby: 0.2.15tinyrainbow: 2.0.0- vitest: 3.2.4(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])+ vitest: 3.2.4(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])'@vitest/[email protected]':dependencies:@@ -9909,12 +9937,34 @@ snapshots:rfdc: 1.4.1wrap-ansi: 9.0.2- [email protected](@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])([email protected])([email protected])([email protected]):+ [email protected](@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])([email protected])([email protected])([email protected]):dependencies:'@llamaindex/core': 0.6.22'@llamaindex/env': 0.1.30'@llamaindex/node-parser': 2.0.22(@llamaindex/[email protected])(@llamaindex/[email protected])([email protected])([email protected])- '@llamaindex/workflow': 1.1.24(@llamaindex/[email protected])(@llamaindex/[email protected])(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])([email protected])+ '@llamaindex/workflow': 1.1.24(@llamaindex/[email protected])(@llamaindex/[email protected])(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])([email protected])+ '@types/lodash': 4.17.23+ '@types/node': 24.10.13+ lodash: 4.17.23+ magic-bytes.js: 1.13.0+ transitivePeerDependencies:+ - '@huggingface/transformers'+ - '@modelcontextprotocol/sdk'+ - gpt-tokenizer+ - hono+ - next+ - p-retry+ - rxjs+ - tree-sitter+ - web-tree-sitter+ - zod++ dependencies:+ '@llamaindex/core': 0.6.22+ '@llamaindex/env': 0.1.30+ '@llamaindex/node-parser': 2.0.22(@llamaindex/[email protected])(@llamaindex/[email protected])([email protected])([email protected])+ '@llamaindex/workflow': 1.1.24(@llamaindex/[email protected])(@llamaindex/[email protected])([email protected])'@types/lodash': 4.17.23'@types/node': 24.10.13lodash: 4.17.23@@ -10194,6 +10244,11 @@ snapshots:is-inside-container: 1.0.0wsl-utils: 0.1.0+ optionalDependencies:+ ws: 8.19.0+ zod: 3.25.76+optionalDependencies:ws: 8.19.0@@ -11291,7 +11346,7 @@ snapshots:dependencies:'@types/chai': 5.2.3'@vitest/expect': 3.2.4- '@vitest/mocker': 3.2.4([email protected](@types/[email protected])([email protected])([email protected]))+ '@vitest/mocker': 3.2.4([email protected](@types/[email protected])([email protected])([email protected]))'@vitest/pretty-format': 3.2.4'@vitest/runner': 3.2.4'@vitest/snapshot': 3.2.4diff --git a/ts/packages/cli/package.json b/ts/packages/cli/package.jsonindex 04d6a693b..a2a5143e3 100644--- a/ts/packages/cli/package.json+++ b/ts/packages/cli/package.json@@ -80,6 +80,7 @@"decompress": "^4.2.1","effect": "catalog:","indent-string": "^5.0.0",+ "js-tiktoken": "^1.0.21","open": "^10.2.0","openapi-typescript": "^7.8.0","picocolors": "^1.1.1",diff --git a/ts/packages/cli/src/commands/connected-accounts/commands/connected-accounts.link.cmd.ts b/ts/packages/cli/src/commands/connected-accounts/commands/connected-accounts.link.cmd.tsindex cff900457..f04fd568e 100644--- a/ts/packages/cli/src/commands/connected-accounts/commands/connected-accounts.link.cmd.ts+++ b/ts/packages/cli/src/commands/connected-accounts/commands/connected-accounts.link.cmd.ts@@ -13,6 +13,7 @@ import {resolveCommandProject,formatResolveCommandProjectError,} from 'src/services/command-project';+import { invalidateConsumerConnectedToolkitsCache } from 'src/services/consumer-short-term-cache';const toolkit = Args.text({ name: 'toolkit' }).pipe(Args.withDescription('Toolkit slug to link (e.g. "github", "gmail")'),@@ -206,12 +207,14 @@ const runConnectedAccountsLink = (params: {});if (Option.isNone(resolvedUserId)) {return yield* Effect.fail(- new Error('Missing user id. Provide --user-id or run composio init to set test_user_id.')+ new Error(+ 'Missing user id. Provide --user-id or run composio dev init to set test_user_id.'+ ));}if (Option.isNone(params.projectName) && Option.isNone(resolvedProjectContext)) {yield* ui.log.error(- '`--auth-config` is developer-project scoped. Pass `--project-name <name>` or run from a directory initialized with `composio init`.'+ '`--auth-config` is developer-project scoped. Pass `--project-name <name>` or run from a directory initialized with `composio dev init`.');return;}@@ -336,6 +339,7 @@ const runConnectedAccountsLink = (params: {if (Option.isNone(validatedLink)) return;const { connectedAccountId: connAccountId, redirectUrl } = validatedLink.value;+ yield* invalidateConsumerConnectedToolkitsCache().pipe(Effect.catchAll(() => Effect.void));if (params.noWait) {yield* ui.note(redirectUrl, 'Redirect URL');diff --git a/ts/packages/cli/src/commands/dev.cmd.ts b/ts/packages/cli/src/commands/dev.cmd.tsnew file mode 100644index 000000000..b34ff84a2--- /dev/null+++ b/ts/packages/cli/src/commands/dev.cmd.ts@@ -0,0 +1,12 @@+import { Command } from '@effect/cli';+import { initCmd } from './init.cmd';+import { triggersCmd$Listen } from './triggers/commands/triggers.listen.cmd';+import { logsCmd } from './logs-cmd/logs.cmd';+import { devToolsCmd$Execute } from './tools/commands/tools.execute.cmd';++export const devCmd = Command.make('dev').pipe(+ Command.withDescription(+ 'Developer workflows: initialize a local project, execute tools with playground users, listen for triggers, and inspect logs.'+ ),+ Command.withSubcommands([initCmd, devToolsCmd$Execute, triggersCmd$Listen, logsCmd])+);diff --git a/ts/packages/cli/src/commands/index.ts b/ts/packages/cli/src/commands/index.tsindex 3899bd6f7..a207bd38c 100644--- a/ts/packages/cli/src/commands/index.ts+++ b/ts/packages/cli/src/commands/index.ts@@ -1,4 +1,5 @@-import { Effect } from 'effect';+import process from 'node:process';+import { Effect, Option } from 'effect';import { Command } from '@effect/cli';import * as constants from 'src/constants';import { $defaultCmd } from './$default.cmd';@@ -8,16 +9,25 @@ import { upgradeCmd } from './upgrade.cmd';import { whoamiCmd } from './whoami.cmd';import { loginCmd } from './login.cmd';import { logoutCmd } from './logout.cmd';+import { runCmd } from './run.cmd';import { installCmd } from './install.cmd';-import { initCmd } from './init.cmd';import { generateCmd } from './generate/generate.cmd';import { manageCmd } from './manage/manage.cmd';+import { devCmd } from './dev.cmd';import { showToolsExecuteInputHelp } from './tools/commands/tools.execute.cmd';import { printRootHelp } from './root-help';import { rootToolsCmd$Search } from './tools/commands/tools.search.cmd';import { rootToolsCmd$Execute } from './tools/commands/tools.execute.cmd';+import { rootToolsCmd } from './tools/tools.cmd';import { rootConnectedAccountsCmd$Link } from './connected-accounts/commands/connected-accounts.link.cmd';-import { triggersCmd$Listen } from './triggers/commands/triggers.listen.cmd';+import { renderCommandHintGraph } from 'src/services/command-hints';+import { resetRuntimeDebugFlags, setRuntimeDebugFlags } from 'src/services/runtime-debug-flags';+import { ComposioUserContext } from 'src/services/user-context';+import { TerminalUI } from 'src/services/terminal-ui';+import {+ formatResolveCommandProjectError,+ resolveCommandProject,+} from 'src/services/command-project';const $cmd = $defaultCmd.pipe(Command.withSubcommands([@@ -26,12 +36,13 @@ const $cmd = $defaultCmd.pipe(whoamiCmd,loginCmd,logoutCmd,+ runCmd,installCmd,- initCmd,+ devCmd,+ rootToolsCmd,rootToolsCmd$Search,rootConnectedAccountsCmd$Link,rootToolsCmd$Execute,- triggersCmd$Listen,generateCmd,manageCmd,])@@ -102,11 +113,64 @@ const normalizeVersionShortFlag = (argv: ReadonlyArray<string>): ReadonlyArray<sreturn argv;};+const normalizeHiddenDebugFlags = (argv: ReadonlyArray<string>): ReadonlyArray<string> => {+ const normalized: string[] = [...argv.slice(0, 2)];+ const args = argv.slice(2);+ let perfDebug: boolean | undefined;+ let toolDebug: boolean | undefined;++ for (const arg of args) {+ if (arg === '--perf-debug') {+ perfDebug = true;+ continue;+ }+ if (arg === '--tool-debug') {+ toolDebug = true;+ continue;+ }+ if (arg === '--perf-debug=false') {+ perfDebug = false;+ continue;+ }+ if (arg === '--tool-debug=false') {+ toolDebug = false;+ continue;+ }+ if (arg === '--perf-debug=true') {+ perfDebug = true;+ continue;+ }+ if (arg === '--tool-debug=true') {+ toolDebug = true;+ continue;+ }+ normalized.push(arg);+ }++ resetRuntimeDebugFlags();+ setRuntimeDebugFlags({+ ...(perfDebug === undefined ? {} : { perfDebug }),+ ...(toolDebug === undefined ? {} : { toolDebug }),+ });++ return normalized;+};+const isRootHelp = (argv: ReadonlyArray<string>): boolean => {const args = argv.slice(2);return args.length === 1 && (args[0] === '--help' || args[0] === '-h');};+const isGenerateGraph = (argv: ReadonlyArray<string>): boolean => {+ const args = argv.slice(2);+ return args.length === 2 && args[0] === 'debug' && args[1] === 'generate-graph';+};++const isDebugApiInfo = (argv: ReadonlyArray<string>): boolean => {+ const args = argv.slice(2);+ return args.length === 2 && args[0] === 'debug' && args[1] === 'api-info';+};+export const runWithConfig = Effect.gen(function* () {const version = yield* getVersion;const run = Command.run($cmd, {@@ -116,10 +180,53 @@ export const runWithConfig = Effect.gen(function* () {});return (argv: ReadonlyArray<string>) => {- const normalizedArgv = normalizeVersionShortFlag(argv);+ const normalizedArgv = normalizeHiddenDebugFlags(normalizeVersionShortFlag(argv));if (isRootHelp(normalizedArgv)) {return printRootHelp();}+ if (isGenerateGraph(normalizedArgv)) {+ return Effect.sync(() => {+ process.stdout.write(`${JSON.stringify(renderCommandHintGraph(), null, 2)}\n`);+ });+ }+ if (isDebugApiInfo(normalizedArgv)) {+ return Effect.gen(function* () {+ const ui = yield* TerminalUI;+ const confirmed = yield* ui.confirm(+ 'This will print your current CLI API key and scoped identifiers to stdout. Continue?',+ { defaultValue: false }+ );+ if (!confirmed) {+ return yield* Effect.fail(new Error('Aborted printing API credentials.'));+ }+ const ctx = yield* ComposioUserContext;+ const apiKey = Option.getOrUndefined(ctx.data.apiKey);+ if (!apiKey) {+ return yield* Effect.fail(new Error('No user API key found in the current CLI session.'));+ }+ const orgId = Option.getOrUndefined(ctx.data.orgId);+ const consumerProject = yield* resolveCommandProject({ mode: 'consumer' }).pipe(+ Effect.mapError(formatResolveCommandProjectError),+ Effect.option+ );+ return yield* Effect.sync(() => {+ process.stdout.write(+ `${JSON.stringify(+ {+ apiKey,+ orgId: orgId ?? null,+ consumerUserId:+ Option.isSome(consumerProject) && consumerProject.value.projectType === 'CONSUMER'+ ? (consumerProject.value.consumerUserId ?? null)+ : null,+ },+ null,+ 2+ )}\n`+ );+ });+ });+ }const executeHelpSlug = parseExecuteInputHelpSlug(normalizedArgv);if (executeHelpSlug) {return showToolsExecuteInputHelp(executeHelpSlug);diff --git a/ts/packages/cli/src/commands/init.cmd.ts b/ts/packages/cli/src/commands/init.cmd.tsindex d734a87be..d3818c1cc 100644--- a/ts/packages/cli/src/commands/init.cmd.ts+++ b/ts/packages/cli/src/commands/init.cmd.ts@@ -230,7 +230,7 @@ export const initCmd = CliCommand.make(const ui = yield* TerminalUI;const proc = yield* NodeProcess;- yield* ui.intro('composio init');+ yield* ui.intro('composio dev init');const composioDir = path.join(proc.cwd, constants.PROJECT_COMPOSIO_DIR);@@ -276,7 +276,7 @@ const initInteractiveFlow = (params: { composioDir: string; noBrowser: boolean;yield* Effect.logDebug('Failed to list org projects:', e);yield* ui.log.warn('Could not fetch projects from the server.');yield* ui.log.info(- 'Create a project at https://platform.composio.dev, then run `composio init` again.'+ 'Create a project at https://platform.composio.dev, then run `composio dev init` again.');yield* ui.outro('');return yield* Effect.fail(e);@@ -287,7 +287,7 @@ const initInteractiveFlow = (params: { composioDir: string; noBrowser: boolean;yield* Effect.logDebug('Failed to decode org projects response:', e);yield* ui.log.warn('Unexpected response from the server.');yield* ui.log.info(- 'Create a project at https://platform.composio.dev, then run `composio init` again.'+ 'Create a project at https://platform.composio.dev, then run `composio dev init` again.');yield* ui.outro('');return yield* Effect.fail(e);@@ -298,7 +298,7 @@ const initInteractiveFlow = (params: { composioDir: string; noBrowser: boolean;if (orgProjects.data.length === 0) {yield* ui.log.warn('No projects found for your organization.');yield* ui.log.info(- 'Create a project at https://platform.composio.dev, then run `composio init` again.'+ 'Create a project at https://platform.composio.dev, then run `composio dev init` again.');yield* ui.outro('');return;diff --git a/ts/packages/cli/src/commands/login.cmd.ts b/ts/packages/cli/src/commands/login.cmd.tsindex c99227ff9..369ea2ede 100644--- a/ts/packages/cli/src/commands/login.cmd.ts+++ b/ts/packages/cli/src/commands/login.cmd.ts@@ -9,7 +9,9 @@ import {} from 'src/services/composio-clients';import { ComposioUserContext } from 'src/services/user-context';import { TerminalUI } from 'src/services/terminal-ui';+import { commandHintStep } from 'src/services/command-hints';import { runOrgSelection } from 'src/effects/select-org-project';+import { primeConsumerConnectedToolkitsCacheInBackground } from 'src/services/consumer-short-term-cache';export const noBrowser = Options.boolean('no-browser').pipe(Options.withDefault(false),@@ -104,14 +106,15 @@ const storeCredentials = (params: {}yield* ctx.login(uakApiKey, orgId, testUserId);+ yield* primeConsumerConnectedToolkitsCacheInBackground({+ orgId,+ });const email = sessionInfo?.org_member.email || fallbackEmail || undefined;yield* ui.log.success(email ? `Logged in as ${email}` : 'Logged in successfully');if (!skipHints) {- yield* ui.log.info(- 'Run `composio init` in your project directory to set up project context.'- );- yield* ui.log.info('To switch your default org later, run `composio manage orgs switch`.');+ yield* ui.log.info(commandHintStep('Set up developer project context', 'dev.init'));+ yield* ui.log.info(commandHintStep('Switch your default org later', 'manage.orgs.switch'));}// Emit structured JSON for piped/scripted consumption (agent-native)@@ -228,6 +231,9 @@ const loginWithKey = (params: { key: string; noWait: boolean; skipOrgProjectPickresult.id,testUserId ?? Option.getOrUndefined(ctx.data.testUserId));+ yield* primeConsumerConnectedToolkitsCacheInBackground({+ orgId: result.id,+ });yield* ui.log.success(`Default org set to "${result.name}".`);}const finalOrgId = result?.id ?? xOrgId;@@ -239,10 +245,8 @@ const loginWithKey = (params: { key: string; noWait: boolean; skipOrgProjectPickorg_name: finalOrgName,}));- yield* ui.log.info(- 'Run `composio init` in your project directory to set up project context.'- );- yield* ui.log.info('To switch your default org later, run `composio manage orgs switch`.');+ yield* ui.log.info(commandHintStep('Set up developer project context', 'dev.init'));+ yield* ui.log.info(commandHintStep('Switch your default org later', 'manage.orgs.switch'));yield* ui.outro("You're all set!");}});@@ -387,6 +391,9 @@ export const browserLogin = (params: {result.id,testUserId ?? Option.getOrUndefined(ctx.data.testUserId));+ yield* primeConsumerConnectedToolkitsCacheInBackground({+ orgId: result.id,+ });yield* ui.log.success(`Default org set to "${result.name}".`);}const finalOrgId = result?.id ?? xOrgId;@@ -398,10 +405,8 @@ export const browserLogin = (params: {org_name: finalOrgName,}));- yield* ui.log.info(- 'Run `composio init` in your project directory to set up project context.'- );- yield* ui.log.info('To switch your default org later, run `composio manage orgs switch`.');+ yield* ui.log.info(commandHintStep('Set up developer project context', 'dev.init'));+ yield* ui.log.info(commandHintStep('Switch your default org later', 'manage.orgs.switch'));yield* ui.outro("You're all set!");}});diff --git a/ts/packages/cli/src/commands/logs-cmd/commands/logs.tools.cmd.ts b/ts/packages/cli/src/commands/logs-cmd/commands/logs.tools.cmd.tsindex 1413ca53d..3fd8199b4 100644--- a/ts/packages/cli/src/commands/logs-cmd/commands/logs.tools.cmd.ts+++ b/ts/packages/cli/src/commands/logs-cmd/commands/logs.tools.cmd.ts@@ -6,6 +6,7 @@ import { ComposioClientSingleton } from 'src/services/composio-clients';import { clampLimit } from 'src/ui/clamp-limit';import { parseCsv } from 'src/commands/triggers/parse-csv';import { formatToolLogInfo, formatToolLogsTable } from '../format';+import { commandHintStep } from 'src/services/command-hints';import { toSearchParam } from '../utils';type ToolLogFilterInput = {@@ -223,7 +224,9 @@ export const logsCmd$Tools = Command.make(const firstLogId = logs[0]?.id;if (firstLogId) {yield* ui.log.step(- `To view full details for a log:\n> composio manage logs tools "${firstLogId}"`+ commandHintStep('To view full details for a log', 'dev.logs.tools', {+ logId: firstLogId,+ }));}diff --git a/ts/packages/cli/src/commands/logs-cmd/commands/logs.triggers.cmd.ts b/ts/packages/cli/src/commands/logs-cmd/commands/logs.triggers.cmd.tsindex e989948ba..1d7bd8fb2 100644--- a/ts/packages/cli/src/commands/logs-cmd/commands/logs.triggers.cmd.ts+++ b/ts/packages/cli/src/commands/logs-cmd/commands/logs.triggers.cmd.ts@@ -6,6 +6,7 @@ import { ComposioClientSingleton } from 'src/services/composio-clients';import { clampLimit } from 'src/ui/clamp-limit';import { parseCsv } from 'src/commands/triggers/parse-csv';import { formatTriggerLogInfo, formatTriggerLogsTable } from '../format';+import { commandHintStep } from 'src/services/command-hints';import { toSearchParam } from '../utils';const cursor = Options.text('cursor').pipe(@@ -193,7 +194,9 @@ export const logsCmd$Triggers = Command.make(const firstLogId = logs[0]?.id;if (firstLogId) {yield* ui.log.step(- `To view full details for a log:\n> composio manage logs triggers "${firstLogId}"`+ commandHintStep('To view full details for a log', 'dev.logs.triggers', {+ logId: firstLogId,+ }));}diff --git a/ts/packages/cli/src/commands/manage/manage.cmd.ts b/ts/packages/cli/src/commands/manage/manage.cmd.tsindex f711aaf5b..81ccc384b 100644--- a/ts/packages/cli/src/commands/manage/manage.cmd.ts+++ b/ts/packages/cli/src/commands/manage/manage.cmd.ts@@ -1,37 +1,33 @@import { Command } from '@effect/cli';import { toolkitsCmd } from '../toolkits/toolkits.cmd';-import { toolsCmd } from '../tools/tools.cmd';import { authConfigsCmd } from '../auth-configs/auth-configs.cmd';import { connectedAccountsCmd } from '../connected-accounts/connected-accounts.cmd';import { triggersCmd } from '../triggers/triggers.cmd';-import { logsCmd } from '../logs-cmd/logs.cmd';import { orgsCmd } from '../orgs/orgs.cmd';import { projectsCmd } from '../projects/projects.cmd';/**- * CLI entry point for management commands.+ * CLI entry point for developer management commands.*- * Groups toolkits, tools, auth-configs, connected-accounts, triggers, logs, orgs, and projects+ * Groups orgs, toolkits, connected-accounts, triggers, auth-configs, and projects* under a single `composio manage` namespace.** @example* ```bash* composio manage <command>* composio manage toolkits list- * composio manage tools search "send email"+ * composio manage projects list* ```*/export const manageCmd = Command.make('manage').pipe(Command.withDescription(- 'Developer/admin workflows: orgs, toolkits, tools, accounts, triggers, logs, auth configs, and deprecated project commands.'+ 'Manage your developer orgs, toolkits, connected accounts, triggers, auth configs, and projects.'),Command.withSubcommands([toolkitsCmd,- toolsCmd,authConfigsCmd,connectedAccountsCmd,triggersCmd,- logsCmd,orgsCmd,projectsCmd,])diff --git a/ts/packages/cli/src/commands/orgs/commands/orgs.switch.cmd.ts b/ts/packages/cli/src/commands/orgs/commands/orgs.switch.cmd.tsindex 1b5511ac7..54f718f6b 100644--- a/ts/packages/cli/src/commands/orgs/commands/orgs.switch.cmd.ts+++ b/ts/packages/cli/src/commands/orgs/commands/orgs.switch.cmd.ts@@ -31,7 +31,7 @@ export const orgsCmd$Switch = Command.make('switch', { orgId, limit }, ({ orgId,}yield* ui.note(- 'This updates your default org for CLI commands. Use `composio init` for local developer project setup.',+ 'This updates your default org for CLI commands. Use `composio dev init` for local developer project setup.','Global defaults');diff --git a/ts/packages/cli/src/commands/projects/commands/projects.list.cmd.ts b/ts/packages/cli/src/commands/projects/commands/projects.list.cmd.tsindex 33f7cc8e6..88118a7e8 100644--- a/ts/packages/cli/src/commands/projects/commands/projects.list.cmd.ts+++ b/ts/packages/cli/src/commands/projects/commands/projects.list.cmd.ts@@ -54,7 +54,7 @@ export const projectsCmd$List = Command.make('list', { orgId, limit }, ({ orgId,if (projects.data.length === 0) {yield* ui.log.warn('No projects found.');yield* ui.outro(- 'Hint: run `composio init` in a directory to bind it to a developer project.'+ 'Hint: run `composio dev init` in a directory to bind it to a developer project.');return;}@@ -65,7 +65,7 @@ export const projectsCmd$List = Command.make('list', { orgId, limit }, ({ orgId,yield* ui.log.step(lines.join('\n'));yield* ui.outro([- 'Hint: run `composio init` in a directory to bind it to a developer project.',+ 'Hint: run `composio dev init` in a directory to bind it to a developer project.','Run `composio manage orgs switch` to change your default org.',].join('\n'));diff --git a/ts/packages/cli/src/commands/projects/commands/projects.switch.cmd.ts b/ts/packages/cli/src/commands/projects/commands/projects.switch.cmd.tsindex 46a69202c..d94407e76 100644--- a/ts/packages/cli/src/commands/projects/commands/projects.switch.cmd.ts+++ b/ts/packages/cli/src/commands/projects/commands/projects.switch.cmd.ts@@ -8,7 +8,7 @@ export const projectsCmd$Switch = Command.make('switch', {}).pipe(Effect.gen(function* () {const ui = yield* TerminalUI;yield* ui.log.error(- 'Global developer project switching is no longer supported. Run `composio init` in a directory to bind it to a developer project.'+ 'Global developer project switching is no longer supported. Run `composio dev init` in a directory to bind it to a developer project.');}))diff --git a/ts/packages/cli/src/commands/projects/projects.cmd.ts b/ts/packages/cli/src/commands/projects/projects.cmd.tsindex 78c8b7399..a13b6e4af 100644--- a/ts/packages/cli/src/commands/projects/projects.cmd.ts+++ b/ts/packages/cli/src/commands/projects/projects.cmd.ts@@ -6,6 +6,6 @@ import { projectsCmd$Switch } from './commands/projects.switch.cmd';* CLI entry point for project context commands.*/export const projectsCmd = Command.make('projects').pipe(- Command.withDescription('Manage default global project context.'),+ Command.withDescription('Inspect developer projects and project context helpers.'),Command.withSubcommands([projectsCmd$List, projectsCmd$Switch]));diff --git a/ts/packages/cli/src/commands/root-help.ts b/ts/packages/cli/src/commands/root-help.tsindex 9d58597db..f15f0e8e0 100644--- a/ts/packages/cli/src/commands/root-help.ts+++ b/ts/packages/cli/src/commands/root-help.ts@@ -47,17 +47,43 @@ const BASIC_COMMANDS: ReadonlyArray<BasicCommand> = [usage: 'logout',},{- name: 'init',- description: 'Initialize this directory with a developer project.',- usage: 'init [--no-browser] [-y, --yes]',+ name: 'run',+ description: 'Run inline ESNext TS/JS code or a file with Bun and injected Composio helpers.',+ usage:+ 'run <code> [-- ...args] | run [-f, --file text] [-- ...args] [--dry-run] [--skip-connection-check] [--skip-tool-params-check] [--no-verify]',options: [- { name: '--no-browser', description: 'Skip opening browser for auth' },- { name: '-y, --yes', description: 'Auto-select the default developer project' },+ {+ name: '<code>',+ description:+ 'Inline Bun ESNext code with injected execute(slug, data?) and search(query, options?) helpers',+ },+ {+ name: '-f, --file',+ description: 'Run a TS/JS file with the Bun runtime instead of inline code',+ },+ {+ name: '--dry-run',+ description: 'Preview execute(...) calls without running remote actions',+ },+ {+ name: '--skip-connection-check',+ description:+ 'Skip the short-lived linked-account fail-fast check if you just connected an account',+ },+ {+ name: '--skip-tool-params-check',+ description: 'Skip the local tool parameter/schema validation check',+ },+ {+ name: '--no-verify',+ description:+ 'Skip both the linked-account fail-fast check and the local tool parameter check',+ },],},{name: 'search',- description: 'Search tools by use case across toolkits/apps.',+ description: 'Semantic search for tools by use case across all toolkits/apps.',usage: 'search <query> [--toolkits text] [--limit integer]',options: [{ name: '<query>', description: 'Semantic use-case query (e.g. "send emails")' },@@ -65,13 +91,54 @@ const BASIC_COMMANDS: ReadonlyArray<BasicCommand> = [{ name: '--limit', description: 'Number of results per page (1-1000)' },],},+ {+ name: 'tools',+ description: 'List tools for one toolkit, or inspect a cached schema-backed summary.',+ usage: 'tools list <toolkit> [--query text] | tools info <slug>',+ options: [+ {+ name: 'list <toolkit>',+ description: 'Non-semantic per-toolkit listing; use this when you already know the toolkit',+ },+ {+ name: 'info <slug>',+ description:+ 'Print a brief summary and cache the same raw schema used by execute --get-schema',+ },+ ],+ },{name: 'execute',- description: 'Execute a tool.',- usage: 'execute <slug> [-d, --data text]',+ description: 'Execute a tool, preview it with --dry-run, or fetch its input schema.',+ usage:+ 'execute <slug> [-d, --data text] [--dry-run] [--get-schema] [--skip-connection-check] [--skip-tool-params-check] [--no-verify]',options: [{ name: '<slug>', description: 'Tool slug (e.g. "GITHUB_CREATE_ISSUE")' },- { name: '-d, --data', description: 'JSON arguments, @file, or - for stdin' },+ {+ name: '-d, --data',+ description:+ 'JSON or JS-style object arguments, e.g. -d \'{ repo: "foo" }\', @file, or - for stdin',+ },+ { name: '--dry-run', description: 'Validate and preview the tool call without executing it' },+ {+ name: '--get-schema',+ description:+ 'Fetch and print the raw cached schema; tools info shows the same schema with a brief summary',+ },+ {+ name: '--skip-connection-check',+ description:+ 'Skip the short-lived linked-account fail-fast check if you just connected an account',+ },+ {+ name: '--skip-tool-params-check',+ description: 'Skip the local tool parameter/schema validation check',+ },+ {+ name: '--no-verify',+ description:+ 'Skip both the linked-account fail-fast check and the local tool parameter check',+ },],},{@@ -83,28 +150,14 @@ const BASIC_COMMANDS: ReadonlyArray<BasicCommand> = [{ name: '--no-browser', description: 'Skip auto-opening the browser' },],},- {- name: 'listen',- description: 'Listen for trigger events.',- usage:- 'listen [--toolkits text] [--trigger-id text] [--user-id text] [--max-events integer] [--forward text] [--out text]',- options: [- { name: '--toolkits', description: 'Filter by toolkit slugs, comma-separated' },- { name: '--trigger-id', description: 'Filter by trigger id' },- { name: '--user-id', description: 'Filter by user id' },- { name: '--max-events', description: 'Stop after N matching events' },- {- name: '--forward',- description: 'Forward events to URL (signed with COMPOSIO_WEBHOOK_SECRET)',- },- { name: '--out', description: 'Append events to file' },- { name: '--json', description: 'Show raw event payload as JSON' },- { name: '--table', description: 'Show compact table rows' },- ],- },];const ADVANCED_COMMANDS: ReadonlyArray<{ name: string; description: string }> = [+ {+ name: 'dev',+ description:+ 'Developer workflows: init a local project, execute tools with playground users, listen for triggers, and inspect logs.',+ },{name: 'generate',description:@@ -113,7 +166,7 @@ const ADVANCED_COMMANDS: ReadonlyArray<{ name: string; description: string }> ={name: 'manage',description:- 'Developer/admin workflows: orgs, toolkits, triggers, auth configs, logs, and deprecated project commands.',+ 'Manage your developer orgs, toolkits, connected accounts, triggers, auth configs, and projects.',},];@@ -146,7 +199,9 @@ export function printRootHelp(): Effect.Effect<void> {const lines: string[] = ['',- '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.',+ '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.',+ "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.",+ 'Use `dev` when you are building with Composio and want scaffolding, playground execution, triggers, and logs.','',bold('USAGE'),` ${name} <command> [options]`,diff --git a/ts/packages/cli/src/commands/run.cmd.ts b/ts/packages/cli/src/commands/run.cmd.tsnew file mode 100644index 000000000..201fa23eb--- /dev/null+++ b/ts/packages/cli/src/commands/run.cmd.ts@@ -0,0 +1,363 @@+import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';+import process from 'node:process';+import { Args, Command, Options } from '@effect/cli';+import { Effect, Option } from 'effect';+import { ts } from 'ts-morph';+import { resolveCommandProject } from 'src/services/command-project';+import { warmToolInputDefinitions } from 'src/services/tool-input-validation';+import { ComposioUserContext } from 'src/services/user-context';+import { isPerfDebugEnabled, isToolDebugEnabled } from 'src/services/runtime-debug-flags';++const file = Options.text('file').pipe(+ Options.withAlias('f'),+ Options.withDescription('Run a TS/JS file instead of inline code'),+ Options.optional+);++const dryRun = Options.boolean('dry-run').pipe(Options.withDefault(false));+const skipConnectionCheck = Options.boolean('skip-connection-check').pipe(+ Options.withDefault(false)+);+const skipToolParamsCheck = Options.boolean('skip-tool-params-check').pipe(+ Options.withDefault(false)+);+const noVerify = Options.boolean('no-verify').pipe(Options.withDefault(false));++const args = Args.repeated(Args.text({ name: 'arg' })).pipe(+ Args.withDescription('Inline code followed by arguments, or just arguments when using --file')+);++const withArgDelimiter = (args: ReadonlyArray<string>) => (args.length > 0 ? ['--', ...args] : []);++export const extractInlineExecuteToolSlugs = (source: string): ReadonlyArray<string> => {+ if (!source.trim()) {+ return [];+ }++ const parsed = ts.createSourceFile(+ 'composio-run-inline.ts',+ source,+ ts.ScriptTarget.Latest,+ true,+ ts.ScriptKind.TSX+ );+ const slugs = new Set<string>();++ const visit = (node: ts.Node) => {+ if (+ ts.isCallExpression(node) &&+ ts.isIdentifier(node.expression) &&+ node.expression.text === 'execute'+ ) {+ const [slugArg] = node.arguments;+ if (slugArg && ts.isStringLiteralLike(slugArg)) {+ slugs.add(slugArg.text);+ }+ }++ ts.forEachChild(node, visit);+ };++ visit(parsed);+ return [...slugs];+};++export const inferCliInvocationPrefix = (+ argv: ReadonlyArray<string> = process.argv+): ReadonlyArray<string> => {+ const entrypoint = argv[1];+ if (!entrypoint) {+ return [process.execPath];+ }++ // Compiled Bun binaries report an internal $bunfs entrypoint which cannot be+ // re-executed as a real filesystem path. In that case the binary itself is+ // the CLI entrypoint.+ if (entrypoint.startsWith('/$bunfs/')) {+ return [process.execPath];+ }++ const resolvedEntrypoint = path.resolve(entrypoint);+ return fs.existsSync(resolvedEntrypoint)+ ? [process.execPath, resolvedEntrypoint]+ : [process.execPath];+};++type RunHelperContext = {+ readonly apiKey?: string;+ readonly baseURL?: string;+ readonly webURL?: string;+ readonly orgId?: string;+ readonly consumerUserId?: string;+ readonly consumerProjectId?: string;+ readonly consumerProjectName?: string;+ readonly perfDebug?: boolean;+ readonly toolDebug?: boolean;+ readonly dryRun?: boolean;+ readonly skipConnectionCheck?: boolean;+ readonly skipToolParamsCheck?: boolean;+ readonly noVerify?: boolean;+};++export const buildRunHelpersSource = (+ cliPrefix: ReadonlyArray<string>,+ context: RunHelperContext = {}+): string =>+ [+ `const cliPrefix = ${JSON.stringify(cliPrefix)};`,+ `const helperContext = ${JSON.stringify(context)};`,+ '',+ 'const perfDebugEnabled = helperContext.perfDebug === true || process.env.COMPOSIO_PERF_DEBUG === "1";',+ 'const toolDebugEnabled = helperContext.toolDebug === true || process.env.COMPOSIO_TOOL_DEBUG === "1";',+ 'const perfDebugStart = Date.now();',+ 'let perfDebugSeq = 0;',+ 'const perfDebugLog = (phase, label, details = {}) => {',+ ' if (!perfDebugEnabled) return;',+ ' const elapsedMs = Date.now() - perfDebugStart;',+ ' const payload = { phase, label, elapsedMs, ...details };',+ ' console.error(`[perf] ${JSON.stringify(payload)}`);',+ '};',+ 'const parseJson = (text) => {',+ ' const value = text.trim();',+ ' if (!value) return undefined;',+ ' try {',+ ' return JSON.parse(value);',+ ' } catch {',+ ' return value;',+ ' }',+ '};',+ '',+ 'const runCliJson = async (args) => {',+ ' const requestId = `${args[0] ?? "cli"}#${++perfDebugSeq}`;',+ ' const env = {',+ ' ...process.env,',+ ' ...(helperContext.apiKey ? { COMPOSIO_USER_API_KEY: helperContext.apiKey } : {}),',+ ' ...(helperContext.baseURL ? { COMPOSIO_BASE_URL: helperContext.baseURL } : {}),',+ ' ...(helperContext.webURL ? { COMPOSIO_WEB_URL: helperContext.webURL } : {}),',+ ' ...(perfDebugEnabled ? { COMPOSIO_PERF_DEBUG: "1" } : {}),',+ ' ...(toolDebugEnabled ? { COMPOSIO_TOOL_DEBUG: "1" } : {}),',+ ' };',+ ' delete env.BUN_BE_BUN;',+ ' perfDebugLog("start", requestId, { cmd: args });',+ ' const child = Bun.spawn({',+ ' cmd: [...cliPrefix, ...args],',+ ' env,',+ " stdio: ['inherit', 'pipe', perfDebugEnabled || toolDebugEnabled ? 'inherit' : 'pipe'],",+ ' });',+ ' const stdout = child.stdout ? await new Response(child.stdout).text() : "";',+ ' const stderr = child.stderr ? await new Response(child.stderr).text() : "";',+ ' const result = parseJson(stdout);',+ ' const exitCode = await child.exited;',+ ' if (exitCode !== 0) {',+ ' perfDebugLog("error", requestId, { exitCode, stderr: stderr.trim() || undefined });',+ ' const error = new Error(`composio ${args.join(" ")} failed with exit code ${exitCode}`);',+ ' Object.assign(error, { exitCode, result, stderr: stderr.trim() || undefined });',+ ' throw error;',+ ' }',+ ' if (result === undefined) {',+ ' const details = stderr.trim();',+ ' const suffix = details ? `: ${details}` : "";',+ ' perfDebugLog("error", requestId, { exitCode, stderr: details || undefined, noJson: true });',+ ' const error = new Error(`composio ${args.join(" ")} returned no JSON output${suffix}`);',+ ' Object.assign(error, { exitCode, result, stderr: details || undefined });',+ ' throw error;',+ ' }',+ ' perfDebugLog("end", requestId, { exitCode, stdoutBytes: stdout.length, stderrBytes: stderr.length });',+ ' return result;',+ '};',+ '',+ 'globalThis.search = async (query, options = {}) => {',+ ' const args = ["search", query];',+ ' if (Array.isArray(options.toolkits) && options.toolkits.length > 0) {',+ ' args.push("--toolkits", options.toolkits.join(","));',+ ' } else if (typeof options.toolkits === "string" && options.toolkits.trim().length > 0) {',+ ' args.push("--toolkits", options.toolkits);',+ ' }',+ ' if (typeof options.limit === "number") {',+ ' args.push("--limit", String(options.limit));',+ ' }',+ ' return runCliJson(args);',+ '};',+ '',+ 'globalThis.execute = async (slug, data = {}) => {',+ ' const args = ["execute", slug];',+ ' if (helperContext.dryRun === true) {',+ ' args.push("--dry-run");',+ ' }',+ ' if (helperContext.skipConnectionCheck === true) {',+ ' args.push("--skip-connection-check");',+ ' }',+ ' if (helperContext.skipToolParamsCheck === true) {',+ ' args.push("--skip-tool-params-check");',+ ' }',+ ' if (helperContext.noVerify === true) {',+ ' args.push("--no-verify");',+ ' }',+ ' if (data !== undefined) {',+ ' const serialized = typeof data === "string" ? data : JSON.stringify(data);',+ ' args.push("--data", serialized);',+ ' }',+ ' return runCliJson(args);',+ '};',+ '',+ 'Object.defineProperty(globalThis, "__composioConsumerContext", {',+ ' value: helperContext,',+ ' configurable: true,',+ '});',+ '',+ ].join('\n');++const createRunHelpersPreloadFile = (+ cliPrefix: ReadonlyArray<string>,+ context: RunHelperContext+) => {+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'composio-run-'));+ const preloadPath = path.join(directory, 'globals.mjs');+ fs.writeFileSync(preloadPath, buildRunHelpersSource(cliPrefix, context), 'utf8');+ return { directory, preloadPath };+};++export const buildRunCommand = ({+ file,+ args,+ preloadPath,+}: {+ file: Option.Option<string>;+ args: ReadonlyArray<string>;+ preloadPath: string;+}) => {+ const base = [process.execPath, '--preload', preloadPath];+ if (Option.isSome(file)) {+ return [...base, 'run', file.value, ...withArgDelimiter(args)];+ }++ const [inlineCode, ...scriptArgs] = args;+ if (inlineCode) {+ return [...base, '--eval', inlineCode, ...withArgDelimiter(scriptArgs)];+ }++ throw new Error('Provide inline code or use --file to run a script file.');+};++const resolveRunHelperContext = () =>+ Effect.gen(function* () {+ const userContext = yield* ComposioUserContext;+ const apiKey = Option.getOrUndefined(userContext.data.apiKey);+ const orgId = Option.getOrUndefined(userContext.data.orgId);+ const baseContext = {+ apiKey,+ baseURL: userContext.data.baseURL,+ webURL: userContext.data.webURL,+ orgId,+ } satisfies RunHelperContext;++ if (!apiKey || !orgId) {+ return baseContext;+ }++ const consumerProject = yield* resolveCommandProject({ mode: 'consumer' }).pipe(Effect.option);+ if (Option.isNone(consumerProject) || consumerProject.value.projectType !== 'CONSUMER') {+ return baseContext;+ }++ return {+ ...baseContext,+ consumerUserId: consumerProject.value.consumerUserId,+ consumerProjectId: consumerProject.value.projectId,+ consumerProjectName: consumerProject.value.projectName,+ } satisfies RunHelperContext;+ });++export const runCmd = Command.make('run', {+ file,+ dryRun,+ skipConnectionCheck,+ skipToolParamsCheck,+ noVerify,+ args,+}).pipe(+ Command.withDescription(+ [+ 'Run inline TS/JS code or a file with the embedded Bun runtime.',+ 'Use this for programmatic multi-step tool workflows when you want to stay in code and not orchestrate everything through bash.',+ '',+ 'Usage:',+ " composio run '<code>' [-- ...args]",+ ' composio run --file ./script.ts [-- ...args]',+ '',+ 'Examples:',+ ` composio run 'const issue = await execute("GITHUB_CREATE_ISSUE", { owner: "acme", repo: "app", title: "Bug report" }); console.log(issue)'`,+ ` composio run --skip-connection-check 'const email = await execute("GMAIL_SEND_EMAIL", { recipient_email: "[email protected]", body: "Hello" }); console.log(email)'`,+ ` composio run --skip-tool-params-check 'const email = await execute("GMAIL_SEND_EMAIL", { recipient_email: "[email protected]", body: "Hello" }); console.log(email)'`,+ ` composio run --no-verify 'const email = await execute("GMAIL_SEND_EMAIL", { recipient_email: "[email protected]", body: "Hello" }); console.log(email)'`,+ ` composio run --dry-run 'const email = await execute("GMAIL_SEND_EMAIL", { recipient_email: "[email protected]", body: "Hello" }); console.log(email)'`,+ ' composio run --file ./script.ts -- hello world',+ '',+ 'Injected globals:',+ ' await execute(slug, data?)',+ ' Primary helper. Wraps `composio execute` and returns parsed JSON output quickly.',+ ' It validates arguments against cached tool schemas in `~/.composio/tool_definitions/` when available.',+ ' await search(query, { toolkits?: string[] | string, limit?: number })',+ ' Secondary discovery helper. Wraps `composio search` and returns parsed JSON stdout.',+ ' Both helpers automatically reuse your top level `execute` and `search` auth states, using the toolkits and apps you have already authorized.',+ '',+ 'Hints:',+ ' Use `composio search "<query>"` outside `run` to discover tool slugs before writing a script.',+ ' Use `composio link <toolkit>` outside `run` to authenticate apps up front before calling `execute(...)`.',+ ' Use `composio execute <slug> --get-schema` if you want to inspect tool inputs before scripting.',+ ' Since execute responses are parsed back into code almost instantly, it is usually fine to just try `execute(...)` directly in a script.',+ ' Treat `run` as the place to compose many tool calls once discovery and auth are already handled.',+ '',+ 'Advanced:',+ ' import { $ } from "bun"',+ ' await $`${process.execPath} manage toolkits list`',+ ].join('\n')+ ),+ Command.withHandler(+ ({ file, dryRun, skipConnectionCheck, skipToolParamsCheck, noVerify, args }) =>+ Effect.gen(function* () {+ const perfDebug = isPerfDebugEnabled();+ const toolDebug = isToolDebugEnabled();+ if (Option.isNone(file)) {+ const [inlineCode] = args;+ const preloadSlugs = extractInlineExecuteToolSlugs(inlineCode ?? '');+ if (preloadSlugs.length > 0) {+ yield* warmToolInputDefinitions(preloadSlugs).pipe(+ Effect.catchAll(() => Effect.void),+ Effect.forkDaemon+ );+ }+ }++ const preload = createRunHelpersPreloadFile(inferCliInvocationPrefix(), {+ ...(yield* resolveRunHelperContext()),+ perfDebug,+ toolDebug,+ dryRun,+ skipConnectionCheck,+ skipToolParamsCheck,+ noVerify,+ });+ try {+ const child = Bun.spawn({+ cmd: buildRunCommand({ file, args, preloadPath: preload.preloadPath }),+ env: {+ ...process.env,+ BUN_BE_BUN: '1',+ ...(perfDebug ? { COMPOSIO_PERF_DEBUG: '1' } : {}),+ ...(toolDebug ? { COMPOSIO_TOOL_DEBUG: '1' } : {}),+ },+ stdio: ['inherit', 'inherit', 'inherit'],+ });++ const exitCode = yield* Effect.promise(() => child.exited);+ fs.rmSync(preload.directory, { recursive: true, force: true });+ process.exit(exitCode);+ } finally {+ fs.rmSync(preload.directory, { recursive: true, force: true });+ }+ })+ )+);diff --git a/ts/packages/cli/src/commands/toolkits/commands/toolkits.info.cmd.ts b/ts/packages/cli/src/commands/toolkits/commands/toolkits.info.cmd.tsindex 5fc9fb7b6..664364449 100644--- a/ts/packages/cli/src/commands/toolkits/commands/toolkits.info.cmd.ts+++ b/ts/packages/cli/src/commands/toolkits/commands/toolkits.info.cmd.ts@@ -163,7 +163,7 @@ export const toolkitsCmd$Info = Command.make(// Next step hintyield* ui.log.step(- `To list tools in this toolkit:\n> composio manage tools list --toolkits "${toolkit.slug}"`+ `To list tools in this toolkit:\n> composio tools list "${toolkit.slug}"`);yield* ui.output(formatToolkitInfoJson(toolkit, detailedToolkit, allDetails));diff --git a/ts/packages/cli/src/commands/toolkits/commands/toolkits.list.cmd.ts b/ts/packages/cli/src/commands/toolkits/commands/toolkits.list.cmd.tsindex a4529c88a..7c67774eb 100644--- a/ts/packages/cli/src/commands/toolkits/commands/toolkits.list.cmd.ts+++ b/ts/packages/cli/src/commands/toolkits/commands/toolkits.list.cmd.ts@@ -83,7 +83,7 @@ export const toolkitsCmd$List = Command.make(if (Option.isSome(connected) && Option.isNone(resolvedUserId)) {yield* ui.log.warn(- '`--connected` requires a user id. Use `--user-id` or run `composio init`.'+ '`--connected` requires a user id. Use `--user-id` or run `composio dev init`.');}diff --git a/ts/packages/cli/src/commands/tools/commands/tools.execute.cmd.ts b/ts/packages/cli/src/commands/tools/commands/tools.execute.cmd.tsindex 8026dce65..30e85ee33 100644--- a/ts/packages/cli/src/commands/tools/commands/tools.execute.cmd.ts+++ b/ts/packages/cli/src/commands/tools/commands/tools.execute.cmd.ts@@ -1,25 +1,37 @@import { Args, Command, Options } from '@effect/cli';+import * as fs from 'node:fs';+import * as path from 'node:path';import util from 'node:util';-import { Effect, Option, Either } from 'effect';+import { Effect, Option, Either, Exit, Fiber, Cause } from 'effect';import { FileSystem } from '@effect/platform';-import { JSONParse } from 'src/effects/json';+import { parse as parseJsonWithComments } from 'comment-json';+import { encodingForModel } from 'js-tiktoken';import { redact } from 'src/ui/redact';import { readStdin, readStdinIfPiped } from 'src/effects/read-stdin';import { requireAuth } from 'src/effects/require-auth';+import {+ getCachedToolInputDefinition,+ getOrFetchToolInputDefinition,+ invalidateToolInputDefinition,+ refreshToolInputDefinitionIfVersionChanged,+ ToolInputValidationError,+ validateToolInputArguments,+ validateToolInputArgumentsWithDefinition,+} from 'src/services/tool-input-validation';import { TerminalUI } from 'src/services/terminal-ui';import {ActionExecuteConnectedAccountNotFoundError,ToolsExecutor,} from 'src/services/tools-executor';-import type { ToolExecuteParams } from 'src/services/tools-executor';+import type { ToolExecuteParams, ToolExecuteResponse } from 'src/services/tools-executor';import { ComposioToolkitsRepository } from 'src/services/composio-clients';import { ComposioUserContext } from 'src/services/user-context';+import { ProjectContext } from 'src/services/project-context';import {extractApiErrorDetails,extractMessage,extractSlug,} from 'src/utils/api-error-extraction';-import { bold } from 'src/ui/colors';import { handleHttpServerError } from 'src/effects/handle-http-error';import { formatToolInputParameters } from '../format';import { ComposioClientSingleton } from 'src/services/composio-clients';@@ -27,6 +39,12 @@ import {resolveCommandProject,formatResolveCommandProjectError,} from 'src/services/command-project';+import { commandHintStep } from 'src/services/command-hints';+import { isPerfDebugEnabled, isToolDebugEnabled } from 'src/services/runtime-debug-flags';+import {+ getFreshConsumerConnectedToolkitsFromCache,+ refreshConsumerConnectedToolkitsCache,+} from 'src/services/consumer-short-term-cache';const slug = Args.text({ name: 'slug' }).pipe(Args.withDescription('Tool slug (e.g. "GITHUB_CREATE_ISSUE")')@@ -48,6 +66,16 @@ const projectName = Options.text('project-name').pipe(Options.withDescription('Developer project name override for this command'));+const getSchema = Options.boolean('get-schema').pipe(Options.withDefault(false));+const dryRun = Options.boolean('dry-run').pipe(Options.withDefault(false));+const skipConnectionCheck = Options.boolean('skip-connection-check').pipe(+ Options.withDefault(false)+);+const skipToolParamsCheck = Options.boolean('skip-tool-params-check').pipe(+ Options.withDefault(false)+);+const noVerify = Options.boolean('no-verify').pipe(Options.withDefault(false));+const resolveInput = (input: Option.Option<string>) =>Effect.gen(function* () {const fs = yield* FileSystem.FileSystem;@@ -78,15 +106,26 @@ const resolveInput = (input: Option.Option<string>) =>const parseArguments = (raw: string) =>Effect.gen(function* () {- const parsed = (yield* JSONParse(raw).pipe(- Effect.mapError(- () =>- new Error('Invalid JSON input. Provide a JSON object, e.g. -d "{\\"key\\":\\"value\\"}"')- )- )) as unknown;+ const parsed = yield* Effect.try({+ try: () => {+ try {+ return JSON.parse(raw) as unknown;+ } catch {+ try {+ return parseJsonWithComments(raw, undefined, true) as unknown;+ } catch {+ return Function(`"use strict"; return (${raw});`)() as unknown;+ }+ }+ },+ catch: () =>+ new Error(+ 'Invalid JSON input. Provide JSON or a JS-style object literal, e.g. -d \'{ "key": "value" }\''+ ),+ });if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {return yield* Effect.fail(- new Error('Expected a JSON object for tool arguments, e.g. -d "{\\"key\\":\\"value\\"}"')+ new Error('Expected a JSON object for tool arguments, e.g. -d \'{ "key": "value" }\''));}return parsed as Record<string, unknown>;@@ -100,25 +139,40 @@ const toolkitFromToolSlug = (toolSlug: string): string | undefined => {return prefix;};-const connectionTips = (toolSlug: string, surface: 'root' | 'manage') => {+const connectionTips = (toolSlug: string, surface: 'root' | 'manage' | 'dev') => {const toolkit = toolkitFromToolSlug(toolSlug);+ const executeStep =+ surface === 'dev'+ ? commandHintStep('Retry', 'dev.execute', {+ slug: toolSlug,+ userId: '<user-id>',+ data: '...',+ })+ : commandHintStep('Retry', 'root.execute', { slug: toolSlug, data: '...' });if (!toolkit) {- return `Retry: ${bold(`composio execute ${toolSlug} ...`)}`;+ return executeStep;}return [- `Link the toolkit first: ${bold(- surface === 'root'- ? `composio link ${toolkit}`- : `composio manage connected-accounts link ${toolkit} --user-id "<user-id>"`- )}`,- `Then retry: ${bold(- surface === 'root'- ? `composio execute ${toolSlug} ...`- : `composio manage tools execute ${toolSlug} ...`- )}`,+ commandHintStep(+ 'Link the toolkit first',+ surface === 'dev' ? 'manage.connectedAccounts.link' : 'root.link',+ surface === 'dev' ? { toolkit, userId: '<user-id>' } : { toolkit }+ ),+ executeStep.replace('Retry:', 'Then retry:'),].join('\n');};+const isNoActiveConnectionError = (details: { code?: number; slug?: string } | undefined) =>+ details?.code === 4302 || details?.slug === 'ToolRouterV2_NoActiveConnection';++const noActiveConnectionMessage = (toolSlug: string) => {+ const toolkit = toolkitFromToolSlug(toolSlug);+ if (!toolkit) {+ return 'No active connection found for this tool call. Link the required toolkit/app, then retry.';+ }+ return `No active connection found for toolkit "${toolkit}". Run \`composio link ${toolkit}\`, then retry.`;+};+const ciRedactReplacer = (_key: string, value: unknown): unknown => {if (typeof value !== 'string') return value;if (_key === 'logId') return redact({ value, prefix: 'log_' });@@ -151,6 +205,83 @@ const redactRequestId = (value: object): object => {};};+const EXECUTE_INLINE_OUTPUT_TOKEN_THRESHOLD = 10_000;+let executeOutputEncoder: ReturnType<typeof encodingForModel> | undefined;++const getExecuteOutputEncoder = () => {+ if (!executeOutputEncoder) {+ executeOutputEncoder = encodingForModel('gpt-4o');+ }+ return executeOutputEncoder;+};++type StoredExecuteOutputSummary = {+ readonly successful: true;+ readonly error: null;+ readonly logId: string;+ readonly storedInFile: true;+ readonly tokenCount: number;+ readonly outputFilePath: string;+};++const serializeExecuteOutput = (result: unknown): string =>+ JSON.stringify(result, ciRedactReplacer, 2);++const randomToken = (length = 16) => crypto.randomUUID().replace(/-/g, '').slice(0, length);++const persistLargeExecuteOutput = (json: string): StoredExecuteOutputSummary => {+ const directoryPath = path.join('/tmp/composio', randomToken());+ const outputHash = randomToken();+ const outputFilePath = path.join(directoryPath, `output-${outputHash}.json`);+ fs.mkdirSync(directoryPath, { recursive: true });+ fs.writeFileSync(outputFilePath, json, 'utf8');++ return {+ successful: true,+ error: null,+ logId: '',+ storedInFile: true,+ tokenCount: getExecuteOutputEncoder().encode(json).length,+ outputFilePath,+ };+};++const perfDebugEpoch = Date.now();+const perfDebugLog = (label: string, details: Record<string, unknown> = {}) => {+ if (!isPerfDebugEnabled()) return;+ console.error(+ `[perf] ${JSON.stringify({+ phase: 'event',+ label,+ elapsedMs: Date.now() - perfDebugEpoch,+ ...details,+ })}`+ );+};+const toolDebugLog = (label: string, details: Record<string, unknown> = {}) => {+ if (!isToolDebugEnabled()) return;+ console.error(`[tool-debug] ${JSON.stringify({ label, ...details })}`);+};++const prepareExecuteOutput = (result: ToolExecuteResponse) => {+ const json = serializeExecuteOutput(result);+ const tokenCount = getExecuteOutputEncoder().encode(json).length;+ if (tokenCount <= EXECUTE_INLINE_OUTPUT_TOKEN_THRESHOLD) {+ return {+ kind: 'inline' as const,+ json,+ };+ }++ return {+ kind: 'file' as const,+ summary: {+ ...persistLargeExecuteOutput(json),+ logId: result.logId,+ } satisfies StoredExecuteOutputSummary,+ };+};+const normalizeError = (error: unknown): unknown => {let current: unknown = error;const seen = new Set<unknown>();@@ -191,7 +322,10 @@ export const showToolsExecuteInputHelp = (toolSlug: string) =>'services/HttpServerError',handleHttpServerError(ui, {fallbackMessage: `Tool "${toolSlug}" not found.`,- hint: 'Browse available tools:\n> composio manage tools list',+ hint: [+ commandHintStep('Browse available toolkits', 'manage.toolkits.list'),+ commandHintStep('Then list tools', 'root.tools.list'),+ ].join('\n'),fallbackValue: Option.none(),searchForSuggestions: () =>repo.searchTools({ search: toolSlug, limit: 3 }).pipe(@@ -219,10 +353,21 @@ export const showToolsExecuteInputHelp = (toolSlug: string) =>const handleExecutionError = (ui: TerminalUI,error: unknown,- context: { toolSlug: string; surface: 'root' | 'manage' }+ context: { toolSlug: string; surface: 'root' | 'manage' | 'dev' }) =>Effect.gen(function* () {const normalized = normalizeError(error);+ if (normalized instanceof ToolInputValidationError) {+ yield* ui.log.error(`Input validation failed for ${context.toolSlug}`);+ yield* ui.note(+ [`Schema: ${normalized.schemaPath}`, ...normalized.issues.map(issue => `- ${issue}`)].join(+ '\n'+ ),+ 'Tool schema validation'+ );+ return { error: normalized.message, slug: context.toolSlug };+ }+const connAccountDetails =normalized instanceof ActionExecuteConnectedAccountNotFoundError? normalized.details@@ -233,8 +378,20 @@ const handleExecutionError = (extractApiErrorDetails(normalized) ??extractApiErrorDetails(connAccountDetails);const slugValue = apiDetails?.slug ?? extractSlug(error) ?? extractSlug(connAccountDetails);+ const noActiveConnection =+ normalized instanceof ActionExecuteConnectedAccountNotFoundError ||+ isNoActiveConnectionError(apiDetails);const message = extractMessage(apiDetails) ?? extractMessage(normalized) ?? 'Unknown error';+ if (noActiveConnection) {+ const rewrittenMessage = noActiveConnectionMessage(context.toolSlug);+ yield* ui.log.error(rewrittenMessage);+ if (toolkitFromToolSlug(context.toolSlug)) {+ yield* ui.note(connectionTips(context.toolSlug, context.surface), 'Tips');+ }+ return { error: rewrittenMessage, slug: slugValue ?? context.toolSlug };+ }+yield* ui.log.error(message);const detailsObject =@@ -260,81 +417,488 @@ class ToolExecutionError {constructor(readonly message: string) {}}-const runToolsExecute = (params: {+type CachedValidationDecision =+ | { readonly status: 'valid' | 'stale' }+ | { readonly status: 'fail'; readonly error: unknown };++type ValidationState = {+ readonly cacheHit: boolean;+ readonly validationGuard: Effect.Effect<never, unknown>;+ readonly awaitCachedValidationDecision: Effect.Effect<CachedValidationDecision, never> | null;+};++type CachedDefinition = {+ readonly schemaPath: string;+ readonly schema: Record<string, unknown>;+ readonly version: string | null;+} | null;++const validationGuardFromFiber = (validationFiber: Fiber.RuntimeFiber<unknown, unknown>) =>+ Fiber.await(validationFiber).pipe(+ Effect.flatMap(+ Exit.match({+ onFailure: cause => {+ const defect = Cause.failureOption(cause);+ if (Option.isSome(defect) && defect.value instanceof ToolInputValidationError) {+ return Effect.failCause(cause);+ }+ return Effect.never;+ },+ onSuccess: () => Effect.never,+ })+ )+ );++const spawnBackgroundValidationGuard = (params: {+ readonly slug: string;+ readonly args: Record<string, unknown>;+ readonly resolvedProject: {+ readonly orgId: string;+ readonly projectId: string;+ };+}) =>+ Effect.gen(function* () {+ perfDebugLog('execute.validation.background_spawn', { slug: params.slug });+ const validationFiber = yield* validateToolInputArguments(params.slug, params.args, {+ orgId: params.resolvedProject.orgId,+ projectId: params.resolvedProject.projectId,+ }).pipe(Effect.forkDaemon);+ perfDebugLog('execute.validation.background_spawned', { slug: params.slug });+ return validationGuardFromFiber(validationFiber);+ });++const initializeValidationState = (params: {+ readonly slug: string;+ readonly args: Record<string, unknown>;+ readonly cachedDefinition: CachedDefinition;+ readonly resolvedProject: {+ readonly orgId: string;+ readonly projectId: string;+ };+}) =>+ Effect.gen(function* () {+ if (!params.cachedDefinition) {+ perfDebugLog('execute.validation.cache_miss', { slug: params.slug });+ return {+ cacheHit: false,+ validationGuard: Effect.never,+ awaitCachedValidationDecision: null,+ } satisfies ValidationState;+ }+ const cachedDefinition = params.cachedDefinition;++ perfDebugLog('execute.validation.cache_hit', {+ slug: params.slug,+ cachedVersion: cachedDefinition.version,+ });+ const versionCheckFiber = yield* refreshToolInputDefinitionIfVersionChanged(+ params.slug,+ cachedDefinition.version,+ {+ orgId: params.resolvedProject.orgId,+ projectId: params.resolvedProject.projectId,+ }+ ).pipe(+ Effect.tap(result =>+ Effect.sync(() =>+ perfDebugLog('execute.validation.version_check_done', {+ slug: params.slug,+ cachedVersion: cachedDefinition.version,+ latestVersion: result.latestVersion,+ isStale: result.isStale,+ })+ )+ ),+ Effect.either,+ Effect.forkDaemon+ );+ const cachedValidationDecisionFiber = yield* Effect.gen(function* () {+ perfDebugLog('execute.validation.cached_start', { slug: params.slug });+ const result = yield* validateToolInputArgumentsWithDefinition(+ params.slug,+ params.args,+ cachedDefinition+ ).pipe(Effect.either);+ perfDebugLog('execute.validation.cached_end', {+ slug: params.slug,+ successful: Either.isRight(result),+ });+ if (Either.isRight(result)) {+ return { status: 'valid' as const };+ }++ const freshnessEither = yield* Fiber.join(versionCheckFiber);+ const isStale = Either.isRight(freshnessEither) && freshnessEither.right.isStale;+ perfDebugLog('execute.validation.cached_failed', {+ slug: params.slug,+ cacheStillCurrent: !isStale,+ });+ return isStale+ ? { status: 'stale' as const }+ : { status: 'fail' as const, error: result.left };+ }).pipe(Effect.forkDaemon);+ const awaitCachedValidationDecision = Fiber.join(+ cachedValidationDecisionFiber+ ) as Effect.Effect<CachedValidationDecision, never>;++ return {+ cacheHit: true,+ awaitCachedValidationDecision,+ validationGuard: awaitCachedValidationDecision.pipe(+ Effect.flatMap(decision => {+ if (decision.status === 'fail') {+ return Effect.fail(decision.error);+ }++ return Effect.never;+ })+ ),+ } satisfies ValidationState;+ });++type DryRunSummary = {+ readonly successful: true;+ readonly dryRun: true;+ readonly slug: string;+ readonly arguments: Record<string, unknown>;+ readonly userId: string;+ readonly schemaPath?: string;+ readonly schemaVersion?: string | null;+};++type RunToolsExecuteParams = {slug: string;data: Option.Option<string>;userId: Option.Option<string>;projectName: Option.Option<string>;- rootOnly: boolean;-}) =>+ surface: 'root' | 'manage' | 'dev';+ projectMode: 'consumer' | 'developer';+ getSchema: boolean;+ dryRun: boolean;+ skipConnectionCheck: boolean;+ skipToolParamsCheck: boolean;+ noVerify: boolean;+};++type ResolvedExecuteContext = {+ readonly ui: TerminalUI;+ readonly executor: ToolsExecutor;+ readonly resolvedProject: {+ readonly orgId: string;+ readonly projectId: string;+ readonly projectType: 'CONSUMER' | 'DEVELOPER';+ readonly consumerUserId?: string;+ };+ readonly args: Record<string, unknown>;+ readonly resolvedUserId: string;+ readonly executeParams: ToolExecuteParams;+};++const emitCachedSchema = (+ ui: TerminalUI,+ slug: string,+ definition: {+ readonly version: string | null;+ readonly schemaPath: string;+ readonly schema: Record<string, unknown>;+ }+) =>Effect.gen(function* () {- if (!(yield* requireAuth)) return;+ yield* ui.log.message(+ `Schema saved, inspect keys like: jq '{required: (.inputSchema.required // []), keys: (.inputSchema.properties | keys)}' ${definition.schemaPath}`+ );+ yield* ui.output(+ JSON.stringify(+ {+ slug,+ version: definition.version,+ schemaPath: definition.schemaPath,+ inputSchema: definition.schema,+ },+ null,+ 2+ )+ );+ });+const resolveExecuteContext = (params: RunToolsExecuteParams) =>+ Effect.gen(function* () {+ const resolvedProject = yield* resolveCommandProject({+ mode: params.projectMode,+ projectName:+ params.surface === 'root' ? undefined : Option.getOrUndefined(params.projectName),+ }).pipe(Effect.mapError(formatResolveCommandProjectError));const ui = yield* TerminalUI;const executor = yield* ToolsExecutor;const clientSingleton = yield* ComposioClientSingleton;const userContext = yield* ComposioUserContext;+ const projectContext = yield* ProjectContext;const input = yield* resolveInput(params.data);const args = yield* parseArguments(input);- const resolvedProject = yield* resolveCommandProject({- mode: 'consumer',- projectName: params.rootOnly ? undefined : Option.getOrUndefined(params.projectName),- }).pipe(Effect.mapError(formatResolveCommandProjectError));+ const localProjectContext = yield* projectContext.resolve.pipe(+ Effect.catchAll(() => Effect.succeed(Option.none()))+ );+ const localTestUserId = Option.flatMap(localProjectContext, keys => keys.testUserId);const resolvedUserId =resolvedProject.projectType === 'CONSUMER'? Option.fromNullable(resolvedProject.consumerUserId): Option.match(params.userId, {onSome: value => Option.some(value),- onNone: () => userContext.data.testUserId,+ onNone: () => Option.orElse(localTestUserId, () => userContext.data.testUserId),});+if (Option.isNone(resolvedUserId)) {return yield* Effect.fail(new Error(- 'Missing user id. Provide --user-id or run composio login to set global test_user_id.'+ params.projectMode === 'developer'+ ? 'Missing user id. Provide --user-id or run `composio dev init` to set a playground test user id.'+ : 'Missing user id. Provide --user-id or run composio login to set global test_user_id.'));}+const client = yield* clientSingleton.getFor({orgId: resolvedProject.orgId,projectId: resolvedProject.projectId,});- const executeParams: ToolExecuteParams = {- userId: resolvedUserId.value,- arguments: args,- client,- };+ return {+ ui,+ executor,+ resolvedProject,+ args,+ resolvedUserId: resolvedUserId.value,+ executeParams: {+ userId: resolvedUserId.value,+ arguments: args,+ client,+ },+ } satisfies ResolvedExecuteContext;+ });- yield* ui.useMakeSpinner(`Executing tool "${params.slug}"...`, spinner =>+const runConnectedToolkitFailFast = (params: {+ readonly slug: string;+ readonly surface: 'root' | 'manage' | 'dev';+ readonly ui: TerminalUI;+ readonly resolvedProject: ResolvedExecuteContext['resolvedProject'];+ readonly resolvedUserId: string;+ readonly skipConnectionCheck: boolean;+ readonly noVerify: boolean;+}) =>+ Effect.gen(function* () {+ if (params.skipConnectionCheck || params.noVerify) {+ perfDebugLog('execute.connected_toolkits.skipped', {+ slug: params.slug,+ reason: params.noVerify ? 'no-verify' : 'skip-connection-check',+ });+ return;+ }+ if (params.resolvedProject.projectType !== 'CONSUMER') return;++ perfDebugLog('execute.connected_toolkits.refresh_start', {+ slug: params.slug,+ orgId: params.resolvedProject.orgId,+ consumerUserId: params.resolvedUserId,+ });+ yield* refreshConsumerConnectedToolkitsCache({+ orgId: params.resolvedProject.orgId,+ consumerUserId: params.resolvedUserId,+ }).pipe(+ Effect.tap(() =>+ Effect.sync(() =>+ perfDebugLog('execute.connected_toolkits.refresh_end', {+ slug: params.slug,+ orgId: params.resolvedProject.orgId,+ consumerUserId: params.resolvedUserId,+ successful: true,+ })+ )+ ),+ Effect.catchAll(() =>+ Effect.sync(() =>+ perfDebugLog('execute.connected_toolkits.refresh_end', {+ slug: params.slug,+ orgId: params.resolvedProject.orgId,+ consumerUserId: params.resolvedUserId,+ successful: false,+ })+ )+ ),+ Effect.forkDaemon,+ Effect.asVoid+ );++ const toolkit = toolkitFromToolSlug(params.slug);+ if (!toolkit) return;++ const cachedToolkits = yield* getFreshConsumerConnectedToolkitsFromCache({+ orgId: params.resolvedProject.orgId,+ consumerUserId: params.resolvedUserId,+ });+ perfDebugLog(+ Option.isSome(cachedToolkits)+ ? 'execute.connected_toolkits.cache_hit'+ : 'execute.connected_toolkits.cache_miss',+ {+ slug: params.slug,+ toolkit,+ orgId: params.resolvedProject.orgId,+ consumerUserId: params.resolvedUserId,+ cachedToolkits: Option.isSome(cachedToolkits) ? cachedToolkits.value : undefined,+ }+ );++ if (Option.isSome(cachedToolkits) && !cachedToolkits.value.includes(toolkit)) {+ perfDebugLog('execute.connected_toolkits.fail_fast', {+ slug: params.slug,+ toolkit,+ orgId: params.resolvedProject.orgId,+ consumerUserId: params.resolvedUserId,+ });+ 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.`;+ yield* params.ui.log.error(message);+ yield* params.ui.note(connectionTips(params.slug, params.surface), 'Tips');+ yield* params.ui.output(+ JSON.stringify(+ {+ successful: false,+ error: message,+ slug: params.slug,+ },+ ciRedactReplacer,+ 2+ )+ );+ return yield* Effect.fail(new ToolExecutionError(message));+ }+ });++const runExecuteWithSpinner = (params: {+ readonly slug: string;+ readonly surface: 'root' | 'manage' | 'dev';+ readonly dryRun: boolean;+ readonly ui: TerminalUI;+ readonly executor: ToolsExecutor;+ readonly resolvedProject: ResolvedExecuteContext['resolvedProject'];+ readonly args: Record<string, unknown>;+ readonly resolvedUserId: string;+ readonly executeParams: ToolExecuteParams;+ readonly skipToolParamsCheck: boolean;+ readonly noVerify: boolean;+}) =>+ Effect.gen(function* () {+ const verificationDisabled = params.noVerify || params.skipToolParamsCheck;+ const cachedDefinition = verificationDisabled+ ? null+ : yield* getCachedToolInputDefinition(params.slug);+ const validationState = verificationDisabled+ ? ({+ cacheHit: false,+ validationGuard: Effect.never,+ awaitCachedValidationDecision: null,+ } satisfies ValidationState)+ : yield* initializeValidationState({+ slug: params.slug,+ args: params.args,+ cachedDefinition,+ resolvedProject: params.resolvedProject,+ });++ yield* params.ui.useMakeSpinner(`Executing tool "${params.slug}"...`, spinner =>Effect.gen(function* () {- const resultEither = yield* executor- .execute(params.slug, executeParams)+ let validationGuard = validationState.validationGuard;+ if (!verificationDisabled && !validationState.cacheHit) {+ validationGuard = yield* spawnBackgroundValidationGuard({+ slug: params.slug,+ args: params.args,+ resolvedProject: params.resolvedProject,+ });+ }++ if (params.dryRun) {+ const definition = verificationDisabled+ ? null+ : (cachedDefinition ??+ (yield* getOrFetchToolInputDefinition(params.slug, {+ orgId: params.resolvedProject.orgId,+ projectId: params.resolvedProject.projectId,+ })));+ if (definition) {+ yield* validateToolInputArgumentsWithDefinition(params.slug, params.args, definition);+ }+ const summary: DryRunSummary = {+ successful: true,+ dryRun: true,+ slug: params.slug,+ arguments: params.args,+ userId: params.resolvedUserId,+ schemaPath: definition?.schemaPath,+ schemaVersion: definition?.version,+ };+ yield* spinner.stop('Dry run successful');+ yield* params.ui.log.message(+ verificationDisabled+ ? 'No tool was executed. Local validation was skipped.'+ : 'No tool was executed. Arguments were validated locally only.'+ );+ yield* params.ui.output(JSON.stringify(summary, ciRedactReplacer, 2));+ return;+ }++ perfDebugLog('execute.tool_call.start', { slug: params.slug });+ const resultEither = yield* params.executor+ .execute(params.slug, params.executeParams)+ .pipe(Effect.raceFirst(validationGuard)).pipe(Effect.either);+ toolDebugLog('execute_result', {+ slug: params.slug,+ result: Either.isRight(resultEither) ? resultEither.right : resultEither.left,+ });+ perfDebugLog('execute.tool_call.end', {+ slug: params.slug,+ successful: Either.isRight(resultEither),+ });if (Either.isLeft(resultEither)) {+ yield* invalidateToolInputDefinition(params.slug).pipe(+ Effect.catchAll(() => Effect.void)+ );yield* spinner.error();- const summary = yield* handleExecutionError(ui, resultEither.left, {+ const summary = yield* handleExecutionError(params.ui, resultEither.left, {toolSlug: params.slug,- surface: params.rootOnly ? 'root' : 'manage',+ surface: params.surface,});- yield* ui.output(JSON.stringify({ successful: false, ...summary }, ciRedactReplacer, 2));+ yield* params.ui.output(+ JSON.stringify({ successful: false, ...summary }, ciRedactReplacer, 2)+ );return yield* Effect.fail(new ToolExecutionError(summary.error));}const result = resultEither.right;+ if (validationState.awaitCachedValidationDecision) {+ const decision = yield* validationState.awaitCachedValidationDecision;+ if (decision.status === 'fail') {+ perfDebugLog('execute.validation.post_success_failure_ignored', {+ slug: params.slug,+ });+ }+ }if (!result.successful) {+ yield* invalidateToolInputDefinition(params.slug).pipe(+ Effect.catchAll(() => Effect.void)+ );const logId = result.logId? ` (logId: ${redact({ value: result.logId, prefix: 'log_' })})`: '';yield* spinner.error(`Execution failed${logId}`);- const summary = yield* handleExecutionError(ui, result.error ?? result, {+ const summary = yield* handleExecutionError(params.ui, result.error ?? result, {toolSlug: params.slug,- surface: params.rootOnly ? 'root' : 'manage',+ surface: params.surface,});- yield* ui.output(JSON.stringify(result, ciRedactReplacer, 2));+ yield* params.ui.output(JSON.stringify(result, ciRedactReplacer, 2));return yield* Effect.fail(new ToolExecutionError(summary.error));}@@ -342,45 +906,223 @@ const runToolsExecute = (params: {? ` (logId: ${redact({ value: result.logId, prefix: 'log_' })})`: '';yield* spinner.stop(`Execution successful${logId}`);- yield* ui.log.message(`Response\n${JSON.stringify(result, ciRedactReplacer, 2)}`);- yield* ui.output(JSON.stringify(result, ciRedactReplacer, 2));+ const output = prepareExecuteOutput(result);+ if (output.kind === 'file') {+ yield* params.ui.log.message(+ `Response stored in ${output.summary.outputFilePath} (${output.summary.tokenCount} tokens)`+ );+ yield* params.ui.output(JSON.stringify(output.summary, ciRedactReplacer, 2));+ return;+ }++ yield* params.ui.log.message(`Response\n${output.json}`);+ yield* params.ui.output(output.json);}));});+const runToolsExecute = (params: RunToolsExecuteParams) =>+ Effect.gen(function* () {+ if (!(yield* requireAuth)) return;++ const context = yield* resolveExecuteContext(params);+ if (params.getSchema) {+ const definition = yield* getOrFetchToolInputDefinition(params.slug, {+ orgId: context.resolvedProject.orgId,+ projectId: context.resolvedProject.projectId,+ });+ yield* emitCachedSchema(context.ui, params.slug, definition);+ return;+ }++ yield* runConnectedToolkitFailFast({+ slug: params.slug,+ surface: params.surface,+ ui: context.ui,+ resolvedProject: context.resolvedProject,+ resolvedUserId: context.resolvedUserId,+ skipConnectionCheck: params.skipConnectionCheck,+ noVerify: params.noVerify,+ });+ toolDebugLog('execute_params', {+ slug: params.slug,+ userId: context.resolvedUserId,+ arguments: context.args,+ projectId: context.resolvedProject.projectId,+ orgId: context.resolvedProject.orgId,+ });+ perfDebugLog('execute.prepare', {+ slug: params.slug,+ surface: params.surface,+ projectMode: params.projectMode,+ });+ yield* runExecuteWithSpinner({+ slug: params.slug,+ surface: params.surface,+ dryRun: params.dryRun,+ ui: context.ui,+ executor: context.executor,+ resolvedProject: context.resolvedProject,+ args: context.args,+ resolvedUserId: context.resolvedUserId,+ executeParams: context.executeParams,+ skipToolParamsCheck: params.skipToolParamsCheck,+ noVerify: params.noVerify,+ });+ });+export const toolsCmd$Execute = Command.make('execute',- { slug, data, userId, projectName },- ({ slug, data, userId, projectName }) =>- runToolsExecute({ slug, data, userId, projectName, rootOnly: false })+ {+ slug,+ data,+ userId,+ projectName,+ getSchema,+ dryRun,+ skipConnectionCheck,+ skipToolParamsCheck,+ noVerify,+ },+ ({+ slug,+ data,+ userId,+ projectName,+ getSchema,+ dryRun,+ skipConnectionCheck,+ skipToolParamsCheck,+ noVerify,+ }) =>+ runToolsExecute({+ slug,+ data,+ userId,+ projectName,+ surface: 'manage',+ projectMode: 'consumer',+ getSchema,+ dryRun,+ skipConnectionCheck,+ skipToolParamsCheck,+ noVerify,+ })).pipe(Command.withDescription([- 'Execute a tool by slug with JSON arguments.',+ 'Execute a tool by slug with JSON arguments, or preview it locally with --dry-run.',+ 'Arguments are validated against cached tool schemas in `~/.composio/tool_definitions/` when available.',+ 'Use `--get-schema` to fetch the latest raw input schema into the cache and print it without executing the tool.',+ 'Use `composio tools info <slug>` for the same schema plus a short human summary and jq hints.',+ '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.',+ '',+ 'Examples:',+ ' composio execute GMAIL_SEND_EMAIL -d \'{ recipient_email: "[email protected]", body: "Hello" }\'',+ ' composio execute GMAIL_SEND_EMAIL --skip-connection-check -d \'{ recipient_email: "[email protected]", body: "Hello" }\'',+ ' composio execute GMAIL_SEND_EMAIL --skip-tool-params-check -d \'{ recipient_email: "[email protected]", body: "Hello" }\'',+ ' composio execute GMAIL_SEND_EMAIL --no-verify -d \'{ recipient_email: "[email protected]", body: "Hello" }\'',+ ' composio execute GMAIL_SEND_EMAIL --dry-run -d \'{ recipient_email: "[email protected]", body: "Hello" }\'',+ ' composio execute GMAIL_SEND_EMAIL --get-schema','','Related:',+ ' composio run \'const first = await execute("TOOL_SLUG", { ... }); const second = await execute("OTHER_TOOL", { ... }); console.log({ first, second })\'',' composio search "<query>"',' composio link <toolkit>',].join('\n')));-export const rootToolsCmd$Execute = Command.make('execute', { slug, data }, ({ slug, data }) =>- runToolsExecute({- slug,- data,- userId: Option.none(),- projectName: Option.none(),- rootOnly: true,- })+export const rootToolsCmd$Execute = Command.make(+ 'execute',+ { slug, data, getSchema, dryRun, skipConnectionCheck, skipToolParamsCheck, noVerify },+ ({ slug, data, getSchema, dryRun, skipConnectionCheck, skipToolParamsCheck, noVerify }) =>+ runToolsExecute({+ slug,+ data,+ userId: Option.none(),+ projectName: Option.none(),+ surface: 'root',+ projectMode: 'consumer',+ getSchema,+ dryRun,+ skipConnectionCheck,+ skipToolParamsCheck,+ noVerify,+ })).pipe(Command.withDescription([- 'Execute a tool by slug with JSON arguments.',+ 'Execute a tool by slug with JSON arguments, or preview it locally with --dry-run.',+ 'Arguments are validated against cached tool schemas in `~/.composio/tool_definitions/` when available.',+ 'Use `--get-schema` to fetch the latest raw input schema into the cache and print it without executing the tool.',+ 'Use `composio tools info <slug>` for the same schema plus a short human summary and jq hints.',+ '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.',+ '',+ 'Examples:',+ ' composio execute GMAIL_SEND_EMAIL -d \'{ recipient_email: "[email protected]", body: "Hello" }\'',+ ' composio execute GMAIL_SEND_EMAIL --skip-connection-check -d \'{ recipient_email: "[email protected]", body: "Hello" }\'',+ ' composio execute GMAIL_SEND_EMAIL --skip-tool-params-check -d \'{ recipient_email: "[email protected]", body: "Hello" }\'',+ ' composio execute GMAIL_SEND_EMAIL --no-verify -d \'{ recipient_email: "[email protected]", body: "Hello" }\'',+ ' composio execute GMAIL_SEND_EMAIL --dry-run -d \'{ recipient_email: "[email protected]", body: "Hello" }\'',+ ' composio execute GMAIL_SEND_EMAIL --get-schema','','Related:',+ ' composio run \'const first = await execute("TOOL_SLUG", { ... }); const second = await execute("OTHER_TOOL", { ... }); console.log({ first, second })\'',' composio search "<query>"',' composio link <toolkit>',].join('\n')));++export const devToolsCmd$Execute = Command.make(+ 'execute',+ {+ slug,+ data,+ userId,+ projectName,+ getSchema,+ dryRun,+ skipConnectionCheck,+ skipToolParamsCheck,+ noVerify,+ },+ ({+ slug,+ data,+ userId,+ projectName,+ getSchema,+ dryRun,+ skipConnectionCheck,+ skipToolParamsCheck,+ noVerify,+ }) =>+ runToolsExecute({+ slug,+ data,+ userId,+ projectName,+ surface: 'dev',+ projectMode: 'developer',+ getSchema,+ dryRun,+ skipConnectionCheck,+ skipToolParamsCheck,+ noVerify,+ })+).pipe(+ Command.withDescription(+ [+ 'Execute a tool with your playground test user id against your developer project auth configs.',+ 'Uses --user-id when provided, otherwise falls back to your local or global playground test user id.',+ 'Arguments are validated against cached tool schemas in `~/.composio/tool_definitions/` when available.',+ '',+ 'Examples:',+ ' composio dev execute GMAIL_SEND_EMAIL -d \'{ recipient_email: "[email protected]", body: "Hello" }\'',+ ' composio dev execute GMAIL_SEND_EMAIL --dry-run -d \'{ recipient_email: "[email protected]", body: "Hello" }\'',+ ' composio dev execute GMAIL_SEND_EMAIL --get-schema',+ ].join('\n')+ )+);diff --git a/ts/packages/cli/src/commands/tools/commands/tools.info.cmd.ts b/ts/packages/cli/src/commands/tools/commands/tools.info.cmd.tsindex 727d467d9..38ed28106 100644--- a/ts/packages/cli/src/commands/tools/commands/tools.info.cmd.ts+++ b/ts/packages/cli/src/commands/tools/commands/tools.info.cmd.ts@@ -4,7 +4,9 @@ import { ComposioToolkitsRepository } from 'src/services/composio-clients';import { TerminalUI } from 'src/services/terminal-ui';import { requireAuth } from 'src/effects/require-auth';import { handleHttpServerError } from 'src/effects/handle-http-error';-import { formatToolInfo } from '../format';+import { getOrFetchToolInputDefinition } from 'src/services/tool-input-validation';+import { bold } from 'src/ui/colors';+import { commandHintExample, commandHintStep } from 'src/services/command-hints';const slug = Args.text({ name: 'slug' }).pipe(Args.withDescription('Tool slug (e.g. "GMAIL_SEND_EMAIL")'),@@ -16,7 +18,7 @@ const slug = Args.text({ name: 'slug' }).pipe(** @example* ```bash- * composio manage tools info "GMAIL_SEND_EMAIL"+ * composio tools info "GMAIL_SEND_EMAIL"* ```*/export const toolsCmd$Info = Command.make('info', { slug }, ({ slug }) =>@@ -29,9 +31,7 @@ export const toolsCmd$Info = Command.make('info', { slug }, ({ slug }) =>// Missing slug guardif (Option.isNone(slug)) {yield* ui.log.warn('Missing required argument: <slug>');- yield* ui.log.step(- 'Try specifying a tool slug, e.g.:\n> composio manage tools info "GMAIL_SEND_EMAIL"'- );+ yield* ui.log.step('Try specifying a tool slug, e.g.:\n> composio tools info "GMAIL_SEND_EMAIL"');return;}@@ -45,14 +45,17 @@ export const toolsCmd$Info = Command.make('info', { slug }, ({ slug }) =>'services/HttpServerError',handleHttpServerError(ui, {fallbackMessage: `Tool "${slugValue}" not found.`,- hint: 'Browse available tools:\n> composio manage tools list',+ hint: [+ commandHintStep('Browse available toolkits', 'manage.toolkits.list'),+ commandHintStep('Then list tools', 'root.tools.list'),+ ].join('\n'),fallbackValue: Option.none(),searchForSuggestions: () =>repo.searchTools({ search: slugValue, limit: 3 }).pipe(Effect.map(r =>r.items.map(s => ({label: `${s.slug} — ${s.description}`,- command: `> composio manage tools info "${s.slug}"`,+ command: `> composio tools info "${s.slug}"`,})))),@@ -65,17 +68,43 @@ export const toolsCmd$Info = Command.make('info', { slug }, ({ slug }) =>}const tool = toolOpt.value;+ const definition = yield* getOrFetchToolInputDefinition(slugValue);- yield* ui.note(formatToolInfo(tool), `Tool: ${tool.name}`);+ const summary = [+ `${bold('Slug:')} ${tool.slug}`,+ `${bold('Name:')} ${tool.name}`,+ `${bold('Toolkit:')} ${tool.toolkit.slug}`,+ `${bold('Version:')} ${definition.version ?? '-'}`,+ `${bold('Description:')} ${tool.description}`,+ `${bold('Schema Cache:')} ${definition.schemaPath}`,+ ].join('\n');- // Next step hint- const toolkitSlug = tool.toolkit.slug;- if (toolkitSlug) {- yield* ui.log.step(- `To list more tools in this toolkit:\n> composio manage tools list --toolkits "${toolkitSlug}"`- );- }-- yield* ui.output(JSON.stringify(tool, null, 2));+ yield* ui.note(summary, `Tool: ${tool.name}`);+ yield* ui.log.step(+ `Inspect schema with jq:\n> jq '{required: (.inputSchema.required // []), keys: (.inputSchema.properties | keys)}' "${definition.schemaPath}"`+ );+ yield* ui.log.step(+ `Then execute it:\n> ${commandHintExample('root.execute', {+ slug: tool.slug,+ })} --dry-run`+ );+ yield* ui.output(+ JSON.stringify(+ {+ slug: tool.slug,+ name: tool.name,+ description: tool.description,+ toolkit: tool.toolkit.slug,+ version: definition.version,+ schemaPath: definition.schemaPath,+ },+ null,+ 2+ )+ );})-).pipe(Command.withDescription('View details of a specific tool.'));+).pipe(+ Command.withDescription(+ 'View a brief summary of a tool and cache the same raw schema used by `composio execute --get-schema`.'+ )+);diff --git a/ts/packages/cli/src/commands/tools/commands/tools.list.cmd.ts b/ts/packages/cli/src/commands/tools/commands/tools.list.cmd.tsindex 04ca79ae1..e15a6405c 100644--- a/ts/packages/cli/src/commands/tools/commands/tools.list.cmd.ts+++ b/ts/packages/cli/src/commands/tools/commands/tools.list.cmd.ts@@ -1,4 +1,4 @@-import { Command, Options } from '@effect/cli';+import { Args, Command, Options } from '@effect/cli';import { Effect, Option } from 'effect';import { ComposioToolkitsRepository } from 'src/services/composio-clients';import { TerminalUI } from 'src/services/terminal-ui';@@ -6,15 +6,12 @@ import { requireAuth } from 'src/effects/require-auth';import { clampLimit } from 'src/ui/clamp-limit';import { formatToolsTable, formatToolsJson } from '../format';-const query = Options.text('query').pipe(- Options.withDescription('Text search by name, slug, or description'),- Options.optional+const toolkit = Args.text({ name: 'toolkit' }).pipe(+ Args.withDescription('Toolkit slug to list tools for (e.g. "gmail")'));-const toolkits = Options.text('toolkits').pipe(- Options.withDescription(- 'Filter by toolkit slugs, comma-separated (e.g. "gmail" or "gmail,slack")'- ),+const query = Options.text('query').pipe(+ Options.withDescription('Text search by name, slug, or description'),Options.optional);@@ -29,19 +26,19 @@ const limit = Options.integer('limit').pipe();/**- * List available tools with optional filters.+ * List available tools for a toolkit with optional filters.** @example* ```bash- * composio manage tools list --toolkits "gmail"- * composio manage tools list --query "send email" --toolkits "gmail"- * composio manage tools list --tags "important" --limit 10+ * composio tools list gmail+ * composio tools list gmail --query "send email"+ * composio tools list gmail --tags "important" --limit 10* ```*/export const toolsCmd$List = Command.make('list',- { query, toolkits, tags, limit },- ({ query, toolkits, tags, limit }) =>+ { toolkit, query, tags, limit },+ ({ toolkit, query, tags, limit }) =>Effect.gen(function* () {if (!(yield* requireAuth)) return;@@ -54,17 +51,16 @@ export const toolsCmd$List = Command.make('Fetching tools...',repo.searchTools({search: Option.getOrUndefined(query),- toolkit_slug: Option.getOrUndefined(toolkits),+ toolkit_slug: toolkit,tags: Option.getOrUndefined(tags),limit: clampedLimit,}));if (result.items.length === 0) {- const hint = Option.isSome(toolkits)- ? `No tools found in toolkit "${toolkits.value}". Verify the toolkit slug with:\n> composio manage toolkits list`- : 'No tools found. Try broadening your search.';- yield* ui.log.warn(hint);+ yield* ui.log.warn(+ `No tools found in toolkit "${toolkit}". Verify the toolkit slug with:\n> composio manage toolkits list`+ );return;}@@ -80,11 +76,9 @@ export const toolsCmd$List = Command.make(// Next step hintconst firstSlug = result.items[0]?.slug;if (firstSlug) {- yield* ui.log.step(- `To view details of a tool:\n> composio manage tools info "${firstSlug}"`- );+ yield* ui.log.step(`To inspect a tool:\n> composio tools info "${firstSlug}"`);}yield* ui.output(formatToolsJson(result.items));})-).pipe(Command.withDescription('List available tools.'));+).pipe(Command.withDescription('List available tools for a toolkit.'));diff --git a/ts/packages/cli/src/commands/tools/commands/tools.search.cmd.ts b/ts/packages/cli/src/commands/tools/commands/tools.search.cmd.tsindex 3c78abcce..ad8330f8e 100644--- a/ts/packages/cli/src/commands/tools/commands/tools.search.cmd.ts+++ b/ts/packages/cli/src/commands/tools/commands/tools.search.cmd.ts@@ -13,6 +13,8 @@ import {resolveCommandProject,formatResolveCommandProjectError,} from 'src/services/command-project';+import { commandHintExample, commandHintStep } from 'src/services/command-hints';+import { primeConsumerConnectedToolkitsCacheInBackground } from 'src/services/consumer-short-term-cache';const query = Args.text({ name: 'query' }).pipe(Args.withDescription(@@ -90,6 +92,12 @@ const runToolsSearch = (params: {orgId: resolvedProject.orgId,projectId: resolvedProject.projectId,});+ if (resolvedProject.projectType === 'CONSUMER') {+ yield* primeConsumerConnectedToolkitsCacheInBackground({+ orgId: resolvedProject.orgId,+ consumerUserId: resolvedUserId.value,+ });+ }const { sessionId } = yield* resolveToolRouterSession(client, resolvedUserId.value, {toolkits: toolkitList,});@@ -169,12 +177,22 @@ const runToolsSearch = (params: {if (firstSlug) {const executeHint = params.rootOnly- ? `> composio execute "${firstSlug}" ${firstDataArg}`- : `> composio manage tools execute "${firstSlug}" --user-id "<user-id>" ${firstDataArg}`;+ ? commandHintStep('Execute a tool', 'root.execute', {+ slug: firstSlug,+ data: firstDataArg,+ })+ : commandHintStep('Execute a tool', 'dev.execute', {+ slug: firstSlug,+ userId: '<user-id>',+ data: firstDataArg,+ });const linkHint = params.rootOnly- ? `> composio link <toolkit>`- : `> composio manage connected-accounts link <toolkit> --user-id "<user-id>"`;- yield* ui.log.step(['Hints:', executeHint, linkHint].join('\n'));+ ? commandHintStep('Link an account', 'root.link', { toolkit: '<toolkit>' })+ : commandHintStep('Link an account', 'manage.connectedAccounts.link', {+ toolkit: '<toolkit>',+ userId: '<user-id>',+ });+ yield* ui.log.step([executeHint, linkHint].join('\n'));}if (searchResponse.error) {@@ -186,16 +204,23 @@ const runToolsSearch = (params: {cta.push({action: 'Execute a tool',command: params.rootOnly- ? `composio execute "${firstSlug}" ${firstDataArg}`- : `composio manage tools execute "${firstSlug}" --user-id "<user-id>" ${firstDataArg}`,+ ? commandHintExample('root.execute', { slug: firstSlug, data: firstDataArg })+ : commandHintExample('dev.execute', {+ slug: firstSlug,+ userId: '<user-id>',+ data: firstDataArg,+ }),});}if (firstToolkit) {cta.push({action: 'Connect a user account',command: params.rootOnly- ? `composio link ${String(firstToolkit).toLowerCase()}`- : `composio manage connected-accounts link ${String(firstToolkit).toLowerCase()} --user-id "<user-id>"`,+ ? commandHintExample('root.link', { toolkit: String(firstToolkit).toLowerCase() })+ : commandHintExample('manage.connectedAccounts.link', {+ toolkit: String(firstToolkit).toLowerCase(),+ userId: '<user-id>',+ }),});}@@ -217,6 +242,7 @@ export const toolsCmd$Search = Command.make('Semantically search tools by use case; returns best-fit tools plus recommended usage guidance.','','Related:',+ ' composio run \'const result = await execute("TOOL_SLUG", { ... }); console.log(result)\'',' composio link <toolkit>'," composio execute <slug> -d '{}'",].join('\n')@@ -241,6 +267,7 @@ export const rootToolsCmd$Search = Command.make('Semantically search tools by use case; returns best-fit tools plus recommended usage guidance.','','Related:',+ ' composio run \'const result = await execute("TOOL_SLUG", { ... }); console.log(result)\'',' composio link <toolkit>'," composio execute <slug> -d '{}'",].join('\n')diff --git a/ts/packages/cli/src/commands/tools/tools.cmd.ts b/ts/packages/cli/src/commands/tools/tools.cmd.tsindex 2c8b5e5e8..b7c5f51ac 100644--- a/ts/packages/cli/src/commands/tools/tools.cmd.ts+++ b/ts/packages/cli/src/commands/tools/tools.cmd.ts@@ -1,18 +1,8 @@import { Command } from '@effect/cli';import { toolsCmd$List } from './commands/tools.list.cmd';import { toolsCmd$Info } from './commands/tools.info.cmd';-import { toolsCmd$Search } from './commands/tools.search.cmd';-import { toolsCmd$Execute } from './commands/tools.execute.cmd';-/**- * CLI entry point for tool discovery commands.- *- * @example- * ```bash- * composio manage tools <command>- * ```- */-export const toolsCmd = Command.make('tools').pipe(- Command.withDescription('Discover and inspect Composio tools.'),- Command.withSubcommands([toolsCmd$List, toolsCmd$Info, toolsCmd$Search, toolsCmd$Execute])+export const rootToolsCmd = Command.make('tools').pipe(+ Command.withDescription('Browse and inspect tools before executing them.'),+ Command.withSubcommands([toolsCmd$List, toolsCmd$Info]));diff --git a/ts/packages/cli/src/commands/triggers/commands/triggers.listen.cmd.ts b/ts/packages/cli/src/commands/triggers/commands/triggers.listen.cmd.tsindex b865009c8..6fb0bedd3 100644--- a/ts/packages/cli/src/commands/triggers/commands/triggers.listen.cmd.ts+++ b/ts/packages/cli/src/commands/triggers/commands/triggers.listen.cmd.ts@@ -340,4 +340,8 @@ export const triggersCmd$Listen = Command.make(yield* Effect.raceFirst(listenEffect, Deferred.await(stopWhenDone));yield* ui.outro(`Stopped after receiving ${matchingEvents} matching events.`);})-).pipe(Command.withDescription('Listen to realtime trigger events for your project.'));+).pipe(+ Command.withDescription(+ 'Listen to realtime trigger events for your developer project and optionally forward them into your local dev environment.'+ )+);diff --git a/ts/packages/cli/src/commands/whoami.cmd.ts b/ts/packages/cli/src/commands/whoami.cmd.tsindex 1ce491c16..6ba89ebf8 100644--- a/ts/packages/cli/src/commands/whoami.cmd.ts+++ b/ts/packages/cli/src/commands/whoami.cmd.ts@@ -2,6 +2,7 @@ import { Command } from '@effect/cli';import { Effect, Option } from 'effect';import { ComposioUserContext } from 'src/services/user-context';import { TerminalUI } from 'src/services/terminal-ui';+import { commandHintStep } from 'src/services/command-hints';/*** CLI command to display your account information.@@ -36,8 +37,8 @@ export const whoamiCmd = Command.make('whoami', {}).pipe();yield* ui.log.step([- 'To switch orgs:\n> composio manage orgs switch',- 'To get API keys:\n> composio init (in your project)',+ commandHintStep('To switch orgs', 'manage.orgs.switch'),+ commandHintStep('To set up developer project context', 'dev.init'),].join('\n\n'));yield* ui.output(diff --git a/ts/packages/cli/src/services/command-hints.ts b/ts/packages/cli/src/services/command-hints.tsnew file mode 100644index 000000000..cf1f9f841--- /dev/null+++ b/ts/packages/cli/src/services/command-hints.ts@@ -0,0 +1,118 @@+type HintParams = Readonly<Record<string, string | undefined>>;++const getParam = (params: HintParams | undefined, key: string, fallback: string) =>+ params?.[key]?.trim() ? params[key]! : fallback;++export type CommandHintId =+ | 'root.search'+ | 'root.tools.list'+ | 'root.tools.info'+ | 'root.execute'+ | 'root.execute.getSchema'+ | 'root.link'+ | 'dev.init'+ | 'dev.execute'+ | 'dev.execute.getSchema'+ | 'dev.logs.tools'+ | 'dev.logs.triggers'+ | 'manage.orgs.switch'+ | 'manage.projects.list'+ | 'manage.toolkits.list'+ | 'manage.connectedAccounts.link'+ | 'manage.authConfigs.list';++type CommandHintNode = {+ readonly example: (params?: HintParams) => string;+ readonly links?: ReadonlyArray<CommandHintId>;+};++export const COMMAND_HINTS: Record<CommandHintId, CommandHintNode> = {+ 'root.search': {+ example: params => `composio search "${getParam(params, 'query', '<query>')}"`,+ links: ['root.execute', 'root.link', 'root.tools.list'],+ },+ 'root.tools.list': {+ example: params => `composio tools list "${getParam(params, 'toolkit', '<toolkit>')}"`,+ links: ['root.tools.info', 'root.execute'],+ },+ 'root.tools.info': {+ example: params => `composio tools info "${getParam(params, 'slug', '<slug>')}"`,+ links: ['root.execute.getSchema', 'root.execute'],+ },+ 'root.execute': {+ example: params =>+ `composio execute "${getParam(params, 'slug', '<slug>')}" ${getParam(params, 'data', "-d '{}'")}`.trim(),+ links: ['root.link', 'root.execute.getSchema'],+ },+ 'root.execute.getSchema': {+ example: params => `composio execute "${getParam(params, 'slug', '<slug>')}" --get-schema`,+ links: ['root.execute', 'root.tools.info'],+ },+ 'root.link': {+ example: params => `composio link ${getParam(params, 'toolkit', '<toolkit>')}`,+ links: ['root.execute'],+ },+ 'dev.init': {+ example: () => 'composio dev init',+ links: ['dev.execute', 'dev.logs.tools', 'dev.logs.triggers'],+ },+ 'dev.execute': {+ example: params =>+ `composio dev execute "${getParam(params, 'slug', '<slug>')}" --user-id "${getParam(params, 'userId', '<user-id>')}" ${getParam(params, 'data', "-d '{}'")}`.trim(),+ links: ['manage.connectedAccounts.link', 'dev.init', 'dev.execute.getSchema'],+ },+ 'dev.execute.getSchema': {+ example: params =>+ `composio dev execute "${getParam(params, 'slug', '<slug>')}" --get-schema`,+ links: ['dev.execute'],+ },+ 'dev.logs.tools': {+ example: params =>+ `composio dev logs tools "${getParam(params, 'logId', '<log_id>')}"`,+ },+ 'dev.logs.triggers': {+ example: params =>+ `composio dev logs triggers "${getParam(params, 'logId', '<log_id>')}"`,+ },+ 'manage.orgs.switch': {+ example: () => 'composio manage orgs switch',+ links: ['dev.init', 'manage.projects.list'],+ },+ 'manage.projects.list': {+ example: () => 'composio manage projects list',+ links: ['dev.init'],+ },+ 'manage.toolkits.list': {+ example: () => 'composio manage toolkits list',+ links: ['root.tools.list', 'manage.connectedAccounts.link'],+ },+ 'manage.connectedAccounts.link': {+ example: params =>+ `composio manage connected-accounts link ${getParam(params, 'toolkit', '<toolkit>')} --user-id "${getParam(params, 'userId', '<user-id>')}"`,+ links: ['dev.execute'],+ },+ 'manage.authConfigs.list': {+ example: () => 'composio manage auth-configs list',+ links: ['manage.connectedAccounts.link'],+ },+};++export const commandHintExample = (id: CommandHintId, params?: HintParams): string =>+ COMMAND_HINTS[id].example(params);++export const commandHintStep = (+ label: string,+ id: CommandHintId,+ params?: HintParams+): string => `${label}:\n> ${commandHintExample(id, params)}`;++export const commandHintLinks = (id: CommandHintId): ReadonlyArray<CommandHintId> =>+ COMMAND_HINTS[id].links ?? [];++export const renderCommandHintGraph = () => ({+ nodes: (Object.keys(COMMAND_HINTS) as CommandHintId[]).map(id => ({+ id,+ example: commandHintExample(id),+ links: [...commandHintLinks(id)],+ })),+});diff --git a/ts/packages/cli/src/services/command-project.ts b/ts/packages/cli/src/services/command-project.tsindex 5fdf6b002..4349967bd 100644--- a/ts/packages/cli/src/services/command-project.ts+++ b/ts/packages/cli/src/services/command-project.ts@@ -134,11 +134,13 @@ export const formatResolveCommandProjectError = (error: unknown): Error => {);}if (error instanceof MissingDeveloperProjectError) {- return new Error('No developer project configured for this directory. Run `composio init`.');+ return new Error(+ 'No developer project configured for this directory. Run `composio dev init`.'+ );}if (error instanceof DeveloperProjectNotFoundError) {return new Error(- `Developer project "${error.projectName}" was not found in org "${error.orgId}". Run \`composio init\` or \`composio manage projects list\`.`+ `Developer project "${error.projectName}" was not found in org "${error.orgId}". Run \`composio dev init\` or \`composio manage projects list\`.`);}if (error instanceof AmbiguousDeveloperProjectNameError) {diff --git a/ts/packages/cli/src/services/composio-clients.ts b/ts/packages/cli/src/services/composio-clients.tsindex 0a58106df..ee3b9516e 100644--- a/ts/packages/cli/src/services/composio-clients.ts+++ b/ts/packages/cli/src/services/composio-clients.ts@@ -744,6 +744,19 @@ export type ConsumerProjectResolveResponse = Schema.Schema.Type<typeof ConsumerProjectResolveResponse>;+export const LatestToolVersionResponse = Schema.Struct({+ tool_slug: Schema.String,+ version: Schema.String,+}).annotations({ identifier: 'LatestToolVersionResponse' });+export type LatestToolVersionResponse = Schema.Schema.Type<typeof LatestToolVersionResponse>;++export const ConsumerConnectedToolkitsResponse = Schema.Struct({+ toolkits: Schema.Array(Schema.String),+}).annotations({ identifier: 'ConsumerConnectedToolkitsResponse' });+export type ConsumerConnectedToolkitsResponse = Schema.Schema.Type<+ typeof ConsumerConnectedToolkitsResponse+>;+const extractArrayPayload = (json: unknown): ReadonlyArray<unknown> => {if (Array.isArray(json)) return json;if (json && typeof json === 'object') {@@ -1136,6 +1149,97 @@ export const resolveConsumerProject = (params: {);});+export const getLatestToolVersion = (params: {+ baseURL: string;+ apiKey: string;+ toolSlug: string;+ orgId?: string;+ projectId?: string;+ projectApiKey?: string;+}): Effect.Effect<LatestToolVersionResponse, HttpServerError | HttpDecodingError> =>+ Effect.gen(function* () {+ const response = yield* Effect.tryPromise({+ try: () =>+ fetch(+ `${params.baseURL}/api/v3/tools/${encodeURIComponent(params.toolSlug)}/get_latest_version`,+ {+ method: 'GET',+ redirect: 'error',+ headers: {+ ...(params.projectApiKey+ ? ({ 'x-api-key': params.projectApiKey } satisfies Record<string, string>)+ : ({ 'x-user-api-key': params.apiKey } satisfies Record<string, string>)),+ ...(params.orgId ? { 'x-org-id': params.orgId } : {}),+ ...(params.projectId ? { 'x-project-id': params.projectId } : {}),+ 'User-Agent': '@composio/cli',+ Accept: 'application/json',+ 'Content-Type': 'application/json',+ },+ }+ ),+ catch: error => new HttpServerError({ cause: error }),+ });++ if (!response.ok) {+ return yield* handleHttpErrorResponse(response);+ }++ const { json } = yield* streamResponseWithByteCount(response);++ return yield* pipe(+ Schema.decodeUnknown(LatestToolVersionResponse)(json),+ Effect.catchTag('ParseError', e => {+ const message = ParseResult.TreeFormatter.formatErrorSync(e);+ return new HttpDecodingError({+ cause: `ParseError\n ${message}`,+ });+ })+ );+ });++export const getConsumerConnectedToolkits = (params: {+ baseURL: string;+ apiKey: string;+ orgId: string;+ consumerUserId: string;+}): Effect.Effect<ConsumerConnectedToolkitsResponse, HttpServerError | HttpDecodingError> =>+ Effect.gen(function* () {+ const response = yield* Effect.tryPromise({+ try: () =>+ fetch(+ `${params.baseURL}/api/v3/org/consumer/connected_toolkits?user_id=${encodeURIComponent(params.consumerUserId)}`,+ {+ method: 'GET',+ redirect: 'error',+ headers: {+ 'x-user-api-key': params.apiKey,+ 'x-org-id': params.orgId,+ 'User-Agent': '@composio/cli',+ Accept: 'application/json',+ 'Content-Type': 'application/json',+ },+ }+ ),+ catch: error => new HttpServerError({ cause: error }),+ });++ if (!response.ok) {+ return yield* handleHttpErrorResponse(response);+ }++ const { json } = yield* streamResponseWithByteCount(response);++ return yield* pipe(+ Schema.decodeUnknown(ConsumerConnectedToolkitsResponse)(json),+ Effect.catchTag('ParseError', e => {+ const message = ParseResult.TreeFormatter.formatErrorSync(e);+ return new HttpDecodingError({+ cause: `ParseError\n ${message}`,+ });+ })+ );+ });+export class DeveloperProjectNotFoundError extends Data.TaggedError('services/DeveloperProjectNotFoundError')<{diff --git a/ts/packages/cli/src/services/consumer-short-term-cache.ts b/ts/packages/cli/src/services/consumer-short-term-cache.tsnew file mode 100644index 000000000..f8d263aeb--- /dev/null+++ b/ts/packages/cli/src/services/consumer-short-term-cache.ts@@ -0,0 +1,222 @@+import path from 'node:path';+import { FileSystem } from '@effect/platform';+import { Effect, Option } from 'effect';+import { setupCacheDir } from 'src/effects/setup-cache-dir';+import { NodeProcess } from 'src/services/node-process';+import {+ getConsumerConnectedToolkits,+ resolveConsumerProject,+} from 'src/services/composio-clients';+import { resolveCommandProject } from 'src/services/command-project';+import { ComposioUserContext } from 'src/services/user-context';++const CACHE_FILE = 'consumer-short-term-cache.json';+const CACHE_TTL_MS = 5 * 60 * 1000;+const SEARCH_SESSION_EXTENSION_MS = 2 * 60 * 1000;++type CacheEntry = {+ readonly toolkits: ReadonlyArray<string>;+ readonly expiresAt: string;+ readonly probablyMyCliSessionsByCwdHash?: Record<+ string,+ {+ readonly id: string;+ readonly expiresAt: string;+ }+ >;+};++type CacheState = Record<string, CacheEntry>;++const cacheKey = (orgId: string, consumerUserId: string) => `${orgId}:${consumerUserId}`;++const cachePath = (cacheDir: string) => path.join(cacheDir, CACHE_FILE);++const cwdHash = (cwd: string): string => {+ let hash = 5381;+ for (let i = 0; i < cwd.length; i += 1) {+ hash = (hash * 33) ^ cwd.charCodeAt(i);+ }+ return Math.abs(hash >>> 0).toString(36);+};++const createProbablyMyCliSessionId = (cwd: string): string => {+ const random = crypto.randomUUID().replace(/-/g, '').slice(0, 10);+ return `cli_s_${cwdHash(cwd)}_${random}`;+};++const resolveSearchSessionMetadata = (params: {+ readonly currentEntry?: CacheEntry;+ readonly cwd: string;+}) => {+ const now = Date.now();+ const currentCwdHash = cwdHash(params.cwd);+ const previousMap = {+ ...(params.currentEntry?.probablyMyCliSessionsByCwdHash ?? {}),+ };++ const probablyMyCliSessionsByCwdHash = Object.fromEntries(+ Object.entries(previousMap).filter(([, session]) => {+ const expiresAtMs = Date.parse(session.expiresAt);+ return Number.isFinite(expiresAtMs) && expiresAtMs > now;+ })+ );++ const currentSession = probablyMyCliSessionsByCwdHash[currentCwdHash];+ if (currentSession) {+ probablyMyCliSessionsByCwdHash[currentCwdHash] = {+ id: currentSession.id,+ expiresAt: new Date(+ Math.max(now, Date.parse(currentSession.expiresAt)) + SEARCH_SESSION_EXTENSION_MS+ ).toISOString(),+ };+ } else {+ probablyMyCliSessionsByCwdHash[currentCwdHash] = {+ id: createProbablyMyCliSessionId(params.cwd),+ expiresAt: new Date(now + CACHE_TTL_MS).toISOString(),+ };+ }++ return {+ probablyMyCliSessionsByCwdHash,+ };+};++const readCache = () =>+ Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const cacheDir = yield* setupCacheDir;+ const filePath = cachePath(cacheDir);+ if (!(yield* fs.exists(filePath))) {+ return {} satisfies CacheState;+ }+ const raw = yield* fs.readFileString(filePath, 'utf8');+ return yield* Effect.sync(() => JSON.parse(raw) as CacheState).pipe(+ Effect.catchAll(() => Effect.succeed({} satisfies CacheState))+ );+ });++const writeCache = (state: CacheState) =>+ Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const cacheDir = yield* setupCacheDir;+ yield* fs.makeDirectory(cacheDir, { recursive: true });+ yield* fs.writeFileString(cachePath(cacheDir), JSON.stringify(state, null, 2));+ });++export const getFreshConsumerConnectedToolkitsFromCache = (params: {+ orgId: string;+ consumerUserId: string;+}) =>+ Effect.gen(function* () {+ const state = yield* readCache();+ const entry = state[cacheKey(params.orgId, params.consumerUserId)];+ if (!entry) {+ return Option.none<ReadonlyArray<string>>();+ }+ const expiresAtMs = Date.parse(entry.expiresAt);+ if (!Number.isFinite(expiresAtMs) || expiresAtMs <= Date.now()) {+ return Option.none<ReadonlyArray<string>>();+ }+ return Option.some(entry.toolkits);+ });++export const invalidateConsumerConnectedToolkitsCache = () =>+ Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const cacheDir = yield* setupCacheDir;+ const filePath = cachePath(cacheDir);+ if (yield* fs.exists(filePath)) {+ yield* fs.remove(filePath);+ }+ });++const resolveConsumerScope = (params?: {+ readonly orgId?: string;+ readonly consumerUserId?: string;+}) =>+ Effect.gen(function* () {+ if (params?.orgId && params.consumerUserId) {+ return {+ orgId: params.orgId,+ consumerUserId: params.consumerUserId,+ };+ }++ const project = yield* resolveCommandProject({ mode: 'consumer' }).pipe(Effect.option);+ if (Option.isSome(project) && project.value.projectType === 'CONSUMER') {+ return {+ orgId: project.value.orgId,+ consumerUserId: project.value.consumerUserId ?? '',+ };+ }++ const userContext = yield* ComposioUserContext;+ const apiKey = Option.getOrUndefined(userContext.data.apiKey);+ const orgId = Option.getOrUndefined(userContext.data.orgId);+ if (!apiKey || !orgId) {+ return null;+ }+ const consumerProject = yield* resolveConsumerProject({+ baseURL: userContext.data.baseURL,+ apiKey,+ orgId,+ }).pipe(Effect.option);+ if (Option.isNone(consumerProject)) {+ return null;+ }+ return {+ orgId,+ consumerUserId: consumerProject.value.consumer_user_id,+ };+ });++export const refreshConsumerConnectedToolkitsCache = (params?: {+ readonly orgId?: string;+ readonly consumerUserId?: string;+}) =>+ Effect.gen(function* () {+ const scope = yield* resolveConsumerScope(params);+ if (!scope?.consumerUserId) {+ return;+ }++ const userContext = yield* ComposioUserContext;+ const apiKey = Option.getOrUndefined(userContext.data.apiKey);+ if (!apiKey) {+ return;+ }++ const response = yield* getConsumerConnectedToolkits({+ baseURL: userContext.data.baseURL,+ apiKey,+ orgId: scope.orgId,+ consumerUserId: scope.consumerUserId,+ });+ const state = yield* readCache();+ const key = cacheKey(scope.orgId, scope.consumerUserId);+ const currentEntry = state[key];+ const proc = yield* NodeProcess;+ const searchSessionFields = resolveSearchSessionMetadata({+ currentEntry,+ cwd: proc.cwd,+ });+ yield* writeCache({+ ...state,+ [key]: {+ toolkits: response.toolkits.map(toolkit => toolkit.toLowerCase()),+ expiresAt: new Date(Date.now() + CACHE_TTL_MS).toISOString(),+ ...searchSessionFields,+ },+ });+ });++export const primeConsumerConnectedToolkitsCacheInBackground = (params?: {+ readonly orgId?: string;+ readonly consumerUserId?: string;+}) =>+ refreshConsumerConnectedToolkitsCache(params).pipe(+ Effect.catchAll(() => Effect.void),+ Effect.forkDaemon,+ Effect.asVoid+ );diff --git a/ts/packages/cli/src/services/runtime-debug-flags.ts b/ts/packages/cli/src/services/runtime-debug-flags.tsnew file mode 100644index 000000000..6ce337e2f--- /dev/null+++ b/ts/packages/cli/src/services/runtime-debug-flags.ts@@ -0,0 +1,29 @@+type RuntimeDebugFlags = {+ readonly perfDebug: boolean;+ readonly toolDebug: boolean;+};++let runtimeDebugFlags: RuntimeDebugFlags = {+ perfDebug: false,+ toolDebug: false,+};++export const setRuntimeDebugFlags = (flags: Partial<RuntimeDebugFlags>) => {+ runtimeDebugFlags = {+ perfDebug: flags.perfDebug ?? runtimeDebugFlags.perfDebug,+ toolDebug: flags.toolDebug ?? runtimeDebugFlags.toolDebug,+ };+};++export const resetRuntimeDebugFlags = () => {+ runtimeDebugFlags = {+ perfDebug: false,+ toolDebug: false,+ };+};++export const isPerfDebugEnabled = () =>+ runtimeDebugFlags.perfDebug || process.env.COMPOSIO_PERF_DEBUG === '1';++export const isToolDebugEnabled = () =>+ runtimeDebugFlags.toolDebug || process.env.COMPOSIO_TOOL_DEBUG === '1';diff --git a/ts/packages/cli/src/services/tool-input-validation.ts b/ts/packages/cli/src/services/tool-input-validation.tsnew file mode 100644index 000000000..46e4345d3--- /dev/null+++ b/ts/packages/cli/src/services/tool-input-validation.ts@@ -0,0 +1,429 @@+import path from 'node:path';+import { FileSystem } from '@effect/platform';+import { Effect, Option } from 'effect';+import { jsonSchemaToZodSchema } from '@composio/core';+import { z } from 'zod/v3';+import { setupCacheDir } from 'src/effects/setup-cache-dir';+import { ComposioToolkitsRepository, getLatestToolVersion } from 'src/services/composio-clients';+import { isToolDebugEnabled } from 'src/services/runtime-debug-flags';+import { ComposioUserContext } from 'src/services/user-context';++const TOOL_DEFINITIONS_DIR = 'tool_definitions';++type CachedToolInputDefinition = {+ readonly version: string | null;+ readonly inputSchema: Record<string, unknown>;+};++const sanitizeToolSlug = (slug: string) => slug.replace(/[^A-Za-z0-9_.-]/g, '_');++const toolDefinitionPath = (cacheDir: string, slug: string) =>+ path.join(cacheDir, TOOL_DEFINITIONS_DIR, `${sanitizeToolSlug(slug)}.json`);++const ensureToolDefinitionsDir = (fs: FileSystem.FileSystem, cacheDir: string) =>+ fs.makeDirectory(path.join(cacheDir, TOOL_DEFINITIONS_DIR), { recursive: true });++const parseSchemaFile = (raw: string, schemaPath: string) =>+ Effect.try({+ try: () => JSON.parse(raw) as Record<string, unknown>,+ catch: () => new Error(`Cached tool schema at ${schemaPath} is not valid JSON.`),+ });++const isRecord = (value: unknown): value is Record<string, unknown> =>+ typeof value === 'object' && value !== null && !Array.isArray(value);++const PLACEHOLDER_TOOL_VERSION = '00000000_00';++const selectLatestVersion = (versions: ReadonlyArray<string> | undefined): string | null => {+ if (!versions || versions.length === 0) {+ return null;+ }++ for (const version of versions) {+ if (+ typeof version === 'string' &&+ version.trim().length > 0 &&+ version !== PLACEHOLDER_TOOL_VERSION+ ) {+ return version;+ }+ }++ return versions.find(version => typeof version === 'string' && version.trim().length > 0) ?? null;+};++const resolveLatestAvailableVersion = (params: {+ readonly toolLatestVersion: string | null;+ readonly toolkitLatestVersion: string | null;+}): string | null => {+ if (+ params.toolLatestVersion &&+ params.toolLatestVersion.trim().length > 0 &&+ params.toolLatestVersion !== PLACEHOLDER_TOOL_VERSION+ ) {+ return params.toolLatestVersion;+ }++ return params.toolkitLatestVersion;+};++const toolDebugLog = (label: string, details: Record<string, unknown>) => {+ if (!isToolDebugEnabled()) return;+ console.error(`[tool-debug] ${JSON.stringify({ label, ...details })}`);+};++const parseCachedToolDefinition = (parsed: Record<string, unknown>): CachedToolInputDefinition => {+ const inputSchema = parsed.inputSchema;+ if (isRecord(inputSchema)) {+ return {+ version: typeof parsed.version === 'string' ? parsed.version : null,+ inputSchema,+ };+ }++ // Backward compatibility for previously cached bare-schema files.+ return {+ version: null,+ inputSchema: parsed,+ };+};++const serializeCachedToolDefinition = (definition: CachedToolInputDefinition): string =>+ JSON.stringify(+ {+ version: definition.version,+ inputSchema: definition.inputSchema,+ },+ null,+ 2+ );++export const getCachedToolInputDefinition = (slug: string) =>+ Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const cacheDir = yield* setupCacheDir;+ const schemaPath = toolDefinitionPath(cacheDir, slug);++ if (!(yield* fs.exists(schemaPath))) {+ return null;+ }++ const raw = yield* fs.readFileString(schemaPath, 'utf8');+ const parsed = yield* parseSchemaFile(raw, schemaPath);+ const cached = parseCachedToolDefinition(parsed);+ return {+ schemaPath,+ schema: cached.inputSchema,+ version: cached.version,+ };+ });++export const getToolDefinitionCachePath = (slug: string) =>+ Effect.gen(function* () {+ const cacheDir = yield* setupCacheDir;+ return toolDefinitionPath(cacheDir, slug);+ });++export const invalidateToolInputDefinition = (slug: string) =>+ Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const cacheDir = yield* setupCacheDir;+ const schemaPath = toolDefinitionPath(cacheDir, slug);+ if (yield* fs.exists(schemaPath)) {+ yield* fs.remove(schemaPath);+ }+ });++const fetchResolvedLatestToolVersion = (+ slug: string,+ params?: { readonly orgId?: string; readonly projectId?: string }+) =>+ Effect.gen(function* () {+ const userContext = yield* ComposioUserContext;+ const apiKey = Option.getOrUndefined(userContext.data.apiKey);+ if (!apiKey) {+ return null;+ }++ const latest = yield* getLatestToolVersion({+ baseURL: userContext.data.baseURL,+ apiKey,+ toolSlug: slug,+ orgId: params?.orgId,+ projectId: params?.projectId,+ });+ toolDebugLog('latest_tool_version', {+ slug,+ orgId: params?.orgId,+ projectId: params?.projectId,+ response: latest,+ });+ return latest.version;+ });++const fetchAndCacheToolInputDefinition = (+ slug: string,+ params?: { readonly orgId?: string; readonly projectId?: string }+) =>+ Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const repo = yield* ComposioToolkitsRepository;+ const cacheDir = yield* setupCacheDir;+ const schemaPath = toolDefinitionPath(cacheDir, slug);+ yield* ensureToolDefinitionsDir(fs, cacheDir);++ const tool = yield* repo.getToolDetailed(slug);+ toolDebugLog('tool_detail', {+ slug,+ tool,+ });+ const schema = (tool.input_parameters ?? {}) as Record<string, unknown>;+ const version =+ (yield* fetchResolvedLatestToolVersion(slug, params).pipe(+ Effect.catchAll(() => Effect.succeed(null))+ )) ??+ resolveLatestAvailableVersion({+ toolLatestVersion: selectLatestVersion(tool.available_versions),+ toolkitLatestVersion: null,+ });+ toolDebugLog('resolved_tool_version', {+ slug,+ resolvedVersion: version,+ cachePath: schemaPath,+ });+ yield* fs.writeFileString(+ schemaPath,+ serializeCachedToolDefinition({+ version,+ inputSchema: schema,+ })+ );++ return { schemaPath, schema, version };+ });++export const getOrFetchToolInputDefinition = (+ slug: string,+ params?: { readonly orgId?: string; readonly projectId?: string }+) =>+ Effect.gen(function* () {+ const cached = yield* getCachedToolInputDefinition(slug);+ if (!cached) {+ return yield* fetchAndCacheToolInputDefinition(slug, params);+ }++ const freshness = yield* refreshToolInputDefinitionIfVersionChanged(+ slug,+ cached.version,+ params+ ).pipe(+ Effect.catchAll(() =>+ Effect.succeed({+ isStale: false,+ latestVersion: cached.version,+ skipped: false as const,+ })+ )+ );++ if (!freshness.isStale) {+ return cached;+ }++ const refreshed = yield* getCachedToolInputDefinition(slug);+ return refreshed ?? (yield* fetchAndCacheToolInputDefinition(slug, params));+ });++export const refreshToolInputDefinitionIfVersionChanged = (+ slug: string,+ cachedVersion: string | null,+ params?: { readonly orgId?: string; readonly projectId?: string }+) =>+ Effect.gen(function* () {+ const latestVersion = yield* fetchResolvedLatestToolVersion(slug, params);+ toolDebugLog('resolved_tool_version', {+ slug,+ mode: 'refresh',+ cachedVersion,+ resolvedVersion: latestVersion,+ orgId: params?.orgId,+ projectId: params?.projectId,+ });+ const isStale = latestVersion !== cachedVersion;++ if (isStale) {+ yield* fetchAndCacheToolInputDefinition(slug, params);+ }++ return { isStale, latestVersion, skipped: false as const };+ });++export class ToolInputValidationError extends Error {+ readonly _tag = 'ToolInputValidationError';++ constructor(+ readonly toolSlug: string,+ readonly schemaPath: string,+ readonly issues: ReadonlyArray<string>,+ options?: ErrorOptions+ ) {+ super(+ [+ `Input validation failed for ${toolSlug}.`,+ `Schema: ${schemaPath}`,+ ...issues.map(issue => `- ${issue}`),+ ].join('\n'),+ options+ );+ }+}++const getObjectSchemaProperties = (schema: Record<string, unknown>): ReadonlyArray<string> => {+ const properties = schema.properties;+ if (!properties || typeof properties !== 'object' || Array.isArray(properties)) {+ return [];+ }++ return Object.keys(properties as Record<string, unknown>);+};++const normalizeKey = (value: string) => value.toLowerCase().replace(/[^a-z0-9]/g, '');++const levenshteinDistance = (left: string, right: string): number => {+ if (left === right) return 0;+ if (left.length === 0) return right.length;+ if (right.length === 0) return left.length;++ const previous = Array.from({ length: right.length + 1 }, (_, index) => index);+ const current = new Array<number>(right.length + 1);++ for (let i = 0; i < left.length; i += 1) {+ current[0] = i + 1;+ for (let j = 0; j < right.length; j += 1) {+ const cost = left[i] === right[j] ? 0 : 1;+ current[j + 1] = Math.min(current[j]! + 1, previous[j + 1]! + 1, previous[j]! + cost);+ }+ for (let j = 0; j <= right.length; j += 1) {+ previous[j] = current[j]!;+ }+ }++ return previous[right.length]!;+};++const findClosestSchemaKey = (+ unknownKey: string,+ allowedKeys: ReadonlyArray<string>+): string | undefined => {+ const normalizedUnknownKey = normalizeKey(unknownKey);+ const candidates = allowedKeys+ .map(key => ({+ key,+ normalized: normalizeKey(key),+ }))+ .map(candidate => {+ const distance = levenshteinDistance(normalizedUnknownKey, candidate.normalized);+ const containsBonus =+ candidate.normalized.includes(normalizedUnknownKey) ||+ normalizedUnknownKey.includes(candidate.normalized)+ ? -2+ : 0;+ return {+ key: candidate.key,+ score: distance + containsBonus,+ };+ })+ .sort((left, right) => left.score - right.score);++ const best = candidates[0];+ if (!best) {+ return undefined;+ }++ const threshold = Math.max(3, Math.ceil(normalizedUnknownKey.length * 0.6));+ return best.score <= threshold ? best.key : undefined;+};++const formatUnknownKeyIssue = (+ unknownKeys: ReadonlyArray<string>,+ allowedKeys: ReadonlyArray<string>+): ReadonlyArray<string> => {+ const allowedList = allowedKeys.join(', ');+ return unknownKeys.map(key => {+ const suggestion = findClosestSchemaKey(key, allowedKeys);+ const lines = [`<root>: Unknown key "${key}".`];+ if (suggestion) {+ lines.push(`Use "${suggestion}" instead.`);+ }+ if (allowedList) {+ lines.push(`Allowed top-level keys: ${allowedList}`);+ }+ return lines.join(' ');+ });+};++export const validateToolInputArgumentsWithDefinition = (+ slug: string,+ args: Record<string, unknown>,+ definition: {+ readonly schemaPath: string;+ readonly schema: Record<string, unknown>;+ }+) =>+ Effect.gen(function* () {+ const { schemaPath, schema } = definition;+ const allowedKeys = getObjectSchemaProperties(schema);++ const zodSchema = yield* Effect.try({+ try: () => jsonSchemaToZodSchema<z.ZodTypeAny>(schema),+ catch: error =>+ new ToolInputValidationError(+ slug,+ schemaPath,+ ['Could not compile the cached JSON schema into a Zod validator.'],+ { cause: error }+ ),+ });++ const parsed = zodSchema.safeParse(args);+ if (parsed.success) {+ return { schemaPath, schema };+ }++ const issues = parsed.error.issues.flatMap(issue => {+ if (issue.code === 'unrecognized_keys') {+ return formatUnknownKeyIssue(issue.keys, allowedKeys);+ }+ const location = issue.path.length > 0 ? issue.path.join('.') : '<root>';+ return [`${location}: ${issue.message}`];+ });++ return yield* Effect.fail(new ToolInputValidationError(slug, schemaPath, issues));+ });++export const validateToolInputArgumentsIfCached = (slug: string, args: Record<string, unknown>) =>+ Effect.gen(function* () {+ const cached = yield* getCachedToolInputDefinition(slug);+ if (!cached) {+ return false as const;+ }++ yield* validateToolInputArgumentsWithDefinition(slug, args, cached);+ return true as const;+ });++export const validateToolInputArguments = (+ slug: string,+ args: Record<string, unknown>,+ params?: { readonly orgId?: string; readonly projectId?: string }+) =>+ Effect.gen(function* () {+ const definition = yield* getOrFetchToolInputDefinition(slug, params);+ return yield* validateToolInputArgumentsWithDefinition(slug, args, definition);+ });++export const warmToolInputDefinitions = (slugs: ReadonlyArray<string>) =>+ Effect.forEach([...new Set(slugs)].filter(Boolean), slug => getOrFetchToolInputDefinition(slug), {+ concurrency: 'unbounded',+ discard: true,+ });diff --git a/ts/packages/cli/test/src/commands/$default.cmd.test.ts b/ts/packages/cli/test/src/commands/$default.cmd.test.tsindex e82d29b3d..9e119c68f 100644--- a/ts/packages/cli/test/src/commands/$default.cmd.test.ts+++ b/ts/packages/cli/test/src/commands/$default.cmd.test.ts@@ -15,7 +15,7 @@ describe('CLI: composio', () => {expect(result).toEqual(ValidationError.commandMismatch(HelpDoc.p(- "Invalid subcommand for composio - use one of 'version', 'upgrade', 'whoami', 'login', 'logout', 'install', 'init', 'search', 'link', 'execute', 'listen', 'generate', 'manage'"+ "Invalid subcommand for composio - use one of 'version', 'upgrade', 'whoami', 'login', 'logout', 'run', 'install', 'dev', 'tools', 'search', 'link', 'execute', 'generate', 'manage'")));diff --git a/ts/packages/cli/test/src/commands/__snapshots__/$default.cmd.test.ts.snap b/ts/packages/cli/test/src/commands/__snapshots__/$default.cmd.test.ts.snapindex d074f777c..6ca41ba19 100644--- a/ts/packages/cli/test/src/commands/__snapshots__/$default.cmd.test.ts.snap+++ b/ts/packages/cli/test/src/commands/__snapshots__/$default.cmd.test.ts.snap@@ -2,7 +2,9 @@exports[`CLI: composio > [Given] --help flag [Then] prints help message 1`] = `"-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.+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.+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.+Use \`dev\` when you are building with Composio and want scaffolding, playground execution, triggers, and logs.USAGEcomposio <command> [options]@@ -33,27 +35,43 @@ BASIC COMMANDSLog out from the Composio CLI session.Usage: composio logout- init- Initialize this directory with a developer project.- Usage: composio init [--no-browser] [-y, --yes]+ run+ Run inline ESNext TS/JS code or a file with Bun and injected Composio helpers.+ Usage: composio run <code> [-- ...args] | run [-f, --file text] [-- ...args] [--dry-run] [--skip-connection-check] [--skip-tool-params-check] [--no-verify]Options:- --no-browser Skip opening browser for auth- -y, --yes Auto-select the default developer project+ <code> Inline Bun ESNext code with injected execute(slug, data?) and search(query, options?) helpers+ -f, --file Run a TS/JS file with the Bun runtime instead of inline code+ --dry-run Preview execute(...) calls without running remote actions+ --skip-connection-check Skip the short-lived linked-account fail-fast check if you just connected an account+ --skip-tool-params-check Skip the local tool parameter/schema validation check+ --no-verify Skip both the linked-account fail-fast check and the local tool parameter checksearch- Search tools by use case across toolkits/apps.+ Semantic search for tools by use case across all toolkits/apps.Usage: composio search <query> [--toolkits text] [--limit integer]Options:<query> Semantic use-case query (e.g. "send emails")--toolkits Filter by toolkit slugs, comma-separated--limit Number of results per page (1-1000)+ tools+ List tools for one toolkit, or inspect a cached schema-backed summary.+ Usage: composio tools list <toolkit> [--query text] | tools info <slug>+ Options:+ list <toolkit> Non-semantic per-toolkit listing; use this when you already know the toolkit+ info <slug> Print a brief summary and cache the same raw schema used by execute --get-schema+execute- Execute a tool.- Usage: composio execute <slug> [-d, --data text]+ Execute a tool, preview it with --dry-run, or fetch its input schema.+ Usage: composio execute <slug> [-d, --data text] [--dry-run] [--get-schema] [--skip-connection-check] [--skip-tool-params-check] [--no-verify]Options:<slug> Tool slug (e.g. "GITHUB_CREATE_ISSUE")- -d, --data JSON arguments, @file, or - for stdin+ -d, --data JSON or JS-style object arguments, e.g. -d '{ repo: "foo" }', @file, or - for stdin+ --dry-run Validate and preview the tool call without executing it+ --get-schema Fetch and print the raw cached schema; tools info shows the same schema with a brief summary+ --skip-connection-check Skip the short-lived linked-account fail-fast check if you just connected an account+ --skip-tool-params-check Skip the local tool parameter/schema validation check+ --no-verify Skip both the linked-account fail-fast check and the local tool parameter checklinkConnect a user account for a toolkit/app.@@ -62,22 +80,10 @@ BASIC COMMANDS<toolkit> Toolkit slug to link (e.g. "github", "gmail")--no-browser Skip auto-opening the browser- listen- Listen for trigger events.- Usage: composio listen [--toolkits text] [--trigger-id text] [--user-id text] [--max-events integer] [--forward text] [--out text]- Options:- --toolkits Filter by toolkit slugs, comma-separated- --trigger-id Filter by trigger id- --user-id Filter by user id- --max-events Stop after N matching events- --forward Forward events to URL (signed with COMPOSIO_WEBHOOK_SECRET)- --out Append events to file- --json Show raw event payload as JSON- --table Show compact table rows-ADVANCED COMMANDS+ dev Developer workflows: init a local project, execute tools with playground users, listen for triggers, and inspect logs.generate Generate type stubs for toolkits, tools, and triggers, auto-detecting project language (TypeScript | Python)- manage Developer/admin workflows: orgs, toolkits, triggers, auth configs, logs, and deprecated project commands.+ manage Manage your developer orgs, toolkits, connected accounts, triggers, auth configs, and projects.FLAGS-h, --help Show help for commanddiff --git a/ts/packages/cli/test/src/commands/init.cmd.test.ts b/ts/packages/cli/test/src/commands/init.cmd.test.tsindex 8db2ae649..57dd3d45d 100644--- a/ts/packages/cli/test/src/commands/init.cmd.test.ts+++ b/ts/packages/cli/test/src/commands/init.cmd.test.ts@@ -2,12 +2,12 @@ import { describe, expect, layer } from '@effect/vitest';import { Effect } from 'effect';import { cli, TestLive, MockConsole } from 'test/__utils__';-describe('CLI: composio init', () => {- describe('init --help', () => {+describe('CLI: composio dev init', () => {+ describe('dev init --help', () => {layer(TestLive({ fixture: 'typescript-project' }))(it => {it.scoped('[Then] shows --no-browser and --yes, no --org-id or --project-id', () =>Effect.gen(function* () {- yield* cli(['init', '--help']);+ yield* cli(['dev', 'init', '--help']);const lines = yield* MockConsole.getLines({ stripAnsi: true });const output = lines.join('\n');expect(output).toContain('--no-browser');diff --git a/ts/packages/cli/test/src/commands/projects/projects.list.cmd.test.ts b/ts/packages/cli/test/src/commands/projects/projects.list.cmd.test.tsindex 225d99b86..b4b2c5c1d 100644--- a/ts/packages/cli/test/src/commands/projects/projects.list.cmd.test.ts+++ b/ts/packages/cli/test/src/commands/projects/projects.list.cmd.test.ts@@ -41,7 +41,7 @@ describe('CLI: composio manage projects list', () => {expect(output).toContain(' Project One (project_1)');expect(output).toContain(' Project Two (project_2)');expect(output).toContain(- 'Hint: run `composio init` in a directory to bind it to a developer project.'+ 'Hint: run `composio dev init` in a directory to bind it to a developer project.');expect(output).toContain('Run `composio manage orgs switch` to change your default org.');})diff --git a/ts/packages/cli/test/src/commands/projects/projects.switch.cmd.test.ts b/ts/packages/cli/test/src/commands/projects/projects.switch.cmd.test.tsindex 0e208208b..4ab4daf5a 100644--- a/ts/packages/cli/test/src/commands/projects/projects.switch.cmd.test.ts+++ b/ts/packages/cli/test/src/commands/projects/projects.switch.cmd.test.ts@@ -9,7 +9,7 @@ describe('CLI: composio manage projects switch', () => {yield* cli(['manage', 'projects', 'switch']).pipe(Effect.catchAll(() => Effect.void));const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');expect(output).toContain('Global developer project switching is no longer supported');- expect(output).toContain('composio init');+ expect(output).toContain('composio dev init');}));});diff --git a/ts/packages/cli/test/src/commands/run.cmd.test.ts b/ts/packages/cli/test/src/commands/run.cmd.test.tsnew file mode 100644index 000000000..d4b068d6d--- /dev/null+++ b/ts/packages/cli/test/src/commands/run.cmd.test.ts@@ -0,0 +1,154 @@+import { describe, expect, layer } from '@effect/vitest';+import { Effect } from 'effect';+import { afterEach, it, vi } from 'vitest';+import {+ buildRunHelpersSource,+ extractInlineExecuteToolSlugs,+ inferCliInvocationPrefix,+} from 'src/commands/run.cmd';+import { cli, MockConsole, TestLive } from 'test/__utils__';++describe('CLI: composio run', () => {+ afterEach(() => {+ vi.unstubAllGlobals();+ vi.restoreAllMocks();+ });++ layer(TestLive())(it => {+ it.scoped(+ '[Given] inline code and args [Then] it forwards them to the embedded Bun runtime',+ () =>+ Effect.gen(function* () {+ const spawn = vi.fn(() => ({ exited: Promise.resolve(7) }));+ const exit = vi.spyOn(process, 'exit').mockImplementation((() => undefined) as never);+ vi.stubGlobal('Bun', { spawn });++ yield* cli(['run', 'console.log("hi")', '--flag', 'value']);++ expect(spawn).toHaveBeenCalledTimes(1);+ const spawnConfig = (spawn as any).mock.calls[0][0] as {+ cmd: string[];+ env: unknown;+ stdio: string[];+ };+ expect(spawnConfig.cmd[0]).toBe(process.execPath);+ expect(spawnConfig.cmd[1]).toBe('--preload');+ expect(spawnConfig.cmd[2]).toMatch(/globals\.mjs$/);+ expect(spawnConfig.cmd.slice(3)).toEqual([+ '--eval',+ 'console.log("hi")',+ '--',+ '--flag',+ 'value',+ ]);+ expect(spawnConfig.env).toEqual(+ expect.objectContaining({+ ...process.env,+ BUN_BE_BUN: '1',+ })+ );+ expect(spawnConfig.stdio).toEqual(['inherit', 'inherit', 'inherit']);+ expect(exit).toHaveBeenCalledWith(7);+ })+ );+ });++ layer(TestLive())(it => {+ it.scoped('[Given] --file [Then] it forwards file execution to the embedded Bun runtime', () =>+ Effect.gen(function* () {+ const spawn = vi.fn(() => ({ exited: Promise.resolve(0) }));+ const exit = vi.spyOn(process, 'exit').mockImplementation((() => undefined) as never);+ vi.stubGlobal('Bun', { spawn });++ yield* cli(['run', '--file', './script.ts', '--', 'hello']);++ expect(spawn).toHaveBeenCalledTimes(1);+ const spawnConfig = (spawn as any).mock.calls[0][0] as {+ cmd: string[];+ env: unknown;+ stdio: string[];+ };+ expect(spawnConfig.cmd[0]).toBe(process.execPath);+ expect(spawnConfig.cmd[1]).toBe('--preload');+ expect(spawnConfig.cmd[2]).toMatch(/globals\.mjs$/);+ expect(spawnConfig.cmd.slice(3)).toEqual(['run', './script.ts', '--', 'hello']);+ expect(spawnConfig.env).toEqual(+ expect.objectContaining({+ ...process.env,+ BUN_BE_BUN: '1',+ })+ );+ expect(spawnConfig.stdio).toEqual(['inherit', 'inherit', 'inherit']);+ expect(exit).toHaveBeenCalledWith(0);+ })+ );+ });++ layer(TestLive())(it => {+ it.scoped('[Given] no inline code and no --file [Then] it fails with a clear error', () =>+ Effect.gen(function* () {+ const exit = yield* cli(['run']).pipe(Effect.exit);+ expect(exit._tag).toBe('Failure');+ })+ );+ });++ layer(TestLive())(it => {+ it.scoped('[Given] run help [Then] it documents injected search and execute helpers', () =>+ Effect.gen(function* () {+ yield* cli(['run', '--help']);+ const lines = yield* MockConsole.getLines({ stripAnsi: true });+ const output = lines.join('\n');+ expect(output).toContain('await search(query');+ expect(output).toContain('await execute(slug, data?)');+ expect(output).toContain('import { $ } from "bun"');+ expect(output).toContain('top level `execute` and `search` auth states');+ expect(output).toContain('tool_definitions');+ })+ );+ });+});++describe('buildRunHelpersSource', () => {+ it('[Given] consumer context [Then] it embeds auth and consumer metadata in the helper source', () => {+ const source = buildRunHelpersSource(['/tmp/composio'], {+ apiKey: 'test_api_key',+ baseURL: 'https://api.example.test',+ webURL: 'https://app.example.test',+ orgId: 'org_test',+ consumerUserId: 'consumer_user_test',+ dryRun: true,+ });++ expect(source).toContain('COMPOSIO_USER_API_KEY');+ expect(source).toContain('"consumerUserId":"consumer_user_test"');+ expect(source).toContain('__composioConsumerContext');+ expect(source).toContain('returned no JSON output');+ expect(source).toContain('args.push("--dry-run");');+ expect(source).toContain('args.push("--skip-connection-check");');+ expect(source).toContain('args.push("--skip-tool-params-check");');+ expect(source).toContain('args.push("--no-verify");');+ expect(source).toContain(+ "stdio: ['inherit', 'pipe', perfDebugEnabled || toolDebugEnabled ? 'inherit' : 'pipe']"+ );+ });+});++describe('inferCliInvocationPrefix', () => {+ it('[Given] a compiled bunfs entrypoint [Then] it falls back to the binary path only', () => {+ expect(inferCliInvocationPrefix(['node', '/$bunfs/root/composio'])).toEqual([process.execPath]);+ });+});++describe('extractInlineExecuteToolSlugs', () => {+ it('[Given] inline run source [Then] it finds static execute slugs from the AST', () => {+ expect(+ extractInlineExecuteToolSlugs(`+ const first = await execute("GMAIL_SEND_EMAIL", { to: "[email protected]" });+ const dynamic = await execute(slug, payload);+ execute('GITHUB_CREATE_ISSUE', { owner: 'acme' });+ execute("GMAIL_SEND_EMAIL", { to: "[email protected]" });+ `)+ ).toEqual(['GMAIL_SEND_EMAIL', 'GITHUB_CREATE_ISSUE']);+ });+});diff --git a/ts/packages/cli/test/src/commands/tools/tools.execute.cmd.test.ts b/ts/packages/cli/test/src/commands/tools/tools.execute.cmd.test.tsindex 9a4826580..35e2b3785 100644--- a/ts/packages/cli/test/src/commands/tools/tools.execute.cmd.test.ts+++ b/ts/packages/cli/test/src/commands/tools/tools.execute.cmd.test.ts@@ -1,12 +1,16 @@+import * as fs from 'node:fs';import { describe, expect, layer } from '@effect/vitest';import { vi, beforeEach, afterEach } from 'vitest';import { ConfigProvider, Effect } from 'effect';import { extendConfigProvider } from 'src/services/config';import { ActionExecuteConnectedAccountNotFoundError } from 'src/services/tools-executor';+import { setupCacheDir } from 'src/effects/setup-cache-dir';+import { getOrFetchToolInputDefinition } from 'src/services/tool-input-validation';import * as redactModule from 'src/ui/redact';import { cli, TestLive, MockConsole } from 'test/__utils__';import type { TestLiveInput } from 'test/__utils__/services/test-layer';import { showToolsExecuteInputHelp } from 'src/commands/tools/commands/tools.execute.cmd';+import type { ToolkitDetailed } from 'src/models/toolkits';const testConfigProvider = ConfigProvider.fromMap(new Map([['COMPOSIO_USER_API_KEY', 'test_api_key']])@@ -30,7 +34,7 @@ const parseLastJson = (lines: ReadonlyArray<string>) => {throw new Error('Expected JSON output but none found');};-describe('CLI: composio manage tools execute', () => {+describe('CLI: composio execute', () => {// Disable CI redaction so tests see raw values.// The explicit CI-redaction test overrides via vi.spyOn and is unaffected.let savedCI: string | undefined;@@ -51,16 +55,7 @@ describe('CLI: composio manage tools execute', () => {)('[Given] -d inline JSON [Then] executes via Tool Router with defaults', it => {it.scoped('executes via Tool Router with defaults', () =>Effect.gen(function* () {- yield* cli([- 'manage',- 'tools',- 'execute',- 'GMAIL_SEND_EMAIL',- '--user-id',- 'default',- '-d',- '{"recipient":"a"}',- ]);+ yield* cli(['execute', 'GMAIL_SEND_EMAIL', '-d', '{"recipient":"a"}']);const lines = yield* MockConsole.getLines({ stripAnsi: true });const output = parseLastJson(lines);@@ -73,13 +68,374 @@ describe('CLI: composio manage tools execute', () => {);});+ layer(+ TestLive({+ baseConfigProvider: testConfigProvider,+ toolkitsData: {+ tools: [+ {+ name: 'Send Email',+ slug: 'GMAIL_SEND_EMAIL',+ description: 'Send an email',+ tags: ['email'],+ available_versions: ['20260115_00', '20260101_00'],+ input_parameters: {+ type: 'object',+ properties: {+ recipient_email: { type: 'string' },+ },+ },+ output_parameters: {+ type: 'object',+ properties: {+ message_id: { type: 'string' },+ },+ },+ },+ ],+ detailedToolkits: [+ {+ name: 'Gmail',+ slug: 'gmail',+ is_local_toolkit: false,+ composio_managed_auth_schemes: ['OAUTH2'],+ no_auth: false,+ meta: {+ description: 'Email service',+ categories: [],+ created_at: new Date('2024-05-03T11:44:32.061Z') as any,+ updated_at: new Date('2024-05-03T11:44:32.061Z') as any,+ available_versions: ['20260115_00', '20260101_00'],+ tools_count: 36,+ triggers_count: 2,+ },+ auth_config_details: [],+ },+ ] satisfies ToolkitDetailed[],+ } satisfies TestLiveInput['toolkitsData'],+ })+ )(+ '[Given] a cache miss [Then] the stored schema file includes the latest available version',+ it => {+ it.scoped('writes version metadata at the top of the cache file', () =>+ Effect.gen(function* () {+ const definition = yield* getOrFetchToolInputDefinition('GMAIL_SEND_EMAIL');+ const raw = fs.readFileSync(definition.schemaPath, 'utf8');+ const parsed = JSON.parse(raw) as {+ version: string | null;+ inputSchema: Record<string, unknown>;+ };++ expect(parsed.version).toBe('20260115_00');+ expect(parsed.inputSchema).toEqual({+ type: 'object',+ properties: {+ recipient_email: { type: 'string' },+ },+ });+ })+ );+ }+ );++ layer(+ TestLive({+ baseConfigProvider: testConfigProvider,+ toolkitsData: {+ tools: [+ {+ name: 'Send Email',+ slug: 'GMAIL_SEND_EMAIL',+ description: 'Send an email',+ tags: ['email'],+ available_versions: ['00000000_00'],+ input_parameters: {+ type: 'object',+ properties: {+ recipient_email: { type: 'string' },+ },+ },+ output_parameters: {+ type: 'object',+ properties: {+ message_id: { type: 'string' },+ },+ },+ },+ ],+ detailedToolkits: [+ {+ name: 'Gmail',+ slug: 'gmail',+ is_local_toolkit: false,+ composio_managed_auth_schemes: ['OAUTH2'],+ no_auth: false,+ meta: {+ description: 'Email service',+ categories: [],+ created_at: new Date('2024-05-03T11:44:32.061Z') as any,+ updated_at: new Date('2024-05-03T11:44:32.061Z') as any,+ available_versions: ['20260316_00'],+ tools_count: 36,+ triggers_count: 2,+ },+ auth_config_details: [],+ },+ ] satisfies ToolkitDetailed[],+ } satisfies TestLiveInput['toolkitsData'],+ })+ )(+ '[Given] a placeholder tool version [Then] it stores the toolkit latest version instead',+ it => {+ it.scoped('prefers toolkit latest version over 00000000_00', () =>+ Effect.gen(function* () {+ const definition = yield* getOrFetchToolInputDefinition('GMAIL_SEND_EMAIL');+ const raw = fs.readFileSync(definition.schemaPath, 'utf8');+ const parsed = JSON.parse(raw) as {+ version: string | null;+ inputSchema: Record<string, unknown>;+ };++ expect(parsed.version).toBe(null);+ })+ );+ }+ );++ layer(+ TestLive({+ baseConfigProvider: testConfigProvider,+ fixture: 'global-test-user-id',+ stdin: { isTTY: true, data: '' },+ toolsExecutor: {+ respondWith: {+ data: {+ ok: true,+ },+ error: null,+ successful: true,+ logId: 'log_stale_cache',+ },+ },+ toolkitsData: {+ tools: [+ {+ name: 'Send Email',+ slug: 'GMAIL_SEND_EMAIL',+ description: 'Send an email',+ tags: ['email'],+ available_versions: ['20260115_00', '20260101_00'],+ input_parameters: {+ type: 'object',+ properties: {+ recipient_email: { type: 'string' },+ subject: { type: 'string' },+ body: { type: 'string' },+ },+ },+ output_parameters: {+ type: 'object',+ properties: {+ message_id: { type: 'string' },+ },+ },+ },+ ],+ detailedToolkits: [+ {+ name: 'Gmail',+ slug: 'gmail',+ is_local_toolkit: false,+ composio_managed_auth_schemes: ['OAUTH2'],+ no_auth: false,+ meta: {+ description: 'Email service',+ categories: [],+ created_at: new Date('2024-05-03T11:44:32.061Z') as any,+ updated_at: new Date('2024-05-03T11:44:32.061Z') as any,+ available_versions: ['20260115_00', '20260101_00'],+ tools_count: 36,+ triggers_count: 2,+ },+ auth_config_details: [],+ },+ ] satisfies ToolkitDetailed[],+ } satisfies TestLiveInput['toolkitsData'],+ })+ )(+ '[Given] a stale cached schema [Then] it does not block execution and refreshes the cache',+ it => {+ it.scoped('uses tool execution instead of stale validation failure', () =>+ Effect.gen(function* () {+ const cacheDir = yield* setupCacheDir;+ const schemaPath = `${cacheDir}/tool_definitions/GMAIL_SEND_EMAIL.json`;+ fs.mkdirSync(`${cacheDir}/tool_definitions`, { recursive: true });+ fs.writeFileSync(+ schemaPath,+ JSON.stringify({+ version: '20260101_00',+ inputSchema: {+ type: 'object',+ properties: {+ to: { type: 'string' },+ },+ },+ }),+ 'utf8'+ );++ yield* cli([+ 'execute',+ 'GMAIL_SEND_EMAIL',+ '-d',+ '{"recipient_email":"[email protected]","subject":"Hi","body":"Hello"}',+ ]);++ const lines = yield* MockConsole.getLines({ stripAnsi: true });+ const output = parseLastJson(lines);+ expect(output.successful).toBe(true);+ expect(output.logId).toBe('log_stale_cache');++ const refreshed = JSON.parse(fs.readFileSync(schemaPath, 'utf8')) as {+ version: string | null;+ inputSchema: Record<string, unknown>;+ };+ expect(['20260101_00', '20260115_00']).toContain(refreshed.version);+ expect(refreshed.inputSchema.type).toBe('object');+ const propertyKeys = Object.keys(+ (refreshed.inputSchema.properties ?? {}) as Record<string, unknown>+ );+ expect(propertyKeys.some(key => key === 'recipient_email' || key === 'to')).toBe(true);+ })+ );+ }+ );++ layer(+ TestLive({+ baseConfigProvider: testConfigProvider,+ fixture: 'global-test-user-id',+ stdin: { isTTY: true, data: '' },+ toolkitsData: {+ tools: [+ {+ name: 'Send Email',+ slug: 'GMAIL_SEND_EMAIL',+ description: 'Send an email',+ tags: ['email'],+ available_versions: ['20260101_00'],+ input_parameters: {+ type: 'object',+ required: ['recipient'],+ properties: {+ recipient: { type: 'string', description: 'Recipient email' },+ },+ },+ output_parameters: {+ type: 'object',+ properties: {+ message_id: { type: 'string' },+ },+ },+ },+ ],+ } satisfies TestLiveInput['toolkitsData'],+ })+ )('[Given] invalid tool input [Then] it fails fast with the cached schema path', it => {+ it.scoped('prints validation issues and writes the schema to tool_definitions', () =>+ Effect.gen(function* () {+ const cacheDir = yield* setupCacheDir;+ const schemaPath = `${cacheDir}/tool_definitions/GMAIL_SEND_EMAIL.json`;+ fs.mkdirSync(`${cacheDir}/tool_definitions`, { recursive: true });+ fs.writeFileSync(+ schemaPath,+ JSON.stringify({+ version: '20260101_00',+ inputSchema: {+ type: 'object',+ required: ['recipient_email'],+ properties: {+ recipient_email: { type: 'string', description: 'Recipient email' },+ subject: { type: 'string' },+ body: { type: 'string' },+ },+ },+ }),+ 'utf8'+ );++ const failure = yield* cli([+ 'execute',+ 'GMAIL_SEND_EMAIL',+ '--dry-run',+ '-d',+ '{"recipient":42}',+ ]).pipe(+ Effect.flip,+ Effect.map(error => (error instanceof Error ? error.message : String(error)))+ );++ expect(failure).toContain('Input validation failed for GMAIL_SEND_EMAIL');+ expect(failure).toContain(schemaPath);+ expect(failure).toContain('Unknown key "recipient"');+ expect(failure).toContain('Use "recipient_email" instead.');+ expect(failure).toContain('Allowed top-level keys: recipient_email, subject, body');+ expect(fs.existsSync(schemaPath)).toBe(true);+ })+ );+ });++ layer(+ TestLive({+ baseConfigProvider: testConfigProvider,+ fixture: 'global-test-user-id',+ stdin: { isTTY: true, data: '' },+ toolsExecutor: {+ respondWith: {+ data: {+ content: 'token '.repeat(20_000),+ },+ error: null,+ successful: true,+ logId: 'log_large_output',+ },+ },+ })+ )('[Given] a large execution response [Then] it stores the payload in a temp file', it => {+ it.scoped('returns a file reference instead of the full inline payload', () =>+ Effect.gen(function* () {+ yield* cli(['execute', 'GMAIL_SEND_EMAIL', '-d', '{"recipient":"a"}']);+ const lines = yield* MockConsole.getLines({ stripAnsi: true });+ const output = parseLastJson(lines) as unknown as {+ successful: boolean;+ error: string | null;+ logId: string;+ storedInFile: boolean;+ tokenCount: number;+ outputFilePath: string;+ };++ expect(output.successful).toBe(true);+ expect(output.storedInFile).toBe(true);+ expect(output.logId).toBe('log_large_output');+ expect(output.tokenCount).toBeGreaterThan(10_000);+ expect(output.outputFilePath).toMatch(/^\/tmp\/composio\/[^/]+\/output-[^.]+\.json$/);+ expect(fs.existsSync(output.outputFilePath)).toBe(true);+ const storedJson = fs.readFileSync(output.outputFilePath, 'utf8');+ expect(storedJson).toContain('token token token');++ fs.rmSync(output.outputFilePath.split('/output-')[0]!, { recursive: true, force: true });+ })+ );+ });+layer(TestLive({baseConfigProvider: testConfigProvider,fixture: 'global-test-user-id',stdin: { isTTY: true, data: '' },})- )('[Given] composio execute alias [Then] works like composio manage tools execute', it => {+ )('[Given] composio execute [Then] it works for the consumer flow', it => {it.scoped('root execute works for consumer flow without developer-only flags', () =>Effect.gen(function* () {yield* cli(['execute', 'GMAIL_SEND_EMAIL', '-d', '{"recipient":"a"}']);@@ -93,6 +449,192 @@ describe('CLI: composio manage tools execute', () => {);});+ layer(+ TestLive({+ baseConfigProvider: testConfigProvider,+ fixture: 'global-test-user-id',+ stdin: { isTTY: true, data: '' },+ toolkitsData: {+ tools: [+ {+ name: 'Send Email',+ slug: 'GMAIL_SEND_EMAIL',+ description: 'Send an email',+ tags: ['email'],+ available_versions: ['20260316_00'],+ input_parameters: {+ type: 'object',+ properties: {+ recipient_email: { type: 'string' },+ body: { type: 'string' },+ },+ },+ output_parameters: {+ type: 'object',+ properties: {+ message_id: { type: 'string' },+ },+ },+ },+ ],+ } satisfies TestLiveInput['toolkitsData'],+ })+ )('[Given] composio execute --dry-run [Then] it validates without executing the tool', it => {+ it.scoped('returns a dry-run summary instead of calling the tool', () =>+ Effect.gen(function* () {+ yield* cli([+ 'execute',+ 'GMAIL_SEND_EMAIL',+ '--dry-run',+ '-d',+ '{ recipient_email: "[email protected]", body: "Hello" }',+ ]);+ const lines = yield* MockConsole.getLines({ stripAnsi: true });+ const output = parseLastJson(lines) as unknown as {+ successful: boolean;+ dryRun: boolean;+ slug: string;+ schemaPath: string;+ schemaVersion: string | null;+ arguments: Record<string, unknown>;+ };++ expect(output.successful).toBe(true);+ expect(output.dryRun).toBe(true);+ expect(output.slug).toBe('GMAIL_SEND_EMAIL');+ expect(output.schemaVersion).toBeTruthy();+ expect(output.arguments).toEqual({ recipient_email: '[email protected]', body: 'Hello' });+ expect(output.schemaPath).toContain('/tool_definitions/GMAIL_SEND_EMAIL.json');+ })+ );+ });++ layer(+ TestLive({+ baseConfigProvider: testConfigProvider,+ fixture: 'global-test-user-id',+ toolkitsData: {+ tools: [+ {+ name: 'Send Email',+ slug: 'GMAIL_SEND_EMAIL',+ description: 'Send an email',+ tags: ['email'],+ available_versions: ['20260316_00'],+ input_parameters: {+ type: 'object',+ properties: {+ recipient_email: { type: 'string' },+ body: { type: 'string' },+ },+ },+ output_parameters: {+ type: 'object',+ properties: {+ message_id: { type: 'string' },+ },+ },+ },+ ],+ detailedToolkits: [+ {+ name: 'Gmail',+ slug: 'gmail',+ is_local_toolkit: false,+ composio_managed_auth_schemes: ['OAUTH2'],+ no_auth: false,+ meta: {+ description: 'Email service',+ categories: [],+ created_at: new Date('2024-05-03T11:44:32.061Z') as any,+ updated_at: new Date('2024-05-03T11:44:32.061Z') as any,+ available_versions: ['20260316_00'],+ tools_count: 36,+ triggers_count: 2,+ },+ auth_config_details: [],+ },+ ] satisfies ToolkitDetailed[],+ } satisfies TestLiveInput['toolkitsData'],+ })+ )('[Given] composio execute --get-schema [Then] it caches and prints the input schema', it => {+ it.scoped('fetches schema without executing the tool', () =>+ Effect.gen(function* () {+ const cacheDir = yield* setupCacheDir;+ const schemaPath = `${cacheDir}/tool_definitions/GMAIL_SEND_EMAIL.json`;++ yield* cli(['execute', 'GMAIL_SEND_EMAIL', '--get-schema']);+ const lines = yield* MockConsole.getLines({ stripAnsi: true });+ const output = parseLastJson(lines) as unknown as {+ slug: string;+ version: string | null;+ schemaPath: string;+ inputSchema: Record<string, unknown>;+ };++ expect(output.slug).toBe('GMAIL_SEND_EMAIL');+ expect(output.version).toBe('20260316_00');+ expect(output.schemaPath).toBe(schemaPath);+ expect(output.inputSchema).toEqual({+ type: 'object',+ properties: {+ recipient_email: { type: 'string' },+ body: { type: 'string' },+ },+ });+ expect(fs.existsSync(schemaPath)).toBe(true);+ })+ );+ });++ layer(+ TestLive({+ baseConfigProvider: testConfigProvider,+ fixture: 'global-test-user-id',+ stdin: { isTTY: true, data: '' },+ })+ )(+ '[Given] composio execute with a JS-style object literal [Then] it parses and executes successfully',+ it => {+ it.scoped('accepts object literal syntax for -d input', () =>+ Effect.gen(function* () {+ yield* cli(['execute', 'GMAIL_SEND_EMAIL', '-d', '{ recipient: "a", subject: "Hello" }']);+ const lines = yield* MockConsole.getLines({ stripAnsi: true });+ const output = parseLastJson(lines);++ expect(output.successful).toBe(true);+ expect(output.data.tool_slug).toBe('GMAIL_SEND_EMAIL');+ expect(output.data.arguments).toEqual({ recipient: 'a', subject: 'Hello' });+ })+ );+ }+ );++ layer(+ TestLive({+ baseConfigProvider: testConfigProvider,+ fixture: 'global-test-user-id',+ stdin: { isTTY: true, data: '' },+ })+ )('[Given] composio execute --perf-debug [Then] it is accepted on the root command', it => {+ it.scoped('parses and executes with perf debug enabled', () =>+ Effect.gen(function* () {+ yield* cli(['execute', '--perf-debug', 'GMAIL_SEND_EMAIL', '-d', '{"recipient":"a"}']);+ const lines = yield* MockConsole.getLines({ stripAnsi: true });+ const output = parseLastJson(lines);++ expect(output.successful).toBe(true);+ expect(output.data.tool_slug).toBe('GMAIL_SEND_EMAIL');+ }).pipe(+ Effect.ensuring(+ Effect.sync(() => {+ delete process.env.COMPOSIO_PERF_DEBUG;+ })+ )+ )+ );+ });+layer(TestLive({baseConfigProvider: testConfigProvider,@@ -104,7 +646,7 @@ describe('CLI: composio manage tools execute', () => {it => {it.scoped('executes without printing global test user diagnostics', () =>Effect.gen(function* () {- yield* cli(['manage', 'tools', 'execute', 'GMAIL_SEND_EMAIL', '-d', '{"recipient":"a"}']);+ yield* cli(['execute', 'GMAIL_SEND_EMAIL', '-d', '{"recipient":"a"}']);const lines = yield* MockConsole.getLines({ stripAnsi: true });const output = parseLastJson(lines);const text = lines.join('\n');@@ -215,7 +757,7 @@ describe('CLI: composio manage tools execute', () => {)('[Given] stdin is piped [Then] reads input from stdin', it => {it.scoped('reads stdin input', () =>Effect.gen(function* () {- yield* cli(['manage', 'tools', 'execute', 'GITHUB_GET_REPOS', '--user-id', 'default']);+ yield* cli(['execute', 'GITHUB_GET_REPOS']);const lines = yield* MockConsole.getLines({ stripAnsi: true });const output = parseLastJson(lines);@@ -242,23 +784,18 @@ describe('CLI: composio manage tools execute', () => {it.scoped('prints connected account tips for legacy slug', () =>Effect.gen(function* () {yield* cli([- 'manage',- 'tools','execute','GMAIL_CREATE_EMAIL_DRAFT',- '--user-id',- 'default','-d','{\"recipient\":\"[email protected]\"}',]).pipe(Effect.catchAll(() => Effect.void));const lines = yield* MockConsole.getLines({ stripAnsi: true });const output = lines.join('\n');- expect(output).toContain('No connected account found');+ expect(output).toContain('Run `composio link gmail`, then retry.');expect(output).toContain('Tips');- expect(output).toContain(- 'composio manage connected-accounts link gmail --user-id "<user-id>"'- );+ expect(output).toContain('composio link gmail');+ expect(output).not.toContain('COMPOSIO_MANAGE_CONNECTIONS');}));});@@ -288,23 +825,18 @@ describe('CLI: composio manage tools execute', () => {it.scoped('prints connection tips with toolkit name derived from tool slug', () =>Effect.gen(function* () {yield* cli([- 'manage',- 'tools','execute','GMAIL_CREATE_EMAIL_DRAFT',- '--user-id',- 'default','-d','{"recipient":"[email protected]"}',]).pipe(Effect.catchAll(() => Effect.void));const lines = yield* MockConsole.getLines({ stripAnsi: true });const output = lines.join('\n');- expect(output).toContain('No active connection');+ expect(output).toContain('Run `composio link gmail`, then retry.');expect(output).toContain('Tips');- expect(output).toContain(- 'composio manage connected-accounts link gmail --user-id "<user-id>"'- );+ expect(output).toContain('composio link gmail');+ expect(output).not.toContain('COMPOSIO_MANAGE_CONNECTIONS');}));});@@ -325,16 +857,7 @@ describe('CLI: composio manage tools execute', () => {)('[Given] custom Tool Router execute mock [Then] returns custom response', it => {it.scoped('flows through real ToolsExecutorLive with custom mock', () =>Effect.gen(function* () {- yield* cli([- 'manage',- 'tools',- 'execute',- 'GITHUB_STAR_REPO',- '--user-id',- 'default',- '-d',- '{"owner":"composio","repo":"composio"}',- ]);+ yield* cli(['execute', 'GITHUB_STAR_REPO', '-d', '{"owner":"composio","repo":"composio"}']);const lines = yield* MockConsole.getLines({ stripAnsi: true });const output = parseLastJson(lines);@@ -363,12 +886,8 @@ describe('CLI: composio manage tools execute', () => {it.scoped('prints actionable error details', () =>Effect.gen(function* () {yield* cli([- 'manage',- 'tools','execute','GMAIL_CREATE_EMAIL_DRAFT',- '--user-id',- 'default','-d','{\"recipient\":\"[email protected]\"}',]).pipe(Effect.catchAll(() => Effect.void));@@ -393,12 +912,8 @@ describe('CLI: composio manage tools execute', () => {it.scoped('prints object error message and details', () =>Effect.gen(function* () {yield* cli([- 'manage',- 'tools','execute','GMAIL_CREATE_EMAIL_DRAFT',- '--user-id',- 'default','-d','{\"recipient\":\"[email protected]\"}',]).pipe(Effect.catchAll(() => Effect.void));@@ -432,12 +947,8 @@ describe('CLI: composio manage tools execute', () => {it.scoped('shows error and logId for soft failure', () =>Effect.gen(function* () {yield* cli([- 'manage',- 'tools','execute','GMAIL_CREATE_EMAIL_DRAFT',- '--user-id',- 'default','-d','{\"recipient\":\"[email protected]\"}',]).pipe(Effect.catchAll(() => Effect.void));@@ -472,12 +983,8 @@ describe('CLI: composio manage tools execute', () => {it.scoped('shows error without logId for soft failure', () =>Effect.gen(function* () {yield* cli([- 'manage',- 'tools','execute','GMAIL_CREATE_EMAIL_DRAFT',- '--user-id',- 'default','-d','{\"recipient\":\"[email protected]\"}',]).pipe(Effect.catchAll(() => Effect.void));@@ -511,22 +1018,16 @@ describe('CLI: composio manage tools execute', () => {)('[Given] meta tool NoActiveConnection error [Then] does not suggest "link composio"', it => {it.scoped('omits connection tips for meta tool slugs', () =>Effect.gen(function* () {- yield* cli([- 'manage',- 'tools',- 'execute',- 'COMPOSIO_SEARCH_TOOLS',- '--user-id',- 'default',- '-d',- '{"query":"email"}',- ]).pipe(Effect.catchAll(() => Effect.void));+ yield* cli(['execute', 'COMPOSIO_SEARCH_TOOLS', '-d', '{"query":"email"}']).pipe(+ Effect.catchAll(() => Effect.void)+ );const lines = yield* MockConsole.getLines({ stripAnsi: true });const output = lines.join('\n');- expect(output).toContain('No active connection');+ expect(output).toContain('Link the required toolkit/app, then retry.');// Should NOT produce a misleading tip like "link composio"expect(output).not.toContain('link composio');+ expect(output).not.toContain('COMPOSIO_MANAGE_CONNECTIONS');}));});@@ -536,26 +1037,17 @@ describe('CLI: composio manage tools execute', () => {layer(TestLive({baseConfigProvider: testConfigProvider,+ fixture: 'global-test-user-id',stdin: { isTTY: true, data: '' },}))('[Given] -d with invalid JSON [Then] fails with parse error', it => {it.scoped('fails with invalid JSON error', () =>Effect.gen(function* () {- const result = yield* cli([- 'manage',- 'tools',- 'execute',- 'GMAIL_SEND_EMAIL',- '--user-id',- 'default',- '-d',- 'not-valid-json',- ]).pipe(Effect.catchAll(e => Effect.succeed(e)));-- expect(result).toBeDefined();- expect(result instanceof Error ? result.message : String(result)).toContain(- 'Invalid JSON input'+ const failure = yield* cli(['execute', 'GMAIL_SEND_EMAIL', '-d', 'not-valid-json']).pipe(+ Effect.flip,+ Effect.map(error => (error instanceof Error ? error.message : String(error))));+ expect(failure).toContain('Invalid JSON input');}));});@@ -563,26 +1055,17 @@ describe('CLI: composio manage tools execute', () => {layer(TestLive({baseConfigProvider: testConfigProvider,+ fixture: 'global-test-user-id',stdin: { isTTY: true, data: '' },}))('[Given] -d with JSON array [Then] fails with expected-object error', it => {it.scoped('fails with expected object error', () =>Effect.gen(function* () {- const result = yield* cli([- 'manage',- 'tools',- 'execute',- 'GMAIL_SEND_EMAIL',- '--user-id',- 'default',- '-d',- '[1,2,3]',- ]).pipe(Effect.catchAll(e => Effect.succeed(e)));-- expect(result).toBeDefined();- expect(result instanceof Error ? result.message : String(result)).toContain(- 'Expected a JSON object'+ const failure = yield* cli(['execute', 'GMAIL_SEND_EMAIL', '-d', '[1,2,3]']).pipe(+ Effect.flip,+ Effect.map(error => (error instanceof Error ? error.message : String(error))));+ expect(failure).toContain('Expected a JSON object');}));});@@ -590,26 +1073,17 @@ describe('CLI: composio manage tools execute', () => {layer(TestLive({baseConfigProvider: testConfigProvider,+ fixture: 'global-test-user-id',stdin: { isTTY: true, data: '' },}))('[Given] -d with JSON string [Then] fails with expected-object error', it => {it.scoped('fails with expected object error for string', () =>Effect.gen(function* () {- const result = yield* cli([- 'manage',- 'tools',- 'execute',- 'GMAIL_SEND_EMAIL',- '--user-id',- 'default',- '-d',- '"just a string"',- ]).pipe(Effect.catchAll(e => Effect.succeed(e)));-- expect(result).toBeDefined();- expect(result instanceof Error ? result.message : String(result)).toContain(- 'Expected a JSON object'+ const failure = yield* cli(['execute', 'GMAIL_SEND_EMAIL', '-d', '"just a string"']).pipe(+ Effect.flip,+ Effect.map(error => (error instanceof Error ? error.message : String(error))));+ expect(failure).toContain('Expected a JSON object');}));});@@ -631,7 +1105,7 @@ describe('CLI: composio manage tools execute', () => {)('[Given] no -d and TTY stdin [Then] defaults to empty object and executes', it => {it.scoped('defaults to {} when no data provided', () =>Effect.gen(function* () {- yield* cli(['manage', 'tools', 'execute', 'GMAIL_SEND_EMAIL', '--user-id', 'default']);+ yield* cli(['execute', 'GMAIL_SEND_EMAIL']);const lines = yield* MockConsole.getLines({ stripAnsi: true });const output = lines.join('\n');@@ -644,24 +1118,17 @@ describe('CLI: composio manage tools execute', () => {layer(TestLive({baseConfigProvider: testConfigProvider,+ fixture: 'global-test-user-id',stdin: { isTTY: false, data: '' },}))('[Given] empty piped stdin [Then] fails with parse error', it => {it.scoped('fails with error for empty stdin', () =>Effect.gen(function* () {- const result = yield* cli([- 'manage',- 'tools',- 'execute',- 'GMAIL_SEND_EMAIL',- '--user-id',- 'default',- ]).pipe(Effect.catchAll(e => Effect.succeed(e)));-- expect(result).toBeDefined();- expect(result instanceof Error ? result.message : String(result)).toContain(- 'Invalid JSON input'+ const failure = yield* cli(['execute', 'GMAIL_SEND_EMAIL']).pipe(+ Effect.flip,+ Effect.map(error => (error instanceof Error ? error.message : String(error))));+ expect(failure).toContain('Invalid JSON input');}));});@@ -697,16 +1164,7 @@ describe('CLI: composio manage tools execute', () => {);try {- yield* cli([- 'manage',- 'tools',- 'execute',- 'GMAIL_SEND_EMAIL',- '--user-id',- 'default',- '-d',- '{"recipient_email":"[email protected]"}',- ]);+ yield* cli(['execute', 'GMAIL_SEND_EMAIL', '-d', '{"recipient_email":"[email protected]"}']);const lines = yield* MockConsole.getLines({ stripAnsi: true });const output = parseLastJson(lines) as unknown as {data: { id: string; labelIds: string[]; threadId: string };diff --git a/ts/packages/cli/test/src/commands/tools/tools.info.cmd.test.ts b/ts/packages/cli/test/src/commands/tools/tools.info.cmd.test.tsindex eb0d2f868..a63a6f404 100644--- a/ts/packages/cli/test/src/commands/tools/tools.info.cmd.test.ts+++ b/ts/packages/cli/test/src/commands/tools/tools.info.cmd.test.ts@@ -49,25 +49,25 @@ const testConfigProvider = ConfigProvider.fromMap(new Map([['COMPOSIO_USER_API_KEY', 'test_api_key']])).pipe(extendConfigProvider);-describe('CLI: composio manage tools info', () => {+describe('CLI: composio tools info', () => {layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))('[Given] valid slug [Then] displays tool info',it => {- it.scoped('shows tool details with input/output schemas', () =>+ it.scoped('shows brief tool details and cached schema path', () =>Effect.gen(function* () {- yield* cli(['manage', 'tools', 'info', 'GMAIL_SEND_EMAIL']);+ yield* cli(['tools', 'info', 'GMAIL_SEND_EMAIL']);const lines = yield* MockConsole.getLines({ stripAnsi: true });const output = lines.join('\n');expect(output).toContain('Send Email');expect(output).toContain('GMAIL_SEND_EMAIL');- expect(output).toContain('Input Parameters');- expect(output).toContain('recipient');- expect(output).toContain('required');- expect(output).toContain('Output Parameters');- expect(output).toContain('message_id');- // Verify next-step hint includes derived toolkit slug- expect(output).toContain('composio manage tools list --toolkits "gmail"');+ expect(output).toContain('Schema Cache');+ expect(output).toContain('/tool_definitions/GMAIL_SEND_EMAIL.json');+ expect(output).toContain(+ "jq '{required: (.inputSchema.required // []), keys: (.inputSchema.properties | keys)}'"+ );+ expect(output).toContain('composio execute "GMAIL_SEND_EMAIL" -d');+ expect(output).toContain('--dry-run');}));}@@ -78,7 +78,7 @@ describe('CLI: composio manage tools info', () => {it => {it.scoped('shows missing argument warning', () =>Effect.gen(function* () {- yield* cli(['manage', 'tools', 'info']);+ yield* cli(['tools', 'info']);const lines = yield* MockConsole.getLines({ stripAnsi: true });const output = lines.join('\n');@@ -93,7 +93,7 @@ describe('CLI: composio manage tools info', () => {it => {it.scoped('shows not found with suggestions', () =>Effect.gen(function* () {- yield* cli(['manage', 'tools', 'info', 'NONEXISTENT_TOOL']);+ yield* cli(['tools', 'info', 'NONEXISTENT_TOOL']);const lines = yield* MockConsole.getLines({ stripAnsi: true });const output = lines.join('\n');@@ -106,7 +106,7 @@ describe('CLI: composio manage tools info', () => {layer(TestLive())('[Given] no API key [Then] warns user to login', it => {it.scoped('warns user to login', () =>Effect.gen(function* () {- yield* cli(['manage', 'tools', 'info', 'GMAIL_SEND_EMAIL']);+ yield* cli(['tools', 'info', 'GMAIL_SEND_EMAIL']);const lines = yield* MockConsole.getLines({ stripAnsi: true });const output = lines.join('\n');diff --git a/ts/packages/cli/test/src/commands/tools/tools.list.cmd.test.ts b/ts/packages/cli/test/src/commands/tools/tools.list.cmd.test.tsindex d14af7413..a275e7341 100644--- a/ts/packages/cli/test/src/commands/tools/tools.list.cmd.test.ts+++ b/ts/packages/cli/test/src/commands/tools/tools.list.cmd.test.ts@@ -55,30 +55,31 @@ const testConfigProvider = ConfigProvider.fromMap(new Map([['COMPOSIO_USER_API_KEY', 'test_api_key']])).pipe(extendConfigProvider);-describe('CLI: composio manage tools list', () => {+describe('CLI: composio tools list', () => {layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))(- '[Given] no flags [Then] lists all tools',+ '[Given] toolkit "gmail" [Then] lists gmail tools',it => {it.scoped('lists all tools', () =>Effect.gen(function* () {- yield* cli(['manage', 'tools', 'list']);+ yield* cli(['tools', 'list', 'gmail']);const lines = yield* MockConsole.getLines({ stripAnsi: true });const output = lines.join('\n');expect(output).toContain('GMAIL_SEND_EMAIL');- expect(output).toContain('SLACK_SEND_MESSAGE');- expect(output).toContain('Listing 3 tools');+ expect(output).toContain('GMAIL_CREATE_DRAFT');+ expect(output).not.toContain('SLACK_SEND_MESSAGE');+ expect(output).toContain('Listing 2 tools');}));});layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))(- '[Given] --toolkits "gmail" [Then] lists only gmail tools',+ '[Given] toolkit "gmail" [Then] lists only gmail tools',it => {it.scoped('filters by toolkit', () =>Effect.gen(function* () {- yield* cli(['manage', 'tools', 'list', '--toolkits', 'gmail']);+ yield* cli(['tools', 'list', 'gmail']);const lines = yield* MockConsole.getLines({ stripAnsi: true });const output = lines.join('\n');@@ -96,12 +97,11 @@ describe('CLI: composio manage tools list', () => {it => {it.scoped('filters by search query', () =>Effect.gen(function* () {- yield* cli(['manage', 'tools', 'list', '--query', 'send']);+ yield* cli(['tools', 'list', 'gmail', '--query', 'send']);const lines = yield* MockConsole.getLines({ stripAnsi: true });const output = lines.join('\n');expect(output).toContain('GMAIL_SEND_EMAIL');- expect(output).toContain('SLACK_SEND_MESSAGE');expect(output).not.toContain('GMAIL_CREATE_DRAFT');}));@@ -113,7 +113,7 @@ describe('CLI: composio manage tools list', () => {it => {it.scoped('respects limit', () =>Effect.gen(function* () {- yield* cli(['manage', 'tools', 'list', '--limit', '2']);+ yield* cli(['tools', 'list', 'gmail', '--limit', '2']);const lines = yield* MockConsole.getLines({ stripAnsi: true });const output = lines.join('\n');@@ -126,7 +126,7 @@ describe('CLI: composio manage tools list', () => {layer(TestLive())('[Given] no API key [Then] warns user to login', it => {it.scoped('warns user to login', () =>Effect.gen(function* () {- yield* cli(['manage', 'tools', 'list']);+ yield* cli(['tools', 'list', 'gmail']);const lines = yield* MockConsole.getLines({ stripAnsi: true });const output = lines.join('\n');@@ -140,7 +140,7 @@ describe('CLI: composio manage tools list', () => {it => {it.scoped('shows no tools found', () =>Effect.gen(function* () {- yield* cli(['manage', 'tools', 'list']);+ yield* cli(['tools', 'list', 'gmail']);const lines = yield* MockConsole.getLines({ stripAnsi: true });const output = lines.join('\n');@@ -155,7 +155,7 @@ describe('CLI: composio manage tools list', () => {it => {it.scoped('filters by tag', () =>Effect.gen(function* () {- yield* cli(['manage', 'tools', 'list', '--tags', 'email']);+ yield* cli(['tools', 'list', 'gmail', '--tags', 'email']);const lines = yield* MockConsole.getLines({ stripAnsi: true });const output = lines.join('\n');@@ -168,11 +168,11 @@ describe('CLI: composio manage tools list', () => {);layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))(- '[Given] --toolkits "nonexistent" [Then] shows no tools found with hint',+ '[Given] toolkit "nonexistent" [Then] shows no tools found with hint',it => {it.scoped('shows hint about verifying toolkit slug', () =>Effect.gen(function* () {- yield* cli(['manage', 'tools', 'list', '--toolkits', 'nonexistent']);+ yield* cli(['tools', 'list', 'nonexistent']);const lines = yield* MockConsole.getLines({ stripAnsi: true });const output = lines.join('\n');diff --git a/ts/packages/cli/test/src/commands/tools/tools.search.cmd.test.ts b/ts/packages/cli/test/src/commands/tools/tools.search.cmd.test.tsindex 330667b46..a9f88e6fd 100644--- a/ts/packages/cli/test/src/commands/tools/tools.search.cmd.test.ts+++ b/ts/packages/cli/test/src/commands/tools/tools.search.cmd.test.ts@@ -53,11 +53,11 @@ const testLiveOptions = {fixture: 'global-test-user-id' as const,};-describe('CLI: composio manage tools search', () => {+describe('CLI: composio search', () => {layer(TestLive(testLiveOptions))('[Given] query "send" [Then] returns matching tools', it => {it.scoped('returns matching tools', () =>Effect.gen(function* () {- yield* cli(['manage', 'tools', 'search', 'send']);+ yield* cli(['search', 'send']);const lines = yield* MockConsole.getLines({ stripAnsi: true });const output = lines.join('\n');@@ -74,7 +74,7 @@ describe('CLI: composio manage tools search', () => {it => {it.scoped('shows not found message', () =>Effect.gen(function* () {- yield* cli(['manage', 'tools', 'search', 'nonexistent_query']);+ yield* cli(['search', 'nonexistent_query']);const lines = yield* MockConsole.getLines({ stripAnsi: true });const output = lines.join('\n');@@ -89,7 +89,7 @@ describe('CLI: composio manage tools search', () => {it => {it.scoped('scopes search to toolkit', () =>Effect.gen(function* () {- yield* cli(['manage', 'tools', 'search', 'send', '--toolkits', 'gmail']);+ yield* cli(['search', 'send', '--toolkits', 'gmail']);const lines = yield* MockConsole.getLines({ stripAnsi: true });const output = lines.join('\n');const humanOutput = output.split('\n{')[0] ?? output;@@ -107,7 +107,7 @@ describe('CLI: composio manage tools search', () => {it => {it.scoped('prints full search response with CTA for jq', () =>Effect.gen(function* () {- yield* cli(['manage', 'tools', 'search', 'send']);+ yield* cli(['search', 'send']);const lines = yield* MockConsole.getLines({ stripAnsi: true });const output = lines.join('\n');@@ -119,8 +119,8 @@ describe('CLI: composio manage tools search', () => {expect(output).toContain('"CTA"');expect(output).toContain('"Execute a tool"');expect(output).toContain('"Connect a user account"');- expect(output).toContain('composio manage tools execute');- expect(output).toContain('composio manage connected-accounts link gmail');+ expect(output).toContain('composio execute');+ expect(output).toContain('composio link gmail');}));}@@ -157,7 +157,7 @@ describe('CLI: composio manage tools search', () => {},});- yield* cli(['manage', 'tools', 'search', 'send']).pipe(Effect.provide(live));+ yield* cli(['search', 'send']).pipe(Effect.provide(live));const lines = yield* MockConsole.getLines({ stripAnsi: true });const output = lines.join('\n');@@ -168,16 +168,12 @@ describe('CLI: composio manage tools search', () => {const executeCta = cta.find(c => c.action === 'Execute a tool');expect(executeCta).toBeTruthy();- expect(executeCta!.command).toContain(- 'composio manage tools execute "GMAIL_SEND_EMAIL" --user-id "<user-id>"'- );+ expect(executeCta!.command).toContain('composio execute "GMAIL_SEND_EMAIL"');expect(executeCta!.command).toMatch(/-d '\{"to":"","subject":"","body":""\}'/);const linkCta = cta.find(c => c.action === 'Connect a user account');expect(linkCta).toBeTruthy();- expect(linkCta!.command).toBe(- 'composio manage connected-accounts link gmail --user-id "<user-id>"'- );+ expect(linkCta!.command).toBe('composio link gmail');}));}@@ -188,7 +184,7 @@ describe('CLI: composio manage tools search', () => {it => {it.scoped('CTA uses -d "{}" when no schema properties', () =>Effect.gen(function* () {- yield* cli(['manage', 'tools', 'search', 'send']);+ yield* cli(['search', 'send']);const lines = yield* MockConsole.getLines({ stripAnsi: true });const output = lines.join('\n');@@ -275,9 +271,7 @@ describe('CLI: composio manage tools search', () => {},});- yield* cli(['manage', 'tools', 'search', 'send', '--toolkits', 'gmail,outlook']).pipe(- Effect.provide(live)- );+ yield* cli(['search', 'send', '--toolkits', 'gmail,outlook']).pipe(Effect.provide(live));expect(createParams?.toolkits).toEqual({ enable: ['gmail', 'outlook'] });expect(searchParams?.queries[0]?.use_case).toBe('send');@@ -342,19 +336,15 @@ describe('CLI: composio manage tools search', () => {},});- yield* cli(['manage', 'tools', 'search', 'send email']).pipe(Effect.provide(live));+ yield* cli(['search', 'send email']).pipe(Effect.provide(live));const lines = yield* MockConsole.getLines({ stripAnsi: true });const output = lines.join('\n');expect(output).toContain('Plan:');expect(output).toContain('1. Collect recipient details');- expect(output).toContain('Hints:');- expect(output).toContain(- `composio manage tools execute "GMAIL_SEND_EMAIL" --user-id "<user-id>" -d "{}"`- );- expect(output).toContain(- `composio manage connected-accounts link <toolkit> --user-id "<user-id>"`- );+ expect(output).toContain('Execute a tool:');+ expect(output).toContain(`composio execute "GMAIL_SEND_EMAIL" -d "{}"`);+ expect(output).toContain(`composio link <toolkit>`);}));}@@ -363,7 +353,7 @@ describe('CLI: composio manage tools search', () => {layer(TestLive())('[Given] no API key [Then] warns user to login', it => {it.scoped('warns user to login', () =>Effect.gen(function* () {- yield* cli(['manage', 'tools', 'search', 'send']);+ yield* cli(['search', 'send']);const lines = yield* MockConsole.getLines({ stripAnsi: true });const output = lines.join('\n');@@ -373,7 +363,7 @@ describe('CLI: composio manage tools search', () => {});layer(TestLive(testLiveOptions))(- '[Given] consumer search with explicit --user-id [Then] it still uses resolved consumer user id',+ '[Given] consumer search [Then] it uses the resolved consumer user id',it => {it.scoped('uses consumer user id from the resolved project context', () =>Effect.gen(function* () {@@ -393,9 +383,7 @@ describe('CLI: composio manage tools search', () => {},});- yield* cli(['manage', 'tools', 'search', 'send', '--user-id', 'alice']).pipe(- Effect.provide(live)- );+ yield* cli(['search', 'send']).pipe(Effect.provide(live));expect(createParams?.user_id).toBe('consumer-user-org_test');})@@ -412,7 +400,7 @@ describe('CLI: composio manage tools search', () => {)('[Given] no explicit --user-id [Then] consumer search does not require one', it => {it.scoped('runs without printing global test user diagnostics', () =>Effect.gen(function* () {- yield* cli(['manage', 'tools', 'search', 'send']);+ yield* cli(['search', 'send']);const lines = yield* MockConsole.getLines({ stripAnsi: true });const output = lines.join('\n');@@ -423,9 +411,9 @@ describe('CLI: composio manage tools search', () => {});layer(TestLive(testLiveOptions))(- '[Given] composio search alias [Then] works like composio manage tools search',+ '[Given] composio search [Then] runs the root search flow',it => {- it.scoped('alias expands to tools search', () =>+ it.scoped('search returns matching tools', () =>Effect.gen(function* () {yield* cli(['search', 'send']);const lines = yield* MockConsole.getLines({ stripAnsi: true });diff --git a/ts/packages/cli/test/src/commands/triggers/triggers.listen.cmd.test.ts b/ts/packages/cli/test/src/commands/triggers/triggers.listen.cmd.test.tsindex b07dbb197..5bd10a4e9 100644--- a/ts/packages/cli/test/src/commands/triggers/triggers.listen.cmd.test.ts+++ b/ts/packages/cli/test/src/commands/triggers/triggers.listen.cmd.test.ts@@ -139,10 +139,10 @@ describe('CLI: composio manage triggers listen', () => {events: [mockV3TriggerEvent],},})- )('[Given] composio listen alias [Then] works like composio manage triggers listen', it => {- it.scoped('alias expands to triggers listen', () =>+ )('[Given] composio dev listen [Then] works like composio manage triggers listen', it => {+ it.scoped('dev listen expands to triggers listen', () =>Effect.gen(function* () {- yield* cli(['listen', '--max-events', '1']);+ yield* cli(['dev', 'listen', '--max-events', '1']);const lines = yield* MockConsole.getLines({ stripAnsi: true });const output = lines.join('\n');diff --git a/ts/packages/cli/test/src/services/command-hints.test.ts b/ts/packages/cli/test/src/services/command-hints.test.tsnew file mode 100644index 000000000..b9b8d4715--- /dev/null+++ b/ts/packages/cli/test/src/services/command-hints.test.ts@@ -0,0 +1,39 @@+import { describe, expect, it } from 'vitest';+import {+ COMMAND_HINTS,+ commandHintExample,+ commandHintLinks,+ renderCommandHintGraph,+ type CommandHintId,+} from 'src/services/command-hints';++describe('command-hints', () => {+ it('has no dangling linked command ids', () => {+ const ids = new Set(Object.keys(COMMAND_HINTS) as CommandHintId[]);++ for (const id of ids) {+ for (const linkedId of commandHintLinks(id)) {+ expect(ids.has(linkedId)).toBe(true);+ }+ }+ });++ it('renders examples from the registry', () => {+ expect(commandHintExample('root.tools.list')).toContain('composio tools list');+ expect(commandHintExample('root.execute', { slug: 'GMAIL_SEND_EMAIL' })).toContain(+ 'GMAIL_SEND_EMAIL'+ );+ expect(commandHintExample('root.execute.getSchema', { slug: 'GMAIL_SEND_EMAIL' })).toContain(+ '--get-schema'+ );+ expect(commandHintExample('dev.logs.tools', { logId: 'log_123' })).toContain('log_123');+ });++ it('serializes the graph with nodes and links', () => {+ const graph = renderCommandHintGraph();+ expect(graph.nodes.length).toBeGreaterThan(0);+ expect(graph.nodes.find(node => node.id === 'root.execute')).toMatchObject({+ id: 'root.execute',+ });+ });+});