@try-works/dsh-minimal-router 0.1.0 → 0.2.1

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 CHANGED
@@ -21,7 +21,7 @@ import path from "node:path"
21
21
  import { createRouterRuntime, createToolDefinitions, initialPolicy } from "./host.js"
22
22
  import { concurrencyCeilingFor, createRoutingController } from "./routing.js"
23
23
  import { createRouteApplication, createRouteMapper, DEFAULT_LOCAL_PROVIDERS } from "./route-application.js"
24
- import { createEngineAdapter } from "./engine-adapter.js"
24
+ import { createEngineAdapter, ROLE_PROVIDER_IDS } from "./engine-adapter.js"
25
25
  import { createCapabilitySync } from "./capability-sync.js"
26
26
  import { createLocalBackend } from "./backend.js"
27
27
  import { BELOW_FLOOR_REPROBE_MS, createSpeedProber, DEFAULT_OMLX_BASE_URL, SPEED_SAMPLE_TTL_MS } from "./telemetry.js"
@@ -63,13 +63,27 @@ export const inject = ["tools", "agents", "llm"]
63
63
  // Run 35: the restrictable global tool names, read from the live tools service
64
64
  // (no scope = the global view). Null when the service cannot answer, so the
65
65
  // runtime reports "unsupported" instead of guessing a list.
66
- const globalToolNames = (ctx) => {
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) => {
67
71
  try {
68
72
  if (ctx === null || typeof ctx !== "object" || typeof ctx.tools?.view !== "function") return null
69
- const view = ctx.tools.view()
70
- const names = view !== null && typeof view === "object" ? view.restrictableNames : undefined
71
- if (names instanceof Set && names.size > 0) return new Set(names)
72
- if (Array.isArray(names) && names.length > 0) return new Set(names)
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
73
87
  } catch {}
74
88
  return null
75
89
  }
