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
Add ACP-backed subagent execution to `composio run` (#3011)
Rahul Tarakf4922f9757b5
diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 67eb4eff6..b7163c29a 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -1043,6 +1043,9 @@ importers:ts/packages/cli:dependencies:+ '@agentclientprotocol/sdk':+ specifier: ^0.16.1+ version: 0.16.1([email protected])'@clack/core':specifier: 'catalog:'version: 1.0.1@@ -1067,6 +1070,12 @@ importers:'@effect/platform-node-shared':specifier: 'catalog:'version: 0.57.1(@effect/[email protected](@effect/[email protected]([email protected]))(@effect/[email protected](@effect/[email protected]([email protected]))([email protected]))(@effect/[email protected](@effect/[email protected](@effect/[email protected]([email protected]))([email protected]))(@effect/[email protected]([email protected]))([email protected]))(@effect/[email protected](@effect/[email protected](@effect/[email protected]([email protected]))([email protected]))(@effect/[email protected]([email protected]))(@effect/[email protected](@effect/[email protected]([email protected]))([email protected]))([email protected]))([email protected]))(@effect/[email protected]([email protected]))(@effect/[email protected](@effect/[email protected]([email protected]))([email protected]))(@effect/[email protected](@effect/[email protected](@effect/[email protected]([email protected]))([email protected]))(@effect/[email protected]([email protected]))([email protected]))([email protected])+ '@zed-industries/claude-code-acp':+ specifier: ^0.16.2+ version: 0.16.2(@cfworker/[email protected])([email protected])+ '@zed-industries/codex-acp':+ specifier: ^0.10.0+ version: 0.10.0ansis:specifier: ^4.1.0version: 4.2.0@@ -1450,6 +1459,16 @@ packages:resolution: {integrity: sha512-VTDuRS5V0ATbJ/LkaQlisMnTAeYKXAK6scMguVBstf+KIBQ7HIuKhiXLv+G/hvejkV+THoXzoNifInAkU81P1g==}engines: {node: '>=18'}+ '@agentclientprotocol/[email protected]':+ resolution: {integrity: sha512-b6r3PS3Nly+Wyw9U+0nOr47bV8tfS476EgyEMhoKvJCZLbgqoDFN7DJwkxL88RR0aiOqOYV1ZnESHqb+RmdH8w==}+ peerDependencies:+ zod: ^3.25.0 || ^4.0.0++ '@agentclientprotocol/[email protected]':+ resolution: {integrity: sha512-1ad+Sc/0sCtZGHthxxvgEUo5Wsbw16I+aF+YwdiLnPwkZG8KAGUEAPK6LM6Pf69lCyJPt1Aomk1d+8oE3C4ZEw==}+ peerDependencies:+ zod: ^3.25.0 || ^4.0.0+'@ai-sdk/[email protected]':resolution: {integrity: sha512-Smq0sMMqhIxZIUN7TjXitpa5M8SrJCpe/6rHxU7In6FuKb7y16qkj8vvWzmZtQFWZ/1h1Yo+h5ZdcS1KtgMP4g==}engines: {node: '>=18'}@@ -1557,6 +1576,12 @@ packages:peerDependencies:zod: ^3.25.0 || ^4.0.0+ '@anthropic-ai/[email protected]':+ resolution: {integrity: sha512-bryUo6qq5dalO4MmhYLTPonTOAmdSVpMaVLJl8Y0qm6M7G+NZ3WS4cTMGrTbz97Uz5nah+FIOMA4hh8sKLm3YQ==}+ engines: {node: '>=18.0.0'}+ peerDependencies:+ zod: ^4.0.0+'@anthropic-ai/[email protected]':resolution: {integrity: sha512-d4c+fg+xy9e46c8+YnrrgIQR45CZlAi7PwdzIfDXDM6ACxEZli1/fxhURsq30ZpMZy6LvSkr41jGq5aF5TD7rQ==}hasBin: true@@ -3629,6 +3654,51 @@ packages:'@vitest/[email protected]':resolution: {integrity: sha512-fB2V0JFrQSMsCo9HiSq3Ezpdv4iYaXRG1Sx8edX3MwxfyNn83mKiGzOcH+Fkxt4MHxr3y42fQi1oeAInqgX2QA==}+ '@zed-industries/[email protected]':+ resolution: {integrity: sha512-D8BJe6CCD49RtNFbZYPsfZOpQI8Z/EzhyYC9zAGMwN/HVunEtVY2sXqYl1iDSkkayzhqABfaDkDZfeqDM1T/aA==}+ deprecated: This package has been renamed to @zed-industries/claude-agent-acp. Please migrate to continue receiving updates.+ hasBin: true++ '@zed-industries/[email protected]':+ resolution: {integrity: sha512-zlIZH+X2aEfxC5UgnIoYbX0cG3/MpRUsQAGJbrcBbgKp0mhuBFtMJHZ426JC5rb3pv8amo1MmDeARZUQ99U/CQ==}+ cpu: [arm64]+ os: [darwin]+ hasBin: true++ '@zed-industries/[email protected]':+ resolution: {integrity: sha512-TFMF9YqfWplnYpWRaUauRbtps1ow1S47MVcBv21/Sd55gRMWWYWSogRLDyAcoMC4y9pdI2bYhx33u7jYhJnj5w==}+ cpu: [x64]+ os: [darwin]+ hasBin: true++ '@zed-industries/[email protected]':+ resolution: {integrity: sha512-tIm0uGKZuirZyqx9KAgIgh6cimVXdh+BMTFyUfH1xnez5Y3B6oFxzup/ZIP34OZ/W59Cnfi4wcIL3No0VV6Kmw==}+ cpu: [arm64]+ os: [linux]+ hasBin: true++ '@zed-industries/[email protected]':+ resolution: {integrity: sha512-oiiN35wsecX1OwesV/KIu72o1OSw+OWFL86vQUUZTdfMXr9eyYFP1uZYLMxIx+tkhlJnm7KHC5L4raDg/MLVtA==}+ cpu: [x64]+ os: [linux]+ hasBin: true++ '@zed-industries/[email protected]':+ resolution: {integrity: sha512-dfybabjibQQpXUs9TjwLjg+mrj8tGSopVcwkFy8u3XG4hrBZVCri91dtVhm7hs98lZlawxwiiPuj4Pmg+4hHyQ==}+ cpu: [arm64]+ os: [win32]+ hasBin: true++ '@zed-industries/[email protected]':+ resolution: {integrity: sha512-xCm3xsE3lD66DlbaLKBqHahPY1Lhb+rGu2IIq60qUsBGiYcSXtpRjQ1LXI/Sym6iCKrPo+eQP0j6rg7CPh1AGw==}+ cpu: [x64]+ os: [win32]+ hasBin: true++ '@zed-industries/[email protected]':+ resolution: {integrity: sha512-vzwAUSHR7TaJh62JoE+6UD/HVm8fJbmMGsMBBMcHrKBIL7MF8yevlPDWVdoaDaGOsgqVZYRv9KhdT8ari0I4mg==}+ hasBin: true+resolution: {integrity: sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==}engines: {node: '>= 0.6'}@@ -4087,6 +4157,10 @@ packages:resolution: {integrity: sha512-nPRkjWzzDQlsejL1WVifk5rvcFi/y1onBRxjaFMjZeR9mFpqu2gmAZ9xUB9/IEanEP/vBtGeGganC/GO1fmufg==}+ resolution: {integrity: sha512-qejHi7bcSD4hQAZE0tNAawRK1ZtafHDmMTMkrrIGgSLl7hTnQHmKCeB45xAcbfTqK2zowkM3j3bHt/4b/ARbYQ==}+ engines: {node: '>=0.3.1'}+resolution: {integrity: sha512-WkrWp9GR4KXfKGYzOLmTuGVi1UWFfws377n9cc55/tb6DuqyF6pcQ5AbiHEshaDpY9v6oaSr2XCDidGmMwdzIA==}engines: {node: '>=8'}@@ -6372,6 +6446,14 @@ snapshots:transitivePeerDependencies:- supports-color+ '@agentclientprotocol/[email protected]([email protected])':+ dependencies:+ zod: 4.3.6++ '@agentclientprotocol/[email protected]([email protected])':+ dependencies:+ zod: 4.3.6+'@ai-sdk/[email protected]([email protected])':dependencies:'@ai-sdk/provider': 3.0.8@@ -6556,6 +6638,19 @@ snapshots:'@img/sharp-linuxmusl-x64': 0.33.5'@img/sharp-win32-x64': 0.33.5+ '@anthropic-ai/[email protected]([email protected])':+ dependencies:+ zod: 4.3.6+ optionalDependencies:+ '@img/sharp-darwin-arm64': 0.33.5+ '@img/sharp-darwin-x64': 0.33.5+ '@img/sharp-linux-arm': 0.33.5+ '@img/sharp-linux-arm64': 0.33.5+ '@img/sharp-linux-x64': 0.33.5+ '@img/sharp-linuxmusl-arm64': 0.33.5+ '@img/sharp-linuxmusl-x64': 0.33.5+ '@img/sharp-win32-x64': 0.33.5+'@anthropic-ai/[email protected]': {}'@anthropic-ai/[email protected]([email protected])':@@ -8556,6 +8651,45 @@ snapshots:loupe: 3.2.1tinyrainbow: 2.0.0+ dependencies:+ '@agentclientprotocol/sdk': 0.14.1([email protected])+ '@anthropic-ai/claude-agent-sdk': 0.2.44([email protected])+ '@modelcontextprotocol/sdk': 1.26.0(@cfworker/[email protected])([email protected])+ diff: 8.0.3+ minimatch: 10.2.1+ transitivePeerDependencies:+ - '@cfworker/json-schema'+ - supports-color+ - zod++ '@zed-industries/[email protected]':+ optional: true++ '@zed-industries/[email protected]':+ optional: true++ '@zed-industries/[email protected]':+ optional: true++ '@zed-industries/[email protected]':+ optional: true++ '@zed-industries/[email protected]':+ optional: true++ '@zed-industries/[email protected]':+ optional: true++ '@zed-industries/[email protected]':+ optionalDependencies:+ '@zed-industries/codex-acp-darwin-arm64': 0.10.0+ '@zed-industries/codex-acp-darwin-x64': 0.10.0+ '@zed-industries/codex-acp-linux-arm64': 0.10.0+ '@zed-industries/codex-acp-linux-x64': 0.10.0+ '@zed-industries/codex-acp-win32-arm64': 0.10.0+ '@zed-industries/codex-acp-win32-x64': 0.10.0+dependencies:mime-types: 2.1.35@@ -9002,6 +9136,8 @@ snapshots:+ [email protected]: {}+dependencies:path-type: 4.0.0diff --git a/ts/packages/cli/package.json b/ts/packages/cli/package.jsonindex 3bc463b0d..40dd73c6a 100644--- a/ts/packages/cli/package.json+++ b/ts/packages/cli/package.json@@ -67,6 +67,9 @@"vitest": "catalog:"},"dependencies": {+ "@agentclientprotocol/sdk": "^0.16.1",+ "@zed-industries/claude-code-acp": "^0.16.2",+ "@zed-industries/codex-acp": "^0.10.0","@clack/core": "catalog:","@clack/prompts": "catalog:","@composio/client": "catalog:",diff --git a/ts/packages/cli/scripts/build-binary.ts b/ts/packages/cli/scripts/build-binary.tsindex 945566cd5..4e5c91091 100644--- a/ts/packages/cli/scripts/build-binary.ts+++ b/ts/packages/cli/scripts/build-binary.ts@@ -72,6 +72,59 @@ export function buildBinary() {}yield* Effect.logDebug('', 'Binary built successfully');++ // Build companion modules that `composio run` imports in the child process.+ // These cannot live inside the compiled binary because they run in a separate+ // Bun process via the --preload globals file.+ const companionModules = [+ 'src/services/run-subagent-shared.ts',+ 'src/services/run-subagent-acp.ts',+ 'src/services/run-subagent-legacy.ts',+ ] as const;++ for (const entry of companionModules) {+ const name = entry.replace(/^.*\//, '').replace(/\.ts$/, '');+ const companionArgs = [+ 'bun',+ 'build',+ `./${entry}`,+ '--outfile',+ `./dist/${name}.mjs`,+ '--format',+ 'esm',+ '--target',+ 'bun',+ ] as const satisfies ReadonlyArray<string>;++ yield* Effect.logDebug(`Building companion module: ${name}`);++ const companionCmd = Command.make(...companionArgs);+ const { exitCode: companionExitCode } = yield* companionCmd.pipe(+ Command.start,+ Effect.flatMap(p =>+ Effect.all(+ {+ exitCode: p.exitCode,+ output: Stream.merge(+ Stream.decodeText(p.stdout, 'utf-8'),+ Stream.decodeText(p.stderr, 'utf-8'),+ { haltStrategy: 'left' }+ ).pipe(+ Stream.tap(chunk => Console.log(chunk)),+ Stream.runDrain+ ),+ },+ { concurrency: 'unbounded' }+ )+ )+ );++ if (companionExitCode !== 0) {+ return yield* Effect.fail(new Error(`Failed to build companion module: ${name}`));+ }+ }++ yield* Effect.logDebug('', 'Companion modules built successfully');});}diff --git a/ts/packages/cli/src/commands/index.ts b/ts/packages/cli/src/commands/index.tsindex 425af4b8e..d713d6f16 100644--- a/ts/packages/cli/src/commands/index.ts+++ b/ts/packages/cli/src/commands/index.ts@@ -130,6 +130,7 @@ const normalizeHiddenDebugFlags = (argv: ReadonlyArray<string>): ReadonlyArray<sconst args = argv.slice(2);let perfDebug: boolean | undefined;let toolDebug: boolean | undefined;+ let acpOnly: boolean | undefined;for (const arg of args) {if (arg === '--perf-debug') {@@ -156,6 +157,18 @@ const normalizeHiddenDebugFlags = (argv: ReadonlyArray<string>): ReadonlyArray<stoolDebug = true;continue;}+ if (arg === '--acp-only') {+ acpOnly = true;+ continue;+ }+ if (arg === '--acp-only=false') {+ acpOnly = false;+ continue;+ }+ if (arg === '--acp-only=true') {+ acpOnly = true;+ continue;+ }normalized.push(arg);}@@ -164,6 +177,11 @@ const normalizeHiddenDebugFlags = (argv: ReadonlyArray<string>): ReadonlyArray<s...(perfDebug === undefined ? {} : { perfDebug }),...(toolDebug === undefined ? {} : { toolDebug }),});+ if (acpOnly === undefined) {+ delete process.env.COMPOSIO_RUN_ACP_ONLY;+ } else {+ process.env.COMPOSIO_RUN_ACP_ONLY = acpOnly ? '1' : '0';+ }return normalized;};diff --git a/ts/packages/cli/src/commands/root-help.ts b/ts/packages/cli/src/commands/root-help.tsindex c6173cde2..6de004e55 100644--- a/ts/packages/cli/src/commands/root-help.ts+++ b/ts/packages/cli/src/commands/root-help.ts@@ -76,9 +76,12 @@ const CORE_COMMANDS: ReadonlyArray<DetailedCommand> = [// ── 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' },+ { name: 'composio tools info <slug>', description: 'Print tool summary and cache its schema' },+ { name: 'composio tools list <toolkit>', description: 'List tools available in a toolkit' },+ {+ name: 'composio artifacts cwd',+ description: 'Print the cwd-scoped session artifact directory',+ },];const DEVELOPER_COMMANDS: ReadonlyArray<CompactCommand> = [@@ -260,6 +263,7 @@ const SUBCOMMAND_HELP: Record<string, SubcommandHelp> = {{ 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' },+ { name: '--logs-off', description: 'Hide the always-on subAgent streaming logs' },],flags: [{ name: '--skip-connection-check', description: 'Skip the linked-account check' },diff --git a/ts/packages/cli/src/commands/run.cmd.ts b/ts/packages/cli/src/commands/run.cmd.tsindex 9338c3297..838ecf51c 100644--- a/ts/packages/cli/src/commands/run.cmd.ts+++ b/ts/packages/cli/src/commands/run.cmd.ts@@ -2,6 +2,7 @@ import * as fs from 'node:fs';import * as os from 'node:os';import * as path from 'node:path';import process from 'node:process';+import { fileURLToPath, pathToFileURL } from 'node:url';import { Args, Command, Options } from '@effect/cli';import { Effect, Option } from 'effect';import { ts } from 'ts-morph';@@ -29,6 +30,10 @@ const debug = Options.boolean('debug').pipe(Options.withDescription('Log helper steps while the script runs'),Options.withDefault(false));+const logsOff = Options.boolean('logs-off').pipe(+ Options.withDescription('Hide the always-on subAgent streaming logs'),+ Options.withDefault(false)+);const skipConnectionCheck = Options.boolean('skip-connection-check').pipe(Options.withDescription('Skip the linked-account check'),Options.withDefault(false)@@ -155,6 +160,48 @@ export const inferCliInvocationPrefix = (: [process.execPath];};+const resolveSiblingModulePath = (relativeNoExtensionFromRunCmd: string): string => {+ const currentFilePath = fileURLToPath(import.meta.url);+ const currentDirectory = path.dirname(currentFilePath);++ // Source (.ts) — running from `bun src/bin.ts`+ const tsPath = path.resolve(currentDirectory, `${relativeNoExtensionFromRunCmd}.ts`);+ if (fs.existsSync(tsPath)) {+ return tsPath;+ }++ // Built (.js) — running from `bun dist/bin.mjs`+ const jsPath = path.resolve(currentDirectory, `${relativeNoExtensionFromRunCmd}.js`);+ if (fs.existsSync(jsPath)) {+ return jsPath;+ }++ // Compiled binary — import.meta.url points to /$bunfs/, files live next to the executable+ const baseName = path.basename(relativeNoExtensionFromRunCmd);+ const exeDir = path.dirname(process.execPath);+ const mjsPath = path.resolve(exeDir, `${baseName}.mjs`);+ if (fs.existsSync(mjsPath)) {+ return mjsPath;+ }+ const exeJsPath = path.resolve(exeDir, `${baseName}.js`);+ if (fs.existsSync(exeJsPath)) {+ return exeJsPath;+ }++ // Fallback — return the .js path (will error at runtime with a clear module-not-found)+ return jsPath;+};++const subAgentSharedModuleUrl = pathToFileURL(+ resolveSiblingModulePath('../services/run-subagent-shared')+).href;+const subAgentAcpModuleUrl = pathToFileURL(+ resolveSiblingModulePath('../services/run-subagent-acp')+).href;+const subAgentLegacyModuleUrl = pathToFileURL(+ resolveSiblingModulePath('../services/run-subagent-legacy')+).href;+type RunHelperContext = {readonly apiKey?: string;readonly baseURL?: string;@@ -172,6 +219,8 @@ type RunHelperContext = {readonly noVerify?: boolean;readonly master?: MasterKind;readonly debug?: boolean;+ readonly acpOnly?: boolean;+ readonly logsOff?: boolean;readonly runOutputDir?: string;};@@ -203,7 +252,7 @@ const buildRunBaseHelpersSource = (): ReadonlyArray<string> => [' returns: {',' type: "object",',' additionalProperties: false,',- ' required: ["master", "target", "result", "structuredOutput"],',+ ' required: ["master", "target", "result"],',' properties: {',' master: { type: "string", enum: ["claude", "codex", "user"] },',' target: { type: "string", enum: ["claude", "codex"] },',@@ -244,11 +293,108 @@ const buildRunBaseHelpersSource = (): ReadonlyArray<string> => [' console.error(`[perf] ${JSON.stringify(payload)}`);','};','const helperDebugEnabled = helperContext.debug === true;',+ 'const helperProgressEnabled = helperContext.logsOff !== true;','const sharedRunOutputDir = typeof helperContext.runOutputDir === "string" && helperContext.runOutputDir.length > 0 ? helperContext.runOutputDir : null;',+ 'const helperProgressSteps = new Set([',+ ' "subAgent.target",',+ ' "subAgent.acp.message",',+ ' "subAgent.acp.thought",',+ ' "subAgent.acp.tool_call",',+ ' "subAgent.acp.tool_call_update",',+ ' "subAgent.acp.plan",',+ ' "subAgent.acp.fallback",',+ ']);',+ 'const helperDebugUseColor = process.stderr?.isTTY === true && process.env.NO_COLOR !== "1";',+ 'const helperDebugColorize = (line) => helperDebugUseColor ? `\\x1b[90m${line}\\x1b[0m` : line;',+ 'const truncateDebugText = (value, max = 240) => {',+ ' const text = typeof value === "string" ? value : String(value ?? "");',+ ' return text.length > max ? `${text.slice(0, max - 1)}…` : text;',+ '};',+ 'const previewDebugValue = (value) => {',+ ' if (value == null) return "";',+ ' if (typeof value === "string") return truncateDebugText(value.replace(/\\s+/g, " ").trim());',+ ' if (typeof value === "number" || typeof value === "boolean") return String(value);',+ ' if (Array.isArray(value)) return `array(${value.length})`;',+ ' if (typeof value === "object") {',+ ' const preferred = ["message", "error", "title", "summary", "brief", "status"];',+ ' for (const key of preferred) {',+ ' if (typeof value[key] === "string" && value[key].trim().length > 0) {',+ ' return truncateDebugText(value[key].trim());',+ ' }',+ ' }',+ ' return `object{${Object.keys(value).slice(0, 4).join(", ")}}`;',+ ' }',+ ' return truncateDebugText(String(value));',+ '};',+ 'const formatHelperDebugEvent = (step, details = {}) => {',+ ' switch (step) {',+ ' case "subAgent.target":',+ ' return `[subAgent] triggered with ${details.resolvedTarget}`;',+ ' case "subAgent.acp.resolve":',+ ' return `[subAgent] ACP via ${details.source} (${details.target})`;',+ ' case "subAgent.acp.initialized":',+ ' return `[subAgent] ACP initialized (${details.target})`;',+ ' case "subAgent.acp.session":',+ ' return `[subAgent] session ready (${details.target})`;',+ ' case "subAgent.acp.model":',+ ' return details.applied === true',+ ' ? `[subAgent] model=${details.model}`',+ ' : `[subAgent] model unchanged (${details.model})`;',+ ' case "subAgent.acp.message": {',+ ' const text = previewDebugValue(details.text);',+ ' return text ? `[subAgent] ${text}` : null;',+ ' }',+ ' case "subAgent.acp.thought": {',+ ' const text = previewDebugValue(details.text);',+ ' return text ? `[subAgent:thinking] ${text}` : null;',+ ' }',+ ' case "subAgent.acp.tool_call": {',+ ' const where = Array.isArray(details.locations) && details.locations.length > 0 ? ` ${details.locations.slice(0, 2).join(", ")}` : "";',+ ' return `[subAgent:tool] ${details.status || "pending"} ${details.title || details.kind || "tool"}${where}`;',+ ' }',+ ' case "subAgent.acp.tool_call_update": {',+ ' const where = Array.isArray(details.locations) && details.locations.length > 0 ? ` ${details.locations.slice(0, 2).join(", ")}` : "";',+ ' const preview = previewDebugValue(details.rawOutput);',+ ' return `[subAgent:tool] ${details.status || "update"} ${details.title || details.toolCallId || details.kind || "tool"}${where}${preview ? ` -> ${preview}` : ""}`;',+ ' }',+ ' case "subAgent.acp.plan": {',+ ' const entries = Array.isArray(details.entries) ? details.entries : [];',+ ' if (entries.length === 0) return "[subAgent:plan] updated";',+ ' const summary = entries.slice(0, 3).map((entry) => `${entry.status}:${truncateDebugText(entry.content || "", 48)}`).join(" | ");',+ ' return `[subAgent:plan] ${summary}`;',+ ' }',+ ' case "subAgent.acp.fallback":',+ ' return `[subAgent] ACP fallback (${details.code})`;',+ ' case "execute.prepare":',+ ' return `[execute] ${details.slug}`;',+ ' case "search.prepare":',+ ' return `[search] ${truncateDebugText(details.query || "", 96)}`;',+ ' case "proxy.request":',+ ' return `[proxy] ${details.method} ${truncateDebugText(details.endpoint || "", 96)}`;',+ ' case "cli.result": {',+ ' const command = typeof details.command === "string" ? details.command : "cli";',+ ' const state = details.successful === false ? "failed" : "ok";',+ ' const preview = previewDebugValue(details.preview);',+ ' return `[${command}] ${state}${preview ? ` ${preview}` : ""}`;',+ ' }',+ ' case "cli.error": {',+ ' const command = typeof details.command === "string" ? details.command : "cli";',+ ' const stderr = previewDebugValue(details.stderr);',+ ' return `[${command}] failed${stderr ? ` ${stderr}` : ""}`;',+ ' }',+ ' default:',+ ' return null;',+ ' }',+ '};','const helperDebugLog = (step, details = {}) => {',+ ' const line = formatHelperDebugEvent(step, details);',+ ' if (line && (helperDebugEnabled || (helperProgressEnabled && helperProgressSteps.has(step)))) {',+ ' console.error(helperDebugColorize(line));',+ ' return;',+ ' }',' if (!helperDebugEnabled) return;',' const elapsedMs = Date.now() - perfDebugStart;',- ' console.error(`[run:debug] ${JSON.stringify({ step, elapsedMs, ...details })}`);',+ ' console.error(helperDebugColorize(`[run:debug] ${JSON.stringify({ step, elapsedMs, ...details })}`));','};','const parseJson = (text) => {',' const value = text.trim();',@@ -300,20 +446,29 @@ const buildRunBaseHelpersSource = (): ReadonlyArray<string> => [' 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) => {',+ 'const summarizeCliResultPreview = (result) => {',+ ' if (result == null) return null;',+ ' if (typeof result !== "object") return result;',+ ' if ("data" in result && result.data !== undefined) return result.data;',+ ' if ("error" in result && typeof result.error === "string" && result.error.trim().length > 0) return result.error.trim();',+ ' return result;',+ '};',+ 'const logCliResultPreview = (requestId, command, result) => {',' if (!helperDebugEnabled) return;',' if (!result || typeof result !== "object") {',- ' helperDebugLog("cli.result", { requestId, result: describeDebugValue(result) });',+ ' helperDebugLog("cli.result", { requestId, command, preview: result, result: describeDebugValue(result) });',' return;',' }',' helperDebugLog("cli.result", {',' requestId,',+ ' command,',' 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,',+ ' preview: summarizeCliResultPreview(result),',' });','};','const detectInvokeAgentMaster = () => {',@@ -342,11 +497,13 @@ const buildRunBaseHelpersSource = (): ReadonlyArray<string> => [' }',' const inputSchema = options.schema ?? options.jsonSchema;',' let structuredSchema;',+ ' let zodSchema;',' 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.");',' }',+ ' zodSchema = inputSchema;',' structuredSchema = z.toJSONSchema(inputSchema);',' } else if (typeof inputSchema === "object" && inputSchema !== null && !Array.isArray(inputSchema)) {',' structuredSchema = inputSchema;',@@ -354,27 +511,7 @@ const buildRunBaseHelpersSource = (): ReadonlyArray<string> => [' 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 };',+ ' return { ...options, structuredSchema, zodSchema };','};','const requireConsumerProxyContext = () => {',' if (!helperContext.apiKey) {',@@ -504,7 +641,7 @@ const buildRunBaseHelpersSource = (): ReadonlyArray<string> => [' 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 });',+ ' helperDebugLog("cli.error", { requestId, command: args[0], 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;',@@ -513,13 +650,13 @@ const buildRunBaseHelpersSource = (): ReadonlyArray<string> => [' 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 });',+ ' helperDebugLog("cli.error", { requestId, command: args[0], 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);',+ ' logCliResultPreview(requestId, args[0], result);',' helperDebugLog("cli.done", { requestId, exitCode });',' return result;','};',@@ -572,74 +709,38 @@ const buildRunBaseHelpersSource = (): ReadonlyArray<string> => [];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);',+ ' const master = detectInvokeAgentMaster();',+ ' helperDebugLog("subAgent.target", { requestedTarget: normalizedOptions.target ?? null, resolvedTarget: target, master });',+ ' try {',+ ' return await invokeAcpSubAgent({',+ ' prompt: prompt.trim(),',+ ' options: normalizedOptions,',+ ' master,',+ ' target,',+ ' helperDebugLog,',+ ' });',+ ' } catch (error) {',+ ' if (!isAcpInvokeError(error)) {',+ ' throw error;',+ ' }',+ ' if (helperContext.acpOnly === true) {',+ ' throw error;',+ ' }',+ ' helperDebugLog("subAgent.acp.fallback", { target, code: error.code, message: error.message });',+ ' return invokeLegacySubAgent({',+ ' prompt: prompt.trim(),',+ ' options: normalizedOptions,',+ ' master,',+ ' target,',+ ' helperDebugLog,',+ ' });',' }',- ' return invokeCodexAgent(prompt.trim(), normalizedOptions);','};','globalThis.subAgent = subAgentImpl;','Object.defineProperty(globalThis.subAgent, "schema", { value: subAgentSchema });',@@ -713,6 +814,9 @@ export const buildRunHelpersSource = (): string =>['import { z } from "zod";',+ `import { isAcpInvokeError } from ${JSON.stringify(subAgentSharedModuleUrl)};`,+ `import { invokeAcpSubAgent } from ${JSON.stringify(subAgentAcpModuleUrl)};`,+ `import { invokeLegacySubAgent } from ${JSON.stringify(subAgentLegacyModuleUrl)};`,'',`const cliPrefix = ${JSON.stringify(cliPrefix)};`,`const helperContext = ${JSON.stringify(context)};`,@@ -833,6 +937,7 @@ export const runCmd = Command.make('run', {file,dryRun,debug,+ logsOff,skipConnectionCheck,skipToolParamsCheck,noVerify,@@ -881,6 +986,7 @@ export const runCmd = Command.make('run', {'Flags:',' --debug Log helper steps while the script runs',' --dry-run Preview execute() calls without running them',+ ' --logs-off Hide the always-on subAgent streaming logs',' --skip-connection-check Skip the linked-account check',' --skip-tool-params-check Skip input validation against cached schema',' --no-verify Skip both checks above',@@ -892,11 +998,12 @@ export const runCmd = Command.make('run', {].join('\n')),Command.withHandler(- ({ file, dryRun, debug, skipConnectionCheck, skipToolParamsCheck, noVerify, args }) =>+ ({ file, dryRun, debug, logsOff, skipConnectionCheck, skipToolParamsCheck, noVerify, args }) =>Effect.gen(function* () {const runId = process.env.COMPOSIO_CLI_PARENT_RUN_ID ?? crypto.randomUUID();const perfDebug = isPerfDebugEnabled();const toolDebug = isToolDebugEnabled();+ const acpOnly = process.env.COMPOSIO_RUN_ACP_ONLY === '1';if (Option.isNone(file)) {const [inlineCode] = args;const preloadSlugs = extractInlineExecuteToolSlugs(inlineCode ?? '');@@ -915,6 +1022,8 @@ export const runCmd = Command.make('run', {perfDebug,toolDebug,debug,+ logsOff,+ acpOnly,dryRun,skipConnectionCheck,skipToolParamsCheck,diff --git a/ts/packages/cli/src/services/run-subagent-acp.ts b/ts/packages/cli/src/services/run-subagent-acp.tsnew file mode 100644index 000000000..e9e29603c--- /dev/null+++ b/ts/packages/cli/src/services/run-subagent-acp.ts@@ -0,0 +1,376 @@+import { spawn } from 'node:child_process';+import { createRequire } from 'node:module';+import { Readable, Writable } from 'node:stream';+import * as acp from '@agentclientprotocol/sdk';+import type { MasterKind } from 'src/services/master-detector';+import {+ AcpInvokeError,+ buildStructuredPrompt,+ finalizeInvokeAgentText,+ toInvokeAgentResponse,+ type HelperDebugLog,+ type InvokeAgentNormalizedOptions,+ type InvokeAgentResponse,+ type InvokeAgentTarget,+} from 'src/services/run-subagent-shared';++const resolveBundledAdapter = (target: InvokeAgentTarget): string | null => {+ const specifier =+ target === 'claude'+ ? '@zed-industries/claude-code-acp/dist/index.js'+ : '@zed-industries/codex-acp/bin/codex-acp.js';+ try {+ const require = createRequire(import.meta.url);+ return require.resolve(specifier);+ } catch {+ return null;+ }+};++export const resolveAcpAdapterCommand = (+ target: InvokeAgentTarget+): {+ readonly cmd: ReadonlyArray<string>;+ readonly source: 'bundled' | 'which' | 'npx';+} => {+ const binary = target === 'claude' ? 'claude-code-acp' : 'codex-acp';+ const packageName =+ target === 'claude' ? '@zed-industries/claude-code-acp' : '@zed-industries/codex-acp';++ // 1. Try the bundled dependency first (no npx overhead)+ const bundled = resolveBundledAdapter(target);+ if (bundled) {+ return {+ cmd: [process.execPath, bundled],+ source: 'bundled',+ };+ }++ // 2. Check if the binary is on PATH+ if (typeof Bun !== 'undefined' && typeof Bun.which === 'function') {+ const resolved = Bun.which(binary);+ if (resolved) {+ return {+ cmd: [resolved],+ source: 'which',+ };+ }+ }++ // 3. Fall back to npx+ return {+ cmd: [process.platform === 'win32' ? 'npx.cmd' : 'npx', '-y', packageName],+ source: 'npx',+ };+};++const chunkFlushPattern = /[\s,.;:!?)\]}"]$/;++export class BufferedChunkLogger {+ private buffer = '';++ constructor(+ private readonly step: 'subAgent.acp.message' | 'subAgent.acp.thought',+ private readonly helperDebugLog: HelperDebugLog+ ) {}++ push(text: string): void {+ this.buffer += text;+ this.flushCompletedLines();+ this.flushWhenReadable();+ }++ flush(): void {+ this.emit(this.buffer);+ this.buffer = '';+ }++ private flushCompletedLines(): void {+ let newlineIndex = this.buffer.indexOf('\n');+ while (newlineIndex !== -1) {+ const line = this.buffer.slice(0, newlineIndex);+ this.emit(line);+ this.buffer = this.buffer.slice(newlineIndex + 1);+ newlineIndex = this.buffer.indexOf('\n');+ }+ }++ private flushWhenReadable(): void {+ if (this.buffer.length < 48) {+ return;+ }++ if (!chunkFlushPattern.test(this.buffer)) {+ return;+ }++ this.emit(this.buffer);+ this.buffer = '';+ }++ private emit(text: string): void {+ const normalized = text.replace(/\s+/g, ' ').trim();+ if (!normalized) {+ return;+ }++ this.helperDebugLog(this.step, {+ text: normalized,+ });+ }+}++class RunSubAgentClient {+ private readonly textChunks: string[] = [];+ private readonly messageLogger: BufferedChunkLogger;+ private readonly thoughtLogger: BufferedChunkLogger;++ constructor(private readonly helperDebugLog: HelperDebugLog) {+ this.messageLogger = new BufferedChunkLogger('subAgent.acp.message', helperDebugLog);+ this.thoughtLogger = new BufferedChunkLogger('subAgent.acp.thought', helperDebugLog);+ }++ async requestPermission(+ params: acp.RequestPermissionRequest+ ): Promise<acp.RequestPermissionResponse> {+ this.helperDebugLog('subAgent.acp.permission', {+ toolCallId: params.toolCall.toolCallId,+ options: params.options.map(option => option.kind),+ });++ const rejectOption =+ params.options.find(option => option.kind === 'reject_once') ??+ params.options.find(option => option.kind === 'reject_always');++ if (rejectOption) {+ return {+ outcome: {+ outcome: 'selected',+ optionId: rejectOption.optionId,+ },+ };+ }++ return {+ outcome: {+ outcome: 'cancelled',+ },+ };+ }++ async sessionUpdate(params: acp.SessionNotification): Promise<void> {+ const update = params.update;+ if (update.sessionUpdate === 'agent_message_chunk' && update.content.type === 'text') {+ this.textChunks.push(update.content.text);+ this.messageLogger.push(update.content.text);+ return;+ }++ if (update.sessionUpdate === 'agent_thought_chunk' && update.content.type === 'text') {+ this.thoughtLogger.push(update.content.text);+ return;+ }++ if (update.sessionUpdate === 'tool_call') {+ this.helperDebugLog('subAgent.acp.tool_call', {+ title: update.title,+ kind: update.kind ?? null,+ status: update.status ?? null,+ locations: update.locations?.map(location => location.path) ?? [],+ });+ return;+ }++ if (update.sessionUpdate === 'tool_call_update') {+ this.helperDebugLog('subAgent.acp.tool_call_update', {+ toolCallId: update.toolCallId,+ title: update.title ?? null,+ kind: update.kind ?? null,+ status: update.status ?? null,+ locations: update.locations?.map(location => location.path) ?? [],+ rawOutput: update.rawOutput ?? null,+ });+ return;+ }++ if (update.sessionUpdate === 'plan') {+ this.helperDebugLog('subAgent.acp.plan', {+ entries: update.entries.map(entry => ({+ status: entry.status,+ priority: entry.priority ?? null,+ content: entry.content,+ })),+ });+ return;+ }++ this.helperDebugLog('subAgent.acp.update', {+ type: update.sessionUpdate,+ });+ }++ getText(): string {+ this.messageLogger.flush();+ this.thoughtLogger.flush();+ return this.textChunks.join('');+ }+}++const createFallbackError = (+ code: ConstructorParameters<typeof AcpInvokeError>[0],+ message: string,+ cause?: unknown+): AcpInvokeError => new AcpInvokeError(code, message, cause === undefined ? undefined : { cause });++export const invokeAcpSubAgent = async ({+ prompt,+ options,+ master,+ target,+ helperDebugLog,+}: {+ prompt: string;+ options: InvokeAgentNormalizedOptions;+ master: MasterKind;+ target: InvokeAgentTarget;+ helperDebugLog: HelperDebugLog;+}): Promise<InvokeAgentResponse> => {+ const resolved = resolveAcpAdapterCommand(target);+ helperDebugLog('subAgent.acp.resolve', {+ target,+ source: resolved.source,+ command: resolved.cmd[0],+ args: resolved.cmd.slice(1),+ });++ const { CLAUDECODE: _, ...childEnv } = process.env;+ const child = spawn(resolved.cmd[0]!, resolved.cmd.slice(1), {+ cwd: process.cwd(),+ env: childEnv,+ stdio: ['pipe', 'pipe', 'pipe'],+ });++ let stderr = '';+ child.stderr?.setEncoding('utf8');+ child.stderr?.on('data', chunk => {+ stderr += chunk;+ });++ const closePromise = new Promise<{ code: number | null; signal: NodeJS.Signals | null }>(+ (resolve, reject) => {+ child.once('error', reject);+ child.once('close', (code, signal) => resolve({ code, signal }));+ }+ );++ if (!child.stdin || !child.stdout) {+ child.kill();+ throw createFallbackError('spawn_failed', `Failed to spawn ${target} ACP adapter.`);+ }++ const client = new RunSubAgentClient(helperDebugLog);+ const stream = acp.ndJsonStream(+ Writable.toWeb(child.stdin) as unknown as WritableStream<Uint8Array>,+ Readable.toWeb(child.stdout) as unknown as ReadableStream<Uint8Array>+ );+ const connection = new acp.ClientSideConnection(() => client, stream);++ try {+ const initialized = await connection+ .initialize({+ protocolVersion: acp.PROTOCOL_VERSION,+ clientCapabilities: {},+ })+ .catch(error => {+ throw createFallbackError(+ 'initialize_failed',+ `${target} ACP initialize failed${stderr.trim() ? `: ${stderr.trim()}` : ''}`,+ error+ );+ });++ helperDebugLog('subAgent.acp.initialized', {+ target,+ protocolVersion: initialized.protocolVersion,+ });++ const session = await connection+ .newSession({+ cwd: process.cwd(),+ mcpServers: [],+ })+ .catch(error => {+ throw createFallbackError(+ 'session_failed',+ `${target} ACP session creation failed${stderr.trim() ? `: ${stderr.trim()}` : ''}`,+ error+ );+ });++ helperDebugLog('subAgent.acp.session', {+ target,+ sessionId: session.sessionId,+ });++ if (typeof options.model === 'string' && options.model.trim().length > 0) {+ try {+ await connection.unstable_setSessionModel({+ sessionId: session.sessionId,+ modelId: options.model.trim(),+ });+ helperDebugLog('subAgent.acp.model', {+ target,+ model: options.model.trim(),+ applied: true,+ });+ } catch (error) {+ helperDebugLog('subAgent.acp.model', {+ target,+ model: options.model.trim(),+ applied: false,+ error: error instanceof Error ? error.message : String(error),+ });+ }+ }++ const promptText = buildStructuredPrompt(prompt, options.structuredSchema);+ const response = await connection+ .prompt({+ sessionId: session.sessionId,+ prompt: [{ type: 'text', text: promptText }],+ })+ .catch(error => {+ if (connection.signal.aborted) {+ throw createFallbackError(+ 'connection_closed',+ `${target} ACP connection closed before prompt completion${stderr.trim() ? `: ${stderr.trim()}` : ''}`,+ error+ );+ }+ throw createFallbackError(+ 'prompt_failed',+ `${target} ACP prompt failed${stderr.trim() ? `: ${stderr.trim()}` : ''}`,+ error+ );+ });++ if (response.stopReason === 'cancelled') {+ throw createFallbackError(+ 'prompt_failed',+ `${target} ACP prompt was cancelled${stderr.trim() ? `: ${stderr.trim()}` : ''}`+ );+ }++ const payload = finalizeInvokeAgentText(client.getText(), options);+ return toInvokeAgentResponse(master, target, payload);+ } finally {+ child.kill();+ await Promise.race([+ closePromise.catch(() => undefined),+ new Promise(resolve => setTimeout(resolve, 200)),+ ]);+ if (!child.killed) {+ child.kill('SIGKILL');+ }+ }+};diff --git a/ts/packages/cli/src/services/run-subagent-legacy.ts b/ts/packages/cli/src/services/run-subagent-legacy.tsnew file mode 100644index 000000000..dc9e179bf--- /dev/null+++ b/ts/packages/cli/src/services/run-subagent-legacy.ts@@ -0,0 +1,181 @@+import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';+import { spawn } from 'node:child_process';+import type { MasterKind } from 'src/services/master-detector';+import {+ finalizeInvokeAgentText,+ parseJson,+ toInvokeAgentResponse,+ type HelperDebugLog,+ type InvokeAgentNormalizedOptions,+ type InvokeAgentResponse,+ type InvokeAgentTarget,+} from 'src/services/run-subagent-shared';++const runExternalCommandText = async (+ cmd: ReadonlyArray<string>,+ helperDebugLog: HelperDebugLog+) => {+ helperDebugLog('agent.spawn', { command: cmd[0], args: cmd.slice(1) });++ const child = spawn(cmd[0]!, cmd.slice(1), {+ cwd: process.cwd(),+ env: process.env,+ stdio: ['ignore', 'pipe', 'pipe'],+ });++ const stdoutChunks: string[] = [];+ const stderrChunks: string[] = [];++ child.stdout?.setEncoding('utf8');+ child.stdout?.on('data', chunk => stdoutChunks.push(chunk));+ child.stderr?.setEncoding('utf8');+ child.stderr?.on('data', chunk => stderrChunks.push(chunk));++ const exitCode = await new Promise<number>((resolve, reject) => {+ child.once('error', reject);+ child.once('close', code => resolve(code ?? 0));+ });++ const stdout = stdoutChunks.join('');+ const stderr = stderrChunks.join('');++ 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 invokeClaudeLegacy = async (+ prompt: string,+ options: InvokeAgentNormalizedOptions,+ master: MasterKind,+ helperDebugLog: HelperDebugLog+): Promise<InvokeAgentResponse> => {+ helperDebugLog('subAgent.prepare', {+ target: 'claude',+ transport: 'legacy',+ 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, helperDebugLog);+ const parsed = parseJson(result.stdout.trim());+ if (!parsed || typeof parsed !== 'object') {+ throw new Error('claude returned non-JSON output in subAgent().');+ }++ const payload =+ options.structuredSchema !== undefined+ ? {+ result: null,+ structuredOutput: (parsed as { structured_output?: unknown }).structured_output ?? null,+ }+ : {+ result:+ typeof (parsed as { result?: unknown }).result === 'string'+ ? (parsed as { result: string }).result+ : null,+ structuredOutput: null,+ };++ return toInvokeAgentResponse(master, 'claude', payload);+};++const invokeCodexLegacy = async (+ prompt: string,+ options: InvokeAgentNormalizedOptions,+ master: MasterKind,+ helperDebugLog: HelperDebugLog+): Promise<InvokeAgentResponse> => {+ const tempDir = 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',+ transport: 'legacy',+ 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, helperDebugLog);++ const text = fs.readFileSync(outputPath, 'utf8').trim();+ if (options.structuredSchema !== undefined) {+ return toInvokeAgentResponse(master, 'codex', {+ result: null,+ structuredOutput: parseJson(text) ?? null,+ });+ }++ return toInvokeAgentResponse(master, 'codex', {+ result: text,+ structuredOutput: null,+ });+ } finally {+ fs.rmSync(tempDir, { recursive: true, force: true });+ }+};++export const invokeLegacySubAgent = async ({+ prompt,+ options,+ master,+ target,+ helperDebugLog,+}: {+ prompt: string;+ options: InvokeAgentNormalizedOptions;+ master: MasterKind;+ target: InvokeAgentTarget;+ helperDebugLog: HelperDebugLog;+}): Promise<InvokeAgentResponse> => {+ if (target === 'claude') {+ return invokeClaudeLegacy(prompt, options, master, helperDebugLog);+ }++ return invokeCodexLegacy(prompt, options, master, helperDebugLog);+};diff --git a/ts/packages/cli/src/services/run-subagent-shared.ts b/ts/packages/cli/src/services/run-subagent-shared.tsnew file mode 100644index 000000000..ffd270c8f--- /dev/null+++ b/ts/packages/cli/src/services/run-subagent-shared.ts@@ -0,0 +1,154 @@+import type { MasterKind } from 'src/services/master-detector';++export type InvokeAgentTarget = 'claude' | 'codex';++export type InvokeAgentNormalizedOptions = {+ readonly target?: InvokeAgentTarget | 'user';+ readonly model?: string;+ readonly schema?: unknown;+ readonly jsonSchema?: unknown;+ readonly structuredSchema?: Record<string, unknown>;+ readonly zodSchema?: {+ safeParse: (+ value: unknown+ ) => { success: true; data: unknown } | { success: false; error: unknown };+ };+};++export type InvokeAgentResponse = {+ readonly master: MasterKind;+ readonly target: InvokeAgentTarget;+ readonly result: string | null;+ readonly structuredOutput?: unknown;+};++export type HelperDebugLog = (step: string, details?: Record<string, unknown>) => void;++export type AcpInvokeFailure =+ | 'adapter_not_found'+ | 'spawn_failed'+ | 'initialize_failed'+ | 'session_failed'+ | 'prompt_failed'+ | 'connection_closed';++export class AcpInvokeError extends Error {+ readonly code: AcpInvokeFailure;++ constructor(code: AcpInvokeFailure, message: string, options?: { cause?: unknown }) {+ super(message, options);+ this.name = 'AcpInvokeError';+ this.code = code;+ }+}++export const isAcpInvokeError = (value: unknown): value is AcpInvokeError =>+ !!value &&+ typeof value === 'object' &&+ (value as { name?: unknown }).name === 'AcpInvokeError' &&+ typeof (value as { message?: unknown }).message === 'string' &&+ typeof (value as { code?: unknown }).code === 'string';++export const toInvokeAgentResponse = (+ master: MasterKind,+ target: InvokeAgentTarget,+ payload: Partial<Pick<InvokeAgentResponse, 'result' | 'structuredOutput'>> = {}+): InvokeAgentResponse => ({+ master,+ target,+ result: payload.result ?? null,+ ...(payload.structuredOutput === undefined || payload.structuredOutput === null+ ? {}+ : { structuredOutput: payload.structuredOutput }),+});++export const parseJson = (text: string): unknown => {+ const value = text.trim();+ if (!value) {+ return undefined;+ }+ try {+ return JSON.parse(value);+ } catch {+ return value;+ }+};++const summarizeValidationError = (error: unknown): string => {+ const issues =+ error &&+ typeof error === 'object' &&+ 'issues' in error &&+ Array.isArray((error as { issues?: unknown[] }).issues)+ ? (error as { issues: Array<{ path?: unknown[]; message?: unknown }> }).issues+ : [];++ if (issues.length === 0) {+ return 'Invalid structured output.';+ }++ return issues+ .slice(0, 5)+ .map(issue => {+ const path =+ Array.isArray(issue.path) && issue.path.length > 0 ? issue.path.join('.') : '<root>';+ const message = typeof issue.message === 'string' ? issue.message : 'Invalid value';+ return `${path}: ${message}`;+ })+ .join('; ');+};++export const buildStructuredPrompt = (+ prompt: string,+ structuredSchema?: Record<string, unknown>+): string => {+ if (!structuredSchema) {+ return prompt;+ }++ return [+ prompt,+ '',+ 'Return only a valid JSON value that matches this schema.',+ 'Do not include Markdown fences, commentary, or any extra text before or after the JSON.',+ JSON.stringify(structuredSchema, null, 2),+ ].join('\n');+};++export const finalizeInvokeAgentText = (+ text: string,+ options: InvokeAgentNormalizedOptions+): Pick<InvokeAgentResponse, 'result' | 'structuredOutput'> => {+ const trimmed = text.trim();+ if (!options.structuredSchema) {+ return {+ result: trimmed,+ };+ }++ let parsed: unknown;+ try {+ parsed = JSON.parse(trimmed);+ } catch {+ throw new Error('subAgent() expected valid JSON output for structured response.');+ }++ if (options.zodSchema && typeof options.zodSchema.safeParse === 'function') {+ const validation = options.zodSchema.safeParse(parsed);+ if (!validation.success) {+ throw new Error(+ `subAgent() structured output failed schema validation: ${summarizeValidationError(validation.error)}`+ );+ }++ return {+ result: null,+ structuredOutput: validation.data,+ };+ }++ return {+ result: null,+ structuredOutput: parsed,+ };+};diff --git a/ts/packages/cli/test/src/commands/run.cmd.test.ts b/ts/packages/cli/test/src/commands/run.cmd.test.tsindex 0f5d6590e..753dc40b7 100644--- a/ts/packages/cli/test/src/commands/run.cmd.test.ts+++ b/ts/packages/cli/test/src/commands/run.cmd.test.ts@@ -10,6 +10,7 @@ import {inferCliInvocationPrefix,wrapInlineCodeForRun,} from 'src/commands/run.cmd';+import { buildStructuredPrompt, finalizeInvokeAgentText } from 'src/services/run-subagent-shared';import { cli, MockConsole, TestLive } from 'test/__utils__';describe('CLI: composio run', () => {@@ -55,6 +56,48 @@ describe('CLI: composio run', () => {);});+ layer(TestLive())(it => {+ it.scoped(+ '[Given] --acp-only [Then] run accepts the flag and forwards execution normally',+ () =>+ Effect.gen(function* () {+ const spawn = vi.fn(() => ({ exited: Promise.resolve(0) }));+ const exit = vi.spyOn(process, 'exit').mockImplementation((() => undefined) as never);+ vi.stubGlobal('Bun', { spawn });++ yield* cli(['run', '--acp-only', 'console.log("hi")']);++ expect(spawn).toHaveBeenCalledTimes(1);+ const spawnConfig = (spawn as any).mock.calls[0][0] as {+ cmd: string[];+ };+ expect(spawnConfig.cmd[3]).toBe('--eval');+ expect(exit).toHaveBeenCalledWith(0);+ })+ );+ });++ layer(TestLive())(it => {+ it.scoped(+ '[Given] --logs-off [Then] run accepts the flag and forwards execution normally',+ () =>+ Effect.gen(function* () {+ const spawn = vi.fn(() => ({ exited: Promise.resolve(0) }));+ const exit = vi.spyOn(process, 'exit').mockImplementation((() => undefined) as never);+ vi.stubGlobal('Bun', { spawn });++ yield* cli(['run', '--logs-off', 'console.log("hi")']);++ expect(spawn).toHaveBeenCalledTimes(1);+ const spawnConfig = (spawn as any).mock.calls[0][0] as {+ cmd: string[];+ };+ expect(spawnConfig.cmd[3]).toBe('--eval');+ expect(exit).toHaveBeenCalledWith(0);+ })+ );+ });+layer(TestLive())(it => {it.scoped('[Given] --file [Then] it forwards file execution to the embedded Bun runtime', () =>Effect.gen(function* () {@@ -118,12 +161,14 @@ describe('CLI: composio run', () => {expect(output).toContain('--skip-connection-check');expect(output).toContain('--skip-tool-params-check');expect(output).toContain('--no-verify');+ expect(output).toContain('--logs-off');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');+ expect(output).not.toContain('--acp-only');}));});@@ -137,10 +182,15 @@ describe('buildRunHelpersSource', () => {webURL: 'https://app.example.test',orgId: 'org_test',consumerUserId: 'consumer_user_test',+ acpOnly: true,+ logsOff: true,dryRun: true,});expect(source).toContain('import { z } from "zod";');+ expect(source).toContain('import { isAcpInvokeError } from "file://');+ expect(source).toContain('import { invokeAcpSubAgent } from "file://');+ expect(source).toContain('import { invokeLegacySubAgent } from "file://');expect(source).toContain('globalThis.z = z;');expect(source).toContain('globalThis.zod = z;');expect(source).toContain('const stringifyForPrompt = (value) => {');@@ -153,14 +203,18 @@ describe('buildRunHelpersSource', () => {'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('const formatHelperDebugEvent = (step, details = {}) => {');+ expect(source).toContain('return `[subAgent] triggered with ${details.resolvedTarget}`;');+ expect(source).toContain('const logCliResultPreview = (requestId, command, result) => {');expect(source).toContain('helperDebugLog("cli.result", {');expect(source).toContain('helperDebugLog("cli.result.stored_in_file"');+ expect(source).toContain('case "subAgent.acp.message":');expect(source).toContain('COMPOSIO_USER_API_KEY');+ expect(source).toContain('"acpOnly":true');+ expect(source).toContain('"logsOff":true');expect(source).toContain('"consumerUserId":"consumer_user_test"');expect(source).toContain('__composioConsumerContext');expect(source).toContain('globalThis.execute = async (slug, data = {}) => {');@@ -173,9 +227,11 @@ describe('buildRunHelpersSource', () => {'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('return await invokeAcpSubAgent({');+ expect(source).toContain('if (!isAcpInvokeError(error)) {');+ expect(source).toContain('if (helperContext.acpOnly === true) {');+ expect(source).toContain('helperDebugLog("subAgent.acp.fallback"');+ expect(source).toContain('return invokeLegacySubAgent({');expect(source).toContain('const detectInvokeAgentMaster = () => {');expect(source).toContain('throw new Error("subAgent() accepts either options.schema or options.jsonSchema, not both.");'@@ -185,12 +241,12 @@ describe('buildRunHelpersSource', () => {expect(source).toContain('subAgent() requires Zod 4 with z.toJSONSchema() when using options.schema.');+ expect(source).toContain('let zodSchema;');+ expect(source).toContain('zodSchema = inputSchema;');expect(source).toContain('structuredSchema = z.toJSONSchema(inputSchema);');- expect(source).toContain(- '["codex", "exec", "--skip-git-repo-check", "--sandbox", "read-only", "-o", outputPath]'+ expect(source).not.toContain(+ 'const runExternalCommandText = async (cmd, spawnOptions = {}) => {');- 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);');@@ -210,6 +266,45 @@ describe('buildRunHelpersSource', () => {});});+describe('run-subagent-shared', () => {+ it('[Given] a structured schema [Then] it appends a strict JSON response contract', () => {+ expect(buildStructuredPrompt('hello', { type: 'object' })).toContain(+ 'Return only a valid JSON value that matches this schema.'+ );+ });++ it('[Given] Zod-like structured output [Then] it validates and returns structured data', () => {+ const result = finalizeInvokeAgentText('{"ok":true}', {+ structuredSchema: { type: 'object' },+ zodSchema: {+ safeParse: value => ({ success: true as const, data: value }),+ },+ });++ expect(result).toEqual({+ result: null,+ structuredOutput: { ok: true },+ });+ });++ it('[Given] plain text output [Then] it omits structuredOutput', () => {+ const result = finalizeInvokeAgentText('hello', {});++ expect(result).toEqual({+ result: 'hello',+ });+ expect('structuredOutput' in result).toBe(false);+ });++ it('[Given] invalid JSON in structured mode [Then] it throws a clear error', () => {+ expect(() =>+ finalizeInvokeAgentText('not-json', {+ structuredSchema: { type: 'object' },+ })+ ).toThrow('subAgent() expected valid JSON output for structured response.');+ });+});+describe('inferCliInvocationPrefix', () => {it('[Given] a compiled bunfs entrypoint [Then] it falls back to the binary path only', () => {expect(inferCliInvocationPrefix(['node', '/$bunfs/root/composio'])).toEqual([process.execPath]);diff --git a/ts/packages/cli/test/src/services/run-subagent-acp.test.ts b/ts/packages/cli/test/src/services/run-subagent-acp.test.tsnew file mode 100644index 000000000..8092eacf7--- /dev/null+++ b/ts/packages/cli/test/src/services/run-subagent-acp.test.ts@@ -0,0 +1,64 @@+import { afterEach, describe, expect, it, vi } from 'vitest';+import { BufferedChunkLogger, resolveAcpAdapterCommand } from 'src/services/run-subagent-acp';+import { AcpInvokeError, isAcpInvokeError } from 'src/services/run-subagent-shared';++describe('run-subagent-acp', () => {+ afterEach(() => {+ vi.unstubAllGlobals();+ });++ it('[Given] bundled adapter packages [Then] it resolves to the bundled path without npx', () => {+ const result = resolveAcpAdapterCommand('claude');+ expect(result.source).toBe('bundled');+ expect(result.cmd[0]).toBe(process.execPath);+ expect(result.cmd[1]).toMatch(/claude-code-acp/);+ });++ it('[Given] bundled codex adapter [Then] it resolves to the bundled path', () => {+ const result = resolveAcpAdapterCommand('codex');+ expect(result.source).toBe('bundled');+ expect(result.cmd[0]).toBe(process.execPath);+ expect(result.cmd[1]).toMatch(/codex-acp/);+ });++ it('[Given] an ACP invoke error [Then] it is classified for fallback', () => {+ const error = new AcpInvokeError('initialize_failed', 'boom');+ expect(isAcpInvokeError(error)).toBe(true);+ expect(error.code).toBe('initialize_failed');+ });++ it('[Given] an ACP-like error from another bundle [Then] it is still classified for fallback', () => {+ const error = {+ name: 'AcpInvokeError',+ code: 'prompt_failed',+ message: 'boom',+ };++ expect(isAcpInvokeError(error)).toBe(true);+ });++ it('[Given] a cancelled ACP prompt [Then] it remains fallback-eligible', () => {+ const error = new AcpInvokeError('prompt_failed', 'claude ACP prompt was cancelled.');++ expect(isAcpInvokeError(error)).toBe(true);+ expect(error.code).toBe('prompt_failed');+ });++ it('[Given] tokenized message chunks [Then] it emits buffered readable text', () => {+ const helperDebugLog = vi.fn();+ const logger = new BufferedChunkLogger('subAgent.acp.message', helperDebugLog);++ logger.push('Pick');+ logger.push(' one');+ logger.push(' fruit');+ logger.push(' from');+ logger.push(' the');+ logger.push(' mixed');+ logger.push(' box.');+ logger.flush();++ expect(helperDebugLog).toHaveBeenCalledWith('subAgent.acp.message', {+ text: 'Pick one fruit from the mixed box.',+ });+ });+});