akanjs 3.3.0-rc.73 → 3.3.0-rc.74

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.74",
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,
@@ -149,13 +151,15 @@ export class AgentLoop {
149
151
 
150
152
  async *#runRound(): Events<AgentLoopStop | null> {
151
153
  const listed = await this.#listTools();
154
+ await this.#pinContext();
152
155
  const compacted = yield* this.#compact(listed);
153
156
  const { answer, tools } = yield* this.#ask(compacted ?? listed);
154
-
157
+
155
158
  const mark = this.#tainted ? { tainted: true } : {};
159
+ const shown = this.#toolkits.tracksListing ? { listed: tools.map((tool) => tool.name) } : {};
156
160
  if (answer.stop === "length") {
157
161
 
158
- if (answer.text) await this.#append({ role: "assistant", text: answer.text, ...mark });
162
+ if (answer.text) await this.#append({ role: "assistant", text: answer.text, ...shown, ...mark });
159
163
  return "length";
160
164
  }
161
165
  const message: AgentWireMessage = {
@@ -163,6 +167,7 @@ export class AgentLoop {
163
167
  ...(answer.text ? { text: answer.text } : {}),
164
168
  ...(answer.toolCalls.length ? { toolCalls: answer.toolCalls } : {}),
165
169
  ...(answer.providerContent ? { providerContent: answer.providerContent } : {}),
170
+ ...shown,
166
171
  ...mark,
167
172
  };
168
173
  if (LoopTranscript.carries(message)) await this.#append(message);
@@ -223,8 +228,16 @@ export class AgentLoop {
223
228
  };
224
229
  }
225
230
 
231
+ async #pinContext() {
232
+ const { context = [] } = this.#request;
233
+ const text = LlmContext.of(context);
234
+ if (!text || this.#messages.findLast((message) => message.context)?.text === text) return;
235
+ await this.#append({ role: "user", text, context: true, ...(LlmFence.marks(context) ? { tainted: true } : {}) });
236
+ }
237
+
226
238
  async *#ask(listed: AgentTool[]): Events<{ answer: AgentLoopAnswer; tools: AgentTool[] }> {
227
239
  const preamble = this.#request.preamble ?? false;
240
+ await this.#pinContext();
228
241
  const request = this.#turnOf(listed);
229
242
  let tools = listed;
230
243
  try {
@@ -237,21 +250,24 @@ export class AgentLoop {
237
250
  if (!compacted) throw error;
238
251
  tools = compacted;
239
252
  }
253
+ await this.#pinContext();
240
254
  return { answer: yield* this.#metered(this.#turnOf(tools), preamble, true), tools };
241
255
  }
242
256
 
243
257
  #turnOf(tools: AgentTool[]): LlmTurnRequest {
244
- const { context = [], model, preamble } = this.#request;
258
+ const { model, preamble } = this.#request;
245
259
  const instructions = [
246
260
  this.#request.instructions || (preamble ? "" : AgentLoop.noInstructions),
247
261
  ...this.#toolkits.pinnedInstructions(),
248
262
  ]
249
263
  .filter(Boolean)
250
264
  .join("\n\n");
265
+ const deferred = this.#toolkits.deferred(tools).map(({ readOnly: _readOnly, ...tool }) => tool);
251
266
  return {
252
267
  messages: LoopTranscript.wire(this.#messages),
253
268
  tools: tools.map(({ readOnly: _readOnly, ...tool }) => tool),
254
- context,
269
+ context: [],
270
+ ...(deferred.length ? { deferred } : {}),
255
271
  ...(instructions ? { instructions } : {}),
256
272
  ...(model ? { model } : {}),
257
273
  };
@@ -20,7 +20,7 @@ export class LoopCompaction {
20
20
  return Math.ceil(chars / 4);
21
21
  }
22
22
 
23
- static frameTokensOf({ messages: _messages, ...frame }: LlmTurnRequest): number {
23
+ static frameTokensOf({ messages: _messages, deferred: _deferred, ...frame }: LlmTurnRequest): number {
24
24
  return Math.ceil(JSON.stringify(frame).length / 4);
25
25
  }
26
26
 
@@ -80,7 +80,10 @@ export class LoopCompaction {
80
80
  const previous = messages
81
81
  .filter((message) => message.summary)
82
82
  .map((message) => `previous summary:\n${message.text ?? ""}`);
83
- const lines = messages.filter((message) => !message.summary).map((message) => LoopCompaction.#line(message));
83
+
84
+ const lines = messages
85
+ .filter((message) => !message.summary && !message.context)
86
+ .map((message) => LoopCompaction.#line(message));
84
87
  return [...previous, LoopCompaction.#fit(lines, budget)].filter(Boolean).join("\n");
85
88
  }
86
89
 
@@ -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
 
@@ -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;
@@ -106,7 +109,10 @@ export class AnthropicLlm
106
109
  /** The API refuses `thinking.block_binding` without it. */
107
110
  static readonly thinkingBindingBeta = "thinking-binding-controls-2026-08-01";
108
111
 
109
- readonly #historyChecked = new Set<string>();
112
+ static readonly #droppedLimit = 500;
113
+
114
+ readonly #dropped = new Set<string>();
115
+ readonly #plainTools = new Set<string>();
110
116
 
111
117
  get #host() {
112
118
  return this.llmOption.host ?? "https://api.anthropic.com/v1";
@@ -139,7 +145,9 @@ export class AnthropicLlm
139
145
  const stream = !!onDelta;
140
146
  const response = await this.#send(
141
147
  model,
142
- (thinking) => AnthropicLlm.requestBody(model, request, { accepts, stream, maxTokens, thinking }),
148
+ AnthropicLlm.#conversationOf(request.messages),
149
+ (thinking, toolChanges) =>
150
+ AnthropicLlm.requestBody(model, request, { accepts, stream, maxTokens, thinking, toolChanges }),
143
151
  signal,
144
152
  );
145
153
  if (!onDelta)
@@ -177,40 +185,88 @@ export class AnthropicLlm
177
185
 
178
186
  async #send(
179
187
  model: string,
180
- bodyOf: (thinking?: AnthropicThinkingReplay) => { messages: AnthropicMessage[] },
188
+ conversation: string | null,
189
+ bodyOf: (
190
+ thinking: AnthropicThinkingReplay | undefined,
191
+ toolChanges: boolean,
192
+ ) => ReturnType<typeof AnthropicLlm.requestBody>,
181
193
  signal?: AbortSignal,
182
194
  ): Promise<Response> {
183
- let thinking: AnthropicThinkingReplay | undefined = this.#historyChecked.has(model) ? "drop" : undefined;
195
+ let thinking: AnthropicThinkingReplay | undefined =
196
+ conversation && this.#dropped.has(conversation) ? "drop" : undefined;
197
+ let toolChanges = !this.#plainTools.has(model);
198
+ let unproven: string | null = null;
184
199
  for (;;) {
185
- const body = bodyOf(thinking);
200
+ const body = bodyOf(thinking, toolChanges);
201
+ const engaged = AnthropicTools.engaged(body);
202
+ const betas = [
203
+ ...(thinking === "drop" ? [AnthropicLlm.thinkingBindingBeta] : []),
204
+ ...(engaged ? [AnthropicTools.beta] : []),
205
+ ];
186
206
  const response: Response = await fetch(`${this.#host}/messages`, {
187
207
  method: "POST",
188
- headers:
189
- thinking === "drop"
190
- ? { ...this.#headers, "anthropic-beta": AnthropicLlm.thinkingBindingBeta }
191
- : this.#headers,
208
+ headers: betas.length ? { ...this.#headers, "anthropic-beta": betas.join(",") } : this.#headers,
192
209
  body: JSON.stringify(body),
193
210
  signal: llmCallSignal(signal),
194
211
  });
195
- if (response.ok) return response;
212
+ if (response.ok) {
213
+ if (unproven) this.#sendPlain(model, unproven);
214
+ return response;
215
+ }
196
216
  const reason = await AnthropicLlm.reasonOf(response);
197
217
  const retry: AnthropicThinkingReplay | null =
198
218
  response.status === 400 && (thinking === "drop" || AnthropicLlm.replaysThinking(body.messages))
199
219
  ? AnthropicLlm.thinkingRetry(thinking, reason)
200
220
  : null;
221
+ if (response.status === 400 && engaged && !(retry && /thinking|block_binding/i.test(reason))) {
222
+ unproven = reason;
223
+ toolChanges = false;
224
+ continue;
225
+ }
201
226
  if (!retry) throw LlmOverflow.refusal(this.#host, response.status, reason);
202
- if (retry === "drop") this.#historyChecked.add(model);
227
+ if (retry === "drop" && conversation) this.#remember(conversation);
203
228
  thinking = retry;
204
229
  }
205
230
  }
206
231
 
232
+ #sendPlain(model: string, reason: string) {
233
+ this.#plainTools.add(model);
234
+ this.logger.warn(
235
+ `Anthropic refused declared tool changes for ${model} (${reason}), so its turns list the shown tools alone.`,
236
+ );
237
+ }
238
+
239
+ #remember(conversation: string) {
240
+ this.#dropped.delete(conversation);
241
+ this.#dropped.add(conversation);
242
+ const oldest = this.#dropped.values().next().value;
243
+ if (this.#dropped.size > AnthropicLlm.#droppedLimit && oldest) this.#dropped.delete(oldest);
244
+ }
245
+
246
+ static #conversationOf(messages: readonly AgentWireMessage[]): string | null {
247
+ for (const message of messages) {
248
+ if (message.providerContent?.dialect !== AnthropicLlm.dialect || !Array.isArray(message.providerContent.content))
249
+ continue;
250
+ for (const block of message.providerContent.content as (AnthropicAnswerBlock | null)[]) {
251
+ const signed =
252
+ block?.type === "thinking" ? block.signature : block?.type === "redacted_thinking" ? block.data : "";
253
+ if (signed) return createHash("sha256").update(signed).digest("hex");
254
+ }
255
+ }
256
+ return null;
257
+ }
258
+
259
+ static #bound(reason: string): boolean {
260
+ return /block_binding|different conversation/i.test(reason);
261
+ }
262
+
207
263
  static thinkingRetry(sent: AnthropicThinkingReplay | undefined, reason: string): AnthropicThinkingReplay | null {
208
264
  if (sent === "strip") return null;
209
- if (!sent && /block_binding|different conversation/i.test(reason)) return "drop";
265
+ if (!sent && AnthropicLlm.#bound(reason)) return "drop";
210
266
  return /thinking|beta/i.test(reason) ? "strip" : null;
211
267
  }
212
268
 
213
- static replaysThinking(messages: AnthropicMessage[]): boolean {
269
+ static replaysThinking(messages: readonly { content: readonly { type: string }[] }[]): boolean {
214
270
  return messages.some((message) =>
215
271
  message.content.some((block) => block.type === "thinking" || block.type === "redacted_thinking"),
216
272
  );
@@ -231,7 +287,10 @@ export class AnthropicLlm
231
287
  return response.statusText || "no reason given";
232
288
  }
233
289
 
234
- /** `thinking: "drop"` needs `thinkingBindingBeta` in the `anthropic-beta` header. */
290
+ /**
291
+ * `thinking: "drop"` needs `thinkingBindingBeta` in the `anthropic-beta` header, and a body that declares tools
292
+ * ahead (`AnthropicTools.engaged`) needs `AnthropicTools.beta`; `toolChanges: false` lists `request.tools` alone.
293
+ */
235
294
  static requestBody(
236
295
  model: string,
237
296
  request: LlmTurnRequest,
@@ -240,7 +299,14 @@ export class AnthropicLlm
240
299
  stream,
241
300
  maxTokens,
242
301
  thinking,
243
- }: { accepts?: LlmAccepts; stream?: boolean; maxTokens?: number; thinking?: AnthropicThinkingReplay } = {},
302
+ toolChanges = true,
303
+ }: {
304
+ accepts?: LlmAccepts;
305
+ stream?: boolean;
306
+ maxTokens?: number;
307
+ thinking?: AnthropicThinkingReplay;
308
+ toolChanges?: boolean;
309
+ } = {},
244
310
  ) {
245
311
  const messages =
246
312
  thinking === "strip"
@@ -248,6 +314,7 @@ export class AnthropicLlm
248
314
  message.providerContent ? { ...message, providerContent: undefined } : message,
249
315
  )
250
316
  : request.messages;
317
+ const { tools, turns } = AnthropicLlm.#listing(request, messages, accepts, toolChanges);
251
318
  return {
252
319
  model,
253
320
  max_tokens: maxTokens ?? AnthropicLlm.defaultMaxTokens,
@@ -256,18 +323,56 @@ export class AnthropicLlm
256
323
  ? { thinking: { type: "adaptive", block_binding: { prefix_mismatch_behavior: "drop_block" } } }
257
324
  : {}),
258
325
  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
- : {}),
326
+ messages: turns,
327
+ ...(tools.length ? { tools } : {}),
328
+ };
329
+ }
330
+
331
+ static #listing(
332
+ request: LlmTurnRequest,
333
+ messages: AgentWireMessage[],
334
+ accepts: LlmAccepts | undefined,
335
+ toolChanges: boolean,
336
+ ) {
337
+ const plain = () => ({
338
+ tools: request.tools.map((tool) => AnthropicTools.definition(tool)),
339
+ turns: AnthropicLlm.contextual(
340
+ AnthropicLlm.providerMessages(messages, accepts),
341
+ request.context,
342
+ ) as AnthropicTurn[],
343
+ });
344
+ if (!toolChanges || (!request.deferred?.length && !messages.some((message) => message.listed))) return plain();
345
+ const declared = AnthropicTools.declared(request);
346
+ const shown = request.tools.map((tool) => tool.name);
347
+ const names = new Set(declared.map((tool) => tool.name));
348
+ const { turns, base, announced } = AnthropicLlm.#turns(messages, accepts, names);
349
+ const first = base ?? shown;
350
+ if (!declared.some((tool) => first.includes(tool.name))) return plain();
351
+ const rank = (name: string) => {
352
+ const at = first.indexOf(name);
353
+ return at < 0 ? first.length : at;
270
354
  };
355
+ const ordered = [...declared].sort(
356
+ (a, b) => rank(a.name) - rank(b.name) || (a.name < b.name ? -1 : a.name > b.name ? 1 : 0),
357
+ );
358
+ const sent = AnthropicLlm.contextual(turns as AnthropicMessage[], request.context) as AnthropicTurn[];
359
+ if (announced) AnthropicLlm.#announce(sent, announced, new Set(shown), names);
360
+ return { tools: ordered.map((tool) => AnthropicTools.definition(tool, !first.includes(tool.name))), turns: sent };
361
+ }
362
+
363
+ static #announce(
364
+ turns: AnthropicTurn[],
365
+ from: ReadonlySet<string>,
366
+ to: ReadonlySet<string>,
367
+ declared: ReadonlySet<string>,
368
+ ): ReadonlySet<string> {
369
+ const changes = AnthropicTools.changes(from, to, declared);
370
+ if (!changes.length) return to;
371
+ const last = turns.at(-1);
372
+ if (last?.role === "system") last.content.push(...changes);
373
+ else if (last?.role === "user") turns.push({ role: "system", content: changes });
374
+ else return from;
375
+ return to;
271
376
  }
