@jini-ai/daemon 0.5.3 → 0.5.4

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 (72) hide show
  1. package/CHANGELOG.md +4 -0
  2. package/dist/agent-executor/contracts.d.ts +12 -10
  3. package/dist/agent-executor/contracts.js +0 -9
  4. package/dist/agent-executor/event-translation.d.ts +2 -2
  5. package/dist/agent-executor/event-translation.js +0 -2
  6. package/dist/agent-executor/events.d.ts +9 -4
  7. package/dist/agent-executor/events.js +21 -5
  8. package/dist/agent-executor/handoff.d.ts +1 -1
  9. package/dist/agent-executor/handoff.js +0 -1
  10. package/dist/agent-executor/launch.d.ts +1 -1
  11. package/dist/agent-executor/launch.js +22 -1
  12. package/dist/agent-executor/mcp-bridge.d.ts +2 -2
  13. package/dist/agent-executor/mcp-bridge.js +0 -2
  14. package/dist/agent-executor/model-receipts.d.ts +6 -0
  15. package/dist/agent-executor/model-receipts.js +26 -0
  16. package/dist/agent-executor.d.ts +7 -1665
  17. package/dist/agent-executor.js +7 -3007
  18. package/dist/core/read-only-tools.d.ts +130 -0
  19. package/dist/core/read-only-tools.js +115 -0
  20. package/dist/core/tool-audit.d.ts +131 -0
  21. package/dist/core/tool-audit.js +113 -0
  22. package/dist/http/active-context.d.ts +2 -2
  23. package/dist/http/agents.d.ts +8 -2
  24. package/dist/http/agents.js +6 -2
  25. package/dist/http/component-catalog.d.ts +2 -2
  26. package/dist/http/connectors.d.ts +17 -17
  27. package/dist/http/daemon-status.d.ts +2 -2
  28. package/dist/http/db-ops.d.ts +3 -3
  29. package/dist/http/delegated-tools.d.ts +1 -1
  30. package/dist/http/delegated-tools.js +1 -1
  31. package/dist/http/frontend-sessions.d.ts +1 -1
  32. package/dist/http/health.d.ts +6 -6
  33. package/dist/http/host-tools.d.ts +2 -2
  34. package/dist/http/media.d.ts +4 -4
  35. package/dist/http/memory.d.ts +15 -15
  36. package/dist/http/remote-run-events.d.ts +2 -2
  37. package/dist/http/research.d.ts +1 -1
  38. package/dist/http/routines.d.ts +7 -7
  39. package/dist/http/run-credentials.d.ts +2 -2
  40. package/dist/http/run-credentials.js +2 -2
  41. package/dist/http/runs.d.ts +4 -4
  42. package/dist/http/terminals.d.ts +6 -6
  43. package/dist/http/tool-catalog.d.ts +2 -2
  44. package/dist/http/xai.d.ts +6 -6
  45. package/dist/index.d.ts +75 -571
  46. package/dist/index.js +75 -571
  47. package/dist/read-only-tools.d.ts +1 -129
  48. package/dist/read-only-tools.js +2 -114
  49. package/dist/run-credentials.d.ts +47 -23
  50. package/dist/run-credentials.js +24 -8
  51. package/dist/scheduler.d.ts +5 -0
  52. package/dist/scheduler.js +13 -1
  53. package/dist/session-coordination.d.ts +58 -24
  54. package/dist/session-coordination.js +40 -12
  55. package/dist/store/event-log/sqlite.js +3 -3
  56. package/dist/surface-exchanges.d.ts +207 -61
  57. package/dist/surface-exchanges.js +167 -20
  58. package/dist/tool-audit.d.ts +1 -113
  59. package/dist/tool-audit.js +2 -94
  60. package/dist/tool-recovery/diagnostics.d.ts +132 -0
  61. package/dist/tool-recovery/diagnostics.js +110 -0
  62. package/dist/tool-recovery/federated-refusal.d.ts +92 -0
  63. package/dist/tool-recovery/federated-refusal.js +152 -0
  64. package/dist/tool-recovery/index.d.ts +6 -0
  65. package/dist/tool-recovery/index.js +6 -0
  66. package/dist/tool-recovery/recovery.d.ts +49 -0
  67. package/dist/tool-recovery/recovery.js +419 -0
  68. package/dist/tool-recovery/redaction.d.ts +166 -0
  69. package/dist/tool-recovery/redaction.js +192 -0
  70. package/dist/tool-recovery/stack.d.ts +69 -0
  71. package/dist/tool-recovery/stack.js +62 -0
  72. package/package.json +35 -12
@@ -1,3010 +1,10 @@
1
- import { messageContentWithImages } from './attachment-content.js';
2
1
  /**
3
- * `AgentExecutor` — the driver `RunLifecycle`'s own module doc names as the
4
- * missing piece: *"It does not spawn or signal a subprocess... A driver...
5
- * calls `emit()` for agent/stdout/stderr/error events, observes cancellation
6
- * via `onCancelRequested`, and calls `finish()` once it knows the real
7
- * outcome."* This module is that driver — it wires `@jini-ai/agent-runtime`'s
8
- * registry/launch-resolution/stream-parsers (previously a complete but
9
- * disconnected library, zero callers anywhere outside its own package) into
10
- * a real `node:child_process` spawn, feeding both `RunLifecycle.emit()` and
11
- * this package's own `@jini-ai/protocol` event envelope.
12
- *
13
- * ## v1 scope: all 24 registered agent defs
14
- *
15
- * `@jini-ai/agent-runtime`'s registry ships 24 built-in defs across four
16
- * `streamFormat` families. The JSON-stream-parser family — the four
17
- * `createXStreamHandler`-shaped parsers (`claude-stream-json`,
18
- * `json-event-stream`, `copilot-stream-json`, `qoder-stream-json`), covering
19
- * 9 defs (amp, codebuddy, claude, codex, cursor-agent, opencode, mimo,
20
- * copilot, qoder) — plus all 9 `acp-json-rpc` defs, plus the one `pi-rpc`
21
- * def (`pi`), are wired here. ACP and pi-rpc each own their own JSON-RPC
22
- * prompt-delivery protocol, so each takes its own lifecycle branch rather
23
- * than being treated as a stdout-tail parser; pi-rpc's events arrive through
24
- * the exact same `{type, ...}` vocabulary `translateAgentRuntimeEvent`
25
- * already handles for ACP/JSON-stream (confirmed by reading every
26
- * `mapPiRpcEvent` `send()` call site — no new translation code was needed),
27
- * so only the driver wiring (spawn → attach → cancel → finish) was new for it.
28
- *
29
- * All 5 `streamFormat: 'plain'` defs — grok-build, aider, deepseek, qwen,
30
- * antigravity — are also driven, per
31
- * `ADS-memory/reports/proposals/PROP-plain-format-agent-driving-2026-07-21.md`'s
32
- * recommended "Option B": no structured stream parser at all. By default
33
- * every raw `child.stdout` chunk is forwarded verbatim as a `text_delta`
34
- * `'agent'` event, live, as it arrives (see `wireChildLifecycle`'s
35
- * `streamFormat === 'plain'` branch). Prompt delivery across the 5 is not
36
- * uniform: qwen and antigravity already fit the pre-existing stdin-only
37
- * guard; grok-build stages the prompt to a temp file via
38
- * `preparePromptFileForAgent` (its path threaded into `buildArgs` through a
39
- * `RuntimeContext`, cleaned up after the child exits on every path,
40
- * including pre-spawn/spawn-failure ones); aider/deepseek carry the prompt
41
- * on argv and are guarded pre-spawn by `checkPromptArgvBudget` plus the two
42
- * Windows CreateProcess command-line-expansion guards
43
- * (`checkWindowsCmdShimCommandLineBudget`/`checkWindowsDirectExeCommandLineBudget`).
44
- *
45
- * ## Antigravity's two extra needs, met declaratively
46
- *
47
- * Antigravity was the one def this driver rejected outright, for two reasons
48
- * the proposal doc (§2c) scoped out to a follow-up: `agy` can print an OAuth
49
- * sign-in URL to stdout and *still exit 0*, so live streaming leaks it; and
50
- * its model choice is written into one process-global `settings.json` that
51
- * `agy` reads on its own startup, so two concurrent runs race on it.
52
- *
53
- * Both are now met through **declarative `RuntimeAgentDef` fields this driver
54
- * reads generically** — `needsAgentLogFile`, `stdoutPolicy`, `runtimeLock` —
55
- * not a `def.id === 'antigravity'` branch. That mirrors how all 14 of the
56
- * def's other optional behavior flags (`promptViaFile`, `authProbe`,
57
- * `capturesSessionIdFromStream`, …) already work, and it is a deliberate
58
- * divergence from OD's own `server.ts`, which hardcodes `def.id ===
59
- * 'antigravity'` twice. The three fields are no-ops for the other 23 defs,
60
- * none of which declares any of them — so nothing else's behavior changed.
61
- *
62
- * `run()` still rejects cleanly (never a bare throw) with an
63
- * `AgentExecutorError` for any def whose `streamFormat` or prompt-delivery
64
- * shape this driver does not implement — see `isSupportedStreamFormat` and
65
- * `assessAgentExecutorCompatibility`.
66
- *
67
- * ## Invariant
68
- *
69
- * `RunLifecycle.start()` already transitions a run to `'running'` before
70
- * `run()` is ever called. Every *pre-spawn* failure path in `run()` — unknown
71
- * `agentId`, an unsupported `streamFormat`/prompt-delivery shape, an
72
- * unresolvable binary, or a spawn error — calls `lifecycle.finish({status:
73
- * 'failed', resumable: false, code: null, signal: null})` itself before
74
- * rejecting, so a run can never get stuck `'running'` with no watchdog.
75
- * `resumable` is unconditionally `false` on these paths — there is no spawned
76
- * child, hence nothing a classifier could examine (see
77
- * `FailureClassificationContext`'s own doc).
78
- *
79
- * For a run that *did* spawn and then failed, `resumable` is decided by
80
- * `classifyFailure` (gap 4 — see `ClassifyFailure`'s own doc), an injectable
81
- * port with no default of its own in this module (`undefined` stays
82
- * byte-identical to pre-gap-4 behavior — every `'failed'` outcome
83
- * resumable:false). OD's ~20-vendor-CLI text-matching failure classifier was
84
- * deliberately never ported (see `run/core/failure-taxonomy.ts`'s own doc and
85
- * `archived provenance ledger`). The real zero-config classifier lives in `@jini-ai/daemon`'s
86
- * `run/core/retry.ts` (`resumableFromProcessExit`/`classifyProcessExitFailure`)
87
- * and is wired in by `@jini-ai/server`'s `createLocalNodeDaemon` — see that
88
- * package's own archived provenance ledger, and `run/core/retry.ts`'s own doc for the
89
- * classification policy and its 2026-07-22 merge-time reconciliation against
90
- * a second, independently-built (and rejected) classifier that once lived in
91
- * this module.
2
+ * Compatibility entry for the agent executor's original module path.
3
+ * The split implementation owns subprocess launch, credential delivery,
4
+ * cancellation, and run events. Named re-exports preserve the existing API
5
+ * and AgentExecutorError identity across this entry and the package barrel;
6
+ * wrappers or a second implementation would let tested and shipped behavior drift.
7
+ * See agent-executor/index.ts for the driver contracts and invariants.
92
8
  */
