@codeconductorai/harmony-mcp 1.0.32 → 1.0.34

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.
Files changed (47) hide show
  1. package/README.md +210 -15
  2. package/package.json +4 -2
  3. package/src/{deviceAuth.js → auth/deviceAuth.js} +2 -2
  4. package/src/{harmonyClient.js → backend/harmonyClient.js} +186 -15
  5. package/src/doctor/doctorCommand.js +382 -0
  6. package/src/index.js +18 -5
  7. package/src/{telemetry.js → observability/telemetry.js} +3 -3
  8. package/src/rsi/bundleHints.js +181 -0
  9. package/src/rsi/bundleRefresher.js +95 -0
  10. package/src/rsi/callContext.js +49 -0
  11. package/src/rsi/causalState.js +103 -0
  12. package/src/rsi/clientAgent.js +58 -0
  13. package/src/rsi/hooks/eventBuilder.js +126 -0
  14. package/src/rsi/hooks/fileHash.js +33 -0
  15. package/src/rsi/hooks/hmacSigner.js +39 -0
  16. package/src/rsi/hooks/hookEventCommand.js +196 -0
  17. package/src/rsi/hooks/normalizers.js +329 -0
  18. package/src/rsi/hooks/offlineSpooler.js +104 -0
  19. package/src/rsi/hooks/secretScrubber.js +50 -0
  20. package/src/rsi/hooks/shellCommandScrubber.js +449 -0
  21. package/src/rsi/hooks/spoolDrainer.js +73 -0
  22. package/src/rsi/hooks/toolEventsClient.js +70 -0
  23. package/src/rsi/localState.js +53 -0
  24. package/src/rsi/serveTelemetry.js +85 -0
  25. package/src/rsi/workspaceRegistry.js +63 -0
  26. package/src/{server.js → server/server.js} +107 -17
  27. package/src/{serverInstructions.js → server/serverInstructions.js} +2 -2
  28. package/src/server/serverMain.js +46 -0
  29. package/src/{sessionIdentity.js → session/sessionIdentity.js} +10 -6
  30. package/src/setup/agentCapabilityMatrix.js +425 -0
  31. package/src/setup/agentsGuide.js +28 -0
  32. package/src/setup/configMergers.js +272 -0
  33. package/src/{installer.js → setup/installer.js} +1 -1
  34. package/src/setup/setupAgentsCommand.js +192 -0
  35. package/src/setup/shim.js +80 -0
  36. package/src/sync/managedMarkdownInjector.js +103 -0
  37. package/src/sync/syncWorkspaceCommand.js +143 -0
  38. package/src/sync/workspaceSync.js +88 -0
  39. package/src/{fileWatcher.js → workspace/fileWatcher.js} +2 -2
  40. package/src/{workspaceIdentity.js → workspace/workspaceIdentity.js} +1 -1
  41. package/src/{workspaceMarker.js → workspace/workspaceMarker.js} +1 -1
  42. package/src/agentsGuide.js +0 -38
  43. package/src/serverMain.js +0 -32
  44. /package/src/{log.js → observability/log.js} +0 -0
  45. /package/src/{toolSchemas.js → server/toolSchemas.js} +0 -0
  46. /package/src/{fileFilters.js → workspace/fileFilters.js} +0 -0
  47. /package/src/{repoIdentity.js → workspace/repoIdentity.js} +0 -0
