@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.
Files changed (47) hide show
  1. package/README.md +217 -15
  2. package/package.json +4 -2
  3. package/src/{deviceAuth.js → auth/deviceAuth.js} +39 -8
  4. package/src/{harmonyClient.js → backend/harmonyClient.js} +183 -13
  5. package/src/doctor/doctorCommand.js +385 -0
  6. package/src/index.js +18 -5
  7. package/src/{telemetry.js → observability/telemetry.js} +3 -3
  8. package/src/rsi/bundleHints.js +181 -0
  9. package/src/rsi/bundleRefresher.js +95 -0
  10. package/src/rsi/callContext.js +49 -0
  11. package/src/rsi/causalState.js +103 -0
  12. package/src/rsi/clientAgent.js +58 -0
  13. package/src/rsi/hooks/eventBuilder.js +129 -0
  14. package/src/rsi/hooks/fileHash.js +33 -0
  15. package/src/rsi/hooks/hmacSigner.js +69 -0
  16. package/src/rsi/hooks/hookEventCommand.js +196 -0
  17. package/src/rsi/hooks/normalizers.js +329 -0
  18. package/src/rsi/hooks/offlineSpooler.js +142 -0
  19. package/src/rsi/hooks/secretScrubber.js +50 -0
  20. package/src/rsi/hooks/shellCommandScrubber.js +449 -0
  21. package/src/rsi/hooks/spoolDrainer.js +78 -0
  22. package/src/rsi/hooks/toolEventsClient.js +70 -0
  23. package/src/rsi/localState.js +53 -0
  24. package/src/rsi/serveTelemetry.js +101 -0
  25. package/src/rsi/workspaceRegistry.js +63 -0
  26. package/src/{server.js → server/server.js} +107 -17
  27. package/src/{serverInstructions.js → server/serverInstructions.js} +2 -2
  28. package/src/server/serverMain.js +46 -0
  29. package/src/{sessionIdentity.js → session/sessionIdentity.js} +10 -6
  30. package/src/setup/agentCapabilityMatrix.js +425 -0
  31. package/src/setup/agentsGuide.js +28 -0
  32. package/src/setup/configMergers.js +272 -0
  33. package/src/{installer.js → setup/installer.js} +1 -1
  34. package/src/setup/setupAgentsCommand.js +192 -0
  35. package/src/setup/shim.js +80 -0
  36. package/src/sync/managedMarkdownInjector.js +103 -0
  37. package/src/sync/syncWorkspaceCommand.js +143 -0
  38. package/src/sync/workspaceSync.js +88 -0
  39. package/src/{fileWatcher.js → workspace/fileWatcher.js} +2 -2
  40. package/src/{workspaceIdentity.js → workspace/workspaceIdentity.js} +1 -1
  41. package/src/agentsGuide.js +0 -38
  42. package/src/serverMain.js +0 -32
  43. /package/src/{log.js → observability/log.js} +0 -0
  44. /package/src/{toolSchemas.js → server/toolSchemas.js} +0 -0
  45. /package/src/{fileFilters.js → workspace/fileFilters.js} +0 -0
  46. /package/src/{repoIdentity.js → workspace/repoIdentity.js} +0 -0
  47. /package/src/{workspaceMarker.js → workspace/workspaceMarker.js} +0 -0
@@ -1,28 +1,66 @@
1
1
  import fs from "fs";
2
2
  import path from "path";
3
3
  import crypto from "crypto";
4
+ import { createRequire } from "module";
4
5
  import archiver from "archiver";
5
6
  import FormData from "form-data";
6
7
 
