@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
package/dist/config.js ADDED
@@ -0,0 +1,65 @@
1
+ import { CliError, configFilePath, resolvePaths, saveConfigFile } from "@wirecat/cli-base";
2
+ import { commandPermissions, DEFAULT_DECISION_POLICY, issueMessage, onThisComputer, readConfigFile, settingsFor, } from "@wirecat/cli-core";
3
+ import * as v from "valibot";
4
+ import { IDENTITY } from "./identity.js";
5
+ import { DIALECTS } from "./notes/dialects/index.js";
6
+ const NotesSchema = v.strictObject({
7
+ /** A bare path is the form before folder ids; `files folders add` turns it into an entry. */
8
+ folders: v.array(v.union([
9
+ v.string(),
10
+ v.strictObject({
11
+ id: v.pipe(v.string(), v.minLength(1)),
12
+ path: v.pipe(v.string(), v.minLength(1)),
13
+ format: v.optional(v.picklist(DIALECTS)),
14
+ }),
15
+ ])),
16
+ ignore: v.optional(v.array(v.string())),
17
+ /** `false` keeps notes out of search by meaning: `files sync` does not embed them. */
18
+ embed: v.optional(v.boolean()),
19
+ /** Where `files notes export` and `--export` write internal notes when no folder is given. */
20
+ export: v.optional(v.strictObject({ dir: v.pipe(v.string(), v.minLength(1)), format: v.optional(v.picklist(DIALECTS)) })),
21
+ });
22
+ /** The reader `files sources suggest` sends a source's text to, and its model; only the owner picks them. */
23
+ const SourcesSchema = v.strictObject({
24
+ reader: v.optional(v.pipe(v.string(), v.minLength(1))),
25
+ model: v.optional(v.pipe(v.string(), v.minLength(1), v.maxLength(200))),
26
+ /** Where the Ollama reader is, when not on its own port: an address on this computer only. */
27
+ base_url: v.optional(v.pipe(v.string(), v.check(onThisComputer, "use an address on this computer"))),
28
+ });
29
+ const OwnSchema = v.object({ notes: v.optional(NotesSchema), sources: v.optional(SourcesSchema) });
30
+ /** Each command is checked against its own path (`notes.list`); add the keys a command checks inside itself. */
31
+ export const permissions = commandPermissions();
32
+ export const configuration = settingsFor(IDENTITY, {
33
+ permissions,
34
+ defaults: { notes: v.optional(NotesSchema), sources: v.optional(SourcesSchema) },
35
+ });
36
+ export const configPath = (env = process.env) => configFilePath(resolvePaths({ appName: IDENTITY.appName, prefix: IDENTITY.envPrefix, env }).config);
37
+ const rawConfig = (env) => {
38
+ const read = readConfigFile(configPath(env));
39
+ if ("issue" in read)
40
+ throw new CliError("configuration_error", issueMessage([read.issue], "files doctor"));
41
+ return read.raw !== null && typeof read.raw === "object" ? read.raw : {};
42
+ };
43
+ export const loadConfig = (env = process.env) => {
44
+ const { defaults = {} } = rawConfig(env);
45
+ const parsed = v.safeParse(OwnSchema, { notes: defaults.notes, sources: defaults.sources });
46
+ if (!parsed.success)
47
+ throw new CliError("configuration_error", `${configPath(env)}: ${parsed.issues.map((issue) => `${v.getDotPath(issue) ?? "defaults"} ${issue.message}`).join("; ")} — files doctor`);
48
+ return parsed.output;
49
+ };
50
+ /** Changes the notes and sources settings and keeps the rest of the file as written. */
51
+ export const updateConfig = (change, env = process.env) => {
52
+ const next = change(loadConfig(env));
53
+ const raw = rawConfig(env);
54
+ const defaults = { ...raw.defaults };
55
+ for (const key of ["notes", "sources"])
56
+ if (next[key] === undefined)
57
+ delete defaults[key];
58
+ else
59
+ defaults[key] = next[key];
60
+ saveConfigFile(configPath(env), { ...raw, defaults });
61
+ return next;
62
+ };
63
+ /** files decides no proposals, so an agent never decides one for the owner here. */
64
+ export const decisionPolicy = (_env) => DEFAULT_DECISION_POLICY;
65
+ //# sourceMappingURL=config.js.map
@@ -0,0 +1,103 @@
1
+ import { metaOf } from "@wirecat/cli-base/commands";
2
+ import { answerEntity, answerFields } from "@wirecat/cli-core";
3
+ import * as v from "valibot";
4
+ /** files' own answers, beyond cli-core's entities, as memo listed them. */
5
+ const OWN_FIELDS = {
6
+ added_source: [
7
+ "ref",
8
+ "created",
9
+ "duplicate_of",
10
+ "title",
11
+ "kind",
12
+ "mime",
13
+ "bytes",
14
+ "chars",
15
+ "truncated",
16
+ "extractor",
17
+ "read",
18
+ "url",
19
+ "kept",
20
+ "searchable",
21
+ "subjects",
22
+ ],
23
+ import_receipt: [
24
+ "dry_run",
25
+ "source",
26
+ "created",
27
+ "updated",
28
+ "unchanged",
29
+ "deleted",
30
+ "refused",
31
+ "errors",
32
+ "by",
33
+ "files",
34
+ "skipped",
35
+ "cut",
36
+ ],
37
+ notes_folder: ["id", "name", "path", "format", "kept_by"],
38
+ source_detail: [
39
+ "ref",
40
+ "title",
41
+ "added",
42
+ "kind",
43
+ "url",
44
+ "file_name",
45
+ "mime",
46
+ "bytes",
47
+ "kept",
48
+ "chars",
49
+ "text",
50
+ "text_truncated",
51
+ "created_at",
52
+ "updated_at",
53
+ "subjects",
54
+ "facts",
55
+ "memories",
56
+ "batches",
57
+ ],
58
+ source_mention: ["ref", "type", "name", "found_as"],
59
+ source_preview: ["url", "title", "site", "description", "excerpt", "kind", "mime", "read", "chars", "truncated"],
60
+ source_reader: [
61
+ "id",
62
+ "title",
63
+ "provider",
64
+ "available",
65
+ "signed_in",
66
+ "version",
67
+ "model",
68
+ "models",
69
+ "needs_model",
70
+ "leaves_computer",
71
+ "reads_files",
72
+ "chosen",
73
+ "problem",
74
+ ],
75
+ source_reader_choice: ["reader", "model", "leaves_computer", "reads_files"],
76
+ source_removal: ["ref", "removed", "copy_deleted", "facts", "memories"],
77
+ source_suggestion: [
78
+ "ref",
79
+ "reader",
80
+ "model",
81
+ "leaves_computer",
82
+ "reused",
83
+ "batch",
84
+ "fingerprint",
85
+ "status",
86
+ "owner_only",
87
+ "facts",
88
+ "dropped",
89
+ ],
90
+ };
91
+ /**
92
+ * Gives each command that answers one of files' own entities its fields, so cli-core's run() refuses a `--json=<field>`
93
+ * the answer lacks instead of printing an empty item. cli-core reads the fields from the command, not from the program.
94
+ */
95
+ export const declareOwnAnswers = (command) => {
96
+ const entity = metaOf(command).output?.entity;
97
+ const fields = entity === undefined ? undefined : OWN_FIELDS[entity];
98
+ if (entity !== undefined && fields !== undefined && answerFields(command) === undefined)
99
+ answerEntity(command, entity, v.strictObject(Object.fromEntries(fields.map((field) => [field, v.optional(v.unknown())]))));
100
+ for (const child of command.commands)
101
+ declareOwnAnswers(child);
102
+ };
103
+ //# sourceMappingURL=entities.js.map
@@ -0,0 +1,21 @@
1
+ import { CliError, errorObjectOf } from "@wirecat/cli-base";
2
+ import { failureContext, storeDamaged } from "@wirecat/cli-core";
3
+ import { CommanderError } from "commander";
4
+ import { ValiError } from "valibot";
5
+ import { APP } from "./app.js";
6
+ const context = failureContext(APP.errors ?? { reasons: [] });
7
+ const recognisable = (error) => {
8
+ if (error instanceof CommanderError)
9
+ return new CliError("validation_error", error.message.replace(/^error: /, ""), { reason: "input.invalid" });
10
+ if (error instanceof ValiError) {
11
+ const [issue] = error.issues;
12
+ const param = issue?.path?.map((item) => String(item.key)).join(".");
13
+ return new CliError("validation_error", issue?.message ?? "the input is not valid", {
14
+ reason: "input.invalid",
15
+ ...(param ? { param } : {}),
16
+ });
17
+ }
18
+ return storeDamaged(error, `${APP.command} store recover`);
19
+ };
20
+ export const errorObject = (error) => errorObjectOf(recognisable(error), context);
21
+ //# sourceMappingURL=failure.js.map
@@ -0,0 +1,27 @@
1
+ import { REASONS } from "./reasons.js";
2
+ import { VERSION } from "./version.js";
3
+ export const PACKAGE = "@wirecat/files-cli";
4
+ export const IDENTITY = {
5
+ command: "files",
6
+ appName: "files-cli",
7
+ envPrefix: "FILES",
8
+ description: "notes folders, documents and transcripts on this computer, in the shared local store",
9
+ version: VERSION,
10
+ issues: "https://github.com/WireCatLabs/files-cli/issues/new",
11
+ messenger: false,
12
+ contentLanguages: ["en", "ru", "es"],
13
+ errors: { reasons: REASONS },
14
+ };
15
+ // The bin hands this to wcatStart before the program loads, so it must not import the command tree; src/wcat.ts adds
16
+ // the permission keys for the manifest.
17
+ export const DESKTOP = {
18
+ ...IDENTITY,
19
+ docs: "https://github.com/WireCatLabs/files-cli#readme",
20
+ tagline: "Your notes, PDFs and transcripts for your agent",
21
+ syncs: "notes folders",
22
+ // The default endpoints of the readers and AI models; the owner may point either at another address.
23
+ hosts: ["api.openai.com", "api.anthropic.com", "localhost", "127.0.0.1"],
24
+ userHosts: "the web pages you add as sources, and the address you set for a reader or an AI model",
25
+ };
26
+ export const SKILL = new URL("../skills/files-cli/SKILL.md", import.meta.url);
27
+ //# sourceMappingURL=identity.js.map
@@ -0,0 +1,96 @@
1
+ import { CliError, isCliError } from "@wirecat/cli-base";
2
+ import { DEFAULT_ORDER, decodeAudio, installedBytes, isInstalled, megabytes, modelsDirectory, recognizeLocalPieces, runFfmpeg, speechModel, } from "@wirecat/cli-core";
3
+ import { idOfPath } from "./external-id.js";
4
+ import { readBytes, sha256Of, titleOfName, unreadable } from "./files.js";
5
+ export const AUDIO_EXTENSIONS = new Set([".wav", ".mp3", ".m4a", ".ogg", ".oga", ".opus", ".flac", ".aac", ".webm"]);
6
+ /** An hour of WAV at 16 kHz is about 115 MB; cli-core's decoder stops at an hour anyway. */
7
+ const AUDIO_BYTES = 2 * 1024 ** 3;
8
+ /** Parakeet first: it hears 25 languages. */
9
+ const MODEL = DEFAULT_ORDER[0] ?? "parakeet-v3";
10
+ /** The model on this computer, never a service: a model that is not downloaded is refused, never fetched. */
11
+ export const hearLocally = async (bytes, env) => {
12
+ const model = speechModel(MODEL);
13
+ const directory = modelsDirectory(env);
14
+ if (!isInstalled(model, directory))
15
+ throw new CliError("not_found", `the speech model ${MODEL} is not on this computer; a WireCat CLI that transcribes downloads it once, such as ` +
16
+ `\`tg models download ${MODEL}\` (${megabytes(installedBytes(model))})`, { reason: "model.not-downloaded", model: MODEL });
17
+ const pcm = await decodeAudio(bytes, runFfmpeg);
18
+ const pieces = await recognizeLocalPieces(MODEL, pcm, { env, directory });
19
+ return { pieces, model: MODEL, seconds: pcm.samples.length / pcm.rate };
20
+ };
21
+ const stampOf = (seconds) => {
22
+ const whole = Math.floor(seconds);
23
+ const [h, m, s] = [Math.floor(whole / 3600), Math.floor((whole % 3600) / 60), whole % 60];
24
+ const two = (n) => String(n).padStart(2, "0");
25
+ return h ? `${h}:${two(m)}:${two(s)}` : `${two(m)}:${two(s)}`;
26
+ };
27
+ /** One line per piece the voice detector cut, with where it starts, so a passage found in search can be played. */
28
+ export const timedText = (pieces) => pieces
29
+ .filter((piece) => piece.text.trim())
30
+ .map((piece) => `[${stampOf(piece.start)}] ${piece.text.trim()}`)
31
+ .join("\n");
32
+ /**
33
+ * Hears every recording before the import writes anything: a dry run holds the store for its length, and a model
34
+ * that is missing stops the import before any record is written. A recording whose bytes match the hash its
35
+ * document keeps is not heard again; its stored text is sent unchanged.
36
+ */
37
+ export const hearAll = async (store, files, { provider, account, type, transcribe, dryRun, hear, env, }) => {
38
+ const heard = new Map();
39
+ for (const file of files) {
40
+ if (!AUDIO_EXTENSIONS.has(file.extension))
41
+ continue;
42
+ if (!transcribe) {
43
+ heard.set(file.path, { refused: "a recording: add --transcribe to hear it on this computer" });
44
+ continue;
45
+ }
46
+ if (file.stat.size > AUDIO_BYTES) {
47
+ heard.set(file.path, { refused: `larger than ${AUDIO_BYTES / 1024 ** 3} GiB` });
48
+ continue;
49
+ }
50
+ const bytes = await readBytes(file.path).catch((error) => unreadable(error));
51
+ if (typeof bytes === "string") {
52
+ heard.set(file.path, { refused: bytes });
53
+ continue;
54
+ }
55
+ const sha256 = sha256Of(bytes);
56
+ const stored = await store.records.get({ provider, account, type, externalId: idOfPath(file.relative) });
57
+ const fields = stored?.deletedAt === null ? stored.fields : undefined;
58
+ const kept = fields?.metadata?.sha256;
59
+ if (fields && kept === sha256 && typeof fields.text === "string" && typeof fields.title === "string") {
60
+ heard.set(file.path, { title: fields.title, text: fields.text, metadata: fields.metadata ?? {} });
61
+ continue;
62
+ }
63
+ if (dryRun) {
64
+ heard.set(file.path, { refused: "a dry run does not transcribe; the import hears it" });
65
+ continue;
66
+ }
67
+ let result;
68
+ try {
69
+ result = await hear(bytes, env);
70
+ }
71
+ catch (error) {
72
+ // A missing model stops the whole import; one bad recording is only that recording's problem.
73
+ if (isCliError(error) && error.details.reason === "model.not-downloaded")
74
+ throw error;
75
+ heard.set(file.path, { refused: `could not be heard: ${error instanceof Error ? error.message : String(error)}` });
76
+ continue;
77
+ }
78
+ const { pieces, model, seconds } = result;
79
+ const text = timedText(pieces);
80
+ if (!text) {
81
+ heard.set(file.path, { refused: "no speech was heard in it" });
82
+ continue;
83
+ }
84
+ heard.set(file.path, {
85
+ title: titleOfName(file.relative),
86
+ text,
87
+ metadata: {
88
+ format: "audio",
89
+ sha256,
90
+ audio: { seconds: Math.round(seconds * 10) / 10, model, pieces: pieces.length },
91
+ },
92
+ });
93
+ }
94
+ return heard;
95
+ };
96
+ //# sourceMappingURL=audio.js.map
@@ -0,0 +1,156 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ import { annotate } from "@wirecat/cli-base/commands";
3
+ import { environmentOf, ingestLines, LOCAL_WRITE, providerNamed } from "@wirecat/cli-core";
4
+ import { answers, itemAnswer, withStore } from "../answer.js";
5
+ import { byOption, isMcpRun, whoRuns } from "../author.js";
6
+ import { importRecords } from "../records/input.js";
7
+ import { receiptText } from "../records/receipt.js";
8
+ import { sourceOf } from "../records/source.js";
9
+ import { hearAll, hearLocally } from "./audio.js";
10
+ import { DOCUMENT_TYPE, documentFields, documentRecord, MOST_FILES, TooMany, unreadable, walk, } from "./files.js";
11
+ import { RECORDS_FILES, readerOf } from "./readers.js";
12
+ const errnoOf = (error) => typeof error === "object" && error !== null && "code" in error ? String(error.code) : undefined;
13
+ /** The accounts an import may name: those holding records already, and every account of an import-only provider. */
14
+ const importAccounts = async (store) => {
15
+ const found = [];
16
+ for (const { provider, account } of await store.accounts.accounts()) {
17
+ const imported = providerNamed(provider)?.imported === true;
18
+ if (imported || (await store.records.list({ provider, account, limit: 1 })).items.length > 0)
19
+ found.push(`${provider}:${account}`);
20
+ }
21
+ return found;
22
+ };
23
+ const noAccount = async (env) => {
24
+ const choices = await withStore(env, importAccounts);
25
+ throw new CliError("validation_error", `name the account to import into: --account <provider>:<account>. ${choices.length ? `Accounts that hold imports: ${choices.join(", ")}.` : "No account holds imports yet."} A new one is made on first use: import:<name> for documents and notes, phone:<exchange> for call transcripts`, { param: "--account", choices });
26
+ };
27
+ /** Every file's record, one JSONL line at a time, so a large folder is never held in memory whole. */
28
+ const folderImport = async (store, { path, provider, account, dryRun, by, onIssue, transcribe, hear, env, }) => {
29
+ if (providerNamed(provider)?.imported !== true)
30
+ throw new CliError("validation_error", `files are imported only into an account of an import-only provider, which no sync owns: ${provider} is not ` +
31
+ "one. Use import:<name> for documents and notes, or phone:<exchange> for call transcripts", { param: "--account", reason: "record.provider-not-imported" });
32
+ let found;
33
+ try {
34
+ found = await walk(path);
35
+ }
36
+ catch (error) {
37
+ if (error instanceof TooMany)
38
+ throw new CliError("validation_error", `${path} holds more than ${MOST_FILES} files: import them by folder`, {
39
+ reason: "import.too-many-files",
40
+ path,
41
+ });
42
+ if (errnoOf(error) === "ENOENT")
43
+ throw new CliError("not_found", `no file or folder ${path}`, { path });
44
+ throw error;
45
+ }
46
+ const heard = await hearAll(store, found.files, {
47
+ provider,
48
+ account,
49
+ type: DOCUMENT_TYPE,
50
+ transcribe,
51
+ dryRun,
52
+ hear,
53
+ env,
54
+ });
55
+ const skipped = [...found.skipped];
56
+ const cut = [];
57
+ const fileOf = new Map();
58
+ let files = 0;
59
+ const batch = `files-import-${new Date().toISOString()}${by === "owner" ? "" : `-by-${by}`}`;
60
+ async function* lines() {
61
+ yield JSON.stringify({ schema_version: 1, source: { provider, account, batch_id: batch } });
62
+ for (const file of found.files) {
63
+ const reader = readerOf(file, heard);
64
+ if (typeof reader === "string") {
65
+ skipped.push({ path: file.relative, reason: reader });
66
+ continue;
67
+ }
68
+ const read = await reader(file).catch((error) => ({ refused: unreadable(error) }));
69
+ if ("refused" in read) {
70
+ skipped.push({ path: file.relative, reason: read.refused });
71
+ continue;
72
+ }
73
+ const { fields, cut: wasCut } = documentFields(file, read);
74
+ if (wasCut)
75
+ cut.push(file.relative);
76
+ files++;
77
+ const record = documentRecord(file, fields, DOCUMENT_TYPE);
78
+ fileOf.set(record.key, file.relative);
79
+ yield JSON.stringify(record);
80
+ }
81
+ }
82
+ const receipt = await ingestLines(store, lines(), { account, dryRun, ...(onIssue ? { onIssue } : {}) });
83
+ // A file whose text looks like a credential is refused alone; the owner sees it beside the other skipped files.
84
+ const secret = (one) => one.code === "record.secret-field" && one.key !== undefined && fileOf.has(one.key);
85
+ for (const one of receipt.errors.filter(secret)) {
86
+ skipped.push({ path: fileOf.get(one.key), reason: `${one.message} (${one.code})` });
87
+ files--;
88
+ }
89
+ return { ...receipt, errors: receipt.errors.filter((one) => !secret(one)), by, files, skipped, cut };
90
+ };
91
+ export const importText = (receipt) => [
92
+ receiptText(receipt),
93
+ `${receipt.files} ${receipt.files === 1 ? "file" : "files"} read${receipt.by === "owner" ? "" : `, recorded as ${receipt.by}`}`,
94
+ ...receipt.cut.map((path) => `only the start kept of ${path}: its text is longer than a record holds`),
95
+ ...receipt.skipped.map((one) => `skipped ${one.path}: ${one.reason}`),
96
+ ].join("\n");
97
+ export const importCommand = (program, streams, env, { hear = hearLocally } = {}) => {
98
+ const { print } = answers(program, streams, env);
99
+ byOption(annotate(program.command("import"), { effects: LOCAL_WRITE, output: { entity: "import_receipt" } })
100
+ .summary("bring a folder of documents or a records file into files' search")
101
+ .description("bring a folder of text, Markdown, PDF and Word files, .vtt or .srt transcripts and, with --transcribe, " +
102
+ "recordings, one such file, or a records file (JSON or JSONL) into the store, under the account you name. " +
103
+ "Each file is a document keyed by its path in the folder: the same folder twice changes nothing, an " +
104
+ "edited file updates its document, and a file gone from the folder is kept. Links are not followed and " +
105
+ "nothing leaves this computer; the text is kept as data, never run"))
106
+ .argument("<path>", "a folder, a .txt, .md, .pdf, .docx, .vtt, .srt or audio file, or a records file (.json, .jsonl; - for stdin)")
107
+ .option("--account <account>", "the source the files belong to: import:<name> (import:handbook), or phone:<exchange> for call transcripts; " +
108
+ "never chosen for you")
109
+ .option("--transcribe", "hear recordings (.wav, .mp3, .m4a, .ogg, .opus, .flac) with the local speech model; a recording heard " +
110
+ "before and unchanged is not heard again. Without it recordings are skipped")
111
+ .option("--dry-run", "read every file and plan the import; write nothing. Holds the store's write lock meanwhile")
112
+ .action(async (path, given, command) => {
113
+ if (isMcpRun(command, env))
114
+ throw new CliError("permission_error", "an agent over MCP hands records over with records import, not a path");
115
+ if (!given.account?.trim())
116
+ await noAccount(env);
117
+ const { provider, account } = sourceOf(given.account);
118
+ const who = await whoRuns(command, env, { asOwner: given.asOwner, question: "import these files as yours?" });
119
+ const by = who === "owner" ? "owner" : who.bot;
120
+ const dryRun = given.dryRun === true;
121
+ const onIssue = (issue) => streams.diagnostic(`refused ${issue.pointer || "/"} · ${issue.message} (${issue.code})\n`);
122
+ const lower = path.toLowerCase();
123
+ const receipt = await withStore(env, async (store) => path === "-" || [...RECORDS_FILES].some((extension) => lower.endsWith(extension))
124
+ ? {
125
+ ...(await importRecords(store, {
126
+ file: path,
127
+ stdin: environmentOf(command).stdin ?? process.stdin,
128
+ account: `${provider}:${account}`,
129
+ dryRun,
130
+ onIssue,
131
+ })),
132
+ by,
133
+ files: 1,
134
+ skipped: [],
135
+ cut: [],
136
+ }
137
+ : folderImport(store, {
138
+ path,
139
+ provider,
140
+ account,
141
+ dryRun,
142
+ by,
143
+ onIssue,
144
+ transcribe: given.transcribe === true,
145
+ hear,
146
+ env,
147
+ }));
148
+ const issues = receipt.errors.map((one) => ({
149
+ code: "validation_error",
150
+ source: one.pointer || "/",
151
+ reason: one.code,
152
+ }));
153
+ print(given.json, itemAnswer(receipt, issues.length ? { meta: { complete: false, issues } } : undefined), importText(receipt));
154
+ });
155
+ };
156
+ //# sourceMappingURL=command.js.map
@@ -0,0 +1,44 @@
1
+ import { createHash } from "node:crypto";
2
+ /**
3
+ * cli-core keys a document by `<namespace>:[A-Za-z0-9._~-]{1,200}`; this leaves room for the namespace. A longer id
4
+ * keeps its readable start and ends with `~~` and a hash of the whole path, which no escape can produce.
5
+ */
6
+ const MOST = 180;
7
+ const HASHED_HEAD = 160;
8
+ const PLAIN = /[A-Za-z0-9._-]/;
9
+ /**
10
+ * A path relative to the folder as an external id: NFC first, because macOS writes names decomposed and the same file
11
+ * would get a second id; then each UTF-8 byte outside `[A-Za-z0-9._-]` as `~XX`, `~` and `/` included, so two paths
12
+ * never share an id and the id reads back with `pathOfId`.
13
+ */
14
+ export const idOfPath = (relative) => {
15
+ const normalized = relative.split(/[\\/]/).join("/").normalize("NFC");
16
+ let id = "";
17
+ for (const char of normalized) {
18
+ if (PLAIN.test(char))
19
+ id += char;
20
+ else
21
+ for (const byte of Buffer.from(char))
22
+ id += `~${byte.toString(16).toUpperCase().padStart(2, "0")}`;
23
+ }
24
+ if (id.length <= MOST)
25
+ return id;
26
+ const head = id.slice(0, HASHED_HEAD).replace(/~[0-9A-F]?$/, "");
27
+ return `${head}~~${createHash("sha256").update(normalized).digest("hex").slice(0, 16)}`;
28
+ };
29
+ /** The path an id stands for; `undefined` for one shortened with a hash, which only the folder can answer. */
30
+ export const pathOfId = (id) => {
31
+ if (id.includes("~~"))
32
+ return undefined;
33
+ const bytes = [];
34
+ for (let at = 0; at < id.length; at++) {
35
+ if (id[at] === "~") {
36
+ bytes.push(Number.parseInt(id.slice(at + 1, at + 3), 16));
37
+ at += 2;
38
+ }
39
+ else
40
+ bytes.push(id.charCodeAt(at));
41
+ }
42
+ return Buffer.from(bytes).toString("utf8");
43
+ };
44
+ //# sourceMappingURL=external-id.js.map