@cubicecho/agent-core 2.24.0 → 2.25.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.
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 +35 -4
  23. package/dist/guards.js +38 -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 +13 -0
  33. package/dist/platform.js +13 -0
  34. package/dist/preselect.d.ts +222 -0
  35. package/dist/preselect.js +290 -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 +29 -138
  41. package/dist/retry.js +69 -282
  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 +340 -175
  50. package/dist/scope.d.ts +28 -5
  51. package/dist/scope.js +37 -10
  52. package/dist/side-task.d.ts +123 -40
  53. package/dist/side-task.js +181 -63
  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 +82 -17
  65. package/dist/tool-calls.js +198 -83
  66. package/dist/tool-loading.d.ts +101 -189
  67. package/dist/tool-loading.js +277 -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 { 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,65 +104,101 @@ 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
  }
139
171
  return tools;
140
172
  }
173
+ /**
174
+ * Orders two names by code unit.
175
+ *
176
+ * @param a - The name on the left.
177
+ * @param b - The name on the right.
178
+ * @returns Negative where `a` sorts first, positive where `b` does, zero where they are the same.
179
+ *
180
+ * @remarks
181
+ * Rather than `localeCompare`, whose answer depends on the host's locale — which is the kind of
182
+ * instability `orderTools` exists to remove.
183
+ */
184
+ function byCodeUnit(a, b) {
185
+ if (a < b) {
186
+ return -1;
187
+ }
188
+ if (a > b) {
189
+ return 1;
190
+ }
191
+ return 0;
192
+ }
141
193
  /**
142
194
  * The tool array in a stable order, so the same set of tools renders the same way twice.
143
195
  *
196
+ * @param tools - The definitions to order. Not written to.
197
+ * @param [order] - `true` for name order, `false` to leave it alone, or a comparator over the names.
198
+ * A tool that is not a function orders as the empty name.
199
+ * @returns `tools` itself when it is already in that order, so the common case copies nothing.
200
+ *
201
+ * @remarks
144
202
  * A chat template renders the declared tools ahead of the system prompt, which makes the tool
145
203
  * array the first thing a prompt cache has to match — and an array assembled from a map, from
146
204
  * database rows, or from the order servers happened to connect in changes between processes and
@@ -152,25 +210,20 @@ export function loadedTools(previous, matched) {
152
210
  *
153
211
  * `false` is for a caller that means its order: the model reads the array top to bottom, and a
154
212
  * 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
213
  */
161
214
  export function orderTools(tools, order = true) {
162
- if (order === false)
215
+ if (order === false) {
163
216
  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);
217
+ }
218
+ const nameOf = (tool) => toolName(tool) ?? '';
219
+ const compare = typeof order === 'function' ? order : byCodeUnit;
168
220
  const sorted = [...tools].sort((a, b) => compare(nameOf(a), nameOf(b)));
169
221
  return sorted.some((tool, at) => tool !== tools[at]) ? sorted : tools;
170
222
  }
171
223
  /**
172
224
  * The most a single `load_tools` call may pull in.
173
225
  *
226
+ * @remarks
174
227
  * A wildcard like `gmail__*` matches 33 tools, and loading them all puts the model right back
175
228
  * in the position on-demand loading exists to avoid — a tool array too large to choose from.
176
229
  * Over-broad requests are refused with the matching names listed, so the next call can be
@@ -186,6 +239,7 @@ export const MAX_PER_LOAD = 12;
186
239
  * The most a conversation carries between turns. Bounds the tool array no matter how long the
187
240
  * conversation runs; past it, the earliest-declared names this turn did not use fall off first.
188
241
  *
242
+ * @remarks
189
243
  * Only a multi-turn caller needs this — a run that starts from nothing each time has nothing to
190
244
  * carry. See `carryOver`, which takes another number if this one is not yours.
191
245
  */