7
- import { log } from "./log.js";
8
- import { currentSessionId } from "./sessionIdentity.js";
9
- import { tracedFetch as fetch, getActiveTraceId } from "./telemetry.js";
8
+ import { log } from "../observability/log.js";
9
+ import { currentSessionId, sessionIdSource } from "../session/sessionIdentity.js";
10
+ import { tracedFetch as fetch, getActiveTraceId } from "../observability/telemetry.js";
10
11
  import {
11
12
  getSessionToken,
12
13
  getWorkspaceToken,
13
14
  getWorkspaceRefreshToken,
14
15
  saveWorkspaceToken,
15
16
  isJwtExpired,
16
- } from "./deviceAuth.js";
17
- import { buildWorkspaceMetadata, PRODUCT_ID, APP_ID, REPO_ID } from "./workspaceIdentity.js";
18
- import { readMarker, writeMarker } from "./workspaceMarker.js";
19
- import { getGitCommitHash } from "./repoIdentity.js";
20
- import { buildZipIgnoreGlobs } from "./fileFilters.js";
17
+ } from "../auth/deviceAuth.js";
18
+ import { buildWorkspaceMetadata, PRODUCT_ID, APP_ID, REPO_ID } from "../workspace/workspaceIdentity.js";
19
+ import { readMarker, writeMarker } from "../workspace/workspaceMarker.js";
20
+ import { getGitCommitHash } from "../workspace/repoIdentity.js";
21
+ import { buildZipIgnoreGlobs } from "../workspace/fileFilters.js";
22
+ import { currentCallContext } from "../rsi/callContext.js";
23
+ import { activeBundleIdFor, requestedBundleId } from "../rsi/bundleHints.js";
24
+ import { recordCausalState } from "../rsi/causalState.js";
25
+
26
+ const MCP_VERSION = createRequire(import.meta.url)("../../package.json").version;
21
27
 
22
28
  export const API_URL = (process.env.API_URL || "https://harmony.codeconductor.ai/").replace(/\/+$/, "");
23
29
 
