llm-large-files 0.8.1 → 0.9.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 (204) hide show
  1. package/CHANGELOG.md +631 -0
  2. package/README.md +9 -10
  3. package/dist/access.d.ts +86 -0
  4. package/dist/access.d.ts.map +1 -0
  5. package/dist/access.js +131 -0
  6. package/dist/access.js.map +1 -0
  7. package/dist/ask.d.ts +45 -1
  8. package/dist/ask.d.ts.map +1 -1
  9. package/dist/ask.js +181 -20
  10. package/dist/ask.js.map +1 -1
  11. package/dist/cache.d.ts +12 -3
  12. package/dist/cache.d.ts.map +1 -1
  13. package/dist/cache.js +18 -5
  14. package/dist/cache.js.map +1 -1
  15. package/dist/encoding.js +5 -3
  16. package/dist/encoding.js.map +1 -1
  17. package/dist/error-info.d.ts +57 -0
  18. package/dist/error-info.d.ts.map +1 -0
  19. package/dist/error-info.js +217 -0
  20. package/dist/error-info.js.map +1 -0
  21. package/dist/errors.d.ts +72 -8
  22. package/dist/errors.d.ts.map +1 -1
  23. package/dist/errors.js +102 -15
  24. package/dist/errors.js.map +1 -1
  25. package/dist/events.d.ts +35 -9
  26. package/dist/events.d.ts.map +1 -1
  27. package/dist/events.js +42 -11
  28. package/dist/events.js.map +1 -1
  29. package/dist/evidence.d.ts +4 -2
  30. package/dist/evidence.d.ts.map +1 -1
  31. package/dist/evidence.js +14 -3
  32. package/dist/evidence.js.map +1 -1
  33. package/dist/extract.d.ts +32 -8
  34. package/dist/extract.d.ts.map +1 -1
  35. package/dist/extract.js +46 -35
  36. package/dist/extract.js.map +1 -1
  37. package/dist/gemini/adapter.d.ts +19 -3
  38. package/dist/gemini/adapter.d.ts.map +1 -1
  39. package/dist/gemini/adapter.js +84 -12
  40. package/dist/gemini/adapter.js.map +1 -1
  41. package/dist/gemini/chat.d.ts +18 -6
  42. package/dist/gemini/chat.d.ts.map +1 -1
  43. package/dist/gemini/chat.js +2 -0
  44. package/dist/gemini/chat.js.map +1 -1
  45. package/dist/gemini/index.d.ts +1 -1
  46. package/dist/gemini/index.d.ts.map +1 -1
  47. package/dist/index.d.ts +9 -6
  48. package/dist/index.d.ts.map +1 -1
  49. package/dist/index.js +4 -3
  50. package/dist/index.js.map +1 -1
  51. package/dist/ingest.d.ts +70 -0
  52. package/dist/ingest.d.ts.map +1 -0
  53. package/dist/ingest.js +868 -0
  54. package/dist/ingest.js.map +1 -0
  55. package/dist/library.d.ts +176 -34
  56. package/dist/library.d.ts.map +1 -1
  57. package/dist/library.js +332 -512
  58. package/dist/library.js.map +1 -1
  59. package/dist/limiter.d.ts +2 -2
  60. package/dist/limiter.js +2 -2
  61. package/dist/map-reduce.js +3 -3
  62. package/dist/map-reduce.js.map +1 -1
  63. package/dist/model.d.ts +43 -2
  64. package/dist/model.d.ts.map +1 -1
  65. package/dist/model.js +63 -3
  66. package/dist/model.js.map +1 -1
  67. package/dist/node/handlers.d.ts +234 -7
  68. package/dist/node/handlers.d.ts.map +1 -1
  69. package/dist/node/handlers.js +482 -121
  70. package/dist/node/handlers.js.map +1 -1
  71. package/dist/node/index.d.ts +3 -2
  72. package/dist/node/index.d.ts.map +1 -1
  73. package/dist/node/index.js +2 -1
  74. package/dist/node/index.js.map +1 -1
  75. package/dist/node/ingest-child.d.ts +7 -1
  76. package/dist/node/ingest-child.d.ts.map +1 -1
  77. package/dist/node/ingest-child.js +18 -3
  78. package/dist/node/ingest-child.js.map +1 -1
  79. package/dist/node/isolated.d.ts +3 -1
  80. package/dist/node/isolated.d.ts.map +1 -1
  81. package/dist/node/isolated.js +11 -4
  82. package/dist/node/isolated.js.map +1 -1
  83. package/dist/node/originals.d.ts +19 -0
  84. package/dist/node/originals.d.ts.map +1 -0
  85. package/dist/node/originals.js +82 -0
  86. package/dist/node/originals.js.map +1 -0
  87. package/dist/node/spool.d.ts +102 -0
  88. package/dist/node/spool.d.ts.map +1 -0
  89. package/dist/node/spool.js +365 -0
  90. package/dist/node/spool.js.map +1 -0
  91. package/dist/node/sse.d.ts +4 -3
  92. package/dist/node/sse.d.ts.map +1 -1
  93. package/dist/node/sse.js +7 -6
  94. package/dist/node/sse.js.map +1 -1
  95. package/dist/pdf-layout.d.ts.map +1 -1
  96. package/dist/pdf-layout.js +71 -12
  97. package/dist/pdf-layout.js.map +1 -1
  98. package/dist/ranged.d.ts +22 -11
  99. package/dist/ranged.d.ts.map +1 -1
  100. package/dist/ranged.js +50 -12
  101. package/dist/ranged.js.map +1 -1
  102. package/dist/retry.d.ts +3 -1
  103. package/dist/retry.d.ts.map +1 -1
  104. package/dist/retry.js +6 -2
  105. package/dist/retry.js.map +1 -1
  106. package/dist/scope.d.ts +25 -0
  107. package/dist/scope.d.ts.map +1 -0
  108. package/dist/scope.js +60 -0
  109. package/dist/scope.js.map +1 -0
  110. package/dist/source.d.ts +60 -0
  111. package/dist/source.d.ts.map +1 -0
  112. package/dist/source.js +170 -0
  113. package/dist/source.js.map +1 -0
  114. package/dist/stores.d.ts +120 -31
  115. package/dist/stores.d.ts.map +1 -1
  116. package/dist/stores.js +582 -139
  117. package/dist/stores.js.map +1 -1
  118. package/dist/testing/fake-fetch.d.ts +31 -0
  119. package/dist/testing/fake-fetch.d.ts.map +1 -0
  120. package/dist/testing/fake-fetch.js +66 -0
  121. package/dist/testing/fake-fetch.js.map +1 -0
  122. package/dist/testing/fake-model.d.ts +38 -0
  123. package/dist/testing/fake-model.d.ts.map +1 -0
  124. package/dist/testing/fake-model.js +62 -0
  125. package/dist/testing/fake-model.js.map +1 -0
  126. package/dist/testing/index.d.ts +7 -0
  127. package/dist/testing/index.d.ts.map +1 -0
  128. package/dist/testing/index.js +9 -0
  129. package/dist/testing/index.js.map +1 -0
  130. package/dist/testing/store-checks.d.ts +72 -0
  131. package/dist/testing/store-checks.d.ts.map +1 -0
  132. package/dist/testing/store-checks.js +619 -0
  133. package/dist/testing/store-checks.js.map +1 -0
  134. package/dist/tools.d.ts +25 -0
  135. package/dist/tools.d.ts.map +1 -1
  136. package/dist/tools.js +135 -13
  137. package/dist/tools.js.map +1 -1
  138. package/dist/types.d.ts +116 -13
  139. package/dist/types.d.ts.map +1 -1
  140. package/docs/README.md +17 -8
  141. package/docs/getting-started.md +18 -13
  142. package/docs/guides/anthropic.md +12 -8
  143. package/docs/guides/conversations.md +112 -47
  144. package/docs/guides/costs-and-limits.md +16 -7
  145. package/docs/guides/deployment.md +309 -87
  146. package/docs/guides/errors-and-reliability.md +161 -23
  147. package/docs/guides/own-adapter-and-loop.md +27 -10
  148. package/docs/guides/pdfs.md +123 -29
  149. package/docs/guides/storage.md +634 -143
  150. package/docs/guides/testing.md +78 -129
  151. package/docs/guides/vertex-and-gemini.md +10 -7
  152. package/docs/guides/web-app.md +322 -77
  153. package/docs/how-it-works.md +35 -8
  154. package/docs/measurements.md +63 -8
  155. package/docs/publishing.md +112 -36
  156. package/docs/reference/ask.md +154 -13
  157. package/docs/reference/errors-and-retries.md +166 -14
  158. package/docs/reference/events.md +53 -20
  159. package/docs/reference/gemini.md +70 -21
  160. package/docs/reference/library.md +709 -165
  161. package/docs/reference/node.md +633 -104
  162. package/docs/reference/testing.md +311 -0
  163. package/docs/reference/tools.md +15 -5
  164. package/docs/security.md +316 -70
  165. package/docs/troubleshooting.md +165 -58
  166. package/docs/upgrading-0.9.md +890 -0
  167. package/package.json +12 -3
  168. package/src/access.ts +144 -0
  169. package/src/ask.ts +230 -19
  170. package/src/cache.ts +20 -5
  171. package/src/encoding.ts +6 -4
  172. package/src/error-info.ts +255 -0
  173. package/src/errors.ts +129 -15
  174. package/src/events.ts +86 -21
  175. package/src/evidence.ts +14 -3
  176. package/src/extract.ts +50 -33
  177. package/src/gemini/adapter.ts +97 -11
  178. package/src/gemini/chat.ts +20 -6
  179. package/src/gemini/index.ts +1 -1
  180. package/src/index.ts +9 -6
  181. package/src/ingest.ts +927 -0
  182. package/src/library.ts +482 -523
  183. package/src/limiter.ts +2 -2
  184. package/src/map-reduce.ts +3 -3
  185. package/src/model.ts +69 -5
  186. package/src/node/handlers.ts +691 -117
  187. package/src/node/index.ts +13 -2
  188. package/src/node/ingest-child.ts +23 -5
  189. package/src/node/isolated.ts +11 -4
  190. package/src/node/originals.ts +78 -0
  191. package/src/node/spool.ts +365 -0
  192. package/src/node/sse.ts +7 -6
  193. package/src/pdf-layout.ts +69 -11
  194. package/src/ranged.ts +42 -14
  195. package/src/retry.ts +6 -2
  196. package/src/scope.ts +63 -0
  197. package/src/source.ts +178 -0
  198. package/src/stores.ts +635 -140
  199. package/src/testing/fake-fetch.ts +80 -0
  200. package/src/testing/fake-model.ts +78 -0
  201. package/src/testing/index.ts +11 -0
  202. package/src/testing/store-checks.ts +660 -0
  203. package/src/tools.ts +150 -14
  204. package/src/types.ts +106 -13
