dsh-project-mcp 0.2.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.
@@ -0,0 +1,1632 @@
1
+ /**
2
+ * Session-scoped activation of the MCP tools a project mounts.
3
+ *
4
+ * A project can declare a large MCP surface, and a model request must not carry
5
+ * every tool the project owns. This module keeps the *presentation* list small
6
+ * without touching the registry:
7
+ *
8
+ * - the usage counters seed a **baseline** of tools the project actually calls
9
+ * ({@link seedFromUsage}) — they are offered directly from the first step on;
10
+ * - the newest task text ranks the project's mounted tools with BM25, and the
11
+ * best matches are offered through a **sticky window** that holds one offered
12
+ * set across several steps ({@link advanceAutoOffer});
13
+ * - the rest are discovered through the `mcp_search_tools` tool this module
14
+ * registers in the agent scope, which **activates** the matches for the next
15
+ * step ({@link activate});
16
+ * - a tool that is never called falls out again ({@link pruneIdle}), and a
17
+ * compaction ends the session's activations while the counter baseline stays
18
+ * ({@link onCompaction});
19
+ * - the agent's own `system-prompt/assemble` listener puts the active schemas
20
+ * back into the assembled request ({@link withActiveTools}).
21
+ *
22
+ * Everything the registry owns stays untouched: no tool is unregistered and no
23
+ * restriction is installed (`ctx.tools.restrict()` cannot hide a scope-local
24
+ * registration anyway — exactly where mcp-client registers its tools). The
25
+ * listener only *adds* schemas to an assembly it did not author, and it is
26
+ * contained: a failure of this plugin's own work returns the continuation's
27
+ * value unchanged.
28
+ *
29
+ * The module is import-free of `@deepseek-ai/dsh-tools` on purpose: that peer is
30
+ * not installed in every deployment, so the registry, definition and schema
31
+ * surfaces are described by the minimal structural types below.
32
+ *
33
+ * @module dsh-project-mcp/activation
34
+ */
35
+
36
+ import { DEFAULT_TOOL_POLICY } from './types.ts'
37
+ import type { OfferedTool, ServerUsage, SessionTools, ToolPolicy } from './types.ts'
38
+
39
+ /** `true` while the session may offer MCP tools through search + activation. */
40
+ export const DEFAULT_ACTIVATION_ENABLED = true
41
+
42
+ /** Tools seeded into the baseline from the durable counters. */
43
+ export const DEFAULT_ACTIVATION_SEEDED = 8
44
+
45
+ /** Calls one tool needs in the counters before it is seeded. */
46
+ export const DEFAULT_ACTIVATION_MIN_CALLS = 5
47
+
48
+ /** How long a session-activated tool survives without a call (`0` disables). */
49
+ export const DEFAULT_TOOL_IDLE_MS = 1_800_000
50
+
51
+ /** Matches one `mcp_search_tools` call activates when it omits `limit`. */
52
+ export const DEFAULT_SEARCH_LIMIT = 8
53
+
54
+ /** Hard cap on matches one `mcp_search_tools` call may activate. */
55
+ export const MAX_SEARCH_LIMIT = 50
56
+
57
+ /**
58
+ * Distinct query words one `mcp_search_tools` call scores at most. A query
59
+ * longer than that is a sentence, and its tail words add noise rather than
60
+ * signal — the first words are the ones the model chose first.
61
+ */
62
+ export const MAX_SEARCH_TOKENS = 8
63
+
64
+ /** Registry name of the discovery tool this module registers. */
65
+ export const SEARCH_TOOL_NAME = 'mcp_search_tools'
66
+
67
+ /** Empty foreign set: what the containment reads when nothing is wired or foreign. */
68
+ const NO_FOREIGN: ReadonlySet<string> = new Set<string>()
69
+
70
+ /**
71
+ * Tools the context-driven tier may offer at once when `activationAutoLimit` is
72
+ * unset; `0` disables the tier.
73
+ */
74
+ export const DEFAULT_AUTO_ACTIVATION_LIMIT = 12
75
+
76
+ /** Hard cap on the context-driven tier, however the config asks for more. */
77
+ export const MAX_AUTO_ACTIVATION_LIMIT = 50
78
+
79
+ /**
80
+ * Extra user messages a context-driven offer survives after the one that ranked
81
+ * it; `0` keeps only that message. The offering set is recomputed when the task
82
+ * context moves, so this is what holds one tool list across several steps.
83
+ */
84
+ export const DEFAULT_AUTO_ACTIVATION_STICKY_STEPS = 2
85
+
86
+ /** Hard cap on the sticky window, however the config asks for more. */
87
+ export const MAX_AUTO_ACTIVATION_STICKY_STEPS = 20
88
+
89
+ /**
90
+ * Serialized size of the MCP surface a session may offer directly before this
91
+ * module defers anything, in characters. Roughly four characters per token, so
92
+ * the default is about 10K tokens: below it the request would carry every
93
+ * mounted tool anyway, and rewriting the prompt prefix to hide a few of them
94
+ * buys nothing and costs the model its cache. `0` disables the gate and defers
95
+ * the whole surface however small it is.
96
+ */
97
+ export const DEFAULT_TOOL_BUDGET_CHARS = 40_000
98
+
99
+ /** BM25 term-frequency saturation. */
100
+ export const BM25_K1 = 1.2
101
+
102
+ /** BM25 document-length normalization. */
103
+ export const BM25_B = 0.75
104
+
105
+ /**
106
+ * Weight one tool-name hit carries over the same hit in the description. A name
107
+ * hit is what a tool *is*, so it outranks a description that merely mentions the
108
+ * term — without the weight a name repeated in a short description and a
109
+ * description-only hit score nearly the same.
110
+ */
111
+ export const BM25_NAME_WEIGHT = 1.5
112
+
113
+ /**
114
+ * Raw BM25 score a tool needs before the context-driven tier may offer it.
115
+ *
116
+ * The floor is what keeps a tool whose name or description shares one incidental
117
+ * word with the task text out of the offered list. A term that stands out in the
118
+ * corpus is worth roughly 1.4 for its first occurrence, one that is merely
119
+ * frequent is worth under 0.3, and a term every tool shares is worth nothing —
120
+ * so the floor sits above the ambient noise a plural or a common verb produces
121
+ * and below a genuine match. Activation through `mcp_search_tools` stays
122
+ * available for anything the floor rejects, and `activationAutoLimit: 0` turns
123
+ * the tier off outright.
124
+ */
125
+ export const MIN_AUTO_SCORE = 0.6
126
+
127
+ /** Maximum task-context characters one advance considers (the newest tail wins). */
128
+ export const MAX_AUTO_QUERY_CHARS = 2_000
129
+
130
+ /** Maximum tool names the recent-call history carries between advances. */
131
+ export const MAX_AUTO_RECENT_CALLS = 16
132
+
133
+ /**
134
+ * Minimal structural view of one model-facing tool schema.
135
+ *
136
+ * It is the exact element type of `system-prompt/assemble`'s `tools` list and of
137
+ * `ctx.tools.schemas()`, described locally because `@deepseek-ai/dsh-tools` is a
138
+ * peer this plugin does not import.
139
+ */
140
+ export interface ToolSchemaLike {
141
+ /** Public registry name, eg `mcp__alpha__run`. */
142
+ readonly name: string
143
+ /** Model-facing description. */
144
+ readonly description: string
145
+ /** JSON Schema object arguments. */
146
+ readonly parameters: Record<string, unknown>
147
+ }
148
+
149
+ /** One text block of the model-facing content vocabulary. */
150
+ export interface TextBlockLike {
151
+ /** Always `text`; the only block this module renders. */
152
+ readonly type: 'text'
153
+ /** Human-readable text. */
154
+ readonly text: string
155
+ }
156
+
157
+ /**
158
+ * Minimal structural view of a tool definition as `ctx.tools.register` accepts
159
+ * it. Only the fields this module writes are declared.
160
+ */
161
+ export interface ToolDefinitionLike {
162
+ /** Registry name presented to the model. */
163
+ readonly name: string
164
+ /** Model-facing description. */
165
+ readonly description: string
166
+ /** JSON Schema object arguments. */
167
+ readonly parameters: Record<string, unknown>
168
+ /** Canonical output contract: a schema to validate and a content renderer. */
169
+ readonly output: {
170
+ /** Enforced JSON Schema of the canonical value `execute` returns. */
171
+ readonly schema: Record<string, unknown>
172
+ /**
173
+ * Project the canonical value onto model-facing content.
174
+ * @param args - parsed call arguments.
175
+ * @param value - the validated canonical value.
176
+ * @returns the content blocks the model sees.
177
+ */
178
+ render(args: unknown, value: unknown): readonly TextBlockLike[]
179
+ }
180
+ /**
181
+ * Run one accepted call.
182
+ * @param args - parsed call arguments.
183
+ * @param context - execution identity; unused here.
184
+ * @returns the canonical value declared by `output.schema`.
185
+ */
186
+ execute(args: unknown, context: unknown): Promise<unknown>
187
+ }
188
+
189
+ /** One listener as `ctx.on` accepts it (method syntax keeps parameters bivariant). */
190
+ export type ListenerLike = (...args: never[]) => unknown
191
+
192
+ /**
193
+ * The agent-scoped context slices this module touches. Described structurally so
194
+ * the wiring is testable without a live harness.
195
+ */
196
+ export interface ActivationContextLike {
197
+ /**
198
+ * Register an event listener through the scope; the scope owns its disposal.
199
+ * @param name - event name.
200
+ * @param listener - listener called with the event's dispatch arguments.
201
+ * @param options - `prepend` places the listener outermost in a waterfall.
202
+ * @returns the disposer, or anything the runtime returns for one.
203
+ */
204
+ on(name: string, listener: ListenerLike, options?: { prepend?: boolean }): unknown
205
+ /** The tool registry, through the scope so registrations stay scope-local. */
206
+ readonly tools: {
207
+ /**
208
+ * Register a tool in the calling scope.
209
+ * @param definition - schema and execution.
210
+ * @returns the exact disposer that unregisters the tool.
211
+ */
212
+ register(definition: ToolDefinitionLike): () => void
213
+ }
214
+ }
215
+
216
+ /** The subset of one prompt assembly this module reads and returns. */
217
+ export interface AssemblyLike {
218
+ /** Model-facing tool schemas, already in canonical order. */
219
+ tools: ToolSchemaLike[]
220
+ }
221
+
222
+ /** Handler of the `system-prompt/assemble` waterfall this module installs. */
223
+ export type AssembleListener = (
224
+ assembly: AssemblyLike,
225
+ context: unknown,
226
+ next: () => Promise<AssemblyLike>,
227
+ ) => Promise<AssemblyLike>
228
+
229
+ /**
230
+ * The fields the wiring reads from one appended session event: enough to catch
231
+ * a `compaction/end` and to recover the task text of a committed `user/message`.
232
+ */
233
+ export interface SessionEventLike {
234
+ /** Session event type, eg `compaction/end`. */
235
+ readonly type?: unknown
236
+ /** Event payload, present on every committed event (`event.data`). */
237
+ readonly data?: unknown
238
+ }
239
+
240
+ /**
241
+ * One session's activation state.
242
+ *
243
+ * `baseline` is the counter-seeded set and outlives a compaction; `active` holds
244
+ * the names this session activated through search, each with the epoch
245
+ * milliseconds of its last touch, and is what idle pruning and compaction clear.
246
+ * Both are read-only because every transition returns a new state.
247
+ */
248
+ export interface ActivationState {
249
+ /** Public names the durable counters proved hot; always offered. */
250
+ readonly baseline: ReadonlySet<string>
251
+ /** Session-activated public names mapped to their last touch. */
252
+ readonly active: ReadonlyMap<string, number>
253
+ }
254
+
255
+ /**
256
+ * Build one session's state.
257
+ * @param baseline - counter-seeded public names; defaults to none.
258
+ * @returns an empty active set over that baseline.
259
+ */
260
+ export function createActivationState(baseline: Iterable<string> = []): ActivationState {
261
+ return { baseline: new Set(baseline), active: new Map() }
262
+ }
263
+
264
+ /** How {@link seedFromUsage} reads the durable counters. */
265
+ export interface SeedOptions {
266
+ /** Maximum names seeded; `0` seeds none. */
267
+ readonly count: number
268
+ /** Calls one tool needs before it is seeded. */
269
+ readonly minCalls: number
270
+ }
271
+
272
+ /**
273
+ * Seed the baseline from a project's durable counters.
274
+ *
275
+ * The counters key tools by the name the server declares them under and servers
276
+ * by `serverName`, so the public registry name is the `mcp__<server>` prefix plus
277
+ * the tool key — the same reconstruction the counter's own attribution relies
278
+ * on. A name the registry had to truncate cannot be reversed this way; such a
279
+ * tool is simply not seeded, which is why the search tool stays the discovery
280
+ * path of record.
281
+ *
282
+ * @param usage - counters of one project, or `undefined` when none were recorded.
283
+ * @param options - seed cap and per-tool minimum.
284
+ * @returns the baseline names, most-called first (name order breaks ties).
285
+ */
286
+ export function seedFromUsage(
287
+ usage: Record<string, ServerUsage> | undefined,
288
+ options: SeedOptions,
289
+ ): Set<string> {
290
+ const baseline = new Set<string>()
291
+ if (usage === undefined || options.count <= 0) return baseline
292
+ const candidates: { name: string; calls: number }[] = []
293
+ for (const [server, serverUsage] of Object.entries(usage)) {
294
+ for (const [tool, calls] of Object.entries(serverUsage.tools)) {
295
+ if (calls < options.minCalls) continue
296
+ candidates.push({ name: `mcp__${server}__${tool}`, calls })
297
+ }
298
+ }
299
+ candidates.sort((left, right) => right.calls - left.calls || compareNames(left.name, right.name))
300
+ for (const candidate of candidates.slice(0, options.count)) baseline.add(candidate.name)
301
+ return baseline
302
+ }
303
+
304
+ /**
305
+ * Activate names for this session, idempotently.
306
+ *
307
+ * A baseline name is skipped: it is already offered, so tracking it in the
308
+ * session set would only make a compaction look like it changed something.
309
+ *
310
+ * @param state - activation state before the activation.
311
+ * @param names - public names activated (already filtered to this plugin's mounts).
312
+ * @param at - epoch milliseconds of the activation.
313
+ * @returns the updated state, or the input when nothing changed.
314
+ */
315
+ export function activate(
316
+ state: ActivationState,
317
+ names: Iterable<string>,
318
+ at: number,
319
+ ): ActivationState {
320
+ let active: Map<string, number> | undefined
321
+ for (const name of names) {
322
+ if (state.baseline.has(name)) continue
323
+ if (state.active.get(name) === at) continue
324
+ active ??= new Map(state.active)
325
+ active.set(name, at)
326
+ }
327
+ return active === undefined ? state : { baseline: state.baseline, active }
328
+ }
329
+
330
+ /**
331
+ * Refresh the freshness of a tool the session actually called. A call is what
332
+ * keeps a session-activated tool offered; a name that is not active (a baseline
333
+ * tool, or a tool the model called by name without activating it) is untouched.
334
+ *
335
+ * @param state - activation state before the call.
336
+ * @param name - public name of the called tool.
337
+ * @param at - epoch milliseconds of the call.
338
+ * @returns the updated state, or the input when nothing changed.
339
+ */
340
+ export function noteUse(state: ActivationState, name: string, at: number): ActivationState {
341
+ const previous = state.active.get(name)
342
+ if (previous === undefined || previous === at) return state
343
+ const active = new Map(state.active)
344
+ active.set(name, at)
345
+ return { baseline: state.baseline, active }
346
+ }
347
+
348
+ /**
349
+ * Drop the session-activated tools that have not been called for `idleMs`.
350
+ * The baseline is never pruned: it comes from the durable counters, not from the
351
+ * session. `idleMs <= 0` disables pruning.
352
+ *
353
+ * @param state - activation state at `now`.
354
+ * @param now - epoch milliseconds of the sweep.
355
+ * @param idleMs - age at which a tool falls out.
356
+ * @returns the updated state, or the input when nothing was stale.
357
+ */
358
+ export function pruneIdle(state: ActivationState, now: number, idleMs: number): ActivationState {
359
+ if (idleMs <= 0 || state.active.size === 0) return state
360
+ let active: Map<string, number> | undefined
361
+ for (const [name, at] of state.active) {
362
+ if (now - at < idleMs) continue
363
+ active ??= new Map(state.active)
364
+ active.delete(name)
365
+ }
366
+ return active === undefined ? state : { baseline: state.baseline, active }
367
+ }
368
+
369
+ /**
370
+ * End the session's activations — a compaction rewrote the conversation they
371
+ * belonged to — while keeping the counter baseline.
372
+ * @param state - activation state before the compaction.
373
+ * @returns the updated state, or the input when no session tool was active.
374
+ */
375
+ export function onCompaction(state: ActivationState): ActivationState {
376
+ if (state.active.size === 0) return state
377
+ return { baseline: state.baseline, active: new Map() }
378
+ }
379
+
380
+ /**
381
+ * Every name this session currently offers: the baseline plus the session's own
382
+ * activations.
383
+ * @param state - current activation state.
384
+ * @returns the union; the baseline itself when nothing is session-activated.
385
+ */
386
+ export function presentedNames(state: ActivationState): ReadonlySet<string> {
387
+ if (state.active.size === 0) return state.baseline
388
+ return new Set([...state.baseline, ...state.active.keys()])
389
+ }
390
+
391
+ /**
392
+ * Serialized size of a tool surface, in characters.
393
+ *
394
+ * Counts what a request actually carries per schema — name, description and the
395
+ * JSON form of the parameters — so the number is comparable with
396
+ * {@link DEFAULT_TOOL_BUDGET_CHARS}. Total: a `parameters` value that cannot be
397
+ * serialized (a cycle) contributes nothing instead of throwing.
398
+ *
399
+ * @param schemas - the schemas a session may offer.
400
+ * @returns the summed character count.
401
+ */
402
+ export function surfaceChars(schemas: readonly ToolSchemaLike[]): number {
403
+ let total = 0
404
+ for (const schema of schemas) total += schemaChars(schema)
405
+ return total
406
+ }
407
+
408
+ /**
409
+ * Serialized size of one tool schema, in characters: the same measurement
410
+ * {@link surfaceChars} sums, so a caller that splits a surface into two halves
411
+ * counts each half by one rule.
412
+ *
413
+ * @param schema - one schema a session may offer.
414
+ * @returns its character count.
415
+ */
416
+ function schemaChars(schema: ToolSchemaLike): number {
417
+ return schema.name.length + schema.description.length + serializedLength(schema.parameters)
418
+ }
419
+
420
+ /**
421
+ * Whether one mounted surface is over the deferral budget.
422
+ *
423
+ * This is exactly the gate {@link installActivation} applies before it defers
424
+ * anything, so a reader that reports the decision cannot drift from the
425
+ * listener that makes it: a surface that fits the budget exactly is carried
426
+ * whole, and a budget of `0` disables the comparison so every surface is over
427
+ * it.
428
+ *
429
+ * @param chars - serialized surface size, as {@link surfaceChars} measures it.
430
+ * @param budgetChars - configured budget in characters.
431
+ * @returns `true` when the surface must be handed over on demand.
432
+ */
433
+ export function overToolBudget(chars: number, budgetChars: number): boolean {
434
+ return budgetChars <= 0 || chars > budgetChars
435
+ }
436
+
437
+ /**
438
+ * The model-facing schema of a definition this module built itself, so its own
439
+ * tool can be offered from the assembly listener rather than through the
440
+ * registry alone.
441
+ *
442
+ * @param definition - a registry-ready tool definition.
443
+ * @returns the three fields an assembly carries for it.
444
+ */
445
+ function schemaOf(definition: ToolDefinitionLike): ToolSchemaLike {
446
+ return {
447
+ name: definition.name,
448
+ description: definition.description,
449
+ parameters: definition.parameters,
450
+ }
451
+ }
452
+
453
+ /** `JSON.stringify` length of one value, or `0` when it cannot be serialized. */
454
+ function serializedLength(value: unknown): number {
455
+ try {
456
+ return JSON.stringify(value)?.length ?? 0
457
+ } catch {
458
+ return 0
459
+ }
460
+ }
461
+
462
+ /**
463
+ * Merge the session's active schemas into an already assembled tool list.
464
+ *
465
+ * Total and side-effect free: it copies the base list, never removes or reorders
466
+ * an entry that is already there, and only appends an active schema that the
467
+ * base does not already carry and that `available` actually publishes (a stale
468
+ * baseline name of a server that is no longer mounted is silently skipped).
469
+ * Missing schemas are inserted at their sorted position, so with the canonical
470
+ * (lexicographic) base order DSH produces the result stays sorted; a deployment
471
+ * with a custom `toolOrder` keeps its existing entries exactly where they were.
472
+ *
473
+ * @param baseTools - the assembly's tool list as the inner listeners left it.
474
+ * @param available - live schemas this plugin may offer for the session.
475
+ * @param activeNames - baseline plus session-activated public names.
476
+ * @returns a new list; equal input yields an equal list.
477
+ */
478
+ export function withActiveTools(
479
+ baseTools: readonly ToolSchemaLike[],
480
+ available: readonly ToolSchemaLike[],
481
+ activeNames: ReadonlySet<string>,
482
+ ): ToolSchemaLike[] {
483
+ const result = [...baseTools]
484
+ if (activeNames.size === 0 || available.length === 0) return result
485
+ const present = new Set(result.map((tool) => tool.name))
486
+ const byName = new Map<string, ToolSchemaLike>()
487
+ for (const tool of available) {
488
+ if (!byName.has(tool.name)) byName.set(tool.name, tool)
489
+ }
490
+ const missing: ToolSchemaLike[] = []
491
+ for (const name of activeNames) {
492
+ if (present.has(name)) continue
493
+ const tool = byName.get(name)
494
+ if (tool === undefined) continue
495
+ present.add(name)
496
+ missing.push(tool)
497
+ }
498
+ missing.sort((left, right) => compareNames(left.name, right.name))
499
+ for (const tool of missing) {
500
+ const index = result.findIndex((existing) => compareNames(existing.name, tool.name) > 0)
501
+ if (index === -1) result.push(tool)
502
+ else result.splice(index, 0, tool)
503
+ }
504
+ return result
505
+ }
506
+
507
+ /**
508
+ * The task context one auto-offer decision reads: the newest user-role text the
509
+ * session committed, plus the tools it called since the last decision.
510
+ *
511
+ * A called name is context, never activation. Only names inside `available`
512
+ * — the tools this plugin mounted for the session — can enter the window, so a
513
+ * call to a profile-level or other-project tool cannot smuggle a foreign schema
514
+ * into the request.
515
+ */
516
+ export interface AutoOfferInput {
517
+ /** Newest committed user message text; `''` when the session has none yet. */
518
+ readonly userText: string
519
+ /**
520
+ * Tool names called since the last decision, call order preserved. Repeating
521
+ * the list is safe: a name already inside the window keeps its stamp.
522
+ */
523
+ readonly recentCalls?: readonly string[]
524
+ }
525
+
526
+ /** How the context-driven tier ranks, caps, and holds one decision. */
527
+ export interface AutoOfferOptions {
528
+ /** Maximum names one decision may offer; `0` disables the tier. */
529
+ readonly limit?: number
530
+ /**
531
+ * Extra user messages a name survives after the one that ranked it. One
532
+ * decision runs per new task text, so this is the sticky window width.
533
+ */
534
+ readonly stickySteps?: number
535
+ /** Raw BM25 score a tool needs before it may be offered. */
536
+ readonly minScore?: number
537
+ }
538
+
539
+ /**
540
+ * The context-driven tier's state: a sticky window over the BM25 ranking of the
541
+ * session's available tools.
542
+ *
543
+ * `window` maps a name to the decision that put it there, so a later decision
544
+ * can count how long the name has been offered without renumbering anything.
545
+ * {@link autoPresentedNames} reads the offered set back out. The state is
546
+ * immutable; a decision that changes nothing returns its input object.
547
+ */
548
+ export interface AutoOfferState {
549
+ /** Name -> decision stamp of every name still inside the sticky window. */
550
+ readonly window: ReadonlyMap<string, number>
551
+ }
552
+
553
+ /**
554
+ * One empty context-driven state.
555
+ * @returns a state whose window is empty.
556
+ */
557
+ export function createAutoOfferState(): AutoOfferState {
558
+ return { window: new Map() }
559
+ }
560
+
561
+ /**
562
+ * Split free text into lowercase search tokens.
563
+ *
564
+ * Separators, punctuation and case boundaries all delimit a token, so `runSQL`,
565
+ * `run_sql`, `run-sql` and `mcp__alpha__run` all yield `run`/`sql`/`mcp`/
566
+ * `alpha` as separate terms instead of one opaque blob. A token must hold at
567
+ * least one letter or digit, which drops the punctuation-only pieces.
568
+ *
569
+ * @param text - raw name, description, or task text.
570
+ * @returns the tokens in source order, duplicates kept (BM25 needs term counts).
571
+ */
572
+ export function tokenize(text: string): string[] {
573
+ const tokens: string[] = []
574
+ for (const chunk of text.split(/[^\p{L}\p{N}]+/u)) {
575
+ if (chunk === '') continue
576
+ for (const piece of chunk.split(/(?<=\p{Ll})(?=\p{Lu})|(?<=\p{Lu})(?=\p{Lu}\p{Ll})/u)) {
577
+ if (piece === '') continue
578
+ const token = piece.toLowerCase()
579
+ if (/[\p{L}\p{N}]/u.test(token)) tokens.push(token)
580
+ }
581
+ }
582
+ return tokens
583
+ }
584
+
585
+ /**
586
+ * Rank the available schemas against one task text with BM25.
587
+ *
588
+ * The corpus is each tool's name plus its description; the query is the task
589
+ * text tokenized the same way. The name is repeated so a name hit outweighs a
590
+ * description hit, and the name breaks score ties, so one corpus and query
591
+ * always produce the same list. Candidates below `minScore` are dropped.
592
+ *
593
+ * @param schemas - live schemas this plugin may offer for the session.
594
+ * @param query - task text to rank against.
595
+ * @param limit - maximum names to return.
596
+ * @param minScore - raw BM25 score a candidate needs.
597
+ * @returns the top names, best first, deterministically ordered.
598
+ */
599
+ export function rankToolsByQuery(
600
+ schemas: readonly ToolSchemaLike[],
601
+ query: string,
602
+ limit: number,
603
+ minScore: number,
604
+ ): string[] {
605
+ const queryTokens = [...new Set(tokenize(query))]
606
+ if (queryTokens.length === 0 || limit <= 0 || schemas.length === 0) return []
607
+
608
+ const documents: {
609
+ tool: ToolSchemaLike
610
+ nameTokens: string[]
611
+ descriptionTokens: string[]
612
+ }[] = []
613
+ const nameFrequency = new Map<string, number>()
614
+ const descriptionFrequency = new Map<string, number>()
615
+ let nameLength = 0
616
+ let descriptionLength = 0
617
+ for (const tool of schemas) {
618
+ const description = typeof tool.description === 'string' ? tool.description : ''
619
+ const nameTokens = tokenize(tool.name)
620
+ const descriptionTokens = tokenize(description)
621
+ documents.push({ tool, nameTokens, descriptionTokens })
622
+ nameLength += nameTokens.length
623
+ descriptionLength += descriptionTokens.length
624
+ for (const token of new Set(nameTokens)) nameFrequency.set(token, (nameFrequency.get(token) ?? 0) + 1)
625
+ for (const token of new Set(descriptionTokens)) {
626
+ descriptionFrequency.set(token, (descriptionFrequency.get(token) ?? 0) + 1)
627
+ }
628
+ }
629
+ const averageNameLength = Math.max(nameLength / documents.length, 1)
630
+ const averageDescriptionLength = Math.max(descriptionLength / documents.length, 1)
631
+
632
+ /** One field's BM25 contribution for one query term, matching the term count. */
633
+ const fieldScore = (
634
+ frequency: number,
635
+ tokens: number,
636
+ documentFrequency: number,
637
+ averageLength: number,
638
+ ): number => {
639
+ const inverse = Math.log(
640
+ 1 + (documents.length - documentFrequency + 0.5) / (documentFrequency + 0.5),
641
+ )
642
+ const saturation =
643
+ (frequency * (BM25_K1 + 1)) /
644
+ (frequency + BM25_K1 * (1 - BM25_B + (BM25_B * tokens) / averageLength))
645
+ return inverse * saturation
646
+ }
647
+
648
+ const ranked: { name: string; score: number }[] = []
649
+ for (const document of documents) {
650
+ const nameCounts = countTokens(document.nameTokens)
651
+ const descriptionCounts = countTokens(document.descriptionTokens)
652
+ let score = 0
653
+ for (const token of queryTokens) {
654
+ if (nameCounts.has(token)) {
655
+ score +=
656
+ BM25_NAME_WEIGHT *
657
+ fieldScore(
658
+ nameCounts.get(token) ?? 0,
659
+ document.nameTokens.length,
660
+ nameFrequency.get(token) ?? 0,
661
+ averageNameLength,
662
+ )
663
+ }
664
+ if (descriptionCounts.has(token)) {
665
+ score += fieldScore(
666
+ descriptionCounts.get(token) ?? 0,
667
+ document.descriptionTokens.length,
668
+ descriptionFrequency.get(token) ?? 0,
669
+ averageDescriptionLength,
670
+ )
671
+ }
672
+ }
673
+ if (score < minScore) continue
674
+ ranked.push({ name: document.tool.name, score })
675
+ }
676
+ ranked.sort((left, right) => right.score - left.score || compareNames(left.name, right.name))
677
+ return ranked.slice(0, limit).map((candidate) => candidate.name)
678
+ }
679
+
680
+ /** Term counts of one field, keyed by token. */
681
+ function countTokens(tokens: readonly string[]): Map<string, number> {
682
+ const counts = new Map<string, number>()
683
+ for (const token of tokens) counts.set(token, (counts.get(token) ?? 0) + 1)
684
+ return counts
685
+ }
686
+
687
+ /**
688
+ * Read the newest user-role text out of one committed session event.
689
+ *
690
+ * Only text blocks enter the task context: an image or file block carries no
691
+ * words to rank against, and an event that is not a `user/message` is not task
692
+ * text at all.
693
+ *
694
+ * Neither is a synthetic `user/message`. The same event type carries every
695
+ * plugin-authored context injection — runtime context snapshots, agent
696
+ * instructions, skill catalogues, cron notices — and they are distinguished
697
+ * only by `source.kind` (`plugin` against a human prompt's `user`). Ranking a
698
+ * tool offer against a context snapshot rather than against the task is worse
699
+ * than ranking against nothing, so only a `user` source is accepted. A
700
+ * deployment that injects its own task text as a `plugin` message therefore
701
+ * ranks on the last human turn instead of that injection.
702
+ *
703
+ * @param event - one event as the `session/event` listener receives it.
704
+ * @returns the message text, or `''` when this event carries none.
705
+ */
706
+ export function readUserMessage(event: SessionEventLike): string {
707
+ if (event?.type !== 'user/message' || !isRecord(event.data)) return ''
708
+ const source = event.data.source
709
+ if (!isRecord(source) || source.kind !== 'user') return ''
710
+ const content = event.data.content
711
+ if (!Array.isArray(content)) return ''
712
+ const parts: string[] = []
713
+ for (const block of content) {
714
+ if (!isRecord(block) || block.type !== 'text') continue
715
+ if (typeof block.text === 'string') parts.push(block.text)
716
+ }
717
+ return parts.join('\n').trim()
718
+ }
719
+
720
+ /**
721
+ * Reset the context-driven tier: a compaction rewrote the conversation the
722
+ * offers belonged to, so nothing sticky survives it.
723
+ *
724
+ * @param state - state before the compaction.
725
+ * @returns an empty state, or the input when it was already empty.
726
+ */
727
+ export function resetAutoOffer(state: AutoOfferState): AutoOfferState {
728
+ if (state.window.size === 0) return state
729
+ return createAutoOfferState()
730
+ }
731
+
732
+ /**
733
+ * Bound one task text to the newest {@link MAX_AUTO_QUERY_CHARS} characters.
734
+ *
735
+ * The tail is the part that matters — a long message states its request last —
736
+ * and the bound keeps one very long paste from turning every later ranking pass
737
+ * into a scan of the whole message.
738
+ *
739
+ * @param text - committed user message text.
740
+ * @returns the text unchanged when it is already short enough.
741
+ */
742
+ export function boundTaskText(text: string): string {
743
+ return text.length <= MAX_AUTO_QUERY_CHARS ? text : text.slice(text.length - MAX_AUTO_QUERY_CHARS)
744
+ }
745
+
746
+ /**
747
+ * Advance the context-driven tier by one input: recompute the BM25 ranking and
748
+ * merge it into the sticky window.
749
+ *
750
+ * A name survives for the advance that offered it plus `stickySteps` later
751
+ * advances, instead of falling out the moment its score dips — that is what
752
+ * keeps one tool list across the steps of a turn. An input that offers nothing
753
+ * clears the window: there is nothing to be sticky about. Nothing here reads a
754
+ * clock; the caller decides what one advance is, so the model stays
755
+ * deterministic and testable.
756
+ *
757
+ * @param previous - state before this input.
758
+ * @param input - the session's newest task text and recent calls.
759
+ * @param available - live schemas this plugin may offer for the session.
760
+ * @param options - ranking and window configuration.
761
+ * @returns the next state, or the input state when nothing changed.
762
+ */
763
+ export function advanceAutoOffer(
764
+ previous: AutoOfferState,
765
+ input: AutoOfferInput,
766
+ available: readonly ToolSchemaLike[],
767
+ options: AutoOfferOptions = {},
768
+ ): AutoOfferState {
769
+ const limit = autoOfferLimit(options.limit)
770
+ const stickySteps = autoOfferStickySteps(options.stickySteps)
771
+ const ranked = rankToolsByQuery(available, input.userText, limit, options.minScore ?? MIN_AUTO_SCORE)
772
+ const previousAdvance = currentAdvance(previous)
773
+
774
+ // A called name is context, never activation: only a tool this plugin
775
+ // mounted for the session may enter the window, so a call to a profile-level
776
+ // or other-project tool cannot smuggle a foreign schema into the request.
777
+ const mounted = new Set(available.map((schema) => schema.name))
778
+ const calls: string[] = []
779
+ for (const name of input.recentCalls ?? []) {
780
+ if (name !== '' && mounted.has(name) && !calls.includes(name)) calls.push(name)
781
+ }
782
+ if (ranked.length === 0 && calls.length === 0) {
783
+ const empty = createAutoOfferState()
784
+ return sameAutoOffer(previous, empty) ? previous : empty
785
+ }
786
+
787
+ const advance = previousAdvance + 1
788
+ // The stamp of the oldest advance still offered. A name entered at advance
789
+ // `E` is offered at `E` itself plus the next `stickySteps` advances, so this
790
+ // advance still shows `advance - stickySteps` and drops anything older.
791
+ const firstKeptAdvance = Math.max(advance - stickySteps, 0)
792
+ const window = new Map<string, number>()
793
+ for (const [name, stamp] of previous.window) {
794
+ if (name === AUTO_ADVANCE_KEY || stamp < firstKeptAdvance) continue
795
+ window.set(name, stamp)
796
+ }
797
+ // A name the window already carries keeps the stamp its offer was made with,
798
+ // so being called never shortens an offer; a fresh one is stamped current.
799
+ for (const name of ranked) window.set(name, advance)
800
+ for (const name of calls) {
801
+ if (!window.has(name)) window.set(name, advance)
802
+ }
803
+ window.set(AUTO_ADVANCE_KEY, advance)
804
+
805
+ const next: AutoOfferState = { window }
806
+ return sameAutoOffer(previous, next) ? previous : next
807
+ }
808
+
809
+
810
+
811
+ /**
812
+ * Reserved window key that records the advance the state has reached. A real
813
+ * tool name can never collide with it: registry names are non-empty, and this
814
+ * key is empty. {@link autoPresentedNames} skips it.
815
+ */
816
+ const AUTO_ADVANCE_KEY = ''
817
+
818
+ /** The advance one state has reached; `0` for a state that never advanced. */
819
+ function currentAdvance(state: AutoOfferState): number {
820
+ return state.window.get(AUTO_ADVANCE_KEY) ?? 0
821
+ }
822
+
823
+ /**
824
+ * Every name the context-driven tier currently offers.
825
+ * @param state - current context-driven state.
826
+ * @returns the offered names, in code-unit order.
827
+ */
828
+ export function autoPresentedNames(state: AutoOfferState): ReadonlySet<string> {
829
+ const names = new Set<string>()
830
+ for (const name of state.window.keys()) {
831
+ if (name !== AUTO_ADVANCE_KEY) names.add(name)
832
+ }
833
+ return new Set([...names].sort(compareNames))
834
+ }
835
+
836
+ /**
837
+ * Every name the context-driven tier currently offers, oldest offer first.
838
+ *
839
+ * The window stamps are advances, not clock readings: this state deliberately
840
+ * holds no wall-clock time, so the order is recency in *decisions*. A caller
841
+ * that needs a timestamp cannot read one from here.
842
+ *
843
+ * @param state - current context-driven state.
844
+ * @returns the offered names, ordered by the advance that offered each.
845
+ */
846
+ export function autoOffers(state: AutoOfferState): readonly string[] {
847
+ const entries: { name: string; advance: number }[] = []
848
+ for (const [name, advance] of state.window) {
849
+ if (name === AUTO_ADVANCE_KEY) continue
850
+ entries.push({ name, advance })
851
+ }
852
+ entries.sort((left, right) => left.advance - right.advance || compareNames(left.name, right.name))
853
+ return entries.map((entry) => entry.name)
854
+ }
855
+
856
+ /** Whether two context-driven states describe the same offered set and history. */
857
+ function sameAutoOffer(left: AutoOfferState, right: AutoOfferState): boolean {
858
+ const leftNames = autoPresentedNames(left)
859
+ const rightNames = autoPresentedNames(right)
860
+ if (leftNames.size !== rightNames.size) return false
861
+ for (const name of leftNames) {
862
+ if (!rightNames.has(name)) return false
863
+ }
864
+ return true
865
+ }
866
+
867
+ /**
868
+ * Read the offered-set cap, clamped to the supported range.
869
+ * @param value - configured cap, or `undefined` for the shipped default.
870
+ * @returns the effective cap; `0` disables the context-driven tier.
871
+ */
872
+ export function autoOfferLimit(value: number | undefined): number {
873
+ return Math.min(Math.max(value ?? DEFAULT_AUTO_ACTIVATION_LIMIT, 0), MAX_AUTO_ACTIVATION_LIMIT)
874
+ }
875
+
876
+ /**
877
+ * Read the sticky-window configuration, clamped to the supported range.
878
+ * @param value - configured extra advances, or `undefined` for the shipped default.
879
+ * @returns the effective extra advances; `0` keeps only the current advance.
880
+ */
881
+ export function autoOfferStickySteps(value: number | undefined): number {
882
+ return Math.min(
883
+ Math.max(value ?? DEFAULT_AUTO_ACTIVATION_STICKY_STEPS, 0),
884
+ MAX_AUTO_ACTIVATION_STICKY_STEPS,
885
+ )
886
+ }
887
+
888
+ /**
889
+ * One live session's presentation inputs, read where the session's state lives.
890
+ *
891
+ * Every field is a snapshot-time read: `mounted` is the registry probe the
892
+ * activation wiring itself consumes, and both states are the session's own, so
893
+ * a caller that derives a row again after an activation sees it — nothing here
894
+ * is a copy a later path updates.
895
+ */
896
+ export interface SessionToolInput {
897
+ /** Live agent (session) id the row describes. */
898
+ readonly sessionId: string
899
+ /** Schemas this plugin mounted for the session, as the registry lists them now. */
900
+ readonly mounted: readonly ToolSchemaLike[]
901
+ /** Activation state of the session; absent before its first seed. */
902
+ readonly activation: ActivationState | undefined
903
+ /** Context-driven window of the session; absent before its first advance. */
904
+ readonly auto: AutoOfferState | undefined
905
+ /** `false` when activation is off, so every mounted tool stays in the request. */
906
+ readonly activationEnabled: boolean
907
+ /** Deferral budget in characters; defaults to {@link DEFAULT_TOOL_BUDGET_CHARS}. */
908
+ readonly budgetChars?: number
909
+ /**
910
+ * Tool policy of the session's project; absent means the shipped default,
911
+ * {@link DEFAULT_TOOL_POLICY}. Read at call time like every other field here,
912
+ * so the row follows a pin or a mode change as soon as it is stored.
913
+ */
914
+ readonly policy?: ToolPolicy
915
+ /**
916
+ * Step each session activation was recorded on, keyed by public name, and the
917
+ * step this row is being read on. Both are optional and independent: `steps`
918
+ * stamps the `activated` tier with the step its offer happened on, while
919
+ * `step` stamps the context tier with the step the request belongs to. Absent
920
+ * means the caller counts no steps, and then no tier carries a number — the
921
+ * panel draws no step tag rather than a zero.
922
+ */
923
+ readonly steps?: ReadonlyMap<string, number>
924
+ /** Step this row is read on; see {@link SessionToolInput.steps}. */
925
+ readonly step?: number
926
+ }
927
+
928
+ /**
929
+ * Derive what one session offers the model right now from its live state.
930
+ *
931
+ * The row is a *measurement*, not a decision: `mounted` counts the schemas the
932
+ * caller probed, and `deferred` is exactly the part of that surface the request
933
+ * does not carry, so `deferred.length` is the panel's "hidden" number and the
934
+ * tier lists name why the rest is there. Nothing is cached: the same inputs
935
+ * read after an activation list it.
936
+ *
937
+ * Names of tiers that the session no longer mounts are dropped, because the
938
+ * row describes what is offered, not what once was. The context tier carries no
939
+ * `at`: the live window stamps an advance, not a wall-clock time.
940
+ *
941
+ * The project's policy is read here too, and it decides all three fields. In
942
+ * `disclosure` the row offers the counter baseline and the pins and hides the
943
+ * part of the mounted surface the budget pushed out of the request. `direct`
944
+ * filters nothing, so it hides nothing: `deferring` is `false` and `deferred` is
945
+ * empty however large the surface is. `off` offers none of the project's tools,
946
+ * so every tier of this row is empty and the whole mounted surface is `deferred`
947
+ * — the row reports what *this* plugin contributes, and a project the user
948
+ * switched off contributes nothing, whether or not another presentation plugin
949
+ * leaves the tools visible to the model. Pinned names join the counter baseline,
950
+ * so in `disclosure` and `direct` they are offered from the first step of every
951
+ * request and are never counted as hidden, whatever the counters and the budget
952
+ * say.
953
+ *
954
+ * @param input - live mount, activation, context, config and policy of one session.
955
+ * @returns the presentation row, or `undefined` when the session mounts no tool
956
+ * (a session the host has not turned has nothing to report, and an empty row
957
+ * would claim it offers nothing rather than that its surface is absent).
958
+ */
959
+ export function toolsFor(input: SessionToolInput): SessionTools | undefined {
960
+ const mounted = input.mounted
961
+ if (mounted.length === 0) return undefined
962
+ const mountedNames = new Set(mounted.map((schema) => schema.name))
963
+ const chars = surfaceChars(mounted)
964
+ const budgetChars = input.budgetChars ?? DEFAULT_TOOL_BUDGET_CHARS
965
+ const policy = input.policy ?? DEFAULT_TOOL_POLICY
966
+ // Nothing is hidden while the surface fits: the activation listener leaves the
967
+ // assembly untouched then, so a name a tier would have offered is in the
968
+ // request anyway. Only a surface the gate defers can hide anything — and only
969
+ // `disclosure` defers by size at all: `direct` filters nothing and `off`
970
+ // offers nothing.
971
+ const deferring =
972
+ policy.mode === 'disclosure' && input.activationEnabled && overToolBudget(chars, budgetChars)
973
+ // `off` offers none of the project's tools, so no tier of this row offers one
974
+ // either. The pins stay in the policy and the session keeps its activations —
975
+ // the mode is read again on the next assembly, so switching back finds them —
976
+ // but a row that promises nothing is what makes the whole mounted surface
977
+ // `deferred` below.
978
+ const offersNothing = policy.mode === 'off'
979
+
980
+ // A pin is the user's own always-offered name, so it belongs to the baseline
981
+ // next to the counter-seeded ones. A pinned name the project no longer mounts
982
+ // is not part of this row — but stays pinned in the policy store, so the
983
+ // declaration coming back finds it again.
984
+ const baselineNames = new Set<string>(input.activation?.baseline ?? [])
985
+ for (const pin of policy.pins) baselineNames.add(pin)
986
+ const baseline = offersNothing
987
+ ? []
988
+ : [...baselineNames].filter((name) => mountedNames.has(name)).sort(compareNames)
989
+ // The step an activation was recorded on, when the caller counted one; `0`
990
+ // (or no map at all) is "this host does not count steps", and a tier must then
991
+ // carry no number rather than a zero a panel would draw as a step tag.
992
+ const stepOf = (name: string): number | undefined => {
993
+ const step = input.steps?.get(name)
994
+ return step === undefined || step <= 0 ? undefined : step
995
+ }
996
+ const activated: OfferedTool[] = offersNothing
997
+ ? []
998
+ : [...(input.activation?.active ?? [])]
999
+ .filter(([name]) => mountedNames.has(name))
1000
+ .sort(
1001
+ ([leftName, leftAt], [rightName, rightAt]) =>
1002
+ leftAt - rightAt || compareNames(leftName, rightName),
1003
+ )
1004
+ .map(([name, at]): OfferedTool => {
1005
+ const step = stepOf(name)
1006
+ return { name, via: 'session', at, ...(step === undefined ? {} : { step }) }
1007
+ })
1008
+ // The context tier is a live window, not a record of offers made: the stamp it
1009
+ // carries is the step this row is read on, which is the step the request it
1010
+ // describes belongs to. A caller that counts no steps leaves it absent.
1011
+ const context: OfferedTool[] = offersNothing
1012
+ ? []
1013
+ : (input.auto === undefined ? [] : autoOffers(input.auto))
1014
+ .filter((name) => mountedNames.has(name))
1015
+ .map((name): OfferedTool => ({
1016
+ name,
1017
+ via: 'context',
1018
+ ...(input.step === undefined ? {} : { step: input.step }),
1019
+ }))
1020
+
1021
+ const offered = new Set<string>(baseline)
1022
+ for (const tool of activated) offered.add(tool.name)
1023
+ for (const tool of context) offered.add(tool.name)
1024
+
1025
+ // `off` promises nothing, so the whole mounted surface is what this plugin
1026
+ // does not offer; `direct` filters nothing, so it hides nothing; only
1027
+ // `disclosure` over its budget hides the difference between the two.
1028
+ const deferred =
1029
+ offersNothing
1030
+ ? [...mountedNames].sort(compareNames)
1031
+ : deferring
1032
+ ? [...mountedNames].filter((name) => !offered.has(name)).sort(compareNames)
1033
+ : []
1034
+
1035
+ // The request's own weight, split the way the request is: exactly the names in
1036
+ // `deferred` are the ones the assembly leaves out, so a surface that fits the
1037
+ // budget carries all of it and defers nothing, and what hiding saved is
1038
+ // `surfaceChars - visibleChars`. Both halves are measured with
1039
+ // {@link surfaceChars}, the same rule the budget gate uses, so the numbers
1040
+ // cannot drift from the decision.
1041
+ const deferredNames = new Set(deferred)
1042
+ let visibleChars = 0
1043
+ let deferredChars = 0
1044
+ for (const schema of mounted) {
1045
+ if (deferredNames.has(schema.name)) deferredChars += schemaChars(schema)
1046
+ else visibleChars += schemaChars(schema)
1047
+ }
1048
+
1049
+ return {
1050
+ sessionId: input.sessionId,
1051
+ baseline,
1052
+ activated,
1053
+ context,
1054
+ deferred,
1055
+ mounted: mounted.length,
1056
+ surfaceChars: chars,
1057
+ visibleChars,
1058
+ deferredChars,
1059
+ budgetChars,
1060
+ deferring,
1061
+ }
1062
+ }
1063
+
1064
+ /** Construction options for the `mcp_search_tools` definition. */
1065
+ export interface SearchToolOptions {
1066
+ /** Live schemas the search matches and may activate: the whole visible MCP surface. */
1067
+ readonly available: () => readonly ToolSchemaLike[]
1068
+ /** Record the matched names as activated for the session. */
1069
+ readonly activate: (names: readonly string[]) => void
1070
+ /** Cap applied when a call omits `limit`; defaults to {@link DEFAULT_SEARCH_LIMIT}. */
1071
+ readonly defaultLimit?: number
1072
+ }
1073
+
1074
+ /** One search result: what the model may call directly from the next step on. */
1075
+ interface SearchMatch {
1076
+ readonly name: string
1077
+ readonly description: string
1078
+ }
1079
+
1080
+ /**
1081
+ * Build the `mcp_search_tools` definition.
1082
+ *
1083
+ * The tool never pretends: a query that matches nothing says so, and it only
1084
+ * ever offers schemas its session actually sees (the caller supplies that
1085
+ * filtered list). Activating is enough to present a tool from the *next* step
1086
+ * on, because the assembly listener reads the state at every request.
1087
+ *
1088
+ * @param options - the session's visible schemas and activation sink.
1089
+ * @returns a registry-ready definition.
1090
+ */
1091
+ export function createSearchTool(options: SearchToolOptions): ToolDefinitionLike {
1092
+ const defaultLimit = options.defaultLimit ?? DEFAULT_SEARCH_LIMIT
1093
+ return {
1094
+ name: SEARCH_TOOL_NAME,
1095
+ description:
1096
+ 'Search the MCP tools this session sees and activate every match, so the activated tools are offered directly from the next model step on. Use it when the tool you need is not listed: a tool it activates joins the offered list from the next model step on, and until then only the tools already listed are reliable. `query` matches tool names and descriptions — case-insensitive, each word on its own, so separate keywords (`issue update`) find what a whole sentence does not; `limit` caps how many matches are activated.',
1097
+ parameters: {
1098
+ type: 'object',
1099
+ properties: {
1100
+ query: {
1101
+ type: 'string',
1102
+ description: 'A keyword or name fragment of the needed MCP tool; several words are matched one by one.',
1103
+ },
1104
+ limit: {
1105
+ type: 'integer',
1106
+ description: `Maximum matches to activate; default ${defaultLimit}.`,
1107
+ },
1108
+ },
1109
+ required: ['query'],
1110
+ additionalProperties: false,
1111
+ },
1112
+ output: {
1113
+ // The canonical value is a small JSON object; any of its shapes is valid.
1114
+ schema: {},
1115
+ render: (_args, value) => [{ type: 'text', text: renderJson(value) }],
1116
+ },
1117
+ async execute(args) {
1118
+ const query = readQuery(args)
1119
+ if (query === '') {
1120
+ throw new Error(`${SEARCH_TOOL_NAME}: "query" must be a non-empty string`)
1121
+ }
1122
+ const matches = searchTools(options.available(), query, readLimit(args, defaultLimit))
1123
+ options.activate(matches.map((match) => match.name))
1124
+ return {
1125
+ query,
1126
+ matches,
1127
+ activated: matches.map((match) => match.name),
1128
+ message:
1129
+ matches.length === 0
1130
+ ? `no MCP tool of this project matches ${JSON.stringify(query)}`
1131
+ : `${matches.length} MCP tool(s) match and will be offered from the next step on`,
1132
+ }
1133
+ },
1134
+ }
1135
+ }
1136
+
1137
+ /** What the wiring needs from the runtime; everything is read at use time. */
1138
+ export interface ActivationWiringOptions {
1139
+ /** Agent-scoped context; both the listener and the search tool live here. */
1140
+ readonly ctx: ActivationContextLike
1141
+ /** Current activation state of the session. */
1142
+ readonly state: () => ActivationState
1143
+ /** Replace the session's activation state after a transition. */
1144
+ readonly setState: (next: ActivationState) => void
1145
+ /** Live schemas of the tools this plugin mounted for the session. */
1146
+ readonly available: () => readonly ToolSchemaLike[]
1147
+ /**
1148
+ * Every MCP schema the session sees — the profile plane, this plugin's own
1149
+ * mounts, and any F-19 forwarders — beyond {@link available}. The deferral
1150
+ * budget and the discovery tool count this whole surface, while the
1151
+ * context-driven tier and the usage counters keep reading `available` alone.
1152
+ * Absent means `available` is the whole surface, so a deployment whose
1153
+ * presentation owner already hides the profile plane keeps today's behaviour.
1154
+ */
1155
+ readonly visible?: () => readonly ToolSchemaLike[]
1156
+ /**
1157
+ * Names that belong to ANOTHER project mounted in this process, which this
1158
+ * session must never be offered. The runtime computes the set from the other
1159
+ * projects it manages, and the assembly listener drops every such name from
1160
+ * the assembled request — whatever the tool mode, and however large the
1161
+ * surface. The budget and the discovery tool keep counting the whole visible
1162
+ * surface, so this only trims the final list and never re-feeds the deferral
1163
+ * decision. Absent means nothing is foreign, which keeps a deployment without
1164
+ * the containment probe on today's behaviour.
1165
+ */
1166
+ readonly foreign?: () => ReadonlySet<string>
1167
+ /** Cap on the tools one search activates; defaults to {@link DEFAULT_SEARCH_LIMIT}. */
1168
+ readonly searchLimit?: number
1169
+ /**
1170
+ * Cap on the names the context-driven tier offers at once; defaults to
1171
+ * {@link DEFAULT_AUTO_ACTIVATION_LIMIT}, and `0` disables the tier.
1172
+ */
1173
+ readonly autoLimit?: number
1174
+ /** Extra advances a context offer survives; defaults to {@link DEFAULT_AUTO_ACTIVATION_STICKY_STEPS}. */
1175
+ readonly autoStickySteps?: number
1176
+ /** Lowest BM25 score the context-driven tier may offer; defaults to {@link MIN_AUTO_SCORE}. */
1177
+ readonly autoMinScore?: number
1178
+ /**
1179
+ * Serialized size of the MCP surface, in characters, above which this module
1180
+ * defers tools at all; defaults to {@link DEFAULT_TOOL_BUDGET_CHARS}. `0`
1181
+ * defers every surface, however small.
1182
+ */
1183
+ readonly toolBudgetChars?: number
1184
+ /**
1185
+ * Live tool policy of the session's project; absent means the shipped default,
1186
+ * {@link DEFAULT_TOOL_POLICY}. Read at every assembly, so a mode or pin change
1187
+ * applies from the next step on, without re-minting the scope.
1188
+ */
1189
+ readonly policy?: () => ToolPolicy
1190
+ /**
1191
+ * Number of the agent step this plugin is currently on, counted by the caller
1192
+ * from its own `agent/pre-step` hook. Read when a search activates names, so
1193
+ * the record of that offer carries the step it happened on. Absent means the
1194
+ * caller counts no steps, and then an activation records none.
1195
+ */
1196
+ readonly step?: () => number
1197
+ /**
1198
+ * Told the names one search just activated, and the step it happened on, so
1199
+ * the caller can keep that stamp for the lifetime of the session — longer
1200
+ * than one scope's wiring, which an idle release disposes. Absent drops the
1201
+ * stamp: the offer is still recorded, it simply carries no step.
1202
+ */
1203
+ readonly onActivated?: (names: readonly string[], step: number) => void
1204
+ /**
1205
+ * Told that a compaction ended the session's activations, so the caller can
1206
+ * drop the step records that belong to them. Absent leaves the records in
1207
+ * place, which only means a later activation of the same name may carry the
1208
+ * step of the offer the compaction removed.
1209
+ */
1210
+ readonly onCompaction?: () => void
1211
+ /** Context-driven state to start from; defaults to an empty state. */
1212
+ readonly autoState?: AutoOfferState
1213
+ /** Sink for the context-driven state after every advance that changed it. */
1214
+ readonly setAutoState?: (next: AutoOfferState) => void
1215
+ /** Sink for a contained failure of this plugin's own work. */
1216
+ readonly onError?: (error: unknown) => void
1217
+ }
1218
+
1219
+ /**
1220
+ * The context-driven tier's live inputs, owned by the wiring for one scope.
1221
+ *
1222
+ * `userText` is the newest committed `user/message` and `calls` holds the tool
1223
+ * names called since the last advance; both are read from the events the
1224
+ * harness already dispatches, and `changed` records that the task context moved
1225
+ * since the offered set was last computed.
1226
+ */
1227
+ interface ActivationQueryTracker {
1228
+ /** Context-driven state as of the last advance. */
1229
+ state: AutoOfferState
1230
+ /** Newest committed user-role text, `''` until the session has one. */
1231
+ userText: string
1232
+ /** Tool names called since the last advance, call order preserved. */
1233
+ calls: string[]
1234
+ /** `true` while a committed user message arrived after the last advance. */
1235
+ changed: boolean
1236
+ }
1237
+
1238
+ /**
1239
+ * Install the session wiring on one agent scope: the `system-prompt/assemble`
1240
+ * listener, the `mcp_search_tools` registration, and the `session/event`
1241
+ * listener that feeds compaction, the task context, and the recent-call names.
1242
+ *
1243
+ * The listener is prepended so it is the **outermost** handler of the waterfall:
1244
+ * `next()` has already run every plugin that filters the catalogue (the
1245
+ * `dsh-progressive-tools` presentation this replaces), and the list it returns is
1246
+ * the one that runs. Idle pruning is not wired here — the runtime already
1247
+ * watches `agent/status`, and it calls {@link pruneIdle} on that transition.
1248
+ *
1249
+ * The context-driven tier advances only when the task context actually moves: a
1250
+ * new user message or a new tool call. When it does, and the resulting offered
1251
+ * set is the one the previous advance produced, this returns the identical
1252
+ * assembly object, so nothing downstream treats the tool list as changed.
1253
+ *
1254
+ * @param options - scope, session state accessors, and the mounted-schema probe.
1255
+ * @returns the disposer that unregisters everything installed here.
1256
+ */
1257
+ export function installActivation(options: ActivationWiringOptions): () => void {
1258
+ const tracker: ActivationQueryTracker = {
1259
+ state: options.autoState ?? createAutoOfferState(),
1260
+ userText: '',
1261
+ calls: [],
1262
+ changed: false,
1263
+ }
1264
+
1265
+ /**
1266
+ * Record the step an activation happened on. Owned by the caller, because the
1267
+ * session, not one scope's wiring, is what keeps an activation across an idle
1268
+ * release; this is the only place a search activation happens, so it is the
1269
+ * only place the record can be made.
1270
+ */
1271
+ const recordActivated = (names: readonly string[]): void => {
1272
+ const step = options.step?.() ?? 0
1273
+ if (step > 0) options.onActivated?.(names, step)
1274
+ }
1275
+
1276
+ const dispose = (fn: () => void): void => {
1277
+ try {
1278
+ fn()
1279
+ } catch (error) {
1280
+ options.onError?.(error)
1281
+ }
1282
+ }
1283
+ const listen = (name: string, listener: ListenerLike, prepend: boolean): (() => void) => {
1284
+ const registered = options.ctx.on(name, listener, { prepend })
1285
+ return typeof registered === 'function' ? (registered as () => void) : () => undefined
1286
+ }
1287
+
1288
+ /** Recompute the context-driven offer whenever the task context actually moved. */
1289
+ const advance = (): void => {
1290
+ const calls = tracker.calls
1291
+ tracker.calls = []
1292
+ // Nothing new: the offered set from the previous advance is still current,
1293
+ // so not touching it is what keeps the request prefix byte-identical.
1294
+ if (!tracker.changed && calls.length === 0) return
1295
+ tracker.changed = false
1296
+ if (autoOfferLimit(options.autoLimit) === 0) return
1297
+ const next = advanceAutoOffer(
1298
+ tracker.state,
1299
+ { userText: tracker.userText, recentCalls: calls },
1300
+ options.available(),
1301
+ {
1302
+ ...(options.autoLimit === undefined ? {} : { limit: options.autoLimit }),
1303
+ ...(options.autoStickySteps === undefined ? {} : { stickySteps: options.autoStickySteps }),
1304
+ ...(options.autoMinScore === undefined ? {} : { minScore: options.autoMinScore }),
1305
+ },
1306
+ )
1307
+ if (next === tracker.state) return
1308
+ tracker.state = next
1309
+ options.setAutoState?.(next)
1310
+ }
1311
+
1312
+ /** Every name the session's explicit activation and context-driven tiers offer. */
1313
+ const offeredNames = (): ReadonlySet<string> => {
1314
+ const names = new Set(presentedNames(options.state()))
1315
+ for (const name of autoPresentedNames(tracker.state)) names.add(name)
1316
+ return names
1317
+ }
1318
+
1319
+ /**
1320
+ * Every MCP schema the session sees, as one name-keyed surface: this plugin's
1321
+ * own mounts first, then the profile plane and any F-19 forwarders, each name
1322
+ * once. This plugin's discovery tool is left out by identity — it is added
1323
+ * separately below, so a profile that already lists a tool named
1324
+ * `mcp_search_tools` cannot shadow the one this module mints.
1325
+ */
1326
+ const wholeSurface = (): readonly ToolSchemaLike[] => {
1327
+ const available = options.available()
1328
+ const visible = options.visible?.() ?? []
1329
+ if (visible.length === 0) return available
1330
+ const seen = new Set<string>()
1331
+ const merged: ToolSchemaLike[] = []
1332
+ for (const schema of available) {
1333
+ if (schema.name === SEARCH_TOOL_NAME) continue
1334
+ seen.add(schema.name)
1335
+ merged.push(schema)
1336
+ }
1337
+ for (const schema of visible) {
1338
+ if (schema.name === SEARCH_TOOL_NAME || seen.has(schema.name)) continue
1339
+ seen.add(schema.name)
1340
+ merged.push(schema)
1341
+ }
1342
+ return merged
1343
+ }
1344
+
1345
+ /**
1346
+ * Whether the whole visible MCP surface is large enough to be worth deferring
1347
+ * at all. A surface that already fits the budget is carried whole by the
1348
+ * request, so hiding a few of its tools would rewrite the prompt prefix — and
1349
+ * cost the model its cache — to save nothing. `0` disables the gate.
1350
+ */
1351
+ const deferring = (surface: readonly ToolSchemaLike[]): boolean =>
1352
+ overToolBudget(
1353
+ surfaceChars(surface),
1354
+ options.toolBudgetChars ?? DEFAULT_TOOL_BUDGET_CHARS,
1355
+ )
1356
+
1357
+ /**
1358
+ * Containment: a name another project mounts in this process never reaches the
1359
+ * assembled request, whatever the mode does around it. The set is read fresh on
1360
+ * every assembly, and the whole visible surface the budget measures is
1361
+ * deliberately unchanged — containment trims the final list only, so the
1362
+ * deferral decision still counts a foreign name the host defect leaked into the
1363
+ * session's chain. Absent (or empty) means nothing is foreign, and the
1364
+ * continuation's value comes back by identity.
1365
+ */
1366
+ const contain = (result: AssemblyLike): AssemblyLike => {
1367
+ const foreign = options.foreign?.() ?? NO_FOREIGN
1368
+ if (foreign.size === 0) return result
1369
+ const kept = result.tools.filter((tool) => !foreign.has(tool.name))
1370
+ return kept.length === result.tools.length ? result : { ...result, tools: kept }
1371
+ }
1372
+
1373
+ /**
1374
+ * The visible surface without the names another project's mount leaked into
1375
+ * this session's chain. The discovery catalogue is built from this rather than
1376
+ * from {@link wholeSurface}: a name the session may never be offered must not
1377
+ * come back as text through a search either, or the containment would hand the
1378
+ * foreign catalogue over one step later. The deferral decision still counts the
1379
+ * whole surface, foreign names included — they occupy the request just as
1380
+ * locally mounted ones would.
1381
+ */
1382
+ const searchable = (): readonly ToolSchemaLike[] => {
1383
+ const foreign = options.foreign?.() ?? NO_FOREIGN
1384
+ const surface = wholeSurface()
1385
+ return foreign.size === 0 ? surface : surface.filter((schema) => !foreign.has(schema.name))
1386
+ }
1387
+
1388
+ const merge = (result: AssemblyLike): AssemblyLike => {
1389
+ const surface = wholeSurface()
1390
+ // Nothing is visible: there is nothing to find, so nothing is added.
1391
+ if (surface.length === 0) return contain(result)
1392
+ const policy = options.policy?.() ?? DEFAULT_TOOL_POLICY
1393
+ // `off` promises that the project's tools are not offered, and the promise is
1394
+ // about the request, not only about what the panel says: the project plane
1395
+ // leaves the assembly here. Only this plugin's own mounts go — the profile
1396
+ // plane and other plugins' tools are none of this mode's business — and a pin
1397
+ // does not cancel the mode, so the discovery tool is not advertised either,
1398
+ // because there is nothing it may disclose.
1399
+ if (policy.mode === 'off') {
1400
+ const mounted = options.available()
1401
+ if (mounted.length === 0) return contain(result)
1402
+ const offNames = new Set(mounted.map((schema) => schema.name))
1403
+ const kept = result.tools.filter((tool) => !offNames.has(tool.name))
1404
+ return contain(kept.length === result.tools.length ? result : { ...result, tools: kept })
1405
+ }
1406
+ // `direct` is the opposite promise: the whole visible catalogue is listed, so
1407
+ // the assembly is handed back exactly as the rest of the harness produced it
1408
+ // and the discovery tool is not advertised — except that another project's
1409
+ // tools, which this session must never carry, still leave it.
1410
+ if (policy.mode !== 'disclosure') return contain(result)
1411
+ advance()
1412
+ // The discovery tool is pinned: offered in every disclosure assembly,
1413
+ // whatever the budget says. A surface inside the budget is carried whole —
1414
+ // every mounted tool stays listed — and the search tool is added alongside
1415
+ // them so the model can always discover tools as the project grows. Over
1416
+ // budget, this module does the trimming a presentation owner would
1417
+ // otherwise do: every `mcp__` tool the budget pushed out is dropped, while
1418
+ // the non-MCP tools the inner listeners listed (core tools, other plugins)
1419
+ // are kept. `withActiveTools` inserts the wanted schemas at their sorted
1420
+ // position and never duplicates or reorders an existing entry. Pins are
1421
+ // wanted unconditionally — offered from the first step of every request,
1422
+ // whatever the counters and the budget say — and a pin or activation may
1423
+ // name a profile-plane tool, whose schema is found in `surface` and
1424
+ // re-inserted.
1425
+ const defer = deferring(surface)
1426
+ const wanted = new Set(offeredNames())
1427
+ for (const pin of policy.pins) wanted.add(pin)
1428
+ wanted.add(SEARCH_TOOL_NAME)
1429
+ const kept = defer
1430
+ ? result.tools.filter(
1431
+ (tool) => wanted.has(tool.name) || !tool.name.startsWith('mcp__'),
1432
+ )
1433
+ : result.tools
1434
+ const merged = withActiveTools(kept, [...surface, schemaOf(search)], wanted)
1435
+ // Identity is decided on the list this call produced, never on whether the
1436
+ // names this module wants have changed: the inner listeners rebuild the
1437
+ // registry list from scratch on every step and re-apply their own filtering,
1438
+ // so a memoized "nothing changed" answer would hand back their trimmed list
1439
+ // with this module's additions missing, one step after they appeared.
1440
+ // Returning `result` when nothing was dropped or added keeps the prompt
1441
+ // prefix — and the model's cache — byte-identical, the property that matters.
1442
+ const changed = kept.length !== result.tools.length || merged.length !== kept.length
1443
+ return contain(changed ? { ...result, tools: merged } : result)
1444
+ }
1445
+
1446
+ const assemble: AssembleListener = async (_assembly, _context, next) => {
1447
+ const result = await next()
1448
+ try {
1449
+ return merge(result)
1450
+ } catch (error) {
1451
+ // A listener that throws would break every model request of the session;
1452
+ // this one degrades to "the assembly the rest of the harness produced".
1453
+ options.onError?.(error)
1454
+ return result
1455
+ }
1456
+ }
1457
+
1458
+ const observe = (_session: unknown, event: SessionEventLike): void => {
1459
+ try {
1460
+ if (event?.type === 'compaction/end') {
1461
+ options.setState(onCompaction(options.state()))
1462
+ // The step records belong to activations a compaction has just dropped,
1463
+ // so they go with them: a name activated again after this is stamped
1464
+ // with the step it returns on, not with the one it left on.
1465
+ options.onCompaction?.()
1466
+ // A compaction rewrote the conversation the offers belonged to, so the
1467
+ // context tier starts over; the counter baseline is untouched.
1468
+ tracker.state = resetAutoOffer(tracker.state)
1469
+ tracker.calls = []
1470
+ tracker.changed = false
1471
+ return
1472
+ }
1473
+ if (event?.type === 'user/message') {
1474
+ const text = readUserMessage(event)
1475
+ // An empty text (an image-only or non-text message) says nothing about
1476
+ // the task, so it must not wipe a context an earlier message set up.
1477
+ if (text !== '' && text !== tracker.userText) {
1478
+ const bounded = boundTaskText(text)
1479
+ tracker.changed = bounded !== tracker.userText
1480
+ tracker.userText = bounded
1481
+ }
1482
+ return
1483
+ }
1484
+ if (event?.type === 'tool/call') {
1485
+ const name = readCallName(event)
1486
+ if (name !== '') {
1487
+ tracker.calls.push(name)
1488
+ if (tracker.calls.length > MAX_AUTO_RECENT_CALLS) {
1489
+ tracker.calls.splice(0, tracker.calls.length - MAX_AUTO_RECENT_CALLS)
1490
+ }
1491
+ }
1492
+ }
1493
+ } catch (error) {
1494
+ options.onError?.(error)
1495
+ }
1496
+ }
1497
+
1498
+ const search = createSearchTool({
1499
+ available: searchable,
1500
+ activate: (names) => {
1501
+ recordActivated(names)
1502
+ options.setState(activate(options.state(), names, Date.now()))
1503
+ },
1504
+ ...(options.searchLimit === undefined ? {} : { defaultLimit: options.searchLimit }),
1505
+ })
1506
+
1507
+ const disposers: (() => void)[] = [
1508
+ listen('system-prompt/assemble', assemble as unknown as ListenerLike, true),
1509
+ listen('session/event', observe as unknown as ListenerLike, false),
1510
+ ]
1511
+ try {
1512
+ disposers.push(options.ctx.tools.register(search))
1513
+ } catch (error) {
1514
+ options.onError?.(error)
1515
+ }
1516
+ return () => {
1517
+ for (const registered of disposers) dispose(registered)
1518
+ }
1519
+ }
1520
+
1521
+ /**
1522
+ * Read the tool name out of one committed `tool/call` event.
1523
+ *
1524
+ * The recent calls are context evidence only, never activation: a name the
1525
+ * context tier offers is still filtered by the runtime's own mount records, so
1526
+ * a call to a profile-level tool cannot smuggle a foreign name into the list.
1527
+ *
1528
+ * @param event - one event as the `session/event` listener receives it.
1529
+ * @returns the called tool's public name, or `''` when the event carries none.
1530
+ */
1531
+ function readCallName(event: SessionEventLike): string {
1532
+ if (event.type !== 'tool/call' || !isRecord(event.data)) return ''
1533
+ const name = event.data.name
1534
+ return typeof name === 'string' ? name : ''
1535
+ }
1536
+
1537
+ /** Read and normalize the `query` argument. */
1538
+ function readQuery(args: unknown): string {
1539
+ if (!isRecord(args)) return ''
1540
+ const query = args.query
1541
+ return typeof query === 'string' ? query.trim() : ''
1542
+ }
1543
+
1544
+ /** Read the `limit` argument, clamped to the tool's supported range. */
1545
+ function readLimit(args: unknown, fallback: number): number {
1546
+ if (!isRecord(args)) return fallback
1547
+ const raw = args.limit
1548
+ if (typeof raw !== 'number' || !Number.isFinite(raw)) return fallback
1549
+ const limit = Math.trunc(raw)
1550
+ if (limit <= 0) return fallback
1551
+ return Math.min(limit, MAX_SEARCH_LIMIT)
1552
+ }
1553
+
1554
+ /**
1555
+ * Score one schema against the query: an exact name beats a name substring, and
1556
+ * both beat a description hit. Results keep the best score first and the name
1557
+ * order breaks ties, so one query always returns the same list.
1558
+ */
1559
+ function searchTools(
1560
+ available: readonly ToolSchemaLike[],
1561
+ query: string,
1562
+ limit: number,
1563
+ ): SearchMatch[] {
1564
+ const needle = query.toLowerCase()
1565
+ const tokens = searchTokens(needle)
1566
+ const scored: { match: SearchMatch; score: number }[] = []
1567
+ for (const tool of available) {
1568
+ const description = typeof tool.description === 'string' ? tool.description : ''
1569
+ const score = scoreTool(tool.name, description, needle, tokens)
1570
+ if (score === 0) continue
1571
+ scored.push({ match: { name: tool.name, description }, score })
1572
+ }
1573
+ scored.sort((left, right) => right.score - left.score || compareNames(left.match.name, right.match.name))
1574
+ return scored.slice(0, limit).map((entry) => entry.match)
1575
+ }
1576
+
1577
+ /**
1578
+ * Distinct words of a query, lowercased, in first-use order. Words shorter
1579
+ * than two characters are dropped (a one-letter word is a substring of half
1580
+ * the catalog and scores noise, not intent); the split keeps letters, digits
1581
+ * and underscores, so a query may quote a tool name verbatim (`issue_update`)
1582
+ * as well as name its concepts (`issue update`).
1583
+ */
1584
+ function searchTokens(needle: string): string[] {
1585
+ const tokens: string[] = []
1586
+ const seen = new Set<string>()
1587
+ for (const piece of needle.split(/[^\p{L}\p{N}_]+/u)) {
1588
+ if (piece.length < 2 || seen.has(piece)) continue
1589
+ seen.add(piece)
1590
+ tokens.push(piece)
1591
+ if (tokens.length >= MAX_SEARCH_TOKENS) break
1592
+ }
1593
+ return tokens
1594
+ }
1595
+
1596
+ /**
1597
+ * Score one candidate tool; `0` means no match. The whole query as one
1598
+ * substring stays the strongest signal (an exact name beats a phrase that
1599
+ * happens to sit inside a description), and every query word then adds its
1600
+ * own hit — a word in the name outweighs the same word in the description.
1601
+ * The per-word tier is what keeps a natural query like "issue get create
1602
+ * update" useful: no tool contains that phrase, but the tools that contain
1603
+ * most of its words are exactly the ones the model meant.
1604
+ */
1605
+ function scoreTool(name: string, description: string, needle: string, tokens: readonly string[]): number {
1606
+ const lowerName = name.toLowerCase()
1607
+ if (lowerName === needle) return 1_000
1608
+ const lowerDescription = description.toLowerCase()
1609
+ let score = 0
1610
+ if (lowerName.includes(needle)) score += 500
1611
+ else if (lowerDescription.includes(needle)) score += 250
1612
+ for (const token of tokens) {
1613
+ if (lowerName.includes(token)) score += 10
1614
+ else if (lowerDescription.includes(token)) score += 1
1615
+ }
1616
+ return score
1617
+ }
1618
+
1619
+ /** Code-unit name comparison, matching the canonical tool order of DSH. */
1620
+ function compareNames(left: string, right: string): number {
1621
+ return left < right ? -1 : left > right ? 1 : 0
1622
+ }
1623
+
1624
+ /** Serialize one canonical value for the model; total by construction. */
1625
+ function renderJson(value: unknown): string {
1626
+ const text = JSON.stringify(value, undefined, 2)
1627
+ return text === undefined ? String(value) : text
1628
+ }
1629
+
1630
+ function isRecord(value: unknown): value is Record<string, unknown> {
1631
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
1632
+ }