opencode-model-router 2.9.0 → 2.10.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.
@@ -81,6 +81,14 @@ function lstatOrUndefined(path: string): Stats | undefined {
81
81
  }
82
82
  }
83
83
 
84
+ /** stat (following links) that reports a missing path, a dangling link or a file used as a directory as undefined. */
85
+ function statOrUndefined(path: string): Stats | undefined {
86
+ try { return statSync(path); } catch (error) {
87
+ if (errorCode(error) === "ENOENT" || errorCode(error) === "ENOTDIR") return undefined;
88
+ throw error;
89
+ }
90
+ }
91
+
84
92
  function isDirectory(path: string): boolean {
85
93
  try { return statSync(path).isDirectory(); } catch (error) {
86
94
  if (errorCode(error) === "ENOENT" || errorCode(error) === "ENOTDIR") return false;
@@ -162,21 +170,247 @@ export function gitEnvironment(extra: Record<string, string> = {}): NodeJS.Proce
162
170
  * Every transport refused on the command line. A repository's `protocol.<name>.allow=always` beats a
163
171
  * generic `protocol.allow=never`, and GIT_NO_LAZY_FETCH is honoured only from git 2.44, so a partial
164
172
  * clone's promisor (an `ext::` command, say) could otherwise run on a lazy fetch. Command-line `-c`
165
- * overrides repository config; no router git call needs a transport.
173
+ * overrides repository config; no router git call needs a transport. A repository's own `protocol.<name>.allow` for any other
174
+ * name (a remote helper) is set to `never` by {@link repositoryOnlyDriverArgs}.
166
175
  */
167
- export const PROTOCOL_HARDENING: readonly string[] = Object.freeze(["ext", "file", "ssh", "git", "http", "https"]
176
+ export const PROTOCOL_HARDENING: readonly string[] = Object.freeze(["ext", "file", "ssh", "git", "http", "https", "ftp", "ftps"]
168
177
  .flatMap(name => ["-c", `protocol.${name}.allow=never`]).concat(["-c", "protocol.allow=never"]));
169
178
 
170
179
  export function hardeningArgs(): string[] {
171
180
  return ["--no-optional-locks", "--no-pager", "-c", "core.pager=cat", "-c", "core.fsmonitor=false", "-c", "diff.external=",
172
181
  "-c", `core.hooksPath=${NULL_DEVICE}`, ...PROTOCOL_HARDENING,
173
182
  "-c", "maintenance.auto=false", "-c", "gc.auto=0", "-c", "color.ui=false",
174
- // G2: signature display would run gpg.program; blank every signing program too.
183
+ // G2: signature display would run gpg.program; blank every signing program too (and the ssh key lookup command).
175
184
  "-c", "log.showSignature=false", "-c", "gpg.program=", "-c", "gpg.ssh.program=", "-c", "gpg.x509.program=",
185
+ "-c", "gpg.ssh.defaultKeyCommand=",
176
186
  // G3: diff's opportunistic index refresh writes .git even with --no-optional-locks.
177
187
  "-c", "diff.autoRefreshIndex=false", "-c", "core.splitIndex=false", "-c", "index.threads=1"];
178
188
  }
179
189
 
190
+ /**
191
+ * The read prefix of a router-run git in the work root that keeps git's own index semantics (the default work-root snapshot,
192
+ * the reference runner): no fsmonitor, no hooks (the `hardeningArgs()` null-device hooksPath, so no `post-index-change` on an
193
+ * index write), no ssh key lookup command, no external diff (defence in depth: every patch diff also passes `--no-ext-diff`),
194
+ * no transport. Unlike `hardeningArgs()` it keeps `diff.autoRefreshIndex`: turning the refresh off would show stat-only dirty
195
+ * files in `diff HEAD` and change the snapshot's fingerprint. A later `-c core.hooksPath=…` still wins over the null device.
196
+ */
197
+ export function workRootReadArgs(): string[] {
198
+ return ["-c", "core.fsmonitor=false", "-c", `core.hooksPath=${NULL_DEVICE}`, "-c", "gpg.ssh.defaultKeyCommand=", "-c", "diff.external=",
199
+ ...PROTOCOL_HARDENING];
200
+ }
201
+
202
+ /**
203
+ * Repository settings through which a work-root git could run a program: filter clean/smudge/process and merge drivers,
204
+ * `protocol.<name>.allow` (a remote helper), and the include directives that can bring more of them in.
205
+ */
206
+ const REPOSITORY_DRIVER_QUERY = "^(filter\\..+\\.(clean|smudge|process)|merge\\..+\\.driver|protocol\\..+\\.allow|include\\.path|includeif\\..+\\.path)$";
207
+ const DRIVER_KEY = /^(?:filter\.(.+)\.(?:clean|smudge|process)|merge\..+\.driver)$/;
208
+ const PROTOCOL_KEY = /^protocol\..+\.allow$/;
209
+ const INCLUDE_KEY = /^(?:include\.path|includeif\..+\.path)$/;
210
+ /** The configuration scopes the user controls; every other scope (local, worktree, an unknown one) is the repository's. */
211
+ const USER_SCOPES: ReadonlySet<string> = new Set(["system", "global", "command"]);
212
+ /** git's own include depth bound (MAX_INCLUDE_DEPTH), and the include targets one listing reads at most. */
213
+ const MAX_INCLUDE_DEPTH = 10;
214
+ const MAX_INCLUDE_TARGETS = 50;
215
+
216
+ /**
217
+ * Every driver/protocol/include setting with the scope and origin that set it (`git config --show-scope --show-origin`, git
218
+ * >= 2.26), NUL-separated: `<scope>\0<origin>\0<key>\n<value>\0`. Exit 1: none is set. Parsed by {@link parseDriverListing}.
219
+ */
220
+ export const DRIVER_SCOPE_ARGS: readonly string[] = Object.freeze(["config", "-z", "--show-scope", "--show-origin", "--get-regexp", REPOSITORY_DRIVER_QUERY]);
221
+
222
+ /** One entry of a {@link DRIVER_SCOPE_ARGS} listing; `value` is undefined for a value-less key. */
223
+ export interface DriverEntry { readonly scope: string; readonly origin: string; readonly key: string; readonly value: string | undefined }
224
+
225
+ function splitConfigEntry(field: string): { key: string; value: string | undefined } {
226
+ const newline = field.indexOf("\n");
227
+ return newline === -1 ? { key: field, value: undefined } : { key: field.slice(0, newline), value: field.slice(newline + 1) };
228
+ }
229
+
230
+ /** The entries of a {@link DRIVER_SCOPE_ARGS} listing, in git's order (a later value of a key wins). */
231
+ export function parseDriverListing(listing: string): DriverEntry[] {
232
+ const fields = listing.split("\0");
233
+ const entries: DriverEntry[] = [];
234
+ for (let index = 0; index + 2 < fields.length; index += 3) {
235
+ entries.push({ scope: fields[index]!, origin: fields[index + 1]!, ...splitConfigEntry(fields[index + 2]!) });
236
+ }
237
+ return entries;
238
+ }
239
+
240
+ /**
241
+ * Router-run git in the work root must not run a program the repository configured. From a {@link DRIVER_SCOPE_ARGS} listing
242
+ * (and the `included` driver/protocol keys of every repository include target, whatever its condition):
243
+ * - `-c <key>=` for every filter clean/smudge/process and merge driver whose effective value comes from the repository's own
244
+ * configuration (local, worktree, or a file those include), and for every included one, unless the value is also set,
245
+ * identically, in the system, global or command-line configuration. A global LFS filter and its `git lfs install --local`
246
+ * copy are kept; a repository without its own drivers gets no arguments.
247
+ * - a blanked filter gets `-c filter.<name>.required=<required>`: `false` for a read-only snapshot (as `inspectGit`), `true`
248
+ * where git writes (the executor, the reference), so git refuses instead of storing or checking out unfiltered content.
249
+ * - `-c protocol.<name>.allow=never` for every `protocol.<name>.allow` the repository sets.
250
+ * Throws when a key cannot be blanked (`-c` splits at the first `=`).
251
+ */
252
+ export function repositoryOnlyDriverArgs(listing: string,
253
+ options: { required?: boolean; included?: readonly { key: string; value: string | undefined }[] } = {}): string[] {
254
+ const userValues = new Map<string, Set<string>>();
255
+ const effective = new Map<string, { scope: string; value: string | undefined }>();
256
+ const protocols = new Set<string>();
257
+ for (const { scope, key, value } of parseDriverListing(listing)) {
258
+ const user = USER_SCOPES.has(scope);
259
+ if (PROTOCOL_KEY.test(key)) {
260
+ if (!user) protocols.add(key);
261
+ continue;
262
+ }
263
+ if (!DRIVER_KEY.test(key)) continue;
264
+ // A value-less key (boolean true) names no program git could run; it never matches a user value.
265
+ if (user && value !== undefined) {
266
+ const values = userValues.get(key) ?? new Set<string>();
267
+ values.add(value);
268
+ userValues.set(key, values);
269
+ }
270
+ effective.set(key, { scope, value }); // the last value wins, as for git
271
+ }
272
+ const trusted = (key: string, value: string | undefined) => value !== undefined && userValues.get(key)?.has(value) === true;
273
+ const blank = new Set<string>();
274
+ for (const [key, { scope, value }] of effective) if (!USER_SCOPES.has(scope) && !trusted(key, value)) blank.add(key);
275
+ for (const { key, value } of options.included ?? []) {
276
+ if (PROTOCOL_KEY.test(key)) protocols.add(key);
277
+ else if (DRIVER_KEY.test(key) && !trusted(key, value)) blank.add(key);
278
+ }
279
+ const args: string[] = [];
280
+ const filters = new Set<string>();
281
+ const refuse = () => new Error("Refusing repository: a filter/merge driver or protocol name contains '=' and cannot be neutralized");
282
+ for (const key of blank) {
283
+ if (key.includes("=")) throw refuse();
284
+ args.push("-c", `${key}=`);
285
+ const filter = /^filter\.(.+)\.(?:clean|smudge|process)$/.exec(key);
286
+ if (filter) filters.add(`filter.${filter[1]}.required=${options.required === true}`);
287
+ }
288
+ for (const setting of filters) args.push("-c", setting);
289
+ for (const key of protocols) {
290
+ if (key.includes("=")) throw refuse();
291
+ args.push("-c", `${key}=never`);
292
+ }
293
+ return args;
294
+ }
295
+
296
+ /** One `git config` query, run where and as the protected command runs: its exit code and stdout. */
297
+ export type DriverQuery = (args: readonly string[]) => Promise<{ readonly code: number | null; readonly stdout: string }>;
298
+
299
+ /** The file an include directive names (git's rules: `~/`, absolute, else relative to the including file); undefined: none. */
300
+ function includeTarget(value: string | undefined, base: string | undefined): string | undefined {
301
+ if (value === undefined || value === "") return undefined; // git refuses a value-less include itself
302
+ if (value === "~" || value.startsWith("~/") || value.startsWith("~\\")) return join(process.env.HOME ?? homedir(), value.slice(1));
303
+ if (value.startsWith("~") || value.startsWith("%(prefix)")) {
304
+ throw new Error(`Refusing repository: the config include ${JSON.stringify(value)} cannot be resolved`);
305
+ }
306
+ if (isAbsolute(value) || win32.isAbsolute(value)) return value;
307
+ return base === undefined ? undefined : resolve(base, value); // a relative include outside a file: git refuses it
308
+ }
309
+
310
+ /**
311
+ * {@link repositoryOnlyDriverArgs} from `query` ({@link DRIVER_SCOPE_ARGS}, then `config --file <target>` for every include
312
+ * directive the repository's configuration holds, nested ones too, whatever its condition: a linked worktree's `gitdir:` or a
313
+ * slot's `onbranch:` may enable a target the listing's own context does not). `cwd`: where the listing ran (a relative origin
314
+ * is resolved against it). A missing target is skipped, as git skips it, and so is a dangling link on every platform (as
315
+ * POSIX git does; Git for Windows may fail on one instead); an unreadable, network or device target (on win32 also a
316
+ * reserved device name such as `NUL` or `com1.cfg`), or more than {@link MAX_INCLUDE_TARGETS} targets or
317
+ * {@link MAX_INCLUDE_DEPTH} levels, throws (fail closed).
318
+ */
319
+ export async function collectRepositoryDriverArgs(query: DriverQuery, cwd: string, options: { required?: boolean } = {}): Promise<string[]> {
320
+ const listed = await query(DRIVER_SCOPE_ARGS);
321
+ if (listed.code === 1) return []; // nothing set anywhere
322
+ if (listed.code !== 0) throw new Error(`Cannot read the repository's driver configuration (exit ${listed.code})`);
323
+ const pending: { path: string; depth: number }[] = [];
324
+ for (const { scope, origin, key, value } of parseDriverListing(listed.stdout)) {
325
+ if (USER_SCOPES.has(scope) || !INCLUDE_KEY.test(key)) continue;
326
+ const base = origin.startsWith("file:") ? dirname(resolve(cwd, origin.slice("file:".length))) : undefined;
327
+ const path = includeTarget(value, base);
328
+ if (path !== undefined) pending.push({ path, depth: 1 });
329
+ }
330
+ const included: { key: string; value: string | undefined }[] = [];
331
+ const seen = new Set<string>();
332
+ for (let next = pending.shift(); next !== undefined; next = pending.shift()) {
333
+ const { path, depth } = next;
334
+ if (depth > MAX_INCLUDE_DEPTH || seen.size >= MAX_INCLUDE_TARGETS) {
335
+ throw new Error("Refusing repository: too many or too deeply nested config includes");
336
+ }
337
+ const id = foldCase(resolve(path));
338
+ if (seen.has(id)) continue;
339
+ seen.add(id);
340
+ if (isNetworkOrDevicePath(path)) throw new Error(`Refusing repository: the config include ${path} is a network or device path`);
341
+ // `C:\dir\NUL`, `nul.txt`, `COM1:`: Windows opens the device whatever the directory (G13, as validatePath).
342
+ if (process.platform === "win32" && WINDOWS_DEVICE.test(win32.basename(path).split(/[.:]/)[0]!.trimEnd())) {
343
+ throw new Error(`Refusing repository: the config include ${path} names a reserved Windows device`);
344
+ }
345
+ // Links are followed: a dangling link is skipped like a missing include, on every platform. POSIX git skips it too (its
346
+ // access() follows the link); Git for Windows' access() may not, so it may fail on the link instead (not tested).
347
+ if (statOrUndefined(path) === undefined) continue;
348
+ const read = await query(["config", "--file", path, "-z", "--get-regexp", REPOSITORY_DRIVER_QUERY]);
349
+ if (read.code === 1) continue;
350
+ if (read.code !== 0) throw new Error(`Cannot read the config include ${path} (exit ${read.code})`);
351
+ for (const field of read.stdout.split("\0")) {
352
+ if (field === "") continue;
353
+ const entry = splitConfigEntry(field);
354
+ if (!INCLUDE_KEY.test(entry.key)) {
355
+ included.push(entry);
356
+ continue;
357
+ }
358
+ const target = includeTarget(entry.value, dirname(resolve(path)));
359
+ if (target !== undefined) pending.push({ path: target, depth: depth + 1 });
360
+ }
361
+ }
362
+ return repositoryOnlyDriverArgs(listed.stdout, { required: options.required === true, included });
363
+ }
364
+
365
+ /** The user's own configuration locations, which plain git honours (git-tools strips every other GIT_* variable). */
366
+ function userConfigVariables(): Record<string, string> {
367
+ const passed: Record<string, string> = {};
368
+ for (const name of ["GIT_CONFIG_SYSTEM", "GIT_CONFIG_GLOBAL", "GIT_CONFIG_NOSYSTEM"]) {
369
+ const value = process.env[name];
370
+ if (value !== undefined) passed[name] = value;
371
+ }
372
+ return passed;
373
+ }
374
+
375
+ /**
376
+ * The environment of a driver listing for a command that runs with `runEnv` (default: this process's environment): the same
377
+ * variables, so the listing sees what the command will see (GIT_DIR, GIT_CONFIG_PARAMETERS/COUNT …), except that the user's
378
+ * own system/global configuration is visible (GIT_CONFIG_SYSTEM/GLOBAL/NOSYSTEM as this process has them: the trusted values a
379
+ * repository copy is compared with, even for a run that hides them) and the legacy GIT_CONFIG, which only `git config`
380
+ * honours (it would replace the repository's configuration in the listing alone), is dropped.
381
+ */
382
+ export function driverListingEnvironment(runEnv?: NodeJS.ProcessEnv): NodeJS.ProcessEnv {
383
+ const env: NodeJS.ProcessEnv = {};
384
+ for (const [key, value] of Object.entries(runEnv ?? process.env)) {
385
+ if (!/^GIT_CONFIG(?:_GLOBAL|_SYSTEM|_NOSYSTEM)?$/i.test(key)) env[key] = value;
386
+ }
387
+ return { ...env, ...userConfigVariables(), GIT_OPTIONAL_LOCKS: "0", GIT_TERMINAL_PROMPT: "0", GIT_NO_LAZY_FETCH: "1" };
388
+ }
389
+
390
+ /**
391
+ * {@link collectRepositoryDriverArgs} for a router-run git in `root`, spawned directly: `executable` (default the router's git
392
+ * outside the work-root guards of `root`), `location` (the command's `--git-dir=`/`--work-tree=` options), `env` (the
393
+ * command's environment, see {@link driverListingEnvironment}), `required` (see {@link repositoryOnlyDriverArgs}). Throws when
394
+ * the configuration cannot be read: the caller has no run (fail closed).
395
+ */
396
+ export async function repositoryDriverArgs(root: string, options: {
397
+ executable?: string; signal?: AbortSignal; timeoutMs?: number; required?: boolean; location?: readonly string[]; env?: NodeJS.ProcessEnv;
398
+ } = {}): Promise<string[]> {
399
+ const executable = options.executable ?? gitExecutable(workRootGuards(root));
400
+ const env = driverListingEnvironment(options.env);
401
+ const deadline = performance.now() + (options.timeoutMs ?? DEADLINE_MS);
402
+ const query: DriverQuery = async (args) => {
403
+ const remaining = deadline - performance.now();
404
+ if (remaining <= 0) throw new Error("Git driver configuration query timed out");
405
+ const result = await spawnBounded(executable, [...hardeningArgs(), ...(options.location ?? []), ...args], root,
406
+ { env, signal: options.signal, timeoutMs: remaining, maxBytes: 1024 * 1024 });
407
+ if (result.truncated) throw new Error("Git driver configuration exceeds its size bound");
408
+ if (result.code !== 0 && result.code !== 1) throw queryFailure("Cannot read the repository's driver configuration", result);
409
+ return { code: result.code, stdout: result.output.toString("utf8") };
410
+ };
411
+ return collectRepositoryDriverArgs(query, root, { required: options.required === true });
412
+ }
413
+
180
414
  function validateInput(operation: GitOperation, input: GitInput): { ref?: string } {
181
415
  if (!GIT_OPERATIONS.includes(operation)) throw new Error("Invalid git operation");
182
416
  if (input.path && isSensitivePath(input.path)) throw new Error("Sensitive git path refused; use read (asks for approval)");
@@ -801,11 +1035,7 @@ const inheritedCache = new Map<string, readonly string[]>();
801
1035
  * and configuration location.
802
1036
  */
803
1037
  async function inheritedConfig(executable: string, budget: Budget): Promise<readonly string[]> {
804
- const passed: Record<string, string> = {};
805
- for (const name of ["GIT_CONFIG_SYSTEM", "GIT_CONFIG_GLOBAL", "GIT_CONFIG_NOSYSTEM"]) {
806
- const value = process.env[name];
807
- if (value !== undefined) passed[name] = value;
808
- }
1038
+ const passed = userConfigVariables();
809
1039
  const key = JSON.stringify([executable, passed, process.env.HOME, process.env.USERPROFILE, process.env.XDG_CONFIG_HOME]);
810
1040
  const cached = inheritedCache.get(key);
811
1041
  if (cached) return cached;
@@ -7,20 +7,44 @@ export type PermissionEffect = "allow" | "deny" | "ask";
7
7
  export type PermissionMap = Record<string, PermissionEffect | Record<string, PermissionEffect>>;
8
8
  export interface PermissionRule { action: string; resource: string; effect: PermissionEffect }
9
9
 
10
- /** Reviewed host shape, not a call into the plugin's bundled SDK pretending to
11
- * describe the running host. Unknown shapes take the conservative branch. */
12
- const KNOWN_HOST_DEFAULTS: readonly PermissionRule[] = [
13
- { action: "*", resource: "*", effect: "allow" },
14
- { action: "external_directory", resource: "*", effect: "ask" },
15
- { action: "read", resource: "*.env", effect: "ask" },
16
- { action: "read", resource: "*.env.*", effect: "ask" },
17
- { action: "read", resource: "*.env.example", effect: "allow" },
10
+ /** Reviewed host shapes of `Agent.Info.default(id).permissions`, not a call into
11
+ * the plugin's bundled SDK pretending to describe the running host. The longest
12
+ * shape that prefixes the inherited rules is the host default; unknown shapes
13
+ * take the conservative branch. */
14
+ const KNOWN_HOST_DEFAULTS: readonly (readonly PermissionRule[])[] = [
15
+ // Host 2.0.22.
16
+ [
17
+ { action: "*", resource: "*", effect: "allow" },
18
+ { action: "external_directory", resource: "*", effect: "ask" },
19
+ { action: "read", resource: "*.env", effect: "ask" },
20
+ { action: "read", resource: "*.env.*", effect: "ask" },
21
+ { action: "read", resource: "*.env.example", effect: "allow" },
22
+ ],
23
+ // Host 2.0.31: the external_directory default is gone.
24
+ [
25
+ { action: "*", resource: "*", effect: "allow" },
26
+ { action: "read", resource: "*.env", effect: "ask" },
27
+ { action: "read", resource: "*.env.*", effect: "ask" },
28
+ { action: "read", resource: "*.env.example", effect: "allow" },
29
+ ],
18
30
  ];
31
+
32
+ /** Length of the longest known host default prefixing `inherited`, or undefined. */
33
+ function knownHostDefaultsLength(inherited: readonly PermissionRule[]): number | undefined {
34
+ let longest: number | undefined;
35
+ for (const shape of KNOWN_HOST_DEFAULTS) {
36
+ if (shape.length > (longest ?? -1) && shape.every((rule, i) => inherited[i]?.action === rule.action
37
+ && inherited[i]?.resource === rule.resource && inherited[i]?.effect === rule.effect)) longest = shape.length;
38
+ }
39
+ return longest;
40
+ }
19
41
  export const READ_ONLY_CANARIES = ["shell", "bash", "edit", "write", "patch", "execute", "subagent", "task", "webfetch", "websearch", "browser",
20
42
  `router_readonly_canary_${randomUUID()}`];
21
43
 
22
- /** Mirrors host v2.0.22 Permission.evaluate + util/wildcard.ts: last match,
23
- * slash normalization, ? and *, dotall, Windows case folding, default ask. */
44
+ /** Mirrors host Permission.evaluate + util/wildcard.ts as reviewed at v2.0.22
45
+ * (host core, not shipped in the @opencode/* packages; their Permission.Rule
46
+ * schema is unchanged in 2.0.31): last match, slash normalization, ? and *,
47
+ * dotall, Windows case folding, default ask. */
24
48
  export function permissionMatches(input: string, pattern: string): boolean {
25
49
  let escaped = pattern.replaceAll("\\", "/").replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*").replace(/\?/g, ".");
26
50
  if (escaped.endsWith(" .*")) escaped = escaped.slice(0, -3) + "( .*)?";
@@ -81,9 +105,9 @@ function publishPluginPermissions(name: string, policy: readonly PermissionRule[
81
105
  export function publishReadOnlyPermissions(name: string, policy: readonly PermissionRule[], inherited: readonly PermissionRule[], warn: (message: string) => void, opts: { plugin?: boolean } = {}): PermissionRule[] {
82
106
  if (opts.plugin === true) return publishPluginPermissions(name, policy, inherited, warn);
83
107
  const canaries = READ_ONLY_CANARIES;
84
- const recognised = KNOWN_HOST_DEFAULTS.every((rule, i) => inherited[i]?.action === rule.action
85
- && inherited[i]?.resource === rule.resource && inherited[i]?.effect === rule.effect);
86
- const tail = inherited.slice(recognised ? KNOWN_HOST_DEFAULTS.length : 0);
108
+ const defaults = knownHostDefaultsLength(inherited);
109
+ const recognised = defaults !== undefined;
110
+ const tail = inherited.slice(defaults ?? 0);
87
111
  const allowed = new Set(policy.filter(rule => rule.effect === "allow" && rule.action !== "*").map(rule => rule.action));
88
112
  // Keep P1's rejection of non-explicit allows: projecting a drifted host's
89
113
  // '* allow' onto read would overwrite the policy's sensitive-path asks.
@@ -742,6 +742,35 @@ function pinnedProgram(program: string): "node" | "npm" | undefined {
742
742
  return match ? match[1]!.toLowerCase() as "node" | "npm" : undefined;
743
743
  }
744
744
 
745
+ /** Discoverability only: this does not validate or authorise a command or its arguments. */
746
+ function argumentCommands(config: RunConfig, script?: string) {
747
+ const sameScript = (argv: readonly string[]): boolean => {
748
+ const [program, command, name] = argv;
749
+ if (program === undefined || pinnedProgram(program) !== "npm") return false;
750
+ if (command === "run" || command === "run-script") return name === script && argv.slice(3).includes("--");
751
+ return script === "test" && command === "test" && argv.slice(2).includes("--");
752
+ };
753
+ return Object.entries(config.commands ?? {})
754
+ .filter(([, command]) => (command.args?.length ?? 0) > 0)
755
+ .sort(([, a], [, b]) => Number(sameScript(b.argv)) - Number(sameScript(a.argv)));
756
+ }
757
+
758
+ function scriptArgumentsHint(config: RunConfig, script: string): string {
759
+ const commands = argumentCommands(config, script);
760
+ return commands.length === 0
761
+ ? `declare a routing.run.commands entry with "args" for "${script}"`
762
+ : `use ${commands.map(([name, command]) => `script "${name}" (args: ${command.args!.join(", ")})`).join("; or ")}`;
763
+ }
764
+
765
+ /** Registration-time summary; execution still reads the current config on every call. */
766
+ function argumentCommandsDescription(config: RunConfig): string {
767
+ const commands = argumentCommands(config);
768
+ if (commands.length === 0) return "";
769
+ const bounded = (text: string, max: number) => text.length <= max ? text : `${text.slice(0, max - 1)}…`;
770
+ const entries = commands.slice(0, 5).map(([name, command]) => `${bounded(name, 64)} (args: ${bounded(command.args!.join(", "), 100)})`);
771
+ return ` Commands accepting arguments: ${entries.join("; ")}${commands.length > 5 ? "; …" : ""}.`;
772
+ }
773
+
745
774
  /**
746
775
  * The fixed npm argv of a `commands` entry (QA-P13-1-5): it starts with an allowed
747
776
  * script-running command (exact name), `run`/`run-script` name a script of the work
@@ -821,7 +850,7 @@ export function planRun(input: RunInput, root: string, config: RunConfig, host:
821
850
  argv = [...fixed, ...args];
822
851
  }
823
852
  } else if (scriptAllowed(config.scripts ?? [], name)) {
824
- if (args.length > 0) throw refuse(`package.json scripts take no caller arguments; declare a routing.run.commands entry with "args" for "${name}"`);
853
+ if (args.length > 0) throw refuse(`package.json scripts take no caller arguments; ${scriptArgumentsHint(config, name)}`);
825
854
  refuseUncForShell(root, host.platform);
826
855
  requireScript(packageScripts(root, host.platform), name);
827
856
  const launch = npmLaunch(root, host, guarded());
@@ -930,7 +959,8 @@ export function routerRunTool(deps: RunToolDeps) {
930
959
  + "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. "
931
960
  + "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) "
932
961
  + "and credential-like environment variables are not passed to the run; agents and credential stores (ssh-agent, git credential helpers, "
933
- + "cloud CLI caches in the home directory) stay reachable to scripts. The run is time-limited.",
962
+ + "cloud CLI caches in the home directory) stay reachable to scripts. The run is time-limited."
963
+ + argumentCommandsDescription(deps.config()),
934
964
  args: {
935
965
  script: tool.schema.string().describe("Entry name: a script listed in routing.run.scripts (e.g. test, typecheck) or a routing.run.commands entry"),
936
966
  args: tool.schema.array(tool.schema.string()).optional().describe("Arguments, only for command entries that declare them"),
@@ -989,6 +989,15 @@ export function runnerDescription(agent: string | undefined): string {
989
989
  return agent ? `Router ${agent} delegation` : RUNNER_VERIFICATION_DESCRIPTION;
990
990
  }
991
991
 
992
+ /**
993
+ * #174: whether `description` has the shape {@link runnerDescription} gives. A shape only: an orchestrator may give its own
994
+ * dispatch the same text, so a caller treats it as a fallback signal, never as proof that the child is the runner's.
995
+ */
996
+ export function isRunnerDescription(description: string): boolean {
997
+ // An agent name is one word (`[\w.-]+`): a longer title such as "Router fix the parser delegation" is never the runner's.
998
+ return /^Router (?:[\w.-]+ delegation|result verification)$/.test(description);
999
+ }
1000
+
992
1001
  interface RunnerMark {
993
1002
  /** Unique per announcement: a withdrawal removes exactly its own mark (QA-INT-3). */
994
1003
  readonly id: number;
@@ -71,7 +71,38 @@ export function applyPatchHeaderPaths(args: unknown): string[] {
71
71
  */
72
72
  function hostPatchPaths(a: Record<string, unknown>): string[] | undefined {
73
73
  const text = PATCH_KEYS.map(key => a[key]).find(value => typeof value === "string");
74
- if (typeof text !== "string") return undefined;
74
+ return typeof text === "string" ? patchTextPaths(text) : undefined;
75
+ }
76
+
77
+ /**
78
+ * The paths of every patch text key of `a` (the git metadata guard's widest reading: a host that took another key than the first
79
+ * string would write those): the host's own text ({@link hostPatchPaths}) must be readable, another key's text adds its paths when
80
+ * it is and is ignored when it has no header. Undefined when the host's own text is unreadable, or (#161, fail closed) another
81
+ * key's text has a header line but cannot be read.
82
+ */
83
+ function everyPatchTextPaths(a: Record<string, unknown>): string[] | undefined {
84
+ const host = hostPatchPaths(a);
85
+ if (host === undefined) return undefined;
86
+ const texts = PATCH_KEYS.map(key => a[key]).filter((value): value is string => typeof value === "string");
87
+ const paths = [...host];
88
+ for (const text of texts) {
89
+ const own = patchTextPaths(text);
90
+ if (own === undefined && hasPatchHeader(text)) return undefined;
91
+ paths.push(...(own ?? []));
92
+ }
93
+ return paths;
94
+ }
95
+
96
+ /** Whether a patch text has a header line as {@link patchTextPaths} reads them (leading blanks allowed). */
97
+ function hasPatchHeader(text: string): boolean {
98
+ return text.split(/\r?\n/).some(raw => {
99
+ const line = raw.trimStart();
100
+ return HOST_PATCH_HEADERS.some(prefix => line.startsWith(prefix));
101
+ });
102
+ }
103
+
104
+ /** The header paths of one patch text; undefined when a header names no path or there is none. */
105
+ function patchTextPaths(text: string): string[] | undefined {
75
106
  const paths: string[] = [];
76
107
  for (const raw of text.split(/\r?\n/)) {
77
108
  const line = raw.trimStart();
@@ -198,18 +229,45 @@ function none(): ToolTargets {
198
229
  return { access: "none", paths: [], roots: [] };
199
230
  }
200
231
 
201
- function writeTargets(tool: string, a: Record<string, unknown>, cwd: string): ToolTargets {
232
+ /**
233
+ * The paths a write-class call names, as written, and whether its targets are known: false only for a patch whose text cannot
234
+ * be read ({@link hostPatchPaths}), whose header paths are then missing.
235
+ */
236
+ function rawWriteTargets(tool: string, a: Record<string, unknown>, everyPatchText = false): { texts: (string | undefined)[]; known: boolean } {
202
237
  if (tool === "patch" || tool === "apply_patch") {
203
238
  // An unreadable patch has unknown targets: a write of nothing the caller can name. The host also honours the
204
239
  // path arguments `filePath`, `path` and `file_path` of a patch call (`toolCallPaths` in src/compat/v2-hooks.ts).
240
+ const headers = everyPatchText ? everyPatchTextPaths(a) : hostPatchPaths(a);
205
241
  const keyed = HOST_PATCH_PATH_KEYS.map(key => nonEmpty(a[key]));
206
- return { access: "write", paths: resolved([...(hostPatchPaths(a) ?? []), ...keyed], cwd), roots: [] };
242
+ return { texts: [...(headers ?? []), ...keyed], known: headers !== undefined };
207
243
  }
208
244
  const raw = pathArgs(a);
209
245
  if (tool === "multiedit" && Array.isArray(a.edits)) {
210
246
  for (const edit of a.edits) raw.push(...pathArgs(record(edit)));
211
247
  }
212
- return { access: "write", paths: resolved(raw, cwd), roots: [] };
248
+ return { texts: raw, known: true };
249
+ }
250
+
251
+ function writeTargets(tool: string, a: Record<string, unknown>, cwd: string): ToolTargets {
252
+ return { access: "write", paths: resolved(rawWriteTargets(tool, a).texts, cwd), roots: [] };
253
+ }
254
+
255
+ /**
256
+ * The files a write-class call ({@link WRITE_CLASS}) names, as written (not resolved: a link must be resolved before any `..`
257
+ * after it), deduped, in the order {@link toolTargets} reads them — and for a patch also the headers of every other patch text key
258
+ * (a superset of the lease targets: {@link toolTargets} reads only the text the host takes). Undefined when its targets are
259
+ * unknown — a `patch` / `apply_patch` whose (host's) text has no header, a header without a path, or no text at all, or whose
260
+ * other patch text key has a header without a path — so the caller fails closed. Empty for any other tool. Never throws.
261
+ */
262
+ export function writeTargetTexts(tool: string, args: unknown): string[] | undefined {
263
+ const name = typeof tool === "string" ? tool.toLowerCase() : "";
264
+ if (!WRITE_CLASS.has(name)) return [];
265
+ try {
266
+ const { texts, known } = rawWriteTargets(name, record(args), true);
267
+ return known ? dedupe(texts.filter((text): text is string => text !== undefined)) : undefined;
268
+ } catch {
269
+ return undefined; // arguments that cannot be read: unknown targets
270
+ }
213
271
  }
214
272
 
215
273
  /**
@@ -40,6 +40,15 @@ function isDotOrSpace(char: string): boolean {
40
40
  return char === "." || char === " ";
41
41
  }
42
42
 
43
+ /**
44
+ * Some segment of one of `texts` (paths, split on `/` and `\`) names `.git` ({@link gitMetadataSegment}). The one `.git` test of
45
+ * the read set ({@link readSetEligible}), the role edit check (`editsGitMetadata`, compat/v2-hooks.ts) and the delegated-agent
46
+ * write guard (router/git-metadata-guard.ts).
47
+ */
48
+ export function namesGitMetadata(...texts: readonly string[]): boolean {
49
+ return texts.some((text) => text.split(/[\\/]/).some(gitMetadataSegment));
50
+ }
51
+
43
52
  /** A path written fully qualified: `X:\…` / `X:/…` on win32 (never drive- or root-relative), `/…` elsewhere. */
44
53
  export function fullyQualifiedPath(path: string): boolean {
45
54
  return process.platform === "win32" ? /^[A-Za-z]:[\\/]/.test(path) : path.startsWith("/");
@@ -54,7 +63,7 @@ export function fullyQualifiedPath(path: string): boolean {
54
63
  */
55
64
  export function readSetEligible(path: string, target: string, hostRelative = false): boolean {
56
65
  if (!hostRelative && !fullyQualifiedPath(path)) return false;
57
- return ![path, target].some((text) => text.split(/[\\/]/).some(gitMetadataSegment));
66
+ return !namesGitMetadata(path, target);
58
67
  }
59
68
 
60
69
  /** C0/C1 controls, format characters (bidi controls, zero-width), line/paragraph separators, unassigned, and `[` `]`. */
@@ -12,6 +12,9 @@ import { isPathSeparator, trimEndWhile } from "../../util/linear-trim";
12
12
  /** A win32 8.3 short-name segment (`PROGRA~1`, `MARQUI~1.TXT`): refused, never expanded (S11, P-11: fail closed). */
13
13
  export const SHORT_NAME_SEGMENT = /(?:^|[\\/])[^\\/~]{1,8}~\d+(?:\.[^\\/.]{0,3})?(?=[\\/]|$)/;
14
14
 
15
+ /** A UNC directory `\\server\share[\…]` (either separator); never a device path (`\\?\…`, `\\.\…`). */
16
+ const UNC_DIRECTORY = /^[\\/]{2}(?![.?][\\/])[^\\/]+[\\/][^\\/]+/;
17
+
15
18
  /**
16
19
  * The canonical long form of a path a role session names (T2.3.1). The RAW path (a relative one joined to `base` as text) goes to
17
20
  * `realpath` (`realpathSync.native`: links, junctions, case and 8.3 as on disk) WITHOUT lexical normalisation first, so a link is
@@ -22,11 +25,21 @@ export const SHORT_NAME_SEGMENT = /(?:^|[\\/])[^\\/~]{1,8}~\d+(?:\.[^\\/.]{0,3})
22
25
  * trimmed), a NUL, a wildcard, and on win32 an 8.3 spelling, a UNC/device
23
26
  * path (`\\server\…`, `\\?\…`: no filesystem call may reach a remote host), a drive-relative path (`C:x`) or a rooted path without
24
27
  * a drive (`\x`); and when anything fails to resolve for another reason than "does not exist".
28
+ *
29
+ * `shortNames: "resolve"` (the delegated-agent git metadata guard, router/git-metadata-guard.ts) lets an 8.3 spelling through to
30
+ * `realpath`, which expands it to the long name on disk; one left in the missing tail names no existing entry (a lookup matches
31
+ * long and short names alike), so it is the literal name the host would create. `uncRoot` (the same guard: the session directory
32
+ * of a project on a share) lets a UNC path through when it lies inside that UNC directory as Win32 resolves it (`..` collapsed as
33
+ * text) — the project's own share, which the host already reaches; any other UNC path and every device path stay refused. Every
34
+ * other refusal stays.
25
35
  */
26
36
  export function canonicalAuthorityPath(
27
37
  path: string,
28
38
  base: string,
29
- opts: { platform?: NodeJS.Platform; realpath?: (path: string) => string; lstat?: (path: string) => unknown } = {},
39
+ opts: {
40
+ platform?: NodeJS.Platform; realpath?: (path: string) => string; lstat?: (path: string) => unknown; shortNames?: "refuse" | "resolve";
41
+ uncRoot?: string;
42
+ } = {},
30
43
  ): string | undefined {
31
44
  const platform = opts.platform ?? process.platform;
32
45
  const realpath = opts.realpath ?? ((p: string) => realpathSync.native(p));
@@ -37,8 +50,12 @@ export function canonicalAuthorityPath(
37
50
  const api = platform === "win32" ? win32 : posix;
38
51
  const unc = (value: string): boolean => /^[\\/]{2}/.test(value);
39
52
  if (platform === "win32") {
40
- if (SHORT_NAME_SEGMENT.test(text) || unc(text) || /^[A-Za-z]:(?![\\/])/.test(text) || /^[\\/](?![\\/])/.test(text)) return undefined;
41
- if (!api.isAbsolute(text) && (SHORT_NAME_SEGMENT.test(base) || unc(base))) return undefined;
53
+ const shortName = (value: string): boolean => opts.shortNames !== "resolve" && SHORT_NAME_SEGMENT.test(value);
54
+ const uncRoot = opts.uncRoot !== undefined && UNC_DIRECTORY.test(opts.uncRoot) ? opts.uncRoot : undefined;
55
+ const full = api.isAbsolute(text) ? text : `${trimEndWhile(base, isPathSeparator)}\\${text}`;
56
+ const ownShare = uncRoot !== undefined && UNC_DIRECTORY.test(full) && insideWorkRoot(win32.resolve(full), uncRoot);
57
+ if (shortName(text) || (unc(text) && !ownShare) || /^[A-Za-z]:(?![\\/])/.test(text) || /^[\\/](?![\\/])/.test(text)) return undefined;
58
+ if (!api.isAbsolute(text) && (shortName(base) || (unc(base) && !ownShare))) return undefined;
42
59
  }
43
60
  if (!api.isAbsolute(text) && !api.isAbsolute(base)) return undefined;
44
61
  const sep = platform === "win32" ? "\\" : "/";
@@ -1,6 +1,7 @@
1
1
  // Impure, cheap HEAD reader: where a working tree is checked out, and how many HEAD reflog entries it has.
2
2
  // Kept apart from tree.ts on purpose: several tests mock that module with `snapshotTree` alone.
3
3
  import { realpath } from "node:fs/promises";
4
+ import { hardeningArgs } from "../router/git-tools";
4
5
  import { execGit, gitExitCode } from "./tree";
5
6
 
6
7
  /** What the branch-switch rule reads of a working tree (see branch.ts `treeMove`). */
@@ -25,9 +26,13 @@ const DEFAULT_TIMEOUT_MS = 5000;
25
26
  const MAX_BUFFER = 1024 * 1024;
26
27
  const MAX_WINDOW = 1000;
27
28
 
29
+ /**
30
+ * #141: read-only git in the work root, as the router's git tools run it: `hardeningArgs()` (no pager, no optional locks, no
31
+ * fsmonitor, hooks or signature programs) and, through execGit's default, git by absolute path from outside the work root.
32
+ */
28
33
  function runner(cwd: string, opts: HeadReadOptions | undefined): (args: readonly string[]) => Promise<string> {
29
34
  const signal = opts?.signal ?? new AbortController().signal;
30
- return (args) => execGit(["--no-pager", "--no-optional-locks", ...args], {
35
+ return (args) => execGit([...hardeningArgs(), ...args], {
31
36
  cwd, signal, timeoutMs: opts?.timeoutMs ?? DEFAULT_TIMEOUT_MS, maxBuffer: MAX_BUFFER, lowPriority: opts?.lowPriority === true,
32
37
  });
33
38
  }