@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,449 @@
|
|
|
1
|
+
// Structural parser for shell commands agents run through a generic Bash/shell tool (RSI MCP spec §5.3).
|
|
2
|
+
//
|
|
3
|
+
// It extracts only what the backend needs to see that the agent went around Harmony: which kind of command
|
|
4
|
+
// (search / read / edit / build), the search pattern (scrubbed later), the file arguments and a line span.
|
|
5
|
+
// Command arguments are never forwarded as-is, and anything unrecognised (echo, curl, ssh, export, docker login,
|
|
6
|
+
// aws, ...) produces nothing at all.
|
|
7
|
+
import path from "path";
|
|
8
|
+
|
|
9
|
+
const MAX_COMMAND_CHARS = 16_384;
|
|
10
|
+
const MAX_ACTIONS = 5;
|
|
11
|
+
|
|
12
|
+
// ---- Lexer: words and control operators, POSIX quoting. ----
|
|
13
|
+
// $(...), `...` and heredoc bodies are opaque: their contents are never parsed as commands.
|
|
14
|
+
const OPERATORS = ["&&", "||", ";;", "|&", "|", ";", "&", "\n", "(", ")"];
|
|
15
|
+
|
|
16
|
+
export function tokenize(command) {
|
|
17
|
+
const tokens = [];
|
|
18
|
+
let word = null;
|
|
19
|
+
let i = 0;
|
|
20
|
+
const src = command.slice(0, MAX_COMMAND_CHARS);
|
|
21
|
+
const push = () => {
|
|
22
|
+
if (word !== null) tokens.push({ word });
|
|
23
|
+
word = null;
|
|
24
|
+
};
|
|
25
|
+
while (i < src.length) {
|
|
26
|
+
const ch = src[i];
|
|
27
|
+
if (ch === "\\" && i + 1 < src.length) {
|
|
28
|
+
if (src[i + 1] === "\n") {
|
|
29
|
+
i += 2;
|
|
30
|
+
continue;
|
|
31
|
+
}
|
|
32
|
+
word = (word ?? "") + src[i + 1];
|
|
33
|
+
i += 2;
|
|
34
|
+
continue;
|
|
35
|
+
}
|
|
36
|
+
if (ch === "'") {
|
|
37
|
+
const end = src.indexOf("'", i + 1);
|
|
38
|
+
const stop = end < 0 ? src.length : end;
|
|
39
|
+
word = (word ?? "") + src.slice(i + 1, stop);
|
|
40
|
+
i = stop + 1;
|
|
41
|
+
continue;
|
|
42
|
+
}
|
|
43
|
+
if (ch === '"') {
|
|
44
|
+
let j = i + 1;
|
|
45
|
+
let buf = "";
|
|
46
|
+
while (j < src.length && src[j] !== '"') {
|
|
47
|
+
if (src[j] === "\\" && j + 1 < src.length && '"\\$`'.includes(src[j + 1])) {
|
|
48
|
+
buf += src[j + 1];
|
|
49
|
+
j += 2;
|
|
50
|
+
} else {
|
|
51
|
+
buf += src[j++];
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
word = (word ?? "") + buf;
|
|
55
|
+
i = j + 1;
|
|
56
|
+
continue;
|
|
57
|
+
}
|
|
58
|
+
if (ch === "$" && src[i + 1] === "(") {
|
|
59
|
+
// Opaque command substitution: skip to the matching paren.
|
|
60
|
+
let depth = 0;
|
|
61
|
+
let j = i + 1;
|
|
62
|
+
for (; j < src.length; j++) {
|
|
63
|
+
if (src[j] === "(") depth++;
|
|
64
|
+
else if (src[j] === ")" && --depth === 0) break;
|
|
65
|
+
}
|
|
66
|
+
word = (word ?? "") + "\u0000SUBST\u0000";
|
|
67
|
+
i = j + 1;
|
|
68
|
+
continue;
|
|
69
|
+
}
|
|
70
|
+
if (ch === "`") {
|
|
71
|
+
const end = src.indexOf("`", i + 1);
|
|
72
|
+
word = (word ?? "") + "\u0000SUBST\u0000";
|
|
73
|
+
i = end < 0 ? src.length : end + 1;
|
|
74
|
+
continue;
|
|
75
|
+
}
|
|
76
|
+
if (ch === "#" && word === null) {
|
|
77
|
+
// Comment to end of line.
|
|
78
|
+
const nl = src.indexOf("\n", i);
|
|
79
|
+
i = nl < 0 ? src.length : nl;
|
|
80
|
+
continue;
|
|
81
|
+
}
|
|
82
|
+
if (ch === "<" && src[i + 1] === "<" && src[i + 2] !== "<") {
|
|
83
|
+
// Heredoc: drop the body (up to the delimiter line) entirely.
|
|
84
|
+
push();
|
|
85
|
+
let j = i + 2;
|
|
86
|
+
if (src[j] === "-") j++;
|
|
87
|
+
while (src[j] === " " || src[j] === "\t") j++;
|
|
88
|
+
const m = /^(['"]?)([A-Za-z0-9_.-]+)\1/.exec(src.slice(j));
|
|
89
|
+
const delimiter = m ? m[2] : null;
|
|
90
|
+
const lineEnd = src.indexOf("\n", j);
|
|
91
|
+
tokens.push({ heredoc: true });
|
|
92
|
+
if (!delimiter || lineEnd < 0) {
|
|
93
|
+
i = src.length;
|
|
94
|
+
continue;
|
|
95
|
+
}
|
|
96
|
+
// Rest of the heredoc line still holds commands (e.g. `cat <<EOF > f`); keep it, skip the body.
|
|
97
|
+
const rest = src.slice(j + m[0].length, lineEnd);
|
|
98
|
+
const bodyEnd = src.slice(lineEnd + 1).search(new RegExp(`^\\s*${delimiter.replace(/[.]/g, "\\.")}\\s*$`, "m"));
|
|
99
|
+
const after = bodyEnd < 0 ? "" : src.slice(lineEnd + 1 + bodyEnd).replace(/^.*(\n|$)/, "\n");
|
|
100
|
+
tokens.push(...tokenize(rest));
|
|
101
|
+
tokens.push({ op: "\n" });
|
|
102
|
+
tokens.push(...tokenize(after));
|
|
103
|
+
return tokens;
|
|
104
|
+
}
|
|
105
|
+
if (ch === " " || ch === "\t") {
|
|
106
|
+
push();
|
|
107
|
+
i++;
|
|
108
|
+
continue;
|
|
109
|
+
}
|
|
110
|
+
const op = OPERATORS.find((o) => src.startsWith(o, i));
|
|
111
|
+
if (op) {
|
|
112
|
+
push();
|
|
113
|
+
tokens.push({ op });
|
|
114
|
+
i += op.length;
|
|
115
|
+
continue;
|
|
116
|
+
}
|
|
117
|
+
if (/[<>]/.test(ch)) {
|
|
118
|
+
// Redirection: `>`, `>>`, `2>&1`, `&>`, `<`. Mark it so the target is not taken as a file argument.
|
|
119
|
+
if (word !== null && /^\d+$/.test(word)) word = null;
|
|
120
|
+
push();
|
|
121
|
+
let j = i + 1;
|
|
122
|
+
while (j < src.length && /[<>&|]/.test(src[j])) j++;
|
|
123
|
+
while (j < src.length && /\d/.test(src[j]) && src[j - 1] === "&") j++;
|
|
124
|
+
tokens.push({ redirect: src.slice(i, j) });
|
|
125
|
+
i = j;
|
|
126
|
+
continue;
|
|
127
|
+
}
|
|
128
|
+
word = (word ?? "") + ch;
|
|
129
|
+
i++;
|
|
130
|
+
}
|
|
131
|
+
push();
|
|
132
|
+
return tokens;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
// Simple commands: argv arrays between control operators, with redirections removed and remembered.
|
|
136
|
+
export function splitSimpleCommands(tokens) {
|
|
137
|
+
const commands = [];
|
|
138
|
+
let argv = [];
|
|
139
|
+
let redirects = [];
|
|
140
|
+
let pendingRedirect = null;
|
|
141
|
+
const flush = () => {
|
|
142
|
+
if (argv.length || redirects.length) commands.push({ argv, redirects });
|
|
143
|
+
argv = [];
|
|
144
|
+
redirects = [];
|
|
145
|
+
};
|
|
146
|
+
for (const t of tokens) {
|
|
147
|
+
if (t.op) {
|
|
148
|
+
pendingRedirect = null;
|
|
149
|
+
flush();
|
|
150
|
+
} else if (t.redirect) {
|
|
151
|
+
pendingRedirect = t.redirect;
|
|
152
|
+
} else if (t.heredoc) {
|
|
153
|
+
// stdin from a heredoc: nothing to record
|
|
154
|
+
} else if (pendingRedirect) {
|
|
155
|
+
if (!/&\d*$/.test(pendingRedirect)) redirects.push({ op: pendingRedirect, target: t.word });
|
|
156
|
+
pendingRedirect = null;
|
|
157
|
+
} else {
|
|
158
|
+
argv.push(t.word);
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
flush();
|
|
162
|
+
return commands;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
// ---- Classification. ----
|
|
166
|
+
const SEARCH_VERBS = new Set(["rg", "ripgrep", "grep", "egrep", "fgrep", "ag", "ack", "fd", "fdfind", "find", "ast-grep", "sg"]);
|
|
167
|
+
const READ_VERBS = new Set(["cat", "head", "tail", "bat", "batcat", "nl", "less", "more", "awk", "sed", "view"]);
|
|
168
|
+
const WRAPPERS = new Set(["sudo", "command", "builtin", "exec", "nohup", "time", "nice", "stdbuf", "xargs"]);
|
|
169
|
+
|
|
170
|
+
// Options that take a separate value, per search tool, so the value is not mistaken for the pattern or a path.
|
|
171
|
+
const VALUE_OPTS = {
|
|
172
|
+
rg: new Set(["-g", "--glob", "--iglob", "-t", "--type", "-T", "--type-not", "-m", "--max-count", "-A", "-B", "-C",
|
|
173
|
+
"--after-context", "--before-context", "--context", "-j", "--threads", "-M", "--max-columns", "--sort", "--sortr",
|
|
174
|
+
"--color", "--colors", "--type-add", "-E", "--encoding", "--max-depth", "--maxdepth", "-d", "--max-filesize",
|
|
175
|
+
"-r", "--replace", "--pre", "--pre-glob", "--ignore-file", "--path-separator", "-V"]),
|
|
176
|
+
grep: new Set(["-A", "-B", "-C", "-m", "--max-count", "-d", "--directories", "-D", "--devices", "--color",
|
|
177
|
+
"--colour", "--label", "--context", "--after-context", "--before-context", "--binary-files", "--exclude",
|
|
178
|
+
"--include", "--exclude-dir"]),
|
|
179
|
+
ag: new Set(["-A", "-B", "-C", "-G", "--file-search-regex", "-m", "--max-count", "--ignore", "--ignore-dir",
|
|
180
|
+
"--depth", "-g", "-p", "--path-to-ignore"]),
|
|
181
|
+
fd: new Set(["-e", "--extension", "-t", "--type", "-d", "--max-depth", "--min-depth", "-E", "--exclude", "-x",
|
|
182
|
+
"--exec", "-X", "--exec-batch", "-j", "--threads", "-S", "--size", "--changed-within", "--changed-before",
|
|
183
|
+
"-o", "--owner", "--base-directory", "--search-path", "-c", "--color"]),
|
|
184
|
+
"ast-grep": new Set(["-l", "--lang", "-r", "--rewrite", "-c", "--config", "--json", "-A", "-B", "-C", "--globs"]),
|
|
185
|
+
};
|
|
186
|
+
VALUE_OPTS.ripgrep = VALUE_OPTS.rg;
|
|
187
|
+
VALUE_OPTS.egrep = VALUE_OPTS.grep;
|
|
188
|
+
VALUE_OPTS.fgrep = VALUE_OPTS.grep;
|
|
189
|
+
VALUE_OPTS.ack = VALUE_OPTS.ag;
|
|
190
|
+
VALUE_OPTS.fdfind = VALUE_OPTS.fd;
|
|
191
|
+
VALUE_OPTS.sg = VALUE_OPTS["ast-grep"];
|
|
192
|
+
|
|
193
|
+
function isAssignment(word) {
|
|
194
|
+
return /^[A-Za-z_][A-Za-z0-9_]*=/.test(word);
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
function verbName(word) {
|
|
198
|
+
return path.basename(word || "");
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
// Strips env assignments and wrapper commands (`FOO=1 sudo timeout 30 rg x`) down to the real argv.
|
|
202
|
+
function realArgv(argv) {
|
|
203
|
+
let i = 0;
|
|
204
|
+
while (i < argv.length) {
|
|
205
|
+
const w = argv[i];
|
|
206
|
+
if (isAssignment(w)) {
|
|
207
|
+
i++;
|
|
208
|
+
} else if (WRAPPERS.has(verbName(w))) {
|
|
209
|
+
i++;
|
|
210
|
+
while (i < argv.length && argv[i].startsWith("-")) i++;
|
|
211
|
+
} else if (verbName(w) === "env") {
|
|
212
|
+
i++;
|
|
213
|
+
while (i < argv.length && (argv[i].startsWith("-") || isAssignment(argv[i]))) i++;
|
|
214
|
+
} else if (verbName(w) === "timeout") {
|
|
215
|
+
i++;
|
|
216
|
+
while (i < argv.length && argv[i].startsWith("-")) i++;
|
|
217
|
+
if (i < argv.length && /^\d/.test(argv[i])) i++;
|
|
218
|
+
} else {
|
|
219
|
+
break;
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
return argv.slice(i);
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
function containsSubst(word) {
|
|
226
|
+
return word.includes("\u0000SUBST\u0000");
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
function parseSearch(verb, args) {
|
|
230
|
+
const valueOpts = VALUE_OPTS[verb] || new Set();
|
|
231
|
+
let pattern = null;
|
|
232
|
+
let fixed = verb === "fgrep";
|
|
233
|
+
let patternFromFile = false;
|
|
234
|
+
const explicitPatterns = []; // every -e / --regexp value; the search matches any of them
|
|
235
|
+
const positionals = [];
|
|
236
|
+
let endOfOpts = false;
|
|
237
|
+
for (let i = 0; i < args.length; i++) {
|
|
238
|
+
const a = args[i];
|
|
239
|
+
if (!endOfOpts && a === "--") {
|
|
240
|
+
endOfOpts = true;
|
|
241
|
+
continue;
|
|
242
|
+
}
|
|
243
|
+
if (!endOfOpts && a.startsWith("-") && a.length > 1) {
|
|
244
|
+
if (a === "-e" || a === "--regexp") {
|
|
245
|
+
// Always consume the value: a second -e must not leak into the file arguments.
|
|
246
|
+
const value = args[++i];
|
|
247
|
+
if (value !== undefined) explicitPatterns.push(value);
|
|
248
|
+
} else if (a.startsWith("--regexp=")) {
|
|
249
|
+
explicitPatterns.push(a.slice("--regexp=".length));
|
|
250
|
+
} else if (a === "-f" || a === "--file") {
|
|
251
|
+
patternFromFile = true;
|
|
252
|
+
i++;
|
|
253
|
+
} else if (a === "-F" || a === "--fixed-strings" || a === "-Q" || a === "--literal") {
|
|
254
|
+
fixed = true;
|
|
255
|
+
} else if (/^-[A-Za-z]*F[A-Za-z]*$/.test(a) && !valueOpts.has(a)) {
|
|
256
|
+
fixed = true;
|
|
257
|
+
} else if (valueOpts.has(a)) {
|
|
258
|
+
i++;
|
|
259
|
+
} else if (/^-[ABCm]\d+$/.test(a) || a.includes("=")) {
|
|
260
|
+
// value attached
|
|
261
|
+
}
|
|
262
|
+
continue;
|
|
263
|
+
}
|
|
264
|
+
positionals.push(a);
|
|
265
|
+
}
|
|
266
|
+
if (explicitPatterns.length) pattern = explicitPatterns.length === 1 ? explicitPatterns[0] : explicitPatterns.join("|");
|
|
267
|
+
if (pattern === null && !patternFromFile) pattern = positionals.shift() ?? null;
|
|
268
|
+
if (pattern !== null && containsSubst(pattern)) pattern = null;
|
|
269
|
+
return { pattern, fixed, paths: positionals.filter((p) => !containsSubst(p)) };
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
function parseFind(args) {
|
|
273
|
+
const paths = [];
|
|
274
|
+
let i = 0;
|
|
275
|
+
while (i < args.length && !args[i].startsWith("-") && args[i] !== "(" && args[i] !== "!") paths.push(args[i++]);
|
|
276
|
+
let pattern = null;
|
|
277
|
+
for (; i < args.length; i++) {
|
|
278
|
+
if (["-name", "-iname", "-path", "-ipath", "-regex", "-iregex", "-wholename"].includes(args[i])) {
|
|
279
|
+
pattern = args[i + 1] ?? null;
|
|
280
|
+
break;
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
if (pattern !== null && containsSubst(pattern)) pattern = null;
|
|
284
|
+
return { pattern, fixed: false, paths: paths.filter((p) => !containsSubst(p)) };
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
function parseLineSpanForRead(verb, args) {
|
|
288
|
+
if (verb === "sed") {
|
|
289
|
+
const nIdx = args.findIndex((a) => a === "-n" || a === "--quiet" || a === "--silent");
|
|
290
|
+
if (nIdx < 0) return null;
|
|
291
|
+
const script = args.find((a, idx) => idx !== nIdx && !a.startsWith("-"));
|
|
292
|
+
const m = /^(\d+)(?:,(\d+))?p$/.exec(script || "");
|
|
293
|
+
if (!m) return null;
|
|
294
|
+
const start = Number(m[1]);
|
|
295
|
+
const end = m[2] ? Number(m[2]) : start;
|
|
296
|
+
return start >= 1 && end >= start ? [start, end] : null;
|
|
297
|
+
}
|
|
298
|
+
if (verb === "head") {
|
|
299
|
+
for (let i = 0; i < args.length; i++) {
|
|
300
|
+
const a = args[i];
|
|
301
|
+
let n = null;
|
|
302
|
+
if (a === "-n" || a === "--lines") n = args[i + 1];
|
|
303
|
+
else if (/^-n\d+$/.test(a)) n = a.slice(2);
|
|
304
|
+
else if (/^--lines=\d+$/.test(a)) n = a.split("=")[1];
|
|
305
|
+
else if (/^-\d+$/.test(a)) n = a.slice(1);
|
|
306
|
+
if (n !== null && /^\d+$/.test(n) && Number(n) >= 1) return [1, Number(n)];
|
|
307
|
+
}
|
|
308
|
+
return [1, 10];
|
|
309
|
+
}
|
|
310
|
+
return null;
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
// File arguments of a reading command: positionals that are not option values or (for sed/awk) the script.
|
|
314
|
+
function readPaths(verb, argsIn) {
|
|
315
|
+
const args = argsIn;
|
|
316
|
+
const out = [];
|
|
317
|
+
let scriptSeen = !(verb === "sed" || verb === "awk");
|
|
318
|
+
for (let i = 0; i < args.length; i++) {
|
|
319
|
+
const a = args[i];
|
|
320
|
+
if (a.startsWith("-") && a.length > 1) {
|
|
321
|
+
if ((verb === "head" || verb === "tail") && (a === "-n" || a === "-c")) i++;
|
|
322
|
+
else if ((verb === "sed" || verb === "awk") && (a === "-e" || a === "-f")) {
|
|
323
|
+
scriptSeen = true;
|
|
324
|
+
i++;
|
|
325
|
+
} else if (verb === "awk" && (a === "-F" || a === "-v")) i++;
|
|
326
|
+
else if (verb === "bat" && /^(-r|--line-range|-l|--language|--style|--theme)$/.test(a)) i++;
|
|
327
|
+
continue;
|
|
328
|
+
}
|
|
329
|
+
if (!scriptSeen) {
|
|
330
|
+
scriptSeen = true;
|
|
331
|
+
continue;
|
|
332
|
+
}
|
|
333
|
+
if (!containsSubst(a)) out.push(a);
|
|
334
|
+
}
|
|
335
|
+
return out;
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
function buildTool(verb, args) {
|
|
339
|
+
const sub = args.find((a) => !a.startsWith("-"));
|
|
340
|
+
switch (verb) {
|
|
341
|
+
case "gradle":
|
|
342
|
+
case "gradlew":
|
|
343
|
+
return "gradle";
|
|
344
|
+
case "mvn":
|
|
345
|
+
case "mvnw":
|
|
346
|
+
return "maven";
|
|
347
|
+
case "pytest":
|
|
348
|
+
case "tsc":
|
|
349
|
+
case "jest":
|
|
350
|
+
case "vitest":
|
|
351
|
+
return verb;
|
|
352
|
+
case "npm":
|
|
353
|
+
case "pnpm":
|
|
354
|
+
case "yarn":
|
|
355
|
+
case "bun":
|
|
356
|
+
if (sub === "test" || sub === "t" || (sub === "run" && /^(test|build|typecheck|lint)(:|$)/.test(args[args.indexOf("run") + 1] || ""))) return verb;
|
|
357
|
+
return null;
|
|
358
|
+
case "npx":
|
|
359
|
+
return ["jest", "vitest", "tsc", "mocha", "playwright"].includes(sub) ? sub : null;
|
|
360
|
+
case "cargo":
|
|
361
|
+
return ["test", "check", "build", "clippy"].includes(sub) ? "cargo" : null;
|
|
362
|
+
case "go":
|
|
363
|
+
return ["test", "build", "vet"].includes(sub) ? "go" : null;
|
|
364
|
+
case "bazel":
|
|
365
|
+
case "bazelisk":
|
|
366
|
+
return ["test", "build"].includes(sub) ? "bazel" : null;
|
|
367
|
+
case "dotnet":
|
|
368
|
+
return ["test", "build"].includes(sub) ? "dotnet" : null;
|
|
369
|
+
case "python":
|
|
370
|
+
case "python3":
|
|
371
|
+
return args[0] === "-m" && ["pytest", "unittest"].includes(args[1]) ? args[1] : null;
|
|
372
|
+
case "make":
|
|
373
|
+
return ["test", "check", "build"].includes(sub) || sub === undefined ? "make" : null;
|
|
374
|
+
default:
|
|
375
|
+
return null;
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
// Classifies one simple command. Returns an action or null (dropped).
|
|
380
|
+
function classify(argv, cwd) {
|
|
381
|
+
const real = realArgv(argv);
|
|
382
|
+
if (!real.length || containsSubst(real[0])) return null;
|
|
383
|
+
let verb = verbName(real[0]);
|
|
384
|
+
// Words built from $(...) are unknown at parse time: never a pattern, never a path.
|
|
385
|
+
const args = real.slice(1);
|
|
386
|
+
|
|
387
|
+
if (verb === "git" && args[0] === "grep") {
|
|
388
|
+
const { pattern, fixed, paths } = parseSearch("grep", args.slice(1));
|
|
389
|
+
return { type: "search", toolName: "git grep", pattern, fixed, paths, cwd };
|
|
390
|
+
}
|
|
391
|
+
if (SEARCH_VERBS.has(verb)) {
|
|
392
|
+
const { pattern, fixed, paths } = verb === "find" ? parseFind(args) : parseSearch(verb, args);
|
|
393
|
+
if (verb === "find" && pattern === null && !paths.length) return null;
|
|
394
|
+
return { type: "search", toolName: verb === "ripgrep" ? "rg" : verb === "fdfind" ? "fd" : verb, pattern, fixed, paths, cwd };
|
|
395
|
+
}
|
|
396
|
+
if (verb === "sed" && args.some((a) => a === "-i" || a.startsWith("-i") || a === "--in-place" || a.startsWith("--in-place="))) {
|
|
397
|
+
const files = readPaths("sed", args.filter((a) => !(a === "-i" || a.startsWith("-i") || a.startsWith("--in-place"))));
|
|
398
|
+
return files.length ? { type: "edit", toolName: "sed -i", paths: files, cwd } : null;
|
|
399
|
+
}
|
|
400
|
+
if (verb === "perl" && args.some((a) => /^-[a-z]*i/.test(a))) {
|
|
401
|
+
const files = args.filter((a, idx) => !a.startsWith("-") && idx > 0 && !/^-[a-z]*e$/.test(args[idx - 1]));
|
|
402
|
+
return files.length ? { type: "edit", toolName: "perl -i", paths: files, cwd } : null;
|
|
403
|
+
}
|
|
404
|
+
if (READ_VERBS.has(verb)) {
|
|
405
|
+
const files = readPaths(verb, args);
|
|
406
|
+
if (!files.length) return null; // reading stdin of a pipeline: nothing local was opened
|
|
407
|
+
return { type: "read", toolName: verb === "batcat" ? "bat" : verb, paths: files, lineSpan: parseLineSpanForRead(verb, args), cwd };
|
|
408
|
+
}
|
|
409
|
+
if (verb === "apply_patch") return { type: "patch", toolName: "apply_patch", cwd };
|
|
410
|
+
const build = buildTool(verb, args);
|
|
411
|
+
if (build) return { type: "build", toolName: build, cwd };
|
|
412
|
+
return null;
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
// Parses a full command line into at most MAX_ACTIONS structural actions. `cd` changes the cwd used to resolve
|
|
416
|
+
// later relative paths. Never throws.
|
|
417
|
+
export function scrubShellCommand(command, cwd) {
|
|
418
|
+
if (typeof command !== "string" || !command.trim()) return [];
|
|
419
|
+
try {
|
|
420
|
+
const actions = [];
|
|
421
|
+
let effectiveCwd = cwd;
|
|
422
|
+
for (const { argv } of splitSimpleCommands(tokenize(command))) {
|
|
423
|
+
const real = realArgv(argv);
|
|
424
|
+
if (verbName(real[0]) === "cd") {
|
|
425
|
+
const target = real[1];
|
|
426
|
+
if (target && !containsSubst(target) && target !== "-" && !target.startsWith("~")) {
|
|
427
|
+
effectiveCwd = path.resolve(effectiveCwd || "/", target);
|
|
428
|
+
}
|
|
429
|
+
continue;
|
|
430
|
+
}
|
|
431
|
+
const action = classify(argv, effectiveCwd);
|
|
432
|
+
if (action) actions.push(action);
|
|
433
|
+
if (actions.length >= MAX_ACTIONS) break;
|
|
434
|
+
}
|
|
435
|
+
return actions;
|
|
436
|
+
} catch {
|
|
437
|
+
return [];
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
// Files named in an apply_patch body (Codex). Only the header lines are read; hunks are never kept.
|
|
442
|
+
export function patchTargetPaths(patchText) {
|
|
443
|
+
if (typeof patchText !== "string") return [];
|
|
444
|
+
const out = [];
|
|
445
|
+
const re = /^\*\*\* (?:Update File|Add File|Delete File|Move to): (.+?)\s*$/gm;
|
|
446
|
+
let m;
|
|
447
|
+
while ((m = re.exec(patchText)) && out.length < 50) out.push(m[1]);
|
|
448
|
+
return [...new Set(out)];
|
|
449
|
+
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
// Sends spooled tool events (RSI MCP spec §5.5, wire contract §3.5). Used by hook-event (one batch after a
|
|
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";
|
|
4
|
+
import { batchBodies, postToolEvents } from "./toolEventsClient.js";
|
|
5
|
+
|
|
6
|
+
// opts:
|
|
7
|
+
// endpoint only records bound to this backend are sent; others are put back untouched
|
|
8
|
+
// getToken(wsId) bearer token or null
|
|
9
|
+
// getKey() key bytes or null; getKey({ refresh: true }) after a 401 may fetch a new key
|
|
10
|
+
// maxBatches cap on requests this drain makes
|
|
11
|
+
// deadlineAt epoch ms after which nothing new is sent
|
|
12
|
+
// timeoutMs per request
|
|
13
|
+
// log(msg)
|
|
14
|
+
// Returns { sent, dropped, requeued }.
|
|
15
|
+
export async function drainSpool({ endpoint, getToken, getKey, maxBatches = 10, deadlineAt = Infinity, timeoutMs = 450, log = () => {}, fetchImpl }) {
|
|
16
|
+
const result = { sent: 0, dropped: 0, requeued: 0 };
|
|
17
|
+
let batches = 0;
|
|
18
|
+
let key = await getKey({ refresh: false });
|
|
19
|
+
if (!key) return result;
|
|
20
|
+
for (const file of listSpoolFiles()) {
|
|
21
|
+
if (batches >= maxBatches || Date.now() >= deadlineAt) break;
|
|
22
|
+
const records = claimSpool(file);
|
|
23
|
+
if (!records.length) continue;
|
|
24
|
+
const mine = records.filter((r) => r.endpoint === endpoint);
|
|
25
|
+
const leftover = records.filter((r) => r.endpoint !== endpoint);
|
|
26
|
+
const byWs = new Map();
|
|
27
|
+
for (const r of mine) {
|
|
28
|
+
if (!byWs.has(r.workspaceId)) byWs.set(r.workspaceId, []);
|
|
29
|
+
byWs.get(r.workspaceId).push(r);
|
|
30
|
+
}
|
|
31
|
+
for (const [workspaceId, recs] of byWs) {
|
|
32
|
+
const token = await getToken(workspaceId);
|
|
33
|
+
if (!token) {
|
|
34
|
+
leftover.push(...recs);
|
|
35
|
+
continue;
|
|
36
|
+
}
|
|
37
|
+
const bodies = batchBodies(recs.map((r) => r.event), DRAIN_BATCH_SIZE);
|
|
38
|
+
let idx = 0;
|
|
39
|
+
for (; idx < bodies.length; idx++) {
|
|
40
|
+
if (batches >= maxBatches || Date.now() >= deadlineAt) break;
|
|
41
|
+
const { events, body } = bodies[idx];
|
|
42
|
+
batches++;
|
|
43
|
+
let res = await postToolEvents({ endpoint, workspaceId, body, token, key, timeoutMs, fetchImpl });
|
|
44
|
+
if (res.outcome === "unauthorized") {
|
|
45
|
+
// Wire contract §3.5: re-fetch the key once, retry once, then drop.
|
|
46
|
+
const fresh = await getKey({ refresh: true });
|
|
47
|
+
if (fresh) {
|
|
48
|
+
key = fresh;
|
|
49
|
+
res = await postToolEvents({ endpoint, workspaceId, body, token, key, timeoutMs, fetchImpl });
|
|
50
|
+
}
|
|
51
|
+
if (res.outcome === "unauthorized") res = { ...res, outcome: fresh ? "drop" : "retry" };
|
|
52
|
+
}
|
|
53
|
+
if (res.outcome === "accepted") result.sent += events.length;
|
|
54
|
+
else if (res.outcome === "drop") {
|
|
55
|
+
result.dropped += events.length;
|
|
56
|
+
log(`[rsi] dropped ${events.length} spooled tool events for workspace ${workspaceId}: HTTP ${res.status}`);
|
|
57
|
+
} else {
|
|
58
|
+
leftover.push(...events.map((event) => ({ endpoint, workspaceId, event })));
|
|
59
|
+
// Backend unreachable: stop here, keep the rest for next time.
|
|
60
|
+
for (const rest of bodies.slice(idx + 1)) leftover.push(...rest.events.map((event) => ({ endpoint, workspaceId, event })));
|
|
61
|
+
idx = bodies.length;
|
|
62
|
+
break;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
for (const rest of bodies.slice(idx)) leftover.push(...rest.events.map((event) => ({ endpoint, workspaceId, event })));
|
|
66
|
+
}
|
|
67
|
+
if (leftover.length) {
|
|
68
|
+
requeue(leftover);
|
|
69
|
+
result.requeued += leftover.length;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
return result;
|
|
73
|
+
}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
// POST /api/code-workspace/{workspaceId}/rsi/tool-events (RSI wire contract §3) plus the no-network token lookup
|
|
2
|
+
// hook processes use. Kept free of the server's heavier modules (OTel, MCP SDK) so a hook starts fast.
|
|
3
|
+
import fs from "fs";
|
|
4
|
+
import os from "os";
|
|
5
|
+
import path from "path";
|
|
6
|
+
|
|
7
|
+
import { signBatch } from "./hmacSigner.js";
|
|
8
|
+
|
|
9
|
+
export const MAX_BODY_BYTES = 64 * 1024;
|
|
10
|
+
|
|
11
|
+
// The user-login token deviceAuth.js stored, if still valid. Never the workspace token: the backend resolves a
|
|
12
|
+
// workspace token to the workspace id (and org 1), not to the user, while telemetry keys are per (org, user) — so
|
|
13
|
+
// events sent with it would be checked against the wrong key and filed under the wrong org. A hook has no time to
|
|
14
|
+
// refresh an expired login, so "no token" means: spool, and let `serve` (which can refresh) send it later.
|
|
15
|
+
export function cachedUserToken() {
|
|
16
|
+
if (process.env.AUTH_ACCESS_TOKEN) return process.env.AUTH_ACCESS_TOKEN;
|
|
17
|
+
try {
|
|
18
|
+
const s = JSON.parse(fs.readFileSync(path.join(os.homedir(), ".harmony-mcp", "session.json"), "utf8"));
|
|
19
|
+
if (s?.accessToken && s.expiresAt > Math.floor(Date.now() / 1000) + 30) return s.accessToken;
|
|
20
|
+
} catch {
|
|
21
|
+
// no session
|
|
22
|
+
}
|
|
23
|
+
return null;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// Splits events into request bodies of ≤ 50 events and ≤ 64 KiB.
|
|
27
|
+
export function batchBodies(events, maxEvents = 50) {
|
|
28
|
+
const bodies = [];
|
|
29
|
+
let current = [];
|
|
30
|
+
const bodyOf = (evs) => JSON.stringify({ schemaVersion: 1, events: evs });
|
|
31
|
+
for (const event of events) {
|
|
32
|
+
const next = [...current, event];
|
|
33
|
+
if (next.length > maxEvents || Buffer.byteLength(bodyOf(next)) > MAX_BODY_BYTES) {
|
|
34
|
+
if (current.length) bodies.push({ events: current, body: bodyOf(current) });
|
|
35
|
+
current = Buffer.byteLength(bodyOf([event])) > MAX_BODY_BYTES ? [] : [event];
|
|
36
|
+
} else {
|
|
37
|
+
current = next;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
if (current.length) bodies.push({ events: current, body: bodyOf(current) });
|
|
41
|
+
return bodies;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// Outcome per wire contract §3.5:
|
|
45
|
+
// "accepted" 202
|
|
46
|
+
// "unauthorized" 401 (caller may re-fetch the key once and retry)
|
|
47
|
+
// "retry" 5xx, 503, timeout, network error -> spool
|
|
48
|
+
// "drop" other 4xx -> final
|
|
49
|
+
export async function postToolEvents({ endpoint, workspaceId, body, token, key, timeoutMs, fetchImpl = fetch }) {
|
|
50
|
+
try {
|
|
51
|
+
const response = await fetchImpl(`${endpoint}/api/code-workspace/${encodeURIComponent(workspaceId)}/rsi/tool-events`, {
|
|
52
|
+
method: "POST",
|
|
53
|
+
headers: {
|
|
54
|
+
"Content-Type": "application/json",
|
|
55
|
+
Authorization: `Bearer ${token}`,
|
|
56
|
+
...signBatch(key, body),
|
|
57
|
+
},
|
|
58
|
+
body,
|
|
59
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
60
|
+
});
|
|
61
|
+
// Drain the body so the socket can close promptly.
|
|
62
|
+
await response.arrayBuffer().catch(() => {});
|
|
63
|
+
if (response.status === 202 || response.status === 200) return { outcome: "accepted", status: response.status };
|
|
64
|
+
if (response.status === 401) return { outcome: "unauthorized", status: 401 };
|
|
65
|
+
if (response.status >= 500) return { outcome: "retry", status: response.status };
|
|
66
|
+
return { outcome: "drop", status: response.status };
|
|
67
|
+
} catch (error) {
|
|
68
|
+
return { outcome: "retry", status: null, error: error?.name === "TimeoutError" ? "timeout" : error?.message };
|
|
69
|
+
}
|
|
70
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
// ~/.harmony/ local state (RSI MCP spec §2.2): owner-only directories (0700) and files (0600), written
|
|
2
|
+
// atomically (temp file -> fsync -> rename) so a crash never leaves a half-written file for another process.
|
|
3
|
+
import fs from "fs";
|
|
4
|
+
import os from "os";
|
|
5
|
+
import path from "path";
|
|
6
|
+
import crypto from "crypto";
|
|
7
|
+
|
|
8
|
+
// HARMONY_HOME overrides the root (tests, sandboxed agents).
|
|
9
|
+
export function harmonyHome() {
|
|
10
|
+
return process.env.HARMONY_HOME || path.join(os.homedir(), ".harmony");
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export function harmonyPath(...parts) {
|
|
14
|
+
return path.join(harmonyHome(), ...parts);
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
// Creates the directory (and parents) owner-only. chmod as well, since mkdir's mode is masked by umask and is
|
|
18
|
+
// not applied to directories that already exist.
|
|
19
|
+
export function ensurePrivateDir(dir) {
|
|
20
|
+
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
21
|
+
try {
|
|
22
|
+
fs.chmodSync(dir, 0o700);
|
|
23
|
+
} catch {
|
|
24
|
+
// not ours to change (e.g. Windows); best effort
|
|
25
|
+
}
|
|
26
|
+
return dir;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function atomicWriteFile(file, data, mode = 0o600) {
|
|
30
|
+
ensurePrivateDir(path.dirname(file));
|
|
31
|
+
const tmp = `${file}.${process.pid}.${crypto.randomBytes(4).toString("hex")}.tmp`;
|
|
32
|
+
const fd = fs.openSync(tmp, "w", mode);
|
|
33
|
+
try {
|
|
34
|
+
fs.writeSync(fd, data);
|
|
35
|
+
fs.fsyncSync(fd);
|
|
36
|
+
} finally {
|
|
37
|
+
fs.closeSync(fd);
|
|
38
|
+
}
|
|
39
|
+
try {
|
|
40
|
+
fs.renameSync(tmp, file);
|
|
41
|
+
} catch (error) {
|
|
42
|
+
fs.rmSync(tmp, { force: true });
|
|
43
|
+
throw error;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function readJsonFile(file) {
|
|
48
|
+
try {
|
|
49
|
+
return JSON.parse(fs.readFileSync(file, "utf8"));
|
|
50
|
+
} catch {
|
|
51
|
+
return null;
|
|
52
|
+
}
|
|
53
|
+
}
|