@jini-ai/daemon 0.2.1 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/README.md +92 -0
  2. package/dist/agent-executor.d.ts +864 -42
  3. package/dist/agent-executor.d.ts.map +1 -1
  4. package/dist/agent-executor.js +1672 -351
  5. package/dist/agent-executor.js.map +1 -1
  6. package/dist/continuation/index.d.ts +1 -0
  7. package/dist/continuation/index.d.ts.map +1 -1
  8. package/dist/continuation/index.js +1 -0
  9. package/dist/continuation/index.js.map +1 -1
  10. package/dist/continuation/run-scoped-context-store.d.ts +79 -0
  11. package/dist/continuation/run-scoped-context-store.d.ts.map +1 -0
  12. package/dist/continuation/run-scoped-context-store.js +56 -0
  13. package/dist/continuation/run-scoped-context-store.js.map +1 -0
  14. package/dist/continuation/run-start-handler.d.ts +39 -9
  15. package/dist/continuation/run-start-handler.d.ts.map +1 -1
  16. package/dist/continuation/run-start-handler.js +12 -2
  17. package/dist/continuation/run-start-handler.js.map +1 -1
  18. package/dist/delegated-tool-bridge.d.ts +8 -0
  19. package/dist/delegated-tool-bridge.d.ts.map +1 -1
  20. package/dist/delegated-tool-bridge.js +117 -1
  21. package/dist/delegated-tool-bridge.js.map +1 -1
  22. package/dist/event-log.d.ts +18 -105
  23. package/dist/event-log.d.ts.map +1 -1
  24. package/dist/event-log.js +0 -17
  25. package/dist/event-log.js.map +1 -1
  26. package/dist/frontend-capability-tools.d.ts +1 -1
  27. package/dist/frontend-capability-tools.js +1 -1
  28. package/dist/frontend-session-registry.d.ts.map +1 -1
  29. package/dist/frontend-session-registry.js +26 -10
  30. package/dist/frontend-session-registry.js.map +1 -1
  31. package/dist/image-prompt-delivery.d.ts +56 -0
  32. package/dist/image-prompt-delivery.d.ts.map +1 -0
  33. package/dist/image-prompt-delivery.js +104 -0
  34. package/dist/image-prompt-delivery.js.map +1 -0
  35. package/dist/index.d.ts +2 -1
  36. package/dist/index.d.ts.map +1 -1
  37. package/dist/index.js +2 -1
  38. package/dist/index.js.map +1 -1
  39. package/dist/remote-tool-bridge.d.ts +45 -0
  40. package/dist/remote-tool-bridge.d.ts.map +1 -0
  41. package/dist/remote-tool-bridge.js +23 -0
  42. package/dist/remote-tool-bridge.js.map +1 -0
  43. package/dist/routines/routine-store.js +1 -1
  44. package/dist/routines/schedule.d.ts +0 -8
  45. package/dist/routines/schedule.d.ts.map +1 -1
  46. package/dist/routines/schedule.js +71 -44
  47. package/dist/routines/schedule.js.map +1 -1
  48. package/dist/routines/scheduler.d.ts +43 -0
  49. package/dist/routines/scheduler.d.ts.map +1 -1
  50. package/dist/routines/scheduler.js +160 -120
  51. package/dist/routines/scheduler.js.map +1 -1
  52. package/dist/run/core/retry.d.ts.map +1 -1
  53. package/dist/run/core/retry.js +47 -35
  54. package/dist/run/core/retry.js.map +1 -1
  55. package/dist/run/diagnostics/diagnostics.d.ts.map +1 -1
  56. package/dist/run/diagnostics/diagnostics.js +149 -91
  57. package/dist/run/diagnostics/diagnostics.js.map +1 -1
  58. package/dist/run-lifecycle.d.ts +84 -4
  59. package/dist/run-lifecycle.d.ts.map +1 -1
  60. package/dist/run-lifecycle.js +378 -116
  61. package/dist/run-lifecycle.js.map +1 -1
  62. package/dist/terminal-session.d.ts +1 -1
  63. package/dist/terminal-session.d.ts.map +1 -1
  64. package/dist/terminal-session.js +1 -1
  65. package/dist/tool-executor.d.ts +26 -6
  66. package/dist/tool-executor.d.ts.map +1 -1
  67. package/dist/tool-executor.js +220 -55
  68. package/dist/tool-executor.js.map +1 -1
  69. package/dist/tool-result-media.d.ts +79 -0
  70. package/dist/tool-result-media.d.ts.map +1 -0
  71. package/dist/tool-result-media.js +80 -0
  72. package/dist/tool-result-media.js.map +1 -0
  73. package/dist/tool-result-surfaces.d.ts +78 -0
  74. package/dist/tool-result-surfaces.d.ts.map +1 -0
  75. package/dist/tool-result-surfaces.js +92 -0
  76. package/dist/tool-result-surfaces.js.map +1 -0
  77. package/package.json +18 -9
@@ -9,7 +9,7 @@
9
9
  * a real `node:child_process` spawn, feeding both `RunLifecycle.emit()` and
10
10
  * this package's own `@jini-ai/protocol` event envelope.
11
11
  *
12
- * ## v1 scope: 23 of 24 registered agent defs
12
+ * ## v1 scope: all 24 registered agent defs
13
13
  *
14
14
  * `@jini-ai/agent-runtime`'s registry ships 24 built-in defs across four
15
15
  * `streamFormat` families. The JSON-stream-parser family — the four
@@ -25,14 +25,14 @@
25
25
  * `mapPiRpcEvent` `send()` call site — no new translation code was needed),
26
26
  * so only the driver wiring (spawn → attach → cancel → finish) was new for it.
27
27
  *
28
- * 4 of the 5 `streamFormat: 'plain'` defs — grok-build, aider, deepseek,
29
- * qwen — are also driven, per
28
+ * All 5 `streamFormat: 'plain'` defs — grok-build, aider, deepseek, qwen,
29
+ * antigravity — are also driven, per
30
30
  * `ADS-memory/reports/proposals/PROP-plain-format-agent-driving-2026-07-21.md`'s