272
377
 
273
378
  static systemPrompt({ instructions }: Pick<LlmTurnRequest, "instructions">): string {
@@ -288,18 +393,29 @@ export class AnthropicLlm
288
393
 
289
394
  /** The API takes strictly alternating roles, so tool results and the user's next ask merge into one user turn. */
290
395
  static providerMessages(messages: AgentWireMessage[], accepts?: LlmAccepts): AnthropicMessage[] {
291
- const merged: AnthropicMessage[] = [];
396
+ return AnthropicLlm.#turns(messages, accepts, null).turns as AnthropicMessage[];
397
+ }
398
+
399
+ static #turns(messages: AgentWireMessage[], accepts: LlmAccepts | undefined, declared: ReadonlySet<string> | null) {
400
+ const merged: AnthropicTurn[] = [];
401
+ let base: string[] | null = null;
402
+ let announced: ReadonlySet<string> | null = null;
292
403
  for (const message of messages) {
293
404
  const mapped = AnthropicLlm.providerMessage(message, accepts);
294
405
  if (!mapped.content.length) continue;
295
- const last = merged[merged.length - 1];
296
- if (last?.role === mapped.role) last.content.push(...mapped.content);
406
+ if (declared && mapped.role === "assistant" && message.listed) {
407
+ const now = new Set(message.listed);
408
+ if (!announced) base = [...message.listed];
409
+ announced = announced ? AnthropicLlm.#announce(merged, announced, now, declared) : now;
410
+ }
411
+ const last = merged.at(-1);
412
+ if (last && last.role !== "system" && last.role === mapped.role) last.content.push(...mapped.content);
297
413
  else merged.push(mapped);
298
414
  }
299
415
 
300
416
  if (merged[0]?.role === "assistant") merged.shift();
301
- if (merged[merged.length - 1]?.role === "assistant") merged.pop();
302
- return merged;
417
+ if (merged.at(-1)?.role === "assistant") merged.pop();
418
+ return { turns: merged, base, announced };
303
419
  }
