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