@cubicecho/agent-core 2.18.1 → 2.20.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.
@@ -340,6 +340,221 @@ export function requestedNames(args) {
340
340
  return value.filter((item) => typeof item === "string");
341
341
  return [];
342
342
  }
343
+ /**
344
+ * The one tool a proxied run reaches every catalogued tool through.
345
+ *
346
+ * Proxied discovery is on-demand loading with a tool array that never changes. On-demand mode
347
+ * declares each tool as it is loaded, and a chat template renders the tool array in the system
348
+ * turn, ahead of the whole conversation — so appending one definition there moves every token
349
+ * after it, and on a model llama.cpp can only rewind to a saved checkpoint a single load
350
+ * re-prefills the transcript from the first token. Proxied, the array is `load_tools` and
351
+ * `call_tool` for the life of the session: a load answers with the definitions as its result, at
352
+ * the end of the history where the cache already stops, and the model runs a loaded tool through
353
+ * this one. The price is a level of indirection the model has to get right, which a small model
354
+ * does less reliably than a native call.
355
+ */
356
+ export const CALL_TOOL = "call_tool";
357
+ /**
358
+ * The whole tool array of a proxied run, `load_tools` then `call_tool`, frozen because it is
359
+ * shared.
360
+ *
361
+ * The load keeps `LOAD_TOOLS` as its name, so `requestedNames` and `expandNames` read its
362
+ * arguments as they do on demand; only what it promises differs, which is why it is not
363
+ * `LOAD_TOOLS_DEFINITION`. `call_tool`'s `arguments` says `additionalProperties: true` and has to:
364
+ * `sanitizeTools` gives an object with no properties an empty property list, a grammar-constrained
365
+ * server compiles that to `{}`, and without the keyword the model is left no way to pass an
366
+ * argument at all.
367
+ */
368
+ export const PROXY_TOOLS = deepFreeze([
369
+ {
370
+ type: "function",
371
+ function: {
372
+ name: LOAD_TOOLS,
373
+ description: "Get the full definitions of tools listed in the tool catalogue: what each does and the " +
374
+ "arguments it takes. Pass the exact names you need, or a trailing wildcard like " +
375
+ "`server__group__*` for a whole group. Then run them with `call_tool`. Load only what " +
376
+ "the task actually needs.",
377
+ parameters: {
378
+ type: "object",
379
+ properties: {
380
+ names: {
381
+ type: "array",
382
+ items: { type: "string" },
383
+ description: "Tool names from the catalogue. Wildcards may end with `*`.",
384
+ },
385
+ },
386
+ required: ["names"],
387
+ additionalProperties: false,
388
+ },
389
+ },
390
+ },
391
+ {
392
+ type: "function",
393
+ function: {
394
+ name: CALL_TOOL,
395
+ description: "Run a tool from the catalogue. Load it with `load_tools` first to learn its arguments, " +
396
+ "then pass its exact name and an arguments object matching its parameters.",
397
+ parameters: {
398
+ type: "object",
399
+ properties: {
400
+ name: { type: "string", description: "The tool's exact name from the catalogue." },
401
+ arguments: {
402
+ type: "object",
403
+ description: "The tool's arguments, as its definition describes them.",
404
+ additionalProperties: true,
405
+ },
406
+ },
407
+ required: ["name", "arguments"],
408
+ },
409
+ },
410
+ },
411
+ ]);
412
+ /**
413
+ * The catalogue block for a proxied run's system prompt, worded for `call_tool` rather than for a
414
+ * tool list.
415
+ *
416
+ * `catalogPrompt` tells the model a loaded tool is in its tool list, which proxied is never true —
417
+ * a model told so looks for it there and calls it natively. The listing itself is the same, and
418
+ * like that one it is never marked, so the head of the prompt is one text for the whole session.
419
+ *
420
+ * @param catalog The connected servers. A catalogue with no tools in it produces an empty string.
421
+ */
422
+ export function proxyCatalogPrompt(catalog) {
423
+ const list = catalogList(catalog);
424
+ if (!list)
425
+ return "";
426
+ return [
427
+ "# Tool catalogue",
428
+ "",
429
+ "These tools exist. Call `load_tools` with the names you need to get their definitions, then",
430
+ "run them with `call_tool`. Names are descriptive; load a tool to see its parameters. A tool",
431
+ "whose definition is already in this conversation does not need loading again. Do not load",
432
+ "tools the task does not need, and do not mention this mechanism in your answer.",
433
+ "",
434
+ list,
435
+ ].join("\n");
436
+ }
437
+ /** How a proxied load result that carries definitions opens, with the count left open. */
438
+ const PROXY_LOADED = /^Loaded \d+ tool\(s\)\. Run them with `call_tool`\./;
439
+ /**
440
+ * Whether a tool result is a proxied load carrying definitions, which is the only copy of them
441
+ * the model has.
442
+ *
443
+ * On demand the definitions are in the tool array and a load's result only repeats their
444
+ * descriptions, so clearing it loses nothing. Proxied, the result is the schema, and
445
+ * `pruneToolResults` asks this before it stubs one. Told by how `proxyLoadResult` opens, the way
446
+ * a summary is told by `SUMMARY_LEAD`, because a `tool` message carries no tool name of its own.
447
+ *
448
+ * @param result The tool message's text. A load that only pointed back or refused is not one.
449
+ */
450
+ export const holdsDefinitions = (result) => PROXY_LOADED.test(result);
451
+ /**
452
+ * What a proxied `load_tools` answers: each new tool's whole definition as a line of JSON, since
453
+ * the result is the only place the model will ever see it.
454
+ *
455
+ * A name loaded before this call is answered with a pointer back rather than its definition a
456
+ * second time, and one the catalogue lists but `definitions` does not hold is said to have none,
457
+ * so the model is not left waiting on a schema that is not coming. The refusals — too broad, over
458
+ * the per-call cap, not in the catalogue, nothing asked for — are `loadResult`'s, worded the same
459
+ * in both modes.
460
+ *
461
+ * @param resolved What the call asked for, from `expandNames`.
462
+ * @param catalog The servers, read for the refusals' wording.
463
+ * @param definitions The definitions of `resolved.matched`, as many as the host has. Ones that
464
+ * are not functions are skipped.
465
+ * @param loaded What was loaded before this call. Absent reports every match as newly loaded.
466
+ */
467
+ export function proxyLoadResult(resolved, catalog, definitions, loaded) {
468
+ const lines = [];
469
+ const again = resolved.matched.filter((name) => loaded?.has(name));
470
+ const fresh = definitions.flatMap((tool) => tool.type === "function" && !loaded?.has(tool.function.name) ? [tool.function] : []);
471
+ const defined = new Set(fresh.map((tool) => tool.name));
472
+ const missing = resolved.matched.filter((name) => !loaded?.has(name) && !defined.has(name));
473
+ if (fresh.length) {
474
+ lines.push(`Loaded ${fresh.length} tool(s). Run them with \`${CALL_TOOL}\`.`);
475
+ for (const { name, description, parameters } of fresh)
476
+ lines.push("", JSON.stringify({ name, description, parameters }));
477
+ }
478
+ if (again.length) {
479
+ if (lines.length)
480
+ lines.push("");
481
+ lines.push(`Already loaded earlier in this conversation: ${again.join(", ")}. Run them with ` +
482
+ `\`${CALL_TOOL}\`; do not load them again.`);
483
+ }
484
+ if (missing.length) {
485
+ if (lines.length)
486
+ lines.push("");
487
+ lines.push(`No definition is available for: ${missing.join(", ")}.`);
488
+ }
489
+ const { overBroad, deferred, unknown, matched } = resolved;
490
+ if (overBroad.length || deferred.length || unknown.length || !matched.length) {
491
+ if (lines.length)
492
+ lines.push("");
493
+ lines.push(loadResult({ ...resolved, matched: [] }, catalog));
494
+ }
495
+ return lines.join("\n");
496
+ }
497
+ /**
498
+ * The tool a `call_tool` names and the arguments to run it with, or a throw the model can read.
499
+ *
500
+ * `arguments` arrives as an object when the model follows the schema and as a JSON string when it
501
+ * copies the shape of a native call instead; both are taken, since the intent is the same. A name
502
+ * outside the catalogue is refused here rather than handed to a dispatcher, which is what keeps
503
+ * `call_tool` from reaching anything the catalogue does not offer.
504
+ *
505
+ * @param args The `call_tool` call's own arguments, parsed. An absent `arguments` is no arguments.
506
+ * @param catalog What may be called. The name is trimmed and then matched exactly.
507
+ */
508
+ export function proxiedCall(args, catalog) {
509
+ const name = typeof args.name === "string" ? args.name.trim() : "";
510
+ if (!name)
511
+ throw new Error(`${CALL_TOOL} needs a name; pass one from the tool catalogue.`);
512
+ if (!inCatalog(catalog, name))
513
+ throw new Error(`Not in the catalogue: ${name}. Check the name and try again.`);
514
+ let input = args.arguments ?? {};
515
+ if (typeof input === "string") {
516
+ const text = input;
517
+ try {
518
+ input = text.trim() ? JSON.parse(text) : {};
519
+ }
520
+ catch {
521
+ throw new Error(`${CALL_TOOL} arguments for ${name} are not valid JSON: ${text.slice(0, 200)}`);
522
+ }
523
+ }
524
+ if (!input || typeof input !== "object" || Array.isArray(input))
525
+ throw new Error(`${CALL_TOOL} arguments for ${name} must be an object.`);
526
+ return { name, input: input };
527
+ }
528
+ /**
529
+ * A tool call as a watcher should see it: a `call_tool` as the tool it ran, anything else as it
530
+ * is.
531
+ *
532
+ * The transcript keeps the `call_tool` the model wrote, since the next request has to repeat it
533
+ * word for word to stay in the cache; only the display looks through it. Anything that does not
534
+ * parse as a proxied call is left as it came.
535
+ *
536
+ * @param name The name the model called.
537
+ * @param input The call's arguments as JSON text.
538
+ * @returns The inner name and its arguments as JSON text — the string itself where the model
539
+ * passed `arguments` as one.
540
+ */
541
+ export function shownCall(name, input) {
542
+ if (name !== CALL_TOOL)
543
+ return { name, input };
544
+ try {
545
+ const args = JSON.parse(input);
546
+ if (typeof args.name !== "string" || !args.name.trim())
547
+ return { name, input };
548
+ const inner = args.arguments ?? {};
549
+ return {
550
+ name: args.name.trim(),
551
+ input: typeof inner === "string" ? inner : JSON.stringify(inner),
552
+ };
553
+ }
554
+ catch {
555
+ return { name, input };
556
+ }
557
+ }
343
558
  /**
344
559
  * Where a request is cut for the preselector, in characters.
345
560
  *
package/llms.txt CHANGED
@@ -15,14 +15,17 @@ The loop above a turn: send, run the tools the model asked for, send again, unti
15
15
 
16
16
  - `AgentLoopHooks` (type) — The hooks a loop runs around one question.
17
17
  - `AgentLoopOptions` (type) — What `runAgentLoop` takes.
18
+ - `AgentLoopRequest` (type) — One step's request as `onRequest` is handed it: what the model is about to read.
18
19
  - `AgentLoopResult` (type) — What a finished loop hands back.
19
20
  - `buildBody` — The one place a streamed request's body is decided from a config and what the endpoint and the model have refused.
20
21
  - `preselect` — The tools a request is likely to need, picked by a small model before the run starts, or none.
21
22
  - `preview` — A long tool argument or result cut to what a watcher needs, with the full length said.
22
23
  - `resolveApiKey` — The key to send, where an endpoint may inherit one from the settings it overrides.
23
24
  - `runAgentLoop` — Runs a question to its answer: one `runTurn` per step, the tools it asks for between them, until a turn asks for none.
25
+ - `StepWindow` (type) — How full the window is as a step is about to be sent, as `beforeStep` is told it.
24
26
  - `ToolCallOutcome` (type) — What one tool call did, in the order the model asked.
25
- - `ToolCallRequest` (type) — One call the model made, as `dispatch` is handed it.
27
+ - `ToolCallRequest` (type) — One call the model made, as `dispatch` and `onToolCall` are handed it.
28
+ - `ToolCallResult` (type) — One call's whole answer, as `onToolResult` is handed it.
26
29
 
27
30
  ### calibration
28
31
 
@@ -163,6 +166,19 @@ Lifecycle hooks, from the host's side: what a session looks like to them, where
163
166
  - `untrusted` — Fences text nobody trusted — a fetched page, an email, a submitted card, a tool result — so the model can see where it starts and ends and read it as data rather than as instructions.
164
167
  - `withContext` — The request, with the hooks' context added to this turn's question.
165
168
 
169
+ ### ledger
170
+
171
+ What stretches of a transcript cost, read off the prompt counts the server already reported.
172
+
173
+ - `estimateFrom` — A per-message cost for `planCompaction`'s `estimate`: the measured share where the ledger covers the message, the calibrated estimate where it does not.
174
+ - `LedgerEntry` (type) — One request's reported prompt, and how far into the transcript that request reached.
175
+ - `LedgerEstimateOptions` (type) — What `tokensBetween` and `estimateFrom` take besides the ledger and the transcript.
176
+ - `LedgerRequest` (type) — What `recordRequest` needs to know of one request.
177
+ - `rebaseLedger` — The ledger for a transcript that has been rewritten, keeping the boundaries the rewrite left standing.
178
+ - `recordRequest` — The ledger with one more request on it, in the epoch the request before it says it belongs to.
179
+ - `TokenLedger` (type) — A transcript's entries in the order their requests were sent, which is also by `through`.
180
+ - `tokensBetween` — What the messages from `from` up to, not including, `to` cost the window, measured where the ledger can say and estimated where it cannot.
181
+
166
182
  ### reset
167
183
 
168
184
  - `resetAll` — Forgets everything this package remembers between calls.
@@ -300,10 +316,12 @@ Reading what a model meant by a tool call when it did not write one cleanly.
300
316
 
301
317
  ### tool-loading
302
318
 
319
+ - `CALL_TOOL` — The one tool a proxied run reaches every catalogued tool through.
303
320
  - `carryOver` — The tools to start the next turn with: last turn's where they were, then what this turn used.
304
321
  - `catalogList` — The catalogue as a plain grouped listing of names, loaded ones marked if asked.
305
322
  - `catalogPrompt` — The catalogue block appended to the system prompt.
306
323
  - `expandNames` — Resolves requested names against the catalogue, expanding trailing `*` wildcards.
324
+ - `holdsDefinitions` — Whether a tool result is a proxied load carrying definitions, which is the only copy of them the model has.
307
325
  - `inCatalog` — Whether the catalogue holds a tool by this name.
308
326
  - `KEYWORD_DROPOFF` — How far the best unpicked tool must fall below the last picked one for the cut to count clean.
309
327
  - `KEYWORD_MIN_SCORE` — The least a best match may score and still be acted on without a model.
@@ -318,10 +336,15 @@ Reading what a model meant by a tool call when it did not write one cleanly.
318
336
  - `orderTools` — The tool array in a stable order, so the same set of tools renders the same way twice.
319
337
  - `PRESELECT_SCHEMA` — The shape a preselector's answer is held to where the server takes a schema: `{ tools: [...] }`.
320
338
  - `PRESELECT_SYSTEM` — The preselection system prompt at the default cap, for a caller that never changes it.
339
+ - `PROXY_TOOLS` — The whole tool array of a proxied run, `load_tools` then `call_tool`, frozen because it is shared.
321
340
  - `preselectByKeywords` — The tools a request's own words point at, ranked, and whether they point clearly enough.
322
341
  - `preselectInput` — The user message for a preselection call: the catalogue, then the request.
323
342
  - `preselection` — Resolves a preselection against the catalogue: unknown names dropped, count capped.
324
343
  - `preselectSystem` — The system prompt a preselector is given, holding it to the cap its answer will be held to.
344
+ - `proxiedCall` — The tool a `call_tool` names and the arguments to run it with, or a throw the model can read.
345
+ - `proxyCatalogPrompt` — The catalogue block for a proxied run's system prompt, worded for `call_tool` rather than for a tool list.
346
+ - `proxyLoadResult` — What a proxied `load_tools` answers: each new tool's whole definition as a line of JSON, since the result is the only place the model will ever see it.
325
347
  - `requestedNames` — `load_tools` arguments, defensively — a model may send a bare string or a nested object.
348
+ - `shownCall` — A tool call as a watcher should see it: a `call_tool` as the tool it ran, anything else as it is.
326
349
  - `ToolMatch` (type) — One tool's score against a request.
327
350
  - `ToolOrder` (type) — How a tool array is ordered before it is sent: `true` by name, `false` as the caller built it, or a comparator over the two names.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cubicecho/agent-core",
3
- "version": "2.18.1",
3
+ "version": "2.20.0",
4
4
  "description": "The endpoint-agnostic half of an OpenAI-compatible agent loop: tool-schema compatibility, on-demand tool loading, one-shot side tasks, run events, and a pooled client.",
5
5
  "keywords": [
6
6
  "openai",