package/dist/ask.js CHANGED
@@ -4,7 +4,8 @@ import { eventErrorOf, EventEmitter, eventStream, newRunId } from "./events.js";
4
4
  import { evidenceOf, stubResult } from "./evidence.js";
5
5
  import { isCutReply, until } from "./http.js";
6
6
  import { Limiter } from "./limiter.js";
7
- import { DocumentsNotFoundError, errorKindOf, laterResult, rateAllowanceOf, UsageMeter, } from "./model.js";
7
+ import { DocumentsNotFoundError, errorKindOf, laterResult, modelErrorOf, rateAllowanceOf, TOOL_TURN_VERSION, UsageMeter, } from "./model.js";
8
+ import { DocumentStoreError } from "./errors.js";
8
9
  import { estimateParts, REQUEST_BYTES_MARGIN } from "./plan.js";
9
10
  import { statusOf, withRetry } from "./retry.js";
10
11
  import { estimateTokens, jsonBytes, wellFormedJson } from "./text.js";
@@ -23,6 +24,75 @@ export const FINAL_ANSWER_WITHOUT_TOOLS = "Answer my question now, from what is
23
24
  * needs, and the other model writes the answer.
24
25
  */
25
26
  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.";
27
+ /** The line added to the system instruction when `count` documents were left out ("drop"). */
28
+ const missingFilesLine = (count) => (count === 1
29
+ ? "1 of the attached files is no longer available; say so if the question needs it."
30
+ : `${count} of the attached files are no longer available; say so if the question needs them.`);
31
+ /** A value as an error quotes it. */
32
+ const shownValue = (value) => (typeof value === "string" ? JSON.stringify(value) : value === null ? "null" : typeof value);
33
+ /** `onMissingDocuments` checked: a value it cannot be is an error before anything is planned. */
34
+ function checkMissingPolicy(given) {
35
+ if (given === undefined || given === "throw" || given === "drop" || typeof given === "function")
36
+ return;
37
+ throw new TypeError(`onMissingDocuments must be "throw", "drop" or a function, and is ${shownValue(given)}.`);
38
+ }
39
+ /** An object made as `{}` or `Object.create(null)` is: not a Map, an array or an instance of a class. */
40
+ const isPlainObject = (value) => {
41
+ if (value === null || typeof value !== "object")
42
+ return false;
43
+ const prototype = Object.getPrototypeOf(value);
44
+ return prototype === Object.prototype || prototype === null;
45
+ };
46
+ /** What a function of `onMissingDocuments` returned, checked. */
47
+ function checkedAction(action) {
48
+ if (action === "throw" || action === "drop")
49
+ return action;
50
+ // Only the keys of an action: a key it does not have is a mistake, not something to ignore.
51
+ if (action !== null && typeof action === "object" && Object.keys(action).every((key) => key === "retry" || key === "replace")) {
52
+ const { retry, replace } = action;
53
+ if (retry === true && replace === undefined)
54
+ return { retry: true };
55
+ if (retry === undefined && isPlainObject(replace) && Object.values(replace).every((id) => typeof id === "string" && id.length > 0)) {
56
+ return { replace: { ...replace } };
57
+ }
58
+ }
59
+ throw new TypeError(`onMissingDocuments returned ${shownValue(action)}: it must return "throw", "drop", { retry: true } or { replace: { [oldId]: newId } }.`);
60
+ }
61
+ /**
62
+ * Plans the documents `ids`, and settles those that are missing as `onMissingDocuments` says. A
63
+ * retry or a replace plans them again, once.
64
+ */
65
+ async function planDocumentsOf(options, ids, prepare) {
66
+ const prepared = await prepare(ids);
67
+ if (prepared.missing.length === 0)
68
+ return { prepared, documentIds: ids, dropped: [] };
69
+ const policy = options.onMissingDocuments ?? "throw";
70
+ let action = policy === "drop" ? "drop" : "throw";
71
+ if (typeof policy === "function") {
72
+ options.signal?.throwIfAborted();
73
+ const context = {
74
+ ...(options.owner !== undefined ? { owner: options.owner } : {}),
75
+ ...(options.scope !== undefined ? { scope: options.scope } : {}),
76
+ ...(options.signal ? { signal: options.signal } : {}),
77
+ };
78
+ // A function that does not look at the signal does not hold the question once it is stopped.
79
+ action = checkedAction(await until(policy([...prepared.missing], context), options.signal));
80
+ }
81
+ if (action === "throw")
82
+ throw new DocumentsNotFoundError(prepared.missing);
83
+ if (action === "drop") {
84
+ const gone = new Set(prepared.missing);
85
+ return { prepared, documentIds: ids.filter((id) => !gone.has(id)), dropped: [...prepared.missing] };
86
+ }
87
+ const replace = "replace" in action ? action.replace : {};
88
+ const again = ids.map((id) => (Object.hasOwn(replace, id) ? replace[id] : id));
89
+ const second = await prepare(again);
90
+ if (second.missing.length > 0)
91
+ throw new DocumentsNotFoundError(second.missing);
92
+ return { prepared: second, documentIds: again, dropped: [] };
93
+ }
94
+ /** The step of a question whose older tool results were shortened to make room. */
95
+ const RESULTS_SHORTENED = "Older tool results were shortened to make room in the request";
26
96
  const DEFAULT_TOOL_TURNS = 12;
