opencode-model-router 2.7.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 (111) hide show
  1. package/CHANGELOG.md +583 -0
  2. package/README.md +20 -0
  3. package/package.json +5 -1
  4. package/src/commands/approvals.ts +354 -0
  5. package/src/commands/output.ts +34 -1
  6. package/src/compat/background.ts +2439 -0
  7. package/src/compat/child-session.ts +6 -0
  8. package/src/compat/turn-state.ts +215 -0
  9. package/src/compat/v2-client.ts +136 -17
  10. package/src/compat/v2-hooks.ts +2853 -109
  11. package/src/compat/v2-observations.ts +328 -0
  12. package/src/executor/capacity.ts +362 -0
  13. package/src/executor/child-guards.ts +40 -0
  14. package/src/executor/command.ts +265 -0
  15. package/src/executor/compile/edges.ts +809 -0
  16. package/src/executor/compile/estimate.ts +158 -0
  17. package/src/executor/compile/footprint.ts +829 -0
  18. package/src/executor/compile/index.ts +1080 -0
  19. package/src/executor/compile/parse.ts +1492 -0
  20. package/src/executor/compile/residue.ts +706 -0
  21. package/src/executor/compile/validate.ts +280 -0
  22. package/src/executor/create.ts +672 -0
  23. package/src/executor/expand.ts +551 -0
  24. package/src/executor/git.ts +1214 -0
  25. package/src/executor/host-preamble.ts +17 -0
  26. package/src/executor/instructions.ts +35 -0
  27. package/src/executor/integrate/bisect.ts +73 -0
  28. package/src/executor/integrate/checks.ts +1086 -0
  29. package/src/executor/integrate/land.ts +177 -0
  30. package/src/executor/integrate/phase-suite.ts +407 -0
  31. package/src/executor/integrate/queue.ts +3083 -0
  32. package/src/executor/integrate/run-resolver.ts +19 -0
  33. package/src/executor/launch.ts +652 -0
  34. package/src/executor/ledger.ts +2208 -0
  35. package/src/executor/observations.ts +212 -0
  36. package/src/executor/paths.ts +159 -0
  37. package/src/executor/platform.ts +39 -0
  38. package/src/executor/process-identity.ts +19 -0
  39. package/src/executor/qa-loop.ts +470 -0
  40. package/src/executor/recovery.ts +403 -0
  41. package/src/executor/runtime.ts +6233 -0
  42. package/src/executor/schedule.ts +246 -0
  43. package/src/executor/slots/env.ts +145 -0
  44. package/src/executor/slots/pool.ts +1564 -0
  45. package/src/executor/slots/provision.ts +853 -0
  46. package/src/executor/tool.ts +534 -0
  47. package/src/executor/types.ts +2064 -0
  48. package/src/executor/unattended.ts +488 -0
  49. package/src/guard/store.ts +3 -1
  50. package/src/index.ts +1789 -288
  51. package/src/router/config.ts +823 -26
  52. package/src/router/dispatch-header.ts +95 -2
  53. package/src/router/git-tools.ts +266 -19
  54. package/src/router/leases.ts +1469 -0
  55. package/src/router/logger.ts +44 -32
  56. package/src/router/protocol.ts +44 -10
  57. package/src/router/role-agents.ts +334 -20
  58. package/src/router/roles-config.ts +93 -1
  59. package/src/router/roles.ts +1 -1
  60. package/src/router/run-tools.ts +56 -4
  61. package/src/router/sessions.ts +11 -0
  62. package/src/router/tool-paths.ts +308 -0
  63. package/src/router/work-roots.ts +86 -0
  64. package/src/routing/advisor/findings.ts +25 -5
  65. package/src/routing/classify/index.ts +7 -1
  66. package/src/routing/classify/route-line.ts +96 -5
  67. package/src/routing/classify/rules.ts +11 -0
  68. package/src/routing/classify/types.ts +26 -0
  69. package/src/routing/commands/stats.ts +2 -2
  70. package/src/routing/outcomes/durations.ts +225 -0
  71. package/src/routing/outcomes/index.ts +59 -2
  72. package/src/routing/outcomes/persist.ts +409 -0
  73. package/src/routing/outcomes/signals.ts +17 -0
  74. package/src/routing/outcomes/stats.ts +170 -11
  75. package/src/routing/outcomes/timings.ts +836 -0
  76. package/src/routing/outcomes/types.ts +98 -0
  77. package/src/routing/roles/admission.ts +1028 -0
  78. package/src/routing/roles/approvals.ts +957 -0
  79. package/src/routing/roles/binding.ts +116 -13
  80. package/src/routing/roles/check-placement.ts +112 -0
  81. package/src/routing/roles/git-root.ts +500 -0
  82. package/src/routing/roles/orphans.ts +68 -0
  83. package/src/routing/roles/policy.ts +30 -3
  84. package/src/routing/roles/read-set.ts +325 -0
  85. package/src/routing/roles/work-root.ts +12 -2
  86. package/src/routing/wire/dispatch.ts +697 -30
  87. package/src/routing/wire/hint.ts +56 -8
  88. package/src/routing/wire/working-set.ts +58 -0
  89. package/src/util/linear-trim.ts +32 -0
  90. package/src/v2.ts +94 -49
  91. package/src/verify/batch.ts +7 -2
  92. package/src/verify/branch.ts +141 -0
  93. package/src/verify/canonical-path.ts +35 -0
  94. package/src/verify/deterministic.ts +268 -17
  95. package/src/verify/dispatch.ts +348 -37
  96. package/src/verify/dod.ts +46 -0
  97. package/src/verify/edges.ts +817 -0
  98. package/src/verify/exec.ts +52 -9
  99. package/src/verify/gate.ts +349 -16
  100. package/src/verify/git-top.ts +43 -0
  101. package/src/verify/head.ts +107 -0
  102. package/src/verify/pending.ts +1846 -18
  103. package/src/verify/perimeter.ts +1186 -0
  104. package/src/verify/pin.ts +109 -0
  105. package/src/verify/plan-task.ts +729 -0
  106. package/src/verify/reference.ts +297 -8
  107. package/src/verify/risk.ts +16 -3
  108. package/src/verify/runner.ts +706 -32
  109. package/src/verify/tree.ts +372 -16
  110. package/src/verify/types.ts +66 -2
  111. package/src/verify/wiring.ts +1594 -46
