llm-large-files 0.10.1 → 0.10.2

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 (47) hide show
  1. package/CHANGELOG.md +75 -0
  2. package/dist/ask.d.ts +16 -0
  3. package/dist/ask.d.ts.map +1 -1
  4. package/dist/ask.js +26 -2
  5. package/dist/ask.js.map +1 -1
  6. package/dist/cache.d.ts +27 -1
  7. package/dist/cache.d.ts.map +1 -1
  8. package/dist/cache.js +96 -21
  9. package/dist/cache.js.map +1 -1
  10. package/dist/index.d.ts +2 -2
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +2 -2
  13. package/dist/index.js.map +1 -1
  14. package/dist/ingest.d.ts +12 -1
  15. package/dist/ingest.d.ts.map +1 -1
  16. package/dist/ingest.js +146 -11
  17. package/dist/ingest.js.map +1 -1
  18. package/dist/library.d.ts +55 -5
  19. package/dist/library.d.ts.map +1 -1
  20. package/dist/library.js +74 -4
  21. package/dist/library.js.map +1 -1
  22. package/dist/stores.d.ts +38 -1
  23. package/dist/stores.d.ts.map +1 -1
  24. package/dist/stores.js +184 -6
  25. package/dist/stores.js.map +1 -1
  26. package/dist/testing/store-checks.d.ts +8 -3
  27. package/dist/testing/store-checks.d.ts.map +1 -1
  28. package/dist/testing/store-checks.js +74 -1
  29. package/dist/testing/store-checks.js.map +1 -1
  30. package/dist/types.d.ts +56 -0
  31. package/dist/types.d.ts.map +1 -1
  32. package/docs/guides/deployment.md +3 -3
  33. package/docs/guides/storage.md +62 -8
  34. package/docs/reference/ask.md +25 -3
  35. package/docs/reference/events.md +1 -1
  36. package/docs/reference/library.md +106 -11
  37. package/docs/reference/testing.md +10 -4
  38. package/docs/security.md +2 -1
  39. package/package.json +1 -1
  40. package/src/ask.ts +35 -2
  41. package/src/cache.ts +95 -19
  42. package/src/index.ts +2 -2
  43. package/src/ingest.ts +144 -12
  44. package/src/library.ts +122 -8
  45. package/src/stores.ts +174 -7
  46. package/src/testing/store-checks.ts +74 -3
  47. package/src/types.ts +55 -0
package/src/ingest.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  // `files.ingest`: reads a file, prepares its text, and stores it. Moved out of library.ts in 0.9.0:
2
2
  // the library hands it what it needs in an `IngestContext`.
3
3
  import { randomUUID } from "node:crypto";
4
- import { checkMetaVersion, checkOwner, checkStuck, formatDuration, heldBy, metaOf, OWNER_REQUIRED, SCOPE_REQUIRED, storeCall, storeContext, watchStuck, type AccessRules } from "./access.js";
4
+ import { checkMetaVersion, checkOwner, checkStuck, formatDuration, heldBy, isTimeLimit, metaOf, OWNER_REQUIRED, SCOPE_REQUIRED, storeCall, storeContext, watchStuck, type AccessRules } from "./access.js";
5
5
  import { buildLogProfileInSlices, buildOutlineInSlices, looksLikeLog } from "./analyze.js";
6
6
  import { DocumentScopeError, DocumentStoreError, IngestError, isStoreWriteFailure, noteStoreWriteFailure, toIngestError } from "./errors.js";
7
7
  import { EventEmitter, eventErrorOf, newRunId, type EventError, type IngestEvent, type IngestStage } from "./events.js";
@@ -14,10 +14,10 @@ import { formatBytes } from "./plan.js";
14
14
  import { measureQuality, type TextQuality } from "./quality.js";
15
15
  import { checkScope } from "./scope.js";
16
16
  import { absolutePath, isSha256, readRanges, readSource, sha256InSlices, statSource, type SourceRead } from "./source.js";
17
- import { APP_DOCUMENT_ID_PATTERN, DOCUMENT_META_VERSION } from "./stores.js";
17
+ import { APP_DOCUMENT_ID_PATTERN, DOCUMENT_META_VERSION, usableStoreMethod } from "./stores.js";
18
18
  import { buildTextIndexInSlices, canSerialize, serializeTextIndex } from "./text-index.js";
19
19
  import { measureText, prepareText, removeInvisible, sliceWhole } from "./text.js";
20
- import type { DocumentContext, DocumentFormat, DocumentMeta, DocumentScope, DocumentStore, DocumentSummary, ExtractedText, ExtractProgress, Extractor } from "./types.js";
20
+ import type { AppData, DocumentContext, DocumentFormat, DocumentMeta, DocumentScope, DocumentStore, DocumentSummary, ExtractedText, ExtractProgress, Extractor } from "./types.js";
21
21
 
