@try-works/dsh-minimal-router 0.0.0-stage → 0.2.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/lib/routing.js ADDED
@@ -0,0 +1,858 @@
1
+ // Plain-JS routing host runtime for the DSH profile.
2
+ //
3
+ // Run 36 (DEC-36-01/02/08/14/15): routing is model-only. The canonical,
4
+ // Effect-typed decision engine is packages/domain/src/routing.ts; the DSH host
5
+ // cannot load TypeScript, so this file is a faithful port of decide() plus the
6
+ // host-side decision writer and pre-step adapter.
7
+ //
8
+ // Gate order: residency -> headroom -> floor -> fallback. There is no scope
9
+ // gate: a role's configured chain picks the model, and the gates decide whether
10
+ // a local candidate can serve. A candidate that cannot serve is skipped to the
11
+ // NEXT model in that role's chain, whatever its target. Host application
12
+ // failures are integration facts recorded as notAppliedReason; they never
13
+ // replace the decision.
14
+
15
+ export const GATES = ["residency", "headroom", "floor", "fallback"]
16
+
17
+ // Run 36 (DEC-36-05): an old row READ from disk may still carry the removed
18
+ // scope gate; it must keep loading as history. New writes use GATES only, so
19
+ // host validateRow accepts LOAD_GATES for loads and GATES for records.
20
+ export const LOAD_GATES = [...GATES, "scope"]
21
+
22
+ export const PRESSURE_LEVELS = ["ok", "soft", "hard"]
23
+ export const MIN_HEADROOM_RATIO = 0.15
24
+
25
+ // R-36-10 (DEC-36-19): the engine's scheduler setting is the concurrency
26
+ // ceiling. The settings document is the oMLX global settings payload the
27
+ // telemetry snapshot carries as engineMax (the Routing page's "Concurrent"
28
+ // value); an absent setting falls back to this documented default at the host.
29
+ export const DEFAULT_CONCURRENCY_CEILING = 16
30
+
31
+ /**
32
+ * Resolve the host-facing ceiling from the engine's reported scheduler limit.
33
+ * Present and positive wins; absent falls back to the documented default.
34
+ * The decision itself treats a zero/invalid ceiling as "no ceiling" below.
35
+ */
36
+ export const concurrencyCeilingFor = (engineMax) =>
37
+ typeof engineMax === "number" && Number.isFinite(engineMax) && engineMax > 0
38
+ ? Math.floor(engineMax)
39
+ : DEFAULT_CONCURRENCY_CEILING
40
+
41
+ // The decision-level ceiling: only a positive finite number binds. A missing,
42
+ // zero or invalid ceiling means the pool is not capped (never skip headroom).
43
+ const bindingCeiling = (value) =>
44
+ typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.floor(value) : null
45
+
46
+ const activeSessionsOf = (value) =>
47
+ typeof value === "number" && Number.isFinite(value) && value >= 0 ? Math.floor(value) : 0
48
+
49
+ const poolTpsOf = (value) =>
50
+ typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : null
51
+
52
+ /**
53
+ * R-36-10: the decision context's load facts. The host supplies
54
+ * { activeLocalSessions, concurrencyCeiling, poolTps } as context.load; callers
55
+ * may also pass the three fields directly on the context. Absent load facts mean
56
+ * no ceiling and no contention evidence, so the decision behaves as before.
57
+ */
58
+ const loadFactsOf = (context) => {
59
+ if (context === null || typeof context !== "object") {
60
+ return { supplied: false, activeLocalSessions: 0, concurrencyCeiling: null, poolTps: null }
61
+ }
62
+ const direct =
63
+ context.concurrencyCeiling !== undefined ||
64
+ context.activeLocalSessions !== undefined ||
65
+ context.poolTps !== undefined
66
+ const source =
67
+ context.load !== null && typeof context.load === "object" && !Array.isArray(context.load)
68
+ ? context.load
69
+ : direct
70
+ ? context
71
+ : null
72
+ if (source === null) {
73
+ return { supplied: false, activeLocalSessions: 0, concurrencyCeiling: null, poolTps: null }
74
+ }
75
+ return {
76
+ supplied: true,
77
+ activeLocalSessions: activeSessionsOf(source.activeLocalSessions),
78
+ concurrencyCeiling: bindingCeiling(source.concurrencyCeiling),
79
+ poolTps: poolTpsOf(source.poolTps)
80
+ }
81
+ }
82
+
83
+ export const ROUTER_ROUTE_LIMITATION =
84
+ "router_route reports the decision; DSH fixes the step's provider/model before pre-step, so the tool cannot change the current step's model"
85
+
86
+ export const ROLE_IDS = ["l1", "l2", "l3"]
87
+ const CHAIN_ROLES = ["l1", "l2", "l3", "advisor"]
88
+ // The only tpsSource values a decision or a ledger row may carry (F-36-V4).
89
+ export const TPS_SOURCES = ["measured", "probe", "unknown"]
90
+
91
+ const round1 = (value) => Math.round(value * 10) / 10
92
+ const formatTps = (value) => `${round1(value).toFixed(1)} tps`
93
+ // R-36-10: pool-contended reasons name the number without a forced decimal
94
+ // ("8 tps effective (40 tps pool, 5 sessions)").
95
+ const formatTpsValue = (value) => `${round1(value)} tps`
96
+ const formatPercent = (ratio) => `${round1(ratio * 100).toFixed(1)}%`
97
+
98
+ const normalizeResidentModels = (models) =>
99
+ Array.isArray(models)
100
+ ? [...new Set(models.filter((id) => typeof id === "string" && id.length > 0))].sort()
101
+ : []
102
+
103
+ const finiteOrNull = (value) => (typeof value === "number" && Number.isFinite(value) ? value : null)
104
+
105
+ const nonEmptyString = (value) => typeof value === "string" && value.length > 0
106
+
107
+ const roleEntry = (chain, role) =>
108
+ chain !== null && typeof chain === "object" && !Array.isArray(chain) ? chain[role] : undefined
109
+
110
+ const validFloor = (value) =>
111
+ typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= 100
112
+
113
+ const isRoleOn = (role, entry) => {
114
+ if (entry === null || typeof entry !== "object") return true
115
+ if (role === "l3") return entry.enabled === true
116
+ return entry.enabled !== false
117
+ }
118
+
119
+ /**
120
+ * The floor gate for a role. L1 keeps the policy floor as its only writer
121
+ * (DEC-25-11); L2/L3/Advisor use their configured floor when the role is on.
122
+ */
123
+ export const floorForRole = (policy, chain, role) => {
124
+ if (role !== "l2" && role !== "l3" && role !== "advisor") return policy.floorTps
125
+ const entry = roleEntry(chain, role)
126
+ if (entry === null || typeof entry !== "object" || !isRoleOn(role, entry)) return policy.floorTps
127
+ return validFloor(entry.floorTps) ? entry.floorTps : policy.floorTps
128
+ }
129
+
130
+ // DEC-36-24: roles.l1.model is the router DEFAULT. The stored policy.mainModel
131
+ // is a legacy field: the L1 default is read live from the Roles document, so a
132
+ // native-picker session override never mutates it.
133
+ const l1DefaultId = (chain) => {
134
+ const entry = roleEntry(chain, "l1")
135
+ return entry !== null && typeof entry === "object" && nonEmptyString(entry.model) ? entry.model : null
136
+ }
137
+
138
+ const defaultCandidates = (policy, chain) => {
139
+ const id = l1DefaultId(chain)
140
+ if (id !== null) return [id]
141
+ return policy.mainModel !== null && policy.mainModel !== undefined ? [policy.mainModel] : []
142
+ }
143
+
144
+ const defaultLabel = (policy, chain) => l1DefaultId(chain) ?? mainModelLabel(policy)
145
+
146
+ const defaultNote = (policy, chain, why) =>
147
+ `${why}; using the router default ${defaultLabel(policy, chain)}`
148
+
149
+ /**
150
+ * The ordered candidate chain for a role (DEC-36-14, DEC-36-24):
151
+ * l1 -> the session's native-picker override (when it differs), then
152
+ * roles.l1.model (the router default), then roles.l1.fallbacks
153
+ * l2/l3 -> roles.<role>.model, then roles.<role>.fallbacks (l3 only when on)
154
+ * advisor -> roles.advisor.model, then roles.advisor.fallbacks
155
+ * An empty or off role falls back to the router default ONLY because the role
156
+ * has no usable model of its own, and the decision says so. Subagent roles
157
+ * never use the session override.
158
+ */
159
+ export const chainForRole = (policy, chain, role, sessionMainModel) => {
160
+ if (role === "unknown") {
161
+ return {
162
+ candidates: defaultCandidates(policy, chain),
163
+ note: `role unknown: delegation depth unavailable; using the router default ${defaultLabel(policy, chain)}`
164
+ }
165
+ }
166
+ if (role === "l1") {
167
+ const entry = roleEntry(chain, "l1")
168
+ const fallbacks = entry !== null && typeof entry === "object" && Array.isArray(entry.fallbacks)
169
+ ? entry.fallbacks.filter(nonEmptyString)
170
+ : []
171
+ const defaultId = l1DefaultId(chain)
172
+ // DEC-36-24 (STEP 3): the DSH native picker is a session-local override for
173
+ // L1 only. A picked model that differs from the router default leads the
174
+ // chain; it never mutates roles.l1.model.
175
+ const override = nonEmptyString(sessionMainModel) && sessionMainModel !== defaultId ? [sessionMainModel] : []
176
+ const base = defaultCandidates(policy, chain)
177
+ const candidates = [...override, ...base, ...fallbacks]
178
+ if (candidates.length === 0) {
179
+ return { candidates: defaultCandidates(policy, chain), note: defaultNote(policy, chain, "roles.l1 has no model") }
180
+ }
181
+ return { candidates, note: null }
182
+ }
183
+ if (!CHAIN_ROLES.includes(role)) {
184
+ return { candidates: defaultCandidates(policy, chain), note: null }
185
+ }
186
+ const entry = roleEntry(chain, role)
187
+ if (entry === null || typeof entry !== "object") {
188
+ return { candidates: defaultCandidates(policy, chain), note: defaultNote(policy, chain, `roles.${role} is not configured`) }
189
+ }
190
+ if (!isRoleOn(role, entry)) {
191
+ return { candidates: defaultCandidates(policy, chain), note: defaultNote(policy, chain, `roles.${role} is off`) }
192
+ }
193
+ const candidates = [entry.model, ...(Array.isArray(entry.fallbacks) ? entry.fallbacks : [])].filter(nonEmptyString)
194
+ if (candidates.length === 0) {
195
+ return { candidates: defaultCandidates(policy, chain), note: defaultNote(policy, chain, `roles.${role} has no model`) }
196
+ }
197
+ return { candidates, note: null }
198
+ }
199
+
200
+ /**
201
+ * Run 25 T1 (DEC-25-10) + Run 36 DEC-36-12: a role is a delegation depth, not a
202
+ * profile concept. depth 0 is L1 (the controller), 1 is L2, 2 is L3. When the
203
+ * depth cannot be read the role is `unknown`, never a silent L1: the caller
204
+ * records that fact and routes by the policy default. The Advisor is a spawn
205
+ * role, not a depth, so it never appears here.
206
+ */
207
+ export const roleOf = (agent) => {
208
+ const depth = agent?.session?.header?.delegationDepth
209
+ if (depth === 0) return "l1"
210
+ if (depth === 1) return "l2"
211
+ if (depth === 2) return "l3"
212
+ return "unknown"
213
+ }
214
+
215
+ const safeResolve = (resolve, model) => {
216
+ if (typeof resolve !== "function") return null
217
+ try {
218
+ const resolved = resolve(model)
219
+ return resolved !== null && typeof resolved === "object" && !Array.isArray(resolved) ? resolved : null
220
+ } catch {
221
+ return null
222
+ }
223
+ }
224
+
225
+ const normalizeCandidate = (policy, telemetry, raw, resolve) => {
226
+ let ref
227
+ if (nonEmptyString(raw)) ref = { model: raw }
228
+ else if (raw !== null && typeof raw === "object" && !Array.isArray(raw) && nonEmptyString(raw.model)) ref = raw
229
+ else return null
230
+
231
+ const model = ref.model
232
+ const resolved = safeResolve(resolve, model)
233
+ const residents = normalizeResidentModels(telemetry?.residentModels)
234
+ const target =
235
+ resolved !== null && (resolved.target === "local" || resolved.target === "remote")
236
+ ? resolved.target
237
+ : ref.target === "local" || ref.target === "remote"
238
+ ? ref.target
239
+ : residents.includes(model)
240
+ ? "local"
241
+ : "remote"
242
+
243
+ let provider = null
244
+ if (target === "remote") {
245
+ if (resolved !== null && nonEmptyString(resolved.provider)) provider = resolved.provider
246
+ else if (nonEmptyString(ref.provider)) provider = ref.provider
247
+ }
248
+ const label =
249
+ resolved !== null && nonEmptyString(resolved.label)
250
+ ? resolved.label
251
+ : nonEmptyString(ref.label)
252
+ ? ref.label
253
+ : model
254
+ return { model, target, provider, label }
255
+ }
256
+
257
+ const tpsSourceOf = (telemetry, observedTps) => {
258
+ if (telemetry === null || telemetry === undefined) return "unknown"
259
+ const declared = telemetry.observedTpsSource
260
+ if (nonEmptyString(declared) && TPS_SOURCES.includes(declared)) return declared
261
+ return observedTps !== null ? "measured" : "unknown"
262
+ }
263
+
264
+ const FRESH_TPS_SOURCES = ["measured", "probe"]
265
+
266
+ // R-36-07 (DEC-36-06/07): a fresh per-model probe sample is the floor gate's
267
+ // preferred evidence. An expired or unknown sample reads as unknown, so it can
268
+ // never skip a model on its own.
269
+ const freshSpeedSample = (speedFor, model) => {
270
+ if (typeof speedFor !== "function") return null
271
+ let sample
272
+ try {
273
+ sample = speedFor(model)
274
+ } catch {
275
+ return null
276
+ }
277
+ if (sample === null || typeof sample !== "object" || Array.isArray(sample)) return null
278
+ if (sample.expired === true) return null
279
+ if (typeof sample.tps !== "number" || !Number.isFinite(sample.tps)) return null
280
+ if (!FRESH_TPS_SOURCES.includes(sample.source)) return null
281
+ return { tps: sample.tps, source: sample.source }
282
+ }
283
+
284
+ const telemetrySpeed = (telemetry) => {
285
+ const tps = finiteOrNull(telemetry?.observedTps)
286
+ if (tps === null) return null
287
+ return { tps, source: tpsSourceOf(telemetry, tps) }
288
+ }
289
+
290
+ // A fresh probe/measured sample first; telemetry.observedTps only when none exists.
291
+ // `fresh` marks the store source, because a fresh per-request observation already
292
+ // reflects contention and must not be divided again by the session count.
293
+ const resolveFloorSpeed = (model, telemetry, speedFor) => {
294
+ const fresh = freshSpeedSample(speedFor, model)
295
+ if (fresh !== null) return { ...fresh, fresh: true }
296
+ const fallback = telemetrySpeed(telemetry)
297
+ return fallback === null ? null : { ...fallback, fresh: false }
298
+ }
299
+
300
+ /**
301
+ * The four gates, applied to one local candidate. Null means it can serve.
302
+ * Residency is pool-level (is ANY local model resident), matching the canonical
303
+ * engine: the role chain, not the telemetry snapshot, names which local model
304
+ * serves. The floor gate writes the speed evidence it used into `evidence`.
305
+ */
306
+ const localGateFailure = (candidate, telemetry, floorTps, speedFor, evidence, loadFacts) => {
307
+ if (telemetry === null || telemetry === undefined) {
308
+ return { gate: "fallback", reason: `telemetry unavailable; local ${candidate.model} cannot be verified` }
309
+ }
310
+ const residents = normalizeResidentModels(telemetry.residentModels)
311
+ if (residents.length === 0) {
312
+ return { gate: "residency", reason: "no local model is resident" }
313
+ }
314
+ // R-36-10 (DEC-36-19): the concurrency ceiling is a headroom fact and runs
315
+ // before the floor. A full pool is skipped to the next model in the chain; it
316
+ // never queues and never pre-empts a running session.
317
+ if (
318
+ loadFacts.concurrencyCeiling !== null &&
319
+ loadFacts.activeLocalSessions >= loadFacts.concurrencyCeiling
320
+ ) {
321
+ return {
322
+ gate: "headroom",
323
+ reason: `local pool at ceiling (${loadFacts.activeLocalSessions} of ${loadFacts.concurrencyCeiling} sessions)`,
324
+ ceilingBlocked: true
325
+ }
326
+ }
327
+ if (typeof telemetry.headroomRatio !== "number" || !Number.isFinite(telemetry.headroomRatio)) {
328
+ return { gate: "headroom", reason: "local memory headroom is unknown" }
329
+ }
330
+ if (telemetry.headroomRatio < MIN_HEADROOM_RATIO) {
331
+ return {
332
+ gate: "headroom",
333
+ reason: `local memory headroom ${formatPercent(telemetry.headroomRatio)} is below ${formatPercent(MIN_HEADROOM_RATIO)}`
334
+ }
335
+ }
336
+ if (telemetry.pressureLevel !== "ok") {
337
+ return { gate: "headroom", reason: `local memory pressure is ${telemetry.pressureLevel}` }
338
+ }
339
+ const speed = resolveFloorSpeed(candidate.model, telemetry, speedFor)
340
+ if (speed === null) {
341
+ return { gate: "floor", reason: `no local speed sample yet for ${candidate.model}` }
342
+ }
343
+ // R-36-10: the floor compares the throughput this session would actually get.
344
+ // When several sessions share one engine, the pool's rate is divided by them;
345
+ // a lone session keeps the measurement unchanged. The floor gate's evidence
346
+ // is whichever sample it used: probe or telemetry.
347
+ const active = loadFacts.activeLocalSessions
348
+ // DEC-37-14 (Owner): dividing the engine's pool figure is only honest when the
349
+ // only evidence is that aggregate. A fresh per-request observation was measured
350
+ // under the current load, so it IS the per-session speed (live: four concurrent
351
+ // requests each decoded at 46.5 tok/s while the engine lifetime average read
352
+ // 20.3 tps).
353
+ const contended = speed.fresh !== true && loadFacts.poolTps !== null && active > 1
354
+ const effectiveTps = contended ? round1(loadFacts.poolTps / active) : speed.tps
355
+ evidence.observedTps = effectiveTps
356
+ evidence.tpsSource = speed.source
357
+ evidence.poolTps = loadFacts.poolTps
358
+ evidence.activeLocalSessions = loadFacts.activeLocalSessions
359
+ evidence.contended = contended
360
+ if (effectiveTps < floorTps) {
361
+ return {
362
+ gate: "floor",
363
+ reason: contended
364
+ ? `local ${candidate.model} below floor: ${formatTpsValue(effectiveTps)} effective (${formatTpsValue(loadFacts.poolTps)} pool, ${active} sessions)`
365
+ : `local ${candidate.model} ${formatTps(speed.tps)} is below floor ${formatTps(floorTps)}`
366
+ }
367
+ }
368
+ return null
369
+ }
370
+
371
+ const withNote = (note, reason) => (note === null ? reason : `${note}; ${reason}`)
372
+
373
+ const decisionOf = (fields) => ({
374
+ target: fields.target,
375
+ provider: fields.target === "remote" ? fields.provider : null,
376
+ model: fields.model,
377
+ gate: fields.gate,
378
+ reason: fields.reason,
379
+ skips: fields.skips,
380
+ floorTps: fields.floorTps,
381
+ observedTps: fields.observedTps,
382
+ tpsSource: fields.tpsSource,
383
+ poolTps: fields.poolTps ?? null,
384
+ activeLocalSessions: fields.activeLocalSessions ?? null,
385
+ // F-36-V2: the binding ceiling the headroom/floor gates judged against; null
386
+ // means the pool is uncapped (never the host's default substituted here).
387
+ concurrencyCeiling: fields.concurrencyCeiling === undefined ? null : fields.concurrencyCeiling,
388
+ policyRev: fields.policyRev,
389
+ role: fields.role
390
+ })
391
+
392
+ /**
393
+ * Evaluate one routing decision by walking a role's configured chain in order.
394
+ * The first candidate the gates can serve wins; a local candidate that cannot
395
+ * serve is pushed onto skips with its gate and reason and the walk continues.
396
+ * A remote candidate needs no local evidence, so it always serves. When the
397
+ * chain is exhausted the decision is one explicit "no usable model".
398
+ */
399
+ export const decide = (policy, telemetry, context = {}) => {
400
+ const requestedRole = context.role
401
+ const role =
402
+ requestedRole === "unknown"
403
+ ? "unknown"
404
+ : CHAIN_ROLES.includes(requestedRole)
405
+ ? requestedRole
406
+ : CHAIN_ROLES.includes(policy?.role)
407
+ ? policy.role
408
+ : "l1"
409
+ const chain = context.chain
410
+ const resolve = context.resolve
411
+ const snapshot = telemetry !== null && typeof telemetry === "object" ? telemetry : null
412
+ const floorTps = floorForRole(policy, chain, role)
413
+ const speedFor = context.speedFor
414
+ const loadFacts = loadFactsOf(context)
415
+ const telemetryEvidence = telemetrySpeed(snapshot)
416
+ // The speed evidence the decision reports: the fresh probe/telemetry sample
417
+ // the floor gate actually used, or the telemetry default before the floor.
418
+ // R-36-10 load facts ride along so every decision (and row) preserves them.
419
+ const evidence = {
420
+ observedTps: telemetryEvidence?.tps ?? null,
421
+ tpsSource: telemetryEvidence?.source ?? "unknown",
422
+ poolTps: loadFacts.supplied ? loadFacts.poolTps : null,
423
+ activeLocalSessions: loadFacts.supplied ? loadFacts.activeLocalSessions : null,
424
+ concurrencyCeiling: loadFacts.supplied ? loadFacts.concurrencyCeiling : null,
425
+ contended: false
426
+ }
427
+ const { candidates, note } = chainForRole(policy, chain, role, context.sessionMainModel)
428
+ // A skip carries only the model and its reason (domain LedgerSkipSchema); the
429
+ // decision's gate is the gate that triggered the last skip.
430
+ const skips = []
431
+ let lastGate = null
432
+ // R-36-10: when the whole chain is skipped at the ceiling the exhaustion is
433
+ // still one explicit no-usable-model decision that names the ceiling.
434
+ let lastCeiling = null
435
+
436
+ for (const raw of candidates) {
437
+ const candidate = normalizeCandidate(policy, snapshot, raw, resolve)
438
+ if (candidate === null) continue
439
+
440
+ if (candidate.target === "local") {
441
+ const failure = localGateFailure(candidate, snapshot, floorTps, speedFor, evidence, loadFacts)
442
+ if (failure !== null) {
443
+ skips.push({ model: candidate.model, reason: failure.reason })
444
+ lastGate = failure.gate
445
+ if (failure.ceilingBlocked === true) {
446
+ lastCeiling = {
447
+ active: loadFacts.activeLocalSessions,
448
+ ceiling: loadFacts.concurrencyCeiling
449
+ }
450
+ }
451
+ continue
452
+ }
453
+ const trigger = skips.length === 0 ? null : skips[skips.length - 1]
454
+ const met = evidence.contended
455
+ ? `local ${candidate.model} ${formatTpsValue(evidence.observedTps)} effective (${formatTpsValue(evidence.poolTps)} pool, ${evidence.activeLocalSessions} sessions) meets floor ${formatTps(floorTps)}`
456
+ : `local ${candidate.model} ${formatTps(evidence.observedTps)} meets floor ${formatTps(floorTps)}`
457
+ return decisionOf({
458
+ target: "local",
459
+ provider: null,
460
+ model: candidate.model,
461
+ gate: lastGate ?? "floor",
462
+ reason: withNote(note, trigger === null ? met : `${trigger.reason}; ${met}`),
463
+ skips: [...skips],
464
+ floorTps,
465
+ observedTps: evidence.observedTps,
466
+ tpsSource: evidence.tpsSource,
467
+ poolTps: evidence.poolTps,
468
+ activeLocalSessions: evidence.activeLocalSessions,
469
+ concurrencyCeiling: evidence.concurrencyCeiling,
470
+ policyRev: policy.rev,
471
+ role
472
+ })
473
+ }
474
+
475
+ const trigger = skips.length === 0 ? null : skips[skips.length - 1]
476
+ const base =
477
+ trigger === null
478
+ ? snapshot === null
479
+ ? `telemetry unavailable; using remote ${candidate.model} (the ${role} primary)`
480
+ : `remote ${candidate.model} is the ${role} primary`
481
+ : `${trigger.reason}; using remote ${candidate.model} (next in the ${role} chain)`
482
+ return decisionOf({
483
+ target: "remote",
484
+ provider: candidate.provider,
485
+ model: candidate.model,
486
+ gate: lastGate ?? "fallback",
487
+ reason: withNote(note, base),
488
+ skips: [...skips],
489
+ floorTps,
490
+ observedTps: evidence.observedTps,
491
+ tpsSource: evidence.tpsSource,
492
+ poolTps: evidence.poolTps,
493
+ activeLocalSessions: evidence.activeLocalSessions,
494
+ concurrencyCeiling: evidence.concurrencyCeiling,
495
+ policyRev: policy.rev,
496
+ role
497
+ })
498
+ }
499
+
500
+ const detail =
501
+ skips.length === 0
502
+ ? `the ${role} chain is empty`
503
+ : skips.map((skip) => `${skip.model} (${skip.reason})`).join("; ")
504
+ // R-36-10: exhausting a chain that was only blocked by the ceiling says so in
505
+ // the decision itself, never via a silent local overload.
506
+ const ceilingDetail =
507
+ lastCeiling === null
508
+ ? ""
509
+ : `; every local candidate is at the concurrency ceiling (${lastCeiling.active} of ${lastCeiling.ceiling} sessions)`
510
+ return decisionOf({
511
+ target: "remote",
512
+ provider: null,
513
+ model: null,
514
+ gate: "fallback",
515
+ reason: withNote(note, `no usable model for ${role}: ${detail}${ceilingDetail}`),
516
+ skips,
517
+ floorTps,
518
+ observedTps: evidence.observedTps,
519
+ tpsSource: evidence.tpsSource,
520
+ poolTps: evidence.poolTps,
521
+ activeLocalSessions: evidence.activeLocalSessions,
522
+ concurrencyCeiling: evidence.concurrencyCeiling,
523
+ policyRev: policy.rev,
524
+ role
525
+ })
526
+ }
527
+
528
+ /**
529
+ * Run 25 T1/T2: a per-role floor as a derived policy view. The policy object is
530
+ * never mutated; a missing or disabled role keeps the global floor verbatim.
531
+ */
532
+ export const policyForRole = (policy, chain, role) => {
533
+ if (role !== "l2" && role !== "l3" && role !== "advisor") return policy
534
+ const floor = floorForRole(policy, chain, role)
535
+ if (floor === policy.floorTps) return policy
536
+ return { ...policy, floorTps: floor, role }
537
+ }
538
+
539
+ const DEFAULT_FALLBACK_POLICY = {
540
+ floorTps: 50,
541
+ mainModel: null,
542
+ advisoryModel: "GPT 6.1 Sol",
543
+ rev: 1
544
+ }
545
+
546
+ export const isMainModelRef = (value) =>
547
+ value !== null &&
548
+ typeof value === "object" &&
549
+ !Array.isArray(value) &&
550
+ typeof value.provider === "string" &&
551
+ value.provider.length > 0 &&
552
+ typeof value.model === "string" &&
553
+ value.model.length > 0 &&
554
+ typeof value.label === "string" &&
555
+ value.label.length > 0
556
+
557
+ export const mainModelLabel = (policy) =>
558
+ typeof policy?.mainModel?.label === "string" && policy.mainModel.label.length > 0
559
+ ? policy.mainModel.label
560
+ : typeof policy?.mainModel?.model === "string" && policy.mainModel.model.length > 0
561
+ ? policy.mainModel.model
562
+ : "no model selected"
563
+
564
+ // A policy is scopeless: the old local/remote scope fields are ignored if an
565
+ // old document still carries them. Requiring one here was the
566
+ // fall-back-everything trap (A-36-01).
567
+ export const isPolicy = (policy) =>
568
+ policy !== null &&
569
+ typeof policy === "object" &&
570
+ !Array.isArray(policy) &&
571
+ (policy.mainModel === null || policy.mainModel === undefined || isMainModelRef(policy.mainModel)) &&
572
+ typeof policy.floorTps === "number" &&
573
+ Number.isFinite(policy.floorTps) &&
574
+ typeof policy.rev === "number" &&
575
+ Number.isFinite(policy.rev)
576
+
577
+ export const isTelemetry = (telemetry) =>
578
+ telemetry !== null &&
579
+ typeof telemetry === "object" &&
580
+ (telemetry.observedTps === null ||
581
+ (typeof telemetry.observedTps === "number" && Number.isFinite(telemetry.observedTps))) &&
582
+ typeof telemetry.headroomRatio === "number" &&
583
+ Number.isFinite(telemetry.headroomRatio) &&
584
+ PRESSURE_LEVELS.includes(telemetry.pressureLevel) &&
585
+ Array.isArray(telemetry.residentModels) &&
586
+ telemetry.residentModels.every((id) => typeof id === "string") &&
587
+ (telemetry.preferredModel === null || typeof telemetry.preferredModel === "string")
588
+
589
+ const errorInfo = (error) => {
590
+ if (error === null || error === undefined) return null
591
+ if (typeof error !== "object") return { name: "Error", message: String(error) }
592
+ const info = { name: error.name ?? "Error", message: error.message ?? String(error) }
593
+ if (error.kind !== undefined) info.kind = error.kind
594
+ if (error.status !== undefined) info.status = error.status
595
+ if (error.attempts !== undefined) info.attempts = error.attempts
596
+ return info
597
+ }
598
+
599
+ const defaultNow = () => new Date()
600
+ let defaultSequence = 0
601
+ const defaultNewId = () => `route-${Date.now().toString(36)}-${(++defaultSequence).toString(36)}`
602
+
603
+ const telemetrySummary = (telemetry) =>
604
+ telemetry === null || telemetry === undefined
605
+ ? null
606
+ : {
607
+ observedTps: telemetry.observedTps,
608
+ observedTpsSource: telemetry.observedTpsSource ?? null,
609
+ headroomRatio: telemetry.headroomRatio,
610
+ pressureLevel: telemetry.pressureLevel,
611
+ residentModels: [...telemetry.residentModels],
612
+ preferredModel: telemetry.preferredModel
613
+ }
614
+
615
+ /**
616
+ * Build one ledger row for a decision. Optional fields are omitted when absent
617
+ * so an older row shape stays valid. The row carries the whole decision
618
+ * (role, gate, skips, tps and source); host application facts live in
619
+ * notAppliedReason/limitation, never as a routing outcome.
620
+ */
621
+ export const buildDecisionRow = (fields) => {
622
+ const decision = fields.decision ?? {}
623
+ const row = {
624
+ id: fields.id,
625
+ requestId: fields.requestId,
626
+ // F-37-49: the deciding session, so a ledger row can be attributed without
627
+ // parsing the requestId prefix.
628
+ sessionId: typeof fields.sessionId === "string" && fields.sessionId.length > 0 ? fields.sessionId : null,
629
+ omlxRequestId: fields.omlxRequestId ?? null,
630
+ agentId: fields.agentId ?? null,
631
+ decision: decision.target,
632
+ model: typeof decision.model === "string" ? decision.model : "",
633
+ reason: decision.reason,
634
+ contextTokens:
635
+ typeof fields.contextTokens === "number" && Number.isFinite(fields.contextTokens)
636
+ ? fields.contextTokens
637
+ : 0,
638
+ floorTps: decision.floorTps,
639
+ latencyMs:
640
+ typeof fields.latencyMs === "number" && Number.isFinite(fields.latencyMs)
641
+ ? Math.max(0, fields.latencyMs)
642
+ : 0,
643
+ at: fields.at,
644
+ gate: decision.gate,
645
+ policyRev: decision.policyRev,
646
+ applied: fields.applied === true,
647
+ surface: fields.surface
648
+ }
649
+ if (typeof decision.role === "string") row.role = decision.role
650
+ if (typeof decision.roleReason === "string") row.roleReason = decision.roleReason
651
+ row.skips = Array.isArray(decision.skips) ? decision.skips : []
652
+ if (typeof decision.tpsSource === "string") row.tpsSource = decision.tpsSource
653
+ if (typeof decision.observedTps === "number" && Number.isFinite(decision.observedTps)) {
654
+ row.observedTps = decision.observedTps
655
+ }
656
+ // R-36-10: the row keeps the pool facts behind a contended floor decision.
657
+ if (typeof decision.poolTps === "number" && Number.isFinite(decision.poolTps)) {
658
+ row.poolTps = decision.poolTps
659
+ }
660
+ if (typeof decision.activeLocalSessions === "number" && Number.isFinite(decision.activeLocalSessions)) {
661
+ row.activeLocalSessions = decision.activeLocalSessions
662
+ }
663
+ // F-36-V2: the binding ceiling behind a headroom decision; null = no ceiling.
664
+ if (
665
+ decision.concurrencyCeiling === null ||
666
+ (typeof decision.concurrencyCeiling === "number" && Number.isFinite(decision.concurrencyCeiling))
667
+ ) {
668
+ row.concurrencyCeiling = decision.concurrencyCeiling
669
+ }
670
+ if (fields.limitation !== undefined && fields.limitation !== null) row.limitation = fields.limitation
671
+ if (fields.notAppliedReason !== undefined && fields.notAppliedReason !== null) {
672
+ row.notAppliedReason = fields.notAppliedReason
673
+ }
674
+ if (fields.appliedBy !== undefined && fields.appliedBy !== null) row.appliedBy = fields.appliedBy
675
+ if (fields.provider !== undefined && fields.provider !== null) row.provider = fields.provider
676
+ if (fields.selectedModel !== undefined && fields.selectedModel !== null) {
677
+ row.selectedModel = fields.selectedModel
678
+ }
679
+ if (typeof fields.turn === "number") row.turn = fields.turn
680
+ if (typeof fields.step === "number") row.step = fields.step
681
+ return row
682
+ }
683
+
684
+ /** Record a row through the host ledger runtime without throwing. */
685
+ export const recordDecision = (runtime, row) => {
686
+ try {
687
+ const result = runtime.record(row)
688
+ if (result !== null && typeof result === "object" && result.invalid === true) {
689
+ return {
690
+ ok: false,
691
+ error: {
692
+ code: "LEDGER_WRITE_FAILED",
693
+ field: result.field,
694
+ value: result.value,
695
+ message: `ledger rejected decision row field "${result.field}"`
696
+ }
697
+ }
698
+ }
699
+ return { ok: true, error: null }
700
+ } catch (error) {
701
+ return {
702
+ ok: false,
703
+ error: {
704
+ code: "LEDGER_WRITE_FAILED",
705
+ message: error instanceof Error ? error.message : String(error)
706
+ }
707
+ }
708
+ }
709
+ }
710
+
711
+ /**
712
+ * Route one step and write exactly one ledger row. Telemetry and policy
713
+ * failures still walk the role chain and produce an explicit decision plus a
714
+ * row. A ledger failure returns the decision and a typed ledgerError instead
715
+ * of dropping the decision.
716
+ */
717
+ export const createRoutingController = (options = {}) => {
718
+ const runtime = options.runtime
719
+ if (runtime === undefined || typeof runtime.record !== "function") {
720
+ throw new TypeError("createRoutingController needs a ledger runtime")
721
+ }
722
+ const readPolicy = options.readPolicy ?? (() => runtime.get())
723
+ const readTelemetry = options.readTelemetry
724
+ const readChain = typeof options.readChain === "function" ? options.readChain : undefined
725
+ const resolveModel = typeof options.resolveModel === "function" ? options.resolveModel : undefined
726
+ const speedFor = typeof options.speedFor === "function" ? options.speedFor : undefined
727
+ // R-36-10: the host's load facts (active local sessions, ceiling, pool tps).
728
+ const readLoad = typeof options.readLoad === "function" ? options.readLoad : undefined
729
+ const fallbackPolicy = options.fallbackPolicy ?? DEFAULT_FALLBACK_POLICY
730
+ const now = options.now ?? defaultNow
731
+ const newId = options.newId ?? defaultNewId
732
+ const logger = options.logger
733
+
734
+ const contextFor = (input) => {
735
+ let chain = input.chain
736
+ if (chain === undefined && readChain !== undefined) {
737
+ try {
738
+ chain = readChain()
739
+ } catch {
740
+ chain = undefined
741
+ }
742
+ }
743
+ // F-36-V1: an absent role is "unknown", never a silent l1 (DEC-36-12).
744
+ const role = nonEmptyString(input.role) ? input.role : "unknown"
745
+ let load
746
+ if (readLoad !== undefined) {
747
+ try {
748
+ load = readLoad()
749
+ } catch {
750
+ load = undefined
751
+ }
752
+ }
753
+ return { role, chain, resolve: resolveModel, speedFor, load, sessionMainModel: input.sessionMainModel }
754
+ }
755
+
756
+ const policyFailureDecision = (policy, error, context) => {
757
+ const base = decide(policy, null, context)
758
+ return {
759
+ ...base,
760
+ reason: `policy read failed (${errorInfo(error).message}); ${base.reason}`
761
+ }
762
+ }
763
+
764
+ const telemetryFailureDecision = (policy, telemetryError, context) => {
765
+ const info = errorInfo(telemetryError)
766
+ const base = decide(policy, null, context)
767
+ return {
768
+ ...base,
769
+ reason: `telemetry unavailable (${info.kind ?? info.name}: ${info.message}); ${base.reason}`
770
+ }
771
+ }
772
+
773
+ const route = async (input = {}) => {
774
+ const startedAt = now().getTime()
775
+ const context = contextFor(input)
776
+ let policy = null
777
+ let policyError = null
778
+ try {
779
+ const candidate = readPolicy()
780
+ if (isPolicy(candidate)) policy = candidate
781
+ else policyError = new Error("invalid policy state")
782
+ } catch (error) {
783
+ policyError = error
784
+ }
785
+
786
+ let telemetry = null
787
+ let telemetryError = null
788
+ let decision
789
+
790
+ if (policyError !== null) {
791
+ const base = isPolicy(fallbackPolicy) ? fallbackPolicy : DEFAULT_FALLBACK_POLICY
792
+ decision = policyFailureDecision(base, policyError, context)
793
+ } else {
794
+ if (readTelemetry !== undefined) {
795
+ try {
796
+ const candidate = await readTelemetry({ signal: input.signal })
797
+ if (candidate === null || candidate === undefined) {
798
+ telemetry = null
799
+ } else if (isTelemetry(candidate)) {
800
+ telemetry = candidate
801
+ } else {
802
+ telemetryError = new Error("invalid telemetry snapshot")
803
+ }
804
+ } catch (error) {
805
+ telemetryError = error
806
+ }
807
+ }
808
+ decision =
809
+ telemetryError !== null
810
+ ? telemetryFailureDecision(policy, telemetryError, context)
811
+ : decide(policy, telemetry, context)
812
+ }
813
+
814
+ const latencyMs = Math.max(0, now().getTime() - startedAt)
815
+ const requestId =
816
+ input.requestId !== undefined && typeof input.requestId === "string" && input.requestId.length > 0
817
+ ? input.requestId
818
+ : `${input.agentId ?? "agent"}:${input.turn ?? "?"}:${input.step ?? "?"}:${decision.gate}`
819
+
820
+ const applied = input.applied === true
821
+ const row = buildDecisionRow({
822
+ id: newId(),
823
+ requestId,
824
+ omlxRequestId: input.omlxRequestId,
825
+ agentId: input.agentId,
826
+ decision,
827
+ contextTokens: input.contextTokens,
828
+ latencyMs,
829
+ at: now().toISOString(),
830
+ turn: input.turn,
831
+ step: input.step,
832
+ applied,
833
+ surface: input.surface ?? "router_route",
834
+ limitation: input.limitation ?? ROUTER_ROUTE_LIMITATION,
835
+ notAppliedReason: applied ? undefined : input.notAppliedReason ?? "step fixed",
836
+ appliedBy: input.appliedBy,
837
+ provider: input.provider
838
+ })
839
+
840
+ const ledger = recordDecision(runtime, row)
841
+ if (!ledger.ok && logger !== undefined && typeof logger.warn === "function") {
842
+ logger.warn(`router ledger write failed: ${ledger.error.message}`)
843
+ }
844
+
845
+ return {
846
+ ok: true,
847
+ decision,
848
+ row: ledger.ok ? row : null,
849
+ ledgerError: ledger.error,
850
+ policyError: errorInfo(policyError),
851
+ telemetryError: errorInfo(telemetryError),
852
+ telemetry: telemetrySummary(telemetry),
853
+ latencyMs
854
+ }
855
+ }
856
+
857
+ return { route }
858
+ }