1
-import { createRequire } from 'node:module';
2
-import * as acp from '@agentclientprotocol/sdk';
3
-import * as BunServices from '@effect/platform-bun/BunServices';
4
-import {
5
- Cause,
6
- Config,
7
- Data,
8
- Effect,
9
- Exit,
10
- FileSystem,
11
- Layer,
12
- Option,
13
- Path,
14
- Predicate,
15
- Queue,
16
- Stream,
17
-} from 'effect';
18
-import { ChildProcess as Command } from 'effect/unstable/process';
19
-import type { MasterKind } from 'src/services/master-detector';
20
-import { NodeOs } from 'src/services/node-os';
21
-import {
22
- codexAcpBinaryTargetFor,
23
- hasInstalledRunCompanionModules,
24
- resolveRunCompanionAssetPath,
25
- resolveRunCompanionModulePath,
26
- RUN_COMPANION_SHARED_STATIC_ASSET_RELATIVE_PATHS,
27
-} from 'src/services/run-companion-modules';
28
-import {
29
- ACP_STRUCTURED_OUTPUT_TOOL_NAME,
30
- AcpInvokeError,
31
- buildStructuredRepairPrompt,
32
- buildStructuredPrompt,
33
- buildStructuredToolPrompt,
34
- finalizeInvokeAgentText,
35
- toInvokeAgentResponse,
36
- unwrapStructuredOutputToolPayload,
37
- validateStructuredOutput,
38
- type HelperDebugLog,
39
- type InvokeAgentNormalizedOptions,
40
- type InvokeAgentResponse,
41
- type InvokeAgentTarget,
42
-} from 'src/services/run-subagent-shared';
43
-
44
-type LegacySetSessionModelConnection = {
45
- readonly unstable_setSessionModel?: (params: {
46
- readonly sessionId: string;
47
- readonly modelId: string;
48
- }) => Promise<unknown>;
49
-};
50
-
51
-type AcpAdapterCommand = {
52
- readonly cmd: readonly [string, ...ReadonlyArray<string>];
53
- readonly env?: Readonly<Record<string, string>>;
54
- readonly source: 'shipped' | 'bundled' | 'which' | 'npx';
55
-};
56
-
57
-// This module is bundled as a standalone `composio run` companion module, so it
58
-// provides its own platform layers instead of assuming the CLI runtime.
59
-const RunSubAgentAcpLive = Layer.mergeAll(BunServices.layer, NodeOs.Default);
60
-
61
-const getLegacySetSessionModel = (
62
- connection: unknown
63
-): LegacySetSessionModelConnection['unstable_setSessionModel'] => {
64
- if (!Predicate.hasProperty(connection, 'unstable_setSessionModel')) {
65
- return undefined;
66
- }
67
- const method = connection.unstable_setSessionModel;
68
- return Predicate.isFunction(method) ? async params => method.call(connection, params) : undefined;
69
-};
70
-
71
-// Bridges the ACP connection's outgoing ndjson writes into an Effect Queue that
72
-// a forked fiber drains into the child's stdin Sink. A bounded queue keeps the
73
-// child's stdin backpressure visible to the ACP writer, and shutting the queue
74
-// down on close/abort ends the stdin stream (EOF) for the child.
75
-const writableStreamFromQueue = (queue: Queue.Queue<Uint8Array>): WritableStream<Uint8Array> =>
76
- new WritableStream<Uint8Array>({
77
- write: chunk => Effect.runPromise(Effect.asVoid(Queue.offer(queue, chunk))),
78
- close: () => Effect.runPromise(Effect.asVoid(Queue.shutdown(queue))),
79
- abort: () => Effect.runPromise(Effect.asVoid(Queue.shutdown(queue))),
80
- });
81
-
82
-/**
83
- * The ACP adapter assets are the lazy tier of the companion install: `composio
84
- * run` no longer requires them at startup, so this is the first place that can
85
- * observe them missing. When a packaged install has lost them, say so with the
86
- * fix instead of silently falling through to an npx download or a 404 from the
87
- * startup repair path.
88
- */
89
-export class MissingAcpAdapterAssetsError extends Data.TaggedError(
90
- 'services/MissingAcpAdapterAssetsError'
91
-)<{
92
- readonly message: string;
93
- readonly target: InvokeAgentTarget;
94
- readonly missingRelativePaths: ReadonlyArray<string>;
95
- readonly installDirectory: string;
96
-}> {
97
- // The error crosses into the user's script as a rejection, so it reports its
98
- // own name rather than the internal `services/`-prefixed tag.
99
- override readonly name = 'MissingAcpAdapterAssetsError';
100
-}
101
-
102
-type ShippedAdapterAsset = {
103
- /** Absolute path to the adapter shipped with this install, when present. */
104
- readonly resolvedPath: string | null;
105
- /**
106
- * Asset paths a complete install ships for this target on this host, relative
107
- * to the install root. Empty when this platform has no shipped adapter at all
108
- * (no codex-acp binary is built for it), which is not a broken install.
109
- */
110
- readonly expectedRelativePaths: ReadonlyArray<string>;
111
-};
112
-
113
-const resolveShippedAdapterAsset = ({
114
- target,
115
- execPath,
116
-}: {
117
- target: InvokeAgentTarget;
118
- execPath: string;
119
-}): Effect.Effect<ShippedAdapterAsset, never, FileSystem.FileSystem | Path.Path> =>
120
- Effect.gen(function* () {
121
- if (target === 'claude') {
122
- return {
123
- resolvedPath: yield* resolveRunCompanionAssetPath({
124
- callerImportMetaUrl: import.meta.url,
125
- execPath,
126
- relativePathFromRoot: 'acp-adapters/claude-code-acp.mjs',
127
- }),
128
- // cli.js has no separate resolution step: the bundled adapter finds it
129
- // through import.meta.url, so name it as part of the requirement.
130
- expectedRelativePaths: RUN_COMPANION_SHARED_STATIC_ASSET_RELATIVE_PATHS,
131
- };
132
- }
133
-
134
- const binaryTarget = codexAcpBinaryTargetFor({
135
- platform: process.platform,
136
- arch: process.arch,
137
- });
138
- if (!binaryTarget) {
139
- return { resolvedPath: null, expectedRelativePaths: [] };
140
- }
141
-
142
- return {
143
- // Reject a zero-byte placeholder: a foreign-platform slot in the archive
144
- // can never execute, so treat it as absent and fall through.
145
- resolvedPath: yield* resolveRunCompanionAssetPath({
146
- callerImportMetaUrl: import.meta.url,
147
- execPath,
148
- relativePathFromRoot: binaryTarget.relativePath,
149
- requireNonEmpty: true,
150
- }),
151
- expectedRelativePaths: [binaryTarget.relativePath],
152
- };
153
- });
154
-
155
-const missingAcpAdapterAssetsError = ({
156
- target,
157
- installDirectory,
158
- missingRelativePaths,
159
-}: {
160
- target: InvokeAgentTarget;
161
- installDirectory: string;
162
- missingRelativePaths: ReadonlyArray<string>;
163
-}) =>
164
- new MissingAcpAdapterAssetsError({
165
- target,
166
- installDirectory,
167
- missingRelativePaths,
168
- message: [
169
- `This Composio install cannot run a ${target} sub-agent: the ACP adapter files are missing from ${installDirectory}.`,
170
- ...missingRelativePaths.map(relativePath => ` - ${relativePath}`),
171
- `Run 'composio upgrade' to restore them, or reinstall the CLI.`,
172
- ].join('\n'),
173
- });
174
-
175
-const resolveInstalledAdapter = (target: InvokeAgentTarget): string | null => {
176
- const specifier =
177
- target === 'claude'
178
- ? '@zed-industries/claude-code-acp/dist/index.js'
179
- : '@zed-industries/codex-acp/bin/codex-acp.js';
180
- const require = createRequire(import.meta.url);
181
- return Option.getOrNull(Option.liftThrowable(() => require.resolve(specifier))());
182
-};
183
-
184
-export const resolveAcpAdapterCommand = (
185
- target: InvokeAgentTarget,
186
- { execPath = process.execPath }: { readonly execPath?: string } = {}
187
-): Effect.Effect<
188
- AcpAdapterCommand,
189
- MissingAcpAdapterAssetsError,
190
- FileSystem.FileSystem | Path.Path
191
-> =>
192
- Effect.gen(function* () {
193
- const path = yield* Path.Path;
194
- const binary = target === 'claude' ? 'claude-code-acp' : 'codex-acp';
195
- const packageName =
196
- target === 'claude' ? '@zed-industries/claude-code-acp' : '@zed-industries/codex-acp';
197
-
198
- // 1. Prefer shipped companion assets next to the CLI binary / dist bundle.
199
- const shipped = yield* resolveShippedAdapterAsset({ target, execPath });
200
- if (shipped.resolvedPath) {
201
- if (target === 'codex') {
202
- return {
203
- cmd: [shipped.resolvedPath],
204
- source: 'shipped',
205
- } satisfies AcpAdapterCommand;
206
- }
207
-
208
- return {
209
- cmd: [execPath, shipped.resolvedPath],
210
- env: {
211
- BUN_BE_BUN: '1',
212
- },
213
- source: 'shipped',
214
- } satisfies AcpAdapterCommand;
215
- }
216
-
217
- // A packaged install ships both the companion wrappers and the adapters. If
218
- // the wrappers are there and the adapters are not, the install is damaged —
219
- // report the repair instead of quietly downloading an adapter through npx.
220
- // A source checkout has no wrappers next to `bun`, so it keeps falling back.
221
- if (
222
- shipped.expectedRelativePaths.length > 0 &&
223
- (yield* hasInstalledRunCompanionModules(execPath))
224
- ) {
225
- return yield* missingAcpAdapterAssetsError({
226
- target,
227
- installDirectory: path.dirname(execPath),
228
- missingRelativePaths: shipped.expectedRelativePaths,
229
- });
230
- }
231
-
232
- // 2. Try the installed dependency bundle next (no npx overhead).
233
- const bundled = resolveInstalledAdapter(target);
234
- if (bundled) {
235
- return {
236
- cmd: [execPath, bundled],
237
- env: {
238
- BUN_BE_BUN: '1',
239
- },
240
- source: 'bundled',
241
- } satisfies AcpAdapterCommand;
242
- }
243
-
244
- // 3. Check if the binary is on PATH.
245
- if (typeof Bun !== 'undefined' && typeof Bun.which === 'function') {
246
- const resolved = Bun.which(binary);
247
- if (resolved) {
248
- return {
249
- cmd: [resolved],
250
- source: 'which',
251
- } satisfies AcpAdapterCommand;
252
- }
253
- }
254
-
255
- // 4. Fall back to npx.
256
- return {
257
- cmd: [process.platform === 'win32' ? 'npx.cmd' : 'npx', '-y', packageName],
258
- source: 'npx',
259
- } satisfies AcpAdapterCommand;
260
- });
261
-
262
-const chunkFlushPattern = /[\s,.;:!?)\]}"]$/;
263
-const resolveStructuredOutputMcpModulePath = resolveRunCompanionModulePath({
264
- callerImportMetaUrl: import.meta.url,
265
- execPath: process.execPath,
266
- relativeNoExtensionFromCaller: './run-subagent-output-mcp',
267
-});
268
-
269
-const collectToolCallPaths = (
270
- value: unknown,
271
- results: Set<string>,
272
- pathApi: Path.Path,
273
- homedir: string,
274
- parentKey?: string
275
-): void => {
276
- if (typeof value === 'string') {
277
- const key = parentKey?.toLowerCase() ?? '';
278
- if (
279
- key === 'path' ||
280
- key === 'file_path' ||
281
- key === 'directory' ||
282
- key.endsWith('_path') ||
283
- key.endsWith('_directory')
284
- ) {
285
- results.add(value);
286
- } else if (key === 'command' || key === 'cmd') {
287
- for (const candidatePath of extractPathsFromCommandText(value, pathApi, homedir)) {
288
- results.add(candidatePath);
289
- }
290
- }
291
- return;
292
- }
293
-
294
- if (Array.isArray(value)) {
295
- const key = parentKey?.toLowerCase() ?? '';
296
- if (
297
- key === 'paths' ||
298
- key === 'directories' ||
299
- key.endsWith('_paths') ||
300
- key.endsWith('_directories')
301
- ) {
302
- for (const entry of value) {
303
- if (typeof entry === 'string') {
304
- results.add(entry);
305
- }
306
- }
307
- return;
308
- }
309
-
310
- for (const entry of value) {
311
- collectToolCallPaths(entry, results, pathApi, homedir);
312
- }
313
- return;
314
- }
315
-
316
- if (!value || typeof value !== 'object') {
317
- return;
318
- }
319
-
320
- for (const [key, nestedValue] of Object.entries(value)) {
321
- collectToolCallPaths(nestedValue, results, pathApi, homedir, key);
322
- }
323
-};
324
-
325
-const extractPathsFromCommandText = (
326
- command: string,
327
- pathApi: Path.Path,
328
- homedir: string
329
-): ReadonlyArray<string> => {
330
- const results = new Set<string>();
331
- const matches = command.matchAll(/(^|[\s"'`])((?:~\/|\/)[^\s"'`|&;<>]+)/g);
332
- for (const match of matches) {
333
- const rawPath = match[2]?.trim();
334
- if (!rawPath) {
335
- continue;
336
- }
337
-
338
- results.add(rawPath.startsWith('~/') ? pathApi.join(homedir, rawPath.slice(2)) : rawPath);
339
- }
340
-
341
- return [...results];
342
-};
343
-
344
-const extractToolCallPaths = (
345
- toolCall: Pick<acp.RequestPermissionRequest, 'toolCall'>['toolCall'],
346
- pathApi: Path.Path,
347
- homedir: string
348
-): ReadonlyArray<string> => {
349
- const paths = new Set<string>();
350
- for (const location of toolCall.locations ?? []) {
351
- if (typeof location.path === 'string' && location.path.length > 0) {
352
- paths.add(location.path);
353
- }
354
- }
355
-
356
- collectToolCallPaths(toolCall.rawInput, paths, pathApi, homedir);
357
- if (typeof toolCall.title === 'string') {
358
- for (const candidatePath of extractPathsFromCommandText(toolCall.title, pathApi, homedir)) {
359
- paths.add(candidatePath);
360
- }
361
- }
362
- return [...paths];
363
-};
364
-
365
-export const selectPermissionOutcome = (
366
- params: Pick<acp.RequestPermissionRequest, 'options' | 'toolCall'>,
367
- _allowedReadRoots: ReadonlyArray<string> = []
368
-): acp.RequestPermissionResponse => {
369
- const allowOnce =
370
- params.options.find(option => option.kind === 'allow_always') ??
371
- params.options.find(option => option.kind === 'allow_once');
372
- const rejectOption =
373
- params.options.find(option => option.kind === 'reject_once') ??
374
- params.options.find(option => option.kind === 'reject_always');
375
-
376
- // Intentionally permissive for `composio run` experimental_subAgent sessions. The user is
377
- // explicitly opting into local tool access, so prefer broad ACP approval over
378
- // heuristic rejections that strand the agent mid-task.
379
- if (allowOnce) {
380
- return {
381
- outcome: {
382
- outcome: 'selected',
383
- optionId: allowOnce.optionId,
384
- },
385
- };
386
- }
387
-
388
- if (rejectOption) {
389
- return {
390
- outcome: {
391
- outcome: 'selected',
392
- optionId: rejectOption.optionId,
393
- },
394
- };
395
- }
396
-
397
- return {
398
- outcome: {
399
- outcome: 'cancelled',
400
- },
401
- };
402
-};
403
-
404
-export class BufferedChunkLogger {
405
- private buffer = '';
406
-
407
- constructor(
408
- private readonly step: 'subAgent.acp.message' | 'subAgent.acp.thought',
409
- private readonly helperDebugLog: HelperDebugLog
410
- ) {}
411
-
412
- push(text: string): void {
413
- this.buffer += text;
414
- this.flushCompletedLines();
415
- this.flushWhenReadable();
416
- }
417
-
418
- flush(): void {
419
- this.emit(this.buffer);
420
- this.buffer = '';
421
- }
422
-
423
- private flushCompletedLines(): void {
424
- let newlineIndex = this.buffer.indexOf('\n');
425
- while (newlineIndex !== -1) {
426
- const line = this.buffer.slice(0, newlineIndex);
427
- this.emit(line);
428
- this.buffer = this.buffer.slice(newlineIndex + 1);
429
- newlineIndex = this.buffer.indexOf('\n');
430
- }
431
- }
432
-
433
- private flushWhenReadable(): void {
434
- if (this.buffer.length < 48) {
435
- return;
436
- }
437
-
438
- if (!chunkFlushPattern.test(this.buffer)) {
439
- return;
440
- }
441
-
442
- this.emit(this.buffer);
443
- this.buffer = '';
444
- }
445
-
446
- private emit(text: string): void {
447
- const normalized = text.replace(/\s+/g, ' ').trim();
448
- if (!normalized) {
449
- return;
450
- }
451
-
452
- this.helperDebugLog(this.step, {
453
- text: normalized,
454
- });
455
- }
456
-}
457
-
458
-class RunSubAgentClient {
459
- private readonly textChunks: string[] = [];
460
- private readonly messageLogger: BufferedChunkLogger;
461
- private readonly thoughtLogger: BufferedChunkLogger;
462
-
463
- constructor(
464
- private readonly helperDebugLog: HelperDebugLog,
465
- private readonly allowedReadRoots: ReadonlyArray<string>,
466
- private readonly pathApi: Path.Path,
467
- private readonly homedir: string
468
- ) {
469
- this.messageLogger = new BufferedChunkLogger('subAgent.acp.message', helperDebugLog);
470
- this.thoughtLogger = new BufferedChunkLogger('subAgent.acp.thought', helperDebugLog);
471
- }
472
-
473
- async requestPermission(
474
- params: acp.RequestPermissionRequest
475
- ): Promise<acp.RequestPermissionResponse> {
476
- const requestedPaths = extractToolCallPaths(params.toolCall, this.pathApi, this.homedir);
477
- const decision = selectPermissionOutcome(params, this.allowedReadRoots);
478
- this.helperDebugLog('subAgent.acp.permission', {
479
- toolCallId: params.toolCall.toolCallId,
480
- title: params.toolCall.title ?? null,
481
- kind: params.toolCall.kind ?? null,
482
- locations: params.toolCall.locations?.map(location => location.path) ?? [],
483
- requestedPaths,
484
- allowedReadRoots: this.allowedReadRoots,
485
- selectedOptionId: decision.outcome.outcome === 'selected' ? decision.outcome.optionId : null,
486
- options: params.options.map(option => option.kind),
487
- });
488
-
489
- return decision;
490
- }
491
-
492
- async sessionUpdate(params: acp.SessionNotification): Promise<void> {
493
- const update = params.update;
494
- if (update.sessionUpdate === 'agent_message_chunk' && update.content.type === 'text') {
495
- this.textChunks.push(update.content.text);
496
- this.messageLogger.push(update.content.text);
497
- return;
498
- }
499
-
500
- if (update.sessionUpdate === 'agent_thought_chunk' && update.content.type === 'text') {
501
- this.thoughtLogger.push(update.content.text);
502
- return;
503
- }
504
-
505
- if (update.sessionUpdate === 'tool_call') {
506
- this.helperDebugLog('subAgent.acp.tool_call', {
507
- title: update.title,
508
- kind: update.kind ?? null,
509
- status: update.status ?? null,
510
- locations: update.locations?.map(location => location.path) ?? [],
511
- });
512
- return;
513
- }
514
-
515
- if (update.sessionUpdate === 'tool_call_update') {
516
- this.helperDebugLog('subAgent.acp.tool_call_update', {
517
- toolCallId: update.toolCallId,
518
- title: update.title ?? null,
519
- kind: update.kind ?? null,
520
- status: update.status ?? null,
521
- locations: update.locations?.map(location => location.path) ?? [],
522
- rawOutput: update.rawOutput ?? null,
523
- });
524
- return;
525
- }
526
-
527
- if (update.sessionUpdate === 'plan') {
528
- this.helperDebugLog('subAgent.acp.plan', {
529
- entries: update.entries.map(entry => ({
530
- status: entry.status,
531
- priority: entry.priority ?? null,
532
- content: entry.content,
533
- })),
534
- });
535
- return;
536
- }
537
-
538
- this.helperDebugLog('subAgent.acp.update', {
539
- type: update.sessionUpdate,
540
- });
541
- }
542
-
543
- getText(): string {
544
- this.messageLogger.flush();
545
- this.thoughtLogger.flush();
546
- return this.textChunks.join('');
547
- }
548
-}
549
-
550
-const createFallbackError = (
551
- code: ConstructorParameters<typeof AcpInvokeError>[0],
552
- message: string,
553
- cause?: unknown
554
-): AcpInvokeError => new AcpInvokeError(code, message, cause === undefined ? undefined : { cause });
555
-
556
-type StructuredOutputMcpContext = {
557
- readonly mcpServer: acp.McpServerStdio;
558
- readonly resultFilePath: string;
559
- readonly cleanup: Effect.Effect<void>;
560
-};
561
-
562
-export const createStructuredOutputMcpContext = ({
563
- options,
564
- helperDebugLog,
565
-}: {
566
- options: InvokeAgentNormalizedOptions;
567
- helperDebugLog: HelperDebugLog;
568
-}): Effect.Effect<StructuredOutputMcpContext | null, never, FileSystem.FileSystem | Path.Path> =>
569
- Effect.gen(function* () {
570
- const structuredSchema = options.structuredSchema;
571
- if (!structuredSchema) {
572
- return null;
573
- }
574
-
575
- const fs = yield* FileSystem.FileSystem;
576
- const pathApi = yield* Path.Path;
577
- const structuredOutputMcpModulePath = yield* resolveStructuredOutputMcpModulePath;
578
-
579
- const build = Effect.gen(function* () {
580
- // Keep this on an OS temp dir for now. Repointing MCP schema/result files into
581
- // session artifacts needs a broader bundling + run-companion test pass so we
582
- // don't break structured sub-agent output in packaged CLI builds.
583
- const tempDirectory = yield* fs.makeTempDirectory({
584
- prefix: 'composio-subagent-output-mcp-',
585
- });
586
- const removeTempDirectory = Effect.ignore(
587
- fs.remove(tempDirectory, { recursive: true, force: true })
588
- );
589
- const schemaFilePath = pathApi.join(tempDirectory, 'schema.json');
590
- const resultFilePath = pathApi.join(tempDirectory, 'result.json');
591
- yield* Effect.try({
592
- try: () => JSON.stringify(structuredSchema),
593
- catch: error => error,
594
- }).pipe(
595
- Effect.flatMap(schemaJson => fs.writeFileString(schemaFilePath, schemaJson)),
596
- Effect.tapError(() => removeTempDirectory)
597
- );
598
-
599
- helperDebugLog('subAgent.acp.structured_output_tool', {
600
- modulePath: structuredOutputMcpModulePath,
601
- schemaFilePath,
602
- resultFilePath,
603
- });
604
-
605
- const context: StructuredOutputMcpContext = {
606
- mcpServer: {
607
- name: 'composio-structured-output',
608
- command: process.execPath,
609
- args: [
610
- structuredOutputMcpModulePath,
611
- '--schema-file',
612
- schemaFilePath,
613
- '--result-file',
614
- resultFilePath,
615
- ],
616
- env: [
617
- {
618
- name: 'BUN_BE_BUN',
619
- value: '1',
620
- },
621
- ],
622
- },
623
- resultFilePath,
624
- cleanup: removeTempDirectory,
625
- };
626
- return context;
627
- });
628
-
629
- return yield* build.pipe(
630
- Effect.catch(error =>
631
- Effect.sync(() => {
632
- helperDebugLog('subAgent.acp.structured_output_tool_failed', {
633
- error: error instanceof Error ? error.message : String(error),
634
- modulePath: structuredOutputMcpModulePath,
635
- });
636
- return null;
637
- })
638
- )
639
- );
640
- });
641
-
642
-const maybeReadStructuredOutputFromTool = ({
643
- context,
644
- options,
645
- helperDebugLog,
646
-}: {
647
- context: StructuredOutputMcpContext | null;
648
- options: InvokeAgentNormalizedOptions;
649
- helperDebugLog: HelperDebugLog;
650
-}): Effect.Effect<unknown, never, FileSystem.FileSystem> =>
651
- Effect.gen(function* () {
652
- const structuredSchema = options.structuredSchema;
653
- if (!context || !structuredSchema) {
654
- return undefined;
655
- }
656
-
657
- const fs = yield* FileSystem.FileSystem;
658
- const resultFileExists = yield* fs
659
- .exists(context.resultFilePath)
660
- .pipe(Effect.orElseSucceed(() => false));
661
- if (!resultFileExists) {
662
- return undefined;
663
- }
664
-
665
- const read = fs.readFileString(context.resultFilePath).pipe(
666
- Effect.flatMap(rawText =>
667
- Effect.try({
668
- try: () => {
669
- const rawPayload: unknown = JSON.parse(rawText);
670
- const parsed = unwrapStructuredOutputToolPayload(rawPayload, structuredSchema);
671
- helperDebugLog('subAgent.acp.structured_output_tool_result', {
672
- resultFilePath: context.resultFilePath,
673
- });
674
- return validateStructuredOutput(parsed, options);
675
- },
676
- catch: error => error,
677
- })
678
- )
679
- );
680
-
681
- return yield* read.pipe(
682
- Effect.catch(error =>
683
- Effect.sync<unknown>(() => {
684
- helperDebugLog('subAgent.acp.structured_output_tool_result_failed', {
685
- resultFilePath: context.resultFilePath,
686
- error: error instanceof Error ? error.message : String(error),
687
- });
688
- return undefined;
689
- })
690
- )
691
- );
692
- });
693
-
694
-type InvokeAcpSubAgentParams = {
695
- prompt: string;
696
- options: InvokeAgentNormalizedOptions;
697
- master: MasterKind;
698
- target: InvokeAgentTarget;
699
- allowedReadRoots: ReadonlyArray<string>;
700
- helperDebugLog: HelperDebugLog;
701
-};
702
-
703
-// Turns the accumulated agent text into the final response, retrying once with
704
-// a structured-repair prompt when a structured schema was requested and the
705
-// first finalize attempt failed. Non-structured failures propagate unchanged.
706
-const finalizeWithStructuredRepair = ({
707
- client,
708
- options,
709
- master,
710
- target,
711
- structuredOutputMcp,
712
- helperDebugLog,
713
- runPrompt,
714
- stderrSuffix,
715
-}: {
716
- client: RunSubAgentClient;
717
- options: InvokeAgentNormalizedOptions;
718
- master: MasterKind;
719
- target: InvokeAgentTarget;
720
- structuredOutputMcp: StructuredOutputMcpContext | null;
721
- helperDebugLog: HelperDebugLog;
722
- runPrompt: (text: string) => Effect.Effect<acp.PromptResponse, AcpInvokeError>;
723
- stderrSuffix: () => string;
724
-}): Effect.Effect<InvokeAgentResponse, unknown, FileSystem.FileSystem> => {
725
- const finalizeText = Effect.try({
726
- try: () => finalizeInvokeAgentText(client.getText(), options),
727
- catch: error => error,
728
- });
729
-
730
- return finalizeText.pipe(
731
- Effect.map(payload => toInvokeAgentResponse(master, target, payload)),
732
- Effect.catch(error => {
733
- const structuredSchema = options.structuredSchema;
734
- if (!structuredSchema) {
735
- return Effect.fail(error);
736
- }
737
-
738
- return Effect.gen(function* () {
739
- helperDebugLog('subAgent.acp.structured_repair', {
740
- target,
741
- reason: error instanceof Error ? error.message : String(error),
742
- });
743
-
744
- const repairResponse = yield* runPrompt(
745
- buildStructuredRepairPrompt(
746
- structuredSchema,
747
- structuredOutputMcp ? ACP_STRUCTURED_OUTPUT_TOOL_NAME : undefined
748
- )
749
- );
750
-
751
- if (repairResponse.stopReason === 'cancelled') {
752
- return yield* Effect.fail(
753
- createFallbackError(
754
- 'prompt_failed',
755
- `${target} ACP repair prompt was cancelled${stderrSuffix()}`
756
- )
757
- );
758
- }
759
-
760
- const repairedStructuredOutput = yield* maybeReadStructuredOutputFromTool({
761
- context: structuredOutputMcp,
762
- options,
763
- helperDebugLog,
764
- });
765
- if (repairedStructuredOutput !== undefined) {
766
- return toInvokeAgentResponse(master, target, {
767
- result: null,
768
- structuredOutput: repairedStructuredOutput,
769
- });
770
- }
771
-
772
- const payload = yield* finalizeText;
773
- return toInvokeAgentResponse(master, target, payload);
774
- });
775
- })
776
- );
777
-};
778
-
779
-const invokeAcpSubAgentEffect = ({
780
- prompt,
781
- options,
782
- master,
783
- target,
784
- allowedReadRoots,
785
- helperDebugLog,
786
-}: InvokeAcpSubAgentParams) =>
787
- Effect.gen(function* () {
788
- const pathApi = yield* Path.Path;
789
- const nodeOs = yield* NodeOs;
790
-
791
- const structuredOutputMcp = yield* createStructuredOutputMcpContext({
792
- options,
793
- helperDebugLog,
794
- });
795
- yield* Effect.addFinalizer(() =>
796
- structuredOutputMcp ? structuredOutputMcp.cleanup : Effect.void
797
- );
798
-
799
- const resolved = yield* resolveAcpAdapterCommand(target);
800
- helperDebugLog('subAgent.acp.resolve', {
801
- target,
802
- source: resolved.source,
803
- command: resolved.cmd[0],
804
- args: resolved.cmd.slice(1),
805
- });
806
-
807
- // The Claude Code CLI refuses to start when it inherits CLAUDECODE=1. The
808
- // platform Command executor inherits the parent environment, so the
809
- // variable cannot be dropped; mask it with an empty string instead —
810
- // falsy and distinct from the guarded "1" — only when the parent has it set.
811
- const claudeCode = yield* Config.option(Config.String('CLAUDECODE'));
812
- const childEnv: Record<string, string> = {
813
- ...(Option.isSome(claudeCode) ? { CLAUDECODE: '' } : {}),
814
- ...(resolved.env ?? {}),
815
- };
816
-
817
- const stdinQueue = yield* Queue.bounded<Uint8Array>(16);
818
- const [executable, ...commandArgs] = resolved.cmd;
819
- // extendEnv keeps the inherited environment (PATH included) underneath the
820
- // per-child overrides, matching the previous spawn semantics.
821
- const command = Command.make(executable, commandArgs, { env: childEnv, extendEnv: true });
822
-
823
- const child = yield* command.pipe(
824
- Effect.mapError(error =>
825
- createFallbackError('spawn_failed', `Failed to spawn ${target} ACP adapter.`, error)
826
- )
827
- );
828
-
829
- // Teardown parity with the previous finally block: SIGTERM the child, wait
830
- // for it to exit for at most 200ms, then SIGKILL it if it is still alive.
831
- // Registered after the spawn so it runs before the spawner's own
832
- // scope finalizer (which would otherwise await a stubborn child forever).
833
- yield* Effect.addFinalizer(() =>
834
- Effect.gen(function* () {
835
- yield* Effect.interruptible(child.kill({ killSignal: 'SIGTERM' })).pipe(
836
- Effect.timeout('200 millis'),
837
- Effect.ignore
838
- );
839
- const stillRunning = yield* child.isRunning.pipe(Effect.orElseSucceed(() => false));
840
- if (stillRunning) {
841
- yield* Effect.ignore(child.kill({ killSignal: 'SIGKILL' }));
842
- }
843
- })
844
- );
845
-
846
- let stderrText = '';
847
- yield* Stream.runForEach(Stream.decodeText(child.stderr), text =>
848
- Effect.sync(() => {
849
- stderrText += text;
850
- })
851
- ).pipe(Effect.ignore, Effect.forkScoped);
852
- const stderrSuffix = () => (stderrText.trim() ? `: ${stderrText.trim()}` : '');
853
-
854
- yield* Stream.run(Stream.fromQueue(stdinQueue), child.stdin).pipe(
855
- Effect.ignore,
856
- Effect.forkScoped
857
- );
858
-
859
- const client = new RunSubAgentClient(
860
- helperDebugLog,
861
- [...new Set(allowedReadRoots.map(root => pathApi.resolve(root)))],
862
- pathApi,
863
- nodeOs.homedir
864
- );
865
- const stream = acp.ndJsonStream(
866
- writableStreamFromQueue(stdinQueue),
867
- Stream.toReadableStream(child.stdout)
868
- );
869
- const connection = new acp.ClientSideConnection(() => client, stream);
870
-
871
- const initialized = yield* Effect.tryPromise({
872
- try: () =>
873
- connection.initialize({
874
- protocolVersion: acp.PROTOCOL_VERSION,
875
- clientCapabilities: {},
876
- }),
877
- catch: error =>
878
- createFallbackError(
879
- 'initialize_failed',
880
- `${target} ACP initialize failed${stderrSuffix()}`,
881
- error
882
- ),
883
- });
884
-
885
- helperDebugLog('subAgent.acp.initialized', {
886
- target,
887
- protocolVersion: initialized.protocolVersion,
888
- });
889
-
890
- const session = yield* Effect.tryPromise({
891
- try: () =>
892
- connection.newSession({
893
- cwd: process.cwd(),
894
- mcpServers: structuredOutputMcp ? [structuredOutputMcp.mcpServer] : [],
895
- }),
896
- catch: error =>
897
- createFallbackError(
898
- 'session_failed',
899
- `${target} ACP session creation failed${stderrSuffix()}`,
900
- error
901
- ),
902
- });
903
-
904
- helperDebugLog('subAgent.acp.session', {
905
- target,
906
- sessionId: session.sessionId,
907
- });
908
-
909
- if (typeof options.model === 'string' && options.model.trim().length > 0) {
910
- const model = options.model.trim();
911
- const setSessionModel = getLegacySetSessionModel(connection);
912
- const modelFailure =
913
- setSessionModel === undefined
914
- ? 'ACP session model selection is not supported by this connection'
915
- : yield* Effect.tryPromise({
916
- try: () => setSessionModel({ sessionId: session.sessionId, modelId: model }),
917
- catch: error => (error instanceof Error ? error.message : String(error)),
918
- }).pipe(
919
- Effect.match({
920
- onSuccess: (): string | undefined => undefined,
921
- onFailure: message => message,
922
- })
923
- );
924
-
925
- helperDebugLog('subAgent.acp.model', {
926
- target,
927
- model,
928
- ...(modelFailure === undefined
929
- ? { applied: true }
930
- : { applied: false, error: modelFailure }),
931
- });
932
- }
933
-
934
- const promptText =
935
- options.structuredSchema && structuredOutputMcp
936
- ? buildStructuredToolPrompt(
937
- prompt,
938
- options.structuredSchema,
939
- ACP_STRUCTURED_OUTPUT_TOOL_NAME
940
- )
941
- : buildStructuredPrompt(prompt, options.structuredSchema);
942
- const runPrompt = (text: string) =>
943
- Effect.tryPromise({
944
- try: () =>
945
- connection.prompt({
946
- sessionId: session.sessionId,
947
- prompt: [{ type: 'text', text }],
948
- }),
949
- catch: error =>
950
- connection.signal.aborted
951
- ? createFallbackError(
952
- 'connection_closed',
953
- `${target} ACP connection closed before prompt completion${stderrSuffix()}`,
954
- error
955
- )
956
- : createFallbackError(
957
- 'prompt_failed',
958
- `${target} ACP prompt failed${stderrSuffix()}`,
959
- error
960
- ),
961
- });
962
-
963
- const response = yield* runPrompt(promptText);
964
-
965
- if (response.stopReason === 'cancelled') {
966
- return yield* Effect.fail(
967
- createFallbackError('prompt_failed', `${target} ACP prompt was cancelled${stderrSuffix()}`)
968
- );
969
- }
970
-
971
- const structuredOutput = yield* maybeReadStructuredOutputFromTool({
972
- context: structuredOutputMcp,
973
- options,
974
- helperDebugLog,
975
- });
976
- if (structuredOutput !== undefined) {
977
- return toInvokeAgentResponse(master, target, {
978
- result: null,
979
- structuredOutput,
980
- });
981
- }
982
-
983
- return yield* finalizeWithStructuredRepair({
984
- client,
985
- options,
986
- master,
987
- target,
988
- structuredOutputMcp,
989
- helperDebugLog,
990
- runPrompt,
991
- stderrSuffix,
992
- });
993
- });
994
-
995
-export const invokeAcpSubAgent = async (
996
- params: InvokeAcpSubAgentParams
997
-): Promise<InvokeAgentResponse> => {
998
- const exit = await Effect.runPromiseExit(
999
- invokeAcpSubAgentEffect(params).pipe(Effect.scoped, Effect.provide(RunSubAgentAcpLive))
1000
- );
1001
- if (Exit.isSuccess(exit)) {
1002
- return exit.value;
1003
- }
1004
-
1005
- // Surface the original error instance (callers branch on AcpInvokeError and
1006
- // its code), not a FiberFailure wrapper.
1007
- throw Cause.squash(exit.cause);
1008
-};