@codeconductorai/harmony-mcp 1.0.33 → 1.0.35
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +217 -15
- package/package.json +4 -2
- package/src/{deviceAuth.js → auth/deviceAuth.js} +39 -8
- package/src/{harmonyClient.js → backend/harmonyClient.js} +183 -13
- package/src/doctor/doctorCommand.js +385 -0
- package/src/index.js +18 -5
- package/src/{telemetry.js → observability/telemetry.js} +3 -3
- package/src/rsi/bundleHints.js +181 -0
- package/src/rsi/bundleRefresher.js +95 -0
- package/src/rsi/callContext.js +49 -0
- package/src/rsi/causalState.js +103 -0
- package/src/rsi/clientAgent.js +58 -0
- package/src/rsi/hooks/eventBuilder.js +129 -0
- package/src/rsi/hooks/fileHash.js +33 -0
- package/src/rsi/hooks/hmacSigner.js +69 -0
- package/src/rsi/hooks/hookEventCommand.js +196 -0
- package/src/rsi/hooks/normalizers.js +329 -0
- package/src/rsi/hooks/offlineSpooler.js +142 -0
- package/src/rsi/hooks/secretScrubber.js +50 -0
- package/src/rsi/hooks/shellCommandScrubber.js +449 -0
- package/src/rsi/hooks/spoolDrainer.js +78 -0
- package/src/rsi/hooks/toolEventsClient.js +70 -0
- package/src/rsi/localState.js +53 -0
- package/src/rsi/serveTelemetry.js +101 -0
- package/src/rsi/workspaceRegistry.js +63 -0
- package/src/{server.js → server/server.js} +107 -17
- package/src/{serverInstructions.js → server/serverInstructions.js} +2 -2
- package/src/server/serverMain.js +46 -0
- package/src/{sessionIdentity.js → session/sessionIdentity.js} +10 -6
- package/src/setup/agentCapabilityMatrix.js +425 -0
- package/src/setup/agentsGuide.js +28 -0
- package/src/setup/configMergers.js +272 -0
- package/src/{installer.js → setup/installer.js} +1 -1
- package/src/setup/setupAgentsCommand.js +192 -0
- package/src/setup/shim.js +80 -0
- package/src/sync/managedMarkdownInjector.js +103 -0
- package/src/sync/syncWorkspaceCommand.js +143 -0
- package/src/sync/workspaceSync.js +88 -0
- package/src/{fileWatcher.js → workspace/fileWatcher.js} +2 -2
- package/src/{workspaceIdentity.js → workspace/workspaceIdentity.js} +1 -1
- package/src/agentsGuide.js +0 -38
- package/src/serverMain.js +0 -32
- /package/src/{log.js → observability/log.js} +0 -0
- /package/src/{toolSchemas.js → server/toolSchemas.js} +0 -0
- /package/src/{fileFilters.js → workspace/fileFilters.js} +0 -0
- /package/src/{repoIdentity.js → workspace/repoIdentity.js} +0 -0
- /package/src/{workspaceMarker.js → workspace/workspaceMarker.js} +0 -0
|
@@ -11,10 +11,10 @@ import { PeriodicExportingMetricReader } from "@opentelemetry/sdk-metrics";
|
|
|
11
11
|
import { BatchLogRecordProcessor } from "@opentelemetry/sdk-logs";
|
|
12
12
|
|
|
13
13
|
import { log } from "./log.js";
|
|
14
|
-
import { API_URL, getSessionToken, getWorkspaceToken } from "
|
|
15
|
-
import { readMarker } from "
|
|
14
|
+
import { API_URL, getSessionToken, getWorkspaceToken } from "../auth/deviceAuth.js";
|
|
15
|
+
import { readMarker } from "../workspace/workspaceMarker.js";
|
|
16
16
|
|
|
17
|
-
const packageJson = createRequire(import.meta.url)("
|
|
17
|
+
const packageJson = createRequire(import.meta.url)("../../package.json");
|
|
18
18
|
|
|
19
19
|
const OTLP_BASE = `${API_URL}/api/v1/otel`;
|
|
20
20
|
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
// RSI bundle tool-hint hydration (RSI MCP spec §4.4).
|
|
2
|
+
//
|
|
3
|
+
// The org's RSI bundle can refine how agents use Harmony's tools without a new harmony-mcp release: each hint
|
|
4
|
+
// appends a bounded suffix to a tool's description and, optionally, to its parameters' descriptions. Hints never
|
|
5
|
+
// rename tools, add or remove parameters, or change schema types, and the auth/setup tools are never touched
|
|
6
|
+
// (their descriptions carry the user-consent rules).
|
|
7
|
+
//
|
|
8
|
+
// Flow: boot from the on-disk cache (tools/list is right on the first call), then in the background ask the
|
|
9
|
+
// backend which bundle this session is pinned to (POST /rsi/pin) and, if it differs from the cache, fetch it
|
|
10
|
+
// (GET /api/rsi/bundles/{id}), rewrite the cache and tell the host the tool list changed.
|
|
11
|
+
import { atomicWriteFile, harmonyPath, readJsonFile } from "./localState.js";
|
|
12
|
+
|
|
13
|
+
export const CACHE_SCHEMA_VERSION = 1;
|
|
14
|
+
const MAX_DESCRIPTION_SUFFIX_CHARS = 400;
|
|
15
|
+
const MAX_PARAM_HINT_CHARS = 200;
|
|
16
|
+
const MAX_HINTED_TOOLS = 32;
|
|
17
|
+
|
|
18
|
+
// Tools whose descriptions enforce user consent (login confirmation, indexing despite secrets): never hinted.
|
|
19
|
+
export const HINT_EXEMPT_TOOLS = new Set(["login", "confirm_login", "setup_workspace"]);
|
|
20
|
+
|
|
21
|
+
const state = {
|
|
22
|
+
workspaceId: null,
|
|
23
|
+
bundleId: null,
|
|
24
|
+
hints: {},
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
export function activeBundleId() {
|
|
28
|
+
return state.bundleId;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
// The bundle to pin calls for this workspace to, so every call runs on the bundle whose hints the agent was shown.
|
|
32
|
+
export function activeBundleIdFor(workspaceId) {
|
|
33
|
+
return workspaceId != null && state.workspaceId === String(workspaceId) ? state.bundleId : null;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function activeHints() {
|
|
37
|
+
return state.hints;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// The bundle this process asks the backend for: an explicit override, else the backend's choice for the org.
|
|
41
|
+
export function requestedBundleId(marker) {
|
|
42
|
+
const explicit = process.env.HARMONY_RSI_BUNDLE_ID || marker?.rsiBundleId;
|
|
43
|
+
return typeof explicit === "string" && explicit.trim() ? explicit.trim() : null;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function bundleCachePath(workspaceId) {
|
|
47
|
+
const safe = String(workspaceId).replace(/[^A-Za-z0-9_-]/g, "_");
|
|
48
|
+
return harmonyPath("cache", "bundles", `ws-${safe}-manifest.json`);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// Printable text only, bounded. Newlines are kept (suffixes may be short lists); other control chars are not.
|
|
52
|
+
function cleanText(value, maxChars) {
|
|
53
|
+
if (typeof value !== "string") return null;
|
|
54
|
+
const text = value.replace(/[\u0000-\u0009\u000b-\u001f\u007f]/g, " ").replace(/\n{3,}/g, "\n\n").trim();
|
|
55
|
+
if (!text) return null;
|
|
56
|
+
return text.length > maxChars ? `${text.slice(0, maxChars - 1)}…` : text;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
// Accepts both the backend's current shape ({tool: "suffix"}) and the spec's ({tool: {descriptionSuffix, paramHints}}).
|
|
60
|
+
export function normalizeToolHints(raw) {
|
|
61
|
+
const out = {};
|
|
62
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return out;
|
|
63
|
+
for (const [tool, value] of Object.entries(raw).slice(0, MAX_HINTED_TOOLS)) {
|
|
64
|
+
if (!/^[a-z][a-z0-9_]{0,63}$/.test(tool) || HINT_EXEMPT_TOOLS.has(tool)) continue;
|
|
65
|
+
const hint = {};
|
|
66
|
+
const suffix = cleanText(typeof value === "string" ? value : value?.descriptionSuffix, MAX_DESCRIPTION_SUFFIX_CHARS);
|
|
67
|
+
if (suffix) hint.descriptionSuffix = suffix;
|
|
68
|
+
if (value && typeof value === "object" && value.paramHints && typeof value.paramHints === "object") {
|
|
69
|
+
const params = {};
|
|
70
|
+
for (const [param, text] of Object.entries(value.paramHints)) {
|
|
71
|
+
const cleaned = cleanText(text, MAX_PARAM_HINT_CHARS);
|
|
72
|
+
if (cleaned && /^[A-Za-z_][A-Za-z0-9_]{0,63}$/.test(param)) params[param] = cleaned;
|
|
73
|
+
}
|
|
74
|
+
if (Object.keys(params).length) hint.paramHints = params;
|
|
75
|
+
}
|
|
76
|
+
if (Object.keys(hint).length) out[tool] = hint;
|
|
77
|
+
}
|
|
78
|
+
return out;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// maxTokens -> max_tokens: bundle authors may use the backend's camelCase names for the tool's snake_case params.
|
|
82
|
+
function snakeCase(name) {
|
|
83
|
+
return name.replace(/([a-z0-9])([A-Z])/g, "$1_$2").toLowerCase();
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// A copy of `tools` with hints merged in. Tools without a hint are returned as the same objects.
|
|
87
|
+
export function applyToolHints(tools, hints = state.hints) {
|
|
88
|
+
if (!hints || !Object.keys(hints).length) return tools;
|
|
89
|
+
return tools.map((tool) => {
|
|
90
|
+
const hint = hints[tool.name];
|
|
91
|
+
if (!hint || HINT_EXEMPT_TOOLS.has(tool.name)) return tool;
|
|
92
|
+
const merged = { ...tool };
|
|
93
|
+
if (hint.descriptionSuffix) merged.description = `${tool.description}\n\n${hint.descriptionSuffix}`;
|
|
94
|
+
const properties = tool.inputSchema?.properties;
|
|
95
|
+
if (hint.paramHints && properties) {
|
|
96
|
+
const nextProps = { ...properties };
|
|
97
|
+
let touched = false;
|
|
98
|
+
for (const [param, text] of Object.entries(hint.paramHints)) {
|
|
99
|
+
const key = param in nextProps ? param : snakeCase(param);
|
|
100
|
+
if (!(key in nextProps)) continue;
|
|
101
|
+
const prop = nextProps[key];
|
|
102
|
+
nextProps[key] = { ...prop, description: prop.description ? `${prop.description} ${text}` : text };
|
|
103
|
+
touched = true;
|
|
104
|
+
}
|
|
105
|
+
if (touched) merged.inputSchema = { ...tool.inputSchema, properties: nextProps };
|
|
106
|
+
}
|
|
107
|
+
return merged;
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function sameHints(a, b) {
|
|
112
|
+
return JSON.stringify(a || {}) === JSON.stringify(b || {});
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
// Loads the cached bundle for this workspace and backend. Returns true if hints were loaded.
|
|
116
|
+
export function loadCachedBundle(workspaceId, apiUrl) {
|
|
117
|
+
if (!workspaceId) return false;
|
|
118
|
+
const cached = readJsonFile(bundleCachePath(workspaceId));
|
|
119
|
+
if (
|
|
120
|
+
cached?.schemaVersion !== CACHE_SCHEMA_VERSION ||
|
|
121
|
+
cached.apiUrl !== apiUrl ||
|
|
122
|
+
String(cached.workspaceId) !== String(workspaceId) ||
|
|
123
|
+
typeof cached.bundleId !== "string"
|
|
124
|
+
) {
|
|
125
|
+
return false;
|
|
126
|
+
}
|
|
127
|
+
state.workspaceId = String(workspaceId);
|
|
128
|
+
state.bundleId = cached.bundleId;
|
|
129
|
+
state.hints = normalizeToolHints(cached.mcpToolHints);
|
|
130
|
+
return true;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// Asks the backend which bundle this session runs on and refreshes hints if it changed.
|
|
134
|
+
// pin(workspaceId, requestedBundleId) -> pinned bundle id, or null when the backend has no RSI support
|
|
135
|
+
// fetchBundle(bundleId) -> bundle JSON ({manifest, mcpToolHints, managedAgentInstructionsMarkdown, ...})
|
|
136
|
+
// Returns { bundleId, changed } where changed means the tool list the host sees is different.
|
|
137
|
+
export async function refreshBundle({ workspaceId, apiUrl, requested, pin, fetchBundle }) {
|
|
138
|
+
if (!workspaceId) return { bundleId: state.bundleId, changed: false };
|
|
139
|
+
const sameWorkspace = state.workspaceId === String(workspaceId);
|
|
140
|
+
const pinnedId = await pin(workspaceId, requested);
|
|
141
|
+
if (!pinnedId) {
|
|
142
|
+
// Backend without RSI: drop hints that came from a cache for a different workspace.
|
|
143
|
+
if (!sameWorkspace && Object.keys(state.hints).length) {
|
|
144
|
+
Object.assign(state, { workspaceId: String(workspaceId), bundleId: null, hints: {} });
|
|
145
|
+
return { bundleId: null, changed: true };
|
|
146
|
+
}
|
|
147
|
+
return { bundleId: state.bundleId, changed: false };
|
|
148
|
+
}
|
|
149
|
+
if (sameWorkspace && state.bundleId === pinnedId) return { bundleId: pinnedId, changed: false };
|
|
150
|
+
|
|
151
|
+
const bundle = await fetchBundle(pinnedId);
|
|
152
|
+
const hints = normalizeToolHints(bundle?.mcpToolHints);
|
|
153
|
+
const changed = !sameHints(hints, sameWorkspace ? state.hints : {}) || (!sameWorkspace && Object.keys(state.hints).length > 0);
|
|
154
|
+
Object.assign(state, { workspaceId: String(workspaceId), bundleId: pinnedId, hints });
|
|
155
|
+
|
|
156
|
+
atomicWriteFile(
|
|
157
|
+
bundleCachePath(workspaceId),
|
|
158
|
+
`${JSON.stringify(
|
|
159
|
+
{
|
|
160
|
+
schemaVersion: CACHE_SCHEMA_VERSION,
|
|
161
|
+
apiUrl,
|
|
162
|
+
workspaceId: String(workspaceId),
|
|
163
|
+
bundleId: pinnedId,
|
|
164
|
+
fetchedAtEpochMs: Date.now(),
|
|
165
|
+
mcpToolHints: hints,
|
|
166
|
+
managedAgentInstructionsMd: typeof bundle?.managedAgentInstructionsMarkdown === "string"
|
|
167
|
+
? bundle.managedAgentInstructionsMarkdown : "",
|
|
168
|
+
workspaceWorldModelMd: typeof bundle?.workspaceWorldModelMarkdown === "string"
|
|
169
|
+
? bundle.workspaceWorldModelMarkdown : "",
|
|
170
|
+
},
|
|
171
|
+
null,
|
|
172
|
+
2,
|
|
173
|
+
)}\n`,
|
|
174
|
+
);
|
|
175
|
+
return { bundleId: pinnedId, changed };
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
// Test hook.
|
|
179
|
+
export function resetBundleStateForTests() {
|
|
180
|
+
Object.assign(state, { workspaceId: null, bundleId: null, hints: {} });
|
|
181
|
+
}
|
|
@@ -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,129 @@
|
|
|
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 os from "os";
|
|
8
|
+
import path from "path";
|
|
9
|
+
|
|
10
|
+
import { looksSecret } from "./secretScrubber.js";
|
|
11
|
+
import { hashFileInRepo, insideRoot } from "./fileHash.js";
|
|
12
|
+
|
|
13
|
+
export const ESCAPE_TYPES = new Set(["SEARCH", "READ", "EDIT", "BUILD", "COMPACT"]);
|
|
14
|
+
const MAX_PATHS = 50;
|
|
15
|
+
const MAX_PATH_CHARS = 512;
|
|
16
|
+
const MAX_HINT_CHARS = 64;
|
|
17
|
+
const CLEAN_IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$.#:-]{1,96}$/;
|
|
18
|
+
const REGEX_META = /[.*+?[\](){}|^\\$]/;
|
|
19
|
+
|
|
20
|
+
export function newClientEventId() {
|
|
21
|
+
return `cev_${crypto.randomBytes(10).toString("hex")}`;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
// Repo-relative POSIX path, or null when it is outside the repo, contains .. after resolution, or a segment of it
|
|
25
|
+
// looks secret. Only the repo-relative part is judged: the absolute prefix never leaves the machine.
|
|
26
|
+
export function toRepoRelative(realRoot, cwd, rawPath) {
|
|
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));
|
|
30
|
+
const abs = path.resolve(cwd || realRoot, rawPath);
|
|
31
|
+
let resolved = abs;
|
|
32
|
+
try {
|
|
33
|
+
resolved = fs.realpathSync(abs);
|
|
34
|
+
} catch {
|
|
35
|
+
// Not on disk (deleted file, glob): judge the lexical path, resolved against the real root.
|
|
36
|
+
const lexicalRel = path.relative(realRoot, abs);
|
|
37
|
+
if (lexicalRel.startsWith("..") || path.isAbsolute(lexicalRel)) {
|
|
38
|
+
// cwd may itself be a symlinked path to the root
|
|
39
|
+
try {
|
|
40
|
+
resolved = path.join(fs.realpathSync(path.dirname(abs)), path.basename(abs));
|
|
41
|
+
} catch {
|
|
42
|
+
return null;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
if (!insideRoot(realRoot, resolved) && resolved !== realRoot) return null;
|
|
47
|
+
const rel = path.relative(realRoot, resolved).split(path.sep).join("/");
|
|
48
|
+
if (!rel) return ".";
|
|
49
|
+
const segments = rel.split("/");
|
|
50
|
+
// A backslash is never part of a repo path here (it is usually a regex escape that was mistaken for a file), and
|
|
51
|
+
// the backend rejects the whole batch for one.
|
|
52
|
+
if (segments.includes("..") || rel.includes("\\") || rel.length > MAX_PATH_CHARS || segments.some(looksSecret)) return null;
|
|
53
|
+
return rel;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function identifierTokens(text) {
|
|
57
|
+
const tokens = (text.match(/[A-Za-z_][A-Za-z0-9_]{2,}/g) || []).filter((t) => !looksSecret(t));
|
|
58
|
+
let out = "";
|
|
59
|
+
for (const t of tokens) {
|
|
60
|
+
const next = out ? `${out} ${t}` : t;
|
|
61
|
+
if (next.length > MAX_HINT_CHARS) break;
|
|
62
|
+
out = next;
|
|
63
|
+
}
|
|
64
|
+
return out || null;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// Search shape per spec §5.3: never the raw pattern unless it is a clean identifier.
|
|
68
|
+
export function searchShapeFor(pattern, { fixed = false } = {}) {
|
|
69
|
+
if (typeof pattern !== "string" || !pattern) return null;
|
|
70
|
+
const hasMeta = !fixed && REGEX_META.test(pattern);
|
|
71
|
+
const base = { tokenLength: pattern.length, matchesKnownWorkspaceSymbol: null };
|
|
72
|
+
if (looksSecret(pattern)) {
|
|
73
|
+
return { ...base, isExactSymbol: false, isRegex: hasMeta, sanitizedSymbolHint: "<REDACTED>" };
|
|
74
|
+
}
|
|
75
|
+
if (CLEAN_IDENTIFIER.test(pattern) && !/[*+?[\](){}|^\\$]/.test(pattern)) {
|
|
76
|
+
return { ...base, isExactSymbol: true, isRegex: false, sanitizedSymbolHint: pattern };
|
|
77
|
+
}
|
|
78
|
+
return { ...base, isExactSymbol: false, isRegex: hasMeta, sanitizedSymbolHint: identifierTokens(pattern) };
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function validLineSpan(span) {
|
|
82
|
+
if (!Array.isArray(span) || span.length !== 2) return null;
|
|
83
|
+
const [start, end] = span.map(Number);
|
|
84
|
+
return Number.isInteger(start) && Number.isInteger(end) && start >= 1 && end >= start ? [start, end] : null;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function cleanToolName(name) {
|
|
88
|
+
const s = String(name || "unknown").replace(/[^A-Za-z0-9 _.:/-]/g, "").slice(0, 64);
|
|
89
|
+
return s || "unknown";
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// action: { escapeType, toolName, paths?, cwd?, lineSpan?, pattern?, fixed?, exitCode? }
|
|
93
|
+
// ctx: { realRoot, clientAgent, mcpSessionId, parentRequestId, parentTraceId, now }
|
|
94
|
+
export async function buildWireEvent(action, ctx) {
|
|
95
|
+
if (!ESCAPE_TYPES.has(action.escapeType)) return null;
|
|
96
|
+
const targetRelPaths = [];
|
|
97
|
+
for (const raw of action.paths || []) {
|
|
98
|
+
const rel = toRepoRelative(ctx.realRoot, action.cwd || ctx.realRoot, raw);
|
|
99
|
+
if (rel && !targetRelPaths.includes(rel)) targetRelPaths.push(rel);
|
|
100
|
+
if (targetRelPaths.length >= MAX_PATHS) break;
|
|
101
|
+
}
|
|
102
|
+
// A read or edit whose every path was outside the repo (or secret-looking) is not about this workspace.
|
|
103
|
+
if ((action.escapeType === "READ" || action.escapeType === "EDIT") && (action.paths || []).length && !targetRelPaths.length) {
|
|
104
|
+
return null;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
let postEditFileSha256 = null;
|
|
108
|
+
if (action.escapeType === "EDIT" && targetRelPaths.length === 1 && targetRelPaths[0] !== ".") {
|
|
109
|
+
postEditFileSha256 = await hashFileInRepo(ctx.realRoot, path.join(ctx.realRoot, targetRelPaths[0]));
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
const isSpanType = action.escapeType === "READ" || action.escapeType === "EDIT";
|
|
113
|
+
return {
|
|
114
|
+
clientEventId: newClientEventId(),
|
|
115
|
+
mcpSessionId: ctx.mcpSessionId || null,
|
|
116
|
+
clientAgent: ctx.clientAgent,
|
|
117
|
+
escapeType: action.escapeType,
|
|
118
|
+
toolName: cleanToolName(action.toolName),
|
|
119
|
+
parentRequestId: ctx.parentRequestId || null,
|
|
120
|
+
parentTraceId: ctx.parentTraceId || null,
|
|
121
|
+
targetRelPaths,
|
|
122
|
+
lineSpan: isSpanType ? validLineSpan(action.lineSpan) : null,
|
|
123
|
+
searchShape: action.escapeType === "SEARCH" ? searchShapeFor(action.pattern, { fixed: action.fixed }) : null,
|
|
124
|
+
postEditFileSha256,
|
|
125
|
+
exitCode: (action.escapeType === "BUILD" || action.escapeType === "SEARCH") && Number.isInteger(action.exitCode)
|
|
126
|
+
? action.exitCode : null,
|
|
127
|
+
clientTimestampEpochMs: ctx.now ?? Date.now(),
|
|
128
|
+
};
|
|
129
|
+
}
|
|
@@ -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
|
+
}
|