@wirecat/files-cli 0.0.0-stage → 0.1.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 (85) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/LICENSE +204 -0
  3. package/README.md +68 -2
  4. package/contracts/wirecat.json +751 -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-GNDPV4HK.js +263 -0
  10. package/dist/bundle/files.js +21 -0
  11. package/dist/bundle/program-EN7Z757N.js +12291 -0
  12. package/dist/config.js +65 -0
  13. package/dist/entities.js +103 -0
  14. package/dist/failure.js +21 -0
  15. package/dist/identity.js +27 -0
  16. package/dist/import/audio.js +96 -0
  17. package/dist/import/command.js +156 -0
  18. package/dist/import/external-id.js +44 -0
  19. package/dist/import/files.js +206 -0
  20. package/dist/import/readers.js +80 -0
  21. package/dist/index.js +3 -0
  22. package/dist/migrate.js +192 -0
  23. package/dist/notes/about.js +55 -0
  24. package/dist/notes/bound.js +39 -0
  25. package/dist/notes/command.js +241 -0
  26. package/dist/notes/dates.js +15 -0
  27. package/dist/notes/dialects/common.js +79 -0
  28. package/dist/notes/dialects/index.js +6 -0
  29. package/dist/notes/dialects/markdown.js +51 -0
  30. package/dist/notes/dialects/obsidian.js +33 -0
  31. package/dist/notes/dialects/types.js +2 -0
  32. package/dist/notes/embed.js +97 -0
  33. package/dist/notes/export.js +76 -0
  34. package/dist/notes/files.js +81 -0
  35. package/dist/notes/folders-command.js +172 -0
  36. package/dist/notes/folders.js +88 -0
  37. package/dist/notes/import.js +234 -0
  38. package/dist/notes/internal.js +51 -0
  39. package/dist/notes/links.js +44 -0
  40. package/dist/notes/list.js +23 -0
  41. package/dist/notes/renames.js +24 -0
  42. package/dist/notes/search.js +16 -0
  43. package/dist/notes/state.js +33 -0
  44. package/dist/options.js +9 -0
  45. package/dist/output.js +4 -0
  46. package/dist/paths.js +5 -0
  47. package/dist/people/identity.js +19 -0
  48. package/dist/people/notes-map.js +58 -0
  49. package/dist/people/owner.js +14 -0
  50. package/dist/people/subject.js +19 -0
  51. package/dist/program.js +98 -0
  52. package/dist/progress.js +19 -0
  53. package/dist/reasons.js +187 -0
  54. package/dist/records/input.js +114 -0
  55. package/dist/records/receipt.js +25 -0
  56. package/dist/records/source.js +12 -0
  57. package/dist/refs.js +28 -0
  58. package/dist/run/lock.js +21 -0
  59. package/dist/save-help.js +3 -0
  60. package/dist/search.js +63 -0
  61. package/dist/sources/command.js +295 -0
  62. package/dist/sources/copy.js +32 -0
  63. package/dist/sources/mentions.js +78 -0
  64. package/dist/sources/read.js +261 -0
  65. package/dist/sources/readers/ai-model.js +74 -0
  66. package/dist/sources/readers/api.js +48 -0
  67. package/dist/sources/readers/claude-code.js +74 -0
  68. package/dist/sources/readers/codex.js +72 -0
  69. package/dist/sources/readers/index.js +10 -0
  70. package/dist/sources/readers/keys.js +31 -0
  71. package/dist/sources/readers/ollama.js +84 -0
  72. package/dist/sources/readers/process.js +49 -0
  73. package/dist/sources/readers/types.js +2 -0
  74. package/dist/sources/suggest-command.js +253 -0
  75. package/dist/sources/suggest.js +142 -0
  76. package/dist/sources/transcript.js +52 -0
  77. package/dist/store/group.js +8 -0
  78. package/dist/store/scope.js +25 -0
  79. package/dist/store/source-list.js +22 -0
  80. package/dist/sync.js +156 -0
  81. package/dist/terminal.js +16 -0
  82. package/dist/version.js +2 -0
  83. package/dist/wcat.js +4 -0
  84. package/package.json +89 -4
  85. package/skills/files-cli/SKILL.md +41 -0
