@wirecat/files-cli 0.0.0-stage → 0.2.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 (87) hide show
  1. package/CHANGELOG.md +52 -0
  2. package/LICENSE +204 -0
  3. package/README.md +68 -2
  4. package/contracts/wirecat.json +793 -0
  5. package/dist/answer.js +60 -0
  6. package/dist/app.js +6 -0
  7. package/dist/author.js +87 -0
  8. package/dist/bin/files.js +40 -0
  9. package/dist/bundle/chunk-3GCXH3WT.js +263 -0
  10. package/dist/bundle/files.js +21 -0
  11. package/dist/bundle/program-OBKXQ4VY.js +12479 -0
  12. package/dist/config.js +74 -0
  13. package/dist/doctor.js +33 -0
  14. package/dist/entities.js +104 -0
  15. package/dist/failure.js +21 -0
  16. package/dist/identity.js +27 -0
  17. package/dist/import/audio.js +96 -0
  18. package/dist/import/command.js +156 -0
  19. package/dist/import/external-id.js +44 -0
  20. package/dist/import/files.js +206 -0
  21. package/dist/import/readers.js +87 -0
  22. package/dist/index.js +3 -0
  23. package/dist/migrate.js +192 -0
  24. package/dist/notes/about.js +55 -0
  25. package/dist/notes/bound.js +41 -0
  26. package/dist/notes/command.js +241 -0
  27. package/dist/notes/dates.js +15 -0
  28. package/dist/notes/dialects/common.js +79 -0
  29. package/dist/notes/dialects/index.js +6 -0
  30. package/dist/notes/dialects/markdown.js +51 -0
  31. package/dist/notes/dialects/obsidian.js +33 -0
  32. package/dist/notes/dialects/types.js +2 -0
  33. package/dist/notes/embed.js +97 -0
  34. package/dist/notes/export.js +76 -0
  35. package/dist/notes/files.js +87 -0
  36. package/dist/notes/folders-command.js +172 -0
  37. package/dist/notes/folders.js +90 -0
  38. package/dist/notes/import.js +289 -0
  39. package/dist/notes/internal.js +51 -0
  40. package/dist/notes/links.js +46 -0
  41. package/dist/notes/list.js +23 -0
  42. package/dist/notes/renames.js +24 -0
  43. package/dist/notes/search.js +16 -0
  44. package/dist/notes/state.js +33 -0
  45. package/dist/options.js +9 -0
  46. package/dist/output.js +4 -0
  47. package/dist/paths.js +5 -0
  48. package/dist/people/command.js +92 -0
  49. package/dist/people/identity.js +19 -0
  50. package/dist/people/notes-map.js +58 -0
  51. package/dist/people/owner.js +14 -0
  52. package/dist/people/subject.js +19 -0
  53. package/dist/program.js +101 -0
  54. package/dist/progress.js +19 -0
  55. package/dist/reasons.js +187 -0
  56. package/dist/records/input.js +114 -0
  57. package/dist/records/receipt.js +25 -0
  58. package/dist/records/source.js +12 -0
  59. package/dist/refs.js +28 -0
  60. package/dist/run/lock.js +21 -0
  61. package/dist/save-help.js +3 -0
  62. package/dist/search.js +63 -0
  63. package/dist/sources/command.js +295 -0
  64. package/dist/sources/copy.js +32 -0
  65. package/dist/sources/mentions.js +78 -0
  66. package/dist/sources/read.js +262 -0
  67. package/dist/sources/readers/ai-model.js +74 -0
  68. package/dist/sources/readers/api.js +48 -0
  69. package/dist/sources/readers/claude-code.js +74 -0
  70. package/dist/sources/readers/codex.js +72 -0
  71. package/dist/sources/readers/index.js +10 -0
  72. package/dist/sources/readers/keys.js +31 -0
  73. package/dist/sources/readers/ollama.js +84 -0
  74. package/dist/sources/readers/process.js +49 -0
  75. package/dist/sources/readers/types.js +2 -0
  76. package/dist/sources/suggest-command.js +253 -0
  77. package/dist/sources/suggest.js +142 -0
  78. package/dist/sources/transcript.js +52 -0
  79. package/dist/store/group.js +8 -0
  80. package/dist/store/scope.js +25 -0
  81. package/dist/store/source-list.js +22 -0
  82. package/dist/sync.js +182 -0
  83. package/dist/terminal.js +16 -0
  84. package/dist/version.js +2 -0
  85. package/dist/wcat.js +4 -0
  86. package/package.json +89 -4
  87. package/skills/files-cli/SKILL.md +41 -0
