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,93 @@
1
+ // Copies the bundled skill into the skill directories of the agent clients on
2
+ // this machine. setup.js runs it after a global install; mcp-server.js runs it
3
+ // every time the server starts, because a server launched through
4
+ // `npx -y codex-supervisor-mcp@latest` never runs postinstall, and the skill
5
+ // text has to move together with the tool surface it describes.
6
+ import { existsSync } from "node:fs";
7
+ import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
8
+ import { homedir } from "node:os";
9
+ import { dirname, join } from "node:path";
10
+ import { fileURLToPath } from "node:url";
11
+
12
+ const packageRoot = dirname(dirname(fileURLToPath(import.meta.url)));
13
+
14
+ export const SKILL_NAME = "codex-supervisor";
15
+ export const skillSource = join(packageRoot, "skills", SKILL_NAME, "SKILL.md");
16
+
17
+ // Resolved on each call so a test can point HOME somewhere else first.
18
+ export function skillRoots() {
19
+ const home = homedir();
20
+ return {
21
+ claude: { id: "claude", label: "Claude Code", skillRoot: join(home, ".claude", "skills") },
22
+ agents: { id: "agents", label: "~/.agents", skillRoot: join(home, ".agents", "skills") },
23
+ codex: { id: "codex", label: "Codex", skillRoot: join(home, ".codex", "skills") }
24
+ };
25
+ }
26
+
27
+ // The skill is read by other processes at any moment, and the server that
28
+ // writes it may be killed at any moment: write beside it, then rename, so
29
+ // the file is always either the old text or the new one, never a torso.
30
+ async function writeAtomically(destination, text) {
31
+ const staging = `${destination}.tmp-${process.pid}-${Date.now()}`;
32
+ await writeFile(staging, text);
33
+ await rename(staging, destination);
34
+ }
35
+
36
+ // Writes the bundled skill under client.skillRoot. A file that differs is
37
+ // backed up as SKILL.md.bak-<timestamp> first unless options.force is set.
38
+ // Returns one of: unchanged, updated, installed, would-update, would-install.
39
+ export async function installSkill(client, options = {}, log = () => {}) {
40
+ const destination = join(client.skillRoot, SKILL_NAME, "SKILL.md");
41
+ const source = await readFile(skillSource, "utf8");
42
+
43
+ if (existsSync(destination)) {
44
+ const current = await readFile(destination, "utf8");
45
+ if (current === source) {
46
+ log(`skill ${client.label}: up to date`);
47
+ return "unchanged";
48
+ }
49
+ if (!options.force) {
50
+ const backup = `${destination}.bak-${Date.now()}`;
51
+ if (options.dryRun) {
52
+ log(`skill ${client.label}: would back up to ${backup} and overwrite`);
53
+ return "would-update";
54
+ }
55
+ await writeAtomically(backup, current);
56
+ }
57
+ if (options.dryRun) {
58
+ log(`skill ${client.label}: would overwrite`);
59
+ return "would-update";
60
+ }
61
+ await writeAtomically(destination, source);
62
+ log(`skill ${client.label}: updated`);
63
+ return "updated";
64
+ }
65
+
66
+ if (options.dryRun) {
67
+ log(`skill ${client.label}: would install to ${destination}`);
68
+ return "would-install";
69
+ }
70
+ await mkdir(dirname(destination), { recursive: true });
71
+ await writeAtomically(destination, source);
72
+ log(`skill ${client.label}: installed`);
73
+ return "installed";
74
+ }
75
+
76
+ // Brings every client whose skill directory already exists up to date. It
77
+ // never creates a client's skill directory: a missing ~/.codex/skills means
78
+ // Codex is not used here. One client failing does not stop the others.
79
+ // Returns { installed, updated, unchanged, failed } as lists of client labels
80
+ // (failed entries carry the error message).
81
+ export async function syncSkills({ force = false } = {}) {
82
+ const result = { installed: [], updated: [], unchanged: [], failed: [] };
83
+ for (const client of Object.values(skillRoots())) {
84
+ if (!existsSync(client.skillRoot)) continue;
85
+ try {
86
+ const outcome = await installSkill(client, { force });
87
+ result[outcome].push(client.label);
88
+ } catch (error) {
89
+ result.failed.push(`${client.label}: ${error.message}`);
90
+ }
91
+ }
92
+ return result;
93
+ }
@@ -10,7 +10,7 @@
10
10
  import { existsSync, readFileSync } from "node:fs";
