@dsh-cc/tool-search 0.9.4 → 0.9.5-rc.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.i18n.yaml +2 -2
- package/README.md +42 -1
- package/README.zh.md +42 -1
- package/lib/discovery-cache.d.ts +208 -0
- package/lib/discovery-cache.d.ts.map +1 -0
- package/lib/discovery-cache.js +296 -0
- package/lib/discovery-cache.js.map +1 -0
- package/lib/discovery-contract.d.ts +144 -0
- package/lib/discovery-contract.d.ts.map +1 -0
- package/lib/discovery-contract.js +144 -0
- package/lib/discovery-contract.js.map +1 -0
- package/lib/discovery-runtime.d.ts +137 -0
- package/lib/discovery-runtime.d.ts.map +1 -0
- package/lib/discovery-runtime.js +343 -0
- package/lib/discovery-runtime.js.map +1 -0
- package/lib/discovery-settings.d.ts +134 -0
- package/lib/discovery-settings.d.ts.map +1 -0
- package/lib/discovery-settings.js +269 -0
- package/lib/discovery-settings.js.map +1 -0
- package/lib/discovery.d.ts +267 -0
- package/lib/discovery.d.ts.map +1 -0
- package/lib/discovery.js +278 -0
- package/lib/discovery.js.map +1 -0
- package/lib/index.d.ts +15 -0
- package/lib/index.d.ts.map +1 -1
- package/lib/index.js +84 -88
- package/lib/index.js.map +1 -1
- package/lib/search-message.d.ts +32 -0
- package/lib/search-message.d.ts.map +1 -0
- package/lib/search-message.js +50 -0
- package/lib/search-message.js.map +1 -0
- package/lib/search-scoring.d.ts +31 -0
- package/lib/search-scoring.d.ts.map +1 -0
- package/lib/search-scoring.js +53 -0
- package/lib/search-scoring.js.map +1 -0
- package/package.json +12 -4
|
@@ -0,0 +1,269 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Settings for S1-05 tool discovery: the `cc-tool-discovery` namespace, whose
|
|
3
|
+
* raw keys are kebab-case and whose internal shape is camelCase.
|
|
4
|
+
*
|
|
5
|
+
* Design: `docs/plans/2026-11-02-systemone-05-tool-discovery.md` § "Settings"
|
|
6
|
+
* (the twelve-row table of keys, types, ranges and defaults; the decision route
|
|
7
|
+
* is not a knob — it is the exported `DECISION_LANE_ALIAS`) and § "Lifecycle,
|
|
8
|
+
* cache, and failure handling" (the fail-soft gate): when ANY setting is
|
|
9
|
+
* invalid the decision runner is NOT called, the original lexical path runs,
|
|
10
|
+
* and the failure is reported ONCE through the settings-namespace error path.
|
|
11
|
+
*
|
|
12
|
+
* Two halves, mirroring the `cc-reasoning-fold` / `retry-attendant` precedent:
|
|
13
|
+
*
|
|
14
|
+
* 1. the validated camelCase projection of the table, produced by
|
|
15
|
+
* {@link parseDiscoverySettings} (kebab raw keys → camelCase fields,
|
|
16
|
+
* unknown keys ignored per repo convention);
|
|
17
|
+
* 2. the warn-once reporter ({@link createWarnOnce}) the caller injects to get
|
|
18
|
+
* "reported once per invalid-settings occurrence" without spamming a warn on
|
|
19
|
+
* every search.
|
|
20
|
+
*
|
|
21
|
+
* Registration: {@link registerDiscoverySettings} mirrors the table as a
|
|
22
|
+
* schemastery schema (same `.min()`/`.max()` bounds) and registers the
|
|
23
|
+
* namespace idempotently through `registerNamespaceSafe`, which defers itself
|
|
24
|
+
* to `ctx.inject(['settings'])` when the settings plane has not arrived yet —
|
|
25
|
+
* the repo's lazy precedence, never a boot-time hard dependency.
|
|
26
|
+
*
|
|
27
|
+
* @module @dsh-cc/tool-search/discovery-settings
|
|
28
|
+
*/
|
|
29
|
+
import z from '@deepseek-ai/schemastery';
|
|
30
|
+
import { registerNamespaceSafe } from '@dsh-cc/settings/ns';
|
|
31
|
+
/** The settings namespace carrying the discovery knobs (design § "Settings"). */
|
|
32
|
+
export const SETTINGS_NAMESPACE = 'cc-tool-discovery';
|
|
33
|
+
/** The three modes of the design's `mode` row. */
|
|
34
|
+
export const DISCOVERY_MODES = ['off', 'shadow', 'active'];
|
|
35
|
+
/**
|
|
36
|
+
* The design's § "Settings" table, exactly: `off` by default (a dark launch),
|
|
37
|
+
* a 1200 ms transaction ceiling, and the first-round evaluation thresholds.
|
|
38
|
+
* These are evaluation parameters, not measured quality guarantees. The route
|
|
39
|
+
* alias is deliberately absent: every consumer pins `DECISION_LANE_ALIAS`.
|
|
40
|
+
*/
|
|
41
|
+
export const DEFAULT_DISCOVERY_SETTINGS = {
|
|
42
|
+
mode: 'off',
|
|
43
|
+
timeoutMs: 1200,
|
|
44
|
+
maxInputTokens: 4096,
|
|
45
|
+
maxCandidates: 64,
|
|
46
|
+
batchSize: 8,
|
|
47
|
+
maxQueryChars: 2048,
|
|
48
|
+
maxMetadataChars: 2048,
|
|
49
|
+
minRelevanceIndex: 3,
|
|
50
|
+
minDirectFit: 0.75,
|
|
51
|
+
maxActivations: 3,
|
|
52
|
+
cacheEntries: 128,
|
|
53
|
+
cacheTtlMs: 60000,
|
|
54
|
+
};
|
|
55
|
+
/** Raw kebab-case key → camelCase field, purely for problem reporting and tests. */
|
|
56
|
+
const RAW_KEYS = {
|
|
57
|
+
mode: 'mode',
|
|
58
|
+
timeoutMs: 'timeout-ms',
|
|
59
|
+
maxInputTokens: 'max-input-tokens',
|
|
60
|
+
maxCandidates: 'max-candidates',
|
|
61
|
+
batchSize: 'batch-size',
|
|
62
|
+
maxQueryChars: 'max-query-chars',
|
|
63
|
+
maxMetadataChars: 'max-metadata-chars',
|
|
64
|
+
minRelevanceIndex: 'min-relevance-index',
|
|
65
|
+
minDirectFit: 'min-direct-fit',
|
|
66
|
+
maxActivations: 'max-activations',
|
|
67
|
+
cacheEntries: 'cache-entries',
|
|
68
|
+
cacheTtlMs: 'cache-ttl-ms',
|
|
69
|
+
};
|
|
70
|
+
/** Read an absent value as its default; collect anything else that breaks the row. */
|
|
71
|
+
function readInt(raw, field, min, max, fallback, problems) {
|
|
72
|
+
const key = RAW_KEYS[field];
|
|
73
|
+
const value = raw[key];
|
|
74
|
+
if (value === undefined)
|
|
75
|
+
return fallback;
|
|
76
|
+
const expected = `integer in ${min}..${max}`;
|
|
77
|
+
if (typeof value !== 'number' || !Number.isInteger(value) || value < min || value > max) {
|
|
78
|
+
problems.push({ key, value, expected });
|
|
79
|
+
return fallback;
|
|
80
|
+
}
|
|
81
|
+
return value;
|
|
82
|
+
}
|
|
83
|
+
/** Read a fractional threshold (`min-relevance-index`, `min-direct-fit`). */
|
|
84
|
+
function readNumber(raw, field, min, max, fallback, problems) {
|
|
85
|
+
const key = RAW_KEYS[field];
|
|
86
|
+
const value = raw[key];
|
|
87
|
+
if (value === undefined)
|
|
88
|
+
return fallback;
|
|
89
|
+
// `NaN`/`Infinity` would silently disable a comparison, so both are rejected.
|
|
90
|
+
const expected = `finite number in ${min}..${max}`;
|
|
91
|
+
if (typeof value !== 'number' || !Number.isFinite(value) || value < min || value > max) {
|
|
92
|
+
problems.push({ key, value, expected });
|
|
93
|
+
return fallback;
|
|
94
|
+
}
|
|
95
|
+
return value;
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* Validate one raw `cc-tool-discovery` section against the design's table.
|
|
99
|
+
*
|
|
100
|
+
* An absent section (or an absent key) resolves to the default; a value that
|
|
101
|
+
* violates the row's type or range is collected as a {@link DiscoverySettingProblem}
|
|
102
|
+
* and the whole section is refused. Unknown keys are ignored (repo convention),
|
|
103
|
+
* so a newer config never breaks an older build.
|
|
104
|
+
* @param raw - the raw namespace section (any shape; junk is reported, not thrown on).
|
|
105
|
+
* @returns the camelCase settings, or every problem found.
|
|
106
|
+
*/
|
|
107
|
+
export function parseDiscoverySettings(raw) {
|
|
108
|
+
if (raw === undefined || raw === null)
|
|
109
|
+
return { ok: true, settings: DEFAULT_DISCOVERY_SETTINGS };
|
|
110
|
+
if (typeof raw !== 'object' || Array.isArray(raw)) {
|
|
111
|
+
return {
|
|
112
|
+
ok: false,
|
|
113
|
+
problems: [{ key: SETTINGS_NAMESPACE, value: raw, expected: 'object of kebab-case keys' }],
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
const section = raw;
|
|
117
|
+
const problems = [];
|
|
118
|
+
const defaults = DEFAULT_DISCOVERY_SETTINGS;
|
|
119
|
+
// `mode` — one of the three literals; anything else leaves the feature off.
|
|
120
|
+
const rawMode = section[RAW_KEYS.mode];
|
|
121
|
+
const modeIsValid = DISCOVERY_MODES.includes(rawMode);
|
|
122
|
+
const mode = modeIsValid ? rawMode : defaults.mode;
|
|
123
|
+
if (rawMode !== undefined && !modeIsValid) {
|
|
124
|
+
problems.push({ key: RAW_KEYS.mode, value: rawMode, expected: DISCOVERY_MODES.join(' | ') });
|
|
125
|
+
}
|
|
126
|
+
const settings = {
|
|
127
|
+
mode,
|
|
128
|
+
// `timeout-ms` is the ceiling for the whole transaction.
|
|
129
|
+
timeoutMs: readInt(section, 'timeoutMs', 100, 5000, defaults.timeoutMs, problems),
|
|
130
|
+
maxInputTokens: readInt(section, 'maxInputTokens', 512, 16384, defaults.maxInputTokens, problems),
|
|
131
|
+
maxCandidates: readInt(section, 'maxCandidates', 1, 128, defaults.maxCandidates, problems),
|
|
132
|
+
batchSize: readInt(section, 'batchSize', 1, 16, defaults.batchSize, problems),
|
|
133
|
+
maxQueryChars: readInt(section, 'maxQueryChars', 64, 8192, defaults.maxQueryChars, problems),
|
|
134
|
+
maxMetadataChars: readInt(section, 'maxMetadataChars', 128, 8192, defaults.maxMetadataChars, problems),
|
|
135
|
+
minRelevanceIndex: readNumber(section, 'minRelevanceIndex', 0, 4, defaults.minRelevanceIndex, problems),
|
|
136
|
+
minDirectFit: readNumber(section, 'minDirectFit', 0, 1, defaults.minDirectFit, problems),
|
|
137
|
+
maxActivations: readInt(section, 'maxActivations', 1, 20, defaults.maxActivations, problems),
|
|
138
|
+
// `cache-entries: 0` disables storage; `cache-ttl-ms: 0` makes no entry reusable.
|
|
139
|
+
cacheEntries: readInt(section, 'cacheEntries', 0, 1024, defaults.cacheEntries, problems),
|
|
140
|
+
cacheTtlMs: readInt(section, 'cacheTtlMs', 0, 300000, defaults.cacheTtlMs, problems),
|
|
141
|
+
};
|
|
142
|
+
if (problems.length > 0)
|
|
143
|
+
return { ok: false, problems };
|
|
144
|
+
return { ok: true, settings };
|
|
145
|
+
}
|
|
146
|
+
/** Render an invalid parse as the single operator-facing line the reporter emits. */
|
|
147
|
+
export function describeDiscoverySettingsProblems(problems) {
|
|
148
|
+
const detail = problems
|
|
149
|
+
.map(problem => `${problem.key} must be ${problem.expected} (got ${JSON.stringify(problem.value) ?? 'undefined'})`)
|
|
150
|
+
.join('; ');
|
|
151
|
+
return `${SETTINGS_NAMESPACE}: invalid settings — running the lexical path with no decision runner: ${detail}`;
|
|
152
|
+
}
|
|
153
|
+
/**
|
|
154
|
+
* Build the warn-once reporter the design's § "Settings" fail-soft path asks
|
|
155
|
+
* for: `ctx.logger.warn` fires at most once per invalid-settings occurrence,
|
|
156
|
+
* never on the hot path more than that.
|
|
157
|
+
* @param warn - the injected sink (usually `message => ctx.logger.warn(message)`).
|
|
158
|
+
* @returns the reporter to hand to {@link resolveDiscoverySettings}.
|
|
159
|
+
*/
|
|
160
|
+
export function createWarnOnce(warn) {
|
|
161
|
+
let lastReported;
|
|
162
|
+
return {
|
|
163
|
+
report(result) {
|
|
164
|
+
if (result.ok)
|
|
165
|
+
return;
|
|
166
|
+
const signature = JSON.stringify(result.problems.map(problem => [problem.key, problem.expected, problem.value]));
|
|
167
|
+
if (signature === lastReported)
|
|
168
|
+
return;
|
|
169
|
+
lastReported = signature;
|
|
170
|
+
warn(describeDiscoverySettingsProblems(result.problems));
|
|
171
|
+
},
|
|
172
|
+
reset() {
|
|
173
|
+
lastReported = undefined;
|
|
174
|
+
},
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
/**
|
|
178
|
+
* Resolve the live settings for one search.
|
|
179
|
+
*
|
|
180
|
+
* This is the runner gate of the design's § "Settings" contract: `undefined`
|
|
181
|
+
* means "invalid configuration — do not call the runner, run the lexical path",
|
|
182
|
+
* and the failure has been reported once through the injected reporter.
|
|
183
|
+
* @param raw - the raw `cc-tool-discovery` section, or `undefined` when absent.
|
|
184
|
+
* @param reporter - the warn-once sink; omitted only in tests.
|
|
185
|
+
* @returns validated settings, or `undefined` when the configuration is invalid.
|
|
186
|
+
*/
|
|
187
|
+
export function resolveDiscoverySettings(raw, reporter) {
|
|
188
|
+
const parsed = parseDiscoverySettings(raw);
|
|
189
|
+
if (parsed.ok)
|
|
190
|
+
return parsed.settings;
|
|
191
|
+
reporter?.report(parsed);
|
|
192
|
+
return undefined;
|
|
193
|
+
}
|
|
194
|
+
/** `z.union([t, z.const(undefined)])`: an absent namespace stays absent. */
|
|
195
|
+
const opt = (t) => z.union([t, z.const(undefined)]);
|
|
196
|
+
/**
|
|
197
|
+
* The design's § "Settings" table as a schemastery shape: raw kebab-case keys
|
|
198
|
+
* with the same `.min()`/`.max()` bounds {@link parseDiscoverySettings}
|
|
199
|
+
* enforces. The bounds are mirrored, not moved — schemastery rejects a
|
|
200
|
+
* malformed user layer at publish time so a typo never reaches a judgment,
|
|
201
|
+
* while the parse stays the authoritative gate for callers reading a raw
|
|
202
|
+
* section (integer-ness is not expressible in schemastery).
|
|
203
|
+
*/
|
|
204
|
+
const DiscoverySettingsObject = z.object({
|
|
205
|
+
mode: z.union([z.const('off'), z.const('shadow'), z.const('active')]).default(DEFAULT_DISCOVERY_SETTINGS.mode),
|
|
206
|
+
'timeout-ms': z.number().min(100).max(5000).default(DEFAULT_DISCOVERY_SETTINGS.timeoutMs),
|
|
207
|
+
'max-input-tokens': z.number().min(512).max(16384).default(DEFAULT_DISCOVERY_SETTINGS.maxInputTokens),
|
|
208
|
+
'max-candidates': z.number().min(1).max(128).default(DEFAULT_DISCOVERY_SETTINGS.maxCandidates),
|
|
209
|
+
'batch-size': z.number().min(1).max(16).default(DEFAULT_DISCOVERY_SETTINGS.batchSize),
|
|
210
|
+
'max-query-chars': z.number().min(64).max(8192).default(DEFAULT_DISCOVERY_SETTINGS.maxQueryChars),
|
|
211
|
+
'max-metadata-chars': z.number().min(128).max(8192).default(DEFAULT_DISCOVERY_SETTINGS.maxMetadataChars),
|
|
212
|
+
'min-relevance-index': z.number().min(0).max(4).default(DEFAULT_DISCOVERY_SETTINGS.minRelevanceIndex),
|
|
213
|
+
'min-direct-fit': z.number().min(0).max(1).default(DEFAULT_DISCOVERY_SETTINGS.minDirectFit),
|
|
214
|
+
'max-activations': z.number().min(1).max(20).default(DEFAULT_DISCOVERY_SETTINGS.maxActivations),
|
|
215
|
+
'cache-entries': z.number().min(0).max(1024).default(DEFAULT_DISCOVERY_SETTINGS.cacheEntries),
|
|
216
|
+
'cache-ttl-ms': z.number().min(0).max(300000).default(DEFAULT_DISCOVERY_SETTINGS.cacheTtlMs),
|
|
217
|
+
});
|
|
218
|
+
/**
|
|
219
|
+
* Namespace schema, wrapped in the `z.const(undefined)` union (the
|
|
220
|
+
* `cc-reasoning-fold` / `retry-attendant` convention) so a genuinely absent
|
|
221
|
+
* namespace never materializes defaults into the cascade; the defaults then
|
|
222
|
+
* come from {@link DEFAULT_DISCOVERY_SETTINGS} on read.
|
|
223
|
+
*/
|
|
224
|
+
export const DiscoverySettingsSchema = opt(DiscoverySettingsObject);
|
|
225
|
+
/**
|
|
226
|
+
* Register the `cc-tool-discovery` namespace and return the live reader.
|
|
227
|
+
*
|
|
228
|
+
* Follows the settings-plane discipline: registration is idempotent and
|
|
229
|
+
* deferred until the settings service exists, an absent or refusing settings
|
|
230
|
+
* plane reads as the documented defaults (`mode: off`), and an invalid section
|
|
231
|
+
* is reported ONCE and then reads `undefined` — the caller's "no runner call,
|
|
232
|
+
* run the lexical path" gate (§ "Settings", § "Lifecycle, cache, and failure
|
|
233
|
+
* handling").
|
|
234
|
+
* @param ctx - the mount context; registration effects bind here.
|
|
235
|
+
* @param reporter - the warn-once sink (`createWarnOnce` over `ctx.logger.warn`).
|
|
236
|
+
* @returns a per-use reader of the validated camelCase settings.
|
|
237
|
+
*/
|
|
238
|
+
export function registerDiscoverySettings(ctx, reporter) {
|
|
239
|
+
let read;
|
|
240
|
+
try {
|
|
241
|
+
read = registerNamespaceSafe(ctx, SETTINGS_NAMESPACE, DiscoverySettingsSchema);
|
|
242
|
+
}
|
|
243
|
+
catch {
|
|
244
|
+
// A settings layer that refuses registration must never break mounting;
|
|
245
|
+
// absent reads keep the feature off.
|
|
246
|
+
return () => DEFAULT_DISCOVERY_SETTINGS;
|
|
247
|
+
}
|
|
248
|
+
return () => {
|
|
249
|
+
let raw;
|
|
250
|
+
try {
|
|
251
|
+
raw = read();
|
|
252
|
+
}
|
|
253
|
+
catch (error) {
|
|
254
|
+
// The schema rejected the user layer on the settings-ns path: report it
|
|
255
|
+
// once and refuse to judge instead of throwing into a hot search.
|
|
256
|
+
reporter?.report({
|
|
257
|
+
ok: false,
|
|
258
|
+
problems: [{
|
|
259
|
+
key: SETTINGS_NAMESPACE,
|
|
260
|
+
value: error instanceof Error ? error.message : String(error),
|
|
261
|
+
expected: 'a valid cc-tool-discovery section',
|
|
262
|
+
}],
|
|
263
|
+
});
|
|
264
|
+
return undefined;
|
|
265
|
+
}
|
|
266
|
+
return resolveDiscoverySettings(raw, reporter);
|
|
267
|
+
};
|
|
268
|
+
}
|
|
269
|
+
//# sourceMappingURL=discovery-settings.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"discovery-settings.js","sourceRoot":"","sources":["../src/discovery-settings.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AAIH,OAAO,CAAC,MAAM,0BAA0B,CAAA;AACxC,OAAO,EAAE,qBAAqB,EAAE,MAAM,qBAAqB,CAAA;AAM3D,iFAAiF;AACjF,MAAM,CAAC,MAAM,kBAAkB,GAAG,mBAAmB,CAAA;AAErD,kDAAkD;AAClD,MAAM,CAAC,MAAM,eAAe,GAAG,CAAC,KAAK,EAAE,QAAQ,EAAE,QAAQ,CAAU,CAAA;AAKnE;;;;;GAKG;AACH,MAAM,CAAC,MAAM,0BAA0B,GAAsB;IAC3D,IAAI,EAAE,KAAK;IACX,SAAS,EAAE,IAAI;IACf,cAAc,EAAE,IAAI;IACpB,aAAa,EAAE,EAAE;IACjB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AAM,CAAC,KAAK,CAAC;wBAC7D,QAAQ,EAAE,mCAAmC;qBAC9C,CAAC;aACH,CAAC,CAAA;YACF,OAAO,SAAS,CAAA;QAClB,CAAC;QACD,OAAO,wBAAwB,CAAC,GAAG,EAAE,QAAQ,CAAC,CAAA;IAChD,CAAC,CAAA;AACH,CAAC"}
|
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The pure policy layer of S1-05 tool discovery: which deferred candidates may
|
|
3
|
+
* be judged, what is asked about each of them, how the pool is grouped against
|
|
4
|
+
* a route's request window, and how the answers collapse into an activation
|
|
5
|
+
* order.
|
|
6
|
+
*
|
|
7
|
+
* Everything here is a total function from plain data to plain data — no I/O,
|
|
8
|
+
* no clock, no cordis, no runner, and no dependency on the SystemOne client
|
|
9
|
+
* package (the question/answer shapes are declared structurally so the wiring
|
|
10
|
+
* layer can pass S1-01's `SystemOneQuestion`/`SystemOneAnswer` through
|
|
11
|
+
* unchanged). Determinism matters on both ends of the decision: the same pool
|
|
12
|
+
* must produce byte-identical questions and batches so the cache key and the
|
|
13
|
+
* offline replay evaluator agree with production.
|
|
14
|
+
*
|
|
15
|
+
* The design's `DiscoveryResult` carries `decisionIds`; those are minted by the
|
|
16
|
+
* runtime that owns a decision, so this layer's result deliberately stops at
|
|
17
|
+
* names and fallback reasons.
|
|
18
|
+
*
|
|
19
|
+
* Section references below are into
|
|
20
|
+
* `docs/plans/2026-11-02-systemone-05-tool-discovery.md`.
|
|
21
|
+
*/
|
|
22
|
+
/** Question-set version sent on the wire ("Inputs, questions, and output"). */
|
|
23
|
+
export declare const TOOL_DISCOVERY_QUESTION_VERSION = "tool-discovery-v1";
|
|
24
|
+
/** Policy version sent on the wire ("Inputs, questions, and output"). */
|
|
25
|
+
export declare const TOOL_DISCOVERY_POLICY_VERSION = "tool-discovery-policy-v1";
|
|
26
|
+
/**
|
|
27
|
+
* Discovery settings in camelCase, one field per row of the "Settings" table.
|
|
28
|
+
* The settings layer validates ranges and the kebab-case raw keys; this layer
|
|
29
|
+
* only consumes the validated values, so it never throws on a bad threshold.
|
|
30
|
+
*/
|
|
31
|
+
export interface DiscoverySettings {
|
|
32
|
+
/** `off` preserves the lexical path with zero runner calls. */
|
|
33
|
+
readonly mode: 'off' | 'shadow' | 'active';
|
|
34
|
+
/** Time ceiling for the whole discovery transaction. */
|
|
35
|
+
readonly timeoutMs: number;
|
|
36
|
+
/** Per runner request, including questions and headroom. */
|
|
37
|
+
readonly maxInputTokens: number;
|
|
38
|
+
/** Cap on the complete eligible pool. */
|
|
39
|
+
readonly maxCandidates: number;
|
|
40
|
+
/** Candidates per runner request before window splitting. */
|
|
41
|
+
readonly batchSize: number;
|
|
42
|
+
/** Longest query, in characters, that may be judged. */
|
|
43
|
+
readonly maxQueryChars: number;
|
|
44
|
+
/** Combined per-field cap applied to the description and the search hint. */
|
|
45
|
+
readonly maxMetadataChars: number;
|
|
46
|
+
/** Experimental relevance threshold, compared against the score's expected value. */
|
|
47
|
+
readonly minRelevanceIndex: number;
|
|
48
|
+
/** Experimental direct-fit threshold, compared against the `noul` answer. */
|
|
49
|
+
readonly minDirectFit: number;
|
|
50
|
+
/** Upper bound on activated names, whatever the caller asks for. */
|
|
51
|
+
readonly maxActivations: number;
|
|
52
|
+
/** In-process cache entries; `0` disables the cache. */
|
|
53
|
+
readonly cacheEntries: number;
|
|
54
|
+
/** Cache entry lifetime. */
|
|
55
|
+
readonly cacheTtlMs: number;
|
|
56
|
+
}
|
|
57
|
+
/** One candidate as it is sent to the runner ("Inputs, questions, and output"). */
|
|
58
|
+
export interface DiscoveryCandidate {
|
|
59
|
+
/** The stable `cN` id assigned by {@link buildEligiblePool}. */
|
|
60
|
+
readonly id: string;
|
|
61
|
+
readonly name: string;
|
|
62
|
+
readonly description: string;
|
|
63
|
+
readonly searchHint?: string;
|
|
64
|
+
/** The lexical baseline score; recorded for tie-breaking, never filtered on. */
|
|
65
|
+
readonly lexicalScore: number;
|
|
66
|
+
}
|
|
67
|
+
/** The whole state one discovery transaction judges. */
|
|
68
|
+
export interface DiscoveryInput {
|
|
69
|
+
readonly query: string;
|
|
70
|
+
readonly candidates: readonly DiscoveryCandidate[];
|
|
71
|
+
/** Hash of the full visible catalog; a change invalidates the judgment. */
|
|
72
|
+
readonly catalogHash: string;
|
|
73
|
+
/** Hash of the scope's admission set; a change invalidates the judgment. */
|
|
74
|
+
readonly admissionHash: string;
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* What the policy layer decides. `lexical` and `cancelled` are whole-path
|
|
78
|
+
* outcomes (the wiring layer runs the original `search()`); `selected` carries
|
|
79
|
+
* names only — the runner that owns a decision mints its `decisionId`.
|
|
80
|
+
*/
|
|
81
|
+
export type DiscoveryResult = {
|
|
82
|
+
readonly kind: 'selected';
|
|
83
|
+
readonly names: string[];
|
|
84
|
+
} | {
|
|
85
|
+
readonly kind: 'lexical';
|
|
86
|
+
readonly reason: 'off' | 'bounds' | 'unavailable' | 'stale';
|
|
87
|
+
} | {
|
|
88
|
+
readonly kind: 'cancelled';
|
|
89
|
+
};
|
|
90
|
+
/**
|
|
91
|
+
* Whole-path fallback: the pool or a group did not fit a hard bound, so the
|
|
92
|
+
* judgment is abandoned as a whole instead of being truncated ("Deterministic
|
|
93
|
+
* execution order" steps 4 and 5). Lexical retrieval is never partially
|
|
94
|
+
* blended with a model judgment.
|
|
95
|
+
*/
|
|
96
|
+
export type BoundsFallback = {
|
|
97
|
+
readonly kind: 'bounds';
|
|
98
|
+
};
|
|
99
|
+
/**
|
|
100
|
+
* One scope-snapshot deferred entry, as the registry exposes it before the pool
|
|
101
|
+
* is built. `lexicalScore` is optional because the score comes from the
|
|
102
|
+
* lexical baseline, not the entry: when absent the candidate is scored `0`,
|
|
103
|
+
* which never excludes it.
|
|
104
|
+
*/
|
|
105
|
+
export interface DeferredEntry {
|
|
106
|
+
readonly name: string;
|
|
107
|
+
readonly description: string;
|
|
108
|
+
readonly searchHint?: string;
|
|
109
|
+
/** Never a discovery candidate: already visible from the start. */
|
|
110
|
+
readonly alwaysLoad: boolean;
|
|
111
|
+
/** Never re-judged: already loaded for this scope. */
|
|
112
|
+
readonly activated: boolean;
|
|
113
|
+
/** The scope's permission verdict; the final activation re-checks it anyway. */
|
|
114
|
+
readonly admitted: boolean;
|
|
115
|
+
/** The lexical baseline score, when the caller has already computed it. */
|
|
116
|
+
readonly lexicalScore?: number;
|
|
117
|
+
}
|
|
118
|
+
/** The eligible pool, or the whole-path fallback sentinel. */
|
|
119
|
+
export type EligiblePool = {
|
|
120
|
+
readonly kind: 'pool';
|
|
121
|
+
readonly candidates: readonly DiscoveryCandidate[];
|
|
122
|
+
} | BoundsFallback;
|
|
123
|
+
/**
|
|
124
|
+
* One typed-decision question. Structurally a subset of S1-01's
|
|
125
|
+
* `SystemOneQuestion`, so it can be sent without this package depending on the
|
|
126
|
+
* SystemOne client.
|
|
127
|
+
*/
|
|
128
|
+
export interface DiscoveryQuestion {
|
|
129
|
+
readonly type: 'score' | 'noul';
|
|
130
|
+
readonly instructions: string;
|
|
131
|
+
readonly criteria?: readonly string[];
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* The keyless route identity returned by `identifyRoute` (design § "File
|
|
135
|
+
* responsibilities": the consumer re-reads it after every await and compares
|
|
136
|
+
* ALL SEVEN fields, because any of them changing is a different judgment). This
|
|
137
|
+
* is the single canonical declaration of that shape in the package — the cache
|
|
138
|
+
* key layer imports it from here rather than restating it.
|
|
139
|
+
*/
|
|
140
|
+
export interface DiscoveryRouteIdentity {
|
|
141
|
+
/** Gateway provider name. */
|
|
142
|
+
readonly provider: string;
|
|
143
|
+
/** Model identifier as the gateway reports it (never compared against an alias). */
|
|
144
|
+
readonly model: string;
|
|
145
|
+
/** Opaque revision/deployment marker; a bump invalidates old judgments. */
|
|
146
|
+
readonly revision: string;
|
|
147
|
+
/** Token budget reserved for one discovery request. */
|
|
148
|
+
readonly perRequestTokens: number;
|
|
149
|
+
/** Token budget reserved for one question. */
|
|
150
|
+
readonly perQuestionTokens: number;
|
|
151
|
+
/** Questions one request may carry. */
|
|
152
|
+
readonly maxQuestions: number;
|
|
153
|
+
/** Maximum output tokens for one answer. */
|
|
154
|
+
readonly maxOutputTokens: number;
|
|
155
|
+
}
|
|
156
|
+
/**
|
|
157
|
+
* The route's request windows alone: what batch planning measures against.
|
|
158
|
+
* Structurally a projection of {@link DiscoveryRouteIdentity}, so a full
|
|
159
|
+
* identity satisfies it.
|
|
160
|
+
*/
|
|
161
|
+
export type DiscoveryRouteWindow = Pick<DiscoveryRouteIdentity, 'perRequestTokens' | 'perQuestionTokens' | 'maxQuestions'>;
|
|
162
|
+
/** The batch plan, or the whole-path fallback sentinel. */
|
|
163
|
+
export type BatchPlan = {
|
|
164
|
+
readonly kind: 'batches';
|
|
165
|
+
readonly batches: readonly (readonly DiscoveryCandidate[])[];
|
|
166
|
+
} | BoundsFallback;
|
|
167
|
+
/** One scored candidate as the policy consumes it ("Deterministic execution order" step 7). */
|
|
168
|
+
export interface DiscoveryScoredItem {
|
|
169
|
+
readonly id: string;
|
|
170
|
+
readonly name: string;
|
|
171
|
+
/** Expected value over indices 0..4 of the relevance answer; may be fractional. */
|
|
172
|
+
readonly scoreIndex: number;
|
|
173
|
+
/** The direct-fit answer, 0..1. */
|
|
174
|
+
readonly noul: number;
|
|
175
|
+
/** The lexical baseline score, used only as a tie-break. */
|
|
176
|
+
readonly lexicalScore: number;
|
|
177
|
+
}
|
|
178
|
+
/**
|
|
179
|
+
* One parsed answer entry. Structurally a subset of S1-01's
|
|
180
|
+
* `SystemOneAnswer`: every field is optional so a partial or malformed entry is
|
|
181
|
+
* merely unusable instead of a type error.
|
|
182
|
+
*/
|
|
183
|
+
export interface DiscoveryAnswer {
|
|
184
|
+
readonly type?: 'choice' | 'score' | 'noul';
|
|
185
|
+
readonly choice?: string;
|
|
186
|
+
readonly probabilities?: Readonly<Record<string, number>>;
|
|
187
|
+
readonly score?: number;
|
|
188
|
+
readonly noul?: number;
|
|
189
|
+
readonly confidence?: number;
|
|
190
|
+
}
|
|
191
|
+
/**
|
|
192
|
+
* Deterministic token estimate used by every window check: one token per three
|
|
193
|
+
* characters, rounded up. Deliberately crude — a stable estimate that both the
|
|
194
|
+
* request budget and the offline replay can reproduce exactly.
|
|
195
|
+
* @param text - the text to estimate.
|
|
196
|
+
* @returns the estimated token count.
|
|
197
|
+
*/
|
|
198
|
+
export declare function estimateTokens(text: string): number;
|
|
199
|
+
/**
|
|
200
|
+
* Build the eligible pool ("Deterministic execution order" steps 3 and 4).
|
|
201
|
+
*
|
|
202
|
+
* Steps: drop `alwaysLoad`, already-activated, and non-admitted entries;
|
|
203
|
+
* assign stable `c0..cN` ids in ascending name order; keep every remaining
|
|
204
|
+
* candidate regardless of its lexical score (a Chinese or synonymous query can
|
|
205
|
+
* score zero and still be relevant); then bound the whole judgment. Any bound
|
|
206
|
+
* violation — a trimmed query longer than `max-query-chars`, one description or
|
|
207
|
+
* search hint longer than `max-metadata-chars`, a pool larger than
|
|
208
|
+
* `max-candidates`, or an empty pool — falls back as a whole. Text is never
|
|
209
|
+
* truncated: a truncated judgment would claim a completeness it does not have.
|
|
210
|
+
* @param entries - the scope-visible deferred entries.
|
|
211
|
+
* @param query - the raw ToolSearch query.
|
|
212
|
+
* @param settings - the validated discovery settings.
|
|
213
|
+
* @returns the pool with stable ids, or the whole-path fallback sentinel.
|
|
214
|
+
*/
|
|
215
|
+
export declare function buildEligiblePool(entries: readonly DeferredEntry[], query: string, settings: DiscoverySettings): EligiblePool;
|
|
216
|
+
/**
|
|
217
|
+
* Build two questions per candidate, keyed `<id>_relevance` (a `score` question
|
|
218
|
+
* over the 0..4 rubric) and `<id>_direct` (a `noul` question). Independent
|
|
219
|
+
* questions per candidate mean one candidate's metadata cannot contaminate
|
|
220
|
+
* another's judgment, and repeated ids stay stable across replays.
|
|
221
|
+
* @param candidates - the eligible pool.
|
|
222
|
+
* @returns the complete question map, in candidate order.
|
|
223
|
+
*/
|
|
224
|
+
export declare function buildQuestions(candidates: readonly DiscoveryCandidate[]): Record<string, DiscoveryQuestion>;
|
|
225
|
+
/**
|
|
226
|
+
* Group the pool for the runner ("Deterministic execution order" step 5).
|
|
227
|
+
*
|
|
228
|
+
* Candidates are ordered by ascending id and cut into groups of `batchSize`.
|
|
229
|
+
* Each group must fit the route's per-request token window, carry no more than
|
|
230
|
+
* `maxQuestions` questions, and keep every single question inside
|
|
231
|
+
* `perQuestionTokens`. A group that does not fit is halved into whole smaller
|
|
232
|
+
* groups and re-measured; when a one-candidate group still does not fit, no
|
|
233
|
+
* partial judgment is possible and the whole path falls back.
|
|
234
|
+
* @param candidates - the eligible pool.
|
|
235
|
+
* @param batchSize - the configured `batch-size`.
|
|
236
|
+
* @param routeIdentity - the keyless route identity from `identifyRoute`.
|
|
237
|
+
* @param query - the query the request would carry; folded into the cost.
|
|
238
|
+
* @returns the whole-group batches in id order, or the fallback sentinel.
|
|
239
|
+
*/
|
|
240
|
+
export declare function planBatches(candidates: readonly DiscoveryCandidate[], batchSize: number, routeIdentity: DiscoveryRouteWindow, query?: string): BatchPlan;
|
|
241
|
+
/**
|
|
242
|
+
* Filter and order the scored pool into an activation list ("Deterministic
|
|
243
|
+
* execution order" steps 7 and 8).
|
|
244
|
+
*
|
|
245
|
+
* Keep only items whose relevance expected value reaches `min-relevance-index`
|
|
246
|
+
* AND whose direct-fit answer reaches `min-direct-fit`; order by score
|
|
247
|
+
* descending, then direct fit, then lexical score, then name. The result is
|
|
248
|
+
* capped at `min(maxResults, max-activations)`. An empty result is valid and is
|
|
249
|
+
* never backfilled with lexical hits.
|
|
250
|
+
* @param scored - the scored candidates.
|
|
251
|
+
* @param settings - the thresholds and the activation cap.
|
|
252
|
+
* @param maxResults - the caller's `max_results`.
|
|
253
|
+
* @returns the names to activate, in deterministic order.
|
|
254
|
+
*/
|
|
255
|
+
export declare function selectNames(scored: readonly DiscoveryScoredItem[], settings: Pick<DiscoverySettings, 'minRelevanceIndex' | 'minDirectFit' | 'maxActivations'>, maxResults: number): string[];
|
|
256
|
+
/**
|
|
257
|
+
* Read the relevance answer's expected value over indices 0..4 ("Inputs,
|
|
258
|
+
* questions, and output"): a fractional `Score` is the weighted sum of the
|
|
259
|
+
* per-index probabilities, not a class label. The probabilities win when they
|
|
260
|
+
* are usable, normalized by their own total so a non-normalized envelope still
|
|
261
|
+
* yields a value in range; the reported `score` is the fallback.
|
|
262
|
+
* @param answers - the answer map keyed by question key.
|
|
263
|
+
* @param id - the candidate id; the `_relevance` question is read.
|
|
264
|
+
* @returns the expected value, or `undefined` when the answer is unusable.
|
|
265
|
+
*/
|
|
266
|
+
export declare function expectedScore(answers: Readonly<Record<string, DiscoveryAnswer | undefined>>, id: string): number | undefined;
|
|
267
|
+
//# sourceMappingURL=discovery.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"discovery.d.ts","sourceRoot":"","sources":["../src/discovery.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH,+EAA+E;AAC/E,eAAO,MAAM,+BAA+B,sBAAsB,CAAA;AAElE,yEAAyE;AACzE,eAAO,MAAM,6BAA6B,6BAA6B,CAAA;AAYvE;;;;GAIG;AACH,MAAM,WAAW,iBAAiB;IAChC,+DAA+D;IAC/D,QAAQ,CAAC,IAAI,EAAE,KAAK,GAAG,QAAQ,GAAG,QAAQ,CAAA;IAC1C,wDAAwD;IACxD,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAA;IAC1B,4DAA4D;IAC5D,QAAQ,CAAC,cAAc,EAAE,MAAM,CAAA;IAC/B,yCAAyC;IACzC,QAAQ,CAAC,aAAa,EAAE,MAAM,CAAA;IAC9B,6DAA6D;IAC7D,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAA;IAC1B,wDAAwD;IACxD,QAAQ,CAAC,aAAa,EAAE,MAAM,CAAA;IAC9B,6EAA6E;IAC7E,QAAQ,CAAC,gBAAgB,EAAE,MAAM,CAAA;IACjC,qFA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