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,147 @@
|
|
|
1
|
+
// ---------------------------------------------------------------------------
|
|
2
|
+
// Beta posteriors (M3): D4 observations, D7 rank priors, time decay, effective-sample cap.
|
|
3
|
+
//
|
|
4
|
+
// Design: docs/qa/cost-aware-routing/phase-1.3.md "Design (1.3.1)" §2.
|
|
5
|
+
// Pure module: no I/O, no clock of its own (every function takes `now`). Must stay runnable under
|
|
6
|
+
// Node type stripping (type-only imports use `import type`).
|
|
7
|
+
//
|
|
8
|
+
// Stored state is *evidence only* (prior excluded) expressed at `updatedAt`. The D7 prior is added on
|
|
9
|
+
// read, so changing a rank never rewrites evidence and old evidence decays toward the prior.
|
|
10
|
+
// ---------------------------------------------------------------------------
|
|
11
|
+
|
|
12
|
+
import type { BetaPrior, BetaState, OutcomeTuning, Posterior } from "./types";
|
|
13
|
+
import { DEFAULT_OUTCOME_TUNING } from "./types";
|
|
14
|
+
|
|
15
|
+
/** `alpha + beta` of every D7 prior. */
|
|
16
|
+
export const PRIOR_STRENGTH = 5;
|
|
17
|
+
/** Evidence totals below this are flushed to 0 so subnormals never reach storage. */
|
|
18
|
+
export const MIN_TINY = 1e-12;
|
|
19
|
+
export const DAY_MS = 86_400_000;
|
|
20
|
+
|
|
21
|
+
const MAX_PRIOR_OFFSET_CENTI = 95;
|
|
22
|
+
const MIN_PRIOR_OFFSET_CENTI = 30;
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* D7: prior for a candidate whose capability rank differs from the static tier of the class by `offset`
|
|
26
|
+
* (`rank(candidate) − rank(static tier)`). Means: ≤ −2 → 0.30 (floor), −1 → 0.55, 0 → 0.80, +1 → 0.85,
|
|
27
|
+
* +2 → 0.90, ≥ +3 → 0.95 (cap). Integer hundredths keep every value exact in binary.
|
|
28
|
+
*/
|
|
29
|
+
export function priorForRankOffset(offset: number): BetaPrior {
|
|
30
|
+
const o = Number.isFinite(offset) ? Math.round(offset) : 0;
|
|
31
|
+
const centi =
|
|
32
|
+
o >= 0
|
|
33
|
+
? Math.min(MAX_PRIOR_OFFSET_CENTI, 80 + 5 * o)
|
|
34
|
+
: Math.max(MIN_PRIOR_OFFSET_CENTI, 80 + 25 * o);
|
|
35
|
+
const alpha = centi / 20;
|
|
36
|
+
return { alpha, beta: PRIOR_STRENGTH - alpha };
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Same-rank prior, `Beta(4, 1)` (mean 0.80). */
|
|
40
|
+
export const SAME_RANK_PRIOR: BetaPrior = Object.freeze(priorForRankOffset(0));
|
|
41
|
+
|
|
42
|
+
function clamp(x: number, lo: number, hi: number): number {
|
|
43
|
+
return Math.min(hi, Math.max(lo, x));
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Defensive normalisation of `routing.outcomes` tuning (1.1 validates the same ranges). */
|
|
47
|
+
export function sanitizeTuning(tuning: Partial<OutcomeTuning> | null | undefined): OutcomeTuning {
|
|
48
|
+
const half = tuning?.halfLifeDays;
|
|
49
|
+
const cap = tuning?.maxEffectiveSamples;
|
|
50
|
+
return {
|
|
51
|
+
halfLifeDays: typeof half === "number" && Number.isFinite(half) ? clamp(half, 1, 365) : DEFAULT_OUTCOME_TUNING.halfLifeDays,
|
|
52
|
+
maxEffectiveSamples:
|
|
53
|
+
typeof cap === "number" && Number.isFinite(cap)
|
|
54
|
+
? clamp(Math.round(cap), 5, 1000)
|
|
55
|
+
: DEFAULT_OUTCOME_TUNING.maxEffectiveSamples,
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* `2 ** (−dt / (halfLifeDays · DAY_MS))` ∈ [0, 1]. A negative, NaN or non-finite `dt` counts as 0, so a
|
|
61
|
+
* clock going backwards gives factor 1 and counts never inflate.
|
|
62
|
+
*/
|
|
63
|
+
export function decayFactor(dtMs: number, halfLifeDays: number): number {
|
|
64
|
+
const dt = Number.isFinite(dtMs) && dtMs > 0 ? dtMs : 0;
|
|
65
|
+
const half = Number.isFinite(halfLifeDays) && halfLifeDays > 0 ? halfLifeDays : DEFAULT_OUTCOME_TUNING.halfLifeDays;
|
|
66
|
+
return 2 ** (-dt / (half * DAY_MS));
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Express `state` at `now`. Pure and multiplicative (materialising at t1 then t2 equals materialising at
|
|
71
|
+
* t2 directly). `updatedAt` never moves backwards by less than a day (clock jitter); further back it is
|
|
72
|
+
* re-stamped at `now` with the counts untouched (QA-1.3-7). A NaN `now` means "no time passed".
|
|
73
|
+
*/
|
|
74
|
+
export function decayTo(state: BetaState, now: number, tuning: OutcomeTuning): BetaState {
|
|
75
|
+
const t = Number.isFinite(now) ? now : state.updatedAt;
|
|
76
|
+
// QA-1.3-7: more than a day behind the stored instant is a clock correction, not jitter: re-stamp the
|
|
77
|
+
// evidence at `t` (counts untouched, so nothing inflates) instead of leaving it frozen in the "future".
|
|
78
|
+
if (t < state.updatedAt - DAY_MS) return { alpha: state.alpha, beta: state.beta, updatedAt: t };
|
|
79
|
+
const f = decayFactor(t - state.updatedAt, tuning.halfLifeDays);
|
|
80
|
+
let alpha = state.alpha * f;
|
|
81
|
+
let beta = state.beta * f;
|
|
82
|
+
if (alpha + beta < MIN_TINY) {
|
|
83
|
+
alpha = 0;
|
|
84
|
+
beta = 0;
|
|
85
|
+
}
|
|
86
|
+
return { alpha, beta, updatedAt: Math.max(state.updatedAt, t) };
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** Scale the evidence down to `maxEffectiveSamples` total, preserving the evidence mean (≤ 1e-15). */
|
|
90
|
+
export function capEvidence(state: BetaState, maxEffectiveSamples: number): BetaState {
|
|
91
|
+
const n = state.alpha + state.beta;
|
|
92
|
+
if (!(n > maxEffectiveSamples)) return state;
|
|
93
|
+
const scale = maxEffectiveSamples / n;
|
|
94
|
+
return { alpha: state.alpha * scale, beta: state.beta * scale, updatedAt: state.updatedAt };
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* D4: one observation. Decays the stored evidence to `now`, adds `weight` (default 1) to alpha (success) or beta, then caps.
|
|
99
|
+
* #84 P3.3 fix 2 (QA-P33F2-1-1): an independent grader's verdict of a role dispatch weighs 0.5 (plan §2.6). QA-P33F2-2 N-b: a
|
|
100
|
+
* weight that is not a finite number in (0, 1] is no observation at all — the state comes back unchanged (an absent state as
|
|
101
|
+
* empty evidence) — so no caller can add more than one observation, nor turn a malformed weight into a full one.
|
|
102
|
+
*/
|
|
103
|
+
export function observe(state: BetaState | undefined, success: boolean, now: number, tuning: OutcomeTuning, weight = 1): BetaState {
|
|
104
|
+
const at = Number.isFinite(now) ? now : (state?.updatedAt ?? 0);
|
|
105
|
+
if (!(Number.isFinite(weight) && weight > 0 && weight <= 1)) return state ?? { alpha: 0, beta: 0, updatedAt: at };
|
|
106
|
+
const base = decayTo(state ?? { alpha: 0, beta: 0, updatedAt: at }, at, tuning);
|
|
107
|
+
const next: BetaState = success
|
|
108
|
+
? { alpha: base.alpha + weight, beta: base.beta, updatedAt: base.updatedAt }
|
|
109
|
+
: { alpha: base.alpha, beta: base.beta + weight, updatedAt: base.updatedAt };
|
|
110
|
+
return capEvidence(next, tuning.maxEffectiveSamples);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function usablePrior(prior: BetaPrior): BetaPrior {
|
|
114
|
+
const ok = Number.isFinite(prior.alpha) && Number.isFinite(prior.beta) && prior.alpha > 0 && prior.beta > 0;
|
|
115
|
+
return ok ? prior : SAME_RANK_PRIOR;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Posterior at read time: prior + evidence decayed to `now` and capped. A read only: it never writes
|
|
120
|
+
* back, so reads cannot drift the stored state. Unknown evidence → exactly the prior.
|
|
121
|
+
*/
|
|
122
|
+
export function posteriorOf(
|
|
123
|
+
state: BetaState | undefined,
|
|
124
|
+
prior: BetaPrior,
|
|
125
|
+
now: number,
|
|
126
|
+
tuning: OutcomeTuning,
|
|
127
|
+
): Posterior {
|
|
128
|
+
const p = usablePrior(prior);
|
|
129
|
+
const e = state ? capEvidence(decayTo(state, now, tuning), tuning.maxEffectiveSamples) : { alpha: 0, beta: 0 };
|
|
130
|
+
const alpha = p.alpha + e.alpha;
|
|
131
|
+
const beta = p.beta + e.beta;
|
|
132
|
+
return { alpha, beta, mean: alpha / (alpha + beta), n: e.alpha + e.beta, prior: p };
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* Add two evidence states (loading a disk snapshot into a live store). Both are decayed to a common
|
|
137
|
+
* instant `max(a.updatedAt, b.updatedAt, now)` (forward only), summed, and capped.
|
|
138
|
+
*/
|
|
139
|
+
export function mergeBeta(a: BetaState, b: BetaState, now: number, tuning: OutcomeTuning): BetaState {
|
|
140
|
+
const newest = Math.max(a.updatedAt, b.updatedAt);
|
|
141
|
+
// A clock more than a day behind both states is a correction (QA-1.3-7): express the sum at `now`.
|
|
142
|
+
const t = !Number.isFinite(now) ? newest : newest - now > DAY_MS ? now : Math.max(newest, now);
|
|
143
|
+
const da = decayTo(a, t, tuning);
|
|
144
|
+
const db = decayTo(b, t, tuning);
|
|
145
|
+
const sum: BetaState = { alpha: da.alpha + db.alpha, beta: da.beta + db.beta, updatedAt: t };
|
|
146
|
+
return capEvidence(sum, tuning.maxEffectiveSamples);
|
|
147
|
+
}
|
|
@@ -0,0 +1,313 @@
|
|
|
1
|
+
// ---------------------------------------------------------------------------
|
|
2
|
+
// Cost accounting (M3): pricing state (A1), step USD (D6), tiered price lookup (A10), per-attempt
|
|
3
|
+
// running means, the D5 unit rule and the D8 expected cost / tax inputs.
|
|
4
|
+
//
|
|
5
|
+
// Design: docs/qa/cost-aware-routing/phase-1.3.md "Design (1.3.1)" §3.
|
|
6
|
+
// Pure module: no I/O, no clock. Must stay runnable under Node type stripping.
|
|
7
|
+
// ---------------------------------------------------------------------------
|
|
8
|
+
|
|
9
|
+
import type {
|
|
10
|
+
CostStats,
|
|
11
|
+
CostUnit,
|
|
12
|
+
MeanStat,
|
|
13
|
+
ModelPriceEntry,
|
|
14
|
+
ModelPricing,
|
|
15
|
+
OpenAttempt,
|
|
16
|
+
PricingState,
|
|
17
|
+
StepEndedTokens,
|
|
18
|
+
TokenMeans,
|
|
19
|
+
TokenSample,
|
|
20
|
+
UnitCandidate,
|
|
21
|
+
} from "./types";
|
|
22
|
+
|
|
23
|
+
/** D5: a candidate is USD-comparable on measured data once it has this many measured attempts. */
|
|
24
|
+
export const MIN_MEASURED_USD_SAMPLES = 3;
|
|
25
|
+
|
|
26
|
+
const PER_MILLION = 1e6;
|
|
27
|
+
|
|
28
|
+
// ---------------------------------------------------------------------------
|
|
29
|
+
// Pricing
|
|
30
|
+
// ---------------------------------------------------------------------------
|
|
31
|
+
|
|
32
|
+
function isNonNegativeFinite(x: unknown): x is number {
|
|
33
|
+
return typeof x === "number" && Number.isFinite(x) && x >= 0;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function isValidEntry(entry: unknown): entry is ModelPriceEntry {
|
|
37
|
+
if (typeof entry !== "object" || entry === null) return false;
|
|
38
|
+
const e = entry as Partial<Record<keyof ModelPriceEntry, unknown>>;
|
|
39
|
+
if (!isNonNegativeFinite(e.input) || !isNonNegativeFinite(e.output)) return false;
|
|
40
|
+
if (e.cache !== undefined) {
|
|
41
|
+
if (typeof e.cache !== "object" || e.cache === null) return false;
|
|
42
|
+
const cache = e.cache as { read?: unknown; write?: unknown };
|
|
43
|
+
if (cache.read !== undefined && !isNonNegativeFinite(cache.read)) return false;
|
|
44
|
+
if (cache.write !== undefined && !isNonNegativeFinite(cache.write)) return false;
|
|
45
|
+
}
|
|
46
|
+
if (e.tier !== undefined) {
|
|
47
|
+
if (typeof e.tier !== "object" || e.tier === null) return false;
|
|
48
|
+
const tier = e.tier as { type?: unknown; size?: unknown };
|
|
49
|
+
if (tier.type !== "context") return false;
|
|
50
|
+
if (typeof tier.size !== "number" || !Number.isFinite(tier.size) || tier.size <= 0) return false;
|
|
51
|
+
}
|
|
52
|
+
return true;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Valid price entries of a catalog `cost` (absent → `[]`, one object → `[obj]`, array → a filtered
|
|
57
|
+
* copy). An entry is kept only if input/output (and cache read/write when present) are finite and
|
|
58
|
+
* ≥ 0 and its `tier`, when present, is `{ type: "context", size > 0 }`.
|
|
59
|
+
*/
|
|
60
|
+
export function normalizePricing(pricing: ModelPricing): ModelPriceEntry[] {
|
|
61
|
+
if (pricing === null || pricing === undefined) return [];
|
|
62
|
+
const list: readonly unknown[] = Array.isArray(pricing) ? (pricing as readonly unknown[]) : [pricing];
|
|
63
|
+
return list.filter(isValidEntry);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** A1: unpriced = no valid entry, or every price field of every entry is 0 (absent from the catalog counts too). */
|
|
67
|
+
export function isUnpriced(pricing: ModelPricing): boolean {
|
|
68
|
+
const entries = normalizePricing(pricing);
|
|
69
|
+
if (entries.length === 0) return true;
|
|
70
|
+
return entries.every(
|
|
71
|
+
(e) => e.input === 0 && e.output === 0 && (e.cache?.read ?? 0) === 0 && (e.cache?.write ?? 0) === 0,
|
|
72
|
+
);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export function pricingState(pricing: ModelPricing): PricingState {
|
|
76
|
+
return isUnpriced(pricing) ? "unpriced" : "priced";
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* D6 + A1: USD of one step. `null` = no usable measurement: an invalid raw cost, or a `0` reported for
|
|
81
|
+
* an unpriced model (the host's default, not a measurement). A priced model's 0 stays 0, and an
|
|
82
|
+
* unpriced model's positive cost is kept (a host measurement). Tokens are always kept elsewhere.
|
|
83
|
+
*/
|
|
84
|
+
export function stepUSD(rawCost: number, pricing: PricingState): number | null {
|
|
85
|
+
if (typeof rawCost !== "number" || !Number.isFinite(rawCost) || rawCost < 0) return null;
|
|
86
|
+
if (rawCost === 0 && pricing === "unpriced") return null;
|
|
87
|
+
return rawCost;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* A10: price entry for a request of `inputTokens` context. Tiered entries (`context over N`) apply
|
|
92
|
+
* strictly above their size; the largest matching tier wins, else the base (untiered) entry, else the
|
|
93
|
+
* smallest tier (closest published price). `null` when the model has no valid entry.
|
|
94
|
+
*/
|
|
95
|
+
export function selectPriceEntry(pricing: ModelPricing, inputTokens: number): ModelPriceEntry | null {
|
|
96
|
+
const entries = normalizePricing(pricing);
|
|
97
|
+
if (entries.length === 0) return null;
|
|
98
|
+
const input = Number.isFinite(inputTokens) ? inputTokens : 0;
|
|
99
|
+
const tiered = entries
|
|
100
|
+
.filter((e): e is ModelPriceEntry & { tier: { type: "context"; size: number } } => e.tier !== undefined)
|
|
101
|
+
.sort((a, b) => a.tier.size - b.tier.size);
|
|
102
|
+
const base = entries.filter((e) => e.tier === undefined);
|
|
103
|
+
let best: ModelPriceEntry | null = null;
|
|
104
|
+
for (const e of tiered) if (input > e.tier.size) best = e;
|
|
105
|
+
return best ?? base[0] ?? tiered[0] ?? null;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** USD of a token sample (or per-attempt token means) at `entry`'s prices. Reasoning is billed as output. */
|
|
109
|
+
export function priceTokens(entry: ModelPriceEntry, t: TokenSample): number {
|
|
110
|
+
return (
|
|
111
|
+
(t.input * entry.input +
|
|
112
|
+
(t.output + t.reasoning) * entry.output +
|
|
113
|
+
t.cacheRead * (entry.cache?.read ?? 0) +
|
|
114
|
+
t.cacheWrite * (entry.cache?.write ?? 0)) /
|
|
115
|
+
PER_MILLION
|
|
116
|
+
);
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// ---------------------------------------------------------------------------
|
|
120
|
+
// Tokens
|
|
121
|
+
// ---------------------------------------------------------------------------
|
|
122
|
+
|
|
123
|
+
function nonNegativeOrZero(x: unknown): number {
|
|
124
|
+
return isNonNegativeFinite(x) ? x : 0;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
export function emptyTokenSample(): TokenSample {
|
|
128
|
+
return { input: 0, output: 0, reasoning: 0, cacheRead: 0, cacheWrite: 0 };
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** Replace any non-finite or negative field with 0. */
|
|
132
|
+
export function cleanTokenSample(t: TokenSample): TokenSample {
|
|
133
|
+
return {
|
|
134
|
+
input: nonNegativeOrZero(t?.input),
|
|
135
|
+
output: nonNegativeOrZero(t?.output),
|
|
136
|
+
reasoning: nonNegativeOrZero(t?.reasoning),
|
|
137
|
+
cacheRead: nonNegativeOrZero(t?.cacheRead),
|
|
138
|
+
cacheWrite: nonNegativeOrZero(t?.cacheWrite),
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/** Flatten `session.step.ended` `data.tokens` (S3 shape). Non-finite or negative fields become 0. */
|
|
143
|
+
export function tokenSampleFromEvent(t: StepEndedTokens): TokenSample {
|
|
144
|
+
return {
|
|
145
|
+
input: nonNegativeOrZero(t?.input),
|
|
146
|
+
output: nonNegativeOrZero(t?.output),
|
|
147
|
+
reasoning: nonNegativeOrZero(t?.reasoning),
|
|
148
|
+
cacheRead: nonNegativeOrZero(t?.cache?.read),
|
|
149
|
+
cacheWrite: nonNegativeOrZero(t?.cache?.write),
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
export function addTokens(a: TokenSample, b: TokenSample): TokenSample {
|
|
154
|
+
return {
|
|
155
|
+
input: a.input + b.input,
|
|
156
|
+
output: a.output + b.output,
|
|
157
|
+
reasoning: a.reasoning + b.reasoning,
|
|
158
|
+
cacheRead: a.cacheRead + b.cacheRead,
|
|
159
|
+
cacheWrite: a.cacheWrite + b.cacheWrite,
|
|
160
|
+
};
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
// ---------------------------------------------------------------------------
|
|
164
|
+
// Running means
|
|
165
|
+
// ---------------------------------------------------------------------------
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* Fold one sample: an exact arithmetic mean while `n + 1 ≤ maxEffectiveSamples`, then an EWMA with
|
|
169
|
+
* weight `1 / maxEffectiveSamples` (bounded memory, follows price and behaviour drift). `n` is the
|
|
170
|
+
* uncapped sample count. Cost statistics are not time-decayed (only Beta evidence is).
|
|
171
|
+
*/
|
|
172
|
+
export function updateMean(stat: MeanStat, x: number, maxEffectiveSamples: number): MeanStat {
|
|
173
|
+
const n1 = stat.n + 1;
|
|
174
|
+
const w = 1 / Math.min(n1, Math.max(1, maxEffectiveSamples));
|
|
175
|
+
return { mean: stat.mean + (x - stat.mean) * w, n: n1 };
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/** {@link updateMean} per token field with a shared `n`. */
|
|
179
|
+
export function updateTokenMeans(t: TokenMeans, sample: TokenSample, maxEffectiveSamples: number): TokenMeans {
|
|
180
|
+
const n1 = t.n + 1;
|
|
181
|
+
const w = 1 / Math.min(n1, Math.max(1, maxEffectiveSamples));
|
|
182
|
+
return {
|
|
183
|
+
n: n1,
|
|
184
|
+
input: t.input + (sample.input - t.input) * w,
|
|
185
|
+
output: t.output + (sample.output - t.output) * w,
|
|
186
|
+
reasoning: t.reasoning + (sample.reasoning - t.reasoning) * w,
|
|
187
|
+
cacheRead: t.cacheRead + (sample.cacheRead - t.cacheRead) * w,
|
|
188
|
+
cacheWrite: t.cacheWrite + (sample.cacheWrite - t.cacheWrite) * w,
|
|
189
|
+
};
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
export function emptyMeanStat(): MeanStat {
|
|
193
|
+
return { mean: 0, n: 0 };
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
export function emptyTokenMeans(): TokenMeans {
|
|
197
|
+
return { n: 0, input: 0, output: 0, reasoning: 0, cacheRead: 0, cacheWrite: 0 };
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
export function emptyCostStats(): CostStats {
|
|
201
|
+
return {
|
|
202
|
+
measuredUSD: emptyMeanStat(),
|
|
203
|
+
unpricedAttempts: 0,
|
|
204
|
+
tokens: emptyTokenMeans(),
|
|
205
|
+
steps: emptyMeanStat(),
|
|
206
|
+
finalMessageTokens: emptyMeanStat(),
|
|
207
|
+
};
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/**
|
|
211
|
+
* Fold one finished attempt into a key's cost statistics (one sample = one attempt, C4). Tokens and
|
|
212
|
+
* step counts always count; the USD mean only takes attempts whose every step had a usable cost, the
|
|
213
|
+
* others bump `unpricedAttempts`. `finalMessageTokens` only takes attempts that reached a final step.
|
|
214
|
+
*/
|
|
215
|
+
export function foldAttempt(stats: CostStats, attempt: OpenAttempt, maxEffectiveSamples: number): CostStats {
|
|
216
|
+
const usdKnown = attempt.usdKnown && attempt.steps > 0;
|
|
217
|
+
return {
|
|
218
|
+
measuredUSD: usdKnown ? updateMean(stats.measuredUSD, attempt.usd, maxEffectiveSamples) : stats.measuredUSD,
|
|
219
|
+
unpricedAttempts: usdKnown ? stats.unpricedAttempts : stats.unpricedAttempts + 1,
|
|
220
|
+
tokens: updateTokenMeans(stats.tokens, attempt.tokens, maxEffectiveSamples),
|
|
221
|
+
steps: updateMean(stats.steps, attempt.steps, maxEffectiveSamples),
|
|
222
|
+
finalMessageTokens:
|
|
223
|
+
attempt.finalOutput !== null
|
|
224
|
+
? updateMean(stats.finalMessageTokens, attempt.finalOutput, maxEffectiveSamples)
|
|
225
|
+
: stats.finalMessageTokens,
|
|
226
|
+
};
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
function mergeMean(a: MeanStat, b: MeanStat): MeanStat {
|
|
230
|
+
const n = a.n + b.n;
|
|
231
|
+
return { mean: n > 0 ? (a.mean * a.n + b.mean * b.n) / n : 0, n };
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
export function mergeTokenMeans(a: TokenMeans, b: TokenMeans): TokenMeans {
|
|
235
|
+
const n = a.n + b.n;
|
|
236
|
+
if (n === 0) return emptyTokenMeans();
|
|
237
|
+
const mix = (x: number, y: number): number => (x * a.n + y * b.n) / n;
|
|
238
|
+
return {
|
|
239
|
+
n,
|
|
240
|
+
input: mix(a.input, b.input),
|
|
241
|
+
output: mix(a.output, b.output),
|
|
242
|
+
reasoning: mix(a.reasoning, b.reasoning),
|
|
243
|
+
cacheRead: mix(a.cacheRead, b.cacheRead),
|
|
244
|
+
cacheWrite: mix(a.cacheWrite, b.cacheWrite),
|
|
245
|
+
};
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/** n-weighted merge (loading a disk snapshot into a live store). */
|
|
249
|
+
export function mergeCostStats(a: CostStats, b: CostStats): CostStats {
|
|
250
|
+
return {
|
|
251
|
+
measuredUSD: mergeMean(a.measuredUSD, b.measuredUSD),
|
|
252
|
+
unpricedAttempts: a.unpricedAttempts + b.unpricedAttempts,
|
|
253
|
+
tokens: mergeTokenMeans(a.tokens, b.tokens),
|
|
254
|
+
steps: mergeMean(a.steps, b.steps),
|
|
255
|
+
finalMessageTokens: mergeMean(a.finalMessageTokens, b.finalMessageTokens),
|
|
256
|
+
};
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
// ---------------------------------------------------------------------------
|
|
260
|
+
// D5 unit rule, D8 expected cost and tax
|
|
261
|
+
// ---------------------------------------------------------------------------
|
|
262
|
+
|
|
263
|
+
/**
|
|
264
|
+
* D5 (+ clarification C1): `usd` iff there is at least one candidate and **every** candidate is
|
|
265
|
+
* USD-comparable, i.e. has ≥ 3 measured attempts, or is priced and has a token profile to price (its
|
|
266
|
+
* own or the class-pooled one). Otherwise `ratio` for all of them. Units are never mixed.
|
|
267
|
+
*/
|
|
268
|
+
export function compareUnit(candidates: readonly UnitCandidate[]): CostUnit {
|
|
269
|
+
if (candidates.length === 0) return "ratio";
|
|
270
|
+
const allComparable = candidates.every(
|
|
271
|
+
(c) => c.measuredUSD.n >= MIN_MEASURED_USD_SAMPLES || (c.priced && c.tokenSamples >= 1),
|
|
272
|
+
);
|
|
273
|
+
return allComparable ? "usd" : "ratio";
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/**
|
|
277
|
+
* D8 `c_k` in USD per attempt: the measured mean once ≥ 3 attempts were measured, else (priced models
|
|
278
|
+
* only) the token profile priced at the catalog entry selected by the mean request context (A10), else
|
|
279
|
+
* `null`. Never invented: an unpriced model with fewer than 3 measured attempts has no USD estimate.
|
|
280
|
+
*/
|
|
281
|
+
export function expectedAttemptUSD(
|
|
282
|
+
stats: CostStats,
|
|
283
|
+
pricing: ModelPricing,
|
|
284
|
+
classProfile: TokenMeans | null,
|
|
285
|
+
): number | null {
|
|
286
|
+
if (stats.measuredUSD.n >= MIN_MEASURED_USD_SAMPLES) return stats.measuredUSD.mean;
|
|
287
|
+
if (isUnpriced(pricing)) return null;
|
|
288
|
+
const profile = stats.tokens.n >= 1 ? stats.tokens : classProfile !== null && classProfile.n >= 1 ? classProfile : null;
|
|
289
|
+
if (profile === null) return null;
|
|
290
|
+
const steps = stats.steps.n >= 1 ? stats.steps.mean : 1;
|
|
291
|
+
const ctx = (profile.input + profile.cacheRead + profile.cacheWrite) / Math.max(1, steps);
|
|
292
|
+
const entry = selectPriceEntry(pricing, ctx);
|
|
293
|
+
return entry === null ? null : priceTokens(entry, profile);
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/**
|
|
297
|
+
* D8 `tax`: USD the orchestrator pays to re-read the child's final message on each remaining turn
|
|
298
|
+
* (cache-read price, else the input price: QA-1.3-14). `null` until a final message was measured, or
|
|
299
|
+
* when the orchestrator model is unpriced; the kernel maps `null` to 0.
|
|
300
|
+
*/
|
|
301
|
+
export function taxUSD(
|
|
302
|
+
finalMessageTokens: MeanStat,
|
|
303
|
+
remainingTurns: number,
|
|
304
|
+
orchestratorPricing: ModelPricing,
|
|
305
|
+
orchestratorContextTokens: number,
|
|
306
|
+
): number | null {
|
|
307
|
+
if (finalMessageTokens.n === 0 || isUnpriced(orchestratorPricing)) return null;
|
|
308
|
+
const entry = selectPriceEntry(orchestratorPricing, orchestratorContextTokens);
|
|
309
|
+
if (entry === null) return null;
|
|
310
|
+
const turns = Number.isFinite(remainingTurns) && remainingTurns > 0 ? remainingTurns : 0;
|
|
311
|
+
// Re-reading the message costs the cache-read price; a model without one is billed at its input price.
|
|
312
|
+
return (finalMessageTokens.mean * turns * (entry.cache?.read ?? entry.input)) / PER_MILLION;
|
|
313
|
+
}
|
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
// ---------------------------------------------------------------------------
|
|
2
|
+
// Outcome store and cost accounting (M3) — public surface and the process-wide registry (A3).
|
|
3
|
+
//
|
|
4
|
+
// Design: docs/qa/cost-aware-routing/phase-1.3.md "Design (1.3.1)" §6.
|
|
5
|
+
// One store and one writer per process and outcomes directory: `acquireOutcomes` hands every caller
|
|
6
|
+
// (e.g. two plugin instances of the same host process) the same bundle and reference-counts it.
|
|
7
|
+
// No I/O of its own: persistence goes through persist.ts. Static mode never calls `acquireOutcomes`.
|
|
8
|
+
// ---------------------------------------------------------------------------
|
|
9
|
+
|
|
10
|
+
import { resolve } from "node:path";
|
|
11
|
+
import type {
|
|
12
|
+
LoadResult,
|
|
13
|
+
OutcomeLogger,
|
|
14
|
+
OutcomesBundle,
|
|
15
|
+
OutcomeTuning,
|
|
16
|
+
PersistDeps,
|
|
17
|
+
FlushScheduler,
|
|
18
|
+
} from "./types";
|
|
19
|
+
import { sanitizeTuning } from "./beta";
|
|
20
|
+
import { createOutcomeStore } from "./store";
|
|
21
|
+
import { createFlusher, createPersister, nodePersistDeps, nodeScheduler } from "./persist";
|
|
22
|
+
|
|
23
|
+
export * from "./types";
|
|
24
|
+
export {
|
|
25
|
+
DAY_MS,
|
|
26
|
+
MIN_TINY,
|
|
27
|
+
PRIOR_STRENGTH,
|
|
28
|
+
SAME_RANK_PRIOR,
|
|
29
|
+
capEvidence,
|
|
30
|
+
decayFactor,
|
|
31
|
+
decayTo,
|
|
32
|
+
mergeBeta,
|
|
33
|
+
observe,
|
|
34
|
+
posteriorOf,
|
|
35
|
+
priorForRankOffset,
|
|
36
|
+
sanitizeTuning,
|
|
37
|
+
} from "./beta";
|
|
38
|
+
export {
|
|
39
|
+
MIN_MEASURED_USD_SAMPLES,
|
|
40
|
+
addTokens,
|
|
41
|
+
compareUnit,
|
|
42
|
+
emptyCostStats,
|
|
43
|
+
expectedAttemptUSD,
|
|
44
|
+
foldAttempt,
|
|
45
|
+
isUnpriced,
|
|
46
|
+
mergeCostStats,
|
|
47
|
+
normalizePricing,
|
|
48
|
+
priceTokens,
|
|
49
|
+
pricingState,
|
|
50
|
+
selectPriceEntry,
|
|
51
|
+
stepUSD,
|
|
52
|
+
taxUSD,
|
|
53
|
+
tokenSampleFromEvent,
|
|
54
|
+
updateMean,
|
|
55
|
+
updateTokenMeans,
|
|
56
|
+
} from "./cost";
|
|
57
|
+
export { createOutcomeStore, parseSnapshot } from "./store";
|
|
58
|
+
export type { ParseSnapshotResult } from "./store";
|
|
59
|
+
export {
|
|
60
|
+
compactStamp,
|
|
61
|
+
createFlusher,
|
|
62
|
+
createPersister,
|
|
63
|
+
nodePersistDeps,
|
|
64
|
+
nodePersistFs,
|
|
65
|
+
nodeScheduler,
|
|
66
|
+
parseLogLine,
|
|
67
|
+
renameWithRetry,
|
|
68
|
+
resolveOutcomesDir,
|
|
69
|
+
} from "./persist";
|
|
70
|
+
|
|
71
|
+
export { USAGE, hasRoleRows, parseStatsArgs, renderMarkdown, renderRoleMarkdown, runStatsCli, summarize, summarizeRoles } from "./stats";
|
|
72
|
+
export type { ParseStatsResult, StatsArgs } from "./stats";
|
|
73
|
+
export {
|
|
74
|
+
REDISPATCH_MAX_EARLIER,
|
|
75
|
+
REDISPATCH_MIN_TOKENS,
|
|
76
|
+
REDISPATCH_SIMILARITY,
|
|
77
|
+
REDISPATCH_WINDOW_MS,
|
|
78
|
+
SAME_TASK_LINE_SHARE,
|
|
79
|
+
SIBLING_SHARED_MIN,
|
|
80
|
+
SIGNAL_MASS_CAPS,
|
|
81
|
+
SIGNAL_WEIGHTS,
|
|
82
|
+
detectRedispatch,
|
|
83
|
+
graderSignal,
|
|
84
|
+
isSignalObservation,
|
|
85
|
+
parseReturnPrefix,
|
|
86
|
+
returnSignal,
|
|
87
|
+
runSignal,
|
|
88
|
+
sameModel,
|
|
89
|
+
sharedLines,
|
|
90
|
+
signalMass,
|
|
91
|
+
signalReason,
|
|
92
|
+
signalRow,
|
|
93
|
+
signedWeight,
|
|
94
|
+
taskSection,
|
|
95
|
+
taskSimilarity,
|
|
96
|
+
tierOfModel,
|
|
97
|
+
tierRank,
|
|
98
|
+
verdictSignal,
|
|
99
|
+
} from "./signals";
|
|
100
|
+
export type {
|
|
101
|
+
DispatchText,
|
|
102
|
+
GraderVerdictInput,
|
|
103
|
+
GuardObservation,
|
|
104
|
+
RedispatchMatch,
|
|
105
|
+
RedispatchOptions,
|
|
106
|
+
ReturnContract,
|
|
107
|
+
ReturnPrefix,
|
|
108
|
+
ReturnSignalInput,
|
|
109
|
+
RunRecord,
|
|
110
|
+
RunSignalInput,
|
|
111
|
+
SignalObservation,
|
|
112
|
+
SignalOutcome,
|
|
113
|
+
SignalRowInput,
|
|
114
|
+
TierRung,
|
|
115
|
+
} from "./signals";
|
|
116
|
+
|
|
117
|
+
export interface AcquireOutcomesOptions {
|
|
118
|
+
/** Outcomes directory (already resolved with `resolveOutcomesDir`). */
|
|
119
|
+
readonly dir: string;
|
|
120
|
+
readonly tuning: Partial<OutcomeTuning>;
|
|
121
|
+
readonly logger: OutcomeLogger;
|
|
122
|
+
/** Injected persistence dependencies (tests); defaults to `nodePersistDeps(logger)`. */
|
|
123
|
+
readonly deps?: PersistDeps;
|
|
124
|
+
/** Injected timers (tests); defaults to `nodeScheduler()`. */
|
|
125
|
+
readonly scheduler?: FlushScheduler;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
interface RegistryEntry {
|
|
129
|
+
readonly core: Omit<OutcomesBundle, "release">;
|
|
130
|
+
refs: number;
|
|
131
|
+
tuning: OutcomeTuning;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
const registry = new Map<string, RegistryEntry>();
|
|
135
|
+
/**
|
|
136
|
+
* Directories whose last holder released but whose final flush has not finished (QA-1.3-1). The entry
|
|
137
|
+
* leaves `registry` at once (a new acquire builds a fresh bundle), but that bundle's initial load waits
|
|
138
|
+
* for this promise, so it can never read the file before the previous bundle wrote it.
|
|
139
|
+
*/
|
|
140
|
+
const closing = new Map<string, Promise<void>>();
|
|
141
|
+
|
|
142
|
+
function registryId(dir: string): string {
|
|
143
|
+
const abs = resolve(dir);
|
|
144
|
+
return process.platform === "win32" ? abs.toLowerCase() : abs;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
function unreadableResult(error: unknown): LoadResult {
|
|
148
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
149
|
+
return { status: "corrupt", snapshot: { version: 1, entries: {} }, dropped: 0, savedAt: null, message };
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
function holderOf(entry: RegistryEntry, id: string): OutcomesBundle {
|
|
154
|
+
let released = false;
|
|
155
|
+
return {
|
|
156
|
+
...entry.core,
|
|
157
|
+
async release(): Promise<void> {
|
|
158
|
+
if (released) return;
|
|
159
|
+
released = true;
|
|
160
|
+
entry.refs -= 1;
|
|
161
|
+
if (entry.refs > 0) return;
|
|
162
|
+
if (registry.get(id) === entry) registry.delete(id);
|
|
163
|
+
// Chain behind an earlier close of the same directory so closes finish in order.
|
|
164
|
+
const previous = closing.get(id);
|
|
165
|
+
const done: Promise<void> = Promise.all([previous, entry.core.flusher.dispose()])
|
|
166
|
+
.then(() => undefined)
|
|
167
|
+
.finally(() => {
|
|
168
|
+
if (closing.get(id) === done) closing.delete(id);
|
|
169
|
+
});
|
|
170
|
+
closing.set(id, done);
|
|
171
|
+
await done;
|
|
172
|
+
},
|
|
173
|
+
};
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* A3: the process-wide bundle for `options.dir`. The first caller creates the store, persister and
|
|
178
|
+
* flusher and starts loading the disk snapshot; later callers (same directory, case-insensitive on
|
|
179
|
+
* win32) share them and the last `tuning` wins. Each caller must `release()` its holder once; the last
|
|
180
|
+
* release flushes and disposes.
|
|
181
|
+
*/
|
|
182
|
+
export function acquireOutcomes(options: AcquireOutcomesOptions): OutcomesBundle {
|
|
183
|
+
const id = registryId(options.dir);
|
|
184
|
+
const tuning = sanitizeTuning(options.tuning);
|
|
185
|
+
const existing = registry.get(id);
|
|
186
|
+
if (existing !== undefined) {
|
|
187
|
+
existing.refs += 1;
|
|
188
|
+
if (existing.tuning.halfLifeDays !== tuning.halfLifeDays || existing.tuning.maxEffectiveSamples !== tuning.maxEffectiveSamples) {
|
|
189
|
+
options.logger.info?.("[router] outcome tuning changed; the last caller wins", { previous: existing.tuning, next: tuning });
|
|
190
|
+
existing.core.store.configure(tuning);
|
|
191
|
+
existing.tuning = tuning;
|
|
192
|
+
}
|
|
193
|
+
return holderOf(existing, id);
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
const deps = options.deps ?? nodePersistDeps(options.logger);
|
|
197
|
+
const store = createOutcomeStore({ ...tuning, now: deps.now });
|
|
198
|
+
const persister = createPersister(options.dir, deps);
|
|
199
|
+
const ready: Promise<LoadResult> = (closing.get(id) ?? Promise.resolve())
|
|
200
|
+
.then(() => persister.load({ quarantine: true }))
|
|
201
|
+
.then((result) => {
|
|
202
|
+
if (result.status === "ok") store.fromSnapshot(result.snapshot, { mode: "merge" });
|
|
203
|
+
return result;
|
|
204
|
+
})
|
|
205
|
+
.catch((error: unknown) => unreadableResult(error));
|
|
206
|
+
const flusher = createFlusher(store, persister, {
|
|
207
|
+
now: deps.now,
|
|
208
|
+
scheduler: options.scheduler ?? nodeScheduler(),
|
|
209
|
+
logger: options.logger,
|
|
210
|
+
ready,
|
|
211
|
+
});
|
|
212
|
+
const entry: RegistryEntry = { core: { dir: options.dir, store, persister, flusher, ready }, refs: 1, tuning };
|
|
213
|
+
registry.set(id, entry);
|
|
214
|
+
return holderOf(entry, id);
|
|
215
|
+
}
|