@mcpbox/mcpbox-claude 0.1.27 → 0.1.29
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/.claude-plugin/plugin.json +2 -2
- package/.codex-plugin/plugin.json +4 -4
- package/README.md +280 -20
- package/bin/mcpbox-claude.mjs +61 -11
- package/commands/close.md +2 -0
- package/commands/mine.md +4 -4
- package/commands/mode.md +4 -12
- package/commands/next.md +4 -3
- package/commands/pipeline-run.md +4 -4
- package/commands/plan.md +4 -4
- package/commands/sync.md +1 -1
- package/commands/tasks.md +4 -4
- package/hooks/acceptance-guard.mjs +5 -62
- package/hooks/bootstrap.mjs +167 -0
- package/hooks/edit-gate.mjs +7 -0
- package/hooks/hooks.json +37 -1
- package/hooks/impl/acceptance-guard.mjs +63 -0
- package/hooks/impl/edit-gate.mjs +32 -0
- package/hooks/impl/prepare-commit-msg.mjs +8 -0
- package/hooks/impl/session-gate.mjs +81 -0
- package/hooks/impl/session-start.mjs +89 -0
- package/hooks/impl/stop.mjs +64 -0
- package/hooks/impl/track-claims.mjs +35 -0
- package/hooks/impl/user-prompt-submit.mjs +234 -0
- package/hooks/prepare-commit-msg.mjs +7 -0
- package/hooks/session-gate.mjs +7 -0
- package/hooks/session-start.mjs +5 -204
- package/hooks/stop.mjs +5 -104
- package/hooks/track-claims.mjs +7 -0
- package/hooks/user-prompt-submit.mjs +5 -259
- package/lib/cloud-knowledge.mjs +19 -3
- package/lib/codex.mjs +2 -2
- package/lib/cursor.mjs +1 -1
- package/lib/edit-gate.mjs +120 -0
- package/lib/git-trailer.mjs +104 -0
- package/lib/harness-hooks.mjs +186 -0
- package/lib/hook-doctor.mjs +517 -0
- package/lib/hook-output.mjs +16 -0
- package/lib/kimi.mjs +16 -4
- package/lib/knowledge-skills.mjs +259 -0
- package/lib/mode.mjs +2 -12
- package/lib/policy.mjs +54 -127
- package/lib/session-gate.mjs +385 -0
- package/lib/version.mjs +1 -1
- package/package.json +2 -2
- package/skills/mcpbox/SKILL.md +17 -94
- package/skills/mcpbox-close/SKILL.md +2 -0
- package/skills/mcpbox-mine/SKILL.md +4 -4
- package/skills/mcpbox-mode/SKILL.md +4 -12
- package/skills/mcpbox-next/SKILL.md +4 -3
- package/skills/mcpbox-pipeline-run/SKILL.md +4 -4
- package/skills/mcpbox-plan/SKILL.md +4 -4
- package/skills/mcpbox-sync/SKILL.md +1 -1
- package/skills/mcpbox-tasks/SKILL.md +4 -4
|
@@ -0,0 +1,517 @@
|
|
|
1
|
+
// `mcpbox-claude doctor` hooks section: why a hook "exited with code 1".
|
|
2
|
+
//
|
|
3
|
+
// Codex shows only "hook exited with code N" and drops the hook's stderr, so
|
|
4
|
+
// the reason has to be reproduced outside it. For every mcpbox entry in the
|
|
5
|
+
// user-level hooks files this runs the command the way the host does —
|
|
6
|
+
// Windows `%COMSPEC% /C "<command>"`, Unix `$SHELL -lc <command>`, the event
|
|
7
|
+
// JSON on stdin — and prints the exit code with the head of stderr/stdout.
|
|
8
|
+
// It also finds `${VAR}`s nobody expands there (plugin variables exist only
|
|
9
|
+
// for hooks a plugin ships), which node the hooks' shell resolves, and
|
|
10
|
+
// whether the harness copy is complete. Diagnosis only: nothing is rewritten.
|
|
11
|
+
// The hooks run in a sandbox — a throwaway home, Codex/Claude config dirs,
|
|
12
|
+
// plugin data and cwd, with policy/skill sync and update checks switched off —
|
|
13
|
+
// so a SessionStart under the doctor cannot refresh the user's AGENTS.md or
|
|
14
|
+
// skills; the policy and skill files are compared before and after anyway.
|
|
15
|
+
// The sandbox starts inside the hook's node (a --require preload): the shell
|
|
16
|
+
// keeps the real environment and cwd, so `${HOME}`/`%USERPROFILE%` or a
|
|
17
|
+
// relative path in a command still resolve to the files the host would run.
|
|
18
|
+
|
|
19
|
+
import { spawn } from "node:child_process";
|
|
20
|
+
import { createHash } from "node:crypto";
|
|
21
|
+
import { existsSync, promises as fs } from "node:fs";
|
|
22
|
+
import { homedir, tmpdir } from "node:os";
|
|
23
|
+
import { dirname, join, resolve } from "node:path";
|
|
24
|
+
|
|
25
|
+
import { harnessImportGaps, harnessRoot, harnessStatus } from "./harness-hooks.mjs";
|
|
26
|
+
|
|
27
|
+
const PLUGIN_VARS = new Set(["PLUGIN_ROOT", "CLAUDE_PLUGIN_ROOT", "PLUGIN_DATA", "CLAUDE_PLUGIN_DATA"]);
|
|
28
|
+
const OUR_SCRIPT = /hooks[\\/](session-start|session-gate|stop|track-claims|user-prompt-submit|edit-gate|acceptance-guard)\.mjs\b/;
|
|
29
|
+
const MIN_NODE = 20; // package.json engines
|
|
30
|
+
const ODD_NODE = /openserver|ospanel|[\\/]\.?nvm[\\/]|volta/i;
|
|
31
|
+
const MAX_TIMEOUT_SEC = 60;
|
|
32
|
+
const STDERR_LINES = 20;
|
|
33
|
+
const STDOUT_LINES = 5;
|
|
34
|
+
// After the shell exits, how long its leftovers may hold our pipes.
|
|
35
|
+
const PIPE_GRACE_MS = 300;
|
|
36
|
+
export const DOCTOR_SESSION = "mcpbox-doctor";
|
|
37
|
+
|
|
38
|
+
const FIX = {
|
|
39
|
+
codex: "remove the ✗ entries above and run: npx -y @mcpbox/mcpbox-claude codex-init",
|
|
40
|
+
cursor: "remove the ✗ entries above and run: npx -y @mcpbox/mcpbox-claude cursor-init",
|
|
41
|
+
claude: "remove the ✗ entries above — the mcpbox plugin runs its hooks itself",
|
|
42
|
+
"codex-plugin": "the Codex plugin ships these hooks; update it: codex plugin marketplace upgrade mcpbox, then restart Codex",
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
export function hookFiles({ homeDir, env = process.env } = {}) {
|
|
46
|
+
const home = resolve(homeDir ?? homedir());
|
|
47
|
+
return [
|
|
48
|
+
{ surface: "codex", path: join(env.CODEX_HOME ? resolve(env.CODEX_HOME) : join(home, ".codex"), "hooks.json") },
|
|
49
|
+
{ surface: "cursor", path: join(home, ".cursor", "hooks.json") },
|
|
50
|
+
{ surface: "claude", path: join(home, ".claude", "settings.json") },
|
|
51
|
+
];
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const codexHome = (home, env) => (env.CODEX_HOME ? resolve(env.CODEX_HOME) : join(home, ".codex"));
|
|
55
|
+
|
|
56
|
+
// `[plugins."<name>@<marketplace>"]` tables with `enabled = true` in Codex's
|
|
57
|
+
// config.toml — just enough TOML for the install `codex plugin add` writes.
|
|
58
|
+
export function enabledCodexPlugins(toml) {
|
|
59
|
+
const out = [];
|
|
60
|
+
let current = null;
|
|
61
|
+
for (const line of String(toml ?? "").split(/\r?\n/)) {
|
|
62
|
+
const table = line.match(/^\s*\[\s*plugins\.(?:"([^"]+)"|([\w.-]+@[\w.-]+))\s*\]\s*$/);
|
|
63
|
+
if (table) {
|
|
64
|
+
current = table[1] ?? table[2];
|
|
65
|
+
continue;
|
|
66
|
+
}
|
|
67
|
+
if (/^\s*\[/.test(line)) {
|
|
68
|
+
current = null;
|
|
69
|
+
continue;
|
|
70
|
+
}
|
|
71
|
+
if (current && /^\s*enabled\s*=\s*true\b/.test(line) && current.includes("@")) out.push(current);
|
|
72
|
+
}
|
|
73
|
+
return [...new Set(out)];
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const versionKey = (v) => v.split(/[.-]/).map((p) => (/^\d+$/.test(p) ? p.padStart(8, "0") : p)).join(".");
|
|
77
|
+
|
|
78
|
+
// Codex runs the hooks/hooks.json of every enabled plugin (no `hooks` key in
|
|
79
|
+
// .codex-plugin/plugin.json needed — seen in `codex app-server` hooks/list,
|
|
80
|
+
// 0.165.0) from its cache copy $CODEX_HOME/plugins/cache/<mkt>/<name>/<ver>,
|
|
81
|
+
// with ${PLUGIN_ROOT}/${CLAUDE_PLUGIN_ROOT} replaced by that root and
|
|
82
|
+
// PLUGIN_DATA = $CODEX_HOME/plugins/data/<name>-<mkt>.
|
|
83
|
+
export async function codexPluginHookFiles({ homeDir, env = process.env } = {}) {
|
|
84
|
+
const base = codexHome(resolve(homeDir ?? homedir()), env);
|
|
85
|
+
let toml;
|
|
86
|
+
try {
|
|
87
|
+
toml = await fs.readFile(join(base, "config.toml"), "utf8");
|
|
88
|
+
} catch {
|
|
89
|
+
return [];
|
|
90
|
+
}
|
|
91
|
+
const out = [];
|
|
92
|
+
for (const id of enabledCodexPlugins(toml)) {
|
|
93
|
+
const [name, marketplace] = id.split("@");
|
|
94
|
+
const dir = join(base, "plugins", "cache", marketplace, name);
|
|
95
|
+
const versions = await fs.readdir(dir).catch(() => []);
|
|
96
|
+
const version = versions.sort((a, b) => versionKey(a).localeCompare(versionKey(b))).pop();
|
|
97
|
+
// Another plugin's hooks are not ours to run, whatever its scripts are called.
|
|
98
|
+
if (!version || !(await isMcpboxPlugin(join(dir, version)))) continue;
|
|
99
|
+
out.push({
|
|
100
|
+
surface: "codex-plugin",
|
|
101
|
+
plugin: id,
|
|
102
|
+
root: join(dir, version),
|
|
103
|
+
data: join(base, "plugins", "data", `${name}-${marketplace}`),
|
|
104
|
+
path: join(dir, version, "hooks", "hooks.json"),
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
return out;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
// The mcpbox plugin by its own manifest — not by the id, the marketplace or a
|
|
111
|
+
// script name another plugin may share.
|
|
112
|
+
export async function isMcpboxPlugin(root) {
|
|
113
|
+
try {
|
|
114
|
+
return JSON.parse(await fs.readFile(join(root, ".codex-plugin", "plugin.json"), "utf8"))?.name === "mcpbox";
|
|
115
|
+
} catch {
|
|
116
|
+
return false;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// Codex 0.141.0 parses a plugin hooks.json strictly: any top-level key but
|
|
121
|
+
// `hooks` ("unknown field `description`") drops the whole file with only a
|
|
122
|
+
// warning, so none of these hooks runs there; 0.165.0 accepts it.
|
|
123
|
+
export function pluginFileWarnings(doc) {
|
|
124
|
+
const extra = Object.keys(doc ?? {}).filter((k) => k !== "hooks");
|
|
125
|
+
return extra.length
|
|
126
|
+
? [`top-level ${extra.map((k) => `"${k}"`).join(", ")} besides "hooks": Codex 0.141 rejects this file (unknown field) and runs none of these hooks — 0.165 runs them; update Codex`]
|
|
127
|
+
: [];
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
export const expandPluginVars = (command, { root, data }) => command
|
|
131
|
+
.replace(/\$\{(?:CLAUDE_)?PLUGIN_ROOT\}/g, root)
|
|
132
|
+
.replace(/\$\{(?:CLAUDE_)?PLUGIN_DATA\}/g, data);
|
|
133
|
+
|
|
134
|
+
// Claude/Codex groups {matcher?, hooks: [{type, command, timeout}]}; Cursor
|
|
135
|
+
// flat entries {command, timeout?} per camelCase event.
|
|
136
|
+
export function hookCommands(doc) {
|
|
137
|
+
const hooks = doc?.hooks;
|
|
138
|
+
if (!hooks || typeof hooks !== "object" || Array.isArray(hooks)) return [];
|
|
139
|
+
const out = [];
|
|
140
|
+
for (const [event, list] of Object.entries(hooks)) {
|
|
141
|
+
if (!Array.isArray(list)) continue;
|
|
142
|
+
for (const group of list) {
|
|
143
|
+
for (const h of Array.isArray(group?.hooks) ? group.hooks : [group]) {
|
|
144
|
+
if (typeof h?.command !== "string") continue;
|
|
145
|
+
out.push({ event, command: h.command, timeout: Number.isFinite(h.timeout) ? h.timeout : null });
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
return out;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
// Ours: the harness copy, or one of our script names under a plugin root or
|
|
153
|
+
// an mcpbox path. A bare `hooks/session-start.mjs` is a common name (other
|
|
154
|
+
// Claude add-ons ship one too) and is not enough.
|
|
155
|
+
const OUR_ROOT = /mcpbox|\$\{(?:CLAUDE_)?PLUGIN_ROOT\}/i;
|
|
156
|
+
export const isMcpboxCommand = (command, root) => command.includes(root) || (OUR_SCRIPT.test(command) && OUR_ROOT.test(command));
|
|
157
|
+
|
|
158
|
+
// `${VAR}`s the host leaves as they are or turns into an empty string.
|
|
159
|
+
export function unexpandedVars(command, { surface, platform = process.platform, env = process.env } = {}) {
|
|
160
|
+
const names = [...new Set([...command.matchAll(/\$\{(\w+)\}/g)].map((m) => m[1]))];
|
|
161
|
+
return names.flatMap((name) => {
|
|
162
|
+
if (PLUGIN_VARS.has(name)) {
|
|
163
|
+
return [{ name, reason: `\${${name}} is set only for hooks a plugin ships; nothing expands it in this file, so node gets a broken path and exits 1` }];
|
|
164
|
+
}
|
|
165
|
+
if (surface === "claude") return [];
|
|
166
|
+
if (platform === "win32") return [{ name, reason: `cmd.exe does not expand \${${name}} (only %${name}%)` }];
|
|
167
|
+
if (env[name] === undefined) return [{ name, reason: `\${${name}} is not set — the shell expands it to an empty string` }];
|
|
168
|
+
return [];
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
export function hostSpawnArgs(command, { surface, platform = process.platform, env = process.env } = {}) {
|
|
173
|
+
// Claude Code runs hooks through bash (Git Bash on Windows), not cmd.exe.
|
|
174
|
+
if (surface === "claude") return { file: platform === "win32" ? "bash" : env.SHELL || "/bin/sh", args: ["-c", command], options: {} };
|
|
175
|
+
if (platform === "win32") {
|
|
176
|
+
// Codex: `%COMSPEC% /C "<command>"` as one raw argument; cmd strips the outer quotes.
|
|
177
|
+
return { file: env.COMSPEC ?? "cmd.exe", args: ["/C", `"${command}"`], options: { windowsVerbatimArguments: true } };
|
|
178
|
+
}
|
|
179
|
+
return { file: env.SHELL || "/bin/sh", args: ["-lc", command], options: {} };
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
const head = (text, n) => text.split(/\r?\n/).filter((l) => l.trim()).slice(0, n);
|
|
183
|
+
|
|
184
|
+
// Kill the shell and everything it started: a node grandchild keeps our
|
|
185
|
+
// pipes open after the shell dies, and `close` would wait for it.
|
|
186
|
+
function killTree(child, platform, env) {
|
|
187
|
+
if (!child.pid) return;
|
|
188
|
+
if (platform === "win32") {
|
|
189
|
+
const taskkill = join(env.SystemRoot ?? env.SYSTEMROOT ?? "C:\\Windows", "System32", "taskkill.exe");
|
|
190
|
+
try {
|
|
191
|
+
spawn(taskkill, ["/PID", String(child.pid), "/T", "/F"], { stdio: "ignore", windowsHide: true }).on("error", () => {});
|
|
192
|
+
} catch { /* gone already */ }
|
|
193
|
+
return;
|
|
194
|
+
}
|
|
195
|
+
try {
|
|
196
|
+
process.kill(-child.pid, "SIGKILL");
|
|
197
|
+
} catch {
|
|
198
|
+
try { child.kill("SIGKILL"); } catch { /* gone already */ }
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
export function runLikeHost(command, {
|
|
203
|
+
event, surface, cwd = process.cwd(), timeoutSec, env = process.env, platform = process.platform, input,
|
|
204
|
+
} = {}) {
|
|
205
|
+
const { file, args, options } = hostSpawnArgs(command, { surface, platform, env });
|
|
206
|
+
const limit = Math.min(timeoutSec ?? MAX_TIMEOUT_SEC, MAX_TIMEOUT_SEC);
|
|
207
|
+
return new Promise((done) => {
|
|
208
|
+
let stdout = "";
|
|
209
|
+
let stderr = "";
|
|
210
|
+
let timedOut = false;
|
|
211
|
+
let settled = false;
|
|
212
|
+
let grace = null;
|
|
213
|
+
let child = null;
|
|
214
|
+
const finish = (result) => {
|
|
215
|
+
if (settled) return;
|
|
216
|
+
settled = true;
|
|
217
|
+
clearTimeout(timer);
|
|
218
|
+
clearTimeout(grace);
|
|
219
|
+
if (child) {
|
|
220
|
+
// Whatever is left of the tree (a grandchild holding the pipes) goes
|
|
221
|
+
// too: the whole group on Unix, the live process tree on Windows.
|
|
222
|
+
const running = child.exitCode === null && child.signalCode === null;
|
|
223
|
+
if (running || platform !== "win32") killTree(child, platform, env);
|
|
224
|
+
child.stdout?.destroy();
|
|
225
|
+
child.stderr?.destroy();
|
|
226
|
+
}
|
|
227
|
+
done({ command, event, stdout, stderr, timed_out: timedOut, ...result });
|
|
228
|
+
};
|
|
229
|
+
const timer = setTimeout(() => {
|
|
230
|
+
timedOut = true;
|
|
231
|
+
killTree(child, platform, env);
|
|
232
|
+
// Bounded: report even if a leftover still holds the pipes.
|
|
233
|
+
grace = setTimeout(() => finish({ code: child.exitCode, signal: child.signalCode ?? "SIGKILL" }), PIPE_GRACE_MS);
|
|
234
|
+
}, limit * 1000);
|
|
235
|
+
try {
|
|
236
|
+
// Own process group on Unix, so the timeout can kill the whole tree.
|
|
237
|
+
child = spawn(file, args, { ...options, cwd, env, stdio: ["pipe", "pipe", "pipe"], detached: platform !== "win32", windowsHide: true });
|
|
238
|
+
} catch (err) {
|
|
239
|
+
finish({ code: null, signal: null, error: err.message });
|
|
240
|
+
return;
|
|
241
|
+
}
|
|
242
|
+
child.stdout.on("data", (chunk) => { stdout += chunk; });
|
|
243
|
+
child.stderr.on("data", (chunk) => { stderr += chunk; });
|
|
244
|
+
child.on("error", (err) => finish({ code: null, signal: null, error: err.message }));
|
|
245
|
+
child.on("exit", (code, signal) => {
|
|
246
|
+
if (timedOut) return;
|
|
247
|
+
grace = setTimeout(() => finish({ code, signal }), PIPE_GRACE_MS);
|
|
248
|
+
});
|
|
249
|
+
child.on("close", (code, signal) => finish({ code, signal }));
|
|
250
|
+
child.stdin.on("error", () => {});
|
|
251
|
+
child.stdin.end(input ?? JSON.stringify({ hook_event_name: event, session_id: DOCTOR_SESSION, cwd }));
|
|
252
|
+
});
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
// The node the hooks get: resolved by the hooks' own shell, not this terminal.
|
|
256
|
+
export async function hostNode({ platform = process.platform, env = process.env, cwd } = {}) {
|
|
257
|
+
const r = await runLikeHost(
|
|
258
|
+
'node -e "console.log(process.versions.node);console.log(process.execPath)"',
|
|
259
|
+
{ event: "doctor", cwd, timeoutSec: 15, env, platform, input: "" },
|
|
260
|
+
);
|
|
261
|
+
const lines = head(r.stdout, Infinity);
|
|
262
|
+
if (r.code !== 0 || lines.length < 2) {
|
|
263
|
+
return { found: false, error: r.error ?? (head(r.stderr, 3).join(" | ") || `exit ${r.code}`), warnings: [] };
|
|
264
|
+
}
|
|
265
|
+
const [version, execPath] = lines.slice(-2).map((l) => l.trim());
|
|
266
|
+
const warnings = [];
|
|
267
|
+
if (Number(version.split(".")[0]) < MIN_NODE) {
|
|
268
|
+
warnings.push(`Node ${version} is older than ${MIN_NODE} (package engines) — the hooks fail to load`);
|
|
269
|
+
}
|
|
270
|
+
if (ODD_NODE.test(execPath)) {
|
|
271
|
+
warnings.push(`node comes from ${execPath} — a panel or version manager on the hooks' PATH may swap it`);
|
|
272
|
+
}
|
|
273
|
+
return { found: true, version, exec_path: execPath, warnings };
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
async function readJson(path) {
|
|
277
|
+
try {
|
|
278
|
+
return { doc: JSON.parse(await fs.readFile(path, "utf8")) };
|
|
279
|
+
} catch (err) {
|
|
280
|
+
if (err.code === "ENOENT") return null;
|
|
281
|
+
return { error: err.message };
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
// Everything a hook may write goes to a throwaway dir: home, Codex/Claude
|
|
286
|
+
// config dirs, plugin data and cwd; the opt-outs switch off policy/skill sync
|
|
287
|
+
// and the update check on top. Credentials live under the home, so the hooks
|
|
288
|
+
// reach no tracker either. Home, config dirs and cwd are swapped by a
|
|
289
|
+
// preload in the hook's node, after the shell has expanded the command and
|
|
290
|
+
// node has resolved its script with the real ones (a login shell reads the
|
|
291
|
+
// real profile too, so PATH and node stay the host's).
|
|
292
|
+
const SANDBOX_OFF = {
|
|
293
|
+
MCPBOX_NO_POLICY_SYNC: "1", MCPBOX_NO_KNOWLEDGE_SKILLS: "1", MCPBOX_NO_UPDATE_CHECK: "1", MCPBOX_NO_POLICY_FETCH: "1",
|
|
294
|
+
};
|
|
295
|
+
const PRELOAD = "sandbox-home.cjs";
|
|
296
|
+
|
|
297
|
+
// NODE_OPTIONS takes a double-quoted path; forward slashes work on Windows too.
|
|
298
|
+
export const preloadOption = (file, existing) => [`--require "${file.replace(/\\/g, "/").replace(/"/g, '\\"')}"`, existing?.trim()]
|
|
299
|
+
.filter(Boolean).join(" ");
|
|
300
|
+
|
|
301
|
+
const POLICY_CARRIERS = ["CLAUDE.md", "AGENTS.md", join(".cursor", "rules", "mcpbox-policy.mdc")];
|
|
302
|
+
const ancestors = (dir) => {
|
|
303
|
+
const out = [];
|
|
304
|
+
for (let d = resolve(dir); ; d = dirname(d)) {
|
|
305
|
+
out.push(d);
|
|
306
|
+
if (dirname(d) === d) return out;
|
|
307
|
+
}
|
|
308
|
+
};
|
|
309
|
+
const carriersUp = (dir) => ancestors(dir).flatMap((d) => POLICY_CARRIERS.map((f) => join(d, f)));
|
|
310
|
+
|
|
311
|
+
// A temp root with no policy file above it: TMPDIR may sit inside the home
|
|
312
|
+
// (next to ~/CLAUDE.md), where a policy walk from the sandbox would land.
|
|
313
|
+
export function sandboxBase({ platform = process.platform } = {}) {
|
|
314
|
+
const candidates = [tmpdir(), ...(platform === "win32" ? [] : ["/tmp", "/var/tmp", "/dev/shm"])];
|
|
315
|
+
return candidates.find((d) => existsSync(d) && !carriersUp(d).some((f) => existsSync(f))) ?? tmpdir();
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
export async function hookSandbox({ env = process.env, platform = process.platform } = {}) {
|
|
319
|
+
const dir = await fs.mkdtemp(join(sandboxBase({ platform }), "mcpbox-doctor-"));
|
|
320
|
+
const home = join(dir, "home");
|
|
321
|
+
const cwd = join(dir, "cwd");
|
|
322
|
+
await Promise.all([fs.mkdir(home, { recursive: true }), fs.mkdir(cwd, { recursive: true })]);
|
|
323
|
+
// os.homedir() reads HOME (USERPROFILE on Windows) on every call, so the
|
|
324
|
+
// swap holds for the hook script and whatever it spawns.
|
|
325
|
+
const swap = { HOME: home, USERPROFILE: home, CODEX_HOME: join(home, ".codex"), CLAUDE_CONFIG_DIR: join(home, ".claude") };
|
|
326
|
+
const preload = join(dir, PRELOAD);
|
|
327
|
+
await fs.writeFile(preload, `Object.assign(process.env, ${JSON.stringify(swap)});\nprocess.chdir(${JSON.stringify(cwd)});\n`);
|
|
328
|
+
const base = { ...env, ...SANDBOX_OFF, NODE_OPTIONS: preloadOption(preload, env.NODE_OPTIONS) };
|
|
329
|
+
for (const key of ["PLUGIN_ROOT", "PLUGIN_DATA", "CLAUDE_PLUGIN_ROOT", "CLAUDE_PLUGIN_DATA"]) delete base[key];
|
|
330
|
+
return {
|
|
331
|
+
dir, cwd, home,
|
|
332
|
+
// Plugin hooks get the variables Codex sets for them; data stays here too.
|
|
333
|
+
env: (plugin) => (plugin
|
|
334
|
+
? { ...base, PLUGIN_ROOT: plugin.root, CLAUDE_PLUGIN_ROOT: plugin.root, PLUGIN_DATA: join(dir, "plugin-data"), CLAUDE_PLUGIN_DATA: join(dir, "plugin-data") }
|
|
335
|
+
: base),
|
|
336
|
+
data: join(dir, "plugin-data"),
|
|
337
|
+
dispose: () => fs.rm(dir, { recursive: true, force: true }).catch(() => {}),
|
|
338
|
+
};
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
// The files a SessionStart refreshes: policy carriers from the project up to
|
|
342
|
+
// the root and the user-level skill dirs. Hash per file, to prove the doctor
|
|
343
|
+
// left them as they were.
|
|
344
|
+
export async function guardedFiles({ projectDir, homeDir, env = process.env, also = [] } = {}) {
|
|
345
|
+
const home = resolve(homeDir ?? homedir());
|
|
346
|
+
const files = [...new Set([projectDir ?? process.cwd(), ...also].flatMap(carriersUp))];
|
|
347
|
+
const dirs = [
|
|
348
|
+
join(env.CLAUDE_CONFIG_DIR?.trim() || join(home, ".claude"), "skills"),
|
|
349
|
+
join(codexHome(home, env), "skills"),
|
|
350
|
+
join(home, ".agents", "skills"),
|
|
351
|
+
];
|
|
352
|
+
return { files, dirs };
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
async function hashFile(path) {
|
|
356
|
+
try {
|
|
357
|
+
return createHash("sha256").update(await fs.readFile(path)).digest("hex");
|
|
358
|
+
} catch {
|
|
359
|
+
return null;
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
async function listTree(dir, depth = 3) {
|
|
364
|
+
const out = [];
|
|
365
|
+
const walk = async (d, level) => {
|
|
366
|
+
let entries;
|
|
367
|
+
try {
|
|
368
|
+
entries = await fs.readdir(d, { withFileTypes: true });
|
|
369
|
+
} catch {
|
|
370
|
+
return;
|
|
371
|
+
}
|
|
372
|
+
for (const e of entries) {
|
|
373
|
+
const p = join(d, e.name);
|
|
374
|
+
if (e.isDirectory()) {
|
|
375
|
+
out.push(p + "/");
|
|
376
|
+
if (level < depth) await walk(p, level + 1);
|
|
377
|
+
} else {
|
|
378
|
+
out.push(p);
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
};
|
|
382
|
+
await walk(dir, 1);
|
|
383
|
+
return out;
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
export async function snapshotFiles({ files, dirs }) {
|
|
387
|
+
const snap = new Map();
|
|
388
|
+
for (const f of files) snap.set(f, await hashFile(f));
|
|
389
|
+
for (const d of dirs) {
|
|
390
|
+
for (const p of await listTree(d)) snap.set(p, p.endsWith("/") ? "dir" : await hashFile(p));
|
|
391
|
+
}
|
|
392
|
+
return snap;
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
export function changedFiles(before, after) {
|
|
396
|
+
const keys = new Set([...before.keys(), ...after.keys()]);
|
|
397
|
+
return [...keys].filter((k) => (before.get(k) ?? null) !== (after.get(k) ?? null)).sort();
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
export async function hookReport({
|
|
401
|
+
homeDir, env = process.env, platform = process.platform, cwd = process.cwd(),
|
|
402
|
+
} = {}) {
|
|
403
|
+
const root = harnessRoot(homeDir);
|
|
404
|
+
const sandbox = await hookSandbox({ env, platform });
|
|
405
|
+
const files = [];
|
|
406
|
+
let guard;
|
|
407
|
+
let before;
|
|
408
|
+
try {
|
|
409
|
+
guard = await guardedFiles({ projectDir: cwd, homeDir, env, also: [dirname(sandbox.dir)] });
|
|
410
|
+
before = await snapshotFiles(guard);
|
|
411
|
+
const sources = [
|
|
412
|
+
...hookFiles({ homeDir, env }).map((f) => ({ ...f, plugin: null })),
|
|
413
|
+
...(await codexPluginHookFiles({ homeDir, env })),
|
|
414
|
+
];
|
|
415
|
+
for (const source of sources) {
|
|
416
|
+
const { surface, path } = source;
|
|
417
|
+
const read = await readJson(path);
|
|
418
|
+
if (!read) continue;
|
|
419
|
+
if (read.error) {
|
|
420
|
+
files.push({ surface, path, error: read.error, entries: [] });
|
|
421
|
+
continue;
|
|
422
|
+
}
|
|
423
|
+
const pluginVars = source.plugin ? { root: source.root, data: sandbox.data } : null;
|
|
424
|
+
const entries = [];
|
|
425
|
+
for (const h of hookCommands(read.doc)) {
|
|
426
|
+
const command = pluginVars ? expandPluginVars(h.command, pluginVars) : h.command;
|
|
427
|
+
// The mcpbox plugin's file is ours whole (codexPluginHookFiles checked
|
|
428
|
+
// its manifest); user files mix in other tools' hooks.
|
|
429
|
+
if (!source.plugin && !isMcpboxCommand(command, root)) continue;
|
|
430
|
+
const vars = unexpandedVars(command, { surface: surface === "codex-plugin" ? "codex" : surface, platform, env });
|
|
431
|
+
const run = await runLikeHost(command, {
|
|
432
|
+
event: h.event,
|
|
433
|
+
surface: surface === "codex-plugin" ? "codex" : surface,
|
|
434
|
+
cwd,
|
|
435
|
+
// The event names the sandbox as the session's cwd, like the preload.
|
|
436
|
+
input: JSON.stringify({ hook_event_name: h.event, session_id: DOCTOR_SESSION, cwd: sandbox.cwd }),
|
|
437
|
+
timeoutSec: h.timeout,
|
|
438
|
+
env: sandbox.env(pluginVars && source),
|
|
439
|
+
platform,
|
|
440
|
+
});
|
|
441
|
+
entries.push({
|
|
442
|
+
event: h.event,
|
|
443
|
+
command,
|
|
444
|
+
unexpanded: vars,
|
|
445
|
+
exit_code: run.code,
|
|
446
|
+
signal: run.signal ?? null,
|
|
447
|
+
timed_out: run.timed_out,
|
|
448
|
+
spawn_error: run.error ?? null,
|
|
449
|
+
reported_failure: reportedFailure(run.stderr),
|
|
450
|
+
stderr_head: head(run.stderr, STDERR_LINES),
|
|
451
|
+
stdout_head: head(run.stdout, STDOUT_LINES),
|
|
452
|
+
});
|
|
453
|
+
}
|
|
454
|
+
if (entries.length) {
|
|
455
|
+
files.push({
|
|
456
|
+
surface, path, ...(source.plugin ? { plugin: source.plugin, warnings: pluginFileWarnings(read.doc) } : {}), fix: FIX[surface], entries,
|
|
457
|
+
});
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
} finally {
|
|
461
|
+
await sandbox.dispose();
|
|
462
|
+
}
|
|
463
|
+
const touched = changedFiles(before, await snapshotFiles(guard));
|
|
464
|
+
const usesHarness = files.some((f) => f.entries.some((e) => e.command.includes(root)));
|
|
465
|
+
const harness = usesHarness ? await harnessStatus({ homeDir }) : null;
|
|
466
|
+
const importGaps = await harnessImportGaps();
|
|
467
|
+
const node = await hostNode({ platform, env, cwd });
|
|
468
|
+
const failing = files.reduce((n, f) => n + (f.error ? 1 : 0) + f.entries.filter(entryFails).length, 0);
|
|
469
|
+
const ok = failing === 0 && importGaps.length === 0 && !(harness && harness.missing.length) && touched.length === 0;
|
|
470
|
+
return { ok, failing, files, harness, import_gaps: importGaps, node, touched };
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
// hooks/bootstrap.mjs turns a hook failure into exit 0 plus this line on
|
|
474
|
+
// stderr (the host shows its JSON copy); exit 0 alone is not "ran clean".
|
|
475
|
+
const FAILURE_LINE = /^\[mcpbox\] hook \S+ failed: /;
|
|
476
|
+
export const reportedFailure = (stderr) => String(stderr ?? "").split(/\r?\n/).find((l) => FAILURE_LINE.test(l)) ?? null;
|
|
477
|
+
|
|
478
|
+
const entryFails = (e) => e.exit_code !== 0 || e.unexpanded.length > 0 || Boolean(e.reported_failure);
|
|
479
|
+
|
|
480
|
+
export function formatHookReport(report) {
|
|
481
|
+
const lines = [];
|
|
482
|
+
const total = report.files.reduce((n, f) => n + f.entries.length, 0);
|
|
483
|
+
const bad = report.files.reduce((n, f) => n + f.entries.filter(entryFails).length, 0);
|
|
484
|
+
lines.push(`Hooks: ${report.ok ? "✓" : "✗"} ${total ? `${total - bad} of ${total} mcpbox hooks ran clean` : "no mcpbox hooks in user hooks files or Codex plugins"}`);
|
|
485
|
+
for (const f of report.files) {
|
|
486
|
+
if (f.error) {
|
|
487
|
+
lines.push(` ✗ ${f.path}: ${f.error}`);
|
|
488
|
+
continue;
|
|
489
|
+
}
|
|
490
|
+
lines.push(` ${f.path} (${f.plugin ? `codex plugin ${f.plugin}` : f.surface}):`);
|
|
491
|
+
for (const w of f.warnings ?? []) lines.push(` ! ${w}`);
|
|
492
|
+
for (const e of f.entries) {
|
|
493
|
+
const status = e.spawn_error ? `could not start: ${e.spawn_error}`
|
|
494
|
+
: e.timed_out ? "timed out" : e.signal ? `killed by ${e.signal}`
|
|
495
|
+
: e.reported_failure ? `exit ${e.exit_code}, the hook reported a failure` : `exit ${e.exit_code}`;
|
|
496
|
+
lines.push(` ${entryFails(e) ? "✗" : "✓"} ${e.event}: ${status}`);
|
|
497
|
+
lines.push(` $ ${e.command}`);
|
|
498
|
+
for (const v of e.unexpanded) lines.push(` ! ${v.reason}`);
|
|
499
|
+
for (const l of e.stderr_head) lines.push(` stderr: ${l}`);
|
|
500
|
+
if (entryFails(e)) for (const l of e.stdout_head) lines.push(` stdout: ${l}`);
|
|
501
|
+
}
|
|
502
|
+
if (f.entries.some(entryFails)) lines.push(` fix: ${f.fix}`);
|
|
503
|
+
}
|
|
504
|
+
if (report.harness) {
|
|
505
|
+
for (const p of report.harness.missing) lines.push(` ✗ harness file missing: ${p} — run: npx -y @mcpbox/mcpbox-claude codex-init`);
|
|
506
|
+
for (const p of report.harness.stale) lines.push(` ! harness file differs from this package: ${p} — run: npx -y @mcpbox/mcpbox-claude codex-init`);
|
|
507
|
+
}
|
|
508
|
+
for (const g of report.import_gaps) lines.push(` ✗ harness incomplete: ${g.file} imports ${g.imports}`);
|
|
509
|
+
const n = report.node;
|
|
510
|
+
lines.push(n.found
|
|
511
|
+
? ` node for hooks: ${n.version} at ${n.exec_path} (resolved by the hooks' shell; Codex uses the PATH it was started with)`
|
|
512
|
+
: ` ✗ node for hooks: not found by the hooks' shell (${n.error})`);
|
|
513
|
+
for (const w of n.warnings) lines.push(` ! ${w}`);
|
|
514
|
+
// Should never happen: the hooks ran in a sandbox. Say so if it did.
|
|
515
|
+
for (const p of report.touched ?? []) lines.push(` ✗ changed while the doctor ran: ${p} — not by design, please report it`);
|
|
516
|
+
return `${lines.join("\n")}\n`;
|
|
517
|
+
}
|
package/lib/hook-output.mjs
CHANGED
|
@@ -39,3 +39,19 @@ export function writeHookOutput(event, text, options = {}, env = process.env) {
|
|
|
39
39
|
}
|
|
40
40
|
process.stdout.write(`${JSON.stringify(hookOutputPayload(event, text, { systemMessage }))}\n`);
|
|
41
41
|
}
|
|
42
|
+
|
|
43
|
+
// Events whose host wire carries additionalContext to the model; the rest
|
|
44
|
+
// take only the user-visible systemMessage.
|
|
45
|
+
const CONTEXT_EVENTS = ["SessionStart", "UserPromptSubmit", "SubagentStart"];
|
|
46
|
+
|
|
47
|
+
// stdout document for a hook that failed (hooks/bootstrap.mjs), so the agent
|
|
48
|
+
// sees the reason instead of "hook exited with code 1". Claude Code, Codex
|
|
49
|
+
// and Kimi take the same JSON; Cursor reads additional_context on
|
|
50
|
+
// sessionStart only, and elsewhere a stray key could mean "continue the
|
|
51
|
+
// loop" — there the reason stays on stderr (null: write nothing).
|
|
52
|
+
export function hookFailureOutput(event, text, { argv = process.argv, env = process.env } = {}) {
|
|
53
|
+
const flag = argv.find((a) => a.startsWith("--surface="))?.slice("--surface=".length);
|
|
54
|
+
if (flag === "cursor") return event === "SessionStart" ? { additional_context: text } : null;
|
|
55
|
+
if (!CONTEXT_EVENTS.includes(event)) return { systemMessage: text };
|
|
56
|
+
return { systemMessage: text, hookSpecificOutput: { hookEventName: event, additionalContext: text } };
|
|
57
|
+
}
|
package/lib/kimi.mjs
CHANGED
|
@@ -46,17 +46,24 @@ const END = "<!-- mcpbox:policy:end -->";
|
|
|
46
46
|
const TOML_BEGIN = "# mcpbox:hooks:begin";
|
|
47
47
|
const TOML_END = "# mcpbox:hooks:end";
|
|
48
48
|
|
|
49
|
-
// Hook assets copied into the Kimi home: the
|
|
50
|
-
// local imports. Tests import static dependencies and execute --policy for the
|
|
49
|
+
// Hook assets copied into the Kimi home: the hook entries, their bootstrap and
|
|
50
|
+
// implementations (hooks/impl) and all their local imports. Tests import static dependencies and execute --policy for the
|
|
51
51
|
// dynamic policy.mjs import.
|
|
52
52
|
const HOOK_ASSETS = [
|
|
53
53
|
["hooks", "session-start.mjs"],
|
|
54
54
|
["hooks", "user-prompt-submit.mjs"],
|
|
55
55
|
["hooks", "stop.mjs"],
|
|
56
|
+
["hooks", "track-claims.mjs"],
|
|
57
|
+
["hooks", "bootstrap.mjs"],
|
|
58
|
+
["hooks/impl", "session-start.mjs"],
|
|
59
|
+
["hooks/impl", "user-prompt-submit.mjs"],
|
|
60
|
+
["hooks/impl", "stop.mjs"],
|
|
61
|
+
["hooks/impl", "track-claims.mjs"],
|
|
56
62
|
["lib", "mcp-client.mjs"],
|
|
57
63
|
["lib", "cloud-knowledge.mjs"],
|
|
58
64
|
["lib", "hook-input.mjs"],
|
|
59
65
|
["lib", "hook-output.mjs"],
|
|
66
|
+
["lib", "session-gate.mjs"],
|
|
60
67
|
["lib", "mode.mjs"],
|
|
61
68
|
// user-prompt-submit.mjs --policy reads the policy body from here.
|
|
62
69
|
["lib", "policy.mjs"],
|
|
@@ -155,6 +162,10 @@ function hooksTomlBlock(assetsRoot) {
|
|
|
155
162
|
command("user-prompt-submit.mjs", " --policy"),
|
|
156
163
|
"",
|
|
157
164
|
"[[hooks]]",
|
|
165
|
+
'event = "PostToolUse"',
|
|
166
|
+
command("track-claims.mjs"),
|
|
167
|
+
"",
|
|
168
|
+
"[[hooks]]",
|
|
158
169
|
'event = "Stop"',
|
|
159
170
|
command("stop.mjs"),
|
|
160
171
|
"",
|
|
@@ -166,7 +177,7 @@ function hooksTomlBlock(assetsRoot) {
|
|
|
166
177
|
// (measured 2026-09-27: 3× on a live install — each hook ran three times).
|
|
167
178
|
// Drop every [[hooks]] table outside the markers that runs one of our
|
|
168
179
|
// scripts, marked or not; trailing blank/comment lines stay with the file.
|
|
169
|
-
const OUR_HOOK = /mcpbox[\\/]+hooks[\\/]+(session-start|user-prompt-submit|stop)\.mjs/;
|
|
180
|
+
const OUR_HOOK = /mcpbox[\\/]+hooks[\\/]+(session-start|user-prompt-submit|stop|track-claims)\.mjs/;
|
|
170
181
|
|
|
171
182
|
function stripOurHookTables(text) {
|
|
172
183
|
const out = [];
|
|
@@ -242,6 +253,7 @@ export async function installKimiHooks({ configPath, kimiHome } = {}) {
|
|
|
242
253
|
begin: TOML_BEGIN,
|
|
243
254
|
end: TOML_END,
|
|
244
255
|
block: hooksTomlBlock(assetsRoot),
|
|
256
|
+
followLinks: true,
|
|
245
257
|
});
|
|
246
258
|
}
|
|
247
259
|
|
|
@@ -249,7 +261,7 @@ export async function removeKimiHooks({ configPath, kimiHome } = {}) {
|
|
|
249
261
|
const home = kimiHomeDir(kimiHome);
|
|
250
262
|
const target = configPath ? resolve(configPath) : join(home, "config.toml");
|
|
251
263
|
await dropOrphanHooks(target);
|
|
252
|
-
const block = await removeManagedBlock({ target, begin: TOML_BEGIN, end: TOML_END });
|
|
264
|
+
const block = await removeManagedBlock({ target, begin: TOML_BEGIN, end: TOML_END, followLinks: true });
|
|
253
265
|
// The assets dir is ours (namespaced `mcpbox` under the Kimi home) — drop it.
|
|
254
266
|
const assetsRoot = join(home, "mcpbox");
|
|
255
267
|
await fs.rm(assetsRoot, { recursive: true, force: true });
|