codex-supervisor-mcp 0.6.1 → 0.7.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.
@@ -0,0 +1,144 @@
1
+ // Keeps a global npm install current without anyone typing `npm i -g`.
2
+ //
3
+ // The server never blocks on this. When the update check says a newer
4
+ // version is published, a detached worker process (auto-update-worker.js)
5
+ // runs `npm install -g codex-supervisor-mcp@<that version>` and writes what
6
+ // happened to data/auto-update.json. The running server keeps its own
7
+ // already-loaded code; the next MCP session starts on the new files. This is
8
+ // the same shape as Claude Code's and opencode's updaters: check in the
9
+ // background, install in the background, take effect on the next launch.
10
+ //
11
+ // It only ever touches a copy that npm installed globally. A git checkout,
12
+ // an `npm link`, a project-local dependency and an npx cache copy are left
13
+ // alone, and the worker double-checks against `npm root -g` before writing.
14
+ import { spawn } from "node:child_process";
15
+ import { closeSync, openSync } from "node:fs";
16
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
17
+ import { dirname, join } from "node:path";
18
+ import { fileURLToPath } from "node:url";
19
+ import { dataDir } from "./paths.js";
20
+
21
+ const PACKAGE_NAME = "codex-supervisor-mcp";
22
+ export const statePath = join(dataDir, "auto-update.json");
23
+ export const lockPath = join(dataDir, "auto-update.lock");
24
+ export const logPath = join(dataDir, "auto-update.log");
25
+ const workerEntry = join(dirname(fileURLToPath(import.meta.url)), "auto-update-worker.js");
26
+
27
+ export function autoUpdateDisabled(env = process.env) {
28
+ return /^(1|true|yes)$/i.test(env.CODEX_SUPERVISOR_NO_AUTO_UPDATE?.trim() ?? "");
29
+ }
30
+
31
+ // Pure. The reason not to install, or null when an install should start.
32
+ export function autoUpdateBlocker(update, env = process.env) {
33
+ if (!update) return "no update check result yet";
34
+ if (autoUpdateDisabled(env)) return "disabled by CODEX_SUPERVISOR_NO_AUTO_UPDATE";
35
+ if (env.CI) return "CI environment";
36
+ if (update.disabled) return "update check is disabled";
37
+ if (!update.update_available) return "already current";
38
+ if (!update.latest?.version) return "registry gave no version";
39
+ const source = update.installed?.source;
40
+ if (source === "npx") return "started through npx, which fetches the latest version itself";
41
+ if (source !== "npm") return `installed from ${source ?? "an unknown source"}, not a global npm install`;
42
+ return null;
43
+ }
44
+
45
+ export async function readAutoUpdateState() {
46
+ try {
47
+ return JSON.parse(await readFile(statePath, "utf8"));
48
+ } catch {
49
+ return null;
50
+ }
51
+ }
52
+
53
+ function processAlive(pid) {
54
+ if (!pid) return false;
55
+ try {
56
+ process.kill(pid, 0);
57
+ return true;
58
+ } catch (error) {
59
+ return error.code === "EPERM";
60
+ }
61
+ }
62
+
63
+ // Launches the detached worker. Its stdio goes to a log file, not to the MCP
64
+ // transport: anything the updater prints on stdout would corrupt the protocol
65
+ // stream.
66
+ async function launchWorker({ version, packageRoot, registry }) {
67
+ await mkdir(dataDir, { recursive: true });
68
+ const args = [workerEntry, "--version", version, "--package-root", packageRoot];
69
+ if (registry) args.push("--registry", registry);
70
+ const log = openSync(logPath, "a");
71
+ try {
72
+ const child = spawn(process.execPath, args, {
73
+ detached: true,
74
+ stdio: ["ignore", log, log],
75
+ env: { ...process.env, CODEX_SUPERVISOR_NO_AUTO_UPDATE: "1" },
76
+ windowsHide: true
77
+ });
78
+ child.unref();
79
+ return child.pid;
80
+ } finally {
81
+ closeSync(log);
82
+ }
83
+ }
84
+
85
+ // Decides and, at most once per published version, starts the install.
86
+ // Returns the auto-update record to show in tool results:
87
+ // { state: "started" | "running" | "done" | "failed" | "skipped", version, reason?, ... }
88
+ //
89
+ // Calls are serialised: the startup check and a forced check_for_update can
90
+ // finish in the same tick, and the second must see the record the first
91
+ // wrote rather than launch a worker of its own.
92
+ let queue = Promise.resolve();
93
+ export function maybeAutoUpdate(update, options = {}) {
94
+ const next = queue.then(() => decide(update, options));
95
+ queue = next.catch(() => {});
96
+ return next;
97
+ }
98
+
99
+ async function decide(update, { env = process.env, launch = launchWorker } = {}) {
100
+ const blocker = autoUpdateBlocker(update, env);
101
+ if (blocker) return { state: "skipped", version: update?.latest?.version ?? null, reason: blocker };
102
+
103
+ const version = update.latest.version;
104
+ const prior = await readAutoUpdateState();
105
+ const inFlight = prior && ["started", "running"].includes(prior.state) && processAlive(prior.pid);
106
+ if (prior && prior.version === version) {
107
+ // One attempt per published version: a finished record stands, a live
108
+ // worker is left alone, a worker that died without a verdict gets one retry
109
+ // per check.
110
+ if (inFlight || ["done", "failed", "skipped"].includes(prior.state)) return prior;
111
+ } else if (inFlight) {
112
+ return { ...prior, reason: `an updater for ${prior.version} is still running` };
113
+ }
114
+
115
+ let record;
116
+ try {
117
+ const pid = await launch({
118
+ version,
119
+ packageRoot: update.installed.path,
120
+ registry: env.CODEX_SUPERVISOR_REGISTRY?.trim() || null
121
+ });
122
+ record = { state: "started", version, pid, started_at: new Date().toISOString() };
123
+ } catch (error) {
124
+ record = { state: "failed", version, reason: `could not start the updater: ${error.message}` };
125
+ }
126
+ // Recorded by the server too, so ten servers starting together do not each
127
+ // launch a worker (the worker's lock is the second line of defence).
128
+ try {
129
+ await mkdir(dataDir, { recursive: true });
130
+ await writeFile(statePath, JSON.stringify({ ...record, updated_at: record.started_at ?? new Date().toISOString() }, null, 2));
131
+ } catch {
132
+ // the worker rewrites it anyway
133
+ }
134
+ return record;
135
+ }
136
+
137
+ // What a tool result says about it. Null when there is nothing worth a line.
138
+ export function autoUpdateSummary(record) {
139
+ if (!record || record.state === "skipped") return null;
140
+ const base = { state: record.state, version: record.version };
141
+ if (record.reason) base.reason = record.reason;
142
+ if (record.state === "done") base.installed_path = record.installed_path ?? null;
143
+ return base;
144
+ }
@@ -171,12 +171,15 @@ export function applyCodexEvent(task, event) {
171
171
  next.current_action = "Failed";
172
172
  next.current_command = null;
173
173
  next.completed_at = now;
174
- next.error = event.error ?? event.message ?? event.msg?.error ?? "Codex turn failed";
174
+ // Codex writes the error as an object ({ message }). Stored as-is it
175
+ // cannot be bound to the TEXT column, the whole row update is dropped,
176
+ // and a worker that failed cleanly is later reported as lost.
177
+ next.error = errorText(event.error) ?? errorText(event.message) ?? errorText(event.msg?.error) ?? "Codex turn failed";
175
178
  return next;
176
179
  }