31
- * recommended "Option B": no structured stream parser at all. Every raw
32
- * `child.stdout` chunk is forwarded verbatim as a `text_delta` `'agent'`
33
- * event, live, as it arrives — never buffered until close (see
34
- * `wireChildLifecycle`'s `streamFormat === 'plain'` branch). Prompt delivery
35
- * across the 4 is not uniform: qwen already fit the pre-existing stdin-only
31
+ * recommended "Option B": no structured stream parser at all. By default
32
+ * every raw `child.stdout` chunk is forwarded verbatim as a `text_delta`
33
+ * `'agent'` event, live, as it arrives (see `wireChildLifecycle`'s
34
+ * `streamFormat === 'plain'` branch). Prompt delivery across the 5 is not
35
+ * uniform: qwen and antigravity already fit the pre-existing stdin-only
36
36
  * guard; grok-build stages the prompt to a temp file via
37
37
  * `preparePromptFileForAgent` (its path threaded into `buildArgs` through a
38
38
  * `RuntimeContext`, cleaned up after the child exits on every path,
@@ -41,16 +41,27 @@
41
41
  * Windows CreateProcess command-line-expansion guards
42
42
  * (`checkWindowsCmdShimCommandLineBudget`/`checkWindowsDirectExeCommandLineBudget`).
43
43
  *
44
- * The 5th plain def, **antigravity, is deliberately still rejected.** It
45
- * needs two concerns unrelated to `streamFormat: 'plain'` itself — buffering
46
- * stdout until close so a leaked OAuth URL can be suppressed before it
47
- * reaches the client, and a cross-run lock serializing writes to its shared
48
- * `settings.json` model-selection file that the proposal doc explicitly
49
- * scoped out to its own follow-up (see that doc's §2c/§3). `run()` guards it
50
- * with its own `def.id === 'antigravity'` check, ahead of (and independent
51
- * of) the generic plain-format prompt-delivery/dispatch logic. `run()`
52
- * rejects cleanly (never a bare throw) with an `AgentExecutorError` for any
53
- * def outside the supported 23 see `isSupportedStreamFormat`.
44
+ * ## Antigravity's two extra needs, met declaratively
45
+ *
46
+ * Antigravity was the one def this driver rejected outright, for two reasons
47
+ * the proposal doc (§2c) scoped out to a follow-up: `agy` can print an OAuth
48
+ * sign-in URL to stdout and *still exit 0*, so live streaming leaks it; and
49
+ * its model choice is written into one process-global `settings.json` that
50
+ * `agy` reads on its own startup, so two concurrent runs race on it.
51
+ *
52
+ * Both are now met through **declarative `RuntimeAgentDef` fields this driver
53
+ * reads generically** `needsAgentLogFile`, `stdoutPolicy`, `runtimeLock`
54
+ * not a `def.id === 'antigravity'` branch. That mirrors how all 14 of the
55
+ * def's other optional behavior flags (`promptViaFile`, `authProbe`,
56
+ * `capturesSessionIdFromStream`, …) already work, and it is a deliberate
57
+ * divergence from OD's own `server.ts`, which hardcodes `def.id ===
58
+ * 'antigravity'` twice. The three fields are no-ops for the other 23 defs,
59
+ * none of which declares any of them — so nothing else's behavior changed.
60
+ *
61
+ * `run()` still rejects cleanly (never a bare throw) with an
62
+ * `AgentExecutorError` for any def whose `streamFormat` or prompt-delivery
63
+ * shape this driver does not implement — see `isSupportedStreamFormat` and
64
+ * `assessAgentExecutorCompatibility`.
54
65
  *
55
66
  * ## Invariant
56
67
  *
@@ -72,7 +83,7 @@
72
83
  * deliberately never ported (see `run/core/failure-taxonomy.ts`'s own doc and
73
84
  * `source-map.md`). The real zero-config classifier lives in `@jini-ai/daemon`'s
74
85
  * `run/core/retry.ts` (`resumableFromProcessExit`/`classifyProcessExitFailure`)
75
- * and is wired in by `@jini-ai/node-host`'s `createLocalNodeDaemon` — see that
86
+ * and is wired in by `@jini-ai/server`'s `createLocalNodeDaemon` — see that
76
87
  * package's own source-map.md, and `run/core/retry.ts`'s own doc for the
77
88
  * classification policy and its 2026-07-22 merge-time reconciliation against
78
89
  * a second, independently-built (and rejected) classifier that once lived in
@@ -80,13 +91,16 @@
80
91
  */
81
92
  import { spawn as nodeSpawn } from 'node:child_process';
82
93
  import { promises as fsPromises } from 'node:fs';
94
+ import { homedir, tmpdir } from 'node:os';
83
95
  import { join } from 'node:path';
84
96
  import { redactSecrets } from '@jini-ai/core';
85
- import { applyAgentLaunchEnv, createClaudeStreamHandler, createCopilotStreamHandler, createJsonEventStreamHandler, createQoderStreamHandler, getAgentDef, resolveAgentLaunch, attachAcpSession, attachPiRpcSession, checkPromptArgvBudget, checkWindowsCmdShimCommandLineBudget, checkWindowsDirectExeCommandLineBudget, preparePromptFileForAgent, } from '@jini-ai/agent-runtime';
97
+ import { agentCapabilities, applyAgentLaunchEnv, createClaudeStreamHandler, createCopilotStreamHandler, createJsonEventStreamHandler, createQoderStreamHandler, getAgentDef, resolveAgentLaunch, attachAcpSession, attachPiRpcSession, checkPromptArgvBudget, checkWindowsCmdShimCommandLineBudget, checkWindowsDirectExeCommandLineBudget, prepareAgentLogFile, preparePromptFileForAgent, } from '@jini-ai/agent-runtime';
86
98
  import { collectProcessTreePids, createCommandInvocation, listProcessSnapshots, stopProcesses, } from '@jini-ai/platform';
87
99
  import { classifyRunCloseStatus } from './close-status.js';
88
100
  import { resolveContinuationTransport } from './continuation/continuation-transport.js';
89
101
  import { resultContent } from './delegated-tool-bridge.js';
102
+ import { applyImagePromptDelivery } from './image-prompt-delivery.js';
103
+ import { extractResultMedia } from './tool-result-media.js';
90
104
  const SUPPORTED_STREAM_FORMATS = [
91
105
  'claude-stream-json',
92
106
  'json-event-stream',
@@ -107,6 +121,59 @@ const SUPPORTED_STREAM_FORMATS = [
107
121
  export function isSupportedStreamFormat(value) {
108
122
  return SUPPORTED_STREAM_FORMATS.includes(value);
109
123
  }
124
+ /**
125
+ * The single source of truth for whether this executor can drive a def.
126
+ *
127
+ * It exists because that knowledge was previously reachable only by *calling* `run()` and inspecting
128
+ * the failure. Anything that lists agents for a user to pick from — a discovery route, an agent
129
+ * picker, a CLI healthcheck — needs the same answer *before* a run exists, and had no way to ask it.
130
+ * The observable symptom was a consumer advertising an agent that its own executor then rejected the
131
+ * instant it was selected.
132
+ *
133
+ * `run()` consumes this rather than re-checking the conditions itself, so the discovery-time answer
134
+ * and the run-time guards cannot disagree. A predicate that merely duplicated the guards would be
135
+ * the same bug in a second location.
136
+ *
137
+ * @param def - The def to assess. Must be the **full** `RuntimeAgentDef`, not a projected
138
+ * `DetectedAgent`: that type omits `maxPromptArgBytes`, one of the three prompt-delivery signals
139
+ * checked here, so the argv-bound defs (`aider`, `deepseek`) would be misjudged as unsupported.
140
+ * @returns A discriminated result — see {@link AgentExecutorCompatibility}. The `reason` text is
141
+ * operator-facing and is what `run()` reports as its `AGENT_RUNTIME_UNSUPPORTED` message.
142
+ * @complexity O(1) — fixed field checks.
143
+ * @overallScore 100/100
144
+ */
145
+ export function assessAgentExecutorCompatibility(def) {
146
+ const streamFormat = def.streamFormat;
147
+ if (!isSupportedStreamFormat(streamFormat)) {
148
+ return {
149
+ supported: false,
150
+ reason: `AgentExecutor: agent "${def.id}" has streamFormat "${streamFormat}", which is not implemented in v1 — only ${SUPPORTED_STREAM_FORMATS.join(', ')} are supported`,
151
+ };
152
+ }
153
+ if (streamFormat !== 'acp-json-rpc' &&
154
+ def.promptViaStdin !== true &&
155
+ def.promptViaFile !== true &&
156
+ typeof def.maxPromptArgBytes !== 'number') {
157
+ return {
158
+ supported: false,
159
+ reason: `AgentExecutor: agent "${def.id}" does not deliver its prompt via stdin, a staged prompt file, or a byte-budgeted argv — v1 has no other prompt delivery path`,
160
+ };
161
+ }
162
+ return { supported: true, streamFormat };
163
+ }
164
+ /**
165
+ * Whether `run()` can actually drive this def — the discovery-time counterpart to the guards inside
166
+ * `run()`, so a consumer never offers a user an agent that fails the moment it is selected.
167
+ *
168
+ * @param def - The full `RuntimeAgentDef`; see {@link assessAgentExecutorCompatibility} for why a
169
+ * projected `DetectedAgent` is not sufficient.
170
+ * @returns `true` when this executor would attempt the run.
171
+ * @complexity O(1).
172
+ * @overallScore 100/100
173
+ */
174
+ export function isAgentExecutorSupported(def) {
175
+ return assessAgentExecutorCompatibility(def).supported;
176
+ }
110
177
  /**
111
178
  * Selects and constructs the real stream-parser handler for a supported
112
179
  * `streamFormat`. `json-event-stream` additionally dispatches on
@@ -148,6 +215,27 @@ function asOptionalString(value) {
148
215
  function asOptionalNumber(value) {
149
216
  return typeof value === 'number' ? value : undefined;
150
217
  }
218
+ /**
219
+ * Narrows a parsed `usage` event's `usage` sub-object (`{input_tokens?, output_tokens?}`) — the one
220
+ * piece of {@link translateUsagePayload} with real nested branching (an optional container holding
221
+ * two optional numeric fields), extracted so that function reads as a flat field-by-field mapping.
222
+ * @param rawUsage - `rawEvent.usage` once already narrowed to a record, or `undefined` when absent/malformed.
223
+ * @returns `undefined` when neither token count is present — matching `translateUsagePayload`'s
224
+ * original "omit the whole `usage` field rather than emit an empty object" behavior.
225
+ * @complexity O(1).
226
+ */
227
+ export function extractUsageTokens(rawUsage) {
228
+ if (!rawUsage)
229
+ return undefined;
230
+ const inputTokens = asOptionalNumber(rawUsage.input_tokens);
231
+ const outputTokens = asOptionalNumber(rawUsage.output_tokens);
232
+ if (inputTokens === undefined && outputTokens === undefined)
233
+ return undefined;
234
+ return {
235
+ ...(inputTokens !== undefined ? { input_tokens: inputTokens } : {}),
236
+ ...(outputTokens !== undefined ? { output_tokens: outputTokens } : {}),
237
+ };
238
+ }
151
239
  /**
152
240
  * Narrows one parsed `usage` event's loosely-typed fields into
153
241
  * `RunAgentPayload`'s `usage` variant. The 4 source parsers attach extra
@@ -162,14 +250,7 @@ function asOptionalNumber(value) {
162
250
  */
163
251
  function translateUsagePayload(rawEvent) {
164
252
  const rawUsage = isRecord(rawEvent.usage) ? rawEvent.usage : undefined;
165
- const inputTokens = rawUsage ? asOptionalNumber(rawUsage.input_tokens) : undefined;
166
- const outputTokens = rawUsage ? asOptionalNumber(rawUsage.output_tokens) : undefined;
167
- const usage = inputTokens !== undefined || outputTokens !== undefined
168
- ? {
169
- ...(inputTokens !== undefined ? { input_tokens: inputTokens } : {}),
170
- ...(outputTokens !== undefined ? { output_tokens: outputTokens } : {}),
171
- }
172
- : undefined;
253
+ const usage = extractUsageTokens(rawUsage);
173
254
  const costUsd = asOptionalNumber(rawEvent.costUsd);
174
255
  const durationMs = asOptionalNumber(rawEvent.durationMs);
175
256
  return {
@@ -179,6 +260,108 @@ function translateUsagePayload(rawEvent) {
179
260
  ...(durationMs !== undefined ? { durationMs } : {}),
180
261
  };
181
262
  }
263
+ export function translateStatusEvent(rawEvent) {
264
+ const model = asOptionalString(rawEvent.model);
265
+ const ttftMs = asOptionalNumber(rawEvent.ttftMs);
266
+ const detail = asOptionalString(rawEvent.detail);
267
+ const sessionId = asOptionalString(rawEvent.sessionId);
268
+ return {
269
+ kind: 'agent',
270
+ payload: {
271
+ type: 'status',
272
+ label: asString(rawEvent.label, 'unknown'),
273
+ ...(model !== undefined ? { model } : {}),
274
+ ...(ttftMs !== undefined ? { ttftMs } : {}),
275
+ ...(detail !== undefined ? { detail } : {}),
276
+ },
277
+ ...(sessionId !== undefined ? { sessionId } : {}),
278
+ };
279
+ }
280
+ function translateTextDeltaEvent(rawEvent) {
281
+ return { kind: 'agent', payload: { type: 'text_delta', delta: asString(rawEvent.delta) } };
282
+ }
283
+ function translateThinkingStartEvent() {
284
+ return { kind: 'agent', payload: { type: 'thinking_start' } };
285
+ }
286
+ function translateThinkingDeltaEvent(rawEvent) {
287
+ return { kind: 'agent', payload: { type: 'thinking_delta', delta: asString(rawEvent.delta) } };
288
+ }
289
+ function translateToolUseEvent(rawEvent) {
290
+ return {
291
+ kind: 'agent',
292
+ payload: {
293
+ type: 'tool_use',
294
+ id: asString(rawEvent.id),
295
+ name: asString(rawEvent.name),
296
+ input: rawEvent.input ?? null,
297
+ },
298
+ };
299
+ }
300
+ function translateToolInputDeltaEvent(rawEvent) {
301
+ return {
302
+ kind: 'agent',
303
+ payload: {
304
+ type: 'tool_input_delta',
305
+ id: asString(rawEvent.id),
306
+ name: asString(rawEvent.name),
307
+ delta: asString(rawEvent.delta),
308
+ },
309
+ };
310
+ }
311
+ export function translateToolResultEvent(rawEvent) {
312
+ const isError = typeof rawEvent.isError === 'boolean' ? rawEvent.isError : undefined;
313
+ return {
314
+ kind: 'agent',
315
+ payload: {
316
+ type: 'tool_result',
317
+ toolUseId: asString(rawEvent.toolUseId),
318
+ content: asString(rawEvent.content),
319
+ ...(isError !== undefined ? { isError } : {}),
320
+ },
321
+ };
322
+ }
323
+ function translateUsageEvent(rawEvent) {
324
+ return { kind: 'agent', payload: translateUsagePayload(rawEvent) };
325
+ }
326
+ function translateRawEvent(rawEvent) {
327
+ return { kind: 'agent', payload: { type: 'raw', line: asString(rawEvent.line) } };
328
+ }
329
+ export function translateErrorEvent(rawEvent) {
330
+ const code = asOptionalString(rawEvent.code);
331
+ const message = asString(rawEvent.message, 'Unknown agent error');
332
+ return {
333
+ kind: 'error',
334
+ payload: { message, ...(code !== undefined ? { error: { code, message } } : {}) },
335
+ };
336
+ }
337
+ export function translateTurnEndEvent(rawEvent) {
338
+ // Claude-specific per-turn boundary. Not forwarded as an 'agent'
339
+ // event (no RunAgentPayload variant represents it) — run() reacts to
340
+ // it directly to close stdin (or, for gap 3, decide whether to inject
341
+ // a tool result and keep it open instead). See module doc.
342
+ const stopReason = asOptionalString(rawEvent.stopReason);
343
+ return { kind: 'turn-end', ...(stopReason !== undefined ? { stopReason } : {}) };
344
+ }
345
+ /**
346
+ * One entry per `rawEvent.type` this driver understands, each producing the same
347
+ * {@link AgentRuntimeEventTranslation} `translateAgentRuntimeEvent` used to return from an inline
348
+ * `switch` — replaced with this table (refactor-patterns' preferred fix for a long switch over an
349
+ * event-kind discriminant) so each case's own mapping is independently readable and testable, and so
350
+ * `translateAgentRuntimeEvent` itself is just a lookup plus the two upfront guards.
351
+ */
352
+ const EVENT_TYPE_TRANSLATORS = {
353
+ status: translateStatusEvent,
354
+ text_delta: translateTextDeltaEvent,
355
+ thinking_start: translateThinkingStartEvent,
356
+ thinking_delta: translateThinkingDeltaEvent,
357
+ tool_use: translateToolUseEvent,
358
+ tool_input_delta: translateToolInputDeltaEvent,
359
+ tool_result: translateToolResultEvent,
360
+ usage: translateUsageEvent,
361
+ raw: translateRawEvent,
362
+ error: translateErrorEvent,
363
+ turn_end: translateTurnEndEvent,
364
+ };
182
365
  /**
183
366
  * Narrows one parser-emitted `{type, ...}` record into this engine's
184
367
  * `RunAgentPayload` union (or the `error`/`turn-end`/`ignored` routing
@@ -198,92 +381,15 @@ function translateUsagePayload(rawEvent) {
198
381
  *
199
382
  * @param rawEvent - One event as delivered to a stream parser's `onEvent` callback.
200
383
  * @returns The routing + payload this event maps to.
201
- * @complexity O(1) — one discriminant switch, no iteration.
384
+ * @complexity O(1) — one table lookup, no iteration.
202
385
  * @overallScore 100/100
203
386
  */
204
387
  export function translateAgentRuntimeEvent(rawEvent) {
205
388
  if (!isRecord(rawEvent) || typeof rawEvent.type !== 'string') {
206
389
  return { kind: 'ignored' };
207
390
  }
208
- switch (rawEvent.type) {
209
- case 'status': {
210
- const model = asOptionalString(rawEvent.model);
211
- const ttftMs = asOptionalNumber(rawEvent.ttftMs);
212
- const detail = asOptionalString(rawEvent.detail);
213
- const sessionId = asOptionalString(rawEvent.sessionId);
214
- return {
215
- kind: 'agent',
216
- payload: {
217
- type: 'status',
218
- label: asString(rawEvent.label, 'unknown'),
219
- ...(model !== undefined ? { model } : {}),
220
- ...(ttftMs !== undefined ? { ttftMs } : {}),
221
- ...(detail !== undefined ? { detail } : {}),
222
- },
223
- ...(sessionId !== undefined ? { sessionId } : {}),
224
- };
225
- }
226
- case 'text_delta':
227
- return { kind: 'agent', payload: { type: 'text_delta', delta: asString(rawEvent.delta) } };
228
- case 'thinking_start':
229
- return { kind: 'agent', payload: { type: 'thinking_start' } };
230
- case 'thinking_delta':
231
- return { kind: 'agent', payload: { type: 'thinking_delta', delta: asString(rawEvent.delta) } };
232
- case 'tool_use':
233
- return {
234
- kind: 'agent',
235
- payload: {
236
- type: 'tool_use',
237
- id: asString(rawEvent.id),
238
- name: asString(rawEvent.name),
239
- input: rawEvent.input ?? null,
240
- },
241
- };
242
- case 'tool_input_delta':
243
- return {
244
- kind: 'agent',
245
- payload: {
246
- type: 'tool_input_delta',
247
- id: asString(rawEvent.id),
248
- name: asString(rawEvent.name),
249
- delta: asString(rawEvent.delta),
250
- },
251
- };
252
- case 'tool_result': {
253
- const isError = typeof rawEvent.isError === 'boolean' ? rawEvent.isError : undefined;
254
- return {
255
- kind: 'agent',
256
- payload: {
257
- type: 'tool_result',
258
- toolUseId: asString(rawEvent.toolUseId),
259
- content: asString(rawEvent.content),
260
- ...(isError !== undefined ? { isError } : {}),
261
- },
262
- };
263
- }
264
- case 'usage':
265
- return { kind: 'agent', payload: translateUsagePayload(rawEvent) };
266
- case 'raw':
267
- return { kind: 'agent', payload: { type: 'raw', line: asString(rawEvent.line) } };
268
- case 'error': {
269
- const code = asOptionalString(rawEvent.code);
270
- const message = asString(rawEvent.message, 'Unknown agent error');
271
- return {
272
- kind: 'error',
273
- payload: { message, ...(code !== undefined ? { error: { code, message } } : {}) },
274
- };
275
- }
276
- case 'turn_end': {
277
- // Claude-specific per-turn boundary. Not forwarded as an 'agent'
278
- // event (no RunAgentPayload variant represents it) — run() reacts to
279
- // it directly to close stdin (or, for gap 3, decide whether to inject
280
- // a tool result and keep it open instead). See module doc.
281
- const stopReason = asOptionalString(rawEvent.stopReason);
282
- return { kind: 'turn-end', ...(stopReason !== undefined ? { stopReason } : {}) };
283
- }
284
- default:
285
- return { kind: 'ignored' };
286
- }
391
+ const translator = EVENT_TYPE_TRANSLATORS[rawEvent.type];
392
+ return translator ? translator(rawEvent) : { kind: 'ignored' };
287
393
  }
288
394
  /** Thrown by `AgentExecutor.run()` on every failure path — never a bare `Error`, so callers can branch on `.code` instead of parsing `.message`. */
289
395
  export class AgentExecutorError extends Error {
@@ -324,6 +430,13 @@ function toStringEnvRecord(env) {
324
430
  const BASELINE_AGENT_ENV_KEYS = [
325
431
  'PATH', 'HOME', 'USERPROFILE', 'TMPDIR', 'TEMP', 'TMP', 'SHELL',
326
432
  'LANG', 'LC_ALL', 'LC_CTYPE',
433
+ // `USER` is required for a spawned `claude` CLI to find its own login/credential state — with
434
+ // it omitted (even though `HOME` is present), `claude` fails fast with "Not logged in · Please
435
+ // run /login" despite real credentials existing on disk/keychain. Confirmed by bisection against
436
+ // a real authenticated `claude` install: `BASELINE_AGENT_ENV_KEYS` alone fails, adding back every
437
+ // `CLAUDE_CODE_*`/`CLAUDECODE` var still fails, `LOGNAME`/`SSH_AUTH_SOCK` alone still fail, but
438
+ // `USER` alone flips it to success. See tovu-learnings.md §9 for the full investigation trail.
439
+ 'USER',
327
440
  'SystemRoot', 'windir', 'ComSpec', 'PATHEXT', // Windows-only; harmless no-ops elsewhere
328
441
  ];
329
442
  /**
@@ -380,6 +493,68 @@ function defaultCleanupFailureSink(context) {
380
493
  // eslint-disable-next-line no-console
381
494
  console.error(`[@jini-ai/daemon] agent-executor: process-tree cleanup failed for run "${context.runId}" (${context.phase}, pid=${context.pid})`, redactSecrets(errorMessage(context.error)));
382
495
  }
496
+ /**
497
+ * Reports a contained post-close failure through the host's sink, absorbing a throwing sink.
498
+ *
499
+ * A diagnostic sink is host code too, and the whole point of the two callers below is that nothing
500
+ * between `'close'` and `finish()` can strand the run — a sink that throws must not reintroduce
501
+ * exactly that. Same reasoning `run-lifecycle.ts`'s `handleInactivityTimeout` already applies to its
502
+ * own `onInternalError`.
503
+ */
504
+ function reportPostCloseFailure(onCleanupFailure, context) {
505
+ try {
506
+ onCleanupFailure(context);
507
+ }
508
+ catch {
509
+ // Nothing further can be done from here, and the terminal transition below still must happen.
510
+ }
511
+ }
512
+ /**
513
+ * Removes this run's staged files, reporting rather than propagating a failure.
514
+ *
515
+ * Unguarded, a rejecting cleanup (EBUSY, a temp directory yanked out from under the daemon, a host
516
+ * stager bug) escaped the `void (async () => …)()` wrapper in each close handler and took `finish()`
517
+ * with it: the child was already gone, yet the run stayed `'running'` forever — unfinishable and
518
+ * unresumable — and the rejection surfaced only as an unhandled promise. A leaked temp file is a real
519
+ * problem, but it is strictly smaller than a permanently stranded run, and reporting it keeps it
520
+ * visible.
521
+ */
522
+ async function cleanupStagedFilesSafely(ctx) {
523
+ try {
524
+ await ctx.cleanupStagedFiles();
525
+ }
526
+ catch (error) {
527
+ reportPostCloseFailure(ctx.onCleanupFailure, {
528
+ runId: ctx.runId,
529
+ phase: 'staged-file-cleanup',
530
+ pid: ctx.child.pid,
531
+ error,
532
+ });
533
+ }
534
+ }
535
+ /**
536
+ * Resolves `finish()`'s `resumable` flag from the host's classifier, falling back to `false` when the
537
+ * classifier itself rejects.
538
+ *
539
+ * `classifyFailure` is host-supplied and may do real work (a keystore read, an HTTP call), so it can
540
+ * fail for reasons unrelated to this run. `false` is the right fallback: it is already the answer for
541
+ * every run with no classifier configured at all, so an unavailable classifier degrades to the
542
+ * documented default rather than losing the run.
543
+ */
544
+ async function classifyFailureSafely(ctx, classifyFailure, context) {
545
+ try {
546
+ return await classifyFailure(context);
547
+ }
548
+ catch (error) {
549
+ reportPostCloseFailure(ctx.onCleanupFailure, {
550
+ runId: ctx.runId,
551
+ phase: 'failure-classification',
552
+ pid: ctx.child.pid,
553
+ error,
554
+ });
555
+ return false;
556
+ }
557
+ }
383
558
  /**
384
559
  * Fire-and-forget-safe wrapper around {@link terminateChildTree} for the cancellation paths
385
560
  * (a synchronous `onCancelRequested` listener, an ACP attach-failure catch) that observed this
@@ -425,16 +600,27 @@ function receivedJournalEntry(channel, content) {
425
600
  }
426
601
  const JINI_MCP_SERVER_KEY = 'jini';
427
602
  /**
428
- * Builds this run's `mcpServers.jini` entry — pure, so every field mapping is directly
429
- * assertable without touching the filesystem.
603
+ * Builds this run's `mcpServers.jini` entry — pure and synchronous, so every field mapping is
604
+ * directly assertable without touching the filesystem. The credential arrives already resolved:
605
+ * `McpJsonInjectionOptions.credential` is a possibly-async per-run resolver, and awaiting it is
606
+ * `writeMcpJsonForRun`'s job, which keeps the effect out of this function.
607
+ *
608
+ * @param runId - The run this entry scopes its child to.
609
+ * @param options - `command`/`args`/`daemonUrl` from the host's injection options.
610
+ * @param credential - The already-resolved bearer token, or `undefined` to omit `JINI_DAEMON_TOKEN`
611
+ * entirely. Omitting produces byte-identical output to before this parameter existed.
430
612
  * @complexity O(1).
431
613
  * @overallScore 100/100
432
614
  */
433
- export function buildMcpJsonServerEntry(runId, options) {
615
+ export function buildMcpJsonServerEntry(runId, options, credential) {
434
616
  return {
435
617
  command: options.command,
436
618
  args: options.args !== undefined ? [...options.args] : [],
437
- env: { JINI_RUN_ID: runId, JINI_DAEMON_URL: options.daemonUrl },
619
+ env: {
620
+ JINI_RUN_ID: runId,
621
+ JINI_DAEMON_URL: options.daemonUrl,
622
+ ...(credential !== undefined ? { JINI_DAEMON_TOKEN: credential } : {}),
623
+ },
438
624
  };
439
625
  }
440
626
  /**
@@ -464,43 +650,471 @@ export function mergeMcpJsonContent(existingRaw, serverEntry) {
464
650
  const mcpServers = { ...existingServers, [JINI_MCP_SERVER_KEY]: serverEntry };
465
651
  return `${JSON.stringify({ ...doc, mcpServers }, null, 2)}\n`;
466
652
  }
653
+ /**
654
+ * Mechanism 2 of 5 — `'acp-merge'`. Re-shapes the same bridge entry into the `mcpServers` element
655
+ * an ACP `session/new` call carries, for the 9 ACP-native defs declaring this strategy (amr, devin,
656
+ * hermes, kilo, kimi, kiro, reasonix, trae-cli, vibe). Pure.
657
+ *
658
+ * `env` is emitted as a plain object on purpose: `@jini-ai/agent-runtime`'s
659
+ * `buildAcpSessionNewParams` already normalises a plain-object `env` into either the
660
+ * `[{name, value}]` array form or the `{"KEY": "val"}` map form according to each def's own
661
+ * `acpMcpEnvFormat`, so the per-vendor wire-shape difference stays in the one place that already
662
+ * owns it rather than being re-decided here.
663
+ *
664
+ * **The credential travels in `env`, never in `args`.** An ACP agent spawns this server itself and
665
+ * applies `env` to that child's environment; a token in `args` would land in the child's process
666
+ * arguments, readable by any other local user via `ps`. Same rule as the `.mcp.json` path.
667
+ *
668
+ * @param entry - The shared bridge entry from {@link buildMcpJsonServerEntry}.
669
+ * @returns A single-element list — this driver contributes exactly its own bridge server and never
670
+ * removes or rewrites servers a def or host added by other means.
671
+ * @complexity O(1).
672
+ * @overallScore 100/100
673
+ */
674
+ export function buildAcpMcpBridgeServers(entry) {
675
+ return [
676
+ {
677
+ type: 'stdio',
678
+ name: JINI_MCP_SERVER_KEY,
679
+ command: entry.command,
680
+ args: [...entry.args],
681
+ env: { ...entry.env },
682
+ },
683
+ ];
684
+ }
685
+ /**
686
+ * Mechanism 3+4 of 5 — the spawn-env-content strategies. One map, not two code paths: OpenCode and
687
+ * MiMo consume byte-identical JSON (MiMo's def doc: "the same JSON schema as OpenCode's `mcp`
688
+ * config ... following the same structure as `OPENCODE_CONFIG_CONTENT`"), and differ only in which
689
+ * env var carries it. Adding a third such CLI is a row here, not a new serializer.
690
+ */
691
+ const ENV_CONTENT_VAR_BY_STRATEGY = {
692
+ 'opencode-env-content': 'OPENCODE_CONFIG_CONTENT',
693
+ 'mimo-env-content': 'MIMOCODE_CONFIG_CONTENT',
694
+ };
695
+ /**
696
+ * Serialises the bridge entry into the OpenCode-schema config JSON that `OPENCODE_CONFIG_CONTENT`
697
+ * / `MIMOCODE_CONFIG_CONTENT` carries, merging into whatever the host already put in that variable
698
+ * rather than replacing it — the same "merge, never clobber" discipline
699
+ * {@link mergeMcpJsonContent} applies to `.mcp.json`, and for the same reason: a host may already
700
+ * be handing the CLI the *user's* configured MCP servers through this exact variable, and
701
+ * overwriting it would silently delete them.
702
+ *
703
+ * A missing, empty, or unparseable-as-a-JSON-object existing value degrades to "start from an empty
704
+ * document". Overwriting an unparseable value is deliberate and matches `mergeMcpJsonContent`: this
705
+ * driver did not create it, cannot safely repair it, and must not block the run on it.
706
+ *
707
+ * Emitted per server: `{type: 'local', command: [<command>, ...<args>], environment: {...},
708
+ * enabled: true}` — the shape `@jini-ai/mcp`'s own `buildOpenCodeMcpConfigContent` emits for a
709
+ * stdio server, so both producers stay schema-compatible.
710
+ *
711
+ * **The credential lands in `environment`, i.e. the MCP child's env — never in `command`.** OpenCode
712
+ * spawns the bridge from `command`, so a token placed there would be visible in `ps` output to
713
+ * every other local user. This is the same constraint that keeps `JINI_DAEMON_TOKEN` out of argv on
714
+ * the `.mcp.json` and ACP paths.
715
+ *
716
+ * @param existingRaw - Whatever the spawn env already held for this variable, or `undefined`.
717
+ * @param entry - The shared bridge entry from {@link buildMcpJsonServerEntry}.
718
+ * @returns The full JSON string to set as the env var's value.
719
+ * @complexity O(1) plus `JSON.parse`/`JSON.stringify` over a small config document.
720
+ * @overallScore 100/100
721
+ */
722
+ export function mergeEnvContentMcpConfig(existingRaw, entry) {
723
+ let doc = {};
724
+ if (existingRaw !== undefined && existingRaw.length > 0) {
725
+ try {
726
+ const parsed = JSON.parse(existingRaw);
727
+ if (isRecord(parsed))
728
+ doc = parsed;
729
+ }
730
+ catch {
731
+ doc = {};
732
+ }
733
+ }
734
+ const existingMcp = isRecord(doc.mcp) ? doc.mcp : {};
735
+ const mcp = {
736
+ ...existingMcp,
737
+ [JINI_MCP_SERVER_KEY]: {
738
+ type: 'local',
739
+ command: [entry.command, ...entry.args],
740
+ environment: { ...entry.env },
741
+ enabled: true,
742
+ },
743
+ };
744
+ return JSON.stringify({ ...doc, mcp });
745
+ }
746
+ /**
747
+ * Merges a staged system-prompt overlay file's path into the `instructions` array of the same
748
+ * OpenCode-schema config document {@link mergeEnvContentMcpConfig} writes `mcp` into — for a
749
+ * `systemPromptDelivery: { strategy: 'config-instructions-file' }` def (`opencode` today).
750
+ *
751
+ * Confirmed live (2026-09-01, opencode-cli 1.17.10), not inferred from docs alone:
752
+ * 1. `instructions` is honored — a run configured with it visibly followed the file's directive
753
+ * (a required exact-token prefix), while an identical run without it did not.
754
+ * 2. It appends, never replaces: the same run that followed the custom instruction ALSO still
755
+ * answered correctly using opencode's own baked-in environment-context system prompt (asked
756
+ * for its cwd, with nothing about cwd anywhere in the custom instructions file) — proof
757
+ * opencode's own defaults survive alongside a custom `instructions` entry, not just proof the
758
+ * file was read at all.
759
+ * 3. Adding this key alongside `mcp` in the same `OPENCODE_CONFIG_CONTENT` document disturbs
760
+ * neither: in one combined run, the MCP bridge still got its connection attempt (logged
761
+ * `key=jini type=local`) AND the custom instruction was still followed — same as running each
762
+ * key alone.
763
+ * 4. `instructions` is re-read fresh from the env on every spawn, including a `-s <id>`-resumed
764
+ * turn (proved by swapping in a second instructions file between two turns of one resumed
765
+ * session and seeing the second turn immediately reflect it while still recalling
766
+ * conversation memory from turn one) — so this mechanism is safe to redeliver every turn like
767
+ * `'append-flag'`/`'env-var'`, exempt from the prompt-prefix fallback's create-only gating
768
+ * (see {@link resolveSystemPromptOverlayDelivery}'s doc): nothing here is ever baked into
769
+ * opencode's own persisted session state the way re-injecting fallback prompt text would be.
770
+ *
771
+ * @param existingRaw - Whatever the spawn env already held for this variable (already possibly
772
+ * carrying `mcp`, if `mergeEnvContentMcpConfig` ran first on the same value — order between the two
773
+ * doesn't matter, each only touches its own top-level key), or `undefined`.
774
+ * @param instructionsFilePath - The staged overlay file's absolute path (see
775
+ * {@link prepareSystemPromptOverlayFileIfNeeded}).
776
+ * @returns The full JSON string to set as the env var's value. Appends to, never clobbers, any
777
+ * `instructions` entries already present — the same "merge, never clobber" discipline
778
+ * {@link mergeEnvContentMcpConfig} applies to `mcp`, in case a host is already using this same
779
+ * config-content variable to carry the operator's own instruction files.
780
+ * @complexity O(1) plus `JSON.parse`/`JSON.stringify` over a small config document.
781
+ * @overallScore 100/100
782
+ */
783
+ export function mergeEnvContentInstructions(existingRaw, instructionsFilePath) {
784
+ let doc = {};
785
+ if (existingRaw !== undefined && existingRaw.length > 0) {
786
+ try {
787
+ const parsed = JSON.parse(existingRaw);
788
+ if (isRecord(parsed))
789
+ doc = parsed;
790
+ }
791
+ catch {
792
+ doc = {};
793
+ }
794
+ }
795
+ const existingInstructions = Array.isArray(doc.instructions)
796
+ ? doc.instructions.filter((entry) => typeof entry === 'string')
797
+ : [];
798
+ return JSON.stringify({ ...doc, instructions: [...existingInstructions, instructionsFilePath] });
799
+ }
800
+ /**
801
+ * TOML basic-string escaping for the narrow value shapes {@link buildCodexMcpServerToml} emits (a
802
+ * command name, an argv token, an env var value — never multi-line or control-character-heavy
803
+ * text). Escapes exactly what TOML's basic-string grammar requires: backslash first (so it is not
804
+ * re-escaped by a later replacement), then the quote delimiter, then the three whitespace control
805
+ * characters a real command/argv/env value could plausibly contain.
806
+ *
807
+ * A hand-rolled minimal escaper rather than a TOML dependency — this mechanism never needs to
808
+ * *parse* TOML (the real install's existing `config.toml` is appended after, never rewritten — see
809
+ * {@link buildCodexHomeConfigToml}), so pulling in a full TOML library for one serialization shape
810
+ * would be substantially more surface than the problem needs. Checked against the repo's existing
811
+ * dependency graph first — no package here already depends on a TOML library.
812
+ * @param value - The raw string to embed inside TOML `"..."` delimiters.
813
+ * @returns The escaped text, WITHOUT the surrounding quotes — {@link tomlString} adds those.
814
+ * @complexity O(n) in the string's length.
815
+ */
816
+ function escapeTomlBasicString(value) {
817
+ return value
818
+ .replace(/\\/g, '\\\\')
819
+ .replace(/"/g, '\\"')
820
+ .replace(/\n/g, '\\n')
821
+ .replace(/\r/g, '\\r')
822
+ .replace(/\t/g, '\\t');
823
+ }
824
+ /** Wraps {@link escapeTomlBasicString}'s output in the TOML basic-string delimiters. */
825
+ function tomlString(value) {
826
+ return `"${escapeTomlBasicString(value)}"`;
827
+ }
828
+ /**
829
+ * Mechanism 5 of 5 — `'codex-toml'`'s serialization step. Builds the `[mcp_servers.jini]` TOML
830
+ * table (plus, when the entry carries any env vars, a separate `[mcp_servers.jini.env]` table)
831
+ * Codex's own config schema expects.
832
+ *
833
+ * Confirmed against a real installed Codex CLI (0.151.0), not assumed from docs: round-tripping
834
+ * `codex mcp add <name> --env K=V -- <cmd> <args>` against a scratch `CODEX_HOME` and reading back
835
+ * `config.toml` produced exactly this shape (`command`/`args` as TOML strings/array in the main
836
+ * table, env vars in a nested `.env` table) — see `source-map.md` for the transcript.
837
+ * @param entry - The shared bridge entry from {@link buildMcpJsonServerEntry}.
838
+ * @returns A TOML fragment with no leading/trailing blank-line padding — {@link buildCodexHomeConfigToml} owns spacing when combining it with existing content.
839
+ * @complexity O(n) in the number of argv/env entries.
840
+ * @overallScore 100/100
841
+ */
842
+ export function buildCodexMcpServerToml(entry) {
843
+ const argsLiteral = entry.args.map(tomlString).join(', ');
844
+ const serverTable = `[mcp_servers.${JINI_MCP_SERVER_KEY}]\ncommand = ${tomlString(entry.command)}\nargs = [${argsLiteral}]\n`;
845
+ const envLines = Object.entries(entry.env)
846
+ .filter((pair) => typeof pair[1] === 'string')
847
+ .map(([key, value]) => `${key} = ${tomlString(value)}`);
848
+ if (envLines.length === 0)
849
+ return serverTable;
850
+ return `${serverTable}\n[mcp_servers.${JINI_MCP_SERVER_KEY}.env]\n${envLines.join('\n')}\n`;
851
+ }
852
+ /**
853
+ * Builds the full `config.toml` a run's scratch `CODEX_HOME` gets: the real Codex home's own
854
+ * config, verbatim, with this run's `[mcp_servers.jini]` table appended.
855
+ *
856
+ * **Append-only by design, not a parse-and-merge.** `mergeMcpJsonContent`/`mergeEnvContentMcpConfig`
857
+ * above can safely parse-merge-reserialize because their formats have a JS-native parser
858
+ * (`JSON.parse`); this driver has no TOML parser in its dependency graph (see
859
+ * `buildCodexMcpServerToml`'s doc), and every other setting a real Codex install carries — model
860
+ * choice, sandbox policy, the trusted-project list, the operator's own other MCP servers — must
861
+ * survive a spawn byte-for-byte. Appending preserves all of it; the one failure mode this trades
862
+ * away is a PRE-EXISTING `[mcp_servers.jini]` table in the operator's own config, which would
863
+ * produce a duplicate TOML key Codex rejects at startup. Accepted as vanishingly unlikely — `jini`
864
+ * is this integration's own reserved server name (see {@link JINI_MCP_SERVER_KEY}), never suggested
865
+ * to an operator for their own config — rather than solved with a full TOML parser for one
866
+ * collision case.
867
+ * @param existingRaw - The real Codex home's `config.toml` content, or `undefined` when it does not
868
+ * exist (a fresh Codex install — degrades to "start from just this run's block", matching
869
+ * {@link mergeMcpJsonContent}'s own "missing file" handling).
870
+ * @param entry - The shared bridge entry.
871
+ * @returns The full text to write to the scratch `CODEX_HOME`'s `config.toml`.
872
+ * @complexity O(n) in the existing config's length.
873
+ * @overallScore 100/100
874
+ */
875
+ export function buildCodexHomeConfigToml(existingRaw, entry) {
876
+ const base = existingRaw ?? '';
877
+ const separator = base.length === 0 ? '' : base.endsWith('\n') ? '\n' : '\n\n';
878
+ return `${base}${separator}${buildCodexMcpServerToml(entry)}`;
879
+ }
880
+ /**
881
+ * Where `'codex-toml'` reads the operator's REAL Codex config from, to seed a run's scratch copy —
882
+ * never where it writes. Resolved against the daemon HOST process's own environment (`hostEnv`,
883
+ * `process.env` at the real call site), not a run's sandboxed spawn env: `CODEX_HOME` is not in
884
+ * `BASELINE_AGENT_ENV_KEYS`, so a spawned child never inherits it anyway, and the whole point here
885
+ * is finding wherever the *operator's actual* Codex install lives, which is a host-machine fact.
886
+ * @param hostEnv - The daemon process's own environment.
887
+ * @returns `hostEnv.CODEX_HOME` when set to a non-blank value (matching Codex's own resolution
888
+ * order), else the CLI's documented default, `~/.codex`.
889
+ * @complexity O(1).
890
+ * @overallScore 100/100
891
+ */
892
+ export function resolveSourceCodexHomeDir(hostEnv) {
893
+ const override = hostEnv.CODEX_HOME;
894
+ return override !== undefined && override.trim().length > 0 ? override : join(homedir(), '.codex');
895
+ }
896
+ /**
897
+ * **The single dispatch point from an `externalMcpInjection` strategy to its delivery mechanism.**
898
+ * Pure and synchronous — the one effectful input (the per-run bearer credential) arrives already
899
+ * resolved, so every strategy's mapping is directly assertable without touching the filesystem,
900
+ * the environment, or a keystore.
901
+ *
902
+ * Keyed off the declared *strategy*, never off `def.id`: a def gets a working bridge by declaring a
903
+ * mechanism, not by being named in this file. That is what makes the 9 `'acp-merge'` defs work
904
+ * without any of their own files being touched.
905
+ *
906
+ * @param input.cwd - The run's working directory; only `'claude-mcp-json'` uses it, to place this
907
+ * run's own config file (see {@link mcpJsonPathForRun}) — never `cwd/.mcp.json` itself.
908
+ * @param input.runId - Scopes the bridge child to this run.
909
+ * @param input.strategy - The def's declared `externalMcpInjection`, or `undefined` for a def with no native MCP transport.
910
+ * @param input.options - The host's bridge options, or `undefined` when the host never configured injection.
911
+ * @param input.credential - Already-resolved bearer token, or `undefined` to omit `JINI_DAEMON_TOKEN` entirely.
912
+ * @returns `null` when this run delivers nothing — an unconfigured host, or a def declaring no
913
+ * strategy — which is byte-identical to this feature not existing.
914
+ * @complexity O(1).
915
+ * @overallScore 100/100
916
+ */
917
+ export function buildMcpBridgeDelivery(input) {
918
+ const { cwd, runId, strategy, options, credential } = input;
919
+ if (options === undefined || strategy === undefined)
920
+ return null;
921
+ const serverEntry = buildMcpJsonServerEntry(runId, options, credential);
922
+ switch (strategy) {
923
+ case 'claude-mcp-json':
924
+ return { kind: 'claude-mcp-json', mcpJsonPath: mcpJsonPathForRun(cwd, runId), serverEntry };
925
+ case 'acp-merge':
926
+ return { kind: 'acp-merge', mcpServers: buildAcpMcpBridgeServers(serverEntry) };
927
+ case 'opencode-env-content':
928
+ case 'mimo-env-content':
929
+ return { kind: 'env-content', envVarName: ENV_CONTENT_VAR_BY_STRATEGY[strategy], serverEntry };
930
+ case 'codex-toml':
931
+ return { kind: 'codex-toml', serverEntry };
932
+ case 'env-passthrough':
933
+ return { kind: 'env-passthrough', serverEntry };
934
+ }
935
+ }
467
936
  function defaultReadMcpJsonFile(path) {
468
937
  return fsPromises.readFile(path, 'utf8');
469
938
  }
470
939
  function defaultWriteMcpJsonFile(path, content) {
471
940
  return fsPromises.writeFile(path, content, 'utf8');
472
941
  }
942
+ function defaultRemoveMcpJsonFile(path) {
943
+ return fsPromises.rm(path, { force: true });
944
+ }
945
+ /**
946
+ * This run's own MCP config path, inside `cwd` but deliberately **not** `cwd/.mcp.json`.
947
+ *
948
+ * A shared filename cannot carry two runs' identities at once, and that is exactly what the file
949
+ * carries: `mcpServers.jini.env` holds this run's `JINI_RUN_ID` and its bearer `JINI_DAEMON_TOKEN`.
950
+ * A spawned CLI reads its MCP config when it starts its client, not synchronously at spawn — so with
951
+ * one shared file, a second run in the same directory overwrote the entry the first run's child had
952
+ * not read yet, and that child's `jini-mcp` subprocess then called back carrying the *other* run's id
953
+ * and token: run A's tool calls executing inside run B's authority context. Concurrent runs in one
954
+ * working directory are supported by design (see `McpJsonInjectionOptions.credential`'s doc on why the
955
+ * credential is a per-run resolver at all), so the resolution is one file per run, not a lock that
956
+ * refuses the second run.
957
+ *
958
+ * Naming it after the run also means the project's own `.mcp.json` is never written at all — it stays
959
+ * purely a merge source, so there is no original content to restore afterwards either.
960
+ *
961
+ * The run id is host-supplied and lands in a filename, so everything outside `[A-Za-z0-9_-]` is
962
+ * replaced (dots included — a `..` segment must not survive) and the result is length-capped. Real run
963
+ * ids are UUIDs, which pass through untouched; the cap could in principle collide two ids sharing a
964
+ * 128-character prefix, which no id shape this daemon mints can produce.
965
+ * @complexity O(n) in the run id's length.
966
+ */
967
+ function mcpJsonPathForRun(cwd, runId) {
968
+ const safeRunId = runId.replace(/[^A-Za-z0-9_-]/g, '_').slice(0, 128);
969
+ return join(cwd, `.mcp.jini-${safeRunId}.json`);
970
+ }
473
971
  /**
474
- * Writes (merging, never clobbering — see {@link mergeMcpJsonContent}) `.mcp.json` into `cwd`
475
- * before spawn, so Claude Code's own spawn-time config load (confirmed in `@jini-ai/agent-runtime`'s
476
- * `defs/claude.ts` doc: "Claude Code auto-loads `.mcp.json` from the project cwd at spawn")
477
- * discovers the `jini-mcp` bridge server without this driver needing to pass any CLI flag at all.
478
- * A no-op when `mcpJsonInjection` is `undefined` (opt-in, see `CreateAgentExecutorOptions`'s doc)
479
- * or `def.externalMcpInjection !== 'claude-mcp-json'` (every other injection strategy delivers
480
- * `mcpServers` a different way — see this module's own doc above).
972
+ * The `'claude-mcp-json'` mechanism's one effect: writes (merging, never clobbering — see
973
+ * {@link mergeMcpJsonContent}) this run's own config the project's own servers merged with this
974
+ * run's `jini` bridge entry to the run-scoped path ({@link mcpJsonPathForRun}) the def was already
975
+ * handed via `RuntimeContext.mcpJsonPath`, so the def's own `--strict-mcp-config --mcp-config <path>`
976
+ * argv has a real file to point at by spawn time, instead of auto-discovering `cwd/.mcp.json` (which
977
+ * needs an interactive trust prompt a headless spawn can never answer — confirmed live 2026-07-30,
978
+ * see `@jini-ai/agent-runtime`'s `defs/claude.ts`).
979
+ *
980
+ * Reads `cwd/.mcp.json` and writes `delivery.mcpJsonPath`: the project's file is a merge source only,
981
+ * never a write target. See {@link mcpJsonPathForRun} for why one file per run is load-bearing rather
982
+ * than cosmetic, and why the read and write paths must differ.
983
+ *
984
+ * A no-op for every other delivery mechanism, which is expressed by the caller simply not having a
985
+ * `'claude-mcp-json'` delivery to hand it rather than by a strategy re-check in here.
986
+ * @param cwd - The run's working directory, so the project's own `.mcp.json` can be read as the
987
+ * merge base — not carried on `delivery` itself, since that only describes the write target.
988
+ * @param delivery - The already-built `'claude-mcp-json'` delivery (path + entry). Both fields come
989
+ * from {@link buildMcpBridgeDelivery}, so the credential was resolved exactly once, for this run.
990
+ * @param options - Supplies the injectable `readFile`/`writeFile` seams.
481
991
  * @throws Whatever `writeFile` rejects with — the caller (`run()`) turns that into a pre-spawn
482
992
  * `AGENT_SPAWN_FAILED` failure, matching every other pre-spawn filesystem guard in this file
483
993
  * (`preparePromptFileForAgentFn`'s own try/catch).
484
994
  * @complexity O(1) plus one `readFile`/`writeFile` round trip.
485
995
  * @overallScore 100/100
486
996
  */
487
- async function writeMcpJsonForRun(cwd, runId, def, mcpJsonInjection) {
488
- if (mcpJsonInjection === undefined || def.externalMcpInjection !== 'claude-mcp-json')
489
- return;
490
- const readFileFn = mcpJsonInjection.readFile ?? defaultReadMcpJsonFile;
491
- const writeFileFn = mcpJsonInjection.writeFile ?? defaultWriteMcpJsonFile;
492
- const filePath = join(cwd, '.mcp.json');
997
+ async function writeMcpJsonForRun(cwd, delivery, options) {
998
+ const readFileFn = options.readFile ?? defaultReadMcpJsonFile;
999
+ const writeFileFn = options.writeFile ?? defaultWriteMcpJsonFile;
493
1000
  let existingRaw;
494
1001
  try {
495
- existingRaw = await readFileFn(filePath);
1002
+ existingRaw = await readFileFn(join(cwd, '.mcp.json'));
496
1003
  }
497
1004
  catch {
498
1005
  // No existing file (ENOENT — the common case) or unreadable for any other reason: both
499
1006
  // degrade to "start fresh", matching mergeMcpJsonContent's own doc.
500
1007
  existingRaw = undefined;
501
1008
  }
502
- const serverEntry = buildMcpJsonServerEntry(runId, mcpJsonInjection);
503
- await writeFileFn(filePath, mergeMcpJsonContent(existingRaw, serverEntry));
1009
+ await writeFileFn(delivery.mcpJsonPath, mergeMcpJsonContent(existingRaw, delivery.serverEntry));
1010
+ }
1011
+ function defaultMkdtempCodexHome(prefix) {
1012
+ return fsPromises.mkdtemp(join(tmpdir(), prefix));
1013
+ }
1014
+ function defaultRemoveCodexHomeDir(path) {
1015
+ return fsPromises.rm(path, { recursive: true, force: true });
1016
+ }
1017
+ function resolveCodexHomeSeams(options) {
1018
+ return {
1019
+ mkdtemp: options.mkdtemp ?? defaultMkdtempCodexHome,
1020
+ readFile: options.readFile ?? defaultReadMcpJsonFile,
1021
+ writeFile: options.writeFile ?? defaultWriteMcpJsonFile,
1022
+ removeDir: options.removeDir ?? defaultRemoveCodexHomeDir,
1023
+ };
1024
+ }
1025
+ /**
1026
+ * Mechanism 5 of 5 — `'codex-toml'`'s one effect. Stages a fresh, randomly-named `CODEX_HOME`
1027
+ * directory (see {@link McpJsonInjectionOptions.mkdtemp}'s doc for why non-deterministic naming is
1028
+ * load-bearing here, not cosmetic) carrying:
1029
+ * - `config.toml`: the real Codex home's own config (read best-effort — see
1030
+ * {@link buildCodexHomeConfigToml}'s "missing file" handling) with this run's
1031
+ * `[mcp_servers.jini]` table appended.
1032
+ * - `auth.json`: a best-effort copy of the real Codex home's stored login, so the spawned CLI is
1033
+ * still authenticated. Best-effort is safe here, not merely convenient: a real headless spawn
1034
+ * against a `CODEX_HOME` with no `auth.json` at all was confirmed (against installed Codex CLI
1035
+ * 0.151.0) to fail fast with a structured `401 Unauthorized` stream event, never an interactive
1036
+ * login prompt or a hang — see `defs/codex.ts`'s module doc for the full transcript summary.
1037
+ *
1038
+ * **Never touches the real `CODEX_HOME`.** `sourceCodexHomeDir` is read-only throughout; nothing is
1039
+ * ever written back to it.
1040
+ *
1041
+ * A failure after the directory is created (a rejecting `writeFile`, most plausibly) does not leak
1042
+ * it: the directory may already hold a partial `config.toml` or a copied credential, so the
1043
+ * `catch` below best-effort-removes it before rethrowing, exactly the "partial-failure state leak"
1044
+ * class of bug this package's own adversarial-test-design guidance calls out.
1045
+ * @param runId - Embedded in the temp-dir prefix for traceability, sanitized the same way
1046
+ * `@jini-ai/agent-runtime`'s `prepareAgentLogFile`'s `label` is.
1047
+ * @param entry - The shared bridge entry.
1048
+ * @param sourceCodexHomeDir - Where to read the real install's `config.toml`/`auth.json` from — see {@link resolveSourceCodexHomeDir}.
1049
+ * @param seams - Injectable mkdtemp/readFile/writeFile/removeDir, real filesystem by default.
1050
+ * @throws Whatever `mkdtemp`/`writeFile` rejects with — the caller ({@link prepareCodexHomeIfNeeded}) turns that into a pre-spawn `AGENT_SPAWN_FAILED` failure, matching {@link writeMcpJsonForRun}'s own contract.
1051
+ * @complexity O(1) plus one directory creation and up to two best-effort file read/write round trips.
1052
+ * @overallScore 100/100
1053
+ */
1054
+ async function prepareCodexHomeForRun(runId, entry, sourceCodexHomeDir, seams) {
1055
+ // Stricter than `@jini-ai/agent-runtime`'s `prepareAgentLogFile`/`preparePromptFileForAgent`
1056
+ // labels (which keep dots): this prefix stages a directory that ends up holding a copied Codex
1057
+ // login credential, so it gets `mcpJsonPathForRun`'s tighter discipline instead — dots stripped
1058
+ // too, not just path separators, so a run id like `../../etc/evil` cannot leave even a cosmetic
1059
+ // `..` substring in the mkdtemp prefix.
1060
+ const safeRunId = runId.replace(/[^A-Za-z0-9_-]/g, '-').slice(0, 80) || 'run';
1061
+ const dir = await seams.mkdtemp(`jini-codex-home-${safeRunId}-`);
1062
+ try {
1063
+ let existingConfigRaw;
1064
+ try {
1065
+ existingConfigRaw = await seams.readFile(join(sourceCodexHomeDir, 'config.toml'));
1066
+ }
1067
+ catch {
1068
+ // No config yet (fresh Codex install) or unreadable — start from just this run's block,
1069
+ // matching writeMcpJsonForRun's identical "missing file" handling.
1070
+ existingConfigRaw = undefined;
1071
+ }
1072
+ await seams.writeFile(join(dir, 'config.toml'), buildCodexHomeConfigToml(existingConfigRaw, entry));
1073
+ try {
1074
+ const authRaw = await seams.readFile(join(sourceCodexHomeDir, 'auth.json'));
1075
+ await seams.writeFile(join(dir, 'auth.json'), authRaw);
1076
+ }
1077
+ catch {
1078
+ // No stored login (or unreadable) — the spawned CLI runs unauthenticated. Confirmed above:
1079
+ // this fails the run fast and observably, never as a hang.
1080
+ }
1081
+ }
1082
+ catch (err) {
1083
+ await seams.removeDir(dir).catch(() => {
1084
+ // Best-effort only — the original error below is what the caller must see either way.
1085
+ });
1086
+ throw err;
1087
+ }
1088
+ return {
1089
+ path: dir,
1090
+ cleanup: async () => {
1091
+ await seams.removeDir(dir);
1092
+ },
1093
+ };
1094
+ }
1095
+ /**
1096
+ * Default ceiling on the `'until-close'` stdout accumulator (see `RuntimeStdoutPolicy` in
1097
+ * `@jini-ai/agent-runtime`), in bytes of received UTF-8.
1098
+ *
1099
+ * A buffered def holds its child's entire stdout in one in-memory string until the process closes,
1100
+ * which is exactly what makes the accumulator a denial-of-service surface: the child is a
1101
+ * prompt-influenced agent CLI this driver already treats as potentially adversarial (SEC-001), and
1102
+ * nothing obliges it to ever close or to stop emitting. Without a ceiling one run could exhaust the
1103
+ * daemon's heap and take every unrelated run in the process down with it.
1104
+ *
1105
+ * 8 MiB is chosen to sit far above any real buffered-agent transcript (antigravity's print-mode
1106
+ * output — the only `'until-close'` def — is a few KiB of auth prompt and result text) while staying
1107
+ * small enough that a hostile child cannot meaningfully pressure the heap. A host that genuinely
1108
+ * needs more passes `CreateAgentExecutorOptions.bufferedStdoutMaxBytes`.
1109
+ */
1110
+ export const DEFAULT_BUFFERED_STDOUT_MAX_BYTES = 8 * 1024 * 1024;
1111
+ /**
1112
+ * The host-authored note appended to a truncated flush. Written *after* the def's own `sanitize`
1113
+ * runs, never before: it is this driver's own text, not agent output, and passing it through a
1114
+ * consumer-supplied redactor could silently delete the one line that says output is missing.
1115
+ */
1116
+ function bufferedStdoutTruncationNotice(droppedBytes, maxBytes) {
1117
+ return `\n[jini] agent stdout truncated: ${droppedBytes} byte(s) dropped after the ${maxBytes}-byte buffer limit was reached.\n`;
504
1118
  }
505
1119
  /**
506
1120
  * Wires one spawned child's full observable lifecycle: raw stdout/stderr
@@ -526,14 +1140,35 @@ async function writeMcpJsonForRun(cwd, runId, def, mcpJsonInjection) {
526
1140
  * `streamFormat: 'plain'` gets no `createStreamHandlerForDef` parser at
527
1141
  * all (Option B — see module doc and
528
1142
  * `ADS-memory/reports/proposals/PROP-plain-format-agent-driving-2026-07-21.md`
529
- * §3): every raw stdout chunk is forwarded live, verbatim, as its own
530
- * `text_delta` `'agent'` event, through the same `enqueueEmit` FIFO queue
531
- * every other emit already goes through — no buffering until close, no new
532
- * parser state machine. **Deliberately un-hygiened for v1**: no ANSI/
533
- * terminal-control-sequence stripping is applied (there is no Jini
534
- * equivalent of OD's `TerminalControlSequenceStripper` yet) — a documented
535
- * decision, not an oversight; see `packages/daemon/source-map.md`'s
536
- * 2026-07-21 addition for the reasoning.
1143
+ * §3): every raw stdout chunk is forwarded verbatim as a `text_delta`
1144
+ * `'agent'` event, through the same `enqueueEmit` FIFO queue every other
1145
+ * emit already goes through — no new parser state machine.
1146
+ * **Deliberately un-hygiened for v1**: no ANSI/terminal-control-sequence
1147
+ * stripping is applied (there is no Jini equivalent of OD's
1148
+ * `TerminalControlSequenceStripper` yet) — a documented decision, not an
1149
+ * oversight; see `packages/daemon/source-map.md`'s 2026-07-21 addition for
1150
+ * the reasoning.
1151
+ *
1152
+ * *When* those chunks leave is the def's call, via `def.stdoutPolicy`:
1153
+ *
1154
+ * - `'live'` (the default, and every def but antigravity) — emit per
1155
+ * chunk, as it arrives.
1156
+ * - `'until-close'` — accumulate, and emit the whole thing exactly once
1157
+ * from the `close` handler, after `def.stdoutPolicy.sanitize`. For an
1158
+ * adapter that can print a secret to stdout and still exit 0, no
1159
+ * per-chunk decision is safe: the pattern to redact can straddle two
1160
+ * `'data'` events.
1161
+ *
1162
+ * The buffered path holds back the raw `'stdout'` echo too, not just the
1163
+ * `'agent'`/`text_delta`, and sanitizes both. Emitting an unsanitized raw
1164
+ * echo while withholding the chat copy would leak the exact string the
1165
+ * sanitizer exists to remove to any client subscribed to the run's events —
1166
+ * the raw channel is a different *purpose*, not a different audience.
1167
+ * `journal` is the one thing still recorded per-chunk and verbatim: it is
1168
+ * the host's own byte record, deliberately kept in a **separate** `EventLog`
1169
+ * instance that is never replayed to run-event subscribers (see
1170
+ * `continuation/journal.ts`'s module doc), and "every byte received" is its
1171
+ * whole contract.
537
1172
  *
538
1173
  * @param ctx - Run/def/child/lifecycle plus the cancellation-escalation ports.
539
1174
  * @returns A handle exposing `closeStdinOnce` for the initial prompt write to share.
@@ -559,6 +1194,20 @@ function wireChildLifecycle(ctx) {
559
1194
  // consumed by a turn-end injection decision. See `ContinuationOptions`'s doc for why this is
560
1195
  // only ever acted on when a host has explicitly allowlisted the tool's name.
561
1196
  let pendingToolUse;
1197
+ // `def.stdoutPolicy` read once, up front, so the per-chunk handler below is a single boolean
1198
+ // test rather than a repeated union narrowing. `undefined` (every def but antigravity) means
1199
+ // live — see this function's own doc.
1200
+ const stdoutPolicy = def.stdoutPolicy;
1201
+ const bufferStdoutUntilClose = stdoutPolicy?.buffering === 'until-close';
1202
+ const sanitizeBufferedStdout = stdoutPolicy?.buffering === 'until-close' ? stdoutPolicy.sanitize : undefined;
1203
+ // Accumulator for the `'until-close'` path. Stays `''` for every live def, and the flush below
1204
+ // is then a no-op that emits nothing. Bounded by `ctx.bufferedStdoutMaxBytes` — see
1205
+ // {@link DEFAULT_BUFFERED_STDOUT_MAX_BYTES} for why an unbounded accumulator was a
1206
+ // denial-of-service surface rather than merely untidy.
1207
+ let bufferedStdout = '';
1208
+ let bufferedStdoutBytes = 0;
1209
+ /** Bytes the ceiling refused, reported verbatim on flush so truncation is never silent. */
1210
+ let droppedStdoutBytes = 0;
562
1211
  function enqueueEmit(task) {
563
1212
  emitQueue = emitQueue.then(async () => {
564
1213
  try {
@@ -618,10 +1267,17 @@ function wireChildLifecycle(ctx) {
618
1267
  const run = { id: runId };
619
1268
  let content;
620
1269
  let isError;
1270
+ // Same extraction `delegated-tool-bridge.ts`'s `execute()` runs, kept consistent per
1271
+ // `resultContent`'s own doc ("both callers share one mapping"). This path never ran
1272
+ // `splitToolResultSurfaces` (it has no `mcp-ui` withhold-from-model concept — the flattened
1273
+ // `content` below already carries the whole raw output, a pre-existing, unrelated gap), so
1274
+ // there is no `remainder` to thread back in — only the extracted blocks are used here.
1275
+ let media = [];
621
1276
  try {
622
1277
  const result = await continuation.toolExecutor.execute(continuation.principal, run, toolUse.name, toolUse.input);
623
1278
  content = resultContent(result);
624
1279
  isError = result.status !== 'completed';
1280
+ media = extractResultMedia(result.output).media;
625
1281
  }
626
1282
  catch (error) {
627
1283
  content = errorMessage(error);
@@ -629,7 +1285,13 @@ function wireChildLifecycle(ctx) {
629
1285
  }
630
1286
  await lifecycle.emit(runId, {
631
1287
  event: 'agent',
632
- data: { type: 'tool_result', toolUseId: toolUse.id, content, ...(isError ? { isError: true } : {}) },
1288
+ data: {
1289
+ type: 'tool_result',
1290
+ toolUseId: toolUse.id,
1291
+ content,
1292
+ ...(isError ? { isError: true } : {}),
1293
+ ...(media.length > 0 ? { media } : {}),
1294
+ },
633
1295
  });
634
1296
  injectToolResultLine(toolUse.id, content, isError);
635
1297
  });
@@ -658,21 +1320,65 @@ function wireChildLifecycle(ctx) {
658
1320
  handleTurnEnd(translation.stopReason);
659
1321
  }
660
1322
  });
1323
+ /**
1324
+ * Emits the accumulated `'until-close'` stdout — sanitized — as exactly one raw `'stdout'` echo
1325
+ * plus one `text_delta`, through the same `enqueueEmit` FIFO queue every other emit uses, so the
1326
+ * flush is ordered after every already-queued event and before `finish()`'s `'end'`. A no-op for
1327
+ * every live-streaming def (nothing was ever accumulated) and for a buffered run that produced
1328
+ * no stdout at all — an empty `text_delta` is noise, not information.
1329
+ *
1330
+ * A run whose accumulator hit its ceiling is the one case that still emits when the sanitized text
1331
+ * is empty: "the sanitizer redacted everything" and "we dropped output on the floor" must not look
1332
+ * identical to a client, so the truncation notice is information in its own right.
1333
+ */
1334
+ function flushBufferedStdout() {
1335
+ if (bufferedStdout.length === 0 && droppedStdoutBytes === 0)
1336
+ return;
1337
+ const safe = sanitizeBufferedStdout ? sanitizeBufferedStdout(bufferedStdout) : bufferedStdout;
1338
+ bufferedStdout = '';
1339
+ bufferedStdoutBytes = 0;
1340
+ const text = droppedStdoutBytes > 0
1341
+ ? `${safe}${bufferedStdoutTruncationNotice(droppedStdoutBytes, ctx.bufferedStdoutMaxBytes)}`
1342
+ : safe;
1343
+ droppedStdoutBytes = 0;
1344
+ if (text.length === 0)
1345
+ return;
1346
+ enqueueEmit(() => lifecycle.emit(runId, { event: 'stdout', data: { chunk: text } }));
1347
+ enqueueEmit(() => lifecycle.emit(runId, { event: 'agent', data: { type: 'text_delta', delta: text } }));
1348
+ }
661
1349
  child.stdout?.on('data', (chunk) => {
662
1350
  const text = chunk.toString('utf8');
663
1351
  if (journal)
664
1352
  enqueueEmit(() => journal.record(runId, receivedJournalEntry('stdout', text)));
665
- enqueueEmit(() => lifecycle.emit(runId, { event: 'stdout', data: { chunk: text } }));
666
1353
  if (streamFormat === 'plain') {
667
1354
  if (text.length > 0)
668
1355
  userVisibleOutputSeen = true;
1356
+ if (bufferStdoutUntilClose) {
1357
+ // Nothing is emitted on *either* channel yet — see this function's doc on why holding the
1358
+ // raw echo back matters as much as holding back the chat copy.
1359
+ //
1360
+ // Whole chunks only: a chunk that would cross the ceiling is dropped entirely rather than
1361
+ // sliced to fit, which keeps the accumulator free of half-written multi-byte characters (a
1362
+ // `data` event boundary already need not align with one) and makes the kept prefix exactly
1363
+ // the bytes some prefix of chunks produced. Everything after the first refusal is dropped
1364
+ // too — the point is a hard ceiling on resident bytes, not a best-effort tail.
1365
+ const chunkBytes = Buffer.byteLength(text, 'utf8');
1366
+ if (droppedStdoutBytes > 0 || bufferedStdoutBytes + chunkBytes > ctx.bufferedStdoutMaxBytes) {
1367
+ droppedStdoutBytes += chunkBytes;
1368
+ return;
1369
+ }
1370
+ bufferedStdout += text;
1371
+ bufferedStdoutBytes += chunkBytes;
1372
+ return;
1373
+ }
1374
+ enqueueEmit(() => lifecycle.emit(runId, { event: 'stdout', data: { chunk: text } }));
669
1375
  enqueueEmit(() => lifecycle.emit(runId, { event: 'agent', data: { type: 'text_delta', delta: text } }));
1376
+ return;
670
1377
  }
671
- else {
672
- // Non-null: `streamHandler` is only ever null when `streamFormat === 'plain'` (see its
673
- // construction above), the branch this `else` provably excludes.
674
- streamHandler.feed(text);
675
- }
1378
+ enqueueEmit(() => lifecycle.emit(runId, { event: 'stdout', data: { chunk: text } }));
1379
+ // Non-null: `streamHandler` is only ever null when `streamFormat === 'plain'` (see its
1380
+ // construction above), the branch this statement is provably unreachable from.
1381
+ streamHandler.feed(text);
676
1382
  });
677
1383
  child.stderr?.on('data', (chunk) => {
678
1384
  const text = chunk.toString('utf8');
@@ -705,12 +1411,17 @@ function wireChildLifecycle(ctx) {
705
1411
  // driver dispatches to. `streamHandler` is null for `'plain'` (no
706
1412
  // parser, hence nothing to flush) — `?.` skips it cleanly.
707
1413
  streamHandler?.flush();
1414
+ // Queued before `await emitQueue` so the flushed text is durably appended ahead of
1415
+ // `finish()`'s `'end'` event, exactly like every live-path emit already is.
1416
+ flushBufferedStdout();
708
1417
  await emitQueue;
709
1418
  unsubscribeCancel();
710
- await ctx.cleanupPromptFile();
1419
+ // Both of the next two steps are guarded: neither a failed cleanup nor a rejecting host
1420
+ // classifier may prevent the terminal transition below — see each helper's own doc.
1421
+ await cleanupStagedFilesSafely(ctx);
711
1422
  const status = classifyRunCloseStatus({ cancelRequested, code, signal });
712
1423
  const resumable = status === 'failed' && classifyFailure !== undefined
713
- ? await classifyFailure({
1424
+ ? await classifyFailureSafely(ctx, classifyFailure, {
714
1425
  runId,
715
1426
  agentId: def.id,
716
1427
  code,
@@ -761,6 +1472,28 @@ function translateAcpError(payload) {
761
1472
  : {}),
762
1473
  };
763
1474
  }
1475
+ /**
1476
+ * Applies one already-translated `'agent'`-kind event's side-effect signals — a captured session id
1477
+ * (gap 5), and the `toolCallSeen`/`userVisibleOutputSeen` pair every `wire*Lifecycle` driver tracks
1478
+ * for `FailureClassificationContext.sideEffects` — through `sink`. Extracted from `wireAcpLifecycle`'s
1479
+ * `send()`, where this exact three-level-deep nesting (session-id check, then tool_use/else-if
1480
+ * delta-length check) was that function's largest single cognitive-complexity contributor. Pure
1481
+ * except for calling the injected `sink` callbacks.
1482
+ * @param payload - The translated event's `RunAgentPayload`.
1483
+ * @param sessionId - The translation's optional captured session id, or `undefined`.
1484
+ * @param sink - The driver-specific effects to apply.
1485
+ * @complexity O(1).
1486
+ */
1487
+ export function applyAgentTranslationSideEffects(payload, sessionId, sink) {
1488
+ if (sessionId !== undefined)
1489
+ sink.onSessionId(sessionId);
1490
+ if (payload.type === 'tool_use') {
1491
+ sink.onToolCall();
1492
+ }
1493
+ else if ((payload.type === 'text_delta' || payload.type === 'thinking_delta') && payload.delta.length > 0) {
1494
+ sink.onUserVisibleOutput();
1495
+ }
1496
+ }
764
1497
  /**
765
1498
  * Wires an ACP child to a run. Unlike the JSON-stream path, ACP owns the
766
1499
  * prompt protocol and reports its parsed events through `attachAcpSession`'s
@@ -814,10 +1547,11 @@ function wireAcpLifecycle(ctx) {
814
1547
  void (async () => {
815
1548
  await emitQueue;
816
1549
  unsubscribeCancel();
817
- await ctx.cleanupPromptFile();
1550
+ // Guarded for the same reasons as the child-driven handler above.
1551
+ await cleanupStagedFilesSafely(ctx);
818
1552
  const status = cancelRequested ? 'cancelled' : controller?.completedSuccessfully() ? 'succeeded' : 'failed';
819
1553
  const resumable = status === 'failed' && classifyFailure !== undefined
820
- ? await classifyFailure({
1554
+ ? await classifyFailureSafely(ctx, classifyFailure, {
821
1555
  runId,
822
1556
  agentId,
823
1557
  code,
@@ -842,20 +1576,20 @@ function wireAcpLifecycle(ctx) {
842
1576
  ...(ctx.model !== undefined ? { model: ctx.model } : {}),
843
1577
  ...(ctx.imagePaths.length > 0 ? { imagePaths: [...ctx.imagePaths] } : {}),
844
1578
  ...(ctx.envFormat !== undefined ? { envFormat: ctx.envFormat } : {}),
1579
+ // Spread-when-present rather than always: passing `mcpServers: []` is not the same as passing
1580
+ // nothing for every downstream ACP agent, and "no bridge configured" must stay byte-identical
1581
+ // to before this field existed.
1582
+ ...(ctx.mcpServers !== undefined && ctx.mcpServers.length > 0 ? { mcpServers: [...ctx.mcpServers] } : {}),
845
1583
  ...(ctx.onPermissionRequest !== undefined ? { onPermissionRequest: ctx.onPermissionRequest } : {}),
846
1584
  send(event, payload) {
847
1585
  if (event === 'agent') {
848
1586
  const translation = translateAgentRuntimeEvent(payload);
849
1587
  if (translation.kind === 'agent') {
850
- if (translation.sessionId !== undefined)
851
- capturedSessionId = translation.sessionId;
852
- if (translation.payload.type === 'tool_use') {
853
- toolCallSeen = true;
854
- }
855
- else if ((translation.payload.type === 'text_delta' || translation.payload.type === 'thinking_delta') &&
856
- translation.payload.delta.length > 0) {
857
- userVisibleOutputSeen = true;
858
- }
1588
+ applyAgentTranslationSideEffects(translation.payload, translation.sessionId, {
1589
+ onSessionId: (sessionId) => { capturedSessionId = sessionId; },
1590
+ onToolCall: () => { toolCallSeen = true; },
1591
+ onUserVisibleOutput: () => { userVisibleOutputSeen = true; },
1592
+ });
859
1593
  enqueueEmit(() => lifecycle.emit(runId, { event: 'agent', data: translation.payload }));
860
1594
  }
861
1595
  else if (translation.kind === 'error') {
@@ -933,10 +1667,11 @@ function wirePiRpcLifecycle(ctx) {
933
1667
  void (async () => {
934
1668
  await emitQueue;
935
1669
  unsubscribeCancel();
936
- await ctx.cleanupPromptFile();
1670
+ // Guarded for the same reasons as the child-driven handler above.
1671
+ await cleanupStagedFilesSafely(ctx);
937
1672
  const status = cancelRequested ? 'cancelled' : session?.hasFatalError() ? 'failed' : 'succeeded';
938
1673
  const resumable = status === 'failed' && classifyFailure !== undefined
939
- ? await classifyFailure({
1674
+ ? await classifyFailureSafely(ctx, classifyFailure, {
940
1675
  runId,
941
1676
  agentId,
942
1677
  code,
@@ -1015,38 +1750,575 @@ function writePromptToStdin(def, child, prompt, handle) {
1015
1750
  handle.closeStdinOnce();
1016
1751
  }
1017
1752
  /**
1018
- * Creates the `AgentExecutor` reference implementation: an in-process
1019
- * `RunLifecycle` driver over real (by default) `@jini-ai/agent-runtime`
1020
- * registry lookup, launch resolution, and stream parsing, plus a real
1021
- * `node:child_process.spawn`. Every collaborator is an injectable seam
1022
- * (matching this package's established convention see
1023
- * `tool-executor.ts`/`run-lifecycle.ts`) so tests can drive a fake child
1024
- * process and a fake registry without touching the filesystem or spawning
1025
- * a real subprocess.
1753
+ * Resolves `CreateAgentExecutorOptions`' agent-runtime collaborator seams (registry lookup, launch
1754
+ * resolution, ACP/pi-rpc session attachment, prompt/log file staging) to their real
1755
+ * `@jini-ai/agent-runtime` defaults. Split out of `createAgentExecutor` together with
1756
+ * {@link resolveProcessDeps}/{@link resolveMiscExecutorDeps}: a flat 14-line `options.x ?? default`
1757
+ * sequence was that function's entire cyclomatic-complexity excess (one branch point per default)
1758
+ * grouping the same defaults by concern keeps each resulting function's own complexity low without
1759
+ * hiding which options belong together. Pure.
1760
+ */
1761
+ function resolveAgentRuntimeDeps(options) {
1762
+ return {
1763
+ getAgentDef: options.getAgentDef ?? getAgentDef,
1764
+ resolveAgentLaunch: options.resolveAgentLaunch ?? resolveAgentLaunch,
1765
+ applyAgentLaunchEnv: options.applyAgentLaunchEnv ?? applyAgentLaunchEnv,
1766
+ attachAcpSession: options.attachAcpSession ?? attachAcpSession,
1767
+ attachPiRpcSession: options.attachPiRpcSession ?? attachPiRpcSession,
1768
+ preparePromptFileForAgent: options.preparePromptFileForAgent ?? preparePromptFileForAgent,
1769
+ prepareAgentLogFile: options.prepareAgentLogFile ?? prepareAgentLogFile,
1770
+ };
1771
+ }
1772
+ /** Resolves the OS-process-facing collaborator seams — see {@link resolveAgentRuntimeDeps}'s doc. Pure. */
1773
+ function resolveProcessDeps(options) {
1774
+ return {
1775
+ createCommandInvocation: options.createCommandInvocation ?? createCommandInvocation,
1776
+ spawn: options.spawn ?? nodeSpawn,
1777
+ listProcessSnapshots: options.listProcessSnapshots ?? listProcessSnapshots,
1778
+ collectProcessTreePids: options.collectProcessTreePids ?? collectProcessTreePids,
1779
+ stopProcesses: options.stopProcesses ?? stopProcesses,
1780
+ };
1781
+ }
1782
+ /** Resolves the two remaining defaultable options — see {@link resolveAgentRuntimeDeps}'s doc. Pure. */
1783
+ function resolveMiscExecutorDeps(options) {
1784
+ return {
1785
+ onCleanupFailure: options.onCleanupFailure ?? defaultCleanupFailureSink,
1786
+ bufferedStdoutMaxBytes: options.bufferedStdoutMaxBytes ?? DEFAULT_BUFFERED_STDOUT_MAX_BYTES,
1787
+ };
1788
+ }
1789
+ /** Phase 1: registry lookup + `assessAgentExecutorCompatibility` guard. */
1790
+ export async function resolveDefAndStreamFormat(input, deps) {
1791
+ const def = deps.getAgentDef(input.agentId);
1792
+ if (!def) {
1793
+ return deps.failBeforeSpawn(input.runId, 'AGENT_NOT_FOUND', `AgentExecutor: unknown agentId "${input.agentId}"`);
1794
+ }
1795
+ const compatibility = assessAgentExecutorCompatibility(def);
1796
+ if (!compatibility.supported) {
1797
+ return deps.failBeforeSpawn(input.runId, 'AGENT_RUNTIME_UNSUPPORTED', compatibility.reason);
1798
+ }
1799
+ return { def, streamFormat: compatibility.streamFormat };
1800
+ }
1801
+ /** Phase 2: image-prompt-delivery augmentation + argv-budget guard for argv-bound defs. */
1802
+ export async function resolveImageDeliveryAndArgvBudget(input, deps) {
1803
+ const imageDelivery = applyImagePromptDelivery(input.def.imageDelivery, input.prompt, input.imagePaths, input.extraAllowedDirs);
1804
+ const argvBudgetError = checkPromptArgvBudget(input.def, imageDelivery.prompt);
1805
+ if (argvBudgetError) {
1806
+ return deps.failBeforeSpawn(input.runId, 'AGENT_PROMPT_TOO_LARGE', argvBudgetError.message);
1807
+ }
1808
+ return imageDelivery;
1809
+ }
1810
+ /**
1811
+ * Phase 3a: the subprocess environment this run's launch resolution and spawn should use — the
1812
+ * caller-supplied escape hatch verbatim, or the deny-by-default `BASELINE_AGENT_ENV_KEYS` allowlist.
1813
+ * Pure.
1814
+ */
1815
+ export function resolveRunEnv(input, hostEnv) {
1816
+ return input.env !== undefined ? toStringEnvRecord(input.env) : buildAgentEnv(hostEnv, input.credentialEnv);
1817
+ }
1818
+ /** Phase 3b: launch-path resolution + binary-not-resolved guard. */
1819
+ export async function resolveLaunch(input, deps) {
1820
+ const launch = deps.resolveAgentLaunch(input.def, input.resolvedEnv);
1821
+ if (!launch.launchPath) {
1822
+ return deps.failBeforeSpawn(input.runId, 'AGENT_BINARY_NOT_RESOLVED', `AgentExecutor: could not resolve an executable for agent "${input.def.id}" (bin "${input.def.bin}")`);
1823
+ }
1824
+ // Narrowed by the guard above; `resolveAgentLaunch`'s own return type still declares
1825
+ // `launchPath: string | null` since it can't know this call site already checked.
1826
+ return launch;
1827
+ }
1828
+ /** Phase 4a: stage a `promptViaFile` def's prompt to a temp file (a no-op for every other def). */
1829
+ export async function stagePromptFile(input, deps) {
1830
+ try {
1831
+ return await deps.preparePromptFileForAgent(input.def, input.prompt, input.runId);
1832
+ }
1833
+ catch (err) {
1834
+ return deps.failBeforeSpawn(input.runId, 'AGENT_SPAWN_FAILED', `AgentExecutor: could not stage a prompt file for agent "${input.def.id}": ${errorMessage(err)}`);
1835
+ }
1836
+ }
1837
+ /** Phase 4b: stage a `needsAgentLogFile` def's diagnostic-log path (a no-op for every other def). */
1838
+ export async function stageLogFile(input, deps) {
1839
+ try {
1840
+ return await deps.prepareAgentLogFile(input.def, input.runId);
1841
+ }
1842
+ catch (err) {
1843
+ await (input.preparedPromptFile ? input.preparedPromptFile.cleanup() : Promise.resolve());
1844
+ return deps.failBeforeSpawn(input.runId, 'AGENT_SPAWN_FAILED', `AgentExecutor: could not stage a log file for agent "${input.def.id}": ${errorMessage(err)}`);
1845
+ }
1846
+ }
1847
+ /** Phase 5: resolves this run's MCP bridge delivery (credential resolution + {@link buildMcpBridgeDelivery}). */
1848
+ export async function resolveMcpBridgeForRun(input, deps) {
1849
+ try {
1850
+ // Awaited here rather than inside `buildMcpBridgeDelivery` so that function stays pure and
1851
+ // synchronous. `undefined` when the host supplied no resolver, which omits the token entirely.
1852
+ const credential = deps.mcpJsonInjection !== undefined ? await deps.mcpJsonInjection.credential?.(input.runId) : undefined;
1853
+ return buildMcpBridgeDelivery({
1854
+ cwd: input.cwd,
1855
+ runId: input.runId,
1856
+ strategy: input.def.externalMcpInjection,
1857
+ options: deps.mcpJsonInjection,
1858
+ credential,
1859
+ });
1860
+ }
1861
+ catch (err) {
1862
+ // Spawning a child that cannot authenticate would produce a run whose every bridged tool call
1863
+ // 401s, so a rejecting credential resolver fails the run before spawn instead.
1864
+ await deps.cleanupStagedFiles();
1865
+ return deps.failBeforeSpawn(input.runId, 'AGENT_SPAWN_FAILED', `AgentExecutor: could not resolve the MCP bridge credential for agent "${input.def.id}": ${errorMessage(err)}`);
1866
+ }
1867
+ }
1868
+ /**
1869
+ * Phase 6a/10c: the subprocess environment every env-riding mechanism uses — mechanism 3+4
1870
+ * (`'opencode-env-content'`/`'mimo-env-content'`, merged into whatever the host already set there,
1871
+ * never a CLI argument: the config embeds `JINI_DAEMON_TOKEN`, and process arguments are readable
1872
+ * by any other local user through `ps`), mechanism 5 (`'codex-toml'`, `CODEX_HOME` relocation),
1873
+ * mechanism 6 (`'env-passthrough'`, the bridge entry's flat env vars set directly with no carrier
1874
+ * document — see {@link McpBridgeDelivery}'s own doc), a
1875
+ * `systemPromptDelivery: 'env-var'` def's overlay (`reasonix`'s `REASONIX_ACP_SYSTEM_APPEND` today
1876
+ * — see `resolveSystemPromptOverlayDelivery`'s own doc), and a `'config-instructions-file'` def's
1877
+ * staged overlay file (`opencode` today — see {@link mergeEnvContentInstructions}'s own doc). Pure
1878
+ * — `codexHomeDir` and `stagedInstructionsFile` arrive already staged by
1879
+ * {@link prepareCodexHomeIfNeeded} and {@link prepareSystemPromptOverlayFileIfNeeded} respectively,
1880
+ * the only parts of this mechanism that are NOT pure (real `mkdtemp`/`writeFile` calls).
1881
+ * @param spawnEnv - The env every other spawn-time step (launch-path resolution, `applyAgentLaunchEnv`) already computed.
1882
+ * @param mcpBridge - This run's resolved bridge delivery, or `null` for an unconfigured host / no-strategy def.
1883
+ * @param codexHomeDir - The staged scratch `CODEX_HOME` path for a `'codex-toml'` def, or `undefined` for every other run (including a `'codex-toml'` def when `mcpJsonInjection` was never configured — see `prepareCodexHomeIfNeeded`'s own gate).
1884
+ * @param systemPromptEnvOverrides - `resolveSystemPromptOverlayDelivery`'s `envOverrides` — `{}` (default) for every def but an `'env-var'`-strategy one with an overlay present, in which case it carries that one var. Applied after `codexHomeDir`, so it can never be shadowed by it — the two never share a key (`CODEX_HOME` vs. e.g. `REASONIX_ACP_SYSTEM_APPEND`), so the ordering is a documentation choice, not a correctness one.
1885
+ * @param stagedInstructionsFile - `varName` (from the def's own `systemPromptDelivery` declaration) and the staged overlay file's `path`, or `undefined` for every def but a `'config-instructions-file'` one with an overlay present. Merged into `varName`'s value AFTER the `mcp` merge above (reading `envContentApplied`, not the original `spawnEnv`, for that same key) so both a `mcp` entry and an `instructions` entry from the two mechanisms survive together in one document — confirmed live this coexistence is safe (see {@link mergeEnvContentInstructions}'s doc).
1886
+ * @complexity O(1) plus `mergeEnvContentMcpConfig`'s and `mergeEnvContentInstructions`'s own `JSON.parse`/`JSON.stringify` cost.
1887
+ * @overallScore 100/100
1888
+ */
1889
+ export function computeChildEnv(spawnEnv, mcpBridge, codexHomeDir, systemPromptEnvOverrides, stagedInstructionsFile) {
1890
+ const envContentApplied = mcpBridge?.kind === 'env-content'
1891
+ ? {
1892
+ ...spawnEnv,
1893
+ [mcpBridge.envVarName]: mergeEnvContentMcpConfig(spawnEnv[mcpBridge.envVarName], mcpBridge.serverEntry),
1894
+ }
1895
+ : spawnEnv;
1896
+ // `'env-passthrough'` (antigravity): no document, no named carrier variable — the bridge
1897
+ // entry's own `env` keys (`JINI_RUN_ID`/`JINI_DAEMON_URL`/`JINI_DAEMON_TOKEN`) are set directly
1898
+ // on the child's environment, for the spawned CLI to inherit down to its own globally
1899
+ // pre-registered MCP child in turn. See `McpBridgeDelivery`'s own doc for why this def has no
1900
+ // config document to merge into at all.
1901
+ const envPassthroughApplied = mcpBridge?.kind === 'env-passthrough' ? { ...envContentApplied, ...mcpBridge.serverEntry.env } : envContentApplied;
1902
+ const instructionsApplied = stagedInstructionsFile === undefined
1903
+ ? envPassthroughApplied
1904
+ : {
1905
+ ...envPassthroughApplied,
1906
+ [stagedInstructionsFile.varName]: mergeEnvContentInstructions(envPassthroughApplied[stagedInstructionsFile.varName], stagedInstructionsFile.path),
1907
+ };
1908
+ const codexHomeApplied = codexHomeDir === undefined ? instructionsApplied : { ...instructionsApplied, CODEX_HOME: codexHomeDir };
1909
+ return systemPromptEnvOverrides === undefined ? codexHomeApplied : { ...codexHomeApplied, ...systemPromptEnvOverrides };
1910
+ }
1911
+ /**
1912
+ * Phase 6b: the `RuntimeContext` `buildArgs` receives — `undefined` unless a file, bridge path, or
1913
+ * session id was staged. Pure.
1026
1914
  *
1027
- * @param options.lifecycle - The `RunLifecycle` this executor drives its `start()` must already have been called for any `runId` passed to `run()`.
1028
- * @returns An `AgentExecutor` whose `run()` never bare-throws (see module doc's Invariant).
1029
- * @complexity `run()`'s own setup is O(1); steady-state cost is the chosen stream parser's.
1915
+ * `resumeSessionId`/`newSessionId` round-trip a prior run's `RunEndPayload.sessionRef` (see
1916
+ * `@jini-ai/protocol`'s doc on that field) back into this run's `RuntimeContext`, letting a
1917
+ * `resumesSessionViaCli` def (e.g. claude) continue its own CLI session across turns instead of
1918
+ * spawning cold every time. Either one alone must still produce a context — a run supplying ONLY a
1919
+ * session id, with no prompt/log file staged and no claude-mcp-json bridge, is exactly the common
1920
+ * case for a resumed turn.
1921
+ */
1922
+ export function computeRuntimeContext(preparedPromptFile, preparedLogFile, mcpBridge, resumeSessionId, newSessionId) {
1923
+ // Matches claude.ts buildArgs' own `typeof x === 'string' && x` truthiness check, so an empty
1924
+ // string or explicit `null` (no resume target yet) is treated as absent here too, rather than
1925
+ // manufacturing a context that carries a session field the def would ignore anyway.
1926
+ const hasResumeSessionId = typeof resumeSessionId === 'string' && resumeSessionId.length > 0;
1927
+ const hasNewSessionId = typeof newSessionId === 'string' && newSessionId.length > 0;
1928
+ if (!preparedPromptFile
1929
+ && !preparedLogFile
1930
+ && mcpBridge?.kind !== 'claude-mcp-json'
1931
+ && !hasResumeSessionId
1932
+ && !hasNewSessionId) {
1933
+ return undefined;
1934
+ }
1935
+ return {
1936
+ ...(preparedPromptFile ? { promptFilePath: preparedPromptFile.path } : {}),
1937
+ ...(preparedLogFile ? { agentLogFilePath: preparedLogFile.path } : {}),
1938
+ // Safe to pass before the file exists: `writeMcpJsonForRun` runs after buildArgs but still
1939
+ // before spawn, so the path is real by the time the child process starts.
1940
+ ...(mcpBridge?.kind === 'claude-mcp-json' ? { mcpJsonPath: mcpBridge.mcpJsonPath } : {}),
1941
+ ...(hasResumeSessionId ? { resumeSessionId } : {}),
1942
+ ...(hasNewSessionId ? { newSessionId } : {}),
1943
+ };
1944
+ }
1945
+ /**
1946
+ * Phase 7: acquires a `runtimeLock` def's process-global mutex before `buildArgs` runs — see
1947
+ * `RuntimeLock`'s own doc for the concrete race. A no-op (`undefined`) for the 23 of 24 defs with no
1948
+ * `runtimeLock` declared.
1949
+ */
1950
+ async function acquireRuntimeLockIfConfigured(def, model) {
1951
+ return def.runtimeLock?.acquire({ model });
1952
+ }
1953
+ /**
1954
+ * Phase 8: the host's `PromptAugmenter.systemOverlay()` result, if configured — see
1955
+ * `CreateAgentExecutorOptions.promptAugmenter`'s doc for `turnIndex`'s coarse 0/1 proxy.
1956
+ */
1957
+ function computeSystemPromptOverlay(promptAugmenter, agentId, runtimeContext) {
1958
+ return promptAugmenter?.systemOverlay?.({
1959
+ agentId,
1960
+ turnIndex: runtimeContext?.hasPriorAssistantTurn ? 1 : 0,
1961
+ });
1962
+ }
1963
+ /** Phase 9a: the def's `buildArgs` 4th argument — `undefined` when the run selects no model/reasoning/permissionMode/overlay at all (byte-identical to omitting the argument). Pure. */
1964
+ export function buildAgentBuildArgsOptions(input, systemPromptOverlay) {
1965
+ const hasOverlay = systemPromptOverlay !== undefined && systemPromptOverlay !== null;
1966
+ if (input.model === undefined && input.reasoning === undefined && input.permissionMode === undefined && !hasOverlay) {
1967
+ return undefined;
1968
+ }
1969
+ return {
1970
+ ...(input.model !== undefined ? { model: input.model } : {}),
1971
+ ...(input.reasoning !== undefined ? { reasoning: input.reasoning } : {}),
1972
+ ...(input.permissionMode !== undefined ? { permissionMode: input.permissionMode } : {}),
1973
+ ...(hasOverlay ? { systemPromptOverlay } : {}),
1974
+ };
1975
+ }
1976
+ /**
1977
+ * **The single dispatch point from a computed system-prompt overlay to its delivery mechanism** —
1978
+ * see `RuntimeAgentDef.systemPromptDelivery`'s own doc for the declared shape. Pure and
1979
+ * synchronous, mirroring {@link buildMcpBridgeDelivery}'s "keyed off the declared strategy, never
1980
+ * off the def's id" contract: a def earns overlay delivery by declaring a strategy, not by being
1981
+ * named in this file. That is what makes every def with no declaration work via the fallback
1982
+ * without any of their own files being touched.
1983
+ *
1984
+ * The fallback (no declared strategy — every def but `claude` today) prefixes the overlay directly
1985
+ * onto the composed prompt text, clearly delimited from the user's own request. It is gated on
1986
+ * session state, not merely on whether an overlay exists: a def that carries its own conversation
1987
+ * memory across spawns (`resumesSessionViaCli` / `resumesSessionViaAcpLoad`) persists whatever its
1988
+ * session-creating turn sends it — see `RuntimeContext.resumeSessionId`'s own doc: its presence on
1989
+ * a run means "continue a prior session", not "start one". Prefixing on every later turn of that
1990
+ * same session would therefore bake the overlay into the CLI's own stored history again and again,
1991
+ * compounding without bound turn over turn. So the fallback prefixes only when there is no resume
1992
+ * target yet (the session's own first turn, or a def with no session memory at all, which never
1993
+ * replays anything back at the CLI and so gets it on every turn).
1994
+ *
1995
+ * `'append-flag'` and `'env-var'` defs are the opposite case: the flag/env var is a fresh,
1996
+ * un-stored per-spawn directive — never part of what a resumed session replays — so it is set on
1997
+ * every turn unconditionally, exactly `claude`'s pre-existing (now-centralized) behavior before
1998
+ * this function existed.
1999
+ *
2000
+ * @param input.defId - Looks up this def's probed capabilities for an `'append-flag'` strategy's
2001
+ * `capabilityKey`. Otherwise unused — the dispatch itself is keyed off `systemPromptDelivery`, per
2002
+ * this function's own doc above, never off the id.
2003
+ * @param input.systemPromptDelivery - The def's declared strategy, or `undefined` for the fallback.
2004
+ * @param input.resumesSessionViaCli - The def's own flag (see `RuntimeAgentDef`'s doc).
2005
+ * @param input.resumesSessionViaAcpLoad - The def's own flag (see `RuntimeAgentDef`'s doc).
2006
+ * @param input.overlay - The computed `PromptAugmenter.systemOverlay()` result. `null`/`undefined`/
2007
+ * empty short-circuits to "no delivery" — byte-identical to no `PromptAugmenter` configured at all.
2008
+ * @param input.prompt - The composed prompt `buildArgs` would otherwise receive verbatim.
2009
+ * @param input.resumeSessionId - This run's `RuntimeContext.resumeSessionId`; presence means an
2010
+ * existing session is being continued, not created.
2011
+ * @returns The (possibly prefixed) prompt to hand `buildArgs`, any extra argv to append to
2012
+ * whatever `buildArgs` itself returns, and any env var overrides to merge into the spawn env
2013
+ * (`{}` for every strategy but `'env-var'`).
2014
+ * @complexity O(n) in the overlay/prompt lengths — string concatenation only, no I/O.
1030
2015
  * @overallScore 100/100
1031
2016
  */
2017
+ export function resolveSystemPromptOverlayDelivery(input) {
2018
+ const { defId, systemPromptDelivery, resumesSessionViaCli, resumesSessionViaAcpLoad, overlay, prompt, resumeSessionId } = input;
2019
+ if (typeof overlay !== 'string' || overlay.length === 0) {
2020
+ return { prompt, extraArgs: [], envOverrides: {} };
2021
+ }
2022
+ if (systemPromptDelivery?.strategy === 'append-flag') {
2023
+ const capabilityKey = systemPromptDelivery.capabilityKey;
2024
+ // `!== false`, not a truthiness check: mirrors `claude.ts`'s own pre-existing
2025
+ // `agentCapabilities.get('claude') || {}` gate exactly (moved here, not changed) — an
2026
+ // undetected/never-probed capability defaults to allowed, and only an EXPLICIT `false` (the
2027
+ // `--help` probe ran and did not find the flag) withholds it. `capabilityKey === undefined`
2028
+ // (e.g. `pi`'s existing `--append-system-prompt`, trusted unconditionally) always passes, same
2029
+ // as an absent key.
2030
+ const capabilityOk = capabilityKey === undefined || agentCapabilities.get(defId)?.[capabilityKey] !== false;
2031
+ return { prompt, extraArgs: capabilityOk ? [systemPromptDelivery.flag, overlay] : [], envOverrides: {} };
2032
+ }
2033
+ if (systemPromptDelivery?.strategy === 'env-var') {
2034
+ // No capability gate, unlike `'append-flag'`: an unrecognized env var is inert to a CLI (it
2035
+ // simply never reads it), never a fatal "unknown option" exit — there is no equivalent hazard
2036
+ // to probe-gate against here. Set verbatim, not merged with any existing value — a dedicated
2037
+ // single-purpose var, not a shared config channel (see this field's own `types.ts` doc).
2038
+ return { prompt, extraArgs: [], envOverrides: { [systemPromptDelivery.varName]: overlay } };
2039
+ }
2040
+ if (systemPromptDelivery?.strategy === 'config-instructions-file') {
2041
+ // Delivered elsewhere, not here: unlike `'append-flag'`/`'env-var'`, this mechanism needs real
2042
+ // filesystem I/O (staging the overlay to a temp file — `opencode`'s `instructions` array only
2043
+ // accepts a file path or URL, confirmed live, never inline text), which this function's "pure
2044
+ // and synchronous" contract cannot perform. `prepareSystemPromptOverlayFileIfNeeded` (a separate
2045
+ // async phase in `run()`, gated on this same strategy check) stages the file, and
2046
+ // `computeChildEnv` merges its path into the config document via `mergeEnvContentInstructions`.
2047
+ // This branch's only job is to make sure the universal prefix fallback below does NOT ALSO run
2048
+ // for a def that already has this strategy declared — the same "no double delivery" concern
2049
+ // `imageDelivery`'s doc calls out for its own native-vs-fallback split.
2050
+ return { prompt, extraArgs: [], envOverrides: {} };
2051
+ }
2052
+ const isContinuingExistingSession = (resumesSessionViaCli === true || resumesSessionViaAcpLoad === true) &&
2053
+ typeof resumeSessionId === 'string' &&
2054
+ resumeSessionId.length > 0;
2055
+ if (isContinuingExistingSession) {
2056
+ return { prompt, extraArgs: [], envOverrides: {} };
2057
+ }
2058
+ // KNOWN TRADE-OFF, deliberate: for a resume-capable def with no `'append-flag'`/`'env-var'`
2059
+ // mechanism yet (`codex`, `codebuddy`, `opencode`, `amr` — all four presently on this fallback),
2060
+ // the overlay is therefore only injected on the SESSION-CREATING turn, not every turn. A host
2061
+ // whose `PromptAugmenter.systemOverlay()` result can change mid-conversation (e.g. a host that
2062
+ // lets an operator edit its own stored instructions and re-reads them before every run — see
2063
+ // `prompt-augmenter.ts`'s own doc for the seam) will see NO effect from such an edit until a NEW
2064
+ // session starts for one of these four defs specifically — a real, silent limitation, not a
2065
+ // theoretical one. This is the correct
2066
+ // trade against the alternative (re-injecting every turn would bake the overlay into that def's
2067
+ // own CLI-persisted session history again and again, compounding without bound) — do not change
2068
+ // this gating to "fix" the staleness. The actual fix is giving each of the four its own
2069
+ // `'append-flag'`-equivalent `systemPromptDelivery` (an argv flag or an env var, neither of which
2070
+ // is part of what a resumed session replays), which removes this limitation entirely for that
2071
+ // def. See `reasonix.ts`'s and `opencode.ts`'s module docs for the two already-identified,
2072
+ // not-yet-wired native mechanisms.
2073
+ return { prompt: `${overlay}\n\n---\n\n${prompt}`, extraArgs: [], envOverrides: {} };
2074
+ }
2075
+ /** Phase 9b: calls the def's `buildArgs`, releasing staged resources and failing the run on a throw. */
2076
+ export async function buildRunArgs(input, deps) {
2077
+ try {
2078
+ // Resolved before `buildArgs` runs so a def with no declared `systemPromptDelivery` sees the
2079
+ // overlay already prefixed into `prompt` — see `resolveSystemPromptOverlayDelivery`'s own doc.
2080
+ const delivery = resolveSystemPromptOverlayDelivery({
2081
+ defId: input.def.id,
2082
+ systemPromptDelivery: input.def.systemPromptDelivery,
2083
+ resumesSessionViaCli: input.def.resumesSessionViaCli,
2084
+ resumesSessionViaAcpLoad: input.def.resumesSessionViaAcpLoad,
2085
+ overlay: input.systemPromptOverlay,
2086
+ prompt: input.imageDelivery.prompt,
2087
+ resumeSessionId: input.runtimeContext?.resumeSessionId,
2088
+ });
2089
+ const args = input.def.buildArgs(delivery.prompt, [...(input.imagePaths ?? [])], input.imageDelivery.extraAllowedDirs === undefined ? undefined : [...input.imageDelivery.extraAllowedDirs], buildAgentBuildArgsOptions(input.runInput, input.systemPromptOverlay), input.runtimeContext);
2090
+ // `'append-flag'` delivery's extra argv (empty for every other def/strategy) is appended after
2091
+ // whatever the def's own `buildArgs` returned — safe because it is only ever non-empty for a
2092
+ // `promptViaStdin` def with no trailing positional argv (`claude`/`pi` today; see
2093
+ // `resolveSystemPromptOverlayDelivery`'s doc for why a future 'append-flag' def must keep that
2094
+ // property too). `envOverrides` (non-empty only for `'env-var'` — `reasonix` today) is handed
2095
+ // back rather than applied here, since the spawn env isn't finalized until `computeChildEnv`
2096
+ // runs, later in `run()`.
2097
+ return { args: [...args, ...delivery.extraArgs], envOverrides: delivery.envOverrides };
2098
+ }
2099
+ catch (err) {
2100
+ await deps.releaseStagedResources();
2101
+ return deps.failBeforeSpawn(input.runId, 'AGENT_SPAWN_FAILED', `AgentExecutor: could not build launch arguments for agent "${input.def.id}": ${errorMessage(err)}`);
2102
+ }
2103
+ }
2104
+ /** Phase 10: mechanism 1 of 5's one effect — stages this run's own `.mcp.json`, returning the path `cleanupStagedFiles` should later remove (`undefined` for every other mechanism / unconfigured host). */
2105
+ export async function writeMcpJsonIfNeeded(input, deps) {
2106
+ if (input.mcpBridge?.kind !== 'claude-mcp-json' || deps.mcpJsonInjection === undefined) {
2107
+ return undefined;
2108
+ }
2109
+ try {
2110
+ await writeMcpJsonForRun(input.cwd, input.mcpBridge, deps.mcpJsonInjection);
2111
+ return input.mcpBridge.mcpJsonPath;
2112
+ }
2113
+ catch (err) {
2114
+ await deps.releaseStagedResources();
2115
+ return deps.failBeforeSpawn(input.runId, 'AGENT_SPAWN_FAILED', `AgentExecutor: could not write .mcp.json for agent "${input.def.id}": ${errorMessage(err)}`);
2116
+ }
2117
+ }
2118
+ /**
2119
+ * Phase 10b1: `systemPromptDelivery: { strategy: 'config-instructions-file' }`'s one effect —
2120
+ * stages the computed overlay to a fresh, run-scoped temp file, so `computeChildEnv` has a real
2121
+ * path to merge into that def's `instructions` config array (see
2122
+ * {@link mergeEnvContentInstructions}'s own doc for the live verification this mechanism rests on).
2123
+ * `null` for every other strategy, an unset `systemPromptDelivery`, or no overlay present at all —
2124
+ * byte-identical to before this mechanism existed, matching {@link writeMcpJsonIfNeeded}'s and
2125
+ * {@link prepareCodexHomeIfNeeded}'s identical no-op-when-inapplicable gate.
2126
+ *
2127
+ * `opencode`'s `instructions` field only accepts a file path or a remote URL — confirmed live
2128
+ * (2026-09-01): a literal instruction string in the array is silently ignored (no error, just never
2129
+ * honored), so an inline-text shortcut is not available and this staging step is load-bearing, not
2130
+ * a defensive extra.
2131
+ * @param input.def - Only used for its `id`, in the failure message, and its `systemPromptDelivery` declaration.
2132
+ * @param input.overlay - The computed `PromptAugmenter.systemOverlay()` result for this run.
2133
+ * @complexity O(1) plus one directory creation and one file write.
2134
+ * @overallScore 100/100
2135
+ */
2136
+ export async function prepareSystemPromptOverlayFileIfNeeded(input, deps) {
2137
+ if (input.def.systemPromptDelivery?.strategy !== 'config-instructions-file' ||
2138
+ typeof input.overlay !== 'string' ||
2139
+ input.overlay.length === 0) {
2140
+ return null;
2141
+ }
2142
+ try {
2143
+ const safeRunId = input.runId.replace(/[^A-Za-z0-9_-]/g, '-').slice(0, 80) || 'run';
2144
+ const dir = await fsPromises.mkdtemp(join(tmpdir(), `jini-system-prompt-overlay-${safeRunId}-`));
2145
+ const filePath = join(dir, 'overlay.md');
2146
+ await fsPromises.writeFile(filePath, input.overlay, { encoding: 'utf8', mode: 0o600 });
2147
+ return {
2148
+ path: filePath,
2149
+ cleanup: async () => {
2150
+ await fsPromises.rm(dir, { recursive: true, force: true });
2151
+ },
2152
+ };
2153
+ }
2154
+ catch (err) {
2155
+ await deps.releaseStagedResources();
2156
+ return deps.failBeforeSpawn(input.runId, 'AGENT_SPAWN_FAILED', `AgentExecutor: could not stage a system-prompt overlay file for agent "${input.def.id}": ${errorMessage(err)}`);
2157
+ }
2158
+ }
2159
+ /**
2160
+ * Phase 10b: mechanism 5 of 5's one effect — stages this run's scratch `CODEX_HOME` directory,
2161
+ * returning the prepared handle `cleanupStagedFiles` should later release (`null` for every other
2162
+ * mechanism, or for an unconfigured host — matching {@link writeMcpJsonIfNeeded}'s identical gate).
2163
+ * @param input.def - Only used for its `id`, in the failure message.
2164
+ * @param input.mcpBridge - This run's resolved bridge delivery — a no-op unless its `kind` is `'codex-toml'`.
2165
+ * @param deps.hostEnv - The daemon's own environment, threaded through to {@link resolveSourceCodexHomeDir} rather than read from a module-level `process.env` so this phase stays testable with an injected env.
2166
+ * @complexity O(1) plus {@link prepareCodexHomeForRun}'s own cost.
2167
+ * @overallScore 100/100
2168
+ */
2169
+ export async function prepareCodexHomeIfNeeded(input, deps) {
2170
+ if (input.mcpBridge?.kind !== 'codex-toml' || deps.mcpJsonInjection === undefined) {
2171
+ return null;
2172
+ }
2173
+ try {
2174
+ return await prepareCodexHomeForRun(input.runId, input.mcpBridge.serverEntry, resolveSourceCodexHomeDir(deps.hostEnv), resolveCodexHomeSeams(deps.mcpJsonInjection));
2175
+ }
2176
+ catch (err) {
2177
+ await deps.releaseStagedResources();
2178
+ return deps.failBeforeSpawn(input.runId, 'AGENT_SPAWN_FAILED', `AgentExecutor: could not stage a CODEX_HOME for agent "${input.def.id}": ${errorMessage(err)}`);
2179
+ }
2180
+ }
2181
+ /** Phase 11: post-`buildArgs` guard for argv-bound defs whose resolved binary is a Windows shim/.exe — a no-op off-Windows and for non-argv-bound defs. */
2182
+ export async function guardWindowsCommandLineBudget(input, deps) {
2183
+ const windowsBudgetError = checkWindowsCmdShimCommandLineBudget(input.def, input.launchPath, input.args) ??
2184
+ checkWindowsDirectExeCommandLineBudget(input.def, input.launchPath, input.args);
2185
+ if (windowsBudgetError) {
2186
+ await deps.releaseStagedResources();
2187
+ await deps.failBeforeSpawn(input.runId, 'AGENT_PROMPT_TOO_LARGE', windowsBudgetError.message);
2188
+ }
2189
+ }
2190
+ /**
2191
+ * Phase 12: the real `node:child_process.spawn` call.
2192
+ *
2193
+ * **Deliberately synchronous, unlike every other phase in this file.** A spawned child can emit
2194
+ * `'error'` on the very next microtask tick (Node schedules it eagerly on some failure modes, and a
2195
+ * test harness simulating "the child emits 'error' before 'spawn'" does so explicitly via
2196
+ * `queueMicrotask`). `run()` must register its `'error'` listeners (`wireChildLifecycle`'s safety net,
2197
+ * then `waitForSpawnOrError`'s `child.once('error', reject)`) in the *same synchronous turn* as this
2198
+ * spawn call — Node's `EventEmitter` throws synchronously when `'error'` fires with zero listeners
2199
+ * attached. Wrapping this call in an `async function` and `await`ing it (as every other phase here
2200
+ * does) would insert a microtask tick between spawn and listener registration, occasionally losing
2201
+ * that race — confirmed by a real test failure during this refactor (an uncaught `EventEmitter`
2202
+ * `'error'` exception) before this function was changed back to a plain, unawaited call returning a
2203
+ * result object instead of throwing/rejecting.
2204
+ * @returns `{kind:'ok', child}` on success, `{kind:'error', error}` on a synchronous throw from `spawn`
2205
+ * — `run()` itself is responsible for cleanup and `failBeforeSpawn` on the error variant, both of
2206
+ * which are safe to make asynchronous since no child (and hence no listener race) exists yet.
2207
+ * @complexity O(1) plus `spawn`'s own cost.
2208
+ */
2209
+ export function spawnAgentChildProcess(input, deps) {
2210
+ try {
2211
+ return {
2212
+ kind: 'ok',
2213
+ child: deps.spawn(input.invocation.command, input.invocation.args, {
2214
+ cwd: input.cwd,
2215
+ env: input.childEnv,
2216
+ stdio: ['pipe', 'pipe', 'pipe'],
2217
+ windowsVerbatimArguments: input.invocation.windowsVerbatimArguments,
2218
+ }),
2219
+ };
2220
+ }
2221
+ catch (error) {
2222
+ return { kind: 'error', error };
2223
+ }
2224
+ }
2225
+ /** Named predicate replacing an inline `streamFormat === 'acp-json-rpc' || streamFormat === 'pi-rpc'` check — the two formats that own their own prompt/event protocol and skip `wireChildLifecycle`. */
2226
+ export function isStdinDrivenFormat(streamFormat) {
2227
+ return streamFormat !== 'acp-json-rpc' && streamFormat !== 'pi-rpc';
2228
+ }
2229
+ /** Phase 13: awaits spawn confirmation, routing a failure through the same `failBeforeSpawn` shape every earlier guard uses. */
2230
+ export async function confirmChildSpawned(input, deps) {
2231
+ try {
2232
+ await waitForSpawnOrError(input.child);
2233
+ }
2234
+ catch (err) {
2235
+ await deps.releaseStagedResources();
2236
+ await deps.failBeforeSpawn(input.runId, 'AGENT_SPAWN_FAILED', `AgentExecutor: failed to spawn agent "${input.def.id}": ${errorMessage(err)}`);
2237
+ }
2238
+ }
2239
+ /** Phase 14: starts a `runtimeLock` def's handoff watcher once a live process exists to consume the locked side effect — a no-op when the def declared no `waitForHandoff`. Deliberately not awaited; see `RuntimeLockHold.waitForHandoff`'s own doc. */
2240
+ export function armHandoffWatcher(runtimeLockHold, handoffInput, release) {
2241
+ if (!runtimeLockHold?.waitForHandoff)
2242
+ return;
2243
+ void runtimeLockHold.waitForHandoff(handoffInput).then(release, release);
2244
+ }
2245
+ /** Phase 15 (ACP branch): attaches the ACP session, escalating process-tree teardown and failing the run through `failBeforeSpawn` on an attach-time throw. */
2246
+ export async function runAcpDispatch(input, deps) {
2247
+ try {
2248
+ wireAcpLifecycle({
2249
+ runId: input.runId,
2250
+ agentId: input.agentId,
2251
+ child: input.child,
2252
+ lifecycle: deps.lifecycle,
2253
+ prompt: input.prompt,
2254
+ cwd: input.cwd,
2255
+ model: input.model,
2256
+ imagePaths: input.imagePaths,
2257
+ envFormat: input.envFormat,
2258
+ // Mechanism 2 of 5 — see `WireAcpLifecycleContext.mcpServers`. `undefined` for any def that
2259
+ // did not declare `'acp-merge'` and for an unconfigured host.
2260
+ mcpServers: input.mcpBridge?.kind === 'acp-merge' ? input.mcpBridge.mcpServers : undefined,
2261
+ onPermissionRequest: deps.onPermissionRequest,
2262
+ attachAcpSession: deps.attachAcpSession,
2263
+ listProcessSnapshots: deps.listProcessSnapshots,
2264
+ collectProcessTreePids: deps.collectProcessTreePids,
2265
+ stopProcesses: deps.stopProcesses,
2266
+ onCleanupFailure: deps.onCleanupFailure,
2267
+ cleanupStagedFiles: deps.cleanupStagedFiles,
2268
+ journal: deps.journal,
2269
+ classifyFailure: deps.classifyFailure,
2270
+ });
2271
+ }
2272
+ catch (err) {
2273
+ // Unlike the cancellation-listener call sites, we are already in an async function about to
2274
+ // call finish() and throw — nothing else races this, so cleanup is awaited here rather than
2275
+ // fired-and-forgotten (SEC-007: "await where lifecycle ordering allows it").
2276
+ await terminateChildTreeBestEffort({ listProcessSnapshots: deps.listProcessSnapshots, collectProcessTreePids: deps.collectProcessTreePids, stopProcesses: deps.stopProcesses }, input.child, input.runId, 'acp-attach-failure', deps.onCleanupFailure);
2277
+ await deps.releaseStagedResources();
2278
+ await deps.failBeforeSpawn(input.runId, 'AGENT_SPAWN_FAILED', `AgentExecutor: could not attach ACP session for agent "${input.agentId}": ${errorMessage(err)}`);
2279
+ }
2280
+ }
2281
+ /** Phase 15 (pi-rpc branch): same discipline as {@link runAcpDispatch}, for the one `'pi-rpc'` def. */
2282
+ export async function runPiRpcDispatch(input, deps) {
2283
+ try {
2284
+ wirePiRpcLifecycle({
2285
+ runId: input.runId,
2286
+ agentId: input.agentId,
2287
+ child: input.child,
2288
+ lifecycle: deps.lifecycle,
2289
+ prompt: input.prompt,
2290
+ cwd: input.cwd,
2291
+ model: input.model,
2292
+ imagePaths: input.imagePaths,
2293
+ uploadRoot: input.uploadRoot,
2294
+ attachPiRpcSession: deps.attachPiRpcSession,
2295
+ listProcessSnapshots: deps.listProcessSnapshots,
2296
+ collectProcessTreePids: deps.collectProcessTreePids,
2297
+ stopProcesses: deps.stopProcesses,
2298
+ onCleanupFailure: deps.onCleanupFailure,
2299
+ cleanupStagedFiles: deps.cleanupStagedFiles,
2300
+ journal: deps.journal,
2301
+ classifyFailure: deps.classifyFailure,
2302
+ });
2303
+ }
2304
+ catch (err) {
2305
+ // Same discipline as the ACP attach-failure path above: await cleanup here rather than
2306
+ // fire-and-forget (SEC-007).
2307
+ await terminateChildTreeBestEffort({ listProcessSnapshots: deps.listProcessSnapshots, collectProcessTreePids: deps.collectProcessTreePids, stopProcesses: deps.stopProcesses }, input.child, input.runId, 'pi-rpc-attach-failure', deps.onCleanupFailure);
2308
+ await deps.releaseStagedResources();
2309
+ await deps.failBeforeSpawn(input.runId, 'AGENT_SPAWN_FAILED', `AgentExecutor: could not attach pi-rpc session for agent "${input.agentId}": ${errorMessage(err)}`);
2310
+ }
2311
+ }
1032
2312
  export function createAgentExecutor(options) {
1033
2313
  const lifecycle = options.lifecycle;
1034
- const getAgentDefFn = options.getAgentDef ?? getAgentDef;
1035
- const resolveAgentLaunchFn = options.resolveAgentLaunch ?? resolveAgentLaunch;
1036
- const applyAgentLaunchEnvFn = options.applyAgentLaunchEnv ?? applyAgentLaunchEnv;
1037
- const createCommandInvocationFn = options.createCommandInvocation ?? createCommandInvocation;
1038
- const spawnFn = options.spawn ?? nodeSpawn;
1039
- const attachAcpSessionFn = options.attachAcpSession ?? attachAcpSession;
1040
- const attachPiRpcSessionFn = options.attachPiRpcSession ?? attachPiRpcSession;
1041
- const preparePromptFileForAgentFn = options.preparePromptFileForAgent ?? preparePromptFileForAgent;
1042
- const listProcessSnapshotsFn = options.listProcessSnapshots ?? listProcessSnapshots;
1043
- const collectProcessTreePidsFn = options.collectProcessTreePids ?? collectProcessTreePids;
1044
- const stopProcessesFn = options.stopProcesses ?? stopProcesses;
1045
- const onCleanupFailureFn = options.onCleanupFailure ?? defaultCleanupFailureSink;
2314
+ const { getAgentDef: getAgentDefFn, resolveAgentLaunch: resolveAgentLaunchFn, applyAgentLaunchEnv: applyAgentLaunchEnvFn, attachAcpSession: attachAcpSessionFn, attachPiRpcSession: attachPiRpcSessionFn, preparePromptFileForAgent: preparePromptFileForAgentFn, prepareAgentLogFile: prepareAgentLogFileFn, } = resolveAgentRuntimeDeps(options);
2315
+ const { createCommandInvocation: createCommandInvocationFn, spawn: spawnFn, listProcessSnapshots: listProcessSnapshotsFn, collectProcessTreePids: collectProcessTreePidsFn, stopProcesses: stopProcessesFn, } = resolveProcessDeps(options);
2316
+ const { onCleanupFailure: onCleanupFailureFn, bufferedStdoutMaxBytes } = resolveMiscExecutorDeps(options);
1046
2317
  const journal = options.journal;
1047
2318
  const continuation = options.continuation;
1048
2319
  const classifyFailure = options.classifyFailure;
1049
2320
  const mcpJsonInjection = options.mcpJsonInjection;
2321
+ const promptAugmenter = options.promptAugmenter;
1050
2322
  /**
1051
2323
  * Transitions `runId` to `'failed'` (idempotent, never resumable — no
1052
2324
  * classifier exists, see module doc) then rejects with a typed
@@ -1075,106 +2347,176 @@ export function createAgentExecutor(options) {
1075
2347
  * @overallScore 100/100
1076
2348
  */
1077
2349
  async function run(input) {
1078
- const def = getAgentDefFn(input.agentId);
1079
- if (!def) {
1080
- return failBeforeSpawn(input.runId, 'AGENT_NOT_FOUND', `AgentExecutor: unknown agentId "${input.agentId}"`);
1081
- }
1082
- const streamFormat = def.streamFormat;
1083
- if (!isSupportedStreamFormat(streamFormat)) {
1084
- return failBeforeSpawn(input.runId, 'AGENT_RUNTIME_UNSUPPORTED', `AgentExecutor: agent "${def.id}" has streamFormat "${streamFormat}", which is not implemented in v1 — only ${SUPPORTED_STREAM_FORMATS.join(', ')} are supported (see packages/daemon/source-map.md for the deferred antigravity guard)`);
1085
- }
1086
- // Antigravity is the one plain def NOT driven see module doc. This
1087
- // guard is deliberately independent of (and ahead of) the generic
1088
- // prompt-delivery/dispatch logic below: even though antigravity's def
1089
- // declares promptViaStdin: true and would otherwise clear every guard
1090
- // that follows, it needs auth-URL-leak buffering and a cross-run
1091
- // model-selection lock this driver has no seam for yet.
1092
- if (streamFormat === 'plain' && def.id === 'antigravity') {
1093
- return failBeforeSpawn(input.runId, 'AGENT_RUNTIME_UNSUPPORTED', `AgentExecutor: agent "${def.id}" needs auth-URL-leak buffering and a cross-run model-selection lock that generic streamFormat 'plain' driving does not provide — deliberately deferred, see ADS-memory/reports/proposals/PROP-plain-format-agent-driving-2026-07-21.md`);
1094
- }
1095
- if (streamFormat !== 'acp-json-rpc' &&
1096
- def.promptViaStdin !== true &&
1097
- def.promptViaFile !== true &&
1098
- typeof def.maxPromptArgBytes !== 'number') {
1099
- return failBeforeSpawn(input.runId, 'AGENT_RUNTIME_UNSUPPORTED', `AgentExecutor: agent "${def.id}" does not deliver its prompt via stdin, a staged prompt file, or a byte-budgeted argv — v1 has no other prompt delivery path`);
1100
- }
1101
- // Argv-bound defs (aider, deepseek) — reject an oversized prompt before
1102
- // ever resolving a binary or touching the filesystem. A no-op for every
1103
- // def without `maxPromptArgBytes` (checkPromptArgvBudget's own guard).
1104
- const argvBudgetError = checkPromptArgvBudget(def, input.prompt);
1105
- if (argvBudgetError) {
1106
- return failBeforeSpawn(input.runId, 'AGENT_PROMPT_TOO_LARGE', argvBudgetError.message);
1107
- }
1108
- const resolvedEnv = input.env !== undefined ? toStringEnvRecord(input.env) : buildAgentEnv(process.env, input.credentialEnv);
1109
- const launch = resolveAgentLaunchFn(def, resolvedEnv);
1110
- if (!launch.launchPath) {
1111
- return failBeforeSpawn(input.runId, 'AGENT_BINARY_NOT_RESOLVED', `AgentExecutor: could not resolve an executable for agent "${def.id}" (bin "${def.bin}")`);
1112
- }
2350
+ const { def, streamFormat } = await resolveDefAndStreamFormat({ runId: input.runId, agentId: input.agentId }, { getAgentDef: getAgentDefFn, failBeforeSpawn });
2351
+ // Computed once, before anything downstream ever looks at "the prompt" or "the allowed
2352
+ // dirs" — a no-op (`{prompt: input.prompt, extraAllowedDirs: input.extraAllowedDirs}`,
2353
+ // literally unchanged) unless `def.imageDelivery === 'prompt-path'` AND `input.imagePaths`
2354
+ // is non-empty, so this can never affect a 'native'-delivery def (ACP, pi-rpc, qoder) or a
2355
+ // run with no attachments. See `image-prompt-delivery.ts`'s own doc for the full mechanism;
2356
+ // every use of `input.prompt`/`input.extraAllowedDirs` below that reflects what the CLI
2357
+ // actually receives reads `imageDelivery.*` instead — the two ACP/pi-rpc `wire*Lifecycle`
2358
+ // calls further down deliberately keep reading `input.prompt` verbatim, since those two
2359
+ // defs' own native protocol already delivers the image and must never also get this
2360
+ // treatment (the double-delivery hazard this mechanism exists to avoid).
2361
+ const imageDelivery = await resolveImageDeliveryAndArgvBudget({ runId: input.runId, def, prompt: input.prompt, imagePaths: input.imagePaths, extraAllowedDirs: input.extraAllowedDirs }, { failBeforeSpawn });
2362
+ const resolvedEnv = resolveRunEnv(input, process.env);
2363
+ const launch = await resolveLaunch({ runId: input.runId, def, resolvedEnv }, { resolveAgentLaunch: resolveAgentLaunchFn, failBeforeSpawn });
1113
2364
  const spawnEnv = applyAgentLaunchEnvFn({ ...resolvedEnv }, launch);
1114
- // Stage a promptViaFile def's (grok-build) prompt to a temp file before
1115
- // buildArgs runs its buildArgs throws without
1116
- // runtimeContext.promptFilePath. A no-op (returns null) for every def
1117
- // without promptViaFile: true (preparePromptFileForAgent's own guard).
1118
- let preparedPromptFile;
1119
- try {
1120
- preparedPromptFile = await preparePromptFileForAgentFn(def, input.prompt, input.runId);
1121
- }
1122
- catch (err) {
1123
- return failBeforeSpawn(input.runId, 'AGENT_SPAWN_FAILED', `AgentExecutor: could not stage a prompt file for agent "${def.id}": ${errorMessage(err)}`);
1124
- }
2365
+ // Stage a promptViaFile def's (grok-build) prompt to a temp file before buildArgs runs — its
2366
+ // buildArgs throws without runtimeContext.promptFilePath. A no-op (returns null) for every
2367
+ // def without promptViaFile: true (preparePromptFileForAgent's own guard).
2368
+ const preparedPromptFile = await stagePromptFile({ runId: input.runId, def, prompt: imageDelivery.prompt }, { preparePromptFileForAgent: preparePromptFileForAgentFn, failBeforeSpawn });
2369
+ // Stage a needsAgentLogFile def's (antigravity) diagnostic-log path, on the same terms and at
2370
+ // the same point as the prompt file above: before buildArgs, since buildArgs is what turns the
2371
+ // path into a `--log-file <path>` argument. A no-op (returns null) for every def without
2372
+ // `needsAgentLogFile: true` (prepareAgentLogFile's own guard). Sequenced after the prompt file
2373
+ // rather than concurrently so the failure path above has exactly one thing to clean up.
2374
+ const preparedLogFile = await stageLogFile({ runId: input.runId, def, preparedPromptFile }, { prepareAgentLogFile: prepareAgentLogFileFn, failBeforeSpawn });
1125
2375
  // Cleaned up after the child exits (wireChildLifecycle/wireAcpLifecycle/wirePiRpcLifecycle's
1126
2376
  // close handlers) and on every pre-spawn/spawn-failure path below — a leaked temp file
1127
- // containing the full prompt is a confidentiality gap, not just a disk leak.
1128
- const cleanupPromptFile = preparedPromptFile
1129
- ? preparedPromptFile.cleanup
1130
- : async () => { };
1131
- const runtimeContext = preparedPromptFile
1132
- ? { promptFilePath: preparedPromptFile.path }
1133
- : undefined;
1134
- const args = def.buildArgs(input.prompt, [...(input.imagePaths ?? [])], input.extraAllowedDirs === undefined ? undefined : [...input.extraAllowedDirs], input.model !== undefined || input.reasoning !== undefined || input.permissionMode !== undefined
1135
- ? {
1136
- ...(input.model !== undefined ? { model: input.model } : {}),
1137
- ...(input.reasoning !== undefined ? { reasoning: input.reasoning } : {}),
1138
- ...(input.permissionMode !== undefined ? { permissionMode: input.permissionMode } : {}),
2377
+ // containing the full prompt, or whatever the CLI chose to write into its log, is a
2378
+ // confidentiality gap, not just a disk leak. One composed closure covering both staged files;
2379
+ // see `WireChildLifecycleContext.cleanupStagedFiles`'s doc for why they are not two fields.
2380
+ /**
2381
+ * Set once `writeMcpJsonForRun` has actually written this run's MCP config, so `cleanupStagedFiles`
2382
+ * knows there is a file holding a live bearer token to remove. Cleared as it is consumed, so the
2383
+ * removal happens exactly once across the several paths that may call the cleanup. Only the
2384
+ * `'claude-mcp-json'` mechanism stages a file at all `'acp-merge'` and `'env-content'` leave
2385
+ * nothing on disk, so this stays `undefined` for those.
2386
+ */
2387
+ let writtenMcpJsonPath;
2388
+ const removeMcpJsonFileFn = mcpJsonInjection?.removeFile ?? defaultRemoveMcpJsonFile;
2389
+ /**
2390
+ * Set once `prepareCodexHomeIfNeeded` has actually staged this run's scratch `CODEX_HOME`, so
2391
+ * `cleanupStagedFiles` knows there is a directory holding a copied login credential to remove.
2392
+ * Cleared as it is consumed, matching `writtenMcpJsonPath`'s identical single-removal discipline.
2393
+ * Only the `'codex-toml'` mechanism stages a directory at all.
2394
+ */
2395
+ let preparedCodexHome = null;
2396
+ /**
2397
+ * Set once `prepareSystemPromptOverlayFileIfNeeded` has actually staged this run's overlay file
2398
+ * for a `'config-instructions-file'` def, so `cleanupStagedFiles` knows there is a temp
2399
+ * directory to remove. Cleared as it is consumed, matching `preparedCodexHome`'s identical
2400
+ * single-removal discipline. Only that one strategy stages a file this way — `null` for every
2401
+ * other def/strategy/no-overlay run.
2402
+ */
2403
+ let preparedSystemPromptOverlayFile = null;
2404
+ const cleanupStagedFiles = async () => {
2405
+ if (preparedPromptFile)
2406
+ await preparedPromptFile.cleanup();
2407
+ if (preparedLogFile)
2408
+ await preparedLogFile.cleanup();
2409
+ if (writtenMcpJsonPath !== undefined) {
2410
+ const mcpJsonFileToRemove = writtenMcpJsonPath;
2411
+ writtenMcpJsonPath = undefined;
2412
+ await removeMcpJsonFileFn(mcpJsonFileToRemove);
1139
2413
  }
1140
- : undefined, runtimeContext);
1141
- // Gap 3, part 2 — write .mcp.json into the managed cwd before spawn, so a 'claude-mcp-json'
1142
- // def's own spawn-time config load discovers the jini-mcp bridge server. A no-op for every
1143
- // other def and whenever mcpJsonInjection is unconfigured — see writeMcpJsonForRun's doc.
1144
- try {
1145
- await writeMcpJsonForRun(input.cwd, input.runId, def, mcpJsonInjection);
1146
- }
1147
- catch (err) {
1148
- await cleanupPromptFile();
1149
- return failBeforeSpawn(input.runId, 'AGENT_SPAWN_FAILED', `AgentExecutor: could not write .mcp.json for agent "${def.id}": ${errorMessage(err)}`);
1150
- }
2414
+ if (preparedCodexHome) {
2415
+ const codexHomeToRemove = preparedCodexHome;
2416
+ preparedCodexHome = null;
2417
+ await codexHomeToRemove.cleanup();
2418
+ }
2419
+ if (preparedSystemPromptOverlayFile) {
2420
+ const overlayFileToRemove = preparedSystemPromptOverlayFile;
2421
+ preparedSystemPromptOverlayFile = null;
2422
+ await overlayFileToRemove.cleanup();
2423
+ }
2424
+ };
2425
+ // Resolve this run's MCP bridge delivery once, before buildArgs — the `'claude-mcp-json'`
2426
+ // variant's path has to be in `runtimeContext` for that def's own `--mcp-config` argv, and
2427
+ // resolving here means the per-run bearer credential is minted exactly once no matter which of
2428
+ // the five mechanisms ends up carrying it. `null` for an unconfigured host or a def declaring
2429
+ // no strategy — see `buildMcpBridgeDelivery`'s doc.
2430
+ const mcpBridge = await resolveMcpBridgeForRun({ runId: input.runId, cwd: input.cwd, def }, { mcpJsonInjection, cleanupStagedFiles, failBeforeSpawn });
2431
+ const runtimeContext = computeRuntimeContext(preparedPromptFile, preparedLogFile, mcpBridge, input.resumeSessionId, input.newSessionId);
2432
+ // A `runtimeLock` def's buildArgs mutates process-global state its own CLI reads back at
2433
+ // startup, so the mutex must be held from before buildArgs until the spawned child has
2434
+ // demonstrably consumed it — see `RuntimeLock`'s own doc for the concrete race. Undefined for
2435
+ // 23 of 24 defs, in which case nothing below waits on anything.
2436
+ const selectedModel = input.model;
2437
+ const runtimeLockHold = await acquireRuntimeLockIfConfigured(def, selectedModel);
2438
+ // Aborts once the spawned process is gone — or immediately, on a path where no process ever
2439
+ // ran — so a def's own handoff watcher can never outlive the run it was polling for.
2440
+ const processExitedController = new AbortController();
2441
+ /**
2442
+ * Releases the runtime lock and cancels any handoff watcher. Safe to call from any number of
2443
+ * paths: `AbortController.abort()` after the first is a no-op, and `RuntimeLockHold.release`
2444
+ * is idempotent by contract.
2445
+ */
2446
+ const releaseRuntimeLock = () => {
2447
+ processExitedController.abort();
2448
+ runtimeLockHold?.release();
2449
+ };
2450
+ /** Both staged-file and lock release, for the pre-spawn/spawn-failure paths that own neither a child nor a close handler. */
2451
+ const releaseStagedResources = async () => {
2452
+ releaseRuntimeLock();
2453
+ await cleanupStagedFiles();
2454
+ };
2455
+ // Computed once per `run()`, not per-token/per-event: a system-prompt overlay is a spawn-time
2456
+ // CLI arg, not something that varies mid-run. `turnIndex` is a coarse 0/1 proxy (no exact turn
2457
+ // counter exists on this driver) — sufficient because every `PromptAugmenter.systemOverlay()`
2458
+ // implementation this seam has today wants the same overlay on every turn, not a first-turn-only
2459
+ // one; a caller that needs finer-grained turn numbering can track it itself and ignore this arg.
2460
+ const systemPromptOverlay = computeSystemPromptOverlay(promptAugmenter, def.id, runtimeContext);
2461
+ // Guarded, like every other step between staging and spawn: a `runtimeLock` def's `buildArgs` is
2462
+ // guarded precisely *because* it performs real filesystem writes (antigravity writes its model
2463
+ // choice into a shared settings file), so EACCES on a read-only home, ENOSPC, or a malformed
2464
+ // existing settings file all reach here as a throw. Unguarded, that escaped `run()` as a bare
2465
+ // `Error` — breaking this driver's "never a bare throw, always an `AgentExecutorError`" contract
2466
+ // — and left the run `'running'` forever while still holding the process-global mutex and both
2467
+ // staged files, so no later run of that def could ever acquire the lock either.
2468
+ const { args, envOverrides: systemPromptEnvOverrides } = await buildRunArgs({ runId: input.runId, def, imageDelivery, imagePaths: input.imagePaths, runInput: input, systemPromptOverlay, runtimeContext }, { releaseStagedResources, failBeforeSpawn });
2469
+ // Mechanism 1 of 5's one effect — stage this run's own MCP config file (run-scoped, see
2470
+ // `mcpJsonPathForRun`) before spawn so the `--mcp-config <path>` argv buildArgs just produced
2471
+ // points at a real file. Skipped entirely for the other four mechanisms and whenever no bridge
2472
+ // was resolved at all. `writtenMcpJsonPath` is set only once the write actually happens, so
2473
+ // `cleanupStagedFiles` knows there is a live-token file to remove afterward.
2474
+ writtenMcpJsonPath = await writeMcpJsonIfNeeded({ runId: input.runId, cwd: input.cwd, def, mcpBridge }, { mcpJsonInjection, releaseStagedResources, failBeforeSpawn });
2475
+ // Mechanism 5 of 5's one effect — stage this run's scratch `CODEX_HOME` directory. Skipped
2476
+ // entirely for the other four mechanisms and whenever no bridge was resolved at all.
2477
+ // `codex.ts`'s `buildArgs` needs no argv change for this (CODEX_HOME is an env var, not a flag),
2478
+ // so — unlike the `.mcp.json` staging above — this can run after `buildArgs` with no ordering
2479
+ // constraint of its own; it is placed here only to keep the two staging steps adjacent.
2480
+ preparedCodexHome = await prepareCodexHomeIfNeeded({ runId: input.runId, def, mcpBridge }, { mcpJsonInjection, hostEnv: process.env, releaseStagedResources, failBeforeSpawn });
2481
+ // `'config-instructions-file'`'s one effect — stage the overlay to a temp file so
2482
+ // `computeChildEnv` below has a real path to merge into that def's `instructions` array. A
2483
+ // no-op (`null`) for every other def/strategy or a run with no overlay at all. Independent of
2484
+ // `mcpBridge`/`preparedCodexHome` above (a different strategy field entirely), so placed here
2485
+ // only to stay adjacent to the other pre-`computeChildEnv` staging steps, not for any ordering
2486
+ // requirement between them.
2487
+ preparedSystemPromptOverlayFile = await prepareSystemPromptOverlayFileIfNeeded({ runId: input.runId, def, overlay: systemPromptOverlay }, { releaseStagedResources, failBeforeSpawn });
2488
+ // Computed only now, not right after `mcpBridge` resolution: mechanism 5's directory path is
2489
+ // not known until the staging step directly above actually runs `mkdtemp` (see
2490
+ // `McpBridgeDelivery`'s `'codex-toml'` variant doc for why it cannot be pre-computed the way
2491
+ // `'claude-mcp-json'`'s deterministic path is). Nothing between the old, earlier call site and
2492
+ // here ever read `childEnv`, so moving the call cost nothing.
2493
+ const childEnv = computeChildEnv(spawnEnv, mcpBridge, preparedCodexHome?.path, systemPromptEnvOverrides, preparedSystemPromptOverlayFile && def.systemPromptDelivery?.strategy === 'config-instructions-file'
2494
+ ? { varName: def.systemPromptDelivery.varName, path: preparedSystemPromptOverlayFile.path }
2495
+ : undefined);
1151
2496
  // Post-buildArgs guard for argv-bound defs whose resolved binary is a
1152
2497
  // Windows .cmd/.bat shim or a direct .exe: a prompt under the raw byte
1153
2498
  // budget can still expand past CreateProcess's command-line cap once
1154
2499
  // quote-escaped. Both are no-ops off-Windows / for non-argv-bound defs.
1155
- const windowsBudgetError = checkWindowsCmdShimCommandLineBudget(def, launch.launchPath, args) ??
1156
- checkWindowsDirectExeCommandLineBudget(def, launch.launchPath, args);
1157
- if (windowsBudgetError) {
1158
- await cleanupPromptFile();
1159
- return failBeforeSpawn(input.runId, 'AGENT_PROMPT_TOO_LARGE', windowsBudgetError.message);
2500
+ await guardWindowsCommandLineBudget({ runId: input.runId, def, launchPath: launch.launchPath, args }, { releaseStagedResources, failBeforeSpawn });
2501
+ const invocation = createCommandInvocationFn({ command: launch.launchPath, args, env: childEnv });
2502
+ // Kept a synchronous call (no `await`) on purpose — see `spawnAgentChildProcess`'s own doc for
2503
+ // the microtask-timing race this avoids. The error branch's own cleanup/failBeforeSpawn calls are
2504
+ // async, which is fine: no child exists yet on that path, so nothing is racing a listener.
2505
+ const spawnResult = spawnAgentChildProcess({ cwd: input.cwd, childEnv, invocation }, { spawn: spawnFn });
2506
+ if (spawnResult.kind === 'error') {
2507
+ await releaseStagedResources();
2508
+ return failBeforeSpawn(input.runId, 'AGENT_SPAWN_FAILED', `AgentExecutor: spawn threw synchronously for agent "${def.id}": ${errorMessage(spawnResult.error)}`);
1160
2509
  }
1161
- const invocation = createCommandInvocationFn({ command: launch.launchPath, args, env: spawnEnv });
1162
- let child;
1163
- try {
1164
- child = spawnFn(invocation.command, invocation.args, {
1165
- cwd: input.cwd,
1166
- env: spawnEnv,
1167
- stdio: ['pipe', 'pipe', 'pipe'],
1168
- windowsVerbatimArguments: invocation.windowsVerbatimArguments,
1169
- });
1170
- }
1171
- catch (err) {
1172
- await cleanupPromptFile();
1173
- return failBeforeSpawn(input.runId, 'AGENT_SPAWN_FAILED', `AgentExecutor: spawn threw synchronously for agent "${def.id}": ${errorMessage(err)}`);
1174
- }
1175
- const stdinHandle = streamFormat === 'acp-json-rpc' || streamFormat === 'pi-rpc'
1176
- ? null
1177
- : wireChildLifecycle({
2510
+ const child = spawnResult.child;
2511
+ // Registered before the spawn-confirmation await below, for the same reason
2512
+ // `wireChildLifecycle` is: a child that exits immediately must not slip past the listener.
2513
+ // `'exit'` rather than `'close'` on purpose — a `runtimeLock` guards state the *process* reads,
2514
+ // so the process being gone is the release condition, not its stdio pipes draining (which a
2515
+ // grandchild inheriting them can delay arbitrarily). A spawn that never produced a process at
2516
+ // all emits no `'exit'`, and is covered instead by `releaseStagedResources` on the reject path.
2517
+ child.once('exit', releaseRuntimeLock);
2518
+ const stdinHandle = isStdinDrivenFormat(streamFormat)
2519
+ ? wireChildLifecycle({
1178
2520
  runId: input.runId,
1179
2521
  def,
1180
2522
  streamFormat,
@@ -1184,94 +2526,73 @@ export function createAgentExecutor(options) {
1184
2526
  collectProcessTreePids: collectProcessTreePidsFn,
1185
2527
  stopProcesses: stopProcessesFn,
1186
2528
  onCleanupFailure: onCleanupFailureFn,
1187
- cleanupPromptFile,
2529
+ cleanupStagedFiles,
1188
2530
  journal,
1189
2531
  continuation,
1190
2532
  classifyFailure,
1191
- });
1192
- try {
1193
- await waitForSpawnOrError(child);
1194
- }
1195
- catch (err) {
1196
- await cleanupPromptFile();
1197
- await lifecycle.finish({ runId: input.runId, status: 'failed', code: null, signal: null, resumable: false });
1198
- throw new AgentExecutorError('AGENT_SPAWN_FAILED', `AgentExecutor: failed to spawn agent "${def.id}": ${errorMessage(err)}`);
1199
- }
2533
+ bufferedStdoutMaxBytes,
2534
+ })
2535
+ : null;
2536
+ await confirmChildSpawned({ runId: input.runId, def, child }, { releaseStagedResources, failBeforeSpawn });
2537
+ // Now — and only now — is there a live process that could consume the locked side effect, so
2538
+ // this is where a def's handoff watcher starts. Deliberately not awaited: the whole point is to
2539
+ // release the lock as soon as the child confirms the handoff, in parallel with this run
2540
+ // continuing. Rejection releases too a lock stuck open because a watcher threw is strictly
2541
+ // worse than releasing early (see `RuntimeLockHold.waitForHandoff`'s own doc).
2542
+ armHandoffWatcher(runtimeLockHold, { logFilePath: preparedLogFile?.path, model: selectedModel, processExited: processExitedController.signal }, releaseRuntimeLock);
1200
2543
  if (streamFormat === 'acp-json-rpc') {
1201
- try {
1202
- wireAcpLifecycle({
1203
- runId: input.runId,
1204
- agentId: def.id,
1205
- child,
1206
- lifecycle,
1207
- prompt: input.prompt,
1208
- cwd: input.cwd,
1209
- model: input.model,
1210
- imagePaths: input.imagePaths ?? [],
1211
- envFormat: def.acpMcpEnvFormat,
1212
- onPermissionRequest: options.acpPermissionHandler,
1213
- attachAcpSession: attachAcpSessionFn,
1214
- listProcessSnapshots: listProcessSnapshotsFn,
1215
- collectProcessTreePids: collectProcessTreePidsFn,
1216
- stopProcesses: stopProcessesFn,
1217
- onCleanupFailure: onCleanupFailureFn,
1218
- cleanupPromptFile,
1219
- journal,
1220
- classifyFailure,
1221
- });
1222
- }
1223
- catch (err) {
1224
- // Unlike the cancellation-listener call sites, we are already in an async function
1225
- // about to call finish() and throw — nothing else races this, so cleanup is awaited
1226
- // here rather than fired-and-forgotten (SEC-007: "await where lifecycle ordering allows it").
1227
- await terminateChildTreeBestEffort({
1228
- listProcessSnapshots: listProcessSnapshotsFn,
1229
- collectProcessTreePids: collectProcessTreePidsFn,
1230
- stopProcesses: stopProcessesFn,
1231
- }, child, input.runId, 'acp-attach-failure', onCleanupFailureFn);
1232
- await cleanupPromptFile();
1233
- await lifecycle.finish({ runId: input.runId, status: 'failed', code: null, signal: null, resumable: false });
1234
- throw new AgentExecutorError('AGENT_SPAWN_FAILED', `AgentExecutor: could not attach ACP session for agent \"${def.id}\": ${errorMessage(err)}`);
1235
- }
2544
+ await runAcpDispatch({
2545
+ runId: input.runId,
2546
+ agentId: def.id,
2547
+ child,
2548
+ prompt: input.prompt,
2549
+ cwd: input.cwd,
2550
+ model: input.model,
2551
+ imagePaths: input.imagePaths ?? [],
2552
+ envFormat: def.acpMcpEnvFormat,
2553
+ mcpBridge,
2554
+ }, {
2555
+ lifecycle,
2556
+ attachAcpSession: attachAcpSessionFn,
2557
+ onPermissionRequest: options.acpPermissionHandler,
2558
+ listProcessSnapshots: listProcessSnapshotsFn,
2559
+ collectProcessTreePids: collectProcessTreePidsFn,
2560
+ stopProcesses: stopProcessesFn,
2561
+ onCleanupFailure: onCleanupFailureFn,
2562
+ cleanupStagedFiles,
2563
+ journal,
2564
+ classifyFailure,
2565
+ releaseStagedResources,
2566
+ failBeforeSpawn,
2567
+ });
1236
2568
  return;
1237
2569
  }
