@try-works/dsh-minimal-router 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +1 -0
- package/README.md +69 -2
- package/client/index.js +70039 -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 +657 -0
- package/lib/evidence.js +1107 -0
- package/lib/host.js +554 -0
- package/lib/index.js +2299 -0
- package/lib/route-application.js +780 -0
- package/lib/routing.js +858 -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 +1019 -0
- package/lib/tool-result-pruner.js +224 -0
- package/package.json +38 -4
|
@@ -0,0 +1,770 @@
|
|
|
1
|
+
// @dsh-local-router/plugin — Router Settings document (Run 25, spec boards 13/14).
|
|
2
|
+
//
|
|
3
|
+
// Plain JS because the host runtime is plain JS (lib/*.js). The typed mirror of
|
|
4
|
+
// the contract lives in packages/domain/src/context-settings.ts and roles.ts.
|
|
5
|
+
//
|
|
6
|
+
// Run 25 repair (review B3/B6): the runtime is a *strict whole-document*
|
|
7
|
+
// validator, not a validator of the two rules it happened to carry. It refuses
|
|
8
|
+
// everything the typed schema refuses - unknown keys (closed structs), a missing
|
|
9
|
+
// role, an advisor parent other than l1, a fallback that is not a non-empty
|
|
10
|
+
// string, and a context fragment without prune - and returns the same
|
|
11
|
+
// { ok:false, invalid:true, field, message } shape the page marks. A document
|
|
12
|
+
// that reaches the store is therefore always loadable by the typed side.
|
|
13
|
+
//
|
|
14
|
+
// It also owns the pure helpers the host needs:
|
|
15
|
+
// loadSettingsOr(file, readFile) - boot persistence, defaults on absent,
|
|
16
|
+
// corrupt or invalid bytes (review B2: nothing loaded the saved document).
|
|
17
|
+
// budgetFromContext(context) - the context.prune -> tool-result pruner
|
|
18
|
+
// budget adapter, so the saved document is consumed rather than dead.
|
|
19
|
+
// resolvePrunePlan(context, configPrune, options) - Run 35: the saved document
|
|
20
|
+
// decides prune enabled/mode/trigger; config.prune is only the fallback.
|
|
21
|
+
// resolveToolSubset(context, inheritedNames) - Run 35 (DEC-35-11): the saved
|
|
22
|
+
// tool subset as an allowlist over the page vocabulary (the 9 core tools),
|
|
23
|
+
// against the names this agent can actually be restricted to.
|
|
24
|
+
|
|
25
|
+
import { readFileSync } from "node:fs"
|
|
26
|
+
// The pruner vocabulary is the runtime truth; the page's "summary" maps into it.
|
|
27
|
+
import { MODES as PRUNER_MODES } from "./tool-result-pruner.js"
|
|
28
|
+
|
|
29
|
+
// DEC-35-11 (Owner): the page vocabulary P is a lean ALLOWLIST, not a subtraction.
|
|
30
|
+
// A subagent starts with exactly these 9 core tools as named tools. skill and
|
|
31
|
+
// ask_user_question are NOT given by default; every other tool (skill,
|
|
32
|
+
// ask_user_question, mcp__paper__*, the agent-team tools, anything else) is NOT
|
|
33
|
+
// handed out as a named tool - the child DISCOVERS and EXECUTES it through
|
|
34
|
+
// run_code, which is the reserved PTC transport and is always available
|
|
35
|
+
// (tools.restrict() refuses to name it, so it can never be masked). run_code is
|
|
36
|
+
// therefore deliberately absent from P; a saved id outside P is ignored with one
|
|
37
|
+
// warning at spawn time, never thrown.
|
|
38
|
+
export const DEFAULT_TOOLS = [
|
|
39
|
+
"read", "write", "edit", "bash", "grep", "glob",
|
|
40
|
+
"todo_write", "working_directory", "subagent"
|
|
41
|
+
]
|
|
42
|
+
|
|
43
|
+
export const PRUNE_MODES = ["reference", "summary", "off"]
|
|
44
|
+
export const PRUNE_TRIGGERS = ["auto", "always", "off"]
|
|
45
|
+
export const IDENTIFIER_MODES = ["index", "drop"]
|
|
46
|
+
|
|
47
|
+
// R-37-03: per-role context window (tokens), default 131k. The window is a role
|
|
48
|
+
// property applied to whatever model the role uses, not a per-model pin.
|
|
49
|
+
// DEC-37-05: the Advisor is a larger remote model and defaults to null (no cap);
|
|
50
|
+
// the numbered levels default to 131k.
|
|
51
|
+
export const DEFAULT_ROLE_WINDOW = 131000
|
|
52
|
+
const roleModels = (model, fallbacks, enabled, floorTps, contextWindow = DEFAULT_ROLE_WINDOW) => ({ model, fallbacks: [...fallbacks], enabled, floorTps, contextWindow })
|
|
53
|
+
|
|
54
|
+
export const defaultSettings = () => ({
|
|
55
|
+
context: {
|
|
56
|
+
toolSubset: { enabled: true, tools: [...DEFAULT_TOOLS] },
|
|
57
|
+
prune: { enabled: true, mode: "reference", trigger: "auto", trimAbove: 20000, keepHead: 10000, keepTail: 4000, spill: true },
|
|
58
|
+
lazySummary: { enabled: true, model: "agent", reserve: 4096, perResult: 1, identifiers: "index" }
|
|
59
|
+
},
|
|
60
|
+
roles: {
|
|
61
|
+
l1: roleModels("deepseek-flash", ["deepseek-v4-pro", "flash-next"], true, 35),
|
|
62
|
+
l2: roleModels("flash-next", ["deepseek-flash"], true, 45),
|
|
63
|
+
l3: roleModels("flash-next", [], true, 40),
|
|
64
|
+
advisor: { ...roleModels("deepseek-v4-pro", [], true, 30, null), parent: "l1" }
|
|
65
|
+
},
|
|
66
|
+
rev: 1,
|
|
67
|
+
// Host-derived, read-only: the model window the Settings page may rely on.
|
|
68
|
+
// null means the host does not know it, so the reserve cap cannot be applied.
|
|
69
|
+
windowTokens: null,
|
|
70
|
+
// Host-derived, read-only: the engine's model catalogue. null means the host
|
|
71
|
+
// does not know it (engine unreachable), so the membership rule is skipped
|
|
72
|
+
// and the page shows the catalogue-stale state instead of a stale list.
|
|
73
|
+
catalogue: null
|
|
74
|
+
})
|
|
75
|
+
|
|
76
|
+
export const ROLE_IDS = ["l1", "l2", "l3", "advisor"]
|
|
77
|
+
const alwaysOn = (role) => role === "l1" || role === "l2" || role === "advisor"
|
|
78
|
+
|
|
79
|
+
// Owner (2026-12-03): L1, L2 and the Advisor cannot be off, and the page has no
|
|
80
|
+
// switch to say so. An older document that stored "enabled: false" is repaired
|
|
81
|
+
// on read and on write instead of being refused, which would leave the page
|
|
82
|
+
// permanently unsaveable with no control to fix it.
|
|
83
|
+
export const normaliseAlwaysOnRoles = (roles) => {
|
|
84
|
+
if (roles === null || typeof roles !== "object" || Array.isArray(roles)) return roles
|
|
85
|
+
const next = { ...roles }
|
|
86
|
+
for (const role of ["l1", "l2", "advisor"]) {
|
|
87
|
+
const entry = next[role]
|
|
88
|
+
if (entry !== null && typeof entry === "object" && !Array.isArray(entry) && entry.enabled !== true) {
|
|
89
|
+
next[role] = { ...entry, enabled: true }
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
// R-37-03/DEC-37-05: fill a missing per-role context window so older documents
|
|
93
|
+
// (rev 15) load without failing validation. The numbered levels fill to 131k;
|
|
94
|
+
// the Advisor fills to null (no cap), and an already-null Advisor is left as is.
|
|
95
|
+
for (const role of ROLE_IDS) {
|
|
96
|
+
const entry = next[role]
|
|
97
|
+
if (entry !== null && typeof entry === "object" && !Array.isArray(entry) &&
|
|
98
|
+
entry.contextWindow !== null && typeof entry.contextWindow !== "number") {
|
|
99
|
+
next[role] = { ...entry, contextWindow: role === "advisor" ? null : DEFAULT_ROLE_WINDOW }
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
return next
|
|
103
|
+
}
|
|
104
|
+
const validFloor = (value) => Number.isFinite(value) && Number.isInteger(value) && value >= 0 && value <= 100
|
|
105
|
+
|
|
106
|
+
// Run 36 (R-36-09, DEC-36-13): DSH's subagent.maxDepth is the source of truth
|
|
107
|
+
// for the Assistants switch. depth >= 2 allows the depth-2 child (L3); 1 does
|
|
108
|
+
// not. roles.l3.enabled is a mirror kept in step on read and on write.
|
|
109
|
+
export const l3EnabledFromMaxDepth = (maxDepth) => Number.isInteger(maxDepth) && maxDepth >= 2
|
|
110
|
+
export const maxDepthFromL3Enabled = (enabled) => (enabled === true ? 2 : 1)
|
|
111
|
+
|
|
112
|
+
// --- shape helpers ---
|
|
113
|
+
// Every helper pushes { field, message } with the field path the page marks, so
|
|
114
|
+
// callers never have to translate a nested path.
|
|
115
|
+
|
|
116
|
+
const isRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value)
|
|
117
|
+
const isNonEmptyString = (value) => typeof value === "string" && value.trim().length > 0
|
|
118
|
+
|
|
119
|
+
const KEYS = {
|
|
120
|
+
document: ["context", "roles", "rev", "windowTokens", "catalogue"],
|
|
121
|
+
context: ["toolSubset", "prune", "lazySummary"],
|
|
122
|
+
toolSubset: ["enabled", "tools"],
|
|
123
|
+
prune: ["enabled", "mode", "trigger", "trimAbove", "keepHead", "keepTail", "spill"],
|
|
124
|
+
lazySummary: ["enabled", "model", "reserve", "perResult", "identifiers"],
|
|
125
|
+
roles: ["l1", "l2", "l3", "advisor"],
|
|
126
|
+
role: ["model", "fallbacks", "enabled", "floorTps", "contextWindow"],
|
|
127
|
+
advisor: ["model", "fallbacks", "enabled", "floorTps", "contextWindow", "parent"]
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
const push = (issues, field, message) => {
|
|
131
|
+
issues.push({ field, message })
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** A closed record: unknown keys are refused, not carried into the document. */
|
|
135
|
+
const closedRecord = (value, field, allowed, issues) => {
|
|
136
|
+
if (!isRecord(value)) {
|
|
137
|
+
if (field.length > 0) push(issues, field, "must be an object")
|
|
138
|
+
else push(issues, "document", "must be an object")
|
|
139
|
+
return null
|
|
140
|
+
}
|
|
141
|
+
for (const key of Object.keys(value)) {
|
|
142
|
+
if (!allowed.includes(key)) push(issues, field.length > 0 ? field + "." + key : key, "unknown field")
|
|
143
|
+
}
|
|
144
|
+
return value
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
const booleanField = (value, field, issues) => {
|
|
148
|
+
if (typeof value !== "boolean") push(issues, field, "must be true or false")
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
const numberField = (value, field, issues) => {
|
|
152
|
+
if (typeof value !== "number" || !Number.isFinite(value)) push(issues, field, "must be a number")
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
// DEC-37-05: a role's context window may be null (the Advisor's "no cap").
|
|
156
|
+
const nullableNumberField = (value, field, issues) => {
|
|
157
|
+
if (value !== null && (typeof value !== "number" || !Number.isFinite(value))) push(issues, field, "must be a number or null")
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
const stringField = (value, field, issues) => {
|
|
161
|
+
if (typeof value !== "string") push(issues, field, "must be a string")
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
const literalField = (value, field, allowed, issues) => {
|
|
165
|
+
if (!allowed.includes(value)) push(issues, field, "must be one of " + allowed.join(", "))
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
const stringListField = (value, field, itemMessage, issues) => {
|
|
169
|
+
if (!Array.isArray(value)) {
|
|
170
|
+
push(issues, field, "must be a list")
|
|
171
|
+
return
|
|
172
|
+
}
|
|
173
|
+
value.forEach((item, index) => {
|
|
174
|
+
if (!isNonEmptyString(item)) push(issues, field + "." + index, itemMessage)
|
|
175
|
+
})
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
export const validateContextShape = (context, issues = []) => {
|
|
179
|
+
const section = closedRecord(context, "context", KEYS.context, issues)
|
|
180
|
+
if (section === null) return issues
|
|
181
|
+
const toolSubset = closedRecord(section.toolSubset, "context.toolSubset", KEYS.toolSubset, issues)
|
|
182
|
+
if (toolSubset !== null) {
|
|
183
|
+
booleanField(toolSubset.enabled, "context.toolSubset.enabled", issues)
|
|
184
|
+
stringListField(toolSubset.tools, "context.toolSubset.tools", "must be a tool name", issues)
|
|
185
|
+
}
|
|
186
|
+
const prune = closedRecord(section.prune, "context.prune", KEYS.prune, issues)
|
|
187
|
+
if (prune !== null) {
|
|
188
|
+
booleanField(prune.enabled, "context.prune.enabled", issues)
|
|
189
|
+
literalField(prune.mode, "context.prune.mode", PRUNE_MODES, issues)
|
|
190
|
+
literalField(prune.trigger, "context.prune.trigger", PRUNE_TRIGGERS, issues)
|
|
191
|
+
numberField(prune.trimAbove, "context.prune.trimAbove", issues)
|
|
192
|
+
numberField(prune.keepHead, "context.prune.keepHead", issues)
|
|
193
|
+
numberField(prune.keepTail, "context.prune.keepTail", issues)
|
|
194
|
+
booleanField(prune.spill, "context.prune.spill", issues)
|
|
195
|
+
}
|
|
196
|
+
const lazySummary = closedRecord(section.lazySummary, "context.lazySummary", KEYS.lazySummary, issues)
|
|
197
|
+
if (lazySummary !== null) {
|
|
198
|
+
booleanField(lazySummary.enabled, "context.lazySummary.enabled", issues)
|
|
199
|
+
stringField(lazySummary.model, "context.lazySummary.model", issues)
|
|
200
|
+
numberField(lazySummary.reserve, "context.lazySummary.reserve", issues)
|
|
201
|
+
numberField(lazySummary.perResult, "context.lazySummary.perResult", issues)
|
|
202
|
+
literalField(lazySummary.identifiers, "context.lazySummary.identifiers", IDENTIFIER_MODES, issues)
|
|
203
|
+
}
|
|
204
|
+
return issues
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
export const validateRolesShape = (roles, issues = []) => {
|
|
208
|
+
const section = closedRecord(roles, "roles", KEYS.roles, issues)
|
|
209
|
+
if (section === null) return issues
|
|
210
|
+
for (const role of ROLE_IDS) {
|
|
211
|
+
if (section[role] === undefined) {
|
|
212
|
+
push(issues, "roles." + role, "role is required")
|
|
213
|
+
continue
|
|
214
|
+
}
|
|
215
|
+
const settings = closedRecord(section[role], "roles." + role, role === "advisor" ? KEYS.advisor : KEYS.role, issues)
|
|
216
|
+
if (settings === null) continue
|
|
217
|
+
stringField(settings.model, "roles." + role + ".model", issues)
|
|
218
|
+
stringListField(settings.fallbacks, "roles." + role + ".fallbacks", "must be a model id", issues)
|
|
219
|
+
booleanField(settings.enabled, "roles." + role + ".enabled", issues)
|
|
220
|
+
numberField(settings.floorTps, "roles." + role + ".floorTps", issues)
|
|
221
|
+
nullableNumberField(settings.contextWindow, "roles." + role + ".contextWindow", issues)
|
|
222
|
+
if (role === "advisor" && settings.parent !== "l1") {
|
|
223
|
+
push(issues, "roles.advisor.parent", "advisor parent must be l1")
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
return issues
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/**
|
|
230
|
+
* The whole document, shape first and rules second. A shape issue returns before
|
|
231
|
+
* any semantic rule reads the fragment, so a missing prune is a named 400 and
|
|
232
|
+
* never a TypeError. Issue fields are absolute (context./roles. prefixed).
|
|
233
|
+
*/
|
|
234
|
+
export const validateDocument = (document, windowTokens, catalogue) => {
|
|
235
|
+
const issues = []
|
|
236
|
+
const root = closedRecord(document, "", KEYS.document, issues)
|
|
237
|
+
if (root === null) return issues
|
|
238
|
+
validateContextShape(root.context, issues)
|
|
239
|
+
validateRolesShape(root.roles, issues)
|
|
240
|
+
if (!Number.isInteger(root.rev) || root.rev < 1) push(issues, "rev", "must be a whole number")
|
|
241
|
+
// windowTokens is the only host-derived field: it must be absent or null, or a
|
|
242
|
+
// positive whole number. A stored number is never trusted (the loader nulls it).
|
|
243
|
+
if (root.windowTokens !== undefined && root.windowTokens !== null && (!Number.isInteger(root.windowTokens) || root.windowTokens <= 0)) {
|
|
244
|
+
push(issues, "windowTokens", "must be null or a positive whole number")
|
|
245
|
+
}
|
|
246
|
+
if (root.catalogue !== undefined && root.catalogue !== null) {
|
|
247
|
+
if (!Array.isArray(root.catalogue)) {
|
|
248
|
+
push(issues, "catalogue", "must be null or a list of model ids")
|
|
249
|
+
} else {
|
|
250
|
+
root.catalogue.forEach((id, index) => {
|
|
251
|
+
if (!isNonEmptyString(id)) push(issues, "catalogue." + index, "must be a model id")
|
|
252
|
+
})
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
if (issues.length > 0) return issues
|
|
256
|
+
// Both host-derived facts are only trusted when the caller supplies them; a
|
|
257
|
+
// value carried in the document itself is never used to judge the document.
|
|
258
|
+
const knownWindow = typeof windowTokens === "number" ? windowTokens : undefined
|
|
259
|
+
const knownCatalogue = Array.isArray(catalogue) ? catalogue : undefined
|
|
260
|
+
for (const issue of validateContext(root.context, knownWindow)) issues.push({ field: "context." + issue.field, message: issue.message })
|
|
261
|
+
for (const issue of validateRoles(root.roles, knownCatalogue)) issues.push({ field: "roles." + issue.field, message: issue.message })
|
|
262
|
+
return issues
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
// --- semantic rules (unchanged; callers reach them through validateDocument) --
|
|
266
|
+
|
|
267
|
+
export const validateContext = (context, windowTokens) => {
|
|
268
|
+
const issues = []
|
|
269
|
+
const { prune, toolSubset, lazySummary } = context
|
|
270
|
+
if (prune.keepHead + prune.keepTail > prune.trimAbove) {
|
|
271
|
+
issues.push({ field: "prune.keepTail", message: "head + tail exceed trim above" })
|
|
272
|
+
}
|
|
273
|
+
if (toolSubset.enabled && toolSubset.tools.length === 0) {
|
|
274
|
+
issues.push({ field: "toolSubset.tools", message: "choose at least one tool" })
|
|
275
|
+
}
|
|
276
|
+
if (typeof windowTokens === "number" && lazySummary.reserve > windowTokens / 4) {
|
|
277
|
+
issues.push({ field: "lazySummary.reserve", message: "reserve exceeds a quarter of the window" })
|
|
278
|
+
}
|
|
279
|
+
if (lazySummary.perResult < 1) {
|
|
280
|
+
issues.push({ field: "lazySummary.perResult", message: "at least one per turn" })
|
|
281
|
+
}
|
|
282
|
+
return issues
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
export const validateRoles = (roles, catalogue) => {
|
|
286
|
+
const issues = []
|
|
287
|
+
for (const role of ROLE_IDS) {
|
|
288
|
+
const settings = roles[role]
|
|
289
|
+
if (settings === undefined) continue
|
|
290
|
+
const seen = new Set([settings.model])
|
|
291
|
+
settings.fallbacks.forEach((model, index) => {
|
|
292
|
+
if (seen.has(model)) {
|
|
293
|
+
issues.push({ field: role + ".fallbacks." + String(index), message: "already in this chain" })
|
|
294
|
+
return
|
|
295
|
+
}
|
|
296
|
+
seen.add(model)
|
|
297
|
+
})
|
|
298
|
+
if (!validFloor(settings.floorTps)) {
|
|
299
|
+
issues.push({ field: role + ".floorTps", message: "floor must be 0-100 tps" })
|
|
300
|
+
}
|
|
301
|
+
if (alwaysOn(role) && settings.enabled !== true) {
|
|
302
|
+
issues.push({ field: role + ".enabled", message: role === "advisor" ? "the Advisor is always on" : "L1 and L2 are always on" })
|
|
303
|
+
}
|
|
304
|
+
if (Array.isArray(catalogue)) {
|
|
305
|
+
// Run 25 verifier fix: name the entry that is actually missing. The chain
|
|
306
|
+
// is [primary, ...fallbacks]; the primary is roles.<role>.model and a
|
|
307
|
+
// fallback is roles.<role>.fallbacks.<index> (the page marks that row).
|
|
308
|
+
const chain = [settings.model, ...settings.fallbacks]
|
|
309
|
+
for (let index = 0; index < chain.length; index += 1) {
|
|
310
|
+
if (!catalogue.includes(chain[index])) {
|
|
311
|
+
issues.push({
|
|
312
|
+
field: index === 0 ? role + ".model" : role + ".fallbacks." + String(index - 1),
|
|
313
|
+
message: "not in the catalogue"
|
|
314
|
+
})
|
|
315
|
+
break
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
return issues
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
// --- boot persistence --------------------------------------------------------
|
|
324
|
+
|
|
325
|
+
/**
|
|
326
|
+
* The document on disk, or the defaults. A stored document that the schema
|
|
327
|
+
* refuses is treated exactly like corrupt bytes, with ONE exception (Run 35
|
|
328
|
+
* repair, FIX 2): an unknown prune mode keeps the document as loaded, because
|
|
329
|
+
* replacing it with defaults both discards the user's settings and silently
|
|
330
|
+
* re-enables pruning. The reader is injected so the fallbacks are unit-testable
|
|
331
|
+
* without touching the filesystem. `unknownPruneMode` names the value the host
|
|
332
|
+
* must warn about; the pruner resolves off with reason "unknown mode <x>".
|
|
333
|
+
*/
|
|
334
|
+
export const loadSettingsWithSource = (file, readFile = (target) => readFileSync(target, "utf8")) => {
|
|
335
|
+
try {
|
|
336
|
+
const parsed = JSON.parse(readFile(file))
|
|
337
|
+
// windowTokens and catalogue are host-derived and read-only: a stored value
|
|
338
|
+
// (from an older host or a hand-edited file) loads as null so the current
|
|
339
|
+
// telemetry / engine wins and a stale list can never be judged against.
|
|
340
|
+
const normalized = { ...parsed, windowTokens: null, catalogue: null, roles: normaliseAlwaysOnRoles(parsed.roles) }
|
|
341
|
+
const issues = validateDocument(normalized)
|
|
342
|
+
if (issues.length === 0) return { document: normalized, source: "file" }
|
|
343
|
+
// Run 35 repair (FIX 2, verifier finding A): one unknown prune mode is a
|
|
344
|
+
// typo, not a corrupt document. Refusing the whole document used to replace
|
|
345
|
+
// rev, roles, subset and prune with the defaults - and the default reference
|
|
346
|
+
// pruner then ran with no warning, pruning behind the user's back. Keep the
|
|
347
|
+
// document as loaded instead: resolvePrunePlan disables pruning with reason
|
|
348
|
+
// "unknown mode <x>" and the host warns once. Any other invalid field still
|
|
349
|
+
// falls back to the defaults.
|
|
350
|
+
const storedMode = normalized?.context?.prune?.mode
|
|
351
|
+
const unknownModeOnly =
|
|
352
|
+
issues.length === 1 &&
|
|
353
|
+
issues[0].field === "context.prune.mode" &&
|
|
354
|
+
typeof storedMode === "string" &&
|
|
355
|
+
!PRUNE_MODES.includes(storedMode)
|
|
356
|
+
if (unknownModeOnly) return { document: normalized, source: "file", unknownPruneMode: storedMode }
|
|
357
|
+
} catch {}
|
|
358
|
+
// No usable document: the store may still derive its role chain from the live
|
|
359
|
+
// catalogue once it is known (run 25 verifier root cause).
|
|
360
|
+
return { document: defaultSettings(), source: "default" }
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
export const loadSettingsOr = (file, readFile) => loadSettingsWithSource(file, readFile).document
|
|
364
|
+
|
|
365
|
+
/**
|
|
366
|
+
* Run 25 verifier root cause: the default role chain must derive from the LIVE
|
|
367
|
+
* catalogue, never from hard-coded ids a host may not advertise. Rules:
|
|
368
|
+
* l1.model is the policy main model when the catalogue has it, else the first
|
|
369
|
+
* catalogue id; l2.model and l3.model are the first engine/configured-local id
|
|
370
|
+
* (a child runs locally when a local model exists), else the first catalogue id;
|
|
371
|
+
* the remaining ids become ordered fallbacks, two for l1 and one for l2,
|
|
372
|
+
* skipping ids already used in that chain. Floors keep the designed
|
|
373
|
+
* 35/45/40/30. Without a catalogue the fixed defaults are all the host has.
|
|
374
|
+
*/
|
|
375
|
+
export const defaultSettingsFor = (catalogue, options = {}) => {
|
|
376
|
+
const ids = Array.isArray(catalogue) ? [...new Set(catalogue.filter((id) => isNonEmptyString(id)))] : []
|
|
377
|
+
if (ids.length === 0) return defaultSettings()
|
|
378
|
+
const localIds = Array.isArray(options.localIds)
|
|
379
|
+
? new Set(options.localIds.filter((id) => isNonEmptyString(id)))
|
|
380
|
+
: null
|
|
381
|
+
const mainModel = isNonEmptyString(options.mainModel) ? options.mainModel : null
|
|
382
|
+
const l1Model = mainModel !== null && ids.includes(mainModel) ? mainModel : ids[0]
|
|
383
|
+
const localModel = localIds === null ? ids[0] : ids.find((id) => localIds.has(id)) ?? ids[0]
|
|
384
|
+
const nextIds = (used, count) => ids.filter((id) => !used.includes(id)).slice(0, count)
|
|
385
|
+
return {
|
|
386
|
+
context: defaultSettings().context,
|
|
387
|
+
roles: {
|
|
388
|
+
l1: roleModels(l1Model, nextIds([l1Model], 2), true, 35),
|
|
389
|
+
l2: roleModels(localModel, nextIds([localModel], 1), true, 45),
|
|
390
|
+
l3: roleModels(localModel, [], true, 40),
|
|
391
|
+
advisor: { ...roleModels(l1Model, [], true, 30), parent: "l1" }
|
|
392
|
+
},
|
|
393
|
+
rev: 1,
|
|
394
|
+
windowTokens: null,
|
|
395
|
+
catalogue: null
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
/**
|
|
400
|
+
* The model window the host can honestly report: the largest context length
|
|
401
|
+
* among the snapshot's resident models (the oMLX snapshot carries it as
|
|
402
|
+
* model.contextLength; an engine-shaped contextWindow is accepted too). Null
|
|
403
|
+
* when there is no snapshot or none of its models reports a window, because a
|
|
404
|
+
* guessed window would make the reserve cap lie.
|
|
405
|
+
*/
|
|
406
|
+
export const windowTokensFromSnapshot = (snapshot) => {
|
|
407
|
+
if (!isRecord(snapshot) || !Array.isArray(snapshot.models)) return null
|
|
408
|
+
let window = null
|
|
409
|
+
for (const model of snapshot.models) {
|
|
410
|
+
if (!isRecord(model)) continue
|
|
411
|
+
const candidate = Number.isInteger(model.contextLength) && model.contextLength > 0
|
|
412
|
+
? model.contextLength
|
|
413
|
+
: Number.isInteger(model.contextWindow) && model.contextWindow > 0
|
|
414
|
+
? model.contextWindow
|
|
415
|
+
: null
|
|
416
|
+
if (candidate !== null && (window === null || candidate > window)) window = candidate
|
|
417
|
+
}
|
|
418
|
+
return window
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
// --- context fragment -> pruner budget --------------------------------------
|
|
422
|
+
|
|
423
|
+
/**
|
|
424
|
+
* Map context.prune to the fields resolveBudget() consumes. Returns null when
|
|
425
|
+
* the fragment cannot supply a whole budget, and the host then keeps its
|
|
426
|
+
* config.prune path. spill is carried through because it decides whether
|
|
427
|
+
* reference mode can honestly retain a body.
|
|
428
|
+
*/
|
|
429
|
+
export const budgetFromContext = (context) => {
|
|
430
|
+
if (!isRecord(context) || !isRecord(context.prune)) return null
|
|
431
|
+
const { trimAbove, keepHead, keepTail, spill } = context.prune
|
|
432
|
+
if (!Number.isInteger(trimAbove) || trimAbove <= 0) return null
|
|
433
|
+
if (!Number.isInteger(keepHead) || keepHead < 0) return null
|
|
434
|
+
if (!Number.isInteger(keepTail) || keepTail < 0) return null
|
|
435
|
+
if (typeof spill !== "boolean") return null
|
|
436
|
+
return { maxChars: trimAbove, headChars: keepHead, tailChars: keepTail, spill }
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
// --- Run 35 (R-35-01/R-35-02): the saved Context document is the runtime truth -
|
|
440
|
+
//
|
|
441
|
+
// The document wins, config.prune is only a fallback for a value the document
|
|
442
|
+
// does not carry. Two rules are load-bearing:
|
|
443
|
+
// * an unsupported mode DISABLES the pruner with one visible warning; it is
|
|
444
|
+
// never coerced silently to off (the page would show an inert switch);
|
|
445
|
+
// * the returned mode is the pruner vocabulary, so the audit row records the
|
|
446
|
+
// effect (reference/summarise/headTail) instead of a hardcoded "off".
|
|
447
|
+
// The page's "summary" is only real when the inline summariser exists: the mode
|
|
448
|
+
// list may offer it, but the runtime refuses it without the lazy-summary block.
|
|
449
|
+
|
|
450
|
+
const PAGE_SUMMARY = "summary"
|
|
451
|
+
|
|
452
|
+
const prunerModeFor = (requested, summariseAvailable) => {
|
|
453
|
+
if (requested === PAGE_SUMMARY) return summariseAvailable ? "summarise" : null
|
|
454
|
+
return PRUNER_MODES.includes(requested) ? requested : null
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
/**
|
|
458
|
+
* Resolve the effective pruning plan for one result.
|
|
459
|
+
* @param context the saved context fragment (settingsStore.get().context)
|
|
460
|
+
* @param configPrune the bundled config.prune fallback
|
|
461
|
+
* @param options.summariseAvailable whether the inline summariser can run
|
|
462
|
+
* @returns { enabled, mode, requestedMode, modeSource, trigger, invalidMode, warning }
|
|
463
|
+
*/
|
|
464
|
+
export const resolvePrunePlan = (context, configPrune = {}, options = {}) => {
|
|
465
|
+
const config = isRecord(configPrune) ? configPrune : {}
|
|
466
|
+
const prune = isRecord(context) && isRecord(context.prune) ? context.prune : null
|
|
467
|
+
const summariseAvailable = options.summariseAvailable === true
|
|
468
|
+
const documentMode = prune !== null && typeof prune.mode === "string" ? prune.mode : null
|
|
469
|
+
const configMode = typeof config.mode === "string" ? config.mode : null
|
|
470
|
+
const requestedMode = documentMode ?? configMode ?? "off"
|
|
471
|
+
const modeSource = documentMode !== null ? "document" : configMode !== null ? "config" : "default"
|
|
472
|
+
const mode = prunerModeFor(requestedMode, summariseAvailable)
|
|
473
|
+
const invalidMode = mode === null
|
|
474
|
+
let warning = null
|
|
475
|
+
if (invalidMode) {
|
|
476
|
+
warning =
|
|
477
|
+
requestedMode === PAGE_SUMMARY
|
|
478
|
+
? 'router: prune mode "summary" needs the inline summariser; enable the lazy-summary block or choose reference - the tool-result pruner is OFF'
|
|
479
|
+
: "router: unknown prune mode " + JSON.stringify(requestedMode) + " - the tool-result pruner is OFF"
|
|
480
|
+
}
|
|
481
|
+
// enabled/trigger are read from the document first, then config; enabled only
|
|
482
|
+
// participates when it is explicitly a boolean.
|
|
483
|
+
const enabledValue =
|
|
484
|
+
prune !== null && typeof prune.enabled === "boolean"
|
|
485
|
+
? prune.enabled
|
|
486
|
+
: typeof config.enabled === "boolean"
|
|
487
|
+
? config.enabled
|
|
488
|
+
: true
|
|
489
|
+
const trigger =
|
|
490
|
+
prune !== null && PRUNE_TRIGGERS.includes(prune.trigger)
|
|
491
|
+
? prune.trigger
|
|
492
|
+
: PRUNE_TRIGGERS.includes(config.trigger)
|
|
493
|
+
? config.trigger
|
|
494
|
+
: "auto"
|
|
495
|
+
const enabled = enabledValue && !invalidMode && mode !== "off" && trigger !== "off"
|
|
496
|
+
// enabledValue is the authored switch (document/config), distinct from the
|
|
497
|
+
// effective enabled: the effective block reports WHY it resolved off.
|
|
498
|
+
return { enabled, enabledValue, mode: mode ?? "off", requestedMode, modeSource, trigger, invalidMode, warning }
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
/**
|
|
502
|
+
* DEC-35-11: resolve the saved tool subset as an ALLOWLIST over the page's own
|
|
503
|
+
* vocabulary. P is the page vocabulary (DEFAULT_TOOLS: the 9 core ids the
|
|
504
|
+
* Context tab offers) and S is the saved selection over P.
|
|
505
|
+
*
|
|
506
|
+
* allow = [ t in S | P.has(t) && inherited.has(t) ]
|
|
507
|
+
*
|
|
508
|
+
* so the child is restricted to exactly the selected core tools it inherits,
|
|
509
|
+
* in the saved order. skill and ask_user_question are not in P by default and
|
|
510
|
+
* every other inherited tool (every mcp_* server, the devtools MCP, the
|
|
511
|
+
* agent-team tools) is MASKED - the child reaches them through run_code, which
|
|
512
|
+
* is always available and never named here (tools.restrict() refuses to name
|
|
513
|
+
* it). Ids in S outside P cannot select anything: they are returned in ignored
|
|
514
|
+
* so the host warns once. A selection with no page id resolves to no mask
|
|
515
|
+
* (allow null), never to an empty allow list.
|
|
516
|
+
*
|
|
517
|
+
* @param context the saved context fragment
|
|
518
|
+
* @param inheritedNames Set/array of the child's inherited global names
|
|
519
|
+
* (tools.view(agent).restrictableNames)
|
|
520
|
+
* @param pageTools the page vocabulary P; DEFAULT_TOOLS unless a caller knows
|
|
521
|
+
* a different page vocabulary
|
|
522
|
+
* @returns { allow: string[] | null, ignored: string[] } or null when there is
|
|
523
|
+
* no enabled subset (or no selection) to apply
|
|
524
|
+
*/
|
|
525
|
+
export const resolveToolSubset = (context, inheritedNames, pageTools = DEFAULT_TOOLS) => {
|
|
526
|
+
const subset = isRecord(context) && isRecord(context.toolSubset) ? context.toolSubset : null
|
|
527
|
+
if (subset === null || subset.enabled !== true || !Array.isArray(subset.tools)) return null
|
|
528
|
+
const inherited =
|
|
529
|
+
inheritedNames instanceof Set
|
|
530
|
+
? inheritedNames
|
|
531
|
+
: new Set(Array.isArray(inheritedNames) ? inheritedNames : [])
|
|
532
|
+
const page = new Set(Array.isArray(pageTools) ? pageTools : DEFAULT_TOOLS)
|
|
533
|
+
const selected = new Set(subset.tools.filter(isNonEmptyString))
|
|
534
|
+
if (selected.size === 0) return null
|
|
535
|
+
const ignored = [...selected].filter((name) => !page.has(name))
|
|
536
|
+
const selectedPage = [...selected].filter((name) => page.has(name))
|
|
537
|
+
if (selectedPage.length === 0) return { allow: null, ignored }
|
|
538
|
+
// The allowlist is exactly the selected page tools this child inherits, in
|
|
539
|
+
// saved order. A selected page tool the child does not inherit simply drops
|
|
540
|
+
// out of allow; run_code stays available regardless and is never named.
|
|
541
|
+
const allow = selectedPage.filter((name) => inherited.has(name))
|
|
542
|
+
return { allow, ignored }
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
|
|
546
|
+
// --- Run 35 R-35-04: the served effective block ------------------------------
|
|
547
|
+
//
|
|
548
|
+
// The page renders what the runtime resolved, not a client mirror. The block is
|
|
549
|
+
// derived with the same helpers the runtime uses (resolvePrunePlan and
|
|
550
|
+
// resolveToolSubset) plus the summariser's availability, so the page and the
|
|
551
|
+
// pruner/subset/summariser can never disagree. mode is the RUNTIME vocabulary
|
|
552
|
+
// (off/reference/summarise/headTail), matching the page's effective line.
|
|
553
|
+
|
|
554
|
+
export const SUBSET_LIMITATION = "the child's context gets only the 9 core tools"
|
|
555
|
+
export const SUBSET_UNSUPPORTED = "this host cannot restrict a child's tools"
|
|
556
|
+
const SUMMARY_UNAVAILABLE_REASON = "summary needs the inline summariser — enable the lazy-summary block or choose reference"
|
|
557
|
+
|
|
558
|
+
/**
|
|
559
|
+
* Project the effective runtime state the Context page reports.
|
|
560
|
+
* @param context saved context fragment (settingsStore.get().context)
|
|
561
|
+
* @param options.configPrune fallback config (passed to resolvePrunePlan)
|
|
562
|
+
* @param options.summariseAvailable whether the inline summariser can run
|
|
563
|
+
* @param options.knownNames restrictable global tool names, or null
|
|
564
|
+
* @returns { prune: {enabled,mode,trigger,reason}, subset: {supported,limitation,applied}, summary: {supported,model} }
|
|
565
|
+
*/
|
|
566
|
+
export const effectiveFromDocument = (context, options = {}) => {
|
|
567
|
+
const summariseAvailable = options.summariseAvailable === true
|
|
568
|
+
const plan = resolvePrunePlan(context, options.configPrune ?? {}, { summariseAvailable })
|
|
569
|
+
const invalidSummary = plan.requestedMode === "summary" && !summariseAvailable
|
|
570
|
+
const reason = invalidSummary
|
|
571
|
+
? SUMMARY_UNAVAILABLE_REASON
|
|
572
|
+
: plan.invalidMode
|
|
573
|
+
? "unknown mode " + plan.requestedMode
|
|
574
|
+
: plan.enabledValue === false
|
|
575
|
+
? "the switch is off"
|
|
576
|
+
: plan.trigger === "off" && plan.mode !== "off"
|
|
577
|
+
? "trigger is off"
|
|
578
|
+
: ""
|
|
579
|
+
const knownNames = options.knownNames
|
|
580
|
+
const known =
|
|
581
|
+
knownNames instanceof Set
|
|
582
|
+
? knownNames
|
|
583
|
+
: Array.isArray(knownNames)
|
|
584
|
+
? new Set(knownNames)
|
|
585
|
+
: null
|
|
586
|
+
const subsetSupported = known !== null && known.size > 0
|
|
587
|
+
const subset = subsetSupported ? resolveToolSubset(context, known) : null
|
|
588
|
+
// DEC-35-11: applied means the enabled selection is IN FORCE (it names at
|
|
589
|
+
// least one page id the host can act on, so allow is a non-empty list of the
|
|
590
|
+
// selected core tools the child inherits).
|
|
591
|
+
const block = isRecord(context) && isRecord(context.lazySummary) ? context.lazySummary : null
|
|
592
|
+
return {
|
|
593
|
+
prune: { enabled: plan.enabled, mode: plan.mode, trigger: plan.trigger, reason },
|
|
594
|
+
subset: {
|
|
595
|
+
supported: subsetSupported,
|
|
596
|
+
limitation: subsetSupported ? SUBSET_LIMITATION : SUBSET_UNSUPPORTED,
|
|
597
|
+
applied: subset !== null && subset.allow !== null
|
|
598
|
+
},
|
|
599
|
+
summary: {
|
|
600
|
+
supported: summariseAvailable,
|
|
601
|
+
model: block !== null && typeof block.model === "string" ? block.model : ""
|
|
602
|
+
}
|
|
603
|
+
}
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
/**
|
|
607
|
+
* DEC-35-11 (reverts DEC-35-09): a stored subset that names ids this host does
|
|
608
|
+
* not have (the retired code_run/list_tools, a hand-edit typo, any other non-DSH
|
|
609
|
+
* id) is migrated by dropping EXACTLY those ids and KEEPING the rest, still
|
|
610
|
+
* enabled. It NEVER widens and NEVER adds skill/ask_user_question: a saved list
|
|
611
|
+
* is an allowlist, so "absent" is a real deselection, not an artefact of an
|
|
612
|
+
* older page. Owner's rev-15 file (the 9 core + code_run + list_tools) therefore
|
|
613
|
+
* migrates to exactly the 9 core, not to all 11. Only when no selectable id
|
|
614
|
+
* remains is the subset switched off (enabled:false, tools:[]), because an
|
|
615
|
+
* enabled empty list is not a document the schema accepts. A subset that is
|
|
616
|
+
* already valid is returned unchanged, and no live tool view means no knowledge
|
|
617
|
+
* means no edit.
|
|
618
|
+
* Pure: the caller persists the returned document (rev unchanged - a migration
|
|
619
|
+
* is not a document edit) and warns once about removed.
|
|
620
|
+
* @returns { document, removed, disabled, widened } - the same document
|
|
621
|
+
* reference when nothing changes; widened is always false now (the
|
|
622
|
+
* DEC-35-09 widening is reverted) and is kept for the call-site shape
|
|
623
|
+
*/
|
|
624
|
+
export const migrateToolSubset = (document, knownNames) => {
|
|
625
|
+
const unchanged = { document, removed: [], disabled: false, widened: false }
|
|
626
|
+
const known =
|
|
627
|
+
knownNames instanceof Set
|
|
628
|
+
? knownNames
|
|
629
|
+
: Array.isArray(knownNames)
|
|
630
|
+
? new Set(knownNames)
|
|
631
|
+
: null
|
|
632
|
+
if (known === null || known.size === 0) return unchanged
|
|
633
|
+
if (!isRecord(document) || !isRecord(document.context) || !isRecord(document.context.toolSubset)) return unchanged
|
|
634
|
+
const subset = document.context.toolSubset
|
|
635
|
+
if (!Array.isArray(subset.tools)) return unchanged
|
|
636
|
+
const tools = subset.tools.filter(isNonEmptyString)
|
|
637
|
+
const removed = tools.filter((name) => !known.has(name))
|
|
638
|
+
if (removed.length === 0) return unchanged
|
|
639
|
+
const kept = [...new Set(tools.filter((name) => known.has(name)))]
|
|
640
|
+
const nextContext = (nextSubset) => ({ ...document, context: { ...document.context, toolSubset: nextSubset } })
|
|
641
|
+
if (kept.length === 0) {
|
|
642
|
+
// Nothing selectable is left: an enabled empty list would be refused by the
|
|
643
|
+
// schema and by the page, so the subset is switched off and the host says so.
|
|
644
|
+
return { document: nextContext({ ...subset, enabled: false, tools: [] }), removed, disabled: true, widened: false }
|
|
645
|
+
}
|
|
646
|
+
// DEC-35-11: drop only the ids that name no DSH tool; keep the rest exactly.
|
|
647
|
+
return { document: nextContext({ ...subset, tools: kept }), removed, disabled: false, widened: false }
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
// --- store -------------------------------------------------------------------
|
|
651
|
+
|
|
652
|
+
const same = (a, b) => JSON.stringify(a) === JSON.stringify(b)
|
|
653
|
+
|
|
654
|
+
const resolveWindowTokens = (source) => {
|
|
655
|
+
const value = typeof source === "function" ? source() : source
|
|
656
|
+
return Number.isInteger(value) && value > 0 ? value : null
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
const resolveCatalogue = (source) => {
|
|
660
|
+
const value = typeof source === "function" ? source() : source
|
|
661
|
+
if (!Array.isArray(value)) return null
|
|
662
|
+
const ids = value.filter((id) => isNonEmptyString(id))
|
|
663
|
+
return ids.length > 0 ? [...new Set(ids)] : null
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
export const createSettingsStore = (initial, options = {}) => {
|
|
667
|
+
// Only the persisted fragments are state; windowTokens and catalogue are read
|
|
668
|
+
// from the host on every read/write so a refreshed snapshot or engine catalog
|
|
669
|
+
// is picked up without a restart.
|
|
670
|
+
let state = { context: initial.context, roles: initial.roles, rev: initial.rev }
|
|
671
|
+
// Run 25 T5: a write is committed only after the injected persist succeeded,
|
|
672
|
+
// so a disk failure can never answer "Saved" (the handler used to swallow it).
|
|
673
|
+
const persist = typeof options.persist === "function" ? options.persist : null
|
|
674
|
+
// Run 25 verifier root cause: a fresh store (no persisted document) replaces
|
|
675
|
+
// its fixed role chain with a catalogue-derived one as soon as the live
|
|
676
|
+
// catalogue is known. A stored document is never re-derived.
|
|
677
|
+
const deriveDefaults = typeof options.deriveDefaults === "function" ? options.deriveDefaults : null
|
|
678
|
+
let pendingDerivedDefaults = options.useDerivedDefaults === true && deriveDefaults !== null
|
|
679
|
+
const ensureDefaults = () => {
|
|
680
|
+
if (!pendingDerivedDefaults) return
|
|
681
|
+
let derived
|
|
682
|
+
try {
|
|
683
|
+
derived = deriveDefaults()
|
|
684
|
+
} catch {
|
|
685
|
+
return
|
|
686
|
+
}
|
|
687
|
+
// No catalogue yet: keep the fixed document and try again on the next read.
|
|
688
|
+
if (derived === null || derived === undefined) return
|
|
689
|
+
pendingDerivedDefaults = false
|
|
690
|
+
const candidate = {
|
|
691
|
+
context: derived.context,
|
|
692
|
+
roles: derived.roles,
|
|
693
|
+
rev: Number.isInteger(derived.rev) ? derived.rev : state.rev
|
|
694
|
+
}
|
|
695
|
+
if (validateDocument({ ...candidate, windowTokens: null, catalogue: null }).length > 0) return
|
|
696
|
+
state = candidate
|
|
697
|
+
}
|
|
698
|
+
const windowTokens = () => resolveWindowTokens(options.windowTokens)
|
|
699
|
+
const catalogue = () => resolveCatalogue(options.catalogue)
|
|
700
|
+
const document = () => ({
|
|
701
|
+
context: state.context,
|
|
702
|
+
roles: normaliseAlwaysOnRoles(state.roles),
|
|
703
|
+
rev: state.rev,
|
|
704
|
+
windowTokens: windowTokens(),
|
|
705
|
+
catalogue: catalogue()
|
|
706
|
+
})
|
|
707
|
+
return {
|
|
708
|
+
get: () => {
|
|
709
|
+
ensureDefaults()
|
|
710
|
+
return document()
|
|
711
|
+
},
|
|
712
|
+
/**
|
|
713
|
+
* Run 36 (R-36-09): write a DSH-derived switch value into the routing
|
|
714
|
+
* document. It is a mirror, not an authored edit, so the rev does not move;
|
|
715
|
+
* routing reads it immediately and the next save persists it as part of the
|
|
716
|
+
* document. Returns whether the value changed.
|
|
717
|
+
*/
|
|
718
|
+
mirrorL3Enabled: (enabled) => {
|
|
719
|
+
ensureDefaults()
|
|
720
|
+
if (typeof enabled !== "boolean") return false
|
|
721
|
+
if (state.roles?.l3?.enabled === enabled) return false
|
|
722
|
+
state = { ...state, roles: { ...state.roles, l3: { ...state.roles.l3, enabled } } }
|
|
723
|
+
return true
|
|
724
|
+
},
|
|
725
|
+
write: (patch, expectedRev) => {
|
|
726
|
+
ensureDefaults()
|
|
727
|
+
if (state.rev !== expectedRev) return { ok: false, conflict: true, current: document() }
|
|
728
|
+
if (!isRecord(patch)) {
|
|
729
|
+
return { ok: false, invalid: true, field: "body", message: "body must be an object" }
|
|
730
|
+
}
|
|
731
|
+
const unknown = Object.keys(patch).find((key) => key !== "context" && key !== "roles")
|
|
732
|
+
if (unknown !== undefined) {
|
|
733
|
+
return { ok: false, invalid: true, field: unknown, message: "unknown field" }
|
|
734
|
+
}
|
|
735
|
+
const next = {
|
|
736
|
+
context: patch.context !== undefined ? patch.context : state.context,
|
|
737
|
+
// The always-on roles are repaired on write too: a page that still holds
|
|
738
|
+
// an older draft must not be stuck behind a rule it cannot control.
|
|
739
|
+
roles: normaliseAlwaysOnRoles(patch.roles !== undefined ? patch.roles : state.roles)
|
|
740
|
+
}
|
|
741
|
+
const issue = validateDocument(
|
|
742
|
+
{ context: next.context, roles: next.roles, rev: state.rev, windowTokens: null, catalogue: null },
|
|
743
|
+
windowTokens(),
|
|
744
|
+
catalogue()
|
|
745
|
+
)[0]
|
|
746
|
+
if (issue !== undefined) {
|
|
747
|
+
return { ok: false, invalid: true, field: issue.field, message: issue.message }
|
|
748
|
+
}
|
|
749
|
+
if (same(next.context, state.context) && same(next.roles, state.roles)) return { ok: true, settings: document() }
|
|
750
|
+
const committed = { context: next.context, roles: next.roles, rev: state.rev + 1 }
|
|
751
|
+
if (persist !== null) {
|
|
752
|
+
try {
|
|
753
|
+
persist(committed)
|
|
754
|
+
} catch (error) {
|
|
755
|
+
// A failed write is a field the page can mark and a dirty document it
|
|
756
|
+
// can retry: the in-memory rev must not advance past what is on disk.
|
|
757
|
+
return {
|
|
758
|
+
ok: false,
|
|
759
|
+
invalid: true,
|
|
760
|
+
storage: true,
|
|
761
|
+
field: "storage",
|
|
762
|
+
message: "settings could not be written: " + (error instanceof Error ? error.message : String(error))
|
|
763
|
+
}
|
|
764
|
+
}
|
|
765
|
+
}
|
|
766
|
+
state = committed
|
|
767
|
+
return { ok: true, settings: document() }
|
|
768
|
+
}
|
|
769
|
+
}
|
|
770
|
+
}
|