@try-works/dsh-minimal-router 0.0.0-stage → 0.1.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,847 @@
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 sample first; telemetry.observedTps only when none exists.
291
+ const resolveFloorSpeed = (model, telemetry, speedFor) => {
292
+ const fresh = freshSpeedSample(speedFor, model)
293
+ if (fresh !== null) return fresh
294
+ return telemetrySpeed(telemetry)
295
+ }
296
+
297
+ /**
298
+ * The four gates, applied to one local candidate. Null means it can serve.
299
+ * Residency is pool-level (is ANY local model resident), matching the canonical
300
+ * engine: the role chain, not the telemetry snapshot, names which local model
301
+ * serves. The floor gate writes the speed evidence it used into `evidence`.
302
+ */
303
+ const localGateFailure = (candidate, telemetry, floorTps, speedFor, evidence, loadFacts) => {
304
+ if (telemetry === null || telemetry === undefined) {
305
+ return { gate: "fallback", reason: `telemetry unavailable; local ${candidate.model} cannot be verified` }
306
+ }
307
+ const residents = normalizeResidentModels(telemetry.residentModels)
308
+ if (residents.length === 0) {
309
+ return { gate: "residency", reason: "no local model is resident" }
310
+ }
311
+ // R-36-10 (DEC-36-19): the concurrency ceiling is a headroom fact and runs
312
+ // before the floor. A full pool is skipped to the next model in the chain; it
313
+ // never queues and never pre-empts a running session.
314
+ if (
315
+ loadFacts.concurrencyCeiling !== null &&
316
+ loadFacts.activeLocalSessions >= loadFacts.concurrencyCeiling
317
+ ) {
318
+ return {
319
+ gate: "headroom",
320
+ reason: `local pool at ceiling (${loadFacts.activeLocalSessions} of ${loadFacts.concurrencyCeiling} sessions)`,
321
+ ceilingBlocked: true
322
+ }
323
+ }
324
+ if (typeof telemetry.headroomRatio !== "number" || !Number.isFinite(telemetry.headroomRatio)) {
325
+ return { gate: "headroom", reason: "local memory headroom is unknown" }
326
+ }
327
+ if (telemetry.headroomRatio < MIN_HEADROOM_RATIO) {
328
+ return {
329
+ gate: "headroom",
330
+ reason: `local memory headroom ${formatPercent(telemetry.headroomRatio)} is below ${formatPercent(MIN_HEADROOM_RATIO)}`
331
+ }
332
+ }
333
+ if (telemetry.pressureLevel !== "ok") {
334
+ return { gate: "headroom", reason: `local memory pressure is ${telemetry.pressureLevel}` }
335
+ }
336
+ const speed = resolveFloorSpeed(candidate.model, telemetry, speedFor)
337
+ if (speed === null) {
338
+ return { gate: "floor", reason: `no local speed sample yet for ${candidate.model}` }
339
+ }
340
+ // R-36-10: the floor compares the throughput this session would actually get.
341
+ // When several sessions share one engine, the pool's rate is divided by them;
342
+ // a lone session keeps the measurement unchanged. The floor gate's evidence
343
+ // is whichever sample it used: probe or telemetry.
344
+ const active = loadFacts.activeLocalSessions
345
+ const contended = loadFacts.poolTps !== null && active > 1
346
+ const effectiveTps = contended ? round1(loadFacts.poolTps / active) : speed.tps
347
+ evidence.observedTps = effectiveTps
348
+ evidence.tpsSource = speed.source
349
+ evidence.poolTps = loadFacts.poolTps
350
+ evidence.activeLocalSessions = loadFacts.activeLocalSessions
351
+ evidence.contended = contended
352
+ if (effectiveTps < floorTps) {
353
+ return {
354
+ gate: "floor",
355
+ reason: contended
356
+ ? `local ${candidate.model} below floor: ${formatTpsValue(effectiveTps)} effective (${formatTpsValue(loadFacts.poolTps)} pool, ${active} sessions)`
357
+ : `local ${candidate.model} ${formatTps(speed.tps)} is below floor ${formatTps(floorTps)}`
358
+ }
359
+ }
360
+ return null
361
+ }
362
+
363
+ const withNote = (note, reason) => (note === null ? reason : `${note}; ${reason}`)
364
+
365
+ const decisionOf = (fields) => ({
366
+ target: fields.target,
367
+ provider: fields.target === "remote" ? fields.provider : null,
368
+ model: fields.model,
369
+ gate: fields.gate,
370
+ reason: fields.reason,
371
+ skips: fields.skips,
372
+ floorTps: fields.floorTps,
373
+ observedTps: fields.observedTps,
374
+ tpsSource: fields.tpsSource,
375
+ poolTps: fields.poolTps ?? null,
376
+ activeLocalSessions: fields.activeLocalSessions ?? null,
377
+ // F-36-V2: the binding ceiling the headroom/floor gates judged against; null
378
+ // means the pool is uncapped (never the host's default substituted here).
379
+ concurrencyCeiling: fields.concurrencyCeiling === undefined ? null : fields.concurrencyCeiling,
380
+ policyRev: fields.policyRev,
381
+ role: fields.role
382
+ })
383
+
384
+ /**
385
+ * Evaluate one routing decision by walking a role's configured chain in order.
386
+ * The first candidate the gates can serve wins; a local candidate that cannot
387
+ * serve is pushed onto skips with its gate and reason and the walk continues.
388
+ * A remote candidate needs no local evidence, so it always serves. When the
389
+ * chain is exhausted the decision is one explicit "no usable model".
390
+ */
391
+ export const decide = (policy, telemetry, context = {}) => {
392
+ const requestedRole = context.role
393
+ const role =
394
+ requestedRole === "unknown"
395
+ ? "unknown"
396
+ : CHAIN_ROLES.includes(requestedRole)
397
+ ? requestedRole
398
+ : CHAIN_ROLES.includes(policy?.role)
399
+ ? policy.role
400
+ : "l1"
401
+ const chain = context.chain
402
+ const resolve = context.resolve
403
+ const snapshot = telemetry !== null && typeof telemetry === "object" ? telemetry : null
404
+ const floorTps = floorForRole(policy, chain, role)
405
+ const speedFor = context.speedFor
406
+ const loadFacts = loadFactsOf(context)
407
+ const telemetryEvidence = telemetrySpeed(snapshot)
408
+ // The speed evidence the decision reports: the fresh probe/telemetry sample
409
+ // the floor gate actually used, or the telemetry default before the floor.
410
+ // R-36-10 load facts ride along so every decision (and row) preserves them.
411
+ const evidence = {
412
+ observedTps: telemetryEvidence?.tps ?? null,
413
+ tpsSource: telemetryEvidence?.source ?? "unknown",
414
+ poolTps: loadFacts.supplied ? loadFacts.poolTps : null,
415
+ activeLocalSessions: loadFacts.supplied ? loadFacts.activeLocalSessions : null,
416
+ concurrencyCeiling: loadFacts.supplied ? loadFacts.concurrencyCeiling : null,
417
+ contended: false
418
+ }
419
+ const { candidates, note } = chainForRole(policy, chain, role, context.sessionMainModel)
420
+ // A skip carries only the model and its reason (domain LedgerSkipSchema); the
421
+ // decision's gate is the gate that triggered the last skip.
422
+ const skips = []
423
+ let lastGate = null
424
+ // R-36-10: when the whole chain is skipped at the ceiling the exhaustion is
425
+ // still one explicit no-usable-model decision that names the ceiling.
426
+ let lastCeiling = null
427
+
428
+ for (const raw of candidates) {
429
+ const candidate = normalizeCandidate(policy, snapshot, raw, resolve)
430
+ if (candidate === null) continue
431
+
432
+ if (candidate.target === "local") {
433
+ const failure = localGateFailure(candidate, snapshot, floorTps, speedFor, evidence, loadFacts)
434
+ if (failure !== null) {
435
+ skips.push({ model: candidate.model, reason: failure.reason })
436
+ lastGate = failure.gate
437
+ if (failure.ceilingBlocked === true) {
438
+ lastCeiling = {
439
+ active: loadFacts.activeLocalSessions,
440
+ ceiling: loadFacts.concurrencyCeiling
441
+ }
442
+ }
443
+ continue
444
+ }
445
+ const trigger = skips.length === 0 ? null : skips[skips.length - 1]
446
+ const met = evidence.contended
447
+ ? `local ${candidate.model} ${formatTpsValue(evidence.observedTps)} effective (${formatTpsValue(evidence.poolTps)} pool, ${evidence.activeLocalSessions} sessions) meets floor ${formatTps(floorTps)}`
448
+ : `local ${candidate.model} ${formatTps(evidence.observedTps)} meets floor ${formatTps(floorTps)}`
449
+ return decisionOf({
450
+ target: "local",
451
+ provider: null,
452
+ model: candidate.model,
453
+ gate: lastGate ?? "floor",
454
+ reason: withNote(note, trigger === null ? met : `${trigger.reason}; ${met}`),
455
+ skips: [...skips],
456
+ floorTps,
457
+ observedTps: evidence.observedTps,
458
+ tpsSource: evidence.tpsSource,
459
+ poolTps: evidence.poolTps,
460
+ activeLocalSessions: evidence.activeLocalSessions,
461
+ concurrencyCeiling: evidence.concurrencyCeiling,
462
+ policyRev: policy.rev,
463
+ role
464
+ })
465
+ }
466
+
467
+ const trigger = skips.length === 0 ? null : skips[skips.length - 1]
468
+ const base =
469
+ trigger === null
470
+ ? snapshot === null
471
+ ? `telemetry unavailable; using remote ${candidate.model} (the ${role} primary)`
472
+ : `remote ${candidate.model} is the ${role} primary`
473
+ : `${trigger.reason}; using remote ${candidate.model} (next in the ${role} chain)`
474
+ return decisionOf({
475
+ target: "remote",
476
+ provider: candidate.provider,
477
+ model: candidate.model,
478
+ gate: lastGate ?? "fallback",
479
+ reason: withNote(note, base),
480
+ skips: [...skips],
481
+ floorTps,
482
+ observedTps: evidence.observedTps,
483
+ tpsSource: evidence.tpsSource,
484
+ poolTps: evidence.poolTps,
485
+ activeLocalSessions: evidence.activeLocalSessions,
486
+ concurrencyCeiling: evidence.concurrencyCeiling,
487
+ policyRev: policy.rev,
488
+ role
489
+ })
490
+ }
491
+
492
+ const detail =
493
+ skips.length === 0
494
+ ? `the ${role} chain is empty`
495
+ : skips.map((skip) => `${skip.model} (${skip.reason})`).join("; ")
496
+ // R-36-10: exhausting a chain that was only blocked by the ceiling says so in
497
+ // the decision itself, never via a silent local overload.
498
+ const ceilingDetail =
499
+ lastCeiling === null
500
+ ? ""
501
+ : `; every local candidate is at the concurrency ceiling (${lastCeiling.active} of ${lastCeiling.ceiling} sessions)`
502
+ return decisionOf({
503
+ target: "remote",
504
+ provider: null,
505
+ model: null,
506
+ gate: "fallback",
507
+ reason: withNote(note, `no usable model for ${role}: ${detail}${ceilingDetail}`),
508
+ skips,
509
+ floorTps,
510
+ observedTps: evidence.observedTps,
511
+ tpsSource: evidence.tpsSource,
512
+ poolTps: evidence.poolTps,
513
+ activeLocalSessions: evidence.activeLocalSessions,
514
+ concurrencyCeiling: evidence.concurrencyCeiling,
515
+ policyRev: policy.rev,
516
+ role
517
+ })
518
+ }
519
+
520
+ /**
521
+ * Run 25 T1/T2: a per-role floor as a derived policy view. The policy object is
522
+ * never mutated; a missing or disabled role keeps the global floor verbatim.
523
+ */
524
+ export const policyForRole = (policy, chain, role) => {
525
+ if (role !== "l2" && role !== "l3" && role !== "advisor") return policy
526
+ const floor = floorForRole(policy, chain, role)
527
+ if (floor === policy.floorTps) return policy
528
+ return { ...policy, floorTps: floor, role }
529
+ }
530
+
531
+ const DEFAULT_FALLBACK_POLICY = {
532
+ floorTps: 50,
533
+ mainModel: null,
534
+ advisoryModel: "GPT 6.1 Sol",
535
+ rev: 1
536
+ }
537
+
538
+ export const isMainModelRef = (value) =>
539
+ value !== null &&
540
+ typeof value === "object" &&
541
+ !Array.isArray(value) &&
542
+ typeof value.provider === "string" &&
543
+ value.provider.length > 0 &&
544
+ typeof value.model === "string" &&
545
+ value.model.length > 0 &&
546
+ typeof value.label === "string" &&
547
+ value.label.length > 0
548
+
549
+ export const mainModelLabel = (policy) =>
550
+ typeof policy?.mainModel?.label === "string" && policy.mainModel.label.length > 0
551
+ ? policy.mainModel.label
552
+ : typeof policy?.mainModel?.model === "string" && policy.mainModel.model.length > 0
553
+ ? policy.mainModel.model
554
+ : "no model selected"
555
+
556
+ // A policy is scopeless: the old local/remote scope fields are ignored if an
557
+ // old document still carries them. Requiring one here was the
558
+ // fall-back-everything trap (A-36-01).
559
+ export const isPolicy = (policy) =>
560
+ policy !== null &&
561
+ typeof policy === "object" &&
562
+ !Array.isArray(policy) &&
563
+ (policy.mainModel === null || policy.mainModel === undefined || isMainModelRef(policy.mainModel)) &&
564
+ typeof policy.floorTps === "number" &&
565
+ Number.isFinite(policy.floorTps) &&
566
+ typeof policy.rev === "number" &&
567
+ Number.isFinite(policy.rev)
568
+
569
+ export const isTelemetry = (telemetry) =>
570
+ telemetry !== null &&
571
+ typeof telemetry === "object" &&
572
+ (telemetry.observedTps === null ||
573
+ (typeof telemetry.observedTps === "number" && Number.isFinite(telemetry.observedTps))) &&
574
+ typeof telemetry.headroomRatio === "number" &&
575
+ Number.isFinite(telemetry.headroomRatio) &&
576
+ PRESSURE_LEVELS.includes(telemetry.pressureLevel) &&
577
+ Array.isArray(telemetry.residentModels) &&
578
+ telemetry.residentModels.every((id) => typeof id === "string") &&
579
+ (telemetry.preferredModel === null || typeof telemetry.preferredModel === "string")
580
+
581
+ const errorInfo = (error) => {
582
+ if (error === null || error === undefined) return null
583
+ if (typeof error !== "object") return { name: "Error", message: String(error) }
584
+ const info = { name: error.name ?? "Error", message: error.message ?? String(error) }
585
+ if (error.kind !== undefined) info.kind = error.kind
586
+ if (error.status !== undefined) info.status = error.status
587
+ if (error.attempts !== undefined) info.attempts = error.attempts
588
+ return info
589
+ }
590
+
591
+ const defaultNow = () => new Date()
592
+ let defaultSequence = 0
593
+ const defaultNewId = () => `route-${Date.now().toString(36)}-${(++defaultSequence).toString(36)}`
594
+
595
+ const telemetrySummary = (telemetry) =>
596
+ telemetry === null || telemetry === undefined
597
+ ? null
598
+ : {
599
+ observedTps: telemetry.observedTps,
600
+ observedTpsSource: telemetry.observedTpsSource ?? null,
601
+ headroomRatio: telemetry.headroomRatio,
602
+ pressureLevel: telemetry.pressureLevel,
603
+ residentModels: [...telemetry.residentModels],
604
+ preferredModel: telemetry.preferredModel
605
+ }
606
+
607
+ /**
608
+ * Build one ledger row for a decision. Optional fields are omitted when absent
609
+ * so an older row shape stays valid. The row carries the whole decision
610
+ * (role, gate, skips, tps and source); host application facts live in
611
+ * notAppliedReason/limitation, never as a routing outcome.
612
+ */
613
+ export const buildDecisionRow = (fields) => {
614
+ const decision = fields.decision ?? {}
615
+ const row = {
616
+ id: fields.id,
617
+ requestId: fields.requestId,
618
+ omlxRequestId: fields.omlxRequestId ?? null,
619
+ agentId: fields.agentId ?? null,
620
+ decision: decision.target,
621
+ model: typeof decision.model === "string" ? decision.model : "",
622
+ reason: decision.reason,
623
+ contextTokens:
624
+ typeof fields.contextTokens === "number" && Number.isFinite(fields.contextTokens)
625
+ ? fields.contextTokens
626
+ : 0,
627
+ floorTps: decision.floorTps,
628
+ latencyMs:
629
+ typeof fields.latencyMs === "number" && Number.isFinite(fields.latencyMs)
630
+ ? Math.max(0, fields.latencyMs)
631
+ : 0,
632
+ at: fields.at,
633
+ gate: decision.gate,
634
+ policyRev: decision.policyRev,
635
+ applied: fields.applied === true,
636
+ surface: fields.surface
637
+ }
638
+ if (typeof decision.role === "string") row.role = decision.role
639
+ if (typeof decision.roleReason === "string") row.roleReason = decision.roleReason
640
+ row.skips = Array.isArray(decision.skips) ? decision.skips : []
641
+ if (typeof decision.tpsSource === "string") row.tpsSource = decision.tpsSource
642
+ if (typeof decision.observedTps === "number" && Number.isFinite(decision.observedTps)) {
643
+ row.observedTps = decision.observedTps
644
+ }
645
+ // R-36-10: the row keeps the pool facts behind a contended floor decision.
646
+ if (typeof decision.poolTps === "number" && Number.isFinite(decision.poolTps)) {
647
+ row.poolTps = decision.poolTps
648
+ }
649
+ if (typeof decision.activeLocalSessions === "number" && Number.isFinite(decision.activeLocalSessions)) {
650
+ row.activeLocalSessions = decision.activeLocalSessions
651
+ }
652
+ // F-36-V2: the binding ceiling behind a headroom decision; null = no ceiling.
653
+ if (
654
+ decision.concurrencyCeiling === null ||
655
+ (typeof decision.concurrencyCeiling === "number" && Number.isFinite(decision.concurrencyCeiling))
656
+ ) {
657
+ row.concurrencyCeiling = decision.concurrencyCeiling
658
+ }
659
+ if (fields.limitation !== undefined && fields.limitation !== null) row.limitation = fields.limitation
660
+ if (fields.notAppliedReason !== undefined && fields.notAppliedReason !== null) {
661
+ row.notAppliedReason = fields.notAppliedReason
662
+ }
663
+ if (fields.appliedBy !== undefined && fields.appliedBy !== null) row.appliedBy = fields.appliedBy
664
+ if (fields.provider !== undefined && fields.provider !== null) row.provider = fields.provider
665
+ if (fields.selectedModel !== undefined && fields.selectedModel !== null) {
666
+ row.selectedModel = fields.selectedModel
667
+ }
668
+ if (typeof fields.turn === "number") row.turn = fields.turn
669
+ if (typeof fields.step === "number") row.step = fields.step
670
+ return row
671
+ }
672
+
673
+ /** Record a row through the host ledger runtime without throwing. */
674
+ export const recordDecision = (runtime, row) => {
675
+ try {
676
+ const result = runtime.record(row)
677
+ if (result !== null && typeof result === "object" && result.invalid === true) {
678
+ return {
679
+ ok: false,
680
+ error: {
681
+ code: "LEDGER_WRITE_FAILED",
682
+ field: result.field,
683
+ value: result.value,
684
+ message: `ledger rejected decision row field "${result.field}"`
685
+ }
686
+ }
687
+ }
688
+ return { ok: true, error: null }
689
+ } catch (error) {
690
+ return {
691
+ ok: false,
692
+ error: {
693
+ code: "LEDGER_WRITE_FAILED",
694
+ message: error instanceof Error ? error.message : String(error)
695
+ }
696
+ }
697
+ }
698
+ }
699
+
700
+ /**
701
+ * Route one step and write exactly one ledger row. Telemetry and policy
702
+ * failures still walk the role chain and produce an explicit decision plus a
703
+ * row. A ledger failure returns the decision and a typed ledgerError instead
704
+ * of dropping the decision.
705
+ */
706
+ export const createRoutingController = (options = {}) => {
707
+ const runtime = options.runtime
708
+ if (runtime === undefined || typeof runtime.record !== "function") {
709
+ throw new TypeError("createRoutingController needs a ledger runtime")
710
+ }
711
+ const readPolicy = options.readPolicy ?? (() => runtime.get())
712
+ const readTelemetry = options.readTelemetry
713
+ const readChain = typeof options.readChain === "function" ? options.readChain : undefined
714
+ const resolveModel = typeof options.resolveModel === "function" ? options.resolveModel : undefined
715
+ const speedFor = typeof options.speedFor === "function" ? options.speedFor : undefined
716
+ // R-36-10: the host's load facts (active local sessions, ceiling, pool tps).
717
+ const readLoad = typeof options.readLoad === "function" ? options.readLoad : undefined
718
+ const fallbackPolicy = options.fallbackPolicy ?? DEFAULT_FALLBACK_POLICY
719
+ const now = options.now ?? defaultNow
720
+ const newId = options.newId ?? defaultNewId
721
+ const logger = options.logger
722
+
723
+ const contextFor = (input) => {
724
+ let chain = input.chain
725
+ if (chain === undefined && readChain !== undefined) {
726
+ try {
727
+ chain = readChain()
728
+ } catch {
729
+ chain = undefined
730
+ }
731
+ }
732
+ // F-36-V1: an absent role is "unknown", never a silent l1 (DEC-36-12).
733
+ const role = nonEmptyString(input.role) ? input.role : "unknown"
734
+ let load
735
+ if (readLoad !== undefined) {
736
+ try {
737
+ load = readLoad()
738
+ } catch {
739
+ load = undefined
740
+ }
741
+ }
742
+ return { role, chain, resolve: resolveModel, speedFor, load, sessionMainModel: input.sessionMainModel }
743
+ }
744
+
745
+ const policyFailureDecision = (policy, error, context) => {
746
+ const base = decide(policy, null, context)
747
+ return {
748
+ ...base,
749
+ reason: `policy read failed (${errorInfo(error).message}); ${base.reason}`
750
+ }
751
+ }
752
+
753
+ const telemetryFailureDecision = (policy, telemetryError, context) => {
754
+ const info = errorInfo(telemetryError)
755
+ const base = decide(policy, null, context)
756
+ return {
757
+ ...base,
758
+ reason: `telemetry unavailable (${info.kind ?? info.name}: ${info.message}); ${base.reason}`
759
+ }
760
+ }
761
+
762
+ const route = async (input = {}) => {
763
+ const startedAt = now().getTime()
764
+ const context = contextFor(input)
765
+ let policy = null
766
+ let policyError = null
767
+ try {
768
+ const candidate = readPolicy()
769
+ if (isPolicy(candidate)) policy = candidate
770
+ else policyError = new Error("invalid policy state")
771
+ } catch (error) {
772
+ policyError = error
773
+ }
774
+
775
+ let telemetry = null
776
+ let telemetryError = null
777
+ let decision
778
+
779
+ if (policyError !== null) {
780
+ const base = isPolicy(fallbackPolicy) ? fallbackPolicy : DEFAULT_FALLBACK_POLICY
781
+ decision = policyFailureDecision(base, policyError, context)
782
+ } else {
783
+ if (readTelemetry !== undefined) {
784
+ try {
785
+ const candidate = await readTelemetry({ signal: input.signal })
786
+ if (candidate === null || candidate === undefined) {
787
+ telemetry = null
788
+ } else if (isTelemetry(candidate)) {
789
+ telemetry = candidate
790
+ } else {
791
+ telemetryError = new Error("invalid telemetry snapshot")
792
+ }
793
+ } catch (error) {
794
+ telemetryError = error
795
+ }
796
+ }
797
+ decision =
798
+ telemetryError !== null
799
+ ? telemetryFailureDecision(policy, telemetryError, context)
800
+ : decide(policy, telemetry, context)
801
+ }
802
+
803
+ const latencyMs = Math.max(0, now().getTime() - startedAt)
804
+ const requestId =
805
+ input.requestId !== undefined && typeof input.requestId === "string" && input.requestId.length > 0
806
+ ? input.requestId
807
+ : `${input.agentId ?? "agent"}:${input.turn ?? "?"}:${input.step ?? "?"}:${decision.gate}`
808
+
809
+ const applied = input.applied === true
810
+ const row = buildDecisionRow({
811
+ id: newId(),
812
+ requestId,
813
+ omlxRequestId: input.omlxRequestId,
814
+ agentId: input.agentId,
815
+ decision,
816
+ contextTokens: input.contextTokens,
817
+ latencyMs,
818
+ at: now().toISOString(),
819
+ turn: input.turn,
820
+ step: input.step,
821
+ applied,
822
+ surface: input.surface ?? "router_route",
823
+ limitation: input.limitation ?? ROUTER_ROUTE_LIMITATION,
824
+ notAppliedReason: applied ? undefined : input.notAppliedReason ?? "step fixed",
825
+ appliedBy: input.appliedBy,
826
+ provider: input.provider
827
+ })
828
+
829
+ const ledger = recordDecision(runtime, row)
830
+ if (!ledger.ok && logger !== undefined && typeof logger.warn === "function") {
831
+ logger.warn(`router ledger write failed: ${ledger.error.message}`)
832
+ }
833
+
834
+ return {
835
+ ok: true,
836
+ decision,
837
+ row: ledger.ok ? row : null,
838
+ ledgerError: ledger.error,
839
+ policyError: errorInfo(policyError),
840
+ telemetryError: errorInfo(telemetryError),
841
+ telemetry: telemetrySummary(telemetry),
842
+ latencyMs
843
+ }
844
+ }
845
+
846
+ return { route }
847
+ }