akanjs 3.3.0-rc.73 → 3.3.0-rc.75

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "akanjs",
3
- "version": "3.3.0-rc.73",
3
+ "version": "3.3.0-rc.75",
4
4
  "sourceType": "module",
5
5
  "type": "module",
6
6
  "publishConfig": {
@@ -13,6 +13,8 @@ import type {
13
13
  LlmTurnRequest,
14
14
  LlmUsage,
15
15
  } from "../predefinedAdaptor/llm.adaptor";
16
+ import { LlmContext } from "../predefinedAdaptor/llmContext";
17
+ import { LlmFence } from "../predefinedAdaptor/llmFence";
16
18
  import type {
17
19
  AgentLoopApproval,
18
20
  AgentLoopCallAnswer,
@@ -25,6 +27,7 @@ import { LoopAnswer, type LoopPark } from "./loopAnswer";
25
27
  import { LoopAsk } from "./loopAsk";
26
28
  import { LoopCompaction } from "./loopCompaction";
27
29
  import { LoopContext } from "./loopContext";
30
+ import { LoopLent } from "./loopLent";
28
31
  import { LoopRemotes } from "./loopRemotes";
29
32
  import { LoopRequest } from "./loopRequest";
30
33
  import { LoopStored } from "./loopStored";
@@ -80,7 +83,7 @@ export class AgentLoop {
80
83
  readonly #remotes: LoopRemotes;
81
84
  readonly #toolkits: LoopToolkits;
82
85
  readonly #askUser: LoopAsk;
83
- #clientNames = new Set<string>();
86
+ readonly #lent = new LoopLent();
84
87
  #account: unknown = null;
85
88
  #round = 0;
86
89
  #tokens = 0;
@@ -149,13 +152,16 @@ export class AgentLoop {
149
152
 
150
153
  async *#runRound(): Events<AgentLoopStop | null> {
151
154
  const listed = await this.#listTools();
155
+ await this.#pinContext();
152
156
  const compacted = yield* this.#compact(listed);
153
157
  const { answer, tools } = yield* this.#ask(compacted ?? listed);
154
-
158
+
155
159
  const mark = this.#tainted ? { tainted: true } : {};
160
+ const tracks = this.#toolkits.tracksListing || this.#lent.tracks(this.#messages);
161
+ const shown = tracks ? this.#lent.listingOf(tools, this.#messages) : {};
156
162
  if (answer.stop === "length") {
157
163
 
158
- if (answer.text) await this.#append({ role: "assistant", text: answer.text, ...mark });
164
+ if (answer.text) await this.#append({ role: "assistant", text: answer.text, ...shown, ...mark });
159
165
  return "length";
160
166
  }
161
167
  const message: AgentWireMessage = {
@@ -163,6 +169,7 @@ export class AgentLoop {
163
169
  ...(answer.text ? { text: answer.text } : {}),
164
170
  ...(answer.toolCalls.length ? { toolCalls: answer.toolCalls } : {}),
165
171
  ...(answer.providerContent ? { providerContent: answer.providerContent } : {}),
172
+ ...shown,
166
173
  ...mark,
167
174
  };
168
175
  if (LoopTranscript.carries(message)) await this.#append(message);
@@ -184,13 +191,14 @@ export class AgentLoop {
184
191
  const listed = this.#toolkits.listed(visible);
185
192
  const taken = new Set(visible.map((tool) => tool.name));
186
193
 
194
+ const free = (name: string) =>
195
+ !taken.has(name) && !this.#toolkits.isMeta(name) && !this.#askUser.isMeta(name) && !this.#remotes.ownerOf(name);
187
196
  const client = (this.#request.clientTools ?? []).filter((tool) => {
188
- if (taken.has(tool.name) || this.#toolkits.isMeta(tool.name) || this.#askUser.isMeta(tool.name)) return false;
189
- if (this.#remotes.ownerOf(tool.name)) return false;
197
+ if (!free(tool.name)) return false;
190
198
  taken.add(tool.name);
191
199
  return true;
192
200
  });
193
- this.#clientNames = new Set(client.map((tool) => tool.name));
201
+ this.#lent.lend(client, this.#messages, free);
194
202
  this.#judgeStored(visible);
195
203
  return [...listed, ...remote.tools, ...client.map(AgentLoop.#clientTool), ...this.#askUser.listed()];
196
204
  }
@@ -223,8 +231,16 @@ export class AgentLoop {
223
231
  };
224
232
  }
225
233
 
234
+ async #pinContext() {
235
+ const { context = [] } = this.#request;
236
+ const text = LlmContext.of(context);
237
+ if (!text || this.#messages.findLast((message) => message.context)?.text === text) return;
238
+ await this.#append({ role: "user", text, context: true, ...(LlmFence.marks(context) ? { tainted: true } : {}) });
239
+ }
240
+
226
241
  async *#ask(listed: AgentTool[]): Events<{ answer: AgentLoopAnswer; tools: AgentTool[] }> {
227
242
  const preamble = this.#request.preamble ?? false;
243
+ await this.#pinContext();
228
244
  const request = this.#turnOf(listed);
229
245
  let tools = listed;
230
246
  try {
@@ -237,21 +253,27 @@ export class AgentLoop {
237
253
  if (!compacted) throw error;
238
254
  tools = compacted;
239
255
  }
256
+ await this.#pinContext();
240
257
  return { answer: yield* this.#metered(this.#turnOf(tools), preamble, true), tools };
241
258
  }
242
259
 
243
260
  #turnOf(tools: AgentTool[]): LlmTurnRequest {
244
- const { context = [], model, preamble } = this.#request;
261
+ const { model, preamble } = this.#request;
245
262
  const instructions = [
246
263
  this.#request.instructions || (preamble ? "" : AgentLoop.noInstructions),
247
264
  ...this.#toolkits.pinnedInstructions(),
248
265
  ]
249
266
  .filter(Boolean)
250
267
  .join("\n\n");
268
+ const deferred = [
269
+ ...this.#toolkits.deferred(tools).map(({ readOnly: _readOnly, ...tool }) => tool),
270
+ ...this.#lent.left,
271
+ ];
251
272
  return {
252
- messages: LoopTranscript.wire(this.#messages),
273
+ messages: LoopLent.unlent(LoopTranscript.wire(this.#messages)),
253
274
  tools: tools.map(({ readOnly: _readOnly, ...tool }) => tool),
254
- context,
275
+ context: [],
276
+ ...(deferred.length ? { deferred } : {}),
255
277
  ...(instructions ? { instructions } : {}),
256
278
  ...(model ? { model } : {}),
257
279
  };
@@ -370,7 +392,7 @@ export class AgentLoop {
370
392
  stop = "awaiting";
371
393
  break;
372
394
  }
373
- if (verdict === "allow" && this.#clientNames.has(call.name)) {
395
+ if (verdict === "allow" && this.#lent.has(call.name)) {
374
396
  this.#toolCalls += 1;
375
397
  yield { type: "awaiting", call, client: true };
376
398
  stop = "awaiting";
@@ -408,7 +430,7 @@ export class AgentLoop {
408
430
  async *#accept(answer: AgentLoopCallAnswer): Events<void> {
409
431
  const whole = LoopAnswer.resultOf(answer, this.#messages, (call) => this.#parks(call));
410
432
  const result = LoopToolOutput.clipped(whole);
411
- if (this.#clientNames.has(whole.name)) this.#tainted = true;
433
+ if (this.#lent.has(whole.name)) this.#tainted = true;
412
434
  await this.#record([result]);
413
435
  yield { type: "toolResult", result, round: this.#round };
414
436
  }
@@ -417,7 +439,7 @@ export class AgentLoop {
417
439
  if (call.argsError) return null;
418
440
  const kit = this.#toolkits.externalOf(call);
419
441
  if (kit) return { refusal: LoopRemotes.declined(kit), code: LoopRemotes.declinedCode };
420
- const parked = this.#askUser.isMeta(call.name) ? !LoopAsk.refusalOf(call) : this.#clientNames.has(call.name);
442
+ const parked = this.#askUser.isMeta(call.name) ? !LoopAsk.refusalOf(call) : this.#lent.has(call.name);
421
443
  return parked ? "answer" : null;
422
444
  }
423
445
 
@@ -456,7 +478,7 @@ export class AgentLoop {
456
478
  const state = {
457
479
  tainted: this.#tainted,
458
480
  tool,
459
- ...(this.#clientNames.has(call.name) ? { client: true as const } : {}),
481
+ ...(this.#lent.has(call.name) ? { client: true as const } : {}),
460
482
  ...(remote ? { remote } : {}),
461
483
  };
462
484
  if (approve) return AgentLoop.#judged(await this.#untilHalted(approve(call, state)));
@@ -1,4 +1,5 @@
1
1
  import type { AgentWireAttachment, AgentWireMessage, LlmTurnRequest } from "../predefinedAdaptor/llm.adaptor";
2
+ import { LoopLent } from "./loopLent";
2
3
  import { LoopTranscript } from "./loopTranscript";
3
4
 
4
5
  export class LoopCompaction {
@@ -16,11 +17,11 @@ export class LoopCompaction {
16
17
 
17
18
  static tokensOf(messages: readonly AgentWireMessage[]): number {
18
19
  let chars = 0;
19
- for (const message of LoopTranscript.seen(messages)) chars += LoopCompaction.#charsOf(message);
20
+ for (const message of LoopLent.unlent(LoopTranscript.seen(messages))) chars += LoopCompaction.#charsOf(message);
20
21
  return Math.ceil(chars / 4);
21
22
  }
22
23
 
23
- static frameTokensOf({ messages: _messages, ...frame }: LlmTurnRequest): number {
24
+ static frameTokensOf({ messages: _messages, deferred: _deferred, ...frame }: LlmTurnRequest): number {
24
25
  return Math.ceil(JSON.stringify(frame).length / 4);
25
26
  }
26
27
 
@@ -80,7 +81,10 @@ export class LoopCompaction {
80
81
  const previous = messages
81
82
  .filter((message) => message.summary)
82
83
  .map((message) => `previous summary:\n${message.text ?? ""}`);
83
- const lines = messages.filter((message) => !message.summary).map((message) => LoopCompaction.#line(message));
84
+
85
+ const lines = messages
86
+ .filter((message) => !message.summary && !message.context)
87
+ .map((message) => LoopCompaction.#line(message));
84
88
  return [...previous, LoopCompaction.#fit(lines, budget)].filter(Boolean).join("\n");
85
89
  }
86
90
 
@@ -16,8 +16,11 @@ export class LoopContext {
16
16
  }
17
17
 
18
18
  static carried(request: AgentLoopRequest, messages: readonly AgentWireMessage[]): boolean {
19
- if (LoopContext.marked(request) || messages.some((message) => !!message.references?.length)) return true;
20
- const first = messages.find(({ role, summary, tainted }) => role === "tool" || summary || tainted);
19
+ if (LoopContext.marked(request)) return true;
20
+ if (messages.some((message) => !!message.references?.length || (message.context && message.tainted))) return true;
21
+ const first = messages.find(
22
+ ({ role, summary, tainted, context }) => !context && (role === "tool" || summary || tainted),
23
+ );
21
24
  return first?.role === "assistant" && !first.summary;
22
25
  }
23
26
 
@@ -0,0 +1,80 @@
1
+ import type { AgentWireMessage, AgentWireTool } from "../predefinedAdaptor/llm.adaptor";
2
+ import { LoopRequest } from "./loopRequest";
3
+
4
+ export class LoopLent {
5
+ #names = new Set<string>();
6
+ #left: AgentWireTool[] = [];
7
+
8
+ lend(lent: readonly AgentWireTool[], messages: readonly AgentWireMessage[], free: (name: string) => boolean) {
9
+ this.#names = new Set(lent.map((tool) => tool.name));
10
+ this.#left = LoopLent.stored(messages).filter((tool) => !this.#names.has(tool.name) && free(tool.name));
11
+ }
12
+
13
+ has(name: string): boolean {
14
+ return this.#names.has(name);
15
+ }
16
+
17
+ get left(): readonly AgentWireTool[] {
18
+ return this.#left;
19
+ }
20
+
21
+ tracks(messages: readonly AgentWireMessage[]): boolean {
22
+ return this.#names.size > 0 || messages.some((message) => message.listed);
23
+ }
24
+
25
+ listingOf(tools: readonly AgentWireTool[], messages: readonly AgentWireMessage[]) {
26
+ const lent = LoopLent.fresh(
27
+ tools.filter((tool) => this.#names.has(tool.name)),
28
+ messages,
29
+ );
30
+ return { listed: tools.map((tool) => tool.name), ...(lent.length ? { lent } : {}) };
31
+ }
32
+
33
+ static definition({ name, description, parameters }: AgentWireTool): AgentWireTool {
34
+ return { name, ...(description ? { description } : {}), ...(parameters ? { parameters } : {}) };
35
+ }
36
+
37
+ static stored(messages: readonly AgentWireMessage[]): AgentWireTool[] {
38
+ const latest = new Map<string, AgentWireTool>();
39
+ for (const message of messages)
40
+ for (const tool of Array.isArray(message.lent) ? message.lent : [])
41
+ if (LoopLent.#valid(tool)) {
42
+ latest.delete(tool.name);
43
+ latest.set(tool.name, LoopLent.definition(tool));
44
+ }
45
+ const kept: AgentWireTool[] = [];
46
+ let chars = 0;
47
+ for (const tool of [...latest.values()].reverse()) {
48
+ chars += JSON.stringify(tool).length;
49
+ if (kept.length >= LoopRequest.maxClientTools || chars > LoopRequest.maxClientToolChars) break;
50
+ kept.push(tool);
51
+ }
52
+ return kept.reverse();
53
+ }
54
+
55
+ static unlent(messages: AgentWireMessage[]): AgentWireMessage[] {
56
+ return messages.map((message) => {
57
+ if (!message.lent) return message;
58
+ const { lent: _lent, ...rest } = message;
59
+ return rest;
60
+ });
61
+ }
62
+
63
+ static fresh(lent: readonly AgentWireTool[], messages: readonly AgentWireMessage[]): AgentWireTool[] {
64
+ const known = new Map(LoopLent.stored(messages).map((tool) => [tool.name, JSON.stringify(tool)]));
65
+ return lent
66
+ .map((tool) => LoopLent.definition(tool))
67
+ .filter((tool) => known.get(tool.name) !== JSON.stringify(tool));
68
+ }
69
+
70
+ static #valid(tool: unknown): tool is AgentWireTool {
71
+ const { name, description, parameters } = (tool ?? {}) as Record<string, unknown>;
72
+ return (
73
+ typeof name === "string" &&
74
+ !!name &&
75
+ (description === undefined || typeof description === "string") &&
76
+ (parameters === undefined ||
77
+ (typeof parameters === "object" && parameters !== null && !Array.isArray(parameters)))
78
+ );
79
+ }
80
+ }
@@ -65,9 +65,19 @@ export class LoopToolkits {
65
65
  this.#unlist(over, loaded);
66
66
  ({ shown } = this.#arrange());
67
67
  }
68
- const closed = this.#closed();
69
- const searchable = this.#search && this.#unlisted(shown).length ? [this.#search.tool()] : [];
70
- return [...shown, ...(closed.length ? [this.#metaTool(closed)] : []), ...searchable];
68
+ const offered = this.#offered();
69
+ const searchable = this.#search ? [this.#search.tool()] : [];
70
+ return [...shown, ...(offered.length ? [this.#metaTool(offered)] : []), ...searchable];
71
+ }
72
+
73
+ deferred(listed: readonly AgentTool[]): AgentTool[] {
74
+ if (!this.#any) return [];
75
+ const names = new Set(listed.map((tool) => tool.name));
76
+ return this.#visible.filter((tool) => this.#inKit(tool.name) && !names.has(tool.name));
77
+ }
78
+
79
+ get tracksListing(): boolean {
80
+ return this.#any;
71
81
  }
72
82
 
73
83
  #arrange(): Arranged {
@@ -246,6 +256,14 @@ export class LoopToolkits {
246
256
  return this.#visible.filter((tool) => tools.includes(tool.name)).map((tool) => tool.name);
247
257
  }
248
258
 
259
+ #offered(): string[] {
260
+ const pinned = (kit: string) => this.#pinned.some((entry) => entry.kind === "kit" && entry.name === kit);
261
+ return [
262
+ ...[...this.#kits.keys()].filter((kit) => !pinned(kit) && this.#toolsOf(kit).length),
263
+ ...this.#external.keys(),
264
+ ];
265
+ }
266
+
249
267
  #closed(): string[] {
250
268
  const partial = (kit: string) => this.#toolsOf(kit).some((tool) => this.#evicted.has(tool));
251
269
  return [
@@ -256,8 +274,8 @@ export class LoopToolkits {
256
274
  ];
257
275
  }
258
276
 
259
- #metaTool(closed: string[]): AgentTool {
260
- const lines = closed.map((kit) =>
277
+ #metaTool(offered: string[]): AgentTool {
278
+ const lines = offered.map((kit) =>
261
279
  `- ${kit}: ${this.#kits.get(kit)?.description ?? this.#external.get(kit) ?? ""}`.trimEnd(),
262
280
  );
263
281
  return {
@@ -269,7 +287,7 @@ export class LoopToolkits {
269
287
  ].join("\n"),
270
288
  parameters: {
271
289
  type: "object",
272
- properties: { name: { type: "string", enum: closed } },
290
+ properties: { name: { type: "string", enum: offered } },
273
291
  required: ["name"],
274
292
  additionalProperties: false,
275
293
  },
@@ -13,7 +13,7 @@ export class LoopTranscript {
13
13
  }
14
14
 
15
15
  static seen(messages: readonly AgentWireMessage[]): AgentWireMessage[] {
16
- const latest = messages.findLastIndex((message) => message.role === "user" && !message.summary);
16
+ const latest = messages.findLastIndex((message) => message.role === "user" && !message.summary && !message.context);
17
17
  if (latest <= 0) return [...messages];
18
18
  return messages.map((message, at) =>
19
19
  at < latest && message.toolResults?.some(LoopTranscript.#carriesFile)
@@ -1,5 +1,7 @@
1
+ import { createHash } from "node:crypto";
1
2
  import { FailureCode } from "akanjs/common";
2
3
  import { adapt } from "../adapt";
4
+ import { type AnthropicToolMessage, AnthropicTools } from "./anthropicTools";
3
5
  import {
4
6
  type AgentWireAttachment,
5
7
  type AgentWireContext,
@@ -39,6 +41,7 @@ interface AnthropicMessage {
39
41
  role: "user" | "assistant";
40
42
  content: AnthropicBlock[];
41
43
  }
44
+ type AnthropicTurn = AnthropicMessage | AnthropicToolMessage;
42
45
  interface AnthropicUsage {
43
46
  input_tokens?: number;
44
47
  output_tokens?: number;
@@ -84,10 +87,19 @@ interface AnthropicStreamEvent {
84
87
  };
85
88
  }
86
89
 
90
+ export type AnthropicRequestBody = ReturnType<typeof AnthropicLlm.requestBody>;
91
+
92
+ export interface AnthropicLlmOption extends LlmOption {
93
+ /** Has the last word on each body, after the retries chose its form: a `cache_control` breakpoint, an `effort`. */
94
+ body?: (body: AnthropicRequestBody, request: LlmTurnRequest) => AnthropicRequestBody & Record<string, unknown>;
95
+ /** `anthropic-beta` values what `body` adds needs, sent beside the ones a retry adds. */
96
+ betas?: string[];
97
+ }
98
+
87
99
  /** Anthropic's Messages API, which reads images and PDFs. `model` is required and has no default. */
88
100
  export class AnthropicLlm
89
101
  extends adapt("akanAnthropicLlm" as const, ({ use }) => ({
90
- llmOption: use<LlmOption>(),
102
+ llmOption: use<AnthropicLlmOption>(),
91
103
  }))
92
104
  implements LlmAdaptor
93
105
  {
@@ -106,7 +118,18 @@ export class AnthropicLlm
106
118
  /** The API refuses `thinking.block_binding` without it. */
107
119
  static readonly thinkingBindingBeta = "thinking-binding-controls-2026-08-01";
108
120
 
109
- readonly #historyChecked = new Set<string>();
121
+ static readonly #droppedLimit = 500;
122
+
123
+ readonly #dropped = new Set<string>();
124
+ readonly #plainTools = new Set<string>();
125
+
126
+ /**
127
+ * One with settings of its own, beside `option.setLlm`: an app's adaptor sending some turns here under another key
128
+ * keeps the retries, and what they learned about each model and conversation, by keeping the instance.
129
+ */
130
+ static of(option: AnthropicLlmOption): AnthropicLlm {
131
+ return Object.assign(new AnthropicLlm(), { llmOption: option });
132
+ }
110
133
 
111
134
  get #host() {
112
135
  return this.llmOption.host ?? "https://api.anthropic.com/v1";
@@ -135,11 +158,15 @@ export class AnthropicLlm
135
158
  }
136
159
  try {
137
160
  const { accepts } = this;
138
- const maxTokens = this.llmOption.maxTokens;
161
+ const { maxTokens, body } = this.llmOption;
139
162
  const stream = !!onDelta;
140
163
  const response = await this.#send(
141
164
  model,
142
- (thinking) => AnthropicLlm.requestBody(model, request, { accepts, stream, maxTokens, thinking }),
165
+ AnthropicLlm.#conversationOf(request.messages),
166
+ (thinking, toolChanges) => {
167
+ const built = AnthropicLlm.requestBody(model, request, { accepts, stream, maxTokens, thinking, toolChanges });
168
+ return body ? body(built, request) : built;
169
+ },
143
170
  signal,
144
171
  );
145
172
  if (!onDelta)
@@ -177,40 +204,88 @@ export class AnthropicLlm
177
204
 
178
205
  async #send(
179
206
  model: string,
180
- bodyOf: (thinking?: AnthropicThinkingReplay) => { messages: AnthropicMessage[] },
207
+ conversation: string | null,
208
+ bodyOf: (thinking: AnthropicThinkingReplay | undefined, toolChanges: boolean) => AnthropicRequestBody,
181
209
  signal?: AbortSignal,
182
210
  ): Promise<Response> {
183
- let thinking: AnthropicThinkingReplay | undefined = this.#historyChecked.has(model) ? "drop" : undefined;
211
+ let thinking: AnthropicThinkingReplay | undefined =
212
+ conversation && this.#dropped.has(conversation) ? "drop" : undefined;
213
+ let toolChanges = !this.#plainTools.has(model);
214
+ let unproven: string | null = null;
184
215
  for (;;) {
185
- const body = bodyOf(thinking);
216
+ const body = bodyOf(thinking, toolChanges);
217
+ const engaged = AnthropicTools.engaged(body);
218
+ const betas = [
219
+ ...new Set([
220
+ ...(thinking === "drop" ? [AnthropicLlm.thinkingBindingBeta] : []),
221
+ ...(engaged ? [AnthropicTools.beta] : []),
222
+ ...(this.llmOption.betas ?? []),
223
+ ]),
224
+ ];
186
225
  const response: Response = await fetch(`${this.#host}/messages`, {
187
226
  method: "POST",
188
- headers:
189
- thinking === "drop"
190
- ? { ...this.#headers, "anthropic-beta": AnthropicLlm.thinkingBindingBeta }
191
- : this.#headers,
227
+ headers: betas.length ? { ...this.#headers, "anthropic-beta": betas.join(",") } : this.#headers,
192
228
  body: JSON.stringify(body),
193
229
  signal: llmCallSignal(signal),
194
230
  });
195
- if (response.ok) return response;
231
+ if (response.ok) {
232
+ if (unproven) this.#sendPlain(model, unproven);
233
+ return response;
234
+ }
196
235
  const reason = await AnthropicLlm.reasonOf(response);
197
236
  const retry: AnthropicThinkingReplay | null =
198
237
  response.status === 400 && (thinking === "drop" || AnthropicLlm.replaysThinking(body.messages))
199
238
  ? AnthropicLlm.thinkingRetry(thinking, reason)
200
239
  : null;
240
+ if (response.status === 400 && engaged && !(retry && /thinking|block_binding/i.test(reason))) {
241
+ unproven = reason;
242
+ toolChanges = false;
243
+ continue;
244
+ }
201
245
  if (!retry) throw LlmOverflow.refusal(this.#host, response.status, reason);
202
- if (retry === "drop") this.#historyChecked.add(model);
246
+ if (retry === "drop" && conversation) this.#remember(conversation);
203
247
  thinking = retry;
204
248
  }
205
249
  }
206
250
 
251
+ #sendPlain(model: string, reason: string) {
252
+ this.#plainTools.add(model);
253
+ this.logger.warn(
254
+ `Anthropic refused declared tool changes for ${model} (${reason}), so its turns list the shown tools alone.`,
255
+ );
256
+ }
257
+
258
+ #remember(conversation: string) {
259
+ this.#dropped.delete(conversation);
260
+ this.#dropped.add(conversation);
261
+ const oldest = this.#dropped.values().next().value;
262
+ if (this.#dropped.size > AnthropicLlm.#droppedLimit && oldest) this.#dropped.delete(oldest);
263
+ }
264
+
265
+ static #conversationOf(messages: readonly AgentWireMessage[]): string | null {
266
+ for (const message of messages) {
267
+ if (message.providerContent?.dialect !== AnthropicLlm.dialect || !Array.isArray(message.providerContent.content))
268
+ continue;
269
+ for (const block of message.providerContent.content as (AnthropicAnswerBlock | null)[]) {
270
+ const signed =
271
+ block?.type === "thinking" ? block.signature : block?.type === "redacted_thinking" ? block.data : "";
272
+ if (signed) return createHash("sha256").update(signed).digest("hex");
273
+ }
274
+ }
275
+ return null;
276
+ }
277
+
278
+ static #bound(reason: string): boolean {
279
+ return /block_binding|different conversation/i.test(reason);
280
+ }
281
+
207
282
  static thinkingRetry(sent: AnthropicThinkingReplay | undefined, reason: string): AnthropicThinkingReplay | null {
208
283
  if (sent === "strip") return null;
209
- if (!sent && /block_binding|different conversation/i.test(reason)) return "drop";
284
+ if (!sent && AnthropicLlm.#bound(reason)) return "drop";
210
285
  return /thinking|beta/i.test(reason) ? "strip" : null;
211
286
  }
212
287
 
213
- static replaysThinking(messages: AnthropicMessage[]): boolean {
288
+ static replaysThinking(messages: readonly { content: readonly { type: string }[] }[]): boolean {
214
289
  return messages.some((message) =>
215
290
  message.content.some((block) => block.type === "thinking" || block.type === "redacted_thinking"),
216
291
  );
@@ -231,7 +306,10 @@ export class AnthropicLlm
231
306
  return response.statusText || "no reason given";
232
307
  }
233
308
 
234
- /** `thinking: "drop"` needs `thinkingBindingBeta` in the `anthropic-beta` header. */
309
+ /**
310
+ * `thinking: "drop"` needs `thinkingBindingBeta` in the `anthropic-beta` header, and a body that declares tools
311
+ * ahead (`AnthropicTools.engaged`) needs `AnthropicTools.beta`; `toolChanges: false` lists `request.tools` alone.
312
+ */
235
313
  static requestBody(
236
314
  model: string,
237
315
  request: LlmTurnRequest,
@@ -240,7 +318,14 @@ export class AnthropicLlm
240
318
  stream,
241
319
  maxTokens,
242
320
  thinking,
243
- }: { accepts?: LlmAccepts; stream?: boolean; maxTokens?: number; thinking?: AnthropicThinkingReplay } = {},
321
+ toolChanges = true,
322
+ }: {
323
+ accepts?: LlmAccepts;
324
+ stream?: boolean;
325
+ maxTokens?: number;
326
+ thinking?: AnthropicThinkingReplay;
327
+ toolChanges?: boolean;
328
+ } = {},
244
329
  ) {
245
330
  const messages =
246
331
  thinking === "strip"
@@ -248,6 +333,7 @@ export class AnthropicLlm
248
333
  message.providerContent ? { ...message, providerContent: undefined } : message,
249
334
  )
250
335
  : request.messages;
336
+ const { tools, turns } = AnthropicLlm.#listing(request, messages, accepts, toolChanges);
251
337
  return {
252
338
  model,
253
339
  max_tokens: maxTokens ?? AnthropicLlm.defaultMaxTokens,
@@ -256,18 +342,56 @@ export class AnthropicLlm
256
342
  ? { thinking: { type: "adaptive", block_binding: { prefix_mismatch_behavior: "drop_block" } } }
257
343
  : {}),
258
344
  system: AnthropicLlm.systemPrompt(request),
259
- messages: AnthropicLlm.contextual(AnthropicLlm.providerMessages(messages, accepts), request.context),
260
- ...(request.tools.length
261
- ? {
262
- tools: request.tools.map((tool) => ({
263
- name: tool.name,
264
- ...(tool.description ? { description: tool.description } : {}),
265
-
266
- input_schema: tool.parameters ?? { type: "object", properties: {} },
267
- })),
268
- }
269
- : {}),
345
+ messages: turns,
346
+ ...(tools.length ? { tools } : {}),
347
+ };
348
+ }
349
+
350
+ static #listing(
351
+ request: LlmTurnRequest,
352
+ messages: AgentWireMessage[],
353
+ accepts: LlmAccepts | undefined,
354
+ toolChanges: boolean,
355
+ ) {
356
+ const plain = () => ({
357
+ tools: request.tools.map((tool) => AnthropicTools.definition(tool)),
358
+ turns: AnthropicLlm.contextual(
359
+ AnthropicLlm.providerMessages(messages, accepts),
360
+ request.context,
361
+ ) as AnthropicTurn[],
362
+ });
363
+ if (!toolChanges || (!request.deferred?.length && !messages.some((message) => message.listed))) return plain();
364
+ const declared = AnthropicTools.declared(request);
365
+ const shown = request.tools.map((tool) => tool.name);
366
+ const names = new Set(declared.map((tool) => tool.name));
367
+ const { turns, base, announced } = AnthropicLlm.#turns(messages, accepts, names);
368
+ const first = base ?? shown;
369
+ if (!declared.some((tool) => first.includes(tool.name))) return plain();
370
+ const rank = (name: string) => {
371
+ const at = first.indexOf(name);
372
+ return at < 0 ? first.length : at;
270
373
  };
374
+ const ordered = [...declared].sort(
375
+ (a, b) => rank(a.name) - rank(b.name) || (a.name < b.name ? -1 : a.name > b.name ? 1 : 0),
376
+ );
377
+ const sent = AnthropicLlm.contextual(turns as AnthropicMessage[], request.context) as AnthropicTurn[];
378
+ if (announced) AnthropicLlm.#announce(sent, announced, new Set(shown), names);
379
+ return { tools: ordered.map((tool) => AnthropicTools.definition(tool, !first.includes(tool.name))), turns: sent };
380
+ }
381
+
382
+ static #announce(
383
+ turns: AnthropicTurn[],
384
+ from: ReadonlySet<string>,
385
+ to: ReadonlySet<string>,
386
+ declared: ReadonlySet<string>,
387
+ ): ReadonlySet<string> {
388
+ const changes = AnthropicTools.changes(from, to, declared);
389
+ if (!changes.length) return to;
390
+ const last = turns.at(-1);
391
+ if (last?.role === "system") last.content.push(...changes);
392
+ else if (last?.role === "user") turns.push({ role: "system", content: changes });
393
+ else return from;
394
+ return to;
271
395
  }
272
396
 
273
397
  static systemPrompt({ instructions }: Pick<LlmTurnRequest, "instructions">): string {
@@ -288,18 +412,29 @@ export class AnthropicLlm
288
412
 
289
413
  /** The API takes strictly alternating roles, so tool results and the user's next ask merge into one user turn. */
290
414
  static providerMessages(messages: AgentWireMessage[], accepts?: LlmAccepts): AnthropicMessage[] {
291
- const merged: AnthropicMessage[] = [];
415
+ return AnthropicLlm.#turns(messages, accepts, null).turns as AnthropicMessage[];
416
+ }
417
+
418
+ static #turns(messages: AgentWireMessage[], accepts: LlmAccepts | undefined, declared: ReadonlySet<string> | null) {
419
+ const merged: AnthropicTurn[] = [];
420
+ let base: string[] | null = null;
421
+ let announced: ReadonlySet<string> | null = null;
292
422
  for (const message of messages) {
293
423
  const mapped = AnthropicLlm.providerMessage(message, accepts);
294
424
  if (!mapped.content.length) continue;
295
- const last = merged[merged.length - 1];
296
- if (last?.role === mapped.role) last.content.push(...mapped.content);
425
+ if (declared && mapped.role === "assistant" && message.listed) {
426
+ const now = new Set(message.listed);
427
+ if (!announced) base = [...message.listed];
428
+ announced = announced ? AnthropicLlm.#announce(merged, announced, now, declared) : now;
429
+ }
430
+ const last = merged.at(-1);
431
+ if (last && last.role !== "system" && last.role === mapped.role) last.content.push(...mapped.content);
297
432
  else merged.push(mapped);
298
433
  }
299
434
 
300
435
  if (merged[0]?.role === "assistant") merged.shift();
301
- if (merged[merged.length - 1]?.role === "assistant") merged.pop();
302
- return merged;
436
+ if (merged.at(-1)?.role === "assistant") merged.pop();
437
+ return { turns: merged, base, announced };
303
438
  }
304
439
 
305
440
  static providerMessage(message: AgentWireMessage, accepts?: LlmAccepts): AnthropicMessage {
@@ -0,0 +1,56 @@
1
+ import type { AgentWireTool, LlmTurnRequest } from "./llm.adaptor";
2
+
3
+ export interface AnthropicToolChange {
4
+ type: "tool_addition" | "tool_removal";
5
+ tool: { type: "tool_reference"; name: string };
6
+ }
7
+ export interface AnthropicToolMessage {
8
+ role: "system";
9
+ content: AnthropicToolChange[];
10
+ }
11
+ export interface AnthropicTool {
12
+ name: string;
13
+ description?: string;
14
+ input_schema: Record<string, unknown>;
15
+ defer_loading?: true;
16
+ }
17
+
18
+ export class AnthropicTools {
19
+ static readonly beta = "mid-conversation-tool-changes-2026-07-01";
20
+
21
+ static definition(tool: AgentWireTool, deferred = false): AnthropicTool {
22
+ return {
23
+ name: tool.name,
24
+ ...(tool.description ? { description: tool.description } : {}),
25
+
26
+ input_schema: tool.parameters ?? { type: "object", properties: {} },
27
+ ...(deferred ? { defer_loading: true as const } : {}),
28
+ };
29
+ }
30
+
31
+ static declared({ tools, deferred = [] }: Pick<LlmTurnRequest, "tools" | "deferred">): AgentWireTool[] {
32
+ const seen = new Set<string>();
33
+ return [...tools, ...deferred].filter((tool) => !seen.has(tool.name) && !!seen.add(tool.name));
34
+ }
35
+
36
+ static changes(
37
+ from: ReadonlySet<string>,
38
+ to: ReadonlySet<string>,
39
+ declared: ReadonlySet<string>,
40
+ ): AnthropicToolChange[] {
41
+ const change = (type: AnthropicToolChange["type"], name: string): AnthropicToolChange => ({
42
+ type,
43
+ tool: { type: "tool_reference", name },
44
+ });
45
+ return [
46
+ ...[...to].filter((name) => !from.has(name) && declared.has(name)).map((name) => change("tool_addition", name)),
47
+ ...[...from].filter((name) => !to.has(name) && declared.has(name)).map((name) => change("tool_removal", name)),
48
+ ];
49
+ }
50
+
51
+ static engaged(body: { tools?: AnthropicTool[]; messages: { role: string }[] }): boolean {
52
+ return (
53
+ !!body.tools?.some((tool) => tool.defer_loading) || body.messages.some((message) => message.role === "system")
54
+ );
55
+ }
56
+ }
@@ -1,5 +1,6 @@
1
1
  export * from "./agentTools.adaptor";
2
2
  export * from "./anthropicLlm";
3
+ export * from "./anthropicTools";
3
4
  export * from "./cache.adaptor";
4
5
  export * from "./compress.adaptor";
5
6
  export * from "./database.adaptor";
@@ -70,6 +70,21 @@ export interface AgentWireMessage {
70
70
  foundTools?: string[];
71
71
  /** On an assistant message: what its provider must be sent back unchanged, which no other dialect reads. */
72
72
  providerContent?: AgentWireProviderContent;
73
+ /**
74
+ * On a user-role message `agentService.loop` wrote: `text` is the run's context as `LlmContext.of` rendered it, data
75
+ * and not an ask. It stays where it was first sent, so the turns after it reach the provider as they were.
76
+ */
77
+ context?: boolean;
78
+ /**
79
+ * On an assistant message `agentService.loop` wrote: the names of the tools listed when the model wrote it, so a
80
+ * provider that declares tools ahead can replay where each one was added or withdrawn.
81
+ */
82
+ listed?: string[];
83
+ /**
84
+ * On an assistant message `agentService.loop` wrote: the definitions of the page's tools that answer listed first,
85
+ * or listed changed. A later run declares them to a provider that keeps thinking, lent by the page or not.
86
+ */
87
+ lent?: AgentWireTool[];
73
88
  }
74
89
 
75
90
  /**
@@ -102,6 +117,11 @@ export interface LlmTurnRequest {
102
117
  messages: AgentWireMessage[];
103
118
  tools: AgentWireTool[];
104
119
  context: AgentWireContext[];
120
+ /**
121
+ * Tools the run may list on a later round, beside `tools`. A provider that can declare a tool before it shows one
122
+ * sends these unlisted, so a tool opened later leaves the earlier turns as they were; any other sends `tools` alone.
123
+ */
124
+ deferred?: AgentWireTool[];
105
125
  instructions?: string;
106
126
  /**
107
127
  * This turn's model in place of `LlmOption.model`. `accepts`, `maxTokens` and `contextWindow` stay the option's, so a
@@ -120,20 +120,34 @@ export class OpenaiDialect {
120
120
 
121
121
  static #conversation(messages: AgentWireMessage[], accepts?: LlmAccepts): OpenaiMessage[] {
122
122
  const asks = (message?: AgentWireMessage) => message?.role === "user" && !message.summary;
123
- return messages.flatMap((message, at) => {
124
- if (message.summary && asks(messages[at + 1])) return [];
125
- const mapped = OpenaiDialect.providerMessages(message, accepts);
123
+ const conversation: OpenaiMessage[] = [];
124
+ for (const [at, message] of messages.entries()) {
125
+ if (message.summary && asks(messages[at + 1])) continue;
126
126
  const before = messages[at - 1];
127
- if (!before?.summary || !asks(message)) return mapped;
128
- const summary = LlmContext.summary(before.text ?? "");
129
- return mapped.map(({ role, content }) => ({
130
- role,
131
- content:
132
- typeof content === "string"
133
- ? [summary, content].filter(Boolean).join("\n\n")
134
- : [{ type: "text" as const, text: summary }, ...content],
135
- }));
136
- });
127
+ const mapped = OpenaiDialect.providerMessages(message, accepts);
128
+ const last = conversation.at(-1);
129
+ if ((message.context || before?.context) && asks(message) && last?.role === "user" && mapped.length === 1) {
130
+ conversation[conversation.length - 1] = OpenaiDialect.#joined(last, mapped[0]?.content ?? "");
131
+ continue;
132
+ }
133
+ if (!before?.summary || !asks(message)) conversation.push(...mapped);
134
+ else
135
+ conversation.push(
136
+ ...mapped.map((part) =>
137
+ OpenaiDialect.#joined({ role: part.role, content: LlmContext.summary(before.text ?? "") }, part.content),
138
+ ),
139
+ );
140
+ }
141
+ return conversation;
142
+ }
143
+
144
+ static #joined(first: OpenaiMessage, content: OpenaiMessage["content"]): OpenaiMessage {
145
+ const head = first.content;
146
+ if (typeof head === "string" && typeof content === "string")
147
+ return { ...first, content: [head, content].filter(Boolean).join("\n\n") };
148
+ const parts = (part: OpenaiMessage["content"]) =>
149
+ typeof part === "string" ? (part ? [{ type: "text" as const, text: part }] : []) : (part ?? []);
150
+ return { ...first, content: [...parts(head), ...parts(content)] };
137
151
  }
138
152
 
139
153
  static providerMessages(message: AgentWireMessage, accepts?: LlmAccepts): OpenaiMessage[] {
@@ -16,6 +16,7 @@ export class ToolNames {
16
16
  static of(request: LlmTurnRequest): ToolNames {
17
17
  return new ToolNames([
18
18
  ...request.tools.map((tool) => tool.name),
19
+ ...(request.deferred ?? []).map((tool) => tool.name),
19
20
  ...request.messages.flatMap((message) => ToolNames.#namesIn(message)),
20
21
  ]);
21
22
  }
@@ -51,6 +52,9 @@ export class ToolNames {
51
52
  return {
52
53
  ...request,
53
54
  tools: request.tools.map((tool) => ({ ...tool, name: this.wire(tool.name) })),
55
+ ...(request.deferred
56
+ ? { deferred: request.deferred.map((tool) => ({ ...tool, name: this.wire(tool.name) })) }
57
+ : {}),
54
58
  messages: request.messages.map((message) => this.#encoded(message)),
55
59
  };
56
60
  }
@@ -61,9 +65,10 @@ export class ToolNames {
61
65
  }
62
66
 
63
67
  #encoded(message: AgentWireMessage): AgentWireMessage {
64
- if (!message.toolCalls?.length && !message.toolResults?.length) return message;
68
+ if (!message.toolCalls?.length && !message.toolResults?.length && !message.listed?.length) return message;
65
69
  return {
66
70
  ...message,
71
+ ...(message.listed?.length ? { listed: message.listed.map((name) => this.wire(name)) } : {}),
67
72
  ...(message.toolCalls?.length
68
73
  ? { toolCalls: message.toolCalls.map((call) => ({ ...call, name: this.wire(call.name) })) }
69
74
  : {}),
@@ -77,6 +82,7 @@ export class ToolNames {
77
82
  return [
78
83
  ...(message.toolCalls ?? []).map((call) => call.name),
79
84
  ...(message.toolResults ?? []).map((result) => result.name),
85
+ ...(message.listed ?? []),
80
86
  ];
81
87
  }
82
88
 
@@ -19,5 +19,5 @@ export declare class RotatingLogWriter {
19
19
  static sanitizeFilePart(value: string): string;
20
20
  write(processKey: string, chunk: string): void;
21
21
  close(): Promise<void>;
22
- static fileMode(value?: string | undefined, warn?: typeof RotatingLogWriter.__#179@#defaultWarn): number;
22
+ static fileMode(value?: string | undefined, warn?: typeof RotatingLogWriter.__#180@#defaultWarn): number;
23
23
  }
@@ -5,7 +5,7 @@ export declare class LoopCompaction {
5
5
  static readonly imageTokens = 1600;
6
6
  static readonly instruction: string;
7
7
  static tokensOf(messages: readonly AgentWireMessage[]): number;
8
- static frameTokensOf({ messages: _messages, ...frame }: LlmTurnRequest): number;
8
+ static frameTokensOf({ messages: _messages, deferred: _deferred, ...frame }: LlmTurnRequest): number;
9
9
  static cutAt(messages: readonly AgentWireMessage[], keep: number): number;
10
10
  static digest(messages: readonly AgentWireMessage[], budget?: number): string;
11
11
  static message(summary: string, tainted?: boolean, toolkits?: string[], foundTools?: string[]): AgentWireMessage;
@@ -0,0 +1,16 @@
1
+ import type { AgentWireMessage, AgentWireTool } from "../predefinedAdaptor/llm.adaptor";
2
+ export declare class LoopLent {
3
+ #private;
4
+ lend(lent: readonly AgentWireTool[], messages: readonly AgentWireMessage[], free: (name: string) => boolean): void;
5
+ has(name: string): boolean;
6
+ get left(): readonly AgentWireTool[];
7
+ tracks(messages: readonly AgentWireMessage[]): boolean;
8
+ listingOf(tools: readonly AgentWireTool[], messages: readonly AgentWireMessage[]): {
9
+ lent?: AgentWireTool[] | undefined;
10
+ listed: string[];
11
+ };
12
+ static definition({ name, description, parameters }: AgentWireTool): AgentWireTool;
13
+ static stored(messages: readonly AgentWireMessage[]): AgentWireTool[];
14
+ static unlent(messages: AgentWireMessage[]): AgentWireMessage[];
15
+ static fresh(lent: readonly AgentWireTool[], messages: readonly AgentWireMessage[]): AgentWireTool[];
16
+ }
@@ -9,6 +9,8 @@ export declare class LoopToolkits {
9
9
  get found(): string[];
10
10
  isMeta(name: string): boolean;
11
11
  listed(visible: AgentTool[]): AgentTool[];
12
+ deferred(listed: readonly AgentTool[]): AgentTool[];
13
+ get tracksListing(): boolean;
12
14
  refusalOf(name: string): string | null;
13
15
  gateOf({ name, args }: AgentWireToolCall): AgentTool | null;
14
16
  answer(call: AgentWireToolCall): Promise<AgentWireToolResult>;
@@ -1,3 +1,4 @@
1
+ import { type AnthropicToolMessage } from "./anthropicTools.d.ts";
1
2
  import { type AgentWireAttachment, type AgentWireContext, type AgentWireMessage, type AgentWireProviderContent, type AgentWireTool, type AgentWireToolResult, type LlmAccepts, type LlmAdaptor, type LlmLimits, type LlmOption, type LlmTurnAnswer, type LlmTurnRequest, type LlmUsage } from "./llm.adaptor";
2
3
  type AnthropicSource = {
3
4
  type: "base64";
@@ -39,6 +40,7 @@ interface AnthropicMessage {
39
40
  role: "user" | "assistant";
40
41
  content: AnthropicBlock[];
41
42
  }
43
+ type AnthropicTurn = AnthropicMessage | AnthropicToolMessage;
42
44
  interface AnthropicUsage {
43
45
  input_tokens?: number;
44
46
  output_tokens?: number;
@@ -66,8 +68,15 @@ interface AnthropicAnswer {
66
68
  usage?: AnthropicUsage;
67
69
  }
68
70
  type AnthropicThinkingReplay = "drop" | "strip";
71
+ export type AnthropicRequestBody = ReturnType<typeof AnthropicLlm.requestBody>;
72
+ export interface AnthropicLlmOption extends LlmOption {
73
+ /** Has the last word on each body, after the retries chose its form: a `cache_control` breakpoint, an `effort`. */
74
+ body?: (body: AnthropicRequestBody, request: LlmTurnRequest) => AnthropicRequestBody & Record<string, unknown>;
75
+ /** `anthropic-beta` values what `body` adds needs, sent beside the ones a retry adds. */
76
+ betas?: string[];
77
+ }
69
78
  declare const AnthropicLlm_base: import("..").AdaptorCls<{}, {
70
- llmOption: import("..").InjectInfo<"use", LlmOption, never, never>;
79
+ llmOption: import("..").InjectInfo<"use", AnthropicLlmOption, never, never>;
71
80
  }>;
72
81
  /** Anthropic's Messages API, which reads images and PDFs. `model` is required and has no default. */
73
82
  export declare class AnthropicLlm extends AnthropicLlm_base implements LlmAdaptor {
@@ -84,28 +93,37 @@ export declare class AnthropicLlm extends AnthropicLlm_base implements LlmAdapto
84
93
  static readonly dialect = "anthropic";
85
94
  /** The API refuses `thinking.block_binding` without it. */
86
95
  static readonly thinkingBindingBeta = "thinking-binding-controls-2026-08-01";
96
+ /**
97
+ * One with settings of its own, beside `option.setLlm`: an app's adaptor sending some turns here under another key
98
+ * keeps the retries, and what they learned about each model and conversation, by keeping the instance.
99
+ */
100
+ static of(option: AnthropicLlmOption): AnthropicLlm;
87
101
  get limits(): LlmLimits;
88
102
  get accepts(): LlmAccepts;
89
103
  chat(request: LlmTurnRequest, onDelta?: (delta: string) => void, signal?: AbortSignal): Promise<LlmTurnAnswer | null>;
90
104
  static thinkingRetry(sent: AnthropicThinkingReplay | undefined, reason: string): AnthropicThinkingReplay | null;
91
- static replaysThinking(messages: AnthropicMessage[]): boolean;
105
+ static replaysThinking(messages: readonly {
106
+ content: readonly {
107
+ type: string;
108
+ }[];
109
+ }[]): boolean;
92
110
  static refusal(host: string, response: Response): Promise<Error>;
93
111
  /** The API answers a refusal as `{ error: { type, message } }`, and the sentence is the half worth printing. */
94
112
  static reasonOf(response: Response): Promise<string>;
95
- /** `thinking: "drop"` needs `thinkingBindingBeta` in the `anthropic-beta` header. */
96
- static requestBody(model: string, request: LlmTurnRequest, { accepts, stream, maxTokens, thinking, }?: {
113
+ /**
114
+ * `thinking: "drop"` needs `thinkingBindingBeta` in the `anthropic-beta` header, and a body that declares tools
115
+ * ahead (`AnthropicTools.engaged`) needs `AnthropicTools.beta`; `toolChanges: false` lists `request.tools` alone.
116
+ */
117
+ static requestBody(model: string, request: LlmTurnRequest, { accepts, stream, maxTokens, thinking, toolChanges, }?: {
97
118
  accepts?: LlmAccepts;
98
119
  stream?: boolean;
99
120
  maxTokens?: number;
100
121
  thinking?: AnthropicThinkingReplay;
122
+ toolChanges?: boolean;
101
123
  }): {
102
- tools?: {
103
- input_schema: Record<string, unknown>;
104
- description?: string | undefined;
105
- name: string;
106
- }[] | undefined;
124
+ tools?: import("./anthropicTools.d.ts").AnthropicTool[] | undefined;
107
125
  system: string;
108
- messages: AnthropicMessage[];
126
+ messages: AnthropicTurn[];
109
127
  thinking?: {
110
128
  type: string;
111
129
  block_binding: {
@@ -0,0 +1,30 @@
1
+ import type { AgentWireTool, LlmTurnRequest } from "./llm.adaptor";
2
+ export interface AnthropicToolChange {
3
+ type: "tool_addition" | "tool_removal";
4
+ tool: {
5
+ type: "tool_reference";
6
+ name: string;
7
+ };
8
+ }
9
+ export interface AnthropicToolMessage {
10
+ role: "system";
11
+ content: AnthropicToolChange[];
12
+ }
13
+ export interface AnthropicTool {
14
+ name: string;
15
+ description?: string;
16
+ input_schema: Record<string, unknown>;
17
+ defer_loading?: true;
18
+ }
19
+ export declare class AnthropicTools {
20
+ static readonly beta = "mid-conversation-tool-changes-2026-07-01";
21
+ static definition(tool: AgentWireTool, deferred?: boolean): AnthropicTool;
22
+ static declared({ tools, deferred }: Pick<LlmTurnRequest, "tools" | "deferred">): AgentWireTool[];
23
+ static changes(from: ReadonlySet<string>, to: ReadonlySet<string>, declared: ReadonlySet<string>): AnthropicToolChange[];
24
+ static engaged(body: {
25
+ tools?: AnthropicTool[];
26
+ messages: {
27
+ role: string;
28
+ }[];
29
+ }): boolean;
30
+ }
@@ -1,5 +1,6 @@
1
1
  export * from "./agentTools.adaptor";
2
2
  export * from "./anthropicLlm.d.ts";
3
+ export * from "./anthropicTools.d.ts";
3
4
  export * from "./cache.adaptor";
4
5
  export * from "./compress.adaptor";
5
6
  export * from "./database.adaptor";
@@ -66,6 +66,21 @@ export interface AgentWireMessage {
66
66
  foundTools?: string[];
67
67
  /** On an assistant message: what its provider must be sent back unchanged, which no other dialect reads. */
68
68
  providerContent?: AgentWireProviderContent;
69
+ /**
70
+ * On a user-role message `agentService.loop` wrote: `text` is the run's context as `LlmContext.of` rendered it, data
71
+ * and not an ask. It stays where it was first sent, so the turns after it reach the provider as they were.
72
+ */
73
+ context?: boolean;
74
+ /**
75
+ * On an assistant message `agentService.loop` wrote: the names of the tools listed when the model wrote it, so a
76
+ * provider that declares tools ahead can replay where each one was added or withdrawn.
77
+ */
78
+ listed?: string[];
79
+ /**
80
+ * On an assistant message `agentService.loop` wrote: the definitions of the page's tools that answer listed first,
81
+ * or listed changed. A later run declares them to a provider that keeps thinking, lent by the page or not.
82
+ */
83
+ lent?: AgentWireTool[];
69
84
  }
70
85
  /**
71
86
  * Anthropic's thinking blocks, signatures included, in answer order: replayed verbatim, the model keeps its reasoning
@@ -94,6 +109,11 @@ export interface LlmTurnRequest {
94
109
  messages: AgentWireMessage[];
95
110
  tools: AgentWireTool[];
96
111
  context: AgentWireContext[];
112
+ /**
113
+ * Tools the run may list on a later round, beside `tools`. A provider that can declare a tool before it shows one
114
+ * sends these unlisted, so a tool opened later leaves the earlier turns as they were; any other sends `tools` alone.
115
+ */
116
+ deferred?: AgentWireTool[];
97
117
  instructions?: string;
98
118
  /**
99
119
  * This turn's model in place of `LlmOption.model`. `accepts`, `maxTokens` and `contextWindow` stay the option's, so a
@@ -2,14 +2,14 @@
2
2
  export declare const badgeRecipe: (variants?: Omit<({
3
3
  size?: "lg" | "md" | "sm" | "xs" | undefined;
4
4
  outline?: boolean | undefined;
5
- variant?: "error" | "default" | "info" | "warning" | "success" | "primary" | "outline" | "secondary" | "accent" | "neutral" | undefined;
5
+ variant?: "default" | "error" | "info" | "warning" | "success" | "primary" | "outline" | "secondary" | "accent" | "neutral" | undefined;
6
6
  } & {
7
7
  class?: import("tailwind-variants/lite").ClassValue;
8
8
  className?: never;
9
9
  }) | ({
10
10
  size?: "lg" | "md" | "sm" | "xs" | undefined;
11
11
  outline?: boolean | undefined;
12
- variant?: "error" | "default" | "info" | "warning" | "success" | "primary" | "outline" | "secondary" | "accent" | "neutral" | undefined;
12
+ variant?: "default" | "error" | "info" | "warning" | "success" | "primary" | "outline" | "secondary" | "accent" | "neutral" | undefined;
13
13
  } & {
14
14
  class?: never;
15
15
  className?: import("tailwind-variants/lite").ClassValue;
@@ -2,7 +2,7 @@
2
2
  export declare const buttonRecipe: (variants?: Omit<({
3
3
  size?: "xl" | "lg" | "md" | "sm" | "xs" | "icon" | undefined;
4
4
  outline?: boolean | undefined;
5
- variant?: "link" | "default" | "info" | "warning" | "success" | "destructive" | "primary" | "outline" | "secondary" | "accent" | "neutral" | "ghost" | undefined;
5
+ variant?: "default" | "link" | "info" | "warning" | "success" | "destructive" | "primary" | "outline" | "secondary" | "accent" | "neutral" | "ghost" | undefined;
6
6
  shape?: "default" | "circle" | "square" | undefined;
7
7
  } & {
8
8
  class?: import("tailwind-variants/lite").ClassValue;
@@ -10,7 +10,7 @@ export declare const buttonRecipe: (variants?: Omit<({
10
10
  }) | ({
11
11
  size?: "xl" | "lg" | "md" | "sm" | "xs" | "icon" | undefined;
12
12
  outline?: boolean | undefined;
13
- variant?: "link" | "default" | "info" | "warning" | "success" | "destructive" | "primary" | "outline" | "secondary" | "accent" | "neutral" | "ghost" | undefined;
13
+ variant?: "default" | "link" | "info" | "warning" | "success" | "destructive" | "primary" | "outline" | "secondary" | "accent" | "neutral" | "ghost" | undefined;
14
14
  shape?: "default" | "circle" | "square" | undefined;
15
15
  } & {
16
16
  class?: never;
@@ -2,14 +2,14 @@
2
2
  export declare const inputRecipe: (variants?: Omit<({
3
3
  kind?: "field" | "select" | "area" | undefined;
4
4
  size?: "xl" | "lg" | "md" | "sm" | "xs" | undefined;
5
- tone?: "error" | "default" | "primary" | undefined;
5
+ tone?: "default" | "error" | "primary" | undefined;
6
6
  } & {
7
7
  class?: import("tailwind-variants/lite").ClassValue;
8
8
  className?: never;
9
9
  }) | ({
10
10
  kind?: "field" | "select" | "area" | undefined;
11
11
  size?: "xl" | "lg" | "md" | "sm" | "xs" | undefined;
12
- tone?: "error" | "default" | "primary" | undefined;
12
+ tone?: "default" | "error" | "primary" | undefined;
13
13
  } & {
14
14
  class?: never;
15
15
  className?: import("tailwind-variants/lite").ClassValue;
@@ -21,7 +21,7 @@ export declare class CsrSlide {
21
21
  static get isCalm(): boolean;
22
22
  static settleMove(kind: "push" | "replace", from: Location, to: Location): boolean;
23
23
  /** How an entry moves: its own page's transition, or that of the page it took the place of. */
24
- static motionOf(location: Location): "stack" | "none" | "fade" | "bottomUp" | "scaleOut";
24
+ static motionOf(location: Location): "none" | "stack" | "fade" | "bottomUp" | "scaleOut";
25
25
  /** Whether an entry swipes back: its own page's `gesture`, or that of the page it took the place of. */
26
26
  static swipesBack(location: Location): boolean;
27
27
  static isStill(entryId: string | undefined): boolean;
@@ -17,8 +17,8 @@ export declare const useCsrRefs: () => {
17
17
  pageContentRef: import("react").RefObject<HTMLDivElement | null>;
18
18
  prevPageContentRef: import("react").RefObject<HTMLDivElement | null>;
19
19
  onBack: import("react").RefObject<{
20
- stack?: (() => Promise<void>) | undefined;
21
20
  none?: (() => Promise<void>) | undefined;
21
+ stack?: (() => Promise<void>) | undefined;
22
22
  fade?: (() => Promise<void>) | undefined;
23
23
  bottomUp?: (() => Promise<void>) | undefined;
24
24
  scaleOut?: (() => Promise<void>) | undefined;