93
- import { spawn as nodeSpawn } from 'node:child_process';
94
- import { promises as fsPromises } from 'node:fs';
95
- import { homedir, tmpdir } from 'node:os';
96
- import { join } from 'node:path';
97
- import { redactSecrets } from '@jini-ai/core';
98
- import { agentCapabilities, applyAgentLaunchEnv, createClaudeStreamHandler, createCopilotStreamHandler, createJsonEventStreamHandler, createQoderStreamHandler, ensureAgentCapabilities, getAgentDef, resolveAgentLaunch, attachAcpSession, attachPiRpcSession, checkPromptArgvBudget, checkWindowsCmdShimCommandLineBudget, checkWindowsDirectExeCommandLineBudget, prepareAgentLogFile, preparePromptFileForAgent, } from '@jini-ai/agent-runtime';
99
- import { collectProcessTreePids, createCommandInvocation, listProcessSnapshots, stopProcesses, } from '@jini-ai/platform';
100
- import { classifyRunCloseStatus } from './close-status.js';
101
- import { resolveContinuationTransport } from './continuation/continuation-transport.js';
102
- import { resultContent } from './delegated-tool-bridge.js';
103
- import { applyImagePromptDelivery } from './image-prompt-delivery.js';
104
- import { extractResultMedia } from './tool-result-media.js';
105
- const SUPPORTED_STREAM_FORMATS = [
106
- 'claude-stream-json',
107
- 'json-event-stream',
108
- 'copilot-stream-json',
109
- 'qoder-stream-json',
110
- 'acp-json-rpc',
111
- 'pi-rpc',
112
- 'plain',
113
- ];
114
- /**
115
- * Narrows a `RuntimeAgentDef.streamFormat` string to the supported
116
- * families.
117
- * @param value - The def's raw `streamFormat` string.
118
- * @returns `true` when `value` is one of the JSON-stream-parser, ACP, pi-rpc, or plain formats this driver wires.
119
- * @complexity O(1) — fixed membership check.
120
- * @overallScore 100/100
121
- */
122
- export function isSupportedStreamFormat(args) {
123
- const { value } = args;
124
- return SUPPORTED_STREAM_FORMATS.includes(value);
125
- }
126
- /**
127
- * The single source of truth for whether this executor can drive a def.
128
- *
129
- * It exists because that knowledge was previously reachable only by *calling* `run()` and inspecting
130
- * the failure. Anything that lists agents for a user to pick from — a discovery route, an agent
131
- * picker, a CLI healthcheck — needs the same answer *before* a run exists, and had no way to ask it.
132
- * The observable symptom was a consumer advertising an agent that its own executor then rejected the
133
- * instant it was selected.
134
- *
135
- * `run()` consumes this rather than re-checking the conditions itself, so the discovery-time answer
136
- * and the run-time guards cannot disagree. A predicate that merely duplicated the guards would be
137
- * the same bug in a second location.
138
- *
139
- * @param def - The def to assess. Must be the **full** `RuntimeAgentDef`, not a projected
140
- * `DetectedAgent`: that type omits `maxPromptArgBytes`, one of the three prompt-delivery signals
141
- * checked here, so the argv-bound defs (`aider`, `deepseek`) would be misjudged as unsupported.
142
- * @returns A discriminated result — see {@link AgentExecutorCompatibility}. The `reason` text is
143
- * operator-facing and is what `run()` reports as its `AGENT_RUNTIME_UNSUPPORTED` message.
144
- * @complexity O(1) — fixed field checks.
145
- * @overallScore 100/100
146
- */
147
- export function assessAgentExecutorCompatibility({ def }) {
148
- const format = { value: def.streamFormat };
149
- if (!isSupportedStreamFormat(format)) {
150
- return {
151
- supported: false,
152
- reason: `AgentExecutor: agent "${def.id}" has streamFormat "${format.value}", which is not implemented in v1 — only ${SUPPORTED_STREAM_FORMATS.join(', ')} are supported`,
153
- };
154
- }
155
- const streamFormat = format.value;
156
- if (streamFormat !== 'acp-json-rpc' &&
157
- def.promptViaStdin !== true &&
158
- def.promptViaFile !== true &&
159
- typeof def.maxPromptArgBytes !== 'number') {
160
- return {
161
- supported: false,
162
- 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`,
163
- };
164
- }
165
- return { supported: true, streamFormat };
166
- }
167
- /**
168
- * Whether `run()` can actually drive this def — the discovery-time counterpart to the guards inside
169
- * `run()`, so a consumer never offers a user an agent that fails the moment it is selected.
170
- *
171
- * @param def - The full `RuntimeAgentDef`; see {@link assessAgentExecutorCompatibility} for why a
172
- * projected `DetectedAgent` is not sufficient.
173
- * @returns `true` when this executor would attempt the run.
174
- * @complexity O(1).
175
- * @overallScore 100/100
176
- */
177
- export function isAgentExecutorSupported({ def }) {
178
- return assessAgentExecutorCompatibility({ def: def }).supported;
179
- }
180
- /**
181
- * Selects and constructs the real stream-parser handler for a supported
182
- * `streamFormat`. `json-event-stream` additionally dispatches on
183
- * `def.eventParser` (the parser's own internal `kind` switch — e.g.
184
- * `'codex'`, `'cursor-agent'`, `'opencode'`; `mimo` shares `'opencode'`'s
185
- * `kind`); an unrecognized/absent `eventParser` degrades to that parser's
186
- * own `{type:'raw', line}` fallback rather than throwing, matching the
187
- * parser's own documented behavior. Never called for `streamFormat:
188
- * 'plain'` — `wireChildLifecycle` handles that format inline with no
189
- * parser at all (see `ChildDrivenStreamFormat`'s doc).
190
- * @param def - The resolved agent def (only `.eventParser` is read beyond `streamFormat`).
191
- * @param streamFormat - `def.streamFormat`, already narrowed by {@link isSupportedStreamFormat}.
192
- * @param onEvent - Sink the parser calls once per parsed (or malformed-raw) event.
193
- * @returns A `{feed, flush}` handle for the chosen parser.
194
- * @complexity O(1) dispatch; the returned handler's own per-chunk cost is the parser's.
195
- * @overallScore 100/100
196
- */
197
- function createStreamHandlerForDef(def, streamFormat, onEvent) {
198
- switch (streamFormat) {
199
- case 'claude-stream-json':
200
- return createClaudeStreamHandler({ onEvent: onEvent });
201
- case 'copilot-stream-json':
202
- return createCopilotStreamHandler({ onEvent: onEvent });
203
- case 'qoder-stream-json':
204
- return createQoderStreamHandler({ onEvent: onEvent });
205
- case 'json-event-stream':
206
- return createJsonEventStreamHandler({ kind: def.eventParser ?? '', onEvent: onEvent });
207
- }
208
- }
209
- function isRecord(value) {
210
- return typeof value === 'object' && value !== null && !Array.isArray(value);
211
- }
212
- function asString(value, fallback = '') {
213
- return typeof value === 'string' ? value : fallback;
214
- }
215
- function asOptionalString(value) {
216
- return typeof value === 'string' ? value : undefined;
217
- }
218
- function asOptionalNumber(value) {
219
- return typeof value === 'number' ? value : undefined;
220
- }
221
- /**
222
- * Narrows a parsed `usage` event's `usage` sub-object (`{input_tokens?, output_tokens?}`) — the one
223
- * piece of {@link translateUsagePayload} with real nested branching (an optional container holding
224
- * two optional numeric fields), extracted so that function reads as a flat field-by-field mapping.
225
- * @param rawUsage - `rawEvent.usage` once already narrowed to a record, or `undefined` when absent/malformed.
226
- * @returns `undefined` when neither token count is present — matching `translateUsagePayload`'s
227
- * original "omit the whole `usage` field rather than emit an empty object" behavior.
228
- * @complexity O(1).
229
- */
230
- export function extractUsageTokens({ rawUsage }) {
231
- if (!rawUsage)
232
- return undefined;
233
- const inputTokens = asOptionalNumber(rawUsage.input_tokens);
234
- const outputTokens = asOptionalNumber(rawUsage.output_tokens);
235
- if (inputTokens === undefined && outputTokens === undefined)
236
- return undefined;
237
- return {
238
- ...(inputTokens !== undefined ? { input_tokens: inputTokens } : {}),
239
- ...(outputTokens !== undefined ? { output_tokens: outputTokens } : {}),
240
- };
241
- }
242
- /**
243
- * Narrows one parsed `usage` event's loosely-typed fields into
244
- * `RunAgentPayload`'s `usage` variant. The 4 source parsers attach extra
245
- * fields this narrow payload has no room for — `thought_tokens`,
246
- * `cached_read_tokens`/`cached_write_tokens` (opencode/gemini/codex),
247
- * `modelUsage`/`stopReason`/`isError` (qoder), a top-level `stopReason`
248
- * (claude/copilot) — all intentionally dropped here, not carried through.
249
- * @param rawEvent - The raw `{type:'usage', ...}` record from a stream parser.
250
- * @returns The narrowed `RunAgentPayload` `usage` variant.
251
- * @complexity O(1).
252
- * @overallScore 100/100
253
- */
254
- function translateUsagePayload(rawEvent) {
255
- const rawUsage = isRecord(rawEvent.usage) ? rawEvent.usage : undefined;
256
- const usage = extractUsageTokens({ rawUsage: rawUsage });
257
- const costUsd = asOptionalNumber(rawEvent.costUsd);
258
- const durationMs = asOptionalNumber(rawEvent.durationMs);
259
- return {
260
- type: 'usage',
261
- ...(usage !== undefined ? { usage } : {}),
262
- ...(costUsd !== undefined ? { costUsd } : {}),
263
- ...(durationMs !== undefined ? { durationMs } : {}),
264
- };
265
- }
266
- export function translateStatusEvent({ rawEvent }) {
267
- const model = asOptionalString(rawEvent.model);
268
- const ttftMs = asOptionalNumber(rawEvent.ttftMs);
269
- const detail = asOptionalString(rawEvent.detail);
270
- const sessionId = asOptionalString(rawEvent.sessionId);
271
- return {
272
- kind: 'agent',
273
- payload: {
274
- type: 'status',
275
- label: asString(rawEvent.label, 'unknown'),
276
- ...(model !== undefined ? { model } : {}),
277
- ...(ttftMs !== undefined ? { ttftMs } : {}),
278
- ...(detail !== undefined ? { detail } : {}),
279
- },
280
- ...(sessionId !== undefined ? { sessionId } : {}),
281
- };
282
- }
283
- function translateTextDeltaEvent(rawEvent) {
284
- return { kind: 'agent', payload: { type: 'text_delta', delta: asString(rawEvent.delta) } };
285
- }
286
- function translateThinkingStartEvent() {
287
- return { kind: 'agent', payload: { type: 'thinking_start' } };
288
- }
289
- function translateThinkingDeltaEvent(rawEvent) {
290
- return { kind: 'agent', payload: { type: 'thinking_delta', delta: asString(rawEvent.delta) } };
291
- }
292
- function translateToolUseEvent(rawEvent) {
293
- return {
294
- kind: 'agent',
295
- payload: {
296
- type: 'tool_use',
297
- id: asString(rawEvent.id),
298
- name: asString(rawEvent.name),
299
- input: rawEvent.input ?? null,
300
- },
301
- };
302
- }
303
- function translateToolInputDeltaEvent(rawEvent) {
304
- return {
305
- kind: 'agent',
306
- payload: {
307
- type: 'tool_input_delta',
308
- id: asString(rawEvent.id),
309
- name: asString(rawEvent.name),
310
- delta: asString(rawEvent.delta),
311
- },
312
- };
313
- }
314
- export function translateToolResultEvent({ rawEvent }) {
315
- const isError = typeof rawEvent.isError === 'boolean' ? rawEvent.isError : undefined;
316
- return {
317
- kind: 'agent',
318
- payload: {
319
- type: 'tool_result',
320
- toolUseId: asString(rawEvent.toolUseId),
321
- content: asString(rawEvent.content),
322
- ...(isError !== undefined ? { isError } : {}),
323
- },
324
- };
325
- }
326
- function translateUsageEvent(rawEvent) {
327
- return { kind: 'agent', payload: translateUsagePayload(rawEvent) };
328
- }
329
- function translateRawEvent(rawEvent) {
330
- return { kind: 'agent', payload: { type: 'raw', line: asString(rawEvent.line) } };
331
- }
332
- export function translateErrorEvent({ rawEvent }) {
333
- const code = asOptionalString(rawEvent.code);
334
- const message = asString(rawEvent.message, 'Unknown agent error');
335
- return {
336
- kind: 'error',
337
- payload: { message, ...(code !== undefined ? { error: { code, message } } : {}) },
338
- };
339
- }
340
- export function translateTurnEndEvent({ rawEvent }) {
341
- // Claude-specific per-turn boundary. Not forwarded as an 'agent'
342
- // event (no RunAgentPayload variant represents it) — run() reacts to
343
- // it directly to close stdin (or, for gap 3, decide whether to inject
344
- // a tool result and keep it open instead). See module doc.
345
- const stopReason = asOptionalString(rawEvent.stopReason);
346
- return { kind: 'turn-end', ...(stopReason !== undefined ? { stopReason } : {}) };
347
- }
348
- /**
349
- * One entry per `rawEvent.type` this driver understands, each producing the same
350
- * {@link AgentRuntimeEventTranslation} `translateAgentRuntimeEvent` used to return from an inline
351
- * `switch` — replaced with this table (refactor-patterns' preferred fix for a long switch over an
352
- * event-kind discriminant) so each case's own mapping is independently readable and testable, and so
353
- * `translateAgentRuntimeEvent` itself is just a lookup plus the two upfront guards.
354
- */
355
- const EVENT_TYPE_TRANSLATORS = {
356
- status: rawEvent => translateStatusEvent({ rawEvent }),
357
- text_delta: translateTextDeltaEvent,
358
- thinking_start: translateThinkingStartEvent,
359
- thinking_delta: translateThinkingDeltaEvent,
360
- tool_use: translateToolUseEvent,
361
- tool_input_delta: translateToolInputDeltaEvent,
362
- tool_result: rawEvent => translateToolResultEvent({ rawEvent }),
363
- usage: translateUsageEvent,
364
- raw: translateRawEvent,
365
- error: rawEvent => translateErrorEvent({ rawEvent }),
366
- turn_end: rawEvent => translateTurnEndEvent({ rawEvent }),
367
- };
368
- /**
369
- * Narrows one parser-emitted `{type, ...}` record into this engine's
370
- * `RunAgentPayload` union (or the `error`/`turn-end`/`ignored` routing
371
- * `run()` special-cases). Pure — no I/O, no closure state — so every
372
- * variant each of the 4 supported parsers can produce is directly
373
- * assertable in isolation.
374
- *
375
- * Defensive by construction: several real parser emissions carry fields
376
- * looser than `RunAgentPayload`'s types promise (e.g. copilot's
377
- * `tool.execution_start` emits `id: data.toolCallId ?? null` — a literal
378
- * `null`, not the `string` `RunAgentPayload['tool_use']['id']` demands).
379
- * Every field read here is defensively coerced (`asString`/
380
- * `asOptionalString`/`asOptionalNumber`) rather than trusted, so a
381
- * malformed or null field degrades to a safe default instead of
382
- * propagating `null`/`undefined` into a field typed as required, or
383
- * throwing.
384
- *
385
- * @param rawEvent - One event as delivered to a stream parser's `onEvent` callback.
386
- * @returns The routing + payload this event maps to.
387
- * @complexity O(1) — one table lookup, no iteration.
388
- * @overallScore 100/100
389
- */
390
- export function translateAgentRuntimeEvent({ rawEvent }) {
391
- if (!isRecord(rawEvent) || typeof rawEvent.type !== 'string') {
392
- return { kind: 'ignored' };
393
- }
394
- const translator = EVENT_TYPE_TRANSLATORS[rawEvent.type];
395
- return translator ? translator(rawEvent) : { kind: 'ignored' };
396
- }
397
- /** Thrown by `AgentExecutor.run()` on every failure path — never a bare `Error`, so callers can branch on `.code` instead of parsing `.message`. */
398
- export class AgentExecutorError extends Error {
399
- code;
400
- constructor({ code, message }) {
401
- super(message);
402
- this.name = 'AgentExecutorError';
403
- this.code = code;
404
- }
405
- }
406
- function errorMessage(err) {
407
- return err instanceof Error ? err.message : String(err);
408
- }
409
- /**
410
- * Drops `undefined` values so `NodeJS.ProcessEnv` (whose values are
411
- * `string | undefined`) can feed `resolveAgentLaunch`'s
412
- * `Record<string, string>` parameter.
413
- * @param env - The source environment (the caller-supplied `input.env` escape hatch — the
414
- * default path builds its env via `buildAgentEnv` instead, never this function on `process.env`).
415
- * @returns A new object containing only the string-valued entries.
416
- * @complexity O(n) in the number of env entries.
417
- * @overallScore 100/100
418
- */
419
- function toStringEnvRecord(env) {
420
- const result = {};
421
- for (const [key, value] of Object.entries(env)) {
422
- if (typeof value === 'string')
423
- result[key] = value;
424
- }
425
- return result;
426
- }
427
- /**
428
- * Fixed baseline of host environment variables every spawned agent subprocess may see by
429
- * default — resolved from the host's env one name at a time, never derived programmatically
430
- * from `process.env` as a bag, so this can't silently widen. SEC-001's deny-by-default fix; see
431
- * `AgentExecutorRunInput.env`'s doc for the full threat model.
432
- */
433
- const BASELINE_AGENT_ENV_KEYS = [
434
- 'PATH', 'HOME', 'USERPROFILE', 'TMPDIR', 'TEMP', 'TMP', 'SHELL',
435
- 'LANG', 'LC_ALL', 'LC_CTYPE',
436
- // `USER` is required for a spawned `claude` CLI to find its own login/credential state — with
437
- // it omitted (even though `HOME` is present), `claude` fails fast with "Not logged in · Please
438
- // run /login" despite real credentials existing on disk/keychain. Confirmed by bisection against
439
- // a real authenticated `claude` install: `BASELINE_AGENT_ENV_KEYS` alone fails, adding back every
440
- // `CLAUDE_CODE_*`/`CLAUDECODE` var still fails, `LOGNAME`/`SSH_AUTH_SOCK` alone still fail, but
441
- // `USER` alone flips it to success. Login lookup requires the user identity
442
- // as well as the home directory.
443
- 'USER',
444
- 'SystemRoot', 'windir', 'ComSpec', 'PATHEXT', // Windows-only; harmless no-ops elsewhere
445
- ];
446
- /**
447
- * Deny-by-default agent subprocess environment: `BASELINE_AGENT_ENV_KEYS` resolved from
448
- * `hostEnv`, plus this run's explicitly-delegated credential(s) — never a passthrough of
449
- * `hostEnv` itself. Only reached when the caller omits `AgentExecutorRunInput.env`; supplying
450
- * `env` bypasses this function entirely (see its call site).
451
- */
452
- function buildAgentEnv(hostEnv, credentialEnv) {
453
- const result = {};
454
- for (const key of BASELINE_AGENT_ENV_KEYS) {
455
- const value = hostEnv[key];
456
- if (typeof value === 'string')
457
- result[key] = value;
458
- }
459
- for (const [key, value] of Object.entries(credentialEnv ?? {})) {
460
- result[key] = value;
461
- }
462
- return result;
463
- }
464
- /**
465
- * Resolves once `child` emits `'spawn'`, or rejects on `'error'`. Replicates
466
- * `@jini-ai/platform`'s own internal (non-exported) `waitForChildSpawn` race
467
- * idiom inline — see that module's `spawnLoggedProcess`/`spawnBackgroundProcess`.
468
- * @param child - The just-spawned `ChildProcess` to race.
469
- * @returns A promise settling on the first of `'spawn'`/`'error'` to fire.
470
- * @complexity O(1) — two one-time listener registrations.
471
- * @overallScore 100/100
472
- */
473
- function waitForSpawnOrError(child) {
474
- return new Promise((resolve, reject) => {
475
- child.once('error', reject);
476
- child.once('spawn', resolve);
477
- });
478
- }
479
- /**
480
- * Enumerates `child`'s full descendant process tree and stops it (SIGTERM →
481
- * SIGKILL escalation, via the injected `stopProcesses` port).
482
- * @param deps - The process-snapshot/tree-collection/stop ports (real `@jini-ai/platform` implementations by default — see {@link CreateAgentExecutorOptions}).
483
- * @param child - The child whose descendant tree should be terminated.
484
- * @returns Resolves once escalation completes (or immediately, as a no-op, if `child.pid` was never assigned — spawn never actually started).
485
- * @complexity O(p) in the number of live OS processes (`listProcessSnapshots`'s own cost) plus O(1) escalation rounds.
486
- * @overallScore 100/100
487
- */
488
- async function terminateChildTree(deps, child) {
489
- if (child.pid == null)
490
- return;
491
- const processes = await deps.listProcessSnapshots();
492
- const pids = deps.collectProcessTreePids({ processes, rootPids: [child.pid] });
493
- await deps.stopProcesses({ pids });
494
- }
495
- /** Default sink when a host does not supply `onCleanupFailure`: still observable, never silent. Redacted per SEC-007 (a spawn/permission error can embed paths/host detail). */
496
- function defaultCleanupFailureSink(context) {
497
- // eslint-disable-next-line no-console
498
- console.error(`[@jini-ai/daemon] agent-executor: process-tree cleanup failed for run "${context.runId}" (${context.phase}, pid=${context.pid})`, redactSecrets({ input: errorMessage(context.error) }));
499
- }
500
- /**
501
- * Reports a contained post-close failure through the host's sink, absorbing a throwing sink.
502
- *
503
- * A diagnostic sink is host code too, and the whole point of the two callers below is that nothing
504
- * between `'close'` and `finish()` can strand the run — a sink that throws must not reintroduce
505
- * exactly that. Same reasoning `run-lifecycle.ts`'s `handleInactivityTimeout` already applies to its
506
- * own `onInternalError`.
507
- */
508
- function reportPostCloseFailure(onCleanupFailure, context) {
509
- try {
510
- onCleanupFailure(context);
511
- }
512
- catch {
513
- // Nothing further can be done from here, and the terminal transition below still must happen.
514
- }
515
- }
516
- /**
517
- * Removes this run's staged files, reporting rather than propagating a failure.
518
- *
519
- * Unguarded, a rejecting cleanup (EBUSY, a temp directory yanked out from under the daemon, a host
520
- * stager bug) escaped the `void (async () => …)()` wrapper in each close handler and took `finish()`
521
- * with it: the child was already gone, yet the run stayed `'running'` forever — unfinishable and
522
- * unresumable — and the rejection surfaced only as an unhandled promise. A leaked temp file is a real
523
- * problem, but it is strictly smaller than a permanently stranded run, and reporting it keeps it
524
- * visible.
525
- */
526
- async function cleanupStagedFilesSafely(ctx) {
527
- try {
528
- await ctx.cleanupStagedFiles();
529
- }
530
- catch (error) {
531
- reportPostCloseFailure(ctx.onCleanupFailure, {
532
- runId: ctx.runId,
533
- phase: 'staged-file-cleanup',
534
- pid: ctx.child.pid,
535
- error,
536
- });
537
- }
538
- }
539
- /**
540
- * Resolves `finish()`'s `resumable` flag from the host's classifier, falling back to `false` when the
541
- * classifier itself rejects.
542
- *
543
- * `classifyFailure` is host-supplied and may do real work (a keystore read, an HTTP call), so it can
544
- * fail for reasons unrelated to this run. `false` is the right fallback: it is already the answer for
545
- * every run with no classifier configured at all, so an unavailable classifier degrades to the
546
- * documented default rather than losing the run.
547
- */
548
- async function classifyFailureSafely(ctx, classifyFailure, context) {
549
- try {
550
- return await classifyFailure(context);
551
- }
552
- catch (error) {
553
- reportPostCloseFailure(ctx.onCleanupFailure, {
554
- runId: ctx.runId,
555
- phase: 'failure-classification',
556
- pid: ctx.child.pid,
557
- error,
558
- });
559
- return false;
560
- }
561
- }
562
- /**
563
- * Fire-and-forget-safe wrapper around {@link terminateChildTree} for the cancellation paths
564
- * (a synchronous `onCancelRequested` listener, an ACP attach-failure catch) that observed this
565
- * promise with a bare `void` — silently swallowing any `listProcessSnapshots`/`stopProcesses`
566
- * rejection (e.g. EPERM — see `packages/platform/src/__tests__/process.test.ts`) and letting it
567
- * become an unhandled rejection, with descendants possibly still running and no diagnostic at
568
- * all (SEC-007). This never rejects: a tree-stop failure is reported through `onCleanupFailure`
569
- * (redacted) and followed by a best-effort direct kill of `child` itself, since the immediate
570
- * child is still worth trying even when tree enumeration/escalation failed.
571
- */
572
- function terminateChildTreeBestEffort(deps, child, runId, phase, onCleanupFailure) {
573
- return terminateChildTree(deps, child).catch((error) => {
574
- // `terminateChildTree` only reaches a rejecting call (rather than its own early return) once
575
- // its own `child.pid == null` guard has already passed, and a real ChildProcess's `pid` is
576
- // never unset after being assigned — so `child.pid` is provably a number here. The non-null
577
- // assertion documents that invariant instead of a `?? null` fallback that could never
578
- // actually be exercised (same pattern as `pi-rpc/session.ts`'s `resolveSessionPathChangedSince`).
579
- onCleanupFailure({ runId, phase, pid: child.pid, error });
580
- try {
581
- if (child.pid != null && !child.killed)
582
- child.kill('SIGKILL');
583
- }
584
- catch {
585
- // Best-effort only — nothing further can be done from here.
586
- }
587
- });
588
- }
589
- /**
590
- * Gap 1's byte-journal record for bytes the host sent to the child's stdin — always `trust:
591
- * 'trusted'`, since these are bytes this driver itself composed and wrote, not agent output. See
592
- * `packages/daemon/src/continuation/journal.ts`'s module doc.
593
- */
594
- function sentJournalEntry(content) {
595
- return { content, provenance: { source: 'host', channel: 'stdin' }, trust: 'trusted' };
596
- }
597
- /**
598
- * Gap 1's byte-journal record for bytes a child agent process produced on `channel` — always
599
- * `trust: 'untrusted'`, since this is attacker-influenceable agent output the kernel does not
600
- * control (see `@jini-ai/protocol`'s `JournalEntry` doc on why `trust` exists).
601
- */
602
- function receivedJournalEntry(channel, content) {
603
- return { content, provenance: { source: 'agent', channel }, trust: 'untrusted' };
604
- }
605
- const JINI_MCP_SERVER_KEY = 'jini';
606
- /** The run-error code a run gets when its CLI reports the injected `jini` bridge as anything but connected. */
607
- export const MCP_BRIDGE_UNAVAILABLE = 'MCP_BRIDGE_UNAVAILABLE';
608
- /**
609
- * Judges a CLI's startup report of the injected bridge. Returns the bridge's status (`'missing'`
610
- * when the list omits it) when it is not `'connected'`, and `undefined` when it is connected or
611
- * when `rawEvent` is not an init status carrying an MCP server list (nothing to judge).
612
- *
613
- * `'pending'` counts as a failure on purpose: the CLI decides which MCP tools a session has at
614
- * startup, so a bridge that is not connected by then never joins this run.
615
- * @param rawEvent - One parsed stream event, as `@jini-ai/agent-runtime`'s parser emits it.
616
- * @complexity O(n) in the number of reported servers.
617
- */
618
- export function unavailableJiniBridgeStatus({ rawEvent }) {
619
- if (!isRecord(rawEvent) || rawEvent.type !== 'status' || rawEvent.label !== 'initializing')
620
- return undefined;
621
- if (!Array.isArray(rawEvent.mcpServers))
622
- return undefined;
623
- const bridge = rawEvent.mcpServers.find((server) => isRecord(server) && server.name === JINI_MCP_SERVER_KEY);
624
- const status = isRecord(bridge) ? String(bridge.status) : 'missing';
625
- return status === 'connected' ? undefined : status;
626
- }
627
- /** The user-readable reason a run stopped because its bridge did not connect. */
628
- function bridgeUnavailableMessage(status) {
629
- return `The assistant's tools did not load (MCP bridge "${JINI_MCP_SERVER_KEY}" status: ${status}). The run was stopped instead of continuing without them.`;
630
- }
631
- /**
632
- * Builds this run's `mcpServers.jini` entry — pure and synchronous, so every field mapping is
633
- * directly assertable without touching the filesystem. The credential arrives already resolved:
634
- * `McpJsonInjectionOptions.credential` is a possibly-async per-run resolver, and awaiting it is
635
- * `writeMcpJsonForRun`'s job, which keeps the effect out of this function.
636
- *
637
- * @param runId - The run this entry scopes its child to.
638
- * @param options - `command`/`args`/`daemonUrl`/`env` from the host's injection options.
639
- * @param credential - The already-resolved bearer token, or `undefined` to omit `JINI_DAEMON_TOKEN`
640
- * entirely. Omitting produces byte-identical output to before this parameter existed.
641
- * @complexity O(1).
642
- * @overallScore 100/100
643
- */
644
- export function buildMcpJsonServerEntry({ runId, options }, { credential } = {}) {
645
- const hostEnv = Object.entries(options.env ?? {}).filter(([key]) => !key.startsWith('JINI_'));
646
- return {
647
- command: options.command,
648
- args: options.args !== undefined ? [...options.args] : [],
649
- env: {
650
- ...Object.fromEntries(hostEnv),
651
- JINI_RUN_ID: runId,
652
- JINI_DAEMON_URL: options.daemonUrl,
653
- ...(credential !== undefined ? { JINI_DAEMON_TOKEN: credential } : {}),
654
- },
655
- };
656
- }
657
- /**
658
- * Merges {@link JINI_MCP_SERVER_KEY} into an existing `.mcp.json`'s `mcpServers` map, preserving
659
- * every other key and every other registered server untouched. A missing (`existingRaw ===
660
- * undefined`), empty, or unparseable-as-a-JSON-object existing file all degrade to "start from an
661
- * empty document" rather than throwing — an unparseable project `.mcp.json` is a pre-existing
662
- * problem this driver did not create and cannot safely repair, so it is deliberately overwritten
663
- * with a fresh, valid file containing just this run's bridge entry rather than left broken or
664
- * left blocking the run. Pure — no I/O — so every branch is directly assertable.
665
- * @complexity O(1) plus `JSON.parse`/`JSON.stringify`'s own cost on a small config file.
666
- * @overallScore 100/100
667
- */
668
- export function mergeMcpJsonContent({ existingRaw, serverEntry }) {
669
- let doc = {};
670
- if (existingRaw !== undefined) {
671
- try {
672
- const parsed = JSON.parse(existingRaw);
673
- if (isRecord(parsed))
674
- doc = parsed;
675
- }
676
- catch {
677
- doc = {};
678
- }
679
- }
680
- const existingServers = isRecord(doc.mcpServers) ? doc.mcpServers : {};
681
- const mcpServers = { ...existingServers, [JINI_MCP_SERVER_KEY]: serverEntry };
682
- return `${JSON.stringify({ ...doc, mcpServers }, null, 2)}\n`;
683
- }
684
- /**
685
- * Mechanism 2 of 5 — `'acp-merge'`. Re-shapes the same bridge entry into the `mcpServers` element
686
- * an ACP `session/new` call carries, for the 9 ACP-native defs declaring this strategy (amr, devin,
687
- * hermes, kilo, kimi, kiro, reasonix, trae-cli, vibe). Pure.
688
- *
689
- * `env` is emitted as a plain object on purpose: `@jini-ai/agent-runtime`'s
690
- * `buildAcpSessionNewParams` already normalises a plain-object `env` into either the
691
- * `[{name, value}]` array form or the `{"KEY": "val"}` map form according to each def's own
692
- * `acpMcpEnvFormat`, so the per-vendor wire-shape difference stays in the one place that already
693
- * owns it rather than being re-decided here.
694
- *
695
- * **The credential travels in `env`, never in `args`.** An ACP agent spawns this server itself and
696
- * applies `env` to that child's environment; a token in `args` would land in the child's process
697
- * arguments, readable by any other local user via `ps`. Same rule as the `.mcp.json` path.
698
- *
699
- * @param entry - The shared bridge entry from {@link buildMcpJsonServerEntry}.
700
- * @returns A single-element list — this driver contributes exactly its own bridge server and never
701
- * removes or rewrites servers a def or host added by other means.
702
- * @complexity O(1).
703
- * @overallScore 100/100
704
- */
705
- export function buildAcpMcpBridgeServers({ entry }) {
706
- return [
707
- {
708
- type: 'stdio',
709
- name: JINI_MCP_SERVER_KEY,
710
- command: entry.command,
711
- args: [...entry.args],
712
- env: { ...entry.env },
713
- },
714
- ];
715
- }
716
- /**
717
- * Mechanism 3+4 of 5 — the spawn-env-content strategies. One map, not two code paths: OpenCode and
718
- * MiMo consume byte-identical JSON (MiMo's def doc: "the same JSON schema as OpenCode's `mcp`
719
- * config ... following the same structure as `OPENCODE_CONFIG_CONTENT`"), and differ only in which
720
- * env var carries it. Adding a third such CLI is a row here, not a new serializer.
721
- */
722
- const ENV_CONTENT_VAR_BY_STRATEGY = {
723
- 'opencode-env-content': 'OPENCODE_CONFIG_CONTENT',
724
- 'mimo-env-content': 'MIMOCODE_CONFIG_CONTENT',
725
- };
726
- /**
727
- * Serialises the bridge entry into the OpenCode-schema config JSON that `OPENCODE_CONFIG_CONTENT`
728
- * / `MIMOCODE_CONFIG_CONTENT` carries, merging into whatever the host already put in that variable
729
- * rather than replacing it — the same "merge, never clobber" discipline
730
- * {@link mergeMcpJsonContent} applies to `.mcp.json`, and for the same reason: a host may already
731
- * be handing the CLI the *user's* configured MCP servers through this exact variable, and
732
- * overwriting it would silently delete them.
733
- *
734
- * A missing, empty, or unparseable-as-a-JSON-object existing value degrades to "start from an empty
735
- * document". Overwriting an unparseable value is deliberate and matches `mergeMcpJsonContent`: this
736
- * driver did not create it, cannot safely repair it, and must not block the run on it.
737
- *
738
- * Emitted per server: `{type: 'local', command: [<command>, ...<args>], environment: {...},
739
- * enabled: true}` — the shape `@jini-ai/mcp`'s own `buildOpenCodeMcpConfigContent` emits for a
740
- * stdio server, so both producers stay schema-compatible.
741
- *
742
- * **The credential lands in `environment`, i.e. the MCP child's env — never in `command`.** OpenCode
743
- * spawns the bridge from `command`, so a token placed there would be visible in `ps` output to
744
- * every other local user. This is the same constraint that keeps `JINI_DAEMON_TOKEN` out of argv on
745
- * the `.mcp.json` and ACP paths.
746
- *
747
- * @param existingRaw - Whatever the spawn env already held for this variable, or `undefined`.
748
- * @param entry - The shared bridge entry from {@link buildMcpJsonServerEntry}.
749
- * @returns The full JSON string to set as the env var's value.
750
- * @complexity O(1) plus `JSON.parse`/`JSON.stringify` over a small config document.
751
- * @overallScore 100/100
752
- */
753
- export function mergeEnvContentMcpConfig({ existingRaw, entry }) {
754
- let doc = {};
755
- if (existingRaw !== undefined && existingRaw.length > 0) {
756
- try {
757
- const parsed = JSON.parse(existingRaw);
758
- if (isRecord(parsed))
759
- doc = parsed;
760
- }
761
- catch {
762
- doc = {};
763
- }
764
- }
765
- const existingMcp = isRecord(doc.mcp) ? doc.mcp : {};
766
- const mcp = {
767
- ...existingMcp,
768
- [JINI_MCP_SERVER_KEY]: {
769
- type: 'local',
770
- command: [entry.command, ...entry.args],
771
- environment: { ...entry.env },
772
- enabled: true,
773
- },
774
- };
775
- return JSON.stringify({ ...doc, mcp });
776
- }
777
- /**
778
- * Merges a staged system-prompt overlay file's path into the `instructions` array of the same
779
- * OpenCode-schema config document {@link mergeEnvContentMcpConfig} writes `mcp` into — for a
780
- * `systemPromptDelivery: { strategy: 'config-instructions-file' }` def (`opencode` today).
781
- *
782
- * Confirmed live (2026-09-01, opencode-cli 1.17.10), not inferred from docs alone:
783
- * 1. `instructions` is honored — a run configured with it visibly followed the file's directive
784
- * (a required exact-token prefix), while an identical run without it did not.
785
- * 2. It appends, never replaces: the same run that followed the custom instruction ALSO still
786
- * answered correctly using opencode's own baked-in environment-context system prompt (asked
787
- * for its cwd, with nothing about cwd anywhere in the custom instructions file) — proof
788
- * opencode's own defaults survive alongside a custom `instructions` entry, not just proof the
789
- * file was read at all.
790
- * 3. Adding this key alongside `mcp` in the same `OPENCODE_CONFIG_CONTENT` document disturbs
791
- * neither: in one combined run, the MCP bridge still got its connection attempt (logged
792
- * `key=jini type=local`) AND the custom instruction was still followed — same as running each
793
- * key alone.
794
- * 4. `instructions` is re-read fresh from the env on every spawn, including a `-s <id>`-resumed
795
- * turn (proved by swapping in a second instructions file between two turns of one resumed
796
- * session and seeing the second turn immediately reflect it while still recalling
797
- * conversation memory from turn one) — so this mechanism is safe to redeliver every turn like
798
- * `'append-flag'`/`'env-var'`, exempt from the prompt-prefix fallback's create-only gating
799
- * (see {@link resolveSystemPromptOverlayDelivery}'s doc): nothing here is ever baked into
800
- * opencode's own persisted session state the way re-injecting fallback prompt text would be.
801
- *
802
- * @param existingRaw - Whatever the spawn env already held for this variable (already possibly
803
- * carrying `mcp`, if `mergeEnvContentMcpConfig` ran first on the same value — order between the two
804
- * doesn't matter, each only touches its own top-level key), or `undefined`.
805
- * @param instructionsFilePath - The staged overlay file's absolute path (see
806
- * {@link prepareSystemPromptOverlayFileIfNeeded}).
807
- * @returns The full JSON string to set as the env var's value. Appends to, never clobbers, any
808
- * `instructions` entries already present — the same "merge, never clobber" discipline
809
- * {@link mergeEnvContentMcpConfig} applies to `mcp`, in case a host is already using this same
810
- * config-content variable to carry the operator's own instruction files.
811
- * @complexity O(1) plus `JSON.parse`/`JSON.stringify` over a small config document.
812
- * @overallScore 100/100
813
- */
814
- export function mergeEnvContentInstructions({ existingRaw, instructionsFilePath }) {
815
- let doc = {};
816
- if (existingRaw !== undefined && existingRaw.length > 0) {
817
- try {
818
- const parsed = JSON.parse(existingRaw);
819
- if (isRecord(parsed))
820
- doc = parsed;
821
- }
822
- catch {
823
- doc = {};
824
- }
825
- }
826
- const existingInstructions = Array.isArray(doc.instructions)
827
- ? doc.instructions.filter((entry) => typeof entry === 'string')
828
- : [];
829
- return JSON.stringify({ ...doc, instructions: [...existingInstructions, instructionsFilePath] });
830
- }
831
- /**
832
- * TOML basic-string escaping for the narrow value shapes {@link buildCodexMcpServerToml} emits (a
833
- * command name, an argv token, an env var value — never multi-line or control-character-heavy
834
- * text). Escapes exactly what TOML's basic-string grammar requires: backslash first (so it is not
835
- * re-escaped by a later replacement), then the quote delimiter, then the three whitespace control
836
- * characters a real command/argv/env value could plausibly contain.
837
- *
838
- * A hand-rolled minimal escaper rather than a TOML dependency — this mechanism never needs to
839
- * *parse* TOML (the real install's existing `config.toml` is appended after, never rewritten — see
840
- * {@link buildCodexHomeConfigToml}), so pulling in a full TOML library for one serialization shape
841
- * would be substantially more surface than the problem needs. Checked against the repo's existing
842
- * dependency graph first — no package here already depends on a TOML library.
843
- * @param value - The raw string to embed inside TOML `"..."` delimiters.
844
- * @returns The escaped text, WITHOUT the surrounding quotes — {@link tomlString} adds those.
845
- * @complexity O(n) in the string's length.
846
- */
847
- function escapeTomlBasicString(value) {
848
- return value
849
- .replace(/\\/g, '\\\\')
850
- .replace(/"/g, '\\"')
851
- .replace(/\n/g, '\\n')
852
- .replace(/\r/g, '\\r')
853
- .replace(/\t/g, '\\t');
854
- }
855
- /** Wraps {@link escapeTomlBasicString}'s output in the TOML basic-string delimiters. */
856
- function tomlString(value) {
857
- return `"${escapeTomlBasicString(value)}"`;
858
- }
859
- /** A TOML key: bare when TOML allows it, quoted otherwise — host-supplied bridge env names are not guaranteed bare-safe. */
860
- function tomlKey(key) {
861
- return /^[A-Za-z0-9_-]+$/.test(key) ? key : tomlString(key);
862
- }
863
- /**
864
- * Codex's per-tool deadline for the Jini bridge, in seconds: `@jini-ai/mcp`'s
865
- * `DEFAULT_DELEGATED_TOOL_TIMEOUT_MS` (6 min, mirrored because this package does not depend on
866
- * that one) plus 40 s. Codex's own default (60 s) is shorter than a delegated call parked on a
867
- * human dialog, and when Codex abandons a call the dialog stayed answerable, so a late click ran
868
- * an action the model had been told failed. Outlasting the bridge's deadline means the bridge
869
- * times out first, drops its daemon request, and the daemon expires the dialog. Codex does not
870
- * pass the parent env through to MCP servers, so the bridge under Codex always runs at its default.
871
- */
872
- const CODEX_TOOL_TIMEOUT_SEC = 6 * 60 + 40;
873
- /**
874
- * Mechanism 5 of 5 — `'codex-toml'`'s serialization step. Builds the `[mcp_servers.jini]` TOML
875
- * table (plus, when the entry carries any env vars, a separate `[mcp_servers.jini.env]` table)
876
- * Codex's own config schema expects.
877
- *
878
- * Confirmed against a real installed Codex CLI (0.151.0), not assumed from docs: round-tripping
879
- * `codex mcp add <name> --env K=V -- <cmd> <args>` against a scratch `CODEX_HOME` and reading back
880
- * `config.toml` produced exactly this shape (`command`/`args` as TOML strings/array in the main
881
- * table, env vars in a nested `.env` table) — see `archived provenance ledger` for the transcript.
882
- * @param entry - The shared bridge entry from {@link buildMcpJsonServerEntry}.
883
- * @returns A TOML fragment with no leading/trailing blank-line padding — {@link buildCodexHomeConfigToml} owns spacing when combining it with existing content.
884
- * @complexity O(n) in the number of argv/env entries.
885
- * @overallScore 100/100
886
- */
887
- export function buildCodexMcpServerToml({ entry }) {
888
- const argsLiteral = entry.args.map(tomlString).join(', ');
889
- const serverTable = `[mcp_servers.${JINI_MCP_SERVER_KEY}]\ncommand = ${tomlString(entry.command)}\nargs = [${argsLiteral}]\n` +
890
- `tool_timeout_sec = ${CODEX_TOOL_TIMEOUT_SEC}\n`;
891
- const envLines = Object.entries(entry.env)
892
- .filter((pair) => typeof pair[1] === 'string')
893
- .map(([key, value]) => `${tomlKey(key)} = ${tomlString(value)}`);
894
- if (envLines.length === 0)
895
- return serverTable;
896
- return `${serverTable}\n[mcp_servers.${JINI_MCP_SERVER_KEY}.env]\n${envLines.join('\n')}\n`;
897
- }
898
- /**
899
- * Splits a TOML table header's dotted key into its individual segments, honoring quoted parts
900
- * (`"basic"` or `'literal'`) that may themselves contain a literal `.` — a bare `.` only
901
- * separates segments outside of quotes. Each segment is trimmed and, if quoted, unwrapped.
902
- *
903
- * Not a full TOML parser: it does not resolve escape sequences (`\"`, `\u...`) inside basic
904
- * strings. That is deliberately out of scope — see {@link stripExistingJiniMcpServerTable}'s doc
905
- * for why it is safe to skip for this specific comparison.
906
- * @param rawKey - The raw text between a table header's `[` and `]`.
907
- * @returns The dotted key's segments, dequoted and trimmed.
908
- * @complexity O(n) in the length of `rawKey`.
909
- */
910
- function splitTomlDottedKey(rawKey) {
911
- const segments = [];
912
- let current = '';
913
- let quote = null;
914
- for (const ch of rawKey) {
915
- if (quote) {
916
- if (ch === quote)
917
- quote = null;
918
- else
919
- current += ch;
920
- continue;
921
- }
922
- if (ch === '"' || ch === "'") {
923
- quote = ch;
924
- continue;
925
- }
926
- if (ch === '.') {
927
- segments.push(current.trim());
928
- current = '';
929
- continue;
930
- }
931
- current += ch;
932
- }
933
- segments.push(current.trim());
934
- return segments;
935
- }
936
- /**
937
- * Removes any pre-existing `[mcp_servers.{@link JINI_MCP_SERVER_KEY}]` table — and its
938
- * `[mcp_servers.{@link JINI_MCP_SERVER_KEY}.*]` subtables (e.g. `.env`) — from a real Codex
939
- * `config.toml`'s raw text, so {@link buildCodexHomeConfigToml} can append this run's own table
940
- * without producing the duplicate TOML key Codex's parser rejects at startup.
941
- *
942
- * Line-oriented, not a real TOML parser (matching {@link buildCodexMcpServerToml}'s own
943
- * no-TOML-dependency constraint), but wide enough to survive a hand-edited config, which is the
944
- * scenario this whole function exists for. A table header line is recognized when, after
945
- * trimming, it is `[<key>]` optionally followed only by a `# comment` (TOML's own grammar allows
946
- * nothing else there) — so it tolerates leading indentation, whitespace inside the brackets, a
947
- * trailing line comment, and a dotted key written with quoted segments (`["mcp_servers"."jini"]`),
948
- * via {@link splitTomlDottedKey}. Once such a header's key matches the jini table or one of its
949
- * subtables, every following line is dropped until the next table header (of any name) or EOF.
950
- * Every other table, key, comment-only, and blank line is passed through untouched.
951
- *
952
- * Deliberately unhandled, and why it is safe to leave that way:
953
- * - **Escape sequences inside quoted key segments** (e.g. a segment containing `\"`) — neither
954
- * `mcp_servers` nor {@link JINI_MCP_SERVER_KEY} ever needs escaping, and this driver's own
955
- * writer ({@link buildCodexMcpServerToml}) never emits a quoted form at all, so no real
956
- * `config.toml` this driver produced can exercise this gap; a hand-edit that goes out of its
957
- * way to escape a character inside a key that is supposed to spell "jini" would fail to match
958
- * and fall back to today's pre-fix behavior (append a duplicate) rather than silently doing
959
- * something worse.
960
- * - **`[[array-of-tables]]` syntax** — Codex's schema has no array-of-tables shape for
961
- * `mcp_servers`, and the header regex's `[^[\]]+` capture cannot match a line starting with a
962
- * second `[`, so `[[mcp_servers.jini]]` is not recognized as a header before or after this fix
963
- * — unchanged, not a new gap.
964
- * - **A single quoted segment that happens to spell the same characters with the dot included**
965
- * (e.g. `["mcp_servers.jini"]`, which in real TOML names one key literally containing a `.`,
966
- * not two nested tables) — this collapses to the same joined string as the real nested-table
967
- * spelling and is therefore treated as a match. This is a false positive in the conservative
968
- * direction the reported bug calls for: a missed detection duplicates a key and crashes Codex,
969
- * so on this axis over-matching a spelling nobody would plausibly hand-write for an MCP server
970
- * table is preferable to under-matching the real one.
971
- * @param existingRaw - The real Codex home's `config.toml` content, already known to be defined
972
- * (callers pass `''` for a missing file).
973
- * @returns `existingRaw` with any jini table/subtable removed.
974
- * @complexity O(n) in the number of lines.
975
- */
976
- function stripExistingJiniMcpServerTable(existingRaw) {
977
- const jiniTableKey = `mcp_servers.${JINI_MCP_SERVER_KEY}`;
978
- const kept = [];
979
- let skipping = false;
980
- for (const line of existingRaw.split('\n')) {
981
- const header = /^\s*\[([^[\]]+)\]\s*(#.*)?$/.exec(line);
982
- if (header) {
983
- const key = splitTomlDottedKey(header[1] ?? '').join('.');
984
- skipping = key === jiniTableKey || key.startsWith(`${jiniTableKey}.`);
985
- if (skipping)
986
- continue;
987
- }
988
- if (!skipping)
989
- kept.push(line);
990
- }
991
- return kept.join('\n');
992
- }
993
- /**
994
- * Builds the full `config.toml` a run's scratch `CODEX_HOME` gets: the real Codex home's own
995
- * config, with any pre-existing `[mcp_servers.jini]` table removed (see
996
- * {@link stripExistingJiniMcpServerTable}), then this run's own table appended.
997
- *
998
- * **Append-only by design, not a parse-and-merge, for everything but the jini table itself.**
999
- * `mergeMcpJsonContent`/`mergeEnvContentMcpConfig` above can safely parse-merge-reserialize because
1000
- * their formats have a JS-native parser (`JSON.parse`); this driver has no general TOML parser in
1001
- * its dependency graph (see `buildCodexMcpServerToml`'s doc), and every other setting a real Codex
1002
- * install carries — model choice, sandbox policy, the trusted-project list, the operator's own
1003
- * other MCP servers — must survive a spawn byte-for-byte. Only the one table this driver itself
1004
- * owns (`jini` is this integration's own reserved server name — see {@link JINI_MCP_SERVER_KEY}) is
1005
- * ever removed, via the narrow line-oriented scan above, never a full TOML parse.
1006
- * @param existingRaw - The real Codex home's `config.toml` content, or `undefined` when it does not
1007
- * exist (a fresh Codex install — degrades to "start from just this run's block", matching
1008
- * {@link mergeMcpJsonContent}'s own "missing file" handling).
1009
- * @param entry - The shared bridge entry.
1010
- * @returns The full text to write to the scratch `CODEX_HOME`'s `config.toml`.
1011
- * @complexity O(n) in the existing config's length.
1012
- */
1013
- export function buildCodexHomeConfigToml({ existingRaw, entry }) {
1014
- const base = stripExistingJiniMcpServerTable(existingRaw ?? '');
1015
- const separator = base.length === 0 ? '' : base.endsWith('\n') ? '\n' : '\n\n';
1016
- return `${base}${separator}${buildCodexMcpServerToml({ entry: entry })}`;
1017
- }
1018
- /**
1019
- * Where `'codex-toml'` reads the operator's REAL Codex config from, to seed a run's scratch copy —
1020
- * never where it writes. Resolved against the daemon HOST process's own environment (`hostEnv`,
1021
- * `process.env` at the real call site), not a run's sandboxed spawn env: `CODEX_HOME` is not in
1022
- * `BASELINE_AGENT_ENV_KEYS`, so a spawned child never inherits it anyway, and the whole point here
1023
- * is finding wherever the *operator's actual* Codex install lives, which is a host-machine fact.
1024
- * @param hostEnv - The daemon process's own environment.
1025
- * @returns `hostEnv.CODEX_HOME` when set to a non-blank value (matching Codex's own resolution
1026
- * order), else the CLI's documented default, `~/.codex`.
1027
- * @complexity O(1).
1028
- * @overallScore 100/100
1029
- */
1030
- export function resolveSourceCodexHomeDir({ hostEnv }) {
1031
- const override = hostEnv.CODEX_HOME;
1032
- return override !== undefined && override.trim().length > 0 ? override : join(homedir(), '.codex');
1033
- }
1034
- /**
1035
- * **The single dispatch point from an `externalMcpInjection` strategy to its delivery mechanism.**
1036
- * Pure and synchronous — the one effectful input (the per-run bearer credential) arrives already
1037
- * resolved, so every strategy's mapping is directly assertable without touching the filesystem,
1038
- * the environment, or a keystore.
1039
- *
1040
- * Keyed off the declared *strategy*, never off `def.id`: a def gets a working bridge by declaring a
1041
- * mechanism, not by being named in this file. That is what makes the 9 `'acp-merge'` defs work
1042
- * without any of their own files being touched.
1043
- *
1044
- * @param input.cwd - The run's working directory; only `'claude-mcp-json'` uses it, to place this
1045
- * run's own config file (see {@link mcpJsonPathForRun}) — never `cwd/.mcp.json` itself.
1046
- * @param input.runId - Scopes the bridge child to this run.
1047
- * @param input.strategy - The def's declared `externalMcpInjection`, or `undefined` for a def with no native MCP transport.
1048
- * @param input.options - The host's bridge options, or `undefined` when the host never configured injection.
1049
- * @param input.credential - Already-resolved bearer token, or `undefined` to omit `JINI_DAEMON_TOKEN` entirely.
1050
- * @returns `null` when this run delivers nothing — an unconfigured host, or a def declaring no
1051
- * strategy — which is byte-identical to this feature not existing.
1052
- * @complexity O(1).
1053
- * @overallScore 100/100
1054
- */
1055
- export function buildMcpBridgeDelivery(input) {
1056
- const { cwd, runId, strategy, options, credential } = input;
1057
- if (options === undefined || strategy === undefined)
1058
- return null;
1059
- const serverEntry = buildMcpJsonServerEntry({ runId: runId, options: options }, credential === undefined ? {} : { credential });
1060
- switch (strategy) {
1061
- case 'claude-mcp-json':
1062
- return { kind: 'claude-mcp-json', mcpJsonPath: mcpJsonPathForRun(cwd, runId), serverEntry };
1063
- case 'acp-merge':
1064
- return { kind: 'acp-merge', mcpServers: buildAcpMcpBridgeServers({ entry: serverEntry }) };
1065
- case 'opencode-env-content':
1066
- case 'mimo-env-content':
1067
- return { kind: 'env-content', envVarName: ENV_CONTENT_VAR_BY_STRATEGY[strategy], serverEntry };
1068
- case 'codex-toml':
1069
- return { kind: 'codex-toml', serverEntry };
1070
- case 'env-passthrough':
1071
- return { kind: 'env-passthrough', serverEntry };
1072
- }
1073
- }
1074
- function defaultReadMcpJsonFile({ path }) {
1075
- return fsPromises.readFile(path, 'utf8');
1076
- }
1077
- function defaultWriteMcpJsonFile({ path, content }) {
1078
- return fsPromises.writeFile(path, content, 'utf8');
1079
- }
1080
- function defaultRemoveMcpJsonFile({ path }) {
1081
- return fsPromises.rm(path, { force: true });
1082
- }
1083
- /**
1084
- * This run's own MCP config path, inside `cwd` but deliberately **not** `cwd/.mcp.json`.
1085
- *
1086
- * A shared filename cannot carry two runs' identities at once, and that is exactly what the file
1087
- * carries: `mcpServers.jini.env` holds this run's `JINI_RUN_ID` and its bearer `JINI_DAEMON_TOKEN`.
1088
- * A spawned CLI reads its MCP config when it starts its client, not synchronously at spawn — so with
1089
- * one shared file, a second run in the same directory overwrote the entry the first run's child had
1090
- * not read yet, and that child's `jini-mcp` subprocess then called back carrying the *other* run's id
1091
- * and token: run A's tool calls executing inside run B's authority context. Concurrent runs in one
1092
- * working directory are supported by design (see `McpJsonInjectionOptions.credential`'s doc on why the
1093
- * credential is a per-run resolver at all), so the resolution is one file per run, not a lock that
1094
- * refuses the second run.
1095
- *
1096
- * Naming it after the run also means the project's own `.mcp.json` is never written at all — it stays
1097
- * purely a merge source, so there is no original content to restore afterwards either.
1098
- *
1099
- * The run id is host-supplied and lands in a filename, so everything outside `[A-Za-z0-9_-]` is
1100
- * replaced (dots included — a `..` segment must not survive) and the result is length-capped. Real run
1101
- * ids are UUIDs, which pass through untouched; the cap could in principle collide two ids sharing a
1102
- * 128-character prefix, which no id shape this daemon mints can produce.
1103
- * @complexity O(n) in the run id's length.
1104
- */
1105
- function mcpJsonPathForRun(cwd, runId) {
1106
- const safeRunId = runId.replace(/[^A-Za-z0-9_-]/g, '_').slice(0, 128);
1107
- return join(cwd, `.mcp.jini-${safeRunId}.json`);
1108
- }
1109
- /**
1110
- * The `'claude-mcp-json'` mechanism's one effect: writes (merging, never clobbering — see
1111
- * {@link mergeMcpJsonContent}) this run's own config — the project's own servers merged with this
1112
- * run's `jini` bridge entry — to the run-scoped path ({@link mcpJsonPathForRun}) the def was already
1113
- * handed via `RuntimeContext.mcpJsonPath`, so the def's own `--strict-mcp-config --mcp-config <path>`
1114
- * argv has a real file to point at by spawn time, instead of auto-discovering `cwd/.mcp.json` (which
1115
- * needs an interactive trust prompt a headless spawn can never answer — confirmed live 2026-07-30,
1116
- * see `@jini-ai/agent-runtime`'s `defs/claude.ts`).
1117
- *
1118
- * Reads `cwd/.mcp.json` and writes `delivery.mcpJsonPath`: the project's file is a merge source only,
1119
- * never a write target. See {@link mcpJsonPathForRun} for why one file per run is load-bearing rather
1120
- * than cosmetic, and why the read and write paths must differ.
1121
- *
1122
- * A no-op for every other delivery mechanism, which is expressed by the caller simply not having a
1123
- * `'claude-mcp-json'` delivery to hand it rather than by a strategy re-check in here.
1124
- * @param cwd - The run's working directory, so the project's own `.mcp.json` can be read as the
1125
- * merge base — not carried on `delivery` itself, since that only describes the write target.
1126
- * @param delivery - The already-built `'claude-mcp-json'` delivery (path + entry). Both fields come
1127
- * from {@link buildMcpBridgeDelivery}, so the credential was resolved exactly once, for this run.
1128
- * @param options - Supplies the injectable `readFile`/`writeFile` seams.
1129
- * @throws Whatever `writeFile` rejects with — the caller (`run()`) turns that into a pre-spawn
1130
- * `AGENT_SPAWN_FAILED` failure, matching every other pre-spawn filesystem guard in this file
1131
- * (`preparePromptFileForAgentFn`'s own try/catch).
1132
- * @complexity O(1) plus one `readFile`/`writeFile` round trip.
1133
- * @overallScore 100/100
1134
- */
1135
- async function writeMcpJsonForRun(cwd, delivery, options) {
1136
- const readFileFn = options.readFile ?? defaultReadMcpJsonFile;
1137
- const writeFileFn = options.writeFile ?? defaultWriteMcpJsonFile;
1138
- let existingRaw;
1139
- try {
1140
- existingRaw = await readFileFn({ path: join(cwd, '.mcp.json') });
1141
- }
1142
- catch {
1143
- // No existing file (ENOENT — the common case) or unreadable for any other reason: both
1144
- // degrade to "start fresh", matching mergeMcpJsonContent's own doc.
1145
- existingRaw = undefined;
1146
- }
1147
- await writeFileFn({ path: delivery.mcpJsonPath, content: mergeMcpJsonContent({ existingRaw: existingRaw, serverEntry: delivery.serverEntry }) });
1148
- }
1149
- function defaultMkdtempCodexHome({ prefix }) {
1150
- return fsPromises.mkdtemp(join(tmpdir(), prefix));
1151
- }
1152
- function defaultRemoveCodexHomeDir({ path }) {
1153
- return fsPromises.rm(path, { recursive: true, force: true });
1154
- }
1155
- function resolveCodexHomeSeams(options) {
1156
- return {
1157
- mkdtemp: options.mkdtemp ?? defaultMkdtempCodexHome,
1158
- readFile: options.readFile ?? defaultReadMcpJsonFile,
1159
- writeFile: options.writeFile ?? defaultWriteMcpJsonFile,
1160
- removeDir: options.removeDir ?? defaultRemoveCodexHomeDir,
1161
- };
1162
- }
1163
- /**
1164
- * Mechanism 5 of 5 — `'codex-toml'`'s one effect. Stages a fresh, randomly-named `CODEX_HOME`
1165
- * directory (see {@link McpJsonInjectionOptions.mkdtemp}'s doc for why non-deterministic naming is
1166
- * load-bearing here, not cosmetic) carrying:
1167
- * - `config.toml`: the real Codex home's own config (read best-effort — see
1168
- * {@link buildCodexHomeConfigToml}'s "missing file" handling) with this run's
1169
- * `[mcp_servers.jini]` table appended.
1170
- * - `auth.json`: a best-effort copy of the real Codex home's stored login, so the spawned CLI is
1171
- * still authenticated. Best-effort is safe here, not merely convenient: a real headless spawn
1172
- * against a `CODEX_HOME` with no `auth.json` at all was confirmed (against installed Codex CLI
1173
- * 0.151.0) to fail fast with a structured `401 Unauthorized` stream event, never an interactive
1174
- * login prompt or a hang — see `defs/codex.ts`'s module doc for the full transcript summary.
1175
- *
1176
- * **Never touches the real `CODEX_HOME`.** `sourceCodexHomeDir` is read-only throughout; nothing is
1177
- * ever written back to it.
1178
- *
1179
- * A failure after the directory is created (a rejecting `writeFile`, most plausibly) does not leak
1180
- * it: the directory may already hold a partial `config.toml` or a copied credential, so the
1181
- * `catch` below best-effort-removes it before rethrowing, exactly the "partial-failure state leak"
1182
- * class of bug this package's own adversarial-test-design guidance calls out.
1183
- * @param runId - Embedded in the temp-dir prefix for traceability, sanitized the same way
1184
- * `@jini-ai/agent-runtime`'s `prepareAgentLogFile`'s `label` is.
1185
- * @param entry - The shared bridge entry.
1186
- * @param sourceCodexHomeDir - Where to read the real install's `config.toml`/`auth.json` from — see {@link resolveSourceCodexHomeDir}.
1187
- * @param seams - Injectable mkdtemp/readFile/writeFile/removeDir, real filesystem by default.
1188
- * @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.
1189
- * @complexity O(1) plus one directory creation and up to two best-effort file read/write round trips.
1190
- * @overallScore 100/100
1191
- */
1192
- async function prepareCodexHomeForRun(runId, entry, sourceCodexHomeDir, seams) {
1193
- // Stricter than `@jini-ai/agent-runtime`'s `prepareAgentLogFile`/`preparePromptFileForAgent`
1194
- // labels (which keep dots): this prefix stages a directory that ends up holding a copied Codex
1195
- // login credential, so it gets `mcpJsonPathForRun`'s tighter discipline instead — dots stripped
1196
- // too, not just path separators, so a run id like `../../etc/evil` cannot leave even a cosmetic
1197
- // `..` substring in the mkdtemp prefix.
1198
- const safeRunId = runId.replace(/[^A-Za-z0-9_-]/g, '-').slice(0, 80) || 'run';
1199
- const dir = await seams.mkdtemp({ prefix: `jini-codex-home-${safeRunId}-` });
1200
- try {
1201
- let existingConfigRaw;
1202
- try {
1203
- existingConfigRaw = await seams.readFile({ path: join(sourceCodexHomeDir, 'config.toml') });
1204
- }
1205
- catch {
1206
- // No config yet (fresh Codex install) or unreadable — start from just this run's block,
1207
- // matching writeMcpJsonForRun's identical "missing file" handling.
1208
- existingConfigRaw = undefined;
1209
- }
1210
- await seams.writeFile({ path: join(dir, 'config.toml'), content: buildCodexHomeConfigToml({ existingRaw: existingConfigRaw, entry: entry }) });
1211
- try {
1212
- const authRaw = await seams.readFile({ path: join(sourceCodexHomeDir, 'auth.json') });
1213
- await seams.writeFile({ path: join(dir, 'auth.json'), content: authRaw });
1214
- }
1215
- catch {
1216
- // No stored login (or unreadable) — the spawned CLI runs unauthenticated. Confirmed above:
1217
- // this fails the run fast and observably, never as a hang.
1218
- }
1219
- }
1220
- catch (err) {
1221
- await seams.removeDir({ path: dir }).catch(() => {
1222
- // Best-effort only — the original error below is what the caller must see either way.
1223
- });
1224
- throw err;
1225
- }
1226
- return {
1227
- path: dir,
1228
- cleanup: async () => {
1229
- await seams.removeDir({ path: dir });
1230
- },
1231
- };
1232
- }
1233
- function defaultMkdtempClaudeConfigDir({ prefix }) {
1234
- return fsPromises.mkdtemp(join(tmpdir(), prefix));
1235
- }
1236
- function defaultRemoveClaudeConfigDir({ path }) {
1237
- return fsPromises.rm(path, { recursive: true, force: true });
1238
- }
1239
- function resolveClaudeConfigDirSeams(options) {
1240
- return {
1241
- mkdtemp: options?.mkdtemp ?? defaultMkdtempClaudeConfigDir,
1242
- readFile: options?.readFile ?? defaultReadMcpJsonFile,
1243
- writeFile: options?.writeFile ?? defaultWriteMcpJsonFile,
1244
- removeDir: options?.removeDir ?? defaultRemoveClaudeConfigDir,
1245
- };
1246
- }
1247
- /**
1248
- * Where `claude`'s own config resolution reads the operator's REAL config from, to seed a run's
1249
- * scratch copy — never where it writes. Mirrors {@link resolveSourceCodexHomeDir}'s exact reasoning
1250
- * and resolution order: `CLAUDE_CONFIG_DIR` is not in `BASELINE_AGENT_ENV_KEYS`, so a spawned child
1251
- * never inherits it anyway — the whole point is finding wherever the *operator's actual* Claude Code
1252
- * install lives, a host-machine fact resolved against the daemon HOST process's own environment.
1253
- * @param hostEnv - The daemon process's own environment.
1254
- * @returns `hostEnv.CLAUDE_CONFIG_DIR` when set to a non-blank value (matching Claude Code's own
1255
- * resolution order, confirmed against installed Claude Code 2.1.263), else the CLI's documented
1256
- * default, `~/.claude`.
1257
- * @complexity O(1).
1258
- */
1259
- export function resolveSourceClaudeConfigDir({ hostEnv }) {
1260
- const override = hostEnv.CLAUDE_CONFIG_DIR;
1261
- return override !== undefined && override.trim().length > 0 ? override : join(homedir(), '.claude');
1262
- }
1263
- /**
1264
- * Stages a fresh, randomly-named `CLAUDE_CONFIG_DIR` directory (same non-determinism requirement as
1265
- * {@link McpJsonInjectionOptions.mkdtemp}'s own doc — `os.tmpdir()` is a shared location on a
1266
- * multi-user host, so a guessable name is a real pre-plant/symlink target).
1267
- *
1268
- * **Deliberately empty by default** — unlike {@link prepareCodexHomeForRun}, which copies the real
1269
- * `config.toml` wholesale (Codex has no personal-data problem in that file), this directory gets
1270
- * NOTHING written into it beyond a best-effort copy of `.credentials.json` (see below). That is the
1271
- * fix: the operator's real `skills`/`plugins`/`agents`/`memory-path index`/`settings.json` must NOT
1272
- * carry over implicitly. `claude` runs correctly against a config directory holding nothing at all —
1273
- * it falls back to its own built-in defaults, not an error.
1274
- *
1275
- * **Login preservation, verified rather than assumed** (per this task's own instruction — "prove
1276
- * login still resolves; do not assume"): confirmed live (2026-09-07, installed Claude Code 2.1.263,
1277
- * macOS) that `claude auth status` reports `loggedIn: false` against ANY `CLAUDE_CONFIG_DIR` other
1278
- * than the operator's real one — including the real `HOME` with only `CLAUDE_CONFIG_DIR` swapped —
1279
- * and confirmed against Claude Code's own docs (code.claude.com/docs/en/authentication) why: "If
1280
- * you've set the CLAUDE_CONFIG_DIR environment variable, Claude Code keeps the .credentials.json
1281
- * file under that directory instead, including the file the macOS fallback writes, and keys the
1282
- * macOS Keychain entry to that directory too, so a session with a different CLAUDE_CONFIG_DIR reads
1283
- * a different entry." So a scratch directory is never logged in by default on ANY platform, not just
1284
- * the ones with no Keychain at all. This function only closes the *portable* case: when the source
1285
- * directory holds a file-based `.credentials.json` (Linux, Windows, or a Keychain-locked macOS
1286
- * fallback — none of which this function can distinguish, and does not need to), it is copied
1287
- * best-effort into the scratch directory, exactly `prepareCodexHomeForRun`'s `auth.json` copy. When
1288
- * it does not (a normal macOS Keychain-only install, confirmed the common case on this codebase's
1289
- * own dev machine), this function does NOT attempt to read the macOS Keychain itself — that would
1290
- * mean this daemon process extracting a live OAuth secret out of an OS-managed credential store into
1291
- * a plaintext file, a materially different and larger security surface than forwarding an
1292
- * already-resolved credential the host handed it (which `credentialEnv`/`ANTHROPIC_API_KEY` already
1293
- * does, safely, today — see `AgentExecutorRunInput.credentialEnv`'s own doc). In that case this
1294
- * mirrors `prepareCodexHomeForRun`'s own accepted outcome for a missing credential file verbatim:
1295
- * "the spawned CLI runs unauthenticated" is documented, existing, precedented behavior in this file,
1296
- * not a new failure mode invented here. A host that needs the isolated child to stay logged in on
1297
- * such an install must supply a credential explicitly via `AgentExecutorRunInput.credentialEnv`
1298
- * (`ANTHROPIC_API_KEY` or `CLAUDE_CODE_OAUTH_TOKEN` — both outrank Keychain-based subscription login
1299
- * in Claude Code's own auth precedence, so the isolated child authenticates without ever needing the
1300
- * operator's personal Keychain entry at all) — see this fix's own handoff report for the operational
1301
- * consequence on a host with no such credential configured yet.
1302
- *
1303
- * **Never touches the real config directory.** `sourceConfigDir` is read-only throughout.
1304
- * @param runId - Embedded in the temp-dir prefix for traceability, same sanitization discipline as {@link prepareCodexHomeForRun}'s `safeRunId`.
1305
- * @param sourceConfigDir - Where to read a possible real `.credentials.json` from — see {@link resolveSourceClaudeConfigDir}.
1306
- * @param seams - Injectable mkdtemp/readFile/writeFile/removeDir, real filesystem by default.
1307
- * @throws Whatever `mkdtemp` rejects with — the caller ({@link prepareClaudeConfigDirIfNeeded}) turns that into a pre-spawn `AGENT_SPAWN_FAILED` failure, matching {@link prepareCodexHomeForRun}'s own contract.
1308
- * @complexity O(1) plus one directory creation and up to one best-effort file read/write round trip.
1309
- */
1310
- async function prepareClaudeConfigDirForRun(runId, sourceConfigDir, seams) {
1311
- const safeRunId = runId.replace(/[^A-Za-z0-9_-]/g, '-').slice(0, 80) || 'run';
1312
- const dir = await seams.mkdtemp({ prefix: `jini-claude-config-${safeRunId}-` });
1313
- try {
1314
- const credentialsPath = join(sourceConfigDir, '.credentials.json');
1315
- let credentialsRaw;
1316
- try {
1317
- credentialsRaw = await seams.readFile({ path: credentialsPath });
1318
- }
1319
- catch {
1320
- // No file-based credential to copy (the common macOS-Keychain-only case) — see this
1321
- // function's own doc for why that is an accepted, documented outcome, not a failure here.
1322
- credentialsRaw = undefined;
1323
- }
1324
- if (credentialsRaw !== undefined) {
1325
- await seams.writeFile({ path: join(dir, '.credentials.json'), content: credentialsRaw });
1326
- }
1327
- }
1328
- catch (err) {
1329
- await seams.removeDir({ path: dir }).catch(() => {
1330
- // Best-effort only — the original error below is what the caller must see either way.
1331
- });
1332
- throw err;
1333
- }
1334
- return {
1335
- path: dir,
1336
- cleanup: async () => {
1337
- await seams.removeDir({ path: dir });
1338
- },
1339
- };
1340
- }
1341
- /**
1342
- * Default ceiling on the `'until-close'` stdout accumulator (see `RuntimeStdoutPolicy` in
1343
- * `@jini-ai/agent-runtime`), in bytes of received UTF-8.
1344
- *
1345
- * A buffered def holds its child's entire stdout in one in-memory string until the process closes,
1346
- * which is exactly what makes the accumulator a denial-of-service surface: the child is a
1347
- * prompt-influenced agent CLI this driver already treats as potentially adversarial (SEC-001), and
1348
- * nothing obliges it to ever close or to stop emitting. Without a ceiling one run could exhaust the
1349
- * daemon's heap and take every unrelated run in the process down with it.
1350
- *
1351
- * 8 MiB is chosen to sit far above any real buffered-agent transcript (antigravity's print-mode
1352
- * output — the only `'until-close'` def — is a few KiB of auth prompt and result text) while staying
1353
- * small enough that a hostile child cannot meaningfully pressure the heap. A host that genuinely
1354
- * needs more passes `CreateAgentExecutorOptions.bufferedStdoutMaxBytes`.
1355
- */
1356
- export const DEFAULT_BUFFERED_STDOUT_MAX_BYTES = 8 * 1024 * 1024;
1357
- /**
1358
- * The host-authored note appended to a truncated flush. Written *after* the def's own `sanitize`
1359
- * runs, never before: it is this driver's own text, not agent output, and passing it through a
1360
- * consumer-supplied redactor could silently delete the one line that says output is missing.
1361
- */
1362
- function bufferedStdoutTruncationNotice(droppedBytes, maxBytes) {
1363
- return `\n[jini] agent stdout truncated: ${droppedBytes} byte(s) dropped after the ${maxBytes}-byte buffer limit was reached.\n`;
1364
- }
1365
- /**
1366
- * Wires one spawned child's full observable lifecycle: raw stdout/stderr
1367
- * forwarding, structured stream-parser dispatch (translated via
1368
- * {@link translateAgentRuntimeEvent}), cancellation (subscribes
1369
- * `lifecycle.onCancelRequested` and escalates via `stopProcesses` on the
1370
- * child's full descendant tree), and the terminal `close` → `finish()`
1371
- * transition. Registered *before* the caller awaits spawn confirmation so
1372
- * no early `'error'`/`'close'` event is ever missed.
1373
- *
1374
- * Every `lifecycle.emit()` call is funneled through a per-run FIFO queue
1375
- * (`enqueueEmit`) rather than fired independently: a single stdout `data`
1376
- * chunk can synchronously produce several parsed events (a JSON line's
1377
- * `feed()` call may invoke `onEvent` more than once), and successive
1378
- * `data` events must not have their derived `emit()` calls race each
1379
- * other out of order. The queue also absorbs an individual `emit()`
1380
- * rejection (e.g. a race against an already-terminal run) without losing
1381
- * subsequently queued events, and the `close` handler awaits it fully
1382
- * drained before computing the terminal outcome — so `finish()`'s `'end'`
1383
- * event is always durably last, never interleaved with a still-in-flight
1384
- * `'agent'`/`'stdout'`/`'stderr'` append.
1385
- *
1386
- * `streamFormat: 'plain'` gets no `createStreamHandlerForDef` parser at
1387
- * all (Option B — see module doc and
1388
- * `ADS-memory/reports/proposals/PROP-plain-format-agent-driving-2026-07-21.md`
1389
- * §3): every raw stdout chunk is forwarded verbatim as a `text_delta`
1390
- * `'agent'` event, through the same `enqueueEmit` FIFO queue every other
1391
- * emit already goes through — no new parser state machine.
1392
- * **Deliberately un-hygiened for v1**: no ANSI/terminal-control-sequence
1393
- * stripping is applied (there is no Jini equivalent of OD's
1394
- * `TerminalControlSequenceStripper` yet) — a documented decision, not an
1395
- * oversight; see `packages/daemon/archived provenance ledger`'s 2026-07-21 addition for
1396
- * the reasoning.
1397
- *
1398
- * *When* those chunks leave is the def's call, via `def.stdoutPolicy`:
1399
- *
1400
- * - `'live'` (the default, and every def but antigravity) — emit per
1401
- * chunk, as it arrives.
1402
- * - `'until-close'` — accumulate, and emit the whole thing exactly once
1403
- * from the `close` handler, after `def.stdoutPolicy.sanitize`. For an
1404
- * adapter that can print a secret to stdout and still exit 0, no
1405
- * per-chunk decision is safe: the pattern to redact can straddle two
1406
- * `'data'` events.
1407
- *
1408
- * The buffered path holds back the raw `'stdout'` echo too, not just the
1409
- * `'agent'`/`text_delta`, and sanitizes both. Emitting an unsanitized raw
1410
- * echo while withholding the chat copy would leak the exact string the
1411
- * sanitizer exists to remove to any client subscribed to the run's events —
1412
- * the raw channel is a different *purpose*, not a different audience.
1413
- * `journal` is the one thing still recorded per-chunk and verbatim: it is
1414
- * the host's own byte record, deliberately kept in a **separate** `EventLog`
1415
- * instance that is never replayed to run-event subscribers (see
1416
- * `continuation/journal.ts`'s module doc), and "every byte received" is its
1417
- * whole contract.
1418
- *
1419
- * @param ctx - Run/def/child/lifecycle plus the cancellation-escalation ports.
1420
- * @returns A handle exposing `closeStdinOnce` for the initial prompt write to share.
1421
- * @complexity Registration is O(1); steady-state per-chunk cost is the
1422
- * chosen stream parser's own `feed()` cost plus O(1) queue bookkeeping.
1423
- * @overallScore 100/100
1424
- */
1425
- function wireChildLifecycle(ctx) {
1426
- const { runId, def, streamFormat, child, lifecycle, journal, continuation, classifyFailure } = ctx;
1427
- let stdinClosed = false;
1428
- let cancelRequested = false;
1429
- let emitQueue = Promise.resolve();
1430
- // Gap 5 (session resume) — the last session/thread id a 'status' event reported, threaded into
1431
- // finish()'s sessionRef below. `streamFormat === 'plain'` defs have no structured parser and
1432
- // therefore never populate this — an honest scope limit, not an oversight.
1433
- let capturedSessionId;
1434
- // Real `FailureClassificationContext.sideEffects` signals (2026-07-22) — see that interface's
1435
- // own doc for exactly what these two mean and why the other two `RunRetrySideEffectState`
1436
- // fields aren't tracked here at all.
1437
- let userVisibleOutputSeen = false;
1438
- let toolCallSeen = false;
1439
- // Gap 3 (stdin-tool-result injection) — the most recently reported tool_use, cleared once
1440
- // consumed by a turn-end injection decision. See `ContinuationOptions`'s doc for why this is
1441
- // only ever acted on when a host has explicitly allowlisted the tool's name.
1442
- let pendingToolUse;
1443
- // Bridge guard (see `expectsJiniBridge`): checked on the first init frame only. Once the bridge is
1444
- // found unavailable, the child is being stopped and nothing it still prints is forwarded.
1445
- let bridgeChecked = !ctx.expectsJiniBridge;
1446
- let bridgeUnavailable = false;
1447
- // `def.stdoutPolicy` read once, up front, so the per-chunk handler below is a single boolean
1448
- // test rather than a repeated union narrowing. `undefined` (every def but antigravity) means
1449
- // live — see this function's own doc.
1450
- const stdoutPolicy = def.stdoutPolicy;
1451
- const bufferStdoutUntilClose = stdoutPolicy?.buffering === 'until-close';
1452
- const sanitizeBufferedStdout = stdoutPolicy?.buffering === 'until-close' ? stdoutPolicy.sanitize : undefined;
1453
- // Accumulator for the `'until-close'` path. Stays `''` for every live def, and the flush below
1454
- // is then a no-op that emits nothing. Bounded by `ctx.bufferedStdoutMaxBytes` — see
1455
- // {@link DEFAULT_BUFFERED_STDOUT_MAX_BYTES} for why an unbounded accumulator was a
1456
- // denial-of-service surface rather than merely untidy.
1457
- let bufferedStdout = '';
1458
- let bufferedStdoutBytes = 0;
1459
- /** Bytes the ceiling refused, reported verbatim on flush so truncation is never silent. */
1460
- let droppedStdoutBytes = 0;
1461
- function enqueueEmit(task) {
1462
- emitQueue = emitQueue.then(async () => {
1463
- try {
1464
- await task();
1465
- }
1466
- catch {
1467
- // A single emit failing (e.g. a race against an already-terminal
1468
- // run) must not block delivery of subsequently queued events —
1469
- // see this function's own doc.
1470
- }
1471
- });
1472
- }
1473
- function closeStdinOnce() {
1474
- if (stdinClosed)
1475
- return;
1476
- stdinClosed = true;
1477
- child.stdin?.end();
1478
- }
1479
- /**
1480
- * Writes a structured (never string-concatenated — see `ContinuationOptions`'s doc on the
1481
- * prompt-injection stakes here) tool_result JSONL line, mirroring the shape
1482
- * `claude-stream.ts`'s own inbound parser already expects on the opposite direction of this
1483
- * exact wire format. Journals the sent content the same way `writePromptToStdin`'s
1484
- * `recordSentBytes` does.
1485
- */
1486
- function injectToolResultLine(toolUseId, content, isError) {
1487
- const stdin = child.stdin;
1488
- if (!stdin)
1489
- return;
1490
- const line = JSON.stringify({
1491
- type: 'user',
1492
- message: { role: 'user', content: [{ type: 'tool_result', tool_use_id: toolUseId, content, ...(isError ? { is_error: true } : {}) }] },
1493
- });
1494
- stdin.write(`${line}\n`, 'utf8');
1495
- if (journal)
1496
- enqueueEmit(() => journal.record({ runId: runId, entry: sentJournalEntry(content) }));
1497
- }
1498
- /**
1499
- * Decides, per `turn_end`, whether to auto-resolve a pending tool_use through the injected
1500
- * `ToolExecutor` and keep stdin open (gap 3), or close stdin exactly as every version of this
1501
- * function has always done (the default, and the only behavior when `continuation` is
1502
- * unconfigured or the pending tool isn't allowlisted).
1503
- */
1504
- function handleTurnEnd(stopReason) {
1505
- const toolUse = pendingToolUse;
1506
- const shouldInject = stopReason === 'tool_use' &&
1507
- toolUse !== undefined &&
1508
- continuation !== undefined &&
1509
- resolveContinuationTransport({ def: def }) === 'stdin-injection' &&
1510
- continuation.autonomousToolNames.has(toolUse.name);
1511
- if (!shouldInject) {
1512
- closeStdinOnce();
1513
- return;
1514
- }
1515
- pendingToolUse = undefined;
1516
- enqueueEmit(async () => {
1517
- const run = { id: runId };
1518
- let content;
1519
- let isError;
1520
- // Same extraction `delegated-tool-bridge.ts`'s `execute()` runs, kept consistent per
1521
- // `resultContent`'s own doc ("both callers share one mapping"). This path never ran
1522
- // `splitToolResultSurfaces` (it has no `mcp-ui` withhold-from-model concept — the flattened
1523
- // `content` below already carries the whole raw output, a pre-existing, unrelated gap), so
1524
- // there is no `remainder` to thread back in — only the extracted blocks are used here.
1525
- let media = [];
1526
- // Suspend the slow-run watchdog for the duration of this daemon-awaited execution: the daemon
1527
- // knows exactly why the run is quiet here (it dispatched the tool itself and is waiting on it),
1528
- // so a legitimately long tool (an install, a build, a repo-wide scan) must not be mistaken for
1529
- // the CPU-starved-and-silent condition the watchdog exists to catch. Resumed in `finally` so a
1530
- // genuinely stalled stretch *after* this tool settles is still caught — see
1531
- // `RunLifecycle.suspendSlowRunNotice`'s own doc.
1532
- lifecycle.suspendSlowRunNotice({ runId: runId });
1533
- try {
1534
- const result = await continuation.toolExecutor.execute({ principal: continuation.principal, run: run, toolId: toolUse.name, input: toolUse.input });
1535
- content = resultContent({ result: result });
1536
- isError = result.status !== 'completed';
1537
- media = extractResultMedia({ output: result.output }).media;
1538
- }
1539
- catch (error) {
1540
- content = errorMessage(error);
1541
- isError = true;
1542
- }
1543
- finally {
1544
- lifecycle.resumeSlowRunNotice({ runId: runId });
1545
- }
1546
- await lifecycle.emit({ runId: runId, input: {
1547
- event: 'agent',
1548
- data: {
1549
- type: 'tool_result',
1550
- toolUseId: toolUse.id,
1551
- content,
1552
- ...(isError ? { isError: true } : {}),
1553
- ...(media.length > 0 ? { media } : {}),
1554
- },
1555
- } });
1556
- injectToolResultLine(toolUse.id, content, isError);
1557
- });
1558
- }
1559
- const streamHandler = streamFormat === 'plain'
1560
- ? null
1561
- : createStreamHandlerForDef(def, streamFormat, (rawEvent) => {
1562
- if (bridgeUnavailable)
1563
- return;
1564
- const translation = translateAgentRuntimeEvent({ rawEvent: rawEvent });
1565
- if (translation.kind === 'agent') {
1566
- if (translation.sessionId !== undefined)
1567
- capturedSessionId = translation.sessionId;
1568
- if (!bridgeChecked && translation.payload.type === 'status' && translation.payload.label === 'initializing') {
1569
- bridgeChecked = true;
1570
- const bridgeStatus = unavailableJiniBridgeStatus({ rawEvent: rawEvent });
1571
- if (bridgeStatus !== undefined) {
1572
- stopForUnavailableBridge(translation.payload, bridgeStatus);
1573
- return;
1574
- }
1575
- }
1576
- if (translation.payload.type === 'tool_use') {
1577
- pendingToolUse = { id: translation.payload.id, name: translation.payload.name, input: translation.payload.input };
1578
- toolCallSeen = true;
1579
- }
1580
- else if ((translation.payload.type === 'text_delta' || translation.payload.type === 'thinking_delta') &&
1581
- translation.payload.delta.length > 0) {
1582
- userVisibleOutputSeen = true;
1583
- }
1584
- enqueueEmit(() => lifecycle.emit({ runId: runId, input: { event: 'agent', data: translation.payload } }));
1585
- }
1586
- else if (translation.kind === 'error') {
1587
- enqueueEmit(() => lifecycle.emit({ runId: runId, input: { event: 'error', data: translation.payload } }));
1588
- }
1589
- else if (translation.kind === 'turn-end') {
1590
- handleTurnEnd(translation.stopReason);
1591
- }
1592
- });
1593
- /**
1594
- * Ends a run whose CLI started without the `jini` bridge: emits the init status and a
1595
- * {@link MCP_BRIDGE_UNAVAILABLE} error, then stops the child's process tree before the model can
1596
- * answer with no host tools. The close handler then finishes the run `'failed'` whatever exit code
1597
- * the child reports.
1598
- */
1599
- function stopForUnavailableBridge(initStatus, bridgeStatus) {
1600
- bridgeUnavailable = true;
1601
- const message = bridgeUnavailableMessage(bridgeStatus);
1602
- enqueueEmit(() => lifecycle.emit({ runId: runId, input: { event: 'agent', data: initStatus } }));
1603
- enqueueEmit(() => lifecycle.emit({ runId: runId, input: { event: 'error', data: { message, error: { code: MCP_BRIDGE_UNAVAILABLE, message } } } }));
1604
- void terminateChildTreeBestEffort(ctx, child, runId, 'cancel', ctx.onCleanupFailure);
1605
- }
1606
- /**
1607
- * Emits the accumulated `'until-close'` stdout — sanitized — as exactly one raw `'stdout'` echo
1608
- * plus one `text_delta`, through the same `enqueueEmit` FIFO queue every other emit uses, so the
1609
- * flush is ordered after every already-queued event and before `finish()`'s `'end'`. A no-op for
1610
- * every live-streaming def (nothing was ever accumulated) and for a buffered run that produced
1611
- * no stdout at all — an empty `text_delta` is noise, not information.
1612
- *
1613
- * A run whose accumulator hit its ceiling is the one case that still emits when the sanitized text
1614
- * is empty: "the sanitizer redacted everything" and "we dropped output on the floor" must not look
1615
- * identical to a client, so the truncation notice is information in its own right.
1616
- */
1617
- function flushBufferedStdout() {
1618
- if (bufferedStdout.length === 0 && droppedStdoutBytes === 0)
1619
- return;
1620
- const safe = sanitizeBufferedStdout ? sanitizeBufferedStdout({ fullText: bufferedStdout }) : bufferedStdout;
1621
- bufferedStdout = '';
1622
- bufferedStdoutBytes = 0;
1623
- const text = droppedStdoutBytes > 0
1624
- ? `${safe}${bufferedStdoutTruncationNotice(droppedStdoutBytes, ctx.bufferedStdoutMaxBytes)}`
1625
- : safe;
1626
- droppedStdoutBytes = 0;
1627
- if (text.length === 0)
1628
- return;
1629
- enqueueEmit(() => lifecycle.emit({ runId: runId, input: { event: 'stdout', data: { chunk: text } } }));
1630
- enqueueEmit(() => lifecycle.emit({ runId: runId, input: { event: 'agent', data: { type: 'text_delta', delta: text } } }));
1631
- }
1632
- child.stdout?.on('data', (chunk) => {
1633
- const text = chunk.toString('utf8');
1634
- if (journal)
1635
- enqueueEmit(() => journal.record({ runId: runId, entry: receivedJournalEntry('stdout', text) }));
1636
- if (streamFormat === 'plain') {
1637
- if (text.length > 0)
1638
- userVisibleOutputSeen = true;
1639
- if (bufferStdoutUntilClose) {
1640
- // Nothing is emitted on *either* channel yet — see this function's doc on why holding the
1641
- // raw echo back matters as much as holding back the chat copy.
1642
- //
1643
- // Whole chunks only: a chunk that would cross the ceiling is dropped entirely rather than
1644
- // sliced to fit, which keeps the accumulator free of half-written multi-byte characters (a
1645
- // `data` event boundary already need not align with one) and makes the kept prefix exactly
1646
- // the bytes some prefix of chunks produced. Everything after the first refusal is dropped
1647
- // too — the point is a hard ceiling on resident bytes, not a best-effort tail.
1648
- const chunkBytes = Buffer.byteLength(text, 'utf8');
1649
- if (droppedStdoutBytes > 0 || bufferedStdoutBytes + chunkBytes > ctx.bufferedStdoutMaxBytes) {
1650
- droppedStdoutBytes += chunkBytes;
1651
- return;
1652
- }
1653
- bufferedStdout += text;
1654
- bufferedStdoutBytes += chunkBytes;
1655
- return;
1656
- }
1657
- enqueueEmit(() => lifecycle.emit({ runId: runId, input: { event: 'stdout', data: { chunk: text } } }));
1658
- enqueueEmit(() => lifecycle.emit({ runId: runId, input: { event: 'agent', data: { type: 'text_delta', delta: text } } }));
1659
- return;
1660
- }
1661
- enqueueEmit(() => lifecycle.emit({ runId: runId, input: { event: 'stdout', data: { chunk: text } } }));
1662
- // Non-null: `streamHandler` is only ever null when `streamFormat === 'plain'` (see its
1663
- // construction above), the branch this statement is provably unreachable from.
1664
- streamHandler.feed({ chunk: text });
1665
- });
1666
- child.stderr?.on('data', (chunk) => {
1667
- const text = chunk.toString('utf8');
1668
- if (journal)
1669
- enqueueEmit(() => journal.record({ runId: runId, entry: receivedJournalEntry('stderr', text) }));
1670
- enqueueEmit(() => lifecycle.emit({ runId: runId, input: { event: 'stderr', data: { chunk: text } } }));
1671
- });
1672
- // EPIPE-tolerant: a fast-exiting child that closes its stdin read end
1673
- // before every queued write lands must not crash the host process with
1674
- // an unhandled stream error — the real failure (if any) surfaces through
1675
- // the 'close' handler below regardless.
1676
- child.stdin?.on('error', () => { });
1677
- // Safety net for any child-level 'error' event that fires after the
1678
- // spawn-confirmation race (see waitForSpawnOrError) has already settled —
1679
- // EventEmitter throws on an unheard 'error' otherwise. The real outcome
1680
- // is still decided by 'close' below.
1681
- child.on('error', () => { });
1682
- const unsubscribeCancel = lifecycle.onCancelRequested({ runId: runId, listener: () => {
1683
- cancelRequested = true;
1684
- void terminateChildTreeBestEffort(ctx, child, runId, 'cancel', ctx.onCleanupFailure);
1685
- } });
1686
- child.on('close', (code, signal) => {
1687
- void (async () => {
1688
- // Not wrapped in try/catch: all 4 supported parser factories'
1689
- // flush() implementations already internally guard their own
1690
- // JSON.parse/dispatch and degrade a malformed trailing buffered
1691
- // line to a `{type:'raw'}` event rather than throwing (confirmed by
1692
- // reading each of the 4 modules in full — see module doc). A guard
1693
- // here would be dead code for the fixed, closed set of parsers this
1694
- // driver dispatches to. `streamHandler` is null for `'plain'` (no
1695
- // parser, hence nothing to flush) — `?.` skips it cleanly.
1696
- streamHandler?.flush();
1697
- // Queued before `await emitQueue` so the flushed text is durably appended ahead of
1698
- // `finish()`'s `'end'` event, exactly like every live-path emit already is.
1699
- flushBufferedStdout();
1700
- await emitQueue;
1701
- unsubscribeCancel();
1702
- // Both of the next two steps are guarded: neither a failed cleanup nor a rejecting host
1703
- // classifier may prevent the terminal transition below — see each helper's own doc.
1704
- await cleanupStagedFilesSafely(ctx);
1705
- const status = bridgeUnavailable ? 'failed' : classifyRunCloseStatus({ cancelRequested, code }, { signal });
1706
- // A bridge failure is not resumable: resuming would start the same CLI with the same bridge.
1707
- const resumable = status === 'failed' && !bridgeUnavailable && classifyFailure !== undefined
1708
- ? await classifyFailureSafely(ctx, classifyFailure, {
1709
- runId,
1710
- agentId: def.id,
1711
- code,
1712
- signal: signal ?? null,
1713
- sideEffects: { userVisibleOutputSeen, toolCallSeen },
1714
- })
1715
- : false;
1716
- await lifecycle.finish({ runId, status, code, signal: signal ?? null, resumable }, { ...(capturedSessionId !== undefined ? { sessionRef: capturedSessionId } : {}) });
1717
- })();
1718
- });
1719
- return {
1720
- closeStdinOnce,
1721
- recordSentBytes(content) {
1722
- if (journal)
1723
- enqueueEmit(() => journal.record({ runId: runId, entry: sentJournalEntry(content) }));
1724
- },
1725
- };
1726
- }
1727
- /**
1728
- * Maps an ACP session's transport error into the canonical run-error shape.
1729
- * ACP adapters may add a structured `error` member, but a daemon driver must
1730
- * never make one vendor's error shape part of the run protocol.
1731
- */
1732
- function translateAcpError(payload) {
1733
- if (!isRecord(payload))
1734
- return { message: asString(payload, 'ACP agent failed') };
1735
- const message = asString(payload.message, 'ACP agent failed');
1736
- const error = isRecord(payload.error) ? payload.error : null;
1737
- const code = error ? asOptionalString(error.code) : undefined;
1738
- const retryable = error && typeof error.retryable === 'boolean' ? error.retryable : undefined;
1739
- return {
1740
- message,
1741
- ...(code !== undefined
1742
- ? {
1743
- error: {
1744
- code,
1745
- message: asString(error?.message, message),
1746
- ...(retryable !== undefined ? { retryable } : {}),
1747
- },
1748
- }
1749
- : {}),
1750
- };
1751
- }
1752
- /**
1753
- * Applies one already-translated `'agent'`-kind event's side-effect signals — a captured session id
1754
- * (gap 5), and the `toolCallSeen`/`userVisibleOutputSeen` pair every `wire*Lifecycle` driver tracks
1755
- * for `FailureClassificationContext.sideEffects` — through `sink`. Extracted from `wireAcpLifecycle`'s
1756
- * `send()`, where this exact three-level-deep nesting (session-id check, then tool_use/else-if
1757
- * delta-length check) was that function's largest single cognitive-complexity contributor. Pure
1758
- * except for calling the injected `sink` callbacks.
1759
- * @param payload - The translated event's `RunAgentPayload`.
1760
- * @param sessionId - The translation's optional captured session id, or `undefined`.
1761
- * @param sink - The driver-specific effects to apply.
1762
- * @complexity O(1).
1763
- */
1764
- export function applyAgentTranslationSideEffects({ payload, sessionId, sink }) {
1765
- if (sessionId !== undefined)
1766
- sink.onSessionId({ sessionId });
1767
- if (payload.type === 'tool_use') {
1768
- sink.onToolCall();
1769
- }
1770
- else if ((payload.type === 'text_delta' || payload.type === 'thinking_delta') && payload.delta.length > 0) {
1771
- sink.onUserVisibleOutput();
1772
- }
1773
- }
1774
- /**
1775
- * Wires an ACP child to a run. Unlike the JSON-stream path, ACP owns the
1776
- * prompt protocol and reports its parsed events through `attachAcpSession`'s
1777
- * callback. This wrapper retains raw stdout/stderr for diagnostics, preserves
1778
- * event order through the same FIFO discipline, forwards cancellation both as
1779
- * ACP `session/cancel` and an OS process-tree stop, and uses the controller's
1780
- * clean-prompt signal rather than SIGTERM (expected ACP cleanup) to determine
1781
- * success.
1782
- */
1783
- function wireAcpLifecycle(ctx) {
1784
- const { runId, agentId, child, lifecycle, journal, classifyFailure } = ctx;
1785
- let cancelRequested = false;
1786
- let emitQueue = Promise.resolve();
1787
- // Gap 5 (session resume) — see wireChildLifecycle's identical local for the full rationale.
1788
- let capturedSessionId;
1789
- // Real `FailureClassificationContext.sideEffects` signals — see that interface's own doc.
1790
- let userVisibleOutputSeen = false;
1791
- let toolCallSeen = false;
1792
- function enqueueEmit(task) {
1793
- emitQueue = emitQueue.then(async () => {
1794
- try {
1795
- await task();
1796
- }
1797
- catch {
1798
- // A late event racing a terminal lifecycle is intentionally dropped;
1799
- // it must not prevent subsequent queued cleanup from running.
1800
- }
1801
- });
1802
- }
1803
- child.stdout?.on('data', (chunk) => {
1804
- const text = chunk.toString('utf8');
1805
- if (journal)
1806
- enqueueEmit(() => journal.record({ runId: runId, entry: receivedJournalEntry('stdout', text) }));
1807
- enqueueEmit(() => lifecycle.emit({ runId: runId, input: { event: 'stdout', data: { chunk: text } } }));
1808
- });
1809
- child.stderr?.on('data', (chunk) => {
1810
- const text = chunk.toString('utf8');
1811
- if (journal)
1812
- enqueueEmit(() => journal.record({ runId: runId, entry: receivedJournalEntry('stderr', text) }));
1813
- enqueueEmit(() => lifecycle.emit({ runId: runId, input: { event: 'stderr', data: { chunk: text } } }));
1814
- });
1815
- child.stdin?.on('error', () => { });
1816
- child.on('error', () => { });
1817
- let controller = null;
1818
- const unsubscribeCancel = lifecycle.onCancelRequested({ runId: runId, listener: () => {
1819
- cancelRequested = true;
1820
- controller?.abort();
1821
- void terminateChildTreeBestEffort(ctx, child, runId, 'cancel', ctx.onCleanupFailure);
1822
- } });
1823
- child.on('close', (code, signal) => {
1824
- void (async () => {
1825
- await emitQueue;
1826
- unsubscribeCancel();
1827
- // Guarded for the same reasons as the child-driven handler above.
1828
- await cleanupStagedFilesSafely(ctx);
1829
- const status = cancelRequested ? 'cancelled' : controller?.completedSuccessfully() ? 'succeeded' : 'failed';
1830
- const resumable = status === 'failed' && classifyFailure !== undefined
1831
- ? await classifyFailureSafely(ctx, classifyFailure, {
1832
- runId,
1833
- agentId,
1834
- code,
1835
- signal: signal ?? null,
1836
- sideEffects: { userVisibleOutputSeen, toolCallSeen },
1837
- })
1838
- : false;
1839
- await lifecycle.finish({ runId, status, code, signal: signal ?? null, resumable }, { ...(capturedSessionId !== undefined ? { sessionRef: capturedSessionId } : {}) });
1840
- })();
1841
- });
1842
- controller = ctx.attachAcpSession({ child, prompt: ctx.prompt, send({ event, payload }) {
1843
- if (event === 'agent') {
1844
- const translation = translateAgentRuntimeEvent({ rawEvent: payload });
1845
- if (translation.kind === 'agent') {
1846
- applyAgentTranslationSideEffects({ payload: translation.payload, sessionId: translation.sessionId, sink: {
1847
- onSessionId: ({ sessionId }) => { capturedSessionId = sessionId; },
1848
- onToolCall: () => { toolCallSeen = true; },
1849
- onUserVisibleOutput: () => { userVisibleOutputSeen = true; },
1850
- } });
1851
- enqueueEmit(() => lifecycle.emit({ runId: runId, input: { event: 'agent', data: translation.payload } }));
1852
- }
1853
- else if (translation.kind === 'error') {
1854
- enqueueEmit(() => lifecycle.emit({ runId: runId, input: { event: 'error', data: translation.payload } }));
1855
- }
1856
- return;
1857
- }
1858
- if (event === 'error') {
1859
- enqueueEmit(() => lifecycle.emit({ runId: runId, input: { event: 'error', data: translateAcpError(payload) } }));
1860
- }
1861
- } }, { cwd: ctx.cwd, ...(ctx.model !== undefined ? { model: ctx.model } : {}), ...(ctx.imagePaths.length > 0 ? { imagePaths: [...ctx.imagePaths] } : {}), ...(ctx.envFormat !== undefined ? { envFormat: ctx.envFormat } : {}),
1862
- // Spread-when-present rather than always: passing `mcpServers: []` is not the same as passing
1863
- // nothing for every downstream ACP agent, and "no bridge configured" must stay byte-identical
1864
- // to before this field existed.
1865
- ...(ctx.mcpServers !== undefined && ctx.mcpServers.length > 0 ? { mcpServers: [...ctx.mcpServers] } : {}), ...(ctx.onPermissionRequest !== undefined ? { onPermissionRequest: ctx.onPermissionRequest } : {}) });
1866
- return controller;
1867
- }
1868
- /**
1869
- * Wires a pi-rpc child to a run. Like ACP, pi owns its own prompt-delivery
1870
- * protocol (`prompt`/`new_session`/`abort` RPC commands over stdin) and
1871
- * reports parsed events through `attachPiRpcSession`'s `send` callback —
1872
- * unlike ACP's callback, pi-rpc's `send` always uses the `'agent'` channel
1873
- * (confirmed by reading every `mapPiRpcEvent` call site: error-ness is
1874
- * signaled via the payload's own `type: 'error'` field, never a separate
1875
- * channel), so this wrapper runs every payload through the same
1876
- * `translateAgentRuntimeEvent` pipeline ACP/JSON-stream already use, with no
1877
- * channel branch needed. Raw stdout/stderr are still forwarded for
1878
- * diagnostics (same as ACP) even though `attachPiRpcSession` also consumes
1879
- * `child.stdout` itself for its own JSON-RPC parsing — Node multicasts
1880
- * `'data'` events to every listener, so both coexist safely.
1881
- *
1882
- * v1 omits `parentSession` — none of
1883
- * `AgentExecutorRunInput`'s fields carry them yet (matching this module's
1884
- * established "explicitly out of scope" discipline for other follow-ups:
1885
- * multi-turn tool continuation, resumable session ids, etc.).
1886
- */
1887
- function wirePiRpcLifecycle(ctx) {
1888
- const { runId, agentId, child, lifecycle, journal, classifyFailure } = ctx;
1889
- let cancelRequested = false;
1890
- let emitQueue = Promise.resolve();
1891
- // Gap 5 (session resume) — see wireChildLifecycle's identical local for the full rationale.
1892
- let capturedSessionId;
1893
- // Real `FailureClassificationContext.sideEffects` signals — see that interface's own doc.
1894
- let userVisibleOutputSeen = false;
1895
- let toolCallSeen = false;
1896
- function enqueueEmit(task) {
1897
- emitQueue = emitQueue.then(async () => {
1898
- try {
1899
- await task();
1900
- }
1901
- catch {
1902
- // A late event racing a terminal lifecycle is intentionally dropped;
1903
- // it must not prevent subsequent queued cleanup from running.
1904
- }
1905
- });
1906
- }
1907
- child.stdout?.on('data', (chunk) => {
1908
- const text = chunk.toString('utf8');
1909
- if (journal)
1910
- enqueueEmit(() => journal.record({ runId: runId, entry: receivedJournalEntry('stdout', text) }));
1911
- enqueueEmit(() => lifecycle.emit({ runId: runId, input: { event: 'stdout', data: { chunk: text } } }));
1912
- });
1913
- child.stderr?.on('data', (chunk) => {
1914
- const text = chunk.toString('utf8');
1915
- if (journal)
1916
- enqueueEmit(() => journal.record({ runId: runId, entry: receivedJournalEntry('stderr', text) }));
1917
- enqueueEmit(() => lifecycle.emit({ runId: runId, input: { event: 'stderr', data: { chunk: text } } }));
1918
- });
1919
- child.stdin?.on('error', () => { });
1920
- child.on('error', () => { });
1921
- let session = null;
1922
- const unsubscribeCancel = lifecycle.onCancelRequested({ runId: runId, listener: () => {
1923
- cancelRequested = true;
1924
- session?.abort();
1925
- void terminateChildTreeBestEffort(ctx, child, runId, 'cancel', ctx.onCleanupFailure);
1926
- } });
1927
- child.on('close', (code, signal) => {
1928
- void (async () => {
1929
- await emitQueue;
1930
- unsubscribeCancel();
1931
- // Guarded for the same reasons as the child-driven handler above.
1932
- await cleanupStagedFilesSafely(ctx);
1933
- const status = cancelRequested ? 'cancelled' : session?.hasFatalError() ? 'failed' : 'succeeded';
1934
- const resumable = status === 'failed' && classifyFailure !== undefined
1935
- ? await classifyFailureSafely(ctx, classifyFailure, {
1936
- runId,
1937
- agentId,
1938
- code,
1939
- signal: signal ?? null,
1940
- sideEffects: { userVisibleOutputSeen, toolCallSeen },
1941
- })
1942
- : false;
1943
- await lifecycle.finish({ runId, status, code, signal: signal ?? null, resumable }, { ...(capturedSessionId !== undefined ? { sessionRef: capturedSessionId } : {}) });
1944
- })();
1945
- });
1946
- session = ctx.attachPiRpcSession({ child: ctx.child, prompt: ctx.prompt, send({ payload }) {
1947
- const translation = translateAgentRuntimeEvent({ rawEvent: payload });
1948
- if (translation.kind === 'agent') {
1949
- if (translation.sessionId !== undefined)
1950
- capturedSessionId = translation.sessionId;
1951
- if (translation.payload.type === 'tool_use') {
1952
- toolCallSeen = true;
1953
- }
1954
- else if ((translation.payload.type === 'text_delta' || translation.payload.type === 'thinking_delta') &&
1955
- translation.payload.delta.length > 0) {
1956
- userVisibleOutputSeen = true;
1957
- }
1958
- enqueueEmit(() => lifecycle.emit({ runId: runId, input: { event: 'agent', data: translation.payload } }));
1959
- }
1960
- else if (translation.kind === 'error') {
1961
- enqueueEmit(() => lifecycle.emit({ runId: runId, input: { event: 'error', data: translation.payload } }));
1962
- }
1963
- } }, { cwd: ctx.cwd, ...(ctx.model !== undefined ? { model: ctx.model } : {}), ...(ctx.imagePaths.length > 0 ? { imagePaths: [...ctx.imagePaths] } : {}), ...(ctx.uploadRoot !== undefined ? { uploadRoot: ctx.uploadRoot } : {}) });
1964
- return session;
1965
- }
1966
- /**
1967
- * Writes the initial user turn to the child's stdin per `def.promptInputFormat`
1968
- * (both branches only run for `promptViaStdin: true` defs — the only shape
1969
- * `run()` supports in v1, see module doc):
1970
- * - `'text'` (default): the raw prompt buffer, then stdin is closed —
1971
- * matches `RuntimeAgentDef.promptInputFormat`'s own doc.
1972
- * - `'stream-json'`: one JSONL line wrapping the prompt as an Anthropic
1973
- * user message; stdin is deliberately left open (a real multi-turn
1974
- * caller would inject further messages) — v1 has no such caller, so
1975
- * {@link wireChildLifecycle}'s `turn_end` handling closes it once the
1976
- * agent's own stream reports the turn ended.
1977
- * @param def - The resolved agent def (only `.promptInputFormat` is read).
1978
- * @param child - The spawned child (no-ops if `.stdin` is unexpectedly absent).
1979
- * @param prompt - The composed user turn.
1980
- * @param handle - Shared stdin-close guard so a `'text'` write's immediate close and a later `turn_end` close never race into a double-`end()`; also carries gap 1's byte-journal recorder (see `StdinCloseHandle.recordSentBytes`).
1981
- * @complexity O(1) plus the underlying stream write's own cost.
1982
- * @overallScore 100/100
1983
- */
1984
- function writePromptToStdin(def, child, prompt, handle) {
1985
- const stdin = child.stdin;
1986
- if (!stdin)
1987
- return;
1988
- if (def.promptInputFormat === 'stream-json') {
1989
- const line = JSON.stringify({ type: 'user', message: { role: 'user', content: messageContentWithImages({ prompt, images: handle.imageContents ?? [] }, {}) } });
1990
- stdin.write(`${line}\n`, 'utf8');
1991
- handle.recordSentBytes(prompt);
1992
- return;
1993
- }
1994
- stdin.write(prompt, 'utf8');
1995
- handle.recordSentBytes(prompt);
1996
- handle.closeStdinOnce();
1997
- }
1998
- /**
1999
- * Resolves `CreateAgentExecutorOptions`' agent-runtime collaborator seams (registry lookup, launch
2000
- * resolution, ACP/pi-rpc session attachment, prompt/log file staging) to their real
2001
- * `@jini-ai/agent-runtime` defaults. Split out of `createAgentExecutor` together with
2002
- * {@link resolveProcessDeps}/{@link resolveMiscExecutorDeps}: a flat 14-line `options.x ?? default`
2003
- * sequence was that function's entire cyclomatic-complexity excess (one branch point per default) —
2004
- * grouping the same defaults by concern keeps each resulting function's own complexity low without
2005
- * hiding which options belong together. Pure.
2006
- */
2007
- function resolveAgentRuntimeDeps(options) {
2008
- return {
2009
- getAgentDef: options.getAgentDef ?? getAgentDef,
2010
- resolveAgentLaunch: options.resolveAgentLaunch ?? resolveAgentLaunch,
2011
- ensureAgentCapabilities: options.ensureAgentCapabilities ?? ensureAgentCapabilities,
2012
- applyAgentLaunchEnv: options.applyAgentLaunchEnv ?? applyAgentLaunchEnv,
2013
- attachAcpSession: options.attachAcpSession ?? attachAcpSession,
2014
- attachPiRpcSession: options.attachPiRpcSession ?? attachPiRpcSession,
2015
- preparePromptFileForAgent: options.preparePromptFileForAgent ?? preparePromptFileForAgent,
2016
- prepareAgentLogFile: options.prepareAgentLogFile ?? prepareAgentLogFile,
2017
- };
2018
- }
2019
- /** Resolves the OS-process-facing collaborator seams — see {@link resolveAgentRuntimeDeps}'s doc. Pure. */
2020
- function resolveProcessDeps(options) {
2021
- return {
2022
- createCommandInvocation: options.createCommandInvocation ?? createCommandInvocation,
2023
- spawn: options.spawn ?? nodeSpawn,
2024
- listProcessSnapshots: options.listProcessSnapshots ?? listProcessSnapshots,
2025
- collectProcessTreePids: options.collectProcessTreePids ?? (({ processes, rootPids }) => collectProcessTreePids(processes, rootPids)),
2026
- stopProcesses: options.stopProcesses ?? (({ pids }) => stopProcesses(pids)),
2027
- };
2028
- }
2029
- /** Resolves the two remaining defaultable options — see {@link resolveAgentRuntimeDeps}'s doc. Pure. */
2030
- function resolveMiscExecutorDeps(options) {
2031
- return {
2032
- onCleanupFailure: options.onCleanupFailure ?? defaultCleanupFailureSink,
2033
- bufferedStdoutMaxBytes: options.bufferedStdoutMaxBytes ?? DEFAULT_BUFFERED_STDOUT_MAX_BYTES,
2034
- };
2035
- }
2036
- /** Phase 1: registry lookup + `assessAgentExecutorCompatibility` guard. */
2037
- export async function resolveDefAndStreamFormat({ input, deps }) {
2038
- const def = deps.getAgentDef({ id: input.agentId });
2039
- if (!def) {
2040
- return deps.failBeforeSpawn({ runId: input.runId, code: 'AGENT_NOT_FOUND', message: `AgentExecutor: unknown agentId "${input.agentId}"` });
2041
- }
2042
- const compatibility = assessAgentExecutorCompatibility({ def: def });
2043
- if (!compatibility.supported) {
2044
- return deps.failBeforeSpawn({ runId: input.runId, code: 'AGENT_RUNTIME_UNSUPPORTED', message: compatibility.reason });
2045
- }
2046
- return { def, streamFormat: compatibility.streamFormat };
2047
- }
2048
- /** Phase 2: image-prompt-delivery augmentation + argv-budget guard for argv-bound defs. */
2049
- export async function resolveImageDeliveryAndArgvBudget({ input, deps }) {
2050
- const imageDelivery = applyImagePromptDelivery({ imageDelivery: input.def.imageDelivery, prompt: input.prompt, imagePaths: input.imagePaths, extraAllowedDirs: input.extraAllowedDirs });
2051
- const argvBudgetError = checkPromptArgvBudget({ def: input.def, composed: imageDelivery.prompt });
2052
- if (argvBudgetError) {
2053
- return deps.failBeforeSpawn({ runId: input.runId, code: 'AGENT_PROMPT_TOO_LARGE', message: argvBudgetError.message });
2054
- }
2055
- return imageDelivery;
2056
- }
2057
- /**
2058
- * Phase 3a: the subprocess environment this run's launch resolution and spawn should use — the
2059
- * caller-supplied escape hatch verbatim, or the deny-by-default `BASELINE_AGENT_ENV_KEYS` allowlist.
2060
- * Pure.
2061
- */
2062
- export function resolveRunEnv({ input, hostEnv }) {
2063
- return input.env !== undefined ? toStringEnvRecord(input.env) : buildAgentEnv(hostEnv, input.credentialEnv);
2064
- }
2065
- /** Phase 3b: launch-path resolution + binary-not-resolved guard. */
2066
- export async function resolveLaunch({ input, deps }) {
2067
- const launch = deps.resolveAgentLaunch({ def: input.def }, { configuredEnv: input.resolvedEnv });
2068
- if (!launch.launchPath) {
2069
- return deps.failBeforeSpawn({ runId: input.runId, code: 'AGENT_BINARY_NOT_RESOLVED', message: `AgentExecutor: could not resolve an executable for agent "${input.def.id}" (bin "${input.def.bin}")` });
2070
- }
2071
- // Narrowed by the guard above; `resolveAgentLaunch`'s own return type still declares
2072
- // `launchPath: string | null` since it can't know this call site already checked.
2073
- return launch;
2074
- }
2075
- /** Phase 4a: stage a `promptViaFile` def's prompt to a temp file (a no-op for every other def). */
2076
- export async function stagePromptFile({ input, deps }) {
2077
- try {
2078
- return await deps.preparePromptFileForAgent({ def: input.def, prompt: input.prompt, label: input.runId });
2079
- }
2080
- catch (err) {
2081
- return deps.failBeforeSpawn({ runId: input.runId, code: 'AGENT_SPAWN_FAILED', message: `AgentExecutor: could not stage a prompt file for agent "${input.def.id}": ${errorMessage(err)}` });
2082
- }
2083
- }
2084
- /** Phase 4b: stage a `needsAgentLogFile` def's diagnostic-log path (a no-op for every other def). */
2085
- export async function stageLogFile({ input, deps }) {
2086
- try {
2087
- return await deps.prepareAgentLogFile({ def: input.def, label: input.runId });
2088
- }
2089
- catch (err) {
2090
- await (input.preparedPromptFile ? input.preparedPromptFile.cleanup() : Promise.resolve());
2091
- return deps.failBeforeSpawn({ runId: input.runId, code: 'AGENT_SPAWN_FAILED', message: `AgentExecutor: could not stage a log file for agent "${input.def.id}": ${errorMessage(err)}` });
2092
- }
2093
- }
2094
- /** Phase 5: resolves this run's MCP bridge delivery (credential resolution + {@link buildMcpBridgeDelivery}). */
2095
- export async function resolveMcpBridgeForRun({ input, deps }) {
2096
- try {
2097
- // Awaited here rather than inside `buildMcpBridgeDelivery` so that function stays pure and
2098
- // synchronous. `undefined` when the host supplied no resolver, which omits the token entirely.
2099
- const credential = deps.mcpJsonInjection !== undefined ? await deps.mcpJsonInjection.credential?.({ runId: input.runId }) : undefined;
2100
- return buildMcpBridgeDelivery({
2101
- cwd: input.cwd,
2102
- runId: input.runId,
2103
- strategy: input.def.externalMcpInjection,
2104
- options: deps.mcpJsonInjection,
2105
- credential,
2106
- });
2107
- }
2108
- catch (err) {
2109
- // Spawning a child that cannot authenticate would produce a run whose every bridged tool call
2110
- // 401s, so a rejecting credential resolver fails the run before spawn instead.
2111
- await deps.cleanupStagedFiles();
2112
- return deps.failBeforeSpawn({ runId: input.runId, code: 'AGENT_SPAWN_FAILED', message: `AgentExecutor: could not resolve the MCP bridge credential for agent "${input.def.id}": ${errorMessage(err)}` });
2113
- }
2114
- }
2115
- /**
2116
- * Phase 6a/10c: the subprocess environment every env-riding mechanism uses — mechanism 3+4
2117
- * (`'opencode-env-content'`/`'mimo-env-content'`, merged into whatever the host already set there,
2118
- * never a CLI argument: the config embeds `JINI_DAEMON_TOKEN`, and process arguments are readable
2119
- * by any other local user through `ps`), mechanism 5 (`'codex-toml'`, `CODEX_HOME` relocation),
2120
- * mechanism 6 (`'env-passthrough'`, the bridge entry's flat env vars set directly with no carrier
2121
- * document — see {@link McpBridgeDelivery}'s own doc), a
2122
- * `systemPromptDelivery: 'env-var'` def's overlay (`reasonix`'s `REASONIX_ACP_SYSTEM_APPEND` today
2123
- * — see `resolveSystemPromptOverlayDelivery`'s own doc), and a `'config-instructions-file'` def's
2124
- * staged overlay file (`opencode` today — see {@link mergeEnvContentInstructions}'s own doc). Pure
2125
- * — `codexHomeDir` and `stagedInstructionsFile` arrive already staged by
2126
- * {@link prepareCodexHomeIfNeeded} and {@link prepareSystemPromptOverlayFileIfNeeded} respectively,
2127
- * the only parts of this mechanism that are NOT pure (real `mkdtemp`/`writeFile` calls).
2128
- * @param spawnEnv - The env every other spawn-time step (launch-path resolution, `applyAgentLaunchEnv`) already computed.
2129
- * @param mcpBridge - This run's resolved bridge delivery, or `null` for an unconfigured host / no-strategy def.
2130
- * @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).
2131
- * @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.
2132
- * @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).
2133
- * @complexity O(1) plus `mergeEnvContentMcpConfig`'s and `mergeEnvContentInstructions`'s own `JSON.parse`/`JSON.stringify` cost.
2134
- * @overallScore 100/100
2135
- */
2136
- export function computeChildEnv({ spawnEnv, mcpBridge }, { codexHomeDir, systemPromptEnvOverrides, stagedInstructionsFile, claudeConfigDir } = {}) {
2137
- const envContentApplied = mcpBridge?.kind === 'env-content'
2138
- ? {
2139
- ...spawnEnv,
2140
- [mcpBridge.envVarName]: mergeEnvContentMcpConfig({ existingRaw: spawnEnv[mcpBridge.envVarName], entry: mcpBridge.serverEntry }),
2141
- }
2142
- : spawnEnv;
2143
- // `'env-passthrough'` (antigravity): no document, no named carrier variable — the bridge
2144
- // entry's own `env` keys (`JINI_RUN_ID`/`JINI_DAEMON_URL`/`JINI_DAEMON_TOKEN`) are set directly
2145
- // on the child's environment, for the spawned CLI to inherit down to its own globally
2146
- // pre-registered MCP child in turn. See `McpBridgeDelivery`'s own doc for why this def has no
2147
- // config document to merge into at all.
2148
- const envPassthroughApplied = mcpBridge?.kind === 'env-passthrough' ? { ...envContentApplied, ...mcpBridge.serverEntry.env } : envContentApplied;
2149
- const instructionsApplied = stagedInstructionsFile === undefined
2150
- ? envPassthroughApplied
2151
- : {
2152
- ...envPassthroughApplied,
2153
- [stagedInstructionsFile.varName]: mergeEnvContentInstructions({ existingRaw: envPassthroughApplied[stagedInstructionsFile.varName], instructionsFilePath: stagedInstructionsFile.path }),
2154
- };
2155
- const codexHomeApplied = codexHomeDir === undefined ? instructionsApplied : { ...instructionsApplied, CODEX_HOME: codexHomeDir };
2156
- // Finding 1 of SEC-assistant-env-isolation-2026-09-07: same "only set when staged" shape as
2157
- // codexHomeApplied above — mutually exclusive with it in practice (codexHomeDir is only ever set
2158
- // for a 'codex-toml' bridge, claudeConfigDir only ever for a `claude`-id run), so both existing
2159
- // side by side here is a documentation convenience, not a real collision risk.
2160
- const claudeConfigDirApplied = claudeConfigDir === undefined ? codexHomeApplied : { ...codexHomeApplied, CLAUDE_CONFIG_DIR: claudeConfigDir };
2161
- return systemPromptEnvOverrides === undefined ? claudeConfigDirApplied : { ...claudeConfigDirApplied, ...systemPromptEnvOverrides };
2162
- }
2163
- /**
2164
- * Phase 6b: the `RuntimeContext` `buildArgs` receives — `undefined` unless a file, bridge path, or
2165
- * session id was staged. Pure.
2166
- *
2167
- * `resumeSessionId`/`newSessionId` round-trip a prior run's `RunEndPayload.sessionRef` (see
2168
- * `@jini-ai/protocol`'s doc on that field) back into this run's `RuntimeContext`, letting a
2169
- * `resumesSessionViaCli` def (e.g. claude) continue its own CLI session across turns instead of
2170
- * spawning cold every time. Either one alone must still produce a context — a run supplying ONLY a
2171
- * session id, with no prompt/log file staged and no claude-mcp-json bridge, is exactly the common
2172
- * case for a resumed turn.
2173
- */
2174
- export function computeRuntimeContext({ preparedPromptFile, preparedLogFile, mcpBridge }, { resumeSessionId, newSessionId } = {}) {
2175
- // Matches claude.ts buildArgs' own `typeof x === 'string' && x` truthiness check, so an empty
2176
- // string or explicit `null` (no resume target yet) is treated as absent here too, rather than
2177
- // manufacturing a context that carries a session field the def would ignore anyway.
2178
- const hasResumeSessionId = typeof resumeSessionId === 'string' && resumeSessionId.length > 0;
2179
- const hasNewSessionId = typeof newSessionId === 'string' && newSessionId.length > 0;
2180
- if (!preparedPromptFile
2181
- && !preparedLogFile
2182
- && mcpBridge?.kind !== 'claude-mcp-json'
2183
- && !hasResumeSessionId
2184
- && !hasNewSessionId) {
2185
- return undefined;
2186
- }
2187
- return {
2188
- ...(preparedPromptFile ? { promptFilePath: preparedPromptFile.path } : {}),
2189
- ...(preparedLogFile ? { agentLogFilePath: preparedLogFile.path } : {}),
2190
- // Safe to pass before the file exists: `writeMcpJsonForRun` runs after buildArgs but still
2191
- // before spawn, so the path is real by the time the child process starts.
2192
- ...(mcpBridge?.kind === 'claude-mcp-json' ? { mcpJsonPath: mcpBridge.mcpJsonPath } : {}),
2193
- ...(hasResumeSessionId ? { resumeSessionId } : {}),
2194
- ...(hasNewSessionId ? { newSessionId } : {}),
2195
- };
2196
- }
2197
- /**
2198
- * Phase 7: acquires a `runtimeLock` def's process-global mutex before `buildArgs` runs — see
2199
- * `RuntimeLock`'s own doc for the concrete race. A no-op (`undefined`) for the 23 of 24 defs with no
2200
- * `runtimeLock` declared.
2201
- */
2202
- async function acquireRuntimeLockIfConfigured(def, model) {
2203
- return def.runtimeLock?.acquire({ model });
2204
- }
2205
- /**
2206
- * Phase 8: the host's `PromptAugmenter.systemOverlay()` result, if configured — see
2207
- * `CreateAgentExecutorOptions.promptAugmenter`'s doc for `turnIndex`'s coarse 0/1 proxy.
2208
- */
2209
- function computeSystemPromptOverlay(promptAugmenter, agentId, runtimeContext) {
2210
- return promptAugmenter?.systemOverlay?.({
2211
- agentId,
2212
- turnIndex: runtimeContext?.hasPriorAssistantTurn ? 1 : 0,
2213
- });
2214
- }
2215
- /** Phase 9a: the def's `buildArgs` 4th argument. Historically omitted when every override was absent;
2216
- * that let defs silently enable auto-approval. Always supply the validated restricted default now. Pure. */
2217
- export function buildAgentBuildArgsOptions({ input, systemPromptOverlay }) {
2218
- const permissionMode = input.permissionMode ?? 'restricted';
2219
- if (permissionMode !== 'restricted' && permissionMode !== 'bypass') {
2220
- throw new AgentExecutorError({ code: 'AGENT_PERMISSION_MODE_INVALID', message: 'AgentExecutor: permissionMode must be restricted or bypass' });
2221
- }
2222
- const hasOverlay = systemPromptOverlay !== undefined && systemPromptOverlay !== null;
2223
- const options = {
2224
- ...(input.model !== undefined ? { model: input.model } : {}),
2225
- ...(input.reasoning !== undefined ? { reasoning: input.reasoning } : {}),
2226
- permissionMode,
2227
- ...(input.disallowedTools !== undefined ? { disallowedTools: input.disallowedTools } : {}),
2228
- ...(input.allowedTools !== undefined ? { allowedTools: input.allowedTools } : {}),
2229
- ...(input.settingSources !== undefined ? { settingSources: input.settingSources } : {}),
2230
- ...(input.settings !== undefined ? { settings: input.settings } : {}),
2231
- ...(hasOverlay ? { systemPromptOverlay } : {}),
2232
- };
2233
- return Object.keys(options).length === 0 ? undefined : options;
2234
- }
2235
- /**
2236
- * **The single dispatch point from a computed system-prompt overlay to its delivery mechanism** —
2237
- * see `RuntimeAgentDef.systemPromptDelivery`'s own doc for the declared shape. Pure and
2238
- * synchronous, mirroring {@link buildMcpBridgeDelivery}'s "keyed off the declared strategy, never
2239
- * off the def's id" contract: a def earns overlay delivery by declaring a strategy, not by being
2240
- * named in this file. That is what makes every def with no declaration work via the fallback
2241
- * without any of their own files being touched.
2242
- *
2243
- * The fallback (no declared strategy — every def but `claude` today) prefixes the overlay directly
2244
- * onto the composed prompt text, clearly delimited from the user's own request. It is gated on
2245
- * session state, not merely on whether an overlay exists: a def that carries its own conversation
2246
- * memory across spawns (`resumesSessionViaCli` / `resumesSessionViaAcpLoad`) persists whatever its
2247
- * session-creating turn sends it — see `RuntimeContext.resumeSessionId`'s own doc: its presence on
2248
- * a run means "continue a prior session", not "start one". Prefixing on every later turn of that
2249
- * same session would therefore bake the overlay into the CLI's own stored history again and again,
2250
- * compounding without bound turn over turn. So the fallback prefixes only when there is no resume
2251
- * target yet (the session's own first turn, or a def with no session memory at all, which never
2252
- * replays anything back at the CLI and so gets it on every turn).
2253
- *
2254
- * `'append-flag'` and `'env-var'` defs are the opposite case: the flag/env var is a fresh,
2255
- * un-stored per-spawn directive — never part of what a resumed session replays — so it is set on
2256
- * every turn unconditionally, exactly `claude`'s pre-existing (now-centralized) behavior before
2257
- * this function existed.
2258
- *
2259
- * @param input.defId - Looks up this def's probed capabilities for an `'append-flag'` strategy's
2260
- * `capabilityKey`. Otherwise unused — the dispatch itself is keyed off `systemPromptDelivery`, per
2261
- * this function's own doc above, never off the id.
2262
- * @param input.systemPromptDelivery - The def's declared strategy, or `undefined` for the fallback.
2263
- * @param input.resumesSessionViaCli - The def's own flag (see `RuntimeAgentDef`'s doc).
2264
- * @param input.resumesSessionViaAcpLoad - The def's own flag (see `RuntimeAgentDef`'s doc).
2265
- * @param input.overlay - The computed `PromptAugmenter.systemOverlay()` result. `null`/`undefined`/
2266
- * empty short-circuits to "no delivery" — byte-identical to no `PromptAugmenter` configured at all.
2267
- * @param input.prompt - The composed prompt `buildArgs` would otherwise receive verbatim.
2268
- * @param input.resumeSessionId - This run's `RuntimeContext.resumeSessionId`; presence means an
2269
- * existing session is being continued, not created.
2270
- * @returns A {@link SystemPromptOverlayDelivery}: the prefix this run's prompt text must carry
2271
- * (`''` unless the fallback applies), that prefix already applied to `input.prompt`, any extra argv
2272
- * to append to whatever `buildArgs` itself returns, and any env var overrides to merge into the
2273
- * spawn env (`{}` for every strategy but `'env-var'`). Every one of `run()`'s four prompt
2274
- * transports consumes this same result — see the interface's own no-double-delivery note.
2275
- * @complexity O(n) in the overlay/prompt lengths — string concatenation only, no I/O.
2276
- * @overallScore 100/100
2277
- */
2278
- export function resolveSystemPromptOverlayDelivery(input) {
2279
- const { defId, systemPromptDelivery, resumesSessionViaCli, resumesSessionViaAcpLoad, overlay, prompt, resumeSessionId } = input;
2280
- if (typeof overlay !== 'string' || overlay.length === 0) {
2281
- return { promptPrefix: '', prompt, extraArgs: [], envOverrides: {} };
2282
- }
2283
- if (systemPromptDelivery?.strategy === 'append-flag') {
2284
- const capabilityKey = systemPromptDelivery.capabilityKey;
2285
- // `!== false`, not a truthiness check: mirrors `claude.ts`'s own pre-existing
2286
- // `agentCapabilities.get('claude') || {}` gate exactly (moved here, not changed) — an
2287
- // undetected/never-probed capability defaults to allowed, and only an EXPLICIT `false` (the
2288
- // `--help` probe ran and did not find the flag) withholds it. `capabilityKey === undefined`
2289
- // (e.g. `pi`'s existing `--append-system-prompt`, trusted unconditionally) always passes, same
2290
- // as an absent key.
2291
- const capabilityOk = capabilityKey === undefined || agentCapabilities.get(defId)?.[capabilityKey] !== false;
2292
- return { promptPrefix: '', prompt, extraArgs: capabilityOk ? [systemPromptDelivery.flag, overlay] : [], envOverrides: {} };
2293
- }
2294
- if (systemPromptDelivery?.strategy === 'env-var') {
2295
- // No capability gate, unlike `'append-flag'`: an unrecognized env var is inert to a CLI (it
2296
- // simply never reads it), never a fatal "unknown option" exit — there is no equivalent hazard
2297
- // to probe-gate against here. Set verbatim, not merged with any existing value — a dedicated
2298
- // single-purpose var, not a shared config channel (see this field's own `types.ts` doc).
2299
- return { promptPrefix: '', prompt, extraArgs: [], envOverrides: { [systemPromptDelivery.varName]: overlay } };
2300
- }
2301
- if (systemPromptDelivery?.strategy === 'config-instructions-file') {
2302
- // Delivered elsewhere, not here: unlike `'append-flag'`/`'env-var'`, this mechanism needs real
2303
- // filesystem I/O (staging the overlay to a temp file — `opencode`'s `instructions` array only
2304
- // accepts a file path or URL, confirmed live, never inline text), which this function's "pure
2305
- // and synchronous" contract cannot perform. `prepareSystemPromptOverlayFileIfNeeded` (a separate
2306
- // async phase in `run()`, gated on this same strategy check) stages the file, and
2307
- // `computeChildEnv` merges its path into the config document via `mergeEnvContentInstructions`.
2308
- // This branch's only job is to make sure the universal prefix fallback below does NOT ALSO run
2309
- // for a def that already has this strategy declared — the same "no double delivery" concern
2310
- // `imageDelivery`'s doc calls out for its own native-vs-fallback split.
2311
- return { promptPrefix: '', prompt, extraArgs: [], envOverrides: {} };
2312
- }
2313
- const isContinuingExistingSession = (resumesSessionViaCli === true || resumesSessionViaAcpLoad === true) &&
2314
- typeof resumeSessionId === 'string' &&
2315
- resumeSessionId.length > 0;
2316
- if (isContinuingExistingSession) {
2317
- return { promptPrefix: '', prompt, extraArgs: [], envOverrides: {} };
2318
- }
2319
- // KNOWN TRADE-OFF, deliberate: for a resume-capable def with no `'append-flag'`/`'env-var'`
2320
- // mechanism yet (`codex`, `codebuddy`, `opencode`, `amr` — all four presently on this fallback),
2321
- // the overlay is therefore only injected on the SESSION-CREATING turn, not every turn. A host
2322
- // whose `PromptAugmenter.systemOverlay()` result can change mid-conversation (e.g. a host that
2323
- // lets an operator edit its own stored instructions and re-reads them before every run — see
2324
- // `prompt-augmenter.ts`'s own doc for the seam) will see NO effect from such an edit until a NEW
2325
- // session starts for one of these four defs specifically — a real, silent limitation, not a
2326
- // theoretical one. This is the correct
2327
- // trade against the alternative (re-injecting every turn would bake the overlay into that def's
2328
- // own CLI-persisted session history again and again, compounding without bound) — do not change
2329
- // this gating to "fix" the staleness. The actual fix is giving each of the four its own
2330
- // `'append-flag'`-equivalent `systemPromptDelivery` (an argv flag or an env var, neither of which
2331
- // is part of what a resumed session replays), which removes this limitation entirely for that
2332
- // def. See `reasonix.ts`'s and `opencode.ts`'s module docs for the two already-identified,
2333
- // not-yet-wired native mechanisms.
2334
- const promptPrefix = `${overlay}\n\n---\n\n`;
2335
- return { promptPrefix, prompt: `${promptPrefix}${prompt}`, extraArgs: [], envOverrides: {} };
2336
- }
2337
- /**
2338
- * Phase 9b: calls the def's `buildArgs`, releasing staged resources and failing the run on a throw.
2339
- *
2340
- * @param input.overlayDelivery - This run's already-resolved overlay decision, computed once in
2341
- * `run()` rather than here. It is resolved upstream because `buildArgs` is only ONE of the four
2342
- * channels that can carry the prompt: the staged prompt file is written *before* this function
2343
- * runs, and stdin/ACP/pi-rpc send theirs *after* spawn. A decision made inside this function could
2344
- * therefore only ever reach the 7 defs whose `buildArgs` reads its first argument at all — the
2345
- * other 17 declare it `_prompt` and discard it, which is exactly how the overlay used to go missing.
2346
- */
2347
- export async function buildRunArgs({ input, deps }) {
2348
- try {
2349
- const delivery = input.overlayDelivery;
2350
- const options = buildAgentBuildArgsOptions({ input: input.runInput, systemPromptOverlay: input.systemPromptOverlay });
2351
- const args = input.def.buildArgs({ prompt: delivery.prompt, imagePaths: [...(input.imagePaths ?? [])] }, {
2352
- ...(input.imageDelivery.extraAllowedDirs === undefined ? {} : { extraAllowedDirs: [...input.imageDelivery.extraAllowedDirs] }),
2353
- ...(options === undefined ? {} : { options }),
2354
- ...(input.runtimeContext === undefined ? {} : { runtimeContext: input.runtimeContext }),
2355
- });
2356
- // `'append-flag'` delivery's extra argv (empty for every other def/strategy) is appended after
2357
- // whatever the def's own `buildArgs` returned — safe because it is only ever non-empty for a
2358
- // `promptViaStdin` def with no trailing positional argv (`claude`/`pi` today; see
2359
- // `resolveSystemPromptOverlayDelivery`'s doc for why a future 'append-flag' def must keep that
2360
- // property too). `envOverrides` (non-empty only for `'env-var'` — `reasonix` today) is handed
2361
- // back rather than applied here, since the spawn env isn't finalized until `computeChildEnv`
2362
- // runs, later in `run()`.
2363
- return { args: [...args, ...delivery.extraArgs], envOverrides: delivery.envOverrides };
2364
- }
2365
- catch (err) {
2366
- await deps.releaseStagedResources();
2367
- return deps.failBeforeSpawn({ runId: input.runId, code: 'AGENT_SPAWN_FAILED', message: `AgentExecutor: could not build launch arguments for agent "${input.def.id}": ${errorMessage(err)}` });
2368
- }
2369
- }
2370
- /** 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). */
2371
- export async function writeMcpJsonIfNeeded({ input, deps }) {
2372
- if (input.mcpBridge?.kind !== 'claude-mcp-json' || deps.mcpJsonInjection === undefined) {
2373
- return undefined;
2374
- }
2375
- try {
2376
- await writeMcpJsonForRun(input.cwd, input.mcpBridge, deps.mcpJsonInjection);
2377
- return input.mcpBridge.mcpJsonPath;
2378
- }
2379
- catch (err) {
2380
- await deps.releaseStagedResources();
2381
- return deps.failBeforeSpawn({ runId: input.runId, code: 'AGENT_SPAWN_FAILED', message: `AgentExecutor: could not write .mcp.json for agent "${input.def.id}": ${errorMessage(err)}` });
2382
- }
2383
- }
2384
- /**
2385
- * Phase 10b1: `systemPromptDelivery: { strategy: 'config-instructions-file' }`'s one effect —
2386
- * stages the computed overlay to a fresh, run-scoped temp file, so `computeChildEnv` has a real
2387
- * path to merge into that def's `instructions` config array (see
2388
- * {@link mergeEnvContentInstructions}'s own doc for the live verification this mechanism rests on).
2389
- * `null` for every other strategy, an unset `systemPromptDelivery`, or no overlay present at all —
2390
- * byte-identical to before this mechanism existed, matching {@link writeMcpJsonIfNeeded}'s and
2391
- * {@link prepareCodexHomeIfNeeded}'s identical no-op-when-inapplicable gate.
2392
- *
2393
- * `opencode`'s `instructions` field only accepts a file path or a remote URL — confirmed live
2394
- * (2026-09-01): a literal instruction string in the array is silently ignored (no error, just never
2395
- * honored), so an inline-text shortcut is not available and this staging step is load-bearing, not
2396
- * a defensive extra.
2397
- * @param input.def - Only used for its `id`, in the failure message, and its `systemPromptDelivery` declaration.
2398
- * @param input.overlay - The computed `PromptAugmenter.systemOverlay()` result for this run.
2399
- * @complexity O(1) plus one directory creation and one file write.
2400
- * @overallScore 100/100
2401
- */
2402
- export async function prepareSystemPromptOverlayFileIfNeeded({ input, deps }) {
2403
- if (input.def.systemPromptDelivery?.strategy !== 'config-instructions-file' ||
2404
- typeof input.overlay !== 'string' ||
2405
- input.overlay.length === 0) {
2406
- return null;
2407
- }
2408
- try {
2409
- const safeRunId = input.runId.replace(/[^A-Za-z0-9_-]/g, '-').slice(0, 80) || 'run';
2410
- const dir = await fsPromises.mkdtemp(join(tmpdir(), `jini-system-prompt-overlay-${safeRunId}-`));
2411
- const filePath = join(dir, 'overlay.md');
2412
- await fsPromises.writeFile(filePath, input.overlay, { encoding: 'utf8', mode: 0o600 });
2413
- return {
2414
- path: filePath,
2415
- cleanup: async () => {
2416
- await fsPromises.rm(dir, { recursive: true, force: true });
2417
- },
2418
- };
2419
- }
2420
- catch (err) {
2421
- await deps.releaseStagedResources();
2422
- return deps.failBeforeSpawn({ runId: input.runId, code: 'AGENT_SPAWN_FAILED', message: `AgentExecutor: could not stage a system-prompt overlay file for agent "${input.def.id}": ${errorMessage(err)}` });
2423
- }
2424
- }
2425
- /**
2426
- * Phase 10b: mechanism 5 of 5's one effect — stages this run's scratch `CODEX_HOME` directory,
2427
- * returning the prepared handle `cleanupStagedFiles` should later release (`null` for every other
2428
- * mechanism, or for an unconfigured host — matching {@link writeMcpJsonIfNeeded}'s identical gate).
2429
- * @param input.def - Only used for its `id`, in the failure message.
2430
- * @param input.mcpBridge - This run's resolved bridge delivery — a no-op unless its `kind` is `'codex-toml'`.
2431
- * @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.
2432
- * @complexity O(1) plus {@link prepareCodexHomeForRun}'s own cost.
2433
- * @overallScore 100/100
2434
- */
2435
- export async function prepareCodexHomeIfNeeded({ input, deps }) {
2436
- if (input.mcpBridge?.kind !== 'codex-toml' || deps.mcpJsonInjection === undefined) {
2437
- return null;
2438
- }
2439
- try {
2440
- return await prepareCodexHomeForRun(input.runId, input.mcpBridge.serverEntry, resolveSourceCodexHomeDir({ hostEnv: deps.hostEnv }), resolveCodexHomeSeams(deps.mcpJsonInjection));
2441
- }
2442
- catch (err) {
2443
- await deps.releaseStagedResources();
2444
- return deps.failBeforeSpawn({ runId: input.runId, code: 'AGENT_SPAWN_FAILED', message: `AgentExecutor: could not stage a CODEX_HOME for agent "${input.def.id}": ${errorMessage(err)}` });
2445
- }
2446
- }
2447
- /**
2448
- * Finding 1 of SEC-assistant-env-isolation-2026-09-07's one effect — stages this run's scratch
2449
- * `CLAUDE_CONFIG_DIR` directory, returning the prepared handle `cleanupStagedFiles` should later
2450
- * release (`null` for every def other than `claude` — see {@link prepareClaudeConfigDirForRun}'s
2451
- * own doc for why this is unconditional for `claude` runs, unlike {@link prepareCodexHomeIfNeeded}'s
2452
- * gate on a host-configured MCP bridge strategy).
2453
- *
2454
- * Gated on `def.id === 'claude'` directly rather than on `externalMcpInjection === 'claude-mcp-json'`
2455
- * (which `codebuddy` also declares): isolating the operator's personal `~/.claude` is specific to
2456
- * the real `claude` CLI's own config resolution, not to every def that happens to share its `.mcp.
2457
- * json` delivery shape. Matches the existing `USER`-for-claude-login special case already singled
2458
- * out by id in `BASELINE_AGENT_ENV_KEYS`'s own doc, a few hundred lines above.
2459
- *
2460
- * ALSO gated on `deps.enabled` (`CreateAgentExecutorOptions.claudeConfigDirIsolationEnabled`, default
2461
- * `false`) since this task's own fix — see that field's doc for why it defaults off (Keychain login
2462
- * is `CLAUDE_CONFIG_DIR`-keyed and no caller was supplying a credential when this was unconditional).
2463
- * `def.id === 'claude'` is still checked first and independently: a host that flips this flag on
2464
- * should not suddenly stage a directory for `codebuddy` or any other def.
2465
- * @param input.def - Used for both the `id` gate and the failure message.
2466
- * @param deps.enabled - The isolation on/off switch — see this function's own doc above.
2467
- * @param deps.hostEnv - The daemon's own environment, threaded through to {@link resolveSourceClaudeConfigDir} rather than read from a module-level `process.env`, matching {@link prepareCodexHomeIfNeeded}'s identical testability reasoning.
2468
- * @complexity O(1) plus {@link prepareClaudeConfigDirForRun}'s own cost.
2469
- */
2470
- export async function prepareClaudeConfigDirIfNeeded({ input, deps }) {
2471
- if (input.def.id !== 'claude' || !deps.enabled) {
2472
- return null;
2473
- }
2474
- try {
2475
- return await prepareClaudeConfigDirForRun(input.runId, resolveSourceClaudeConfigDir({ hostEnv: deps.hostEnv }), resolveClaudeConfigDirSeams(deps.claudeConfigDirIsolation));
2476
- }
2477
- catch (err) {
2478
- await deps.releaseStagedResources();
2479
- return deps.failBeforeSpawn({ runId: input.runId, code: 'AGENT_SPAWN_FAILED', message: `AgentExecutor: could not stage a CLAUDE_CONFIG_DIR for agent "${input.def.id}": ${errorMessage(err)}` });
2480
- }
2481
- }
2482
- /** 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. */
2483
- export async function guardWindowsCommandLineBudget({ input, deps }) {
2484
- const windowsBudgetError = checkWindowsCmdShimCommandLineBudget({ def: input.def, resolvedBin: input.launchPath, args: input.args }) ??
2485
- checkWindowsDirectExeCommandLineBudget({ def: input.def, resolvedBin: input.launchPath, args: input.args });
2486
- if (windowsBudgetError) {
2487
- await deps.releaseStagedResources();
2488
- await deps.failBeforeSpawn({ runId: input.runId, code: 'AGENT_PROMPT_TOO_LARGE', message: windowsBudgetError.message });
2489
- }
2490
- }
2491
- /**
2492
- * Phase 12: the real `node:child_process.spawn` call.
2493
- *
2494
- * **Deliberately synchronous, unlike every other phase in this file.** A spawned child can emit
2495
- * `'error'` on the very next microtask tick (Node schedules it eagerly on some failure modes, and a
2496
- * test harness simulating "the child emits 'error' before 'spawn'" does so explicitly via
2497
- * `queueMicrotask`). `run()` must register its `'error'` listeners (`wireChildLifecycle`'s safety net,
2498
- * then `waitForSpawnOrError`'s `child.once('error', reject)`) in the *same synchronous turn* as this
2499
- * spawn call — Node's `EventEmitter` throws synchronously when `'error'` fires with zero listeners
2500
- * attached. Wrapping this call in an `async function` and `await`ing it (as every other phase here
2501
- * does) would insert a microtask tick between spawn and listener registration, occasionally losing
2502
- * that race — confirmed by a real test failure during this refactor (an uncaught `EventEmitter`
2503
- * `'error'` exception) before this function was changed back to a plain, unawaited call returning a
2504
- * result object instead of throwing/rejecting.
2505
- * @returns `{kind:'ok', child}` on success, `{kind:'error', error}` on a synchronous throw from `spawn`
2506
- * — `run()` itself is responsible for cleanup and `failBeforeSpawn` on the error variant, both of
2507
- * which are safe to make asynchronous since no child (and hence no listener race) exists yet.
2508
- * @complexity O(1) plus `spawn`'s own cost.
2509
- */
2510
- export function spawnAgentChildProcess({ input, deps }) {
2511
- try {
2512
- return {
2513
- kind: 'ok',
2514
- child: deps.spawn(input.invocation.command, input.invocation.args, {
2515
- cwd: input.cwd,
2516
- env: input.childEnv,
2517
- stdio: ['pipe', 'pipe', 'pipe'],
2518
- windowsVerbatimArguments: input.invocation.windowsVerbatimArguments,
2519
- }),
2520
- };
2521
- }
2522
- catch (error) {
2523
- return { kind: 'error', error };
2524
- }
2525
- }
2526
- /** 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`. */
2527
- export function isStdinDrivenFormat(args) {
2528
- const { streamFormat } = args;
2529
- return streamFormat !== 'acp-json-rpc' && streamFormat !== 'pi-rpc';
2530
- }
2531
- /** Phase 13: awaits spawn confirmation, routing a failure through the same `failBeforeSpawn` shape every earlier guard uses. */
2532
- export async function confirmChildSpawned({ input, deps }) {
2533
- try {
2534
- await waitForSpawnOrError(input.child);
2535
- }
2536
- catch (err) {
2537
- await deps.releaseStagedResources();
2538
- await deps.failBeforeSpawn({ runId: input.runId, code: 'AGENT_SPAWN_FAILED', message: `AgentExecutor: failed to spawn agent "${input.def.id}": ${errorMessage(err)}` });
2539
- }
2540
- }
2541
- /** 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. */
2542
- export function armHandoffWatcher({ runtimeLockHold, handoffInput, release }) {
2543
- if (!runtimeLockHold?.waitForHandoff)
2544
- return;
2545
- void runtimeLockHold.waitForHandoff(handoffInput).then(release, release);
2546
- }
2547
- /** Phase 15 (ACP branch): attaches the ACP session, escalating process-tree teardown and failing the run through `failBeforeSpawn` on an attach-time throw. */
2548
- export async function runAcpDispatch({ input, deps }) {
2549
- try {
2550
- wireAcpLifecycle({
2551
- runId: input.runId,
2552
- agentId: input.agentId,
2553
- child: input.child,
2554
- lifecycle: deps.lifecycle,
2555
- prompt: input.prompt,
2556
- cwd: input.cwd,
2557
- model: input.model,
2558
- imagePaths: input.imagePaths,
2559
- envFormat: input.envFormat,
2560
- // Mechanism 2 of 5 — see `WireAcpLifecycleContext.mcpServers`. `undefined` for any def that
2561
- // did not declare `'acp-merge'` and for an unconfigured host.
2562
- mcpServers: input.mcpBridge?.kind === 'acp-merge' ? input.mcpBridge.mcpServers : undefined,
2563
- onPermissionRequest: deps.onPermissionRequest,
2564
- attachAcpSession: deps.attachAcpSession,
2565
- listProcessSnapshots: deps.listProcessSnapshots,
2566
- collectProcessTreePids: deps.collectProcessTreePids,
2567
- stopProcesses: deps.stopProcesses,
2568
- onCleanupFailure: deps.onCleanupFailure,
2569
- cleanupStagedFiles: deps.cleanupStagedFiles,
2570
- journal: deps.journal,
2571
- classifyFailure: deps.classifyFailure,
2572
- });
2573
- }
2574
- catch (err) {
2575
- // Unlike the cancellation-listener call sites, we are already in an async function about to
2576
- // call finish() and throw — nothing else races this, so cleanup is awaited here rather than
2577
- // fired-and-forgotten (SEC-007: "await where lifecycle ordering allows it").
2578
- await terminateChildTreeBestEffort({ listProcessSnapshots: deps.listProcessSnapshots, collectProcessTreePids: deps.collectProcessTreePids, stopProcesses: deps.stopProcesses }, input.child, input.runId, 'acp-attach-failure', deps.onCleanupFailure);
2579
- await deps.releaseStagedResources();
2580
- await deps.failBeforeSpawn({ runId: input.runId, code: 'AGENT_SPAWN_FAILED', message: `AgentExecutor: could not attach ACP session for agent "${input.agentId}": ${errorMessage(err)}` });
2581
- }
2582
- }
2583
- /** Phase 15 (pi-rpc branch): same discipline as {@link runAcpDispatch}, for the one `'pi-rpc'` def. */
2584
- export async function runPiRpcDispatch({ input, deps }) {
2585
- try {
2586
- wirePiRpcLifecycle({
2587
- runId: input.runId,
2588
- agentId: input.agentId,
2589
- child: input.child,
2590
- lifecycle: deps.lifecycle,
2591
- prompt: input.prompt,
2592
- cwd: input.cwd,
2593
- model: input.model,
2594
- imagePaths: input.imagePaths,
2595
- uploadRoot: input.uploadRoot,
2596
- attachPiRpcSession: deps.attachPiRpcSession,
2597
- listProcessSnapshots: deps.listProcessSnapshots,
2598
- collectProcessTreePids: deps.collectProcessTreePids,
2599
- stopProcesses: deps.stopProcesses,
2600
- onCleanupFailure: deps.onCleanupFailure,
2601
- cleanupStagedFiles: deps.cleanupStagedFiles,
2602
- journal: deps.journal,
2603
- classifyFailure: deps.classifyFailure,
2604
- });
2605
- }
2606
- catch (err) {
2607
- // Same discipline as the ACP attach-failure path above: await cleanup here rather than
2608
- // fire-and-forget (SEC-007).
2609
- await terminateChildTreeBestEffort({ listProcessSnapshots: deps.listProcessSnapshots, collectProcessTreePids: deps.collectProcessTreePids, stopProcesses: deps.stopProcesses }, input.child, input.runId, 'pi-rpc-attach-failure', deps.onCleanupFailure);
2610
- await deps.releaseStagedResources();
2611
- await deps.failBeforeSpawn({ runId: input.runId, code: 'AGENT_SPAWN_FAILED', message: `AgentExecutor: could not attach pi-rpc session for agent "${input.agentId}": ${errorMessage(err)}` });
2612
- }
2613
- }
2614
- export function createAgentExecutor(requiredArgs, optionalArgs = {}) {
2615
- const options = { ...requiredArgs, ...optionalArgs };
2616
- const lifecycle = options.lifecycle;
2617
- const { getAgentDef: getAgentDefFn, resolveAgentLaunch: resolveAgentLaunchFn, ensureAgentCapabilities: ensureAgentCapabilitiesFn, applyAgentLaunchEnv: applyAgentLaunchEnvFn, attachAcpSession: attachAcpSessionFn, attachPiRpcSession: attachPiRpcSessionFn, preparePromptFileForAgent: preparePromptFileForAgentFn, prepareAgentLogFile: prepareAgentLogFileFn, } = resolveAgentRuntimeDeps(options);
2618
- const { createCommandInvocation: createCommandInvocationFn, spawn: spawnFn, listProcessSnapshots: listProcessSnapshotsFn, collectProcessTreePids: collectProcessTreePidsFn, stopProcesses: stopProcessesFn, } = resolveProcessDeps(options);
2619
- const { onCleanupFailure: onCleanupFailureFn, bufferedStdoutMaxBytes } = resolveMiscExecutorDeps(options);
2620
- const journal = options.journal;
2621
- const continuation = options.continuation;
2622
- const classifyFailure = options.classifyFailure;
2623
- const mcpJsonInjection = options.mcpJsonInjection;
2624
- const claudeConfigDirIsolation = options.claudeConfigDirIsolation;
2625
- const claudeConfigDirIsolationEnabled = options.claudeConfigDirIsolationEnabled ?? false;
2626
- const promptAugmenter = options.promptAugmenter;
2627
- /**
2628
- * Transitions `runId` to `'failed'` (idempotent, never resumable — no
2629
- * classifier exists, see module doc) then rejects with a typed
2630
- * {@link AgentExecutorError}. Every pre-spawn guard in `run()` returns
2631
- * this call directly.
2632
- * @param runId - The run to transition.
2633
- * @param code - The machine-readable failure reason.
2634
- * @param message - The human-readable rejection message.
2635
- * @throws Always — this function never returns normally.
2636
- * @complexity O(1) plus `lifecycle.finish()`'s own cost.
2637
- * @overallScore 100/100
2638
- */
2639
- async function failBeforeSpawn({ runId, code, message }) {
2640
- // The reason goes on the run's own stream before `end`, not only into the thrown error: the
2641
- // thrown error reaches the server log, while a chat client sees only this stream. Without it
2642
- // the user got a bare "Run failed". Best-effort: a stream that will not take the event must not
2643
- // stop the run from finishing.
2644
- await lifecycle
2645
- .emit({ runId: runId, input: { event: 'error', data: { message: `The assistant could not start: ${message.replace(/^AgentExecutor:\s*/, '')}` } } })
2646
- .catch(() => undefined);
2647
- await lifecycle.finish({ runId, status: 'failed', code: null, signal: null, resumable: false });
2648
- throw new AgentExecutorError({ code: code, message: message });
2649
- }
2650
- /**
2651
- * `AgentExecutor.run()` — see that interface method's own doc for the
2652
- * public contract. Implementation note on shape: every guard below
2653
- * returns `failBeforeSpawn(...)` directly (a `Promise<never>`, valid
2654
- * wherever `Promise<void>` is expected) rather than `await`-then-`return`,
2655
- * so each failure path reads as a single, obviously-terminal statement.
2656
- * @param input - `{runId, agentId, prompt, cwd, model?, reasoning?, imagePaths?, extraAllowedDirs?, uploadRoot?, env?}` — `runId` must already be `lifecycle.start()`-ed.
2657
- * @throws {@link AgentExecutorError} — see module doc's Invariant; never a bare `Error`.
2658
- * @complexity O(1) setup (registry lookup, launch resolution, one spawn call); steady-state cost thereafter belongs to {@link wireChildLifecycle}.
2659
- * @overallScore 100/100
2660
- */
2661
- async function run(requiredArgs, optionalArgs = {}) {
2662
- const input = { ...requiredArgs, ...optionalArgs, permissionMode: optionalArgs.permissionMode ?? 'restricted' };
2663
- if (input.permissionMode !== 'restricted' && input.permissionMode !== 'bypass') {
2664
- return failBeforeSpawn({ runId: input.runId, code: 'AGENT_PERMISSION_MODE_INVALID', message: 'AgentExecutor: permissionMode must be restricted or bypass' });
2665
- }
2666
- const { def, streamFormat } = await resolveDefAndStreamFormat({ input: { runId: input.runId, agentId: input.agentId }, deps: { getAgentDef: getAgentDefFn, failBeforeSpawn } });
2667
- // Computed once, before anything downstream ever looks at "the prompt" or "the allowed
2668
- // dirs" — a no-op (`{prompt: input.prompt, extraAllowedDirs: input.extraAllowedDirs}`,
2669
- // literally unchanged) unless `def.imageDelivery === 'prompt-path'` AND `input.imagePaths`
2670
- // is non-empty, so this can never affect a 'native'-delivery def (ACP, pi-rpc, qoder) or a
2671
- // run with no attachments. See `image-prompt-delivery.ts`'s own doc for the full mechanism;
2672
- // every use of `input.prompt`/`input.extraAllowedDirs` below that reflects what the CLI
2673
- // actually receives reads `imageDelivery.*` instead — the two ACP/pi-rpc `wire*Lifecycle`
2674
- // calls further down deliberately keep reading `input.prompt` verbatim, since those two
2675
- // defs' own native protocol already delivers the image and must never also get this
2676
- // treatment (the double-delivery hazard this mechanism exists to avoid).
2677
- const imageDelivery = await resolveImageDeliveryAndArgvBudget({ input: { runId: input.runId, def, prompt: input.prompt, imagePaths: input.imagePaths, extraAllowedDirs: input.extraAllowedDirs }, deps: { failBeforeSpawn } });
2678
- // Phase 8, hoisted deliberately above EVERY step that writes or sends the prompt. Four
2679
- // different channels carry a prompt in this driver, and they do not all run at the same point:
2680
- // the `promptViaFile` staging below writes its file BEFORE `buildArgs`, `buildArgs` itself runs
2681
- // mid-`run()`, and stdin/ACP/pi-rpc all send theirs AFTER spawn. Resolving the overlay once,
2682
- // here, is what lets all four consume the same decision; resolving it later (as this used to,
2683
- // inside `buildRunArgs`) could only ever reach `buildArgs`, so the 17 defs that discard that
2684
- // argument, plus grok-build's staged file, silently received no overlay at all.
2685
- //
2686
- // `computeSystemPromptOverlay`'s third argument is the pre-staging `RuntimeContext`: it reads
2687
- // only `hasPriorAssistantTurn`, which `computeRuntimeContext` never populates from any of the
2688
- // staged-file/MCP inputs added to the fuller context built further down, so nothing between
2689
- // here and there can change the overlay this returns. Passing the narrower context makes that
2690
- // independence explicit rather than relying on the ordering staying lucky.
2691
- //
2692
- // `turnIndex` is a coarse 0/1 proxy (no exact turn counter exists on this driver) — sufficient
2693
- // because every `PromptAugmenter.systemOverlay()` implementation this seam has today wants the
2694
- // same overlay on every turn, not a first-turn-only one; a caller that needs finer-grained turn
2695
- // numbering can track it itself and ignore this arg.
2696
- const preStagingRuntimeContext = computeRuntimeContext({ preparedPromptFile: null, preparedLogFile: null, mcpBridge: null }, {
2697
- ...(input.resumeSessionId === undefined ? {} : { resumeSessionId: input.resumeSessionId }),
2698
- ...(input.newSessionId === undefined ? {} : { newSessionId: input.newSessionId }),
2699
- });
2700
- const systemPromptOverlay = computeSystemPromptOverlay(promptAugmenter, def.id, preStagingRuntimeContext);
2701
- const overlayDelivery = resolveSystemPromptOverlayDelivery({
2702
- defId: def.id,
2703
- systemPromptDelivery: def.systemPromptDelivery,
2704
- resumesSessionViaCli: def.resumesSessionViaCli,
2705
- resumesSessionViaAcpLoad: def.resumesSessionViaAcpLoad,
2706
- overlay: systemPromptOverlay,
2707
- prompt: imageDelivery.prompt,
2708
- resumeSessionId: preStagingRuntimeContext?.resumeSessionId,
2709
- });
2710
- // The def's own declared env (e.g. claude's `ENABLE_TOOL_SEARCH=false`) is a default the run's
2711
- // env can override. Detection already spawns with it (`detection.ts`); without this the run
2712
- // spawn silently dropped it. Declared by the def itself, so it never widens SEC-001's allowlist.
2713
- const resolvedEnv = { ...(def.env ?? {}), ...resolveRunEnv({ input: input, hostEnv: process.env }) };
2714
- const launch = await resolveLaunch({ input: { runId: input.runId, def, resolvedEnv }, deps: { resolveAgentLaunch: resolveAgentLaunchFn, failBeforeSpawn } });
2715
- const spawnEnv = applyAgentLaunchEnvFn({ env: { ...resolvedEnv }, launch });
2716
- // Fill the def's `--help` capability gate before `buildArgs` reads it. Without this, only a
2717
- // host that happened to call `detectAgents` in THIS process ever had the gate filled, so e.g.
2718
- // `claude` never got `--include-partial-messages` (no streamed text). Probes once per binary;
2719
- // never rejects (a failed probe keeps the safe no-optional-flags baseline).
2720
- await ensureAgentCapabilitiesFn({ def, launchPath: launch.launchPath, env: spawnEnv });
2721
- // Stage a promptViaFile def's (grok-build) prompt to a temp file before buildArgs runs — its
2722
- // buildArgs throws without runtimeContext.promptFilePath. A no-op (returns null) for every
2723
- // def without promptViaFile: true (preparePromptFileForAgent's own guard).
2724
- //
2725
- // `overlayDelivery.prompt`, not `imageDelivery.prompt`: for a `promptViaFile` def this file IS
2726
- // the prompt transport — its `buildArgs` declares `_prompt` and passes only the path — so the
2727
- // overlay has to be in the bytes written here or the CLI never sees it at all.
2728
- const preparedPromptFile = await stagePromptFile({ input: { runId: input.runId, def, prompt: overlayDelivery.prompt }, deps: { preparePromptFileForAgent: preparePromptFileForAgentFn, failBeforeSpawn } });
2729
- // Stage a needsAgentLogFile def's (antigravity) diagnostic-log path, on the same terms and at
2730
- // the same point as the prompt file above: before buildArgs, since buildArgs is what turns the
2731
- // path into a `--log-file <path>` argument. A no-op (returns null) for every def without
2732
- // `needsAgentLogFile: true` (prepareAgentLogFile's own guard). Sequenced after the prompt file
2733
- // rather than concurrently so the failure path above has exactly one thing to clean up.
2734
- const preparedLogFile = await stageLogFile({ input: { runId: input.runId, def, preparedPromptFile }, deps: { prepareAgentLogFile: prepareAgentLogFileFn, failBeforeSpawn } });
2735
- // Cleaned up after the child exits (wireChildLifecycle/wireAcpLifecycle/wirePiRpcLifecycle's
2736
- // close handlers) and on every pre-spawn/spawn-failure path below — a leaked temp file
2737
- // containing the full prompt, or whatever the CLI chose to write into its log, is a
2738
- // confidentiality gap, not just a disk leak. One composed closure covering both staged files;
2739
- // see `WireChildLifecycleContext.cleanupStagedFiles`'s doc for why they are not two fields.
2740
- /**
2741
- * Set once `writeMcpJsonForRun` has actually written this run's MCP config, so `cleanupStagedFiles`
2742
- * knows there is a file holding a live bearer token to remove. Cleared as it is consumed, so the
2743
- * removal happens exactly once across the several paths that may call the cleanup. Only the
2744
- * `'claude-mcp-json'` mechanism stages a file at all — `'acp-merge'` and `'env-content'` leave
2745
- * nothing on disk, so this stays `undefined` for those.
2746
- */
2747
- let writtenMcpJsonPath;
2748
- const removeMcpJsonFileFn = mcpJsonInjection?.removeFile ?? defaultRemoveMcpJsonFile;
2749
- /**
2750
- * Set once `prepareCodexHomeIfNeeded` has actually staged this run's scratch `CODEX_HOME`, so
2751
- * `cleanupStagedFiles` knows there is a directory holding a copied login credential to remove.
2752
- * Cleared as it is consumed, matching `writtenMcpJsonPath`'s identical single-removal discipline.
2753
- * Only the `'codex-toml'` mechanism stages a directory at all.
2754
- */
2755
- let preparedCodexHome = null;
2756
- /**
2757
- * Set once `prepareClaudeConfigDirIfNeeded` has actually staged this run's scratch
2758
- * `CLAUDE_CONFIG_DIR`, so `cleanupStagedFiles` knows there is a directory (possibly holding a
2759
- * copied login credential) to remove. Cleared as it is consumed, matching `preparedCodexHome`'s
2760
- * identical single-removal discipline. Only a `claude`-id run stages a directory this way.
2761
- */
2762
- let preparedClaudeConfigDir = null;
2763
- /**
2764
- * Set once `prepareSystemPromptOverlayFileIfNeeded` has actually staged this run's overlay file
2765
- * for a `'config-instructions-file'` def, so `cleanupStagedFiles` knows there is a temp
2766
- * directory to remove. Cleared as it is consumed, matching `preparedCodexHome`'s identical
2767
- * single-removal discipline. Only that one strategy stages a file this way — `null` for every
2768
- * other def/strategy/no-overlay run.
2769
- */
2770
- let preparedSystemPromptOverlayFile = null;
2771
- const cleanupStagedFiles = async () => {
2772
- if (preparedPromptFile)
2773
- await preparedPromptFile.cleanup();
2774
- if (preparedLogFile)
2775
- await preparedLogFile.cleanup();
2776
- if (writtenMcpJsonPath !== undefined) {
2777
- const mcpJsonFileToRemove = writtenMcpJsonPath;
2778
- writtenMcpJsonPath = undefined;
2779
- await removeMcpJsonFileFn({ path: mcpJsonFileToRemove });
2780
- }
2781
- if (preparedCodexHome) {
2782
- const codexHomeToRemove = preparedCodexHome;
2783
- preparedCodexHome = null;
2784
- await codexHomeToRemove.cleanup();
2785
- }
2786
- if (preparedClaudeConfigDir) {
2787
- const claudeConfigDirToRemove = preparedClaudeConfigDir;
2788
- preparedClaudeConfigDir = null;
2789
- await claudeConfigDirToRemove.cleanup();
2790
- }
2791
- if (preparedSystemPromptOverlayFile) {
2792
- const overlayFileToRemove = preparedSystemPromptOverlayFile;
2793
- preparedSystemPromptOverlayFile = null;
2794
- await overlayFileToRemove.cleanup();
2795
- }
2796
- };
2797
- // Resolve this run's MCP bridge delivery once, before buildArgs — the `'claude-mcp-json'`
2798
- // variant's path has to be in `runtimeContext` for that def's own `--mcp-config` argv, and
2799
- // resolving here means the per-run bearer credential is minted exactly once no matter which of
2800
- // the five mechanisms ends up carrying it. `null` for an unconfigured host or a def declaring
2801
- // no strategy — see `buildMcpBridgeDelivery`'s doc.
2802
- const mcpBridge = await resolveMcpBridgeForRun({ input: { runId: input.runId, cwd: input.cwd, def }, deps: { mcpJsonInjection, cleanupStagedFiles, failBeforeSpawn } });
2803
- const runtimeContext = computeRuntimeContext({ preparedPromptFile: preparedPromptFile, preparedLogFile: preparedLogFile, mcpBridge: mcpBridge }, {
2804
- ...(input.resumeSessionId === undefined ? {} : { resumeSessionId: input.resumeSessionId }),
2805
- ...(input.newSessionId === undefined ? {} : { newSessionId: input.newSessionId }),
2806
- });
2807
- // A `runtimeLock` def's buildArgs mutates process-global state its own CLI reads back at
2808
- // startup, so the mutex must be held from before buildArgs until the spawned child has
2809
- // demonstrably consumed it — see `RuntimeLock`'s own doc for the concrete race. Undefined for
2810
- // 23 of 24 defs, in which case nothing below waits on anything.
2811
- const selectedModel = input.model;
2812
- const runtimeLockHold = await acquireRuntimeLockIfConfigured(def, selectedModel);
2813
- // Aborts once the spawned process is gone — or immediately, on a path where no process ever
2814
- // ran — so a def's own handoff watcher can never outlive the run it was polling for.
2815
- const processExitedController = new AbortController();
2816
- /**
2817
- * Releases the runtime lock and cancels any handoff watcher. Safe to call from any number of
2818
- * paths: `AbortController.abort()` after the first is a no-op, and `RuntimeLockHold.release`
2819
- * is idempotent by contract.
2820
- */
2821
- const releaseRuntimeLock = () => {
2822
- processExitedController.abort();
2823
- runtimeLockHold?.release();
2824
- };
2825
- /** Both staged-file and lock release, for the pre-spawn/spawn-failure paths that own neither a child nor a close handler. */
2826
- const releaseStagedResources = async () => {
2827
- releaseRuntimeLock();
2828
- await cleanupStagedFiles();
2829
- };
2830
- // Guarded, like every other step between staging and spawn: a `runtimeLock` def's `buildArgs` is
2831
- // guarded precisely *because* it performs real filesystem writes (antigravity writes its model
2832
- // choice into a shared settings file), so EACCES on a read-only home, ENOSPC, or a malformed
2833
- // existing settings file all reach here as a throw. Unguarded, that escaped `run()` as a bare
2834
- // `Error` — breaking this driver's "never a bare throw, always an `AgentExecutorError`" contract
2835
- // — and left the run `'running'` forever while still holding the process-global mutex and both
2836
- // staged files, so no later run of that def could ever acquire the lock either.
2837
- const { args, envOverrides: systemPromptEnvOverrides } = await buildRunArgs({ input: { runId: input.runId, def, imageDelivery, imagePaths: input.imagePaths, runInput: input, systemPromptOverlay, overlayDelivery, runtimeContext }, deps: { releaseStagedResources, failBeforeSpawn } });
2838
- // Mechanism 1 of 5's one effect — stage this run's own MCP config file (run-scoped, see
2839
- // `mcpJsonPathForRun`) before spawn so the `--mcp-config <path>` argv buildArgs just produced
2840
- // points at a real file. Skipped entirely for the other four mechanisms and whenever no bridge
2841
- // was resolved at all. `writtenMcpJsonPath` is set only once the write actually happens, so
2842
- // `cleanupStagedFiles` knows there is a live-token file to remove afterward.
2843
- writtenMcpJsonPath = await writeMcpJsonIfNeeded({ input: { runId: input.runId, cwd: input.cwd, def, mcpBridge }, deps: { mcpJsonInjection, releaseStagedResources, failBeforeSpawn } });
2844
- // Mechanism 5 of 5's one effect — stage this run's scratch `CODEX_HOME` directory. Skipped
2845
- // entirely for the other four mechanisms and whenever no bridge was resolved at all.
2846
- // `codex.ts`'s `buildArgs` needs no argv change for this (CODEX_HOME is an env var, not a flag),
2847
- // so — unlike the `.mcp.json` staging above — this can run after `buildArgs` with no ordering
2848
- // constraint of its own; it is placed here only to keep the two staging steps adjacent.
2849
- preparedCodexHome = await prepareCodexHomeIfNeeded({ input: { runId: input.runId, def, mcpBridge }, deps: { mcpJsonInjection, hostEnv: process.env, releaseStagedResources, failBeforeSpawn } });
2850
- // Finding 1 of SEC-assistant-env-isolation-2026-09-07's one effect — stage this run's scratch
2851
- // `CLAUDE_CONFIG_DIR` directory. Unconditional for a `claude`-id run (unlike CODEX_HOME above,
2852
- // this does not depend on `mcpJsonInjection` being configured at all — see
2853
- // `prepareClaudeConfigDirIfNeeded`'s own doc for why). Placed here only to stay adjacent to the
2854
- // other pre-`computeChildEnv` staging steps; `claude.ts`'s `buildArgs` needs no argv change for
2855
- // this (CLAUDE_CONFIG_DIR is an env var, not a flag), same as CODEX_HOME.
2856
- preparedClaudeConfigDir = await prepareClaudeConfigDirIfNeeded({ input: { runId: input.runId, def }, deps: {
2857
- enabled: claudeConfigDirIsolationEnabled,
2858
- claudeConfigDirIsolation,
2859
- hostEnv: process.env,
2860
- releaseStagedResources,
2861
- failBeforeSpawn,
2862
- } });
2863
- // `'config-instructions-file'`'s one effect — stage the overlay to a temp file so
2864
- // `computeChildEnv` below has a real path to merge into that def's `instructions` array. A
2865
- // no-op (`null`) for every other def/strategy or a run with no overlay at all. Independent of
2866
- // `mcpBridge`/`preparedCodexHome` above (a different strategy field entirely), so placed here
2867
- // only to stay adjacent to the other pre-`computeChildEnv` staging steps, not for any ordering
2868
- // requirement between them.
2869
- preparedSystemPromptOverlayFile = await prepareSystemPromptOverlayFileIfNeeded({ input: { runId: input.runId, def, overlay: systemPromptOverlay }, deps: { releaseStagedResources, failBeforeSpawn } });
2870
- // Computed only now, not right after `mcpBridge` resolution: mechanism 5's directory path is
2871
- // not known until the staging step directly above actually runs `mkdtemp` (see
2872
- // `McpBridgeDelivery`'s `'codex-toml'` variant doc for why it cannot be pre-computed the way
2873
- // `'claude-mcp-json'`'s deterministic path is). Nothing between the old, earlier call site and
2874
- // here ever read `childEnv`, so moving the call cost nothing.
2875
- const childEnv = computeChildEnv({ spawnEnv: spawnEnv, mcpBridge: mcpBridge }, {
2876
- ...(preparedCodexHome === null ? {} : { codexHomeDir: preparedCodexHome.path }),
2877
- systemPromptEnvOverrides,
2878
- ...(preparedSystemPromptOverlayFile && def.systemPromptDelivery?.strategy === 'config-instructions-file'
2879
- ? { stagedInstructionsFile: { varName: def.systemPromptDelivery.varName, path: preparedSystemPromptOverlayFile.path } }
2880
- : {}),
2881
- ...(preparedClaudeConfigDir === null ? {} : { claudeConfigDir: preparedClaudeConfigDir.path }),
2882
- });
2883
- // Post-buildArgs guard for argv-bound defs whose resolved binary is a
2884
- // Windows .cmd/.bat shim or a direct .exe: a prompt under the raw byte
2885
- // budget can still expand past CreateProcess's command-line cap once
2886
- // quote-escaped. Both are no-ops off-Windows / for non-argv-bound defs.
2887
- await guardWindowsCommandLineBudget({ input: { runId: input.runId, def, launchPath: launch.launchPath, args }, deps: { releaseStagedResources, failBeforeSpawn } });
2888
- const invocation = createCommandInvocationFn({ command: launch.launchPath, args, env: childEnv });
2889
- // Kept a synchronous call (no `await`) on purpose — see `spawnAgentChildProcess`'s own doc for
2890
- // the microtask-timing race this avoids. The error branch's own cleanup/failBeforeSpawn calls are
2891
- // async, which is fine: no child exists yet on that path, so nothing is racing a listener.
2892
- const spawnResult = spawnAgentChildProcess({ input: { cwd: input.cwd, childEnv, invocation }, deps: { spawn: spawnFn } });
2893
- if (spawnResult.kind === 'error') {
2894
- await releaseStagedResources();
2895
- return failBeforeSpawn({ runId: input.runId, code: 'AGENT_SPAWN_FAILED', message: `AgentExecutor: spawn threw synchronously for agent "${def.id}": ${errorMessage(spawnResult.error)}` });
2896
- }
2897
- const child = spawnResult.child;
2898
- // Registered before the spawn-confirmation await below, for the same reason
2899
- // `wireChildLifecycle` is: a child that exits immediately must not slip past the listener.
2900
- // `'exit'` rather than `'close'` on purpose — a `runtimeLock` guards state the *process* reads,
2901
- // so the process being gone is the release condition, not its stdio pipes draining (which a
2902
- // grandchild inheriting them can delay arbitrarily). A spawn that never produced a process at
2903
- // all emits no `'exit'`, and is covered instead by `releaseStagedResources` on the reject path.
2904
- child.once('exit', releaseRuntimeLock);
2905
- const formatForStdin = { streamFormat };
2906
- const stdinHandle = isStdinDrivenFormat(formatForStdin)
2907
- ? wireChildLifecycle({
2908
- runId: input.runId,
2909
- def,
2910
- streamFormat: formatForStdin.streamFormat,
2911
- child,
2912
- lifecycle,
2913
- listProcessSnapshots: listProcessSnapshotsFn,
2914
- collectProcessTreePids: collectProcessTreePidsFn,
2915
- stopProcesses: stopProcessesFn,
2916
- onCleanupFailure: onCleanupFailureFn,
2917
- cleanupStagedFiles,
2918
- journal,
2919
- continuation,
2920
- classifyFailure,
2921
- bufferedStdoutMaxBytes,
2922
- expectsJiniBridge: writtenMcpJsonPath !== undefined,
2923
- })
2924
- : null;
2925
- await confirmChildSpawned({ input: { runId: input.runId, def, child }, deps: { releaseStagedResources, failBeforeSpawn } });
2926
- // Now — and only now — is there a live process that could consume the locked side effect, so
2927
- // this is where a def's handoff watcher starts. Deliberately not awaited: the whole point is to
2928
- // release the lock as soon as the child confirms the handoff, in parallel with this run
2929
- // continuing. Rejection releases too — a lock stuck open because a watcher threw is strictly
2930
- // worse than releasing early (see `RuntimeLockHold.waitForHandoff`'s own doc).
2931
- armHandoffWatcher({ runtimeLockHold: runtimeLockHold, handoffInput: { logFilePath: preparedLogFile?.path, model: selectedModel, processExited: processExitedController.signal }, release: releaseRuntimeLock });
2932
- if (streamFormat === 'acp-json-rpc') {
2933
- await runAcpDispatch({ input: {
2934
- runId: input.runId,
2935
- agentId: def.id,
2936
- child,
2937
- // `overlayDelivery.promptPrefix` applied to `input.prompt`, NOT `overlayDelivery.prompt`:
2938
- // this call site deliberately sends the raw input prompt rather than the image-delivery
2939
- // rewrite (see `resolveImageDeliveryAndArgvBudget`'s call site above — an ACP def delivers
2940
- // images natively and must never also get `'prompt-path'`'s appended paths), and the prefix
2941
- // is the part of the overlay decision that applies to whatever prompt text a transport was
2942
- // already sending. `''` for `reasonix` (env-var) and any resumed ACP session, so those keep
2943
- // sending byte-identical text and never receive the overlay twice.
2944
- prompt: `${overlayDelivery.promptPrefix}${input.prompt}`,
2945
- cwd: input.cwd,
2946
- model: input.model,
2947
- imagePaths: input.imagePaths ?? [],
2948
- envFormat: def.acpMcpEnvFormat,
2949
- mcpBridge,
2950
- }, deps: {
2951
- lifecycle,
2952
- attachAcpSession: attachAcpSessionFn,
2953
- onPermissionRequest: options.acpPermissionHandler,
2954
- listProcessSnapshots: listProcessSnapshotsFn,
2955
- collectProcessTreePids: collectProcessTreePidsFn,
2956
- stopProcesses: stopProcessesFn,
2957
- onCleanupFailure: onCleanupFailureFn,
2958
- cleanupStagedFiles,
2959
- journal,
2960
- classifyFailure,
2961
- releaseStagedResources,
2962
- failBeforeSpawn,
2963
- } });
2964
- return;
2965
- }
2966
- if (streamFormat === 'pi-rpc') {
2967
- await runPiRpcDispatch({ input: {
2968
- runId: input.runId,
2969
- agentId: def.id,
2970
- child,
2971
- // Same reasoning as the ACP call site above. `pi` declares an `'append-flag'` strategy,
2972
- // so its prefix is `''` and this stays byte-identical to the raw prompt — the overlay
2973
- // rides `--append-system-prompt` instead, exactly once.
2974
- prompt: `${overlayDelivery.promptPrefix}${input.prompt}`,
2975
- cwd: input.cwd,
2976
- model: input.model,
2977
- imagePaths: input.imagePaths ?? [],
2978
- uploadRoot: input.uploadRoot,
2979
- }, deps: {
2980
- lifecycle,
2981
- attachPiRpcSession: attachPiRpcSessionFn,
2982
- listProcessSnapshots: listProcessSnapshotsFn,
2983
- collectProcessTreePids: collectProcessTreePidsFn,
2984
- stopProcesses: stopProcessesFn,
2985
- onCleanupFailure: onCleanupFailureFn,
2986
- cleanupStagedFiles,
2987
- journal,
2988
- classifyFailure,
2989
- releaseStagedResources,
2990
- failBeforeSpawn,
2991
- } });
2992
- return;
2993
- }
2994
- // The overlay reaches stdin only for a def that declares stdin as its prompt transport. The
2995
- // four `plain`-format defs that do not (`aider`/`antigravity`/`deepseek` put the prompt in
2996
- // argv, `grok-build` in a staged file) are still written to and closed here exactly as before,
2997
- // because this driver always spawns with `stdio: ['pipe','pipe','pipe']` and their CLIs need
2998
- // the EOF — but their prompt already carried the overlay through argv or the staged file, so
2999
- // sending the overlaid text here too would deliver it twice. This is the one place the
3000
- // resolver's own `''`-prefix rule is not sufficient on its own: those four defs are on the
3001
- // fallback strategy, so their prefix is genuinely non-empty; what makes stdin the wrong
3002
- // channel for them is the def's declared transport, not the strategy.
3003
- const stdinPrompt = def.promptViaStdin === true ? overlayDelivery.prompt : imageDelivery.prompt;
3004
- if (input.imageContents !== undefined)
3005
- stdinHandle.imageContents = input.imageContents;
3006
- writePromptToStdin(def, child, stdinPrompt, stdinHandle);
3007
- }
3008
- return { run };
3009
- }
9
+ export { isSupportedStreamFormat, assessAgentExecutorCompatibility, isAgentExecutorSupported, extractUsageTokens, translateStatusEvent, translateToolResultEvent, translateErrorEvent, translateTurnEndEvent, translateAgentRuntimeEvent, AgentExecutorError, MCP_BRIDGE_UNAVAILABLE, unavailableJiniBridgeStatus, buildMcpJsonServerEntry, mergeMcpJsonContent, buildAcpMcpBridgeServers, mergeEnvContentMcpConfig, mergeEnvContentInstructions, buildCodexMcpServerToml, buildCodexHomeConfigToml, resolveSourceCodexHomeDir, buildMcpBridgeDelivery, resolveSourceClaudeConfigDir, DEFAULT_BUFFERED_STDOUT_MAX_BYTES, applyAgentTranslationSideEffects, resolveDefAndStreamFormat, resolveImageDeliveryAndArgvBudget, resolveRunEnv, resolveLaunch, stagePromptFile, stageLogFile, resolveMcpBridgeForRun, computeChildEnv, computeRuntimeContext, buildAgentBuildArgsOptions, resolveSystemPromptOverlayDelivery, buildRunArgs, writeMcpJsonIfNeeded, prepareSystemPromptOverlayFileIfNeeded, prepareCodexHomeIfNeeded, prepareClaudeConfigDirIfNeeded, guardWindowsCommandLineBudget, spawnAgentChildProcess, isStdinDrivenFormat, confirmChildSpawned, armHandoffWatcher, runAcpDispatch, runPiRpcDispatch, createAgentExecutor, } from './agent-executor/index.js';
3010
10
  //# sourceMappingURL=agent-executor.js.map