@try-works/dsh-minimal-router 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js ADDED
@@ -0,0 +1,2299 @@
1
+ // @dsh-local-router/plugin — DSH host cordis plugin entry.
2
+ //
3
+ // Registers the policy API, ledger and router_route tools, and applies routing
4
+ // decisions to DSH model selection using only existing DSH APIs:
5
+ //
6
+ // agent/status(running) -> select a turn-level route before turn/start
7
+ // session/event(turn/start)-> resolve ctx.agents.get(session.id), persist turn
8
+ // agent/inbox/claimed -> select before pre-step reads modelSelection
9
+ // agent/pre-step -> write one row; deferred fallback for next step
10
+ //
11
+ // session/event turn/start itself cannot append model/selection: the Session
12
+ // append is still publishing, and a selection append would be reentrant. This
13
+ // exact limitation is recorded in packages/plugin/lib/route-application.js.
14
+ // The client slot bundle (client/index.js) is a separate web module and stays
15
+ // intact.
16
+
17
+ import fs from "node:fs"
18
+ import os from "node:os"
19
+ import { createHash } from "node:crypto"
20
+ import path from "node:path"
21
+ import { createRouterRuntime, createToolDefinitions, initialPolicy } from "./host.js"
22
+ import { concurrencyCeilingFor, createRoutingController } from "./routing.js"
23
+ import { createRouteApplication, createRouteMapper, DEFAULT_LOCAL_PROVIDERS } from "./route-application.js"
24
+ import { createEngineAdapter, ROLE_PROVIDER_IDS } from "./engine-adapter.js"
25
+ import { createCapabilitySync } from "./capability-sync.js"
26
+ import { createLocalBackend } from "./backend.js"
27
+ import { BELOW_FLOOR_REPROBE_MS, createSpeedProber, DEFAULT_OMLX_BASE_URL, SPEED_SAMPLE_TTL_MS } from "./telemetry.js"
28
+ import {
29
+ AUTH_HEADER,
30
+ createEvidenceAdapter,
31
+ createRouterRoutes,
32
+ EVIDENCE_ROUTES,
33
+ ROUTE_AUTH_LIMITATION
34
+ } from "./evidence.js"
35
+ // Run 30 (DEC-30-06): the host reads the committed build id; it does not hash at
36
+ // boot. The artifact is regenerated by scripts/build-client.mjs in lockstep with
37
+ // the client stamp.
38
+ import { buildId as committedBuildId } from "./build-id.js"
39
+ // Run 24 (DEC-24-07): bundled tool-result pruner (pure module, wired below).
40
+ import { codePointLength, createToolResultPruner, resolveBudget } from "./tool-result-pruner.js"
41
+ import {
42
+ budgetFromContext,
43
+ createSettingsStore,
44
+ DEFAULT_TOOLS,
45
+ defaultSettingsFor,
46
+ effectiveFromDocument,
47
+ l3EnabledFromMaxDepth,
48
+ loadSettingsWithSource,
49
+ maxDepthFromL3Enabled,
50
+ migrateToolSubset,
51
+ resolvePrunePlan,
52
+ resolveToolSubset,
53
+ windowTokensFromSnapshot
54
+ } from "./settings-store.js"
55
+ import { createInlineSummariser } from "./summariser.js"
56
+ import { createSettingsHandlers } from "./settings-route.js"
57
+
58
+ export { AUTH_HEADER, createEvidenceAdapter, createRouterRoutes, EVIDENCE_ROUTES, ROUTE_AUTH_LIMITATION } from "./evidence.js"
59
+
60
+ export const name = "router"
61
+ export const inject = ["tools", "agents", "llm"]
62
+
63
+ // Run 35: the restrictable global tool names, read from the live tools service
64
+ // (no scope = the global view). Null when the service cannot answer, so the
65
+ // runtime reports "unsupported" instead of guessing a list.
66
+ // Run 37 (F-37-05): the inventory a caller can actually reach is the union of the
67
+ // global registry and the caller's OWN scoped registrations. A global-only view
68
+ // omits agent-scoped tools (e.g. `subagent`), which the caller can call but the
69
+ // roster did not list. `agent` is optional; without it the global view is used.
70
+ const globalToolNames = (ctx, agent) => {
71
+ try {
72
+ if (ctx === null || typeof ctx !== "object" || typeof ctx.tools?.view !== "function") return null
73
+ const collect = (view, key) => {
74
+ if (view === null || typeof view !== "object") return []
75
+ const names = view[key] ?? view.restrictableNames
76
+ if (names instanceof Set) return [...names]
77
+ if (Array.isArray(names)) return names
78
+ return []
79
+ }
80
+ const merged = new Set([...collect(ctx.tools.view(), "knownNames")])
81
+ if (agent !== undefined && agent !== null) {
82
+ try {
83
+ for (const name of collect(ctx.tools.view(agent), "knownNames")) merged.add(name)
84
+ } catch {}
85
+ }
86
+ if (merged.size > 0) return merged
87
+ } catch {}
88
+ return null
89
+ }
90
+
91
+ // Run 35 migration safety: a plugin may register its tool after the router
92
+ // applies, so the boot view can be incomplete. The page's own known ids are real
93
+ // DSH tool names - only ids that are neither live nor page-known can be
94
+ // migrated. DEC-35-11: migration only drops such ids and never widens. Without a
95
+ // live view we cannot tell, so the document is left alone.
96
+ const migrationKnownTools = (ctx) => {
97
+ const live = globalToolNames(ctx)
98
+ if (live === null) return null
99
+ return new Set([...live, ...DEFAULT_TOOLS])
100
+ }
101
+
102
+ export function apply(ctx, config = {}) {
103
+ // R-23-01 (DEC-23-01): the policy owns the main model and the plugin cannot
104
+ // know which model a user has access to. A config that still seeds
105
+ // policy.mainModel is therefore DROPPED (the seed is stripped, not validated
106
+ // against discovery) and logged exactly once below, alongside the other stale
107
+ // transport keys. Run 36 (R-36-03): the removed scope keys are stripped the
108
+ // same way - a config file cannot re-introduce the local/remote distinction.
109
+ const policySeedSource =
110
+ config.policy !== null && typeof config.policy === "object" && !Array.isArray(config.policy)
111
+ ? config.policy
112
+ : null
113
+ const policySeed =
114
+ policySeedSource === null
115
+ ? config.policy
116
+ : { ...policySeedSource, mainModel: undefined, subagentScope: undefined, mainScope: undefined }
117
+ const runtime = createRouterRuntime(policySeed ?? initialPolicy())
118
+ const warnOnceKeys = new Set()
119
+ const warnOnce = (key, message) => {
120
+ if (warnOnceKeys.has(key)) return
121
+ warnOnceKeys.add(key)
122
+ if (typeof ctx.logger?.warn === "function") ctx.logger.warn(message)
123
+ }
124
+
125
+ // R-23-01: the config may only carry transport facts. A stale install that
126
+ // still names a provider/model is ignored (the policy owns the main model)
127
+ // and logged exactly once, never honoured.
128
+ const staleModelKeys = ["remoteProvider", "remoteModel", "remoteModels", "remoteReasoningEffort"].filter((key) => config[key] !== undefined)
129
+ if (config.policy !== null && typeof config.policy === "object" && !Array.isArray(config.policy) && config.policy.mainModel !== undefined) {
130
+ staleModelKeys.push("policy.mainModel")
131
+ }
132
+ if (staleModelKeys.length > 0 && typeof ctx.logger?.warn === "function") {
133
+ ctx.logger.warn("router: config names model identity (" + staleModelKeys.join(", ") + "); these keys are ignored because the policy owns the main model")
134
+ }
135
+ // Run 36 DEC-36-05: a profile that still seeds a scope is ignored with the
136
+ // same warn-and-drop precedent; routing is model-only.
137
+ const staleScopeKeys =
138
+ policySeedSource === null
139
+ ? []
140
+ : ["subagentScope", "mainScope"]
141
+ .filter((key) => policySeedSource[key] !== undefined)
142
+ .map((key) => "policy." + key)
143
+ if (staleScopeKeys.length > 0 && typeof ctx.logger?.warn === "function") {
144
+ ctx.logger.warn(
145
+ "router: config names scope (" + staleScopeKeys.join(", ") + "); these keys are ignored because routing is model-only"
146
+ )
147
+ }
148
+ // Durable state lives outside the profile so restarts keep credentials and history.
149
+ const dataDir =
150
+ typeof config.dataDir === "string" && config.dataDir.length > 0
151
+ ? config.dataDir
152
+ : process.env.DSH_ROUTER_DATA_DIR ?? path.join(os.homedir(), ".dsh", "storages", "dsh-local-router")
153
+ try {
154
+ fs.mkdirSync(dataDir, { recursive: true })
155
+ } catch {}
156
+ // Run 25 repair (review B2): the Router Settings document is durable. Load it
157
+ // from dataDir/settings-pages.json at boot (defaults when absent, unreadable
158
+ // or invalid) and share one store between the settings route and the pruner
159
+ // budget below, so a saved document is consumed, not a dead end.
160
+ const settingsPagesFile = path.join(dataDir, "settings-pages.json")
161
+ // Run 25 wave 2 (R-25-03): the served document carries two host-derived,
162
+ // read-only facts - the model window (largest resident context length) and,
163
+ // below, the engine catalogue. Both read live, both null until the host can
164
+ // honestly know them, so the page shows its no-telemetry / catalogue-stale
165
+ // state instead of a guessed value.
166
+ let readTelemetrySnapshot = () => null
167
+ // The engine's own model list (the LOCAL half of the served catalogue); the
168
+ // remote half is the discovery list below. Refreshed with the catalog.
169
+ let engineCatalogue = null
170
+ // The DSH catalog for the local selection provider (the configured local
171
+ // model list the router already selects from). Distinct from the engine's own
172
+ // list: a profile can configure a local model the engine adapter does not
173
+ // advertise (the live profile's flash-next), which is still selectable.
174
+ let configuredLocalCatalogue = null
175
+ // Remote models come only from runtime discovery. There is no config fallback:
176
+ // naming a model in config is the Run 23 defect the policy now owns.
177
+ let remoteModels = []
178
+ // Run 25 verifier fix: the catalogue the roles are validated against is the
179
+ // router's full model universe - engine local ids first, then the remote
180
+ // provider ids the host discovered, then the policy's explicit main-model
181
+ // mapping. Read live and de-duplicated, so whichever source answers is
182
+ // enough; null only when every source is unknown (the catalogue-stale state).
183
+ const settingsCatalogueNow = () => {
184
+ const ids = []
185
+ if (Array.isArray(engineCatalogue)) ids.push(...engineCatalogue)
186
+ if (Array.isArray(configuredLocalCatalogue)) ids.push(...configuredLocalCatalogue)
187
+ for (const entry of Array.isArray(remoteModels) ? remoteModels : []) {
188
+ if (entry !== null && typeof entry === "object" && typeof entry.model === "string") ids.push(entry.model)
189
+ }
190
+ const main = runtime.get().mainModel
191
+ if (main !== null && typeof main === "object" && typeof main.model === "string" && main.model.length > 0) {
192
+ ids.push(main.model)
193
+ }
194
+ const union = [...new Set(ids.filter((id) => typeof id === "string" && id.length > 0))]
195
+ return union.length > 0 ? union : null
196
+ }
197
+ const settingsLoad = loadSettingsWithSource(settingsPagesFile)
198
+ // Run 25 T5: a failed persist must reach the page as an error, never a
199
+ // "Saved" that only lived in memory.
200
+ const persistSettingsDocument =
201
+ config.persistSettings ??
202
+ ((document) => {
203
+ fs.mkdirSync(dataDir, { recursive: true })
204
+ fs.writeFileSync(settingsPagesFile, JSON.stringify(document, null, 2))
205
+ })
206
+ // DEC-35-11 (reverts DEC-35-07/09/10): a stored tool subset may still name ids
207
+ // this host does not have (the page used to offer code_run/list_tools, or a
208
+ // hand-edit typo). With the allowlist those stale ids are dropped and the rest
209
+ // of the saved selection is KEPT exactly - migration never widens and never
210
+ // adds skill/ask_user_question. Owner's rev-15 file (9 core + code_run +
211
+ // list_tools) migrates to exactly the 9 core. Only a list with nothing
212
+ // selectable left is switched off, because an enabled empty list is not a
213
+ // document the schema accepts. One warning names the removed ids. Rev-safe:
214
+ // the write keeps the loaded rev and only happens while the file on disk still
215
+ // carries that rev - a migration is not a document edit.
216
+ const settingsMigration = migrateToolSubset(settingsLoad.document, migrationKnownTools(ctx))
217
+ if (settingsMigration.removed.length > 0) {
218
+ const removedLabel = settingsMigration.removed.map((id) => JSON.stringify(id)).join(", ")
219
+ if (typeof ctx.logger?.warn === "function") {
220
+ ctx.logger.warn(
221
+ "router: removed " +
222
+ String(settingsMigration.removed.length) +
223
+ " unknown tool id" +
224
+ (settingsMigration.removed.length === 1 ? "" : "s") +
225
+ " from the saved tool subset: " +
226
+ removedLabel +
227
+ (settingsMigration.disabled
228
+ ? " - they name no DSH tool and nothing else is left to select, so the subset is now OFF (enabled:false); re-choose it in the Context tab"
229
+ : " - they name no DSH tool, so they are dropped and the rest of the saved selection is kept exactly")
230
+ )
231
+ }
232
+ if (settingsLoad.source === "file") {
233
+ let revSafe = true
234
+ if (config.persistSettings === undefined) {
235
+ try {
236
+ const onDisk = JSON.parse(fs.readFileSync(settingsPagesFile, "utf8"))
237
+ revSafe =
238
+ onDisk !== null &&
239
+ typeof onDisk === "object" &&
240
+ onDisk.rev === settingsLoad.document.rev
241
+ } catch {
242
+ revSafe = false
243
+ }
244
+ }
245
+ if (revSafe) {
246
+ try {
247
+ persistSettingsDocument({
248
+ context: settingsMigration.document.context,
249
+ roles: settingsMigration.document.roles,
250
+ rev: settingsMigration.document.rev
251
+ })
252
+ } catch {}
253
+ }
254
+ }
255
+ }
256
+ const settingsStore = createSettingsStore(settingsMigration.document, {
257
+ windowTokens: () => windowTokensFromSnapshot(readTelemetrySnapshot()),
258
+ catalogue: settingsCatalogueNow,
259
+ // Run 25 verifier root cause: a fresh profile has no stored document, so its
260
+ // role chain is derived from the live catalogue at first read instead of
261
+ // hard-coded ids that may not be advertised. A stored document is never
262
+ // re-derived.
263
+ useDerivedDefaults: settingsLoad.source === "default",
264
+ deriveDefaults: () => {
265
+ const liveCatalogue = settingsCatalogueNow()
266
+ if (liveCatalogue === null) return null
267
+ const main = runtime.get().mainModel
268
+ return defaultSettingsFor(liveCatalogue, {
269
+ mainModel: main !== null && typeof main === "object" && typeof main.model === "string" ? main.model : null,
270
+ localIds: [
271
+ ...(Array.isArray(engineCatalogue) ? engineCatalogue : []),
272
+ ...(Array.isArray(configuredLocalCatalogue) ? configuredLocalCatalogue : [])
273
+ ]
274
+ })
275
+ },
276
+ persist: persistSettingsDocument
277
+ })
278
+ // Run 36 (R-36-09, DEC-36-13): subagent.maxDepth is the source of truth for
279
+ // roles.l3.enabled. Read it through the same settings service the write side
280
+ // uses; unknown (no service, no row, no value) leaves the stored mirror alone.
281
+ const settingsServiceNow = () => {
282
+ let service = null
283
+ try {
284
+ service = typeof ctx.get === "function" ? ctx.get("settings") : null
285
+ } catch {
286
+ service = null
287
+ }
288
+ if (service === null || service === undefined) {
289
+ try {
290
+ service = ctx.settings ?? null
291
+ } catch {
292
+ service = null
293
+ }
294
+ }
295
+ return service
296
+ }
297
+ const readMaxDepth = async () => {
298
+ const service = settingsServiceNow()
299
+ if (service === null || service === undefined || typeof service.describe !== "function") return undefined
300
+ try {
301
+ const described = await Promise.resolve(service.describe())
302
+ const rows = Array.isArray(described)
303
+ ? described
304
+ : Array.isArray(described?.namespaces)
305
+ ? described.namespaces
306
+ : []
307
+ const row = rows.find((entry) => entry !== null && typeof entry === "object" && entry.ns === "subagent")
308
+ if (row === undefined) return undefined
309
+ // The host settings service returns { ns, revision, value, base, user }:
310
+ // value is the effective config, base/user the inherited layers.
311
+ const depth = row.value?.maxDepth ?? row.user?.maxDepth ?? row.base?.maxDepth
312
+ return Number.isInteger(depth) && depth >= 0 ? depth : undefined
313
+ } catch {
314
+ return undefined
315
+ }
316
+ }
317
+ const mirrorL3FromDepth = (maxDepth) => {
318
+ if (maxDepth === undefined) return false
319
+ return settingsStore.mirrorL3Enabled(l3EnabledFromMaxDepth(maxDepth))
320
+ }
321
+ // Keep routing in step with DSH from boot, not only after the Roles page loads.
322
+ void readMaxDepth().then((maxDepth) => mirrorL3FromDepth(maxDepth))
323
+ const connectionFile = path.join(dataDir, "connection.json")
324
+ const readPersistedConnection = () => {
325
+ try {
326
+ const parsed = JSON.parse(fs.readFileSync(connectionFile, "utf8"))
327
+ if (parsed !== null && typeof parsed === "object") {
328
+ return {
329
+ endpoint: typeof parsed.endpoint === "string" ? parsed.endpoint : null,
330
+ apiKey: typeof parsed.apiKey === "string" ? parsed.apiKey : null
331
+ }
332
+ }
333
+ } catch {}
334
+ return null
335
+ }
336
+ const persistedConnection = readPersistedConnection()
337
+ // Routing defaults OFF and never selects a model until the user enables it.
338
+ if (config.enabled === true) runtime.setEnabled(true)
339
+ const localProvider =
340
+ config.localProvider ?? process.env.DSH_ROUTER_LOCAL_PROVIDER ?? "omlx"
341
+ // The provider a local decision actually selects. The engine adapter owns that
342
+ // transport and its catalog comes from the engine, not from DSH config.
343
+ // A profile that still pins a local provider keeps that route; otherwise the
344
+ // plugin-owned engine provider is the default transport (no config needed).
345
+ const localSelectionProvider =
346
+ config.localSelectionProvider ??
347
+ (config.localProvider === undefined && process.env.DSH_ROUTER_LOCAL_PROVIDER === undefined ? "engine" : localProvider)
348
+ const omlxBaseUrl =
349
+ config.oMLXBaseUrl ??
350
+ process.env.DSH_ROUTER_OMLX_URL ??
351
+ process.env.OMLX_BASE_URL ??
352
+ DEFAULT_OMLX_BASE_URL
353
+ const omlxApiKey =
354
+ config.oMLXApiKey ?? process.env.DSH_ROUTER_OMLX_API_KEY ?? process.env.OMLX_API_KEY
355
+ const backendKind = config.backendKind ?? "omlx"
356
+ const normalizeEndpoint = (value) =>
357
+ String(value)
358
+ .trim()
359
+ .replace(/\/+$/u, "")
360
+ .replace(/\/admin\/api$/u, "")
361
+ .replace(/\/admin$/u, "")
362
+ const envEndpoint =
363
+ config.oMLXBaseUrl ?? process.env.DSH_ROUTER_OMLX_URL ?? process.env.OMLX_BASE_URL
364
+ const envApiKey = config.oMLXApiKey ?? process.env.DSH_ROUTER_OMLX_API_KEY ?? process.env.OMLX_API_KEY
365
+ // The local engine keeps its own credential; use it when nothing more
366
+ // specific (config, env, or a saved connection) provides one, so a fresh
367
+ // install connects without re-entering the key.
368
+ const omlxSettingsKey = () => {
369
+ try {
370
+ const parsed = JSON.parse(fs.readFileSync(path.join(os.homedir(), ".omlx", "settings.json"), "utf8"))
371
+ const key = parsed?.auth?.api_key
372
+ return typeof key === "string" && key.length > 0 ? key : ""
373
+ } catch {
374
+ return ""
375
+ }
376
+ }
377
+ let connection = {
378
+ endpoint: normalizeEndpoint(
379
+ envEndpoint !== undefined && envEndpoint !== null
380
+ ? envEndpoint
381
+ : persistedConnection !== null && persistedConnection.endpoint !== null
382
+ ? persistedConnection.endpoint
383
+ : omlxBaseUrl
384
+ ),
385
+ apiKey:
386
+ typeof envApiKey === "string" && envApiKey.length > 0
387
+ ? envApiKey
388
+ : persistedConnection !== null && persistedConnection.apiKey !== null && persistedConnection.apiKey.length > 0
389
+ ? persistedConnection.apiKey
390
+ : omlxSettingsKey()
391
+ }
392
+ const persistConnection = () => {
393
+ try {
394
+ fs.writeFileSync(connectionFile, JSON.stringify({ endpoint: connection.endpoint, apiKey: connection.apiKey }), {
395
+ mode: 0o600
396
+ })
397
+ // mode only applies on creation; tighten pre-existing files too.
398
+ try {
399
+ fs.chmodSync(connectionFile, 0o600)
400
+ } catch {}
401
+ } catch {}
402
+ }
403
+ // Per-session auto-routing: sessionId -> { enabled, mainModel }. Routing is
404
+ // OFF for every session until the user enables it in that session. A profile
405
+ // may pre-enable a session list for tests/CI via config.routedSessions.
406
+ const sessionRouting = new Map()
407
+ // F-37-51: the recent-session rows the Overview lists, refreshed by the host.
408
+ let recentSessionsCache = []
409
+ const sessionRoutingFile = path.join(dataDir, "session-routing.json")
410
+ const persistSessionRouting = () => {
411
+ try {
412
+ const entries = {}
413
+ for (const [id, value] of sessionRouting.entries()) entries[id] = value
414
+ fs.writeFileSync(sessionRoutingFile, JSON.stringify(entries))
415
+ } catch {}
416
+ }
417
+ // DEC-36-24 (STEP 3): the DSH native picker is a session-local override for L1.
418
+ // Capture the session's current picked model into the durable session entry so
419
+ // it survives a restart; the decision itself reads the model live at each step.
420
+ const captureSessionMainModel = (sessionId, agent) => {
421
+ try {
422
+ const current = typeof agent?.model?.current === "function" ? agent.model.current() : null
423
+ const model = current !== null && typeof current === "object" && !Array.isArray(current) ? current.model : null
424
+ if (typeof model !== "string" || model.length === 0) return
425
+ const entry = sessionRouting.get(sessionId)
426
+ if (entry !== undefined && entry.enabled === true && entry.mainModel !== model) {
427
+ sessionRouting.set(sessionId, { enabled: true, mainModel: model })
428
+ persistSessionRouting()
429
+ }
430
+ } catch {}
431
+ }
432
+ try {
433
+ const raw = JSON.parse(fs.readFileSync(sessionRoutingFile, "utf8"))
434
+ if (raw !== null && typeof raw === "object" && !Array.isArray(raw)) {
435
+ for (const [id, value] of Object.entries(raw)) {
436
+ if (typeof id !== "string" || value === null || typeof value !== "object") continue
437
+ sessionRouting.set(id, {
438
+ enabled: value.enabled === true,
439
+ mainModel: typeof value.mainModel === "string" ? value.mainModel : null
440
+ })
441
+ }
442
+ }
443
+ } catch {}
444
+ if (Array.isArray(config.routedSessions)) {
445
+ for (const sessionId of config.routedSessions) {
446
+ if (typeof sessionId === "string" && sessionId.length > 0) {
447
+ sessionRouting.set(sessionId, { enabled: true, mainModel: null })
448
+ }
449
+ }
450
+ }
451
+ // A masked hint (••••) is never a real secret; treat it as absent.
452
+ const effectiveApiKey = () =>
453
+ connection.apiKey.length > 0 && !/^•+$/u.test(connection.apiKey) ? connection.apiKey : ""
454
+ // Run 36 (R-36-07, DEC-36-06/07): one per-process speed sample store behind the
455
+ // floor gate. Probes run in background sweeps only - at boot/after the first
456
+ // catalogue read, on catalogue change, and every 10 minutes for models that
457
+ // stay below floor - never inside a request path. Live traffic refreshes a
458
+ // sample through samples.measured(); a route only ever reads sampleFor().
459
+ // A test may inject config.speedProber to observe the wiring without an engine.
460
+ const localCatalogueIds = () => {
461
+ const ids = []
462
+ if (Array.isArray(engineCatalogue)) ids.push(...engineCatalogue)
463
+ else if (Array.isArray(configuredLocalCatalogue)) ids.push(...configuredLocalCatalogue)
464
+ // Run 37 (F-37-02): when neither catalogue source answered, the telemetry
465
+ // snapshot's residents are the only local ids the host has seen. Use the RAW
466
+ // residents recorded before filtering - the cached snapshot's residents are
467
+ // filtered against catalogModels, which is empty when the DSH catalogue read
468
+ // failed, so the cached view would be empty too.
469
+ if (ids.length === 0) {
470
+ if (Array.isArray(lastResidentModels) && lastResidentModels.length > 0) {
471
+ ids.push(...lastResidentModels)
472
+ } else {
473
+ try {
474
+ const snapshot = readTelemetrySnapshot()
475
+ const residents =
476
+ Array.isArray(snapshot?.residentModels)
477
+ ? snapshot.residentModels
478
+ : Array.isArray(snapshot?.residents)
479
+ ? snapshot.residents
480
+ : []
481
+ ids.push(...residents)
482
+ } catch {}
483
+ }
484
+ }
485
+ return [...new Set(ids.filter((id) => typeof id === "string" && id.length > 0))]
486
+ }
487
+ let speedProberInstance =
488
+ config.speedProber !== undefined && config.speedProber !== null ? config.speedProber : null
489
+ const speedProber = () => {
490
+ if (speedProberInstance !== null) return speedProberInstance
491
+ speedProberInstance = createSpeedProber({
492
+ baseUrl: connection.endpoint,
493
+ apiKey: effectiveApiKey(),
494
+ now: config.now
495
+ })
496
+ return speedProberInstance
497
+ }
498
+ let lastCatalogueSweep = null
499
+ const sweepLocalCatalogue = () => {
500
+ const ids = localCatalogueIds()
501
+ const signature = ids.join("\n")
502
+ if (signature === lastCatalogueSweep) return
503
+ lastCatalogueSweep = signature
504
+ if (ids.length === 0) return
505
+ try {
506
+ void speedProber().sweep(ids)
507
+ } catch {}
508
+ // DEC-37-12: the first reading after a boot can be measured while the engine is
509
+ // already serving a turn, which understates the decode speed and can flip a
510
+ // decision to the remote fallback (live: a probe read 9.3 tps while the same
511
+ // model read 109.6 tps idle). Re-probe only the models that landed below their
512
+ // floor, a moment later, so a contended first reading self-corrects in seconds
513
+ // instead of waiting for the next two-minute cycle. The never-lower rule keeps
514
+ // the better reading.
515
+ try {
516
+ const correction = setTimeout(() => {
517
+ try {
518
+ void speedProber().reprobeBelowFloor(ids, floorForSpeedModel, config.now ? config.now() : new Date())
519
+ } catch {}
520
+ }, Number.isFinite(config.speedCorrectionMs) ? config.speedCorrectionMs : 2_000)
521
+ correction.unref?.()
522
+ if (typeof ctx.effect === "function") {
523
+ ctx.effect(() => () => clearTimeout(correction), "router.speedCorrection()")
524
+ }
525
+ } catch {}
526
+ // DEC-37-10 (Owner): the boot snapshot's observedTps is the engine's LIFETIME
527
+ // average, not a measurement, so it is no longer seeded into the sample store.
528
+ // Fresh observations come from the adapter's per-request measurement and from
529
+ // the probe sweep above; a model stays "unknown" until one of those lands.
530
+ }
531
+ // The per-model floor for the re-probe sweep: a model is below its floor when
532
+ // any configured role chain that uses it has a higher floor than its reading.
533
+ const floorForSpeedModel = (modelId) => {
534
+ const floors = []
535
+ try {
536
+ const policyFloor = runtime.get().floorTps
537
+ if (Number.isFinite(policyFloor)) floors.push(policyFloor)
538
+ } catch {}
539
+ try {
540
+ const roles = settingsStore.get().roles
541
+ for (const role of ["l2", "l3", "advisor"]) {
542
+ const entry = roles?.[role]
543
+ if (entry === null || typeof entry !== "object") continue
544
+ const chain = [entry.model, ...(Array.isArray(entry.fallbacks) ? entry.fallbacks : [])]
545
+ if (chain.includes(modelId) && Number.isFinite(entry.floorTps)) floors.push(entry.floorTps)
546
+ }
547
+ } catch {}
548
+ return floors.length === 0 ? 0 : Math.max(...floors)
549
+ }
550
+ const buildLocalRead = () =>
551
+ createLocalBackend({
552
+ kind: backendKind,
553
+ baseUrl: connection.endpoint,
554
+ apiKey: effectiveApiKey(),
555
+ timeoutMs: config.timeoutMs,
556
+ retries: config.retries
557
+ }).read
558
+ const backend =
559
+ config.backend ??
560
+ config.telemetry ??
561
+ { kind: backendKind, read: (...args) => buildLocalRead()(...args) }
562
+ // Run 37 (F-37-02): the UNFILTERED resident ids from the last telemetry read.
563
+ // The cached snapshot filters residents against catalogModels, which is empty
564
+ // when the DSH catalogue read failed, so the prober needs this raw view.
565
+ let lastResidentModels = []
566
+ const readTelemetry = typeof backend.read === "function" ? backend.read : backend
567
+ // The router must only pick local models the DSH provider actually exposes.
568
+ // oMLX serves more models than the profile configures; selecting one of those
569
+ // leaves the model switch pending and the turn never runs.
570
+ const catalogModels = new Set()
571
+ // Capability facts per engine model (context window, input modalities) for the
572
+ // Models page. Refreshed with the catalog, not guessed by the UI.
573
+ const engineModelInfo = {}
574
+ // Unknown until the first successful read; "known" with an empty set means the
575
+ // local provider is gone (deleted in DSH), so no local model may be selected.
576
+ let catalogKnown = false
577
+ // Whether DSH itself owns the configured local route (a pinned profile provider).
578
+ let dshLocalPresent = config.localProvider !== undefined || process.env.DSH_ROUTER_LOCAL_PROVIDER !== undefined
579
+ // Engine model load/unload changes the served set; refresh capabilities then.
580
+ const syncCapabilities = createCapabilitySync({
581
+ snapshotOf: () =>
582
+ application !== null && application.cache !== null && typeof application.cache.snapshot === "function"
583
+ ? application.cache.snapshot()
584
+ : null,
585
+ invalidate: () => {
586
+ if (typeof engineAdapter.invalidateCapabilities === "function") engineAdapter.invalidateCapabilities()
587
+ },
588
+ refresh: () => void refreshCatalog()
589
+ })
590
+ const refreshCatalog = async () => {
591
+ const llm = ctx.llm
592
+ if (llm === undefined || llm === null || typeof llm.listModels !== "function") {
593
+ warnOnce("catalog-empty", "router: local catalogue is empty (no llm.listModels on the host); the boot sweep falls back to the telemetry snapshot residents")
594
+ return
595
+ }
596
+ let emptyReason = null
597
+ try {
598
+ if (typeof llm.listProviders === "function") {
599
+ const providers = await llm.listProviders()
600
+ dshLocalPresent = Array.isArray(providers) && providers.some((entry) => (entry?.id ?? entry) === localSelectionProvider)
601
+ if (Array.isArray(providers) && !providers.some((entry) => (entry?.id ?? entry) === localSelectionProvider) && !(localSelectionProvider === "engine" && engineRegistered)) {
602
+ catalogModels.clear()
603
+ catalogKnown = true
604
+ emptyReason = "provider " + JSON.stringify(localSelectionProvider) + " is absent and the engine adapter is not registered"
605
+ return
606
+ }
607
+ }
608
+ const models = await llm.listModels(localSelectionProvider)
609
+ if (!Array.isArray(models)) {
610
+ emptyReason = "llm.listModels(" + JSON.stringify(localSelectionProvider) + ") returned no array"
611
+ return
612
+ }
613
+ catalogModels.clear()
614
+ for (const model of models) {
615
+ if (typeof model?.id === "string" && model.id.length > 0) catalogModels.add(model.id)
616
+ }
617
+ catalogKnown = true
618
+ // Run 25 verifier fix: the configured local catalog is a catalogue source
619
+ // in its own right (a local model the engine does not advertise).
620
+ const configuredIds = models
621
+ .map((model) => (typeof model === "string" ? model : model?.id))
622
+ .filter((id) => typeof id === "string" && id.length > 0)
623
+ configuredLocalCatalogue = configuredIds.length > 0 ? [...new Set(configuredIds)] : null
624
+ if (localSelectionProvider === "engine" && engineRegistered) {
625
+ try {
626
+ const engineModels = await engineAdapter.listModels("engine")
627
+ if (Array.isArray(engineModels)) {
628
+ for (const key of Object.keys(engineModelInfo)) delete engineModelInfo[key]
629
+ for (const entry of engineModels) {
630
+ if (entry === null || typeof entry !== "object" || typeof entry.id !== "string") continue
631
+ engineModelInfo[entry.id] = {
632
+ ...Number.isFinite(entry.context?.contextWindow)
633
+ ? { contextWindow: entry.context.contextWindow }
634
+ : {},
635
+ ...Array.isArray(entry.inputModalities) ? { inputModalities: entry.inputModalities } : {}
636
+ }
637
+ }
638
+ }
639
+ } catch {}
640
+ }
641
+ // Run 25 (BLK-2 + verifier): the engine's own model list is the LOCAL half
642
+ // of the served catalogue (see settingsCatalogueNow); the remote half is
643
+ // the discovery list. An empty or failed engine read is null for that
644
+ // half only - the union still serves whatever the other sources know.
645
+ try {
646
+ const engineModels = await engineAdapter.listModels(localSelectionProvider)
647
+ const ids = Array.isArray(engineModels)
648
+ ? engineModels
649
+ .map((entry) => (typeof entry === "string" ? entry : entry?.id))
650
+ .filter((id) => typeof id === "string" && id.length > 0)
651
+ : []
652
+ engineCatalogue = ids.length > 0 ? [...new Set(ids)] : null
653
+ } catch {
654
+ engineCatalogue = null
655
+ }
656
+ } catch (error) {
657
+ // A transient provider error keeps the previous catalog state.
658
+ emptyReason = "the catalogue read threw: " + (error instanceof Error ? error.message : String(error))
659
+ }
660
+ if (!Array.isArray(engineCatalogue) && !Array.isArray(configuredLocalCatalogue)) {
661
+ warnOnce(
662
+ "catalog-empty",
663
+ "router: local catalogue is empty (" + (emptyReason ?? "engine adapter and DSH model list both returned no ids") + "); the boot sweep falls back to the telemetry snapshot residents"
664
+ )
665
+ }
666
+ // R-36-07 / F-37-02: the sweep must run on EVERY catalogue read, including the
667
+ // early-return paths above - an empty DSH catalogue does not mean there is no
668
+ // local model to probe (the telemetry snapshot's residents supply ids, and the
669
+ // engine's in-process adapter may answer even when the DSH list does not).
670
+ // sweepLocalCatalogue() is idempotent via its signature guard.
671
+ sweepLocalCatalogue()
672
+ }
673
+ const filteredTelemetry = async (...args) => {
674
+ const snapshot = await readTelemetry(...args)
675
+ if (snapshot !== null && typeof snapshot === "object" && Array.isArray(snapshot.residents)) {
676
+ lastResidentModels = snapshot.residents.filter((id) => typeof id === "string" && id.length > 0)
677
+ }
678
+ if (!catalogKnown || snapshot === null || typeof snapshot !== "object") return snapshot
679
+ const residents = Array.isArray(snapshot.residents)
680
+ ? snapshot.residents.filter((id) => catalogModels.has(id))
681
+ : snapshot.residents
682
+ // DEC-37-10 (Owner): the engine's observedTps is a LIFETIME aggregate and must
683
+ // never enter the sample store as a measurement. Fresh observations come from
684
+ // the adapter's per-request measurement (onRequestSpeed) and from the probe.
685
+ // The previous feed of snapshot.observedTps is deliberately gone.
686
+ // DEC-37-09 (Owner): the probe reading is the router's speed evidence; the
687
+ // engine's own average lags and can stay wrong for minutes. When a fresh probe
688
+ // sample exists for the preferred local model, it REPLACES the engine's
689
+ // observedTps in the snapshot, so every reader (gate, ledger, UI) sees the
690
+ // probe speed rather than the outdated engine average.
691
+ const probed = (modelId) => {
692
+ if (typeof modelId !== "string" || modelId.length === 0) return null
693
+ try {
694
+ const sample = speedProber().sampleFor(modelId)
695
+ if (
696
+ sample !== null &&
697
+ typeof sample === "object" &&
698
+ sample.source === "probe" &&
699
+ sample.expired !== true &&
700
+ typeof sample.tps === "number" &&
701
+ Number.isFinite(sample.tps)
702
+ ) {
703
+ return sample.tps
704
+ }
705
+ } catch {}
706
+ return null
707
+ }
708
+ const probedTps = probed(snapshot.preferredModel)
709
+ if (probedTps !== null) {
710
+ return { ...snapshot, residents, observedTps: probedTps, observedTpsSource: "probe" }
711
+ }
712
+ return { ...snapshot, residents }
713
+ }
714
+ // Run 37 (F-37-12): join the engine's per-request observation onto the ledger
715
+ // row of the session that issued the request. The claimed/pre-step path knows
716
+ // sessionId + requestId, so the host keeps a per-session map of the LATEST
717
+ // request key and the adapter's onRequestObserved callback consumes and clears
718
+ // it (a session has at most one in-flight engine request). Only when no key is
719
+ // set does the host fall back to model + nearest-time matching; the correlation
720
+ // actually used is recorded on the persisted observation so an unattributable
721
+ // case is visible, never guessed into a row.
722
+ const sessionIdOfAgent = (agent) => {
723
+ const id = agent?.id ?? agent?.session?.id ?? agent?.session?.header?.id
724
+ return typeof id === "string" ? id : null
725
+ }
726
+ const nowMs = () => {
727
+ const value = config.now ? config.now() : new Date()
728
+ return value instanceof Date ? value.getTime() : Number(value)
729
+ }
730
+ const requestKeysBySession = new Map() // sessionId -> { requestId, model, issuedAt }
731
+ const observationsFile = path.join(dataDir, "request-observations.jsonl")
732
+ const markRequestKey = (sessionId, requestId, model) => {
733
+ if (typeof sessionId !== "string" || sessionId.length === 0) return
734
+ if (typeof requestId !== "string" || requestId.length === 0) return
735
+ requestKeysBySession.set(sessionId, {
736
+ requestId,
737
+ model: typeof model === "string" && model.length > 0 ? model : null,
738
+ issuedAt: nowMs()
739
+ })
740
+ }
741
+ const ledgerRows = () => {
742
+ const listed = runtime.list()
743
+ return Array.isArray(listed?.rows) ? listed.rows : []
744
+ }
745
+ const attachObservationToRow = (row, observation) => {
746
+ if (row === null || typeof row !== "object") return false
747
+ if (typeof observation.engineRequestId === "string" && observation.engineRequestId.length > 0) {
748
+ row.omlxRequestId = observation.engineRequestId
749
+ }
750
+ if (typeof observation.promptTokens === "number" && Number.isFinite(observation.promptTokens)) {
751
+ row.contextTokens = observation.promptTokens
752
+ }
753
+ return true
754
+ }
755
+ const persistObservation = (observation) => {
756
+ try {
757
+ fs.mkdirSync(dataDir, { recursive: true })
758
+ fs.appendFileSync(observationsFile, JSON.stringify(observation) + "\n")
759
+ } catch {}
760
+ }
761
+ const correlateObservation = (model, observation) => {
762
+ // Primary: the per-session request key whose model matches, oldest first
763
+ // (FIFO so two sessions on one model keep their own observations).
764
+ let winner = null
765
+ for (const [sessionId, entry] of requestKeysBySession) {
766
+ if (entry.model !== model) continue
767
+ if (winner === null || entry.issuedAt < winner.issuedAt) winner = { sessionId, ...entry }
768
+ }
769
+ if (winner !== null) {
770
+ requestKeysBySession.delete(winner.sessionId)
771
+ return { correlation: "key", sessionId: winner.sessionId, requestId: winner.requestId, row: null }
772
+ }
773
+ // Fallback: the most recent unjoined ledger row for the model (nearest time).
774
+ const unjoined = ledgerRows()
775
+ .filter(
776
+ (row) =>
777
+ row !== null &&
778
+ typeof row === "object" &&
779
+ row.model === model &&
780
+ (row.omlxRequestId === null || row.omlxRequestId === undefined)
781
+ )
782
+ .sort((a, b) => {
783
+ const aAt = typeof a.at === "string" ? Date.parse(a.at) : Number.NaN
784
+ const bAt = typeof b.at === "string" ? Date.parse(b.at) : Number.NaN
785
+ return (Number.isFinite(bAt) ? bAt : 0) - (Number.isFinite(aAt) ? aAt : 0)
786
+ })
787
+ const row = unjoined[0] ?? null
788
+ if (row !== null) {
789
+ return {
790
+ correlation: "fallback",
791
+ sessionId: typeof row.agentId === "string" ? row.agentId : null,
792
+ requestId: typeof row.requestId === "string" ? row.requestId : null,
793
+ row
794
+ }
795
+ }
796
+ return { correlation: "none", sessionId: null, requestId: null, row: null }
797
+ }
798
+ const handleRequestObserved = (model, observation) => {
799
+ const result = correlateObservation(model, observation)
800
+ const row =
801
+ result.row ??
802
+ (result.correlation === "key" && result.requestId !== null
803
+ ? ledgerRows().find((entry) => entry !== null && typeof entry === "object" && entry.requestId === result.requestId) ?? null
804
+ : null)
805
+ attachObservationToRow(row, observation)
806
+ persistObservation({
807
+ ...observation,
808
+ model,
809
+ observedAt: new Date(nowMs()).toISOString(),
810
+ correlation: result.correlation,
811
+ sessionId: result.sessionId,
812
+ requestId: result.requestId,
813
+ rowId: row !== null && typeof row === "object" && typeof row.id === "string" ? row.id : null
814
+ })
815
+ }
816
+ // F-37-12: read-time join source for the Activity page - the newest observation
817
+ // for a requestId. Cached on the file's mtime so a read does not re-parse it.
818
+ let observationCache = { at: -1, byRequest: new Map() }
819
+ const observationsForRequest = (requestId) => {
820
+ if (typeof requestId !== "string" || requestId.length === 0) return null
821
+ try {
822
+ const stat = fs.statSync(observationsFile)
823
+ if (stat.mtimeMs !== observationCache.at) {
824
+ const byRequest = new Map()
825
+ for (const line of fs.readFileSync(observationsFile, "utf8").split("\n")) {
826
+ if (line.length === 0) continue
827
+ let entry
828
+ try {
829
+ entry = JSON.parse(line)
830
+ } catch {
831
+ continue
832
+ }
833
+ if (entry !== null && typeof entry === "object" && typeof entry.requestId === "string") {
834
+ byRequest.set(entry.requestId, entry)
835
+ }
836
+ }
837
+ observationCache = { at: stat.mtimeMs, byRequest }
838
+ }
839
+ return observationCache.byRequest.get(requestId) ?? null
840
+ } catch {
841
+ return null
842
+ }
843
+ }
844
+ const engineAdapter = createEngineAdapter({
845
+ // DEC-37-11: a role-scoped provider route returns the role's context window.
846
+ roleWindowFor: (role) => {
847
+ const entry = settingsStore.get().roles?.[role]
848
+ return entry !== null && typeof entry === "object" && Number.isFinite(entry.contextWindow) ? entry.contextWindow : null
849
+ },
850
+ // DEC-37-10: every proxied request is a fresh speed observation.
851
+ onRequestSpeed: (modelId, tps) => {
852
+ try {
853
+ speedProber().samples.measured(modelId, tps)
854
+ } catch {}
855
+ },
856
+ // DEC-37-12: every proxied request also forwards its engine id and token/timing
857
+ // usage; the host joins it onto the issuing session's ledger row.
858
+ onRequestObserved: handleRequestObserved,
859
+ getConnection: () => connection,
860
+ // Injectable transport so a test can serve the engine surfaces without a
861
+ // live engine; production leaves it undefined and uses global fetch.
862
+ fetchImpl: config.fetchImpl,
863
+ // Per-model capability overrides for engines that report incomplete metadata.
864
+ modelCapabilities:
865
+ config.modelCapabilities !== null && typeof config.modelCapabilities === "object"
866
+ ? config.modelCapabilities
867
+ : {}
868
+ })
869
+ // Own only the engine route; a pinned profile provider stays DSH-owned.
870
+ let engineRegistered = false
871
+ if (typeof ctx.llm?.registerAdapter === "function") {
872
+ // Register the engine transport under its own id and the legacy local id.
873
+ // Persisted subagent model selections may still name provider "omlx", and
874
+ // without an adapter those turns fail with "no adapter registered".
875
+ try {
876
+ ctx.llm.registerAdapter(["engine", "omlx", ...ROLE_PROVIDER_IDS], engineAdapter)
877
+ engineRegistered = true
878
+ } catch {
879
+ // A real omlx provider may already exist; keep the engine route alone.
880
+ try {
881
+ ctx.llm.registerAdapter(["engine", ...ROLE_PROVIDER_IDS], engineAdapter)
882
+ engineRegistered = true
883
+ } catch (error) {
884
+ // A second plugin instance may already own the route; never crash the host.
885
+ if (typeof ctx.logger?.warn === "function") {
886
+ ctx.logger.warn("router: engine provider not registered: " + (error?.message ?? String(error)))
887
+ }
888
+ }
889
+ }
890
+ }
891
+ // Registered before the first catalog read so "engine" is a known provider.
892
+ Promise.resolve().then(() => void refreshCatalog())
893
+ const mapper = createRouteMapper({
894
+ // DEC-37-11: role routes carry the role's context window.
895
+ // DEC-37-11 scope: workers (l2) and assistants (l3) - the child roles the
896
+ // window exists for. L1 keeps the plain engine route so the main session's
897
+ // behaviour is unchanged, and the Advisor's window is null (no cap, DEC-37-05).
898
+ roleProviderFor: (role) => {
899
+ if (role !== "l2" && role !== "l3") return null
900
+ const entry = settingsStore.get().roles?.[role]
901
+ return entry !== null && typeof entry === "object" && Number.isFinite(entry.contextWindow) && entry.contextWindow > 0
902
+ ? "engine-" + role
903
+ : null
904
+ },
905
+ localProvider,
906
+ localSelectionProvider,
907
+ localAvailable: () => dshLocalPresent || (localSelectionProvider === "engine" && engineRegistered),
908
+ localProviders: config.localProviders
909
+ })
910
+ // R-36-10 (DEC-36-19): the load facts every decision needs. The ceiling is the
911
+ // engine's scheduler setting carried by the telemetry snapshot (the Routing
912
+ // page's "Concurrent" value; the oMLX global settings document), else the
913
+ // documented default. poolTps is the measured pool throughput; the active
914
+ // session count comes from the DSH turn lifecycle in route-application.
915
+ const applicationRef = { current: null }
916
+ const loadFactsNow = () => {
917
+ const snapshot = readTelemetrySnapshot()
918
+ const record = snapshot !== null && typeof snapshot === "object" ? snapshot : null
919
+ const observedTps =
920
+ record !== null && typeof record.observedTps === "number" && Number.isFinite(record.observedTps)
921
+ ? record.observedTps
922
+ : null
923
+ const active =
924
+ applicationRef.current !== null && typeof applicationRef.current.activeLocalSessions === "function"
925
+ ? applicationRef.current.activeLocalSessions()
926
+ : 0
927
+ return {
928
+ concurrencyCeiling: concurrencyCeilingFor(record === null ? null : record.engineMax),
929
+ poolTps: observedTps,
930
+ activeLocalSessions: active
931
+ }
932
+ }
933
+ const application = createRouteApplication({
934
+ runtime,
935
+ readPolicy: runtime.get,
936
+ readTelemetry: filteredTelemetry,
937
+ fallbackPolicy: initialPolicy(),
938
+ mapper,
939
+ resolveAgent: (sessionId) => ctx.agents.get(sessionId),
940
+ now: config.now,
941
+ newId: config.newId,
942
+ logger: ctx.logger,
943
+ cacheMaxAgeMs: config.cacheMaxAgeMs,
944
+ isRouted: (sessionId, agent) => {
945
+ const entry = sessionRouting.get(sessionId)
946
+ if (entry?.enabled === true) {
947
+ captureSessionMainModel(sessionId, agent)
948
+ return true
949
+ }
950
+ // A subagent inherits its parent session's routing choice (F-36-11). To
951
+ // make inheritance transitive - a depth-2 assistant must inherit from its
952
+ // depth-1 worker, which itself only inherited and has no direct entry -
953
+ // materialize the child's own entry so ITS descendants inherit too.
954
+ const parent = agent?.session?.header?.parentSession
955
+ if (typeof parent === "string" && sessionRouting.get(parent)?.enabled === true) {
956
+ sessionRouting.set(sessionId, { enabled: true, mainModel: null })
957
+ persistSessionRouting()
958
+ captureSessionMainModel(sessionId, agent)
959
+ return true
960
+ }
961
+ return false
962
+ },
963
+ // Run 25 (DEC-25-10): the Roles document is read live at every decision and
964
+ // a role model id is resolved against the catalogues the host already keeps.
965
+ readRoles: () => settingsStore.get().roles,
966
+ resolveRoleModel: (modelId) => resolveRoleModel(modelId),
967
+ // R-36-07: the floor gate's per-model speed source. decide() reads it
968
+ // synchronously; the host never probes inside a request path.
969
+ speedFor: (modelId) => speedProber().sampleFor(modelId),
970
+ // R-36-10: concurrency ceiling, pool throughput and the active local
971
+ // session count, read at decision time (never snapshotted at boot).
972
+ readLoad: loadFactsNow
973
+ })
974
+ applicationRef.current = application
975
+ if (config.telemetrySnapshot !== undefined) {
976
+ application.primeTelemetry(config.telemetrySnapshot)
977
+ }
978
+ // The settings route is synchronous, so it reads the cached snapshot the
979
+ // routing cache already holds; refreshTelemetry keeps it current.
980
+ readTelemetrySnapshot = () =>
981
+ typeof application.cache?.snapshot === "function" ? application.cache.snapshot() : null
982
+
983
+ // Ledger history: JSONL under ledgerDir (defaults to the plugin data dir).
984
+ let ledgerDir =
985
+ typeof config.ledgerDir === "string" && config.ledgerDir.length > 0 ? config.ledgerDir : path.join(dataDir, "ledger")
986
+ let ledgerFile = path.join(ledgerDir, "ledger.jsonl")
987
+ const ensureLedgerDir = () => {
988
+ try {
989
+ fs.mkdirSync(ledgerDir, { recursive: true })
990
+ } catch {}
991
+ }
992
+ const baseRecord = runtime.record
993
+ const appendLedgerRow = (row) => {
994
+ try {
995
+ ensureLedgerDir()
996
+ fs.appendFileSync(ledgerFile, JSON.stringify(row) + "\n")
997
+ } catch {}
998
+ }
999
+ runtime.record = (row) => {
1000
+ const result = baseRecord(row)
1001
+ if (result !== null && typeof result === "object" && result.row !== undefined) appendLedgerRow(result.row)
1002
+ return result
1003
+ }
1004
+ const loadLedgerRows = () => {
1005
+ let text
1006
+ try {
1007
+ text = fs.readFileSync(ledgerFile, "utf8")
1008
+ } catch {
1009
+ return
1010
+ }
1011
+ const loaded = []
1012
+ for (const line of text.split("\n")) {
1013
+ if (line.trim().length === 0) continue
1014
+ try {
1015
+ const row = JSON.parse(line)
1016
+ if (row !== null && typeof row === "object") loaded.push(row)
1017
+ else if (typeof ctx.logger?.warn === "function") ctx.logger.warn("router: dropped ledger line (not a row object)")
1018
+ } catch {
1019
+ if (typeof ctx.logger?.warn === "function") ctx.logger.warn("router: dropped ledger line (invalid JSON)")
1020
+ }
1021
+ }
1022
+ const existing = new Set(
1023
+ (runtime.list().rows ?? []).map((row) => (row !== null && typeof row === "object" ? row.id : undefined))
1024
+ )
1025
+ // Run 36 (DEC-36-05): a row on disk may carry the removed scope gate, so it
1026
+ // is loaded through the LOAD_GATES set. A row the loader refuses is logged
1027
+ // by id and field instead of vanishing silently.
1028
+ const loadRow =
1029
+ typeof runtime.load === "function" ? runtime.load : (row) => baseRecord(row, { load: true })
1030
+ for (const row of loaded) {
1031
+ if (row !== null && typeof row === "object" && existing.has(row.id)) {
1032
+ // Run 36 F-36-V5: a duplicate id is the remaining silent drop. Log it by
1033
+ // id like every other rejected row instead of dropping it silently.
1034
+ if (typeof ctx.logger?.warn === "function") {
1035
+ ctx.logger.warn('router: dropped ledger row "' + row.id + '" (duplicate id)')
1036
+ }
1037
+ continue
1038
+ }
1039
+ const result = loadRow(row)
1040
+ if (result !== null && typeof result === "object" && result.row !== undefined) {
1041
+ existing.add(result.row.id)
1042
+ continue
1043
+ }
1044
+ const id = row !== null && typeof row === "object" && typeof row.id === "string" ? row.id : "unknown"
1045
+ const field = result !== null && typeof result === "object" && typeof result.field === "string" ? result.field : "row"
1046
+ if (typeof ctx.logger?.warn === "function") {
1047
+ ctx.logger.warn('router: dropped ledger row "' + id + '" (invalid ' + field + ")")
1048
+ }
1049
+ }
1050
+ }
1051
+ loadLedgerRows()
1052
+ void application.refreshTelemetry().then(syncCapabilities)
1053
+
1054
+ // S5: pollSeconds is live — the settings endpoint reschedules this timer.
1055
+ let pollIntervalMs =
1056
+ typeof config.pollIntervalMs === "number" && config.pollIntervalMs > 0 ? config.pollIntervalMs : 2000
1057
+ let pollTimer = null
1058
+ const schedulePoll = () => {
1059
+ if (config.poll === false) return
1060
+ pollTimer = setTimeout(() => {
1061
+ void application.refreshTelemetry().then(syncCapabilities)
1062
+ schedulePoll()
1063
+ }, pollIntervalMs)
1064
+ pollTimer.unref?.()
1065
+ }
1066
+ schedulePoll()
1067
+ if (typeof ctx.effect === "function") {
1068
+ ctx.effect(() => () => {
1069
+ if (pollTimer !== null) clearTimeout(pollTimer)
1070
+ }, "router.telemetryPoll()")
1071
+ }
1072
+
1073
+ const catalogInterval = setInterval(() => void refreshCatalog(), 10000)
1074
+ catalogInterval.unref?.()
1075
+ if (typeof ctx.effect === "function") {
1076
+ ctx.effect(() => () => clearInterval(catalogInterval), "router.catalogPoll()")
1077
+ }
1078
+
1079
+ // R-36-07/DEC-36-07: a model that stays below its floor is re-probed every ten
1080
+ // minutes, so a temporary slowdown (load) is not a permanent penalty.
1081
+ // DEC-37-07: the same tick also refreshes any sample older than half the TTL,
1082
+ // so a fresh decode reading exists before the sample can expire and the
1083
+ // engine's lagging average fills the slot as "measured" (the sawtooth).
1084
+ const speedReprobeTimer = setInterval(() => {
1085
+ const ids = localCatalogueIds()
1086
+ if (ids.length === 0) return
1087
+ const at = config.now ? config.now() : new Date()
1088
+ try {
1089
+ void speedProber().reprobeBelowFloor(ids, floorForSpeedModel, at)
1090
+ } catch {}
1091
+ try {
1092
+ // DEC-37-09: re-probe anything older than one cycle (2 min), not TTL/2, so
1093
+ // the floor gate always compares against a probe reading, never the engine's
1094
+ // outdated average.
1095
+ void speedProber().refreshAged(ids, Math.floor(Math.min(SPEED_SAMPLE_TTL_MS / 2, 2 * 60 * 1000)), at)
1096
+ } catch {}
1097
+ }, config.reprobeIntervalMs ?? BELOW_FLOOR_REPROBE_MS)
1098
+ speedReprobeTimer.unref?.()
1099
+
1100
+ if (typeof ctx.effect === "function") {
1101
+ ctx.effect(() => () => clearInterval(speedReprobeTimer), "router.speedReprobe()")
1102
+ }
1103
+
1104
+ // R-36-02/08/15 (DEC-36-14/15): the role's configured chain is an input to the
1105
+ // decision. The controller walks the same Roles document route-application
1106
+ // uses; the speed sample store is the floor gate's speedFor(id) source.
1107
+ const speedFor = (modelId) => speedProber().sampleFor(modelId)
1108
+ const routing = createRoutingController({
1109
+ runtime,
1110
+ readTelemetry,
1111
+ fallbackPolicy: initialPolicy(),
1112
+ now: config.now,
1113
+ newId: config.newId,
1114
+ logger: ctx.logger,
1115
+ readChain: () => settingsStore.get().roles,
1116
+ resolveModel: (modelId) => resolveRoleModel(modelId),
1117
+ speedFor,
1118
+ // R-36-10: router_route reports the same ceiling/contention facts as the
1119
+ // applied decisions.
1120
+ readLoad: loadFactsNow
1121
+ })
1122
+ const definitions = createToolDefinitions(runtime, { routing, listTools: () => globalToolNames(ctx) })
1123
+
1124
+ // DEC-36-24 (STEP 1): the one-way mirror is removed. roles.l1.model is the
1125
+ // router default and is served verbatim; the DSH native picker is a
1126
+ // session-local override at decision time and never overwrites the Roles
1127
+ // document on read.
1128
+
1129
+ // Host evidence data path: one backend-agnostic model, four exact read-only
1130
+ // routes on ctx.webServer. ctx.inject keeps the plugin loadable on hosts that
1131
+ // do not compose a web server (the routes simply never mount there).
1132
+ const engineEndpoint = (() => {
1133
+ try {
1134
+ return new URL(omlxBaseUrl).host + "/admin/api"
1135
+ } catch {
1136
+ return omlxBaseUrl
1137
+ }
1138
+ })()
1139
+ const configuredEndpoint = config.oMLXBaseUrl !== undefined
1140
+ const environmentEndpoint =
1141
+ process.env.DSH_ROUTER_OMLX_URL !== undefined || process.env.OMLX_BASE_URL !== undefined
1142
+ // Run 25 T3 (DEC-25-10): a role model is a bare id; turn it into a real route
1143
+ // against evidence the host already keeps. The engine catalogue means a local
1144
+ // route; a discovered remote model carries its provider; the policy main model
1145
+ // is the last remote match. Anything else is unavailable (null), never a guess.
1146
+ const resolveRoleModel = (modelId) => {
1147
+ if (typeof modelId !== "string" || modelId.length === 0) return null
1148
+ if (
1149
+ (Array.isArray(engineCatalogue) && engineCatalogue.includes(modelId)) ||
1150
+ (Array.isArray(configuredLocalCatalogue) && configuredLocalCatalogue.includes(modelId))
1151
+ ) {
1152
+ return { target: "local", provider: localSelectionProvider, model: modelId, label: modelId }
1153
+ }
1154
+ const remote = Array.isArray(remoteModels)
1155
+ ? remoteModels.find((entry) => entry !== null && typeof entry === "object" && entry.model === modelId)
1156
+ : undefined
1157
+ if (remote !== undefined && typeof remote.provider === "string" && remote.provider.length > 0) {
1158
+ const label = typeof remote.label === "string" && remote.label.length > 0 ? remote.label : modelId
1159
+ return { target: "remote", provider: remote.provider, model: modelId, label }
1160
+ }
1161
+ const main = runtime.get().mainModel
1162
+ if (main !== null && typeof main === "object" && main.model === modelId && typeof main.provider === "string") {
1163
+ const label = typeof main.label === "string" && main.label.length > 0 ? main.label : modelId
1164
+ return { target: "remote", provider: main.provider, model: modelId, label }
1165
+ }
1166
+ return null
1167
+ }
1168
+ // Every known local provider: the routed local provider, the profile's local
1169
+ // providers, and the built-in local set (omlx/mtplx/mtplx-inkling/lamq). A
1170
+ // provider in this set is never a remote model source.
1171
+ const localProviderIds = new Set(
1172
+ [
1173
+ localProvider,
1174
+ localSelectionProvider,
1175
+ "router",
1176
+ ...DEFAULT_LOCAL_PROVIDERS,
1177
+ ...(Array.isArray(config.localProviders) ? config.localProviders : [])
1178
+ ].filter((p) => typeof p === "string" && p.length > 0)
1179
+ )
1180
+ const enumerateRemoteModels = async () => {
1181
+ try {
1182
+ const llm = ctx.llm ?? (typeof ctx.get === "function" ? ctx.get("llm") : undefined)
1183
+ if (llm === undefined || typeof llm.listProviders !== "function") {
1184
+ ctx.logger?.info?.("[router] llm service unavailable for remote enumeration")
1185
+ return
1186
+ }
1187
+ const providers = await llm.listProviders()
1188
+ const discovered = []
1189
+ for (const provider of providers) {
1190
+ if (provider === null || typeof provider !== "object") continue
1191
+ const id = typeof provider.id === "string" ? provider.id : provider
1192
+ if (typeof id !== "string" || localProviderIds.has(id)) continue
1193
+ let models = []
1194
+ try {
1195
+ models = await llm.listModels(id)
1196
+ } catch {
1197
+ continue
1198
+ }
1199
+ for (const model of models) {
1200
+ if (model === null || typeof model !== "object" || typeof model.id !== "string") continue
1201
+ discovered.push({
1202
+ provider: id,
1203
+ model: model.id,
1204
+ label: typeof model.name === "string" && model.name.length > 0 ? model.name : model.id,
1205
+ role: model.id === (runtime.get().mainModel?.model ?? null) ? "main" : "advisory"
1206
+ })
1207
+ }
1208
+ }
1209
+ if (discovered.length > 0) {
1210
+ remoteModels = discovered
1211
+ ctx.logger?.info?.("[router] remote models enumerated: " + discovered.map((m) => m.provider + "/" + m.model).join(", "))
1212
+ }
1213
+ } catch {
1214
+ // Enumeration is best-effort; discovery is the only remote model source.
1215
+ }
1216
+ }
1217
+ void enumerateRemoteModels()
1218
+ if (config.poll !== false) {
1219
+ const enumInterval = setInterval(() => void enumerateRemoteModels(), 10_000)
1220
+ enumInterval.unref?.()
1221
+ if (typeof ctx.effect === "function") {
1222
+ ctx.effect(() => () => clearInterval(enumInterval), "router.remoteEnumeration()")
1223
+ }
1224
+ }
1225
+ // Run 30 (DEC-30-03/06): a test-only host override forces the reported id
1226
+ // through the real route; otherwise the committed build artifact is reported.
1227
+ // The host reads; it never hashes at boot.
1228
+ const buildId =
1229
+ typeof process.env.DSH_ROUTER_FORCE_BUILD_ID === "string" && process.env.DSH_ROUTER_FORCE_BUILD_ID.length > 0
1230
+ ? process.env.DSH_ROUTER_FORCE_BUILD_ID
1231
+ : committedBuildId
1232
+ // A fresh probe/measured reading for one local model, or null. The engine's own
1233
+ // observedTps is a lifetime average and is never used as evidence.
1234
+ const freshSampleOf = (modelId) => {
1235
+ try {
1236
+ const sample = speedProber().sampleFor(modelId)
1237
+ if (
1238
+ sample !== null &&
1239
+ typeof sample === "object" &&
1240
+ sample.expired !== true &&
1241
+ (sample.source === "probe" || sample.source === "measured") &&
1242
+ typeof sample.tps === "number" &&
1243
+ Number.isFinite(sample.tps)
1244
+ ) {
1245
+ return { tps: sample.tps, source: sample.source }
1246
+ }
1247
+ } catch {}
1248
+ return null
1249
+ }
1250
+ const evidenceAdapter = createEvidenceAdapter({
1251
+ buildId,
1252
+ runtime,
1253
+ backend: { kind: typeof backend.kind === "string" ? backend.kind : "unknown", baseUrl: omlxBaseUrl },
1254
+ cache: application.cache,
1255
+ now: config.now,
1256
+ cacheMaxAgeMs: config.cacheMaxAgeMs,
1257
+ getRemoteModels: () => remoteModels,
1258
+ // Run 37 F-37-12: join a historical ledger row to its recorded request
1259
+ // observation so Prefill and the oMLX join survive a restart.
1260
+ getObservations: observationsForRequest,
1261
+ // F-37-51: the Overview's sessions card reads the cached recent-session list.
1262
+ readSessions: () => recentSessionsCache,
1263
+ // DEC-37-09/14: the Overview's engine meter shows the fresh probe/measured
1264
+ // reading, never the engine's lifetime average.
1265
+ getSpeed: (modelId) => {
1266
+ // oMLX often reports no default model (preferredModel null), so the engine
1267
+ // status must not depend on it: with no named model, report the best fresh
1268
+ // reading among the local catalogue.
1269
+ const ids =
1270
+ typeof modelId === "string" && modelId.length > 0 ? [modelId] : localCatalogueIds()
1271
+ if (ids.length === 0) return null
1272
+ let best = null
1273
+ for (const id of ids) {
1274
+ const fresh = freshSampleOf(id)
1275
+ if (fresh === null) continue
1276
+ if (best === null || fresh.tps > best.tps) best = { ...fresh, model: id }
1277
+ }
1278
+ return best
1279
+ },
1280
+ getModelCapabilities: () => ({
1281
+ models: engineModelInfo,
1282
+ report:
1283
+ typeof engineAdapter.capabilitiesReport === "function" ? engineAdapter.capabilitiesReport() : null
1284
+ }),
1285
+ engine: {
1286
+ kind: typeof backend.kind === "string" ? backend.kind : "omlx",
1287
+ label: "oMLX",
1288
+ version: config.backendVersion ?? "0.8.3"
1289
+ },
1290
+ getConnection: () => ({
1291
+ endpoint: connection.endpoint,
1292
+ authKind: effectiveApiKey().length > 0 ? "bearer" : "none",
1293
+ keyPresent: effectiveApiKey().length > 0,
1294
+ source: "config"
1295
+ }),
1296
+ // Run 34 (DEC-34-13): the Overview reads the settings document from the
1297
+ // projection it already loads. The mirror is the same one the Roles route
1298
+ // applies, so both pages see roles.l1.model === policy.mainModel.
1299
+ getSettings: () => settingsStore.get(),
1300
+ probe: () => application.refreshTelemetry().then(syncCapabilities)
1301
+ })
1302
+ const updateEngineConnection = (body) => {
1303
+ const source = body !== null && typeof body === "object" ? body : {}
1304
+ const endpoint = source.endpoint
1305
+ if (typeof endpoint !== "string" || endpoint.trim().length === 0) {
1306
+ return { ok: false, status: 400, error: { field: "endpoint", message: "endpoint is required" } }
1307
+ }
1308
+ let parsed
1309
+ try {
1310
+ parsed = new URL(endpoint)
1311
+ } catch {
1312
+ return { ok: false, status: 400, error: { field: "endpoint", message: "endpoint must be an http(s) URL" } }
1313
+ }
1314
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
1315
+ return { ok: false, status: 400, error: { field: "endpoint", message: "endpoint must be an http(s) URL" } }
1316
+ }
1317
+ // The telemetry adapter appends /admin/api/*, so accept a base URL (or one that
1318
+ // already includes /admin/api or /admin) and normalize it to the base URL.
1319
+ const base = normalizeEndpoint(endpoint)
1320
+ const apiKey = source.apiKey
1321
+ if (apiKey !== undefined && typeof apiKey !== "string") {
1322
+ return { ok: false, status: 400, error: { field: "apiKey", message: "apiKey must be a string" } }
1323
+ }
1324
+ const providedKey = typeof apiKey === "string" ? apiKey.trim() : ""
1325
+ // The masked hint (••••) is not a real key: keep the stored key when it is
1326
+ // unchanged or empty.
1327
+ const isMask = /^•+$/u.test(providedKey)
1328
+ const nextKey = providedKey.length > 0 && !isMask ? providedKey : connection.apiKey
1329
+ connection = { endpoint: base, apiKey: nextKey }
1330
+ persistConnection()
1331
+ return { ok: true }
1332
+ }
1333
+ const readConnection = (webCtx) => {
1334
+ if (typeof webCtx.get !== "function") return undefined
1335
+ try {
1336
+ return webCtx.get("connection")
1337
+ } catch {
1338
+ return undefined
1339
+ }
1340
+ }
1341
+ const mountEvidenceRoutes = (webCtx) => {
1342
+ const authorize = (req) => {
1343
+ const connection = readConnection(webCtx)
1344
+ if (connection === undefined || connection === null || typeof connection.requestRejection !== "function") {
1345
+ return undefined
1346
+ }
1347
+ return connection.requestRejection({ headers: req.headers })
1348
+ }
1349
+ const authLabel = () => {
1350
+ const connection = readConnection(webCtx)
1351
+ return connection !== undefined && connection !== null && typeof connection.requestRejection === "function"
1352
+ ? "connection"
1353
+ : "unauthenticated"
1354
+ }
1355
+ const onSave = async (body) => {
1356
+ const result = updateEngineConnection(body)
1357
+ if (result.ok !== true) return result
1358
+ await refreshCatalog()
1359
+ await application.refreshTelemetry()
1360
+ syncCapabilities()
1361
+ return { ok: true, payload: evidenceAdapter.engine() }
1362
+ }
1363
+ // S5 operational defaults (no policy writes; the sentence is Overview's).
1364
+ const settingsState = {
1365
+ ledgerDir,
1366
+ pollSeconds: Math.max(1, Math.round((typeof config.pollIntervalMs === "number" ? config.pollIntervalMs : 2000) / 1000)),
1367
+ advisory: config.advisory === true,
1368
+ version: 1
1369
+ }
1370
+ const settingsGet = () => ({
1371
+ endpoint: connection.endpoint,
1372
+ ledgerDir: settingsState.ledgerDir,
1373
+ pollSeconds: settingsState.pollSeconds,
1374
+ advisory: settingsState.advisory,
1375
+ version: settingsState.version
1376
+ })
1377
+ const settingsSave = async (body, ifMatch) => {
1378
+ const expected = Number.parseInt(String(ifMatch ?? ""), 10)
1379
+ if (!Number.isInteger(expected) || expected !== settingsState.version) {
1380
+ return { ok: false, status: 409, payload: settingsGet() }
1381
+ }
1382
+ const patch = body !== null && typeof body === "object" ? body : {}
1383
+ if (patch.endpoint !== undefined) {
1384
+ if (typeof patch.endpoint !== "string") {
1385
+ return { ok: false, status: 400, error: { field: "endpoint", message: "endpoint must be a string" } }
1386
+ }
1387
+ const result = updateEngineConnection({ endpoint: patch.endpoint })
1388
+ if (result.ok !== true) return { ok: false, status: 400, error: result.error }
1389
+ await refreshCatalog()
1390
+ await application.refreshTelemetry()
1391
+ syncCapabilities()
1392
+ }
1393
+ if (patch.ledgerDir !== undefined) {
1394
+ if (typeof patch.ledgerDir !== "string" || patch.ledgerDir.length > 1024) {
1395
+ return { ok: false, status: 400, error: { field: "ledgerDir", message: "ledgerDir must be a path string" } }
1396
+ }
1397
+ settingsState.ledgerDir = patch.ledgerDir
1398
+ ledgerDir = patch.ledgerDir
1399
+ ledgerFile = path.join(ledgerDir, "ledger.jsonl")
1400
+ loadLedgerRows()
1401
+ }
1402
+ if (patch.pollSeconds !== undefined) {
1403
+ const value = Number(patch.pollSeconds)
1404
+ if (!Number.isInteger(value) || value < 1 || value > 3600) {
1405
+ return { ok: false, status: 400, error: { field: "pollSeconds", message: "pollSeconds must be 1..3600" } }
1406
+ }
1407
+ settingsState.pollSeconds = value
1408
+ pollIntervalMs = value * 1000
1409
+ if (pollTimer !== null) clearTimeout(pollTimer)
1410
+ schedulePoll()
1411
+ void application.refreshTelemetry().then(syncCapabilities)
1412
+ }
1413
+ if (patch.advisory !== undefined) {
1414
+ if (typeof patch.advisory !== "boolean") {
1415
+ return { ok: false, status: 400, error: { field: "advisory", message: "advisory must be a boolean" } }
1416
+ }
1417
+ settingsState.advisory = patch.advisory
1418
+ }
1419
+ settingsState.version += 1
1420
+ return { ok: true, payload: settingsGet() }
1421
+ }
1422
+ for (const route of createRouterRoutes(evidenceAdapter, { authorize, authLabel, onSave, onSettingsGet: settingsGet, onSettingsSave: settingsSave })) {
1423
+ if (typeof webCtx.effect === "function") {
1424
+ webCtx.effect(() => webCtx.webServer.register(route), `router: ${route.path}`)
1425
+ } else {
1426
+ webCtx.webServer.register(route)
1427
+ }
1428
+ }
1429
+
1430
+ const respondJson = (res, status, value) => {
1431
+ const body = JSON.stringify(value)
1432
+ res.writeHead(status, {
1433
+ "content-type": "application/json; charset=utf-8",
1434
+ "cache-control": "no-store",
1435
+ "content-length": String(Buffer.byteLength(body)),
1436
+ [AUTH_HEADER]: authLabel()
1437
+ })
1438
+ res.end(body)
1439
+ }
1440
+ const readSessionJson = (req) => {
1441
+ if (req.body !== undefined && typeof req.body === "object" && req.body !== null) {
1442
+ return Promise.resolve(req.body)
1443
+ }
1444
+ return new Promise((resolve, reject) => {
1445
+ const chunks = []
1446
+ let total = 0
1447
+ req.on("data", (chunk) => {
1448
+ total += chunk.length
1449
+ if (total > 16_384) reject(new Error("request body too large"))
1450
+ else chunks.push(chunk)
1451
+ })
1452
+ req.on("end", () => {
1453
+ try {
1454
+ resolve(JSON.parse(Buffer.concat(chunks).toString("utf8") || "{}"))
1455
+ } catch (error) {
1456
+ reject(error)
1457
+ }
1458
+ })
1459
+ req.on("error", reject)
1460
+ })
1461
+ }
1462
+ // F-37-51: the five most recent sessions with their routing state. Session
1463
+ // identity comes from DSH's sessionQuery when it is mounted; otherwise the
1464
+ // ledger's recent sessions are the honest fallback (a session that never made
1465
+ // a decision is only visible through sessionQuery).
1466
+ const refreshRecentSessions = async () => {
1467
+ try {
1468
+ recentSessionsCache = await recentSessionRouting()
1469
+ } catch {}
1470
+ return recentSessionsCache
1471
+ }
1472
+ // F-37-51: keep the Overview's session list current (5 s is enough for a list
1473
+ // that only changes when a session is created or a toggle flips).
1474
+ const startSessionsRefresh = () => {
1475
+ const timer = setInterval(() => void refreshRecentSessions(), 5_000)
1476
+ timer.unref?.()
1477
+ if (typeof webCtx.effect === "function") {
1478
+ webCtx.effect(() => () => clearInterval(timer), "router.sessions()")
1479
+ }
1480
+ void refreshRecentSessions()
1481
+ }
1482
+ const recentSessionRouting = async () => {
1483
+ const limit = 5
1484
+ const entries = []
1485
+ const push = (id, title, updatedAt, live) => {
1486
+ if (entries.some((entry) => entry.id === id)) return
1487
+ const state = sessionRouting.get(id)
1488
+ entries.push({
1489
+ id,
1490
+ title: typeof title === "string" && title.length > 0 ? title : null,
1491
+ updatedAt: typeof updatedAt === "number" ? new Date(updatedAt).toISOString() : null,
1492
+ live: live === true,
1493
+ enabled: state?.enabled === true,
1494
+ mainModel: state?.mainModel ?? null
1495
+ })
1496
+ }
1497
+ try {
1498
+ const query = typeof ctx.get === "function" ? ctx.get("sessionQuery") : undefined
1499
+ if (query !== undefined && query !== null && typeof query.listSessions === "function") {
1500
+ const records = await query.listSessions()
1501
+ for (const record of Array.isArray(records) ? records : []) {
1502
+ const header = record?.header ?? {}
1503
+ const at = Number.isFinite(header.updatedAt) ? header.updatedAt : header.createdAt
1504
+ push(header.id, header.title, at, record?.live === true)
1505
+ if (entries.length >= limit) break
1506
+ }
1507
+ }
1508
+ } catch {}
1509
+ if (entries.length < limit) {
1510
+ try {
1511
+ for (const row of ledgerRows()) {
1512
+ if (typeof row?.sessionId !== "string") continue
1513
+ push(row.sessionId, null, Date.parse(row.at), false)
1514
+ if (entries.length >= limit) break
1515
+ }
1516
+ } catch {}
1517
+ }
1518
+ return entries.slice(0, limit)
1519
+ }
1520
+ const sessionRoutingHandler = async (req, res) => {
1521
+ if (authorize(req) === 401 || authorize(req) === 403) {
1522
+ const rejection = authorize(req)
1523
+ res.writeHead(rejection, { "content-type": "text/plain; charset=utf-8", [AUTH_HEADER]: authLabel() })
1524
+ res.end(rejection === 401 ? "unauthorized" : "forbidden")
1525
+ return
1526
+ }
1527
+ const url = new URL(req.url ?? "/", "http://router.local")
1528
+ if (req.method === "GET") {
1529
+ const sessionId = url.searchParams.get("sessionId")
1530
+ // F-37-51: no sessionId asks for the recent-session routing list, so a page
1531
+ // that is not tied to one session can show which sessions route and let the
1532
+ // Owner toggle any of them. The toggle is the same store the model picker
1533
+ // writes, so the two cannot disagree.
1534
+ if (typeof sessionId !== "string" || sessionId.length === 0) {
1535
+ respondJson(res, 200, { sessions: await recentSessionRouting() })
1536
+ return
1537
+ }
1538
+ const entry = sessionRouting.get(sessionId)
1539
+ let currentProvider = null
1540
+ let currentModel = null
1541
+ try {
1542
+ const agent = typeof sessionId === "string" && sessionId.length > 0 ? ctx.agents?.get(sessionId) : undefined
1543
+ const current = typeof agent?.model?.current === "function" ? agent.model.current() : null
1544
+ if (current !== null && typeof current.model === "string") {
1545
+ currentProvider = typeof current.provider === "string" ? current.provider : null
1546
+ currentModel = current.model
1547
+ }
1548
+ } catch {
1549
+ currentProvider = null
1550
+ currentModel = null
1551
+ }
1552
+ respondJson(res, 200, {
1553
+ enabled: entry?.enabled === true,
1554
+ mainModel: entry?.mainModel ?? null,
1555
+ currentProvider,
1556
+ currentModel
1557
+ })
1558
+ return
1559
+ }
1560
+ if (req.method === "POST") {
1561
+ let body
1562
+ try {
1563
+ body = await readSessionJson(req)
1564
+ } catch {
1565
+ respondJson(res, 400, { ok: false, error: { field: "body", message: "invalid JSON body" } })
1566
+ return
1567
+ }
1568
+ const sessionId = body !== null && typeof body === "object" ? body.sessionId : undefined
1569
+ const enabled = body !== null && typeof body === "object" ? body.enabled : undefined
1570
+ if (typeof sessionId !== "string" || sessionId.length === 0) {
1571
+ respondJson(res, 400, { ok: false, error: { field: "sessionId", message: "sessionId is required" } })
1572
+ return
1573
+ }
1574
+ if (typeof enabled !== "boolean") {
1575
+ respondJson(res, 400, { ok: false, error: { field: "enabled", message: "enabled must be a boolean" } })
1576
+ return
1577
+ }
1578
+ let mainModel = null
1579
+ if (enabled) {
1580
+ try {
1581
+ const agent = ctx.agents?.get(sessionId)
1582
+ const current = typeof agent?.model?.current === "function" ? agent.model.current() : null
1583
+ mainModel = current !== null && typeof current.model === "string" ? current.model : null
1584
+ } catch {
1585
+ mainModel = null
1586
+ }
1587
+ }
1588
+ sessionRouting.set(sessionId, { enabled, mainModel })
1589
+ persistSessionRouting()
1590
+ void refreshRecentSessions()
1591
+ respondJson(res, 200, { sessionId, enabled, mainModel })
1592
+ return
1593
+ }
1594
+ res.writeHead(405, { "content-type": "text/plain; charset=utf-8", allow: "GET, POST", [AUTH_HEADER]: authLabel() })
1595
+ res.end()
1596
+ }
1597
+ startSessionsRefresh()
1598
+ const sessionRoutingRoute = { kind: "exact", path: "/api/router/session-routing", handler: sessionRoutingHandler }
1599
+ if (typeof webCtx.effect === "function") {
1600
+ webCtx.effect(() => webCtx.webServer.register(sessionRoutingRoute), "router: /api/router/session-routing")
1601
+ } else {
1602
+ webCtx.webServer.register(sessionRoutingRoute)
1603
+ }
1604
+
1605
+ const policyHandler = async (req, res) => {
1606
+ const rejection = authorize(req)
1607
+ if (rejection === 401 || rejection === 403) {
1608
+ res.writeHead(rejection, { "content-type": "text/plain; charset=utf-8", [AUTH_HEADER]: authLabel() })
1609
+ res.end(rejection === 401 ? "unauthorized" : "forbidden")
1610
+ return
1611
+ }
1612
+ if (req.method === "GET") {
1613
+ respondJson(res, 200, { policy: runtime.get() })
1614
+ return
1615
+ }
1616
+ if (req.method === "POST") {
1617
+ let body
1618
+ try {
1619
+ body = await readSessionJson(req)
1620
+ } catch {
1621
+ respondJson(res, 400, { ok: false, error: { field: "body", message: "invalid JSON body" } })
1622
+ return
1623
+ }
1624
+ const source = body !== null && typeof body === "object" ? body : {}
1625
+ if (!Number.isInteger(source.expectedRev)) {
1626
+ respondJson(res, 400, { ok: false, error: { field: "expectedRev", message: "expectedRev must be an integer" } })
1627
+ return
1628
+ }
1629
+ const result = runtime.write(source.patch !== null && typeof source.patch === "object" ? source.patch : {}, source.expectedRev)
1630
+ if (result.conflict === true) {
1631
+ respondJson(res, 409, { ok: false, conflict: true, policy: result.current })
1632
+ return
1633
+ }
1634
+ if (result.invalid === true) {
1635
+ respondJson(res, 400, { ok: false, error: { field: result.field ?? "patch", message: "invalid policy value" } })
1636
+ return
1637
+ }
1638
+ respondJson(res, 200, { ok: true, policy: result.policy })
1639
+ return
1640
+ }
1641
+ res.writeHead(405, { "content-type": "text/plain; charset=utf-8", allow: "GET, POST", [AUTH_HEADER]: authLabel() })
1642
+ res.end()
1643
+ }
1644
+ const policyRoute = { kind: "exact", path: "/api/router/policy", handler: policyHandler }
1645
+ if (typeof webCtx.effect === "function") {
1646
+ webCtx.effect(() => webCtx.webServer.register(policyRoute), "router: /api/router/policy")
1647
+ } else {
1648
+ webCtx.webServer.register(policyRoute)
1649
+ }
1650
+
1651
+ // Run 25: the Router Settings page fragments (context + roles), PUT with If-Match.
1652
+ const settingsHandlers = createSettingsHandlers(settingsStore)
1653
+ // Run 25 DEC-25-13: the L3 "active" switch is real - it maps to the subagent
1654
+ // row's volatile maxDepth through ctx.settings.update (never a direct cordis
1655
+ // profile write).
1656
+ //
1657
+ // Mapping from the harness rule (dsh-subagent/src/child-agent.ts
1658
+ // resolveChildDepth): childDepth = delegationDepthOf(parent) + 1, and the
1659
+ // child is refused when childDepth > maxDepth. Levels: L1 depth 0, L2 depth
1660
+ // 1, L3 depth 2. So L3 ALLOWED needs maxDepth >= 2, and L3 FORBIDDEN needs
1661
+ // maxDepth <= 1 (the subagent row defaults to 1; 0 would forbid the L2 level
1662
+ // too). L3 on -> 2, off -> 1.
1663
+ //
1664
+ // This runs only when roles.l3.enabled actually changes, so a Context-only
1665
+ // save never overwrites a manually tuned maxDepth. A conflict or an absent
1666
+ // service never invalidates an otherwise valid document save: it is
1667
+ // reported as a field error on roles.l3.enabled and the saved document stays
1668
+ // authoritative.
1669
+ const applyL3Depth = async (document) => {
1670
+ const enabled = document?.roles?.l3?.enabled === true
1671
+ const maxDepth = maxDepthFromL3Enabled(enabled)
1672
+ const unavailable = {
1673
+ ok: false,
1674
+ field: "roles.l3.enabled",
1675
+ message: "subagent.maxDepth was not applied: the DSH settings service is unavailable"
1676
+ }
1677
+ const service = settingsServiceNow()
1678
+ if (service === null || service === undefined || typeof service.update !== "function") return unavailable
1679
+ let revision
1680
+ if (typeof service.describe === "function") {
1681
+ try {
1682
+ const descriptors = await Promise.resolve(service.describe())
1683
+ const row = Array.isArray(descriptors)
1684
+ ? descriptors.find((entry) => entry !== null && typeof entry === "object" && entry.ns === "subagent")
1685
+ : undefined
1686
+ if (row !== undefined && Number.isInteger(row.revision)) revision = row.revision
1687
+ } catch {
1688
+ return {
1689
+ ok: false,
1690
+ field: "roles.l3.enabled",
1691
+ message: "subagent.maxDepth was not applied: the settings service could not be read"
1692
+ }
1693
+ }
1694
+ }
1695
+ try {
1696
+ await service.update("subagent", { maxDepth }, revision)
1697
+ return { ok: true }
1698
+ } catch (error) {
1699
+ if (error !== null && typeof error === "object" && error.code === "SETTINGS_CONFLICT") {
1700
+ return {
1701
+ ok: false,
1702
+ field: "roles.l3.enabled",
1703
+ message: "subagent.maxDepth was not applied: settings changed since they were read (revision conflict); retry the save"
1704
+ }
1705
+ }
1706
+ return {
1707
+ ok: false,
1708
+ field: "roles.l3.enabled",
1709
+ message: "subagent.maxDepth was not applied: " + (error instanceof Error ? error.message : String(error))
1710
+ }
1711
+ }
1712
+ }
1713
+ const settingsPagesHandler = async (req, res) => {
1714
+ const rejection = authorize(req)
1715
+ if (rejection === 401 || rejection === 403) {
1716
+ res.writeHead(rejection, { "content-type": "text/plain; charset=utf-8", [AUTH_HEADER]: authLabel() })
1717
+ res.end(rejection === 401 ? "unauthorized" : "forbidden")
1718
+ return
1719
+ }
1720
+ if (req.method === "GET" || req.method === "HEAD") {
1721
+ // R-36-09 (DEC-36-13): subagent.maxDepth is authoritative on read, so an
1722
+ // external change is reflected on the next page load and routing reads
1723
+ // the same mirrored value.
1724
+ mirrorL3FromDepth(await readMaxDepth())
1725
+ const result = settingsHandlers.get()
1726
+ respondJson(res, result.status, withEffective(result.payload))
1727
+ return
1728
+ }
1729
+ if (req.method !== "PUT") {
1730
+ res.writeHead(405, { "content-type": "text/plain; charset=utf-8", allow: "GET, HEAD, PUT", [AUTH_HEADER]: authLabel() })
1731
+ res.end()
1732
+ return
1733
+ }
1734
+ let body
1735
+ try {
1736
+ body = await readSessionJson(req)
1737
+ } catch {
1738
+ respondJson(res, 400, { ok: false, error: { field: "body", message: "invalid JSON body" } })
1739
+ return
1740
+ }
1741
+ const before = settingsStore.get()
1742
+ const result = settingsHandlers.put(body, req.headers?.["if-match"])
1743
+ if (result.status !== 200) {
1744
+ // A 409 hands the page the document it must adopt; it needs the same
1745
+ // policy mirror as a 200, or the L1 row would show a stale model.
1746
+ const body409 =
1747
+ result.status === 409 && result.payload?.current !== undefined
1748
+ ? { ...result.payload, current: withEffective(result.payload.current) }
1749
+ : result.payload
1750
+ respondJson(res, result.status, body409)
1751
+ return
1752
+ }
1753
+ // DEC-36-24 (STEP 2): roles.l1.model is the router default. A Roles save
1754
+ // writes only the document; it never writes the stored policy.mainModel and
1755
+ // never the native picker. The store's own catalogue validation refuses an
1756
+ // unknown id.
1757
+ const payload = result.payload
1758
+ const documentChanged =
1759
+ (before?.roles?.l3?.enabled === true) !== (result.payload?.roles?.l3?.enabled === true)
1760
+ let depth = null
1761
+ if (documentChanged) {
1762
+ // R-36-09: toggling the switch writes the one DSH setting.
1763
+ depth = await applyL3Depth(result.payload)
1764
+ if (depth !== null && depth.ok === true) {
1765
+ settingsStore.mirrorL3Enabled(result.payload?.roles?.l3?.enabled === true)
1766
+ }
1767
+ } else {
1768
+ // maxDepth stays authoritative even when the save touched another field:
1769
+ // a stale document mirror is corrected, never written back to DSH.
1770
+ const depthNow = await readMaxDepth()
1771
+ if (depthNow !== undefined) {
1772
+ const enabled = l3EnabledFromMaxDepth(depthNow)
1773
+ settingsStore.mirrorL3Enabled(enabled)
1774
+ if (payload !== null && typeof payload === "object" && payload.roles?.l3 !== undefined) {
1775
+ payload.roles = { ...payload.roles, l3: { ...payload.roles.l3, enabled } }
1776
+ }
1777
+ }
1778
+ }
1779
+ const depthIssue = depth !== null && depth.ok !== true ? { field: depth.field, message: depth.message } : null
1780
+ const effectivePayload = withEffective(payload)
1781
+ respondJson(res, 200, depthIssue === null ? effectivePayload : { ...effectivePayload, issue: depthIssue })
1782
+ }
1783
+ const settingsPagesRoute = { kind: "exact", path: "/api/router/settings/pages", handler: settingsPagesHandler }
1784
+ if (typeof webCtx.effect === "function") {
1785
+ webCtx.effect(() => webCtx.webServer.register(settingsPagesRoute), "router: /api/router/settings/pages")
1786
+ } else {
1787
+ webCtx.webServer.register(settingsPagesRoute)
1788
+ }
1789
+
1790
+
1791
+ // Runtime probe used by verification: is the engine provider mounted, and
1792
+ // which models does its adapter currently see on the engine?
1793
+ const engineProviderHandler = async (req, res) => {
1794
+ const rejection = authorize(req)
1795
+ if (rejection === 401 || rejection === 403) {
1796
+ res.writeHead(rejection, { "content-type": "text/plain; charset=utf-8", [AUTH_HEADER]: authLabel() })
1797
+ res.end(rejection === 401 ? "unauthorized" : "forbidden")
1798
+ return
1799
+ }
1800
+ if (req.method !== "GET") {
1801
+ res.writeHead(405, { "content-type": "text/plain; charset=utf-8", allow: "GET", [AUTH_HEADER]: authLabel() })
1802
+ res.end()
1803
+ return
1804
+ }
1805
+ let registered = false
1806
+ try {
1807
+ const providers = await ctx.llm.listProviders()
1808
+ registered = Array.isArray(providers) && providers.some((entry) => (entry?.id ?? entry) === localSelectionProvider)
1809
+ } catch {
1810
+ registered = false
1811
+ }
1812
+ let models = []
1813
+ try {
1814
+ models = await engineAdapter.listModels(localSelectionProvider)
1815
+ } catch {
1816
+ models = []
1817
+ }
1818
+ // Exercise DSH's own catalog validation (provider match, non-empty id/name).
1819
+ let catalogOk = false
1820
+ let runtimeModels = []
1821
+ try {
1822
+ const catalog = await ctx.llm.listModels(localSelectionProvider)
1823
+ catalogOk = Array.isArray(catalog)
1824
+ runtimeModels = catalogOk ? catalog.map((model) => model.id) : []
1825
+ } catch {
1826
+ catalogOk = false
1827
+ }
1828
+ respondJson(res, 200, {
1829
+ provider: localSelectionProvider,
1830
+ registered,
1831
+ catalogOk,
1832
+ models: Array.isArray(models) ? models.map((model) => model.id) : [],
1833
+ runtimeModels
1834
+ })
1835
+ }
1836
+ const engineProviderRoute = { kind: "exact", path: "/api/router/engine-provider", handler: engineProviderHandler }
1837
+ if (typeof webCtx.effect === "function") {
1838
+ webCtx.effect(() => webCtx.webServer.register(engineProviderRoute), "router: /api/router/engine-provider")
1839
+ } else {
1840
+ webCtx.webServer.register(engineProviderRoute)
1841
+ }
1842
+ }
1843
+ if (typeof ctx.inject === "function") {
1844
+ ctx.inject(["webServer"], (webCtx) => mountEvidenceRoutes(webCtx))
1845
+ } else if (ctx.webServer !== undefined) {
1846
+ mountEvidenceRoutes(ctx)
1847
+ } else if (typeof ctx.logger?.warn === "function") {
1848
+ ctx.logger.warn("router evidence routes not mounted: ctx.webServer is unavailable")
1849
+ }
1850
+
1851
+ ctx.tools.register(definitions.router_policy)
1852
+ ctx.tools.register(definitions.router_ledger)
1853
+ ctx.tools.register(definitions.router_route)
1854
+ ctx.tools.register(definitions.list_tools)
1855
+ ctx.on("agent/status", application.handleStatus)
1856
+ // F-37-06: the depth is only readable once the session header exists, so the
1857
+ // child preset is (re)attempted when the agent starts running.
1858
+ ctx.on("agent/status", ({ agent, status } = {}) => {
1859
+ try {
1860
+ if (status !== "running") return
1861
+ if (!isSubagentAgent(agent) || presetApplied.has(agent)) return
1862
+ void selectSubagentPreset(agent)
1863
+ } catch (error) {
1864
+ warnOnce("agent-preset-status:" + errorText(error), "router: the child preset was not applied on status: " + errorText(error))
1865
+ }
1866
+ })
1867
+ ctx.on("session/event", application.handleTurnStart)
1868
+ ctx.on("session/disposed", application.handleSessionDisposed)
1869
+ // Run 37 (F-37-12): mark the latest request key for the session as the
1870
+ // claimed/pre-step path applies the decision, so the adapter's completion
1871
+ // observation can be joined back to the ledger row this session just wrote.
1872
+ ctx.on("agent/inbox/claimed", (payload = {}) => {
1873
+ const pending = application.handleClaimed(payload)
1874
+ const sessionId = sessionIdOfAgent(payload?.agent)
1875
+ if (sessionId !== null && pending !== null && typeof pending.requestId === "string") {
1876
+ markRequestKey(sessionId, pending.requestId, pending.route?.model ?? null)
1877
+ }
1878
+ return pending
1879
+ })
1880
+ ctx.on("agent/pre-step", async (payload = {}, next) => {
1881
+ const stepDecision = await application.handlePreStep(payload, next)
1882
+ const sessionId = sessionIdOfAgent(payload?.agent)
1883
+ if (sessionId !== null) {
1884
+ const pending = application.pendingFor(sessionId)
1885
+ if (pending !== null && typeof pending.requestId === "string") {
1886
+ markRequestKey(sessionId, pending.requestId, pending.route?.model ?? null)
1887
+ }
1888
+ }
1889
+ return stepDecision
1890
+ })
1891
+
1892
+ // Run 35 (R-35-01..03): the saved Context document drives pruning, the tool
1893
+ // subset and the inline summariser, and every value is read live at use - a
1894
+ // Context save applies without the restart the boot-built pruner used to need.
1895
+ // config.prune is only the fallback for a value the document does not carry
1896
+ // (resolvePrunePlan owns that contract, including the "unsupported mode
1897
+ // disables pruning with one visible warning" rule).
1898
+ const pruneConfig =
1899
+ config.prune !== null && typeof config.prune === "object" && !Array.isArray(config.prune)
1900
+ ? config.prune
1901
+ : {}
1902
+ const errorText = (error) => (error instanceof Error ? error.message : String(error))
1903
+ // The store is the only source; get() also applies the host-derived fields and
1904
+ // repairs an older document, and a read never throws at the caller.
1905
+ const readContextNow = () => {
1906
+ try {
1907
+ const document = settingsStore.get()
1908
+ return document !== null && typeof document === "object" && document.context !== null && typeof document.context === "object"
1909
+ ? document.context
1910
+ : null
1911
+ } catch {
1912
+ return null
1913
+ }
1914
+ }
1915
+ const readMainModel = () => {
1916
+ const main = runtime.get().mainModel
1917
+ return main !== null && typeof main === "object" && typeof main.provider === "string" && typeof main.model === "string"
1918
+ ? { provider: main.provider, model: main.model }
1919
+ : null
1920
+ }
1921
+ // "local" means the router's local transport and a model that transport really
1922
+ // advertises; never a hard-coded id and never the remote main model.
1923
+ const readLocalModel = () => {
1924
+ const local = [
1925
+ ...(Array.isArray(engineCatalogue) ? engineCatalogue : []),
1926
+ ...(Array.isArray(configuredLocalCatalogue) ? configuredLocalCatalogue : [])
1927
+ ].find((id) => typeof id === "string" && id.length > 0)
1928
+ return typeof local === "string" && local.length > 0
1929
+ ? { provider: localSelectionProvider, model: local }
1930
+ : null
1931
+ }
1932
+ // perResult is an allowance per turn; the Session's committed turn boundary is
1933
+ // the only honest turn identity available to a tool-result handler.
1934
+ const readTurnFor = (agent) => {
1935
+ try {
1936
+ const boundary = typeof ctx.agents?.turnBoundaryOf === "function" ? ctx.agents.turnBoundaryOf(agent?.session) : null
1937
+ return Number.isInteger(boundary?.lastTurn) ? boundary.lastTurn : null
1938
+ } catch {
1939
+ return null
1940
+ }
1941
+ }
1942
+ const summariser = createInlineSummariser({
1943
+ llm: ctx.llm,
1944
+ readContext: readContextNow,
1945
+ readMainModel,
1946
+ readLocalModel,
1947
+ readTurn: readTurnFor
1948
+ })
1949
+ // Run 35 repair (FIX 2, verifier finding A): the loader now keeps a document
1950
+ // whose prune mode is unknown instead of replacing it with the defaults, so the
1951
+ // typo has to be visible here. The same warn-once key the per-result hook uses
1952
+ // means the boot warning is the only one; pruning is already off because
1953
+ // resolvePrunePlan refuses an unknown mode (reason "unknown mode <x>").
1954
+ if (typeof settingsLoad.unknownPruneMode === "string") {
1955
+ const bootPlan = resolvePrunePlan(readContextNow(), pruneConfig, { summariseAvailable: summariser.available() })
1956
+ if (bootPlan.invalidMode === true && bootPlan.warning !== null) {
1957
+ warnOnce("prune-mode:" + bootPlan.requestedMode, bootPlan.warning)
1958
+ }
1959
+ }
1960
+ // R-35-04: the served settings payload carries the effective block, derived at
1961
+ // read time with the same helpers the runtime uses (prune plan, tool subset,
1962
+ // summariser availability). The page renders it instead of its client mirror.
1963
+ const withEffective = (payload) => {
1964
+ if (payload === null || typeof payload !== "object" || payload.context === undefined) return payload
1965
+ try {
1966
+ return {
1967
+ ...payload,
1968
+ effective: effectiveFromDocument(payload.context, {
1969
+ configPrune: pruneConfig,
1970
+ summariseAvailable: summariser.available(),
1971
+ knownNames: globalToolNames(ctx)
1972
+ })
1973
+ }
1974
+ } catch {
1975
+ return payload
1976
+ }
1977
+ }
1978
+ const isSubagentAgent = (agent) => {
1979
+ const header = agent !== null && typeof agent === "object" && agent.session !== null && typeof agent.session === "object"
1980
+ ? agent.session.header
1981
+ : undefined
1982
+ return header !== null && typeof header === "object" && header.origin === "subagent"
1983
+ }
1984
+ // DEC-35-11 (reverts DEC-35-02/07/09/10): the saved subset is an ALLOWLIST over
1985
+ // the page vocabulary (the 9 core tools), enforced through the agent-scoped
1986
+ // tools service on creation. resolveToolSubset returns exactly the selected
1987
+ // core tools this child inherits, so every tool the page does not select -
1988
+ // skill, ask_user_question, every mcp_* server (Paper included), the devtools
1989
+ // MCP, the agent-team tools - is masked and reached through run_code, which is
1990
+ // always available and never named (tools.restrict() refuses to name it). Ids
1991
+ // outside the page vocabulary cannot select anything, so they are named once
1992
+ // in a single warning. A failure never rejects creation.
1993
+ const restrictSubagentTools = (agent) => {
1994
+ const context = readContextNow()
1995
+ const configured =
1996
+ context !== null && context.toolSubset !== null && typeof context.toolSubset === "object"
1997
+ ? context.toolSubset
1998
+ : null
1999
+ if (configured === null || configured.enabled !== true || !Array.isArray(configured.tools) || configured.tools.length === 0) return
2000
+ const scopedTools = agent?.ctx?.tools
2001
+ if (scopedTools === null || typeof scopedTools !== "object" || typeof scopedTools.restrict !== "function") {
2002
+ warnOnce("tool-subset-service", "router: the saved tool subset was not applied: this agent has no scoped tools service")
2003
+ return
2004
+ }
2005
+ let view = null
2006
+ try {
2007
+ view = typeof scopedTools.view === "function" ? scopedTools.view(agent) : null
2008
+ if (view === null && typeof ctx.tools?.view === "function") view = ctx.tools.view(agent)
2009
+ } catch (error) {
2010
+ warnOnce("tool-subset-view", "router: the saved tool subset was not applied: the tool view could not be read (" + errorText(error) + ")")
2011
+ return
2012
+ }
2013
+ const restrictedNames = view !== null && view !== undefined ? view.restrictableNames : undefined
2014
+ const known =
2015
+ restrictedNames instanceof Set
2016
+ ? restrictedNames
2017
+ : Array.isArray(restrictedNames)
2018
+ ? new Set(restrictedNames)
2019
+ : null
2020
+ if (known === null) {
2021
+ warnOnce("tool-subset-view", "router: the saved tool subset was not applied: the tool view names no restrictable tools")
2022
+ return
2023
+ }
2024
+ const subset = resolveToolSubset(context, known)
2025
+ if (subset === null) return
2026
+ if (subset.ignored.length > 0) {
2027
+ // One warning for the whole ignored set: these ids are outside the page
2028
+ // vocabulary (code_run/list_tools are retired; run_code is the always-on
2029
+ // PTC transport), so they cannot select anything.
2030
+ warnOnce(
2031
+ "tool-subset-ignored",
2032
+ "router: the tool subset ignores " +
2033
+ String(subset.ignored.length) +
2034
+ (subset.ignored.length === 1 ? " id that is not a page tool: " : " ids that are not page tools: ") +
2035
+ subset.ignored.map((id) => JSON.stringify(id)).join(", ") +
2036
+ " - " +
2037
+ (subset.ignored.length === 1 ? "it cannot" : "they cannot") +
2038
+ " select anything"
2039
+ )
2040
+ }
2041
+ // allow is null only when there is no enabled subset or no selected page id;
2042
+ // otherwise restrict the child to exactly the selected core tools.
2043
+ if (subset.allow === null) return
2044
+ try {
2045
+ // R-37-02: list_tools is the discovery primitive for a restricted child, so
2046
+ // it must stay callable even though it is not one of the 9 core tools. A
2047
+ // child whose allow list omitted it could not discover anything (found by
2048
+ // the live spawn probe: 10 tools, has_list_tools false).
2049
+ const allow =
2050
+ known.has("list_tools") && !subset.allow.includes("list_tools")
2051
+ ? [...subset.allow, "list_tools"]
2052
+ : subset.allow
2053
+ scopedTools.restrict({ allow })
2054
+ } catch (error) {
2055
+ warnOnce("tool-subset-restrict:" + errorText(error), "router: the saved tool subset was not applied: " + errorText(error))
2056
+ }
2057
+ }
2058
+ // F-37-03: the lean presets ship with this plugin (cordis.patch.yml) but a
2059
+ // child INHERITS the parent's preset when nothing selects one, so every child
2060
+ // ran on 'ptc' and the lean instructions (agent-instructions maxBytes 16384)
2061
+ // never applied. Select the role-appropriate preset at spawn: delegationDepth
2062
+ // 1 -> lean-worker, 2 or deeper -> lean-assistant; depth 0 (and any unreadable
2063
+ // depth) is the advisor/none role and is left alone. The registry is optional:
2064
+ // it is read through ctx.get('agentPresets') and guarded when absent, only
2065
+ // presets the registry knows are selected, and any failure is warned once and
2066
+ // never rejects agent creation.
2067
+ const leanPresetForDepth = (depth) => {
2068
+ if (depth === 1) return "lean-worker"
2069
+ if (typeof depth === "number" && Number.isFinite(depth) && depth >= 2) return "lean-assistant"
2070
+ return null
2071
+ }
2072
+ const presetKnown = async (presets, preset) => {
2073
+ if (typeof presets.resolve === "function") {
2074
+ const resolved = await presets.resolve(preset)
2075
+ return resolved !== null && typeof resolved === "object" && resolved.broken === undefined
2076
+ }
2077
+ if (typeof presets.list === "function") {
2078
+ const rows = await presets.list()
2079
+ return Array.isArray(rows) && rows.some((row) => row !== null && typeof row === "object" && row.id === preset)
2080
+ }
2081
+ return false
2082
+ }
2083
+ // F-37-06 (live): agent/created fires before a child's session header carries
2084
+ // delegationDepth, so the depth-1 worker kept 'ptc' while its own child (depth 1
2085
+ // by then) received 'lean-worker'. The selection is therefore attempted at
2086
+ // creation AND again from agent/status (running), where the depth is populated,
2087
+ // at most once per agent.
2088
+ const presetApplied = new WeakSet()
2089
+ const selectSubagentPreset = async (agent) => {
2090
+ const presets = typeof ctx.get === "function" ? ctx.get("agentPresets") : undefined
2091
+ if (presets === null || typeof presets !== "object" || typeof presets.select !== "function") return
2092
+ const header = agent !== null && typeof agent === "object" && agent.session !== null && typeof agent.session === "object" ? agent.session.header : undefined
2093
+ const depth = header !== null && typeof header === "object" ? header.delegationDepth : undefined
2094
+ const preset = leanPresetForDepth(typeof depth === "number" ? depth : undefined)
2095
+ if (preset === null) return
2096
+ try {
2097
+ const known = await presetKnown(presets, preset)
2098
+ if (!known) {
2099
+ warnOnce("agent-preset-unknown:" + preset, "router: the child preset was not applied: the registry does not know '" + preset + "'")
2100
+ return
2101
+ }
2102
+ await presets.select(agent, preset)
2103
+ presetApplied.add(agent)
2104
+ } catch (error) {
2105
+ warnOnce("agent-preset-select:" + errorText(error), "router: the child preset '" + preset + "' was not applied: " + errorText(error))
2106
+ }
2107
+ }
2108
+ if (typeof ctx.on === "function") {
2109
+ try {
2110
+ ctx.on("agent/created", ({ agent } = {}) => {
2111
+ try {
2112
+ if (isSubagentAgent(agent)) restrictSubagentTools(agent)
2113
+ } catch (error) {
2114
+ warnOnce("tool-subset-handler:" + errorText(error), "router: the saved tool subset was not applied: " + errorText(error))
2115
+ }
2116
+ try {
2117
+ if (isSubagentAgent(agent) && !presetApplied.has(agent)) return selectSubagentPreset(agent)
2118
+ } catch (error) {
2119
+ warnOnce("agent-preset-handler:" + errorText(error), "router: the child preset was not applied: " + errorText(error))
2120
+ }
2121
+ })
2122
+ } catch (error) {
2123
+ warnOnce("tool-subset-hook", "router: tool subset enforcement unavailable: " + errorText(error))
2124
+ }
2125
+ }
2126
+ // F-24-01: the post-execute waterfall replaces content BEFORE tool/result
2127
+ // commits, so the original is not in the session log. Reference mode is only
2128
+ // honest when the body is spilled to disk; this writer gives it a real path.
2129
+ const spillDir = path.join(dataDir, "tool-results")
2130
+ const spillForPruner = async (body, meta) => {
2131
+ if (typeof config.toolResultsSpill === "function") return config.toolResultsSpill(body, meta)
2132
+ try {
2133
+ fs.mkdirSync(spillDir, { recursive: true })
2134
+ const digest = createHash("sha256").update(body).digest("hex").slice(0, 16)
2135
+ const safeTool = String(meta?.tool ?? "tool").replace(/[^a-zA-Z0-9._-]/g, "_").slice(0, 40)
2136
+ const file = path.join(spillDir, safeTool + "-" + digest + ".txt")
2137
+ if (!fs.existsSync(file)) fs.writeFileSync(file, body)
2138
+ return file
2139
+ } catch {
2140
+ return null
2141
+ }
2142
+ }
2143
+ // Measured (evidence/plugin-arms-v6.json): model-only summarisation dropped
2144
+ // every identifier, so summarise mode appends a DETERMINISTIC index of the
2145
+ // identifiers present in the body. Losing a fact must be a decision, not a
2146
+ // side effect of the summariser.
2147
+ const preserveForPruner = (body) => {
2148
+ const found = new Set()
2149
+ for (const match of String(body).match(/\b[A-Z][A-Z0-9]{0,6}-\d{2,}\b/g) ?? []) found.add(match)
2150
+ for (const match of String(body).match(/(?:^|\s)(\/[\w.-]+(?:\/[\w.-]+)+)/g) ?? []) found.add(match.trim())
2151
+ return [...found].slice(0, 200)
2152
+ }
2153
+ // The pruner is built per result, not once at boot: the document's enabled,
2154
+ // mode, trigger and budget are the runtime truth and a save must not wait for
2155
+ // a restart. The trigger follows the model's window when the operator declares
2156
+ // one; a fixed 20,000-char trigger is most of an 8k-token window.
2157
+ const pruneBudgetFor = (context) => {
2158
+ const contextBudget = budgetFromContext(context)
2159
+ const budget = resolveBudget(
2160
+ contextBudget === null
2161
+ ? {
2162
+ contextWindow: pruneConfig.contextWindow,
2163
+ maxChars: pruneConfig.maxChars,
2164
+ headChars: pruneConfig.headChars,
2165
+ tailChars: pruneConfig.tailChars,
2166
+ charRatio: pruneConfig.charRatio
2167
+ }
2168
+ : {
2169
+ maxChars: contextBudget.maxChars,
2170
+ headChars: contextBudget.headChars,
2171
+ tailChars: contextBudget.tailChars
2172
+ }
2173
+ )
2174
+ return { contextBudget, budget }
2175
+ }
2176
+ // A block document the page saved decides identifiers; the fallback keeps the
2177
+ // measured behaviour (deterministic index) when the fragment is absent.
2178
+ const summaryIdentifiersFor = (context) =>
2179
+ context !== null && context.lazySummary !== null && typeof context.lazySummary === "object" && context.lazySummary.identifiers === "drop"
2180
+ ? "drop"
2181
+ : "index"
2182
+ const toolResultsFile = path.join(dataDir, "tool-results.jsonl")
2183
+ const writeAuditRow = (row) => {
2184
+ if (typeof config.toolResultsWriter === "function") {
2185
+ try { config.toolResultsWriter(row) } catch {}
2186
+ return
2187
+ }
2188
+ try {
2189
+ fs.appendFileSync(toolResultsFile, JSON.stringify(row) + "\n")
2190
+ } catch {}
2191
+ }
2192
+ const normalizeToolResult = (exec, result) => {
2193
+ const agent = exec !== null && typeof exec === "object" ? exec.agent : undefined
2194
+ const session = agent !== null && typeof agent === "object" ? agent.session : undefined
2195
+ const sessionId = session !== null && typeof session === "object" && typeof session.id === "string" ? session.id : ""
2196
+ const header = session !== null && typeof session === "object" ? session.header : undefined
2197
+ const subagent =
2198
+ (header !== null && typeof header === "object" && header.origin === "subagent") ||
2199
+ (header !== null && typeof header === "object" && typeof header.parentSession === "string" && header.parentSession.length > 0)
2200
+ const content = result !== null && typeof result === "object" && Array.isArray(result.content) ? result.content : []
2201
+ const body = content
2202
+ .filter((block) => block !== null && typeof block === "object" && block.type === "text")
2203
+ .map((block) => block.text)
2204
+ .join("\n")
2205
+ return {
2206
+ tool: exec !== null && typeof exec === "object" && typeof exec.name === "string" ? exec.name : "",
2207
+ sessionId,
2208
+ subagent: subagent === true,
2209
+ callId: exec !== null && typeof exec === "object" && typeof exec.callId === "string" ? exec.callId : undefined,
2210
+ body
2211
+ }
2212
+ }
2213
+ const rebuildContent = (prunedBody, originalContent) => {
2214
+ const nonText = (Array.isArray(originalContent) ? originalContent : [])
2215
+ .filter((block) => block !== null && typeof block === "object" && block.type !== "text")
2216
+ return prunedBody.length > 0 ? [{ type: "text", text: prunedBody }, ...nonText] : nonText
2217
+ }
2218
+ if (typeof ctx.on === "function" && ctx.tools !== undefined) {
2219
+ try {
2220
+ ctx.on("tools/post-execute", async (exec, result, next) => {
2221
+ const decision = await next()
2222
+ if (decision.kind !== "accept") return decision
2223
+ try {
2224
+ const context = readContextNow()
2225
+ const plan = resolvePrunePlan(context, pruneConfig, { summariseAvailable: summariser.available() })
2226
+ if (plan.invalidMode === true && plan.warning !== null) {
2227
+ warnOnce("prune-mode:" + plan.requestedMode, plan.warning)
2228
+ }
2229
+ // The enable switch (and mode/trigger off) gates the hook: no pruning
2230
+ // and no audit row, exactly the state the page shows.
2231
+ if (plan.enabled !== true) return decision
2232
+ const { contextBudget, budget } = pruneBudgetFor(context)
2233
+ const identifiers = summaryIdentifiersFor(context)
2234
+ summariser.resetLast()
2235
+ const pruner = createToolResultPruner({
2236
+ mode: plan.mode,
2237
+ // trigger=always ignores the per-result size gate; the pruner's only
2238
+ // threshold is maxChars, so one character is the honest expression.
2239
+ maxChars: plan.trigger === "always" ? 1 : budget.maxChars,
2240
+ headChars: budget.headChars,
2241
+ tailChars: budget.tailChars,
2242
+ // summary mode is only reachable with the inline summariser (the plan
2243
+ // refused it otherwise), so it is the summariser the pruner calls. The
2244
+ // pruner only passes the body; the child agent rides the closure.
2245
+ summarise: plan.mode === "summarise" ? (body) => summariser.summarise(body, { agent: exec?.agent }) : null,
2246
+ preserve: identifiers === "drop" ? null : preserveForPruner,
2247
+ // context.prune.spill is the page's switch: off means reference mode
2248
+ // can no longer claim the body was retained, so no spiller is wired.
2249
+ spill: contextBudget === null || contextBudget.spill === true ? spillForPruner : null,
2250
+ now: config.now
2251
+ })
2252
+ const normalized = normalizeToolResult(exec, result)
2253
+ const applied = await pruner.apply(normalized)
2254
+ // Run 35 repair (FIX 3, verifier finding E): a replacement must never be
2255
+ // larger than the body it replaces. trigger:"always" sends even a
2256
+ // 10-character result to the mode, whose reference pointer is ~330
2257
+ // characters, so "pruning" would grow the payload. Keep the original and
2258
+ // record why; charsAfter reports the length the model actually saw.
2259
+ const bodyChars = codePointLength(normalized.body)
2260
+ const replacementChars = codePointLength(applied.result.body)
2261
+ const keptSmaller = replacementChars > bodyChars
2262
+ // R-35-01: the row records the effective mode (never a hardcoded off)
2263
+ // and, when it summarised, which route produced the summary.
2264
+ const row = {
2265
+ ...applied.audit,
2266
+ ...(keptSmaller ? { charsAfter: bodyChars, kind: "kept-smaller", attemptedCharsAfter: replacementChars } : {}),
2267
+ effectiveMode: plan.mode,
2268
+ trigger: plan.trigger,
2269
+ modeSource: plan.modeSource
2270
+ }
2271
+ if (plan.mode === "summarise") {
2272
+ const summary = summariser.lastResult()
2273
+ if (summary !== null && typeof summary === "object") {
2274
+ row.summarised = summary.status === "summarised"
2275
+ if (summary.status === "summarised") row.summariser = { provider: summary.provider, model: summary.model }
2276
+ else if (typeof summary.reason === "string") row.summarySkipped = summary.reason
2277
+ }
2278
+ }
2279
+ writeAuditRow(row)
2280
+ if (!keptSmaller && applied.result.body !== normalized.body) {
2281
+ return {
2282
+ kind: "accept",
2283
+ content: rebuildContent(applied.result.body, result.content),
2284
+ ...(decision.additionalContexts !== undefined ? { additionalContexts: decision.additionalContexts } : {})
2285
+ }
2286
+ }
2287
+ return decision
2288
+ } catch {
2289
+ return decision
2290
+ }
2291
+ })
2292
+ } catch (error) {
2293
+ if (typeof ctx.logger?.warn === "function") {
2294
+ ctx.logger.warn("router: tool-result pruner disabled: " + (error?.message ?? String(error)))
2295
+ }
2296
+ }
2297
+ }
2298
+ return application
2299
+ }