llm-large-files 0.5.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (221) hide show
  1. package/CHANGELOG.md +1402 -467
  2. package/README.md +188 -60
  3. package/dist/analyze.d.ts +5 -0
  4. package/dist/analyze.d.ts.map +1 -1
  5. package/dist/analyze.js +96 -47
  6. package/dist/analyze.js.map +1 -1
  7. package/dist/anthropic/adapter.d.ts +14 -3
  8. package/dist/anthropic/adapter.d.ts.map +1 -1
  9. package/dist/anthropic/adapter.js +190 -39
  10. package/dist/anthropic/adapter.js.map +1 -1
  11. package/dist/ask.d.ts +60 -4
  12. package/dist/ask.d.ts.map +1 -1
  13. package/dist/ask.js +1068 -206
  14. package/dist/ask.js.map +1 -1
  15. package/dist/encoding.d.ts +17 -0
  16. package/dist/encoding.d.ts.map +1 -0
  17. package/dist/encoding.js +852 -0
  18. package/dist/encoding.js.map +1 -0
  19. package/dist/errors.d.ts +4 -0
  20. package/dist/errors.d.ts.map +1 -1
  21. package/dist/errors.js +15 -0
  22. package/dist/errors.js.map +1 -1
  23. package/dist/events.d.ts +333 -0
  24. package/dist/events.d.ts.map +1 -0
  25. package/dist/events.js +159 -0
  26. package/dist/events.js.map +1 -0
  27. package/dist/evidence.d.ts +2 -0
  28. package/dist/evidence.d.ts.map +1 -1
  29. package/dist/evidence.js +3 -2
  30. package/dist/evidence.js.map +1 -1
  31. package/dist/extract.d.ts +35 -3
  32. package/dist/extract.d.ts.map +1 -1
  33. package/dist/extract.js +626 -58
  34. package/dist/extract.js.map +1 -1
  35. package/dist/gemini/adapter.d.ts +17 -8
  36. package/dist/gemini/adapter.d.ts.map +1 -1
  37. package/dist/gemini/adapter.js +108 -61
  38. package/dist/gemini/adapter.js.map +1 -1
  39. package/dist/gemini/chat.d.ts +23 -3
  40. package/dist/gemini/chat.d.ts.map +1 -1
  41. package/dist/gemini/chat.js +6 -2
  42. package/dist/gemini/chat.js.map +1 -1
  43. package/dist/gemini/errors.d.ts +9 -4
  44. package/dist/gemini/errors.d.ts.map +1 -1
  45. package/dist/gemini/errors.js +32 -0
  46. package/dist/gemini/errors.js.map +1 -1
  47. package/dist/gemini/generate.d.ts +10 -2
  48. package/dist/gemini/generate.d.ts.map +1 -1
  49. package/dist/gemini/generate.js +13 -7
  50. package/dist/gemini/generate.js.map +1 -1
  51. package/dist/gemini/index.d.ts +3 -3
  52. package/dist/gemini/index.d.ts.map +1 -1
  53. package/dist/gemini/index.js +2 -2
  54. package/dist/gemini/index.js.map +1 -1
  55. package/dist/gemini/sse.d.ts +1 -1
  56. package/dist/gemini/sse.d.ts.map +1 -1
  57. package/dist/gemini/sse.js +1 -1
  58. package/dist/gemini/sse.js.map +1 -1
  59. package/dist/http.d.ts +116 -0
  60. package/dist/http.d.ts.map +1 -1
  61. package/dist/http.js +347 -1
  62. package/dist/http.js.map +1 -1
  63. package/dist/index.d.ts +11 -6
  64. package/dist/index.d.ts.map +1 -1
  65. package/dist/index.js +6 -4
  66. package/dist/index.js.map +1 -1
  67. package/dist/library.d.ts +67 -5
  68. package/dist/library.d.ts.map +1 -1
  69. package/dist/library.js +405 -85
  70. package/dist/library.js.map +1 -1
  71. package/dist/map-reduce.d.ts +28 -1
  72. package/dist/map-reduce.d.ts.map +1 -1
  73. package/dist/map-reduce.js +240 -52
  74. package/dist/map-reduce.js.map +1 -1
  75. package/dist/model.d.ts +84 -2
  76. package/dist/model.d.ts.map +1 -1
  77. package/dist/model.js +182 -1
  78. package/dist/model.js.map +1 -1
  79. package/dist/node/handlers.d.ts +20 -4
  80. package/dist/node/handlers.d.ts.map +1 -1
  81. package/dist/node/handlers.js +122 -20
  82. package/dist/node/handlers.js.map +1 -1
  83. package/dist/node/index.d.ts +2 -0
  84. package/dist/node/index.d.ts.map +1 -1
  85. package/dist/node/index.js +1 -0
  86. package/dist/node/index.js.map +1 -1
  87. package/dist/node/sse.d.ts +59 -0
  88. package/dist/node/sse.d.ts.map +1 -0
  89. package/dist/node/sse.js +174 -0
  90. package/dist/node/sse.js.map +1 -0
  91. package/dist/openai/adapter.d.ts +29 -5
  92. package/dist/openai/adapter.d.ts.map +1 -1
  93. package/dist/openai/adapter.js +311 -37
  94. package/dist/openai/adapter.js.map +1 -1
  95. package/dist/output-limit.d.ts +14 -2
  96. package/dist/output-limit.d.ts.map +1 -1
  97. package/dist/output-limit.js +39 -10
  98. package/dist/output-limit.js.map +1 -1
  99. package/dist/pause.d.ts +24 -0
  100. package/dist/pause.d.ts.map +1 -0
  101. package/dist/pause.js +38 -0
  102. package/dist/pause.js.map +1 -0
  103. package/dist/pdf-pages.d.ts +32 -2
  104. package/dist/pdf-pages.d.ts.map +1 -1
  105. package/dist/pdf-pages.js +275 -14
  106. package/dist/pdf-pages.js.map +1 -1
  107. package/dist/pdf-pictures.d.ts +30 -3
  108. package/dist/pdf-pictures.d.ts.map +1 -1
  109. package/dist/pdf-pictures.js +50 -8
  110. package/dist/pdf-pictures.js.map +1 -1
  111. package/dist/pdf-work.d.ts +40 -0
  112. package/dist/pdf-work.d.ts.map +1 -0
  113. package/dist/pdf-work.js +734 -0
  114. package/dist/pdf-work.js.map +1 -0
  115. package/dist/plan.d.ts +22 -4
  116. package/dist/plan.d.ts.map +1 -1
  117. package/dist/plan.js +61 -12
  118. package/dist/plan.js.map +1 -1
  119. package/dist/retry.d.ts +23 -1
  120. package/dist/retry.d.ts.map +1 -1
  121. package/dist/retry.js +33 -3
  122. package/dist/retry.js.map +1 -1
  123. package/dist/search.d.ts +8 -2
  124. package/dist/search.d.ts.map +1 -1
  125. package/dist/search.js +60 -10
  126. package/dist/search.js.map +1 -1
  127. package/dist/sse.d.ts +35 -2
  128. package/dist/sse.d.ts.map +1 -1
  129. package/dist/sse.js +145 -31
  130. package/dist/sse.js.map +1 -1
  131. package/dist/stores.d.ts.map +1 -1
  132. package/dist/stores.js +5 -2
  133. package/dist/stores.js.map +1 -1
  134. package/dist/text-index.d.ts +6 -0
  135. package/dist/text-index.d.ts.map +1 -1
  136. package/dist/text-index.js +25 -8
  137. package/dist/text-index.js.map +1 -1
  138. package/dist/text.d.ts +62 -2
  139. package/dist/text.d.ts.map +1 -1
  140. package/dist/text.js +314 -14
  141. package/dist/text.js.map +1 -1
  142. package/dist/tools.d.ts +61 -1
  143. package/dist/tools.d.ts.map +1 -1
  144. package/dist/tools.js +269 -42
  145. package/dist/tools.js.map +1 -1
  146. package/dist/types.d.ts +102 -3
  147. package/dist/types.d.ts.map +1 -1
  148. package/dist/zip-directory.d.ts +43 -0
  149. package/dist/zip-directory.d.ts.map +1 -0
  150. package/dist/zip-directory.js +130 -0
  151. package/dist/zip-directory.js.map +1 -0
  152. package/docs/README.md +288 -0
  153. package/docs/api.md +37 -381
  154. package/docs/configuration.md +28 -558
  155. package/docs/getting-started.md +407 -223
  156. package/docs/guides/anthropic.md +590 -0
  157. package/docs/guides/conversations.md +629 -0
  158. package/docs/guides/costs-and-limits.md +726 -0
  159. package/docs/guides/deployment.md +654 -0
  160. package/docs/guides/errors-and-reliability.md +735 -0
  161. package/docs/guides/explorer-model.md +399 -0
  162. package/docs/guides/openai-compatible.md +602 -0
  163. package/docs/guides/own-adapter-and-loop.md +1169 -0
  164. package/docs/guides/pdfs.md +971 -0
  165. package/docs/guides/storage.md +731 -0
  166. package/docs/guides/testing.md +1199 -0
  167. package/docs/guides/vertex-and-gemini.md +717 -0
  168. package/docs/guides/web-app.md +1589 -0
  169. package/docs/how-it-works.md +1012 -164
  170. package/docs/measurements.md +881 -0
  171. package/docs/publishing.md +274 -46
  172. package/docs/reference/anthropic.md +427 -0
  173. package/docs/reference/ask.md +892 -0
  174. package/docs/reference/errors-and-retries.md +758 -0
  175. package/docs/reference/events.md +993 -0
  176. package/docs/reference/gemini.md +823 -0
  177. package/docs/reference/library.md +1467 -0
  178. package/docs/reference/node.md +528 -0
  179. package/docs/reference/openai.md +385 -0
  180. package/docs/reference/tools.md +883 -0
  181. package/docs/security.md +897 -103
  182. package/docs/troubleshooting.md +1390 -0
  183. package/package.json +2 -2
  184. package/src/analyze.ts +93 -42
  185. package/src/anthropic/adapter.ts +196 -39
  186. package/src/ask.ts +1087 -202
  187. package/src/encoding.ts +850 -0
  188. package/src/errors.ts +17 -0
  189. package/src/events.ts +442 -0
  190. package/src/evidence.ts +5 -2
  191. package/src/extract.ts +602 -62
  192. package/src/gemini/adapter.ts +118 -65
  193. package/src/gemini/chat.ts +28 -4
  194. package/src/gemini/errors.ts +34 -1
  195. package/src/gemini/generate.ts +23 -10
  196. package/src/gemini/index.ts +3 -3
  197. package/src/gemini/sse.ts +1 -1
  198. package/src/http.ts +376 -1
  199. package/src/index.ts +27 -5
  200. package/src/library.ts +459 -85
  201. package/src/map-reduce.ts +252 -51
  202. package/src/model.ts +236 -3
  203. package/src/node/handlers.ts +137 -22
  204. package/src/node/index.ts +2 -0
  205. package/src/node/sse.ts +198 -0
  206. package/src/openai/adapter.ts +306 -38
  207. package/src/output-limit.ts +44 -8
  208. package/src/pause.ts +41 -0
  209. package/src/pdf-pages.ts +268 -15
  210. package/src/pdf-pictures.ts +56 -9
  211. package/src/pdf-work.ts +722 -0
  212. package/src/plan.ts +68 -12
  213. package/src/retry.ts +49 -5
  214. package/src/search.ts +63 -10
  215. package/src/sse.ts +153 -28
  216. package/src/stores.ts +5 -2
  217. package/src/text-index.ts +26 -7
  218. package/src/text.ts +323 -13
  219. package/src/tools.ts +261 -42
  220. package/src/types.ts +107 -4
  221. package/src/zip-directory.ts +136 -0
package/src/ask.ts CHANGED
@@ -1,10 +1,15 @@
1
1
  // The tool loop, for any model: plan the documents, offer the tools, run the calls within the
2
2
  // limits of the request, and end with an answer. A provider is an adapter (see model.ts).
3
+ import { eventErrorOf, EventEmitter, eventStream, newRunId, type AskEvent, type DocumentRef, type EventResult, type EventStream, type NoticeCode, type RequestPurpose, type RequestRole, type ToolOutcome } from "./events.js";
3
4
  import { evidenceOf, stubResult, type Evidence } from "./evidence.js";
5
+ import { isCutReply, until } from "./http.js";
4
6
  import type { LargeFiles } from "./library.js";
5
7
  import { Limiter } from "./limiter.js";
