dsh-boost 0.1.1 → 0.1.2

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 (48) hide show
  1. package/README.en.md +97 -33
  2. package/README.md +85 -32
  3. package/dist/gate/decide.js +33 -2
  4. package/dist/gate/decide.js.map +1 -1
  5. package/dist/hooks/llm-stream.js +129 -54
  6. package/dist/hooks/llm-stream.js.map +1 -1
  7. package/dist/hooks/post-execute.js +104 -21
  8. package/dist/hooks/post-execute.js.map +1 -1
  9. package/dist/hooks/session-state.js +18 -8
  10. package/dist/hooks/session-state.js.map +1 -1
  11. package/dist/index.js +371 -67
  12. package/dist/index.js.map +1 -1
  13. package/dist/scope/doc.js.map +1 -1
  14. package/dist/scope/store.js +24 -9
  15. package/dist/scope/store.js.map +1 -1
  16. package/package.json +8 -4
  17. package/dist/admission/fixed-cost.d.ts +0 -23
  18. package/dist/admission/ledger.d.ts +0 -113
  19. package/dist/admission/retrieval.d.ts +0 -65
  20. package/dist/admission/usage.d.ts +0 -75
  21. package/dist/config.d.ts +0 -43
  22. package/dist/gate/binding.d.ts +0 -113
  23. package/dist/gate/decide.d.ts +0 -82
  24. package/dist/gate/guard.d.ts +0 -69
  25. package/dist/gate/invalidate.d.ts +0 -112
  26. package/dist/gate/plan.d.ts +0 -86
  27. package/dist/hooks/clock.d.ts +0 -68
  28. package/dist/hooks/execute.d.ts +0 -79
  29. package/dist/hooks/llm-stream.d.ts +0 -283
  30. package/dist/hooks/pending.d.ts +0 -89
  31. package/dist/hooks/post-execute.d.ts +0 -257
  32. package/dist/hooks/session-state.d.ts +0 -158
  33. package/dist/hooks/synthesize.d.ts +0 -74
  34. package/dist/host/loader.d.ts +0 -23
  35. package/dist/host/platform.d.ts +0 -18
  36. package/dist/host/root.d.ts +0 -25
  37. package/dist/projection/apply.d.ts +0 -174
  38. package/dist/projection/canonicalise.d.ts +0 -43
  39. package/dist/projection/counters.d.ts +0 -65
  40. package/dist/projection/truncate.d.ts +0 -47
  41. package/dist/prompt/protocol.d.ts +0 -45
  42. package/dist/receipts/store.d.ts +0 -198
  43. package/dist/scope/doc.d.ts +0 -117
  44. package/dist/scope/resolve.d.ts +0 -91
  45. package/dist/scope/store.d.ts +0 -135
  46. package/dist/selector/jev.d.ts +0 -93
  47. package/dist/tools/boost.d.ts +0 -380
  48. package/dist/tools/family.d.ts +0 -26
