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.
- package/CHANGELOG.md +214 -0
- package/README.md +90 -12
- package/package.json +4 -1
- package/src/commands/output.ts +24 -1
- package/src/compat/child-session.ts +43 -0
- package/src/compat/v2-client.ts +107 -7
- package/src/compat/v2-hooks.ts +1435 -44
- package/src/escalate/attempt-recorder.ts +263 -0
- package/src/escalate/ladder.ts +496 -10
- package/src/escalate/resume.ts +208 -0
- package/src/escalate/variants.ts +391 -0
- package/src/guard/enforce.ts +186 -22
- package/src/guard/guards.ts +132 -6
- package/src/guard/store.ts +5 -0
- package/src/index.ts +1193 -56
- package/src/router/build-info.ts +151 -0
- package/src/router/config.ts +1611 -19
- package/src/router/dispatch-header.ts +46 -4
- package/src/router/git-tools.ts +1152 -0
- package/src/router/guard-profile.ts +100 -0
- package/src/router/plugin-agents.ts +433 -0
- package/src/router/prompts.ts +26 -1
- package/src/router/protocol.ts +180 -0
- package/src/router/read-only.ts +149 -0
- package/src/router/role-agents.ts +409 -0
- package/src/router/roles-config.ts +429 -0
- package/src/router/roles.ts +600 -0
- package/src/router/run-tools.ts +913 -0
- package/src/router/sensitive-paths.ts +101 -0
- package/src/router/sessions.ts +533 -9
- package/src/router/subagents.ts +28 -1
- package/src/routing/advisor/findings.ts +898 -0
- package/src/routing/advisor/index.ts +614 -0
- package/src/routing/classify/backends/host.ts +163 -0
- package/src/routing/classify/backends/openai-compatible.ts +275 -0
- package/src/routing/classify/backends/shared.ts +741 -0
- package/src/routing/classify/backends/typesafe.ts +315 -0
- package/src/routing/classify/fences.ts +96 -0
- package/src/routing/classify/index.ts +594 -0
- package/src/routing/classify/route-line.ts +362 -0
- package/src/routing/classify/rules.ts +667 -0
- package/src/routing/classify/scrub.ts +214 -0
- package/src/routing/classify/state.ts +148 -0
- package/src/routing/classify/text.ts +20 -0
- package/src/routing/classify/types.ts +1310 -0
- package/src/routing/commands/annotate-plan.ts +652 -0
- package/src/routing/commands/stats.ts +134 -0
- package/src/routing/commands/v1-roles.ts +64 -0
- package/src/routing/engine/index.ts +32 -0
- package/src/routing/engine/kernel.ts +760 -0
- package/src/routing/engine/ladders.ts +802 -0
- package/src/routing/engine/plan.ts +404 -0
- package/src/routing/engine/protocol-line.ts +150 -0
- package/src/routing/engine/roles-taxonomy.ts +52 -0
- package/src/routing/engine/simulate.ts +167 -0
- package/src/routing/engine/types.ts +368 -0
- package/src/routing/file-lock.ts +53 -0
- package/src/routing/outcomes/beta.ts +147 -0
- package/src/routing/outcomes/cost.ts +313 -0
- package/src/routing/outcomes/index.ts +215 -0
- package/src/routing/outcomes/ingest.ts +960 -0
- package/src/routing/outcomes/persist.ts +1080 -0
- package/src/routing/outcomes/signals.ts +650 -0
- package/src/routing/outcomes/stats.ts +873 -0
- package/src/routing/outcomes/store.ts +673 -0
- package/src/routing/outcomes/types.ts +1093 -0
- package/src/routing/roles/authority.ts +495 -0
- package/src/routing/roles/binding.ts +543 -0
- package/src/routing/roles/policy.ts +416 -0
- package/src/routing/roles/work-root.ts +132 -0
- package/src/routing/wire/dispatch.ts +2088 -0
- package/src/routing/wire/hint.ts +222 -0
- package/src/routing/wire/host-info.ts +256 -0
- package/src/routing/wire/runtime.ts +348 -0
- package/src/v2.ts +40 -1
- package/src/verify/checker.ts +249 -7
- package/src/verify/deterministic.ts +10 -1
- package/src/verify/dispatch.ts +63 -6
- package/src/verify/dod.ts +127 -10
- package/src/verify/gate.ts +75 -7
- package/src/verify/types.ts +12 -0
- package/src/verify/wiring.ts +55 -10
- package/tiers.json +13 -5
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Runner simulation (A25, QA-1.4-2) — the attempts the 1.5 escalation runner makes after a rung fails.
|
|
3
|
+
*
|
|
4
|
+
* D8 prices a candidate as "attempt it; if it fails and the failure is detected, the cascade continues". The
|
|
5
|
+
* cascade of a router rung is not a fixed chain: it is whatever `nextAction` decides from the attempt count,
|
|
6
|
+
* the cumulative cost, the cost ceiling, `maxAttemptsPerTier`, variant steps and the covered-tier skips of
|
|
7
|
+
* the policy. This module replays exactly that loop (`newLadderState` → `recordAttempt` → `nextAction` →
|
|
8
|
+
* `advance`) with a failing verdict after every attempt and returns the rungs it ran, so the kernel never
|
|
9
|
+
* prices an escalation the runner would not perform (e.g. a tier covered by a rung already tried, or a tier
|
|
10
|
+
* beyond the cost ceiling).
|
|
11
|
+
*
|
|
12
|
+
* Costs are in `costRatio` units, as the runner charges them (`action.costRatio ?? tier.costRatio`), whatever
|
|
13
|
+
* unit the kernel later prices in. Pure: no I/O, no clock, no randomness, no module state.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import {
|
|
17
|
+
advance,
|
|
18
|
+
newLadderState,
|
|
19
|
+
nextAction,
|
|
20
|
+
recordAttempt,
|
|
21
|
+
startCostRatio,
|
|
22
|
+
type EscalatePolicy,
|
|
23
|
+
type LadderState,
|
|
24
|
+
type LadderVerdict,
|
|
25
|
+
} from "../../escalate/ladder";
|
|
26
|
+
import { DEFAULT_VARIANT } from "../../escalate/variants";
|
|
27
|
+
|
|
28
|
+
/** One rung the runner runs: a tier on `model#variant`, charged `costRatio`. */
|
|
29
|
+
export interface RunnerRung {
|
|
30
|
+
readonly tier: string;
|
|
31
|
+
readonly model: string;
|
|
32
|
+
/** `null` = the model's default variant. */
|
|
33
|
+
readonly variant: string | null;
|
|
34
|
+
readonly costRatio: number;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** The base rung of a tier (its own `model`, `variant`, `costRatio`), or `undefined` for an unknown tier. */
|
|
38
|
+
export type TierBase = (tier: string) => RunnerRung | undefined;
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Upper bound on simulated attempts. `maxTotalAttempts` ends every real path (default 4); the bound only
|
|
42
|
+
* protects against an absurd configured value.
|
|
43
|
+
*/
|
|
44
|
+
export const MAX_SIMULATED_ATTEMPTS = 64;
|
|
45
|
+
|
|
46
|
+
const FAILED: LadderVerdict = { pass: false, outcome: "fail", reasons: [] };
|
|
47
|
+
|
|
48
|
+
function ownVariantInfo(policy: EscalatePolicy, tier: string) {
|
|
49
|
+
const perTier = policy.variants?.perTier;
|
|
50
|
+
return perTier !== undefined && Object.prototype.hasOwnProperty.call(perTier, tier) ? perTier[tier] : undefined;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Rungs the runner runs when it is started on `start` and every attempt fails with a detected failure, in
|
|
55
|
+
* order (the first is `start` itself, unless `floorTier` lifts the start tier: QA-1.4-17, the first attempt is
|
|
56
|
+
* then the floor tier's base). Ends when the runner gives up, when it would enter a tier the preset does not
|
|
57
|
+
* define, or after {@link MAX_SIMULATED_ATTEMPTS}.
|
|
58
|
+
*
|
|
59
|
+
* A start on a rung other than the tier's base is modelled as a delegation that already stepped there (its
|
|
60
|
+
* variant is recorded as tried, so the ladder never re-runs it).
|
|
61
|
+
*/
|
|
62
|
+
export function simulateRunner(policy: EscalatePolicy, tierBase: TierBase, start: RunnerRung): RunnerRung[] {
|
|
63
|
+
let state = newLadderState(start.tier, policy);
|
|
64
|
+
let first: RunnerRung;
|
|
65
|
+
if (state.currentTier === start.tier) {
|
|
66
|
+
const info = ownVariantInfo(policy, start.tier);
|
|
67
|
+
const variant = start.variant ?? DEFAULT_VARIANT;
|
|
68
|
+
if (info !== undefined && !info.effortConfigured && variant !== info.base) {
|
|
69
|
+
state = advance(state, {
|
|
70
|
+
action: "retry",
|
|
71
|
+
tier: start.tier,
|
|
72
|
+
variantStep: true,
|
|
73
|
+
model: info.model,
|
|
74
|
+
variant,
|
|
75
|
+
rung: { model: info.model, variant },
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
first = start;
|
|
79
|
+
} else {
|
|
80
|
+
// floorTier lifts the start: the first attempt runs the floor tier's base, whatever rung was asked for.
|
|
81
|
+
const base = tierBase(state.currentTier);
|
|
82
|
+
if (base === undefined) return [];
|
|
83
|
+
first = { ...base, costRatio: startCostRatio(policy, state) ?? base.costRatio };
|
|
84
|
+
}
|
|
85
|
+
return walk(policy, tierBase, state, first);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* QA-1.4-16: the rungs the runner runs AFTER a native agent has already made `seed.attempts` (its own-model
|
|
90
|
+
* rung and the owning tier's rungs) on tier `seed.tier`. The escalation out of a role chain continues the same
|
|
91
|
+
* delegation, so the attempts and the cost already spent count against `maxTotalAttempts` and the cost
|
|
92
|
+
* ceiling, the chain's tier has used its per-tier retries, and the models the chain ran are recorded as tried
|
|
93
|
+
* (a later tier on one of them is skipped like any covered tier). Returns the continuation only.
|
|
94
|
+
*/
|
|
95
|
+
export function simulateAfter(
|
|
96
|
+
policy: EscalatePolicy,
|
|
97
|
+
tierBase: TierBase,
|
|
98
|
+
seed: { readonly tier: string; readonly attempts: readonly RunnerRung[] },
|
|
99
|
+
): RunnerRung[] {
|
|
100
|
+
if (seed.attempts.length === 0) return [];
|
|
101
|
+
const spent = seed.attempts.reduce((sum, rung) => sum + rung.costRatio, 0);
|
|
102
|
+
let state = newLadderState(seed.tier, policy);
|
|
103
|
+
const info = ownVariantInfo(policy, seed.tier);
|
|
104
|
+
if (info !== undefined && !info.effortConfigured) {
|
|
105
|
+
// Record every rung the chain ran (raises `triedByModel`); `advance` of a variant step does exactly that.
|
|
106
|
+
for (const rung of seed.attempts) {
|
|
107
|
+
const variant = rung.variant ?? DEFAULT_VARIANT;
|
|
108
|
+
state = advance(state, {
|
|
109
|
+
action: "retry",
|
|
110
|
+
tier: seed.tier,
|
|
111
|
+
variantStep: true,
|
|
112
|
+
model: rung.model,
|
|
113
|
+
variant,
|
|
114
|
+
rung: { model: rung.model, variant },
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
const lastOwn = [...seed.attempts].reverse().find((rung) => rung.model === info.model);
|
|
118
|
+
state = { ...state, currentVariant: lastOwn === undefined ? null : (lastOwn.variant ?? DEFAULT_VARIANT) };
|
|
119
|
+
}
|
|
120
|
+
state = {
|
|
121
|
+
...state,
|
|
122
|
+
currentTier: seed.tier,
|
|
123
|
+
// The chain was this tier's retries: only a variant step or an escalation is left.
|
|
124
|
+
attemptsThisTier: Math.max(policy.maxAttemptsPerTier, state.attemptsThisTier),
|
|
125
|
+
totalAttempts: seed.attempts.length,
|
|
126
|
+
cumulativeCost: spent,
|
|
127
|
+
firstAttemptCost: seed.attempts[0]!.costRatio,
|
|
128
|
+
};
|
|
129
|
+
return walk(policy, tierBase, state, null);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* The shared loop: record the attempt just made (`current`; none for a seeded state), ask `nextAction` what
|
|
134
|
+
* the runner does after a detected failure, advance, and read the rung it lands on.
|
|
135
|
+
*/
|
|
136
|
+
function walk(policy: EscalatePolicy, tierBase: TierBase, start: LadderState, first: RunnerRung | null): RunnerRung[] {
|
|
137
|
+
let state = start;
|
|
138
|
+
let current = first;
|
|
139
|
+
const rungs: RunnerRung[] = [];
|
|
140
|
+
for (let attempt = 0; attempt < MAX_SIMULATED_ATTEMPTS; attempt++) {
|
|
141
|
+
if (current !== null) {
|
|
142
|
+
rungs.push(current);
|
|
143
|
+
state = recordAttempt(state, current.costRatio);
|
|
144
|
+
}
|
|
145
|
+
const action = nextAction(state, FAILED, policy);
|
|
146
|
+
if (action.action !== "retry" && action.action !== "escalate") break;
|
|
147
|
+
state = advance(state, action);
|
|
148
|
+
const base = tierBase(state.currentTier);
|
|
149
|
+
if (base === undefined) break;
|
|
150
|
+
if (current !== null && action.action === "retry" && action.variantStep !== true && state.currentVariant === undefined) {
|
|
151
|
+
// No variant info in the policy: a plain retry re-runs the rung it just ran (the runner still charges
|
|
152
|
+
// the tier's own ratio, A17).
|
|
153
|
+
current = { ...current, costRatio: action.costRatio ?? base.costRatio };
|
|
154
|
+
continue;
|
|
155
|
+
}
|
|
156
|
+
const info = ownVariantInfo(policy, state.currentTier);
|
|
157
|
+
const variant = state.currentVariant ?? info?.base ?? base.variant ?? DEFAULT_VARIANT;
|
|
158
|
+
current = {
|
|
159
|
+
tier: state.currentTier,
|
|
160
|
+
model: info?.model ?? base.model,
|
|
161
|
+
variant: variant === DEFAULT_VARIANT ? null : variant,
|
|
162
|
+
// A17: the runner charges the action's rung ratio, else the tier's own.
|
|
163
|
+
costRatio: action.costRatio ?? base.costRatio,
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
return rungs;
|
|
167
|
+
}
|
|
@@ -0,0 +1,368 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Decision kernel (M4) — shared types of `src/routing/engine/*`.
|
|
3
|
+
*
|
|
4
|
+
* Design: `docs/qa/cost-aware-routing/phase-1.4.md` → "Design (1.4.1)".
|
|
5
|
+
* Plan #74 §1.5 D5, D7, D8, D9 (amendment A16), D12, D13; amendments A1, A11.
|
|
6
|
+
*
|
|
7
|
+
* TYPES ONLY: every import is `import type`, so this module has no runtime
|
|
8
|
+
* dependency (the kernel stays pure and cheap to load). Producers:
|
|
9
|
+
* - `ladders.ts` (1.4.2) builds a {@link Ladder} per decision;
|
|
10
|
+
* - the caller (2.2 dispatch wiring, `protocol-line.ts`, `plan.ts`) assembles a
|
|
11
|
+
* {@link DecisionInput};
|
|
12
|
+
* - `kernel.ts` turns it into a {@link Decision}, which maps 1:1 onto the
|
|
13
|
+
* `DecisionRow` fields of the 1.3 decision log.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import type { ResolvedRouting } from "../../router/config";
|
|
17
|
+
import type { ExplorationConfig } from "../../router/roles";
|
|
18
|
+
import type { Detection, Need, TaskFacts } from "../classify/types";
|
|
19
|
+
import type { ClassifiedDispatch, EffectiveDetection } from "../roles/policy";
|
|
20
|
+
import type {
|
|
21
|
+
AgentRef,
|
|
22
|
+
CostUnit,
|
|
23
|
+
ModelPricing,
|
|
24
|
+
OutcomeStore,
|
|
25
|
+
RouteChoice,
|
|
26
|
+
} from "../outcomes/types";
|
|
27
|
+
|
|
28
|
+
// ---------------------------------------------------------------------------
|
|
29
|
+
// Candidates and ladders
|
|
30
|
+
// ---------------------------------------------------------------------------
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Where a rung comes from (D12):
|
|
34
|
+
* - `tier` — a rung of a router tier's own ladder (`resolveCandidates`);
|
|
35
|
+
* - `role-own-model` — a `routing.roles` agent on the model the host configured for it;
|
|
36
|
+
* - `role-tier-rung` — a `routing.roles` agent on a rung of the tier that owns the class
|
|
37
|
+
* (applied at dispatch by a per-call `model` override).
|
|
38
|
+
*/
|
|
39
|
+
export type CandidateSource = "tier" | "role-own-model" | "role-tier-rung" | "role-range";
|
|
40
|
+
|
|
41
|
+
/** One `(agent, model#variant)` the engine may dispatch, with what the kernel needs to price it. */
|
|
42
|
+
export interface Candidate {
|
|
43
|
+
/** `router` for a tier agent of the active preset, `host` for any other agent (outcome-key origin). */
|
|
44
|
+
readonly agent: AgentRef;
|
|
45
|
+
/** `provider/model`, never with a `#variant` suffix. */
|
|
46
|
+
readonly model: string;
|
|
47
|
+
/** Catalog variant id; `null` = the model's default (stored as `default`, A9). */
|
|
48
|
+
readonly variant: string | null;
|
|
49
|
+
/**
|
|
50
|
+
* Cost of one attempt in `costRatio` units (fast = 1), finite and > 0. Router rungs: the rung's own
|
|
51
|
+
* ratio from `resolveCandidates`. Role rungs: see `ladders.ts` (inherited, never invented).
|
|
52
|
+
*/
|
|
53
|
+
readonly costRatio: number;
|
|
54
|
+
/**
|
|
55
|
+
* Capability rank on the escalation ladder: index of the router tier in the escalate ladder for
|
|
56
|
+
* router rungs; for role rungs the rank of the tier that owns the class (D7 "inherited rank").
|
|
57
|
+
*/
|
|
58
|
+
readonly rank: number;
|
|
59
|
+
/** Router tier that owns the rung: the tier itself, or the class's owning tier for role rungs. */
|
|
60
|
+
readonly tier: string;
|
|
61
|
+
readonly source: CandidateSource;
|
|
62
|
+
/**
|
|
63
|
+
* Needs the agent's EVALUATED permissions grant (A11), supplied by the caller from host agent
|
|
64
|
+
* info — never inferred from the agent id. `null` = unknown: covers no need at all.
|
|
65
|
+
*/
|
|
66
|
+
readonly grants: readonly Need[] | null;
|
|
67
|
+
/** Catalog `cost` of `model`; absent/empty/all-zero = unpriced (A1). */
|
|
68
|
+
readonly pricing?: ModelPricing;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* The candidate graph of one decision. `next[k]` is the index of the rung the cascade of D8 moves to
|
|
73
|
+
* when candidate `k` fails and the failure is detected (`null` = terminal: give up at cost `U`). A candidate
|
|
74
|
+
* that has a simulated runner path in `paths` is priced through that path instead and its `next` is `null`
|
|
75
|
+
* (A25: the router rungs); role chains use `next`.
|
|
76
|
+
* `ladders.ts` guarantees the graph is acyclic; the kernel also treats any back edge, out-of-range or
|
|
77
|
+
* unusable successor as terminal, so no input can make it recurse forever.
|
|
78
|
+
*/
|
|
79
|
+
export interface Ladder {
|
|
80
|
+
readonly candidates: readonly Candidate[];
|
|
81
|
+
/** Same length as `candidates`. */
|
|
82
|
+
readonly next: readonly (number | null)[];
|
|
83
|
+
/**
|
|
84
|
+
* Rank of the class's static tier (`CLASS_STATIC_TIER`) on the same scale as `Candidate.rank`;
|
|
85
|
+
* `null` when the class has none (`other`) or that tier is not on the ladder. D7 prior offsets are
|
|
86
|
+
* `rank − classRank`.
|
|
87
|
+
*/
|
|
88
|
+
readonly classRank: number | null;
|
|
89
|
+
/** Candidates dropped while building the ladder (permissions, unknown agents, ...), for the log. */
|
|
90
|
+
readonly excluded: readonly ExcludedCandidate[];
|
|
91
|
+
/**
|
|
92
|
+
* Rungs the 1.5 runner reaches (variant steps, covered-tier entries) that the engine never dispatches on
|
|
93
|
+
* its own: priced exactly like candidates, never `best`. Indices `candidates.length + i` in {@link paths}.
|
|
94
|
+
*/
|
|
95
|
+
readonly reachable?: readonly Candidate[];
|
|
96
|
+
/**
|
|
97
|
+
* A25: per candidate, the attempts the 1.5 runner makes when every attempt fails and the failure is
|
|
98
|
+
* detected, as indices into `[...candidates, ...reachable]` (first = the candidate itself): retries,
|
|
99
|
+
* variant steps, escalations, covered-tier skips, `maxTotalAttempts` and the cost ceiling are already
|
|
100
|
+
* applied by simulating `nextAction`/`advance`. The path ends in a give-up (cost `U`). `null`/absent =
|
|
101
|
+
* the candidate is priced through its `next` pointer instead (role chains, hand-built ladders).
|
|
102
|
+
*/
|
|
103
|
+
readonly paths?: readonly (readonly number[] | null)[];
|
|
104
|
+
/**
|
|
105
|
+
* A34 (QA-G-B1): every rung of the active preset on the escalate ladder — modelled or not, its agent available or not — with
|
|
106
|
+
* its tier's rank: the table a dispatch's CAPABILITY rank is read from (`kernel.capabilityRank`). Absent on hand-built ladders:
|
|
107
|
+
* the router rungs of `candidates` and `reachable` stand in for it.
|
|
108
|
+
*/
|
|
109
|
+
readonly presetRungs?: readonly PresetRung[];
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** A34: one rung of the active preset and the rank of its tier on the escalate ladder. */
|
|
113
|
+
export interface PresetRung {
|
|
114
|
+
/** `provider/model`, never with a `#variant` suffix. */
|
|
115
|
+
readonly model: string;
|
|
116
|
+
readonly variant: string | null;
|
|
117
|
+
readonly rank: number;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
export type ExclusionReason =
|
|
121
|
+
/** The agent's evaluated permissions do not cover `TaskFacts.needs` (A11, D12). */
|
|
122
|
+
| "needs"
|
|
123
|
+
/** Not in the host agent list, `mode: primary`, `hidden`, not permitted for the parent, or reserved (D12). */
|
|
124
|
+
| "agent-unavailable"
|
|
125
|
+
/** The class has no static tier on the escalate ladder, so a role agent has no inherited rank (D7). */
|
|
126
|
+
| "no-owning-tier"
|
|
127
|
+
/** Same `(agent, model, variant)` as an earlier rung, or a role naming a router tier agent. */
|
|
128
|
+
| "duplicate"
|
|
129
|
+
/** A25: an other-model rung of a tier's `candidates`; the 1.5 runner never runs it (escalation territory). */
|
|
130
|
+
| "not-modelled";
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* What the caller knows about one host agent: `ctx.agent.list()` on v2 (router tier agents
|
|
134
|
+
* included), the config agent map plus the native agents on v1. Supplied, never inferred (A11).
|
|
135
|
+
*/
|
|
136
|
+
export interface HostAgentInfo {
|
|
137
|
+
readonly id: string;
|
|
138
|
+
/** `provider/model[#variant]` configured for the agent; absent/null = it runs on the parent's model. */
|
|
139
|
+
readonly model?: string | null;
|
|
140
|
+
/** Host agent mode; `primary` agents are never candidates (D12). */
|
|
141
|
+
readonly mode: string;
|
|
142
|
+
readonly hidden: boolean;
|
|
143
|
+
/** The parent session may dispatch it (host permission check). */
|
|
144
|
+
readonly permitted: boolean;
|
|
145
|
+
/** Needs its EVALUATED permissions grant (A11), e.g. via `ladders.grantsFromTools`. */
|
|
146
|
+
readonly grants: readonly Need[];
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
export interface ExcludedCandidate {
|
|
150
|
+
readonly agent: AgentRef;
|
|
151
|
+
readonly model: string;
|
|
152
|
+
readonly variant: string | null;
|
|
153
|
+
readonly why: ExclusionReason;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
// ---------------------------------------------------------------------------
|
|
157
|
+
// Kernel input
|
|
158
|
+
// ---------------------------------------------------------------------------
|
|
159
|
+
|
|
160
|
+
/** What the kernel reads from the 1.3 outcome store. */
|
|
161
|
+
export type EngineStoreView = Pick<OutcomeStore, "posterior" | "cost" | "classTokenProfile">;
|
|
162
|
+
|
|
163
|
+
/** The slice of the resolved `routing` block the kernel uses (D8, D9). */
|
|
164
|
+
export type KernelRouting = Pick<ResolvedRouting, "profile" | "margin" | "minClassConfidence" | "detection">;
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* The orchestrator's pick, fully resolved by the caller: the agent it named and the model#variant
|
|
168
|
+
* that agent runs on (the tier's rung for a router tier, the configured model for a host agent).
|
|
169
|
+
*/
|
|
170
|
+
export interface ChosenDispatch {
|
|
171
|
+
readonly agent: AgentRef;
|
|
172
|
+
/** `provider/model` (a `#variant` suffix is accepted and split off when `variant` is null). */
|
|
173
|
+
readonly model: string;
|
|
174
|
+
readonly variant: string | null;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** Orchestrator pricing for the D8 `tax` term (USD unit only). */
|
|
178
|
+
export interface OrchestratorCost {
|
|
179
|
+
readonly pricing: ModelPricing;
|
|
180
|
+
/** Current orchestrator context size in tokens (selects the A10 price entry). */
|
|
181
|
+
readonly contextTokens: number;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
export interface DecisionInput {
|
|
185
|
+
/** Classifier output (M2). `confidence` gates switching (D9) and store reads (1.2 → 1.4 handoff). */
|
|
186
|
+
readonly facts: TaskFacts;
|
|
187
|
+
readonly chosen: ChosenDispatch;
|
|
188
|
+
readonly ladder: Ladder;
|
|
189
|
+
/** Verification depth of the dispatch (its `[acceptance]` checks or a plan `d=`); `d = routing.detection[detection]`. */
|
|
190
|
+
readonly detection: Detection;
|
|
191
|
+
/** `[route pin]` (D13): never switched; `best` still computed. */
|
|
192
|
+
readonly pin: boolean;
|
|
193
|
+
readonly routing: KernelRouting;
|
|
194
|
+
/** `null` = no outcome data (static/degenerate case): priors and `costRatio` only. */
|
|
195
|
+
readonly store: EngineStoreView | null;
|
|
196
|
+
/** Rank of `enforcement.escalate.floorTier`; candidates below it are never `best` (D9). */
|
|
197
|
+
readonly floorRank?: number | null;
|
|
198
|
+
/** Needed only for a measured `tax` in USD; absent → `tax = 0`. */
|
|
199
|
+
readonly orchestrator?: OrchestratorCost | null;
|
|
200
|
+
/** D8 `remainingTurnsEstimate`; default 4. */
|
|
201
|
+
readonly remainingTurns?: number;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
// ---------------------------------------------------------------------------
|
|
205
|
+
// Kernel output
|
|
206
|
+
// ---------------------------------------------------------------------------
|
|
207
|
+
|
|
208
|
+
/** Why a candidate (other than the orchestrator's pick) could not be `best`. */
|
|
209
|
+
export type IneligibleReason =
|
|
210
|
+
/** Permissions do not cover `needs` (A11). */
|
|
211
|
+
| "needs"
|
|
212
|
+
/** Below `floorTier` (D9). */
|
|
213
|
+
| "floor"
|
|
214
|
+
/**
|
|
215
|
+
* `risk == high` and `d == none`: never down (D9, A34): a rank below the pick's CAPABILITY rank, or the pick's own model on a
|
|
216
|
+
* lower-effort variant at the same rank.
|
|
217
|
+
*/
|
|
218
|
+
| "never-down"
|
|
219
|
+
/** Non-finite or non-positive attempt cost. */
|
|
220
|
+
| "invalid-cost"
|
|
221
|
+
/** A27: not ranked above the pick and fewer than 5 recorded outcomes for its key: it cannot be `best`. */
|
|
222
|
+
| "evidence";
|
|
223
|
+
|
|
224
|
+
export type DecisionReasonCode =
|
|
225
|
+
| "switched"
|
|
226
|
+
| "kept:no-candidates"
|
|
227
|
+
| "kept:pinned"
|
|
228
|
+
| "kept:chosen-not-candidate"
|
|
229
|
+
| "kept:best-is-chosen"
|
|
230
|
+
| "kept:class-confidence"
|
|
231
|
+
| "kept:margin"
|
|
232
|
+
/** A24: a down switch whose `best` has fewer than 5 recorded outcomes. */
|
|
233
|
+
| "kept:evidence"
|
|
234
|
+
| "kept:invalid-config";
|
|
235
|
+
|
|
236
|
+
export interface Decision {
|
|
237
|
+
/** The orchestrator's pick (as dispatched unless `switched`). */
|
|
238
|
+
readonly chosen: RouteChoice;
|
|
239
|
+
/** Argmin of `C(k)` over the pick and the eligible candidates; `null` when nothing could be priced. */
|
|
240
|
+
readonly best: RouteChoice | null;
|
|
241
|
+
/** The engine would replace `chosen` with `best` (D9 as amended by A16); never with `pinned`. */
|
|
242
|
+
readonly switched: boolean;
|
|
243
|
+
readonly pinned: boolean;
|
|
244
|
+
/**
|
|
245
|
+
* Trust in `best` ∈ [0, 1]: `facts.confidence × n / (n + 5)` with `n` the effective evidence of
|
|
246
|
+
* `best`'s posterior (0 with priors only). Reported, never a gate.
|
|
247
|
+
*/
|
|
248
|
+
readonly confidence: number;
|
|
249
|
+
readonly reasonCode: DecisionReasonCode;
|
|
250
|
+
/** Human-readable reason, with the compared costs. */
|
|
251
|
+
readonly reason: string;
|
|
252
|
+
/**
|
|
253
|
+
* A27: the argmin BEFORE the evidence filter (the cheapest candidate that passes the permission, floor and never-down
|
|
254
|
+
* filters, whether or not it has evidence); `null` when nothing could be priced. It differs from `best` exactly when the
|
|
255
|
+
* evidence gate removed a cheaper candidate: the statistics log it in the row's trace.
|
|
256
|
+
*/
|
|
257
|
+
readonly argmin: RouteChoice | null;
|
|
258
|
+
/** `C(k)` per candidate key, finite numbers only, in `unit`. */
|
|
259
|
+
readonly costs: Readonly<Record<string, number>>;
|
|
260
|
+
/** D5: every cost of this decision is in this unit. */
|
|
261
|
+
readonly unit: CostUnit;
|
|
262
|
+
/** Candidates that could not be `best`, by key. */
|
|
263
|
+
readonly ineligible: Readonly<Record<string, IneligibleReason>>;
|
|
264
|
+
/** `best`'s candidate (its `agent`/`model`/`variant` are what an `enforce` swap writes); `null` with `best`. */
|
|
265
|
+
readonly target: Candidate | null;
|
|
266
|
+
/**
|
|
267
|
+
* A34 (QA-G-B1): the pick's CAPABILITY rank — the highest rank of a preset rung on the pick's model (`kernel.capabilityRank`),
|
|
268
|
+
* never below its candidate rank. Never-down and the A24/A27 "strictly higher rank" test compare against it; candidate ranks
|
|
269
|
+
* stay capped at the class's owning tier (A25). `null` when the pick is not a candidate.
|
|
270
|
+
*/
|
|
271
|
+
readonly pickRank: number | null;
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
// ---------------------------------------------------------------------------
|
|
275
|
+
// Role dispatches (role-tier-assurance plan §2.1, §2.3, P1.2 T1.2.3/T1.2.4) — additive
|
|
276
|
+
// ---------------------------------------------------------------------------
|
|
277
|
+
|
|
278
|
+
/**
|
|
279
|
+
* The tier window of one role dispatch, as `roles/policy.tierBounds` returns it (tier names of the escalate ladder):
|
|
280
|
+
* `floor`/`ceiling` already include the authority floor, `floorTier` and the running rung; `pinned` is the route-line
|
|
281
|
+
* `tier=` already lifted or clamped into the window (null = no pin).
|
|
282
|
+
*/
|
|
283
|
+
export interface RoleWindow {
|
|
284
|
+
readonly floor: string;
|
|
285
|
+
readonly ceiling: string;
|
|
286
|
+
readonly pinned: string | null;
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
/** One tier of a role ladder: its rank on the escalate ladder and its first candidate (`null` when every rung was a duplicate). */
|
|
290
|
+
export interface RoleLadderTier {
|
|
291
|
+
readonly tier: string;
|
|
292
|
+
readonly rank: number;
|
|
293
|
+
readonly first: number | null;
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/**
|
|
297
|
+
* The candidate graph of a role dispatch (T1.2.3): the rungs of every tier in `[floor, ceiling]`, all run by the role agent
|
|
298
|
+
* (`AgentRef` origin `role`, outcome keys `class|role:<agent>|provider/model#variant`). Every rung is priced through its
|
|
299
|
+
* simulated runner path under `ladders.roleEscalatePolicy` (the runtime's raise path: one tier per FAIL up to the ceiling).
|
|
300
|
+
*/
|
|
301
|
+
export interface RoleLadder extends Ladder {
|
|
302
|
+
/** The role agent. */
|
|
303
|
+
readonly role: string;
|
|
304
|
+
/** Ranks of the window on the escalate ladder; `null` when the window could not be placed (then there are no candidates). */
|
|
305
|
+
readonly floorRank: number | null;
|
|
306
|
+
readonly ceilingRank: number | null;
|
|
307
|
+
readonly tiers: readonly RoleLadderTier[];
|
|
308
|
+
/** Candidate index of the static default: the class's taxonomy tier clamped into the window; `null` when there are no candidates. */
|
|
309
|
+
readonly staticDefault: number | null;
|
|
310
|
+
/** Candidate index of the pinned tier (`RoleWindow.pinned`); `null` when not pinned. */
|
|
311
|
+
readonly pinnedIndex: number | null;
|
|
312
|
+
/** Window, default and pin notes for the decision row (`default:clamp:floor`, `pinned:heavy`, ...). */
|
|
313
|
+
readonly reasons: readonly string[];
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
/** `routing.exploration` for one dispatch (T1.2.4): the rate (clamped to `[0, MAX_EXPLORATION_RATE]`) and the RNG seed. */
|
|
317
|
+
export interface RoleExploration extends Pick<ExplorationConfig, "rate"> {
|
|
318
|
+
/** The decision row's id: the only seed of the exploration draw (same id → same draw). */
|
|
319
|
+
readonly decisionID: string;
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
export interface RoleDecisionInput {
|
|
323
|
+
/**
|
|
324
|
+
* The classify result (`ClassifyResult` itself: `facts`, `trace.rules`, `trace.routeLine`). The kernel reads the
|
|
325
|
+
* EFFECTIVE risk and scope from it (`roles/policy.effectiveFactsOf`, raise-only, QA-P12-1-1): never-down, `U` and
|
|
326
|
+
* exploration use that risk.
|
|
327
|
+
*/
|
|
328
|
+
readonly classified: ClassifiedDispatch;
|
|
329
|
+
readonly ladder: RoleLadder;
|
|
330
|
+
/**
|
|
331
|
+
* The EFFECTIVE detection (§2.1, A34; `roles/policy.effectiveDetection`): `deterministic` only when the router's own
|
|
332
|
+
* gate runs the checks. Never `ClassifyResult.detection` (the route line's claim).
|
|
333
|
+
*/
|
|
334
|
+
readonly detection: EffectiveDetection;
|
|
335
|
+
/** `routing.engine`: only `enforce` applies a kernel switch or explores. */
|
|
336
|
+
readonly engine: ResolvedRouting["engine"];
|
|
337
|
+
readonly routing: KernelRouting;
|
|
338
|
+
readonly store: EngineStoreView | null;
|
|
339
|
+
/** A resume: the rung the child runs on. The dispatch never moves below it and is never switched or explored. */
|
|
340
|
+
readonly resume?: { readonly model: string; readonly variant: string | null } | null;
|
|
341
|
+
/** Absent/null or rate 0 = no exploration. */
|
|
342
|
+
readonly exploration?: RoleExploration | null;
|
|
343
|
+
readonly orchestrator?: OrchestratorCost | null;
|
|
344
|
+
readonly remainingTurns?: number;
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
export interface RoleDecision {
|
|
348
|
+
/** The kernel's decision with `chosen` = {@link base} (`pinned` = the window has a pin). */
|
|
349
|
+
readonly decision: Decision;
|
|
350
|
+
/** The policy's pick before the kernel: the pinned tier, else the static default, raised to the running rung on a resume. */
|
|
351
|
+
readonly base: Candidate | null;
|
|
352
|
+
/**
|
|
353
|
+
* What the router sets as the per-call model. `null` = no candidate (reason `window:no-candidates`): P2.1 REFUSES the
|
|
354
|
+
* role dispatch. It never falls back to `buildEscalatePolicy`/`buildLadder` or to a tier agent on its own (QA-P12-1-5).
|
|
355
|
+
*/
|
|
356
|
+
readonly dispatch: Candidate | null;
|
|
357
|
+
/** `enforce` applied the kernel's switch (`dispatch` = `decision.target`); never on a resume, a pin or an exploration draw. */
|
|
358
|
+
readonly switched: boolean;
|
|
359
|
+
/** `dispatch` was drawn by exploration (reason `explore`). */
|
|
360
|
+
readonly explore: boolean;
|
|
361
|
+
/** Probability that this policy dispatches `dispatch` for this input, in (0, 1]; 1 when no draw was possible. */
|
|
362
|
+
readonly propensity: number;
|
|
363
|
+
/**
|
|
364
|
+
* `RoleLadder.reasons` plus `resume:running`, `resume:off-ladder` (raised to the running model's capability rank),
|
|
365
|
+
* `resume:off-ladder:lift` (unknown rank: raised to the window ceiling), `kept:resume`, `explore`.
|
|
366
|
+
*/
|
|
367
|
+
readonly reasons: readonly string[];
|
|
368
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import type { PersistFs, OutcomeLogger } from "./outcomes/types";
|
|
3
|
+
|
|
4
|
+
export const LOCK_STALE_MS = 30_000;
|
|
5
|
+
export type LockResult<T> = { status: "ran"; value: T } | { status: "busy" };
|
|
6
|
+
|
|
7
|
+
/** Exclusive create, bounded attempts, mtime-based stale recovery; never waits on the hot path.
|
|
8
|
+
* A process suspended longer than staleMs can lose its lease: this is a best-effort local-file lock.
|
|
9
|
+
* Lock errors propagate: callers choose whether an unlocked fallback is safe.
|
|
10
|
+
*/
|
|
11
|
+
export async function withLock<T>(
|
|
12
|
+
fs: PersistFs, dir: string, lockPath: string, now: () => number,
|
|
13
|
+
logger: OutcomeLogger, run: () => Promise<T>, staleMs = LOCK_STALE_MS,
|
|
14
|
+
): Promise<LockResult<T>> {
|
|
15
|
+
await fs.mkdirp(dir);
|
|
16
|
+
let acquired = false;
|
|
17
|
+
for (let attempt = 0; attempt < 3; attempt++) {
|
|
18
|
+
if (await fs.createExclusive(lockPath, String(now()))) {
|
|
19
|
+
acquired = true;
|
|
20
|
+
break;
|
|
21
|
+
}
|
|
22
|
+
const held = await fs.stat(lockPath);
|
|
23
|
+
if (held === null) continue;
|
|
24
|
+
if (now() - held.mtimeMs < staleMs) return { status: "busy" };
|
|
25
|
+
const grave = `${lockPath}.stale-${randomUUID()}`;
|
|
26
|
+
try {
|
|
27
|
+
await fs.rename(lockPath, grave);
|
|
28
|
+
} catch (error) {
|
|
29
|
+
if (typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT") continue;
|
|
30
|
+
throw error;
|
|
31
|
+
}
|
|
32
|
+
const moved = await fs.stat(grave);
|
|
33
|
+
if (moved !== null && now() - moved.mtimeMs < staleMs) {
|
|
34
|
+
try {
|
|
35
|
+
await fs.rename(grave, lockPath);
|
|
36
|
+
} catch (error) {
|
|
37
|
+
logger.warn("[router] could not put back a live file lock", { error: String(error) });
|
|
38
|
+
}
|
|
39
|
+
return { status: "busy" };
|
|
40
|
+
}
|
|
41
|
+
try { await fs.unlink(grave); } catch (error) {
|
|
42
|
+
logger.warn("[router] could not remove stale file lock", { error: String(error) });
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
if (!acquired) return { status: "busy" };
|
|
46
|
+
try {
|
|
47
|
+
return { status: "ran", value: await run() };
|
|
48
|
+
} finally {
|
|
49
|
+
try { await fs.unlink(lockPath); } catch (error) {
|
|
50
|
+
logger.warn("[router] could not remove file lock", { error: String(error) });
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
}
|