@wirecat/cli-core 0.738.0 → 0.740.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 (44) hide show
  1. package/CHANGELOG.md +59 -0
  2. package/dist/attachments/ocr.d.ts +2 -0
  3. package/dist/attachments/ocr.js +2 -1
  4. package/dist/attachments/tesseract.d.ts +11 -0
  5. package/dist/attachments/tesseract.js +82 -0
  6. package/dist/cli/documents/file-edit.js +79 -34
  7. package/dist/cli/documents/file-update.d.ts +5 -0
  8. package/dist/cli/documents/index.d.ts +2 -1
  9. package/dist/cli/documents/index.js +2 -1
  10. package/dist/cli/documents/library.d.ts +12 -0
  11. package/dist/cli/documents/library.js +33 -3
  12. package/dist/cli/documents/manifest/manifest.d.ts +10 -0
  13. package/dist/cli/documents/manifest/manifest.js +9 -1
  14. package/dist/cli/documents/manifest/source.d.ts +4 -1
  15. package/dist/cli/documents/manifest/source.js +67 -1
  16. package/dist/cli/documents/rekey.d.ts +22 -0
  17. package/dist/cli/documents/rekey.js +25 -0
  18. package/dist/documents/file-mirror-model.d.ts +4 -1
  19. package/dist/documents/index.d.ts +1 -0
  20. package/dist/documents/index.js +1 -0
  21. package/dist/documents/model.d.ts +8 -0
  22. package/dist/errors/reasons.js +6 -15
  23. package/dist/errors/sftp-reasons.d.ts +5 -0
  24. package/dist/errors/sftp-reasons.js +15 -0
  25. package/dist/office/create.d.ts +38 -7
  26. package/dist/office/create.js +84 -20
  27. package/dist/office/index.d.ts +1 -1
  28. package/dist/services/documents/file-text.d.ts +6 -1
  29. package/dist/services/documents/file-text.js +29 -11
  30. package/dist/services/documents/ingestion.d.ts +5 -0
  31. package/dist/services/documents/ingestion.js +21 -1
  32. package/dist/services/documents/plan.js +151 -102
  33. package/dist/services/documents/ports.d.ts +3 -0
  34. package/dist/services/documents/scans.d.ts +42 -0
  35. package/dist/services/documents/scans.js +136 -0
  36. package/dist/services/documents/sync.js +57 -4
  37. package/dist/services/files/guarded-write.d.ts +6 -0
  38. package/dist/services/files/guarded-write.js +7 -1
  39. package/dist/services/files/mirror.js +2 -3
  40. package/dist/store/sqlite/file-note-rekey.d.ts +8 -0
  41. package/dist/store/sqlite/file-note-rekey.js +47 -0
  42. package/dist/store/sqlite/notes.d.ts +7 -2
  43. package/dist/store/sqlite/notes.js +4 -1
  44. package/package.json +1 -1
@@ -1,4 +1,4 @@
1
- import { CliError } from "@wirecat/cli-base";
1
+ import { CliError, isCliError } from "@wirecat/cli-base";
2
2
  import { walkQuery } from "@wirecat/cli-base/query";
