opencode-model-router 2.3.0 → 2.5.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.
Files changed (68) hide show
  1. package/CHANGELOG.md +171 -0
  2. package/README.md +86 -11
  3. package/package.json +6 -1
  4. package/src/commands/output.ts +21 -1
  5. package/src/compat/v2-hooks.ts +1374 -24
  6. package/src/escalate/ladder.ts +12 -0
  7. package/src/guard/enforce.ts +186 -22
  8. package/src/guard/guards.ts +132 -6
  9. package/src/guard/store.ts +5 -0
  10. package/src/index.ts +718 -29
  11. package/src/router/config.ts +247 -1
  12. package/src/router/dispatch-header.ts +46 -4
  13. package/src/router/git-tools.ts +1152 -0
  14. package/src/router/guard-profile.ts +100 -0
  15. package/src/router/plugin-agents.ts +433 -0
  16. package/src/router/prompts.ts +26 -1
  17. package/src/router/protocol.ts +133 -0
  18. package/src/router/read-only.ts +149 -0
  19. package/src/router/role-agents.ts +409 -0
  20. package/src/router/roles-config.ts +429 -0
  21. package/src/router/roles.ts +600 -0
  22. package/src/router/run-tools.ts +913 -0
  23. package/src/router/sensitive-paths.ts +101 -0
  24. package/src/router/sessions.ts +92 -0
  25. package/src/router/subagents.ts +28 -1
  26. package/src/routing/advisor/findings.ts +193 -1
  27. package/src/routing/advisor/index.ts +13 -5
  28. package/src/routing/classify/index.ts +23 -5
  29. package/src/routing/classify/route-line.ts +67 -3
  30. package/src/routing/classify/rules.ts +80 -20
  31. package/src/routing/classify/types.ts +34 -4
  32. package/src/routing/commands/stats.ts +3 -0
  33. package/src/routing/engine/kernel.ts +163 -0
  34. package/src/routing/engine/ladders.ts +242 -1
  35. package/src/routing/engine/protocol-line.ts +17 -0
  36. package/src/routing/engine/roles-taxonomy.ts +52 -0
  37. package/src/routing/engine/types.ts +99 -1
  38. package/src/routing/outcomes/beta.ts +10 -4
  39. package/src/routing/outcomes/index.ts +44 -1
  40. package/src/routing/outcomes/ingest.ts +163 -15
  41. package/src/routing/outcomes/persist.ts +23 -1
  42. package/src/routing/outcomes/signals.ts +650 -0
  43. package/src/routing/outcomes/stats.ts +273 -2
  44. package/src/routing/outcomes/store.ts +25 -5
  45. package/src/routing/outcomes/types.ts +145 -6
  46. package/src/routing/roles/authority.ts +495 -0
  47. package/src/routing/roles/binding.ts +543 -0
  48. package/src/routing/roles/policy.ts +416 -0
  49. package/src/routing/roles/work-root.ts +132 -0
  50. package/src/routing/wire/dispatch.ts +1306 -17
  51. package/src/routing/wire/hint.ts +14 -0
  52. package/src/routing/wire/runtime.ts +117 -28
  53. package/src/tui/effort-channel.ts +220 -0
  54. package/src/tui/effort-rpc.ts +60 -0
  55. package/src/tui/host-types.ts +154 -0
  56. package/src/tui/opentui-solid.d.ts +16 -0
  57. package/src/tui/plugin.ts +1007 -0
  58. package/src/tui/status-model.ts +561 -0
  59. package/src/v2.ts +26 -1
  60. package/src/verify/checker.ts +249 -7
  61. package/src/verify/deterministic.ts +10 -1
  62. package/src/verify/dispatch.ts +63 -6
  63. package/src/verify/dod.ts +127 -10
  64. package/src/verify/gate.ts +75 -7
  65. package/src/verify/types.ts +12 -0
  66. package/src/verify/wiring.ts +55 -10
  67. package/tiers.json +13 -5
  68. package/tui.ts +4 -0