@@ -390,6 +404,8 @@ export function apply(ctx, config = {}) {
390
404
  // OFF for every session until the user enables it in that session. A profile
391
405
  // may pre-enable a session list for tests/CI via config.routedSessions.
392
406
  const sessionRouting = new Map()
407
+ // F-37-51: the recent-session rows the Overview lists, refreshed by the host.
408
+ let recentSessionsCache = []
393
409
  const sessionRoutingFile = path.join(dataDir, "session-routing.json")
394
410
  const persistSessionRouting = () => {
395
411
  try {
@@ -480,39 +496,37 @@ export function apply(ctx, config = {}) {
480
496
  return speedProberInstance
481
497
  }
482
498
  let lastCatalogueSweep = null
483
- // F-37-02 diagnostic: the sweep outcome is invisible from outside the host, so
484
- // record each attempt to <dataDir>/sweep.log. Temporary; removed once the
485
- // probe is confirmed live.
486
- const sweepDiag = (line) => {
487
- try {
488
- fs.appendFileSync(path.join(dataDir, "sweep.log"), new Date().toISOString() + " " + line + "\n")
489
- } catch {}
490
- }
491
499
  const sweepLocalCatalogue = () => {
492
500
  const ids = localCatalogueIds()
493
501
  const signature = ids.join("\n")
494
- sweepDiag("ids=" + JSON.stringify(ids) + " last=" + JSON.stringify(lastCatalogueSweep) + " sig=" + JSON.stringify(signature))
495
502
  if (signature === lastCatalogueSweep) return
496
503
  lastCatalogueSweep = signature
497
504
  if (ids.length === 0) return
498
505
  try {
499
506
  void speedProber().sweep(ids)
500
507
  } catch {}
501
- // The boot read already carries live throughput for the preferred model;
502
- // record it once so a model is not "unknown" until the first poll tick.
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.
503
515
  try {
504
- const snapshot = application.cache?.snapshot?.()
505
- if (
506
- snapshot !== null &&
507
- typeof snapshot === "object" &&
508
- typeof snapshot.preferredModel === "string" &&
509
- ids.includes(snapshot.preferredModel) &&
510
- typeof snapshot.observedTps === "number" &&
511
- Number.isFinite(snapshot.observedTps)
512
- ) {
513
- speedProber().samples.measured(snapshot.preferredModel, snapshot.observedTps)
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()")
514
524
  }
515
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.
516
530
  }
517
531
  // The per-model floor for the re-probe sweep: a model is below its floor when
518
532
  // any configured role chain that uses it has a higher floor than its reading.
@@ -665,23 +679,183 @@ export function apply(ctx, config = {}) {
665
679
  const residents = Array.isArray(snapshot.residents)
666
680
  ? snapshot.residents.filter((id) => catalogModels.has(id))
667
681
  : snapshot.residents
668
- // R-36-07: real traffic refreshes the preferred local model's sample. This
669
- // is the only writer that is not a background sweep; it never probes.
670
- const localIds = localCatalogueIds()
671
- if (
672
- localIds.length > 0 &&
673
- typeof snapshot.preferredModel === "string" &&
674
- localIds.includes(snapshot.preferredModel) &&
675
- typeof snapshot.observedTps === "number" &&
676
- Number.isFinite(snapshot.observedTps)
677
- ) {
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
678
693
  try {
679
- speedProber().samples.measured(snapshot.preferredModel, snapshot.observedTps)
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
+ }
680
705
  } catch {}
706
+ return null
707
+ }
708
+ const probedTps = probed(snapshot.preferredModel)
709
+ if (probedTps !== null) {
710
+ return { ...snapshot, residents, observedTps: probedTps, observedTpsSource: "probe" }
681
711
  }
682
712
  return { ...snapshot, residents }
683
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
+ }
684
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,
685
859
  getConnection: () => connection,
686
860
  // Injectable transport so a test can serve the engine surfaces without a
687
861
  // live engine; production leaves it undefined and uses global fetch.
@@ -699,12 +873,12 @@ export function apply(ctx, config = {}) {
699
873
  // Persisted subagent model selections may still name provider "omlx", and
700
874
  // without an adapter those turns fail with "no adapter registered".
701
875
  try {
702
- ctx.llm.registerAdapter(["engine", "omlx"], engineAdapter)
876
+ ctx.llm.registerAdapter(["engine", "omlx", ...ROLE_PROVIDER_IDS], engineAdapter)
703
877
  engineRegistered = true
704
878
  } catch {
705
879
  // A real omlx provider may already exist; keep the engine route alone.
706
880
  try {
707
- ctx.llm.registerAdapter(["engine"], engineAdapter)
881
+ ctx.llm.registerAdapter(["engine", ...ROLE_PROVIDER_IDS], engineAdapter)
708
882
  engineRegistered = true
709
883
  } catch (error) {
710
884
  // A second plugin instance may already own the route; never crash the host.
@@ -717,6 +891,17 @@ export function apply(ctx, config = {}) {
717
891
  // Registered before the first catalog read so "engine" is a known provider.
718
892
  Promise.resolve().then(() => void refreshCatalog())
719
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
+ },
720
905
  localProvider,
721
906
  localSelectionProvider,
722
907
  localAvailable: () => dshLocalPresent || (localSelectionProvider === "engine" && engineRegistered),
@@ -904,10 +1089,14 @@ export function apply(ctx, config = {}) {
904
1089
  void speedProber().reprobeBelowFloor(ids, floorForSpeedModel, at)
905
1090
  } catch {}
906
1091
  try {
907
- void speedProber().refreshAged(ids, Math.floor(SPEED_SAMPLE_TTL_MS / 2), at)
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)
908
1096
  } catch {}
909
1097
  }, config.reprobeIntervalMs ?? BELOW_FLOOR_REPROBE_MS)
910
1098
  speedReprobeTimer.unref?.()
1099
+
911
1100
  if (typeof ctx.effect === "function") {
912
1101
  ctx.effect(() => () => clearInterval(speedReprobeTimer), "router.speedReprobe()")
913
1102
  }
@@ -1040,6 +1229,24 @@ export function apply(ctx, config = {}) {
1040
1229
  typeof process.env.DSH_ROUTER_FORCE_BUILD_ID === "string" && process.env.DSH_ROUTER_FORCE_BUILD_ID.length > 0
1041
1230
  ? process.env.DSH_ROUTER_FORCE_BUILD_ID
1042
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
+ }
1043
1250
  const evidenceAdapter = createEvidenceAdapter({
1044
1251
  buildId,
1045
1252
  runtime,
@@ -1048,6 +1255,28 @@ export function apply(ctx, config = {}) {
1048
1255
  now: config.now,
1049
1256
  cacheMaxAgeMs: config.cacheMaxAgeMs,
1050
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
+ },
1051
1280
  getModelCapabilities: () => ({
1052
1281
  models: engineModelInfo,
1053
1282
  report:
@@ -1230,6 +1459,64 @@ export function apply(ctx, config = {}) {
1230
1459
  req.on("error", reject)
1231
1460
  })
1232
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
+ }
1233
1520
  const sessionRoutingHandler = async (req, res) => {
1234
1521
  if (authorize(req) === 401 || authorize(req) === 403) {
1235
1522
  const rejection = authorize(req)
@@ -1240,7 +1527,15 @@ export function apply(ctx, config = {}) {
1240
1527
  const url = new URL(req.url ?? "/", "http://router.local")
1241
1528
  if (req.method === "GET") {
1242
1529
  const sessionId = url.searchParams.get("sessionId")
1243
- const entry = typeof sessionId === "string" && sessionId.length > 0 ? sessionRouting.get(sessionId) : undefined
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)
1244
1539
  let currentProvider = null
1245
1540
  let currentModel = null
1246
1541
  try {
@@ -1292,12 +1587,14 @@ export function apply(ctx, config = {}) {
1292
1587
  }
1293
1588
  sessionRouting.set(sessionId, { enabled, mainModel })
1294
1589
  persistSessionRouting()
1590
+ void refreshRecentSessions()
1295
1591
  respondJson(res, 200, { sessionId, enabled, mainModel })
1296
1592
  return
1297
1593
  }
1298
1594
  res.writeHead(405, { "content-type": "text/plain; charset=utf-8", allow: "GET, POST", [AUTH_HEADER]: authLabel() })
1299
1595
  res.end()
1300
1596
  }
1597
+ startSessionsRefresh()
1301
1598
  const sessionRoutingRoute = { kind: "exact", path: "/api/router/session-routing", handler: sessionRoutingHandler }
1302
1599
  if (typeof webCtx.effect === "function") {
1303
1600
  webCtx.effect(() => webCtx.webServer.register(sessionRoutingRoute), "router: /api/router/session-routing")
@@ -1556,10 +1853,41 @@ export function apply(ctx, config = {}) {
1556
1853
  ctx.tools.register(definitions.router_route)
1557
1854
  ctx.tools.register(definitions.list_tools)
1558
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
+ })
1559
1867
  ctx.on("session/event", application.handleTurnStart)
1560
1868
  ctx.on("session/disposed", application.handleSessionDisposed)
1561
- ctx.on("agent/inbox/claimed", application.handleClaimed)
1562
- ctx.on("agent/pre-step", application.handlePreStep)
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
+ })
1563
1891
 
1564
1892
  // Run 35 (R-35-01..03): the saved Context document drives pruning, the tool
1565
1893
  // subset and the inline summariser, and every value is read live at use - a
@@ -1727,6 +2055,56 @@ export function apply(ctx, config = {}) {
1727
2055
  warnOnce("tool-subset-restrict:" + errorText(error), "router: the saved tool subset was not applied: " + errorText(error))
1728
2056
  }
1729
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
+ }
1730
2108
  if (typeof ctx.on === "function") {
1731
2109
  try {
1732
2110
  ctx.on("agent/created", ({ agent } = {}) => {
@@ -1735,6 +2113,11 @@ export function apply(ctx, config = {}) {
1735
2113
  } catch (error) {
1736
2114
  warnOnce("tool-subset-handler:" + errorText(error), "router: the saved tool subset was not applied: " + errorText(error))
1737
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
+ }
1738
2121
  })
1739
2122
  } catch (error) {
1740
2123
  warnOnce("tool-subset-hook", "router: tool subset enforcement unavailable: " + errorText(error))