@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,51 @@
1
+ import { resolve } from "node:path";
2
+ import { CliError } from "@wirecat/cli-base";
3
+ import { dialectOf } from "./dialects/index.js";
4
+ import { exportNotes } from "./export.js";
5
+ const PAGE = 500;
6
+ const MAX_TITLE = 80;
7
+ export const internalNotes = async (store) => {
8
+ const notes = [];
9
+ for (let offset = 0;; offset += PAGE) {
10
+ const page = await store.notes.notes({ source: "internal", limit: PAGE, offset });
11
+ notes.push(...page.items);
12
+ if (!page.hasMore)
13
+ return notes;
14
+ }
15
+ };
16
+ const titleOf = (note) => note.title ??
17
+ (note.text
18
+ .split("\n")
19
+ .find((line) => line.trim())
20
+ ?.trim()
21
+ .slice(0, MAX_TITLE) ||
22
+ note.id);
23
+ /** Where an export goes: the folder given, else the config's `notes.export`. */
24
+ export const exportTarget = (config, dir, format) => {
25
+ const chosen = typeof dir === "string" ? dir : config.notes?.export?.dir;
26
+ if (chosen === undefined)
27
+ throw new CliError("configuration_error", "name a folder — --output-dir <dir>, --export <dir>, or notes.export.dir in the config");
28
+ return { dir: resolve(chosen), format: format ?? config.notes?.export?.format ?? "obsidian" };
29
+ };
30
+ /**
31
+ * Writes internal notes as files, each with what it is about as links and its tags. The store keeps a note's first
32
+ * subject on the note, not among its links, so it leads the list.
33
+ */
34
+ export const exportInternal = async (store, { dir, format, notes }) => {
35
+ const exported = [];
36
+ for (const note of notes) {
37
+ const linked = (await store.notes.links({ from: note.ref })).filter((link) => link.to !== null);
38
+ const about = [...(note.subject === null ? [] : [{ to: note.subject, anchor: null }]), ...linked];
39
+ exported.push({
40
+ id: note.id,
41
+ title: titleOf(note),
42
+ text: note.text,
43
+ aliases: [],
44
+ tags: (await store.notes.noteTags(note.ref)).map(({ tag }) => tag),
45
+ links: about.map((link) => ({ target: link.to, anchor: link.anchor, label: null })),
46
+ frontMatter: {},
47
+ });
48
+ }
49
+ return exportNotes({ dir, dialect: dialectOf(format), notes: exported });
50
+ };
51
+ //# sourceMappingURL=internal.js.map
@@ -0,0 +1,46 @@
1
+ import { posix } from "node:path";
2
+ import { isReference } from "./dialects/common.js";
3
+ import { NOTE_EXTENSIONS, PICTURE_EXTENSIONS } from "./files.js";
4
+ const fold = (value) => value.normalize("NFC").toLocaleLowerCase("en");
5
+ const STEM = new RegExp(`\\.(${[...NOTE_EXTENSIONS, ...PICTURE_EXTENSIONS].map((ext) => ext.slice(1)).join("|")})$`, "i");
6
+ const stem = (path) => path.replace(STEM, "");
7
+ const aliasesOf = (frontMatter) => {
8
+ const value = frontMatter?.aliases ??
9
+ frontMatter?.alias;
10
+ if (typeof value === "string")
11
+ return [value];
12
+ return Array.isArray(value) ? value.filter((alias) => typeof alias === "string") : [];
13
+ };
14
+ export const documentOf = (note) => ({
15
+ id: note.id,
16
+ path: note.path,
17
+ aliases: aliasesOf(note.frontMatter),
18
+ });
19
+ /** The notes a written target names: by path (relative when it starts with `./` or `../`), else by file name or alias. */
20
+ export const notesNamed = (source, target, documents) => {
21
+ const normalized = stem(posix.normalize(target.replace(/\\/g, "/").replace(/^\//, "")));
22
+ const relative = stem(posix.normalize(posix.join(posix.dirname(source), normalized)));
23
+ const explicit = target.startsWith("./") || target.startsWith("../") || target.startsWith("/") || normalized.includes("/");
24
+ const preferred = target.startsWith("./") || target.startsWith("../") ? relative : normalized;
25
+ if (target === "")
26
+ return documents.filter((doc) => doc.path === source);
27
+ if (explicit)
28
+ return documents.filter((doc) => fold(stem(doc.path)) === fold(preferred));
29
+ const name = fold(stem(target));
30
+ return documents.filter((doc) => [stem(posix.basename(doc.path)), ...doc.aliases].some((known) => fold(known) === name));
31
+ };
32
+ /**
33
+ * What a file's links become in the store. A record (`person:…`, `msg:…`) is linked as written; a note
34
+ * named once is linked by id. A name no note has — or several have — stays as written, so the store can
35
+ * resolve it to a person the moment one by that name, alias or username appears.
36
+ */
37
+ export const fileLinks = (source, links, documents) => links.map(({ target, anchor }) => {
38
+ const at = anchor === null ? {} : { anchor };
39
+ if (isReference(target))
40
+ return { to: target, kind: "links-to", ...at };
41
+ const named = notesNamed(source, target, documents);
42
+ return named.length === 1
43
+ ? { to: `document:${named[0].id}`, kind: "links-to", ...at }
44
+ : { targetText: posix.basename(target.replace(/\\/g, "/")) || target, kind: "links-to", ...at };
45
+ });
46
+ //# sourceMappingURL=links.js.map
@@ -0,0 +1,23 @@
1
+ import { notesReaching } from "./about.js";
2
+ const PRIORITY = ["about", "link", "through", "name"];
3
+ export const listNotes = async (store, filter) => {
4
+ const { offset, limit } = filter;
5
+ if (filter.about === undefined) {
6
+ const { about: _, ...rest } = filter;
7
+ return store.notes.notes(rest);
8
+ }
9
+ const { about } = filter;
10
+ const byRef = new Map();
11
+ for (const { note, via, anchor, text } of await notesReaching(store, about)) {
12
+ const known = byRef.get(note.ref);
13
+ const row = !known || PRIORITY.indexOf(via) < PRIORITY.indexOf(known.via) ? { ...known, ...note, via } : known;
14
+ if (anchor !== null && !row.anchors?.includes(anchor))
15
+ row.anchors = [...(row.anchors ?? []), anchor];
16
+ if (via === "name" && text !== null)
17
+ row.linkText = text;
18
+ byRef.set(note.ref, row);
19
+ }
20
+ const all = [...byRef.values()].sort((a, b) => b.createdAt.localeCompare(a.createdAt) || b.ref.localeCompare(a.ref));
21
+ return { items: all.slice(offset, offset + limit), hasMore: all.length > offset + limit };
22
+ };
23
+ //# sourceMappingURL=list.js.map
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Files that moved between two listings: a path gone from `before` whose content hash appears at a path
3
+ * new in `after`. A hash shared by two gone or two new files names no single move, so it is left out —
4
+ * a wrong guess would hand one note's links and tags to another.
5
+ */
6
+ export const detectRenames = (before, after) => {
7
+ const byHash = (paths, hashes) => {
8
+ const grouped = new Map();
9
+ for (const path of paths) {
10
+ const hash = hashes[path];
11
+ grouped.set(hash, [...(grouped.get(hash) ?? []), path]);
12
+ }
13
+ return grouped;
14
+ };
15
+ const gone = byHash(Object.keys(before).filter((path) => !(path in after)), before);
16
+ const added = byHash(Object.keys(after).filter((path) => !(path in before)), after);
17
+ return [...gone]
18
+ .flatMap(([hash, from]) => {
19
+ const to = added.get(hash);
20
+ return from.length === 1 && to?.length === 1 ? [{ from: from[0], to: to[0] }] : [];
21
+ })
22
+ .sort((a, b) => a.from.localeCompare(b.from));
23
+ };
24
+ //# sourceMappingURL=renames.js.map
@@ -0,0 +1,16 @@
1
+ import { shownOf } from "@wirecat/cli-core";
2
+ export { searchNotes, } from "@wirecat/cli-core";
3
+ export const searchText = (result, offset = 0) => [
4
+ ...(result.items.length === 0 ? [`No note holds "${result.query}". Run files sync if notes changed.`] : []),
5
+ ...result.items.map((hit) => `${"key" in hit ? "key " : ""}${hit.path ?? hit.ref}${hit.found_by.length === 1 && hit.found_by[0] === "meaning" ? " (by meaning)" : ""}\n ${hit.excerpt}`),
6
+ ...[shownOf(result.items.length, offset, result.total)].filter((line) => line !== undefined),
7
+ ...(result.hasMore ? ["More notes match; raise --limit or ask for --page with the next number."] : []),
8
+ ...(result.linked.length === 0
9
+ ? []
10
+ : [
11
+ "",
12
+ "Linked from these notes",
13
+ ...result.linked.map(({ ref, name, notes }) => ` ${name ?? ref} ${ref ?? "(nobody by that name yet)"} (${notes})`),
14
+ ]),
15
+ ].join("\n");
16
+ //# sourceMappingURL=search.js.map
@@ -0,0 +1,33 @@
1
+ import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { filesPaths } from "../paths.js";
4
+ const empty = () => ({ files: {}, documents: {} });
5
+ const fileOf = (env, id) => join(filesPaths(env).state, "folders", `${id}.json`);
6
+ /** `undefined` before this computer's first import of the folder. */
7
+ export const loadFolderState = (env, id) => {
8
+ try {
9
+ return { ...empty(), ...JSON.parse(readFileSync(fileOf(env, id), "utf8")) };
10
+ }
11
+ catch {
12
+ return undefined;
13
+ }
14
+ };
15
+ export const saveFolderState = (env, id, state) => {
16
+ const file = fileOf(env, id);
17
+ mkdirSync(join(file, ".."), { recursive: true });
18
+ writeFileSync(`${file}.tmp`, JSON.stringify(state));
19
+ renameSync(`${file}.tmp`, file);
20
+ };
21
+ /**
22
+ * After the folder's format changed: the next import parses every text note again, so tags and links read in the old
23
+ * format are replaced. A state file that already names its format needs nothing; one without it gets the old one.
24
+ */
25
+ export const formatChanged = (env, id, previous) => {
26
+ const state = loadFolderState(env, id);
27
+ if (state?.format !== undefined)
28
+ return;
29
+ saveFolderState(env, id, { ...(state ?? empty()), format: previous });
30
+ };
31
+ /** Forgets what this computer saw of the folder, so a folder added again is read in full. */
32
+ export const dropFolderState = (env, id) => rmSync(fileOf(env, id), { force: true });
33
+ //# sourceMappingURL=state.js.map
@@ -0,0 +1,9 @@
1
+ import { InvalidArgumentError } from "commander";
2
+ export const positive = (value) => {
3
+ const number = Number(value);
4
+ if (!Number.isInteger(number) || number < 1)
5
+ throw new InvalidArgumentError("a whole number above zero");
6
+ return number;
7
+ };
8
+ export const collect = (value, previous = []) => [...previous, value];
9
+ //# sourceMappingURL=options.js.map
package/dist/output.js ADDED
@@ -0,0 +1,4 @@
1
+ import { snakeKeysKeeping } from "@wirecat/cli-core";
2
+ /** Every key snake_case, except under a note's front matter or an email's headers: the owner's or a provider's words. */
3
+ export const snakeKeys = snakeKeysKeeping(["front_matter", "metadata", "headers"]);
4
+ //# sourceMappingURL=output.js.map
package/dist/paths.js ADDED
@@ -0,0 +1,5 @@
1
+ import { resolvePaths } from "@wirecat/cli-base";
2
+ import { IDENTITY } from "./identity.js";
3
+ /** files' own config, state and cache folders, with FILES_CONFIG_DIR and the others moving them. */
4
+ export const filesPaths = (env) => resolvePaths({ appName: IDENTITY.appName, prefix: IDENTITY.envPrefix, env });
5
+ //# sourceMappingURL=paths.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
@@ -0,0 +1,19 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ import { pickPerson } from "@wirecat/cli-core";
3
+ const parsed = (reference) => {
4
+ const match = /^([a-z][a-z0-9-]*):(.+)$/.exec(reference.trim());
5
+ if (match === null)
6
+ throw new CliError("validation_error", `"${reference}" names no messenger — write it as <messenger>:<name or id>`, {
7
+ reason: "identity.no-messenger",
8
+ });
9
+ const [, provider = "", who = ""] = match;
10
+ return { provider, who };
11
+ };
12
+ /** `telegram:Ana`, `max:12345`, `email:ana@example.com` — the messenger is always named. */
13
+ export const identityOf = async (store, reference) => {
14
+ const { provider, who } = parsed(reference);
15
+ const people = await store.people.people(provider);
16
+ const exact = people.get(provider === "email" ? who.toLowerCase() : who);
17
+ return { provider, id: exact?.id ?? pickPerson(who, people).id };
18
+ };
19
+ //# sourceMappingURL=identity.js.map
@@ -0,0 +1,58 @@
1
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { loadConfigFile } from "@wirecat/cli-base";
4
+ import * as v from "valibot";
5
+ import { folderOfFile } from "../notes/bound.js";
6
+ import { folderNotes } from "../notes/import.js";
7
+ import { filesPaths } from "../paths.js";
8
+ const NotesMapSchema = v.record(v.string(), v.string());
9
+ const mapPath = (env) => join(filesPaths(env).config, "people-notes.json");
10
+ const donePath = (env) => join(filesPaths(env).state, "people-notes-imported.json");
11
+ /**
12
+ * Moves each entry of the old `people-notes.json` into the store as an `about` link, once. An entry whose
13
+ * note is not imported yet waits for a later run; the file itself is left as the owner wrote it.
14
+ */
15
+ export const importNotesMap = async (store, env, folders) => {
16
+ if (!existsSync(mapPath(env)))
17
+ return 0;
18
+ const map = loadConfigFile(mapPath(env), NotesMapSchema, () => ({}));
19
+ let done = [];
20
+ try {
21
+ done = JSON.parse(readFileSync(donePath(env), "utf8"));
22
+ }
23
+ catch { }
24
+ const pending = Object.entries(map).filter(([uid]) => !done.includes(uid));
25
+ if (pending.length === 0)
26
+ return 0;
27
+ const byFolder = new Map();
28
+ let linked = 0;
29
+ for (const [uid, file] of pending) {
30
+ let place;
31
+ try {
32
+ place = folderOfFile(folders, file);
33
+ }
34
+ catch {
35
+ continue;
36
+ }
37
+ if (!byFolder.has(place.folder.id))
38
+ byFolder.set(place.folder.id, new Map((await folderNotes(store, place.folder.id)).map((note) => [note.path, note.id])));
39
+ const id = byFolder.get(place.folder.id)?.get(place.path);
40
+ // An uid from the store before wirecat.db names nobody now: leave the entry waiting, never fail the run.
41
+ if (id === undefined || (await store.people.personByUid(uid)) === undefined)
42
+ continue;
43
+ // The map is the owner's own file from before links; moving it in decides nothing for them.
44
+ await store.notes.addLink({
45
+ from: `document:${id}`,
46
+ to: `person:${uid}`,
47
+ kind: "about",
48
+ origin: "owner",
49
+ by: "owner",
50
+ });
51
+ done.push(uid);
52
+ linked++;
53
+ }
54
+ mkdirSync(join(donePath(env), ".."), { recursive: true });
55
+ writeFileSync(donePath(env), JSON.stringify(done));
56
+ return linked;
57
+ };
58
+ //# sourceMappingURL=notes-map.js.map
@@ -0,0 +1,14 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ /**
3
+ * `person:me` as the owner's `person:<uid>`; any other reference as written. The store always holds an owner row; it is
4
+ * marked once an identity is linked to it.
5
+ */
6
+ export const withOwner = async (store, reference) => {
7
+ if (reference.trim() !== "person:me")
8
+ return reference;
9
+ const owner = await store.people.owner();
10
+ if (owner === undefined || owner.identities.length === 0)
11
+ throw new CliError("not_found", "person:me: no person is marked as you in the store; mark yours with `tg <profile> contacts link <your id> me`", { reason: "person.no-owner" });
12
+ return `person:${owner.uid}`;
13
+ };
14
+ //# sourceMappingURL=owner.js.map
@@ -0,0 +1,19 @@
1
+ import { formatReference, looksLikeReference } from "@wirecat/cli-core";
2
+ import { identityOf } from "./identity.js";
3
+ import { withOwner } from "./owner.js";
4
+ /** A typed reference as written, or `<messenger>:<name or id>` turned into the person behind it. */
5
+ export const subjectOf = async (store, text) => {
6
+ const typed = (await withOwner(store, text)).trim();
7
+ if (typed.startsWith("person:")) {
8
+ const person = await store.people.personByUid(typed.slice("person:".length));
9
+ return person === undefined ? { ref: typed } : { ref: typed, person };
10
+ }
11
+ if (looksLikeReference(typed))
12
+ return { ref: typed };
13
+ const identity = await identityOf(store, text);
14
+ const person = await store.people.personOf(identity);
15
+ return person === undefined
16
+ ? { ref: formatReference({ type: "contact", provider: identity.provider, id: identity.id }) }
17
+ : { ref: `person:${person.uid}`, person };
18
+ };
19
+ //# sourceMappingURL=subject.js.map
@@ -0,0 +1,101 @@
1
+ import { join } from "node:path";
2
+ import { processStreams, resolvePaths } from "@wirecat/cli-base";
3
+ import { appDoctorCommand, appMcpCommand, appUpdate, commandsCommand, configCommand, createProgram as createSharedProgram, outputFor, run as runShared, runsCommand, skillCommand, upgradeCommand, } from "@wirecat/cli-core";
4
+ import { Command } from "commander";
5
+ import { trackAnswers } from "./answer.js";
6
+ import { configuration } from "./config.js";
7
+ import { notesFolderCheck } from "./doctor.js";
8
+ import { declareOwnAnswers } from "./entities.js";
9
+ import { IDENTITY, PACKAGE, SKILL } from "./identity.js";
10
+ import { importCommand } from "./import/command.js";
11
+ import { isInstalledCopy, migrateFromMemo } from "./migrate.js";
12
+ import { notesCommand } from "./notes/command.js";
13
+ import { foldersCommand } from "./notes/folders-command.js";
14
+ import { noteLinksCommand } from "./people/command.js";
15
+ import { searchCommand } from "./search.js";
16
+ import { sourcesCommand } from "./sources/command.js";
17
+ import { syncCommand } from "./sync.js";
18
+ import { provideTerminal } from "./terminal.js";
19
+ const update = appUpdate({
20
+ packageName: PACKAGE,
21
+ command: IDENTITY.command,
22
+ version: IDENTITY.version,
23
+ entry: import.meta.url,
24
+ statePath: (env) => join(resolvePaths({ appName: IDENTITY.appName, prefix: IDENTITY.envPrefix, env }).state, "update-check.json"),
25
+ // biome-ignore lint/plugin/no-own-settings: the update check runs before any command exists to give baseContext
26
+ enabled: (env) => configuration.resolveSettings({}, { env, needsProfile: false }).updateCheck,
27
+ offVariables: [`${IDENTITY.envPrefix}_NO_UPDATE_CHECK`],
28
+ });
29
+ const mcpCommand = () => appMcpCommand(IDENTITY, configuration, {
30
+ name: "notes folders",
31
+ untrusted: ["note text", "document text", "transcripts", "file names"],
32
+ permissionExample: "notes.add=deny",
33
+ skill: SKILL,
34
+ });
35
+ /**
36
+ * The file commands are built for one run, with that run's streams, environment and keyring: they read them when they
37
+ * act, not from cli-core's context.
38
+ */
39
+ const fileCommands = (options) => {
40
+ const streams = options.streams ?? processStreams;
41
+ const env = options.env ?? process.env;
42
+ const keyring = options.keyring;
43
+ const root = new Command(IDENTITY.command);
44
+ notesCommand(root, streams, env);
45
+ noteLinksCommand(root, streams, env);
46
+ foldersCommand(root, streams, env);
47
+ sourcesCommand(root, streams, env, {
48
+ ...(options.fetchPage ? { fetch: options.fetchPage } : {}),
49
+ readers: { ...(options.readerFetch ? { fetch: options.readerFetch } : {}), ...(keyring ? { keyring } : {}) },
50
+ });
51
+ importCommand(root, streams, env, options.hear ? { hear: options.hear } : {});
52
+ syncCommand(root, streams, env, keyring);
53
+ searchCommand(root, streams, env);
54
+ trackAnswers(root);
55
+ declareOwnAnswers(root);
56
+ return [...root.commands];
57
+ };
58
+ export const definition = (options = {}) => ({
59
+ app: IDENTITY,
60
+ // The daily "a newer version exists" line after a command that succeeded; FILES_NO_UPDATE_CHECK turns it off.
61
+ update,
62
+ // The whole object: cli-core refuses a command by its key only when it gets the permission table too.
63
+ configuration,
64
+ firstScreen: {
65
+ pitch: "your notes folders, PDFs and transcripts in the shared local store, searchable by your agent.",
66
+ can: [
67
+ { command: "folders add <path>", does: "give a notes folder or an Obsidian vault an id" },
68
+ { command: "sync", does: "bring every notes folder up to date in the store" },
69
+ { command: 'search notes "budget"', does: "notes by words and by meaning" },
70
+ { command: "import <path> --account import:<name>", does: "a folder of PDFs, documents or recordings" },
71
+ { command: "sources add <file or url>", does: "one file, web page or pasted text" },
72
+ { command: "notes add <text>", does: "a note of your own about a person or a project" },
73
+ ],
74
+ profile: false,
75
+ start: "files folders add <path>",
76
+ },
77
+ commands: () => [
78
+ ...fileCommands(options),
79
+ commandsCommand(IDENTITY),
80
+ appDoctorCommand(IDENTITY, configuration, { packageName: PACKAGE, local: notesFolderCheck }),
81
+ skillCommand(IDENTITY, SKILL),
82
+ mcpCommand(),
83
+ upgradeCommand(IDENTITY, PACKAGE, (command) => ({
84
+ ...outputFor(command),
85
+ installer: () => update.installer({}),
86
+ latest: () => update.latest({}),
87
+ install: (argv) => update.runUpdate(argv, {}),
88
+ })),
89
+ configCommand(IDENTITY, configuration),
90
+ runsCommand(IDENTITY),
91
+ ],
92
+ configure: (program) => provideTerminal(program, options.terminal),
93
+ prepare: (_program, environment) => {
94
+ if (!isInstalledCopy(process.argv[1]))
95
+ return;
96
+ migrateFromMemo(options.env ?? process.env, options.keyring ?? environment.keyring);
97
+ },
98
+ });
99
+ export const createProgram = (options) => createSharedProgram(definition(), options);
100
+ export const run = (argv, options = {}) => runShared(argv, definition(options), options);
101
+ //# sourceMappingURL=program.js.map
@@ -0,0 +1,19 @@
1
+ const EVERY_MS = 500;
2
+ /**
3
+ * cli-core's `{"event":"progress","step":…}` stderr line, with counts a window can draw a bar by. Only with --json,
4
+ * at most every half second but always the first and last, and never a note's name: these lines reach the desktop
5
+ * app's logs.
6
+ */
7
+ export const progressLine = (diagnostic, json, { step, unit, label }) => {
8
+ let last = Number.NEGATIVE_INFINITY;
9
+ return (done, total) => {
10
+ if (!json)
11
+ return;
12
+ const now = Date.now();
13
+ if (done !== total && now - last < EVERY_MS)
14
+ return;
15
+ last = now;
16
+ diagnostic(JSON.stringify({ event: "progress", step, done, total, unit, ...(label === undefined ? {} : { label }) }));
17
+ };
18
+ };
19
+ //# sourceMappingURL=progress.js.map