opencode-model-router 2.2.0 → 2.4.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 (83) hide show
  1. package/CHANGELOG.md +214 -0
  2. package/README.md +90 -12
  3. package/package.json +4 -1
  4. package/src/commands/output.ts +24 -1
  5. package/src/compat/child-session.ts +43 -0
  6. package/src/compat/v2-client.ts +107 -7
  7. package/src/compat/v2-hooks.ts +1435 -44
  8. package/src/escalate/attempt-recorder.ts +263 -0
  9. package/src/escalate/ladder.ts +496 -10
  10. package/src/escalate/resume.ts +208 -0
  11. package/src/escalate/variants.ts +391 -0
  12. package/src/guard/enforce.ts +186 -22
  13. package/src/guard/guards.ts +132 -6
  14. package/src/guard/store.ts +5 -0
  15. package/src/index.ts +1193 -56
  16. package/src/router/build-info.ts +151 -0
  17. package/src/router/config.ts +1611 -19
  18. package/src/router/dispatch-header.ts +46 -4
  19. package/src/router/git-tools.ts +1152 -0
  20. package/src/router/guard-profile.ts +100 -0
  21. package/src/router/plugin-agents.ts +433 -0
  22. package/src/router/prompts.ts +26 -1
  23. package/src/router/protocol.ts +180 -0
  24. package/src/router/read-only.ts +149 -0
  25. package/src/router/role-agents.ts +409 -0
  26. package/src/router/roles-config.ts +429 -0
  27. package/src/router/roles.ts +600 -0
  28. package/src/router/run-tools.ts +913 -0
  29. package/src/router/sensitive-paths.ts +101 -0
  30. package/src/router/sessions.ts +533 -9
  31. package/src/router/subagents.ts +28 -1
  32. package/src/routing/advisor/findings.ts +898 -0
  33. package/src/routing/advisor/index.ts +614 -0
  34. package/src/routing/classify/backends/host.ts +163 -0
  35. package/src/routing/classify/backends/openai-compatible.ts +275 -0
  36. package/src/routing/classify/backends/shared.ts +741 -0
  37. package/src/routing/classify/backends/typesafe.ts +315 -0
  38. package/src/routing/classify/fences.ts +96 -0
  39. package/src/routing/classify/index.ts +594 -0
  40. package/src/routing/classify/route-line.ts +362 -0
  41. package/src/routing/classify/rules.ts +667 -0
  42. package/src/routing/classify/scrub.ts +214 -0
  43. package/src/routing/classify/state.ts +148 -0
  44. package/src/routing/classify/text.ts +20 -0
  45. package/src/routing/classify/types.ts +1310 -0
  46. package/src/routing/commands/annotate-plan.ts +652 -0
  47. package/src/routing/commands/stats.ts +134 -0
  48. package/src/routing/commands/v1-roles.ts +64 -0
  49. package/src/routing/engine/index.ts +32 -0
  50. package/src/routing/engine/kernel.ts +760 -0
  51. package/src/routing/engine/ladders.ts +802 -0
  52. package/src/routing/engine/plan.ts +404 -0
  53. package/src/routing/engine/protocol-line.ts +150 -0
  54. package/src/routing/engine/roles-taxonomy.ts +52 -0
  55. package/src/routing/engine/simulate.ts +167 -0
  56. package/src/routing/engine/types.ts +368 -0
  57. package/src/routing/file-lock.ts +53 -0
  58. package/src/routing/outcomes/beta.ts +147 -0
  59. package/src/routing/outcomes/cost.ts +313 -0
  60. package/src/routing/outcomes/index.ts +215 -0
  61. package/src/routing/outcomes/ingest.ts +960 -0
  62. package/src/routing/outcomes/persist.ts +1080 -0
  63. package/src/routing/outcomes/signals.ts +650 -0
  64. package/src/routing/outcomes/stats.ts +873 -0
  65. package/src/routing/outcomes/store.ts +673 -0
  66. package/src/routing/outcomes/types.ts +1093 -0
  67. package/src/routing/roles/authority.ts +495 -0
  68. package/src/routing/roles/binding.ts +543 -0
  69. package/src/routing/roles/policy.ts +416 -0
  70. package/src/routing/roles/work-root.ts +132 -0
  71. package/src/routing/wire/dispatch.ts +2088 -0
  72. package/src/routing/wire/hint.ts +222 -0
  73. package/src/routing/wire/host-info.ts +256 -0
  74. package/src/routing/wire/runtime.ts +348 -0
  75. package/src/v2.ts +40 -1
  76. package/src/verify/checker.ts +249 -7
  77. package/src/verify/deterministic.ts +10 -1
  78. package/src/verify/dispatch.ts +63 -6
  79. package/src/verify/dod.ts +127 -10
  80. package/src/verify/gate.ts +75 -7
  81. package/src/verify/types.ts +12 -0
  82. package/src/verify/wiring.ts +55 -10
  83. package/tiers.json +13 -5