@@ -0,0 +1,114 @@
1
+ import { open } from "node:fs/promises";
2
+ import { CliError } from "@wirecat/cli-base";
3
+ import { envelopeOfText, ingest, ingestLines, ingestVcard, isVcard, jsonlLines, } from "@wirecat/cli-core";
4
+ /** A vCard address book is a phone's contacts: they go under the seeded `phone` provider, one account per device. */
5
+ const PHONE = "phone";
6
+ const BOM = /^\uFEFF/;
7
+ const errnoOf = (error) => typeof error === "object" && error !== null && "code" in error ? String(error.code) : undefined;
8
+ /** A file opened now, so a missing one fails before anything is read; its errors come as answers, not as errno. */
9
+ const linesOf = async (file, stdin) => {
10
+ if (file === "-")
11
+ return jsonlLines(stdin);
12
+ try {
13
+ const handle = await open(file);
14
+ if (!(await handle.stat()).isFile()) {
15
+ await handle.close();
16
+ throw Object.assign(new Error(`${file} is a folder`), { code: "EISDIR" });
17
+ }
18
+ return jsonlLines(handle.createReadStream({ encoding: "utf8" }));
19
+ }
20
+ catch (error) {
21
+ if (errnoOf(error) === "ENOENT")
22
+ throw new CliError("not_found", `no records file ${file}: give a file that exists, or - for stdin`, {
23
+ reason: "records.file-missing",
24
+ path: file,
25
+ });
26
+ const why = errnoOf(error) === "EISDIR" ? "it is a folder" : errnoOf(error) === "EACCES" ? "no permission" : "unreadable";
27
+ throw new CliError("validation_error", `the records file ${file} cannot be read: ${why}`, {
28
+ reason: "records.file-unreadable",
29
+ path: file,
30
+ why,
31
+ });
32
+ }
33
+ };
34
+ /** A JSONL file's first line: an object holding no `records`. */
35
+ const headerOf = (line) => {
36
+ try {
37
+ const value = JSON.parse(line);
38
+ return value && typeof value === "object" && !Array.isArray(value) && !("records" in value)
39
+ ? value
40
+ : undefined;
41
+ }
42
+ catch {
43
+ return undefined;
44
+ }
45
+ };
46
+ /** `sheet:rentals` names the envelope's provider and account, as records list and link take it. */
47
+ const accountIn = (envelope, given) => {
48
+ const provider = envelope?.source?.provider;
49
+ return typeof provider === "string" && given.startsWith(`${provider}:`) ? given.slice(provider.length + 1) : given;
50
+ };
51
+ const deviceOf = (given) => {
52
+ const at = given.indexOf(":");
53
+ if (at < 0)
54
+ return given;
55
+ if (given.slice(0, at) !== PHONE)
56
+ throw new CliError("validation_error", "a vCard file holds a phone's contacts: --account phone:<device>", {
57
+ param: "--account",
58
+ });
59
+ return given.slice(at + 1);
60
+ };
61
+ /**
62
+ * Imports a records file or stdin. JSONL streams, a record at a time, so a file of any length fits in memory; a JSON
63
+ * envelope and a vCard address book are read whole, as one envelope each. A CSV sheet is a document to `files import`. `onIssue` hears every refusal as it
64
+ * happens, also those past the receipt's capped lists.
65
+ */
66
+ export const importRecords = async (store, { file, stdin, account, dryRun, onIssue, }) => {
67
+ const iterator = (await linesOf(file, stdin))[Symbol.asyncIterator]();
68
+ const before = [];
69
+ let next = await iterator.next();
70
+ while (!next.done && next.value.replace(BOM, "").trim() === "") {
71
+ before.push(next.value);
72
+ next = await iterator.next();
73
+ }
74
+ async function* rest() {
75
+ for (let line = await iterator.next(); !line.done; line = await iterator.next())
76
+ yield line.value;
77
+ }
78
+ const whole = async (first) => {
79
+ const lines = [...before, ...first];
80
+ for await (const line of rest())
81
+ lines.push(line);
82
+ return lines.join("\n");
83
+ };
84
+ if (next.done)
85
+ return ingest(store, envelopeOfText(before.join("\n")), { account, dryRun, onIssue });
86
+ const first = next.value.replace(BOM, "");
87
+ if (isVcard(first)) {
88
+ const { vcard, ...receipt } = await ingestVcard(store, await whole([first]), {
89
+ account: deviceOf(account),
90
+ provider: PHONE,
91
+ batchId: `vcard-${new Date().toISOString()}`,
92
+ dryRun,
93
+ onIssue,
94
+ });
95
+ return { ...receipt, vcard: vcard.map((one) => ({ ...one, card: one.card + 1 })) };
96
+ }
97
+ const header = headerOf(first);
98
+ if (header !== undefined) {
99
+ async function* all() {
100
+ // A refused header stops the stream at its first line; the file is closed here, not when it is collected.
101
+ try {
102
+ yield first;
103
+ yield* rest();
104
+ }
105
+ finally {
106
+ await iterator.return?.();
107
+ }
108
+ }
109
+ return ingestLines(store, all(), { account: accountIn(header, account), dryRun, onIssue });
110
+ }
111
+ const envelope = envelopeOfText(await whole([first]));
112
+ return ingest(store, envelope, { account: accountIn(envelope, account), dryRun, onIssue });
113
+ };
114
+ //# sourceMappingURL=input.js.map
@@ -0,0 +1,25 @@
1
+ /** The review kinds of what the import proposed, as `wcat review kind:` takes them: each ref's prefix. */
2
+ const kindsOf = (proposed) => [...new Set(proposed.map((ref) => ref.slice(0, ref.indexOf(":"))))];
3
+ /** The envelope's root is `/`: an empty JSON pointer would break the answer's issue shape. */
4
+ const pointerOf = (pointer) => pointer || "/";
5
+ const refusedLine = (one) => `refused ${pointerOf(one.pointer)} · ${one.message} (${one.code})`;
6
+ export const receiptText = (receipt) => [
7
+ `${receipt.dryRun ? "would import" : "imported"} ${receipt.source?.batchId ?? "nothing"}: ` +
8
+ `${receipt.created} created, ${receipt.updated} updated, ${receipt.unchanged} unchanged, ` +
9
+ `${receipt.deleted} deleted, ${receipt.refused} refused`,
10
+ ...(receipt.proposed.length
11
+ ? [
12
+ `proposed for your review (wcat review list kind:${kindsOf(receipt.proposed).join(",")}): ` +
13
+ receipt.proposed.join(" "),
14
+ ]
15
+ : []),
16
+ ...receipt.waiting.map((one) => `waiting ${one.key}: no entity yet for ${one.missing.join(", ")}`),
17
+ ...receipt.unmatched.map((one) => `unmatched ${one.key}: ${one.candidates.length ? `could be ${one.candidates.join(" or ")}` : one.reason}; ` +
18
+ "you say which with wcat records link"),
19
+ ...receipt.flagged.map((one) => `changed at the source ${one.key}: ${one.entity} kept as it was`),
20
+ ...receipt.ignored.map((one) => `kept as data only ${one.key} ${one.pointer} (${one.reason})`),
21
+ ...(receipt.vcard ?? []).map((one) => `notice card ${one.card}: ${one.message}`),
22
+ ...receipt.errors.map(refusedLine),
23
+ ...(receipt.truncated ? ["the lists stop at 1000 entries each; the counts are exact"] : []),
24
+ ].join("\n");
25
+ //# sourceMappingURL=receipt.js.map
@@ -0,0 +1,12 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ /** `sheet:rentals`: records are kept per source, so a read or a mapping names its provider and account. */
3
+ export const sourceOf = (account) => {
4
+ const [provider = "", ...rest] = (account ?? "").trim().split(":");
5
+ const name = rest.join(":");
6
+ if (!provider || !name)
7
+ throw new CliError("validation_error", "name the source as --account <provider>:<account>, such as sheet:rentals", {
8
+ param: "--account",
9
+ });
10
+ return { provider, account: name };
11
+ };
12
+ //# sourceMappingURL=source.js.map
package/dist/refs.js ADDED
@@ -0,0 +1,28 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ const BARE = /^\d+$/;
3
+ const either = (words) => words.length < 2 ? (words[0] ?? "") : `${words.slice(0, -1).join(", ")} or ${words.at(-1)}`;
4
+ /**
5
+ * An argument that takes several kinds refuses a bare number (NEED-2140 A): the same words would change meaning as
6
+ * the store grows. The refusal names only the references that exist, from one read of the store.
7
+ */
8
+ export const refuseBareNumber = async (store, text, kinds, options = {}) => {
9
+ const value = text.trim();
10
+ if (!BARE.test(value))
11
+ return;
12
+ const candidates = kinds.map((kind) => `${kind}:${value}`);
13
+ const found = await store.refs.summaries(candidates);
14
+ const existing = candidates.filter((ref) => {
15
+ const state = found.get(ref)?.state;
16
+ return state !== undefined && state !== "unavailable";
17
+ });
18
+ const guess = existing.length
19
+ ? `did you mean ${either(existing)}?`
20
+ : `no ${either(kinds.map((kind) => (kind === "msg" ? "message" : kind)))} has id ${value}`;
21
+ const path = options.path ? `; to read a file named ${value}, give its path: ./${value}` : "";
22
+ throw new CliError("validation_error", `"${value}" is a bare number; ${guess}${path}`, {
23
+ reason: "ref.bare-number",
24
+ value,
25
+ suggestion: existing[0] ?? candidates[0],
26
+ });
27
+ };
28
+ //# sourceMappingURL=refs.js.map
@@ -0,0 +1,21 @@
1
+ import { join } from "node:path";
2
+ import { CliError } from "@wirecat/cli-base";
3
+ import { releaseLock, takeLock } from "@wirecat/cli-core";
4
+ import { filesPaths } from "../paths.js";
5
+ /** Runs one sync at a time: `files sync` by hand and from the timer share this lock. */
6
+ export const withImportLock = async (env, work) => {
7
+ const lock = join(filesPaths(env).state, "import.lock");
8
+ const holder = takeLock(lock, { pid: process.pid, startedAt: new Date().toISOString() });
9
+ if (holder !== undefined)
10
+ throw new CliError("rate_limited", `another files sync is running (process ${holder.pid}); try again when it ends`, {
11
+ reason: "sync.running",
12
+ pid: holder.pid,
13
+ });
14
+ try {
15
+ return await work();
16
+ }
17
+ finally {
18
+ releaseLock(lock, process.pid);
19
+ }
20
+ };
21
+ //# sourceMappingURL=lock.js.map
@@ -0,0 +1,3 @@
1
+ export const SAVE_HELP = `Worth keeping — a decision, a promise, a preference? Record it with \`wcat facts add\` or
2
+ \`wcat memories add\`, citing the msg:, note: or meeting: reference as --evidence.`;
3
+ //# sourceMappingURL=save-help.js.map
package/dist/search.js ADDED
@@ -0,0 +1,63 @@
1
+ import { annotate } from "@wirecat/cli-base/commands";
2
+ import { LOCAL_READ, noteHitItem, searchNotesOf } from "@wirecat/cli-core";
3
+ import { InvalidArgumentError } from "commander";
4
+ import { answers, listAnswer, withStore } from "./answer.js";
5
+ import { APP } from "./app.js";
6
+ import { searchText } from "./notes/search.js";
7
+ import { positive } from "./options.js";
8
+ import { OWN_NOTES } from "./store/group.js";
9
+ const meaningMissed = (why, exact = false) => why === undefined || exact ? [] : [{ field: "found_by", why }];
10
+ const notesAnswer = (found, limit, page, args = {}) => listAnswer("search notes", {
11
+ items: found.items.map(noteHitItem),
12
+ limit,
13
+ has_more: found.hasMore && found.nextOffset !== undefined,
14
+ page,
15
+ ...(found.total ? { total: found.total } : {}),
16
+ args,
17
+ missing: meaningMissed(found.meaning_skipped, args.exact === true),
18
+ });
19
+ /** `files search notes`: the notes in the store, by words and, with the local model, by meaning. */
20
+ export const searchCommand = (program, streams, env) => {
21
+ const { print } = answers(program, streams, env);
22
+ const group = program.command("search").description("search the notes in the local store");
23
+ annotate(group.command("notes"), { effects: LOCAL_READ, output: { entity: "note", view: "hit" } })
24
+ .description("native notes by words and, with the local model, meaning")
25
+ .argument("<query...>", "words, phrases, Boolean operators and field queries")
26
+ .addHelpText("after", "\nsource:internal keeps the notes you wrote with notes add, source:file the notes from a folder — 'budget source:internal'." +
27
+ "\n--source notes:<folder id> is different: it chooses which notes accounts are read." +
28
+ "\nFields in the query or in --filter (tag:, date:) hold for every hit, found by words or by meaning; a query of" +
29
+ "\nfields alone lists the matching notes, newest first — 'budget tag:work', 'date:today'." +
30
+ "\n--json: each note's reference is ref (note: or document:).")
31
+ .option("--limit <n>", "most results, at most 100", (value) => {
32
+ const limit = positive(value);
33
+ if (limit > 100)
34
+ throw new InvalidArgumentError("at most 100");
35
+ return limit;
36
+ }, 20)
37
+ .option("--page <n>", "which page, from 1", positive, 1)
38
+ .option("--exact", "words as written; skip meaning search")
39
+ .option("--timezone <zone>", "IANA timezone for calendar date boundaries")
40
+ .option("--filter <query>", "another query every note must match")
41
+ .option("--source <accounts>", "only these notes accounts, separated by commas: notes:internal for the notes you wrote, notes:<folder id> " +
42
+ "as a hit shows it, or notes")
43
+ .action(async (words, options) => {
44
+ const text = words.join(" ");
45
+ const answer = await withStore(env, (store) => searchNotesOf(store, OWN_NOTES, text, {
46
+ limit: options.limit,
47
+ offset: (options.page - 1) * options.limit,
48
+ env,
49
+ app: APP,
50
+ ...(options.filter === undefined ? {} : { filter: options.filter }),
51
+ ...(options.source === undefined ? {} : { accounts: options.source }),
52
+ ...(options.exact ? { exact: true } : {}),
53
+ ...(options.timezone === undefined ? {} : { timezone: options.timezone }),
54
+ }));
55
+ if (answer.meaning_skipped && options.exact !== true)
56
+ streams.diagnostic(`Searched by words only: ${answer.meaning_skipped}\n`);
57
+ for (const { source, reason } of answer.skipped)
58
+ streams.diagnostic(`${source} not searched: ${reason}\n`);
59
+ const { limit, page, ...rest } = options;
60
+ print(true, notesAnswer(answer, limit, page, { query: text, ...rest }), searchText(answer, (page - 1) * limit));
61
+ });
62
+ };
63
+ //# sourceMappingURL=search.js.map
@@ -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