opencode-model-router 2.2.0 → 2.3.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 (54) hide show
  1. package/CHANGELOG.md +65 -0
  2. package/README.md +35 -3
  3. package/package.json +4 -1
  4. package/src/commands/output.ts +4 -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 +118 -31
  8. package/src/escalate/attempt-recorder.ts +263 -0
  9. package/src/escalate/ladder.ts +484 -10
  10. package/src/escalate/resume.ts +208 -0
  11. package/src/escalate/variants.ts +391 -0
  12. package/src/index.ts +486 -38
  13. package/src/router/build-info.ts +151 -0
  14. package/src/router/config.ts +1365 -19
  15. package/src/router/protocol.ts +47 -0
  16. package/src/router/sessions.ts +441 -9
  17. package/src/routing/advisor/findings.ts +706 -0
  18. package/src/routing/advisor/index.ts +606 -0
  19. package/src/routing/classify/backends/host.ts +163 -0
  20. package/src/routing/classify/backends/openai-compatible.ts +275 -0
  21. package/src/routing/classify/backends/shared.ts +741 -0
  22. package/src/routing/classify/backends/typesafe.ts +315 -0
  23. package/src/routing/classify/fences.ts +96 -0
  24. package/src/routing/classify/index.ts +576 -0
  25. package/src/routing/classify/route-line.ts +298 -0
  26. package/src/routing/classify/rules.ts +607 -0
  27. package/src/routing/classify/scrub.ts +214 -0
  28. package/src/routing/classify/state.ts +148 -0
  29. package/src/routing/classify/text.ts +20 -0
  30. package/src/routing/classify/types.ts +1280 -0
  31. package/src/routing/commands/annotate-plan.ts +652 -0
  32. package/src/routing/commands/stats.ts +131 -0
  33. package/src/routing/commands/v1-roles.ts +64 -0
  34. package/src/routing/engine/index.ts +32 -0
  35. package/src/routing/engine/kernel.ts +597 -0
  36. package/src/routing/engine/ladders.ts +561 -0
  37. package/src/routing/engine/plan.ts +404 -0
  38. package/src/routing/engine/protocol-line.ts +133 -0
  39. package/src/routing/engine/simulate.ts +167 -0
  40. package/src/routing/engine/types.ts +270 -0
  41. package/src/routing/file-lock.ts +53 -0
  42. package/src/routing/outcomes/beta.ts +141 -0
  43. package/src/routing/outcomes/cost.ts +313 -0
  44. package/src/routing/outcomes/index.ts +172 -0
  45. package/src/routing/outcomes/ingest.ts +812 -0
  46. package/src/routing/outcomes/persist.ts +1058 -0
  47. package/src/routing/outcomes/stats.ts +602 -0
  48. package/src/routing/outcomes/store.ts +653 -0
  49. package/src/routing/outcomes/types.ts +954 -0
  50. package/src/routing/wire/dispatch.ts +799 -0
  51. package/src/routing/wire/hint.ts +208 -0
  52. package/src/routing/wire/host-info.ts +256 -0
  53. package/src/routing/wire/runtime.ts +259 -0
  54. package/src/v2.ts +15 -1
