@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,272 @@
|
|
|
1
|
+
// Lossless config edits for host agents (RSI MCP spec §1 invariant 5, §6.2).
|
|
2
|
+
//
|
|
3
|
+
// JSON / JSONC files are edited with jsonc-parser's modify/applyEdits: only the touched value changes, so comments,
|
|
4
|
+
// key order, formatting and every user hook or server stay exactly as they were. TOML is edited only by adding or
|
|
5
|
+
// removing a block between Harmony marker comments. Every write is atomic (temp -> fsync -> rename), keeps the
|
|
6
|
+
// file's mode, and backs the original up once to <file>.harmony-bak.
|
|
7
|
+
import crypto from "crypto";
|
|
8
|
+
import fs from "fs";
|
|
9
|
+
import path from "path";
|
|
10
|
+
import { applyEdits, modify, parse, printParseErrorCode } from "jsonc-parser";
|
|
11
|
+
|
|
12
|
+
// ---------- files ----------
|
|
13
|
+
|
|
14
|
+
export function readText(file) {
|
|
15
|
+
try {
|
|
16
|
+
return fs.readFileSync(file, "utf8");
|
|
17
|
+
} catch {
|
|
18
|
+
return null;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function writeConfigAtomic(file, text) {
|
|
23
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
24
|
+
let mode = 0o644;
|
|
25
|
+
if (fs.existsSync(file)) {
|
|
26
|
+
mode = fs.statSync(file).mode & 0o777;
|
|
27
|
+
const backup = `${file}.harmony-bak`;
|
|
28
|
+
if (!fs.existsSync(backup)) fs.copyFileSync(file, backup);
|
|
29
|
+
}
|
|
30
|
+
const tmp = `${file}.${process.pid}.${crypto.randomBytes(4).toString("hex")}.tmp`;
|
|
31
|
+
const fd = fs.openSync(tmp, "w", mode);
|
|
32
|
+
try {
|
|
33
|
+
fs.writeSync(fd, text);
|
|
34
|
+
fs.fsyncSync(fd);
|
|
35
|
+
} finally {
|
|
36
|
+
fs.closeSync(fd);
|
|
37
|
+
}
|
|
38
|
+
fs.renameSync(tmp, file);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function removeFile(file) {
|
|
42
|
+
if (!fs.existsSync(file)) return false;
|
|
43
|
+
fs.rmSync(file);
|
|
44
|
+
return true;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// ---------- JSONC ----------
|
|
48
|
+
|
|
49
|
+
export class InvalidConfigError extends Error {}
|
|
50
|
+
|
|
51
|
+
// Parses JSON with comments / trailing commas. Throws InvalidConfigError rather than guessing at a broken file.
|
|
52
|
+
export function parseJsonc(text, file = "config") {
|
|
53
|
+
if (text === null || text.trim() === "") return {};
|
|
54
|
+
const errors = [];
|
|
55
|
+
const value = parse(text, errors, { allowTrailingComma: true, disallowComments: false });
|
|
56
|
+
if (errors.length) {
|
|
57
|
+
throw new InvalidConfigError(`${file}: ${printParseErrorCode(errors[0].error)} at offset ${errors[0].offset}`);
|
|
58
|
+
}
|
|
59
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
60
|
+
throw new InvalidConfigError(`${file}: top level is not an object`);
|
|
61
|
+
}
|
|
62
|
+
return value;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function formattingFor(text) {
|
|
66
|
+
const indented = /\n([ \t]+)\S/.exec(text || "");
|
|
67
|
+
if (indented && indented[1].startsWith("\t")) return { insertSpaces: false, tabSize: 1, eol: "\n" };
|
|
68
|
+
return { insertSpaces: true, tabSize: indented ? indented[1].length : 2, eol: text?.includes("\r\n") ? "\r\n" : "\n" };
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// Sets (or, with value === undefined, removes) the value at jsonPath. Starts "{}" for a missing/empty file.
|
|
72
|
+
export function jsoncSet(text, jsonPath, value, { insertAt } = {}) {
|
|
73
|
+
const base = text === null || text.trim() === "" ? "{}\n" : text;
|
|
74
|
+
const p = insertAt === undefined ? jsonPath : [...jsonPath, insertAt];
|
|
75
|
+
const edits = modify(base, p, value, {
|
|
76
|
+
formattingOptions: formattingFor(text),
|
|
77
|
+
isArrayInsertion: insertAt !== undefined,
|
|
78
|
+
});
|
|
79
|
+
return applyEdits(base, edits);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// ---------- Harmony hook detection ----------
|
|
83
|
+
|
|
84
|
+
// Spec §6.2.2 dedup key: an entry whose command runs `harmony-mcp ... hook-event`, or the SessionStart hook that
|
|
85
|
+
// setup-agents itself added (through the ~/.harmony/bin launcher). Session hooks added some other way — e.g. by
|
|
86
|
+
// `harmony-mcp install` as `npx … --session-hook` — are the user's, and are never updated or removed here.
|
|
87
|
+
export function isHarmonyHookCommand(cmd) {
|
|
88
|
+
if (typeof cmd !== "string" || !cmd.includes("harmony-mcp")) return false;
|
|
89
|
+
return /\bhook-event\b/.test(cmd) || (cmd.includes("/.harmony/bin/harmony-mcp") && cmd.includes("--session-hook"));
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// Adds a SessionStart hook running `<launcher> --session-hook` unless any Harmony session hook is already there.
|
|
93
|
+
// It tells the MCP server the agent's real session id (Codex exposes it no other way; Claude Code needs it to
|
|
94
|
+
// follow /clear). Grouped shape: hooks.SessionStart = [{ hooks: [{type, command, ...}] }].
|
|
95
|
+
export function upsertSessionStartHook(text, file, hook) {
|
|
96
|
+
const data = parseJsonc(text, file);
|
|
97
|
+
const groups = Array.isArray(data.hooks?.SessionStart) ? data.hooks.SessionStart : null;
|
|
98
|
+
const existing = (groups || []).some((g) =>
|
|
99
|
+
(g?.hooks || []).some((h) => typeof h?.command === "string" && h.command.includes("harmony-mcp") && h.command.includes("--session-hook")),
|
|
100
|
+
);
|
|
101
|
+
if (existing) return { text, status: "unchanged" };
|
|
102
|
+
if (!groups) return { text: jsoncSet(text, ["hooks", "SessionStart"], [{ hooks: [hook] }]), status: "added" };
|
|
103
|
+
return { text: jsoncSet(text, ["hooks", "SessionStart"], { hooks: [hook] }, { insertAt: groups.length }), status: "added" };
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function entryCommand(entry) {
|
|
107
|
+
return entry?.command ?? entry?.bash ?? entry?.powershell;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function sameJson(a, b) {
|
|
111
|
+
return JSON.stringify(a) === JSON.stringify(b);
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// Claude Code / Codex / Gemini shape: hooks[event] = [{ matcher?, hooks: [ {type, command, ...} ] }].
|
|
115
|
+
// Updates Harmony's entry in place if present, otherwise appends a new group. Returns { text, status }.
|
|
116
|
+
export function upsertGroupedHook(text, file, event, matcher, hook) {
|
|
117
|
+
const data = parseJsonc(text, file);
|
|
118
|
+
const groups = Array.isArray(data.hooks?.[event]) ? data.hooks[event] : null;
|
|
119
|
+
const group = matcher === undefined ? { hooks: [hook] } : { matcher, hooks: [hook] };
|
|
120
|
+
if (!groups) return { text: jsoncSet(text, ["hooks", event], [group]), status: "added" };
|
|
121
|
+
for (let gi = 0; gi < groups.length; gi++) {
|
|
122
|
+
const hooks = Array.isArray(groups[gi]?.hooks) ? groups[gi].hooks : [];
|
|
123
|
+
const hi = hooks.findIndex((h) => isHarmonyHookCommand(entryCommand(h)));
|
|
124
|
+
if (hi < 0) continue;
|
|
125
|
+
// Ours alone in its group: the whole group is ours, matcher included.
|
|
126
|
+
if (hooks.length === 1) {
|
|
127
|
+
if (sameJson(groups[gi], group)) return { text, status: "unchanged" };
|
|
128
|
+
return { text: jsoncSet(text, ["hooks", event, gi], group), status: "updated" };
|
|
129
|
+
}
|
|
130
|
+
if (sameJson(hooks[hi], hook)) return { text, status: "unchanged" };
|
|
131
|
+
return { text: jsoncSet(text, ["hooks", event, gi, "hooks", hi], hook), status: "updated" };
|
|
132
|
+
}
|
|
133
|
+
return { text: jsoncSet(text, ["hooks", event], group, { insertAt: groups.length }), status: "added" };
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
// Cursor / Copilot shape: hooks[event] = [ {command|bash, ...} ].
|
|
137
|
+
export function upsertFlatHook(text, file, event, entry) {
|
|
138
|
+
const data = parseJsonc(text, file);
|
|
139
|
+
const list = Array.isArray(data.hooks?.[event]) ? data.hooks[event] : null;
|
|
140
|
+
if (!list) return { text: jsoncSet(text, ["hooks", event], [entry]), status: "added" };
|
|
141
|
+
const idx = list.findIndex((e) => isHarmonyHookCommand(entryCommand(e)));
|
|
142
|
+
if (idx < 0) return { text: jsoncSet(text, ["hooks", event], entry, { insertAt: list.length }), status: "added" };
|
|
143
|
+
if (sameJson(list[idx], entry)) return { text, status: "unchanged" };
|
|
144
|
+
return { text: jsoncSet(text, ["hooks", event, idx], entry), status: "updated" };
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
// Ensures a top-level key has a value only if it is absent (e.g. Cursor's "version": 1).
|
|
148
|
+
export function ensureKey(text, file, key, value) {
|
|
149
|
+
const data = parseJsonc(text, file);
|
|
150
|
+
return key in data ? text : jsoncSet(text, [key], value);
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
// Removes every Harmony hook entry (both shapes). Groups / event arrays / the hooks object that become empty because
|
|
154
|
+
// of it are removed too; anything that held user entries is left in place. Returns { text, removed }.
|
|
155
|
+
export function removeHarmonyHooks(text, file) {
|
|
156
|
+
if (text === null) return { text, removed: 0 };
|
|
157
|
+
let current = text;
|
|
158
|
+
let removed = 0;
|
|
159
|
+
const data = parseJsonc(current, file);
|
|
160
|
+
const events = data.hooks && typeof data.hooks === "object" ? Object.keys(data.hooks) : [];
|
|
161
|
+
for (const event of events) {
|
|
162
|
+
const list = data.hooks[event];
|
|
163
|
+
if (!Array.isArray(list)) continue;
|
|
164
|
+
let emptied = 0;
|
|
165
|
+
for (let i = list.length - 1; i >= 0; i--) {
|
|
166
|
+
const item = list[i];
|
|
167
|
+
if (isHarmonyHookCommand(entryCommand(item))) {
|
|
168
|
+
current = jsoncSet(current, ["hooks", event, i], undefined);
|
|
169
|
+
removed++;
|
|
170
|
+
emptied++;
|
|
171
|
+
continue;
|
|
172
|
+
}
|
|
173
|
+
const inner = Array.isArray(item?.hooks) ? item.hooks : null;
|
|
174
|
+
if (!inner) continue;
|
|
175
|
+
const ours = inner.map((h, hi) => (isHarmonyHookCommand(entryCommand(h)) ? hi : -1)).filter((hi) => hi >= 0);
|
|
176
|
+
if (!ours.length) continue;
|
|
177
|
+
removed += ours.length;
|
|
178
|
+
if (ours.length === inner.length) {
|
|
179
|
+
current = jsoncSet(current, ["hooks", event, i], undefined);
|
|
180
|
+
emptied++;
|
|
181
|
+
} else {
|
|
182
|
+
for (const hi of ours.reverse()) current = jsoncSet(current, ["hooks", event, i, "hooks", hi], undefined);
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
if (emptied && emptied === list.length) current = jsoncSet(current, ["hooks", event], undefined);
|
|
186
|
+
}
|
|
187
|
+
if (removed) {
|
|
188
|
+
const after = parseJsonc(current, file);
|
|
189
|
+
if (after.hooks && typeof after.hooks === "object" && !Object.keys(after.hooks).length) {
|
|
190
|
+
current = jsoncSet(current, ["hooks"], undefined);
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
return { text: current, removed };
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
// mcpServers-style entry: added when missing, never overwritten (the user's own entry wins).
|
|
197
|
+
export function upsertMcpServer(text, file, keyPath, entry) {
|
|
198
|
+
const data = parseJsonc(text, file);
|
|
199
|
+
let node = data;
|
|
200
|
+
for (const k of keyPath) node = node && typeof node === "object" ? node[k] : undefined;
|
|
201
|
+
if (node !== undefined) return { text, status: "kept" };
|
|
202
|
+
return { text: jsoncSet(text, keyPath, entry), status: "added" };
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
// ---------- TOML (Codex config.toml) ----------
|
|
206
|
+
|
|
207
|
+
export const TOML_BLOCK_START = "# >>> harmony-mcp rsi hooks (managed; remove with `harmony-mcp setup-agents --uninstall`)";
|
|
208
|
+
export const TOML_BLOCK_END = "# <<< harmony-mcp rsi hooks";
|
|
209
|
+
|
|
210
|
+
function blockRange(text) {
|
|
211
|
+
const s = text.indexOf(TOML_BLOCK_START);
|
|
212
|
+
const e = text.indexOf(TOML_BLOCK_END);
|
|
213
|
+
return s >= 0 && e > s ? [s, e + TOML_BLOCK_END.length] : null;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
// True when config.toml already defines hooks inline (so Codex reads hooks from it, not hooks.json).
|
|
217
|
+
export function tomlHasInlineHooks(toml) {
|
|
218
|
+
if (!toml) return false;
|
|
219
|
+
const withoutOurs = (() => {
|
|
220
|
+
const r = blockRange(toml);
|
|
221
|
+
return r ? toml.slice(0, r[0]) + toml.slice(r[1]) : toml;
|
|
222
|
+
})();
|
|
223
|
+
// Hook definitions only: [[hooks.PostToolUse]], [hooks.SessionStart] or a bare [hooks] table with event keys.
|
|
224
|
+
// [hooks.state] (and its sub-tables) is where Codex records which hooks the user trusted — not definitions.
|
|
225
|
+
return /^\s*\[\[?\s*hooks\.(?!state\b)[A-Za-z]+\s*\]\]?\s*$/m.test(withoutOurs)
|
|
226
|
+
|| /^\s*\[\s*hooks\s*\][^[]*?^\s*[A-Z][A-Za-z]+\s*=/ms.test(withoutOurs);
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
// Inline arrays (`PostToolUse = [...]` under [hooks]) cannot be extended with [[hooks.PostToolUse]] tables.
|
|
230
|
+
export function tomlHasInlineHookArrays(toml) {
|
|
231
|
+
return /^\s*\[hooks\][^[]*?^\s*[A-Za-z]+\s*=\s*\[/ms.test(toml || "");
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
function tomlString(s) {
|
|
235
|
+
return JSON.stringify(String(s));
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
export function renderCodexTomlHooks(entries) {
|
|
239
|
+
const lines = [TOML_BLOCK_START];
|
|
240
|
+
for (const { event, matcher, hook } of entries) {
|
|
241
|
+
lines.push(`[[hooks.${event}]]`);
|
|
242
|
+
if (matcher !== undefined) lines.push(`matcher = ${tomlString(matcher)}`);
|
|
243
|
+
lines.push(`[[hooks.${event}.hooks]]`);
|
|
244
|
+
for (const [k, v] of Object.entries(hook)) {
|
|
245
|
+
lines.push(`${k} = ${typeof v === "string" ? tomlString(v) : String(v)}`);
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
lines.push(TOML_BLOCK_END);
|
|
249
|
+
return lines.join("\n");
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
export function upsertTomlBlock(toml, block) {
|
|
253
|
+
const text = toml || "";
|
|
254
|
+
const r = blockRange(text);
|
|
255
|
+
if (r) {
|
|
256
|
+
if (text.slice(r[0], r[1]) === block) return { text, status: "unchanged" };
|
|
257
|
+
return { text: text.slice(0, r[0]) + block + text.slice(r[1]), status: "updated" };
|
|
258
|
+
}
|
|
259
|
+
const sep = text.length === 0 ? "" : text.endsWith("\n\n") ? "" : text.endsWith("\n") ? "\n" : "\n\n";
|
|
260
|
+
return { text: `${text}${sep}${block}\n`, status: "added" };
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
export function removeTomlBlock(toml) {
|
|
264
|
+
const text = toml || "";
|
|
265
|
+
const r = blockRange(text);
|
|
266
|
+
if (!r) return { text, removed: 0 };
|
|
267
|
+
let before = text.slice(0, r[0]);
|
|
268
|
+
let after = text.slice(r[1]);
|
|
269
|
+
if (after.startsWith("\n")) after = after.slice(1);
|
|
270
|
+
if (before.endsWith("\n\n") && after === "") before = before.slice(0, -1);
|
|
271
|
+
return { text: before + after, removed: 1 };
|
|
272
|
+
}
|
|
@@ -17,7 +17,7 @@ import { createRequire } from "module";
|
|
|
17
17
|
import { AGENTS_MD_GUIDE } from "./agentsGuide.js";
|
|
18
18
|
|
|
19
19
|
const require = createRequire(import.meta.url);
|
|
20
|
-
const packageJson = require("
|
|
20
|
+
const packageJson = require("../../package.json");
|
|
21
21
|
|
|
22
22
|
export const SERVER_NAME = "harmony";
|
|
23
23
|
export const AGENTS_MD_START = "<!-- harmony-mcp:start -->";
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
// `harmony-mcp setup-agents` (RSI MCP spec §3, §6): detects installed coding agents, adds Harmony's MCP server and
|
|
2
|
+
// its non-blocking tool hooks to each, and prints what each agent now has. Idempotent; `--uninstall` removes
|
|
3
|
+
// only what this command added (hook entries, the managed Codex TOML block, Harmony's own hook files, the shim).
|
|
4
|
+
import fs from "fs";
|
|
5
|
+
import path from "path";
|
|
6
|
+
|
|
7
|
+
import { AGENTS, defaultUninstallHooks, mcpConfigured } from "./agentCapabilityMatrix.js";
|
|
8
|
+
import { writeConfigAtomic } from "./configMergers.js";
|
|
9
|
+
import { installShim, PACKAGE_SPEC, shimPath } from "./shim.js";
|
|
10
|
+
|
|
11
|
+
const USAGE = `Usage: harmony-mcp setup-agents [options]
|
|
12
|
+
|
|
13
|
+
Adds Harmony to the coding agents installed on this machine:
|
|
14
|
+
- the Harmony MCP server, where the agent's MCP config is a JSON file (Claude Code via \`claude mcp add\`)
|
|
15
|
+
- async tool hooks (\`harmony-mcp hook-event\`) for Claude Code, Codex, Cursor, Gemini CLI/Antigravity, Copilot CLI
|
|
16
|
+
Existing settings, comments and user hooks are kept; each changed file is backed up once to <file>.harmony-bak.
|
|
17
|
+
|
|
18
|
+
Options:
|
|
19
|
+
--agents <list> all (default: every detected agent) or a comma list, e.g. claude-code,codex,cursor
|
|
20
|
+
--scope <scope> user (default) or project (hooks only; writes portable npx commands into the repo)
|
|
21
|
+
--project <dir> repo for --scope project (default: current directory)
|
|
22
|
+
--hooks-only do not add MCP server entries
|
|
23
|
+
--mcp-only do not add hooks
|
|
24
|
+
--uninstall remove Harmony's hooks (MCP server entries are left alone)
|
|
25
|
+
--dry-run show what would change, write nothing
|
|
26
|
+
`;
|
|
27
|
+
|
|
28
|
+
export function parseSetupArgs(argv) {
|
|
29
|
+
const opts = { agents: "all", scope: "user", project: process.cwd(), hooks: true, mcp: true, uninstall: false, dryRun: false, help: false };
|
|
30
|
+
for (let i = 0; i < argv.length; i++) {
|
|
31
|
+
const a = argv[i];
|
|
32
|
+
const value = () => {
|
|
33
|
+
const v = argv[++i];
|
|
34
|
+
if (v === undefined) throw new Error(`${a} needs a value`);
|
|
35
|
+
return v;
|
|
36
|
+
};
|
|
37
|
+
if (a === "--agents") opts.agents = value();
|
|
38
|
+
else if (a.startsWith("--agents=")) opts.agents = a.slice(9);
|
|
39
|
+
else if (a === "--scope") opts.scope = value();
|
|
40
|
+
else if (a.startsWith("--scope=")) opts.scope = a.slice(8);
|
|
41
|
+
else if (a === "--project") opts.project = path.resolve(value());
|
|
42
|
+
else if (a === "--hooks-only") opts.mcp = false;
|
|
43
|
+
else if (a === "--mcp-only") opts.hooks = false;
|
|
44
|
+
else if (a === "--uninstall") opts.uninstall = true;
|
|
45
|
+
else if (a === "--dry-run") opts.dryRun = true;
|
|
46
|
+
else if (a === "--help" || a === "-h") opts.help = true;
|
|
47
|
+
else throw new Error(`Unknown option: ${a}`);
|
|
48
|
+
}
|
|
49
|
+
if (!["user", "project"].includes(opts.scope)) throw new Error(`--scope must be user or project, got "${opts.scope}"`);
|
|
50
|
+
if (opts.scope === "project") opts.mcp = false;
|
|
51
|
+
return opts;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function selectAgents(spec) {
|
|
55
|
+
if (spec === "all") return { agents: AGENTS.filter((a) => a.detect()), explicit: false };
|
|
56
|
+
const ids = spec.split(",").map((s) => s.trim()).filter(Boolean);
|
|
57
|
+
const unknown = ids.filter((id) => !AGENTS.some((a) => a.id === id));
|
|
58
|
+
if (unknown.length) throw new Error(`Unknown agent(s): ${unknown.join(", ")}. Known: ${AGENTS.map((a) => a.id).join(", ")}`);
|
|
59
|
+
return { agents: AGENTS.filter((a) => ids.includes(a.id)), explicit: true };
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
class Context {
|
|
63
|
+
constructor(opts) {
|
|
64
|
+
Object.assign(this, { scope: opts.scope, project: opts.project, dryRun: opts.dryRun });
|
|
65
|
+
this.lines = [];
|
|
66
|
+
this.current = null;
|
|
67
|
+
}
|
|
68
|
+
forAgent(agent) {
|
|
69
|
+
this.current = agent;
|
|
70
|
+
this.statuses = [];
|
|
71
|
+
}
|
|
72
|
+
note(status, what) {
|
|
73
|
+
this.statuses.push(status);
|
|
74
|
+
this.lines.push(` ${status.padEnd(9)} ${what}`);
|
|
75
|
+
}
|
|
76
|
+
write(file, text) {
|
|
77
|
+
if (!this.dryRun) writeConfigAtomic(file, text);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function cell(statuses) {
|
|
82
|
+
if (!statuses.length) return "-";
|
|
83
|
+
if (statuses.includes("skipped")) return "skipped";
|
|
84
|
+
if (statuses.includes("manual")) return "manual";
|
|
85
|
+
if (statuses.some((s) => s === "added" || s === "updated")) return "installed";
|
|
86
|
+
if (statuses.every((s) => s === "removed")) return "removed";
|
|
87
|
+
return "present";
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function renderTable(rows) {
|
|
91
|
+
const header = ["Agent", "Tier", "MCP server", "Tool hooks", "Instructions"];
|
|
92
|
+
const all = [header, ...rows];
|
|
93
|
+
const widths = header.map((_, i) => Math.max(...all.map((r) => String(r[i]).length)));
|
|
94
|
+
const line = (r) => r.map((c, i) => String(c).padEnd(widths[i])).join(" ").trimEnd();
|
|
95
|
+
return [line(header), widths.map((w) => "-".repeat(w)).join(" "), ...rows.map(line)].join("\n");
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export async function runSetupAgents(argv, { out = process.stdout, err = process.stderr } = {}) {
|
|
99
|
+
let opts;
|
|
100
|
+
try {
|
|
101
|
+
opts = parseSetupArgs(argv);
|
|
102
|
+
} catch (e) {
|
|
103
|
+
err.write(`${e.message}\n\n${USAGE}`);
|
|
104
|
+
return 2;
|
|
105
|
+
}
|
|
106
|
+
if (opts.help) {
|
|
107
|
+
out.write(USAGE);
|
|
108
|
+
return 0;
|
|
109
|
+
}
|
|
110
|
+
let selection;
|
|
111
|
+
try {
|
|
112
|
+
selection = selectAgents(opts.agents);
|
|
113
|
+
} catch (e) {
|
|
114
|
+
err.write(`${e.message}\n`);
|
|
115
|
+
return 2;
|
|
116
|
+
}
|
|
117
|
+
const ctx = new Context(opts);
|
|
118
|
+
const rows = [];
|
|
119
|
+
|
|
120
|
+
if (!opts.uninstall && opts.hooks && opts.scope === "user" && selection.agents.some((a) => a.installHooks)) {
|
|
121
|
+
const shim = installShim({ dryRun: opts.dryRun });
|
|
122
|
+
ctx.lines.push(` ${shim.status.padEnd(9)} ${shim.path} (hook launcher)`);
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
for (const agent of selection.agents) {
|
|
126
|
+
ctx.lines.push(`${agent.name}:`);
|
|
127
|
+
// MCP server
|
|
128
|
+
ctx.forAgent(agent);
|
|
129
|
+
let mcpCell = "-";
|
|
130
|
+
if (!opts.uninstall && opts.mcp) {
|
|
131
|
+
try {
|
|
132
|
+
if (agent.installMcp) agent.installMcp(ctx);
|
|
133
|
+
else if (agent.manualMcp) ctx.note("manual", `add the Harmony MCP server (npx -y ${PACKAGE_SPEC}) in ${agent.manualMcp}`);
|
|
134
|
+
} catch (e) {
|
|
135
|
+
ctx.note("skipped", `MCP server: ${e.message}`);
|
|
136
|
+
}
|
|
137
|
+
mcpCell = cell(ctx.statuses);
|
|
138
|
+
} else {
|
|
139
|
+
const configured = mcpConfigured(agent);
|
|
140
|
+
mcpCell = configured === null ? "-" : configured ? "present" : "missing";
|
|
141
|
+
}
|
|
142
|
+
// Hooks
|
|
143
|
+
ctx.forAgent(agent);
|
|
144
|
+
let hookCell;
|
|
145
|
+
if (!agent.installHooks) {
|
|
146
|
+
hookCell = agent.hooksPending ? "pending" : "n/a (server-side join)";
|
|
147
|
+
if (opts.hooks && agent.hooksPending && !opts.uninstall) ctx.lines.push(` ${"pending".padEnd(9)} hooks: ${agent.hooksPending}`);
|
|
148
|
+
} else if (!agent.hookScopes.includes(opts.scope)) {
|
|
149
|
+
ctx.note("skipped", `hooks: ${opts.scope} scope not supported for ${agent.name}`);
|
|
150
|
+
hookCell = "skipped";
|
|
151
|
+
} else if (opts.uninstall) {
|
|
152
|
+
try {
|
|
153
|
+
if (agent.uninstallHooks) agent.uninstallHooks(ctx);
|
|
154
|
+
else defaultUninstallHooks(agent, ctx);
|
|
155
|
+
} catch (e) {
|
|
156
|
+
ctx.note("skipped", `hooks: ${e.message}`);
|
|
157
|
+
}
|
|
158
|
+
hookCell = ctx.statuses.length ? cell(ctx.statuses) : "none found";
|
|
159
|
+
} else if (opts.hooks) {
|
|
160
|
+
try {
|
|
161
|
+
agent.installHooks(ctx);
|
|
162
|
+
} catch (e) {
|
|
163
|
+
ctx.note("skipped", `hooks: ${e.message}`);
|
|
164
|
+
}
|
|
165
|
+
hookCell = cell(ctx.statuses);
|
|
166
|
+
} else {
|
|
167
|
+
hookCell = "-";
|
|
168
|
+
}
|
|
169
|
+
rows.push([agent.name, agent.tier, mcpCell, hookCell, agent.instructions]);
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
// The shim is shared by every agent's hooks: remove it only when uninstalling from all of them.
|
|
173
|
+
if (opts.uninstall && opts.scope === "user" && opts.agents === "all") {
|
|
174
|
+
const shim = shimPath();
|
|
175
|
+
if (fs.existsSync(shim)) {
|
|
176
|
+
if (!opts.dryRun) fs.rmSync(shim);
|
|
177
|
+
ctx.lines.push(` ${"removed".padEnd(9)} ${shim}`);
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
const title = opts.uninstall ? "Harmony uninstall" : "Harmony agent setup";
|
|
182
|
+
out.write(`${title}${opts.dryRun ? " (dry run, nothing written)" : ""} — scope: ${opts.scope}\n${ctx.lines.join("\n")}\n\n`);
|
|
183
|
+
if (!selection.agents.length) {
|
|
184
|
+
out.write("No supported coding agents detected. Pass --agents <list> to choose explicitly.\n");
|
|
185
|
+
return 0;
|
|
186
|
+
}
|
|
187
|
+
out.write(`${renderTable(rows)}\n`);
|
|
188
|
+
if (!opts.uninstall && opts.hooks) {
|
|
189
|
+
out.write("\nTool hooks only send for repos where the Harmony MCP server has run setup_workspace; until then they do nothing.\n");
|
|
190
|
+
}
|
|
191
|
+
return 0;
|
|
192
|
+
}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
// Stable launcher for hooks: ~/.harmony/bin/harmony-mcp (RSI MCP spec §6.2.1).
|
|
2
|
+
//
|
|
3
|
+
// Hooks must name an absolute path (GUI IDEs run them with a minimal PATH, where `harmony-mcp` or even `npx` may
|
|
4
|
+
// be missing → exit 127). The package itself may live in a throwaway npx cache, so the hook points at this shim,
|
|
5
|
+
// which runs the installed copy when it is still there and falls back to npx otherwise. For hook-event the
|
|
6
|
+
// fallback is silenced and always exits 0, so a broken install can never fail an agent's turn.
|
|
7
|
+
import fs from "fs";
|
|
8
|
+
import path from "path";
|
|
9
|
+
import { fileURLToPath } from "url";
|
|
10
|
+
import { createRequire } from "module";
|
|
11
|
+
|
|
12
|
+
import { ensurePrivateDir, harmonyPath } from "../rsi/localState.js";
|
|
13
|
+
|
|
14
|
+
const packageJson = createRequire(import.meta.url)("../../package.json");
|
|
15
|
+
export const PACKAGE_SPEC = `${packageJson.name}@${packageJson.version}`;
|
|
16
|
+
export const ENTRY_PATH = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "index.js");
|
|
17
|
+
|
|
18
|
+
export function shimPath() {
|
|
19
|
+
return harmonyPath("bin", process.platform === "win32" ? "harmony-mcp.cmd" : "harmony-mcp");
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function shQuote(s) {
|
|
23
|
+
return `'${String(s).replace(/'/g, `'\\''`)}'`;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function renderPosixShim({ nodePath = process.execPath, entryPath = ENTRY_PATH } = {}) {
|
|
27
|
+
return `#!/bin/sh
|
|
28
|
+
# Generated by harmony-mcp setup-agents (${PACKAGE_SPEC}). Regenerated on every run; do not edit.
|
|
29
|
+
ENTRY=${shQuote(entryPath)}
|
|
30
|
+
NODE=${shQuote(nodePath)}
|
|
31
|
+
if [ -f "$ENTRY" ] && [ -x "$NODE" ]; then
|
|
32
|
+
exec "$NODE" "$ENTRY" "$@"
|
|
33
|
+
fi
|
|
34
|
+
if [ "$1" = "hook-event" ]; then
|
|
35
|
+
npx -y ${PACKAGE_SPEC} "$@" >/dev/null 2>&1
|
|
36
|
+
exit 0
|
|
37
|
+
fi
|
|
38
|
+
exec npx -y ${PACKAGE_SPEC} "$@"
|
|
39
|
+
`;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function renderWindowsShim({ nodePath = process.execPath, entryPath = ENTRY_PATH } = {}) {
|
|
43
|
+
return `@echo off\r\nrem Generated by harmony-mcp setup-agents (${PACKAGE_SPEC}).\r\nif exist "${entryPath}" (\r\n "${nodePath}" "${entryPath}" %*\r\n exit /b %ERRORLEVEL%\r\n)\r\nif "%1"=="hook-event" (\r\n npx -y ${PACKAGE_SPEC} %* >nul 2>&1\r\n exit /b 0\r\n)\r\nnpx -y ${PACKAGE_SPEC} %*\r\n`;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// Writes the shim if its content changed. Returns { path, status }.
|
|
47
|
+
export function installShim({ dryRun = false } = {}) {
|
|
48
|
+
const file = shimPath();
|
|
49
|
+
const content = process.platform === "win32" ? renderWindowsShim() : renderPosixShim();
|
|
50
|
+
let current = null;
|
|
51
|
+
try {
|
|
52
|
+
current = fs.readFileSync(file, "utf8");
|
|
53
|
+
} catch {
|
|
54
|
+
// not installed yet
|
|
55
|
+
}
|
|
56
|
+
if (current === content) return { path: file, status: "unchanged" };
|
|
57
|
+
if (!dryRun) {
|
|
58
|
+
ensurePrivateDir(path.dirname(file));
|
|
59
|
+
const tmp = `${file}.${process.pid}.tmp`;
|
|
60
|
+
fs.writeFileSync(tmp, content, { mode: 0o700 });
|
|
61
|
+
fs.renameSync(tmp, file);
|
|
62
|
+
}
|
|
63
|
+
return { path: file, status: current === null ? "added" : "updated" };
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// The command string a hook runs. Project-scope files are shared through git, so they use the portable npx form.
|
|
67
|
+
export function hookCommand({ agent, event, scope }) {
|
|
68
|
+
const base = scope === "project" ? `npx -y ${PACKAGE_SPEC}` : quoteIfNeeded(shimPath());
|
|
69
|
+
return `${base} hook-event --agent ${agent}${event ? ` --event ${event}` : ""}`;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// SessionStart command: records the agent's session id for the MCP server (see sessionIdentity.js).
|
|
73
|
+
export function sessionHookCommand({ scope }) {
|
|
74
|
+
const base = scope === "project" ? `npx -y ${PACKAGE_SPEC}` : quoteIfNeeded(shimPath());
|
|
75
|
+
return `${base} --session-hook`;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function quoteIfNeeded(p) {
|
|
79
|
+
return /[\s"'$`\\]/.test(p) ? JSON.stringify(p) : p;
|
|
80
|
+
}
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
// Managed Harmony block in AGENTS.md / CLAUDE.md (RSI MCP spec §7.1, §7.2).
|
|
2
|
+
//
|
|
3
|
+
// <!-- HARMONY:BEGIN bundle="org-42-g0014-8f3c2a" sha256="c4f91e82" -->
|
|
4
|
+
// ...managed text...
|
|
5
|
+
// <!-- HARMONY:END -->
|
|
6
|
+
//
|
|
7
|
+
// Only text between the sentinels is ever changed. The sha256 attribute is the first 8 hex chars of SHA-256 over the
|
|
8
|
+
// block body, so an unchanged bundle is detected without rewriting the file (its mtime stays, build watchers stay
|
|
9
|
+
// quiet). A BEGIN without a matching END (or more than one block) aborts the edit of that file: guessing where the
|
|
10
|
+
// block ends could delete the user's prose.
|
|
11
|
+
import crypto from "crypto";
|
|
12
|
+
|
|
13
|
+
export const BLOCK_END = "<!-- HARMONY:END -->";
|
|
14
|
+
const BEGIN_RE = /<!-- HARMONY:BEGIN\b([^>]*?)-->/g;
|
|
15
|
+
const ATTR_RE = /(\w+)="([^"]*)"/g;
|
|
16
|
+
const MAX_MANAGED_CHARS = 16_000;
|
|
17
|
+
export const MANAGED_HEADING = "## Harmony Workspace Intelligence (Managed — Do Not Edit Inside Markers)";
|
|
18
|
+
export const WORLD_MODEL_REL_PATH = ".harmony/workspace-world-model.md";
|
|
19
|
+
|
|
20
|
+
export class MarkerIntegrityError extends Error {}
|
|
21
|
+
|
|
22
|
+
export function shortSha(text) {
|
|
23
|
+
return crypto.createHash("sha256").update(text, "utf8").digest("hex").slice(0, 8);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// Bundle text is inserted between our own sentinels: it must not be able to open or close a block itself.
|
|
27
|
+
function sanitize(md) {
|
|
28
|
+
let text = String(md || "")
|
|
29
|
+
.replace(/\r\n/g, "\n")
|
|
30
|
+
.replace(/<!--\s*HARMONY:(BEGIN|END)[^>]*-->/gi, "")
|
|
31
|
+
.trim();
|
|
32
|
+
if (text.length > MAX_MANAGED_CHARS) text = `${text.slice(0, MAX_MANAGED_CHARS).trimEnd()}\n…`;
|
|
33
|
+
return text;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// The block body for a bundle, or null when the bundle gives the agent nothing to read.
|
|
37
|
+
export function renderManagedBody({ instructionsMd, hasWorldModel }) {
|
|
38
|
+
const instructions = sanitize(instructionsMd);
|
|
39
|
+
if (!instructions && !hasWorldModel) return null;
|
|
40
|
+
const lines = [];
|
|
41
|
+
if (!/^#{1,6}\s/.test(instructions)) lines.push(MANAGED_HEADING);
|
|
42
|
+
if (instructions) lines.push(instructions);
|
|
43
|
+
if (hasWorldModel) {
|
|
44
|
+
lines.push(`- Reference workspace architectural invariants in \`${WORLD_MODEL_REL_PATH}\` before proposing cross-service edits.`);
|
|
45
|
+
}
|
|
46
|
+
return lines.join("\n");
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function renderBlock(bundleId, body) {
|
|
50
|
+
const safeBundle = String(bundleId).replace(/[^A-Za-z0-9._:-]/g, "");
|
|
51
|
+
return `<!-- HARMONY:BEGIN bundle="${safeBundle}" sha256="${shortSha(body)}" -->\n${body}\n${BLOCK_END}`;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// Locates the managed block. Returns null when there is none; throws MarkerIntegrityError when markers are broken.
|
|
55
|
+
export function findBlock(text) {
|
|
56
|
+
const begins = [...text.matchAll(BEGIN_RE)];
|
|
57
|
+
const endCount = text.split(BLOCK_END).length - 1;
|
|
58
|
+
if (!begins.length && !endCount) return null;
|
|
59
|
+
if (begins.length !== 1 || endCount !== 1) {
|
|
60
|
+
throw new MarkerIntegrityError(`expected one HARMONY:BEGIN and one HARMONY:END, found ${begins.length} and ${endCount}`);
|
|
61
|
+
}
|
|
62
|
+
const begin = begins[0];
|
|
63
|
+
const endIdx = text.indexOf(BLOCK_END);
|
|
64
|
+
if (endIdx < begin.index) throw new MarkerIntegrityError("HARMONY:END comes before HARMONY:BEGIN");
|
|
65
|
+
const attrs = Object.fromEntries([...begin[1].matchAll(ATTR_RE)].map((m) => [m[1], m[2]]));
|
|
66
|
+
const bodyStart = begin.index + begin[0].length;
|
|
67
|
+
const body = text.slice(bodyStart, endIdx).replace(/^\r?\n/, "").replace(/\r?\n$/, "");
|
|
68
|
+
return { start: begin.index, end: endIdx + BLOCK_END.length, attrs, body };
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function useEol(text, original) {
|
|
72
|
+
return original.includes("\r\n") ? text.replace(/\r?\n/g, "\r\n") : text;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// Computes the new file text. mode:
|
|
76
|
+
// "update" — only replace an existing block (server startup)
|
|
77
|
+
// "add" — replace, or append a block to an existing file (CLI)
|
|
78
|
+
// body === null removes an existing block (the bundle no longer provides instructions).
|
|
79
|
+
// Returns { text, status: unchanged|updated|added|removed|absent, userEdited? }.
|
|
80
|
+
export function applyManagedBlock(original, { bundleId, body, mode }) {
|
|
81
|
+
const text = original ?? "";
|
|
82
|
+
const block = findBlock(text);
|
|
83
|
+
if (body === null) {
|
|
84
|
+
if (!block) return { text, status: "absent" };
|
|
85
|
+
let before = text.slice(0, block.start);
|
|
86
|
+
let after = text.slice(block.end);
|
|
87
|
+
after = after.replace(/^\r?\n/, "");
|
|
88
|
+
if (!after.trim()) before = before.replace(/(\r?\n)+$/, "\n");
|
|
89
|
+
return { text: before + after, status: "removed" };
|
|
90
|
+
}
|
|
91
|
+
const rendered = renderBlock(bundleId, body);
|
|
92
|
+
if (block) {
|
|
93
|
+
if (block.attrs.bundle === String(bundleId) && block.attrs.sha256 === shortSha(body)) {
|
|
94
|
+
// Idempotent skip (spec §7.2.1) — unless someone edited inside the markers since.
|
|
95
|
+
if (shortSha(block.body.replace(/\r\n/g, "\n")) === block.attrs.sha256) return { text, status: "unchanged" };
|
|
96
|
+
}
|
|
97
|
+
const userEdited = block.attrs.sha256 && shortSha(block.body.replace(/\r\n/g, "\n")) !== block.attrs.sha256;
|
|
98
|
+
return { text: text.slice(0, block.start) + useEol(rendered, text) + text.slice(block.end), status: "updated", userEdited };
|
|
99
|
+
}
|
|
100
|
+
if (mode !== "add") return { text, status: "absent" };
|
|
101
|
+
const sep = text.length === 0 ? "" : /\n\s*\n$/.test(text) ? "" : text.endsWith("\n") ? "\n" : "\n\n";
|
|
102
|
+
return { text: text + useEol(`${sep}${rendered}\n`, text || "\n"), status: "added" };
|
|
103
|
+
}
|