Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
TypeScript agentic-aiagentsaiai-agentsaiagentsdeveloper-toolsfunction-callinggpt-4javascriptjsllmllmopsmcppythonremote-mcp-serverssetypescript
fix(cli): harden run subAgent structured output (#3046)
Rahul Tarakcb0257506530
diff --git a/.changeset/fix-run-subagent-logfile-output.md b/.changeset/fix-run-subagent-logfile-output.mdnew file mode 100644index 000000000..77ccd3a8b--- /dev/null+++ b/.changeset/fix-run-subagent-logfile-output.md@@ -0,0 +1,5 @@+---+"@composio/cli": patch+---++fix(cli): harden run subagent structured output and logfile path propagationdiff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex b7163c29a..9d8c9ea49 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -1070,6 +1070,9 @@ importers:'@effect/platform-node-shared':specifier: 'catalog:'version: 0.57.1(@effect/[email protected](@effect/[email protected]([email protected]))(@effect/[email protected](@effect/[email protected]([email protected]))([email protected]))(@effect/[email protected](@effect/[email protected](@effect/[email protected]([email protected]))([email protected]))(@effect/[email protected]([email protected]))([email protected]))(@effect/[email protected](@effect/[email protected](@effect/[email protected]([email protected]))([email protected]))(@effect/[email protected]([email protected]))(@effect/[email protected](@effect/[email protected]([email protected]))([email protected]))([email protected]))([email protected]))(@effect/[email protected]([email protected]))(@effect/[email protected](@effect/[email protected]([email protected]))([email protected]))(@effect/[email protected](@effect/[email protected](@effect/[email protected]([email protected]))([email protected]))(@effect/[email protected]([email protected]))([email protected]))([email protected])+ '@modelcontextprotocol/sdk':+ specifier: ^1.26.0+ version: 1.26.0(@cfworker/[email protected])([email protected])'@zed-industries/claude-code-acp':specifier: ^0.16.2version: 0.16.2(@cfworker/[email protected])([email protected])diff --git a/ts/packages/cli/package.json b/ts/packages/cli/package.jsonindex 506b69a02..1a0ae4ff2 100644--- a/ts/packages/cli/package.json+++ b/ts/packages/cli/package.json@@ -78,6 +78,7 @@"@effect/cli": "catalog:","@effect/platform-bun": "catalog:","@effect/platform-node-shared": "catalog:",+ "@modelcontextprotocol/sdk": "^1.26.0","ansis": "^4.1.0","comment-json": "^4.2.5","decompress": "^4.2.1",diff --git a/ts/packages/cli/src/commands/run.cmd.ts b/ts/packages/cli/src/commands/run.cmd.tsindex 1351e09d5..43ea878fe 100644--- a/ts/packages/cli/src/commands/run.cmd.ts+++ b/ts/packages/cli/src/commands/run.cmd.ts@@ -20,6 +20,7 @@ import {appendCliSessionHistory,resolveCliSessionArtifacts,} from 'src/services/cli-session-artifacts';+import { USER_COMPOSIO_DIR } from 'src/constants';const file = Options.text('file').pipe(Options.withAlias('f'),@@ -36,7 +37,9 @@ const debug = Options.boolean('debug').pipe(Options.withDefault(false));const logsOff = Options.boolean('logs-off').pipe(- Options.withDescription('Hide the always-on subAgent streaming logs'),+ Options.withDescription(+ 'Compatibility flag. Helper logs are written to the run log file instead of stderr.'+ ),Options.withDefault(false));const skipConnectionCheck = Options.boolean('skip-connection-check').pipe(@@ -215,6 +218,8 @@ type RunHelperContext = {readonly acpOnly?: boolean;readonly logsOff?: boolean;readonly runOutputDir?: string;+ readonly runLogFilePath?: string;+ readonly readAccessRoots?: ReadonlyArray<string>;};// eslint-disable-next-line max-lines-per-function@@ -251,6 +256,7 @@ const buildRunBaseHelpersSource = (): ReadonlyArray<string> => [' target: { type: "string", enum: ["claude", "codex"] },',' result: { description: "Final plain-text result when available." },',' structuredOutput: { description: "Structured output when jsonSchema was requested." },',+ ' logFilePath: { description: "Path to the local run log file for helper execution details." },',' },',' },','};',@@ -285,20 +291,12 @@ const buildRunBaseHelpersSource = (): ReadonlyArray<string> => [' const payload = { phase, label, elapsedMs, ...details };',' console.error(`[perf] ${JSON.stringify(payload)}`);','};',- 'const helperDebugEnabled = helperContext.debug === true;',- 'const helperProgressEnabled = helperContext.logsOff !== true;','const sharedRunOutputDir = typeof helperContext.runOutputDir === "string" && helperContext.runOutputDir.length > 0 ? helperContext.runOutputDir : null;',- 'const helperProgressSteps = new Set([',- ' "subAgent.target",',- ' "subAgent.acp.message",',- ' "subAgent.acp.thought",',- ' "subAgent.acp.tool_call",',- ' "subAgent.acp.tool_call_update",',- ' "subAgent.acp.plan",',- ' "subAgent.acp.fallback",',- ']);',- 'const helperDebugUseColor = process.stderr?.isTTY === true && process.env.NO_COLOR !== "1";',- 'const helperDebugColorize = (line) => helperDebugUseColor ? `\\x1b[90m${line}\\x1b[0m` : line;',+ 'const sharedRunLogFilePath = typeof helperContext.runLogFilePath === "string" && helperContext.runLogFilePath.length > 0 ? helperContext.runLogFilePath : null;',+ 'const appendRunLogLine = (line) => {',+ ' if (!sharedRunLogFilePath || typeof line !== "string" || line.length === 0) return;',+ ' fs.appendFileSync(sharedRunLogFilePath, `${line}\\n`, "utf8");',+ '};','const truncateDebugText = (value, max = 240) => {',' const text = typeof value === "string" ? value : String(value ?? "");',' return text.length > max ? `${text.slice(0, max - 1)}…` : text;',@@ -381,13 +379,8 @@ const buildRunBaseHelpersSource = (): ReadonlyArray<string> => ['};','const helperDebugLog = (step, details = {}) => {',' const line = formatHelperDebugEvent(step, details);',- ' if (line && (helperDebugEnabled || (helperProgressEnabled && helperProgressSteps.has(step)))) {',- ' console.error(helperDebugColorize(line));',- ' return;',- ' }',- ' if (!helperDebugEnabled) return;',' const elapsedMs = Date.now() - perfDebugStart;',- ' console.error(helperDebugColorize(`[run:debug] ${JSON.stringify({ step, elapsedMs, ...details })}`));',+ ' appendRunLogLine(line ?? `[run:debug] ${JSON.stringify({ step, elapsedMs, ...details })}`);','};','const parseJson = (text) => {',' const value = text.trim();',@@ -447,7 +440,6 @@ const buildRunBaseHelpersSource = (): ReadonlyArray<string> => [' return result;','};','const logCliResultPreview = (requestId, command, result) => {',- ' if (!helperDebugEnabled) return;',' if (!result || typeof result !== "object") {',' helperDebugLog("cli.result", { requestId, command, preview: result, result: describeDebugValue(result) });',' return;',@@ -706,18 +698,21 @@ const buildRunInvokeAgentHelpersSource = (): ReadonlyArray<string> => [' if (typeof prompt !== "string" || prompt.trim().length === 0) {',' throw new Error("subAgent() requires a non-empty prompt string.");',' }',+ ' const logFilePath = typeof helperContext.runLogFilePath === "string" && helperContext.runLogFilePath.length > 0 ? helperContext.runLogFilePath : undefined;',' const normalizedOptions = normalizeInvokeAgentOptions(options);',' const target = resolveInvokeAgentTarget(normalizedOptions.target);',' const master = detectInvokeAgentMaster();',' helperDebugLog("subAgent.target", { requestedTarget: normalizedOptions.target ?? null, resolvedTarget: target, master });',' try {',- ' return await invokeAcpSubAgent({',+ ' const response = await invokeAcpSubAgent({',' prompt: prompt.trim(),',' options: normalizedOptions,',' master,',' target,',+ ' allowedReadRoots: Array.isArray(helperContext.readAccessRoots) ? helperContext.readAccessRoots : [],',' helperDebugLog,',' });',+ ' return logFilePath ? { ...response, logFilePath } : response;',' } catch (error) {',' if (!isAcpInvokeError(error)) {',' throw error;',@@ -726,13 +721,15 @@ const buildRunInvokeAgentHelpersSource = (): ReadonlyArray<string> => [' throw error;',' }',' helperDebugLog("subAgent.acp.fallback", { target, code: error.code, message: error.message });',- ' return invokeLegacySubAgent({',+ ' const response = await invokeLegacySubAgent({',' prompt: prompt.trim(),',' options: normalizedOptions,',' master,',' target,',+ ' allowedReadRoots: Array.isArray(helperContext.readAccessRoots) ? helperContext.readAccessRoots : [],',' helperDebugLog,',' });',+ ' return logFilePath ? { ...response, logFilePath } : response;',' }','};','globalThis.subAgent = subAgentImpl;',@@ -794,6 +791,14 @@ const buildRunProxyHelpersSource = (): ReadonlyArray<string> => ['};','Object.defineProperty(globalThis.proxy, "schema", { value: proxySchema });','',+ 'Object.defineProperty(globalThis, "__composioRunContext", {',+ ' value: Object.freeze({',+ ' outputDir: sharedRunOutputDir,',+ ' logFilePath: sharedRunLogFilePath,',+ ' }),',+ ' configurable: true,',+ '});',+ '','Object.defineProperty(globalThis, "__composioConsumerContext", {',' value: helperContext,',' configurable: true,',@@ -807,6 +812,7 @@ export const buildRunHelpersSource = (moduleUrls: RunHelperModuleUrls = resolveRunHelperModuleUrls()): string =>[+ 'import * as fs from "node:fs";','import { z } from "zod";',`import { isAcpInvokeError } from ${JSON.stringify(moduleUrls.subAgentSharedModuleUrl)};`,`import { invokeAcpSubAgent } from ${JSON.stringify(moduleUrls.subAgentAcpModuleUrl)};`,@@ -831,13 +837,28 @@ const createRunHelpersPreloadFile = (typeof context.runOutputDir === 'string' && context.runOutputDir.length > 0? context.runOutputDir: path.join(directory, 'artifacts');+ const runLogFilePath = path.join(runOutputDir, 'run.log');+ const readAccessRoots = [+ ...new Set(+ [+ ...(Array.isArray(context.readAccessRoots) ? context.readAccessRoots : []),+ runOutputDir,+ ].map(value => path.resolve(value))+ ),+ ];fs.mkdirSync(runOutputDir, { recursive: true });+ fs.writeFileSync(runLogFilePath, '', 'utf8');fs.writeFileSync(preloadPath,- buildRunHelpersSource(cliPrefix, { ...context, runOutputDir }, moduleUrls),+ buildRunHelpersSource(cliPrefix, {+ ...context,+ runOutputDir,+ runLogFilePath,+ readAccessRoots,+ }, moduleUrls),'utf8');- return { directory, preloadPath, runOutputDir };+ return { directory, preloadPath, runOutputDir, runLogFilePath };};export const buildRunCommand = ({@@ -898,11 +919,19 @@ const resolveRunHelperContext = () =>const userContext = yield* ComposioUserContext;const apiKey = Option.getOrUndefined(userContext.data.apiKey);const orgId = Option.getOrUndefined(userContext.data.orgId);+ const defaultComposioDir = path.join(os.homedir(), USER_COMPOSIO_DIR);+ const configuredCacheDir =+ process.env.COMPOSIO_CACHE_DIR?.trim() || process.env.CACHE_DIR?.trim() || defaultComposioDir;+ const baseReadAccessRoots = [+ ...new Set([defaultComposioDir, configuredCacheDir].map(value => path.resolve(value))),+ ];+const baseContext = {apiKey,baseURL: userContext.data.baseURL,webURL: userContext.data.webURL,orgId,+ readAccessRoots: baseReadAccessRoots,} satisfies RunHelperContext;if (!apiKey || !orgId) {@@ -925,6 +954,21 @@ const resolveRunHelperContext = () =>consumerUserId: consumerProject.value.consumerUserId,}).pipe(Effect.map(Option.map(artifacts => artifacts.directoryPath)))),+ readAccessRoots: [+ ...new Set(+ [+ ...baseReadAccessRoots,+ Option.getOrUndefined(+ yield* resolveCliSessionArtifacts({+ orgId,+ consumerUserId: consumerProject.value.consumerUserId,+ }).pipe(Effect.map(Option.map(artifacts => artifacts.directoryPath)))+ ),+ ]+ .filter((value): value is string => typeof value === 'string' && value.length > 0)+ .map(value => path.resolve(value))+ ),+ ],} satisfies RunHelperContext;});@@ -1068,6 +1112,7 @@ export const runCmd = Command.make('run', {debug,},}).pipe(Effect.catchAll(() => Effect.void));+ process.stderr.write(`RUN_LOG_FILE=${preload.runLogFilePath}\n`);const runCommand = buildRunCommand({file,args,diff --git a/ts/packages/cli/src/services/run-companion-modules.ts b/ts/packages/cli/src/services/run-companion-modules.tsindex c4059dbe9..17fa17d0a 100644--- a/ts/packages/cli/src/services/run-companion-modules.ts+++ b/ts/packages/cli/src/services/run-companion-modules.ts@@ -8,6 +8,7 @@ export const RUN_COMPANION_MODULE_BASENAMES = ['run-subagent-shared','run-subagent-acp','run-subagent-legacy',+ 'run-subagent-output-mcp',] as const;export const RUN_COMPANION_MODULE_FILENAMES = RUN_COMPANION_MODULE_BASENAMES.map(diff --git a/ts/packages/cli/src/services/run-subagent-acp.ts b/ts/packages/cli/src/services/run-subagent-acp.tsindex e9e29603c..26a435f62 100644--- a/ts/packages/cli/src/services/run-subagent-acp.ts+++ b/ts/packages/cli/src/services/run-subagent-acp.ts@@ -1,13 +1,22 @@+import * as fs from 'node:fs';import { spawn } from 'node:child_process';import { createRequire } from 'node:module';+import * as os from 'node:os';+import path from 'node:path';import { Readable, Writable } from 'node:stream';import * as acp from '@agentclientprotocol/sdk';import type { MasterKind } from 'src/services/master-detector';+import { resolveRunCompanionModulePath } from 'src/services/run-companion-modules';import {+ ACP_STRUCTURED_OUTPUT_TOOL_NAME,AcpInvokeError,+ buildStructuredRepairPrompt,buildStructuredPrompt,+ buildStructuredToolPrompt,finalizeInvokeAgentText,toInvokeAgentResponse,+ unwrapStructuredOutputToolPayload,+ validateStructuredOutput,type HelperDebugLog,type InvokeAgentNormalizedOptions,type InvokeAgentResponse,@@ -65,6 +74,134 @@ export const resolveAcpAdapterCommand = (};const chunkFlushPattern = /[\s,.;:!?)\]}"]$/;+const structuredOutputMcpModulePath = resolveRunCompanionModulePath({+ callerImportMetaUrl: import.meta.url,+ execPath: process.execPath,+ relativeNoExtensionFromCaller: './run-subagent-output-mcp',+});++const collectToolCallPaths = (value: unknown, results: Set<string>, parentKey?: string): void => {+ if (typeof value === 'string') {+ const key = parentKey?.toLowerCase() ?? '';+ if (+ key === 'path' ||+ key === 'file_path' ||+ key === 'directory' ||+ key.endsWith('_path') ||+ key.endsWith('_directory')+ ) {+ results.add(value);+ } else if (key === 'command' || key === 'cmd') {+ for (const candidatePath of extractPathsFromCommandText(value)) {+ results.add(candidatePath);+ }+ }+ return;+ }++ if (Array.isArray(value)) {+ const key = parentKey?.toLowerCase() ?? '';+ if (+ key === 'paths' ||+ key === 'directories' ||+ key.endsWith('_paths') ||+ key.endsWith('_directories')+ ) {+ for (const entry of value) {+ if (typeof entry === 'string') {+ results.add(entry);+ }+ }+ return;+ }++ for (const entry of value) {+ collectToolCallPaths(entry, results);+ }+ return;+ }++ if (!value || typeof value !== 'object') {+ return;+ }++ for (const [key, nestedValue] of Object.entries(value)) {+ collectToolCallPaths(nestedValue, results, key);+ }+};++const extractPathsFromCommandText = (command: string): ReadonlyArray<string> => {+ const results = new Set<string>();+ const matches = command.matchAll(/(^|[\s"'`])((?:~\/|\/)[^\s"'`|&;<>]+)/g);+ for (const match of matches) {+ const rawPath = match[2]?.trim();+ if (!rawPath) {+ continue;+ }++ results.add(rawPath.startsWith('~/') ? path.join(os.homedir(), rawPath.slice(2)) : rawPath);+ }++ return [...results];+};++const extractToolCallPaths = (+ toolCall: Pick<acp.RequestPermissionRequest, 'toolCall'>['toolCall']+): ReadonlyArray<string> => {+ const paths = new Set<string>();+ for (const location of toolCall.locations ?? []) {+ if (typeof location.path === 'string' && location.path.length > 0) {+ paths.add(location.path);+ }+ }++ collectToolCallPaths(toolCall.rawInput, paths);+ if (typeof toolCall.title === 'string') {+ for (const candidatePath of extractPathsFromCommandText(toolCall.title)) {+ paths.add(candidatePath);+ }+ }+ return [...paths];+};++export const selectPermissionOutcome = (+ params: Pick<acp.RequestPermissionRequest, 'options' | 'toolCall'>,+ _allowedReadRoots: ReadonlyArray<string> = []+): acp.RequestPermissionResponse => {+ const allowOnce =+ params.options.find(option => option.kind === 'allow_always') ??+ params.options.find(option => option.kind === 'allow_once');+ const rejectOption =+ params.options.find(option => option.kind === 'reject_once') ??+ params.options.find(option => option.kind === 'reject_always');++ // Intentionally permissive for `composio run` subAgent sessions. The user is+ // explicitly opting into local tool access, so prefer broad ACP approval over+ // heuristic rejections that strand the agent mid-task.+ if (allowOnce) {+ return {+ outcome: {+ outcome: 'selected',+ optionId: allowOnce.optionId,+ },+ };+ }++ if (rejectOption) {+ return {+ outcome: {+ outcome: 'selected',+ optionId: rejectOption.optionId,+ },+ };+ }++ return {+ outcome: {+ outcome: 'cancelled',+ },+ };+};export class BufferedChunkLogger {private buffer = '';@@ -125,7 +262,10 @@ class RunSubAgentClient {private readonly messageLogger: BufferedChunkLogger;private readonly thoughtLogger: BufferedChunkLogger;- constructor(private readonly helperDebugLog: HelperDebugLog) {+ constructor(+ private readonly helperDebugLog: HelperDebugLog,+ private readonly allowedReadRoots: ReadonlyArray<string>+ ) {this.messageLogger = new BufferedChunkLogger('subAgent.acp.message', helperDebugLog);this.thoughtLogger = new BufferedChunkLogger('subAgent.acp.thought', helperDebugLog);}@@ -133,29 +273,20 @@ class RunSubAgentClient {async requestPermission(params: acp.RequestPermissionRequest): Promise<acp.RequestPermissionResponse> {+ const requestedPaths = extractToolCallPaths(params.toolCall);+ const decision = selectPermissionOutcome(params, this.allowedReadRoots);this.helperDebugLog('subAgent.acp.permission', {toolCallId: params.toolCall.toolCallId,+ title: params.toolCall.title ?? null,+ kind: params.toolCall.kind ?? null,+ locations: params.toolCall.locations?.map(location => location.path) ?? [],+ requestedPaths,+ allowedReadRoots: this.allowedReadRoots,+ selectedOptionId: decision.outcome.outcome === 'selected' ? decision.outcome.optionId : null,options: params.options.map(option => option.kind),});- const rejectOption =- params.options.find(option => option.kind === 'reject_once') ??- params.options.find(option => option.kind === 'reject_always');-- if (rejectOption) {- return {- outcome: {- outcome: 'selected',- optionId: rejectOption.optionId,- },- };- }-- return {- outcome: {- outcome: 'cancelled',- },- };+ return decision;}async sessionUpdate(params: acp.SessionNotification): Promise<void> {@@ -222,19 +353,121 @@ const createFallbackError = (cause?: unknown): AcpInvokeError => new AcpInvokeError(code, message, cause === undefined ? undefined : { cause });+type StructuredOutputMcpContext = {+ readonly mcpServer: acp.McpServerStdio;+ readonly resultFilePath: string;+ readonly cleanup: () => void;+};++export const createStructuredOutputMcpContext = ({+ options,+ helperDebugLog,+}: {+ options: InvokeAgentNormalizedOptions;+ helperDebugLog: HelperDebugLog;+}): StructuredOutputMcpContext | null => {+ if (!options.structuredSchema) {+ return null;+ }++ let tempDirectory: string | null = null;+ try {+ tempDirectory = fs.mkdtempSync(path.join(os.tmpdir(), 'composio-subagent-output-mcp-'));+ const schemaFilePath = path.join(tempDirectory, 'schema.json');+ const resultFilePath = path.join(tempDirectory, 'result.json');+ fs.writeFileSync(schemaFilePath, JSON.stringify(options.structuredSchema), 'utf8');++ helperDebugLog('subAgent.acp.structured_output_tool', {+ modulePath: structuredOutputMcpModulePath,+ schemaFilePath,+ resultFilePath,+ });++ return {+ mcpServer: {+ name: 'composio-structured-output',+ command: process.execPath,+ args: [+ structuredOutputMcpModulePath,+ '--schema-file',+ schemaFilePath,+ '--result-file',+ resultFilePath,+ ],+ env: [+ {+ name: 'BUN_BE_BUN',+ value: '1',+ },+ ],+ },+ resultFilePath,+ cleanup: () => {+ if (tempDirectory) {+ fs.rmSync(tempDirectory, { recursive: true, force: true });+ }+ },+ };+ } catch (error) {+ if (tempDirectory) {+ fs.rmSync(tempDirectory, { recursive: true, force: true });+ }+ helperDebugLog('subAgent.acp.structured_output_tool_failed', {+ error: error instanceof Error ? error.message : String(error),+ modulePath: structuredOutputMcpModulePath,+ });+ return null;+ }+};++const maybeReadStructuredOutputFromTool = ({+ context,+ options,+ helperDebugLog,+}: {+ context: StructuredOutputMcpContext | null;+ options: InvokeAgentNormalizedOptions;+ helperDebugLog: HelperDebugLog;+}): unknown | undefined => {+ if (!context || !options.structuredSchema || !fs.existsSync(context.resultFilePath)) {+ return undefined;+ }++ try {+ const rawPayload = JSON.parse(fs.readFileSync(context.resultFilePath, 'utf8')) as unknown;+ const parsed = unwrapStructuredOutputToolPayload(rawPayload, options.structuredSchema);+ helperDebugLog('subAgent.acp.structured_output_tool_result', {+ resultFilePath: context.resultFilePath,+ });+ return validateStructuredOutput(parsed, options);+ } catch (error) {+ helperDebugLog('subAgent.acp.structured_output_tool_result_failed', {+ resultFilePath: context.resultFilePath,+ error: error instanceof Error ? error.message : String(error),+ });+ return undefined;+ }+};+export const invokeAcpSubAgent = async ({prompt,options,master,target,+ allowedReadRoots,helperDebugLog,}: {prompt: string;options: InvokeAgentNormalizedOptions;master: MasterKind;target: InvokeAgentTarget;+ allowedReadRoots: ReadonlyArray<string>;helperDebugLog: HelperDebugLog;}): Promise<InvokeAgentResponse> => {+ const structuredOutputMcp = createStructuredOutputMcpContext({+ options,+ helperDebugLog,+ });const resolved = resolveAcpAdapterCommand(target);helperDebugLog('subAgent.acp.resolve', {target,@@ -268,7 +501,9 @@ export const invokeAcpSubAgent = async ({throw createFallbackError('spawn_failed', `Failed to spawn ${target} ACP adapter.`);}- const client = new RunSubAgentClient(helperDebugLog);+ const client = new RunSubAgentClient(helperDebugLog, [+ ...new Set(allowedReadRoots.map(root => path.resolve(root))),+ ]);const stream = acp.ndJsonStream(Writable.toWeb(child.stdin) as unknown as WritableStream<Uint8Array>,Readable.toWeb(child.stdout) as unknown as ReadableStream<Uint8Array>@@ -297,7 +532,7 @@ export const invokeAcpSubAgent = async ({const session = await connection.newSession({cwd: process.cwd(),- mcpServers: [],+ mcpServers: structuredOutputMcp ? [structuredOutputMcp.mcpServer] : [],}).catch(error => {throw createFallbackError(@@ -333,26 +568,36 @@ export const invokeAcpSubAgent = async ({}}- const promptText = buildStructuredPrompt(prompt, options.structuredSchema);- const response = await connection- .prompt({- sessionId: session.sessionId,- prompt: [{ type: 'text', text: promptText }],- })- .catch(error => {- if (connection.signal.aborted) {+ const promptText =+ options.structuredSchema && structuredOutputMcp+ ? buildStructuredToolPrompt(+ prompt,+ options.structuredSchema,+ ACP_STRUCTURED_OUTPUT_TOOL_NAME+ )+ : buildStructuredPrompt(prompt, options.structuredSchema);+ const runPrompt = async (promptText: string) =>+ connection+ .prompt({+ sessionId: session.sessionId,+ prompt: [{ type: 'text', text: promptText }],+ })+ .catch(error => {+ if (connection.signal.aborted) {+ throw createFallbackError(+ 'connection_closed',+ `${target} ACP connection closed before prompt completion${stderr.trim() ? `: ${stderr.trim()}` : ''}`,+ error+ );+ }throw createFallbackError(- 'connection_closed',- `${target} ACP connection closed before prompt completion${stderr.trim() ? `: ${stderr.trim()}` : ''}`,+ 'prompt_failed',+ `${target} ACP prompt failed${stderr.trim() ? `: ${stderr.trim()}` : ''}`,error);- }- throw createFallbackError(- 'prompt_failed',- `${target} ACP prompt failed${stderr.trim() ? `: ${stderr.trim()}` : ''}`,- error- );- });+ });++ const response = await runPrompt(promptText);if (response.stopReason === 'cancelled') {throw createFallbackError(@@ -361,9 +606,63 @@ export const invokeAcpSubAgent = async ({);}- const payload = finalizeInvokeAgentText(client.getText(), options);+ const structuredOutput = maybeReadStructuredOutputFromTool({+ context: structuredOutputMcp,+ options,+ helperDebugLog,+ });+ if (structuredOutput !== undefined) {+ return toInvokeAgentResponse(master, target, {+ result: null,+ structuredOutput,+ });+ }++ let payload: Pick<InvokeAgentResponse, 'result' | 'structuredOutput'>;+ try {+ payload = finalizeInvokeAgentText(client.getText(), options);+ } catch (error) {+ if (!options.structuredSchema) {+ throw error;+ }++ helperDebugLog('subAgent.acp.structured_repair', {+ target,+ reason: error instanceof Error ? error.message : String(error),+ });++ const repairResponse = await runPrompt(+ buildStructuredRepairPrompt(+ options.structuredSchema,+ structuredOutputMcp ? ACP_STRUCTURED_OUTPUT_TOOL_NAME : undefined+ )+ );++ if (repairResponse.stopReason === 'cancelled') {+ throw createFallbackError(+ 'prompt_failed',+ `${target} ACP repair prompt was cancelled${stderr.trim() ? `: ${stderr.trim()}` : ''}`+ );+ }++ const repairedStructuredOutput = maybeReadStructuredOutputFromTool({+ context: structuredOutputMcp,+ options,+ helperDebugLog,+ });+ if (repairedStructuredOutput !== undefined) {+ return toInvokeAgentResponse(master, target, {+ result: null,+ structuredOutput: repairedStructuredOutput,+ });+ }++ payload = finalizeInvokeAgentText(client.getText(), options);+ }+return toInvokeAgentResponse(master, target, payload);} finally {+ structuredOutputMcp?.cleanup();child.kill();await Promise.race([closePromise.catch(() => undefined),diff --git a/ts/packages/cli/src/services/run-subagent-output-mcp.ts b/ts/packages/cli/src/services/run-subagent-output-mcp.tsnew file mode 100644index 000000000..fba34162f--- /dev/null+++ b/ts/packages/cli/src/services/run-subagent-output-mcp.ts@@ -0,0 +1,106 @@+import path from 'node:path';+import * as fs from 'node:fs';+import { createRequire } from 'node:module';+import process from 'node:process';+import { pathToFileURL } from 'node:url';+import { jsonSchemaToZodSchema } from '@composio/core';+import {+ ACP_STRUCTURED_OUTPUT_TOOL_NAME,+ buildStructuredOutputToolSchema,+} from 'src/services/run-subagent-shared';++const readFlag = (name: string): string => {+ const index = process.argv.indexOf(name);+ const value = index >= 0 ? process.argv[index + 1] : undefined;+ if (!value) {+ throw new Error(`Missing required flag: ${name}`);+ }+ return value;+};++type McpServerInstance = {+ registerTool: (+ name: string,+ config: {+ title?: string;+ description?: string;+ inputSchema?: unknown;+ },+ cb: (payload: unknown) => Promise<{+ content: Array<{+ type: string;+ text: string;+ }>;+ }>+ ) => void;+ connect: (transport: unknown) => Promise<void>;+};++type McpServerConstructor = new (serverInfo: {+ name: string;+ version: string;+}) => McpServerInstance;++type StdioServerTransportConstructor = new () => unknown;++const loadMcpSdk = async (): Promise<{+ McpServer: McpServerConstructor;+ StdioServerTransport: StdioServerTransportConstructor;+}> => {+ const require = createRequire(import.meta.url);+ const sdkPackageJsonPath = require.resolve('@modelcontextprotocol/sdk/package.json');+ const sdkDirectory = path.dirname(sdkPackageJsonPath);+ const [mcpModule, stdioModule] = await Promise.all([+ import(pathToFileURL(path.join(sdkDirectory, 'dist/esm/server/mcp.js')).href),+ import(pathToFileURL(path.join(sdkDirectory, 'dist/esm/server/stdio.js')).href),+ ]);++ return {+ McpServer: mcpModule.McpServer as McpServerConstructor,+ StdioServerTransport: stdioModule.StdioServerTransport as StdioServerTransportConstructor,+ };+};++const main = async (): Promise<void> => {+ const { McpServer, StdioServerTransport } = await loadMcpSdk();+ const schemaFilePath = readFlag('--schema-file');+ const resultFilePath = readFlag('--result-file');+ const schemaText = fs.readFileSync(schemaFilePath, 'utf8');+ const structuredSchema = JSON.parse(schemaText) as Record<string, unknown>;+ const toolInputSchema = jsonSchemaToZodSchema(buildStructuredOutputToolSchema(structuredSchema));++ const server = new McpServer({+ name: 'composio-subagent-output',+ version: '1.0.0',+ });++ server.registerTool(+ ACP_STRUCTURED_OUTPUT_TOOL_NAME,+ {+ title: 'Submit structured output',+ description:+ 'Submit the final structured subAgent output. Call this exactly once when the task is complete.',+ inputSchema: toolInputSchema,+ },+ async (payload: unknown) => {+ fs.writeFileSync(resultFilePath, JSON.stringify(payload), 'utf8');+ return {+ content: [+ {+ type: 'text',+ text: 'Structured output captured.',+ },+ ],+ };+ }+ );++ const transport = new StdioServerTransport();+ await server.connect(transport);+};++void main().catch(error => {+ const message = error instanceof Error ? (error.stack ?? error.message) : String(error);+ process.stderr.write(`${message}\n`);+ process.exit(1);+});diff --git a/ts/packages/cli/src/services/run-subagent-shared.ts b/ts/packages/cli/src/services/run-subagent-shared.tsindex ffd270c8f..b1622af92 100644--- a/ts/packages/cli/src/services/run-subagent-shared.ts+++ b/ts/packages/cli/src/services/run-subagent-shared.ts@@ -20,8 +20,12 @@ export type InvokeAgentResponse = {readonly target: InvokeAgentTarget;readonly result: string | null;readonly structuredOutput?: unknown;+ readonly logFilePath?: string;};+export const ACP_STRUCTURED_OUTPUT_TOOL_NAME = 'submit_structured_output';+export const ACP_STRUCTURED_OUTPUT_WRAPPER_KEY = 'value';+export type HelperDebugLog = (step: string, details?: Record<string, unknown>) => void;export type AcpInvokeFailure =@@ -52,7 +56,7 @@ export const isAcpInvokeError = (value: unknown): value is AcpInvokeError =>export const toInvokeAgentResponse = (master: MasterKind,target: InvokeAgentTarget,- payload: Partial<Pick<InvokeAgentResponse, 'result' | 'structuredOutput'>> = {}+ payload: Partial<Pick<InvokeAgentResponse, 'result' | 'structuredOutput' | 'logFilePath'>> = {}): InvokeAgentResponse => ({master,target,@@ -60,6 +64,9 @@ export const toInvokeAgentResponse = (...(payload.structuredOutput === undefined || payload.structuredOutput === null? {}: { structuredOutput: payload.structuredOutput }),+ ...(typeof payload.logFilePath === 'string' && payload.logFilePath.length > 0+ ? { logFilePath: payload.logFilePath }+ : {}),});export const parseJson = (text: string): unknown => {@@ -115,24 +122,103 @@ export const buildStructuredPrompt = (].join('\n');};-export const finalizeInvokeAgentText = (- text: string,- options: InvokeAgentNormalizedOptions-): Pick<InvokeAgentResponse, 'result' | 'structuredOutput'> => {- const trimmed = text.trim();- if (!options.structuredSchema) {- return {- result: trimmed,- };+const isStructuredObjectSchema = (structuredSchema?: Record<string, unknown>): boolean => {+ if (!structuredSchema || Array.isArray(structuredSchema)) {+ return false;}- let parsed: unknown;- try {- parsed = JSON.parse(trimmed);- } catch {- throw new Error('subAgent() expected valid JSON output for structured response.');+ const schemaType = structuredSchema.type;+ if (schemaType === 'object') {+ return true;+ }++ if (Array.isArray(schemaType) && schemaType.includes('object')) {+ return true;+ }++ return (+ 'properties' in structuredSchema ||+ 'required' in structuredSchema ||+ 'additionalProperties' in structuredSchema+ );+};++export const buildStructuredOutputToolSchema = (+ structuredSchema: Record<string, unknown>+): Record<string, unknown> =>+ isStructuredObjectSchema(structuredSchema)+ ? structuredSchema+ : {+ type: 'object',+ additionalProperties: false,+ required: [ACP_STRUCTURED_OUTPUT_WRAPPER_KEY],+ properties: {+ [ACP_STRUCTURED_OUTPUT_WRAPPER_KEY]: structuredSchema,+ },+ };++export const unwrapStructuredOutputToolPayload = (+ payload: unknown,+ structuredSchema: Record<string, unknown>+): unknown => {+ if (isStructuredObjectSchema(structuredSchema)) {+ return payload;+ }++ if (+ payload &&+ typeof payload === 'object' &&+ !Array.isArray(payload) &&+ ACP_STRUCTURED_OUTPUT_WRAPPER_KEY in payload+ ) {+ return (payload as Record<string, unknown>)[ACP_STRUCTURED_OUTPUT_WRAPPER_KEY];}+ return payload;+};++export const buildStructuredToolPrompt = (+ prompt: string,+ structuredSchema: Record<string, unknown>,+ toolName: string+): string => {+ const usesWrapper = !isStructuredObjectSchema(structuredSchema);+ const toolShapeInstruction = usesWrapper+ ? `Call \`${toolName}\` with a single argument named \`${ACP_STRUCTURED_OUTPUT_WRAPPER_KEY}\` containing the final value.`+ : `Call \`${toolName}\` with the final structured object as the tool arguments.`;++ return [+ prompt,+ '',+ 'You may inspect files, search, and use tools as needed before producing the final answer.',+ `When you are ready to deliver the final structured response, call the MCP tool \`${toolName}\` exactly once.`,+ toolShapeInstruction,+ `If the MCP tool \`${toolName}\` is unavailable or you cannot call it, reply with only raw JSON matching the schema.`,+ 'Do not include prose, markdown fences, or any text before or after the final structured payload.',+ 'The final structured value must match this schema:',+ JSON.stringify(structuredSchema, null, 2),+ ].join('\n');+};++export const buildStructuredRepairPrompt = (+ structuredSchema: Record<string, unknown>,+ toolName?: string+): string =>+ [+ 'Your previous response was not valid structured output.',+ 'Do not read files. Do not run terminal commands. Do not inspect the workspace again.',+ 'Reuse the analysis you already completed.',+ toolName+ ? `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.`+ : 'Reply with only raw JSON matching the schema.',+ 'Do not include prose, markdown fences, or any extra text.',+ JSON.stringify(structuredSchema, null, 2),+ ].join('\n');++export const validateStructuredOutput = (+ parsed: unknown,+ options: InvokeAgentNormalizedOptions+): unknown => {if (options.zodSchema && typeof options.zodSchema.safeParse === 'function') {const validation = options.zodSchema.safeParse(parsed);if (!validation.success) {@@ -141,14 +227,160 @@ export const finalizeInvokeAgentText = ();}+ return validation.data;+ }++ return parsed;+};++const tryParseStructuredJson = (text: string): unknown | undefined => {+ const trimmed = text.trim();+ if (!trimmed) {+ return undefined;+ }++ try {+ return JSON.parse(trimmed);+ } catch {+ // Fall through to more permissive extraction for agents that emit a short+ // status line before the final JSON payload.+ }++ const fencedMatches = [...trimmed.matchAll(/```(?:json)?\s*([\s\S]*?)```/gi)];+ for (let index = fencedMatches.length - 1; index >= 0; index -= 1) {+ const candidate = fencedMatches[index]?.[1]?.trim();+ if (!candidate) {+ continue;+ }++ try {+ return JSON.parse(candidate);+ } catch {+ // Keep scanning for a valid fenced block.+ }+ }++ const findBalancedJsonEnd = (value: string, start: number): number | null => {+ const opening = value[start];+ if (opening !== '{' && opening !== '[') {+ return null;+ }++ const closingStack = [opening === '{' ? '}' : ']'];+ let insideString = false;+ let escaped = false;++ for (let cursor = start + 1; cursor < value.length; cursor += 1) {+ const char = value[cursor]!;+ if (insideString) {+ if (escaped) {+ escaped = false;+ continue;+ }+ if (char === '\\') {+ escaped = true;+ continue;+ }+ if (char === '"') {+ insideString = false;+ }+ continue;+ }++ if (char === '"') {+ insideString = true;+ continue;+ }+ if (char === '{') {+ closingStack.push('}');+ continue;+ }+ if (char === '[') {+ closingStack.push(']');+ continue;+ }++ const expected = closingStack.at(-1);+ if ((char === '}' || char === ']') && expected === char) {+ closingStack.pop();+ if (closingStack.length === 0) {+ return cursor;+ }+ }+ }++ return null;+ };++ let bestCandidate:+ | {+ readonly length: number;+ readonly start: number;+ readonly isObject: boolean;+ readonly value: unknown;+ }+ | undefined;++ for (let start = 0; start < trimmed.length; start += 1) {+ const char = trimmed[start];+ if (char !== '{' && char !== '[') {+ continue;+ }++ const end = findBalancedJsonEnd(trimmed, start);+ if (end === null) {+ continue;+ }++ const candidate = trimmed.slice(start, end + 1);+ try {+ const parsed = JSON.parse(candidate);+ const nextCandidate = {+ length: candidate.length,+ start,+ isObject: !Array.isArray(parsed) && parsed !== null && typeof parsed === 'object',+ value: parsed,+ };++ if (+ !bestCandidate ||+ nextCandidate.length > bestCandidate.length ||+ (nextCandidate.length === bestCandidate.length &&+ nextCandidate.isObject &&+ !bestCandidate.isObject) ||+ (nextCandidate.length === bestCandidate.length &&+ nextCandidate.isObject === bestCandidate.isObject &&+ nextCandidate.start < bestCandidate.start)+ ) {+ bestCandidate = nextCandidate;+ }+ } catch {+ // Keep scanning for a larger valid JSON payload.+ }+ }++ return bestCandidate?.value;+};++export const finalizeInvokeAgentText = (+ text: string,+ options: InvokeAgentNormalizedOptions+): Pick<InvokeAgentResponse, 'result' | 'structuredOutput'> => {+ const trimmed = text.trim();+ if (!options.structuredSchema) {return {- result: null,- structuredOutput: validation.data,+ result: trimmed,};}+ let parsed: unknown;+ parsed = tryParseStructuredJson(trimmed);+ if (parsed === undefined) {+ throw new Error('subAgent() expected valid JSON output for structured response.');+ }+return {result: null,- structuredOutput: parsed,+ structuredOutput: validateStructuredOutput(parsed, options),};};diff --git a/ts/packages/cli/test/src/commands/run.cmd.test.ts b/ts/packages/cli/test/src/commands/run.cmd.test.tsindex 2876788a2..4f89128c5 100644--- a/ts/packages/cli/test/src/commands/run.cmd.test.ts+++ b/ts/packages/cli/test/src/commands/run.cmd.test.ts@@ -18,7 +18,14 @@ import {resolveRunCompanionModulePath,writeInstalledReleaseTag,} from 'src/services/run-companion-modules';-import { buildStructuredPrompt, finalizeInvokeAgentText } from 'src/services/run-subagent-shared';+import {+ ACP_STRUCTURED_OUTPUT_WRAPPER_KEY,+ buildStructuredRepairPrompt,+ buildStructuredOutputToolSchema,+ buildStructuredPrompt,+ buildStructuredToolPrompt,+ finalizeInvokeAgentText,+} from 'src/services/run-subagent-shared';import { cli, MockConsole, TestLive } from 'test/__utils__';describe('CLI: composio run', () => {@@ -34,6 +41,9 @@ describe('CLI: composio run', () => {Effect.gen(function* () {const spawn = vi.fn(() => ({ exited: Promise.resolve(7) }));const exit = vi.spyOn(process, 'exit').mockImplementation((() => undefined) as never);+ const stderrWrite = vi+ .spyOn(process.stderr, 'write')+ .mockImplementation((() => true) as never);vi.stubGlobal('Bun', { spawn });yield* cli(['run', 'console.log("hi")', '--flag', 'value']);@@ -59,6 +69,9 @@ describe('CLI: composio run', () => {}));expect(spawnConfig.stdio).toEqual(['inherit', 'inherit', 'inherit']);+ expect(stderrWrite).toHaveBeenCalledWith(+ expect.stringMatching(/^RUN_LOG_FILE=.*run\.log\n$/)+ );expect(exit).toHaveBeenCalledWith(7);}));@@ -193,8 +206,10 @@ describe('buildRunHelpersSource', () => {acpOnly: true,logsOff: true,dryRun: true,+ runLogFilePath: '/tmp/composio-run/run.log',});+ expect(source).toContain('import * as fs from "node:fs";');expect(source).toContain('import { z } from "zod";');expect(source).toContain('import { isAcpInvokeError } from "file://');expect(source).toContain('import { invokeAcpSubAgent } from "file://');@@ -210,6 +225,10 @@ describe('buildRunHelpersSource', () => {expect(source).toContain('const sharedRunOutputDir = typeof helperContext.runOutputDir === "string"');+ expect(source).toContain(+ 'const sharedRunLogFilePath = typeof helperContext.runLogFilePath === "string"'+ );+ expect(source).toContain('const appendRunLogLine = (line) => {');expect(source).toContain('COMPOSIO_RUN_OUTPUT_DIR');expect(source).toContain('const maybeLoadStoredCliResult = (result) => {');expect(source).toContain('storedInFilePath: outputFilePath !== null,');@@ -223,7 +242,9 @@ describe('buildRunHelpersSource', () => {expect(source).toContain('COMPOSIO_USER_API_KEY');expect(source).toContain('"acpOnly":true');expect(source).toContain('"logsOff":true');+ expect(source).toContain('"runLogFilePath":"/tmp/composio-run/run.log"');expect(source).toContain('"consumerUserId":"consumer_user_test"');+ expect(source).toContain('Object.defineProperty(globalThis, "__composioRunContext", {');expect(source).toContain('__composioConsumerContext');expect(source).toContain('globalThis.execute = async (slug, data = {}) => {');expect(source).toContain(@@ -235,11 +256,15 @@ describe('buildRunHelpersSource', () => {'Object.defineProperty(globalThis.subAgent, "schema", { value: subAgentSchema });');expect(source).toContain('globalThis.invokeAgent = subAgentImpl;');- expect(source).toContain('return await invokeAcpSubAgent({');+ expect(source).toContain(+ 'const logFilePath = typeof helperContext.runLogFilePath === "string"'+ );+ expect(source).toContain('const response = await invokeAcpSubAgent({');+ expect(source).toContain('return logFilePath ? { ...response, logFilePath } : response;');expect(source).toContain('if (!isAcpInvokeError(error)) {');expect(source).toContain('if (helperContext.acpOnly === true) {');expect(source).toContain('helperDebugLog("subAgent.acp.fallback"');- expect(source).toContain('return invokeLegacySubAgent({');+ expect(source).toContain('const response = await invokeLegacySubAgent({');expect(source).toContain('const detectInvokeAgentMaster = () => {');expect(source).toContain('throw new Error("subAgent() accepts either options.schema or options.jsonSchema, not both.");'@@ -281,6 +306,38 @@ describe('run-subagent-shared', () => {);});+ it('[Given] a non-object structured schema [Then] the MCP output tool schema wraps it under a value key', () => {+ expect(buildStructuredOutputToolSchema({ type: 'array', items: { type: 'string' } })).toEqual({+ type: 'object',+ additionalProperties: false,+ required: [ACP_STRUCTURED_OUTPUT_WRAPPER_KEY],+ properties: {+ [ACP_STRUCTURED_OUTPUT_WRAPPER_KEY]: { type: 'array', items: { type: 'string' } },+ },+ });+ });++ it('[Given] structured tool mode [Then] the prompt instructs the agent to use the output tool', () => {+ expect(+ buildStructuredToolPrompt(+ 'Summarize it.',+ { type: 'array', items: { type: 'string' } },+ 'submit_structured_output'+ )+ ).toContain('call the MCP tool `submit_structured_output` exactly once');+ });++ it('[Given] a repair prompt [Then] it requires no more tools and JSON-only fallback', () => {+ const prompt = buildStructuredRepairPrompt(+ { type: 'object', properties: { summary: { type: 'string' } } },+ 'submit_structured_output'+ );++ expect(prompt).toContain('Your previous response was not valid structured output.');+ expect(prompt).toContain('Do not read files. Do not run terminal commands.');+ expect(prompt).toContain('reply with only raw JSON matching the schema');+ });+it('[Given] Zod-like structured output [Then] it validates and returns structured data', () => {const result = finalizeInvokeAgentText('{"ok":true}', {structuredSchema: { type: 'object' },@@ -311,6 +368,48 @@ describe('run-subagent-shared', () => {})).toThrow('subAgent() expected valid JSON output for structured response.');});++ it('[Given] prose followed by JSON in structured mode [Then] it recovers the final JSON payload', () => {+ const result = finalizeInvokeAgentText('Reading file now.\n{"ok":true}', {+ structuredSchema: { type: 'object' },+ zodSchema: {+ safeParse: value => ({ success: true as const, data: value }),+ },+ });++ expect(result).toEqual({+ result: null,+ structuredOutput: { ok: true },+ });+ });++ it('[Given] fenced JSON in structured mode [Then] it parses the fenced payload', () => {+ const result = finalizeInvokeAgentText('```json\n{"ok":true}\n```', {+ structuredSchema: { type: 'object' },+ zodSchema: {+ safeParse: value => ({ success: true as const, data: value }),+ },+ });++ expect(result).toEqual({+ result: null,+ structuredOutput: { ok: true },+ });+ });++ it('[Given] an object containing arrays [Then] it prefers the full object over an inner array', () => {+ const result = finalizeInvokeAgentText('Working...\n{"summary":"done","urgent":["a","b"]}', {+ structuredSchema: { type: 'object' },+ zodSchema: {+ safeParse: value => ({ success: true as const, data: value }),+ },+ });++ expect(result).toEqual({+ result: null,+ structuredOutput: { summary: 'done', urgent: ['a', 'b'] },+ });+ });});describe('inferCliInvocationPrefix', () => {diff --git a/ts/packages/cli/test/src/services/run-subagent-acp.test.ts b/ts/packages/cli/test/src/services/run-subagent-acp.test.tsindex 8092eacf7..5da6b6a09 100644--- a/ts/packages/cli/test/src/services/run-subagent-acp.test.ts+++ b/ts/packages/cli/test/src/services/run-subagent-acp.test.ts@@ -1,5 +1,10 @@import { afterEach, describe, expect, it, vi } from 'vitest';-import { BufferedChunkLogger, resolveAcpAdapterCommand } from 'src/services/run-subagent-acp';+import {+ BufferedChunkLogger,+ createStructuredOutputMcpContext,+ resolveAcpAdapterCommand,+ selectPermissionOutcome,+} from 'src/services/run-subagent-acp';import { AcpInvokeError, isAcpInvokeError } from 'src/services/run-subagent-shared';describe('run-subagent-acp', () => {@@ -61,4 +66,180 @@ describe('run-subagent-acp', () => {text: 'Pick one fruit from the mixed box.',});});++ it('[Given] a read permission request [Then] it allows the read once', () => {+ const result = selectPermissionOutcome(+ {+ options: [+ { optionId: 'allow', kind: 'allow_once', name: 'Allow once' },+ { optionId: 'reject', kind: 'reject_once', name: 'Reject once' },+ ],+ toolCall: {+ toolCallId: 'tool-1',+ kind: 'read',+ title: 'Read File',+ rawInput: {+ file_path: '/tmp/composio/session/artifacts/emails.json',+ },+ },+ } as never,+ ['/tmp/composio/session', '/Users/test/.composio']+ );++ expect(result).toEqual({+ outcome: {+ outcome: 'selected',+ optionId: 'allow',+ },+ });+ });++ it('[Given] a non-read permission request [Then] it allows the request in permissive mode', () => {+ const result = selectPermissionOutcome(+ {+ options: [+ { optionId: 'allow-always', kind: 'allow_always', name: 'Allow always' },+ { optionId: 'allow-once', kind: 'allow_once', name: 'Allow once' },+ { optionId: 'reject', kind: 'reject_once', name: 'Reject once' },+ ],+ toolCall: {+ toolCallId: 'tool-2',+ kind: 'edit',+ title: 'Edit File',+ rawInput: {+ file_path: '/tmp/composio/session/artifacts/emails.json',+ },+ },+ } as never,+ ['/tmp/composio/session', '/Users/test/.composio']+ );++ expect(result).toEqual({+ outcome: {+ outcome: 'selected',+ optionId: 'allow-always',+ },+ });+ });++ it('[Given] a title-only read permission request [Then] it still allows the read once', () => {+ const result = selectPermissionOutcome(+ {+ options: [+ { optionId: 'allow', kind: 'allow_once', name: 'Allow once' },+ { optionId: 'reject', kind: 'reject_once', name: 'Reject once' },+ ],+ toolCall: {+ toolCallId: 'tool-3',+ kind: null,+ title: 'Read File',+ rawInput: {+ file_path: '/Users/test/.composio/tool_definitions/GMAIL_FETCH_EMAILS.json',+ },+ },+ } as never,+ ['/tmp/composio/session', '/Users/test/.composio']+ );++ expect(result).toEqual({+ outcome: {+ outcome: 'selected',+ optionId: 'allow',+ },+ });+ });++ it('[Given] an out-of-scope read request [Then] it still allows the read in permissive mode', () => {+ const result = selectPermissionOutcome(+ {+ options: [+ { optionId: 'allow-always', kind: 'allow_always', name: 'Allow always' },+ { optionId: 'allow', kind: 'allow_once', name: 'Allow once' },+ { optionId: 'reject', kind: 'reject_once', name: 'Reject once' },+ ],+ toolCall: {+ toolCallId: 'tool-4',+ kind: 'read',+ title: 'Read File',+ rawInput: {+ file_path: '/etc/passwd',+ },+ },+ } as never,+ ['/tmp/composio/session', '/Users/test/.composio']+ );++ expect(result).toEqual({+ outcome: {+ outcome: 'selected',+ optionId: 'allow-always',+ },+ });+ });++ it('[Given] a read-only terminal command over an allowed artifact path [Then] it allows the command once', () => {+ const result = selectPermissionOutcome(+ {+ options: [+ { optionId: 'allow', kind: 'allow_once', name: 'Allow once' },+ { optionId: 'reject', kind: 'reject_once', name: 'Reject once' },+ ],+ toolCall: {+ toolCallId: 'tool-5',+ kind: null,+ title:+ "`head -n 100 /tmp/composio/session/artifacts/emails.json | jq '.data' 2>/dev/null || head -n 100 /tmp/composio/session/artifacts/emails.json`",+ rawInput: {},+ },+ } as never,+ ['/tmp/composio/session', '/Users/test/.composio']+ );++ expect(result).toEqual({+ outcome: {+ outcome: 'selected',+ optionId: 'allow',+ },+ });+ });++ it('[Given] a structured schema [Then] it creates a stdio MCP server context for output capture', () => {+ const helperDebugLog = vi.fn();+ const context = createStructuredOutputMcpContext({+ options: {+ structuredSchema: {+ type: 'object',+ properties: {+ summary: { type: 'string' },+ },+ required: ['summary'],+ },+ },+ helperDebugLog,+ });++ expect(context).not.toBeNull();+ expect(context?.mcpServer.command).toBe(process.execPath);+ expect(context?.mcpServer.args).toEqual(+ expect.arrayContaining([+ expect.stringContaining('run-subagent-output-mcp'),+ '--schema-file',+ expect.stringContaining('schema.json'),+ '--result-file',+ expect.stringContaining('result.json'),+ ])+ );+ expect(context?.mcpServer.env).toEqual(+ expect.arrayContaining([{ name: 'BUN_BE_BUN', value: '1' }])+ );+ expect(context?.resultFilePath).toContain('result.json');+ expect(helperDebugLog).toHaveBeenCalledWith(+ 'subAgent.acp.structured_output_tool',+ expect.objectContaining({+ modulePath: expect.stringContaining('run-subagent-output-mcp'),+ })+ );++ context?.cleanup();+ });});diff --git a/ts/packages/cli/tsdown.config.ts b/ts/packages/cli/tsdown.config.tsindex 4b55b45b5..4daf2d5f0 100644--- a/ts/packages/cli/tsdown.config.ts+++ b/ts/packages/cli/tsdown.config.ts@@ -8,6 +8,7 @@ export default defineConfig({'src/services/run-subagent-shared.ts','src/services/run-subagent-acp.ts','src/services/run-subagent-legacy.ts',+ 'src/services/run-subagent-output-mcp.ts',],format: ['esm'],tsconfig: './tsconfig.src.json',