11
11
  import { mkdir, readFile, writeFile } from "node:fs/promises";
12
12
  import { execFileSync } from "node:child_process";
13
- import { dirname, join, resolve } from "node:path";
13
+ import { basename, dirname, join, resolve } from "node:path";
14
14
  import { fileURLToPath } from "node:url";
15
15
  import { dataDir } from "./paths.js";
16
16
 
@@ -59,27 +59,47 @@ export function compareVersions(a, b) {
59
59
  // What is actually on disk: the version from package.json, plus whichever
60
60
  // provenance is available - npm's recorded integrity for a global install,
61
61
  // the HEAD commit for a git checkout.
62
+ // A copy that npx fetched lives under npm's cache (.../_npx/<hash>/...).
63
+ // npx resolves `latest` on every start, so such a copy must never be
64
+ // auto-installed over a global one.
65
+ export function isNpxPath(path) {
66
+ return String(path).split(/[\\/]/).includes("_npx");
67
+ }
68
+
69
+ // Who put this copy here. Pure, so it can be tested on made-up paths.
70
+ // git - a checkout (also what `npm link` resolves to, since node follows
71
+ // the symlink before import.meta.url is set)
72
+ // npx - npm's exec cache; npx refreshes it by itself
73
+ // npm - a directory npm installed, global or project-local (the
74
+ // auto-updater tells those apart with `npm root -g` before writing)
75
+ export function installSource(root, { exists = existsSync } = {}) {
76
+ if (exists(join(root, ".git"))) return "git";
77
+ if (isNpxPath(root)) return "npx";
78
+ if (basename(dirname(root)) === "node_modules") return "npm";
79
+ return "unknown";
80
+ }
81
+
62
82
  export function installedPackage() {
63
- const info = { name: PACKAGE_NAME, version: packageJson.version, path: packageRoot, integrity: null, commit: null, source: "unknown" };
83
+ const info = { name: PACKAGE_NAME, version: packageJson.version, path: packageRoot, integrity: null, commit: null, source: installSource(packageRoot) };
84
+ // A project-local install records the package's integrity in the hidden
85
+ // lockfile one level up. A global install has no such record (each global
86
+ // package is its own root), so integrity stays null and only the version
87
+ // is compared.
64
88
  const lockPath = join(packageRoot, "..", ".package-lock.json");
65
- if (existsSync(lockPath)) {
89
+ if (info.source === "npm" && existsSync(lockPath)) {
66
90
  try {
67
91
  const lock = JSON.parse(readFileSync(lockPath, "utf8"));
68
92
  const entry = lock.packages?.[`node_modules/${PACKAGE_NAME}`];
69
- if (entry?.integrity) {
70
- info.integrity = entry.integrity;
71
- info.source = "npm";
72
- }
93
+ if (entry?.integrity) info.integrity = entry.integrity;
73
94
  } catch {
74
- // unreadable lock: fall through, provenance stays unknown
95
+ // unreadable lock: integrity stays unknown
75
96
  }
76
97
  }
77
- if (!info.integrity && existsSync(join(packageRoot, ".git"))) {
98
+ if (info.source === "git") {
78
99
  try {
79
100
  info.commit = execFileSync("git", ["-C", packageRoot, "rev-parse", "HEAD"], { encoding: "utf8", timeout: 5000, stdio: ["ignore", "pipe", "ignore"] }).trim();
80
- info.source = "git";
81
101
  } catch {
82
- // not a usable checkout
102
+ // a checkout without a usable git: still a checkout
83
103
  }
84
104
  }
85
105
  return info;
@@ -193,9 +213,12 @@ export async function checkForUpdate({ force = false } = {}) {
193
213
 
194
214
  // The small object that rides along in tool results. Null when there is
195
215
  // nothing to say, so the common case costs no bytes.
196
- export function updateNotice(result) {
216
+ // `autoUpdate` is the auto-update record (see auto-update.js); when it says
217
+ // the install is already under way or done, the notice stops asking the user
218
+ // to run npm and says what to do instead: start a new session.
219
+ export function updateNotice(result, autoUpdate = null) {
197
220
  if (!result || !result.notice) return null;
198
- return {
221
+ const field = {
199
222
  update_available: result.update_available,
200
223
  installed_version: result.installed.version,
201
224
  latest_version: result.latest?.version ?? null,
@@ -203,4 +226,21 @@ export function updateNotice(result) {
203
226
  install_command: result.install_command,
204
227
  notice: result.notice
205
228
  };
229
+ if (result.update_available && autoUpdate && autoUpdate.version === field.latest_version) {
230
+ const name = `${PACKAGE_NAME} ${field.latest_version}`;
231
+ if (autoUpdate.state === "done") {
232
+ field.install_command = null;
233
+ field.notice = `${name} has been installed in the background; this session still runs ${field.installed_version}. Start a new session (restart the MCP client) to use it.`;
234
+ } else if (autoUpdate.state === "started" || autoUpdate.state === "running") {
235
+ field.install_command = null;
236
+ field.notice = `${name} is being installed in the background; this session still runs ${field.installed_version}. The next session starts on it once the install finishes.`;
237
+ } else if (autoUpdate.state === "failed") {
238
+ field.notice = `${field.notice} (automatic install failed: ${autoUpdate.reason ?? "unknown"})`;
239
+ }
240
+ field.auto_update = { state: autoUpdate.state, version: autoUpdate.version, ...(autoUpdate.reason ? { reason: autoUpdate.reason } : {}) };
241
+ } else if (result.update_available && result.installed.source === "npx") {
242
+ field.install_command = null;
243
+ field.notice = `${PACKAGE_NAME} ${field.latest_version} is published; this npx-started session runs ${field.installed_version}. The next session fetches the new one by itself.`;
244
+ }
245
+ return field;
206
246
  }
package/src/worktree.js CHANGED
@@ -11,8 +11,9 @@
11
11
  // so the committed part is read as `git diff --name-only <base> HEAD`, where
12
12
  // base is the commit the worktree was created from.
13
13
  import { execFileSync } from "node:child_process";
14
- import { existsSync } from "node:fs";
14
+ import { existsSync, readFileSync } from "node:fs";
15
15
  import { join } from "node:path";
16
+ import { truncateMiddleChars } from "./truncate.js";
16
17
 
17
18
  const defaultGitBin = process.env.GIT_BIN?.trim() || "git";
18
19
 
@@ -36,7 +37,7 @@ function git(worktreePath, args) {
36
37
  });
37
38
  }
38
39
 
39
- function parsePorcelainLine(line) {
40
+ export function parsePorcelainLine(line) {
40
41
  // " M path", "?? path", "R old -> new"
41
42
  const trimmed = line.replace(/\s+$/, "");
42
43
  if (trimmed.length < 4) return null;
@@ -86,6 +87,113 @@ export function readWorktreeChanges(worktreePath, { baseCommit = null, branch =
86
87
  return Array.from(found, (entry) => join(worktreePath, entry));
87
88
  }
88
89
 
90
+ // What the worker changed, as patches: everything between the commit the
91
+ // worktree started from and the working tree, committed or not, plus files
92
+ // git does not track yet. This is the main thread's ground truth for "what
93
+ // did it do", as opposed to what the worker says it did.
94
+ //
95
+ // `maxChars` bounds the whole answer. Files are served in git's order; a
96
+ // file that does not fit is cut in the middle (truncated: true), and files
97
+ // after the budget is spent come back without a patch so the list of what
98
+ // changed is still complete.
99
+ export function readWorktreeDiff(worktreePath, { baseCommit = null, branch = null } = {}, { maxChars = 60000, paths = [] } = {}) {
100
+ if (!worktreePath || !existsSync(worktreePath)) return { error: "no_worktree", files: [] };
101
+ const base = resolveWorktreeBase(worktreePath, { baseCommit, branch });
102
+ if (!base) return { error: "no_base_commit", files: [] };
103
+ let head = null;
104
+ try {
105
+ head = git(worktreePath, ["rev-parse", "HEAD"]).trim();
106
+ } catch {
107
+ // a worktree without a resolvable HEAD still has a working tree to diff
108
+ }
109
+ const scope = Array.isArray(paths) && paths.length > 0 ? ["--", ...paths] : [];
110
+
111
+ const files = [];
112
+ const known = new Set();
113
+ try {
114
+ for (const line of nonEmptyLines(git(worktreePath, ["diff", "--name-status", "-M", base, ...scope]))) {
115
+ const [code, ...rest] = line.split("\t");
116
+ const path = rest.at(-1);
117
+ if (!path) continue;
118
+ known.add(path);
119
+ files.push({ path, status: statusWord(code), from: code.startsWith("R") && rest.length > 1 ? rest[0] : null });
120
+ }
121
+ } catch {
122
+ return { error: "diff_failed", base_commit: base, head, files: [] };
123
+ }
124
+ const counts = new Map();
125
+ try {
126
+ for (const line of nonEmptyLines(git(worktreePath, ["diff", "--numstat", "-M", base, ...scope]))) {
127
+ const [added, deleted, ...rest] = line.split("\t");
128
+ counts.set(rest.at(-1), { additions: added === "-" ? null : Number(added), deletions: deleted === "-" ? null : Number(deleted) });
129
+ }
130
+ } catch {
131
+ // counts are decoration
132
+ }
133
+ // Untracked files never show in `git diff`; the worker may have created
134
+ // them with a shell command and not added them.
135
+ try {
136
+ for (const line of git(worktreePath, ["status", "--porcelain", "--untracked-files=all", ...scope]).split("\n")) {
137
+ if (!line.startsWith("??")) continue;
138
+ const path = parsePorcelainLine(line);
139
+ if (!path || known.has(path)) continue;
140
+ known.add(path);
141
+ files.push({ path, status: "untracked", from: null });
142
+ }
143
+ } catch {
144
+ // status failing leaves the tracked part
145
+ }
146
+
147
+ let remaining = maxChars;
148
+ let truncatedFiles = 0;
149
+ for (const file of files) {
150
+ const stat = counts.get(file.path);
151
+ file.additions = stat?.additions ?? null;
152
+ file.deletions = stat?.deletions ?? null;
153
+ file.patch = null;
154
+ file.truncated = false;
155
+ if (remaining <= 0) {
156
+ file.truncated = true;
157
+ truncatedFiles += 1;
158
+ continue;
159
+ }
160
+ let patch = "";
161
+ try {
162
+ if (file.status === "untracked") {
163
+ const text = readFileSync(join(worktreePath, file.path), "utf8");
164
+ patch = text.split("\n").map((l, i, all) => (i === all.length - 1 && l === "" ? null : `+${l}`)).filter((l) => l !== null).join("\n");
165
+ if (file.additions === null) file.additions = patch === "" ? 0 : patch.split("\n").length;
166
+ } else {
167
+ patch = git(worktreePath, ["diff", "-M", base, "--", file.path]);
168
+ }
169
+ } catch {
170
+ patch = "";
171
+ }
172
+ if (patch.length > remaining) {
173
+ file.patch = truncateMiddleChars(patch, remaining);
174
+ file.truncated = true;
175
+ truncatedFiles += 1;
176
+ remaining = 0;
177
+ } else {
178
+ file.patch = patch;
179
+ remaining -= patch.length;
180
+ }
181
+ }
182
+ return { base_commit: base, head, files, total_files: files.length, truncated_files: truncatedFiles };
183
+ }
184
+
185
+ function statusWord(code) {
186
+ switch (code[0]) {
187
+ case "A": return "added";
188
+ case "M": return "modified";
189
+ case "D": return "deleted";
190
+ case "R": return "renamed";
191
+ case "C": return "copied";
192
+ case "T": return "type-changed";
193
+ default: return code;
194
+ }
195
+ }
196
+
89
197
  export function mergeChangedFiles(existing, discovered) {
90
198
  return Array.from(new Set([...(existing ?? []), ...(discovered ?? [])]));
91
199
  }