@cubicecho/agent-core 2.24.0 → 2.25.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.
Files changed (71) hide show
  1. package/README.md +10 -7
  2. package/dist/agent-loop.d.ts +84 -205
  3. package/dist/agent-loop.js +288 -597
  4. package/dist/calibration.d.ts +14 -10
  5. package/dist/calibration.js +30 -23
  6. package/dist/capabilities.d.ts +111 -42
  7. package/dist/capabilities.js +281 -138
  8. package/dist/client.d.ts +104 -35
  9. package/dist/client.js +205 -74
  10. package/dist/compaction.d.ts +103 -60
  11. package/dist/compaction.js +160 -86
  12. package/dist/config.d.ts +48 -12
  13. package/dist/config.js +20 -1
  14. package/dist/continuation.d.ts +24 -16
  15. package/dist/continuation.js +70 -44
  16. package/dist/digest.d.ts +7 -0
  17. package/dist/digest.js +18 -0
  18. package/dist/errors.d.ts +24 -15
  19. package/dist/errors.js +23 -15
  20. package/dist/events.d.ts +100 -63
  21. package/dist/events.js +250 -120
  22. package/dist/guards.d.ts +49 -4
  23. package/dist/guards.js +60 -5
  24. package/dist/hook-events.d.ts +21 -5
  25. package/dist/hook-events.js +23 -9
  26. package/dist/hooks.d.ts +96 -73
  27. package/dist/hooks.js +202 -116
  28. package/dist/index.d.ts +30 -26
  29. package/dist/index.js +29 -24
  30. package/dist/ledger.d.ts +62 -30
  31. package/dist/ledger.js +163 -56
  32. package/dist/platform.d.ts +15 -0
  33. package/dist/platform.js +15 -0
  34. package/dist/preselect.d.ts +223 -0
  35. package/dist/preselect.js +291 -0
  36. package/dist/request-body.d.ts +32 -0
  37. package/dist/request-body.js +47 -0
  38. package/dist/reset.d.ts +1 -0
  39. package/dist/reset.js +7 -6
  40. package/dist/retry.d.ts +44 -138
  41. package/dist/retry.js +83 -281
  42. package/dist/run-calls.d.ts +123 -0
  43. package/dist/run-calls.js +351 -0
  44. package/dist/run-turn.d.ts +36 -15
  45. package/dist/run-turn.js +74 -37
  46. package/dist/runtime.d.ts +23 -17
  47. package/dist/runtime.js +34 -24
  48. package/dist/schema-compat.d.ts +35 -18
  49. package/dist/schema-compat.js +346 -176
  50. package/dist/scope.d.ts +28 -5
  51. package/dist/scope.js +37 -10
  52. package/dist/side-task.d.ts +124 -40
  53. package/dist/side-task.js +186 -66
  54. package/dist/snapshot.d.ts +10 -5
  55. package/dist/snapshot.js +73 -30
  56. package/dist/spec.d.ts +56 -25
  57. package/dist/spec.js +494 -215
  58. package/dist/stream.d.ts +66 -16
  59. package/dist/stream.js +220 -97
  60. package/dist/thinking.d.ts +23 -8
  61. package/dist/thinking.js +92 -44
  62. package/dist/tokens.d.ts +164 -6
  63. package/dist/tokens.js +319 -6
  64. package/dist/tool-calls.d.ts +90 -17
  65. package/dist/tool-calls.js +207 -84
  66. package/dist/tool-loading.d.ts +101 -189
  67. package/dist/tool-loading.js +257 -371
  68. package/dist/wire.d.ts +81 -0
  69. package/dist/wire.js +73 -0
  70. package/llms.txt +76 -39
  71. package/package.json +4 -4
@@ -1,7 +1,10 @@
1
- import { isRecord } from "./guards.js";
1
+ import { byCodeUnit, isRecord } from './guards.js';
2
+ import { ARGUMENT_PREVIEW_CHARS } from './tool-calls.js';
3
+ import { FUNCTION_TOOL, SchemaType } from './wire.js';
2
4
  /**
3
5
  * On-demand tool loading.
4
6
  *
7
+ * @remarks
5
8
  * A full tool definition is mostly JSON Schema, and it is sent on every request of every
6
9
  * iteration whether or not the model wants it — a couple of connected servers can cost more
7
10
  * tokens per request than the task's own prompt. So in on-demand mode the run starts with a
@@ -12,39 +15,48 @@ import { isRecord } from "./guards.js";
12
15
  * Names alone cost roughly a fortieth of what the schemas cost, so a run that needs no tools
13
16
  * pays almost nothing, and a run that needs three pays for three.
14
17
  */
15
- export const LOAD_TOOLS = "load_tools";
16
- /** Shallow freezing this one would leave `.function.description` — the part worth editing. */
18
+ export const LOAD_TOOLS = 'load_tools';
19
+ /**
20
+ * Shallow freezing this one would leave `.function.description` — the part worth editing.
21
+ *
22
+ * @param value - What to freeze, in place, with every object and array reachable from it. A
23
+ * primitive passes through. Nothing stops the walk on a value that holds itself.
24
+ * @returns `value` itself, not a copy.
25
+ */
17
26
  function deepFreeze(value) {
18
- if (value && typeof value === "object")
19
- for (const held of Object.values(value))
27
+ if (value && typeof value === 'object') {
28
+ for (const held of Object.values(value)) {
20
29
  deepFreeze(held);
30
+ }
31
+ }
21
32
  return Object.freeze(value);
22
33
  }
23
34
  /**
24
35
  * One object for the life of the process — the agent loop asks for it on every iteration.
25
36
  *
37
+ * @remarks
26
38
  * Frozen because it is shared: one mutable export reached by every consumer in the process
27
39
  * means a caller that edits the description in place has edited it for all of them, in a place
28
40
  * nobody would think to look for the change.
29
41
  */