27
97
  const DEFAULT_CALLS_PER_TURN = 8;
28
98
  /** Tool calls of one turn that run at the same time. */
@@ -64,10 +134,28 @@ function pagesShown(result) {
64
134
  * character in it (0.5.0 cut some search windows inside an emoji, and Claude's API refuses them).
65
135
  */
66
136
  const carriedResult = (result) => wellFormedJson(laterResult(result));
67
- /** The conversation as the loop keeps it: copies, so that nothing of the caller's is changed. */
137
+ /**
138
+ * Refuses a stored tool round of a version this package does not read: one a newer version made
139
+ * (`ToolTurn.version` above `TOOL_TURN_VERSION`). A round without a version (before 0.9.0) is read
140
+ * as before. A `TypeError`, which an application can catch to leave such rounds out.
141
+ */
142
+ function checkToolTurnVersion(turn) {
143
+ const version = turn.version ?? 0;
144
+ if (typeof version === "number" && version <= TOOL_TURN_VERSION)
145
+ return;
146
+ if (typeof version !== "number" || Number.isNaN(version)) {
147
+ 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.`);
148
+ }
149
+ 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.`);
150
+ }
151
+ /**
152
+ * The conversation as the loop keeps it: copies, so that nothing of the caller's is changed. Of a
153
+ * stored tool round, only the calls are kept: its version is not sent to the model.
154
+ */
68
155
  function toMessages(given) {
69
156
  const messages = given.map((message) => {
70
157
  if (message.role === "tools") {
158
+ checkToolTurnVersion(message);
71
159
  const answers = message.calls.map(({ result, ...call }) => ({ call, result: carriedResult(result) }));
72
160
  return { role: "tools", calls: answers.map((answer) => answer.call), answers };
73
161
  }
@@ -88,7 +176,9 @@ function textSize(messages, system) {
88
176
  for (const part of message.parts) {
89
177
  if (typeof part.text === "string") {
90
178
  tokens += estimateTokens(part.text);
91
- bytes += jsonBytes(part.text);
179
+ // A part in the provider's own form is sent whole: its text, and what is next to it (a
180
+ // thought signature), or the call that the text stands for.
181
+ bytes += part.native === undefined ? jsonBytes(part.text) : Math.max(jsonBytes(part.text), (JSON.stringify(part.native) ?? "").length);
92
182
  }
93
183
  else {
94
184
  const size = (JSON.stringify(part.native) ?? "").length;
@@ -385,7 +475,9 @@ async function askPlanned(options, state) {
385
475
  // Failed before it sent anything (a budget of the application's that cannot work with the
386
476
  // smaller window): the provider's error, with what the first try found, is the one to report.
387
477
  // (The question's own record: `partialResultOf` gives nothing for an error another question threw too.)
388
- if (state.failed?.error !== again && again?.status === undefined) {
478
+ // (A store that failed, or a document gone, has a status since 0.9.0, but is not the model's.)
479
+ const fromModel = again?.status !== undefined && !DocumentStoreError.is(again) && !DocumentsNotFoundError.is(again);
480
+ if (state.failed?.error !== again && !fromModel) {
389
481
  keepPartial(error.overflow, state, error.partial);
390
482
  throw error.overflow;
391
483
  }
@@ -401,6 +493,7 @@ async function ask(options, carried, state) {
401
493
  const toolModel = explorer ?? model;
402
494
  const models = explorer ? [model, explorer] : [model];
403
495
  const limits = checkedLimits(options.limits);
496
+ checkMissingPolicy(options.onMissingDocuments);
404
497
  // A question planned again goes on counting what its first try paid for.
405
498
  const usage = carried?.usage ?? new UsageMeter();
406
499
  // The budget is counted in the library's estimate of tokens. A model whose tokenizer counts
@@ -431,16 +524,24 @@ async function ask(options, carried, state) {
431
524
  const meter = new RequestMeter(pageTokens);
432
525
  const asText = textSize(messages, options.system);
433
526
  const earlier = meter.rounds(messages);
434
- const prepared = await files.prepare(options.documentIds, { tokens: asText.tokens + earlier.tokens, bytes: asText.bytes + earlier.bytes }, {
527
+ // Who asks: the documents are looked up, and every tool call reads them, for this owner and scope.
528
+ const access = {
435
529
  ...(options.owner !== undefined ? { owner: options.owner } : {}),
530
+ ...(options.scope !== undefined ? { scope: options.scope } : {}),
531
+ };
532
+ // Documents that are missing are settled as `onMissingDocuments` says. A question planned again
533
+ // starts from the documents its first try planned: the function is not asked again about them.
534
+ const planned = await planDocumentsOf(options, carried?.documentIds ?? options.documentIds, (ids) => files.prepare(ids, { tokens: asText.tokens + earlier.tokens, bytes: asText.bytes + earlier.bytes }, {
535
+ ...access,
436
536
  viewPages: options.viewPages !== false && canShowFiles,
437
537
  // The guide and the cards name `analyze_whole_document` only when the tools will have it.
438
538
  wholeDocumentAnalysis: options.wholeDocumentAnalysis !== false && typeof toolModel.generateText === "function",
439
539
  budget,
440
- });
441
- if (prepared.missing.length)
442
- throw new DocumentsNotFoundError(prepared.missing);
443
- const blocks = [...new Set(options.documentIds)].map((id) => prepared.blocks.get(id)).filter((block) => Boolean(block));
540
+ }));
541
+ const { prepared, documentIds } = planned;
542
+ /** The documents left out of the question ("drop"), by this try and by the first. */
543
+ const missing = [...carried?.missing ?? [], ...planned.dropped];
544
+ const blocks = [...new Set(documentIds)].map((id) => prepared.blocks.get(id)).filter((block) => Boolean(block));
444
545
  if (blocks.length) {
445
546
  const block = { text: blocks.join("\n\n") };
446
547
  if (options.documentPlacement === "last")
@@ -449,12 +550,14 @@ async function ask(options, carried, state) {
449
550
  else
450
551
  messages.find((message) => message.role === "user").parts.unshift(block);
451
552
  }
452
- const system = [options.system?.trim(), prepared.instruction].filter(Boolean).join("\n\n");
553
+ // A question without some of its files says so to the model, in one line of its own.
554
+ const missingLine = missing.length > 0 ? missingFilesLine(missing.length) : "";
555
+ const system = [options.system?.trim(), prepared.instruction, missingLine].filter(Boolean).join("\n\n");
453
556
  // The size of what stays in every request: the text as asked, the documents, the tool guide.
454
557
  const whole = new Set(prepared.plan.inline.map((meta) => meta.id));
455
558
  meter.fixed = {
456
- tokens: asText.tokens + prepared.plan.inlineTokens + estimateTokens(prepared.instruction),
457
- bytes: asText.bytes + prepared.plan.inlineBytes + jsonBytes(prepared.instruction),
559
+ tokens: asText.tokens + prepared.plan.inlineTokens + estimateTokens(prepared.instruction) + (missingLine ? estimateTokens(missingLine) : 0),
560
+ bytes: asText.bytes + prepared.plan.inlineBytes + jsonBytes(prepared.instruction) + (missingLine ? jsonBytes(missingLine) : 0),
458
561
  };
459
562
  for (const [id, block] of prepared.blocks) {
460
563
  if (whole.has(id))
@@ -492,7 +595,7 @@ async function ask(options, carried, state) {
492
595
  events.emit({ type: "notice", code, message, display: "activity" });
493
596
  };
494
597
  /** A notice that earlier versions did not show. */
495
- const notice = (code, message) => events.emit({ type: "notice", code, message, display: "none" });
598
+ const notice = (code, message, documentIds) => events.emit({ type: "notice", code, message, display: "none", ...(documentIds ? { documentIds } : {}) });
496
599
  const budgetReached = () => {
497
600
  if (state.budgetSaid)
498
601
  return;
@@ -503,6 +606,10 @@ async function ask(options, carried, state) {
503
606
  steps.push(...carried?.steps ?? []);
504
607
  if (carried)
505
608
  step(carried.step, "replanned");
609
+ if (planned.dropped.length > 0) {
610
+ const count = planned.dropped.length;
611
+ 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]);
612
+ }
506
613
  if (events.active)
507
614
  events.emit({ type: "plan", inline: prepared.plan.inline.map(documentRef), searchable: prepared.plan.searchable.map(documentRef) });
508
615
  // A model turn in its provider's own form goes back only to the adapter it came from. Any other
@@ -631,12 +738,14 @@ async function ask(options, carried, state) {
631
738
  // The rounds as the model last had them. A file cannot be kept as JSON: what is kept says that it was shown.
632
739
  toolTurns: messages.slice(asked).filter(isRound).map((round) => ({
633
740
  role: "tools",
741
+ version: TOOL_TURN_VERSION,
634
742
  calls: round.answers.map(({ call: { problem: _problem, ...call }, result: returned, files: shownFiles }) => ({
635
743
  ...call,
636
744
  result: shownFiles?.length ? stubResult(call, returned, true) ?? returned : returned,
637
745
  })),
638
746
  })),
639
747
  plan: prepared.plan,
748
+ ...(missing.length > 0 ? { missing: [...missing] } : {}),
640
749
  budget,
641
750
  turns,
642
751
  ...(finishReason ? { finishReason } : {}),
@@ -770,7 +879,7 @@ async function ask(options, carried, state) {
770
879
  * work. A model whose conversation may only grow (Claude) has nothing shortened.
771
880
  */
772
881
  const makeRoom = (adapter, sent, error) => {
773
- const refused = error;
882
+ const refused = modelErrorOf(error) ?? {};
774
883
  const own = scaleOf(adapter);
775
884
  meter.overflowed(meter.estimate(sent.messages).tokens, refused.requestedTokens !== undefined ? refused.requestedTokens / own : undefined);
776
885
  if (refused.limitTokens !== undefined) {
@@ -778,22 +887,47 @@ async function ask(options, carried, state) {
778
887
  }
779
888
  if (!canShrink)
780
889
  return false;
890
+ return shortenUntil(() => meter.current(messages).tokens <= tokenLimit);
891
+ };
892
+ /**
893
+ * Shortens old tool results until `fits`: those of every round but the last three, then two,
894
+ * then one, then all. True when anything was shortened.
895
+ */
896
+ const shortenUntil = (fits) => {
781
897
  let changed = false;
782
898
  for (const keep of [...ROUNDS_KEPT, 0]) {
783
- if (changed && meter.current(messages).tokens <= tokenLimit)
899
+ if (changed && fits())
784
900
  break;
785
901
  if (shrink(keep))
786
902
  changed = true;
787
903
  }
788
904
  return changed;
789
905
  };
906
+ /**
907
+ * Before the first request of the question: when the stored rounds of earlier questions make it
908
+ * larger than the room it has in tokens, their results are shortened as they would be after the
909
+ * provider refused it (`makeRoom`, which counts tokens too), and it is sent shortened, instead of
910
+ * sent to be refused. The rounds are those of earlier questions: nothing of this question has
911
+ * been sent, and a stored round has no thinking in it, so this is done for a model whose
912
+ * conversation may only grow (Claude) too. A question planned again shortens them again, and
913
+ * does not say so twice: its first try's steps already do.
914
+ */
915
+ let firstSent = false;
916
+ const preflight = () => {
917
+ if (firstSent)
918
+ return;
919
+ firstSent = true;
920
+ const fits = () => meter.current(messages).tokens <= tokenLimit;
921
+ if (!fits() && shortenUntil(fits) && !carried?.steps.includes(RESULTS_SHORTENED))
922
+ step(RESULTS_SHORTENED, "results_shortened");
923
+ };
790
924
  /**
791
925
  * The window to plan the documents for again, in the models' tokens, after the first request was
792
926
  * refused as too large: the one the provider named, made smaller by how much more than the
793
927
  * estimate it counted. Without its numbers, seven tenths of the window the budget assumed.
794
928
  */
795
929
  const smallerWindow = (adapter, sent, error) => {
796
- const refused = error;
930
+ const refused = modelErrorOf(error) ?? {};
797
931
  const estimated = meter.estimate(sent.messages).tokens;
798
932
  const ratio = refused.requestedTokens !== undefined && estimated > 0 ? refused.requestedTokens / scaleOf(adapter) / estimated : undefined;
799
933
  const limit = refused.limitTokens;
@@ -820,13 +954,15 @@ async function ask(options, carried, state) {
820
954
  * window (`Replan`). `build` makes the request from the conversation as it is then.
821
955
  */
822
956
  const send = async (adapter, build, shown, kind) => {
957
+ preflight();
823
958
  for (let again = false;; again = true) {
824
959
  const body = build();
825
960
  try {
826
961
  return await request(adapter, body, shown, kind);
827
962
  }
828
963
  catch (error) {
829
- if (errorKindOf(error) !== "context_overflow" || signal?.aborted)
964
+ // By the kind its events report: also for an error of your own adapter with a status and no kind.
965
+ if (modelErrorOf(error)?.kind !== "context_overflow" || signal?.aborted)
830
966
  throw error;
831
967
  if (!again && recoveries < MOST_OVERFLOW_RECOVERIES && makeRoom(adapter, body, error)) {
832
968
  recoveries++;
@@ -838,7 +974,7 @@ async function ask(options, carried, state) {
838
974
  }
839
975
  if (carried === undefined && callsAnswered === 0 && !text) {
840
976
  const smaller = smallerWindow(adapter, body, error);
841
- throw new Replan({ usage, steps: [...steps], turns, answered: answeredRequests, nudges, recoveries, contextTokens: smaller.contextTokens, step: smaller.step }, error, result(false));
977
+ throw new Replan({ usage, steps: [...steps], turns, answered: answeredRequests, nudges, recoveries, contextTokens: smaller.contextTokens, step: smaller.step, documentIds, missing }, error, result(false));
842
978
  }
843
979
  throw error;
844
980
  }
@@ -910,6 +1046,9 @@ async function ask(options, carried, state) {
910
1046
  return text;
911
1047
  });
912
1048
  const tools = files.tools(searchable, {
1049
+ // The owner and scope the store holds are checked against the question's own, not against
1050
+ // the metadata handed in.
1051
+ access,
913
1052
  ...(generate ? { generate } : {}),
914
1053
  onProgress: (event) => options.onActivity?.(`${event.message}…`),
915
1054
  signal: halt.signal,
@@ -919,6 +1058,10 @@ async function ask(options, carried, state) {
919
1058
  budget,
920
1059
  });
921
1060
  const declarations = tools.declarations;
1061
+ /** The documents a tool call found gone, told once each ("document_gone"). */
1062
+ const gone = new Set();
1063
+ /** The file name of a document of the question, as the plan has it. */
1064
+ const nameOf = (id) => [...searchable, ...viewable].find((meta) => meta.id === id)?.name;
922
1065
  // The requests that use the tools are the chat's own, or an explorer model's: the same
923
1066
  // conversation, and a line that says what its part is.
924
1067
  const toolSystem = explorer ? `${system}\n\n${EXPLORER_INSTRUCTION}` : system;
@@ -1086,7 +1229,7 @@ async function ask(options, carried, state) {
1086
1229
  }
1087
1230
  }
1088
1231
  if (dropped) {
1089
- step("Older tool results were shortened to make room in the request", "results_shortened");
1232
+ step(RESULTS_SHORTENED, "results_shortened");
1090
1233
  // A result that was shortened is no longer shown in full: a call that pointed to it is run after all.
1091
1234
  for (const plan of planned) {
1092
1235
  if (!plan.earlier)
@@ -1246,6 +1389,8 @@ async function ask(options, carried, state) {
1246
1389
  end,
1247
1390
  };
1248
1391
  };
1392
+ /** A look of this turn waited `pageLookWaitMs` and was told the server is busy: the others do not wait (`maxWaitMs`). */
1393
+ let pagesBusy = false;
1249
1394
  /**
1250
1395
  * The listeners of one call: its progress goes to `onActivity` as before (in place of the
1251
1396
  * tool set's shared listener) and is told apart by call in the events, with its requests.
@@ -1257,6 +1402,17 @@ async function ask(options, carried, state) {
1257
1402
  events.emit({ type: "tool.progress", callId: callIds[index], stage: event.kind, done: event.done, total: event.total, message: event.message });
1258
1403
  }),
1259
1404
  ...(events.active ? { onRequest: (start) => readerRequest(index, start) } : {}),
1405
+ // Notices of the question, not steps: the call's own step says what the model was told.
1406
+ onDocumentGone: (id) => tell(() => {
1407
+ if (gone.has(id))
1408
+ return;
1409
+ gone.add(id);
1410
+ notice("document_gone", `${nameOf(id) ?? "A file"} is no longer available on the server.`, [id]);
1411
+ }),
1412
+ onPagesBusy: (id) => {
1413
+ pagesBusy = true;
1414
+ 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]));
1415
+ },
1260
1416
  });
1261
1417
  // The calls of a turn run together, a few at a time. Looks at pages take their turns, one
1262
1418
  // after another: each is given the room the ones before it left.
@@ -1281,7 +1437,12 @@ async function ask(options, carried, state) {
1281
1437
  requestBytes = toolModel.requestBytes?.(waiting) ?? meter.estimate(waiting.messages).bytes;
1282
1438
  }
1283
1439
  // Base64 turns three bytes into four characters.
1284
- const output = await tools.executeWithFiles(call.name, call.args, { maxFileBytes: Math.floor((maxRequestBytes - bytesKeptFree - requestBytes) * 3 / 4), maxPages: pagesLeft });
1440
+ const output = await tools.executeWithFiles(call.name, call.args, {
1441
+ maxFileBytes: Math.floor((maxRequestBytes - bytesKeptFree - requestBytes) * 3 / 4),
1442
+ maxPages: pagesLeft,
1443
+ // 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.
1444
+ ...(pagesBusy ? { maxWaitMs: 0 } : {}),
1445
+ }, hooksFor(index));
1285
1446
  for (const file of output.files)
1286
1447
  requestBytes += Math.ceil(file.bytes.length / 3) * 4 + 512;
1287
1448
  if (output.files.length > 0)