dsh-boost 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (110) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +29 -0
  3. package/README.en.md +526 -0
  4. package/README.md +444 -2
  5. package/cordis.patch.yml +40 -0
  6. package/dist/admission/fixed-cost.d.ts +23 -0
  7. package/dist/admission/fixed-cost.js +61 -0
  8. package/dist/admission/fixed-cost.js.map +1 -0
  9. package/dist/admission/ledger.d.ts +113 -0
  10. package/dist/admission/ledger.js +176 -0
  11. package/dist/admission/ledger.js.map +1 -0
  12. package/dist/admission/retrieval.d.ts +65 -0
  13. package/dist/admission/retrieval.js +162 -0
  14. package/dist/admission/retrieval.js.map +1 -0
  15. package/dist/admission/usage.d.ts +75 -0
  16. package/dist/admission/usage.js +124 -0
  17. package/dist/admission/usage.js.map +1 -0
  18. package/dist/config.d.ts +43 -0
  19. package/dist/config.js +103 -0
  20. package/dist/config.js.map +1 -0
  21. package/dist/gate/binding.d.ts +113 -0
  22. package/dist/gate/binding.js +297 -0
  23. package/dist/gate/binding.js.map +1 -0
  24. package/dist/gate/decide.d.ts +82 -0
  25. package/dist/gate/decide.js +163 -0
  26. package/dist/gate/decide.js.map +1 -0
  27. package/dist/gate/guard.d.ts +69 -0
  28. package/dist/gate/guard.js +195 -0
  29. package/dist/gate/guard.js.map +1 -0
  30. package/dist/gate/invalidate.d.ts +112 -0
  31. package/dist/gate/invalidate.js +111 -0
  32. package/dist/gate/invalidate.js.map +1 -0
  33. package/dist/gate/plan.d.ts +86 -0
  34. package/dist/gate/plan.js +222 -0
  35. package/dist/gate/plan.js.map +1 -0
  36. package/dist/hooks/clock.d.ts +68 -0
  37. package/dist/hooks/clock.js +82 -0
  38. package/dist/hooks/clock.js.map +1 -0
  39. package/dist/hooks/execute.d.ts +79 -0
  40. package/dist/hooks/execute.js +128 -0
  41. package/dist/hooks/execute.js.map +1 -0
  42. package/dist/hooks/llm-stream.d.ts +283 -0
  43. package/dist/hooks/llm-stream.js +1086 -0
  44. package/dist/hooks/llm-stream.js.map +1 -0
  45. package/dist/hooks/pending.d.ts +89 -0
  46. package/dist/hooks/pending.js +115 -0
  47. package/dist/hooks/pending.js.map +1 -0
  48. package/dist/hooks/post-execute.d.ts +257 -0
  49. package/dist/hooks/post-execute.js +1950 -0
  50. package/dist/hooks/post-execute.js.map +1 -0
  51. package/dist/hooks/session-state.d.ts +158 -0
  52. package/dist/hooks/session-state.js +168 -0
  53. package/dist/hooks/session-state.js.map +1 -0
  54. package/dist/hooks/synthesize.d.ts +74 -0
  55. package/dist/hooks/synthesize.js +100 -0
  56. package/dist/hooks/synthesize.js.map +1 -0
  57. package/dist/host/loader.d.ts +23 -0
  58. package/dist/host/loader.js +31 -0
  59. package/dist/host/loader.js.map +1 -0
  60. package/dist/host/platform.d.ts +18 -0
  61. package/dist/host/platform.js +19 -0
  62. package/dist/host/platform.js.map +1 -0
  63. package/dist/host/root.d.ts +25 -0
  64. package/dist/host/root.js +64 -0
  65. package/dist/host/root.js.map +1 -0
  66. package/dist/index.d.ts +13 -0
  67. package/dist/index.js +984 -0
  68. package/dist/index.js.map +1 -0
  69. package/dist/projection/apply.d.ts +174 -0
  70. package/dist/projection/apply.js +137 -0
  71. package/dist/projection/apply.js.map +1 -0
  72. package/dist/projection/canonicalise.d.ts +43 -0
  73. package/dist/projection/canonicalise.js +43 -0
  74. package/dist/projection/canonicalise.js.map +1 -0
  75. package/dist/projection/counters.d.ts +65 -0
  76. package/dist/projection/counters.js +88 -0
  77. package/dist/projection/counters.js.map +1 -0
  78. package/dist/projection/truncate.d.ts +47 -0
  79. package/dist/projection/truncate.js +57 -0
  80. package/dist/projection/truncate.js.map +1 -0
  81. package/dist/prompt/protocol.d.ts +45 -0
  82. package/dist/prompt/protocol.js +56 -0
  83. package/dist/prompt/protocol.js.map +1 -0
  84. package/dist/receipts/store.d.ts +198 -0
  85. package/dist/receipts/store.js +734 -0
  86. package/dist/receipts/store.js.map +1 -0
  87. package/dist/scope/doc.d.ts +117 -0
  88. package/dist/scope/doc.js +158 -0
  89. package/dist/scope/doc.js.map +1 -0
  90. package/dist/scope/resolve.d.ts +91 -0
  91. package/dist/scope/resolve.js +146 -0
  92. package/dist/scope/resolve.js.map +1 -0
  93. package/dist/scope/store.d.ts +135 -0
  94. package/dist/scope/store.js +573 -0
  95. package/dist/scope/store.js.map +1 -0
  96. package/dist/selector/jev.d.ts +93 -0
  97. package/dist/selector/jev.js +171 -0
  98. package/dist/selector/jev.js.map +1 -0
  99. package/dist/tools/boost.d.ts +380 -0
  100. package/dist/tools/boost.js +801 -0
  101. package/dist/tools/boost.js.map +1 -0
  102. package/dist/tools/family.d.ts +26 -0
  103. package/dist/tools/family.js +26 -0
  104. package/dist/tools/family.js.map +1 -0
  105. package/dist/types.d.ts +130 -0
  106. package/dist/types.js +21 -0
  107. package/dist/types.js.map +1 -0
  108. package/locale/en.json +6 -0
  109. package/locale/zh.json +6 -0
  110. package/package.json +75 -4