@@ -0,0 +1,295 @@
1
+ import { existsSync } from "node:fs";
2
+ import { CliError } from "@wirecat/cli-base";
3
+ import { annotate } from "@wirecat/cli-base/commands";
4
+ import { addedSourceKeyOf, environmentOf, FETCH, LOCAL_READ, LOCAL_WRITE, REMOTE_READ, } from "@wirecat/cli-core";
5
+ import { agentPictureReader, aiImageReader, MAX_TEXT_CHARS } from "@wirecat/cli-core/documents";
6
+ import { InvalidArgumentError } from "commander";
7
+ import { answers, itemAnswer, listAnswer, withStore } from "../answer.js";
8
+ import { APP } from "../app.js";
9
+ import { byOption, reasonOption, whoRuns } from "../author.js";
10
+ import { loadConfig } from "../config.js";
11
+ import { searchModelPresent } from "../notes/embed.js";
12
+ import { collect } from "../options.js";
13
+ import { subjectOf } from "../people/subject.js";
14
+ import { refuseBareNumber } from "../refs.js";
15
+ import { dropCopy, keepCopy } from "./copy.js";
16
+ import { namedIn } from "./mentions.js";
17
+ import { argumentKind, previewOf, readFile, readPage, readText, SOURCE_TEXT_CHARS, withNextStep, } from "./read.js";
18
+ import { readerCommands } from "./suggest-command.js";
19
+ const SUBJECT_HELP = "who or what it is about: person:, organization:, project:, task:, meeting:, or <messenger>:<name or id>; repeat for more";
20
+ const TEXT_BYTES = 16_384;
21
+ const MAX_TEXT_BYTES = 1_048_576;
22
+ const between = (low, high, what) => (value) => {
23
+ const number = Number(value);
24
+ if (!Number.isInteger(number) || number < low || number > high)
25
+ throw new InvalidArgumentError(`${what}: a whole number, ${low} to ${high}`);
26
+ return number;
27
+ };
28
+ /** The text cut at a character, so its UTF-8 form is at most `bytes`. */
29
+ const boundedText = (text, bytes) => {
30
+ const encoded = Buffer.from(text);
31
+ if (encoded.byteLength <= bytes)
32
+ return { text, truncated: false };
33
+ let cut = encoded.subarray(0, bytes).toString("utf8");
34
+ if (cut.endsWith("�"))
35
+ cut = cut.slice(0, -1);
36
+ return { text: cut, truncated: true };
37
+ };
38
+ const documentRef = async (store, reference) => {
39
+ await refuseBareNumber(store, reference, ["document"]);
40
+ const ref = reference.trim();
41
+ if (!/^document:[1-9]\d*$/.test(ref))
42
+ throw new CliError("validation_error", `${reference} is not a source; give its document:<id>`, {
43
+ reason: "input.invalid",
44
+ });
45
+ return ref;
46
+ };
47
+ const isAgentServer = (command, _env) => environmentOf(command).agent !== undefined;
48
+ /** Every findings batch whose evidence cites `ref`; the store lists batches by project only, so all are read. */
49
+ const batchesCiting = async (store, ref) => {
50
+ const found = [];
51
+ for (let offset = 0;; offset += 50) {
52
+ const page = await store.evidenceFindings.list({ limit: 50, offset });
53
+ for (const batch of page.items) {
54
+ const findings = batch.input.findings
55
+ .filter((finding) => finding.evidence.some((evidence) => evidence.reference === ref))
56
+ .map((finding) => finding.id);
57
+ if (findings.length > 0)
58
+ found.push({ id: batch.id, status: batch.status, findings });
59
+ }
60
+ if (!page.hasMore)
61
+ return found;
62
+ }
63
+ };
64
+ const citing = async (store, ref) => {
65
+ const links = await store.notes.links({ to: ref, kind: "evidence" });
66
+ const of = (type) => [...new Set(links.flatMap(({ from }) => (from.startsWith(`${type}:`) ? [from] : [])))];
67
+ return { facts: of("fact"), memories: of("memory") };
68
+ };
69
+ const IMAGE_WHY = {
70
+ "ai.not-set": "kept by its name: no AI model is chosen (wcat models ai set)",
71
+ "ai.images-not-allowed": "kept by its name: images may not go to your AI model (wcat models ai set … --allow-remote)",
72
+ "ai.key-missing": "kept by its name: no key is stored for your AI model (wcat models ai set … --secret-stdin)",
73
+ "ai.owner-only": "kept by its name: only your own add sends an image to your AI model, not an agent's",
74
+ "ai.setting-invalid": "kept by its name: the ai section of the WireCat config is not one files can read (wcat models ai set)",
75
+ "image.unsupported": "kept by its name: the model reads PNG, JPEG and WebP up to 4 MB",
76
+ "ai.empty-answer": "kept by its name: the model answered nothing; it may not read pictures — choose a vision model (wcat models ai set)",
77
+ "ai.failed": "kept by its name: your AI model could not read it (wcat models ai check)",
78
+ };
79
+ const imageLine = (image) => image.read_by ? `read by ${image.read_by}` : IMAGE_WHY[image.reason ?? "ai.failed"];
80
+ export const sourcesCommand = (program, streams, env, { fetch, readers = {} } = {}) => {
81
+ const { print, run } = answers(program, streams, env);
82
+ const sources = program
83
+ .command("sources")
84
+ .summary("files, web pages and text you add by hand")
85
+ .description("sources you add by hand: pasted text, a file or a web page, kept as searchable documents");
86
+ byOption(reasonOption(annotate(sources.command("add"), { effects: FETCH, output: { entity: "added_source" } })
87
+ .summary("keep a file, a web page or pasted text as a document")
88
+ .description("keep a file, a web page or pasted text as a document of its own; only its text is kept unless --keep-copy")))
89
+ .argument("<source>", "a file's path, an http(s) address, or - to read the text from stdin")
90
+ .option("--title <title>", "a title; otherwise the page's or file's own, or the text's first line")
91
+ .option("--subject <ref>", SUBJECT_HELP, collect)
92
+ .option("--keep-copy", "also keep a copy of the file in files' data folder, so it opens after the file is gone")
93
+ .option("--max-chars <n>", `most characters of text to keep, up to ${MAX_TEXT_CHARS} (default ${SOURCE_TEXT_CHARS})`, between(1, MAX_TEXT_CHARS, "--max-chars"))
94
+ .action(async (given, options, command) => {
95
+ const kind = argumentKind(given);
96
+ if (isAgentServer(command, env) && kind !== "text")
97
+ throw new CliError("permission_error", "over MCP a source is added as text only, never from a path or a link");
98
+ if (options.keepCopy && kind !== "path")
99
+ throw new CliError("validation_error", "--keep-copy keeps a file; a link or pasted text keeps its text only", {
100
+ reason: "input.invalid",
101
+ param: "keep_copy",
102
+ });
103
+ const maxChars = options.maxChars ?? SOURCE_TEXT_CHARS;
104
+ const who = await whoRuns(command, env, { asOwner: options.asOwner, question: "add this source as yours?" });
105
+ const by = who === "owner" ? "owner" : { bot: who.bot, reason: options.reason?.trim() || "files sources add" };
106
+ const read = await (kind === "text"
107
+ ? readText(environmentOf(command).stdin ?? process.stdin, { maxChars })
108
+ : kind === "url"
109
+ ? readPage(given, { maxChars, ...(fetch ? { fetch } : {}) })
110
+ : readFile(given, {
111
+ maxChars,
112
+ // An agent's add never sends the owner's image off this computer; the consent was for the owner's own adds.
113
+ image: () => {
114
+ if (who !== "owner")
115
+ return { refused: "ai.owner-only" };
116
+ try {
117
+ return (agentPictureReader(env) ??
118
+ aiImageReader({ app: APP, env, keyring: readers.keyring, fetch: readers.fetch }));
119
+ }
120
+ catch {
121
+ return { refused: "ai.setting-invalid" };
122
+ }
123
+ },
124
+ })).catch((error) => {
125
+ throw withNextStep(error);
126
+ });
127
+ const content = {
128
+ kind: read.kind,
129
+ text: read.text,
130
+ url: read.url ?? null,
131
+ ...(read.bytes ? { bytes: read.bytes } : {}),
132
+ };
133
+ const item = await withStore(env, async (store) => {
134
+ const subjects = await Promise.all((options.subject ?? []).map(async (subject) => (await subjectOf(store, subject)).ref));
135
+ let copy;
136
+ if (options.keepCopy && read.bytes && (await store.notes.findAddedSource(content)).duplicateOf === null)
137
+ copy = keepCopy(env, addedSourceKeyOf(content).hash, read.bytes);
138
+ let saved;
139
+ try {
140
+ saved = await store.notes.saveAddedSource({
141
+ ...content,
142
+ read: read.read,
143
+ title: options.title?.trim() || read.title,
144
+ fileName: read.fileName ?? null,
145
+ mime: read.mime ?? null,
146
+ size: read.size,
147
+ subjects,
148
+ by,
149
+ ...(copy ? { keepCopy: { path: copy.path } } : {}),
150
+ ...(read.metadata ? { metadata: read.metadata } : {}),
151
+ ...(read.sections ? { sections: read.sections } : {}),
152
+ });
153
+ }
154
+ catch (error) {
155
+ if (copy?.wrote)
156
+ dropCopy(env, copy.path);
157
+ throw error;
158
+ }
159
+ if (copy?.wrote && saved.duplicateOf !== null)
160
+ dropCopy(env, copy.path);
161
+ const text = read.read === "extracted";
162
+ // A source stored before keeps the text of its first read; this read's cut says nothing about it.
163
+ const same = saved.duplicateOf === null && saved.note.text === read.text.trim();
164
+ return {
165
+ ref: saved.note.ref,
166
+ created: saved.created,
167
+ duplicateOf: saved.duplicateOf,
168
+ title: saved.note.title,
169
+ kind: read.kind,
170
+ mime: read.mime ?? null,
171
+ bytes: read.size,
172
+ chars: saved.note.text.length,
173
+ truncated: same ? read.truncated : null,
174
+ extractor: read.extractor,
175
+ read: read.read,
176
+ url: read.url ?? null,
177
+ kept: saved.kept,
178
+ searchable: {
179
+ words: text,
180
+ meaning: text && searchModelPresent(env) && loadConfig(env).notes?.embed !== false,
181
+ },
182
+ subjects: saved.subjects,
183
+ ...(read.image ? { image: read.image } : {}),
184
+ };
185
+ });
186
+ print(options.json, itemAnswer(item), [
187
+ `${item.ref}${item.duplicateOf ? " already stored: only its subjects were added" : item.created ? " added" : " already added"}`,
188
+ ` ${item.title ?? ""} ${item.kind}${item.mime ? ` · ${item.mime}` : ""} · ${item.chars} characters${item.truncated === true ? " (only the first part is kept)" : ""}`,
189
+ ` kept: ${item.kept === "copy" ? "its text and a copy of the file" : item.kept === "text" ? "its text" : "nothing new"}`,
190
+ ` search: ${item.searchable.words ? "by words" : "by its title and subjects only"}${item.searchable.meaning ? " and by meaning after files sync" : ""}`,
191
+ ...(item.image ? [` image: ${imageLine(item.image)}`] : []),
192
+ ...(item.subjects.length ? [` about: ${item.subjects.join(", ")}`] : []),
193
+ ].join("\n"));
194
+ });
195
+ annotate(sources.command("preview"), { effects: REMOTE_READ, output: { entity: "source_preview" } })
196
+ .summary("read a web page as sources add would, and keep nothing")
197
+ .description("read a web page as sources add would, with the same refusals, and say what would be kept; nothing is saved")
198
+ .argument("<url>", "an http(s) address")
199
+ .action(async (given, options, command) => {
200
+ if (isAgentServer(command, env))
201
+ throw new CliError("permission_error", "an agent over MCP cannot make files fetch an address", {
202
+ reason: "source.agent-fetch",
203
+ });
204
+ if (argumentKind(given) !== "url")
205
+ throw new CliError("validation_error", "give an http(s) address; a file is previewed by the app that picked it", {
206
+ reason: "input.invalid",
207
+ });
208
+ const read = await readPage(given, { maxChars: SOURCE_TEXT_CHARS, ...(fetch ? { fetch } : {}) }).catch((error) => {
209
+ throw withNextStep(error);
210
+ });
211
+ const item = previewOf(read);
212
+ print(options.json, itemAnswer(item), [
213
+ `${item.url} nothing saved`,
214
+ ` ${item.title ?? ""} ${item.kind}${item.mime ? ` · ${item.mime}` : ""} · ${item.chars} characters${item.truncated ? " (only the first part would be kept)" : ""}`,
215
+ ...(item.description ? [` ${item.description}`] : []),
216
+ ...(item.excerpt ? [` “${item.excerpt}”`] : []),
217
+ ].join("\n"));
218
+ });
219
+ annotate(sources.command("show"), { effects: LOCAL_READ, output: { entity: "source_detail" } })
220
+ .summary("one source: its text, what is kept, and what cites it")
221
+ .description("one source: its text, what is kept, what it is about, and the facts, memories and batches citing it")
222
+ .argument("<ref>", "document:<id>, as sources add answered")
223
+ .option("--bytes <bytes>", `most UTF-8 bytes of its text, up to ${MAX_TEXT_BYTES} (default ${TEXT_BYTES})`, between(1, MAX_TEXT_BYTES, "--bytes"))
224
+ .action((reference, options) => run(options.json, async (store) => {
225
+ const ref = await documentRef(store, reference);
226
+ const source = await store.notes.addedSource(ref);
227
+ const note = source?.note ?? (await store.notes.note(ref));
228
+ const { text, truncated } = boundedText(note.text, options.bytes ?? TEXT_BYTES);
229
+ const subjects = (await store.notes.links({ from: ref, kind: "about" })).flatMap(({ to, confirmed }) => to === null ? [] : [{ ref: to, confirmed }]);
230
+ return itemAnswer({
231
+ ref,
232
+ title: note.title,
233
+ added: source !== undefined,
234
+ kind: source?.kind ?? null,
235
+ url: source?.url ?? null,
236
+ fileName: source?.fileName ?? null,
237
+ mime: source?.mime ?? null,
238
+ bytes: source?.size ?? null,
239
+ // The row says a copy was kept; only the file itself says it still is.
240
+ kept: source === undefined ? null : source.copy !== null && existsSync(source.copy) ? "copy" : "text",
241
+ chars: note.text.length,
242
+ text,
243
+ textTruncated: truncated,
244
+ createdAt: note.createdAt,
245
+ updatedAt: note.updatedAt,
246
+ subjects,
247
+ ...(await citing(store, ref)),
248
+ batches: await batchesCiting(store, ref),
249
+ });
250
+ }));
251
+ annotate(sources.command("mentions"), { effects: LOCAL_READ, output: { entity: "source_mention" } })
252
+ .summary("known people and organizations named in a source")
253
+ .description("people and organizations files knows whose names appear in a source's text; nothing leaves")
254
+ .argument("<ref>", "document:<id>")
255
+ .action((reference, options) => run(options.json, async (store) => {
256
+ const ref = await documentRef(store, reference);
257
+ const found = await namedIn(store, await store.notes.note(ref));
258
+ return listAnswer("sources mentions", {
259
+ items: found.items,
260
+ limit: Math.max(1, found.items.length),
261
+ has_more: false,
262
+ ...(found.organizationsComplete
263
+ ? {}
264
+ : {
265
+ missing: [
266
+ {
267
+ field: "organizations",
268
+ why: `only the first ${found.organizationsChecked} organizations were matched by name`,
269
+ },
270
+ ],
271
+ }),
272
+ });
273
+ }));
274
+ byOption(annotate(sources.command("remove"), { effects: LOCAL_WRITE, output: { entity: "source_removal" } })
275
+ .summary("remove a source you added, and its kept copy")
276
+ .description("remove a source you added, and its copy if one was kept; the next source check reviews what cites it"))
277
+ .argument("<ref>", "document:<id> of a source you added")
278
+ .action(async (reference, options, command) => {
279
+ const who = await whoRuns(command, env, { asOwner: options.asOwner, question: "remove this source as you?" });
280
+ const by = who === "owner" ? "owner" : { bot: who.bot, reason: "files sources remove" };
281
+ await run(options.json, async (store) => {
282
+ const ref = await documentRef(store, reference);
283
+ const cited = await citing(store, ref);
284
+ const removed = await store.notes.removeAddedSource(ref, by);
285
+ return itemAnswer({
286
+ ref: removed.ref,
287
+ removed: true,
288
+ copyDeleted: removed.copy !== null && dropCopy(env, removed.copy),
289
+ ...cited,
290
+ });
291
+ });
292
+ });
293
+ readerCommands(program, sources, streams, env, readers);
294
+ };
295
+ //# sourceMappingURL=command.js.map
@@ -0,0 +1,32 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { existsSync, mkdirSync, renameSync, rmSync, writeFileSync } from "node:fs";
3
+ import { isAbsolute, join, relative, resolve, sep } from "node:path";
4
+ import { resolvePaths } from "@wirecat/cli-base";
5
+ import { APP } from "../app.js";
6
+ /** Where files keeps the copies the owner asked for, each named by the hash of its bytes. */
7
+ export const copiesDir = (env) => join(resolvePaths({ appName: APP.appName, prefix: APP.envPrefix, env }).state, "sources");
8
+ const copyPath = (env, hash) => join(copiesDir(env), hash);
9
+ /** Writes the copy unless it is there; answers whether this call wrote it, so a failed save can take it back. */
10
+ export const keepCopy = (env, hash, bytes) => {
11
+ const path = copyPath(env, hash);
12
+ if (existsSync(path))
13
+ return { path, wrote: false };
14
+ mkdirSync(copiesDir(env), { recursive: true, mode: 0o700 });
15
+ // A rename is whole or nothing: a run stopped half way leaves no copy that looks kept.
16
+ const partial = `${path}.${randomUUID()}.part`;
17
+ writeFileSync(partial, bytes, { mode: 0o600 });
18
+ renameSync(partial, path);
19
+ return { path, wrote: true };
20
+ };
21
+ /**
22
+ * Deletes a copy the store named, only inside files' own folder: the path comes from the database, and a row
23
+ * someone edited must not make files delete any other file.
24
+ */
25
+ export const dropCopy = (env, path) => {
26
+ const inside = relative(resolve(copiesDir(env)), resolve(path));
27
+ if (!inside || isAbsolute(inside) || inside.startsWith("..") || inside.includes(sep) || !existsSync(path))
28
+ return false;
29
+ rmSync(path);
30
+ return true;
31
+ };
32
+ //# sourceMappingURL=copy.js.map
@@ -0,0 +1,78 @@
1
+ const PAGE = 500;
2
+ const ORGANIZATIONS_LISTED = 500;
3
+ const escaped = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
4
+ const folded = (text) => text.normalize("NFC").toLocaleLowerCase();
5
+ /**
6
+ * The document's own mentions, read from cli-core's list of every document's mentions. The list is ordered by each
7
+ * document's time, newest first, then its id, so one document's mentions come together and the walk stops once it is
8
+ * past them, or past where they would be.
9
+ */
10
+ const mentionsOf = async (store, note) => {
11
+ const id = Number(note.id);
12
+ const at = note.modifiedAt ?? note.updatedAt;
13
+ const found = [];
14
+ for (let offset = 0;; offset += PAGE) {
15
+ const page = await store.sourceMentions.list("document", undefined, { limit: PAGE, offset }, []);
16
+ for (const mention of page.items) {
17
+ const when = mention.source.at ?? "";
18
+ if (mention.source.id === id)
19
+ found.push(mention);
20
+ else if (found.length > 0 || when < at || (when === at && mention.source.id < id))
21
+ return found;
22
+ }
23
+ if (!page.hasMore)
24
+ return found;
25
+ }
26
+ };
27
+ /**
28
+ * People and organizations files knows whose names appear in a document. People come from cli-core's mentions: a
29
+ * name it found, linked or matching known people, and an e-mail address or phone number a person owns. Organizations
30
+ * are matched by their whole name in the text, since no mention kind finds them.
31
+ */
32
+ export const namedIn = async (store, note) => {
33
+ const named = new Map();
34
+ const add = (ref, type, name, foundAs) => {
35
+ const entry = named.get(ref) ?? { ref, type, name, foundAs: [] };
36
+ if (!entry.foundAs.includes(foundAs))
37
+ entry.foundAs.push(foundAs);
38
+ named.set(ref, entry);
39
+ };
40
+ const candidates = new Map();
41
+ for (const mention of await mentionsOf(store, note)) {
42
+ if (mention.status === "dismissed")
43
+ continue;
44
+ if (mention.kind === "person-name") {
45
+ let people = mention.target?.startsWith("person:") ? [mention.target] : candidates.get(mention.value);
46
+ if (people === undefined) {
47
+ people = (await store.sourceMentions.show(mention.id, []))?.candidates ?? [];
48
+ candidates.set(mention.value, people);
49
+ }
50
+ for (const ref of people)
51
+ add(ref, "person", null, mention.written);
52
+ }
53
+ else if (mention.kind === "email" || mention.kind === "phone") {
54
+ const person = await store.people.personOf({ provider: mention.kind, id: mention.value });
55
+ if (person)
56
+ add(`person:${person.uid}`, "person", person.name, mention.written);
57
+ }
58
+ }
59
+ for (const entry of named.values())
60
+ if (entry.name === null)
61
+ entry.name = (await store.people.personByUid(entry.ref.slice("person:".length)))?.name ?? null;
62
+ const text = folded(`${note.title ?? ""}\n${note.text}`);
63
+ const organizations = await store.knowledge.organizations();
64
+ for (const organization of organizations) {
65
+ const name = organization.name.trim();
66
+ if (name.length < 3)
67
+ continue;
68
+ const at = new RegExp(`(?<![\\p{L}\\p{N}])${escaped(folded(name))}(?![\\p{L}\\p{N}])`, "u");
69
+ if (at.test(text))
70
+ add(organization.ref, "organization", organization.name, name);
71
+ }
72
+ return {
73
+ items: [...named.values()],
74
+ organizationsChecked: organizations.length,
75
+ organizationsComplete: organizations.length < ORGANIZATIONS_LISTED,
76
+ };
77
+ };
78
+ //# sourceMappingURL=mentions.js.map
@@ -0,0 +1,262 @@
1
+ import { statSync } from "node:fs";
2
+ import { basename, extname } from "node:path";
3
+ import { CliError, isCliError } from "@wirecat/cli-base";
4
+ import { attachmentMaxBytes, extractText, fetchPage, importEngine, ocrImage, readWhole, sizeText, } from "@wirecat/cli-core/documents";
5
+ import { transcriptText } from "./transcript.js";
6
+ /** What files' folder import keeps of a file's text; `--max-chars` may raise it to the store's own limit. */
7
+ export const SOURCE_TEXT_CHARS = 200_000;
8
+ const URL_LIKE = /^[a-z][a-z0-9+.-]*:\/\//i;
9
+ export const isUrl = (given) => URL_LIKE.test(given);
10
+ export const argumentKind = (given) => (given === "-" ? "text" : isUrl(given) ? "url" : "path");
11
+ export const MIMES = {
12
+ ".md": "text/markdown",
13
+ ".markdown": "text/markdown",
14
+ ".txt": "text/plain",
15
+ ".csv": "text/csv",
16
+ ".tsv": "text/tab-separated-values",
17
+ ".html": "text/html",
18
+ ".htm": "text/html",
19
+ ".pdf": "application/pdf",
20
+ ".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
21
+ ".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
22
+ ".pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation",
23
+ ".doc": "application/msword",
24
+ ".xls": "application/vnd.ms-excel",
25
+ ".odt": "application/vnd.oasis.opendocument.text",
26
+ ".ods": "application/vnd.oasis.opendocument.spreadsheet",
27
+ ".odp": "application/vnd.oasis.opendocument.presentation",
28
+ ".epub": "application/epub+zip",
29
+ ".rtf": "application/rtf",
30
+ ".vtt": "text/vtt",
31
+ ".srt": "application/x-subrip",
32
+ ".png": "image/png",
33
+ ".jpg": "image/jpeg",
34
+ ".jpeg": "image/jpeg",
35
+ ".gif": "image/gif",
36
+ ".webp": "image/webp",
37
+ };
38
+ const NEXT = {
39
+ "source.unsupported": "save it as PDF, Word or plain text and add that file",
40
+ "source.no-text": "nothing was saved; add a file that holds text, or paste the text with files sources add -",
41
+ "source.unreadable": "open it and save it again, or as PDF or plain text, and add that file",
42
+ "source.engine-missing": "files installs its readers on first use: run the same command once this computer can reach registry.npmjs.org",
43
+ "source.too-large": "add a smaller part of it, or save only its text and add that",
44
+ "source.url-refused": "give an http or https address of a public page",
45
+ "source.url-status": "check the address in a browser; if it opens only for you, save the page as a file and add it",
46
+ "source.url-timeout": "try again later, or save the page as a file and add it",
47
+ "source.url-redirects": "open the address in a browser and add the address it ends at",
48
+ "source.url-unreachable": "check the address and the connection, or save the page as a file and add it",
49
+ "source.needs-sign-in": "add it through your signed-in Google account: drive documents add <url> --profiles <names|all> (or drive <profile> documents add <url>)",
50
+ };
51
+ /** cli-core's refusal, with the plain next step files knows for it; its code and reason stay as they were. */
52
+ export const withNextStep = (error) => {
53
+ if (!isCliError(error))
54
+ return error;
55
+ const reason = error.details.reason;
56
+ const step = typeof reason === "string" ? NEXT[reason] : undefined;
57
+ return step === undefined ? error : new CliError(error.code, `${error.message} — ${step}`, error.details);
58
+ };
59
+ const refusal = (extraction, name) => {
60
+ switch (extraction.status) {
61
+ case "unsupported":
62
+ return new CliError("validation_error", `no reader takes ${name}`, { reason: "source.unsupported" });
63
+ case "unreadable":
64
+ return new CliError("validation_error", `the ${extraction.extractor} reader could not read ${name}`, {
65
+ reason: "source.unreadable",
66
+ });
67
+ case "engine-missing":
68
+ return new CliError("configuration_error", `reading ${name} needs ${extraction.engine}, which is not installed`, {
69
+ reason: "source.engine-missing",
70
+ });
71
+ case "too-large":
72
+ return new CliError("validation_error", `${name} is larger than its reader reads`, { reason: "source.too-large" });
73
+ }
74
+ };
75
+ const tooLarge = (what) => new CliError("validation_error", `${what} is larger than ${sizeText(attachmentMaxBytes())}; configure MESSAGING_ATTACHMENT_MAX_MIB`, {
76
+ reason: "source.too-large",
77
+ });
78
+ const noText = (what) => new CliError("validation_error", `${what} holds no text to keep`, { reason: "source.no-text" });
79
+ /** Line ends as one `\n`, and at most `maxChars`: what the reader found, as the store keeps it. */
80
+ const bounded = (text, maxChars) => {
81
+ const normalized = text.replace(/\r\n?/g, "\n");
82
+ return { text: normalized.slice(0, maxChars), cut: normalized.length > maxChars };
83
+ };
84
+ const firstLine = (text) => {
85
+ const line = text.trimStart().split("\n", 1)[0]?.trim() ?? "";
86
+ return line ? line.slice(0, 120) : null;
87
+ };
88
+ /** A metadata value as one line of text: the first non-empty one when the page gave several. */
89
+ const metaText = (metadata, key) => {
90
+ const value = metadata?.[key];
91
+ const first = (Array.isArray(value) ? value : [value]).find((v) => typeof v === "string" && v.trim());
92
+ return first ? first.trim().slice(0, 500) : null;
93
+ };
94
+ const titleIn = (metadata) => metaText(metadata, "title");
95
+ const readStdin = async (stdin) => {
96
+ const max = attachmentMaxBytes();
97
+ const chunks = [];
98
+ let size = 0;
99
+ for await (const chunk of stdin) {
100
+ const bytes = typeof chunk === "string" ? Buffer.from(chunk) : Buffer.from(chunk);
101
+ size += bytes.byteLength;
102
+ if (size > max)
103
+ throw tooLarge("the text on stdin");
104
+ chunks.push(bytes);
105
+ }
106
+ return Buffer.concat(chunks).toString("utf8");
107
+ };
108
+ export const readText = async (stdin, { maxChars }) => {
109
+ const raw = await readStdin(stdin);
110
+ const { text, cut } = bounded(raw, maxChars);
111
+ if (!text.trim())
112
+ throw noText("the text on stdin");
113
+ return {
114
+ kind: "text",
115
+ text,
116
+ read: "extracted",
117
+ url: null,
118
+ fileName: null,
119
+ mime: "text/plain",
120
+ size: Buffer.byteLength(raw),
121
+ extractor: null,
122
+ truncated: cut,
123
+ title: firstLine(text),
124
+ };
125
+ };
126
+ export const readFile = async (path, { maxChars, load = importEngine, image }) => {
127
+ const stat = statSync(path, { throwIfNoEntry: false });
128
+ const name = basename(path);
129
+ if (!stat)
130
+ throw new CliError("not_found", `no file ${path}`, { path });
131
+ if (!stat.isFile())
132
+ throw new CliError("validation_error", `${path} is not a file`, { path });
133
+ if (stat.size > attachmentMaxBytes())
134
+ throw tooLarge(name);
135
+ const read = await readWhole(path);
136
+ const bytes = new Uint8Array(read.buffer, read.byteOffset, read.byteLength);
137
+ const extension = extname(name).toLowerCase();
138
+ const mime = MIMES[extension] ?? null;
139
+ const base = {
140
+ kind: "file",
141
+ url: null,
142
+ fileName: name,
143
+ mime,
144
+ bytes,
145
+ size: bytes.byteLength,
146
+ };
147
+ const byName = name.replace(/\.[^.]+$/, "") || name;
148
+ if (extension === ".vtt" || extension === ".srt") {
149
+ const { text, cut } = bounded(transcriptText(new TextDecoder().decode(bytes)), maxChars);
150
+ if (!text.trim())
151
+ throw noText(name);
152
+ return { ...base, text, read: "extracted", extractor: "transcript", truncated: cut, title: byName };
153
+ }
154
+ const found = await extractText(bytes, { kind: "file", name, mime, path }, load);
155
+ if (found.status === "needs-agent" && mime?.startsWith("image/") && image) {
156
+ const reader = image();
157
+ if ("refused" in reader)
158
+ return {
159
+ ...base,
160
+ text: "",
161
+ read: "no-text",
162
+ extractor: found.extractor ?? null,
163
+ truncated: false,
164
+ title: byName,
165
+ image: { read_by: null, reason: reader.refused },
166
+ };
167
+ const seen = await ocrImage(bytes, reader.pipeline);
168
+ if (seen.status === "extracted") {
169
+ const { text, cut } = bounded(seen.text, maxChars);
170
+ return {
171
+ ...base,
172
+ text,
173
+ read: "extracted",
174
+ extractor: seen.extractor,
175
+ truncated: cut,
176
+ title: byName,
177
+ image: { read_by: reader.by, reason: null },
178
+ };
179
+ }
180
+ return {
181
+ ...base,
182
+ text: "",
183
+ read: "no-text",
184
+ extractor: reader.pipeline.extractor,
185
+ truncated: false,
186
+ title: byName,
187
+ image: {
188
+ read_by: null,
189
+ reason: seen.status === "needs-agent"
190
+ ? "image.unsupported"
191
+ : seen.status === "unreadable" && seen.error === "empty_answer"
192
+ ? "ai.empty-answer"
193
+ : "ai.failed",
194
+ },
195
+ };
196
+ }
197
+ if (found.status === "needs-agent")
198
+ return {
199
+ ...base,
200
+ text: "",
201
+ read: "no-text",
202
+ extractor: found.extractor ?? null,
203
+ truncated: false,
204
+ title: byName,
205
+ };
206
+ if (found.status !== "extracted")
207
+ throw refusal(found, name);
208
+ const { text, cut } = bounded(found.text, maxChars);
209
+ if (!text.trim())
210
+ throw noText(name);
211
+ return {
212
+ ...base,
213
+ text,
214
+ read: "extracted",
215
+ extractor: found.extractor,
216
+ truncated: cut || found.truncated === true,
217
+ title: titleIn(found.metadata) ?? byName,
218
+ ...(found.metadata ? { metadata: found.metadata } : {}),
219
+ ...(found.sections ? { sections: found.sections } : {}),
220
+ };
221
+ };
222
+ /** The page as read from its address; only the address as given is kept, never where its redirects ended. */
223
+ export const readPage = async (address, { maxChars, fetch }) => {
224
+ const page = await fetchPage(address, fetch);
225
+ const { text, cut } = bounded(page.text, maxChars);
226
+ const mime = page.contentType?.split(";")[0]?.trim().toLowerCase() || null;
227
+ return {
228
+ kind: "page",
229
+ text,
230
+ read: page.read,
231
+ url: page.requestedUrl,
232
+ fileName: null,
233
+ mime,
234
+ size: page.bytes,
235
+ extractor: page.extractor,
236
+ truncated: cut || page.truncated,
237
+ title: titleIn(page.metadata) ?? new URL(page.requestedUrl).hostname,
238
+ ...(page.metadata ? { metadata: page.metadata } : {}),
239
+ ...(page.sections ? { sections: page.sections } : {}),
240
+ };
241
+ };
242
+ /** Enough of the text to recognise the page; the app shows a few lines of it. */
243
+ const EXCERPT_CHARS = 800;
244
+ /** What `sources preview` answers: the page as `sources add` would keep it, without the text itself. */
245
+ export const previewOf = (read) => {
246
+ const flat = read.text.replace(/\s+/g, " ").trim();
247
+ return {
248
+ url: read.url ?? null,
249
+ title: read.title,
250
+ site: read.url ? new URL(read.url).hostname : null,
251
+ description: metaText(read.metadata, "description"),
252
+ // By code point, so an emoji at the cut is never split into half a character.
253
+ excerpt: flat ? Array.from(flat).slice(0, EXCERPT_CHARS).join("") : null,
254
+ kind: read.kind,
255
+ mime: read.mime ?? null,
256
+ read: read.read,
257
+ // The store keeps the text trimmed, and sources add answers its length.
258
+ chars: read.text.trim().length,
259
+ truncated: read.truncated,
260
+ };
261
+ };
262
+ //# sourceMappingURL=read.js.map