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/src/ask.ts CHANGED
@@ -1,6 +1,7 @@
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, type AskEvent, type DocumentRef, type EventResult, type EventStream, type NoticeCode, type RequestPurpose, type RequestRole, type ToolOutcome } from "./events.js";
4
+ import { checkCitations, type CitationCheck } from "./citations.js";
4
5
  import { evidenceOf, stubResult, type Evidence } from "./evidence.js";
5
6
  import { isCutReply, until } from "./http.js";
6
7
  import type { LargeFiles } from "./library.js";
@@ -9,7 +10,10 @@ import {
9
10
  DocumentsNotFoundError,
10
11
  errorKindOf,
11
12
  laterResult,
13
+ modelErrorOf,
12
14
  rateAllowanceOf,
15
+ reportsInput,
16
+ TOOL_TURN_VERSION,
13
17
  UsageMeter,
14
18
  type ChatMessage,
15
19
  type ModelAdapter,
@@ -23,7 +27,9 @@ import {
23
27
  type ToolTurn,
24
28
  type UsageTotals,
25
29
  } from "./model.js";
26
- import { estimateParts, REQUEST_BYTES_MARGIN } from "./plan.js";
30
+ import { DocumentStoreError } from "./errors.js";
31
+ import { canBeReadWhole, estimateParts, inlineInstruction, questionTools, REQUEST_BYTES_MARGIN } from "./plan.js";
32
+ import { preparedHere } from "./prepare.js";
27
33
  import { statusOf, withRetry, type RetryNotice, type RetryOptions } from "./retry.js";
28
34
  import { estimateTokens, jsonBytes, wellFormedJson } from "./text.js";
29
35
  import {
@@ -39,10 +45,17 @@ import {
39
45
  toolResultSummary,
40
46
  unknownToolName,
41
47
  } from "./tools.js";
42
- import type { Budget, DocumentMeta, DocumentPlan, GenerateText, ToolCallHooks, ToolCallLimits, ToolOutput, ToolRequestEnd, ToolRequestHandle, ToolRequestStart, ToolResult } from "./types.js";
48
+ import type { Budget, DocumentFormat, DocumentMeta, DocumentPlan, DocumentScope, GenerateText, PreparedContext, ToolCallHooks, ToolCallLimits, ToolOutput, ToolRequestEnd, ToolRequestHandle, ToolRequestStart, ToolResult } from "./types.js";
49
+ import { wholeReadCost } from "./whole-cost.js";
43
50
 
44
51
  /** Sent (invisibly to the user) when the model must stop using tools and answer. */
45
52
  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.";
53
+ /**
54
+ * The same, when files were also sent whole and the tools can read them or their lines are
55
+ * numbered (`inlineTables`, `numberInline`): what they say is part of the answer too, not only what
56
+ * the tools returned. New in 0.10.0. Not exported from the package.
57
+ */
58
+ 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.";
46
59
  /** The same, when the only tool was `view_pages`: the text of the files is in the prompt, not in tool results. */
47
60
  export const FINAL_ANSWER_AFTER_PAGES = "Stop using tools now. Answer my question from the text of the files and the pages you looked at. Say plainly what you could not see or find. Answer in the language of my question.";
48
61
  /**
@@ -56,6 +69,16 @@ export const FINAL_ANSWER_WITHOUT_TOOLS = "Answer my question now, from what is
56
69
  */
57
70
  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.";
58
71
 
72
+ /**
73
+ * The least ceiling on the input tokens of a question that sets no `limits.inputTokens`. Its
74
+ * ceiling is the larger of this and `toolTurns` times its first request, with the room for its
75
+ * whole-file reads added. New in 0.10.0.
76
+ */
77
+ export const DEFAULT_INPUT_TOKENS = 1_000_000;
78
+
79
+ /** How many whole-file reads one question may make, over all its documents, by default (`limits.wholeReadsPerQuestion`). */
80
+ const DEFAULT_WHOLE_READS_PER_QUESTION = 2;
81
+
59
82
  /** The limits of one question. */
60
83
  export type AskLimits = {
61
84
  /**
@@ -79,12 +102,25 @@ export type AskLimits = {
79
102
  wholeDocumentReads?: number;
80
103
  /**
81
104
  * A ceiling on the input tokens of one question, over all its requests, whole-file part reads
82
- * included. Once it is reached no more tools run and the next request is the answer; a
83
- * whole-file read that would pass it is refused. Unset: no ceiling.
105
+ * included, in the models' own tokens. Before each tool request the loop looks ahead: when what
106
+ * was spent, that request and the answer's request would pass it, no more tools run and the next
107
+ * request is the answer. A whole-file read that would pass it is refused. A request whose
108
+ * provider reports no input counts by the library's estimate (`UsageTotals.estimatedInputTokens`).
109
+ * Unset (since 0.10.0): the larger of `DEFAULT_INPUT_TOKENS` and `toolTurns` times the estimate
110
+ * of the question's first request, plus room for its whole-file reads: as many as
111
+ * `wholeReadsPerQuestion` and the documents allow, each at the price of the dearest one.
112
+ * `Infinity`: no ceiling, as before 0.10.0.
84
113
  */
85
114
  inputTokens?: number;
86
115
  /** The same ceiling, on the number of model requests: the chat's and the part reads' together. */
87
116
  requests?: number;
117
+ /**
118
+ * How many whole-file reads (`analyze_whole_document`) one question may make over all its
119
+ * documents, next to `wholeDocumentReads` for each one. A read that sent requests counts, one
120
+ * that failed among them. Defaults to 2; `Infinity` keeps the rule of 0.9, one read of each
121
+ * document. New in 0.10.0.
122
+ */
123
+ wholeReadsPerQuestion?: number;
88
124
  };
89
125
 
90
126
  export type AskOptions = {
@@ -97,7 +133,8 @@ export type AskOptions = {
97
133
  /**
98
134
  * A second model that explores the documents: it makes the tool calls (search, read, look at
99
135
  * pages) and reads a whole file in parts. It may be of another provider than `model`. Left out,
100
- * or the same adapter as `model`: one model does both.
136
+ * or the same adapter as `model`: one model does both. Since 0.10.0 it is not used when no file
137
+ * is searched and the tools are there for tables sent whole (`inlineTables`): `model` runs them.
101
138
  */
102
139
  explorer?: ModelAdapter | undefined;
103
140
  /** Documents this conversation may use. Where their text or cards go: see `documentPlacement`. */
@@ -109,6 +146,38 @@ export type AskOptions = {
109
146
  * document then moves on every turn and is billed in full each time.
110
147
  */
111
148
  documentPlacement?: "first" | "last";
149
+ /**
150
+ * "tools": a table sent whole (a CSV, a workbook, a file with `| cell |` rows) can still be
151
+ * counted and searched: the question gets `search_document`, `read_document` and
152
+ * `aggregate_table` for it, and runs the tool loop. When no file is searched, `model` runs that
153
+ * loop itself, without the explorer, so a question that needs no count is still answered in one
154
+ * request. "text": it is sent whole without tools, as in 0.9. Defaults to "tools". New in 0.10.0.
155
+ */
156
+ inlineTables?: "tools" | "text";
157
+ /**
158
+ * Number the lines of the files sent whole, as the tools number them ("12| "), so that the answer
159
+ * can cite them. When no file is searched, the system text asks for citations like
160
+ * "(report.docx L12)". Defaults to true; false sends them as in 0.9. New in 0.10.0.
161
+ */
162
+ numberInline?: boolean;
163
+ /**
164
+ * What to do with an answer that a filter of the provider stopped (`AskResult.finish`
165
+ * "filtered"): "keep" (the default) keeps its text, as in 0.9; "drop" gives `answered: false` and
166
+ * `text: ""`. Text already sent through `onText` and `text` events cannot be taken back: the
167
+ * "answer_filtered" notice then says `discardText`, before `run.finish`. New in 0.10.0.
168
+ */
169
+ filteredAnswer?: "keep" | "drop";
170
+ /**
171
+ * Called with the result of every tool call that ran, before the model, the evidence, the steps
172
+ * and the events get it: return `{ result }` to send another result (it is sent with
173
+ * `redacted: true`, and the call's outcome is "redacted"), `{ reject: "why" }` to send
174
+ * `{ error: "why" }` in its place (outcome "refused"), or undefined to keep it. What it throws, or
175
+ * a value of another shape, ends the question. Each call's hook is called as soon as its result
176
+ * is in, so those of one turn may run at the same time; the verdicts are applied in call order,
177
+ * and what they let through is then fitted to the room in the request. The parts of a whole-file
178
+ * read go to the model that reads them, not through this. New in 0.10.0.
179
+ */
180
+ onToolResult?: (context: ToolResultContext) => ToolResultVerdict | undefined | Promise<ToolResultVerdict | undefined>;
112
181
  /**
113
182
  * The conversation; the last message must be the user's question. Plain turns
114
183
  * (`{ role, text }`), the tool rounds an earlier question returned (`AskResult.toolTurns`), and
@@ -118,6 +187,26 @@ export type AskOptions = {
118
187
  system?: string;
119
188
  /** The user asking. Documents ingested with a different owner are treated as missing. */
120
189
  owner?: string;
190
+ /**
191
+ * The scope of the question, such as [userId, chatId] (`DocumentScope`). It is passed to every
192
+ * store call, and documents ingested with another scope are treated as missing. New in 0.9.0.
193
+ */
194
+ scope?: DocumentScope;
195
+ /**
196
+ * What to do when documents of `documentIds` are missing: expired, deleted, never ingested, or of
197
+ * another owner or scope, which look the same. It is settled before any model request.
198
+ * - "throw" (the default): the question fails with `DocumentsNotFoundError`, as before 0.9.0.
199
+ * - "drop": the question is answered without them. The system instruction gets one line that says
200
+ * how many files are no longer available, `AskResult.missing` lists them, and a
201
+ * "documents_missing" notice names them. With no document left, it is a plain chat: no tools.
202
+ * - A function, given the missing IDs, that returns what to do (`MissingDocumentsAction`): "throw",
203
+ * "drop", `{ retry: true }` once it has ingested them again under the same IDs, or
204
+ * `{ replace: { [oldId]: newId } }` for the IDs it ingested them under. A retry or replace plans
205
+ * the question again, once: an ID still missing then fails it with `DocumentsNotFoundError`.
206
+ * What the function throws fails the question.
207
+ * New in 0.9.0.
208
+ */
209
+ onMissingDocuments?: "throw" | "drop" | ((missing: string[], context: MissingDocumentsContext) => MissingDocumentsAction | Promise<MissingDocumentsAction>);
121
210
  limits?: AskLimits;
122
211
  /** How a model request that failed is sent again. Defaults to three more tries, with a wait that doubles. */
123
212
  retry?: RetryOptions;
@@ -178,16 +267,23 @@ export type AskResult = {
178
267
  */
179
268
  text: string;
180
269
  /**
181
- * False when the model's last turn had no text: the prompt was blocked, the reply was cut off
182
- * before any text, or the model produced a malformed tool call. `text` may then be empty or
183
- * hold only an earlier remark, so show your own message instead of treating it as the answer.
270
+ * False when the reply that should be the answer had no text: the prompt was blocked, or the
271
+ * reply was cut off or filtered before any text. A turn whose tool call could not be read is
272
+ * not an answer either, even with text: the answer is asked for once more. With
273
+ * `filteredAnswer: "drop"`, false for a filtered answer too. `text` may then be empty or hold
274
+ * only an earlier remark, so show your own message instead of treating it as the answer
275
+ * (`answerInfoOf` says which).
184
276
  */
185
277
  answered: boolean;
186
278
  /** Why the provider refused the prompt, when it did. */
187
279
  blockReason?: string;
188
280
  /** Every tool step taken, in order (also delivered through `onStep`). */
189
281
  steps: string[];
190
- /** What each tool call showed the model: the document, and the lines or pages. In call order. */
282
+ /**
283
+ * What the model was shown: first each file sent whole, in the order of its block (`tool`
284
+ * "inline", every line, `whole: true`, no `callId`; since 0.10.0), then what each tool call
285
+ * showed, the document and the lines or pages, in call order.
286
+ */
191
287
  evidence: Evidence[];
192
288
  /**
193
289
  * The tool rounds of this question as plain JSON. Kept with the conversation and passed back in
@@ -197,6 +293,11 @@ export type AskResult = {
197
293
  toolTurns: ToolTurn[];
198
294
  /** Which documents went in whole and which were searched. */
199
295
  plan: DocumentPlan;
296
+ /**
297
+ * The documents of `documentIds` that were missing, and that the question was answered without
298
+ * (`onMissingDocuments` "drop"). Absent when none was. New in 0.9.0.
299
+ */
300
+ missing?: string[];
200
301
  /** The budget the question ran with: the library's, fitted to the models. */
201
302
  budget: Budget;
202
303
  /** Model requests made for the chat itself, an explorer model's among them (whole-document part reads not included). */
@@ -206,22 +307,233 @@ export type AskResult = {
206
307
  usage: UsageTotals;
207
308
  /** The provider's own usage object of the last chat response, as it came. */
208
309
  lastUsage?: Record<string, unknown>;
310
+ /**
311
+ * How the reply whose text is the answer ended (`ModelReply.finish`), or the last reply of the
312
+ * chat when none answered. Absent when the adapter does not say. A "filtered" or "cut" answer
313
+ * also has an "answer_filtered" or "answer_cut" notice. New in 0.10.0.
314
+ */
315
+ finish?: ModelReply["finish"];
316
+ /**
317
+ * The line citations of `text`, checked against what the tools showed (`checkCitations`): a
318
+ * document sent whole counts as shown. Set when the question had documents. New in 0.10.0.
319
+ */
320
+ citations?: CitationCheck;
321
+ };
322
+
323
+ /**
324
+ * What `AskOptions.onToolResult` is given: the call and its result, as the tool returned it (before
325
+ * it is fitted to the room in the request), the document it names, who asks, and a signal that
326
+ * aborts when the question is stopped or fails. New in 0.10.0.
327
+ */
328
+ export type ToolResultContext = { call: ToolCall; result: ToolResult; documentId?: string; owner?: string; scope?: DocumentScope; signal: AbortSignal };
329
+
330
+ /**
331
+ * What `AskOptions.onToolResult` returns: `{ result }` sends that result in place of the tool's,
332
+ * and `{ reject }` sends `{ error: reject }`. Undefined keeps the tool's result. New in 0.10.0.
333
+ */
334
+ export type ToolResultVerdict = { result: ToolResult } | { reject: string };
335
+
336
+ /**
337
+ * What `AskOptions.onMissingDocuments` says to do with the documents that are missing:
338
+ * - "throw": fail the question with `DocumentsNotFoundError`;
339
+ * - "drop": answer it without them;
340
+ * - `{ retry: true }`: plan it again with the same IDs, under which the documents were ingested again;
341
+ * - `{ replace: { [oldId]: newId } }`: plan it again with each new ID in place of its old one.
342
+ * New in 0.9.0.
343
+ */
344
+ export type MissingDocumentsAction = "throw" | "drop" | { retry: true } | { replace: Record<string, string> };
345
+
346
+ /** What a function of `AskOptions.onMissingDocuments` is told besides the IDs: who asks, and the question's signal. New in 0.9.0. */
347
+ export type MissingDocumentsContext = { owner?: string; scope?: DocumentScope; signal?: AbortSignal };
348
+
349
+ /** The line added to the system instruction when `count` documents were left out ("drop"). */
350
+ const missingFilesLine = (count: number) => (count === 1
351
+ ? "1 of the attached files is no longer available; say so if the question needs it."
352
+ : `${count} of the attached files are no longer available; say so if the question needs them.`);
353
+
354
+ /** A value as an error quotes it. */
355
+ const shownValue = (value: unknown) => (typeof value === "string" ? JSON.stringify(value) : value === null ? "null" : typeof value);
356
+
357
+ /** `onMissingDocuments` checked: a value it cannot be is an error before anything is planned. */
358
+ function checkMissingPolicy(given: unknown): void {
359
+ if (given === undefined || given === "throw" || given === "drop" || typeof given === "function") return;
360
+ throw new TypeError(`onMissingDocuments must be "throw", "drop" or a function, and is ${shownValue(given)}.`);
361
+ }
362
+
363
+ /**
364
+ * `filteredAnswer` checked: a value it cannot be ("Drop", true) is an error before anything is
365
+ * planned. It would otherwise keep a filtered answer that the application meant to drop.
366
+ */
367
+ function checkFilteredAnswer(given: unknown): void {
368
+ if (given === undefined || given === "keep" || given === "drop") return;
369
+ throw new TypeError(`filteredAnswer must be "keep" or "drop", and is ${shownValue(given)}.`);
370
+ }
371
+
372
+ /**
373
+ * `inlineTables` and `numberInline` checked: a value they cannot be ("Text", "false") is an error
374
+ * before anything is planned, as `prepare` would throw it, but in the words of the question.
375
+ */
376
+ function checkInlineOptions(tables: unknown, numbered: unknown): void {
377
+ if (tables !== undefined && tables !== "tools" && tables !== "text") throw new TypeError(`inlineTables must be "tools" or "text", and is ${shownValue(tables)}.`);
378
+ if (numbered !== undefined && typeof numbered !== "boolean") throw new TypeError(`numberInline must be true or false, and is ${shownValue(numbered)}.`);
379
+ }
380
+
381
+ /**
382
+ * The evidence of a document sent whole (since 0.10.0): every line of it was shown. It comes from
383
+ * no tool call, so it has no `callId`.
384
+ */
385
+ const sentWhole = (meta: DocumentMeta): Evidence => ({
386
+ tool: "inline",
387
+ documentId: meta.id,
388
+ document: meta.name,
389
+ ...(Number.isFinite(meta.lines) && meta.lines >= 1 ? { lines: [[1, Math.trunc(meta.lines)]] } : {}),
390
+ whole: true,
391
+ });
392
+
393
+ /** An object made as `{}` or `Object.create(null)` is: not a Map, an array or an instance of a class. */
394
+ const isPlainObject = (value: unknown): value is Record<string, unknown> => {
395
+ if (value === null || typeof value !== "object") return false;
396
+ const prototype: unknown = Object.getPrototypeOf(value);
397
+ return prototype === Object.prototype || prototype === null;
209
398
  };
210
399
 
400
+ /** What a function of `onMissingDocuments` returned, checked. */
401
+ function checkedAction(action: unknown): MissingDocumentsAction {
402
+ if (action === "throw" || action === "drop") return action;
403
+ // Only the keys of an action: a key it does not have is a mistake, not something to ignore.
404
+ if (action !== null && typeof action === "object" && Object.keys(action).every((key) => key === "retry" || key === "replace")) {
405
+ const { retry, replace } = action as { retry?: unknown; replace?: unknown };
406
+ if (retry === true && replace === undefined) return { retry: true };
407
+ if (retry === undefined && isPlainObject(replace) && Object.values(replace).every((id) => typeof id === "string" && id.length > 0)) {
408
+ return { replace: { ...(replace as Record<string, string>) } };
409
+ }
410
+ }
411
+ throw new TypeError(`onMissingDocuments returned ${shownValue(action)}: it must return "throw", "drop", { retry: true } or { replace: { [oldId]: newId } }.`);
412
+ }
413
+
414
+ /**
415
+ * What `onToolResult` returned, checked: undefined, `{ result }` with a result that is an object,
416
+ * or `{ reject }` with a string. A verdict with a `result` is a result, whatever else it holds.
417
+ * Anything else ends the question: the hook is there to keep something from the model, and a
418
+ * mistake in it must not let the result through.
419
+ */
420
+ function checkedVerdict(verdict: unknown): ToolResultVerdict | undefined {
421
+ if (verdict === undefined) return undefined;
422
+ if (verdict !== null && typeof verdict === "object") {
423
+ if (Object.hasOwn(verdict, "result")) {
424
+ const { result } = verdict as { result: unknown };
425
+ if (result !== null && typeof result === "object" && !Array.isArray(result)) return { result: result as ToolResult };
426
+ } else if (Object.hasOwn(verdict, "reject")) {
427
+ const { reject } = verdict as { reject: unknown };
428
+ if (typeof reject === "string") return { reject };
429
+ }
430
+ }
431
+ throw new TypeError(`onToolResult returned ${shownValue(verdict)}: it must return { result }, { reject: "why" } or undefined.`);
432
+ }
433
+
434
+ /** The documents of a question once `onMissingDocuments` had its say. */
435
+ type PlannedDocuments = {
436
+ prepared: PreparedContext;
437
+ /** The IDs planned: those asked about, without those left out, with those replaced. */
438
+ documentIds: string[];
439
+ /** The IDs left out ("drop"). */
440
+ dropped: string[];
441
+ };
442
+
443
+ /**
444
+ * Plans the documents `ids`, and settles those that are missing as `onMissingDocuments` says. A
445
+ * retry or a replace plans them again, once.
446
+ */
447
+ async function planDocumentsOf(options: AskOptions, ids: string[], prepare: (ids: string[]) => Promise<PreparedContext>): Promise<PlannedDocuments> {
448
+ const prepared = await prepare(ids);
449
+ if (prepared.missing.length === 0) return { prepared, documentIds: ids, dropped: [] };
450
+ const policy = options.onMissingDocuments ?? "throw";
451
+ let action: MissingDocumentsAction = policy === "drop" ? "drop" : "throw";
452
+ if (typeof policy === "function") {
453
+ options.signal?.throwIfAborted();
454
+ const context: MissingDocumentsContext = {
455
+ ...(options.owner !== undefined ? { owner: options.owner } : {}),
456
+ ...(options.scope !== undefined ? { scope: options.scope } : {}),
457
+ ...(options.signal ? { signal: options.signal } : {}),
458
+ };
459
+ // A function that does not look at the signal does not hold the question once it is stopped.
460
+ action = checkedAction(await until(policy([...prepared.missing], context), options.signal));
461
+ }
462
+ if (action === "throw") throw new DocumentsNotFoundError(prepared.missing);
463
+ if (action === "drop") {
464
+ const gone = new Set(prepared.missing);
465
+ return { prepared, documentIds: ids.filter((id) => !gone.has(id)), dropped: [...prepared.missing] };
466
+ }
467
+ const replace = "replace" in action ? action.replace : {};
468
+ const again = ids.map((id) => (Object.hasOwn(replace, id) ? replace[id]! : id));
469
+ const second = await prepare(again);
470
+ if (second.missing.length > 0) throw new DocumentsNotFoundError(second.missing);
471
+ return { prepared: second, documentIds: again, dropped: [] };
472
+ }
473
+
474
+ /** The step of a question whose older tool results were shortened to make room. */
475
+ const RESULTS_SHORTENED = "Older tool results were shortened to make room in the request";
476
+
211
477
  const DEFAULT_TOOL_TURNS = 12;
212
478
  const DEFAULT_CALLS_PER_TURN = 8;
213
479
  /** Tool calls of one turn that run at the same time. */
214
480
  const CALLS_AT_ONCE = 4;
215
481
  /** With less room than this for its result, a call is not run. */
216
482
  const LEAST_ROOM_CHARACTERS = 1_500;
217
- /** Characters of a tool result for each token of room. A log full of IDs and numbers comes to about two. */
483
+ /**
484
+ * Characters of a tool result for each token of room, when the call names no document of the
485
+ * question. Since 0.10.0 a call that names one takes its document's own (`charactersPerToken`).
486
+ */
218
487
  const CHARACTERS_PER_TOKEN = 2;
488
+
489
+ /**
490
+ * The characters of a document's text for each token of the estimate, as its ingest counted them,
491
+ * from 0.8 to 4: about 0.9 for a table of numbers, 1.4 for a service log, 1.9 for Hebrew prose.
492
+ * The JSON of a tool result that quotes the text comes to about the same. `CHARACTERS_PER_TOKEN`
493
+ * when the metadata does not say. New in 0.10.0.
494
+ */
495
+ function charactersPerToken(meta: Pick<DocumentMeta, "characters" | "estimatedTokens"> | undefined): number {
496
+ const ratio = meta && meta.estimatedTokens > 0 ? meta.characters / meta.estimatedTokens : Number.NaN;
497
+ return Number.isFinite(ratio) ? Math.min(4, Math.max(0.8, ratio)) : CHARACTERS_PER_TOKEN;
498
+ }
499
+
500
+ /** The tokens of room a tool result takes in a request, as the request meter counts an answer. */
501
+ const resultTokens = (result: ToolResult): number => estimateTokens(JSON.stringify(result)) + 8;
502
+
503
+ /**
504
+ * `result` cut to `tokens` of room (`resultTokens`): by `fitAnswer`, to the characters its own
505
+ * characters per token give, and a little less again while it is still over. Never below
506
+ * `LEAST_RESULT_CHARACTERS`.
507
+ */
508
+ function cutToTokens(result: ToolResult, tokens: number): ToolResult {
509
+ const json = JSON.stringify(result);
510
+ const perToken = json.length / Math.max(1, resultTokens(result));
511
+ let characters = Math.max(LEAST_RESULT_CHARACTERS, Math.floor(tokens * perToken));
512
+ let cut = fitAnswer(result, characters);
513
+ for (let tries = 0; tries < 4 && resultTokens(cut) > tokens && characters > LEAST_RESULT_CHARACTERS; tries++) {
514
+ characters = Math.max(LEAST_RESULT_CHARACTERS, Math.floor(characters * 0.85));
515
+ cut = fitAnswer(result, characters);
516
+ }
517
+ return cut;
518
+ }
519
+
520
+ /**
521
+ * `alreadyShown`, but never a pointer to a result that `onToolResult` replaced (`redacted: true`):
522
+ * it does not hold what the call would return.
523
+ */
524
+ function pointerTo(call: { name: string; args: Record<string, unknown> }, earlier: { call: { name: string; args: Record<string, unknown> }; result: ToolResult }, stored = false): ToolResult | undefined {
525
+ return earlier.result.redacted === true ? undefined : alreadyShown(call, earlier, stored);
526
+ }
219
527
  /** Bytes a character of a tool result may take in the request. */
220
528
  const BYTES_PER_CHARACTER = 3;
221
529
  /** Tool rounds whose results are kept in full when older ones are dropped to make room. */
222
530
  const ROUNDS_KEPT = [3, 2, 1];
223
531
 
224
532
  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.";
533
+ /** How the error of a whole-file read that sent its parts, and could read none of them, begins (`NothingReadError`). */
534
+ const NOTHING_READ = "Could not read any part of ";
535
+ /** 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. */
536
+ const unknownTool = (name: string, tools: string[]) => `Unknown tool ${unknownToolName(name)}. The tools are: ${tools.join(", ")}.`;
225
537
  /** Why a request of a whole-file read that its read left behind ended with its call. */
226
538
  const CALL_ENDED = "The tool call ended before this request did.";
227
539
 
@@ -256,10 +568,28 @@ function pagesShown(result: ToolResult): number {
256
568
  */
257
569
  const carriedResult = (result: ToolResult): ToolResult => wellFormedJson(laterResult(result));
258
570
 
259
- /** The conversation as the loop keeps it: copies, so that nothing of the caller's is changed. */
571
+ /**
572
+ * Refuses a stored tool round of a version this package does not read: one a newer version made
573
+ * (`ToolTurn.version` above `TOOL_TURN_VERSION`). A round without a version (before 0.9.0) is read
574
+ * as before. A `TypeError`, which an application can catch to leave such rounds out.
575
+ */
576
+ function checkToolTurnVersion(turn: ToolTurn): void {
577
+ const version: unknown = turn.version ?? 0;
578
+ if (typeof version === "number" && version <= TOOL_TURN_VERSION) return;
579
+ if (typeof version !== "number" || Number.isNaN(version)) {
580
+ 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.`);
581
+ }
582
+ 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.`);
583
+ }
584
+
585
+ /**
586
+ * The conversation as the loop keeps it: copies, so that nothing of the caller's is changed. Of a
587
+ * stored tool round, only the calls are kept: its version is not sent to the model.
588
+ */
260
589
  function toMessages(given: ChatMessage[]): ModelMessage[] {
261
590
  const messages = given.map((message): ModelMessage => {
262
591
  if (message.role === "tools") {
592
+ checkToolTurnVersion(message);
263
593
  const answers = message.calls.map(({ result, ...call }) => ({ call, result: carriedResult(result) }));
264
594
  return { role: "tools", calls: answers.map((answer) => answer.call), answers };
265
595
  }
@@ -279,7 +609,9 @@ function textSize(messages: ModelMessage[], system: string | undefined): Size {
279
609
  for (const part of message.parts) {
280
610
  if (typeof part.text === "string") {
281
611
  tokens += estimateTokens(part.text);
282
- bytes += jsonBytes(part.text);
612
+ // A part in the provider's own form is sent whole: its text, and what is next to it (a
613
+ // thought signature), or the call that the text stands for.
614
+ bytes += part.native === undefined ? jsonBytes(part.text) : Math.max(jsonBytes(part.text), (JSON.stringify(part.native) ?? "").length);
283
615
  } else {
284
616
  const size = (JSON.stringify(part.native) ?? "").length;
285
617
  bytes += size;
@@ -372,23 +704,30 @@ class RequestMeter {
372
704
  }
373
705
 
374
706
  /**
375
- * Shares `room` characters among tool calls whose results may be up to `caps` characters. A call
376
- * gets no more than its cap, and the others split what it leaves. Calls that cannot each get
377
- * `LEAST_ROOM_CHARACTERS` (or their cap, when it is smaller) are not run, the last ones first:
378
- * their share is undefined.
707
+ * Shares `room` among tool calls whose results may be up to `caps` characters. A character of the
708
+ * result of call i takes `rates[i]` of the room (1 when `rates` is left out: the room is in
709
+ * characters; since 0.10.0 the loop gives it in tokens, and each call the tokens a character of its
710
+ * document takes). A call gets no more than its cap, and the others split what it leaves. Calls
711
+ * that cannot each get `LEAST_ROOM_CHARACTERS` (or their cap, when it is smaller) are not run, the
712
+ * last ones first: their share is undefined. The shares are in characters.
379
713
  */
380
- export function shareRoom(caps: number[], room: number): Array<number | undefined> {
381
- const least = (cap: number) => Math.min(cap, LEAST_ROOM_CHARACTERS);
714
+ export function shareRoom(caps: number[], room: number, rates?: number[]): Array<number | undefined> {
715
+ const rate = (index: number) => rates?.[index] ?? 1;
716
+ const least = (cap: number, index: number) => Math.min(cap, LEAST_ROOM_CHARACTERS) * rate(index);
382
717
  let count = caps.length;
383
- let needed = caps.reduce((sum, cap) => sum + least(cap), 0);
384
- while (count > 0 && needed > room) needed -= least(caps[--count]!);
718
+ let needed = caps.reduce((sum, cap, index) => sum + least(cap, index), 0);
719
+ while (count > 0 && needed > room) {
720
+ count--;
721
+ needed -= least(caps[count]!, count);
722
+ }
385
723
  const shares: Array<number | undefined> = caps.map(() => undefined);
386
724
  // The smallest caps first: each call takes its cap or an even share of what is left, whichever is less.
387
- const order = caps.slice(0, count).map((cap, index) => ({ cap, index })).sort((left, right) => left.cap - right.cap);
725
+ const order = caps.slice(0, count).map((cap, index) => ({ cap: cap * rate(index), index })).sort((left, right) => left.cap - right.cap);
388
726
  let left = Math.max(0, Math.floor(room));
389
727
  order.forEach(({ cap, index }, position) => {
390
728
  const share = Math.min(cap, Math.floor(left / (order.length - position)));
391
- shares[index] = share;
729
+ // A call given its whole cap gets the cap as it is, not as it comes back from the rate.
730
+ shares[index] = share === cap ? caps[index]! : Math.floor(share / rate(index));
392
731
  left -= share;
393
732
  });
394
733
  return shares;
@@ -451,6 +790,9 @@ type Carried = {
451
790
  recoveries: number;
452
791
  contextTokens: number;
453
792
  step: string;
793
+ /** The documents the first try planned, once `onMissingDocuments` had its say, and those it left out. */
794
+ documentIds: string[];
795
+ missing: string[];
454
796
  };
455
797
 
456
798
  /**
@@ -486,7 +828,7 @@ const MOST_OVERFLOW_RECOVERIES = 2;
486
828
  * so it turned off the ceilings and the cap on whole-file reads, or every tool.
487
829
  */
488
830
  function checkedLimits(given: AskLimits | undefined): AskLimits {
489
- for (const field of ["toolTurns", "callsPerTurn", "wholeDocumentReads", "inputTokens", "requests"] as const) {
831
+ for (const field of ["toolTurns", "callsPerTurn", "wholeDocumentReads", "inputTokens", "requests", "wholeReadsPerQuestion"] as const) {
490
832
  const value: unknown = given?.[field];
491
833
  if (value === undefined) continue;
492
834
  if (typeof value !== "number") throw new TypeError(`limits.${field} must be a number, and is ${typeof value === "string" ? JSON.stringify(value) : typeof value}.`);
@@ -562,13 +904,22 @@ export async function askWithFiles(options: AskOptions): Promise<AskResult> {
562
904
  * A result as `run.finish` and `run.error` carry it: a copy, so that a listener cannot change the
563
905
  * caller's, without the tool rounds and with the plan naming documents only (both hold text of
564
906
  * the documents: tool results, outline headings, the commonest lines of a log) unless `withTurns`.
907
+ * Its plan never holds the owner, scope, SHA-256 or original of a document.
565
908
  */
566
909
  function eventResultOf(result: AskResult, withTurns: boolean): EventResult {
567
- if (withTurns) return { ...result };
568
- const { toolTurns: _toolTurns, plan, ...rest } = result;
910
+ const { toolTurns, plan, ...rest } = result;
911
+ // The full metadata only with `withTurns`, and never what is to stay on the server: who owns a
912
+ // document, its scope, the SHA-256 and the ref of its original.
913
+ if (withTurns) return { ...rest, toolTurns, plan: { inline: plan.inline.map(withoutServerFields), searchable: plan.searchable.map(withoutServerFields) } };
569
914
  return { ...rest, plan: { inline: plan.inline.map(documentRef), searchable: plan.searchable.map(documentRef) } };
570
915
  }
571
916
 
917
+ /** A document's metadata without what is to stay on the server, for an event (since 0.10.0). */
918
+ function withoutServerFields(meta: DocumentMeta): Omit<DocumentMeta, "owner" | "scope" | "sha256" | "original" | "metaVersion"> {
919
+ const { owner: _owner, scope: _scope, sha256: _sha256, original: _original, metaVersion: _metaVersion, ...rest } = meta;
920
+ return rest;
921
+ }
922
+
572
923
  /**
573
924
  * `askWithFiles` as a stream of its events, for a page that shows the question as it goes: see
574
925
  * `AskEvent`. Leaving the loop early (`break`) stops the question. `result` is what `askWithFiles`
@@ -605,7 +956,9 @@ async function askPlanned(options: AskOptions, state: RunState): Promise<AskResu
605
956
  // Failed before it sent anything (a budget of the application's that cannot work with the
606
957
  // smaller window): the provider's error, with what the first try found, is the one to report.
607
958
  // (The question's own record: `partialResultOf` gives nothing for an error another question threw too.)
608
- if (state.failed?.error !== again && (again as { status?: unknown } | null)?.status === undefined) {
959
+ // (A store that failed, or a document gone, has a status since 0.9.0, but is not the model's.)
960
+ const fromModel = (again as { status?: unknown } | null)?.status !== undefined && !DocumentStoreError.is(again) && !DocumentsNotFoundError.is(again);
961
+ if (state.failed?.error !== again && !fromModel) {
609
962
  keepPartial(error.overflow, state, error.partial);
610
963
  throw error.overflow;
611
964
  }
@@ -617,11 +970,18 @@ async function askPlanned(options: AskOptions, state: RunState): Promise<AskResu
617
970
  async function ask(options: AskOptions, carried: Carried | undefined, state: RunState): Promise<AskResult> {
618
971
  const { files, model, signal } = options;
619
972
  const { events } = state;
620
- // A second model for the requests that use tools. The answering model itself is not one.
621
- const explorer = options.explorer && options.explorer !== model ? options.explorer : undefined;
622
- const toolModel = explorer ?? model;
623
- const models = explorer ? [model, explorer] : [model];
973
+ // A second model for the requests that use tools. The answering model itself is not one. It
974
+ // explores only when a file is searched (see `explorer` below), but the budget is fitted to it.
975
+ const given = options.explorer && options.explorer !== model ? options.explorer : undefined;
976
+ const models = given ? [model, given] : [model];
624
977
  const limits = checkedLimits(options.limits);
978
+ checkMissingPolicy(options.onMissingDocuments);
979
+ checkFilteredAnswer(options.filteredAnswer);
980
+ checkInlineOptions(options.inlineTables, options.numberInline);
981
+ // Since 0.10.0 by default: the tables sent whole get the tools, and the files sent whole have
982
+ // numbered lines. "text" and false send them as 0.9 did.
983
+ const inlineTables = options.inlineTables ?? "tools";
984
+ const numberInline = options.numberInline ?? true;
625
985
  // A question planned again goes on counting what its first try paid for.
626
986
  const usage = carried?.usage ?? new UsageMeter();
627
987
 
@@ -654,29 +1014,67 @@ async function ask(options: AskOptions, carried: Carried | undefined, state: Run
654
1014
  const meter = new RequestMeter(pageTokens);
655
1015
  const asText = textSize(messages, options.system);
656
1016
  const earlier = meter.rounds(messages);
657
- const prepared = await files.prepare(options.documentIds, { tokens: asText.tokens + earlier.tokens, bytes: asText.bytes + earlier.bytes }, {
1017
+ // Who asks: the documents are looked up, and every tool call reads them, for this owner and
1018
+ // scope. The question's signal goes with them, for a library that ends its waits for the store
1019
+ // with it (`AccessOptions.signal`).
1020
+ const access = {
658
1021
  ...(options.owner !== undefined ? { owner: options.owner } : {}),
1022
+ ...(options.scope !== undefined ? { scope: options.scope } : {}),
1023
+ ...(signal ? { signal } : {}),
1024
+ };
1025
+ // Documents that are missing are settled as `onMissingDocuments` says. A question planned again
1026
+ // starts from the documents its first try planned: the function is not asked again about them.
1027
+ // The question stops when its signal aborts, whether the library does or not: a store call that
1028
+ // hangs (a network volume that does not answer) must not hold it, with any `LargeFiles`.
1029
+ const planned = await planDocumentsOf(options, carried?.documentIds ?? options.documentIds, (ids) => until(files.prepare(ids, { tokens: asText.tokens + earlier.tokens, bytes: asText.bytes + earlier.bytes }, {
1030
+ ...access,
659
1031
  viewPages: options.viewPages !== false && canShowFiles,
660
1032
  // The guide and the cards name `analyze_whole_document` only when the tools will have it.
661
- wholeDocumentAnalysis: options.wholeDocumentAnalysis !== false && typeof toolModel.generateText === "function",
1033
+ wholeDocumentAnalysis: options.wholeDocumentAnalysis !== false && typeof (given ?? model).generateText === "function",
662
1034
  budget,
663
- });
664
- if (prepared.missing.length) throw new DocumentsNotFoundError(prepared.missing);
1035
+ numberInline,
1036
+ inlineTables,
1037
+ }), signal));
1038
+ const { prepared, documentIds } = planned;
1039
+ /** The documents left out of the question ("drop"), by this try and by the first. */
1040
+ const missing = [...carried?.missing ?? [], ...planned.dropped];
1041
+ // Tools are needed for a file that is too large to send whole, for a PDF whose pages can be
1042
+ // looked at (that one may have its whole text in the prompt and still hide a chart from the
1043
+ // model), and for a table sent whole whose rows they can count (`inlineTables`). A library of
1044
+ // your own whose `prepare` gives no `toolable` has none of the last.
1045
+ const { searchable } = prepared.plan;
1046
+ const { viewable } = prepared;
1047
+ const toolable = prepared.toolable ?? [];
1048
+ // The explorer gathers what the answer needs from the files searched with the tools. When none
1049
+ // is, and the tools are there for tables sent whole, the answering model runs the loop itself: a
1050
+ // question that needs no count is then answered in its first request, and the whole files are
1051
+ // not sent to two models that share no cache.
1052
+ const explorer = given && !(searchable.length === 0 && toolable.length > 0) ? given : undefined;
1053
+ const toolModel = explorer ?? model;
1054
+ // The lines of the files sent whole are numbered when asked, by a library whose `prepare` is
1055
+ // that of this package (its result has the mark, `preparedHere`): one of your own of 0.9 sends
1056
+ // them as they are.
1057
+ const numbered = numberInline && preparedHere(prepared);
665
1058
 
666
- const blocks = [...new Set(options.documentIds)].map((id) => prepared.blocks.get(id)).filter((block): block is string => Boolean(block));
1059
+ const blocks = [...new Set(documentIds)].map((id) => prepared.blocks.get(id)).filter((block): block is string => Boolean(block));
667
1060
  if (blocks.length) {
668
1061
  const block = { text: blocks.join("\n\n") };
669
1062
  if (options.documentPlacement === "last") (messages.at(-1) as ModelTextMessage).parts.push(block);
670
1063
  // The last turn is the user's, so there is always a first user turn.
671
1064
  else (messages.find((message) => message.role === "user") as ModelTextMessage).parts.unshift(block);
672
1065
  }
673
- const system = [options.system?.trim(), prepared.instruction].filter(Boolean).join("\n\n");
1066
+ // A question without some of its files says so to the model, in one line of its own.
1067
+ const missingLine = missing.length > 0 ? missingFilesLine(missing.length) : "";
1068
+ // The fixed lines for the files sent whole (since 0.10.0): that their tables can still be counted
1069
+ // with the tools, and, when no file is searched, to cite their numbered lines.
1070
+ const inlineLine = inlineInstruction(prepared, numbered);
1071
+ const system = [options.system?.trim(), prepared.instruction, inlineLine, missingLine].filter(Boolean).join("\n\n");
674
1072
 
675
1073
  // The size of what stays in every request: the text as asked, the documents, the tool guide.
676
1074
  const whole = new Set(prepared.plan.inline.map((meta) => meta.id));
677
1075
  meter.fixed = {
678
- tokens: asText.tokens + prepared.plan.inlineTokens + estimateTokens(prepared.instruction),
679
- bytes: asText.bytes + prepared.plan.inlineBytes + jsonBytes(prepared.instruction),
1076
+ tokens: asText.tokens + prepared.plan.inlineTokens + estimateTokens(prepared.instruction) + (inlineLine ? estimateTokens(inlineLine) : 0) + (missingLine ? estimateTokens(missingLine) : 0),
1077
+ bytes: asText.bytes + prepared.plan.inlineBytes + jsonBytes(prepared.instruction) + (inlineLine ? jsonBytes(inlineLine) : 0) + (missingLine ? jsonBytes(missingLine) : 0),
680
1078
  };
681
1079
  for (const [id, block] of prepared.blocks) {
682
1080
  if (whole.has(id)) continue;
@@ -686,11 +1084,20 @@ async function ask(options: AskOptions, carried: Carried | undefined, state: Run
686
1084
 
687
1085
  let text = "";
688
1086
  let turns = carried?.turns ?? 0;
1087
+ /** The last reply of the chat: its `finish` is the answer's (`AskResult.finish`). */
1088
+ let lastReply: ModelReply | undefined;
1089
+ const dropFiltered = options.filteredAnswer === "drop";
689
1090
  let finishReason: string | undefined;
690
1091
  let blockReason: string | undefined;
691
1092
  let lastUsage: Record<string, unknown> | undefined;
692
1093
  const steps: string[] = [];
693
- const evidence: Evidence[] = [];
1094
+ // The files sent whole come first, in the order of their blocks: the model was shown every line
1095
+ // of them before any tool ran (since 0.10.0).
1096
+ const inlineById = new Map(prepared.plan.inline.map((meta) => [meta.id, meta]));
1097
+ const evidence: Evidence[] = [...new Set(documentIds)].flatMap((id) => {
1098
+ const meta = inlineById.get(id);
1099
+ return meta ? [sentWhole(meta)] : [];
1100
+ });
694
1101
  const emit = (delta: string, requestId: string) => {
695
1102
  text += delta;
696
1103
  options.onText?.(delta);
@@ -713,7 +1120,7 @@ async function ask(options: AskOptions, carried: Carried | undefined, state: Run
713
1120
  events.emit({ type: "notice", code, message, display: "activity" });
714
1121
  };
715
1122
  /** A notice that earlier versions did not show. */
716
- const notice = (code: NoticeCode, message: string) => events.emit({ type: "notice", code, message, display: "none" });
1123
+ const notice = (code: NoticeCode, message: string, documentIds?: string[]) => events.emit({ type: "notice", code, message, display: "none", ...(documentIds ? { documentIds } : {}) });
717
1124
  const budgetReached = () => {
718
1125
  if (state.budgetSaid) return;
719
1126
  state.budgetSaid = true;
@@ -722,6 +1129,10 @@ async function ask(options: AskOptions, carried: Carried | undefined, state: Run
722
1129
  // What a first try that was planned again showed is part of this question; then why it was planned again.
723
1130
  steps.push(...carried?.steps ?? []);
724
1131
  if (carried) step(carried.step, "replanned");
1132
+ if (planned.dropped.length > 0) {
1133
+ const count = planned.dropped.length;
1134
+ 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]);
1135
+ }
725
1136
  if (events.active) events.emit({ type: "plan", inline: prepared.plan.inline.map(documentRef), searchable: prepared.plan.searchable.map(documentRef) });
726
1137
 
727
1138
  // A model turn in its provider's own form goes back only to the adapter it came from. Any other
@@ -808,10 +1219,13 @@ async function ask(options: AskOptions, carried: Carried | undefined, state: Run
808
1219
  if (events.active) events.emit({ type: "request.end", requestId, ms: Date.now() - began, outcome: "error", error: eventErrorOf(error) });
809
1220
  throw error;
810
1221
  }
811
- // Text the adapter did not pass on as it came (no streaming was asked for, or it cannot).
812
- if (shown && reply.text.length > got.length && reply.text.startsWith(got)) write(reply.text.slice(got.length));
1222
+ // Text the adapter did not pass on as it came (no streaming was asked for, or it cannot). Not
1223
+ // the text of a reply a filter stopped, when such an answer is dropped: it was not shown yet.
1224
+ if (shown && reply.text.length > got.length && reply.text.startsWith(got) && !(dropFiltered && reply.finish === "filtered")) write(reply.text.slice(got.length));
813
1225
  answeredRequests++;
814
- usage.add(adapter.id, reply.usage);
1226
+ lastReply = reply;
1227
+ // A reply without its input tokens is counted by the estimate, in the model's own tokens.
1228
+ usage.add(adapter.id, reply.usage, estimated * scaleOf(adapter));
815
1229
  // The count of the model that answered, in the library's tokens by that model's own scale: how
816
1230
  // much more than its scale says the text costs it, which the other model will see too. By the
817
1231
  // larger scale of the two, a count of the model with the smaller one was taken for no more.
@@ -828,6 +1242,8 @@ async function ask(options: AskOptions, carried: Carried | undefined, state: Run
828
1242
  ...(reply.finish ? { finish: reply.finish } : {}),
829
1243
  ...(reply.finishReason !== undefined ? { finishReason: reply.finishReason } : {}),
830
1244
  toolCalls: reply.calls.length,
1245
+ ...(typeof reply.responseId === "string" ? { responseId: reply.responseId } : {}),
1246
+ ...(typeof reply.responseModel === "string" ? { responseModel: reply.responseModel } : {}),
831
1247
  });
832
1248
  if (reply.blockReason) notice("blocked", `The provider refused the prompt: ${reply.blockReason}.`);
833
1249
  return reply;
@@ -836,6 +1252,25 @@ async function ask(options: AskOptions, carried: Carried | undefined, state: Run
836
1252
  const wrote = (reply: ModelReply) => reply.text.trim().length > 0 && !reply.blockReason;
837
1253
 
838
1254
  const asked = messages.length;
1255
+ /** The documents of the question, by ID: their names and formats, for the citations of the answer. */
1256
+ const documents = [...prepared.plan.inline, ...prepared.plan.searchable];
1257
+ const citationsOf = (): CitationCheck => {
1258
+ const names: Record<string, string> = {};
1259
+ const formats: Record<string, DocumentFormat> = {};
1260
+ for (const meta of documents) {
1261
+ names[meta.id] = meta.name;
1262
+ formats[meta.id] = meta.format;
1263
+ }
1264
+ // A document sent whole was shown, every line of it (its evidence comes first and says so),
1265
+ // and a whole-file read read every line: those from 1 to its last. A line past the end of the
1266
+ // file is not supported.
1267
+ const linesOf = new Map(documents.map((meta) => [meta.id, meta.lines]));
1268
+ const bounded = (entry: Evidence): Evidence => {
1269
+ const lines = linesOf.get(entry.documentId);
1270
+ return entry.whole === true && !entry.lines && typeof lines === "number" && Number.isFinite(lines) ? { ...entry, lines: lines >= 1 ? [[1, Math.trunc(lines)]] : [] } : entry;
1271
+ };
1272
+ return checkCitations(text, evidence.map(bounded), names, formats);
1273
+ };
839
1274
  const result = (answered: boolean): AskResult => ({
840
1275
  text,
841
1276
  answered,
@@ -845,18 +1280,46 @@ async function ask(options: AskOptions, carried: Carried | undefined, state: Run
845
1280
  // The rounds as the model last had them. A file cannot be kept as JSON: what is kept says that it was shown.
846
1281
  toolTurns: messages.slice(asked).filter(isRound).map((round) => ({
847
1282
  role: "tools" as const,
1283
+ version: TOOL_TURN_VERSION,
848
1284
  calls: round.answers.map(({ call: { problem: _problem, ...call }, result: returned, files: shownFiles }) => ({
849
1285
  ...call,
850
1286
  result: shownFiles?.length ? stubResult(call, returned, true) ?? returned : returned,
851
1287
  })),
852
1288
  })),
853
1289
  plan: prepared.plan,
1290
+ ...(missing.length > 0 ? { missing: [...missing] } : {}),
854
1291
  budget,
855
1292
  turns,
856
1293
  ...(finishReason ? { finishReason } : {}),
857
1294
  usage: usage.totals,
858
1295
  ...(lastUsage ? { lastUsage } : {}),
1296
+ ...(lastReply?.finish !== undefined ? { finish: lastReply.finish } : {}),
1297
+ ...(documents.length > 0 ? { citations: citationsOf() } : {}),
859
1298
  });
1299
+ /**
1300
+ * The result of a question that ends with an answer: one that a filter stopped, or that was cut
1301
+ * at the output limit, says so in a notice, before `run.finish`. A filtered answer is dropped
1302
+ * when `filteredAnswer` says so; text of it already sent is to be taken away (`discardText`).
1303
+ */
1304
+ const answer = (answered: boolean): AskResult => {
1305
+ const finish = lastReply?.finish;
1306
+ if (finish === "filtered") {
1307
+ const sent = text.length > 0;
1308
+ const message = !lastReply?.text.trim()
1309
+ ? "A filter of the provider stopped the answer before any text came."
1310
+ : dropFiltered
1311
+ ? "A filter of the provider stopped the answer before it was finished: its text was dropped."
1312
+ : "A filter of the provider stopped the answer before it was finished.";
1313
+ events.emit({ type: "notice", code: "answer_filtered", message, display: "none", ...(dropFiltered && sent ? { discardText: true as const } : {}) });
1314
+ if (dropFiltered) {
1315
+ text = "";
1316
+ return result(false);
1317
+ }
1318
+ } else if (finish === "cut") {
1319
+ 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.");
1320
+ }
1321
+ return result(answered);
1322
+ };
860
1323
 
861
1324
  // Pages the model looks at stay in the request until the question is answered, so they are
862
1325
  // counted twice: as bytes against the request limit, and as tokens against half of what the
@@ -869,10 +1332,15 @@ async function ask(options: AskOptions, carried: Carried | undefined, state: Run
869
1332
  // request as too large, and names its window, makes it smaller.
870
1333
  let tokenLimit = budget.contextTokens - Math.floor(reservedTokens / 2);
871
1334
  const byteLimit = maxRequestBytes - Math.max(32_768, Math.floor(maxRequestBytes / 50));
872
- /** Characters of tool results that still fit, with a model turn that is about to be answered. */
873
- const room = (pending: ModelToolRound): number => {
1335
+ /**
1336
+ * The tokens of tool results that still fit, with a model turn that is about to be answered, for
1337
+ * calls whose results take `rates` tokens a character: within the token limit, and within the
1338
+ * bytes of the request for the call that takes the fewest tokens a character.
1339
+ */
1340
+ const room = (pending: ModelToolRound, rates: number[]): number => {
874
1341
  const now = meter.current([...messages, pending]);
875
- return Math.floor(Math.min((tokenLimit - now.tokens) * CHARACTERS_PER_TOKEN, (byteLimit - now.bytes) / BYTES_PER_CHARACTER));
1342
+ const fewest = rates.length > 0 ? Math.min(...rates) : 1 / CHARACTERS_PER_TOKEN;
1343
+ return Math.floor(Math.min(tokenLimit - now.tokens, (byteLimit - now.bytes) / BYTES_PER_CHARACTER * fewest));
876
1344
  };
877
1345
  /**
878
1346
  * Makes room: the results of every tool round but the last `keep` are replaced by short
@@ -931,7 +1399,7 @@ async function ask(options: AskOptions, carried: Carried | undefined, state: Run
931
1399
  if (answer.result.already_shown === true) {
932
1400
  const held = canPoint && ((key !== undefined && (inRound.has(key) || (answer.call.name !== TOOL_NAMES.read && shownKeys.has(key))))
933
1401
  || (answer.call.name === TOOL_NAMES.read && (shownReads.get(answer.call.args.document_id) ?? [])
934
- .some((read) => alreadyShown(answer.call, read.answer, read.index < asked && read.question !== question) !== undefined)));
1402
+ .some((read) => pointerTo(answer.call, read.answer, read.index < asked && read.question !== question) !== undefined)));
935
1403
  if (!held) {
936
1404
  touched = true;
937
1405
  now = {
@@ -943,7 +1411,7 @@ async function ask(options: AskOptions, carried: Carried | undefined, state: Run
943
1411
  },
944
1412
  };
945
1413
  }
946
- } else if (key !== undefined && alreadyShown(answer.call, answer) !== undefined) {
1414
+ } else if (key !== undefined && pointerTo(answer.call, answer) !== undefined) {
947
1415
  // A result in full: what a later pointer may point to.
948
1416
  if (answer.call.name === TOOL_NAMES.read) {
949
1417
  const reads = shownReads.get(answer.call.args.document_id) ?? [];
@@ -977,27 +1445,50 @@ async function ask(options: AskOptions, carried: Carried | undefined, state: Run
977
1445
  * work. A model whose conversation may only grow (Claude) has nothing shortened.
978
1446
  */
979
1447
  const makeRoom = (adapter: ModelAdapter, sent: ModelRequest, error: unknown): boolean => {
980
- const refused = error as { limitTokens?: number; requestedTokens?: number };
1448
+ const refused: { limitTokens?: number; requestedTokens?: number } = modelErrorOf(error) ?? {};
981
1449
  const own = scaleOf(adapter);
982
1450
  meter.overflowed(meter.estimate(sent.messages).tokens, refused.requestedTokens !== undefined ? refused.requestedTokens / own : undefined);
983
1451
  if (refused.limitTokens !== undefined) {
984
1452
  tokenLimit = Math.min(tokenLimit, Math.floor(refused.limitTokens / own) - replyTokens - Math.floor(reservedTokens / 2));
985
1453
  }
986
1454
  if (!canShrink) return false;
1455
+ return shortenUntil(() => meter.current(messages).tokens <= tokenLimit);
1456
+ };
1457
+ /**
1458
+ * Shortens old tool results until `fits`: those of every round but the last three, then two,
1459
+ * then one, then all. True when anything was shortened.
1460
+ */
1461
+ const shortenUntil = (fits: () => boolean): boolean => {
987
1462
  let changed = false;
988
1463
  for (const keep of [...ROUNDS_KEPT, 0]) {
989
- if (changed && meter.current(messages).tokens <= tokenLimit) break;
1464
+ if (changed && fits()) break;
990
1465
  if (shrink(keep)) changed = true;
991
1466
  }
992
1467
  return changed;
993
1468
  };
1469
+ /**
1470
+ * Before the first request of the question: when the stored rounds of earlier questions make it
1471
+ * larger than the room it has in tokens, their results are shortened as they would be after the
1472
+ * provider refused it (`makeRoom`, which counts tokens too), and it is sent shortened, instead of
1473
+ * sent to be refused. The rounds are those of earlier questions: nothing of this question has
1474
+ * been sent, and a stored round has no thinking in it, so this is done for a model whose
1475
+ * conversation may only grow (Claude) too. A question planned again shortens them again, and
1476
+ * does not say so twice: its first try's steps already do.
1477
+ */
1478
+ let firstSent = false;
1479
+ const preflight = () => {
1480
+ if (firstSent) return;
1481
+ firstSent = true;
1482
+ const fits = () => meter.current(messages).tokens <= tokenLimit;
1483
+ if (!fits() && shortenUntil(fits) && !carried?.steps.includes(RESULTS_SHORTENED)) step(RESULTS_SHORTENED, "results_shortened");
1484
+ };
994
1485
  /**
995
1486
  * The window to plan the documents for again, in the models' tokens, after the first request was
996
1487
  * refused as too large: the one the provider named, made smaller by how much more than the
997
1488
  * estimate it counted. Without its numbers, seven tenths of the window the budget assumed.
998
1489
  */
999
1490
  const smallerWindow = (adapter: ModelAdapter, sent: ModelRequest, error: unknown): { contextTokens: number; step: string } => {
1000
- const refused = error as { limitTokens?: number; requestedTokens?: number };
1491
+ const refused: { limitTokens?: number; requestedTokens?: number } = modelErrorOf(error) ?? {};
1001
1492
  const estimated = meter.estimate(sent.messages).tokens;
1002
1493
  const ratio = refused.requestedTokens !== undefined && estimated > 0 ? refused.requestedTokens / scaleOf(adapter) / estimated : undefined;
1003
1494
  const limit = refused.limitTokens;
@@ -1023,12 +1514,14 @@ async function ask(options: AskOptions, carried: Carried | undefined, state: Run
1023
1514
  * window (`Replan`). `build` makes the request from the conversation as it is then.
1024
1515
  */
1025
1516
  const send = async (adapter: ModelAdapter, build: () => ModelRequest, shown: boolean, kind: RequestKind): Promise<ModelReply> => {
1517
+ preflight();
1026
1518
  for (let again = false; ; again = true) {
1027
1519
  const body = build();
1028
1520
  try {
1029
1521
  return await request(adapter, body, shown, kind);
1030
1522
  } catch (error) {
1031
- if (errorKindOf(error) !== "context_overflow" || signal?.aborted) throw error;
1523
+ // By the kind its events report: also for an error of your own adapter with a status and no kind.
1524
+ if (modelErrorOf(error)?.kind !== "context_overflow" || signal?.aborted) throw error;
1032
1525
  if (!again && recoveries < MOST_OVERFLOW_RECOVERIES && makeRoom(adapter, body, error)) {
1033
1526
  recoveries++;
1034
1527
  const period = rateAllowanceOf(error);
@@ -1039,7 +1532,7 @@ async function ask(options: AskOptions, carried: Carried | undefined, state: Run
1039
1532
  }
1040
1533
  if (carried === undefined && callsAnswered === 0 && !text) {
1041
1534
  const smaller = smallerWindow(adapter, body, error);
1042
- throw new Replan({ usage, steps: [...steps], turns, answered: answeredRequests, nudges, recoveries, contextTokens: smaller.contextTokens, step: smaller.step }, error, result(false));
1535
+ throw new Replan({ usage, steps: [...steps], turns, answered: answeredRequests, nudges, recoveries, contextTokens: smaller.contextTokens, step: smaller.step, documentIds, missing }, error, result(false));
1043
1536
  }
1044
1537
  throw error;
1045
1538
  }
@@ -1082,31 +1575,41 @@ async function ask(options: AskOptions, carried: Carried | undefined, state: Run
1082
1575
  else signal?.addEventListener("abort", stopTools, { once: true });
1083
1576
 
1084
1577
  try {
1085
- // Tools are needed for a file that is too large to send whole, and for a PDF whose pages can be
1086
- // looked at: that one may have its whole text in the prompt and still hide a chart from the model.
1087
- const { searchable } = prepared.plan;
1088
- const { viewable } = prepared;
1089
- if (searchable.length === 0 && viewable.length === 0) return result(wrote(await send(model, () => ({ system, messages }), true, { role: "answer", purpose: "direct" })));
1578
+ // Nothing for the tools (see `toolable` above): one request, without them.
1579
+ if (searchable.length === 0 && viewable.length === 0 && toolable.length === 0) return answer(wrote(await send(model, () => ({ system, messages }), true, { role: "answer", purpose: "direct" })));
1090
1580
 
1091
1581
  // Reading a whole file in parts is exploring too: the explorer model's work, when there is one.
1092
1582
  // Bound to its adapter: a class with a `generateText` method that uses `this` keeps it.
1093
1583
  const partReader = options.wholeDocumentAnalysis === false ? undefined : toolModel.generateText?.bind(toolModel);
1094
1584
  const generate: GenerateText | undefined = partReader && (async (part) => {
1095
1585
  let reported = false;
1586
+ // What the request sends, in the reader's tokens: counted for a request whose usage does not
1587
+ // give its input, so that `limits.inputTokens` sees it. Worked out only then.
1588
+ const estimate = () => (estimateTokens(part.system) + estimateTokens(part.prompt)) * scaleOf(toolModel);
1096
1589
  const text = await partReader({
1097
1590
  ...part,
1098
1591
  onUsage: (used) => {
1099
1592
  reported = true;
1100
- usage.add(toolModel.id, used);
1593
+ usage.add(toolModel.id, used, reportsInput(used) ? undefined : estimate());
1101
1594
  part.onUsage?.(used);
1102
1595
  },
1103
1596
  });
1104
1597
  // A part reader that does not report its usage (`onUsage` is optional) still made a request,
1105
1598
  // and `limits.requests` counts it.
1106
- if (!reported) usage.add(toolModel.id, undefined);
1599
+ if (!reported) usage.add(toolModel.id, undefined, estimate());
1107
1600
  return text;
1108
1601
  });
1109
- const tools = files.tools(searchable, {
1602
+ // The tables sent whole are read by the tools too. Their question declares exactly the tools it
1603
+ // needs (`questionTools`): search_document, read_document and aggregate_table for them, never
1604
+ // get_document_overview or analyze_whole_document, which refuses a file sent whole if it is
1605
+ // called. With no such table, the tool set of 0.9.
1606
+ const declare = toolable.length > 0
1607
+ ? { declare: questionTools({ searchable, toolable, viewable }, generate !== undefined && searchable.some((meta) => canBeReadWhole(meta, budget))), inline: prepared.plan.inline.map((meta) => meta.id) }
1608
+ : {};
1609
+ const tools = files.tools([...searchable, ...toolable], {
1610
+ // The owner and scope the store holds are checked against the question's own, not against
1611
+ // the metadata handed in.
1612
+ access,
1110
1613
  ...(generate ? { generate } : {}),
1111
1614
  onProgress: (event) => options.onActivity?.(`${event.message}…`),
1112
1615
  signal: halt.signal,
@@ -1114,8 +1617,14 @@ async function ask(options: AskOptions, carried: Carried | undefined, state: Run
1114
1617
  maxWholeDocumentReads: limits.wholeDocumentReads ?? MAX_WHOLE_DOCUMENT_READS,
1115
1618
  ...(options.retry ? { retry: options.retry } : {}),
1116
1619
  budget,
1620
+ ...declare,
1117
1621
  });
1118
1622
  const declarations = tools.declarations;
1623
+ /** The documents a tool call found gone, told once each ("document_gone"). */
1624
+ const gone = new Set<string>();
1625
+ /** The file name of a document of the question, as the plan has it. */
1626
+ const metaOf = (id: unknown): DocumentMeta | undefined => (typeof id === "string" ? [...searchable, ...toolable, ...viewable].find((meta) => meta.id === id) : undefined);
1627
+ const nameOf = (id: string): string | undefined => metaOf(id)?.name;
1119
1628
  // The requests that use the tools are the chat's own, or an explorer model's: the same
1120
1629
  // conversation, and a line that says what its part is.
1121
1630
  const toolSystem = explorer ? `${system}\n\n${EXPLORER_INSTRUCTION}` : system;
@@ -1126,43 +1635,138 @@ async function ask(options: AskOptions, carried: Carried | undefined, state: Run
1126
1635
 
1127
1636
  const maxTurns = Math.max(1, Math.trunc(limits.toolTurns ?? DEFAULT_TOOL_TURNS));
1128
1637
  const maxCalls = Math.max(1, Math.trunc(limits.callsPerTurn ?? DEFAULT_CALLS_PER_TURN));
1129
- /** True once the question has used what it may: no more tools run. One request is kept for the answer. */
1130
- const spent = (): boolean => (
1131
- (limits.inputTokens !== undefined && usage.totals.inputTokens >= limits.inputTokens)
1132
- || (limits.requests !== undefined && usage.totals.requests >= limits.requests - 1)
1133
- );
1638
+ const readsOfEach = limits.wholeDocumentReads ?? MAX_WHOLE_DOCUMENT_READS;
1639
+ // As the tool set reads its own count of reads of each document: whole numbers, none below 0.
1640
+ const readsInAll = Math.max(0, Math.trunc(limits.wholeReadsPerQuestion ?? DEFAULT_WHOLE_READS_PER_QUESTION));
1134
1641
  /**
1135
- * A whole-file read is many requests at once: one that would pass a ceiling of the question is
1136
- * not started. `reserved` is what the reads already let through in this turn will take: they run
1137
- * together, and the totals do not show them yet.
1642
+ * The price of a whole-file read of `meta` by the model that explores, in its own tokens and
1643
+ * requests: a read that lists items (`output: "items"`) is its parts alone; any other, its
1644
+ * parts, the merges of their notes and its answer.
1138
1645
  */
1139
- const tooCostly = (call: ToolCall, reserved: { inputTokens: number; requests: number; reads: Map<string, number> }): { refusal?: string; own?: number } => {
1140
- if (call.name !== TOOL_NAMES.analyze) return {};
1141
- const meta = searchable.find((document) => document.id === call.args.document_id);
1142
- if (!meta) return {};
1143
- // A read of a document read whole as often as it may be is refused by the tool, at no cost: it
1144
- // takes nothing from the reads of other documents.
1145
- const before = evidence.filter((shown) => shown.whole && shown.documentId === meta.id).length + (reserved.reads.get(meta.id) ?? 0);
1146
- if (before >= (limits.wholeDocumentReads ?? MAX_WHOLE_DOCUMENT_READS)) return {};
1147
- // The parts are read by the model that explores, in its own tokens.
1148
- const tokens = Math.ceil(meta.estimatedTokens * scaleOf(toolModel));
1149
- // The parts, a merge of their notes, the answer of the read, and the answer of the question.
1150
- const requests = estimateParts(meta, budget) + 3;
1151
- if (limits.inputTokens !== undefined) {
1152
- const left = Math.max(0, limits.inputTokens - usage.totals.inputTokens - reserved.inputTokens);
1153
- if (tokens > left) return { refusal: `Not run: reading all of ${meta.name} takes about ${count(tokens)} input tokens, and ${count(left)} are left of the ${count(limits.inputTokens)} this question may use. Use search_document and read_document.` };
1646
+ const priceOf = (meta: DocumentMeta, output: "answer" | "items" = "answer") => wholeReadCost(meta, budget, scaleOf(toolModel), output);
1647
+ /**
1648
+ * The ceiling on the input tokens of the question: `limits.inputTokens`, or by default the larger
1649
+ * of `DEFAULT_INPUT_TOKENS` and `toolTurns` times the first request, plus room for the
1650
+ * whole-file reads the question may make: as many as `wholeReadsPerQuestion` and the documents
1651
+ * that can be read whole allow, each at the price of the dearest of them.
1652
+ */
1653
+ const ceiling = ((): number => {
1654
+ if (limits.inputTokens !== undefined) return limits.inputTokens;
1655
+ const first = meter.current(viewFor(toolModel)).tokens * scaleOf(toolModel);
1656
+ const readable = tools.has(TOOL_NAMES.analyze) && readsOfEach > 0 ? searchable.filter((meta) => canBeReadWhole(meta, budget)) : [];
1657
+ const reads = Math.max(0, Math.min(readsInAll, readable.length * Math.trunc(readsOfEach)));
1658
+ const prices = readable.map((meta) => priceOf(meta).inputTokens).filter((price) => Number.isFinite(price));
1659
+ const allowance = prices.length > 0 ? (Number.isFinite(reads) ? reads : readable.length) * Math.max(...prices) : 0;
1660
+ return Math.max(DEFAULT_INPUT_TOKENS, maxTurns * first) + allowance;
1661
+ })();
1662
+ /** The input tokens the question has used: those the providers reported, and the estimates of those they did not. */
1663
+ const spentTokens = (): number => usage.totals.inputTokens + (usage.totals.estimatedInputTokens ?? 0);
1664
+ /**
1665
+ * True once the question has used what it may: no more tools run. One request is kept for the
1666
+ * answer. The ceiling of input tokens looks ahead: what was spent, the tool request about to be
1667
+ * sent and the answer's request after it, each as the meter counts it now, must stay within it.
1668
+ */
1669
+ const spent = (): boolean => {
1670
+ if (limits.requests !== undefined && usage.totals.requests >= limits.requests - 1) return true;
1671
+ if (!(ceiling < Number.POSITIVE_INFINITY)) return false;
1672
+ const next = meter.current(viewFor(toolModel)).tokens * scaleOf(toolModel);
1673
+ const closing = meter.current(viewFor(model)).tokens * scaleOf(model);
1674
+ return spentTokens() + next + closing > ceiling;
1675
+ };
1676
+ /**
1677
+ * The whole-file reads of the question that sent requests, by document: those that returned, and
1678
+ * those that failed after they sent them. Counted from what the tool returned, before
1679
+ * `onToolResult`: a read whose answer the hook replaced or rejected still made its requests.
1680
+ */
1681
+ const readsSent = new Map<string, number>();
1682
+ const readsMade = (documentId?: string): number => {
1683
+ if (documentId !== undefined) return readsSent.get(documentId) ?? 0;
1684
+ let made = 0;
1685
+ for (const reads of readsSent.values()) made += reads;
1686
+ return made;
1687
+ };
1688
+ /** 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. */
1689
+ const sentParts = (call: ToolCall, output: ToolResult): boolean => call.name === TOOL_NAMES.analyze
1690
+ && (evidenceOf(call, output)?.whole === true || (typeof output.error === "string" && output.error.startsWith(NOTHING_READ)));
1691
+ /** What the whole-file reads already let through in a turn will take: they run together, and the totals do not show them yet. */
1692
+ type Reserved = { inputTokens: number; requests: number; reads: Map<string, number> };
1693
+ /**
1694
+ * True when no whole-file read of `meta` is left, past those of `reserved`: the tool refuses one
1695
+ * itself, at no cost, with its own reason (such as a read that failed earlier). The tool set says
1696
+ * how many reads are left; one of your own that does not is read by what the reads of this
1697
+ * question returned.
1698
+ */
1699
+ const noReadLeft = (meta: DocumentMeta, reserved: Reserved): boolean => {
1700
+ const inTurn = reserved.reads.get(meta.id) ?? 0;
1701
+ const left = tools.wholeReadsLeft?.(meta.id);
1702
+ return typeof left === "number" ? left - inTurn <= 0 : readsMade(meta.id) + inTurn >= readsOfEach;
1703
+ };
1704
+ /**
1705
+ * What a whole-file read of `meta` takes, and why the question would not start it now, past the
1706
+ * reads of `reserved`: its whole reads made, or a ceiling it would pass. Not the tool's own
1707
+ * reasons (`noReadLeft`). `output` is the read's own: a read that lists items ("items") is
1708
+ * priced at its parts alone, any other ("answer") at its parts, merges and answer.
1709
+ */
1710
+ const readNeeds = (meta: DocumentMeta, reserved: Reserved, output: "answer" | "items"): { refusal?: string; tokens: number; requests: number } => {
1711
+ // The parts are read by the model that explores, in its own tokens: their lines numbered, the
1712
+ // prompts, and the merges of their notes (`wholeReadCost`). A read that lists items sends its
1713
+ // parts alone, with the rules of a list.
1714
+ const items = output === "items";
1715
+ const price = priceOf(meta, output).inputTokens;
1716
+ const tokens = Number.isFinite(price) ? price : Math.ceil(meta.estimatedTokens * scaleOf(toolModel));
1717
+ // The parts, a merge of their notes, the answer of the read, and the answer of the question;
1718
+ // for a list of items, the parts and the answer of the question.
1719
+ const requests = estimateParts(meta, budget) + (items ? 1 : 3);
1720
+ const allReserved = [...reserved.reads.values()].reduce((sum, reads) => sum + reads, 0);
1721
+ if (readsMade() + allReserved >= readsInAll) {
1722
+ 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}.` };
1723
+ }
1724
+ if (ceiling < Number.POSITIVE_INFINITY) {
1725
+ const left = Math.max(0, ceiling - spentTokens() - reserved.inputTokens);
1726
+ if (tokens > left) 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.` };
1154
1727
  }
1155
1728
  if (limits.requests !== undefined) {
1156
1729
  const left = Math.max(0, limits.requests - usage.totals.requests - reserved.requests);
1157
- if (requests > left) return { refusal: `Not run: reading all of ${meta.name} takes about ${count(requests)} model requests, and ${count(left)} are left of the ${count(limits.requests)} this question may make. Use search_document and read_document.` };
1730
+ if (requests > left) 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.` };
1158
1731
  }
1732
+ return { tokens, requests };
1733
+ };
1734
+ /**
1735
+ * A whole-file read is many requests at once: one that would pass a ceiling of the question is
1736
+ * not started. `reserved` is what the reads already let through in this turn will take.
1737
+ */
1738
+ const tooCostly = (call: ToolCall, reserved: Reserved): { refusal?: string; own?: number } => {
1739
+ if (call.name !== TOOL_NAMES.analyze) return {};
1740
+ const meta = searchable.find((document) => document.id === call.args.document_id);
1741
+ // A read of a document read whole as often as it may be takes nothing from the reads of other documents.
1742
+ if (!meta || noReadLeft(meta, reserved)) return {};
1743
+ const { refusal, tokens, requests } = readNeeds(meta, reserved, call.args.output === "items" ? "items" : "answer");
1744
+ if (refusal) return { refusal };
1159
1745
  reserved.inputTokens += tokens;
1160
1746
  // The answer of the question is one request, whatever number of reads come before it.
1161
1747
  reserved.requests += requests - 1;
1162
1748
  reserved.reads.set(meta.id, (reserved.reads.get(meta.id) ?? 0) + 1);
1163
- // The read's own requests: its parts, a merge of their notes, and its answer.
1749
+ // The read's own requests: its parts, a merge of their notes, and its answer; or its parts.
1164
1750
  return { own: requests - 1 };
1165
1751
  };
1752
+ /**
1753
+ * The requests a whole-file read of the document of a `read_document` call may make
1754
+ * (`ToolCallLimits.maxRequests`), judged as on the next turn, the first the model can call it on:
1755
+ * with the reads of this turn reserved, and that turn's request, of the conversation with
1756
+ * `pending` at least (its results are not in it yet). 0 when the question would not start one
1757
+ * then (`noReadLeft`, `readNeeds`), so that a read cut short of its range does not point at it
1758
+ * (`whole_file`); what is left of `limits.requests` with one kept for the answer, when that is
1759
+ * set; undefined otherwise.
1760
+ */
1761
+ const wholeReadRequests = (call: ToolCall, reserved: Reserved, pending: ModelToolRound): number | undefined => {
1762
+ const meta = searchable.find((document) => document.id === call.args.document_id);
1763
+ if (!meta) return undefined;
1764
+ const nextTurn = meter.current(viewFor(toolModel, [...messages, pending])).tokens * scaleOf(toolModel);
1765
+ const later: Reserved = { ...reserved, inputTokens: reserved.inputTokens + nextTurn, requests: reserved.requests + 1 };
1766
+ // The hint points at a read that gives an answer, the dearer of the two kinds.
1767
+ if (noReadLeft(meta, later) || readNeeds(meta, later, "answer").refusal !== undefined) return 0;
1768
+ return limits.requests === undefined ? undefined : Math.max(0, limits.requests - usage.totals.requests - 1 - later.requests);
1769
+ };
1166
1770
  /**
1167
1771
  * A pointer for a call whose result is already in the conversation, in full: an earlier result
1168
1772
  * (of this question or of one before it) holds what this one would return. The files do not
@@ -1175,7 +1779,7 @@ async function ask(options: AskOptions, carried: Carried | undefined, state: Run
1175
1779
  if (!isRound(message)) continue;
1176
1780
  // The rounds before `asked` are those of earlier questions, which an older version may have written.
1177
1781
  for (const answer of message.answers) {
1178
- const pointer = alreadyShown(call, answer, at < asked);
1782
+ const pointer = pointerTo(call, answer, at < asked);
1179
1783
  if (pointer) return pointer;
1180
1784
  }
1181
1785
  }
@@ -1192,6 +1796,19 @@ async function ask(options: AskOptions, carried: Carried | undefined, state: Run
1192
1796
  const toolRole: RequestRole = explorer ? "explorer" : "tools";
1193
1797
  /** A call as one line of plain text. An unknown tool's name is quoted and cut: no step starts with what the model chose, at any length. */
1194
1798
  const labelOf = (call: ToolCall): string => stepLine(tools.has(call.name) ? tools.describe(call.name, call.args) : `Call ${unknownToolName(call.name)}`);
1799
+ // The tools are there only for tables sent whole (`inlineTables`): without them, the question
1800
+ // would be the one request of 0.9 (and of "text"). It is still that, without the tools, the
1801
+ // line that says to count with them, or a notice, when not one tool turn fits: a ceiling or a
1802
+ // count of requests sized for that one request, or `toolTurns: 1`.
1803
+ const tablesOnly = !explorer && searchable.length === 0 && viewable.length === 0;
1804
+ if (tablesOnly && (1 + (carried?.answered ?? 0) >= maxTurns || spent())) {
1805
+ const plainLine = inlineInstruction({ plan: prepared.plan }, numbered);
1806
+ const plain = [options.system?.trim(), prepared.instruction, plainLine, missingLine].filter(Boolean).join("\n\n");
1807
+ // Its estimate, for a provider that reports no usage: no declarations, its own line.
1808
+ meter.fixed.tokens += -estimateTokens(sentTools) - (inlineLine ? estimateTokens(inlineLine) : 0) + (plainLine ? estimateTokens(plainLine) : 0);
1809
+ meter.fixed.bytes += -Buffer.byteLength(sentTools) - (inlineLine ? jsonBytes(inlineLine) : 0) + (plainLine ? jsonBytes(plainLine) : 0);
1810
+ return answer(wrote(await send(model, () => ({ system: plain, messages }), true, { role: "answer", purpose: "direct" })));
1811
+ }
1195
1812
  for (let round = 1 + (carried?.answered ?? 0); round < maxTurns && !outOfRoom; round++) {
1196
1813
  if (spent()) {
1197
1814
  budgetReached();
@@ -1205,7 +1822,9 @@ async function ask(options: AskOptions, carried: Carried | undefined, state: Run
1205
1822
  // It is a request of the chat like any other: it takes a tool turn, and the last turn is still the answer's.
1206
1823
  if (reply.calls.length === 0 && nudges < MOST_NUDGES && round + 1 < maxTurns && !reply.blockReason && !spent()) {
1207
1824
  const malformed = reply.finish === "malformed_call";
1208
- const empty = !reply.text.trim() && callsAnswered === 0 && reply.finish !== "cut" && reply.finish !== "filtered";
1825
+ // Not a reply that a filter, the output limit or another reason that asking again does not
1826
+ // mend ended ("other": Gemini's OTHER, LANGUAGE): it would only end the same way.
1827
+ const empty = !reply.text.trim() && callsAnswered === 0 && reply.finish !== "cut" && reply.finish !== "filtered" && reply.finish !== "other";
1209
1828
  if (malformed || empty) {
1210
1829
  nudges++;
1211
1830
  round++;
@@ -1217,8 +1836,15 @@ async function ask(options: AskOptions, carried: Carried | undefined, state: Run
1217
1836
  }
1218
1837
  if (reply.calls.length === 0) {
1219
1838
  // Text from this turn is the answer. A remark made earlier, before a tool call, is not.
1220
- // Neither is anything an explorer model writes: the answer is asked for below.
1221
- answered = wrote(reply) && !explorer;
1839
+ // Neither is anything an explorer model writes: the answer is asked for below. Nor the
1840
+ // remark of a turn whose tool call could not be read ("Let me look at the errors."), on
1841
+ // the last tool turn or after its nudge: the answer is asked for below.
1842
+ answered = wrote(reply) && !explorer && reply.finish !== "malformed_call";
1843
+ // Over tables sent whole alone, a reply that a filter or another reason that asking again
1844
+ // does not mend ended ("other"), or one cut at the output limit before any text, ends the
1845
+ // question, as it ends the direct request of 0.9: the request for the answer would send
1846
+ // the whole tables again, only to end the same way.
1847
+ if (tablesOnly && !answered && (reply.finish === "filtered" || reply.finish === "other" || reply.finish === "cut")) return answer(false);
1222
1848
  break;
1223
1849
  }
1224
1850
  const pending: ModelToolRound = { role: "tools", calls: reply.calls, answers: [], ...(reply.raw !== undefined ? { raw: reply.raw } : {}) };
@@ -1241,6 +1867,10 @@ async function ask(options: AskOptions, carried: Carried | undefined, state: Run
1241
1867
  const label = labelOf(call);
1242
1868
  // A call that did not arrive whole is not run: the model is told, and can send it again.
1243
1869
  if (call.problem) return { call, label, refusal: call.problem };
1870
+ // Nor a call of a tool the question does not have: it is told which there are, and its
1871
+ // answer takes no room (a turn of unknown calls made room for each of them, at the cap of
1872
+ // a result, and shortened the results of earlier turns for nothing).
1873
+ if (!tools.has(call.name)) return { call, label, refusal: unknownTool(call.name, declarations.map((declaration) => declaration.name)) };
1244
1874
  // A look at pages returns a file and a few words: the file has its own room, worked out when it runs.
1245
1875
  if (call.name === TOOL_NAMES.view) return { call, label };
1246
1876
  const key = toolCallKey(call.name, call.args);
@@ -1263,21 +1893,31 @@ async function ask(options: AskOptions, carried: Carried | undefined, state: Run
1263
1893
  const slack = Math.max(0, limits.requests - usage.totals.requests - 1 - reserved.requests);
1264
1894
  for (const plan of reads) plan.limits = { ...plan.limits, maxRequests: plan.own! + Math.floor(slack / reads.length) };
1265
1895
  }
1896
+ // A read of lines points at a whole read of its file only when the question would start one
1897
+ // on the next turn, past the whole reads of this turn: each is told the requests one may make.
1898
+ for (const plan of planned) {
1899
+ if (plan.refusal || plan.call.name !== TOOL_NAMES.read) continue;
1900
+ const most = wholeReadRequests(plan.call, reserved, pending);
1901
+ if (most !== undefined) plan.limits = { ...plan.limits, maxRequests: most };
1902
+ }
1266
1903
  // The calls that return text, and the most they may return: a call that is refused, or
1267
1904
  // answered with a pointer to what is already shown, needs no room.
1268
1905
  const sized = planned.filter((plan) => !plan.refusal && !plan.pointer && plan.call.name !== TOOL_NAMES.view);
1269
- const needed = sized.reduce((sum, plan) => sum + most(plan.call), 0);
1270
- let left = room(pending);
1906
+ // The room is in tokens, and each result takes those of its document's characters.
1907
+ const rateOf = (call: ToolCall) => 1 / charactersPerToken(metaOf(call.args.document_id));
1908
+ const sizedRates = sized.map((plan) => rateOf(plan.call));
1909
+ const needed = sized.reduce((sum, plan, index) => sum + most(plan.call) * sizedRates[index]!, 0);
1910
+ let left = room(pending, sizedRates);
1271
1911
  let dropped = false;
1272
1912
  for (const keep of canShrink ? ROUNDS_KEPT : []) {
1273
1913
  if (left >= needed) break;
1274
1914
  if (shrink(keep)) {
1275
1915
  dropped = true;
1276
- left = room(pending);
1916
+ left = room(pending, sizedRates);
1277
1917
  }
1278
1918
  }
1279
1919
  if (dropped) {
1280
- step("Older tool results were shortened to make room in the request", "results_shortened");
1920
+ step(RESULTS_SHORTENED, "results_shortened");
1281
1921
  // A result that was shortened is no longer shown in full: a call that pointed to it is run after all.
1282
1922
  for (const plan of planned) {
1283
1923
  if (!plan.earlier) continue;
@@ -1295,10 +1935,14 @@ async function ask(options: AskOptions, carried: Carried | undefined, state: Run
1295
1935
  // The room is shared by those calls. A result is most often far smaller than its cap, so a call
1296
1936
  // that was given its whole cap first could leave none for the next ones, and a turn of small
1297
1937
  // searches ended the question.
1298
- const shares = shareRoom(runsNow.map((plan) => most(plan.call)), left);
1938
+ const runRates = runsNow.map((plan) => rateOf(plan.call));
1939
+ const shares = shareRoom(runsNow.map((plan) => most(plan.call)), left, runRates);
1940
+ /** The tokens of room each call that runs was given, by its index in the turn. */
1941
+ const given = new Map<number, number>();
1299
1942
  runsNow.forEach((plan, index) => {
1300
1943
  const share = shares[index];
1301
1944
  const cap = most(plan.call);
1945
+ if (share !== undefined) given.set(planned.indexOf(plan), share * runRates[index]!);
1302
1946
  if (share === undefined) {
1303
1947
  if (!outOfRoom) notice("no_room", "There is no room left in this conversation for another tool result.");
1304
1948
  outOfRoom = true;
@@ -1423,6 +2067,8 @@ async function ask(options: AskOptions, carried: Carried | undefined, state: Run
1423
2067
  end,
1424
2068
  };
1425
2069
  };
2070
+ /** A look of this turn waited `pageLookWaitMs` and was told the server is busy: the others do not wait (`maxWaitMs`). */
2071
+ let pagesBusy = false;
1426
2072
  /**
1427
2073
  * The listeners of one call: its progress goes to `onActivity` as before (in place of the
1428
2074
  * tool set's shared listener) and is told apart by call in the events, with its requests.
@@ -1433,6 +2079,16 @@ async function ask(options: AskOptions, carried: Carried | undefined, state: Run
1433
2079
  if (openCalls.has(index)) events.emit({ type: "tool.progress", callId: callIds[index]!, stage: event.kind, done: event.done, total: event.total, message: event.message });
1434
2080
  }),
1435
2081
  ...(events.active ? { onRequest: (start: ToolRequestStart) => readerRequest(index, start) } : {}),
2082
+ // Notices of the question, not steps: the call's own step says what the model was told.
2083
+ onDocumentGone: (id) => tell(() => {
2084
+ if (gone.has(id)) return;
2085
+ gone.add(id);
2086
+ notice("document_gone", `${nameOf(id) ?? "A file"} is no longer available on the server.`, [id]);
2087
+ }),
2088
+ onPagesBusy: (id) => {
2089
+ pagesBusy = true;
2090
+ 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]));
2091
+ },
1436
2092
  });
1437
2093
 
1438
2094
  // The calls of a turn run together, a few at a time. Looks at pages take their turns, one
@@ -1455,7 +2111,12 @@ async function ask(options: AskOptions, carried: Carried | undefined, state: Run
1455
2111
  requestBytes = toolModel.requestBytes?.(waiting) ?? meter.estimate(waiting.messages).bytes;
1456
2112
  }
1457
2113
  // Base64 turns three bytes into four characters.
1458
- const output = await tools.executeWithFiles(call.name, call.args, { maxFileBytes: Math.floor((maxRequestBytes - bytesKeptFree - requestBytes) * 3 / 4), maxPages: pagesLeft });
2114
+ const output = await until(tools.executeWithFiles(call.name, call.args, {
2115
+ maxFileBytes: Math.floor((maxRequestBytes - bytesKeptFree - requestBytes) * 3 / 4),
2116
+ maxPages: pagesLeft,
2117
+ // 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.
2118
+ ...(pagesBusy ? { maxWaitMs: 0 } : {}),
2119
+ }, hooksFor(index)), halt.signal);
1459
2120
  for (const file of output.files) requestBytes += Math.ceil(file.bytes.length / 3) * 4 + 512;
1460
2121
  if (output.files.length > 0) pagesLeft -= pagesShown(output.result);
1461
2122
  return output;
@@ -1469,7 +2130,9 @@ async function ask(options: AskOptions, carried: Carried | undefined, state: Run
1469
2130
  halt.signal.throwIfAborted();
1470
2131
  options.onActivity?.(`${label}…`);
1471
2132
  startTool(index, call, label);
1472
- return await tools.executeWithFiles(call.name, call.args, callLimits, hooksFor(index));
2133
+ // The question stops when its signal aborts, whether the tool set does or not: a store
2134
+ // call that hangs inside a tool of any `LargeFiles` must not hold it.
2135
+ return await until(tools.executeWithFiles(call.name, call.args, callLimits, hooksFor(index)), halt.signal);
1473
2136
  } finally {
1474
2137
  release();
1475
2138
  }
@@ -1487,6 +2150,54 @@ async function ask(options: AskOptions, carried: Carried | undefined, state: Run
1487
2150
  outputs.push(output);
1488
2151
  }
1489
2152
 
2153
+ /**
2154
+ * The application's say on what the model gets (`onToolResult`): each call's verdict, asked
2155
+ * for as soon as its result is in, so that the hooks of a turn run at the same time. They are
2156
+ * applied below, in call order, before the result is fitted to the room in the request, and
2157
+ * before the evidence, the step and the events, which all tell what the model was sent.
2158
+ * `raw` is what the tool returned; `output`, what the hook let through. A call made twice in
2159
+ * the turn is given the verdict of its first (`copied`): no pointer to a result the hook
2160
+ * replaced or rejected. A hook that fails ends the turn at once.
2161
+ */
2162
+ type Judged = { raw: ToolOutput; output: ToolOutput; judged?: ToolOutcome; copied?: boolean };
2163
+ const hook = options.onToolResult;
2164
+ const judgedOutputs: Array<Promise<Judged>> = [];
2165
+ for (const [index, { call, refusal, pointer, twinOf }] of planned.entries()) {
2166
+ const raw = outputs[index]!;
2167
+ let judging: Promise<Judged>;
2168
+ if (hook && pointer && twinOf !== undefined) {
2169
+ judging = Promise.all([raw, judgedOutputs[twinOf]!]).then(([own, first]): Judged => (first.judged
2170
+ ? { raw: own, output: { result: first.output.result, files: [] }, judged: first.judged, copied: true }
2171
+ : { raw: own, output: own }));
2172
+ } else if (hook && !refusal && !pointer) {
2173
+ judging = raw.then(async (own): Promise<Judged> => {
2174
+ const context: ToolResultContext = {
2175
+ call,
2176
+ result: own.result,
2177
+ ...(typeof call.args.document_id === "string" ? { documentId: call.args.document_id } : {}),
2178
+ ...(options.owner !== undefined ? { owner: options.owner } : {}),
2179
+ ...(options.scope !== undefined ? { scope: options.scope } : {}),
2180
+ signal: halt.signal,
2181
+ };
2182
+ let verdict: ToolResultVerdict | undefined;
2183
+ try {
2184
+ // A hook that does not look at the signal does not hold the question once it is stopped.
2185
+ verdict = checkedVerdict(await until(Promise.resolve().then(() => hook(context)), halt.signal));
2186
+ } catch (error) {
2187
+ halt.abort(error);
2188
+ throw error;
2189
+ }
2190
+ if (verdict && "result" in verdict) return { raw: own, output: { ...own, result: { ...verdict.result, redacted: true } }, judged: "redacted" };
2191
+ if (verdict) return { raw: own, output: { result: { error: verdict.reject }, files: [] }, judged: "refused" };
2192
+ return { raw: own, output: own };
2193
+ });
2194
+ } else {
2195
+ judging = raw.then((own): Judged => ({ raw: own, output: own }));
2196
+ }
2197
+ judging.catch(() => undefined);
2198
+ judgedOutputs.push(judging);
2199
+ }
2200
+
1490
2201
  /**
1491
2202
  * The room of each whole-file read of the turn: what the other results left, shared among the
1492
2203
  * reads, the smaller answers first. Worked out when the first of them is reached, by which time
@@ -1494,7 +2205,7 @@ async function ask(options: AskOptions, carried: Carried | undefined, state: Run
1494
2205
  */
1495
2206
  let lateRoom: Map<number, number> | undefined;
1496
2207
  const roomOfReads = async (): Promise<Map<number, number>> => {
1497
- const sizes = await Promise.all(outputs.map(async (output) => JSON.stringify((await output).result).length));
2208
+ const sizes = await Promise.all(judgedOutputs.map(async (judging) => resultTokens((await judging).output.result)));
1498
2209
  const reads = planned.flatMap((plan, index) => (plan.late ? [index] : []));
1499
2210
  let free = left - sizes.reduce((sum, size, index) => sum + (planned[index]!.late ? 0 : size), 0);
1500
2211
  const shares = new Map<number, number>();
@@ -1506,17 +2217,46 @@ async function ask(options: AskOptions, carried: Carried | undefined, state: Run
1506
2217
  return shares;
1507
2218
  };
1508
2219
 
2220
+ /**
2221
+ * The tokens the results of this turn took so far, of the calls that were given room and are
2222
+ * not whole-file reads (those are fitted to what the others left, above), and of those the
2223
+ * hook replaced. A result is cut when it would take more than the room leaves it once the
2224
+ * calls after it, and the reads, have their shares: the room shared by characters is a
2225
+ * guess, a tool set of your own may not keep to `maxResultCharacters`, and a hook may return
2226
+ * more than the tool did.
2227
+ */
2228
+ let took = 0;
2229
+ const roomFor = (index: number): number => {
2230
+ let others = 0;
2231
+ for (const [other, tokens] of given) if (other > index || planned[other]!.late) others += tokens;
2232
+ return left - took - others;
2233
+ };
2234
+
1509
2235
  // The answers in call order. Each call's `tool.end` goes out here, in the same order.
1510
2236
  for (const [index, { call, label, late, refusal, pointer }] of planned.entries()) {
1511
- let output = await outputs[index]!;
2237
+ const { raw, output: judgedOutput, judged, copied } = await judgedOutputs[index]!;
1512
2238
  if (listenerError) throw listenerError.error;
2239
+ // A hook of a later call failed: nothing more of the turn reaches the model.
2240
+ if (halt.signal.aborted) throw halt.signal.reason;
1513
2241
  callsAnswered++;
2242
+ // A whole-file read that sent its parts counts against `wholeReadsPerQuestion`, whatever the hook made of its answer.
2243
+ if (!refusal && !pointer && sentParts(call, raw.result)) {
2244
+ const id = String(call.args.document_id);
2245
+ readsSent.set(id, (readsSent.get(id) ?? 0) + 1);
2246
+ }
2247
+ let output = judgedOutput;
1514
2248
  if (late) {
1515
2249
  lateRoom ??= await roomOfReads();
1516
2250
  const share = lateRoom.get(index)!;
1517
- if (JSON.stringify(output.result).length > share) output = { ...output, result: fitAnswer(output.result, Math.max(LEAST_RESULT_CHARACTERS, share)) };
2251
+ if (resultTokens(output.result) > share) output = { ...output, result: cutToTokens(output.result, share) };
2252
+ } else if (given.has(index) || judged) {
2253
+ const fits = roomFor(index);
2254
+ if (resultTokens(output.result) > fits) output = { ...output, result: cutToTokens(output.result, fits) };
2255
+ took += resultTokens(output.result);
1518
2256
  }
1519
- if (pointer) {
2257
+ // A cut replacement is still a replacement.
2258
+ if (judged === "redacted" && output.result.redacted !== true) output = { ...output, result: { ...output.result, redacted: true } };
2259
+ if (pointer && !copied) {
1520
2260
  const line = step(`${label} — already shown above`);
1521
2261
  const sent = { ...output.result, tool_turns_left: turnsLeft };
1522
2262
  answers.push({ call, result: sent, files: [] });
@@ -1524,23 +2264,26 @@ async function ask(options: AskOptions, carried: Carried | undefined, state: Run
1524
2264
  continue;
1525
2265
  }
1526
2266
  // Two searches in a row that failed in the same mode: the second says to try another way.
1527
- if (!refusal) {
2267
+ // Read from what the tool returned; the hint goes only to a result the hook kept.
2268
+ if (!refusal && !copied) {
2269
+ const own = judged ? raw.result : output.result;
1528
2270
  const kind = failureKind(call);
1529
2271
  if (kind === undefined) {
1530
2272
  failing = undefined;
1531
- } else if (typeof output.result.error === "string") {
2273
+ } else if (typeof own.error === "string") {
1532
2274
  failing = failing?.kind === kind ? { kind, count: failing.count + 1 } : { kind, count: 1 };
1533
- if (failing.count >= 2) output = { ...output, result: { ...output.result, error: `${output.result.error} ${repeatedFailureHint(call)}` } };
2275
+ if (failing.count >= 2 && !judged) output = { ...output, result: { ...output.result, error: `${output.result.error} ${repeatedFailureHint(call)}` } };
1534
2276
  } else {
1535
2277
  failing = undefined;
1536
2278
  }
1537
2279
  }
1538
2280
  const line = step(`${label}${toolResultSummary(label, output.result)}`);
1539
- const shown = evidenceOf(call, output.result);
2281
+ // A copy of the first call's verdict shows nothing that the first did not.
2282
+ const shown = copied ? undefined : evidenceOf(call, output.result);
1540
2283
  if (shown) evidence.push({ ...shown, callId: callIds[index]! });
1541
2284
  const sent = { ...output.result, tool_turns_left: turnsLeft };
1542
2285
  answers.push({ call, result: sent, files: output.files });
1543
- const outcome: ToolOutcome = call.problem ? "error" : refusal ? "refused" : typeof output.result.error === "string" ? "error" : "ok";
2286
+ const outcome: ToolOutcome = judged ?? (call.problem ? "error" : refusal ? "refused" : typeof output.result.error === "string" ? "error" : "ok");
1544
2287
  endTool(index, outcome, sent, line, shown);
1545
2288
  }
1546
2289
  // A listener of a read that went on after its call returned (its progress).
@@ -1572,7 +2315,12 @@ async function ask(options: AskOptions, carried: Carried | undefined, state: Run
1572
2315
  // With an explorer model this request is always made: it is the one the answering model gets.
1573
2316
  if (!answered && !blockReason) {
1574
2317
  activity("writing_answer", "Writing the answer…");
1575
- let closing = searchable.length > 0 ? FINAL_ANSWER_REQUEST : FINAL_ANSWER_AFTER_PAGES;
2318
+ // With view_pages alone, the files are in the prompt and the pages were looked at. With the
2319
+ // text tools, the answer comes from what they returned, and from the files sent whole too when
2320
+ // their lines can be cited or their tables were counted: a model told "only what the tools
2321
+ // returned" said that a fact of a file shown in full was not there.
2322
+ const fromFiles = prepared.plan.inline.length > 0 && (numbered || toolable.length > 0);
2323
+ let closing = searchable.length === 0 && toolable.length === 0 ? FINAL_ANSWER_AFTER_PAGES : fromFiles ? FINAL_ANSWER_WITH_FILES : FINAL_ANSWER_REQUEST;
1576
2324
  // No tool ran (the explorer needed none, the first reply was empty, or no turn was left for
1577
2325
  // tools): there is no tool result to answer from. The answering model gets the explorer's
1578
2326
  // calls and what they returned, and nothing else of it.
@@ -1586,14 +2334,17 @@ async function ask(options: AskOptions, carried: Carried | undefined, state: Run
1586
2334
  let reply = await send(model, answerRequest(), true, { role: "answer", purpose: "closing" });
1587
2335
  // A reply with no text (empty, or a tool call the model was told not to make, or one that
1588
2336
  // could not be read) is asked for once more, with a note that is not kept: otherwise the
1589
- // question ends with nothing to show. Not after a refusal or a filter, which would come again,
1590
- // nor a reply cut off at the output limit with nothing in it, nor once a ceiling of `limits`
1591
- // is reached. It is one of the second tries of the question, and may be one request past
1592
- // `limits.toolTurns`, which counts the answer's first request.
2337
+ // question ends with nothing to show. Not after a refusal, a filter or another reason that
2338
+ // asking again does not mend ("other"), which would come again, nor a reply cut off at the
2339
+ // output limit with nothing in it, nor when it would pass a ceiling of the question: the
2340
+ // ceiling of input tokens looks ahead, as before each tool request, by what was spent and
2341
+ // what this request takes, as the meter counts it now. It is one of the second tries of the
2342
+ // question, and may be one request past `limits.toolTurns`, which counts the answer's first
2343
+ // request.
1593
2344
  const calledInstead = reply.calls.length > 0 || reply.finish === "malformed_call";
1594
- const ceilingReached = (limits.inputTokens !== undefined && usage.totals.inputTokens >= limits.inputTokens)
1595
- || (limits.requests !== undefined && usage.totals.requests >= limits.requests);
1596
- if (!wrote(reply) && !reply.blockReason && reply.finish !== "filtered" && (calledInstead || reply.finish !== "cut") && nudges < MOST_NUDGES) {
2345
+ const again = ceiling < Number.POSITIVE_INFINITY ? meter.current(viewFor(model)).tokens * scaleOf(model) : 0;
2346
+ const ceilingReached = spentTokens() + again > ceiling || (limits.requests !== undefined && usage.totals.requests >= limits.requests);
2347
+ if (!wrote(reply) && !reply.blockReason && reply.finish !== "filtered" && reply.finish !== "other" && (calledInstead || reply.finish !== "cut") && nudges < MOST_NUDGES) {
1597
2348
  if (ceilingReached) {
1598
2349
  budgetReached();
1599
2350
  } else {
@@ -1604,7 +2355,7 @@ async function ask(options: AskOptions, carried: Carried | undefined, state: Run
1604
2355
  }
1605
2356
  answered = wrote(reply);
1606
2357
  }
1607
- return result(answered);
2358
+ return answer(answered);
1608
2359
  } catch (error) {
1609
2360
  // What the question found and paid for until it failed, for the application to keep. The usage is
1610
2361
  // a copy: a part reader that went on after the question was stopped may still report its own.