@@ -193,19 +247,21 @@ export const MAX_CARRIED = 16;
193
247
  /**
194
248
  * The tools to start the next turn with: last turn's where they were, then what this turn used.
195
249
  *
250
+ * @param previous - Last turn's names, in the order they were declared.
251
+ * @param used - What this turn called. Names not already carried are appended in the order given,
252
+ * so pass them in load order to keep them where the tool array had them.
253
+ * @param [max] - How many to carry. Past it, the earliest names not in
254
+ * `used` go first, then the earliest of all. At least one: a cap of zero is read as one, not as
255
+ * no cap and not as none.
256
+ * @returns The names to carry, as a new array no longer than the cap.
257
+ *
258
+ * @remarks
196
259
  * Nothing carried moves. A template renders the tool array near the head of the prompt, and
197
260
  * moving each used tool to the end — which this did until it was found in a local server's cache
198
261
  * log — reordered the array between turns and re-prefilled the whole transcript from the first
199
262
  * moved definition. Kept in place, the next turn's array is this one's with only the unused
200
263
  * loads gone, a prefix of it when every load was used. Past `max`, dropping a name from the
201
264
  * 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
265
  */
210
266
  export function carryOver(previous, used, max = MAX_CARRIED) {
211
267
  const next = [...previous, ...[...used].filter((name) => !previous.includes(name))];
@@ -219,16 +275,19 @@ export function carryOver(previous, used, max = MAX_CARRIED) {
219
275
  /**
220
276
  * Resolves requested names against the catalogue, expanding trailing `*` wildcards.
221
277
  *
278
+ * @param requested - What the model asked for. A trailing `*` expands.
279
+ * @param catalog - The servers to resolve against.
280
+ * @param [maxPerLoad] - The most this call may load. It comes back on
281
+ * the resolution so `loadResult` reports the same number rather than a second opinion of it.
282
+ * @returns The names that resolved, each once; the ones nothing matched; the asks too broad for
283
+ * any call, with what they matched; and the ones that only did not fit this call.
284
+ *
285
+ * @remarks
222
286
  * Names are matched leniently. Catalogue entries are slug-qualified (`nas_fs__read_file`) and
223
287
  * models routinely ask for the bare tool name, so an exact miss falls back to a suffix match
224
288
  * on the `__` boundary — accepted only when it is unambiguous. Rejecting those outright just
225
289
  * buys a wasted round trip while the model guesses the prefix, and pushes it toward
226
290
  * 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
291
  */
233
292
  export function expandNames(requested, catalog, maxPerLoad = MAX_PER_LOAD) {
234
293
  const all = flatten(catalog);
@@ -238,26 +297,29 @@ export function expandNames(requested, catalog, maxPerLoad = MAX_PER_LOAD) {
238
297
  const deferred = [];
239
298
  const known = new Set(all.map((tool) => tool.name));
240
299
  const resolve = (name) => {
241
- if (name.endsWith("*")) {
300
+ if (name.endsWith('*')) {
242
301
  const stem = name.slice(0, -1);
243
302
  const direct = all.filter((tool) => tool.name.startsWith(stem));
244
- if (direct.length)
303
+ if (direct.length) {
245
304
  return direct.map((tool) => tool.name);
305
+ }
246
306
  return all.filter((tool) => tool.name.includes(`__${stem}`)).map((tool) => tool.name);
247
307
  }
248
- if (known.has(name))
308
+ if (known.has(name)) {
249
309
  return [name];
310
+ }
250
311
  const suffix = all.filter((tool) => tool.name.endsWith(`__${name}`));
251
312
  return suffix.length === 1 ? [suffix[0].name] : [];
252
313
  };
253
314
  for (const raw of requested) {
254
315
  const name = raw.trim();
255
- if (!name)
316
+ if (!name) {
256
317
  continue;
318
+ }
257
319
  // A bare `*` is not a guess at a name, it is a refusal to choose, and its empty stem
258
320
  // prefixes every tool in the catalogue. Answer it the way any other over-broad request is
259
321
  // answered: with the names, so the next call can pick from them.
260
- if (name === "*") {
322
+ if (name === '*') {
261
323
  overBroad.push({ name, hits: all.map((tool) => tool.name) });
262
324
  continue;
263
325
  }
@@ -277,82 +339,105 @@ export function expandNames(requested, catalog, maxPerLoad = MAX_PER_LOAD) {
277
339
  // enough already — telling a model that asked for one exact tool that it matches one tool,
278
340
  // "more than the twelve one call may load", and to choose from a list holding just that
279
341
  // name, leaves it nothing to do but send the identical call again.
280
- if (fresh.length > maxPerLoad)
342
+ if (fresh.length > maxPerLoad) {
281
343
  overBroad.push({ name, hits });
282
- else if (matched.size + fresh.length > maxPerLoad)
344
+ }
345
+ else if (matched.size + fresh.length > maxPerLoad) {
283
346
  deferred.push(name);
284
- else
285
- for (const hit of hits)
347
+ }
348
+ else {
349
+ for (const hit of hits) {
286
350
  matched.add(hit);
351
+ }
352
+ }
287
353
  }
288
354
  return { matched: [...matched], unknown, overBroad, deferred, maxPerLoad };
289
355
  }
356
+ /**
357
+ * Each block's lines on their own, and a blank line between one block and the next.
358
+ *
359
+ * @param blocks - The blocks, each as its lines.
360
+ * @returns One text, empty where there are no blocks.
361
+ */
362
+ const joinBlocks = (blocks) => blocks.map((block) => block.join('\n')).join('\n\n');
290
363
  /**
291
364
  * What `load_tools` reports back: the descriptions, now that they are worth their tokens.
292
365
  *
366
+ * @param expanded - What `expandNames` resolved: the matches, the misses, and the over-broad asks.
367
+ * @param catalog - The servers, read for the descriptions now worth their tokens.
368
+ * @param [loaded] - What was loaded before this call. Absent reports every match as newly loaded.
369
+ * @returns What the model reads, a blank line between each thing it is told: what was loaded with
370
+ * its descriptions, what already was, each over-broad ask with its matches, what did not fit this
371
+ * call, and what is not in the catalogue. `No tool names were given.` where there is none of them.
372
+ *
373
+ * @remarks
293
374
  * A name that was loaded before this call is reported as already loaded rather than loaded
294
375
  * again. The catalogue no longer marks what is loaded — see `catalogPrompt` — so this is where a
295
376
  * 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
377
  */
301
378
  export function loadResult({ matched, unknown, overBroad, deferred, maxPerLoad }, catalog, loaded) {
302
379
  const byName = new Map(flatten(catalog).map((tool) => [tool.name, tool.description]));
303
- const lines = [];
380
+ // One entry per thing the model is told, each a blank line from the next.
381
+ const blocks = [];
304
382
  const fresh = matched.filter((name) => !loaded?.has(name));
305
383
  const again = matched.filter((name) => loaded?.has(name));
306
384
  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());
385
+ blocks.push([
386
+ `Loaded ${fresh.length} tool(s); they are callable on your next step.`,
387
+ '',
388
+ ...fresh.map((name) => `${name}: ${byName.get(name) ?? ''}`.trim()),
389
+ ]);
310
390
  }
311
391
  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}`));
392
+ blocks.push([
393
+ `Already loaded and in your tool list: ${again.join(', ')}. Call them directly; do not load them again.`,
394
+ ]);
320
395
  }
396
+ blocks.push(...overBroad.map(({ name, hits }) => [
397
+ `\`${name}\` matches ${hits.length} tools, more than the ${maxPerLoad} one call may load.`,
398
+ 'Name the ones you need from:',
399
+ ...hits.map((hit) => ` ${hit}`),
400
+ ]));
321
401
  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.");
402
+ blocks.push([
403
+ `This call is full at ${maxPerLoad} tools, so these were not loaded: ${deferred.join(', ')}.`,
404
+ 'Ask for them on your next step.',
405
+ ]);
325
406
  }