30
42
  export const LOAD_TOOLS_DEFINITION = deepFreeze({
31
- type: "function",
43
+ type: FUNCTION_TOOL,
32
44
  function: {
33
45
  name: LOAD_TOOLS,
34
- description: "Load the full definitions of tools listed in the tool catalogue so you can call them. " +
35
- "Pass the exact names you need, or a trailing wildcard like `server__group__*` for a " +
36
- "whole group. The tools become callable on your next step — load them, then call them. " +
37
- "Load only what the task actually needs.",
46
+ description: 'Load the full definitions of tools listed in the tool catalogue so you can call them. ' +
47
+ 'Pass the exact names you need, or a trailing wildcard like `server__group__*` for a ' +
48
+ 'whole group. The tools become callable on your next step — load them, then call them. ' +
49
+ 'Load only what the task actually needs.',
38
50
  parameters: {
39
- type: "object",
51
+ type: SchemaType.Object,
40
52
  properties: {
41
53
  names: {
42
- type: "array",
43
- items: { type: "string" },
44
- description: "Tool names from the catalogue. Wildcards may end with `*`.",
54
+ type: SchemaType.Array,
55
+ items: { type: SchemaType.String },
56
+ description: 'Tool names from the catalogue. Wildcards may end with `*`.',
45
57
  },
46
58
  },
47
- required: ["names"],
59
+ required: ['names'],
48
60
  additionalProperties: false,
49
61
  },
50
62
  },
@@ -52,26 +64,36 @@ export const LOAD_TOOLS_DEFINITION = deepFreeze({
52
64
  /**
53
65
  * The catalogue as a plain grouped listing of names, loaded ones marked if asked.
54
66
  *
67
+ * @param catalog - The connected servers. Ones with no tools are dropped.
68
+ * @param [loaded] - Names to mark `(loaded)` rather than remove. Absent marks nothing, which keeps the
69
+ * listing the same text for the whole run.
70
+ * @returns Each server's label on a line ending in a colon, its tool names indented beneath, one
71
+ * server straight after another. Empty where no server has a tool.
72
+ *
73
+ * @remarks
55
74
  * A server with no tools is dropped rather than titled: a pool hands one over whenever a
56
75
  * server is connected but has nothing to offer, and a label with nothing under it reads as a
57
76
  * listing that got cut off.
58
- *
59
- * @param catalog The connected servers. Ones with no tools are dropped.
60
- * @param loaded Names to mark `(loaded)` rather than remove. Absent marks nothing, which keeps the
61
- * listing the same text for the whole run.
62
77
  */
63
78
  export function catalogList(catalog, loaded) {
64
79
  return catalog
65
80
  .filter((server) => server.tools.length > 0)
66
81
  .map((server) => {
67
- const names = server.tools.map((tool) => ` ${tool.name}${loaded?.has(tool.name) ? " (loaded)" : ""}`);
68
- return `${server.label}:\n${names.join("\n")}`;
82
+ const names = server.tools.map((tool) => ` ${tool.name}${loaded?.has(tool.name) ? ' (loaded)' : ''}`);
83
+ return `${server.label}:\n${names.join('\n')}`;
69
84
  })
70
- .join("\n");
85
+ .join('\n');
71
86
  }
72
87
  /**
73
88
  * The catalogue block appended to the system prompt. Names only — descriptions arrive on load.
74
89
  *
90
+ * @param catalog - The connected servers. A catalogue with no tools in it produces an empty string.
91
+ * @param [loaded] - Names to mark `(loaded)`, for a caller that rebuilds its prompt per load and does
92
+ * not mind the cache. Absent marks nothing.
93
+ * @returns The heading, the instructions and the listing, with no blank line before or after — the
94
+ * caller separates it from its own prompt. Empty where there is nothing to list.
95
+ *
96
+ * @remarks
75
97
  * `runAgentLoop` passes no `loaded`, so the block is the same text on every step. The system
76
98
  * prompt is the head of the request, and marking each load there threw away the prompt cache for
77
99
  * the whole transcript on every `load_tools` call. What is loaded is said where it does not move
@@ -82,57 +104,67 @@ export function catalogList(catalog, loaded) {
82
104
  * it was loaded, and the model loads again to get it back; hoisting them into a separate "already
83
105
  * loaded" section splits a server's tools apart, and the model picks a sibling from the longer
84
106
  * list instead.
85
- *
86
- * @param catalog The connected servers. A catalogue with no tools in it produces an empty string.
87
- * @param loaded Names to mark `(loaded)`, for a caller that rebuilds its prompt per load and does
88
- * not mind the cache. Absent marks nothing.
89
107
  */
90
108
  export function catalogPrompt(catalog, loaded) {
91
109
  const list = catalogList(catalog, loaded);
92
110
  // Not `catalog.length`: a catalogue of nothing but empty servers has no names to offer, and
93
111
  // the preamble below would then explain a mechanism against an empty list.
94
- if (!list)
95
- return "";
112
+ if (!list) {
113
+ return '';
114
+ }
96
115
  return [
97
- "# Tool catalogue",
98
- "",
99
- "These tools exist but are not loaded. Call `load_tools` with the names you need, then call",
100
- "them on the step after. Names are descriptive; load a tool to see its parameters. A tool",
101
- "already in your tool list is loaded — call it directly, do not load it again. Do not load",
102
- "tools the task does not need, and do not mention this mechanism in your answer.",
103
- "",
116
+ '# Tool catalogue',
117
+ '',
118
+ 'These tools exist but are not loaded. Call `load_tools` with the names you need, then call',
119
+ 'them on the step after. Names are descriptive; load a tool to see its parameters. A tool',
120
+ 'already in your tool list is loaded — call it directly, do not load it again. Do not load',
121
+ 'tools the task does not need, and do not mention this mechanism in your answer.',
122
+ '',
104
123
  list,
105
- ].join("\n");
124
+ ].join('\n');
106
125
  }
126
+ /**
127
+ * Every tool in the catalogue as one list, server by server.
128
+ *
129
+ * @param catalog - The connected servers.
130
+ * @returns A new array in catalogue order. A name two servers offer is in it twice.
131
+ */
107
132
  const flatten = (catalog) => catalog.flatMap((server) => server.tools);
108
133
  /**
109
134
  * The name a tool definition is called by, or `undefined` for one that is not a function.
110
135
  *
136
+ * @param tool - The definition, as a request declares it.
137
+ * @returns The function's name as the definition spells it — an empty one comes back empty, not
138
+ * `undefined`.
139
+ *
140
+ * @remarks
111
141
  * Undefined rather than empty, so a caller that skips such a tool and one that has to place it
112
142
  * somewhere each say which they mean — a sort and a positional comparison want `?? ""`, a lookup
113
143
  * by name wants the tool left out.
114
- *
115
- * @param tool The definition, as a request declares it.
116
144
  */
117
- export const toolName = (tool) => tool.type === "function" ? tool.function.name : undefined;
145
+ export const toolName = (tool) => tool.type === FUNCTION_TOOL ? tool.function.name : undefined;
118
146
  /**
119
147
  * A tool array with newly loaded definitions appended, in the order they were loaded.
120
148
  *
149
+ * @param previous - What the last request declared, `load_tools` included. Not written to.
150
+ * @param matched - The definitions to add. Ones whose name is already declared, here or earlier in
151
+ * this list, are skipped rather than moved. One that is not a function has no name to be
152
+ * skipped by, and is appended.
153
+ * @returns A new array, `previous` first — a copy even where nothing was added.
154
+ *
155
+ * @remarks
121
156
  * Appended and never rebuilt from a set, so what a load adds is decided by the load and not by
122
157
  * the shape of whatever collection the definitions came out of. Where the appended array ends up
123
158
  * in the request is `orderTools`' business, which the loop applies after this.
124
- *
125
- * @param previous What the last request declared, `load_tools` included. Not written to.
126
- * @param matched The definitions to add. Ones whose name is already declared, here or earlier in
127
- * this list, are skipped rather than moved.
128
159
  */
129
160
  export function loadedTools(previous, matched) {
130
161
  const declared = new Set(previous.map(toolName));
131
162
  const tools = [...previous];
132
163
  for (const tool of matched) {
133
164
  const name = toolName(tool);
134
- if (name !== undefined && declared.has(name))
165
+ if (name !== undefined && declared.has(name)) {
135
166
  continue;
167
+ }
136
168
  declared.add(name);
137
169
  tools.push(tool);
138
170
  }
@@ -141,6 +173,12 @@ export function loadedTools(previous, matched) {
141
173
  /**
142
174
  * The tool array in a stable order, so the same set of tools renders the same way twice.
143
175
  *
176
+ * @param tools - The definitions to order. Not written to.
177
+ * @param [order] - `true` for name order, `false` to leave it alone, or a comparator over the names.
178
+ * A tool that is not a function orders as the empty name.
179
+ * @returns `tools` itself when it is already in that order, so the common case copies nothing.
180
+ *
181
+ * @remarks
144
182
  * A chat template renders the declared tools ahead of the system prompt, which makes the tool
145
183
  * array the first thing a prompt cache has to match — and an array assembled from a map, from
146
184
  * database rows, or from the order servers happened to connect in changes between processes and
@@ -152,25 +190,20 @@ export function loadedTools(previous, matched) {
152
190
  *
153
191
  * `false` is for a caller that means its order: the model reads the array top to bottom, and a
154
192
  * host may be putting what it wants reached for first at the front.
155
- *
156
- * @param tools The definitions to order. Not written to.
157
- * @param order `true` for name order, `false` to leave it alone, or a comparator over the names.
158
- * A tool that is not a function orders as the empty name.
159
- * @returns `tools` itself when it is already in that order, so the common case copies nothing.
160
193
  */
161
194
  export function orderTools(tools, order = true) {
162
- if (order === false)
195
+ if (order === false) {
163
196
  return tools;
164
- const nameOf = (tool) => toolName(tool) ?? "";
165
- // Code-unit order rather than `localeCompare`, whose answer depends on the host's locale —
166
- // which is the kind of instability this exists to remove.
167
- const compare = typeof order === "function" ? order : (a, b) => (a < b ? -1 : a > b ? 1 : 0);
197
+ }
198
+ const nameOf = (tool) => toolName(tool) ?? '';
199
+ const compare = typeof order === 'function' ? order : byCodeUnit;
168
200
  const sorted = [...tools].sort((a, b) => compare(nameOf(a), nameOf(b)));
169
201
  return sorted.some((tool, at) => tool !== tools[at]) ? sorted : tools;
170
202
  }
171
203
  /**
172
204
  * The most a single `load_tools` call may pull in.
173
205
  *
206
+ * @remarks
174
207
  * A wildcard like `gmail__*` matches 33 tools, and loading them all puts the model right back
175
208
  * in the position on-demand loading exists to avoid — a tool array too large to choose from.
176
209
  * Over-broad requests are refused with the matching names listed, so the next call can be
@@ -186,6 +219,7 @@ export const MAX_PER_LOAD = 12;
186
219
  * The most a conversation carries between turns. Bounds the tool array no matter how long the
187
220
  * conversation runs; past it, the earliest-declared names this turn did not use fall off first.
188
221
  *
222
+ * @remarks
189
223
  * Only a multi-turn caller needs this — a run that starts from nothing each time has nothing to
190
224
  * carry. See `carryOver`, which takes another number if this one is not yours.
191
225
  */
@@ -193,19 +227,21 @@ export const MAX_CARRIED = 16;
193
227
  /**
194
228
  * The tools to start the next turn with: last turn's where they were, then what this turn used.
195
229
  *
230
+ * @param previous - Last turn's names, in the order they were declared.
231
+ * @param used - What this turn called. Names not already carried are appended in the order given,
232
+ * so pass them in load order to keep them where the tool array had them.
233
+ * @param [max] - How many to carry. Past it, the earliest names not in
234
+ * `used` go first, then the earliest of all. At least one: a cap of zero is read as one, not as
235
+ * no cap and not as none.
236
+ * @returns The names to carry, as a new array no longer than the cap.
237
+ *
238
+ * @remarks
196
239
  * Nothing carried moves. A template renders the tool array near the head of the prompt, and
197
240
  * moving each used tool to the end — which this did until it was found in a local server's cache
198
241
  * log — reordered the array between turns and re-prefilled the whole transcript from the first
199
242
  * moved definition. Kept in place, the next turn's array is this one's with only the unused
200
243
  * loads gone, a prefix of it when every load was used. Past `max`, dropping a name from the
201
244
  * middle costs the cache from there, so it happens only when the cap forces it.
202
- *
203
- * @param previous Last turn's names, in the order they were declared.
204
- * @param used What this turn called. Names not already carried are appended in the order given,
205
- * so pass them in load order to keep them where the tool array had them.
206
- * @param max How many to carry, defaulting to `MAX_CARRIED`. Past it, the earliest names not in
207
- * `used` go first, then the earliest of all. At least one: a cap of zero is read as one, not as
208
- * no cap and not as none.
209
245
  */
210
246
  export function carryOver(previous, used, max = MAX_CARRIED) {
211
247
  const next = [...previous, ...[...used].filter((name) => !previous.includes(name))];
@@ -219,16 +255,19 @@ export function carryOver(previous, used, max = MAX_CARRIED) {
219
255
  /**
220
256
  * Resolves requested names against the catalogue, expanding trailing `*` wildcards.
221
257
  *
258
+ * @param requested - What the model asked for. A trailing `*` expands.
259
+ * @param catalog - The servers to resolve against.
260
+ * @param [maxPerLoad] - The most this call may load. It comes back on
261
+ * the resolution so `loadResult` reports the same number rather than a second opinion of it.
262
+ * @returns The names that resolved, each once; the ones nothing matched; the asks too broad for
263
+ * any call, with what they matched; and the ones that only did not fit this call.
264
+ *
265
+ * @remarks
222
266
  * Names are matched leniently. Catalogue entries are slug-qualified (`nas_fs__read_file`) and
223
267
  * models routinely ask for the bare tool name, so an exact miss falls back to a suffix match
224
268
  * on the `__` boundary — accepted only when it is unambiguous. Rejecting those outright just
225
269
  * buys a wasted round trip while the model guesses the prefix, and pushes it toward
226
270
  * shotgunning wildcards.
227
- *
228
- * @param requested What the model asked for. A trailing `*` expands.
229
- * @param catalog The servers to resolve against.
230
- * @param maxPerLoad The most this call may load, defaulting to `MAX_PER_LOAD`. It comes back on
231
- * the resolution so `loadResult` reports the same number rather than a second opinion of it.
232
271
  */
233
272
  export function expandNames(requested, catalog, maxPerLoad = MAX_PER_LOAD) {
234
273
  const all = flatten(catalog);
@@ -238,26 +277,29 @@ export function expandNames(requested, catalog, maxPerLoad = MAX_PER_LOAD) {
238
277
  const deferred = [];
239
278
  const known = new Set(all.map((tool) => tool.name));
240
279
  const resolve = (name) => {
241
- if (name.endsWith("*")) {
280
+ if (name.endsWith('*')) {
242
281
  const stem = name.slice(0, -1);
243
282
  const direct = all.filter((tool) => tool.name.startsWith(stem));
244
- if (direct.length)
283
+ if (direct.length) {
245
284
  return direct.map((tool) => tool.name);
285
+ }
246
286
  return all.filter((tool) => tool.name.includes(`__${stem}`)).map((tool) => tool.name);
247
287
  }
248
- if (known.has(name))
288
+ if (known.has(name)) {
249
289
  return [name];
290
+ }
250
291
  const suffix = all.filter((tool) => tool.name.endsWith(`__${name}`));
251
292
  return suffix.length === 1 ? [suffix[0].name] : [];
252
293
  };
253
294
  for (const raw of requested) {
254
295
  const name = raw.trim();
255
- if (!name)
296
+ if (!name) {
256
297
  continue;
298
+ }
257
299
  // A bare `*` is not a guess at a name, it is a refusal to choose, and its empty stem
258
300
  // prefixes every tool in the catalogue. Answer it the way any other over-broad request is
259
301
  // answered: with the names, so the next call can pick from them.
260
- if (name === "*") {
302
+ if (name === '*') {
261
303
  overBroad.push({ name, hits: all.map((tool) => tool.name) });
262
304
  continue;
263
305
  }
@@ -277,82 +319,105 @@ export function expandNames(requested, catalog, maxPerLoad = MAX_PER_LOAD) {
277
319
  // enough already — telling a model that asked for one exact tool that it matches one tool,
278
320
  // "more than the twelve one call may load", and to choose from a list holding just that
279
321
  // name, leaves it nothing to do but send the identical call again.
280
- if (fresh.length > maxPerLoad)
322
+ if (fresh.length > maxPerLoad) {
281
323
  overBroad.push({ name, hits });
282
- else if (matched.size + fresh.length > maxPerLoad)
324
+ }
325
+ else if (matched.size + fresh.length > maxPerLoad) {
283
326
  deferred.push(name);
284
- else
285
- for (const hit of hits)
327
+ }
328
+ else {
329
+ for (const hit of hits) {
286
330
  matched.add(hit);
331
+ }
332
+ }
287
333
  }
288
334
  return { matched: [...matched], unknown, overBroad, deferred, maxPerLoad };
289
335
  }
336
+ /**
337
+ * Each block's lines on their own, and a blank line between one block and the next.
338
+ *
339
+ * @param blocks - The blocks, each as its lines.
340
+ * @returns One text, empty where there are no blocks.
341
+ */
342
+ const joinBlocks = (blocks) => blocks.map((block) => block.join('\n')).join('\n\n');
290
343
  /**
291
344
  * What `load_tools` reports back: the descriptions, now that they are worth their tokens.
292
345
  *
346
+ * @param expanded - What `expandNames` resolved: the matches, the misses, and the over-broad asks.
347
+ * @param catalog - The servers, read for the descriptions now worth their tokens.
348
+ * @param [loaded] - What was loaded before this call. Absent reports every match as newly loaded.
349
+ * @returns What the model reads, a blank line between each thing it is told: what was loaded with
350
+ * its descriptions, what already was, each over-broad ask with its matches, what did not fit this
351
+ * call, and what is not in the catalogue. `No tool names were given.` where there is none of them.
352
+ *
353
+ * @remarks
293
354
  * A name that was loaded before this call is reported as already loaded rather than loaded
294
355
  * again. The catalogue no longer marks what is loaded — see `catalogPrompt` — so this is where a
295
356
  * model that asks twice finds out it need not have, and is told to call the tool instead.
296
- *
297
- * @param expanded What `expandNames` resolved: the matches, the misses, and the over-broad asks.
298
- * @param catalog The servers, read for the descriptions now worth their tokens.
299
- * @param loaded What was loaded before this call. Absent reports every match as newly loaded.
300
357
  */
301
358
  export function loadResult({ matched, unknown, overBroad, deferred, maxPerLoad }, catalog, loaded) {
302
359
  const byName = new Map(flatten(catalog).map((tool) => [tool.name, tool.description]));
303
- const lines = [];
360
+ // One entry per thing the model is told, each a blank line from the next.
361
+ const blocks = [];
304
362
  const fresh = matched.filter((name) => !loaded?.has(name));
305
363
  const again = matched.filter((name) => loaded?.has(name));
306
364
  if (fresh.length) {
307
- lines.push(`Loaded ${fresh.length} tool(s); they are callable on your next step.`, "");
308
- for (const name of fresh)
309
- lines.push(`${name}: ${byName.get(name) ?? ""}`.trim());
365
+ blocks.push([
366
+ `Loaded ${fresh.length} tool(s); they are callable on your next step.`,
367
+ '',
368
+ ...fresh.map((name) => `${name}: ${byName.get(name) ?? ''}`.trim()),
369
+ ]);
310
370
  }
311
371
  if (again.length) {
312
- if (lines.length)
313
- lines.push("");
314
- lines.push(`Already loaded and in your tool list: ${again.join(", ")}. Call them directly; do not load them again.`);
315
- }
316
- for (const { name, hits } of overBroad) {
317
- if (lines.length)
318
- lines.push("");
319
- lines.push(`\`${name}\` matches ${hits.length} tools, more than the ${maxPerLoad} one call may load.`, "Name the ones you need from:", ...hits.map((hit) => ` ${hit}`));
372
+ blocks.push([
373
+ `Already loaded and in your tool list: ${again.join(', ')}. Call them directly; do not load them again.`,
374
+ ]);
320
375
  }
376
+ blocks.push(...overBroad.map(({ name, hits }) => [
377
+ `\`${name}\` matches ${hits.length} tools, more than the ${maxPerLoad} one call may load.`,
378
+ 'Name the ones you need from:',
379
+ ...hits.map((hit) => ` ${hit}`),
380
+ ]));
321
381
  if (deferred.length) {
322
- if (lines.length)
323
- lines.push("");
324
- lines.push(`This call is full at ${maxPerLoad} tools, so these were not loaded: ${deferred.join(", ")}.`, "Ask for them on your next step.");
382
+ blocks.push([
383
+ `This call is full at ${maxPerLoad} tools, so these were not loaded: ${deferred.join(', ')}.`,
384
+ 'Ask for them on your next step.',
385
+ ]);
325
386
  }
326
387
  if (unknown.length) {
327
- if (lines.length)
328
- lines.push("");
329
- lines.push(`Not in the catalogue: ${unknown.join(", ")}. Check the names and try again.`);
388
+ blocks.push([`Not in the catalogue: ${unknown.join(', ')}. Check the names and try again.`]);
330
389
  }
331
- return lines.join("\n") || "No tool names were given.";
390
+ return joinBlocks(blocks) || 'No tool names were given.';
332
391
  }
333
392
  /**
334
393
  * Whether the catalogue holds a tool by this name.
335
394
  *
336
- * @param catalog The connected servers and the tools each one offers.
337
- * @param name An exact name. Nothing is prefixed, trimmed or fuzzily matched.
395
+ * @param catalog - The connected servers and the tools each one offers.
396
+ * @param name - An exact name. Nothing is prefixed, trimmed or fuzzily matched.
397
+ * @returns True where any server offers it, which no server of an empty catalogue does.
338
398
  */
339
399
  export const inCatalog = (catalog, name) => catalog.some((server) => server.tools.some((tool) => tool.name === name));
340
400
  /**
341
401
  * `load_tools` arguments, defensively — a model may send a bare string or a nested object.
342
402
  *
343
- * @param args The tool call's arguments, exactly as the model sent them.
403
+ * @param args - The tool call's arguments, exactly as the model sent them.
404
+ * @returns The names under `names`, or failing that `tools`, or `name`: a string as a list of one,
405
+ * an array less whatever in it is not a string, and anything else as none. Not trimmed.
344
406
  */
345
407
  export function requestedNames(args) {
346
408
  const value = args.names ?? args.tools ?? args.name;
347
- if (typeof value === "string")
409
+ if (typeof value === 'string') {
348
410
  return [value];
349
- if (Array.isArray(value))
350
- return value.filter((item) => typeof item === "string");
411
+ }
412
+ if (Array.isArray(value)) {
413
+ return value.filter((item) => typeof item === 'string');
414
+ }
351
415
  return [];
352
416
  }
353
417
  /**
354
418
  * The one tool a proxied run reaches every catalogued tool through.
355
419
  *
420
+ * @remarks
356
421
  * Proxied discovery is on-demand loading with a tool array that never changes. On-demand mode
357
422
  * declares each tool as it is loaded, and a chat template renders the tool array in the system
358
423
  * turn, ahead of the whole conversation — so appending one definition there moves every token
@@ -363,11 +428,12 @@ export function requestedNames(args) {
363
428
  * this one. The price is a level of indirection the model has to get right, which a small model
364
429
  * does less reliably than a native call.
365
430
  */
366
- export const CALL_TOOL = "call_tool";
431
+ export const CALL_TOOL = 'call_tool';
367
432
  /**
368
433
  * The whole tool array of a proxied run, `load_tools` then `call_tool`, frozen because it is
369
434
  * shared.
370
435
  *
436
+ * @remarks
371
437
  * The load keeps `LOAD_TOOLS` as its name, so `requestedNames` and `expandNames` read its
372
438
  * arguments as they do on demand; only what it promises differs, which is why it is not
373
439
  * `LOAD_TOOLS_DEFINITION`. `call_tool`'s `arguments` says `additionalProperties: true` and has to:
@@ -377,44 +443,44 @@ export const CALL_TOOL = "call_tool";
377
443
  */
378
444
  export const PROXY_TOOLS = deepFreeze([
379
445
  {
380
- type: "function",
446
+ type: FUNCTION_TOOL,
381
447
  function: {
382
448
  name: LOAD_TOOLS,
383
- description: "Get the full definitions of tools listed in the tool catalogue: what each does and the " +
384
- "arguments it takes. Pass the exact names you need, or a trailing wildcard like " +
385
- "`server__group__*` for a whole group. Then run them with `call_tool`. Load only what " +
386
- "the task actually needs.",
449
+ description: 'Get the full definitions of tools listed in the tool catalogue: what each does and the ' +
450
+ 'arguments it takes. Pass the exact names you need, or a trailing wildcard like ' +
451
+ '`server__group__*` for a whole group. Then run them with `call_tool`. Load only what ' +
452
+ 'the task actually needs.',
387
453
  parameters: {
388
- type: "object",
454
+ type: SchemaType.Object,
389
455
  properties: {
390
456
  names: {
391
- type: "array",
392
- items: { type: "string" },
393
- description: "Tool names from the catalogue. Wildcards may end with `*`.",
457
+ type: SchemaType.Array,
458
+ items: { type: SchemaType.String },
459
+ description: 'Tool names from the catalogue. Wildcards may end with `*`.',
394
460
  },
395
461
  },
396
- required: ["names"],
462
+ required: ['names'],
397
463
  additionalProperties: false,
398
464
  },
399
465
  },
400
466
  },
401
467
  {
402
- type: "function",
468
+ type: FUNCTION_TOOL,
403
469
  function: {
404
470
  name: CALL_TOOL,
405
- description: "Run a tool from the catalogue. Load it with `load_tools` first to learn its arguments, " +
406
- "then pass its exact name and an arguments object matching its parameters.",
471
+ description: 'Run a tool from the catalogue. Load it with `load_tools` first to learn its arguments, ' +
472
+ 'then pass its exact name and an arguments object matching its parameters.',
407
473
  parameters: {
408
- type: "object",
474
+ type: SchemaType.Object,
409
475
  properties: {
410
- name: { type: "string", description: "The tool's exact name from the catalogue." },
476
+ name: { type: SchemaType.String, description: "The tool's exact name from the catalogue." },
411
477
  arguments: {
412
- type: "object",
478
+ type: SchemaType.Object,
413
479
  description: "The tool's arguments, as its definition describes them.",
414
480
  additionalProperties: true,
415
481
  },
416
482
  },
417
- required: ["name", "arguments"],
483
+ required: ['name', 'arguments'],
418
484
  },
419
485
  },
420
486
  },
@@ -423,26 +489,29 @@ export const PROXY_TOOLS = deepFreeze([
423
489
  * The catalogue block for a proxied run's system prompt, worded for `call_tool` rather than for a
424
490
  * tool list.
425
491
  *
492
+ * @param catalog - The connected servers. A catalogue with no tools in it produces an empty string.
493
+ * @returns The heading, the instructions and the listing, with no blank line before or after.
494
+ *
495
+ * @remarks
426
496
  * `catalogPrompt` tells the model a loaded tool is in its tool list, which proxied is never true —
427
497
  * a model told so looks for it there and calls it natively. The listing itself is the same, and
428
498
  * like that one it is never marked, so the head of the prompt is one text for the whole session.
429
- *
430
- * @param catalog The connected servers. A catalogue with no tools in it produces an empty string.
431
499
  */
432
500
  export function proxyCatalogPrompt(catalog) {
433
501
  const list = catalogList(catalog);
434
- if (!list)
435
- return "";
502
+ if (!list) {
503
+ return '';
504
+ }
436
505
  return [
437
- "# Tool catalogue",
438
- "",
439
- "These tools exist. Call `load_tools` with the names you need to get their definitions, then",
440
- "run them with `call_tool`. Names are descriptive; load a tool to see its parameters. A tool",
441
- "whose definition is already in this conversation does not need loading again. Do not load",
442
- "tools the task does not need, and do not mention this mechanism in your answer.",
443
- "",
506
+ '# Tool catalogue',
507
+ '',
508
+ 'These tools exist. Call `load_tools` with the names you need to get their definitions, then',
509
+ 'run them with `call_tool`. Names are descriptive; load a tool to see its parameters. A tool',
510
+ 'whose definition is already in this conversation does not need loading again. Do not load',
511
+ 'tools the task does not need, and do not mention this mechanism in your answer.',
512
+ '',
444
513
  list,
445
- ].join("\n");
514
+ ].join('\n');
446
515
  }
447
516
  /** How a proxied load result that carries definitions opens, with the count left open. */
448
517
  const PROXY_LOADED = /^Loaded \d+ tool\(s\)\. Run them with `call_tool`\./;
@@ -450,312 +519,129 @@ const PROXY_LOADED = /^Loaded \d+ tool\(s\)\. Run them with `call_tool`\./;
450
519
  * Whether a tool result is a proxied load carrying definitions, which is the only copy of them
451
520
  * the model has.
452
521
  *
522
+ * @param result - The tool message's text. A load that only pointed back or refused is not one.
523
+ * @returns True where the text opens as `proxyLoadResult` opens a result with a definition in it.
524
+ *
525
+ * @remarks
453
526
  * On demand the definitions are in the tool array and a load's result only repeats their
454
527
  * descriptions, so clearing it loses nothing. Proxied, the result is the schema, and
455
528
  * `pruneToolResults` asks this before it stubs one. Told by how `proxyLoadResult` opens, the way
456
529
  * a summary is told by `SUMMARY_LEAD`, because a `tool` message carries no tool name of its own.
457
- *
458
- * @param result The tool message's text. A load that only pointed back or refused is not one.
459
530
  */
460
531
  export const holdsDefinitions = (result) => PROXY_LOADED.test(result);
461
532
  /**
462
533
  * What a proxied `load_tools` answers: each new tool's whole definition as a line of JSON, since
463
534
  * the result is the only place the model will ever see it.
464
535
  *
536
+ * @param resolved - What the call asked for, from `expandNames`.
537
+ * @param catalog - The servers, read for the refusals' wording.
538
+ * @param definitions - The definitions of `resolved.matched`, as many as the host has. Ones that
539
+ * are not functions are skipped.
540
+ * @param [loaded] - What was loaded before this call. Absent reports every match as newly loaded.
541
+ * @returns What the model reads, a blank line between each part: the count and one line of JSON
542
+ * per new definition, then what was already loaded, what has no definition, and the refusals.
543
+ * Never empty.
544
+ *
545
+ * @remarks
465
546
  * A name loaded before this call is answered with a pointer back rather than its definition a
466
547
  * second time, and one the catalogue lists but `definitions` does not hold is said to have none,
467
548
  * so the model is not left waiting on a schema that is not coming. The refusals — too broad, over
468
549
  * the per-call cap, not in the catalogue, nothing asked for — are `loadResult`'s, worded the same
469
550
  * in both modes.
470
- *
471
- * @param resolved What the call asked for, from `expandNames`.
472
- * @param catalog The servers, read for the refusals' wording.
473
- * @param definitions The definitions of `resolved.matched`, as many as the host has. Ones that
474
- * are not functions are skipped.
475
- * @param loaded What was loaded before this call. Absent reports every match as newly loaded.
476
551
  */
477
552
  export function proxyLoadResult(resolved, catalog, definitions, loaded) {
478
- const lines = [];
553
+ const blocks = [];
479
554
  const again = resolved.matched.filter((name) => loaded?.has(name));
480
- const fresh = definitions.flatMap((tool) => tool.type === "function" && !loaded?.has(tool.function.name) ? [tool.function] : []);
555
+ const fresh = definitions.flatMap((tool) => tool.type === FUNCTION_TOOL && !loaded?.has(tool.function.name) ? [tool.function] : []);
481
556
  const defined = new Set(fresh.map((tool) => tool.name));
482
557
  const missing = resolved.matched.filter((name) => !loaded?.has(name) && !defined.has(name));
483
558
  if (fresh.length) {
484
- lines.push(`Loaded ${fresh.length} tool(s). Run them with \`${CALL_TOOL}\`.`);
485
- for (const { name, description, parameters } of fresh)
486
- lines.push("", JSON.stringify({ name, description, parameters }));
559
+ blocks.push([`Loaded ${fresh.length} tool(s). Run them with \`${CALL_TOOL}\`.`]);
560
+ blocks.push(...fresh.map(({ name, description, parameters }) => [JSON.stringify({ name, description, parameters })]));
487
561
  }
488
562
  if (again.length) {
489
- if (lines.length)
490
- lines.push("");
491
- lines.push(`Already loaded earlier in this conversation: ${again.join(", ")}. Run them with ` +
492
- `\`${CALL_TOOL}\`; do not load them again.`);
563
+ blocks.push([
564
+ `Already loaded earlier in this conversation: ${again.join(', ')}. Run them with ` +
565
+ `\`${CALL_TOOL}\`; do not load them again.`,
566
+ ]);
493
567
  }
494
568
  if (missing.length) {
495
- if (lines.length)
496
- lines.push("");
497
- lines.push(`No definition is available for: ${missing.join(", ")}.`);
569
+ blocks.push([`No definition is available for: ${missing.join(', ')}.`]);
498
570
  }
499
571
  const { overBroad, deferred, unknown, matched } = resolved;
500
- if (overBroad.length || deferred.length || unknown.length || !matched.length) {
501
- if (lines.length)
502
- lines.push("");
503
- lines.push(loadResult({ ...resolved, matched: [] }, catalog));
572
+ const hasMoreToSay = overBroad.length || deferred.length || unknown.length || !matched.length;
573
+ if (hasMoreToSay) {
574
+ blocks.push([loadResult({ ...resolved, matched: [] }, catalog)]);
504
575
  }
505
- return lines.join("\n");
576
+ return joinBlocks(blocks);
506
577
  }
507
578
  /**
508
579
  * The tool a `call_tool` names and the arguments to run it with, or a throw the model can read.
509
580
  *
581
+ * @param args - The `call_tool` call's own arguments, parsed. An absent `arguments` is no arguments.
582
+ * @param catalog - What may be called. The name is trimmed and then matched exactly.
583
+ * @returns The trimmed name, and the arguments as an object: the one the model passed, not a copy,
584
+ * or the one its JSON string parsed to.
585
+ *
586
+ * @remarks
510
587
  * `arguments` arrives as an object when the model follows the schema and as a JSON string when it
511
588
  * copies the shape of a native call instead; both are taken, since the intent is the same. A name
512
589
  * outside the catalogue is refused here rather than handed to a dispatcher, which is what keeps
513
590
  * `call_tool` from reaching anything the catalogue does not offer.
514
- *
515
- * @param args The `call_tool` call's own arguments, parsed. An absent `arguments` is no arguments.
516
- * @param catalog What may be called. The name is trimmed and then matched exactly.
517
591
  */
518
592
  export function proxiedCall(args, catalog) {
519
- const name = typeof args.name === "string" ? args.name.trim() : "";
520
- if (!name)
593
+ const name = typeof args.name === 'string' ? args.name.trim() : '';
594
+ if (!name) {
521
595
  throw new Error(`${CALL_TOOL} needs a name; pass one from the tool catalogue.`);
522
- if (!inCatalog(catalog, name))
596
+ }
597
+ if (!inCatalog(catalog, name)) {
523
598
  throw new Error(`Not in the catalogue: ${name}. Check the name and try again.`);
599
+ }
524
600
  let input = args.arguments ?? {};
525
- if (typeof input === "string") {
601
+ if (typeof input === 'string') {
526
602
  const text = input;
527
603
  try {
528
604
  input = text.trim() ? JSON.parse(text) : {};
529
605
  }
530
606
  catch {
531
- throw new Error(`${CALL_TOOL} arguments for ${name} are not valid JSON: ${text.slice(0, 200)}`);
607
+ throw new Error(`${CALL_TOOL} arguments for ${name} are not valid JSON: ${text.slice(0, ARGUMENT_PREVIEW_CHARS)}`);
532
608
  }
533
609
  }
534
- if (!input || typeof input !== "object" || Array.isArray(input))
610
+ if (!isRecord(input)) {
535
611
  throw new Error(`${CALL_TOOL} arguments for ${name} must be an object.`);
536
- return { name, input: input };
612
+ }
613
+ return { name, input };
537
614
  }
538
615
  /**
539
616
  * A tool call as a watcher should see it: a `call_tool` as the tool it ran, anything else as it
540
617
  * is.
541
618
  *
619
+ * @param name - The name the model called.
620
+ * @param input - The call's arguments as JSON text.
621
+ * @returns The inner name and its arguments as JSON text — the string itself where the model
622
+ * passed `arguments` as one.
623
+ *
624
+ * @remarks
542
625
  * The transcript keeps the `call_tool` the model wrote, since the next request has to repeat it
543
626
  * word for word to stay in the cache; only the display looks through it. Anything that does not
544
627
  * parse as a proxied call is left as it came.
545
- *
546
- * @param name The name the model called.
547
- * @param input The call's arguments as JSON text.
548
- * @returns The inner name and its arguments as JSON text — the string itself where the model
549
- * passed `arguments` as one.
550
628
  */
551
629
  export function shownCall(name, input) {
552
- if (name !== CALL_TOOL)
630
+ if (name !== CALL_TOOL) {
553
631
  return { name, input };
632
+ }
554
633
  try {
555
634
  const args = JSON.parse(input);
556
- if (typeof args.name !== "string" || !args.name.trim())
635
+ if (typeof args.name !== 'string' || !args.name.trim()) {
557
636
  return { name, input };
637
+ }
558
638
  const inner = args.arguments ?? {};
559
639
  return {
560
640
  name: args.name.trim(),
561
- input: typeof inner === "string" ? inner : JSON.stringify(inner),
641
+ input: typeof inner === 'string' ? inner : JSON.stringify(inner),
562
642
  };
563
643
  }
564
644
  catch {
565
645
  return { name, input };
566
646
  }
567
647
  }
568
- /**
569
- * Where a request is cut for the preselector, in characters.
570
- *
571
- * A tool choice is made on what the work is, which is the top of a request rather than all of
572
- * it — and the whole of a long one is paid for again in the preselection call. `preselectInput`
573
- * takes another number for a caller whose requests are not shaped that way.
574
- */
575
- const PRESELECT_PROMPT_CHARS = 2000;
576
- /**
577
- * The system prompt a preselector is given, holding it to the cap its answer will be held to.
578
- *
579
- * On-demand loading otherwise costs a round trip every run: the model reads the catalogue,
580
- * calls `load_tools`, and only then can do the work. A small model reading the same catalogue
581
- * usually names the right tools outright, so the task model finds them already loaded and
582
- * starts working on its first step.
583
- *
584
- * A wrong guess is cheap — an unused definition is a few hundred tokens for one run — but a
585
- * broad guess is not, so the same cap applies here as to a `load_tools` call.
586
- *
587
- * @param maxPerLoad The most to ask for, defaulting to `MAX_PER_LOAD`. Give `preselection` the
588
- * same number: this one is what the preselector is told, and that one is what it is held to.
589
- */
590
- export const preselectSystem = (maxPerLoad = MAX_PER_LOAD) => "You choose tools. Below is a catalogue of tool names, then a request. Reply with a JSON " +
591
- 'object whose "tools" array holds the names the request is likely to need — exact names from ' +
592
- `the catalogue, at most ${maxPerLoad}, and as few as could do the job. Reply with ` +
593
- '`{"tools": []}` if the request can be answered without tools. Reply with the object alone — ' +
594
- "no prose, no explanation.";
595
- /**
596
- * The shape a preselector's answer is held to where the server takes a schema: `{ tools: [...] }`.
597
- *
598
- * An object around the array rather than the array, because a structured answer's root has to be
599
- * an object — OpenAI's strict mode and every tool-schema normaliser insist.
600
- */
601
- export const PRESELECT_SCHEMA = {
602
- type: "object",
603
- properties: { tools: { type: "array", items: { type: "string" } } },
604
- required: ["tools"],
605
- additionalProperties: false,
606
- };
607
- /** The preselection system prompt at the default cap, for a caller that never changes it. */
608
- export const PRESELECT_SYSTEM = preselectSystem();
609
- /**
610
- * The user message for a preselection call: the catalogue, then the request.
611
- *
612
- * @param catalog The connected servers, rendered as the name-only listing.
613
- * @param prompt The request being planned for, truncated — choosing tools needs the shape of the
614
- * ask, not all of it.
615
- * @param maxPromptChars Where the request is cut, defaulting to 2000. A caller whose requests
616
- * carry the part that names the work at the end wants a larger one, and pays for it in the
617
- * preselector's prompt.
618
- */
619
- export const preselectInput = (catalog, prompt, maxPromptChars = PRESELECT_PROMPT_CHARS) => `# Tool catalogue\n\n${catalogList(catalog)}\n\n# Request\n\n${prompt.slice(0, maxPromptChars)}`;
620
- /**
621
- * Resolves a preselection against the catalogue: unknown names dropped, count capped.
622
- *
623
- * @param names What the preselector replied: `{ tools: [...] }` as `PRESELECT_SCHEMA` has it, or
624
- * the bare array an older prompt asked for. Unvalidated: anything else gives none, and entries
625
- * that are not strings are dropped.
626
- * @param catalog The servers to resolve against.
627
- * @param maxPerLoad The most to keep, defaulting to `MAX_PER_LOAD`. The same number
628
- * `preselectSystem` was given, or the model is being held to a cap it was never told about.
629
- */
630
- export function preselection(names, catalog, maxPerLoad = MAX_PER_LOAD) {
631
- const list = isRecord(names) ? names.tools : names;
632
- if (!Array.isArray(list))
633
- return [];
634
- const wanted = list.filter((name) => typeof name === "string");
635
- return expandNames(wanted, catalog, maxPerLoad).matched.slice(0, maxPerLoad);
636
- }
637
- /**
638
- * Saturation and length normalisation for the BM25 score. Robertson's usual values.
639
- *
640
- * Nothing here is tuned for this corpus, because tuning them against a catalogue of forty short
641
- * documents would be fitting noise. `dropoff` and `minScore` are the knobs worth turning.
642
- */
643
- const BM25_K1 = 1.2;
644
- const BM25_B = 0.75;
645
- /**
646
- * The least a best match may score and still be acted on without a model.
647
- *
648
- * A BM25 score, so it is read against the shape of the corpus rather than as a percentage: a
649
- * query term carried by half the catalogue is worth about 0.7, and one carried by a single tool
650
- * about 3. One at this floor is therefore "something more distinctive than a word every other
651
- * tool uses", which is the weakest evidence worth skipping a round trip on.
652
- *
653
- * A term is distinctive only against other terms, so a catalogue of three or four tools rarely
654
- * clears it. That is the right answer rather than a gap: a catalogue that small is not costing
655
- * enough tokens to be worth choosing from in the first place.
656
- */
657
- export const KEYWORD_MIN_SCORE = 1;
658
- /**
659
- * How far the best unpicked tool must fall below the last picked one for the cut to count clean.
660
- *
661
- * Half. The cap is the only reason a hit is dropped, so a hit just underneath it scoring nearly
662
- * as much as one just above means the ranking chose arbitrarily, which is exactly the case a
663
- * model should be spent on.
664
- */
665
- export const KEYWORD_DROPOFF = 0.5;
666
- /**
667
- * English function words, dropped before matching.
668
- *
669
- * The inverse document frequency is supposed to make this unnecessary, and over a real corpus it
670
- * would: a word carried by every document is worth nothing. But a tool catalogue is twenty
671
- * one-line descriptions, and at that size "for" or "on" is rare by accident — it lands in one
672
- * description, scores as the most distinctive term in the query, and a request that says "for me"
673
- * is answered with whichever tool happened to use the word. Only closure-class words are here;
674
- * "list", "get", "run" and "show" are what tools are called and stay.
675
- */
676
- const NOISE = new Set(("about all also am an and any are as at be been being but by can could do does for from had " +
677
- "has have how if in into is it its just me more most my no not of on or other our out over " +
678
- "please should so some such than that the their them then there these they this to too up us " +
679
- "very was we were what when where which who will with would you your").split(" "));
680
- /**
681
- * A text as the matcher reads it: lowercase words, `server__tool_name` and camelCase split apart.
682
- *
683
- * Plurals are folded, crudely, by dropping a trailing `s`: a request says "read the files" and
684
- * the tool is called `read_file`, and without this the two do not meet. Nothing else is stemmed —
685
- * a real stemmer is a table of English morphology, and this is matching identifiers.
686
- */
687
- const terms = (text) => text
688
- .replace(/([a-z0-9])([A-Z])/g, "$1 $2")
689
- .toLowerCase()
690
- .split(/[^a-z0-9]+/)
691
- .filter((word) => word.length > 1 && !NOISE.has(word))
692
- .map((word) => word.length > 3 && word.endsWith("s") && !word.endsWith("ss") ? word.slice(0, -1) : word);
693
- /**
694
- * The tools a request's own words point at, ranked, and whether they point clearly enough.
695
- *
696
- * A preselection call costs a round trip to a model that is being asked to do term matching, and
697
- * on a local box that is seconds before the run has started. For a catalogue of a few dozen tools
698
- * the words usually decide it: a request that says "commit" and a tool called `git__commit` need
699
- * no reasoning to connect.
700
- *
701
- * BM25 rather than counting shared words, because the ranking has to survive the words every tool
702
- * uses. "list", "get" and "file" are in half the descriptions in a real catalogue, and a plain
703
- * overlap count hands the top of the ranking to whichever tool has the longest description. The
704
- * inverse document frequency makes a term worth what it distinguishes, and the length
705
- * normalisation stops a wordy description from outscoring the tool actually named.
706
- *
707
- * `confident` is what a caller acts on, and it is deliberately hard to earn: something more
708
- * distinctive than a word the whole catalogue shares has to have matched, and the tools left
709
- * unpicked have to score well below the ones picked. Anything else is ambiguous, and ambiguous is
710
- * what the model is for. Nothing matching is not confident either — the words cannot tell "this
711
- * request needs no tools" from "these words are not in the catalogue".
712
- *
713
- * @param catalog The servers to choose from. Each tool is matched on its name, its server's label
714
- * and its one-line description, which is everything the catalogue holds.
715
- * @param prompt The request being planned for. Only its head is read, as in `preselectInput`.
716
- * @param options The cap, the two confidence thresholds, and where the request is cut.
717
- */
718
- export function preselectByKeywords(catalog, prompt, { maxPerLoad = MAX_PER_LOAD, minScore = KEYWORD_MIN_SCORE, dropoff = KEYWORD_DROPOFF, maxPromptChars = PRESELECT_PROMPT_CHARS, } = {}) {
719
- const empty = { names: [], confident: false, ranked: [] };
720
- const docs = catalog.flatMap((server) => server.tools.map((tool) => ({
721
- name: tool.name,
722
- terms: terms(`${tool.name} ${server.label} ${tool.description}`),
723
- })));
724
- // A query term repeated in the request is not worth more than one said once: the request is
725
- // prose about a task, not a document being matched against another document.
726
- const query = new Set(terms(prompt.slice(0, maxPromptChars)));
727
- if (!docs.length || !query.size)
728
- return empty;
729
- const length = docs.reduce((total, doc) => total + doc.terms.length, 0) / docs.length;
730
- const documents = new Map();
731
- for (const doc of docs)
732
- for (const term of new Set(doc.terms))
733
- documents.set(term, (documents.get(term) ?? 0) + 1);
734
- const ranked = docs
735
- .map((doc) => {
736
- const counts = new Map();
737
- for (const term of doc.terms)
738
- counts.set(term, (counts.get(term) ?? 0) + 1);
739
- let score = 0;
740
- for (const term of query) {
741
- const found = counts.get(term);
742
- if (!found)
743
- continue;
744
- const held = documents.get(term) ?? 0;
745
- const idf = Math.log(1 + (docs.length - held + 0.5) / (held + 0.5));
746
- const norm = BM25_K1 * (1 - BM25_B + (BM25_B * doc.terms.length) / length);
747
- score += (idf * found * (BM25_K1 + 1)) / (found + norm);
748
- }
749
- return { name: doc.name, score };
750
- })
751
- .filter((hit) => hit.score > 0)
752
- // Ties break on the name, not on where the tool sat in the catalogue, so reconnecting a
753
- // server in a different order does not change what a run opens with.
754
- .sort((a, b) => b.score - a.score || a.name.localeCompare(b.name));
755
- if (!ranked.length)
756
- return empty;
757
- const names = ranked.slice(0, maxPerLoad).map((hit) => hit.name);
758
- const cut = ranked[names.length - 1].score;
759
- const next = ranked[maxPerLoad]?.score ?? 0;
760
- return { names, confident: ranked[0].score >= minScore && next <= dropoff * cut, ranked };
761
- }