@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/client/index.js CHANGED
@@ -65290,6 +65290,13 @@ var OverviewCss = [
65290
65290
  ".router-meter-track { position: relative; width: 100%; height: 6px; flex-shrink: 0; border-radius: var(--radius-pill); background: var(--color-line-panel); }",
65291
65291
  ".router-meter-indicator { border-radius: var(--radius-pill); }",
65292
65292
  ".router-meter-tick { position: absolute; top: 0; bottom: 0; width: 2px; background: var(--color-bg); }",
65293
+ ".router-sessions { display: flex; flex-direction: column; gap: 6px; border-top: 1px solid var(--color-line-rule); padding-top: var(--spacing-4); width: 100%; }",
65294
+ ".router-sessions-head { display: flex; align-items: baseline; justify-content: space-between; gap: var(--spacing-4); }",
65295
+ ".router-sessions-label { font-family: var(--font-mono); font-size: var(--text-caps); line-height: var(--leading-caps); letter-spacing: var(--tracking-caps); text-transform: uppercase; color: var(--color-meta); }",
65296
+ ".router-sessions-meta { font-family: var(--font-mono); font-size: var(--text-meta); color: var(--color-meta); }",
65297
+ ".router-session-row { display: flex; align-items: center; gap: var(--spacing-4); border-top: 1px solid var(--color-line-rule); padding: 6px 0; font-family: var(--font-ui); font-size: var(--text-meta); }",
65298
+ ".router-session-title { flex: 1 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--color-ink); }",
65299
+ ".router-session-meta { flex-shrink: 0; font-family: var(--font-mono); color: var(--color-meta); }",
65293
65300
  ".router-meter-status { font-family: var(--font-mono); font-size: var(--text-meta); line-height: var(--leading-meta); color: var(--color-meta); overflow-wrap: anywhere; }",
65294
65301
  /* The page's own error line (the one error role) and the recent-calls list:
65295
65302
  classes, not inline styles (F-34-15). The two remaining inline values are
@@ -65346,6 +65353,19 @@ var OverviewViewSchema = Schema_exports.NullOr(
65346
65353
  // source), so the field accepts null as well as absence.
65347
65354
  engineTpsSource: Schema_exports.optional(Schema_exports.NullOr(Schema_exports.Literals(["live", "historical"]))),
65348
65355
  headroomRatio: Schema_exports.optional(Schema_exports.NullOr(Schema_exports.Number)),
65356
+ // F-37-51: routing is per session, so the Overview lists the recent sessions
65357
+ // and their state instead of claiming a global on/off.
65358
+ sessions: Schema_exports.optional(
65359
+ Schema_exports.Array(
65360
+ Schema_exports.Struct({
65361
+ id: Schema_exports.String,
65362
+ title: Schema_exports.NullOr(Schema_exports.String),
65363
+ updatedAt: Schema_exports.NullOr(Schema_exports.String),
65364
+ live: Schema_exports.Boolean,
65365
+ enabled: Schema_exports.Boolean
65366
+ })
65367
+ )
65368
+ ),
65349
65369
  // DEC-34-13: the same settings document the Roles page loads, mirrored to
65350
65370
  // policy.mainModel by the host on every read.
65351
65371
  settings: Schema_exports.optional(Schema_exports.NullOr(SettingsDocSchema)),
@@ -65369,7 +65389,21 @@ var OverviewMessage = UiSchema_exports.TaggedEnum({
65369
65389
  field: Schema_exports.String,
65370
65390
  message: Schema_exports.String
65371
65391
  },
65372
- RetryRoleSave: {}
65392
+ RetryRoleSave: {},
65393
+ // F-37-51: the per-session routing toggle. It writes the same store the model
65394
+ // picker writes, so the two can never disagree.
65395
+ RequestedToggleSession: { sessionId: Schema_exports.String, enabled: Schema_exports.Boolean },
65396
+ SessionRoutingChanged: {
65397
+ sessions: Schema_exports.Array(
65398
+ Schema_exports.Struct({
65399
+ id: Schema_exports.String,
65400
+ title: Schema_exports.NullOr(Schema_exports.String),
65401
+ updatedAt: Schema_exports.NullOr(Schema_exports.String),
65402
+ live: Schema_exports.Boolean,
65403
+ enabled: Schema_exports.Boolean
65404
+ })
65405
+ )
65406
+ }
65373
65407
  });
65374
65408
  var engineHost = (endpoint) => {
65375
65409
  if (endpoint === null) return "the configured engine";
@@ -65536,6 +65570,48 @@ var SaveSettings = Command_exports.make(
65536
65570
  )
65537
65571
  )
65538
65572
  );
65573
+ var ToggleSessionRouting = Command_exports.make(
65574
+ "ToggleSessionRouting",
65575
+ { args: { sessionId: Schema_exports.String, enabled: Schema_exports.Boolean } },
65576
+ ({ sessionId, enabled }) => Effect_exports.gen(function* () {
65577
+ const response = yield* Effect_exports.tryPromise({
65578
+ try: () => fetch("/api/router/session-routing", {
65579
+ method: "POST",
65580
+ credentials: "same-origin",
65581
+ headers: { "content-type": "application/json", accept: "application/json" },
65582
+ body: JSON.stringify({ sessionId, enabled })
65583
+ }),
65584
+ catch: () => "network"
65585
+ }).pipe(Effect_exports.catch(() => Effect_exports.succeed(null)));
65586
+ if (response === null || typeof response.json !== "function") {
65587
+ return OverviewMessage.SessionRoutingChanged({ sessions: [] });
65588
+ }
65589
+ const settled2 = yield* Effect_exports.tryPromise({
65590
+ try: () => response.json(),
65591
+ catch: () => null
65592
+ }).pipe(Effect_exports.catch(() => Effect_exports.succeed(null)));
65593
+ const listed = yield* Effect_exports.tryPromise({
65594
+ try: () => fetch("/api/router/session-routing", {
65595
+ credentials: "same-origin",
65596
+ cache: "no-store",
65597
+ headers: { accept: "application/json" }
65598
+ }).then((res) => res.json()),
65599
+ catch: () => null
65600
+ }).pipe(Effect_exports.catch(() => Effect_exports.succeed(null)));
65601
+ const rows = listed !== null && typeof listed === "object" && Array.isArray(listed.sessions) ? listed.sessions : [];
65602
+ return OverviewMessage.SessionRoutingChanged({
65603
+ sessions: rows.filter((row) => row !== null && typeof row === "object" && typeof row.id === "string").map((row) => ({
65604
+ id: row.id,
65605
+ title: typeof row.title === "string" ? row.title : null,
65606
+ updatedAt: typeof row.updatedAt === "string" ? row.updatedAt : null,
65607
+ live: row.live === true,
65608
+ enabled: row.enabled === true
65609
+ }))
65610
+ });
65611
+ })
65612
+ );
65613
+ var OverviewSessionLabel = (row) => row.title !== null && row.title.length > 0 ? row.title : row.id;
65614
+ var OverviewSessionStateText = (row) => row.enabled ? "Routing on" : "Routing off";
65539
65615
  var OverviewDef = Html_exports.component({
65540
65616
  name: "Overview",
65541
65617
  props: Schema_exports.Struct({
@@ -65555,6 +65631,16 @@ var OverviewDef = Html_exports.component({
65555
65631
  // did not carry one (the page then says so instead of inventing values).
65556
65632
  settings: Schema_exports.NullOr(SettingsDocSchema),
65557
65633
  engine: Schema_exports.NullOr(EngineInfoSchema),
65634
+ // F-37-51: the recent-session rows the toggle list renders.
65635
+ sessions: Schema_exports.Array(
65636
+ Schema_exports.Struct({
65637
+ id: Schema_exports.String,
65638
+ title: Schema_exports.NullOr(Schema_exports.String),
65639
+ updatedAt: Schema_exports.NullOr(Schema_exports.String),
65640
+ live: Schema_exports.Boolean,
65641
+ enabled: Schema_exports.Boolean
65642
+ })
65643
+ ),
65558
65644
  selectOpen: Schema_exports.NullOr(Schema_exports.String),
65559
65645
  pending: Schema_exports.Boolean,
65560
65646
  saveError: Schema_exports.NullOr(Schema_exports.String),
@@ -65568,6 +65654,7 @@ var OverviewDef = Html_exports.component({
65568
65654
  var Overview = OverviewDef.make({
65569
65655
  init: ({ props }) => ({
65570
65656
  policy: props.initialPolicy,
65657
+ sessions: Array.isArray(props.overview?.sessions) ? props.overview.sessions : [],
65571
65658
  overview: props.overview,
65572
65659
  models: props.models,
65573
65660
  policyError: props.policyError,
@@ -65584,6 +65671,11 @@ var Overview = OverviewDef.make({
65584
65671
  // document; there is nothing to preserve in place (Run 20 R-20-01 retired the
65585
65672
  // editor that needed it).
65586
65673
  update: {
65674
+ RequestedToggleSession: ($, { sessionId, enabled }) => {
65675
+ const flipped = $.model.sessions.map((row) => row.id === sessionId ? { ...row, enabled } : row);
65676
+ return $.evolve({ sessions: flipped }).run(ToggleSessionRouting.make({ sessionId, enabled }));
65677
+ },
65678
+ SessionRoutingChanged: ($, { sessions: sessions2 }) => $.model.sessions.length === 0 && sessions2.length === 0 ? $.model : $.evolve({ sessions: sessions2 }),
65587
65679
  RequestedOpenSelect: ($, { path }) => $.evolve({ selectOpen: path }),
65588
65680
  RequestedCloseSelect: ($, { path }) => $.model.selectOpen === path ? $.evolve({ selectOpen: null }) : $.model,
65589
65681
  PickedRoleSetting: ($, { path, value: value3 }) => {
@@ -65665,6 +65757,24 @@ var Overview = OverviewDef.make({
65665
65757
  h3.div.class("router-meter-status").children(status.statusLine)
65666
65758
  )
65667
65759
  });
65760
+ const sessions2 = model.sessions;
65761
+ const sessionsCard = h3.div.class("router-sessions").attr("data-sessions-card", "").children(
65762
+ h3.div.class("router-sessions-head").children(
65763
+ h3.span.class("router-sessions-label").children("Sessions \xB7 routing"),
65764
+ h3.span.class("router-sessions-meta").children(sessions2.length === 0 ? "none" : String(sessions2.length))
65765
+ ),
65766
+ ...sessions2.length === 0 ? [h3.p.class("router-note").children("No recent sessions")] : sessions2.map(
65767
+ (row) => h3.div.class("router-session-row").attr("data-session-row", row.id).children(
65768
+ h3.span.class("router-session-title").children(OverviewSessionLabel(row)),
65769
+ h3.span.class("router-session-meta").children(
65770
+ (row.live ? "live \xB7 " : "") + (row.updatedAt === null ? "" : row.updatedAt.slice(11, 16))
65771
+ ),
65772
+ Button(h3, {
65773
+ onPress: OverviewMessage.RequestedToggleSession({ sessionId: row.id, enabled: !row.enabled })
65774
+ }).class("router-session-toggle").attr("data-control", "").attr("data-session-enabled", row.enabled ? "true" : "false").children(OverviewSessionStateText(row))
65775
+ )
65776
+ )
65777
+ );
65668
65778
  const recent = model.overview === null ? [] : model.overview.recent;
65669
65779
  return PageFrame(h3, {
65670
65780
  // Run 34 P3 (DEC-34-04 / DEC-34-07): no footer status line and no page
@@ -65693,6 +65803,7 @@ var Overview = OverviewDef.make({
65693
65803
  ],
65694
65804
  Separator(h3).class("router-rule"),
65695
65805
  meter,
65806
+ sessionsCard,
65696
65807
  Separator(h3).class("router-rule"),
65697
65808
  ...recent.length === 0 ? [
65698
65809
  h3.div.class("router-recent-empty").children("No calls yet")
@@ -65892,7 +66003,9 @@ var EvidenceActivitySchema = Schema_exports.Struct({
65892
66003
  activeRequests: Schema_exports.Number,
65893
66004
  waitingRequests: Schema_exports.Number,
65894
66005
  memoryUsedBytes: Schema_exports.Number,
65895
- memoryMaxBytes: Schema_exports.Number
66006
+ memoryMaxBytes: Schema_exports.Number,
66007
+ // F-37-48: the engine's soft memory limit (the guard), null when unreported.
66008
+ memorySoftBytes: Schema_exports.optional(Schema_exports.NullOr(Schema_exports.Number))
65896
66009
  });
65897
66010
  var EvidenceDeviceSchema = Schema_exports.Struct({
65898
66011
  chipName: Schema_exports.String,
@@ -65977,7 +66090,9 @@ var ModelsKpisSchema = Schema_exports.Struct({
65977
66090
  cacheEfficiency: Schema_exports.Number,
65978
66091
  uptimeSeconds: Schema_exports.Number,
65979
66092
  memoryUsedBytes: Schema_exports.Number,
65980
- memoryMaxBytes: Schema_exports.Number
66093
+ memoryMaxBytes: Schema_exports.Number,
66094
+ // F-37-48: the engine's soft memory limit (the guard) for the Models header.
66095
+ memorySoftBytes: Schema_exports.optional(Schema_exports.NullOr(Schema_exports.Number))
65981
66096
  });
65982
66097
  var ModelCapabilityFields = {
65983
66098
  contextWindow: Schema_exports.optional(Schema_exports.NullOr(Schema_exports.Number)),
@@ -65987,12 +66102,18 @@ var ModelsResidentSchema = Schema_exports.Struct({
65987
66102
  id: Schema_exports.String,
65988
66103
  preferred: Schema_exports.Boolean,
65989
66104
  selected: Schema_exports.Boolean,
66105
+ // F-37-48: the role ids whose settings chain routes to this model, so the page
66106
+ // can label it by what it actually serves (l1 | l2 | l3 | advisor).
66107
+ roles: Schema_exports.optional(Schema_exports.Array(Schema_exports.String)),
66108
+ // F-37-48: the fresh probe/measured reading for this model (null when none).
66109
+ tps: Schema_exports.optional(Schema_exports.NullOr(Schema_exports.Number)),
65990
66110
  ...ModelCapabilityFields
65991
66111
  });
65992
66112
  var RemoteModelSchema = Schema_exports.Struct({
65993
66113
  provider: Schema_exports.String,
65994
66114
  model: Schema_exports.String,
65995
66115
  role: Schema_exports.Literals(["main", "advisory"]),
66116
+ roles: Schema_exports.optional(Schema_exports.Array(Schema_exports.String)),
65996
66117
  label: Schema_exports.optional(Schema_exports.String)
65997
66118
  });
65998
66119
  var ModelsViewSchema = Schema_exports.Struct({
@@ -66361,14 +66482,19 @@ var fetchEvidence = async (tab, options = {}) => {
66361
66482
  if (typeof request3 !== "function") {
66362
66483
  return { ok: false, status: null, message: "No fetch implementation is available.", retryable: false };
66363
66484
  }
66485
+ const call = () => request3(evidencePath(tab, options.probe === true), {
66486
+ method: "GET",
66487
+ headers: { accept: "application/json" },
66488
+ credentials: "same-origin",
66489
+ cache: "no-store",
66490
+ ...options.signal === void 0 ? {} : { signal: options.signal }
66491
+ });
66364
66492
  try {
66365
- const response = await request3(evidencePath(tab, options.probe === true), {
66366
- method: "GET",
66367
- headers: { accept: "application/json" },
66368
- credentials: "same-origin",
66369
- cache: "no-store",
66370
- ...options.signal === void 0 ? {} : { signal: options.signal }
66371
- });
66493
+ let response = await call();
66494
+ if (response.status === 404) {
66495
+ await new Promise((resolve7) => setTimeout(resolve7, 750));
66496
+ if (options.signal?.aborted !== true) response = await call();
66497
+ }
66372
66498
  if (!response.ok) {
66373
66499
  return { ok: false, status: response.status, message: evidenceStatusMessage(response.status), retryable: true };
66374
66500
  }
@@ -66505,7 +66631,7 @@ if (typeof document !== "undefined" && document.head !== null) {
66505
66631
  }
66506
66632
 
66507
66633
  // packages/plugin/client/build-id.ts
66508
- var clientBuildId = true ? "6a887da8bca27c824da9667ccc532d49f3509c0935d3928128876c18932c22a4" : "";
66634
+ var clientBuildId = true ? "05bec211f5afe235f2510ce06128a98aa892db2e48f29d84d53d5093c2fc8bba" : "";
66509
66635
  var compareBuildIds = (hostId, clientId) => {
66510
66636
  const host = typeof hostId === "string" && hostId.length > 0 ? hostId : null;
66511
66637
  const client = typeof clientId === "string" && clientId.length > 0 ? clientId : null;
@@ -67131,6 +67257,13 @@ var modelStateLabel = (local, tpsValue, sampleSource) => {
67131
67257
  if (tpsValue === null || !Number.isFinite(tpsValue)) return "probing";
67132
67258
  return sampleSource === "live" ? "resident \xB7 measured" : "resident \xB7 probe";
67133
67259
  };
67260
+ var roleLabel = (roles) => {
67261
+ if (!Array.isArray(roles) || roles.length === 0) return "not routed";
67262
+ const names3 = { l1: "L1 controller", l2: "L2 workers", l3: "L3 assistants", advisor: "Advisor" };
67263
+ const order = ["l1", "l2", "l3", "advisor"];
67264
+ const known = order.filter((role) => roles.includes(role)).map((role) => names3[role]);
67265
+ return known.length === 0 ? "not routed" : known.join(" + ");
67266
+ };
67134
67267
  var modelCatalog = (payload) => {
67135
67268
  const { view: view2, evidence } = payload;
67136
67269
  const policy = evidence.policy;
@@ -67140,13 +67273,15 @@ var modelCatalog = (payload) => {
67140
67273
  const local = view2.residents.map((resident) => {
67141
67274
  const detail = details.get(resident.id) ?? null;
67142
67275
  const pinned = detail?.pinned === true;
67143
- const tpsValue = detail?.tps ?? null;
67276
+ const viewTps = resident.tps;
67277
+ const tpsValue = Number.isFinite(viewTps) ? viewTps : detail?.tps ?? null;
67144
67278
  const contextLength = detail?.contextLength ?? null;
67145
67279
  const sizeBytes = detail?.sizeBytes ?? null;
67146
67280
  return {
67147
67281
  id: resident.id,
67148
67282
  state: modelStateLabel(true, tpsValue, sampleSource),
67149
- role: resident.preferred ? "default \xB7 subagent" : pinned ? "subagent \xB7 pinned" : "subagent",
67283
+ // F-37-48: the roles the settings document routes to this model.
67284
+ role: roleLabel(resident.roles) + (pinned ? " \xB7 pinned" : ""),
67150
67285
  tps: tpsValue === null ? "\u2014" : String(Math.round(tpsValue)),
67151
67286
  kv: "\u2014",
67152
67287
  context: formatContext(contextLength),
@@ -67169,7 +67304,7 @@ var modelCatalog = (payload) => {
67169
67304
  remote.push({
67170
67305
  id: entry.model,
67171
67306
  state: modelStateLabel(false, null, sampleSource),
67172
- role: `${entry.role} \xB7 remote`,
67307
+ role: roleLabel(entry.roles) + " \xB7 remote",
67173
67308
  tps: "\u2014",
67174
67309
  kv: "\u2014",
67175
67310
  context: "\u2014",
@@ -67244,11 +67379,13 @@ var ModelsPage = Html_exports.component({
67244
67379
  {
67245
67380
  label: "Memory",
67246
67381
  value: snapshot2 === null ? "\u2014" : `${gb(used)} / ${gb(max6)}`,
67247
- sub: "GB \xB7 guard \u2014"
67382
+ // F-37-48: the engine's own soft limit is the guard; unknown stays "—".
67383
+ sub: Number.isFinite(payload.view.kpis?.memorySoftBytes) ? `GB \xB7 guard ${gb(payload.view.kpis?.memorySoftBytes)}` : "GB \xB7 guard \u2014"
67248
67384
  },
67249
67385
  {
67250
67386
  label: "Concurrent",
67251
- value: snapshot2 === null ? "\u2014" : `${active2 + waiting} of \u2014`,
67387
+ // F-37-48: the ceiling the router routes against, when the engine reports it.
67388
+ value: snapshot2 === null ? "\u2014" : Number.isFinite(payload.view.kpis?.engineMax) ? `${active2 + waiting} of ${payload.view.kpis?.engineMax}` : `${active2 + waiting} of \u2014`,
67252
67389
  sub: `at ${payload.evidence.policy.floorTps} tps`
67253
67390
  },
67254
67391
  { label: "Evicted", value: "\u2014", sub: "not captured" }
@@ -68301,6 +68438,7 @@ var CONTEXT_WINDOW_LABELS = {
68301
68438
  };
68302
68439
  var NO_CAP_VALUE = "none";
68303
68440
  var NO_CAP_LABEL = "no cap";
68441
+ var CONTEXT_WINDOW_LIMITATION_NOTE = "advisory only \u2014 DSH records the model's own context window and cannot be capped per role";
68304
68442
  var rolesRows = (roles, catalogue) => {
68305
68443
  const rows = [];
68306
68444
  const known = catalogue == null ? [] : [...catalogue];
@@ -68331,6 +68469,7 @@ var rolesRows = (roles, catalogue) => {
68331
68469
  const windowOptions = role === "advisor" ? [NO_CAP_VALUE, ...CONTEXT_WINDOWS] : [...CONTEXT_WINDOWS];
68332
68470
  const windowLabels = role === "advisor" ? { [NO_CAP_VALUE]: NO_CAP_LABEL, ...CONTEXT_WINDOW_LABELS } : CONTEXT_WINDOW_LABELS;
68333
68471
  rows.push({ kind: "select", label: "context window", path: "roles." + role + ".contextWindow", value: windowValue, options: uniqueValues([...windowOptions, windowValue]), labels: windowLabels });
68472
+ if (settings.contextWindow !== null) rows.push({ kind: "note", text: CONTEXT_WINDOW_LIMITATION_NOTE });
68334
68473
  rows.push({ kind: "note", text: note });
68335
68474
  };
68336
68475
  const models = ["deepseek-flash", "deepseek-v4-pro", "flash-next"];
package/lib/build-id.js CHANGED
@@ -1,4 +1,4 @@
1
1
  // GENERATED by scripts/build-id.mjs - do not edit by hand.
2
2
  // sha256 over the canonical 19-file list (11 plugin lib + 8 domain contract
3
3
  // sources), so a domain-contract change moves the id too (DEC-30-01).
4
- export const buildId = "6a887da8bca27c824da9667ccc532d49f3509c0935d3928128876c18932c22a4"
4
+ export const buildId = "05bec211f5afe235f2510ce06128a98aa892db2e48f29d84d53d5093c2fc8bba"
@@ -12,6 +12,20 @@
12
12
  export const ENGINE_PROVIDER = "engine"
13
13
  export const ENGINE_PROVIDER_NAME = "Engine"
14
14
 
15
+ // DEC-37-11 (Owner, option C): the router owns this adapter, and DSH reads a
16
+ // model's context window ONLY from adapter.resolveModel(...).context.contextWindow
17
+ // (dsh-llm:2226/2231/2248 -> agent-loop:1079/1088 and compaction-basic:955-959).
18
+ // Registering role-scoped provider routes therefore gives a per-role window at
19
+ // spawn time, and the same number prices the role's compaction budget.
20
+ export const ROLE_PROVIDER_ROUTES = Object.freeze({
21
+ "engine-l1": "l1",
22
+ "engine-l2": "l2",
23
+ "engine-l3": "l3",
24
+ "engine-advisor": "advisor"
25
+ })
26
+ export const ROLE_PROVIDER_IDS = Object.freeze(Object.keys(ROLE_PROVIDER_ROUTES))
27
+ export const roleOfProviderRoute = (provider) => ROLE_PROVIDER_ROUTES[provider] ?? null
28
+
15
29
  /** Join the text blocks of one DSH message. */
16
30
  const textOf = (message) =>
17
31
  Array.isArray(message?.content)
@@ -157,6 +171,39 @@ const usageOf = (usage) => {
157
171
  }
158
172
  }