326
407
  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.`);
408
+ blocks.push([`Not in the catalogue: ${unknown.join(', ')}. Check the names and try again.`]);
330
409
  }
331
- return lines.join("\n") || "No tool names were given.";
410
+ return joinBlocks(blocks) || 'No tool names were given.';
332
411
  }
333
412
  /**
334
413
  * Whether the catalogue holds a tool by this name.
335
414
  *
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.
415
+ * @param catalog - The connected servers and the tools each one offers.
416
+ * @param name - An exact name. Nothing is prefixed, trimmed or fuzzily matched.
417
+ * @returns True where any server offers it, which no server of an empty catalogue does.
338
418
  */
339
419
  export const inCatalog = (catalog, name) => catalog.some((server) => server.tools.some((tool) => tool.name === name));
340
420
  /**
341
421
  * `load_tools` arguments, defensively — a model may send a bare string or a nested object.
342
422
  *
343
- * @param args The tool call's arguments, exactly as the model sent them.
423
+ * @param args - The tool call's arguments, exactly as the model sent them.
424
+ * @returns The names under `names`, or failing that `tools`, or `name`: a string as a list of one,
425
+ * an array less whatever in it is not a string, and anything else as none. Not trimmed.
344
426
  */
345
427
  export function requestedNames(args) {
346
428
  const value = args.names ?? args.tools ?? args.name;
347
- if (typeof value === "string")
429
+ if (typeof value === 'string') {
348
430
  return [value];
349
- if (Array.isArray(value))
350
- return value.filter((item) => typeof item === "string");
431
+ }
432
+ if (Array.isArray(value)) {
433
+ return value.filter((item) => typeof item === 'string');
434
+ }
351
435
  return [];
352
436
  }
353
437
  /**
354
438
  * The one tool a proxied run reaches every catalogued tool through.
355
439
  *
440
+ * @remarks
356
441
  * Proxied discovery is on-demand loading with a tool array that never changes. On-demand mode
357
442
  * declares each tool as it is loaded, and a chat template renders the tool array in the system
358
443
  * turn, ahead of the whole conversation — so appending one definition there moves every token
@@ -363,11 +448,12 @@ export function requestedNames(args) {
363
448
  * this one. The price is a level of indirection the model has to get right, which a small model
364
449
  * does less reliably than a native call.
365
450
  */
366
- export const CALL_TOOL = "call_tool";
451
+ export const CALL_TOOL = 'call_tool';
367
452
  /**
368
453
  * The whole tool array of a proxied run, `load_tools` then `call_tool`, frozen because it is
369
454
  * shared.
370
455
  *
456
+ * @remarks
371
457
  * The load keeps `LOAD_TOOLS` as its name, so `requestedNames` and `expandNames` read its
372
458
  * arguments as they do on demand; only what it promises differs, which is why it is not
373
459
  * `LOAD_TOOLS_DEFINITION`. `call_tool`'s `arguments` says `additionalProperties: true` and has to:
@@ -377,44 +463,44 @@ export const CALL_TOOL = "call_tool";
377
463
  */
378
464
  export const PROXY_TOOLS = deepFreeze([
379
465
  {
380
- type: "function",
466
+ type: FUNCTION_TOOL,
381
467
  function: {
382
468
  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.",
469
+ description: 'Get the full definitions of tools listed in the tool catalogue: what each does and the ' +
470
+ 'arguments it takes. Pass the exact names you need, or a trailing wildcard like ' +
471
+ '`server__group__*` for a whole group. Then run them with `call_tool`. Load only what ' +
472
+ 'the task actually needs.',
387
473
  parameters: {
388
- type: "object",
474
+ type: SchemaType.Object,
389
475
  properties: {
390
476
  names: {
391
- type: "array",
392
- items: { type: "string" },
393
- description: "Tool names from the catalogue. Wildcards may end with `*`.",
477
+ type: SchemaType.Array,
478
+ items: { type: SchemaType.String },
479
+ description: 'Tool names from the catalogue. Wildcards may end with `*`.',
394
480
  },
395
481
  },
396
- required: ["names"],
482
+ required: ['names'],
397
483
  additionalProperties: false,
398
484
  },
399
485
  },
400
486
  },
401
487
  {
402
- type: "function",
488
+ type: FUNCTION_TOOL,
403
489
  function: {
404
490
  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.",
491
+ description: 'Run a tool from the catalogue. Load it with `load_tools` first to learn its arguments, ' +
492
+ 'then pass its exact name and an arguments object matching its parameters.',
407
493
  parameters: {
408
- type: "object",
494
+ type: SchemaType.Object,
409
495
  properties: {
410
- name: { type: "string", description: "The tool's exact name from the catalogue." },
496
+ name: { type: SchemaType.String, description: "The tool's exact name from the catalogue." },
411
497
  arguments: {
412
- type: "object",
498
+ type: SchemaType.Object,
413
499
  description: "The tool's arguments, as its definition describes them.",
414
500
  additionalProperties: true,
415
501
  },
416
502
  },
417
- required: ["name", "arguments"],
503
+ required: ['name', 'arguments'],
418
504
  },
419
505
  },
420
506
  },
@@ -423,26 +509,29 @@ export const PROXY_TOOLS = deepFreeze([
423
509
  * The catalogue block for a proxied run's system prompt, worded for `call_tool` rather than for a
424
510
  * tool list.
425
511
  *
512
+ * @param catalog - The connected servers. A catalogue with no tools in it produces an empty string.
513
+ * @returns The heading, the instructions and the listing, with no blank line before or after.
514
+ *
515
+ * @remarks
426
516
  * `catalogPrompt` tells the model a loaded tool is in its tool list, which proxied is never true —
427
517
  * a model told so looks for it there and calls it natively. The listing itself is the same, and
428
518
  * 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
519
  */
432
520
  export function proxyCatalogPrompt(catalog) {
433
521
  const list = catalogList(catalog);
434
- if (!list)
435
- return "";
522
+ if (!list) {
523
+ return '';
524
+ }
436
525
  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
- "",
526
+ '# Tool catalogue',
527
+ '',
528
+ 'These tools exist. Call `load_tools` with the names you need to get their definitions, then',
529
+ 'run them with `call_tool`. Names are descriptive; load a tool to see its parameters. A tool',
530
+ 'whose definition is already in this conversation does not need loading again. Do not load',
531
+ 'tools the task does not need, and do not mention this mechanism in your answer.',
532
+ '',
444
533
  list,
445
- ].join("\n");
534
+ ].join('\n');
446
535
  }
447
536
  /** How a proxied load result that carries definitions opens, with the count left open. */
448
537
  const PROXY_LOADED = /^Loaded \d+ tool\(s\)\. Run them with `call_tool`\./;
@@ -450,312 +539,129 @@ const PROXY_LOADED = /^Loaded \d+ tool\(s\)\. Run them with `call_tool`\./;
450
539
  * Whether a tool result is a proxied load carrying definitions, which is the only copy of them
451
540
  * the model has.
452
541
  *
542
+ * @param result - The tool message's text. A load that only pointed back or refused is not one.
543
+ * @returns True where the text opens as `proxyLoadResult` opens a result with a definition in it.
544
+ *
545
+ * @remarks
453
546
  * On demand the definitions are in the tool array and a load's result only repeats their
454
547
  * descriptions, so clearing it loses nothing. Proxied, the result is the schema, and
455
548
  * `pruneToolResults` asks this before it stubs one. Told by how `proxyLoadResult` opens, the way
456
549
  * 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
550
  */
460
551
  export const holdsDefinitions = (result) => PROXY_LOADED.test(result);
461
552
  /**
462
553
  * What a proxied `load_tools` answers: each new tool's whole definition as a line of JSON, since
463
554
  * the result is the only place the model will ever see it.
464
555
  *
556
+ * @param resolved - What the call asked for, from `expandNames`.
557
+ * @param catalog - The servers, read for the refusals' wording.
558
+ * @param definitions - The definitions of `resolved.matched`, as many as the host has. Ones that
559
+ * are not functions are skipped.
560
+ * @param [loaded] - What was loaded before this call. Absent reports every match as newly loaded.
561
+ * @returns What the model reads, a blank line between each part: the count and one line of JSON
562
+ * per new definition, then what was already loaded, what has no definition, and the refusals.
563
+ * Never empty.
564
+ *
565
+ * @remarks
465
566
  * A name loaded before this call is answered with a pointer back rather than its definition a
466
567
  * second time, and one the catalogue lists but `definitions` does not hold is said to have none,
467
568
  * so the model is not left waiting on a schema that is not coming. The refusals — too broad, over
468
569
  * the per-call cap, not in the catalogue, nothing asked for — are `loadResult`'s, worded the same
469
570
  * 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
571
  */
477
572
  export function proxyLoadResult(resolved, catalog, definitions, loaded) {
478
- const lines = [];
573
+ const blocks = [];
479
574
  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] : []);
575
+ const fresh = definitions.flatMap((tool) => tool.type === FUNCTION_TOOL && !loaded?.has(tool.function.name) ? [tool.function] : []);
481
576
  const defined = new Set(fresh.map((tool) => tool.name));
482
577
  const missing = resolved.matched.filter((name) => !loaded?.has(name) && !defined.has(name));
483
578
  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 }));
579
+ blocks.push([`Loaded ${fresh.length} tool(s). Run them with \`${CALL_TOOL}\`.`]);
580
+ blocks.push(...fresh.map(({ name, description, parameters }) => [JSON.stringify({ name, description, parameters })]));
487
581
  }
