@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.
@@ -0,0 +1,780 @@
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
+ // DEC-37-11: a role with a finite context window is served through its own
178
+ // provider route, whose adapter resolveModel() carries that window - so the
179
+ // child's recorded window and compaction budget are the role's, at spawn.
180
+ const roleProvider =
181
+ typeof options.roleProviderFor === "function" && typeof decision.role === "string"
182
+ ? options.roleProviderFor(decision.role)
183
+ : null
184
+ return {
185
+ provider: typeof roleProvider === "string" && roleProvider.length > 0 ? roleProvider : localSelectionProvider,
186
+ model: decision.model
187
+ }
188
+ }
189
+ // A remote decision applies exactly the model's provider/model, carried on
190
+ // the decision by decide(). There is no config pin, session preserve, or
191
+ // remote baseline: the decision is the single source of truth.
192
+ if (
193
+ typeof decision.provider === "string" && decision.provider.length > 0 &&
194
+ typeof decision.model === "string" && decision.model.length > 0
195
+ ) {
196
+ return { provider: decision.provider, model: decision.model }
197
+ }
198
+ return null
199
+ }
200
+
201
+ return { localProvider, isLocalProvider, map }
202
+ }
203
+
204
+ /**
205
+ * Apply router decisions to DSH agents using only existing DSH APIs.
206
+ * The pre-step handler records one row per decision (one per turn) and is the
207
+ * last surface that can apply the decision before the step's model is fixed.
208
+ */
209
+ export const createRouteApplication = (options = {}) => {
210
+ const runtime = options.runtime
211
+ if (runtime === undefined || typeof runtime.record !== "function") {
212
+ throw new TypeError("createRouteApplication needs a ledger runtime")
213
+ }
214
+ const readPolicy = options.readPolicy ?? (() => runtime.get())
215
+ const readTelemetry = options.readTelemetry
216
+ const fallbackPolicy = isPolicy(options.fallbackPolicy)
217
+ ? options.fallbackPolicy
218
+ : DEFAULT_FALLBACK_POLICY
219
+ const now = options.now ?? (() => new Date())
220
+ const newId = options.newId ?? (() => `route-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`)
221
+ const logger = options.logger
222
+ const resolveAgent = options.resolveAgent
223
+ const mapper = options.mapper ?? createRouteMapper(options)
224
+ // Per-session opt-in: routing only applies to sessions the user explicitly
225
+ // enabled. The host passes isRouted(sessionId) in; it defaults to false.
226
+ const isRouted = options.isRouted ?? (() => false)
227
+ // Run 25 (DEC-25-10): the Roles document is read live, never snapshotted at
228
+ // boot; resolveRoleModel maps a bare role model id to a real route (null when
229
+ // the model is unavailable). decide() walks the chain; this module only
230
+ // supplies it.
231
+ const readRoles = typeof options.readRoles === "function" ? options.readRoles : () => undefined
232
+ const resolveRoleModel = typeof options.resolveRoleModel === "function" ? options.resolveRoleModel : () => null
233
+ // R-36-07: the floor gate's per-model speed source (the probe store). Read
234
+ // synchronously at decision time; no probe runs inside a request path.
235
+ const speedFor = typeof options.speedFor === "function" ? options.speedFor : undefined
236
+ // R-36-10 (DEC-36-19): the host's load facts. The ceiling and pool throughput
237
+ // come from the engine snapshot; activeLocalSessions is counted from the DSH
238
+ // turn lifecycle below unless the caller already supplies it.
239
+ const readLoad = typeof options.readLoad === "function" ? options.readLoad : undefined
240
+ const cache =
241
+ options.cache ??
242
+ createTelemetryCache({
243
+ read: readTelemetry,
244
+ now,
245
+ maxAgeMs: options.cacheMaxAgeMs
246
+ })
247
+
248
+ const states = new Map()
249
+ const stateFor = (sessionId) => {
250
+ let state = states.get(sessionId)
251
+ if (state === undefined) {
252
+ state = { sessionId, pending: null, lastTurn: null }
253
+ states.set(sessionId, state)
254
+ }
255
+ return state
256
+ }
257
+
258
+ // R-36-10 (DEC-36-19): active local sessions, the input the headroom ceiling
259
+ // and the pool-contended floor need. A routed session counts while its turn is
260
+ // open and its decision target is local. session/event turn/start increments,
261
+ // turn/end decrements, and session/disposed releases a leaked slot. A missed
262
+ // turn/end therefore over-counts - the safe direction: the pool looks full, so
263
+ // new steps fall back instead of overloading it - until the session is
264
+ // disposed or the host restarts.
265
+ const activeLocalSessionIds = new Set()
266
+ const noteLocalActivity = (sessionId, decision) => {
267
+ if (decision !== null && decision !== undefined && decision.target === "local") {
268
+ activeLocalSessionIds.add(sessionId)
269
+ } else {
270
+ activeLocalSessionIds.delete(sessionId)
271
+ }
272
+ }
273
+ const loadFactsNow = () => {
274
+ let supplied = null
275
+ if (readLoad !== undefined) {
276
+ try {
277
+ const value = readLoad()
278
+ if (value !== null && typeof value === "object" && !Array.isArray(value)) supplied = value
279
+ } catch {
280
+ supplied = null
281
+ }
282
+ }
283
+ const load = supplied ?? {}
284
+ const suppliedActive = typeof load.activeLocalSessions === "number" && Number.isFinite(load.activeLocalSessions)
285
+ return { ...load, activeLocalSessions: suppliedActive ? load.activeLocalSessions : activeLocalSessionIds.size }
286
+ }
287
+
288
+ const chainForDecision = () => {
289
+ try {
290
+ return readRoles()
291
+ } catch {
292
+ return undefined
293
+ }
294
+ }
295
+
296
+ // DEC-36-24 (STEP 3): the DSH native picker is the session's current model.
297
+ // It is a session-local override for L1 only: read live at decision time, never
298
+ // stored back into roles.l1.model.
299
+ const sessionMainModelOf = (agent) => {
300
+ try {
301
+ const current = typeof agent?.model?.current === "function" ? agent.model.current() : null
302
+ const model = current !== null && typeof current === "object" && !Array.isArray(current) ? current.model : null
303
+ return typeof model === "string" && model.length > 0 ? model : null
304
+ } catch {
305
+ return null
306
+ }
307
+ }
308
+
309
+ // The decision context: role identity and the role's configured chain. The
310
+ // resolver turns a bare model id into a route; decide() does the choosing.
311
+ const contextFor = (agent) => ({
312
+ role: roleOf(agent),
313
+ chain: chainForDecision(),
314
+ resolve: resolveRoleModel,
315
+ speedFor,
316
+ load: loadFactsNow(),
317
+ sessionMainModel: sessionMainModelOf(agent)
318
+ })
319
+
320
+ const policyInput = () => {
321
+ try {
322
+ const policy = readPolicy()
323
+ if (isPolicy(policy)) return { policy, error: null }
324
+ return { policy: fallbackPolicy, error: new Error("invalid policy state") }
325
+ } catch (error) {
326
+ return { policy: fallbackPolicy, error }
327
+ }
328
+ }
329
+
330
+ const policyFailureDecision = (policy, error, context) => {
331
+ const base = decide(policy, null, context)
332
+ return {
333
+ ...base,
334
+ reason: `policy read failed (${errorMessage(error)}); ${base.reason}`
335
+ }
336
+ }
337
+
338
+ const telemetryFailureDecision = (policy, error, context) => {
339
+ const base = decide(policy, null, context)
340
+ return {
341
+ ...base,
342
+ reason: `telemetry unavailable (${error?.kind ?? error?.name ?? "error"}: ${errorMessage(error)}); ${base.reason}`
343
+ }
344
+ }
345
+
346
+ const decisionSync = (telemetry, agent) => {
347
+ const { policy, error } = policyInput()
348
+ const context = contextFor(agent)
349
+ if (error !== null) {
350
+ return { decision: policyFailureDecision(policy, error, context), policy, policyError: error, telemetry: null, telemetryError: null }
351
+ }
352
+ return { decision: decide(policy, telemetry, context), policy, policyError: null, telemetry, telemetryError: null }
353
+ }
354
+
355
+ const decisionFresh = async (signal, agent) => {
356
+ const { policy, error } = policyInput()
357
+ const context = contextFor(agent)
358
+ if (error !== null) {
359
+ return { decision: policyFailureDecision(policy, error, context), policy, policyError: error, telemetry: null, telemetryError: null }
360
+ }
361
+ if (readTelemetry === undefined) {
362
+ return { decision: decide(policy, null, context), policy, policyError: null, telemetry: null, telemetryError: null }
363
+ }
364
+ try {
365
+ const snapshot = await readTelemetry({ signal })
366
+ if (snapshot === null || snapshot === undefined) {
367
+ return { decision: decide(policy, null, context), policy, policyError: null, telemetry: null, telemetryError: null }
368
+ }
369
+ if (!isTelemetry(snapshot)) {
370
+ throw new Error("invalid telemetry snapshot")
371
+ }
372
+ return { decision: decide(policy, snapshot, context), policy, policyError: null, telemetry: snapshot, telemetryError: null }
373
+ } catch (telemetryError) {
374
+ return {
375
+ decision: telemetryFailureDecision(policy, telemetryError, context),
376
+ policy,
377
+ policyError: null,
378
+ telemetry: null,
379
+ telemetryError
380
+ }
381
+ }
382
+ }
383
+
384
+ const decisionForCache = (agent) => {
385
+ const { policy, error } = policyInput()
386
+ const context = contextFor(agent)
387
+ if (error !== null) {
388
+ return { decision: policyFailureDecision(policy, error, context), policy, policyError: error, telemetry: null, telemetryError: null }
389
+ }
390
+ const telemetry = cache.peek()
391
+ if (telemetry === null && cache.error() !== null) {
392
+ return {
393
+ decision: telemetryFailureDecision(policy, cache.error(), context),
394
+ policy,
395
+ policyError: null,
396
+ telemetry: null,
397
+ telemetryError: cache.error()
398
+ }
399
+ }
400
+ return { decision: decide(policy, telemetry, context), policy, policyError: null, telemetry, telemetryError: null }
401
+ }
402
+
403
+ const routeFor = (decision) => mapper.map(decision)
404
+
405
+ const attemptSelect = (agent, route) => {
406
+ if (route === null) {
407
+ return {
408
+ applied: false,
409
+ notAppliedReason: NOT_APPLIED_REASONS.noRoute,
410
+ limitation: NO_ROUTE_LIMITATION,
411
+ error: null
412
+ }
413
+ }
414
+ if (agent === undefined || agent === null) {
415
+ return {
416
+ applied: false,
417
+ notAppliedReason: NOT_APPLIED_REASONS.agentNotReady,
418
+ limitation: NO_AGENT_LIMITATION,
419
+ error: null
420
+ }
421
+ }
422
+ if (agent.model === undefined || typeof agent.model.select !== "function") {
423
+ return {
424
+ applied: false,
425
+ notAppliedReason: NOT_APPLIED_REASONS.selectUnavailable,
426
+ limitation: SELECT_UNAVAILABLE_LIMITATION,
427
+ error: null
428
+ }
429
+ }
430
+ try {
431
+ agent.model.select(route)
432
+ return { applied: true, notAppliedReason: null, limitation: null, error: null }
433
+ } catch (error) {
434
+ return {
435
+ applied: false,
436
+ notAppliedReason: NOT_APPLIED_REASONS.selectThrew,
437
+ limitation: `agent.model.select failed: ${errorMessage(error)}`,
438
+ error
439
+ }
440
+ }
441
+ }
442
+
443
+ const applySelection = (pending, selection, appliedBy) => {
444
+ if (selection.applied) {
445
+ pending.applied = true
446
+ pending.appliedBy = appliedBy
447
+ pending.notAppliedReason = null
448
+ pending.limitation = null
449
+ pending.error = null
450
+ } else {
451
+ pending.applied = false
452
+ pending.appliedBy = null
453
+ pending.notAppliedReason = selection.notAppliedReason ?? NOT_APPLIED_REASONS.stepFixed
454
+ pending.limitation = selection.limitation
455
+ pending.error = selection.error
456
+ }
457
+ }
458
+
459
+ const makePending = (input) => ({
460
+ decision: input.decision,
461
+ route: input.route,
462
+ turn: input.turn,
463
+ requestId: input.turn === null || input.turn === undefined ? null : `${input.sessionId}:${input.turn}`,
464
+ applied: false,
465
+ appliedBy: null,
466
+ notAppliedReason: null,
467
+ limitation: null,
468
+ error: null,
469
+ policyError: input.policyError ?? null,
470
+ telemetry: input.telemetry ?? null,
471
+ telemetryError: input.telemetryError ?? null,
472
+ surface: input.surface,
473
+ rowWritten: false,
474
+ rowId: null,
475
+ agentMissing: false,
476
+ createdAt: now().getTime()
477
+ })
478
+
479
+ const handleStatus = (payload = {}) => {
480
+ if (payload.status !== "running") return null
481
+ const agent = payload.agent
482
+ const sessionId = sessionIdOfAgent(agent)
483
+ if (sessionId === null) return null
484
+ if (!isRouted(sessionId, agent)) return null
485
+ const state = stateFor(sessionId)
486
+ const result = decisionForCache(agent)
487
+ const route = routeFor(result.decision)
488
+ const pending = makePending({
489
+ decision: result.decision,
490
+ route,
491
+ turn: null,
492
+ sessionId,
493
+ policyError: result.policyError,
494
+ telemetry: result.telemetry,
495
+ telemetryError: result.telemetryError,
496
+ surface: "agent/status"
497
+ })
498
+ applySelection(pending, attemptSelect(agent, route), "agent/status")
499
+ state.pending = pending
500
+ return pending
501
+ }
502
+
503
+ const handleTurnStart = (session, event) => {
504
+ // Capture the reported context size (F-36-10) so the next row records it.
505
+ if (event?.type === "assistant/message") {
506
+ const inputTokens = event?.usage?.inputTokens ?? event?.message?.usage?.inputTokens
507
+ if (typeof inputTokens === "number" && Number.isFinite(inputTokens) && inputTokens >= 0) {
508
+ lastContextTokens.set(sessionIdOfSession(session), Math.trunc(inputTokens))
509
+ }
510
+ }
511
+ if (event?.type !== "turn/start") {
512
+ if (event?.type === "turn/end") {
513
+ const sessionId = sessionIdOfSession(session)
514
+ if (sessionId !== null) {
515
+ const state = states.get(sessionId)
516
+ if (state !== undefined) state.pending = null
517
+ activeLocalSessionIds.delete(sessionId)
518
+ }
519
+ }
520
+ return null
521
+ }
522
+ const sessionId = sessionIdOfSession(session)
523
+ if (sessionId === null) return null
524
+ if (!isRouted(sessionId)) return null
525
+ const turn = event.data?.turn
526
+ const state = stateFor(sessionId)
527
+ let agent
528
+ try {
529
+ agent = resolveAgent?.(sessionId)
530
+ } catch {
531
+ agent = undefined
532
+ }
533
+ let pending = state.pending
534
+ if (pending === null || pending.rowWritten === true) {
535
+ const result = decisionForCache(agent)
536
+ const route = routeFor(result.decision)
537
+ pending = makePending({
538
+ decision: result.decision,
539
+ route,
540
+ turn,
541
+ sessionId,
542
+ policyError: result.policyError,
543
+ telemetry: result.telemetry,
544
+ telemetryError: result.telemetryError,
545
+ surface: "turn/start"
546
+ })
547
+ pending.limitation = TURN_START_LIMITATION
548
+ state.pending = pending
549
+ } else {
550
+ pending.turn = turn
551
+ pending.requestId = `${sessionId}:${turn}`
552
+ if (pending.surface === "agent/status" && pending.applied) {
553
+ pending.notAppliedReason = null
554
+ pending.limitation = null
555
+ }
556
+ if (pending.route === null) pending.route = routeFor(pending.decision)
557
+ }
558
+
559
+ if ((agent === undefined || agent === null) && !pending.applied) {
560
+ pending.agentMissing = true
561
+ pending.notAppliedReason = NOT_APPLIED_REASONS.agentNotReady
562
+ pending.limitation = NO_AGENT_LIMITATION
563
+ }
564
+ noteLocalActivity(sessionId, pending.decision)
565
+ state.lastTurn = turn
566
+ return pending
567
+ }
568
+
569
+ const handleClaimed = (payload = {}) => {
570
+ const agent = payload.agent
571
+ const turn = payload.turn
572
+ const sessionId = sessionIdOfAgent(agent)
573
+ if (sessionId === null) return null
574
+ if (!isRouted(sessionId, agent)) return null
575
+ const state = stateFor(sessionId)
576
+ let pending = state.pending
577
+ if (pending === null || (pending.turn !== null && pending.turn !== turn)) {
578
+ const result = decisionForCache(agent)
579
+ const route = routeFor(result.decision)
580
+ pending = makePending({
581
+ decision: result.decision,
582
+ route,
583
+ turn,
584
+ sessionId,
585
+ policyError: result.policyError,
586
+ telemetry: result.telemetry,
587
+ telemetryError: result.telemetryError,
588
+ surface: "agent/inbox/claimed"
589
+ })
590
+ state.pending = pending
591
+ } else if (pending.turn === null) {
592
+ pending.turn = turn
593
+ pending.requestId = `${sessionId}:${turn}`
594
+ }
595
+ if (pending.agentMissing) {
596
+ const result = decisionForCache(agent)
597
+ pending.decision = result.decision
598
+ pending.route = routeFor(result.decision)
599
+ pending.telemetry = result.telemetry
600
+ pending.telemetryError = result.telemetryError
601
+ pending.policyError = result.policyError
602
+ pending.agentMissing = false
603
+ pending.notAppliedReason = null
604
+ pending.limitation = null
605
+ }
606
+ if (pending.applied) return pending
607
+
608
+ if (pending.route === null) pending.route = routeFor(pending.decision)
609
+ pending.surface = pending.surface === "agent/status" || pending.surface === "turn/start"
610
+ ? "agent/inbox/claimed"
611
+ : pending.surface
612
+ applySelection(pending, attemptSelect(agent, pending.route), "agent/inbox/claimed")
613
+ return pending
614
+ }
615
+
616
+ const handlePreStep = async (payload = {}, next) => {
617
+ const stepDecision = await next()
618
+ if (stepDecision?.kind === "reject" || payload.signal?.aborted === true) return stepDecision
619
+
620
+ const agent = payload.agent
621
+ const sessionId = sessionIdOfAgent(agent)
622
+ if (sessionId === null) return stepDecision
623
+ if (!isRouted(sessionId, agent)) return stepDecision
624
+ const turn = payload.turn
625
+ const step = payload.step
626
+ const state = stateFor(sessionId)
627
+ let pending = state.pending
628
+ let usedFreshTelemetry = false
629
+
630
+ if (pending === null || pending.turn !== turn) {
631
+ usedFreshTelemetry = true
632
+ const result = await decisionFresh(payload.signal, agent)
633
+ const route = routeFor(result.decision)
634
+ pending = makePending({
635
+ decision: result.decision,
636
+ route,
637
+ turn,
638
+ sessionId,
639
+ policyError: result.policyError,
640
+ telemetry: result.telemetry,
641
+ telemetryError: result.telemetryError,
642
+ surface: "pre-step"
643
+ })
644
+ pending.notAppliedReason = NOT_APPLIED_REASONS.stepFixed
645
+ pending.limitation = PRE_STEP_LIMITATION
646
+ state.pending = pending
647
+ }
648
+
649
+ if (pending.agentMissing) {
650
+ usedFreshTelemetry = true
651
+ const result = await decisionFresh(payload.signal, agent)
652
+ pending.decision = result.decision
653
+ pending.route = routeFor(result.decision)
654
+ pending.telemetry = result.telemetry
655
+ pending.telemetryError = result.telemetryError
656
+ pending.policyError = result.policyError
657
+ pending.agentMissing = false
658
+ pending.notAppliedReason = null
659
+ pending.limitation = null
660
+ }
661
+
662
+ let mismatchLimitation = null
663
+ if (pending.applied && pending.route !== null && !sameSelection(payload.modelSelection, pending.route)) {
664
+ mismatchLimitation = "the step's fixed modelSelection does not match the applied router selection"
665
+ pending.applied = false
666
+ pending.appliedBy = null
667
+ pending.notAppliedReason = NOT_APPLIED_REASONS.stepFixed
668
+ pending.limitation = mismatchLimitation
669
+ }
670
+
671
+ if (!pending.applied && !pending.rowWritten) {
672
+ if (pending.route === null) pending.route = routeFor(pending.decision)
673
+ if (pending.route !== null && agent?.model !== undefined && typeof agent.model.select === "function") {
674
+ const selection = attemptSelect(agent, pending.route)
675
+ if (selection.applied) {
676
+ // The current step already read its selection, so the model is
677
+ // selected for the NEXT step. The current step is still not applied.
678
+ pending.applied = false
679
+ pending.appliedBy = "agent/pre-step"
680
+ pending.notAppliedReason = NOT_APPLIED_REASONS.stepFixed
681
+ pending.limitation =
682
+ mismatchLimitation === null
683
+ ? PRE_STEP_LIMITATION
684
+ : mismatchLimitation + "; " + PRE_STEP_LIMITATION
685
+ pending.error = null
686
+ } else {
687
+ pending.notAppliedReason = selection.notAppliedReason
688
+ pending.limitation = selection.limitation
689
+ pending.error = selection.error
690
+ }
691
+ } else if (pending.limitation === null) {
692
+ pending.notAppliedReason =
693
+ pending.route === null ? NOT_APPLIED_REASONS.noRoute : NOT_APPLIED_REASONS.selectUnavailable
694
+ pending.limitation = pending.route === null ? NO_ROUTE_LIMITATION : SELECT_UNAVAILABLE_LIMITATION
695
+ }
696
+ }
697
+
698
+ if (!pending.rowWritten) {
699
+ const row = buildDecisionRow({
700
+ id: newId(),
701
+ requestId: pending.requestId ?? `${sessionId}:${turn}`,
702
+ sessionId,
703
+ agentId: sessionId,
704
+ decision: pending.decision,
705
+ contextTokens: lastContextTokens.get(sessionId) ?? 0,
706
+ latencyMs: Math.max(0, now().getTime() - pending.createdAt),
707
+ at: now().toISOString(),
708
+ turn,
709
+ step,
710
+ applied: pending.applied,
711
+ appliedBy: pending.appliedBy,
712
+ notAppliedReason: pending.applied
713
+ ? null
714
+ : pending.notAppliedReason ?? NOT_APPLIED_REASONS.stepFixed,
715
+ limitation: pending.limitation,
716
+ provider: pending.route?.provider ?? null,
717
+ selectedModel: pending.route?.model ?? null,
718
+ surface: pending.surface
719
+ })
720
+ const ledger = recordDecision(runtime, row)
721
+ if (ledger.ok) {
722
+ pending.rowWritten = true
723
+ pending.rowId = row.id
724
+ } else if (typeof logger?.warn === "function") {
725
+ logger.warn(`router harness ledger write failed: ${ledger.error.message}`)
726
+ }
727
+ if (usedFreshTelemetry) {
728
+ if (pending.telemetry !== null && pending.telemetry !== undefined) {
729
+ cache.prime(pending.telemetry)
730
+ }
731
+ } else {
732
+ void cache.refresh()
733
+ }
734
+ }
735
+
736
+ // Run 37 (F-37-04, PROVEN LIMITATION): the step decision is passed through
737
+ // UNCHANGED. DSH records the request contextWindow exclusively from the LLM
738
+ // adapter's model metadata, and no plugin surface can cap it below the
739
+ // model's window:
740
+ // - dsh-agent-loop buildRequest reads preparedCall.context.contextWindow
741
+ // (dsh-agent-loop/lib/index.js:1079) and appends the request/context
742
+ // record at :1088 - the only writer of that record.
743
+ // - preparedCall is llm.prepareCall's return (dsh-agent-loop:1018), NOT the
744
+ // pre-step waterfall result; the pre-step decision carries only
745
+ // kind/messages (dsh-agent-loop:706-721).
746
+ // - preparedCall.context comes from resolveCallWithInfo's info.context
747
+ // (dsh-llm/lib/index.js:2315) - the adapter's declared window. The
748
+ // agent/request config's context field is never read there.
749
+ // - compaction prices its budget from ctx.llm.resolveModelInfo
750
+ // (compaction-basic:955-959), the same adapter path.
751
+ // The role's contextWindow therefore stays an advisory Roles-page setting
752
+ // (null = no cap, DEC-37-05) and the Roles page carries the limitation note;
753
+ // injecting it anywhere would be a dead field, not a cap.
754
+ return stepDecision
755
+ }
756
+
757
+ const handleSessionDisposed = (session) => {
758
+ const sessionId = sessionIdOfSession(session)
759
+ if (sessionId !== null) {
760
+ states.delete(sessionId)
761
+ activeLocalSessionIds.delete(sessionId)
762
+ }
763
+ }
764
+
765
+ return {
766
+ cache,
767
+ mapper,
768
+ handleStatus,
769
+ handleTurnStart,
770
+ handleClaimed,
771
+ handlePreStep,
772
+ handleSessionDisposed,
773
+ primeTelemetry: (snapshot, at) => cache.prime(snapshot, at),
774
+ refreshTelemetry: () => cache.refresh(),
775
+ stateFor,
776
+ pendingFor: (sessionId) => states.get(sessionId)?.pending ?? null,
777
+ // R-36-10: sessions currently sharing the local engine (the ceiling input).
778
+ activeLocalSessions: () => activeLocalSessionIds.size
779
+ }
780
+ }