6
8
  import {
7
9
  DocumentsNotFoundError,
10
+ errorKindOf,
11
+ laterResult,
12
+ rateAllowanceOf,
8
13
  UsageMeter,
9
14
  type ChatMessage,
10
15
  type ModelAdapter,
@@ -20,15 +25,30 @@ import {
20
25
  } from "./model.js";
21
26
  import { estimateParts, REQUEST_BYTES_MARGIN } from "./plan.js";
22
27
  import { statusOf, withRetry, type RetryNotice, type RetryOptions } from "./retry.js";
23
- import { estimateTokens, jsonBytes } from "./text.js";
24
- import { MAX_WHOLE_DOCUMENT_READS, TOOL_NAMES, toolResultSummary } from "./tools.js";
25
- import type { Budget, DocumentPlan, GenerateText, ToolCallLimits, ToolOutput, ToolResult } from "./types.js";
28
+ import { estimateTokens, jsonBytes, wellFormedJson } from "./text.js";
29
+ import {
30
+ alreadyShown,
31
+ failureKind,
32
+ fitAnswer,
33
+ LEAST_RESULT_CHARACTERS,
34
+ MAX_WHOLE_DOCUMENT_READS,
35
+ repeatedFailureHint,
36
+ stepLine,
37
+ TOOL_NAMES,
38
+ toolCallKey,
39
+ toolResultSummary,
40
+ unknownToolName,
41
+ } from "./tools.js";
42
+ import type { Budget, DocumentMeta, DocumentPlan, GenerateText, ToolCallHooks, ToolCallLimits, ToolOutput, ToolRequestEnd, ToolRequestHandle, ToolRequestStart, ToolResult } from "./types.js";
26
43
 
27
44
  /** Sent (invisibly to the user) when the model must stop using tools and answer. */
28
45
  export const FINAL_ANSWER_REQUEST = "Stop using tools now. Answer my question using only what the tools returned above, with line citations. Say plainly what you could not find.";
29
46
  /** The same, when the only tool was `view_pages`: the text of the files is in the prompt, not in tool results. */
30
47
  export const FINAL_ANSWER_AFTER_PAGES = "Stop using tools now. Answer my question from the text of the files and the pages you looked at. Say plainly what you could not see or find.";
31
- /** Sent to the answering model when an explorer model used no tool, so there is no tool result to answer from. */
48
+ /**
49
+ * Sent when no tool ran (an explorer model called none, the first reply was empty, or no turn was
50
+ * left for tools), so there is no tool result to answer from.
51
+ */
32
52
  export const FINAL_ANSWER_WITHOUT_TOOLS = "Answer my question now, from what is in this conversation. No tools are available for this reply: if the answer needs a part of a file that is not shown here, say so plainly.";
33
53
  /**
34
54
  * Added to the system instruction of an explorer model's requests: it gathers what the answer
@@ -42,7 +62,8 @@ export type AskLimits = {
42
62
  * The most model requests of the chat for one question, counting the answer. Tools can run in
43
63
  * all but the last: if the model is still calling tools then, the last request must be answered
44
64
  * in text. Defaults to 12. With an explorer model the answer is always a request of its own, so
45
- * the explorer has one less than this.
65
+ * the explorer has one less than this. An answer that comes back without text is asked for once
66
+ * more, and that request can be one past this.
46
67
  */
47
68
  toolTurns?: number;
48
69
  /**
@@ -105,7 +126,11 @@ export type AskOptions = {
105
126
  * what the adapters say of their models (`capabilities.contextTokens`, `maxRequestBytes`).
106
127
  */
107
128
  budget?: Partial<Budget>;
108
- /** Offer `analyze_whole_document`, which reads a whole file in many model calls. Defaults to true. */
129
+ /**
130
+ * Offer `analyze_whole_document`, which reads a whole file in many model calls. Defaults to true.
131
+ * It is offered only when the model that uses the tools (`explorer`, or else `model`) has
132
+ * `generateText`.
133
+ */
109
134
  wholeDocumentAnalysis?: boolean;
110
135
  /**
111
136
  * Offer `view_pages` for PDFs whose original file is kept (`keepOriginals`), so the model can
@@ -113,12 +138,36 @@ export type AskOptions = {
113
138
  * the question can be sent a file, and changes nothing for a library that keeps no originals.
114
139
  */
115
140
  viewPages?: boolean;
116
- /** Answer text as it arrives. The adapter streams when this is set and it can. */
141
+ /** Answer text as it arrives. The adapter streams when this is set and it can (see `streamText`). */
117
142
  onText?: (delta: string) => void;
143
+ /**
144
+ * Whether to ask the model for the answer as it is written (the adapter's streaming request).
145
+ * Defaults to true when `onText` is given, false otherwise; `askStream` defaults it to true. With
146
+ * it, a reply that fails after its first piece of text is not sent again. New in 0.7.0.
147
+ */
148
+ streamText?: boolean;
118
149
  /** Short-lived status, such as "Searching app.log for “timeout”…". */
119
150
  onActivity?: (text: string) => void;
120
151
  /** A finished step, such as "Search app.log (exact) for “timeout” — 12 matching lines". */
121
152
  onStep?: (text: string) => void;
153
+ /**
154
+ * Everything the question does, as typed events in order: the plan, each model request, tool
155
+ * call, piece of text and notice, and last `run.finish` or `run.error`. The callbacks above get
156
+ * the same strings as before. It does not change how the model is asked: without `streamText`
157
+ * (or `onText`), the text of a reply comes in its `text` events once the reply is in. A throw
158
+ * from it ends the question with that error (on `run.finish`, the answer is lost: `askWithFiles`
159
+ * throws it; on `run.error`, it replaces the question's own error). `askStream` gives the events
160
+ * as an async iterable. New in 0.7.0.
161
+ */
162
+ onEvent?: (event: AskEvent) => void;
163
+ /** The `runId` of the events. Defaults to one made for the question ("run_…"). */
164
+ runId?: string;
165
+ /**
166
+ * Put each tool result in its `tool.end` event (`result`), and the tool rounds in the result that
167
+ * `run.finish` and `run.error` carry (`toolTurns`). Off by default: results hold the text of the
168
+ * documents, and events are often sent on to a browser.
169
+ */
170
+ eventResults?: boolean;
122
171
  signal?: AbortSignal;
123
172
  };
124
173
 
@@ -173,10 +222,14 @@ const BYTES_PER_CHARACTER = 3;
173
222
  const ROUNDS_KEPT = [3, 2, 1];
174
223
 
175
224
  const NO_ROOM = "Not run: there is no room left in this conversation for another tool result. Answer now, from what the tools returned so far.";
225
+ /** Why a request of a whole-file read that its read left behind ended with its call. */
226
+ const CALL_ENDED = "The tool call ended before this request did.";
176
227
 
177
228
  type Size = { tokens: number; bytes: number };
178
229
 
179
230
  const count = (value: number) => Math.max(0, Math.round(value)).toLocaleString("en-US");
231
+ /** How many of a model's tokens one token of the library's estimate comes to. */
232
+ const scaleOf = (adapter: ModelAdapter): number => (adapter.capabilities.tokenScale && adapter.capabilities.tokenScale > 0 ? adapter.capabilities.tokenScale : 1);
180
233
  const isRound = (message: ModelMessage): message is ModelToolRound => message.role === "tools";
181
234
 
182
235
  /** How many pages a `view_pages` result showed: its `pages` is "12" or "12-14". */
@@ -185,11 +238,18 @@ function pagesShown(result: ToolResult): number {
185
238
  return Number.isFinite(first) ? (Number.isFinite(last) ? last! - first! + 1 : 1) : 0;
186
239
  }
187
240
 
241
+ /**
242
+ * A result of a tool round of an earlier question, as it is sent again: without its
243
+ * `tool_turns_left`, which counted the turns of that question, not of this one, and with no half of a
244
+ * character in it (0.5.0 cut some search windows inside an emoji, and Claude's API refuses them).
245
+ */
246
+ const carriedResult = (result: ToolResult): ToolResult => wellFormedJson(laterResult(result));
247
+
188
248
  /** The conversation as the loop keeps it: copies, so that nothing of the caller's is changed. */