488
582
  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.`);
583
+ blocks.push([
584
+ `Already loaded earlier in this conversation: ${again.join(', ')}. Run them with ` +
585
+ `\`${CALL_TOOL}\`; do not load them again.`,
586
+ ]);
493
587
  }
494
588
  if (missing.length) {
495
- if (lines.length)
496
- lines.push("");
497
- lines.push(`No definition is available for: ${missing.join(", ")}.`);
589
+ blocks.push([`No definition is available for: ${missing.join(', ')}.`]);
498
590
  }
499
591
  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));
592
+ const hasMoreToSay = overBroad.length || deferred.length || unknown.length || !matched.length;
593
+ if (hasMoreToSay) {
594
+ blocks.push([loadResult({ ...resolved, matched: [] }, catalog)]);
504
595
  }
505
- return lines.join("\n");
596
+ return joinBlocks(blocks);
506
597
  }
507
598
  /**
508
599
  * The tool a `call_tool` names and the arguments to run it with, or a throw the model can read.
509
600
  *
601
+ * @param args - The `call_tool` call's own arguments, parsed. An absent `arguments` is no arguments.
602
+ * @param catalog - What may be called. The name is trimmed and then matched exactly.
603
+ * @returns The trimmed name, and the arguments as an object: the one the model passed, not a copy,
604
+ * or the one its JSON string parsed to.
605
+ *
606
+ * @remarks
510
607
  * `arguments` arrives as an object when the model follows the schema and as a JSON string when it
511
608
  * copies the shape of a native call instead; both are taken, since the intent is the same. A name
512
609
  * outside the catalogue is refused here rather than handed to a dispatcher, which is what keeps
513
610
  * `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
611
  */
