llm-large-files 0.8.2 → 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 (201) hide show
  1. package/CHANGELOG.md +535 -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 +169 -34
  56. package/dist/library.d.ts.map +1 -1
  57. package/dist/library.js +324 -591
  58. package/dist/library.js.map +1 -1
  59. package/dist/map-reduce.js +3 -3
  60. package/dist/map-reduce.js.map +1 -1
  61. package/dist/model.d.ts +43 -2
  62. package/dist/model.d.ts.map +1 -1
  63. package/dist/model.js +63 -3
  64. package/dist/model.js.map +1 -1
  65. package/dist/node/handlers.d.ts +226 -14
  66. package/dist/node/handlers.d.ts.map +1 -1
  67. package/dist/node/handlers.js +423 -181
  68. package/dist/node/handlers.js.map +1 -1
  69. package/dist/node/index.d.ts +3 -2
  70. package/dist/node/index.d.ts.map +1 -1
  71. package/dist/node/index.js +2 -1
  72. package/dist/node/index.js.map +1 -1
  73. package/dist/node/ingest-child.d.ts +7 -1
  74. package/dist/node/ingest-child.d.ts.map +1 -1
  75. package/dist/node/ingest-child.js +18 -3
  76. package/dist/node/ingest-child.js.map +1 -1
  77. package/dist/node/isolated.d.ts +3 -1
  78. package/dist/node/isolated.d.ts.map +1 -1
  79. package/dist/node/isolated.js +11 -4
  80. package/dist/node/isolated.js.map +1 -1
  81. package/dist/node/originals.d.ts +19 -0
  82. package/dist/node/originals.d.ts.map +1 -0
  83. package/dist/node/originals.js +82 -0
  84. package/dist/node/originals.js.map +1 -0
  85. package/dist/node/spool.d.ts +102 -0
  86. package/dist/node/spool.d.ts.map +1 -0
  87. package/dist/node/spool.js +365 -0
  88. package/dist/node/spool.js.map +1 -0
  89. package/dist/node/sse.d.ts +4 -3
  90. package/dist/node/sse.d.ts.map +1 -1
  91. package/dist/node/sse.js +7 -6
  92. package/dist/node/sse.js.map +1 -1
  93. package/dist/pdf-layout.d.ts.map +1 -1
  94. package/dist/pdf-layout.js +71 -12
  95. package/dist/pdf-layout.js.map +1 -1
  96. package/dist/ranged.d.ts +15 -11
  97. package/dist/ranged.d.ts.map +1 -1
  98. package/dist/ranged.js +42 -11
  99. package/dist/ranged.js.map +1 -1
  100. package/dist/retry.d.ts +3 -1
  101. package/dist/retry.d.ts.map +1 -1
  102. package/dist/retry.js +6 -2
  103. package/dist/retry.js.map +1 -1
  104. package/dist/scope.d.ts +25 -0
  105. package/dist/scope.d.ts.map +1 -0
  106. package/dist/scope.js +60 -0
  107. package/dist/scope.js.map +1 -0
  108. package/dist/source.d.ts +60 -0
  109. package/dist/source.d.ts.map +1 -0
  110. package/dist/source.js +170 -0
  111. package/dist/source.js.map +1 -0
  112. package/dist/stores.d.ts +120 -31
  113. package/dist/stores.d.ts.map +1 -1
  114. package/dist/stores.js +582 -139
  115. package/dist/stores.js.map +1 -1
  116. package/dist/testing/fake-fetch.d.ts +31 -0
  117. package/dist/testing/fake-fetch.d.ts.map +1 -0
  118. package/dist/testing/fake-fetch.js +66 -0
  119. package/dist/testing/fake-fetch.js.map +1 -0
  120. package/dist/testing/fake-model.d.ts +38 -0
  121. package/dist/testing/fake-model.d.ts.map +1 -0
  122. package/dist/testing/fake-model.js +62 -0
  123. package/dist/testing/fake-model.js.map +1 -0
  124. package/dist/testing/index.d.ts +7 -0
  125. package/dist/testing/index.d.ts.map +1 -0
  126. package/dist/testing/index.js +9 -0
  127. package/dist/testing/index.js.map +1 -0
  128. package/dist/testing/store-checks.d.ts +72 -0
  129. package/dist/testing/store-checks.d.ts.map +1 -0
  130. package/dist/testing/store-checks.js +619 -0
  131. package/dist/testing/store-checks.js.map +1 -0
  132. package/dist/tools.d.ts +25 -0
  133. package/dist/tools.d.ts.map +1 -1
  134. package/dist/tools.js +135 -13
  135. package/dist/tools.js.map +1 -1
  136. package/dist/types.d.ts +116 -13
  137. package/dist/types.d.ts.map +1 -1
  138. package/docs/README.md +17 -8
  139. package/docs/getting-started.md +18 -13
  140. package/docs/guides/anthropic.md +12 -8
  141. package/docs/guides/conversations.md +112 -47
  142. package/docs/guides/costs-and-limits.md +16 -7
  143. package/docs/guides/deployment.md +284 -83
  144. package/docs/guides/errors-and-reliability.md +161 -23
  145. package/docs/guides/own-adapter-and-loop.md +27 -10
  146. package/docs/guides/pdfs.md +123 -29
  147. package/docs/guides/storage.md +633 -145
  148. package/docs/guides/testing.md +78 -129
  149. package/docs/guides/vertex-and-gemini.md +10 -7
  150. package/docs/guides/web-app.md +312 -78
  151. package/docs/how-it-works.md +35 -8
  152. package/docs/measurements.md +43 -8
  153. package/docs/publishing.md +112 -36
  154. package/docs/reference/ask.md +154 -13
  155. package/docs/reference/errors-and-retries.md +166 -14
  156. package/docs/reference/events.md +53 -20
  157. package/docs/reference/gemini.md +70 -21
  158. package/docs/reference/library.md +706 -165
  159. package/docs/reference/node.md +624 -110
  160. package/docs/reference/testing.md +311 -0
  161. package/docs/reference/tools.md +15 -5
  162. package/docs/security.md +304 -67
  163. package/docs/troubleshooting.md +144 -65
  164. package/docs/upgrading-0.9.md +890 -0
  165. package/package.json +12 -3
  166. package/src/access.ts +144 -0
  167. package/src/ask.ts +230 -19
  168. package/src/cache.ts +20 -5
  169. package/src/encoding.ts +6 -4
  170. package/src/error-info.ts +255 -0
  171. package/src/errors.ts +129 -15
  172. package/src/events.ts +86 -21
  173. package/src/evidence.ts +14 -3
  174. package/src/extract.ts +50 -33
  175. package/src/gemini/adapter.ts +97 -11
  176. package/src/gemini/chat.ts +20 -6
  177. package/src/gemini/index.ts +1 -1
  178. package/src/index.ts +9 -6
  179. package/src/ingest.ts +927 -0
  180. package/src/library.ts +467 -601
  181. package/src/map-reduce.ts +3 -3
  182. package/src/model.ts +69 -5
  183. package/src/node/handlers.ts +630 -183
  184. package/src/node/index.ts +13 -2
  185. package/src/node/ingest-child.ts +23 -5
  186. package/src/node/isolated.ts +11 -4
  187. package/src/node/originals.ts +78 -0
  188. package/src/node/spool.ts +365 -0
  189. package/src/node/sse.ts +7 -6
  190. package/src/pdf-layout.ts +69 -11
  191. package/src/ranged.ts +34 -13
  192. package/src/retry.ts +6 -2
  193. package/src/scope.ts +63 -0
  194. package/src/source.ts +178 -0
  195. package/src/stores.ts +635 -140
  196. package/src/testing/fake-fetch.ts +80 -0
  197. package/src/testing/fake-model.ts +78 -0
  198. package/src/testing/index.ts +11 -0
  199. package/src/testing/store-checks.ts +660 -0
  200. package/src/tools.ts +150 -14
  201. package/src/types.ts +106 -13
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "llm-large-files",
3
- "version": "0.8.2",
3
+ "version": "0.9.0",
4
4
  "description": "Let an LLM answer questions about books, logs, and other files larger than its request limit or context window: upload, plan, search and read tools, map-reduce, a look at the pages of a PDF, and one tool loop for any model. Adapters for Gemini and Vertex AI, OpenAI-compatible endpoints, and Claude.",