@@ -0,0 +1,913 @@
1
+ /**
2
+ * `router_run`: the structured run tool of roles mode (plan P1.3, #84). It runs one
3
+ * allowlisted entry in the dispatch's work root and reports the exit code; it is the
4
+ * only exec-class action a role is ever granted (§2.2).
5
+ *
6
+ * Trust model (T1.3.2).
7
+ * - The tool never spawns a shell itself: every spawn is `shell: false` with a fixed
8
+ * argv (`spawnBounded`), and a caller only picks an entry name, plus arguments when
9
+ * the entry declares them (each one allowlisted and confined to the work root, never
10
+ * interpreted by the tool).
11
+ * - npm script bodies (`package.json` `scripts`, including the `pre<name>`/`post<name>`
12
+ * hooks npm runs with them) are TRUSTED REPOSITORY CONTENT, executed by npm's script
13
+ * shell exactly as `npm run <name>` would. The tool pins WHICH npm, node and shell run
14
+ * them (none may come from the repository or the plugin's checkout, #77 G4) and the
15
+ * npm settings that would change that: `--script-shell`, `--node-options=`,
16
+ * `--workspaces=false`, `--update-notifier=false`, `--logs-max=0` and `--userconfig`
17
+ * on the command line outrank every npmrc file and the environment. `--globalconfig`
18
+ * does NOT: npm keeps the command-line value in its default layer, so any npmrc that
19
+ * sets `globalconfig` wins over it (QA-P13-3-3). A work-root `.npmrc` is therefore
20
+ * refused when it selects workspaces (`workspace`, `workspaces`,
21
+ * `include-workspace-root`: npm would run another package's scripts) or moves npm's
22
+ * config files (`globalconfig`, `userconfig`, `prefix`: a repository file could then
23
+ * select a workspace unchecked). The user's own `~/.npmrc` may still set
24
+ * `globalconfig`; that file is user-owned, outside every work root. Other repository
25
+ * `.npmrc` settings (cache, registry, …) still apply to npm itself. The tool does not
26
+ * and cannot make a script safe.
27
+ * - Because an edit can change what a script does, a grant holding both write and exec
28
+ * is floored at medium/heavy by the §2.3 floor table: write + exec is as strong as
29
+ * running code the agent wrote.
30
+ *
31
+ * Authority (S11, P-10, P-12, I9). No `evaluate` hook fires for plugin tools, so the tool
32
+ * checks its own authority: the session must be bound to a work root (resolver injected
33
+ * by P2.1), and `cwd` must name that root after canonicalisation. The tool never reads
34
+ * `context.directory`, `context.worktree` or the session location: under the v2 bridge
35
+ * they name the main checkout, not a sibling worktree.
36
+ *
37
+ * Residual risks (documented, not defended; QA-P13-1-12):
38
+ * - The work root itself may be replaced (a junction or symlink swapped in) between the
39
+ * check and the spawn; the agent only writes inside the root, not its parent.
40
+ * - POSIX: the run's process group is killed when the call settles, but a process that
41
+ * left the group (`setsid`, a double fork into a new session) escapes it.
42
+ * - win32: there is no process tree once the parent has exited, so a background process
43
+ * a script started and left running survives a normal exit (taskkill /T only reaches
44
+ * the tree while the parent lives, i.e. on timeout or abort).
45
+ * - win32 cmd.exe searches the current directory before PATH; the run sets
46
+ * `NoDefaultCurrentDirectoryInExePath=1`, which cmd.exe honours, but a script can unset it.
47
+ * - npm puts `node_modules/.bin` of the work root on PATH for scripts (npm's behaviour,
48
+ * repository content by the trust model above); the inherited PATH is stripped of
49
+ * relative entries and entries inside the guarded directories.
50
+ * - Credential redaction of the output is best effort (URL userinfo and credential-like
51
+ * query parameters), not a secret scanner; credential-like environment variables are
52
+ * not passed to the run.
53
+ * - Agents and credential stores stay reachable (QA-P13-2-6): the ssh-agent socket
54
+ * (SSH_AUTH_SOCK), git credential helpers and the OS keychain, cloud CLI caches under
55
+ * the home directory (~/.aws, ~/.config/gcloud, ~/.azure, ~/.docker/config.json, …),
56
+ * and environment variables whose values carry credentials under other names (for
57
+ * example a URL with userinfo). A script can use them as the user can.
58
+ * - Argument confinement is lexical (QA-P13-2-1): a caller argument never names an
59
+ * absolute, drive, UNC or URL path or a `..` segment, but a symlink or junction inside
60
+ * the work root, and the contents of an `@response` file, are repository content.
61
+ */
62
+ import { realpathSync, statSync } from "node:fs";
63
+ import { createRequire } from "node:module";
64
+ import { homedir } from "node:os";
65
+ import { posix, win32 } from "node:path";
66
+ import { tool } from "@opencode-ai/plugin";
67
+ import type { RunConfig } from "./roles";
68
+ import {
69
+ checkWorkRootAnswer, dropPartialCredential, envLookup, errorMessage, firstOutside, isFullPath, readBoundedRegularFile as readBounded,
70
+ realFileOrUndefined, spawnBounded, stripUrlUserinfo, workRootGuards, type BoundedLabel, type BoundedResult, type WorkRootAnswer,
71
+ } from "./git-tools";
72
+
73
+ export { isFullPath } from "./git-tools";
74
+ export type { WorkRootAnswer } from "./git-tools";
75
+
76
+ export const RUN_TOOL_NAME = "router_run";
77
+ /** Every caller argument must match this allowlist (no spaces, quotes or shell metacharacters on any platform). */
78
+ export const RUN_ARG_RE = /^[A-Za-z0-9_./:=@+-]{1,200}$/;
79
+ /** An entry name: never option-like (it is an npm argv element). */
80
+ export const RUN_NAME_RE = /^[A-Za-z0-9_][A-Za-z0-9_.:@+-]{0,199}$/;
81
+ export const RUN_MAX_ARGS = 50;
82
+ /**
83
+ * Output bound (raw bytes): the first RUN_HEAD_BYTES and the last RUN_TAIL_BYTES of
84
+ * stdout+stderr in arrival order, plus the last RUN_STDERR_TAIL_BYTES of stderr on their
85
+ * own when the output was cut and they are not already shown. stdout and stderr are
86
+ * separate pipes without a relative order, so a script's final stderr lines (a test
87
+ * runner's failure summary) can arrive before the last stdout bytes and fall out of the
88
+ * merged tail; the stderr tail keeps them.
89
+ */
90
+ export const RUN_OUTPUT_BYTES = 64 * 1024;
91
+ export const RUN_HEAD_BYTES = 16 * 1024;
92
+ export const RUN_STDERR_TAIL_BYTES = 8 * 1024;
93
+ export const RUN_TAIL_BYTES = RUN_OUTPUT_BYTES - RUN_HEAD_BYTES - RUN_STDERR_TAIL_BYTES;
94
+ /**
95
+ * Bound of the rendered text in UTF-8 bytes (QA-P13-1-13): invalid UTF-8 decodes to
96
+ * U+FFFD (3 bytes per invalid byte), so the decoded text is capped again.
97
+ */
98
+ export const RUN_RENDERED_MAX_BYTES = RUN_OUTPUT_BYTES + 1024;
99
+ export const DEFAULT_RUN_TIMEOUT_MS = 600_000;
100
+ const MAX_TIMER_MS = 2 ** 31 - 1;
101
+ const MAX_CONFIG_FILE_BYTES = 4 * 1024 * 1024;
102
+ const RUN_LABEL: BoundedLabel = { message: "router_run", tag: "router_run", program: "the run" };
103
+ /** Bun's temporary node directory (`bun run` puts a node link to bun first on PATH; see verify/runner.ts F.1). */
104
+ const BUN_NODE_DIR_RE = /^bun-node-[0-9a-f]+$/i;
105
+ /** Command executables refused outright: a shell (or `env`) would make the fixed argv a script. */
106
+ const SHELL_RE = /^(cmd|command|powershell|pwsh|sh|bash|dash|zsh|ksh|mksh|ash|csh|tcsh|fish|busybox|toybox|wsl|wscript|cscript|mshta|env)$/i;
107
+ /** Package-manager front ends that read repository config (`.npmrc` `script-shell`, `node-options`) themselves. */
108
+ const SHIM_RE = /^(npx|pnpm|pnpx|yarn|yarnpkg|corepack|bun|bunx)$/i;
109
+ /** npm commands a `commands` entry may run: script runners only (never `exec`, `install`, …). Exact names. */
110
+ export const NPM_RUN_COMMANDS: ReadonlySet<string> = new Set(["run", "run-script", "test", "start", "stop", "restart"]);
111
+ /** npm flags a `commands` entry may fix before `--` (exact spellings; npm accepts abbreviations, so nothing else). */
112
+ const NPM_SAFE_FLAGS: ReadonlySet<string> = new Set(["--silent", "-s", "--quiet", "-q", "--if-present"]);
113
+ /** `.npmrc` keys that make npm run another package's scripts. */
114
+ const NPMRC_WORKSPACE_KEYS: ReadonlySet<string> = new Set(["workspace", "workspaces", "include-workspace-root"]);
115
+ /** `.npmrc` keys that move npm's config files out of the tool's checks (QA-P13-3-3). */
116
+ const NPMRC_LOCATION_KEYS: ReadonlySet<string> = new Set(["globalconfig", "userconfig", "prefix"]);
117
+ /**
118
+ * Credential-bearing environment variable names (QA-P13-1-9). QA-G-A2-6: PASSWORD/PASSWD match
119
+ * anywhere and PWD before the end or a `_`, without a leading `_` (`PGPASSWORD`, `MYSQL_PWD`);
120
+ * the working-directory variables `PWD`/`OLDPWD` are exempt ({@link WORKING_DIRECTORY_ENV}).
121
+ */
122
+ export const CREDENTIAL_ENV_RE = /(^|_)(TOKEN|SECRET|API_?KEY|ACCESS_?KEY|PRIVATE_?KEY|CREDENTIALS?)($|_)|PASSW(OR)?D|PWD($|_)/i;
123
+ /** The POSIX working directory and the previous one: never credentials, kept as they are. */
124
+ const WORKING_DIRECTORY_ENV = /^(OLD)?PWD$/i;
125
+ /** Provider credentials whose names the pattern above does not match. */
126
+ const PROVIDER_ENV: ReadonlySet<string> = new Set(["OPENAI_KEY", "AZURE_OPENAI_KEY", "COHERE_KEY", "GROQ_KEY", "MISTRAL_KEY",
127
+ "OPENROUTER_KEY", "DEEPSEEK_KEY", "XAI_KEY", "GEMINI_KEY", "GOOGLE_KEY", "DATABASE_URL"]);
128
+
129
+ /** What the outcome store receives after every run that was spawned (P1.4 `run` signal). */
130
+ export interface RunRecord {
131
+ sessionID: string;
132
+ /** The entry name the caller asked for. */
133
+ script: string;
134
+ /** null: no exit code (timed out, aborted or killed by a signal). */
135
+ exitCode: number | null;
136
+ /** When the run STARTED (ms since epoch): a run that started before an edit never counts as after it. */
137
+ at: number;
138
+ }
139
+
140
+ export interface RunToolDeps {
141
+ /** Effective `routing.run` (global layer only, P1.1). Read on every call. */
142
+ config: () => RunConfig;
143
+ /**
144
+ * The session's work-root answer (P2.1 wires it to the dispatch binding; the type is
145
+ * shared with router_git_*, QA-P13-2-8). `{ role: false }` → refused (router_run is
146
+ * for role sessions only); `{ role: true, root: null }` → refused (I9); `{ role: true,
147
+ * root }` → `cwd` must name that root. Any other answer is reported as an error.
148
+ */
149
+ resolveWorkRoot: (sessionID: string) => WorkRootAnswer;
150
+ /** P1.4 `run` signal. A throwing recorder never hides the run's result. */
151
+ recordRun?: (e: RunRecord) => void;
152
+ /** Test seam: the node executable (absolute; still refused inside the guarded directories). Default: F.1 lookup. */
153
+ nodeExecPath?: string;
154
+ /** Test seam for platform-dependent resolution (shell, PATH lookup, path comparison). Default: process.platform. */
155
+ platform?: NodeJS.Platform;
156
+ /** Test seam: the environment the run inherits (hardened). Default: process.env at call time. */
157
+ env?: NodeJS.ProcessEnv;
158
+ }
159
+
160
+ export interface RunInput { script: string; args?: readonly string[]; cwd: string }
161
+
162
+ /** A resolved, spawnable run. `executable` is absolute; argv never passes through a shell. */
163
+ export interface RunPlan {
164
+ kind: "script" | "command";
165
+ name: string;
166
+ executable: string;
167
+ argv: string[];
168
+ cwd: string;
169
+ env: NodeJS.ProcessEnv;
170
+ timeoutMs: number;
171
+ }
172
+
173
+ /**
174
+ * QA-G-A2-6: there is no credential passthrough. The `envPassthrough` option was never wired to
175
+ * any configuration, so it was removed rather than kept as a dead knob: credential-like
176
+ * variables are always dropped.
177
+ */
178
+ export interface RunHost { platform: NodeJS.Platform; env: NodeJS.ProcessEnv; nodeExecPath?: string }
179
+
180
+ class RunRefused extends Error {}
181
+ const refuse = (message: string) => new RunRefused(message);
182
+
183
+ function pathApi(platform: NodeJS.Platform) { return platform === "win32" ? win32 : posix; }
184
+
185
+ function samePath(a: string, b: string, platform: NodeJS.Platform): boolean {
186
+ return platform === "win32" ? a.toLowerCase() === b.toLowerCase() : a === b;
187
+ }
188
+
189
+ function nativeRealpath(path: string): string | undefined {
190
+ try { return realpathSync.native(path); } catch { return undefined; }
191
+ }
192
+
193
+ /**
194
+ * Text form of a path for comparison WITHOUT touching the filesystem (QA-G-A2-1): separators
195
+ * unified (win32: `\`), repeated separators and `.` segments dropped (a leading `\\` is kept),
196
+ * no trailing separator except a root's; case folded on win32.
197
+ */
198
+ function pathText(path: string, platform: NodeJS.Platform): string {
199
+ const win = platform === "win32";
200
+ const sep = win ? "\\" : "/";
201
+ const text = win ? path.replace(/\//g, "\\") : path;
202
+ const lead = win && text.startsWith("\\\\") ? "\\\\" : text.startsWith(sep) ? sep : "";
203
+ let out = lead + text.split(sep).filter(part => part !== "" && part !== ".").join(sep);
204
+ if (win && /^[A-Za-z]:$/.test(out)) out += sep;
205
+ return win ? out.toLowerCase() : out;
206
+ }
207
+
208
+ /**
209
+ * win32: the `host\share` (lower case) a network path names, `"device"` for any other `\\`/`//`
210
+ * path (`\\?\C:\…`, `\\.\pipe\…`), undefined for a local path. POSIX: always undefined.
211
+ */
212
+ function networkShare(path: string, platform: NodeJS.Platform): string | undefined {
213
+ if (platform !== "win32" || !/^[\\/]{2}/.test(path)) return undefined;
214
+ const parts = path.replace(/\//g, "\\").split("\\").filter(part => part !== "");
215
+ const unc = parts[0] === "?" || parts[0] === "." ? (parts[1]?.toLowerCase() === "unc" ? parts.slice(2) : undefined) : parts;
216
+ return unc !== undefined && unc.length >= 2 ? `${unc[0]}\\${unc[1]}`.toLowerCase() : "device";
217
+ }
218
+
219
+ /**
220
+ * QA-G-A2 round 2 (nit 1): may a LOCAL cwd that differs from the root as text be resolved?
221
+ * Never with a `..` segment. POSIX: only at or below the parent directory of the bound root or
222
+ * of its real path (elsewhere, an automounter path such as `/net/<host>/…` would make realpath
223
+ * contact that host). win32: only on the drive of the bound root or of its real path (another
224
+ * drive may be a mapped network drive); the same-drive rule keeps junction and 8.3 spellings.
225
+ */
226
+ function resolvableNearRoot(cwd: string, bound: string, root: string, platform: NodeJS.Platform): boolean {
227
+ const sep = platform === "win32" ? "\\" : "/";
228
+ const text = pathText(cwd, platform);
229
+ if (text.split(sep).includes("..")) return false;
230
+ if (platform === "win32") {
231
+ const drive = (path: string) => (/^[a-z]:/.test(path) ? path.slice(0, 2) : undefined);
232
+ const own = drive(text);
233
+ return own !== undefined && [bound, root].some(base => drive(pathText(base, platform)) === own);
234
+ }
235
+ return [bound, root].some(base => {
236
+ const parent = pathText(posix.dirname(base), platform);
237
+ return text === parent || text.startsWith(parent.endsWith("/") ? parent : `${parent}/`);
238
+ });
239
+ }
240
+
241
+ /**
242
+ * The canonical work root a call may run in (P-10, I9): the session must be bound, and
243
+ * `cwd` must name the same directory as the bound root, case-insensitively on win32.
244
+ * QA-G-A2-1: the cwd is first compared as TEXT with the bound root and its real path; only
245
+ * when that fails is it resolved (realpathSync.native: links, junctions and 8.3 names
246
+ * expanded). A network or device cwd (`\\host\share\…`, `//host/…`, `\\?\…`, `\\.\…`) is
247
+ * never resolved unless the bound root itself lies on that same `\\host\share`: no
248
+ * filesystem call reaches a host the work root is not on. A local cwd is resolved only near
249
+ * the root ({@link resolvableNearRoot}: POSIX below the root's parent, win32 on its drive).
250
+ */
251
+ export function authorizeCwd(bound: unknown, cwd: unknown, platform: NodeJS.Platform = process.platform): string {
252
+ if (typeof bound !== "string" || bound === "") throw refuse("this session has no bound work root (I9); router_run only runs in a dispatch's work root");
253
+ if (!isFullPath(bound, platform)) throw refuse("the bound work root is not an absolute path");
254
+ const root = nativeRealpath(bound);
255
+ if (root === undefined || !statSync(root).isDirectory()) throw refuse(`the bound work root does not exist: ${bound}`);
256
+ if (typeof cwd !== "string" || !isFullPath(cwd, platform)) throw refuse(`cwd must be the absolute path of this dispatch's work root (${root})`);
257
+ const text = pathText(cwd, platform);
258
+ if (text === pathText(bound, platform) || text === pathText(root, platform)) return root;
259
+ const share = networkShare(cwd, platform);
260
+ if (share !== undefined && (share === "device" || (share !== networkShare(bound, platform) && share !== networkShare(root, platform)))) {
261
+ throw refuse(`cwd is not this dispatch's work root (${root})`);
262
+ }
263
+ if (share === undefined && !resolvableNearRoot(cwd, bound, root, platform)) throw refuse(`cwd is not this dispatch's work root (${root})`);
264
+ const real = nativeRealpath(cwd);
265
+ if (real === undefined || !samePath(real, root, platform)) throw refuse(`cwd is not this dispatch's work root (${root})`);
266
+ return root;
267
+ }
268
+
269
+ /**
270
+ * Plan amendment R9: `routing.run.scripts` names scripts exactly (the config sanitiser admits no wildcard), so an entry
271
+ * matches only the identical name.
272
+ */
273
+ export function scriptAllowed(scripts: readonly string[], name: string): boolean {
274
+ return scripts.some(entry => typeof entry === "string" && entry === name);
275
+ }
276
+
277
+ /** The option-like lead of an argument (`-x`, `@responsefile`, `+opt`), or undefined. */
278
+ export function optionLead(arg: string): string | undefined {
279
+ return /^[-@+]/.test(arg) ? arg[0] : undefined;
280
+ }
281
+
282
+ /**
283
+ * The argument may name a path outside the work root (QA-P13-1-1, QA-P13-2-1). Lexical:
284
+ * - a piece starting with `/`, `\` or a drive (`X:`), where pieces start at the
285
+ * argument, after its option lead, after a two-character short option (`-o/abs`,
286
+ * `-I../x`) and after every `=`, `:`, `@` or `+` (`--define=K=/abs`, `pkg@/abs`);
287
+ * - `:/` or `//` anywhere (URLs such as `file:///D:/x`, UNC, `--alias=x:/abs`);
288
+ * - a `..` segment bounded by `/`, `\`, `=`, `:`, `@`, `+` or the ends, also right
289
+ * after a two-character short option (`-r../x.js`).
290
+ * - a single-dash argument (`/^-[^-]/`) with any `/`, `\` or `..` (QA-P13-3-1): yargs
291
+ * and minimist read `-br../evil.js` as `-b -r ../evil.js` and `-ofoo/abs` as
292
+ * `-o foo/abs`, so a short-option cluster can carry a path at any offset. Paths stay
293
+ * available through checked `--long=value` arguments.
294
+ * On win32 a leading `/switch` is refused by the same rule. Symlinks inside the work
295
+ * root and the contents of `@response` files are repository content (not checked).
296
+ */
297
+ export function escapesWorkRoot(arg: string): boolean {
298
+ if (/^-[^-]/.test(arg) && /[\\/]|\.\./.test(arg)) return true;
299
+ if (/:[\\/]|[\\/]{2}/.test(arg)) return true;
300
+ const short = /^-[^-]/.test(arg) ? arg.slice(2) : undefined;
301
+ const starts = [arg, arg.replace(/^[-@+]+/, ""), ...(short !== undefined ? [short] : [])];
302
+ for (let index = 0; index < arg.length; index++) if ("=:@+".includes(arg[index]!)) starts.push(arg.slice(index + 1));
303
+ if (starts.some(start => /^([\\/]|[A-Za-z]:)/.test(start))) return true;
304
+ const dots = /(^|[\\/=:@+])\.\.($|[\\/=:@+])/;
305
+ return dots.test(arg) || (short !== undefined && dots.test(short));
306
+ }
307
+
308
+ /**
309
+ * `commands.<name>.args` lists the caller arguments an entry accepts: an exact string,
310
+ * or a prefix ending in `*` (`test/*`, `--reporter=*`). An option-like caller argument
311
+ * (leading `-`, `@` or `+`) matches only a pattern with the same leading character, so
312
+ * `*` never admits `--output`, `@file` or `+opt`. Absent or empty: no caller arguments.
313
+ * Path confinement (escapesWorkRoot) is checked separately and always applies.
314
+ */
315
+ export function argAllowed(patterns: readonly string[], arg: string): boolean {
316
+ const lead = optionLead(arg);
317
+ return patterns.some(pattern => {
318
+ if (typeof pattern !== "string" || pattern === "") return false;
319
+ if (lead !== undefined && pattern[0] !== lead) return false;
320
+ if (!pattern.endsWith("*")) return pattern === arg;
321
+ return arg.startsWith(pattern.slice(0, -1));
322
+ });
323
+ }
324
+
325
+ /** Validate caller arguments against the allowlist; the message names the argument's position, never its text. */
326
+ export function validateRunArgs(args: readonly unknown[]): string[] {
327
+ if (args.length > RUN_MAX_ARGS) throw refuse(`at most ${RUN_MAX_ARGS} arguments`);
328
+ return args.map((arg, index) => {
329
+ if (typeof arg !== "string" || !RUN_ARG_RE.test(arg)) {
330
+ throw refuse(`argument ${index + 1} refused: 1-200 characters from [A-Za-z0-9_./:=@+-] only (no spaces, quotes or shell metacharacters)`);
331
+ }
332
+ return arg;
333
+ });
334
+ }
335
+
336
+ /** A credential-bearing environment variable name (QA-P13-1-9). */
337
+ export function isCredentialEnv(name: string): boolean {
338
+ if (WORKING_DIRECTORY_ENV.test(name)) return false;
339
+ return CREDENTIAL_ENV_RE.test(name) || PROVIDER_ENV.has(name.toUpperCase());
340
+ }
341
+
342
+ function insideAny(path: string, guards: readonly string[]): boolean {
343
+ return firstOutside([path], guards) === undefined;
344
+ }
345
+
346
+ /**
347
+ * The hardened environment of a run:
348
+ * - dropped: every `npm_*` variable (any case: npm_config_*, NPM_CONFIG_*, inherited
349
+ * npm_lifecycle_* and npm_package_*), NODE_OPTIONS, PREFIX (npm's global-config
350
+ * location) and credential-like variables (isCredentialEnv; no passthrough, QA-G-A2-6);
351
+ * - PATH: relative entries and entries inside the guarded directories removed, so a
352
+ * `#!/usr/bin/env node` tool or a bare name cannot resolve into the repository; each
353
+ * entry is tested as written and by its real path (a link into the repository counts
354
+ * as inside, QA-P13-2-3e);
355
+ * - set: CI=1; on win32 ComSpec (the validated shell) and NoDefaultCurrentDirectoryInExePath=1.
356
+ */
357
+ export function runEnvironment(base: NodeJS.ProcessEnv, platform: NodeJS.Platform, shell?: string,
358
+ options: { guards?: readonly string[] } = {}): NodeJS.ProcessEnv {
359
+ const guards = options.guards ?? [];
360
+ const env: NodeJS.ProcessEnv = {};
361
+ for (const [key, value] of Object.entries(base)) {
362
+ if (value === undefined || /^npm_/i.test(key) || /^(NODE_OPTIONS|PREFIX)$/i.test(key)) continue;
363
+ if (isCredentialEnv(key)) continue;
364
+ if (/^PATH$/i.test(key)) {
365
+ const separator = platform === "win32" ? ";" : ":";
366
+ env[key] = value.split(separator).filter(entry => {
367
+ const dir = entry.replace(/^"|"$/g, "");
368
+ if (dir === "" || !isFullPath(dir, platform) || insideAny(dir, guards)) return false;
369
+ const real = guards.length > 0 ? nativeRealpath(dir) : undefined;
370
+ return real === undefined || !insideAny(real, guards);
371
+ }).join(separator);
372
+ continue;
373
+ }
374
+ env[key] = value;
375
+ }
376
+ const set = (name: string, value: string) => {
377
+ if (platform === "win32") for (const key of Object.keys(env)) if (key.toUpperCase() === name.toUpperCase()) delete env[key];
378
+ env[name] = value;
379
+ };
380
+ set("CI", "1");
381
+ if (platform === "win32") {
382
+ set("NoDefaultCurrentDirectoryInExePath", "1");
383
+ if (shell !== undefined) set("ComSpec", shell);
384
+ }
385
+ return env;
386
+ }
387
+
388
+ function pathEntries(host: RunHost): string[] {
389
+ const raw = envLookup(host.env, "PATH") ?? "";
390
+ return raw.split(host.platform === "win32" ? ";" : ":").map(entry => entry.replace(/^"|"$/g, ""))
391
+ .filter(entry => entry !== "" && isFullPath(entry, host.platform));
392
+ }
393
+
394
+ function sameFile(a: string, b: string): boolean {
395
+ try {
396
+ const x = statSync(a, { bigint: true });
397
+ const y = statSync(b, { bigint: true });
398
+ return x.ino !== 0n && x.ino === y.ino && x.dev === y.dev;
399
+ } catch { return false; }
400
+ }
401
+
402
+ /** An existing file as found, with its real path (QA-P13-1-3: spawn the found path, guard both spellings). */
403
+ interface Found { found: string; real: string }
404
+
405
+ function foundFile(path: string, platform: NodeJS.Platform): Found | undefined {
406
+ if (!isFullPath(path, platform)) return undefined;
407
+ const real = realFileOrUndefined(path);
408
+ return real === undefined ? undefined : { found: pathApi(platform).normalize(path), real };
409
+ }
410
+
411
+ /** An operator-given executable path with a `..` segment is refused, never normalised (QA-P13-2-7). */
412
+ function refuseDotDot(path: string, what: string): void {
413
+ if (/(^|[\\/])\.\.([\\/]|$)/.test(path)) throw refuse(`${what} must not contain a ".." segment: ${path}`);
414
+ }
415
+
416
+ /** Both the found spelling and the real path are outside every guarded directory (G4). */
417
+ function outside(file: Found, guards: readonly string[]): boolean {
418
+ return !insideAny(file.real, guards) && !insideAny(file.found, guards);
419
+ }
420
+
421
+ /** The program name without a Windows extension; both separators count, so a Windows path is named on POSIX too. */
422
+ function stemOf(path: string): string {
423
+ return win32.basename(path).replace(/\.(exe|com|cmd|bat|ps1|js)$/i, "").toLowerCase();
424
+ }
425
+
426
+ /**
427
+ * The node that runs npm-cli.js (verify/runner.ts F.1 rules): the explicit seam; else
428
+ * process.execPath when the runtime really is node (opencode hosts plugins in Bun);
429
+ * else the first node on an absolute PATH entry that is not Bun's temporary link. The
430
+ * first candidate outside the guarded directories wins (G4). The path is returned as
431
+ * found (a version-manager shim keeps its argv[0]); the real path is only checked.
432
+ */
433
+ export function resolveNodeExecutable(host: RunHost, guards: readonly string[]): string {
434
+ const P = pathApi(host.platform);
435
+ if (host.nodeExecPath !== undefined) {
436
+ refuseDotDot(host.nodeExecPath, "node executable");
437
+ const file = foundFile(host.nodeExecPath, host.platform);
438
+ if (file === undefined) throw refuse(`node executable is not an absolute path to a file: ${host.nodeExecPath}`);
439
+ if (!outside(file, guards)) throw refuse(`refusing a node executable inside the work root: ${file.found}`);
440
+ return file.found;
441
+ }
442
+ const candidates: Found[] = [];
443
+ const add = (file: Found | undefined) => { if (file !== undefined && !candidates.some(known => known.found === file.found)) candidates.push(file); };
444
+ const runtimeIsNode = process.versions.bun === undefined && /^node(\.exe)?$/i.test(P.basename(process.execPath))
445
+ && !BUN_NODE_DIR_RE.test(P.basename(P.dirname(process.execPath)));
446
+ if (runtimeIsNode) add(foundFile(process.execPath, host.platform));
447
+ for (const dir of pathEntries(host)) {
448
+ if (BUN_NODE_DIR_RE.test(P.basename(dir))) continue;
449
+ const file = foundFile(P.join(dir, host.platform === "win32" ? "node.exe" : "node"), host.platform);
450
+ if (file === undefined || /^bun(\.exe)?$/i.test(P.basename(file.real))) continue;
451
+ if (!runtimeIsNode && sameFile(file.real, process.execPath)) continue; // Bun's win32 hard link
452
+ add(file);
453
+ }
454
+ const selected = candidates.find(file => outside(file, guards));
455
+ if (selected !== undefined) return selected.found;
456
+ throw refuse(candidates.length === 0 ? "node executable not found (no node runtime and no node on an absolute PATH entry)"
457
+ : `refusing a node executable inside the work root: ${candidates[0]!.found}`);
458
+ }
459
+
460
+ /**
461
+ * npm-cli.js of the node install (never a .cmd/.ps1 shim, never from a guarded
462
+ * directory), looked up beside the node as found AND beside its real path:
463
+ * `<dir>/node_modules/npm/bin/npm-cli.js`, and on POSIX `<dir>/../lib/node_modules/npm/…`
464
+ * (Homebrew links `bin/node` into the Cellar while npm lives under `lib`).
465
+ */
466
+ export function resolveNpmCli(node: string, platform: NodeJS.Platform, guards: readonly string[]): string {
467
+ const P = pathApi(platform);
468
+ const dirs = [P.dirname(node)];
469
+ const real = realFileOrUndefined(node);
470
+ if (real !== undefined && !dirs.includes(P.dirname(real))) dirs.push(P.dirname(real));
471
+ const candidates = dirs.flatMap(dir => [P.join(dir, "node_modules", "npm", "bin", "npm-cli.js"),
472
+ ...(platform === "win32" ? [] : [P.join(dir, "..", "lib", "node_modules", "npm", "bin", "npm-cli.js")])])
473
+ .map(path => foundFile(path, platform)).filter((file): file is Found => file !== undefined);
474
+ const selected = candidates.find(file => outside(file, guards));
475
+ if (selected !== undefined) return selected.found;
476
+ throw refuse(candidates.length === 0 ? `npm-cli.js not found in the node install of ${node}`
477
+ : `refusing npm-cli.js inside the work root: ${candidates[0]!.found}`);
478
+ }
479
+
480
+ /**
481
+ * npm's script shell, as found (never a realpath: busybox and bash pick their mode from
482
+ * argv[0]): on win32 %ComSpec% only when its basename is cmd.exe, else
483
+ * %SystemRoot%\System32\cmd.exe; `/bin/sh` on POSIX. Absolute, existing, outside the guards.
484
+ */
485
+ export function resolveSystemShell(host: RunHost, guards: readonly string[]): string {
486
+ const P = pathApi(host.platform);
487
+ const comspec = envLookup(host.env, "ComSpec");
488
+ const wanted = host.platform === "win32"
489
+ ? [...(comspec !== undefined && P.basename(comspec).toLowerCase() === "cmd.exe" ? [comspec] : []),
490
+ P.join(envLookup(host.env, "SystemRoot") ?? "C:\\Windows", "System32", "cmd.exe")]
491
+ : ["/bin/sh"];
492
+ const selected = wanted.map(path => foundFile(path, host.platform)).find(file => file !== undefined && outside(file, guards));
493
+ if (selected === undefined) throw refuse("no absolute system shell outside the work root (ComSpec cmd.exe / System32\\cmd.exe / /bin/sh)");
494
+ return selected.found;
495
+ }
496
+
497
+ function refuseProgramStem(stem: string, program: string): void {
498
+ if (SHELL_RE.test(stem)) throw refuse(`command executable "${stem}" is a shell; router_run never spawns a shell (use a package.json script)`);
499
+ if (SHIM_RE.test(stem)) throw refuse(`command executable "${stem}" reads repository configuration itself; use an "npm" command or a package.json script`);
500
+ if (stem === "node" || stem === "nodejs" || stem === "npm" || stem === "npm-cli") {
501
+ throw refuse(`command executable ${program} is node or npm: write the bare name "node" or "npm" so the pinned install is used`);
502
+ }
503
+ }
504
+
505
+ /**
506
+ * A configured command's executable (argv[0]): an absolute path to a file outside the
507
+ * guarded directories, or a bare name found on an absolute PATH entry outside them
508
+ * (`.exe`/`.com` only on win32: `.cmd`/`.bat` need a shell). Shells, `env`,
509
+ * package-manager front ends and a node/npm reached by another name or path are
510
+ * refused (by the name and by the real file's name). Returned as found.
511
+ */
512
+ export function resolveCommandExecutable(program: string, host: RunHost, guards: readonly string[]): string {
513
+ const P = pathApi(host.platform);
514
+ refuseProgramStem(stemOf(program), program);
515
+ const runnable = (path: string) => host.platform !== "win32" || /\.(exe|com)$/i.test(path);
516
+ if (host.platform === "win32" && /\.(cmd|bat|ps1)$/i.test(program)) throw refuse(`command executable must be a .exe or .com on Windows: ${program}`);
517
+ const accept = (file: Found) => {
518
+ if (!runnable(file.found) || !runnable(file.real)) throw refuse(`command executable must be a .exe or .com on Windows: ${program}`);
519
+ refuseProgramStem(stemOf(file.real), program);
520
+ return file.found;
521
+ };
522
+ if (isFullPath(program, host.platform)) {
523
+ refuseDotDot(program, "command executable");
524
+ const file = foundFile(program, host.platform);
525
+ if (file === undefined) throw refuse(`command executable not found: ${program}`);
526
+ if (!outside(file, guards)) throw refuse(`refusing a command executable inside the work root: ${file.found}`);
527
+ return accept(file);
528
+ }
529
+ if (!/^[A-Za-z0-9_][A-Za-z0-9_.+-]{0,99}$/.test(program)) throw refuse(`command executable must be absolute or a bare name: ${program}`);
530
+ const name = host.platform === "win32" && !/\.(exe|com)$/i.test(program) ? `${program}.exe` : program;
531
+ const candidates = pathEntries(host).map(dir => foundFile(P.join(dir, name), host.platform))
532
+ .filter((file): file is Found => file !== undefined);
533
+ const selected = candidates.find(file => outside(file, guards));
534
+ if (selected !== undefined) return accept(selected);
535
+ throw refuse(candidates.length === 0 ? `command executable "${program}" not found on an absolute PATH entry`
536
+ : `refusing a command executable inside the work root: ${candidates[0]!.found}`);
537
+ }
538
+
539
+ /** Where npm reads its user and global config files; pinned on the command line (QA-P13-2-2). */
540
+ export interface NpmConfigPins { userconfig: string; globalconfig: string }
541
+
542
+ /**
543
+ * Flags that pin npm's script shell and node options, keep npm in the work root's
544
+ * package, write no npm log file, and pin the user and global config files. Command
545
+ * line flags outrank npmrc files and the environment except `--globalconfig`: npm keeps
546
+ * that value in its default layer, so any npmrc setting `globalconfig` beats it
547
+ * (`config ls -l`: "overridden by user"/"project"). The project `.npmrc` keys that move
548
+ * config files are refused by checkNpmrc (QA-P13-3-3); the user's own `~/.npmrc` may
549
+ * still set `globalconfig` (user-owned, outside every work root).
550
+ */
551
+ export function npmHardeningFlags(shell: string, pins: NpmConfigPins): string[] {
552
+ return [`--script-shell=${shell}`, "--node-options=", "--workspaces=false", "--update-notifier=false", "--logs-max=0",
553
+ `--userconfig=${pins.userconfig}`, `--globalconfig=${pins.globalconfig}`];
554
+ }
555
+
556
+ export { readBoundedRegularFile } from "./git-tools";
557
+
558
+ /** A config file of the work root, bounded and regular; failures are refusals. */
559
+ function readConfigFile(path: string, label: string): string | undefined {
560
+ try { return readBounded(path, MAX_CONFIG_FILE_BYTES, label); } catch (error) { throw refuse(errorMessage(error)); }
561
+ }
562
+
563
+ /** npm's `${VAR}` / `${VAR?}` substitution (@npmcli/config env-replace), with the environment the npm child sees. */
564
+ export function npmEnvReplace(text: string, env: NodeJS.ProcessEnv, platform: NodeJS.Platform = process.platform): string {
565
+ return text.replace(/(?<!\\)(\\*)\$\{([^${}?]+)(\?)?\}/g, (original, escapes: string, name: string, modifier: string | undefined) => {
566
+ const value = platform === "win32" ? envLookup(env, name) : env[name];
567
+ if (escapes.length % 2) return original.slice((escapes.length + 1) / 2);
568
+ return escapes.slice(escapes.length / 2) + (value ?? (modifier === "?" ? "" : `\${${name}}`));
569
+ });
570
+ }
571
+
572
+ type IniDecode = (text: string) => Record<string, unknown>;
573
+ const iniCache = new Map<string, IniDecode>();
574
+
575
+ /**
576
+ * npm's own ini parser, loaded from the resolved npm install (never from the repository):
577
+ * the `.npmrc` checks must read keys exactly as npm does (`\r` line breaks, comments
578
+ * cutting unquoted keys at `;`/`#`, JSON-decoded quoted keys, `key[]` arrays).
579
+ */
580
+ export function loadNpmIni(npmCli: string, platform: NodeJS.Platform, guards: readonly string[]): IniDecode {
581
+ const P = pathApi(platform);
582
+ const dir = P.join(P.dirname(P.dirname(npmCli)), "node_modules", "ini");
583
+ const cached = iniCache.get(dir);
584
+ if (cached !== undefined) return cached;
585
+ const real = nativeRealpath(dir);
586
+ if (real === undefined) throw refuse(`npm's ini parser is missing from the npm install (${dir})`);
587
+ if (insideAny(real, guards) || insideAny(dir, guards)) throw refuse(`refusing npm's ini parser inside the work root: ${dir}`);
588
+ let loaded: { decode?: unknown; parse?: unknown };
589
+ try { loaded = createRequire(npmCli)(dir) as typeof loaded; } catch (error) {
590
+ throw refuse(`cannot load npm's ini parser from ${dir} (${errorMessage(error)})`);
591
+ }
592
+ const decode = typeof loaded.decode === "function" ? loaded.decode : loaded.parse;
593
+ if (typeof decode !== "function") throw refuse(`npm's ini parser at ${dir} has no decode function`);
594
+ const bound: IniDecode = text => (decode as IniDecode)(text);
595
+ iniCache.set(dir, bound);
596
+ return bound;
597
+ }
598
+
599
+ /**
600
+ * The config files npm would use by default, for the npm child's environment: the user
601
+ * config `<HOME | USERPROFILE | homedir>/.npmrc`, and the global config
602
+ * `<prefix>/etc/npmrc` with the prefix of npm's builtin `npmrc` (env-substituted), else
603
+ * npm's default (win32: the node directory; POSIX: its parent; DESTDIR prepended).
604
+ */
605
+ export function npmConfigPins(node: string, npmCli: string, env: NodeJS.ProcessEnv, platform: NodeJS.Platform, guards: readonly string[]): NpmConfigPins {
606
+ const P = pathApi(platform);
607
+ const get = (name: string) => (platform === "win32" ? envLookup(env, name) : env[name]) || undefined;
608
+ const home = get("HOME") ?? (platform === "win32" ? get("USERPROFILE") : undefined) ?? homedir();
609
+ const builtin = readConfigFile(P.join(P.dirname(P.dirname(npmCli)), "npmrc"), "npm's builtin npmrc");
610
+ let prefix: string | undefined;
611
+ if (builtin !== undefined) {
612
+ const value = loadNpmIni(npmCli, platform, guards)(builtin).prefix;
613
+ if (typeof value === "string" && value !== "") prefix = P.resolve(npmEnvReplace(value, env, platform));
614
+ }
615
+ if (prefix === undefined) {
616
+ const execPath = platform === "win32" ? node : (realFileOrUndefined(node) ?? node);
617
+ prefix = platform === "win32" ? P.dirname(execPath) : P.dirname(P.dirname(execPath));
618
+ const destdir = get("DESTDIR");
619
+ if (destdir !== undefined) prefix = P.join(destdir, prefix);
620
+ }
621
+ return { userconfig: P.resolve(home, ".npmrc"), globalconfig: P.resolve(prefix, "etc", "npmrc") };
622
+ }
623
+
624
+ /** The work root's package.json scripts (QA-P13-1-4: every npm plan needs one in the root itself). */
625
+ function packageScripts(root: string, platform: NodeJS.Platform): Record<string, unknown> {
626
+ const text = readConfigFile(pathApi(platform).join(root, "package.json"), "package.json");
627
+ if (text === undefined) throw refuse("no readable package.json in the work root (npm would walk up to another package)");
628
+ let pkg: unknown;
629
+ try { pkg = JSON.parse(text); } catch {
630
+ throw refuse("no readable package.json in the work root (not valid JSON)");
631
+ }
632
+ const scripts = typeof pkg === "object" && pkg !== null ? (pkg as { scripts?: unknown }).scripts : undefined;
633
+ return typeof scripts === "object" && scripts !== null ? scripts as Record<string, unknown> : {};
634
+ }
635
+
636
+ function requireScript(scripts: Record<string, unknown>, name: string): void {
637
+ if (!Object.hasOwn(scripts, name) || typeof scripts[name] !== "string") throw refuse(`package.json has no script "${name}"`);
638
+ }
639
+
640
+ /**
641
+ * Refuse a work-root .npmrc that selects workspaces (npm would run another package's
642
+ * scripts, QA-P13-1-4) or moves npm's config files (`globalconfig` beats the pinned
643
+ * `--globalconfig`, and a planted global or user file could select a workspace
644
+ * unchecked, QA-P13-3-3). Keys are read with npm's own ini parser (QA-P13-2-2) and
645
+ * compared case-insensitively; a key using `${…}` substitution is refused outright
646
+ * (npm substitutes keys too, so `work${X}space` can be `workspace`).
647
+ */
648
+ function checkNpmrc(root: string, platform: NodeJS.Platform, decode: IniDecode): void {
649
+ const text = readConfigFile(pathApi(platform).join(root, ".npmrc"), ".npmrc");
650
+ if (text === undefined) return;
651
+ let parsed: Record<string, unknown>;
652
+ try { parsed = decode(text); } catch { throw refuse("the work root's .npmrc cannot be parsed"); }
653
+ for (const key of Object.keys(parsed)) {
654
+ if (key.includes("${")) throw refuse(`the work root's .npmrc has a key with environment substitution: npm would rewrite it`);
655
+ if (NPMRC_WORKSPACE_KEYS.has(key.toLowerCase())) throw refuse(`the work root's .npmrc sets "${key}": npm would run another package's scripts`);
656
+ if (NPMRC_LOCATION_KEYS.has(key.toLowerCase())) throw refuse(`the work root's .npmrc sets "${key}": npm would load config files the tool does not check`);
657
+ }
658
+ }
659
+
660
+ /** node, npm-cli.js, the shell and the hardening flags of an npm plan, after the work-root config checks. */
661
+ function npmLaunch(root: string, host: RunHost, guards: readonly string[]): { node: string; flags: string[]; cli: string; shell: string } {
662
+ const node = resolveNodeExecutable(host, guards);
663
+ const shell = resolveSystemShell(host, guards);
664
+ const cli = resolveNpmCli(node, host.platform, guards);
665
+ checkNpmrc(root, host.platform, loadNpmIni(cli, host.platform, guards));
666
+ const env = runEnvironment(host.env, host.platform, shell, { guards });
667
+ return { node, cli, shell, flags: npmHardeningFlags(shell, npmConfigPins(node, cli, env, host.platform, guards)) };
668
+ }
669
+
670
+ function effectiveTimeout(ms: unknown): number {
671
+ return typeof ms === "number" && Number.isFinite(ms) && ms > 0 ? Math.min(Math.floor(ms), MAX_TIMER_MS) : DEFAULT_RUN_TIMEOUT_MS;
672
+ }
673
+
674
+ function assertArgv(executable: string, argv: readonly string[], platform: NodeJS.Platform): void {
675
+ if (!isFullPath(executable, platform)) throw new Error("router_run internal error: executable is not absolute");
676
+ for (const arg of argv) {
677
+ if (typeof arg !== "string" || /[\0\r\n]/.test(arg)) throw refuse("command argv elements must be strings without NUL or line breaks");
678
+ }
679
+ }
680
+
681
+ /** cmd.exe cannot use a UNC current directory (it falls back to %SystemRoot%): refuse it for anything npm runs (QA-P13-1-7). */
682
+ function refuseUncForShell(root: string, platform: NodeJS.Platform): void {
683
+ if (platform === "win32" && /^[\\/]{2}/.test(root)) {
684
+ throw refuse("the work root is a UNC path: cmd.exe cannot run scripts there (it would use %SystemRoot%); map a drive letter");
685
+ }
686
+ }
687
+
688
+ /** The bare name `node`/`npm` (with an optional Windows extension) routes to the pinned install. */
689
+ function pinnedProgram(program: string): "node" | "npm" | undefined {
690
+ const match = /^(node|npm)(\.exe|\.cmd)?$/i.exec(program);
691
+ return match ? match[1]!.toLowerCase() as "node" | "npm" : undefined;
692
+ }
693
+
694
+ /**
695
+ * The fixed npm argv of a `commands` entry (QA-P13-1-5): it starts with an allowed
696
+ * script-running command (exact name), `run`/`run-script` name a script of the work
697
+ * root's package.json, and options before `--` are limited to NPM_SAFE_FLAGS.
698
+ */
699
+ function checkNpmArgv(fixed: readonly string[], scripts: Record<string, unknown>, name: string): void {
700
+ const command = fixed[0];
701
+ if (command === undefined || !NPM_RUN_COMMANDS.has(command)) {
702
+ throw refuse(`npm command "${name}" must start with one of ${[...NPM_RUN_COMMANDS].join(", ")}`);
703
+ }
704
+ const end = fixed.indexOf("--") === -1 ? fixed.length : fixed.indexOf("--");
705
+ for (const part of fixed.slice(1, end)) {
706
+ if (part.startsWith("-") && !NPM_SAFE_FLAGS.has(part)) throw refuse(`npm command "${name}" fixes the npm option ${part}; only ${[...NPM_SAFE_FLAGS].join(", ")} are allowed`);
707
+ }
708
+ if (command === "run" || command === "run-script") {
709
+ const script = fixed[1];
710
+ if (script === undefined || script === "--" || script.startsWith("-") || !RUN_NAME_RE.test(script)) {
711
+ throw refuse(`npm command "${name}" must name its script right after "${command}"`);
712
+ }
713
+ requireScript(scripts, script);
714
+ } else {
715
+ requireScript(scripts, command);
716
+ }
717
+ }
718
+
719
+ /**
720
+ * Resolve a call into a spawnable plan. `root` must come from authorizeCwd. Commands
721
+ * win over scripts of the same name. Package.json scripts take no caller arguments
722
+ * (`RunConfig` has no per-script knob): parameterised runs need a `commands` entry
723
+ * declaring `args`, e.g. `{ "argv": ["npm", "run", "test", "--"], "args": ["test/*"] }`.
724
+ * Caller arguments never name a path outside the work root, and an option-like one
725
+ * (`-`, `@`, `+`) needs a pattern with the same lead; a `node` entry takes option-like
726
+ * caller arguments only when its fixed argv starts with the script (QA-P13-1-1).
727
+ */
728
+ export function planRun(input: RunInput, root: string, config: RunConfig, host: RunHost): RunPlan {
729
+ const name = input.script;
730
+ if (typeof name !== "string" || !RUN_NAME_RE.test(name)) throw refuse("invalid entry name");
731
+ const args = validateRunArgs(input.args ?? []);
732
+ const timeoutMs = effectiveTimeout(config.timeoutMs);
733
+ const commands = config.commands ?? {};
734
+ const command = Object.hasOwn(commands, name) ? commands[name] : undefined;
735
+ let executable: string;
736
+ let argv: string[];
737
+ let shell: string | undefined;
738
+ let guards: string[] | undefined;
739
+ const guarded = () => (guards ??= workRootGuards(root));
740
+ if (command !== undefined) {
741
+ if (!Array.isArray(command.argv) || command.argv.length === 0 || command.argv.some(part => typeof part !== "string" || part === "")) {
742
+ throw refuse(`routing.run.commands.${name} has no valid argv`);
743
+ }
744
+ const patterns = command.args ?? [];
745
+ if (args.length > 0 && patterns.length === 0) throw refuse(`"${name}" takes no caller arguments (its entry declares no args)`);
746
+ args.forEach((arg, index) => {
747
+ if (escapesWorkRoot(arg)) throw refuse(`argument ${index + 1} names a path outside the work root (absolute, drive or "..")`);
748
+ if (!argAllowed(patterns, arg)) throw refuse(`argument ${index + 1} is not among the arguments "${name}" declares`);
749
+ });
750
+ const [program, ...fixed] = command.argv as string[];
751
+ const pinned = pinnedProgram(program!);
752
+ if (pinned === "node") {
753
+ if (args.some(arg => optionLead(arg) !== undefined) && (fixed.length === 0 || optionLead(fixed[0]!) !== undefined)) {
754
+ throw refuse(`option-like arguments to the node command "${name}" need a fixed script first in its argv`);
755
+ }
756
+ executable = resolveNodeExecutable(host, guarded());
757
+ argv = [...fixed, ...args];
758
+ } else if (pinned === "npm") {
759
+ refuseUncForShell(root, host.platform);
760
+ checkNpmArgv(fixed, packageScripts(root, host.platform), name);
761
+ // Caller options before `--` would be npm flags and could undo the hardening flags.
762
+ if (!fixed.includes("--") && args.some(arg => arg.startsWith("-"))) throw refuse(`option-like arguments to the npm command "${name}" need a "--" in its argv`);
763
+ const launch = npmLaunch(root, host, guarded());
764
+ executable = launch.node;
765
+ shell = launch.shell;
766
+ argv = [launch.cli, ...launch.flags, ...fixed, ...args];
767
+ } else {
768
+ executable = resolveCommandExecutable(program!, host, guarded());
769
+ argv = [...fixed, ...args];
770
+ }
771
+ } else if (scriptAllowed(config.scripts ?? [], name)) {
772
+ if (args.length > 0) throw refuse(`package.json scripts take no caller arguments; declare a routing.run.commands entry with "args" for "${name}"`);
773
+ refuseUncForShell(root, host.platform);
774
+ requireScript(packageScripts(root, host.platform), name);
775
+ const launch = npmLaunch(root, host, guarded());
776
+ executable = launch.node;
777
+ shell = launch.shell;
778
+ argv = [launch.cli, ...launch.flags, "run", name];
779
+ } else {
780
+ throw refuse(`"${name}" is not in routing.run.scripts or routing.run.commands`);
781
+ }
782
+ assertArgv(executable, argv, host.platform);
783
+ if (shell === undefined && host.platform === "win32") {
784
+ // ComSpec for anything the command starts: the validated system shell when one exists.
785
+ try { shell = resolveSystemShell(host, guarded()); } catch { shell = undefined; }
786
+ }
787
+ return {
788
+ kind: command !== undefined ? "command" : "script", name, executable, argv, cwd: root,
789
+ env: runEnvironment(host.env, host.platform, shell, { guards: guarded() }), timeoutMs,
790
+ };
791
+ }
792
+
793
+ /** Drop the leading partial line (or token) of a tail window: the cut may fall inside a credential. */
794
+ export function dropLeadingPartial(text: string): string {
795
+ const newline = text.indexOf("\n");
796
+ if (newline !== -1) return text.slice(newline + 1);
797
+ const space = text.search(/\s/);
798
+ return space === -1 ? "" : text.slice(space + 1);
799
+ }
800
+
801
+ /** Cap decoded text at RUN_RENDERED_MAX_BYTES of UTF-8 (U+FFFD expansion, QA-P13-1-13). */
802
+ export function capRendered(text: string, max = RUN_RENDERED_MAX_BYTES): string {
803
+ if (Buffer.byteLength(text) <= max) return text;
804
+ const notice = `\n[router_run] rendered output capped at ${max} bytes (undecodable bytes expand when decoded)\n`;
805
+ const kept = Buffer.from(text).subarray(0, Math.max(0, max - Buffer.byteLength(notice))).toString("utf8").replace(/\uFFFD+$/, "");
806
+ return `${dropPartialCredential(kept)}${notice}`;
807
+ }
808
+
809
+ /**
810
+ * Bounded, credential-redacted output: at each cut point the partial token is dropped
811
+ * first (dropPartialCredential at the head's end, dropLeadingPartial at the tail's
812
+ * start), then complete credentials are redacted (stripUrlUserinfo), then the notice.
813
+ * When bytes were omitted, the stderr tail follows unless the shown text already holds
814
+ * it (stdout and stderr have no relative order, see RUN_OUTPUT_BYTES). The decoded text
815
+ * is capped again (capRendered).
816
+ */
817
+ export function renderRunOutput(result: Pick<BoundedResult, "output" | "truncated" | "tail" | "omitted" | "stderrTail" | "stderrTotal">): string {
818
+ const tail = result.tail ?? Buffer.alloc(0);
819
+ const omitted = result.omitted ?? 0;
820
+ if (!result.truncated || (omitted === 0 && result.tail !== undefined)) {
821
+ return capRendered(stripUrlUserinfo(Buffer.concat([result.output, tail]).toString("utf8")));
822
+ }
823
+ const head = stripUrlUserinfo(dropPartialCredential(result.output.toString("utf8")));
824
+ const rest = result.tail === undefined ? "" : stripUrlUserinfo(dropLeadingPartial(tail.toString("utf8")));
825
+ const notice = `[router_run] output truncated: ${omitted > 0 ? `${omitted} bytes omitted; ` : ""}showing at most the first ${RUN_HEAD_BYTES} and the last ${RUN_TAIL_BYTES} bytes, `
826
+ + `plus the last ${RUN_STDERR_TAIL_BYTES} bytes of stderr when not shown (bound ${RUN_OUTPUT_BYTES} bytes)`;
827
+ const body = `${head}${head.endsWith("\n") || head === "" ? "" : "\n"}${notice}\n${rest}`;
828
+ return capRendered(`${body}${stderrSection(result, body)}`);
829
+ }
830
+
831
+ /** The stderr tail of a cut run, unless the shown text already holds it. */
832
+ function stderrSection(result: Pick<BoundedResult, "omitted" | "stderrTail" | "stderrTotal">, shown: string): string {
833
+ const raw = result.stderrTail;
834
+ if (raw === undefined || raw.length === 0 || (result.omitted ?? 0) === 0) return "";
835
+ let text = raw.toString("utf8");
836
+ if ((result.stderrTotal ?? raw.length) > raw.length) text = dropLeadingPartial(text); // the window may start inside a credential
837
+ text = stripUrlUserinfo(text);
838
+ const trimmed = text.trim();
839
+ if (trimmed === "" || shown.includes(trimmed)) return "";
840
+ const label = `[router_run] stderr tail (last ${Buffer.byteLength(text)} bytes; stdout and stderr are separate pipes, so these lines may appear above out of order or have been omitted):`;
841
+ return `${shown.endsWith("\n") || shown === "" ? "" : "\n"}${label}\n${text}${text.endsWith("\n") ? "" : "\n"}`;
842
+ }
843
+
844
+ function statusLine(plan: RunPlan, result: BoundedResult, ms: number): string {
845
+ const duration = `${(ms / 1000).toFixed(1)} s`;
846
+ const what = `${plan.kind === "script" ? "package.json script" : "command"} "${plan.name}"`;
847
+ if (result.failure?.endsWith("timed out")) return `[router_run] ${what}: timed out after ${plan.timeoutMs} ms, process tree killed; exit code: none; duration ${duration}`;
848
+ if (result.failure !== undefined) return `[router_run] ${what}: aborted, process tree killed; exit code: none; duration ${duration}`;
849
+ return `[router_run] ${what}: exit code: ${result.code ?? "none (killed by a signal)"}; duration ${duration}`;
850
+ }
851
+
852
+ /** Spawn a plan (shell: false), bounded by time, abort and 64 KiB of output; never rejects on a timeout or abort. */
853
+ export async function executeRunPlan(plan: RunPlan, signal?: AbortSignal): Promise<{ result: BoundedResult; text: string; ms: number }> {
854
+ const started = performance.now();
855
+ const result = await spawnBounded(plan.executable, plan.argv, plan.cwd, {
856
+ env: plan.env, timeoutMs: plan.timeoutMs, signal, maxBytes: RUN_HEAD_BYTES, tailBytes: RUN_TAIL_BYTES,
857
+ mergeStderr: true, stderrTailBytes: RUN_STDERR_TAIL_BYTES, settleOnFailure: true, label: RUN_LABEL, killGroupOnSettle: true,
858
+ });
859
+ const ms = performance.now() - started;
860
+ const output = renderRunOutput(result);
861
+ return { result, ms, text: `${statusLine(plan, result, ms)}\n${output}${output.endsWith("\n") || output === "" ? "" : "\n"}` };
862
+ }
863
+
864
+ /**
865
+ * The `router_run` tool (not registered here: P2.1 registers it for roles whose grant
866
+ * holds exec, with the bound work-root resolver). Errors and refusals are returned as
867
+ * `[router_run] error: …` text, redacted, never thrown into the session; a non-zero exit
868
+ * is a normal result.
869
+ */
870
+ export function routerRunTool(deps: RunToolDeps) {
871
+ const inputSchema = tool.schema.object({
872
+ script: tool.schema.string().min(1).max(200),
873
+ args: tool.schema.array(tool.schema.string().max(200)).max(RUN_MAX_ARGS).optional(),
874
+ cwd: tool.schema.string().min(1).max(4096),
875
+ }).strict();
876
+ return tool({
877
+ description: "Run one allowlisted package.json script or configured command in this dispatch's work root and report its exit code. "
878
+ + "No shell is spawned by the tool; arguments are accepted only when the entry declares them, each 1-200 characters of [A-Za-z0-9_./:=@+-], never a path outside the work root. "
879
+ + "cwd must be the dispatch's work root. Output (stdout and stderr) is bounded to 64 KiB; URL credentials in it are redacted (best effort, not a secret scanner) "
880
+ + "and credential-like environment variables are not passed to the run; agents and credential stores (ssh-agent, git credential helpers, "
881
+ + "cloud CLI caches in the home directory) stay reachable to scripts. The run is time-limited.",
882
+ args: {
883
+ script: tool.schema.string().describe("Entry name: a script listed in routing.run.scripts (e.g. test, typecheck) or a routing.run.commands entry"),
884
+ args: tool.schema.array(tool.schema.string()).optional().describe("Arguments, only for command entries that declare them"),
885
+ cwd: tool.schema.string().describe("Absolute path of the dispatch's work root"),
886
+ },
887
+ async execute(input, context) {
888
+ try {
889
+ const platform = deps.platform ?? process.platform;
890
+ // Authority first (P-10, I9, QA-P13-2-8): nothing else is looked at for an unbound session.
891
+ const answer = checkWorkRootAnswer(deps.resolveWorkRoot(context.sessionID));
892
+ if (!answer.role) throw refuse("router_run is only available to role sessions (this session is not one)");
893
+ if (answer.root === null) throw refuse("this session has no bound work root (I9); router_run only runs in a dispatch's work root");
894
+ const root = authorizeCwd(answer.root, (input as { cwd?: unknown } | undefined)?.cwd, platform);
895
+ const parsed = inputSchema.parse(input);
896
+ const plan = planRun(parsed, root, deps.config(), {
897
+ platform, env: deps.env ?? process.env,
898
+ ...(deps.nodeExecPath !== undefined ? { nodeExecPath: deps.nodeExecPath } : {}),
899
+ });
900
+ const at = Date.now();
901
+ const { result, text } = await executeRunPlan(plan, context.abort);
902
+ const exitCode = result.failure === undefined ? result.code : null;
903
+ try { deps.recordRun?.({ sessionID: context.sessionID, script: plan.name, exitCode, at }); } catch (error) {
904
+ console.warn(`[model-router] router_run: could not record the run (${errorMessage(error)})`);
905
+ }
906
+ return text;
907
+ } catch (error) {
908
+ const prefix = error instanceof RunRefused ? "refused: " : "";
909
+ return `[router_run] error: ${prefix}${stripUrlUserinfo(errorMessage(error))}`;
910
+ }
911
+ },
912
+ });
913
+ }