@codeconductorai/harmony-mcp 1.0.33 → 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.
- package/README.md +210 -15
- package/package.json +4 -2
- package/src/{deviceAuth.js → auth/deviceAuth.js} +2 -2
- package/src/{harmonyClient.js → backend/harmonyClient.js} +183 -13
- package/src/doctor/doctorCommand.js +382 -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 +126 -0
- package/src/rsi/hooks/fileHash.js +33 -0
- package/src/rsi/hooks/hmacSigner.js +39 -0
- package/src/rsi/hooks/hookEventCommand.js +196 -0
- package/src/rsi/hooks/normalizers.js +329 -0
- package/src/rsi/hooks/offlineSpooler.js +104 -0
- package/src/rsi/hooks/secretScrubber.js +50 -0
- package/src/rsi/hooks/shellCommandScrubber.js +449 -0
- package/src/rsi/hooks/spoolDrainer.js +73 -0
- package/src/rsi/hooks/toolEventsClient.js +70 -0
- package/src/rsi/localState.js +53 -0
- package/src/rsi/serveTelemetry.js +85 -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,382 @@
|
|
|
1
|
+
// `harmony-mcp doctor` (RSI MCP spec §3): one screen that says whether Harmony works in this repo and, if not, what
|
|
2
|
+
// to do. Checks install, workspace binding, credentials, backend reachability and index status, the RSI bundle and
|
|
3
|
+
// telemetry key, agent hooks, the hook spool, and the ROI summary. Read-only except `--rotate-telemetry-key`.
|
|
4
|
+
// Never prints a token or key: only who/when/expiry and the key id.
|
|
5
|
+
import fs from "fs";
|
|
6
|
+
import os from "os";
|
|
7
|
+
import path from "path";
|
|
8
|
+
import { createRequire } from "module";
|
|
9
|
+
|
|
10
|
+
import { harmonyPath, readJsonFile } from "../rsi/localState.js";
|
|
11
|
+
import { resolveWorkspaceForDir } from "../rsi/workspaceRegistry.js";
|
|
12
|
+
import { statePath } from "../rsi/causalState.js";
|
|
13
|
+
import { readTelemetryKey, telemetryKeyId, writeTelemetryKey } from "../rsi/hooks/hmacSigner.js";
|
|
14
|
+
import { listSpoolFiles } from "../rsi/hooks/offlineSpooler.js";
|
|
15
|
+
|
|
16
|
+
const packageJson = createRequire(import.meta.url)("../../package.json");
|
|
17
|
+
|
|
18
|
+
const USAGE = `Usage: harmony-mcp doctor [options]
|
|
19
|
+
|
|
20
|
+
Checks that Harmony works for the repo in the current directory and says what to fix.
|
|
21
|
+
|
|
22
|
+
Options:
|
|
23
|
+
--dir <repo> repo to check (default: current directory)
|
|
24
|
+
--offline skip every network check
|
|
25
|
+
--json machine-readable output
|
|
26
|
+
--rotate-telemetry-key ask the backend for a new hook-signing key and store it
|
|
27
|
+
`;
|
|
28
|
+
|
|
29
|
+
export function parseDoctorArgs(argv) {
|
|
30
|
+
const opts = { dir: process.cwd(), offline: false, json: false, rotateKey: false, help: false };
|
|
31
|
+
for (let i = 0; i < argv.length; i++) {
|
|
32
|
+
const a = argv[i];
|
|
33
|
+
if (a === "--dir") {
|
|
34
|
+
if (argv[i + 1] === undefined) throw new Error("--dir needs a value");
|
|
35
|
+
opts.dir = path.resolve(argv[++i]);
|
|
36
|
+
} else if (a.startsWith("--dir=")) opts.dir = path.resolve(a.slice(6));
|
|
37
|
+
else if (a === "--offline") opts.offline = true;
|
|
38
|
+
else if (a === "--json") opts.json = true;
|
|
39
|
+
else if (a === "--rotate-telemetry-key") opts.rotateKey = true;
|
|
40
|
+
else if (a === "--help" || a === "-h") opts.help = true;
|
|
41
|
+
else throw new Error(`Unknown option: ${a}`);
|
|
42
|
+
}
|
|
43
|
+
return opts;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// ---------- helpers ----------
|
|
47
|
+
|
|
48
|
+
function ago(ms) {
|
|
49
|
+
if (ms < 0) return "in the future";
|
|
50
|
+
const s = Math.round(ms / 1000);
|
|
51
|
+
if (s < 90) return `${s}s ago`;
|
|
52
|
+
const m = Math.round(s / 60);
|
|
53
|
+
if (m < 90) return `${m}m ago`;
|
|
54
|
+
const h = Math.round(m / 60);
|
|
55
|
+
return h < 48 ? `${h}h ago` : `${Math.round(h / 24)}d ago`;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function inFuture(ms) {
|
|
59
|
+
if (ms <= 0) return "expired";
|
|
60
|
+
const m = Math.round(ms / 60_000);
|
|
61
|
+
return m < 90 ? `expires in ${m}m` : m < 60 * 48 ? `expires in ${Math.round(m / 60)}h` : `expires in ${Math.round(m / 1440)}d`;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function jwtClaims(token) {
|
|
65
|
+
try {
|
|
66
|
+
return JSON.parse(Buffer.from(String(token).split(".")[1], "base64url").toString("utf8"));
|
|
67
|
+
} catch {
|
|
68
|
+
return null;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function tilde(p) {
|
|
73
|
+
const home = os.homedir();
|
|
74
|
+
return p && p.startsWith(home) ? `~${p.slice(home.length)}` : p;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function fmtInt(n) {
|
|
78
|
+
return Number(n || 0).toLocaleString("en-US");
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
class Report {
|
|
82
|
+
constructor() {
|
|
83
|
+
this.items = [];
|
|
84
|
+
this.section = null;
|
|
85
|
+
}
|
|
86
|
+
start(section) {
|
|
87
|
+
this.section = section;
|
|
88
|
+
}
|
|
89
|
+
add(level, check, detail, fix) {
|
|
90
|
+
this.items.push({ section: this.section, level, check, detail, ...(fix ? { fix } : {}) });
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// ---------- checks ----------
|
|
95
|
+
|
|
96
|
+
function checkInstall(r) {
|
|
97
|
+
r.start("Install");
|
|
98
|
+
r.add("ok", "harmony-mcp", `${packageJson.version} on node ${process.versions.node}`);
|
|
99
|
+
const shim = harmonyPath("bin", process.platform === "win32" ? "harmony-mcp.cmd" : "harmony-mcp");
|
|
100
|
+
const text = (() => {
|
|
101
|
+
try {
|
|
102
|
+
return fs.readFileSync(shim, "utf8");
|
|
103
|
+
} catch {
|
|
104
|
+
return null;
|
|
105
|
+
}
|
|
106
|
+
})();
|
|
107
|
+
if (text === null) {
|
|
108
|
+
r.add("info", "hook launcher", "not installed (only needed for tool hooks)", "harmony-mcp setup-agents");
|
|
109
|
+
return;
|
|
110
|
+
}
|
|
111
|
+
const entry = /^ENTRY='(.*)'$/m.exec(text)?.[1]?.replace(/'\\''/g, "'");
|
|
112
|
+
if (entry && fs.existsSync(entry)) r.add("ok", "hook launcher", `${tilde(shim)} → ${tilde(entry)}`);
|
|
113
|
+
else r.add("warn", "hook launcher", `${tilde(shim)} points at a removed install; hooks fall back to npx (slower)`, "harmony-mcp setup-agents");
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function checkWorkspace(r, opts) {
|
|
117
|
+
r.start("Workspace");
|
|
118
|
+
const bound = resolveWorkspaceForDir(opts.dir);
|
|
119
|
+
const root = bound?.root || opts.dir;
|
|
120
|
+
const marker = readJsonFile(path.join(root, process.env.HARMONY_WORKSPACE_MARKER || ".harmony_workspace.json"));
|
|
121
|
+
const workspaceId = bound?.workspaceId || (marker?.workspaceId ? String(marker.workspaceId) : null);
|
|
122
|
+
if (!workspaceId) {
|
|
123
|
+
r.add("fail", "workspace", `${tilde(root)} is not set up for Harmony`, "ask your agent to call setup_workspace");
|
|
124
|
+
return { root, workspaceId: null, endpoint: null, bound: false };
|
|
125
|
+
}
|
|
126
|
+
const envUrl = process.env.API_URL ? process.env.API_URL.replace(/\/+$/, "") : null;
|
|
127
|
+
// Never guess a backend: a token issued by one backend must not be sent to another.
|
|
128
|
+
const endpoint = bound?.endpoint || envUrl;
|
|
129
|
+
r.add("ok", "workspace", `${workspaceId} at ${tilde(root)}${marker?.indexStatus ? ` (last known index status ${marker.indexStatus})` : ""}`);
|
|
130
|
+
if (bound) {
|
|
131
|
+
r.add("ok", "backend binding", `${endpoint} (tool hooks send here)`);
|
|
132
|
+
if (envUrl && envUrl !== bound.endpoint) r.add("warn", "API_URL", `this shell has API_URL=${envUrl}, but the repo is bound to ${bound.endpoint}; checking the bound one`);
|
|
133
|
+
} else if (endpoint) {
|
|
134
|
+
r.add("warn", "backend binding", `not recorded in ${tilde(harmonyPath("workspaces.json"))}, so tool hooks will not send; checking API_URL=${endpoint}`, "start the Harmony MCP server in this repo once");
|
|
135
|
+
} else {
|
|
136
|
+
r.add("warn", "backend binding", "no backend recorded for this repo and API_URL is not set; skipping network checks", "start the Harmony MCP server in this repo once, or run with API_URL=<backend>");
|
|
137
|
+
}
|
|
138
|
+
return { root, workspaceId, endpoint, bound: Boolean(bound) };
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
async function checkCredentials(r, ws) {
|
|
142
|
+
r.start("Credentials");
|
|
143
|
+
// telemetry.js and deviceAuth.js import each other; load them in the server's order or API_URL is uninitialised.
|
|
144
|
+
await import("../observability/telemetry.js");
|
|
145
|
+
const { getLoggedInUser, getWorkspaceToken, getWorkspaceRefreshToken } = await import("../auth/deviceAuth.js");
|
|
146
|
+
if (process.env.AUTH_ACCESS_TOKEN) r.add("info", "AUTH_ACCESS_TOKEN", "set in the environment; it overrides stored logins");
|
|
147
|
+
const session = readJsonFile(path.join(os.homedir(), ".harmony-mcp", "session.json"));
|
|
148
|
+
const user = getLoggedInUser();
|
|
149
|
+
const who = user?.name || user?.username || user?.email || "unknown user";
|
|
150
|
+
if (session?.accessToken) {
|
|
151
|
+
const left = (session.expiresAt || 0) * 1000 - Date.now();
|
|
152
|
+
if (left > 0) r.add("ok", "login", `${who}, ${inFuture(left)}`);
|
|
153
|
+
else if (session.refreshToken) r.add("ok", "login", `${who}, access token expired; renews automatically`);
|
|
154
|
+
else r.add("fail", "login", `${who}, expired and cannot renew`, "call the login tool");
|
|
155
|
+
} else if (!process.env.AUTH_ACCESS_TOKEN) {
|
|
156
|
+
r.add("warn", "login", "no user login stored; only the workspace token can be used", "call the login tool");
|
|
157
|
+
}
|
|
158
|
+
if (!ws.workspaceId) return;
|
|
159
|
+
const token = getWorkspaceToken(ws.workspaceId);
|
|
160
|
+
if (!token) {
|
|
161
|
+
r.add(session?.accessToken ? "info" : "warn", "workspace token", `none stored for workspace ${ws.workspaceId}`);
|
|
162
|
+
return;
|
|
163
|
+
}
|
|
164
|
+
const exp = jwtClaims(token)?.exp;
|
|
165
|
+
const left = exp ? exp * 1000 - Date.now() : null;
|
|
166
|
+
if (left === null || left > 0) r.add("ok", "workspace token", left === null ? "present" : inFuture(left));
|
|
167
|
+
else if (getWorkspaceRefreshToken(ws.workspaceId)) r.add("ok", "workspace token", "expired; renews automatically");
|
|
168
|
+
else r.add("warn", "workspace token", "expired and no refresh token", "call setup_workspace again");
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
async function checkBackend(r, ws, client) {
|
|
172
|
+
r.start("Backend");
|
|
173
|
+
const res = await client.probeBackend(client.workspaceStatusPath(ws.workspaceId), { workspaceId: ws.workspaceId });
|
|
174
|
+
if (res.status === null) {
|
|
175
|
+
r.add("fail", "reachable", `${ws.endpoint}: ${res.error}`, "check the network / VPN, or API_URL");
|
|
176
|
+
return false;
|
|
177
|
+
}
|
|
178
|
+
if (res.status === 401 || res.status === 403) {
|
|
179
|
+
r.add("fail", "authorized", `HTTP ${res.status} for workspace ${ws.workspaceId} (${res.ms} ms)`, "call the login tool");
|
|
180
|
+
return false;
|
|
181
|
+
}
|
|
182
|
+
if (res.status === 404) {
|
|
183
|
+
r.add("fail", "workspace", `the backend does not know workspace ${ws.workspaceId}`, "call setup_workspace");
|
|
184
|
+
return false;
|
|
185
|
+
}
|
|
186
|
+
if (!res.ok) {
|
|
187
|
+
r.add("fail", "reachable", `HTTP ${res.status} (${res.ms} ms)`);
|
|
188
|
+
return false;
|
|
189
|
+
}
|
|
190
|
+
r.add(res.ms > 1500 ? "warn" : "ok", "reachable", `${ws.endpoint} in ${res.ms} ms`);
|
|
191
|
+
const status = /<status>([^<]+)<\/status>/i.exec(res.text || "")?.[1]?.trim() || res.json?.status;
|
|
192
|
+
if (status === "TEXT_AND_SYMBOLS_COMPLETE") r.add("ok", "index", status);
|
|
193
|
+
else if (status) r.add("warn", "index", `${status} (symbol tools may be incomplete until it finishes)`, "call setup_workspace to check again");
|
|
194
|
+
return true;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
async function checkRsi(r, ws, client, { online, rotateKey }) {
|
|
198
|
+
r.start("RSI");
|
|
199
|
+
const cache = readJsonFile(harmonyPath("cache", "bundles", `ws-${String(ws.workspaceId).replace(/[^A-Za-z0-9_-]/g, "_")}-manifest.json`));
|
|
200
|
+
if (online) {
|
|
201
|
+
const pin = await client.probeBackend(`/api/code-workspace/${ws.workspaceId}/rsi/pin`, { method: "POST", body: {}, workspaceId: ws.workspaceId });
|
|
202
|
+
const bundleId = pin.json?.pinnedBundleId;
|
|
203
|
+
if (pin.ok && bundleId) {
|
|
204
|
+
const b = await client.probeBackend(`/api/rsi/bundles/${encodeURIComponent(bundleId)}`, { workspaceId: ws.workspaceId });
|
|
205
|
+
const hints = b.json?.mcpToolHints ? Object.keys(b.json.mcpToolHints).length : 0;
|
|
206
|
+
const docs = [b.json?.managedAgentInstructionsMarkdown?.trim() && "instructions", b.json?.workspaceWorldModelMarkdown?.trim() && "world model"].filter(Boolean);
|
|
207
|
+
r.add("ok", "bundle", `${bundleId}: ${hints} tool hint${hints === 1 ? "" : "s"}${docs.length ? `, ${docs.join(" + ")}` : ", no managed docs"}`);
|
|
208
|
+
if (cache?.bundleId && cache.bundleId !== bundleId) r.add("info", "bundle cache", `holds ${cache.bundleId}; the MCP server refreshes it on its next start`);
|
|
209
|
+
} else if (pin.status === 404 || pin.status === 405) {
|
|
210
|
+
r.add("info", "bundle", "this backend has no RSI bundles yet");
|
|
211
|
+
} else {
|
|
212
|
+
r.add("warn", "bundle", `pin failed: ${pin.status === null ? pin.error : `HTTP ${pin.status}`}`);
|
|
213
|
+
}
|
|
214
|
+
} else if (cache?.bundleId) {
|
|
215
|
+
r.add("info", "bundle", `${cache.bundleId} (cached ${cache.fetchedAtEpochMs ? ago(Date.now() - cache.fetchedAtEpochMs) : ""})`);
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
if (rotateKey && online) {
|
|
219
|
+
const res = await client.probeBackend(`/api/code-workspace/${ws.workspaceId}/rsi/telemetry-key`, { method: "POST", body: { rotate: true }, workspaceId: ws.workspaceId, userAuth: true });
|
|
220
|
+
const hex = res.json?.telemetryKeyHex;
|
|
221
|
+
if (res.ok && typeof hex === "string" && /^[0-9a-f]{64}$/.test(hex)) {
|
|
222
|
+
writeTelemetryKey(hex);
|
|
223
|
+
r.add("ok", "telemetry key", `rotated → ${telemetryKeyId(Buffer.from(hex, "hex"))} (the old key keeps verifying for 24 h)`);
|
|
224
|
+
} else {
|
|
225
|
+
r.add("fail", "telemetry key", `rotation failed: ${res.status === null ? res.error : `HTTP ${res.status}`}${res.status === 404 ? " (backend does not issue keys)" : ""}`);
|
|
226
|
+
}
|
|
227
|
+
return;
|
|
228
|
+
}
|
|
229
|
+
const key = readTelemetryKey();
|
|
230
|
+
if (key) r.add("ok", "telemetry key", telemetryKeyId(key));
|
|
231
|
+
else r.add("warn", "telemetry key", "missing, so tool hooks only spool events", "start the MCP server (it fetches the key), or the backend does not issue keys yet");
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
async function checkHooks(r, ws) {
|
|
235
|
+
r.start("Agent hooks");
|
|
236
|
+
const { AGENTS } = await import("../setup/agentCapabilityMatrix.js");
|
|
237
|
+
const { isHarmonyHookCommand } = await import("../setup/configMergers.js");
|
|
238
|
+
const ctx = { scope: "user", project: ws.root };
|
|
239
|
+
let any = false;
|
|
240
|
+
const missing = [];
|
|
241
|
+
for (const agent of AGENTS) {
|
|
242
|
+
if (!agent.installHooks || !agent.detect()) continue;
|
|
243
|
+
any = true;
|
|
244
|
+
const files = agent.hookFiles(ctx);
|
|
245
|
+
const installed = files.some((f) => {
|
|
246
|
+
try {
|
|
247
|
+
return fs.readFileSync(f, "utf8").split(/\r?\n/).some((line) => isHarmonyHookCommand(line));
|
|
248
|
+
} catch {
|
|
249
|
+
return false;
|
|
250
|
+
}
|
|
251
|
+
});
|
|
252
|
+
if (installed) r.add("ok", agent.name, "hooks installed");
|
|
253
|
+
else missing.push(agent);
|
|
254
|
+
}
|
|
255
|
+
// Hooks are optional (they only feed Harmony's learning), so missing ones are information, not a warning.
|
|
256
|
+
if (missing.length) {
|
|
257
|
+
r.add("info", "not installed", missing.map((a) => a.name).join(", "), `harmony-mcp setup-agents --agents ${missing.map((a) => a.id).join(",")}`);
|
|
258
|
+
}
|
|
259
|
+
if (!any) r.add("info", "agents", "no hook-capable agent detected");
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
function checkPipeline(r, ws) {
|
|
263
|
+
r.start("Hook telemetry");
|
|
264
|
+
let count = 0;
|
|
265
|
+
let oldest = null;
|
|
266
|
+
for (const file of listSpoolFiles()) {
|
|
267
|
+
try {
|
|
268
|
+
const lines = fs.readFileSync(file, "utf8").split("\n").filter(Boolean);
|
|
269
|
+
count += lines.length;
|
|
270
|
+
const ts = JSON.parse(lines[0] || "null")?.event?.clientTimestampEpochMs;
|
|
271
|
+
if (ts && (!oldest || ts < oldest)) oldest = ts;
|
|
272
|
+
} catch {
|
|
273
|
+
// unreadable spool file
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
if (!count) r.add("ok", "spool", "empty (nothing waiting to be sent)");
|
|
277
|
+
else r.add(count > 1000 ? "warn" : "info", "spool", `${fmtInt(count)} event${count === 1 ? "" : "s"} waiting${oldest ? `, oldest ${ago(Date.now() - oldest)}` : ""}`, count > 1000 ? "check the telemetry key and backend above; the spool keeps at most 2 MiB" : undefined);
|
|
278
|
+
|
|
279
|
+
if (ws.workspaceId) {
|
|
280
|
+
// Read the state as-is: doctor is not an agent session, so the hooks' same-session rule does not apply here.
|
|
281
|
+
const raw = readJsonFile(statePath(ws.root));
|
|
282
|
+
const age = raw?.updatedAtEpochMs ? Date.now() - raw.updatedAtEpochMs : null;
|
|
283
|
+
if (age === null) r.add("info", "last Harmony call", "none recorded for this repo yet");
|
|
284
|
+
else if (age > 900_000) r.add("info", "last Harmony call", `${ago(age)} (older than 15 min, so new hook events are not linked to it)`);
|
|
285
|
+
else r.add("ok", "last Harmony call", `${raw.lastEndpoint || "query"} ${ago(age)}${raw.lastHarmonyRequestId ? "; hook events from the same agent session link to it" : " (backend sent no ledger id, so hook events cannot link to it)"}`);
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
const logFile = harmonyPath("logs", "harmony-mcp.log");
|
|
289
|
+
try {
|
|
290
|
+
const dayAgo = Date.now() - 86_400_000;
|
|
291
|
+
const errors = fs
|
|
292
|
+
.readFileSync(logFile, "utf8")
|
|
293
|
+
.split("\n")
|
|
294
|
+
.filter((l) => l.includes("[hook-event") && !/: (sent|spooled|no-actions|no-events|unregistered-workspace)\b/.test(l))
|
|
295
|
+
.filter((l) => Date.parse(l.slice(1, 25)) >= dayAgo);
|
|
296
|
+
if (errors.length) r.add("warn", "hook errors (24h)", `${errors.length}; last: ${errors.at(-1).replace(/^\[[^\]]+\] \[hook-event \d+\] /, "").slice(0, 160)}`, `see ${tilde(logFile)}`);
|
|
297
|
+
} catch {
|
|
298
|
+
// no hook log yet
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
async function checkRoi(r, client, ws) {
|
|
303
|
+
r.start("Value (ROI)");
|
|
304
|
+
let res = await client.probeBackend("/api/rsi/outcomes/summary", { workspaceId: ws.workspaceId });
|
|
305
|
+
if (res.status === 404) res = await client.probeBackend(`/api/code-workspace/${ws.workspaceId}/rsi/value-summary`, { workspaceId: ws.workspaceId });
|
|
306
|
+
const s = res.json;
|
|
307
|
+
if (!res.ok || !s || typeof s !== "object") {
|
|
308
|
+
r.add("info", "summary", res.status === 404 ? "not available on this backend" : `not available (${res.status === null ? res.error : `HTTP ${res.status}`})`);
|
|
309
|
+
return;
|
|
310
|
+
}
|
|
311
|
+
if (!s.sampleCount) {
|
|
312
|
+
r.add("info", "summary", "no recorded Harmony calls yet for your organization");
|
|
313
|
+
return;
|
|
314
|
+
}
|
|
315
|
+
// Measured by the backend: the files each answer covers, read in full, minus what Harmony sent. Time is a heuristic.
|
|
316
|
+
const saved = s.totalExactTokensSaved ?? s.totalEstimatedTokensSaved;
|
|
317
|
+
// The backend's averageCompressionRatio is the fraction of tokens saved per call (0.47 = answers 47% smaller).
|
|
318
|
+
const ratio = typeof s.averageCompressionRatio === "number" ? `, answers on average ${Math.round(s.averageCompressionRatio * 100)}% smaller` : "";
|
|
319
|
+
const secs = typeof s.totalEstimatedSecondsSaved === "number" ? `, ~${Math.round(s.totalEstimatedSecondsSaved / 60)} min saved (estimate)` : "";
|
|
320
|
+
r.add("ok", "summary", `${fmtInt(s.sampleCount)} calls (org-wide${s.bundleId ? `, bundle ${s.bundleId}` : ""}): ~${fmtInt(saved)} tokens saved${ratio}${secs}`);
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
// ---------- output ----------
|
|
324
|
+
|
|
325
|
+
const MARK = { ok: "ok ", warn: "WARN", fail: "FAIL", info: "info" };
|
|
326
|
+
|
|
327
|
+
function render(items, root) {
|
|
328
|
+
const lines = [`Harmony doctor — ${tilde(root)}`];
|
|
329
|
+
let section = null;
|
|
330
|
+
for (const it of items) {
|
|
331
|
+
if (it.section !== section) {
|
|
332
|
+
section = it.section;
|
|
333
|
+
lines.push("", section);
|
|
334
|
+
}
|
|
335
|
+
lines.push(` ${MARK[it.level]} ${it.check.padEnd(18)} ${it.detail}`);
|
|
336
|
+
if (it.fix) lines.push(` ${" ".repeat(6)}${" ".repeat(18)} → ${it.fix}`);
|
|
337
|
+
}
|
|
338
|
+
const fails = items.filter((i) => i.level === "fail").length;
|
|
339
|
+
const warns = items.filter((i) => i.level === "warn").length;
|
|
340
|
+
lines.push("", fails ? `${fails} problem${fails === 1 ? "" : "s"}, ${warns} warning${warns === 1 ? "" : "s"}.` : warns ? `Working, with ${warns} warning${warns === 1 ? "" : "s"}.` : "All good.");
|
|
341
|
+
return `${lines.join("\n")}\n`;
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
export async function runDoctor(argv, { out = process.stdout, err = process.stderr } = {}) {
|
|
345
|
+
let opts;
|
|
346
|
+
try {
|
|
347
|
+
opts = parseDoctorArgs(argv);
|
|
348
|
+
} catch (e) {
|
|
349
|
+
err.write(`${e.message}\n\n${USAGE}`);
|
|
350
|
+
return 2;
|
|
351
|
+
}
|
|
352
|
+
if (opts.help) {
|
|
353
|
+
out.write(USAGE);
|
|
354
|
+
return 0;
|
|
355
|
+
}
|
|
356
|
+
const r = new Report();
|
|
357
|
+
checkInstall(r);
|
|
358
|
+
const ws = checkWorkspace(r, opts);
|
|
359
|
+
|
|
360
|
+
if (ws.workspaceId) {
|
|
361
|
+
// deviceAuth / harmonyClient read API_URL and the marker (cwd) at import time.
|
|
362
|
+
if (ws.endpoint) process.env.API_URL = ws.endpoint;
|
|
363
|
+
process.chdir(ws.root);
|
|
364
|
+
await checkCredentials(r, ws);
|
|
365
|
+
let online = false;
|
|
366
|
+
let client = null;
|
|
367
|
+
if (!opts.offline && ws.endpoint) {
|
|
368
|
+
client = await import("../backend/harmonyClient.js");
|
|
369
|
+
online = await checkBackend(r, ws, client);
|
|
370
|
+
}
|
|
371
|
+
await checkRsi(r, ws, client, { online, rotateKey: opts.rotateKey });
|
|
372
|
+
await checkHooks(r, ws);
|
|
373
|
+
checkPipeline(r, ws);
|
|
374
|
+
if (online) await checkRoi(r, client, ws);
|
|
375
|
+
} else {
|
|
376
|
+
await checkHooks(r, ws);
|
|
377
|
+
checkPipeline(r, ws);
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
out.write(opts.json ? `${JSON.stringify({ root: ws.root, workspaceId: ws.workspaceId, checks: r.items }, null, 2)}\n` : render(r.items, ws.root));
|
|
381
|
+
return r.items.some((i) => i.level === "fail") ? 1 : 0;
|
|
382
|
+
}
|
package/src/index.js
CHANGED
|
@@ -1,13 +1,26 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
if (process.argv[2] === "
|
|
3
|
-
|
|
2
|
+
if (process.argv[2] === "hook-event") {
|
|
3
|
+
// Agent PostToolUse/PreCompact hook: keep this path free of the server's imports so it starts fast.
|
|
4
|
+
const { runHookEvent } = await import("./rsi/hooks/hookEventCommand.js");
|
|
5
|
+
await runHookEvent(process.argv.slice(3));
|
|
6
|
+
} else if (process.argv[2] === "doctor") {
|
|
7
|
+
const { runDoctor } = await import("./doctor/doctorCommand.js");
|
|
8
|
+
process.exitCode = await runDoctor(process.argv.slice(3));
|
|
9
|
+
} else if (process.argv[2] === "sync-workspace") {
|
|
10
|
+
const { runSyncWorkspace } = await import("./sync/syncWorkspaceCommand.js");
|
|
11
|
+
process.exitCode = await runSyncWorkspace(process.argv.slice(3));
|
|
12
|
+
} else if (process.argv[2] === "setup-agents") {
|
|
13
|
+
const { runSetupAgents } = await import("./setup/setupAgentsCommand.js");
|
|
14
|
+
process.exitCode = await runSetupAgents(process.argv.slice(3));
|
|
15
|
+
} else if (process.argv[2] === "install") {
|
|
16
|
+
const { runInstall } = await import("./setup/installer.js");
|
|
4
17
|
await runInstall(process.argv.slice(3));
|
|
5
18
|
} else if (process.argv.includes("--session-hook")) {
|
|
6
|
-
const { runSessionHook } = await import("./sessionIdentity.js");
|
|
19
|
+
const { runSessionHook } = await import("./session/sessionIdentity.js");
|
|
7
20
|
await runSessionHook();
|
|
8
21
|
} else if (process.argv.includes("--print-agents-md")) {
|
|
9
|
-
const { AGENTS_MD_GUIDE } = await import("./agentsGuide.js");
|
|
22
|
+
const { AGENTS_MD_GUIDE } = await import("./setup/agentsGuide.js");
|
|
10
23
|
process.stdout.write(`${AGENTS_MD_GUIDE}\n`);
|
|
11
24
|
} else {
|
|
12
|
-
await import("./serverMain.js");
|
|
25
|
+
await import("./server/serverMain.js");
|
|
13
26
|
}
|
|
@@ -11,10 +11,10 @@ import { PeriodicExportingMetricReader } from "@opentelemetry/sdk-metrics";
|
|
|
11
11
|
import { BatchLogRecordProcessor } from "@opentelemetry/sdk-logs";
|
|
12
12
|
|
|
13
13
|
import { log } from "./log.js";
|
|
14
|
-
import { API_URL, getSessionToken, getWorkspaceToken } from "
|
|
15
|
-
import { readMarker } from "
|
|
14
|
+
import { API_URL, getSessionToken, getWorkspaceToken } from "../auth/deviceAuth.js";
|
|
15
|
+
import { readMarker } from "../workspace/workspaceMarker.js";
|
|
16
16
|
|
|
17
|
-
const packageJson = createRequire(import.meta.url)("
|
|
17
|
+
const packageJson = createRequire(import.meta.url)("../../package.json");
|
|
18
18
|
|
|
19
19
|
const OTLP_BASE = `${API_URL}/api/v1/otel`;
|
|
20
20
|
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
// RSI bundle tool-hint hydration (RSI MCP spec §4.4).
|
|
2
|
+
//
|
|
3
|
+
// The org's RSI bundle can refine how agents use Harmony's tools without a new harmony-mcp release: each hint
|
|
4
|
+
// appends a bounded suffix to a tool's description and, optionally, to its parameters' descriptions. Hints never
|
|
5
|
+
// rename tools, add or remove parameters, or change schema types, and the auth/setup tools are never touched
|
|
6
|
+
// (their descriptions carry the user-consent rules).
|
|
7
|
+
//
|
|
8
|
+
// Flow: boot from the on-disk cache (tools/list is right on the first call), then in the background ask the
|
|
9
|
+
// backend which bundle this session is pinned to (POST /rsi/pin) and, if it differs from the cache, fetch it
|
|
10
|
+
// (GET /api/rsi/bundles/{id}), rewrite the cache and tell the host the tool list changed.
|
|
11
|
+
import { atomicWriteFile, harmonyPath, readJsonFile } from "./localState.js";
|
|
12
|
+
|
|
13
|
+
export const CACHE_SCHEMA_VERSION = 1;
|
|
14
|
+
const MAX_DESCRIPTION_SUFFIX_CHARS = 400;
|
|
15
|
+
const MAX_PARAM_HINT_CHARS = 200;
|
|
16
|
+
const MAX_HINTED_TOOLS = 32;
|
|
17
|
+
|
|
18
|
+
// Tools whose descriptions enforce user consent (login confirmation, indexing despite secrets): never hinted.
|
|
19
|
+
export const HINT_EXEMPT_TOOLS = new Set(["login", "confirm_login", "setup_workspace"]);
|
|
20
|
+
|
|
21
|
+
const state = {
|
|
22
|
+
workspaceId: null,
|
|
23
|
+
bundleId: null,
|
|
24
|
+
hints: {},
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
export function activeBundleId() {
|
|
28
|
+
return state.bundleId;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
// The bundle to pin calls for this workspace to, so every call runs on the bundle whose hints the agent was shown.
|
|
32
|
+
export function activeBundleIdFor(workspaceId) {
|
|
33
|
+
return workspaceId != null && state.workspaceId === String(workspaceId) ? state.bundleId : null;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function activeHints() {
|
|
37
|
+
return state.hints;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// The bundle this process asks the backend for: an explicit override, else the backend's choice for the org.
|
|
41
|
+
export function requestedBundleId(marker) {
|
|
42
|
+
const explicit = process.env.HARMONY_RSI_BUNDLE_ID || marker?.rsiBundleId;
|
|
43
|
+
return typeof explicit === "string" && explicit.trim() ? explicit.trim() : null;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function bundleCachePath(workspaceId) {
|
|
47
|
+
const safe = String(workspaceId).replace(/[^A-Za-z0-9_-]/g, "_");
|
|
48
|
+
return harmonyPath("cache", "bundles", `ws-${safe}-manifest.json`);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// Printable text only, bounded. Newlines are kept (suffixes may be short lists); other control chars are not.
|
|
52
|
+
function cleanText(value, maxChars) {
|
|
53
|
+
if (typeof value !== "string") return null;
|
|
54
|
+
const text = value.replace(/[\u0000-\u0009\u000b-\u001f\u007f]/g, " ").replace(/\n{3,}/g, "\n\n").trim();
|
|
55
|
+
if (!text) return null;
|
|
56
|
+
return text.length > maxChars ? `${text.slice(0, maxChars - 1)}…` : text;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
// Accepts both the backend's current shape ({tool: "suffix"}) and the spec's ({tool: {descriptionSuffix, paramHints}}).
|
|
60
|
+
export function normalizeToolHints(raw) {
|
|
61
|
+
const out = {};
|
|
62
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return out;
|
|
63
|
+
for (const [tool, value] of Object.entries(raw).slice(0, MAX_HINTED_TOOLS)) {
|
|
64
|
+
if (!/^[a-z][a-z0-9_]{0,63}$/.test(tool) || HINT_EXEMPT_TOOLS.has(tool)) continue;
|
|
65
|
+
const hint = {};
|
|
66
|
+
const suffix = cleanText(typeof value === "string" ? value : value?.descriptionSuffix, MAX_DESCRIPTION_SUFFIX_CHARS);
|
|
67
|
+
if (suffix) hint.descriptionSuffix = suffix;
|
|
68
|
+
if (value && typeof value === "object" && value.paramHints && typeof value.paramHints === "object") {
|
|
69
|
+
const params = {};
|
|
70
|
+
for (const [param, text] of Object.entries(value.paramHints)) {
|
|
71
|
+
const cleaned = cleanText(text, MAX_PARAM_HINT_CHARS);
|
|
72
|
+
if (cleaned && /^[A-Za-z_][A-Za-z0-9_]{0,63}$/.test(param)) params[param] = cleaned;
|
|
73
|
+
}
|
|
74
|
+
if (Object.keys(params).length) hint.paramHints = params;
|
|
75
|
+
}
|
|
76
|
+
if (Object.keys(hint).length) out[tool] = hint;
|
|
77
|
+
}
|
|
78
|
+
return out;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// maxTokens -> max_tokens: bundle authors may use the backend's camelCase names for the tool's snake_case params.
|
|
82
|
+
function snakeCase(name) {
|
|
83
|
+
return name.replace(/([a-z0-9])([A-Z])/g, "$1_$2").toLowerCase();
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// A copy of `tools` with hints merged in. Tools without a hint are returned as the same objects.
|
|
87
|
+
export function applyToolHints(tools, hints = state.hints) {
|
|
88
|
+
if (!hints || !Object.keys(hints).length) return tools;
|
|
89
|
+
return tools.map((tool) => {
|
|
90
|
+
const hint = hints[tool.name];
|
|
91
|
+
if (!hint || HINT_EXEMPT_TOOLS.has(tool.name)) return tool;
|
|
92
|
+
const merged = { ...tool };
|
|
93
|
+
if (hint.descriptionSuffix) merged.description = `${tool.description}\n\n${hint.descriptionSuffix}`;
|
|
94
|
+
const properties = tool.inputSchema?.properties;
|
|
95
|
+
if (hint.paramHints && properties) {
|
|
96
|
+
const nextProps = { ...properties };
|
|
97
|
+
let touched = false;
|
|
98
|
+
for (const [param, text] of Object.entries(hint.paramHints)) {
|
|
99
|
+
const key = param in nextProps ? param : snakeCase(param);
|
|
100
|
+
if (!(key in nextProps)) continue;
|
|
101
|
+
const prop = nextProps[key];
|
|
102
|
+
nextProps[key] = { ...prop, description: prop.description ? `${prop.description} ${text}` : text };
|
|
103
|
+
touched = true;
|
|
104
|
+
}
|
|
105
|
+
if (touched) merged.inputSchema = { ...tool.inputSchema, properties: nextProps };
|
|
106
|
+
}
|
|
107
|
+
return merged;
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function sameHints(a, b) {
|
|
112
|
+
return JSON.stringify(a || {}) === JSON.stringify(b || {});
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
// Loads the cached bundle for this workspace and backend. Returns true if hints were loaded.
|
|
116
|
+
export function loadCachedBundle(workspaceId, apiUrl) {
|
|
117
|
+
if (!workspaceId) return false;
|
|
118
|
+
const cached = readJsonFile(bundleCachePath(workspaceId));
|
|
119
|
+
if (
|
|
120
|
+
cached?.schemaVersion !== CACHE_SCHEMA_VERSION ||
|
|
121
|
+
cached.apiUrl !== apiUrl ||
|
|
122
|
+
String(cached.workspaceId) !== String(workspaceId) ||
|
|
123
|
+
typeof cached.bundleId !== "string"
|
|
124
|
+
) {
|
|
125
|
+
return false;
|
|
126
|
+
}
|
|
127
|
+
state.workspaceId = String(workspaceId);
|
|
128
|
+
state.bundleId = cached.bundleId;
|
|
129
|
+
state.hints = normalizeToolHints(cached.mcpToolHints);
|
|
130
|
+
return true;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// Asks the backend which bundle this session runs on and refreshes hints if it changed.
|
|
134
|
+
// pin(workspaceId, requestedBundleId) -> pinned bundle id, or null when the backend has no RSI support
|
|
135
|
+
// fetchBundle(bundleId) -> bundle JSON ({manifest, mcpToolHints, managedAgentInstructionsMarkdown, ...})
|
|
136
|
+
// Returns { bundleId, changed } where changed means the tool list the host sees is different.
|
|
137
|
+
export async function refreshBundle({ workspaceId, apiUrl, requested, pin, fetchBundle }) {
|
|
138
|
+
if (!workspaceId) return { bundleId: state.bundleId, changed: false };
|
|
139
|
+
const sameWorkspace = state.workspaceId === String(workspaceId);
|
|
140
|
+
const pinnedId = await pin(workspaceId, requested);
|
|
141
|
+
if (!pinnedId) {
|
|
142
|
+
// Backend without RSI: drop hints that came from a cache for a different workspace.
|
|
143
|
+
if (!sameWorkspace && Object.keys(state.hints).length) {
|
|
144
|
+
Object.assign(state, { workspaceId: String(workspaceId), bundleId: null, hints: {} });
|
|
145
|
+
return { bundleId: null, changed: true };
|
|
146
|
+
}
|
|
147
|
+
return { bundleId: state.bundleId, changed: false };
|
|
148
|
+
}
|
|
149
|
+
if (sameWorkspace && state.bundleId === pinnedId) return { bundleId: pinnedId, changed: false };
|
|
150
|
+
|
|
151
|
+
const bundle = await fetchBundle(pinnedId);
|
|
152
|
+
const hints = normalizeToolHints(bundle?.mcpToolHints);
|
|
153
|
+
const changed = !sameHints(hints, sameWorkspace ? state.hints : {}) || (!sameWorkspace && Object.keys(state.hints).length > 0);
|
|
154
|
+
Object.assign(state, { workspaceId: String(workspaceId), bundleId: pinnedId, hints });
|
|
155
|
+
|
|
156
|
+
atomicWriteFile(
|
|
157
|
+
bundleCachePath(workspaceId),
|
|
158
|
+
`${JSON.stringify(
|
|
159
|
+
{
|
|
160
|
+
schemaVersion: CACHE_SCHEMA_VERSION,
|
|
161
|
+
apiUrl,
|
|
162
|
+
workspaceId: String(workspaceId),
|
|
163
|
+
bundleId: pinnedId,
|
|
164
|
+
fetchedAtEpochMs: Date.now(),
|
|
165
|
+
mcpToolHints: hints,
|
|
166
|
+
managedAgentInstructionsMd: typeof bundle?.managedAgentInstructionsMarkdown === "string"
|
|
167
|
+
? bundle.managedAgentInstructionsMarkdown : "",
|
|
168
|
+
workspaceWorldModelMd: typeof bundle?.workspaceWorldModelMarkdown === "string"
|
|
169
|
+
? bundle.workspaceWorldModelMarkdown : "",
|
|
170
|
+
},
|
|
171
|
+
null,
|
|
172
|
+
2,
|
|
173
|
+
)}\n`,
|
|
174
|
+
);
|
|
175
|
+
return { bundleId: pinnedId, changed };
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
// Test hook.
|
|
179
|
+
export function resetBundleStateForTests() {
|
|
180
|
+
Object.assign(state, { workspaceId: null, bundleId: null, hints: {} });
|
|
181
|
+
}
|