177
180
 
178
181
  if (eventType === "error") {
179
- return appendNotice(next, event.message ?? event.error ?? "Codex reported an error event");
182
+ return appendNotice(next, errorText(event.message) ?? errorText(event.error) ?? "Codex reported an error event");
180
183
  }
181
184
 
182
185
  if (GOAL_EVENT_TYPES.has(eventType)) {
@@ -185,3 +188,19 @@ export function applyCodexEvent(task, event) {
185
188
 
186
189
  return next;
187
190
  }
191
+
192
+ // An error field as a string, whatever shape Codex gave it.
193
+ function errorText(value) {
194
+ if (value === null || value === undefined) return null;
195
+ if (typeof value === "string") return value || null;
196
+ if (typeof value === "object") {
197
+ const inner = value.message ?? value.error ?? value.msg ?? null;
198
+ if (typeof inner === "string" && inner) return inner;
199
+ try {
200
+ return JSON.stringify(value);
201
+ } catch {
202
+ return String(value);
203
+ }
204
+ }
205
+ return String(value);
206
+ }
package/src/landing.js ADDED
@@ -0,0 +1,117 @@
1
+ // Landing a worker's commits where they were dispatched from.
2
+ //
3
+ // A worker commits on codex/<taskId> inside its own worktree. Getting that
4
+ // work onto the branch the main thread integrates on used to be the main
5
+ // thread's job, one cherry-pick per step, dozens of times per batch. This
6
+ // does the same thing with the same guard rails a careful person would use:
7
+ // the target must be clean, it is never switched to another branch, and a
8
+ // conflict leaves nothing half-applied.
9
+ import { execFileSync } from "node:child_process";
10
+ import { existsSync } from "node:fs";
11
+ import { parsePorcelainLine, resolveWorktreeBase, worktreeRef } from "./worktree.js";
12
+
13
+ const defaultGitBin = process.env.GIT_BIN?.trim() || "git";
14
+
15
+ function git(cwd, args, { timeout = 60000 } = {}) {
16
+ return execFileSync(defaultGitBin, ["-C", cwd, "-c", "core.quotePath=false", ...args], {
17
+ encoding: "utf8",
18
+ timeout,
19
+ stdio: ["ignore", "pipe", "pipe"],
20
+ env: { ...process.env, GIT_TERMINAL_PROMPT: "0", GIT_EDITOR: "true" }
21
+ });
22
+ }
23
+
24
+ function lines(output) {
25
+ return output.split("\n").map((line) => line.trim()).filter(Boolean);
26
+ }
27
+
28
+ // Porcelain lines carry their status in the first two columns, so they must
29
+ // not be trimmed before parsing.
30
+ function porcelainPaths(output) {
31
+ return output.split("\n").filter((line) => line.length > 3).map(parsePorcelainLine).filter(Boolean);
32
+ }
33
+
34
+ function currentBranch(cwd) {
35
+ const name = git(cwd, ["symbolic-ref", "--short", "-q", "HEAD"]).trim();
36
+ return name || null;
37
+ }
38
+
39
+ // Lands task's commits onto the current branch of its dispatch directory
40
+ // (task.project_root: the row's cwd is the worktree the worker ran in).
41
+ // `onto`, when given, must name that branch: it is a guard, not a switch.
42
+ // Returns { landed: [{ sha, original, subject }], onto, head } on success;
43
+ // otherwise { error, reason, ... } with nothing changed in the target.
44
+ export function landWorker(task, { onto = null } = {}) {
45
+ const target = task.project_root;
46
+ if (!task.worktree_path || !existsSync(task.worktree_path)) {
47
+ return { error: "no_worktree", reason: "this worker has no worktree (it ran in place), so there is nothing on a codex/ branch to land" };
48
+ }
49
+ if (!target || !existsSync(target)) {
50
+ return { error: "no_target", reason: `the directory the worker was dispatched from (${target}) no longer exists` };
51
+ }
52
+ let branch;
53
+ try {
54
+ branch = currentBranch(target);
55
+ } catch (error) {
56
+ return { error: "no_target", reason: `${target} is not a git checkout: ${error.message.split("\n")[0]}` };
57
+ }
58
+ if (!branch) return { error: "detached_target", reason: `${target} has a detached HEAD; check out the branch you integrate on first` };
59
+ if (onto && onto !== branch) {
60
+ return { error: "wrong_branch", reason: `${target} is on ${branch}, not ${onto}; this tool never switches branches for you`, current_branch: branch };
61
+ }
62
+ const dirty = porcelainPaths(git(target, ["status", "--porcelain", "--untracked-files=no"]));
63
+ if (dirty.length > 0) {
64
+ return { error: "dirty_target", reason: `${target} has uncommitted changes; commit or stash them before landing`, dirty_files: dirty };
65
+ }
66
+
67
+ const base = resolveWorktreeBase(task.worktree_path, worktreeRef(task));
68
+ if (!base) return { error: "no_base_commit", reason: "the commit this worker started from is unknown, so its commits cannot be told apart" };
69
+ let commits;
70
+ try {
71
+ commits = lines(git(task.worktree_path, ["rev-list", "--reverse", `${base}..HEAD`]));
72
+ } catch (error) {
73
+ return { error: "no_base_commit", reason: `the base ${base} no longer resolves in the worktree: ${error.message.split("\n")[0]}` };
74
+ }
75
+ const uncommitted = porcelainPaths(git(task.worktree_path, ["--no-optional-locks", "status", "--porcelain"]));
76
+ if (commits.length === 0) {
77
+ return { error: "nothing_to_land", reason: "the worker made no commits on its branch; uncommitted edits are not landed", uncommitted, base_commit: base };
78
+ }
79
+
80
+ const before = git(target, ["rev-parse", "HEAD"]).trim();
81
+ try {
82
+ git(target, ["cherry-pick", "--allow-empty-message", ...commits], { timeout: 10 * 60 * 1000 });
83
+ } catch (error) {
84
+ let conflicts = [];
85
+ try {
86
+ conflicts = lines(git(target, ["diff", "--name-only", "--diff-filter=U"]));
87
+ } catch {
88
+ // no conflict list, still abort
89
+ }
90
+ try {
91
+ git(target, ["cherry-pick", "--abort"]);
92
+ } catch {
93
+ // nothing in progress to abort
94
+ }
95
+ const tail = `${error.stdout ?? ""}${error.stderr ?? ""}`.trim().split("\n").slice(-4).join("\n");
96
+ return {
97
+ error: "conflict",
98
+ reason: conflicts.length > 0 ? `cherry-pick stopped on a conflict; ${target} was reset to where it was` : `cherry-pick failed; ${target} was reset to where it was`,
99
+ conflicts,
100
+ git: tail,
101
+ base_commit: base,
102
+ commits,
103
+ uncommitted
104
+ };
105
+ }
106
+ const landed = lines(git(target, ["rev-list", "--reverse", `${before}..HEAD`]));
107
+ const subjects = lines(git(target, ["log", "--format=%H%x09%s", `${before}..HEAD`]));
108
+ const subjectOf = new Map(subjects.map((line) => line.split("\t")).map(([sha, subject]) => [sha, subject]));
109
+ return {
110
+ onto: branch,
111
+ target,
112
+ base_commit: base,
113
+ head: landed.at(-1) ?? before,
114
+ landed: landed.map((sha, index) => ({ sha, original: commits[index] ?? null, subject: subjectOf.get(sha) ?? null })),
115
+ uncommitted
116
+ };
117
+ }
package/src/mcp-server.js CHANGED
@@ -26,10 +26,14 @@ import {
26
26
  upsertTask
27
27
  } from "./task-store.js";
28
28
  import { readNativeGoal } from "./goal-store.js";
29
- import { readTaskChanges } from "./worktree.js";
29
+ import { readTaskChanges, readWorktreeDiff, worktreeRef } from "./worktree.js";
30
30
  import { ACTIVE_STATUSES, TERMINAL_STATUSES, TASK_STATUSES, isGoalNeedingAttention } from "./status.js";
31
31
  import { approxTokenCount, truncateEventStrings, truncateMiddleChars } from "./truncate.js";
32
32
  import { checkForUpdate, updateNotice } from "./update-check.js";
33
+ import { syncSkills } from "./skill-sync.js";
34
+ import { maybeAutoUpdate } from "./auto-update.js";
35
+ import { askWorker, endSideSession, latestSideTurn } from "./side-chat.js";
36
+ import { landWorker } from "./landing.js";
33
37
 
34
38
  // Report the real package version. This string had drifted to 0.4.0 while the
35
39
  // package shipped 0.5.x, so the handshake named a version nobody was running.
@@ -48,10 +52,15 @@ const server = new McpServer({
48
52
  // which are the calls every orchestrating session makes.
49
53
  const UPDATE_RECHECK_MS = 6 * 60 * 60 * 1000;
50
54
  let updateState = null;
55
+ // The last word from auto-update.js: null until a check found a newer
56
+ // version, then started | running | done | failed | skipped.
57
+ let autoUpdateState = null;
51
58
  async function refreshUpdateState({ force = false } = {}) {
52
59
  try {
53
60
  updateState = await checkForUpdate({ force });
54
- if (updateState.notice) process.stderr.write(`[codex-supervisor] ${updateState.notice}\n`);
61
+ autoUpdateState = await maybeAutoUpdate(updateState);
62
+ const notice = updateNotice(updateState, autoUpdateState)?.notice;
63
+ if (notice) process.stderr.write(`[codex-supervisor] ${notice}\n`);
55
64
  } catch (error) {
56
65
  process.stderr.write(`[codex-supervisor] update check failed: ${error.message}\n`);
57
66
  }
@@ -60,9 +69,32 @@ async function refreshUpdateState({ force = false } = {}) {
60
69
  refreshUpdateState();
61
70
  setInterval(() => refreshUpdateState({ force: true }), UPDATE_RECHECK_MS).unref();
62
71
 
72
+ // The skill describes this tool surface, so it moves with the server: a
73
+ // server fetched by `npx -y codex-supervisor-mcp@latest` never ran postinstall,
74
+ // and a global install only synced the skill on the day it was installed.
75
+ // Runs in the background; a client that cannot write its skill directory
76
+ // only costs a line on stderr.
77
+ if (!process.env.CODEX_SUPERVISOR_SKIP_SKILL_SYNC) {
78
+ syncSkills()
79
+ .then((result) => {
80
+ const changed = [...result.installed, ...result.updated];
81
+ if (changed.length > 0) {
82
+ process.stderr.write(
83
+ `[codex-supervisor] skill synced for ${changed.join(", ")}; a session that already loaded the skill keeps the old text until it loads it again\n`
84
+ );
85
+ }
86
+ for (const failure of result.failed) {
87
+ process.stderr.write(`[codex-supervisor] skill sync failed: ${failure}\n`);
88
+ }
89
+ })
90
+ .catch((error) => {
91
+ process.stderr.write(`[codex-supervisor] skill sync failed: ${error.message}\n`);
92
+ });
93
+ }
94
+
63
95
  // The short form for tool results: null when the install is current.
64
96
  function updateField() {
65
- return updateNotice(updateState);
97
+ return updateNotice(updateState, autoUpdateState);
66
98
  }
67
99
 
68
100
  // Spread into a result: adds `update` only when there is something to say.
@@ -536,7 +568,11 @@ server.registerTool(
536
568
  // unreadable. The default bounds each string; pass a bigger number when
537
569
  // you actually want the raw text.
538
570
  eventMaxChars: z.number().int().min(0).max(1000000).default(800),
539
- eventKinds: z.array(z.string().min(1)).optional()
571
+ eventKinds: z.array(z.string().min(1)).optional(),
572
+ // The smallest useful answer: one line per worker, for a caller that
573
+ // only wants to know who is done. Everything else comes from
574
+ // get_worker_result / get_worker_diff afterwards.
575
+ compact: z.boolean().default(false)
540
576
  }
541
577
  },
542
578
  async ({
@@ -548,7 +584,8 @@ server.registerTool(
548
584
  includeEvents,
549
585
  eventLimit,
550
586
  eventMaxChars,
551
- eventKinds
587
+ eventKinds,
588
+ compact
552
589
  }) => {
553
590
  const startedAt = Date.now();
554
591
  const effectiveTimeoutMs = timeoutMs ?? timeoutMinutes * 60 * 1000;
@@ -602,7 +639,17 @@ server.registerTool(
602
639
  cancelled_count: tasks.filter((task) => task.status === "cancelled").length,
603
640
  lost_count: tasks.filter((task) => task.status === "lost").length,
604
641
  active_count: tasks.filter((task) => ACTIVE_STATUSES.has(task.status)).length,
605
- workers: summaries
642
+ workers: compact
643
+ ? tasks.map((task) => ({
644
+ id: task.id,
645
+ title: clip(task.title, 60),
646
+ status: task.status,
647
+ phase: task.phase ?? null,
648
+ exit_code: task.exit_code ?? null,
649
+ changed_file_count: readTaskChanges(task).length,
650
+ updated_at: task.updated_at ?? null
651
+ }))
652
+ : summaries
606
653
  }));
607
654
  }
608
655
  );
@@ -643,7 +690,8 @@ server.registerTool(
643
690
  },
644
691
  async ({ force }) => {
645
692
  const result = await refreshUpdateState({ force });
646
- return textResult(result ?? { error: "update_check_failed" });
693
+ if (!result) return textResult({ error: "update_check_failed" });
694
+ return textResult({ ...result, auto_update: autoUpdateState });
647
695
  }
648
696
  );
649
697
 
@@ -826,6 +874,97 @@ server.registerTool(
826
874
  }
827
875
  );
