@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.
@@ -0,0 +1,144 @@
1
+ /**
2
+ * The structural boundary between tool discovery and S1-02's decision runtime:
3
+ * the request/response faces it consumes, the host resolver seam, and the two
4
+ * snapshot digests that pin a judgment to a catalog and an admission set.
5
+ *
6
+ * Design: `docs/plans/2026-11-02-systemone-05-tool-discovery.md`
7
+ * § "File responsibilities" (the runner comes from the optional
8
+ * `ctx.systemoneDecisions` service; re-read the identity after every await and
9
+ * compare all fields), § "Inputs, questions, and output", § "Lifecycle, cache,
10
+ * and failure handling" (what the cache key pins).
11
+ *
12
+ * These interfaces are declared STRUCTURALLY — exactly as `discovery.ts`
13
+ * declares the question and answer shapes — so `@dsh-cc/tool-search` never takes
14
+ * a dependency on the SystemOne client: the host passes its real
15
+ * `BoundDecisionRunner`/`DecisionRun` through these seams unchanged.
16
+ *
17
+ * @module @dsh-cc/tool-search/discovery-contract
18
+ */
19
+ import type { DeferredEntry, DiscoveryAnswer, DiscoveryCandidate, DiscoveryQuestion, DiscoveryRouteIdentity, DiscoverySettings } from './discovery.ts';
20
+ import type { DiscoveryThresholds } from './discovery-cache.ts';
21
+ /** The actor a judgment is bound to: structurally an `Agent`, opaque here. */
22
+ export type DiscoveryActor = object;
23
+ /**
24
+ * The metering scope S1-02 binds to an actor: the host resolves project,
25
+ * session and agent, and `originSeq` is the persisted session watermark —
26
+ * never `events.length` (§ "Inputs, questions, and output").
27
+ */
28
+ export interface DiscoveryScope {
29
+ readonly projectKey: string;
30
+ readonly sessionId: string;
31
+ readonly agentId: string;
32
+ readonly originSeq: number;
33
+ }
34
+ /** One parsed answer map, keyed by question key. */
35
+ export type DiscoveryAnswerMap = Readonly<Record<string, DiscoveryAnswer | undefined>>;
36
+ /** The closed unavailable reasons of a runner decision (S1-02 contract). */
37
+ export type DiscoveryUnavailableReason = 'unconfigured' | 'budget' | 'timeout' | 'cancelled' | 'malformed' | 'error';
38
+ /** One runner response, structurally S1-02's `DecisionRun`. */
39
+ export type DiscoveryDecisionRun = {
40
+ readonly status: 'answered';
41
+ readonly answers: DiscoveryAnswerMap;
42
+ readonly decisionId?: string;
43
+ } | {
44
+ readonly status: 'unavailable';
45
+ readonly reason: DiscoveryUnavailableReason;
46
+ readonly decisionId?: string;
47
+ };
48
+ /**
49
+ * The one request this layer sends, structurally S1-02's `DecisionRequest`.
50
+ * `state` carries ONLY the query and this batch's candidate metadata — no tool
51
+ * callbacks, credentials, parameter schemas or message history.
52
+ */
53
+ export interface DiscoveryDecisionRequest {
54
+ readonly feature: 'tool-discovery';
55
+ readonly mode: 'shadow' | 'active';
56
+ readonly routeAlias: string;
57
+ readonly questionVersion: string;
58
+ readonly policyVersion: string;
59
+ readonly scope: DiscoveryScope;
60
+ readonly state: unknown;
61
+ readonly questions: Record<string, DiscoveryQuestion>;
62
+ readonly timeoutMs: number;
63
+ readonly maxInputTokens: number;
64
+ readonly signal: AbortSignal;
65
+ }
66
+ /** The bound runner face this layer consumes: S1-02's `BoundDecisionRunner`. */
67
+ export interface DiscoveryRunner {
68
+ identifyRoute(alias: string, scope: DiscoveryScope): DiscoveryRouteIdentity | undefined;
69
+ scope(originSeq?: number): DiscoveryScope;
70
+ run(request: DiscoveryDecisionRequest): Promise<DiscoveryDecisionRun>;
71
+ }
72
+ /**
73
+ * The host face the default resolver reads: the optional `systemoneDecisions`
74
+ * service mounted by S1-02's `decision-usage` plugin. Its absence is the
75
+ * design's "runner missing" row — a lexical fallback with no model call.
76
+ */
77
+ export interface DiscoveryHostFace {
78
+ readonly systemoneDecisions?: {
79
+ forAgent(actor: DiscoveryActor): DiscoveryRunner;
80
+ };
81
+ readonly ccSystemoneDecisions?: {
82
+ forAgent(actor: DiscoveryActor): DiscoveryRunner;
83
+ };
84
+ /** Optional guarded service getter (structurally cordis `ctx.get`). */
85
+ get?(name: string): unknown;
86
+ }
87
+ /**
88
+ * The default runner resolver: read the optional host service and bind it to
89
+ * the calling actor. Never throws — a service that refuses to bind is
90
+ * "unavailable", not a failed search.
91
+ *
92
+ * Resolution order (issue #359: tool-search is mounted at the bundle layer,
93
+ * the ROOT realm, where the isolate-scoped `systemoneDecisions` name has no
94
+ * implementation — the root-realm bridge `ccSystemoneDecisions`, published by
95
+ * `@dsh-cc/decision-usage` for exactly such out-of-group consumers, is the
96
+ * production landing):
97
+ *
98
+ * 1. `host.get('systemoneDecisions')` — the isolated name, so in-group hosts
99
+ * bind their OWN tree's instance (a second preset tree can overwrite the
100
+ * root bridge while each tree keeps its isolated service).
101
+ * 2. `host.get('ccSystemoneDecisions')` — the root-realm bridge.
102
+ * 3. Property fallbacks — the pre-bridge behavior, for structural hosts
103
+ * without a `get` seam.
104
+ *
105
+ * Each step is individually guarded: a throw (an isolate name crossing
106
+ * realms), an `undefined` result (no implementation in this realm's store) or
107
+ * a wrong-shaped value degrades to the NEXT step, never aborts resolution.
108
+ * @param host - the host context face (structurally the cordis context).
109
+ * @returns the resolver handed to `createDiscoveryRuntime`.
110
+ */
111
+ export declare function hostRunnerResolver(host: DiscoveryHostFace): (actor: DiscoveryActor) => DiscoveryRunner | undefined;
112
+ /**
113
+ * `catalogHash` — the approved resolution of the design's underspecified
114
+ * "catalog hash": `sha256` over the sorted `(name, description, searchHint)`
115
+ * triples of the eligible pool. A registration, an unload, or a description
116
+ * edit changes it, which invalidates every cached judgment (§ "Lifecycle,
117
+ * cache, and failure handling": "Candidate activation, registration, unload, or
118
+ * a limit change alters the key").
119
+ * @param candidates - the eligible pool.
120
+ * @returns an opaque `sha256:…` digest.
121
+ */
122
+ export declare function catalogHashOf(candidates: readonly DiscoveryCandidate[]): string;
123
+ /**
124
+ * `admissionHash` — the approved resolution of the design's underspecified
125
+ * "admission hash": `sha256` over the sorted `(name, isAdmitted)` pairs of the
126
+ * pool. The pool only holds admitted entries, so this pins the permission
127
+ * verdict the judgment was made under; a restriction applied during the
128
+ * judgment changes the pool and discards it at step 9.
129
+ * @param candidates - the eligible pool.
130
+ * @param entries - the snapshot the pool was built from (the verdict source).
131
+ * @returns an opaque `sha256:…` digest.
132
+ */
133
+ export declare function admissionHashOf(candidates: readonly DiscoveryCandidate[], entries: readonly DeferredEntry[]): string;
134
+ /**
135
+ * The judgment-shaping thresholds, camelCase, for the cache key (§ "Settings").
136
+ * The two cache knobs are deliberately absent: they govern reuse, not what a
137
+ * judgment means.
138
+ */
139
+ export declare function thresholdsOf(settings: DiscoverySettings): DiscoveryThresholds;
140
+ /** Whether two identities agree on ALL SEVEN fields (§ "File responsibilities"). */
141
+ export declare function sameIdentity(left: DiscoveryRouteIdentity, right: DiscoveryRouteIdentity): boolean;
142
+ /** Whether two metering scopes agree: a different scope is a different judgment. */
143
+ export declare function sameScope(left: DiscoveryScope, right: DiscoveryScope): boolean;
144
+ //# sourceMappingURL=discovery-contract.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"discovery-contract.d.ts","sourceRoot":"","sources":["../src/discovery-contract.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAGH,OAAO,KAAK,EACV,aAAa,EACb,eAAe,EACf,kBAAkB,EAClB,iBAAiB,EACjB,sBAAsB,EACtB,iBAAiB,EAClB,MAAM,gBAAgB,CAAA;AACvB,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,sBAAsB,CAAA;AAE/D,8EAA8E;AAC9E,MAAM,MAAM,cAAc,GAAG,MAAM,CAAA;AAEnC;;;;GAIG;AACH,MAAM,WAAW,cAAc;IAC7B,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAA;IAC3B,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAA;IAC1B,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAA;IACxB,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAA;CAC3B;AAED,oDAAoD;AACpD,MAAM,MAAM,kBAAkB,GAAG,QAAQ,CAAC,MAAM,CAAC,MAAM,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,CAAC,SAAS,CAAC,EAAE,MAAM,GAAG,cAAc,CAAA;IACzC,GAAG,CAAC,OAAO,EAAE,wBAAwB,GAAG,OAAO,CAAC,oBAAoB,CAAC,CAAA;CACtE;AAED;;;;GAIG;AACH,MAAM,WAAW,iBAAiB;IAChC,QAAQ,CAAC,kBAAkB,CAAC,EAAE;QAAE,QAAQ,CAAC,KAAK,EAAE,cAAc,GAAG,eAAe,CAAA;KAAE,CAAA;IAClF,QAAQ,CAAC,oBAAoB,CAAC,EAAE;QAAE,QAAQ,CAAC,KAAK,EAAE,cAAc,GAAG,eAAe,CAAA;KAAE,CAAA;IACpF,uEAAuE;IACvE,GAAG,CAAC,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAA;CAC5B;AAQD;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,wBAAgB,kBAAkB,CAChC,IAAI,EAAE,iBAAiB,GACtB,CAAC,KAAK,EAAE,cAAc,KAAK,eAAe,GAAG,SAAS,CAqBxD;AAYD;;;;;;;;;GASG;AACH,wBAAgB,aAAa,CAAC,UAAU,EAAE,SAAS,kBAAkB,EAAE,GAAG,MAAM,CAE/E;AAED;;;;;;;;;GASG;AACH,wBAAgB,eAAe,CAC7B,UAAU,EAAE,SAAS,kBAAkB,EAAE,EACzC,OAAO,EAAE,SAAS,aAAa,EAAE,GAChC,MAAM,CAGR;AAED;;;;GAIG;AACH,wBAAgB,YAAY,CAAC,QAAQ,EAAE,iBAAiB,GAAG,mBAAmB,CAY7E;AAED,oFAAoF;AACpF,wBAAgB,YAAY,CAAC,IAAI,EAAE,sBAAsB,EAAE,KAAK,EAAE,sBAAsB,GAAG,OAAO,CAQjG;AAED,oFAAoF;AACpF,wBAAgB,SAAS,CAAC,IAAI,EAAE,cAAc,EAAE,KAAK,EAAE,cAAc,GAAG,OAAO,CAK9E"}
@@ -0,0 +1,144 @@
1
+ /**
2
+ * The structural boundary between tool discovery and S1-02's decision runtime:
3
+ * the request/response faces it consumes, the host resolver seam, and the two
4
+ * snapshot digests that pin a judgment to a catalog and an admission set.
5
+ *
6
+ * Design: `docs/plans/2026-11-02-systemone-05-tool-discovery.md`
7
+ * § "File responsibilities" (the runner comes from the optional
8
+ * `ctx.systemoneDecisions` service; re-read the identity after every await and
9
+ * compare all fields), § "Inputs, questions, and output", § "Lifecycle, cache,
10
+ * and failure handling" (what the cache key pins).
11
+ *
12
+ * These interfaces are declared STRUCTURALLY — exactly as `discovery.ts`
13
+ * declares the question and answer shapes — so `@dsh-cc/tool-search` never takes
14
+ * a dependency on the SystemOne client: the host passes its real
15
+ * `BoundDecisionRunner`/`DecisionRun` through these seams unchanged.
16
+ *
17
+ * @module @dsh-cc/tool-search/discovery-contract
18
+ */
19
+ import { createHash } from 'node:crypto';
20
+ /** The service shape both names must carry to be usable. */
21
+ function isRunnerService(value) {
22
+ return typeof value === 'object' && value !== null
23
+ && typeof value.forAgent === 'function';
24
+ }
25
+ /**
26
+ * The default runner resolver: read the optional host service and bind it to
27
+ * the calling actor. Never throws — a service that refuses to bind is
28
+ * "unavailable", not a failed search.
29
+ *
30
+ * Resolution order (issue #359: tool-search is mounted at the bundle layer,
31
+ * the ROOT realm, where the isolate-scoped `systemoneDecisions` name has no
32
+ * implementation — the root-realm bridge `ccSystemoneDecisions`, published by
33
+ * `@dsh-cc/decision-usage` for exactly such out-of-group consumers, is the
34
+ * production landing):
35
+ *
36
+ * 1. `host.get('systemoneDecisions')` — the isolated name, so in-group hosts
37
+ * bind their OWN tree's instance (a second preset tree can overwrite the
38
+ * root bridge while each tree keeps its isolated service).
39
+ * 2. `host.get('ccSystemoneDecisions')` — the root-realm bridge.
40
+ * 3. Property fallbacks — the pre-bridge behavior, for structural hosts
41
+ * without a `get` seam.
42
+ *
43
+ * Each step is individually guarded: a throw (an isolate name crossing
44
+ * realms), an `undefined` result (no implementation in this realm's store) or
45
+ * a wrong-shaped value degrades to the NEXT step, never aborts resolution.
46
+ * @param host - the host context face (structurally the cordis context).
47
+ * @returns the resolver handed to `createDiscoveryRuntime`.
48
+ */
49
+ export function hostRunnerResolver(host) {
50
+ const viaGet = (name) => {
51
+ try {
52
+ const service = host.get?.(name);
53
+ return isRunnerService(service) ? service : undefined;
54
+ }
55
+ catch {
56
+ return undefined;
57
+ }
58
+ };
59
+ return (actor) => {
60
+ const service = viaGet('systemoneDecisions')
61
+ ?? viaGet('ccSystemoneDecisions')
62
+ ?? (isRunnerService(host.systemoneDecisions) ? host.systemoneDecisions : undefined)
63
+ ?? (isRunnerService(host.ccSystemoneDecisions) ? host.ccSystemoneDecisions : undefined);
64
+ if (service === undefined)
65
+ return undefined;
66
+ try {
67
+ return service.forAgent(actor);
68
+ }
69
+ catch {
70
+ return undefined;
71
+ }
72
+ };
73
+ }
74
+ /** Total deterministic digest: `sha256:` over the JSON of the value. */
75
+ function digest(value) {
76
+ return `sha256:${createHash('sha256').update(JSON.stringify(value)).digest('hex')}`;
77
+ }
78
+ /** Name-ascending order, the id order {@link buildEligiblePool} assigns. */
79
+ function byName(left, right) {
80
+ return left.name.localeCompare(right.name);
81
+ }
82
+ /**
83
+ * `catalogHash` — the approved resolution of the design's underspecified
84
+ * "catalog hash": `sha256` over the sorted `(name, description, searchHint)`
85
+ * triples of the eligible pool. A registration, an unload, or a description
86
+ * edit changes it, which invalidates every cached judgment (§ "Lifecycle,
87
+ * cache, and failure handling": "Candidate activation, registration, unload, or
88
+ * a limit change alters the key").
89
+ * @param candidates - the eligible pool.
90
+ * @returns an opaque `sha256:…` digest.
91
+ */
92
+ export function catalogHashOf(candidates) {
93
+ return digest([...candidates].sort(byName).map(candidate => [candidate.name, candidate.description, candidate.searchHint ?? null]));
94
+ }
95
+ /**
96
+ * `admissionHash` — the approved resolution of the design's underspecified
97
+ * "admission hash": `sha256` over the sorted `(name, isAdmitted)` pairs of the
98
+ * pool. The pool only holds admitted entries, so this pins the permission
99
+ * verdict the judgment was made under; a restriction applied during the
100
+ * judgment changes the pool and discards it at step 9.
101
+ * @param candidates - the eligible pool.
102
+ * @param entries - the snapshot the pool was built from (the verdict source).
103
+ * @returns an opaque `sha256:…` digest.
104
+ */
105
+ export function admissionHashOf(candidates, entries) {
106
+ const admitted = new Map(entries.map(entry => [entry.name, entry.admitted]));
107
+ return digest([...candidates].sort(byName).map(candidate => [candidate.name, admitted.get(candidate.name) === true]));
108
+ }
109
+ /**
110
+ * The judgment-shaping thresholds, camelCase, for the cache key (§ "Settings").
111
+ * The two cache knobs are deliberately absent: they govern reuse, not what a
112
+ * judgment means.
113
+ */
114
+ export function thresholdsOf(settings) {
115
+ return {
116
+ timeoutMs: settings.timeoutMs,
117
+ maxInputTokens: settings.maxInputTokens,
118
+ maxCandidates: settings.maxCandidates,
119
+ batchSize: settings.batchSize,
120
+ maxQueryChars: settings.maxQueryChars,
121
+ maxMetadataChars: settings.maxMetadataChars,
122
+ minRelevanceIndex: settings.minRelevanceIndex,
123
+ minDirectFit: settings.minDirectFit,
124
+ maxActivations: settings.maxActivations,
125
+ };
126
+ }
127
+ /** Whether two identities agree on ALL SEVEN fields (§ "File responsibilities"). */
128
+ export function sameIdentity(left, right) {
129
+ return left.provider === right.provider
130
+ && left.model === right.model
131
+ && left.revision === right.revision
132
+ && left.perRequestTokens === right.perRequestTokens
133
+ && left.perQuestionTokens === right.perQuestionTokens
134
+ && left.maxQuestions === right.maxQuestions
135
+ && left.maxOutputTokens === right.maxOutputTokens;
136
+ }
137
+ /** Whether two metering scopes agree: a different scope is a different judgment. */
138
+ export function sameScope(left, right) {
139
+ return left.projectKey === right.projectKey
140
+ && left.sessionId === right.sessionId
141
+ && left.agentId === right.agentId
142
+ && left.originSeq === right.originSeq;
143
+ }
144
+ //# sourceMappingURL=discovery-contract.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"discovery-contract.js","sourceRoot":"","sources":["../src/discovery-contract.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAA;AAiFxC,4DAA4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,CAAC,SAAS;QAC7B,aAAa,EAAE,QAAQ,CAAC,aAAa;QACrC,gBAAgB,EAAE,QAAQ,CAAC,gBAAgB;QAC3C,iBAAiB,EAAE,QAAQ,CAAC,iBAAiB;QAC7C,YAAY,EAAE,QAAQ,CAAC,YAAY;QACnC,cAAc,EAAE,QAAQ,CAAC,cAAc;KACxC,CAAA;AACH,CAAC;AAED,oFAAoF;AACpF,MAAM,UAAU,YAAY,CAAC,IAA4B,EAAE,KAA6B;IACtF,OAAO,IAAI,CAAC,QAAQ,KAAK,KAAK,CAAC,QAAQ;WAClC,IAAI,CAAC,KAAK,KAAK,KAAK,CAAC,KAAK;WAC1B,IAAI,CAAC,QAAQ,KAAK,KAAK,CAAC,QAAQ;WAChC,IAAI,CAAC,gBAAgB,KAAK,KAAK,CAAC,gBAAgB;WAChD,IAAI,CAAC,iBAAiB,KAAK,KAAK,CAAC,iBAAiB;WAClD,IAAI,CAAC,YAAY,KAAK,KAAK,CAAC,YAAY;WACxC,IAAI,CAAC,eAAe,KAAK,KAAK,CAAC,eAAe,CAAA;AACrD,CAAC;AAED,oFAAoF;AACpF,MAAM,UAAU,SAAS,CAAC,IAAoB,EAAE,KAAqB;IACnE,OAAO,IAAI,CAAC,UAAU,KAAK,KAAK,CAAC,UAAU;WACtC,IAAI,CAAC,SAAS,KAAK,KAAK,CAAC,SAAS;WAClC,IAAI,CAAC,OAAO,KAAK,KAAK,CAAC,OAAO;WAC9B,IAAI,CAAC,SAAS,KAAK,KAAK,CAAC,SAAS,CAAA;AACzC,CAAC"}
@@ -0,0 +1,137 @@
1
+ /**
2
+ * The asynchronous orchestration of S1-05 tool discovery: settings gate, pool
3
+ * snapshot, route identity, cache key, sequential batch execution, post-await
4
+ * revalidation, and the shadow/active publication rules.
5
+ *
6
+ * Design: `docs/plans/2026-11-02-systemone-05-tool-discovery.md`
7
+ * § "File responsibilities", § "Inputs, questions, and output",
8
+ * § "Deterministic execution order" (the ten numbered steps referenced below),
9
+ * § "Lifecycle, cache, and failure handling" (the shadow/active fallback table).
10
+ *
11
+ * This module is its own file (an approved deviation from the design's file
12
+ * table, which names only the policy, settings and cache modules): the
13
+ * orchestration is a state machine of its own size and `index.ts` sits at the
14
+ * repo's per-file budget. It owns no registry, no settings and no cache state —
15
+ * every host fact arrives through {@link DiscoveryRuntimeDeps}, so the policy,
16
+ * the settings table and the cache stay independently testable. The structural
17
+ * S1-02 faces and the snapshot digests live in `discovery-contract.ts`.
18
+ *
19
+ * `evaluate()` is TOTAL: it never throws and never rejects. Every fault maps
20
+ * onto a {@link DiscoveryEvaluation}, because the caller is a tool body that
21
+ * must always render something for the model.
22
+ *
23
+ * @module @dsh-cc/tool-search/discovery-runtime
24
+ */
25
+ import type { DeferredEntry, DiscoveryScoredItem, DiscoverySettings } from './discovery.ts';
26
+ import type { DiscoveryCache } from './discovery-cache.ts';
27
+ import type { DiscoveryActor, DiscoveryHostFace, DiscoveryRunner } from './discovery-contract.ts';
28
+ /**
29
+ * Why the feature made no judgment and the original lexical path ran (§
30
+ * "Lifecycle, cache, and failure handling": one row per reason).
31
+ *
32
+ * - `off` — `mode: off`: zero runner calls.
33
+ * - `exact` — the trimmed query names a visible admitted candidate (step 2);
34
+ * shadow keeps the original lexical result.
35
+ * - `shadow` — a complete shadow judgment was tallied; the caller executes the
36
+ * original lexical hits.
37
+ * - `bounds` — the pool or a group broke a hard bound (steps 4 and 5): the
38
+ * judgment is abandoned as a whole, never truncated.
39
+ * - `unavailable` — no actor, no runner, no route, or the runner refused
40
+ * (budget, unconfigured, transport error): steps 1 and 6.
41
+ * - `stale` — the route identity, scope, settings mode, catalog or admission
42
+ * changed across an await (steps 6 and 9): the judgment is discarded.
43
+ * - `incomplete` — a batch answered without a usable answer for every question,
44
+ * or the shared deadline was spent: nothing partial is published.
45
+ * - `invalid` — the settings section is invalid: no runner call (§ "Settings").
46
+ */
47
+ export type DiscoveryFallbackReason = 'off' | 'exact' | 'shadow' | 'bounds' | 'unavailable' | 'stale' | 'incomplete' | 'invalid';
48
+ /**
49
+ * What one evaluation decided. `selected` means "activate exactly these names,
50
+ * in this order" — the design's `DiscoveryResult.selected` minus `decisionIds`,
51
+ * because the runner that owns a decision mints those and this package keeps no
52
+ * second decision ledger. `cancelled` means the caller left: no activation of
53
+ * any kind and no lexical backfill (§ "Lifecycle, cache, and failure handling").
54
+ */
55
+ export type DiscoveryEvaluation = {
56
+ readonly kind: 'selected';
57
+ readonly names: readonly string[];
58
+ } | {
59
+ readonly kind: 'lexical';
60
+ readonly reason: DiscoveryFallbackReason;
61
+ } | {
62
+ readonly kind: 'cancelled';
63
+ };
64
+ /**
65
+ * A complete, fully validated judgment: the ONLY value the cache stores. It
66
+ * holds the scored candidates rather than the caller's final name list, because
67
+ * `max_results` is deliberately NOT part of the cache key — each waiter applies
68
+ * its own cap at publish time (§ "Lifecycle, cache, and failure handling").
69
+ */
70
+ export interface DiscoveryJudgment {
71
+ readonly kind: 'selected';
72
+ readonly scored: readonly DiscoveryScoredItem[];
73
+ }
74
+ /**
75
+ * In-memory shadow counters (§ "Release gates and rollback": shadow accumulates
76
+ * hit-set differences and counts — never queries, candidate names or answers).
77
+ */
78
+ export interface DiscoveryShadowCounters {
79
+ /** Complete judgments tallied. */
80
+ readonly judgments: number;
81
+ /** Judgments whose suggested set differed from the lexical hit set. */
82
+ readonly differing: number;
83
+ /** Names suggested but not among the lexical hits. */
84
+ readonly suggestedOnly: number;
85
+ /** Lexical hits the judgment did not suggest. */
86
+ readonly lexicalOnly: number;
87
+ }
88
+ /**
89
+ * Host dependencies: every fact about the registry arrives through these.
90
+ * `S` is the calling scope token the host uses to address its deferred layers
91
+ * (a `ScopeKey` for the tool-search registry); this module never interprets it.
92
+ */
93
+ export interface DiscoveryRuntimeDeps<S = unknown> {
94
+ /** Live settings reader; `undefined` = invalid configuration (step 1 gate). */
95
+ readonly readSettings: () => DiscoverySettings | undefined;
96
+ /** Scope-visible deferred snapshot with lexical scores (steps 3 and 9). */
97
+ readonly snapshotEntries: (query: string, scope: S | undefined) => readonly DeferredEntry[];
98
+ /** Bound runner for the calling actor; absent is `unavailable`. */
99
+ readonly resolveRunner?: (actor: DiscoveryActor) => DiscoveryRunner | undefined;
100
+ /** Host service face the default resolver reads. */
101
+ readonly host?: DiscoveryHostFace;
102
+ /** The fiber's cache, built from the settings table at mount; cleared on unload. */
103
+ readonly cache: DiscoveryCache<DiscoveryJudgment>;
104
+ /** Operator-facing warn sink for genuine faults, never on the hot path. */
105
+ readonly warn?: (message: string) => void;
106
+ /** Clock, injectable for tests; defaults to `Date.now`. */
107
+ readonly now?: () => number;
108
+ }
109
+ /** One evaluation request: the caller's query, cap, actor and cancellation. */
110
+ export interface DiscoveryEvaluateInput<S = unknown> {
111
+ readonly query: string;
112
+ readonly maxResults: number;
113
+ /** The calling actor (an `Agent`); absent ⇒ no decision-service binding. */
114
+ readonly actor?: DiscoveryActor | undefined;
115
+ /** The calling registry scope whose deferred layers are judged. */
116
+ readonly scope?: S | undefined;
117
+ /** The caller's own cancellation signal. */
118
+ readonly signal?: AbortSignal | undefined;
119
+ /** The lexical hit names, for the shadow tally only. */
120
+ readonly lexicalNames: readonly string[];
121
+ }
122
+ /** The runtime face the tool wiring holds. */
123
+ export interface DiscoveryRuntime<S = unknown> {
124
+ /** Judge one query. Total: never throws (§ module note). */
125
+ evaluate(input: DiscoveryEvaluateInput<S>): Promise<DiscoveryEvaluation>;
126
+ /** Shadow counters snapshot (in-memory, counts only). */
127
+ shadow(): DiscoveryShadowCounters;
128
+ /** Clear the cache and abort in-flight runs (plugin unload, rollback). */
129
+ clear(): void;
130
+ }
131
+ /**
132
+ * Create the discovery runtime for one plugin fiber.
133
+ * @param deps - host seams (settings, registry snapshot, runner, cache).
134
+ * @returns the runtime the tool body calls.
135
+ */
136
+ export declare function createDiscoveryRuntime<S>(deps: DiscoveryRuntimeDeps<S>): DiscoveryRuntime<S>;
137
+ //# sourceMappingURL=discovery-runtime.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":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