22
22
  export { checkOwner } from "./access.js";
23
23
 
@@ -77,6 +77,10 @@ type Target = {
77
77
  readonly scope: DocumentScope | undefined;
78
78
  /** The context of every store call of the ingest. */
79
79
  readonly context: DocumentContext;
80
+ /** `IngestInput.appData`, checked and copied (0.10.2). */
81
+ readonly appData?: AppData;
82
+ /** `IngestInput.dedupe` (0.10.2). */
83
+ readonly dedupe: boolean;
80
84
  };
81
85
 
82
86
  /** The TypeError of an `IngestInput.id` of another shape. It does not repeat the ID, which may hold what it must not. */
@@ -91,7 +95,13 @@ function targetOf(input: IngestInput | IngestFromSource, rules: AccessRules): Ta
91
95
  const { id, ifExists = "fail" } = input;
92
96
  if (id !== undefined && (typeof id !== "string" || !APP_DOCUMENT_ID_PATTERN.test(id))) throw new TypeError(ID_SHAPE);
93
97
  if (ifExists !== "fail" && ifExists !== "replace") throw new TypeError('ifExists must be "fail" or "replace".');
94
- return { id, ifExists, owner: input.owner, scope, context: storeContext(scope, input.owner) };
98
+ // Null is none, as a database gives a field that was left out.
99
+ const given: unknown = input.appData ?? undefined;
100
+ const appData = given === undefined ? undefined : checkAppData(given, "appData");
101
+ const dedupe: unknown = input.dedupe ?? false;
102
+ if (typeof dedupe !== "boolean") throw new TypeError("dedupe must be true or false.");
103
+ if (dedupe && id !== undefined) throw new TypeError("dedupe and id cannot be given together: an application's ID names its own document.");
104
+ return { id, ifExists, owner: input.owner, scope, context: storeContext(scope, input.owner), ...(appData !== undefined ? { appData } : {}), dedupe };
95
105
  }
96
106
 
97
107
  /** The refusal of an application's ID that is taken (`ifExists`). It says nothing of the document that has it. */
@@ -121,6 +131,47 @@ async function claim(context: IngestContext, target: Target & { id: string }, na
121
131
  throw exists(name);
122
132
  }
123
133
 
134
+ /**
135
+ * The document of the same owner and scope whose file has this SHA-256 (`IngestInput.dedupe`), as
136
+ * the store lists them (`list`), when its text is still there: the latest stored, when several
137
+ * are. Expired documents (as `getMeta` reads the date), and those of a newer version, are not it.
138
+ * Its expiry is counted again from now when the store can change metadata alone (`patchMeta`), as
139
+ * `files.touch` does; a document the store then says is gone (deleted meanwhile) is not it either,
140
+ * and the next one is tried. Undefined when there is none. Each store call is refused at once while too many calls are stuck, and
141
+ * counts as stuck past `slotCapMs`, as the look-up of an application's ID does. New in 0.10.2.
142
+ */
143
+ async function sameDocument(context: IngestContext, target: Target, sha256: string): Promise<DocumentMeta | undefined> {
144
+ const { store, now, ttlMs, maxStuck, slotCapMs } = context;
145
+ const call = <T>(operation: "read" | "write", run: () => Promise<T>) => watchStuck(storeCall(operation, run, { maxStuck }), slotCapMs);
146
+ const list = usableStoreMethod(store, "list")!;
147
+ const listed: unknown = await call("read", () => list.call(store, target.context));
148
+ const at = now().getTime();
149
+ const candidates: DocumentMeta[] = [];
150
+ for (const item of Array.isArray(listed) ? listed : []) {
151
+ const meta = metaOf(item as DocumentMeta, (item as { id?: unknown } | null)?.id as string);
152
+ if (!meta || typeof meta.id !== "string" || !APP_DOCUMENT_ID_PATTERN.test(meta.id) || meta.sha256 !== sha256 || Date.parse(meta.expiresAt) <= at || !heldBy(meta, target.owner, target.scope)) continue;
153
+ const version: unknown = meta.metaVersion ?? 0;
154
+ if (typeof version === "number" && version <= DOCUMENT_META_VERSION) candidates.push(meta);
155
+ }
156
+ // The latest first: an older copy may be on its way out.
157
+ candidates.sort((left, right) => Date.parse(right.createdAt) - Date.parse(left.createdAt));
158
+ for (const meta of candidates) {
159
+ // Metadata whose text is gone is not a document: a byte of the text, or the whole text from a
160
+ // store that cannot read a range.
161
+ const there = typeof store.readTextRange === "function"
162
+ ? await call("read", () => store.readTextRange!(meta.id, 0, 1, target.context)) !== undefined
163
+ : await call("read", () => store.get(meta.id, target.context)) !== undefined;
164
+ if (!there) continue;
165
+ const patchMeta = usableStoreMethod(store, "patchMeta");
166
+ if (!patchMeta) return meta;
167
+ // The document of that `createdAt` only: one deleted and stored again under the ID is not it.
168
+ const one = { createdAt: meta.createdAt, ...(meta.owner !== undefined ? { owner: meta.owner } : {}), ...(meta.scope !== undefined ? { scope: meta.scope } : {}) };
169
+ const touched = metaOf(await call("write", () => patchMeta.call(store, meta.id, { ...one, expiresAt: expiryAfter(now(), ttlMs) }, target.context)), meta.id);
170
+ if (touched && touched.createdAt === meta.createdAt && heldBy(touched, target.owner, target.scope)) return touched;
171
+ }
172
+ return undefined;
173
+ }
174
+
124
175
  /**
125
176
  * Removes what an ingest wrote under its ID, after a write that failed or a listener that threw on
126
177
  * `ingest.finish`: only while the document there, if any, is the ingest's own (the same `createdAt`,
@@ -319,6 +370,37 @@ function fileOf(extracted: ExtractedText): { bytes: number; sha256: string } | u
319
370
  */