304
420
 
305
421
  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,16 @@ 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[];
73
83
  }
74
84
 
75
85
  /**
@@ -102,6 +112,11 @@ export interface LlmTurnRequest {
102
112
  messages: AgentWireMessage[];
103
113
  tools: AgentWireTool[];
104
114
  context: AgentWireContext[];
115
+ /**
116
+ * Tools the run may list on a later round, beside `tools`. A provider that can declare a tool before it shows one
117
+ * sends these unlisted, so a tool opened later leaves the earlier turns as they were; any other sends `tools` alone.
118
+ */
119
+ deferred?: AgentWireTool[];
105
120
  instructions?: string;
106
121
  /**
107
122
  * 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
 
@@ -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;
@@ -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;
@@ -88,24 +90,28 @@ export declare class AnthropicLlm extends AnthropicLlm_base implements LlmAdapto
88
90
  get accepts(): LlmAccepts;
89
91
  chat(request: LlmTurnRequest, onDelta?: (delta: string) => void, signal?: AbortSignal): Promise<LlmTurnAnswer | null>;
90
92
  static thinkingRetry(sent: AnthropicThinkingReplay | undefined, reason: string): AnthropicThinkingReplay | null;
91
- static replaysThinking(messages: AnthropicMessage[]): boolean;
93
+ static replaysThinking(messages: readonly {
94
+ content: readonly {
95
+ type: string;
96
+ }[];
97
+ }[]): boolean;
92
98
  static refusal(host: string, response: Response): Promise<Error>;
93
99
  /** The API answers a refusal as `{ error: { type, message } }`, and the sentence is the half worth printing. */
