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,
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 = '';
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
}
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> {
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,
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>
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(
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(
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),