828
876
 
877
+ server.registerTool(
878
+ "get_worker_diff",
879
+ {
880
+ title: "Get worker diff",
881
+ description:
882
+ "The worker's actual changes as patches: everything between the commit its worktree started from and its working tree, committed or not, plus untracked files. This is the ground truth to check a worker's report against. maxChars bounds the whole answer: files past the budget come back listed but without a patch, so the file list is always complete. paths narrows the diff to those files or directories.",
883
+ inputSchema: {
884
+ task_id: z.string().min(1),
885
+ maxChars: z.number().int().min(0).max(1000000).default(60000),
886
+ paths: z.array(z.string().min(1)).optional()
887
+ }
888
+ },
889
+ async ({ task_id, maxChars, paths }) => {
890
+ const task = await getTask(task_id);
891
+ if (!task) return textResult({ error: "task_not_found", task_id });
892
+ if (!task.worktree_path) {
893
+ return textResult({ error: "no_worktree", task_id, reason: "this worker ran in place (its cwd is not a git repository or the worktree could not be created), so there is no isolated diff to read; look at changed_files from get_worker_result instead" });
894
+ }
895
+ const diff = readWorktreeDiff(task.worktree_path, worktreeRef(task), { maxChars, paths: paths ?? [] });
896
+ return textResult({
897
+ task_id,
898
+ title: task.title,
899
+ status: task.status,
900
+ worktree_path: task.worktree_path,
901
+ branch: `codex/${task.id}`,
902
+ ...diff
903
+ });
904
+ }
905
+ );
906
+
907
+ server.registerTool(
908
+ "ask_codex_worker",
909
+ {
910
+ title: "Ask a worker on the side",
911
+ description:
912
+ "Ask a finished or running worker a question without touching its thread: the worker's Codex thread is forked once into a read-only side session (like Codex's own /btw), the question is asked there, and later questions resume that fork. The fork carries everything the worker saw and did, so 'why did you change X' or 'where is Y handled' costs one short answer instead of a read of the event stream. It can read the worktree and change nothing; to make the worker change something, use resume_codex_worker. Without a question it returns the latest side turn (for an answer that outran timeoutMs). end: true deletes the fork.",
913
+ inputSchema: {
914
+ task_id: z.string().min(1),
915
+ question: z.string().min(1).optional(),
916
+ timeoutMs: z.number().int().min(1000).max(600000).default(110000),
917
+ maxChars: z.number().int().min(0).max(1000000).default(8000),
918
+ end: z.boolean().default(false)
919
+ }
920
+ },
921
+ async ({ task_id, question, timeoutMs, maxChars, end }) => {
922
+ const task = await getTask(task_id);
923
+ if (!task) return textResult({ error: "task_not_found", task_id });
924
+ const clipAnswer = (state) => {
925
+ if (state?.turn?.answer && maxChars !== undefined) state.turn.answer = truncateMiddleChars(state.turn.answer, maxChars);
926
+ return state;
927
+ };
928
+ if (end) {
929
+ const ended = await endSideSession(task_id);
930
+ return textResult({ task_id, ...ended });
931
+ }
932
+ if (!question) {
933
+ return textResult({ task_id, ...clipAnswer(await latestSideTurn(task_id)) });
934
+ }
935
+ try {
936
+ const state = clipAnswer(await askWorker({ task, question, timeoutMs }));
937
+ const next = state.timed_out
938
+ ? `The side turn is still running; call ask_codex_worker again with only task_id to read the answer when it lands.`
939
+ : null;
940
+ return textResult({ task_id, ...state, next_step: next });
941
+ } catch (error) {
942
+ if (error.code === "busy") {
943
+ return textResult({ task_id, error: "busy", reason: error.message, ...clipAnswer(await latestSideTurn(task_id)) });
944
+ }
945
+ return textResult({ task_id, error: error.code ?? "side_turn_failed", reason: error.message });
946
+ }
947
+ }
948
+ );
949
+
950
+ server.registerTool(
951
+ "land_codex_worker",
952
+ {
953
+ title: "Land a worker's commits",
954
+ description:
955
+ "Cherry-pick the commits a worker made on its codex/<taskId> branch onto the current branch of the directory it was dispatched from (its cwd). The target must be clean and is never switched to another branch; `onto` is a guard that names the branch you expect to be on. A conflict aborts the cherry-pick, lists the files, and leaves the target as it was. Uncommitted edits in the worker's worktree are reported, not landed. Check the work first with get_worker_result and get_worker_diff; land once it passes.",
956
+ inputSchema: {
957
+ task_id: z.string().min(1),
958
+ onto: z.string().min(1).optional()
959
+ }
960
+ },
961
+ async ({ task_id, onto }) => {
962
+ const task = await getTask(task_id);
963
+ if (!task) return textResult({ error: "task_not_found", task_id });
964
+ return textResult({ task_id, title: task.title, status: task.status, branch: `codex/${task.id}`, ...landWorker(task, { onto }) });
965
+ }
966
+ );
967
+
829
968
  server.registerTool(
830
969
  "cancel_codex_worker",
831
970
  {
package/src/setup.js CHANGED
@@ -11,7 +11,6 @@
11
11
  // Set CODEX_SUPERVISOR_SKIP_SETUP=1 to opt out of the automatic run.
12
12
  import { execFile } from "node:child_process";
13
13
  import { existsSync, readdirSync } from "node:fs";
14
- import { mkdir, readFile, writeFile } from "node:fs/promises";
15
14
  import { homedir } from "node:os";
16
15
  import { dirname, join } from "node:path";
17
16
  import { fileURLToPath } from "node:url";
@@ -25,11 +24,11 @@ import {
25
24
 
26
25
  const run = promisify(execFile);
27
26
 
27
+ import { installSkill, skillRoots } from "./skill-sync.js";
28
+
28
29
  const packageRoot = dirname(dirname(fileURLToPath(import.meta.url)));
29
- const skillSource = join(packageRoot, "skills", "codex-supervisor", "SKILL.md");
30
30
  const serverEntry = join(packageRoot, "src", "mcp-server.js");
31
31
 
32
- const SKILL_NAME = "codex-supervisor";
33
32
  const MCP_NAME = "codex-supervisor";
34
33
  const CLIENT_TIMEOUT_MS = 60_000;
35
34
 
@@ -38,20 +37,17 @@ const CLIENT_TIMEOUT_MS = 60_000;
38
37
  // `npmEntry` lets bin-resolver.js step over a Windows .cmd shim by pointing at
39
38
  // the package's own entry point. `binEnv` is the override named in the repair
40
39
  // message when that fails (only Codex has one).
40
+ const SKILL_ROOTS = skillRoots();
41
41
  const CLIENTS = [
42
42
  {
43
- id: "claude",
44
- label: "Claude Code",
45
- skillRoot: join(homedir(), ".claude", "skills"),
43
+ ...SKILL_ROOTS.claude,
46
44
  binary: "claude",
47
45
  binEnv: null,
48
46
  npmEntry: { pkg: "@anthropic-ai/claude-code", bin: "bin/claude.exe" }
49
47
  },
50
- { id: "agents", label: "~/.agents", skillRoot: join(homedir(), ".agents", "skills"), binary: null },
48
+ { ...SKILL_ROOTS.agents, binary: null },
51
49
  {
52
- id: "codex",
53
- label: "Codex",
54
- skillRoot: join(homedir(), ".codex", "skills"),
50
+ ...SKILL_ROOTS.codex,
55
51
  binary: "codex",
56
52
  binEnv: "CODEX_BIN",
57
53
  npmEntry: { pkg: "@openai/codex", bin: "bin/codex.js" }
@@ -175,43 +171,6 @@ function selectClients(options) {
175
171
  });
176
172
  }
177
173
 
178
- async function installSkill(client, options, log) {
179
- const destination = join(client.skillRoot, SKILL_NAME, "SKILL.md");
180
- const source = await readFile(skillSource, "utf8");
181
-
182
- if (existsSync(destination)) {
183
- const current = await readFile(destination, "utf8");
184
- if (current === source) {
185
- log(`skill ${client.label}: up to date`);
186
- return "unchanged";
187
- }
188
- if (!options.force) {
189
- const backup = `${destination}.bak-${Date.now()}`;
190
- if (options.dryRun) {
191
- log(`skill ${client.label}: would back up to ${backup} and overwrite`);
192
- return "would-update";
193
- }
194
- await writeFile(backup, current);
195
- }
196
- if (options.dryRun) {
197
- log(`skill ${client.label}: would overwrite`);
198
- return "would-update";
199
- }
200
- await writeFile(destination, source);
201
- log(`skill ${client.label}: updated`);
202
- return "updated";
203
- }
204
-
205
- if (options.dryRun) {
206
- log(`skill ${client.label}: would install to ${destination}`);
207
- return "would-install";
208
- }
209
- await mkdir(dirname(destination), { recursive: true });
210
- await writeFile(destination, source);
211
- log(`skill ${client.label}: installed`);
212
- return "installed";
213
- }
214
-
215
174
  async function mcpAlreadyRegistered(target, options) {
216
175
  if (options.dryRun) return false;
217
176
  try {
package/src/side-chat.js CHANGED
@@ -410,6 +410,69 @@ export async function runSideTurn({ task, text, res = null }) {
410
410
  });
411
411
  }
412
412
 
413
+ // The answer of a turn, as the text parts joined; null while nothing has
414
+ // been said yet.
415
+ function answerOf(turn) {
416
+ const parts = partsFromChunks(turn.chunks ?? []);
417
+ const text = parts.filter((p) => p.type === "text").map((p) => p.text).join("\n").trim();
418
+ return text || null;
419
+ }
420
+
421
+ function turnView(turn) {
422
+ return {
423
+ turn_id: turn.id,
424
+ question: turn.question,
425
+ status: turn.status,
426
+ answer: answerOf(turn),
427
+ usage: turn.usage ?? null,
428
+ error: turn.error ?? null,
429
+ started_at: turn.started_at ?? null,
430
+ ended_at: turn.ended_at ?? null
431
+ };
432
+ }
433
+
434
+ // The newest side turn of a worker, for a caller that asked earlier and
435
+ // comes back for the answer. Null when nothing was ever asked.
436
+ export async function latestSideTurn(taskId) {
437
+ await sweepOnce();
438
+ const turns = await readSideTurns(taskId);
439
+ const live = running.get(taskId) ?? null;
440
+ const latest = turns.at(-1) ?? null;
441
+ const session = await getSideSession(taskId);
442
+ if (!latest) return { active: Boolean(session), fork_thread_id: session?.fork_thread_id ?? null, busy: Boolean(live), turn: null };
443
+ const view = turnView(latest);
444
+ if (live && live.turnId === latest.id) {
445
+ view.status = "running";
446
+ view.answer = answerOf({ chunks: live.chunks });
447
+ }
448
+ return { active: Boolean(session), fork_thread_id: session?.fork_thread_id ?? null, busy: Boolean(live), turn: view };
449
+ }
450
+
451
+ // Ask the worker a question on the side, without touching its own thread,
452
+ // and wait up to `timeoutMs` for the answer. A turn that outlives the budget
453
+ // keeps running in this process; the caller reads it back with latestSideTurn.
454
+ export async function askWorker({ task, question, timeoutMs = 110000 }) {
455
+ const turn = runSideTurn({ task, text: question });
456
+ // runSideTurn throws synchronously-ish (rejected promise) for no_thread,
457
+ // busy and codex_missing before anything starts; surface those as-is.
458
+ let timer;
459
+ const budget = new Promise((resolve) => {
460
+ timer = setTimeout(() => resolve({ timedOut: true }), timeoutMs);
461
+ });
462
+ try {
463
+ const outcome = await Promise.race([turn.then((r) => ({ timedOut: false, ...r })), budget]);
464
+ if (!outcome.timedOut) {
465
+ const state = await latestSideTurn(task.id);
466
+ return { ...state, timed_out: false };
467
+ }
468
+ turn.catch(() => {});
469
+ const state = await latestSideTurn(task.id);
470
+ return { ...state, timed_out: true };
471
+ } finally {
472
+ clearTimeout(timer);
473
+ }
474
+ }
475
+
413
476
  export function stopSideTurn(taskId) {
414
477
  const live = running.get(taskId);
415
478
  if (!live) return { stopped: false };