189
249
  function toMessages(given: ChatMessage[]): ModelMessage[] {
190
250
  const messages = given.map((message): ModelMessage => {
191
251
  if (message.role === "tools") {
192
- const answers = message.calls.map(({ result, ...call }) => ({ call, result }));
252
+ const answers = message.calls.map(({ result, ...call }) => ({ call, result: carriedResult(result) }));
193
253
  return { role: "tools", calls: answers.map((answer) => answer.call), answers };
194
254
  }
195
255
  const role = message.role === "user" ? "user" : "assistant";
@@ -280,14 +340,138 @@ class RequestMeter {
280
340
  observe(estimated: number, counted: number | undefined): void {
281
341
  if (estimated > 0 && typeof counted === "number" && counted > 0) this.factor = Math.min(2, Math.max(1, counted / estimated));
282
342
  }
343
+
344
+ /**
345
+ * Takes note of a request the provider refused as too large: it counted `counted` tokens (in the
346
+ * library's tokens by the model's scale) of one estimated at `estimated`, or, when it did not say,
347
+ * a quarter more than the estimate. Unlike `observe`, nothing caps it at twice the estimate: the
348
+ * refusal is the provider's word that the estimate was too low.
349
+ */
350
+ overflowed(estimated: number, counted: number | undefined): void {
351
+ const ratio = estimated > 0 && typeof counted === "number" && counted > 0 ? counted / estimated : this.factor * 1.25;
352
+ this.factor = Math.min(8, Math.max(this.factor, ratio));
353
+ }
354
+ }
355
+
356
+ /**
357
+ * Shares `room` characters among tool calls whose results may be up to `caps` characters. A call
358
+ * gets no more than its cap, and the others split what it leaves. Calls that cannot each get
359
+ * `LEAST_ROOM_CHARACTERS` (or their cap, when it is smaller) are not run, the last ones first:
360
+ * their share is undefined.
361
+ */
362
+ export function shareRoom(caps: number[], room: number): Array<number | undefined> {
363
+ const least = (cap: number) => Math.min(cap, LEAST_ROOM_CHARACTERS);
364
+ let count = caps.length;
365
+ let needed = caps.reduce((sum, cap) => sum + least(cap), 0);
366
+ while (count > 0 && needed > room) needed -= least(caps[--count]!);
367
+ const shares: Array<number | undefined> = caps.map(() => undefined);
368
+ // The smallest caps first: each call takes its cap or an even share of what is left, whichever is less.
369
+ const order = caps.slice(0, count).map((cap, index) => ({ cap, index })).sort((left, right) => left.cap - right.cap);
370
+ let left = Math.max(0, Math.floor(room));
371
+ order.forEach(({ cap, index }, position) => {
372
+ const share = Math.min(cap, Math.floor(left / (order.length - position)));
373
+ shares[index] = share;
374
+ left -= share;
375
+ });
376
+ return shares;
283
377
  }
284
378
 
285
379
  function retryMessage({ error, delayMs }: RetryNotice): string {
286
380
  const status = statusOf(error);
287
381
  const seconds = delayMs >= 1_000 ? ` in ${Math.round(delayMs / 1_000)} s` : "";
288
- return `${status ? `The model did not answer (HTTP ${status})` : "The model could not be reached"}. Trying again${seconds}…`;
382
+ const what = errorKindOf(error) === "timeout" && status === 0 ? "The model sent nothing for too long"
383
+ // The model was reached, and its reply began to arrive.
384
+ : isCutReply(error) ? "The model's reply was cut off on its way"
385
+ : status ? `The model did not answer (HTTP ${status})` : "The model could not be reached";
386
+ return `${what}. Trying again${seconds}…`;
289
387
  }
290
388
 
389
+ /** What the question had found when it failed: see `partialResultOf`. */
390
+ const partialResults = new WeakMap<object, AskResult>();
391
+
392
+ /**
393
+ * What a question that failed had done before it failed: its tool steps, evidence, tool rounds and
394
+ * usage, with `answered: false`. `askWithFiles` throws the provider's error as it came (a
395
+ * `ModelRequestError` that was not worth sending again, or still failed after the retries); this
396
+ * gives what was found and paid for until then, so that an application can keep the tool rounds
397
+ * with the conversation and count the usage. Undefined for an error that did not come from a
398
+ * question under way (a document that is missing, a budget that does not work).
399
+ */
400
+ export function partialResultOf(error: unknown): AskResult | undefined {
401
+ return error !== null && typeof error === "object" ? partialResults.get(error) : undefined;
402
+ }
403
+
404
+ /**
405
+ * What a question that is planned again carries over from its first try: what it paid for and the
406
+ * steps it showed, so that the totals, the ceilings of `limits` and the steps of the result count
407
+ * them, and the window the documents are planned for now.
408
+ */
409
+ type Carried = {
410
+ usage: UsageMeter;
411
+ steps: string[];
412
+ turns: number;
413
+ /** Chat requests of the first try that were answered: each took a tool turn of the question. */
414
+ answered: number;
415
+ nudges: number;
416
+ recoveries: number;
417
+ contextTokens: number;
418
+ step: string;
419
+ };
420
+
421
+ /**
422
+ * Thrown inside a question whose first requests were too large for the model before any tool ran,
423
+ * when nothing can be shortened: the documents are planned again for a smaller window. Never
424
+ * leaves `askWithFiles`.
425
+ */
426
+ class Replan extends Error {
427
+ constructor(readonly carried: Carried, readonly overflow: unknown, readonly partial: AskResult) {
428
+ super("replan");
429
+ }
430
+ }
431
+
432
+ /** Sent, once, after a tool turn whose call could not be read. Not kept in the conversation. */
433
+ const MALFORMED_CALL_NUDGE = "Your last reply tried to call a tool, but the call could not be read. Call the tools again, with arguments that match their declarations, or answer if you already have enough.";
434
+ const MALFORMED_EXPLORER_NUDGE = "Your last reply tried to call a tool, but the call could not be read. Call the tools again, with arguments that match their declarations, or reply DONE if the results above already hold what the answer needs.";
435
+ /** Sent, once, after a first reply that was empty. Not kept in the conversation. */
436
+ const EMPTY_REPLY_NUDGE = "Your last reply was empty. Use the tools to read the files the question is about, or answer the question.";
437
+ const EMPTY_EXPLORER_NUDGE = "Your last reply was empty. Call the tools to gather what the answer needs from the files, then reply DONE.";
438
+ /**
439
+ * Sent, once, after a reply to the answer's request that had no text: it was empty, or held a tool
440
+ * call that the model was told not to make. Not kept in the conversation.
441
+ */
442
+ const ANSWER_AGAIN_NOTE = "Your last reply had no text. No tool can be called in this reply: write the answer now, in text, from what is above.";
443
+ /** The most such second tries in one question, the answer's included. */
444
+ const MOST_NUDGES = 2;
445
+ /** The most requests sent again, smaller, after the provider refused one as too large. */
446
+ const MOST_OVERFLOW_RECOVERIES = 2;
447
+
448
+ /** Said, once, when a ceiling of `limits` stops the tools. */
449
+ const BUDGET_REACHED = "No more tools: the question reached its limit of input tokens or requests.";
450
+
451
+ /**
452
+ * What the tries of one question share for its events: where they go, and the counters of the ids
453
+ * of its requests and tool calls, which a question planned again goes on counting.
454
+ */
455
+ type RunState = {
456
+ events: EventEmitter<AskEvent>;
457
+ requests: number;
458
+ calls: number;
459
+ /** True once "budget_reached" was said. */
460
+ budgetSaid: boolean;
461
+ };
462
+
463
+ /** A document as an event names it. */
464
+ const documentRef = (meta: DocumentMeta): DocumentRef => ({
465
+ id: meta.id,
466
+ name: meta.name,
467
+ format: meta.format,
468
+ estimatedTokens: meta.estimatedTokens,
469
+ ...(meta.pages !== undefined ? { pages: meta.pages } : {}),
470
+ });
471
+
472
+ /** Which model a chat request goes to, and why. */
473
+ type RequestKind = { role: RequestRole; purpose: RequestPurpose };
474
+
291
475
  /**
292
476
  * Answers a chat turn about large documents with any model that has an adapter.
293
477
  * Documents that fit go into the prompt whole; otherwise the model gets search and read tools and
@@ -295,20 +479,106 @@ function retryMessage({ error, delayMs }: RetryNotice): string {
295
479
  * an answer. With an `explorer`, that model runs the tool loop and `model` writes the answer.
296
480
  */
297
481
  export async function askWithFiles(options: AskOptions): Promise<AskResult> {
482
+ const events = new EventEmitter<AskEvent>(options.runId ?? newRunId(), options.onEvent);
483
+ const state: RunState = { events, requests: 0, calls: 0, budgetSaid: false };
484
+ try {
485
+ if (events.active) {
486
+ // Always first, whatever the options hold: they are checked after it, and a question whose
487
+ // options do not work ends with run.error like any other.
488
+ const { model, explorer, documentIds } = options as Partial<AskOptions>;
489
+ const other = explorer && explorer !== model ? explorer : undefined;
490
+ events.emit({
491
+ type: "run.start",
492
+ models: { answer: model?.id ?? "", ...(other ? { explorer: other.id } : {}) },
493
+ documentIds: Array.isArray(documentIds) ? [...documentIds] : [],
494
+ });
495
+ }
496
+ const result = await askPlanned(options, state);
497
+ if (events.active) events.emit({ type: "run.finish", result: eventResultOf(result, options.eventResults === true) });
498
+ return result;
499
+ } catch (error) {
500
+ if (events.active) {
501
+ const partial = partialResultOf(error);
502
+ events.emit({ type: "run.error", error: eventErrorOf(error), ...(partial ? { partial: eventResultOf(partial, options.eventResults === true) } : {}) });
503
+ }
504
+ throw error;
505
+ }
506
+ }
507
+
508
+ /**
509
+ * A result as `run.finish` and `run.error` carry it: a copy, so that a listener cannot change the
510
+ * caller's, without the tool rounds and with the plan naming documents only (both hold text of
511
+ * the documents: tool results, outline headings, the commonest lines of a log) unless `withTurns`.
512
+ */
513
+ function eventResultOf(result: AskResult, withTurns: boolean): EventResult {
514
+ if (withTurns) return { ...result };
515
+ const { toolTurns: _toolTurns, plan, ...rest } = result;
516
+ return { ...rest, plan: { inline: plan.inline.map(documentRef), searchable: plan.searchable.map(documentRef) } };
517
+ }
518
+
519
+ /**
520
+ * `askWithFiles` as a stream of its events, for a page that shows the question as it goes: see
521
+ * `AskEvent`. Leaving the loop early (`break`) stops the question. `result` is what `askWithFiles`
522
+ * returns. `onEvent`, when given, gets each event too, after the stream. The model is asked for
523
+ * the answer as it is written unless `streamText` is false. New in 0.7.0.
524
+ */
525
+ export function askStream(options: AskOptions): EventStream<AskEvent, AskResult> {
526
+ return eventStream<AskEvent, AskResult>((onEvent, signal) => askWithFiles({
527
+ ...options,
528
+ // A page that reads the events shows the text as it is written, unless told not to.
529
+ streamText: options.streamText !== false,
530
+ signal,
531
+ onEvent: (event) => {
532
+ // The stream first: a throw of the caller's listener cannot keep an event, the last one
533
+ // included, from the stream.
534
+ onEvent(event);
535
+ options.onEvent?.(event);
536
+ },
537
+ }), { signal: options.signal });
538
+ }
539
+
540
+ /** The question, planned again once when its first requests were too large for the model. */
541
+ async function askPlanned(options: AskOptions, state: RunState): Promise<AskResult> {
542
+ try {
543
+ return await ask(options, undefined, state);
544
+ } catch (error) {
545
+ if (!(error instanceof Replan)) throw error;
546
+ // The first requests were too large for the model, and nothing in them could be shortened: the
547
+ // documents are planned again for the window the provider named, or a smaller one. Once. The
548
+ // window is a limit of the model's, as one it declares: the application's budget is fitted to it.
549
+ try {
550
+ return await ask(options, error.carried, state);
551
+ } catch (again) {
552
+ // Failed before it sent anything (a budget of the application's that cannot work with the
553
+ // smaller window): the provider's error, with what the first try found, is the one to report.
554
+ if (partialResultOf(again) === undefined && (again as { status?: unknown } | null)?.status === undefined) {
555
+ if (error.overflow !== null && typeof error.overflow === "object") partialResults.set(error.overflow, error.partial);
556
+ throw error.overflow;
557
+ }
558
+ throw again;
559
+ }
560
+ }
561
+ }
562
+
563
+ async function ask(options: AskOptions, carried: Carried | undefined, state: RunState): Promise<AskResult> {
298
564
  const { files, model, signal } = options;
565
+ const { events } = state;
299
566
  // A second model for the requests that use tools. The answering model itself is not one.
300
567
  const explorer = options.explorer && options.explorer !== model ? options.explorer : undefined;
301
568
  const toolModel = explorer ?? model;
302
569
  const models = explorer ? [model, explorer] : [model];
303
570
  const limits = options.limits ?? {};
304
- const usage = new UsageMeter();
571
+ // A question planned again goes on counting what its first try paid for.
572
+ const usage = carried?.usage ?? new UsageMeter();
305
573
 
306
574
  // The budget is counted in the library's estimate of tokens. A model whose tokenizer counts
307
575
  // more of them for the same text has, in those terms, a smaller window.
308
- const scale = Math.max(...models.map((adapter) => (adapter.capabilities.tokenScale && adapter.capabilities.tokenScale > 0 ? adapter.capabilities.tokenScale : 1)));
576
+ const scale = Math.max(...models.map(scaleOf));
309
577
  const declared = (pick: (adapter: ModelAdapter) => number | undefined): number[] => models.map(pick).filter((value): value is number => typeof value === "number" && value > 0);
310
578
  const own = files.budgetFor(options.budget);
311
- const windowTokens = Math.floor(Math.min(own.contextTokens, ...declared((adapter) => adapter.capabilities.contextTokens)) / scale);
579
+ // The window in the models' own tokens, and in the library's.
580
+ const modelWindow = Math.min(own.contextTokens, carried?.contextTokens ?? Number.POSITIVE_INFINITY, ...declared((adapter) => adapter.capabilities.contextTokens));
581
+ const windowTokens = Math.floor(modelWindow / scale);
312
582
  // A reply that is counted against the window: that part of it is not there for the prompt.
313
583
  const replyTokens = Math.ceil(Math.max(0, ...declared((adapter) => adapter.capabilities.outputTokens)) / scale);
314
584
  const requestBytesLimit = declared((adapter) => adapter.capabilities.maxRequestBytes);
@@ -321,6 +591,9 @@ export async function askWithFiles(options: AskOptions): Promise<AskResult> {
321
591
  const canShowFiles = models.every((adapter) => adapter.capabilities.toolFiles !== "none");
322
592
  // Every model must be able to take a conversation whose earlier turns were made shorter.
323
593
  const canShrink = models.every((adapter) => !adapter.capabilities.appendOnly);
594
+ // A call made again is answered with a pointer to its earlier result only while that result stays
595
+ // in the conversation: a provider that clears old tool results on its side may have removed it.
596
+ const canPoint = models.every((adapter) => !adapter.capabilities.clearsToolResults);
324
597
 
325
598
  const messages = toMessages(options.messages);
326
599
  const meter = new RequestMeter(pageTokens);
@@ -329,6 +602,8 @@ export async function askWithFiles(options: AskOptions): Promise<AskResult> {
329
602
  const prepared = await files.prepare(options.documentIds, { tokens: asText.tokens + earlier.tokens, bytes: asText.bytes + earlier.bytes }, {
330
603
  ...(options.owner !== undefined ? { owner: options.owner } : {}),
331
604
  viewPages: options.viewPages !== false && canShowFiles,
605
+ // The guide and the cards name `analyze_whole_document` only when the tools will have it.
606
+ wholeDocumentAnalysis: options.wholeDocumentAnalysis !== false && typeof toolModel.generateText === "function",
332
607
  budget,
333
608
  });
334
609
  if (prepared.missing.length) throw new DocumentsNotFoundError(prepared.missing);
@@ -355,20 +630,44 @@ export async function askWithFiles(options: AskOptions): Promise<AskResult> {
355
630
  }
356
631
 
357
632
  let text = "";
358
- let turns = 0;
633
+ let turns = carried?.turns ?? 0;
359
634
  let finishReason: string | undefined;
360
635
  let blockReason: string | undefined;
361
636
  let lastUsage: Record<string, unknown> | undefined;
362
637
  const steps: string[] = [];
363
638
  const evidence: Evidence[] = [];
364
- const emit = (delta: string) => {
639
+ const emit = (delta: string, requestId: string) => {
365
640
  text += delta;
366
641
  options.onText?.(delta);
642
+ events.emit({ type: "text", requestId, delta });
643
+ };
644
+ /**
645
+ * A step can quote what the model sent: it is made one line of plain text before anyone sees it.
646
+ * A step that is not a tool call's is also a notice, with that code. Returns the line.
647
+ */
648
+ const step = (line: string, code?: NoticeCode): string => {
649
+ const plain = stepLine(line);
650
+ steps.push(plain);
651
+ options.onStep?.(plain);
652
+ if (code) events.emit({ type: "notice", code, message: plain, display: "step" });
653
+ return plain;
654
+ };
655
+ /** Short-lived status that is also a notice. */
656
+ const activity = (code: NoticeCode, message: string) => {
657
+ options.onActivity?.(message);
658
+ events.emit({ type: "notice", code, message, display: "activity" });
367
659
  };
368
- const step = (line: string) => {
369
- steps.push(line);
370
- options.onStep?.(line);
660
+ /** A notice that earlier versions did not show. */
661
+ const notice = (code: NoticeCode, message: string) => events.emit({ type: "notice", code, message, display: "none" });
662
+ const budgetReached = () => {
663
+ if (state.budgetSaid) return;
664
+ state.budgetSaid = true;
665
+ notice("budget_reached", BUDGET_REACHED);
371
666
  };
667
+ // What a first try that was planned again showed is part of this question; then why it was planned again.
668
+ steps.push(...carried?.steps ?? []);
669
+ if (carried) step(carried.step, "replanned");
670
+ if (events.active) events.emit({ type: "plan", inline: prepared.plan.inline.map(documentRef), searchable: prepared.plan.searchable.map(documentRef) });
372
671
 
373
672
  // A model turn in its provider's own form goes back only to the adapter it came from. Any other
374
673
  // model gets the tool calls alone: a thought signature belongs to the model that wrote it, and
@@ -383,45 +682,99 @@ export async function askWithFiles(options: AskOptions): Promise<AskResult> {
383
682
  }
384
683
  return known;
385
684
  };
386
- const viewFor = (adapter: ModelAdapter, list: ModelMessage[] = messages): ModelMessage[] => list.map((message) => (
387
- isRound(message) && message.raw !== undefined && rawOwner.get(message) !== adapter ? callsOnly(message) : message
388
- ));
685
+ /**
686
+ * Turns that hold a note for the model that explores, kept in the conversation because that model
687
+ * may not have it rewritten (see `notedMessages`), with the turn as it was before the note, or
688
+ * undefined for a turn that is only the note. The other model never gets them.
689
+ */
690
+ const notes = new Map<ModelMessage, ModelMessage | undefined>();
691
+ const viewFor = (adapter: ModelAdapter, list: ModelMessage[] = messages): ModelMessage[] => list.flatMap((message): ModelMessage[] => {
692
+ if (adapter !== toolModel && notes.has(message)) {
693
+ const before = notes.get(message);
694
+ return before ? [before] : [];
695
+ }
696
+ return [isRound(message) && message.raw !== undefined && rawOwner.get(message) !== adapter ? callsOnly(message) : message];
697
+ });
389
698
 
390
699
  /**
391
700
  * One model request of the chat. Text is passed on as it arrives when it is `shown`: an
392
701
  * explorer's words are not, because the answer comes from the other model. A request that
393
702
  * failed is sent again by the rule of `retry`, unless text of it was already shown.
394
703
  */
395
- const request = async (adapter: ModelAdapter, body: ModelRequest, shown: boolean): Promise<ModelReply> => {
704
+ /** Chat requests of the question that were answered, those of a first try included: each took a tool turn. */
705
+ let answeredRequests = carried?.answered ?? 0;
706
+ const streamText = options.streamText ?? options.onText !== undefined;
707
+ const request = async (adapter: ModelAdapter, body: ModelRequest, shown: boolean, kind: RequestKind): Promise<ModelReply> => {
396
708
  turns++;
709
+ const requestId = `req_${++state.requests}`;
710
+ const began = Date.now();
397
711
  let separated = text.length === 0;
398
712
  let got = "";
399
713
  const write = (delta: string) => {
400
- if (!delta) return;
714
+ // Nothing more is shown once the question was stopped, by an adapter that goes on regardless.
715
+ if (!delta || signal?.aborted) return;
401
716
  if (!separated) {
402
- emit("\n\n");
717
+ emit("\n\n", requestId);
403
718
  separated = true;
404
719
  }
405
720
  got += delta;
406
- emit(delta);
721
+ emit(delta, requestId);
407
722
  };
408
723
  const estimated = meter.estimate(body.messages).tokens;
409
- const reply = await withRetry(() => adapter.send(body, {
410
- ...(signal ? { signal } : {}),
411
- ...(shown && options.onText ? { onText: write } : {}),
412
- }), {
413
- retry: options.retry,
414
- signal,
415
- canRetry: () => got.length === 0,
416
- onRetry: (notice) => options.onActivity?.(retryMessage(notice)),
417
- });
724
+ let reply: ModelReply;
725
+ try {
726
+ // In the try: a listener that throws on the start still gets its end.
727
+ events.emit({ type: "request.start", requestId, role: kind.role, purpose: kind.purpose, model: adapter.id, turn: turns, estimatedInputTokens: estimated });
728
+ reply = await withRetry(() => {
729
+ // Nothing is sent once the question was stopped.
730
+ signal?.throwIfAborted();
731
+ const sending = adapter.send(body, {
732
+ ...(signal ? { signal } : {}),
733
+ // The adapter streams only when the text is asked for as it is written: a listener of
734
+ // the events alone does not change how the model is asked.
735
+ ...(shown && streamText ? { onText: write } : {}),
736
+ });
737
+ // The question stops when the signal aborts, whether the adapter does or not: one that does
738
+ // not look at it would hold the question, and the user, until its request ends, if it ever
739
+ // does. That holds when the signal aborted while the adapter was called (its onText ran the
740
+ // caller's code): `until` then ends at once with the signal's reason.
741
+ return until(sending, signal);
742
+ }, {
743
+ retry: options.retry,
744
+ signal,
745
+ canRetry: () => got.length === 0,
746
+ onRetry: (retried) => {
747
+ const message = retryMessage(retried);
748
+ options.onActivity?.(message);
749
+ if (events.active) events.emit({ type: "retry", requestId, attempt: retried.attempt, delayMs: retried.delayMs, error: eventErrorOf(retried.error), message });
750
+ },
751
+ });
752
+ } catch (error) {
753
+ if (events.active) events.emit({ type: "request.end", requestId, ms: Date.now() - began, outcome: "error", error: eventErrorOf(error) });
754
+ throw error;
755
+ }
418
756
  // Text the adapter did not pass on as it came (no streaming was asked for, or it cannot).
419
757
  if (shown && reply.text.length > got.length && reply.text.startsWith(got)) write(reply.text.slice(got.length));
758
+ answeredRequests++;
420
759
  usage.add(adapter.id, reply.usage);
421
- meter.observe(estimated, typeof reply.usage?.inputTokens === "number" ? reply.usage.inputTokens / scale : undefined);
760
+ // The count of the model that answered, in the library's tokens by that model's own scale: how
761
+ // much more than its scale says the text costs it, which the other model will see too. By the
762
+ // larger scale of the two, a count of the model with the smaller one was taken for no more.
763
+ meter.observe(estimated, typeof reply.usage?.inputTokens === "number" ? reply.usage.inputTokens / scaleOf(adapter) : undefined);
422
764
  if (reply.blockReason) blockReason = reply.blockReason;
423
765
  finishReason = reply.finishReason ?? finishReason;
424
766
  lastUsage = reply.providerUsage ?? lastUsage;
767
+ events.emit({
768
+ type: "request.end",
769
+ requestId,
770
+ ms: Date.now() - began,
771
+ outcome: "ok",
772
+ ...(reply.usage ? { usage: reply.usage } : {}),
773
+ ...(reply.finish ? { finish: reply.finish } : {}),
774
+ ...(reply.finishReason !== undefined ? { finishReason: reply.finishReason } : {}),
775
+ toolCalls: reply.calls.length,
776
+ });
777
+ if (reply.blockReason) notice("blocked", `The provider refused the prompt: ${reply.blockReason}.`);
425
778
  return reply;
426
779
  };
427
780
  // What a model wrote before it was stopped by a refusal is not an answer.
@@ -450,39 +803,6 @@ export async function askWithFiles(options: AskOptions): Promise<AskResult> {
450
803
  ...(lastUsage ? { lastUsage } : {}),
451
804
  });
452
805
 
453
- // Tools are needed for a file that is too large to send whole, and for a PDF whose pages can be
454
- // looked at: that one may have its whole text in the prompt and still hide a chart from the model.
455
- const { searchable } = prepared.plan;
456
- const { viewable } = prepared;
457
- if (searchable.length === 0 && viewable.length === 0) return result(wrote(await request(model, { system, messages }, true)));
458
-
459
- // Reading a whole file in parts is exploring too: the explorer model's work, when there is one.
460
- const partReader = options.wholeDocumentAnalysis === false ? undefined : toolModel.generateText;
461
- const generate: GenerateText | undefined = partReader && ((part) => partReader({
462
- ...part,
463
- onUsage: (used) => {
464
- usage.add(toolModel.id, used);
465
- part.onUsage?.(used);
466
- },
467
- }));
468
- const tools = files.tools(searchable, {
469
- ...(generate ? { generate } : {}),
470
- onProgress: (event) => options.onActivity?.(`${event.message}…`),
471
- ...(signal ? { signal } : {}),
472
- ...(viewable.length > 0 ? { viewPages: viewable } : {}),
473
- maxWholeDocumentReads: limits.wholeDocumentReads ?? MAX_WHOLE_DOCUMENT_READS,
474
- ...(options.retry ? { retry: options.retry } : {}),
475
- budget,
476
- });
477
- const declarations = tools.declarations;
478
- // The requests that use the tools are the chat's own, or an explorer model's: the same
479
- // conversation, and a line that says what its part is.
480
- const toolSystem = explorer ? `${system}\n\n${EXPLORER_INSTRUCTION}` : system;
481
- const sentTools = JSON.stringify(declarations);
482
- meter.fixed.tokens += estimateTokens(sentTools) + (explorer ? estimateTokens(EXPLORER_INSTRUCTION) : 0);
483
- meter.fixed.bytes += Buffer.byteLength(sentTools) + (explorer ? EXPLORER_INSTRUCTION.length : 0);
484
- if (searchable.length > 0) options.onActivity?.(`Too large to read at once: ${searchable.map((meta) => meta.name).join(", ")}. Searching instead…`);
485
-
486
806
  // Pages the model looks at stay in the request until the question is answered, so they are
487
807
  // counted twice: as bytes against the request limit, and as tokens against half of what the
488
808
  // budget keeps free for tool results and the answer.
@@ -490,8 +810,9 @@ export async function askWithFiles(options: AskOptions): Promise<AskResult> {
490
810
  const bytesKeptFree = Math.max(REQUEST_BYTES_MARGIN, Math.floor(maxRequestBytes / 10));
491
811
  let pagesLeft = Math.floor(reservedTokens / 2 / pageTokens);
492
812
  // The results of the text tools may fill the context window up to half of what is kept free (the
493
- // other half is the answer's), and the request up to a small margin.
494
- const tokenLimit = budget.contextTokens - Math.floor(reservedTokens / 2);
813
+ // other half is the answer's), and the request up to a small margin. A provider that refuses a
814
+ // request as too large, and names its window, makes it smaller.
815
+ let tokenLimit = budget.contextTokens - Math.floor(reservedTokens / 2);
495
816
  const byteLimit = maxRequestBytes - Math.max(32_768, Math.floor(maxRequestBytes / 50));
496
817
  /** Characters of tool results that still fit, with a model turn that is about to be answered. */
497
818
  const room = (pending: ModelToolRound): number => {
@@ -521,155 +842,719 @@ export async function askWithFiles(options: AskOptions): Promise<AskResult> {
521
842
  messages[index] = smaller;
522
843
  changed = true;
523
844
  }
845
+ if (changed) unpoint();
524
846
  return changed;
525
847
  };
526
848
 
527
- const maxTurns = Math.max(1, Math.trunc(limits.toolTurns ?? DEFAULT_TOOL_TURNS));
528
- const maxCalls = Math.max(1, Math.trunc(limits.callsPerTurn ?? DEFAULT_CALLS_PER_TURN));
529
- /** True once the question has used what it may: no more tools run. One request is kept for the answer. */
530
- const spent = (): boolean => (
531
- (limits.inputTokens !== undefined && usage.totals.inputTokens >= limits.inputTokens)
532
- || (limits.requests !== undefined && usage.totals.requests >= limits.requests - 1)
533
- );
534
- /** A whole-file read is many requests at once: one that would pass a ceiling of the question is not started. */
535
- const tooCostly = (call: ToolCall): string | undefined => {
536
- if (call.name !== TOOL_NAMES.analyze) return undefined;
537
- const meta = searchable.find((document) => document.id === call.args.document_id);
538
- if (!meta) return undefined;
539
- if (limits.inputTokens !== undefined) {
540
- const cost = Math.ceil(meta.estimatedTokens * scale);
541
- const left = limits.inputTokens - usage.totals.inputTokens;
542
- if (cost > left) return `Not run: reading all of ${meta.name} takes about ${count(cost)} input tokens, and ${count(left)} are left of the ${count(limits.inputTokens)} this question may use. Use search_document and read_document.`;
849
+ /**
850
+ * A pointer ("already shown above") whose result is no longer in the conversation in full (it was
851
+ * shortened to make room, here or in an earlier question) is made a stand-in that says so: the
852
+ * model must not be told to use what it no longer has. Every round is looked at, the kept ones too.
853
+ * With a provider that clears old tool results on its side, every pointer is. So is a pointer to a
854
+ * read of one line made in an earlier question than the pointer: 0.5.0 cut such reads without
855
+ * saying so, and `shownBefore` does not point to them either.
856
+ */
857
+ function unpoint(): void {
858
+ // What the answers before the one looked at hold, as they are now, found once in one pass:
859
+ // the calls whose result is shown in full, by key, and the reads shown in full, by document,
860
+ // with the question each was made in (stored questions are told apart by their user turns).
861
+ const shownKeys = new Set<string>();
862
+ const shownReads = new Map<unknown, Array<{ answer: ToolAnswer; index: number; question: number }>>();
863
+ let question = 0;
864
+ messages.forEach((message, index) => {
865
+ if (!isRound(message)) {
866
+ if (message.role === "user") question++;
867
+ return;
868
+ }
869
+ let touched = false;
870
+ /** The answers of this round so far that are not stand-ins, by key: a call made twice in a turn points to the first. */
871
+ const inRound = new Map<string, ToolAnswer>();
872
+ const answers: ToolAnswer[] = [];
873
+ for (const answer of message.answers) {
874
+ const key = toolCallKey(answer.call.name, answer.call.args);
875
+ let now = answer;
876
+ if (answer.result.already_shown === true) {
877
+ const held = canPoint && ((key !== undefined && (inRound.has(key) || (answer.call.name !== TOOL_NAMES.read && shownKeys.has(key))))
878
+ || (answer.call.name === TOOL_NAMES.read && (shownReads.get(answer.call.args.document_id) ?? [])
879
+ .some((read) => alreadyShown(answer.call, read.answer, read.index < asked && read.question !== question) !== undefined)));
880
+ if (!held) {
881
+ touched = true;
882
+ now = {
883
+ call: answer.call,
884
+ result: {
885
+ ...(typeof answer.result.document === "string" ? { document: answer.result.document } : {}),
886
+ dropped: true,
887
+ note: "Not run then: it repeated an earlier call whose result was later dropped from the conversation to make room. Call it again if you need it.",
888
+ },
889
+ };
890
+ }
891
+ } else if (key !== undefined && alreadyShown(answer.call, answer) !== undefined) {
892
+ // A result in full: what a later pointer may point to.
893
+ if (answer.call.name === TOOL_NAMES.read) {
894
+ const reads = shownReads.get(answer.call.args.document_id) ?? [];
895
+ reads.push({ answer, index, question });
896
+ shownReads.set(answer.call.args.document_id, reads);
897
+ } else {
898
+ shownKeys.add(key);
899
+ }
900
+ }
901
+ if (key !== undefined && now.result.dropped !== true) inRound.set(key, now);
902
+ answers.push(now);
903
+ }
904
+ if (!touched) return;
905
+ const smaller: ModelToolRound = { ...message, answers };
906
+ const owner = rawOwner.get(message);
907
+ if (owner) rawOwner.set(smaller, owner);
908
+ messages[index] = smaller;
909
+ });
910
+ }
911
+ // Rounds of earlier questions are stored as the model last had them: a pointer may have lost its result there.
912
+ unpoint();
913
+
914
+ /** Calls answered in this question, refused ones included: none means that no tool ran. */
915
+ let callsAnswered = 0;
916
+ let recoveries = carried?.recoveries ?? 0;
917
+ let nudges = carried?.nudges ?? 0;
918
+ /**
919
+ * After the provider refused `sent` as larger than the model takes: the meter learns what the
920
+ * provider counted, the window it named, and old tool results are shortened until the request
921
+ * fits by the meter's new count. True when anything was shortened, so that sending it again can
922
+ * work. A model whose conversation may only grow (Claude) has nothing shortened.
923
+ */
924
+ const makeRoom = (adapter: ModelAdapter, sent: ModelRequest, error: unknown): boolean => {
925
+ const refused = error as { limitTokens?: number; requestedTokens?: number };
926
+ const own = scaleOf(adapter);
927
+ meter.overflowed(meter.estimate(sent.messages).tokens, refused.requestedTokens !== undefined ? refused.requestedTokens / own : undefined);
928
+ if (refused.limitTokens !== undefined) {
929
+ tokenLimit = Math.min(tokenLimit, Math.floor(refused.limitTokens / own) - replyTokens - Math.floor(reservedTokens / 2));
543
930
  }
544
- if (limits.requests !== undefined) {
545
- // The parts, a merge of their notes, the answer of the read, and the answer of the question.
546
- const cost = estimateParts(meta, budget) + 3;
547
- const left = limits.requests - usage.totals.requests;
548
- if (cost > left) return `Not run: reading all of ${meta.name} takes about ${count(cost)} model requests, and ${count(left)} are left of the ${count(limits.requests)} this question may make. Use search_document and read_document.`;
931
+ if (!canShrink) return false;
932
+ let changed = false;
933
+ for (const keep of [...ROUNDS_KEPT, 0]) {
934
+ if (changed && meter.current(messages).tokens <= tokenLimit) break;
935
+ if (shrink(keep)) changed = true;
549
936
  }
550
- return undefined;
937
+ return changed;
551
938
  };
552
-
553
- let answered = false;
554
- let outOfRoom = false;
555
- // Tools run in at most maxTurns - 1 requests. The last request is the one below that must be
556
- // answered in text, so a model that never stops calling tools does not cost a request whose
557
- // calls are thrown away.
558
- for (let round = 1; round < maxTurns && !outOfRoom && !spent(); round++) {
559
- const reply = await request(toolModel, { system: toolSystem, messages: viewFor(toolModel), tools: declarations, toolChoice: "auto" }, !explorer);
560
- if (reply.calls.length === 0) {
561
- // Text from this turn is the answer. A remark made earlier, before a tool call, is not.
562
- // Neither is anything an explorer model writes: the answer is asked for below.
563
- answered = wrote(reply) && !explorer;
564
- break;
565
- }
566
- const pending: ModelToolRound = { role: "tools", calls: reply.calls, answers: [], ...(reply.raw !== undefined ? { raw: reply.raw } : {}) };
567
- if (reply.raw !== undefined) rawOwner.set(pending, toolModel);
568
- // Every call must be answered, but not every call is run: a turn of sixty reads would build
569
- // a request that no model accepts, and a file can ask a model for exactly that.
570
- const run = reply.calls.slice(0, maxCalls);
571
- const most = (call: ToolCall) => tools.resultCharacters(call.name);
572
- const needed = run.reduce((sum, call) => sum + (call.name === TOOL_NAMES.view ? 0 : most(call)), 0);
573
- let left = room(pending);
574
- let dropped = false;
575
- for (const keep of canShrink ? ROUNDS_KEPT : []) {
576
- if (left >= needed) break;
577
- if (shrink(keep)) {
578
- dropped = true;
579
- left = room(pending);
939
+ /**
940
+ * The window to plan the documents for again, in the models' tokens, after the first request was
941
+ * refused as too large: the one the provider named, made smaller by how much more than the
942
+ * estimate it counted. Without its numbers, seven tenths of the window the budget assumed.
943
+ */
944
+ const smallerWindow = (adapter: ModelAdapter, sent: ModelRequest, error: unknown): { contextTokens: number; step: string } => {
945
+ const refused = error as { limitTokens?: number; requestedTokens?: number };
946
+ const estimated = meter.estimate(sent.messages).tokens;
947
+ const ratio = refused.requestedTokens !== undefined && estimated > 0 ? refused.requestedTokens / scaleOf(adapter) / estimated : undefined;
948
+ const limit = refused.limitTokens;
949
+ let contextTokens = Math.floor((limit ?? modelWindow * 0.7) / Math.max(1, ratio ?? (limit !== undefined ? 1.25 : 1)));
950
+ if (contextTokens >= modelWindow) contextTokens = Math.floor(modelWindow * 0.7);
951
+ // The limit may be the tokens a minute of the provider allows (OpenAI's TPM), not the window.
952
+ const period = rateAllowanceOf(error);
953
+ return {
954
+ contextTokens,
955
+ step: limit !== undefined
956
+ ? period
957
+ ? `The first request was larger than the ${count(limit)} tokens a ${period} that the provider allows: the files were planned again to fit it`
958
+ : `The first request was larger than the model's window of ${count(limit)} tokens: the files were planned again to fit it`
959
+ : period
960
+ ? `The first request was larger than the provider allows in a ${period}: the files were planned again for a smaller request`
961
+ : "The first request was larger than the model takes: the files were planned again for a smaller window",
962
+ };
963
+ };
964
+ /**
965
+ * `request`, for a request the provider may refuse as larger than the model takes. Then room is
966
+ * made, and it is sent once more, at most twice in a question. When nothing can be made smaller
967
+ * and nothing has happened yet in this question, the documents are planned again for a smaller
968
+ * window (`Replan`). `build` makes the request from the conversation as it is then.
969
+ */
970
+ const send = async (adapter: ModelAdapter, build: () => ModelRequest, shown: boolean, kind: RequestKind): Promise<ModelReply> => {
971
+ for (let again = false; ; again = true) {
972
+ const body = build();
973
+ try {
974
+ return await request(adapter, body, shown, kind);
975
+ } catch (error) {
976
+ if (errorKindOf(error) !== "context_overflow" || signal?.aborted) throw error;
977
+ if (!again && recoveries < MOST_OVERFLOW_RECOVERIES && makeRoom(adapter, body, error)) {
978
+ recoveries++;
979
+ const period = rateAllowanceOf(error);
980
+ step(period
981
+ ? `The request was larger than the provider allows in a ${period}: older tool results were shortened, and it was sent again`
982
+ : "The request was larger than the model takes: older tool results were shortened, and it was sent again", "room_made");
983
+ continue;
984
+ }
985
+ if (carried === undefined && callsAnswered === 0 && !text) {
986
+ const smaller = smallerWindow(adapter, body, error);
987
+ throw new Replan({ usage, steps: [...steps], turns, answered: answeredRequests, nudges, recoveries, contextTokens: smaller.contextTokens, step: smaller.step }, error, result(false));
988
+ }
989
+ throw error;
580
990
  }
581
991
  }
582
- if (dropped) step("Older tool results were shortened to make room in the request");
583
-
584
- type Planned = { call: ToolCall; label: string; refusal?: string; limits?: ToolCallLimits };
585
- const planned = run.map((call): Planned => {
586
- const label = tools.has(call.name) ? tools.describe(call.name, call.args) : call.name;
587
- // A call that did not arrive whole is not run: the model is told, and can send it again.
588
- if (call.problem) return { call, label, refusal: call.problem };
589
- // A look at pages returns a file and a few words: the file has its own room, worked out when it runs.
590
- if (call.name === TOOL_NAMES.view) return { call, label };
591
- const refusal = tooCostly(call);
592
- if (refusal) return { call, label, refusal };
593
- const cap = most(call);
594
- if (left < Math.min(cap, LEAST_ROOM_CHARACTERS)) {
595
- outOfRoom = true;
596
- return { call, label, refusal: NO_ROOM };
597
- }
598
- const allowed = Math.min(cap, left);
599
- left -= allowed;
600
- return { call, label, ...(allowed < cap ? { limits: { maxResultCharacters: allowed } } : {}) };
992
+ };
993
+ /** The conversation with a note at its end: in the last user turn, or in one of its own after a tool round. */
994
+ const withNote = (list: ModelMessage[], note: string): ModelMessage[] => {
995
+ const last = list.at(-1);
996
+ if (last && !isRound(last) && last.role === "user") return [...list.slice(0, -1), { role: "user", parts: [...last.parts, { text: note }] }];
997
+ return [...list, { role: "user", parts: [{ text: note }] }];
998
+ };
999
+ /**
1000
+ * The tool request with a note at its end. The note is not kept in the conversation, so that the
1001
+ * start of the later requests is the one the provider's cache holds. A model that explores whose
1002
+ * conversation may only grow (Claude ties its thinking to the turns it was written after) keeps
1003
+ * it: what it thinks next follows the note. The answering model, when it is another, never gets it.
1004
+ */
1005
+ const notedMessages = (note: string): (() => ModelMessage[]) => {
1006
+ if (!toolModel.capabilities.appendOnly) return () => withNote(viewFor(toolModel), note);
1007
+ const last = messages.at(-1);
1008
+ if (last && !isRound(last) && last.role === "user") {
1009
+ const noted: ModelMessage = { role: "user", parts: [...last.parts, { text: note }] };
1010
+ notes.set(noted, notes.has(last) ? notes.get(last) : last);
1011
+ messages[messages.length - 1] = noted;
1012
+ } else {
1013
+ const noted: ModelMessage = { role: "user", parts: [{ text: note }] };
1014
+ notes.set(noted, undefined);
1015
+ messages.push(noted);
1016
+ }
1017
+ return () => viewFor(toolModel);
1018
+ };
1019
+
1020
+ // The tool calls run with a signal of their own. The question's aborts it, and so does a turn
1021
+ // that fails (a listener that threw): the calls still waiting for a slot, or running, stop. A
1022
+ // failed turn ends the question, so one signal serves every turn, with the tool set that counts
1023
+ // the whole-file reads of the question.
1024
+ const halt = new AbortController();
1025
+ const stopTools = () => halt.abort(signal?.reason);
1026
+ if (signal?.aborted) halt.abort(signal.reason);
1027
+ else signal?.addEventListener("abort", stopTools, { once: true });
1028
+
1029
+ try {
1030
+ // Tools are needed for a file that is too large to send whole, and for a PDF whose pages can be
1031
+ // looked at: that one may have its whole text in the prompt and still hide a chart from the model.
1032
+ const { searchable } = prepared.plan;
1033
+ const { viewable } = prepared;
1034
+ if (searchable.length === 0 && viewable.length === 0) return result(wrote(await send(model, () => ({ system, messages }), true, { role: "answer", purpose: "direct" })));
1035
+
1036
+ // Reading a whole file in parts is exploring too: the explorer model's work, when there is one.
1037
+ const partReader = options.wholeDocumentAnalysis === false ? undefined : toolModel.generateText;
1038
+ const generate: GenerateText | undefined = partReader && (async (part) => {
1039
+ let reported = false;
1040
+ const text = await partReader({
1041
+ ...part,
1042
+ onUsage: (used) => {
1043
+ reported = true;
1044
+ usage.add(toolModel.id, used);
1045
+ part.onUsage?.(used);
1046
+ },
1047
+ });
1048
+ // A part reader that does not report its usage (`onUsage` is optional) still made a request,
1049
+ // and `limits.requests` counts it.
1050
+ if (!reported) usage.add(toolModel.id, undefined);
1051
+ return text;
601
1052
  });
1053
+ const tools = files.tools(searchable, {
1054
+ ...(generate ? { generate } : {}),
1055
+ onProgress: (event) => options.onActivity?.(`${event.message}…`),
1056
+ signal: halt.signal,
1057
+ ...(viewable.length > 0 ? { viewPages: viewable } : {}),
1058
+ maxWholeDocumentReads: limits.wholeDocumentReads ?? MAX_WHOLE_DOCUMENT_READS,
1059
+ ...(options.retry ? { retry: options.retry } : {}),
1060
+ budget,
1061
+ });
1062
+ const declarations = tools.declarations;
1063
+ // The requests that use the tools are the chat's own, or an explorer model's: the same
1064
+ // conversation, and a line that says what its part is.
1065
+ const toolSystem = explorer ? `${system}\n\n${EXPLORER_INSTRUCTION}` : system;
1066
+ const sentTools = JSON.stringify(declarations);
1067
+ meter.fixed.tokens += estimateTokens(sentTools) + (explorer ? estimateTokens(EXPLORER_INSTRUCTION) : 0);
1068
+ meter.fixed.bytes += Buffer.byteLength(sentTools) + (explorer ? EXPLORER_INSTRUCTION.length : 0);
1069
+ if (searchable.length > 0) activity("searching_instead", `Too large to read at once: ${searchable.map((meta) => meta.name).join(", ")}. Searching instead…`);
1070
+
1071
+ const maxTurns = Math.max(1, Math.trunc(limits.toolTurns ?? DEFAULT_TOOL_TURNS));
1072
+ const maxCalls = Math.max(1, Math.trunc(limits.callsPerTurn ?? DEFAULT_CALLS_PER_TURN));
1073
+ /** True once the question has used what it may: no more tools run. One request is kept for the answer. */
1074
+ const spent = (): boolean => (
1075
+ (limits.inputTokens !== undefined && usage.totals.inputTokens >= limits.inputTokens)
1076
+ || (limits.requests !== undefined && usage.totals.requests >= limits.requests - 1)
1077
+ );
1078
+ /**
1079
+ * A whole-file read is many requests at once: one that would pass a ceiling of the question is
1080
+ * not started. `reserved` is what the reads already let through in this turn will take: they run
1081
+ * together, and the totals do not show them yet.
1082
+ */
1083
+ const tooCostly = (call: ToolCall, reserved: { inputTokens: number; requests: number; reads: Map<string, number> }): { refusal?: string; own?: number } => {
1084
+ if (call.name !== TOOL_NAMES.analyze) return {};
1085
+ const meta = searchable.find((document) => document.id === call.args.document_id);
1086
+ if (!meta) return {};
1087
+ // A read of a document read whole as often as it may be is refused by the tool, at no cost: it
1088
+ // takes nothing from the reads of other documents.
1089
+ const before = evidence.filter((shown) => shown.whole && shown.documentId === meta.id).length + (reserved.reads.get(meta.id) ?? 0);
1090
+ if (before >= (limits.wholeDocumentReads ?? MAX_WHOLE_DOCUMENT_READS)) return {};
1091
+ // The parts are read by the model that explores, in its own tokens.
1092
+ const tokens = Math.ceil(meta.estimatedTokens * scaleOf(toolModel));
1093
+ // The parts, a merge of their notes, the answer of the read, and the answer of the question.
1094
+ const requests = estimateParts(meta, budget) + 3;
1095
+ if (limits.inputTokens !== undefined) {
1096
+ const left = Math.max(0, limits.inputTokens - usage.totals.inputTokens - reserved.inputTokens);
1097
+ if (tokens > left) return { refusal: `Not run: reading all of ${meta.name} takes about ${count(tokens)} input tokens, and ${count(left)} are left of the ${count(limits.inputTokens)} this question may use. Use search_document and read_document.` };
1098
+ }
1099
+ if (limits.requests !== undefined) {
1100
+ const left = Math.max(0, limits.requests - usage.totals.requests - reserved.requests);
1101
+ if (requests > left) return { refusal: `Not run: reading all of ${meta.name} takes about ${count(requests)} model requests, and ${count(left)} are left of the ${count(limits.requests)} this question may make. Use search_document and read_document.` };
1102
+ }
1103
+ reserved.inputTokens += tokens;
1104
+ // The answer of the question is one request, whatever number of reads come before it.
1105
+ reserved.requests += requests - 1;
1106
+ reserved.reads.set(meta.id, (reserved.reads.get(meta.id) ?? 0) + 1);
1107
+ // The read's own requests: its parts, a merge of their notes, and its answer.
1108
+ return { own: requests - 1 };
1109
+ };
1110
+ /**
1111
+ * A pointer for a call whose result is already in the conversation, in full: an earlier result
1112
+ * (of this question or of one before it) holds what this one would return. The files do not
1113
+ * change, so running it again would only take room.
1114
+ */
1115
+ const shownBefore = (call: ToolCall): ToolResult | undefined => {
1116
+ if (!canPoint) return undefined;
1117
+ for (let at = messages.length - 1; at >= 0; at--) {
1118
+ const message = messages[at]!;
1119
+ if (!isRound(message)) continue;
1120
+ // The rounds before `asked` are those of earlier questions, which an older version may have written.
1121
+ for (const answer of message.answers) {
1122
+ const pointer = alreadyShown(call, answer, at < asked);
1123
+ if (pointer) return pointer;
1124
+ }
1125
+ }
1126
+ return undefined;
1127
+ };
1128
+ /** The tool and mode of the calls that failed last, and how many failed in a row. */
1129
+ let failing: { kind: string; count: number } | undefined;
1130
+
1131
+ let answered = false;
1132
+ let outOfRoom = false;
1133
+ // Tools run in at most maxTurns - 1 requests. The last request is the one below that must be
1134
+ // answered in text, so a model that never stops calling tools does not cost a request whose
1135
+ // calls are thrown away.
1136
+ const toolRole: RequestRole = explorer ? "explorer" : "tools";
1137
+ /** A call as one line of plain text. An unknown tool's name is quoted and cut: no step starts with what the model chose, at any length. */
1138
+ const labelOf = (call: ToolCall): string => stepLine(tools.has(call.name) ? tools.describe(call.name, call.args) : `Call ${unknownToolName(call.name)}`);
1139
+ for (let round = 1 + (carried?.answered ?? 0); round < maxTurns && !outOfRoom; round++) {
1140
+ if (spent()) {
1141
+ budgetReached();
1142
+ break;
1143
+ }
1144
+ const toolRequest = (): ModelRequest => ({ system: toolSystem, messages: viewFor(toolModel), tools: declarations, toolChoice: "auto" });
1145
+ let reply = await send(toolModel, () => toolRequest(), !explorer, { role: toolRole, purpose: "turn" });
1146
+ // A turn whose tool call could not be read, or a first reply with nothing in it, is asked
1147
+ // for once more, with a note that says what was wrong: the answer would otherwise be written
1148
+ // from the cards alone, and look like any other. The note is not kept in the conversation.
1149
+ // It is a request of the chat like any other: it takes a tool turn, and the last turn is still the answer's.
1150
+ if (reply.calls.length === 0 && nudges < MOST_NUDGES && round + 1 < maxTurns && !reply.blockReason && !spent()) {
1151
+ const malformed = reply.finish === "malformed_call";
1152
+ const empty = !reply.text.trim() && callsAnswered === 0 && reply.finish !== "cut" && reply.finish !== "filtered";
1153
+ if (malformed || empty) {
1154
+ nudges++;
1155
+ round++;
1156
+ step(malformed ? "The model's tool call could not be read: it was asked to send it again" : "The model's first reply was empty: it was asked again", "nudged");
1157
+ const note = malformed ? (explorer ? MALFORMED_EXPLORER_NUDGE : MALFORMED_CALL_NUDGE) : explorer ? EMPTY_EXPLORER_NUDGE : EMPTY_REPLY_NUDGE;
1158
+ const withIt = notedMessages(note);
1159
+ reply = await send(toolModel, () => ({ system: toolSystem, messages: withIt(), tools: declarations, toolChoice: "auto" }), !explorer, { role: toolRole, purpose: "nudge" });
1160
+ }
1161
+ }
1162
+ if (reply.calls.length === 0) {
1163
+ // Text from this turn is the answer. A remark made earlier, before a tool call, is not.
1164
+ // Neither is anything an explorer model writes: the answer is asked for below.
1165
+ answered = wrote(reply) && !explorer;
1166
+ break;
1167
+ }
1168
+ const pending: ModelToolRound = { role: "tools", calls: reply.calls, answers: [], ...(reply.raw !== undefined ? { raw: reply.raw } : {}) };
1169
+ if (reply.raw !== undefined) rawOwner.set(pending, toolModel);
1170
+ // Every call must be answered, but not every call is run: a turn of sixty reads would build
1171
+ // a request that no model accepts, and a file can ask a model for exactly that.
1172
+ const run = reply.calls.slice(0, maxCalls);
1173
+ const most = (call: ToolCall) => tools.resultCharacters(call.name);
602
1174
 
603
- // The calls of a turn run together, a few at a time. Looks at pages take their turns, one
604
- // after another: each is given the room the ones before it left.
605
- const together = new Limiter(CALLS_AT_ONCE);
606
- let looks: Promise<unknown> = Promise.resolve();
607
- // The size of the request as it stands, worked out when the first look at pages in this turn needs it.
608
- let requestBytes: number | undefined;
609
- const outputs = planned.map(({ call, label, refusal, limits: callLimits }): Promise<ToolOutput> => {
610
- if (refusal) return Promise.resolve({ result: { error: refusal }, files: [] });
611
- if (call.name === TOOL_NAMES.view) {
612
- const look = looks.then(async () => {
613
- signal?.throwIfAborted();
614
- options.onActivity?.(`${label}…`);
615
- if (requestBytes === undefined) {
616
- const waiting: ModelRequest = { system: toolSystem, messages: [...viewFor(toolModel), pending], tools: declarations, toolChoice: "auto" };
617
- requestBytes = toolModel.requestBytes?.(waiting) ?? meter.estimate(waiting.messages).bytes;
1175
+ /**
1176
+ * `late`: a whole-file read, whose answer is fitted to the room once the other results of the
1177
+ * turn are in. `pointer`: the result of a call whose result is already in the conversation;
1178
+ * `earlier` when that is the result of an earlier turn, which room may still be made from.
1179
+ */
1180
+ type Planned = { call: ToolCall; label: string; refusal?: string; pointer?: ToolResult; earlier?: boolean; twinOf?: number; own?: number; limits?: ToolCallLimits; late?: boolean };
1181
+ const reserved = { inputTokens: 0, requests: 0, reads: new Map<string, number>() };
1182
+ /** The first call of this turn with each key: the same call made again in the turn is not run twice. */
1183
+ const seen = new Map<string, number>();
1184
+ const planned = run.map((call, index): Planned => {
1185
+ const label = labelOf(call);
1186
+ // A call that did not arrive whole is not run: the model is told, and can send it again.
1187
+ if (call.problem) return { call, label, refusal: call.problem };
1188
+ // A look at pages returns a file and a few words: the file has its own room, worked out when it runs.
1189
+ if (call.name === TOOL_NAMES.view) return { call, label };
1190
+ const key = toolCallKey(call.name, call.args);
1191
+ if (key !== undefined && canPoint) {
1192
+ const twin = seen.get(key);
1193
+ if (twin !== undefined) return { call, label, twinOf: twin, pointer: { already_shown: true, note: `Not run: call ${twin + 1} of this turn is the same call, and its result is next to this one. Use it.` } };
1194
+ seen.set(key, index);
1195
+ }
1196
+ const pointer = shownBefore(call);
1197
+ if (pointer) return { call, label, pointer, earlier: true };
1198
+ const cost = tooCostly(call, reserved);
1199
+ if (cost.refusal) return { call, label, refusal: cost.refusal };
1200
+ return { call, label, ...(cost.own !== undefined ? { own: cost.own } : {}) };
1201
+ });
1202
+ // The requests each whole-file read of the turn may make, once all of them are reserved: its
1203
+ // own, and an even share of what the question has left over them (a part read as two halves
1204
+ // takes one more). Together they never pass limits.requests.
1205
+ const reads = planned.filter((plan) => plan.own !== undefined);
1206
+ if (limits.requests !== undefined && reads.length > 0) {
1207
+ const slack = Math.max(0, limits.requests - usage.totals.requests - 1 - reserved.requests);
1208
+ for (const plan of reads) plan.limits = { ...plan.limits, maxRequests: plan.own! + Math.floor(slack / reads.length) };
1209
+ }
1210
+ // The calls that return text, and the most they may return: a call that is refused, or
1211
+ // answered with a pointer to what is already shown, needs no room.
1212
+ const sized = planned.filter((plan) => !plan.refusal && !plan.pointer && plan.call.name !== TOOL_NAMES.view);
1213
+ const needed = sized.reduce((sum, plan) => sum + most(plan.call), 0);
1214
+ let left = room(pending);
1215
+ let dropped = false;
1216
+ for (const keep of canShrink ? ROUNDS_KEPT : []) {
1217
+ if (left >= needed) break;
1218
+ if (shrink(keep)) {
1219
+ dropped = true;
1220
+ left = room(pending);
1221
+ }
1222
+ }
1223
+ if (dropped) {
1224
+ step("Older tool results were shortened to make room in the request", "results_shortened");
1225
+ // A result that was shortened is no longer shown in full: a call that pointed to it is run after all.
1226
+ for (const plan of planned) {
1227
+ if (!plan.earlier) continue;
1228
+ const pointer = shownBefore(plan.call);
1229
+ if (pointer) {
1230
+ plan.pointer = pointer;
1231
+ } else {
1232
+ delete plan.pointer;
1233
+ delete plan.earlier;
618
1234
  }
619
- // Base64 turns three bytes into four characters.
620
- const output = await tools.executeWithFiles(call.name, call.args, { maxFileBytes: Math.floor((maxRequestBytes - bytesKeptFree - requestBytes) * 3 / 4), maxPages: pagesLeft });
621
- for (const file of output.files) requestBytes += Math.ceil(file.bytes.length / 3) * 4 + 512;
622
- if (output.files.length > 0) pagesLeft -= pagesShown(output.result);
623
- return output;
624
- });
625
- looks = look.catch(() => undefined);
626
- return look;
1235
+ }
627
1236
  }
628
- return together.acquire(signal).then(async (release) => {
1237
+ const runsNow = planned.filter((plan) => !plan.refusal && !plan.pointer && plan.call.name !== TOOL_NAMES.view);
1238
+
1239
+ // The room is shared by those calls. A result is most often far smaller than its cap, so a call
1240
+ // that was given its whole cap first could leave none for the next ones, and a turn of small
1241
+ // searches ended the question.
1242
+ const shares = shareRoom(runsNow.map((plan) => most(plan.call)), left);
1243
+ runsNow.forEach((plan, index) => {
1244
+ const share = shares[index];
1245
+ const cap = most(plan.call);
1246
+ if (share === undefined) {
1247
+ if (!outOfRoom) notice("no_room", "There is no room left in this conversation for another tool result.");
1248
+ outOfRoom = true;
1249
+ plan.refusal = NO_ROOM;
1250
+ } else if (plan.call.name === TOOL_NAMES.analyze) {
1251
+ // The answer of a whole-file read cannot be asked for again. It is not cut to an even share
1252
+ // up front: it gets all the room the other results of the turn leave, once they are in.
1253
+ plan.late = true;
1254
+ } else if (share < cap) {
1255
+ plan.limits = { ...plan.limits, maxResultCharacters: share };
1256
+ }
1257
+ });
1258
+ // A call made twice in the turn whose first was refused (no room, or not whole) is refused the
1259
+ // same way: there is no result next to it to use.
1260
+ for (const plan of planned) {
1261
+ const source = plan.twinOf === undefined ? undefined : planned[plan.twinOf];
1262
+ if (source?.refusal) {
1263
+ plan.refusal = source.refusal;
1264
+ delete plan.pointer;
1265
+ }
1266
+ }
1267
+
1268
+ // Each call of the turn, those over `maxCalls` too, has an id for its events, in call order.
1269
+ const callIds = reply.calls.map(() => `call_${++state.calls}`);
1270
+ /**
1271
+ * The calls of this turn whose `tool.start` went out and whose `tool.end` has not, by index:
1272
+ * when each started, and how to end the requests of a whole-file read still under way.
1273
+ */
1274
+ const openCalls = new Map<number, { began: number; requests: Set<(error: unknown) => void> }>();
1275
+ /** True once the turn failed (the question was stopped): nothing more of it is reported. */
1276
+ let turnFailed = false;
1277
+ /**
1278
+ * The first throw of a listener told of a whole-file read while it runs (`onEvent`,
1279
+ * `onActivity`). It must reach the caller, not become the read's own failure: the calls of the
1280
+ * question stop, and the turn ends with it.
1281
+ */
1282
+ let listenerError: { error: unknown } | undefined;
1283
+ const tell = (told: () => void) => {
629
1284
  try {
630
- options.onActivity?.(`${label}…`);
631
- return await tools.executeWithFiles(call.name, call.args, callLimits);
632
- } finally {
633
- release();
1285
+ told();
1286
+ } catch (error) {
1287
+ if (listenerError) return;
1288
+ listenerError = { error };
1289
+ halt.abort(error);
1290
+ }
1291
+ };
1292
+ const startTool = (index: number, call: ToolCall, label: string) => {
1293
+ if (turnFailed) return;
1294
+ openCalls.set(index, { began: Date.now(), requests: new Set() });
1295
+ if (!events.active) return;
1296
+ events.emit({
1297
+ type: "tool.start",
1298
+ callId: callIds[index]!,
1299
+ ...(call.id !== undefined ? { providerCallId: call.id } : {}),
1300
+ tool: call.name,
1301
+ args: call.args,
1302
+ label,
1303
+ ...(typeof call.args?.document_id === "string" ? { documentId: call.args.document_id } : {}),
1304
+ round,
1305
+ });
1306
+ };
1307
+ /** `sent`: the result as the model gets it. `line`: the step, as `onStep` got it. */
1308
+ const endTool = (index: number, outcome: ToolOutcome, sent: ToolResult, line?: string, shown?: Evidence) => {
1309
+ const open = openCalls.get(index);
1310
+ openCalls.delete(index);
1311
+ // A request of a whole-file read that its read left behind ends before its call does.
1312
+ for (const end of [...open?.requests ?? []]) end(new Error(CALL_ENDED));
1313
+ if (!events.active || turnFailed) return;
1314
+ events.emit({
1315
+ type: "tool.end",
1316
+ callId: callIds[index]!,
1317
+ outcome,
1318
+ ms: open ? Date.now() - open.began : 0,
1319
+ ...(line !== undefined ? { step: line } : {}),
1320
+ ...(shown ? { evidence: { ...shown, callId: callIds[index]! } } : {}),
1321
+ resultCharacters: JSON.stringify(sent).length,
1322
+ ...(typeof sent.error === "string" ? { error: sent.error } : {}),
1323
+ ...(options.eventResults === true ? { result: sent } : {}),
1324
+ });
1325
+ };
1326
+ /** Ends every call of the turn still open, and its requests, in call order, when the turn failed. */
1327
+ const failTurn = (error: unknown) => {
1328
+ const open = [...openCalls].sort(([first], [second]) => first - second);
1329
+ openCalls.clear();
1330
+ turnFailed = true;
1331
+ const why = events.active ? eventErrorOf(error).message : "";
1332
+ for (const [index, call] of open) {
1333
+ for (const end of [...call.requests]) end(error);
1334
+ if (!events.active) continue;
1335
+ events.emit({ type: "tool.end", callId: callIds[index]!, outcome: "error", ms: Date.now() - call.began, error: why, resultCharacters: 0 });
634
1336
  }
1337
+ };
1338
+ /** A model request of a whole-file read, for its events. */
1339
+ const readerRequest = (index: number, start: ToolRequestStart): ToolRequestHandle => {
1340
+ const open = openCalls.get(index);
1341
+ // The call was ended already (the question was stopped): nothing more of it is reported.
1342
+ if (!open) return { retry: () => undefined, end: () => undefined };
1343
+ const requestId = `req_${++state.requests}`;
1344
+ const began = Date.now();
1345
+ let ended = false;
1346
+ const end = (last: ToolRequestEnd) => {
1347
+ if (ended) return;
1348
+ ended = true;
1349
+ open.requests.delete(abandon);
1350
+ tell(() => events.emit({
1351
+ type: "request.end",
1352
+ requestId,
1353
+ ms: Date.now() - began,
1354
+ outcome: last.outcome,
1355
+ ...(last.usage ? { usage: last.usage } : {}),
1356
+ ...(last.error !== undefined ? { error: eventErrorOf(last.error) } : {}),
1357
+ }));
1358
+ };
1359
+ const abandon = (error: unknown) => end({ outcome: "error", error });
1360
+ // Before its start goes out: a listener that throws on the start still gets the end.
1361
+ open.requests.add(abandon);
1362
+ tell(() => events.emit({ type: "request.start", requestId, role: "reader", purpose: start.purpose, model: toolModel.id, callId: callIds[index]!, detail: start.detail }));
1363
+ return {
1364
+ retry: (retried) => {
1365
+ if (!ended && events.active) tell(() => events.emit({ type: "retry", requestId, attempt: retried.attempt, delayMs: retried.delayMs, error: eventErrorOf(retried.error), message: retryMessage(retried) }));
1366
+ },
1367
+ end,
1368
+ };
1369
+ };
1370
+ /**
1371
+ * The listeners of one call: its progress goes to `onActivity` as before (in place of the
1372
+ * tool set's shared listener) and is told apart by call in the events, with its requests.
1373
+ */
1374
+ const hooksFor = (index: number): ToolCallHooks => ({
1375
+ onProgress: (event) => tell(() => {
1376
+ options.onActivity?.(`${event.message}…`);
1377
+ if (openCalls.has(index)) events.emit({ type: "tool.progress", callId: callIds[index]!, stage: event.kind, done: event.done, total: event.total, message: event.message });
1378
+ }),
1379
+ ...(events.active ? { onRequest: (start: ToolRequestStart) => readerRequest(index, start) } : {}),
635
1380
  });
636
- });
637
- // One that fails (the question was stopped) is reported below, in call order; the others must not go unheard.
638
- for (const output of outputs) output.catch(() => undefined);
639
-
640
- const turnsLeft = outOfRoom ? 0 : maxTurns - round - 1;
641
- const answers: ToolAnswer[] = [];
642
- for (const [index, { call, label }] of planned.entries()) {
643
- const output = await outputs[index]!;
644
- step(`${label}${toolResultSummary(label, output.result)}`);
645
- const shown = evidenceOf(call, output.result);
646
- if (shown) evidence.push(shown);
647
- answers.push({ call, result: { ...output.result, tool_turns_left: turnsLeft }, files: output.files });
648
- }
649
- for (const call of reply.calls.slice(maxCalls)) {
650
- answers.push({ call, result: { error: `Not run: one turn runs at most ${maxCalls} tool calls. Send this call again if you still need it.`, tool_turns_left: turnsLeft }, files: [] });
1381
+
1382
+ // The calls of a turn run together, a few at a time. Looks at pages take their turns, one
1383
+ // after another: each is given the room the ones before it left.
1384
+ const together = new Limiter(CALLS_AT_ONCE);
1385
+ let looks: Promise<unknown> = Promise.resolve();
1386
+ // The size of the request as it stands, worked out when the first look at pages in this turn needs it.
1387
+ let requestBytes: number | undefined;
1388
+ const runCall = ({ call, label, refusal, pointer, limits: callLimits }: Planned, index: number): Promise<ToolOutput> => {
1389
+ if (refusal || pointer) startTool(index, call, label);
1390
+ if (refusal) return Promise.resolve({ result: { error: refusal }, files: [] });
1391
+ if (pointer) return Promise.resolve({ result: pointer, files: [] });
1392
+ if (call.name === TOOL_NAMES.view) {
1393
+ const look = looks.then(async () => {
1394
+ halt.signal.throwIfAborted();
1395
+ options.onActivity?.(`${label}…`);
1396
+ startTool(index, call, label);
1397
+ if (requestBytes === undefined) {
1398
+ const waiting: ModelRequest = { system: toolSystem, messages: [...viewFor(toolModel), pending], tools: declarations, toolChoice: "auto" };
1399
+ requestBytes = toolModel.requestBytes?.(waiting) ?? meter.estimate(waiting.messages).bytes;
1400
+ }
1401
+ // Base64 turns three bytes into four characters.
1402
+ const output = await tools.executeWithFiles(call.name, call.args, { maxFileBytes: Math.floor((maxRequestBytes - bytesKeptFree - requestBytes) * 3 / 4), maxPages: pagesLeft });
1403
+ for (const file of output.files) requestBytes += Math.ceil(file.bytes.length / 3) * 4 + 512;
1404
+ if (output.files.length > 0) pagesLeft -= pagesShown(output.result);
1405
+ return output;
1406
+ });
1407
+ looks = look.catch(() => undefined);
1408
+ return look;
1409
+ }
1410
+ return together.acquire(halt.signal).then(async (release) => {
1411
+ try {
1412
+ // The turn may have failed while this call waited for its slot.
1413
+ halt.signal.throwIfAborted();
1414
+ options.onActivity?.(`${label}…`);
1415
+ startTool(index, call, label);
1416
+ return await tools.executeWithFiles(call.name, call.args, callLimits, hooksFor(index));
1417
+ } finally {
1418
+ release();
1419
+ }
1420
+ });
1421
+ };
1422
+
1423
+ const turnsLeft = outOfRoom ? 0 : maxTurns - round - 1;
1424
+ const answers: ToolAnswer[] = [];
1425
+ try {
1426
+ const outputs: Array<Promise<ToolOutput>> = [];
1427
+ for (const [index, plan] of planned.entries()) {
1428
+ const output = runCall(plan, index);
1429
+ // One that fails (the question was stopped) is reported below, in call order; the others must not go unheard.
1430
+ output.catch(() => undefined);
1431
+ outputs.push(output);
1432
+ }
1433
+
1434
+ /**
1435
+ * The room of each whole-file read of the turn: what the other results left, shared among the
1436
+ * reads, the smaller answers first. Worked out when the first of them is reached, by which time
1437
+ * the other calls, which are quick, have most often returned.
1438
+ */
1439
+ let lateRoom: Map<number, number> | undefined;
1440
+ const roomOfReads = async (): Promise<Map<number, number>> => {
1441
+ const sizes = await Promise.all(outputs.map(async (output) => JSON.stringify((await output).result).length));
1442
+ const reads = planned.flatMap((plan, index) => (plan.late ? [index] : []));
1443
+ let free = left - sizes.reduce((sum, size, index) => sum + (planned[index]!.late ? 0 : size), 0);
1444
+ const shares = new Map<number, number>();
1445
+ [...reads].sort((first, second) => sizes[first]! - sizes[second]!).forEach((index, position) => {
1446
+ const share = Math.min(sizes[index]!, Math.floor(free / (reads.length - position)));
1447
+ shares.set(index, share);
1448
+ free -= share;
1449
+ });
1450
+ return shares;
1451
+ };
1452
+
1453
+ // The answers in call order. Each call's `tool.end` goes out here, in the same order.
1454
+ for (const [index, { call, label, late, refusal, pointer }] of planned.entries()) {
1455
+ let output = await outputs[index]!;
1456
+ if (listenerError) throw listenerError.error;
1457
+ callsAnswered++;
1458
+ if (late) {
1459
+ lateRoom ??= await roomOfReads();
1460
+ const share = lateRoom.get(index)!;
1461
+ if (JSON.stringify(output.result).length > share) output = { ...output, result: fitAnswer(output.result, Math.max(LEAST_RESULT_CHARACTERS, share)) };
1462
+ }
1463
+ if (pointer) {
1464
+ const line = step(`${label} — already shown above`);
1465
+ const sent = { ...output.result, tool_turns_left: turnsLeft };
1466
+ answers.push({ call, result: sent, files: [] });
1467
+ endTool(index, "already_shown", sent, line);
1468
+ continue;
1469
+ }
1470
+ // Two searches in a row that failed in the same mode: the second says to try another way.
1471
+ if (!refusal) {
1472
+ const kind = failureKind(call);
1473
+ if (kind === undefined) {
1474
+ failing = undefined;
1475
+ } else if (typeof output.result.error === "string") {
1476
+ failing = failing?.kind === kind ? { kind, count: failing.count + 1 } : { kind, count: 1 };
1477
+ if (failing.count >= 2) output = { ...output, result: { ...output.result, error: `${output.result.error} ${repeatedFailureHint(call)}` } };
1478
+ } else {
1479
+ failing = undefined;
1480
+ }
1481
+ }
1482
+ const line = step(`${label}${toolResultSummary(label, output.result)}`);
1483
+ const shown = evidenceOf(call, output.result);
1484
+ if (shown) evidence.push({ ...shown, callId: callIds[index]! });
1485
+ const sent = { ...output.result, tool_turns_left: turnsLeft };
1486
+ answers.push({ call, result: sent, files: output.files });
1487
+ const outcome: ToolOutcome = call.problem ? "error" : refusal ? "refused" : typeof output.result.error === "string" ? "error" : "ok";
1488
+ endTool(index, outcome, sent, line, shown);
1489
+ }
1490
+ // A listener of a read that went on after its call returned (its progress).
1491
+ if (listenerError) throw listenerError.error;
1492
+ } catch (error) {
1493
+ // The calls of the turn still waiting for a slot, or running, stop.
1494
+ halt.abort(error);
1495
+ failTurn(error);
1496
+ throw error;
1497
+ }
1498
+ for (const [offset, call] of reply.calls.slice(maxCalls).entries()) {
1499
+ callsAnswered++;
1500
+ const sent = { error: `Not run: one turn runs at most ${maxCalls} tool calls. Send this call again if you still need it.`, tool_turns_left: turnsLeft };
1501
+ answers.push({ call, result: sent, files: [] });
1502
+ if (events.active) {
1503
+ startTool(maxCalls + offset, call, labelOf(call));
1504
+ endTool(maxCalls + offset, "not_run", sent);
1505
+ }
1506
+ }
1507
+ const notRun = reply.calls.length - maxCalls;
1508
+ if (notRun > 0) step(`${notRun} more tool ${notRun === 1 ? "call in this turn was" : "calls in this turn were"} not run (at most ${maxCalls} a turn)`, "calls_not_run");
1509
+ const done: ModelToolRound = { ...pending, answers };
1510
+ if (reply.raw !== undefined) rawOwner.set(done, toolModel);
1511
+ messages.push(done);
651
1512
  }
652
- if (reply.calls.length > maxCalls) step(`${reply.calls.length - maxCalls} more tool calls in this turn were not run (at most ${maxCalls} a turn)`);
653
- const done: ModelToolRound = { ...pending, answers };
654
- if (reply.raw !== undefined) rawOwner.set(done, toolModel);
655
- messages.push(done);
656
- }
657
1513
 
658
- // Out of tool turns or of room, or the last turn had no text (cut off, or a malformed tool call):
659
- // ask once more, for an answer in text. A blocked prompt would only be blocked again.
660
- // With an explorer model this request is always made: it is the one the answering model gets.
661
- if (!answered && !blockReason) {
662
- options.onActivity?.("Writing the answer…");
663
- let closing = searchable.length > 0 ? FINAL_ANSWER_REQUEST : FINAL_ANSWER_AFTER_PAGES;
664
- // The answering model gets the explorer's calls and what they returned, and nothing else of it.
665
- if (explorer && steps.length === 0) closing = FINAL_ANSWER_WITHOUT_TOOLS;
666
- const reply = await request(model, {
667
- system,
668
- messages: [...viewFor(model), { role: "user", parts: [{ text: closing }] }],
669
- tools: declarations,
670
- toolChoice: "none",
671
- }, true);
672
- answered = wrote(reply);
1514
+ // Out of tool turns or of room, or the last turn had no text (cut off, or a malformed tool call):
1515
+ // ask once more, for an answer in text. A blocked prompt would only be blocked again.
1516
+ // With an explorer model this request is always made: it is the one the answering model gets.
1517
+ if (!answered && !blockReason) {
1518
+ activity("writing_answer", "Writing the answer…");
1519
+ let closing = searchable.length > 0 ? FINAL_ANSWER_REQUEST : FINAL_ANSWER_AFTER_PAGES;
1520
+ // No tool ran (the explorer needed none, the first reply was empty, or no turn was left for
1521
+ // tools): there is no tool result to answer from. The answering model gets the explorer's
1522
+ // calls and what they returned, and nothing else of it.
1523
+ if (callsAnswered === 0) closing = FINAL_ANSWER_WITHOUT_TOOLS;
1524
+ const answerRequest = (note?: string) => (): ModelRequest => ({
1525
+ system,
1526
+ messages: [...viewFor(model), { role: "user", parts: [{ text: closing }, ...(note ? [{ text: note }] : [])] }],
1527
+ tools: declarations,
1528
+ toolChoice: "none",
1529
+ });
1530
+ let reply = await send(model, answerRequest(), true, { role: "answer", purpose: "closing" });
1531
+ // A reply with no text (empty, or a tool call the model was told not to make, or one that
1532
+ // could not be read) is asked for once more, with a note that is not kept: otherwise the
1533
+ // question ends with nothing to show. Not after a refusal or a filter, which would come again,
1534
+ // nor a reply cut off at the output limit with nothing in it, nor once a ceiling of `limits`
1535
+ // is reached. It is one of the second tries of the question, and may be one request past
1536
+ // `limits.toolTurns`, which counts the answer's first request.
1537
+ const calledInstead = reply.calls.length > 0 || reply.finish === "malformed_call";
1538
+ const ceilingReached = (limits.inputTokens !== undefined && usage.totals.inputTokens >= limits.inputTokens)
1539
+ || (limits.requests !== undefined && usage.totals.requests >= limits.requests);
1540
+ if (!wrote(reply) && !reply.blockReason && reply.finish !== "filtered" && (calledInstead || reply.finish !== "cut") && nudges < MOST_NUDGES) {
1541
+ if (ceilingReached) {
1542
+ budgetReached();
1543
+ } else {
1544
+ nudges++;
1545
+ step(calledInstead ? "The model called a tool instead of answering: it was asked again for the answer" : "The model's answer was empty: it was asked again", "answer_again");
1546
+ reply = await send(model, answerRequest(ANSWER_AGAIN_NOTE), true, { role: "answer", purpose: "answer_again" });
1547
+ }
1548
+ }
1549
+ answered = wrote(reply);
1550
+ }
1551
+ return result(answered);
1552
+ } catch (error) {
1553
+ // What the question found and paid for until it failed, for the application to keep. The usage is
1554
+ // a copy: a part reader that went on after the question was stopped may still report its own.
1555
+ if (!(error instanceof Replan) && error !== null && typeof error === "object") partialResults.set(error, { ...result(false), usage: structuredClone(usage.totals) });
1556
+ throw error;
1557
+ } finally {
1558
+ signal?.removeEventListener("abort", stopTools);
673
1559
  }
674
- return result(answered);
675
1560
  }