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