opencode-model-router 2.8.0 → 2.9.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 (90) hide show
  1. package/CHANGELOG.md +364 -0
  2. package/README.md +20 -0
  3. package/package.json +5 -1
  4. package/src/commands/output.ts +23 -1
  5. package/src/compat/background.ts +2439 -0
  6. package/src/compat/child-session.ts +6 -0
  7. package/src/compat/turn-state.ts +215 -0
  8. package/src/compat/v2-client.ts +136 -17
  9. package/src/compat/v2-hooks.ts +2656 -114
  10. package/src/compat/v2-observations.ts +328 -0
  11. package/src/executor/capacity.ts +362 -0
  12. package/src/executor/child-guards.ts +40 -0
  13. package/src/executor/command.ts +265 -0
  14. package/src/executor/compile/edges.ts +809 -0
  15. package/src/executor/compile/estimate.ts +158 -0
  16. package/src/executor/compile/footprint.ts +829 -0
  17. package/src/executor/compile/index.ts +1080 -0
  18. package/src/executor/compile/parse.ts +1492 -0
  19. package/src/executor/compile/residue.ts +706 -0
  20. package/src/executor/compile/validate.ts +280 -0
  21. package/src/executor/create.ts +672 -0
  22. package/src/executor/expand.ts +551 -0
  23. package/src/executor/git.ts +1214 -0
  24. package/src/executor/host-preamble.ts +17 -0
  25. package/src/executor/instructions.ts +35 -0
  26. package/src/executor/integrate/bisect.ts +73 -0
  27. package/src/executor/integrate/checks.ts +1086 -0
  28. package/src/executor/integrate/land.ts +177 -0
  29. package/src/executor/integrate/phase-suite.ts +407 -0
  30. package/src/executor/integrate/queue.ts +3083 -0
  31. package/src/executor/integrate/run-resolver.ts +19 -0
  32. package/src/executor/launch.ts +652 -0
  33. package/src/executor/ledger.ts +2208 -0
  34. package/src/executor/observations.ts +212 -0
  35. package/src/executor/paths.ts +159 -0
  36. package/src/executor/platform.ts +39 -0
  37. package/src/executor/process-identity.ts +19 -0
  38. package/src/executor/qa-loop.ts +470 -0
  39. package/src/executor/recovery.ts +403 -0
  40. package/src/executor/runtime.ts +6233 -0
  41. package/src/executor/schedule.ts +246 -0
  42. package/src/executor/slots/env.ts +145 -0
  43. package/src/executor/slots/pool.ts +1564 -0
  44. package/src/executor/slots/provision.ts +853 -0
  45. package/src/executor/tool.ts +534 -0
  46. package/src/executor/types.ts +2064 -0
  47. package/src/executor/unattended.ts +488 -0
  48. package/src/guard/store.ts +3 -1
  49. package/src/index.ts +1498 -288
  50. package/src/router/config.ts +776 -25
  51. package/src/router/git-tools.ts +106 -15
  52. package/src/router/leases.ts +1469 -0
  53. package/src/router/logger.ts +44 -32
  54. package/src/router/protocol.ts +40 -10
  55. package/src/router/role-agents.ts +224 -17
  56. package/src/router/roles-config.ts +10 -1
  57. package/src/router/roles.ts +1 -1
  58. package/src/router/run-tools.ts +56 -4
  59. package/src/router/tool-paths.ts +308 -0
  60. package/src/router/work-roots.ts +86 -0
  61. package/src/routing/advisor/findings.ts +25 -5
  62. package/src/routing/classify/index.ts +7 -1
  63. package/src/routing/classify/rules.ts +11 -0
  64. package/src/routing/commands/stats.ts +2 -2
  65. package/src/routing/outcomes/durations.ts +225 -0
  66. package/src/routing/outcomes/index.ts +59 -2
  67. package/src/routing/outcomes/persist.ts +409 -0
  68. package/src/routing/outcomes/stats.ts +170 -11
  69. package/src/routing/outcomes/timings.ts +836 -0
  70. package/src/routing/outcomes/types.ts +98 -0
  71. package/src/routing/roles/approvals.ts +86 -5
  72. package/src/routing/roles/binding.ts +99 -9
  73. package/src/routing/roles/orphans.ts +68 -0
  74. package/src/routing/roles/policy.ts +21 -3
  75. package/src/routing/roles/work-root.ts +3 -1
  76. package/src/routing/wire/dispatch.ts +86 -12
  77. package/src/routing/wire/hint.ts +56 -8
  78. package/src/v2.ts +94 -49
  79. package/src/verify/branch.ts +8 -2
  80. package/src/verify/canonical-path.ts +35 -0
  81. package/src/verify/deterministic.ts +38 -9
  82. package/src/verify/dispatch.ts +64 -28
  83. package/src/verify/exec.ts +52 -9
  84. package/src/verify/pending.ts +1691 -10
  85. package/src/verify/perimeter.ts +12 -6
  86. package/src/verify/plan-task.ts +729 -0
  87. package/src/verify/reference.ts +216 -3
  88. package/src/verify/tree.ts +30 -13
  89. package/src/verify/types.ts +9 -2
  90. package/src/verify/wiring.ts +290 -31
