codex-supervisor-mcp 0.13.5 → 0.13.6
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.
- package/package.json +18 -63
- package/src/{acceptance.js → app/acceptance.js} +54 -68
- package/src/app/cancel.js +60 -0
- package/src/{cleanup-plan.js → app/cleanup-plan.js} +11 -12
- package/src/app/compose.js +7 -0
- package/src/{context-compiler.js → app/context-compiler.js} +7 -13
- package/src/app/dispatch.js +396 -0
- package/src/app/followup.js +98 -0
- package/src/app/land-chain.js +124 -0
- package/src/app/landing.js +357 -0
- package/src/app/ownership.js +57 -0
- package/src/app/rebase.js +216 -0
- package/src/app/resume.js +164 -0
- package/src/app/run-state.js +26 -0
- package/src/app/settled.js +28 -0
- package/src/{side-chat.js → app/side-chat.js} +79 -265
- package/src/app/sse.js +20 -0
- package/src/app/start-run.js +77 -0
- package/src/app/verify-push.js +119 -0
- package/src/app/worktree-setup.js +176 -0
- package/src/{acceptance-baseline.js → domain/acceptance-baseline.js} +2 -1
- package/src/domain/acceptance-spec.js +30 -0
- package/src/domain/command-outcome.js +6 -0
- package/src/{overview-delta.js → domain/overview-delta.js} +5 -1
- package/src/domain/side-turn-view.js +73 -0
- package/src/{worker-preflight.js → domain/worker-preflight.js} +1 -1
- package/src/infra/git.js +30 -0
- package/src/infra/process.js +59 -0
- package/src/{sandbox-roots.js → infra/sandbox-roots.js} +2 -1
- package/src/{skill-sync.js → infra/skill-sync.js} +1 -1
- package/src/infra/store/db.js +265 -0
- package/src/infra/store/events.js +146 -0
- package/src/infra/store/facts.js +338 -0
- package/src/infra/store/reconcile.js +172 -0
- package/src/infra/store/records.js +160 -0
- package/src/infra/store/runner-readers.js +16 -0
- package/src/infra/store/schema.js +306 -0
- package/src/infra/store/sessions.js +138 -0
- package/src/infra/store/tasks.js +307 -0
- package/src/{auto-update-worker.js → infra/update/auto-update-worker.js} +4 -4
- package/src/{auto-update.js → infra/update/auto-update.js} +3 -3
- package/src/{update-check.js → infra/update/update-check.js} +4 -4
- package/src/{workspace-kind.js → infra/workspace-kind.js} +5 -7
- package/src/{worktree.js → infra/worktree.js} +56 -41
- package/src/{acceptance-cli.js → interface/bin/acceptance-cli.js} +7 -3
- package/src/{cleanup.js → interface/bin/cleanup.js} +3 -2
- package/src/{monitor.jsx → interface/bin/monitor.jsx} +4 -1
- package/src/{setup.js → interface/bin/setup.js} +7 -6
- package/src/{stage.js → interface/bin/stage.js} +1 -1
- package/src/{web-server.js → interface/bin/web-server.js} +2 -2
- package/src/interface/mcp/meta.js +7 -0
- package/src/interface/mcp/result.js +34 -0
- package/src/interface/mcp/schemas.js +24 -0
- package/src/interface/mcp/server.js +94 -0
- package/src/interface/mcp/tools/delivery.js +197 -0
- package/src/interface/mcp/tools/dispatch.js +267 -0
- package/src/interface/mcp/tools/facts.js +239 -0
- package/src/interface/mcp/tools/overview.js +202 -0
- package/src/interface/mcp/tools/poll.js +62 -0
- package/src/interface/mcp/tools/results.js +270 -0
- package/src/interface/mcp/tools/review.js +135 -0
- package/src/interface/mcp/tools/wait.js +145 -0
- package/src/interface/mcp/update-state.js +34 -0
- package/src/interface/mcp/views/overview.js +183 -0
- package/src/interface/mcp/views/task.js +223 -0
- package/src/interface/web/app.js +226 -0
- package/src/interface/web/views.js +224 -0
- package/src/mcp-server.js +3 -2223
- package/src/run-host/entry.js +23 -0
- package/src/run-host/finalize.js +236 -0
- package/src/run-host/launch.js +63 -0
- package/src/run-host/live-run.js +73 -0
- package/src/run-host/outcome-facts.js +61 -0
- package/src/run-host/streams.js +76 -0
- package/src/run-host/track.js +128 -0
- package/src/{runner-adapter.js → runners/codex/adapter.js} +6 -6
- package/src/runners/codex/chat-chunks.js +97 -0
- package/src/{event-parser.js → runners/codex/event-parser.js} +57 -55
- package/src/{goal-store.js → runners/codex/goal-store.js} +2 -2
- package/src/{mcp-config.js → runners/codex/mcp-config.js} +1 -1
- package/src/codex-runner.js +0 -1586
- package/src/landing.js +0 -507
- package/src/task-store.js +0 -1800
- package/src/web-app.js +0 -425
- /package/src/{failure-class.js → domain/failure-class.js} +0 -0
- /package/src/{owned-changes.js → domain/owned-changes.js} +0 -0
- /package/src/{prompt.js → domain/prompt.js} +0 -0
- /package/src/{status.js → domain/status.js} +0 -0
- /package/src/{thread-health.js → domain/thread-health.js} +0 -0
- /package/src/{truncate.js → domain/truncate.js} +0 -0
- /package/src/{worker-changes.js → domain/worker-changes.js} +0 -0
- /package/src/{worker-env.js → domain/worker-env.js} +0 -0
- /package/src/{worker-report.js → domain/worker-report.js} +0 -0
- /package/src/{worker-report.schema.json → domain/worker-report.schema.json} +0 -0
- /package/src/{bin-resolver.js → infra/bin-resolver.js} +0 -0
- /package/src/{cleanup-hint.js → infra/cleanup-hint.js} +0 -0
- /package/src/{external-output.js → infra/external-output.js} +0 -0
- /package/src/{handoff.js → infra/handoff.js} +0 -0
- /package/src/{paths.js → infra/paths.js} +0 -0
- /package/src/{stage-store.js → infra/stage-store.js} +0 -0
- /package/src/{tool-guard.js → runners/codex/tool-guard.js} +0 -0
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// The detached process that owns one run: it reads the worker's output, writes
|
|
3
|
+
// the exit and runs acceptance, and outlives the MCP server that started it.
|
|
4
|
+
import "../app/compose.js";
|
|
5
|
+
import { failedStart } from "../app/run-state.js";
|
|
6
|
+
import { upsertTask } from "../infra/store/tasks.js";
|
|
7
|
+
import { trackRunInHost } from "./track.js";
|
|
8
|
+
|
|
9
|
+
process.once("message", async (job) => {
|
|
10
|
+
const keepAlive = setInterval(() => {}, 1000);
|
|
11
|
+
let result;
|
|
12
|
+
try {
|
|
13
|
+
result = await trackRunInHost(job);
|
|
14
|
+
if (!result.ok) await upsertTask(result.record);
|
|
15
|
+
} catch (error) {
|
|
16
|
+
result = failedStart(job.record, `run host failed: ${error.message}`);
|
|
17
|
+
await upsertTask(result.record);
|
|
18
|
+
}
|
|
19
|
+
if (process.connected) await new Promise((resolveSent) => process.send({ ok: result.ok, record: result.record }, resolveSent));
|
|
20
|
+
if (result.settled) await result.settled;
|
|
21
|
+
clearInterval(keepAlive);
|
|
22
|
+
if (process.connected) process.disconnect();
|
|
23
|
+
});
|
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
// What happens after the worker process closes: decide the terminal status,
|
|
2
|
+
// gather the evidence of what the run did, flag runs that need attention, run
|
|
3
|
+
// acceptance and write the final row.
|
|
4
|
+
import { DEFAULT_ACCEPTANCE_TIMEOUT_MS, runAcceptance } from "../app/acceptance.js";
|
|
5
|
+
import { acceptanceRuns, cancelledTasks, processes } from "../app/run-state.js";
|
|
6
|
+
import { TERMINAL_STATUSES } from "../domain/status.js";
|
|
7
|
+
import { parseWorkerReportForRun } from "../domain/worker-report.js";
|
|
8
|
+
import { captureExternalOutputs, compareExternalOutputs } from "../infra/external-output.js";
|
|
9
|
+
import { appendTaskEvent, completeRunRecord } from "../infra/store/events.js";
|
|
10
|
+
import { updateWorkItemDelivery } from "../infra/store/records.js";
|
|
11
|
+
import { getTask } from "../infra/store/tasks.js";
|
|
12
|
+
import { captureWorkspaceManifest } from "../infra/workspace-kind.js";
|
|
13
|
+
import { readTaskChanges, snapshotTaskOutput } from "../infra/worktree.js";
|
|
14
|
+
import { persist } from "./live-run.js";
|
|
15
|
+
import { projectOutcomeFacts } from "./outcome-facts.js";
|
|
16
|
+
import { queueEventLines } from "./streams.js";
|
|
17
|
+
import { createHash } from "node:crypto";
|
|
18
|
+
import { appendFile } from "node:fs/promises";
|
|
19
|
+
|
|
20
|
+
function terminalStatus(run, stored, code, signal) {
|
|
21
|
+
const { live } = run;
|
|
22
|
+
// A cancel can be issued from another MCP process, so the marker is read
|
|
23
|
+
// back from disk rather than trusted to this process's memory.
|
|
24
|
+
const cancelRequested = cancelledTasks.has(run.record.id)
|
|
25
|
+
|| Boolean(live.cancel_requested_at)
|
|
26
|
+
|| Boolean(stored?.cancel_requested_at);
|
|
27
|
+
if (stored && TERMINAL_STATUSES.has(stored.status) && stored.status !== live.status) return stored.status;
|
|
28
|
+
if (run.terminalEvent && TERMINAL_STATUSES.has(live.status)) return live.status;
|
|
29
|
+
if (cancelRequested) return "cancelled";
|
|
30
|
+
// Killed by a signal nobody asked for: the worker did not fail, it
|
|
31
|
+
// vanished. Re-running is the fix, so it is reported as lost.
|
|
32
|
+
if (signal) return "lost";
|
|
33
|
+
if (code === 0) return "lost";
|
|
34
|
+
return "failed";
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function terminalRow(run, status, code, signal, finishedAt) {
|
|
38
|
+
const { live } = run;
|
|
39
|
+
const next = {
|
|
40
|
+
...live,
|
|
41
|
+
status,
|
|
42
|
+
phase: null,
|
|
43
|
+
changed_files: readTaskChanges(live),
|
|
44
|
+
exit_code: code,
|
|
45
|
+
signal,
|
|
46
|
+
current_command: null,
|
|
47
|
+
current_action: status === "completed" ? "Completed" : live.current_action,
|
|
48
|
+
completed_at: live.completed_at ?? finishedAt,
|
|
49
|
+
updated_at: finishedAt
|
|
50
|
+
};
|
|
51
|
+
const stdinEpipe = /^stdin write failed:.*\bEPIPE\b/i.test(next.error ?? "");
|
|
52
|
+
if (status === "failed" && (!next.error || stdinEpipe)) {
|
|
53
|
+
next.error = `codex exited with code ${code}${signal ? ` (signal ${signal})` : ""}`;
|
|
54
|
+
}
|
|
55
|
+
if (status === "lost" && (!next.error || stdinEpipe)) {
|
|
56
|
+
next.error = signal ? `codex worker was killed by signal ${signal} before writing a terminal event` : "Codex worker exited without recording a terminal event";
|
|
57
|
+
}
|
|
58
|
+
if (status === "cancelled") next.error = null;
|
|
59
|
+
if (run.quotaReason) {
|
|
60
|
+
next.attention_reason = run.quotaReason;
|
|
61
|
+
next.error = `Supervisor time quota exceeded: ${run.quotaReason}; inspect partial work before changing the budget`;
|
|
62
|
+
}
|
|
63
|
+
return next;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
async function externalChangesOf(run, next) {
|
|
67
|
+
try {
|
|
68
|
+
return compareExternalOutputs(run.externalBefore, await captureExternalOutputs(run.record.guard_policy?.externalOutputs ?? []));
|
|
69
|
+
} catch (error) {
|
|
70
|
+
next.attention_reason = "external_output_unverified";
|
|
71
|
+
next.error = error.message;
|
|
72
|
+
return [];
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
async function workspaceAfterOf(run, next) {
|
|
77
|
+
const metadata = run.record.workspace_metadata;
|
|
78
|
+
if (!run.workspaceBefore || !Array.isArray(metadata?.manifest_paths)) return null;
|
|
79
|
+
try {
|
|
80
|
+
return await captureWorkspaceManifest(metadata.source_root, metadata.manifest_paths);
|
|
81
|
+
} catch (error) {
|
|
82
|
+
next.attention_reason = "workspace_manifest_unverified";
|
|
83
|
+
next.error = error.message;
|
|
84
|
+
return null;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// Records what the run changed and a fingerprint of the attempt, used to tell
|
|
89
|
+
// two consecutive runs that made no progress.
|
|
90
|
+
async function attachEvidence(run, next) {
|
|
91
|
+
const { live, record, workspaceBefore, outputBefore } = run;
|
|
92
|
+
const outputAfter = snapshotTaskOutput(live);
|
|
93
|
+
const externalChanges = await externalChangesOf(run, next);
|
|
94
|
+
const workspaceAfter = await workspaceAfterOf(run, next);
|
|
95
|
+
const structuredReport = parseWorkerReportForRun(run.rawReport, { outputSchema: run.outputSchema });
|
|
96
|
+
next.run_evidence = {
|
|
97
|
+
run: live.run_count, commands_run: live.commands.length,
|
|
98
|
+
structured_report: structuredReport,
|
|
99
|
+
output_before: outputBefore, output_after: outputAfter,
|
|
100
|
+
output_changed: outputBefore && outputAfter ? outputBefore !== outputAfter : null,
|
|
101
|
+
workspace: workspaceBefore ? {
|
|
102
|
+
kind: record.workspace_kind,
|
|
103
|
+
before_manifest: workspaceBefore,
|
|
104
|
+
after_manifest: workspaceAfter,
|
|
105
|
+
manifest_changed: workspaceAfter ? workspaceBefore.sha256 !== workspaceAfter.sha256 : null
|
|
106
|
+
} : null
|
|
107
|
+
};
|
|
108
|
+
next.run_evidence.external_outputs = externalChanges;
|
|
109
|
+
if (externalChanges.some((entry) => entry.changed)) next.run_evidence.output_changed = true;
|
|
110
|
+
next.changed_files = [...new Set([...next.changed_files, ...externalChanges.filter((entry) => entry.changed).map((entry) => entry.path)])];
|
|
111
|
+
next.run_evidence.attempt_fingerprint = createHash("sha256").update(JSON.stringify({
|
|
112
|
+
output_changed: next.run_evidence.output_changed,
|
|
113
|
+
commands_run: live.commands.length,
|
|
114
|
+
changed_files: next.changed_files,
|
|
115
|
+
acceptance_configured: Array.isArray(live.acceptance) && live.acceptance.length > 0,
|
|
116
|
+
workspace_manifest_changed: next.run_evidence.workspace?.manifest_changed ?? null
|
|
117
|
+
})).digest("hex");
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function flagAttention(run, next, status, code) {
|
|
121
|
+
const { live } = run;
|
|
122
|
+
if (status === "completed" && code === 0 && live.sandbox !== "read-only"
|
|
123
|
+
&& !next.run_evidence.output_changed && next.run_evidence.output_changed !== null
|
|
124
|
+
&& live.commands.length === 0 && !run.reportOnlyRecovery) {
|
|
125
|
+
next.attention_reason = run.priorAttemptFingerprint === next.run_evidence.attempt_fingerprint ? "two_stall" : "no_work";
|
|
126
|
+
if (next.attention_reason === "two_stall") next.current_action = "No progress in two consecutive runs; needs attention";
|
|
127
|
+
}
|
|
128
|
+
if (status === "completed" && !next.run_evidence.structured_report.valid && !live.guard_policy?.preflight) {
|
|
129
|
+
// The report is a summary, not the business result. Keep the completed
|
|
130
|
+
// lifecycle and let acceptance plus the reviewed diff decide whether it
|
|
131
|
+
// can land; a report-only recovery can still repair the summary.
|
|
132
|
+
next.attention_reason = "invalid_report";
|
|
133
|
+
next.error = `Invalid final worker report: ${next.run_evidence.structured_report.error}`;
|
|
134
|
+
next.current_action = "Work completed, but the final report is invalid; acceptance and diff remain authoritative";
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
// The terminal lifecycle and exit code are primary evidence. Persist them
|
|
139
|
+
// before fact projection, which is secondary and may fail on a stale control
|
|
140
|
+
// record without turning completed work into lost work.
|
|
141
|
+
async function writeFinal(run, finalRecord, factOptions) {
|
|
142
|
+
await persist(run, finalRecord, "final persist");
|
|
143
|
+
await projectOutcomeFacts(run, finalRecord, factOptions);
|
|
144
|
+
if (finalRecord.attention_reason === "two_stall") await updateWorkItemDelivery(finalRecord.id, "needs_attention");
|
|
145
|
+
await completeRunRecord(finalRecord, run.live.run_count);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function failingCheckLabel(failing, results) {
|
|
149
|
+
if (!failing) return results.error ?? "see acceptance_results";
|
|
150
|
+
const why = failing.error ?? (failing.baseline?.passed === false ? "baseline/evidence mismatch" : failing.timed_out ? "timeout" : failing.exit_code ?? "?");
|
|
151
|
+
return `${failing.command.slice(0, 80)} exit ${why}`;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
async function runAcceptanceChecks(run, acceptance) {
|
|
155
|
+
const { record, live } = run;
|
|
156
|
+
const control = { kill: null, cancelled: false, isCancelled: () => control.cancelled };
|
|
157
|
+
acceptanceRuns.set(record.id, control);
|
|
158
|
+
// A fresh MCP has no in-memory acceptance handle. Consume its durable
|
|
159
|
+
// cancellation marker while a command runs, then stop subsequent checks.
|
|
160
|
+
const cancellationWatch = setInterval(async () => {
|
|
161
|
+
const current = await getTask(record.id).catch(() => null);
|
|
162
|
+
if (current?.cancel_requested_at) {
|
|
163
|
+
control.cancelled = true;
|
|
164
|
+
control.kill?.();
|
|
165
|
+
}
|
|
166
|
+
}, 100);
|
|
167
|
+
try {
|
|
168
|
+
return await runAcceptance(acceptance, {
|
|
169
|
+
cwd: record.cwd,
|
|
170
|
+
timeoutMs: live.acceptance_timeout_ms ?? DEFAULT_ACCEPTANCE_TIMEOUT_MS,
|
|
171
|
+
run: live.run_count,
|
|
172
|
+
taskId: record.id,
|
|
173
|
+
baseCommit: live.base_commit,
|
|
174
|
+
control
|
|
175
|
+
});
|
|
176
|
+
} finally {
|
|
177
|
+
clearInterval(cancellationWatch);
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
// Acceptance runs after the worker is gone, in two writes. The first records
|
|
182
|
+
// the terminal status with exit_code still null and the run marked as this
|
|
183
|
+
// process's, so a wait keeps waiting and reconcile (which sees a dead codex
|
|
184
|
+
// pid) leaves the row alone; the second records exit_code and the verdict.
|
|
185
|
+
// changed_files is read before the checks run so build output they leave
|
|
186
|
+
// behind is not counted as the worker's.
|
|
187
|
+
async function settleWithAcceptance(run, next, acceptance, finishedAt) {
|
|
188
|
+
const { record, live } = run;
|
|
189
|
+
await persist(run, {
|
|
190
|
+
...next,
|
|
191
|
+
exit_code: null,
|
|
192
|
+
signal: null,
|
|
193
|
+
current_action: "Running acceptance",
|
|
194
|
+
acceptance_results: { status: "running", passed: null, run: live.run_count, supervisor_pid: process.pid, started_at: finishedAt }
|
|
195
|
+
});
|
|
196
|
+
const results = await runAcceptanceChecks(run, acceptance);
|
|
197
|
+
acceptanceRuns.delete(record.id);
|
|
198
|
+
const event = { type: "supervisor.acceptance", ...results };
|
|
199
|
+
const acceptanceEvent = await appendTaskEvent(record.id, event, { runId: run.runId, actor: "supervisor" }).catch(() => null);
|
|
200
|
+
await appendFile(run.logPath, `${JSON.stringify(event)}\n`).catch(() => {});
|
|
201
|
+
const failing = results.checks.find((check) => check.passed === false || check.exit_code !== 0 || check.timed_out);
|
|
202
|
+
const finalRecord = {
|
|
203
|
+
...next,
|
|
204
|
+
acceptance_results: results,
|
|
205
|
+
current_action: results.status === "passed"
|
|
206
|
+
? "Completed, acceptance passed"
|
|
207
|
+
: results.status === "failed"
|
|
208
|
+
? `Acceptance failed: ${failingCheckLabel(failing, results)}`
|
|
209
|
+
: next.current_action,
|
|
210
|
+
updated_at: new Date().toISOString()
|
|
211
|
+
};
|
|
212
|
+
await writeFinal(run, finalRecord, { acceptanceEventId: acceptanceEvent?.id ?? null, acceptancePassed: results.passed === true });
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
export async function finalizeChild(run, code, signal) {
|
|
216
|
+
if (run.childSettled) return;
|
|
217
|
+
run.childSettled = true;
|
|
218
|
+
const { record } = run;
|
|
219
|
+
if (run.quotaWatch) clearInterval(run.quotaWatch);
|
|
220
|
+
processes.delete(record.id);
|
|
221
|
+
if (run.stdoutRest.trim()) queueEventLines(run, [run.stdoutRest]);
|
|
222
|
+
await run.eventChain.catch(() => {});
|
|
223
|
+
run.logStream.end();
|
|
224
|
+
const finishedAt = new Date().toISOString();
|
|
225
|
+
const stored = await getTask(record.id).catch(() => null);
|
|
226
|
+
const status = terminalStatus(run, stored, code, signal);
|
|
227
|
+
const next = terminalRow(run, status, code, signal, finishedAt);
|
|
228
|
+
await attachEvidence(run, next);
|
|
229
|
+
flagAttention(run, next, status, code);
|
|
230
|
+
|
|
231
|
+
const { live } = run;
|
|
232
|
+
const acceptance = Array.isArray(live.acceptance) && live.acceptance.length > 0 ? live.acceptance : null;
|
|
233
|
+
if (acceptance && (status === "completed" || status === "failed")) await settleWithAcceptance(run, next, acceptance, finishedAt);
|
|
234
|
+
else await writeFinal(run, acceptance ? { ...next, acceptance_results: null } : next);
|
|
235
|
+
cancelledTasks.delete(record.id);
|
|
236
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
// What a worker process is started with: the guard policy, the CLI arguments
|
|
2
|
+
// that install it, and the environment the worker's tools read.
|
|
3
|
+
import { workspaceSetupWriteRoots } from "../app/worktree-setup.js";
|
|
4
|
+
import { findOutsideOwnedChanges } from "../domain/owned-changes.js";
|
|
5
|
+
import { buildGuardPreamble } from "../domain/prompt.js";
|
|
6
|
+
import { withWorkerToolPath } from "../domain/worker-env.js";
|
|
7
|
+
import { workerReportSchemaPath } from "../domain/worker-report.js";
|
|
8
|
+
import { cacheRoots } from "../infra/sandbox-roots.js";
|
|
9
|
+
import { supervisorMcpDisableArgs } from "../runners/codex/mcp-config.js";
|
|
10
|
+
import { dirname } from "node:path";
|
|
11
|
+
import { fileURLToPath } from "node:url";
|
|
12
|
+
|
|
13
|
+
const quoteCommand = (path) => process.platform === "win32" ? `"${path.replace(/"/g, '""')}"` : `'${path.replace(/'/g, "'\\''")}'`;
|
|
14
|
+
|
|
15
|
+
function guardPolicyFor(record, externalBefore, outputSchema) {
|
|
16
|
+
const owned = [...findOutsideOwnedChanges(record, []).mapping.map((entry) => entry.worker), ...externalBefore.map((entry) => entry.path)];
|
|
17
|
+
return { cwd: record.cwd, worktree: record.cwd, sandbox: record.sandbox, ownedPaths: owned, ...(record.guard_policy ?? {}),
|
|
18
|
+
output_schema: outputSchema,
|
|
19
|
+
goalTokenBudget: record.goal_token_budget ?? null,
|
|
20
|
+
allowedCommands: [
|
|
21
|
+
...(record.guard_policy?.allowedCommands ?? []),
|
|
22
|
+
...(record.acceptance ?? []).map((check) => typeof check === "string" ? check : check.command),
|
|
23
|
+
// This CLI writes only data/stages/<this task>.json. It is part of the
|
|
24
|
+
// runtime contract, not an ad-hoc command the model must declare. The
|
|
25
|
+
// task id comes from the injected environment; stage.js has no override.
|
|
26
|
+
'node "$CODEX_SUPERVISOR_STAGE_CLI"*',
|
|
27
|
+
'node "$CODEX_SUPERVISOR_ACCEPTANCE_CLI"*'
|
|
28
|
+
] };
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function configArgsFor(record, externalBefore, outputSchema) {
|
|
32
|
+
const guard = fileURLToPath(new URL("../runners/codex/tool-guard.js", import.meta.url));
|
|
33
|
+
const hookCommand = `${quoteCommand(process.execPath)} ${quoteCommand(guard)}`;
|
|
34
|
+
const configArgs = [...(outputSchema ? ["--output-schema", workerReportSchemaPath] : []), "--dangerously-bypass-hook-trust", "-c",
|
|
35
|
+
`hooks.PreToolUse=[{matcher="Bash|apply_patch|create_goal",hooks=[{type="command",command=${JSON.stringify(hookCommand)}}]}]`];
|
|
36
|
+
// A worker may use its explicitly configured business MCP servers, but it
|
|
37
|
+
// must not inherit this supervisor and create a second orchestration tree.
|
|
38
|
+
configArgs.push(...supervisorMcpDisableArgs());
|
|
39
|
+
configArgs.push("-c", `sandbox_workspace_write.network_access=${record.guard_policy?.networkAccess === true}`);
|
|
40
|
+
const sandboxWritableRoots = [...new Set([
|
|
41
|
+
...externalBefore.map((file) => dirname(file.path)),
|
|
42
|
+
...cacheRoots(),
|
|
43
|
+
...workspaceSetupWriteRoots(record),
|
|
44
|
+
...(record.guard_policy?.writableRoots ?? [])
|
|
45
|
+
])];
|
|
46
|
+
if (sandboxWritableRoots.length) configArgs.push("-c", `sandbox_workspace_write.writable_roots=${JSON.stringify(sandboxWritableRoots)}`);
|
|
47
|
+
return configArgs;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function buildLaunch({ record, args, prompt, outputSchema, externalBefore }) {
|
|
51
|
+
const guardPolicy = guardPolicyFor(record, externalBefore, outputSchema);
|
|
52
|
+
const stageCli = fileURLToPath(new URL("../interface/bin/stage.js", import.meta.url));
|
|
53
|
+
const acceptanceCli = fileURLToPath(new URL("../interface/bin/acceptance-cli.js", import.meta.url));
|
|
54
|
+
const configArgs = configArgsFor(record, externalBefore, outputSchema);
|
|
55
|
+
// Insert before the prompt/session positional arguments for exec/resume.
|
|
56
|
+
const guardedArgs = [...args.slice(0, -1), ...configArgs, args.at(-1)];
|
|
57
|
+
const env = () => withWorkerToolPath({ ...process.env, NO_COLOR: "1", CODEX_SUPERVISOR_TASK_ID: record.id,
|
|
58
|
+
CODEX_SUPERVISOR_BASE_COMMIT: record.base_commit ?? "",
|
|
59
|
+
CODEX_SUPERVISOR_STAGE_CLI: stageCli,
|
|
60
|
+
CODEX_SUPERVISOR_ACCEPTANCE_CLI: acceptanceCli,
|
|
61
|
+
CODEX_SUPERVISOR_RUN: String((record.run_count ?? 0) + 1), CODEX_SUPERVISOR_GUARD_POLICY: JSON.stringify(guardPolicy) });
|
|
62
|
+
return { guardedArgs, prompt: `${buildGuardPreamble(guardPolicy)}\n\n${prompt}`, env };
|
|
63
|
+
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
// The state of one run while its worker is alive, and the single serialized
|
|
2
|
+
// write path that keeps the task row in step with it. Every write goes through
|
|
3
|
+
// one chain so concurrent stdout/stderr callbacks cannot persist out of order.
|
|
4
|
+
import { terminateChild } from "../app/cancel.js";
|
|
5
|
+
import { runIdFor } from "../infra/store/db.js";
|
|
6
|
+
import { appendTaskEvent } from "../infra/store/events.js";
|
|
7
|
+
import { upsertTask } from "../infra/store/tasks.js";
|
|
8
|
+
|
|
9
|
+
// A new run starts clean. A resumed worker used to carry the error from the
|
|
10
|
+
// run that was lost, so a worker that was plainly running still showed
|
|
11
|
+
// "process disappeared" until it finished.
|
|
12
|
+
export function startingRow(record, child, outputSchema, now) {
|
|
13
|
+
return {
|
|
14
|
+
...record,
|
|
15
|
+
status: "running",
|
|
16
|
+
phase: "starting",
|
|
17
|
+
pid: child.pid ?? null,
|
|
18
|
+
run_host_pid: process.pid,
|
|
19
|
+
started_at: now,
|
|
20
|
+
completed_at: null,
|
|
21
|
+
exit_code: null,
|
|
22
|
+
signal: null,
|
|
23
|
+
error: null,
|
|
24
|
+
cancel_requested_at: null,
|
|
25
|
+
acceptance_results: null,
|
|
26
|
+
attention_reason: null,
|
|
27
|
+
run_evidence: null,
|
|
28
|
+
guard_policy: { ...record.guard_policy, output_schema: outputSchema },
|
|
29
|
+
commands: [],
|
|
30
|
+
last_message: null,
|
|
31
|
+
current_action: null,
|
|
32
|
+
current_command: null,
|
|
33
|
+
// A resumed row still carries the last event of the run that ended;
|
|
34
|
+
// idle time for this run counts from now.
|
|
35
|
+
last_event_at: now,
|
|
36
|
+
last_event_type: null,
|
|
37
|
+
run_count: (record.run_count ?? 0) + 1,
|
|
38
|
+
updated_at: now
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// Stops the worker when its per-run or total time budget runs out.
|
|
43
|
+
export function watchQuota(run, now) {
|
|
44
|
+
const maxRunMs = run.record.guard_policy?.maxRunMs;
|
|
45
|
+
const maxTotalMs = run.record.guard_policy?.maxTotalMs;
|
|
46
|
+
if (!maxRunMs && !maxTotalMs) return null;
|
|
47
|
+
return setInterval(() => {
|
|
48
|
+
if (run.quotaReason) return;
|
|
49
|
+
if (maxRunMs && Date.now() - Date.parse(now) >= maxRunMs) run.quotaReason = "run_time_limit";
|
|
50
|
+
else if (maxTotalMs && Date.now() - Date.parse(run.record.created_at) >= maxTotalMs) run.quotaReason = "total_time_limit";
|
|
51
|
+
if (run.quotaReason) terminateChild(run.child);
|
|
52
|
+
}, 250);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function writeSnapshot(run, next) {
|
|
56
|
+
run.live = next;
|
|
57
|
+
const snapshot = run.live;
|
|
58
|
+
const pending = run.writeChain.then(() => upsertTask(snapshot));
|
|
59
|
+
// Keep later writes usable after one failed snapshot. Callers that need
|
|
60
|
+
// failure visibility use the returned promise explicitly.
|
|
61
|
+
run.writeChain = pending.catch(() => {});
|
|
62
|
+
return pending;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export async function persist(run, next, label = "persist") {
|
|
66
|
+
try {
|
|
67
|
+
await writeSnapshot(run, next);
|
|
68
|
+
} catch (error) {
|
|
69
|
+
await appendTaskEvent(next.id, { type: "supervisor.persist_failed", label, error: error.message, run: next.run_count },
|
|
70
|
+
{ runId: runIdFor(next.id, next.run_count), actor: "supervisor" }).catch(() => null);
|
|
71
|
+
process.stderr.write(`[codex-supervisor] ${label} failed for ${next.id}: ${error.message}\n`);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
// A finished run's report becomes a candidate fact; acceptance passing turns
|
|
2
|
+
// it into the work item's verified outcome.
|
|
3
|
+
import { appendTaskEvent } from "../infra/store/events.js";
|
|
4
|
+
import { getWorkItemForTask, recordFact } from "../infra/store/facts.js";
|
|
5
|
+
import { updateWorkItemDelivery } from "../infra/store/records.js";
|
|
6
|
+
|
|
7
|
+
async function recordOutcomeFacts({ task, runId, report, reportEventId = null, acceptanceEventId = null, acceptancePassed = false }) {
|
|
8
|
+
if (!report?.valid) return;
|
|
9
|
+
const workItem = await getWorkItemForTask(task.id);
|
|
10
|
+
if (!workItem) return;
|
|
11
|
+
const validForManifestHash = task.run_evidence?.workspace?.after_manifest?.sha256 ?? null;
|
|
12
|
+
const candidate = await recordFact({
|
|
13
|
+
workItemId: workItem.id,
|
|
14
|
+
scopeType: "run",
|
|
15
|
+
scopeId: runId,
|
|
16
|
+
key: "worker_outcome",
|
|
17
|
+
value: report.report,
|
|
18
|
+
state: "candidate",
|
|
19
|
+
sourceEventId: reportEventId,
|
|
20
|
+
validForSha: task.base_commit ?? null,
|
|
21
|
+
validForContentHash: task.input_context?.content_hash ?? null,
|
|
22
|
+
validForManifestHash,
|
|
23
|
+
watchedPaths: task.owned_paths ?? []
|
|
24
|
+
});
|
|
25
|
+
if (!acceptancePassed || report.format === "text") return;
|
|
26
|
+
await recordFact({
|
|
27
|
+
workItemId: workItem.id,
|
|
28
|
+
scopeType: "work_item",
|
|
29
|
+
scopeId: workItem.id,
|
|
30
|
+
key: "accepted_outcome",
|
|
31
|
+
value: report.report,
|
|
32
|
+
state: "verified",
|
|
33
|
+
sourceEventId: acceptanceEventId,
|
|
34
|
+
validForSha: task.base_commit ?? null,
|
|
35
|
+
validForContentHash: task.input_context?.content_hash ?? null,
|
|
36
|
+
validForManifestHash,
|
|
37
|
+
watchedPaths: task.owned_paths ?? [],
|
|
38
|
+
supersedesId: candidate.id,
|
|
39
|
+
verifiedBy: "supervisor.acceptance"
|
|
40
|
+
});
|
|
41
|
+
await updateWorkItemDelivery(task.id, "verified");
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// Fact projection is secondary evidence: a failure is recorded and reported,
|
|
45
|
+
// and never turns completed work into lost work.
|
|
46
|
+
export async function projectOutcomeFacts(run, finalRecord, { acceptanceEventId = null, acceptancePassed = false } = {}) {
|
|
47
|
+
try {
|
|
48
|
+
await recordOutcomeFacts({
|
|
49
|
+
task: finalRecord,
|
|
50
|
+
runId: run.runId,
|
|
51
|
+
report: finalRecord.run_evidence?.structured_report,
|
|
52
|
+
reportEventId: run.rawReportEventId,
|
|
53
|
+
acceptanceEventId,
|
|
54
|
+
acceptancePassed
|
|
55
|
+
});
|
|
56
|
+
} catch (error) {
|
|
57
|
+
await appendTaskEvent(finalRecord.id, { type: "supervisor.fact_record_failed", error: error.message, run: run.live.run_count },
|
|
58
|
+
{ runId: run.runId, actor: "supervisor" }).catch(() => null);
|
|
59
|
+
process.stderr.write(`[codex-supervisor] fact projection failed for ${finalRecord.id}: ${error.message}\n`);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
// Reads the worker's output: stdout lines become stored events and move the
|
|
2
|
+
// task row forward, stderr keeps a tail on the row.
|
|
3
|
+
import { splitLines } from "../app/worktree-setup.js";
|
|
4
|
+
import { appendTaskEvents } from "../infra/store/events.js";
|
|
5
|
+
import { codexRunner } from "../runners/codex/adapter.js";
|
|
6
|
+
import { persist } from "./live-run.js";
|
|
7
|
+
|
|
8
|
+
async function handleLines(run, lines) {
|
|
9
|
+
const events = [];
|
|
10
|
+
for (const line of lines) {
|
|
11
|
+
try {
|
|
12
|
+
const event = JSON.parse(line);
|
|
13
|
+
run.logStream.write(`${JSON.stringify(event)}\n`);
|
|
14
|
+
events.push(event);
|
|
15
|
+
} catch (error) {
|
|
16
|
+
run.logStream.write(`${JSON.stringify({ type: "supervisor.parse_error", line, error: error.message })}\n`);
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
if (events.length === 0) return;
|
|
20
|
+
const storedEvents = await appendTaskEvents(run.record.id, events, { runId: run.runId, actor: "codex" });
|
|
21
|
+
let next = run.live;
|
|
22
|
+
for (const [index, event] of events.entries()) {
|
|
23
|
+
if (event.type === "item.completed" && event.item?.type === "agent_message") {
|
|
24
|
+
run.rawReport = event.item.text;
|
|
25
|
+
run.rawReportEventId = storedEvents[index].id;
|
|
26
|
+
}
|
|
27
|
+
if (["turn.completed", "turn.failed"].includes(event.type)) run.terminalEvent = true;
|
|
28
|
+
next = codexRunner.parseEvent(next, event);
|
|
29
|
+
}
|
|
30
|
+
await persist(run, next);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// Lines that arrive in one tick are stored and applied as one batch.
|
|
34
|
+
export function queueEventLines(run, lines) {
|
|
35
|
+
run.pendingLines.push(...lines);
|
|
36
|
+
if (run.eventFlushPending) return;
|
|
37
|
+
run.eventFlushPending = true;
|
|
38
|
+
run.eventChain = run.eventChain.then(async () => {
|
|
39
|
+
await new Promise((resolveFlush) => setImmediate(resolveFlush));
|
|
40
|
+
const batch = run.pendingLines;
|
|
41
|
+
run.pendingLines = [];
|
|
42
|
+
run.eventFlushPending = false;
|
|
43
|
+
await handleLines(run, batch);
|
|
44
|
+
}).catch((error) => {
|
|
45
|
+
process.stderr.write(`[codex-supervisor] event handling failed for ${run.record.id}: ${error.message}\n`);
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function attachStreams(run, earlyOutput) {
|
|
50
|
+
const { child } = run;
|
|
51
|
+
const handleStdoutChunk = (chunk) => {
|
|
52
|
+
const split = splitLines(run.stdoutRest, chunk.toString("utf8"));
|
|
53
|
+
run.stdoutRest = split.rest;
|
|
54
|
+
const lines = split.lines.filter((line) => line.trim());
|
|
55
|
+
if (lines.length) queueEventLines(run, lines);
|
|
56
|
+
};
|
|
57
|
+
earlyOutput.capture = false;
|
|
58
|
+
for (const chunk of earlyOutput.stdout) handleStdoutChunk(chunk);
|
|
59
|
+
child.stdout.on("data", handleStdoutChunk);
|
|
60
|
+
child.stdout.on("error", () => {});
|
|
61
|
+
|
|
62
|
+
run.stderr = earlyOutput.stderr.map((chunk) => chunk.toString("utf8")).join("");
|
|
63
|
+
child.stderr.on("data", (chunk) => {
|
|
64
|
+
run.stderr += chunk.toString("utf8");
|
|
65
|
+
persist(run, { ...run.live, stderr_tail: run.stderr.slice(-4000), updated_at: new Date().toISOString() });
|
|
66
|
+
});
|
|
67
|
+
child.stderr.on("error", () => {});
|
|
68
|
+
|
|
69
|
+
child.on("error", (error) => {
|
|
70
|
+
persist(run, {
|
|
71
|
+
...run.live,
|
|
72
|
+
error: run.live.error ?? `codex process error: ${error.message}`,
|
|
73
|
+
updated_at: new Date().toISOString()
|
|
74
|
+
});
|
|
75
|
+
});
|
|
76
|
+
}
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
// Starts one worker process and tracks it to the end. Runs inside the detached
|
|
2
|
+
// run host, so the worker's output, exit and acceptance are recorded even when
|
|
3
|
+
// the MCP server that dispatched it is gone.
|
|
4
|
+
import "../app/compose.js";
|
|
5
|
+
import { failedStart, processes } from "../app/run-state.js";
|
|
6
|
+
import { captureExternalOutputs } from "../infra/external-output.js";
|
|
7
|
+
import { spawnProcess } from "../infra/process.js";
|
|
8
|
+
import { clearStage } from "../infra/stage-store.js";
|
|
9
|
+
import { appendTaskEvent, ensureRunRecord } from "../infra/store/events.js";
|
|
10
|
+
import { getTask } from "../infra/store/tasks.js";
|
|
11
|
+
import { snapshotTaskOutput } from "../infra/worktree.js";
|
|
12
|
+
import { codexRunner } from "../runners/codex/adapter.js";
|
|
13
|
+
import { finalizeChild } from "./finalize.js";
|
|
14
|
+
import { buildLaunch } from "./launch.js";
|
|
15
|
+
import { persist, startingRow, watchQuota } from "./live-run.js";
|
|
16
|
+
import { attachStreams } from "./streams.js";
|
|
17
|
+
import { createWriteStream } from "node:fs";
|
|
18
|
+
|
|
19
|
+
// Spawn can fail either by throwing synchronously, or by emitting "error"
|
|
20
|
+
// instead of "spawn". Both paths are handled so a bad CODEX_BIN marks the task
|
|
21
|
+
// failed instead of taking the whole MCP process down.
|
|
22
|
+
async function spawnAndAwaitStart(target, args, options) {
|
|
23
|
+
const child = spawnProcess(target.cmd, [...target.prefixArgs, ...args], options);
|
|
24
|
+
const earlyOutput = { stdout: [], stderr: [], capture: true };
|
|
25
|
+
child.stdout?.on("data", (chunk) => { if (earlyOutput.capture) earlyOutput.stdout.push(chunk); });
|
|
26
|
+
child.stderr?.on("data", (chunk) => { if (earlyOutput.capture) earlyOutput.stderr.push(chunk); });
|
|
27
|
+
const spawnError = await new Promise((resolvePromise) => {
|
|
28
|
+
let settled = false;
|
|
29
|
+
child.once("spawn", () => {
|
|
30
|
+
if (!settled) {
|
|
31
|
+
settled = true;
|
|
32
|
+
resolvePromise(null);
|
|
33
|
+
}
|
|
34
|
+
});
|
|
35
|
+
child.once("error", (error) => {
|
|
36
|
+
if (!settled) {
|
|
37
|
+
settled = true;
|
|
38
|
+
resolvePromise(error);
|
|
39
|
+
}
|
|
40
|
+
});
|
|
41
|
+
});
|
|
42
|
+
return { child, spawnError, earlyOutput };
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// Everything the handlers of one run share. `live` is the task row as last
|
|
46
|
+
// written; the chains serialize row writes and event handling.
|
|
47
|
+
function openRun({ record, child, outputSchema, logPath, before, now }) {
|
|
48
|
+
return {
|
|
49
|
+
record, child, outputSchema, logPath, ...before,
|
|
50
|
+
priorAttemptFingerprint: record.run_evidence?.attempt_fingerprint ?? null,
|
|
51
|
+
reportOnlyRecovery: record.attention_reason === "invalid_report",
|
|
52
|
+
live: startingRow(record, child, outputSchema, now),
|
|
53
|
+
quotaReason: null, quotaWatch: null,
|
|
54
|
+
writeChain: Promise.resolve(), eventChain: Promise.resolve(),
|
|
55
|
+
terminalEvent: false, rawReport: null, rawReportEventId: null,
|
|
56
|
+
stdoutRest: "", pendingLines: [], eventFlushPending: false, stderr: "",
|
|
57
|
+
childSettled: false, runId: null, logStream: null
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// A child that exits early makes a stdin write fail with EPIPE. That must not
|
|
62
|
+
// reach the process level, or one oversized prompt kills the run host.
|
|
63
|
+
function noteStdinFailure(run, error) {
|
|
64
|
+
return persist(run, {
|
|
65
|
+
...run.live,
|
|
66
|
+
error: run.live.error ?? `stdin write failed: ${error.message}`,
|
|
67
|
+
updated_at: new Date().toISOString()
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// finalizeChild runs detached from any caller. A rejection there would end the
|
|
72
|
+
// run host as an unhandled rejection, so it is reported and recorded instead.
|
|
73
|
+
// The note goes onto the row as it is stored now, not onto this process's last
|
|
74
|
+
// snapshot: another process may already have closed the row, and writing an
|
|
75
|
+
// older "running" snapshot over it would reopen a finished worker.
|
|
76
|
+
async function noteFinalizeFailure(run, error) {
|
|
77
|
+
process.stderr.write(`[codex-supervisor] finalize failed for ${run.record.id}: ${error.stack ?? error.message}\n`);
|
|
78
|
+
await appendTaskEvent(run.record.id, { type: "supervisor.finalize_failed", error: error.message, stack: String(error.stack ?? "").slice(0, 2000), run: run.live.run_count },
|
|
79
|
+
{ runId: run.runId, actor: "supervisor" }).catch(() => null);
|
|
80
|
+
const stored = await getTask(run.record.id).catch(() => null);
|
|
81
|
+
const base = stored ?? run.live;
|
|
82
|
+
await persist(run, { ...base, error: base.error ?? `supervisor could not finish recording this run: ${error.message}`, updated_at: new Date().toISOString() });
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export async function trackRunInHost({ record, args, prompt, logPath, spawnOptions = {}, outputSchema = true }) {
|
|
86
|
+
const capability = codexRunner.capabilityPreflight();
|
|
87
|
+
if (!capability.ok) return failedStart(record, capability.error);
|
|
88
|
+
const target = capability.target;
|
|
89
|
+
const before = {
|
|
90
|
+
outputBefore: snapshotTaskOutput(record),
|
|
91
|
+
workspaceBefore: record.workspace_metadata?.before_manifest ?? null,
|
|
92
|
+
externalBefore: await captureExternalOutputs(record.guard_policy?.externalOutputs ?? [], { checkBaseline: (record.run_count ?? 0) === 0 })
|
|
93
|
+
};
|
|
94
|
+
const launch = buildLaunch({ record, args, prompt, outputSchema, externalBefore: before.externalBefore });
|
|
95
|
+
clearStage(record.id);
|
|
96
|
+
|
|
97
|
+
const { child, spawnError, earlyOutput } = await spawnAndAwaitStart(target, launch.guardedArgs, {
|
|
98
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
99
|
+
env: launch.env(),
|
|
100
|
+
windowsHide: true,
|
|
101
|
+
...spawnOptions
|
|
102
|
+
});
|
|
103
|
+
if (spawnError) return failedStart(record, `failed to spawn ${target.cmd}: ${spawnError.message}`);
|
|
104
|
+
|
|
105
|
+
const now = new Date().toISOString();
|
|
106
|
+
const run = openRun({ record, child, outputSchema, logPath, before, now });
|
|
107
|
+
processes.set(record.id, child);
|
|
108
|
+
run.quotaWatch = watchQuota(run, now);
|
|
109
|
+
await persist(run, run.live);
|
|
110
|
+
run.runId = await ensureRunRecord(run.live, run.live.run_count);
|
|
111
|
+
run.logStream = createWriteStream(logPath, { flags: "a" });
|
|
112
|
+
run.logStream.on("error", () => {});
|
|
113
|
+
child.stdin.on("error", (error) => { noteStdinFailure(run, error); });
|
|
114
|
+
attachStreams(run, earlyOutput);
|
|
115
|
+
|
|
116
|
+
let settleRun;
|
|
117
|
+
const settled = new Promise((resolveSettled) => { settleRun = resolveSettled; });
|
|
118
|
+
const finalize = (code, signal) => { void finalizeChild(run, code, signal).catch((error) => noteFinalizeFailure(run, error)).finally(settleRun); };
|
|
119
|
+
child.once("close", finalize);
|
|
120
|
+
if (child.exitCode !== null || child.signalCode !== null) setImmediate(() => finalize(child.exitCode, child.signalCode));
|
|
121
|
+
|
|
122
|
+
try {
|
|
123
|
+
child.stdin.end(launch.prompt);
|
|
124
|
+
} catch (error) {
|
|
125
|
+
await noteStdinFailure(run, error);
|
|
126
|
+
}
|
|
127
|
+
return { ok: true, record: run.live, child, settled };
|
|
128
|
+
}
|