159
173
 
174
+ /**
175
+ * Build the per-request observation the adapter reports after a completion.
176
+ * Every field is null unless the engine actually reports it - the adapter never
177
+ * invents a token count or a timing. oMLX reports durations in seconds (a live
178
+ * 64-token request read generation_duration 0.34 s), so the observation carries
179
+ * milliseconds; the per-second rates pass through unchanged.
180
+ * @param {object} body - the assembled chat-completion body (carries the id).
181
+ * @param {object} [usage] - the engine's usage block.
182
+ * @returns {{ engineRequestId: string|null, promptTokens: number|null, completionTokens: number|null, firstTokenMs: number|null, promptEvalMs: number|null, generationMs: number|null, generationTps: number|null, promptTps: number|null }}
183
+ */
184
+ export const observationOf = (body, usage) => {
185
+ const u = usage !== null && typeof usage === "object" ? usage : body?.usage ?? {}
186
+ const finite = (value) => {
187
+ const number = Number(value)
188
+ return Number.isFinite(number) ? number : null
189
+ }
190
+ const secondsToMs = (value) => {
191
+ const number = Number(value)
192
+ return Number.isFinite(number) ? Math.round(number * 1000) : null
193
+ }
194
+ const id = typeof body?.id === "string" && body.id.length > 0 ? body.id : null
195
+ return {
196
+ engineRequestId: id,
197
+ promptTokens: finite(u.prompt_tokens),
198
+ completionTokens: finite(u.completion_tokens),
199
+ firstTokenMs: secondsToMs(u.time_to_first_token),
200
+ promptEvalMs: secondsToMs(u.prompt_eval_duration),
201
+ generationMs: secondsToMs(u.generation_duration),
202
+ generationTps: finite(u.generation_tokens_per_second),
203
+ promptTps: finite(u.prompt_tokens_per_second)
204
+ }
205
+ }
206
+
160
207
  /**
161
208
  * Convert one non-streaming chat-completion body into the harness chunk protocol.
162
209
  * @param {object} body - engine response JSON.
@@ -213,7 +260,132 @@ const engineError = (message, code) => {
213
260
  * @param {object} options - getConnection() and optional fetch/now injection.
214
261
  * @returns {object} adapter
215
262
  */