5
5
  "keywords": [
6
6
  "llm",
@@ -34,7 +34,7 @@
34
34
  "type": "module",
35
35
  "sideEffects": false,
36
36
  "engines": {
37
- "node": ">=20.19"
37
+ "node": ">=22.12"
38
38
  },
39
39
  "main": "./dist/index.js",
40
40
  "types": "./dist/index.d.ts",
@@ -59,6 +59,10 @@
59
59
  "types": "./dist/node/index.d.ts",
60
60
  "default": "./dist/node/index.js"
61
61
  },
62
+ "./testing": {
63
+ "types": "./dist/testing/index.d.ts",
64
+ "default": "./dist/testing/index.js"
65
+ },
62
66
  "./node/ingest-child.js": "./dist/node/ingest-child.js",
63
67
  "./package.json": "./package.json"
64
68
  },
@@ -75,6 +79,9 @@
75
79
  ],
76
80
  "node": [
77
81
  "./dist/node/index.d.ts"
82
+ ],
83
+ "testing": [
84
+ "./dist/testing/index.d.ts"
78
85
  ]
79
86
  }
80
87
  },
@@ -89,6 +96,7 @@
89
96
  "typecheck": "tsc --noEmit",
90
97
  "test": "vitest run",
91
98
  "test:watch": "vitest",
99
+ "coverage": "vitest run --coverage --project unit --testTimeout=60000",
92
100
  "check": "npm run typecheck && npm test && npm run build",
93
101
  "prepublishOnly": "npm run check"
94
102
  },
@@ -110,7 +118,8 @@
110
118
  },