@@ -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,172 @@
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, parseStatsArgs, renderMarkdown, runStatsCli, summarize } from "./stats";
72
+ export type { ParseStatsResult, StatsArgs } from "./stats";
73
+
74
+ export interface AcquireOutcomesOptions {
75
+ /** Outcomes directory (already resolved with `resolveOutcomesDir`). */
76
+ readonly dir: string;
77
+ readonly tuning: Partial<OutcomeTuning>;
78
+ readonly logger: OutcomeLogger;
79
+ /** Injected persistence dependencies (tests); defaults to `nodePersistDeps(logger)`. */
80
+ readonly deps?: PersistDeps;
81
+ /** Injected timers (tests); defaults to `nodeScheduler()`. */
82
+ readonly scheduler?: FlushScheduler;
83
+ }
84
+
85
+ interface RegistryEntry {
86
+ readonly core: Omit<OutcomesBundle, "release">;
87
+ refs: number;
88
+ tuning: OutcomeTuning;
89
+ }
90
+
91
+ const registry = new Map<string, RegistryEntry>();
92
+ /**
93
+ * Directories whose last holder released but whose final flush has not finished (QA-1.3-1). The entry
94
+ * leaves `registry` at once (a new acquire builds a fresh bundle), but that bundle's initial load waits
95
+ * for this promise, so it can never read the file before the previous bundle wrote it.
96
+ */
97
+ const closing = new Map<string, Promise<void>>();
98
+
99
+ function registryId(dir: string): string {
100
+ const abs = resolve(dir);
101
+ return process.platform === "win32" ? abs.toLowerCase() : abs;
102
+ }
103
+
104
+ function unreadableResult(error: unknown): LoadResult {
105
+ const message = error instanceof Error ? error.message : String(error);
106
+ return { status: "corrupt", snapshot: { version: 1, entries: {} }, dropped: 0, savedAt: null, message };
107
+ }
108
+
109
+
110
+ function holderOf(entry: RegistryEntry, id: string): OutcomesBundle {
111
+ let released = false;
112
+ return {
113
+ ...entry.core,
114
+ async release(): Promise<void> {
115
+ if (released) return;
116
+ released = true;
117
+ entry.refs -= 1;
118
+ if (entry.refs > 0) return;
119
+ if (registry.get(id) === entry) registry.delete(id);
120
+ // Chain behind an earlier close of the same directory so closes finish in order.
121
+ const previous = closing.get(id);
122
+ const done: Promise<void> = Promise.all([previous, entry.core.flusher.dispose()])
123
+ .then(() => undefined)
124
+ .finally(() => {
125
+ if (closing.get(id) === done) closing.delete(id);
126
+ });
127
+ closing.set(id, done);
128
+ await done;
129
+ },
130
+ };
131
+ }
132
+
133
+ /**
134
+ * A3: the process-wide bundle for `options.dir`. The first caller creates the store, persister and
135
+ * flusher and starts loading the disk snapshot; later callers (same directory, case-insensitive on
136
+ * win32) share them and the last `tuning` wins. Each caller must `release()` its holder once; the last
137
+ * release flushes and disposes.
138
+ */
139
+ export function acquireOutcomes(options: AcquireOutcomesOptions): OutcomesBundle {
140
+ const id = registryId(options.dir);
141
+ const tuning = sanitizeTuning(options.tuning);
142
+ const existing = registry.get(id);
143
+ if (existing !== undefined) {
144
+ existing.refs += 1;
145
+ if (existing.tuning.halfLifeDays !== tuning.halfLifeDays || existing.tuning.maxEffectiveSamples !== tuning.maxEffectiveSamples) {
146
+ options.logger.info?.("[router] outcome tuning changed; the last caller wins", { previous: existing.tuning, next: tuning });
147
+ existing.core.store.configure(tuning);
148
+ existing.tuning = tuning;
149
+ }
150
+ return holderOf(existing, id);
151
+ }
152
+
153
+ const deps = options.deps ?? nodePersistDeps(options.logger);
154
+ const store = createOutcomeStore({ ...tuning, now: deps.now });
155
+ const persister = createPersister(options.dir, deps);
156
+ const ready: Promise<LoadResult> = (closing.get(id) ?? Promise.resolve())
157
+ .then(() => persister.load({ quarantine: true }))
158
+ .then((result) => {
159
+ if (result.status === "ok") store.fromSnapshot(result.snapshot, { mode: "merge" });
160
+ return result;
161
+ })
162
+ .catch((error: unknown) => unreadableResult(error));
163
+ const flusher = createFlusher(store, persister, {
164
+ now: deps.now,
165
+ scheduler: options.scheduler ?? nodeScheduler(),
166
+ logger: options.logger,
167
+ ready,
168
+ });
169
+ const entry: RegistryEntry = { core: { dir: options.dir, store, persister, flusher, ready }, refs: 1, tuning };
170
+ registry.set(id, entry);
171
+ return holderOf(entry, id);
172
+ }