dsh-boost 0.0.0-stage → 0.1.0

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