3
3
  export const documentIngestion = (store, options) => {
4
4
  const folder = async (principal, create) => {
@@ -101,6 +101,26 @@ export const documentIngestion = (store, options) => {
101
101
  await options.observed?.(principal, content.metadata, note.id);
102
102
  return note.ref;
103
103
  },
104
+ /**
105
+ * Moves a synced document to the new id its source gave the file, as a replace through a temporary file does, so
106
+ * its tags, the notes about it and its links stay with it. False when the file was never synced.
107
+ */
108
+ rekey: async (principal, from, to) => {
109
+ const selected = await folder(principal, false);
110
+ if (!selected)
111
+ return false;
112
+ try {
113
+ const [was, now] = [options.externalId(from), options.externalId(to)];
114
+ const note = await store.notes.renameFileNote(selected.id, was, now, { fold: true });
115
+ await stale(note.ref);
116
+ return true;
117
+ }
118
+ catch (error) {
119
+ if (isCliError(error) && error.code === "not_found")
120
+ return false;
121
+ throw error;
122
+ }
123
+ },
104
124
  remove: async (principal, id, reason) => {
105
125
  const selected = await folder(principal, false);
106
126
  if (selected) {
@@ -228,114 +228,156 @@ export const planDocuments = async (options, source, state, roots, limit, pictur
228
228
  let spent = 0;
229
229
  let listed = 0;
230
230
  let stopped = null;
231
- try {
232
- for (let step = walk.stack.at(-1); step; step = walk.stack.at(-1)) {
233
- if (step.ancestry.includes(step.id))
234
- throw new CliError("invalid_response", "folder traversal contains a cycle");
235
- if (visited.has(step.id)) {
236
- walk.stack.pop();
237
- continue;
238
- }
239
- // One listing at least per call, so a folder with more children than the bound still moves on.
240
- // The run's own signal too: a cooperative sync is not cut from outside, and a CLI may pass no budget.
241
- // The time budget keeps a margin of 5 s or more, so a short run would never list a folder: its first request
242
- // goes ahead while one still fits before the deadline itself.
243
- const taken = options.signal?.aborted
244
- ? "cancelled"
245
- : listed > 0 && spent >= maxEntries
246
- ? "entries"
247
- : budget?.take();
248
- stopped = taken === "deadline" && budget?.first?.() ? null : (taken ?? null);
249
- if (stopped)
250
- break;
251
- if (!step.folder) {
252
- const known = state.folders[step.id];
253
- let root;
254
- try {
255
- root = await source.metadata(step.id, known);
256
- }
257
- catch (error) {
258
- // Without a feed, a folder the last pass held and the provider no longer finds is skipped as unavailable,
259
- // as a round of changes does, so a moved or deleted root does not fail every sync. A source with a feed
260
- // walks in full only on a rescan, where a root it cannot read still fails and keeps what it holds.
261
- if (feed || !known || errorOf(error).code !== "not_found")
262
- throw error;
263
- walk.stack.pop();
264
- visited.add(step.id);
265
- folders[step.id] = { ...known, trashed: true };
266
- spent++;
267
- listed++;
268
- continue;
269
- }
270
- if (!isFolder(root) || root.trashed)
271
- throw new CliError("validation_error", "configured root is not an accessible folder");
272
- container(root);
273
- // Kept on the step, so a call stopped before the listing does not read the root again.
274
- step.folder = root;
275
- stopped = charge();
276
- if (stopped)
277
- break;
278
- }
279
- const folder = step.folder;
280
- let children;
281
- let more;
231
+ // A value that is not a whole number would leave the batch empty and end the walk as if it found nothing.
232
+ const asked = source.parallelListings;
233
+ const width = Number.isInteger(asked) && asked > 1 ? Math.min(asked, 8) : 1;
234
+ // A root read in a listing that then fails is still filed, as the walk saves it on the step.
235
+ const rootsRead = new Map();
236
+ const list = async (step) => {
237
+ if (!step.folder) {
238
+ let root;
282
239
  try {
283
- if (source.childrenPage)
284
- ({ files: children, cursor: more } = await source.childrenPage(folder.id, step.listing, folder));
285
- else
286
- children = await source.children(folder.id, folder);
240
+ root = await source.metadata(step.id, state.folders[step.id]);
287
241
  }
288
242
  catch (error) {
289
- if (errorOf(error).code !== "not_found")
243
+ // Without a feed, a folder the last pass held and the provider no longer finds is skipped as unavailable,
244
+ // as a round of changes does, so a moved or deleted root does not fail every sync. A source with a feed
245
+ // walks in full only on a rescan, where a root it cannot read still fails and keeps what it holds.
246
+ if (feed || !state.folders[step.id] || errorOf(error).code !== "not_found")
290
247
  throw error;
291
- // A later page's 404 can be a cursor the provider no longer knows: the folder is listed again from its first
292
- // page, which tells a gone folder from a stale cursor, and the files already kept are only kept again.
293
- if (step.listing !== undefined) {
294
- delete step.listing;
295
- spent++;
296
- listed++;
297
- continue;
298
- }
299
- // Deleted or unshared since the walk saved it: gone, with what is below it, instead of failing every sync.
300
- // A listing's 404 alone can be passing, so the folder is read again and is gone only when that read is a
301
- // 404 too or finds it trashed; on any doubt the call fails and the next sync lists it again.
302
- if (!(await vanished(folder.id, folder)))
303
- throw error;
304
- walk.stack.pop();
305
- visited.add(folder.id);
306
- folders[folder.id] = { ...folder, trashed: true };
307
- drop(folder.id, "unavailable");
308
- spent++;
309
- listed++;
310
- continue;
248
+ return { kind: "root-gone" };
311
249
  }
312
- spent += 1 + children.length;
313
- listed++;
314
- walk.discovered += children.length;
315
- folders[folder.id] = folder;
316
- const nested = [];
317
- for (const file of children)
318
- if (isFolder(file)) {
319
- container(file);
320
- if (excluded(file))
321
- continue;
322
- if (walked(file.id))
323
- folders[file.id] = file;
324
- else
325
- nested.push({ id: file.id, ancestry: [...step.ancestry, folder.id], folder: file });
326
- }
327
- else if (file.trashed)
328
- trash(file);
250
+ if (!isFolder(root) || root.trashed)
251
+ throw new CliError("validation_error", "configured root is not an accessible folder");
252
+ rootsRead.set(step, root);
253
+ // Kept on the step, so a call stopped before the listing does not read the root again.
254
+ step.folder = root;
255
+ const after = charge();
256
+ if (after)
257
+ return { kind: "root", stopped: after };
258
+ }
259
+ const folder = step.folder;
260
+ try {
261
+ if (!source.childrenPage)
262
+ return { kind: "listed", children: await source.children(folder.id, folder) };
263
+ const page = await source.childrenPage(folder.id, step.listing, folder);
264
+ return { kind: "listed", children: page.files, ...(page.cursor ? { more: page.cursor } : {}) };
265
+ }
266
+ catch (error) {
267
+ if (errorOf(error).code !== "not_found")
268
+ throw error;
269
+ // A later page's 404 can be a cursor the provider no longer knows: the folder is listed again from its first
270
+ // page, which tells a gone folder from a stale cursor, and the files already kept are only kept again.
271
+ if (step.listing !== undefined)
272
+ return { kind: "relist" };
273
+ // Deleted or unshared since the walk saved it: gone, with what is below it, instead of failing every sync.
274
+ // A listing's 404 alone can be passing, so the folder is read again and is gone only when that read is a
275
+ // 404 too or finds it trashed; on any doubt the call fails and the next sync lists it again.
276
+ if (!(await vanished(folder.id, folder)))
277
+ throw error;
278
+ return { kind: "gone" };
279
+ }
280
+ };
281
+ // In the step's own place, so the stack keeps the order a walk one folder at a time has.
282
+ const place = (step, entries) => current.stack.splice(current.stack.indexOf(step), 1, ...entries);
283
+ const apply = (step, result) => {
284
+ if (result.kind === "root") {
285
+ stopped ??= result.stopped;
286
+ return;
287
+ }
288
+ spent++;
289
+ listed++;
290
+ if (result.kind === "relist") {
291
+ delete step.listing;
292
+ return;
293
+ }
294
+ if (result.kind === "root-gone") {
295
+ place(step, []);
296
+ visited.add(step.id);
297
+ folders[step.id] = { ...state.folders[step.id], trashed: true };
298
+ return;
299
+ }
300
+ const folder = step.folder;
301
+ if (result.kind === "gone") {
302
+ place(step, []);
303
+ visited.add(folder.id);
304
+ folders[folder.id] = { ...folder, trashed: true };
305
+ drop(folder.id, "unavailable");
306
+ return;
307
+ }
308
+ const { children, more } = result;
309
+ spent += children.length;
310
+ current.discovered += children.length;
311
+ folders[folder.id] = folder;
312
+ const nested = [];
313
+ for (const file of children)
314
+ if (isFolder(file)) {
315
+ container(file);
316
+ if (excluded(file))
317
+ continue;
318
+ if (walked(file.id))
319
+ folders[file.id] = file;
329
320
  else
330
- keep(file);
331
- walk.stack.pop();
332
- for (const entry of nested.reverse())
333
- walk.stack.push(entry);
334
- // A folder with more pages goes back on top with its cursor, above its child folders.
335
- if (more)
336
- walk.stack.push({ ...step, folder, listing: more });
321
+ nested.push({ id: file.id, ancestry: [...step.ancestry, folder.id], folder: file });
322
+ }
323
+ else if (file.trashed)
324
+ trash(file);
337
325
  else
338
- visited.add(folder.id);
326
+ keep(file);
327
+ // A folder with more pages goes back on top with its cursor, above its child folders.
328
+ place(step, [...nested.reverse(), ...(more ? [{ ...step, folder, listing: more }] : [])]);
329
+ if (!more)
330
+ visited.add(folder.id);
331
+ };
332
+ const done = (step) => {
333
+ if (step.ancestry.includes(step.id))
334
+ throw new CliError("invalid_response", "folder traversal contains a cycle");
335
+ return visited.has(step.id);
336
+ };
337
+ try {
338
+ for (;;) {
339
+ for (let top = current.stack.at(-1); top && done(top); top = current.stack.at(-1))
340
+ current.stack.pop();
341
+ // The folders at the top of the stack, listed together on a source that allows it; each takes its request
342
+ // before it starts, so the budget and the deadline bound the batch as they bound one listing.
343
+ const batch = [];
344
+ for (let at = current.stack.length - 1; at >= 0 && batch.length < width; at--) {
345
+ const step = current.stack[at];
346
+ if (done(step) || batch.some((one) => one.id === step.id))
347
+ continue;
348
+ // One listing at least per call, so a folder with more children than the bound still moves on.
349
+ // The run's own signal too: a cooperative sync is not cut from outside, and a CLI may pass no budget.
350
+ // The time budget keeps a margin of 5 s or more, so a short run would never list a folder: its first
351
+ // request goes ahead while one still fits before the deadline itself.
352
+ const taken = options.signal?.aborted
353
+ ? "cancelled"
354
+ : (listed > 0 || batch.length > 0) && spent >= maxEntries
355
+ ? "entries"
356
+ : budget?.take();
357
+ stopped = taken === "deadline" && budget?.first?.() ? null : (taken ?? null);
358
+ if (stopped)
359
+ break;
360
+ batch.push(step);
361
+ }
362
+ if (!batch.length)
363
+ break;
364
+ const results = await Promise.allSettled(batch.map(list));
365
+ let failure;
366
+ batch.forEach((step, at) => {
367
+ const root = rootsRead.get(step);
368
+ if (root)
369
+ container(root);
370
+ rootsRead.delete(step);
371
+ const result = results[at];
372
+ if (result.status === "fulfilled")
373
+ apply(step, result.value);
374
+ else
375
+ failure ??= { reason: result.reason };
376
+ });
377
+ if (failure)
378
+ throw failure.reason;
379
+ if (stopped)
380
+ break;
339
381
  if (now() - savedAt > SAVE_EVERY_MS)
340
382
  record();
341
383
  }
@@ -376,7 +418,14 @@ export const planDocuments = async (options, source, state, roots, limit, pictur
376
418
  const skipped = [];
377
419
  const again = [];
378
420
  let rereads = 0;
379
- const reread = (known) => known !== undefined && !known.notRead && rereads < REREAD_BATCH && source.reread?.(known) === true && ++rereads > 0;
421
+ const extractor = options.scans?.extractor;
422
+ // OCR text from another engine or model is read again; turning OCR off keeps it.
423
+ const ocrStale = (known) => known.ocr !== undefined && extractor !== undefined && known.ocr !== extractor;
424
+ const reread = (known) => known !== undefined &&
425
+ !known.notRead &&
426
+ rereads < REREAD_BATCH &&
427
+ (ocrStale(known) || source.reread?.(known) === true) &&
428
+ ++rereads > 0;
380
429
  for (const root of roots)
381
430
  if (folders[root]?.trashed)
382
431
  skipped.push({ id: root, reason: "selected folder is unavailable" });
@@ -2,6 +2,7 @@ import type { CliError } from "@wirecat/cli-base";
2
2
  import type { Deadline } from "../../background/budget.js";
3
3
  import type { FeedlessDocumentSource, SourceFile, SourceIndex, SourceSkip, SourceStatePort } from "../../documents/model.js";
4
4
  import type { SourceQuery } from "../../documents/scope.js";
5
+ import type { ScanReader } from "./scans.js";
5
6
  export interface SyncOptions<M extends SourceFile> {
6
7
  source: FeedlessDocumentSource<M> | undefined;
7
8
  index: SourceIndex<M>;
@@ -37,6 +38,8 @@ export interface SyncOptions<M extends SourceFile> {
37
38
  isDocument?(file: M): boolean;
38
39
  skipReason(file: M): string | undefined;
39
40
  retryable(skip: SourceSkip<M>, limit: number): boolean;
41
+ /** Reads scans and pictures by OCR: a PDF whose `content()` answers `document.needs-ocr`, and a picture. */
42
+ scans?: ScanReader;
40
43
  errorOf(error: unknown): CliError;
41
44
  assertHeld(): void;
42
45
  storeVersion: string;
@@ -0,0 +1,42 @@
1
+ import { type LoadEngine } from "../../attachments/extract.js";
2
+ import { type AiCallDeps } from "../../models/ai.js";
3
+ /** Who reads the text of a scan or a picture: this computer, one of the two model providers the owner allows, or no one. */
4
+ export declare const SCAN_READERS: readonly ["local", "anthropic", "openai", "off"];
5
+ export type ScanReaderChoice = (typeof SCAN_READERS)[number];
6
+ /** Pages one file may have to be read by OCR; a longer scan is kept by name only. */
7
+ export declare const SCAN_PAGES_PER_FILE = 20;
8
+ /** Pages one sync reads by OCR; the rest wait for the next sync. */
9
+ export declare const SCAN_PAGES_PER_SYNC = 100;
10
+ /** A picture OCR reads: what `ocrImage` takes. Other images (TIFF, HEIC) stay by name only. */
11
+ export declare const isPicture: (file: {
12
+ mime: string;
13
+ }) => boolean;
14
+ /**
15
+ * The CLI's skip reason with a picture it keeps for its type let through when a reader reads pictures: CLIs name
16
+ * every image `unsupported type: …`, as no text reader takes one.
17
+ */
18
+ export declare const scanSkipReason: (reader: ScanReader | undefined, file: {
19
+ mime: string;
20
+ size?: number | undefined;
21
+ }, reason: string | undefined) => string | undefined;
22
+ /** Reads the text of a scan or a picture, or fails as `validation_error` with the reason the file is kept by name. */
23
+ export interface ScanReader {
24
+ /** The reading's name, saved with the text, so a change of engine or model reads the scans again. Unset: none. */
25
+ extractor?: string;
26
+ /** True once this sync's page limit is reached: every read then answers without a download. */
27
+ full?(): boolean;
28
+ /** `bytes` downloads the file; it is called only when the reader will read it. */
29
+ read(bytes: () => Promise<Uint8Array>, file: {
30
+ name: string;
31
+ mime: string;
32
+ }): Promise<string>;
33
+ }
34
+ /** A skip this reader would now read: a scan an earlier sync could not, or one this sync's page limit held back. */
35
+ export declare const scanRetry: (reader: ScanReader | undefined, reason: string) => boolean;
36
+ /**
37
+ * The scan reader a documents sync uses, from the profile's `read_scans`: undefined for `off`. A local reader that
38
+ * finds no program, or a model the settings do not allow, still answers, with the reason as each file's skip.
39
+ */
40
+ export declare const scanReader: (choice: ScanReaderChoice, deps: AiCallDeps & {
41
+ command: string;
42
+ }, load?: LoadEngine, pagesPerSync?: number) => Promise<ScanReader | undefined>;
@@ -0,0 +1,136 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ import { engineHint, importEngine } from "../../attachments/extract.js";
3
+ import { MAX_PAGES, ocrImage, ocrPdf } from "../../attachments/ocr.js";
4
+ import { tesseractPipeline } from "../../attachments/tesseract.js";
5
+ import { aiImageReader, aiOrigin, aiSettingPath, readAiSetting } from "../../models/ai.js";
6
+ import { NO_TEXT_LAYER } from "./file-text.js";
7
+ /** Who reads the text of a scan or a picture: this computer, one of the two model providers the owner allows, or no one. */
8
+ export const SCAN_READERS = ["local", "anthropic", "openai", "off"];
9
+ /** Pages one file may have to be read by OCR; a longer scan is kept by name only. */
10
+ export const SCAN_PAGES_PER_FILE = MAX_PAGES;
11
+ /** Pages one sync reads by OCR; the rest wait for the next sync. */
12
+ export const SCAN_PAGES_PER_SYNC = 100;
13
+ const OFFICIAL = {
14
+ anthropic: "https://api.anthropic.com",
15
+ openai: "https://api.openai.com",
16
+ };
17
+ const PICTURES = new Set(["image/jpeg", "image/png", "image/webp"]);
18
+ const UNAVAILABLE = "scans are not read: ";
19
+ const LATER = "OCR page limit of this sync reached";
20
+ const BUSY = "OCR is unavailable for now";
21
+ /** Errors of a model that pass: the file is read on a later sync, not kept by name for good. */
22
+ const PASSING = new Set(["rate_limited", "timeout", "network_error", "provider_unavailable"]);
23
+ /** A picture OCR reads: what `ocrImage` takes. Other images (TIFF, HEIC) stay by name only. */
24
+ export const isPicture = (file) => PICTURES.has(file.mime);
25
+ const PICTURE_BYTES = 25 * 1024 * 1024;
26
+ /**
27
+ * The CLI's skip reason with a picture it keeps for its type let through when a reader reads pictures: CLIs name
28
+ * every image `unsupported type: …`, as no text reader takes one.
29
+ */
30
+ export const scanSkipReason = (reader, file, reason) => reason?.startsWith("unsupported type: ") &&
31
+ reader?.extractor !== undefined &&
32
+ isPicture(file) &&
33
+ (file.size ?? 0) <= PICTURE_BYTES
34
+ ? undefined
35
+ : reason;
36
+ /** A skip this reader would now read: a scan an earlier sync could not, or one this sync's page limit held back. */
37
+ export const scanRetry = (reader, reason) => reader?.extractor !== undefined &&
38
+ (reason.startsWith(NO_TEXT_LAYER) ||
39
+ reason.startsWith(UNAVAILABLE) ||
40
+ reason.startsWith(LATER) ||
41
+ reason.startsWith(BUSY));
42
+ const refusing = (why) => ({
43
+ read: async () => {
44
+ throw new CliError("validation_error", `${UNAVAILABLE}${why}`, { reason: "document.scan-unread" });
45
+ },
46
+ });
47
+ const modelPipeline = (choice, deps) => {
48
+ const setting = readAiSetting(aiSettingPath(deps.env));
49
+ // Only these two providers at their own address: an OpenAI-shaped address elsewhere is another provider.
50
+ if (!setting || setting.provider !== choice || aiOrigin(setting) !== OFFICIAL[choice])
51
+ return `read_scans is ${choice}, but the AI model is not ${choice} at ${OFFICIAL[choice]}; choose it with \`ai set\``;
52
+ const reader = aiImageReader(deps);
53
+ if ("refused" in reader)
54
+ return reader.refused === "ai.key-missing"
55
+ ? `the ${choice} key is missing; add it with \`ai set\``
56
+ : `pictures may not go to ${setting.model} yet; allow them with \`ai set --images\``;
57
+ return reader.pipeline;
58
+ };
59
+ const reasonOf = (status, error) => status === "too-large"
60
+ ? `scan is over ${SCAN_PAGES_PER_FILE} pages, or a page is too large to read`
61
+ : status === "needs-agent"
62
+ ? "picture is too large to read"
63
+ : error === "empty_answer"
64
+ ? "OCR found no text in the file"
65
+ : "OCR could not read the file";
66
+ const later = (why) => new CliError("validation_error", why, { reason: "document.scan-later" });
67
+ /**
68
+ * The scan reader a documents sync uses, from the profile's `read_scans`: undefined for `off`. A local reader that
69
+ * finds no program, or a model the settings do not allow, still answers, with the reason as each file's skip.
70
+ */
71
+ export const scanReader = async (choice, deps, load = importEngine, pagesPerSync = SCAN_PAGES_PER_SYNC) => {
72
+ if (choice === "off")
73
+ return undefined;
74
+ let pipeline;
75
+ if (choice === "local") {
76
+ const local = await tesseractPipeline(deps.env, deps.signal);
77
+ if ("missing" in local)
78
+ return refusing(local.missing);
79
+ pipeline = local.pipeline;
80
+ }
81
+ else {
82
+ const model = modelPipeline(choice, deps);
83
+ if (typeof model === "string")
84
+ return refusing(model);
85
+ pipeline = model;
86
+ }
87
+ // Probed once: without them every scan PDF would be downloaded on every sync only to answer that they are missing.
88
+ let pdfMissing;
89
+ for (const engine of ["unpdf", "@napi-rs/canvas"])
90
+ if (pdfMissing === undefined)
91
+ pdfMissing = await load(engine).then(() => undefined, () => `${UNAVAILABLE}${engineHint(engine, deps.command)}`);
92
+ let pages = 0;
93
+ let held = false;
94
+ const counted = {
95
+ extractor: pipeline.extractor,
96
+ transcribe: async (image) => {
97
+ if (pages >= pagesPerSync) {
98
+ held = true;
99
+ throw new Error("page limit");
100
+ }
101
+ pages += 1;
102
+ return pipeline.transcribe(image);
103
+ },
104
+ };
105
+ return {
106
+ extractor: pipeline.extractor,
107
+ full: () => pages >= pagesPerSync,
108
+ read: async (bytes, file) => {
109
+ if (pages >= pagesPerSync)
110
+ throw later(`${LATER}; the next sync goes on`);
111
+ const picture = isPicture(file);
112
+ if (!picture && pdfMissing)
113
+ throw new CliError("validation_error", pdfMissing, { reason: "document.scan-unread" });
114
+ const data = await bytes();
115
+ if (!picture && Buffer.from(data.subarray(0, 5)).toString() !== "%PDF-")
116
+ throw new CliError("validation_error", "OCR reads PDF files and JPEG, PNG and WebP pictures only", {
117
+ reason: "document.scan-unread",
118
+ });
119
+ held = false;
120
+ const read = picture ? await ocrImage(data, counted, deps.signal) : await ocrPdf(data, counted, load, deps.signal);
121
+ if (read.status === "extracted")
122
+ return read.text;
123
+ if (held)
124
+ throw later(`${LATER}; the next sync goes on`);
125
+ if (read.status === "engine-missing")
126
+ throw new CliError("validation_error", `${UNAVAILABLE}${engineHint(read.engine, deps.command)}`, {
127
+ reason: "document.scan-unread",
128
+ });
129
+ if (read.status === "unreadable" && (read.error === "rate_limited" || PASSING.has(read.issue?.code ?? "")))
130
+ throw later(`${BUSY}; the next sync tries again`);
131
+ throw new CliError("validation_error", reasonOf(read.status, read.status === "unreadable" ? read.error : undefined), {
132
+ reason: "document.scan-unread",
133
+ });
134
+ },
135
+ };
136
+ };
@@ -4,6 +4,7 @@ import { deadlineMargin } from "../../background/budget.js";
4
4
  import { catalogFiles } from "../../documents/catalog.js";
5
5
  import { inScope } from "../../documents/scope.js";
6
6
  import { changedSince, planDocuments, scopeHash } from "./plan.js";
7
+ import { isPicture as readsAsPicture } from "./scans.js";
7
8
  const MAX_PICTURE_BYTES = 25 * 1024 * 1024;
8
9
  const SAVE_EVERY_MS = 2000;
9
10
  const SAVE_EVERY_ITEMS = 25;
@@ -13,7 +14,7 @@ export const KEEP_VERSIONS_FOR_DAYS = 365;
13
14
  const isPicture = (file) => file.mime.startsWith("image/") && file.canDownload;
14
15
  const hashText = (text) => createHash("sha256").update(text).digest("hex");
15
16
  export const syncDocuments = async (options) => {
16
- const { source, index, state: statePort, principal, roots, textLimit: limit, max, signal, rescan = false, pictures = false, assertHeld, errorOf, skipReason, storeVersion: VERSION, query, } = options;
17
+ const { source, index, state: statePort, principal, roots, textLimit: limit, max, signal, rescan = false, pictures = false, assertHeld, errorOf, skipReason, storeVersion: VERSION, query, scans, } = options;
17
18
  if (![max, limit, options.maxEntries].every((value) => Number.isSafeInteger(value) && value > 0))
18
19
  throw new CliError("validation_error", "sync limits must be positive whole numbers");
19
20
  const profile = { principal, roots, picture_search: pictures };
@@ -184,12 +185,40 @@ export const syncDocuments = async (options) => {
184
185
  else {
185
186
  if (!source)
186
187
  throw new CliError("configuration_error", "a pending save requires source sign-in");
187
- const stop = ask();
188
+ const picture = scans?.extractor !== undefined && job.file !== undefined && readsAsPicture(job.file);
189
+ // A picture past this sync's OCR page limit is refused without a download, so it takes none of the budget.
190
+ const stop = picture && scans?.full?.() ? null : ask();
188
191
  if (stop) {
189
192
  result.stopped = stop;
190
193
  break;
191
194
  }
192
- const content = await source.content(job.id, limit, job.file);
195
+ // A scan's text comes from OCR of its bytes, one more download, taken from the budget as a read is.
196
+ const scanned = async (file) => {
197
+ const reader = scans;
198
+ const text = (await reader.read(() => source.bytes(file.id, file), file)).slice(0, limit);
199
+ return { metadata: file, markdown: text, text, tabs: [] };
200
+ };
201
+ let content;
202
+ let ocr;
203
+ if (picture && job.file) {
204
+ content = await scanned(job.file);
205
+ ocr = scans.extractor;
206
+ }
207
+ else
208
+ try {
209
+ content = await source.content(job.id, limit, job.file);
210
+ }
211
+ catch (error) {
212
+ if (!scans || !job.file || errorOf(error).details.reason !== "document.needs-ocr")
213
+ throw error;
214
+ const again = scans.full?.() ? null : ask();
215
+ if (again) {
216
+ result.stopped = again;
217
+ break;
218
+ }
219
+ content = await scanned(job.file);
220
+ ocr = scans.extractor;
221
+ }
193
222
  const listed = query?.mode === "include" && (pending.matched?.includes(job.id) ?? query.matches(content.metadata));
194
223
  if (!listed && !inScope(content.metadata, profile.roots, pending.folders, new Set(), query)) {
195
224
  await index.remove(profile.principal, job.id, "unsynced");
@@ -209,11 +238,24 @@ export const syncDocuments = async (options) => {
209
238
  });
210
239
  });
211
240
  statePort.saveSnapshot(content);
212
- state.documents[job.id] = { metadata: content.metadata, hash, reference, tabs: content.tabs.length };
241
+ state.documents[job.id] = {
242
+ metadata: content.metadata,
243
+ hash,
244
+ reference,
245
+ tabs: content.tabs.length,
246
+ ...(ocr ? { ocr } : {}),
247
+ };
213
248
  if (previous?.hash === hash)
214
249
  result.unchanged++;
215
250
  else
216
251
  result.saved++;
252
+ if (ocr && readsAsPicture(content.metadata)) {
253
+ const stop = await savePictureOf(content.metadata);
254
+ if (stop) {
255
+ result.stopped = stop;
256
+ break;
257
+ }
258
+ }
217
259
  }
218
260
  }
219
261
  pending.jobs = pending.jobs.filter((item) => item !== job);
@@ -225,6 +267,17 @@ export const syncDocuments = async (options) => {
225
267
  throw safe;
226
268
  // A file the sign-in may not read is skipped as a gone one is: retried on every sync, it would hold the pass,
227
269
  // and the change cursor with it, for good.
270
+ const kept = job.kind === "save" ? state.documents[job.id] : undefined;
271
+ // Text OCR read once stays when reading it again fails, OCR was turned off or its program removed: only an
272
+ // edit of the file makes that text old.
273
+ if (kept?.ocr && job.file && safe.code === "validation_error" && !changedSince(kept.metadata, job.file)) {
274
+ // The new reading was tried: trying it on every sync would spend the page limit on a file it cannot read.
275
+ if (scans?.extractor && safe.details.reason !== "document.scan-later")
276
+ kept.ocr = scans.extractor;
277
+ pending.jobs = pending.jobs.filter((item) => item !== job);
278
+ progress();
279
+ continue;
280
+ }
228
281
  if (job.kind === "save" &&
229
282
  (safe.code === "not_found" || safe.code === "permission_error" || safe.code === "validation_error")) {
230
283
  const skipped = {
@@ -24,6 +24,12 @@ export interface GuardedFileWriteResult {
24
24
  sha256: string;
25
25
  };
26
26
  }
27
+ /** The reason of a conflict a target raised for itself, which callers pass on as it is; undefined for the usual one. */
28
+ export declare const ownConflict: (error: {
29
+ details?: {
30
+ reason?: unknown;
31
+ };
32
+ }) => string | undefined;
27
33
  export declare const remoteChanged: (path: string, why: string, reread: string) => CliError;
28
34
  /**
29
35
  * Writes a file only over the content the caller read. Few providers offer a conditional upload, so the current
@@ -1,4 +1,9 @@
1
1
  import { CliError, isCliError } from "@wirecat/cli-base";
2
+ /** The reason of a conflict a target raised for itself, which callers pass on as it is; undefined for the usual one. */
3
+ export const ownConflict = (error) => {
4
+ const reason = error.details?.reason;
5
+ return typeof reason === "string" && reason !== "mirror.remote-changed" ? reason : undefined;
6
+ };
2
7
  export const remoteChanged = (path, why, reread) => new CliError("conflict", `${path} ${why}; nothing was written. Read it again: ${reread}`, {
3
8
  reason: "mirror.remote-changed",
4
9
  });
@@ -23,7 +28,8 @@ export const guardedFileWrite = async (write) => {
23
28
  file = await target.upload(path, from, kept === undefined ? { absent: true } : { sha256: kept }, signal);
24
29
  }
25
30
  catch (error) {
26
- if (isCliError(error) && error.code === "conflict")
31
+ // A target's conflict with its own reason says what it did, which "nothing was written" would hide.
32
+ if (isCliError(error) && error.code === "conflict" && ownConflict(error) === undefined)
27
33
  throw remoteChanged(path, kept === undefined ? "appeared since it was read" : "changed since it was read", reread);
28
34
  throw error;
29
35
  }