@@ -20,6 +20,13 @@ export interface GitInspectOptions {
20
20
  * dispatch) the common directory must be that repository's. QA-G-A2-4: paths and output are limited to the work root.
21
21
  */
22
22
  role?: { dispatchRepository?: string };
23
+ /**
24
+ * Phase 2.1 (leases): a git search lists paths (`ls_files`). With this set, the listed repository-relative paths (`/`-separated, as
25
+ * git prints them) go through it and only `kept` is shown; a non-empty `note` is appended as the last line. It runs on the
26
+ * decoded path list (the same names `ls-files -z` reports), so a name git would quote is matched by its real spelling. A throwing
27
+ * filter fails the call closed (nothing is listed).
28
+ */
29
+ filterSearch?: (root: string, paths: readonly string[]) => { kept: readonly string[]; note?: string };
23
30
  /** Absolute `Date.now()` deadline shared with the caller (a `root` resolution, SD-3b-8); without it a fresh 15 s budget starts. */
24
31
  deadlineAt?: number;
25
32
  }
@@ -528,6 +535,8 @@ function killDirect(child: ChildProcess, label: BoundedLabel): void {
528
535
  }
529
536
 
530
537
  export interface BoundedOptions {
538
+ /** Optional v2 process-lifetime diagnostics; never includes executable/environment/directory preparation. */
539
+ service?: import("../executor/observations").ServiceExecution;
531
540
  signal?: AbortSignal; timeoutMs?: number; maxBytes?: number; env?: NodeJS.ProcessEnv;
532
541
  /**
533
542
  * Keep running past `maxBytes` (the head) and retain only the last `tailBytes` of
@@ -585,18 +594,43 @@ function rollingWindow(max: number) {
585
594
  };
586
595
  }
587
596
 
597
+ function observeBoundedProcess(options: BoundedOptions, event: "prepare" | "start" | "end", result = "error"): void {
598
+ try {
599
+ if (event === "end") options.service?.end(result);
600
+ else options.service?.[event]();
601
+ } catch { /* Diagnostics must never affect the process. */ }
602
+ }
603
+
588
604
  /**
589
605
  * Spawn with byte, time and abort bounds. Settles on `close`, or shortly after
590
606
  * `exit` when helpers that inherited the pipes (MSYS sh/sleep re-parented away
591
607
  * from taskkill's tree) keep `close` from firing (G7). Never a shell.
592
608
  */
