codex-supervisor-mcp 0.10.3 → 0.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -4,22 +4,54 @@ function readyToLand(task) {
4
4
  return task.status === "completed" && task.exit_code === 0 && (!task.acceptance_results || task.acceptance_results.passed === true) && !task.landed_at;
5
5
  }
6
6
 
7
- function readyToClean(task) {
7
+ function readyToClean(task, readyToCleanTaskIds = null) {
8
+ if (readyToCleanTaskIds) return readyToCleanTaskIds.has(task.id);
8
9
  return task.push_verified_at && ["cleanup_eligible"].includes(task.delivery_state);
9
10
  }
10
11
 
11
- export function buildOverviewDelta(tasks, cursor = {}) {
12
+ function attentionReason(task) {
13
+ if (task.attention_reason) return String(task.attention_reason).slice(0, 180);
14
+ if (task.acceptance_results?.passed === false) return "acceptance_failed";
15
+ if (isGoalNeedingAttention(task.goal_status)) return `goal_${task.goal_status}`;
16
+ return null;
17
+ }
18
+
19
+ function nextAction(task, { attention, readyToLand, readyToClean }) {
20
+ if (attention) return "inspect the worker evidence and resolve the recorded blocker";
21
+ if (task.delivery_state === "cleanup_eligible" && !readyToClean) return "rerun cleanup_plan; the previous cleanup proof is no longer current";
22
+ if (readyToLand) return "review the diff and acceptance, then land the worker";
23
+ if (readyToClean) return "review the cleanup plan item, then explicitly apply it";
24
+ if (task.status === "completed" && !task.landed_at) return "review the worker result and decide whether to land it";
25
+ return null;
26
+ }
27
+
28
+ export function buildOverviewDelta(tasks, cursor = {}, { readyToCleanTaskIds = null } = {}) {
12
29
  const active = tasks.filter((task) => ACTIVE_STATUSES.has(task.status));
13
30
  const attention = tasks.filter((task) => isGoalNeedingAttention(task.goal_status) || task.attention_reason || task.acceptance_results?.passed === false);
14
31
  const land = tasks.filter(readyToLand);
15
- const clean = tasks.filter(readyToClean);
32
+ const clean = tasks.filter((task) => readyToClean(task, readyToCleanTaskIds));
16
33
  const nextCursor = {};
17
34
  const changes = [];
18
35
  for (const task of tasks) {
19
- const fingerprint = JSON.stringify([task.run_count ?? 0, task.status, task.exit_code ?? null, task.attention_reason ?? null, task.landed_head ?? null, task.push_verified_at ?? null, task.delivery_state ?? null, task.updated_at]);
36
+ const isAttention = attention.some((item) => item.id === task.id);
37
+ const isReadyToLand = land.some((item) => item.id === task.id);
38
+ const isReadyToClean = clean.some((item) => item.id === task.id);
39
+ const reason = attentionReason(task);
40
+ const fingerprint = JSON.stringify([task.run_count ?? 0, task.status, task.exit_code ?? null, task.attention_reason ?? null, task.landed_head ?? null, task.push_verified_at ?? null, task.delivery_state ?? null, isReadyToClean, reason, task.updated_at]);
20
41
  nextCursor[task.id] = fingerprint;
21
42
  if (cursor[task.id] !== fingerprint) {
22
- changes.push({ id: task.id, title: task.title ?? task.id, status: task.status, delivery_state: task.delivery_state ?? "draft", attention: attention.some((item) => item.id === task.id), ready_to_land: land.some((item) => item.id === task.id), ready_to_clean: clean.some((item) => item.id === task.id), updated_at: task.updated_at });
43
+ changes.push({
44
+ id: task.id,
45
+ title: task.title ?? task.id,
46
+ status: task.status,
47
+ delivery_state: task.delivery_state ?? "draft",
48
+ attention: isAttention,
49
+ attention_reason: reason,
50
+ ready_to_land: isReadyToLand,
51
+ ready_to_clean: isReadyToClean,
52
+ next_action: nextAction(task, { attention: isAttention, readyToLand: isReadyToLand, readyToClean: isReadyToClean }),
53
+ updated_at: task.updated_at
54
+ });
23
55
  }
24
56
  }
25
57
  return {
package/src/paths.js CHANGED
@@ -19,4 +19,6 @@ export const goalsDbPath = join(codexHome, "goals_1.sqlite");
19
19
  export const dataDir = join(supervisorRoot, "data");
20
20
  export const dbPath = join(dataDir, "supervisor.sqlite");
21
21
  export const runsDir = join(dataDir, "runs");
22
+ export const artifactsDir = join(dataDir, "artifacts");
22
23
  export const worktreesDir = join(supervisorRoot, "worktrees");
24
+ export const scratchDir = join(supervisorRoot, "scratch");
package/src/prompt.js CHANGED
@@ -50,7 +50,7 @@ export const REPORT_SECTIONS = ["Result", "Verification", "Not done / risks"];
50
50
  // is stated. A worker is not always an editor: a read-only one can only read,
51
51
  // and one with no ownedPaths lands nothing, so both are told what their shell
52
52
  // may do instead of being told to use apply_patch they cannot use.
53
- export function buildGuardPreamble({ sandbox, ownedPaths = [], allowedCommands = [], forbid = [], networkAccess = false } = {}) {
53
+ export function buildGuardPreamble({ sandbox, ownedPaths = [], allowedCommands = [], forbid = [], networkAccess = false, workspaceKind = null } = {}) {
54
54
  const forbidden = JSON.stringify(forbid);
55
55
  if (sandbox === "read-only") {
56
56
  return [
@@ -61,9 +61,12 @@ export function buildGuardPreamble({ sandbox, ownedPaths = [], allowedCommands =
61
61
  ].join(" ");
62
62
  }
63
63
  if (Array.isArray(ownedPaths) && ownedPaths.length === 0) {
64
+ const location = workspaceKind === "scratch"
65
+ ? "Its execution directory is a supervisor-managed scratch directory, not the user's source directory"
66
+ : "Its worktree is a scratch copy";
64
67
  return [
65
68
  "Runtime supervisor guard: this worker lands nothing: no ownedPaths means nothing it writes is ever merged into the project.",
66
- "Its worktree is a scratch copy, so the shell is unrestricted apart from the red lines; keep notes and downloads inside it.",
69
+ `${location}, so the shell is unrestricted apart from the red lines; keep notes and downloads inside it.`,
67
70
  networkAccess ? "Network is available." : "There is no network in this sandbox; ask for it instead of retrying a failing fetch.",
68
71
  `Forbidden: ${forbidden}.`,
69
72
  "Report what you found and name the files a writer would have to change."
@@ -73,7 +76,7 @@ export function buildGuardPreamble({ sandbox, ownedPaths = [], allowedCommands =
73
76
  // shell as a heredoc; the guard accepts that shape too, so the worker is told
74
77
  // about it instead of stalling on a tool it does not have.
75
78
  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.";
76
- return `Runtime supervisor guard: edits must use apply_patch within ${JSON.stringify(ownedPaths)}. ${shellEdit} Shell verification 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.`;
79
+ return `Runtime supervisor guard: edits must use apply_patch within ${JSON.stringify(ownedPaths)}. ${shellEdit} 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.`;
77
80
  }
78
81
 
79
82
  // The acceptance commands are shown to the worker. Hiding them would not
@@ -0,0 +1,100 @@
1
+ import { execFileSync, spawn } from "node:child_process";
2
+ import { defaultBinDirs, findBinaryPath, resolveCommand, shimMessage } from "./bin-resolver.js";
3
+ import { applyCodexEvent } from "./event-parser.js";
4
+
5
+ const CODEX_NPM_ENTRY = { pkg: "@openai/codex", bin: "bin/codex.js" };
6
+
7
+ export class CodexRunnerAdapter {
8
+ constructor({ env = process.env } = {}) {
9
+ this.env = env;
10
+ this.name = "codex";
11
+ }
12
+
13
+ resolveTarget() {
14
+ const configured = this.env.CODEX_BIN?.trim();
15
+ const located = configured ? configured : (findBinaryPath("codex", { extraDirs: defaultBinDirs() }) ?? "codex");
16
+ const target = resolveCommand(located, { npmEntry: CODEX_NPM_ENTRY });
17
+ if (target.shim) return { error: shimMessage("codex", target.cmd, "CODEX_BIN") };
18
+ return { cmd: target.cmd, prefixArgs: target.prefixArgs };
19
+ }
20
+
21
+ capabilityPreflight(target = this.resolveTarget()) {
22
+ if (target.error) return { ok: false, error: target.error };
23
+ try {
24
+ const help = execFileSync(target.cmd, [...target.prefixArgs, "exec", "--help"], {
25
+ encoding: "utf8",
26
+ timeout: 15000,
27
+ windowsHide: true,
28
+ stdio: ["ignore", "pipe", "pipe"]
29
+ });
30
+ if (!help.includes("--dangerously-bypass-hook-trust") || !help.includes("--output-schema")) {
31
+ return { ok: false, error: "Codex CLI lacks required per-run hooks/output-schema; install Codex 0.162 or newer before dispatch" };
32
+ }
33
+ return { ok: true, target };
34
+ } catch (error) {
35
+ return { ok: false, error: error.code === "ENOENT"
36
+ ? `failed to spawn ${target.cmd} for Codex capability preflight: ${error.message}`
37
+ : `Codex capability preflight failed: ${error.message}` };
38
+ }
39
+ }
40
+
41
+ startArgs({ cwd, sandbox, model, reasoningEffort, skipGitRepoCheck }) {
42
+ const args = ["exec", "--json", "--cd", cwd, "--sandbox", sandbox];
43
+ if (skipGitRepoCheck) args.push("--skip-git-repo-check");
44
+ if (model) args.push("--model", model);
45
+ args.push("-c", `model_reasoning_effort="${reasoningEffort}"`, "-");
46
+ return args;
47
+ }
48
+
49
+ resumeArgs(task) {
50
+ const args = ["exec", "resume", "--json", "-c", `sandbox_mode="${task.sandbox}"`];
51
+ if (task.model) args.push("--model", task.model);
52
+ args.push("-c", `model_reasoning_effort="${task.reasoning_effort ?? "high"}"`);
53
+ if (task.skip_git_repo_check) args.push("--skip-git-repo-check");
54
+ args.push(task.thread_id, "-");
55
+ return args;
56
+ }
57
+
58
+ forkSideArgs({ forkThreadId, workerThreadId, model }) {
59
+ const args = forkThreadId
60
+ ? ["exec", "resume", "--json", "--skip-git-repo-check", "-c", 'sandbox_mode="read-only"']
61
+ : ["exec", "fork", "--json", "--skip-git-repo-check", "-c", 'sandbox_mode="read-only"'];
62
+ if (model) args.push("-m", model);
63
+ args.push(forkThreadId ?? workerThreadId, "-");
64
+ return args;
65
+ }
66
+
67
+ start(target, args, options) {
68
+ return spawn(target.cmd, [...target.prefixArgs, ...args], options);
69
+ }
70
+
71
+ parseEvent(task, event) {
72
+ return applyCodexEvent(task, event);
73
+ }
74
+
75
+ cancelChild(child) {
76
+ if (process.platform === "win32" && child.pid) {
77
+ try {
78
+ execFileSync("taskkill", ["/PID", String(child.pid), "/T", "/F"], { stdio: "ignore", timeout: 5000, windowsHide: true });
79
+ return;
80
+ } catch {
81
+ // fall through to the process handle
82
+ }
83
+ }
84
+ child.kill("SIGTERM");
85
+ }
86
+
87
+ cancelPid(pid) {
88
+ if (process.platform === "win32") {
89
+ execFileSync("taskkill", ["/PID", String(pid), "/T", "/F"], { stdio: "ignore", timeout: 5000, windowsHide: true });
90
+ return;
91
+ }
92
+ process.kill(pid, "SIGTERM");
93
+ }
94
+
95
+ ownsPid(pid, describeProcess) {
96
+ return describeProcess(pid).includes("codex");
97
+ }
98
+ }
99
+
100
+ export const codexRunner = new CodexRunnerAdapter();
@@ -1,6 +1,10 @@
1
1
  import { lstatSync, realpathSync } from "node:fs";
2
2
  import { homedir } from "node:os";
3
- import { dirname, isAbsolute, join, resolve } from "node:path";
3
+ import { dirname, isAbsolute, posix, resolve, win32 } from "node:path";
4
+
5
+ function pathJoin(platform, ...parts) {
6
+ return (platform === "win32" ? win32 : posix).join(...parts);
7
+ }
4
8
 
5
9
  // Codex refuses a writable root that contains a symlink component: the worker
6
10
  // does not merely lose that directory, every command in it fails with
@@ -72,12 +76,24 @@ export const TOOLCHAIN_CACHE_DIRS = [
72
76
  export const EXPLICIT_ONLY_DIRS = [".ssh", ".gnupg", ".config", ".aws", ".docker", ".kube", ".netrc", ".git-credentials", "Library/Keychains"];
73
77
  function osCacheCandidates({ env, platform, home }) {
74
78
  if (platform === "win32") return [env.LOCALAPPDATA];
75
- return [env.XDG_CACHE_HOME, platform === "darwin" ? join(home, "Library", "Caches") : null, join(home, ".cache")];
79
+ return [env.XDG_CACHE_HOME, platform === "darwin" ? pathJoin(platform, home, "Library", "Caches") : null, pathJoin(platform, home, ".cache")];
80
+ }
81
+
82
+ function goBuildCacheCandidate({ env, platform, home }) {
83
+ const configured = env.GOCACHE?.trim();
84
+ if (configured && configured !== "off") return configured;
85
+ if (platform === "win32") return env.LOCALAPPDATA ? win32.join(env.LOCALAPPDATA, "go-build") : null;
86
+ if (platform === "darwin") return pathJoin(platform, home, "Library", "Caches", "go-build");
87
+ return pathJoin(platform, env.XDG_CACHE_HOME?.trim() || pathJoin(platform, home, ".cache"), "go-build");
76
88
  }
77
89
 
78
90
  export function cacheRoots({ env = process.env, platform = process.platform, home = homedir(), resolveRoot = resolveWritableRoot, includeToolchain = true } = {}) {
79
91
  if (/^(1|true|yes)$/i.test((env.SUPERVISOR_NO_AUTO_CACHE_ROOTS ?? "").trim())) return [];
80
- const candidates = [...osCacheCandidates({ env, platform, home }), ...(includeToolchain ? TOOLCHAIN_CACHE_DIRS.map((dir) => join(home, dir)) : [])];
92
+ const candidates = [
93
+ ...osCacheCandidates({ env, platform, home }),
94
+ goBuildCacheCandidate({ env, platform, home }),
95
+ ...(includeToolchain ? TOOLCHAIN_CACHE_DIRS.map((dir) => pathJoin(platform, home, dir)) : [])
96
+ ];
81
97
  const roots = [];
82
98
  for (const candidate of candidates) {
83
99
  if (!candidate?.trim()) continue;
package/src/side-chat.js CHANGED
@@ -24,8 +24,8 @@
24
24
  // session ended ................... fork deleted, history cleared
25
25
  import { execFileSync, spawn } from "node:child_process";
26
26
  import { randomUUID } from "node:crypto";
27
- import { defaultBinDirs, findBinaryPath, resolveCommand, shimMessage } from "./bin-resolver.js";
28
27
  import { codexConfigText, disableMcpServerArgs } from "./mcp-config.js";
28
+ import { codexRunner } from "./runner-adapter.js";
29
29
  import {
30
30
  closeSideSession,
31
31
  getSideSession,
@@ -37,7 +37,6 @@ import {
37
37
  updateSideTurn
38
38
  } from "./task-store.js";
39
39
 
40
- const CODEX_NPM_ENTRY = { pkg: "@openai/codex", bin: "bin/codex.js" };
41
40
  const TURN_TIMEOUT_MS = 10 * 60 * 1000;
42
41
 
43
42
  // What a side question is, said to the fork every time. Without it the fork
@@ -104,29 +103,6 @@ async function sweepOnce() {
104
103
  await interruptRunningSideTurns();
105
104
  }
106
105
 
107
- function codexTarget() {
108
- const configured = process.env.CODEX_BIN?.trim();
109
- const located = configured ? configured : (findBinaryPath("codex", { extraDirs: defaultBinDirs() }) ?? "codex");
110
- const target = resolveCommand(located, { npmEntry: CODEX_NPM_ENTRY });
111
- if (target.shim) return { error: shimMessage("codex", target.cmd, "CODEX_BIN") };
112
- return { cmd: target.cmd, prefixArgs: target.prefixArgs };
113
- }
114
-
115
- // Stop a side turn and everything under it. On Windows the direct child is
116
- // the JS wrapper around the native Codex binary; killing the wrapper alone
117
- // leaves the real CLI running, so the whole tree goes through taskkill.
118
- function killTree(child) {
119
- if (process.platform === "win32" && child.pid) {
120
- try {
121
- execFileSync("taskkill", ["/PID", String(child.pid), "/T", "/F"], { stdio: "ignore", timeout: 5000, windowsHide: true });
122
- return;
123
- } catch {
124
- // fall back to the handle below
125
- }
126
- }
127
- child.kill("SIGTERM");
128
- }
129
-
130
106
  function clip(text, max = OUTPUT_CLIP) {
131
107
  if (typeof text !== "string") return text ?? null;
132
108
  return text.length <= max ? text : `${text.slice(0, max)}\n…(${text.length - max} more characters)`;
@@ -338,20 +314,16 @@ export async function runSideTurn({ task, text, res = null, fresh = false }) {
338
314
  await sweepOnce();
339
315
  if (!task.thread_id) throw Object.assign(new Error("this worker recorded no thread_id, so there is no Codex thread to fork"), { code: "no_thread" });
340
316
  if (running.has(task.id)) throw Object.assign(new Error("a side turn is already running for this worker"), { code: "busy" });
341
- const target = codexTarget();
317
+ const target = codexRunner.resolveTarget();
342
318
  if (target.error) throw Object.assign(new Error(target.error), { code: "codex_missing" });
343
319
 
344
320
  const { session, refreshed } = await prepareSideSession(task, { fresh });
345
321
 
346
- const args = session.fork_thread_id
347
- ? ["exec", "resume", "--json", "--skip-git-repo-check", "-c", 'sandbox_mode="read-only"']
348
- : ["exec", "fork", "--json", "--skip-git-repo-check", "-c", 'sandbox_mode="read-only"'];
349
- args.push(...sideTurnConfigArgs(codexConfigText()));
350
- if (task.model) args.push("-m", task.model);
351
- args.push(session.fork_thread_id ?? task.thread_id, "-");
322
+ const args = codexRunner.forkSideArgs({ forkThreadId: session.fork_thread_id, workerThreadId: task.thread_id, model: task.model });
323
+ args.splice(-2, 0, ...sideTurnConfigArgs(codexConfigText()));
352
324
 
353
325
  const cwd = task.worktree_path || task.project_root || process.cwd();
354
- const child = spawn(target.cmd, [...target.prefixArgs, ...args], {
326
+ const child = codexRunner.start(target, args, {
355
327
  cwd,
356
328
  stdio: ["pipe", "pipe", "pipe"],
357
329
  env: { ...process.env, NO_COLOR: "1" },
@@ -390,11 +362,11 @@ export async function runSideTurn({ task, text, res = null, fresh = false }) {
390
362
  let stoppedBy = null;
391
363
  const timer = setTimeout(() => {
392
364
  stoppedBy = "timeout";
393
- killTree(child);
365
+ codexRunner.cancelChild(child);
394
366
  }, TURN_TIMEOUT_MS);
395
367
  live.stop = (reason) => {
396
368
  stoppedBy = reason;
397
- killTree(child);
369
+ codexRunner.cancelChild(child);
398
370
  };
399
371
 
400
372
  child.stdout.setEncoding("utf8");
@@ -546,12 +518,12 @@ export async function endSideSession(taskId) {
546
518
  if (!row) return { ended: false };
547
519
  let deleted = false;
548
520
  if (row.fork_thread_id) {
549
- const target = codexTarget();
521
+ const target = codexRunner.resolveTarget();
550
522
  if (!target.error) {
551
523
  deleted = await new Promise((resolve) => {
552
524
  // --force: without a terminal codex asks for confirmation and exits.
553
- const child = spawn(target.cmd, [...target.prefixArgs, "delete", "--force", row.fork_thread_id], { stdio: "ignore", windowsHide: true, env: { ...process.env, NO_COLOR: "1" } });
554
- const t = setTimeout(() => { killTree(child); resolve(false); }, 15000);
525
+ const child = codexRunner.start(target, ["delete", "--force", row.fork_thread_id], { stdio: "ignore", windowsHide: true, env: { ...process.env, NO_COLOR: "1" } });
526
+ const t = setTimeout(() => { codexRunner.cancelChild(child); resolve(false); }, 15000);
555
527
  child.on("exit", (code) => { clearTimeout(t); resolve(code === 0); });
556
528
  child.on("error", () => { clearTimeout(t); resolve(false); });
557
529
  });