llm-large-files 0.8.2 → 0.10.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 (288) hide show
  1. package/CHANGELOG.md +981 -0
  2. package/README.md +22 -17
  3. package/dist/access.d.ts +128 -0
  4. package/dist/access.d.ts.map +1 -0
  5. package/dist/access.js +234 -0
  6. package/dist/access.js.map +1 -0
  7. package/dist/aggregate.d.ts +6 -0
  8. package/dist/aggregate.d.ts.map +1 -1
  9. package/dist/aggregate.js +86 -13
  10. package/dist/aggregate.js.map +1 -1
  11. package/dist/analyze.d.ts +4 -0
  12. package/dist/analyze.d.ts.map +1 -1
  13. package/dist/analyze.js +2 -2
  14. package/dist/analyze.js.map +1 -1
  15. package/dist/answer-info.d.ts +26 -0
  16. package/dist/answer-info.d.ts.map +1 -0
  17. package/dist/answer-info.js +32 -0
  18. package/dist/answer-info.js.map +1 -0
  19. package/dist/anthropic/adapter.d.ts +5 -1
  20. package/dist/anthropic/adapter.d.ts.map +1 -1
  21. package/dist/anthropic/adapter.js +35 -10
  22. package/dist/anthropic/adapter.js.map +1 -1
  23. package/dist/ask.d.ts +159 -14
  24. package/dist/ask.d.ts.map +1 -1
  25. package/dist/ask.js +743 -113
  26. package/dist/ask.js.map +1 -1
  27. package/dist/cache.d.ts +12 -3
  28. package/dist/cache.d.ts.map +1 -1
  29. package/dist/cache.js +18 -5
  30. package/dist/cache.js.map +1 -1
  31. package/dist/citations.d.ts +36 -0
  32. package/dist/citations.d.ts.map +1 -0
  33. package/dist/citations.js +291 -0
  34. package/dist/citations.js.map +1 -0
  35. package/dist/encoding.js +5 -3
  36. package/dist/encoding.js.map +1 -1
  37. package/dist/error-info.d.ts +70 -0
  38. package/dist/error-info.d.ts.map +1 -0
  39. package/dist/error-info.js +253 -0
  40. package/dist/error-info.js.map +1 -0
  41. package/dist/errors.d.ts +74 -8
  42. package/dist/errors.d.ts.map +1 -1
  43. package/dist/errors.js +104 -15
  44. package/dist/errors.js.map +1 -1
  45. package/dist/events.d.ts +57 -13
  46. package/dist/events.d.ts.map +1 -1
  47. package/dist/events.js +42 -11
  48. package/dist/events.js.map +1 -1
  49. package/dist/evidence.d.ts +4 -2
  50. package/dist/evidence.d.ts.map +1 -1
  51. package/dist/evidence.js +35 -5
  52. package/dist/evidence.js.map +1 -1
  53. package/dist/extract.d.ts +32 -8
  54. package/dist/extract.d.ts.map +1 -1
  55. package/dist/extract.js +52 -36
  56. package/dist/extract.js.map +1 -1
  57. package/dist/gemini/adapter.d.ts +54 -7
  58. package/dist/gemini/adapter.d.ts.map +1 -1
  59. package/dist/gemini/adapter.js +152 -41
  60. package/dist/gemini/adapter.js.map +1 -1
  61. package/dist/gemini/chat.d.ts +38 -53
  62. package/dist/gemini/chat.d.ts.map +1 -1
  63. package/dist/gemini/chat.js +20 -25
  64. package/dist/gemini/chat.js.map +1 -1
  65. package/dist/gemini/endpoints.d.ts +59 -11
  66. package/dist/gemini/endpoints.d.ts.map +1 -1
  67. package/dist/gemini/endpoints.js +33 -7
  68. package/dist/gemini/endpoints.js.map +1 -1
  69. package/dist/gemini/errors.d.ts +39 -5
  70. package/dist/gemini/errors.d.ts.map +1 -1
  71. package/dist/gemini/errors.js +70 -9
  72. package/dist/gemini/errors.js.map +1 -1
  73. package/dist/gemini/generate.d.ts +53 -2
  74. package/dist/gemini/generate.d.ts.map +1 -1
  75. package/dist/gemini/generate.js +100 -50
  76. package/dist/gemini/generate.js.map +1 -1
  77. package/dist/gemini/index.d.ts +4 -4
  78. package/dist/gemini/index.d.ts.map +1 -1
  79. package/dist/http.d.ts +41 -3
  80. package/dist/http.d.ts.map +1 -1
  81. package/dist/http.js +40 -2
  82. package/dist/http.js.map +1 -1
  83. package/dist/index.d.ts +13 -8
  84. package/dist/index.d.ts.map +1 -1
  85. package/dist/index.js +8 -5
  86. package/dist/index.js.map +1 -1
  87. package/dist/ingest.d.ts +78 -0
  88. package/dist/ingest.d.ts.map +1 -0
  89. package/dist/ingest.js +893 -0
  90. package/dist/ingest.js.map +1 -0
  91. package/dist/library.d.ts +295 -33
  92. package/dist/library.d.ts.map +1 -1
  93. package/dist/library.js +458 -650
  94. package/dist/library.js.map +1 -1
  95. package/dist/map-reduce.d.ts +176 -10
  96. package/dist/map-reduce.d.ts.map +1 -1
  97. package/dist/map-reduce.js +807 -61
  98. package/dist/map-reduce.js.map +1 -1
  99. package/dist/model.d.ts +79 -6
  100. package/dist/model.d.ts.map +1 -1
  101. package/dist/model.js +80 -4
  102. package/dist/model.js.map +1 -1
  103. package/dist/node/handlers.d.ts +247 -14
  104. package/dist/node/handlers.d.ts.map +1 -1
  105. package/dist/node/handlers.js +491 -227
  106. package/dist/node/handlers.js.map +1 -1
  107. package/dist/node/index.d.ts +3 -2
  108. package/dist/node/index.d.ts.map +1 -1
  109. package/dist/node/index.js +2 -1
  110. package/dist/node/index.js.map +1 -1
  111. package/dist/node/ingest-child.d.ts +7 -1
  112. package/dist/node/ingest-child.d.ts.map +1 -1
  113. package/dist/node/ingest-child.js +19 -4
  114. package/dist/node/ingest-child.js.map +1 -1
  115. package/dist/node/isolated.d.ts +3 -1
  116. package/dist/node/isolated.d.ts.map +1 -1
  117. package/dist/node/isolated.js +11 -4
  118. package/dist/node/isolated.js.map +1 -1
  119. package/dist/node/originals.d.ts +19 -0
  120. package/dist/node/originals.d.ts.map +1 -0
  121. package/dist/node/originals.js +82 -0
  122. package/dist/node/originals.js.map +1 -0
  123. package/dist/node/spool.d.ts +106 -0
  124. package/dist/node/spool.d.ts.map +1 -0
  125. package/dist/node/spool.js +378 -0
  126. package/dist/node/spool.js.map +1 -0
  127. package/dist/node/sse.d.ts +6 -4
  128. package/dist/node/sse.d.ts.map +1 -1
  129. package/dist/node/sse.js +9 -7
  130. package/dist/node/sse.js.map +1 -1
  131. package/dist/openai/adapter.d.ts +5 -1
  132. package/dist/openai/adapter.d.ts.map +1 -1
  133. package/dist/openai/adapter.js +53 -12
  134. package/dist/openai/adapter.js.map +1 -1
  135. package/dist/output-limit.d.ts +2 -1
  136. package/dist/output-limit.d.ts.map +1 -1
  137. package/dist/output-limit.js +5 -2
  138. package/dist/output-limit.js.map +1 -1
  139. package/dist/pdf-layout.d.ts.map +1 -1
  140. package/dist/pdf-layout.js +71 -12
  141. package/dist/pdf-layout.js.map +1 -1
  142. package/dist/pdf-outline.d.ts +71 -0
  143. package/dist/pdf-outline.d.ts.map +1 -0
  144. package/dist/pdf-outline.js +414 -0
  145. package/dist/pdf-outline.js.map +1 -0
  146. package/dist/plan.d.ts +137 -7
  147. package/dist/plan.d.ts.map +1 -1
  148. package/dist/plan.js +248 -26
  149. package/dist/plan.js.map +1 -1
  150. package/dist/prepare.d.ts +50 -0
  151. package/dist/prepare.d.ts.map +1 -0
  152. package/dist/prepare.js +207 -0
  153. package/dist/prepare.js.map +1 -0
  154. package/dist/ranged.d.ts +16 -11
  155. package/dist/ranged.d.ts.map +1 -1
  156. package/dist/ranged.js +56 -12
  157. package/dist/ranged.js.map +1 -1
  158. package/dist/retry.d.ts +3 -1
  159. package/dist/retry.d.ts.map +1 -1
  160. package/dist/retry.js +6 -2
  161. package/dist/retry.js.map +1 -1
  162. package/dist/scope.d.ts +25 -0
  163. package/dist/scope.d.ts.map +1 -0
  164. package/dist/scope.js +60 -0
  165. package/dist/scope.js.map +1 -0
  166. package/dist/search.d.ts +7 -0
  167. package/dist/search.d.ts.map +1 -1
  168. package/dist/search.js +72 -10
  169. package/dist/search.js.map +1 -1
  170. package/dist/source.d.ts +60 -0
  171. package/dist/source.d.ts.map +1 -0
  172. package/dist/source.js +170 -0
  173. package/dist/source.js.map +1 -0
  174. package/dist/stores.d.ts +126 -31
  175. package/dist/stores.d.ts.map +1 -1
  176. package/dist/stores.js +655 -141
  177. package/dist/stores.js.map +1 -1
  178. package/dist/testing/fake-fetch.d.ts +31 -0
  179. package/dist/testing/fake-fetch.d.ts.map +1 -0
  180. package/dist/testing/fake-fetch.js +66 -0
  181. package/dist/testing/fake-fetch.js.map +1 -0
  182. package/dist/testing/fake-model.d.ts +38 -0
  183. package/dist/testing/fake-model.d.ts.map +1 -0
  184. package/dist/testing/fake-model.js +62 -0
  185. package/dist/testing/fake-model.js.map +1 -0
  186. package/dist/testing/index.d.ts +7 -0
  187. package/dist/testing/index.d.ts.map +1 -0
  188. package/dist/testing/index.js +9 -0
  189. package/dist/testing/index.js.map +1 -0
  190. package/dist/testing/store-checks.d.ts +72 -0
  191. package/dist/testing/store-checks.d.ts.map +1 -0
  192. package/dist/testing/store-checks.js +619 -0
  193. package/dist/testing/store-checks.js.map +1 -0
  194. package/dist/tools.d.ts +47 -2
  195. package/dist/tools.d.ts.map +1 -1
  196. package/dist/tools.js +440 -71
  197. package/dist/tools.js.map +1 -1
  198. package/dist/types.d.ts +165 -14
  199. package/dist/types.d.ts.map +1 -1
  200. package/dist/whole-cost.d.ts +37 -0
  201. package/dist/whole-cost.d.ts.map +1 -0
  202. package/dist/whole-cost.js +46 -0
  203. package/dist/whole-cost.js.map +1 -0
  204. package/docs/README.md +21 -8
  205. package/docs/getting-started.md +18 -13
  206. package/docs/guides/anthropic.md +17 -10
  207. package/docs/guides/conversations.md +112 -47
  208. package/docs/guides/costs-and-limits.md +147 -42
  209. package/docs/guides/deployment.md +380 -86
  210. package/docs/guides/errors-and-reliability.md +317 -67
  211. package/docs/guides/explorer-model.md +4 -1
  212. package/docs/guides/openai-compatible.md +47 -7
  213. package/docs/guides/own-adapter-and-loop.md +60 -16
  214. package/docs/guides/pdfs.md +219 -36
  215. package/docs/guides/storage.md +676 -145
  216. package/docs/guides/testing.md +149 -129
  217. package/docs/guides/vertex-and-gemini.md +169 -57
  218. package/docs/guides/web-app.md +318 -80
  219. package/docs/how-it-works.md +155 -30
  220. package/docs/measurements.md +215 -13
  221. package/docs/publishing.md +185 -37
  222. package/docs/reference/anthropic.md +12 -7
  223. package/docs/reference/ask.md +415 -47
  224. package/docs/reference/errors-and-retries.md +194 -14
  225. package/docs/reference/events.md +77 -27
  226. package/docs/reference/gemini.md +252 -87
  227. package/docs/reference/library.md +886 -178
  228. package/docs/reference/node.md +659 -111
  229. package/docs/reference/openai.md +21 -10
  230. package/docs/reference/testing.md +311 -0
  231. package/docs/reference/tools.md +285 -30
  232. package/docs/security.md +404 -78
  233. package/docs/troubleshooting.md +151 -70
  234. package/docs/upgrading-0.10.md +472 -0
  235. package/docs/upgrading-0.9.md +890 -0
  236. package/package.json +16 -3
  237. package/src/access.ts +267 -0
  238. package/src/aggregate.ts +92 -14
  239. package/src/analyze.ts +2 -2
  240. package/src/answer-info.ts +45 -0
  241. package/src/anthropic/adapter.ts +40 -11
  242. package/src/ask.ts +866 -115
  243. package/src/cache.ts +20 -5
  244. package/src/citations.ts +294 -0
  245. package/src/encoding.ts +6 -4
  246. package/src/error-info.ts +290 -0
  247. package/src/errors.ts +131 -15
  248. package/src/events.ts +112 -24
  249. package/src/evidence.ts +35 -5
  250. package/src/extract.ts +56 -34
  251. package/src/gemini/adapter.ts +196 -43
  252. package/src/gemini/chat.ts +63 -78
  253. package/src/gemini/endpoints.ts +89 -16
  254. package/src/gemini/errors.ts +74 -11
  255. package/src/gemini/generate.ts +147 -57
  256. package/src/gemini/index.ts +4 -4
  257. package/src/http.ts +65 -4
  258. package/src/index.ts +13 -8
  259. package/src/ingest.ts +958 -0
  260. package/src/library.ts +711 -651
  261. package/src/map-reduce.ts +858 -70
  262. package/src/model.ts +113 -9
  263. package/src/node/handlers.ts +709 -221
  264. package/src/node/index.ts +14 -2
  265. package/src/node/ingest-child.ts +24 -6
  266. package/src/node/isolated.ts +11 -4
  267. package/src/node/originals.ts +78 -0
  268. package/src/node/spool.ts +379 -0
  269. package/src/node/sse.ts +9 -7
  270. package/src/openai/adapter.ts +56 -13
  271. package/src/output-limit.ts +5 -2
  272. package/src/pdf-layout.ts +69 -11
  273. package/src/pdf-outline.ts +400 -0
  274. package/src/plan.ts +287 -36
  275. package/src/prepare.ts +253 -0
  276. package/src/ranged.ts +48 -14
  277. package/src/retry.ts +6 -2
  278. package/src/scope.ts +63 -0
  279. package/src/search.ts +69 -13
  280. package/src/source.ts +178 -0
  281. package/src/stores.ts +702 -142
  282. package/src/testing/fake-fetch.ts +80 -0
  283. package/src/testing/fake-model.ts +78 -0
  284. package/src/testing/index.ts +11 -0
  285. package/src/testing/store-checks.ts +660 -0
  286. package/src/tools.ts +461 -73
  287. package/src/types.ts +151 -14
  288. package/src/whole-cost.ts +64 -0
