@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.
@@ -0,0 +1,766 @@
1
+ // DSH route application for the dsh-local-router host.
2
+ //
3
+ // DSH source evidence (0.2.2-rc.5):
4
+ // dsh-agent-loop/src/agent.ts:235-256 wakeDriver emits agent/status before kick
5
+ // dsh-agent-loop/src/agent.ts:333-353 append turn/start, then preStep
6
+ // dsh-agent-loop/src/agent.ts:289-295 claim, then read modelSelection
7
+ // dsh-agent-loop/src/inbox.ts:103-111 agent/inbox/claimed before selection
8
+ // dsh-session/src/index.ts:404-420 session/event observers are observe-only
9
+ // dsh-session/src/index.ts:952-963 append reentrancy throws
10
+ //
11
+ // The verified DSH 0.2.2-rc.5 ordering is:
12
+ //
13
+ // agent/status("running")
14
+ // -> session/event("turn/start") [append is still publishing]
15
+ // -> agent/inbox/claimed [before preStep reads modelSelection]
16
+ // -> AgentModel.current() [selection fixed here]
17
+ // -> agent/pre-step [too late to select this step]
18
+ //
19
+ // session/event observers are synchronous observe-only and run while the
20
+ // session append is publishing; appending model/selection from there throws
21
+ // "session append cannot reenter while another append is being published".
22
+ // agent/pre-step reads modelSelection before dispatching. The working
23
+ // pre-selection surfaces are therefore agent/status (turn-level, before
24
+ // turn/start) and agent/inbox/claimed (step-level, immediately before
25
+ // modelSelection is read). session/event turn/start resolves and persists the
26
+ // turn decision; pre-step records it.
27
+ //
28
+ // Run 36 (DEC-36-03/15): route-application NEVER chooses a model. decide()
29
+ // returns the whole decision (model, target, gate, skips, reason); this module
30
+ // maps it to a DSH ModelSelection and applies it. When the host cannot apply
31
+ // the selection the decision is kept intact and notAppliedReason records why:
32
+ // agent not ready, model.select unavailable, model.select threw, step fixed.
33
+
34
+ import {
35
+ buildDecisionRow,
36
+ decide,
37
+ isPolicy,
38
+ isTelemetry,
39
+ recordDecision,
40
+ roleOf
41
+ } from "./routing.js"
42
+
43
+ export const TURN_START_LIMITATION =
44
+ "turn/start cannot append a model selection: the session append is still publishing; selection is applied from agent/inbox/claimed immediately before pre-step reads modelSelection"
45
+
46
+ export const NO_AGENT_LIMITATION =
47
+ "agent not ready: ctx.agents.get(session.id) returned undefined"
48
+
49
+ export const NO_ROUTE_LIMITATION =
50
+ "no applicable provider/model selection is available for this decision"
51
+
52
+ export const SELECT_UNAVAILABLE_LIMITATION =
53
+ "model.select is unavailable on this agent"
54
+
55
+ export const PRE_STEP_LIMITATION =
56
+ "step fixed: agent/pre-step runs after the step's model selection is fixed; model.select applies to the next step"
57
+
58
+ // The short, stable reasons a decision was not applied. These are integration
59
+ // facts, never a routing outcome: the decision keeps its model and gate.
60
+ export const NOT_APPLIED_REASONS = {
61
+ agentNotReady: "agent not ready",
62
+ selectUnavailable: "model.select unavailable",
63
+ selectThrew: "model.select threw",
64
+ stepFixed: "step fixed",
65
+ noRoute: "no applicable model"
66
+ }
67
+
68
+ const DEFAULT_FALLBACK_POLICY = {
69
+ floorTps: 50,
70
+ mainModel: null,
71
+ advisoryModel: "GPT 6.1 Sol",
72
+ rev: 1
73
+ }
74
+
75
+ const errorMessage = (error) =>
76
+ error instanceof Error ? error.message : error === undefined || error === null ? "unknown error" : String(error)
77
+
78
+ const sessionIdOfAgent = (agent) => {
79
+ const id = agent?.id ?? agent?.session?.id ?? agent?.session?.header?.id
80
+ return typeof id === "string" ? id : null
81
+ }
82
+
83
+ const sessionIdOfSession = (session) => (typeof session?.id === "string" ? session.id : null)
84
+
85
+ // F-36-10: context size. DSH reports input tokens on each assistant/message;
86
+ // there is no synchronous per-session token field a plugin can read, so we keep
87
+ // the latest per session and write it onto the NEXT routing row.
88
+ const lastContextTokens = new Map()
89
+
90
+ // Applied means provider/model reached the step; reasoning effort may be
91
+ // adapter-defaulted and is not part of the routed route identity.
92
+ const sameSelection = (left, right) =>
93
+ left !== null &&
94
+ right !== null &&
95
+ left.provider === right.provider &&
96
+ left.model === right.model
97
+
98
+ /** Bounded, non-throwing telemetry cache for synchronous pre-turn selection. */
99
+ export const createTelemetryCache = (options = {}) => {
100
+ const read = options.read
101
+ const now = options.now ?? (() => new Date())
102
+ const maxAgeMs = typeof options.maxAgeMs === "number" ? options.maxAgeMs : 10_000
103
+ let snapshot = null
104
+ let readAt = 0
105
+ let error = null
106
+ let inflight = null
107
+
108
+ const refresh = () => {
109
+ if (inflight !== null) return inflight
110
+ inflight = (async () => {
111
+ try {
112
+ const next = await read()
113
+ snapshot = next ?? null
114
+ readAt = now().getTime()
115
+ error = null
116
+ return snapshot
117
+ } catch (cause) {
118
+ // A failed refresh invalidates the snapshot: the chain is walked with no
119
+ // local evidence instead of stale speed/headroom evidence.
120
+ snapshot = null
121
+ readAt = 0
122
+ error = cause
123
+ return null
124
+ } finally {
125
+ inflight = null
126
+ }
127
+ })()
128
+ return inflight
129
+ }
130
+
131
+ const peek = () => {
132
+ if (snapshot === null) return null
133
+ if (now().getTime() - readAt > maxAgeMs) return null
134
+ return snapshot
135
+ }
136
+
137
+ return {
138
+ refresh,
139
+ peek,
140
+ snapshot: () => snapshot,
141
+ readAt: () => readAt,
142
+ error: () => error,
143
+ prime: (value, at = now().getTime()) => {
144
+ snapshot = value ?? null
145
+ readAt = at
146
+ error = null
147
+ }
148
+ }
149
+ }
150
+
151
+ /** Local providers registered in the host profile. A selection on any of
152
+ * these is a local route and must never be treated as the agent's remote route. */
153
+ export const DEFAULT_LOCAL_PROVIDERS = ["omlx", "mtplx", "mtplx-inkling", "lamq"]
154
+
155
+ /** Map a decision to a DSH ModelSelection (provider/model/reasoningEffort). */
156
+ export const createRouteMapper = (options = {}) => {
157
+ const localProvider = options.localProvider ?? "omlx"
158
+ // The provider route a local decision actually selects. It may differ from the
159
+ // telemetry provider: the engine adapter owns the transport.
160
+ const localSelectionProvider = options.localSelectionProvider ?? localProvider
161
+ const localProviders = new Set(
162
+ [
163
+ ...(Array.isArray(options.localProviders) ? options.localProviders : DEFAULT_LOCAL_PROVIDERS),
164
+ localProvider,
165
+ localSelectionProvider
166
+ ].filter((provider) => typeof provider === "string" && provider.length > 0)
167
+ )
168
+ const isLocalProvider = (provider) => localProviders.has(provider)
169
+
170
+ const map = (decision) => {
171
+ if (decision.target === "local") {
172
+ // Without a mounted local transport the selection would leave a pending
173
+ // model switch; fall back instead of applying an unroutable local model.
174
+ if (typeof options.localAvailable === "function" && options.localAvailable() === false) return null
175
+ if (typeof localSelectionProvider !== "string" || localSelectionProvider.length === 0) return null
176
+ if (typeof decision.model !== "string" || decision.model.length === 0) return null
177
+ return { provider: localSelectionProvider, model: decision.model }
178
+ }
179
+ // A remote decision applies exactly the model's provider/model, carried on
180
+ // the decision by decide(). There is no config pin, session preserve, or
181
+ // remote baseline: the decision is the single source of truth.
182
+ if (
183
+ typeof decision.provider === "string" && decision.provider.length > 0 &&
184
+ typeof decision.model === "string" && decision.model.length > 0
185
+ ) {
186
+ return { provider: decision.provider, model: decision.model }
187
+ }
188
+ return null
189
+ }
190
+
191
+ return { localProvider, isLocalProvider, map }
192
+ }
193
+
194
+ /**
195
+ * Apply router decisions to DSH agents using only existing DSH APIs.
196
+ * The pre-step handler records one row per decision (one per turn) and is the
197
+ * last surface that can apply the decision before the step's model is fixed.
198
+ */
199
+ export const createRouteApplication = (options = {}) => {
200
+ const runtime = options.runtime
201
+ if (runtime === undefined || typeof runtime.record !== "function") {
202
+ throw new TypeError("createRouteApplication needs a ledger runtime")
203
+ }
204
+ const readPolicy = options.readPolicy ?? (() => runtime.get())
205
+ const readTelemetry = options.readTelemetry
206
+ const fallbackPolicy = isPolicy(options.fallbackPolicy)
207
+ ? options.fallbackPolicy
208
+ : DEFAULT_FALLBACK_POLICY
209
+ const now = options.now ?? (() => new Date())
210
+ const newId = options.newId ?? (() => `route-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`)
211
+ const logger = options.logger
212
+ const resolveAgent = options.resolveAgent
213
+ const mapper = options.mapper ?? createRouteMapper(options)
214
+ // Per-session opt-in: routing only applies to sessions the user explicitly
215
+ // enabled. The host passes isRouted(sessionId) in; it defaults to false.
216
+ const isRouted = options.isRouted ?? (() => false)
217
+ // Run 25 (DEC-25-10): the Roles document is read live, never snapshotted at
218
+ // boot; resolveRoleModel maps a bare role model id to a real route (null when
219
+ // the model is unavailable). decide() walks the chain; this module only
220
+ // supplies it.
221
+ const readRoles = typeof options.readRoles === "function" ? options.readRoles : () => undefined
222
+ const resolveRoleModel = typeof options.resolveRoleModel === "function" ? options.resolveRoleModel : () => null
223
+ // R-36-07: the floor gate's per-model speed source (the probe store). Read
224
+ // synchronously at decision time; no probe runs inside a request path.
225
+ const speedFor = typeof options.speedFor === "function" ? options.speedFor : undefined
226
+ // R-36-10 (DEC-36-19): the host's load facts. The ceiling and pool throughput
227
+ // come from the engine snapshot; activeLocalSessions is counted from the DSH
228
+ // turn lifecycle below unless the caller already supplies it.
229
+ const readLoad = typeof options.readLoad === "function" ? options.readLoad : undefined
230
+ const cache =
231
+ options.cache ??
232
+ createTelemetryCache({
233
+ read: readTelemetry,
234
+ now,
235
+ maxAgeMs: options.cacheMaxAgeMs
236
+ })
237
+
238
+ const states = new Map()
239
+ const stateFor = (sessionId) => {
240
+ let state = states.get(sessionId)
241
+ if (state === undefined) {
242
+ state = { sessionId, pending: null, lastTurn: null }
243
+ states.set(sessionId, state)
244
+ }
245
+ return state
246
+ }
247
+
248
+ // R-36-10 (DEC-36-19): active local sessions, the input the headroom ceiling
249
+ // and the pool-contended floor need. A routed session counts while its turn is
250
+ // open and its decision target is local. session/event turn/start increments,
251
+ // turn/end decrements, and session/disposed releases a leaked slot. A missed
252
+ // turn/end therefore over-counts - the safe direction: the pool looks full, so
253
+ // new steps fall back instead of overloading it - until the session is
254
+ // disposed or the host restarts.
255
+ const activeLocalSessionIds = new Set()
256
+ const noteLocalActivity = (sessionId, decision) => {
257
+ if (decision !== null && decision !== undefined && decision.target === "local") {
258
+ activeLocalSessionIds.add(sessionId)
259
+ } else {
260
+ activeLocalSessionIds.delete(sessionId)
261
+ }
262
+ }
263
+ const loadFactsNow = () => {
264
+ let supplied = null
265
+ if (readLoad !== undefined) {
266
+ try {
267
+ const value = readLoad()
268
+ if (value !== null && typeof value === "object" && !Array.isArray(value)) supplied = value
269
+ } catch {
270
+ supplied = null
271
+ }
272
+ }
273
+ const load = supplied ?? {}
274
+ const suppliedActive = typeof load.activeLocalSessions === "number" && Number.isFinite(load.activeLocalSessions)
275
+ return { ...load, activeLocalSessions: suppliedActive ? load.activeLocalSessions : activeLocalSessionIds.size }
276
+ }
277
+
278
+ const chainForDecision = () => {
279
+ try {
280
+ return readRoles()
281
+ } catch {
282
+ return undefined
283
+ }
284
+ }
285
+
286
+ // DEC-36-24 (STEP 3): the DSH native picker is the session's current model.
287
+ // It is a session-local override for L1 only: read live at decision time, never
288
+ // stored back into roles.l1.model.
289
+ const sessionMainModelOf = (agent) => {
290
+ try {
291
+ const current = typeof agent?.model?.current === "function" ? agent.model.current() : null
292
+ const model = current !== null && typeof current === "object" && !Array.isArray(current) ? current.model : null
293
+ return typeof model === "string" && model.length > 0 ? model : null
294
+ } catch {
295
+ return null
296
+ }
297
+ }
298
+
299
+ // The decision context: role identity and the role's configured chain. The
300
+ // resolver turns a bare model id into a route; decide() does the choosing.
301
+ const contextFor = (agent) => ({
302
+ role: roleOf(agent),
303
+ chain: chainForDecision(),
304
+ resolve: resolveRoleModel,
305
+ speedFor,
306
+ load: loadFactsNow(),
307
+ sessionMainModel: sessionMainModelOf(agent)
308
+ })
309
+
310
+ const policyInput = () => {
311
+ try {
312
+ const policy = readPolicy()
313
+ if (isPolicy(policy)) return { policy, error: null }
314
+ return { policy: fallbackPolicy, error: new Error("invalid policy state") }
315
+ } catch (error) {
316
+ return { policy: fallbackPolicy, error }
317
+ }
318
+ }
319
+
320
+ const policyFailureDecision = (policy, error, context) => {
321
+ const base = decide(policy, null, context)
322
+ return {
323
+ ...base,
324
+ reason: `policy read failed (${errorMessage(error)}); ${base.reason}`
325
+ }
326
+ }
327
+
328
+ const telemetryFailureDecision = (policy, error, context) => {
329
+ const base = decide(policy, null, context)
330
+ return {
331
+ ...base,
332
+ reason: `telemetry unavailable (${error?.kind ?? error?.name ?? "error"}: ${errorMessage(error)}); ${base.reason}`
333
+ }
334
+ }
335
+
336
+ const decisionSync = (telemetry, agent) => {
337
+ const { policy, error } = policyInput()
338
+ const context = contextFor(agent)
339
+ if (error !== null) {
340
+ return { decision: policyFailureDecision(policy, error, context), policy, policyError: error, telemetry: null, telemetryError: null }
341
+ }
342
+ return { decision: decide(policy, telemetry, context), policy, policyError: null, telemetry, telemetryError: null }
343
+ }
344
+
345
+ const decisionFresh = async (signal, agent) => {
346
+ const { policy, error } = policyInput()
347
+ const context = contextFor(agent)
348
+ if (error !== null) {
349
+ return { decision: policyFailureDecision(policy, error, context), policy, policyError: error, telemetry: null, telemetryError: null }
350
+ }
351
+ if (readTelemetry === undefined) {
352
+ return { decision: decide(policy, null, context), policy, policyError: null, telemetry: null, telemetryError: null }
353
+ }
354
+ try {
355
+ const snapshot = await readTelemetry({ signal })
356
+ if (snapshot === null || snapshot === undefined) {
357
+ return { decision: decide(policy, null, context), policy, policyError: null, telemetry: null, telemetryError: null }
358
+ }
359
+ if (!isTelemetry(snapshot)) {
360
+ throw new Error("invalid telemetry snapshot")
361
+ }
362
+ return { decision: decide(policy, snapshot, context), policy, policyError: null, telemetry: snapshot, telemetryError: null }
363
+ } catch (telemetryError) {
364
+ return {
365
+ decision: telemetryFailureDecision(policy, telemetryError, context),
366
+ policy,
367
+ policyError: null,
368
+ telemetry: null,
369
+ telemetryError
370
+ }
371
+ }
372
+ }
373
+
374
+ const decisionForCache = (agent) => {
375
+ const { policy, error } = policyInput()
376
+ const context = contextFor(agent)
377
+ if (error !== null) {
378
+ return { decision: policyFailureDecision(policy, error, context), policy, policyError: error, telemetry: null, telemetryError: null }
379
+ }
380
+ const telemetry = cache.peek()
381
+ if (telemetry === null && cache.error() !== null) {
382
+ return {
383
+ decision: telemetryFailureDecision(policy, cache.error(), context),
384
+ policy,
385
+ policyError: null,
386
+ telemetry: null,
387
+ telemetryError: cache.error()
388
+ }
389
+ }
390
+ return { decision: decide(policy, telemetry, context), policy, policyError: null, telemetry, telemetryError: null }
391
+ }
392
+
393
+ const routeFor = (decision) => mapper.map(decision)
394
+
395
+ const attemptSelect = (agent, route) => {
396
+ if (route === null) {
397
+ return {
398
+ applied: false,
399
+ notAppliedReason: NOT_APPLIED_REASONS.noRoute,
400
+ limitation: NO_ROUTE_LIMITATION,
401
+ error: null
402
+ }
403
+ }
404
+ if (agent === undefined || agent === null) {
405
+ return {
406
+ applied: false,
407
+ notAppliedReason: NOT_APPLIED_REASONS.agentNotReady,
408
+ limitation: NO_AGENT_LIMITATION,
409
+ error: null
410
+ }
411
+ }
412
+ if (agent.model === undefined || typeof agent.model.select !== "function") {
413
+ return {
414
+ applied: false,
415
+ notAppliedReason: NOT_APPLIED_REASONS.selectUnavailable,
416
+ limitation: SELECT_UNAVAILABLE_LIMITATION,
417
+ error: null
418
+ }
419
+ }
420
+ try {
421
+ agent.model.select(route)
422
+ return { applied: true, notAppliedReason: null, limitation: null, error: null }
423
+ } catch (error) {
424
+ return {
425
+ applied: false,
426
+ notAppliedReason: NOT_APPLIED_REASONS.selectThrew,
427
+ limitation: `agent.model.select failed: ${errorMessage(error)}`,
428
+ error
429
+ }
430
+ }
431
+ }
432
+
433
+ const applySelection = (pending, selection, appliedBy) => {
434
+ if (selection.applied) {
435
+ pending.applied = true
436
+ pending.appliedBy = appliedBy
437
+ pending.notAppliedReason = null
438
+ pending.limitation = null
439
+ pending.error = null
440
+ } else {
441
+ pending.applied = false
442
+ pending.appliedBy = null
443
+ pending.notAppliedReason = selection.notAppliedReason ?? NOT_APPLIED_REASONS.stepFixed
444
+ pending.limitation = selection.limitation
445
+ pending.error = selection.error
446
+ }
447
+ }
448
+
449
+ const makePending = (input) => ({
450
+ decision: input.decision,
451
+ route: input.route,
452
+ turn: input.turn,
453
+ requestId: input.turn === null || input.turn === undefined ? null : `${input.sessionId}:${input.turn}`,
454
+ applied: false,
455
+ appliedBy: null,
456
+ notAppliedReason: null,
457
+ limitation: null,
458
+ error: null,
459
+ policyError: input.policyError ?? null,
460
+ telemetry: input.telemetry ?? null,
461
+ telemetryError: input.telemetryError ?? null,
462
+ surface: input.surface,
463
+ rowWritten: false,
464
+ rowId: null,
465
+ agentMissing: false,
466
+ createdAt: now().getTime()
467
+ })
468
+
469
+ const handleStatus = (payload = {}) => {
470
+ if (payload.status !== "running") return null
471
+ const agent = payload.agent
472
+ const sessionId = sessionIdOfAgent(agent)
473
+ if (sessionId === null) return null
474
+ if (!isRouted(sessionId, agent)) return null
475
+ const state = stateFor(sessionId)
476
+ const result = decisionForCache(agent)
477
+ const route = routeFor(result.decision)
478
+ const pending = makePending({
479
+ decision: result.decision,
480
+ route,
481
+ turn: null,
482
+ sessionId,
483
+ policyError: result.policyError,
484
+ telemetry: result.telemetry,
485
+ telemetryError: result.telemetryError,
486
+ surface: "agent/status"
487
+ })
488
+ applySelection(pending, attemptSelect(agent, route), "agent/status")
489
+ state.pending = pending
490
+ return pending
491
+ }
492
+
493
+ const handleTurnStart = (session, event) => {
494
+ // Capture the reported context size (F-36-10) so the next row records it.
495
+ if (event?.type === "assistant/message") {
496
+ const inputTokens = event?.usage?.inputTokens ?? event?.message?.usage?.inputTokens
497
+ if (typeof inputTokens === "number" && Number.isFinite(inputTokens) && inputTokens >= 0) {
498
+ lastContextTokens.set(sessionIdOfSession(session), Math.trunc(inputTokens))
499
+ }
500
+ }
501
+ if (event?.type !== "turn/start") {
502
+ if (event?.type === "turn/end") {
503
+ const sessionId = sessionIdOfSession(session)
504
+ if (sessionId !== null) {
505
+ const state = states.get(sessionId)
506
+ if (state !== undefined) state.pending = null
507
+ activeLocalSessionIds.delete(sessionId)
508
+ }
509
+ }
510
+ return null
511
+ }
512
+ const sessionId = sessionIdOfSession(session)
513
+ if (sessionId === null) return null
514
+ if (!isRouted(sessionId)) return null
515
+ const turn = event.data?.turn
516
+ const state = stateFor(sessionId)
517
+ let agent
518
+ try {
519
+ agent = resolveAgent?.(sessionId)
520
+ } catch {
521
+ agent = undefined
522
+ }
523
+ let pending = state.pending
524
+ if (pending === null || pending.rowWritten === true) {
525
+ const result = decisionForCache(agent)
526
+ const route = routeFor(result.decision)
527
+ pending = makePending({
528
+ decision: result.decision,
529
+ route,
530
+ turn,
531
+ sessionId,
532
+ policyError: result.policyError,
533
+ telemetry: result.telemetry,
534
+ telemetryError: result.telemetryError,
535
+ surface: "turn/start"
536
+ })
537
+ pending.limitation = TURN_START_LIMITATION
538
+ state.pending = pending
539
+ } else {
540
+ pending.turn = turn
541
+ pending.requestId = `${sessionId}:${turn}`
542
+ if (pending.surface === "agent/status" && pending.applied) {
543
+ pending.notAppliedReason = null
544
+ pending.limitation = null
545
+ }
546
+ if (pending.route === null) pending.route = routeFor(pending.decision)
547
+ }
548
+
549
+ if ((agent === undefined || agent === null) && !pending.applied) {
550
+ pending.agentMissing = true
551
+ pending.notAppliedReason = NOT_APPLIED_REASONS.agentNotReady
552
+ pending.limitation = NO_AGENT_LIMITATION
553
+ }
554
+ noteLocalActivity(sessionId, pending.decision)
555
+ state.lastTurn = turn
556
+ return pending
557
+ }
558
+
559
+ const handleClaimed = (payload = {}) => {
560
+ const agent = payload.agent
561
+ const turn = payload.turn
562
+ const sessionId = sessionIdOfAgent(agent)
563
+ if (sessionId === null) return null
564
+ if (!isRouted(sessionId, agent)) return null
565
+ const state = stateFor(sessionId)
566
+ let pending = state.pending
567
+ if (pending === null || (pending.turn !== null && pending.turn !== turn)) {
568
+ const result = decisionForCache(agent)
569
+ const route = routeFor(result.decision)
570
+ pending = makePending({
571
+ decision: result.decision,
572
+ route,
573
+ turn,
574
+ sessionId,
575
+ policyError: result.policyError,
576
+ telemetry: result.telemetry,
577
+ telemetryError: result.telemetryError,
578
+ surface: "agent/inbox/claimed"
579
+ })
580
+ state.pending = pending
581
+ } else if (pending.turn === null) {
582
+ pending.turn = turn
583
+ pending.requestId = `${sessionId}:${turn}`
584
+ }
585
+ if (pending.agentMissing) {
586
+ const result = decisionForCache(agent)
587
+ pending.decision = result.decision
588
+ pending.route = routeFor(result.decision)
589
+ pending.telemetry = result.telemetry
590
+ pending.telemetryError = result.telemetryError
591
+ pending.policyError = result.policyError
592
+ pending.agentMissing = false
593
+ pending.notAppliedReason = null
594
+ pending.limitation = null
595
+ }
596
+ if (pending.applied) return pending
597
+
598
+ if (pending.route === null) pending.route = routeFor(pending.decision)
599
+ pending.surface = pending.surface === "agent/status" || pending.surface === "turn/start"
600
+ ? "agent/inbox/claimed"
601
+ : pending.surface
602
+ applySelection(pending, attemptSelect(agent, pending.route), "agent/inbox/claimed")
603
+ return pending
604
+ }
605
+
606
+ const handlePreStep = async (payload = {}, next) => {
607
+ const stepDecision = await next()
608
+ if (stepDecision?.kind === "reject" || payload.signal?.aborted === true) return stepDecision
609
+
610
+ const agent = payload.agent
611
+ const sessionId = sessionIdOfAgent(agent)
612
+ if (sessionId === null) return stepDecision
613
+ if (!isRouted(sessionId, agent)) return stepDecision
614
+ const turn = payload.turn
615
+ const step = payload.step
616
+ const state = stateFor(sessionId)
617
+ let pending = state.pending
618
+ let usedFreshTelemetry = false
619
+
620
+ if (pending === null || pending.turn !== turn) {
621
+ usedFreshTelemetry = true
622
+ const result = await decisionFresh(payload.signal, agent)
623
+ const route = routeFor(result.decision)
624
+ pending = makePending({
625
+ decision: result.decision,
626
+ route,
627
+ turn,
628
+ sessionId,
629
+ policyError: result.policyError,
630
+ telemetry: result.telemetry,
631
+ telemetryError: result.telemetryError,
632
+ surface: "pre-step"
633
+ })
634
+ pending.notAppliedReason = NOT_APPLIED_REASONS.stepFixed
635
+ pending.limitation = PRE_STEP_LIMITATION
636
+ state.pending = pending
637
+ }
638
+
639
+ if (pending.agentMissing) {
640
+ usedFreshTelemetry = true
641
+ const result = await decisionFresh(payload.signal, agent)
642
+ pending.decision = result.decision
643
+ pending.route = routeFor(result.decision)
644
+ pending.telemetry = result.telemetry
645
+ pending.telemetryError = result.telemetryError
646
+ pending.policyError = result.policyError
647
+ pending.agentMissing = false
648
+ pending.notAppliedReason = null
649
+ pending.limitation = null
650
+ }
651
+
652
+ let mismatchLimitation = null
653
+ if (pending.applied && pending.route !== null && !sameSelection(payload.modelSelection, pending.route)) {
654
+ mismatchLimitation = "the step's fixed modelSelection does not match the applied router selection"
655
+ pending.applied = false
656
+ pending.appliedBy = null
657
+ pending.notAppliedReason = NOT_APPLIED_REASONS.stepFixed
658
+ pending.limitation = mismatchLimitation
659
+ }
660
+
661
+ if (!pending.applied && !pending.rowWritten) {
662
+ if (pending.route === null) pending.route = routeFor(pending.decision)
663
+ if (pending.route !== null && agent?.model !== undefined && typeof agent.model.select === "function") {
664
+ const selection = attemptSelect(agent, pending.route)
665
+ if (selection.applied) {
666
+ // The current step already read its selection, so the model is
667
+ // selected for the NEXT step. The current step is still not applied.
668
+ pending.applied = false
669
+ pending.appliedBy = "agent/pre-step"
670
+ pending.notAppliedReason = NOT_APPLIED_REASONS.stepFixed
671
+ pending.limitation =
672
+ mismatchLimitation === null
673
+ ? PRE_STEP_LIMITATION
674
+ : mismatchLimitation + "; " + PRE_STEP_LIMITATION
675
+ pending.error = null
676
+ } else {
677
+ pending.notAppliedReason = selection.notAppliedReason
678
+ pending.limitation = selection.limitation
679
+ pending.error = selection.error
680
+ }
681
+ } else if (pending.limitation === null) {
682
+ pending.notAppliedReason =
683
+ pending.route === null ? NOT_APPLIED_REASONS.noRoute : NOT_APPLIED_REASONS.selectUnavailable
684
+ pending.limitation = pending.route === null ? NO_ROUTE_LIMITATION : SELECT_UNAVAILABLE_LIMITATION
685
+ }
686
+ }
687
+
688
+ if (!pending.rowWritten) {
689
+ const row = buildDecisionRow({
690
+ id: newId(),
691
+ requestId: pending.requestId ?? `${sessionId}:${turn}`,
692
+ agentId: sessionId,
693
+ decision: pending.decision,
694
+ contextTokens: lastContextTokens.get(sessionId) ?? 0,
695
+ latencyMs: Math.max(0, now().getTime() - pending.createdAt),
696
+ at: now().toISOString(),
697
+ turn,
698
+ step,
699
+ applied: pending.applied,
700
+ appliedBy: pending.appliedBy,
701
+ notAppliedReason: pending.applied
702
+ ? null
703
+ : pending.notAppliedReason ?? NOT_APPLIED_REASONS.stepFixed,
704
+ limitation: pending.limitation,
705
+ provider: pending.route?.provider ?? null,
706
+ selectedModel: pending.route?.model ?? null,
707
+ surface: pending.surface
708
+ })
709
+ const ledger = recordDecision(runtime, row)
710
+ if (ledger.ok) {
711
+ pending.rowWritten = true
712
+ pending.rowId = row.id
713
+ } else if (typeof logger?.warn === "function") {
714
+ logger.warn(`router harness ledger write failed: ${ledger.error.message}`)
715
+ }
716
+ if (usedFreshTelemetry) {
717
+ if (pending.telemetry !== null && pending.telemetry !== undefined) {
718
+ cache.prime(pending.telemetry)
719
+ }
720
+ } else {
721
+ void cache.refresh()
722
+ }
723
+ }
724
+
725
+ // R-37-03/DEC-37-05: cap the prepared call's context window to the role's
726
+ // window, applied to whatever model the role uses. A null or absent window
727
+ // (the Advisor's "no cap", or an unknown depth) injects nothing, so the
728
+ // model's own window stands. The loop reads preparedCall.context.contextWindow
729
+ // (dsh-agent-loop:1079) for the request/context record and compaction budget.
730
+ const roles = typeof options.readRoles === "function" ? options.readRoles() : null
731
+ const role = roleOf(agent)
732
+ const roleWindow =
733
+ roles !== null && typeof roles === "object" && !Array.isArray(roles) &&
734
+ roles[role] !== null && typeof roles[role] === "object" && Number.isFinite(roles[role].contextWindow)
735
+ ? Math.trunc(roles[role].contextWindow)
736
+ : null
737
+ const prepared = stepDecision !== null && typeof stepDecision === "object" && !Array.isArray(stepDecision) ? stepDecision : {}
738
+ const context = { ...(prepared.context ?? {}) }
739
+ if (roleWindow !== null) context.contextWindow = roleWindow
740
+ return { ...prepared, context }
741
+ }
742
+
743
+ const handleSessionDisposed = (session) => {
744
+ const sessionId = sessionIdOfSession(session)
745
+ if (sessionId !== null) {
746
+ states.delete(sessionId)
747
+ activeLocalSessionIds.delete(sessionId)
748
+ }
749
+ }
750
+
751
+ return {
752
+ cache,
753
+ mapper,
754
+ handleStatus,
755
+ handleTurnStart,
756
+ handleClaimed,
757
+ handlePreStep,
758
+ handleSessionDisposed,
759
+ primeTelemetry: (snapshot, at) => cache.prime(snapshot, at),
760
+ refreshTelemetry: () => cache.refresh(),
761
+ stateFor,
762
+ pendingFor: (sessionId) => states.get(sessionId)?.pending ?? null,
763
+ // R-36-10: sessions currently sharing the local engine (the ceiling input).
764
+ activeLocalSessions: () => activeLocalSessionIds.size
765
+ }
766
+ }