24
- function sessionHeader() {
25
- return { "X-Mcp-Session-Id": currentSessionId() };
30
+ // Session and RSI headers sent on every workspace call (RSI wire contract §1.1): which agent session this is,
31
+ // which agent and MCP version made it, which RSI bundle the session runs on, and the agent's own W3C trace
32
+ // context when it sent one (tracedFetch replaces traceparent with a child span's when OTel export is on).
33
+ function sessionHeader(workspaceId) {
34
+ const ctx = currentCallContext();
35
+ const headers = {
36
+ "X-Mcp-Session-Id": currentSessionId(),
37
+ "X-Harmony-Client-Agent": ctx.clientAgent,
38
+ "X-Harmony-Mcp-Version": MCP_VERSION,
39
+ ...ctx.trace,
40
+ };
41
+ // An explicitly requested bundle wins from the very first call: the backend pins a session on its first request,
42
+ // and a cached id from an earlier session (or none) would pin the wrong bundle while the startup pin is in flight.
43
+ const bundleId = requestedBundleId(readMarker()) || activeBundleIdFor(workspaceId);
44
+ if (bundleId) headers["X-Rsi-Bundle-Id"] = bundleId;
45
+ return headers;
46
+ }
47
+
48
+ // After a 200 from a query endpoint, record it as the parent for the next local tool hook. Never fails the call.
49
+ function noteBackendResponse(endpointPath, response, workspaceId) {
50
+ try {
51
+ recordCausalState({
52
+ endpointPath,
53
+ workspaceId,
54
+ mcpSessionId: currentSessionId(),
55
+ sessionSource: sessionIdSource(),
56
+ clientAgent: currentCallContext().clientAgent,
57
+ ledgerId: response.headers.get("x-harmony-ledger-id"),
58
+ traceId: response.headers.get("x-trace-id") || getActiveTraceId(),
59
+ bundleId: response.headers.get("x-harmony-bundle-id") || activeBundleIdFor(workspaceId),
60
+ });
61
+ } catch (error) {
62
+ log(`[rsi] could not write causal state: ${error.message}`);
63
+ }
26
64
  }
27
65
 
28
66
  async function refreshWorkspaceToken(workspaceId, refreshToken) {
@@ -42,7 +80,7 @@ async function refreshWorkspaceToken(workspaceId, refreshToken) {
42
80
  return newAccessToken;
43
81
  }
44
82
 
45
- async function resolveToken(workspaceId) {
83
+ export async function resolveToken(workspaceId) {
46
84
  const sessionToken = await getSessionToken();
47
85
  if (sessionToken) return sessionToken;
48
86
 
@@ -342,7 +380,7 @@ export async function callHarmonySearchEndpoint(endpointPath, args, workspaceId)
342
380
  headers: {
343
381
  "Content-Type": "application/json",
344
382
  Accept: "application/xml",
345
- ...sessionHeader(),
383
+ ...sessionHeader(workspaceId),
346
384
  ...(await authHeader(workspaceId)),
347
385
  },
348
386
  body: JSON.stringify(requestBody),
@@ -351,6 +389,7 @@ export async function callHarmonySearchEndpoint(endpointPath, args, workspaceId)
351
389
  if (!response.ok) {
352
390
  throw new Error(`${endpointPath} request failed: ${response.status} ${body}${traceSuffix()}`);
353
391
  }
392
+ noteBackendResponse(endpointPath, response, workspaceId);
354
393
  return body;
355
394
  }
356
395
 
@@ -364,7 +403,7 @@ async function callHarmonyJsonEndpoint(endpointPath, requestBody, workspaceId, a
364
403
  headers: {
365
404
  "Content-Type": "application/json",
366
405
  Accept: accept,
367
- ...sessionHeader(),
406
+ ...sessionHeader(workspaceId),
368
407
  ...(await authHeader(workspaceId)),
369
408
  },
370
409
  body: JSON.stringify(requestBody),
@@ -373,6 +412,7 @@ async function callHarmonyJsonEndpoint(endpointPath, requestBody, workspaceId, a
373
412
  if (!response.ok) {
374
413
  throw new Error(`${endpointPath} request failed: ${response.status} ${body}${traceSuffix()}`);
375
414
  }
415
+ noteBackendResponse(endpointPath, response, workspaceId);
376
416
  return body;
377
417
  }
378
418
 
@@ -534,3 +574,133 @@ export async function sendFileDelete(filePath, workspaceId) {
534
574
  return { ok: false, status: null, body: error.message };
535
575
  }
536
576
  }
577
+
578
+ // ---- RSI bundle (RSI MCP spec §4.4, against the backend's RsiController). ----
579
+ const RSI_REQUEST_TIMEOUT_MS = 5_000;
580
+
581
+ // Statuses meaning "this backend has no RSI for us" rather than a failure worth logging loudly.
582
+ const RSI_UNSUPPORTED_STATUSES = new Set([401, 403, 404, 405, 501]);
583
+
584
+ // POST /api/code-workspace/{workspaceId}/rsi/pin — pins this session to a bundle (the requested one, else the
585
+ // backend's choice) and returns its id. null when the backend has no RSI support or the call fails.
586
+ export async function callRsiPin(workspaceId, requestedBundleId) {
587
+ try {
588
+ const response = await fetch(`${API_URL}/api/code-workspace/${workspaceId}/rsi/pin`, {
589
+ method: "POST",
590
+ headers: {
591
+ "Content-Type": "application/json",
592
+ Accept: "application/json",
593
+ ...sessionHeader(workspaceId),
594
+ ...(await authHeader(workspaceId)),
595
+ },
596
+ body: JSON.stringify(requestedBundleId ? { bundleId: requestedBundleId } : {}),
597
+ signal: AbortSignal.timeout(RSI_REQUEST_TIMEOUT_MS),
598
+ });
599
+ if (!response.ok) {
600
+ if (!RSI_UNSUPPORTED_STATUSES.has(response.status)) log(`[rsi] pin failed: HTTP ${response.status}${traceSuffix()}`);
601
+ return null;
602
+ }
603
+ const json = await response.json();
604
+ return typeof json?.pinnedBundleId === "string" && json.pinnedBundleId ? json.pinnedBundleId : null;
605
+ } catch (error) {
606
+ log(`[rsi] pin failed: ${error.message}`);
607
+ return null;
608
+ }
609
+ }
610
+
611
+ // GET /api/rsi/bundles/{bundleId} — the bundle's tool hints and managed instructions. Throws on failure.
612
+ export async function fetchRsiBundle(workspaceId, bundleId) {
613
+ const response = await fetch(`${API_URL}/api/rsi/bundles/${encodeURIComponent(bundleId)}`, {
614
+ method: "GET",
615
+ headers: { Accept: "application/json", ...sessionHeader(workspaceId), ...(await authHeader(workspaceId)) },
616
+ signal: AbortSignal.timeout(RSI_REQUEST_TIMEOUT_MS),
617
+ });
618
+ if (!response.ok) throw new Error(`RSI bundle ${bundleId} fetch failed: HTTP ${response.status}${traceSuffix()}`);
619
+ return response.json();
620
+ }
621
+
622
+ // RSI telemetry (key, tool events) is keyed per (org, user), and only a user login identifies both: the backend
623
+ // treats a workspace token as the workspace id in org 1. So telemetry uses the user login only, never the
624
+ // workspace token. null when nobody is logged in.
625
+ export async function resolveUserToken() {
626
+ try {
627
+ return (await getSessionToken()) || null;
628
+ } catch {
629
+ return null;
630
+ }
631
+ }
632
+
633
+ // POST /api/code-workspace/{workspaceId}/rsi/telemetry-key (wire contract §4) — the HMAC key for tool-events.
634
+ // Returns the 64-hex key, or null when nobody is logged in or the backend does not issue keys. Never logs the key.
635
+ export async function fetchTelemetryKeyHex(workspaceId, { rotate = false } = {}) {
636
+ const userToken = await resolveUserToken();
637
+ if (!userToken) return null;
638
+ try {
639
+ const response = await fetch(`${API_URL}/api/code-workspace/${workspaceId}/rsi/telemetry-key`, {
640
+ method: "POST",
641
+ headers: {
642
+ "Content-Type": "application/json",
643
+ Accept: "application/json",
644
+ ...sessionHeader(workspaceId),
645
+ Authorization: `Bearer ${userToken}`,
646
+ },
647
+ body: JSON.stringify(rotate ? { rotate: true } : {}),
648
+ signal: AbortSignal.timeout(RSI_REQUEST_TIMEOUT_MS),
649
+ });
650
+ if (!response.ok) {
651
+ if (!RSI_UNSUPPORTED_STATUSES.has(response.status) && response.status !== 503) {
652
+ log(`[rsi] telemetry key request failed: HTTP ${response.status}${traceSuffix()}`);
653
+ }
654
+ return null;
655
+ }
656
+ const json = await response.json();
657
+ return typeof json?.telemetryKeyHex === "string" && /^[0-9a-f]{64}$/.test(json.telemetryKeyHex) ? json.telemetryKeyHex : null;
658
+ } catch (error) {
659
+ log(`[rsi] telemetry key request failed: ${error.message}`);
660
+ return null;
661
+ }
662
+ }
663
+
664
+ // ---- Diagnostics (harmony-mcp doctor). Never throws; never returns tokens. ----
665
+
666
+ // One request with a short timeout: { ok, status, ms, json, text, error }. status null = backend unreachable.
667
+ // userAuth: send only the user login (RSI telemetry endpoints; see resolveUserToken).
668
+ export async function probeBackend(pathAndQuery, { method = "GET", body, workspaceId, timeoutMs = 3_000, auth = true, userAuth = false } = {}) {
669
+ const startedAt = Date.now();
670
+ try {
671
+ let authHeaders = {};
672
+ if (userAuth) {
673
+ const userToken = await resolveUserToken();
674
+ if (!userToken) return { ok: false, status: null, ms: 0, error: "not logged in (telemetry needs a user login, not the workspace token)" };
675
+ authHeaders = { Authorization: `Bearer ${userToken}` };
676
+ } else if (auth) {
677
+ authHeaders = await authHeader(workspaceId);
678
+ }
679
+ const response = await fetch(`${API_URL}${pathAndQuery}`, {
680
+ method,
681
+ headers: {
682
+ Accept: "application/json, application/xml;q=0.9, */*;q=0.8",
683
+ ...(body !== undefined ? { "Content-Type": "application/json" } : {}),
684
+ ...sessionHeader(workspaceId),
685
+ ...authHeaders,
686
+ },
687
+ body: body === undefined ? undefined : JSON.stringify(body),
688
+ signal: AbortSignal.timeout(timeoutMs),
689
+ });
690
+ const text = await response.text();
691
+ let json = null;
692
+ try {
693
+ json = JSON.parse(text);
694
+ } catch {
695
+ // not JSON
696
+ }
697
+ return { ok: response.ok, status: response.status, ms: Date.now() - startedAt, json, text: text.slice(0, 2_000) };
698
+ } catch (error) {
699
+ return { ok: false, status: null, ms: Date.now() - startedAt, error: error?.name === "TimeoutError" ? "timed out" : error?.message };
700
+ }
701
+ }
702
+
703
+ export function workspaceStatusPath(workspaceId) {
704
+ const params = new URLSearchParams({ productId: PRODUCT_ID, appId: APP_ID, repoId: REPO_ID });
705
+ return `/api/code-workspace/${workspaceId}/status?${params}`;
706
+ }
@@ -0,0 +1,385 @@
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, telemetryKeyEndpoint, telemetryKeyId, telemetryKeyMatches, 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, ws.endpoint);
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
+ const match = ws.endpoint ? telemetryKeyMatches(ws.endpoint) : null;
231
+ if (!key) 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
+ else if (match === true) r.add("ok", "telemetry key", `${telemetryKeyId(key)} (issued by this backend)`);
233
+ else if (match === false) r.add("warn", "telemetry key", `${telemetryKeyId(key)} was issued by ${telemetryKeyEndpoint()}, not ${ws.endpoint}; hooks spool until the MCP server fetches this backend's key`, "start the MCP server in this repo, or run doctor --rotate-telemetry-key");
234
+ else r.add("info", "telemetry key", `${telemetryKeyId(key)} (issuing backend not recorded; the MCP server replaces it with this backend's key on its next start)`);
235
+ }
236
+
237
+ async function checkHooks(r, ws) {
238
+ r.start("Agent hooks");
239
+ const { AGENTS } = await import("../setup/agentCapabilityMatrix.js");
240
+ const { isHarmonyHookCommand } = await import("../setup/configMergers.js");
241
+ const ctx = { scope: "user", project: ws.root };
242
+ let any = false;
243
+ const missing = [];
244
+ for (const agent of AGENTS) {
245
+ if (!agent.installHooks || !agent.detect()) continue;
246
+ any = true;
247
+ const files = agent.hookFiles(ctx);
248
+ const installed = files.some((f) => {
249
+ try {
250
+ return fs.readFileSync(f, "utf8").split(/\r?\n/).some((line) => isHarmonyHookCommand(line));
251
+ } catch {
252
+ return false;
253
+ }
254
+ });
255
+ if (installed) r.add("ok", agent.name, "hooks installed");
256
+ else missing.push(agent);
257
+ }
258
+ // Hooks are optional (they only feed Harmony's learning), so missing ones are information, not a warning.
259
+ if (missing.length) {
260
+ r.add("info", "not installed", missing.map((a) => a.name).join(", "), `harmony-mcp setup-agents --agents ${missing.map((a) => a.id).join(",")}`);
261
+ }
262
+ if (!any) r.add("info", "agents", "no hook-capable agent detected");
263
+ }
264
+
265
+ function checkPipeline(r, ws) {
266
+ r.start("Hook telemetry");
267
+ let count = 0;
268
+ let oldest = null;
269
+ for (const file of listSpoolFiles()) {
270
+ try {
271
+ const lines = fs.readFileSync(file, "utf8").split("\n").filter(Boolean);
272
+ count += lines.length;
273
+ const ts = JSON.parse(lines[0] || "null")?.event?.clientTimestampEpochMs;
274
+ if (ts && (!oldest || ts < oldest)) oldest = ts;
275
+ } catch {
276
+ // unreadable spool file
277
+ }
278
+ }
279
+ if (!count) r.add("ok", "spool", "empty (nothing waiting to be sent)");
280
+ 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);
281
+
282
+ if (ws.workspaceId) {
283
+ // Read the state as-is: doctor is not an agent session, so the hooks' same-session rule does not apply here.
284
+ const raw = readJsonFile(statePath(ws.root));
285
+ const age = raw?.updatedAtEpochMs ? Date.now() - raw.updatedAtEpochMs : null;
286
+ if (age === null) r.add("info", "last Harmony call", "none recorded for this repo yet");
287
+ 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)`);
288
+ 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)"}`);
289
+ }
290
+
291
+ const logFile = harmonyPath("logs", "harmony-mcp.log");
292
+ try {
293
+ const dayAgo = Date.now() - 86_400_000;
294
+ const errors = fs
295
+ .readFileSync(logFile, "utf8")
296
+ .split("\n")
297
+ .filter((l) => l.includes("[hook-event") && !/: (sent|spooled|no-actions|no-events|unregistered-workspace)\b/.test(l))
298
+ .filter((l) => Date.parse(l.slice(1, 25)) >= dayAgo);
299
+ 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)}`);
300
+ } catch {
301
+ // no hook log yet
302
+ }
303
+ }
304
+
305
+ async function checkRoi(r, client, ws) {
306
+ r.start("Value (ROI)");
307
+ let res = await client.probeBackend("/api/rsi/outcomes/summary", { workspaceId: ws.workspaceId });
308
+ if (res.status === 404) res = await client.probeBackend(`/api/code-workspace/${ws.workspaceId}/rsi/value-summary`, { workspaceId: ws.workspaceId });
309
+ const s = res.json;
310
+ if (!res.ok || !s || typeof s !== "object") {
311
+ r.add("info", "summary", res.status === 404 ? "not available on this backend" : `not available (${res.status === null ? res.error : `HTTP ${res.status}`})`);
312
+ return;
313
+ }
314
+ if (!s.sampleCount) {
315
+ r.add("info", "summary", "no recorded Harmony calls yet for your organization");
316
+ return;
317
+ }
318
+ // Measured by the backend: the files each answer covers, read in full, minus what Harmony sent. Time is a heuristic.
319
+ const saved = s.totalExactTokensSaved ?? s.totalEstimatedTokensSaved;
320
+ // The backend's averageCompressionRatio is the fraction of tokens saved per call (0.47 = answers 47% smaller).
321
+ const ratio = typeof s.averageCompressionRatio === "number" ? `, answers on average ${Math.round(s.averageCompressionRatio * 100)}% smaller` : "";
322
+ const secs = typeof s.totalEstimatedSecondsSaved === "number" ? `, ~${Math.round(s.totalEstimatedSecondsSaved / 60)} min saved (estimate)` : "";
323
+ r.add("ok", "summary", `${fmtInt(s.sampleCount)} calls (org-wide${s.bundleId ? `, bundle ${s.bundleId}` : ""}): ~${fmtInt(saved)} tokens saved${ratio}${secs}`);
324
+ }
325
+
326
+ // ---------- output ----------
327
+
328
+ const MARK = { ok: "ok ", warn: "WARN", fail: "FAIL", info: "info" };
329
+
330
+ function render(items, root) {
331
+ const lines = [`Harmony doctor — ${tilde(root)}`];
332
+ let section = null;
333
+ for (const it of items) {
334
+ if (it.section !== section) {
335
+ section = it.section;
336
+ lines.push("", section);
337
+ }
338
+ lines.push(` ${MARK[it.level]} ${it.check.padEnd(18)} ${it.detail}`);
339
+ if (it.fix) lines.push(` ${" ".repeat(6)}${" ".repeat(18)} → ${it.fix}`);
340
+ }
341
+ const fails = items.filter((i) => i.level === "fail").length;
342
+ const warns = items.filter((i) => i.level === "warn").length;
343
+ lines.push("", fails ? `${fails} problem${fails === 1 ? "" : "s"}, ${warns} warning${warns === 1 ? "" : "s"}.` : warns ? `Working, with ${warns} warning${warns === 1 ? "" : "s"}.` : "All good.");
344
+ return `${lines.join("\n")}\n`;
345
+ }
346
+
347
+ export async function runDoctor(argv, { out = process.stdout, err = process.stderr } = {}) {
348
+ let opts;
349
+ try {
350
+ opts = parseDoctorArgs(argv);
351
+ } catch (e) {
352
+ err.write(`${e.message}\n\n${USAGE}`);
353
+ return 2;
354
+ }
355
+ if (opts.help) {
356
+ out.write(USAGE);
357
+ return 0;
358
+ }
359
+ const r = new Report();
360
+ checkInstall(r);
361
+ const ws = checkWorkspace(r, opts);
362
+
363
+ if (ws.workspaceId) {
364
+ // deviceAuth / harmonyClient read API_URL and the marker (cwd) at import time.
365
+ if (ws.endpoint) process.env.API_URL = ws.endpoint;
366
+ process.chdir(ws.root);
367
+ await checkCredentials(r, ws);
368
+ let online = false;
369
+ let client = null;
370
+ if (!opts.offline && ws.endpoint) {
371
+ client = await import("../backend/harmonyClient.js");
372
+ online = await checkBackend(r, ws, client);
373
+ }
374
+ await checkRsi(r, ws, client, { online, rotateKey: opts.rotateKey });
375
+ await checkHooks(r, ws);
376
+ checkPipeline(r, ws);
377
+ if (online) await checkRoi(r, client, ws);
378
+ } else {
379
+ await checkHooks(r, ws);
380
+ checkPipeline(r, ws);
381
+ }
382
+
383
+ out.write(opts.json ? `${JSON.stringify({ root: ws.root, workspaceId: ws.workspaceId, checks: r.items }, null, 2)}\n` : render(r.items, ws.root));
384
+ return r.items.some((i) => i.level === "fail") ? 1 : 0;
385
+ }
package/src/index.js CHANGED
@@ -1,13 +1,26 @@
1
1
  #!/usr/bin/env node
2
- if (process.argv[2] === "install") {
3
- const { runInstall } = await import("./installer.js");
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
  }