@codeconductorai/harmony-mcp 1.0.34 → 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 +38 -31
- package/package.json +1 -1
- package/src/auth/deviceAuth.js +37 -6
- package/src/doctor/doctorCommand.js +7 -4
- package/src/rsi/hooks/eventBuilder.js +3 -0
- package/src/rsi/hooks/hmacSigner.js +33 -3
- package/src/rsi/hooks/hookEventCommand.js +1 -1
- package/src/rsi/hooks/offlineSpooler.js +45 -7
- package/src/rsi/hooks/spoolDrainer.js +8 -3
- package/src/rsi/serveTelemetry.js +25 -9
- package/src/server/server.js +3 -3
package/README.md
CHANGED
|
@@ -27,18 +27,18 @@ Re-run `node -v` afterwards to confirm before continuing.
|
|
|
27
27
|
|
|
28
28
|
## Installation
|
|
29
29
|
|
|
30
|
-
The server is published as `@codeconductorai/harmony-mcp` and run via `npx`, so no local build step is required. The commands below pin an exact version (`@1.0.
|
|
30
|
+
The server is published as `@codeconductorai/harmony-mcp` and run via `npx`, so no local build step is required. The commands below pin an exact version (`@1.0.35`) rather than a floating tag — this lets `npx` reuse its local cache instead of re-resolving the package from the registry on every agent startup, which otherwise makes MCP initialization noticeably slower (and occasionally hang). Bump the pinned version deliberately when you want to upgrade.
|
|
31
31
|
|
|
32
32
|
### Claude Code
|
|
33
33
|
|
|
34
34
|
```bash
|
|
35
|
-
npx -y @codeconductorai/harmony-mcp@1.0.
|
|
35
|
+
npx -y @codeconductorai/harmony-mcp@1.0.35 install claude
|
|
36
36
|
```
|
|
37
37
|
|
|
38
38
|
This registers the server for all your projects (`claude mcp add harmony --scope user ...`) and adds the session
|
|
39
39
|
hook from [Session id](#session-id) to `~/.claude/settings.json`. Claude Code reads Harmony's guidance (when to use
|
|
40
40
|
which tool, and to treat returned code as already read) from the server's instructions, so nothing is added to your
|
|
41
|
-
project. To register only the server: `claude mcp add harmony -- npx -y @codeconductorai/harmony-mcp@1.0.
|
|
41
|
+
project. To register only the server: `claude mcp add harmony -- npx -y @codeconductorai/harmony-mcp@1.0.35`.
|
|
42
42
|
|
|
43
43
|
### Antigravity
|
|
44
44
|
|
|
@@ -52,7 +52,7 @@ Open **MCP Servers → Manage MCP Servers → View raw config** from the agent p
|
|
|
52
52
|
"mcpServers": {
|
|
53
53
|
"harmony": {
|
|
54
54
|
"command": "npx",
|
|
55
|
-
"args": ["-y", "@codeconductorai/harmony-mcp@1.0.
|
|
55
|
+
"args": ["-y", "@codeconductorai/harmony-mcp@1.0.35"]
|
|
56
56
|
}
|
|
57
57
|
}
|
|
58
58
|
}
|
|
@@ -65,7 +65,7 @@ Restart Antigravity (or reload MCP servers) after saving.
|
|
|
65
65
|
Run this in your project:
|
|
66
66
|
|
|
67
67
|
```bash
|
|
68
|
-
npx -y @codeconductorai/harmony-mcp@1.0.
|
|
68
|
+
npx -y @codeconductorai/harmony-mcp@1.0.35 install codex
|
|
69
69
|
```
|
|
70
70
|
|
|
71
71
|
It does the three things Codex needs to actually use Harmony, and is safe to run again:
|
|
@@ -80,13 +80,13 @@ It does the three things Codex needs to actually use Harmony, and is safe to run
|
|
|
80
80
|
Each file is backed up once (`*.harmony-bak`) before its first change. Options: `--yes` (no prompt), `--no-agents-md`,
|
|
81
81
|
`--project <dir>`, `--env API_URL=...`, `--dry-run`. If you skip it, `setup_workspace` reminds Codex to offer it.
|
|
82
82
|
|
|
83
|
-
To set it up by hand instead, `codex mcp add harmony -- npx -y @codeconductorai/harmony-mcp@1.0.
|
|
83
|
+
To set it up by hand instead, `codex mcp add harmony -- npx -y @codeconductorai/harmony-mcp@1.0.35` writes the entry
|
|
84
84
|
to `~/.codex/config.toml`, or add:
|
|
85
85
|
|
|
86
86
|
```toml
|
|
87
87
|
[mcp_servers.harmony]
|
|
88
88
|
command = "npx"
|
|
89
|
-
args = ["-y", "@codeconductorai/harmony-mcp@1.0.
|
|
89
|
+
args = ["-y", "@codeconductorai/harmony-mcp@1.0.35"]
|
|
90
90
|
# Harmony's query tools only read the index; pre-approving them avoids an approval prompt (or, with
|
|
91
91
|
# --approve-for-me, an automatic reviewer that costs extra model requests and can reject the calls).
|
|
92
92
|
default_tools_approval_mode = "approve"
|
|
@@ -105,7 +105,7 @@ The installer's other two steps, by hand:
|
|
|
105
105
|
better" section to the project's `AGENTS.md`:
|
|
106
106
|
|
|
107
107
|
```bash
|
|
108
|
-
npx -y @codeconductorai/harmony-mcp@1.0.
|
|
108
|
+
npx -y @codeconductorai/harmony-mcp@1.0.35 --print-agents-md >> AGENTS.md
|
|
109
109
|
```
|
|
110
110
|
|
|
111
111
|
### Aria
|
|
@@ -117,7 +117,7 @@ In the Aria Code panel, click the settings icon → **MCP Servers**, then scroll
|
|
|
117
117
|
"mcpServers": {
|
|
118
118
|
"harmony": {
|
|
119
119
|
"command": "npx",
|
|
120
|
-
"args": ["-y", "@codeconductorai/harmony-mcp@1.0.
|
|
120
|
+
"args": ["-y", "@codeconductorai/harmony-mcp@1.0.35"]
|
|
121
121
|
}
|
|
122
122
|
}
|
|
123
123
|
}
|
|
@@ -134,7 +134,7 @@ Any client that reads a `command`/`args` style config (e.g. Claude Desktop's `cl
|
|
|
134
134
|
"mcpServers": {
|
|
135
135
|
"harmony": {
|
|
136
136
|
"command": "npx",
|
|
137
|
-
"args": ["-y", "@codeconductorai/harmony-mcp@1.0.
|
|
137
|
+
"args": ["-y", "@codeconductorai/harmony-mcp@1.0.35"]
|
|
138
138
|
}
|
|
139
139
|
}
|
|
140
140
|
}
|
|
@@ -169,10 +169,10 @@ backend joins answers + actions ──► "Agent insights" page per workspace in
|
|
|
169
169
|
|
|
170
170
|
To turn it on for a machine:
|
|
171
171
|
|
|
172
|
-
1. `npx -y @codeconductorai/harmony-mcp@1.0.
|
|
172
|
+
1. `npx -y @codeconductorai/harmony-mcp@1.0.35 setup-agents`: adds Harmony and its hooks to every installed agent.
|
|
173
173
|
For Codex, trust the new hooks once in Codex's `/hooks`.
|
|
174
174
|
2. In each repo: `login` (hook events are sent with your user login, not the workspace token), then `setup_workspace`.
|
|
175
|
-
3. `npx -y @codeconductorai/harmony-mcp@1.0.
|
|
175
|
+
3. `npx -y @codeconductorai/harmony-mcp@1.0.35 doctor` in the repo: every check should be green.
|
|
176
176
|
4. Results: **My Workspaces → Agent insights** in the Harmony web app shows tokens saved, how often agents still
|
|
177
177
|
searched or read files after an answer, results per tool and agent, and the files agents had to find themselves.
|
|
178
178
|
|
|
@@ -279,9 +279,9 @@ can add short usage hints to tool descriptions, so how agents use Harmony can im
|
|
|
279
279
|
## Set up every installed agent (`harmony-mcp setup-agents`)
|
|
280
280
|
|
|
281
281
|
```bash
|
|
282
|
-
npx -y @codeconductorai/harmony-mcp@1.0.
|
|
283
|
-
npx -y @codeconductorai/harmony-mcp@1.0.
|
|
284
|
-
npx -y @codeconductorai/harmony-mcp@1.0.
|
|
282
|
+
npx -y @codeconductorai/harmony-mcp@1.0.35 setup-agents # all detected agents, user scope
|
|
283
|
+
npx -y @codeconductorai/harmony-mcp@1.0.35 setup-agents --dry-run # show what would change
|
|
284
|
+
npx -y @codeconductorai/harmony-mcp@1.0.35 setup-agents --uninstall
|
|
285
285
|
```
|
|
286
286
|
|
|
287
287
|
It finds the coding agents on this machine, adds the Harmony MCP server where it is missing, and installs the async
|
|
@@ -311,9 +311,9 @@ tool hooks described below. At the end it prints a table of what each agent now
|
|
|
311
311
|
## Health check (`harmony-mcp doctor`)
|
|
312
312
|
|
|
313
313
|
```bash
|
|
314
|
-
npx -y @codeconductorai/harmony-mcp@1.0.
|
|
315
|
-
npx -y @codeconductorai/harmony-mcp@1.0.
|
|
316
|
-
npx -y @codeconductorai/harmony-mcp@1.0.
|
|
314
|
+
npx -y @codeconductorai/harmony-mcp@1.0.35 doctor # run inside the repo
|
|
315
|
+
npx -y @codeconductorai/harmony-mcp@1.0.35 doctor --json # machine-readable
|
|
316
|
+
npx -y @codeconductorai/harmony-mcp@1.0.35 doctor --offline # local checks only
|
|
317
317
|
```
|
|
318
318
|
|
|
319
319
|
It checks, in order:
|
|
@@ -321,7 +321,8 @@ It checks, in order:
|
|
|
321
321
|
- **Workspace:** whether the repo is set up, and which backend it is bound to.
|
|
322
322
|
- **Credentials:** login and workspace-token expiry. Tokens are never printed.
|
|
323
323
|
- **Backend:** whether it can be reached, how fast, and the index status.
|
|
324
|
-
- **RSI:** the pinned bundle, its tool hints and documents, and the telemetry key (only its id is shown)
|
|
324
|
+
- **RSI:** the pinned bundle, its tool hints and documents, and the telemetry key (only its id is shown), including
|
|
325
|
+
whether this backend issued it.
|
|
325
326
|
- **Agent hooks:** which agents have them.
|
|
326
327
|
- **Hook telemetry:** the spool backlog, the last Harmony call, and hook errors in the last 24 h.
|
|
327
328
|
- **Value:** the organisation's token and time savings, from `/api/rsi/outcomes/summary`.
|
|
@@ -333,9 +334,9 @@ only talks to the backend the repo is bound to, or to `API_URL` if set; it never
|
|
|
333
334
|
## Managed workspace instructions (`harmony-mcp sync-workspace`)
|
|
334
335
|
|
|
335
336
|
```bash
|
|
336
|
-
npx -y @codeconductorai/harmony-mcp@1.0.
|
|
337
|
-
npx -y @codeconductorai/harmony-mcp@1.0.
|
|
338
|
-
npx -y @codeconductorai/harmony-mcp@1.0.
|
|
337
|
+
npx -y @codeconductorai/harmony-mcp@1.0.35 sync-workspace # current repo
|
|
338
|
+
npx -y @codeconductorai/harmony-mcp@1.0.35 sync-workspace --create-if-missing # also create AGENTS.md
|
|
339
|
+
npx -y @codeconductorai/harmony-mcp@1.0.35 sync-workspace --remove # take Harmony's text out again
|
|
339
340
|
```
|
|
340
341
|
|
|
341
342
|
It pulls the workspace's RSI bundle from the backend this repo is bound to (`~/.harmony/workspaces.json`, written by
|
|
@@ -363,11 +364,11 @@ asking Harmony. It helps Harmony learn where its answers fall short. `setup-agen
|
|
|
363
364
|
{
|
|
364
365
|
"hooks": {
|
|
365
366
|
"PostToolUse": [{ "matcher": "Bash|Grep|Glob|Read|Edit|MultiEdit|Write|NotebookEdit",
|
|
366
|
-
"hooks": [{ "type": "command", "command": "npx -y @codeconductorai/harmony-mcp@1.0.
|
|
367
|
+
"hooks": [{ "type": "command", "command": "npx -y @codeconductorai/harmony-mcp@1.0.35 hook-event --agent claude-code", "async": true, "timeout": 5 }] }],
|
|
367
368
|
"PostToolUseFailure": [{ "matcher": "Bash",
|
|
368
|
-
"hooks": [{ "type": "command", "command": "npx -y @codeconductorai/harmony-mcp@1.0.
|
|
369
|
+
"hooks": [{ "type": "command", "command": "npx -y @codeconductorai/harmony-mcp@1.0.35 hook-event --agent claude-code --event PostToolUseFailure", "async": true, "timeout": 5 }] }],
|
|
369
370
|
"PreCompact": [{
|
|
370
|
-
"hooks": [{ "type": "command", "command": "npx -y @codeconductorai/harmony-mcp@1.0.
|
|
371
|
+
"hooks": [{ "type": "command", "command": "npx -y @codeconductorai/harmony-mcp@1.0.35 hook-event --agent claude-code --event PreCompact", "async": true, "timeout": 5 }] }]
|
|
371
372
|
}
|
|
372
373
|
}
|
|
373
374
|
```
|
|
@@ -394,15 +395,21 @@ as-is, or the word tokens of a regex; anything that looks like a credential beco
|
|
|
394
395
|
the Harmony request that came just before. Tool output, file contents, patch hunks, command arguments, and paths
|
|
395
396
|
outside the repo are never sent.
|
|
396
397
|
|
|
397
|
-
- The hook never writes to stdout, always exits 0, and waits at most 450 ms for the backend.
|
|
398
|
+
- The hook never writes to stdout, always exits 0, and waits at most 450 ms for the backend. A remote backend is
|
|
399
|
+
often slower than that (a new TLS connection alone can take over a second); the event is then queued and the MCP
|
|
400
|
+
server sends it, so nothing is lost and the agent is never slowed down.
|
|
398
401
|
- It sends only for repos that the MCP server has bound to a backend in `~/.harmony/workspaces.json`, and only to
|
|
399
402
|
that backend.
|
|
400
403
|
- Each request is signed with `~/.harmony/telemetry.key` (`X-Harmony-Hook-Signature`). The MCP server fetches the
|
|
401
|
-
key from the backend.
|
|
404
|
+
key from the backend when it connects. Keys belong to the backend that issued them (recorded in
|
|
405
|
+
`~/.harmony/telemetry.key.endpoint`): after switching backends, for example from local to production, the old key
|
|
406
|
+
is not used and the server fetches the new backend's key.
|
|
402
407
|
- Events are sent only with your user login (from the `login` tool), never the workspace token, because the
|
|
403
408
|
signing key and the stored events belong to you and your organisation.
|
|
404
|
-
- When the key, a valid login, or the backend is missing, events wait in `~/.harmony/spool/` (at most 2 MiB;
|
|
405
|
-
dropped first). The MCP server sends them on connect
|
|
409
|
+
- When the key, a valid login, or the backend is missing or slow, events wait in `~/.harmony/spool/` (at most 2 MiB;
|
|
410
|
+
oldest dropped first). The MCP server sends them on connect and every minute, allowing 10 s per request
|
|
411
|
+
(`HARMONY_RSI_DRAIN_TIMEOUT_MS`), and tries once more when the agent exits. A queue file stays on disk until its
|
|
412
|
+
events are sent, so closing the agent mid-send never loses them; the backend drops duplicates.
|
|
406
413
|
- Problems are logged to `~/.harmony/logs/harmony-mcp.log` (set `HARMONY_HOOK_DEBUG=true` for one line per event).
|
|
407
414
|
`HARMONY_RSI_DISABLED=true` turns the hook off.
|
|
408
415
|
|
|
@@ -426,7 +433,7 @@ To follow `/clear` and compaction in Claude Code, add this `SessionStart` hook t
|
|
|
426
433
|
{
|
|
427
434
|
"hooks": {
|
|
428
435
|
"SessionStart": [
|
|
429
|
-
{ "hooks": [{ "type": "command", "command": "npx -y @codeconductorai/harmony-mcp@1.0.
|
|
436
|
+
{ "hooks": [{ "type": "command", "command": "npx -y @codeconductorai/harmony-mcp@1.0.35 --session-hook" }] }
|
|
430
437
|
]
|
|
431
438
|
}
|
|
432
439
|
}
|
|
@@ -439,7 +446,7 @@ they run):
|
|
|
439
446
|
{
|
|
440
447
|
"hooks": {
|
|
441
448
|
"SessionStart": [
|
|
442
|
-
{ "hooks": [{ "type": "command", "command": "npx -y @codeconductorai/harmony-mcp@1.0.
|
|
449
|
+
{ "hooks": [{ "type": "command", "command": "npx -y @codeconductorai/harmony-mcp@1.0.35 --session-hook" }] }
|
|
443
450
|
]
|
|
444
451
|
}
|
|
445
452
|
}
|
package/package.json
CHANGED
package/src/auth/deviceAuth.js
CHANGED
|
@@ -108,6 +108,14 @@ export async function initiateDeviceLogin() {
|
|
|
108
108
|
};
|
|
109
109
|
}
|
|
110
110
|
|
|
111
|
+
export function isTransientStatus(status) {
|
|
112
|
+
return status === 429 || (status >= 500 && status <= 599);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export function isTransientMessage(message) {
|
|
116
|
+
return typeof message === "string" && /<html|\b(429|50[0-4])\b|service unavailable|bad gateway|gateway time-?out|no server is available/i.test(message);
|
|
117
|
+
}
|
|
118
|
+
|
|
111
119
|
export async function pollDeviceLogin(timeoutSeconds = 300) {
|
|
112
120
|
if (!pendingDeviceCode) {
|
|
113
121
|
throw new Error("No pending login session. Call login first.");
|
|
@@ -121,18 +129,35 @@ export async function pollDeviceLogin(timeoutSeconds = 300) {
|
|
|
121
129
|
await sleep(intervalMs);
|
|
122
130
|
|
|
123
131
|
log(`[deviceAuth] pollDeviceLogin URL: ${API_URL}/api/apps/public/auth/confirm-login`);
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
132
|
+
let res;
|
|
133
|
+
try {
|
|
134
|
+
res = await fetch(`${API_URL}/api/apps/public/auth/confirm-login`, {
|
|
135
|
+
method: "POST",
|
|
136
|
+
headers: { "Content-Type": "application/json" },
|
|
137
|
+
body: JSON.stringify({ deviceCode, device_code: deviceCode }),
|
|
138
|
+
});
|
|
139
|
+
} catch (error) {
|
|
140
|
+
// Network blip: the device code is still valid, keep polling until the deadline.
|
|
141
|
+
log(`[deviceAuth] confirm-login unreachable, retrying: ${error.message}`);
|
|
142
|
+
continue;
|
|
143
|
+
}
|
|
129
144
|
|
|
130
145
|
if (!res.ok) {
|
|
131
146
|
const body = await res.text();
|
|
147
|
+
if (isTransientStatus(res.status)) {
|
|
148
|
+
log(`[deviceAuth] confirm-login HTTP ${res.status}, retrying`);
|
|
149
|
+
continue;
|
|
150
|
+
}
|
|
132
151
|
throw new Error(`confirm-login request failed (${res.status}): ${body}`);
|
|
133
152
|
}
|
|
134
153
|
|
|
135
|
-
|
|
154
|
+
let data;
|
|
155
|
+
try {
|
|
156
|
+
data = await res.json();
|
|
157
|
+
} catch {
|
|
158
|
+
log("[deviceAuth] confirm-login returned a non-JSON body, retrying");
|
|
159
|
+
continue;
|
|
160
|
+
}
|
|
136
161
|
const accessToken = field(data, "accessToken", "access_token");
|
|
137
162
|
const idToken = field(data, "idToken", "id_token");
|
|
138
163
|
const expiresIn = field(data, "expiresIn", "expires_in");
|
|
@@ -175,6 +200,12 @@ export async function pollDeviceLogin(timeoutSeconds = 300) {
|
|
|
175
200
|
throw new Error("Login session expired. Call login again to start a new one.");
|
|
176
201
|
}
|
|
177
202
|
|
|
203
|
+
// The backend relays upstream failures (a load balancer's 503 page, say) as a failed status; those pass.
|
|
204
|
+
if (isTransientMessage(data.message)) {
|
|
205
|
+
log("[deviceAuth] confirm-login reported a temporary upstream error, retrying");
|
|
206
|
+
continue;
|
|
207
|
+
}
|
|
208
|
+
|
|
178
209
|
throw new Error(`Login failed: ${data.message || "unknown error"}`);
|
|
179
210
|
}
|
|
180
211
|
|
|
@@ -10,7 +10,7 @@ import { createRequire } from "module";
|
|
|
10
10
|
import { harmonyPath, readJsonFile } from "../rsi/localState.js";
|
|
11
11
|
import { resolveWorkspaceForDir } from "../rsi/workspaceRegistry.js";
|
|
12
12
|
import { statePath } from "../rsi/causalState.js";
|
|
13
|
-
import { readTelemetryKey, telemetryKeyId, writeTelemetryKey } from "../rsi/hooks/hmacSigner.js";
|
|
13
|
+
import { readTelemetryKey, telemetryKeyEndpoint, telemetryKeyId, telemetryKeyMatches, writeTelemetryKey } from "../rsi/hooks/hmacSigner.js";
|
|
14
14
|
import { listSpoolFiles } from "../rsi/hooks/offlineSpooler.js";
|
|
15
15
|
|
|
16
16
|
const packageJson = createRequire(import.meta.url)("../../package.json");
|
|
@@ -219,7 +219,7 @@ async function checkRsi(r, ws, client, { online, rotateKey }) {
|
|
|
219
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
220
|
const hex = res.json?.telemetryKeyHex;
|
|
221
221
|
if (res.ok && typeof hex === "string" && /^[0-9a-f]{64}$/.test(hex)) {
|
|
222
|
-
writeTelemetryKey(hex);
|
|
222
|
+
writeTelemetryKey(hex, ws.endpoint);
|
|
223
223
|
r.add("ok", "telemetry key", `rotated → ${telemetryKeyId(Buffer.from(hex, "hex"))} (the old key keeps verifying for 24 h)`);
|
|
224
224
|
} else {
|
|
225
225
|
r.add("fail", "telemetry key", `rotation failed: ${res.status === null ? res.error : `HTTP ${res.status}`}${res.status === 404 ? " (backend does not issue keys)" : ""}`);
|
|
@@ -227,8 +227,11 @@ async function checkRsi(r, ws, client, { online, rotateKey }) {
|
|
|
227
227
|
return;
|
|
228
228
|
}
|
|
229
229
|
const key = readTelemetryKey();
|
|
230
|
-
|
|
231
|
-
|
|
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)`);
|
|
232
235
|
}
|
|
233
236
|
|
|
234
237
|
async function checkHooks(r, ws) {
|
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
// command arguments have no field to go into.
|
|
5
5
|
import crypto from "crypto";
|
|
6
6
|
import fs from "fs";
|
|
7
|
+
import os from "os";
|
|
7
8
|
import path from "path";
|
|
8
9
|
|
|
9
10
|
import { looksSecret } from "./secretScrubber.js";
|
|
@@ -24,6 +25,8 @@ export function newClientEventId() {
|
|
|
24
25
|
// looks secret. Only the repo-relative part is judged: the absolute prefix never leaves the machine.
|
|
25
26
|
export function toRepoRelative(realRoot, cwd, rawPath) {
|
|
26
27
|
if (typeof rawPath !== "string" || !rawPath || rawPath.includes("\u0000")) return null;
|
|
28
|
+
if (/^\$|\$[{(]|`/.test(rawPath)) return null;
|
|
29
|
+
if (rawPath === "~" || rawPath.startsWith("~/")) rawPath = path.join(os.homedir(), rawPath.slice(1));
|
|
27
30
|
const abs = path.resolve(cwd || realRoot, rawPath);
|
|
28
31
|
let resolved = abs;
|
|
29
32
|
try {
|
|
@@ -1,5 +1,8 @@
|
|
|
1
1
|
// Telemetry key + X-Harmony-Hook-Signature (RSI wire contract §3.2, §4).
|
|
2
2
|
// The key is 32 bytes kept as 64 lowercase hex in ~/.harmony/telemetry.key (0600). It is never logged.
|
|
3
|
+
// Keys are issued per backend, so ~/.harmony/telemetry.key.endpoint records which backend issued it: a key from
|
|
4
|
+
// another backend (say, local dev after testing against prod) is never trusted by the MCP server, which fetches a
|
|
5
|
+
// fresh one. A key file without that record (written by 1.0.34 or earlier) is treated as "issuer unknown".
|
|
3
6
|
import crypto from "crypto";
|
|
4
7
|
import fs from "fs";
|
|
5
8
|
|
|
@@ -11,8 +14,33 @@ export function telemetryKeyPath() {
|
|
|
11
14
|
return harmonyPath("telemetry.key");
|
|
12
15
|
}
|
|
13
16
|
|
|
14
|
-
|
|
15
|
-
|
|
17
|
+
function endpointPath() {
|
|
18
|
+
return harmonyPath("telemetry.key.endpoint");
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function normEndpoint(endpoint) {
|
|
22
|
+
return String(endpoint || "").trim().replace(/\/+$/, "").toLowerCase();
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
// The backend that issued the stored key, or null when unknown (no key, or a key written before 1.0.35).
|
|
26
|
+
export function telemetryKeyEndpoint() {
|
|
27
|
+
try {
|
|
28
|
+
return normEndpoint(fs.readFileSync(endpointPath(), "utf8")) || null;
|
|
29
|
+
} catch {
|
|
30
|
+
return null;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// Whether the stored key was issued by this backend: true, false (another backend), or null (issuer unknown).
|
|
35
|
+
export function telemetryKeyMatches(endpoint) {
|
|
36
|
+
const issuer = telemetryKeyEndpoint();
|
|
37
|
+
return issuer === null ? null : issuer === normEndpoint(endpoint);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// The key bytes, or null when there is no valid key file — or, with `endpoint`, when the key is known to come from
|
|
41
|
+
// another backend (it would only earn 401s there).
|
|
42
|
+
export function readTelemetryKey(endpoint = null) {
|
|
43
|
+
if (endpoint && telemetryKeyMatches(endpoint) === false) return null;
|
|
16
44
|
try {
|
|
17
45
|
const hex = fs.readFileSync(telemetryKeyPath(), "utf8").trim().toLowerCase();
|
|
18
46
|
return KEY_HEX.test(hex) ? Buffer.from(hex, "hex") : null;
|
|
@@ -21,10 +49,12 @@ export function readTelemetryKey() {
|
|
|
21
49
|
}
|
|
22
50
|
}
|
|
23
51
|
|
|
24
|
-
export function writeTelemetryKey(hex) {
|
|
52
|
+
export function writeTelemetryKey(hex, endpoint = null) {
|
|
25
53
|
const clean = String(hex || "").trim().toLowerCase();
|
|
26
54
|
if (!KEY_HEX.test(clean)) throw new Error("telemetry key must be 64 lowercase hex chars");
|
|
27
55
|
atomicWriteFile(telemetryKeyPath(), `${clean}\n`, 0o600);
|
|
56
|
+
if (endpoint) atomicWriteFile(endpointPath(), `${normEndpoint(endpoint)}\n`, 0o600);
|
|
57
|
+
else fs.rmSync(endpointPath(), { force: true });
|
|
28
58
|
}
|
|
29
59
|
|
|
30
60
|
export function telemetryKeyId(keyBytes) {
|
|
@@ -125,7 +125,7 @@ export async function processHookPayload({ agent, event, raw, now = Date.now(),
|
|
|
125
125
|
const events = (await Promise.all(normalized.actions.map((a) => buildWireEvent(a, ctx)))).filter(Boolean);
|
|
126
126
|
if (!events.length) return { status: "no-events" };
|
|
127
127
|
|
|
128
|
-
const key = readTelemetryKey();
|
|
128
|
+
const key = readTelemetryKey(ws.endpoint);
|
|
129
129
|
const token = cachedUserToken();
|
|
130
130
|
if (!key || !token) {
|
|
131
131
|
spoolEvents(ws.endpoint, ws.workspaceId, events);
|
|
@@ -3,6 +3,9 @@
|
|
|
3
3
|
// Each line is { endpoint, workspaceId, event } — unsigned; batches are signed when sent (wire contract §3.2.6).
|
|
4
4
|
// Appends are single small O_APPEND writes, safe across concurrent hook processes. Over 2 MiB the oldest 25% of
|
|
5
5
|
// lines are dropped. A drain claims the file by renaming it, so appends that race the drain land in a fresh file.
|
|
6
|
+
// The claimed file stays on disk until the drain has sent or requeued its events: if the process is killed mid-drain
|
|
7
|
+
// (an agent closing its MCP server), the next drain picks the orphaned file up again. The backend deduplicates
|
|
8
|
+
// events by clientEventId, so a batch sent just before the kill is never counted twice.
|
|
6
9
|
import fs from "fs";
|
|
7
10
|
import path from "path";
|
|
8
11
|
|
|
@@ -46,9 +49,35 @@ export function spoolEvents(endpoint, workspaceId, events) {
|
|
|
46
49
|
if (fs.statSync(file).size > SPOOL_MAX_BYTES) trimOldest(file);
|
|
47
50
|
}
|
|
48
51
|
|
|
52
|
+
const SPOOL_NAME = /^ws-[A-Za-z0-9_-]+-events\.jsonl$/;
|
|
53
|
+
const CLAIMED_NAME = /^ws-[A-Za-z0-9_-]+-events\.jsonl\.draining-(\d+)-(\d+)$/;
|
|
54
|
+
// A claim older than this is taken over even if its pid is alive again (pid reuse).
|
|
55
|
+
const STALE_CLAIM_MS = 10 * 60_000;
|
|
56
|
+
|
|
57
|
+
function pidAlive(pid) {
|
|
58
|
+
try {
|
|
59
|
+
process.kill(pid, 0);
|
|
60
|
+
return true;
|
|
61
|
+
} catch (error) {
|
|
62
|
+
return error?.code === "EPERM";
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// A claimed file whose drain is gone: its process exited, or the claim is too old to still be in progress.
|
|
67
|
+
function isOrphanedClaim(name, now = Date.now()) {
|
|
68
|
+
const m = CLAIMED_NAME.exec(name);
|
|
69
|
+
if (!m) return false;
|
|
70
|
+
const pid = Number(m[1]);
|
|
71
|
+
return pid !== process.pid && (!pidAlive(pid) || now - Number(m[2]) > STALE_CLAIM_MS);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// Spool files to send: live spools plus claims orphaned by a drain that never finished.
|
|
49
75
|
export function listSpoolFiles() {
|
|
50
76
|
try {
|
|
51
|
-
return fs
|
|
77
|
+
return fs
|
|
78
|
+
.readdirSync(spoolDir())
|
|
79
|
+
.filter((n) => SPOOL_NAME.test(n) || isOrphanedClaim(n))
|
|
80
|
+
.map((n) => path.join(spoolDir(), n));
|
|
52
81
|
} catch {
|
|
53
82
|
return [];
|
|
54
83
|
}
|
|
@@ -66,16 +95,19 @@ export function spoolBacklog() {
|
|
|
66
95
|
return count;
|
|
67
96
|
}
|
|
68
97
|
|
|
69
|
-
// Takes all lines out of a spool file. Returns
|
|
98
|
+
// Takes all lines out of a spool file by renaming it to a claim. Returns { records, claimed }; records is [] if
|
|
99
|
+
// another process claimed it first. The caller must call releaseClaim(claimed) once every record is sent or requeued.
|
|
70
100
|
export function claimSpool(file) {
|
|
71
|
-
const
|
|
101
|
+
const base = file.replace(/\.draining-\d+-\d+$/, "");
|
|
102
|
+
const claimed = `${base}.draining-${process.pid}-${Date.now()}`;
|
|
72
103
|
try {
|
|
73
104
|
fs.renameSync(file, claimed);
|
|
74
105
|
} catch {
|
|
75
|
-
return [];
|
|
106
|
+
return { records: [], claimed: null };
|
|
76
107
|
}
|
|
108
|
+
let records = [];
|
|
77
109
|
try {
|
|
78
|
-
|
|
110
|
+
records = fs
|
|
79
111
|
.readFileSync(claimed, "utf8")
|
|
80
112
|
.split("\n")
|
|
81
113
|
.filter(Boolean)
|
|
@@ -87,9 +119,15 @@ export function claimSpool(file) {
|
|
|
87
119
|
}
|
|
88
120
|
})
|
|
89
121
|
.filter((rec) => rec?.event && rec.endpoint && rec.workspaceId);
|
|
90
|
-
}
|
|
91
|
-
|
|
122
|
+
} catch {
|
|
123
|
+
// unreadable right now: keep the claim on disk, a later drain picks it up as orphaned
|
|
124
|
+
return { records: [], claimed: null };
|
|
92
125
|
}
|
|
126
|
+
return { records, claimed };
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
export function releaseClaim(claimed) {
|
|
130
|
+
if (claimed) fs.rmSync(claimed, { force: true });
|
|
93
131
|
}
|
|
94
132
|
|
|
95
133
|
// Puts records that were not sent back into their spool.
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Sends spooled tool events (RSI MCP spec §5.5, wire contract §3.5). Used by hook-event (one batch after a
|
|
2
2
|
// successful send) and by `serve` (on startup and on stdin EOF, with a deadline).
|
|
3
|
-
import { DRAIN_BATCH_SIZE, claimSpool, listSpoolFiles, requeue } from "./offlineSpooler.js";
|
|
3
|
+
import { DRAIN_BATCH_SIZE, claimSpool, listSpoolFiles, releaseClaim, requeue } from "./offlineSpooler.js";
|
|
4
4
|
import { batchBodies, postToolEvents } from "./toolEventsClient.js";
|
|
5
5
|
|
|
6
6
|
// opts:
|
|
@@ -19,8 +19,11 @@ export async function drainSpool({ endpoint, getToken, getKey, maxBatches = 10,
|
|
|
19
19
|
if (!key) return result;
|
|
20
20
|
for (const file of listSpoolFiles()) {
|
|
21
21
|
if (batches >= maxBatches || Date.now() >= deadlineAt) break;
|
|
22
|
-
const records = claimSpool(file);
|
|
23
|
-
if (!records.length)
|
|
22
|
+
const { records, claimed } = claimSpool(file);
|
|
23
|
+
if (!records.length) {
|
|
24
|
+
releaseClaim(claimed);
|
|
25
|
+
continue;
|
|
26
|
+
}
|
|
24
27
|
const mine = records.filter((r) => r.endpoint === endpoint);
|
|
25
28
|
const leftover = records.filter((r) => r.endpoint !== endpoint);
|
|
26
29
|
const byWs = new Map();
|
|
@@ -68,6 +71,8 @@ export async function drainSpool({ endpoint, getToken, getKey, maxBatches = 10,
|
|
|
68
71
|
requeue(leftover);
|
|
69
72
|
result.requeued += leftover.length;
|
|
70
73
|
}
|
|
74
|
+
// Only now: a process killed before this line leaves the claim for the next drain instead of losing it.
|
|
75
|
+
releaseClaim(claimed);
|
|
71
76
|
}
|
|
72
77
|
return result;
|
|
73
78
|
}
|
|
@@ -2,16 +2,19 @@
|
|
|
2
2
|
// - binds this repo to this backend in ~/.harmony/workspaces.json so hooks know where (and whether) to send
|
|
3
3
|
// - drains the hook spool with the server's refreshable credentials: on connect, every few minutes, and in the
|
|
4
4
|
// ≤180 ms window after the host closes stdin (RSI MCP spec §4.5, §5.5)
|
|
5
|
-
// - fetches the telemetry key when
|
|
5
|
+
// - fetches the telemetry key on connect when there is none from this backend, and after a 401
|
|
6
|
+
// Sends use a generous per-request timeout: a cold TLS connection to a remote backend alone can take over a second,
|
|
7
|
+
// and this runs in the background, never in the agent's path.
|
|
6
8
|
import { log } from "../observability/log.js";
|
|
7
9
|
import { readMarker } from "../workspace/workspaceMarker.js";
|
|
8
10
|
import { API_URL, fetchTelemetryKeyHex, resolveUserToken } from "../backend/harmonyClient.js";
|
|
9
11
|
import { registerWorkspaceRoot } from "./workspaceRegistry.js";
|
|
10
|
-
import { readTelemetryKey, writeTelemetryKey } from "./hooks/hmacSigner.js";
|
|
12
|
+
import { readTelemetryKey, telemetryKeyMatches, writeTelemetryKey } from "./hooks/hmacSigner.js";
|
|
11
13
|
import { drainSpool } from "./hooks/spoolDrainer.js";
|
|
12
14
|
import { spoolBacklog } from "./hooks/offlineSpooler.js";
|
|
13
15
|
|
|
14
|
-
const DRAIN_INTERVAL_MS = Number(process.env.HARMONY_RSI_DRAIN_MS) ||
|
|
16
|
+
const DRAIN_INTERVAL_MS = Number(process.env.HARMONY_RSI_DRAIN_MS) || 60_000;
|
|
17
|
+
const DRAIN_REQUEST_TIMEOUT_MS = Number(process.env.HARMONY_RSI_DRAIN_TIMEOUT_MS) || 10_000;
|
|
15
18
|
export const EOF_DRAIN_DEADLINE_MS = 180;
|
|
16
19
|
|
|
17
20
|
let draining = null;
|
|
@@ -35,17 +38,30 @@ export function registerLocalWorkspace() {
|
|
|
35
38
|
}
|
|
36
39
|
|
|
37
40
|
async function keyFor({ refresh }) {
|
|
38
|
-
|
|
39
|
-
|
|
41
|
+
// Only a key this backend issued is good enough; an unknown-issuer key (written by 1.0.34 or earlier) is replaced
|
|
42
|
+
// when a fresh one can be fetched and used as a last resort otherwise.
|
|
43
|
+
const existing = readTelemetryKey(API_URL);
|
|
44
|
+
if (existing && !refresh && telemetryKeyMatches(API_URL) === true) return existing;
|
|
40
45
|
const workspaceId = readMarker()?.workspaceId;
|
|
41
46
|
if (!workspaceId) return refresh ? null : existing;
|
|
42
47
|
const hex = await fetchTelemetryKeyHex(workspaceId);
|
|
43
48
|
if (!hex) return refresh ? null : existing;
|
|
44
|
-
writeTelemetryKey(hex);
|
|
45
|
-
return readTelemetryKey();
|
|
49
|
+
writeTelemetryKey(hex, API_URL);
|
|
50
|
+
return readTelemetryKey(API_URL);
|
|
46
51
|
}
|
|
47
52
|
|
|
48
|
-
|
|
53
|
+
// On connect: make sure hooks have a key from this backend, so they can send directly instead of spooling.
|
|
54
|
+
export async function ensureTelemetryKey() {
|
|
55
|
+
if (disabled()) return null;
|
|
56
|
+
try {
|
|
57
|
+
return await keyFor({ refresh: false });
|
|
58
|
+
} catch (error) {
|
|
59
|
+
log(`[rsi] telemetry key check failed: ${error.message}`);
|
|
60
|
+
return null;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export function drainHookSpool({ deadlineMs = 30_000, maxBatches = 10 } = {}) {
|
|
49
65
|
if (disabled()) return Promise.resolve(null);
|
|
50
66
|
if (draining) return draining;
|
|
51
67
|
if (!spoolBacklog()) return Promise.resolve(null);
|
|
@@ -56,7 +72,7 @@ export function drainHookSpool({ deadlineMs = 5_000, maxBatches = 10 } = {}) {
|
|
|
56
72
|
getKey: keyFor,
|
|
57
73
|
maxBatches,
|
|
58
74
|
deadlineAt: Date.now() + deadlineMs,
|
|
59
|
-
timeoutMs: Math.min(
|
|
75
|
+
timeoutMs: Math.min(DRAIN_REQUEST_TIMEOUT_MS, deadlineMs),
|
|
60
76
|
log,
|
|
61
77
|
})
|
|
62
78
|
.then((result) => {
|
package/src/server/server.js
CHANGED
|
@@ -54,7 +54,7 @@ import { buildCallContext, rememberHandshakeClient, runWithCallContext } from ".
|
|
|
54
54
|
import { readRegistry } from "../rsi/workspaceRegistry.js";
|
|
55
55
|
import { applyToolHints } from "../rsi/bundleHints.js";
|
|
56
56
|
import { awaitInitialRefresh, bootBundleFromCache, cachedBundleDocs, refreshBundleInBackground } from "../rsi/bundleRefresher.js";
|
|
57
|
-
import { drainHookSpool, registerLocalWorkspace, startPeriodicDrain } from "../rsi/serveTelemetry.js";
|
|
57
|
+
import { drainHookSpool, ensureTelemetryKey, registerLocalWorkspace, startPeriodicDrain } from "../rsi/serveTelemetry.js";
|
|
58
58
|
|
|
59
59
|
function textContent(text, isError = false) {
|
|
60
60
|
const result = { content: [{ type: "text", text }] };
|
|
@@ -508,7 +508,7 @@ export function buildMcpServer() {
|
|
|
508
508
|
// send; this process drains that spool with its refreshable credentials.
|
|
509
509
|
registerLocalWorkspace();
|
|
510
510
|
server.oninitialized = () => {
|
|
511
|
-
refreshBundleInBackground().then(() => drainHookSpool());
|
|
511
|
+
refreshBundleInBackground().then(() => ensureTelemetryKey()).then(() => drainHookSpool());
|
|
512
512
|
startPeriodicDrain();
|
|
513
513
|
};
|
|
514
514
|
|
|
@@ -609,7 +609,7 @@ export function buildMcpServer() {
|
|
|
609
609
|
// A new workspace or a fresh login can change which bundle the backend pins (or allow pinning at all).
|
|
610
610
|
if ((name === "setup_workspace" || name === "confirm_login") && result && !result.isError) {
|
|
611
611
|
if (name === "setup_workspace") registerLocalWorkspace();
|
|
612
|
-
refreshBundleInBackground().then(() => drainHookSpool());
|
|
612
|
+
refreshBundleInBackground().then(() => ensureTelemetryKey()).then(() => drainHookSpool());
|
|
613
613
|
}
|
|
614
614
|
}
|
|
615
615
|
}));
|