@wirecat/files-cli 0.1.0 → 0.3.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/dist/config.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { CliError, configFilePath, resolvePaths, saveConfigFile } from "@wirecat/cli-base";
2
- import { commandPermissions, DEFAULT_DECISION_POLICY, issueMessage, onThisComputer, readConfigFile, settingsFor, } from "@wirecat/cli-core";
2
+ import { baseContext, commandPermissions, DEFAULT_DECISION_POLICY, fromFile, issueMessage, onThisComputer, readConfigFile, settingsFor, } from "@wirecat/cli-core";
3
+ import { DOCUMENT_SCAN_SETTINGS } from "@wirecat/cli-core/documents";
3
4
  import * as v from "valibot";
4
5
  import { IDENTITY } from "./identity.js";
5
6
  import { DIALECTS } from "./notes/dialects/index.js";
@@ -32,7 +33,15 @@ export const permissions = commandPermissions();
32
33
  export const configuration = settingsFor(IDENTITY, {
33
34
  permissions,
34
35
  defaults: { notes: v.optional(NotesSchema), sources: v.optional(SourcesSchema) },
36
+ profile: DOCUMENT_SCAN_SETTINGS.profile,
37
+ settings: DOCUMENT_SCAN_SETTINGS.settings,
35
38
  });
39
+ /** `read_scans`: who reads the text of scans and pictures in the notes folders; `local` unless set. */
40
+ export const readScans = (command) => {
41
+ // files keeps no profiles: the setting is the whole program's, under `defaults`.
42
+ const { settings } = baseContext(command, (flags, options) => configuration.resolveSettings(flags, { ...options, needsProfile: false }));
43
+ return fromFile(settings, "read_scans", "local").value;
44
+ };
36
45
  export const configPath = (env = process.env) => configFilePath(resolvePaths({ appName: IDENTITY.appName, prefix: IDENTITY.envPrefix, env }).config);