package/dist/ask.js CHANGED
@@ -1,16 +1,26 @@
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
3
  import { eventErrorOf, EventEmitter, eventStream, newRunId } from "./events.js";
4
+ import { checkCitations } from "./citations.js";
4
5
  import { evidenceOf, stubResult } from "./evidence.js";
5
6
  import { isCutReply, until } from "./http.js";
6
7
  import { Limiter } from "./limiter.js";
7
- import { DocumentsNotFoundError, errorKindOf, laterResult, rateAllowanceOf, UsageMeter, } from "./model.js";
8
- import { estimateParts, REQUEST_BYTES_MARGIN } from "./plan.js";
8
+ import { DocumentsNotFoundError, errorKindOf, laterResult, modelErrorOf, rateAllowanceOf, reportsInput, TOOL_TURN_VERSION, UsageMeter, } from "./model.js";
9
+ import { DocumentStoreError } from "./errors.js";
10
+ import { canBeReadWhole, estimateParts, inlineInstruction, questionTools, REQUEST_BYTES_MARGIN } from "./plan.js";
11
+ import { preparedHere } from "./prepare.js";
9
12
  import { statusOf, withRetry } from "./retry.js";
10
13
  import { estimateTokens, jsonBytes, wellFormedJson } from "./text.js";
11
14
  import { alreadyShown, failureKind, fitAnswer, LEAST_RESULT_CHARACTERS, MAX_WHOLE_DOCUMENT_READS, repeatedFailureHint, stepLine, TOOL_NAMES, toolCallKey, toolResultSummary, unknownToolName, } from "./tools.js";
15
+ import { wholeReadCost } from "./whole-cost.js";
12
16
  /** Sent (invisibly to the user) when the model must stop using tools and answer. */
13
17
  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.";
18
+ /**
19
+ * The same, when files were also sent whole and the tools can read them or their lines are
20
+ * numbered (`inlineTables`, `numberInline`): what they say is part of the answer too, not only what
21
+ * the tools returned. New in 0.10.0. Not exported from the package.
22
+ */
23
+ export const FINAL_ANSWER_WITH_FILES = "Stop using tools now. Answer my question using only the files shown in full and what the tools returned above, with line citations. Say plainly what you could not find. Answer in the language of my question.";
14
24
  /** The same, when the only tool was `view_pages`: the text of the files is in the prompt, not in tool results. */
15
25
  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.";
16
26
  /**
@@ -23,19 +33,191 @@ export const FINAL_ANSWER_WITHOUT_TOOLS = "Answer my question now, from what is
23
33
  * needs, and the other model writes the answer.
24
34
  */
25
35
  export const EXPLORER_INSTRUCTION = "You only gather material in this conversation: another model writes the answer. It sees this conversation and what your tool calls returned, not what you thought or wrote. So call the tools until their results hold everything the answer needs from the files. Then, or at once if no tool is needed, reply with the single word DONE instead of an answer.";
36
+ /**
37
+ * The least ceiling on the input tokens of a question that sets no `limits.inputTokens`. Its
38
+ * ceiling is the larger of this and `toolTurns` times its first request, with the room for its
39
+ * whole-file reads added. New in 0.10.0.
40
+ */
41
+ export const DEFAULT_INPUT_TOKENS = 1_000_000;
42
+ /** How many whole-file reads one question may make, over all its documents, by default (`limits.wholeReadsPerQuestion`). */
43
+ const DEFAULT_WHOLE_READS_PER_QUESTION = 2;
44
+ /** The line added to the system instruction when `count` documents were left out ("drop"). */
45
+ const missingFilesLine = (count) => (count === 1
46
+ ? "1 of the attached files is no longer available; say so if the question needs it."
47
+ : `${count} of the attached files are no longer available; say so if the question needs them.`);
48
+ /** A value as an error quotes it. */
49
+ const shownValue = (value) => (typeof value === "string" ? JSON.stringify(value) : value === null ? "null" : typeof value);
50
+ /** `onMissingDocuments` checked: a value it cannot be is an error before anything is planned. */
51
+ function checkMissingPolicy(given) {
52
+ if (given === undefined || given === "throw" || given === "drop" || typeof given === "function")
53
+ return;
54
+ throw new TypeError(`onMissingDocuments must be "throw", "drop" or a function, and is ${shownValue(given)}.`);
55
+ }
56
+ /**
57
+ * `filteredAnswer` checked: a value it cannot be ("Drop", true) is an error before anything is
58
+ * planned. It would otherwise keep a filtered answer that the application meant to drop.
59
+ */
60
+ function checkFilteredAnswer(given) {
61
+ if (given === undefined || given === "keep" || given === "drop")
62
+ return;
63
+ throw new TypeError(`filteredAnswer must be "keep" or "drop", and is ${shownValue(given)}.`);
64
+ }
65
+ /**
66
+ * `inlineTables` and `numberInline` checked: a value they cannot be ("Text", "false") is an error
67
+ * before anything is planned, as `prepare` would throw it, but in the words of the question.
68
+ */
69
+ function checkInlineOptions(tables, numbered) {
70
+ if (tables !== undefined && tables !== "tools" && tables !== "text")
71
+ throw new TypeError(`inlineTables must be "tools" or "text", and is ${shownValue(tables)}.`);
72
+ if (numbered !== undefined && typeof numbered !== "boolean")
73
+ throw new TypeError(`numberInline must be true or false, and is ${shownValue(numbered)}.`);
74
+ }
75
+ /**
76
+ * The evidence of a document sent whole (since 0.10.0): every line of it was shown. It comes from
77
+ * no tool call, so it has no `callId`.
78
+ */
79
+ const sentWhole = (meta) => ({
80
+ tool: "inline",
81
+ documentId: meta.id,
82
+ document: meta.name,
83
+ ...(Number.isFinite(meta.lines) && meta.lines >= 1 ? { lines: [[1, Math.trunc(meta.lines)]] } : {}),
84
+ whole: true,
85
+ });
86
+ /** An object made as `{}` or `Object.create(null)` is: not a Map, an array or an instance of a class. */
87
+ const isPlainObject = (value) => {
88
+ if (value === null || typeof value !== "object")
89
+ return false;
90
+ const prototype = Object.getPrototypeOf(value);
91
+ return prototype === Object.prototype || prototype === null;
92
+ };
93
+ /** What a function of `onMissingDocuments` returned, checked. */
94
+ function checkedAction(action) {
95
+ if (action === "throw" || action === "drop")
96
+ return action;
97
+ // Only the keys of an action: a key it does not have is a mistake, not something to ignore.
98
+ if (action !== null && typeof action === "object" && Object.keys(action).every((key) => key === "retry" || key === "replace")) {
99
+ const { retry, replace } = action;
100
+ if (retry === true && replace === undefined)
101
+ return { retry: true };
102
+ if (retry === undefined && isPlainObject(replace) && Object.values(replace).every((id) => typeof id === "string" && id.length > 0)) {
103
+ return { replace: { ...replace } };
104
+ }
105
+ }
106
+ throw new TypeError(`onMissingDocuments returned ${shownValue(action)}: it must return "throw", "drop", { retry: true } or { replace: { [oldId]: newId } }.`);
107
+ }
108
+ /**
109
+ * What `onToolResult` returned, checked: undefined, `{ result }` with a result that is an object,
110
+ * or `{ reject }` with a string. A verdict with a `result` is a result, whatever else it holds.
111
+ * Anything else ends the question: the hook is there to keep something from the model, and a
112
+ * mistake in it must not let the result through.
113
+ */
114
+ function checkedVerdict(verdict) {
115
+ if (verdict === undefined)
116
+ return undefined;
117
+ if (verdict !== null && typeof verdict === "object") {
118
+ if (Object.hasOwn(verdict, "result")) {
119
+ const { result } = verdict;
120
+ if (result !== null && typeof result === "object" && !Array.isArray(result))
121
+ return { result: result };
122
+ }
123
+ else if (Object.hasOwn(verdict, "reject")) {
124
+ const { reject } = verdict;
125
+ if (typeof reject === "string")
126
+ return { reject };
127
+ }
128
+ }
129
+ throw new TypeError(`onToolResult returned ${shownValue(verdict)}: it must return { result }, { reject: "why" } or undefined.`);
130
+ }
131
+ /**
132
+ * Plans the documents `ids`, and settles those that are missing as `onMissingDocuments` says. A
133
+ * retry or a replace plans them again, once.
134
+ */
135
+ async function planDocumentsOf(options, ids, prepare) {
136
+ const prepared = await prepare(ids);
137
+ if (prepared.missing.length === 0)
138
+ return { prepared, documentIds: ids, dropped: [] };
139
+ const policy = options.onMissingDocuments ?? "throw";
140
+ let action = policy === "drop" ? "drop" : "throw";
141
+ if (typeof policy === "function") {
142
+ options.signal?.throwIfAborted();
143
+ const context = {
144
+ ...(options.owner !== undefined ? { owner: options.owner } : {}),
145
+ ...(options.scope !== undefined ? { scope: options.scope } : {}),
146
+ ...(options.signal ? { signal: options.signal } : {}),
147
+ };
148
+ // A function that does not look at the signal does not hold the question once it is stopped.
149
+ action = checkedAction(await until(policy([...prepared.missing], context), options.signal));
150
+ }
151
+ if (action === "throw")
152
+ throw new DocumentsNotFoundError(prepared.missing);
153
+ if (action === "drop") {
154
+ const gone = new Set(prepared.missing);
155
+ return { prepared, documentIds: ids.filter((id) => !gone.has(id)), dropped: [...prepared.missing] };
156
+ }
157
+ const replace = "replace" in action ? action.replace : {};
158
+ const again = ids.map((id) => (Object.hasOwn(replace, id) ? replace[id] : id));
159
+ const second = await prepare(again);
160
+ if (second.missing.length > 0)
161
+ throw new DocumentsNotFoundError(second.missing);
162
+ return { prepared: second, documentIds: again, dropped: [] };
163
+ }
164
+ /** The step of a question whose older tool results were shortened to make room. */
165
+ const RESULTS_SHORTENED = "Older tool results were shortened to make room in the request";
26
166
  const DEFAULT_TOOL_TURNS = 12;
