codex-supervisor-mcp 0.14.0 → 1.1.0
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/README.en.md +37 -45
- package/README.md +37 -45
- package/package.json +2 -2
- package/skills/codex-supervisor/SKILL.md +88 -91
- package/src/app/acceptance.js +5 -5
- package/src/app/auto-cleanup.js +6 -5
- package/src/app/cleanup-facts.js +21 -16
- package/src/app/cleanup-plan.js +22 -20
- package/src/app/context-compiler.js +2 -1
- package/src/app/dispatch.js +17 -15
- package/src/app/followup.js +5 -4
- package/src/app/land-chain.js +5 -4
- package/src/app/landing.js +8 -8
- package/src/app/ownership.js +1 -1
- package/src/app/rebase.js +1 -1
- package/src/app/restore-worktree.js +2 -1
- package/src/app/resume.js +11 -6
- package/src/app/worktree-setup.js +58 -16
- package/src/domain/acceptance-spec.js +1 -1
- package/src/domain/failure-class.js +36 -4
- package/src/domain/prompt.js +7 -7
- package/src/domain/status.js +15 -2
- package/src/domain/thread-health.js +2 -2
- package/src/domain/worker-branch.js +6 -0
- package/src/domain/worker-changes.js +3 -3
- package/src/domain/worker-preflight.js +2 -1
- package/src/infra/cleanup-hint.js +1 -1
- package/src/infra/crash-guard.js +44 -0
- package/src/infra/external-output.js +2 -2
- package/src/infra/git.js +35 -4
- package/src/infra/sandbox-roots.js +1 -1
- package/src/infra/store/event-body.js +82 -0
- package/src/infra/store/events.js +9 -6
- package/src/infra/store/reconcile.js +4 -3
- package/src/infra/store/tasks.js +15 -1
- package/src/infra/update/auto-update-worker.js +3 -3
- package/src/infra/update/auto-update.js +4 -4
- package/src/infra/update/update-check.js +3 -3
- package/src/infra/workspace-kind.js +8 -8
- package/src/infra/worktree.js +4 -3
- package/src/interface/bin/acceptance-cli.js +4 -4
- package/src/interface/bin/monitor.jsx +6 -6
- package/src/interface/bin/setup.js +3 -3
- package/src/interface/bin/stage.js +2 -2
- package/src/interface/bin/web-server.js +2 -0
- package/src/interface/mcp/{tools → handlers}/delivery.js +30 -62
- package/src/interface/mcp/handlers/dispatch.js +233 -0
- package/src/interface/mcp/{tools → handlers}/facts.js +30 -65
- package/src/interface/mcp/handlers/overview.js +106 -0
- package/src/interface/mcp/{tools → handlers}/results.js +31 -60
- package/src/interface/mcp/{tools → handlers}/review.js +16 -36
- package/src/interface/mcp/{tools → handlers}/wait.js +13 -17
- package/src/interface/mcp/server.js +20 -50
- package/src/interface/mcp/tools/deliver.js +48 -0
- package/src/interface/mcp/tools/dispatch.js +78 -257
- package/src/interface/mcp/tools/optional.js +57 -0
- package/src/interface/mcp/tools/read.js +115 -0
- package/src/interface/mcp/tools/run.js +57 -0
- package/src/interface/mcp/tools/shapes.js +66 -0
- package/src/interface/mcp/tools/track.js +84 -0
- package/src/interface/mcp/views/task.js +8 -7
- package/src/interface/web/views.js +5 -2
- package/src/run-host/entry.js +3 -0
- package/src/run-host/finalize.js +8 -1
- package/src/run-host/launch.js +7 -7
- package/src/run-host/live-run.js +2 -0
- package/src/run-host/streams.js +28 -5
- package/src/run-host/track.js +5 -2
- package/src/runners/codex/tool-guard.js +6 -6
- package/web/dist/assets/{index-fJQbspTY.js → index-BnV-AYYI.js} +1 -1
- package/web/dist/assets/index-f8esISCp.css +2 -0
- package/web/dist/index.html +2 -2
- package/src/domain/overview-delta.js +0 -77
- package/src/interface/mcp/tools/overview.js +0 -202
- package/src/interface/mcp/tools/poll.js +0 -58
- package/web/dist/assets/index-DI1hLMxE.css +0 -2
|
@@ -1,12 +1,14 @@
|
|
|
1
|
+
import { newWorkerBranch } from "../domain/worker-branch.js";
|
|
1
2
|
import { gitBin, runGit } from "../infra/git.js";
|
|
2
3
|
import { worktreesDir } from "../infra/paths.js";
|
|
3
4
|
import { runToExit } from "../infra/process.js";
|
|
4
5
|
import { resolveWritableRoot } from "../infra/sandbox-roots.js";
|
|
6
|
+
import { isPidAlive } from "../infra/store/tasks.js";
|
|
5
7
|
import { DEFAULT_ACCEPTANCE_TIMEOUT_MS, runAcceptance } from "./acceptance.js";
|
|
6
8
|
import { WORKTREE_LOCK_TIMEOUT_MS } from "./run-state.js";
|
|
7
9
|
import { createHash } from "node:crypto";
|
|
8
10
|
import { existsSync } from "node:fs";
|
|
9
|
-
import { lstat, mkdir, realpath, rm, stat, symlink } from "node:fs/promises";
|
|
11
|
+
import { lstat, mkdir, readFile, realpath, rename, rm, stat, symlink, writeFile } from "node:fs/promises";
|
|
10
12
|
import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
11
13
|
|
|
12
14
|
export function splitLines(buffer, chunk) {
|
|
@@ -30,15 +32,15 @@ export function resolveCommit(cwd, ref) {
|
|
|
30
32
|
}
|
|
31
33
|
|
|
32
34
|
export function invalidBaseRefError(cwd, baseRef) {
|
|
33
|
-
const error = new Error(`
|
|
35
|
+
const error = new Error(`workspace.base_ref "${baseRef}" does not resolve to a commit in ${cwd}`);
|
|
34
36
|
error.code = "invalid_base_ref";
|
|
35
37
|
return error;
|
|
36
38
|
}
|
|
37
39
|
|
|
38
|
-
// The worktree is cut from
|
|
40
|
+
// The worktree is cut from workspace.base_ref when given, else from the repository's
|
|
39
41
|
// HEAD. The resolved commit is recorded on the task: it is what
|
|
40
42
|
// readWorktreeChanges diffs against, so committed work stays visible. An
|
|
41
|
-
// explicit
|
|
43
|
+
// explicit workspace.base_ref that does not resolve is an error, not a silent fallback
|
|
42
44
|
// to HEAD - the caller asked for a specific baseline for a reason.
|
|
43
45
|
export async function ensureWorktree(cwd, taskId, baseRef = null) {
|
|
44
46
|
const taskWorktreeDir = join(worktreesDir, taskId);
|
|
@@ -61,7 +63,7 @@ export async function ensureWorktree(cwd, taskId, baseRef = null) {
|
|
|
61
63
|
}
|
|
62
64
|
try {
|
|
63
65
|
await rm(taskWorktreeDir, { recursive: true, force: true });
|
|
64
|
-
const branch =
|
|
66
|
+
const branch = newWorkerBranch(taskId);
|
|
65
67
|
await runToExit(gitBin(), ["-C", cwd, "worktree", "add", "--detach", taskWorktreeDir, baseCommit]);
|
|
66
68
|
await runToExit(gitBin(), ["-C", taskWorktreeDir, "switch", "-c", branch]);
|
|
67
69
|
return { path: taskWorktreeDir, baseCommit };
|
|
@@ -79,16 +81,16 @@ function insidePath(parent, child) {
|
|
|
79
81
|
|
|
80
82
|
export function normalizeWorkspaceSetup(value, projectRoot) {
|
|
81
83
|
if (value == null) return null;
|
|
82
|
-
if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("
|
|
84
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("workspace.setup must be an object");
|
|
83
85
|
const links = (value.links ?? []).map((entry) => {
|
|
84
86
|
if (!entry || typeof entry.path !== "string" || !entry.path.trim()
|
|
85
|
-
|| typeof entry.source !== "string" || !entry.source.trim()) throw new Error("
|
|
87
|
+
|| typeof entry.source !== "string" || !entry.source.trim()) throw new Error("workspace.setup.links requires path and source");
|
|
86
88
|
const path = entry.path.trim();
|
|
87
|
-
if (isAbsolute(path) || path.split(/[\\/]/).includes("..")) throw new Error(`
|
|
89
|
+
if (isAbsolute(path) || path.split(/[\\/]/).includes("..")) throw new Error(`workspace.setup link path must stay inside the worktree: ${path}`);
|
|
88
90
|
return { path, source: resolve(projectRoot, entry.source.trim()) };
|
|
89
91
|
});
|
|
90
92
|
const commands = (value.commands ?? []).map((command) => String(command).trim()).filter(Boolean);
|
|
91
|
-
if (links.length > 20 || commands.length > 20) throw new Error("
|
|
93
|
+
if (links.length > 20 || commands.length > 20) throw new Error("workspace.setup accepts at most 20 links and 20 commands");
|
|
92
94
|
const submodules = value.submodules === true;
|
|
93
95
|
return links.length || submodules || commands.length ? { links, submodules, commands } : null;
|
|
94
96
|
}
|
|
@@ -99,7 +101,7 @@ export function requireDependencySetup({ kind, projectRoot, setup, commands }) {
|
|
|
99
101
|
if (kind !== "git_worktree" || setup || !existsSync(join(projectRoot, "package.json"))) return;
|
|
100
102
|
const commandText = (commands ?? []).map((check) => typeof check === "string" ? check : check?.command).filter(Boolean).join("\n");
|
|
101
103
|
if (!JS_DEPENDENCY_COMMAND.test(commandText)) return;
|
|
102
|
-
const error = new Error("workspace_setup_required: this JavaScript acceptance uses local project tooling, but the new worktree has no node_modules or generated prepare files; pass
|
|
104
|
+
const error = new Error("workspace_setup_required: this JavaScript acceptance uses local project tooling, but the new worktree has no node_modules or generated prepare files; pass workspace.setup with dependency links and prepare commands (the same setup must be used by preflight)");
|
|
103
105
|
error.code = "workspace_setup_required";
|
|
104
106
|
throw error;
|
|
105
107
|
}
|
|
@@ -107,15 +109,15 @@ export function requireDependencySetup({ kind, projectRoot, setup, commands }) {
|
|
|
107
109
|
export async function prepareWorktreeWorkspace(setup, projectRoot, worktreePath, taskId) {
|
|
108
110
|
if (!setup) return;
|
|
109
111
|
for (const link of setup.links) {
|
|
110
|
-
if (!existsSync(link.source)) throw new Error(`
|
|
112
|
+
if (!existsSync(link.source)) throw new Error(`workspace.setup link source does not exist: ${link.source}`);
|
|
111
113
|
const destination = resolve(worktreePath, link.path);
|
|
112
|
-
if (!insidePath(worktreePath, destination)) throw new Error(`
|
|
114
|
+
if (!insidePath(worktreePath, destination)) throw new Error(`workspace.setup link escapes the worktree: ${link.path}`);
|
|
113
115
|
await mkdir(dirname(destination), { recursive: true });
|
|
114
116
|
if (existsSync(destination)) {
|
|
115
117
|
const existing = await lstat(destination);
|
|
116
|
-
if (!existing.isSymbolicLink()) throw new Error(`
|
|
118
|
+
if (!existing.isSymbolicLink()) throw new Error(`workspace.setup link destination already exists: ${link.path}`);
|
|
117
119
|
const [actual, expected] = await Promise.all([realpath(destination), realpath(link.source)]);
|
|
118
|
-
if (actual !== expected) throw new Error(`
|
|
120
|
+
if (actual !== expected) throw new Error(`workspace.setup link destination points elsewhere: ${link.path}`);
|
|
119
121
|
continue;
|
|
120
122
|
}
|
|
121
123
|
const sourceInfo = await stat(link.source);
|
|
@@ -131,7 +133,7 @@ export async function prepareWorktreeWorkspace(setup, projectRoot, worktreePath,
|
|
|
131
133
|
const result = await runAcceptance(setup.commands, { cwd: worktreePath, taskId, timeoutMs: DEFAULT_ACCEPTANCE_TIMEOUT_MS });
|
|
132
134
|
if (!result.passed) {
|
|
133
135
|
const failing = result.checks.find((check) => !check.passed);
|
|
134
|
-
throw new Error(`
|
|
136
|
+
throw new Error(`workspace.setup command failed: ${failing?.command ?? "unknown"}${failing?.output_tail ? `\n${failing.output_tail}` : ""}`);
|
|
135
137
|
}
|
|
136
138
|
}
|
|
137
139
|
}
|
|
@@ -154,6 +156,44 @@ function sleep(ms) {
|
|
|
154
156
|
return new Promise((resolvePromise) => setTimeout(resolvePromise, ms));
|
|
155
157
|
}
|
|
156
158
|
|
|
159
|
+
// A lock whose holder died would otherwise stay for good: nothing else
|
|
160
|
+
// removes it, and every later dispatch into that repository would time out.
|
|
161
|
+
// The holder writes its pid into the lock; a waiter that finds the pid dead
|
|
162
|
+
// takes the lock away by renaming it, which only one waiter can win.
|
|
163
|
+
const LOCK_UNCLAIMED_MS = 10000;
|
|
164
|
+
|
|
165
|
+
async function lockIsAbandoned(lockPath) {
|
|
166
|
+
let owner;
|
|
167
|
+
try {
|
|
168
|
+
owner = Number(await readFile(join(lockPath, "owner"), "utf8"));
|
|
169
|
+
} catch (error) {
|
|
170
|
+
// Only a missing file means "not written yet"; anything else is a lock we cannot judge.
|
|
171
|
+
if (error.code !== "ENOENT") return false;
|
|
172
|
+
owner = 0;
|
|
173
|
+
}
|
|
174
|
+
if (owner) return !isPidAlive(owner);
|
|
175
|
+
// No owner yet: either the holder is between mkdir and its write, or it
|
|
176
|
+
// died there. Age tells them apart.
|
|
177
|
+
const info = await stat(lockPath).catch(() => null);
|
|
178
|
+
return Boolean(info) && Date.now() - info.mtimeMs > LOCK_UNCLAIMED_MS;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
async function breakAbandonedLock(lockPath) {
|
|
182
|
+
const aside = `${lockPath}.${process.pid}.${Date.now()}.stale`;
|
|
183
|
+
try {
|
|
184
|
+
await rename(lockPath, aside);
|
|
185
|
+
} catch {
|
|
186
|
+
return; // someone else broke it, or the holder released it
|
|
187
|
+
}
|
|
188
|
+
// Between the check and the rename another waiter may have broken the lock
|
|
189
|
+
// and taken a fresh one, which is then what was moved. It goes back.
|
|
190
|
+
if (!await lockIsAbandoned(aside)) {
|
|
191
|
+
await rename(aside, lockPath).catch(() => {});
|
|
192
|
+
return;
|
|
193
|
+
}
|
|
194
|
+
await rm(aside, { recursive: true, force: true }).catch(() => {});
|
|
195
|
+
}
|
|
196
|
+
|
|
157
197
|
export async function withWorktreeCreationLock(cwd, work) {
|
|
158
198
|
const lockName = `create-${createHash("sha256").update(resolve(cwd)).digest("hex").slice(0, 24)}.lock`;
|
|
159
199
|
const lockPath = join(worktreesDir, lockName);
|
|
@@ -165,10 +205,12 @@ export async function withWorktreeCreationLock(cwd, work) {
|
|
|
165
205
|
break;
|
|
166
206
|
} catch (error) {
|
|
167
207
|
if (error.code !== "EEXIST" || Date.now() >= deadline) throw new Error(`worktree creation lock timed out for ${cwd}`, { cause: error });
|
|
168
|
-
await
|
|
208
|
+
if (await lockIsAbandoned(lockPath)) await breakAbandonedLock(lockPath);
|
|
209
|
+
else await sleep(100);
|
|
169
210
|
}
|
|
170
211
|
}
|
|
171
212
|
try {
|
|
213
|
+
await writeFile(join(lockPath, "owner"), String(process.pid));
|
|
172
214
|
return await work();
|
|
173
215
|
} finally {
|
|
174
216
|
await rm(lockPath, { recursive: true, force: true }).catch(() => {});
|
|
@@ -9,7 +9,7 @@ export function normalizeAcceptance(value) {
|
|
|
9
9
|
const commands = list.filter((entry) => entry != null && entry !== "").map((entry) => {
|
|
10
10
|
if (typeof entry === "string") return entry.trim();
|
|
11
11
|
if (!entry || typeof entry !== "object" || Array.isArray(entry) || typeof entry.command !== "string" || !entry.command.trim()) throw new Error("acceptance requires a command string or structured check");
|
|
12
|
-
if (typeof entry.reportPath !== "string" || !entry.reportPath || isAbsolute(entry.reportPath) || /^[A-Za-z]:|^\\\\/.test(entry.reportPath) || entry.reportPath.split(/[\\/]/).includes("..")) throw new Error("
|
|
12
|
+
if (typeof entry.reportPath !== "string" || !entry.reportPath || isAbsolute(entry.reportPath) || /^[A-Za-z]:|^\\\\/.test(entry.reportPath) || entry.reportPath.split(/[\\/]/).includes("..")) throw new Error("report_path must stay inside the worktree");
|
|
13
13
|
const validation = compareFailureBaseline(entry.baseline, {
|
|
14
14
|
complete: true, identity: entry.baseline?.identity,
|
|
15
15
|
executed: [...new Set([...(entry.baseline?.required ?? []), ...(entry.baseline?.failures ?? []).map((item) => item?.test_id)])],
|
|
@@ -7,6 +7,36 @@ function providerFailure(text) {
|
|
|
7
7
|
return { source: "provider", code: status ? `provider_http_${status}` : "provider_error", retryable };
|
|
8
8
|
}
|
|
9
9
|
|
|
10
|
+
// "codex exited with code 1" says only that the process ended badly. The
|
|
11
|
+
// reason is whatever it last wrote to stderr, so that is read for the causes a
|
|
12
|
+
// caller acts on differently: fix the login, wait for the provider, fix the
|
|
13
|
+
// configuration. The last line is passed on either way.
|
|
14
|
+
const lastLine = (text) => text.split(/\r?\n/).map((line) => line.trim()).filter(Boolean).at(-1)?.slice(0, 300) ?? null;
|
|
15
|
+
|
|
16
|
+
function processExitFailure(stderr) {
|
|
17
|
+
const detail = lastLine(stderr);
|
|
18
|
+
const withDetail = (failure) => (detail ? { ...failure, detail } : failure);
|
|
19
|
+
// A bare 401 is also a line number or a millisecond; it counts only next to a word that makes it a status.
|
|
20
|
+
if (/(?:http|status|code|error)\D{0,8}(?:401|403)\b|unauthori[sz]ed|not logged in|login required|invalid api key|missing api key|forbidden/i.test(stderr)) {
|
|
21
|
+
return withDetail({ source: "auth", code: "auth_failed", retryable: false });
|
|
22
|
+
}
|
|
23
|
+
// A process of an earlier run still holds the session; it clears when that process ends.
|
|
24
|
+
if (/already has an active writer|thread-store conflict/i.test(stderr)) return withDetail({ source: "runner_session", code: "session_busy", retryable: true });
|
|
25
|
+
// The specific causes first: the general provider match answers to the word "provider" alone.
|
|
26
|
+
if (/(?:http|status|code|error)\D{0,8}429\b|rate.?limit|too many requests/i.test(stderr)) {
|
|
27
|
+
return withDetail({ source: "provider", code: "provider_rate_limited", retryable: true });
|
|
28
|
+
}
|
|
29
|
+
if (/ECONNREFUSED|ECONNRESET|ENOTFOUND|ETIMEDOUT|error sending request|connection (refused|reset|closed)|stream disconnected|dns error/i.test(stderr)) {
|
|
30
|
+
return withDetail({ source: "provider", code: "provider_unreachable", retryable: true });
|
|
31
|
+
}
|
|
32
|
+
const provider = providerFailure(stderr);
|
|
33
|
+
if (provider) return withDetail(provider);
|
|
34
|
+
if (/config\.toml|unknown model|model .{0,80}(not found|does not exist|not supported)|unexpected argument|invalid value/i.test(stderr)) {
|
|
35
|
+
return withDetail({ source: "runner_config", code: "config_invalid", retryable: false });
|
|
36
|
+
}
|
|
37
|
+
return withDetail({ source: "worker_process", code: "process_exit_nonzero", retryable: true });
|
|
38
|
+
}
|
|
39
|
+
|
|
10
40
|
export function classifyFailure(task) {
|
|
11
41
|
if (!task) return null;
|
|
12
42
|
const error = String(task.error ?? "");
|
|
@@ -16,15 +46,17 @@ export function classifyFailure(task) {
|
|
|
16
46
|
if (provider) return provider;
|
|
17
47
|
if (/did not record the process exit/i.test(error)) return { source: "supervisor_process", code: "exit_unrecorded", retryable: true };
|
|
18
48
|
if (attention === "start_failed") return { source: "supervisor_process", code: "start_failed", retryable: true };
|
|
19
|
-
if (/^
|
|
20
|
-
if (/^
|
|
49
|
+
if (/^workspace\.setup command failed:/i.test(error)) return { source: "workspace_setup", code: "setup_command_failed", retryable: true };
|
|
50
|
+
if (/^workspace\.setup link /i.test(error)) return { source: "workspace_setup", code: "setup_link_failed", retryable: true };
|
|
21
51
|
if (attention === "invalid_report" || /Invalid final worker report/i.test(error)) return { source: "model_output", code: "invalid_report", retryable: true };
|
|
22
52
|
if (task.acceptance_results?.passed === false) return { source: "acceptance", code: "acceptance_failed", retryable: true };
|
|
23
53
|
if (attention === "no_work" || attention === "two_stall") return { source: "worker_progress", code: attention, retryable: false };
|
|
24
|
-
if (
|
|
54
|
+
if (task.status === "timed_out" || attention === "run_time_limit" || attention === "total_time_limit") {
|
|
55
|
+
return { source: "time_limit", code: attention || "time_limit", retryable: false };
|
|
56
|
+
}
|
|
25
57
|
if (task.status === "lost") return { source: "supervisor_process", code: "worker_lost", retryable: true };
|
|
26
58
|
if (task.status === "cancelled") return { source: "caller", code: "cancelled", retryable: true };
|
|
27
|
-
if (/codex exited with code/i.test(error)) return
|
|
59
|
+
if (/codex exited with code/i.test(error)) return processExitFailure(String(task.stderr_tail ?? ""));
|
|
28
60
|
if (isGoalNeedingAttention(task.goal_status)) return { source: "goal", code: `goal_${task.goal_status}`, retryable: false };
|
|
29
61
|
if (task.status === "failed") return { source: "unknown", code: "failed", retryable: null };
|
|
30
62
|
return null;
|
package/src/domain/prompt.js
CHANGED
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
// its goal.
|
|
10
10
|
//
|
|
11
11
|
// Report format, at the end. A worker's last message is what the supervisor
|
|
12
|
-
// reads back through
|
|
12
|
+
// reads back through get_worker (include result). Left to itself a worker narrates
|
|
13
13
|
// the whole run and lists every file it touched, and one real report ran to
|
|
14
14
|
// four thousand tokens with the conclusion buried in the middle. The format
|
|
15
15
|
// asks for the three things a reviewer checks and nothing else: the result,
|
|
@@ -51,11 +51,11 @@ export const REPORT_SECTIONS = ["Result", "Verification", "Not done / risks"];
|
|
|
51
51
|
|
|
52
52
|
// The first thing a worker reads, and the only place the run's write boundary
|
|
53
53
|
// is stated. A worker is not always an editor: a read-only one can only read,
|
|
54
|
-
// and one with no
|
|
54
|
+
// and one with no owned_paths lands nothing, so both are told what their shell
|
|
55
55
|
// may do instead of being told to use apply_patch they cannot use.
|
|
56
56
|
export function buildGuardPreamble({ sandbox, ownedPaths = [], allowedCommands = [], forbid = [], networkAccess = false, workspaceKind = null } = {}) {
|
|
57
57
|
const forbidden = JSON.stringify(forbid);
|
|
58
|
-
const stage = 'For a long gate, checkpoint phases with node "$
|
|
58
|
+
const stage = 'For a long gate, checkpoint phases with node "$AGENT_SUPERVISOR_STAGE_CLI" "gate:s3" --detail "current check"; stage text is visible to status/overview/wait and must not contain secrets.';
|
|
59
59
|
if (sandbox === "read-only") {
|
|
60
60
|
return [
|
|
61
61
|
"Runtime supervisor guard: this is a read-only task.",
|
|
@@ -70,7 +70,7 @@ export function buildGuardPreamble({ sandbox, ownedPaths = [], allowedCommands =
|
|
|
70
70
|
? "Its execution directory is a supervisor-managed scratch directory, not the user's source directory"
|
|
71
71
|
: "Its worktree is a scratch copy";
|
|
72
72
|
return [
|
|
73
|
-
"Runtime supervisor guard: this worker lands nothing: no
|
|
73
|
+
"Runtime supervisor guard: this worker lands nothing: no owned_paths means nothing it writes is ever merged into the project.",
|
|
74
74
|
`${location}, so the shell is unrestricted apart from the red lines; keep notes and downloads inside it.`,
|
|
75
75
|
networkAccess ? "Network is available." : "There is no network in this sandbox; ask for it instead of retrying a failing fetch.",
|
|
76
76
|
`Forbidden: ${forbidden}.`,
|
|
@@ -83,7 +83,7 @@ export function buildGuardPreamble({ sandbox, ownedPaths = [], allowedCommands =
|
|
|
83
83
|
// about it instead of stalling on a tool it does not have.
|
|
84
84
|
const shellEdit = "If your toolset has no apply_patch tool, run it through the shell as apply_patch <<'EOF' ... EOF; the guard checks the file paths the same way. A declared command ending in * is a prefix, so go test ./internal/* covers go test ./internal/service -run TestX.";
|
|
85
85
|
const delivery = sandbox === "workspace-write" && (!workspaceKind || workspaceKind === "git_worktree")
|
|
86
|
-
? "Do not run git add, git commit or git commit --amend: the dispatcher commits reviewed edits with
|
|
86
|
+
? "Do not run git add, git commit or git commit --amend: the dispatcher commits reviewed edits with land_worker({commit_message}). Leave your edits uncommitted; clean status and commit-count checks belong after landing. If the task or acceptance requires a self-commit or a clean edited worktree, report the contract conflict instead of bypassing the guard."
|
|
87
87
|
: "";
|
|
88
88
|
return `Runtime supervisor guard: edits must use apply_patch within ${JSON.stringify(ownedPaths)}. ${shellEdit} ${delivery} Safe read-only inspection commands (rg, cat, sed without -i, git status/diff/log, jq without -i, find without -exec/-delete) are allowed and never reserve another worker's paths. Commands that validate, write, execute code or have side effects must exactly match declared commands ${JSON.stringify(allowedCommands)}. Forbidden: ${forbidden}. Undeclared shell programs are denied; report a needed validation command instead of bypassing the guard. ${stage}`;
|
|
89
89
|
}
|
|
@@ -96,7 +96,7 @@ export function buildGuardPreamble({ sandbox, ownedPaths = [], allowedCommands =
|
|
|
96
96
|
export function buildAcceptanceBlock(acceptance, { resume = false } = {}) {
|
|
97
97
|
const commands = Array.isArray(acceptance) ? acceptance.filter(Boolean) : [];
|
|
98
98
|
if (commands.length === 0) return "";
|
|
99
|
-
const runner = 'Run node "$
|
|
99
|
+
const runner = 'Run node "$AGENT_SUPERVISOR_ACCEPTANCE_CLI" to execute this exact contract through the supervisor\'s non-interactive Bash with errexit and pipefail. Do not retype the commands in zsh; the interactive shell is not the acceptance shell.';
|
|
100
100
|
if (resume) {
|
|
101
101
|
return ["Acceptance is unchanged.", runner, `Commands: ${commands.map((check) => typeof check === "string" ? check : JSON.stringify(check)).join(" ; ")}`].join("\n");
|
|
102
102
|
}
|
|
@@ -145,7 +145,7 @@ export function frameWorkerPrompt(prompt, goalOptions, { acceptance = null, outp
|
|
|
145
145
|
export function buildHostGoalSync(session) {
|
|
146
146
|
const id = JSON.stringify(String(session.id));
|
|
147
147
|
const condition = [
|
|
148
|
-
`For supervisor session ${id}, read
|
|
148
|
+
`For supervisor session ${id}, read find_works and use its current objective, default_acceptance, approval_state and policy_revision (at least ${session.policy_revision ?? 0}).`,
|
|
149
149
|
"Use the latest explicit human instruction and approved failure baseline; superseded goals and checks must not be revived.",
|
|
150
150
|
"Stop when the current approved objective is verified and all required worker results are collected, checked and integrated as requested.",
|
|
151
151
|
"If approval_state is waiting_user, stop after clearly reporting the blocker, attempted checks, options and recommendation and asking for the required decision; do not auto-resume or repeat unchanged waiting reports.",
|
package/src/domain/status.js
CHANGED
|
@@ -4,13 +4,16 @@
|
|
|
4
4
|
// phase = what the worker is doing right now. Only meaningful while
|
|
5
5
|
// status === "running"; NULL once the work reaches a terminal status.
|
|
6
6
|
|
|
7
|
-
|
|
7
|
+
// timed_out is a worker the supervisor stopped because its time budget ran
|
|
8
|
+
// out. It is not lost: nothing vanished, and re-running it unchanged would
|
|
9
|
+
// only run out of time again.
|
|
10
|
+
export const TASK_STATUSES = ["queued", "running", "completed", "failed", "cancelled", "lost", "timed_out"];
|
|
8
11
|
|
|
9
12
|
export const PHASES = ["starting", "thinking", "command", "editing", "reporting"];
|
|
10
13
|
|
|
11
14
|
export const ACTIVE_STATUSES = new Set(["queued", "running"]);
|
|
12
15
|
|
|
13
|
-
export const TERMINAL_STATUSES = new Set(["completed", "failed", "cancelled", "lost"]);
|
|
16
|
+
export const TERMINAL_STATUSES = new Set(["completed", "failed", "cancelled", "lost", "timed_out"]);
|
|
14
17
|
|
|
15
18
|
// Codex native thread goal status -> work status.
|
|
16
19
|
// Storage uses snake_case ("usage_limited"); the RPC layer uses camelCase
|
|
@@ -35,3 +38,13 @@ export function isGoalNeedingAttention(nativeStatus) {
|
|
|
35
38
|
const key = String(nativeStatus ?? "").replace(/_/g, "").toLowerCase();
|
|
36
39
|
return ["blocked", "paused", "usagelimited", "budgetlimited"].includes(key);
|
|
37
40
|
}
|
|
41
|
+
|
|
42
|
+
// True once nothing of a worker's last run can still be running: its exit
|
|
43
|
+
// code or the signal that ended it is recorded (the last thing a run host
|
|
44
|
+
// writes), or the row was marked
|
|
45
|
+
// lost (done only after both processes were seen gone). From then on the pids
|
|
46
|
+
// on the row are history. The system hands them to other processes, on
|
|
47
|
+
// Windows within seconds, and a live stranger must not read as a live worker.
|
|
48
|
+
export function runIsOver(task) {
|
|
49
|
+
return task.status === "lost" || (TERMINAL_STATUSES.has(task.status) && (task.exit_code != null || task.signal != null));
|
|
50
|
+
}
|
|
@@ -2,7 +2,7 @@ const DEFAULT_HANDOFF_TOKEN_THRESHOLD = 300000;
|
|
|
2
2
|
const LONG_THREAD_RATIO = 0.75;
|
|
3
3
|
|
|
4
4
|
export function handoffTokenThreshold(env = process.env) {
|
|
5
|
-
const raw = env.
|
|
5
|
+
const raw = env.AGENT_SUPERVISOR_HANDOFF_TOKEN_THRESHOLD;
|
|
6
6
|
if (raw == null || raw === "") return DEFAULT_HANDOFF_TOKEN_THRESHOLD;
|
|
7
7
|
const value = Number(raw);
|
|
8
8
|
if (!Number.isFinite(value) || value < 0) return DEFAULT_HANDOFF_TOKEN_THRESHOLD;
|
|
@@ -18,7 +18,7 @@ export function threadHealth(task, { threshold = handoffTokenThreshold() } = {})
|
|
|
18
18
|
state: "handoff_recommended",
|
|
19
19
|
threshold,
|
|
20
20
|
tokens_used: tokens,
|
|
21
|
-
next_step: "Start a fresh 1000-1500-token handoff with
|
|
21
|
+
next_step: "Start a fresh 1000-1500-token handoff with create_worker with followup_of; keep this thread as evidence"
|
|
22
22
|
};
|
|
23
23
|
}
|
|
24
24
|
if (tokens >= Math.floor(threshold * LONG_THREAD_RATIO)) {
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
// The branch a worker's commits live on. Workers dispatched before 1.0 used
|
|
2
|
+
// codex/<id>; their rows carry no branch name, so that is the fallback, and
|
|
3
|
+
// they can still be resumed, landed and restored.
|
|
4
|
+
export const newWorkerBranch = (taskId) => `worker/${taskId}`;
|
|
5
|
+
|
|
6
|
+
export const branchOf = (task) => task.workspace_metadata?.branch ?? `codex/${task.id}`;
|
|
@@ -20,7 +20,7 @@ export function collectWorkerChanges(tasks, cursor = {}) {
|
|
|
20
20
|
id: task.id, title: task.title ?? task.id, run: task.run_count, status: task.status,
|
|
21
21
|
reason: "handoff_recommended", tokens_used: health.tokens_used, threshold: health.threshold,
|
|
22
22
|
next_step: {
|
|
23
|
-
tool: "
|
|
23
|
+
tool: "get_worker", arguments: { task_id: task.id, include: ["status"] },
|
|
24
24
|
instruction: "Inspect the live command and stage. Let this bounded step settle or explicitly cancel it before preparing a reviewed checkpoint and a fresh follow-up; do not launch a duplicate while it is active."
|
|
25
25
|
}
|
|
26
26
|
};
|
|
@@ -46,8 +46,8 @@ export function collectWorkerChanges(tasks, cursor = {}) {
|
|
|
46
46
|
const receipt = {
|
|
47
47
|
id: task.id, title: task.title ?? task.id, run: task.run_count, status: task.status,
|
|
48
48
|
reason, next_step: {
|
|
49
|
-
tool: needsAttention ? "
|
|
50
|
-
arguments: { task_id: task.id },
|
|
49
|
+
tool: needsAttention ? "get_worker" : "get_worker_diff",
|
|
50
|
+
arguments: needsAttention ? { task_id: task.id, include: ["result"] } : { task_id: task.id },
|
|
51
51
|
instruction: needsAttention ? "Read the failure or goal evidence before deciding whether to resume; user approval waits must not auto-resume." : "Read the result and diff, then decide whether to land. Completion is not proof of correctness."
|
|
52
52
|
}
|
|
53
53
|
};
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { TERMINAL_STATUSES } from "./status.js";
|
|
1
2
|
import { createHash } from "node:crypto";
|
|
2
3
|
import { resolve } from "node:path";
|
|
3
4
|
import { commandFailed } from "./command-outcome.js";
|
|
@@ -117,7 +118,7 @@ export function readPreflightResult(task) {
|
|
|
117
118
|
passed: Boolean(result) && !commandFailed(result)
|
|
118
119
|
};
|
|
119
120
|
});
|
|
120
|
-
const terminal =
|
|
121
|
+
const terminal = TERMINAL_STATUSES.has(task.status);
|
|
121
122
|
const failedCommands = commands.filter(commandFailed);
|
|
122
123
|
const probesPassed = probes.every((probe) => probe.passed);
|
|
123
124
|
const exitConfirmed = task.status === "completed" && task.exit_code === 0;
|
|
@@ -23,7 +23,7 @@ export async function cleanupHint({ list = readdir, root = supervisorRoot, dir =
|
|
|
23
23
|
threshold,
|
|
24
24
|
command: `SUPERVISOR_HOME=${root} codex-supervisor-cleanup --dry-run`,
|
|
25
25
|
apply: null,
|
|
26
|
-
next_step: "Read the plan: REVIEW items say when they become removable. Land or resume the work you still want;
|
|
26
|
+
next_step: "Read the plan: REVIEW items say when they become removable. Land or resume the work you still want; cleanup (action apply) removes a SAFE item right away.",
|
|
27
27
|
note: "a worktree is SAFE once its work has landed, or has nothing to keep, or its hold period is over; uncommitted edits are saved on the worker branch first, and branches and evidence are never removed"
|
|
28
28
|
};
|
|
29
29
|
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
// Last line of defence for a long-lived process. Without it one promise that
|
|
2
|
+
// nobody awaited ends the MCP server, and every tool call after that answers
|
|
3
|
+
// "Connection closed" with no trace of why.
|
|
4
|
+
//
|
|
5
|
+
// A rejection nobody handled is written down and the process carries on: the
|
|
6
|
+
// state is in the store, not in memory, so the next call is as good as the
|
|
7
|
+
// last. A thrown exception is written down and the process exits, because
|
|
8
|
+
// after one the stack it interrupted cannot be trusted.
|
|
9
|
+
import { appendFileSync, mkdirSync, statSync, writeFileSync } from "node:fs";
|
|
10
|
+
import { join } from "node:path";
|
|
11
|
+
import { dataDir } from "./paths.js";
|
|
12
|
+
|
|
13
|
+
export const crashLogPath = join(dataDir, "crash.log");
|
|
14
|
+
const MAX_BYTES = 1024 * 1024;
|
|
15
|
+
|
|
16
|
+
function record(role, kind, error) {
|
|
17
|
+
const text = error instanceof Error ? (error.stack ?? error.message) : String(error);
|
|
18
|
+
const line = `${JSON.stringify({ at: new Date().toISOString(), role, pid: process.pid, kind, error: text })}\n`;
|
|
19
|
+
process.stderr.write(`[agent-supervisor] ${role} ${kind}: ${text}\n`);
|
|
20
|
+
try {
|
|
21
|
+
mkdirSync(dataDir, { recursive: true });
|
|
22
|
+
const size = statSync(crashLogPath, { throwIfNoEntry: false })?.size ?? 0;
|
|
23
|
+
if (size > MAX_BYTES) writeFileSync(crashLogPath, line);
|
|
24
|
+
else appendFileSync(crashLogPath, line);
|
|
25
|
+
} catch (writeError) {
|
|
26
|
+
process.stderr.write(`[agent-supervisor] could not write ${crashLogPath}: ${writeError.message}\n`);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// role names the process in the log: "mcp-server", "run-host", "web".
|
|
31
|
+
//
|
|
32
|
+
// exitOnRejection is for the run host, whose state is in memory: the live run,
|
|
33
|
+
// the child, the write chains. Kept alive after a rejection it would hold its
|
|
34
|
+
// row at "running" for good, where a dead one is found and recovered by pid.
|
|
35
|
+
export function installCrashGuard(role, { exitOnRejection = false } = {}) {
|
|
36
|
+
process.on("unhandledRejection", (reason) => {
|
|
37
|
+
record(role, "unhandled_rejection", reason);
|
|
38
|
+
if (exitOnRejection) process.exit(1);
|
|
39
|
+
});
|
|
40
|
+
process.on("uncaughtException", (error) => {
|
|
41
|
+
record(role, "uncaught_exception", error);
|
|
42
|
+
process.exit(1);
|
|
43
|
+
});
|
|
44
|
+
}
|
|
@@ -3,10 +3,10 @@ import { isAbsolute, dirname } from "node:path";
|
|
|
3
3
|
import { createHash } from "node:crypto";
|
|
4
4
|
|
|
5
5
|
export async function captureExternalOutputs(declarations, { checkBaseline = false } = {}) {
|
|
6
|
-
if (!Array.isArray(declarations) || declarations.length > 20) throw new Error("
|
|
6
|
+
if (!Array.isArray(declarations) || declarations.length > 20) throw new Error("workspace.external_outputs must contain at most 20 files");
|
|
7
7
|
const captured = [];
|
|
8
8
|
for (const entry of declarations) {
|
|
9
|
-
if (!entry || !isAbsolute(entry.path)) throw new Error("
|
|
9
|
+
if (!entry || !isAbsolute(entry.path)) throw new Error("workspace.external_outputs must use absolute file paths");
|
|
10
10
|
let info;
|
|
11
11
|
try { info = await lstat(entry.path); } catch (error) { if (error.code !== "ENOENT") throw error; }
|
|
12
12
|
let snapshot = { path: entry.path, exists: false, sha256: null, content: null, truncated: false };
|
package/src/infra/git.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// The only place that runs git. Callers differ in real ways (optional locks,
|
|
2
2
|
// path quoting, what happens to stderr, whether output is trimmed), so those
|
|
3
3
|
// are options here instead of one private copy per caller.
|
|
4
|
-
import { execFileSync } from "node:child_process";
|
|
4
|
+
import { execFile, execFileSync } from "node:child_process";
|
|
5
5
|
|
|
6
6
|
export const gitBin = () => process.env.GIT_BIN?.trim() || "git";
|
|
7
7
|
|
|
@@ -19,12 +19,43 @@ export function runGit(cwd, args, options = {}) {
|
|
|
19
19
|
return trim && typeof output === "string" ? output.trim() : output;
|
|
20
20
|
}
|
|
21
21
|
|
|
22
|
-
//
|
|
22
|
+
// git that does not hold the event loop, for the paths that run many
|
|
23
|
+
// commands inside one request: cleanup walks every finished worktree during a
|
|
24
|
+
// poll. Takes the options runGit takes, apart from input and stderr.
|
|
25
|
+
export function runGitAsync(cwd, args, options = {}) {
|
|
26
|
+
const { timeout = 60000, noOptionalLocks = false, rawPaths = false, maxBuffer, env, trim = true } = options;
|
|
27
|
+
const argv = [...(noOptionalLocks ? ["--no-optional-locks"] : []), "-C", cwd, ...(rawPaths ? ["-c", "core.quotePath=false"] : []), ...args];
|
|
28
|
+
return new Promise((resolveRun, rejectRun) => {
|
|
29
|
+
execFile(gitBin(), argv, { encoding: "utf8", timeout, ...(maxBuffer ? { maxBuffer } : {}), ...(env ? { env } : {}) }, (error, stdout, stderr) => {
|
|
30
|
+
if (!error) return resolveRun(trim ? stdout.trim() : stdout);
|
|
31
|
+
error.message = `${error.message.split("\n")[0]}${stderr?.trim() ? `\n${stderr.trim()}` : ""}`;
|
|
32
|
+
rejectRun(error);
|
|
33
|
+
});
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// A question git answers with its exit code, such as merge-base
|
|
38
|
+
// --is-ancestor. An exit code is an answer. A timeout, a signal or a git that
|
|
39
|
+
// could not be started is not "no", and reading it as one turns a slow disk
|
|
40
|
+
// into "this commit never landed", so those throw.
|
|
41
|
+
const answered = (error) => typeof (error.status ?? error.code) === "number";
|
|
42
|
+
|
|
23
43
|
export function gitSucceeds(cwd, args, { timeout = 15000 } = {}) {
|
|
24
44
|
try {
|
|
25
45
|
execFileSync(gitBin(), ["-C", cwd, ...args], { stdio: "ignore", timeout });
|
|
26
46
|
return true;
|
|
27
|
-
} catch {
|
|
28
|
-
return false;
|
|
47
|
+
} catch (error) {
|
|
48
|
+
if (answered(error)) return false;
|
|
49
|
+
throw error;
|
|
29
50
|
}
|
|
30
51
|
}
|
|
52
|
+
|
|
53
|
+
export function gitSucceedsAsync(cwd, args, { timeout = 15000 } = {}) {
|
|
54
|
+
return new Promise((resolveRun, rejectRun) => {
|
|
55
|
+
execFile(gitBin(), ["-C", cwd, ...args], { timeout }, (error) => {
|
|
56
|
+
if (!error) resolveRun(true);
|
|
57
|
+
else if (answered(error)) resolveRun(false);
|
|
58
|
+
else rejectRun(error);
|
|
59
|
+
});
|
|
60
|
+
});
|
|
61
|
+
}
|
|
@@ -68,7 +68,7 @@ export const TOOLCHAIN_CACHE_DIRS = [
|
|
|
68
68
|
];
|
|
69
69
|
|
|
70
70
|
// Credentials are never granted automatically. A dispatcher that needs them
|
|
71
|
-
// names the directory in
|
|
71
|
+
// names the directory in sandbox.writable_roots for that one dispatch: an ssh test wants
|
|
72
72
|
// ~/.ssh (known_hosts, ControlMaster sockets), a kubectl test ~/.kube, a registry
|
|
73
73
|
// push ~/.docker, an aws test ~/.aws, a signed commit ~/.gnupg. Everything here is
|
|
74
74
|
// granted automatically only when it holds build state, not secrets, so a worker
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
// A worker's output is written twice: the raw line to its JSONL log and the
|
|
2
|
+
// event to the store. Nearly all of the store's size was the second copy of
|
|
3
|
+
// command output. A large event from the worker now keeps only a clipped copy
|
|
4
|
+
// in the store, marked with the hash of the full line; the JSONL is the one
|
|
5
|
+
// place the full body lives, and it is read back from there on request.
|
|
6
|
+
//
|
|
7
|
+
// Kept whole whatever their size: the worker's messages and turn events, which
|
|
8
|
+
// the state machine and the result readers query, and everything the
|
|
9
|
+
// supervisor writes itself, which is in no log.
|
|
10
|
+
import { truncateEventStrings } from "../../domain/truncate.js";
|
|
11
|
+
import { extractAgentMessage } from "./runner-readers.js";
|
|
12
|
+
import { createHash } from "node:crypto";
|
|
13
|
+
import { createReadStream } from "node:fs";
|
|
14
|
+
import { createInterface } from "node:readline";
|
|
15
|
+
|
|
16
|
+
export const EVENT_INLINE_BYTES = 2048;
|
|
17
|
+
const CLIPPED_STRING_BYTES = 1024;
|
|
18
|
+
// The marker is the supervisor's, named so it cannot be taken for a field of the worker's event.
|
|
19
|
+
export const CLIP_KEY = "supervisor_clipped";
|
|
20
|
+
|
|
21
|
+
const sha256 = (text) => createHash("sha256").update(text).digest("hex");
|
|
22
|
+
|
|
23
|
+
function keptWhole(event) {
|
|
24
|
+
if (String(event.type ?? "").startsWith("turn.") || event.type === "thread.started") return true;
|
|
25
|
+
try {
|
|
26
|
+
return extractAgentMessage(event) != null;
|
|
27
|
+
} catch {
|
|
28
|
+
return true; // an event the runner cannot read is not ours to cut
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// Returns what goes in the store for one event: { payload, sha256 }, where
|
|
33
|
+
// sha256 is always the hash of the full line as the log has it.
|
|
34
|
+
export function storedForm(event, { bodyInLog = false, offset = null } = {}) {
|
|
35
|
+
const full = JSON.stringify(event);
|
|
36
|
+
const hash = sha256(full);
|
|
37
|
+
const bytes = Buffer.byteLength(full, "utf8");
|
|
38
|
+
if (!bodyInLog || bytes <= EVENT_INLINE_BYTES || keptWhole(event)) return { payload: full, sha256: hash };
|
|
39
|
+
const clipped = JSON.stringify({ ...truncateEventStrings(event, CLIPPED_STRING_BYTES), [CLIP_KEY]: { stored: "jsonl", bytes, sha256: hash, offset } });
|
|
40
|
+
// An event made of many small strings does not shrink; marking it would only cost a log read later.
|
|
41
|
+
if (Buffer.byteLength(clipped, "utf8") > bytes / 2) return { payload: full, sha256: hash };
|
|
42
|
+
return { payload: clipped, sha256: hash };
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const isClipped = (event) => event?.[CLIP_KEY]?.stored === "jsonl" && typeof event[CLIP_KEY].sha256 === "string";
|
|
46
|
+
|
|
47
|
+
// Collects the wanted lines from the log, reading from `start`.
|
|
48
|
+
async function scanLog(logPath, start, wanted, found) {
|
|
49
|
+
const lines = createInterface({ input: createReadStream(logPath, { encoding: "utf8", start }), crlfDelay: Infinity });
|
|
50
|
+
for await (const line of lines) {
|
|
51
|
+
if (Buffer.byteLength(line, "utf8") <= EVENT_INLINE_BYTES) continue;
|
|
52
|
+
const hash = sha256(line);
|
|
53
|
+
if (wanted.has(hash)) found.set(hash, line);
|
|
54
|
+
if (found.size === wanted.size) break;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// Puts the full bodies back from the log. The recorded offset says where to
|
|
59
|
+
// start, so reading the newest events does not mean reading the whole log; a
|
|
60
|
+
// line that is not where it was recorded is looked for once from the top. An
|
|
61
|
+
// event whose line cannot be found stays clipped and says so.
|
|
62
|
+
export async function restoreEventBodies(events, logPath) {
|
|
63
|
+
const clipped = events.filter(isClipped);
|
|
64
|
+
if (clipped.length === 0) return events;
|
|
65
|
+
const wanted = new Set(clipped.map((event) => event[CLIP_KEY].sha256));
|
|
66
|
+
const found = new Map();
|
|
67
|
+
if (logPath) {
|
|
68
|
+
try {
|
|
69
|
+
const offsets = clipped.map((event) => event[CLIP_KEY].offset);
|
|
70
|
+
const start = offsets.every((offset) => Number.isInteger(offset) && offset >= 0) ? Math.min(...offsets) : 0;
|
|
71
|
+
await scanLog(logPath, start, wanted, found);
|
|
72
|
+
if (found.size < wanted.size && start > 0) await scanLog(logPath, 0, wanted, found);
|
|
73
|
+
} catch {
|
|
74
|
+
// a log that is gone leaves the events clipped, marked below
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
return events.map((event) => {
|
|
78
|
+
if (!isClipped(event)) return event;
|
|
79
|
+
const line = found.get(event[CLIP_KEY].sha256);
|
|
80
|
+
return line ? JSON.parse(line) : { ...event, [CLIP_KEY]: { ...event[CLIP_KEY], missing: true } };
|
|
81
|
+
});
|
|
82
|
+
}
|