518
612
  export function proxiedCall(args, catalog) {
519
- const name = typeof args.name === "string" ? args.name.trim() : "";
520
- if (!name)
613
+ const name = typeof args.name === 'string' ? args.name.trim() : '';
614
+ if (!name) {
521
615
  throw new Error(`${CALL_TOOL} needs a name; pass one from the tool catalogue.`);
522
- if (!inCatalog(catalog, name))
616
+ }
617
+ if (!inCatalog(catalog, name)) {
523
618
  throw new Error(`Not in the catalogue: ${name}. Check the name and try again.`);
619
+ }
524
620
  let input = args.arguments ?? {};
525
- if (typeof input === "string") {
621
+ if (typeof input === 'string') {
526
622
  const text = input;
527
623
  try {
528
624
  input = text.trim() ? JSON.parse(text) : {};
529
625
  }
530
626
  catch {
531
- throw new Error(`${CALL_TOOL} arguments for ${name} are not valid JSON: ${text.slice(0, 200)}`);
627
+ throw new Error(`${CALL_TOOL} arguments for ${name} are not valid JSON: ${text.slice(0, ARGUMENT_PREVIEW_CHARS)}`);
532
628
  }
533
629
  }
534
- if (!input || typeof input !== "object" || Array.isArray(input))
630
+ if (!isRecord(input)) {
535
631
  throw new Error(`${CALL_TOOL} arguments for ${name} must be an object.`);
536
- return { name, input: input };
632
+ }
633
+ return { name, input };
537
634
  }
538
635
  /**
539
636
  * A tool call as a watcher should see it: a `call_tool` as the tool it ran, anything else as it
540
637
  * is.
541
638
  *
639
+ * @param name - The name the model called.
640
+ * @param input - The call's arguments as JSON text.
641
+ * @returns The inner name and its arguments as JSON text — the string itself where the model
642
+ * passed `arguments` as one.
643
+ *
644
+ * @remarks
542
645
  * The transcript keeps the `call_tool` the model wrote, since the next request has to repeat it
543
646
  * word for word to stay in the cache; only the display looks through it. Anything that does not
544
647
  * 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
648
  */
551
649
  export function shownCall(name, input) {
552
- if (name !== CALL_TOOL)
650
+ if (name !== CALL_TOOL) {
553
651
  return { name, input };
652
+ }
554
653
  try {
555
654
  const args = JSON.parse(input);
556
- if (typeof args.name !== "string" || !args.name.trim())
655
+ if (typeof args.name !== 'string' || !args.name.trim()) {
557
656
  return { name, input };
657
+ }
558
658
  const inner = args.arguments ?? {};
559
659
  return {
560
660
  name: args.name.trim(),
561
- input: typeof inner === "string" ? inner : JSON.stringify(inner),
661
+ input: typeof inner === 'string' ? inner : JSON.stringify(inner),
562
662
  };
563
663
  }
564
664
  catch {
565
665
  return { name, input };
566
666
  }
567
667
  }
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
- }