package/dist/index.js ADDED
@@ -0,0 +1,984 @@
1
+ /**
2
+ * dsh-boost cordis plugin entry point.
3
+ *
4
+ * The plugin is a plain function plugin: cordis reads `name` and `inject` from
5
+ * the module and calls `apply(ctx, config)`. Only the production assembly lives
6
+ * here — configuration resolution, the two stores the hooks and the control
7
+ * tool share, the hook mounts, the lifecycle events that warm visibility,
8
+ * drive the clock, flush receipts at turn end and clean up on session
9
+ * disposal, and the `boost` tool, all wired once per plugin instance.
10
+ *
11
+ * Wiring failures are contained: a host that lacks the services a mount point
12
+ * lives on must load the plugin with a warning, not die loading it. The data
13
+ * root is `<dshHome>/boost` (`config.dshHome` when the row supplies it, else
14
+ * `$DSH_HOME`), falling back to `~/.dsh/boost`.
15
+ *
16
+ * ## Why the mount disposers are dropped
17
+ *
18
+ * `ctx.on`, `ctx.systemPrompt.section` and `ctx.tools.register` all return a
19
+ * disposer. Every one is deliberately discarded. A cordis plugin entry is
20
+ * mounted in its own context, and disposing that entry tears down everything
21
+ * registered through it; a retained disposer would add nothing except the
22
+ * chance that a stale closure removes a mount owned by a later instance. The
23
+ * assumption is exactly that per-entry ownership — if this plugin is ever
24
+ * mounted into a context it does not own (a shared host context), the
25
+ * disposers, or an explicit teardown, become required (review row 76).
26
+ *
27
+ * @module dsh-boost
28
+ */
29
+ import { readFileSync } from 'node:fs';
30
+ import { createRequire } from 'node:module';
31
+ import { measureBoostFixedOverhead } from './tools/boost.js';
32
+ import { RuntimeStepHorizon, StepBudget } from './admission/ledger.js';
33
+ import { RetrievalLedger } from './admission/retrieval.js';
34
+ import { UsageLedger } from './admission/usage.js';
35
+ import { resolveConfig } from './config.js';
36
+ import { AnchorStore } from './gate/invalidate.js';
37
+ import { resolveBoostRoot } from './host/root.js';
38
+ import { clearSession, SessionRuntime } from './hooks/llm-stream.js';
39
+ import { TurnClock } from './hooks/clock.js';
40
+ import { PendingQueue } from './hooks/pending.js';
41
+ import { clearAcceptedDispatch, registerHooks } from './hooks/post-execute.js';
42
+ import { ProjectionCounters } from './projection/counters.js';
43
+ import { PROTOCOL_NAME, PROTOCOL_TEXT } from './prompt/protocol.js';
44
+ import { ReceiptStore } from './receipts/store.js';
45
+ import { resolveWorkspace } from './scope/resolve.js';
46
+ import { ScopeStore } from './scope/store.js';
47
+ import { boostTool } from './tools/boost.js';
48
+ export const name = 'dsh-boost';
49
+ /**
50
+ * Required host services.
51
+ *
52
+ * `llm` is deliberately absent: projection and admission use no model, and
53
+ * only the selector does. A hard injection would leave the whole plugin
54
+ * pending — no hooks, no tool, no warning — on a composition without the LLM
55
+ * runtime, even though it could still project. The selector resolves `llm`
56
+ * lazily and fails closed with `selector-unavailable` when it is absent.
57
+ */
58
+ export const inject = ['tools', 'systemPrompt'];
59
+ /** Whether the host exposes both services the hook mounts attach to. */
60
+ function canRegister(ctx) {
61
+ return typeof ctx.on === 'function' && typeof ctx.systemPrompt?.section === 'function';
62
+ }
63
+ /** One-line detail for a contained wiring failure. */
64
+ function messageOf(error) {
65
+ return error instanceof Error ? error.message : String(error);
66
+ }
67
+ /** The dsh host line this build was verified against (`engines.dsh`). */
68
+ const VERIFIED_HOST_VERSION = '0.2.2-rc.4';
69
+ /**
70
+ * Whether a reported version names the verified release, ignoring build
71
+ * metadata.
72
+ *
73
+ * The host's compatibility preflight compares with
74
+ * `semver.satisfies(version, range, { includePrerelease: true })`, and semver
75
+ * ignores `+build` metadata on both sides. String equality would warn on
76
+ * `0.2.2-rc.4+build.5` — a build the host itself accepts — so the comparison
77
+ * strips everything from the first `+` (review row 34).
78
+ */
79
+ function isVerifiedHostVersion(version) {
80
+ const core = (value) => {
81
+ const build = value.indexOf('+');
82
+ return build === -1 ? value : value.slice(0, build);
83
+ };
84
+ return core(version) === core(VERIFIED_HOST_VERSION);
85
+ }
86
+ /**
87
+ * Stable host code: the resolved host version is not the verified one.
88
+ *
89
+ * A warning, never a hard failure: an unverified version is a risk, not proof
90
+ * that an API this build uses has moved. It belongs to the `ERR_HOST_*` family
91
+ * this module already logs (`ERR_HOST_NO_AGENT_REQUEST`,
92
+ * `ERR_HOST_COMPLETE_SECTION`).
93
+ */
94
+ const ERR_HOST_VERSION_MISMATCH = 'ERR_HOST_VERSION_MISMATCH';
95
+ /** The app-boot package whose version IS the dsh runtime version. */
96
+ const HOST_VERSION_PACKAGE = '@deepseek-ai/dsh-app-boot';
97
+ /** Node's resolver, used only when the host service is unavailable. */
98
+ const requireFromHere = createRequire(import.meta.url);
99
+ /**
100
+ * The resolved dsh host version, or `undefined` when it cannot be determined.
101
+ *
102
+ * `dsh-app-boot`'s own manifest is the runtime version the compatibility
103
+ * preflight compares `engines.dsh` against, so it is the authority here too.
104
+ * The profile's `pluginPackages` service is preferred because it resolves
105
+ * through the same runtime interception the host used (a linked or mixed tree
106
+ * reports the version actually loaded); a plain Node resolve from this module
107
+ * is the fallback for an embedded composition without that service. Reading a
108
+ * manifest is not a host import: the package is never loaded, and nothing in
109
+ * `dist/` statically imports it.
110
+ *
111
+ * Never throws: an absent service, an unresolvable package and a malformed
112
+ * manifest all mean "unknown", which is logged but not warned about.
113
+ */
114
+ function hostVersionOf(ctx) {
115
+ try {
116
+ const packages = serviceOf(ctx, 'pluginPackages');
117
+ const pkg = packages?.packageOf?.(HOST_VERSION_PACKAGE, import.meta.url);
118
+ if (typeof pkg?.version === 'string' && pkg.version !== '')
119
+ return pkg.version;
120
+ }
121
+ catch {
122
+ // A foreign resolver is the same as no resolver.
123
+ }
124
+ try {
125
+ const manifest = requireFromHere.resolve(`${HOST_VERSION_PACKAGE}/package.json`);
126
+ const parsed = JSON.parse(readFileSync(manifest, 'utf8'));
127
+ return typeof parsed.version === 'string' && parsed.version !== '' ? parsed.version : undefined;
128
+ }
129
+ catch {
130
+ return undefined;
131
+ }
132
+ }
133
+ /**
134
+ * Log the resolved host version once and warn on a mismatch.
135
+ *
136
+ * The version guard is deliberately advisory. npm does not read `engines.dsh`;
137
+ * the host enforces it only through the managed-install compatibility preflight,
138
+ * which does not run for every composition. A warning here is the only signal
139
+ * an embedded or mixed tree gets, and it must never stop the plugin: a version
140
+ * this build did not verify may still work.
141
+ */
142
+ function reportHostVersion(ctx) {
143
+ const version = hostVersionOf(ctx);
144
+ if (version === undefined) {
145
+ ctx.logger?.info?.(`dsh-boost: dsh host version unknown (verified against ${VERIFIED_HOST_VERSION}); compatibility cannot be checked`);
146
+ return;
147
+ }
148
+ if (isVerifiedHostVersion(version)) {
149
+ ctx.logger?.info?.(`dsh-boost: dsh host ${version} (verified)`);
150
+ return;
151
+ }
152
+ ctx.logger?.warn?.(`dsh-boost: ${ERR_HOST_VERSION_MISMATCH}: this build is verified against dsh ${VERIFIED_HOST_VERSION}, but the host reports ${version}; continuing, but a renamed host API may make the plugin inert`);
153
+ }
154
+ /**
155
+ * Duplicate applies observed in this process.
156
+ *
157
+ * The host exposes no stable duplicate-mount code for a prompt section, so the
158
+ * only evidence is the plain Error's message. A throw counts as "this plugin is
159
+ * already wired" only when that message names OUR section and says it is
160
+ * already registered; every other failure is a wiring error with its own code
161
+ * (see `isDuplicateSectionError`). The counter makes repeated applies visible
162
+ * in the log without changing the mounts.
163
+ */
164
+ let duplicateMountAttempts = 0;
165
+ /**
166
+ * Whether a section-registration throw is the host's genuine duplicate error.
167
+ *
168
+ * `dsh-system-prompt` builds a plain `Error` whose message starts with
169
+ * `prompt section "<name>" is already registered` (global and scoped variants
170
+ * both start that way) and exposes no code. Matching that prefix for our own
171
+ * section is the only duplicate evidence available; a future wording change
172
+ * falls through to the generic branch, which warns with the raw error and keeps
173
+ * the control tool mountable instead of silently disabling everything.
174
+ */
175
+ function isDuplicateSectionError(error) {
176
+ return (error instanceof Error &&
177
+ error.message.startsWith(`prompt section "${PROTOCOL_NAME}" is already registered`));
178
+ }
179
+ /**
180
+ * Read a soft host service through `ctx.get`.
181
+ *
182
+ * `workspaceRegistry`, `spillStore` and `tokenMeter` are optional peers: a
183
+ * static injection would make the plugin fail to load on a host that does not
184
+ * provide them, so they are fetched, never declared in `inject`. A host whose
185
+ * `get` throws is the same as one without the service (the plugin-load test
186
+ * pins that the data root is never resolved this way).
187
+ */
188
+ function serviceOf(ctx, name) {
189
+ try {
190
+ if (typeof ctx.get !== 'function')
191
+ return undefined;
192
+ return ctx.get(name) ?? undefined;
193
+ }
194
+ catch {
195
+ return undefined;
196
+ }
197
+ }
198
+ function lazyService(ctx, name) {
199
+ let resolved;
200
+ const get = (() => {
201
+ if (resolved !== undefined)
202
+ return resolved;
203
+ resolved = serviceOf(ctx, name);
204
+ return resolved;
205
+ });
206
+ get.reset = () => {
207
+ resolved = undefined;
208
+ };
209
+ return get;
210
+ }
211
+ /**
212
+ * The session id behind an agent or a `Session`.
213
+ *
214
+ * An agent exposes `session.header.id`; the `session/disposed` payload is the
215
+ * `Session` itself and exposes `header.id` (and `id`). Anything else is
216
+ * `undefined`, which makes every caller fail closed.
217
+ */
218
+ function sessionIdOf(value) {
219
+ const carrier = value;
220
+ const agentId = carrier?.session?.header?.id;
221
+ if (typeof agentId === 'string')
222
+ return agentId;
223
+ const headerId = carrier?.header?.id;
224
+ if (typeof headerId === 'string')
225
+ return headerId;
226
+ return typeof carrier?.id === 'string' ? carrier.id : undefined;
227
+ }
228
+ /**
229
+ * The host token meter's synchronous message estimator, resolved lazily.
230
+ *
231
+ * `ctx.tokenMeter` is a cordis service with a synchronous `estimateMessage`
232
+ * method, so `ctx.get('tokenMeter')` is a real synchronous seam. Like every
233
+ * soft service it may become active after this plugin's `apply`, so the
234
+ * estimator is probed on first use and re-probed while absent; a success is
235
+ * memoised. Presence is not capability: a service that throws or returns a
236
+ * non-finite number is a broken meter, not a meter, and substitution is
237
+ * refused exactly as when no service exists (review R5). A broken meter is not
238
+ * memoised either, so a provider that finishes wiring its meter later can
239
+ * still recover.
240
+ *
241
+ * The receipt label is `host` so the number is never mistaken for a provider
242
+ * measurement; the only other label would be a fabricated `chars/4` fallback,
243
+ * which this assembly deliberately does not implement.
244
+ *
245
+ * Memoisation covers the *binding*, not the answer. `kind()` probes the
246
+ * memoised estimator on every call, because a meter that answered once is not
247
+ * a meter forever: after it starts returning `NaN`, projection receipts already
248
+ * record `estimate:'unknown'` for that assembly, and a cached `host` label
249
+ * would contradict them in the same `boost status` output.
250
+ */
251
+ const METER_PROBE = 'dsh-boost meter probe';
252
+ function meterSeamOf(ctx) {
253
+ let estimator;
254
+ /** One probe through a raw host estimator; a throw or non-number is failure. */
255
+ const probe = (estimate) => {
256
+ try {
257
+ const value = estimate({
258
+ role: 'user',
259
+ content: [{ type: 'text', text: METER_PROBE }],
260
+ });
261
+ return typeof value === 'number' && Number.isFinite(value);
262
+ }
263
+ catch {
264
+ return false;
265
+ }
266
+ };
267
+ const resolve = () => {
268
+ if (estimator !== undefined)
269
+ return estimator;
270
+ const meter = serviceOf(ctx, 'tokenMeter');
271
+ if (meter === undefined || typeof meter.estimateMessage !== 'function')
272
+ return undefined;
273
+ const estimate = meter.estimateMessage.bind(meter);
274
+ if (!probe(estimate))
275
+ return undefined;
276
+ estimator = (text) => {
277
+ try {
278
+ const value = estimate({ role: 'user', content: [{ type: 'text', text }] });
279
+ return typeof value === 'number' && Number.isFinite(value) ? value : Number.NaN;
280
+ }
281
+ catch {
282
+ return Number.NaN;
283
+ }
284
+ };
285
+ return estimator;
286
+ };
287
+ return {
288
+ estimate: resolve,
289
+ kind: () => {
290
+ const estimate = resolve();
291
+ if (estimate === undefined)
292
+ return 'unknown';
293
+ // Probe through the memoised wrapper, so the label prices the same
294
+ // pipeline every receipt uses. `resolve()` alone cannot answer: it
295
+ // returns a cached binding even after the meter stopped answering.
296
+ return Number.isFinite(estimate(METER_PROBE)) ? 'host' : 'unknown';
297
+ },
298
+ };
299
+ }
300
+ /** How many disposed session ids the runtime facade remembers (FIFO). */
301
+ const MAX_DISPOSED_RUNTIME_SESSIONS = 256;
302
+ /**
303
+ * `SessionRuntime` that refuses to recreate state for a disposed session.
304
+ *
305
+ * `clearSession` drops a session's runtime entry, but a `post-execute` that was
306
+ * already in flight (a selector call can take 20 s) lands after disposal and
307
+ * calls `clockFor`/`budgetFor`/`usageFor` again; the base class would create a
308
+ * fresh entry nothing ever clears. The facade returns throwaway primitives for
309
+ * disposed ids instead: the late hook records nothing, and the map cannot grow
310
+ * after session end. The id set is FIFO-bounded so a long process cannot grow
311
+ * it without limit.
312
+ */
313
+ class DisposalAwareSessionRuntime extends SessionRuntime {
314
+ disposed = new Set();
315
+ disposedOrder = [];
316
+ /** Mark a session disposed and drop whatever the base class still holds. */
317
+ markDisposed(sessionId) {
318
+ this.clear(sessionId);
319
+ if (this.disposed.has(sessionId))
320
+ return;
321
+ this.disposed.add(sessionId);
322
+ this.disposedOrder.push(sessionId);
323
+ while (this.disposedOrder.length > MAX_DISPOSED_RUNTIME_SESSIONS) {
324
+ const oldest = this.disposedOrder.shift();
325
+ if (oldest !== undefined)
326
+ this.disposed.delete(oldest);
327
+ }
328
+ }
329
+ clockFor(sessionId) {
330
+ return this.disposed.has(sessionId) ? new TurnClock() : super.clockFor(sessionId);
331
+ }
332
+ budgetFor(sessionId) {
333
+ return this.disposed.has(sessionId) ? new StepBudget(0) : super.budgetFor(sessionId);
334
+ }
335
+ usageFor(sessionId) {
336
+ return this.disposed.has(sessionId) ? new UsageLedger() : super.usageFor(sessionId);
337
+ }
338
+ onModelRequest(sessionId, turn, step) {
339
+ if (!this.disposed.has(sessionId))
340
+ super.onModelRequest(sessionId, turn, step);
341
+ }
342
+ }
343
+ /**
344
+ * Warm the synchronous visibility cache and remember the canonical workspace.
345
+ *
346
+ * `resolveWorkspace` is the async answer and also writes `scope.judgement(key)`;
347
+ * it prefers the registry's `resolveByPath`, so a symlinked or trailing-slash
348
+ * cwd resolves to the same id the judgement used. The workspace id is kept even
349
+ * when the answer is "invisible", so the resolver must consult the live
350
+ * judgement rather than treating the map as the answer. A workspace disabled
351
+ * after a commit therefore stops resolving before the next synthesized turn.
352
+ */
353
+ async function warmVisibility(scope, registry, agent, sessionId, workspaces) {
354
+ try {
355
+ const result = await resolveWorkspace(scope, agent, registry());
356
+ // The map carries identity, `scope.judgement` carries visibility: cache the
357
+ // id even when the answer is "invisible", and let the resolver combine the
358
+ // two. A stale id therefore cannot outlive a visibility change.
359
+ if (typeof result.workspaceId === 'string')
360
+ workspaces.set(sessionId, result.workspaceId);
361
+ else
362
+ workspaces.delete(sessionId);
363
+ return result.visible;
364
+ }
365
+ catch {
366
+ // `resolveWorkspace` is total; this contains a foreign registry.
367
+ return false;
368
+ }
369
+ }
370
+ /** Remember the effective route the selector call must inherit. */
371
+ function rememberRoute(routes, sessionId, config) {
372
+ const resolved = config;
373
+ if (resolved == null)
374
+ return;
375
+ if (typeof resolved.provider !== 'string' || typeof resolved.model !== 'string')
376
+ return;
377
+ const route = { provider: resolved.provider, model: resolved.model };
378
+ if (typeof resolved.reasoningEffort === 'string')
379
+ route.reasoningEffort = resolved.reasoningEffort;
380
+ routes.set(sessionId, route);
381
+ }
382
+ /**
383
+ * Replace the protocol section's already-resolved text with the fresh answer.
384
+ *
385
+ * This runs *after* the assemble waterfall, so it rewrites text a section
386
+ * provider already produced. That is deliberate and does not contradict D4
387
+ * ("persistent, stable content"): every agent has its own prompt prefix and
388
+ * its own context window, so changing this section cannot invalidate another
389
+ * agent's cached prefix. Within one agent the answer changes only when its
390
+ * resolved visibility changes (a workspace edit/`scope-set`), which is exactly
391
+ * the point at which the prefix must change; every other assembly reproduces
392
+ * the same bytes. The alternative — a section whose text is fixed at
393
+ * registration — would either leak one agent's visibility to every other or
394
+ * require a second provider to read a cache this listener has not warmed yet.
395
+ */
396
+ function patchProtocolSection(assembly, visible) {
397
+ const value = assembly;
398
+ if (value === undefined || value === null || !Array.isArray(value.sections))
399
+ return assembly;
400
+ const sections = value.sections.map((section) => {
401
+ const entry = section;
402
+ return entry?.name === PROTOCOL_NAME
403
+ ? { ...entry, text: visible ? PROTOCOL_TEXT : '' }
404
+ : section;
405
+ });
406
+ return { ...value, sections };
407
+ }
408
+ /** The marker every protocol text carries; a system prompt without it lost the section. */
409
+ const PROTOCOL_PROBE = '<CHISEL_PLAN>';
410
+ /**
411
+ * The system-role text of one model request, or `undefined` when the request
412
+ * carries no system prompt at all.
413
+ *
414
+ * Loop-built requests put the rendered prompt in the leading system-role
415
+ * message (``GenerateOptions.messages``); one-shot callers use `system`. A
416
+ * request with neither is a diagnostic that cannot tell us whether the section
417
+ * landed, so it is not evidence of a complete-section swallow.
418
+ */
419
+ function systemTextOf(options) {
420
+ const source = options;
421
+ if (typeof source?.system === 'string' && source.system.length > 0)
422
+ return source.system;
423
+ const messages = source?.messages;
424
+ if (!Array.isArray(messages))
425
+ return undefined;
426
+ let seen = false;
427
+ let text = '';
428
+ for (const message of messages) {
429
+ const entry = message;
430
+ if (entry?.role !== 'system')
431
+ continue;
432
+ seen = true;
433
+ if (typeof entry.content === 'string') {
434
+ text += entry.content;
435
+ continue;
436
+ }
437
+ if (!Array.isArray(entry.content))
438
+ continue;
439
+ for (const block of entry.content) {
440
+ const part = block;
441
+ if (part?.type === 'text' && typeof part.text === 'string')
442
+ text += part.text;
443
+ }
444
+ }
445
+ return seen ? text : undefined;
446
+ }
447
+ /**
448
+ * Mount the host events the assembly owns.
449
+ *
450
+ * ## Why `system-prompt/assemble` owns the warm
451
+ *
452
+ * The host's preStep is `tools.resolve` -> `systemPrompt.assemble` ->
453
+ * `agent/pre-step`; section text resolves inside `assemble`, and
454
+ * `agent/request` fires only later in `step()`. A warm driven from
455
+ * `agent/request` therefore misses request 1 (the gate can never act on step
456
+ * 1) and then flips the system prompt on request 2, invalidating the whole
457
+ * cached prefix (design D4). This listener runs inside the awaited assemble
458
+ * waterfall, after sections resolve, with `context.scope` being the agent: it
459
+ * warms the judgement and then rewrites our section's text from that fresh
460
+ * answer. Request 1 is correct and request 2 reproduces the same bytes.
461
+ *
462
+ * The tool-level `when` was the alternative early seam; it is worse here
463
+ * because it never runs when `tools.resolve` is unavailable or the boost tool
464
+ * is filtered out, and it cannot await `resolveByPath` without making a
465
+ * synchronous visibility predicate asynchronous. The assemble listener also
466
+ * costs nothing on tool-listing paths.
467
+ *
468
+ * `agent/pre-step` is the non-deprecated clock seam (`agent/request` is
469
+ * marked `@deprecated`); it fires once per proposed step with the host
470
+ * `turn`/`step`. `agent/request` is kept for the selector route, which only
471
+ * its resolved config carries, and as a clock/visibility fallback. A model
472
+ * request that reaches `llm/stream` without any observed `agent/request` is
473
+ * reported once with `ERR_HOST_NO_AGENT_REQUEST` instead of silently losing
474
+ * the route.
475
+ *
476
+ * `session/event` (`turn/end`), `session/flush` and `session/disposed` call
477
+ * `ReceiptStore.flush()` so the turn-end durability the design promises is
478
+ * real. `session/disposed` also drops every per-session map the assembly owns
479
+ * and tells the stores to evict their state.
480
+ */
481
+ function wireSessionEvents(ctx, deps, scope, registry, sessions, horizon, workspaces, routes, counters) {
482
+ /** Session ids seen at `agent/pre-step`; a `llm/stream` without a request is drift. */
483
+ const preStepSeen = new Set();
484
+ /** Session ids observed on `agent/request`. */
485
+ const requestSeen = new Set();
486
+ let warnedMissingRequest = false;
487
+ /** Warn once per process about a prompt that swallowed the protocol section. */
488
+ let warnedCompleteSection = false;
489
+ ctx.on('system-prompt/assemble', async (_assembly, context, next) => {
490
+ const resolved = await next();
491
+ try {
492
+ // `dsh-agent` augments `AssembleContext` with the real `Agent`; `scope`
493
+ // is an opaque `ScopeKey` and is never read as an Agent (review row 11).
494
+ // A diagnostic assembly has no agent: the documented no-scope view, so
495
+ // the section is suppressed and counted rather than keyed on a guess.
496
+ const carrier = (context ?? {});
497
+ const agent = carrier.agent;
498
+ const sessionId = sessionIdOf(agent);
499
+ if (sessionId === undefined) {
500
+ // The provider has nothing to key the judgement on and returns '';
501
+ // clear the section explicitly so a stale provider answer cannot leak
502
+ // into an assembly with no agent. Count the decision, not the
503
+ // section's presence — design §5.5:378 asks for every assembly to be
504
+ // judged.
505
+ counters.protocolSuppressed();
506
+ return patchProtocolSection(resolved, false);
507
+ }
508
+ const visible = await warmVisibility(scope, registry, agent, sessionId, workspaces);
509
+ // Same rule for an invisible workspace: the section is suppressed for
510
+ // this assembly, so the operator gets a live signal in `boost status`.
511
+ // A visible one never increments, so the count stays a failure count.
512
+ if (!visible)
513
+ counters.protocolSuppressed();
514
+ return patchProtocolSection(resolved, visible);
515
+ }
516
+ catch {
517
+ return resolved;
518
+ }
519
+ });
520
+ ctx.on('agent/pre-step', async (payload, next) => {
521
+ const request = (payload ?? {});
522
+ const sessionId = sessionIdOf(request.agent);
523
+ if (sessionId !== undefined) {
524
+ preStepSeen.add(sessionId);
525
+ try {
526
+ sessions.onModelRequest(sessionId, typeof request.turn === 'number' ? request.turn : Number(request.turn), typeof request.step === 'number' ? request.step : undefined);
527
+ }
528
+ catch {
529
+ // A clock that cannot be driven must not break the step.
530
+ }
531
+ try {
532
+ horizon.observe(sessionId, typeof request.turn === 'number' ? request.turn : Number(request.turn), typeof request.step === 'number' ? request.step : Number(request.step));
533
+ }
534
+ catch {
535
+ // History is an estimate; a bad observation is not a step failure.
536
+ }
537
+ // `agent/pre-step` already carries the captured step selection. It is
538
+ // the non-deprecated source for the selector route; `agent/request`'s
539
+ // resolved config remains a fallback for hosts that only populate it
540
+ // there (review row 37). A later request overwrites with the same route.
541
+ rememberRoute(routes, sessionId, request.modelSelection);
542
+ }
543
+ return next();
544
+ });
545
+ ctx.on('agent/request', async (payload, next) => {
546
+ const request = (payload ?? {});
547
+ const sessionId = sessionIdOf(request.agent);
548
+ if (sessionId !== undefined) {
549
+ requestSeen.add(sessionId);
550
+ try {
551
+ sessions.onModelRequest(sessionId, typeof request.turn === 'number' ? request.turn : Number(request.turn), typeof request.step === 'number' ? request.step : undefined);
552
+ }
553
+ catch {
554
+ // A clock that cannot be driven must not break the model request.
555
+ }
556
+ try {
557
+ horizon.observe(sessionId, typeof request.turn === 'number' ? request.turn : Number(request.turn), typeof request.step === 'number' ? request.step : Number(request.step));
558
+ }
559
+ catch {
560
+ // Same as the pre-step observation: history is an estimate.
561
+ }
562
+ await warmVisibility(scope, registry, request.agent, sessionId, workspaces);
563
+ }
564
+ const config = await next();
565
+ if (sessionId !== undefined)
566
+ rememberRoute(routes, sessionId, config);
567
+ return config;
568
+ });
569
+ // The deprecated event's disappearance would otherwise disable the selector
570
+ // route silently. A session that reached `llm/stream` after a pre-step but
571
+ // never saw `agent/request` is proof enough; the model request itself is
572
+ // passed through untouched.
573
+ //
574
+ // This listener is also the complete-section detector, and it MUST be
575
+ // outermost: the synthesizer mounted by `registerHooks` consumes a queued
576
+ // entry synchronously, so a detector registered after it would only mark the
577
+ // session unsubstitutable *after* the first affected request had already been
578
+ // substituted. Cordis runs the first-registered listener outermost
579
+ // (`events.ts` unshifts on `prepend`), so `prepend: true` is what puts the
580
+ // detector before the synthesizer regardless of mount order (finding 4).
581
+ ctx.on('llm/stream', (options, next) => {
582
+ try {
583
+ const request = (options ?? {});
584
+ const sessionId = request.sessionId;
585
+ if (!warnedMissingRequest &&
586
+ typeof sessionId === 'string' &&
587
+ preStepSeen.has(sessionId) &&
588
+ !requestSeen.has(sessionId)) {
589
+ warnedMissingRequest = true;
590
+ ctx.logger?.warn?.('ERR_HOST_NO_AGENT_REQUEST: agent/request was not observed before llm/stream; the selector route cannot be captured (the event is deprecated and may have been removed)');
591
+ }
592
+ // A `complete: true` prompt section replaces every other section after
593
+ // the assembly waterfall, so the protocol text
594
+ // `system-prompt/assemble` patched in is gone from the request the
595
+ // model actually receives. The host exposes no code or flag for that
596
+ // restoration; the outgoing system prompt is the first place it is
597
+ // observable. Detect it, count it, and fail closed: without the
598
+ // protocol there is nothing to teach the plan grammar, so substitution
599
+ // (and the projection that shares the same visibility gate) must not
600
+ // act for this request (review row 12).
601
+ //
602
+ // Only a main-agent request is evidence. Every auxiliary stream — the
603
+ // selector, compaction, and the default-on session-title provider —
604
+ // sets `purpose` and carries its own summariser prompt, which never
605
+ // contains the protocol section. Treating one as a swallow would count
606
+ // a suppression that never happened, flip the session's cached
607
+ // visibility off, and leave `ERR_HOST_COMPLETE_SECTION` in `status`
608
+ // for the rest of the process (review row 1). This is the same rule the
609
+ // synthesizer applies (`llm-stream.ts`: any `purpose` is auxiliary).
610
+ if (request.purpose === undefined &&
611
+ typeof sessionId === 'string' &&
612
+ scope.judgement(sessionId)) {
613
+ const systemText = systemTextOf(options);
614
+ if (systemText !== undefined && !systemText.includes(PROTOCOL_PROBE)) {
615
+ counters.protocolSuppressed();
616
+ counters.protocolMissing();
617
+ scope.remember(sessionId, false);
618
+ if (!warnedCompleteSection) {
619
+ warnedCompleteSection = true;
620
+ ctx.logger?.warn?.('ERR_HOST_COMPLETE_SECTION: the final system prompt does not carry the dsh-boost protocol section (a complete prompt section replaced the assembly); substitution is disabled for affected requests');
621
+ }
622
+ }
623
+ }
624
+ }
625
+ catch {
626
+ // Detection must never break the model request.
627
+ }
628
+ return next();
629
+ }, { prepend: true });
630
+ // `session/event` carries a plain `type` string, so `turn/end` is matched by
631
+ // value, not by a stable code. That match is a convenience: it flushes early
632
+ // on the common path, but it is not the durability boundary. The host does
633
+ // not await this listener, so a process exit immediately after `turn/end`
634
+ // can drop the flush; the awaited `session/flush` below is what the
635
+ // persistence contract rests on, and `session/disposed` flushes again after
636
+ // the last hook for the id. Receipts are evidence, so an early flush that
637
+ // does not happen costs latency, never correctness.
638
+ ctx.on('session/event', (_session, event) => {
639
+ const type = event?.type;
640
+ if (type === 'turn/end') {
641
+ // Fire-and-forget on the real host; `flush()` never rejects.
642
+ return deps.receipts.flush();
643
+ }
644
+ return undefined;
645
+ });
646
+ ctx.on('session/flush', () => deps.receipts.flush());
647
+ ctx.on('session/disposed', async (session) => {
648
+ const sessionId = sessionIdOf(session);
649
+ if (sessionId === undefined)
650
+ return;
651
+ try {
652
+ clearSession(deps, sessionId);
653
+ }
654
+ catch {
655
+ // Session end owns no tool result; a failed clear must not throw here.
656
+ }
657
+ sessions.markDisposed(sessionId);
658
+ workspaces.delete(sessionId);
659
+ routes.delete(sessionId);
660
+ requestSeen.delete(sessionId);
661
+ preStepSeen.delete(sessionId);
662
+ horizon.clear(sessionId);
663
+ scope.forget(sessionId);
664
+ // Flush this session's buffered lines before evicting its state, then make
665
+ // every later hook for the id a no-op.
666
+ try {
667
+ await deps.receipts.flush();
668
+ }
669
+ catch {
670
+ // Flush is total; a foreign store must not break session end.
671
+ }
672
+ deps.receipts.disposeSession(sessionId);
673
+ });
674
+ }
675
+ /**
676
+ * Register the `boost` tool family.
677
+ *
678
+ * After T19 the family is just this one tool. The tool itself is scope-exempt
679
+ * (`when: () => true`) because it is the only way a user can enable a workspace
680
+ * that is not enabled yet — gating it on the scope document would make
681
+ * `selected + []` impossible to leave. The protocol section is not exempt; T17
682
+ * already handles it.
683
+ *
684
+ * No step-`when` capability probe is needed: the condition is constant-true, so
685
+ * a host that ignored the registration options would register it
686
+ * unconditionally — exactly the behaviour this build wants. The old probe only
687
+ * tested `typeof tools.register === 'function'`, which every host since
688
+ * 0.2.2-rc.1 satisfies, so the branch it fed could never run; it was removed
689
+ * rather than left as a claim that can never be false.
690
+ */
691
+ function registerBoostTool(ctx, deps) {
692
+ // Annotating with the host's ToolDefinition makes a host-side tightening a
693
+ // build error instead of a runtime registration failure. The tool is
694
+ // scope-exempt by design (`when: () => true`), so it needs no registry: the
695
+ // registry is only the visibility warm's input, wired above.
696
+ const definition = boostTool(deps);
697
+ ctx.tools.register(definition, { when: () => true });
698
+ }
699
+ /** The mount label the prompt section reports when it cannot be registered. */
700
+ const MOUNT_SECTION = 'systemPrompt.section';
701
+ /**
702
+ * Mount the four integration points, attributing each failure.
703
+ *
704
+ * `registerHooks` mounts the prompt section first and aborts on its failure, so
705
+ * handing it the real context would lose the three event mounts whenever the
706
+ * section is rejected — while `apply` logged "continuing with the remaining
707
+ * mounts" and `status` still reported `degraded: []` (review row 2). It is
708
+ * called with a recording context instead: the section is registered
709
+ * immediately (its duplicate check must happen before anything else is
710
+ * mounted), a rejection is recorded rather than rethrown so `registerHooks`
711
+ * still describes the three event mounts, and those are then mounted one by one
712
+ * so a failure names the mount that failed and lands in `missing`.
713
+ *
714
+ * Returns `true` when the section error is the host's duplicate-registration
715
+ * error: a previous apply owns every mount and this one must register nothing.
716
+ */
717
+ function mountHooks(ctx, deps, missing) {
718
+ const deferred = [];
719
+ let sectionError;
720
+ let registrationError;
721
+ const recording = {
722
+ logger: ctx.logger,
723
+ on(event, handler, options) {
724
+ deferred.push({ event, handler, options });
725
+ },
726
+ systemPrompt: {
727
+ section(section) {
728
+ try {
729
+ ctx.systemPrompt.section(section);
730
+ }
731
+ catch (error) {
732
+ // Record, do not rethrow: `registerHooks` aborts on a throwing
733
+ // section, and the other three mounts must still be described.
734
+ sectionError = error;
735
+ }
736
+ },
737
+ },
738
+ };
739
+ try {
740
+ registerHooks(recording, deps);
741
+ }
742
+ catch (error) {
743
+ registrationError = error;
744
+ }
745
+ if (sectionError !== undefined && isDuplicateSectionError(sectionError)) {
746
+ duplicateMountAttempts += 1;
747
+ ctx.logger?.warn?.(`dsh-boost: ERR_BOOST_ALREADY_MOUNTED: duplicate apply #${duplicateMountAttempts} found an existing mount; registration skipped (${messageOf(sectionError)})`);
748
+ return true;
749
+ }
750
+ if (sectionError !== undefined) {
751
+ missing.add(MOUNT_SECTION);
752
+ ctx.logger?.warn?.(`dsh-boost: ERR_BOOST_SECTION_REGISTER_FAILED: prompt section registration failed; mounting the remaining hooks independently (${messageOf(sectionError)})`);
753
+ }
754
+ else if (registrationError !== undefined) {
755
+ // The section did not throw, so this is an assembly bug: an unknown mount
756
+ // is missing even though no specific one can be named.
757
+ missing.add('hooks');
758
+ ctx.logger?.warn?.(`dsh-boost: ERR_BOOST_PARTIAL_MOUNT: hook assembly failed (${messageOf(registrationError)})`);
759
+ }
760
+ for (const mount of deferred) {
761
+ try {
762
+ ctx.on(mount.event, mount.handler, mount.options);
763
+ }
764
+ catch (error) {
765
+ missing.add(mount.event);
766
+ ctx.logger?.warn?.(`dsh-boost: ERR_BOOST_PARTIAL_MOUNT: ${mount.event} mount failed (${messageOf(error)})`);
767
+ }
768
+ }
769
+ if (missing.size > 0) {
770
+ ctx.logger?.warn?.(`dsh-boost: ERR_BOOST_PARTIAL_MOUNT: missing mount(s): ${[...missing].join(', ')}; the plugin is partially wired and boost status reports this code`);
771
+ }
772
+ return false;
773
+ }
774
+ export function apply(ctx, config) {
775
+ const repairs = [];
776
+ const cfg = resolveConfig(config, message => {
777
+ repairs.push(message);
778
+ ctx.logger?.warn?.(message);
779
+ });
780
+ // The effective-config line serialises `resolveConfig`'s output, which never
781
+ // carries `dshHome` (that override is resolved by `resolveBoostRoot`). Log
782
+ // the resolved root with it, once, so the operator can see the state root in
783
+ // use — including the `$DSH_HOME`/`~/.dsh` fallback and the cwd resolution of
784
+ // a relative override.
785
+ let root;
786
+ try {
787
+ root = resolveBoostRoot(config);
788
+ }
789
+ catch (error) {
790
+ ctx.logger?.warn?.(`dsh-boost: cannot resolve the state root: ${messageOf(error)}`);
791
+ return;
792
+ }
793
+ // One line with the effective values (not only the keys this module happens
794
+ // to use): an operator can see every clamp and fallback instead of guessing.
795
+ ctx.logger?.info?.(`dsh-boost loaded (stepsPerTurn=${cfg.stepsPerTurn}, horizonSteps=${cfg.horizonSteps}); effective config=${JSON.stringify(cfg)}; root=${root}`);
796
+ if (repairs.length > 0) {
797
+ ctx.logger?.info?.(`dsh-boost: ${repairs.length} configuration value(s) repaired`);
798
+ }
799
+ // The only version guard outside the managed-install preflight. Advisory:
800
+ // an unverified host is a warning, never a refusal to load.
801
+ reportHostVersion(ctx);
802
+ if (!canRegister(ctx)) {
803
+ ctx.logger?.warn?.('dsh-boost: host hook services unavailable; registration skipped');
804
+ return;
805
+ }
806
+ try {
807
+ // The root was resolved above (D4) so the log can show it; both stores use
808
+ // the same value. `resolveBoostRoot` is the only root rule (design §10), so
809
+ // `apply` and the hook stores cannot diverge.
810
+ const scope = new ScopeStore(root, { warn: (message) => ctx.logger?.warn?.(message) });
811
+ const receipts = new ReceiptStore(root);
812
+ const anchors = new AnchorStore();
813
+ const queue = new PendingQueue();
814
+ const plans = new Map();
815
+ const sessions = new DisposalAwareSessionRuntime(cfg.stepsPerTurn);
816
+ const horizon = new RuntimeStepHorizon(cfg.horizonSteps, cfg.historyTurns);
817
+ const retrievals = new RetrievalLedger();
818
+ /** Session id → workspace id, populated by the visibility warm. */
819
+ const workspaces = new Map();
820
+ /** Session id → the route the selector call inherits. */
821
+ const routes = new Map();
822
+ // Soft host services. Cordis activates sibling providers concurrently, so
823
+ // these getters retry until the provider fiber is ACTIVE; an absence is
824
+ // never memoised. The workspace registry is the `resolveByPath`/`list()`
825
+ // seam; the spill store is the projection backend; the token meter prices
826
+ // projections and admission.
827
+ const registry = lazyService(ctx, 'workspaceRegistry');
828
+ const spillService = lazyService(ctx, 'spillStore');
829
+ /**
830
+ * The spill backend the decision path uses, with a failure re-probe.
831
+ *
832
+ * A store that resolved is not a store that works: `saveText` rejecting is
833
+ * the only evidence the projection path gets (`projection-skipped:spill-failed`),
834
+ * and memoising that first success forever would keep every later
835
+ * projection pointed at a dead backend while `hasSpill` stayed true. A
836
+ * rejection therefore drops the memo; the next decision asks `ctx.get`
837
+ * again, which cordis answers from the provider fiber's live state.
838
+ */
839
+ const spillBackend = () => {
840
+ const backend = spillService();
841
+ if (backend === undefined)
842
+ return undefined;
843
+ return {
844
+ saveText: async (input) => {
845
+ try {
846
+ return await backend.saveText(input);
847
+ }
848
+ catch (error) {
849
+ spillService.reset();
850
+ throw error;
851
+ }
852
+ },
853
+ };
854
+ };
855
+ // `llm` is soft (see `inject`): projection and admission never need it, and
856
+ // the selector checks it at call time. A getter keeps a provider that
857
+ // becomes active after `apply` reachable on the next decision.
858
+ const llm = lazyService(ctx, 'llm');
859
+ const meter = meterSeamOf(ctx);
860
+ const projectionCounters = new ProjectionCounters();
861
+ // Host capabilities `status` renders as stable codes. Getters keep them
862
+ // facts about the host *now*: a service that appears after `apply` must not
863
+ // leave a permanent `ERR_HOST_NO_*`. The fixed-cost probe starts here
864
+ // (startup time) and is awaited only by `status` — it is deliberately not
865
+ // on any request path.
866
+ const hostFacts = {
867
+ get hasTokenMeter() {
868
+ return meter.kind() === 'host';
869
+ },
870
+ get hasSpill() {
871
+ return spillService() !== undefined;
872
+ },
873
+ get hasWorkspaceRegistry() {
874
+ return registry() !== undefined;
875
+ },
876
+ };
877
+ const fixedOverhead = measureBoostFixedOverhead();
878
+ // The hook reads this synchronously, so it only ever returns the warmed
879
+ // answer. The map alone is not the answer: a workspace disabled between
880
+ // commit and synthesis leaves the id behind but flips `judgement` to false.
881
+ const resolveSession = (sessionId) => {
882
+ try {
883
+ if (!scope.judgement(sessionId))
884
+ return undefined;
885
+ return workspaces.get(sessionId);
886
+ }
887
+ catch {
888
+ return undefined;
889
+ }
890
+ };
891
+ // `deps` MUST stay the same object `registerHooks` receives: it publishes
892
+ // the created `ReceiptSessionState` onto `deps.sessionState`, and
893
+ // `clearSession(deps, id)` can only reach it through that reference.
894
+ const deps = {
895
+ config: cfg,
896
+ scope,
897
+ receipts,
898
+ anchors,
899
+ resolveSession,
900
+ queue,
901
+ plans,
902
+ sessions,
903
+ // Getters, not snapshots: the hook reads them per decision, so a service
904
+ // that becomes active after `apply` is picked up on the next call.
905
+ get spill() {
906
+ return spillBackend();
907
+ },
908
+ retrievals,
909
+ get estimateText() {
910
+ return meter.estimate();
911
+ },
912
+ get estimateKind() {
913
+ return meter.kind();
914
+ },
915
+ projectionCounters,
916
+ // The live horizon, so a projection receipt pins the value its own
917
+ // decision was made under instead of whatever the cross-session minimum
918
+ // happens to be when an operator runs `boost status` (design §5.3).
919
+ horizonFor: (sessionId) => horizon.remainingFor(sessionId),
920
+ // The dispatch mirror lives in the post-execute module and `clearSession`
921
+ // lives in the stream module; this is the seam that lets a disposal drop
922
+ // the mirror instead of leaking one entry per disposed session.
923
+ clearAcceptedDispatch: (sessionId) => clearAcceptedDispatch(deps, sessionId),
924
+ get llm() {
925
+ return llm();
926
+ },
927
+ selectorRoute: (sessionId) => routes.get(sessionId),
928
+ };
929
+ // The section mount is the first thing `registerHooks` touches. Only the
930
+ // host's genuine duplicate error means a previous apply already owns the
931
+ // mounts; every other throw is a wiring failure that must be named, must
932
+ // not take the other three mounts (or the control tool) down with it, and
933
+ // must be visible in `status` as `ERR_BOOST_PARTIAL_MOUNT` (review row 2).
934
+ const missingMounts = new Set();
935
+ if (mountHooks(ctx, deps, missingMounts))
936
+ return;
937
+ // The clock/visibility warm and the session-end cleanup. Wired separately
938
+ // so a host that cannot accept these events still gets the tool below.
939
+ try {
940
+ wireSessionEvents(ctx, deps, scope, registry, sessions, horizon, workspaces, routes, projectionCounters);
941
+ }
942
+ catch (error) {
943
+ ctx.logger?.warn?.(`dsh-boost: session wiring failed: ${messageOf(error)}`);
944
+ }
945
+ // After the hooks: a genuine duplicate aborts above before it can register
946
+ // the tool twice. A different section failure still reaches here, and so
947
+ // does a tool registration failure of its own — neither may be swallowed
948
+ // behind the other's diagnosis.
949
+ try {
950
+ registerBoostTool(ctx, {
951
+ scope,
952
+ receipts,
953
+ host: hostFacts,
954
+ fixedOverhead: () => fixedOverhead,
955
+ get estimateKind() {
956
+ return meter.kind();
957
+ },
958
+ // Design §5.3's runtime horizon: min(config horizon, mean of the last
959
+ // `historyTurns` completed turns) over live sessions. `runBoost` spreads
960
+ // the deps when it is called, so this getter is read at status time.
961
+ get horizonSteps() {
962
+ return horizon.remaining();
963
+ },
964
+ locatorEvictions: () => retrievals.evictions(),
965
+ receiptReadErrors: () => receipts.readErrors(),
966
+ receiptsTruncated: () => receipts.scanTruncated(),
967
+ unknownFamilies: () => projectionCounters.unknownFamilies(),
968
+ unknownTools: () => projectionCounters.unknownToolCounts(),
969
+ protocolSuppressed: () => projectionCounters.protocolSuppressions(),
970
+ completeSectionSuppressions: () => projectionCounters.protocolMissings(),
971
+ partialMounts: () => [...missingMounts],
972
+ });
973
+ }
974
+ catch (error) {
975
+ // The tool is the user's only control surface; its failure is reported
976
+ // on its own, never as a hook failure.
977
+ ctx.logger?.warn?.(`dsh-boost: boost tool registration failed (ERR_BOOST_TOOL_REGISTER_FAILED): ${messageOf(error)}`);
978
+ }
979
+ }
980
+ catch (error) {
981
+ ctx.logger?.warn?.(`dsh-boost: hook registration skipped: ${messageOf(error)}`);
982
+ }
983
+ }
984
+ //# sourceMappingURL=index.js.map