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/src/tools.ts CHANGED
@@ -1,8 +1,11 @@
1
1
  import { safeErrorMessage } from "./errors.js";
2
+ import { until } from "./http.js";
2
3
  import { aggregateTable, FILTER_OPS, MAX_SHOWN_GROUPS, type AggregateRequest, type FilterOp } from "./aggregate.js";
3
4
  import { GROUP_BY_VALUES, MAX_GROUP_KEYS, type GroupBy, type GroupResult } from "./groups.js";
4
5
  import { analyzeWholeDocument, NothingReadError } from "./map-reduce.js";
5
- import { cutPdfPages } from "./pdf-pages.js";
6
+ import { cutPdfPages, type PageCut } from "./pdf-pages.js";
7
+ import type { Limiter } from "./limiter.js";
8
+ import { DocumentGoneError } from "./ranged.js";
6
9
  import { grepSource, numberLines, rankSource, REGEX_TIME_LIMIT_MS, type DocumentSource, type LineMatch } from "./search.js";
7
10
  import { estimateParts, formatBytes, outlineLines, REQUEST_BYTES_MARGIN } from "./plan.js";
8
11
  import type { RetryOptions } from "./retry.js";
@@ -677,9 +680,42 @@ export const unknownToolName = (name: string): string => `“${sliceWhole(name,
677
680
  */
678
681
  const shownId = (id: string): string => (id.length > 64 ? `${sliceWhole(id, 64)}…` : id);
679
682
 
683
+ /** A document that a call names is no longer in the store, as a read by range finds it: its message is the model's. */
684
+ const gone = (id: string) => new DocumentGoneError(`${id} is no longer available on the server. Ask the user to attach the file again.`);
685
+
686
+ /** A look at pages that waited its turn for too long: its message is the model's. */
687
+ class PagesBusyError extends Error {
688
+ constructor(readonly documentId: string, file: string) {
689
+ super(`${file}: The pages cannot be looked at right now; the server is busy. Answer from the text, or look again later.`);
690
+ }
691
+ }
692
+
693
+ /** A timer may wait at most this long (2^31 - 1 ms, 24.8 days). */
694
+ const LONGEST_WAIT_MS = 2_147_483_647;
695
+
696
+ /** How the looks at pages of a library take their turns (`maxConcurrentPageLooks`, `pageLookWaitMs`). */
697
+ export type PageLookTurns = {
698
+ /** Shared by every tool set of the library: one look at a time, by default. */
699
+ limiter: Limiter;
700
+ /** How long a look waits for its turn before the model is told that the server is busy. Infinity: without end. */
701
+ waitMs: number;
702
+ /**
703
+ * How long a look may hold its turn while its original file is read from the store. Past it, the
704
+ * turn goes back and the model is told that the file could not be read in time: a store that
705
+ * never answers holds no turn for good. Left out, or Infinity: without end.
706
+ */
707
+ holdMs?: number;
708
+ };
709
+
680
710
  export function createDocumentTools(options: {
681
711
  /** Loads a document the tools may access. Return undefined for anything out of scope. */
682
712
  load(documentId: string): Promise<DocumentSource | undefined>;
713
+ /**
714
+ * Asked, once a call of a text tool has ended, about the document it read: false when the store
715
+ * no longer describes it as it was loaded, so that what was read of it may be another document's.
716
+ * The call then answers that the document is no longer available.
717
+ */
718
+ checkRead?(document: DocumentSource): Promise<boolean>;
683
719
  documentIds: string[];
684
720
  /** File names by document ID, so `describe` can name files before they are loaded. */
685
721
  names?: Record<string, string>;
@@ -706,6 +742,11 @@ export function createDocumentTools(options: {
706
742
  viewableIds?: string[];
707
743
  /** Loads the uploaded file of a document, for `view_pages`. */
708
744
  loadOriginal?(documentId: string): Promise<Uint8Array | undefined>;
745
+ /**
746
+ * The turns of the looks at pages, shared by the tool sets of one library: a look waits for its
747
+ * turn before the original file is loaded. Without it, looks do not wait.
748
+ */
749
+ pageLooks?: PageLookTurns;
709
750
  /**
710
751
  * True when a document may hold a table (a CSV, a workbook, a document with `| cell |` rows):
711
752
  * `aggregate_table` is then declared. A call of it is answered either way. Defaults to false.
@@ -758,6 +799,9 @@ export function createDocumentTools(options: {
758
799
  // When no limit is given with a call: three eighths of a request, so that two looks still fit.
759
800
  const defaultFileBytes = Math.floor((options.budget.maxRequestBytes - REQUEST_BYTES_MARGIN) * 3 / 8);
760
801
 
802
+ /** The documents the calls under way loaded, by the arguments of the call: checked once it ends (`checkRead`). */
803
+ const loaded = new WeakMap<object, Set<DocumentSource[]>>();
804
+
761
805
  async function documentFor(args: Record<string, unknown>): Promise<DocumentSource> {
762
806
  const id = text(args.document_id, "document_id");
763
807
  // Scope check: a model can only reach files attached to this conversation.
@@ -769,11 +813,57 @@ export function createDocumentTools(options: {
769
813
  : `Unknown document_id ${shownId(id)}. Use one of: ${usable.join(", ")}${allowed.size > 20 ? ", …" : ""}.`);
770
814
  }
771
815
  const document = await options.load(id);
772
- if (!document) throw new Error(`${id} is no longer available on the server. Ask the user to attach the file again.`);
816
+ if (!document) throw gone(id);
817
+ for (const reads of loaded.get(args) ?? []) reads.push(document);
773
818
  names.set(id, document.meta.name);
774
819
  return document;
775
820
  }
776
821
 
822
+ /**
823
+ * Waits for the turn of a look at pages of `file`, for at most `pageLookWaitMs`, or the call's
824
+ * `maxWaitMs` when that is less. Returns the function that gives the turn back. Past the wait, a
825
+ * `PagesBusyError`. The wait ends at once when the tool set is stopped, with the reason it was
826
+ * stopped for.
827
+ */
828
+ async function pageLookTurn(id: string, file: string, limits: ToolCallLimits): Promise<() => void> {
829
+ const turns = options.pageLooks;
830
+ if (!turns) return () => undefined;
831
+ const waited = new AbortController();
832
+ const callWait = typeof limits.maxWaitMs === "number" && !Number.isNaN(limits.maxWaitMs) ? limits.maxWaitMs : Infinity;
833
+ const waitMs = Math.max(0, Math.min(turns.waitMs, callWait));
834
+ const timer = waitMs <= LONGEST_WAIT_MS ? setTimeout(() => waited.abort(), waitMs) : undefined;
835
+ timer?.unref?.();
836
+ try {
837
+ return await turns.limiter.acquire(options.signal ? AbortSignal.any([options.signal, waited.signal]) : waited.signal);
838
+ } catch (error) {
839
+ if (options.signal?.aborted || !waited.signal.aborted) throw error;
840
+ throw new PagesBusyError(id, file);
841
+ } finally {
842
+ clearTimeout(timer);
843
+ }
844
+ }
845
+
846
+ /**
847
+ * The original file of a look, read while the look holds its turn: for at most `holdMs`, and
848
+ * only while the tool set runs. A read given up on goes on, but holds no turn.
849
+ */
850
+ async function originalOf(id: string, file: string): Promise<Uint8Array | undefined> {
851
+ const reading = until(options.loadOriginal!(id), options.signal);
852
+ const holdMs = options.pageLooks?.holdMs;
853
+ if (holdMs === undefined || !(holdMs <= LONGEST_WAIT_MS)) return reading;
854
+ let timer: ReturnType<typeof setTimeout> | undefined;
855
+ // The timer keeps the process alive: a read that never ends may hold nothing that does, and
856
+ // the question waiting for it would be lost.
857
+ const late = new Promise<never>((_, reject) => {
858
+ timer = setTimeout(() => reject(new Error(`The original file of ${file} could not be read in time, so its pages cannot be shown. Answer from the text.`)), Math.max(0, holdMs));
859
+ });
860
+ try {
861
+ return await Promise.race([reading, late]);
862
+ } finally {
863
+ clearTimeout(timer);
864
+ }
865
+ }
866
+
777
867
  const handlers: Record<string, (args: Record<string, unknown>, limits: ToolCallLimits, hooks: ToolCallHooks) => Promise<ToolResult>> = {
778
868
  async [TOOL_NAMES.search](args, limits) {
779
869
  const limit = limitOf(limits);
@@ -1035,7 +1125,7 @@ export function createDocumentTools(options: {
1035
1125
  : `Unknown document_id ${shownId(id)}. Use the document_id of an attached PDF.`);
1036
1126
  }
1037
1127
  const document = await options.load(id);
1038
- if (!document) throw new Error(`${id} is no longer available on the server. Ask the user to attach the file again.`);
1128
+ if (!document) throw gone(id);
1039
1129
  const file = document.meta.name;
1040
1130
  names.set(id, file);
1041
1131
  const from = pageNumber(args.from_page, "from_page");
@@ -1048,13 +1138,32 @@ export function createDocumentTools(options: {
1048
1138
  if (mostPages < 1) throw new Error("No more pages can be looked at for this question. Answer from the pages and the text you already have.");
1049
1139
  const maxBytes = whole(limits.maxFileBytes, defaultFileBytes);
1050
1140
  if (maxBytes < MIN_FILE_BYTES) throw new Error("There is no room left in this request to show more pages. Answer from the pages and the text you already have.");
1051
- const original = await options.loadOriginal!(id);
1052
- if (!original) throw new Error(`The original file of ${file} is no longer on the server, so its pages cannot be shown. Answer from the text.`);
1053
- let cut;
1141
+ // Looks take their turns in the library (`maxConcurrentPageLooks`): they share one thread, and
1142
+ // more of them at once only hold more memory. The original is loaded once the turn comes, so a
1143
+ // look that waits holds none of its bytes, and the memory left is looked at then (`cutPdfPages`).
1144
+ // A question stopped while its original is read gives the turn back at once, and so does a
1145
+ // read that takes longer than the library allows its store calls (`holdMs`).
1146
+ const release = await pageLookTurn(id, file, limits);
1147
+ let cut: PageCut | undefined;
1054
1148
  try {
1055
- cut = await cutPdfPages(original, from, Math.min(asked, from + mostPages - 1), maxBytes, total);
1056
- } catch (error) {
1057
- throw new Error(`${file}: ${safeErrorMessage(error)}`);
1149
+ options.signal?.throwIfAborted();
1150
+ const original = await originalOf(id, file);
1151
+ // Stopped while the original was read: no pages are cut for a question that has left.
1152
+ options.signal?.throwIfAborted();
1153
+ if (original) {
1154
+ try {
1155
+ cut = await cutPdfPages(original, from, Math.min(asked, from + mostPages - 1), maxBytes, total);
1156
+ } catch (error) {
1157
+ throw new Error(`${file}: ${safeErrorMessage(error)}`);
1158
+ }
1159
+ }
1160
+ } finally {
1161
+ release();
1162
+ }
1163
+ if (!cut) {
1164
+ // The document may have gone while the look waited for its turn: that is told as such.
1165
+ if (!await options.load(id)) throw gone(id);
1166
+ throw new Error(`The original file of ${file} is no longer on the server, so its pages cannot be shown. Answer from the text.`);
1058
1167
  }
1059
1168
  const pages = pageRange(cut.from, cut.to);
1060
1169
  const shown = cut.to - cut.from + 1;
@@ -1073,19 +1182,46 @@ export function createDocumentTools(options: {
1073
1182
  };
1074
1183
  }
1075
1184
 
1076
- // What a tool could not do goes to the model, and from there to a user's screen: never a server path.
1077
- const failure = (error: unknown): ToolResult => ({ error: safeErrorMessage(error) });
1185
+ /**
1186
+ * What a tool could not do goes to the model, and from there to a user's screen: never a server
1187
+ * path. A document found gone, or a look that waited too long, is also told to the call's hooks.
1188
+ */
1189
+ const failure = (error: unknown, args: Record<string, unknown>, hooks: ToolCallHooks): ToolResult => {
1190
+ // Found gone when the call began, or while a read by range went through its text.
1191
+ if (error instanceof DocumentGoneError && typeof args.document_id === "string") hooks.onDocumentGone?.(args.document_id);
1192
+ else if (error instanceof PagesBusyError) hooks.onPagesBusy?.(error.documentId);
1193
+ return { error: safeErrorMessage(error) };
1194
+ };
1078
1195
 
1079
1196
  async function execute(name: string, args: Record<string, unknown>, limits: ToolCallLimits = {}, hooks: ToolCallHooks = {}): Promise<ToolResult> {
1080
1197
  if (!known.has(name)) return { error: `Unknown tool ${unknownToolName(name)}.` };
1081
1198
  // The pages are a file, and this method returns only JSON. Saying that pages are attached
1082
1199
  // with nothing attached would be worse than saying that they could not be shown.
1083
1200
  if (name === TOOL_NAMES.view) return { error: FILES_NOT_DELIVERED };
1201
+ // The documents this call loads (`documentFor`), by its arguments: calls given the same object
1202
+ // at once each note them all.
1203
+ const reads: DocumentSource[] = [];
1204
+ const calls = typeof args === "object" && args !== null ? loaded.get(args) ?? new Set<DocumentSource[]>() : undefined;
1205
+ if (calls) loaded.set(args, calls.add(reads));
1206
+ const checkReads = async () => {
1207
+ for (const document of reads) if (options.checkRead && !await options.checkRead(document)) throw gone(document.meta.id);
1208
+ };
1084
1209
  try {
1085
- return await handlers[name]!(args, limits, hooks);
1210
+ let result: ToolResult;
1211
+ try {
1212
+ result = await handlers[name]!(args, limits, hooks);
1213
+ } catch (error) {
1214
+ if (options.signal?.aborted) throw error;
1215
+ await checkReads();
1216
+ throw error;
1217
+ }
1218
+ await checkReads();
1219
+ return result;
1086
1220
  } catch (error) {
1087
1221
  if (options.signal?.aborted) throw error;
1088
- return failure(error);
1222
+ return failure(error, args, hooks);
1223
+ } finally {
1224
+ calls?.delete(reads);
1089
1225
  }
1090
1226
  }
1091
1227
 
@@ -1100,7 +1236,7 @@ export function createDocumentTools(options: {
1100
1236
  return await viewPages(args, limits);
1101
1237
  } catch (error) {
1102
1238
  if (options.signal?.aborted) throw error;
1103
- return { result: failure(error), files: [] };
1239
+ return { result: failure(error, args, hooks), files: [] };
1104
1240
  }
1105
1241
  },
1106
1242
  describe(name, args) {
package/src/types.ts CHANGED
@@ -27,10 +27,52 @@ export type LogProfile = {
27
27
  topIssues: LogIssue[];
28
28
  };
29
29
 
30
+ /**
31
+ * Where a document belongs, from the widest part to the narrowest: `[userId, chatId]`. 1 to 8
32
+ * segments, each 1 to 256 UTF-16 units, with no control characters, no "/" or "\", and none of them
33
+ * "." or "..". A scope that breaks these rules is a `DocumentScopeError`. New in 0.9.0.
34
+ */
35
+ export type DocumentScope = readonly string[];
36
+
37
+ /**
38
+ * What the library knows of the caller of a store method: the scope and the owner it was given. It
39
+ * is the last argument of every `DocumentStore` method, and both fields may be absent. A store may
40
+ * keep the documents of each scope apart (a folder, a key prefix, a collection filter), and pass
41
+ * the context on unchanged when it wraps another store. New in 0.9.0.
42
+ */
43
+ export type DocumentContext = { readonly scope?: DocumentScope; readonly owner?: string };
44
+
30
45
  export type DocumentMeta = {
31
46
  id: string;
47
+ /**
48
+ * The version of this metadata's shape: `DOCUMENT_META_VERSION` (1) on documents ingested by
49
+ * 0.9.0 and later, absent on older ones. The library refuses a higher one (a document written by a
50
+ * newer version of the package) with a `DocumentStoreError` of code "NEWER_VERSION". It is never
51
+ * sent to the model. New in 0.9.0.
52
+ */
53
+ metaVersion?: number;
32
54
  /** Who may use this document. Set it at ingest; access with another owner is refused. */
33
55
  owner?: string;
56
+ /**
57
+ * The scope the document was ingested in (`IngestInput.scope`), as a copy. Only a caller with the
58
+ * same scope may use it. It is never sent to the model, nor in a summary. An event holds it only
59
+ * with `AskOptions.eventResults: true`, in the full plan of `run.finish` and `run.error`. New in 0.9.0.
60
+ */
61
+ scope?: string[];
62
+ /**
63
+ * The SHA-256 of the uploaded file, as 64 lowercase hex digits. It is never sent to the model, nor
64
+ * in a summary. An event holds it only with `AskOptions.eventResults: true`, in the full plan of
65
+ * `run.finish` and `run.error`. New in 0.9.0.
66
+ */
67
+ sha256?: string;
68
+ /**
69
+ * The uploaded file, when the application keeps it and the library reads it from there
70
+ * (`IngestInput.original`): where it is, and its size and SHA-256 when it was read, to know that
71
+ * it has not changed since. `ref` is never sent to the model, nor in a summary. An event holds it
72
+ * only with `AskOptions.eventResults: true`, in the full plan of `run.finish` and `run.error`.
73
+ * New in 0.9.0.
74
+ */
75
+ original?: { ref: string; bytes: number; sha256: string };
34
76
  name: string;
35
77
  mimeType: string;
36
78
  format: DocumentFormat;
@@ -109,38 +151,47 @@ export type DocumentSummary = {
109
151
  expiresAt: string;
110
152
  };
111
153
 
112
- /** Where extracted text lives. Implement this for Redis, S3, a database, etc. */
154
+ /**
155
+ * Where extracted text lives. Implement this for Redis, S3, a database, etc.
156
+ *
157
+ * Every method takes a last, optional `context` (`DocumentContext`): the scope and the owner of
158
+ * the call. New in 0.9.0. A store written for 0.8, whose methods take no context, still implements
159
+ * this interface, and works as before. A store that wraps another one passes the context on.
160
+ */
113
161
  export interface DocumentStore {
114
- put(document: StoredDocument): Promise<void>;
162
+ put(document: StoredDocument, context?: DocumentContext): Promise<void>;
115
163
  /** Returns undefined for unknown or expired documents. */
116
- get(id: string): Promise<StoredDocument | undefined>;
117
- getMeta(id: string): Promise<DocumentMeta | undefined>;
164
+ get(id: string, context?: DocumentContext): Promise<StoredDocument | undefined>;
165
+ getMeta(id: string, context?: DocumentContext): Promise<DocumentMeta | undefined>;
118
166
  /** Removes the document, and its original file if one is kept. */
119
- delete(id: string): Promise<boolean>;
120
- /** Removes expired documents (and their original files) and returns how many were removed. */
121
- sweep?(now?: Date): Promise<number>;
167
+ delete(id: string, context?: DocumentContext): Promise<boolean>;
168
+ /**
169
+ * Removes expired documents (and their original files) and returns how many were removed. With
170
+ * a scope in `context`, only those of that scope; without one, those of every scope.
171
+ */
172
+ sweep?(now?: Date, context?: DocumentContext): Promise<number>;
122
173
  /**
123
174
  * Keeps the uploaded file of a document. It is called before `put` for the same ID. Optional: a
124
175
  * store without it works as before, and original files are then not kept.
125
176
  */
126
- putOriginal?(id: string, bytes: Uint8Array): Promise<void>;
177
+ putOriginal?(id: string, bytes: Uint8Array, context?: DocumentContext): Promise<void>;
127
178
  /** The uploaded file, or undefined when none was kept or the document is unknown or expired. */
128
- getOriginal?(id: string): Promise<Uint8Array | undefined>;
179
+ getOriginal?(id: string, context?: DocumentContext): Promise<Uint8Array | undefined>;
129
180
  /**
130
181
  * Bytes `start` (inclusive) to `end` (exclusive) of the stored text, as UTF-8. Optional: with it,
131
182
  * a tool call reads only the lines it needs, and a search reads the text a piece at a time,
132
183
  * instead of loading the whole text into memory. Return fewer bytes at the end of the text, and
133
184
  * undefined when the document is gone. It is called only after `getMeta` found the document.
134
185
  */
135
- readTextRange?(id: string, start: number, end: number): Promise<Uint8Array | undefined>;
186
+ readTextRange?(id: string, start: number, end: number, context?: DocumentContext): Promise<Uint8Array | undefined>;
136
187
  /**
137
188
  * Keeps the line index of a document (a few bytes a line), so that reading by range needs no
138
189
  * pass over the text first. Called at ingest, before `put`, and when an older document without an
139
190
  * index is first read. Optional, and only useful with `readTextRange`.
140
191
  */
141
- putIndex?(id: string, index: Uint8Array): Promise<void>;
192
+ putIndex?(id: string, index: Uint8Array, context?: DocumentContext): Promise<void>;
142
193
  /** The index kept by `putIndex`, or undefined. A damaged one is noticed and built again. */
143
- getIndex?(id: string): Promise<Uint8Array | undefined>;
194
+ getIndex?(id: string, context?: DocumentContext): Promise<Uint8Array | undefined>;
144
195
  }
145
196
 
146
197
  export type ExtractedText = {
@@ -153,6 +204,13 @@ export type ExtractedText = {
153
204
  encoding?: string;
154
205
  /** Characters that were not valid in the encoding the file was read in, each now U+FFFD. Kept as `DocumentMeta.replacedCharacters`. */
155
206
  replacedCharacters?: number;
207
+ /**
208
+ * What an extractor that reads paths (`Extractor.readsPath`) read from `ExtractInput.path`: how
209
+ * many bytes the file has, and their SHA-256, as 64 lowercase hex digits. Kept as
210
+ * `DocumentMeta.bytes` and `DocumentMeta.sha256`. Without it, `ingest` reads the file once more
211
+ * to hash it, a slice at a time. Other extractors leave it out. New in 0.9.0.
212
+ */
213
+ file?: { bytes: number; sha256: string };
156
214
  };
157
215
 
158
216
  export type ExtractInput = {
@@ -187,6 +245,15 @@ export type ExtractInput = {
187
245
  * extractor of your own may ignore it. New in 0.7.0.
188
246
  */
189
247
  onProgress?: (progress: ExtractProgress) => void;
248
+ /**
249
+ * The path of the file, when it is ingested from a path (`IngestFromSource`) and the extractor
250
+ * reads the file itself (`Extractor.readsPath`): the bytes it is given are then empty. Read it
251
+ * once, at most `maxUploadBytes + 1` bytes, refuse it when it has more than `maxUploadBytes`, and
252
+ * return its size and SHA-256 in `ExtractedText.file`. Never write, move or delete it. New in 0.9.0.
253
+ */
254
+ path?: string;
255
+ /** With `path`: the most bytes the file may have (`maxUploadBytes`). New in 0.9.0. */
256
+ maxUploadBytes?: number;
190
257
  };
191
258
 
192
259
  /** How far an extraction is, for `ExtractInput.onProgress`. */
@@ -199,7 +266,14 @@ export type ExtractProgress = {
199
266
  unit: "pages" | "parts" | "bytes";
200
267
  };
201
268
 
202
- export type Extractor = (bytes: Uint8Array, input: ExtractInput) => Promise<ExtractedText>;
269
+ /**
270
+ * Reads the text of a file. A plain function is an extractor, as before. `readsPath`, new in 0.9.0:
271
+ * the extractor reads a file ingested from a path itself, from `ExtractInput.path`, so the server
272
+ * does not read it first (`createIsolatedExtractors` sets it: its child processes read the file).
273
+ * It is then given empty bytes, unless the file is kept in the store (`keepOriginals` without
274
+ * `IngestInput.original`), which needs its bytes in the server.
275
+ */
276
+ export type Extractor = ((bytes: Uint8Array, input: ExtractInput) => Promise<ExtractedText>) & { readsPath?: boolean };
203
277
 
204
278
  /** The limits of the model connection the documents must fit through. */
205
279
  export type Budget = {
@@ -270,6 +344,13 @@ export type ToolCallLimits = {
270
344
  * halves only while that and `maxMapChunks` allow it.
271
345
  */
272
346
  maxRequests?: number;
347
+ /**
348
+ * The most milliseconds a look at pages (`view_pages`) of this call waits for its turn, when that
349
+ * is less than the library's `pageLookWaitMs`. 0: it runs only when a turn is free now, and is
350
+ * told the server is busy if not. `askWithFiles` gives 0 to the looks of a turn after one of them
351
+ * came back busy, so that a wait that ends busy comes once in a turn. New in 0.9.0.
352
+ */
353
+ maxWaitMs?: number;
273
354
  };
274
355
  /**
275
356
  * Listeners for one tool call, next to its limits. New in 0.7.0: with them, the progress of two
@@ -283,6 +364,18 @@ export type ToolCallHooks = {
283
364
  * returns about each retry of that request, and when it ends.
284
365
  */
285
366
  onRequest?: (request: ToolRequestStart) => ToolRequestHandle;
367
+ /**
368
+ * The document this call names is no longer in the store: deleted or expired since it was
369
+ * planned, or not readable by the caller (which looks the same). The call answers the model with
370
+ * an error that says so. `askWithFiles` makes it a "document_gone" notice. New in 0.9.0.
371
+ */
372
+ onDocumentGone?: (documentId: string) => void;
373
+ /**
374
+ * A look at pages (`view_pages`) waited longer than `pageLookWaitMs` for its turn
375
+ * (`maxConcurrentPageLooks`) and was not run. The call answers the model with an error that says
376
+ * the server is busy. `askWithFiles` makes it a "page_looks_busy" notice. New in 0.9.0.
377
+ */
378
+ onPagesBusy?: (documentId: string) => void;
286
379
  };
287
380
 
288
381
  /** One model request of a tool call (`ToolCallHooks.onRequest`). */