@wirecat/cli-core 0.739.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.
- package/CHANGELOG.md +19 -0
- package/dist/attachments/ocr.d.ts +2 -0
- package/dist/attachments/ocr.js +2 -1
- package/dist/attachments/tesseract.d.ts +11 -0
- package/dist/attachments/tesseract.js +82 -0
- package/dist/cli/documents/index.d.ts +1 -1
- package/dist/cli/documents/index.js +1 -1
- package/dist/cli/documents/library.d.ts +12 -0
- package/dist/cli/documents/library.js +31 -3
- package/dist/cli/documents/manifest/manifest.d.ts +10 -0
- package/dist/cli/documents/manifest/manifest.js +9 -1
- package/dist/cli/documents/manifest/source.d.ts +4 -1
- package/dist/cli/documents/manifest/source.js +67 -1
- package/dist/documents/index.d.ts +1 -0
- package/dist/documents/index.js +1 -0
- package/dist/documents/model.d.ts +2 -0
- package/dist/errors/reasons.js +4 -0
- package/dist/services/documents/file-text.d.ts +2 -0
- package/dist/services/documents/file-text.js +13 -9
- package/dist/services/documents/plan.js +8 -1
- package/dist/services/documents/ports.d.ts +3 -0
- package/dist/services/documents/scans.d.ts +42 -0
- package/dist/services/documents/scans.js +136 -0
- package/dist/services/documents/sync.js +57 -4
- package/dist/services/metadata.d.ts +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -5,6 +5,25 @@ Notable changes to `@wirecat/cli-core` (`@wirecat/cli-messaging` up to 0.261.0,
|
|
|
5
5
|
minor version may break callers, and says how under "Changed — may break callers". `pnpm docs:check` checks the
|
|
6
6
|
shape of this file.
|
|
7
7
|
|
|
8
|
+
## 0.740.0 — 24.11.2026
|
|
9
|
+
|
|
10
|
+
### Added
|
|
11
|
+
|
|
12
|
+
- **A documents source from a manifest reads a deletions feed in every round of changes.** `deletions` names a call
|
|
13
|
+
that lists the documents deleted since a time (Linear's audit log, where its trash leaves `updatedAt` as it was),
|
|
14
|
+
and each id it names leaves the local copy as `deleted` in the next `sync`, not only after `sync --rescan`. A
|
|
15
|
+
provider that refuses the feed (`permission_error`) does not fail the sync: its answer warns
|
|
16
|
+
`source.deletions-unchecked`, which says `sync --rescan` finds them. A source with `deletions` passes the run's
|
|
17
|
+
`warn` to `documentSourceFromManifest`, or it is refused when built
|
|
18
|
+
([a deletions feed](docs/dev/DOCUMENTS.md#a-deletions-feed)).
|
|
19
|
+
- **A documents sync reads the text of scans and pictures.** A PDF with no text layer and a JPEG, PNG or WebP picture
|
|
20
|
+
are read by OCR, chosen by the profile's `read_scans`: `local` by default (the `tesseract` program on this
|
|
21
|
+
computer, Russian and English, nothing downloaded), `anthropic` or `openai` (the `ai set` model at that provider's
|
|
22
|
+
own address, with pictures allowed), or `off`. At most 20 pages a file and 100 a sync. A scan an earlier sync kept
|
|
23
|
+
by name is read on the next sync, and a sync with no reader says how to install one. A CLI adds
|
|
24
|
+
`DOCUMENT_SCAN_SETTINGS` to `settingsFor` for its config file to take `read_scans`
|
|
25
|
+
([scans and pictures](docs/dev/DOCUMENTS.md#scans-and-pictures)).
|
|
26
|
+
|
|
8
27
|
## 0.739.0 — 24.11.2026
|
|
9
28
|
|
|
10
29
|
### Added
|
|
@@ -4,5 +4,7 @@ export interface OcrPipeline {
|
|
|
4
4
|
extractor: string;
|
|
5
5
|
transcribe: (image: ModelImage) => Promise<string>;
|
|
6
6
|
}
|
|
7
|
+
/** Pages one PDF may have to be read by OCR; a longer one answers `too-large`. */
|
|
8
|
+
export declare const MAX_PAGES = 20;
|
|
7
9
|
export declare const ocrImage: (bytes: Uint8Array, pipeline: OcrPipeline, signal?: AbortSignal) => Promise<Extraction>;
|
|
8
10
|
export declare const ocrPdf: (bytes: Uint8Array, pipeline: OcrPipeline, load: LoadEngine, signal?: AbortSignal) => Promise<Extraction>;
|
package/dist/attachments/ocr.js
CHANGED
|
@@ -4,7 +4,8 @@ import { withRecovery } from "../domain/recovery.js";
|
|
|
4
4
|
import { isCliFailure } from "../errors/failures.js";
|
|
5
5
|
import { MAX_MODEL_IMAGE_BYTES } from "../models/types.js";
|
|
6
6
|
import { MAX_TEXT_CHARS } from "./extract.js";
|
|
7
|
-
|
|
7
|
+
/** Pages one PDF may have to be read by OCR; a longer one answers `too-large`. */
|
|
8
|
+
export const MAX_PAGES = 20;
|
|
8
9
|
const MAX_PIXELS = 20_000_000;
|
|
9
10
|
const cancelled = (signal) => {
|
|
10
11
|
if (signal?.aborted)
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { OcrPipeline } from "./ocr.js";
|
|
2
|
+
export declare const TESSERACT_HINT: string;
|
|
3
|
+
/**
|
|
4
|
+
* The OCR of the `tesseract` program on this computer, or why there is none. Nothing leaves the computer and
|
|
5
|
+
* nothing is downloaded: the program and its language data are the owner's own install.
|
|
6
|
+
*/
|
|
7
|
+
export declare const tesseractPipeline: (env: NodeJS.ProcessEnv, signal?: AbortSignal) => Promise<{
|
|
8
|
+
pipeline: OcrPipeline;
|
|
9
|
+
} | {
|
|
10
|
+
missing: string;
|
|
11
|
+
}>;
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { CliError } from "@wirecat/cli-base";
|
|
3
|
+
import { MAX_TEXT_CHARS } from "./limits.js";
|
|
4
|
+
/** Russian first: an owner's scans are more often Russian, and the order only breaks ties. */
|
|
5
|
+
const LANGUAGES = ["rus", "eng"];
|
|
6
|
+
const PAGE_MS = 120_000;
|
|
7
|
+
const PROBE_MS = 10_000;
|
|
8
|
+
const PROBE_BYTES = 64 * 1024;
|
|
9
|
+
export const TESSERACT_HINT = "reading scans on this computer needs the tesseract program with its Russian and English data " +
|
|
10
|
+
"(apt install tesseract-ocr tesseract-ocr-rus, brew install tesseract tesseract-lang); scans are read on the next sync";
|
|
11
|
+
const run = (args, env, timeout, { input, signal, errors = false } = {}) => new Promise((resolve, reject) => {
|
|
12
|
+
// The PATH of the run's own environment finds the program, so a test or a moved run picks its own.
|
|
13
|
+
const child = spawn("tesseract", args, {
|
|
14
|
+
env,
|
|
15
|
+
shell: false,
|
|
16
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
17
|
+
timeout,
|
|
18
|
+
windowsHide: true,
|
|
19
|
+
...(signal ? { signal } : {}),
|
|
20
|
+
});
|
|
21
|
+
const chunks = [];
|
|
22
|
+
let size = 0;
|
|
23
|
+
child.stdout.on("data", (chunk) => {
|
|
24
|
+
size += chunk.length;
|
|
25
|
+
// Four bytes a character at most: more than that is never text the store keeps.
|
|
26
|
+
if (size > MAX_TEXT_CHARS * 4)
|
|
27
|
+
child.kill();
|
|
28
|
+
else
|
|
29
|
+
chunks.push(chunk);
|
|
30
|
+
});
|
|
31
|
+
// Tesseract 3 printed its version and languages to stderr, so a probe reads both; a page's warnings are dropped.
|
|
32
|
+
child.stderr.on("data", (chunk) => {
|
|
33
|
+
if (errors && size < PROBE_BYTES)
|
|
34
|
+
chunks.push(chunk);
|
|
35
|
+
if (errors)
|
|
36
|
+
size += chunk.length;
|
|
37
|
+
});
|
|
38
|
+
child.on("error", reject);
|
|
39
|
+
child.on("close", (code) => resolve({ code, stdout: Buffer.concat(chunks).toString("utf8") }));
|
|
40
|
+
child.stdin.on("error", () => { });
|
|
41
|
+
child.stdin.end(input ?? new Uint8Array());
|
|
42
|
+
});
|
|
43
|
+
/**
|
|
44
|
+
* The OCR of the `tesseract` program on this computer, or why there is none. Nothing leaves the computer and
|
|
45
|
+
* nothing is downloaded: the program and its language data are the owner's own install.
|
|
46
|
+
*/
|
|
47
|
+
export const tesseractPipeline = async (env, signal) => {
|
|
48
|
+
let version;
|
|
49
|
+
let listed;
|
|
50
|
+
try {
|
|
51
|
+
version = await run(["--version"], env, PROBE_MS, { errors: true });
|
|
52
|
+
listed = await run(["--list-langs"], env, PROBE_MS, { errors: true });
|
|
53
|
+
}
|
|
54
|
+
catch {
|
|
55
|
+
return { missing: TESSERACT_HINT };
|
|
56
|
+
}
|
|
57
|
+
const number = /tesseract\s+v?(\d+(?:\.\d+)*)/iu.exec(version.stdout)?.[1];
|
|
58
|
+
const installed = new Set(listed.stdout.split(/\r?\n/u).map((line) => line.trim()));
|
|
59
|
+
const languages = LANGUAGES.filter((language) => installed.has(language));
|
|
60
|
+
if (version.code !== 0 || !number || !languages.length)
|
|
61
|
+
return { missing: TESSERACT_HINT };
|
|
62
|
+
const chosen = languages.join("+");
|
|
63
|
+
return {
|
|
64
|
+
pipeline: {
|
|
65
|
+
// The version and the languages name the reading, so installing Russian data later reads the scans again.
|
|
66
|
+
extractor: `ocr:v1:tesseract@${number}:${chosen}`,
|
|
67
|
+
transcribe: async (image) => {
|
|
68
|
+
const read = await run(["stdin", "stdout", "-l", chosen], env, PAGE_MS, {
|
|
69
|
+
input: Buffer.from(image.data, "base64"),
|
|
70
|
+
signal,
|
|
71
|
+
}).catch((error) => {
|
|
72
|
+
if (signal?.aborted)
|
|
73
|
+
throw new CliError("cancelled", "OCR cancelled");
|
|
74
|
+
throw error;
|
|
75
|
+
});
|
|
76
|
+
if (read.code !== 0)
|
|
77
|
+
throw new Error("tesseract failed");
|
|
78
|
+
return read.stdout.trim();
|
|
79
|
+
},
|
|
80
|
+
},
|
|
81
|
+
};
|
|
82
|
+
};
|
|
@@ -44,6 +44,6 @@ export interface DocumentCommands<S> {
|
|
|
44
44
|
* `search`, `catalog`, the knowledge groups and, when given, `mirrors`, in that order. Answers the `documents` group, for the CLI's live subcommands.
|
|
45
45
|
*/
|
|
46
46
|
export declare const addDocumentCommands: <S>(program: Command, options: DocumentCommands<S>) => Command;
|
|
47
|
-
export { claimDocumentAccount, type DocumentLibraryOptions, type DocumentLibraryTools, type DocumentSourceRun, type DocumentSyncOutcome, type DocumentSyncStep, type DocumentWarning, documentLibrary, documentLibraryCommands, documentProfile, } from "./library.js";
|
|
47
|
+
export { claimDocumentAccount, DOCUMENT_SCAN_SETTINGS, type DocumentLibraryOptions, type DocumentLibraryTools, type DocumentSourceRun, type DocumentSyncOutcome, type DocumentSyncStep, type DocumentWarning, documentLibrary, documentLibraryCommands, documentProfile, } from "./library.js";
|
|
48
48
|
export { type DocumentCall, type DocumentFileMap, type DocumentManifest, parseDocumentManifest, } from "./manifest/manifest.js";
|
|
49
49
|
export { type DocumentManifestSourceOptions, type DocumentManifestTools, type DocumentSlots, documentSourceFromManifest, type ManifestDocumentSource, } from "./manifest/source.js";
|
|
@@ -40,6 +40,6 @@ export const addDocumentCommands = (program, options) => {
|
|
|
40
40
|
addDocumentMirrorCommands(program, { ...shared, ...options.mirrors });
|
|
41
41
|
return documents;
|
|
42
42
|
};
|
|
43
|
-
export { claimDocumentAccount, documentLibrary, documentLibraryCommands, documentProfile, } from "./library.js";
|
|
43
|
+
export { claimDocumentAccount, DOCUMENT_SCAN_SETTINGS, documentLibrary, documentLibraryCommands, documentProfile, } from "./library.js";
|
|
44
44
|
export { parseDocumentManifest, } from "./manifest/manifest.js";
|
|
45
45
|
export { documentSourceFromManifest, } from "./manifest/source.js";
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { type ErrorCode } from "@wirecat/cli-base";
|
|
2
2
|
import type { NextStep } from "@wirecat/cli-base/standards";
|
|
3
3
|
import { Command } from "commander";
|
|
4
|
+
import * as v from "valibot";
|
|
4
5
|
import type { Deadline, RunBudget } from "../../background/budget.js";
|
|
5
6
|
import { type documentIngestion, type FeedlessDocumentSource, type SourceContent, type SourceFile, type SourceStatePort } from "../../documents.js";
|
|
6
7
|
import type { ProviderEntry } from "../../domain/providers.js";
|
|
@@ -13,6 +14,17 @@ import { ProfileTokenStore } from "../profile-token.js";
|
|
|
13
14
|
import type { DocumentKnowledgePort } from "./knowledge.js";
|
|
14
15
|
import { type DocumentSyncAnswer } from "./sync.js";
|
|
15
16
|
import { type DocumentWords } from "./words.js";
|
|
17
|
+
/** `read_scans`: a documents CLI adds it to `settingsFor`; left out, scans are read on this computer. */
|
|
18
|
+
export declare const DOCUMENT_SCAN_SETTINGS: {
|
|
19
|
+
profile: {
|
|
20
|
+
read_scans: v.OptionalSchema<v.PicklistSchema<readonly ["local", "anthropic", "openai", "off"], `has to be one of ${string}`>, undefined>;
|
|
21
|
+
};
|
|
22
|
+
settings: {
|
|
23
|
+
key: string;
|
|
24
|
+
default: string;
|
|
25
|
+
description: string;
|
|
26
|
+
}[];
|
|
27
|
+
};
|
|
16
28
|
type Resolve = Parameters<typeof baseContext>[1];
|
|
17
29
|
type Ingestion<M extends SourceFile> = ReturnType<typeof documentIngestion<M>>;
|
|
18
30
|
/** Something a source met on its way and went on past: one per file, gathered into the answer's issues. */
|
|
@@ -4,9 +4,10 @@ import { join } from "node:path";
|
|
|
4
4
|
import { CliError, isCliError, resolvePaths, writeSecurely } from "@wirecat/cli-base";
|
|
5
5
|
import { annotate, metaOf } from "@wirecat/cli-base/commands";
|
|
6
6
|
import { Command } from "commander";
|
|
7
|
+
import * as v from "valibot";
|
|
7
8
|
import { resolveAISettings } from "../../analysis/settings.js";
|
|
8
9
|
import { progressOf } from "../../background/checkpoints.js";
|
|
9
|
-
import { catalogFiles, documentKnowledge, syncDocuments, } from "../../documents.js";
|
|
10
|
+
import { catalogFiles, documentKnowledge, SCAN_READERS, scanReader, scanRetry, scanSkipReason, syncDocuments, } from "../../documents.js";
|
|
10
11
|
import { acquireLock } from "../../files/lock.js";
|
|
11
12
|
import { modelGateway } from "../../models/index.js";
|
|
12
13
|
import { modelTarget } from "../../models/settings.js";
|
|
@@ -19,6 +20,7 @@ import { writesOwnerFiles } from "../effects.js";
|
|
|
19
20
|
import { renderAnswer } from "../envelope.js";
|
|
20
21
|
import { accountFileFor, profilesHere, rememberAccount } from "../messenger/accounts.js";
|
|
21
22
|
import { ProfileTokenStore } from "../profile-token.js";
|
|
23
|
+
import { fromFile } from "../settings.js";
|
|
22
24
|
import { DOCUMENT_UNTRUSTED, marksUntrusted } from "../untrusted-marks.js";
|
|
23
25
|
import { addDocumentCatalogCommands } from "./catalog.js";
|
|
24
26
|
import { addLocalDocumentCommands } from "./documents.js";
|
|
@@ -29,6 +31,21 @@ import { factItem, memoryItem } from "./queries.js";
|
|
|
29
31
|
import { addDocumentSearchCommand } from "./search.js";
|
|
30
32
|
import { addDocumentSyncCommands, DOCUMENT_SYNC_LIMIT, documentSyncPart, } from "./sync.js";
|
|
31
33
|
import { wordsOf } from "./words.js";
|
|
34
|
+
/** `read_scans`: a documents CLI adds it to `settingsFor`; left out, scans are read on this computer. */
|
|
35
|
+
export const DOCUMENT_SCAN_SETTINGS = {
|
|
36
|
+
profile: {
|
|
37
|
+
read_scans: v.optional(v.picklist(SCAN_READERS, `has to be one of ${SCAN_READERS.join(", ")}`)),
|
|
38
|
+
},
|
|
39
|
+
settings: [
|
|
40
|
+
{
|
|
41
|
+
key: "read_scans",
|
|
42
|
+
default: "local",
|
|
43
|
+
description: "who reads the text of scans and pictures: local (the tesseract program), anthropic or openai " +
|
|
44
|
+
"(the AI model `ai set` chose, with pictures allowed), or off",
|
|
45
|
+
},
|
|
46
|
+
],
|
|
47
|
+
};
|
|
48
|
+
const readScans = (settings) => fromFile(settings, "read_scans", "local").value;
|
|
32
49
|
const readJson = (path) => {
|
|
33
50
|
try {
|
|
34
51
|
return JSON.parse(readFileSync(path, "utf8"));
|
|
@@ -341,6 +358,16 @@ const libraryOf = (options, withSync) => {
|
|
|
341
358
|
throw new CliError("configuration_error", `the documents are signed in as ${options.service} account ${live}, not ${expected}, the account the ` +
|
|
342
359
|
`rest of this sync read; sign in again with one account (\`${app.command} ${name} session start\`)`, { reason: "documents.other-account" });
|
|
343
360
|
claimDocumentAccount(app, env(), name, live, tokens());
|
|
361
|
+
const { keyring, settings } = context();
|
|
362
|
+
const signal = environmentOf(command()).signal;
|
|
363
|
+
const scans = await scanReader(readScans(settings), {
|
|
364
|
+
app,
|
|
365
|
+
env: env(),
|
|
366
|
+
command: app.command,
|
|
367
|
+
...(keyring ? { keyring } : {}),
|
|
368
|
+
...(signal ? { signal } : {}),
|
|
369
|
+
});
|
|
370
|
+
const skipReason = options.skipReason ?? (() => undefined);
|
|
344
371
|
return files().locked((assertHeld) => withStore(true, async (store) => {
|
|
345
372
|
const result = await syncDocuments({
|
|
346
373
|
source,
|
|
@@ -359,10 +386,11 @@ const libraryOf = (options, withSync) => {
|
|
|
359
386
|
maxEntries: options.maxEntries,
|
|
360
387
|
isFolder: options.isFolder,
|
|
361
388
|
...(options.isDocument ? { isDocument: options.isDocument } : {}),
|
|
362
|
-
skipReason:
|
|
389
|
+
skipReason: (file) => scanSkipReason(scans, file, skipReason(file)),
|
|
363
390
|
// A file an older version kept by name for its type is read once a newer one reads that type; the
|
|
364
391
|
// planner asks only when `skipReason` no longer gives a reason. The words are the CLIs' own.
|
|
365
|
-
retryable: (skip) => skip.reason.startsWith("unsupported type: "),
|
|
392
|
+
retryable: (skip) => skip.reason.startsWith("unsupported type: ") || scanRetry(scans, skip.reason),
|
|
393
|
+
...(scans ? { scans } : {}),
|
|
366
394
|
errorOf,
|
|
367
395
|
assertHeld,
|
|
368
396
|
storeVersion: app.version,
|
|
@@ -61,6 +61,16 @@ export interface DocumentManifest {
|
|
|
61
61
|
overlapMs?: number;
|
|
62
62
|
map?: DocumentFileMap;
|
|
63
63
|
};
|
|
64
|
+
/**
|
|
65
|
+
* The documents deleted since a time, for a provider whose `changes` misses them (Linear's trash leaves `updatedAt`
|
|
66
|
+
* as it was): the id of each at `id`. Read in every round of changes from the same time: needs `"{since}"`.
|
|
67
|
+
*/
|
|
68
|
+
deletions?: DocumentCall & {
|
|
69
|
+
since: "iso" | "ms" | "seconds";
|
|
70
|
+
time: string;
|
|
71
|
+
id: string;
|
|
72
|
+
overlapMs?: number;
|
|
73
|
+
};
|
|
64
74
|
/** A document's text as Markdown, at `markdown` in the answer: needs `"{id}"`. */
|
|
65
75
|
content?: DocumentCall & {
|
|
66
76
|
markdown: string;
|
|
@@ -39,11 +39,18 @@ const schema = v.strictObject({
|
|
|
39
39
|
overlapMs: v.optional(v.pipe(v.number(), v.integer(), v.minValue(0))),
|
|
40
40
|
map: v.optional(fileMap),
|
|
41
41
|
})),
|
|
42
|
+
deletions: v.optional(v.strictObject({
|
|
43
|
+
...callEntries,
|
|
44
|
+
since: v.picklist(["iso", "ms", "seconds"]),
|
|
45
|
+
time: dotPath,
|
|
46
|
+
id: dotPath,
|
|
47
|
+
overlapMs: v.optional(v.pipe(v.number(), v.integer(), v.minValue(0))),
|
|
48
|
+
})),
|
|
42
49
|
content: v.optional(v.strictObject({ ...callEntries, markdown: dotPath })),
|
|
43
50
|
reread: v.optional(v.strictObject({ missing: dotPath })),
|
|
44
51
|
reads: v.optional(v.record(v.pipe(v.string(), v.regex(/^[a-z][A-Za-z0-9]*$/, "a camelCase name")), v.strictObject(callEntries))),
|
|
45
52
|
});
|
|
46
|
-
const BUILT_IN = ["identity", "get", "children", "changes", "content"];
|
|
53
|
+
const BUILT_IN = ["identity", "get", "children", "changes", "deletions", "content"];
|
|
47
54
|
const invalid = (where, message) => new CliError("configuration_error", `source manifest: ${where}: ${message}`, { reason: "manifest.invalid" });
|
|
48
55
|
const nearest = (wanted, known) => known
|
|
49
56
|
.map((one) => ({ one, edits: editDistance(wanted, one, 2) }))
|
|
@@ -82,6 +89,7 @@ export const parseDocumentManifest = (input, api) => {
|
|
|
82
89
|
check("get", manifest.get, "{id}");
|
|
83
90
|
check("children", manifest.children, "{id}");
|
|
84
91
|
check("changes", manifest.changes, "{since}");
|
|
92
|
+
check("deletions", manifest.deletions, "{since}");
|
|
85
93
|
check("content", manifest.content, "{id}");
|
|
86
94
|
for (const [name, call] of Object.entries(manifest.reads ?? {})) {
|
|
87
95
|
// A hook sends a named call and a manifest call by the same name; one would hide the other.
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { DocumentSource, FeedlessDocumentSource, SourceFile } from "../../../documents.js";
|
|
2
2
|
import type { ServiceApiCall } from "../../service-api-call.js";
|
|
3
3
|
import { type ServiceApiManifest } from "../../service-api-manifest.js";
|
|
4
|
+
import type { DocumentWarning } from "../library.js";
|
|
4
5
|
import { type DocumentManifest } from "./manifest.js";
|
|
5
6
|
/** What a slot in a call is filled with; one left without a value is left out of the request. */
|
|
6
7
|
export interface DocumentSlots {
|
|
@@ -13,7 +14,7 @@ export type ManifestDocumentSource<M extends SourceFile = SourceFile> = Feedless
|
|
|
13
14
|
/** What a hook builds on: the manifest's own calls, and the source the manifest alone describes. */
|
|
14
15
|
export interface DocumentManifestTools<M extends SourceFile = SourceFile> {
|
|
15
16
|
manifest: DocumentManifest;
|
|
16
|
-
/** Sends one named call of `reads`, or `identity`, `get`, `children`, `changes`, `content`. */
|
|
17
|
+
/** Sends one named call of `reads`, or `identity`, `get`, `children`, `changes`, `deletions`, `content`. */
|
|
17
18
|
read(name: string, slots?: DocumentSlots, body?: unknown): Promise<unknown>;
|
|
18
19
|
/** One row of an answer as a file, by `get.map` (or the named call's own map). */
|
|
19
20
|
file(row: unknown, from?: "get" | "children" | "changes"): M;
|
|
@@ -23,6 +24,8 @@ export interface DocumentManifestSourceOptions<M extends SourceFile = SourceFile
|
|
|
23
24
|
api: ServiceApiManifest;
|
|
24
25
|
call: ServiceApiCall;
|
|
25
26
|
now?: () => number;
|
|
27
|
+
/** The run's `warn`: a refused `deletions` feed is said there, and the round goes on without it. */
|
|
28
|
+
warn?: (warning: DocumentWarning) => void;
|
|
26
29
|
/** The methods the manifest cannot describe, or that the provider does otherwise; each wins over the manifest's. */
|
|
27
30
|
hooks?: (tools: DocumentManifestTools<M>) => Partial<ManifestDocumentSource<M>>;
|
|
28
31
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { CliError } from "@wirecat/cli-base";
|
|
1
|
+
import { CliError, isCliError } from "@wirecat/cli-base";
|
|
2
2
|
import { answerAt as at, nextPage, parameterValue, withValue, } from "../../service-api-manifest.js";
|
|
3
3
|
import { parseDocumentManifest } from "./manifest.js";
|
|
4
4
|
const OVERLAP_MS = 10 * 60_000;
|
|
@@ -66,6 +66,7 @@ export const documentSourceFromManifest = (input, options) => {
|
|
|
66
66
|
get: manifest.get,
|
|
67
67
|
children: manifest.children,
|
|
68
68
|
changes: manifest.changes,
|
|
69
|
+
deletions: manifest.deletions,
|
|
69
70
|
content: manifest.content,
|
|
70
71
|
};
|
|
71
72
|
const callOf = (name) => {
|
|
@@ -253,5 +254,70 @@ export const documentSourceFromManifest = (input, options) => {
|
|
|
253
254
|
throw new CliError("configuration_error", "source manifest: a change feed needs both startToken and changes", {
|
|
254
255
|
reason: "manifest.invalid",
|
|
255
256
|
});
|
|
257
|
+
const { deletions } = manifest;
|
|
258
|
+
if (deletions) {
|
|
259
|
+
const changesOf = source.changes;
|
|
260
|
+
if (!changesOf)
|
|
261
|
+
throw new CliError("configuration_error", "source manifest: deletions needs a change feed to read them in", {
|
|
262
|
+
reason: "manifest.invalid",
|
|
263
|
+
});
|
|
264
|
+
const warn = options.warn;
|
|
265
|
+
// A refused feed with no one told would answer a sync that never checked deletions as a whole one.
|
|
266
|
+
if (!warn)
|
|
267
|
+
throw new CliError("configuration_error", "source manifest: deletions needs the run's warn", {
|
|
268
|
+
reason: "manifest.invalid",
|
|
269
|
+
});
|
|
270
|
+
const overlap = deletions.overlapMs ?? changes?.overlapMs ?? OVERLAP_MS;
|
|
271
|
+
const deletedSince = async (sinceMs) => {
|
|
272
|
+
const since = SINCE[deletions.since](sinceMs);
|
|
273
|
+
const items = [];
|
|
274
|
+
let cursor;
|
|
275
|
+
for (let pages = 0; pages < MOST_PAGES; pages++) {
|
|
276
|
+
let listed;
|
|
277
|
+
try {
|
|
278
|
+
listed = await page(deletions, { since }, cursor);
|
|
279
|
+
}
|
|
280
|
+
catch (error) {
|
|
281
|
+
// The provider may keep this feed to admins or a higher plan; the changes still hold, and a full walk finds
|
|
282
|
+
// the trash.
|
|
283
|
+
if (!isCliError(error) || error.code !== "permission_error")
|
|
284
|
+
throw error;
|
|
285
|
+
warn({
|
|
286
|
+
code: "permission_error",
|
|
287
|
+
reason: "source.deletions-unchecked",
|
|
288
|
+
message: `${manifest.provider} refused its list of deleted documents to this sign-in, so documents deleted ` +
|
|
289
|
+
"since the last sync were not checked; sync --rescan finds them",
|
|
290
|
+
});
|
|
291
|
+
return items;
|
|
292
|
+
}
|
|
293
|
+
for (const row of listed.rows) {
|
|
294
|
+
const deleted = Date.parse(time(at(row, deletions.time)) ?? "");
|
|
295
|
+
if (Number.isFinite(deleted) && deleted < sinceMs)
|
|
296
|
+
continue;
|
|
297
|
+
const id = text(at(row, deletions.id));
|
|
298
|
+
if (!id)
|
|
299
|
+
throw new CliError("invalid_response", `a ${manifest.provider} deletion has no id at ${deletions.id}`, {
|
|
300
|
+
reason: "source.no-id",
|
|
301
|
+
});
|
|
302
|
+
items.push({ id, removed: true, gone: "deleted" });
|
|
303
|
+
}
|
|
304
|
+
if (!listed.next)
|
|
305
|
+
return items;
|
|
306
|
+
cursor = listed.next;
|
|
307
|
+
}
|
|
308
|
+
throw new CliError("invalid_response", `more than ${MOST_PAGES} pages of ${manifest.provider} deletions since one sync; run sync --rescan`, { reason: "source.changes-too-many" });
|
|
309
|
+
};
|
|
310
|
+
source.changes = async (token) => {
|
|
311
|
+
const from = Number(token);
|
|
312
|
+
if (!Number.isSafeInteger(from))
|
|
313
|
+
throw new CliError("validation_error", `not a change token of ${manifest.provider}: ${token}`, {
|
|
314
|
+
reason: "source.token-invalid",
|
|
315
|
+
});
|
|
316
|
+
const deleted = await deletedSince(from - overlap);
|
|
317
|
+
// Read after the deletions and listed after them, a row of the changes is the newer word and wins.
|
|
318
|
+
const round = await changesOf.call(source, token);
|
|
319
|
+
return { ...round, items: [...deleted, ...round.items] };
|
|
320
|
+
};
|
|
321
|
+
}
|
|
256
322
|
return source;
|
|
257
323
|
};
|
|
@@ -9,6 +9,7 @@ export { conflictReport, fileMirrorState, type HeldLock, type Mirror, type Mirro
|
|
|
9
9
|
export type { SyncOptions } from "../services/documents/ports.js";
|
|
10
10
|
export { extractDocumentMemories, type ImportedSource, type ProposalOptions } from "../services/documents/proposals.js";
|
|
11
11
|
export { type MirrorAction, type PushConflict, type PushOptions, type PushResult, planPush, pushDocuments, scanLocal, skippedName, } from "../services/documents/push.js";
|
|
12
|
+
export { SCAN_READERS, type ScanReader, type ScanReaderChoice, scanReader, scanRetry, scanSkipReason, } from "../services/documents/scans.js";
|
|
12
13
|
export { KEEP_VERSIONS_FOR_DAYS, type SyncResult, syncDocuments } from "../services/documents/sync.js";
|
|
13
14
|
export { type FileConflictResolution, type FileConflictResolveOptions, type FileConflictVersion, type FileConflictView, listFileConflicts, resolveFileConflict, showFileConflict, } from "../services/files/conflicts.js";
|
|
14
15
|
export { excludedBy, exclusionPattern } from "../services/files/exclusions.js";
|
package/dist/documents/index.js
CHANGED
|
@@ -8,6 +8,7 @@ export { watchMirrors, } from "../services/documents/mirror-watch.js";
|
|
|
8
8
|
export { conflictReport, fileMirrorState, mirrorId, mirrorStatus, syncMirrors, } from "../services/documents/mirrors.js";
|
|
9
9
|
export { extractDocumentMemories } from "../services/documents/proposals.js";
|
|
10
10
|
export { planPush, pushDocuments, scanLocal, skippedName, } from "../services/documents/push.js";
|
|
11
|
+
export { SCAN_READERS, scanReader, scanRetry, scanSkipReason, } from "../services/documents/scans.js";
|
|
11
12
|
export { KEEP_VERSIONS_FOR_DAYS, syncDocuments } from "../services/documents/sync.js";
|
|
12
13
|
export { listFileConflicts, resolveFileConflict, showFileConflict, } from "../services/files/conflicts.js";
|
|
13
14
|
export { excludedBy, exclusionPattern } from "../services/files/exclusions.js";
|
|
@@ -97,6 +97,8 @@ export interface IndexedSource<M extends SourceFile = SourceFile> {
|
|
|
97
97
|
tabs: number;
|
|
98
98
|
notRead?: string;
|
|
99
99
|
picture?: "saved" | "too-large";
|
|
100
|
+
/** The OCR reading its text came from (`ScanReader.extractor`); absent for text a reader found in the file. */
|
|
101
|
+
ocr?: string;
|
|
100
102
|
}
|
|
101
103
|
export interface SourceWork<M extends SourceFile = SourceFile> {
|
|
102
104
|
id: string;
|
package/dist/errors/reasons.js
CHANGED
|
@@ -87,6 +87,7 @@ const PROVIDER_API = [
|
|
|
87
87
|
"invalid_response",
|
|
88
88
|
"more changed since one sync than a round reads, and the provider does not list changes oldest first",
|
|
89
89
|
],
|
|
90
|
+
["source.deletions-unchecked", "permission_error", "the provider refused its deletions; sync --rescan finds them"],
|
|
90
91
|
["verify.no-id", "provider_error", "the answer to the sign-in check holds no account id where auth.verify says"],
|
|
91
92
|
["provider.usage-limit", "rate_limited", "the account's usage limit at the provider is reached; wait, do not retry"],
|
|
92
93
|
["access.denied", "permission_error", "the provider refused this account access to the item"],
|
|
@@ -226,6 +227,9 @@ const OTHERS = [
|
|
|
226
227
|
],
|
|
227
228
|
validation("agent.cost-unknown", "the agent reports no cost, so a cost cap cannot stop it"),
|
|
228
229
|
validation("document.changed", "the document changed while it was read; nothing was saved"),
|
|
230
|
+
validation("document.needs-ocr", "the PDF has no text layer; a documents sync reads it with OCR (read_scans)"),
|
|
231
|
+
validation("document.scan-unread", "OCR could not read the scan or picture; a sync tries again once the file changes"),
|
|
232
|
+
validation("document.scan-later", "OCR stopped at its page limit or a busy model; the next sync goes on"),
|
|
229
233
|
["document.not-imported", "not_found", "the document is not imported in this source account"],
|
|
230
234
|
["document.version-missing", "not_found", "the local copy holds no such version of the document"],
|
|
231
235
|
["document.not-found", "not_found", "no listed document has that reference"],
|
|
@@ -6,6 +6,8 @@ export declare const readableFile: ({ name, mime }: {
|
|
|
6
6
|
name: string;
|
|
7
7
|
mime: string;
|
|
8
8
|
}) => boolean;
|
|
9
|
+
/** The start of the reason a file with no text layer is kept by name only, before and after OCR was offered. */
|
|
10
|
+
export declare const NO_TEXT_LAYER = "file has no text layer (a scan or images only)";
|
|
9
11
|
/**
|
|
10
12
|
* The text of a downloaded file through cli-core's readers, or a `validation_error` that says why there is none, in
|
|
11
13
|
* words a person acts on. `command` names the CLI in the hint for a missing reader.
|
|
@@ -26,6 +26,8 @@ const READABLE = new Set([
|
|
|
26
26
|
*/
|
|
27
27
|
export const readableFile = ({ name, mime }) => READABLE.has(mime) ||
|
|
28
28
|
/\.(md|markdown|txt|pdf|doc|docx|rtf|odt|ods|odp|xlsx|pptx|epub|html?|xhtml|csv|tsv)$/iu.test(name);
|
|
29
|
+
/** The start of the reason a file with no text layer is kept by name only, before and after OCR was offered. */
|
|
30
|
+
export const NO_TEXT_LAYER = "file has no text layer (a scan or images only)";
|
|
29
31
|
/**
|
|
30
32
|
* The text of a downloaded file through cli-core's readers, or a `validation_error` that says why there is none, in
|
|
31
33
|
* words a person acts on. `command` names the CLI in the hint for a missing reader.
|
|
@@ -34,14 +36,16 @@ export const fileText = async (bytes, file, command, env = process.env) => {
|
|
|
34
36
|
const read = await extractText(bytes, { kind: "document", name: file.name, mime: file.mime, path: file.name }, importEngine, undefined, env);
|
|
35
37
|
if (read.status === "extracted")
|
|
36
38
|
return read.text;
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
39
|
+
if (read.status === "needs-agent")
|
|
40
|
+
throw new CliError("validation_error", `${NO_TEXT_LAYER}; a documents sync reads it with OCR (read_scans)`, {
|
|
41
|
+
reason: "document.needs-ocr",
|
|
42
|
+
});
|
|
43
|
+
const reason = read.status === "engine-missing"
|
|
44
|
+
? engineHint(read.engine, command)
|
|
45
|
+
: read.status === "unreadable"
|
|
46
|
+
? "file could not be read as text; it may be damaged or protected"
|
|
47
|
+
: read.status === "unsupported"
|
|
48
|
+
? "file contents do not match its type"
|
|
49
|
+
: `file is too large for the document readers (over ${Math.round(attachmentMaxBytes(env) / 1024 / 1024)} MB, or over ${MAX_TEXT_CHARS} characters of text)`;
|
|
46
50
|
throw new CliError("validation_error", reason);
|
|
47
51
|
};
|
|
@@ -418,7 +418,14 @@ export const planDocuments = async (options, source, state, roots, limit, pictur
|
|
|
418
418
|
const skipped = [];
|
|
419
419
|
const again = [];
|
|
420
420
|
let rereads = 0;
|
|
421
|
-
const
|
|
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;
|
|
422
429
|
for (const root of roots)
|
|
423
430
|
if (folders[root]?.trashed)
|
|
424
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
|
|
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
|
-
|
|
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] = {
|
|
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 = {
|
|
@@ -14,12 +14,12 @@ export declare const metadataService: (deps: ServiceDeps) => {
|
|
|
14
14
|
dryRun?: boolean;
|
|
15
15
|
}) => Promise<{
|
|
16
16
|
items: ({
|
|
17
|
+
error?: undefined;
|
|
17
18
|
chatId: string;
|
|
18
19
|
tags: import("../domain/channel-tags.js").ChannelTagMatch[];
|
|
19
20
|
algorithm: string;
|
|
20
21
|
fetchedAt: string | null;
|
|
21
22
|
source: string;
|
|
22
|
-
error?: undefined;
|
|
23
23
|
} | {
|
|
24
24
|
tags?: undefined;
|
|
25
25
|
algorithm?: undefined;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@wirecat/cli-core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.740.0",
|
|
4
4
|
"description": "The messenger-neutral half of a messaging CLI: domain model, message locators, rendering, name resolution, the SQLite seam, the command skeleton and shared read commands, the send guard, run records and the message store",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"author": "Viacheslav Ptsarev",
|