@codeconductorai/harmony-mcp 1.0.33 → 1.0.35

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/README.md +217 -15
  2. package/package.json +4 -2
  3. package/src/{deviceAuth.js → auth/deviceAuth.js} +39 -8
  4. package/src/{harmonyClient.js → backend/harmonyClient.js} +183 -13
  5. package/src/doctor/doctorCommand.js +385 -0
  6. package/src/index.js +18 -5
  7. package/src/{telemetry.js → observability/telemetry.js} +3 -3
  8. package/src/rsi/bundleHints.js +181 -0
  9. package/src/rsi/bundleRefresher.js +95 -0
  10. package/src/rsi/callContext.js +49 -0
  11. package/src/rsi/causalState.js +103 -0
  12. package/src/rsi/clientAgent.js +58 -0
  13. package/src/rsi/hooks/eventBuilder.js +129 -0
  14. package/src/rsi/hooks/fileHash.js +33 -0
  15. package/src/rsi/hooks/hmacSigner.js +69 -0
  16. package/src/rsi/hooks/hookEventCommand.js +196 -0
  17. package/src/rsi/hooks/normalizers.js +329 -0
  18. package/src/rsi/hooks/offlineSpooler.js +142 -0
  19. package/src/rsi/hooks/secretScrubber.js +50 -0
  20. package/src/rsi/hooks/shellCommandScrubber.js +449 -0
  21. package/src/rsi/hooks/spoolDrainer.js +78 -0
  22. package/src/rsi/hooks/toolEventsClient.js +70 -0
  23. package/src/rsi/localState.js +53 -0
  24. package/src/rsi/serveTelemetry.js +101 -0
  25. package/src/rsi/workspaceRegistry.js +63 -0
  26. package/src/{server.js → server/server.js} +107 -17
  27. package/src/{serverInstructions.js → server/serverInstructions.js} +2 -2
  28. package/src/server/serverMain.js +46 -0
  29. package/src/{sessionIdentity.js → session/sessionIdentity.js} +10 -6
  30. package/src/setup/agentCapabilityMatrix.js +425 -0
  31. package/src/setup/agentsGuide.js +28 -0
  32. package/src/setup/configMergers.js +272 -0
  33. package/src/{installer.js → setup/installer.js} +1 -1
  34. package/src/setup/setupAgentsCommand.js +192 -0
  35. package/src/setup/shim.js +80 -0
  36. package/src/sync/managedMarkdownInjector.js +103 -0
  37. package/src/sync/syncWorkspaceCommand.js +143 -0
  38. package/src/sync/workspaceSync.js +88 -0
  39. package/src/{fileWatcher.js → workspace/fileWatcher.js} +2 -2
  40. package/src/{workspaceIdentity.js → workspace/workspaceIdentity.js} +1 -1
  41. package/src/agentsGuide.js +0 -38
  42. package/src/serverMain.js +0 -32
  43. /package/src/{log.js → observability/log.js} +0 -0
  44. /package/src/{toolSchemas.js → server/toolSchemas.js} +0 -0
  45. /package/src/{fileFilters.js → workspace/fileFilters.js} +0 -0
  46. /package/src/{repoIdentity.js → workspace/repoIdentity.js} +0 -0
  47. /package/src/{workspaceMarker.js → workspace/workspaceMarker.js} +0 -0