320
371
  export const NEVER_EXPIRES = "9999-12-31T23:59:59.999Z";
321
372
 
373
+ /** The expiry of a document stored, or used, at `at`: `ttlMs` later, or `NEVER_EXPIRES` past what a date can hold. */
374
+ export function expiryAfter(at: Date, ttlMs: number): string {
375
+ const expires = at.getTime() + ttlMs;
376
+ return expires >= Date.parse(NEVER_EXPIRES) ? NEVER_EXPIRES : new Date(expires).toISOString();
377
+ }
378
+
379
+ /** The most bytes `DocumentMeta.appData` may take, as JSON in UTF-8: 16 KB. New in 0.10.2. */
380
+ export const MAX_APP_DATA_BYTES = 16_384;
381
+
382
+ /**
383
+ * `appData` checked, and copied through JSON, as a store that keeps it as JSON gives it back. A
384
+ * value that is not an object (an array, a string, null), or that JSON cannot write (a BigInt, a
385
+ * loop), is a TypeError; one larger than `MAX_APP_DATA_BYTES` as JSON, a RangeError. What JSON
386
+ * leaves out (a function, undefined) is left out. `where` names the option in the message.
387
+ */
388
+ export function checkAppData(value: unknown, where: string): AppData {
389
+ const shape = `${where} must be a JSON object, such as { "rowId": "42" }`;
390
+ if (typeof value !== "object" || value === null || Array.isArray(value)) throw new TypeError(`${shape}.`);
391
+ let json: unknown;
392
+ try {
393
+ json = JSON.stringify(value);
394
+ } catch (error) {
395
+ throw new TypeError(`${shape}: ${error instanceof Error ? error.message : String(error)}`);
396
+ }
397
+ // A toJSON of its own may turn it into something else.
398
+ if (typeof json !== "string" || !json.startsWith("{")) throw new TypeError(`${shape}.`);
399
+ const bytes = Buffer.byteLength(json);
400
+ if (bytes > MAX_APP_DATA_BYTES) throw new RangeError(`${where} takes ${bytes} bytes as JSON; it may take ${MAX_APP_DATA_BYTES}.`);
401
+ return JSON.parse(json) as AppData;
402
+ }
403
+
322
404
  /** The refusal of a file whose text is larger than `maxTextBytes`. */
323
405
  const tooMuchText = (name: string, maxTextBytes: number) =>
324
406
  new Error(`${name} holds more than ${formatBytes(maxTextBytes)} of text, more than is kept from one file. Split it, and attach the part you need.`);
@@ -347,6 +429,9 @@ function settleWithin<T>(work: Promise<T>, ms: number, late: () => Error): Promi
347
429
  * itself cannot be stopped; it holds no turn.
348
430
  */
349
431
  function lookWithin<T>(look: Promise<T>, signal: AbortSignal | undefined, ms: number, syscall: "lstat" | "read"): Promise<T> {
432
+ // Counted as stuck past `ms`, as a store call is, until it ends (0.10.2): a volume that does not
433
+ // answer holds a thread of the pool either way.
434
+ watchStuck(look, ms);
350
435
  return settleWithin(signal ? untilAborted(look, signal) : look, ms, () =>
351
436
  Object.assign(new Error(`The file to ingest did not answer within ${formatDuration(ms)}.`), { code: "ETIMEDOUT", syscall }));
352
437
  }
