codex-supervisor-mcp 1.0.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 +3 -0
- package/README.md +3 -0
- package/package.json +2 -2
- package/skills/codex-supervisor/SKILL.md +2 -1
- package/src/app/cleanup-facts.js +14 -12
- package/src/app/cleanup-plan.js +19 -18
- package/src/app/resume.js +6 -2
- package/src/app/worktree-setup.js +43 -2
- package/src/domain/failure-class.js +34 -2
- package/src/domain/status.js +8 -4
- package/src/domain/worker-preflight.js +2 -1
- package/src/infra/crash-guard.js +44 -0
- package/src/infra/git.js +35 -4
- package/src/infra/store/event-body.js +82 -0
- package/src/infra/store/events.js +7 -5
- package/src/infra/store/tasks.js +14 -0
- package/src/interface/bin/web-server.js +2 -0
- package/src/interface/mcp/handlers/overview.js +4 -1
- package/src/interface/mcp/handlers/wait.js +5 -3
- package/src/interface/mcp/server.js +3 -0
- package/src/interface/web/views.js +3 -1
- package/src/run-host/entry.js +3 -0
- package/src/run-host/finalize.js +8 -1
- 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/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/web/dist/assets/index-DI1hLMxE.css +0 -2
package/README.en.md
CHANGED
|
@@ -18,6 +18,8 @@ codex-supervisor-mcp is an MCP server. A main thread (Claude Code, Codex, or any
|
|
|
18
18
|
|
|
19
19
|
*30 seconds, recorded live: three workers in their own worktrees in parallel, then the main thread collects three diffs and makes one commit.*
|
|
20
20
|
|
|
21
|
+
> **Upgrading from 0.x to 1.x**: 39 tools became 14, with new names and arguments and no aliases for the old ones. Finish the workers in flight first, then reopen the session after upgrading so the new skill loads. The tool table is in the [reference](docs/reference.en.md); what changed is in the [1.0.0 release](https://github.com/zriyox/codex-supervisor-mcp/releases/tag/v1.0.0).
|
|
22
|
+
|
|
21
23
|
## What it solves
|
|
22
24
|
|
|
23
25
|
| Problem | What it does |
|
|
@@ -169,6 +171,7 @@ rm -rf ~/.claude/skills/codex-supervisor ~/.agents/skills/codex-supervisor ~/.co
|
|
|
169
171
|
| `codex only resolved to a shell shim` | Windows found only the `.cmd`; the package entry is gone | Reinstall `@openai/codex`, or point `CODEX_BIN` at `codex.js` |
|
|
170
172
|
| `Cannot find module 'node:sqlite'` | Node older than 22.13.0 | Upgrade Node |
|
|
171
173
|
| Worker is `lost` | The worker or its run process was killed | Read the events, then `resume_worker` |
|
|
174
|
+
| Worker is `timed_out` | Its time budget ran out and it was stopped | Read what it left; `resume_worker` after a per-run limit, `followup_of` with new `limits` after the total one |
|
|
172
175
|
| `git add` fails with `index.lock: Operation not permitted` | The sandbox makes `.git` read-only. That is the intended boundary | Let `land_worker` commit with `commit_message` |
|
|
173
176
|
| `owned_paths overlap with active worker(s)` | Two workers claimed the same paths | Split the work differently, or cancel the one holding them |
|
|
174
177
|
| The board is empty | The board and the MCP server use different `SUPERVISOR_HOME` | Point both at the same directory |
|
package/README.md
CHANGED
|
@@ -18,6 +18,8 @@ codex-supervisor-mcp 是一个 MCP server。主线程(Claude Code、Codex 或
|
|
|
18
18
|
|
|
19
19
|
*30 秒真跑:派 3 个 worker,各自 worktree 并行,主线程收 3 份 diff 合成一次 commit。*
|
|
20
20
|
|
|
21
|
+
> **从 0.x 升级到 1.x**:工具从 39 个收成 14 个,名字和参数都换了,旧名不留别名。升级前先把在跑的 worker 收完,升级后重开会话让新 skill 生效。对照表在[参考手册](docs/reference.md),变更说明在 [1.0.0 release](https://github.com/zriyox/codex-supervisor-mcp/releases/tag/v1.0.0)。
|
|
22
|
+
|
|
21
23
|
## 解决什么
|
|
22
24
|
|
|
23
25
|
| 问题 | 做法 |
|
|
@@ -168,6 +170,7 @@ rm -rf ~/.claude/skills/codex-supervisor ~/.agents/skills/codex-supervisor ~/.co
|
|
|
168
170
|
| `codex only resolved to a shell shim` | Windows 只找到 `.cmd`,包入口没了 | 重装 `@openai/codex`,或 `CODEX_BIN` 指到 `codex.js` |
|
|
169
171
|
| `Cannot find module 'node:sqlite'` | Node 低于 22.13.0 | 升 Node |
|
|
170
172
|
| worker `lost` | worker 或它的运行进程被杀了 | 查事件,`resume_worker` 接回 |
|
|
173
|
+
| worker `timed_out` | 时间预算用完被停掉 | 看已有改动;单轮超时 `resume_worker`,总预算用完用 `followup_of` 带新 `limits` 接续 |
|
|
171
174
|
| `git add` 报 `index.lock: Operation not permitted` | 沙箱把 `.git` 设成只读,这是正常边界 | 让 `land_worker` 带 `commit_message` 代提交 |
|
|
172
175
|
| `owned_paths overlap with active worker(s)` | 两路认领了同一片路径 | 改拆法,或取消占着的那路 |
|
|
173
176
|
| 看板是空的 | 看板和 MCP 的 `SUPERVISOR_HOME` 不一样 | 两边指同一个目录 |
|
package/package.json
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "codex-supervisor-mcp",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.1.0",
|
|
4
4
|
"mcpName": "io.github.zriyox/codex-supervisor-mcp",
|
|
5
5
|
"type": "module",
|
|
6
|
-
"description": "MCP server that
|
|
6
|
+
"description": "MCP server that runs parallel Codex CLI workers from Claude Code, Codex or any MCP client: one Git worktree each, 14 tools to dispatch, track, check, land and clean up, state on disk.",
|
|
7
7
|
"homepage": "https://codex-supervisor.zriyo.com",
|
|
8
8
|
"license": "MIT",
|
|
9
9
|
"repository": {
|
|
@@ -112,8 +112,9 @@ description: 用 Codex CLI 并行做可独立验收的功能包,每路一个 G
|
|
|
112
112
|
|---|---|
|
|
113
113
|
| 主线程挂了 | worker 的独立进程会继续记录日志、状态和验收。新窗口用 `find_works` 按 session 接回 |
|
|
114
114
|
| worker 变 `lost` | 确实中断才 `resume_worker`;worktree、改动和线程都保留 |
|
|
115
|
+
| worker 变 `timed_out` | 时间预算用完被停掉,不会自动重试。先看已有改动;`run_time_limit` 可以 `resume_worker`(每轮重新计时),`total_time_limit` 只能 `followup_of` 带新 `limits` 接续 |
|
|
115
116
|
| worktree 落后主线 | `resume_worker` 带 `rebase_onto: "HEAD"` |
|
|
116
|
-
| worker 失败 | 先看 `failure
|
|
117
|
+
| worker 失败 | 先看 `failure`:`source` 是 `auth`(登录或 key,重试没用)、`provider`(上游,`retryable` 为 true 就等一会再 resume)、`runner_config`(配置或模型名)、`workspace_setup`、`model_output`、`acceptance`、`time_limit`、`worker_process`。进程非零退出时 `failure.detail` 是它 stderr 的最后一行 |
|
|
117
118
|
| worktree 被清掉了 | 照常 `resume_worker` / `land_worker` / `get_worker_diff` / `ask_worker`,会从分支切回来 |
|
|
118
119
|
|
|
119
120
|
审批、认证、权限、quota 和时间限制造成的停顿不会被自动重试。
|
package/src/app/cleanup-facts.js
CHANGED
|
@@ -2,16 +2,16 @@
|
|
|
2
2
|
import { branchOf } from "../domain/worker-branch.js";
|
|
3
3
|
import "./compose.js";
|
|
4
4
|
import { ACTIVE_STATUSES, TERMINAL_STATUSES, runIsOver } from "../domain/status.js";
|
|
5
|
-
import {
|
|
5
|
+
import { gitSucceedsAsync, runGitAsync } from "../infra/git.js";
|
|
6
6
|
import { worktreesDir } from "../infra/paths.js";
|
|
7
|
-
import { isPidAlive } from "../infra/store/tasks.js";
|
|
7
|
+
import { isGroupAlive, isPidAlive } from "../infra/store/tasks.js";
|
|
8
8
|
import { parsePorcelainLine, resolveWorktreeBase, workspaceSetupIgnorePaths, worktreeRef } from "../infra/worktree.js";
|
|
9
9
|
import { lstat, realpath } from "node:fs/promises";
|
|
10
10
|
import { resolve } from "node:path";
|
|
11
11
|
|
|
12
12
|
// Raw output: porcelain status lines start with a significant space, and a
|
|
13
13
|
// quoted path would never match a setup path. Callers trim single values.
|
|
14
|
-
const git = (cwd, args) =>
|
|
14
|
+
const git = (cwd, args) => runGitAsync(cwd, args, { timeout: 15000, noOptionalLocks: true, rawPaths: true, trim: false });
|
|
15
15
|
const lines = (text) => text.split("\n").filter(Boolean);
|
|
16
16
|
|
|
17
17
|
function activeReason(task) {
|
|
@@ -19,6 +19,8 @@ function activeReason(task) {
|
|
|
19
19
|
const settled = runIsOver(task);
|
|
20
20
|
if (!settled && task.pid && isPidAlive(task.pid)) return "worker process is still active";
|
|
21
21
|
if (!settled && task.run_host_pid && isPidAlive(task.run_host_pid)) return "run host process is still active";
|
|
22
|
+
// A lost run can leave a process behind that still writes in the worktree; only a recorded exit rules that out.
|
|
23
|
+
if (task.exit_code == null && isGroupAlive(task.run_host_pid)) return "a process of the worker's run is still active";
|
|
22
24
|
const acceptance = task.acceptance_results;
|
|
23
25
|
if (acceptance?.status === "running" || (acceptance?.supervisor_pid && isPidAlive(acceptance.supervisor_pid))) return "acceptance process is still active";
|
|
24
26
|
return null;
|
|
@@ -34,9 +36,9 @@ async function identityProblem(task) {
|
|
|
34
36
|
const info = await lstat(path);
|
|
35
37
|
if (info.isSymbolicLink()) return "worktree is a symlink";
|
|
36
38
|
if (await realpath(path) !== await realpath(managed)) return "worktree realpath is unexpected";
|
|
37
|
-
const branch = git(path, ["symbolic-ref", "--short", "HEAD"]).trim();
|
|
39
|
+
const branch = (await git(path, ["symbolic-ref", "--short", "HEAD"])).trim();
|
|
38
40
|
if (branch !== branchOf(task)) return "worktree branch ownership is unexpected";
|
|
39
|
-
const registered = git(task.project_root, ["worktree", "list", "--porcelain", "-z"]).split("\0").filter((line) => line.startsWith("worktree "));
|
|
41
|
+
const registered = (await git(task.project_root, ["worktree", "list", "--porcelain", "-z"])).split("\0").filter((line) => line.startsWith("worktree "));
|
|
40
42
|
const own = await realpath(path);
|
|
41
43
|
for (const line of registered) {
|
|
42
44
|
// A registration whose directory someone deleted has no realpath; it is not ours either way.
|
|
@@ -58,20 +60,20 @@ function setupFilter(task) {
|
|
|
58
60
|
function isLanded(task) {
|
|
59
61
|
if (!task.landed_at || !task.landed_head) return false;
|
|
60
62
|
const target = task.landed_branch ? `refs/heads/${task.landed_branch}` : "HEAD";
|
|
61
|
-
return
|
|
63
|
+
return gitSucceedsAsync(task.project_root, ["merge-base", "--is-ancestor", task.landed_head, target]);
|
|
62
64
|
}
|
|
63
65
|
|
|
64
|
-
function worktreeState(task) {
|
|
66
|
+
async function worktreeState(task) {
|
|
65
67
|
const path = resolve(task.worktree_path);
|
|
66
68
|
const keep = setupFilter(task);
|
|
67
|
-
const status = lines(git(path, ["status", "--porcelain", "--untracked-files=all"]));
|
|
69
|
+
const status = lines(await git(path, ["status", "--porcelain", "--untracked-files=all"]));
|
|
68
70
|
const uncommittedPaths = status.map(parsePorcelainLine).filter((entry) => entry && keep(entry));
|
|
69
71
|
// Without the base the worker's own commits cannot be counted, and "nothing
|
|
70
72
|
// to keep" could not be told from "cannot tell".
|
|
71
73
|
const base = resolveWorktreeBase(path, worktreeRef(task));
|
|
72
74
|
if (!base) throw new Error("the commit this worker started from is unknown");
|
|
73
|
-
const unlandedCommits = lines(git(path, ["rev-list", `${base}..HEAD`])).length;
|
|
74
|
-
return { uncommittedPaths, unlandedCommits, head: git(path, ["rev-parse", "HEAD"]).trim() };
|
|
75
|
+
const unlandedCommits = lines(await git(path, ["rev-list", `${base}..HEAD`])).length;
|
|
76
|
+
return { uncommittedPaths, unlandedCommits, head: (await git(path, ["rev-parse", "HEAD"])).trim() };
|
|
75
77
|
}
|
|
76
78
|
|
|
77
79
|
export async function cleanupFacts(task, tasks) {
|
|
@@ -86,8 +88,8 @@ export async function cleanupFacts(task, tasks) {
|
|
|
86
88
|
facts.identity = await identityProblem(task);
|
|
87
89
|
if (facts.identity) return facts;
|
|
88
90
|
try {
|
|
89
|
-
const state = worktreeState(task);
|
|
90
|
-
facts.landed = isLanded(task);
|
|
91
|
+
const state = await worktreeState(task);
|
|
92
|
+
facts.landed = await isLanded(task);
|
|
91
93
|
facts.uncommittedPaths = state.uncommittedPaths;
|
|
92
94
|
facts.uncommitted = state.uncommittedPaths.length;
|
|
93
95
|
facts.unlandedCommits = state.unlandedCommits;
|
package/src/app/cleanup-plan.js
CHANGED
|
@@ -5,8 +5,8 @@
|
|
|
5
5
|
import { branchOf } from "../domain/worker-branch.js";
|
|
6
6
|
import "./compose.js";
|
|
7
7
|
import { cleanupVerdict, holdMsFrom } from "../domain/cleanup-policy.js";
|
|
8
|
-
import {
|
|
9
|
-
import {
|
|
8
|
+
import { gitSucceedsAsync, runGitAsync } from "../infra/git.js";
|
|
9
|
+
import { runFile } from "../infra/process.js";
|
|
10
10
|
import { runIdFor } from "../infra/store/db.js";
|
|
11
11
|
import { appendTaskEvent } from "../infra/store/events.js";
|
|
12
12
|
import { markCleanupPlanItemApplied, updateWorkItemDelivery } from "../infra/store/records.js";
|
|
@@ -22,17 +22,18 @@ export const CLEANUP_PLAN_TTL_MS = 15 * 60 * 1000;
|
|
|
22
22
|
export const CLEANUP_POLICY = "keep_branch_and_evidence_checkpoint_before_removal";
|
|
23
23
|
const RETAINED = ["branch", "task", "events", "jsonl", "artifacts"];
|
|
24
24
|
|
|
25
|
-
const git = (cwd, args, options = {}) =>
|
|
25
|
+
const git = (cwd, args, options = {}) => runGitAsync(cwd, args, { timeout: 15000, noOptionalLocks: true, ...options });
|
|
26
26
|
const holdMs = () => holdMsFrom(process.env.AGENT_SUPERVISOR_CLEANUP_HOLD_DAYS);
|
|
27
27
|
|
|
28
|
+
// The size is a hint for the reader of a plan. Where du is missing or slow
|
|
29
|
+
// the answer is 0, never a failed plan.
|
|
28
30
|
function directoryBytes(path) {
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
}
|
|
31
|
+
return new Promise((resolveSize) => {
|
|
32
|
+
runFile("du", ["-sk", path], { encoding: "utf8", timeout: 30000 }, (error, stdout) => {
|
|
33
|
+
const kib = error ? NaN : Number(stdout.trim().split(/\s+/)[0]);
|
|
34
|
+
resolveSize(Number.isFinite(kib) ? kib * 1024 : 0);
|
|
35
|
+
});
|
|
36
|
+
});
|
|
36
37
|
}
|
|
37
38
|
|
|
38
39
|
// A plan item is only applied to the worktree it was made for: same commit,
|
|
@@ -60,7 +61,7 @@ export async function createCleanupPlan({ taskIds = null, projectRoot = null, no
|
|
|
60
61
|
reasons: result.reasons,
|
|
61
62
|
checkpoint: result.checkpoint,
|
|
62
63
|
fingerprint: result.fingerprint,
|
|
63
|
-
reclaimable_bytes: result.verdict === "safe" ? directoryBytes(task.worktree_path) : 0,
|
|
64
|
+
reclaimable_bytes: result.verdict === "safe" ? await directoryBytes(task.worktree_path) : 0,
|
|
64
65
|
eligible_after: result.eligible_after ?? (result.verdict === "safe" ? new Date(now).toISOString() : null)
|
|
65
66
|
});
|
|
66
67
|
}
|
|
@@ -78,13 +79,13 @@ export async function createCleanupPlan({ taskIds = null, projectRoot = null, no
|
|
|
78
79
|
|
|
79
80
|
// Saves the worker's uncommitted edits as one commit on its branch. Setup
|
|
80
81
|
// links are left out; hooks are skipped because nobody is there to answer them.
|
|
81
|
-
function checkpointUncommitted(task) {
|
|
82
|
+
async function checkpointUncommitted(task) {
|
|
82
83
|
const path = resolve(task.worktree_path);
|
|
83
84
|
const env = { ...process.env, GIT_TERMINAL_PROMPT: "0", GIT_EDITOR: "true", ...identityEnv(path) };
|
|
84
85
|
const exclude = workspaceSetupIgnorePaths(task).map((entry) => `:(exclude)${entry}`);
|
|
85
|
-
git(path, ["add", "-A", "--", ".", ...exclude], { env });
|
|
86
|
-
if (
|
|
87
|
-
git(path, ["commit", "-q", "--no-verify", "-m", `Checkpoint before worktree cleanup (${task.id})`], { env });
|
|
86
|
+
await git(path, ["add", "-A", "--", ".", ...exclude], { env });
|
|
87
|
+
if (await gitSucceedsAsync(path, ["diff", "--cached", "--quiet"])) return null;
|
|
88
|
+
await git(path, ["commit", "-q", "--no-verify", "-m", `Checkpoint before worktree cleanup (${task.id})`], { env });
|
|
88
89
|
return git(path, ["rev-parse", "HEAD"]);
|
|
89
90
|
}
|
|
90
91
|
|
|
@@ -101,12 +102,12 @@ export async function removeSafeWorktree(task, fingerprint) {
|
|
|
101
102
|
if (result.fingerprint !== fingerprint) throw new Error("worktree changed since cleanup plan; create a new plan");
|
|
102
103
|
// The same lock that creating and restoring a worktree takes.
|
|
103
104
|
return await withWorktreeCreationLock(task.project_root, async () => {
|
|
104
|
-
const checkpoint = result.checkpoint ? checkpointUncommitted(task) : null;
|
|
105
|
+
const checkpoint = result.checkpoint ? await checkpointUncommitted(task) : null;
|
|
105
106
|
// What is left now is setup links and ignored build output, neither of
|
|
106
107
|
// which is the worker's work; a plain remove would refuse them.
|
|
107
|
-
git(task.project_root, ["worktree", "remove", "--force", task.worktree_path]);
|
|
108
|
+
await git(task.project_root, ["worktree", "remove", "--force", task.worktree_path]);
|
|
108
109
|
try {
|
|
109
|
-
git(task.project_root, ["worktree", "prune"]);
|
|
110
|
+
await git(task.project_root, ["worktree", "prune"]);
|
|
110
111
|
} catch {
|
|
111
112
|
// pruning is housekeeping; the worktree is already gone
|
|
112
113
|
}
|
package/src/app/resume.js
CHANGED
|
@@ -6,7 +6,7 @@ import { ACTIVE_STATUSES, runIsOver } from "../domain/status.js";
|
|
|
6
6
|
import { buildHandoff } from "../infra/handoff.js";
|
|
7
7
|
import { appendTaskEvent } from "../infra/store/events.js";
|
|
8
8
|
import { getSession } from "../infra/store/sessions.js";
|
|
9
|
-
import { claimTaskRun, getTask, readTasks, releaseTaskRun, upsertTask } from "../infra/store/tasks.js";
|
|
9
|
+
import { claimTaskRun, getTask, isGroupAlive, readTasks, releaseTaskRun, upsertTask } from "../infra/store/tasks.js";
|
|
10
10
|
import { codexRunner } from "../runners/codex/adapter.js";
|
|
11
11
|
import { readNativeGoalState } from "../runners/codex/goal-store.js";
|
|
12
12
|
import { DEFAULT_ACCEPTANCE_TIMEOUT_MS, normalizeAcceptance } from "./acceptance.js";
|
|
@@ -159,7 +159,11 @@ export async function recoverEligibleRuns() {
|
|
|
159
159
|
|| /401|403|unauthori[sz]ed|not logged|permission denied|approval|rate.?limit|429/i.test(task.error ?? "")
|
|
160
160
|
|| /time_limit|quota/.test(`${task.attention_reason ?? ""} ${task.error ?? ""}`)
|
|
161
161
|
// Once the run is over its pids may belong to anyone.
|
|
162
|
-
|| (!runIsOver(task) && (await isPidAlive(task.pid) || await isPidAlive(task.run_host_pid)))
|
|
162
|
+
|| (!runIsOver(task) && (await isPidAlive(task.pid) || await isPidAlive(task.run_host_pid)))
|
|
163
|
+
// Something of the dead run is still alive and holds the session;
|
|
164
|
+
// resuming now fails with "already has an active writer". A later poll retries.
|
|
165
|
+
// A recorded exit is the one thing that rules a survivor out.
|
|
166
|
+
|| (task.exit_code == null && isGroupAlive(task.run_host_pid))) continue;
|
|
163
167
|
const session = task.session_id ? await getSession(task.session_id) : null;
|
|
164
168
|
if (session?.approval_state === "waiting_user") continue;
|
|
165
169
|
try {
|
|
@@ -3,11 +3,12 @@ import { gitBin, runGit } from "../infra/git.js";
|
|
|
3
3
|
import { worktreesDir } from "../infra/paths.js";
|
|
4
4
|
import { runToExit } from "../infra/process.js";
|
|
5
5
|
import { resolveWritableRoot } from "../infra/sandbox-roots.js";
|
|
6
|
+
import { isPidAlive } from "../infra/store/tasks.js";
|
|
6
7
|
import { DEFAULT_ACCEPTANCE_TIMEOUT_MS, runAcceptance } from "./acceptance.js";
|
|
7
8
|
import { WORKTREE_LOCK_TIMEOUT_MS } from "./run-state.js";
|
|
8
9
|
import { createHash } from "node:crypto";
|
|
9
10
|
import { existsSync } from "node:fs";
|
|
10
|
-
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";
|
|
11
12
|
import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
12
13
|
|
|
13
14
|
export function splitLines(buffer, chunk) {
|
|
@@ -155,6 +156,44 @@ function sleep(ms) {
|
|
|
155
156
|
return new Promise((resolvePromise) => setTimeout(resolvePromise, ms));
|
|
156
157
|
}
|
|
157
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
|
+
|
|
158
197
|
export async function withWorktreeCreationLock(cwd, work) {
|
|
159
198
|
const lockName = `create-${createHash("sha256").update(resolve(cwd)).digest("hex").slice(0, 24)}.lock`;
|
|
160
199
|
const lockPath = join(worktreesDir, lockName);
|
|
@@ -166,10 +205,12 @@ export async function withWorktreeCreationLock(cwd, work) {
|
|
|
166
205
|
break;
|
|
167
206
|
} catch (error) {
|
|
168
207
|
if (error.code !== "EEXIST" || Date.now() >= deadline) throw new Error(`worktree creation lock timed out for ${cwd}`, { cause: error });
|
|
169
|
-
await
|
|
208
|
+
if (await lockIsAbandoned(lockPath)) await breakAbandonedLock(lockPath);
|
|
209
|
+
else await sleep(100);
|
|
170
210
|
}
|
|
171
211
|
}
|
|
172
212
|
try {
|
|
213
|
+
await writeFile(join(lockPath, "owner"), String(process.pid));
|
|
173
214
|
return await work();
|
|
174
215
|
} finally {
|
|
175
216
|
await rm(lockPath, { recursive: true, force: true }).catch(() => {});
|
|
@@ -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 ?? "");
|
|
@@ -21,10 +51,12 @@ export function classifyFailure(task) {
|
|
|
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/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
|
|
@@ -37,10 +40,11 @@ export function isGoalNeedingAttention(nativeStatus) {
|
|
|
37
40
|
}
|
|
38
41
|
|
|
39
42
|
// True once nothing of a worker's last run can still be running: its exit
|
|
40
|
-
// code is recorded (the last thing a run host
|
|
43
|
+
// code or the signal that ended it is recorded (the last thing a run host
|
|
44
|
+
// writes), or the row was marked
|
|
41
45
|
// lost (done only after both processes were seen gone). From then on the pids
|
|
42
46
|
// on the row are history. The system hands them to other processes, on
|
|
43
47
|
// Windows within seconds, and a live stranger must not read as a live worker.
|
|
44
48
|
export function runIsOver(task) {
|
|
45
|
-
return task.status === "lost" || (TERMINAL_STATUSES.has(task.status) && task.exit_code != null);
|
|
49
|
+
return task.status === "lost" || (TERMINAL_STATUSES.has(task.status) && (task.exit_code != null || task.signal != null));
|
|
46
50
|
}
|
|
@@ -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;
|
|
@@ -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
|
+
}
|
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
|
+
}
|
|
@@ -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
|
+
}
|