37
46
  const rawConfig = (env) => {
38
47
  const read = readConfigFile(configPath(env));
package/dist/doctor.js ADDED
@@ -0,0 +1,33 @@
1
+ import { existsSync } from "node:fs";
2
+ import { loadConfig } from "./config.js";
3
+ import { noteFolders, overlapping } from "./notes/folders.js";
4
+ /** What `files doctor` reads of the notes folders, from the config and the disk only: no store is opened. */
5
+ export const notesFolderCheck = (env) => {
6
+ const configured = noteFolders(loadConfig(env).notes);
7
+ const problems = [];
8
+ for (const [index, folder] of configured.entries())
9
+ for (const other of overlapping(configured.slice(index + 1), folder.path))
10
+ problems.push({
11
+ what: `the notes folders ${folder.path} and ${other.path} overlap, so the files they share are read twice`,
12
+ fix: `files folders remove "${other.path}" (or the other one)`,
13
+ });
14
+ const folders = configured.map(({ path, id }) => ({ path, exists: existsSync(path), bound: id !== null }));
15
+ for (const folder of folders) {
16
+ if (!folder.exists)
17
+ problems.push({
18
+ what: `the notes folder ${folder.path} is missing`,
19
+ fix: "connect its disk; if it moved, files folders update <id> <new path>",
20
+ });
21
+ else if (!folder.bound)
22
+ problems.push({
23
+ what: `the notes folder ${folder.path} has no folder id`,
24
+ fix: `files folders add "${folder.path}"`,
25
+ });
26
+ }
27
+ return {
28
+ fields: { notes_folders: folders, problems },
29
+ notes: problems.map(({ what, fix }) => `${what} — ${fix}`),
30
+ failing: problems.length > 0,
31
+ };
32
+ };
33
+ //# sourceMappingURL=doctor.js.map
package/dist/entities.js CHANGED
@@ -35,6 +35,7 @@ const OWN_FIELDS = {
35
35
  "cut",
36
36
  ],
37
37
  notes_folder: ["id", "name", "path", "format", "kept_by"],
38
+ person_note_links: ["person", "name", "files"],
38
39
  source_detail: [
39
40
  "ref",
40
41
  "title",
@@ -1,11 +1,18 @@
1
1
  import { isCliError } from "@wirecat/cli-base";
2
+ import { NOTE_EXTENSIONS } from "../notes/files.js";
2
3
  import { readFile } from "../sources/read.js";
3
4
  import { readBytes, readTextFile, sha256Of, TEXT_CHARS, TEXT_EXTENSIONS, titleOfName, } from "./files.js";
4
5
  export const RECORDS_FILES = new Set([".json", ".jsonl"]);
5
- /** Read by `sources add`'s own readers; an image is never among them, so nothing is sent to a model. */
6
- const DOCUMENT_EXTENSIONS = { ".pdf": "pdf", ".docx": "docx" };
6
+ /**
7
+ * Read on this computer by the readers of a notes folder, less what `TEXT_EXTENSIONS` reads and `.xls`, which no
8
+ * reader takes; an image is never among them, so nothing is sent to a model.
9
+ */
10
+ const DOCUMENT_EXTENSIONS = Object.fromEntries(NOTE_EXTENSIONS.filter((extension) => !TEXT_EXTENSIONS[extension] && extension !== ".xls").map((extension) => [
11
+ extension,
12
+ extension.slice(1),
13
+ ]));
7
14
  const TRANSCRIPT_EXTENSIONS = { ".vtt": "vtt", ".srt": "srt" };
8
- /** A PDF or Word file through files' document readers, which run on this computer. */
15
+ /** A document, sheet or web page through files' document readers, which run on this computer. */
9
16
  const readDocument = async (file) => {
10
17
  try {
11
18
  const read = await readFile(file.path, { maxChars: TEXT_CHARS });
@@ -1,4 +1,4 @@
1
- import { resolve } from "node:path";
1
+ import { isAbsolute, relative, resolve, sep } from "node:path";
2
2
  import { CliError } from "@wirecat/cli-base";
3
3
  import { loadConfig } from "../config.js";
4
4
  import { noteFolders } from "./folders.js";
@@ -31,9 +31,11 @@ export const boundFolders = async (store, env, { only, strict = true } = {}) =>
31
31
  /** The folder a file lies in, and its path inside it. */
32
32
  export const folderOfFile = (folders, file) => {
33
33
  const at = resolve(file);
34
- const folder = folders.find((candidate) => at.startsWith(`${candidate.path}/`));
35
- if (!folder)
36
- throw new CliError("not_found", `${at} is in no configured folder of notes`, { reason: "folder.not-found" });
37
- return { folder, path: at.slice(folder.path.length + 1) };
34
+ for (const folder of folders) {
35
+ const path = relative(folder.path, at);
36
+ if (path && path !== ".." && !path.startsWith(`..${sep}`) && !isAbsolute(path))
37
+ return { folder, path: path.split(sep).join("/") };
38
+ }
39
+ throw new CliError("not_found", `${at} is in no configured folder of notes`, { reason: "folder.not-found" });
38
40
  };
39
41
  //# sourceMappingURL=bound.js.map
@@ -1,12 +1,13 @@
1
1
  import { readFileSync } from "node:fs";
2
2
  import { CliError } from "@wirecat/cli-base";
3
3
  import { annotate } from "@wirecat/cli-base/commands";
4
+ import { stepOf } from "@wirecat/cli-base/standards";
4
5
  import { contextEvidenceFingerprint, LOCAL_READ, LOCAL_WRITE, queryTerms, termField, withQuery, } from "@wirecat/cli-core";
5
6
  import { InvalidArgumentError } from "commander";
6
7
  import { answers, itemAnswer, listAnswer, withStore } from "../answer.js";
7
8
  import { isMcpRun } from "../author.js";
8
9
  import { loadConfig } from "../config.js";
9
- import { collect, positive } from "../options.js";
10
+ import { between, collect, positive } from "../options.js";
10
11
  import { importNotesMap } from "../people/notes-map.js";
11
12
  import { subjectOf } from "../people/subject.js";
12
13
  import { refuseBareNumber } from "../refs.js";
@@ -69,6 +70,22 @@ const noteOf = async (store, env, reference) => {
69
70
  });
70
71
  return found;
71
72
  };
73
+ /** The top of wcat show --max-chars, so the two read a text alike. */
74
+ const MAX_CHARS = 200_000;
75
+ const SHOW_WHOLE = {
76
+ id: "show.whole",
77
+ kind: "command",
78
+ command: "notes show",
79
+ args: [{ name: "note", required: true }],
80
+ why: "the whole text of {note}",
81
+ };
82
+ /** Counted in code points, so a cut never splits a character. */
83
+ const cutText = (text, maxChars) => {
84
+ const whole = Array.from(text);
85
+ return maxChars === undefined || whole.length <= maxChars
86
+ ? undefined
87
+ : { text: whole.slice(0, maxChars).join(""), length: whole.length };
88
+ };
72
89
  const notesCommandDefinition = (program, streams, env) => {
73
90
  const { print } = answers(program, streams, env);
74
91
  // The note's own export_path says where it was written; a file edited since is left as it is, and said so.
@@ -86,8 +103,9 @@ const notesCommandDefinition = (program, streams, env) => {
86
103
  .description("one note: its text, tags, what it links and what links it")
87
104
  .addHelpText("after", SAVE_HELP)
88
105
  .argument("<note>", "note:<id>, document:<id>, or a file in a configured folder")
106
+ .option("--max-chars <n>", `characters of the text at most, 1–${MAX_CHARS}; the whole text without it`, between(1, MAX_CHARS, "--max-chars"))
89
107
  .action(async (reference, options) => {
90
- const answer = await withNotes(async (store) => {
108
+ const whole = await withNotes(async (store) => {
91
109
  const note = await noteOf(store, env, reference);
92
110
  const ref = note.ref;
93
111
  return {
@@ -109,11 +127,20 @@ const notesCommandDefinition = (program, streams, env) => {
109
127
  fingerprint: await citedFingerprint(store, ref),
110
128
  };
111
129
  });
112
- print(options.json, itemAnswer(answer), [
130
+ const cut = cutText(whole.text, options.maxChars);
131
+ const answer = cut ? { ...whole, text: cut.text } : whole;
132
+ // The note entity has no field for a cut, so the envelope says it: missing text, and a step to the rest.
133
+ const shortened = cut && {
134
+ next: [stepOf(SHOW_WHOLE, { args: { note: answer.ref } })],
135
+ missing: [{ field: "text", why: `cut at ${options.maxChars} of ${cut.length} characters by --max-chars` }],
136
+ meta: { complete: false },
137
+ };
138
+ print(options.json, itemAnswer(answer, shortened), [
113
139
  `${answer.ref} ${answer.path ?? answer.title ?? ""}`.trimEnd(),
114
140
  ` updated ${new Date(answer.updatedAt).toISOString().slice(0, 16).replace("T", " ")}${answer.tags.length ? ` tags: ${answer.tags.join(", ")}` : ""}`,
115
141
  "",
116
142
  answer.text,
143
+ ...(cut ? [` … ${cut.length} characters in all`] : []),
117
144
  ...(answer.links.length
118
145
  ? ["", `links: ${answer.links.map(({ to, targetText }) => to ?? `${targetText} (not found)`).join(", ")}`]
119
146
  : []),
@@ -13,11 +13,17 @@ export const NOTE_EXTENSIONS = [
13
13
  ".ods",
14
14
  ".pptx",
15
15
  ".epub",
16
+ ".odp",
16
17
  ".doc",
18
+ ".rtf",
19
+ // cli-core has no reader for it: listed so the sync names it as not read instead of passing it over.
17
20
  ".xls",
18
21
  ".html",
19
22
  ".htm",
20
23
  ];
24
+ /** Pictures OCR reads, as cli-core's scan reader takes them; a picture is a note only when OCR finds text in it. */
25
+ export const PICTURE_EXTENSIONS = [".jpg", ".jpeg", ".png", ".webp"];
26
+ export const isPicturePath = (path) => PICTURE_EXTENSIONS.some((extension) => path.toLowerCase().endsWith(extension));
21
27
  const MEMO_ID = /^---\r?\n(?:[^\n]*\n)*?memo-id:[ \t]*["']?([^"'\s]+)/;
22
28
  const HEAD = 1024;
23
29
  /** The `memo-id` of a file files exported, read from the front matter at its start; `null` for any other file. */
@@ -1,5 +1,5 @@
1
1
  import { realpathSync, statSync } from "node:fs";
2
- import { dirname, join, resolve, sep } from "node:path";
2
+ import { basename, dirname, join, resolve, sep } from "node:path";
3
3
  import { CliError } from "@wirecat/cli-base";
4
4
  const entryOf = (entry) => typeof entry === "string"
5
5
  ? { id: null, path: resolve(entry), format: "obsidian" }
@@ -45,13 +45,15 @@ export const attachFolder = (config, id, path, format) => {
45
45
  return { config: withFolders(config, [...kept, folder]), folder };
46
46
  };
47
47
  export const unbindFolder = (config, path) => withFolders(config, noteFolders(config.notes).filter((folder) => folder.path !== resolve(path)));
48
- /** The folder with every link followed, or as written when it cannot be resolved. */
48
+ /** The folder with every link followed; a part that does not exist yet is kept as written under its real parent. */
49
49
  const real = (path) => {
50
+ const at = resolve(path);
50
51
  try {
51
- return realpathSync(path);
52
+ return realpathSync(at);
52
53
  }
53
54
  catch {
54
- return resolve(path);
55
+ const parent = dirname(at);
56
+ return parent === at ? at : join(real(parent), basename(at));
55
57
  }
56
58
  };
57
59
  /**
@@ -1,12 +1,13 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { existsSync, statSync } from "node:fs";
3
3
  import { basename, extname, relative, sep } from "node:path";
4
- import { CliError } from "@wirecat/cli-base";
4
+ import { CliError, isCliError } from "@wirecat/cli-base";
5
5
  import { normalizeTag } from "@wirecat/cli-core";
6
- import { attachmentMaxBytes, extractText, importEngine, readWhole } from "@wirecat/cli-core/documents";
6
+ import { attachmentMaxBytes, extractText, importEngine, readWhole, scanRetry, } from "@wirecat/cli-core/documents";
7
+ import { MIMES } from "../sources/read.js";
7
8
  import { noteFileTime } from "./dates.js";
8
9
  import { dialectOf } from "./dialects/index.js";
9
- import { matcher, NOTE_EXTENSIONS, noteFiles, readMemoId } from "./files.js";
10
+ import { isPicturePath, matcher, NOTE_EXTENSIONS, noteFiles, PICTURE_EXTENSIONS, readMemoId } from "./files.js";
10
11
  import { documentOf, fileLinks } from "./links.js";
11
12
  import { detectRenames } from "./renames.js";
12
13
  import { loadFolderState, saveFolderState } from "./state.js";
@@ -45,7 +46,7 @@ const storable = (tags) => [
45
46
  * A file gone from one path whose content appears at a new one is a move. A file files exported is not a note.
46
47
  * `ignore` keeps files out of the store, so a note stored before is dropped; `skip` only leaves them alone this run.
47
48
  */
48
- export const importNotes = async (store, folder, { ignore = [], skip = [], env = process.env, loadEngine = importEngine, onFile = () => { }, } = {}) => {
49
+ export const importNotes = async (store, folder, { ignore = [], skip = [], env = process.env, loadEngine = importEngine, scans, onFile = () => { }, } = {}) => {
49
50
  if (!existsSync(folder.path))
50
51
  throw new CliError("not_found", missingFolder(folder.path), {
51
52
  reason: "notes.folder-missing",
@@ -63,15 +64,27 @@ export const importNotes = async (store, folder, { ignore = [], skip = [], env =
63
64
  const notRead = [];
64
65
  const truncated = [];
65
66
  const unreadable = [];
67
+ /** `bytes` is null for a picture: read again when OCR needs it, so a vault of pictures is not held in memory. */
66
68
  const read = [];
67
69
  const mtimes = new Map();
68
- const notReadAs = (path, status, engine) => {
69
- const entry = { status, ...(engine === undefined ? {} : { engine }) };
70
+ const notReadAs = (path, status, engine, reason) => {
71
+ const entry = { status, ...(engine === undefined ? {} : { engine }), ...(reason === undefined ? {} : { reason }) };
70
72
  notRead.push({ path, ...entry });
71
73
  notReadNow[path] = entry;
72
74
  unreadable.push(path);
73
75
  };
74
- const files = noteFiles(folder.path, ignore, NOTE_EXTENSIONS, { skipExported: false });
76
+ const reads = scans?.extractor !== undefined;
77
+ // What this reader answers every scan PDF when it cannot read any, such as with @napi-rs/canvas missing: such a scan
78
+ // is not read again on each sync only to be told the same.
79
+ const refused = reads ? await refusal(scans, { name: "probe.pdf", mime: "application/pdf" }) : undefined;
80
+ const ocr = { read: 0, picturesWaiting: 0 };
81
+ const scanned = (id) => isPicturePath(id) || extname(id).toLowerCase() === ".pdf";
82
+ // A scan kept as not read is read again once an engine can: tesseract installed, or another engine chosen.
83
+ const retried = (id, entry) => reads &&
84
+ entry?.status === "needs-agent" &&
85
+ scanned(id) &&
86
+ (entry.reason === undefined || (entry.reason !== refused && scanRetry(scans, entry.reason)));
87
+ const files = noteFiles(folder.path, ignore, [...NOTE_EXTENSIONS, ...PICTURE_EXTENSIONS], { skipExported: false });
75
88
  onFile(0, files.length);
76
89
  for (const [index, path] of files.entries()) {
77
90
  if (index > 0)
@@ -79,7 +92,15 @@ export const importNotes = async (store, folder, { ignore = [], skip = [], env =
79
92
  const id = inside(folder.path, path);
80
93
  const previous = before?.files[id];
81
94
  const wasNotRead = before?.notRead?.[id];
82
- if (skipped(id)) {
95
+ // Without an engine a picture is only counted: thousands pasted into a vault would each be listed as not read. One
96
+ // read before is kept, so turning OCR off does not trip the guard against mass deletion.
97
+ const waiting = !reads && isPicturePath(id);
98
+ if (waiting && !stored.has(id)) {
99
+ if (scans)
100
+ ocr.picturesWaiting++;
101
+ continue;
102
+ }
103
+ if (skipped(id) || waiting) {
83
104
  held.add(id);
84
105
  if (previous !== undefined)
85
106
  after.files[id] = previous;
@@ -94,11 +115,14 @@ export const importNotes = async (store, folder, { ignore = [], skip = [], env =
94
115
  // A missing reader may have been installed since, or the file budget raised, so that file is read again; so is an
95
116
  // unstored file an older state file did not mark as not read.
96
117
  const settled = stored.has(id) ||
97
- (wasNotRead !== undefined && wasNotRead.status !== "engine-missing" && wasNotRead.status !== "too-large");
118
+ (wasNotRead !== undefined &&
119
+ wasNotRead.status !== "engine-missing" &&
120
+ wasNotRead.status !== "too-large" &&
121
+ !retried(id, wasNotRead));
98
122
  if (exported || (previous?.startsWith(stamp) && settled && !reparse(id))) {
99
123
  after.files[id] = previous;
100
124
  if (wasNotRead)
101
- notReadAs(id, wasNotRead.status, wasNotRead.engine);
125
+ notReadAs(id, wasNotRead.status, wasNotRead.engine, wasNotRead.reason);
102
126
  continue;
103
127
  }
104
128
  if (stat.size > attachmentMaxBytes()) {
@@ -114,7 +138,7 @@ export const importNotes = async (store, folder, { ignore = [], skip = [], env =
114
138
  const bytes = await readWhole(path);
115
139
  const hash = createHash("sha256").update(bytes).digest("hex");
116
140
  after.files[id] = `${stamp}${hash}`;
117
- read.push({ id, path, bytes, hash });
141
+ read.push({ id, path, bytes: isPicturePath(id) ? null : bytes, hash });
118
142
  }
119
143
  const listed = new Set([
120
144
  ...Object.keys(after.files).filter((id) => !after.files[id]?.startsWith(MEMO)),
@@ -138,7 +162,23 @@ export const importNotes = async (store, folder, { ignore = [], skip = [], env =
138
162
  onFile(files.length - read.length + index, files.length);
139
163
  if (stored.get(id)?.contentHash === hash && !reparse(id))
140
164
  continue;
141
- const extraction = await extractText(bytes, { kind: "file", name: basename(path), mime: null, path }, loadEngine);
165
+ let extraction = bytes === null
166
+ ? { status: "needs-agent" }
167
+ : await extractText(bytes, { kind: "file", name: basename(path), mime: null, path }, loadEngine);
168
+ if (extraction.status === "needs-agent" && scans && scanned(id)) {
169
+ const mime = MIMES[extname(id).toLowerCase()] ?? "application/octet-stream";
170
+ try {
171
+ const text = await scans.read(async () => bytes ?? (await readWhole(path)), { name: basename(path), mime });
172
+ extraction = { status: "extracted", text, extractor: scans.extractor ?? "ocr" };
173
+ ocr.read++;
174
+ }
175
+ catch (error) {
176
+ if (!isCliError(error) || error.code !== "validation_error")
177
+ throw error;
178
+ notReadAs(id, "needs-agent", undefined, error.message);
179
+ continue;
180
+ }
181
+ }
142
182
  if (extraction.status !== "extracted") {
143
183
  notReadAs(id, extraction.status, "engine" in extraction ? extraction.engine : undefined);
144
184
  continue;
@@ -219,6 +259,7 @@ export const importNotes = async (store, folder, { ignore = [], skip = [], env =
219
259
  // A note this run held back is still in the old format, so the next run parses it again.
220
260
  const heldBack = [...held].some((id) => reparse(id) && stored.has(id));
221
261
  saveFolderState(env, folder.id, { ...after, format: heldBack ? before?.format : folder.format });
262
+ const scansNotRead = notRead.filter(({ reason }) => reason !== undefined).length;
222
263
  return {
223
264
  folder: folder.path,
224
265
  folderId: folder.id,
@@ -229,6 +270,20 @@ export const importNotes = async (store, folder, { ignore = [], skip = [], env =
229
270
  ...(notRead.length ? { notRead } : {}),
230
271
  ...(truncated.length ? { truncated } : {}),
231
272
  ...(deletionsSkipped === undefined ? {} : { deletionsSkipped }),
273
+ ...(ocr.read + scansNotRead + ocr.picturesWaiting > 0
274
+ ? {
275
+ ocr: {
276
+ read: ocr.read,
277
+ notRead: scansNotRead,
278
+ ...(ocr.picturesWaiting ? { picturesWaiting: ocr.picturesWaiting } : {}),
279
+ ...(!reads && scans ? { unavailable: await refusal(scans, { name: "probe.png", mime: "image/png" }) } : {}),
280
+ },
281
+ }
282
+ : {}),
232
283
  };
233
284
  };
285
+ /** The reason a reader that cannot read this kind of file gives each one; it refuses before it reads a byte. */
286
+ const refusal = (scans, file) => scans
287
+ .read(async () => new Uint8Array(), file)
288
+ .then(() => "", (error) => (error instanceof Error ? error.message : String(error)));
234
289
  //# sourceMappingURL=import.js.map
@@ -1,7 +1,9 @@
1
1
  import { posix } from "node:path";
2
2
  import { isReference } from "./dialects/common.js";
3
+ import { NOTE_EXTENSIONS, PICTURE_EXTENSIONS } from "./files.js";
3
4
  const fold = (value) => value.normalize("NFC").toLocaleLowerCase("en");
4
- const stem = (path) => path.replace(/\.(md|markdown|txt|csv|tsv|pdf|docx|xlsx)$/i, "");
5
+ const STEM = new RegExp(`\\.(${[...NOTE_EXTENSIONS, ...PICTURE_EXTENSIONS].map((ext) => ext.slice(1)).join("|")})$`, "i");
6
+ const stem = (path) => path.replace(STEM, "");
5
7
  const aliasesOf = (frontMatter) => {
6
8
  const value = frontMatter?.aliases ??
7
9
  frontMatter?.alias;
package/dist/options.js CHANGED
@@ -6,4 +6,10 @@ export const positive = (value) => {
6
6
  return number;
7
7
  };
8
8
  export const collect = (value, previous = []) => [...previous, value];
9
+ export const between = (low, high, what) => (value) => {
10
+ const number = Number(value);
11
+ if (!Number.isInteger(number) || number < low || number > high)
12
+ throw new InvalidArgumentError(`${what}: a whole number, ${low} to ${high}`);
13
+ return number;
14
+ };
9
15
  //# sourceMappingURL=options.js.map
@@ -0,0 +1,92 @@
1
+ import { join } from "node:path";
2
+ import { CliError } from "@wirecat/cli-base";
3
+ import { annotate } from "@wirecat/cli-base/commands";
4
+ import { LOCAL_READ, LOCAL_WRITE } from "@wirecat/cli-core";
5
+ import { answers, itemAnswer, withStore } from "../answer.js";
6
+ import { byOption, whoRuns } from "../author.js";
7
+ import { boundFolders, folderOfFile } from "../notes/bound.js";
8
+ import { folderNotes } from "../notes/import.js";
9
+ import { identityOf } from "./identity.js";
10
+ import { importNotesMap } from "./notes-map.js";
11
+ /** Who is who is linked in messaging (`tg contacts link`); the note about a person is an `about` link. */
12
+ export const noteLinksCommand = (program, streams, env) => {
13
+ const notes = program.commands.find((command) => command.name() === "notes") ?? program.command("notes");
14
+ const links = notes.command("links").description("imported note files linked to the person behind an identity");
15
+ const { print } = answers(program, streams, env);
16
+ for (const operation of ["show", "add", "clear"]) {
17
+ const command = annotate(links.command(operation), {
18
+ effects: operation === "show" ? LOCAL_READ : LOCAL_WRITE,
19
+ output: { entity: "person_note_links" },
20
+ examples: [
21
+ {
22
+ show: "files notes links show telegram:'Kai Sample'",
23
+ add: "files notes links add telegram:'Kai Sample' /path/to/vault/People/Kai.md",
24
+ clear: "files notes links clear telegram:'Kai Sample'",
25
+ }[operation],
26
+ ],
27
+ })
28
+ .description({
29
+ show: "show the note files about a person",
30
+ add: "link an imported note file to a person",
31
+ clear: "remove the owner's note-file links for a person",
32
+ }[operation])
33
+ .argument("<identity>", "<messenger>:<name or id> of an identity of the person")
34
+ .option("--json", "print the standard JSON answer");
35
+ if (operation === "add")
36
+ command.argument("<path>", "the imported note file in a configured folder");
37
+ if (operation !== "show")
38
+ byOption(command);
39
+ command.action(async (identity, ...rest) => {
40
+ const options = command.opts();
41
+ const path = operation === "add" ? String(rest[0]) : undefined;
42
+ let by = "owner";
43
+ if (operation !== "show") {
44
+ const who = await whoRuns(command, env, {
45
+ asOwner: options.asOwner,
46
+ question: `change ${identity}'s note files as you, the owner?`,
47
+ });
48
+ // The store refuses an agent's owner link, so its run fails there rather than here.
49
+ if (who !== "owner")
50
+ by = { bot: who.bot, reason: `files notes links ${operation}` };
51
+ }
52
+ const result = await withStore(env, async (store) => {
53
+ const folders = await boundFolders(store, env, { strict: false });
54
+ await importNotesMap(store, env, folders);
55
+ const person = await store.people.personOf(await identityOf(store, identity));
56
+ if (person === undefined)
57
+ throw new CliError("not_found", `the store has no person for "${identity}"`, { reason: "person.not-found" });
58
+ const to = `person:${person.uid}`;
59
+ const files = async () => {
60
+ const found = [];
61
+ for (const link of await store.notes.links({ to })) {
62
+ if (link.kind !== "about" || link.origin !== "owner")
63
+ continue;
64
+ const note = await store.notes.resolveNote(link.from);
65
+ if (note?.source === "file" && note.deletedAt === null)
66
+ found.push({ link, note });
67
+ }
68
+ return found;
69
+ };
70
+ if (operation === "clear")
71
+ for (const { link } of await files())
72
+ await store.notes.removeLink(link.id, by);
73
+ else if (path !== undefined) {
74
+ const { folder, path: inside } = folderOfFile(folders, path);
75
+ const note = (await folderNotes(store, folder.id)).find((candidate) => candidate.path === inside);
76
+ if (!note)
77
+ throw new CliError("not_found", `${path} is not imported yet — files sync`, {
78
+ reason: "note.not-imported",
79
+ });
80
+ await store.notes.addLink({ from: note.ref, to, kind: "about", origin: "owner", by });
81
+ }
82
+ const paths = (await files()).map(({ note }) => {
83
+ const folder = folders.find((candidate) => candidate.id === note.folderId);
84
+ return folder ? join(folder.path, note.path) : note.ref;
85
+ });
86
+ return { person: to, name: person.name ?? person.uid, files: paths };
87
+ });
88
+ print(options.json, itemAnswer(result), `${result.name}: ${result.files.join(", ") || "no note"}`);
89
+ });
90
+ }
91
+ };
92
+ //# sourceMappingURL=command.js.map
package/dist/program.js CHANGED
@@ -4,12 +4,14 @@ import { appDoctorCommand, appMcpCommand, appUpdate, commandsCommand, configComm
4
4
  import { Command } from "commander";
5
5
  import { trackAnswers } from "./answer.js";
6
6
  import { configuration } from "./config.js";
7
+ import { notesFolderCheck } from "./doctor.js";
7
8
  import { declareOwnAnswers } from "./entities.js";
8
9
  import { IDENTITY, PACKAGE, SKILL } from "./identity.js";
9
10
  import { importCommand } from "./import/command.js";
10
11
  import { isInstalledCopy, migrateFromMemo } from "./migrate.js";
11
12
  import { notesCommand } from "./notes/command.js";
12
13
  import { foldersCommand } from "./notes/folders-command.js";
14
+ import { noteLinksCommand } from "./people/command.js";
13
15
  import { searchCommand } from "./search.js";
14
16
  import { sourcesCommand } from "./sources/command.js";
15
17
  import { syncCommand } from "./sync.js";
@@ -40,6 +42,7 @@ const fileCommands = (options) => {
40
42
  const keyring = options.keyring;
41
43
  const root = new Command(IDENTITY.command);
42
44
  notesCommand(root, streams, env);
45
+ noteLinksCommand(root, streams, env);
43
46
  foldersCommand(root, streams, env);
44
47
  sourcesCommand(root, streams, env, {
45
48
  ...(options.fetchPage ? { fetch: options.fetchPage } : {}),
@@ -74,7 +77,7 @@ export const definition = (options = {}) => ({
74
77
  commands: () => [
75
78
  ...fileCommands(options),
76
79
  commandsCommand(IDENTITY),
77
- appDoctorCommand(IDENTITY, configuration, { packageName: PACKAGE }),
80
+ appDoctorCommand(IDENTITY, configuration, { packageName: PACKAGE, local: notesFolderCheck }),
78
81
  skillCommand(IDENTITY, SKILL),
79
82
  mcpCommand(),
80
83
  upgradeCommand(IDENTITY, PACKAGE, (command) => ({
@@ -3,13 +3,12 @@ import { CliError } from "@wirecat/cli-base";
3
3
  import { annotate } from "@wirecat/cli-base/commands";
4
4
  import { addedSourceKeyOf, environmentOf, FETCH, LOCAL_READ, LOCAL_WRITE, REMOTE_READ, } from "@wirecat/cli-core";
5
5
  import { agentPictureReader, aiImageReader, MAX_TEXT_CHARS } from "@wirecat/cli-core/documents";
6
- import { InvalidArgumentError } from "commander";
7
6
  import { answers, itemAnswer, listAnswer, withStore } from "../answer.js";
8
7
  import { APP } from "../app.js";
9
8
  import { byOption, reasonOption, whoRuns } from "../author.js";
10
9
  import { loadConfig } from "../config.js";
11
10
  import { searchModelPresent } from "../notes/embed.js";
12
- import { collect } from "../options.js";
11
+ import { between, collect } from "../options.js";
13
12
  import { subjectOf } from "../people/subject.js";
14
13
  import { refuseBareNumber } from "../refs.js";
15
14
  import { dropCopy, keepCopy } from "./copy.js";
@@ -19,12 +18,6 @@ import { readerCommands } from "./suggest-command.js";
19
18
  const SUBJECT_HELP = "who or what it is about: person:, organization:, project:, task:, meeting:, or <messenger>:<name or id>; repeat for more";
20
19
  const TEXT_BYTES = 16_384;
21
20
  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
21
  /** The text cut at a character, so its UTF-8 form is at most `bytes`. */
29
22
  const boundedText = (text, bytes) => {
30
23
  const encoded = Buffer.from(text);
@@ -8,7 +8,7 @@ export const SOURCE_TEXT_CHARS = 200_000;
8
8
  const URL_LIKE = /^[a-z][a-z0-9+.-]*:\/\//i;
9
9
  export const isUrl = (given) => URL_LIKE.test(given);
10
10
  export const argumentKind = (given) => (given === "-" ? "text" : isUrl(given) ? "url" : "path");
11
- const MIMES = {
11
+ export const MIMES = {
12
12
  ".md": "text/markdown",
13
13
  ".markdown": "text/markdown",
14
14
  ".txt": "text/plain",
@@ -24,6 +24,7 @@ const MIMES = {
24
24
  ".xls": "application/vnd.ms-excel",
25
25
  ".odt": "application/vnd.oasis.opendocument.text",
26
26
  ".ods": "application/vnd.oasis.opendocument.spreadsheet",
27
+ ".odp": "application/vnd.oasis.opendocument.presentation",
27
28
  ".epub": "application/epub+zip",
28
29
  ".rtf": "application/rtf",
29
30
  ".vtt": "text/vtt",