@@ -530,6 +615,11 @@ type IngestWork = {
530
615
  * stays held in `ingesting` until they have ended, since they may still land.
531
616
  */
532
617
  writes?: Promise<unknown>;
618
+ /**
619
+ * The document the ingest gives back was stored before, by another ingest (`IngestInput.dedupe`):
620
+ * it is never removed for this one, whatever happens to it (0.10.2).
621
+ */
622
+ reused?: true;
533
623
  };
534
624
 
535
625
  /**
@@ -592,6 +682,8 @@ async function ingestFile(
592
682
  let sha256 = "";
593
683
  /** The bytes to keep in the store (`putOriginal`), until they are written. */
594
684
  let copy: Uint8Array | undefined;
685
+ /** The size and SHA-256 of a file at a path that its extractor reads, taken before for `dedupe`. */
686
+ let early: { bytes: number; sha256: string } | undefined;
595
687
  /**
596
688
  * A read of the file at `path`, or the signal's reason once it aborts. A volume that does not
597
689
  * answer within the ingest's time is the server's trouble, not the file's: a system error
@@ -599,6 +691,9 @@ async function ingestFile(
599
691
  * read (422, "split it"), since 0.10.0. The ingest keeps its turn until the read ends (`IngestSlot`).
600
692
  */
601
693
  const readWithin = async <T>(read: Promise<T>): Promise<T> => {
694
+ // Counted as stuck past the ingest's time, until it ends (0.10.2): only when the ingest has a
695
+ // time limit (`ingestTimeoutMs`), since a read without one may go on, and still be reading.
696
+ if (isTimeLimit(ingestTimeoutMs)) watchStuck(read, slotCapMs);
602
697
  work.abandoned = read;
603
698
  let got: T;
604
699
  try {
@@ -638,6 +733,34 @@ async function ingestFile(
638
733
  sha256 = got.sha256;
639
734
  got = undefined;
640
735
  }
736
+ // With `dedupe`, the document of the same owner and scope with the same SHA-256 is the answer,
737
+ // when there is one: the file is hashed first, and not extracted (0.10.2).
738
+ if (target.dedupe) {
739
+ if (path === undefined) sha256 = await sha256InSlices(bytes!, slicer);
740
+ else if (extractorReads) {
741
+ const got = await readWithin(readSource(path, maxUploadBytes, { keep: false, slicer, signal }));
742
+ early = { bytes: checkedSize(name, got.size, maxUploadBytes), sha256: got.sha256 };
743
+ sha256 = got.sha256;
744
+ }
745
+ // Within the time the ingest gives its store calls, and the caller's signal: a store that does
746
+ // not answer fails the ingest, which keeps its turn until the calls end (`IngestWork`).
747
+ const looking = sameDocument(context, target, sha256);
748
+ work.abandoned = looking;
749
+ let same: DocumentMeta | undefined;
750
+ try {
751
+ same = await settleWithin(untilAborted(looking, signal), slotCapMs, () => storeTimeout(name, slotCapMs, "read"));
752
+ } catch (error) {
753
+ // The ingest's time ran out while the store did not answer: the store's trouble (503), not
754
+ // a file that takes too long to read (422).
755
+ if (timedOut(error)) throw storeTimeout(name, ingestTimeoutMs, "read");
756
+ throw error;
757
+ }
758
+ work.abandoned = undefined;
759
+ if (same) {
760
+ work.reused = true;
761
+ return jsonCopy(same);
762
+ }
763
+ }
641
764
  // In a function of its own, so that the text as extracted is let go once it is prepared:
642
765
  // the steps after it hold only the prepared text.
643
766
  const read = async () => {
@@ -683,11 +806,11 @@ async function ingestFile(
683
806
  // Bytes given are hashed once the extractor is done with them, a slice at a time: the extractor
684
807
  // is called at once at the ingest's turn, as before 0.9.0, so the ingests of one turn reach it
685
808
  // in the order they came, and the SHA-256 is that of the bytes a kept copy holds.
686
- if (path === undefined) sha256 = await sha256InSlices(bytes!, slicer);
809
+ if (path === undefined && !target.dedupe) sha256 = await sha256InSlices(bytes!, slicer);
687
810
  if (path !== undefined && extractorReads) {
688
811
  // What the extractor read of the file: its size and SHA-256. One that did not say is hashed
689
812
  // here, a slice at a time, and nothing of it is kept.
690
- let hashed = done.file;
813
+ let hashed = done.file ?? early;
691
814
  if (!hashed) {
692
815
  const got = await readWithin(readSource(path, maxUploadBytes, { keep: false, slicer, signal }));
693
816
  hashed = { bytes: got.size, sha256: got.sha256 };
@@ -719,7 +842,6 @@ async function ingestFile(
719
842
  dispose();
720
843
  }
721
844
  const created = now();
722
- const expires = created.getTime() + ttlMs;
723
845
  // Kept by its ref, or as a copy in the store, which has the bytes to write.
724
846
  const keepOriginal = byRef ? keeps(format, true) : copy !== undefined;
725
847
  // A copy: the outline's headings and the log's timestamps are pieces of the text, and a piece
@@ -754,7 +876,9 @@ async function ingestFile(
754
876
  ...quality,
755
877
  createdAt: created.toISOString(),
756
878
  // Never, for a time to live without end (or one that runs past what a date can hold).
757
- expiresAt: expires >= Date.parse(NEVER_EXPIRES) ? NEVER_EXPIRES : new Date(expires).toISOString(),
879
+ expiresAt: expiryAfter(created, ttlMs),
880
+ // The application's own, checked when the ingest began. Never sent to the model.
881
+ ...(target.appData !== undefined ? { appData: target.appData } : {}),
758
882
  });
759
883
  const savedIndex = index && canSerialize(index) && index.lineCount === meta.lines && index.characters === meta.characters && index.textBytes === meta.textBytes
760
884
  ? serializeTextIndex(index)
@@ -880,6 +1004,7 @@ export async function ingestDocument(context: IngestContext, input: IngestInput
880
1004
  if (events.active) events.emit({ type: "ingest.start", ...startOf(input, stated?.size) });
881
1005
  checkOwner(input.owner);
882
1006
  const target = targetOf(input, context.rules);
1007
+ if (target.dedupe && !usableStoreMethod(context.store, "list")) throw new TypeError("dedupe needs a store with list(): MemoryDocumentStore and FileDocumentStore have it (a subclass of one, or one whose put, get, getMeta or delete was replaced, needs its own list).");
883
1008
  // The path looked at, as it was made absolute then (the working directory may have changed
884
1009
  // since); checked again for an input it was not taken from, which throws here.
885
1010
  const path = quietPath ?? sourcePathOf(input);
@@ -931,14 +1056,21 @@ export async function ingestDocument(context: IngestContext, input: IngestInput
931
1056
  throw toIngestError(error);
932
1057
  }
933
1058
  // Once more, before the document is told stored: a caller that has left by now gets its reason.
934
- if (input.signal?.aborted) await removeAbandoned(context, target, meta, work, input.signal.reason);
1059
+ // A document stored before (`dedupe`) is not this ingest's to remove.
1060
+ if (input.signal?.aborted) {
1061
+ if (work.reused) throw input.signal.reason;
1062
+ await removeAbandoned(context, target, meta, work, input.signal.reason);
1063
+ }
935
1064
  try {
936
1065
  events.emit({ type: "ingest.finish", document: toDocumentSummary(meta) });
937
1066
  } catch (error) {
938
1067
  // The caller never gets the id: the document goes, as on a throw of the listener a moment
939
- // earlier, while it is this ingest's own. The listener's error is passed on as it is.
940
- await removeOwn(context, target, meta).catch(() => undefined);
941
- forget(meta.id);
1068
+ // earlier, while it is this ingest's own (not one stored before, `dedupe`). The listener's
1069
+ // error is passed on as it is.
1070
+ if (!work.reused) {
1071
+ await removeOwn(context, target, meta).catch(() => undefined);
1072
+ forget(meta.id);
1073
+ }
942
1074
  throw error;
943
1075
  }
944
1076
  return meta;
package/src/library.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import {
2
- callerOf, checkMetaVersion, checkStuck, documentContext, isTimeLimit, mayUse, metaOf, OWNER_REQUIRED, SCOPE_REQUIRED, storeCall, storeContext, storeTimeout,
2
+ callerOf, checkMetaVersion, checkStuck, documentContext, heldBy, isTimeLimit, mayUse, metaOf, OWNER_REQUIRED, SCOPE_REQUIRED, storeCall, storeContext, storeTimeout,
3
3
  stuckCalls, type AccessRules, type Caller,
4
4
  } from "./access.js";
5
5
  import { givenBudget, resolveBudget, type ModelLimits } from "./budget.js";
@@ -7,7 +7,7 @@ import { DocumentCache, documentVersion, type Sized } from "./cache.js";
7
7
  import type { DocumentStoreOperation } from "./errors.js";
8
8
  import type { IngestEvent } from "./events.js";
9
9
  import { until } from "./http.js";
10
- import { ingestDocument, LONGEST_TIMER_MS, type IngestContext } from "./ingest.js";
10
+ import { checkAppData, expiryAfter, ingestDocument, LONGEST_TIMER_MS, type IngestContext } from "./ingest.js";
11
11
  import { Limiter } from "./limiter.js";
12
12
  import { canBeReadWhole, TABLE_FORMATS } from "./plan.js";
13
13
  import { prepareDocuments, type PrepareContext } from "./prepare.js";
@@ -16,11 +16,12 @@ import { SearchableDocument, type DocumentSource } from "./search.js";
16
16
  import { TimeSlicer } from "./pause.js";
17
17
  import { checkScope } from "./scope.js";
18
18
  import { isSha256, sha256InSlices } from "./source.js";
19
- import { APP_DOCUMENT_ID_PATTERN } from "./stores.js";
19
+ import { APP_DOCUMENT_ID_PATTERN, DOCUMENT_META_VERSION, usableStoreMethod } from "./stores.js";
20
20
  import { wellFormed } from "./text.js";
21
21
  import type { RetryOptions } from "./retry.js";
22
22
  import { createDocumentTools, type PageLookTurns } from "./tools.js";
23
23
  import type {
24
+ AppData,
24
25
  Budget,
25
26
  DocumentContext,
26
27
  DocumentFormat,
@@ -29,6 +30,7 @@ import type {
29
30
  DocumentStore,
30
31
  Extractor,
31
32
  GenerateText,
33
+ MetaPatch,
32
34
  PreparedContext,
33
35
  ProgressListener,
34
36
  ToolName,
@@ -36,7 +38,7 @@ import type {
36
38
  } from "./types.js";
37
39
 
38
40
  export { DEFAULT_BUDGET } from "./budget.js";
39
- export { checkOwner, cleanFileName, cleanMimeType, NEVER_EXPIRES, toDocumentSummary } from "./ingest.js";
41
+ export { checkOwner, cleanFileName, cleanMimeType, MAX_APP_DATA_BYTES, NEVER_EXPIRES, toDocumentSummary } from "./ingest.js";
40
42
 
41
43
  export type LargeFilesOptions = {
42
44
  /** Where extracted text is kept: `new FileDocumentStore(dir)`, `new MemoryDocumentStore()`, or your own. */
@@ -97,7 +99,9 @@ export type LargeFilesOptions = {
97
99
  scannedPdfPages?: number;
98
100
  /**
99
101
  * The most memory, in bytes, that documents kept ready for repeated tool calls may take.
100
- * Defaults to 256 MB. A document larger than this is read again for each call. 0 keeps none.
102
+ * Defaults to 256 MB. A document larger than this is not kept with the others: since 0.10.2 the
103
+ * last one is kept apart for a minute after its last use (P4), so the tool calls of a question
104
+ * do not each load it again; before, it was read again for each call. 0 keeps none.
101
105
  *
102
106
  * Every use of a kept document first asks the store whether it is still there, so a document
103
107
  * deleted or expired on another server sharing the store is never served from memory here.
@@ -275,6 +279,23 @@ export type IngestInput = {
275
279
  * deletes the file: `delete` leaves it. New in 0.9.0.
276
280
  */
277
281
  original?: { ref: string };
282
+ /**
283
+ * The application's own data about the document, kept as `DocumentMeta.appData`: a JSON object
284
+ * of at most 16 KB as JSON (`MAX_APP_DATA_BYTES`). Another value is a TypeError; a larger one, a
285
+ * RangeError. Never sent to the model, nor in a summary. Change it later with `files.update`.
286
+ * New in 0.10.2.
287
+ */
288
+ appData?: object;
289
+ /**
290
+ * When the store already has a document of the same owner and scope whose file has the same
291
+ * SHA-256, and its text is there, give back that document instead of storing another: its name,
292
+ * ID, `createdAt` and `appData` stay its own (a `createdAt` before the ingest began tells it from
293
+ * a new one: never delete it as one this ingest made), and its expiry is counted again from now
294
+ * when the store has `patchMeta`. The file is read once to hash it, and not extracted. It needs a store with `list`
295
+ * (another is a TypeError), and it cannot be given with `id` (a TypeError). Never across owners
296
+ * or scopes (H6). New in 0.10.2.
297
+ */
298
+ dedupe?: boolean;
278
299
  };
279
300
 
280
301
  /** A file to ingest from where it is, rather than from bytes in memory (`IngestFromSource`). New in 0.9.0. */
@@ -460,6 +481,32 @@ export interface LargeFiles {
460
481
  * compiles; the one `createLargeFiles` makes has it. New in 0.10.0.
461
482
  */
462
483
  toolsFor?(ids: string[], options: ToolOptions & { access: AccessOptions }): Promise<{ tools: ToolSet; missing: string[] }>;
484
+ /**
485
+ * The documents held by exactly the caller's owner and scope (`access.owner` and `access.scope`;
486
+ * without one, those without one), as `getMeta` would give each, the oldest first. A document
487
+ * without an owner is listed only to a caller without one: its ID is all it takes to use it, and
488
+ * a list must not hand it to every user. Expired documents, and metadata this version cannot read
489
+ * (damaged, or of a newer version), are left out. It needs a store with `list`
490
+ * (`MemoryDocumentStore` and `FileDocumentStore` have it): another is a TypeError. A store that
491
+ * fails is a `DocumentStoreError` (operation "read"). Optional, so that a `LargeFiles` of your own
492
+ * still compiles; the one `createLargeFiles` makes has it. New in 0.10.2.
493
+ */
494
+ list?(access?: AccessOptions): Promise<DocumentMeta[]>;
495
+ /**
496
+ * Marks a document used: its expiry is counted again from now (`ttlMs`), so that a chat that
497
+ * still reads a file keeps it. An expiry already later stays. Returns the metadata as it now is,
498
+ * or undefined when the document is missing for this caller. It needs a store with `patchMeta`:
499
+ * another is a TypeError. A store that fails is a `DocumentStoreError`. Optional, as `list` is.
500
+ * New in 0.10.2.
501
+ */
502
+ touch?(id: string, access?: AccessOptions): Promise<DocumentMeta | undefined>;
503
+ /**
504
+ * Changes the application's own data about a document (`appData`, a JSON object; null removes
505
+ * it), and nothing else. Returns the metadata as it now is, or undefined when the document is
506
+ * missing for this caller. It needs a store with `patchMeta`, as `touch` does. Optional, as `list`
507
+ * is. New in 0.10.2.
508
+ */
509
+ update?(id: string, changes: { appData?: object | null }, access?: AccessOptions): Promise<DocumentMeta | undefined>;
463
510
  }
464
511
 
465
512
  /** What `files.stats()` counts: plain numbers, for metrics and alerts. New in 0.10.0. */
@@ -472,13 +519,16 @@ export type LargeFilesStats = {
472
519
  pageLooks: { active: number; waiting: number };
473
520
  /**
474
521
  * What is kept in memory: its bytes, how many entries (documents, and pieces of documents read by
475
- * range), and the most bytes they may take (`cacheBytes`).
522
+ * range), and the most bytes those entries may take (`cacheBytes`). Since 0.10.2 `bytes` also
523
+ * counts the last document larger than `cacheBytes`, kept apart on top of it, which `entries`
524
+ * does not.
476
525
  */
477
526
  cache: { bytes: number; entries: number; maxBytes: number };
478
527
  /**
479
528
  * Calls of this process that ran past their time limit and have not settled: the store calls of
480
- * every library (past `storeTimeoutMs`, or for `ingest` past `ingestTimeoutMs`), and the calls to
481
- * the disk of the upload handlers (`uploadIdleTimeoutMs`).
529
+ * every library (past `storeTimeoutMs`, or for `ingest` past `ingestTimeoutMs`), the calls to
530
+ * the disk of the upload handlers (`uploadIdleTimeoutMs`), and since 0.10.2 an ingest's own
531
+ * reads of a path upload.
482
532
  */
483
533
  stuckStoreCalls: number;
484
534
  /** This library's limit on them (`maxStuckStoreCalls`). */
@@ -768,6 +818,27 @@ export function createLargeFiles(options: LargeFilesOptions): CreatedLargeFiles
768
818
  return meta && mayUse(meta, caller, rules) ? meta : undefined;
769
819
  }
770
820
 
821
+ /**
822
+ * Changes the metadata of a document `caller` may use (`patchMeta`): the document as `getMeta`
823
+ * finds it, then the change, made by the store to the document of that `createdAt` only, so that
824
+ * one deleted and stored again under the ID since is never changed. The metadata as it is after
825
+ * the change, or undefined when the document is missing for this caller or went meanwhile.
826
+ * `operation` names the method in the TypeError of a store without `patchMeta`.
827
+ */
828
+ async function changeMeta(id: string, caller: Caller, operation: string, change: Omit<MetaPatch, "createdAt">): Promise<DocumentMeta | undefined> {
829
+ const patchMeta = usableStoreMethod(store, "patchMeta");
830
+ if (!patchMeta) throw new TypeError(`files.${operation} needs a store with patchMeta(): MemoryDocumentStore and FileDocumentStore have it (a subclass of one, or one whose put, get, getMeta or delete was replaced, needs its own patchMeta).`);
831
+ const meta = await metaFor(id, caller);
832
+ if (!meta) return undefined;
833
+ // An expiry already as late: nothing to write.
834
+ if (change.appData === undefined && change.expiresAt !== undefined && Date.parse(change.expiresAt) <= Date.parse(meta.expiresAt)) return meta;
835
+ // The document as it was looked up: its `createdAt`, owner and scope.
836
+ const one = { createdAt: meta.createdAt, ...(meta.owner !== undefined ? { owner: meta.owner } : {}), ...(meta.scope !== undefined ? { scope: meta.scope } : {}) };
837
+ const changed = metaOf(await timed("write", () => patchMeta.call(store, id, { ...change, ...one }, caller.context), caller.signal), id);
838
+ // The store changed that document, or none: one of another is not given back.
839
+ return changed && changed.createdAt === meta.createdAt && heldBy(changed, meta.owner, meta.scope) ? wholeName(changed) : undefined;
840
+ }
841
+
771
842
  /**
772
843
  * A document ready to read and search, for `caller`, who may use it. The store is asked first,
773
844
  * every time: a kept copy is used only while the store still has the same document. `known` is
@@ -1055,6 +1126,49 @@ export function createLargeFiles(options: LargeFilesOptions): CreatedLargeFiles
1055
1126
  }
1056
1127
  return { tools: tools(found, toolOptions), missing };
1057
1128
  },
1129
+
1130
+ async list(access) {
1131
+ const caller = callerOf(access, rules);
1132
+ const list = usableStoreMethod(store, "list");
1133
+ if (!list) throw new TypeError("files.list needs a store with list(): MemoryDocumentStore and FileDocumentStore have it (a subclass of one, or one whose put, get, getMeta or delete was replaced, needs its own list).");
1134
+ const found: unknown = await reading(() => list.call(store, caller.context), caller.signal);
1135
+ const at = now().getTime();
1136
+ const listed: DocumentMeta[] = [];
1137
+ for (const item of Array.isArray(found) ? found : []) {
1138
+ const meta = metaOf(item as DocumentMeta, (item as { id?: unknown } | null)?.id as string);
1139
+ // Damaged, or of another ID than a document may have, or expired (as `getMeta` reads the date): not listed.
1140
+ if (!meta || typeof meta.id !== "string" || !isDocumentId(meta.id) || Date.parse(meta.expiresAt) <= at) continue;
1141
+ // Written by a newer version of the package: left out, where `getMeta` would throw.
1142
+ const version: unknown = meta.metaVersion ?? 0;
1143
+ if (typeof version !== "number" || version > DOCUMENT_META_VERSION) continue;
1144
+ // Exactly the caller's owner and scope: a document without an owner, which any caller who
1145
+ // has its ID may use, is never handed to a caller with an owner (nor one without a scope to
1146
+ // a caller with one), and the rules of `requireOwner` and `requireScope` still hold.
1147
+ if (heldBy(meta, caller.owner, caller.scope) && mayUse(meta, caller, rules)) listed.push(wholeName(meta));
1148
+ }
1149
+ // The oldest first, then by ID: the same order whatever order the store gave.
1150
+ return listed.sort((left, right) => (Date.parse(left.createdAt) - Date.parse(right.createdAt)) || (left.id < right.id ? -1 : left.id > right.id ? 1 : 0));
1151
+ },
1152
+
1153
+ async touch(id, access) {
1154
+ // An expiry already later stays: the store keeps the later of the two.
1155
+ return changeMeta(id, callerOf(access, rules), "touch", { expiresAt: expiryAfter(now(), ttlMs) });
1156
+ },
1157
+
1158
+ async update(id, changes, access) {
1159
+ if (typeof changes !== "object" || changes === null || Array.isArray(changes)) throw new TypeError("files.update needs the changes as an object, such as { appData: { rowId: \"42\" } }.");
1160
+ const unknown = Object.keys(changes).filter((key) => key !== "appData");
1161
+ if (unknown.length > 0) throw new TypeError(`files.update changes appData only; it was given ${unknown.map((key) => JSON.stringify(key)).join(", ")}.`);
1162
+ const given: unknown = changes.appData;
1163
+ const appData: AppData | null | undefined = given === undefined || given === null ? given : checkAppData(given, "appData");
1164
+ const caller = callerOf(access, rules);
1165
+ if (appData === undefined) {
1166
+ // Nothing to change: the document as it is, when the store could change it.
1167
+ if (!usableStoreMethod(store, "patchMeta")) throw new TypeError("files.update needs a store with patchMeta(): MemoryDocumentStore and FileDocumentStore have it (a subclass of one, or one whose put, get, getMeta or delete was replaced, needs its own patchMeta).");
1168
+ return metaFor(id, caller);
1169
+ }
1170
+ return changeMeta(id, caller, "update", { appData });
1171
+ },
1058
1172
  };
1059
1173
 
1060
1174
  /**