pi-braid 0.44.5 → 0.45.0

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.
@@ -0,0 +1,503 @@
1
+ /**
2
+ * The execution core of the `run` tool: one program and its argv, no shell.
3
+ *
4
+ * What this module refuses is what a shell would have interpreted:
5
+ * - the five operators that make a command string a program (`|`, `&&`, `;`,
6
+ * a backtick, `$(`);
7
+ * - a shell invoked with a command string (`sh -c ...`), which is the same
8
+ * thing in a different spelling;
9
+ * - a glob at a path-segment boundary (`*.md`, `src/*`), because the caller
10
+ * passed an expression where a program expects a path.
11
+ * A `*` inside an argument (a sed quantifier, a grep `--include` filter) is
12
+ * not a boundary and is left to the program, which is where such a pattern
13
+ * belongs.
14
+ *
15
+ * What it does not do is as load-bearing: no TTY, no shell profile, no glob
16
+ * expansion, no environment invention. The child gets the caller's environment,
17
+ * a stdin that ends (or the text the caller supplied), and stdout/stderr to
18
+ * files so the bytes are exact and the memory is bounded. Both streams are
19
+ * returned separately; each is capped, and the dropped bytes and the file that
20
+ * holds the rest are named rather than dropped silently.
21
+ */
22
+
23
+ import { spawn } from "node:child_process";
24
+ import type { ChildProcess } from "node:child_process";
25
+ import { closeSync, mkdtempSync, openSync, readSync, rmSync, statSync } from "node:fs";
26
+ import { tmpdir } from "node:os";
27
+ import { basename, join, resolve } from "node:path";
28
+ import { DEFAULT_MAX_BYTES } from "@earendil-works/pi-coding-agent";
29
+ import { findWorkspaceEscape } from "../../../lib/tools/workspace-guard.js";
30
+
31
+ /** setTimeout's own ceiling: a longer timeout cannot be armed. */
32
+ export const MAX_TIMEOUT_MS = 2_147_483_647;
33
+
34
+ /** The smallest cap worth reporting a window for. */
35
+ export const MIN_OUTPUT_BYTES = 1_024;
36
+
37
+ /** A cap past the harness's own structured-output budget buys nothing. */
38
+ export const MAX_OUTPUT_BYTES = 1_048_576;
39
+
40
+ /** Per stream, when the call names no cap: the harness's truncation default. */
41
+ export const DEFAULT_OUTPUT_BYTES = DEFAULT_MAX_BYTES;
42
+
43
+ /**
44
+ * Verbs whose operand is destroyed or rewritten. The set is this tool's policy,
45
+ * not the guard's: `git` will bring its own.
46
+ */
47
+ export const DESTRUCTIVE_VERBS: ReadonlySet<string> = new Set([
48
+ "rm",
49
+ "mv",
50
+ "dd",
51
+ "chmod",
52
+ "shred",
53
+ "truncate",
54
+ ]);
55
+
56
+ /** Programs that take a command string: `-c` makes one of them a shell again. */
57
+ const SHELL_PROGRAMS: ReadonlySet<string> = new Set(["sh", "bash", "zsh", "dash", "ksh", "fish"]);
58
+
59
+ /** Shell operators that only mean something inside a shell. */
60
+ const SHELL_OPERATORS = ["&&", "$(", "|", ";", "`"] as const;
61
+
62
+ /** Longest argument quoted back in a refusal, so the message stays readable. */
63
+ const MAX_QUOTED_ARGUMENT = 160;
64
+
65
+ /** How far past a byte budget a read looks for a line boundary. */
66
+ const LINE_WINDOW_SLACK = 8 * 1024;
67
+
68
+ /** Share of the cap kept from the head; the tail keeps the rest. */
69
+ const HEAD_SHARE = 0.6;
70
+
71
+ /** A validated `run` call. */
72
+ export interface RunRequest {
73
+ argv: string[];
74
+ cwd?: string;
75
+ env?: Record<string, string>;
76
+ stdin?: string;
77
+ timeout_ms: number;
78
+ max_output_bytes?: number;
79
+ }
80
+
81
+ /** Why a call never reached a program. */
82
+ export interface RunRefusal {
83
+ kind:
84
+ | "argv"
85
+ | "metacharacter"
86
+ | "shell-string"
87
+ | "glob"
88
+ | "timeout"
89
+ | "output-cap"
90
+ | "cwd"
91
+ | "destructive-escape";
92
+ message: string;
93
+ }
94
+
95
+ /** One stream after the cap was applied. */
96
+ export interface RunStream {
97
+ /** What the result text shows. */
98
+ text: string;
99
+ /** Bytes the program wrote to this stream. */
100
+ bytes: number;
101
+ /** Bytes the text shows, before the omission marker. */
102
+ shownBytes: number;
103
+ /** Bytes the text does not show. */
104
+ droppedBytes: number;
105
+ /** Whether the cap applied. */
106
+ truncated: boolean;
107
+ /** The file holding the full stream; present when `truncated`. */
108
+ fullTextPath?: string;
109
+ }
110
+
111
+ /** What one call captured, before the cap is applied to either stream. */
112
+ export interface RunCapture {
113
+ exitCode: number | null;
114
+ signal: string | null;
115
+ timedOut: boolean;
116
+ aborted: boolean;
117
+ durationMs: number;
118
+ cwd: string;
119
+ argv: string[];
120
+ /** Present when the child could not be spawned at all. */
121
+ spawnError?: string;
122
+ /** Full stdout, in a file this call owns. */
123
+ stdoutPath: string;
124
+ /** Full stderr, in a file this call owns. */
125
+ stderrPath: string;
126
+ stdoutBytes: number;
127
+ stderrBytes: number;
128
+ /** The capture directory, removed by `discardCapture`. */
129
+ captureDir?: string;
130
+ }
131
+
132
+ /** Where a call runs, and what bounds its destructive verbs. */
133
+ export interface RunContext {
134
+ /** Absolute directory the program runs in. */
135
+ cwd: string;
136
+ /** Boundary for the destructive guard. */
137
+ workspaceRoot: string;
138
+ }
139
+
140
+ function quote(text: string): string {
141
+ return text.length > MAX_QUOTED_ARGUMENT ? `${text.slice(0, MAX_QUOTED_ARGUMENT)}...` : text;
142
+ }
143
+
144
+ /**
145
+ * A `*` at a path-segment boundary: the whole element, a leading `*.ext`, a
146
+ * trailing directory wildcard, or a wildcard between two segments. A star
147
+ * inside a word or a pattern is the program's business.
148
+ */
149
+ export function isGlobExpression(element: string): boolean {
150
+ if (!element.includes("*")) return false;
151
+ return element.startsWith("*") || element.endsWith("*") || element.includes("/*");
152
+ }
153
+
154
+ /** The first element carrying a shell operator, or null. */
155
+ function findShellOperator(argv: readonly string[]): {
156
+ index: number;
157
+ operator: string;
158
+ } | null {
159
+ for (let index = 0; index < argv.length; index++) {
160
+ const element = argv[index];
161
+ for (const operator of SHELL_OPERATORS) {
162
+ if (element.includes(operator)) return { index, operator };
163
+ }
164
+ }
165
+ return null;
166
+ }
167
+
168
+ /** Whether a shell program is being handed a command string. */
169
+ function isShellCommandString(argv: readonly string[]): boolean {
170
+ if (!SHELL_PROGRAMS.has(basename(argv[0] ?? ""))) return false;
171
+ return argv.slice(1).some((element) => {
172
+ if (element === "--command") return true;
173
+ // A short-flag cluster: -c, -ec, -lc. A long flag (--login) is not one.
174
+ return /^-[A-Za-z]*c[A-Za-z]*$/.test(element);
175
+ });
176
+ }
177
+
178
+ /**
179
+ * Everything wrong with a call that can be known before a process starts: the
180
+ * argv shape, shell operators, a shell command string, a glob, the timeout, the
181
+ * cap, and a destructive verb reaching outside the workspace.
182
+ *
183
+ * Pure. The cwd is already resolved and its existence checked by the caller;
184
+ * the workspace boundary is passed in.
185
+ */
186
+ export function findRefusal(request: RunRequest, context: RunContext): RunRefusal | null {
187
+ const { argv } = request;
188
+ if (!Array.isArray(argv) || argv.length === 0) {
189
+ return {
190
+ kind: "argv",
191
+ message:
192
+ "refused: argv is required and must be non-empty. Pass the program as argv[0] and one element per argument.",
193
+ };
194
+ }
195
+ if (argv.some((element) => typeof element !== "string" || element === "")) {
196
+ return {
197
+ kind: "argv",
198
+ message:
199
+ "refused: every argv element must be a non-empty string. An empty element cannot be passed to a program.",
200
+ };
201
+ }
202
+
203
+ const operator = findShellOperator(argv);
204
+ if (operator) {
205
+ return {
206
+ kind: "metacharacter",
207
+ message:
208
+ `refused: argv[${operator.index}] carries "${operator.operator}". ` +
209
+ "run executes argv directly and never through a shell, so the operator would be a literal argument. " +
210
+ `Argument: ${quote(argv[operator.index])}`,
211
+ };
212
+ }
213
+
214
+ if (isShellCommandString(argv)) {
215
+ return {
216
+ kind: "shell-string",
217
+ message:
218
+ "refused: argv[0] is a shell and argv carries -c, so this is a command string rather than a program call. " +
219
+ "run does not hand commands to a shell. Use bash, or pass the program and its arguments directly.",
220
+ };
221
+ }
222
+
223
+ const glob = argv.slice(1).find(isGlobExpression);
224
+ if (glob !== undefined) {
225
+ return {
226
+ kind: "glob",
227
+ message:
228
+ `refused: "${quote(glob)}" is a glob, and run does not expand globs. ` +
229
+ "Pass the paths the glob would have matched, or use find or grep, which take patterns themselves.",
230
+ };
231
+ }
232
+
233
+ const timeout = request.timeout_ms;
234
+ if (typeof timeout !== "number" || !Number.isFinite(timeout)) {
235
+ return {
236
+ kind: "timeout",
237
+ message:
238
+ "refused: timeout_ms is required and must be a finite number of milliseconds. " +
239
+ "A call with no timeout can hang the session.",
240
+ };
241
+ }
242
+ if (!Number.isInteger(timeout) || timeout < 1 || timeout > MAX_TIMEOUT_MS) {
243
+ return {
244
+ kind: "timeout",
245
+ message:
246
+ `refused: timeout_ms must be an integer from 1 to ${MAX_TIMEOUT_MS}; got ${timeout}. ` +
247
+ "A call with no timeout can hang the session.",
248
+ };
249
+ }
250
+
251
+ if (request.max_output_bytes !== undefined) {
252
+ const cap = request.max_output_bytes;
253
+ if (!Number.isInteger(cap) || cap < MIN_OUTPUT_BYTES || cap > MAX_OUTPUT_BYTES) {
254
+ return {
255
+ kind: "output-cap",
256
+ message: `refused: max_output_bytes must be an integer from ${MIN_OUTPUT_BYTES} to ${MAX_OUTPUT_BYTES}; got ${String(cap)}.`,
257
+ };
258
+ }
259
+ }
260
+
261
+ const escape = findWorkspaceEscape({
262
+ verbs: DESTRUCTIVE_VERBS,
263
+ argv,
264
+ cwd: context.cwd,
265
+ workspaceRoot: context.workspaceRoot,
266
+ });
267
+ if (escape) {
268
+ return {
269
+ kind: "destructive-escape",
270
+ message:
271
+ `refused: "${escape.verb}" names "${escape.path}", which resolves to ${escape.resolved}, ` +
272
+ `outside the workspace ${escape.root}. A destructive verb is refused when a path argument leaves the workspace; use bash if that is intended.`,
273
+ };
274
+ }
275
+
276
+ return null;
277
+ }
278
+
279
+ function statSize(file: string): number {
280
+ try {
281
+ return statSync(file).size;
282
+ } catch {
283
+ // The capture file is created by this call and read after the child exits;
284
+ // a vanished file reads as empty output rather than failing the result.
285
+ return 0;
286
+ }
287
+ }
288
+
289
+ /** Read into `buffer` from `fd`, closing the descriptor whatever happens. */
290
+ function readFrom(fd: number, buffer: Buffer, length: number, position: number): number {
291
+ try {
292
+ return readSync(fd, buffer, 0, length, position);
293
+ } finally {
294
+ closeSync(fd);
295
+ }
296
+ }
297
+
298
+ /** Read the first `budget` bytes of a file, cut at a line boundary. */
299
+ function readHead(file: string, budget: number): string {
300
+ const window = Math.min(Math.max(budget, 1) + LINE_WINDOW_SLACK, Math.max(statSize(file), 1));
301
+ const buffer = Buffer.allocUnsafe(window);
302
+ const read = readFrom(openSync(file, "r"), buffer, window, 0);
303
+ const slice = buffer.subarray(0, read);
304
+ const newline = slice.lastIndexOf(0x0a);
305
+ const end = newline >= 0 && newline <= budget ? newline + 1 : Math.min(budget, read);
306
+ return stripSplitCharacter(slice.subarray(0, end).toString("utf8"), "end");
307
+ }
308
+
309
+ /** Read the last `budget` bytes of a file, cut at a line boundary. */
310
+ function readTail(file: string, budget: number): string {
311
+ const size = statSize(file);
312
+ const start = Math.max(0, size - budget - LINE_WINDOW_SLACK);
313
+ const length = size - start;
314
+ const buffer = Buffer.allocUnsafe(length);
315
+ const read = readFrom(openSync(file, "r"), buffer, length, start);
316
+ const slice = buffer.subarray(0, read);
317
+ const newline = slice.indexOf(0x0a);
318
+ const offset = newline >= 0 && newline < slice.length ? newline + 1 : 0;
319
+ const kept = slice.subarray(offset);
320
+ const fromEnd = kept.subarray(Math.max(0, kept.length - budget));
321
+ return stripSplitCharacter(fromEnd.toString("utf8"), "start");
322
+ }
323
+
324
+ /**
325
+ * A byte window can cut a multi-byte character in half; a lone replacement
326
+ * character at that edge is the cut, not the program's output.
327
+ */
328
+ function stripSplitCharacter(text: string, edge: "start" | "end"): string {
329
+ return edge === "end" ? text.replace(/\uFFFD$/, "") : text.replace(/^\uFFFD/, "");
330
+ }
331
+
332
+ /** Apply the byte cap to one captured stream, keeping a head and a tail. */
333
+ export function boundStream(file: string, cap: number, fullTextPath?: string): RunStream {
334
+ const bytes = statSize(file);
335
+ if (bytes <= cap) {
336
+ const buffer = Buffer.allocUnsafe(bytes);
337
+ const read = bytes === 0 ? 0 : readFrom(openSync(file, "r"), buffer, bytes, 0);
338
+ return {
339
+ text: buffer.subarray(0, read).toString("utf8"),
340
+ bytes,
341
+ shownBytes: read,
342
+ droppedBytes: 0,
343
+ truncated: false,
344
+ };
345
+ }
346
+
347
+ const headBudget = Math.floor(cap * HEAD_SHARE);
348
+ const tailBudget = cap - headBudget;
349
+ const head = readHead(file, headBudget);
350
+ const tail = readTail(file, tailBudget);
351
+ const kept = Buffer.byteLength(head) + Buffer.byteLength(tail);
352
+ const droppedBytes = Math.max(0, bytes - kept);
353
+ const marker = `\n[... ${droppedBytes} bytes omitted ...]\n`;
354
+ return {
355
+ text: `${head}${marker}${tail}`,
356
+ bytes,
357
+ shownBytes: kept,
358
+ droppedBytes,
359
+ truncated: true,
360
+ ...(fullTextPath ? { fullTextPath } : {}),
361
+ };
362
+ }
363
+
364
+ /** Kill the child's process group, falling back to the child alone. */
365
+ function killTree(child: ChildProcess): void {
366
+ const pid = child.pid;
367
+ if (pid === undefined) return;
368
+ if (process.platform !== "win32") {
369
+ try {
370
+ process.kill(-pid, "SIGKILL");
371
+ return;
372
+ } catch {
373
+ // The group is already gone, or the child never led one; fall through to
374
+ // the direct kill so a single process is still terminated.
375
+ }
376
+ }
377
+ try {
378
+ child.kill("SIGKILL");
379
+ } catch {
380
+ // The child exited between the timeout firing and this call; the exit
381
+ // event already carries the result, so there is nothing left to stop.
382
+ }
383
+ }
384
+
385
+ /**
386
+ * Run one program. The caller has already refused the shapes that never reach a
387
+ * program (see `findRefusal`) and resolved `context.cwd`.
388
+ *
389
+ * The child is spawned detached on POSIX so the timeout and an aborted tool call
390
+ * kill the whole tree, not only the leader; stdout and stderr are files rather
391
+ * than pipes, so a grandchild cannot hold the result open after the program
392
+ * exits, and the capture is byte-exact without buffering the stream in memory.
393
+ */
394
+ export async function executeArgv(
395
+ request: RunRequest,
396
+ context: RunContext,
397
+ signal?: AbortSignal,
398
+ ): Promise<RunCapture> {
399
+ const cwd = resolve(context.cwd);
400
+ const dir = mkdtempSync(join(tmpdir(), "pi-run-"));
401
+ const stdoutPath = join(dir, "stdout");
402
+ const stderrPath = join(dir, "stderr");
403
+
404
+ let child: ChildProcess;
405
+ const startedAt = performance.now();
406
+ let stdoutFd: number | undefined;
407
+ let stderrFd: number | undefined;
408
+ try {
409
+ stdoutFd = openSync(stdoutPath, "w");
410
+ stderrFd = openSync(stderrPath, "w");
411
+ child = spawn(request.argv[0], request.argv.slice(1), {
412
+ cwd,
413
+ env: { ...process.env, ...(request.env ?? {}) },
414
+ // shell: false is the default; it is written out because "no shell" is
415
+ // this tool's contract, not an inherited default a refactor could flip.
416
+ shell: false,
417
+ detached: process.platform !== "win32",
418
+ windowsHide: true,
419
+ stdio: [request.stdin === undefined ? "ignore" : "pipe", stdoutFd, stderrFd],
420
+ });
421
+ } catch (error) {
422
+ rmSync(dir, { recursive: true, force: true });
423
+ throw error;
424
+ } finally {
425
+ if (stdoutFd !== undefined) closeSync(stdoutFd);
426
+ if (stderrFd !== undefined) closeSync(stderrFd);
427
+ }
428
+
429
+ let timedOut = false;
430
+ let aborted = false;
431
+ let spawnError: string | undefined;
432
+
433
+ const exit = new Promise<{ code: number | null; signal: string | null }>((settle) => {
434
+ let done = false;
435
+ const finish = (code: number | null, killed: string | null) => {
436
+ if (done) return;
437
+ done = true;
438
+ settle({ code, signal: killed });
439
+ };
440
+ child.once("exit", (code, killed) => finish(code, killed));
441
+ child.once("error", (error) => {
442
+ spawnError = `${(error as NodeJS.ErrnoException).code ?? "spawn"}: ${error.message}`;
443
+ finish(null, null);
444
+ });
445
+ });
446
+
447
+ const onAbort = () => {
448
+ aborted = true;
449
+ killTree(child);
450
+ };
451
+ if (signal) {
452
+ if (signal.aborted) onAbort();
453
+ else signal.addEventListener("abort", onAbort, { once: true });
454
+ }
455
+
456
+ if (child.stdin) {
457
+ child.stdin.on("error", () => {
458
+ // A program may exit before reading its stdin; the write failure is then
459
+ // the program's answer, reported through its exit code, not a tool error.
460
+ });
461
+ child.stdin.end(request.stdin ?? "");
462
+ }
463
+
464
+ const timer = setTimeout(() => {
465
+ timedOut = true;
466
+ killTree(child);
467
+ }, request.timeout_ms);
468
+
469
+ // The timer and the abort listener belong to the wait, not to the call: they
470
+ // are released when the wait settles, whichever way it settles.
471
+ const result = await exit.finally(() => {
472
+ clearTimeout(timer);
473
+ if (signal) signal.removeEventListener("abort", onAbort);
474
+ });
475
+
476
+ return {
477
+ exitCode: result.code,
478
+ signal: result.signal,
479
+ timedOut,
480
+ aborted,
481
+ durationMs: Math.round(performance.now() - startedAt),
482
+ cwd,
483
+ argv: request.argv,
484
+ ...(spawnError === undefined ? {} : { spawnError }),
485
+ stdoutPath,
486
+ stderrPath,
487
+ stdoutBytes: spawnError === undefined ? statSize(stdoutPath) : 0,
488
+ stderrBytes: statSize(stderrPath),
489
+ captureDir: dir,
490
+ };
491
+ }
492
+
493
+ /** Remove the capture directory after the caller has offloaded what it needs. */
494
+ export function discardCapture(capture: RunCapture): void {
495
+ if (capture.captureDir) {
496
+ rmSync(capture.captureDir, { recursive: true, force: true });
497
+ }
498
+ }
499
+
500
+ /** The capture file for one stream, while the capture directory still exists. */
501
+ export function capturePathFor(capture: RunCapture, stream: "stdout" | "stderr"): string {
502
+ return stream === "stdout" ? capture.stdoutPath : capture.stderrPath;
503
+ }
@@ -18,6 +18,7 @@ import orchestratorFn from "./orchestrator/index.js";
18
18
  // context-management (tool profile switching)
