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

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

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

Synced Nov 22, 02:00 UTC

Add ACP-backed subagent execution to `composio run` (#3011)

## Summary - Adds a new ACP execution path for `subAgent()` in the CLI `run` command, with fallback to the legacy CLI-based implementation when ACP is unavailable. - Introduces shared subagent helpers plus separate ACP and legacy service modules to keep the invocation logic isolated. - Adds `--acp-only` to force ACP usage and fail instead of falling back. - Updates binary build output so the CLI ships the companion modules needed by the `run` command in both source and compiled forms. - Bumps CLI dependencies to include ACP packages used by the new execution path. ## Testing - `pnpm test ts/packages/cli/test/src/commands/run.cmd.test.ts` - `pnpm test ts/packages/cli/test/src/services/run-subagent-acp.test.ts` - Not run: full repository build or end-to-end CLI validation.

Rahul Tarak committed Mar 24, 2026 at 20:34 UTC f4922f9757b5cbb0812f37f9e4a53514dff89244
11 files changed +1295 -102
pnpm-lock.yaml
+136
@@ -1043,6 +1043,9 @@ importers:
1043
1044 ts/packages/cli:
1045 dependencies:
1046 + '@agentclientprotocol/sdk':
1047 + specifier: ^0.16.1
1048 + version: 0.16.1(zod@4.3.6)
1049 '@clack/core':
1050 specifier: 'catalog:'
1051 version: 1.0.1
@@ -1067,6 +1070,12 @@ importers:
1070 '@effect/platform-node-shared':
1071 specifier: 'catalog:'
1072 version: 0.57.1(@effect/cluster@0.56.4(@effect/platform@0.94.5(effect@3.19.18))(@effect/rpc@0.73.2(@effect/platform@0.94.5(effect@3.19.18))(effect@3.19.18))(@effect/sql@0.49.0(@effect/experimental@0.58.0(@effect/platform@0.94.5(effect@3.19.18))(effect@3.19.18))(@effect/platform@0.94.5(effect@3.19.18))(effect@3.19.18))(@effect/workflow@0.16.0(@effect/experimental@0.58.0(@effect/platform@0.94.5(effect@3.19.18))(effect@3.19.18))(@effect/platform@0.94.5(effect@3.19.18))(@effect/rpc@0.73.2(@effect/platform@0.94.5(effect@3.19.18))(effect@3.19.18))(effect@3.19.18))(effect@3.19.18))(@effect/platform@0.94.5(effect@3.19.18))(@effect/rpc@0.73.2(@effect/platform@0.94.5(effect@3.19.18))(effect@3.19.18))(@effect/sql@0.49.0(@effect/experimental@0.58.0(@effect/platform@0.94.5(effect@3.19.18))(effect@3.19.18))(@effect/platform@0.94.5(effect@3.19.18))(effect@3.19.18))(effect@3.19.18)
1073 + '@zed-industries/claude-code-acp':
1074 + specifier: ^0.16.2
1075 + version: 0.16.2(@cfworker/json-schema@4.1.1)(zod@4.3.6)
1076 + '@zed-industries/codex-acp':
1077 + specifier: ^0.10.0
1078 + version: 0.10.0
1079 ansis:
1080 specifier: ^4.1.0
1081 version: 4.2.0
@@ -1450,6 +1459,16 @@ packages:
1459 resolution: {integrity: sha512-VTDuRS5V0ATbJ/LkaQlisMnTAeYKXAK6scMguVBstf+KIBQ7HIuKhiXLv+G/hvejkV+THoXzoNifInAkU81P1g==}
1460 engines: {node: '>=18'}
1461
1462 + '@agentclientprotocol/sdk@0.14.1':
1463 + resolution: {integrity: sha512-b6r3PS3Nly+Wyw9U+0nOr47bV8tfS476EgyEMhoKvJCZLbgqoDFN7DJwkxL88RR0aiOqOYV1ZnESHqb+RmdH8w==}
1464 + peerDependencies:
1465 + zod: ^3.25.0 || ^4.0.0
1466 +
1467 + '@agentclientprotocol/sdk@0.16.1':
1468 + resolution: {integrity: sha512-1ad+Sc/0sCtZGHthxxvgEUo5Wsbw16I+aF+YwdiLnPwkZG8KAGUEAPK6LM6Pf69lCyJPt1Aomk1d+8oE3C4ZEw==}
1469 + peerDependencies:
1470 + zod: ^3.25.0 || ^4.0.0
1471 +
1472 '@ai-sdk/gateway@3.0.49':
1473 resolution: {integrity: sha512-Smq0sMMqhIxZIUN7TjXitpa5M8SrJCpe/6rHxU7In6FuKb7y16qkj8vvWzmZtQFWZ/1h1Yo+h5ZdcS1KtgMP4g==}
1474 engines: {node: '>=18'}
@@ -1557,6 +1576,12 @@ packages:
1576 peerDependencies:
1577 zod: ^3.25.0 || ^4.0.0
1578
1579 + '@anthropic-ai/claude-agent-sdk@0.2.44':
1580 + resolution: {integrity: sha512-bryUo6qq5dalO4MmhYLTPonTOAmdSVpMaVLJl8Y0qm6M7G+NZ3WS4cTMGrTbz97Uz5nah+FIOMA4hh8sKLm3YQ==}
1581 + engines: {node: '>=18.0.0'}
1582 + peerDependencies:
1583 + zod: ^4.0.0
1584 +
1585 '@anthropic-ai/sdk@0.52.0':
1586 resolution: {integrity: sha512-d4c+fg+xy9e46c8+YnrrgIQR45CZlAi7PwdzIfDXDM6ACxEZli1/fxhURsq30ZpMZy6LvSkr41jGq5aF5TD7rQ==}
1587 hasBin: true
@@ -3629,6 +3654,51 @@ packages:
3654 '@vitest/utils@3.2.4':
3655 resolution: {integrity: sha512-fB2V0JFrQSMsCo9HiSq3Ezpdv4iYaXRG1Sx8edX3MwxfyNn83mKiGzOcH+Fkxt4MHxr3y42fQi1oeAInqgX2QA==}
3656
3657 + '@zed-industries/claude-code-acp@0.16.2':
3658 + resolution: {integrity: sha512-D8BJe6CCD49RtNFbZYPsfZOpQI8Z/EzhyYC9zAGMwN/HVunEtVY2sXqYl1iDSkkayzhqABfaDkDZfeqDM1T/aA==}
3659 + deprecated: This package has been renamed to @zed-industries/claude-agent-acp. Please migrate to continue receiving updates.
3660 + hasBin: true
3661 +
3662 + '@zed-industries/codex-acp-darwin-arm64@0.10.0':
3663 + resolution: {integrity: sha512-zlIZH+X2aEfxC5UgnIoYbX0cG3/MpRUsQAGJbrcBbgKp0mhuBFtMJHZ426JC5rb3pv8amo1MmDeARZUQ99U/CQ==}
3664 + cpu: [arm64]
3665 + os: [darwin]
3666 + hasBin: true
3667 +
3668 + '@zed-industries/codex-acp-darwin-x64@0.10.0':
3669 + resolution: {integrity: sha512-TFMF9YqfWplnYpWRaUauRbtps1ow1S47MVcBv21/Sd55gRMWWYWSogRLDyAcoMC4y9pdI2bYhx33u7jYhJnj5w==}
3670 + cpu: [x64]
3671 + os: [darwin]
3672 + hasBin: true
3673 +
3674 + '@zed-industries/codex-acp-linux-arm64@0.10.0':
3675 + resolution: {integrity: sha512-tIm0uGKZuirZyqx9KAgIgh6cimVXdh+BMTFyUfH1xnez5Y3B6oFxzup/ZIP34OZ/W59Cnfi4wcIL3No0VV6Kmw==}
3676 + cpu: [arm64]
3677 + os: [linux]
3678 + hasBin: true
3679 +
3680 + '@zed-industries/codex-acp-linux-x64@0.10.0':
3681 + resolution: {integrity: sha512-oiiN35wsecX1OwesV/KIu72o1OSw+OWFL86vQUUZTdfMXr9eyYFP1uZYLMxIx+tkhlJnm7KHC5L4raDg/MLVtA==}
3682 + cpu: [x64]
3683 + os: [linux]
3684 + hasBin: true
3685 +
3686 + '@zed-industries/codex-acp-win32-arm64@0.10.0':
3687 + resolution: {integrity: sha512-dfybabjibQQpXUs9TjwLjg+mrj8tGSopVcwkFy8u3XG4hrBZVCri91dtVhm7hs98lZlawxwiiPuj4Pmg+4hHyQ==}
3688 + cpu: [arm64]
3689 + os: [win32]
3690 + hasBin: true
3691 +
3692 + '@zed-industries/codex-acp-win32-x64@0.10.0':
3693 + resolution: {integrity: sha512-xCm3xsE3lD66DlbaLKBqHahPY1Lhb+rGu2IIq60qUsBGiYcSXtpRjQ1LXI/Sym6iCKrPo+eQP0j6rg7CPh1AGw==}
3694 + cpu: [x64]
3695 + os: [win32]
3696 + hasBin: true
3697 +
3698 + '@zed-industries/codex-acp@0.10.0':
3699 + resolution: {integrity: sha512-vzwAUSHR7TaJh62JoE+6UD/HVm8fJbmMGsMBBMcHrKBIL7MF8yevlPDWVdoaDaGOsgqVZYRv9KhdT8ari0I4mg==}
3700 + hasBin: true
3701 +
3702 accepts@1.3.8:
3703 resolution: {integrity: sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==}
3704 engines: {node: '>= 0.6'}
@@ -4087,6 +4157,10 @@ packages:
4157 devalue@5.6.2:
4158 resolution: {integrity: sha512-nPRkjWzzDQlsejL1WVifk5rvcFi/y1onBRxjaFMjZeR9mFpqu2gmAZ9xUB9/IEanEP/vBtGeGganC/GO1fmufg==}
4159
4160 + diff@8.0.3:
4161 + resolution: {integrity: sha512-qejHi7bcSD4hQAZE0tNAawRK1ZtafHDmMTMkrrIGgSLl7hTnQHmKCeB45xAcbfTqK2zowkM3j3bHt/4b/ARbYQ==}
4162 + engines: {node: '>=0.3.1'}
4163 +
4164 dir-glob@3.0.1:
4165 resolution: {integrity: sha512-WkrWp9GR4KXfKGYzOLmTuGVi1UWFfws377n9cc55/tb6DuqyF6pcQ5AbiHEshaDpY9v6oaSr2XCDidGmMwdzIA==}
4166 engines: {node: '>=8'}
@@ -6372,6 +6446,14 @@ snapshots:
6446 transitivePeerDependencies:
6447 - supports-color
6448
6449 + '@agentclientprotocol/sdk@0.14.1(zod@4.3.6)':
6450 + dependencies:
6451 + zod: 4.3.6
6452 +
6453 + '@agentclientprotocol/sdk@0.16.1(zod@4.3.6)':
6454 + dependencies:
6455 + zod: 4.3.6
6456 +
6457 '@ai-sdk/gateway@3.0.49(zod@3.25.76)':
6458 dependencies:
6459 '@ai-sdk/provider': 3.0.8
@@ -6556,6 +6638,19 @@ snapshots:
6638 '@img/sharp-linuxmusl-x64': 0.33.5
6639 '@img/sharp-win32-x64': 0.33.5
6640
6641 + '@anthropic-ai/claude-agent-sdk@0.2.44(zod@4.3.6)':
6642 + dependencies:
6643 + zod: 4.3.6
6644 + optionalDependencies:
6645 + '@img/sharp-darwin-arm64': 0.33.5
6646 + '@img/sharp-darwin-x64': 0.33.5
6647 + '@img/sharp-linux-arm': 0.33.5
6648 + '@img/sharp-linux-arm64': 0.33.5
6649 + '@img/sharp-linux-x64': 0.33.5
6650 + '@img/sharp-linuxmusl-arm64': 0.33.5
6651 + '@img/sharp-linuxmusl-x64': 0.33.5
6652 + '@img/sharp-win32-x64': 0.33.5
6653 +
6654 '@anthropic-ai/sdk@0.52.0': {}
6655
6656 '@anthropic-ai/sdk@0.71.2(zod@3.25.76)':
@@ -8556,6 +8651,45 @@ snapshots:
8651 loupe: 3.2.1
8652 tinyrainbow: 2.0.0
8653
8654 + '@zed-industries/claude-code-acp@0.16.2(@cfworker/json-schema@4.1.1)(zod@4.3.6)':
8655 + dependencies:
8656 + '@agentclientprotocol/sdk': 0.14.1(zod@4.3.6)
8657 + '@anthropic-ai/claude-agent-sdk': 0.2.44(zod@4.3.6)
8658 + '@modelcontextprotocol/sdk': 1.26.0(@cfworker/json-schema@4.1.1)(zod@4.3.6)
8659 + diff: 8.0.3
8660 + minimatch: 10.2.1
8661 + transitivePeerDependencies:
8662 + - '@cfworker/json-schema'
8663 + - supports-color
8664 + - zod
8665 +
8666 + '@zed-industries/codex-acp-darwin-arm64@0.10.0':
8667 + optional: true
8668 +
8669 + '@zed-industries/codex-acp-darwin-x64@0.10.0':
8670 + optional: true
8671 +
8672 + '@zed-industries/codex-acp-linux-arm64@0.10.0':
8673 + optional: true
8674 +
8675 + '@zed-industries/codex-acp-linux-x64@0.10.0':
8676 + optional: true
8677 +
8678 + '@zed-industries/codex-acp-win32-arm64@0.10.0':
8679 + optional: true
8680 +
8681 + '@zed-industries/codex-acp-win32-x64@0.10.0':
8682 + optional: true
8683 +
8684 + '@zed-industries/codex-acp@0.10.0':
8685 + optionalDependencies:
8686 + '@zed-industries/codex-acp-darwin-arm64': 0.10.0
8687 + '@zed-industries/codex-acp-darwin-x64': 0.10.0
8688 + '@zed-industries/codex-acp-linux-arm64': 0.10.0
8689 + '@zed-industries/codex-acp-linux-x64': 0.10.0
8690 + '@zed-industries/codex-acp-win32-arm64': 0.10.0
8691 + '@zed-industries/codex-acp-win32-x64': 0.10.0
8692 +
8693 accepts@1.3.8:
8694 dependencies:
8695 mime-types: 2.1.35
@@ -9002,6 +9136,8 @@ snapshots:
9136
9137 devalue@5.6.2: {}
9138
9139 + diff@8.0.3: {}
9140 +
9141 dir-glob@3.0.1:
9142 dependencies:
9143 path-type: 4.0.0
ts/packages/cli/package.json
+3
@@ -67,6 +67,9 @@
67 "vitest": "catalog:"
68 },
69 "dependencies": {
70 + "@agentclientprotocol/sdk": "^0.16.1",
71 + "@zed-industries/claude-code-acp": "^0.16.2",
72 + "@zed-industries/codex-acp": "^0.10.0",
73 "@clack/core": "catalog:",
74 "@clack/prompts": "catalog:",
75 "@composio/client": "catalog:",
ts/packages/cli/scripts/build-binary.ts
+53
@@ -72,6 +72,59 @@ export function buildBinary() {
72 }
73
74 yield* Effect.logDebug('', 'Binary built successfully');
75 +
76 + // Build companion modules that `composio run` imports in the child process.
77 + // These cannot live inside the compiled binary because they run in a separate
78 + // Bun process via the --preload globals file.
79 + const companionModules = [
80 + 'src/services/run-subagent-shared.ts',
81 + 'src/services/run-subagent-acp.ts',
82 + 'src/services/run-subagent-legacy.ts',
83 + ] as const;
84 +
85 + for (const entry of companionModules) {
86 + const name = entry.replace(/^.*\//, '').replace(/\.ts$/, '');
87 + const companionArgs = [
88 + 'bun',
89 + 'build',
90 + `./${entry}`,
91 + '--outfile',
92 + `./dist/${name}.mjs`,
93 + '--format',
94 + 'esm',
95 + '--target',
96 + 'bun',
97 + ] as const satisfies ReadonlyArray<string>;
98 +
99 + yield* Effect.logDebug(`Building companion module: ${name}`);
100 +
101 + const companionCmd = Command.make(...companionArgs);
102 + const { exitCode: companionExitCode } = yield* companionCmd.pipe(
103 + Command.start,
104 + Effect.flatMap(p =>
105 + Effect.all(
106 + {
107 + exitCode: p.exitCode,
108 + output: Stream.merge(
109 + Stream.decodeText(p.stdout, 'utf-8'),
110 + Stream.decodeText(p.stderr, 'utf-8'),
111 + { haltStrategy: 'left' }
112 + ).pipe(
113 + Stream.tap(chunk => Console.log(chunk)),
114 + Stream.runDrain
115 + ),
116 + },
117 + { concurrency: 'unbounded' }
118 + )
119 + )
120 + );
121 +
122 + if (companionExitCode !== 0) {
123 + return yield* Effect.fail(new Error(`Failed to build companion module: ${name}`));
124 + }
125 + }
126 +
127 + yield* Effect.logDebug('', 'Companion modules built successfully');
128 });
129 }
130
ts/packages/cli/src/commands/index.ts
+18
@@ -130,6 +130,7 @@ const normalizeHiddenDebugFlags = (argv: ReadonlyArray<string>): ReadonlyArray<s
130 const args = argv.slice(2);
131 let perfDebug: boolean | undefined;
132 let toolDebug: boolean | undefined;
133 + let acpOnly: boolean | undefined;
134
135 for (const arg of args) {
136 if (arg === '--perf-debug') {
@@ -156,6 +157,18 @@ const normalizeHiddenDebugFlags = (argv: ReadonlyArray<string>): ReadonlyArray<s
157 toolDebug = true;
158 continue;
159 }
160 + if (arg === '--acp-only') {
161 + acpOnly = true;
162 + continue;
163 + }
164 + if (arg === '--acp-only=false') {
165 + acpOnly = false;
166 + continue;
167 + }
168 + if (arg === '--acp-only=true') {
169 + acpOnly = true;
170 + continue;
171 + }
172 normalized.push(arg);
173 }
174
@@ -164,6 +177,11 @@ const normalizeHiddenDebugFlags = (argv: ReadonlyArray<string>): ReadonlyArray<s
177 ...(perfDebug === undefined ? {} : { perfDebug }),
178 ...(toolDebug === undefined ? {} : { toolDebug }),
179 });
180 + if (acpOnly === undefined) {
181 + delete process.env.COMPOSIO_RUN_ACP_ONLY;
182 + } else {
183 + process.env.COMPOSIO_RUN_ACP_ONLY = acpOnly ? '1' : '0';
184 + }
185
186 return normalized;
187 };
ts/packages/cli/src/commands/root-help.ts
+7 -3
@@ -76,9 +76,12 @@ const CORE_COMMANDS: ReadonlyArray<DetailedCommand> = [
76 // ── Developer commands ─────────────────────────────────────────────────
77
78 const OTHER_COMMANDS: ReadonlyArray<CompactCommand> = [
79 - { name: 'tools info <slug>', description: 'Print tool summary and cache its schema' },
80 - { name: 'tools list <toolkit>', description: 'List tools available in a toolkit' },
81 - { name: 'artifacts cwd', description: 'Print the cwd-scoped session artifact directory' },
79 + { name: 'composio tools info <slug>', description: 'Print tool summary and cache its schema' },
80 + { name: 'composio tools list <toolkit>', description: 'List tools available in a toolkit' },
81 + {
82 + name: 'composio artifacts cwd',
83 + description: 'Print the cwd-scoped session artifact directory',
84 + },
85 ];
86
87 const DEVELOPER_COMMANDS: ReadonlyArray<CompactCommand> = [
@@ -260,6 +263,7 @@ const SUBCOMMAND_HELP: Record<string, SubcommandHelp> = {
263 { name: '-f, --file <text>', description: 'Run a TS/JS file instead of inline code' },
264 { name: '--dry-run', description: 'Preview execute() calls without running them' },
265 { name: '--debug', description: 'Log helper steps while the script runs' },
266 + { name: '--logs-off', description: 'Hide the always-on subAgent streaming logs' },
267 ],
268 flags: [
269 { name: '--skip-connection-check', description: 'Skip the linked-account check' },
ts/packages/cli/src/commands/run.cmd.ts
+199 -90
@@ -2,6 +2,7 @@ import * as fs from 'node:fs';
2 import * as os from 'node:os';
3 import * as path from 'node:path';
4 import process from 'node:process';
5 +import { fileURLToPath, pathToFileURL } from 'node:url';
6 import { Args, Command, Options } from '@effect/cli';
7 import { Effect, Option } from 'effect';
8 import { ts } from 'ts-morph';
@@ -29,6 +30,10 @@ const debug = Options.boolean('debug').pipe(
30 Options.withDescription('Log helper steps while the script runs'),
31 Options.withDefault(false)
32 );
33 +const logsOff = Options.boolean('logs-off').pipe(
34 + Options.withDescription('Hide the always-on subAgent streaming logs'),
35 + Options.withDefault(false)
36 +);
37 const skipConnectionCheck = Options.boolean('skip-connection-check').pipe(
38 Options.withDescription('Skip the linked-account check'),
39 Options.withDefault(false)
@@ -155,6 +160,48 @@ export const inferCliInvocationPrefix = (
160 : [process.execPath];
161 };
162
163 +const resolveSiblingModulePath = (relativeNoExtensionFromRunCmd: string): string => {
164 + const currentFilePath = fileURLToPath(import.meta.url);
165 + const currentDirectory = path.dirname(currentFilePath);
166 +
167 + // Source (.ts) — running from `bun src/bin.ts`
168 + const tsPath = path.resolve(currentDirectory, `${relativeNoExtensionFromRunCmd}.ts`);
169 + if (fs.existsSync(tsPath)) {
170 + return tsPath;
171 + }
172 +
173 + // Built (.js) — running from `bun dist/bin.mjs`
174 + const jsPath = path.resolve(currentDirectory, `${relativeNoExtensionFromRunCmd}.js`);
175 + if (fs.existsSync(jsPath)) {
176 + return jsPath;
177 + }
178 +
179 + // Compiled binary — import.meta.url points to /$bunfs/, files live next to the executable
180 + const baseName = path.basename(relativeNoExtensionFromRunCmd);
181 + const exeDir = path.dirname(process.execPath);
182 + const mjsPath = path.resolve(exeDir, `${baseName}.mjs`);
183 + if (fs.existsSync(mjsPath)) {
184 + return mjsPath;
185 + }
186 + const exeJsPath = path.resolve(exeDir, `${baseName}.js`);
187 + if (fs.existsSync(exeJsPath)) {
188 + return exeJsPath;
189 + }
190 +
191 + // Fallback — return the .js path (will error at runtime with a clear module-not-found)
192 + return jsPath;
193 +};
194 +
195 +const subAgentSharedModuleUrl = pathToFileURL(
196 + resolveSiblingModulePath('../services/run-subagent-shared')
197 +).href;
198 +const subAgentAcpModuleUrl = pathToFileURL(
199 + resolveSiblingModulePath('../services/run-subagent-acp')
200 +).href;
201 +const subAgentLegacyModuleUrl = pathToFileURL(
202 + resolveSiblingModulePath('../services/run-subagent-legacy')
203 +).href;
204 +
205 type RunHelperContext = {
206 readonly apiKey?: string;
207 readonly baseURL?: string;
@@ -172,6 +219,8 @@ type RunHelperContext = {
219 readonly noVerify?: boolean;
220 readonly master?: MasterKind;
221 readonly debug?: boolean;
222 + readonly acpOnly?: boolean;
223 + readonly logsOff?: boolean;
224 readonly runOutputDir?: string;
225 };
226
@@ -203,7 +252,7 @@ const buildRunBaseHelpersSource = (): ReadonlyArray<string> => [
252 ' returns: {',
253 ' type: "object",',
254 ' additionalProperties: false,',
206 - ' required: ["master", "target", "result", "structuredOutput"],',
255 + ' required: ["master", "target", "result"],',
256 ' properties: {',
257 ' master: { type: "string", enum: ["claude", "codex", "user"] },',
258 ' target: { type: "string", enum: ["claude", "codex"] },',
@@ -244,11 +293,108 @@ const buildRunBaseHelpersSource = (): ReadonlyArray<string> => [
293 ' console.error(`[perf] ${JSON.stringify(payload)}`);',
294 '};',
295 'const helperDebugEnabled = helperContext.debug === true;',
296 + 'const helperProgressEnabled = helperContext.logsOff !== true;',
297 'const sharedRunOutputDir = typeof helperContext.runOutputDir === "string" && helperContext.runOutputDir.length > 0 ? helperContext.runOutputDir : null;',
298 + 'const helperProgressSteps = new Set([',
299 + ' "subAgent.target",',
300 + ' "subAgent.acp.message",',
301 + ' "subAgent.acp.thought",',
302 + ' "subAgent.acp.tool_call",',
303 + ' "subAgent.acp.tool_call_update",',
304 + ' "subAgent.acp.plan",',
305 + ' "subAgent.acp.fallback",',
306 + ']);',
307 + 'const helperDebugUseColor = process.stderr?.isTTY === true && process.env.NO_COLOR !== "1";',
308 + 'const helperDebugColorize = (line) => helperDebugUseColor ? `\\x1b[90m${line}\\x1b[0m` : line;',
309 + 'const truncateDebugText = (value, max = 240) => {',
310 + ' const text = typeof value === "string" ? value : String(value ?? "");',
311 + ' return text.length > max ? `${text.slice(0, max - 1)}…` : text;',
312 + '};',
313 + 'const previewDebugValue = (value) => {',
314 + ' if (value == null) return "";',
315 + ' if (typeof value === "string") return truncateDebugText(value.replace(/\\s+/g, " ").trim());',
316 + ' if (typeof value === "number" || typeof value === "boolean") return String(value);',
317 + ' if (Array.isArray(value)) return `array(${value.length})`;',
318 + ' if (typeof value === "object") {',
319 + ' const preferred = ["message", "error", "title", "summary", "brief", "status"];',
320 + ' for (const key of preferred) {',
321 + ' if (typeof value[key] === "string" && value[key].trim().length > 0) {',
322 + ' return truncateDebugText(value[key].trim());',
323 + ' }',
324 + ' }',
325 + ' return `object{${Object.keys(value).slice(0, 4).join(", ")}}`;',
326 + ' }',
327 + ' return truncateDebugText(String(value));',
328 + '};',
329 + 'const formatHelperDebugEvent = (step, details = {}) => {',
330 + ' switch (step) {',
331 + ' case "subAgent.target":',
332 + ' return `[subAgent] triggered with ${details.resolvedTarget}`;',
333 + ' case "subAgent.acp.resolve":',
334 + ' return `[subAgent] ACP via ${details.source} (${details.target})`;',
335 + ' case "subAgent.acp.initialized":',
336 + ' return `[subAgent] ACP initialized (${details.target})`;',
337 + ' case "subAgent.acp.session":',
338 + ' return `[subAgent] session ready (${details.target})`;',
339 + ' case "subAgent.acp.model":',
340 + ' return details.applied === true',
341 + ' ? `[subAgent] model=${details.model}`',
342 + ' : `[subAgent] model unchanged (${details.model})`;',
343 + ' case "subAgent.acp.message": {',
344 + ' const text = previewDebugValue(details.text);',
345 + ' return text ? `[subAgent] ${text}` : null;',
346 + ' }',
347 + ' case "subAgent.acp.thought": {',
348 + ' const text = previewDebugValue(details.text);',
349 + ' return text ? `[subAgent:thinking] ${text}` : null;',
350 + ' }',
351 + ' case "subAgent.acp.tool_call": {',
352 + ' const where = Array.isArray(details.locations) && details.locations.length > 0 ? ` ${details.locations.slice(0, 2).join(", ")}` : "";',
353 + ' return `[subAgent:tool] ${details.status || "pending"} ${details.title || details.kind || "tool"}${where}`;',
354 + ' }',
355 + ' case "subAgent.acp.tool_call_update": {',
356 + ' const where = Array.isArray(details.locations) && details.locations.length > 0 ? ` ${details.locations.slice(0, 2).join(", ")}` : "";',
357 + ' const preview = previewDebugValue(details.rawOutput);',
358 + ' return `[subAgent:tool] ${details.status || "update"} ${details.title || details.toolCallId || details.kind || "tool"}${where}${preview ? ` -> ${preview}` : ""}`;',
359 + ' }',
360 + ' case "subAgent.acp.plan": {',
361 + ' const entries = Array.isArray(details.entries) ? details.entries : [];',
362 + ' if (entries.length === 0) return "[subAgent:plan] updated";',
363 + ' const summary = entries.slice(0, 3).map((entry) => `${entry.status}:${truncateDebugText(entry.content || "", 48)}`).join(" | ");',
364 + ' return `[subAgent:plan] ${summary}`;',
365 + ' }',
366 + ' case "subAgent.acp.fallback":',
367 + ' return `[subAgent] ACP fallback (${details.code})`;',
368 + ' case "execute.prepare":',
369 + ' return `[execute] ${details.slug}`;',
370 + ' case "search.prepare":',
371 + ' return `[search] ${truncateDebugText(details.query || "", 96)}`;',
372 + ' case "proxy.request":',
373 + ' return `[proxy] ${details.method} ${truncateDebugText(details.endpoint || "", 96)}`;',
374 + ' case "cli.result": {',
375 + ' const command = typeof details.command === "string" ? details.command : "cli";',
376 + ' const state = details.successful === false ? "failed" : "ok";',
377 + ' const preview = previewDebugValue(details.preview);',
378 + ' return `[${command}] ${state}${preview ? ` ${preview}` : ""}`;',
379 + ' }',
380 + ' case "cli.error": {',
381 + ' const command = typeof details.command === "string" ? details.command : "cli";',
382 + ' const stderr = previewDebugValue(details.stderr);',
383 + ' return `[${command}] failed${stderr ? ` ${stderr}` : ""}`;',
384 + ' }',
385 + ' default:',
386 + ' return null;',
387 + ' }',
388 + '};',
389 'const helperDebugLog = (step, details = {}) => {',
390 + ' const line = formatHelperDebugEvent(step, details);',
391 + ' if (line && (helperDebugEnabled || (helperProgressEnabled && helperProgressSteps.has(step)))) {',
392 + ' console.error(helperDebugColorize(line));',
393 + ' return;',
394 + ' }',
395 ' if (!helperDebugEnabled) return;',
396 ' const elapsedMs = Date.now() - perfDebugStart;',
251 - ' console.error(`[run:debug] ${JSON.stringify({ step, elapsedMs, ...details })}`);',
397 + ' console.error(helperDebugColorize(`[run:debug] ${JSON.stringify({ step, elapsedMs, ...details })}`));',
398 '};',
399 'const parseJson = (text) => {',
400 ' const value = text.trim();',
@@ -300,20 +446,29 @@ const buildRunBaseHelpersSource = (): ReadonlyArray<string> => [
446 ' if (value && typeof value === "object") return { type: "object", keys: Object.keys(value).slice(0, 20) };',
447 ' return { type: typeof value, value: typeof value === "string" ? value.slice(0, 200) : value ?? null };',
448 '};',
303 - 'const logCliResultPreview = (requestId, result) => {',
449 + 'const summarizeCliResultPreview = (result) => {',
450 + ' if (result == null) return null;',
451 + ' if (typeof result !== "object") return result;',
452 + ' if ("data" in result && result.data !== undefined) return result.data;',
453 + ' if ("error" in result && typeof result.error === "string" && result.error.trim().length > 0) return result.error.trim();',
454 + ' return result;',
455 + '};',
456 + 'const logCliResultPreview = (requestId, command, result) => {',
457 ' if (!helperDebugEnabled) return;',
458 ' if (!result || typeof result !== "object") {',
306 - ' helperDebugLog("cli.result", { requestId, result: describeDebugValue(result) });',
459 + ' helperDebugLog("cli.result", { requestId, command, preview: result, result: describeDebugValue(result) });',
460 ' return;',
461 ' }',
462 ' helperDebugLog("cli.result", {',
463 ' requestId,',
464 + ' command,',
465 ' successful: result.successful ?? null,',
466 ' storedInFile: result.storedInFile ?? false,',
467 ' outputFilePath: result.outputFilePath ?? null,',
468 ' error: result.error ?? null,',
469 ' topLevelKeys: Object.keys(result).slice(0, 20),',
470 ' data: "data" in result ? describeDebugValue(result.data) : null,',
471 + ' preview: summarizeCliResultPreview(result),',
472 ' });',
473 '};',
474 'const detectInvokeAgentMaster = () => {',
@@ -342,11 +497,13 @@ const buildRunBaseHelpersSource = (): ReadonlyArray<string> => [
497 ' }',
498 ' const inputSchema = options.schema ?? options.jsonSchema;',
499 ' let structuredSchema;',
500 + ' let zodSchema;',
501 ' if (inputSchema !== undefined) {',
502 ' if (inputSchema && typeof inputSchema.safeParse === "function" && inputSchema._def) {',
503 ' if (typeof z.toJSONSchema !== "function") {',
504 ' throw new Error("subAgent() requires Zod 4 with z.toJSONSchema() when using options.schema.");',
505 ' }',
506 + ' zodSchema = inputSchema;',
507 ' structuredSchema = z.toJSONSchema(inputSchema);',
508 ' } else if (typeof inputSchema === "object" && inputSchema !== null && !Array.isArray(inputSchema)) {',
509 ' structuredSchema = inputSchema;',
@@ -354,27 +511,7 @@ const buildRunBaseHelpersSource = (): ReadonlyArray<string> => [
511 ' throw new Error("subAgent() schema must be a Zod schema or JSON Schema object.");',
512 ' }',
513 ' }',
357 - ' return { ...options, structuredSchema };',
358 - '};',
359 - 'const runExternalCommandText = async (cmd, spawnOptions = {}) => {',
360 - ' helperDebugLog("agent.spawn", { command: cmd[0], args: cmd.slice(1) });',
361 - ' const child = Bun.spawn({',
362 - ' cmd,',
363 - ' env: { ...process.env, ...(sharedRunOutputDir ? { COMPOSIO_RUN_OUTPUT_DIR: sharedRunOutputDir } : {}), ...(spawnOptions.env || {}) },',
364 - ' cwd: spawnOptions.cwd || process.cwd(),',
365 - ' stdio: ["pipe", "pipe", "pipe"],',
366 - ' });',
367 - ' const stdout = child.stdout ? await new Response(child.stdout).text() : "";',
368 - ' const stderr = child.stderr ? await new Response(child.stderr).text() : "";',
369 - ' const exitCode = await child.exited;',
370 - ' if (exitCode !== 0) {',
371 - ' const details = stderr.trim() || stdout.trim();',
372 - ' const suffix = details ? `: ${details}` : "";',
373 - ' helperDebugLog("agent.error", { command: cmd[0], exitCode, stderr: stderr.trim() || undefined });',
374 - ' throw new Error(`${cmd[0]} failed with exit code ${exitCode}${suffix}`);',
375 - ' }',
376 - ' helperDebugLog("agent.done", { command: cmd[0], exitCode, stdoutBytes: stdout.length, stderrBytes: stderr.length });',
377 - ' return { stdout, stderr, exitCode };',
514 + ' return { ...options, structuredSchema, zodSchema };',
515 '};',
516 'const requireConsumerProxyContext = () => {',
517 ' if (!helperContext.apiKey) {',
@@ -504,7 +641,7 @@ const buildRunBaseHelpersSource = (): ReadonlyArray<string> => [
641 ' const exitCode = await child.exited;',
642 ' if (exitCode !== 0) {',
643 ' perfDebugLog("error", requestId, { exitCode, stderr: stderr.trim() || undefined });',
507 - ' helperDebugLog("cli.error", { requestId, exitCode, stderr: stderr.trim() || undefined });',
644 + ' helperDebugLog("cli.error", { requestId, command: args[0], exitCode, stderr: stderr.trim() || undefined });',
645 ' const error = new Error(`composio ${args.join(" ")} failed with exit code ${exitCode}`);',
646 ' Object.assign(error, { exitCode, result, stderr: stderr.trim() || undefined });',
647 ' throw error;',
@@ -513,13 +650,13 @@ const buildRunBaseHelpersSource = (): ReadonlyArray<string> => [
650 ' const details = stderr.trim();',
651 ' const suffix = details ? `: ${details}` : "";',
652 ' perfDebugLog("error", requestId, { exitCode, stderr: details || undefined, noJson: true });',
516 - ' helperDebugLog("cli.error", { requestId, exitCode, stderr: details || undefined, noJson: true });',
653 + ' helperDebugLog("cli.error", { requestId, command: args[0], exitCode, stderr: details || undefined, noJson: true });',
654 ' const error = new Error(`composio ${args.join(" ")} returned no JSON output${suffix}`);',
655 ' Object.assign(error, { exitCode, result, stderr: details || undefined });',
656 ' throw error;',
657 ' }',
658 ' perfDebugLog("end", requestId, { exitCode, stdoutBytes: stdout.length, stderrBytes: stderr.length });',
522 - ' logCliResultPreview(requestId, result);',
659 + ' logCliResultPreview(requestId, args[0], result);',
660 ' helperDebugLog("cli.done", { requestId, exitCode });',
661 ' return result;',
662 '};',
@@ -572,74 +709,38 @@ const buildRunBaseHelpersSource = (): ReadonlyArray<string> => [
709 ];
710
711 const buildRunInvokeAgentHelpersSource = (): ReadonlyArray<string> => [
575 - 'const toInvokeAgentResponse = (master, target, payload = {}) => ({',
576 - ' master,',
577 - ' target,',
578 - ' result: payload.result ?? null,',
579 - ' structuredOutput: payload.structuredOutput ?? null,',
580 - '});',
581 - 'const invokeClaudeAgent = async (prompt, options) => {',
582 - ' helperDebugLog("subAgent.prepare", { target: "claude", hasSchema: options.structuredSchema !== undefined });',
583 - ' const args = ["claude", "--bare", "-p", "--output-format", "json"];',
584 - ' if (typeof options.model === "string" && options.model.trim().length > 0) {',
585 - ' args.push("--model", options.model.trim());',
586 - ' }',
587 - ' if (options.structuredSchema !== undefined) {',
588 - ' args.push("--json-schema", JSON.stringify(options.structuredSchema));',
589 - ' }',
590 - ' args.push(prompt);',
591 - ' const result = await runExternalCommandText(args);',
592 - ' const parsed = parseJson(result.stdout.trim());',
593 - ' if (!parsed || typeof parsed !== "object") {',
594 - ' throw new Error("claude returned non-JSON output in subAgent().");',
595 - ' }',
596 - ' return toInvokeAgentResponse(detectInvokeAgentMaster(), "claude", {',
597 - ' result: typeof parsed.result === "string" ? parsed.result : null,',
598 - ' structuredOutput: parsed.structured_output ?? null,',
599 - ' });',
600 - '};',
601 - 'const invokeCodexAgent = async (prompt, options) => {',
602 - ' const fs = await import("node:fs");',
603 - ' const os = await import("node:os");',
604 - ' const path = await import("node:path");',
605 - ' const tempDir = sharedRunOutputDir',
606 - ' ? fs.mkdtempSync(path.join(sharedRunOutputDir, "invoke-agent-"))',
607 - ' : fs.mkdtempSync(path.join(os.tmpdir(), "composio-invoke-agent-"));',
608 - ' const outputPath = path.join(tempDir, "last-message.txt");',
609 - ' const args = ["codex", "exec", "--skip-git-repo-check", "--sandbox", "read-only", "-o", outputPath];',
610 - ' try {',
611 - ' helperDebugLog("subAgent.prepare", { target: "codex", hasSchema: options.structuredSchema !== undefined });',
612 - ' if (typeof options.model === "string" && options.model.trim().length > 0) {',
613 - ' args.push("--model", options.model.trim());',
614 - ' }',
615 - ' if (options.structuredSchema !== undefined) {',
616 - ' const schemaPath = path.join(tempDir, "schema.json");',
617 - ' fs.writeFileSync(schemaPath, JSON.stringify(options.structuredSchema), "utf8");',
618 - ' args.push("--output-schema", schemaPath);',
619 - ' }',
620 - ' args.push(prompt);',
621 - ' await runExternalCommandText(args);',
622 - ' const text = fs.readFileSync(outputPath, "utf8").trim();',
623 - ' const parsed = options.structuredSchema ? parseJson(text) : null;',
624 - ' return toInvokeAgentResponse(detectInvokeAgentMaster(), "codex", {',
625 - ' result: options.structuredSchema ? null : text,',
626 - ' structuredOutput: options.structuredSchema ? parsed : null,',
627 - ' });',
628 - ' } finally {',
629 - ' fs.rmSync(tempDir, { recursive: true, force: true });',
630 - ' }',
631 - '};',
712 'const subAgentImpl = async (prompt, options = {}) => {',
713 ' if (typeof prompt !== "string" || prompt.trim().length === 0) {',
714 ' throw new Error("subAgent() requires a non-empty prompt string.");',
715 ' }',
716 ' const normalizedOptions = normalizeInvokeAgentOptions(options);',
717 ' const target = resolveInvokeAgentTarget(normalizedOptions.target);',
638 - ' helperDebugLog("subAgent.target", { requestedTarget: normalizedOptions.target ?? null, resolvedTarget: target });',
639 - ' if (target === "claude") {',
640 - ' return invokeClaudeAgent(prompt.trim(), normalizedOptions);',
718 + ' const master = detectInvokeAgentMaster();',
719 + ' helperDebugLog("subAgent.target", { requestedTarget: normalizedOptions.target ?? null, resolvedTarget: target, master });',
720 + ' try {',
721 + ' return await invokeAcpSubAgent({',
722 + ' prompt: prompt.trim(),',
723 + ' options: normalizedOptions,',
724 + ' master,',
725 + ' target,',
726 + ' helperDebugLog,',
727 + ' });',
728 + ' } catch (error) {',
729 + ' if (!isAcpInvokeError(error)) {',
730 + ' throw error;',
731 + ' }',
732 + ' if (helperContext.acpOnly === true) {',
733 + ' throw error;',
734 + ' }',
735 + ' helperDebugLog("subAgent.acp.fallback", { target, code: error.code, message: error.message });',
736 + ' return invokeLegacySubAgent({',
737 + ' prompt: prompt.trim(),',
738 + ' options: normalizedOptions,',
739 + ' master,',
740 + ' target,',
741 + ' helperDebugLog,',
742 + ' });',
743 ' }',
642 - ' return invokeCodexAgent(prompt.trim(), normalizedOptions);',
744 '};',
745 'globalThis.subAgent = subAgentImpl;',
746 'Object.defineProperty(globalThis.subAgent, "schema", { value: subAgentSchema });',
@@ -713,6 +814,9 @@ export const buildRunHelpersSource = (
814 ): string =>
815 [
816 'import { z } from "zod";',
817 + `import { isAcpInvokeError } from ${JSON.stringify(subAgentSharedModuleUrl)};`,
818 + `import { invokeAcpSubAgent } from ${JSON.stringify(subAgentAcpModuleUrl)};`,
819 + `import { invokeLegacySubAgent } from ${JSON.stringify(subAgentLegacyModuleUrl)};`,
820 '',
821 `const cliPrefix = ${JSON.stringify(cliPrefix)};`,
822 `const helperContext = ${JSON.stringify(context)};`,
@@ -833,6 +937,7 @@ export const runCmd = Command.make('run', {
937 file,
938 dryRun,
939 debug,
940 + logsOff,
941 skipConnectionCheck,
942 skipToolParamsCheck,
943 noVerify,
@@ -881,6 +986,7 @@ export const runCmd = Command.make('run', {
986 'Flags:',
987 ' --debug Log helper steps while the script runs',
988 ' --dry-run Preview execute() calls without running them',
989 + ' --logs-off Hide the always-on subAgent streaming logs',
990 ' --skip-connection-check Skip the linked-account check',
991 ' --skip-tool-params-check Skip input validation against cached schema',
992 ' --no-verify Skip both checks above',
@@ -892,11 +998,12 @@ export const runCmd = Command.make('run', {
998 ].join('\n')
999 ),
1000 Command.withHandler(
895 - ({ file, dryRun, debug, skipConnectionCheck, skipToolParamsCheck, noVerify, args }) =>
1001 + ({ file, dryRun, debug, logsOff, skipConnectionCheck, skipToolParamsCheck, noVerify, args }) =>
1002 Effect.gen(function* () {
1003 const runId = process.env.COMPOSIO_CLI_PARENT_RUN_ID ?? crypto.randomUUID();
1004 const perfDebug = isPerfDebugEnabled();
1005 const toolDebug = isToolDebugEnabled();
1006 + const acpOnly = process.env.COMPOSIO_RUN_ACP_ONLY === '1';
1007 if (Option.isNone(file)) {
1008 const [inlineCode] = args;
1009 const preloadSlugs = extractInlineExecuteToolSlugs(inlineCode ?? '');
@@ -915,6 +1022,8 @@ export const runCmd = Command.make('run', {
1022 perfDebug,
1023 toolDebug,
1024 debug,
1025 + logsOff,
1026 + acpOnly,
1027 dryRun,
1028 skipConnectionCheck,
1029 skipToolParamsCheck,
ts/packages/cli/src/services/run-subagent-acp.ts new
+376
@@ -0,0 +1,376 @@
1 +import { spawn } from 'node:child_process';
2 +import { createRequire } from 'node:module';
3 +import { Readable, Writable } from 'node:stream';
4 +import * as acp from '@agentclientprotocol/sdk';
5 +import type { MasterKind } from 'src/services/master-detector';
6 +import {
7 + AcpInvokeError,
8 + buildStructuredPrompt,
9 + finalizeInvokeAgentText,
10 + toInvokeAgentResponse,
11 + type HelperDebugLog,
12 + type InvokeAgentNormalizedOptions,
13 + type InvokeAgentResponse,
14 + type InvokeAgentTarget,
15 +} from 'src/services/run-subagent-shared';
16 +
17 +const resolveBundledAdapter = (target: InvokeAgentTarget): string | null => {
18 + const specifier =
19 + target === 'claude'
20 + ? '@zed-industries/claude-code-acp/dist/index.js'
21 + : '@zed-industries/codex-acp/bin/codex-acp.js';
22 + try {
23 + const require = createRequire(import.meta.url);
24 + return require.resolve(specifier);
25 + } catch {
26 + return null;
27 + }
28 +};
29 +
30 +export const resolveAcpAdapterCommand = (
31 + target: InvokeAgentTarget
32 +): {
33 + readonly cmd: ReadonlyArray<string>;
34 + readonly source: 'bundled' | 'which' | 'npx';
35 +} => {
36 + const binary = target === 'claude' ? 'claude-code-acp' : 'codex-acp';
37 + const packageName =
38 + target === 'claude' ? '@zed-industries/claude-code-acp' : '@zed-industries/codex-acp';
39 +
40 + // 1. Try the bundled dependency first (no npx overhead)
41 + const bundled = resolveBundledAdapter(target);
42 + if (bundled) {
43 + return {
44 + cmd: [process.execPath, bundled],
45 + source: 'bundled',
46 + };
47 + }
48 +
49 + // 2. Check if the binary is on PATH
50 + if (typeof Bun !== 'undefined' && typeof Bun.which === 'function') {
51 + const resolved = Bun.which(binary);
52 + if (resolved) {
53 + return {
54 + cmd: [resolved],
55 + source: 'which',
56 + };
57 + }
58 + }
59 +
60 + // 3. Fall back to npx
61 + return {
62 + cmd: [process.platform === 'win32' ? 'npx.cmd' : 'npx', '-y', packageName],
63 + source: 'npx',
64 + };
65 +};
66 +
67 +const chunkFlushPattern = /[\s,.;:!?)\]}"]$/;
68 +
69 +export class BufferedChunkLogger {
70 + private buffer = '';
71 +
72 + constructor(
73 + private readonly step: 'subAgent.acp.message' | 'subAgent.acp.thought',
74 + private readonly helperDebugLog: HelperDebugLog
75 + ) {}
76 +
77 + push(text: string): void {
78 + this.buffer += text;
79 + this.flushCompletedLines();
80 + this.flushWhenReadable();
81 + }
82 +
83 + flush(): void {
84 + this.emit(this.buffer);
85 + this.buffer = '';
86 + }
87 +
88 + private flushCompletedLines(): void {
89 + let newlineIndex = this.buffer.indexOf('\n');
90 + while (newlineIndex !== -1) {
91 + const line = this.buffer.slice(0, newlineIndex);
92 + this.emit(line);
93 + this.buffer = this.buffer.slice(newlineIndex + 1);
94 + newlineIndex = this.buffer.indexOf('\n');
95 + }
96 + }
97 +
98 + private flushWhenReadable(): void {
99 + if (this.buffer.length < 48) {
100 + return;
101 + }
102 +
103 + if (!chunkFlushPattern.test(this.buffer)) {
104 + return;
105 + }
106 +
107 + this.emit(this.buffer);
108 + this.buffer = '';
109 + }
110 +
111 + private emit(text: string): void {
112 + const normalized = text.replace(/\s+/g, ' ').trim();
113 + if (!normalized) {
114 + return;
115 + }
116 +
117 + this.helperDebugLog(this.step, {
118 + text: normalized,
119 + });
120 + }
121 +}
122 +
123 +class RunSubAgentClient {
124 + private readonly textChunks: string[] = [];
125 + private readonly messageLogger: BufferedChunkLogger;
126 + private readonly thoughtLogger: BufferedChunkLogger;
127 +
128 + constructor(private readonly helperDebugLog: HelperDebugLog) {
129 + this.messageLogger = new BufferedChunkLogger('subAgent.acp.message', helperDebugLog);
130 + this.thoughtLogger = new BufferedChunkLogger('subAgent.acp.thought', helperDebugLog);
131 + }
132 +
133 + async requestPermission(
134 + params: acp.RequestPermissionRequest
135 + ): Promise<acp.RequestPermissionResponse> {
136 + this.helperDebugLog('subAgent.acp.permission', {
137 + toolCallId: params.toolCall.toolCallId,
138 + options: params.options.map(option => option.kind),
139 + });
140 +
141 + const rejectOption =
142 + params.options.find(option => option.kind === 'reject_once') ??
143 + params.options.find(option => option.kind === 'reject_always');
144 +
145 + if (rejectOption) {
146 + return {
147 + outcome: {
148 + outcome: 'selected',
149 + optionId: rejectOption.optionId,
150 + },
151 + };
152 + }
153 +
154 + return {
155 + outcome: {
156 + outcome: 'cancelled',
157 + },
158 + };
159 + }
160 +
161 + async sessionUpdate(params: acp.SessionNotification): Promise<void> {
162 + const update = params.update;
163 + if (update.sessionUpdate === 'agent_message_chunk' && update.content.type === 'text') {
164 + this.textChunks.push(update.content.text);
165 + this.messageLogger.push(update.content.text);
166 + return;
167 + }
168 +
169 + if (update.sessionUpdate === 'agent_thought_chunk' && update.content.type === 'text') {
170 + this.thoughtLogger.push(update.content.text);
171 + return;
172 + }
173 +
174 + if (update.sessionUpdate === 'tool_call') {
175 + this.helperDebugLog('subAgent.acp.tool_call', {
176 + title: update.title,
177 + kind: update.kind ?? null,
178 + status: update.status ?? null,
179 + locations: update.locations?.map(location => location.path) ?? [],
180 + });
181 + return;
182 + }
183 +
184 + if (update.sessionUpdate === 'tool_call_update') {
185 + this.helperDebugLog('subAgent.acp.tool_call_update', {
186 + toolCallId: update.toolCallId,
187 + title: update.title ?? null,
188 + kind: update.kind ?? null,
189 + status: update.status ?? null,
190 + locations: update.locations?.map(location => location.path) ?? [],
191 + rawOutput: update.rawOutput ?? null,
192 + });
193 + return;
194 + }
195 +
196 + if (update.sessionUpdate === 'plan') {
197 + this.helperDebugLog('subAgent.acp.plan', {
198 + entries: update.entries.map(entry => ({
199 + status: entry.status,
200 + priority: entry.priority ?? null,
201 + content: entry.content,
202 + })),
203 + });
204 + return;
205 + }
206 +
207 + this.helperDebugLog('subAgent.acp.update', {
208 + type: update.sessionUpdate,
209 + });
210 + }
211 +
212 + getText(): string {
213 + this.messageLogger.flush();
214 + this.thoughtLogger.flush();
215 + return this.textChunks.join('');
216 + }
217 +}
218 +
219 +const createFallbackError = (
220 + code: ConstructorParameters<typeof AcpInvokeError>[0],
221 + message: string,
222 + cause?: unknown
223 +): AcpInvokeError => new AcpInvokeError(code, message, cause === undefined ? undefined : { cause });
224 +
225 +export const invokeAcpSubAgent = async ({
226 + prompt,
227 + options,
228 + master,
229 + target,
230 + helperDebugLog,
231 +}: {
232 + prompt: string;
233 + options: InvokeAgentNormalizedOptions;
234 + master: MasterKind;
235 + target: InvokeAgentTarget;
236 + helperDebugLog: HelperDebugLog;
237 +}): Promise<InvokeAgentResponse> => {
238 + const resolved = resolveAcpAdapterCommand(target);
239 + helperDebugLog('subAgent.acp.resolve', {
240 + target,
241 + source: resolved.source,
242 + command: resolved.cmd[0],
243 + args: resolved.cmd.slice(1),
244 + });
245 +
246 + const { CLAUDECODE: _, ...childEnv } = process.env;
247 + const child = spawn(resolved.cmd[0]!, resolved.cmd.slice(1), {
248 + cwd: process.cwd(),
249 + env: childEnv,
250 + stdio: ['pipe', 'pipe', 'pipe'],
251 + });
252 +
253 + let stderr = '';
254 + child.stderr?.setEncoding('utf8');
255 + child.stderr?.on('data', chunk => {
256 + stderr += chunk;
257 + });
258 +
259 + const closePromise = new Promise<{ code: number | null; signal: NodeJS.Signals | null }>(
260 + (resolve, reject) => {
261 + child.once('error', reject);
262 + child.once('close', (code, signal) => resolve({ code, signal }));
263 + }
264 + );
265 +
266 + if (!child.stdin || !child.stdout) {
267 + child.kill();
268 + throw createFallbackError('spawn_failed', `Failed to spawn ${target} ACP adapter.`);
269 + }
270 +
271 + const client = new RunSubAgentClient(helperDebugLog);
272 + const stream = acp.ndJsonStream(
273 + Writable.toWeb(child.stdin) as unknown as WritableStream<Uint8Array>,
274 + Readable.toWeb(child.stdout) as unknown as ReadableStream<Uint8Array>
275 + );
276 + const connection = new acp.ClientSideConnection(() => client, stream);
277 +
278 + try {
279 + const initialized = await connection
280 + .initialize({
281 + protocolVersion: acp.PROTOCOL_VERSION,
282 + clientCapabilities: {},
283 + })
284 + .catch(error => {
285 + throw createFallbackError(
286 + 'initialize_failed',
287 + `${target} ACP initialize failed${stderr.trim() ? `: ${stderr.trim()}` : ''}`,
288 + error
289 + );
290 + });
291 +
292 + helperDebugLog('subAgent.acp.initialized', {
293 + target,
294 + protocolVersion: initialized.protocolVersion,
295 + });
296 +
297 + const session = await connection
298 + .newSession({
299 + cwd: process.cwd(),
300 + mcpServers: [],
301 + })
302 + .catch(error => {
303 + throw createFallbackError(
304 + 'session_failed',
305 + `${target} ACP session creation failed${stderr.trim() ? `: ${stderr.trim()}` : ''}`,
306 + error
307 + );
308 + });
309 +
310 + helperDebugLog('subAgent.acp.session', {
311 + target,
312 + sessionId: session.sessionId,
313 + });
314 +
315 + if (typeof options.model === 'string' && options.model.trim().length > 0) {
316 + try {
317 + await connection.unstable_setSessionModel({
318 + sessionId: session.sessionId,
319 + modelId: options.model.trim(),
320 + });
321 + helperDebugLog('subAgent.acp.model', {
322 + target,
323 + model: options.model.trim(),
324 + applied: true,
325 + });
326 + } catch (error) {
327 + helperDebugLog('subAgent.acp.model', {
328 + target,
329 + model: options.model.trim(),
330 + applied: false,
331 + error: error instanceof Error ? error.message : String(error),
332 + });
333 + }
334 + }
335 +
336 + const promptText = buildStructuredPrompt(prompt, options.structuredSchema);
337 + const response = await connection
338 + .prompt({
339 + sessionId: session.sessionId,
340 + prompt: [{ type: 'text', text: promptText }],
341 + })
342 + .catch(error => {
343 + if (connection.signal.aborted) {
344 + throw createFallbackError(
345 + 'connection_closed',
346 + `${target} ACP connection closed before prompt completion${stderr.trim() ? `: ${stderr.trim()}` : ''}`,
347 + error
348 + );
349 + }
350 + throw createFallbackError(
351 + 'prompt_failed',
352 + `${target} ACP prompt failed${stderr.trim() ? `: ${stderr.trim()}` : ''}`,
353 + error
354 + );
355 + });
356 +
357 + if (response.stopReason === 'cancelled') {
358 + throw createFallbackError(
359 + 'prompt_failed',
360 + `${target} ACP prompt was cancelled${stderr.trim() ? `: ${stderr.trim()}` : ''}`
361 + );
362 + }
363 +
364 + const payload = finalizeInvokeAgentText(client.getText(), options);
365 + return toInvokeAgentResponse(master, target, payload);
366 + } finally {
367 + child.kill();
368 + await Promise.race([
369 + closePromise.catch(() => undefined),
370 + new Promise(resolve => setTimeout(resolve, 200)),
371 + ]);
372 + if (!child.killed) {
373 + child.kill('SIGKILL');
374 + }
375 + }
376 +};
ts/packages/cli/src/services/run-subagent-legacy.ts new
+181
@@ -0,0 +1,181 @@
1 +import * as fs from 'node:fs';
2 +import * as os from 'node:os';
3 +import * as path from 'node:path';
4 +import { spawn } from 'node:child_process';
5 +import type { MasterKind } from 'src/services/master-detector';
6 +import {
7 + finalizeInvokeAgentText,
8 + parseJson,
9 + toInvokeAgentResponse,
10 + type HelperDebugLog,
11 + type InvokeAgentNormalizedOptions,
12 + type InvokeAgentResponse,
13 + type InvokeAgentTarget,
14 +} from 'src/services/run-subagent-shared';
15 +
16 +const runExternalCommandText = async (
17 + cmd: ReadonlyArray<string>,
18 + helperDebugLog: HelperDebugLog
19 +) => {
20 + helperDebugLog('agent.spawn', { command: cmd[0], args: cmd.slice(1) });
21 +
22 + const child = spawn(cmd[0]!, cmd.slice(1), {
23 + cwd: process.cwd(),
24 + env: process.env,
25 + stdio: ['ignore', 'pipe', 'pipe'],
26 + });
27 +
28 + const stdoutChunks: string[] = [];
29 + const stderrChunks: string[] = [];
30 +
31 + child.stdout?.setEncoding('utf8');
32 + child.stdout?.on('data', chunk => stdoutChunks.push(chunk));
33 + child.stderr?.setEncoding('utf8');
34 + child.stderr?.on('data', chunk => stderrChunks.push(chunk));
35 +
36 + const exitCode = await new Promise<number>((resolve, reject) => {
37 + child.once('error', reject);
38 + child.once('close', code => resolve(code ?? 0));
39 + });
40 +
41 + const stdout = stdoutChunks.join('');
42 + const stderr = stderrChunks.join('');
43 +
44 + if (exitCode !== 0) {
45 + const details = stderr.trim() || stdout.trim();
46 + const suffix = details ? `: ${details}` : '';
47 + helperDebugLog('agent.error', {
48 + command: cmd[0],
49 + exitCode,
50 + stderr: stderr.trim() || undefined,
51 + });
52 + throw new Error(`${cmd[0]} failed with exit code ${exitCode}${suffix}`);
53 + }
54 +
55 + helperDebugLog('agent.done', {
56 + command: cmd[0],
57 + exitCode,
58 + stdoutBytes: stdout.length,
59 + stderrBytes: stderr.length,
60 + });
61 + return { stdout, stderr, exitCode };
62 +};
63 +
64 +const invokeClaudeLegacy = async (
65 + prompt: string,
66 + options: InvokeAgentNormalizedOptions,
67 + master: MasterKind,
68 + helperDebugLog: HelperDebugLog
69 +): Promise<InvokeAgentResponse> => {
70 + helperDebugLog('subAgent.prepare', {
71 + target: 'claude',
72 + transport: 'legacy',
73 + hasSchema: options.structuredSchema !== undefined,
74 + });
75 +
76 + const args = ['claude', '--bare', '-p', '--output-format', 'json'];
77 + if (typeof options.model === 'string' && options.model.trim().length > 0) {
78 + args.push('--model', options.model.trim());
79 + }
80 + if (options.structuredSchema !== undefined) {
81 + args.push('--json-schema', JSON.stringify(options.structuredSchema));
82 + }
83 + args.push(prompt);
84 +
85 + const result = await runExternalCommandText(args, helperDebugLog);
86 + const parsed = parseJson(result.stdout.trim());
87 + if (!parsed || typeof parsed !== 'object') {
88 + throw new Error('claude returned non-JSON output in subAgent().');
89 + }
90 +
91 + const payload =
92 + options.structuredSchema !== undefined
93 + ? {
94 + result: null,
95 + structuredOutput: (parsed as { structured_output?: unknown }).structured_output ?? null,
96 + }
97 + : {
98 + result:
99 + typeof (parsed as { result?: unknown }).result === 'string'
100 + ? (parsed as { result: string }).result
101 + : null,
102 + structuredOutput: null,
103 + };
104 +
105 + return toInvokeAgentResponse(master, 'claude', payload);
106 +};
107 +
108 +const invokeCodexLegacy = async (
109 + prompt: string,
110 + options: InvokeAgentNormalizedOptions,
111 + master: MasterKind,
112 + helperDebugLog: HelperDebugLog
113 +): Promise<InvokeAgentResponse> => {
114 + const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'composio-invoke-agent-'));
115 + const outputPath = path.join(tempDir, 'last-message.txt');
116 + const args = [
117 + 'codex',
118 + 'exec',
119 + '--skip-git-repo-check',
120 + '--sandbox',
121 + 'read-only',
122 + '-o',
123 + outputPath,
124 + ];
125 +
126 + try {
127 + helperDebugLog('subAgent.prepare', {
128 + target: 'codex',
129 + transport: 'legacy',
130 + hasSchema: options.structuredSchema !== undefined,
131 + });
132 +
133 + if (typeof options.model === 'string' && options.model.trim().length > 0) {
134 + args.push('--model', options.model.trim());
135 + }
136 +
137 + if (options.structuredSchema !== undefined) {
138 + const schemaPath = path.join(tempDir, 'schema.json');
139 + fs.writeFileSync(schemaPath, JSON.stringify(options.structuredSchema), 'utf8');
140 + args.push('--output-schema', schemaPath);
141 + }
142 +
143 + args.push(prompt);
144 + await runExternalCommandText(args, helperDebugLog);
145 +
146 + const text = fs.readFileSync(outputPath, 'utf8').trim();
147 + if (options.structuredSchema !== undefined) {
148 + return toInvokeAgentResponse(master, 'codex', {
149 + result: null,
150 + structuredOutput: parseJson(text) ?? null,
151 + });
152 + }
153 +
154 + return toInvokeAgentResponse(master, 'codex', {
155 + result: text,
156 + structuredOutput: null,
157 + });
158 + } finally {
159 + fs.rmSync(tempDir, { recursive: true, force: true });
160 + }
161 +};
162 +
163 +export const invokeLegacySubAgent = async ({
164 + prompt,
165 + options,
166 + master,
167 + target,
168 + helperDebugLog,
169 +}: {
170 + prompt: string;
171 + options: InvokeAgentNormalizedOptions;
172 + master: MasterKind;
173 + target: InvokeAgentTarget;
174 + helperDebugLog: HelperDebugLog;
175 +}): Promise<InvokeAgentResponse> => {
176 + if (target === 'claude') {
177 + return invokeClaudeLegacy(prompt, options, master, helperDebugLog);
178 + }
179 +
180 + return invokeCodexLegacy(prompt, options, master, helperDebugLog);
181 +};
ts/packages/cli/src/services/run-subagent-shared.ts new
+154
@@ -0,0 +1,154 @@
1 +import type { MasterKind } from 'src/services/master-detector';
2 +
3 +export type InvokeAgentTarget = 'claude' | 'codex';
4 +
5 +export type InvokeAgentNormalizedOptions = {
6 + readonly target?: InvokeAgentTarget | 'user';
7 + readonly model?: string;
8 + readonly schema?: unknown;
9 + readonly jsonSchema?: unknown;
10 + readonly structuredSchema?: Record<string, unknown>;
11 + readonly zodSchema?: {
12 + safeParse: (
13 + value: unknown
14 + ) => { success: true; data: unknown } | { success: false; error: unknown };
15 + };
16 +};
17 +
18 +export type InvokeAgentResponse = {
19 + readonly master: MasterKind;
20 + readonly target: InvokeAgentTarget;
21 + readonly result: string | null;
22 + readonly structuredOutput?: unknown;
23 +};
24 +
25 +export type HelperDebugLog = (step: string, details?: Record<string, unknown>) => void;
26 +
27 +export type AcpInvokeFailure =
28 + | 'adapter_not_found'
29 + | 'spawn_failed'
30 + | 'initialize_failed'
31 + | 'session_failed'
32 + | 'prompt_failed'
33 + | 'connection_closed';
34 +
35 +export class AcpInvokeError extends Error {
36 + readonly code: AcpInvokeFailure;
37 +
38 + constructor(code: AcpInvokeFailure, message: string, options?: { cause?: unknown }) {
39 + super(message, options);
40 + this.name = 'AcpInvokeError';
41 + this.code = code;
42 + }
43 +}
44 +
45 +export const isAcpInvokeError = (value: unknown): value is AcpInvokeError =>
46 + !!value &&
47 + typeof value === 'object' &&
48 + (value as { name?: unknown }).name === 'AcpInvokeError' &&
49 + typeof (value as { message?: unknown }).message === 'string' &&
50 + typeof (value as { code?: unknown }).code === 'string';
51 +
52 +export const toInvokeAgentResponse = (
53 + master: MasterKind,
54 + target: InvokeAgentTarget,
55 + payload: Partial<Pick<InvokeAgentResponse, 'result' | 'structuredOutput'>> = {}
56 +): InvokeAgentResponse => ({
57 + master,
58 + target,
59 + result: payload.result ?? null,
60 + ...(payload.structuredOutput === undefined || payload.structuredOutput === null
61 + ? {}
62 + : { structuredOutput: payload.structuredOutput }),
63 +});
64 +
65 +export const parseJson = (text: string): unknown => {
66 + const value = text.trim();
67 + if (!value) {
68 + return undefined;
69 + }
70 + try {
71 + return JSON.parse(value);
72 + } catch {
73 + return value;
74 + }
75 +};
76 +
77 +const summarizeValidationError = (error: unknown): string => {
78 + const issues =
79 + error &&
80 + typeof error === 'object' &&
81 + 'issues' in error &&
82 + Array.isArray((error as { issues?: unknown[] }).issues)
83 + ? (error as { issues: Array<{ path?: unknown[]; message?: unknown }> }).issues
84 + : [];
85 +
86 + if (issues.length === 0) {
87 + return 'Invalid structured output.';
88 + }
89 +
90 + return issues
91 + .slice(0, 5)
92 + .map(issue => {
93 + const path =
94 + Array.isArray(issue.path) && issue.path.length > 0 ? issue.path.join('.') : '<root>';
95 + const message = typeof issue.message === 'string' ? issue.message : 'Invalid value';
96 + return `${path}: ${message}`;
97 + })
98 + .join('; ');
99 +};
100 +
101 +export const buildStructuredPrompt = (
102 + prompt: string,
103 + structuredSchema?: Record<string, unknown>
104 +): string => {
105 + if (!structuredSchema) {
106 + return prompt;
107 + }
108 +
109 + return [
110 + prompt,
111 + '',
112 + 'Return only a valid JSON value that matches this schema.',
113 + 'Do not include Markdown fences, commentary, or any extra text before or after the JSON.',
114 + JSON.stringify(structuredSchema, null, 2),
115 + ].join('\n');
116 +};
117 +
118 +export const finalizeInvokeAgentText = (
119 + text: string,
120 + options: InvokeAgentNormalizedOptions
121 +): Pick<InvokeAgentResponse, 'result' | 'structuredOutput'> => {
122 + const trimmed = text.trim();
123 + if (!options.structuredSchema) {
124 + return {
125 + result: trimmed,
126 + };
127 + }
128 +
129 + let parsed: unknown;
130 + try {
131 + parsed = JSON.parse(trimmed);
132 + } catch {
133 + throw new Error('subAgent() expected valid JSON output for structured response.');
134 + }
135 +
136 + if (options.zodSchema && typeof options.zodSchema.safeParse === 'function') {
137 + const validation = options.zodSchema.safeParse(parsed);
138 + if (!validation.success) {
139 + throw new Error(
140 + `subAgent() structured output failed schema validation: ${summarizeValidationError(validation.error)}`
141 + );
142 + }
143 +
144 + return {
145 + result: null,
146 + structuredOutput: validation.data,
147 + };
148 + }
149 +
150 + return {
151 + result: null,
152 + structuredOutput: parsed,
153 + };
154 +};
ts/packages/cli/test/src/commands/run.cmd.test.ts
+104 -9
@@ -10,6 +10,7 @@ import {
10 inferCliInvocationPrefix,
11 wrapInlineCodeForRun,
12 } from 'src/commands/run.cmd';
13 +import { buildStructuredPrompt, finalizeInvokeAgentText } from 'src/services/run-subagent-shared';
14 import { cli, MockConsole, TestLive } from 'test/__utils__';
15
16 describe('CLI: composio run', () => {
@@ -55,6 +56,48 @@ describe('CLI: composio run', () => {
56 );
57 });
58
59 + layer(TestLive())(it => {
60 + it.scoped(
61 + '[Given] --acp-only [Then] run accepts the flag and forwards execution normally',
62 + () =>
63 + Effect.gen(function* () {
64 + const spawn = vi.fn(() => ({ exited: Promise.resolve(0) }));
65 + const exit = vi.spyOn(process, 'exit').mockImplementation((() => undefined) as never);
66 + vi.stubGlobal('Bun', { spawn });
67 +
68 + yield* cli(['run', '--acp-only', 'console.log("hi")']);
69 +
70 + expect(spawn).toHaveBeenCalledTimes(1);
71 + const spawnConfig = (spawn as any).mock.calls[0][0] as {
72 + cmd: string[];
73 + };
74 + expect(spawnConfig.cmd[3]).toBe('--eval');
75 + expect(exit).toHaveBeenCalledWith(0);
76 + })
77 + );
78 + });
79 +
80 + layer(TestLive())(it => {
81 + it.scoped(
82 + '[Given] --logs-off [Then] run accepts the flag and forwards execution normally',
83 + () =>
84 + Effect.gen(function* () {
85 + const spawn = vi.fn(() => ({ exited: Promise.resolve(0) }));
86 + const exit = vi.spyOn(process, 'exit').mockImplementation((() => undefined) as never);
87 + vi.stubGlobal('Bun', { spawn });
88 +
89 + yield* cli(['run', '--logs-off', 'console.log("hi")']);
90 +
91 + expect(spawn).toHaveBeenCalledTimes(1);
92 + const spawnConfig = (spawn as any).mock.calls[0][0] as {
93 + cmd: string[];
94 + };
95 + expect(spawnConfig.cmd[3]).toBe('--eval');
96 + expect(exit).toHaveBeenCalledWith(0);
97 + })
98 + );
99 + });
100 +
101 layer(TestLive())(it => {
102 it.scoped('[Given] --file [Then] it forwards file execution to the embedded Bun runtime', () =>
103 Effect.gen(function* () {
@@ -118,12 +161,14 @@ describe('CLI: composio run', () => {
161 expect(output).toContain('--skip-connection-check');
162 expect(output).toContain('--skip-tool-params-check');
163 expect(output).toContain('--no-verify');
164 + expect(output).toContain('--logs-off');
165 expect(output).toContain('subAgent');
166 expect(output).toContain('schema: z.object');
167 expect(output).toContain('INJECTED HELPERS');
168 expect(output).toContain('Global from zod');
169 expect(output).toContain('composio search "<query>"');
170 expect(output).toContain('composio execute <slug> --get-schema');
171 + expect(output).not.toContain('--acp-only');
172 })
173 );
174 });
@@ -137,10 +182,15 @@ describe('buildRunHelpersSource', () => {
182 webURL: 'https://app.example.test',
183 orgId: 'org_test',
184 consumerUserId: 'consumer_user_test',
185 + acpOnly: true,
186 + logsOff: true,
187 dryRun: true,
188 });
189
190 expect(source).toContain('import { z } from "zod";');
191 + expect(source).toContain('import { isAcpInvokeError } from "file://');
192 + expect(source).toContain('import { invokeAcpSubAgent } from "file://');
193 + expect(source).toContain('import { invokeLegacySubAgent } from "file://');
194 expect(source).toContain('globalThis.z = z;');
195 expect(source).toContain('globalThis.zod = z;');
196 expect(source).toContain('const stringifyForPrompt = (value) => {');
@@ -153,14 +203,18 @@ describe('buildRunHelpersSource', () => {
203 'const sharedRunOutputDir = typeof helperContext.runOutputDir === "string"'
204 );
205 expect(source).toContain('COMPOSIO_RUN_OUTPUT_DIR');
156 - expect(source).toContain('fs.mkdtempSync(path.join(sharedRunOutputDir, "invoke-agent-"))');
206 expect(source).toContain('const maybeLoadStoredCliResult = (result) => {');
207 expect(source).toContain('storedInFilePath: outputFilePath !== null,');
208 expect(source).toContain('outputFilePath,');
160 - expect(source).toContain('const logCliResultPreview = (requestId, result) => {');
209 + expect(source).toContain('const formatHelperDebugEvent = (step, details = {}) => {');
210 + expect(source).toContain('return `[subAgent] triggered with ${details.resolvedTarget}`;');
211 + expect(source).toContain('const logCliResultPreview = (requestId, command, result) => {');
212 expect(source).toContain('helperDebugLog("cli.result", {');
213 expect(source).toContain('helperDebugLog("cli.result.stored_in_file"');
214 + expect(source).toContain('case "subAgent.acp.message":');
215 expect(source).toContain('COMPOSIO_USER_API_KEY');
216 + expect(source).toContain('"acpOnly":true');
217 + expect(source).toContain('"logsOff":true');
218 expect(source).toContain('"consumerUserId":"consumer_user_test"');
219 expect(source).toContain('__composioConsumerContext');
220 expect(source).toContain('globalThis.execute = async (slug, data = {}) => {');
@@ -173,9 +227,11 @@ describe('buildRunHelpersSource', () => {
227 'Object.defineProperty(globalThis.subAgent, "schema", { value: subAgentSchema });'
228 );
229 expect(source).toContain('globalThis.invokeAgent = subAgentImpl;');
176 - expect(source).toContain('const toInvokeAgentResponse = (master, target, payload = {}) => ({');
177 - expect(source).toContain('const invokeClaudeAgent = async (prompt, options) => {');
178 - expect(source).toContain('const invokeCodexAgent = async (prompt, options) => {');
230 + expect(source).toContain('return await invokeAcpSubAgent({');
231 + expect(source).toContain('if (!isAcpInvokeError(error)) {');
232 + expect(source).toContain('if (helperContext.acpOnly === true) {');
233 + expect(source).toContain('helperDebugLog("subAgent.acp.fallback"');
234 + expect(source).toContain('return invokeLegacySubAgent({');
235 expect(source).toContain('const detectInvokeAgentMaster = () => {');
236 expect(source).toContain(
237 'throw new Error("subAgent() accepts either options.schema or options.jsonSchema, not both.");'
@@ -185,12 +241,12 @@ describe('buildRunHelpersSource', () => {
241 expect(source).toContain(
242 'subAgent() requires Zod 4 with z.toJSONSchema() when using options.schema.'
243 );
244 + expect(source).toContain('let zodSchema;');
245 + expect(source).toContain('zodSchema = inputSchema;');
246 expect(source).toContain('structuredSchema = z.toJSONSchema(inputSchema);');
189 - expect(source).toContain(
190 - '["codex", "exec", "--skip-git-repo-check", "--sandbox", "read-only", "-o", outputPath]'
247 + expect(source).not.toContain(
248 + 'const runExternalCommandText = async (cmd, spawnOptions = {}) => {'
249 );
192 - expect(source).toContain('["claude", "--bare", "-p", "--output-format", "json"]');
193 - expect(source).toContain('structuredOutput: parsed.structured_output ?? null');
250 expect(source).toContain('globalThis.proxy = async (toolkit) => {');
251 expect(source).toContain('const proxyFetch = async (input, init = {}) => {');
252 expect(source).toContain('return toProxyResponse(result);');
@@ -210,6 +266,45 @@ describe('buildRunHelpersSource', () => {
266 });
267 });
268
269 +describe('run-subagent-shared', () => {
270 + it('[Given] a structured schema [Then] it appends a strict JSON response contract', () => {
271 + expect(buildStructuredPrompt('hello', { type: 'object' })).toContain(
272 + 'Return only a valid JSON value that matches this schema.'
273 + );
274 + });
275 +
276 + it('[Given] Zod-like structured output [Then] it validates and returns structured data', () => {
277 + const result = finalizeInvokeAgentText('{"ok":true}', {
278 + structuredSchema: { type: 'object' },
279 + zodSchema: {
280 + safeParse: value => ({ success: true as const, data: value }),
281 + },
282 + });
283 +
284 + expect(result).toEqual({
285 + result: null,
286 + structuredOutput: { ok: true },
287 + });
288 + });
289 +
290 + it('[Given] plain text output [Then] it omits structuredOutput', () => {
291 + const result = finalizeInvokeAgentText('hello', {});
292 +
293 + expect(result).toEqual({
294 + result: 'hello',
295 + });
296 + expect('structuredOutput' in result).toBe(false);
297 + });
298 +
299 + it('[Given] invalid JSON in structured mode [Then] it throws a clear error', () => {
300 + expect(() =>
301 + finalizeInvokeAgentText('not-json', {
302 + structuredSchema: { type: 'object' },
303 + })
304 + ).toThrow('subAgent() expected valid JSON output for structured response.');
305 + });
306 +});
307 +
308 describe('inferCliInvocationPrefix', () => {
309 it('[Given] a compiled bunfs entrypoint [Then] it falls back to the binary path only', () => {
310 expect(inferCliInvocationPrefix(['node', '/$bunfs/root/composio'])).toEqual([process.execPath]);
ts/packages/cli/test/src/services/run-subagent-acp.test.ts new
+64
@@ -0,0 +1,64 @@
1 +import { afterEach, describe, expect, it, vi } from 'vitest';
2 +import { BufferedChunkLogger, resolveAcpAdapterCommand } from 'src/services/run-subagent-acp';
3 +import { AcpInvokeError, isAcpInvokeError } from 'src/services/run-subagent-shared';
4 +
5 +describe('run-subagent-acp', () => {
6 + afterEach(() => {
7 + vi.unstubAllGlobals();
8 + });
9 +
10 + it('[Given] bundled adapter packages [Then] it resolves to the bundled path without npx', () => {
11 + const result = resolveAcpAdapterCommand('claude');
12 + expect(result.source).toBe('bundled');
13 + expect(result.cmd[0]).toBe(process.execPath);
14 + expect(result.cmd[1]).toMatch(/claude-code-acp/);
15 + });
16 +
17 + it('[Given] bundled codex adapter [Then] it resolves to the bundled path', () => {
18 + const result = resolveAcpAdapterCommand('codex');
19 + expect(result.source).toBe('bundled');
20 + expect(result.cmd[0]).toBe(process.execPath);
21 + expect(result.cmd[1]).toMatch(/codex-acp/);
22 + });
23 +
24 + it('[Given] an ACP invoke error [Then] it is classified for fallback', () => {
25 + const error = new AcpInvokeError('initialize_failed', 'boom');
26 + expect(isAcpInvokeError(error)).toBe(true);
27 + expect(error.code).toBe('initialize_failed');
28 + });
29 +
30 + it('[Given] an ACP-like error from another bundle [Then] it is still classified for fallback', () => {
31 + const error = {
32 + name: 'AcpInvokeError',
33 + code: 'prompt_failed',
34 + message: 'boom',
35 + };
36 +
37 + expect(isAcpInvokeError(error)).toBe(true);
38 + });
39 +
40 + it('[Given] a cancelled ACP prompt [Then] it remains fallback-eligible', () => {
41 + const error = new AcpInvokeError('prompt_failed', 'claude ACP prompt was cancelled.');
42 +
43 + expect(isAcpInvokeError(error)).toBe(true);
44 + expect(error.code).toBe('prompt_failed');
45 + });
46 +
47 + it('[Given] tokenized message chunks [Then] it emits buffered readable text', () => {
48 + const helperDebugLog = vi.fn();
49 + const logger = new BufferedChunkLogger('subAgent.acp.message', helperDebugLog);
50 +
51 + logger.push('Pick');
52 + logger.push(' one');
53 + logger.push(' fruit');
54 + logger.push(' from');
55 + logger.push(' the');
56 + logger.push(' mixed');
57 + logger.push(' box.');
58 + logger.flush();
59 +
60 + expect(helperDebugLog).toHaveBeenCalledWith('subAgent.acp.message', {
61 + text: 'Pick one fruit from the mixed box.',
62 + });
63 + });
64 +});