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.
- package/LICENSE +202 -0
- package/NOTICE +29 -0
- package/README.en.md +476 -0
- package/README.md +408 -2
- package/cordis.patch.yml +40 -0
- package/dist/admission/fixed-cost.d.ts +23 -0
- package/dist/admission/fixed-cost.js +61 -0
- package/dist/admission/fixed-cost.js.map +1 -0
- package/dist/admission/ledger.d.ts +113 -0
- package/dist/admission/ledger.js +176 -0
- package/dist/admission/ledger.js.map +1 -0
- package/dist/admission/retrieval.d.ts +65 -0
- package/dist/admission/retrieval.js +162 -0
- package/dist/admission/retrieval.js.map +1 -0
- package/dist/admission/usage.d.ts +75 -0
- package/dist/admission/usage.js +124 -0
- package/dist/admission/usage.js.map +1 -0
- package/dist/config.d.ts +43 -0
- package/dist/config.js +103 -0
- package/dist/config.js.map +1 -0
- package/dist/gate/binding.d.ts +113 -0
- package/dist/gate/binding.js +297 -0
- package/dist/gate/binding.js.map +1 -0
- package/dist/gate/decide.d.ts +82 -0
- package/dist/gate/decide.js +163 -0
- package/dist/gate/decide.js.map +1 -0
- package/dist/gate/guard.d.ts +69 -0
- package/dist/gate/guard.js +195 -0
- package/dist/gate/guard.js.map +1 -0
- package/dist/gate/invalidate.d.ts +112 -0
- package/dist/gate/invalidate.js +111 -0
- package/dist/gate/invalidate.js.map +1 -0
- package/dist/gate/plan.d.ts +86 -0
- package/dist/gate/plan.js +222 -0
- package/dist/gate/plan.js.map +1 -0
- package/dist/hooks/clock.d.ts +68 -0
- package/dist/hooks/clock.js +82 -0
- package/dist/hooks/clock.js.map +1 -0
- package/dist/hooks/execute.d.ts +79 -0
- package/dist/hooks/execute.js +128 -0
- package/dist/hooks/execute.js.map +1 -0
- package/dist/hooks/llm-stream.d.ts +276 -0
- package/dist/hooks/llm-stream.js +1008 -0
- package/dist/hooks/llm-stream.js.map +1 -0
- package/dist/hooks/pending.d.ts +89 -0
- package/dist/hooks/pending.js +115 -0
- package/dist/hooks/pending.js.map +1 -0
- package/dist/hooks/post-execute.d.ts +247 -0
- package/dist/hooks/post-execute.js +1776 -0
- package/dist/hooks/post-execute.js.map +1 -0
- package/dist/hooks/session-state.d.ts +158 -0
- package/dist/hooks/session-state.js +168 -0
- package/dist/hooks/session-state.js.map +1 -0
- package/dist/hooks/synthesize.d.ts +74 -0
- package/dist/hooks/synthesize.js +100 -0
- package/dist/hooks/synthesize.js.map +1 -0
- package/dist/host/loader.d.ts +23 -0
- package/dist/host/loader.js +31 -0
- package/dist/host/loader.js.map +1 -0
- package/dist/host/platform.d.ts +18 -0
- package/dist/host/platform.js +19 -0
- package/dist/host/platform.js.map +1 -0
- package/dist/host/root.d.ts +18 -0
- package/dist/host/root.js +43 -0
- package/dist/host/root.js.map +1 -0
- package/dist/index.d.ts +13 -0
- package/dist/index.js +866 -0
- package/dist/index.js.map +1 -0
- package/dist/projection/apply.d.ts +174 -0
- package/dist/projection/apply.js +137 -0
- package/dist/projection/apply.js.map +1 -0
- package/dist/projection/canonicalise.d.ts +43 -0
- package/dist/projection/canonicalise.js +43 -0
- package/dist/projection/canonicalise.js.map +1 -0
- package/dist/projection/counters.d.ts +65 -0
- package/dist/projection/counters.js +88 -0
- package/dist/projection/counters.js.map +1 -0
- package/dist/projection/truncate.d.ts +47 -0
- package/dist/projection/truncate.js +57 -0
- package/dist/projection/truncate.js.map +1 -0
- package/dist/prompt/protocol.d.ts +45 -0
- package/dist/prompt/protocol.js +56 -0
- package/dist/prompt/protocol.js.map +1 -0
- package/dist/receipts/store.d.ts +198 -0
- package/dist/receipts/store.js +734 -0
- package/dist/receipts/store.js.map +1 -0
- package/dist/scope/doc.d.ts +117 -0
- package/dist/scope/doc.js +158 -0
- package/dist/scope/doc.js.map +1 -0
- package/dist/scope/resolve.d.ts +91 -0
- package/dist/scope/resolve.js +146 -0
- package/dist/scope/resolve.js.map +1 -0
- package/dist/scope/store.d.ts +135 -0
- package/dist/scope/store.js +573 -0
- package/dist/scope/store.js.map +1 -0
- package/dist/selector/jev.d.ts +93 -0
- package/dist/selector/jev.js +171 -0
- package/dist/selector/jev.js.map +1 -0
- package/dist/tools/boost.d.ts +367 -0
- package/dist/tools/boost.js +768 -0
- package/dist/tools/boost.js.map +1 -0
- package/dist/tools/family.d.ts +26 -0
- package/dist/tools/family.js +26 -0
- package/dist/tools/family.js.map +1 -0
- package/dist/types.d.ts +113 -0
- package/dist/types.js +21 -0
- package/dist/types.js.map +1 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +75 -4
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Usage pairing: turn two consecutive model requests into the measured saving
|
|
3
|
+
* of one substitution (design §5.3).
|
|
4
|
+
*
|
|
5
|
+
* When the plugin substitutes a call, the model is not asked for that step, so
|
|
6
|
+
* the next real request replays a shorter history. The saving is therefore
|
|
7
|
+
* measured as the size of that next request — `input + cacheRead`, because the
|
|
8
|
+
* host reports `inputTokens` excluding cache reads — never estimated. A missing
|
|
9
|
+
* next request is `'unknown'`; an interpolated number would be indistinguishable
|
|
10
|
+
* from a measurement once written to a receipt.
|
|
11
|
+
*
|
|
12
|
+
* The ledger keeps two request slots plus a mark: `latest`, the first request
|
|
13
|
+
* after the mark, and the mark itself — which holds the request that preceded
|
|
14
|
+
* it and the candidate id. No whole-history table (YAGNI). Pure arithmetic: no
|
|
15
|
+
* timers, no I/O, no host calls.
|
|
16
|
+
*
|
|
17
|
+
* @module dsh-boost/admission/usage
|
|
18
|
+
*/
|
|
19
|
+
/**
|
|
20
|
+
* A sample is usable only when all three counts are finite and non-negative
|
|
21
|
+
* and their input total does not overflow. A negative or non-finite count is a
|
|
22
|
+
* protocol violation, and any arithmetic on it would invent `NaN` or
|
|
23
|
+
* `Infinity` — a bogus number no receipt reader could tell from a measurement.
|
|
24
|
+
* An unusable after-mark sample makes the whole settlement unusable; an
|
|
25
|
+
* unusable pre-mark sample only loses the delta.
|
|
26
|
+
*/
|
|
27
|
+
function usable(u) {
|
|
28
|
+
return ([u.input, u.cacheRead, u.output].every((n) => Number.isFinite(n) && n >= 0) &&
|
|
29
|
+
Number.isFinite(u.input + u.cacheRead));
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Cache hit rate of one request, `cacheRead / (input + cacheRead)`. `null`
|
|
33
|
+
* when the rate cannot be told: no sample, an unusable sample, or a
|
|
34
|
+
* non-positive denominator. Both sides of the delta go through this one
|
|
35
|
+
* helper so they cannot drift.
|
|
36
|
+
*/
|
|
37
|
+
function hitRate(u) {
|
|
38
|
+
if (u === undefined || !usable(u))
|
|
39
|
+
return null;
|
|
40
|
+
const denominator = u.input + u.cacheRead;
|
|
41
|
+
if (denominator <= 0)
|
|
42
|
+
return null;
|
|
43
|
+
const rate = u.cacheRead / denominator;
|
|
44
|
+
return Number.isFinite(rate) ? rate : null;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Pairs two consecutive model requests around one substitution.
|
|
48
|
+
*
|
|
49
|
+
* The pairing target is the FIRST request after the mark, never the latest:
|
|
50
|
+
* when a caller forgets to settle, a later unrelated request must not be
|
|
51
|
+
* attributed to the substitution. `settle()` consumes the mark and clears the
|
|
52
|
+
* pairing slots; `last()` is a pure reader and survives it.
|
|
53
|
+
*/
|
|
54
|
+
export class UsageLedger {
|
|
55
|
+
latest;
|
|
56
|
+
hasMark = false;
|
|
57
|
+
beforeMark;
|
|
58
|
+
afterMark;
|
|
59
|
+
candidateId;
|
|
60
|
+
/**
|
|
61
|
+
* Record one real request. The first request after a mark claims the pairing
|
|
62
|
+
* slot and keeps it; later requests only advance `last()`.
|
|
63
|
+
*/
|
|
64
|
+
request(u) {
|
|
65
|
+
this.latest = u;
|
|
66
|
+
if (this.hasMark && this.afterMark === undefined)
|
|
67
|
+
this.afterMark = u;
|
|
68
|
+
}
|
|
69
|
+
/** Most recent request, or `undefined` before the first one. Never consumes. */
|
|
70
|
+
last() {
|
|
71
|
+
return this.latest;
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Record that a substitution just happened.
|
|
75
|
+
*
|
|
76
|
+
* `candidateId` is kept only so the caller can pair `settle()` with the right
|
|
77
|
+
* substitution receipt (`pendingCandidateId()`); it never changes the
|
|
78
|
+
* arithmetic. A new mark discards any unconsumed pairing and starts over from
|
|
79
|
+
* the current latest request.
|
|
80
|
+
*/
|
|
81
|
+
markSubstituted(candidateId) {
|
|
82
|
+
this.hasMark = true;
|
|
83
|
+
this.beforeMark = this.latest;
|
|
84
|
+
this.afterMark = undefined;
|
|
85
|
+
this.candidateId = candidateId;
|
|
86
|
+
}
|
|
87
|
+
/** Id of the pending mark, or `undefined` before a mark and after `settle()`. */
|
|
88
|
+
pendingCandidateId() {
|
|
89
|
+
return this.candidateId;
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* Consume the mark and report the substitution's measured cost.
|
|
93
|
+
*
|
|
94
|
+
* `saved_input_tokens` is the first after-mark request's `input + cacheRead`;
|
|
95
|
+
* `output_tokens` is that request's `output`, a third count that is never
|
|
96
|
+
* folded into input. Both are `'unknown'` when no usable request arrived after
|
|
97
|
+
* the mark — never a copy of the previous request's numbers. `cache_hit_delta`
|
|
98
|
+
* is the after-mark hit rate minus the pre-mark hit rate, `null` when either
|
|
99
|
+
* side cannot be told (a `null` delta means "cannot tell", not zero).
|
|
100
|
+
*
|
|
101
|
+
* A second `settle()` has nothing left to consume and reports the same
|
|
102
|
+
* `'unknown'` / `null`.
|
|
103
|
+
*/
|
|
104
|
+
settle() {
|
|
105
|
+
const after = this.hasMark ? this.afterMark : undefined;
|
|
106
|
+
const before = this.hasMark ? this.beforeMark : undefined;
|
|
107
|
+
this.hasMark = false;
|
|
108
|
+
this.beforeMark = undefined;
|
|
109
|
+
this.afterMark = undefined;
|
|
110
|
+
this.candidateId = undefined;
|
|
111
|
+
if (after === undefined || !usable(after)) {
|
|
112
|
+
return { saved_input_tokens: 'unknown', cache_hit_delta: null, output_tokens: 'unknown' };
|
|
113
|
+
}
|
|
114
|
+
const afterRate = hitRate(after);
|
|
115
|
+
const beforeRate = hitRate(before);
|
|
116
|
+
const delta = afterRate !== null && beforeRate !== null ? afterRate - beforeRate : null;
|
|
117
|
+
return {
|
|
118
|
+
saved_input_tokens: after.input + after.cacheRead,
|
|
119
|
+
cache_hit_delta: delta !== null && Number.isFinite(delta) ? delta : null,
|
|
120
|
+
output_tokens: after.output,
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
//# sourceMappingURL=usage.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"usage.js","sourceRoot":"","sources":["../../src/admission/usage.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AASH;;;;;;;GAOG;AACH,SAAS,MAAM,CAAC,CAAQ;IACtB,OAAO,CACL,CAAC,CAAC,CAAC,KAAK,EAAE,CAAC,CAAC,SAAS,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QAC3E,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC,KAAK,GAAG,CAAC,CAAC,SAAS,CAAC,CACvC,CAAA;AACH,CAAC;AAED;;;;;GAKG;AACH,SAAS,OAAO,CAAC,CAAoB;IACnC,IAAI,CAAC,KAAK,SAAS,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC;QAAE,OAAO,IAAI,CAAA;IAC9C,MAAM,WAAW,GAAG,CAAC,CAAC,KAAK,GAAG,CAAC,CAAC,SAAS,CAAA;IACzC,IAAI,WAAW,IAAI,CAAC;QAAE,OAAO,IAAI,CAAA;IACjC,MAAM,IAAI,GAAG,CAAC,CAAC,SAAS,GAAG,WAAW,CAAA;IACtC,OAAO,MAAM,CAAC,QAAQ,CAAC,IAAI,CA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B,IAAI,KAAK,KAAK,SAAS,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC;YAC1C,OAAO,EAAE,kBAAkB,EAAE,SAAS,EAAE,eAAe,EAAE,IAAI,EAAE,aAAa,EAAE,SAAS,EAAE,CAAA;QAC3F,CAAC;QAED,MAAM,SAAS,GAAG,OAAO,CAAC,KAAK,CAAC,CAAA;QAChC,MAAM,UAAU,GAAG,OAAO,CAAC,MAAM,CAAC,CAAA;QAClC,MAAM,KAAK,GAAG,SAAS,KAAK,IAAI,IAAI,UAAU,KAAK,IAAI,CAAC,CAAC,CAAC,SAAS,GAAG,UAAU,CAAC,CAAC,CAAC,IAAI,CAAA;QAEvF,OAAO;YACL,kBAAkB,EAAE,KAAK,CAAC,KAAK,GAAG,KAAK,CAAC,SAAS;YACjD,eAAe,EAAE,KAAK,KAAK,IAAI,IAAI,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI;YACxE,aAAa,EAAE,KAAK,CAAC,MAAM;SAC5B,CAAA;IACH,CAAC;CACF","sourcesContent":["/**\n * Usage pairing: turn two consecutive model requests into the measured saving\n * of one substitution (design §5.3).\n *\n * When the plugin substitutes a call, the model is not asked for that step, so\n * the next real request replays a shorter history. The saving is therefore\n * measured as the size of that next request — `input + cacheRead`, because the\n * host reports `inputTokens` excluding cache reads — never estimated. A missing\n * next request is `'unknown'`; an interpolated number would be indistinguishable\n * from a measurement once written to a receipt.\n *\n * The ledger keeps two request slots plus a mark: `latest`, the first request\n * after the mark, and the mark itself — which holds the request that preceded\n * it and the candidate id. No whole-history table (YAGNI). Pure arithmetic: no\n * timers, no I/O, no host calls.\n *\n * @module dsh-boost/admission/usage\n */\n\n/** One model request's raw counts, mapped from the `llm/stream` usage chunk. */\nexport interface Usage {\n input: number\n cacheRead: number\n output: number\n}\n\n/**\n * A sample is usable only when all three counts are finite and non-negative\n * and their input total does not overflow. A negative or non-finite count is a\n * protocol violation, and any arithmetic on it would invent `NaN` or\n * `Infinity` — a bogus number no receipt reader could tell from a measurement.\n * An unusable after-mark sample makes the whole settlement unusable; an\n * unusable pre-mark sample only loses the delta.\n */\nfunction usable(u: Usage): boolean {\n return (\n [u.input, u.cacheRead, u.output].every((n) => Number.isFinite(n) && n >= 0) &&\n Number.isFinite(u.input + u.cacheRead)\n )\n}\n\n/**\n * Cache hit rate of one request, `cacheRead / (input + cacheRead)`. `null`\n * when the rate cannot be told: no sample, an unusable sample, or a\n * non-positive denominator. Both sides of the delta go through this one\n * helper so they cannot drift.\n */\nfunction hitRate(u: Usage | undefined): number | null {\n if (u === undefined || !usable(u)) return null\n const denominator = u.input + u.cacheRead\n if (denominator <= 0) return null\n const rate = u.cacheRead / denominator\n return Number.isFinite(rate) ? rate : null\n}\n\n/**\n * Pairs two consecutive model requests around one substitution.\n *\n * The pairing target is the FIRST request after the mark, never the latest:\n * when a caller forgets to settle, a later unrelated request must not be\n * attributed to the substitution. `settle()` consumes the mark and clears the\n * pairing slots; `last()` is a pure reader and survives it.\n */\nexport class UsageLedger {\n private latest: Usage | undefined\n private hasMark = false\n private beforeMark: Usage | undefined\n private afterMark: Usage | undefined\n private candidateId: string | undefined\n\n /**\n * Record one real request. The first request after a mark claims the pairing\n * slot and keeps it; later requests only advance `last()`.\n */\n request(u: Usage): void {\n this.latest = u\n if (this.hasMark && this.afterMark === undefined) this.afterMark = u\n }\n\n /** Most recent request, or `undefined` before the first one. Never consumes. */\n last(): Usage | undefined {\n return this.latest\n }\n\n /**\n * Record that a substitution just happened.\n *\n * `candidateId` is kept only so the caller can pair `settle()` with the right\n * substitution receipt (`pendingCandidateId()`); it never changes the\n * arithmetic. A new mark discards any unconsumed pairing and starts over from\n * the current latest request.\n */\n markSubstituted(candidateId: string): void {\n this.hasMark = true\n this.beforeMark = this.latest\n this.afterMark = undefined\n this.candidateId = candidateId\n }\n\n /** Id of the pending mark, or `undefined` before a mark and after `settle()`. */\n pendingCandidateId(): string | undefined {\n return this.candidateId\n }\n\n /**\n * Consume the mark and report the substitution's measured cost.\n *\n * `saved_input_tokens` is the first after-mark request's `input + cacheRead`;\n * `output_tokens` is that request's `output`, a third count that is never\n * folded into input. Both are `'unknown'` when no usable request arrived after\n * the mark — never a copy of the previous request's numbers. `cache_hit_delta`\n * is the after-mark hit rate minus the pre-mark hit rate, `null` when either\n * side cannot be told (a `null` delta means \"cannot tell\", not zero).\n *\n * A second `settle()` has nothing left to consume and reports the same\n * `'unknown'` / `null`.\n */\n settle(): {\n saved_input_tokens: number | 'unknown'\n cache_hit_delta: number | null\n output_tokens: number | 'unknown'\n } {\n const after = this.hasMark ? this.afterMark : undefined\n const before = this.hasMark ? this.beforeMark : undefined\n this.hasMark = false\n this.beforeMark = undefined\n this.afterMark = undefined\n this.candidateId = undefined\n\n if (after === undefined || !usable(after)) {\n return { saved_input_tokens: 'unknown', cache_hit_delta: null, output_tokens: 'unknown' }\n }\n\n const afterRate = hitRate(after)\n const beforeRate = hitRate(before)\n const delta = afterRate !== null && beforeRate !== null ? afterRate - beforeRate : null\n\n return {\n saved_input_tokens: after.input + after.cacheRead,\n cache_hit_delta: delta !== null && Number.isFinite(delta) ? delta : null,\n output_tokens: after.output,\n }\n }\n}"]}
|
package/dist/config.d.ts
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Configuration defaults and resolution.
|
|
3
|
+
*
|
|
4
|
+
* The host's patch replaces the plugin `config` wholesale (design §11), so a
|
|
5
|
+
* missing key never means "keep the previous value": `resolveConfig` merges the
|
|
6
|
+
* host object over `DEFAULT_CONFIG` one key at a time. A key whose value is
|
|
7
|
+
* malformed falls back to its own default rather than raising — a bad overlay
|
|
8
|
+
* degrades to design defaults, it does not break plugin loading.
|
|
9
|
+
*
|
|
10
|
+
* ## Validation
|
|
11
|
+
*
|
|
12
|
+
* A finite number is not automatically a usable value. Negative or fractional
|
|
13
|
+
* projection windows, budgets and counts are rejected or clamped here rather
|
|
14
|
+
* than flowing into the decision path: a negative `triggerChars` would make
|
|
15
|
+
* every receipt a candidate and a negative `selector.maxTokens` would reach the
|
|
16
|
+
* selector LLM. Every repair is reported through the optional callback so the
|
|
17
|
+
* operator sees the effective value instead of a silent fallback, and
|
|
18
|
+
* `projection.*.headChars + tailChars` must stay below `triggerChars` (design
|
|
19
|
+
* §5.3: a window at or above the trigger cannot cut anything).
|
|
20
|
+
*
|
|
21
|
+
* Unknown keys are ignored: hosts may hand a superset of `BoostConfig`.
|
|
22
|
+
*
|
|
23
|
+
* @module dsh-boost/config
|
|
24
|
+
*/
|
|
25
|
+
import type { BoostConfig } from './types.js';
|
|
26
|
+
/** Design defaults; must stay verbatim in sync with `cordis.patch.yml` (§5.3). */
|
|
27
|
+
export declare const DEFAULT_CONFIG: BoostConfig;
|
|
28
|
+
/** Receives one human-readable line per repaired configuration key. */
|
|
29
|
+
export type ConfigRepair = (message: string) => void;
|
|
30
|
+
/**
|
|
31
|
+
* Turn whatever the host hands `apply` into a complete `BoostConfig`.
|
|
32
|
+
*
|
|
33
|
+
* Always returns a fresh deep copy, so callers cannot mutate `DEFAULT_CONFIG`.
|
|
34
|
+
* Non-object input resolves to the defaults. `onRepair` receives one line per
|
|
35
|
+
* key that was rejected, clamped or repaired; it is never called for a valid
|
|
36
|
+
* value.
|
|
37
|
+
*
|
|
38
|
+
* Total: it never throws. The host hands `apply` an arbitrary object, so a
|
|
39
|
+
* throwing getter anywhere in the tree (or a throwing `onRepair` sink) aborts
|
|
40
|
+
* the resolution and returns a fresh copy of `DEFAULT_CONFIG` rather than
|
|
41
|
+
* escaping as a plugin-load failure (review row 68).
|
|
42
|
+
*/
|
|
43
|
+
export declare function resolveConfig(raw: unknown, onRepair?: ConfigRepair): BoostConfig;
|
package/dist/config.js
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
/** Families with projection windows, in the order defaults are declared. */
|
|
2
|
+
const FAMILIES = ['read', 'grep', 'glob', 'bash', 'ssh'];
|
|
3
|
+
/** Design defaults; must stay verbatim in sync with `cordis.patch.yml` (§5.3). */
|
|
4
|
+
export const DEFAULT_CONFIG = {
|
|
5
|
+
projection: {
|
|
6
|
+
read: { triggerChars: 3000, headChars: 2000, tailChars: 500 },
|
|
7
|
+
grep: { triggerChars: 700, headChars: 400, tailChars: 100 },
|
|
8
|
+
glob: { triggerChars: 700, headChars: 400, tailChars: 100 },
|
|
9
|
+
bash: { triggerChars: 4000, headChars: 2000, tailChars: 500 },
|
|
10
|
+
ssh: { triggerChars: 2000, headChars: 1200, tailChars: 300 },
|
|
11
|
+
},
|
|
12
|
+
admission: { thresholdTokens: 1024 },
|
|
13
|
+
selector: { maxTokens: 512 },
|
|
14
|
+
stepsPerTurn: 8,
|
|
15
|
+
horizonSteps: 20,
|
|
16
|
+
historyTurns: 5,
|
|
17
|
+
};
|
|
18
|
+
/** A config section is any non-null object; everything else is absent. */
|
|
19
|
+
function section(value) {
|
|
20
|
+
return typeof value === 'object' && value !== null ? value : undefined;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Take `value` when it is an integer >= `min`, otherwise `fallback`.
|
|
24
|
+
*
|
|
25
|
+
* A finite fractional value floors and is reported; a negative, non-finite,
|
|
26
|
+
* unsafe or non-numeric value is rejected and the key's own default is used.
|
|
27
|
+
*/
|
|
28
|
+
function integerAtLeast(value, fallback, min, label, repair) {
|
|
29
|
+
if (typeof value !== 'number' || !Number.isFinite(value) || value < min) {
|
|
30
|
+
if (value !== undefined) {
|
|
31
|
+
repair(`dsh-boost: ignoring config ${label}=${String(value)}; using ${fallback}`);
|
|
32
|
+
}
|
|
33
|
+
return fallback;
|
|
34
|
+
}
|
|
35
|
+
const clamped = Math.floor(value);
|
|
36
|
+
if (!Number.isSafeInteger(clamped) || clamped < min) {
|
|
37
|
+
repair(`dsh-boost: ignoring config ${label}=${String(value)}; using ${fallback}`);
|
|
38
|
+
return fallback;
|
|
39
|
+
}
|
|
40
|
+
if (clamped !== value) {
|
|
41
|
+
repair(`dsh-boost: clamping config ${label}=${String(value)} to ${clamped}`);
|
|
42
|
+
}
|
|
43
|
+
return clamped;
|
|
44
|
+
}
|
|
45
|
+
/** Resolve one family's window key by key, then enforce the window invariant. */
|
|
46
|
+
function pickProjection(raw, fallback, family, repair) {
|
|
47
|
+
const source = section(raw);
|
|
48
|
+
const picked = {
|
|
49
|
+
triggerChars: integerAtLeast(source?.triggerChars, fallback.triggerChars, 0, `projection.${family}.triggerChars`, repair),
|
|
50
|
+
headChars: integerAtLeast(source?.headChars, fallback.headChars, 0, `projection.${family}.headChars`, repair),
|
|
51
|
+
tailChars: integerAtLeast(source?.tailChars, fallback.tailChars, 0, `projection.${family}.tailChars`, repair),
|
|
52
|
+
};
|
|
53
|
+
const window = picked.headChars + picked.tailChars;
|
|
54
|
+
// Design §5.3: the window must be strictly smaller than the trigger, or the
|
|
55
|
+
// guaranteed saving disappears (and `triggerChars: 0` would project every
|
|
56
|
+
// receipt before the net check rejects it).
|
|
57
|
+
if (!Number.isSafeInteger(window) || window >= picked.triggerChars) {
|
|
58
|
+
repair(`dsh-boost: config projection.${family} window ${picked.headChars}+${picked.tailChars} is not below triggerChars ${picked.triggerChars}; using the design default window`);
|
|
59
|
+
return { ...fallback };
|
|
60
|
+
}
|
|
61
|
+
return picked;
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Turn whatever the host hands `apply` into a complete `BoostConfig`.
|
|
65
|
+
*
|
|
66
|
+
* Always returns a fresh deep copy, so callers cannot mutate `DEFAULT_CONFIG`.
|
|
67
|
+
* Non-object input resolves to the defaults. `onRepair` receives one line per
|
|
68
|
+
* key that was rejected, clamped or repaired; it is never called for a valid
|
|
69
|
+
* value.
|
|
70
|
+
*
|
|
71
|
+
* Total: it never throws. The host hands `apply` an arbitrary object, so a
|
|
72
|
+
* throwing getter anywhere in the tree (or a throwing `onRepair` sink) aborts
|
|
73
|
+
* the resolution and returns a fresh copy of `DEFAULT_CONFIG` rather than
|
|
74
|
+
* escaping as a plugin-load failure (review row 68).
|
|
75
|
+
*/
|
|
76
|
+
export function resolveConfig(raw, onRepair = () => { }) {
|
|
77
|
+
try {
|
|
78
|
+
return resolveConfigUnchecked(raw, onRepair);
|
|
79
|
+
}
|
|
80
|
+
catch {
|
|
81
|
+
return structuredClone(DEFAULT_CONFIG);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
/** The resolved read, split out so the public entry point can stay total. */
|
|
85
|
+
function resolveConfigUnchecked(raw, onRepair) {
|
|
86
|
+
const cfg = structuredClone(DEFAULT_CONFIG);
|
|
87
|
+
const root = section(raw);
|
|
88
|
+
if (!root)
|
|
89
|
+
return cfg;
|
|
90
|
+
const projection = section(root.projection);
|
|
91
|
+
for (const family of FAMILIES) {
|
|
92
|
+
cfg.projection[family] = pickProjection(projection?.[family], cfg.projection[family], family, onRepair);
|
|
93
|
+
}
|
|
94
|
+
const admission = section(root.admission);
|
|
95
|
+
cfg.admission.thresholdTokens = integerAtLeast(admission?.thresholdTokens, cfg.admission.thresholdTokens, 0, 'admission.thresholdTokens', onRepair);
|
|
96
|
+
const selector = section(root.selector);
|
|
97
|
+
cfg.selector.maxTokens = integerAtLeast(selector?.maxTokens, cfg.selector.maxTokens, 1, 'selector.maxTokens', onRepair);
|
|
98
|
+
cfg.stepsPerTurn = integerAtLeast(root.stepsPerTurn, cfg.stepsPerTurn, 0, 'stepsPerTurn', onRepair);
|
|
99
|
+
cfg.horizonSteps = integerAtLeast(root.horizonSteps, cfg.horizonSteps, 0, 'horizonSteps', onRepair);
|
|
100
|
+
cfg.historyTurns = integerAtLeast(root.historyTurns, cfg.historyTurns, 1, 'historyTurns', onRepair);
|
|
101
|
+
return cfg;
|
|
102
|
+
}
|
|
103
|
+
//# sourceMappingURL=config.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"config.js","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AA0BA,4EAA4E;AAC5E,MAAM,QAAQ,GAA0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IACzC,GAAG,CAAC,SAAS,CAAC,eAAe,GAAG,cAAc,CAC5C,SAAS,EAAE,eAAe,EAC1B,GAAG,CAAC,SAAS,CAAC,eAAe,EAC7B,CAAC,EACD,2BAA2B,EAC3B,QAAQ,CACT,CAAA;IAED,MAAM,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAA;IACvC,GAAG,CAAC,QAAQ,CAAC,SAAS,GAAG,cAAc,CACrC,QAAQ,EAAE,SAAS,EACnB,GAAG,CAAC,QAAQ,CAAC,SAAS,EACtB,CAAC,EACD,oBAAoB,EACpB,QAAQ,CACT,CAAA;IAED,GAAG,CAAC,YAAY,GAAG,cAAc,CAAC,IAAI,CAAC,YAAY,EAAE,GAAG,CAAC,YAAY,EAAE,CAAC,EAAE,cAAc,EAAE,QAAQ,CAAC,CAAA;IACnG,GAAG,CAAC,YAAY,GAAG,cAAc,CAAC,IAAI,CAAC,YAAY,EAAE,GAAG,CAAC,YAAY,EAAE,CAAC,EAAE,cAAc,EAAE,QAAQ,CAAC,CAAA;IACnG,GAAG,CAAC,YAAY,GAAG,cAAc,CAC/B,IAAI,CAAC,YAAY,EACjB,GAAG,CAAC,YAAY,EAChB,CAAC,EACD,cAAc,EACd,QAAQ,CACT,CAAA;IAED,OAAO,GAAG,CAAA;AACZ,CAAC","sourcesContent":["/**\n * Configuration defaults and resolution.\n *\n * The host's patch replaces the plugin `config` wholesale (design §11), so a\n * missing key never means \"keep the previous value\": `resolveConfig` merges the\n * host object over `DEFAULT_CONFIG` one key at a time. A key whose value is\n * malformed falls back to its own default rather than raising — a bad overlay\n * degrades to design defaults, it does not break plugin loading.\n *\n * ## Validation\n *\n * A finite number is not automatically a usable value. Negative or fractional\n * projection windows, budgets and counts are rejected or clamped here rather\n * than flowing into the decision path: a negative `triggerChars` would make\n * every receipt a candidate and a negative `selector.maxTokens` would reach the\n * selector LLM. Every repair is reported through the optional callback so the\n * operator sees the effective value instead of a silent fallback, and\n * `projection.*.headChars + tailChars` must stay below `triggerChars` (design\n * §5.3: a window at or above the trigger cannot cut anything).\n *\n * Unknown keys are ignored: hosts may hand a superset of `BoostConfig`.\n *\n * @module dsh-boost/config\n */\nimport type { BoostConfig, ProjectionParams, ToolFamily } from './types.js'\n\n/** Families with projection windows, in the order defaults are declared. */\nconst FAMILIES: readonly ToolFamily[] = ['read', 'grep', 'glob', 'bash', 'ssh']\n\n/** Design defaults; must stay verbatim in sync with `cordis.patch.yml` (§5.3). */\nexport const DEFAULT_CONFIG: BoostConfig = {\n projection: {\n read: { triggerChars: 3000, headChars: 2000, tailChars: 500 },\n grep: { triggerChars: 700, headChars: 400, tailChars: 100 },\n glob: { triggerChars: 700, headChars: 400, tailChars: 100 },\n bash: { triggerChars: 4000, headChars: 2000, tailChars: 500 },\n ssh: { triggerChars: 2000, headChars: 1200, tailChars: 300 },\n },\n admission: { thresholdTokens: 1024 },\n selector: { maxTokens: 512 },\n stepsPerTurn: 8,\n horizonSteps: 20,\n historyTurns: 5,\n}\n\n/** Receives one human-readable line per repaired configuration key. */\nexport type ConfigRepair = (message: string) => void\n\n/** A config section is any non-null object; everything else is absent. */\nfunction section(value: unknown): Record<string, unknown> | undefined {\n return typeof value === 'object' && value !== null ? (value as Record<string, unknown>) : undefined\n}\n\n/**\n * Take `value` when it is an integer >= `min`, otherwise `fallback`.\n *\n * A finite fractional value floors and is reported; a negative, non-finite,\n * unsafe or non-numeric value is rejected and the key's own default is used.\n */\nfunction integerAtLeast(\n value: unknown,\n fallback: number,\n min: number,\n label: string,\n repair: ConfigRepair,\n): number {\n if (typeof value !== 'number' || !Number.isFinite(value) || value < min) {\n if (value !== undefined) {\n repair(`dsh-boost: ignoring config ${label}=${String(value)}; using ${fallback}`)\n }\n return fallback\n }\n const clamped = Math.floor(value)\n if (!Number.isSafeInteger(clamped) || clamped < min) {\n repair(`dsh-boost: ignoring config ${label}=${String(value)}; using ${fallback}`)\n return fallback\n }\n if (clamped !== value) {\n repair(`dsh-boost: clamping config ${label}=${String(value)} to ${clamped}`)\n }\n return clamped\n}\n\n/** Resolve one family's window key by key, then enforce the window invariant. */\nfunction pickProjection(\n raw: unknown,\n fallback: ProjectionParams,\n family: ToolFamily,\n repair: ConfigRepair,\n): ProjectionParams {\n const source = section(raw)\n const picked: ProjectionParams = {\n triggerChars: integerAtLeast(\n source?.triggerChars,\n fallback.triggerChars,\n 0,\n `projection.${family}.triggerChars`,\n repair,\n ),\n headChars: integerAtLeast(\n source?.headChars,\n fallback.headChars,\n 0,\n `projection.${family}.headChars`,\n repair,\n ),\n tailChars: integerAtLeast(\n source?.tailChars,\n fallback.tailChars,\n 0,\n `projection.${family}.tailChars`,\n repair,\n ),\n }\n const window = picked.headChars + picked.tailChars\n // Design §5.3: the window must be strictly smaller than the trigger, or the\n // guaranteed saving disappears (and `triggerChars: 0` would project every\n // receipt before the net check rejects it).\n if (!Number.isSafeInteger(window) || window >= picked.triggerChars) {\n repair(\n `dsh-boost: config projection.${family} window ${picked.headChars}+${picked.tailChars} is not below triggerChars ${picked.triggerChars}; using the design default window`,\n )\n return { ...fallback }\n }\n return picked\n}\n\n/**\n * Turn whatever the host hands `apply` into a complete `BoostConfig`.\n *\n * Always returns a fresh deep copy, so callers cannot mutate `DEFAULT_CONFIG`.\n * Non-object input resolves to the defaults. `onRepair` receives one line per\n * key that was rejected, clamped or repaired; it is never called for a valid\n * value.\n *\n * Total: it never throws. The host hands `apply` an arbitrary object, so a\n * throwing getter anywhere in the tree (or a throwing `onRepair` sink) aborts\n * the resolution and returns a fresh copy of `DEFAULT_CONFIG` rather than\n * escaping as a plugin-load failure (review row 68).\n */\nexport function resolveConfig(raw: unknown, onRepair: ConfigRepair = () => {}): BoostConfig {\n try {\n return resolveConfigUnchecked(raw, onRepair)\n } catch {\n return structuredClone(DEFAULT_CONFIG)\n }\n}\n\n/** The resolved read, split out so the public entry point can stay total. */\nfunction resolveConfigUnchecked(raw: unknown, onRepair: ConfigRepair): BoostConfig {\n const cfg = structuredClone(DEFAULT_CONFIG)\n const root = section(raw)\n if (!root) return cfg\n\n const projection = section(root.projection)\n for (const family of FAMILIES) {\n cfg.projection[family] = pickProjection(\n projection?.[family],\n cfg.projection[family],\n family,\n onRepair,\n )\n }\n\n const admission = section(root.admission)\n cfg.admission.thresholdTokens = integerAtLeast(\n admission?.thresholdTokens,\n cfg.admission.thresholdTokens,\n 0,\n 'admission.thresholdTokens',\n onRepair,\n )\n\n const selector = section(root.selector)\n cfg.selector.maxTokens = integerAtLeast(\n selector?.maxTokens,\n cfg.selector.maxTokens,\n 1,\n 'selector.maxTokens',\n onRepair,\n )\n\n cfg.stepsPerTurn = integerAtLeast(root.stepsPerTurn, cfg.stepsPerTurn, 0, 'stepsPerTurn', onRepair)\n cfg.horizonSteps = integerAtLeast(root.horizonSteps, cfg.horizonSteps, 0, 'horizonSteps', onRepair)\n cfg.historyTurns = integerAtLeast(\n root.historyTurns,\n cfg.historyTurns,\n 1,\n 'historyTurns',\n onRepair,\n )\n\n return cfg\n}\n"]}
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `$public` argument binding: the anti-forgery core of the gate.
|
|
3
|
+
*
|
|
4
|
+
* A plan is written by the model with literal arguments, except for values that
|
|
5
|
+
* only exist after an earlier step has run. Those are written as a template
|
|
6
|
+
* `{ "$public": { "after": "A", "field": "name" } }`, and this module fills the
|
|
7
|
+
* template in from the named receipt. The point is mechanical projection: a
|
|
8
|
+
* value that the model reads and then re-types can be steered by whatever the
|
|
9
|
+
* value contains, so the value is copied from the receipt text instead of being
|
|
10
|
+
* reproduced by the model.
|
|
11
|
+
*
|
|
12
|
+
* Uniqueness is the whole safety rule. A field is usable only when it appears
|
|
13
|
+
* exactly once, as a quoted string, on its own line (`name: "v"` / `name="v"`);
|
|
14
|
+
* zero matches, two matches, or an unquoted right-hand side are all
|
|
15
|
+
* `ambiguous`, and ambiguity means the slow path — never a guess. `$scalar`
|
|
16
|
+
* and `$single` are whole-text forms, so they are unique by construction;
|
|
17
|
+
* `$single` additionally refuses a value that spans a line.
|
|
18
|
+
*
|
|
19
|
+
* A line boundary is LF, CR, CRLF, NEL (U+0085), U+2028 or U+2029, so a
|
|
20
|
+
* duplicate cannot hide behind one of these common separator conventions.
|
|
21
|
+
* Identifier projection scans each line once with an anchored, non-global regex
|
|
22
|
+
* instead of running one cross-line global regex: the latter re-consumes the
|
|
23
|
+
* remaining whitespace at every line start, which is quadratic on a
|
|
24
|
+
* blank-line-heavy receipt. The identifier form's closing quote must not be
|
|
25
|
+
* escaped: a captured value ending in an odd run of backslashes means the quote
|
|
26
|
+
* that ended the match was itself escaped, so the line abstains instead of
|
|
27
|
+
* binding a truncated prefix (`C:\x` ends in `x` and still binds).
|
|
28
|
+
*
|
|
29
|
+
* Two scoping consequences are deliberate: a second assignment later on the
|
|
30
|
+
* same line is not counted (`name: "a" name: "b"` binds `a`), and a line whose
|
|
31
|
+
* right-hand side is not double-quoted is not a match at all (`name: "a"`
|
|
32
|
+
* followed by `name: b` binds `a`). In both cases the projected value is the
|
|
33
|
+
* line-start quoted occurrence, so nothing attacker-chosen is projected.
|
|
34
|
+
*
|
|
35
|
+
* Within the gate's contract — `args` from `parsePlan`, receipts from
|
|
36
|
+
* `canonicalise` — failures are values, never throws, and the order is fixed: a
|
|
37
|
+
* missing graph node is `unresolvable`, an errored or empty receipt is
|
|
38
|
+
* `missing-receipt`, a receipt that is not exactly one text block is
|
|
39
|
+
* `not-single-text`, and a non-unique projection is `ambiguous`. The function
|
|
40
|
+
* does not re-validate those inputs: a `null` receipt value, a `null` args, a
|
|
41
|
+
* cyclic tree, or an array passed as `args` would throw or be miscast. All of
|
|
42
|
+
* these are unreachable through `parsePlan`/`canonicalise`.
|
|
43
|
+
*
|
|
44
|
+
* Two containers fail closed. The root `args` object can never be a template
|
|
45
|
+
* (`unresolvable`): a template replaces one value with a scalar, and an
|
|
46
|
+
* argument object is not a scalar. Any other object that carries a `$public`
|
|
47
|
+
* key but is not a well-formed template — extra keys alongside it, a
|
|
48
|
+
* non-object value, extra keys inside it — is also `unresolvable`, so a
|
|
49
|
+
* malformed template never reaches the host as a literal `$public` argument.
|
|
50
|
+
* `field` is model-controlled, so it is regex-escaped, must be non-empty, and
|
|
51
|
+
* may only start with `$` when it is exactly `$scalar` or `$single`.
|
|
52
|
+
*
|
|
53
|
+
* `textBlocks` (not `blocks.length`) decides `not-single-text`, because only
|
|
54
|
+
* text blocks contribute to `text`. `empty` is defined by `canonicalise` as
|
|
55
|
+
* `text.length === 0`; a receipt that contradicts that invariant (empty text
|
|
56
|
+
* with `empty: false`) is treated as `missing-receipt` rather than projected,
|
|
57
|
+
* since there is no text to project from and the contradiction is a producer
|
|
58
|
+
* bug, not something to guess around.
|
|
59
|
+
*
|
|
60
|
+
* `args` comes from `JSON.parse`, so it is acyclic and already depth-capped by
|
|
61
|
+
* plan parsing. Binding returns a fresh tree and never mutates its input.
|
|
62
|
+
*
|
|
63
|
+
* @module dsh-boost/gate/binding
|
|
64
|
+
*/
|
|
65
|
+
import type { CanonicalReceipt } from '../projection/canonicalise.js';
|
|
66
|
+
/** The one well-formed template: a single `$public` key with two string fields. */
|
|
67
|
+
export type PublicTemplate = {
|
|
68
|
+
$public: {
|
|
69
|
+
after: 'root' | string;
|
|
70
|
+
field: string;
|
|
71
|
+
};
|
|
72
|
+
};
|
|
73
|
+
/** Why a value could not be projected; every one is a fallback to the model. */
|
|
74
|
+
type BindFailure = 'ambiguous' | 'unresolvable' | 'missing-receipt' | 'not-single-text';
|
|
75
|
+
/** A successful binding or the single reason it was abandoned. */
|
|
76
|
+
type BindResult = {
|
|
77
|
+
ok: true;
|
|
78
|
+
args: Record<string, unknown>;
|
|
79
|
+
} | {
|
|
80
|
+
ok: false;
|
|
81
|
+
reason: BindFailure;
|
|
82
|
+
};
|
|
83
|
+
/**
|
|
84
|
+
* Project one field out of a receipt's canonical text.
|
|
85
|
+
*
|
|
86
|
+
* `undefined` always means "cannot use this"; callers turn it into `ambiguous`.
|
|
87
|
+
* Empty fields and unknown `$`-prefixed fields are rejected before touching the
|
|
88
|
+
* text, and identifier fields are matched literally.
|
|
89
|
+
*/
|
|
90
|
+
export declare function extractField(text: string, field: string): string | undefined;
|
|
91
|
+
/**
|
|
92
|
+
* Whether `value` is the sanctioned template shape, and nothing else.
|
|
93
|
+
*
|
|
94
|
+
* A plain object with exactly one own key, `$public`, whose value is an object
|
|
95
|
+
* with exactly the two string keys `after` and `field`. Extra keys on either
|
|
96
|
+
* level are rejected rather than silently dropped: this module only understands
|
|
97
|
+
* `after`/`field`, and a template with a third directive is not something the
|
|
98
|
+
* host may receive.
|
|
99
|
+
*/
|
|
100
|
+
export declare function isTemplate(value: unknown): value is PublicTemplate;
|
|
101
|
+
/**
|
|
102
|
+
* Bind every `$public` template in `args` against the receipts of earlier
|
|
103
|
+
* steps.
|
|
104
|
+
*
|
|
105
|
+
* The root object is checked separately and can never be a template: it is an
|
|
106
|
+
* argument object, while a template produces a scalar. The same check rejects a
|
|
107
|
+
* root that merely carries a `$public` key alongside other keys.
|
|
108
|
+
*
|
|
109
|
+
* Returns a fresh `args` tree on success, or one reason the whole plan must
|
|
110
|
+
* fall back to the model. There is no partial result and no mutation.
|
|
111
|
+
*/
|
|
112
|
+
export declare function bindArgs(args: Record<string, unknown>, receipts: ReadonlyMap<string, CanonicalReceipt>): BindResult;
|
|
113
|
+
export {};
|