@@ -0,0 +1,142 @@
1
+ // Bounded offline spool for tool events (RSI MCP spec §5.5): ~/.harmony/spool/ws-{workspaceId}-events.jsonl.
2
+ //
3
+ // Each line is { endpoint, workspaceId, event } — unsigned; batches are signed when sent (wire contract §3.2.6).
4
+ // Appends are single small O_APPEND writes, safe across concurrent hook processes. Over 2 MiB the oldest 25% of
5
+ // lines are dropped. A drain claims the file by renaming it, so appends that race the drain land in a fresh file.
6
+ // The claimed file stays on disk until the drain has sent or requeued its events: if the process is killed mid-drain
7
+ // (an agent closing its MCP server), the next drain picks the orphaned file up again. The backend deduplicates
8
+ // events by clientEventId, so a batch sent just before the kill is never counted twice.
9
+ import fs from "fs";
10
+ import path from "path";
11
+
12
+ import { atomicWriteFile, ensurePrivateDir, harmonyPath } from "../localState.js";
13
+
14
+ export const SPOOL_MAX_BYTES = 2 * 1024 * 1024;
15
+ export const DRAIN_BATCH_SIZE = 50;
16
+
17
+ export function spoolDir() {
18
+ return harmonyPath("spool");
19
+ }
20
+
21
+ export function spoolPath(workspaceId) {
22
+ const safe = String(workspaceId).replace(/[^A-Za-z0-9_-]/g, "_");
23
+ return path.join(spoolDir(), `ws-${safe}-events.jsonl`);
24
+ }
25
+
26
+ // Drops the oldest 25% of lines, repeatedly, until the file is back under the cap (one big append can need more
27
+ // than one round).
28
+ function trimOldest(file) {
29
+ let lines = fs.readFileSync(file, "utf8").split("\n").filter(Boolean);
30
+ let size = Buffer.byteLength(lines.join("\n")) + 1;
31
+ while (lines.length && size > SPOOL_MAX_BYTES) {
32
+ lines = lines.slice(Math.ceil(lines.length * 0.25));
33
+ size = Buffer.byteLength(lines.join("\n")) + 1;
34
+ }
35
+ atomicWriteFile(file, lines.length ? `${lines.join("\n")}\n` : "");
36
+ }
37
+
38
+ export function spoolEvents(endpoint, workspaceId, events) {
39
+ if (!events.length) return;
40
+ ensurePrivateDir(spoolDir());
41
+ const file = spoolPath(workspaceId);
42
+ const data = events.map((event) => JSON.stringify({ endpoint, workspaceId: String(workspaceId), event })).join("\n") + "\n";
43
+ const fd = fs.openSync(file, "a", 0o600);
44
+ try {
45
+ fs.writeSync(fd, data);
46
+ } finally {
47
+ fs.closeSync(fd);
48
+ }
49
+ if (fs.statSync(file).size > SPOOL_MAX_BYTES) trimOldest(file);
50
+ }
51
+
52
+ const SPOOL_NAME = /^ws-[A-Za-z0-9_-]+-events\.jsonl$/;
53
+ const CLAIMED_NAME = /^ws-[A-Za-z0-9_-]+-events\.jsonl\.draining-(\d+)-(\d+)$/;
54
+ // A claim older than this is taken over even if its pid is alive again (pid reuse).
55
+ const STALE_CLAIM_MS = 10 * 60_000;
56
+
57
+ function pidAlive(pid) {
58
+ try {
59
+ process.kill(pid, 0);
60
+ return true;
61
+ } catch (error) {
62
+ return error?.code === "EPERM";
63
+ }
64
+ }
65
+
66
+ // A claimed file whose drain is gone: its process exited, or the claim is too old to still be in progress.
67
+ function isOrphanedClaim(name, now = Date.now()) {
68
+ const m = CLAIMED_NAME.exec(name);
69
+ if (!m) return false;
70
+ const pid = Number(m[1]);
71
+ return pid !== process.pid && (!pidAlive(pid) || now - Number(m[2]) > STALE_CLAIM_MS);
72
+ }
73
+
74
+ // Spool files to send: live spools plus claims orphaned by a drain that never finished.
75
+ export function listSpoolFiles() {
76
+ try {
77
+ return fs
78
+ .readdirSync(spoolDir())
79
+ .filter((n) => SPOOL_NAME.test(n) || isOrphanedClaim(n))
80
+ .map((n) => path.join(spoolDir(), n));
81
+ } catch {
82
+ return [];
83
+ }
84
+ }
85
+
86
+ export function spoolBacklog() {
87
+ let count = 0;
88
+ for (const file of listSpoolFiles()) {
89
+ try {
90
+ count += fs.readFileSync(file, "utf8").split("\n").filter(Boolean).length;
91
+ } catch {
92
+ // ignore
93
+ }
94
+ }
95
+ return count;
96
+ }
97
+
98
+ // Takes all lines out of a spool file by renaming it to a claim. Returns { records, claimed }; records is [] if
99
+ // another process claimed it first. The caller must call releaseClaim(claimed) once every record is sent or requeued.
100
+ export function claimSpool(file) {
101
+ const base = file.replace(/\.draining-\d+-\d+$/, "");
102
+ const claimed = `${base}.draining-${process.pid}-${Date.now()}`;
103
+ try {
104
+ fs.renameSync(file, claimed);
105
+ } catch {
106
+ return { records: [], claimed: null };
107
+ }
108
+ let records = [];
109
+ try {
110
+ records = fs
111
+ .readFileSync(claimed, "utf8")
112
+ .split("\n")
113
+ .filter(Boolean)
114
+ .map((line) => {
115
+ try {
116
+ return JSON.parse(line);
117
+ } catch {
118
+ return null;
119
+ }
120
+ })
121
+ .filter((rec) => rec?.event && rec.endpoint && rec.workspaceId);
122
+ } catch {
123
+ // unreadable right now: keep the claim on disk, a later drain picks it up as orphaned
124
+ return { records: [], claimed: null };
125
+ }
126
+ return { records, claimed };
127
+ }
128
+
129
+ export function releaseClaim(claimed) {
130
+ if (claimed) fs.rmSync(claimed, { force: true });
131
+ }
132
+
133
+ // Puts records that were not sent back into their spool.
134
+ export function requeue(records) {
135
+ const byWorkspace = new Map();
136
+ for (const rec of records) {
137
+ const key = `${rec.workspaceId}\u0000${rec.endpoint}`;
138
+ if (!byWorkspace.has(key)) byWorkspace.set(key, { endpoint: rec.endpoint, workspaceId: rec.workspaceId, events: [] });
139
+ byWorkspace.get(key).events.push(rec.event);
140
+ }
141
+ for (const { endpoint, workspaceId, events } of byWorkspace.values()) spoolEvents(endpoint, workspaceId, events);
142
+ }
@@ -0,0 +1,50 @@
1
+ // Client-side secret detection for anything a hook might send (RSI MCP spec §5.3, §9.2). Conservative by design:
2
+ // a false positive only costs a redacted search hint, a false negative leaks a secret.
3
+
4
+ const SECRET_PATTERNS = [
5
+ /\bsk-[A-Za-z0-9_-]{8,}/, // OpenAI / Anthropic style
6
+ /\b(?:sk|rk|pk)_(?:live|test)_[A-Za-z0-9]{8,}/, // Stripe
7
+ /\b(?:AKIA|ASIA|AGPA|AIDA|AROA)[0-9A-Z]{12,}/, // AWS access key ids
8
+ /\bgh[pousr]_[A-Za-z0-9]{16,}/, // GitHub tokens
9
+ /\bgithub_pat_[A-Za-z0-9_]{16,}/,
10
+ /\bglpat-[A-Za-z0-9_-]{12,}/, // GitLab
11
+ /\bxox[abposr]-[A-Za-z0-9-]{8,}/, // Slack
12
+ /\bAIza[0-9A-Za-z_-]{20,}/, // Google API keys
13
+ /\beyJ[A-Za-z0-9_-]{8,}\.?/, // JWT / base64 JSON
14
+ /-----BEGIN [A-Z ]*PRIVATE KEY/,
15
+ /[a-z][a-z0-9+.-]*:\/\/[^\s/:@]+:[^\s/@]+@/i, // URL with user:password
16
+ /\b(?:bearer|basic)\s+[A-Za-z0-9._~+/=-]{12,}/i,
17
+ /\b[A-Za-z_][A-Za-z0-9_]*\s*=\s*['"]?[^\s'"=]{4,}/, // KEY=VAL assignments (not ==)
18
+ ];
19
+
20
+ const ENTROPY_THRESHOLD_BITS = 4.2;
21
+ const ENTROPY_MIN_LENGTH = 16;
22
+
23
+ export function shannonEntropy(text) {
24
+ if (!text) return 0;
25
+ const counts = new Map();
26
+ for (const ch of text) counts.set(ch, (counts.get(ch) || 0) + 1);
27
+ let bits = 0;
28
+ const n = text.length;
29
+ for (const count of counts.values()) {
30
+ const p = count / n;
31
+ bits -= p * Math.log2(p);
32
+ }
33
+ return bits;
34
+ }
35
+
36
+ function highEntropy(text) {
37
+ return text.length >= ENTROPY_MIN_LENGTH && shannonEntropy(text) > ENTROPY_THRESHOLD_BITS;
38
+ }
39
+
40
+ // True when the text contains, or is, something that looks like a credential.
41
+ export function looksSecret(text) {
42
+ if (typeof text !== "string" || !text) return false;
43
+ if (SECRET_PATTERNS.some((pattern) => pattern.test(text))) return true;
44
+ if (highEntropy(text)) return true;
45
+ // A secret embedded in a longer pattern or path: check each long token on its own.
46
+ for (const token of text.split(/[^A-Za-z0-9+/=_-]+/)) {
47
+ if (highEntropy(token)) return true;
48
+ }
49
+ return false;
50
+ }
@@ -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
+ }