@@ -43,6 +43,8 @@
43
43
 
44
44
  export interface PluginLogger {
45
45
  warn(message: string, extra?: Record<string, unknown>): void;
46
+ /** An informational entry (level `info`), posted like `warn`; optional so bare logger stubs stay valid. */
47
+ info?(message: string, extra?: Record<string, unknown>): void;
46
48
  /**
47
49
  * Await every post still in flight, so a shutting-down process does not drop
48
50
  * warnings it already decided to emit. Never rejects: a failing flush must
@@ -105,6 +107,9 @@ export function createPluginLogger(client?: unknown): PluginLogger {
105
107
  warn(message) {
106
108
  console.warn(`${CONSOLE_PREFIX} ${message}`);
107
109
  },
110
+ info(message) {
111
+ console.info(`${CONSOLE_PREFIX} ${message}`);
112
+ },
108
113
  // console.warn is synchronous, so there is never anything to wait for.
109
114
  flush: () => Promise.resolve(),
110
115
  };
@@ -114,40 +119,47 @@ export function createPluginLogger(client?: unknown): PluginLogger {
114
119
  // stays bounded on a long-lived server rather than growing for its lifetime.
115
120
  const inFlight = new Set<Promise<void>>();
116
121
 
122
+ const post = (level: "warn" | "info", message: string, extra?: Record<string, unknown>): void => {
123
+ const toConsole = () => (level === "warn" ? console.warn : console.info)(`${CONSOLE_PREFIX} ${message}`);
124
+ let result: unknown;
125
+ try {
126
+ // Bound to `app` on purpose — see (1) in the module comment. Calling
127
+ // the detached reference would throw on every real client.
128
+ result = log.call(app, {
129
+ body: {
130
+ service: LOG_SERVICE,
131
+ level,
132
+ message,
133
+ ...(extra ? { extra } : {}),
134
+ },
135
+ });
136
+ } catch {
137
+ // A synchronous throw means the transport is unusable; say it somewhere.
138
+ toConsole();
139
+ return;
140
+ }
141
+ // Fire-and-forget: never await, but never leave a rejection unhandled
142
+ // either, and do not lose the diagnostic when the post fails — whether it
143
+ // fails by rejecting or by resolving with an error. See (2) above.
144
+ const settled: Promise<void> = Promise.resolve(result)
145
+ .then((value) => {
146
+ if (isErrorResult(value)) toConsole();
147
+ })
148
+ .catch(toConsole);
149
+ // Tracked so `flush` can wait for it. `settled` already absorbs its own
150
+ // failures, so nothing here can reject. See (3) above.
151
+ inFlight.add(settled);
152
+ void settled.finally(() => {
153
+ inFlight.delete(settled);
154
+ });
155
+ };
156
+
117
157
  return {
118
158
  warn(message, extra) {
119
- const toConsole = () => console.warn(`${CONSOLE_PREFIX} ${message}`);
120
- let result: unknown;
121
- try {
122
- // Bound to `app` on purpose — see (1) in the module comment. Calling
123
- // the detached reference would throw on every real client.
124
- result = log.call(app, {
125
- body: {
126
- service: LOG_SERVICE,
127
- level: "warn",
128
- message,
129
- ...(extra ? { extra } : {}),
130
- },
131
- });
132
- } catch {
133
- // A synchronous throw means the transport is unusable; say it somewhere.
134
- toConsole();
135
- return;
136
- }
137
- // Fire-and-forget: never await, but never leave a rejection unhandled
138
- // either, and do not lose the diagnostic when the post fails — whether it
139
- // fails by rejecting or by resolving with an error. See (2) above.
140
- const settled: Promise<void> = Promise.resolve(result)
141
- .then((value) => {
142
- if (isErrorResult(value)) toConsole();
143
- })
144
- .catch(toConsole);
145
- // Tracked so `flush` can wait for it. `settled` already absorbs its own
146
- // failures, so nothing here can reject. See (3) above.
147
- inFlight.add(settled);
148
- void settled.finally(() => {
149
- inFlight.delete(settled);
150
- });
159
+ post("warn", message, extra);
160
+ },
161
+ info(message, extra) {
162
+ post("info", message, extra);
151
163
  },
152
164
  async flush() {
153
165
  await Promise.allSettled([...inFlight]);
@@ -1,3 +1,4 @@
1
+ import { resolveRouting } from "./config";
1
2
  import type { RouterConfig, Preset, ModeConfig } from "./config";
2
3
  import type { RoleKind, RoleSpec } from "./roles";
3
4
  import { ROLE_MENU_INTENT, ROUTER_BUDGET_NOTE_PREFIX } from "./prompts";
@@ -54,38 +55,47 @@ export function buildRolesProtocol(cfg: RouterConfig, roles: ReadonlyMap<string,
54
55
  const taxonomy = generateRolesTaxonomy(new Map(enabled.map((spec) => [spec.agent, spec] as const)));
55
56
  const researcher = agentOf("research");
56
57
  const editor = agentOf("implement") ?? agentOf("general");
57
- const runner = agentOf("run");
58
58
  const compose = researcher !== undefined && editor !== undefined
59
59
  ? ` Compose: ${researcher} first, then paste its findings into the ${editor} dispatch.`
60
60
  : "";
61
+ const cost = editor !== undefined
62
+ ? `Cost: edit+run without a router-gated check gets the top tier. Slice non-design work into \`class=implement needs=edit d=deterministic\` ${editor} dispatches with \`check: testsPass\`; if a slice must run commands, add \`VERIFY:required\`.`
63
+ : "";
61
64
  // QA-P22-1-8: a tier agent is the exception for a command `router_run` refuses, never the default.
62
65
  // QA-P22-2-1: keyed on the router_run grant of ANY enabled role (the implementer holds it too), not on a `run` role.
63
66
  const rawShell = enabled.some((spec) => spec.authority.allow.includes("router_run"))
64
67
  ? `Only when \`router_run\` refuses a command that is not on its allowlist, ask the user or dispatch a tier agent explicitly.`
65
68
  : `For a command, ask the user or dispatch a tier agent explicitly.`;
69
+ const background = buildBackgroundDispatchesBlock(cfg);
70
+ // Cross-repo (P1.7): one sentence, only when `routing.repoParents` is configured; otherwise the text is unchanged.
71
+ const crossRepo = (cfg.routing?.repoParents?.length ?? 0) > 0
72
+ ? ` Cross-repo: name another repository with repo=<name> (and branch=<ref> when it has several worktrees) instead of root=; each dispatch edits one repository, and a role may read the others below routing.repoParents. A check may run in another repository of the read set with cwd= and must then use scope=full, e.g. \`check: testsPass cwd="<repo>" scope=full\`.`
73
+ : "";
66
74
  return [
67
75
  ROLES_PROTOCOL_HEADING,
68
76
  ``,
69
- `You are the orchestrator: delegate execution to role agents with \`subagent(agent="<role>", prompt="...")\` and answer the user yourself. Reading, searching and running commands are execution; you may make about 2 direct read-only calls per turn to settle a question. Run independent dispatches in parallel, in one message.`,
77
+ `Delegate execution via \`subagent(agent="<role>", prompt="...")\`; answer the user. Reads/searches/commands are execution; about 2 direct read-only calls/turn may settle a question. Parallelize independent dispatches in one message.`,
70
78
  ``,
71
- `Roles (pick by intent; the router narrows each grant to the task):`,
79
+ `Roles by intent (grants narrowed to task):`,
72
80
  ...menu,
73
81
  ...(taxonomy ? [``, taxonomy] : []),
74
82
  ``,
75
- `The router picks each dispatch's model: never set \`model\` or pick a tier; name the role.`,
83
+ `Router picks the model: never set \`model\` or pick a tier; name the role.`,
76
84
  ``,
77
85
  // QA-P22-1-1: `tier`/`pin` are not in the template; only a plan's `[tier:X]` tag is transcribed.
78
- `Route line: when present it must be the FIRST line of the prompt (the router removes it; a malformed one is refused for a role): \`[route class=<c> risk=<r> scope=<s> needs=<n,..> d=<d> budget=<n> root=<path>]\`, every key optional. class=search|recon|mechanical|implement|debug|design|review|other; risk=low|medium|high; scope=single|multi|repo; needs=shell|web|edit|network|external_dir (\`edit\` unlocks editing, \`shell\` router_run, where the role allows); d=deterministic|grader|none (counts only when the prompt's \`[acceptance]\` block backs it); budget=tool calls (up to twice the role's); root=the absolute work root. Only when the plan step carries \`[tier:X]\`, add \`tier=X pin\`; never otherwise.`,
86
+ `Optional route: FIRST prompt line (router removes it; a malformed one is refused for a role): \`[route class=<c> risk=<r> scope=<s> needs=<n,..> d=<d> budget=<n> root=<path>]\`; keys optional. class=search|recon|mechanical|implement|debug|design|review|other; risk=low|medium|high; scope=single|multi|repo; needs=shell|web|edit|network|external_dir (\`edit\`=editing, \`shell\`=router_run, role permitting); d=deterministic|grader|none (counts only when the prompt's \`[acceptance]\` block backs it); budget=tool calls (max 2x role budget); root=absolute work root. Only when the plan step carries \`[tier:X]\`, add \`tier=X pin\`; never otherwise.`,
79
87
  ``,
80
- `Work root: a role works only in the session directory or one git worktree of this repo; for a worktree put \`root=<absolute path>\` on the route line (quote a path with spaces) and in ENVIRONMENT.`,
88
+ ...(cost === "" ? [] : [cost, ``]),
89
+ `Work root: only the session directory or one git worktree of this repo; for a worktree set \`root=<absolute path>\` on the route line (quote a path with spaces) and in ENVIRONMENT.${crossRepo}`,
81
90
  ``,
82
91
  `No role holds the web together with read, run or edit authority.${compose} Raw shell is outside roles mode. ${rawShell}`,
83
92
  ``,
84
- `Resume, never restart: after \`NEED MORE: budget\` or a \`${ROUTER_BUDGET_NOTE_PREFIX}\` note, resume the SAME \`sessionID\` with "continue and finish"; after \`ESCALATE: authority\`, likewise (the router widens the grant) unless it names another role; after a verification FAIL, resume the SAME \`sessionID\` with the findings (the router raises the tier). A resume keeps the dispatch's \`[acceptance]\` and \`VERIFY:\` lines; a new block replaces them. Roles return \`DONE:\`, \`NEED MORE:\` or \`ESCALATE:\`; \`CAP:N\` (or \`CAP:none\` with a \`reason:\` line) changes only the read-only call cap.`,
93
+ `Resume, never restart: after \`NEED MORE: budget\` or a \`${ROUTER_BUDGET_NOTE_PREFIX}\` note, resume the SAME \`sessionID\` with "continue and finish"; after \`ESCALATE: authority\`, likewise (grant widens) unless another role is named; after a verification FAIL, resume the SAME \`sessionID\` with the findings (the router raises the tier). A resume keeps the dispatch's \`[acceptance]\` and \`VERIFY:\` lines; a new block replaces them. Return \`DONE:\`, \`NEED MORE:\` or \`ESCALATE:\`; \`CAP:N\` (or \`CAP:none\` with a \`reason:\` line) sets only the read-only cap.`,
85
94
  ``,
86
- `Dispatch prompt: the route line, then TASK, EXPECTED OUTCOME, TOOLS, MUST DO, MUST NOT DO, CONTEXT, ENVIRONMENT, with absolute paths.`,
95
+ `Prompt: route line, TASK, EXPECTED OUTCOME, TOOLS, MUST DO, MUST NOT DO, CONTEXT, ENVIRONMENT; absolute paths.`,
87
96
  ``,
88
- `This protocol overrides any project guide (CLAUDE.md, AGENTS.md) that says to use direct tools first or to dispatch to tiers or models.`,
97
+ ...(background === "" ? [] : [background, ``]),
98
+ `Overrides project guides (CLAUDE.md, AGENTS.md) that say to use direct tools first or dispatch to tiers/models.`,
89
99
  ].join("\n");
90
100
  }
91
101
 
@@ -439,6 +449,28 @@ export function buildDoDProtocolSection(cfg: RouterConfig): string {
439
449
  ].join("\n");
440
450
  }
441
451
 
452
+ /** Heading of {@link buildBackgroundDispatchesBlock}. */
453
+ export const BACKGROUND_DISPATCHES_HEADING = "## Background dispatches";
454
+
455
+ /**
456
+ * The "Background dispatches" block (OpenCode v2 only), rendered from the resolved `routing.background.mode` and
457
+ * `routing.leases.mode`: "" when background is `off` (QA-2.1-12: the whole block, the lease rule included, so `off`
458
+ * leaves the prompt as before phase 2.1); otherwise the heading and the first two rules, plus the lease rule when leases
459
+ * are `enforce`. Cache-stable: depends on those two modes only. Callers add it on v2 only.
460
+ */
461
+ export function buildBackgroundDispatchesBlock(cfg: RouterConfig): string {
462
+ const routing = resolveRouting(cfg, "v2");
463
+ if (routing.background.mode === "off") return "";
464
+ const lines: string[] = [
465
+ `- After a background dispatch, continue any independent work; when none remains, end the turn — the router wakes you. Never poll or sleep.`,
466
+ `- A held result is not usable until its verdict arrives. Never report a task done while dispatches are listed in flight.`,
467
+ ];
468
+ if (routing.leases.mode === "enforce") {
469
+ lines.push(`- A lease refusal is resolved by waiting for the holder, not by retrying.`);
470
+ }
471
+ return [BACKGROUND_DISPATCHES_HEADING, ...lines].join("\n");
472
+ }
473
+
442
474
  /**
443
475
  * Assembles the full system prompt injected by the experimental.chat.system.transform hook.
444
476
  * For Claude orchestrators: prepends CLAUDE_ORCHESTRATOR_PREFIX + CLAUDE_ANTI_NARRATION.
@@ -451,8 +483,10 @@ export function assembleSystemPrompt(
451
483
  cfg: RouterConfig,
452
484
  orchestratorModel: string | undefined,
453
485
  enforcementOn: boolean = false,
486
+ host: "v1" | "v2" = "v1",
454
487
  ): string {
455
- const delegationProtocol = buildDelegationProtocol(cfg);
488
+ const background = host === "v2" ? buildBackgroundDispatchesBlock(cfg) : "";
489
+ const delegationProtocol = `${buildDelegationProtocol(cfg)}${background === "" ? "" : `\n\n${background}`}`;
456
490
  const dodSection = enforcementOn ? `\n\n---\n\n${buildDoDProtocolSection(cfg)}` : "";
457
491
  if (!isClaudeModel(orchestratorModel)) {
458
492
  return `${delegationProtocol}${dodSection}`;