@@ -0,0 +1,134 @@
1
+ /**
2
+ * `/router stats [--since <ISO>] [--until <ISO>] [--json] [--dir <path>]` and the checkpoint line of the bare `/router` (Phase 2.4.5, D18).
3
+ *
4
+ * The statistics are not re-implemented here: this runs the very `runStatsCli` that `scripts/routing-stats.ts` runs, over the same
5
+ * persister, so for the same directory and window the in-session output is the script's stdout, byte for byte. The one difference is
6
+ * that, while the engine is live, the rows still queued in memory are flushed to disk first (`flushNow`), so the table is current.
7
+ *
8
+ * Reading the directory lists it (it can hold thousands of scorecard logs, 1.3 QA-1.3-15), so this runs only from the user-invoked
9
+ * command, never from a hook.
10
+ *
11
+ * Failure policy (§0.10.10): never throws. A usage error or an unreadable store comes back as text with a non-zero `exit`, exactly
12
+ * as the script prints it on stderr; a failing flush is logged and the table is read from disk as it is.
13
+ *
14
+ * Role rows (P2.2): the "By role × tier" section is rendered by `runStatsCli` itself (`summarizeRoles` + `renderRoleMarkdown`), which is
15
+ * why the in-session output and the script agree for role rows; a log without role rows renders exactly as before.
16
+ */
17
+
18
+ import { readFileSync } from "node:fs";
19
+ import { homedir, tmpdir } from "node:os";
20
+ import { dirname, join } from "node:path";
21
+ import { fileURLToPath } from "node:url";
22
+ import { resolveRouting, type RouterConfig } from "../../router/config";
23
+ import { acquireOutcomes, createPersister, nodePersistDeps, resolveOutcomesDir, runStatsCli } from "../outcomes";
24
+ import { ingestSettings } from "../outcomes/ingest";
25
+ import type { OutcomesBundle } from "../outcomes";
26
+
27
+ export interface StatsCommandDeps {
28
+ readonly cfg: RouterConfig;
29
+ readonly host: "v1" | "v2";
30
+ readonly logger: { warn(message: string, extra?: Record<string, unknown>): void };
31
+ /** Test seam: the directories `~` and the default location resolve against. */
32
+ readonly env?: { readonly tmpdir: string; readonly homedir: string };
33
+ }
34
+
35
+ export interface StatsCommandResult {
36
+ /** Exactly what `scripts/routing-stats.ts` writes to stdout for the same arguments. */
37
+ readonly stdout: string;
38
+ /** What it writes to stderr (notes and warnings, e.g. "no outcome data"). */
39
+ readonly stderr: string;
40
+ /** The script's exit code (0 ok, 1 corrupt store, 2 usage). */
41
+ readonly exit: number;
42
+ }
43
+
44
+ function describeError(error: unknown): string {
45
+ return error instanceof Error ? error.message : String(error);
46
+ }
47
+
48
+ /** The text `/router stats` shows: stdout as the script prints it, then the script's stderr notes after a blank line. */
49
+ export function formatStatsReply(result: StatsCommandResult): string {
50
+ const notes = result.stderr.trim();
51
+ const body = result.stdout.endsWith("\n") ? result.stdout.slice(0, -1) : result.stdout;
52
+ return notes === "" ? body : `${body}${body === "" ? "" : "\n\n"}${notes}`;
53
+ }
54
+
55
+ /**
56
+ * Run the stats driver for `args` (the words after `stats`). The store directory is `routing.outcomes.path` (or the default); a
57
+ * `--dir` argument overrides it exactly as it does for the script.
58
+ */
59
+ export async function runStatsCommand(args: string, deps: StatsCommandDeps): Promise<StatsCommandResult> {
60
+ const env = deps.env ?? { tmpdir: tmpdir(), homedir: homedir() };
61
+ let stdout = "";
62
+ let stderr = "";
63
+ let bundle: OutcomesBundle | null = null;
64
+ try {
65
+ const routing = resolveRouting(deps.cfg, deps.host, deps.logger);
66
+ const defaultDir = resolveOutcomesDir(routing.outcomes.path, env);
67
+ // Only a live engine holds (or may hold) rows in memory; static never touches the store (§1.2).
68
+ const live = deps.host === "v2" ? ingestSettings(deps.cfg, "v2") : null;
69
+ if (live !== null) {
70
+ try {
71
+ bundle = acquireOutcomes({ dir: live.outcomesDir, tuning: live.tuning, logger: deps.logger });
72
+ await bundle.ready;
73
+ await bundle.flusher.flushNow();
74
+ } catch (error) {
75
+ deps.logger.warn("[router] /router stats: could not flush the queued rows; showing what is on disk", { error: describeError(error) });
76
+ }
77
+ }
78
+ const persistDeps = nodePersistDeps({ warn: () => undefined }); // the driver reports through stderr, not the logger
79
+ const exit = await runStatsCli(args.split(/\s+/).filter(Boolean), {
80
+ defaultDir,
81
+ open: (dir) => createPersister(resolveOutcomesDir(dir, env), persistDeps),
82
+ stdout: (text) => {
83
+ stdout += text;
84
+ },
85
+ stderr: (text) => {
86
+ stderr += text;
87
+ },
88
+ });
89
+ return { stdout, stderr, exit };
90
+ } catch (error) {
91
+ deps.logger.warn("[router] /router stats failed", { error: describeError(error) });
92
+ return { stdout, stderr: `${stderr}routing-stats: ${describeError(error)}\n`, exit: 1 };
93
+ } finally {
94
+ if (bundle !== null) {
95
+ try {
96
+ await bundle.release();
97
+ } catch (error) {
98
+ deps.logger.warn("[router] /router stats: releasing the outcome store failed", { error: describeError(error) });
99
+ }
100
+ }
101
+ }
102
+ }
103
+
104
+ // ---------------------------------------------------------------------------
105
+ // The checkpoint id of the bare `/router`
106
+ // ---------------------------------------------------------------------------
107
+
108
+ /** `<root>/docs/qa/cost-aware-routing/dogfood.md`: where the dogfood checkpoints are recorded (shipped with the checkout, not the package). */
109
+ export const DOGFOOD_PATH = join("docs", "qa", "cost-aware-routing", "dogfood.md");
110
+
111
+ function pluginRoot(): string {
112
+ return join(dirname(fileURLToPath(import.meta.url)), "..", "..", "..");
113
+ }
114
+
115
+ /**
116
+ * The id of the last checkpoint heading (`## DF<n> …`) of `dogfood.md`, e.g. `DF2`; `null` when the file is absent, unreadable
117
+ * or has none (a published package ships without it). Never throws.
118
+ */
119
+ export function readLastCheckpoint(root: () => string = pluginRoot): string | null {
120
+ try {
121
+ const text = readFileSync(join(root(), DOGFOOD_PATH), "utf-8");
122
+ let last: string | null = null;
123
+ for (const match of text.matchAll(/^##[ \t]+(DF\d+)\b/gm)) last = match[1] ?? last;
124
+ return last;
125
+ } catch {
126
+ return null; // no dogfood record next to this code: the line is simply omitted
127
+ }
128
+ }
129
+
130
+ /** `router: last checkpoint=DF2`, or `null` when there is none. */
131
+ export function checkpointLine(root?: () => string): string | null {
132
+ const id = readLastCheckpoint(root);
133
+ return id === null ? null : `router: last checkpoint=${id}`;
134
+ }
@@ -0,0 +1,64 @@
1
+ /**
2
+ * The v1 text-only `R:` line for an explicit `routing.roles` (plan D1, amendment A28, Phase 2.4).
3
+ *
4
+ * On OpenCode v1 the routing engine does not exist (`engine` is forced to `static`, D1). The one v1 effect is opt-in and prose only: when the
5
+ * user sets `routing.roles` explicitly, the orchestrator protocol's `R:` taxonomy line lists those agents as destinations for their
6
+ * classes (`R: … | by class: search→@explore implement→@general`). No model override, no classification, no outcome store, no new file.
7
+ *
8
+ * Without an explicit `routing.roles` nothing here changes anything: {@link applyV1Roles} returns the prompt it was given, the very same
9
+ * string, so the v1 protocol stays byte-identical (§1.2, D2).
10
+ */
11
+
12
+ import { resolveRouting, type RouterConfig } from "../../router/config";
13
+ import { swapTaxonomyLine } from "../../router/protocol";
14
+ import { generateTaxonomy } from "../engine/protocol-line";
15
+ import type { HostAgentInfo } from "../engine/types";
16
+ import type { PluginLogger } from "../../router/logger";
17
+
18
+ function isRecord(value: unknown): value is Record<string, unknown> {
19
+ return typeof value === "object" && value !== null;
20
+ }
21
+
22
+ /**
23
+ * The v1 agent list (`client.app.agents()`: `Agent` records with `name`, `mode` of `subagent`, `primary` or `all`, an optional model) as the
24
+ * line generator reads it. `all` can be dispatched as a subagent. Nothing is inferred about permissions or tools (the text-only line has
25
+ * no needs check), so every agent counts as permitted with no grants.
26
+ */
27
+ export function v1AgentInfos(raw: readonly unknown[]): HostAgentInfo[] {
28
+ const infos: HostAgentInfo[] = [];
29
+ for (const entry of raw) {
30
+ if (!isRecord(entry) || typeof entry.name !== "string" || entry.name === "") continue;
31
+ const model = isRecord(entry.model) && typeof entry.model.providerID === "string" && typeof entry.model.modelID === "string"
32
+ ? `${entry.model.providerID}/${entry.model.modelID}`
33
+ : null;
34
+ infos.push({
35
+ id: entry.name,
36
+ model,
37
+ mode: entry.mode === "primary" ? "primary" : "subagent",
38
+ hidden: entry.hidden === true,
39
+ permitted: true,
40
+ grants: [],
41
+ });
42
+ }
43
+ return infos;
44
+ }
45
+
46
+ /**
47
+ * True when the config carries an explicit `routing.roles` that names at least one agent (the only thing that can make the v1 line differ
48
+ * from today's). `roles: {}` is an explicit "none": nothing to list, so nothing is fetched or changed.
49
+ */
50
+ export function hasExplicitV1Roles(cfg: RouterConfig, logger?: Pick<PluginLogger, "warn">): boolean {
51
+ const routing = resolveRouting(cfg, "v1", logger);
52
+ return routing.applied.rolesSource === "configured" && Object.values(routing.roles).some((agents) => agents.length > 0);
53
+ }
54
+
55
+ /**
56
+ * `prompt` (the assembled system prompt) with its `R:` line extended by the configured roles. Returns `prompt` itself when the roles are not
57
+ * explicit, when the agent list is unknown, or when no configured agent is usable (`generateTaxonomy` then answers the shipped line).
58
+ */
59
+ export function applyV1Roles(prompt: string, cfg: RouterConfig, agents: readonly HostAgentInfo[] | null, logger?: Pick<PluginLogger, "warn">): string {
60
+ if (!hasExplicitV1Roles(cfg, logger) || agents === null) return prompt;
61
+ const routing = resolveRouting(cfg, "v1", logger);
62
+ const line = generateTaxonomy({ cfg, routing, host: "v1", store: null, agents });
63
+ return swapTaxonomyLine(prompt, cfg, line);
64
+ }
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Decision kernel (M4) — public surface of `src/routing/engine/*`.
3
+ *
4
+ * Re-exports only: no logic, no state. Design: `docs/qa/cost-aware-routing/phase-1.4.md` → §6.
5
+ */
6
+
7
+ export type * from "./types";
8
+ export {
9
+ DEFAULT_REMAINING_TURNS,
10
+ GIVE_UP_COST,
11
+ MIN_EVIDENCE_TO_SWITCH_DOWN,
12
+ candidateKey,
13
+ capabilityRank,
14
+ coversNeeds,
15
+ decide,
16
+ giveUpCost,
17
+ hasMinEvidence,
18
+ lowerEffortOnSameModel,
19
+ } from "./kernel";
20
+ export {
21
+ buildLadder,
22
+ escalateLadder,
23
+ floorRankOf,
24
+ grantsFromTools,
25
+ resolveChosen,
26
+ tierRankOf,
27
+ } from "./ladders";
28
+ export type { ChosenInput, LadderBuildInput } from "./ladders";
29
+ export { MIN_EVIDENCE_TO_MOVE, generateTaxonomy } from "./protocol-line";
30
+ export type { TaxonomyInput } from "./protocol-line";
31
+ export { annotateSteps, detectionOf, formatRouteLine, weakerDetection } from "./plan";
32
+ export type { AnnotateDeps, AnnotatedPlan, AnnotatedStep, PlanStep } from "./plan";