19
19
  import contextManagementFn from "./context-management/index.js";
20
20
  import coreAgentEnvFn from "./core/agent-environment/index.js";
21
+ import coreRunToolFn from "./core/run-tool/index.js";
21
22
  import corePromptBuilderFn from "./core/prompt-builder/index.js";
22
23
 
23
24
  // cognitive (reasoning tools + detectors: think, verify, topic-drift, MARS reflection, ...)
@@ -106,6 +107,11 @@ export const MANIFEST: ManifestEntry[] = [
106
107
  alwaysOn: true,
107
108
  desc: "time_status, L1 context injection",
108
109
  },
110
+ {
111
+ id: "run-tool",
112
+ fn: coreRunToolFn,
113
+ desc: "run tool - one program and its argv, without a shell",
114
+ },
109
115
  {
110
116
  id: "workspace-snapshot",
111
117
  fn: workspaceSnapshotFn,
@@ -33,6 +33,7 @@ export const TOOL_FAMILIES: Readonly<Record<string, ToolFamily>> = {
33
33
  get_search_content: "web-fetch",
34
34
 
35
35
  bash: "terminal",
36
+ run: "terminal",
36
37
  herdr_pane: "terminal",
37
38
  herdr_layout: "terminal",
38
39
 
@@ -0,0 +1,134 @@
1
+ /**
2
+ * Workspace escape guard for destructive argv.
3
+ *
4
+ * A tool that takes an argv list lets a caller name a path, and a verb that
5
+ * removes or overwrites what it names turns a path typo into data loss. This
6
+ * module answers one question for such a tool: does this argv carry a path
7
+ * argument that resolves outside the workspace root?
8
+ *
9
+ * It is a mechanism, not a policy:
10
+ * - the destructive verb set is the caller's, passed in;
11
+ * - the workspace root and the invocation cwd are the caller's;
12
+ * - nothing here executes, refuses, rewrites or reports. The caller decides
13
+ * what to do with an escape, and its own message names the outcome.
14
+ *
15
+ * Resolution is canonical on both sides. The root and the target's nearest
16
+ * existing ancestor go through realpath, so a symlink that lives inside the
17
+ * workspace and points outside it is caught, while a target that does not exist
18
+ * yet is compared by the canonical path of its parent. A target equal to the
19
+ * root is an escape: removing or rewriting the workspace itself is outside the
20
+ * set of things a single path argument may name.
21
+ */
22
+
23
+ import { existsSync, realpathSync } from "node:fs";
24
+ import { basename, dirname, isAbsolute, resolve, sep } from "node:path";
25
+
26
+ /** One path argument that resolves outside the workspace. */
27
+ export interface WorkspaceEscape {
28
+ /** The program (argv[0]) whose verb the caller marked destructive. */
29
+ verb: string;
30
+ /** The argument as the caller wrote it. */
31
+ argument: string;
32
+ /** The path value read out of the argument (`of=` is read as its right side). */
33
+ path: string;
34
+ /** That path, canonical and absolute. */
35
+ resolved: string;
36
+ /** The workspace root, canonical and absolute. */
37
+ root: string;
38
+ }
39
+
40
+ /** A candidate path value and the argument it was read from. */
41
+ interface Candidate {
42
+ argument: string;
43
+ path: string;
44
+ }
45
+
46
+ /**
47
+ * Path values carried by an argv, read conservatively: every element after the
48
+ * program that is not a flag, plus the right side of any `key=value` element
49
+ * (`dd of=/etc/passwd`). A flag's own value (`-o /etc/x`) is not followed by the
50
+ * scanner, which is why the caller keeps destructive verbs to the set whose
51
+ * operands are positional or `key=value`; the guard never guesses at a program's
52
+ * option grammar.
53
+ */
54
+ export function pathCandidates(argv: readonly string[]): Candidate[] {
55
+ const candidates: Candidate[] = [];
56
+ for (const argument of argv.slice(1)) {
57
+ if (argument === "" || argument === "--" || argument.startsWith("-")) continue;
58
+ const eq = argument.indexOf("=");
59
+ const path = eq >= 0 ? argument.slice(eq + 1) : argument;
60
+ if (path === "") continue;
61
+ candidates.push({ argument, path });
62
+ }
63
+ return candidates;
64
+ }
65
+
66
+ /** Canonical absolute path for a target, whether or not it exists yet. */
67
+ export function canonicalPath(target: string): string {
68
+ let current = resolve(target);
69
+ const missing: string[] = [];
70
+ // realpath the nearest existing ancestor, then re-attach the names that do
71
+ // not exist yet. The loop is bounded by the filesystem's depth: each step
72
+ // removes one segment.
73
+ for (;;) {
74
+ if (existsSync(current)) {
75
+ let real: string;
76
+ try {
77
+ real = realpathSync(current);
78
+ } catch {
79
+ // A path that exists but cannot be resolved (a race, a permission
80
+ // boundary) is compared as written rather than skipped: a guard that
81
+ // ignores what it cannot resolve is a guard that can be bypassed by
82
+ // making the target unreadable.
83
+ real = current;
84
+ }
85
+ return missing.length ? resolve(real, ...missing.reverse()) : real;
86
+ }
87
+ const parent = dirname(current);
88
+ if (parent === current) return resolve(current, ...missing.reverse());
89
+ missing.push(basename(current));
90
+ current = parent;
91
+ }
92
+ }
93
+
94
+ /** Whether `target` is strictly below `root` after both are canonicalized. */
95
+ export function isBelow(root: string, target: string): boolean {
96
+ const canonicalRoot = canonicalPath(root);
97
+ const canonicalTarget = canonicalPath(target);
98
+ return canonicalTarget.startsWith(canonicalRoot + sep);
99
+ }
100
+
101
+ /**
102
+ * The first path argument, in argv order, that resolves outside the workspace.
103
+ * Null when the program's verb is not in `verbs`, when no path argument escapes,
104
+ * or when the argv carries no path argument at all.
105
+ *
106
+ * `cwd` is the directory the argv runs in, so relative operands are read the
107
+ * way the program will read them. `workspaceRoot` is the boundary, which need
108
+ * not be `cwd`: a call may run in a subdirectory and still be bounded by the
109
+ * session's working directory.
110
+ */
111
+ export function findWorkspaceEscape(options: {
112
+ verbs: ReadonlySet<string>;
113
+ argv: readonly string[];
114
+ cwd: string;
115
+ workspaceRoot: string;
116
+ }): WorkspaceEscape | null {
117
+ const { verbs, argv, cwd, workspaceRoot } = options;
118
+ const program = argv[0] ?? "";
119
+ const verb = basename(program);
120
+ if (!verbs.has(verb)) return null;
121
+ const root = canonicalPath(workspaceRoot);
122
+ for (const candidate of pathCandidates(argv)) {
123
+ const target = isAbsolute(candidate.path) ? candidate.path : resolve(cwd, candidate.path);
124
+ if (isBelow(root, target)) continue;
125
+ return {
126
+ verb,
127
+ argument: candidate.argument,
128
+ path: candidate.path,
129
+ resolved: canonicalPath(target),
130
+ root,
131
+ };
132
+ }
133
+ return null;
134
+ }