@@ -0,0 +1,196 @@
1
+ // `harmony-mcp hook-event --agent <id> [--event <kind>]` (RSI MCP spec §5.1).
2
+ //
3
+ // Runs as a PostToolUse / PreCompact hook of the coding agent. Contract with the host:
4
+ // - stdout stays empty (0 bytes), always — even on bugs: stdout writes are swallowed for the whole process
5
+ // - exit code is always 0, whatever happens (malformed stdin, backend down, disk full)
6
+ // - bounded time: 450 ms per backend request, a hard 2 s watchdog for the whole process
7
+ // Pipeline: normalize -> resolve workspace -> scrub/build events (+ edit hash) -> attach causal parent ->
8
+ // sign + POST, or spool when that is not possible right now.
9
+ import fs from "fs";
10
+ import path from "path";
11
+
12
+ import { harmonyPath, ensurePrivateDir } from "../localState.js";
13
+ import { readCausalState } from "../causalState.js";
14
+ import { resolveWorkspaceForDir } from "../workspaceRegistry.js";
15
+ import { AGENT_SLUGS, normalizeHookPayload } from "./normalizers.js";
16
+ import { buildWireEvent } from "./eventBuilder.js";
17
+ import { readTelemetryKey } from "./hmacSigner.js";
18
+ import { spoolEvents } from "./offlineSpooler.js";
19
+ import { batchBodies, cachedUserToken, postToolEvents } from "./toolEventsClient.js";
20
+ import { drainSpool } from "./spoolDrainer.js";
21
+
22
+ const MAX_STDIN_BYTES = 8 * 1024 * 1024;
23
+ const STDIN_TIMEOUT_MS = 1_000;
24
+ const POST_TIMEOUT_MS = Number(process.env.HARMONY_HOOK_TIMEOUT_MS) || 450;
25
+ const WATCHDOG_MS = 2_000;
26
+ const LOG_MAX_BYTES = 5 * 1024 * 1024;
27
+
28
+ function hookLog(message) {
29
+ try {
30
+ const dir = ensurePrivateDir(harmonyPath("logs"));
31
+ const file = path.join(dir, "harmony-mcp.log");
32
+ try {
33
+ if (fs.statSync(file).size > LOG_MAX_BYTES) fs.renameSync(file, `${file}.1`);
34
+ } catch {
35
+ // no log yet
36
+ }
37
+ fs.appendFileSync(file, `[${new Date().toISOString()}] [hook-event ${process.pid}] ${message}\n`, { mode: 0o600 });
38
+ } catch {
39
+ // logging must never fail the hook
40
+ }
41
+ }
42
+
43
+ export function parseHookArgs(argv) {
44
+ const out = { agent: null, event: null };
45
+ for (let i = 0; i < argv.length; i++) {
46
+ if (argv[i] === "--agent") out.agent = argv[++i] ?? null;
47
+ else if (argv[i].startsWith("--agent=")) out.agent = argv[i].slice(8);
48
+ else if (argv[i] === "--event") out.event = argv[++i] ?? null;
49
+ else if (argv[i].startsWith("--event=")) out.event = argv[i].slice(8);
50
+ }
51
+ return out;
52
+ }
53
+
54
+ // Reads stdin up to the cap; anything beyond is consumed and discarded so the writer never sees EPIPE.
55
+ function readStdin() {
56
+ return new Promise((resolve) => {
57
+ if (process.stdin.isTTY) return resolve("");
58
+ const chunks = [];
59
+ let size = 0;
60
+ let overflow = false;
61
+ const done = () => resolve(overflow ? "" : Buffer.concat(chunks).toString("utf8"));
62
+ const timer = setTimeout(done, STDIN_TIMEOUT_MS);
63
+ process.stdin.on("data", (chunk) => {
64
+ size += chunk.length;
65
+ if (size > MAX_STDIN_BYTES) {
66
+ overflow = true;
67
+ chunks.length = 0;
68
+ } else if (!overflow) {
69
+ chunks.push(chunk);
70
+ }
71
+ });
72
+ process.stdin.on("end", () => {
73
+ clearTimeout(timer);
74
+ done();
75
+ });
76
+ process.stdin.on("error", () => {
77
+ clearTimeout(timer);
78
+ resolve("");
79
+ });
80
+ });
81
+ }
82
+
83
+ // The pipeline without process concerns; returns a short summary (used by tests).
84
+ export async function processHookPayload({ agent, event, raw, now = Date.now(), fetchImpl }) {
85
+ const slug = AGENT_SLUGS[agent];
86
+ if (!slug) return { status: "unknown-agent" };
87
+ let payload;
88
+ try {
89
+ payload = JSON.parse(raw);
90
+ } catch {
91
+ return { status: "bad-json" };
92
+ }
93
+ // For the debug log only: which tool the agent reported (a name, never its input).
94
+ const reportedTool = String(payload?.tool_name ?? payload?.toolName ?? payload?.tool ?? payload?.hook_event_name ?? "")
95
+ .replace(/[^A-Za-z0-9_.:-]/g, "").slice(0, 64);
96
+ const normalized = normalizeHookPayload(slug, payload, event);
97
+ payload = null; // tool_response / outputs leave memory here; nothing below can reach them
98
+ if (!normalized.actions.length) return { status: "no-actions", reportedTool };
99
+
100
+ // The hook's own folder first; then where the commands actually ran (a workdir) or what they touched (absolute
101
+ // paths) — agents such as Codex often run from another folder against a repo by absolute path.
102
+ const candidates = [
103
+ normalized.cwd || process.cwd(),
104
+ ...normalized.actions.map((a) => a.cwd).filter(Boolean),
105
+ ...normalized.actions.flatMap((a) => (a.paths || []).filter((p) => path.isAbsolute(p)).map((p) => path.dirname(p))),
106
+ ];
107
+ let ws = null;
108
+ for (const dir of [...new Set(candidates)]) {
109
+ ws = resolveWorkspaceForDir(dir);
110
+ if (ws) break;
111
+ }
112
+ if (!ws) return { status: "unregistered-workspace" };
113
+
114
+ const state = readCausalState({ workspaceRoot: ws.root, now, hookSessionId: normalized.hookSessionId });
115
+ const parent = state && state.workspaceId === ws.workspaceId ? state : null;
116
+ const ctx = {
117
+ realRoot: ws.root,
118
+ clientAgent: slug,
119
+ // Unlinked events still say which agent session they came from, so the backend can group them.
120
+ mcpSessionId: parent?.mcpSessionId ?? (/^[A-Za-z0-9._:#-]{1,128}$/.test(normalized.hookSessionId || "") ? normalized.hookSessionId : null),
121
+ parentRequestId: parent?.lastHarmonyRequestId ?? null,
122
+ parentTraceId: parent?.lastTraceId ?? null,
123
+ now,
124
+ };
125
+ const events = (await Promise.all(normalized.actions.map((a) => buildWireEvent(a, ctx)))).filter(Boolean);
126
+ if (!events.length) return { status: "no-events" };
127
+
128
+ const key = readTelemetryKey();
129
+ const token = cachedUserToken();
130
+ if (!key || !token) {
131
+ spoolEvents(ws.endpoint, ws.workspaceId, events);
132
+ return { status: "spooled", reason: !key ? "no-telemetry-key" : "no-user-login", events };
133
+ }
134
+
135
+ let allAccepted = true;
136
+ const spooled = [];
137
+ for (const { events: batch, body } of batchBodies(events)) {
138
+ const res = await postToolEvents({ endpoint: ws.endpoint, workspaceId: ws.workspaceId, body, token, key, timeoutMs: POST_TIMEOUT_MS, fetchImpl });
139
+ if (res.outcome === "accepted") continue;
140
+ allAccepted = false;
141
+ if (res.outcome === "drop") {
142
+ hookLog(`dropped ${batch.length} events: HTTP ${res.status}`);
143
+ } else {
144
+ // 401 is retried by `serve`, which can re-fetch the key; 5xx/timeouts wait for the backend.
145
+ spoolEvents(ws.endpoint, ws.workspaceId, batch);
146
+ spooled.push(...batch);
147
+ }
148
+ }
149
+ if (allAccepted) {
150
+ await drainSpool({
151
+ endpoint: ws.endpoint,
152
+ getToken: async () => token,
153
+ getKey: async ({ refresh }) => (refresh ? null : key),
154
+ maxBatches: 1,
155
+ timeoutMs: POST_TIMEOUT_MS,
156
+ log: hookLog,
157
+ fetchImpl,
158
+ });
159
+ }
160
+ return { status: allAccepted ? "sent" : spooled.length ? "spooled" : "dropped", events };
161
+ }
162
+
163
+ export async function runHookEvent(argv) {
164
+ // stdout purity: nothing this process does may reach the host agent's hook output channel.
165
+ process.stdout.write = () => true;
166
+ console.log = console.info = console.debug = () => {};
167
+ const finish = () => process.exit(0);
168
+ process.on("uncaughtException", (error) => {
169
+ hookLog(`uncaught: ${error?.message || error}`);
170
+ finish();
171
+ });
172
+ process.on("unhandledRejection", (error) => {
173
+ hookLog(`unhandled: ${error?.message || error}`);
174
+ finish();
175
+ });
176
+ setTimeout(() => {
177
+ hookLog("watchdog: exceeded 2s, exiting");
178
+ finish();
179
+ }, WATCHDOG_MS);
180
+
181
+ try {
182
+ if (process.env.HARMONY_RSI_DISABLED === "true") return finish();
183
+ const { agent, event } = parseHookArgs(argv);
184
+ const raw = await readStdin();
185
+ if (!raw) return finish();
186
+ const result = await processHookPayload({ agent, event, raw });
187
+ // Debug logging: HARMONY_HOOK_DEBUG=true, or the file ~/.harmony/hook-debug (switchable without editing the
188
+ // hook command — Codex re-asks for trust whenever a hook command changes).
189
+ if (process.env.HARMONY_HOOK_DEBUG === "true" || fs.existsSync(harmonyPath("hook-debug"))) {
190
+ hookLog(`${agent}/${event || "-"}: ${result.status}${result.reason ? ` (${result.reason})` : ""}, ${result.events?.length ?? 0} events${result.reportedTool ? `, tool ${result.reportedTool}` : ""}`);
191
+ }
192
+ } catch (error) {
193
+ hookLog(`failed: ${error?.message || error}`);
194
+ }
195
+ finish();
196
+ }
@@ -0,0 +1,329 @@
1
+ // Per-agent hook payload normalizers (RSI MCP spec §5.2).
2
+ //
3
+ // Each takes the agent's raw hook JSON and returns { hookSessionId, cwd, actions } where every action is
4
+ // { escapeType, toolName, paths, cwd, lineSpan?, pattern?, fixed?, exitCode? }. Only tool *inputs* are read; tool
5
+ // output / response bodies are never touched beyond an exit status. Tools that are not search/read/edit/shell/
6
+ // compaction (including Harmony's own MCP tools) produce no actions.
7
+ import { patchTargetPaths, scrubShellCommand } from "./shellCommandScrubber.js";
8
+
9
+ const MAX_PATCH_FILES = 20;
10
+
11
+ export const AGENT_SLUGS = {
12
+ "claude-code": "claude-code",
13
+ claude: "claude-code",
14
+ codex: "codex-cli",
15
+ "codex-cli": "codex-cli",
16
+ cursor: "cursor",
17
+ antigravity: "antigravity",
18
+ gemini: "antigravity",
19
+ copilot: "copilot-cli",
20
+ "copilot-cli": "copilot-cli",
21
+ opencode: "opencode",
22
+ "kilo-code": "kilo-code",
23
+ kilo: "kilo-code",
24
+ };
25
+
26
+ function str(v) {
27
+ return typeof v === "string" && v ? v : null;
28
+ }
29
+
30
+ function int(v) {
31
+ const n = typeof v === "string" && /^-?\d+$/.test(v) ? Number(v) : v;
32
+ return Number.isInteger(n) ? n : null;
33
+ }
34
+
35
+ function firstString(obj, keys) {
36
+ for (const k of keys) {
37
+ const v = str(obj?.[k]);
38
+ if (v) return v;
39
+ }
40
+ return null;
41
+ }
42
+
43
+ const PATH_KEYS = ["file_path", "filePath", "target_file", "targetFile", "absolute_path", "path", "notebook_path"];
44
+
45
+ // Shell actions -> escape actions. `patch` (apply_patch run through the shell) is expanded from the command text.
46
+ function shellActions(command, cwd, exitCode) {
47
+ const out = [];
48
+ for (const a of scrubShellCommand(command, cwd)) {
49
+ if (a.type === "search") out.push({ escapeType: "SEARCH", toolName: a.toolName, pattern: a.pattern, fixed: a.fixed, paths: a.paths, cwd: a.cwd, exitCode });
50
+ else if (a.type === "read") out.push({ escapeType: "READ", toolName: a.toolName, paths: a.paths, lineSpan: a.lineSpan, cwd: a.cwd });
51
+ else if (a.type === "edit") for (const p of a.paths.slice(0, MAX_PATCH_FILES)) out.push({ escapeType: "EDIT", toolName: a.toolName, paths: [p], cwd: a.cwd });
52
+ else if (a.type === "build") out.push({ escapeType: "BUILD", toolName: a.toolName, paths: [], cwd: a.cwd, exitCode });
53
+ else if (a.type === "patch") out.push(...patchActions(command, a.cwd));
54
+ }
55
+ return out;
56
+ }
57
+
58
+ function patchActions(patchText, cwd) {
59
+ return patchTargetPaths(patchText)
60
+ .slice(0, MAX_PATCH_FILES)
61
+ .map((p) => ({ escapeType: "EDIT", toolName: "apply_patch", paths: [p], cwd }));
62
+ }
63
+
64
+ function commandText(input) {
65
+ const c = input?.command ?? input?.cmd;
66
+ if (Array.isArray(c)) {
67
+ // ["bash", "-lc", "rg foo"] -> the script; otherwise argv joined.
68
+ const idx = c.findIndex((x) => x === "-c" || x === "-lc");
69
+ return idx >= 0 && typeof c[idx + 1] === "string" ? c[idx + 1] : c.filter((x) => typeof x === "string").join(" ");
70
+ }
71
+ return str(c);
72
+ }
73
+
74
+ function readSpan(offset, limit) {
75
+ const start = int(offset);
76
+ const len = int(limit);
77
+ if (start === null && len === null) return null;
78
+ const s = start && start > 0 ? start : 1;
79
+ return len && len > 0 ? [s, s + len - 1] : null;
80
+ }
81
+
82
+ // ---- Claude Code ----
83
+ function claudeCode(p, eventArg) {
84
+ const event = str(p.hook_event_name) || eventArg;
85
+ const cwd = str(p.cwd);
86
+ const base = { hookSessionId: str(p.session_id), cwd };
87
+ if (event === "PreCompact") return { ...base, actions: [{ escapeType: "COMPACT", toolName: "PreCompact", paths: [], cwd }] };
88
+ if (event !== "PostToolUse" && event !== "PostToolUseFailure") return { ...base, actions: [] };
89
+ const tool = str(p.tool_name) || "";
90
+ const input = p.tool_input || {};
91
+ const failed = event === "PostToolUseFailure";
92
+ switch (tool) {
93
+ case "Grep":
94
+ return { ...base, actions: [{ escapeType: "SEARCH", toolName: "Grep", pattern: str(input.pattern), paths: [input.path].filter(Boolean), cwd }] };
95
+ case "Glob":
96
+ return { ...base, actions: [{ escapeType: "SEARCH", toolName: "Glob", pattern: str(input.pattern), paths: [input.path].filter(Boolean), cwd }] };
97
+ case "Read":
98
+ return { ...base, actions: [{ escapeType: "READ", toolName: "Read", paths: [input.file_path].filter(Boolean), lineSpan: readSpan(input.offset, input.limit), cwd }] };
99
+ case "Edit":
100
+ case "MultiEdit":
101
+ case "Write":
102
+ case "NotebookEdit":
103
+ if (failed) return { ...base, actions: [] };
104
+ return { ...base, actions: [{ escapeType: "EDIT", toolName: tool, paths: [firstString(input, PATH_KEYS)].filter(Boolean), cwd }] };
105
+ case "Bash": {
106
+ // Claude Code reports a non-zero exit as PostToolUseFailure; an explicit integer wins when present.
107
+ const explicit = int(p.tool_response?.exit_code ?? p.tool_response?.exitCode);
108
+ return { ...base, actions: shellActions(str(input.command), cwd, explicit ?? (failed ? 1 : 0)) };
109
+ }
110
+ default:
111
+ return { ...base, actions: [] };
112
+ }
113
+ }
114
+
115
+ // ---- OpenAI Codex ----
116
+ function codex(p, eventArg) {
117
+ const event = str(p.hook_event_name) || eventArg;
118
+ const cwd = str(p.cwd);
119
+ const base = { hookSessionId: str(p.session_id), cwd };
120
+ if (event === "PreCompact") return { ...base, actions: [{ escapeType: "COMPACT", toolName: "PreCompact", paths: [], cwd }] };
121
+ if (event !== "PostToolUse") return { ...base, actions: [] };
122
+ const tool = str(p.tool_name) || "";
123
+ const input = p.tool_input || {};
124
+ const exitCode = int(p.tool_response?.exit_code ?? p.tool_response?.exitCode ?? p.exit_code);
125
+ if (tool === "apply_patch") {
126
+ const patch = typeof input === "string" ? input : firstString(input, ["input", "patch", "command"]);
127
+ return { ...base, actions: patchActions(patch, cwd) };
128
+ }
129
+ if (["shell", "Bash", "bash", "exec_command", "local_shell", "container.exec", "unified_exec"].includes(tool)) {
130
+ const cmd = commandText(input);
131
+ if (cmd && cmd.includes("*** Begin Patch")) return { ...base, actions: patchActions(cmd, str(input.workdir) || cwd) };
132
+ return { ...base, actions: shellActions(cmd, str(input.workdir) || cwd, exitCode) };
133
+ }
134
+ // Code mode: Codex runs one JavaScript tool ("exec") whose script calls tools.exec_command({cmd, workdir}),
135
+ // tools.apply_patch(...) and MCP tools. Only the shell commands and patch headers are read out of the script.
136
+ if (CODE_MODE_TOOLS.has(tool)) {
137
+ const code = typeof input === "string" ? input : firstString(input, ["code", "input", "script", "source"]);
138
+ return { ...base, actions: codeModeActions(code, cwd) };
139
+ }
140
+ return { ...base, actions: [] };
141
+ }
142
+
143
+ const CODE_MODE_TOOLS = new Set(["exec", "js", "javascript", "code", "code_mode", "run_code"]);
144
+ const MAX_CODE_CHARS = 64_000;
145
+
146
+ // The value of a JS string literal ('…', "…" or `…` without interpolation), or null.
147
+ function jsString(quote, body) {
148
+ if (quote === "`" && body.includes("${")) return null;
149
+ return body.replace(/\\(u[0-9a-fA-F]{4}|x[0-9a-fA-F]{2}|.)/gs, (_, e) =>
150
+ e[0] === "u" || e[0] === "x" ? String.fromCharCode(parseInt(e.slice(1), 16))
151
+ : e === "n" ? "\n" : e === "t" ? "\t" : e === "r" ? "\r" : e);
152
+ }
153
+
154
+ function codeModeActions(code, cwd) {
155
+ if (typeof code !== "string" || !code) return [];
156
+ const src = code.slice(0, MAX_CODE_CHARS);
157
+ const out = [];
158
+ const literal = (key, text) => {
159
+ // Key may be bare (cmd:) or quoted ("cmd":), as Codex writes both.
160
+ const m = new RegExp(`(?:\\b|["'])${key}["']?\\s*:\\s*(["'\`])((?:\\\\.|(?!\\1)[^\\\\])*)\\1`, "s").exec(text);
161
+ return m ? jsString(m[1], m[2]) : null;
162
+ };
163
+ // Each exec_command({...}) call: its argument object runs to the first "})" (commands rarely contain it).
164
+ const callRe = /exec_command\s*\(\s*\{/g;
165
+ let m;
166
+ while ((m = callRe.exec(src)) && out.length < MAX_PATCH_FILES) {
167
+ const end = src.indexOf("})", m.index);
168
+ const args = src.slice(m.index, end < 0 ? src.length : end + 2);
169
+ const cmd = literal("cmd", args) ?? literal("command", args);
170
+ if (!cmd) continue;
171
+ const workdir = literal("workdir", args) || cwd;
172
+ if (cmd.includes("*** Begin Patch")) out.push(...patchActions(cmd, workdir));
173
+ else out.push(...shellActions(cmd, workdir, null));
174
+ }
175
+ if (/apply_patch\s*\(/.test(src) && src.includes("*** Begin Patch")) out.push(...patchActions(jsString('"', src) ?? src, cwd));
176
+ return out;
177
+ }
178
+
179
+ // ---- Cursor ----
180
+ function cursor(p, eventArg) {
181
+ const event = str(p.hook_event_name) || eventArg;
182
+ const cwd = str(p.cwd) || (Array.isArray(p.workspace_roots) && str(p.workspace_roots[0])) || null;
183
+ const base = { hookSessionId: str(p.conversation_id) || str(p.session_id), cwd };
184
+ if (event === "preCompact") return { ...base, actions: [{ escapeType: "COMPACT", toolName: "preCompact", paths: [], cwd }] };
185
+ if (event !== "postToolUse") return { ...base, actions: [] };
186
+ const tool = str(p.tool_name) || "";
187
+ const input = p.tool_input || {};
188
+ const file = firstString(input, PATH_KEYS);
189
+ if (/^(read_file|read)$/i.test(tool)) {
190
+ const span = int(input.start_line_one_indexed) && int(input.end_line_one_indexed_inclusive)
191
+ ? [int(input.start_line_one_indexed), int(input.end_line_one_indexed_inclusive)]
192
+ : readSpan(input.offset, input.limit);
193
+ return { ...base, actions: [{ escapeType: "READ", toolName: tool, paths: [file].filter(Boolean), lineSpan: span, cwd }] };
194
+ }
195
+ if (/^(edit_file|write|search_replace|multi_edit|edit|apply_patch|delete_file)$/i.test(tool)) {
196
+ return { ...base, actions: [{ escapeType: "EDIT", toolName: tool, paths: [file].filter(Boolean), cwd }] };
197
+ }
198
+ if (/^(grep|glob|grep_search|file_search|glob_file_search|codebase_search|ripgrep)$/i.test(tool)) {
199
+ const pattern = firstString(input, ["pattern", "query", "glob_pattern", "regex"]);
200
+ return { ...base, actions: [{ escapeType: "SEARCH", toolName: tool, pattern, paths: [input.path, input.target_directory].filter(Boolean), cwd }] };
201
+ }
202
+ if (/^(run_terminal_cmd|shell|terminal)$/i.test(tool)) {
203
+ return { ...base, actions: shellActions(commandText(input), cwd, int(input.exit_code)) };
204
+ }
205
+ return { ...base, actions: [] };
206
+ }
207
+
208
+ // ---- Google Antigravity / Gemini CLI ----
209
+ function antigravity(p, eventArg) {
210
+ const event = str(p.hook_event_name) || eventArg;
211
+ const cwd = str(p.cwd);
212
+ const base = { hookSessionId: str(p.session_id), cwd };
213
+ if (event === "PreCompress" || event === "PreCompact") return { ...base, actions: [{ escapeType: "COMPACT", toolName: event, paths: [], cwd }] };
214
+ if (event !== "AfterTool" && event !== "PostToolUse") return { ...base, actions: [] };
215
+ const tool = str(p.tool_name) || "";
216
+ const input = p.tool_input || {};
217
+ if (tool === "read_file" || tool === "view_file") {
218
+ return { ...base, actions: [{ escapeType: "READ", toolName: tool, paths: [firstString(input, PATH_KEYS)].filter(Boolean), lineSpan: readSpan(input.offset, input.limit), cwd }] };
219
+ }
220
+ if (tool === "read_many_files") {
221
+ const paths = Array.isArray(input.paths) ? input.paths.filter((x) => typeof x === "string") : [];
222
+ return { ...base, actions: [{ escapeType: "READ", toolName: tool, paths, cwd }] };
223
+ }
224
+ if (tool === "write_file" || tool === "replace" || tool === "edit" || tool === "edit_file") {
225
+ return { ...base, actions: [{ escapeType: "EDIT", toolName: tool, paths: [firstString(input, PATH_KEYS)].filter(Boolean), cwd }] };
226
+ }
227
+ if (tool === "search_file_content" || tool === "grep" || tool === "glob" || tool === "find_by_name" || tool === "grep_search") {
228
+ return { ...base, actions: [{ escapeType: "SEARCH", toolName: tool, pattern: firstString(input, ["pattern", "query"]), paths: [input.path, input.dir_path].filter(Boolean), cwd }] };
229
+ }
230
+ if (tool === "run_shell_command" || tool === "run_command") {
231
+ return { ...base, actions: shellActions(commandText(input), str(input.directory) || cwd, int(p.tool_response?.exit_code)) };
232
+ }
233
+ return { ...base, actions: [] };
234
+ }
235
+
236
+ // ---- GitHub Copilot CLI ----
237
+ // camelCase payload (event key `postToolUse`, what setup-agents installs); the VS Code-compatible PascalCase form
238
+ // (`PostToolUse`: tool_name / tool_input / tool_result.result_type) is mapped onto it.
239
+ function copilot(p, eventArg) {
240
+ if (p.hook_event_name === "PostToolUse" || (p.tool_name && !p.toolName)) {
241
+ p = {
242
+ ...p,
243
+ hook_event_name: "postToolUse",
244
+ toolName: p.tool_name,
245
+ toolArgs: p.tool_input,
246
+ toolResult: { resultType: p.tool_result?.result_type },
247
+ sessionId: p.session_id,
248
+ };
249
+ }
250
+ const event = str(p.hook_event_name) || eventArg || "postToolUse";
251
+ const cwd = str(p.cwd);
252
+ const base = { hookSessionId: str(p.session_id) || str(p.sessionId), cwd };
253
+ if (event !== "postToolUse") return { ...base, actions: [] };
254
+ let args = p.toolArgs;
255
+ if (typeof args === "string") {
256
+ try {
257
+ args = JSON.parse(args);
258
+ } catch {
259
+ args = {};
260
+ }
261
+ }
262
+ args = args || {};
263
+ const tool = str(p.toolName) || "";
264
+ const resultType = str(p.toolResult?.resultType);
265
+ const exitCode = resultType === "success" ? 0 : resultType === "failure" ? 1 : null;
266
+ if (tool === "view") {
267
+ const r = Array.isArray(args.view_range) ? args.view_range.map(int) : null;
268
+ const span = r && r[0] && r[1] && r[1] > 0 ? [r[0], r[1]] : null;
269
+ return { ...base, actions: [{ escapeType: "READ", toolName: tool, paths: [str(args.path)].filter(Boolean), lineSpan: span, cwd }] };
270
+ }
271
+ if (tool === "edit" || tool === "create" || tool === "str_replace" || tool === "write") {
272
+ if (resultType && resultType !== "success") return { ...base, actions: [] };
273
+ return { ...base, actions: [{ escapeType: "EDIT", toolName: tool, paths: [firstString(args, PATH_KEYS)].filter(Boolean), cwd }] };
274
+ }
275
+ if (tool === "grep" || tool === "glob") {
276
+ return { ...base, actions: [{ escapeType: "SEARCH", toolName: tool, pattern: str(args.pattern), paths: [args.path].filter(Boolean), cwd, exitCode }] };
277
+ }
278
+ if (tool === "bash" || tool === "powershell" || tool === "shell") {
279
+ return { ...base, actions: shellActions(str(args.command), cwd, exitCode) };
280
+ }
281
+ return { ...base, actions: [] };
282
+ }
283
+
284
+ // ---- OpenCode / Kilo Code (payload built by Harmony's own plugin: { sessionID, tool, args, directory, event }) ----
285
+ function openCode(p, eventArg) {
286
+ const event = str(p.event) || eventArg || "tool.execute.after";
287
+ const cwd = str(p.directory) || str(p.cwd);
288
+ const base = { hookSessionId: str(p.sessionID), cwd };
289
+ if (event === "session.compacted") return { ...base, actions: [{ escapeType: "COMPACT", toolName: "session.compacted", paths: [], cwd }] };
290
+ if (event !== "tool.execute.after") return { ...base, actions: [] };
291
+ const tool = str(p.tool) || "";
292
+ const args = p.args || {};
293
+ if (tool === "read") {
294
+ return { ...base, actions: [{ escapeType: "READ", toolName: tool, paths: [firstString(args, PATH_KEYS)].filter(Boolean), lineSpan: readSpan(args.offset, args.limit), cwd }] };
295
+ }
296
+ if (tool === "edit" || tool === "write" || tool === "multiedit") {
297
+ return { ...base, actions: [{ escapeType: "EDIT", toolName: tool, paths: [firstString(args, PATH_KEYS)].filter(Boolean), cwd }] };
298
+ }
299
+ if (tool === "patch" || tool === "apply_patch") {
300
+ return { ...base, actions: patchActions(firstString(args, ["patchText", "patch", "input"]), cwd) };
301
+ }
302
+ if (tool === "grep" || tool === "glob") {
303
+ return { ...base, actions: [{ escapeType: "SEARCH", toolName: tool, pattern: str(args.pattern), paths: [args.path].filter(Boolean), cwd }] };
304
+ }
305
+ if (tool === "bash") return { ...base, actions: shellActions(str(args.command), cwd, null) };
306
+ return { ...base, actions: [] };
307
+ }
308
+
309
+ const NORMALIZERS = {
310
+ "claude-code": claudeCode,
311
+ "codex-cli": codex,
312
+ cursor,
313
+ antigravity,
314
+ "copilot-cli": copilot,
315
+ opencode: openCode,
316
+ "kilo-code": openCode,
317
+ };
318
+
319
+ // Never throws: a payload the normalizer does not understand yields no actions.
320
+ export function normalizeHookPayload(agentSlug, payload, eventArg) {
321
+ const fn = NORMALIZERS[agentSlug];
322
+ if (!fn || !payload || typeof payload !== "object") return { hookSessionId: null, cwd: null, actions: [] };
323
+ try {
324
+ const result = fn(payload, eventArg);
325
+ return { ...result, actions: result.actions.filter((a) => a.escapeType) };
326
+ } catch {
327
+ return { hookSessionId: null, cwd: null, actions: [] };
328
+ }
329
+ }
@@ -0,0 +1,104 @@
1
+ // Bounded offline spool for tool events (RSI MCP spec §5.5): ~/.harmony/spool/ws-{workspaceId}-events.jsonl.
2
+ //
3
+ // Each line is { endpoint, workspaceId, event } — unsigned; batches are signed when sent (wire contract §3.2.6).
4
+ // Appends are single small O_APPEND writes, safe across concurrent hook processes. Over 2 MiB the oldest 25% of
5
+ // lines are dropped. A drain claims the file by renaming it, so appends that race the drain land in a fresh file.
6
+ import fs from "fs";
7
+ import path from "path";
8
+
9
+ import { atomicWriteFile, ensurePrivateDir, harmonyPath } from "../localState.js";
10
+
11
+ export const SPOOL_MAX_BYTES = 2 * 1024 * 1024;
12
+ export const DRAIN_BATCH_SIZE = 50;
13
+
14
+ export function spoolDir() {
15
+ return harmonyPath("spool");
16
+ }
17
+
18
+ export function spoolPath(workspaceId) {
19
+ const safe = String(workspaceId).replace(/[^A-Za-z0-9_-]/g, "_");
20
+ return path.join(spoolDir(), `ws-${safe}-events.jsonl`);
21
+ }
22
+
23
+ // Drops the oldest 25% of lines, repeatedly, until the file is back under the cap (one big append can need more
24
+ // than one round).
25
+ function trimOldest(file) {
26
+ let lines = fs.readFileSync(file, "utf8").split("\n").filter(Boolean);
27
+ let size = Buffer.byteLength(lines.join("\n")) + 1;
28
+ while (lines.length && size > SPOOL_MAX_BYTES) {
29
+ lines = lines.slice(Math.ceil(lines.length * 0.25));
30
+ size = Buffer.byteLength(lines.join("\n")) + 1;
31
+ }
32
+ atomicWriteFile(file, lines.length ? `${lines.join("\n")}\n` : "");
33
+ }
34
+
35
+ export function spoolEvents(endpoint, workspaceId, events) {
36
+ if (!events.length) return;
37
+ ensurePrivateDir(spoolDir());
38
+ const file = spoolPath(workspaceId);
39
+ const data = events.map((event) => JSON.stringify({ endpoint, workspaceId: String(workspaceId), event })).join("\n") + "\n";
40
+ const fd = fs.openSync(file, "a", 0o600);
41
+ try {
42
+ fs.writeSync(fd, data);
43
+ } finally {
44
+ fs.closeSync(fd);
45
+ }
46
+ if (fs.statSync(file).size > SPOOL_MAX_BYTES) trimOldest(file);
47
+ }
48
+
49
+ export function listSpoolFiles() {
50
+ try {
51
+ return fs.readdirSync(spoolDir()).filter((n) => /^ws-[A-Za-z0-9_-]+-events\.jsonl$/.test(n)).map((n) => path.join(spoolDir(), n));
52
+ } catch {
53
+ return [];
54
+ }
55
+ }
56
+
57
+ export function spoolBacklog() {
58
+ let count = 0;
59
+ for (const file of listSpoolFiles()) {
60
+ try {
61
+ count += fs.readFileSync(file, "utf8").split("\n").filter(Boolean).length;
62
+ } catch {
63
+ // ignore
64
+ }
65
+ }
66
+ return count;
67
+ }
68
+
69
+ // Takes all lines out of a spool file. Returns [] if another process claimed it first.
70
+ export function claimSpool(file) {
71
+ const claimed = `${file}.draining-${process.pid}-${Date.now()}`;
72
+ try {
73
+ fs.renameSync(file, claimed);
74
+ } catch {
75
+ return [];
76
+ }
77
+ try {
78
+ return fs
79
+ .readFileSync(claimed, "utf8")
80
+ .split("\n")
81
+ .filter(Boolean)
82
+ .map((line) => {
83
+ try {
84
+ return JSON.parse(line);
85
+ } catch {
86
+ return null;
87
+ }
88
+ })
89
+ .filter((rec) => rec?.event && rec.endpoint && rec.workspaceId);
90
+ } finally {
91
+ fs.rmSync(claimed, { force: true });
92
+ }
93
+ }
94
+
95
+ // Puts records that were not sent back into their spool.
96
+ export function requeue(records) {
97
+ const byWorkspace = new Map();
98
+ for (const rec of records) {
99
+ const key = `${rec.workspaceId}\u0000${rec.endpoint}`;
100
+ if (!byWorkspace.has(key)) byWorkspace.set(key, { endpoint: rec.endpoint, workspaceId: rec.workspaceId, events: [] });
101
+ byWorkspace.get(key).events.push(rec.event);
102
+ }
103
+ for (const { endpoint, workspaceId, events } of byWorkspace.values()) spoolEvents(endpoint, workspaceId, events);
104
+ }
@@ -0,0 +1,50 @@
1
+ // Client-side secret detection for anything a hook might send (RSI MCP spec §5.3, §9.2). Conservative by design:
2
+ // a false positive only costs a redacted search hint, a false negative leaks a secret.
3
+
4
+ const SECRET_PATTERNS = [
5
+ /\bsk-[A-Za-z0-9_-]{8,}/, // OpenAI / Anthropic style
6
+ /\b(?:sk|rk|pk)_(?:live|test)_[A-Za-z0-9]{8,}/, // Stripe
7
+ /\b(?:AKIA|ASIA|AGPA|AIDA|AROA)[0-9A-Z]{12,}/, // AWS access key ids
8
+ /\bgh[pousr]_[A-Za-z0-9]{16,}/, // GitHub tokens
9
+ /\bgithub_pat_[A-Za-z0-9_]{16,}/,
10
+ /\bglpat-[A-Za-z0-9_-]{12,}/, // GitLab
11
+ /\bxox[abposr]-[A-Za-z0-9-]{8,}/, // Slack
12
+ /\bAIza[0-9A-Za-z_-]{20,}/, // Google API keys
13
+ /\beyJ[A-Za-z0-9_-]{8,}\.?/, // JWT / base64 JSON
14
+ /-----BEGIN [A-Z ]*PRIVATE KEY/,
15
+ /[a-z][a-z0-9+.-]*:\/\/[^\s/:@]+:[^\s/@]+@/i, // URL with user:password
16
+ /\b(?:bearer|basic)\s+[A-Za-z0-9._~+/=-]{12,}/i,
17
+ /\b[A-Za-z_][A-Za-z0-9_]*\s*=\s*['"]?[^\s'"=]{4,}/, // KEY=VAL assignments (not ==)
18
+ ];
19
+
20
+ const ENTROPY_THRESHOLD_BITS = 4.2;
21
+ const ENTROPY_MIN_LENGTH = 16;
22
+
23
+ export function shannonEntropy(text) {
24
+ if (!text) return 0;
25
+ const counts = new Map();
26
+ for (const ch of text) counts.set(ch, (counts.get(ch) || 0) + 1);
27
+ let bits = 0;
28
+ const n = text.length;
29
+ for (const count of counts.values()) {
30
+ const p = count / n;
31
+ bits -= p * Math.log2(p);
32
+ }
33
+ return bits;
34
+ }
35
+
36
+ function highEntropy(text) {
37
+ return text.length >= ENTROPY_MIN_LENGTH && shannonEntropy(text) > ENTROPY_THRESHOLD_BITS;
38
+ }
39
+
40
+ // True when the text contains, or is, something that looks like a credential.
41
+ export function looksSecret(text) {
42
+ if (typeof text !== "string" || !text) return false;
43
+ if (SECRET_PATTERNS.some((pattern) => pattern.test(text))) return true;
44
+ if (highEntropy(text)) return true;
45
+ // A secret embedded in a longer pattern or path: check each long token on its own.
46
+ for (const token of text.split(/[^A-Za-z0-9+/=_-]+/)) {
47
+ if (highEntropy(token)) return true;
48
+ }
49
+ return false;
50
+ }