@codeconductorai/harmony-mcp 1.0.33 → 1.0.35
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/README.md +217 -15
- package/package.json +4 -2
- package/src/{deviceAuth.js → auth/deviceAuth.js} +39 -8
- package/src/{harmonyClient.js → backend/harmonyClient.js} +183 -13
- package/src/doctor/doctorCommand.js +385 -0
- package/src/index.js +18 -5
- package/src/{telemetry.js → observability/telemetry.js} +3 -3
- package/src/rsi/bundleHints.js +181 -0
- package/src/rsi/bundleRefresher.js +95 -0
- package/src/rsi/callContext.js +49 -0
- package/src/rsi/causalState.js +103 -0
- package/src/rsi/clientAgent.js +58 -0
- package/src/rsi/hooks/eventBuilder.js +129 -0
- package/src/rsi/hooks/fileHash.js +33 -0
- package/src/rsi/hooks/hmacSigner.js +69 -0
- package/src/rsi/hooks/hookEventCommand.js +196 -0
- package/src/rsi/hooks/normalizers.js +329 -0
- package/src/rsi/hooks/offlineSpooler.js +142 -0
- package/src/rsi/hooks/secretScrubber.js +50 -0
- package/src/rsi/hooks/shellCommandScrubber.js +449 -0
- package/src/rsi/hooks/spoolDrainer.js +78 -0
- package/src/rsi/hooks/toolEventsClient.js +70 -0
- package/src/rsi/localState.js +53 -0
- package/src/rsi/serveTelemetry.js +101 -0
- package/src/rsi/workspaceRegistry.js +63 -0
- package/src/{server.js → server/server.js} +107 -17
- package/src/{serverInstructions.js → server/serverInstructions.js} +2 -2
- package/src/server/serverMain.js +46 -0
- package/src/{sessionIdentity.js → session/sessionIdentity.js} +10 -6
- package/src/setup/agentCapabilityMatrix.js +425 -0
- package/src/setup/agentsGuide.js +28 -0
- package/src/setup/configMergers.js +272 -0
- package/src/{installer.js → setup/installer.js} +1 -1
- package/src/setup/setupAgentsCommand.js +192 -0
- package/src/setup/shim.js +80 -0
- package/src/sync/managedMarkdownInjector.js +103 -0
- package/src/sync/syncWorkspaceCommand.js +143 -0
- package/src/sync/workspaceSync.js +88 -0
- package/src/{fileWatcher.js → workspace/fileWatcher.js} +2 -2
- package/src/{workspaceIdentity.js → workspace/workspaceIdentity.js} +1 -1
- package/src/agentsGuide.js +0 -38
- package/src/serverMain.js +0 -32
- /package/src/{log.js → observability/log.js} +0 -0
- /package/src/{toolSchemas.js → server/toolSchemas.js} +0 -0
- /package/src/{fileFilters.js → workspace/fileFilters.js} +0 -0
- /package/src/{repoIdentity.js → workspace/repoIdentity.js} +0 -0
- /package/src/{workspaceMarker.js → workspace/workspaceMarker.js} +0 -0
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
// Telemetry key + X-Harmony-Hook-Signature (RSI wire contract §3.2, §4).
|
|
2
|
+
// The key is 32 bytes kept as 64 lowercase hex in ~/.harmony/telemetry.key (0600). It is never logged.
|
|
3
|
+
// Keys are issued per backend, so ~/.harmony/telemetry.key.endpoint records which backend issued it: a key from
|
|
4
|
+
// another backend (say, local dev after testing against prod) is never trusted by the MCP server, which fetches a
|
|
5
|
+
// fresh one. A key file without that record (written by 1.0.34 or earlier) is treated as "issuer unknown".
|
|
6
|
+
import crypto from "crypto";
|
|
7
|
+
import fs from "fs";
|
|
8
|
+
|
|
9
|
+
import { atomicWriteFile, harmonyPath } from "../localState.js";
|
|
10
|
+
|
|
11
|
+
const KEY_HEX = /^[0-9a-f]{64}$/;
|
|
12
|
+
|
|
13
|
+
export function telemetryKeyPath() {
|
|
14
|
+
return harmonyPath("telemetry.key");
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function endpointPath() {
|
|
18
|
+
return harmonyPath("telemetry.key.endpoint");
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function normEndpoint(endpoint) {
|
|
22
|
+
return String(endpoint || "").trim().replace(/\/+$/, "").toLowerCase();
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
// The backend that issued the stored key, or null when unknown (no key, or a key written before 1.0.35).
|
|
26
|
+
export function telemetryKeyEndpoint() {
|
|
27
|
+
try {
|
|
28
|
+
return normEndpoint(fs.readFileSync(endpointPath(), "utf8")) || null;
|
|
29
|
+
} catch {
|
|
30
|
+
return null;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// Whether the stored key was issued by this backend: true, false (another backend), or null (issuer unknown).
|
|
35
|
+
export function telemetryKeyMatches(endpoint) {
|
|
36
|
+
const issuer = telemetryKeyEndpoint();
|
|
37
|
+
return issuer === null ? null : issuer === normEndpoint(endpoint);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// The key bytes, or null when there is no valid key file — or, with `endpoint`, when the key is known to come from
|
|
41
|
+
// another backend (it would only earn 401s there).
|
|
42
|
+
export function readTelemetryKey(endpoint = null) {
|
|
43
|
+
if (endpoint && telemetryKeyMatches(endpoint) === false) return null;
|
|
44
|
+
try {
|
|
45
|
+
const hex = fs.readFileSync(telemetryKeyPath(), "utf8").trim().toLowerCase();
|
|
46
|
+
return KEY_HEX.test(hex) ? Buffer.from(hex, "hex") : null;
|
|
47
|
+
} catch {
|
|
48
|
+
return null;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function writeTelemetryKey(hex, endpoint = null) {
|
|
53
|
+
const clean = String(hex || "").trim().toLowerCase();
|
|
54
|
+
if (!KEY_HEX.test(clean)) throw new Error("telemetry key must be 64 lowercase hex chars");
|
|
55
|
+
atomicWriteFile(telemetryKeyPath(), `${clean}\n`, 0o600);
|
|
56
|
+
if (endpoint) atomicWriteFile(endpointPath(), `${normEndpoint(endpoint)}\n`, 0o600);
|
|
57
|
+
else fs.rmSync(endpointPath(), { force: true });
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export function telemetryKeyId(keyBytes) {
|
|
61
|
+
return `tk_${crypto.createHash("sha256").update(keyBytes).digest("hex").slice(0, 16)}`;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// Headers for one tool-events request. `rawBody` must be the exact string sent.
|
|
65
|
+
export function signBatch(keyBytes, rawBody, timestampMs = Date.now()) {
|
|
66
|
+
const timestamp = String(timestampMs);
|
|
67
|
+
const mac = crypto.createHmac("sha256", keyBytes).update(`${timestamp}.`).update(rawBody, "utf8").digest("hex");
|
|
68
|
+
return { "X-Harmony-Hook-Timestamp": timestamp, "X-Harmony-Hook-Signature": `sha256=${mac}` };
|
|
69
|
+
}
|
|
@@ -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(ws.endpoint);
|
|
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
|
+
}
|