27
167
  const DEFAULT_CALLS_PER_TURN = 8;
28
168
  /** Tool calls of one turn that run at the same time. */
29
169
  const CALLS_AT_ONCE = 4;
30
170
  /** With less room than this for its result, a call is not run. */
31
171
  const LEAST_ROOM_CHARACTERS = 1_500;
32
- /** Characters of a tool result for each token of room. A log full of IDs and numbers comes to about two. */
172
+ /**
173
+ * Characters of a tool result for each token of room, when the call names no document of the
174
+ * question. Since 0.10.0 a call that names one takes its document's own (`charactersPerToken`).
175
+ */
33
176
  const CHARACTERS_PER_TOKEN = 2;
177
+ /**
178
+ * The characters of a document's text for each token of the estimate, as its ingest counted them,
179
+ * from 0.8 to 4: about 0.9 for a table of numbers, 1.4 for a service log, 1.9 for Hebrew prose.
180
+ * The JSON of a tool result that quotes the text comes to about the same. `CHARACTERS_PER_TOKEN`
181
+ * when the metadata does not say. New in 0.10.0.
182
+ */
183
+ function charactersPerToken(meta) {
184
+ const ratio = meta && meta.estimatedTokens > 0 ? meta.characters / meta.estimatedTokens : Number.NaN;
185
+ return Number.isFinite(ratio) ? Math.min(4, Math.max(0.8, ratio)) : CHARACTERS_PER_TOKEN;
186
+ }
187
+ /** The tokens of room a tool result takes in a request, as the request meter counts an answer. */
188
+ const resultTokens = (result) => estimateTokens(JSON.stringify(result)) + 8;
189
+ /**
190
+ * `result` cut to `tokens` of room (`resultTokens`): by `fitAnswer`, to the characters its own
191
+ * characters per token give, and a little less again while it is still over. Never below
192
+ * `LEAST_RESULT_CHARACTERS`.
193
+ */
194
+ function cutToTokens(result, tokens) {
195
+ const json = JSON.stringify(result);
196
+ const perToken = json.length / Math.max(1, resultTokens(result));
197
+ let characters = Math.max(LEAST_RESULT_CHARACTERS, Math.floor(tokens * perToken));
198
+ let cut = fitAnswer(result, characters);
199
+ for (let tries = 0; tries < 4 && resultTokens(cut) > tokens && characters > LEAST_RESULT_CHARACTERS; tries++) {
200
+ characters = Math.max(LEAST_RESULT_CHARACTERS, Math.floor(characters * 0.85));
201
+ cut = fitAnswer(result, characters);
202
+ }
203
+ return cut;
204
+ }
205
+ /**
206
+ * `alreadyShown`, but never a pointer to a result that `onToolResult` replaced (`redacted: true`):
207
+ * it does not hold what the call would return.
208
+ */
209
+ function pointerTo(call, earlier, stored = false) {
210
+ return earlier.result.redacted === true ? undefined : alreadyShown(call, earlier, stored);
211
+ }
34
212
  /** Bytes a character of a tool result may take in the request. */
35
213
  const BYTES_PER_CHARACTER = 3;
36
214
  /** Tool rounds whose results are kept in full when older ones are dropped to make room. */
37
215
  const ROUNDS_KEPT = [3, 2, 1];
38
216
  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.";
217
+ /** How the error of a whole-file read that sent its parts, and could read none of them, begins (`NothingReadError`). */
218
+ const NOTHING_READ = "Could not read any part of ";
219
+ /** The answer to a call of a tool the question does not have: it is not run, and takes no room. New in 0.10.0. */
220
+ const unknownTool = (name, tools) => `Unknown tool ${unknownToolName(name)}. The tools are: ${tools.join(", ")}.`;
39
221
  /** Why a request of a whole-file read that its read left behind ended with its call. */
40
222
  const CALL_ENDED = "The tool call ended before this request did.";
41
223
  const count = (value) => Math.max(0, Math.round(value)).toLocaleString("en-US");