1238
2570
  if (streamFormat === 'pi-rpc') {
1239
- try {
1240
- wirePiRpcLifecycle({
1241
- runId: input.runId,
1242
- agentId: def.id,
1243
- child,
1244
- lifecycle,
1245
- prompt: input.prompt,
1246
- cwd: input.cwd,
1247
- model: input.model,
1248
- imagePaths: input.imagePaths ?? [],
1249
- uploadRoot: input.uploadRoot,
1250
- attachPiRpcSession: attachPiRpcSessionFn,
1251
- listProcessSnapshots: listProcessSnapshotsFn,
1252
- collectProcessTreePids: collectProcessTreePidsFn,
1253
- stopProcesses: stopProcessesFn,
1254
- onCleanupFailure: onCleanupFailureFn,
1255
- cleanupPromptFile,
1256
- journal,
1257
- classifyFailure,
1258
- });
1259
- }
1260
- catch (err) {
1261
- // Same discipline as the ACP attach-failure path directly above: await cleanup here
1262
- // rather than fire-and-forget (SEC-007).
1263
- await terminateChildTreeBestEffort({
1264
- listProcessSnapshots: listProcessSnapshotsFn,
1265
- collectProcessTreePids: collectProcessTreePidsFn,
1266
- stopProcesses: stopProcessesFn,
1267
- }, child, input.runId, 'pi-rpc-attach-failure', onCleanupFailureFn);
1268
- await cleanupPromptFile();
1269
- await lifecycle.finish({ runId: input.runId, status: 'failed', code: null, signal: null, resumable: false });
1270
- throw new AgentExecutorError('AGENT_SPAWN_FAILED', `AgentExecutor: could not attach pi-rpc session for agent \"${def.id}\": ${errorMessage(err)}`);
1271
- }
2571
+ await runPiRpcDispatch({
2572
+ runId: input.runId,
2573
+ agentId: def.id,
2574
+ child,
2575
+ prompt: input.prompt,
2576
+ cwd: input.cwd,
2577
+ model: input.model,
2578
+ imagePaths: input.imagePaths ?? [],
2579
+ uploadRoot: input.uploadRoot,
2580
+ }, {
2581
+ lifecycle,
2582
+ attachPiRpcSession: attachPiRpcSessionFn,
2583
+ listProcessSnapshots: listProcessSnapshotsFn,
2584
+ collectProcessTreePids: collectProcessTreePidsFn,
2585
+ stopProcesses: stopProcessesFn,
2586
+ onCleanupFailure: onCleanupFailureFn,
2587
+ cleanupStagedFiles,
2588
+ journal,
2589
+ classifyFailure,
2590
+ releaseStagedResources,
2591
+ failBeforeSpawn,
2592
+ });
1272
2593
  return;
1273
2594
  }
1274
- writePromptToStdin(def, child, input.prompt, stdinHandle);
2595
+ writePromptToStdin(def, child, imageDelivery.prompt, stdinHandle);
1275
2596
  }
1276
2597
  return { run };
1277
2598
  }