593
609
  export function spawnBounded(executable: string, args: readonly string[], cwd: string, options: BoundedOptions = {}): Promise<BoundedResult> {
610
+ observeBoundedProcess(options, "prepare");
594
611
  const label = options.label ?? GIT_LABEL;
595
- if (options.signal?.aborted) return Promise.reject(new Error(`${label.message} aborted`));
596
- if (!isDirectory(cwd)) return Promise.reject(new Error(`${label.message} directory does not exist`));
612
+ if (options.signal?.aborted) {
613
+ observeBoundedProcess(options, "end", "interrupted");
614
+ return Promise.reject(new Error(`${label.message} aborted`));
615
+ }
616
+ if (!isDirectory(cwd)) {
617
+ observeBoundedProcess(options, "end");
618
+ return Promise.reject(new Error(`${label.message} directory does not exist`));
619
+ }
597
620
  return new Promise((resolveResult, reject) => {
598
- const child = spawn(executable, args, { cwd, env: options.env ?? gitEnvironment(), shell: false, windowsHide: true,
599
- detached: process.platform !== "win32", stdio: ["ignore", "pipe", "pipe"] });
621
+ const launch = () => {
622
+ const env = options.env ?? gitEnvironment();
623
+ observeBoundedProcess(options, "start");
624
+ return spawn(executable, args, { cwd, env, shell: false, windowsHide: true,
625
+ detached: process.platform !== "win32", stdio: ["ignore", "pipe", "pipe"] });
626
+ };
627
+ let child: ReturnType<typeof launch>;
628
+ try { child = launch(); }
629
+ catch (error) {
630
+ observeBoundedProcess(options, "end");
631
+ reject(error);
632
+ return;
633
+ }
600
634
  const max = options.maxBytes ?? MAX_BYTES;
601
635
  const tailMax = options.tailBytes;
602
636
  const errorTail = options.mergeStderr && options.stderrTailBytes !== undefined ? rollingWindow(options.stderrTailBytes) : undefined;
@@ -618,9 +652,10 @@ export function spawnBounded(executable: string, args: readonly string[], cwd: s
618
652
  timers.add(timer);
619
653
  return timer;
620
654
  };
621
- const settle = (outcome: () => void) => {
655
+ const settle = (outcome: () => void, serviceResult = "error") => {
622
656
  if (settled) return;
623
657
  settled = true;
658
+ observeBoundedProcess(options, "end", serviceResult);
624
659
  for (const timer of timers) clearTimeout(timer);
625
660
  timers.clear();
626
661
  options.signal?.removeEventListener("abort", abort);
@@ -645,7 +680,8 @@ export function spawnBounded(executable: string, args: readonly string[], cwd: s
645
680
  };
646
681
  const finish = (code: number | null) => {
647
682
  if (settled) return;
648
- const done = () => settle(() => failure && !options.settleOnFailure ? reject(new Error(failure)) : resolveResult(result(code)));
683
+ const done = () => settle(() => failure && !options.settleOnFailure ? reject(new Error(failure)) : resolveResult(result(code)),
684
+ failure !== undefined ? options.signal?.aborted ? "interrupted" : "timed-out" : truncated ? "fail" : code === 0 ? "pass" : "fail");
649
685
  if (!killing) { done(); return; }
650
686
  void Promise.race([killing, new Promise(wait => setTimeout(wait, KILL_WAIT_MS))]).then(done);
651
687
  };
@@ -957,13 +993,50 @@ async function diffNames(executable: string, argv: string[], root: string, env:
957
993
  return withWarnings(result.truncated ? `${text}[truncated: output exceeds ${MAX_BYTES} bytes]` : text, result);
958
994
  }
959
995
 
960
- function nearestRepository(directory: string): string | undefined {
996
+ /**
997
+ * Phase 2.1: `ls-files` with its listing filtered (leases). The listing is read NUL-separated, so a name git would quote is still
998
+ * matched by its real spelling; the filter's `kept` paths are printed one per line, then its note. A `[truncated: …]` marker the
999
+ * bounded runner appended stays last. A throwing filter propagates: the call fails and lists nothing (fail closed).
1000
+ */
1001
+ async function filteredListing(executable: string, argv: string[], root: string, env: NodeJS.ProcessEnv, budget: Budget,
1002
+ filter: NonNullable<GitInspectOptions["filterSearch"]>): Promise<string> {
1003
+ const at = argv.indexOf("ls-files");
1004
+ const run = (args: string[]) => runBoundedProcess(executable, args, root, { signal: budget.signal, timeoutMs: budget.timeoutMs(), env });
1005
+ if (at < 0) return await run(argv); // not a listing argv: nothing to filter
1006
+ const raw = await run([...argv.slice(0, at + 1), "-z", ...argv.slice(at + 1)]);
1007
+ const marker = /\n?\[truncated:[^\]]*\]\s*$/.exec(raw);
1008
+ const body = marker === null ? raw : raw.slice(0, marker.index);
1009
+ const listed = body.split("\0").filter(name => name !== "");
1010
+ const { kept, note } = filter(root, listed);
1011
+ const lines = [...kept, ...(note === undefined || note === "" ? [] : [note])];
1012
+ const text = lines.length === 0 ? "" : `${lines.join("\n")}\n`;
1013
+ return marker === null ? text : `${text}${marker[0].replace(/^\n/, "")}`;
1014
+ }
1015
+
1016
+ export function nearestRepository(directory: string): string | undefined {
961
1017
  for (let current = directory; ; current = dirname(current)) {
962
1018
  if (existsSync(join(current, ".git"))) return current;
963
1019
  if (dirname(current) === current) return undefined;
964
1020
  }
965
1021
  }
966
1022
 
1023
+ /**
1024
+ * Phase 2.1 (`LeaseSeams.repoKeyOf`): the repository and work tree containing `dir`, or undefined outside any (and when its `.git`
1025
+ * cannot be read safely). `repo` is the common git directory, so every linked worktree of one repository shares it; `tree` is the
1026
+ * checkout. Both are real paths. Reads `.git` pointers only (bounded, never followed onto a network or device path); spawns nothing.
1027
+ */
1028
+ export function repositoryIdentity(dir: string): { repo: string; tree: string } | undefined {
1029
+ try {
1030
+ const checkout = nearestRepository(dir);
1031
+ if (checkout === undefined) return undefined;
1032
+ const pointers = gitPointers(checkout);
1033
+ if (pointers === undefined) return undefined;
1034
+ return { repo: realpath(pointers.common), tree: realpath(checkout) };
1035
+ } catch {
1036
+ return undefined; // unreadable or refused (link, network/device path): outside any repository for the lease keys
1037
+ }
1038
+ }
1039
+
967
1040
  /** Honour an explicit containing worktree; otherwise discover the nearest checkout, including linked worktrees. */
968
1041
  function sessionBoundary(session: string, worktree: string | undefined): string {
969
1042
  if (worktree && isAbsolute(worktree) && isDirectory(worktree)) {
@@ -1094,9 +1167,12 @@ export async function inspectGit(operation: GitOperation, input: GitInput, direc
1094
1167
  inspected = { ...input, ref: oid };
1095
1168
  }
1096
1169
  const argv = gitArgv(operation, inspected, root, { config, exclude: linked, ...(scope === undefined ? {} : { scope }) });
1097
- const raw = operation === "diff" && input.mode === "name-only"
1098
- ? await diffNames(executable, argv, root, env, budget)
1099
- : await runBoundedProcess(executable, argv, root, { signal, timeoutMs: budget.timeoutMs(), env });
1170
+ const searchFilter = operation === "ls_files" ? options.filterSearch : undefined;
1171
+ const raw = searchFilter !== undefined
1172
+ ? await filteredListing(executable, argv, root, env, budget, searchFilter)
1173
+ : operation === "diff" && input.mode === "name-only"
1174
+ ? await diffNames(executable, argv, root, env, budget)
1175
+ : await runBoundedProcess(executable, argv, root, { signal, timeoutMs: budget.timeoutMs(), env });
1100
1176
  let output = ["show", "diff", "log"].includes(operation) ? filterSensitiveDiff(raw) : raw;
1101
1177
  if (operation === "show" || operation === "log") output = await annotateWithheld(output, executable, base, root, env, budget, scopeSpec);
1102
1178
  if (linked.length === 0) return output;
@@ -1204,6 +1280,15 @@ export function checkWorkRootAnswer(answer: unknown): WorkRootAnswer {
1204
1280
  throw new Error("Invalid work-root answer: expected { role: false } or { role: true, root }");
1205
1281
  }
1206
1282
 
1283
+ /** Phase 2.1: a process-wide filter for the listings of `router_git_ls_files` (leases); installed by the v2 adapter only. */
1284
+ export type GitSearchFilter = (e: { sessionID: string; root: string; paths: readonly string[] }) => { kept: readonly string[]; note?: string };
1285
+ let installedSearchFilter: GitSearchFilter | undefined;
1286
+ /** Install the listing filter; the returned function removes it (only while it is still the installed one). */
1287
+ export function installGitSearchFilter(filter: GitSearchFilter): () => void {
1288
+ installedSearchFilter = filter;
1289
+ return () => { if (installedSearchFilter === filter) installedSearchFilter = undefined; };
1290
+ }
1291
+
1207
1292
  /** SD-3b-1: appended to every router_git_* description only when a `root` resolver is configured. */
1208
1293
  const GIT_ROOT_DESCRIPTION_SUFFIX = " Role agents may set root to inspect another repository they may read (its absolute top-level path, or its name below routing.repoParents).";
1209
1294
  const GIT_ROOT_ARG_DESCRIPTION = "Another repository to inspect, read-only: its absolute top-level path, or its name below routing.repoParents; path is then relative to it";
@@ -1218,10 +1303,12 @@ function displayRoot(text: string): string {
1218
1303
 
1219
1304
  /**
1220
1305
  * 3b.3: one call with `root` (SD-3b-4, SD-3b-6 to SD-3b-8). Undefined: `root` names the work root, inspect as without it.
1221
- * `root` is only the git cwd, never a git argument; a refusal or a malformed answer spawns nothing.
1306
+ * `root` is only the git cwd, never a git argument; a refusal or a malformed answer spawns nothing. `filtering` (leases, Phase 2.1)
1307
+ * applies to the other repository's listing as to the work root's.
1222
1308
  */
1223
1309
  async function inspectRoot(operation: GitOperation, input: GitInput, value: unknown, resolveRoot: GitRootResolver,
1224
- executables: readonly string[], sessionID: string, signal: AbortSignal, deadlineAt: number): Promise<string | undefined> {
1310
+ executables: readonly string[], sessionID: string, signal: AbortSignal, deadlineAt: number,
1311
+ filtering: Pick<GitInspectOptions, "filterSearch"> = {}): Promise<string | undefined> {
1225
1312
  if (typeof value !== "string") return "[router_git] error: refused: root must be a string; nothing ran";
1226
1313
  try {
1227
1314
  const answer = checkGitRootAnswer(await resolveRoot(value, { sessionID, signal, deadlineAt }));
@@ -1243,7 +1330,7 @@ async function inspectRoot(operation: GitOperation, input: GitInput, value: unkn
1243
1330
  }
1244
1331
  const output = await inspectGit(operation, input, answer.root, signal, {
1245
1332
  executables, guards: [...workRootGuards(answer.root), ...workRootGuards(answer.workRoot)],
1246
- role: { dispatchRepository: answer.repository }, deadlineAt,
1333
+ role: { dispatchRepository: answer.repository }, deadlineAt, ...filtering,
1247
1334
  });
1248
1335
  return `${answer.provenance}\n${output}`;
1249
1336
  } catch (error) {
@@ -1272,6 +1359,9 @@ export function gitTools(opts: GitToolsOptions = {}) {
1272
1359
  },
1273
1360
  async execute(input, context) {
1274
1361
  try {
1362
+ const searchFilter = installedSearchFilter;
1363
+ const filtering: Pick<GitInspectOptions, "filterSearch"> = searchFilter === undefined ? {}
1364
+ : { filterSearch: (root, paths) => searchFilter({ sessionID: context.sessionID, root, paths }) };
1275
1365
  // 3b.3: `root` is stripped before the strict parse; without a resolver the input is parsed as given (unchanged, I9).
1276
1366
  let args: unknown = input;
1277
1367
  let deadline: { deadlineAt?: number } = {};
@@ -1282,7 +1372,7 @@ export function gitTools(opts: GitToolsOptions = {}) {
1282
1372
  // SD-3b-8: one 15 s deadline covers resolution and inspection.
1283
1373
  const deadlineAt = Date.now() + DEADLINE_MS;
1284
1374
  deadline = { deadlineAt };
1285
- const other = await inspectRoot(operation, inputSchema.parse(rest), root, resolveRoot, executables, context.sessionID, context.abort, deadlineAt);
1375
+ const other = await inspectRoot(operation, inputSchema.parse(rest), root, resolveRoot, executables, context.sessionID, context.abort, deadlineAt, filtering);
1286
1376
  if (other !== undefined) return other;
1287
1377
  }
1288
1378
  }
@@ -1295,10 +1385,11 @@ export function gitTools(opts: GitToolsOptions = {}) {
1295
1385
  return await inspectGit(operation, inputSchema.parse(args), answer.root, context.abort, {
1296
1386
  executables, guards: workRootGuards(answer.root),
1297
1387
  role: expected ? { dispatchRepository: expected } : {}, ...deadline,
1388
+ ...filtering,
1298
1389
  });
1299
1390
  }
1300
1391
  }
1301
- return await inspectGit(operation, inputSchema.parse(args), context.directory, context.abort, { worktree: context.worktree, executables, ...deadline });
1392
+ return await inspectGit(operation, inputSchema.parse(args), context.directory, context.abort, { worktree: context.worktree, executables, ...deadline, ...filtering });
1302
1393
  } catch (error) {
1303
1394
  // G12: report, never throw into the session; messages are credential-redacted.
1304
1395
  return `[router_git] error: ${stripUrlUserinfo(errorMessage(error))}`;