llm-large-files 0.5.0 → 0.7.0

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