@@ -1,158 +0,0 @@
1
- /**
2
- * Per-session bookkeeping for the post-execute decision path.
3
- *
4
- * The receipt/dispatch maps below are the class's own state. The module also
5
- * owns the small plumbing both hook modules share — queue/anchor/plan access,
6
- * receipt appends, the clock-turn read and receipt previews — so the two
7
- * former copies cannot drift (in particular, their `clockTurnOf` fallbacks
8
- * disagreed on `0` vs `undefined`).
9
- *
10
- * Both maps are keyed by session id and scoped to one host turn
11
- * (design §5.2-7: the anchor cache expires at turn end):
12
- *
13
- * - **Receipts.** `decide` evaluates guards and `$public` templates against the
14
- * receipt that just arrived (filed under `'root'`) *and* the receipts of the
15
- * calls this plugin substituted earlier in the turn (filed under the plan
16
- * candidate id). Without the second half a later step's
17
- * `{ "$public": { "after": "A" … } }` can never bind, so the plan could only
18
- * ever commit its first step.
19
- * - **In-flight dispatches.** `tools/execute` clears the pending entry once the
20
- * arriving call's id matches it (on accept or reject); a call with a different
21
- * id passes through untouched. `tools/post-execute` still needs to know which
22
- * candidate the arriving call belonged to. The execute hook records `callId -> candidateId` here
23
- * before clearing, and the post-execute hook consumes it once.
24
- *
25
- * A new host turn drops both maps. Turn detection is lazy: the hooks see no
26
- * turn-end event, so the first call of a new turn is what folds the old turn
27
- * away. Nothing here throws on its own, but every method is still called from
28
- * inside the hooks' `try` blocks, because the callers own the no-throw
29
- * contract with the host.
30
- *
31
- * **Lifetime.** One entry per session, scoped to the host turn. A session's
32
- * entry is replaced on the first call of its next turn, so the steady-state
33
- * retention is one turn's receipts (at most 27: `'root'` plus the plan's
34
- * `A`–`Z`) and any in-flight dispatches. `session/disposed` is wired in
35
- * `src/index.ts`, which calls `clearSession(deps, sessionId)`; that drops this
36
- * state along with the queue, anchors, plan and per-session runtime, so a
37
- * disposed session leaves nothing behind.
38
- *
39
- * The class's internals stay private (`HookDeps` exposes only the optional
40
- * instance), and only the plumbing helpers are exported. It lives apart from
41
- * `post-execute.ts` because that file already carries the four mount bodies and
42
- * the eleven obligations; mixing a mutable session map into it would make the
43
- * hook harder to audit.
44
- *
45
- * @module dsh-boost/hooks/session-state
46
- */
47
- import type { ReceiptAnchors } from '../gate/invalidate.js';
48
- import type { ReceiptStore } from '../receipts/store.js';
49
- import type { CanonicalReceipt } from '../projection/canonicalise.js';
50
- import type { TurnClock } from './clock.js';
51
- import type { PendingEntry, PendingQueue } from './pending.js';
52
- /** One session's receipts and in-flight dispatches for the current turn. */
53
- interface SessionEntry {
54
- /** The host turn the entry belongs to; a different turn resets it. */
55
- turn: number;
56
- /** Receipts keyed by `'root'` or a plan candidate id. */
57
- receipts: Map<string, CanonicalReceipt>;
58
- /** `callId -> candidateId` for substitutions the execute hook accepted. */
59
- dispatches: Map<string, string>;
60
- }
61
- /**
62
- * Receipt and dispatch memory for every session the plugin has seen.
63
- *
64
- * `begin` is the only reader that can fold a turn away; callers use it once per
65
- * hook invocation and then use the rest of the API. There is no eviction within
66
- * a turn: a session's candidate receipts are exactly the steps of the current
67
- * plan, and plan parsing caps a plan at 26 steps (`A`–`Z`).
68
- */
69
- export declare class ReceiptSessionState {
70
- private readonly bySession;
71
- /**
72
- * Return the state for `sessionId` at `turn`, discarding a previous turn's
73
- * receipts and dispatches.
74
- *
75
- * `rolledOver` tells the caller that the previous turn's anchors (which live
76
- * in `AnchorStore`, not here) are stale too and must be dropped. A brand-new
77
- * session has nothing to roll over, so it reports `false`.
78
- */
79
- begin(sessionId: string, turn: number): {
80
- entry: SessionEntry;
81
- rolledOver: boolean;
82
- };
83
- /** File the receipt that just arrived under `'root'`, keeping candidate receipts. */
84
- recordRoot(sessionId: string, turn: number, receipt: CanonicalReceipt): void;
85
- /** File an executed candidate's receipt under its plan candidate id. */
86
- recordCandidate(sessionId: string, turn: number, candidateId: string, receipt: CanonicalReceipt): void;
87
- /** The receipt map `decide` reads; contains `'root'` after `recordRoot`. */
88
- receiptsFor(sessionId: string, turn: number): ReadonlyMap<string, CanonicalReceipt>;
89
- /** Remember which candidate a dispatched call id belongs to. */
90
- recordDispatch(sessionId: string, turn: number, callId: string, candidateId: string): void;
91
- /** Consume the candidate id for `callId`, or `undefined` when the call is not one of ours. */
92
- takeDispatch(sessionId: string, turn: number, callId: string): string | undefined;
93
- /**
94
- * Drop everything for one session: both maps and the stored turn.
95
- *
96
- * `src/index.ts` calls this from its `session/disposed` listener through
97
- * `clearSession`; the hooks themselves only replace an entry lazily when the
98
- * next turn's first call arrives.
99
- */
100
- clear(sessionId: string): void;
101
- }
102
- /** The store's append input, shared by both hook modules. */
103
- export type ReceiptInput = Parameters<ReceiptStore['append']>[0];
104
- /** The dependencies these helpers read; `HookDeps` is structurally assignable. */
105
- export interface SessionPlumbing {
106
- /** Shared fallback clock when no per-session runtime is wired. */
107
- clock?: TurnClock;
108
- /** Per-session runtime; its clock is authoritative when present. */
109
- sessions?: {
110
- clockFor(sessionId: string): TurnClock;
111
- };
112
- /** At most one pending substitution per session. */
113
- queue?: PendingQueue;
114
- /** Per-session receipt anchors. */
115
- anchors?: {
116
- get(sessionId: string): ReceiptAnchors | undefined;
117
- clear(sessionId: string): void;
118
- };
119
- /** Append-only receipt store. */
120
- receipts?: ReceiptStore;
121
- /** Parsed plans, keyed by session. */
122
- plans?: {
123
- delete(sessionId: string): boolean;
124
- };
125
- }
126
- /**
127
- * The session's host turn, or `undefined` when no clock can answer a real turn.
128
- *
129
- * The per-session runtime wins over the shared fallback, exactly as in
130
- * `sessionClock`. A clock that throws, a missing clock and a non-finite or
131
- * non-positive turn all mean "no host turn": `TurnClock` reports 0 before the
132
- * first `agent/request`, and real host turns start at 1. Callers that need a
133
- * number for a receipt field write `?? 0`; callers that decide turn validity
134
- * keep the `undefined` distinction.
135
- */
136
- export declare function clockTurnOf(deps: SessionPlumbing, sessionId: string): number | undefined;
137
- /** The pending entry for a session, never removing it and never throwing. */
138
- export declare function peekPending(deps: SessionPlumbing, sessionId: string): PendingEntry | undefined;
139
- /** Drop the session's pending entry; a foreign queue must not break the call. */
140
- export declare function clearPending(deps: SessionPlumbing, sessionId: string): void;
141
- /** Drop the session's anchors; a foreign store must not break the call. */
142
- export declare function clearAnchors(deps: SessionPlumbing, sessionId: string): void;
143
- /** Drop the session's parsed plan; a foreign map must not break the call. */
144
- export declare function clearPlan(deps: SessionPlumbing, sessionId: string): void;
145
- /** Append one receipt; a receipt is evidence, never a precondition. */
146
- export declare function appendReceipt(deps: SessionPlumbing, receipt: ReceiptInput): Promise<void>;
147
- /** The first 256 code points of a canonical receipt, or of a synthesized call. */
148
- export declare function previewOf(text: string | undefined): string;
149
- /**
150
- * The evidence line for a receipt that predates its tool result.
151
- *
152
- * A substitute or a refused dispatch has no canonical tool result yet, so its
153
- * preview names the call that is being made (or was refused): the operator's
154
- * question is "why did this call run?", and the name plus bound args is the
155
- * answer available at that point.
156
- */
157
- export declare function callPreview(name: string, args: unknown): string;
158
- export {};
@@ -1,74 +0,0 @@
1
- /**
2
- * The synthesized model turn: a fake assistant reply that asks for the tool
3
- * call the plugin already decided on.
4
- *
5
- * The host's agent loop consumes chunks and then dispatches the tool call it
6
- * saw. The chunk sequence is therefore a protocol, not a presentation choice:
7
- *
8
- * 1. a `reasoning` block, then
9
- * 2. a `tool-call` block, then
10
- * 3. a terminal `finish` with reason `tool-calls`.
11
- *
12
- * The reasoning block is emitted first so the assistant turn carries the
13
- * sibling a reasoning-preserving adapter needs. DeepSeek's thinking mode
14
- * requires the assistant `tool_use` message to carry a sibling `thinking` block
15
- * (`content[].thinking … must be passed back`, appendix §7), and a synthesized
16
- * turn with only a `tool-call` block cannot satisfy that on such a route.
17
- *
18
- * It does **not** reach the wire on this host build's current
19
- * `openai-completions` route. A settled assistant message with no `replayState`
20
- * is routed to `foreignAssistant` and stamped `api:'dsh-foreign'`
21
- * (`dsh-llm-pi-ai/lib/index.js:180,250-252`), and pi-ai's `transformMessages`
22
- * drops every thinking block of a non-same-model message
23
- * (`transform-messages.js:87-96`). Emitting the block is still the right shape
24
- * and costs nothing — a route that preserves reasoning needs it — but whether a
25
- * route that enforces the sibling rule is satisfied end to end is a Task 24
26
- * question, not a claim this module makes.
27
- *
28
- * The host's `ReasoningBlock` has exactly `type` and `text` — there is no
29
- * signature field to fill in — so the block is emitted unsigned.
30
- *
31
- * No `usage` chunk is emitted: nothing was measured, and a fabricated usage
32
- * would corrupt the token ledger. The chunk shape follows
33
- * `StreamChunk`/`ContentBlock` in `@deepseek-ai/dsh-llm/types` field by field;
34
- * in particular `tool-call.arguments` is the raw JSON string and must be
35
- * byte-identical to the `argumentsDelta` that streamed it.
36
- *
37
- * The generator is pure over `e`: it reads no clock, no queue, and no I/O, so
38
- * the same entry always produces the same chunks.
39
- *
40
- * @module dsh-boost/hooks/synthesize
41
- */
42
- import type { StreamChunk } from '@deepseek-ai/dsh-llm';
43
- import type { PendingEntry } from './pending.js';
44
- /**
45
- * Stream the turn that asks for `e`'s tool call.
46
- *
47
- * Yields, in order and with these indexes:
48
- *
49
- * ```text
50
- * block-start {index:0, blockType:'reasoning'}
51
- * reasoning-delta {index:0, text}
52
- * block-end {index:0, block:{type:'reasoning', text}}
53
- * block-start {index:1, blockType:'tool-call'}
54
- * tool-call-delta {index:1, id, name, argumentsDelta}
55
- * block-end {index:1, block:{type:'tool-call', id, name, arguments}}
56
- * finish {reason:{kind:'tool-calls'}}
57
- * ```
58
- *
59
- * **Invalid call id.** A `PendingEntry` with a blank `callId` (empty or
60
- * whitespace-only) violates this module's contract and cannot be repaired here:
61
- * inventing one would make the execute-side tamper check compare a different id
62
- * and reject every dispatch silently. The generator throws `RangeError` before
63
- * its first yield, so no partial turn reaches the host.
64
- *
65
- * **Unserialisable arguments.** `args` is plan-validated JSON in production,
66
- * but this function is exported and must be total. When `JSON.stringify`
67
- * throws (a `BigInt`, a cycle) or returns `undefined`, the turn emits the
68
- * reasoning block and then a terminal `finish` with `kind:'error'` — it never
69
- * emits a `tool-call` block, because substituting an empty or partial argument
70
- * object would dispatch a call nobody decided. The error is a protocol chunk,
71
- * not a thrown exception: appendix §1.1 defines errors as `finish.reason`, and
72
- * a partially-consumed stream must not blow up the host loop.
73
- */
74
- export declare function synthesizeTurn(e: PendingEntry): AsyncIterable<StreamChunk>;
@@ -1,23 +0,0 @@
1
- /**
2
- * The optional-peer import seam.
3
- *
4
- * A static `import` of an optional host package is `ERR_MODULE_NOT_FOUND` at
5
- * module-evaluation time, which kills the whole plugin before any degradation
6
- * path can run (design §5.4/§9). Every optional peer — the spill policy and the
7
- * token meter — must therefore load through this function, which turns a
8
- * missing package (or one that throws while evaluating) into `undefined`.
9
- *
10
- * The function is deliberately total: a broken peer is the same as an absent
11
- * one for the plugin's purposes, and a host that installed it badly must still
12
- * get the plugin's degraded mode rather than a failed load.
13
- *
14
- * @module dsh-boost/host/loader
15
- */
16
- /**
17
- * Import `specifier`, or return `undefined` when it cannot be loaded.
18
- *
19
- * `T` is the module namespace the caller expects; it is not validated here —
20
- * callers check the individual export they use, because a package can exist
21
- * while an export is missing in another version.
22
- */
23
- export declare function loadOptional<T>(specifier: string): Promise<T | undefined>;
@@ -1,18 +0,0 @@
1
- /**
2
- * Platform capability: is the host a POSIX system?
3
- *
4
- * Substitution depends on POSIX process semantics (the dispatched call is
5
- * synthesised and replayed through the host's tool pipeline), so on Windows it
6
- * is refused. Projection does not depend on the platform and stays on. The
7
- * refusal is not silent: `dsh-boost`'s `boost status` reports
8
- * `ERR_HOST_PLATFORM_UNSUPPORTED` (design §9).
9
- *
10
- * The predicate reads `process.platform` at call time rather than caching it at
11
- * module load, which is what makes the platform a seam a test can control
12
- * (`Object.defineProperty(process, 'platform', …)`): a load-time constant would
13
- * freeze the value before the test could change it.
14
- *
15
- * @module dsh-boost/host/platform
16
- */
17
- /** Whether substitution may run on this host. Only `win32` is excluded. */
18
- export declare const isPosixOnly: () => boolean;
@@ -1,25 +0,0 @@
1
- /**
2
- * `<DSH_HOME>/boost`, falling back to `<homedir>/.dsh/boost`.
3
- *
4
- * A `config.dshHome` override wins over the environment, matching the other
5
- * host plugins (`dsh-mcp-btwy` resolves `config.dshHome` before `$DSH_HOME`):
6
- * an operator who patches the plugin row should not have to change the
7
- * process environment for all plugins. A non-string or blank override is
8
- * ignored and the environment rule applies.
9
- *
10
- * A blank value is treated as unset: `join('', 'boost')` would otherwise put
11
- * state in the process's working directory, which is not a home directory.
12
- *
13
- * A relative home is resolved against the current cwd **once**, here.
14
- * Passing it through would leave the stores resolving it again on every read,
15
- * so a later `chdir` would silently move the state root mid-session (review
16
- * minor).
17
- *
18
- * A leading `~` is expanded exactly as the host's `expandHomePath`
19
- * (`@deepseek-ai/dsh-home-paths`) does: `~` is the home directory and `~/` or
20
- * `~\` are joined under it. The host applies that rule to `$DSH_HOME` and to a
21
- * configured `dshHome` before resolving; without it `DSH_HOME='~/x'` would
22
- * create a literal `~` directory under the cwd while the host's own home is
23
- * `$HOME/x`, and `boost status` would read an empty ledger (review row 30).
24
- */
25
- export declare function resolveBoostRoot(config?: unknown): string;
@@ -1,174 +0,0 @@
1
- /**
2
- * Projection execution: the shadow accounting and the real replacement.
3
- *
4
- * `projectShadow` is the half of projection that never changes what the model
5
- * sees: it decides whether a receipt *would* be cut, composes the replacement
6
- * string `projectApply` would produce, and prices both sides in tokens through
7
- * the caller's `estimate`. It writes nothing and reads no host service, so the
8
- * caller alone decides which mode to invoke (design §5.4).
9
- *
10
- * `projectApply` is the half that replaces, and it only replaces what is still
11
- * recoverable: the canonical receipt is persisted through the injected spill
12
- * backend first, then head line, head, spill footer and tail are composed. All
13
- * guards run before the write, a failed write or footer is a skip rather than
14
- * an exception, and a footer that would grow the receipt sends the original
15
- * back unchanged — a projection that grows a receipt defeats the plugin's
16
- * premise.
17
- *
18
- * The projected size is composed here, not read off `Truncation.after`:
19
- * `after` is the head line plus the two windows *without* the omission note, so
20
- * it is only a lower bound on the final replacement. Shadow mode prices
21
- * `renderHeadLine + head + omission note + tail`; the note's locator part is
22
- * unknown before the spill write, so only the standardized omission clause is
23
- * included.
24
- *
25
- * Skip reasons are stable codes, never prose: `error-receipt` (an error receipt
26
- * is evidence and is never projected), `family-not-configured` (the family has
27
- * no window), `not-worth-it` (`truncate`'s guard said no, or the footer left no
28
- * net gain), `empty` (shadow's empty receipt), and on the apply half
29
- * `no-spill`, `no-owner`, `projection-skipped:no-footer`, `spill-failed`, and
30
- * `footer-failed`.
31
- *
32
- * @module dsh-boost/projection/apply
33
- */
34
- import type { BoostConfig, ToolFamily } from '../types.js';
35
- /** Which projection behaviour the caller is running. */
36
- export type ProjectionMode = 'off' | 'shadow' | 'on';
37
- /** What projection did, or would have done, to one receipt. */
38
- export interface ProjectionOutcome {
39
- kind: 'skipped' | 'shadow' | 'applied';
40
- /** Stable skip code; present only when `kind === 'skipped'`. */
41
- reason?: string;
42
- /**
43
- * Tokens in the original receipt.
44
- *
45
- * Present only when `kind === 'shadow'` and the estimator priced both
46
- * sides; absent (with `estimate: 'unknown'` on the receipt) when it did not.
47
- */
48
- before?: number;
49
- /** Tokens in the replacement shadow mode would have produced. */
50
- after?: number;
51
- /** `before - after`. */
52
- saved?: number;
53
- /**
54
- * UTF-8 bytes the replacement omits; present only when `kind === 'applied'`.
55
- *
56
- * Apply mode has no token estimator: the caller (T23b) prices both texts
57
- * itself, and these two fields are the projection's own accounting.
58
- */
59
- omittedBytes?: number;
60
- /** Unicode code points the replacement omits; applied outcomes only. */
61
- omittedCodePoints?: number;
62
- /**
63
- * The persisted artifact's locator; applied outcomes only.
64
- *
65
- * It is the path the footer tells the model to read, and the retrieval ledger
66
- * matches later `read`/`grep` arguments against it (Task 25).
67
- */
68
- locator?: string;
69
- }
70
- /** A persisted spill artifact's model-facing handle. */
71
- export interface SpillHandle {
72
- /** Opaque locator the model can `read` or `grep`; never parsed here. */
73
- locator: string;
74
- /** How to retrieve the artifact, as guidance for the model. */
75
- retrievalHint: string;
76
- }
77
- /**
78
- * The host spill store, narrowed to the one method projection needs.
79
- *
80
- * `callId` and `label` are required because the host's `SaveTextSpill` requires
81
- * them; `projectApply` fills them in before calling. `saveText` rejects on a
82
- * real storage failure, and that rejection is handled as a skip.
83
- */
84
- export interface SpillBackend {
85
- saveText(input: {
86
- owner: {
87
- sessionId: string;
88
- };
89
- source: {
90
- kind: 'tool';
91
- toolName: string;
92
- callId: string;
93
- label: string;
94
- };
95
- suggestedName: string;
96
- content: string;
97
- }): Promise<SpillHandle>;
98
- }
99
- /**
100
- * Render the footer that names what was omitted and where the original lives.
101
- *
102
- * Injected by the caller, which dynamically imports the host's
103
- * `formatSpillNotice`; this module must never statically import
104
- * `@deepseek-ai/dsh-spill-policy` — it is not declared as a dependency, and a static import
105
- * would make the degradation path unreachable (design §5.4).
106
- */
107
- export type FormatFooter = (omitted: {
108
- kind: 'exact';
109
- count: number;
110
- }, ref: SpillHandle) => string;
111
- /** Everything one apply decision reads; every host service arrives pre-bound. */
112
- export interface ProjectApplyInput {
113
- /** Canonical receipt text, byte for byte as it would enter history. */
114
- text: string;
115
- /** Whether the host marked the receipt as an error. */
116
- isError: boolean;
117
- /** Projection family, which selects the window from `cfg`. */
118
- family: ToolFamily;
119
- /** Resolved plugin configuration. */
120
- cfg: BoostConfig;
121
- /** Owning session; without one the spill has no owner and projection stops. */
122
- sessionId: string | undefined;
123
- /** Tool name, recorded on the spill source and used for its file name. */
124
- toolName: string;
125
- /** Model-issued call id; defaults to `toolName`. */
126
- callId?: string;
127
- /** Human label for the artifact; defaults to `family`. */
128
- label?: string;
129
- /** Spill backend, absent when the host has none (projection then stops). */
130
- spill: SpillBackend | undefined;
131
- /** Footer renderer, absent when the host spill policy package is not installed. */
132
- formatFooter: FormatFooter | undefined;
133
- }
134
- /**
135
- * Report what projection would save, without touching the receipt.
136
- *
137
- * Guards run in a fixed order: an error receipt is skipped before anything
138
- * else, so even an empty or oversized error keeps its evidence (design §5.4
139
- * contract 4); then empty text; then a family with no configured window; then
140
- * `truncate`'s own decision (trigger, 256 KiB cap, net-gain guard).
141
- */
142
- export declare function projectShadow(input: {
143
- /** Canonical receipt text, byte for byte as it would enter history. */
144
- text: string;
145
- /** Whether the host marked the receipt as an error. */
146
- isError: boolean;
147
- /** Projection family, which selects the window from `cfg`. */
148
- family: ToolFamily;
149
- /** Resolved plugin configuration. */
150
- cfg: BoostConfig;
151
- /** Token estimator injected by the caller (never imported from the host). */
152
- estimate: (s: string) => number;
153
- }): Promise<ProjectionOutcome>;
154
- /**
155
- * Replace an oversized receipt with its head, tail, and a way back to the rest.
156
- *
157
- * The canonical original is spilled *before* anything is replaced — never the
158
- * projection, which would make the footer point at an artifact that does not
159
- * contain what it promises. The footer sits on its own line between the two
160
- * windows, and the composed replacement is re-checked against the original:
161
- * at the trigger boundary a long locator can make the "projection" longer than
162
- * the receipt it replaces, and a projection that grows a receipt is worse than
163
- * none.
164
- *
165
- * A spill or footer failure is swallowed and reported as `spill-failed` /
166
- * `footer-failed`; the caller's `post-execute` hook must never see an exception
167
- * from here. The footer must be guarded too: the host turns a throwing
168
- * `post-execute` listener into an `isError` result, which would lose the very
169
- * output this module exists to preserve.
170
- */
171
- export declare function projectApply(input: ProjectApplyInput): Promise<{
172
- content: string;
173
- outcome: ProjectionOutcome;
174
- }>;
@@ -1,43 +0,0 @@
1
- /**
2
- * Receipt canonicalisation.
3
- *
4
- * The host hands a tool result's content to the plugin as an array of content
5
- * blocks; every later stage (binding, guards, projection, hashing) reasons
6
- * about one string. This module is the only place that array becomes that
7
- * string.
8
- *
9
- * Only `type === 'text'` blocks contribute, in input order, byte-faithfully:
10
- * no trim, no line-ending normalisation, no reordering, no separator. Text
11
- * blocks without a `text` value contribute nothing and are not counted in
12
- * `textBlocks`; other block kinds (image, file, …) are skipped entirely.
13
- *
14
- * The block array is untrusted at this boundary even though the host declares
15
- * `ContentBlock[]`: the host validates lossless JSON, not block shape, so a
16
- * third-party tool's renderer can hand over `null` or a non-object. Such a
17
- * block is skipped, never dereferenced, and a content value that is not an
18
- * array is an empty receipt. Throwing here would make the host replace the
19
- * tool's real output with a tool error — the exact evidence loss this module
20
- * exists to prevent.
21
- *
22
- * `empty` means "no text content" — it is true for an empty array and for
23
- * text blocks whose concatenation is the empty string, and it is independent
24
- * of `isError`.
25
- *
26
- * @module dsh-boost/projection/canonicalise
27
- */
28
- /** The single string later stages consume, plus the facts they branch on. */
29
- export interface CanonicalReceipt {
30
- /** Text blocks concatenated in order, byte-for-byte as received. */
31
- text: string;
32
- /** Whether the host marked the tool result as an error. */
33
- isError: boolean;
34
- /** `text.length === 0`; means "no text content", not "no blocks". */
35
- empty: boolean;
36
- /** Number of text blocks that contributed to `text`, not `blocks.length`. */
37
- textBlocks: number;
38
- }
39
- /** Project a tool result's content blocks onto one canonical string. */
40
- export declare function canonicalise(blocks: ReadonlyArray<{
41
- type: string;
42
- text?: string;
43
- }>, isError: boolean): CanonicalReceipt;
@@ -1,65 +0,0 @@
1
- /**
2
- * Projection skip observability.
3
- *
4
- * A tool with no configured family returns its receipt unchanged, which is the
5
- * correct policy for `web_fetch`/`edit` and a silent mapping failure for a
6
- * decorated tool such as a new `mcp__ssh__*`. Both used to look identical from
7
- * `boost status` ("nothing projected"), so the operator could not tell "not
8
- * worth it" from "your tool is invisible to the mapper".
9
- *
10
- * The counter is deliberately cheap and bounded: two integers plus at most
11
- * {@link MAX_TRACKED_TOOLS} names. It counts calls that reached the projection
12
- * stage with a text receipt and no family; it is not a per-tool ledger. The
13
- * prompt-suppression count is the same shape, for the same reason: assembly
14
- * runs on every request, so only a number may be kept.
15
- *
16
- * @module dsh-boost/projection/counters
17
- */
18
- /** Process-wide projection counters, owned by `apply` and read by `status`. */
19
- export declare class ProjectionCounters {
20
- private unknownFamilyCount;
21
- private readonly unknownTools;
22
- private suppressedAssemblies;
23
- private missingProtocols;
24
- /**
25
- * Count one **decorated** call (`mcp__*`) whose family is not configured.
26
- *
27
- * Only decorated names are counted. An undecorated non-family tool (`edit`,
28
- * `web_fetch`, `todo_write`, or this plugin's own `boost`) is a by-design
29
- * pass, not a mapper gap, and counting it would bury the gap that matters in
30
- * noise the operator cannot separate out.
31
- *
32
- * `name` is optional because `exec.name` can be absent; the count still
33
- * increments, and only a present name is retained for the tool list.
34
- */
35
- unknownFamily(name: string | undefined): void;
36
- /** Calls skipped because no projection family matched. */
37
- unknownFamilies(): number;
38
- /** The retained unmapped tool names and their call counts (a copy). */
39
- unknownToolCounts(): Record<string, number>;
40
- /**
41
- * Count one prompt assembly whose protocol section was suppressed.
42
- *
43
- * `systemPrompt` assembly runs on every request, so design §5.5:378 requires
44
- * a count and forbids a per-assembly receipt. Without the count, `status`
45
- * cannot distinguish the shipped `selected + []` (correctly inert) from an
46
- * assembly whose section failed to inject — the exact "inert looks identical
47
- * to broken" failure the operator has no other signal for.
48
- */
49
- protocolSuppressed(): void;
50
- /** Prompt assemblies suppressed since load; read live by `boost status`. */
51
- protocolSuppressions(): number;
52
- /**
53
- * Count one model request whose final system prompt lost the protocol
54
- * section to a `complete: true` section.
55
- *
56
- * Distinct from {@link protocolSuppressed}: that counter includes correctly
57
- * invisible workspaces, while this one means the plugin judged the workspace
58
- * visible and still could not teach the model the plan grammar. It is the
59
- * operator's only signal that the prompt belongs to another plugin (review
60
- * row 12), and it drives the stable `ERR_HOST_COMPLETE_SECTION` code.
61
- */
62
- protocolMissing(): void;
63
- /** Model requests that lost the protocol section since load. */
64
- protocolMissings(): number;
65
- }
@@ -1,47 +0,0 @@
1
- /**
2
- * Receipt truncation: whether to cut, the two windows, and the head line.
3
- *
4
- * Lengths are counted in Unicode code points, never UTF-16 code units (design
5
- * §5.4): a CJK or emoji receipt must be cut at the same visual length as an
6
- * ASCII one, and slicing the code-point array is the only way never to split a
7
- * surrogate pair. `text.length` appears only as a cheap pre-filter — it is an
8
- * upper bound on the code-point count, so `text.length <= triggerChars` proves
9
- * that no cut is due.
10
- *
11
- * `truncate` returns `null` when a cut is not worth it: when the receipt does
12
- * not exceed the trigger, when its UTF-8 size exceeds the projection cap, or
13
- * when the rendered replacement would not be shorter than the original. Every
14
- * non-null result therefore satisfies `after.length < before.length`, which
15
- * the shadow-mode accounting relies on.
16
- *
17
- * @module dsh-boost/projection/truncate
18
- */
19
- import type { ProjectionParams } from '../types.js';
20
- /** The two windows plus the facts later stages report and account for. */
21
- export interface Truncation {
22
- /** The original receipt text, byte for byte. */
23
- before: string;
24
- /** The rendered replacement: head line, then head, then tail. */
25
- after: string;
26
- /** First `headChars` code points of `before`. */
27
- head: string;
28
- /** Last `tailChars` code points of `before`. */
29
- tail: string;
30
- /** UTF-8 bytes of `before` that neither window carries. */
31
- omittedBytes: number;
32
- /** `before` code points minus the two window sizes. */
33
- omittedCodePoints: number;
34
- }
35
- /** Render the head line of a truncation, with `en-US` thousands separators. */
36
- export declare function renderHeadLine(truncation: Truncation): string;
37
- /**
38
- * Whether `truncate` would cut `text`.
39
- *
40
- * Delegates instead of re-deriving the decision, so the two entry points can
41
- * never disagree at the edges (the exact cut, the net-gain guard, the byte
42
- * cap). The cheap pre-filters inside `truncate` keep the common "not worth
43
- * cutting" path free of code-point allocation.
44
- */
45
- export declare function shouldTruncate(text: string, params: ProjectionParams): boolean;
46
- /** Cut `text` down to its head and tail windows, or `null` when that is not worth it. */
47
- export declare function truncate(text: string, params: ProjectionParams): Truncation | null;