@@ -64,10 +246,28 @@ function pagesShown(result) {
64
246
  * character in it (0.5.0 cut some search windows inside an emoji, and Claude's API refuses them).
65
247
  */
66
248
  const carriedResult = (result) => wellFormedJson(laterResult(result));
67
- /** The conversation as the loop keeps it: copies, so that nothing of the caller's is changed. */
249
+ /**
250
+ * Refuses a stored tool round of a version this package does not read: one a newer version made
251
+ * (`ToolTurn.version` above `TOOL_TURN_VERSION`). A round without a version (before 0.9.0) is read
252
+ * as before. A `TypeError`, which an application can catch to leave such rounds out.
253
+ */
254
+ function checkToolTurnVersion(turn) {
255
+ const version = turn.version ?? 0;
256
+ if (typeof version === "number" && version <= TOOL_TURN_VERSION)
257
+ return;
258
+ if (typeof version !== "number" || Number.isNaN(version)) {
259
+ throw new TypeError(`A stored tool round (toolTurns) has a version that is not a number (${typeof version === "string" ? JSON.stringify(version) : String(version)}). Leave it out of messages, or store it as it was given.`);
260
+ }
261
+ throw new TypeError(`A stored tool round (toolTurns) has version ${String(version)}: a newer version of llm-large-files made it, and this one reads up to version ${TOOL_TURN_VERSION}. Leave it out of messages.`);
262
+ }
263
+ /**
264
+ * The conversation as the loop keeps it: copies, so that nothing of the caller's is changed. Of a
265
+ * stored tool round, only the calls are kept: its version is not sent to the model.
266
+ */
68
267
  function toMessages(given) {
69
268
  const messages = given.map((message) => {
70
269
  if (message.role === "tools") {
270
+ checkToolTurnVersion(message);
71
271
  const answers = message.calls.map(({ result, ...call }) => ({ call, result: carriedResult(result) }));
72
272
  return { role: "tools", calls: answers.map((answer) => answer.call), answers };
73
273
  }
@@ -88,7 +288,9 @@ function textSize(messages, system) {
88
288
  for (const part of message.parts) {
89
289
  if (typeof part.text === "string") {
90
290
  tokens += estimateTokens(part.text);
91
- bytes += jsonBytes(part.text);
291
+ // A part in the provider's own form is sent whole: its text, and what is next to it (a
292
+ // thought signature), or the call that the text stands for.
293
+ bytes += part.native === undefined ? jsonBytes(part.text) : Math.max(jsonBytes(part.text), (JSON.stringify(part.native) ?? "").length);
92
294
  }
93
295
  else {
94
296
  const size = (JSON.stringify(part.native) ?? "").length;
@@ -182,24 +384,30 @@ class RequestMeter {
182
384
  }
183
385
  }
184
386
  /**
185
- * Shares `room` characters among tool calls whose results may be up to `caps` characters. A call
186
- * gets no more than its cap, and the others split what it leaves. Calls that cannot each get
187
- * `LEAST_ROOM_CHARACTERS` (or their cap, when it is smaller) are not run, the last ones first:
188
- * their share is undefined.
387
+ * Shares `room` among tool calls whose results may be up to `caps` characters. A character of the
388
+ * result of call i takes `rates[i]` of the room (1 when `rates` is left out: the room is in
389
+ * characters; since 0.10.0 the loop gives it in tokens, and each call the tokens a character of its
390
+ * document takes). A call gets no more than its cap, and the others split what it leaves. Calls
391
+ * that cannot each get `LEAST_ROOM_CHARACTERS` (or their cap, when it is smaller) are not run, the
392
+ * last ones first: their share is undefined. The shares are in characters.
189
393
  */
190
- export function shareRoom(caps, room) {
191
- const least = (cap) => Math.min(cap, LEAST_ROOM_CHARACTERS);
394
+ export function shareRoom(caps, room, rates) {
395
+ const rate = (index) => rates?.[index] ?? 1;
396
+ const least = (cap, index) => Math.min(cap, LEAST_ROOM_CHARACTERS) * rate(index);
192
397
  let count = caps.length;
193
- let needed = caps.reduce((sum, cap) => sum + least(cap), 0);
194
- while (count > 0 && needed > room)
195
- needed -= least(caps[--count]);
398
+ let needed = caps.reduce((sum, cap, index) => sum + least(cap, index), 0);
399
+ while (count > 0 && needed > room) {
400
+ count--;
401
+ needed -= least(caps[count], count);
402
+ }
196
403
  const shares = caps.map(() => undefined);
197
404
  // The smallest caps first: each call takes its cap or an even share of what is left, whichever is less.
198
- const order = caps.slice(0, count).map((cap, index) => ({ cap, index })).sort((left, right) => left.cap - right.cap);
405
+ const order = caps.slice(0, count).map((cap, index) => ({ cap: cap * rate(index), index })).sort((left, right) => left.cap - right.cap);
199
406
  let left = Math.max(0, Math.floor(room));
200
407
  order.forEach(({ cap, index }, position) => {
201
408
  const share = Math.min(cap, Math.floor(left / (order.length - position)));
202
- shares[index] = share;
409
+ // A call given its whole cap gets the cap as it is, not as it comes back from the rate.
410
+ shares[index] = share === cap ? caps[index] : Math.floor(share / rate(index));
203
411
  left -= share;
204
412
  });
205
413
  return shares;
@@ -280,7 +488,7 @@ const MOST_OVERFLOW_RECOVERIES = 2;
280
488
  * so it turned off the ceilings and the cap on whole-file reads, or every tool.
281
489
  */
282
490
  function checkedLimits(given) {
283
- for (const field of ["toolTurns", "callsPerTurn", "wholeDocumentReads", "inputTokens", "requests"]) {
491
+ for (const field of ["toolTurns", "callsPerTurn", "wholeDocumentReads", "inputTokens", "requests", "wholeReadsPerQuestion"]) {
284
492
  const value = given?.[field];
285
493
  if (value === undefined)
286
494
  continue;
@@ -340,13 +548,21 @@ export async function askWithFiles(options) {
340
548
  * A result as `run.finish` and `run.error` carry it: a copy, so that a listener cannot change the
341
549
  * caller's, without the tool rounds and with the plan naming documents only (both hold text of
342
550
  * the documents: tool results, outline headings, the commonest lines of a log) unless `withTurns`.
551
+ * Its plan never holds the owner, scope, SHA-256 or original of a document.
343
552
  */
344
553
  function eventResultOf(result, withTurns) {
554
+ const { toolTurns, plan, ...rest } = result;
555
+ // The full metadata only with `withTurns`, and never what is to stay on the server: who owns a
556
+ // document, its scope, the SHA-256 and the ref of its original.
345
557
  if (withTurns)
346
- return { ...result };
347
- const { toolTurns: _toolTurns, plan, ...rest } = result;
558
+ return { ...rest, toolTurns, plan: { inline: plan.inline.map(withoutServerFields), searchable: plan.searchable.map(withoutServerFields) } };
348
559
  return { ...rest, plan: { inline: plan.inline.map(documentRef), searchable: plan.searchable.map(documentRef) } };
349
560
  }
561
+ /** A document's metadata without what is to stay on the server, for an event (since 0.10.0). */
562
+ function withoutServerFields(meta) {
563
+ const { owner: _owner, scope: _scope, sha256: _sha256, original: _original, metaVersion: _metaVersion, ...rest } = meta;
564
+ return rest;
565
+ }
350
566
  /**
351
567
  * `askWithFiles` as a stream of its events, for a page that shows the question as it goes: see
352
568
  * `AskEvent`. Leaving the loop early (`break`) stops the question. `result` is what `askWithFiles`
@@ -385,7 +601,9 @@ async function askPlanned(options, state) {
385
601
  // Failed before it sent anything (a budget of the application's that cannot work with the
386
602
  // smaller window): the provider's error, with what the first try found, is the one to report.
387
603
  // (The question's own record: `partialResultOf` gives nothing for an error another question threw too.)
388
- if (state.failed?.error !== again && again?.status === undefined) {
604
+ // (A store that failed, or a document gone, has a status since 0.9.0, but is not the model's.)
605
+ const fromModel = again?.status !== undefined && !DocumentStoreError.is(again) && !DocumentsNotFoundError.is(again);
606
+ if (state.failed?.error !== again && !fromModel) {
389
607
  keepPartial(error.overflow, state, error.partial);
390
608
  throw error.overflow;
391
609
  }
@@ -396,11 +614,18 @@ async function askPlanned(options, state) {
396
614
  async function ask(options, carried, state) {
397
615
  const { files, model, signal } = options;
398
616
  const { events } = state;
399
- // A second model for the requests that use tools. The answering model itself is not one.
400
- const explorer = options.explorer && options.explorer !== model ? options.explorer : undefined;
401
- const toolModel = explorer ?? model;
402
- const models = explorer ? [model, explorer] : [model];
617
+ // A second model for the requests that use tools. The answering model itself is not one. It
618
+ // explores only when a file is searched (see `explorer` below), but the budget is fitted to it.
619
+ const given = options.explorer && options.explorer !== model ? options.explorer : undefined;
620
+ const models = given ? [model, given] : [model];
403
621
  const limits = checkedLimits(options.limits);
622
+ checkMissingPolicy(options.onMissingDocuments);
623
+ checkFilteredAnswer(options.filteredAnswer);
624
+ checkInlineOptions(options.inlineTables, options.numberInline);
625
+ // Since 0.10.0 by default: the tables sent whole get the tools, and the files sent whole have
626
+ // numbered lines. "text" and false send them as 0.9 did.
627
+ const inlineTables = options.inlineTables ?? "tools";
628
+ const numberInline = options.numberInline ?? true;
404
629
  // A question planned again goes on counting what its first try paid for.
405
630
  const usage = carried?.usage ?? new UsageMeter();
406
631
  // The budget is counted in the library's estimate of tokens. A model whose tokenizer counts
@@ -431,16 +656,48 @@ async function ask(options, carried, state) {
431
656
  const meter = new RequestMeter(pageTokens);
432
657
  const asText = textSize(messages, options.system);
433
658
  const earlier = meter.rounds(messages);
434
- const prepared = await files.prepare(options.documentIds, { tokens: asText.tokens + earlier.tokens, bytes: asText.bytes + earlier.bytes }, {
659
+ // Who asks: the documents are looked up, and every tool call reads them, for this owner and
660
+ // scope. The question's signal goes with them, for a library that ends its waits for the store
661
+ // with it (`AccessOptions.signal`).
662
+ const access = {
435
663
  ...(options.owner !== undefined ? { owner: options.owner } : {}),
664
+ ...(options.scope !== undefined ? { scope: options.scope } : {}),
665
+ ...(signal ? { signal } : {}),
666
+ };
667
+ // Documents that are missing are settled as `onMissingDocuments` says. A question planned again
668
+ // starts from the documents its first try planned: the function is not asked again about them.
669
+ // The question stops when its signal aborts, whether the library does or not: a store call that
670
+ // hangs (a network volume that does not answer) must not hold it, with any `LargeFiles`.
671
+ const planned = await planDocumentsOf(options, carried?.documentIds ?? options.documentIds, (ids) => until(files.prepare(ids, { tokens: asText.tokens + earlier.tokens, bytes: asText.bytes + earlier.bytes }, {
672
+ ...access,
436
673
  viewPages: options.viewPages !== false && canShowFiles,
437
674
  // The guide and the cards name `analyze_whole_document` only when the tools will have it.
438
- wholeDocumentAnalysis: options.wholeDocumentAnalysis !== false && typeof toolModel.generateText === "function",
675
+ wholeDocumentAnalysis: options.wholeDocumentAnalysis !== false && typeof (given ?? model).generateText === "function",
439
676
  budget,
440
- });
441
- if (prepared.missing.length)
442
- throw new DocumentsNotFoundError(prepared.missing);
443
- const blocks = [...new Set(options.documentIds)].map((id) => prepared.blocks.get(id)).filter((block) => Boolean(block));
677
+ numberInline,
678
+ inlineTables,
679
+ }), signal));
680
+ const { prepared, documentIds } = planned;
681
+ /** The documents left out of the question ("drop"), by this try and by the first. */
682
+ const missing = [...carried?.missing ?? [], ...planned.dropped];
683
+ // Tools are needed for a file that is too large to send whole, for a PDF whose pages can be
684
+ // looked at (that one may have its whole text in the prompt and still hide a chart from the
685
+ // model), and for a table sent whole whose rows they can count (`inlineTables`). A library of
686
+ // your own whose `prepare` gives no `toolable` has none of the last.
687
+ const { searchable } = prepared.plan;
688
+ const { viewable } = prepared;
689
+ const toolable = prepared.toolable ?? [];
690
+ // The explorer gathers what the answer needs from the files searched with the tools. When none
691
+ // is, and the tools are there for tables sent whole, the answering model runs the loop itself: a
692
+ // question that needs no count is then answered in its first request, and the whole files are
693
+ // not sent to two models that share no cache.
694
+ const explorer = given && !(searchable.length === 0 && toolable.length > 0) ? given : undefined;
695
+ const toolModel = explorer ?? model;
696
+ // The lines of the files sent whole are numbered when asked, by a library whose `prepare` is
697
+ // that of this package (its result has the mark, `preparedHere`): one of your own of 0.9 sends
698
+ // them as they are.
699
+ const numbered = numberInline && preparedHere(prepared);
700
+ const blocks = [...new Set(documentIds)].map((id) => prepared.blocks.get(id)).filter((block) => Boolean(block));
444
701
  if (blocks.length) {
445
702
  const block = { text: blocks.join("\n\n") };
446
703
  if (options.documentPlacement === "last")
@@ -449,12 +706,17 @@ async function ask(options, carried, state) {
449
706
  else
450
707
  messages.find((message) => message.role === "user").parts.unshift(block);
451
708
  }
452
- const system = [options.system?.trim(), prepared.instruction].filter(Boolean).join("\n\n");
709
+ // A question without some of its files says so to the model, in one line of its own.
710
+ const missingLine = missing.length > 0 ? missingFilesLine(missing.length) : "";
711
+ // The fixed lines for the files sent whole (since 0.10.0): that their tables can still be counted
712
+ // with the tools, and, when no file is searched, to cite their numbered lines.
713
+ const inlineLine = inlineInstruction(prepared, numbered);
714
+ const system = [options.system?.trim(), prepared.instruction, inlineLine, missingLine].filter(Boolean).join("\n\n");
453
715
  // The size of what stays in every request: the text as asked, the documents, the tool guide.
454
716
  const whole = new Set(prepared.plan.inline.map((meta) => meta.id));
455
717
  meter.fixed = {
456
- tokens: asText.tokens + prepared.plan.inlineTokens + estimateTokens(prepared.instruction),
457
- bytes: asText.bytes + prepared.plan.inlineBytes + jsonBytes(prepared.instruction),
718
+ tokens: asText.tokens + prepared.plan.inlineTokens + estimateTokens(prepared.instruction) + (inlineLine ? estimateTokens(inlineLine) : 0) + (missingLine ? estimateTokens(missingLine) : 0),
719
+ bytes: asText.bytes + prepared.plan.inlineBytes + jsonBytes(prepared.instruction) + (inlineLine ? jsonBytes(inlineLine) : 0) + (missingLine ? jsonBytes(missingLine) : 0),
458
720
  };
459
721
  for (const [id, block] of prepared.blocks) {
460
722
  if (whole.has(id))
@@ -464,11 +726,20 @@ async function ask(options, carried, state) {
464
726
  }
465
727
  let text = "";
466
728
  let turns = carried?.turns ?? 0;
729
+ /** The last reply of the chat: its `finish` is the answer's (`AskResult.finish`). */
730
+ let lastReply;
731
+ const dropFiltered = options.filteredAnswer === "drop";
467
732
  let finishReason;
468
733
  let blockReason;
469
734
  let lastUsage;
470
735
  const steps = [];
471
- const evidence = [];
736
+ // The files sent whole come first, in the order of their blocks: the model was shown every line
737
+ // of them before any tool ran (since 0.10.0).
738
+ const inlineById = new Map(prepared.plan.inline.map((meta) => [meta.id, meta]));
739
+ const evidence = [...new Set(documentIds)].flatMap((id) => {
740
+ const meta = inlineById.get(id);
741
+ return meta ? [sentWhole(meta)] : [];
742
+ });
472
743
  const emit = (delta, requestId) => {
473
744
  text += delta;
474
745
  options.onText?.(delta);
@@ -492,7 +763,7 @@ async function ask(options, carried, state) {
492
763
  events.emit({ type: "notice", code, message, display: "activity" });
493
764
  };
494
765
  /** A notice that earlier versions did not show. */
495
- const notice = (code, message) => events.emit({ type: "notice", code, message, display: "none" });
766
+ const notice = (code, message, documentIds) => events.emit({ type: "notice", code, message, display: "none", ...(documentIds ? { documentIds } : {}) });
496
767
  const budgetReached = () => {
497
768
  if (state.budgetSaid)
498
769
  return;
@@ -503,6 +774,10 @@ async function ask(options, carried, state) {
503
774
  steps.push(...carried?.steps ?? []);
504
775
  if (carried)
505
776
  step(carried.step, "replanned");
777
+ if (planned.dropped.length > 0) {
778
+ const count = planned.dropped.length;
779
+ notice("documents_missing", `${count === 1 ? "1 of the attached files is" : `${count} of the attached files are`} no longer available: the question is answered without ${count === 1 ? "it" : "them"}.`, [...planned.dropped]);
780
+ }
506
781
  if (events.active)
507
782
  events.emit({ type: "plan", inline: prepared.plan.inline.map(documentRef), searchable: prepared.plan.searchable.map(documentRef) });
508
783
  // A model turn in its provider's own form goes back only to the adapter it came from. Any other
@@ -592,11 +867,14 @@ async function ask(options, carried, state) {
592
867
  events.emit({ type: "request.end", requestId, ms: Date.now() - began, outcome: "error", error: eventErrorOf(error) });
593
868
  throw error;
594
869
  }
595
- // Text the adapter did not pass on as it came (no streaming was asked for, or it cannot).
596
- if (shown && reply.text.length > got.length && reply.text.startsWith(got))
870
+ // Text the adapter did not pass on as it came (no streaming was asked for, or it cannot). Not
871
+ // the text of a reply a filter stopped, when such an answer is dropped: it was not shown yet.
872
+ if (shown && reply.text.length > got.length && reply.text.startsWith(got) && !(dropFiltered && reply.finish === "filtered"))
597
873
  write(reply.text.slice(got.length));
598
874
  answeredRequests++;
599
- usage.add(adapter.id, reply.usage);
875
+ lastReply = reply;
876
+ // A reply without its input tokens is counted by the estimate, in the model's own tokens.
877
+ usage.add(adapter.id, reply.usage, estimated * scaleOf(adapter));
600
878
  // The count of the model that answered, in the library's tokens by that model's own scale: how
601
879
  // much more than its scale says the text costs it, which the other model will see too. By the
602
880
  // larger scale of the two, a count of the model with the smaller one was taken for no more.
@@ -614,6 +892,8 @@ async function ask(options, carried, state) {
614
892
  ...(reply.finish ? { finish: reply.finish } : {}),
615
893
  ...(reply.finishReason !== undefined ? { finishReason: reply.finishReason } : {}),
616
894
  toolCalls: reply.calls.length,
895
+ ...(typeof reply.responseId === "string" ? { responseId: reply.responseId } : {}),
896
+ ...(typeof reply.responseModel === "string" ? { responseModel: reply.responseModel } : {}),
617
897
  });
618
898
  if (reply.blockReason)
619
899
  notice("blocked", `The provider refused the prompt: ${reply.blockReason}.`);
@@ -622,6 +902,25 @@ async function ask(options, carried, state) {
622
902
  // What a model wrote before it was stopped by a refusal is not an answer.
623
903
  const wrote = (reply) => reply.text.trim().length > 0 && !reply.blockReason;
624
904
  const asked = messages.length;
905
+ /** The documents of the question, by ID: their names and formats, for the citations of the answer. */
906
+ const documents = [...prepared.plan.inline, ...prepared.plan.searchable];
907
+ const citationsOf = () => {
908
+ const names = {};
909
+ const formats = {};
910
+ for (const meta of documents) {
911
+ names[meta.id] = meta.name;
912
+ formats[meta.id] = meta.format;
913
+ }
914
+ // A document sent whole was shown, every line of it (its evidence comes first and says so),
915
+ // and a whole-file read read every line: those from 1 to its last. A line past the end of the
916
+ // file is not supported.
917
+ const linesOf = new Map(documents.map((meta) => [meta.id, meta.lines]));
918
+ const bounded = (entry) => {
919
+ const lines = linesOf.get(entry.documentId);
920
+ return entry.whole === true && !entry.lines && typeof lines === "number" && Number.isFinite(lines) ? { ...entry, lines: lines >= 1 ? [[1, Math.trunc(lines)]] : [] } : entry;
921
+ };
922
+ return checkCitations(text, evidence.map(bounded), names, formats);
923
+ };
625
924
  const result = (answered) => ({
626
925
  text,
627
926
  answered,
@@ -631,18 +930,47 @@ async function ask(options, carried, state) {
631
930
  // The rounds as the model last had them. A file cannot be kept as JSON: what is kept says that it was shown.
632
931
  toolTurns: messages.slice(asked).filter(isRound).map((round) => ({
633
932
  role: "tools",
933
+ version: TOOL_TURN_VERSION,
634
934
  calls: round.answers.map(({ call: { problem: _problem, ...call }, result: returned, files: shownFiles }) => ({
635
935
  ...call,
636
936
  result: shownFiles?.length ? stubResult(call, returned, true) ?? returned : returned,
637
937
  })),
638
938
  })),
639
939
  plan: prepared.plan,
940
+ ...(missing.length > 0 ? { missing: [...missing] } : {}),
640
941
  budget,
641
942
  turns,
642
943
  ...(finishReason ? { finishReason } : {}),
643
944
  usage: usage.totals,
644
945
  ...(lastUsage ? { lastUsage } : {}),
946
+ ...(lastReply?.finish !== undefined ? { finish: lastReply.finish } : {}),
947
+ ...(documents.length > 0 ? { citations: citationsOf() } : {}),
645
948
  });
949
+ /**
950
+ * The result of a question that ends with an answer: one that a filter stopped, or that was cut
951
+ * at the output limit, says so in a notice, before `run.finish`. A filtered answer is dropped
952
+ * when `filteredAnswer` says so; text of it already sent is to be taken away (`discardText`).
953
+ */
954
+ const answer = (answered) => {
955
+ const finish = lastReply?.finish;
956
+ if (finish === "filtered") {
957
+ const sent = text.length > 0;
958
+ const message = !lastReply?.text.trim()
959
+ ? "A filter of the provider stopped the answer before any text came."
960
+ : dropFiltered
961
+ ? "A filter of the provider stopped the answer before it was finished: its text was dropped."
962
+ : "A filter of the provider stopped the answer before it was finished.";
963
+ events.emit({ type: "notice", code: "answer_filtered", message, display: "none", ...(dropFiltered && sent ? { discardText: true } : {}) });
964
+ if (dropFiltered) {
965
+ text = "";
966
+ return result(false);
967
+ }
968
+ }
969
+ else if (finish === "cut") {
970
+ notice("answer_cut", lastReply?.text.trim() ? "The answer stopped at the model's output limit, so it is incomplete." : "The answer stopped at the model's output limit before any text came.");
971
+ }
972
+ return result(answered);
973
+ };
646
974
  // Pages the model looks at stay in the request until the question is answered, so they are
647
975
  // counted twice: as bytes against the request limit, and as tokens against half of what the
648
976
  // budget keeps free for tool results and the answer.
@@ -654,10 +982,15 @@ async function ask(options, carried, state) {
654
982
  // request as too large, and names its window, makes it smaller.
655
983
  let tokenLimit = budget.contextTokens - Math.floor(reservedTokens / 2);
656
984
  const byteLimit = maxRequestBytes - Math.max(32_768, Math.floor(maxRequestBytes / 50));
657
- /** Characters of tool results that still fit, with a model turn that is about to be answered. */
658
- const room = (pending) => {
985
+ /**
986
+ * The tokens of tool results that still fit, with a model turn that is about to be answered, for
987
+ * calls whose results take `rates` tokens a character: within the token limit, and within the
988
+ * bytes of the request for the call that takes the fewest tokens a character.
989
+ */
990
+ const room = (pending, rates) => {
659
991
  const now = meter.current([...messages, pending]);
660
- return Math.floor(Math.min((tokenLimit - now.tokens) * CHARACTERS_PER_TOKEN, (byteLimit - now.bytes) / BYTES_PER_CHARACTER));
992
+ const fewest = rates.length > 0 ? Math.min(...rates) : 1 / CHARACTERS_PER_TOKEN;
993
+ return Math.floor(Math.min(tokenLimit - now.tokens, (byteLimit - now.bytes) / BYTES_PER_CHARACTER * fewest));
661
994
  };
662
995
  /**
663
996
  * Makes room: the results of every tool round but the last `keep` are replaced by short
@@ -720,7 +1053,7 @@ async function ask(options, carried, state) {
720
1053
  if (answer.result.already_shown === true) {
721
1054
  const held = canPoint && ((key !== undefined && (inRound.has(key) || (answer.call.name !== TOOL_NAMES.read && shownKeys.has(key))))
722
1055
  || (answer.call.name === TOOL_NAMES.read && (shownReads.get(answer.call.args.document_id) ?? [])
723
- .some((read) => alreadyShown(answer.call, read.answer, read.index < asked && read.question !== question) !== undefined)));
1056
+ .some((read) => pointerTo(answer.call, read.answer, read.index < asked && read.question !== question) !== undefined)));
724
1057
  if (!held) {
725
1058
  touched = true;
726
1059
  now = {
@@ -733,7 +1066,7 @@ async function ask(options, carried, state) {
733
1066
  };
734
1067
  }
735
1068
  }
736
- else if (key !== undefined && alreadyShown(answer.call, answer) !== undefined) {
1069
+ else if (key !== undefined && pointerTo(answer.call, answer) !== undefined) {
737
1070
  // A result in full: what a later pointer may point to.
738
1071
  if (answer.call.name === TOOL_NAMES.read) {
739
1072
  const reads = shownReads.get(answer.call.args.document_id) ?? [];
@@ -770,7 +1103,7 @@ async function ask(options, carried, state) {
770
1103
  * work. A model whose conversation may only grow (Claude) has nothing shortened.
771
1104
  */
772
1105
  const makeRoom = (adapter, sent, error) => {
773
- const refused = error;
1106
+ const refused = modelErrorOf(error) ?? {};
774
1107
  const own = scaleOf(adapter);
775
1108
  meter.overflowed(meter.estimate(sent.messages).tokens, refused.requestedTokens !== undefined ? refused.requestedTokens / own : undefined);
776
1109
  if (refused.limitTokens !== undefined) {
@@ -778,22 +1111,47 @@ async function ask(options, carried, state) {
778
1111
  }
779
1112
  if (!canShrink)
780
1113
  return false;
1114
+ return shortenUntil(() => meter.current(messages).tokens <= tokenLimit);
1115
+ };
1116
+ /**
1117
+ * Shortens old tool results until `fits`: those of every round but the last three, then two,
1118
+ * then one, then all. True when anything was shortened.
1119
+ */
1120
+ const shortenUntil = (fits) => {
781
1121
  let changed = false;
782
1122
  for (const keep of [...ROUNDS_KEPT, 0]) {
783
- if (changed && meter.current(messages).tokens <= tokenLimit)
1123
+ if (changed && fits())
784
1124
  break;
785
1125
  if (shrink(keep))
786
1126
  changed = true;
787
1127
  }
788
1128
  return changed;
789
1129
  };
1130
+ /**
1131
+ * Before the first request of the question: when the stored rounds of earlier questions make it
1132
+ * larger than the room it has in tokens, their results are shortened as they would be after the
1133
+ * provider refused it (`makeRoom`, which counts tokens too), and it is sent shortened, instead of
1134
+ * sent to be refused. The rounds are those of earlier questions: nothing of this question has
1135
+ * been sent, and a stored round has no thinking in it, so this is done for a model whose
1136
+ * conversation may only grow (Claude) too. A question planned again shortens them again, and
1137
+ * does not say so twice: its first try's steps already do.
1138
+ */
1139
+ let firstSent = false;
1140
+ const preflight = () => {
1141
+ if (firstSent)
1142
+ return;
1143
+ firstSent = true;
1144
+ const fits = () => meter.current(messages).tokens <= tokenLimit;
1145
+ if (!fits() && shortenUntil(fits) && !carried?.steps.includes(RESULTS_SHORTENED))
1146
+ step(RESULTS_SHORTENED, "results_shortened");
1147
+ };
790
1148
  /**
791
1149
  * The window to plan the documents for again, in the models' tokens, after the first request was
792
1150
  * refused as too large: the one the provider named, made smaller by how much more than the
793
1151
  * estimate it counted. Without its numbers, seven tenths of the window the budget assumed.
794
1152
  */
795
1153
  const smallerWindow = (adapter, sent, error) => {
796
- const refused = error;
1154
+ const refused = modelErrorOf(error) ?? {};
797
1155
  const estimated = meter.estimate(sent.messages).tokens;
798
1156
  const ratio = refused.requestedTokens !== undefined && estimated > 0 ? refused.requestedTokens / scaleOf(adapter) / estimated : undefined;
799
1157
  const limit = refused.limitTokens;
@@ -820,13 +1178,15 @@ async function ask(options, carried, state) {
820
1178
  * window (`Replan`). `build` makes the request from the conversation as it is then.
821
1179
  */
822
1180
  const send = async (adapter, build, shown, kind) => {
1181
+ preflight();
823
1182
  for (let again = false;; again = true) {
824
1183
  const body = build();
825
1184
  try {
826
1185
  return await request(adapter, body, shown, kind);
827
1186
  }
828
1187
  catch (error) {
829
- if (errorKindOf(error) !== "context_overflow" || signal?.aborted)
1188
+ // By the kind its events report: also for an error of your own adapter with a status and no kind.
1189
+ if (modelErrorOf(error)?.kind !== "context_overflow" || signal?.aborted)
830
1190
  throw error;
831
1191
  if (!again && recoveries < MOST_OVERFLOW_RECOVERIES && makeRoom(adapter, body, error)) {
832
1192
  recoveries++;
@@ -838,7 +1198,7 @@ async function ask(options, carried, state) {
838
1198
  }
839
1199
  if (carried === undefined && callsAnswered === 0 && !text) {
840
1200
  const smaller = smallerWindow(adapter, body, error);
841
- throw new Replan({ usage, steps: [...steps], turns, answered: answeredRequests, nudges, recoveries, contextTokens: smaller.contextTokens, step: smaller.step }, error, result(false));
1201
+ throw new Replan({ usage, steps: [...steps], turns, answered: answeredRequests, nudges, recoveries, contextTokens: smaller.contextTokens, step: smaller.step, documentIds, missing }, error, result(false));
842
1202
  }
843
1203
  throw error;
844
1204
  }
@@ -884,32 +1244,42 @@ async function ask(options, carried, state) {
884
1244
  else
885
1245
  signal?.addEventListener("abort", stopTools, { once: true });
886
1246
  try {
887
- // Tools are needed for a file that is too large to send whole, and for a PDF whose pages can be
888
- // looked at: that one may have its whole text in the prompt and still hide a chart from the model.
889
- const { searchable } = prepared.plan;
890
- const { viewable } = prepared;
891
- if (searchable.length === 0 && viewable.length === 0)
892
- return result(wrote(await send(model, () => ({ system, messages }), true, { role: "answer", purpose: "direct" })));
1247
+ // Nothing for the tools (see `toolable` above): one request, without them.
1248
+ if (searchable.length === 0 && viewable.length === 0 && toolable.length === 0)
1249
+ return answer(wrote(await send(model, () => ({ system, messages }), true, { role: "answer", purpose: "direct" })));
893
1250
  // Reading a whole file in parts is exploring too: the explorer model's work, when there is one.
894
1251
  // Bound to its adapter: a class with a `generateText` method that uses `this` keeps it.
895
1252
  const partReader = options.wholeDocumentAnalysis === false ? undefined : toolModel.generateText?.bind(toolModel);
896
1253
  const generate = partReader && (async (part) => {
897
1254
  let reported = false;
1255
+ // What the request sends, in the reader's tokens: counted for a request whose usage does not
1256
+ // give its input, so that `limits.inputTokens` sees it. Worked out only then.
1257
+ const estimate = () => (estimateTokens(part.system) + estimateTokens(part.prompt)) * scaleOf(toolModel);
898
1258
  const text = await partReader({
899
1259
  ...part,
900
1260
  onUsage: (used) => {
901
1261
  reported = true;
902
- usage.add(toolModel.id, used);
1262
+ usage.add(toolModel.id, used, reportsInput(used) ? undefined : estimate());
903
1263
  part.onUsage?.(used);
904
1264
  },
905
1265
  });
906
1266
  // A part reader that does not report its usage (`onUsage` is optional) still made a request,
907
1267
  // and `limits.requests` counts it.
908
1268
  if (!reported)
909
- usage.add(toolModel.id, undefined);
1269
+ usage.add(toolModel.id, undefined, estimate());
910
1270
  return text;
911
1271
  });
912
- const tools = files.tools(searchable, {
1272
+ // The tables sent whole are read by the tools too. Their question declares exactly the tools it
1273
+ // needs (`questionTools`): search_document, read_document and aggregate_table for them, never
1274
+ // get_document_overview or analyze_whole_document, which refuses a file sent whole if it is
1275
+ // called. With no such table, the tool set of 0.9.
1276
+ const declare = toolable.length > 0
1277
+ ? { declare: questionTools({ searchable, toolable, viewable }, generate !== undefined && searchable.some((meta) => canBeReadWhole(meta, budget))), inline: prepared.plan.inline.map((meta) => meta.id) }
1278
+ : {};
1279
+ const tools = files.tools([...searchable, ...toolable], {
1280
+ // The owner and scope the store holds are checked against the question's own, not against
1281
+ // the metadata handed in.
1282
+ access,
913
1283
  ...(generate ? { generate } : {}),
914
1284
  onProgress: (event) => options.onActivity?.(`${event.message}…`),
915
1285
  signal: halt.signal,
@@ -917,8 +1287,14 @@ async function ask(options, carried, state) {
917
1287
  maxWholeDocumentReads: limits.wholeDocumentReads ?? MAX_WHOLE_DOCUMENT_READS,
918
1288
  ...(options.retry ? { retry: options.retry } : {}),
919
1289
  budget,
1290
+ ...declare,
920
1291
  });
921
1292
  const declarations = tools.declarations;
1293
+ /** The documents a tool call found gone, told once each ("document_gone"). */
1294
+ const gone = new Set();
1295
+ /** The file name of a document of the question, as the plan has it. */
1296
+ const metaOf = (id) => (typeof id === "string" ? [...searchable, ...toolable, ...viewable].find((meta) => meta.id === id) : undefined);
1297
+ const nameOf = (id) => metaOf(id)?.name;
922
1298
  // The requests that use the tools are the chat's own, or an explorer model's: the same
923
1299
  // conversation, and a line that says what its part is.
924
1300
  const toolSystem = explorer ? `${system}\n\n${EXPLORER_INSTRUCTION}` : system;
@@ -929,46 +1305,148 @@ async function ask(options, carried, state) {
929
1305
  activity("searching_instead", `Too large to read at once: ${searchable.map((meta) => meta.name).join(", ")}. Searching instead…`);
930
1306
  const maxTurns = Math.max(1, Math.trunc(limits.toolTurns ?? DEFAULT_TOOL_TURNS));
931
1307
  const maxCalls = Math.max(1, Math.trunc(limits.callsPerTurn ?? DEFAULT_CALLS_PER_TURN));
932
- /** True once the question has used what it may: no more tools run. One request is kept for the answer. */
933
- const spent = () => ((limits.inputTokens !== undefined && usage.totals.inputTokens >= limits.inputTokens)
934
- || (limits.requests !== undefined && usage.totals.requests >= limits.requests - 1));
1308
+ const readsOfEach = limits.wholeDocumentReads ?? MAX_WHOLE_DOCUMENT_READS;
1309
+ // As the tool set reads its own count of reads of each document: whole numbers, none below 0.
1310
+ const readsInAll = Math.max(0, Math.trunc(limits.wholeReadsPerQuestion ?? DEFAULT_WHOLE_READS_PER_QUESTION));
935
1311
  /**
936
- * A whole-file read is many requests at once: one that would pass a ceiling of the question is
937
- * not started. `reserved` is what the reads already let through in this turn will take: they run
938
- * together, and the totals do not show them yet.
1312
+ * The price of a whole-file read of `meta` by the model that explores, in its own tokens and
1313
+ * requests: a read that lists items (`output: "items"`) is its parts alone; any other, its
1314
+ * parts, the merges of their notes and its answer.
939
1315
  */
940
- const tooCostly = (call, reserved) => {
941
- if (call.name !== TOOL_NAMES.analyze)
942
- return {};
943
- const meta = searchable.find((document) => document.id === call.args.document_id);
944
- if (!meta)
945
- return {};
946
- // A read of a document read whole as often as it may be is refused by the tool, at no cost: it
947
- // takes nothing from the reads of other documents.
948
- const before = evidence.filter((shown) => shown.whole && shown.documentId === meta.id).length + (reserved.reads.get(meta.id) ?? 0);
949
- if (before >= (limits.wholeDocumentReads ?? MAX_WHOLE_DOCUMENT_READS))
950
- return {};
951
- // The parts are read by the model that explores, in its own tokens.
952
- const tokens = Math.ceil(meta.estimatedTokens * scaleOf(toolModel));
953
- // The parts, a merge of their notes, the answer of the read, and the answer of the question.
954
- const requests = estimateParts(meta, budget) + 3;
955
- if (limits.inputTokens !== undefined) {
956
- const left = Math.max(0, limits.inputTokens - usage.totals.inputTokens - reserved.inputTokens);
1316
+ const priceOf = (meta, output = "answer") => wholeReadCost(meta, budget, scaleOf(toolModel), output);
1317
+ /**
1318
+ * The ceiling on the input tokens of the question: `limits.inputTokens`, or by default the larger
1319
+ * of `DEFAULT_INPUT_TOKENS` and `toolTurns` times the first request, plus room for the
1320
+ * whole-file reads the question may make: as many as `wholeReadsPerQuestion` and the documents
1321
+ * that can be read whole allow, each at the price of the dearest of them.
1322
+ */
1323
+ const ceiling = (() => {
1324
+ if (limits.inputTokens !== undefined)
1325
+ return limits.inputTokens;
1326
+ const first = meter.current(viewFor(toolModel)).tokens * scaleOf(toolModel);
1327
+ const readable = tools.has(TOOL_NAMES.analyze) && readsOfEach > 0 ? searchable.filter((meta) => canBeReadWhole(meta, budget)) : [];
1328
+ const reads = Math.max(0, Math.min(readsInAll, readable.length * Math.trunc(readsOfEach)));
1329
+ const prices = readable.map((meta) => priceOf(meta).inputTokens).filter((price) => Number.isFinite(price));
1330
+ const allowance = prices.length > 0 ? (Number.isFinite(reads) ? reads : readable.length) * Math.max(...prices) : 0;
1331
+ return Math.max(DEFAULT_INPUT_TOKENS, maxTurns * first) + allowance;
1332
+ })();
1333
+ /** The input tokens the question has used: those the providers reported, and the estimates of those they did not. */
1334
+ const spentTokens = () => usage.totals.inputTokens + (usage.totals.estimatedInputTokens ?? 0);
1335
+ /**
1336
+ * True once the question has used what it may: no more tools run. One request is kept for the
1337
+ * answer. The ceiling of input tokens looks ahead: what was spent, the tool request about to be
1338
+ * sent and the answer's request after it, each as the meter counts it now, must stay within it.
1339
+ */
1340
+ const spent = () => {
1341
+ if (limits.requests !== undefined && usage.totals.requests >= limits.requests - 1)
1342
+ return true;
1343
+ if (!(ceiling < Number.POSITIVE_INFINITY))
1344
+ return false;
1345
+ const next = meter.current(viewFor(toolModel)).tokens * scaleOf(toolModel);
1346
+ const closing = meter.current(viewFor(model)).tokens * scaleOf(model);
1347
+ return spentTokens() + next + closing > ceiling;
1348
+ };
1349
+ /**
1350
+ * The whole-file reads of the question that sent requests, by document: those that returned, and
1351
+ * those that failed after they sent them. Counted from what the tool returned, before
1352
+ * `onToolResult`: a read whose answer the hook replaced or rejected still made its requests.
1353
+ */
1354
+ const readsSent = new Map();
1355
+ const readsMade = (documentId) => {
1356
+ if (documentId !== undefined)
1357
+ return readsSent.get(documentId) ?? 0;
1358
+ let made = 0;
1359
+ for (const reads of readsSent.values())
1360
+ made += reads;
1361
+ return made;
1362
+ };
1363
+ /** True for the output of a whole-file read that sent its parts: its answer, or the error of a read that could read none of them. */
1364
+ const sentParts = (call, output) => call.name === TOOL_NAMES.analyze
1365
+ && (evidenceOf(call, output)?.whole === true || (typeof output.error === "string" && output.error.startsWith(NOTHING_READ)));
1366
+ /**
1367
+ * True when no whole-file read of `meta` is left, past those of `reserved`: the tool refuses one
1368
+ * itself, at no cost, with its own reason (such as a read that failed earlier). The tool set says
1369
+ * how many reads are left; one of your own that does not is read by what the reads of this
1370
+ * question returned.
1371
+ */
1372
+ const noReadLeft = (meta, reserved) => {
1373
+ const inTurn = reserved.reads.get(meta.id) ?? 0;
1374
+ const left = tools.wholeReadsLeft?.(meta.id);
1375
+ return typeof left === "number" ? left - inTurn <= 0 : readsMade(meta.id) + inTurn >= readsOfEach;
1376
+ };
1377
+ /**
1378
+ * What a whole-file read of `meta` takes, and why the question would not start it now, past the
1379
+ * reads of `reserved`: its whole reads made, or a ceiling it would pass. Not the tool's own
1380
+ * reasons (`noReadLeft`). `output` is the read's own: a read that lists items ("items") is
1381
+ * priced at its parts alone, any other ("answer") at its parts, merges and answer.
1382
+ */
1383
+ const readNeeds = (meta, reserved, output) => {
1384
+ // The parts are read by the model that explores, in its own tokens: their lines numbered, the
1385
+ // prompts, and the merges of their notes (`wholeReadCost`). A read that lists items sends its
1386
+ // parts alone, with the rules of a list.
1387
+ const items = output === "items";
1388
+ const price = priceOf(meta, output).inputTokens;
1389
+ const tokens = Number.isFinite(price) ? price : Math.ceil(meta.estimatedTokens * scaleOf(toolModel));
1390
+ // The parts, a merge of their notes, the answer of the read, and the answer of the question;
1391
+ // for a list of items, the parts and the answer of the question.
1392
+ const requests = estimateParts(meta, budget) + (items ? 1 : 3);
1393
+ const allReserved = [...reserved.reads.values()].reduce((sum, reads) => sum + reads, 0);
1394
+ if (readsMade() + allReserved >= readsInAll) {
1395
+ return { tokens, requests, refusal: `Not run: one question makes at most ${count(readsInAll)} whole-file ${readsInAll === 1 ? "read" : "reads"}, and this one has made ${readsInAll === 1 ? "it" : "them"}. Use search_document and read_document on ${meta.name}.` };
1396
+ }
1397
+ if (ceiling < Number.POSITIVE_INFINITY) {
1398
+ const left = Math.max(0, ceiling - spentTokens() - reserved.inputTokens);
957
1399
  if (tokens > left)
958
- 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.` };
1400
+ return { tokens, requests, refusal: `Not run: reading all of ${meta.name} takes about ${count(tokens)} input tokens, and ${count(left)} ${count(left) === "1" ? "is" : "are"} left of the ${count(ceiling)} this question may use. Use search_document and read_document.` };
959
1401
  }
960
1402
  if (limits.requests !== undefined) {
961
1403
  const left = Math.max(0, limits.requests - usage.totals.requests - reserved.requests);
962
1404
  if (requests > left)
963
- 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.` };
1405
+ return { tokens, requests, refusal: `Not run: reading all of ${meta.name} takes about ${count(requests)} model requests, and ${count(left)} ${count(left) === "1" ? "is" : "are"} left of the ${count(limits.requests)} this question may make. Use search_document and read_document.` };
964
1406
  }
1407
+ return { tokens, requests };
1408
+ };
1409
+ /**
1410
+ * A whole-file read is many requests at once: one that would pass a ceiling of the question is
1411
+ * not started. `reserved` is what the reads already let through in this turn will take.
1412
+ */
1413
+ const tooCostly = (call, reserved) => {
1414
+ if (call.name !== TOOL_NAMES.analyze)
1415
+ return {};
1416
+ const meta = searchable.find((document) => document.id === call.args.document_id);
1417
+ // A read of a document read whole as often as it may be takes nothing from the reads of other documents.
1418
+ if (!meta || noReadLeft(meta, reserved))
1419
+ return {};
1420
+ const { refusal, tokens, requests } = readNeeds(meta, reserved, call.args.output === "items" ? "items" : "answer");
1421
+ if (refusal)
1422
+ return { refusal };
965
1423
  reserved.inputTokens += tokens;
966
1424
  // The answer of the question is one request, whatever number of reads come before it.
967
1425
  reserved.requests += requests - 1;
968
1426
  reserved.reads.set(meta.id, (reserved.reads.get(meta.id) ?? 0) + 1);
969
- // The read's own requests: its parts, a merge of their notes, and its answer.
1427
+ // The read's own requests: its parts, a merge of their notes, and its answer; or its parts.
970
1428
  return { own: requests - 1 };
971
1429
  };
1430
+ /**
1431
+ * The requests a whole-file read of the document of a `read_document` call may make
1432
+ * (`ToolCallLimits.maxRequests`), judged as on the next turn, the first the model can call it on:
1433
+ * with the reads of this turn reserved, and that turn's request, of the conversation with
1434
+ * `pending` at least (its results are not in it yet). 0 when the question would not start one
1435
+ * then (`noReadLeft`, `readNeeds`), so that a read cut short of its range does not point at it
1436
+ * (`whole_file`); what is left of `limits.requests` with one kept for the answer, when that is
1437
+ * set; undefined otherwise.
1438
+ */
1439
+ const wholeReadRequests = (call, reserved, pending) => {
1440
+ const meta = searchable.find((document) => document.id === call.args.document_id);
1441
+ if (!meta)
1442
+ return undefined;
1443
+ const nextTurn = meter.current(viewFor(toolModel, [...messages, pending])).tokens * scaleOf(toolModel);
1444
+ const later = { ...reserved, inputTokens: reserved.inputTokens + nextTurn, requests: reserved.requests + 1 };
1445
+ // The hint points at a read that gives an answer, the dearer of the two kinds.
1446
+ if (noReadLeft(meta, later) || readNeeds(meta, later, "answer").refusal !== undefined)
1447
+ return 0;
1448
+ return limits.requests === undefined ? undefined : Math.max(0, limits.requests - usage.totals.requests - 1 - later.requests);
1449
+ };
972
1450
  /**
973
1451
  * A pointer for a call whose result is already in the conversation, in full: an earlier result
974
1452
  * (of this question or of one before it) holds what this one would return. The files do not
@@ -983,7 +1461,7 @@ async function ask(options, carried, state) {
983
1461
  continue;
984
1462
  // The rounds before `asked` are those of earlier questions, which an older version may have written.
985
1463
  for (const answer of message.answers) {
986
- const pointer = alreadyShown(call, answer, at < asked);
1464
+ const pointer = pointerTo(call, answer, at < asked);
987
1465
  if (pointer)
988
1466
  return pointer;
989
1467
  }
@@ -1000,6 +1478,19 @@ async function ask(options, carried, state) {
1000
1478
  const toolRole = explorer ? "explorer" : "tools";
1001
1479
  /** 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. */
1002
1480
  const labelOf = (call) => stepLine(tools.has(call.name) ? tools.describe(call.name, call.args) : `Call ${unknownToolName(call.name)}`);
1481
+ // The tools are there only for tables sent whole (`inlineTables`): without them, the question
1482
+ // would be the one request of 0.9 (and of "text"). It is still that, without the tools, the
1483
+ // line that says to count with them, or a notice, when not one tool turn fits: a ceiling or a
1484
+ // count of requests sized for that one request, or `toolTurns: 1`.
1485
+ const tablesOnly = !explorer && searchable.length === 0 && viewable.length === 0;
1486
+ if (tablesOnly && (1 + (carried?.answered ?? 0) >= maxTurns || spent())) {
1487
+ const plainLine = inlineInstruction({ plan: prepared.plan }, numbered);
1488
+ const plain = [options.system?.trim(), prepared.instruction, plainLine, missingLine].filter(Boolean).join("\n\n");
1489
+ // Its estimate, for a provider that reports no usage: no declarations, its own line.
1490
+ meter.fixed.tokens += -estimateTokens(sentTools) - (inlineLine ? estimateTokens(inlineLine) : 0) + (plainLine ? estimateTokens(plainLine) : 0);
1491
+ meter.fixed.bytes += -Buffer.byteLength(sentTools) - (inlineLine ? jsonBytes(inlineLine) : 0) + (plainLine ? jsonBytes(plainLine) : 0);
1492
+ return answer(wrote(await send(model, () => ({ system: plain, messages }), true, { role: "answer", purpose: "direct" })));
1493
+ }
1003
1494
  for (let round = 1 + (carried?.answered ?? 0); round < maxTurns && !outOfRoom; round++) {
1004
1495
  if (spent()) {
1005
1496
  budgetReached();
@@ -1013,7 +1504,9 @@ async function ask(options, carried, state) {
1013
1504
  // It is a request of the chat like any other: it takes a tool turn, and the last turn is still the answer's.
1014
1505
  if (reply.calls.length === 0 && nudges < MOST_NUDGES && round + 1 < maxTurns && !reply.blockReason && !spent()) {
1015
1506
  const malformed = reply.finish === "malformed_call";
1016
- const empty = !reply.text.trim() && callsAnswered === 0 && reply.finish !== "cut" && reply.finish !== "filtered";
1507
+ // Not a reply that a filter, the output limit or another reason that asking again does not
1508
+ // mend ended ("other": Gemini's OTHER, LANGUAGE): it would only end the same way.
1509
+ const empty = !reply.text.trim() && callsAnswered === 0 && reply.finish !== "cut" && reply.finish !== "filtered" && reply.finish !== "other";
1017
1510
  if (malformed || empty) {
1018
1511
  nudges++;
1019
1512
  round++;
@@ -1025,8 +1518,16 @@ async function ask(options, carried, state) {
1025
1518
  }
1026
1519
  if (reply.calls.length === 0) {
1027
1520
  // Text from this turn is the answer. A remark made earlier, before a tool call, is not.
1028
- // Neither is anything an explorer model writes: the answer is asked for below.
1029
- answered = wrote(reply) && !explorer;
1521
+ // Neither is anything an explorer model writes: the answer is asked for below. Nor the
1522
+ // remark of a turn whose tool call could not be read ("Let me look at the errors."), on
1523
+ // the last tool turn or after its nudge: the answer is asked for below.
1524
+ answered = wrote(reply) && !explorer && reply.finish !== "malformed_call";
1525
+ // Over tables sent whole alone, a reply that a filter or another reason that asking again
1526
+ // does not mend ended ("other"), or one cut at the output limit before any text, ends the
1527
+ // question, as it ends the direct request of 0.9: the request for the answer would send
1528
+ // the whole tables again, only to end the same way.
1529
+ if (tablesOnly && !answered && (reply.finish === "filtered" || reply.finish === "other" || reply.finish === "cut"))
1530
+ return answer(false);
1030
1531
  break;
1031
1532
  }
1032
1533
  const pending = { role: "tools", calls: reply.calls, answers: [], ...(reply.raw !== undefined ? { raw: reply.raw } : {}) };
@@ -1044,6 +1545,11 @@ async function ask(options, carried, state) {
1044
1545
  // A call that did not arrive whole is not run: the model is told, and can send it again.
1045
1546
  if (call.problem)
1046
1547
  return { call, label, refusal: call.problem };
1548
+ // Nor a call of a tool the question does not have: it is told which there are, and its
1549
+ // answer takes no room (a turn of unknown calls made room for each of them, at the cap of
1550
+ // a result, and shortened the results of earlier turns for nothing).
1551
+ if (!tools.has(call.name))
1552
+ return { call, label, refusal: unknownTool(call.name, declarations.map((declaration) => declaration.name)) };
1047
1553
  // A look at pages returns a file and a few words: the file has its own room, worked out when it runs.
1048
1554
  if (call.name === TOOL_NAMES.view)
1049
1555
  return { call, label };
@@ -1071,22 +1577,34 @@ async function ask(options, carried, state) {
1071
1577
  for (const plan of reads)
1072
1578
  plan.limits = { ...plan.limits, maxRequests: plan.own + Math.floor(slack / reads.length) };
1073
1579
  }
1580
+ // A read of lines points at a whole read of its file only when the question would start one
1581
+ // on the next turn, past the whole reads of this turn: each is told the requests one may make.
1582
+ for (const plan of planned) {
1583
+ if (plan.refusal || plan.call.name !== TOOL_NAMES.read)
1584
+ continue;
1585
+ const most = wholeReadRequests(plan.call, reserved, pending);
1586
+ if (most !== undefined)
1587
+ plan.limits = { ...plan.limits, maxRequests: most };
1588
+ }
1074
1589
  // The calls that return text, and the most they may return: a call that is refused, or
1075
1590
  // answered with a pointer to what is already shown, needs no room.
1076
1591
  const sized = planned.filter((plan) => !plan.refusal && !plan.pointer && plan.call.name !== TOOL_NAMES.view);
1077
- const needed = sized.reduce((sum, plan) => sum + most(plan.call), 0);
1078
- let left = room(pending);
1592
+ // The room is in tokens, and each result takes those of its document's characters.
1593
+ const rateOf = (call) => 1 / charactersPerToken(metaOf(call.args.document_id));
1594
+ const sizedRates = sized.map((plan) => rateOf(plan.call));
1595
+ const needed = sized.reduce((sum, plan, index) => sum + most(plan.call) * sizedRates[index], 0);
1596
+ let left = room(pending, sizedRates);
1079
1597
  let dropped = false;
1080
1598
  for (const keep of canShrink ? ROUNDS_KEPT : []) {
1081
1599
  if (left >= needed)
1082
1600
  break;
1083
1601
  if (shrink(keep)) {
1084
1602
  dropped = true;
1085
- left = room(pending);
1603
+ left = room(pending, sizedRates);
1086
1604
  }
1087
1605
  }
1088
1606
  if (dropped) {
1089
- step("Older tool results were shortened to make room in the request", "results_shortened");
1607
+ step(RESULTS_SHORTENED, "results_shortened");
1090
1608
  // A result that was shortened is no longer shown in full: a call that pointed to it is run after all.
1091
1609
  for (const plan of planned) {
1092
1610
  if (!plan.earlier)
@@ -1105,10 +1623,15 @@ async function ask(options, carried, state) {
1105
1623
  // The room is shared by those calls. A result is most often far smaller than its cap, so a call
1106
1624
  // that was given its whole cap first could leave none for the next ones, and a turn of small
1107
1625
  // searches ended the question.
1108
- const shares = shareRoom(runsNow.map((plan) => most(plan.call)), left);
1626
+ const runRates = runsNow.map((plan) => rateOf(plan.call));
1627
+ const shares = shareRoom(runsNow.map((plan) => most(plan.call)), left, runRates);
1628
+ /** The tokens of room each call that runs was given, by its index in the turn. */
1629
+ const given = new Map();
1109
1630
  runsNow.forEach((plan, index) => {
1110
1631
  const share = shares[index];
1111
1632
  const cap = most(plan.call);
1633
+ if (share !== undefined)
1634
+ given.set(planned.indexOf(plan), share * runRates[index]);
1112
1635
  if (share === undefined) {
1113
1636
  if (!outOfRoom)
1114
1637
  notice("no_room", "There is no room left in this conversation for another tool result.");
@@ -1246,6 +1769,8 @@ async function ask(options, carried, state) {
1246
1769
  end,
1247
1770
  };
1248
1771
  };
1772
+ /** A look of this turn waited `pageLookWaitMs` and was told the server is busy: the others do not wait (`maxWaitMs`). */
1773
+ let pagesBusy = false;
1249
1774
  /**
1250
1775
  * The listeners of one call: its progress goes to `onActivity` as before (in place of the
1251
1776
  * tool set's shared listener) and is told apart by call in the events, with its requests.
@@ -1257,6 +1782,17 @@ async function ask(options, carried, state) {
1257
1782
  events.emit({ type: "tool.progress", callId: callIds[index], stage: event.kind, done: event.done, total: event.total, message: event.message });
1258
1783
  }),
1259
1784
  ...(events.active ? { onRequest: (start) => readerRequest(index, start) } : {}),
1785
+ // Notices of the question, not steps: the call's own step says what the model was told.
1786
+ onDocumentGone: (id) => tell(() => {
1787
+ if (gone.has(id))
1788
+ return;
1789
+ gone.add(id);
1790
+ notice("document_gone", `${nameOf(id) ?? "A file"} is no longer available on the server.`, [id]);
1791
+ }),
1792
+ onPagesBusy: (id) => {
1793
+ pagesBusy = true;
1794
+ tell(() => notice("page_looks_busy", `The pages of ${nameOf(id) ?? "a file"} were not looked at: the server was busy with other looks at pages.`, [id]));
1795
+ },
1260
1796
  });
1261
1797
  // The calls of a turn run together, a few at a time. Looks at pages take their turns, one
1262
1798
  // after another: each is given the room the ones before it left.
@@ -1281,7 +1817,12 @@ async function ask(options, carried, state) {
1281
1817
  requestBytes = toolModel.requestBytes?.(waiting) ?? meter.estimate(waiting.messages).bytes;
1282
1818
  }
1283
1819
  // Base64 turns three bytes into four characters.
1284
- const output = await tools.executeWithFiles(call.name, call.args, { maxFileBytes: Math.floor((maxRequestBytes - bytesKeptFree - requestBytes) * 3 / 4), maxPages: pagesLeft });
1820
+ const output = await until(tools.executeWithFiles(call.name, call.args, {
1821
+ maxFileBytes: Math.floor((maxRequestBytes - bytesKeptFree - requestBytes) * 3 / 4),
1822
+ maxPages: pagesLeft,
1823
+ // A wait that ends busy comes once in a tool turn: after a busy look, the others run only when a turn is free now.
1824
+ ...(pagesBusy ? { maxWaitMs: 0 } : {}),
1825
+ }, hooksFor(index)), halt.signal);
1285
1826
  for (const file of output.files)
1286
1827
  requestBytes += Math.ceil(file.bytes.length / 3) * 4 + 512;
1287
1828
  if (output.files.length > 0)
@@ -1297,7 +1838,9 @@ async function ask(options, carried, state) {
1297
1838
  halt.signal.throwIfAborted();
1298
1839
  options.onActivity?.(`${label}…`);
1299
1840
  startTool(index, call, label);
1300
- return await tools.executeWithFiles(call.name, call.args, callLimits, hooksFor(index));
1841
+ // The question stops when its signal aborts, whether the tool set does or not: a store
1842
+ // call that hangs inside a tool of any `LargeFiles` must not hold it.
1843
+ return await until(tools.executeWithFiles(call.name, call.args, callLimits, hooksFor(index)), halt.signal);
1301
1844
  }
1302
1845
  finally {
1303
1846
  release();
@@ -1314,6 +1857,48 @@ async function ask(options, carried, state) {
1314
1857
  output.catch(() => undefined);
1315
1858
  outputs.push(output);
1316
1859
  }
1860
+ const hook = options.onToolResult;
1861
+ const judgedOutputs = [];
1862
+ for (const [index, { call, refusal, pointer, twinOf }] of planned.entries()) {
1863
+ const raw = outputs[index];
1864
+ let judging;
1865
+ if (hook && pointer && twinOf !== undefined) {
1866
+ judging = Promise.all([raw, judgedOutputs[twinOf]]).then(([own, first]) => (first.judged
1867
+ ? { raw: own, output: { result: first.output.result, files: [] }, judged: first.judged, copied: true }
1868
+ : { raw: own, output: own }));
1869
+ }
1870
+ else if (hook && !refusal && !pointer) {
1871
+ judging = raw.then(async (own) => {
1872
+ const context = {
1873
+ call,
1874
+ result: own.result,
1875
+ ...(typeof call.args.document_id === "string" ? { documentId: call.args.document_id } : {}),
1876
+ ...(options.owner !== undefined ? { owner: options.owner } : {}),
1877
+ ...(options.scope !== undefined ? { scope: options.scope } : {}),
1878
+ signal: halt.signal,
1879
+ };
1880
+ let verdict;
1881
+ try {
1882
+ // A hook that does not look at the signal does not hold the question once it is stopped.
1883
+ verdict = checkedVerdict(await until(Promise.resolve().then(() => hook(context)), halt.signal));
1884
+ }
1885
+ catch (error) {
1886
+ halt.abort(error);
1887
+ throw error;
1888
+ }
1889
+ if (verdict && "result" in verdict)
1890
+ return { raw: own, output: { ...own, result: { ...verdict.result, redacted: true } }, judged: "redacted" };
1891
+ if (verdict)
1892
+ return { raw: own, output: { result: { error: verdict.reject }, files: [] }, judged: "refused" };
1893
+ return { raw: own, output: own };
1894
+ });
1895
+ }
1896
+ else {
1897
+ judging = raw.then((own) => ({ raw: own, output: own }));
1898
+ }
1899
+ judging.catch(() => undefined);
1900
+ judgedOutputs.push(judging);
1901
+ }
1317
1902
  /**
1318
1903
  * The room of each whole-file read of the turn: what the other results left, shared among the
1319
1904
  * reads, the smaller answers first. Worked out when the first of them is reached, by which time
@@ -1321,7 +1906,7 @@ async function ask(options, carried, state) {
1321
1906
  */
1322
1907
  let lateRoom;
1323
1908
  const roomOfReads = async () => {
1324
- const sizes = await Promise.all(outputs.map(async (output) => JSON.stringify((await output).result).length));
1909
+ const sizes = await Promise.all(judgedOutputs.map(async (judging) => resultTokens((await judging).output.result)));
1325
1910
  const reads = planned.flatMap((plan, index) => (plan.late ? [index] : []));
1326
1911
  let free = left - sizes.reduce((sum, size, index) => sum + (planned[index].late ? 0 : size), 0);
1327
1912
  const shares = new Map();
@@ -1332,19 +1917,53 @@ async function ask(options, carried, state) {
1332
1917
  });
1333
1918
  return shares;
1334
1919
  };
1920
+ /**
1921
+ * The tokens the results of this turn took so far, of the calls that were given room and are
1922
+ * not whole-file reads (those are fitted to what the others left, above), and of those the
1923
+ * hook replaced. A result is cut when it would take more than the room leaves it once the
1924
+ * calls after it, and the reads, have their shares: the room shared by characters is a
1925
+ * guess, a tool set of your own may not keep to `maxResultCharacters`, and a hook may return
1926
+ * more than the tool did.
1927
+ */
1928
+ let took = 0;
1929
+ const roomFor = (index) => {
1930
+ let others = 0;
1931
+ for (const [other, tokens] of given)
1932
+ if (other > index || planned[other].late)
1933
+ others += tokens;
1934
+ return left - took - others;
1935
+ };
1335
1936
  // The answers in call order. Each call's `tool.end` goes out here, in the same order.
1336
1937
  for (const [index, { call, label, late, refusal, pointer }] of planned.entries()) {
1337
- let output = await outputs[index];
1938
+ const { raw, output: judgedOutput, judged, copied } = await judgedOutputs[index];
1338
1939
  if (listenerError)
1339
1940
  throw listenerError.error;
1941
+ // A hook of a later call failed: nothing more of the turn reaches the model.
1942
+ if (halt.signal.aborted)
1943
+ throw halt.signal.reason;
1340
1944
  callsAnswered++;
1945
+ // A whole-file read that sent its parts counts against `wholeReadsPerQuestion`, whatever the hook made of its answer.
1946
+ if (!refusal && !pointer && sentParts(call, raw.result)) {
1947
+ const id = String(call.args.document_id);
1948
+ readsSent.set(id, (readsSent.get(id) ?? 0) + 1);
1949
+ }
1950
+ let output = judgedOutput;
1341
1951
  if (late) {
1342
1952
  lateRoom ??= await roomOfReads();
1343
1953
  const share = lateRoom.get(index);
1344
- if (JSON.stringify(output.result).length > share)
1345
- output = { ...output, result: fitAnswer(output.result, Math.max(LEAST_RESULT_CHARACTERS, share)) };
1954
+ if (resultTokens(output.result) > share)
1955
+ output = { ...output, result: cutToTokens(output.result, share) };
1346
1956
  }
1347
- if (pointer) {
1957
+ else if (given.has(index) || judged) {
1958
+ const fits = roomFor(index);
1959
+ if (resultTokens(output.result) > fits)
1960
+ output = { ...output, result: cutToTokens(output.result, fits) };
1961
+ took += resultTokens(output.result);
1962
+ }
1963
+ // A cut replacement is still a replacement.
1964
+ if (judged === "redacted" && output.result.redacted !== true)
1965
+ output = { ...output, result: { ...output.result, redacted: true } };
1966
+ if (pointer && !copied) {
1348
1967
  const line = step(`${label} — already shown above`);
1349
1968
  const sent = { ...output.result, tool_turns_left: turnsLeft };
1350
1969
  answers.push({ call, result: sent, files: [] });
@@ -1352,14 +1971,16 @@ async function ask(options, carried, state) {
1352
1971
  continue;
1353
1972
  }
1354
1973
  // Two searches in a row that failed in the same mode: the second says to try another way.
1355
- if (!refusal) {
1974
+ // Read from what the tool returned; the hint goes only to a result the hook kept.
1975
+ if (!refusal && !copied) {
1976
+ const own = judged ? raw.result : output.result;
1356
1977
  const kind = failureKind(call);
1357
1978
  if (kind === undefined) {
1358
1979
  failing = undefined;
1359
1980
  }
1360
- else if (typeof output.result.error === "string") {
1981
+ else if (typeof own.error === "string") {
1361
1982
  failing = failing?.kind === kind ? { kind, count: failing.count + 1 } : { kind, count: 1 };
1362
- if (failing.count >= 2)
1983
+ if (failing.count >= 2 && !judged)
1363
1984
  output = { ...output, result: { ...output.result, error: `${output.result.error} ${repeatedFailureHint(call)}` } };
1364
1985
  }
1365
1986
  else {
@@ -1367,12 +1988,13 @@ async function ask(options, carried, state) {
1367
1988
  }
1368
1989
  }
1369
1990
  const line = step(`${label}${toolResultSummary(label, output.result)}`);
1370
- const shown = evidenceOf(call, output.result);
1991
+ // A copy of the first call's verdict shows nothing that the first did not.
1992
+ const shown = copied ? undefined : evidenceOf(call, output.result);
1371
1993
  if (shown)
1372
1994
  evidence.push({ ...shown, callId: callIds[index] });
1373
1995
  const sent = { ...output.result, tool_turns_left: turnsLeft };
1374
1996
  answers.push({ call, result: sent, files: output.files });
1375
- const outcome = call.problem ? "error" : refusal ? "refused" : typeof output.result.error === "string" ? "error" : "ok";
1997
+ const outcome = judged ?? (call.problem ? "error" : refusal ? "refused" : typeof output.result.error === "string" ? "error" : "ok");
1376
1998
  endTool(index, outcome, sent, line, shown);
1377
1999
  }
1378
2000
  // A listener of a read that went on after its call returned (its progress).
@@ -1407,7 +2029,12 @@ async function ask(options, carried, state) {
1407
2029
  // With an explorer model this request is always made: it is the one the answering model gets.
1408
2030
  if (!answered && !blockReason) {
1409
2031
  activity("writing_answer", "Writing the answer…");
1410
- let closing = searchable.length > 0 ? FINAL_ANSWER_REQUEST : FINAL_ANSWER_AFTER_PAGES;
2032
+ // With view_pages alone, the files are in the prompt and the pages were looked at. With the
2033
+ // text tools, the answer comes from what they returned, and from the files sent whole too when
2034
+ // their lines can be cited or their tables were counted: a model told "only what the tools
2035
+ // returned" said that a fact of a file shown in full was not there.
2036
+ const fromFiles = prepared.plan.inline.length > 0 && (numbered || toolable.length > 0);
2037
+ let closing = searchable.length === 0 && toolable.length === 0 ? FINAL_ANSWER_AFTER_PAGES : fromFiles ? FINAL_ANSWER_WITH_FILES : FINAL_ANSWER_REQUEST;
1411
2038
  // No tool ran (the explorer needed none, the first reply was empty, or no turn was left for
1412
2039
  // tools): there is no tool result to answer from. The answering model gets the explorer's
1413
2040
  // calls and what they returned, and nothing else of it.
@@ -1422,14 +2049,17 @@ async function ask(options, carried, state) {
1422
2049
  let reply = await send(model, answerRequest(), true, { role: "answer", purpose: "closing" });
1423
2050
  // A reply with no text (empty, or a tool call the model was told not to make, or one that
1424
2051
  // could not be read) is asked for once more, with a note that is not kept: otherwise the
1425
- // question ends with nothing to show. Not after a refusal or a filter, which would come again,
1426
- // nor a reply cut off at the output limit with nothing in it, nor once a ceiling of `limits`
1427
- // is reached. It is one of the second tries of the question, and may be one request past
1428
- // `limits.toolTurns`, which counts the answer's first request.
2052
+ // question ends with nothing to show. Not after a refusal, a filter or another reason that
2053
+ // asking again does not mend ("other"), which would come again, nor a reply cut off at the
2054
+ // output limit with nothing in it, nor when it would pass a ceiling of the question: the
2055
+ // ceiling of input tokens looks ahead, as before each tool request, by what was spent and
2056
+ // what this request takes, as the meter counts it now. It is one of the second tries of the
2057
+ // question, and may be one request past `limits.toolTurns`, which counts the answer's first
2058
+ // request.
1429
2059
  const calledInstead = reply.calls.length > 0 || reply.finish === "malformed_call";
1430
- const ceilingReached = (limits.inputTokens !== undefined && usage.totals.inputTokens >= limits.inputTokens)
1431
- || (limits.requests !== undefined && usage.totals.requests >= limits.requests);
1432
- if (!wrote(reply) && !reply.blockReason && reply.finish !== "filtered" && (calledInstead || reply.finish !== "cut") && nudges < MOST_NUDGES) {
2060
+ const again = ceiling < Number.POSITIVE_INFINITY ? meter.current(viewFor(model)).tokens * scaleOf(model) : 0;
2061
+ const ceilingReached = spentTokens() + again > ceiling || (limits.requests !== undefined && usage.totals.requests >= limits.requests);
2062
+ if (!wrote(reply) && !reply.blockReason && reply.finish !== "filtered" && reply.finish !== "other" && (calledInstead || reply.finish !== "cut") && nudges < MOST_NUDGES) {
1433
2063
  if (ceilingReached) {
1434
2064
  budgetReached();
1435
2065
  }
@@ -1441,7 +2071,7 @@ async function ask(options, carried, state) {
1441
2071
  }
1442
2072
  answered = wrote(reply);
1443
2073
  }
1444
- return result(answered);
2074
+ return answer(answered);
1445
2075
  }
1446
2076
  catch (error) {
1447
2077
  // What the question found and paid for until it failed, for the application to keep. The usage is