216
- export const createEngineAdapter = ({ getConnection, fetchImpl, now = Date.now, modelCapabilities = {} } = {}) => {
263
+
264
+ /**
265
+ * DEC-37-10: read an SSE chat-completions stream and assemble the full completion.
266
+ * Returns the assembled body plus the DECODE window (first delta -> last delta) and
267
+ * the engine's usage, so a request can be measured without the prefill/queue time
268
+ * that made the wall-clock number meaningless (live: 5 s wall for a cold model).
269
+ */
270
+ export const readSseCompletion = async (response, now) => {
271
+ const body = { choices: [{ index: 0, message: { role: "assistant" }, finish_reason: null }] }
272
+ let decodeStart = null
273
+ let decodeEnd = null
274
+ let content = ""
275
+ let reasoning = ""
276
+ let usage = null
277
+ let deltas = 0
278
+ const toolCalls = []
279
+ const decoder = new TextDecoder()
280
+ let buffer = ""
281
+ const note = () => {
282
+ const at = now()
283
+ if (decodeStart === null) decodeStart = at
284
+ decodeEnd = at
285
+ }
286
+ const handle = (data) => {
287
+ if (data.length === 0 || data === "[DONE]") return
288
+ let event
289
+ try {
290
+ event = JSON.parse(data)
291
+ } catch {
292
+ return
293
+ }
294
+ if (event?.usage) usage = event.usage
295
+ if (typeof event?.model === "string") body.model = event.model
296
+ if (typeof event?.id === "string") body.id = event.id
297
+ const choice = Array.isArray(event?.choices) ? event.choices[0] : undefined
298
+ if (choice === undefined || choice === null) return
299
+ if (choice.finish_reason) body.choices[0].finish_reason = choice.finish_reason
300
+ const delta = choice.delta ?? {}
301
+ const hasText = typeof delta.content === "string" && delta.content.length > 0
302
+ const hasReasoning = typeof delta.reasoning_content === "string" && delta.reasoning_content.length > 0
303
+ const hasTools = Array.isArray(delta.tool_calls) && delta.tool_calls.length > 0
304
+ if (!hasText && !hasReasoning && !hasTools) return
305
+ note()
306
+ deltas += 1
307
+ if (hasReasoning) reasoning += delta.reasoning_content
308
+ if (hasText) content += delta.content
309
+ if (hasTools) {
310
+ for (const call of delta.tool_calls) {
311
+ const index = Number.isInteger(call?.index) ? call.index : toolCalls.length
312
+ const slot = toolCalls[index] ?? (toolCalls[index] = { id: "", type: "function", function: { name: "", arguments: "" } })
313
+ if (typeof call?.id === "string" && call.id.length > 0) slot.id = call.id
314
+ if (typeof call?.function?.name === "string" && call.function.name.length > 0) slot.function.name += call.function.name
315
+ if (typeof call?.function?.arguments === "string" && call.function.arguments.length > 0) slot.function.arguments += call.function.arguments
316
+ }
317
+ }
318
+ }
319
+ const reader = response.body.getReader()
320
+ for (;;) {
321
+ const { done, value } = await reader.read()
322
+ if (done === true) break
323
+ buffer += decoder.decode(value, { stream: true })
324
+ let newline = buffer.indexOf("\n")
325
+ while (newline >= 0) {
326
+ const line = buffer.slice(0, newline).trimEnd()
327
+ buffer = buffer.slice(newline + 1)
328
+ if (line.startsWith("data:")) handle(line.slice(5).trim())
329
+ newline = buffer.indexOf("\n")
330
+ }
331
+ }
332
+ if (buffer.startsWith("data:")) handle(buffer.slice(5).trim())
333
+ const message = body.choices[0].message
334
+ if (reasoning.length > 0) message.reasoning_content = reasoning
335
+ if (content.length > 0) message.content = content
336
+ const calls = toolCalls.filter((call) => call !== undefined && call !== null)
337
+ if (calls.length > 0) message.tool_calls = calls
338
+ const tokens = Number.isFinite(Number(usage?.completion_tokens)) && Number(usage.completion_tokens) > 0
339
+ ? Number(usage.completion_tokens)
340
+ : deltas
341
+ return { body, decodeStart, decodeEnd, usage, tokens }
342
+ }
343
+
344
+ export const createEngineAdapter = ({ getConnection, fetchImpl, now = Date.now, modelCapabilities = {}, onRequestSpeed = null, onRequestObserved = null, roleWindowFor = null } = {}) => {
345
+ // The role's configured context window for a role-scoped provider route, or null
346
+ // when the route is not role-scoped / the role has no finite window (the Advisor's
347
+ // "no cap", DEC-37-05).
348
+ const roleWindowOf = (provider) => {
349
+ const role = roleOfProviderRoute(provider)
350
+ if (role === null || typeof roleWindowFor !== "function") return null
351
+ try {
352
+ const window = roleWindowFor(role)
353
+ return Number.isFinite(window) && window > 0 ? Math.trunc(window) : null
354
+ } catch {
355
+ return null
356
+ }
357
+ }
358
+ // DEC-37-10 (Owner): the engine's /admin/api/stats only exposes LIFETIME
359
+ // aggregates (722,359 completion tokens over 63,347 s -> 18.2 tps), which must
360
+ // never drive routing. Every request this adapter proxies is therefore measured
361
+ // as a fresh observation: completion tokens over the wall time of the call.
362
+ // Non-streaming on the wire (stream:false below), so the decode window cannot be
363
+ // isolated exactly; this is a real per-request observation, not an average.
364
+ const reportTps = (model, tps) => {
365
+ if (typeof onRequestSpeed !== "function") return
366
+ if (!Number.isFinite(tps) || tps <= 0) return
367
+ try {
368
+ onRequestSpeed(model, tps)
369
+ } catch {}
370
+ }
371
+ const reportSpeed = (model, decodeStart, decodeEnd, tokens) => {
372
+ if (typeof onRequestSpeed !== "function") return
373
+ if (!Number.isFinite(tokens) || tokens <= 0) return
374
+ const elapsedMs = decodeEnd - decodeStart
375
+ if (!Number.isFinite(elapsedMs) || elapsedMs <= 0) return
376
+ try {
377
+ onRequestSpeed(model, tokens / (elapsedMs / 1000))
378
+ } catch {}
379
+ }
380
+ // DEC-37-12: every proxied request also forwards its engine id and token/timing
381
+ // usage as one observation, so the ledger can join the local per-request facts
382
+ // (context tokens, oMLX request id) that the Activity page otherwise cannot see.
383
+ const reportObserved = (model, observation) => {
384
+ if (typeof onRequestObserved !== "function") return
385
+ try {
386
+ onRequestObserved(model, observation)
387
+ } catch {}
388
+ }
217
389
  const doFetch = typeof fetchImpl === "function" ? fetchImpl : (...args) => globalThis.fetch(...args)
218
390
  let cache = { at: Number.NEGATIVE_INFINITY, base: "", models: [] }
219
391
  // Last capability reconciliation: which sources answered, what was excluded.
@@ -242,11 +414,13 @@ export const createEngineAdapter = ({ getConnection, fetchImpl, now = Date.now,
242
414
  // Context length comes from the engine's own admin metadata; when the engine
243
415
  // does not report one it stays omitted rather than invented.
244
416
  const modelInfo = (provider, entry) => {
245
- const contextWindow = Number.isFinite(entry.contextWindow)
417
+ const engineWindow = Number.isFinite(entry.contextWindow)
246
418
  ? entry.contextWindow
247
419
  : Number.isFinite(entry.context?.contextWindow)
248
420
  ? entry.context.contextWindow
249
421
  : null
422
+ // DEC-37-11: a role route wins over the engine's advertised window.
423
+ const contextWindow = roleWindowOf(provider) ?? engineWindow
250
424
  const modalities = Array.isArray(entry.inputModalities) ? entry.inputModalities : ["text"]
251
425
  return {
252
426
  id: entry.id,
@@ -413,7 +587,8 @@ export const createEngineAdapter = ({ getConnection, fetchImpl, now = Date.now,
413
587
  const payload = {
414
588
  model,
415
589
  messages: serializeMessages(options),
416
- stream: false,
590
+ stream: true,
591
+ stream_options: { include_usage: true },
417
592
  ...Array.isArray(options?.tools) && options.tools.length > 0 ? { tools: serializeTools(options.tools) } : {},
418
593
  ...Number.isFinite(options?.temperature) ? { temperature: options.temperature } : {},
419
594
  ...Number.isFinite(options?.maxTokens) ? { max_tokens: options.maxTokens } : {},
@@ -426,6 +601,40 @@ export const createEngineAdapter = ({ getConnection, fetchImpl, now = Date.now,
426
601
  if (options?.signal?.aborted === true) throw engineError("engine request aborted", "ABORTED")
427
602
  throw engineError("engine transport failed: " + (error?.message ?? String(error)), "TRANSPORT")
428
603
  }
604
+ if (!response.ok) {
605
+ let detail = ""
606
+ try {
607
+ detail = String(await response.text()).slice(0, 240)
608
+ } catch {}
609
+ const code = response.status === 401 || response.status === 403 ? "AUTH" : response.status === 429 ? "RATE_LIMIT" : response.status >= 500 ? "SERVER" : "INVALID_REQUEST"
610
+ throw engineError("engine chat request failed (" + response.status + "): " + detail, code)
611
+ }
612
+ // DEC-37-10 (Owner): the engine exposes only LIFETIME aggregates, so every
613
+ // proxied request is measured itself: decode window (first delta -> last
614
+ // delta) over the engine's completion tokens. Streaming is what makes the
615
+ // window observable; a non-streaming body falls back to no measurement
616
+ // rather than recording the wall time (which includes model load/prefill).
617
+ if (typeof response.body?.getReader === "function") {
618
+ let assembled
619
+ try {
620
+ assembled = await readSseCompletion(response, now)
621
+ } catch (error) {
622
+ if (options?.signal?.aborted === true) throw engineError("engine request aborted", "ABORTED")
623
+ throw engineError("engine stream read failed: " + (error?.message ?? String(error)), "TRANSPORT")
624
+ }
625
+ // oMLX reports the per-request generation speed in the usage block
626
+ // (generation_tokens_per_second) - a true fresh observation from a past
627
+ // request. Prefer it; fall back to our own decode-window measurement.
628
+ const reported = Number(assembled.usage?.generation_tokens_per_second)
629
+ if (Number.isFinite(reported) && reported > 0) {
630
+ reportTps(model, reported)
631
+ } else if (assembled.decodeStart !== null && assembled.decodeEnd !== null) {
632
+ reportSpeed(model, assembled.decodeStart, assembled.decodeEnd, assembled.tokens)
633
+ }
634
+ reportObserved(model, observationOf(assembled.body, assembled.usage))
635
+ for (const chunk of toChunks(assembled.body)) yield chunk
636
+ return
637
+ }
429
638
  let text
430
639
  try {
431
640
  text = await response.text()
@@ -433,16 +642,13 @@ export const createEngineAdapter = ({ getConnection, fetchImpl, now = Date.now,
433
642
  if (options?.signal?.aborted === true) throw engineError("engine request aborted", "ABORTED")
434
643
  throw engineError("engine body read failed: " + (error?.message ?? String(error)), "TRANSPORT")
435
644
  }
436
- if (!response.ok) {
437
- const code = response.status === 401 || response.status === 403 ? "AUTH" : response.status === 429 ? "RATE_LIMIT" : response.status >= 500 ? "SERVER" : "INVALID_REQUEST"
438
- throw engineError("engine chat request failed (" + response.status + "): " + text.slice(0, 240), code)
439
- }
440
645
  let body
441
646
  try {
442
647
  body = JSON.parse(text)
443
648
  } catch {
444
649
  throw engineError("engine returned a non-JSON chat response", "SERVER")
445
650
  }
651
+ reportObserved(model, observationOf(body, body?.usage))
446
652
  for (const chunk of toChunks(body)) yield chunk
447
653
  })()
448
654
  }