@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,95 @@
|
|
|
1
|
+
// When to load and refresh the RSI bundle's tool hints for the local workspace (RSI MCP spec §4.4).
|
|
2
|
+
// - boot: from the on-disk cache, synchronously
|
|
3
|
+
// - once after the host finishes `initialize`; the first tools/list waits briefly for it (awaitInitialRefresh)
|
|
4
|
+
// - right after setup_workspace / confirm_login (the workspace or login may be new to this process)
|
|
5
|
+
//
|
|
6
|
+
// The tool list the host sees is frozen for the session: no tools/list_changed, no periodic refresh. Tool
|
|
7
|
+
// definitions sit at the top of the agent's prompt, so changing them mid-session makes the host rewrite its whole
|
|
8
|
+
// prompt cache (the dominant cost in the RSI A/B). It is also pointless: the backend pins a session to one bundle
|
|
9
|
+
// for its lifetime. A newer bundle reaches the next session through the on-disk cache.
|
|
10
|
+
// HARMONY_RSI_DISABLED=true turns all of it off; tools/list then shows the built-in descriptions only.
|
|
11
|
+
import { log } from "../observability/log.js";
|
|
12
|
+
import { readMarker } from "../workspace/workspaceMarker.js";
|
|
13
|
+
import { API_URL, callRsiPin, fetchRsiBundle } from "../backend/harmonyClient.js";
|
|
14
|
+
import { bundleCachePath, loadCachedBundle, refreshBundle, requestedBundleId } from "./bundleHints.js";
|
|
15
|
+
import { readJsonFile } from "./localState.js";
|
|
16
|
+
import { syncWorkspaceFiles } from "../sync/workspaceSync.js";
|
|
17
|
+
|
|
18
|
+
// How long the first tools/list may wait for the startup pin, so the session starts with the right hints.
|
|
19
|
+
const FIRST_LIST_WAIT_MS = Number(process.env.HARMONY_RSI_FIRST_LIST_WAIT_MS) || 1_000;
|
|
20
|
+
|
|
21
|
+
let inflight = null;
|
|
22
|
+
|
|
23
|
+
function disabled() {
|
|
24
|
+
return process.env.HARMONY_RSI_DISABLED === "true";
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
// Resolves once the startup refresh (if any) has finished, or after FIRST_LIST_WAIT_MS — whichever is first.
|
|
28
|
+
export function awaitInitialRefresh(timeoutMs = FIRST_LIST_WAIT_MS) {
|
|
29
|
+
if (!inflight) return Promise.resolve();
|
|
30
|
+
return Promise.race([inflight, new Promise((resolve) => setTimeout(resolve, timeoutMs).unref())]);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function bootBundleFromCache() {
|
|
34
|
+
if (disabled()) return false;
|
|
35
|
+
const workspaceId = readMarker()?.workspaceId;
|
|
36
|
+
const loaded = loadCachedBundle(workspaceId, API_URL);
|
|
37
|
+
if (loaded) log(`[rsi] tool hints loaded from cache for workspace ${workspaceId}`);
|
|
38
|
+
return loaded;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// The cached bundle's managed documents for a workspace ({ bundleId, managedAgentInstructionsMd, workspaceWorldModelMd }),
|
|
42
|
+
// or null.
|
|
43
|
+
export function cachedBundleDocs(workspaceId) {
|
|
44
|
+
if (!workspaceId) return null;
|
|
45
|
+
const cached = readJsonFile(bundleCachePath(workspaceId));
|
|
46
|
+
return cached?.apiUrl === API_URL && String(cached.workspaceId) === String(workspaceId) && cached.bundleId ? cached : null;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// Server startup counterpart of `sync-workspace` (spec §7.2): refreshes blocks the user already has, never adds one.
|
|
50
|
+
// HARMONY_SYNC_WORKSPACE=false turns it off.
|
|
51
|
+
function syncExistingManagedBlocks(workspaceId) {
|
|
52
|
+
if (process.env.HARMONY_SYNC_WORKSPACE === "false") return;
|
|
53
|
+
const docs = cachedBundleDocs(workspaceId);
|
|
54
|
+
if (!docs) return;
|
|
55
|
+
try {
|
|
56
|
+
const results = syncWorkspaceFiles({
|
|
57
|
+
root: process.cwd(),
|
|
58
|
+
bundleId: docs.bundleId,
|
|
59
|
+
instructionsMd: docs.managedAgentInstructionsMd,
|
|
60
|
+
worldModelMd: docs.workspaceWorldModelMd,
|
|
61
|
+
mode: "update",
|
|
62
|
+
warn: (m) => log(`[rsi] sync-workspace: ${m}`),
|
|
63
|
+
});
|
|
64
|
+
for (const r of results) {
|
|
65
|
+
if (!["unchanged", "absent"].includes(r.status)) log(`[rsi] sync-workspace: ${r.status} ${r.file}`);
|
|
66
|
+
}
|
|
67
|
+
} catch (error) {
|
|
68
|
+
log(`[rsi] sync-workspace failed: ${error.message}`);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// Fire-and-forget; resolves when done (tests await it). Never rejects.
|
|
73
|
+
export function refreshBundleInBackground() {
|
|
74
|
+
if (disabled()) return Promise.resolve();
|
|
75
|
+
if (inflight) return inflight;
|
|
76
|
+
const marker = readMarker();
|
|
77
|
+
const workspaceId = marker?.workspaceId;
|
|
78
|
+
if (!workspaceId) return Promise.resolve();
|
|
79
|
+
inflight = refreshBundle({
|
|
80
|
+
workspaceId,
|
|
81
|
+
apiUrl: API_URL,
|
|
82
|
+
requested: requestedBundleId(marker),
|
|
83
|
+
pin: callRsiPin,
|
|
84
|
+
fetchBundle: (bundleId) => fetchRsiBundle(workspaceId, bundleId),
|
|
85
|
+
})
|
|
86
|
+
.then(({ bundleId, changed }) => {
|
|
87
|
+
if (bundleId) log(`[rsi] workspace ${workspaceId} pinned to bundle ${bundleId}${changed ? " (tool hints updated)" : ""}`);
|
|
88
|
+
if (bundleId) syncExistingManagedBlocks(workspaceId);
|
|
89
|
+
})
|
|
90
|
+
.catch((error) => log(`[rsi] bundle refresh failed: ${error.message}`))
|
|
91
|
+
.finally(() => {
|
|
92
|
+
inflight = null;
|
|
93
|
+
});
|
|
94
|
+
return inflight;
|
|
95
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
// Per-tool-call context, carried through async calls so the HTTP layer can add the agent and trace headers of the
|
|
2
|
+
// call it is serving without threading them through every function signature.
|
|
3
|
+
import { AsyncLocalStorage } from "async_hooks";
|
|
4
|
+
|
|
5
|
+
import { CLIENT_INFO_META_KEY, resolveClientAgent } from "./clientAgent.js";
|
|
6
|
+
|
|
7
|
+
const storage = new AsyncLocalStorage();
|
|
8
|
+
|
|
9
|
+
// clientInfo from `initialize`, kept for requests that carry no per-request client metadata.
|
|
10
|
+
let handshakeClientInfo = null;
|
|
11
|
+
|
|
12
|
+
export function rememberHandshakeClient(clientInfo) {
|
|
13
|
+
handshakeClientInfo = clientInfo || null;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export function handshakeClient() {
|
|
17
|
+
return handshakeClientInfo;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
const W3C_FIELDS = ["traceparent", "tracestate", "baggage"];
|
|
21
|
+
|
|
22
|
+
// The W3C trace fields an OTel-instrumented agent put in params._meta, verbatim (spec §4.2). Values must be
|
|
23
|
+
// header-safe strings; anything else is dropped rather than forwarded.
|
|
24
|
+
export function traceFieldsFromMeta(meta) {
|
|
25
|
+
const out = {};
|
|
26
|
+
for (const field of W3C_FIELDS) {
|
|
27
|
+
const value = meta?.[field];
|
|
28
|
+
if (typeof value === "string" && value.length <= 8192 && !/[\r\n]/.test(value)) out[field] = value;
|
|
29
|
+
}
|
|
30
|
+
return out;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function buildCallContext(meta) {
|
|
34
|
+
return {
|
|
35
|
+
clientAgent: resolveClientAgent({ meta, clientInfo: handshakeClientInfo }),
|
|
36
|
+
clientName: meta?.[CLIENT_INFO_META_KEY]?.name || handshakeClientInfo?.name || null,
|
|
37
|
+
trace: traceFieldsFromMeta(meta),
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function runWithCallContext(ctx, fn) {
|
|
42
|
+
return storage.run(ctx, fn);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// The active call's context; outside a tool call (file watcher, background refresh) it is derived from the
|
|
46
|
+
// handshake alone.
|
|
47
|
+
export function currentCallContext() {
|
|
48
|
+
return storage.getStore() || buildCallContext(undefined);
|
|
49
|
+
}
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
// Causal state bridge (RSI MCP spec §4.3, wire contract §1.2).
|
|
2
|
+
//
|
|
3
|
+
// Hook processes (`harmony-mcp hook-event`) share no memory with this server. After each successful Harmony query
|
|
4
|
+
// the server records which request it was in ~/.harmony/run/<cwd-hash>.state; the next local rg/Read/Edit hook in
|
|
5
|
+
// the same repo reads it and attaches that request as its parent, so the backend can tell which Harmony answer the
|
|
6
|
+
// agent went around.
|
|
7
|
+
import crypto from "crypto";
|
|
8
|
+
import fs from "fs";
|
|
9
|
+
|
|
10
|
+
import { atomicWriteFile, harmonyPath, readJsonFile } from "./localState.js";
|
|
11
|
+
|
|
12
|
+
export const STATE_SCHEMA_VERSION = 1;
|
|
13
|
+
export const STATE_MAX_AGE_MS = 900_000; // 15 minutes
|
|
14
|
+
|
|
15
|
+
// Only answers from these endpoints become a parent for later hook events (wire contract §1.2).
|
|
16
|
+
export const CAUSAL_ENDPOINTS = new Set(["investigate", "context-search", "traces/inspect", "preflight", "security/audit"]);
|
|
17
|
+
|
|
18
|
+
function realpathOrSelf(dir) {
|
|
19
|
+
try {
|
|
20
|
+
return fs.realpathSync(dir);
|
|
21
|
+
} catch {
|
|
22
|
+
return dir;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function cwdKey(workspaceRoot = process.cwd()) {
|
|
27
|
+
return crypto.createHash("sha256").update(realpathOrSelf(workspaceRoot)).digest("hex").slice(0, 16);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function statePath(workspaceRoot = process.cwd()) {
|
|
31
|
+
return harmonyPath("run", `${cwdKey(workspaceRoot)}.state`);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const LEDGER_ID = /^rsi_[0-9a-f]{20}$/;
|
|
35
|
+
const TRACE_ID = /^[0-9a-f]{32}$/;
|
|
36
|
+
const BUNDLE_ID = /^[A-Za-z0-9._:-]{1,128}$/;
|
|
37
|
+
|
|
38
|
+
function valid(value, pattern) {
|
|
39
|
+
return typeof value === "string" && pattern.test(value) ? value : null;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// Records the request that produced a 200 from a causal endpoint. Missing or malformed response headers are stored
|
|
43
|
+
// as null: the backend may not emit X-Harmony-Ledger-Id yet, and that is not an error (wire contract §1.2).
|
|
44
|
+
export function recordCausalState({
|
|
45
|
+
endpointPath,
|
|
46
|
+
workspaceId,
|
|
47
|
+
mcpSessionId,
|
|
48
|
+
sessionSource = null,
|
|
49
|
+
clientAgent,
|
|
50
|
+
ledgerId,
|
|
51
|
+
traceId,
|
|
52
|
+
bundleId,
|
|
53
|
+
workspaceRoot = process.cwd(),
|
|
54
|
+
now = Date.now(),
|
|
55
|
+
}) {
|
|
56
|
+
if (!CAUSAL_ENDPOINTS.has(endpointPath)) return false;
|
|
57
|
+
const record = {
|
|
58
|
+
schemaVersion: STATE_SCHEMA_VERSION,
|
|
59
|
+
workspaceId: workspaceId == null ? null : String(workspaceId),
|
|
60
|
+
orgId: null,
|
|
61
|
+
mcpSessionId: mcpSessionId || null,
|
|
62
|
+
sessionSource: sessionSource || null,
|
|
63
|
+
clientAgent: clientAgent || null,
|
|
64
|
+
lastEndpoint: endpointPath,
|
|
65
|
+
lastHarmonyRequestId: valid(ledgerId, LEDGER_ID),
|
|
66
|
+
lastTraceId: valid(traceId?.toLowerCase?.(), TRACE_ID),
|
|
67
|
+
lastBundleId: valid(bundleId, BUNDLE_ID),
|
|
68
|
+
updatedAtEpochMs: now,
|
|
69
|
+
mcpPid: process.pid,
|
|
70
|
+
};
|
|
71
|
+
atomicWriteFile(statePath(workspaceRoot), `${JSON.stringify(record)}\n`);
|
|
72
|
+
return true;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function pidAlive(pid) {
|
|
76
|
+
if (!Number.isInteger(pid) || pid <= 0) return false;
|
|
77
|
+
try {
|
|
78
|
+
process.kill(pid, 0);
|
|
79
|
+
return true;
|
|
80
|
+
} catch (error) {
|
|
81
|
+
return error.code === "EPERM";
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// Whether a hook from `hookSessionId` may treat this state's request as its parent. The state file is per repo, so
|
|
86
|
+
// several agent sessions share it. When the server's session id came from the agent itself (its session hook, its
|
|
87
|
+
// env, or HARMONY_SESSION_ID) it must match the hook's own session (compactions append "#compact-N"). A generated
|
|
88
|
+
// id cannot be matched; then liveness and freshness are all we have.
|
|
89
|
+
export function sameSession(record, hookSessionId) {
|
|
90
|
+
if (!hookSessionId || !record?.mcpSessionId || record.sessionSource === "generated") return true;
|
|
91
|
+
return record.mcpSessionId === hookSessionId || record.mcpSessionId.startsWith(`${hookSessionId}#`);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// Reader for hook-event: the parent anchors, or null when the state is missing, stale (> 15 min), from another agent
|
|
95
|
+
// session, or — when the hook has no session id of its own to match — written by a server process that has exited.
|
|
96
|
+
export function readCausalState({ workspaceRoot = process.cwd(), now = Date.now(), hookSessionId = null } = {}) {
|
|
97
|
+
const record = readJsonFile(statePath(workspaceRoot));
|
|
98
|
+
if (record?.schemaVersion !== STATE_SCHEMA_VERSION || typeof record.updatedAtEpochMs !== "number") return null;
|
|
99
|
+
if (now - record.updatedAtEpochMs > STATE_MAX_AGE_MS || record.updatedAtEpochMs > now + 60_000) return null;
|
|
100
|
+
if (!hookSessionId && !pidAlive(record.mcpPid)) return null;
|
|
101
|
+
if (!sameSession(record, hookSessionId)) return null;
|
|
102
|
+
return record;
|
|
103
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
// Which coding agent is driving this MCP process, as the canonical slug sent in X-Harmony-Client-Agent
|
|
2
|
+
// (RSI MCP spec §4.2, wire contract §1.1). Resolution order:
|
|
3
|
+
// 1. params._meta["io.modelcontextprotocol/client-info"].name on the request (stateless 2026-07-28 hosts)
|
|
4
|
+
// 2. clientInfo.name from `initialize` (2025-11-25 hosts)
|
|
5
|
+
// 3. environment variables the agent sets for its child processes
|
|
6
|
+
// 4. "unknown-mcp"
|
|
7
|
+
|
|
8
|
+
export const UNKNOWN_AGENT = "unknown-mcp";
|
|
9
|
+
|
|
10
|
+
// Only the wire contract's canonical slugs (the backend files anything else under unknown-mcp). First match wins,
|
|
11
|
+
// so kilo comes before opencode (Kilo Code reports names containing both). Roo Code is a Cline fork.
|
|
12
|
+
const NAME_PATTERNS = [
|
|
13
|
+
[/claude[-_ ]?code|^claude$/i, "claude-code"],
|
|
14
|
+
[/codex/i, "codex-cli"],
|
|
15
|
+
[/cursor/i, "cursor"],
|
|
16
|
+
[/antigravity|gemini/i, "antigravity"],
|
|
17
|
+
[/copilot/i, "copilot-cli"],
|
|
18
|
+
[/kilo/i, "kilo-code"],
|
|
19
|
+
[/opencode/i, "opencode"],
|
|
20
|
+
[/cline|roo[-_ ]?(code|cline)/i, "cline"],
|
|
21
|
+
[/aider/i, "aider"],
|
|
22
|
+
];
|
|
23
|
+
|
|
24
|
+
const ENV_HINTS = [
|
|
25
|
+
["CLAUDE_CODE_ENTRYPOINT", "claude-code"],
|
|
26
|
+
["CLAUDECODE", "claude-code"],
|
|
27
|
+
["CODEX_SANDBOX", "codex-cli"],
|
|
28
|
+
["CURSOR_TRACE_ID", "cursor"],
|
|
29
|
+
["ANTIGRAVITY_CLI", "antigravity"],
|
|
30
|
+
["GITHUB_COPILOT_CLI", "copilot-cli"],
|
|
31
|
+
["OPENCODE_VERSION", "opencode"],
|
|
32
|
+
];
|
|
33
|
+
|
|
34
|
+
export const CLIENT_INFO_META_KEY = "io.modelcontextprotocol/client-info";
|
|
35
|
+
|
|
36
|
+
export function slugForClientName(name) {
|
|
37
|
+
if (typeof name !== "string" || !name.trim()) return null;
|
|
38
|
+
for (const [pattern, slug] of NAME_PATTERNS) {
|
|
39
|
+
if (pattern.test(name)) return slug;
|
|
40
|
+
}
|
|
41
|
+
return null;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function slugFromEnv(env = process.env) {
|
|
45
|
+
for (const [key, slug] of ENV_HINTS) {
|
|
46
|
+
if (env[key]) return slug;
|
|
47
|
+
}
|
|
48
|
+
return null;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export function resolveClientAgent({ meta, clientInfo, env = process.env } = {}) {
|
|
52
|
+
return (
|
|
53
|
+
slugForClientName(meta?.[CLIENT_INFO_META_KEY]?.name) ||
|
|
54
|
+
slugForClientName(clientInfo?.name) ||
|
|
55
|
+
slugFromEnv(env) ||
|
|
56
|
+
UNKNOWN_AGENT
|
|
57
|
+
);
|
|
58
|
+
}
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
// Turns a normalized hook action into a wire event (RSI wire contract §3.4). This is the single place that decides
|
|
2
|
+
// what crosses the network, so every field is built from an allow-list: verb, repo-relative paths, line span,
|
|
3
|
+
// a scrubbed search shape, an exit code and a post-edit file hash. Raw tool output, file bodies, patch hunks and
|
|
4
|
+
// command arguments have no field to go into.
|
|
5
|
+
import crypto from "crypto";
|
|
6
|
+
import fs from "fs";
|
|
7
|
+
import path from "path";
|
|
8
|
+
|
|
9
|
+
import { looksSecret } from "./secretScrubber.js";
|
|
10
|
+
import { hashFileInRepo, insideRoot } from "./fileHash.js";
|
|
11
|
+
|
|
12
|
+
export const ESCAPE_TYPES = new Set(["SEARCH", "READ", "EDIT", "BUILD", "COMPACT"]);
|
|
13
|
+
const MAX_PATHS = 50;
|
|
14
|
+
const MAX_PATH_CHARS = 512;
|
|
15
|
+
const MAX_HINT_CHARS = 64;
|
|
16
|
+
const CLEAN_IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$.#:-]{1,96}$/;
|
|
17
|
+
const REGEX_META = /[.*+?[\](){}|^\\$]/;
|
|
18
|
+
|
|
19
|
+
export function newClientEventId() {
|
|
20
|
+
return `cev_${crypto.randomBytes(10).toString("hex")}`;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
// Repo-relative POSIX path, or null when it is outside the repo, contains .. after resolution, or a segment of it
|
|
24
|
+
// looks secret. Only the repo-relative part is judged: the absolute prefix never leaves the machine.
|
|
25
|
+
export function toRepoRelative(realRoot, cwd, rawPath) {
|
|
26
|
+
if (typeof rawPath !== "string" || !rawPath || rawPath.includes("\u0000")) return null;
|
|
27
|
+
const abs = path.resolve(cwd || realRoot, rawPath);
|
|
28
|
+
let resolved = abs;
|
|
29
|
+
try {
|
|
30
|
+
resolved = fs.realpathSync(abs);
|
|
31
|
+
} catch {
|
|
32
|
+
// Not on disk (deleted file, glob): judge the lexical path, resolved against the real root.
|
|
33
|
+
const lexicalRel = path.relative(realRoot, abs);
|
|
34
|
+
if (lexicalRel.startsWith("..") || path.isAbsolute(lexicalRel)) {
|
|
35
|
+
// cwd may itself be a symlinked path to the root
|
|
36
|
+
try {
|
|
37
|
+
resolved = path.join(fs.realpathSync(path.dirname(abs)), path.basename(abs));
|
|
38
|
+
} catch {
|
|
39
|
+
return null;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
if (!insideRoot(realRoot, resolved) && resolved !== realRoot) return null;
|
|
44
|
+
const rel = path.relative(realRoot, resolved).split(path.sep).join("/");
|
|
45
|
+
if (!rel) return ".";
|
|
46
|
+
const segments = rel.split("/");
|
|
47
|
+
// A backslash is never part of a repo path here (it is usually a regex escape that was mistaken for a file), and
|
|
48
|
+
// the backend rejects the whole batch for one.
|
|
49
|
+
if (segments.includes("..") || rel.includes("\\") || rel.length > MAX_PATH_CHARS || segments.some(looksSecret)) return null;
|
|
50
|
+
return rel;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function identifierTokens(text) {
|
|
54
|
+
const tokens = (text.match(/[A-Za-z_][A-Za-z0-9_]{2,}/g) || []).filter((t) => !looksSecret(t));
|
|
55
|
+
let out = "";
|
|
56
|
+
for (const t of tokens) {
|
|
57
|
+
const next = out ? `${out} ${t}` : t;
|
|
58
|
+
if (next.length > MAX_HINT_CHARS) break;
|
|
59
|
+
out = next;
|
|
60
|
+
}
|
|
61
|
+
return out || null;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// Search shape per spec §5.3: never the raw pattern unless it is a clean identifier.
|
|
65
|
+
export function searchShapeFor(pattern, { fixed = false } = {}) {
|
|
66
|
+
if (typeof pattern !== "string" || !pattern) return null;
|
|
67
|
+
const hasMeta = !fixed && REGEX_META.test(pattern);
|
|
68
|
+
const base = { tokenLength: pattern.length, matchesKnownWorkspaceSymbol: null };
|
|
69
|
+
if (looksSecret(pattern)) {
|
|
70
|
+
return { ...base, isExactSymbol: false, isRegex: hasMeta, sanitizedSymbolHint: "<REDACTED>" };
|
|
71
|
+
}
|
|
72
|
+
if (CLEAN_IDENTIFIER.test(pattern) && !/[*+?[\](){}|^\\$]/.test(pattern)) {
|
|
73
|
+
return { ...base, isExactSymbol: true, isRegex: false, sanitizedSymbolHint: pattern };
|
|
74
|
+
}
|
|
75
|
+
return { ...base, isExactSymbol: false, isRegex: hasMeta, sanitizedSymbolHint: identifierTokens(pattern) };
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function validLineSpan(span) {
|
|
79
|
+
if (!Array.isArray(span) || span.length !== 2) return null;
|
|
80
|
+
const [start, end] = span.map(Number);
|
|
81
|
+
return Number.isInteger(start) && Number.isInteger(end) && start >= 1 && end >= start ? [start, end] : null;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function cleanToolName(name) {
|
|
85
|
+
const s = String(name || "unknown").replace(/[^A-Za-z0-9 _.:/-]/g, "").slice(0, 64);
|
|
86
|
+
return s || "unknown";
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// action: { escapeType, toolName, paths?, cwd?, lineSpan?, pattern?, fixed?, exitCode? }
|
|
90
|
+
// ctx: { realRoot, clientAgent, mcpSessionId, parentRequestId, parentTraceId, now }
|
|
91
|
+
export async function buildWireEvent(action, ctx) {
|
|
92
|
+
if (!ESCAPE_TYPES.has(action.escapeType)) return null;
|
|
93
|
+
const targetRelPaths = [];
|
|
94
|
+
for (const raw of action.paths || []) {
|
|
95
|
+
const rel = toRepoRelative(ctx.realRoot, action.cwd || ctx.realRoot, raw);
|
|
96
|
+
if (rel && !targetRelPaths.includes(rel)) targetRelPaths.push(rel);
|
|
97
|
+
if (targetRelPaths.length >= MAX_PATHS) break;
|
|
98
|
+
}
|
|
99
|
+
// A read or edit whose every path was outside the repo (or secret-looking) is not about this workspace.
|
|
100
|
+
if ((action.escapeType === "READ" || action.escapeType === "EDIT") && (action.paths || []).length && !targetRelPaths.length) {
|
|
101
|
+
return null;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
let postEditFileSha256 = null;
|
|
105
|
+
if (action.escapeType === "EDIT" && targetRelPaths.length === 1 && targetRelPaths[0] !== ".") {
|
|
106
|
+
postEditFileSha256 = await hashFileInRepo(ctx.realRoot, path.join(ctx.realRoot, targetRelPaths[0]));
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
const isSpanType = action.escapeType === "READ" || action.escapeType === "EDIT";
|
|
110
|
+
return {
|
|
111
|
+
clientEventId: newClientEventId(),
|
|
112
|
+
mcpSessionId: ctx.mcpSessionId || null,
|
|
113
|
+
clientAgent: ctx.clientAgent,
|
|
114
|
+
escapeType: action.escapeType,
|
|
115
|
+
toolName: cleanToolName(action.toolName),
|
|
116
|
+
parentRequestId: ctx.parentRequestId || null,
|
|
117
|
+
parentTraceId: ctx.parentTraceId || null,
|
|
118
|
+
targetRelPaths,
|
|
119
|
+
lineSpan: isSpanType ? validLineSpan(action.lineSpan) : null,
|
|
120
|
+
searchShape: action.escapeType === "SEARCH" ? searchShapeFor(action.pattern, { fixed: action.fixed }) : null,
|
|
121
|
+
postEditFileSha256,
|
|
122
|
+
exitCode: (action.escapeType === "BUILD" || action.escapeType === "SEARCH") && Number.isInteger(action.exitCode)
|
|
123
|
+
? action.exitCode : null,
|
|
124
|
+
clientTimestampEpochMs: ctx.now ?? Date.now(),
|
|
125
|
+
};
|
|
126
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
// SHA-256 of a file's raw disk bytes after an edit (RSI MCP spec §5.4): no decoding, no line-ending changes, so it
|
|
2
|
+
// equals Java's MessageDigest.getInstance("SHA-256") over Files.readAllBytes for the same file.
|
|
3
|
+
import crypto from "crypto";
|
|
4
|
+
import fs from "fs";
|
|
5
|
+
import path from "path";
|
|
6
|
+
|
|
7
|
+
export const MAX_HASH_BYTES = 10_485_760; // 10 MiB
|
|
8
|
+
|
|
9
|
+
// realpath-resolved containment: rejects ../ escapes and symlinks pointing outside the repo.
|
|
10
|
+
export function insideRoot(realRoot, candidate) {
|
|
11
|
+
const rel = path.relative(realRoot, candidate);
|
|
12
|
+
return rel !== "" && !rel.startsWith("..") && !path.isAbsolute(rel);
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
// Lowercase hex digest, or null when the file is missing, not regular, too large, or outside the repo.
|
|
16
|
+
export async function hashFileInRepo(realRoot, absPath) {
|
|
17
|
+
try {
|
|
18
|
+
const real = fs.realpathSync(absPath);
|
|
19
|
+
if (!insideRoot(realRoot, real)) return null;
|
|
20
|
+
const stat = fs.statSync(real);
|
|
21
|
+
if (!stat.isFile() || stat.size > MAX_HASH_BYTES) return null;
|
|
22
|
+
const hash = crypto.createHash("sha256");
|
|
23
|
+
await new Promise((resolve, reject) => {
|
|
24
|
+
fs.createReadStream(real)
|
|
25
|
+
.on("data", (chunk) => hash.update(chunk))
|
|
26
|
+
.on("end", resolve)
|
|
27
|
+
.on("error", reject);
|
|
28
|
+
});
|
|
29
|
+
return hash.digest("hex");
|
|
30
|
+
} catch {
|
|
31
|
+
return null;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
// Telemetry key + X-Harmony-Hook-Signature (RSI wire contract §3.2, §4).
|
|
2
|
+
// The key is 32 bytes kept as 64 lowercase hex in ~/.harmony/telemetry.key (0600). It is never logged.
|
|
3
|
+
import crypto from "crypto";
|
|
4
|
+
import fs from "fs";
|
|
5
|
+
|
|
6
|
+
import { atomicWriteFile, harmonyPath } from "../localState.js";
|
|
7
|
+
|
|
8
|
+
const KEY_HEX = /^[0-9a-f]{64}$/;
|
|
9
|
+
|
|
10
|
+
export function telemetryKeyPath() {
|
|
11
|
+
return harmonyPath("telemetry.key");
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
// The key bytes, or null when there is no valid key file.
|
|
15
|
+
export function readTelemetryKey() {
|
|
16
|
+
try {
|
|
17
|
+
const hex = fs.readFileSync(telemetryKeyPath(), "utf8").trim().toLowerCase();
|
|
18
|
+
return KEY_HEX.test(hex) ? Buffer.from(hex, "hex") : null;
|
|
19
|
+
} catch {
|
|
20
|
+
return null;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function writeTelemetryKey(hex) {
|
|
25
|
+
const clean = String(hex || "").trim().toLowerCase();
|
|
26
|
+
if (!KEY_HEX.test(clean)) throw new Error("telemetry key must be 64 lowercase hex chars");
|
|
27
|
+
atomicWriteFile(telemetryKeyPath(), `${clean}\n`, 0o600);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function telemetryKeyId(keyBytes) {
|
|
31
|
+
return `tk_${crypto.createHash("sha256").update(keyBytes).digest("hex").slice(0, 16)}`;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// Headers for one tool-events request. `rawBody` must be the exact string sent.
|
|
35
|
+
export function signBatch(keyBytes, rawBody, timestampMs = Date.now()) {
|
|
36
|
+
const timestamp = String(timestampMs);
|
|
37
|
+
const mac = crypto.createHmac("sha256", keyBytes).update(`${timestamp}.`).update(rawBody, "utf8").digest("hex");
|
|
38
|
+
return { "X-Harmony-Hook-Timestamp": timestamp, "X-Harmony-Hook-Signature": `sha256=${mac}` };
|
|
39
|
+
}
|