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
@@ -48,7 +48,7 @@ import {
48
48
  import { buildRoleLadder, roleTierOrder, routerTierIds } from "../engine/ladders";
49
49
  import { decideRole } from "../engine/kernel";
50
50
  import type { Candidate, ChosenDispatch, Decision, HostAgentInfo, Ladder, RoleLadder } from "../engine/types";
51
- import { CLASS_IMPLIED_NEEDS, FACT_SOURCES, NEEDS, RISKS, SCOPES, TASK_CLASSES, classify, classifyNeedMatches } from "../classify";
51
+ import { CLASS_BASE_RISK, CLASS_IMPLIED_NEEDS, FACT_SOURCES, NEEDS, RISKS, SCOPES, TASK_CLASSES, classify, classifyNeedMatches, classifyRiskTerm } from "../classify";
52
52
  import type { ClassifyResult, Detection, Need, RouteLine, TaskFacts } from "../classify/types";
53
53
  import { resolveRolesRouting, resolveVerifyBudget, type RouterConfig } from "../../router/config";
54
54
  import { resolveEnforcementMode } from "../../router/enforcement";
@@ -305,6 +305,8 @@ export interface RoleRouted {
305
305
  /** Grant and catalog notes (decision-row / diagnostic text; they are not shown in the dispatch header or the parent result). */
306
306
  readonly notes: readonly string[];
307
307
  readonly detection: EffectiveDetection;
308
+ /** The bounds reason includes `gated:authority`: gating lowered the final floor compared with strict. Absent otherwise. */
309
+ readonly gated?: true;
308
310
  /** The dispatch's total call budget (`roleGuardProfile(spec, tier, routeLine.budget).budget`). */
309
311
  readonly budget: number;
310
312
  /** The route line's `budget=`, or null (pass it to `roleGuardProfile`, handoff 27). */
@@ -357,6 +359,8 @@ export const ROLE_REFUSALS = {
357
359
  `no model is available inside the tier window ${floor}..${ceiling} (${reasons.join(", ") || "window:no-candidates"}); the router never falls back to a tier agent — fix the preset, or dispatch a tier agent explicitly`,
358
360
  failed: (detail: string): string => `the router could not route it (${detail}); retry, or dispatch a tier agent explicitly`,
359
361
  session: (detail: string): string => `the dispatching session is unavailable (${detail}); retry`,
362
+ staleResume: (child: string): string =>
363
+ `resume refused: session ${child} belongs to a role dispatch this OpenCode process no longer tracks (lost in a restart, or already finished), so it would run unbound: local actions only, no work root. Dispatch a fresh task (same prompt and route line); do not resume this session.`,
360
364
  } as const;
361
365
 
362
366
  const UNTOUCHED: RouteOutcome = Object.freeze({ mode: "static" });
@@ -367,6 +371,15 @@ const UNTOUCHED: RouteOutcome = Object.freeze({ mode: "static" });
367
371
  */
368
372
  const RUNNER_CHILD_TITLE = /^Router (?:.+ delegation|result verification)$/;
369
373
 
374
+ /** Phase 2.1: the routing facts of one dispatch that the background and timing policy needs (`DispatchRouter.decisionOf`). */
375
+ export interface DispatchDecisionInfo {
376
+ readonly role: string | undefined;
377
+ readonly class: string;
378
+ readonly scope: string;
379
+ readonly tier: string | undefined;
380
+ readonly model: string | undefined;
381
+ }
382
+
370
383
  export interface DispatchRouter {
371
384
  /**
372
385
  * Decide one `subagent` call. Writes and registers nothing: `commit` writes its decision row and registers it. Never throws, except
@@ -390,6 +403,12 @@ export interface DispatchRouter {
390
403
  * row; nothing when the engine writes no rows or the dispatch is unknown. Never throws.
391
404
  */
392
405
  noteBinding(childSessionID: string, binding: Pick<Binding, "kind" | "decisionID">): void;
406
+ /**
407
+ * Phase 2.1: what `route()` decided for a call, for the background and timing policy. Valid from `route()` until the call's result
408
+ * (`onCallResult`) or end (`onCallFinished`). `role` is the role agent (absent for a tier dispatch); `class` and `scope` are
409
+ * `"unknown"` when the engine knows none (`engine: static`). Undefined for a call `route()` did not act on. Never throws.
410
+ */
411
+ decisionOf(callID: string): DispatchDecisionInfo | undefined;
393
412
  /** Dispatches still waiting to be claimed (diagnostics, tests). */
394
413
  pendingCount(): number;
395
414
  /** Children registered by a wrong heuristic claim and not yet taken over by their own dispatch (diagnostics, tests). */
@@ -526,7 +545,7 @@ function claimCall(key: string): boolean {
526
545
  }
527
546
 
528
547
  /** Bound on children with pending subagent-result annotations (oldest dropped first). */
529
- export const MAX_ANNOTATED_CHILDREN = 256;
548
+ export const MAX_ANNOTATED_CHILDREN = 1024 /* >= MAX_LIVE_ATTEMPTS: background children collect annotations for hours */;
530
549
  /** Bound on annotations kept per child (oldest dropped first). */
531
550
  export const MAX_ANNOTATIONS_PER_CHILD = 8;
532
551
 
@@ -1358,7 +1377,7 @@ function factsOf(facts: TaskFacts): DecisionRow["facts"] {
1358
1377
  return { class: facts.class, risk: facts.risk, scope: facts.scope, needs: [...facts.needs], confidence: facts.confidence, source: facts.source };
1359
1378
  }
1360
1379
 
1361
- function traceOf(result: ClassifyResult, argmin: RouteChoice | null): DecisionTrace {
1380
+ function traceOf(result: ClassifyResult, argmin: RouteChoice | null, riskSources?: DecisionTrace["riskSources"]): DecisionTrace {
1362
1381
  const { routeLines, backend, backendSkipped } = result.trace;
1363
1382
  return {
1364
1383
  routeLines: { count: routeLines.count, conflict: routeLines.conflict, edgeOnly: routeLines.edgeOnly },
@@ -1374,6 +1393,7 @@ function traceOf(result: ClassifyResult, argmin: RouteChoice | null): DecisionTr
1374
1393
  },
1375
1394
  ...(backendSkipped === undefined ? {} : { backendSkipped }),
1376
1395
  ...(argmin === null ? {} : { argmin }),
1396
+ ...(riskSources === undefined ? {} : { riskSources }),
1377
1397
  };
1378
1398
  }
1379
1399
 
@@ -1448,6 +1468,13 @@ export function createDispatchRouter(deps: DispatchRouterDeps): DispatchRouter {
1448
1468
  const instanceNonce = randomBytes(8).toString("hex");
1449
1469
  /** Between `route()` and `commit()`. */
1450
1470
  const decided = new Map<string, Decided>();
1471
+ /** Phase 2.1: the routing facts of a routed call, until its result or end (`decisionOf`). Bounded like the other per-call maps. */
1472
+ const decisionInfos = new Map<string, DispatchDecisionInfo>();
1473
+ const noteDecision = (callID: string, info: DispatchDecisionInfo): void => {
1474
+ decisionInfos.delete(callID);
1475
+ decisionInfos.set(callID, info);
1476
+ while (decisionInfos.size > MAX_HANDLED_CALLS) decisionInfos.delete(decisionInfos.keys().next().value as string);
1477
+ };
1451
1478
  /** Committed dispatches, in insertion order, until their call ends. */
1452
1479
  const entries = new Map<string, Entry>();
1453
1480
  /**
@@ -2110,14 +2137,15 @@ export function createDispatchRouter(deps: DispatchRouterDeps): DispatchRouter {
2110
2137
  const env = deps.env === undefined ? {} : { env: deps.env };
2111
2138
  const verifyRoot = verifyRootOf(grant, sessionDirectory, workRootDeps.realpath);
2112
2139
  const inReadSet = readSetFor(rp.cfg, call.sessionID);
2140
+ // QA-P21-1-2, QA-P21-2 nit 3. QA-G-B-2-1: a carried acceptance is never deferred (its gate runs at the return); its change-set
2141
+ // checks (testsPass, lintClean) can cover the child's earlier attempts only once the attempt that introduced the block was
2142
+ // gated with a known change set (its baseline) — until then the gate cannot back `deterministic`.
2143
+ const deferred = carried === null
2144
+ ? roleGateDeferred(rp.cfg, verifyPrompt, description, { verifyEnabled: deps.routerVerifyEnabled?.() !== false })
2145
+ : (carried.baseline === undefined || carried.baseline.changed === "unavailable") && carriedChecksChangeSet(carried.block);
2113
2146
  const routerGate = roleRouterGate({
2114
2147
  cfg: rp.cfg, bypassed, acceptance, ...env,
2115
- // QA-P21-1-2, QA-P21-2 nit 3. QA-G-B-2-1: a carried acceptance is never deferred (its gate runs at the return); its change-set
2116
- // checks (testsPass, lintClean) can cover the child's earlier attempts only once the attempt that introduced the block was
2117
- // gated with a known change set (its baseline) — until then the gate cannot back `deterministic`.
2118
- deferred: carried === null
2119
- ? roleGateDeferred(rp.cfg, verifyPrompt, description, { verifyEnabled: deps.routerVerifyEnabled?.() !== false })
2120
- : (carried.baseline === undefined || carried.baseline.changed === "unavailable") && carriedChecksChangeSet(carried.block),
2148
+ deferred,
2121
2149
  outsideWorkRoot: roleGateOutsideWorkRoot(grant.workRoot, verifyPrompt, description, args.cwd, inReadSet), // DF2-F1, QA-P33F1-1-1, nit 3
2122
2150
  });
2123
2151
  // QA-G-B-7: the gate verifies nothing at all (enforcement off, /bypass, `require: never`, a cwd outside the root it verifies in)
@@ -2126,6 +2154,7 @@ export function createDispatchRouter(deps: DispatchRouterDeps): DispatchRouter {
2126
2154
  cfg: rp.cfg, bypassed, ...env, outsideWorkRoot: roleGateOutsideWorkRoot(verifyRoot, verifyPrompt, description, args.cwd, inReadSet),
2127
2155
  });
2128
2156
  const detection = effectiveDetection({ routerGate, claim, acceptance, verifies });
2157
+ const gateAtReturn = verifies && !deferred && acceptance !== "none";
2129
2158
 
2130
2159
  // 6. bounds on the one role tier order (handoff 9); a resume passes the child's running tier. QA-P21-2-2: the raise recorded
2131
2160
  // after a verification FAIL of this child (for this parent) is a raise-only floor, like `floorTier`; consumed on success.
@@ -2134,6 +2163,11 @@ export function createDispatchRouter(deps: DispatchRouterDeps): DispatchRouter {
2134
2163
  const raised = resumeID === null ? null : pendingResumeRaise(resumeID, call.sessionID);
2135
2164
  const floorTier = higherTier(tiers, rp.cfg.enforcement?.escalate?.floorTier ?? null, raised);
2136
2165
  const bounds = tierBounds(rp.spec, grant, classified, detection, {
2166
+ // The gated cell promises a one-step raise to heavy; a narrowed ceiling or an intermediate rung cannot back it.
2167
+ floorPolicy: {
2168
+ mode: resolveRolesRouting(rp.cfg, "v2").roleFloor,
2169
+ gateAtReturn: gateAtReturn && nextRoleTier(tiers, rp.spec.tierRange.ceiling, "medium") === "heavy",
2170
+ },
2137
2171
  floorTier,
2138
2172
  runningTier: running?.tier ?? null,
2139
2173
  pinTier: routeLine?.tier ?? null,
@@ -2211,6 +2245,8 @@ export function createDispatchRouter(deps: DispatchRouterDeps): DispatchRouter {
2211
2245
  // QA-P21-1-11: a fresh dispatch has no binding yet (its child binds later; `noteBinding` writes the observed kind then).
2212
2246
  // A resume records the child's current binding.
2213
2247
  const binding = resumed ? currentBinding(resumeID, { maxOf: (name) => roleMaxActions(rp.roles.get(name)) })?.kind : undefined;
2248
+ const riskTerm = classifyRiskTerm({ description, prompt, cwd: classifyCwd }, rp.classifyDeps);
2249
+ const inheritedRisk = RISKS.find((risk) => risk === original?.facts.risk);
2214
2250
  row = {
2215
2251
  v: LOG_ROW_VERSION,
2216
2252
  ts: new Date(safeNow(now)).toISOString(),
@@ -2230,7 +2266,15 @@ export function createDispatchRouter(deps: DispatchRouterDeps): DispatchRouter {
2230
2266
  reason: `${head}; role @${agent} on ${tier} in ${bounds.floor}..${bounds.ceiling}${extra.length > 0 ? ` [${extra.join("; ")}]` : ""}`,
2231
2267
  step: "dispatch",
2232
2268
  resume: resumed,
2233
- trace: { ...traceOf(result, argmin), needTerms }, // QA-G-B-3 (3)
2269
+ trace: { ...traceOf(result, argmin, {
2270
+ base: CLASS_BASE_RISK[result.trace.rules.class],
2271
+ rules: result.trace.rules.risk,
2272
+ routeLine: routeLine?.risk ?? null,
2273
+ facts: result.facts.risk,
2274
+ ...(inheritedRisk === undefined ? {} : { resumedDispatch: inheritedRisk }),
2275
+ effective: taskFacts.risk,
2276
+ ...(riskTerm === undefined ? {} : { term: riskTerm }),
2277
+ }), needTerms }, // QA-G-B-3 (3)
2234
2278
  detection: {
2235
2279
  effective: detection,
2236
2280
  ...(result.detection !== undefined && result.detection !== null && result.detection !== detection ? { claimed: result.detection } : {}),
@@ -2260,6 +2304,7 @@ export function createDispatchRouter(deps: DispatchRouterDeps): DispatchRouter {
2260
2304
  requestedRoot: root.requested,
2261
2305
  notes,
2262
2306
  detection,
2307
+ ...(bounds.reasons.includes("gated:authority") ? { gated: true as const } : {}),
2263
2308
  budget,
2264
2309
  routeBudget,
2265
2310
  nonce,
@@ -2433,8 +2478,7 @@ export function createDispatchRouter(deps: DispatchRouterDeps): DispatchRouter {
2433
2478
  }
2434
2479
  };
2435
2480
 
2436
- return {
2437
- async route(call): Promise<RouteOutcome> {
2481
+ const routeInner = async (call: RouteCall): Promise<RouteOutcome> => {
2438
2482
  try {
2439
2483
  const agent = str(call.args.agent);
2440
2484
  const callKey = `${call.sessionID}\u0000${call.callID}`;
@@ -2477,8 +2521,36 @@ export function createDispatchRouter(deps: DispatchRouterDeps): DispatchRouter {
2477
2521
  deps.logger.warn("[router] routing: the engine failed; the dispatch proceeds as the orchestrator chose", { error: describeError(error) });
2478
2522
  return UNTOUCHED;
2479
2523
  }
2524
+ };
2525
+
2526
+ return {
2527
+ async route(call): Promise<RouteOutcome> {
2528
+ const outcome = await routeInner(call); // throws only RoleDispatchRefusal
2529
+ try {
2530
+ const routed = outcome.role;
2531
+ const d = decided.get(call.callID);
2532
+ if (routed !== undefined) {
2533
+ noteDecision(call.callID, { role: routed.agent, class: routed.class ?? "unknown", scope: d?.facts.scope ?? "unknown", tier: routed.tier, model: routed.model });
2534
+ } else if (d !== undefined) {
2535
+ noteDecision(call.callID, {
2536
+ role: undefined,
2537
+ class: d.facts.class,
2538
+ scope: d.facts.scope,
2539
+ tier: d.final !== null && classifyAgentOrigin(d.final.agent, d.routerIds) === "router" ? d.final.agent : undefined,
2540
+ model: d.final === null ? undefined : d.final.model,
2541
+ });
2542
+ } else {
2543
+ noteDecision(call.callID, { role: undefined, class: "unknown", scope: "unknown", tier: undefined, model: undefined });
2544
+ }
2545
+ } catch (error) {
2546
+ deps.logger.warn("[router] routing: the decision of a call could not be noted", { error: describeError(error) });
2547
+ }
2548
+ return outcome;
2480
2549
  },
2481
2550
 
2551
+ // Valid until `onCallResult`/`onCallFinished` of the call: the adapter reads it in `execute.before` and, before `onCallResult`, in `execute.after`.
2552
+ decisionOf: (callID) => decisionInfos.get(callID),
2553
+
2482
2554
  commit(callID, input): void {
2483
2555
  try {
2484
2556
  const d = decided.get(callID);
@@ -2587,6 +2659,7 @@ export function createDispatchRouter(deps: DispatchRouterDeps): DispatchRouter {
2587
2659
  onCallResult(callID, childSessionID): void {
2588
2660
  try {
2589
2661
  decided.delete(callID);
2662
+ decisionInfos.delete(callID);
2590
2663
  const entry = entries.get(callID);
2591
2664
  entries.delete(callID);
2592
2665
  if (entry === undefined) return;
@@ -2613,6 +2686,7 @@ export function createDispatchRouter(deps: DispatchRouterDeps): DispatchRouter {
2613
2686
 
2614
2687
  onCallFinished(callID): void {
2615
2688
  decided.delete(callID);
2689
+ decisionInfos.delete(callID);
2616
2690
  const entry = entries.get(callID);
2617
2691
  entries.delete(callID);
2618
2692
  if (entry !== undefined) undoResume(entry);
@@ -5,9 +5,12 @@
5
5
  * - swap the taxonomy line of the delegation protocol for `generateTaxonomy(...)` (a class moves only when the winner
6
6
  * has ≥ 5 recorded outcomes, so the line stays the shipped one until evidence exists, D2), and append the route-line
7
7
  * paragraph of `protocol.ts`;
8
- * - in advise only, add one extra system part, the per-turn hint: stable class and destination text, computed from the
9
- * latest user message with the RULES classifier only (a hint never costs a model call) and cached for the turn, so the
10
- * system prompt does not change between the steps of one turn.
8
+ * - in advise only, add the per-turn hint: stable class and destination text, computed from the latest user message with
9
+ * the RULES classifier only (a hint never costs a model call) and cached for the turn, so it does not change between the
10
+ * steps of one turn. Without a turn-state registry it is one extra system part; with one (Phase 1.2) nothing is pushed:
11
+ * the hint is kept per session and rendered by the `route-hint` provider into the turn-state tail, and the generated `R:`
12
+ * line is frozen per session (reused while the config object and the dispatching agent, model and permissions are the
13
+ * same) so no router system part changes between turns. Fresh routing evidence still reaches the model through the hint.
11
14
  *
12
15
  * The hint and the generated `R:` line come from the same kernel, but the hint is only emitted when the kernel says
13
16
  * `switched` for the class's static tier, i.e. when it agrees with a move the line itself could make (QA focus: a hint
@@ -15,7 +18,7 @@
15
18
  *
16
19
  * Roles mode (`routing.delegation: "roles"`, plan #84 T2.2.1): nothing is added or rewritten — no per-turn hint, no tier
17
20
  * `R:` line, no route-line paragraph. The roles protocol carries its own class → role line and route-line keys, and a
18
- * hint or a tier line would name tiers; a system part that changes per turn would also cost the orchestrator its
21
+ * hint or a tier line would name tiers; a router text that changes per turn would also cost the orchestrator its
19
22
  * prompt cache. The check is the roles protocol's heading among the router's own parts, i.e. the text the orchestrator
20
23
  * actually carries: a roles config with no enabled role falls back to the tiers protocol, augmented as in tiers mode.
21
24
  */
@@ -29,6 +32,7 @@ import {
29
32
  /** The roles heading only counts at the start of a line (QA-P22-2-4): a part that merely quotes it mid-line is not the roles protocol. */
30
33
  const ROLES_HEADING_LINE = /^## Role Delegation Protocol \(MANDATORY\)$/m;
31
34
 
35
+ import type { TurnStateRegistry } from "../../compat/turn-state";
32
36
  import { classify } from "../classify";
33
37
  import { CLASS_STATIC_TIER, type TaskFacts } from "../classify/types";
34
38
  import { buildLadder, decide, floorRankOf, generateTaxonomy, resolveChosen } from "../engine";
@@ -95,7 +99,8 @@ export interface ContextInput {
95
99
  export interface SystemAugmenter {
96
100
  /**
97
101
  * Called by the context hook after the legacy hook has pushed its text. Rewrites the protocol text in `system` in place
98
- * and pushes the hint, registering both in `added` (the texts whose vocabulary the adapter translates). Never throws.
102
+ * and pushes the hint, registering both in `added` (the texts whose vocabulary the adapter translates); with a turn-state
103
+ * registry the hint is kept for the `route-hint` provider instead and nothing is pushed. Never throws.
99
104
  */
100
105
  augment(input: ContextInput, system: string[], added: Set<string>): Promise<void>;
101
106
  }
@@ -105,6 +110,8 @@ export interface SystemAugmenterDeps {
105
110
  readonly getSession: (sessionID: string) => Promise<unknown>;
106
111
  readonly logger: WireLogger;
107
112
  readonly now?: () => number;
113
+ /** v2 only (Phase 1.2): when present the hint goes to the turn-state tail instead of the system array and the `R:` line is frozen per session. */
114
+ readonly turnState?: TurnStateRegistry;
108
115
  }
109
116
 
110
117
  function describeError(error: unknown): string {
@@ -116,10 +123,43 @@ export function createSystemAugmenter(deps: SystemAugmenterDeps): SystemAugmente
116
123
  // QA-2.2-9: the line depends on the config, the dispatching agent, its (and its session's) permissions and the orchestrator's model.
117
124
  const taxonomyMemo = new Map<string, { cfg: Prepared["cfg"]; at: number; line: string }>();
118
125
  const hints = new Map<string, { key: string; hint: string | null }>();
126
+ // Phase 1.2 (v2 only): the hint of the current request per session, read by the `route-hint` provider; and the frozen `R:` line.
127
+ const routeHints = new Map<string, string>();
128
+ const frozenLines = new Map<string, { memoKey: string; cfg: Prepared["cfg"]; line: string }>();
129
+
130
+ if (deps.turnState !== undefined) {
131
+ try {
132
+ deps.turnState.registerTurnStateProvider({
133
+ name: "route-hint",
134
+ order: 90,
135
+ render: (sid) => routeHints.get(sid),
136
+ });
137
+ } catch (error) {
138
+ deps.logger.warn("[router] turn state: the route-hint provider could not be registered", { error: describeError(error) });
139
+ }
140
+ }
119
141
 
120
142
  const taxonomyLine = (prepared: Prepared, view: AgentView, input: ContextInput): string => {
121
- const t = now();
122
143
  const memoKey = `${input.agent}\u0000${input.parentModel ?? ""}\u0000${JSON.stringify(view.parentRules)}`;
144
+ if (deps.turnState === undefined) return computedTaxonomyLine(prepared, view, input, memoKey);
145
+ // 1.2.4.d: reused while the key (agent name, parent model, parent rules) and the config object are unchanged, so the system prompt
146
+ // does not move between turns. The line is regenerated (an accepted cache break) only when one of those changes: a config/env
147
+ // change, a model switch, other rules. A changed agent catalog alone does not refresh it (a removed host agent can stay named).
148
+ const frozen = frozenLines.get(input.sessionID);
149
+ if (frozen !== undefined && frozen.memoKey === memoKey && frozen.cfg === prepared.cfg) {
150
+ frozenLines.delete(input.sessionID);
151
+ frozenLines.set(input.sessionID, frozen);
152
+ return frozen.line;
153
+ }
154
+ const line = computedTaxonomyLine(prepared, view, input, memoKey);
155
+ frozenLines.delete(input.sessionID);
156
+ frozenLines.set(input.sessionID, { memoKey, cfg: prepared.cfg, line });
157
+ while (frozenLines.size > HINT_MEMO_LIMIT) frozenLines.delete(frozenLines.keys().next().value as string);
158
+ return line;
159
+ };
160
+
161
+ const computedTaxonomyLine = (prepared: Prepared, view: AgentView, input: ContextInput, memoKey: string): string => {
162
+ const t = now();
123
163
  const memo = taxonomyMemo.get(memoKey);
124
164
  if (memo !== undefined && memo.cfg === prepared.cfg && t - memo.at < TAXONOMY_TTL_MS) return memo.line;
125
165
  const line = generateTaxonomy({
@@ -184,6 +224,8 @@ export function createSystemAugmenter(deps: SystemAugmenterDeps): SystemAugmente
184
224
 
185
225
  return {
186
226
  async augment(input, system, added): Promise<void> {
227
+ // A request that returns early below (roles, static, shadow, no orchestrator) must leave no hint of an earlier one behind.
228
+ routeHints.delete(input.sessionID);
187
229
  try {
188
230
  // Roles mode: no hint part, and the protocol text stays exactly as the legacy hook built it. Keyed on the roles
189
231
  // protocol the orchestrator actually carries (QA-P22-1-5): `delegation: "roles"` with no enabled role keeps the
@@ -211,8 +253,14 @@ export function createSystemAugmenter(deps: SystemAugmenterDeps): SystemAugmente
211
253
  }
212
254
  const hint = mode === "advise" ? await hintFor(prepared, view, input) : null;
213
255
  if (hint !== null) {
214
- added.add(hint);
215
- system.push(hint);
256
+ if (deps.turnState !== undefined) {
257
+ // The tail carries the hint (provider `route-hint`); nothing is pushed into the system array.
258
+ routeHints.set(input.sessionID, hint);
259
+ while (routeHints.size > HINT_MEMO_LIMIT) routeHints.delete(routeHints.keys().next().value as string);
260
+ } else {
261
+ added.add(hint);
262
+ system.push(hint);
263
+ }
216
264
  }
217
265
  } catch (error) {
218
266
  deps.logger.warn("[router] routing: the protocol could not be adapted to the engine; the shipped text stays", { error: describeError(error) });
package/src/v2.ts CHANGED
@@ -5,60 +5,105 @@ import { createV2Runtime } from "./compat/v2-client";
5
5
  import { registerV2Hooks } from "./compat/v2-hooks";
6
6
  import type { Ingest } from "./routing/outcomes/ingest";
7
7
  import type { BudgetSnapshot } from "./guard/enforce";
8
+ import type { PlanTaskVerifier } from "./executor/runtime";
9
+ import type { ExecutorChildGuardPort } from "./executor/types";
10
+ import { createExecutor, createExecutorAccess, prepareExecutor, type CreateExecutorOptions, type PreparedExecutor } from "./executor/create";
11
+ import { EXECUTOR_PLATFORM_REASON, executorPlatformSupported } from "./executor/platform";
12
+ import { loadConfig, resolveRolesRouting, resolveRouting } from "./router/config";
13
+ import { locationOutsideWorkRoots } from "./router/work-roots";
14
+ import { openV2Observations } from "./compat/v2-observations";
8
15
 
9
16
  /** Keep the routing engine shared; translate only the host API at this boundary. */
10
17
  export default {
11
18
  id: "opencode-model-router",
12
19
  server: ModelRouterPlugin,
13
20
  async setup(ctx: Plugin.Context) {
14
- const runtime = createV2Runtime(ctx);
15
- // The engine consumes directory/client only. V2 has no legacy HTTP server
16
- // URL or Bun shell context; do not invent either for the adapter.
17
- let ingest: Ingest | undefined;
18
- // #84 P2.1: the plugin's `/bypass` state, read by the role dispatch path (the router's own gate will not run while bypassed, S10/P-9).
19
- let isBypassed: (() => boolean) | undefined;
20
- let budgetSnapshot: ((childSessionID: string) => BudgetSnapshot) | undefined;
21
- // #84 P2.1 (handoff 22): the host's own stops of role children (step limit, context overflow), observed by the adapter from the
22
- // event stream and folded into the plugin's budget signals. The adapter hands its observer back once registered.
23
- let observeHostBudget: ((childSessionID: string, stepLimit: number | null) => boolean | "unobserved") | undefined;
24
- let roleLive: ((agent: string) => boolean) | undefined;
25
- let verifyEnabled: (() => boolean) | undefined;
26
- // QA-G-A3-2: the plugin's count of a role child's call refused outside its guard (role-authority refusals, permission denials).
27
- let recordRefusal: ((sessionID: string, agent: string | undefined, tool: string, args: unknown) => string | undefined) | undefined;
28
- const input = {
29
- directory: ctx.location.directory,
30
- worktree: ctx.location.project.directory,
31
- client: runtime.client,
32
- routerChildRunner: runtime.childRunner,
33
- routerHost: "v2" as const,
34
- // Step pricing reads the catalog the adapter already queries; the plugin's single telemetry ingest comes back
35
- // here so the event loop feeds the instance that also receives the verdicts (QA-2.1-7).
36
- routerCatalog: async () => (await ctx.model.list({ location: { directory: ctx.location.directory } })).data,
37
- // The agents of THIS plugin instance's location (QA-2.4-16): the host lists agents per location.
38
- routerAgents: async () => (await ctx.agent.list({ location: { directory: ctx.location.directory } })).data,
39
- ...(ctx.generate === undefined ? {} : { routerGenerate: ctx.generate }),
40
- // The same host call the adapter uses for the config-reload and narration notices (src/compat/v2-hooks.ts): a transcript entry that
41
- // does not resume the session (QA-2.4-R2-1).
42
- routerSynthetic: async (notice: { sessionID: string; text: string; description: string }) => {
43
- await ctx.session.synthetic({ sessionID: notice.sessionID, text: notice.text, description: notice.description, resume: false });
44
- },
45
- routerOnIngest: (created: Ingest) => { ingest = created; },
46
- routerOnBypassState: (read: () => boolean) => { isBypassed = read; },
47
- // QA-P21-1-3: the plugin's budget snapshot (guard state + read-only CAP state) for the adapter's budget notice.
48
- routerOnBudgetSnapshot: (read: (childSessionID: string) => BudgetSnapshot) => { budgetSnapshot = read; },
49
- routerHostBudget: (childSessionID: string, stepLimit: number | null) => observeHostBudget?.(childSessionID, stepLimit),
50
- // QA-P21-2-4: the adapter's "this role agent is registered" check; QA-P21-2 nit 3: whether router_verify is registered.
51
- routerRoleLive: (agent: string) => roleLive?.(agent),
52
- routerOnVerifyEnabled: (read: () => boolean) => { verifyEnabled = read; },
53
- routerOnRefusal: (record: NonNullable<typeof recordRefusal>) => { recordRefusal = record; },
54
- };
55
- const hooks = await ModelRouterPlugin(input as unknown as PluginInput);
56
- return registerV2Hooks(ctx, hooks, runtime, {
57
- ...(ingest ? { ingest } : {}), ...(isBypassed ? { isBypassed } : {}), ...(budgetSnapshot ? { budgetSnapshot } : {}),
58
- ...(verifyEnabled ? { routerVerifyEnabled: verifyEnabled } : {}),
59
- ...(recordRefusal ? { recordRefusal } : {}),
60
- onHostBudget: (observe) => { observeHostBudget = observe; },
61
- onRoleLive: (isLive) => { roleLive = isLive; },
62
- });
21
+ const observations = openV2Observations();
22
+ try {
23
+ const runtime = createV2Runtime(ctx);
24
+ const directory = ctx.location.directory;
25
+ const access = createExecutorAccess();
26
+ const cfg = loadConfig(directory), routing = resolveRouting(cfg, "v2"), rolesRouting = resolveRolesRouting(cfg, "v2");
27
+ // G-16: off Windows the executor is not assembled; start-up discovery runs no git and touches no executor home.
28
+ const discoveryDisabled = !executorPlatformSupported() ? EXECUTOR_PLATFORM_REASON
29
+ : rolesRouting.delegation !== "roles" ? "routing.delegation must be roles at start"
30
+ : routing.leases.mode !== "enforce" ? "routing.leases.mode must be enforce"
31
+ : cfg.enforcement?.verify?.require === "never" ? "enforcement.verify.require is never"
32
+ : locationOutsideWorkRoots(directory, rolesRouting.workRoots) ? "the location is outside routing.workRoots"
33
+ : null;
34
+ const prep: Promise<PreparedExecutor> = discoveryDisabled === null ? prepareExecutor(directory)
35
+ : Promise.resolve({ ok: false, reason: discoveryDisabled });
36
+ // The engine consumes directory/client only. V2 has no legacy HTTP server
37
+ // URL or Bun shell context; do not invent either for the adapter.
38
+ let ingest: Ingest | undefined;
39
+ // #84 P2.1: the plugin's `/bypass` state, read by the role dispatch path (the router's own gate will not run while bypassed, S10/P-9).
40
+ let isBypassed: (() => boolean) | undefined;
41
+ let budgetSnapshot: ((childSessionID: string) => BudgetSnapshot) | undefined;
42
+ // #84 P2.1 (handoff 22): the host's own stops of role children (step limit, context overflow), observed by the adapter from the
43
+ // event stream and folded into the plugin's budget signals. The adapter hands its observer back once registered.
44
+ let observeHostBudget: ((childSessionID: string, stepLimit: number | null) => boolean | "unobserved") | undefined;
45
+ let roleLive: ((agent: string) => boolean) | undefined;
46
+ let verifyEnabled: (() => boolean) | undefined;
47
+ // QA-G-A3-2: the plugin's count of a role child's call refused outside its guard (role-authority refusals, permission denials).
48
+ let recordRefusal: ((sessionID: string, agent: string | undefined, tool: string, args: unknown) => string | undefined) | undefined;
49
+ // Phase 5.1 D8: the plan-task verifier built over this plugin instance's dispatch verification engine.
50
+ let slotVerifier: PlanTaskVerifier | undefined;
51
+ let annotate: CreateExecutorOptions["annotate"];
52
+ // Publishes executor child rounds/caps process-wide; the slot-location plugin consumes each new round locally.
53
+ let executorChildGuard: ExecutorChildGuardPort | undefined;
54
+ const input = {
55
+ directory: ctx.location.directory,
56
+ worktree: ctx.location.project.directory,
57
+ client: runtime.client,
58
+ routerChildRunner: runtime.childRunner,
59
+ routerHost: "v2" as const,
60
+ routerObservations: observations,
61
+ routerExecutor: access,
62
+ routerOnPlanAnnotate: (port: NonNullable<typeof annotate>) => { annotate = port; },
63
+ // Step pricing reads the catalog the adapter already queries; the plugin's single telemetry ingest comes back
64
+ // here so the event loop feeds the instance that also receives the verdicts (QA-2.1-7).
65
+ routerCatalog: async () => (await ctx.model.list({ location: { directory: ctx.location.directory } })).data,
66
+ // The agents of THIS plugin instance's location (QA-2.4-16): the host lists agents per location.
67
+ routerAgents: async () => (await ctx.agent.list({ location: { directory: ctx.location.directory } })).data,
68
+ ...(ctx.generate === undefined ? {} : { routerGenerate: ctx.generate }),
69
+ // The same host call the adapter uses for the config-reload and narration notices (src/compat/v2-hooks.ts): a transcript entry that
70
+ // does not resume the session (QA-2.4-R2-1).
71
+ routerSynthetic: async (notice: { sessionID: string; text: string; description: string }) => {
72
+ await ctx.session.synthetic({ sessionID: notice.sessionID, text: notice.text, description: notice.description, resume: false });
73
+ },
74
+ routerOnIngest: (created: Ingest) => { ingest = created; },
75
+ routerOnBypassState: (read: () => boolean) => { isBypassed = read; },
76
+ // QA-P21-1-3: the plugin's budget snapshot (guard state + read-only CAP state) for the adapter's budget notice.
77
+ routerOnBudgetSnapshot: (read: (childSessionID: string) => BudgetSnapshot) => { budgetSnapshot = read; },
78
+ routerHostBudget: (childSessionID: string, stepLimit: number | null) => observeHostBudget?.(childSessionID, stepLimit),
79
+ // QA-P21-2-4: the adapter's "this role agent is registered" check; QA-P21-2 nit 3: whether router_verify is registered.
80
+ routerRoleLive: (agent: string) => roleLive?.(agent),
81
+ routerOnVerifyEnabled: (read: () => boolean) => { verifyEnabled = read; },
82
+ routerOnRefusal: (record: NonNullable<typeof recordRefusal>) => { recordRefusal = record; },
83
+ routerOnSlotVerifier: (verifier: PlanTaskVerifier) => { slotVerifier = verifier; },
84
+ routerOnExecutorChildGuard: (port: ExecutorChildGuardPort) => { executorChildGuard = port; },
85
+ };
86
+ const hooks = await ModelRouterPlugin(input as unknown as PluginInput);
87
+ const prepared = await prep;
88
+ if (!prepared.ok) access.clear(prepared.reason);
89
+ if (prepared.ok && runtime.childRunner === undefined) access.clear("the child runner is not available");
90
+ const registration = registerV2Hooks(ctx, hooks, runtime, {
91
+ observations,
92
+ executor: (host) => createExecutor({ routerHost: "v2", directory }, { host, prepared, access, observations, ...(annotate ? { annotate } : {}) }) ?? null,
93
+ ...(ingest ? { ingest } : {}), ...(isBypassed ? { isBypassed } : {}), ...(budgetSnapshot ? { budgetSnapshot } : {}),
94
+ ...(verifyEnabled ? { routerVerifyEnabled: verifyEnabled } : {}),
95
+ ...(recordRefusal ? { recordRefusal } : {}),
96
+ ...(slotVerifier ? { slotVerifier } : {}),
97
+ ...(executorChildGuard ? { executorChildGuard } : {}),
98
+ onHostBudget: (observe) => { observeHostBudget = observe; },
99
+ onRoleLive: (isLive) => { roleLive = isLive; },
100
+ });
101
+ if (observations === undefined) return registration;
102
+ const dispose = await registration;
103
+ let disposal: Promise<void> | undefined;
104
+ // Later cleanup calls can finish before the first drain: every caller must share its seal barrier.
105
+ // Start cleanup synchronously; the async wrapper converts synchronous throws to rejections.
106
+ return () => disposal ??= (async () => { await dispose(); })().finally(() => observations.close());
107
+ } catch (error) { observations?.close(); throw error; }
63
108
  },
64
109
  } satisfies Plugin.Plugin & { server: typeof ModelRouterPlugin };
@@ -33,12 +33,18 @@ export function describeBranch(state: BranchState): string {
33
33
  return `branch ${state.branch}`;
34
34
  }
35
35
 
36
+ /**
37
+ * QA-SYNC1-17: the window of a gate re-run after a restart on the journaled dispatch-time head: it runs from the dispatch to the
38
+ * gate after the restart, not only the dispatch.
39
+ */
40
+ export const AFTER_RESTART_WINDOW = "between the dispatch and the check after the restart";
41
+
36
42
  /** The gate's unverifiable reason for a switch (Artefact.branchSwitch); each side describes itself. */
37
43
  export function branchSwitchReason(
38
44
  root: string,
39
45
  before: BranchState,
40
46
  now: BranchState,
41
- when: "during the dispatch" | "since the producer returned" | "since the attempt that introduced this acceptance",
47
+ when: "during the dispatch" | typeof AFTER_RESTART_WINDOW | "since the producer returned" | "since the attempt that introduced this acceptance",
42
48
  ): string {
43
49
  const verb = before.branch === null && now.branch === null ? "moved" : "switched";
44
50
  return `the working tree ${root} ${verb} from ${describeBranch(before)} to ${describeBranch(now)} ${when}; the checks would verify another branch`;
@@ -122,7 +128,7 @@ export function treeMoveReason(
122
128
  before: HeadState,
123
129
  now: HeadState,
124
130
  move: TreeMove,
125
- when: "during the dispatch" | "since the producer returned",
131
+ when: "during the dispatch" | typeof AFTER_RESTART_WINDOW | "since the producer returned",
126
132
  ): string {
127
133
  switch (move.kind) {
128
134
  case "switched":
@@ -0,0 +1,35 @@
1
+ /**
2
+ * src/verify/canonical-path.ts — the canonical spelling of a path (QA-2.1-8, moved here by QA-1.3-16).
3
+ * A leaf module: it imports only node built-ins, so both the verify change-set store and the lease registry can use
4
+ * it without a dependency cycle.
5
+ */
6
+ import { basename, dirname, join, resolve } from "node:path";
7
+ import { realpathSync } from "node:fs";
8
+
9
+ /**
10
+ * QA-2.1-8: the canonical spelling of `path`, so a Windows 8.3 short name (`C:\Users\MARQUI~1\…`),
11
+ * a junction or symlink alias, and the long real path of one file key the same change-set entry.
12
+ * The native realpath of the path, or of its nearest existing ancestor with the missing tail
13
+ * appended (a deleted file keeps its directory's canonical spelling); lexical `resolve` when no
14
+ * ancestor resolves. A `realpath` that is not a function is replaced by the native one.
15
+ */
16
+ export function canonicalPath(
17
+ path: string,
18
+ realpath: (p: string) => string = realpathSync.native,
19
+ ): string {
20
+ const real: (p: string) => string = typeof realpath === "function" ? realpath : realpathSync.native;
21
+ const absolute = resolve(path);
22
+ let head = absolute;
23
+ const tail: string[] = [];
24
+ for (;;) {
25
+ try {
26
+ const found = real(head);
27
+ return tail.length === 0 ? found : join(found, ...tail.reverse());
28
+ } catch {
29
+ const parent = dirname(head);
30
+ if (parent === head) return absolute;
31
+ tail.push(basename(head));
32
+ head = parent;
33
+ }
34
+ }
35
+ }