@devries-cameron20 / composio-1 / commits / cb0257506
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.

fix(cli): harden run subAgent structured output (#3046)

## Summary - harden `composio run` sub-agent structured output by adding an MCP-backed `submit_structured_output` tool, permissive ACP approval, and a repair turn when the agent answers with prose - route all `run` helper logs into the per-run `artifacts/run.log`, print `RUN_LOG_FILE=...` before execution starts, and include `logFilePath` on `subAgent()` responses - keep the run artifact directory and `~/.composio` accessible to sub-agents and cover the new behavior with focused CLI/ACP tests ## Verification - `pnpm --filter @composio/cli typecheck:src` - `pnpm --filter @composio/cli test test/src/commands/run.cmd.test.ts test/src/services/run-subagent-acp.test.ts` - `pnpm --filter @composio/cli exec tsdown --config-loader unrun` - `pnpm --filter @composio/cli run build:binary` - manual `./ts/packages/cli/dist/composio run ...` checks against both `target: "claude"` and `target: "codex"` --------- Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>

Rahul Tarak committed Mar 27, 2026 at 05:21 UTC cb025750653061fd37828c877fe0da106682a738
11 files changed +1059 -86
.changeset/fix-run-subagent-logfile-output.md new
+5
@@ -0,0 +1,5 @@
1 +---
2 +"@composio/cli": patch
3 +---
4 +
5 +fix(cli): harden run subagent structured output and logfile path propagation
pnpm-lock.yaml
+3
@@ -1070,6 +1070,9 @@ 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 + '@modelcontextprotocol/sdk':
1074 + specifier: ^1.26.0
1075 + version: 1.26.0(@cfworker/json-schema@4.1.1)(zod@4.3.6)
1076 '@zed-industries/claude-code-acp':
1077 specifier: ^0.16.2
1078 version: 0.16.2(@cfworker/json-schema@4.1.1)(zod@4.3.6)
ts/packages/cli/package.json
+1
@@ -78,6 +78,7 @@
78 "@effect/cli": "catalog:",
79 "@effect/platform-bun": "catalog:",
80 "@effect/platform-node-shared": "catalog:",
81 + "@modelcontextprotocol/sdk": "^1.26.0",
82 "ansis": "^4.1.0",
83 "comment-json": "^4.2.5",
84 "decompress": "^4.2.1",
ts/packages/cli/src/commands/run.cmd.ts
+70 -25
@@ -20,6 +20,7 @@ import {
20 appendCliSessionHistory,
21 resolveCliSessionArtifacts,
22 } from 'src/services/cli-session-artifacts';
23 +import { USER_COMPOSIO_DIR } from 'src/constants';
24
25 const file = Options.text('file').pipe(
26 Options.withAlias('f'),
@@ -36,7 +37,9 @@ const debug = Options.boolean('debug').pipe(
37 Options.withDefault(false)
38 );
39 const logsOff = Options.boolean('logs-off').pipe(
39 - Options.withDescription('Hide the always-on subAgent streaming logs'),
40 + Options.withDescription(
41 + 'Compatibility flag. Helper logs are written to the run log file instead of stderr.'
42 + ),
43 Options.withDefault(false)
44 );
45 const skipConnectionCheck = Options.boolean('skip-connection-check').pipe(
@@ -215,6 +218,8 @@ type RunHelperContext = {
218 readonly acpOnly?: boolean;
219 readonly logsOff?: boolean;
220 readonly runOutputDir?: string;
221 + readonly runLogFilePath?: string;
222 + readonly readAccessRoots?: ReadonlyArray<string>;
223 };
224
225 // eslint-disable-next-line max-lines-per-function
@@ -251,6 +256,7 @@ const buildRunBaseHelpersSource = (): ReadonlyArray<string> => [
256 ' target: { type: "string", enum: ["claude", "codex"] },',
257 ' result: { description: "Final plain-text result when available." },',
258 ' structuredOutput: { description: "Structured output when jsonSchema was requested." },',
259 + ' logFilePath: { description: "Path to the local run log file for helper execution details." },',
260 ' },',
261 ' },',
262 '};',
@@ -285,20 +291,12 @@ const buildRunBaseHelpersSource = (): ReadonlyArray<string> => [
291 ' const payload = { phase, label, elapsedMs, ...details };',
292 ' console.error(`[perf] ${JSON.stringify(payload)}`);',
293 '};',
288 - 'const helperDebugEnabled = helperContext.debug === true;',
289 - 'const helperProgressEnabled = helperContext.logsOff !== true;',
294 'const sharedRunOutputDir = typeof helperContext.runOutputDir === "string" && helperContext.runOutputDir.length > 0 ? helperContext.runOutputDir : null;',
291 - 'const helperProgressSteps = new Set([',
292 - ' "subAgent.target",',
293 - ' "subAgent.acp.message",',
294 - ' "subAgent.acp.thought",',
295 - ' "subAgent.acp.tool_call",',
296 - ' "subAgent.acp.tool_call_update",',
297 - ' "subAgent.acp.plan",',
298 - ' "subAgent.acp.fallback",',
299 - ']);',
300 - 'const helperDebugUseColor = process.stderr?.isTTY === true && process.env.NO_COLOR !== "1";',
301 - 'const helperDebugColorize = (line) => helperDebugUseColor ? `\\x1b[90m${line}\\x1b[0m` : line;',
295 + 'const sharedRunLogFilePath = typeof helperContext.runLogFilePath === "string" && helperContext.runLogFilePath.length > 0 ? helperContext.runLogFilePath : null;',
296 + 'const appendRunLogLine = (line) => {',
297 + ' if (!sharedRunLogFilePath || typeof line !== "string" || line.length === 0) return;',
298 + ' fs.appendFileSync(sharedRunLogFilePath, `${line}\\n`, "utf8");',
299 + '};',
300 'const truncateDebugText = (value, max = 240) => {',
301 ' const text = typeof value === "string" ? value : String(value ?? "");',
302 ' return text.length > max ? `${text.slice(0, max - 1)}…` : text;',
@@ -381,13 +379,8 @@ const buildRunBaseHelpersSource = (): ReadonlyArray<string> => [
379 '};',
380 'const helperDebugLog = (step, details = {}) => {',
381 ' const line = formatHelperDebugEvent(step, details);',
384 - ' if (line && (helperDebugEnabled || (helperProgressEnabled && helperProgressSteps.has(step)))) {',
385 - ' console.error(helperDebugColorize(line));',
386 - ' return;',
387 - ' }',
388 - ' if (!helperDebugEnabled) return;',
382 ' const elapsedMs = Date.now() - perfDebugStart;',
390 - ' console.error(helperDebugColorize(`[run:debug] ${JSON.stringify({ step, elapsedMs, ...details })}`));',
383 + ' appendRunLogLine(line ?? `[run:debug] ${JSON.stringify({ step, elapsedMs, ...details })}`);',
384 '};',
385 'const parseJson = (text) => {',
386 ' const value = text.trim();',
@@ -447,7 +440,6 @@ const buildRunBaseHelpersSource = (): ReadonlyArray<string> => [
440 ' return result;',
441 '};',
442 'const logCliResultPreview = (requestId, command, result) => {',
450 - ' if (!helperDebugEnabled) return;',
443 ' if (!result || typeof result !== "object") {',
444 ' helperDebugLog("cli.result", { requestId, command, preview: result, result: describeDebugValue(result) });',
445 ' return;',
@@ -706,18 +698,21 @@ const buildRunInvokeAgentHelpersSource = (): ReadonlyArray<string> => [
698 ' if (typeof prompt !== "string" || prompt.trim().length === 0) {',
699 ' throw new Error("subAgent() requires a non-empty prompt string.");',
700 ' }',
701 + ' const logFilePath = typeof helperContext.runLogFilePath === "string" && helperContext.runLogFilePath.length > 0 ? helperContext.runLogFilePath : undefined;',
702 ' const normalizedOptions = normalizeInvokeAgentOptions(options);',
703 ' const target = resolveInvokeAgentTarget(normalizedOptions.target);',
704 ' const master = detectInvokeAgentMaster();',
705 ' helperDebugLog("subAgent.target", { requestedTarget: normalizedOptions.target ?? null, resolvedTarget: target, master });',
706 ' try {',
714 - ' return await invokeAcpSubAgent({',
707 + ' const response = await invokeAcpSubAgent({',
708 ' prompt: prompt.trim(),',
709 ' options: normalizedOptions,',
710 ' master,',
711 ' target,',
712 + ' allowedReadRoots: Array.isArray(helperContext.readAccessRoots) ? helperContext.readAccessRoots : [],',
713 ' helperDebugLog,',
714 ' });',
715 + ' return logFilePath ? { ...response, logFilePath } : response;',
716 ' } catch (error) {',
717 ' if (!isAcpInvokeError(error)) {',
718 ' throw error;',
@@ -726,13 +721,15 @@ const buildRunInvokeAgentHelpersSource = (): ReadonlyArray<string> => [
721 ' throw error;',
722 ' }',
723 ' helperDebugLog("subAgent.acp.fallback", { target, code: error.code, message: error.message });',
729 - ' return invokeLegacySubAgent({',
724 + ' const response = await invokeLegacySubAgent({',
725 ' prompt: prompt.trim(),',
726 ' options: normalizedOptions,',
727 ' master,',
728 ' target,',
729 + ' allowedReadRoots: Array.isArray(helperContext.readAccessRoots) ? helperContext.readAccessRoots : [],',
730 ' helperDebugLog,',
731 ' });',
732 + ' return logFilePath ? { ...response, logFilePath } : response;',
733 ' }',
734 '};',
735 'globalThis.subAgent = subAgentImpl;',
@@ -794,6 +791,14 @@ const buildRunProxyHelpersSource = (): ReadonlyArray<string> => [
791 '};',
792 'Object.defineProperty(globalThis.proxy, "schema", { value: proxySchema });',
793 '',
794 + 'Object.defineProperty(globalThis, "__composioRunContext", {',
795 + ' value: Object.freeze({',
796 + ' outputDir: sharedRunOutputDir,',
797 + ' logFilePath: sharedRunLogFilePath,',
798 + ' }),',
799 + ' configurable: true,',
800 + '});',
801 + '',
802 'Object.defineProperty(globalThis, "__composioConsumerContext", {',
803 ' value: helperContext,',
804 ' configurable: true,',
@@ -807,6 +812,7 @@ export const buildRunHelpersSource = (
812 moduleUrls: RunHelperModuleUrls = resolveRunHelperModuleUrls()
813 ): string =>
814 [
815 + 'import * as fs from "node:fs";',
816 'import { z } from "zod";',
817 `import { isAcpInvokeError } from ${JSON.stringify(moduleUrls.subAgentSharedModuleUrl)};`,
818 `import { invokeAcpSubAgent } from ${JSON.stringify(moduleUrls.subAgentAcpModuleUrl)};`,
@@ -831,13 +837,28 @@ const createRunHelpersPreloadFile = (
837 typeof context.runOutputDir === 'string' && context.runOutputDir.length > 0
838 ? context.runOutputDir
839 : path.join(directory, 'artifacts');
840 + const runLogFilePath = path.join(runOutputDir, 'run.log');
841 + const readAccessRoots = [
842 + ...new Set(
843 + [
844 + ...(Array.isArray(context.readAccessRoots) ? context.readAccessRoots : []),
845 + runOutputDir,
846 + ].map(value => path.resolve(value))
847 + ),
848 + ];
849 fs.mkdirSync(runOutputDir, { recursive: true });
850 + fs.writeFileSync(runLogFilePath, '', 'utf8');
851 fs.writeFileSync(
852 preloadPath,
837 - buildRunHelpersSource(cliPrefix, { ...context, runOutputDir }, moduleUrls),
853 + buildRunHelpersSource(cliPrefix, {
854 + ...context,
855 + runOutputDir,
856 + runLogFilePath,
857 + readAccessRoots,
858 + }, moduleUrls),
859 'utf8'
860 );
840 - return { directory, preloadPath, runOutputDir };
861 + return { directory, preloadPath, runOutputDir, runLogFilePath };
862 };
863
864 export const buildRunCommand = ({
@@ -898,11 +919,19 @@ const resolveRunHelperContext = () =>
919 const userContext = yield* ComposioUserContext;
920 const apiKey = Option.getOrUndefined(userContext.data.apiKey);
921 const orgId = Option.getOrUndefined(userContext.data.orgId);
922 + const defaultComposioDir = path.join(os.homedir(), USER_COMPOSIO_DIR);
923 + const configuredCacheDir =
924 + process.env.COMPOSIO_CACHE_DIR?.trim() || process.env.CACHE_DIR?.trim() || defaultComposioDir;
925 + const baseReadAccessRoots = [
926 + ...new Set([defaultComposioDir, configuredCacheDir].map(value => path.resolve(value))),
927 + ];
928 +
929 const baseContext = {
930 apiKey,
931 baseURL: userContext.data.baseURL,
932 webURL: userContext.data.webURL,
933 orgId,
934 + readAccessRoots: baseReadAccessRoots,
935 } satisfies RunHelperContext;
936
937 if (!apiKey || !orgId) {
@@ -925,6 +954,21 @@ const resolveRunHelperContext = () =>
954 consumerUserId: consumerProject.value.consumerUserId,
955 }).pipe(Effect.map(Option.map(artifacts => artifacts.directoryPath)))
956 ),
957 + readAccessRoots: [
958 + ...new Set(
959 + [
960 + ...baseReadAccessRoots,
961 + Option.getOrUndefined(
962 + yield* resolveCliSessionArtifacts({
963 + orgId,
964 + consumerUserId: consumerProject.value.consumerUserId,
965 + }).pipe(Effect.map(Option.map(artifacts => artifacts.directoryPath)))
966 + ),
967 + ]
968 + .filter((value): value is string => typeof value === 'string' && value.length > 0)
969 + .map(value => path.resolve(value))
970 + ),
971 + ],
972 } satisfies RunHelperContext;
973 });
974
@@ -1068,6 +1112,7 @@ export const runCmd = Command.make('run', {
1112 debug,
1113 },
1114 }).pipe(Effect.catchAll(() => Effect.void));
1115 + process.stderr.write(`RUN_LOG_FILE=${preload.runLogFilePath}\n`);
1116 const runCommand = buildRunCommand({
1117 file,
1118 args,
ts/packages/cli/src/services/run-companion-modules.ts
+1
@@ -8,6 +8,7 @@ export const RUN_COMPANION_MODULE_BASENAMES = [
8 'run-subagent-shared',
9 'run-subagent-acp',
10 'run-subagent-legacy',
11 + 'run-subagent-output-mcp',
12 ] as const;
13
14 export const RUN_COMPANION_MODULE_FILENAMES = RUN_COMPANION_MODULE_BASENAMES.map(
ts/packages/cli/src/services/run-subagent-acp.ts
+338 -39
@@ -1,13 +1,22 @@
1 +import * as fs from 'node:fs';
2 import { spawn } from 'node:child_process';
3 import { createRequire } from 'node:module';
4 +import * as os from 'node:os';
5 +import path from 'node:path';
6 import { Readable, Writable } from 'node:stream';
7 import * as acp from '@agentclientprotocol/sdk';
8 import type { MasterKind } from 'src/services/master-detector';
9 +import { resolveRunCompanionModulePath } from 'src/services/run-companion-modules';
10 import {
11 + ACP_STRUCTURED_OUTPUT_TOOL_NAME,
12 AcpInvokeError,
13 + buildStructuredRepairPrompt,
14 buildStructuredPrompt,
15 + buildStructuredToolPrompt,
16 finalizeInvokeAgentText,
17 toInvokeAgentResponse,
18 + unwrapStructuredOutputToolPayload,
19 + validateStructuredOutput,
20 type HelperDebugLog,
21 type InvokeAgentNormalizedOptions,
22 type InvokeAgentResponse,
@@ -65,6 +74,134 @@ export const resolveAcpAdapterCommand = (
74 };
75
76 const chunkFlushPattern = /[\s,.;:!?)\]}"]$/;
77 +const structuredOutputMcpModulePath = resolveRunCompanionModulePath({
78 + callerImportMetaUrl: import.meta.url,
79 + execPath: process.execPath,
80 + relativeNoExtensionFromCaller: './run-subagent-output-mcp',
81 +});
82 +
83 +const collectToolCallPaths = (value: unknown, results: Set<string>, parentKey?: string): void => {
84 + if (typeof value === 'string') {
85 + const key = parentKey?.toLowerCase() ?? '';
86 + if (
87 + key === 'path' ||
88 + key === 'file_path' ||
89 + key === 'directory' ||
90 + key.endsWith('_path') ||
91 + key.endsWith('_directory')
92 + ) {
93 + results.add(value);
94 + } else if (key === 'command' || key === 'cmd') {
95 + for (const candidatePath of extractPathsFromCommandText(value)) {
96 + results.add(candidatePath);
97 + }
98 + }
99 + return;
100 + }
101 +
102 + if (Array.isArray(value)) {
103 + const key = parentKey?.toLowerCase() ?? '';
104 + if (
105 + key === 'paths' ||
106 + key === 'directories' ||
107 + key.endsWith('_paths') ||
108 + key.endsWith('_directories')
109 + ) {
110 + for (const entry of value) {
111 + if (typeof entry === 'string') {
112 + results.add(entry);
113 + }
114 + }
115 + return;
116 + }
117 +
118 + for (const entry of value) {
119 + collectToolCallPaths(entry, results);
120 + }
121 + return;
122 + }
123 +
124 + if (!value || typeof value !== 'object') {
125 + return;
126 + }
127 +
128 + for (const [key, nestedValue] of Object.entries(value)) {
129 + collectToolCallPaths(nestedValue, results, key);
130 + }
131 +};
132 +
133 +const extractPathsFromCommandText = (command: string): ReadonlyArray<string> => {
134 + const results = new Set<string>();
135 + const matches = command.matchAll(/(^|[\s"'`])((?:~\/|\/)[^\s"'`|&;<>]+)/g);
136 + for (const match of matches) {
137 + const rawPath = match[2]?.trim();
138 + if (!rawPath) {
139 + continue;
140 + }
141 +
142 + results.add(rawPath.startsWith('~/') ? path.join(os.homedir(), rawPath.slice(2)) : rawPath);
143 + }
144 +
145 + return [...results];
146 +};
147 +
148 +const extractToolCallPaths = (
149 + toolCall: Pick<acp.RequestPermissionRequest, 'toolCall'>['toolCall']
150 +): ReadonlyArray<string> => {
151 + const paths = new Set<string>();
152 + for (const location of toolCall.locations ?? []) {
153 + if (typeof location.path === 'string' && location.path.length > 0) {
154 + paths.add(location.path);
155 + }
156 + }
157 +
158 + collectToolCallPaths(toolCall.rawInput, paths);
159 + if (typeof toolCall.title === 'string') {
160 + for (const candidatePath of extractPathsFromCommandText(toolCall.title)) {
161 + paths.add(candidatePath);
162 + }
163 + }
164 + return [...paths];
165 +};
166 +
167 +export const selectPermissionOutcome = (
168 + params: Pick<acp.RequestPermissionRequest, 'options' | 'toolCall'>,
169 + _allowedReadRoots: ReadonlyArray<string> = []
170 +): acp.RequestPermissionResponse => {
171 + const allowOnce =
172 + params.options.find(option => option.kind === 'allow_always') ??
173 + params.options.find(option => option.kind === 'allow_once');
174 + const rejectOption =
175 + params.options.find(option => option.kind === 'reject_once') ??
176 + params.options.find(option => option.kind === 'reject_always');
177 +
178 + // Intentionally permissive for `composio run` subAgent sessions. The user is
179 + // explicitly opting into local tool access, so prefer broad ACP approval over
180 + // heuristic rejections that strand the agent mid-task.
181 + if (allowOnce) {
182 + return {
183 + outcome: {
184 + outcome: 'selected',
185 + optionId: allowOnce.optionId,
186 + },
187 + };
188 + }
189 +
190 + if (rejectOption) {
191 + return {
192 + outcome: {
193 + outcome: 'selected',
194 + optionId: rejectOption.optionId,
195 + },
196 + };
197 + }
198 +
199 + return {
200 + outcome: {
201 + outcome: 'cancelled',
202 + },
203 + };
204 +};
205
206 export class BufferedChunkLogger {
207 private buffer = '';
@@ -125,7 +262,10 @@ class RunSubAgentClient {
262 private readonly messageLogger: BufferedChunkLogger;
263 private readonly thoughtLogger: BufferedChunkLogger;
264
128 - constructor(private readonly helperDebugLog: HelperDebugLog) {
265 + constructor(
266 + private readonly helperDebugLog: HelperDebugLog,
267 + private readonly allowedReadRoots: ReadonlyArray<string>
268 + ) {
269 this.messageLogger = new BufferedChunkLogger('subAgent.acp.message', helperDebugLog);
270 this.thoughtLogger = new BufferedChunkLogger('subAgent.acp.thought', helperDebugLog);
271 }
@@ -133,29 +273,20 @@ class RunSubAgentClient {
273 async requestPermission(
274 params: acp.RequestPermissionRequest
275 ): Promise<acp.RequestPermissionResponse> {
276 + const requestedPaths = extractToolCallPaths(params.toolCall);
277 + const decision = selectPermissionOutcome(params, this.allowedReadRoots);
278 this.helperDebugLog('subAgent.acp.permission', {
279 toolCallId: params.toolCall.toolCallId,
280 + title: params.toolCall.title ?? null,
281 + kind: params.toolCall.kind ?? null,
282 + locations: params.toolCall.locations?.map(location => location.path) ?? [],
283 + requestedPaths,
284 + allowedReadRoots: this.allowedReadRoots,
285 + selectedOptionId: decision.outcome.outcome === 'selected' ? decision.outcome.optionId : null,
286 options: params.options.map(option => option.kind),
287 });
288
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 - };
289 + return decision;
290 }
291
292 async sessionUpdate(params: acp.SessionNotification): Promise<void> {
@@ -222,19 +353,121 @@ const createFallbackError = (
353 cause?: unknown
354 ): AcpInvokeError => new AcpInvokeError(code, message, cause === undefined ? undefined : { cause });
355
356 +type StructuredOutputMcpContext = {
357 + readonly mcpServer: acp.McpServerStdio;
358 + readonly resultFilePath: string;
359 + readonly cleanup: () => void;
360 +};
361 +
362 +export const createStructuredOutputMcpContext = ({
363 + options,
364 + helperDebugLog,
365 +}: {
366 + options: InvokeAgentNormalizedOptions;
367 + helperDebugLog: HelperDebugLog;
368 +}): StructuredOutputMcpContext | null => {
369 + if (!options.structuredSchema) {
370 + return null;
371 + }
372 +
373 + let tempDirectory: string | null = null;
374 + try {
375 + tempDirectory = fs.mkdtempSync(path.join(os.tmpdir(), 'composio-subagent-output-mcp-'));
376 + const schemaFilePath = path.join(tempDirectory, 'schema.json');
377 + const resultFilePath = path.join(tempDirectory, 'result.json');
378 + fs.writeFileSync(schemaFilePath, JSON.stringify(options.structuredSchema), 'utf8');
379 +
380 + helperDebugLog('subAgent.acp.structured_output_tool', {
381 + modulePath: structuredOutputMcpModulePath,
382 + schemaFilePath,
383 + resultFilePath,
384 + });
385 +
386 + return {
387 + mcpServer: {
388 + name: 'composio-structured-output',
389 + command: process.execPath,
390 + args: [
391 + structuredOutputMcpModulePath,
392 + '--schema-file',
393 + schemaFilePath,
394 + '--result-file',
395 + resultFilePath,
396 + ],
397 + env: [
398 + {
399 + name: 'BUN_BE_BUN',
400 + value: '1',
401 + },
402 + ],
403 + },
404 + resultFilePath,
405 + cleanup: () => {
406 + if (tempDirectory) {
407 + fs.rmSync(tempDirectory, { recursive: true, force: true });
408 + }
409 + },
410 + };
411 + } catch (error) {
412 + if (tempDirectory) {
413 + fs.rmSync(tempDirectory, { recursive: true, force: true });
414 + }
415 + helperDebugLog('subAgent.acp.structured_output_tool_failed', {
416 + error: error instanceof Error ? error.message : String(error),
417 + modulePath: structuredOutputMcpModulePath,
418 + });
419 + return null;
420 + }
421 +};
422 +
423 +const maybeReadStructuredOutputFromTool = ({
424 + context,
425 + options,
426 + helperDebugLog,
427 +}: {
428 + context: StructuredOutputMcpContext | null;
429 + options: InvokeAgentNormalizedOptions;
430 + helperDebugLog: HelperDebugLog;
431 +}): unknown | undefined => {
432 + if (!context || !options.structuredSchema || !fs.existsSync(context.resultFilePath)) {
433 + return undefined;
434 + }
435 +
436 + try {
437 + const rawPayload = JSON.parse(fs.readFileSync(context.resultFilePath, 'utf8')) as unknown;
438 + const parsed = unwrapStructuredOutputToolPayload(rawPayload, options.structuredSchema);
439 + helperDebugLog('subAgent.acp.structured_output_tool_result', {
440 + resultFilePath: context.resultFilePath,
441 + });
442 + return validateStructuredOutput(parsed, options);
443 + } catch (error) {
444 + helperDebugLog('subAgent.acp.structured_output_tool_result_failed', {
445 + resultFilePath: context.resultFilePath,
446 + error: error instanceof Error ? error.message : String(error),
447 + });
448 + return undefined;
449 + }
450 +};
451 +
452 export const invokeAcpSubAgent = async ({
453 prompt,
454 options,
455 master,
456 target,
457 + allowedReadRoots,
458 helperDebugLog,
459 }: {
460 prompt: string;
461 options: InvokeAgentNormalizedOptions;
462 master: MasterKind;
463 target: InvokeAgentTarget;
464 + allowedReadRoots: ReadonlyArray<string>;
465 helperDebugLog: HelperDebugLog;
466 }): Promise<InvokeAgentResponse> => {
467 + const structuredOutputMcp = createStructuredOutputMcpContext({
468 + options,
469 + helperDebugLog,
470 + });
471 const resolved = resolveAcpAdapterCommand(target);
472 helperDebugLog('subAgent.acp.resolve', {
473 target,
@@ -268,7 +501,9 @@ export const invokeAcpSubAgent = async ({
501 throw createFallbackError('spawn_failed', `Failed to spawn ${target} ACP adapter.`);
502 }
503
271 - const client = new RunSubAgentClient(helperDebugLog);
504 + const client = new RunSubAgentClient(helperDebugLog, [
505 + ...new Set(allowedReadRoots.map(root => path.resolve(root))),
506 + ]);
507 const stream = acp.ndJsonStream(
508 Writable.toWeb(child.stdin) as unknown as WritableStream<Uint8Array>,
509 Readable.toWeb(child.stdout) as unknown as ReadableStream<Uint8Array>
@@ -297,7 +532,7 @@ export const invokeAcpSubAgent = async ({
532 const session = await connection
533 .newSession({
534 cwd: process.cwd(),
300 - mcpServers: [],
535 + mcpServers: structuredOutputMcp ? [structuredOutputMcp.mcpServer] : [],
536 })
537 .catch(error => {
538 throw createFallbackError(
@@ -333,26 +568,36 @@ export const invokeAcpSubAgent = async ({
568 }
569 }
570
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) {
571 + const promptText =
572 + options.structuredSchema && structuredOutputMcp
573 + ? buildStructuredToolPrompt(
574 + prompt,
575 + options.structuredSchema,
576 + ACP_STRUCTURED_OUTPUT_TOOL_NAME
577 + )
578 + : buildStructuredPrompt(prompt, options.structuredSchema);
579 + const runPrompt = async (promptText: string) =>
580 + connection
581 + .prompt({
582 + sessionId: session.sessionId,
583 + prompt: [{ type: 'text', text: promptText }],
584 + })
585 + .catch(error => {
586 + if (connection.signal.aborted) {
587 + throw createFallbackError(
588 + 'connection_closed',
589 + `${target} ACP connection closed before prompt completion${stderr.trim() ? `: ${stderr.trim()}` : ''}`,
590 + error
591 + );
592 + }
593 throw createFallbackError(
345 - 'connection_closed',
346 - `${target} ACP connection closed before prompt completion${stderr.trim() ? `: ${stderr.trim()}` : ''}`,
594 + 'prompt_failed',
595 + `${target} ACP prompt failed${stderr.trim() ? `: ${stderr.trim()}` : ''}`,
596 error
597 );
349 - }
350 - throw createFallbackError(
351 - 'prompt_failed',
352 - `${target} ACP prompt failed${stderr.trim() ? `: ${stderr.trim()}` : ''}`,
353 - error
354 - );
355 - });
598 + });
599 +
600 + const response = await runPrompt(promptText);
601
602 if (response.stopReason === 'cancelled') {
603 throw createFallbackError(
@@ -361,9 +606,63 @@ export const invokeAcpSubAgent = async ({
606 );
607 }
608
364 - const payload = finalizeInvokeAgentText(client.getText(), options);
609 + const structuredOutput = maybeReadStructuredOutputFromTool({
610 + context: structuredOutputMcp,
611 + options,
612 + helperDebugLog,
613 + });
614 + if (structuredOutput !== undefined) {
615 + return toInvokeAgentResponse(master, target, {
616 + result: null,
617 + structuredOutput,
618 + });
619 + }
620 +
621 + let payload: Pick<InvokeAgentResponse, 'result' | 'structuredOutput'>;
622 + try {
623 + payload = finalizeInvokeAgentText(client.getText(), options);
624 + } catch (error) {
625 + if (!options.structuredSchema) {
626 + throw error;
627 + }
628 +
629 + helperDebugLog('subAgent.acp.structured_repair', {
630 + target,
631 + reason: error instanceof Error ? error.message : String(error),
632 + });
633 +
634 + const repairResponse = await runPrompt(
635 + buildStructuredRepairPrompt(
636 + options.structuredSchema,
637 + structuredOutputMcp ? ACP_STRUCTURED_OUTPUT_TOOL_NAME : undefined
638 + )
639 + );
640 +
641 + if (repairResponse.stopReason === 'cancelled') {
642 + throw createFallbackError(
643 + 'prompt_failed',
644 + `${target} ACP repair prompt was cancelled${stderr.trim() ? `: ${stderr.trim()}` : ''}`
645 + );
646 + }
647 +
648 + const repairedStructuredOutput = maybeReadStructuredOutputFromTool({
649 + context: structuredOutputMcp,
650 + options,
651 + helperDebugLog,
652 + });
653 + if (repairedStructuredOutput !== undefined) {
654 + return toInvokeAgentResponse(master, target, {
655 + result: null,
656 + structuredOutput: repairedStructuredOutput,
657 + });
658 + }
659 +
660 + payload = finalizeInvokeAgentText(client.getText(), options);
661 + }
662 +
663 return toInvokeAgentResponse(master, target, payload);
664 } finally {
665 + structuredOutputMcp?.cleanup();
666 child.kill();
667 await Promise.race([
668 closePromise.catch(() => undefined),
ts/packages/cli/src/services/run-subagent-output-mcp.ts new
+106
@@ -0,0 +1,106 @@
1 +import path from 'node:path';
2 +import * as fs from 'node:fs';
3 +import { createRequire } from 'node:module';
4 +import process from 'node:process';
5 +import { pathToFileURL } from 'node:url';
6 +import { jsonSchemaToZodSchema } from '@composio/core';
7 +import {
8 + ACP_STRUCTURED_OUTPUT_TOOL_NAME,
9 + buildStructuredOutputToolSchema,
10 +} from 'src/services/run-subagent-shared';
11 +
12 +const readFlag = (name: string): string => {
13 + const index = process.argv.indexOf(name);
14 + const value = index >= 0 ? process.argv[index + 1] : undefined;
15 + if (!value) {
16 + throw new Error(`Missing required flag: ${name}`);
17 + }
18 + return value;
19 +};
20 +
21 +type McpServerInstance = {
22 + registerTool: (
23 + name: string,
24 + config: {
25 + title?: string;
26 + description?: string;
27 + inputSchema?: unknown;
28 + },
29 + cb: (payload: unknown) => Promise<{
30 + content: Array<{
31 + type: string;
32 + text: string;
33 + }>;
34 + }>
35 + ) => void;
36 + connect: (transport: unknown) => Promise<void>;
37 +};
38 +
39 +type McpServerConstructor = new (serverInfo: {
40 + name: string;
41 + version: string;
42 +}) => McpServerInstance;
43 +
44 +type StdioServerTransportConstructor = new () => unknown;
45 +
46 +const loadMcpSdk = async (): Promise<{
47 + McpServer: McpServerConstructor;
48 + StdioServerTransport: StdioServerTransportConstructor;
49 +}> => {
50 + const require = createRequire(import.meta.url);
51 + const sdkPackageJsonPath = require.resolve('@modelcontextprotocol/sdk/package.json');
52 + const sdkDirectory = path.dirname(sdkPackageJsonPath);
53 + const [mcpModule, stdioModule] = await Promise.all([
54 + import(pathToFileURL(path.join(sdkDirectory, 'dist/esm/server/mcp.js')).href),
55 + import(pathToFileURL(path.join(sdkDirectory, 'dist/esm/server/stdio.js')).href),
56 + ]);
57 +
58 + return {
59 + McpServer: mcpModule.McpServer as McpServerConstructor,
60 + StdioServerTransport: stdioModule.StdioServerTransport as StdioServerTransportConstructor,
61 + };
62 +};
63 +
64 +const main = async (): Promise<void> => {
65 + const { McpServer, StdioServerTransport } = await loadMcpSdk();
66 + const schemaFilePath = readFlag('--schema-file');
67 + const resultFilePath = readFlag('--result-file');
68 + const schemaText = fs.readFileSync(schemaFilePath, 'utf8');
69 + const structuredSchema = JSON.parse(schemaText) as Record<string, unknown>;
70 + const toolInputSchema = jsonSchemaToZodSchema(buildStructuredOutputToolSchema(structuredSchema));
71 +
72 + const server = new McpServer({
73 + name: 'composio-subagent-output',
74 + version: '1.0.0',
75 + });
76 +
77 + server.registerTool(
78 + ACP_STRUCTURED_OUTPUT_TOOL_NAME,
79 + {
80 + title: 'Submit structured output',
81 + description:
82 + 'Submit the final structured subAgent output. Call this exactly once when the task is complete.',
83 + inputSchema: toolInputSchema,
84 + },
85 + async (payload: unknown) => {
86 + fs.writeFileSync(resultFilePath, JSON.stringify(payload), 'utf8');
87 + return {
88 + content: [
89 + {
90 + type: 'text',
91 + text: 'Structured output captured.',
92 + },
93 + ],
94 + };
95 + }
96 + );
97 +
98 + const transport = new StdioServerTransport();
99 + await server.connect(transport);
100 +};
101 +
102 +void main().catch(error => {
103 + const message = error instanceof Error ? (error.stack ?? error.message) : String(error);
104 + process.stderr.write(`${message}\n`);
105 + process.exit(1);
106 +});
ts/packages/cli/src/services/run-subagent-shared.ts
+250 -18
@@ -20,8 +20,12 @@ export type InvokeAgentResponse = {
20 readonly target: InvokeAgentTarget;
21 readonly result: string | null;
22 readonly structuredOutput?: unknown;
23 + readonly logFilePath?: string;
24 };
25
26 +export const ACP_STRUCTURED_OUTPUT_TOOL_NAME = 'submit_structured_output';
27 +export const ACP_STRUCTURED_OUTPUT_WRAPPER_KEY = 'value';
28 +
29 export type HelperDebugLog = (step: string, details?: Record<string, unknown>) => void;
30
31 export type AcpInvokeFailure =
@@ -52,7 +56,7 @@ export const isAcpInvokeError = (value: unknown): value is AcpInvokeError =>
56 export const toInvokeAgentResponse = (
57 master: MasterKind,
58 target: InvokeAgentTarget,
55 - payload: Partial<Pick<InvokeAgentResponse, 'result' | 'structuredOutput'>> = {}
59 + payload: Partial<Pick<InvokeAgentResponse, 'result' | 'structuredOutput' | 'logFilePath'>> = {}
60 ): InvokeAgentResponse => ({
61 master,
62 target,
@@ -60,6 +64,9 @@ export const toInvokeAgentResponse = (
64 ...(payload.structuredOutput === undefined || payload.structuredOutput === null
65 ? {}
66 : { structuredOutput: payload.structuredOutput }),
67 + ...(typeof payload.logFilePath === 'string' && payload.logFilePath.length > 0
68 + ? { logFilePath: payload.logFilePath }
69 + : {}),
70 });
71
72 export const parseJson = (text: string): unknown => {
@@ -115,24 +122,103 @@ export const buildStructuredPrompt = (
122 ].join('\n');
123 };
124
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 - };
125 +const isStructuredObjectSchema = (structuredSchema?: Record<string, unknown>): boolean => {
126 + if (!structuredSchema || Array.isArray(structuredSchema)) {
127 + return false;
128 }
129
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.');
130 + const schemaType = structuredSchema.type;
131 + if (schemaType === 'object') {
132 + return true;
133 + }
134 +
135 + if (Array.isArray(schemaType) && schemaType.includes('object')) {
136 + return true;
137 + }
138 +
139 + return (
140 + 'properties' in structuredSchema ||
141 + 'required' in structuredSchema ||
142 + 'additionalProperties' in structuredSchema
143 + );
144 +};
145 +
146 +export const buildStructuredOutputToolSchema = (
147 + structuredSchema: Record<string, unknown>
148 +): Record<string, unknown> =>
149 + isStructuredObjectSchema(structuredSchema)
150 + ? structuredSchema
151 + : {
152 + type: 'object',
153 + additionalProperties: false,
154 + required: [ACP_STRUCTURED_OUTPUT_WRAPPER_KEY],
155 + properties: {
156 + [ACP_STRUCTURED_OUTPUT_WRAPPER_KEY]: structuredSchema,
157 + },
158 + };
159 +
160 +export const unwrapStructuredOutputToolPayload = (
161 + payload: unknown,
162 + structuredSchema: Record<string, unknown>
163 +): unknown => {
164 + if (isStructuredObjectSchema(structuredSchema)) {
165 + return payload;
166 + }
167 +
168 + if (
169 + payload &&
170 + typeof payload === 'object' &&
171 + !Array.isArray(payload) &&
172 + ACP_STRUCTURED_OUTPUT_WRAPPER_KEY in payload
173 + ) {
174 + return (payload as Record<string, unknown>)[ACP_STRUCTURED_OUTPUT_WRAPPER_KEY];
175 }
176
177 + return payload;
178 +};
179 +
180 +export const buildStructuredToolPrompt = (
181 + prompt: string,
182 + structuredSchema: Record<string, unknown>,
183 + toolName: string
184 +): string => {
185 + const usesWrapper = !isStructuredObjectSchema(structuredSchema);
186 + const toolShapeInstruction = usesWrapper
187 + ? `Call \`${toolName}\` with a single argument named \`${ACP_STRUCTURED_OUTPUT_WRAPPER_KEY}\` containing the final value.`
188 + : `Call \`${toolName}\` with the final structured object as the tool arguments.`;
189 +
190 + return [
191 + prompt,
192 + '',
193 + 'You may inspect files, search, and use tools as needed before producing the final answer.',
194 + `When you are ready to deliver the final structured response, call the MCP tool \`${toolName}\` exactly once.`,
195 + toolShapeInstruction,
196 + `If the MCP tool \`${toolName}\` is unavailable or you cannot call it, reply with only raw JSON matching the schema.`,
197 + 'Do not include prose, markdown fences, or any text before or after the final structured payload.',
198 + 'The final structured value must match this schema:',
199 + JSON.stringify(structuredSchema, null, 2),
200 + ].join('\n');
201 +};
202 +
203 +export const buildStructuredRepairPrompt = (
204 + structuredSchema: Record<string, unknown>,
205 + toolName?: string
206 +): string =>
207 + [
208 + 'Your previous response was not valid structured output.',
209 + 'Do not read files. Do not run terminal commands. Do not inspect the workspace again.',
210 + 'Reuse the analysis you already completed.',
211 + toolName
212 + ? `If the MCP tool \`${toolName}\` is available, call it exactly once with the final structured result. Otherwise reply with only raw JSON matching the schema.`
213 + : 'Reply with only raw JSON matching the schema.',
214 + 'Do not include prose, markdown fences, or any extra text.',
215 + JSON.stringify(structuredSchema, null, 2),
216 + ].join('\n');
217 +
218 +export const validateStructuredOutput = (
219 + parsed: unknown,
220 + options: InvokeAgentNormalizedOptions
221 +): unknown => {
222 if (options.zodSchema && typeof options.zodSchema.safeParse === 'function') {
223 const validation = options.zodSchema.safeParse(parsed);
224 if (!validation.success) {
@@ -141,14 +227,160 @@ export const finalizeInvokeAgentText = (
227 );
228 }
229
230 + return validation.data;
231 + }
232 +
233 + return parsed;
234 +};
235 +
236 +const tryParseStructuredJson = (text: string): unknown | undefined => {
237 + const trimmed = text.trim();
238 + if (!trimmed) {
239 + return undefined;
240 + }
241 +
242 + try {
243 + return JSON.parse(trimmed);
244 + } catch {
245 + // Fall through to more permissive extraction for agents that emit a short
246 + // status line before the final JSON payload.
247 + }
248 +
249 + const fencedMatches = [...trimmed.matchAll(/```(?:json)?\s*([\s\S]*?)```/gi)];
250 + for (let index = fencedMatches.length - 1; index >= 0; index -= 1) {
251 + const candidate = fencedMatches[index]?.[1]?.trim();
252 + if (!candidate) {
253 + continue;
254 + }
255 +
256 + try {
257 + return JSON.parse(candidate);
258 + } catch {
259 + // Keep scanning for a valid fenced block.
260 + }
261 + }
262 +
263 + const findBalancedJsonEnd = (value: string, start: number): number | null => {
264 + const opening = value[start];
265 + if (opening !== '{' && opening !== '[') {
266 + return null;
267 + }
268 +
269 + const closingStack = [opening === '{' ? '}' : ']'];
270 + let insideString = false;
271 + let escaped = false;
272 +
273 + for (let cursor = start + 1; cursor < value.length; cursor += 1) {
274 + const char = value[cursor]!;
275 + if (insideString) {
276 + if (escaped) {
277 + escaped = false;
278 + continue;
279 + }
280 + if (char === '\\') {
281 + escaped = true;
282 + continue;
283 + }
284 + if (char === '"') {
285 + insideString = false;
286 + }
287 + continue;
288 + }
289 +
290 + if (char === '"') {
291 + insideString = true;
292 + continue;
293 + }
294 + if (char === '{') {
295 + closingStack.push('}');
296 + continue;
297 + }
298 + if (char === '[') {
299 + closingStack.push(']');
300 + continue;
301 + }
302 +
303 + const expected = closingStack.at(-1);
304 + if ((char === '}' || char === ']') && expected === char) {
305 + closingStack.pop();
306 + if (closingStack.length === 0) {
307 + return cursor;
308 + }
309 + }
310 + }
311 +
312 + return null;
313 + };
314 +
315 + let bestCandidate:
316 + | {
317 + readonly length: number;
318 + readonly start: number;
319 + readonly isObject: boolean;
320 + readonly value: unknown;
321 + }
322 + | undefined;
323 +
324 + for (let start = 0; start < trimmed.length; start += 1) {
325 + const char = trimmed[start];
326 + if (char !== '{' && char !== '[') {
327 + continue;
328 + }
329 +
330 + const end = findBalancedJsonEnd(trimmed, start);
331 + if (end === null) {
332 + continue;
333 + }
334 +
335 + const candidate = trimmed.slice(start, end + 1);
336 + try {
337 + const parsed = JSON.parse(candidate);
338 + const nextCandidate = {
339 + length: candidate.length,
340 + start,
341 + isObject: !Array.isArray(parsed) && parsed !== null && typeof parsed === 'object',
342 + value: parsed,
343 + };
344 +
345 + if (
346 + !bestCandidate ||
347 + nextCandidate.length > bestCandidate.length ||
348 + (nextCandidate.length === bestCandidate.length &&
349 + nextCandidate.isObject &&
350 + !bestCandidate.isObject) ||
351 + (nextCandidate.length === bestCandidate.length &&
352 + nextCandidate.isObject === bestCandidate.isObject &&
353 + nextCandidate.start < bestCandidate.start)
354 + ) {
355 + bestCandidate = nextCandidate;
356 + }
357 + } catch {
358 + // Keep scanning for a larger valid JSON payload.
359 + }
360 + }
361 +
362 + return bestCandidate?.value;
363 +};
364 +
365 +export const finalizeInvokeAgentText = (
366 + text: string,
367 + options: InvokeAgentNormalizedOptions
368 +): Pick<InvokeAgentResponse, 'result' | 'structuredOutput'> => {
369 + const trimmed = text.trim();
370 + if (!options.structuredSchema) {
371 return {
145 - result: null,
146 - structuredOutput: validation.data,
372 + result: trimmed,
373 };
374 }
375
376 + let parsed: unknown;
377 + parsed = tryParseStructuredJson(trimmed);
378 + if (parsed === undefined) {
379 + throw new Error('subAgent() expected valid JSON output for structured response.');
380 + }
381 +
382 return {
383 result: null,
152 - structuredOutput: parsed,
384 + structuredOutput: validateStructuredOutput(parsed, options),
385 };
386 };
ts/packages/cli/test/src/commands/run.cmd.test.ts
+102 -3
@@ -18,7 +18,14 @@ import {
18 resolveRunCompanionModulePath,
19 writeInstalledReleaseTag,
20 } from 'src/services/run-companion-modules';
21 -import { buildStructuredPrompt, finalizeInvokeAgentText } from 'src/services/run-subagent-shared';
21 +import {
22 + ACP_STRUCTURED_OUTPUT_WRAPPER_KEY,
23 + buildStructuredRepairPrompt,
24 + buildStructuredOutputToolSchema,
25 + buildStructuredPrompt,
26 + buildStructuredToolPrompt,
27 + finalizeInvokeAgentText,
28 +} from 'src/services/run-subagent-shared';
29 import { cli, MockConsole, TestLive } from 'test/__utils__';
30
31 describe('CLI: composio run', () => {
@@ -34,6 +41,9 @@ describe('CLI: composio run', () => {
41 Effect.gen(function* () {
42 const spawn = vi.fn(() => ({ exited: Promise.resolve(7) }));
43 const exit = vi.spyOn(process, 'exit').mockImplementation((() => undefined) as never);
44 + const stderrWrite = vi
45 + .spyOn(process.stderr, 'write')
46 + .mockImplementation((() => true) as never);
47 vi.stubGlobal('Bun', { spawn });
48
49 yield* cli(['run', 'console.log("hi")', '--flag', 'value']);
@@ -59,6 +69,9 @@ describe('CLI: composio run', () => {
69 })
70 );
71 expect(spawnConfig.stdio).toEqual(['inherit', 'inherit', 'inherit']);
72 + expect(stderrWrite).toHaveBeenCalledWith(
73 + expect.stringMatching(/^RUN_LOG_FILE=.*run\.log\n$/)
74 + );
75 expect(exit).toHaveBeenCalledWith(7);
76 })
77 );
@@ -193,8 +206,10 @@ describe('buildRunHelpersSource', () => {
206 acpOnly: true,
207 logsOff: true,
208 dryRun: true,
209 + runLogFilePath: '/tmp/composio-run/run.log',
210 });
211
212 + expect(source).toContain('import * as fs from "node:fs";');
213 expect(source).toContain('import { z } from "zod";');
214 expect(source).toContain('import { isAcpInvokeError } from "file://');
215 expect(source).toContain('import { invokeAcpSubAgent } from "file://');
@@ -210,6 +225,10 @@ describe('buildRunHelpersSource', () => {
225 expect(source).toContain(
226 'const sharedRunOutputDir = typeof helperContext.runOutputDir === "string"'
227 );
228 + expect(source).toContain(
229 + 'const sharedRunLogFilePath = typeof helperContext.runLogFilePath === "string"'
230 + );
231 + expect(source).toContain('const appendRunLogLine = (line) => {');
232 expect(source).toContain('COMPOSIO_RUN_OUTPUT_DIR');
233 expect(source).toContain('const maybeLoadStoredCliResult = (result) => {');
234 expect(source).toContain('storedInFilePath: outputFilePath !== null,');
@@ -223,7 +242,9 @@ describe('buildRunHelpersSource', () => {
242 expect(source).toContain('COMPOSIO_USER_API_KEY');
243 expect(source).toContain('"acpOnly":true');
244 expect(source).toContain('"logsOff":true');
245 + expect(source).toContain('"runLogFilePath":"/tmp/composio-run/run.log"');
246 expect(source).toContain('"consumerUserId":"consumer_user_test"');
247 + expect(source).toContain('Object.defineProperty(globalThis, "__composioRunContext", {');
248 expect(source).toContain('__composioConsumerContext');
249 expect(source).toContain('globalThis.execute = async (slug, data = {}) => {');
250 expect(source).toContain(
@@ -235,11 +256,15 @@ describe('buildRunHelpersSource', () => {
256 'Object.defineProperty(globalThis.subAgent, "schema", { value: subAgentSchema });'
257 );
258 expect(source).toContain('globalThis.invokeAgent = subAgentImpl;');
238 - expect(source).toContain('return await invokeAcpSubAgent({');
259 + expect(source).toContain(
260 + 'const logFilePath = typeof helperContext.runLogFilePath === "string"'
261 + );
262 + expect(source).toContain('const response = await invokeAcpSubAgent({');
263 + expect(source).toContain('return logFilePath ? { ...response, logFilePath } : response;');
264 expect(source).toContain('if (!isAcpInvokeError(error)) {');
265 expect(source).toContain('if (helperContext.acpOnly === true) {');
266 expect(source).toContain('helperDebugLog("subAgent.acp.fallback"');
242 - expect(source).toContain('return invokeLegacySubAgent({');
267 + expect(source).toContain('const response = await invokeLegacySubAgent({');
268 expect(source).toContain('const detectInvokeAgentMaster = () => {');
269 expect(source).toContain(
270 'throw new Error("subAgent() accepts either options.schema or options.jsonSchema, not both.");'
@@ -281,6 +306,38 @@ describe('run-subagent-shared', () => {
306 );
307 });
308
309 + it('[Given] a non-object structured schema [Then] the MCP output tool schema wraps it under a value key', () => {
310 + expect(buildStructuredOutputToolSchema({ type: 'array', items: { type: 'string' } })).toEqual({
311 + type: 'object',
312 + additionalProperties: false,
313 + required: [ACP_STRUCTURED_OUTPUT_WRAPPER_KEY],
314 + properties: {
315 + [ACP_STRUCTURED_OUTPUT_WRAPPER_KEY]: { type: 'array', items: { type: 'string' } },
316 + },
317 + });
318 + });
319 +
320 + it('[Given] structured tool mode [Then] the prompt instructs the agent to use the output tool', () => {
321 + expect(
322 + buildStructuredToolPrompt(
323 + 'Summarize it.',
324 + { type: 'array', items: { type: 'string' } },
325 + 'submit_structured_output'
326 + )
327 + ).toContain('call the MCP tool `submit_structured_output` exactly once');
328 + });
329 +
330 + it('[Given] a repair prompt [Then] it requires no more tools and JSON-only fallback', () => {
331 + const prompt = buildStructuredRepairPrompt(
332 + { type: 'object', properties: { summary: { type: 'string' } } },
333 + 'submit_structured_output'
334 + );
335 +
336 + expect(prompt).toContain('Your previous response was not valid structured output.');
337 + expect(prompt).toContain('Do not read files. Do not run terminal commands.');
338 + expect(prompt).toContain('reply with only raw JSON matching the schema');
339 + });
340 +
341 it('[Given] Zod-like structured output [Then] it validates and returns structured data', () => {
342 const result = finalizeInvokeAgentText('{"ok":true}', {
343 structuredSchema: { type: 'object' },
@@ -311,6 +368,48 @@ describe('run-subagent-shared', () => {
368 })
369 ).toThrow('subAgent() expected valid JSON output for structured response.');
370 });
371 +
372 + it('[Given] prose followed by JSON in structured mode [Then] it recovers the final JSON payload', () => {
373 + const result = finalizeInvokeAgentText('Reading file now.\n{"ok":true}', {
374 + structuredSchema: { type: 'object' },
375 + zodSchema: {
376 + safeParse: value => ({ success: true as const, data: value }),
377 + },
378 + });
379 +
380 + expect(result).toEqual({
381 + result: null,
382 + structuredOutput: { ok: true },
383 + });
384 + });
385 +
386 + it('[Given] fenced JSON in structured mode [Then] it parses the fenced payload', () => {
387 + const result = finalizeInvokeAgentText('```json\n{"ok":true}\n```', {
388 + structuredSchema: { type: 'object' },
389 + zodSchema: {
390 + safeParse: value => ({ success: true as const, data: value }),
391 + },
392 + });
393 +
394 + expect(result).toEqual({
395 + result: null,
396 + structuredOutput: { ok: true },
397 + });
398 + });
399 +
400 + it('[Given] an object containing arrays [Then] it prefers the full object over an inner array', () => {
401 + const result = finalizeInvokeAgentText('Working...\n{"summary":"done","urgent":["a","b"]}', {
402 + structuredSchema: { type: 'object' },
403 + zodSchema: {
404 + safeParse: value => ({ success: true as const, data: value }),
405 + },
406 + });
407 +
408 + expect(result).toEqual({
409 + result: null,
410 + structuredOutput: { summary: 'done', urgent: ['a', 'b'] },
411 + });
412 + });
413 });
414
415 describe('inferCliInvocationPrefix', () => {
ts/packages/cli/test/src/services/run-subagent-acp.test.ts
+182 -1
@@ -1,5 +1,10 @@
1 import { afterEach, describe, expect, it, vi } from 'vitest';
2 -import { BufferedChunkLogger, resolveAcpAdapterCommand } from 'src/services/run-subagent-acp';
2 +import {
3 + BufferedChunkLogger,
4 + createStructuredOutputMcpContext,
5 + resolveAcpAdapterCommand,
6 + selectPermissionOutcome,
7 +} from 'src/services/run-subagent-acp';
8 import { AcpInvokeError, isAcpInvokeError } from 'src/services/run-subagent-shared';
9
10 describe('run-subagent-acp', () => {
@@ -61,4 +66,180 @@ describe('run-subagent-acp', () => {
66 text: 'Pick one fruit from the mixed box.',
67 });
68 });
69 +
70 + it('[Given] a read permission request [Then] it allows the read once', () => {
71 + const result = selectPermissionOutcome(
72 + {
73 + options: [
74 + { optionId: 'allow', kind: 'allow_once', name: 'Allow once' },
75 + { optionId: 'reject', kind: 'reject_once', name: 'Reject once' },
76 + ],
77 + toolCall: {
78 + toolCallId: 'tool-1',
79 + kind: 'read',
80 + title: 'Read File',
81 + rawInput: {
82 + file_path: '/tmp/composio/session/artifacts/emails.json',
83 + },
84 + },
85 + } as never,
86 + ['/tmp/composio/session', '/Users/test/.composio']
87 + );
88 +
89 + expect(result).toEqual({
90 + outcome: {
91 + outcome: 'selected',
92 + optionId: 'allow',
93 + },
94 + });
95 + });
96 +
97 + it('[Given] a non-read permission request [Then] it allows the request in permissive mode', () => {
98 + const result = selectPermissionOutcome(
99 + {
100 + options: [
101 + { optionId: 'allow-always', kind: 'allow_always', name: 'Allow always' },
102 + { optionId: 'allow-once', kind: 'allow_once', name: 'Allow once' },
103 + { optionId: 'reject', kind: 'reject_once', name: 'Reject once' },
104 + ],
105 + toolCall: {
106 + toolCallId: 'tool-2',
107 + kind: 'edit',
108 + title: 'Edit File',
109 + rawInput: {
110 + file_path: '/tmp/composio/session/artifacts/emails.json',
111 + },
112 + },
113 + } as never,
114 + ['/tmp/composio/session', '/Users/test/.composio']
115 + );
116 +
117 + expect(result).toEqual({
118 + outcome: {
119 + outcome: 'selected',
120 + optionId: 'allow-always',
121 + },
122 + });
123 + });
124 +
125 + it('[Given] a title-only read permission request [Then] it still allows the read once', () => {
126 + const result = selectPermissionOutcome(
127 + {
128 + options: [
129 + { optionId: 'allow', kind: 'allow_once', name: 'Allow once' },
130 + { optionId: 'reject', kind: 'reject_once', name: 'Reject once' },
131 + ],
132 + toolCall: {
133 + toolCallId: 'tool-3',
134 + kind: null,
135 + title: 'Read File',
136 + rawInput: {
137 + file_path: '/Users/test/.composio/tool_definitions/GMAIL_FETCH_EMAILS.json',
138 + },
139 + },
140 + } as never,
141 + ['/tmp/composio/session', '/Users/test/.composio']
142 + );
143 +
144 + expect(result).toEqual({
145 + outcome: {
146 + outcome: 'selected',
147 + optionId: 'allow',
148 + },
149 + });
150 + });
151 +
152 + it('[Given] an out-of-scope read request [Then] it still allows the read in permissive mode', () => {
153 + const result = selectPermissionOutcome(
154 + {
155 + options: [
156 + { optionId: 'allow-always', kind: 'allow_always', name: 'Allow always' },
157 + { optionId: 'allow', kind: 'allow_once', name: 'Allow once' },
158 + { optionId: 'reject', kind: 'reject_once', name: 'Reject once' },
159 + ],
160 + toolCall: {
161 + toolCallId: 'tool-4',
162 + kind: 'read',
163 + title: 'Read File',
164 + rawInput: {
165 + file_path: '/etc/passwd',
166 + },
167 + },
168 + } as never,
169 + ['/tmp/composio/session', '/Users/test/.composio']
170 + );
171 +
172 + expect(result).toEqual({
173 + outcome: {
174 + outcome: 'selected',
175 + optionId: 'allow-always',
176 + },
177 + });
178 + });
179 +
180 + it('[Given] a read-only terminal command over an allowed artifact path [Then] it allows the command once', () => {
181 + const result = selectPermissionOutcome(
182 + {
183 + options: [
184 + { optionId: 'allow', kind: 'allow_once', name: 'Allow once' },
185 + { optionId: 'reject', kind: 'reject_once', name: 'Reject once' },
186 + ],
187 + toolCall: {
188 + toolCallId: 'tool-5',
189 + kind: null,
190 + title:
191 + "`head -n 100 /tmp/composio/session/artifacts/emails.json | jq '.data' 2>/dev/null || head -n 100 /tmp/composio/session/artifacts/emails.json`",
192 + rawInput: {},
193 + },
194 + } as never,
195 + ['/tmp/composio/session', '/Users/test/.composio']
196 + );
197 +
198 + expect(result).toEqual({
199 + outcome: {
200 + outcome: 'selected',
201 + optionId: 'allow',
202 + },
203 + });
204 + });
205 +
206 + it('[Given] a structured schema [Then] it creates a stdio MCP server context for output capture', () => {
207 + const helperDebugLog = vi.fn();
208 + const context = createStructuredOutputMcpContext({
209 + options: {
210 + structuredSchema: {
211 + type: 'object',
212 + properties: {
213 + summary: { type: 'string' },
214 + },
215 + required: ['summary'],
216 + },
217 + },
218 + helperDebugLog,
219 + });
220 +
221 + expect(context).not.toBeNull();
222 + expect(context?.mcpServer.command).toBe(process.execPath);
223 + expect(context?.mcpServer.args).toEqual(
224 + expect.arrayContaining([
225 + expect.stringContaining('run-subagent-output-mcp'),
226 + '--schema-file',
227 + expect.stringContaining('schema.json'),
228 + '--result-file',
229 + expect.stringContaining('result.json'),
230 + ])
231 + );
232 + expect(context?.mcpServer.env).toEqual(
233 + expect.arrayContaining([{ name: 'BUN_BE_BUN', value: '1' }])
234 + );
235 + expect(context?.resultFilePath).toContain('result.json');
236 + expect(helperDebugLog).toHaveBeenCalledWith(
237 + 'subAgent.acp.structured_output_tool',
238 + expect.objectContaining({
239 + modulePath: expect.stringContaining('run-subagent-output-mcp'),
240 + })
241 + );
242 +
243 + context?.cleanup();
244 + });
245 });
ts/packages/cli/tsdown.config.ts
+1
@@ -8,6 +8,7 @@ export default defineConfig({
8 'src/services/run-subagent-shared.ts',
9 'src/services/run-subagent-acp.ts',
10 'src/services/run-subagent-legacy.ts',
11 + 'src/services/run-subagent-output-mcp.ts',
12 ],
13 format: ['esm'],
14 tsconfig: './tsconfig.src.json',