94
100
  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, }?: {
101
+ /**
102
+ * `thinking: "drop"` needs `thinkingBindingBeta` in the `anthropic-beta` header, and a body that declares tools
103
+ * ahead (`AnthropicTools.engaged`) needs `AnthropicTools.beta`; `toolChanges: false` lists `request.tools` alone.
104
+ */
105
+ static requestBody(model: string, request: LlmTurnRequest, { accepts, stream, maxTokens, thinking, toolChanges, }?: {
97
106
  accepts?: LlmAccepts;
98
107
  stream?: boolean;
99
108
  maxTokens?: number;
100
109
  thinking?: AnthropicThinkingReplay;
110
+ toolChanges?: boolean;
101
111
  }): {
102
- tools?: {
103
- input_schema: Record<string, unknown>;
104
- description?: string | undefined;
105
- name: string;
106
- }[] | undefined;
112
+ tools?: import("./anthropicTools.d.ts").AnthropicTool[] | undefined;
107
113
  system: string;
108
- messages: AnthropicMessage[];
114
+ messages: AnthropicTurn[];
109
115
  thinking?: {
110
116
  type: string;
111
117
  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,16 @@ 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[];
69
79
  }
70
80
  /**
71
81
  * Anthropic's thinking blocks, signatures included, in answer order: replayed verbatim, the model keeps its reasoning
@@ -94,6 +104,11 @@ export interface LlmTurnRequest {
94
104
  messages: AgentWireMessage[];
95
105
  tools: AgentWireTool[];
96
106
  context: AgentWireContext[];
107
+ /**
108
+ * Tools the run may list on a later round, beside `tools`. A provider that can declare a tool before it shows one
109
+ * sends these unlisted, so a tool opened later leaves the earlier turns as they were; any other sends `tools` alone.
110
+ */
111
+ deferred?: AgentWireTool[];
97
112
  instructions?: string;
98
113
  /**
99
114
  * 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;