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): add proxy execute (#2995)
Rahul Tarakae08b37f9103
diff --git a/.changeset/vast-showers-lose.md b/.changeset/vast-showers-lose.mdnew file mode 100644index 000000000..63f94bd78--- /dev/null+++ b/.changeset/vast-showers-lose.md@@ -0,0 +1,10 @@+---+'@composio/cli': patch+---++- Make top-level `composio search`, `composio link`, and `composio execute` consumer-only+- Keep developer-scoped usage under `composio manage ...`+- Remove developer-only flags from root help and add short related-command hints+- Use `consumer_user_id` from consumer project resolve for consumer flows+- Execute: Default to empty object `{}` when no -d/--data or piped stdin provided+- Search CTA: Use `-d "{}"` for tools with no schema properties (shell-safe)diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 23cf01095..67eb4eff6 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@@ -1109,6 +1109,9 @@ importers:ts-morph:specifier: ^26.0.0version: 26.0.0+ zod:+ specifier: 'catalog:'+ version: 4.3.6devDependencies:'@effect/eslint-plugin':specifier: 'catalog:'@@ -1324,7 +1327,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:*@@ -7563,43 +7566,26 @@ 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])- 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])+ '@llamaindex/workflow-core': 1.3.3(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])([email protected])transitivePeerDependencies:- '@modelcontextprotocol/sdk'- hono@@ -8533,14 +8519,6 @@ 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@@ -8570,7 +8548,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:@@ -9937,34 +9915,12 @@ 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]):- 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])- '@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-+ [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])([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.13lodash: 4.17.23@@ -10244,11 +10200,6 @@ 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@@ -11346,7 +11297,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 a2a5143e3..3134d34c0 100644--- a/ts/packages/cli/package.json+++ b/ts/packages/cli/package.json@@ -88,7 +88,8 @@"semver": "^7.7.2","source-map-js": "^1.2.1","superjson": "^2.2.2",- "ts-morph": "^26.0.0"+ "ts-morph": "^26.0.0",+ "zod": "catalog:"},"gitHead": "4fae6e54d5c150fba955cc5fa314281da5a1e064","module": "./dist/bin.mjs",diff --git a/ts/packages/cli/src/bin.ts b/ts/packages/cli/src/bin.tsindex 55f67e2ed..e729dbddc 100644--- a/ts/packages/cli/src/bin.ts+++ b/ts/packages/cli/src/bin.ts@@ -28,6 +28,7 @@ import { ProjectEnvironmentDetector } from 'src/services/project-environment-detimport { CommandRunner } from 'src/services/command-runner';import { StdinLive } from 'src/services/stdin';import { showUpdateNotice, checkForUpdateInBackground } from 'src/services/update-check';+import { mapOnlyComposioOverrideError } from 'src/services/composio-error-overrides';/*** Concrete Effect layer compositions for the Composio CLI runtime.@@ -188,6 +189,9 @@ checkForUpdateInBackground();*/runWithArgs.pipe(Effect.scoped,+ Effect.mapError(error =>+ ValidationError.isValidationError(error) ? error : mapOnlyComposioOverrideError({ error })+ ),// @effect/cli already prints validation errors (missing args, invalid flags, etc.)// via its own printDocs before re-failing. Swallow the re-thrown error to avoid// routing it through the generic error box which would dump raw JSON.diff --git a/ts/packages/cli/src/commands/artifacts.cmd.ts b/ts/packages/cli/src/commands/artifacts.cmd.tsnew file mode 100644index 000000000..e15e7f544--- /dev/null+++ b/ts/packages/cli/src/commands/artifacts.cmd.ts@@ -0,0 +1,23 @@+import process from 'node:process';+import { Command } from '@effect/cli';+import { Effect, Option } from 'effect';+import { resolveCliSessionArtifacts } from 'src/services/cli-session-artifacts';++const cwdCmd = Command.make('cwd').pipe(+ Command.withDescription('Print the current cwd-scoped session artifact directory.'),+ Command.withHandler(() =>+ Effect.gen(function* () {+ const artifacts = yield* resolveCliSessionArtifacts();+ const directoryPath = Option.match(artifacts, {+ onNone: () => '/tmp/composio',+ onSome: value => value.directoryPath,+ });+ process.stdout.write(`${directoryPath}\n`);+ })+ )+);++export const artifactsCmd = Command.make('artifacts').pipe(+ Command.withDescription('Inspect session artifact directories.'),+ Command.withSubcommands([cwdCmd])+);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 f04fd568e..b59219f66 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@@ -14,6 +14,7 @@ import {formatResolveCommandProjectError,} from 'src/services/command-project';import { invalidateConsumerConnectedToolkitsCache } from 'src/services/consumer-short-term-cache';+import { appendCliSessionHistory } from 'src/services/cli-session-artifacts';const toolkit = Args.text({ name: 'toolkit' }).pipe(Args.withDescription('Toolkit slug to link (e.g. "github", "gmail")'),@@ -357,8 +358,32 @@ const runConnectedAccountsLink = (params: {2));+ yield* appendCliSessionHistory({+ orgId: resolvedProject.projectType === 'CONSUMER' ? resolvedProject.orgId : undefined,+ consumerUserId:+ resolvedProject.projectType === 'CONSUMER' ? resolvedProject.consumerUserId : undefined,+ entry: {+ command: 'link',+ status: 'pending',+ toolkit: toolkitSlug,+ connectedAccountId: connAccountId,+ redirectUrl,+ },+ }).pipe(Effect.catchAll(() => Effect.void));} else {yield* waitForActiveConnection(ui, repo, connAccountId, redirectUrl, params.noBrowser);+ yield* appendCliSessionHistory({+ orgId: resolvedProject.projectType === 'CONSUMER' ? resolvedProject.orgId : undefined,+ consumerUserId:+ resolvedProject.projectType === 'CONSUMER' ? resolvedProject.consumerUserId : undefined,+ entry: {+ command: 'link',+ status: 'active',+ toolkit: toolkitSlug,+ connectedAccountId: connAccountId,+ redirectUrl,+ },+ }).pipe(Effect.catchAll(() => Effect.void));}});@@ -378,11 +403,16 @@ export const connectedAccountsCmd$Link = Command.make().pipe(Command.withDescription([- 'Link an external account via OAuth redirect.',+ 'Connect an external account (GitHub, Gmail, Slack, etc.) so tools can act on your behalf.',+ 'Opens a browser for OAuth authorization and waits for confirmation.','',- 'Related:',- ' composio search "<query>"',- " composio execute <slug> -d '{}'",+ 'Examples:',+ ' composio link github',+ ' composio link gmail --no-browser Print the auth URL instead of opening it',+ '',+ 'See also:',+ ' composio search "<query>" Find tools to use after linking',+ " composio execute <slug> -d '{ ... }' Execute a tool with your linked account",].join('\n')));@@ -403,11 +433,16 @@ export const rootConnectedAccountsCmd$Link = Command.make().pipe(Command.withDescription([- 'Link an external account via OAuth redirect.',+ 'Connect an external account (GitHub, Gmail, Slack, etc.) so tools can act on your behalf.',+ 'Opens a browser for OAuth authorization and waits for confirmation.',+ '',+ 'Examples:',+ ' composio link github',+ ' composio link gmail --no-browser Print the auth URL instead of opening it','',- 'Related:',- ' composio search "<query>"',- " composio execute <slug> -d '{}'",+ 'See also:',+ ' composio search "<query>" Find tools to use after linking',+ " composio execute <slug> -d '{ ... }' Execute a tool with your linked account",].join('\n')));diff --git a/ts/packages/cli/src/commands/index.ts b/ts/packages/cli/src/commands/index.tsindex a207bd38c..b20270875 100644--- a/ts/packages/cli/src/commands/index.ts+++ b/ts/packages/cli/src/commands/index.ts@@ -10,12 +10,14 @@ import { whoamiCmd } from './whoami.cmd';import { loginCmd } from './login.cmd';import { logoutCmd } from './logout.cmd';import { runCmd } from './run.cmd';+import { proxyCmd } from './proxy.cmd';+import { artifactsCmd } from './artifacts.cmd';import { installCmd } from './install.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 { printRootHelp, matchSubcommandHelp, printSubcommandHelp } 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';@@ -24,6 +26,7 @@ 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 { detectMaster } from 'src/services/master-detector';import {formatResolveCommandProjectError,resolveCommandProject,@@ -37,6 +40,8 @@ const $cmd = $defaultCmd.pipe(loginCmd,logoutCmd,runCmd,+ proxyCmd,+ artifactsCmd,installCmd,devCmd,rootToolsCmd,@@ -171,6 +176,11 @@ const isDebugApiInfo = (argv: ReadonlyArray<string>): boolean => {return args.length === 2 && args[0] === 'debug' && args[1] === 'api-info';};+const isDebugWhoIsMyMaster = (argv: ReadonlyArray<string>): boolean => {+ const args = argv.slice(2);+ return args.length === 2 && args[0] === 'debug' && args[1] === 'who-is-my-master';+};+export const runWithConfig = Effect.gen(function* () {const version = yield* getVersion;const run = Command.run($cmd, {@@ -184,6 +194,10 @@ export const runWithConfig = Effect.gen(function* () {if (isRootHelp(normalizedArgv)) {return printRootHelp();}+ const subHelp = matchSubcommandHelp(normalizedArgv);+ if (subHelp) {+ return printSubcommandHelp(subHelp);+ }if (isGenerateGraph(normalizedArgv)) {return Effect.sync(() => {process.stdout.write(`${JSON.stringify(renderCommandHintGraph(), null, 2)}\n`);@@ -227,6 +241,11 @@ export const runWithConfig = Effect.gen(function* () {});});}+ if (isDebugWhoIsMyMaster(normalizedArgv)) {+ return Effect.sync(() => {+ process.stdout.write(`${JSON.stringify({ master: detectMaster() }, null, 2)}\n`);+ });+ }const executeHelpSlug = parseExecuteInputHelpSlug(normalizedArgv);if (executeHelpSlug) {return showToolsExecuteInputHelp(executeHelpSlug);diff --git a/ts/packages/cli/src/commands/proxy.cmd.ts b/ts/packages/cli/src/commands/proxy.cmd.tsnew file mode 100644index 000000000..1db3a4391--- /dev/null+++ b/ts/packages/cli/src/commands/proxy.cmd.ts@@ -0,0 +1,350 @@+import { Args, Command, Options } from '@effect/cli';+import { Effect, Option } from 'effect';+import type {+ SessionProxyExecuteParams,+ SessionProxyExecuteResponse,+} from '@composio/client/resources/tool-router/session';+import { requireAuth } from 'src/effects/require-auth';+import { resolveOptionalTextInput } from 'src/effects/resolve-optional-text-input';+import { resolveToolRouterSession } from 'src/effects/create-tool-router-session';+import {+ getFreshConsumerConnectedToolkitsFromCache,+ refreshConsumerConnectedToolkitsCache,+} from 'src/services/consumer-short-term-cache';+import { TerminalUI } from 'src/services/terminal-ui';+import { ComposioClientSingleton } from 'src/services/composio-clients';+import {+ resolveCommandProject,+ formatResolveCommandProjectError,+} from 'src/services/command-project';+import {+ ComposioNoActiveConnectionError,+ mapComposioError,+} from 'src/services/composio-error-overrides';+import { parseJsonIsh } from 'src/utils/parse-json-ish';++const endpoint = Args.text({ name: 'url' }).pipe(+ Args.withDescription('Absolute or relative API endpoint to call through proxy execute.')+);++const toolkit = Options.text('toolkit').pipe(+ Options.withAlias('t'),+ Options.withDescription('Toolkit slug whose connected account should be used')+);++const method = Options.text('method').pipe(+ Options.withAlias('X'),+ Options.withDefault('GET'),+ Options.withDescription('HTTP method, curl-style (GET, POST, PUT, DELETE, PATCH)')+);++const headers = Options.text('header').pipe(+ Options.withAlias('H'),+ Options.withDescription('Header in "Name: value" format. Repeat for multiple headers.'),+ Options.repeated+);++const data = Options.text('data').pipe(+ Options.withAlias('d'),+ Options.withDescription('Request body as raw text, JSON, @file, or - for stdin'),+ Options.optional+);++const skipConnectionCheck = Options.boolean('skip-connection-check').pipe(+ Options.withDefault(false),+ Options.withDescription(+ 'Skip the short-lived linked-account fail-fast check if you just connected an account'+ )+);++type ProxyMethod = Extract<+ SessionProxyExecuteParams['method'],+ 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH'+>;++const SUPPORTED_PROXY_METHODS = [+ 'GET',+ 'POST',+ 'PUT',+ 'DELETE',+ 'PATCH',+] as const satisfies ReadonlyArray<ProxyMethod>;++export const normalizeProxyMethod = (value: string): ProxyMethod => {+ const normalized = value.trim().toUpperCase();+ if (!SUPPORTED_PROXY_METHODS.includes(normalized as ProxyMethod)) {+ throw new Error('Unsupported method. Use one of GET, POST, PUT, DELETE, PATCH.');+ }+ return normalized as ProxyMethod;+};++export const parseProxyHeader = (value: string): { name: string; value: string } => {+ const idx = value.indexOf(':');+ if (idx <= 0) {+ throw new Error(`Invalid header "${value}". Use "Name: value".`);+ }++ const name = value.slice(0, idx).trim();+ const headerValue = value.slice(idx + 1).trim();+ if (!name) {+ throw new Error(`Invalid header "${value}". Missing header name.`);+ }+ return { name, value: headerValue };+};++const resolveBodyInput = (input: Option.Option<string>) => resolveOptionalTextInput(input);++export const parseProxyBody = (raw: string): unknown => {+ try {+ return parseJsonIsh(raw);+ } catch {+ return raw;+ }+};++const formatProxyOutput = (+ result: Pick<SessionProxyExecuteResponse, 'status' | 'data' | 'headers' | 'binary_data'>+) => {+ if (result.binary_data) {+ return JSON.stringify(+ {+ status: result.status ?? null,+ headers: result.headers ?? {},+ binary_data: result.binary_data,+ },+ null,+ 2+ );+ }++ if (typeof result.data === 'string') {+ return result.data;+ }++ if (result.data === undefined || result.data === null) {+ return '';+ }++ return JSON.stringify(result.data, null, 2);+};++const formatProxyErrorOutput = (params: {+ readonly error: string;+ readonly toolkit: string;+ readonly endpoint: string;+ readonly slug?: string;+}) =>+ JSON.stringify(+ {+ successful: false,+ error: params.error,+ toolkit: params.toolkit,+ endpoint: params.endpoint,+ slug: params.slug ?? null,+ },+ null,+ 2+ );++const handleProxyExecutionError = (params: {+ readonly ui: TerminalUI;+ readonly error: unknown;+ readonly toolkit: string;+ readonly endpoint: string;+}) =>+ Effect.gen(function* () {+ const mapped = mapComposioError({+ error: params.error,+ toolkit: params.toolkit,+ });++ if (mapped.normalized instanceof ComposioNoActiveConnectionError) {+ yield* params.ui.log.error(mapped.message);+ yield* params.ui.note(+ [+ `Link the toolkit first: composio link ${params.toolkit}`,+ 'Then retry the proxy call.',+ ].join('\n'),+ 'Tips'+ );+ const output = formatProxyErrorOutput({+ error: mapped.message,+ toolkit: params.toolkit,+ endpoint: params.endpoint,+ slug: mapped.slugValue,+ });+ yield* params.ui.output(output);+ return yield* Effect.fail(mapped.normalized);+ }++ yield* params.ui.log.error(mapped.message);+ const output = formatProxyErrorOutput({+ error: mapped.message,+ toolkit: params.toolkit,+ endpoint: params.endpoint,+ slug: mapped.slugValue,+ });+ yield* params.ui.output(output);+ return yield* Effect.fail(mapped.normalized);+ });++const runProxyConnectedToolkitFailFast = (params: {+ readonly toolkit: string;+ readonly ui: TerminalUI;+ readonly resolvedProject: {+ readonly projectType: 'CONSUMER' | 'DEVELOPER';+ readonly orgId: string;+ };+ readonly resolvedUserId: string;+ readonly endpoint: string;+ readonly skipConnectionCheck: boolean;+}) =>+ Effect.gen(function* () {+ if (params.skipConnectionCheck) return;+ if (params.resolvedProject.projectType !== 'CONSUMER') return;++ yield* refreshConsumerConnectedToolkitsCache({+ orgId: params.resolvedProject.orgId,+ consumerUserId: params.resolvedUserId,+ }).pipe(+ Effect.catchAll(() => Effect.void),+ Effect.forkDaemon,+ Effect.asVoid+ );++ const cachedToolkits = yield* getFreshConsumerConnectedToolkitsFromCache({+ orgId: params.resolvedProject.orgId,+ consumerUserId: params.resolvedUserId,+ });++ if (Option.isSome(cachedToolkits) && !cachedToolkits.value.includes(params.toolkit)) {+ const message = `Toolkit "${params.toolkit}" is not connected for this user (cached within the last 5 minutes). If you just connected the account, use --skip-connection-check.`;+ yield* params.ui.log.error(message);+ yield* params.ui.note(+ [+ `Link the toolkit first: composio link ${params.toolkit}`,+ 'Then retry the proxy call.',+ ].join('\n'),+ 'Tips'+ );+ yield* params.ui.output(+ JSON.stringify(+ {+ successful: false,+ error: message,+ toolkit: params.toolkit,+ endpoint: params.endpoint,+ },+ null,+ 2+ )+ );+ return yield* Effect.fail(new Error(message));+ }+ });++export const proxyCmd = Command.make('proxy', {+ endpoint,+ toolkit,+ method,+ headers,+ data,+ skipConnectionCheck,+}).pipe(+ Command.withDescription(+ [+ 'curl-like access to any toolkit API through Composio using your linked account.',+ 'Composio handles authentication — just provide the full URL and toolkit.',+ '',+ 'Examples:',+ ' composio proxy https://gmail.googleapis.com/gmail/v1/users/me/profile --toolkit gmail',+ ` composio proxy https://gmail.googleapis.com/gmail/v1/users/me/drafts --toolkit gmail \\`,+ ` -X POST -H 'content-type: application/json' -d '{"message":{"raw":"..."}}'`,+ '',+ 'See also:',+ ' composio link <toolkit> Connect an account before calling proxy',+ ' composio run \'const f = await proxy("gmail"); ...\' Use proxy in a script',+ ].join('\n')+ ),+ Command.withHandler(({ endpoint, toolkit, method, headers, data, skipConnectionCheck }) =>+ Effect.gen(function* () {+ if (!(yield* requireAuth)) return;++ const ui = yield* TerminalUI;+ const clientSingleton = yield* ComposioClientSingleton;+ const resolvedProject = yield* resolveCommandProject({ mode: 'consumer' }).pipe(+ Effect.mapError(formatResolveCommandProjectError)+ );++ if (resolvedProject.projectType !== 'CONSUMER' || !resolvedProject.consumerUserId) {+ return yield* Effect.fail(+ new Error('No consumer project user is available for proxy execution in this context.')+ );+ }+ const consumerUserId = resolvedProject.consumerUserId;+ const normalizedToolkit = toolkit.toLowerCase();++ yield* runProxyConnectedToolkitFailFast({+ toolkit: normalizedToolkit,+ ui,+ resolvedProject,+ resolvedUserId: consumerUserId,+ endpoint,+ skipConnectionCheck,+ });++ const normalizedMethod = normalizeProxyMethod(method);+ const headerParameters = headers.map(header => {+ const parsed = parseProxyHeader(header);+ return {+ name: parsed.name,+ type: 'header' as const,+ value: parsed.value,+ };+ });+ const rawBody = yield* resolveBodyInput(data);+ const parsedBody = rawBody === undefined ? undefined : parseProxyBody(rawBody);++ const result = yield* ui.withSpinner(+ `Proxying ${normalizedMethod} ${endpoint} via ${normalizedToolkit}...`,+ Effect.gen(function* () {+ const client = yield* clientSingleton.getFor({+ orgId: resolvedProject.orgId,+ projectId: resolvedProject.projectId,+ });+ const { sessionId } = yield* resolveToolRouterSession(client, consumerUserId, {+ toolkits: [normalizedToolkit],+ });++ const resultEither = yield* Effect.tryPromise(() =>+ client.toolRouter.session.proxyExecute(sessionId, {+ toolkit_slug: normalizedToolkit,+ endpoint,+ method: normalizedMethod,+ ...(parsedBody !== undefined ? { body: parsedBody } : {}),+ ...(headerParameters.length > 0 ? { parameters: headerParameters } : {}),+ })+ ).pipe(Effect.either);++ if (resultEither._tag === 'Left') {+ return yield* handleProxyExecutionError({+ ui,+ error: resultEither.left,+ toolkit: normalizedToolkit,+ endpoint,+ });+ }++ return resultEither.right;+ })+ );++ const output = formatProxyOutput(result);+ yield* ui.log.info(`Status: ${String(result.status ?? 'unknown')}`);+ if (output) {+ yield* ui.note(output, 'Proxy Response');+ yield* ui.output(output);+ }+ })+ )+);diff --git a/ts/packages/cli/src/commands/root-help.ts b/ts/packages/cli/src/commands/root-help.tsindex f15f0e8e0..e8b81ca15 100644--- a/ts/packages/cli/src/commands/root-help.ts+++ b/ts/packages/cli/src/commands/root-help.ts@@ -1,218 +1,936 @@import { Console, Effect } from 'effect';-import { bold } from 'src/ui/colors';+import { bold, dim, gray } from 'src/ui/colors';-type BasicCommand = {+type DetailedCommand = {name: string;description: string;usage: string;options?: ReadonlyArray<{ name: string; description: string }>;};-const BASIC_COMMANDS: ReadonlyArray<BasicCommand> = [+type CompactCommand = {+ name: string;+ description: string;+};++// ── Core workflow commands ──────────────────────────────────────────────++const CORE_COMMANDS: ReadonlyArray<DetailedCommand> = [{- name: 'version',- description: 'Display the current Composio CLI version.',- usage: 'version',+ name: 'search',+ description: 'Find 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")' },+ { name: '--toolkits', description: 'Filter by toolkit slugs, comma-separated' },+ { name: '--limit', description: 'Number of results per page (1-1000)' },+ ],},{- name: 'upgrade',- description: 'Upgrade your Composio CLI to the latest available version.',- usage: 'upgrade',+ name: 'execute',+ description:+ 'Execute a tool. Validates inputs and connections automatically; use it aggressively.',+ usage: 'execute <slug> [-d, --data text] [--dry-run] [--get-schema]',+ options: [+ { name: '<slug>', description: 'Tool slug (e.g. "GITHUB_CREATE_ISSUE")' },+ {+ 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 tool schema' },+ ],},{- name: 'whoami',- description: 'Display your account information.',- usage: 'whoami',+ name: 'link',+ description: 'Connect your account for a toolkit/app.',+ usage: 'link [<toolkit>] [--no-browser]',+ options: [{ name: '<toolkit>', description: 'Toolkit slug to link (e.g. "github", "gmail")' }],},{- name: 'login',- description: 'Log in to the Composio CLI session.',- usage: 'login [--no-browser] [--no-wait] [--key text] [-y, --yes]',+ name: 'run',+ description:+ 'Run inline TS/JS code with shimmed CLI commands; injected execute(), search(), proxy(), subAgent(), and z (zod).',+ usage: 'run <code> [-- ...args] | run [-f, --file text] [-- ...args] [--dry-run]',options: [- { name: '--no-browser', description: 'Login without browser interaction' },- {- name: '--no-wait',- description: 'Print login URL and session info, then exit (no browser, no waiting)',- },- {- name: '--key',- description: 'Complete login using session key from --no-wait',- },- { name: '-y, --yes', description: 'Skip org picker; use session default org' },+ { name: '<code>', description: 'Inline Bun ESNext code to evaluate' },+ { name: '-f, --file', description: 'Run a TS/JS file instead of inline code' },+ { name: '--dry-run', description: 'Preview execute() calls without running remote actions' },],},{- name: 'logout',- description: 'Log out from the Composio CLI session.',- usage: 'logout',+ name: 'proxy',+ description: 'curl-like access to any toolkit API through Composio using your linked account.',+ usage: 'proxy <url> --toolkit text [-X method] [-H header]... [-d data]',+ options: [+ { name: '<url>', description: 'Full API endpoint URL' },+ { name: '--toolkit', description: 'Toolkit slug whose connected account should be used' },+ { name: '-X, --method', description: 'HTTP method (GET, POST, PUT, DELETE, PATCH)' },+ { name: '-H, --header', description: 'Header in "Name: value" format. Repeat for multiple.' },+ { name: '-d, --data', description: 'Request body as raw text, JSON, @file, or - for stdin' },+ ],},{- 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]',+ name: 'artifacts',+ description: 'Inspect the cwd-scoped session artifact directory and history.',+ usage: 'artifacts cwd',+ options: [{ name: 'cwd', description: 'Print the current session artifact directory path' }],+ },+];++// ── Developer commands ─────────────────────────────────────────────────++const OTHER_COMMANDS: ReadonlyArray<CompactCommand> = [+ { name: 'tools info <slug>', description: 'Print tool summary and cache its schema' },+ { name: 'tools list <toolkit>', description: 'List tools available in a toolkit' },+ { name: 'artifacts cwd', description: 'Print the cwd-scoped session artifact directory' },+];++const DEVELOPER_COMMANDS: ReadonlyArray<CompactCommand> = [+ {+ name: 'dev',+ description: 'Developer workflows: init, playground execution, triggers, and logs.',+ },+ {+ name: 'generate',+ description: 'Generate type stubs for toolkits, tools, and triggers (TypeScript | Python).',+ },+ {+ name: 'manage',+ description: 'Manage orgs, toolkits, connected accounts, triggers, auth configs, and projects.',+ },+];++// ── Account commands ───────────────────────────────────────────────────++const ACCOUNT_COMMANDS: ReadonlyArray<CompactCommand> = [+ { name: 'login', description: 'Log in to Composio' },+ { name: 'logout', description: 'Log out from Composio' },+ { name: 'whoami', description: 'Show current account info' },+ { name: 'version', description: 'Display CLI version' },+ { name: 'upgrade', description: 'Upgrade CLI to the latest version' },+];++// ── Render helpers ─────────────────────────────────────────────────────++function renderDetailedCommands(name: string, commands: ReadonlyArray<DetailedCommand>): string[] {+ const lines: string[] = [];+ for (const cmd of commands) {+ lines.push(` ${bold(cmd.name)}`);+ lines.push(` ${cmd.description}`);+ lines.push(` ${dim('Usage:')} ${name} ${cmd.usage}`);+ if (cmd.options && cmd.options.length > 0) {+ for (const opt of cmd.options) {+ lines.push(` ${dim(opt.name.padEnd(20))}${opt.description}`);+ }+ }+ lines.push('');+ }+ return lines;+}++function renderCompactCommands(commands: ReadonlyArray<CompactCommand>): string[] {+ const maxLen = Math.max(...commands.map(c => c.name.length));+ return commands.map(cmd => ` ${cmd.name.padEnd(maxLen + 2)}${cmd.description}`);+}++// ── Subcommand help definitions ────────────────────────────────────────++type SubcommandHelp = {+ usage: string;+ description: string;+ args?: ReadonlyArray<{ name: string; description: string }>;+ options?: ReadonlyArray<{ name: string; description: string }>;+ flags?: ReadonlyArray<{ name: string; description: string }>;+ injectedHelpers?: ReadonlyArray<{ name: string; description: string }>;+ examples?: ReadonlyArray<string>;+ seeAlso?: ReadonlyArray<string>;+};++const SUBCOMMAND_HELP: Record<string, SubcommandHelp> = {+ search: {+ usage: 'composio search <query> [--toolkits text] [--limit integer]',+ description:+ 'Find tools by use case. Returns matching tools with slugs you can pass directly to execute.',+ args: [+ {+ name: '<query>',+ description: 'Semantic use-case query (e.g. "send an email", "create github issue")',+ },+ ],+ options: [+ { name: '--toolkits <text>', description: 'Filter by toolkit slugs, comma-separated' },+ { name: '--limit <integer>', description: 'Number of results per page (1-1000)' },+ ],+ examples: [+ '# Find tools for a use case',+ 'composio search "send an email"',+ 'composio search "create issue" --toolkits github',+ '',+ '# Cross-app workflow discovery',+ 'composio search "post a message to a slack channel"',+ 'composio search "add a row to google sheet"',+ '',+ '# Narrow results to a specific toolkit',+ 'composio search "list calendar events" --toolkits google_calendar --limit 5',+ ],+ seeAlso: [+ "composio execute <slug> -d '{ ... }' Run a tool from the results",+ "composio tools info <slug> Inspect a tool's full schema",+ 'composio link <toolkit> Connect an account if execute tells you to',+ ],+ },+ execute: {+ usage: 'composio execute <slug> [-d, --data text] [--dry-run] [--get-schema]',+ description:+ 'Execute a tool by slug. Validates inputs against cached schemas and checks connections automatically — just try it and it will tell you what to fix.',+ args: [{ name: '<slug>', description: 'Tool slug (e.g. "GITHUB_CREATE_ISSUE")' }],options: [{- name: '<code>',+ name: '-d, --data <text>',description:- 'Inline Bun ESNext code with injected execute(slug, data?) and search(query, options?) helpers',+ 'JSON or JS-style object arguments, e.g. -d \'{ repo: "foo" }\', @file, or - for stdin',},{- name: '-f, --file',- description: 'Run a TS/JS file with the Bun runtime instead of inline code',+ name: '--get-schema',+ description: 'Fetch and print the raw tool schema without executing',},{name: '--dry-run',- description: 'Preview execute(...) calls without running remote actions',+ description: 'Validate and preview the tool call without executing',},+ ],+ flags: [+ { name: '--skip-connection-check', description: 'Skip the linked-account check' },{- 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 input validation against cached schema',},+ { name: '--no-verify', description: 'Skip both checks above' },+ ],+ examples: [+ '# Send an email',+ `composio execute GMAIL_SEND_EMAIL -d '{ recipient_email: "[email protected]", subject: "Hello", body: "World" }'`,+ '',+ '# Create a GitHub issue',+ `composio execute GITHUB_CREATE_ISSUE -d '{ owner: "acme", repo: "app", title: "Bug report", body: "Steps to reproduce..." }'`,+ '',+ '# Preview what a tool call would send without executing',+ `composio execute SLACK_SEND_A_MESSAGE_TO_A_SLACK_CHANNEL --dry-run -d '{ channel: "general", text: "Hello team" }'`,+ '',+ '# Check what inputs a tool needs',+ 'composio execute GMAIL_SEND_EMAIL --get-schema',+ '',+ '# Read arguments from a file',+ 'composio execute GITHUB_CREATE_ISSUE -d @issue.json',+ ],+ seeAlso: [+ 'composio search "<query>" Find tool slugs by use case',+ 'composio tools info <slug> Schema summary with jq hints',+ 'composio link <toolkit> Connect an account for a toolkit',+ 'composio artifacts cwd Print the current session artifact directory',+ ],+ },+ link: {+ usage: 'composio link [<toolkit>] [--no-browser] [--no-wait]',+ description:+ 'Connect an external account (GitHub, Gmail, Slack, etc.) so tools can act on your behalf. Opens a browser for OAuth authorization and waits for confirmation.',+ args: [{ name: '<toolkit>', description: 'Toolkit slug to link (e.g. "github", "gmail")' }],+ flags: [+ { name: '--no-browser', description: 'Print the auth URL instead of opening a browser' },+ {+ name: '--no-wait',+ description: 'Print link info and exit without waiting for authorization',+ },+ ],+ examples: ['composio link github', 'composio link gmail --no-browser'],+ seeAlso: [+ 'composio search "<query>" Find tools to use after linking',+ "composio execute <slug> -d '{ ... }' Execute a tool with your linked account",+ ],+ },+ run: {+ usage: 'composio run <code> [-- ...args] | run -f <file> [-- ...args]',+ description:+ 'Run inline TS/JS code or a file with injected Composio helpers that behave like their CLI counterparts.',+ args: [{ name: '<code>', description: 'Inline Bun ESNext code to evaluate' }],+ options: [+ { name: '-f, --file <text>', description: 'Run a TS/JS file instead of inline code' },+ { name: '--dry-run', description: 'Preview execute() calls without running them' },+ { name: '--debug', description: 'Log helper steps while the script runs' },+ ],+ flags: [+ { name: '--skip-connection-check', description: 'Skip the linked-account check' },{name: '--skip-tool-params-check',- description: 'Skip the local tool parameter/schema validation check',+ description: 'Skip input validation against cached schema',},+ { name: '--no-verify', description: 'Skip both checks above' },+ ],+ injectedHelpers: [{- name: '--no-verify',- description:- 'Skip both the linked-account fail-fast check and the local tool parameter check',+ name: 'execute(slug, data?)',+ description: 'Run a tool — same as `composio execute`, returns parsed JSON',},+ { name: 'search(query, opts?)', description: 'Find tools — same as `composio search`' },+ { name: 'proxy(toolkit)', description: 'Returns a fetch() bound to your linked account' },+ {+ name: 'subAgent(prompt, opts?)',+ description: 'Spawn a sub-agent (Claude/Codex) with optional structured output',+ },+ {+ name: 'result.prompt()',+ description: 'Serialize any helper result into an LLM-friendly string',+ },+ { name: 'z', description: 'Global from zod for defining structured output schemas' },+ ],+ examples: [+ `composio run '`,+ ` // execute(slug, data?) — run a tool, returns parsed JSON`,+ ` const me = await execute("GITHUB_GET_THE_AUTHENTICATED_USER");`,+ ` console.log(me);`,+ `'`,+ '',+ `composio run '`,+ ` // search(query, opts?) — find tools by use case`,+ ` const tools = await search("send email");`,+ ` console.log(tools);`,+ `'`,+ '',+ '# Sequential: chain tool outputs across services',+ `composio run '`,+ ` const issue = await execute("GITHUB_CREATE_ISSUE", { owner: "acme", repo: "app", title: "Deploy v2" });`,+ ` await execute("SLACK_SEND_A_MESSAGE_TO_A_SLACK_CHANNEL", { channel: "eng", text: "Created: " + issue.data.html_url });`,+ `'`,+ '',+ '# Parallel: fetch from multiple services at once with Promise.all',+ `composio run '`,+ ` const [emails, issues, events] = await Promise.all([`,+ ` execute("GMAIL_FETCH_EMAILS", { max_results: 5 }),`,+ ` execute("GITHUB_LIST_REPOSITORY_ISSUES", { owner: "composiohq", repo: "composio", state: "open" }),`,+ ` execute("GOOGLECALENDAR_FIND_EVENT", { calendar_id: "primary" }),`,+ ` ]);`,+ ` console.log({ emails: emails.data, issues: issues.data, events: events.data });`,+ `'`,+ '',+ '# Bulk: fan out with Promise.all + .map()',+ `composio run '`,+ ` const issues = [101, 102, 103, 104];`,+ ` await Promise.all(issues.map(n =>`,+ ` execute("GITHUB_ADD_LABELS_TO_ISSUE", { owner: "acme", repo: "app", issue_number: n, labels: ["priority"] })`,+ ` ));`,+ `'`,+ '',+ '# proxy(toolkit) — returns a fetch() bound to your linked account',+ `composio run '`,+ ` const f = await proxy("gmail");`,+ ` console.log(await f("https://gmail.googleapis.com/gmail/v1/users/me/profile"));`,+ `'`,+ '',+ '# subAgent + z + result.prompt() — structured output from a sub-agent',+ `composio run '`,+ ` const [emails, issues] = await Promise.all([`,+ ` execute("GMAIL_FETCH_EMAILS", { max_results: 5 }),`,+ ` execute("GITHUB_LIST_REPOSITORY_ISSUES", { owner: "composiohq", repo: "composio", state: "open" }),`,+ ` ]);`,+ ` // result.prompt() serializes helper output for LLM consumption`,+ ` // z is a global from zod for defining structured output schemas`,+ ` const brief = await subAgent(`,+ ` \`Summarize these emails and issues.\\n\\n\${emails.prompt()}\\n\\n\${issues.prompt()}\`,`,+ ` { schema: z.object({ summary: z.string(), urgent: z.array(z.string()) }) }`,+ ` );`,+ ` console.log(brief.structuredOutput);`,+ `'`,+ '',+ '# Run from a file',+ 'composio run --file ./workflow.ts -- --repo acme/app',+ ],+ seeAlso: [+ 'composio search "<query>" Discover tool slugs before scripting',+ 'composio link <toolkit> Connect accounts before scripting',+ 'composio execute <slug> --get-schema Inspect tool inputs before scripting',+ 'composio artifacts cwd Print the current session artifact directory',],},- {- name: 'search',- description: 'Semantic search for tools by use case across all toolkits/apps.',- usage: 'search <query> [--toolkits text] [--limit integer]',+ proxy: {+ usage: 'composio proxy <url> --toolkit <text> [-X method] [-H header]... [-d data]',+ description:+ 'curl-like access to any toolkit API through Composio using your linked account. Composio handles authentication — just provide the full URL and toolkit.',+ args: [{ name: '<url>', description: 'Full API endpoint URL' }],options: [- { name: '<query>', description: 'Semantic use-case query (e.g. "send emails")' },- { name: '--toolkits', description: 'Filter by toolkit slugs, comma-separated' },- { name: '--limit', description: 'Number of results per page (1-1000)' },+ {+ name: '-t, --toolkit <text>',+ description: 'Toolkit slug whose connected account should be used',+ },+ { name: '-X, --method <text>', description: 'HTTP method (GET, POST, PUT, DELETE, PATCH)' },+ {+ name: '-H, --header <text>',+ description: 'Header in "Name: value" format. Repeat for multiple.',+ },+ {+ name: '-d, --data <text>',+ description: 'Request body as raw text, JSON, @file, or - for stdin',+ },+ ],+ flags: [{ name: '--skip-connection-check', description: 'Skip the linked-account check' }],+ examples: [+ 'composio proxy https://gmail.googleapis.com/gmail/v1/users/me/profile --toolkit gmail',+ `composio proxy https://gmail.googleapis.com/gmail/v1/users/me/drafts --toolkit gmail \\`,+ ` -X POST -H 'content-type: application/json' -d '{"message":{"raw":"..."}}'`,+ ],+ seeAlso: [+ 'composio link <toolkit> Connect an account first',+ `composio run 'const f = await proxy("gmail"); ...' Use proxy in a script`,],},- {- name: 'tools',- description: 'List tools for one toolkit, or inspect a cached schema-backed summary.',- usage: 'tools list <toolkit> [--query text] | tools info <slug>',++ // ── Account commands ──────────────────────────────────────────────────++ login: {+ usage: 'composio login [--no-browser] [--no-wait] [--key text] [-y, --yes]',+ description: 'Log in to the Composio CLI session.',options: [{- name: 'list <toolkit>',- description: 'Non-semantic per-toolkit listing; use this when you already know the toolkit',+ name: '--key <text>',+ description: 'Complete login using session key from composio login --no-wait',},+ ],+ flags: [+ { name: '--no-browser', description: 'Login without browser interaction' },+ { name: '--no-wait', description: 'Print login URL and session info, then exit' },+ { name: '-y, --yes', description: 'Skip org picker; use session default org' },+ ],+ },+ logout: {+ usage: 'composio logout',+ description: 'Log out from the Composio CLI session.',+ },+ whoami: {+ usage: 'composio whoami',+ description: 'Display your account information.',+ },+ version: {+ usage: 'composio version',+ description: 'Display the current Composio CLI version.',+ },+ upgrade: {+ usage: 'composio upgrade',+ description: 'Upgrade your Composio CLI to the latest available version.',+ },++ // ── Tools commands ────────────────────────────────────────────────────++ 'tools list': {+ usage: 'composio tools list <toolkit> [--query text] [--tags text] [--limit integer]',+ description: 'List available tools for a toolkit.',+ args: [{ name: '<toolkit>', description: 'Toolkit slug to list tools for (e.g. "gmail")' }],+ options: [+ { name: '--query <text>', description: 'Text search by name, slug, or description' },+ { name: '--tags <text>', description: 'Filter by tags (e.g. "important")' },+ { name: '--limit <integer>', description: 'Number of results per page (1-1000)' },+ ],+ },+ 'tools info': {+ usage: 'composio tools info [<slug>]',+ description:+ 'View a brief summary of a tool and cache the raw schema used by `composio execute --get-schema`.',+ args: [{ name: '<slug>', description: 'Tool slug (e.g. "GMAIL_SEND_EMAIL")' }],+ },++ // ── Generate commands ─────────────────────────────────────────────────++ generate: {+ usage: 'composio generate [--output-dir dir] [--type-tools] --toolkits text...',+ description:+ 'Generate type stubs for toolkits, tools, and triggers, auto-detecting project language (TypeScript | Python).',+ options: [+ { name: '-o, --output-dir <dir>', description: 'Output directory for type stubs' },{- name: 'info <slug>',- description:- 'Print a brief summary and cache the same raw schema used by execute --get-schema',+ name: '--toolkits <text>...',+ description: 'Toolkits to generate for (repeat for multiple)',+ },+ ],+ flags: [+ {+ name: '--type-tools',+ description: 'Generate typed input/output schemas for each tool (slower)',},],},- {- name: 'execute',- description: 'Execute a tool, preview it with --dry-run, or fetch its input schema.',+ 'generate ts': {usage:- 'execute <slug> [-d, --data text] [--dry-run] [--get-schema] [--skip-connection-check] [--skip-tool-params-check] [--no-verify]',+ 'composio generate ts [--output-dir dir] [--compact] [--transpiled] [--type-tools] --toolkits text...',+ description: 'Generate TypeScript type stubs for toolkits, tools, and triggers.',options: [- { name: '<slug>', description: 'Tool slug (e.g. "GITHUB_CREATE_ISSUE")' },{- name: '-d, --data',- description:- 'JSON or JS-style object arguments, e.g. -d \'{ repo: "foo" }\', @file, or - for stdin',+ name: '-o, --output-dir <dir>',+ description: 'Output directory for generated TypeScript stubs',},- { 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: '--toolkits <text>...',+ description: 'Toolkits to generate for (repeat for multiple)',},+ ],+ flags: [+ { name: '--compact', description: 'Emit a single TypeScript file' },{- name: '--skip-connection-check',- description:- 'Skip the short-lived linked-account fail-fast check if you just connected an account',+ name: '--transpiled',+ description: 'Emit transpiled JavaScript alongside TypeScript files',},{- 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: '--type-tools',+ description: 'Generate typed input/output schemas for each tool (slower)',},],},- {- name: 'link',- description: 'Connect a user account for a toolkit/app.',- usage: 'link [<toolkit>] [--no-browser]',+ 'generate py': {+ usage: 'composio generate py [--output-dir dir] --toolkits text...',+ description: 'Generate Python type stubs for toolkits, tools, and triggers.',options: [- { name: '<toolkit>', description: 'Toolkit slug to link (e.g. "github", "gmail")' },- { name: '--no-browser', description: 'Skip auto-opening the browser' },+ {+ name: '-o, --output-dir <dir>',+ description: 'Output directory for generated Python stubs',+ },+ {+ name: '--toolkits <text>...',+ description: 'Toolkits to generate for (repeat for multiple)',+ },],},-];-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.',+ // ── Dev commands ──────────────────────────────────────────────────────++ 'dev init': {+ usage: 'composio dev init [--no-browser] [-y, --yes]',+ description: 'Initialize this directory with a developer project.',+ flags: [+ { name: '--no-browser', description: 'Login without browser interaction' },+ { name: '-y, --yes', description: 'Auto-select the default org project' },+ ],},- {- name: 'generate',+ 'dev execute': {+ usage:+ 'composio dev execute <slug> [-d, --data text] [--user-id text] [--project-name text] [--dry-run] [--get-schema]',description:- 'Generate type stubs for toolkits, tools, and triggers, auto-detecting project language (TypeScript | Python)',+ 'Execute a tool with your playground test user against your developer project auth configs.',+ args: [{ name: '<slug>', description: 'Tool slug (e.g. "GITHUB_CREATE_ISSUE")' }],+ options: [+ { name: '-d, --data <text>', description: 'JSON arguments, @file, or - for stdin' },+ { name: '--user-id <text>', description: 'Developer-project user ID override' },+ { name: '--project-name <text>', description: 'Developer project name override' },+ {+ name: '--get-schema',+ description: 'Fetch and print the raw tool schema without executing',+ },+ { name: '--dry-run', description: 'Validate and preview without executing' },+ ],+ flags: [+ { name: '--skip-connection-check', description: 'Skip the linked-account check' },+ {+ name: '--skip-tool-params-check',+ description: 'Skip input validation against cached schema',+ },+ { name: '--no-verify', description: 'Skip both checks above' },+ ],},- {- name: 'manage',+ 'dev listen': {+ usage:+ 'composio dev listen [--toolkits text] [--trigger-slug text] [--json] [--table] [--max-events int] [--forward url] [--out file]',description:- 'Manage your developer orgs, toolkits, connected accounts, triggers, auth configs, and projects.',+ 'Listen to realtime trigger events for your developer project and optionally forward them.',+ options: [+ { name: '--toolkits <text>', description: 'Filter by toolkit slugs, comma-separated' },+ { name: '--trigger-id <text>', description: 'Filter by trigger id' },+ { name: '--connected-account-id <text>', description: 'Filter by connected account id' },+ { name: '--trigger-slug <text>', description: 'Filter by trigger slug, comma-separated' },+ { name: '--user-id <text>', description: 'Filter by user id' },+ { name: '--max-events <int>', description: 'Stop after receiving N matching events' },+ { name: '--forward <url>', description: 'Forward each event to the given URL' },+ { name: '--out <file>', description: 'Append each event to this file' },+ ],+ flags: [+ { name: '--json', description: 'Show raw event payload as JSON' },+ { name: '--table', description: 'Show compact table rows' },+ ],},-];-/**- * Prints the root-level help output in gh-style format.- * Shows only top-level commands, not nested subcommands.- * Basic commands include full usage and options.- */-export function printRootHelp(): Effect.Effect<void> {- const name = 'composio';- const allCommands = [- ...BASIC_COMMANDS.map(c => ({ name: c.name, description: c.description })),- ...ADVANCED_COMMANDS,+ // ── Manage commands ───────────────────────────────────────────────────++ 'manage toolkits list': {+ usage:+ 'composio manage toolkits list [--query text] [--limit integer] [--connected] [--user-id text]',+ description: 'List available toolkits with connection status.',+ options: [+ { name: '--query <text>', description: 'Text search by name, slug, or description' },+ { name: '--limit <integer>', description: 'Number of results per page (1-1000)' },+ { name: '--user-id <text>', description: 'User ID override' },+ ],+ flags: [{ name: '--connected', description: 'Show only connected toolkits' }],+ },+ 'manage toolkits info': {+ usage: 'composio manage toolkits info [--user-id text] [-a, --all] [<slug>]',+ description: 'View details of a specific toolkit.',+ args: [{ name: '<slug>', description: 'Toolkit slug (e.g. "github")' }],+ flags: [{ name: '-a, --all', description: 'Show all details' }],+ },+ 'manage toolkits search': {+ usage: 'composio manage toolkits search <query> [--limit integer]',+ description: 'Search toolkits by use case.',+ args: [{ name: '<query>', description: 'Search query' }],+ options: [{ name: '--limit <integer>', description: 'Number of results' }],+ },+ 'manage toolkits version': {+ usage: 'composio manage toolkits version <slug>',+ description: 'Show latest and recent versions for a toolkit.',+ args: [{ name: '<slug>', description: 'Toolkit slug' }],+ },+ 'manage auth-configs list': {+ usage: 'composio manage auth-configs list [--toolkits text] [--query text] [--limit integer]',+ description: 'List auth configs.',+ options: [+ { name: '--toolkits <text>', description: 'Filter by toolkit slugs' },+ { name: '--query <text>', description: 'Search text' },+ { name: '--limit <integer>', description: 'Number of results' },+ ],+ },+ 'manage auth-configs info': {+ usage: 'composio manage auth-configs info [<id>]',+ description: 'View details of a specific auth config.',+ args: [{ name: '<id>', description: 'Auth config ID' }],+ },+ 'manage auth-configs create': {+ usage:+ 'composio manage auth-configs create --toolkit text [--auth-scheme text] [--scopes text] [--custom-credentials text] [<name>]',+ description: 'Create a new auth config.',+ args: [{ name: '<name>', description: 'Auth config name' }],+ options: [+ { name: '--toolkit <text>', description: 'Toolkit slug' },+ { name: '--auth-scheme <text>', description: 'Authentication scheme' },+ { name: '--scopes <text>', description: 'Comma-separated scopes' },+ { name: '--custom-credentials <text>', description: 'Custom credentials JSON' },+ ],+ },+ 'manage auth-configs delete': {+ usage: 'composio manage auth-configs delete [-y, --yes] [<id>]',+ description: 'Delete an auth config.',+ args: [{ name: '<id>', description: 'Auth config ID' }],+ flags: [{ name: '-y, --yes', description: 'Skip confirmation prompt' }],+ },+ 'manage connected-accounts list': {+ usage:+ 'composio manage connected-accounts list [--toolkits text] [--user-id text] [--status text] [--limit integer]',+ description: 'List connected accounts.',+ options: [+ { name: '--toolkits <text>', description: 'Filter by toolkit slugs' },+ { name: '--user-id <text>', description: 'Filter by user id' },+ { name: '--status <text>', description: 'Filter by status (ACTIVE, FAILED, EXPIRED, etc.)' },+ { name: '--limit <integer>', description: 'Number of results' },+ ],+ },+ 'manage connected-accounts info': {+ usage: 'composio manage connected-accounts info [<id>]',+ description: 'View details of a specific connected account.',+ args: [{ name: '<id>', description: 'Connected account ID' }],+ },+ 'manage connected-accounts whoami': {+ usage: 'composio manage connected-accounts whoami [<id>]',+ description: 'Show the external account profile for a connected account.',+ args: [{ name: '<id>', description: 'Connected account ID' }],+ },+ 'manage connected-accounts delete': {+ usage: 'composio manage connected-accounts delete [-y, --yes] [<id>]',+ description: 'Delete a connected account.',+ args: [{ name: '<id>', description: 'Connected account ID' }],+ flags: [{ name: '-y, --yes', description: 'Skip confirmation prompt' }],+ },+ 'manage connected-accounts link': {+ usage:+ 'composio manage connected-accounts link [--auth-config text] [--user-id text] [--project-name text] [--no-browser] [--no-wait] [<toolkit>]',+ description: 'Connect an external account so tools can act on your behalf.',+ args: [{ name: '<toolkit>', description: 'Toolkit slug to link (e.g. "github", "gmail")' }],+ options: [+ { name: '--auth-config <text>', description: 'Auth config ID to use' },+ { name: '--user-id <text>', description: 'User ID override' },+ { name: '--project-name <text>', description: 'Project name override' },+ ],+ flags: [+ { name: '--no-browser', description: 'Print the auth URL instead of opening a browser' },+ { name: '--no-wait', description: 'Print link info and exit without waiting' },+ ],+ },+ 'manage triggers list': {+ usage: 'composio manage triggers list [--toolkits text] [--limit integer]',+ description: 'List available trigger types.',+ options: [+ { name: '--toolkits <text>', description: 'Filter by toolkit slugs' },+ { name: '--limit <integer>', description: 'Number of results' },+ ],+ },+ 'manage triggers info': {+ usage: 'composio manage triggers info [<slug>]',+ description: 'View details of a specific trigger type.',+ args: [{ name: '<slug>', description: 'Trigger slug' }],+ },+ 'manage triggers listen': {+ usage:+ 'composio manage triggers listen [--toolkits text] [--trigger-slug text] [--json] [--table] [--max-events int] [--forward url] [--out file]',+ description: 'Listen to realtime trigger events and optionally forward them.',+ options: [+ { name: '--toolkits <text>', description: 'Filter by toolkit slugs, comma-separated' },+ { name: '--trigger-id <text>', description: 'Filter by trigger id' },+ { name: '--connected-account-id <text>', description: 'Filter by connected account id' },+ { name: '--trigger-slug <text>', description: 'Filter by trigger slug, comma-separated' },+ { name: '--user-id <text>', description: 'Filter by user id' },+ { name: '--max-events <int>', description: 'Stop after receiving N events' },+ { name: '--forward <url>', description: 'Forward each event to the given URL' },+ { name: '--out <file>', description: 'Append each event to this file' },+ ],+ flags: [+ { name: '--json', description: 'Show raw event payload as JSON' },+ { name: '--table', description: 'Show compact table rows' },+ ],+ },+ 'manage triggers status': {+ usage:+ 'composio manage triggers status [--user-ids text] [--toolkits text] [--trigger-ids text] [--show-disabled] [--limit integer]',+ description: 'Show active triggers with optional filters.',+ options: [+ { name: '--user-ids <text>', description: 'Filter by user IDs' },+ { name: '--connected-account-ids <text>', description: 'Filter by connected account IDs' },+ { name: '--toolkits <text>', description: 'Filter by toolkit slugs' },+ { name: '--trigger-ids <text>', description: 'Filter by trigger IDs' },+ { name: '--trigger-names <text>', description: 'Filter by trigger names' },+ { name: '--limit <integer>', description: 'Number of results' },+ ],+ flags: [{ name: '--show-disabled', description: 'Include disabled triggers' }],+ },+ 'manage triggers create': {+ usage:+ 'composio manage triggers create [--connected-account-id text] [--trigger-config text] [<trigger-name>]',+ description: 'Create a new trigger instance.',+ args: [{ name: '<trigger-name>', description: 'Trigger type slug' }],+ options: [+ { name: '--connected-account-id <text>', description: 'Connected account to use' },+ { name: '--trigger-config <text>', description: 'Trigger configuration JSON' },+ ],+ },+ 'manage triggers enable': {+ usage: 'composio manage triggers enable [<id>]',+ description: 'Enable a trigger instance.',+ args: [{ name: '<id>', description: 'Trigger instance ID' }],+ },+ 'manage triggers disable': {+ usage: 'composio manage triggers disable [<id>]',+ description: 'Disable a trigger instance.',+ args: [{ name: '<id>', description: 'Trigger instance ID' }],+ },+ 'manage triggers delete': {+ usage: 'composio manage triggers delete [-y, --yes] [<id>]',+ description: 'Delete a trigger instance.',+ args: [{ name: '<id>', description: 'Trigger instance ID' }],+ flags: [{ name: '-y, --yes', description: 'Skip confirmation prompt' }],+ },+ 'manage orgs list': {+ usage: 'composio manage orgs list [--limit integer]',+ description: 'List organizations and show current global selection.',+ options: [{ name: '--limit <integer>', description: 'Number of results' }],+ },+ 'manage orgs switch': {+ usage: 'composio manage orgs switch [--org-id text] [--limit integer]',+ description: 'Switch default organization context.',+ options: [+ { name: '--org-id <text>', description: 'Organization ID to switch to' },+ { name: '--limit <integer>', description: 'Number of orgs to show in picker' },+ ],+ },+ 'manage projects list': {+ usage: 'composio manage projects list [--org-id text] [--limit integer]',+ description: 'List developer projects for the current organization.',+ options: [+ { name: '--org-id <text>', description: 'Organization ID override' },+ { name: '--limit <integer>', description: 'Number of results' },+ ],+ },++ // ── Dev logs commands ─────────────────────────────────────────────────++ 'dev logs tools': {+ usage:+ 'composio dev logs tools [--toolkit text] [--tool text] [--status text] [--limit integer] [<log_id>]',+ description: 'List tool execution logs, or pass a log_id to fetch a specific log.',+ args: [{ name: '<log_id>', description: 'Specific log ID to fetch' }],+ options: [+ { name: '--toolkit <text>', description: 'Filter by toolkit slug' },+ { name: '--tool <text>', description: 'Filter by tool slug' },+ { name: '--status <text>', description: 'Filter by status' },+ { name: '--user-id <text>', description: 'Filter by user id' },+ { name: '--limit <integer>', description: 'Number of results' },+ { name: '--from <integer>', description: 'Start timestamp (epoch ms)' },+ { name: '--to <integer>', description: 'End timestamp (epoch ms)' },+ ],+ flags: [{ name: '--case-sensitive', description: 'Case-sensitive filtering' }],+ },+ 'dev logs triggers': {+ usage:+ 'composio dev logs triggers [--trigger text] [--trigger-id text] [--limit integer] [--time 5m|30m|6h|1d|1w] [<log_id>]',+ description: 'List trigger logs.',+ args: [{ name: '<log_id>', description: 'Specific log ID to fetch' }],+ options: [+ { name: '--trigger <text>', description: 'Filter by trigger slug' },+ { name: '--trigger-id <text>', description: 'Filter by trigger id' },+ { name: '--user-id <text>', description: 'Filter by user id' },+ { name: '--connected-account-id <text>', description: 'Filter by connected account id' },+ { name: '--limit <integer>', description: 'Number of results' },+ { name: '--time <period>', description: 'Time window (5m, 30m, 6h, 1d, 1w, 1month, 1y)' },+ { name: '--search <text>', description: 'Search in log content' },+ ],+ flags: [{ name: '--include-payload', description: 'Include full event payload' }],+ },+};++function renderSubcommandHelp(cmd: SubcommandHelp): string {+ const lines: string[] = [+ '',+ bold('USAGE'),+ ` ${cmd.usage}`,+ '',+ bold('DESCRIPTION'),+ ` ${cmd.description}`,+ '',];- const maxNameLen = Math.max(...allCommands.map(c => c.name.length), 10);- const basicLines: string[] = [];- for (const cmd of BASIC_COMMANDS) {- basicLines.push(` ${cmd.name}`);- basicLines.push(` ${cmd.description}`);- basicLines.push(` Usage: ${name} ${cmd.usage}`);- if (cmd.options && cmd.options.length > 0) {- basicLines.push(' Options:');- for (const opt of cmd.options) {- basicLines.push(` ${opt.name.padEnd(20)} ${opt.description}`);- }+ if (cmd.args && cmd.args.length > 0) {+ lines.push(bold('ARGUMENTS'));+ for (const arg of cmd.args) {+ lines.push(` ${dim(arg.name.padEnd(24))}${arg.description}`);+ }+ lines.push('');+ }++ if (cmd.options && cmd.options.length > 0) {+ lines.push(bold('OPTIONS'));+ for (const opt of cmd.options) {+ lines.push(` ${dim(opt.name.padEnd(24))}${opt.description}`);}- basicLines.push('');+ lines.push('');}+ if (cmd.flags && cmd.flags.length > 0) {+ lines.push(bold('FLAGS'));+ for (const flag of cmd.flags) {+ lines.push(` ${dim(flag.name.padEnd(28))}${flag.description}`);+ }+ lines.push('');+ }++ if (cmd.injectedHelpers && cmd.injectedHelpers.length > 0) {+ lines.push(bold('INJECTED HELPERS'));+ const maxLen = Math.max(...cmd.injectedHelpers.map(h => h.name.length));+ for (const helper of cmd.injectedHelpers) {+ lines.push(` ${dim(helper.name.padEnd(maxLen + 2))}${helper.description}`);+ }+ lines.push('');+ }++ if (cmd.examples && cmd.examples.length > 0) {+ lines.push(bold('EXAMPLES'));+ for (const ex of cmd.examples) {+ lines.push(` ${ex}`);+ }+ lines.push('');+ }++ if (cmd.seeAlso && cmd.seeAlso.length > 0) {+ lines.push(bold('SEE ALSO'));+ for (const sa of cmd.seeAlso) {+ lines.push(` ${sa}`);+ }+ lines.push('');+ }++ return lines.join('\n');+}++/**+ * Check if argv is `composio <subcommand> --help` for a command we have custom help for.+ * Returns the command name if matched, undefined otherwise.+ */+export function matchSubcommandHelp(argv: ReadonlyArray<string>): string | undefined {+ const args = argv.slice(2);+ if (args.length < 2) return undefined;+ const last = args[args.length - 1];+ if (last !== '--help' && last !== '-h') return undefined;++ const cmdParts = args.slice(0, -1);+ // Try longest match first: "manage toolkits list" → "manage toolkits" → "manage"+ for (let len = cmdParts.length; len > 0; len--) {+ const key = cmdParts.slice(0, len).join(' ');+ if (key in SUBCOMMAND_HELP) return key;+ }+ return undefined;+}++export function printSubcommandHelp(cmd: string): Effect.Effect<void> {+ const help = SUBCOMMAND_HELP[cmd];+ if (!help) return Console.log(`Unknown command: ${cmd}`);+ return Console.log(renderSubcommandHelp(help));+}++// ── Main help output ───────────────────────────────────────────────────++/**+ * Prints the root-level help output.+ * Core workflow commands are shown first with full usage/options.+ * Housekeeping and developer commands are shown compactly at the bottom.+ */+export function printRootHelp(): Effect.Effect<void> {+ const name = 'composio';+const lines: string[] = ['',- '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.',+ `Connect AI agents to external tools. ${bold('search')}, ${bold('execute')}, ${bold('link')}, ${bold('proxy')}, and ${bold('run')} let you`,+ 'take actions across 1000+ apps directly; if you can describe it, it is probably supported.',+ `Try ${bold('execute')} sooner than you'd think — it validates inputs, checks connections, and tells`,+ 'you what to fix.',+ '',+ `Use ${bold('dev')} when you are building an agent with Composio's SDK and want scaffolding,`,+ 'playground execution, triggers, and logs.','',bold('USAGE'),` ${name} <command> [options]`,'',- bold('BASIC COMMANDS'),- ...basicLines,- bold('ADVANCED COMMANDS'),- ...ADVANCED_COMMANDS.map(cmd => ` ${cmd.name.padEnd(maxNameLen)} ${cmd.description}`),+ bold('CORE COMMANDS'),+ ...renderDetailedCommands(name, CORE_COMMANDS),+ gray(' Typical flow: search → execute (link and tools when needed)'),+ '',+ bold('TOOLS'),+ ...renderCompactCommands(OTHER_COMMANDS),+ '',+ bold('EXAMPLES'),+ ` ${dim('# Find a tool')}`,+ ` ${name} search "create github issue"`,+ '',+ ` ${dim('# Connect your GitHub account')}`,+ ` ${name} link github`,+ '',+ ` ${dim('# Execute a tool')}`,+ ` ${name} execute GITHUB_CREATE_ISSUE -d '{ repo: "owner/repo", title: "Bug" }'`,+ '',+ ` ${dim('# Call an API directly through proxy')}`,+ ` ${name} proxy https://gmail.googleapis.com/gmail/v1/users/me/profile --toolkit gmail`,+ '',+ ` ${dim('# Run a script with injected helpers')}`,+ ` ${name} run 'const me = await execute("GITHUB_GET_THE_AUTHENTICATED_USER"); console.log(me)'`,+ '',+ bold('DEVELOPER COMMANDS'),+ ...renderCompactCommands(DEVELOPER_COMMANDS),+ '',+ bold('ACCOUNT'),+ ...renderCompactCommands(ACCOUNT_COMMANDS),'',bold('FLAGS'),- ` -h, --help Show help for command`,+ ' -h, --help Show help for command',` --version Show ${name} version`,'',bold('LEARN MORE'),diff --git a/ts/packages/cli/src/commands/run.cmd.ts b/ts/packages/cli/src/commands/run.cmd.tsindex 201fa23eb..d54981038 100644--- a/ts/packages/cli/src/commands/run.cmd.ts+++ b/ts/packages/cli/src/commands/run.cmd.ts@@ -9,6 +9,11 @@ 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';+import { detectMaster, type MasterKind } from 'src/services/master-detector';+import {+ appendCliSessionHistory,+ resolveCliSessionArtifacts,+} from 'src/services/cli-session-artifacts';const file = Options.text('file').pipe(Options.withAlias('f'),@@ -16,14 +21,26 @@ const file = Options.text('file').pipe(Options.optional);-const dryRun = Options.boolean('dry-run').pipe(Options.withDefault(false));+const dryRun = Options.boolean('dry-run').pipe(+ Options.withDescription('Preview execute() calls without running them'),+ Options.withDefault(false)+);+const debug = Options.boolean('debug').pipe(+ Options.withDescription('Log helper steps while the script runs'),+ Options.withDefault(false)+);const skipConnectionCheck = Options.boolean('skip-connection-check').pipe(+ Options.withDescription('Skip the linked-account check'),Options.withDefault(false));const skipToolParamsCheck = Options.boolean('skip-tool-params-check').pipe(+ Options.withDescription('Skip input validation against cached schema'),+ Options.withDefault(false)+);+const noVerify = Options.boolean('no-verify').pipe(+ Options.withDescription('Skip both connection and input validation checks'),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')@@ -64,6 +81,59 @@ export const extractInlineExecuteToolSlugs = (source: string): ReadonlyArray<strreturn [...slugs];};+export const wrapInlineCodeForRun = (source: string): string => {+ const parsed = ts.createSourceFile(+ 'composio-run-inline.ts',+ source,+ ts.ScriptTarget.Latest,+ true,+ ts.ScriptKind.TSX+ );+ const statements = [...parsed.statements];+ if (statements.length === 0) {+ return source;+ }++ const lastStatement = statements.at(-1);+ if (!lastStatement || !ts.isExpressionStatement(lastStatement)) {+ return source;+ }++ const prefix = source.slice(0, lastStatement.getFullStart());+ const suffix = source.slice(lastStatement.getEnd());+ const expressionText = lastStatement.expression.getText(parsed);+ return `${prefix}return (${expressionText});${suffix}`;+};++export const wrapFileSourceForRun = (source: string): string => {+ const parsed = ts.createSourceFile(+ 'composio-run-file.ts',+ source,+ ts.ScriptTarget.Latest,+ true,+ ts.ScriptKind.TSX+ );+ const statements = [...parsed.statements];+ const firstNonImportIndex = statements.findIndex(statement => !ts.isImportDeclaration(statement));+ if (firstNonImportIndex === -1) {+ return source;+ }++ const bodyStart = statements[firstNonImportIndex]!.getFullStart();+ const importPrefix = source.slice(0, bodyStart);+ const body = source.slice(bodyStart);+ return [+ importPrefix,+ 'const __composioResult = await (async () => {',+ wrapInlineCodeForRun(body),+ '})();',+ 'if (__composioResult !== undefined) {',+ ' console.log(__composioResult);',+ '}',+ '',+ ].join('\n');+};+export const inferCliInvocationPrefix = (argv: ReadonlyArray<string> = process.argv): ReadonlyArray<string> => {@@ -99,114 +169,554 @@ type RunHelperContext = {readonly skipConnectionCheck?: boolean;readonly skipToolParamsCheck?: boolean;readonly noVerify?: boolean;+ readonly master?: MasterKind;+ readonly debug?: boolean;+ readonly runOutputDir?: string;};+// eslint-disable-next-line max-lines-per-function+const buildRunBaseHelpersSource = (): ReadonlyArray<string> => [+ 'globalThis.z = z;',+ 'globalThis.zod = z;',+ '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 proxySessionCache = new Map();',+ 'const composioBaseURL = (helperContext.baseURL || "https://backend.composio.dev").replace(/\\/$/, "");',+ 'const subAgentSchema = {',+ ' type: "function",',+ ' description: "Prompt a sub-agent from the same agent family as the current main agent (Codex -> Codex, Claude -> Claude) and return its final response.",',+ ' parameters: {',+ ' type: "object",',+ ' additionalProperties: false,',+ ' required: ["prompt"],',+ ' properties: {',+ ' prompt: { type: "string", description: "The prompt to send to the agent CLI." },',+ ' target: { type: "string", enum: ["claude", "codex", "user"], description: "Optional master override. Defaults to the detected current master." },',+ ' model: { type: "string", description: "Optional model override passed through to the agent CLI." },',+ ' schema: { description: "Optional structured-output schema. Accepts a Zod schema or raw JSON Schema object." },',+ ' jsonSchema: { description: "Optional JSON Schema requesting structured output from the agent." },',+ ' },',+ ' },',+ ' returns: {',+ ' type: "object",',+ ' additionalProperties: false,',+ ' required: ["master", "target", "result", "structuredOutput"],',+ ' properties: {',+ ' master: { type: "string", enum: ["claude", "codex", "user"] },',+ ' target: { type: "string", enum: ["claude", "codex"] },',+ ' result: { description: "Final plain-text result when available." },',+ ' structuredOutput: { description: "Structured output when jsonSchema was requested." },',+ ' },',+ ' },',+ '};',+ 'const proxySchema = {',+ ' type: "function",',+ ' description: "Call proxy(toolkit) to get a fetch-compatible function bound to that toolkit\'s connected account.",',+ ' parameters: {',+ ' type: "object",',+ ' additionalProperties: false,',+ ' required: ["toolkit"],',+ ' properties: {',+ ' toolkit: { type: "string", description: "Toolkit slug whose connected account should be used" },',+ ' },',+ ' },',+ ' returns: {',+ ' type: "function",',+ ' signature: "fetch(input, init?) => Promise<Response>",',+ ' requestInit: {',+ ' type: "object",',+ ' additionalProperties: true,',+ ' properties: {',+ ' method: { type: "string", enum: ["GET", "POST", "PUT", "DELETE", "PATCH"] },',+ ' headers: { description: "Standard fetch headers init" },',+ ' body: { description: "String, JSON-ish value, Blob, ArrayBuffer, or Uint8Array" },',+ ' },',+ ' },',+ ' },',+ '};',+ '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 helperDebugEnabled = helperContext.debug === true;',+ 'const sharedRunOutputDir = typeof helperContext.runOutputDir === "string" && helperContext.runOutputDir.length > 0 ? helperContext.runOutputDir : null;',+ 'const helperDebugLog = (step, details = {}) => {',+ ' if (!helperDebugEnabled) return;',+ ' const elapsedMs = Date.now() - perfDebugStart;',+ ' console.error(`[run:debug] ${JSON.stringify({ step, elapsedMs, ...details })}`);',+ '};',+ 'const parseJson = (text) => {',+ ' const value = text.trim();',+ ' if (!value) return undefined;',+ ' try {',+ ' return JSON.parse(value);',+ ' } catch {',+ ' return value;',+ ' }',+ '};',+ 'const stringifyForPrompt = (value) => {',+ ' if (value === undefined) return "undefined";',+ ' if (value === null) return "null";',+ ' if (typeof value === "string") return value;',+ ' if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") {',+ ' return String(value);',+ ' }',+ ' try {',+ ' return JSON.stringify(value, null, 2);',+ ' } catch {',+ ' return String(value);',+ ' }',+ '};',+ 'const attachPromptMethod = (value) => {',+ ' if (!value || typeof value !== "object" || Array.isArray(value)) return value;',+ ' if (typeof value.prompt === "function") return value;',+ ' Object.defineProperty(value, "prompt", {',+ ' value: () => stringifyForPrompt("data" in value ? value.data : value),',+ ' enumerable: false,',+ ' });',+ ' return value;',+ '};',+ 'const maybeLoadStoredCliResult = (result) => {',+ ' if (!result || typeof result !== "object" || result.storedInFile !== true) {',+ ' return attachPromptMethod(result);',+ ' }',+ ' helperDebugLog("cli.result.stored_in_file", { outputFilePath: result.outputFilePath ?? null, tokenCount: result.tokenCount ?? null });',+ ' const outputFilePath = typeof result.outputFilePath === "string" ? result.outputFilePath : null;',+ ' return attachPromptMethod({',+ ' ...result,',+ ' data: {',+ ' storedInFilePath: outputFilePath !== null,',+ ' outputFilePath,',+ ' },',+ ' });',+ '};',+ 'const describeDebugValue = (value) => {',+ ' if (Array.isArray(value)) return { type: "array", length: value.length };',+ ' if (value && typeof value === "object") return { type: "object", keys: Object.keys(value).slice(0, 20) };',+ ' return { type: typeof value, value: typeof value === "string" ? value.slice(0, 200) : value ?? null };',+ '};',+ 'const logCliResultPreview = (requestId, result) => {',+ ' if (!helperDebugEnabled) return;',+ ' if (!result || typeof result !== "object") {',+ ' helperDebugLog("cli.result", { requestId, result: describeDebugValue(result) });',+ ' return;',+ ' }',+ ' helperDebugLog("cli.result", {',+ ' requestId,',+ ' successful: result.successful ?? null,',+ ' storedInFile: result.storedInFile ?? false,',+ ' outputFilePath: result.outputFilePath ?? null,',+ ' error: result.error ?? null,',+ ' topLevelKeys: Object.keys(result).slice(0, 20),',+ ' data: "data" in result ? describeDebugValue(result.data) : null,',+ ' });',+ '};',+ 'const detectInvokeAgentMaster = () => {',+ ' if (helperContext.master === "claude" || helperContext.master === "codex" || helperContext.master === "user") {',+ ' return helperContext.master;',+ ' }',+ ' const envKeys = Object.keys(process.env || {});',+ ' if (envKeys.some((key) => key.startsWith("CODEX_"))) return "codex";',+ ' if (envKeys.some((key) => key.startsWith("CLAUDE_"))) return "claude";',+ ' return "user";',+ '};',+ 'const resolveInvokeAgentTarget = (requestedTarget) => {',+ ' if (requestedTarget === "claude" || requestedTarget === "codex") return requestedTarget;',+ ' const detected = requestedTarget === "user" ? "user" : detectInvokeAgentMaster();',+ ' if (detected === "codex" || detected === "claude") return detected;',+ ' if (typeof Bun.which === "function" && Bun.which("codex")) return "codex";',+ ' if (typeof Bun.which === "function" && Bun.which("claude")) return "claude";',+ ' throw new Error("subAgent() could not determine an agent CLI. Current master is user; install codex or claude, or pass { target: \\"codex\\" | \\"claude\\" }.");',+ '};',+ 'const normalizeInvokeAgentOptions = (options = {}) => {',+ ' if (options == null || typeof options !== "object" || Array.isArray(options)) {',+ ' throw new Error("subAgent() options must be an object when provided.");',+ ' }',+ ' if (options.schema !== undefined && options.jsonSchema !== undefined) {',+ ' throw new Error("subAgent() accepts either options.schema or options.jsonSchema, not both.");',+ ' }',+ ' const inputSchema = options.schema ?? options.jsonSchema;',+ ' let structuredSchema;',+ ' if (inputSchema !== undefined) {',+ ' if (inputSchema && typeof inputSchema.safeParse === "function" && inputSchema._def) {',+ ' if (typeof z.toJSONSchema !== "function") {',+ ' throw new Error("subAgent() requires Zod 4 with z.toJSONSchema() when using options.schema.");',+ ' }',+ ' structuredSchema = z.toJSONSchema(inputSchema);',+ ' } else if (typeof inputSchema === "object" && inputSchema !== null && !Array.isArray(inputSchema)) {',+ ' structuredSchema = inputSchema;',+ ' } else {',+ ' throw new Error("subAgent() schema must be a Zod schema or JSON Schema object.");',+ ' }',+ ' }',+ ' return { ...options, structuredSchema };',+ '};',+ 'const runExternalCommandText = async (cmd, spawnOptions = {}) => {',+ ' helperDebugLog("agent.spawn", { command: cmd[0], args: cmd.slice(1) });',+ ' const child = Bun.spawn({',+ ' cmd,',+ ' env: { ...process.env, ...(sharedRunOutputDir ? { COMPOSIO_RUN_OUTPUT_DIR: sharedRunOutputDir } : {}), ...(spawnOptions.env || {}) },',+ ' cwd: spawnOptions.cwd || process.cwd(),',+ ' stdio: ["pipe", "pipe", "pipe"],',+ ' });',+ ' const stdout = child.stdout ? await new Response(child.stdout).text() : "";',+ ' const stderr = child.stderr ? await new Response(child.stderr).text() : "";',+ ' const exitCode = await child.exited;',+ ' if (exitCode !== 0) {',+ ' const details = stderr.trim() || stdout.trim();',+ ' const suffix = details ? `: ${details}` : "";',+ ' helperDebugLog("agent.error", { command: cmd[0], exitCode, stderr: stderr.trim() || undefined });',+ ' throw new Error(`${cmd[0]} failed with exit code ${exitCode}${suffix}`);',+ ' }',+ ' helperDebugLog("agent.done", { command: cmd[0], exitCode, stdoutBytes: stdout.length, stderrBytes: stderr.length });',+ ' return { stdout, stderr, exitCode };',+ '};',+ 'const requireConsumerProxyContext = () => {',+ ' if (!helperContext.apiKey) {',+ ' throw new Error("proxy() requires an authenticated Composio user session.");',+ ' }',+ ' if (!helperContext.orgId || !helperContext.consumerProjectId || !helperContext.consumerUserId) {',+ ' throw new Error("proxy() requires a consumer project context so it can use the consumer project credentials.");',+ ' }',+ ' return {',+ ' apiKey: helperContext.apiKey,',+ ' orgId: helperContext.orgId,',+ ' projectId: helperContext.consumerProjectId,',+ ' userId: helperContext.consumerUserId,',+ ' };',+ '};',+ 'const normalizeProxyToolkit = (toolkit) => {',+ ' if (typeof toolkit !== "string" || toolkit.trim().length === 0) {',+ ' throw new Error("proxy() requires a non-empty toolkit string.");',+ ' }',+ ' return toolkit.trim();',+ '};',+ 'const normalizeFetchHeaders = (headers) => {',+ ' if (!headers) return [];',+ ' return Array.from(new Headers(headers).entries()).map(([name, value]) => ({',+ ' name,',+ ' type: "header",',+ ' value,',+ ' }));',+ '};',+ 'const normalizeFetchBody = async (body) => {',+ ' if (body === undefined || body === null) return undefined;',+ ' if (typeof body === "string") return body;',+ ' if (typeof body === "number" || typeof body === "boolean") return body;',+ ' if (typeof Blob !== "undefined" && body instanceof Blob) {',+ ' return await body.text();',+ ' }',+ ' if (body instanceof ArrayBuffer) {',+ ' return Buffer.from(body).toString("base64");',+ ' }',+ ' if (ArrayBuffer.isView(body)) {',+ ' return Buffer.from(body.buffer, body.byteOffset, body.byteLength).toString("base64");',+ ' }',+ ' return body;',+ '};',+ 'const normalizeFetchInput = async (input, init = {}) => {',+ ' if (typeof Request !== "undefined" && input instanceof Request) {',+ ' throw new Error("proxy() does not support passing a Request instance yet. Pass a URL string and init instead.");',+ ' }',+ ' const endpoint = input instanceof URL ? input.toString() : input;',+ ' if (typeof endpoint !== "string" || endpoint.trim().length === 0) {',+ ' throw new Error("proxy fetch requires a non-empty URL string or URL object.");',+ ' }',+ ' const method = typeof init.method === "string" ? init.method.toUpperCase() : "GET";',+ ' if (!["GET", "POST", "PUT", "DELETE", "PATCH"].includes(method)) {',+ ' throw new Error("proxy fetch only supports GET, POST, PUT, DELETE, PATCH.");',+ ' }',+ ' return {',+ ' endpoint: endpoint.trim(),',+ ' method,',+ ' parameters: normalizeFetchHeaders(init.headers),',+ ' body: await normalizeFetchBody(init.body),',+ ' };',+ '};',+ 'const fetchComposioJson = async (pathname, body) => {',+ ' const auth = requireConsumerProxyContext();',+ ' const response = await fetch(`${composioBaseURL}${pathname}`, {',+ ' method: "POST",',+ ' headers: {',+ ' "content-type": "application/json",',+ ' "x-user-api-key": auth.apiKey,',+ ' "x-org-id": auth.orgId,',+ ' "x-project-id": auth.projectId,',+ ' },',+ ' body: JSON.stringify(body),',+ ' });',+ ' const raw = await response.text();',+ ' const parsed = parseJson(raw);',+ ' if (!response.ok) {',+ ' const detail = typeof parsed === "string" ? parsed : (parsed?.message || parsed?.error || raw.trim() || undefined);',+ ' const error = new Error(`Composio proxy request failed with status ${response.status}${detail ? `: ${detail}` : ""}`);',+ ' Object.assign(error, { status: response.status, response: parsed ?? raw });',+ ' throw error;',+ ' }',+ ' return parsed;',+ '};',+ 'const getProxySessionId = async (toolkit) => {',+ ' const cached = proxySessionCache.get(toolkit);',+ ' if (cached) return cached;',+ ' const auth = requireConsumerProxyContext();',+ ' const created = await fetchComposioJson("/api/v3/tool_router/session", {',+ ' user_id: auth.userId,',+ ' manage_connections: { enable: false },',+ ' toolkits: { enable: [toolkit] },',+ ' });',+ ' const sessionId = created?.session_id;',+ ' if (typeof sessionId !== "string" || sessionId.length === 0) {',+ ' throw new Error("Composio proxy session creation returned no session_id.");',+ ' }',+ ' proxySessionCache.set(toolkit, sessionId);',+ ' return sessionId;',+ '};',+ '',+ 'const runCliJson = async (args) => {',+ ' const requestId = `${args[0] ?? "cli"}#${++perfDebugSeq}`;',+ ' helperDebugLog("cli.start", { requestId, args });',+ ' 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 } : {}),',+ ' ...(sharedRunOutputDir ? { COMPOSIO_RUN_OUTPUT_DIR: sharedRunOutputDir } : {}),',+ ' ...(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 = maybeLoadStoredCliResult(parseJson(stdout));',+ ' const exitCode = await child.exited;',+ ' if (exitCode !== 0) {',+ ' perfDebugLog("error", requestId, { exitCode, stderr: stderr.trim() || undefined });',+ ' helperDebugLog("cli.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 });',+ ' helperDebugLog("cli.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 });',+ ' logCliResultPreview(requestId, result);',+ ' helperDebugLog("cli.done", { requestId, exitCode });',+ ' return result;',+ '};',+ '',+ 'globalThis.search = async (query, options = {}) => {',+ ' helperDebugLog("search.prepare", { 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 = {}) => {',+ ' helperDebugLog("execute.prepare", { slug, hasData: data !== undefined });',+ ' 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);',+ ' }',+ ' const result = await runCliJson(args);',+ ' if (result && typeof result === "object" && result.successful === false) {',+ ' const message = typeof result.error === "string" && result.error.trim().length > 0',+ ' ? result.error.trim()',+ ' : `composio execute ${slug} failed`;',+ ' const error = new Error(message);',+ ' Object.assign(error, { result, slug });',+ ' throw error;',+ ' }',+ ' return result;',+ '};',+ '',+];++const buildRunInvokeAgentHelpersSource = (): ReadonlyArray<string> => [+ 'const toInvokeAgentResponse = (master, target, payload = {}) => ({',+ ' master,',+ ' target,',+ ' result: payload.result ?? null,',+ ' structuredOutput: payload.structuredOutput ?? null,',+ '});',+ 'const invokeClaudeAgent = async (prompt, options) => {',+ ' helperDebugLog("subAgent.prepare", { target: "claude", hasSchema: options.structuredSchema !== undefined });',+ ' const args = ["claude", "--bare", "-p", "--output-format", "json"];',+ ' if (typeof options.model === "string" && options.model.trim().length > 0) {',+ ' args.push("--model", options.model.trim());',+ ' }',+ ' if (options.structuredSchema !== undefined) {',+ ' args.push("--json-schema", JSON.stringify(options.structuredSchema));',+ ' }',+ ' args.push(prompt);',+ ' const result = await runExternalCommandText(args);',+ ' const parsed = parseJson(result.stdout.trim());',+ ' if (!parsed || typeof parsed !== "object") {',+ ' throw new Error("claude returned non-JSON output in subAgent().");',+ ' }',+ ' return toInvokeAgentResponse(detectInvokeAgentMaster(), "claude", {',+ ' result: typeof parsed.result === "string" ? parsed.result : null,',+ ' structuredOutput: parsed.structured_output ?? null,',+ ' });',+ '};',+ 'const invokeCodexAgent = async (prompt, options) => {',+ ' const fs = await import("node:fs");',+ ' const os = await import("node:os");',+ ' const path = await import("node:path");',+ ' const tempDir = sharedRunOutputDir',+ ' ? fs.mkdtempSync(path.join(sharedRunOutputDir, "invoke-agent-"))',+ ' : fs.mkdtempSync(path.join(os.tmpdir(), "composio-invoke-agent-"));',+ ' const outputPath = path.join(tempDir, "last-message.txt");',+ ' const args = ["codex", "exec", "--skip-git-repo-check", "--sandbox", "read-only", "-o", outputPath];',+ ' try {',+ ' helperDebugLog("subAgent.prepare", { target: "codex", hasSchema: options.structuredSchema !== undefined });',+ ' if (typeof options.model === "string" && options.model.trim().length > 0) {',+ ' args.push("--model", options.model.trim());',+ ' }',+ ' if (options.structuredSchema !== undefined) {',+ ' const schemaPath = path.join(tempDir, "schema.json");',+ ' fs.writeFileSync(schemaPath, JSON.stringify(options.structuredSchema), "utf8");',+ ' args.push("--output-schema", schemaPath);',+ ' }',+ ' args.push(prompt);',+ ' await runExternalCommandText(args);',+ ' const text = fs.readFileSync(outputPath, "utf8").trim();',+ ' const parsed = options.structuredSchema ? parseJson(text) : null;',+ ' return toInvokeAgentResponse(detectInvokeAgentMaster(), "codex", {',+ ' result: options.structuredSchema ? null : text,',+ ' structuredOutput: options.structuredSchema ? parsed : null,',+ ' });',+ ' } finally {',+ ' fs.rmSync(tempDir, { recursive: true, force: true });',+ ' }',+ '};',+ 'const subAgentImpl = async (prompt, options = {}) => {',+ ' if (typeof prompt !== "string" || prompt.trim().length === 0) {',+ ' throw new Error("subAgent() requires a non-empty prompt string.");',+ ' }',+ ' const normalizedOptions = normalizeInvokeAgentOptions(options);',+ ' const target = resolveInvokeAgentTarget(normalizedOptions.target);',+ ' helperDebugLog("subAgent.target", { requestedTarget: normalizedOptions.target ?? null, resolvedTarget: target });',+ ' if (target === "claude") {',+ ' return invokeClaudeAgent(prompt.trim(), normalizedOptions);',+ ' }',+ ' return invokeCodexAgent(prompt.trim(), normalizedOptions);',+ '};',+ 'globalThis.subAgent = subAgentImpl;',+ 'Object.defineProperty(globalThis.subAgent, "schema", { value: subAgentSchema });',+ 'globalThis.invokeAgent = subAgentImpl;',+ 'Object.defineProperty(globalThis.invokeAgent, "schema", { value: subAgentSchema });',+ '',+];++const buildRunProxyHelpersSource = (): ReadonlyArray<string> => [+ 'const toProxyResponse = async (result) => {',+ ' const headers = new Headers(result?.headers || {});',+ ' if (result?.binary_data?.url) {',+ ' const binaryResponse = await fetch(result.binary_data.url);',+ ' binaryResponse.headers.forEach((value, key) => {',+ ' if (!headers.has(key)) headers.set(key, value);',+ ' });',+ ' return new Response(binaryResponse.body, {',+ ' status: result.status ?? binaryResponse.status,',+ ' headers,',+ ' });',+ ' }',+ ' if (result?.data === undefined || result?.data === null) {',+ ' return new Response(null, { status: result?.status ?? 200, headers });',+ ' }',+ ' if (typeof result.data === "string") {',+ ' if (!headers.has("content-type")) headers.set("content-type", "text/plain; charset=utf-8");',+ ' return new Response(result.data, { status: result.status ?? 200, headers });',+ ' }',+ ' if (!headers.has("content-type")) headers.set("content-type", "application/json; charset=utf-8");',+ ' return new Response(JSON.stringify(result.data), { status: result.status ?? 200, headers });',+ '};',+ 'globalThis.proxy = async (toolkit) => {',+ ' const normalizedToolkit = normalizeProxyToolkit(toolkit);',+ ' helperDebugLog("proxy.session", { toolkit: normalizedToolkit, cached: proxySessionCache.has(normalizedToolkit) });',+ ' const sessionId = await getProxySessionId(normalizedToolkit);',+ ' const proxyFetch = async (input, init = {}) => {',+ ' const request = await normalizeFetchInput(input, init);',+ ' helperDebugLog("proxy.request", { toolkit: normalizedToolkit, method: request.method, endpoint: request.endpoint });',+ ' const result = await fetchComposioJson(`/api/v3/tool_router/session/${sessionId}/proxy_execute`, {',+ ' toolkit_slug: normalizedToolkit,',+ ' endpoint: request.endpoint,',+ ' method: request.method,',+ ' ...(request.body !== undefined ? { body: request.body } : {}),',+ ' ...(request.parameters?.length',+ ' ? {',+ ' parameters: request.parameters.map((parameter) => ({',+ ' name: parameter.name,',+ ' type: parameter.type,',+ ' value: String(parameter.value),',+ ' })),',+ ' }',+ ' : {}),',+ ' });',+ ' return toProxyResponse(result);',+ ' };',+ ' Object.defineProperty(proxyFetch, "toolkit", { value: normalizedToolkit });',+ ' return proxyFetch;',+ '};',+ 'Object.defineProperty(globalThis.proxy, "schema", { value: proxySchema });',+ '',+ 'Object.defineProperty(globalThis, "__composioConsumerContext", {',+ ' value: helperContext,',+ ' configurable: true,',+ '});',+ '',+];+export const buildRunHelpersSource = (cliPrefix: ReadonlyArray<string>,context: RunHelperContext = {}): string =>[+ 'import { z } from "zod";',+ '',`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,',- '});',- '',+ ...buildRunBaseHelpersSource(),+ ...buildRunInvokeAgentHelpersSource(),+ ...buildRunProxyHelpersSource(),].join('\n');const createRunHelpersPreloadFile = (@@ -215,27 +725,67 @@ const createRunHelpersPreloadFile = () => {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 };+ const runOutputDir =+ typeof context.runOutputDir === 'string' && context.runOutputDir.length > 0+ ? context.runOutputDir+ : path.join(directory, 'artifacts');+ fs.mkdirSync(runOutputDir, { recursive: true });+ fs.writeFileSync(+ preloadPath,+ buildRunHelpersSource(cliPrefix, { ...context, runOutputDir }),+ 'utf8'+ );+ return { directory, preloadPath, runOutputDir };};export const buildRunCommand = ({file,args,preloadPath,+ preloadDirectory,}: {file: Option.Option<string>;args: ReadonlyArray<string>;preloadPath: string;+ preloadDirectory: string;}) => {+ // Use process.execPath directly — the child is spawned with BUN_BE_BUN=1+ // which makes compiled Bun binaries act as a plain Bun runtime.+ // Avoid the `run` subcommand entirely since Bun intercepts it as its own+ // built-in; `bun --preload <file> <script>` works without it.const base = [process.execPath, '--preload', preloadPath];if (Option.isSome(file)) {- return [...base, 'run', file.value, ...withArgDelimiter(args)];+ const filePath = path.resolve(file.value);+ const wrapperFilePath = path.join(+ path.dirname(filePath),+ `.composio-run-${path.basename(preloadDirectory)}${path.extname(filePath) || '.ts'}`+ );+ fs.writeFileSync(+ wrapperFilePath,+ wrapFileSourceForRun(fs.readFileSync(filePath, 'utf8')),+ 'utf8'+ );+ return {+ cmd: [...base, wrapperFilePath, ...withArgDelimiter(args)],+ cleanupPaths: [wrapperFilePath],+ };}const [inlineCode, ...scriptArgs] = args;if (inlineCode) {- return [...base, '--eval', inlineCode, ...withArgDelimiter(scriptArgs)];+ const wrappedInlineCode = [+ '(async () => {',+ wrapInlineCodeForRun(inlineCode),+ '})().then((__composioResult) => {',+ ' if (__composioResult !== undefined) {',+ ' console.log(__composioResult);',+ ' }',+ '});',+ ].join('\n');+ return {+ cmd: [...base, '--eval', wrappedInlineCode, ...withArgDelimiter(scriptArgs)],+ cleanupPaths: [],+ };}throw new Error('Provide inline code or use --file to run a script file.');@@ -267,12 +817,19 @@ const resolveRunHelperContext = () =>consumerUserId: consumerProject.value.consumerUserId,consumerProjectId: consumerProject.value.projectId,consumerProjectName: consumerProject.value.projectName,+ runOutputDir: Option.getOrUndefined(+ yield* resolveCliSessionArtifacts({+ orgId,+ consumerUserId: consumerProject.value.consumerUserId,+ }).pipe(Effect.map(Option.map(artifacts => artifacts.directoryPath)))+ ),} satisfies RunHelperContext;});export const runCmd = Command.make('run', {file,dryRun,+ debug,skipConnectionCheck,skipToolParamsCheck,noVerify,@@ -280,43 +837,59 @@ export const runCmd = Command.make('run', {}).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]',+ 'Run inline TS/JS code or a file with injected Composio helpers that behave like their CLI counterparts.','','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 'const issue = await execute("GITHUB_CREATE_ISSUE", { owner: "composiohq", repo: "composio", title: "Bug report" }); console.log(issue)'`,+ ` composio run --dry-run 'await execute("GMAIL_SEND_EMAIL", { recipient_email: "[email protected]", body: "Hello" })'`,+ ` composio run --debug 'const me = await execute("GITHUB_GET_THE_AUTHENTICATED_USER"); console.log(me)'`,+ ` composio run '`,+ ` const [emails, issues] = await Promise.all([`,+ ` execute("GMAIL_FETCH_EMAILS", { max_results: 5 }),`,+ ` execute("GITHUB_LIST_REPOSITORY_ISSUES", { owner: "composiohq", repo: "composio", state: "open" }),`,+ ` ]);`,+ ` const brief = await subAgent(`,+ ` \`Create a morning brief from these emails and issues.\\n\\n\${emails.prompt()}\\n\\n\${issues.prompt()}\`,`,+ ` {`,+ ` schema: z.object({`,+ ` brief: z.string(),`,+ ` urgentEmails: z.array(z.string()),`,+ ` urgentIssues: z.array(z.string()),`,+ ` }),`,+ ` }`,+ ` );`,+ ` brief.structuredOutput;`,+ ` '`,' 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.',+ 'Injected helpers (behave like their CLI counterparts):',+ ' execute(slug, data?) Same as `composio execute` — returns parsed JSON',+ ' search(query, options?) Same as `composio search` — returns matching tools',+ ' subAgent(prompt, options?) Spawn a powerful sub-agent from the same agent family as your current main agent',+ ' (Codex -> Codex, Claude -> Claude) with optional Zod structured output',+ ' result.prompt() Prompt-safe serialization of a helper result, ideal for subAgent(...)',+ ' const f = await proxy(toolkit) Same as `composio proxy` — returns a fetch function',+ ' Example: const f = await proxy("gmail")',+ ' const me = await f("https://gmail.googleapis.com/gmail/v1/users/me/profile")',+ ' z Injected global from `zod` for structured output schemas',+ '',+ 'All helpers reuse your CLI auth state and linked accounts.','',- '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.',+ 'Flags:',+ ' --debug Log helper steps while the script runs',+ ' --dry-run Preview execute() calls without running them',+ ' --skip-connection-check Skip the linked-account check',+ ' --skip-tool-params-check Skip input validation against cached schema',+ ' --no-verify Skip both checks above','',- 'Advanced:',- ' import { $ } from "bun"',- ' await $`${process.execPath} manage toolkits list`',+ 'See also:',+ ' composio search "<query>" Discover tool slugs before scripting',+ ' composio link <toolkit> Connect accounts before scripting',+ ' composio execute <slug> --get-schema Inspect tool inputs before scripting',].join('\n')),Command.withHandler(- ({ file, dryRun, skipConnectionCheck, skipToolParamsCheck, noVerify, args }) =>+ ({ file, dryRun, debug, skipConnectionCheck, skipToolParamsCheck, noVerify, args }) =>Effect.gen(function* () {const perfDebug = isPerfDebugEnabled();const toolDebug = isToolDebugEnabled();@@ -331,18 +904,40 @@ export const runCmd = Command.make('run', {}}- const preload = createRunHelpersPreloadFile(inferCliInvocationPrefix(), {+ const helperContext: RunHelperContext = {...(yield* resolveRunHelperContext()),+ master: detectMaster(),perfDebug,toolDebug,+ debug,dryRun,skipConnectionCheck,skipToolParamsCheck,noVerify,- });+ };+ const preload = createRunHelpersPreloadFile(inferCliInvocationPrefix(), helperContext);+ let cleanupPaths: ReadonlyArray<string> = [];try {+ yield* appendCliSessionHistory({+ orgId: helperContext.orgId,+ consumerUserId: helperContext.consumerUserId,+ entry: {+ command: 'run',+ status: 'start',+ file: Option.getOrUndefined(file),+ args,+ debug,+ },+ }).pipe(Effect.catchAll(() => Effect.void));+ const runCommand = buildRunCommand({+ file,+ args,+ preloadPath: preload.preloadPath,+ preloadDirectory: preload.directory,+ });+ cleanupPaths = runCommand.cleanupPaths;const child = Bun.spawn({- cmd: buildRunCommand({ file, args, preloadPath: preload.preloadPath }),+ cmd: runCommand.cmd,env: {...process.env,BUN_BE_BUN: '1',@@ -353,9 +948,11 @@ export const runCmd = Command.make('run', {});const exitCode = yield* Effect.promise(() => child.exited);- fs.rmSync(preload.directory, { recursive: true, force: true });process.exit(exitCode);} finally {+ for (const cleanupPath of cleanupPaths) {+ fs.rmSync(cleanupPath, { force: true });+ }fs.rmSync(preload.directory, { recursive: true, force: true });}})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 30e85ee33..772d5eb03 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,14 +1,11 @@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, Exit, Fiber, Cause } from 'effect';-import { FileSystem } from '@effect/platform';-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 { parseJsonIsh } from 'src/utils/parse-json-ish';import { requireAuth } from 'src/effects/require-auth';+import { resolveOptionalTextInput } from 'src/effects/resolve-optional-text-input';import {getCachedToolInputDefinition,getOrFetchToolInputDefinition,@@ -19,19 +16,11 @@ import {validateToolInputArgumentsWithDefinition,} from 'src/services/tool-input-validation';import { TerminalUI } from 'src/services/terminal-ui';-import {- ActionExecuteConnectedAccountNotFoundError,- ToolsExecutor,-} from 'src/services/tools-executor';+import { ToolsExecutor } 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 { handleHttpServerError } from 'src/effects/handle-http-error';import { formatToolInputParameters } from '../format';import { ComposioClientSingleton } from 'src/services/composio-clients';@@ -45,6 +34,15 @@ import {getFreshConsumerConnectedToolkitsFromCache,refreshConsumerConnectedToolkitsCache,} from 'src/services/consumer-short-term-cache';+import {+ appendCliSessionHistory,+ resolveCliSessionArtifacts,+} from 'src/services/cli-session-artifacts';+import { storeCliSessionArtifact } from 'src/services/cli-session-artifacts';+import {+ ComposioNoActiveConnectionError,+ mapComposioError,+} from 'src/services/composio-error-overrides';const slug = Args.text({ name: 'slug' }).pipe(Args.withDescription('Tool slug (e.g. "GITHUB_CREATE_ISSUE")')@@ -66,58 +64,37 @@ 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 getSchema = Options.boolean('get-schema').pipe(+ Options.withDescription('Fetch and print the raw tool schema without executing'),+ Options.withDefault(false)+);+const dryRun = Options.boolean('dry-run').pipe(+ Options.withDescription('Validate and preview the tool call without executing'),+ Options.withDefault(false)+);const skipConnectionCheck = Options.boolean('skip-connection-check').pipe(+ Options.withDescription('Skip the linked-account check'),Options.withDefault(false));const skipToolParamsCheck = Options.boolean('skip-tool-params-check').pipe(+ Options.withDescription('Skip input validation against cached schema'),+ Options.withDefault(false)+);+const noVerify = Options.boolean('no-verify').pipe(+ Options.withDescription('Skip both connection and input validation checks'),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;-- if (Option.isSome(input)) {- const value = input.value.trim();- if (value === '-') {- return yield* readStdin;- }- if (value.startsWith('@')) {- const filePath = value.slice(1).trim();- if (!filePath) {- return yield* Effect.fail(new Error('Missing file path after "@" in --data'));- }- return yield* fs.readFileString(filePath, 'utf-8');- }- return value;- }-- const piped = yield* readStdinIfPiped;- if (Option.isSome(piped)) {- return piped.value;- }-+ resolveOptionalTextInput(input, {// Default to empty object when no data provided (e.g. tools with no required args)- return '{}';+ missingValue: '{}',});const parseArguments = (raw: string) =>Effect.gen(function* () {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;- }- }- },+ try: () => parseJsonIsh(raw),catch: () =>new Error('Invalid JSON input. Provide JSON or a JS-style object literal, e.g. -d \'{ "key": "value" }\''@@ -162,17 +139,6 @@ const connectionTips = (toolSlug: string, surface: 'root' | 'manage' | 'dev') =>].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_' });@@ -227,85 +193,65 @@ type StoredExecuteOutputSummary = {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');+const persistLargeExecuteOutput = (toolSlug: string, json: string, sharedDirectory?: string) =>+ Effect.gen(function* () {+ const outputFilePath = yield* storeCliSessionArtifact({+ contents: json,+ name: `${toolSlug}_OUTPUT`,+ extension: 'json',+ directoryPath: sharedDirectory?.trim() || process.env.COMPOSIO_RUN_OUTPUT_DIR?.trim(),+ });- return {- successful: true,- error: null,- logId: '',- storedInFile: true,- tokenCount: getExecuteOutputEncoder().encode(json).length,- outputFilePath,- };-};+ return {+ successful: true,+ error: null,+ logId: '',+ storedInFile: true,+ tokenCount: getExecuteOutputEncoder().encode(json).length,+ outputFilePath,+ } satisfies StoredExecuteOutputSummary;+ });const perfDebugEpoch = Date.now();const perfDebugLog = (label: string, details: Record<string, unknown> = {}) => {if (!isPerfDebugEnabled()) return;- console.error(+ process.stderr.write(`[perf] ${JSON.stringify({phase: 'event',label,elapsedMs: Date.now() - perfDebugEpoch,...details,- })}`+ })}\n`);};const toolDebugLog = (label: string, details: Record<string, unknown> = {}) => {if (!isToolDebugEnabled()) return;- console.error(`[tool-debug] ${JSON.stringify({ label, ...details })}`);+ process.stderr.write(`[tool-debug] ${JSON.stringify({ label, ...details })}\n`);};-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>();-- while (current && typeof current === 'object' && !seen.has(current)) {- seen.add(current);-- if (current instanceof Error) {- return current;- }-- if ('error' in current) {- current = (current as { error?: unknown }).error;- continue;- }- if ('cause' in current) {- current = (current as { cause?: unknown }).cause;- continue;+const prepareExecuteOutput = (+ toolSlug: string,+ result: ToolExecuteResponse,+ sharedDirectory?: string+) =>+ Effect.gen(function* () {+ const json = serializeExecuteOutput(result);+ const tokenCount = getExecuteOutputEncoder().encode(json).length;+ if (tokenCount <= EXECUTE_INLINE_OUTPUT_TOKEN_THRESHOLD) {+ return {+ kind: 'inline' as const,+ json,+ };}- break;- }- return current;-};+ return {+ kind: 'file' as const,+ summary: {+ ...(yield* persistLargeExecuteOutput(toolSlug, json, sharedDirectory)),+ logId: result.logId,+ } satisfies StoredExecuteOutputSummary,+ };+ });export const showToolsExecuteInputHelp = (toolSlug: string) =>Effect.gen(function* () {@@ -356,7 +302,8 @@ const handleExecutionError = (context: { toolSlug: string; surface: 'root' | 'manage' | 'dev' }) =>Effect.gen(function* () {- const normalized = normalizeError(error);+ const mapped = mapComposioError({ error, toolSlug: context.toolSlug });+ const normalized = mapped.normalized;if (normalized instanceof ToolInputValidationError) {yield* ui.log.error(`Input validation failed for ${context.toolSlug}`);yield* ui.note(@@ -368,48 +315,25 @@ const handleExecutionError = (return { error: normalized.message, slug: context.toolSlug };}- const connAccountDetails =- normalized instanceof ActionExecuteConnectedAccountNotFoundError- ? normalized.details- : undefined;-- const apiDetails =- extractApiErrorDetails(error) ??- 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);+ const apiDetails = mapped.apiDetails;+ const slugValue = mapped.slugValue;++ if (normalized instanceof ComposioNoActiveConnectionError) {+ yield* ui.log.error(mapped.message);if (toolkitFromToolSlug(context.toolSlug)) {yield* ui.note(connectionTips(context.toolSlug, context.surface), 'Tips');}- return { error: rewrittenMessage, slug: slugValue ?? context.toolSlug };+ return { error: mapped.message, slug: slugValue ?? context.toolSlug };}- yield* ui.log.error(message);+ yield* ui.log.error(mapped.message);- const detailsObject =- apiDetails ??- (normalized instanceof ActionExecuteConnectedAccountNotFoundError &&- normalized.details &&- typeof normalized.details === 'object'- ? (normalized.details as object)- : undefined);+ const detailsObject = apiDetails;if (detailsObject) {yield* ui.note(formatUnknownObject(redactRequestId(detailsObject)), 'Error details');}- if (normalized instanceof ActionExecuteConnectedAccountNotFoundError) {- yield* ui.note(connectionTips(context.toolSlug, context.surface), 'Tips');- }-- return { error: message, slug: slugValue };+ return { error: mapped.message, slug: slugValue };});class ToolExecutionError {@@ -592,6 +516,7 @@ type ResolvedExecuteContext = {readonly args: Record<string, unknown>;readonly resolvedUserId: string;readonly executeParams: ToolExecuteParams;+ readonly executeOutputDir?: string;};const emitCachedSchema = (@@ -634,7 +559,7 @@ const resolveExecuteContext = (params: RunToolsExecuteParams) =>const userContext = yield* ComposioUserContext;const projectContext = yield* ProjectContext;- const input = yield* resolveInput(params.data);+ const input = (yield* resolveInput(params.data)) ?? '{}';const args = yield* parseArguments(input);const localProjectContext = yield* projectContext.resolve.pipe(Effect.catchAll(() => Effect.succeed(Option.none()))@@ -662,6 +587,15 @@ const resolveExecuteContext = (params: RunToolsExecuteParams) =>orgId: resolvedProject.orgId,projectId: resolvedProject.projectId,});+ const executeOutputDir =+ process.env.COMPOSIO_RUN_OUTPUT_DIR?.trim() ||+ Option.getOrUndefined(+ yield* resolveCliSessionArtifacts({+ orgId: resolvedProject.projectType === 'CONSUMER' ? resolvedProject.orgId : undefined,+ consumerUserId:+ resolvedProject.projectType === 'CONSUMER' ? resolvedProject.consumerUserId : undefined,+ }).pipe(Effect.map(Option.map(artifacts => artifacts.directoryPath)))+ );return {ui,@@ -669,6 +603,7 @@ const resolveExecuteContext = (params: RunToolsExecuteParams) =>resolvedProject,args,resolvedUserId: resolvedUserId.value,+ executeOutputDir,executeParams: {userId: resolvedUserId.value,arguments: args,@@ -784,6 +719,7 @@ const runExecuteWithSpinner = (params: {readonly args: Record<string, unknown>;readonly resolvedUserId: string;readonly executeParams: ToolExecuteParams;+ readonly executeOutputDir?: string;readonly skipToolParamsCheck: boolean;readonly noVerify: boolean;}) =>@@ -843,6 +779,22 @@ const runExecuteWithSpinner = (params: {: 'No tool was executed. Arguments were validated locally only.');yield* params.ui.output(JSON.stringify(summary, ciRedactReplacer, 2));+ yield* appendCliSessionHistory({+ orgId:+ params.resolvedProject.projectType === 'CONSUMER'+ ? params.resolvedProject.orgId+ : undefined,+ consumerUserId:+ params.resolvedProject.projectType === 'CONSUMER'+ ? params.resolvedProject.consumerUserId+ : undefined,+ entry: {+ command: 'execute',+ status: 'dry-run',+ slug: params.slug,+ arguments: params.args,+ },+ }).pipe(Effect.catchAll(() => Effect.void));return;}@@ -872,6 +824,23 @@ const runExecuteWithSpinner = (params: {yield* params.ui.output(JSON.stringify({ successful: false, ...summary }, ciRedactReplacer, 2));+ yield* appendCliSessionHistory({+ orgId:+ params.resolvedProject.projectType === 'CONSUMER'+ ? params.resolvedProject.orgId+ : undefined,+ consumerUserId:+ params.resolvedProject.projectType === 'CONSUMER'+ ? params.resolvedProject.consumerUserId+ : undefined,+ entry: {+ command: 'execute',+ status: 'error',+ slug: params.slug,+ arguments: params.args,+ error: summary.error,+ },+ }).pipe(Effect.catchAll(() => Effect.void));return yield* Effect.fail(new ToolExecutionError(summary.error));}@@ -906,17 +875,55 @@ const runExecuteWithSpinner = (params: {? ` (logId: ${redact({ value: result.logId, prefix: 'log_' })})`: '';yield* spinner.stop(`Execution successful${logId}`);- const output = prepareExecuteOutput(result);+ const output = yield* prepareExecuteOutput(params.slug, result, params.executeOutputDir);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));+ yield* appendCliSessionHistory({+ orgId:+ params.resolvedProject.projectType === 'CONSUMER'+ ? params.resolvedProject.orgId+ : undefined,+ consumerUserId:+ params.resolvedProject.projectType === 'CONSUMER'+ ? params.resolvedProject.consumerUserId+ : undefined,+ entry: {+ command: 'execute',+ status: 'success',+ slug: params.slug,+ arguments: params.args,+ storedInFile: true,+ outputFilePath: output.summary.outputFilePath,+ tokenCount: output.summary.tokenCount,+ logId: result.logId,+ },+ }).pipe(Effect.catchAll(() => Effect.void));return;}yield* params.ui.log.message(`Response\n${output.json}`);yield* params.ui.output(output.json);+ yield* appendCliSessionHistory({+ orgId:+ params.resolvedProject.projectType === 'CONSUMER'+ ? params.resolvedProject.orgId+ : undefined,+ consumerUserId:+ params.resolvedProject.projectType === 'CONSUMER'+ ? params.resolvedProject.consumerUserId+ : undefined,+ entry: {+ command: 'execute',+ status: 'success',+ slug: params.slug,+ arguments: params.args,+ storedInFile: false,+ logId: result.logId,+ },+ }).pipe(Effect.catchAll(() => Effect.void));}));});@@ -1011,24 +1018,23 @@ export const toolsCmd$Execute = Command.make().pipe(Command.withDescription([- '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.',+ 'Execute a tool by slug. Validates inputs against cached schemas and checks connections',+ 'automatically — just try it and it will tell you what to fix.','','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',+ " composio execute GMAIL_SEND_EMAIL --dry-run -d '{ ... }' Preview without executing",+ ' composio execute GMAIL_SEND_EMAIL --get-schema Fetch and print the input schema',+ '',+ 'Flags:',+ ' --skip-connection-check Skip the linked-account check',+ ' --skip-tool-params-check Skip input validation against cached schema',+ ' --no-verify Skip both checks above','',- '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>',+ 'See also:',+ ' composio search "<query>" Find tool slugs by use case',+ ' composio tools info <slug> Schema summary with jq hints',+ ' composio link <toolkit> Connect an account for a toolkit',].join('\n')));@@ -1053,24 +1059,23 @@ export const rootToolsCmd$Execute = Command.make().pipe(Command.withDescription([- '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.',+ 'Execute a tool by slug. Validates inputs against cached schemas and checks connections',+ 'automatically — just try it and it will tell you what to fix.','','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',+ " composio execute GMAIL_SEND_EMAIL --dry-run -d '{ ... }' Preview without executing",+ ' composio execute GMAIL_SEND_EMAIL --get-schema Fetch and print the input schema',+ '',+ 'Flags:',+ ' --skip-connection-check Skip the linked-account check',+ ' --skip-tool-params-check Skip input validation against cached schema',+ ' --no-verify Skip both checks above','',- '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>',+ 'See also:',+ ' composio search "<query>" Find tool slugs by use case',+ ' composio tools info <slug> Schema summary with jq hints',+ ' composio link <toolkit> Connect an account for a toolkit',].join('\n')));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 ad8330f8e..27b577a72 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@@ -15,6 +15,7 @@ import {} from 'src/services/command-project';import { commandHintExample, commandHintStep } from 'src/services/command-hints';import { primeConsumerConnectedToolkitsCacheInBackground } from 'src/services/consumer-short-term-cache';+import { appendCliSessionHistory } from 'src/services/cli-session-artifacts';const query = Args.text({ name: 'query' }).pipe(Args.withDescription(@@ -66,7 +67,7 @@ const runToolsSearch = (params: {.filter(Boolean): undefined;- const searchResponse = yield* ui.withSpinner(+ const searchResult = yield* ui.withSpinner(`Searching tools for "${params.query}"...`,Effect.gen(function* () {const resolvedProject = yield* resolveCommandProject({@@ -101,13 +102,25 @@ const runToolsSearch = (params: {const { sessionId } = yield* resolveToolRouterSession(client, resolvedUserId.value, {toolkits: toolkitList,});- return yield* Effect.tryPromise(() =>+ const searchResponse = yield* Effect.tryPromise(() =>client.toolRouter.session.search(sessionId, {queries: [{ use_case: params.query }],}));+ return {+ searchResponse,+ historyScope:+ resolvedProject.projectType === 'CONSUMER'+ ? {+ orgId: resolvedProject.orgId,+ consumerUserId: resolvedUserId.value,+ toolRouterSessionId: sessionId,+ }+ : undefined,+ };}));+ const searchResponse = searchResult.searchResponse;const toolkitSet = toolkitList && toolkitList.length > 0 ? new Set(toolkitList) : undefined;@@ -228,6 +241,19 @@ const runToolsSearch = (params: {...searchResponse,CTA: cta,};+ yield* appendCliSessionHistory({+ orgId: searchResult.historyScope?.orgId,+ consumerUserId: searchResult.historyScope?.consumerUserId,+ entry: {+ command: 'search',+ query: params.query,+ toolkitFilter: toolkitList ?? [],+ limit: clampedLimit,+ resultCount: toolsList.length,+ toolRouterSessionId: searchResult.historyScope?.toolRouterSessionId,+ nextSteps: searchResponse.next_steps_guidance,+ },+ }).pipe(Effect.catchAll(() => Effect.void));yield* ui.output(JSON.stringify(outputForJq, null, 2));});@@ -239,12 +265,17 @@ export const toolsCmd$Search = Command.make().pipe(Command.withDescription([- 'Semantically search tools by use case; returns best-fit tools plus recommended usage guidance.',+ 'Find tools by use case. Returns matching tools with slugs you can pass directly to `execute`.','',- 'Related:',- ' composio run \'const result = await execute("TOOL_SLUG", { ... }); console.log(result)\'',- ' composio link <toolkit>',- " composio execute <slug> -d '{}'",+ 'Examples:',+ ' composio search "send an email"',+ ' composio search "create issue" --toolkits github',+ ' composio search "list calendar events" --limit 5',+ '',+ 'Next steps:',+ " composio execute <slug> -d '{ ... }' Run a tool from the results",+ " composio tools info <slug> Inspect a tool's schema before executing",+ ' composio link <toolkit> Connect an account if execute tells you to',].join('\n')));@@ -264,12 +295,17 @@ export const rootToolsCmd$Search = Command.make().pipe(Command.withDescription([- 'Semantically search tools by use case; returns best-fit tools plus recommended usage guidance.',+ 'Find tools by use case. Returns matching tools with slugs you can pass directly to `execute`.',+ '',+ 'Examples:',+ ' composio search "send an email"',+ ' composio search "create issue" --toolkits github',+ ' composio search "list calendar events" --limit 5','',- 'Related:',- ' composio run \'const result = await execute("TOOL_SLUG", { ... }); console.log(result)\'',- ' composio link <toolkit>',- " composio execute <slug> -d '{}'",+ 'Next steps:',+ " composio execute <slug> -d '{ ... }' Run a tool from the results",+ " composio tools info <slug> Inspect a tool's schema before executing",+ ' composio link <toolkit> Connect an account if execute tells you to',].join('\n')));diff --git a/ts/packages/cli/src/effects/resolve-optional-text-input.ts b/ts/packages/cli/src/effects/resolve-optional-text-input.tsnew file mode 100644index 000000000..b2020a140--- /dev/null+++ b/ts/packages/cli/src/effects/resolve-optional-text-input.ts@@ -0,0 +1,38 @@+import { FileSystem } from '@effect/platform';+import { Effect, Option } from 'effect';++import { readStdin, readStdinIfPiped } from 'src/effects/read-stdin';++type ResolveOptionalTextInputOptions = {+ readonly missingValue?: string;+};++export const resolveOptionalTextInput = (+ input: Option.Option<string>,+ options: ResolveOptionalTextInputOptions = {}+) =>+ Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;++ if (Option.isSome(input)) {+ const value = input.value.trim();+ if (value === '-') {+ return yield* readStdin;+ }+ if (value.startsWith('@')) {+ const filePath = value.slice(1).trim();+ if (!filePath) {+ return yield* Effect.fail(new Error('Missing file path after "@" in --data'));+ }+ return yield* fs.readFileString(filePath, 'utf-8');+ }+ return value;+ }++ const piped = yield* readStdinIfPiped;+ if (Option.isSome(piped)) {+ return piped.value;+ }++ return options.missingValue;+ });diff --git a/ts/packages/cli/src/services/cli-session-artifacts.ts b/ts/packages/cli/src/services/cli-session-artifacts.tsnew file mode 100644index 000000000..bfd90a7c3--- /dev/null+++ b/ts/packages/cli/src/services/cli-session-artifacts.ts@@ -0,0 +1,88 @@+import fs from 'node:fs';+import path from 'node:path';+import { Effect, Option } from 'effect';+import { getOrCreateProbablyMyCliSessionIdForCurrentCwd } from 'src/services/consumer-short-term-cache';++const CLI_SESSION_ARTIFACTS_ROOT = '/tmp/composio';+const SESSION_HISTORY_FILE = 'session-history.jsonl';++export type CliSessionArtifacts = {+ readonly sessionId: string;+ readonly directoryPath: string;+ readonly historyFilePath: string;+};++const randomToken = (length = 8) => crypto.randomUUID().replace(/-/g, '').slice(0, length);++const sanitizeArtifactName = (value: string): string =>+ value.replace(/[^A-Z0-9_]+/gi, '_').replace(/^_+|_+$/g, '') || 'ARTIFACT';++export const resolveCliSessionArtifacts = (params?: {+ readonly orgId?: string;+ readonly consumerUserId?: string;+}) =>+ Effect.gen(function* () {+ const sessionIdOption = yield* getOrCreateProbablyMyCliSessionIdForCurrentCwd(params);+ if (Option.isNone(sessionIdOption)) {+ return Option.none<CliSessionArtifacts>();+ }++ const directoryPath = path.join(CLI_SESSION_ARTIFACTS_ROOT, sessionIdOption.value);+ fs.mkdirSync(directoryPath, { recursive: true });+ return Option.some({+ sessionId: sessionIdOption.value,+ directoryPath,+ historyFilePath: path.join(directoryPath, SESSION_HISTORY_FILE),+ } satisfies CliSessionArtifacts);+ });++export const appendCliSessionHistory = (params: {+ readonly entry: Record<string, unknown>;+ readonly orgId?: string;+ readonly consumerUserId?: string;+}) =>+ Effect.gen(function* () {+ const artifactsOption = yield* resolveCliSessionArtifacts({+ orgId: params.orgId,+ consumerUserId: params.consumerUserId,+ });+ if (Option.isNone(artifactsOption)) {+ return;+ }++ const line = JSON.stringify({+ timestamp: new Date().toISOString(),+ sessionId: artifactsOption.value.sessionId,+ ...params.entry,+ });+ fs.appendFileSync(artifactsOption.value.historyFilePath, `${line}\n`, 'utf8');+ });++export const storeCliSessionArtifact = (params: {+ readonly contents: string;+ readonly name: string;+ readonly extension?: string;+ readonly directoryPath?: string;+ readonly orgId?: string;+ readonly consumerUserId?: string;+}) =>+ Effect.gen(function* () {+ const directoryPath =+ params.directoryPath ||+ Option.getOrUndefined(+ yield* resolveCliSessionArtifacts({+ orgId: params.orgId,+ consumerUserId: params.consumerUserId,+ }).pipe(Effect.map(Option.map(artifacts => artifacts.directoryPath)))+ ) ||+ path.join(CLI_SESSION_ARTIFACTS_ROOT, `adhoc_${randomToken(12)}`);++ fs.mkdirSync(directoryPath, { recursive: true });+ const extension = (params.extension ?? 'json').replace(/^\.+/, '') || 'json';+ const filePath = path.join(+ directoryPath,+ `${sanitizeArtifactName(params.name)}_${randomToken()}.${extension}`+ );+ fs.writeFileSync(filePath, params.contents, 'utf8');+ return filePath;+ });diff --git a/ts/packages/cli/src/services/composio-error-overrides.ts b/ts/packages/cli/src/services/composio-error-overrides.tsnew file mode 100644index 000000000..1048a10c2--- /dev/null+++ b/ts/packages/cli/src/services/composio-error-overrides.ts@@ -0,0 +1,185 @@+import {+ extractApiErrorDetails,+ extractMessage,+ extractSlug,+ type ApiErrorDetails,+} from 'src/utils/api-error-extraction';++const NO_CONNECTION_SLUGS: ReadonlySet<string> = new Set([+ 'ActionExecute_ConnectedAccountNotFound',+ 'ToolRouterV2_NoActiveConnection',+]);++const extractNestedDetails = (value: unknown): unknown => {+ let current: unknown = value;+ const seen = new Set<unknown>();++ while (current && typeof current === 'object' && !seen.has(current)) {+ seen.add(current);++ if ('details' in current) {+ const details = (current as { details?: unknown }).details;+ if (details !== undefined) {+ return details;+ }+ }++ if ('error' in current) {+ current = (current as { error?: unknown }).error;+ continue;+ }+ if ('cause' in current) {+ current = (current as { cause?: unknown }).cause;+ continue;+ }+ break;+ }++ return undefined;+};++export const normalizeCliError = (error: unknown): unknown => {+ let current: unknown = error;+ const seen = new Set<unknown>();++ while (current && typeof current === 'object' && !seen.has(current)) {+ seen.add(current);++ if (current instanceof Error) {+ return current;+ }++ if ('error' in current) {+ current = (current as { error?: unknown }).error;+ continue;+ }+ if ('cause' in current) {+ current = (current as { cause?: unknown }).cause;+ continue;+ }+ break;+ }++ return current;+};++export const isNoConnectionSlug = (slug: string | undefined | null): boolean =>+ slug != null && NO_CONNECTION_SLUGS.has(slug);++export const isNoActiveConnectionApiError = (+ details: { code?: number; slug?: string } | undefined+): boolean => details?.code === 4302 || isNoConnectionSlug(details?.slug);++export const buildNoActiveConnectionMessage = (params: {+ readonly toolkit?: string;+ readonly toolSlug?: string;+}) => {+ if (params.toolkit) {+ return `No active connection found for toolkit "${params.toolkit}". Run \`composio link ${params.toolkit}\`, then retry.`;+ }+ if (params.toolSlug) {+ const idx = params.toolSlug.indexOf('_');+ const toolkit =+ idx <= 0 ? params.toolSlug.toLowerCase() : params.toolSlug.slice(0, idx).toLowerCase();+ if (toolkit !== 'composio') {+ return `No active connection found for toolkit "${toolkit}". Run \`composio link ${toolkit}\`, then retry.`;+ }+ }+ return 'No active connection found for this tool call. Link the required toolkit/app, then retry.';+};++export class ComposioNoActiveConnectionError extends Error {+ readonly details: unknown;+ readonly apiDetails?: ApiErrorDetails;+ readonly toolkit?: string;+ readonly toolSlug?: string;++ constructor(params: {+ readonly details: unknown;+ readonly apiDetails?: ApiErrorDetails;+ readonly toolkit?: string;+ readonly toolSlug?: string;+ }) {+ super(+ buildNoActiveConnectionMessage({+ toolkit: params.toolkit,+ toolSlug: params.toolSlug,+ })+ );+ this.name = 'ComposioNoActiveConnectionError';+ this.details = params.details;+ this.apiDetails = params.apiDetails;+ this.toolkit = params.toolkit;+ this.toolSlug = params.toolSlug;+ }+}++export const mapComposioError = (params: {+ readonly error: unknown;+ readonly toolkit?: string;+ readonly toolSlug?: string;+}) => {+ const normalized = normalizeCliError(params.error);+ const nestedDetails = extractNestedDetails(params.error) ?? extractNestedDetails(normalized);+ const apiDetails =+ extractApiErrorDetails(params.error) ??+ extractApiErrorDetails(nestedDetails) ??+ extractApiErrorDetails(normalized) ??+ (normalized instanceof ComposioNoActiveConnectionError ? normalized.apiDetails : undefined);+ const slugValue =+ apiDetails?.slug ??+ extractSlug(nestedDetails) ??+ extractSlug(params.error) ??+ extractSlug(normalized) ??+ (normalized instanceof ComposioNoActiveConnectionError+ ? normalized.apiDetails?.slug+ : undefined);++ if (+ normalized instanceof ComposioNoActiveConnectionError ||+ isNoActiveConnectionApiError(apiDetails) ||+ isNoConnectionSlug(slugValue)+ ) {+ const mapped =+ normalized instanceof ComposioNoActiveConnectionError+ ? normalized+ : new ComposioNoActiveConnectionError({+ details: apiDetails ?? params.error,+ apiDetails,+ toolkit: params.toolkit,+ toolSlug: params.toolSlug,+ });++ return {+ normalized: mapped,+ apiDetails,+ slugValue,+ message: mapped.message,+ override: {+ kind: 'no_active_connection' as const,+ error: mapped,+ },+ };+ }++ return {+ normalized,+ apiDetails,+ slugValue,+ message:+ extractMessage(apiDetails) ??+ extractMessage(nestedDetails) ??+ extractMessage(normalized) ??+ 'Unknown error',+ override: null,+ };+};++export const mapOnlyComposioOverrideError = (params: {+ readonly error: unknown;+ readonly toolkit?: string;+ readonly toolSlug?: string;+}): unknown => {+ const mapped = mapComposioError(params);+ return mapped.override ? mapped.normalized : params.error;+};diff --git a/ts/packages/cli/src/services/consumer-short-term-cache.ts b/ts/packages/cli/src/services/consumer-short-term-cache.tsindex f8d263aeb..e285d4007 100644--- a/ts/packages/cli/src/services/consumer-short-term-cache.ts+++ b/ts/packages/cli/src/services/consumer-short-term-cache.ts@@ -11,8 +11,8 @@ 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;+const CACHE_TTL_MS = 15 * 60 * 1000;+const SEARCH_SESSION_EXTENSION_MS = 5 * 60 * 1000;type CacheEntry = {readonly toolkits: ReadonlyArray<string>;@@ -220,3 +220,39 @@ export const primeConsumerConnectedToolkitsCacheInBackground = (params?: {Effect.forkDaemon,Effect.asVoid);++export const getOrCreateProbablyMyCliSessionIdForCurrentCwd = (params?: {+ readonly orgId?: string;+ readonly consumerUserId?: string;+}) =>+ Effect.gen(function* () {+ const scope = yield* resolveConsumerScope(params);+ if (!scope?.consumerUserId) {+ return Option.none<string>();+ }++ const proc = yield* NodeProcess;+ const state = yield* readCache();+ const key = cacheKey(scope.orgId, scope.consumerUserId);+ const currentEntry = state[key];+ const searchSessionFields = resolveSearchSessionMetadata({+ currentEntry,+ cwd: proc.cwd,+ });+ const currentCwdHash = cwdHash(proc.cwd);+ const session = searchSessionFields.probablyMyCliSessionsByCwdHash[currentCwdHash];+ if (!session) {+ return Option.none<string>();+ }++ yield* writeCache({+ ...state,+ [key]: {+ toolkits: currentEntry?.toolkits ?? [],+ expiresAt: currentEntry?.expiresAt ?? new Date(Date.now() + CACHE_TTL_MS).toISOString(),+ ...searchSessionFields,+ },+ });++ return Option.some(session.id);+ });diff --git a/ts/packages/cli/src/services/master-detector.ts b/ts/packages/cli/src/services/master-detector.tsnew file mode 100644index 000000000..19bd0b5aa--- /dev/null+++ b/ts/packages/cli/src/services/master-detector.ts@@ -0,0 +1,14 @@+export type MasterKind = 'claude' | 'codex' | 'user';++const hasEnvPrefix = (env: NodeJS.ProcessEnv, prefix: string): boolean =>+ Object.keys(env).some(key => key.startsWith(prefix));++export const detectMaster = (env: NodeJS.ProcessEnv = process.env): MasterKind => {+ if (hasEnvPrefix(env, 'CODEX_')) {+ return 'codex';+ }+ if (hasEnvPrefix(env, 'CLAUDE_')) {+ return 'claude';+ }+ return 'user';+};diff --git a/ts/packages/cli/src/services/tools-executor.ts b/ts/packages/cli/src/services/tools-executor.tsindex b3746c994..7de9ac8bc 100644--- a/ts/packages/cli/src/services/tools-executor.ts+++ b/ts/packages/cli/src/services/tools-executor.ts@@ -8,30 +8,9 @@ import type {import { ComposioClientSingleton } from 'src/services/composio-clients';import { createToolRouterSession } from 'src/effects/create-tool-router-session';import {- extractMessage,- extractSlug,- extractApiErrorDetails,-} from 'src/utils/api-error-extraction';--/** Error slugs that indicate a missing connected account / no active connection. */-const NO_CONNECTION_SLUGS: ReadonlySet<string> = new Set([- 'ActionExecute_ConnectedAccountNotFound',- 'ToolRouterV2_NoActiveConnection',-]);--export const isNoConnectionSlug = (slug: string | undefined | null): boolean =>- slug != null && NO_CONNECTION_SLUGS.has(slug);--export class ActionExecuteConnectedAccountNotFoundError extends Error {- readonly details: unknown;-- constructor(details: unknown) {- const message = extractMessage(details) ?? 'No connected account found for this user/toolkit.';- super(message);- this.name = 'ActionExecuteConnectedAccountNotFoundError';- this.details = details;- }-}+ ComposioNoActiveConnectionError,+ mapComposioError,+} from 'src/services/composio-error-overrides';/*** Parameters accepted by the Tool Router-based executor.@@ -133,12 +112,9 @@ export const ToolsExecutorLive = Layer.effect(return normalizeResponse(raw);}).pipe(Effect.catchAll((error): Effect.Effect<never, unknown> => {- const apiDetails = extractApiErrorDetails(error);- const slugValue = apiDetails?.slug ?? extractSlug(error);- if (isNoConnectionSlug(slugValue)) {- return Effect.fail(- new ActionExecuteConnectedAccountNotFoundError(apiDetails ?? error)- );+ const mapped = mapComposioError({ error, toolSlug: slug });+ if (mapped.normalized instanceof ComposioNoActiveConnectionError) {+ return Effect.fail(mapped.normalized);}return Effect.fail(error);})diff --git a/ts/packages/cli/src/utils/parse-json-ish.ts b/ts/packages/cli/src/utils/parse-json-ish.tsnew file mode 100644index 000000000..679532ed0--- /dev/null+++ b/ts/packages/cli/src/utils/parse-json-ish.ts@@ -0,0 +1,13 @@+import { parse as parseJsonWithComments } from 'comment-json';++export const parseJsonIsh = (raw: string): unknown => {+ 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;+ }+ }+};diff --git a/ts/packages/cli/test/__utils__/services/test-layer.ts b/ts/packages/cli/test/__utils__/services/test-layer.tsindex f5eb89a6a..d67af21b2 100644--- a/ts/packages/cli/test/__utils__/services/test-layer.ts+++ b/ts/packages/cli/test/__utils__/services/test-layer.ts@@ -51,10 +51,12 @@ import type {SessionLinkResponse,SessionSearchResponse,SessionToolkitsResponse,+ SessionProxyExecuteResponse,SessionCreateParams,SessionExecuteParams,SessionExecuteMetaParams,SessionLinkParams,+ SessionProxyExecuteParams,SessionSearchParams,SessionToolkitsParams,} from '@composio/client/resources/tool-router';@@ -164,6 +166,11 @@ export interface TestLiveInput {) => Promise<SessionExecuteMetaResponse>;/** Override `session.link`. Receives sessionId and params. */link?: (sessionId: string, params: SessionLinkParams) => Promise<SessionLinkResponse>;+ /** Override `session.proxyExecute`. Receives sessionId and params. */+ proxyExecute?: (+ sessionId: string,+ params: SessionProxyExecuteParams+ ) => Promise<SessionProxyExecuteResponse>;/** Override `session.search`. Receives sessionId and params. */search?: (sessionId: string, params: SessionSearchParams) => Promise<SessionSearchResponse>;/** Override `session.toolkits`. Receives sessionId and optional params. */@@ -987,6 +994,19 @@ export const TestLayer = (input?: TestLiveInput) =>link_token: 'lt_test_token',redirect_url: 'https://app.composio.dev/link?token=lt_test_token',})),+ proxyExecute:+ toolRouterOverrides?.proxyExecute ??+ (async (_sessionId: string, params: SessionProxyExecuteParams) => ({+ status: 200,+ data: {+ toolkit_slug: params.toolkit_slug,+ endpoint: params.endpoint,+ method: params.method,+ body: params.body ?? null,+ parameters: params.parameters ?? [],+ },+ headers: {},+ })),search: toolRouterOverrides?.search ?? defaultSearchHandler,toolkits: toolRouterOverrides?.toolkits ?? defaultToolkitsHandler,tools: async () => ({diff --git a/ts/packages/cli/test/src/commands/$default.cmd.test.ts b/ts/packages/cli/test/src/commands/$default.cmd.test.tsindex 9e119c68f..799403ca4 100644--- a/ts/packages/cli/test/src/commands/$default.cmd.test.ts+++ b/ts/packages/cli/test/src/commands/$default.cmd.test.ts@@ -2,9 +2,13 @@ import { describe, expect, layer } from '@effect/vitest';import { Effect } from 'effect';import { ValidationError, HelpDoc } from '@effect/cli';import { cli, pkg, TestLive, MockConsole } from 'test/__utils__';-import { sanitize } from 'test/__utils__/sanitize';+import { afterEach, vi } from 'vitest';describe('CLI: composio', () => {+ afterEach(() => {+ vi.unstubAllEnvs();+ });+layer(TestLive())(it => {it.scoped('[Given] unknown argument [Then] print error message', () =>Effect.gen(function* () {@@ -15,7 +19,7 @@ describe('CLI: composio', () => {expect(result).toEqual(ValidationError.commandMismatch(HelpDoc.p(- "Invalid subcommand for composio - use one of 'version', 'upgrade', 'whoami', 'login', 'logout', 'run', 'install', 'dev', 'tools', 'search', 'link', 'execute', 'generate', 'manage'"+ "Invalid subcommand for composio - use one of 'version', 'upgrade', 'whoami', 'login', 'logout', 'run', 'proxy', 'artifacts', 'install', 'dev', 'tools', 'search', 'link', 'execute', 'generate', 'manage'")));@@ -30,7 +34,16 @@ describe('CLI: composio', () => {yield* cli(args);const lines = yield* MockConsole.getLines({ stripAnsi: true });const output = lines.join('\n');- expect(yield* sanitize(output)).toMatchSnapshot();+ expect(output).toContain('CORE COMMANDS');+ expect(output).toContain('composio search <query>');+ expect(output).toContain('composio execute <slug>');+ expect(output).toContain('composio link [<toolkit>]');+ expect(output).toContain('composio run <code>');+ expect(output).toContain('composio proxy <url> --toolkit text');+ expect(output).toContain('composio artifacts cwd');+ expect(output).toContain('DEVELOPER COMMANDS');+ expect(output).toContain('ACCOUNT');+ expect(output).toContain('Documentation: https://docs.composio.dev');}));});@@ -58,4 +71,39 @@ describe('CLI: composio', () => {}));});++ layer(TestLive())(it => {+ it.scoped('[Given] debug who-is-my-master [Then] it prints the detected master as json', () =>+ Effect.gen(function* () {+ vi.stubEnv('CODEX_THREAD_ID', 'thread_123');+ vi.stubEnv('CLAUDE_CODE_ENTRYPOINT', 'sdk-ts');+ const write = vi+ .spyOn(process.stdout, 'write')+ .mockImplementation((() => true) as typeof process.stdout.write);++ yield* cli(['debug', 'who-is-my-master']);+ const output = write.mock.calls.map(call => String(call[0])).join('\n');++ expect(output).toContain('"master": "codex"');+ })+ );+ });++ layer(TestLive())(it => {+ it.scoped('[Given] artifacts cwd [Then] it prints the current session artifact directory', () =>+ Effect.gen(function* () {+ const write = vi+ .spyOn(process.stdout, 'write')+ .mockImplementation((() => true) as typeof process.stdout.write);++ yield* cli(['artifacts', 'cwd']);+ const output = write.mock.calls+ .map(call => String(call[0]))+ .join('\n')+ .trim();++ expect(output).toContain('/tmp/composio');+ })+ );+ });});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.snapdeleted file mode 100644index 6ca41ba19..000000000--- a/ts/packages/cli/test/src/commands/__snapshots__/$default.cmd.test.ts.snap+++ /dev/null@@ -1,96 +0,0 @@-// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html--exports[`CLI: composio > [Given] --help flag [Then] prints help message 1`] = `-"-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.--USAGE- composio <command> [options]--BASIC COMMANDS- version- Display the current Composio CLI version.- Usage: composio version-- upgrade- Upgrade your Composio CLI to the latest available version.- Usage: composio upgrade-- whoami- Display your account information.- Usage: composio whoami-- login- Log in to the Composio CLI session.- Usage: composio login [--no-browser] [--no-wait] [--key text] [-y, --yes]- Options:- --no-browser Login without browser interaction- --no-wait Print login URL and session info, then exit (no browser, no waiting)- --key Complete login using session key from --no-wait- -y, --yes Skip org picker; use session default org-- logout- Log out from the Composio CLI session.- Usage: composio logout-- 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:- <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 check-- search- 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, 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 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 check-- link- Connect a user account for a toolkit/app.- Usage: composio link [<toolkit>] [--no-browser]- Options:- <toolkit> Toolkit slug to link (e.g. "github", "gmail")- --no-browser Skip auto-opening the browser--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 Manage your developer orgs, toolkits, connected accounts, triggers, auth configs, and projects.--FLAGS- -h, --help Show help for command- --version Show composio version--LEARN MORE- Use \`composio <command> --help\` for more information about a command.- Documentation: https://docs.composio.dev-"-`;diff --git a/ts/packages/cli/test/src/commands/proxy.cmd.test.ts b/ts/packages/cli/test/src/commands/proxy.cmd.test.tsnew file mode 100644index 000000000..b3a572e1d--- /dev/null+++ b/ts/packages/cli/test/src/commands/proxy.cmd.test.ts@@ -0,0 +1,215 @@+import { describe, expect, layer } from '@effect/vitest';+import { ConfigProvider, Effect, Option } from 'effect';+import { afterEach, it, vi } from 'vitest';+import type {+ SessionCreateParams,+ SessionProxyExecuteParams,+} from '@composio/client/resources/tool-router';+import { extendConfigProvider } from 'src/services/config';+import { normalizeProxyMethod, parseProxyBody, parseProxyHeader } from 'src/commands/proxy.cmd';+import * as consumerShortTermCache from 'src/services/consumer-short-term-cache';+import { cli, MockConsole, TestLive } from 'test/__utils__';++const testConfigProvider = ConfigProvider.fromMap(+ new Map([['COMPOSIO_USER_API_KEY', 'test_api_key']])+).pipe(extendConfigProvider);++describe('CLI: composio proxy', () => {+ afterEach(() => {+ vi.restoreAllMocks();+ });++ it('parses curl-style header values', () => {+ expect(parseProxyHeader('content-type: application/json')).toEqual({+ name: 'content-type',+ value: 'application/json',+ });+ });++ it('normalizes HTTP methods', () => {+ expect(normalizeProxyMethod('post')).toBe('POST');+ });++ it('parses JSON-like request bodies when possible', () => {+ expect(parseProxyBody('{ foo: "bar" }')).toEqual({ foo: 'bar' });+ expect(parseProxyBody('plain text')).toBe('plain text');+ });++ layer(TestLive({ baseConfigProvider: testConfigProvider, fixture: 'global-test-user-id' }))(+ '[Given] curl-like proxy flags [Then] it creates a scoped session and forwards proxy_execute',+ it => {+ it.scoped('forwards proxy execute params and prints the response', () =>+ Effect.gen(function* () {+ let createParams: SessionCreateParams | undefined;+ let proxyParams:+ | {+ sessionId: string;+ params: SessionProxyExecuteParams;+ }+ | undefined;++ const live = TestLive({+ baseConfigProvider: testConfigProvider,+ fixture: 'global-test-user-id',+ toolRouter: {+ create: async (params: SessionCreateParams) => {+ createParams = params;+ return {+ session_id: 'trs_proxy_test',+ config: { user_id: params.user_id },+ mcp: { type: 'http' as const, url: 'https://mcp.test.composio.dev' },+ tool_router_tools: [],+ };+ },+ proxyExecute: async (sessionId: string, params: SessionProxyExecuteParams) => {+ proxyParams = { sessionId, params };+ return {+ status: 200,+ data: {+ ok: true,+ endpoint: params.endpoint,+ method: params.method,+ },+ headers: { 'content-type': 'application/json' },+ };+ },+ },+ });++ yield* cli([+ 'proxy',+ 'https://gmail.googleapis.com/gmail/v1/users/me/drafts',+ '--toolkit',+ 'gmail',+ '-X',+ 'post',+ '-H',+ 'content-type: application/json',+ '-d',+ '{ "message": { "raw": "abc" } }',+ ]).pipe(Effect.provide(live));++ expect(createParams).toEqual({+ user_id: 'consumer-user-org_test',+ manage_connections: { enable: false },+ toolkits: { enable: ['gmail'] },+ });+ expect(proxyParams).toEqual({+ sessionId: 'trs_proxy_test',+ params: {+ toolkit_slug: 'gmail',+ endpoint: 'https://gmail.googleapis.com/gmail/v1/users/me/drafts',+ method: 'POST',+ body: { message: { raw: 'abc' } },+ parameters: [+ {+ name: 'content-type',+ type: 'header',+ value: 'application/json',+ },+ ],+ },+ });++ const lines = yield* MockConsole.getLines({ stripAnsi: true });+ const output = lines.join('\n');+ expect(output).toContain('Status: 200');+ expect(output).toContain('"ok": true');+ })+ );+ }+ );++ layer(TestLive({ baseConfigProvider: testConfigProvider, fixture: 'global-test-user-id' }))(+ '[Given] cached missing toolkit [Then] proxy fails fast before session creation',+ it => {+ it.scoped('uses the connected toolkit cache keyed by toolkit', () =>+ Effect.gen(function* () {+ const refreshSpy = vi+ .spyOn(consumerShortTermCache, 'refreshConsumerConnectedToolkitsCache')+ .mockReturnValue(Effect.void);+ const getFreshSpy = vi+ .spyOn(consumerShortTermCache, 'getFreshConsumerConnectedToolkitsFromCache')+ .mockReturnValue(Effect.succeed(Option.some(['slack'])));++ let createCalled = false;+ const live = TestLive({+ baseConfigProvider: testConfigProvider,+ fixture: 'global-test-user-id',+ toolRouter: {+ create: async (_params: SessionCreateParams) => {+ createCalled = true;+ return {+ session_id: 'trs_proxy_test',+ config: { user_id: 'global_test_user_id' },+ mcp: { type: 'http' as const, url: 'https://mcp.test.composio.dev' },+ tool_router_tools: [],+ };+ },+ },+ });++ yield* cli([+ 'proxy',+ 'https://gmail.googleapis.com/gmail/v1/users/me/profile',+ '--toolkit',+ 'gmail',+ ]).pipe(+ Effect.provide(live),+ Effect.catchAll(() => Effect.void)+ );++ expect(createCalled).toBe(false);++ const lines = yield* MockConsole.getLines({ stripAnsi: true });+ const output = lines.join('\n');+ expect(output).toContain('Toolkit "gmail" is not connected for this user');+ expect(output).toContain('composio link gmail');+ expect(refreshSpy).toHaveBeenCalled();+ expect(getFreshSpy).toHaveBeenCalled();+ })+ );+ }+ );++ layer(TestLive({ baseConfigProvider: testConfigProvider, fixture: 'global-test-user-id' }))(+ '[Given] backend 4302 no-connection error [Then] proxy rewrites it to link guidance',+ it => {+ it.scoped('translates proxy_execute connection errors like execute does', () =>+ Effect.gen(function* () {+ const live = TestLive({+ baseConfigProvider: testConfigProvider,+ fixture: 'global-test-user-id',+ toolRouter: {+ proxyExecute: async () => {+ throw {+ message: 'raw backend error',+ details: {+ code: 4302,+ slug: 'ToolRouterV2_NoActiveConnection',+ message: 'No active connection',+ },+ };+ },+ },+ });++ const exit = yield* cli([+ 'proxy',+ 'https://gmail.googleapis.com/gmail/v1/users/me/profile',+ '--toolkit',+ 'gmail',+ '--skip-connection-check',+ ]).pipe(Effect.provide(live), Effect.exit);++ expect(exit._tag).toBe('Failure');++ const lines = yield* MockConsole.getLines({ stripAnsi: true });+ const output = lines.join('\n');+ expect(output).toContain('No active connection found for toolkit "gmail"');+ expect(output).toContain('composio link gmail');+ })+ );+ }+ );+});diff --git a/ts/packages/cli/test/src/commands/run.cmd.test.ts b/ts/packages/cli/test/src/commands/run.cmd.test.tsindex d4b068d6d..0f5d6590e 100644--- a/ts/packages/cli/test/src/commands/run.cmd.test.ts+++ b/ts/packages/cli/test/src/commands/run.cmd.test.ts@@ -1,3 +1,6 @@+import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';import { describe, expect, layer } from '@effect/vitest';import { Effect } from 'effect';import { afterEach, it, vi } from 'vitest';@@ -5,6 +8,7 @@ import {buildRunHelpersSource,extractInlineExecuteToolSlugs,inferCliInvocationPrefix,+ wrapInlineCodeForRun,} from 'src/commands/run.cmd';import { cli, MockConsole, TestLive } from 'test/__utils__';@@ -34,13 +38,11 @@ describe('CLI: composio run', () => {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.cmd[3]).toBe('--eval');+ expect(spawnConfig.cmd[4]).toContain('(async () => {');+ expect(spawnConfig.cmd[4]).toContain('return (console.log("hi"));');+ expect(spawnConfig.cmd[4]).toContain('if (__composioResult !== undefined) {');+ expect(spawnConfig.cmd.slice(5)).toEqual(['--', '--flag', 'value']);expect(spawnConfig.env).toEqual(expect.objectContaining({...process.env,@@ -56,30 +58,39 @@ describe('CLI: composio run', () => {layer(TestLive())(it => {it.scoped('[Given] --file [Then] it forwards file execution to the embedded Bun runtime', () =>Effect.gen(function* () {+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'composio-run-test-'));+ const scriptPath = path.join(tempDir, 'script.ts');+ fs.writeFileSync(scriptPath, 'const value = 1 + 1;\nvalue * 2;\n', 'utf8');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']);+ try {+ yield* cli(['run', '--file', scriptPath, '--', '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);+ 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[3]).toMatch(/\.composio-run-.*\.ts$/);+ expect(spawnConfig.cmd[4]).toBe('--');+ expect(spawnConfig.cmd[5]).toBe('hello');+ expect(spawnConfig.env).toEqual(+ expect.objectContaining({+ ...process.env,+ BUN_BE_BUN: '1',+ })+ );+ expect(spawnConfig.stdio).toEqual(['inherit', 'inherit', 'inherit']);+ expect(exit).toHaveBeenCalledWith(0);+ } finally {+ fs.rmSync(tempDir, { recursive: true, force: true });+ }}));});@@ -94,17 +105,26 @@ describe('CLI: composio run', () => {});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');- })+ it.scoped(+ '[Given] run help [Then] it documents injected execute, search, proxy, subAgent, and z helpers',+ () =>+ Effect.gen(function* () {+ yield* cli(['run', '--help']);+ const lines = yield* MockConsole.getLines({ stripAnsi: true });+ const output = lines.join('\n');+ expect(output).toContain(+ 'Run inline TS/JS code or a file with injected Composio helpers that behave like their CLI counterparts.'+ );+ expect(output).toContain('--skip-connection-check');+ expect(output).toContain('--skip-tool-params-check');+ expect(output).toContain('--no-verify');+ expect(output).toContain('subAgent');+ expect(output).toContain('schema: z.object');+ expect(output).toContain('INJECTED HELPERS');+ expect(output).toContain('Global from zod');+ expect(output).toContain('composio search "<query>"');+ expect(output).toContain('composio execute <slug> --get-schema');+ }));});});@@ -120,9 +140,65 @@ describe('buildRunHelpersSource', () => {dryRun: true,});+ expect(source).toContain('import { z } from "zod";');+ expect(source).toContain('globalThis.z = z;');+ expect(source).toContain('globalThis.zod = z;');+ expect(source).toContain('const stringifyForPrompt = (value) => {');+ expect(source).toContain('const attachPromptMethod = (value) => {');+ expect(source).toContain('typeof value.prompt === "function"');+ expect(source).toContain(+ 'value: () => stringifyForPrompt("data" in value ? value.data : value),'+ );+ expect(source).toContain(+ 'const sharedRunOutputDir = typeof helperContext.runOutputDir === "string"'+ );+ expect(source).toContain('COMPOSIO_RUN_OUTPUT_DIR');+ expect(source).toContain('fs.mkdtempSync(path.join(sharedRunOutputDir, "invoke-agent-"))');+ expect(source).toContain('const maybeLoadStoredCliResult = (result) => {');+ expect(source).toContain('storedInFilePath: outputFilePath !== null,');+ expect(source).toContain('outputFilePath,');+ expect(source).toContain('const logCliResultPreview = (requestId, result) => {');+ expect(source).toContain('helperDebugLog("cli.result", {');+ expect(source).toContain('helperDebugLog("cli.result.stored_in_file"');expect(source).toContain('COMPOSIO_USER_API_KEY');expect(source).toContain('"consumerUserId":"consumer_user_test"');expect(source).toContain('__composioConsumerContext');+ expect(source).toContain('globalThis.execute = async (slug, data = {}) => {');+ expect(source).toContain(+ 'if (result && typeof result === "object" && result.successful === false) {'+ );+ expect(source).toContain('Object.assign(error, { result, slug });');+ expect(source).toContain('globalThis.subAgent = subAgentImpl;');+ expect(source).toContain(+ 'Object.defineProperty(globalThis.subAgent, "schema", { value: subAgentSchema });'+ );+ expect(source).toContain('globalThis.invokeAgent = subAgentImpl;');+ expect(source).toContain('const toInvokeAgentResponse = (master, target, payload = {}) => ({');+ expect(source).toContain('const invokeClaudeAgent = async (prompt, options) => {');+ expect(source).toContain('const invokeCodexAgent = async (prompt, options) => {');+ expect(source).toContain('const detectInvokeAgentMaster = () => {');+ expect(source).toContain(+ 'throw new Error("subAgent() accepts either options.schema or options.jsonSchema, not both.");'+ );+ expect(source).toContain('const inputSchema = options.schema ?? options.jsonSchema;');+ expect(source).toContain('if (typeof z.toJSONSchema !== "function") {');+ expect(source).toContain(+ 'subAgent() requires Zod 4 with z.toJSONSchema() when using options.schema.'+ );+ expect(source).toContain('structuredSchema = z.toJSONSchema(inputSchema);');+ expect(source).toContain(+ '["codex", "exec", "--skip-git-repo-check", "--sandbox", "read-only", "-o", outputPath]'+ );+ expect(source).toContain('["claude", "--bare", "-p", "--output-format", "json"]');+ expect(source).toContain('structuredOutput: parsed.structured_output ?? null');+ expect(source).toContain('globalThis.proxy = async (toolkit) => {');+ expect(source).toContain('const proxyFetch = async (input, init = {}) => {');+ expect(source).toContain('return toProxyResponse(result);');+ expect(source).toContain(+ 'Object.defineProperty(globalThis.proxy, "schema", { value: proxySchema });'+ );+ expect(source).toContain('`/api/v3/tool_router/session/${sessionId}/proxy_execute`');+ expect(source).toContain('"proxy() requires a consumer project context');expect(source).toContain('returned no JSON output');expect(source).toContain('args.push("--dry-run");');expect(source).toContain('args.push("--skip-connection-check");');@@ -152,3 +228,14 @@ describe('extractInlineExecuteToolSlugs', () => {).toEqual(['GMAIL_SEND_EMAIL', 'GITHUB_CREATE_ISSUE']);});});++describe('wrapInlineCodeForRun', () => {+ it('[Given] inline code ending in an expression [Then] it rewrites the last expression to a return', () => {+ expect(+ wrapInlineCodeForRun(`+ const value = 1 + 1;+ value * 2;+ `)+ ).toContain('return (value * 2);');+ });+});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 35e2b3785..ff539b65b 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,11 +1,12 @@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 { ConfigProvider, Effect, Option } from 'effect';import { extendConfigProvider } from 'src/services/config';-import { ActionExecuteConnectedAccountNotFoundError } from 'src/services/tools-executor';+import { ComposioNoActiveConnectionError } from 'src/services/composio-error-overrides';import { setupCacheDir } from 'src/effects/setup-cache-dir';import { getOrFetchToolInputDefinition } from 'src/services/tool-input-validation';+import * as consumerShortTermCache from 'src/services/consumer-short-term-cache';import * as redactModule from 'src/ui/redact';import { cli, TestLive, MockConsole } from 'test/__utils__';import type { TestLiveInput } from 'test/__utils__/services/test-layer';@@ -41,8 +42,15 @@ describe('CLI: composio execute', () => {beforeEach(() => {savedCI = process.env.CI;delete process.env.CI;+ vi.spyOn(consumerShortTermCache, 'getFreshConsumerConnectedToolkitsFromCache').mockReturnValue(+ Effect.succeed(Option.some(['gmail', 'github']))+ );+ vi.spyOn(consumerShortTermCache, 'refreshConsumerConnectedToolkitsCache').mockImplementation(+ () => Effect.succeed(['gmail', 'github'])+ );});afterEach(() => {+ vi.restoreAllMocks();if (savedCI !== undefined) process.env.CI = savedCI;});@@ -55,7 +63,13 @@ describe('CLI: composio 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(['execute', 'GMAIL_SEND_EMAIL', '-d', '{"recipient":"a"}']);+ yield* cli([+ 'execute',+ 'GMAIL_SEND_EMAIL',+ '--skip-connection-check',+ '-d',+ '{"recipient":"a"}',+ ]);const lines = yield* MockConsole.getLines({ stripAnsi: true });const output = parseLastJson(lines);@@ -419,12 +433,17 @@ describe('CLI: composio execute', () => {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(output.outputFilePath).toMatch(+ /^\/tmp\/composio\/[^/]+\/GMAIL_SEND_EMAIL_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 });+ fs.rmSync(output.outputFilePath.slice(0, output.outputFilePath.lastIndexOf('/')), {+ recursive: true,+ force: true,+ });}));});@@ -734,16 +753,18 @@ describe('CLI: composio execute', () => {} satisfies TestLiveInput['toolkitsData'],stdin: { isTTY: true, data: '' },})- )('[Given] execute-help with options before slug [Then] resolves correct slug', it => {- it.scoped('resolves root execute help slug correctly', () =>+ )('[Given] execute --help with a slug [Then] it shows command help', it => {+ it.scoped('shows the root execute help text', () =>Effect.gen(function* () {yield* cli(['execute', 'GMAIL_SEND_EMAIL', '--help']);const lines = yield* MockConsole.getLines({ stripAnsi: true });const output = lines.join('\n');- expect(output).toContain('Slug: GMAIL_SEND_EMAIL');- expect(output).toContain('Data Parameters:');- expect(output).toContain('recipient');+ expect(output).toContain('USAGE');+ expect(output).toContain(+ 'composio execute <slug> [-d, --data text] [--dry-run] [--get-schema]'+ );+ expect(output).toContain('composio execute GMAIL_SEND_EMAIL --get-schema');}));});@@ -774,9 +795,12 @@ describe('CLI: composio execute', () => {fixture: 'global-test-user-id',stdin: { isTTY: true, data: '' },toolsExecutor: {- failWith: new ActionExecuteConnectedAccountNotFoundError({- slug: 'ActionExecute_ConnectedAccountNotFound',- message: 'No connected account found for entity ID default for toolkit gmail',+ failWith: new ComposioNoActiveConnectionError({+ details: {+ slug: 'ActionExecute_ConnectedAccountNotFound',+ message: 'No connected account found for entity ID default for toolkit gmail',+ },+ toolSlug: 'GMAIL_CREATE_EMAIL_DRAFT',}),},})@@ -1009,9 +1033,12 @@ describe('CLI: composio execute', () => {fixture: 'global-test-user-id',stdin: { isTTY: true, data: '' },toolsExecutor: {- failWith: new ActionExecuteConnectedAccountNotFoundError({- slug: 'ToolRouterV2_NoActiveConnection',- message: 'No active connection found for toolkit(s) in this session',+ failWith: new ComposioNoActiveConnectionError({+ details: {+ slug: 'ToolRouterV2_NoActiveConnection',+ message: 'No active connection found for toolkit(s) in this session',+ },+ toolSlug: 'COMPOSIO_SEARCH_TOOLS',}),},})diff --git a/ts/packages/cli/test/src/services/composio-error-overrides.test.ts b/ts/packages/cli/test/src/services/composio-error-overrides.test.tsnew file mode 100644index 000000000..4ebf4c1ad--- /dev/null+++ b/ts/packages/cli/test/src/services/composio-error-overrides.test.ts@@ -0,0 +1,77 @@+import { describe, expect, it } from 'vitest';++import {+ ComposioNoActiveConnectionError,+ mapComposioError,+ mapOnlyComposioOverrideError,+} from 'src/services/composio-error-overrides';++describe('composio-error-overrides', () => {+ it('rewrites tool-router no-active-connection errors by toolkit', () => {+ const result = mapComposioError({+ toolkit: 'gmail',+ error: {+ details: {+ code: 4302,+ slug: 'ToolRouterV2_NoActiveConnection',+ message: 'No active connection',+ },+ },+ });++ expect(result.normalized).toBeInstanceOf(ComposioNoActiveConnectionError);+ expect(result.message).toBe(+ 'No active connection found for toolkit "gmail". Run `composio link gmail`, then retry.'+ );+ });++ it('rewrites execute no-connection errors by tool slug', () => {+ const result = mapComposioError({+ toolSlug: 'SLACK_SEND_MESSAGE',+ error: {+ error: {+ slug: 'ActionExecute_ConnectedAccountNotFound',+ message: 'Missing connected account',+ },+ },+ });++ expect(result.normalized).toBeInstanceOf(ComposioNoActiveConnectionError);+ expect(result.message).toBe(+ 'No active connection found for toolkit "slack". Run `composio link slack`, then retry.'+ );+ });++ it('passes through unrelated errors', () => {+ const error = new Error('Something else broke');++ const result = mapComposioError({ error });++ expect(result.normalized).toBe(error);+ expect(result.override).toBeNull();+ expect(result.message).toBe('Something else broke');+ });++ it('preserves original generic errors for top-level CLI handling', () => {+ const error = {+ _tag: 'ToolExecutionError',+ error: new Error('inner'),+ };++ expect(mapOnlyComposioOverrideError({ error })).toBe(error);+ });++ it('still rewrites override-class Composio errors at the top level', () => {+ const mapped = mapOnlyComposioOverrideError({+ toolkit: 'gmail',+ error: {+ details: {+ code: 4302,+ slug: 'ToolRouterV2_NoActiveConnection',+ },+ },+ });++ expect(mapped).toBeInstanceOf(ComposioNoActiveConnectionError);+ });+});diff --git a/ts/packages/cli/test/src/services/master-detector.test.ts b/ts/packages/cli/test/src/services/master-detector.test.tsnew file mode 100644index 000000000..993389f03--- /dev/null+++ b/ts/packages/cli/test/src/services/master-detector.test.ts@@ -0,0 +1,34 @@+import { describe, expect, it } from 'vitest';++import { detectMaster } from 'src/services/master-detector';++describe('master-detector', () => {+ it('detects codex when codex env markers are present', () => {+ expect(+ detectMaster({+ CODEX_THREAD_ID: 'thread_123',+ })+ ).toBe('codex');+ });++ it('detects claude when claude env markers are present without codex markers', () => {+ expect(+ detectMaster({+ CLAUDE_CODE_ENTRYPOINT: 'sdk-ts',+ })+ ).toBe('claude');+ });++ it('prefers codex when both codex and claude markers are present', () => {+ expect(+ detectMaster({+ CLAUDE_CODE_ENTRYPOINT: 'sdk-ts',+ CODEX_THREAD_ID: 'thread_123',+ })+ ).toBe('codex');+ });++ it('falls back to user when no known agent markers are present', () => {+ expect(detectMaster({})).toBe('user');+ });+});