111
119
  "devDependencies": {
112
120
  "@cantoo/pdf-lib": "2.11.1",
113
- "@types/node": "^22.10.2",
121
+ "@types/node": "^22.12.0",
122
+ "@vitest/coverage-v8": "4.1.12",
114
123
  "jszip": "3.10.1",
115
124
  "typescript": "5.9.3",
116
125
  "unpdf": "1.4.0",
package/src/access.ts ADDED
@@ -0,0 +1,144 @@
1
+ // Who is asking, and what they may use: the owner and the scope of a call, the context the store is
2
+ // given for it, and the rule that decides which documents serve it. New in 0.9.0.
3
+ import { DocumentScopeError, DocumentStoreError, type DocumentStoreOperation } from "./errors.js";
4
+ import { checkScope, sameScope, scopeKey } from "./scope.js";
5
+ import { DOCUMENT_META_VERSION } from "./stores.js";
6
+ import type { DocumentContext, DocumentMeta, DocumentScope } from "./types.js";
7
+
8
+ /** The TypeError of a call without an owner, when the library requires one (`requireOwner`). */
9
+ export const OWNER_REQUIRED = "owner is required: requireOwner is on";
10
+ /** The TypeError of a call without a scope, when the library requires one (`requireScope`). */
11
+ export const SCOPE_REQUIRED = "scope is required: requireScope is on";
12
+
13
+ /**
14
+ * Refuses an owner that every caller without a user would share: an empty string (what
15
+ * `user?.id ?? ""` gives), one of spaces only, or null. Undefined is no owner. A number is let
16
+ * through, as before, for JavaScript code that passes numeric user IDs.
17
+ */
18
+ export function checkOwner(owner: unknown): void {
19
+ if (owner === undefined || (typeof owner === "string" && owner.trim() !== "") || (typeof owner === "number" && Number.isFinite(owner))) return;
20
+ throw new TypeError("owner must be a string that is not empty or only spaces, such as the signed-in user's ID. To let anyone with the document's ID use it, leave owner out.");
21
+ }
22
+
23
+ /** What a library requires of every call (`LargeFilesOptions.requireOwner` and `requireScope`). */
24
+ export type AccessRules = { readonly requireOwner: boolean; readonly requireScope: boolean };
25
+
26
+ /** A caller, checked: its owner, its scope (a frozen copy), and what the store calls made for it carry. */
27
+ export type Caller = {
28
+ readonly owner?: string;
29
+ readonly scope?: DocumentScope;
30
+ /** The context of the store calls made for this caller. */
31
+ readonly context: DocumentContext;
32
+ /** The key of the scope (`scopeKey`): what this caller's copies of documents are kept under in memory. */
33
+ readonly key: string;
34
+ };
35
+
36
+ /** The context of a store call: a frozen object, without the fields that are absent. */
37
+ export function storeContext(scope: DocumentScope | undefined, owner: string | undefined): DocumentContext {
38
+ return Object.freeze({ ...(scope !== undefined ? { scope } : {}), ...(owner !== undefined ? { owner } : {}) });
39
+ }
40
+
41
+ /**
42
+ * The caller of a call made with `access`. Null is no owner and no scope, as a database gives a
43
+ * field that was left out. The scope is checked (`checkScope`: a `DocumentScopeError` when it is
44
+ * not valid). Under `requireOwner`, a call without an owner, or with one that `checkOwner` refuses,
45
+ * is a TypeError; under `requireScope`, a call without a scope.
46
+ */
47
+ export function callerOf(access: { readonly owner?: unknown; readonly scope?: unknown } | undefined, rules: AccessRules): Caller {
48
+ const owner = (access?.owner ?? undefined) as string | undefined;
49
+ if (rules.requireOwner) {
50
+ if (owner === undefined) throw new TypeError(OWNER_REQUIRED);
51
+ checkOwner(owner);
52
+ }
53
+ const scope = checkScope(access?.scope ?? undefined);
54
+ if (rules.requireScope && scope === undefined) throw new TypeError(SCOPE_REQUIRED);
55
+ return {
56
+ ...(owner !== undefined ? { owner } : {}),
57
+ ...(scope !== undefined ? { scope } : {}),
58
+ context: storeContext(scope, owner),
59
+ key: scopeKey(scope),
60
+ };
61
+ }
62
+
63
+ /**
64
+ * Whether `caller` may use the document `meta` describes. A document with an owner serves only that
65
+ * owner, and one with a scope only a caller of the same scope, segment by segment. A document
66
+ * without an owner serves any caller, unless the library requires owners; the same for scopes.
67
+ * Null is no owner and no scope, as a database gives a field that was left out. A refusal is never
68
+ * told: the document reads as missing.
69
+ */
70
+ export function mayUse(meta: DocumentMeta, caller: Caller, rules: AccessRules): boolean {
71
+ const owner: unknown = meta.owner ?? undefined;
72
+ if (owner === undefined ? rules.requireOwner : owner !== caller.owner) return false;
73
+ const scope: unknown = meta.scope ?? undefined;
74
+ if (scope === undefined) return !rules.requireScope;
75
+ // A scope that is not a list of segments (damaged, or written by hand) serves nobody.
76
+ return Array.isArray(scope) && sameScope(scope as string[], caller.scope);
77
+ }
78
+
79
+ /**
80
+ * Whether the document `found` has exactly this owner and this scope: no owner is the same as no
81
+ * owner only, and so for scopes. An owner or a scope of null counts as none. A scope that is not a
82
+ * list of segments (damaged, or written by hand) is nobody's.
83
+ */
84
+ export function heldBy(found: DocumentMeta, owner: string | undefined, scope: DocumentScope | undefined): boolean {
85
+ const theirs: unknown = found.scope ?? undefined;
86
+ if ((found.owner ?? undefined) !== owner) return false;
87
+ return theirs === undefined ? scope === undefined : Array.isArray(theirs) && sameScope(theirs as string[], scope);
88
+ }
89
+
90
+ /**
91
+ * The context of the reads of a document's text (`get`, `readTextRange`, `getIndex`, and `putIndex`
92
+ * when its index is built again), once `caller` may use it (`mayUse`): the caller's scope, where
93
+ * `getMeta` found the document, and the owner only when the document has one. The copy kept in memory
94
+ * is kept under the caller's scope, and shared by every caller of it, whose owners differ when the
95
+ * document has none: so its reads carry one context whoever makes them. A document whose metadata
96
+ * has no scope (one of 0.8, moved into a scope) is still read in the scope it was found in. The
97
+ * owner sent is the caller's, which `mayUse` found the same as the document's; it is left out when
98
+ * the document has none.
99
+ */
100
+ export function documentContext(meta: DocumentMeta, caller: Caller): DocumentContext {
101
+ return storeContext(caller.scope, (meta.owner ?? undefined) === undefined ? undefined : caller.owner);
102
+ }
103
+
104
+ /**
105
+ * The metadata a store gave for `id`, when it is that of `id`: metadata of another document (a
106
+ * store that looked up the wrong one) is none. An owner or a scope of null, as a database gives a
107
+ * field that was left out, is left out.
108
+ */
109
+ export function metaOf(found: DocumentMeta | undefined, id: string): DocumentMeta | undefined {
110
+ if (typeof found !== "object" || found === null || found.id !== id) return undefined;
111
+ const { owner, scope } = found as { owner?: unknown; scope?: unknown };
112
+ if (owner !== null && scope !== null) return found;
113
+ const { owner: _owner, scope: _scope, ...rest } = found;
114
+ return { ...rest, ...(owner !== null && owner !== undefined ? { owner: owner as string } : {}), ...(scope !== null && scope !== undefined ? { scope: scope as string[] } : {}) };
115
+ }
116
+
117
+ /**
118
+ * A call of the store. What it throws is passed on as a `DocumentStoreError` of `operation`, with
119
+ * the store's error as `cause`: the store's own error may name a path, a host or a bucket, and a
120
+ * store that failed is not a document that is gone. A `DocumentStoreError` is passed on as it is,
121
+ * and so is a `DocumentScopeError`: a scope the store cannot use is a mistake of the call, and the
122
+ * same call would fail again.
123
+ */
124
+ export async function storeCall<T>(operation: DocumentStoreOperation, call: () => Promise<T>): Promise<T> {
125
+ try {
126
+ return await call();
127
+ } catch (error) {
128
+ throw DocumentStoreError.is(error) || DocumentScopeError.is(error) ? error : new DocumentStoreError(error, { operation });
129
+ }
130
+ }
131
+
132
+ /**
133
+ * Refuses metadata written by a newer version of the package (`metaVersion` above
134
+ * `DOCUMENT_META_VERSION`), which may mean what this version cannot tell: a `DocumentStoreError`
135
+ * with code "NEWER_VERSION", not a document that is missing, so that an application does not
136
+ * ingest the file again over it. Metadata without a version (before 0.9.0), or with null as a
137
+ * database gives a field that was left out, is read as before.
138
+ */
139
+ export function checkMetaVersion(meta: DocumentMeta): void {
140
+ const version: unknown = meta.metaVersion ?? 0;
141
+ if (typeof version === "number" && version <= DOCUMENT_META_VERSION) return;
142
+ const found = new RangeError(`The metadata of ${String(meta.id)} has metaVersion ${String(version)}; this version of llm-large-files reads up to ${DOCUMENT_META_VERSION}.`);
143
+ throw new DocumentStoreError(found, { operation: "read", code: "NEWER_VERSION" });
144
+ }
package/src/ask.ts CHANGED
@@ -9,7 +9,9 @@ import {
9
9
  DocumentsNotFoundError,
10
10
  errorKindOf,
11
11
  laterResult,
12
+ modelErrorOf,
12
13
  rateAllowanceOf,
14
+ TOOL_TURN_VERSION,
13
15
  UsageMeter,
14
16
  type ChatMessage,
15
17
  type ModelAdapter,
@@ -23,6 +25,7 @@ import {
23
25
  type ToolTurn,
24
26
  type UsageTotals,
25
27
  } from "./model.js";
28
+ import { DocumentStoreError } from "./errors.js";
26
29
  import { estimateParts, REQUEST_BYTES_MARGIN } from "./plan.js";
27
30
  import { statusOf, withRetry, type RetryNotice, type RetryOptions } from "./retry.js";
28
31
  import { estimateTokens, jsonBytes, wellFormedJson } from "./text.js";
@@ -39,7 +42,7 @@ import {
39
42
  toolResultSummary,
40
43
  unknownToolName,
41
44
  } from "./tools.js";
42
- import type { Budget, DocumentMeta, DocumentPlan, GenerateText, ToolCallHooks, ToolCallLimits, ToolOutput, ToolRequestEnd, ToolRequestHandle, ToolRequestStart, ToolResult } from "./types.js";
45
+ import type { Budget, DocumentMeta, DocumentPlan, DocumentScope, GenerateText, PreparedContext, ToolCallHooks, ToolCallLimits, ToolOutput, ToolRequestEnd, ToolRequestHandle, ToolRequestStart, ToolResult } from "./types.js";
43
46
 
44
47
  /** Sent (invisibly to the user) when the model must stop using tools and answer. */
45
48
  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.";
@@ -118,6 +121,26 @@ export type AskOptions = {
118
121
  system?: string;
119
122
  /** The user asking. Documents ingested with a different owner are treated as missing. */
120
123
  owner?: string;
124
+ /**
125
+ * The scope of the question, such as [userId, chatId] (`DocumentScope`). It is passed to every
126
+ * store call, and documents ingested with another scope are treated as missing. New in 0.9.0.
127
+ */
128
+ scope?: DocumentScope;
129
+ /**
130
+ * What to do when documents of `documentIds` are missing: expired, deleted, never ingested, or of
131
+ * another owner or scope, which look the same. It is settled before any model request.
132
+ * - "throw" (the default): the question fails with `DocumentsNotFoundError`, as before 0.9.0.
133
+ * - "drop": the question is answered without them. The system instruction gets one line that says
134
+ * how many files are no longer available, `AskResult.missing` lists them, and a
135
+ * "documents_missing" notice names them. With no document left, it is a plain chat: no tools.
136
+ * - A function, given the missing IDs, that returns what to do (`MissingDocumentsAction`): "throw",
137
+ * "drop", `{ retry: true }` once it has ingested them again under the same IDs, or
138
+ * `{ replace: { [oldId]: newId } }` for the IDs it ingested them under. A retry or replace plans
139
+ * the question again, once: an ID still missing then fails it with `DocumentsNotFoundError`.
140
+ * What the function throws fails the question.
141
+ * New in 0.9.0.
142
+ */
143
+ onMissingDocuments?: "throw" | "drop" | ((missing: string[], context: MissingDocumentsContext) => MissingDocumentsAction | Promise<MissingDocumentsAction>);
121
144
  limits?: AskLimits;
122
145
  /** How a model request that failed is sent again. Defaults to three more tries, with a wait that doubles. */
123
146
  retry?: RetryOptions;
@@ -197,6 +220,11 @@ export type AskResult = {
197
220
  toolTurns: ToolTurn[];
198
221
  /** Which documents went in whole and which were searched. */
199
222
  plan: DocumentPlan;
223
+ /**
224
+ * The documents of `documentIds` that were missing, and that the question was answered without
225
+ * (`onMissingDocuments` "drop"). Absent when none was. New in 0.9.0.
226
+ */
227
+ missing?: string[];
200
228
  /** The budget the question ran with: the library's, fitted to the models. */
201
229
  budget: Budget;
202
230
  /** Model requests made for the chat itself, an explorer model's among them (whole-document part reads not included). */
@@ -208,6 +236,97 @@ export type AskResult = {
208
236
  lastUsage?: Record<string, unknown>;
209
237
  };
210
238
 
239
+ /**
240
+ * What `AskOptions.onMissingDocuments` says to do with the documents that are missing:
241
+ * - "throw": fail the question with `DocumentsNotFoundError`;
242
+ * - "drop": answer it without them;
243
+ * - `{ retry: true }`: plan it again with the same IDs, under which the documents were ingested again;
244
+ * - `{ replace: { [oldId]: newId } }`: plan it again with each new ID in place of its old one.
245
+ * New in 0.9.0.
246
+ */
247
+ export type MissingDocumentsAction = "throw" | "drop" | { retry: true } | { replace: Record<string, string> };
248
+
249
+ /** What a function of `AskOptions.onMissingDocuments` is told besides the IDs: who asks, and the question's signal. New in 0.9.0. */
250
+ export type MissingDocumentsContext = { owner?: string; scope?: DocumentScope; signal?: AbortSignal };
251
+
252
+ /** The line added to the system instruction when `count` documents were left out ("drop"). */
253
+ const missingFilesLine = (count: number) => (count === 1
254
+ ? "1 of the attached files is no longer available; say so if the question needs it."
255
+ : `${count} of the attached files are no longer available; say so if the question needs them.`);
256
+
257
+ /** A value as an error quotes it. */
258
+ const shownValue = (value: unknown) => (typeof value === "string" ? JSON.stringify(value) : value === null ? "null" : typeof value);
259
+
260
+ /** `onMissingDocuments` checked: a value it cannot be is an error before anything is planned. */
261
+ function checkMissingPolicy(given: unknown): void {
262
+ if (given === undefined || given === "throw" || given === "drop" || typeof given === "function") return;
263
+ throw new TypeError(`onMissingDocuments must be "throw", "drop" or a function, and is ${shownValue(given)}.`);
264
+ }
265
+
266
+ /** An object made as `{}` or `Object.create(null)` is: not a Map, an array or an instance of a class. */
267
+ const isPlainObject = (value: unknown): value is Record<string, unknown> => {
268
+ if (value === null || typeof value !== "object") return false;
269
+ const prototype: unknown = Object.getPrototypeOf(value);
270
+ return prototype === Object.prototype || prototype === null;
271
+ };
272
+
273
+ /** What a function of `onMissingDocuments` returned, checked. */
274
+ function checkedAction(action: unknown): MissingDocumentsAction {
275
+ if (action === "throw" || action === "drop") return action;
276
+ // Only the keys of an action: a key it does not have is a mistake, not something to ignore.
277
+ if (action !== null && typeof action === "object" && Object.keys(action).every((key) => key === "retry" || key === "replace")) {
278
+ const { retry, replace } = action as { retry?: unknown; replace?: unknown };
279
+ if (retry === true && replace === undefined) return { retry: true };
280
+ if (retry === undefined && isPlainObject(replace) && Object.values(replace).every((id) => typeof id === "string" && id.length > 0)) {
281
+ return { replace: { ...(replace as Record<string, string>) } };
282
+ }
283
+ }
284
+ throw new TypeError(`onMissingDocuments returned ${shownValue(action)}: it must return "throw", "drop", { retry: true } or { replace: { [oldId]: newId } }.`);
285
+ }
286
+
287
+ /** The documents of a question once `onMissingDocuments` had its say. */
288
+ type PlannedDocuments = {
289
+ prepared: PreparedContext;
290
+ /** The IDs planned: those asked about, without those left out, with those replaced. */
291
+ documentIds: string[];
292
+ /** The IDs left out ("drop"). */
293
+ dropped: string[];
294
+ };
295
+
296
+ /**
297
+ * Plans the documents `ids`, and settles those that are missing as `onMissingDocuments` says. A
298
+ * retry or a replace plans them again, once.
299
+ */
300
+ async function planDocumentsOf(options: AskOptions, ids: string[], prepare: (ids: string[]) => Promise<PreparedContext>): Promise<PlannedDocuments> {
301
+ const prepared = await prepare(ids);
302
+ if (prepared.missing.length === 0) return { prepared, documentIds: ids, dropped: [] };
303
+ const policy = options.onMissingDocuments ?? "throw";
304
+ let action: MissingDocumentsAction = policy === "drop" ? "drop" : "throw";
305
+ if (typeof policy === "function") {
306
+ options.signal?.throwIfAborted();
307
+ const context: MissingDocumentsContext = {
308
+ ...(options.owner !== undefined ? { owner: options.owner } : {}),
309
+ ...(options.scope !== undefined ? { scope: options.scope } : {}),
310
+ ...(options.signal ? { signal: options.signal } : {}),
311
+ };
312
+ // A function that does not look at the signal does not hold the question once it is stopped.
313
+ action = checkedAction(await until(policy([...prepared.missing], context), options.signal));
314
+ }
315
+ if (action === "throw") throw new DocumentsNotFoundError(prepared.missing);
316
+ if (action === "drop") {
317
+ const gone = new Set(prepared.missing);
318
+ return { prepared, documentIds: ids.filter((id) => !gone.has(id)), dropped: [...prepared.missing] };
319
+ }
320
+ const replace = "replace" in action ? action.replace : {};
321
+ const again = ids.map((id) => (Object.hasOwn(replace, id) ? replace[id]! : id));
322
+ const second = await prepare(again);
323
+ if (second.missing.length > 0) throw new DocumentsNotFoundError(second.missing);
324
+ return { prepared: second, documentIds: again, dropped: [] };
325
+ }
326
+
327
+ /** The step of a question whose older tool results were shortened to make room. */
328
+ const RESULTS_SHORTENED = "Older tool results were shortened to make room in the request";
329
+
211
330
  const DEFAULT_TOOL_TURNS = 12;
212
331
  const DEFAULT_CALLS_PER_TURN = 8;
213
332
  /** Tool calls of one turn that run at the same time. */
@@ -256,10 +375,28 @@ function pagesShown(result: ToolResult): number {
256
375
  */
257
376
  const carriedResult = (result: ToolResult): ToolResult => wellFormedJson(laterResult(result));
258
377
 
259
- /** The conversation as the loop keeps it: copies, so that nothing of the caller's is changed. */
378
+ /**
379
+ * Refuses a stored tool round of a version this package does not read: one a newer version made
380
+ * (`ToolTurn.version` above `TOOL_TURN_VERSION`). A round without a version (before 0.9.0) is read
381
+ * as before. A `TypeError`, which an application can catch to leave such rounds out.
382
+ */
383
+ function checkToolTurnVersion(turn: ToolTurn): void {
384
+ const version: unknown = turn.version ?? 0;
385
+ if (typeof version === "number" && version <= TOOL_TURN_VERSION) return;
386
+ if (typeof version !== "number" || Number.isNaN(version)) {
387
+ 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.`);
388
+ }
389
+ 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.`);
390
+ }
391
+
392
+ /**
393
+ * The conversation as the loop keeps it: copies, so that nothing of the caller's is changed. Of a
394
+ * stored tool round, only the calls are kept: its version is not sent to the model.
395
+ */
260
396
  function toMessages(given: ChatMessage[]): ModelMessage[] {
261
397
  const messages = given.map((message): ModelMessage => {
262
398
  if (message.role === "tools") {
399
+ checkToolTurnVersion(message);
263
400
  const answers = message.calls.map(({ result, ...call }) => ({ call, result: carriedResult(result) }));
264
401
  return { role: "tools", calls: answers.map((answer) => answer.call), answers };
265
402
  }
@@ -279,7 +416,9 @@ function textSize(messages: ModelMessage[], system: string | undefined): Size {
279
416
  for (const part of message.parts) {
280
417
  if (typeof part.text === "string") {
281
418
  tokens += estimateTokens(part.text);
282
- bytes += jsonBytes(part.text);
419
+ // A part in the provider's own form is sent whole: its text, and what is next to it (a
420
+ // thought signature), or the call that the text stands for.
421
+ bytes += part.native === undefined ? jsonBytes(part.text) : Math.max(jsonBytes(part.text), (JSON.stringify(part.native) ?? "").length);
283
422
  } else {
284
423
  const size = (JSON.stringify(part.native) ?? "").length;
285
424
  bytes += size;
@@ -451,6 +590,9 @@ type Carried = {
451
590
  recoveries: number;
452
591
  contextTokens: number;
453
592
  step: string;
593
+ /** The documents the first try planned, once `onMissingDocuments` had its say, and those it left out. */
594
+ documentIds: string[];
595
+ missing: string[];
454
596
  };
455
597
 
456
598
  /**
@@ -605,7 +747,9 @@ async function askPlanned(options: AskOptions, state: RunState): Promise<AskResu
605
747
  // Failed before it sent anything (a budget of the application's that cannot work with the
606
748
  // smaller window): the provider's error, with what the first try found, is the one to report.
607
749
  // (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) {
750
+ // (A store that failed, or a document gone, has a status since 0.9.0, but is not the model's.)
751
+ const fromModel = (again as { status?: unknown } | null)?.status !== undefined && !DocumentStoreError.is(again) && !DocumentsNotFoundError.is(again);
752
+ if (state.failed?.error !== again && !fromModel) {
609
753
  keepPartial(error.overflow, state, error.partial);
610
754
  throw error.overflow;
611
755
  }
@@ -622,6 +766,7 @@ async function ask(options: AskOptions, carried: Carried | undefined, state: Run
622
766
  const toolModel = explorer ?? model;
623
767
  const models = explorer ? [model, explorer] : [model];
624
768
  const limits = checkedLimits(options.limits);
769
+ checkMissingPolicy(options.onMissingDocuments);
625
770
  // A question planned again goes on counting what its first try paid for.
626
771
  const usage = carried?.usage ?? new UsageMeter();
627
772
 
@@ -654,29 +799,40 @@ async function ask(options: AskOptions, carried: Carried | undefined, state: Run
654
799
  const meter = new RequestMeter(pageTokens);
655
800
  const asText = textSize(messages, options.system);
656
801
  const earlier = meter.rounds(messages);
657
- const prepared = await files.prepare(options.documentIds, { tokens: asText.tokens + earlier.tokens, bytes: asText.bytes + earlier.bytes }, {
802
+ // Who asks: the documents are looked up, and every tool call reads them, for this owner and scope.
803
+ const access = {
658
804
  ...(options.owner !== undefined ? { owner: options.owner } : {}),
805
+ ...(options.scope !== undefined ? { scope: options.scope } : {}),
806
+ };
807
+ // Documents that are missing are settled as `onMissingDocuments` says. A question planned again
808
+ // starts from the documents its first try planned: the function is not asked again about them.
809
+ const planned = await planDocumentsOf(options, carried?.documentIds ?? options.documentIds, (ids) => files.prepare(ids, { tokens: asText.tokens + earlier.tokens, bytes: asText.bytes + earlier.bytes }, {
810
+ ...access,
659
811
  viewPages: options.viewPages !== false && canShowFiles,
660
812
  // The guide and the cards name `analyze_whole_document` only when the tools will have it.
661
813
  wholeDocumentAnalysis: options.wholeDocumentAnalysis !== false && typeof toolModel.generateText === "function",
662
814
  budget,
663
- });
664
- if (prepared.missing.length) throw new DocumentsNotFoundError(prepared.missing);
815
+ }));
816
+ const { prepared, documentIds } = planned;
817
+ /** The documents left out of the question ("drop"), by this try and by the first. */
818
+ const missing = [...carried?.missing ?? [], ...planned.dropped];
665
819
 
666
- const blocks = [...new Set(options.documentIds)].map((id) => prepared.blocks.get(id)).filter((block): block is string => Boolean(block));
820
+ const blocks = [...new Set(documentIds)].map((id) => prepared.blocks.get(id)).filter((block): block is string => Boolean(block));
667
821
  if (blocks.length) {
668
822
  const block = { text: blocks.join("\n\n") };
669
823
  if (options.documentPlacement === "last") (messages.at(-1) as ModelTextMessage).parts.push(block);
670
824
  // The last turn is the user's, so there is always a first user turn.
671
825
  else (messages.find((message) => message.role === "user") as ModelTextMessage).parts.unshift(block);
672
826
  }
673
- const system = [options.system?.trim(), prepared.instruction].filter(Boolean).join("\n\n");
827
+ // A question without some of its files says so to the model, in one line of its own.
828
+ const missingLine = missing.length > 0 ? missingFilesLine(missing.length) : "";
829
+ const system = [options.system?.trim(), prepared.instruction, missingLine].filter(Boolean).join("\n\n");
674
830
 
675
831
  // The size of what stays in every request: the text as asked, the documents, the tool guide.
676
832
  const whole = new Set(prepared.plan.inline.map((meta) => meta.id));
677
833
  meter.fixed = {
678
- tokens: asText.tokens + prepared.plan.inlineTokens + estimateTokens(prepared.instruction),
679
- bytes: asText.bytes + prepared.plan.inlineBytes + jsonBytes(prepared.instruction),
834
+ tokens: asText.tokens + prepared.plan.inlineTokens + estimateTokens(prepared.instruction) + (missingLine ? estimateTokens(missingLine) : 0),
835
+ bytes: asText.bytes + prepared.plan.inlineBytes + jsonBytes(prepared.instruction) + (missingLine ? jsonBytes(missingLine) : 0),
680
836
  };
681
837
  for (const [id, block] of prepared.blocks) {
682
838
  if (whole.has(id)) continue;
@@ -713,7 +869,7 @@ async function ask(options: AskOptions, carried: Carried | undefined, state: Run
713
869
  events.emit({ type: "notice", code, message, display: "activity" });
714
870
  };
715
871
  /** A notice that earlier versions did not show. */
716
- const notice = (code: NoticeCode, message: string) => events.emit({ type: "notice", code, message, display: "none" });
872
+ const notice = (code: NoticeCode, message: string, documentIds?: string[]) => events.emit({ type: "notice", code, message, display: "none", ...(documentIds ? { documentIds } : {}) });
717
873
  const budgetReached = () => {
718
874
  if (state.budgetSaid) return;
719
875
  state.budgetSaid = true;
@@ -722,6 +878,10 @@ async function ask(options: AskOptions, carried: Carried | undefined, state: Run
722
878
  // What a first try that was planned again showed is part of this question; then why it was planned again.
723
879
  steps.push(...carried?.steps ?? []);
724
880
  if (carried) step(carried.step, "replanned");
881
+ if (planned.dropped.length > 0) {
882
+ const count = planned.dropped.length;
883
+ 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]);
884
+ }
725
885
  if (events.active) events.emit({ type: "plan", inline: prepared.plan.inline.map(documentRef), searchable: prepared.plan.searchable.map(documentRef) });
726
886
 
727
887
  // A model turn in its provider's own form goes back only to the adapter it came from. Any other
@@ -845,12 +1005,14 @@ async function ask(options: AskOptions, carried: Carried | undefined, state: Run
845
1005
  // The rounds as the model last had them. A file cannot be kept as JSON: what is kept says that it was shown.
846
1006
  toolTurns: messages.slice(asked).filter(isRound).map((round) => ({
847
1007
  role: "tools" as const,
1008
+ version: TOOL_TURN_VERSION,
848
1009
  calls: round.answers.map(({ call: { problem: _problem, ...call }, result: returned, files: shownFiles }) => ({
849
1010
  ...call,
850
1011
  result: shownFiles?.length ? stubResult(call, returned, true) ?? returned : returned,
851
1012
  })),
852
1013
  })),
853
1014
  plan: prepared.plan,
1015
+ ...(missing.length > 0 ? { missing: [...missing] } : {}),
854
1016
  budget,
855
1017
  turns,
856
1018
  ...(finishReason ? { finishReason } : {}),
@@ -977,27 +1139,50 @@ async function ask(options: AskOptions, carried: Carried | undefined, state: Run
977
1139
  * work. A model whose conversation may only grow (Claude) has nothing shortened.
978
1140
  */
979
1141
  const makeRoom = (adapter: ModelAdapter, sent: ModelRequest, error: unknown): boolean => {
980
- const refused = error as { limitTokens?: number; requestedTokens?: number };
1142
+ const refused: { limitTokens?: number; requestedTokens?: number } = modelErrorOf(error) ?? {};
981
1143
  const own = scaleOf(adapter);
982
1144
  meter.overflowed(meter.estimate(sent.messages).tokens, refused.requestedTokens !== undefined ? refused.requestedTokens / own : undefined);
983
1145
  if (refused.limitTokens !== undefined) {
984
1146
  tokenLimit = Math.min(tokenLimit, Math.floor(refused.limitTokens / own) - replyTokens - Math.floor(reservedTokens / 2));
985
1147
  }
986
1148
  if (!canShrink) return false;
1149
+ return shortenUntil(() => meter.current(messages).tokens <= tokenLimit);
1150
+ };
1151
+ /**
1152
+ * Shortens old tool results until `fits`: those of every round but the last three, then two,
1153
+ * then one, then all. True when anything was shortened.
1154
+ */
1155
+ const shortenUntil = (fits: () => boolean): boolean => {
987
1156
  let changed = false;
988
1157
  for (const keep of [...ROUNDS_KEPT, 0]) {
989
- if (changed && meter.current(messages).tokens <= tokenLimit) break;
1158
+ if (changed && fits()) break;
990
1159
  if (shrink(keep)) changed = true;
991
1160
  }
992
1161
  return changed;
993
1162
  };
1163
+ /**
1164
+ * Before the first request of the question: when the stored rounds of earlier questions make it
1165
+ * larger than the room it has in tokens, their results are shortened as they would be after the
1166
+ * provider refused it (`makeRoom`, which counts tokens too), and it is sent shortened, instead of
1167
+ * sent to be refused. The rounds are those of earlier questions: nothing of this question has
1168
+ * been sent, and a stored round has no thinking in it, so this is done for a model whose
1169
+ * conversation may only grow (Claude) too. A question planned again shortens them again, and
1170
+ * does not say so twice: its first try's steps already do.
1171
+ */
1172
+ let firstSent = false;
1173
+ const preflight = () => {
1174
+ if (firstSent) return;
1175
+ firstSent = true;
1176
+ const fits = () => meter.current(messages).tokens <= tokenLimit;
1177
+ if (!fits() && shortenUntil(fits) && !carried?.steps.includes(RESULTS_SHORTENED)) step(RESULTS_SHORTENED, "results_shortened");
1178
+ };
994
1179
  /**
995
1180
  * The window to plan the documents for again, in the models' tokens, after the first request was
996
1181
  * refused as too large: the one the provider named, made smaller by how much more than the
997
1182
  * estimate it counted. Without its numbers, seven tenths of the window the budget assumed.
998
1183
  */
999
1184
  const smallerWindow = (adapter: ModelAdapter, sent: ModelRequest, error: unknown): { contextTokens: number; step: string } => {
1000
- const refused = error as { limitTokens?: number; requestedTokens?: number };
1185
+ const refused: { limitTokens?: number; requestedTokens?: number } = modelErrorOf(error) ?? {};
1001
1186
  const estimated = meter.estimate(sent.messages).tokens;
1002
1187
  const ratio = refused.requestedTokens !== undefined && estimated > 0 ? refused.requestedTokens / scaleOf(adapter) / estimated : undefined;
1003
1188
  const limit = refused.limitTokens;
@@ -1023,12 +1208,14 @@ async function ask(options: AskOptions, carried: Carried | undefined, state: Run
1023
1208
  * window (`Replan`). `build` makes the request from the conversation as it is then.
1024
1209
  */
1025
1210
  const send = async (adapter: ModelAdapter, build: () => ModelRequest, shown: boolean, kind: RequestKind): Promise<ModelReply> => {
1211
+ preflight();
1026
1212
  for (let again = false; ; again = true) {
1027
1213
  const body = build();
1028
1214
  try {
1029
1215
  return await request(adapter, body, shown, kind);
1030
1216
  } catch (error) {
1031
- if (errorKindOf(error) !== "context_overflow" || signal?.aborted) throw error;
1217
+ // By the kind its events report: also for an error of your own adapter with a status and no kind.
1218
+ if (modelErrorOf(error)?.kind !== "context_overflow" || signal?.aborted) throw error;
1032
1219
  if (!again && recoveries < MOST_OVERFLOW_RECOVERIES && makeRoom(adapter, body, error)) {
1033
1220
  recoveries++;
1034
1221
  const period = rateAllowanceOf(error);
@@ -1039,7 +1226,7 @@ async function ask(options: AskOptions, carried: Carried | undefined, state: Run
1039
1226
  }
1040
1227
  if (carried === undefined && callsAnswered === 0 && !text) {
1041
1228
  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));
1229
+ throw new Replan({ usage, steps: [...steps], turns, answered: answeredRequests, nudges, recoveries, contextTokens: smaller.contextTokens, step: smaller.step, documentIds, missing }, error, result(false));
1043
1230
  }
1044
1231
  throw error;
1045
1232
  }
@@ -1107,6 +1294,9 @@ async function ask(options: AskOptions, carried: Carried | undefined, state: Run
1107
1294
  return text;
1108
1295
  });
1109
1296
  const tools = files.tools(searchable, {
1297
+ // The owner and scope the store holds are checked against the question's own, not against
1298
+ // the metadata handed in.
1299
+ access,
1110
1300
  ...(generate ? { generate } : {}),
1111
1301
  onProgress: (event) => options.onActivity?.(`${event.message}…`),
1112
1302
  signal: halt.signal,
@@ -1116,6 +1306,10 @@ async function ask(options: AskOptions, carried: Carried | undefined, state: Run
1116
1306
  budget,
1117
1307
  });
1118
1308
  const declarations = tools.declarations;
1309
+ /** The documents a tool call found gone, told once each ("document_gone"). */
1310
+ const gone = new Set<string>();
1311
+ /** The file name of a document of the question, as the plan has it. */
1312
+ const nameOf = (id: string): string | undefined => [...searchable, ...viewable].find((meta) => meta.id === id)?.name;
1119
1313
  // The requests that use the tools are the chat's own, or an explorer model's: the same
1120
1314
  // conversation, and a line that says what its part is.
1121
1315
  const toolSystem = explorer ? `${system}\n\n${EXPLORER_INSTRUCTION}` : system;
@@ -1277,7 +1471,7 @@ async function ask(options: AskOptions, carried: Carried | undefined, state: Run
1277
1471
  }
1278
1472
  }
1279
1473
  if (dropped) {
1280
- step("Older tool results were shortened to make room in the request", "results_shortened");
1474
+ step(RESULTS_SHORTENED, "results_shortened");
1281
1475
  // A result that was shortened is no longer shown in full: a call that pointed to it is run after all.
1282
1476
  for (const plan of planned) {
1283
1477
  if (!plan.earlier) continue;
@@ -1423,6 +1617,8 @@ async function ask(options: AskOptions, carried: Carried | undefined, state: Run
1423
1617
  end,
1424
1618
  };
1425
1619
  };
1620
+ /** A look of this turn waited `pageLookWaitMs` and was told the server is busy: the others do not wait (`maxWaitMs`). */
1621
+ let pagesBusy = false;
1426
1622
  /**
1427
1623
  * The listeners of one call: its progress goes to `onActivity` as before (in place of the
1428
1624
  * tool set's shared listener) and is told apart by call in the events, with its requests.
@@ -1433,6 +1629,16 @@ async function ask(options: AskOptions, carried: Carried | undefined, state: Run
1433
1629
  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
1630
  }),
1435
1631
  ...(events.active ? { onRequest: (start: ToolRequestStart) => readerRequest(index, start) } : {}),
1632
+ // Notices of the question, not steps: the call's own step says what the model was told.
1633
+ onDocumentGone: (id) => tell(() => {
1634
+ if (gone.has(id)) return;
1635
+ gone.add(id);
1636
+ notice("document_gone", `${nameOf(id) ?? "A file"} is no longer available on the server.`, [id]);
1637
+ }),
1638
+ onPagesBusy: (id) => {
1639
+ pagesBusy = true;
1640
+ 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]));
1641
+ },
1436
1642
  });
1437
1643
 
1438
1644
  // The calls of a turn run together, a few at a time. Looks at pages take their turns, one
@@ -1455,7 +1661,12 @@ async function ask(options: AskOptions, carried: Carried | undefined, state: Run
1455
1661
  requestBytes = toolModel.requestBytes?.(waiting) ?? meter.estimate(waiting.messages).bytes;
1456
1662
  }
1457
1663
  // 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 });
1664
+ const output = await tools.executeWithFiles(call.name, call.args, {
1665
+ maxFileBytes: Math.floor((maxRequestBytes - bytesKeptFree - requestBytes) * 3 / 4),
1666
+ maxPages: pagesLeft,
1667
+ // 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.
1668
+ ...(pagesBusy ? { maxWaitMs: 0 } : {}),
1669
+ }, hooksFor(index));
1459
1670
  for (const file of output.files) requestBytes += Math.ceil(file.bytes.length / 3) * 4 + 512;
1460
1671
  if (output.files.length > 0) pagesLeft -= pagesShown(output.result);
1461
1672
  return output;