@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,78 @@
1
+ const PAGE = 500;
2
+ const ORGANIZATIONS_LISTED = 500;
3
+ const escaped = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
4
+ const folded = (text) => text.normalize("NFC").toLocaleLowerCase();
5
+ /**
6
+ * The document's own mentions, read from cli-core's list of every document's mentions. The list is ordered by each
7
+ * document's time, newest first, then its id, so one document's mentions come together and the walk stops once it is
8
+ * past them, or past where they would be.
9
+ */
10
+ const mentionsOf = async (store, note) => {
11
+ const id = Number(note.id);
12
+ const at = note.modifiedAt ?? note.updatedAt;
13
+ const found = [];
14
+ for (let offset = 0;; offset += PAGE) {
15
+ const page = await store.sourceMentions.list("document", undefined, { limit: PAGE, offset }, []);
16
+ for (const mention of page.items) {
17
+ const when = mention.source.at ?? "";
18
+ if (mention.source.id === id)
19
+ found.push(mention);
20
+ else if (found.length > 0 || when < at || (when === at && mention.source.id < id))
21
+ return found;
22
+ }
23
+ if (!page.hasMore)
24
+ return found;
25
+ }
26
+ };
27
+ /**
28
+ * People and organizations files knows whose names appear in a document. People come from cli-core's mentions: a
29
+ * name it found, linked or matching known people, and an e-mail address or phone number a person owns. Organizations
30
+ * are matched by their whole name in the text, since no mention kind finds them.
31
+ */
32
+ export const namedIn = async (store, note) => {
33
+ const named = new Map();
34
+ const add = (ref, type, name, foundAs) => {
35
+ const entry = named.get(ref) ?? { ref, type, name, foundAs: [] };
36
+ if (!entry.foundAs.includes(foundAs))
37
+ entry.foundAs.push(foundAs);
38
+ named.set(ref, entry);
39
+ };
40
+ const candidates = new Map();
41
+ for (const mention of await mentionsOf(store, note)) {
42
+ if (mention.status === "dismissed")
43
+ continue;
44
+ if (mention.kind === "person-name") {
45
+ let people = mention.target?.startsWith("person:") ? [mention.target] : candidates.get(mention.value);
46
+ if (people === undefined) {
47
+ people = (await store.sourceMentions.show(mention.id, []))?.candidates ?? [];
48
+ candidates.set(mention.value, people);
49
+ }
50
+ for (const ref of people)
51
+ add(ref, "person", null, mention.written);
52
+ }
53
+ else if (mention.kind === "email" || mention.kind === "phone") {
54
+ const person = await store.people.personOf({ provider: mention.kind, id: mention.value });
55
+ if (person)
56
+ add(`person:${person.uid}`, "person", person.name, mention.written);
57
+ }
58
+ }
59
+ for (const entry of named.values())
60
+ if (entry.name === null)
61
+ entry.name = (await store.people.personByUid(entry.ref.slice("person:".length)))?.name ?? null;
62
+ const text = folded(`${note.title ?? ""}\n${note.text}`);
63
+ const organizations = await store.knowledge.organizations();
64
+ for (const organization of organizations) {
65
+ const name = organization.name.trim();
66
+ if (name.length < 3)
67
+ continue;
68
+ const at = new RegExp(`(?<![\\p{L}\\p{N}])${escaped(folded(name))}(?![\\p{L}\\p{N}])`, "u");
69
+ if (at.test(text))
70
+ add(organization.ref, "organization", organization.name, name);
71
+ }
72
+ return {
73
+ items: [...named.values()],
74
+ organizationsChecked: organizations.length,
75
+ organizationsComplete: organizations.length < ORGANIZATIONS_LISTED,
76
+ };
77
+ };
78
+ //# sourceMappingURL=mentions.js.map
@@ -0,0 +1,261 @@
1
+ import { statSync } from "node:fs";
2
+ import { basename, extname } from "node:path";
3
+ import { CliError, isCliError } from "@wirecat/cli-base";
4
+ import { attachmentMaxBytes, extractText, fetchPage, importEngine, ocrImage, readWhole, sizeText, } from "@wirecat/cli-core/documents";
5
+ import { transcriptText } from "./transcript.js";
6
+ /** What files' folder import keeps of a file's text; `--max-chars` may raise it to the store's own limit. */
7
+ export const SOURCE_TEXT_CHARS = 200_000;
8
+ const URL_LIKE = /^[a-z][a-z0-9+.-]*:\/\//i;
9
+ export const isUrl = (given) => URL_LIKE.test(given);
10
+ export const argumentKind = (given) => (given === "-" ? "text" : isUrl(given) ? "url" : "path");
11
+ const MIMES = {
12
+ ".md": "text/markdown",
13
+ ".markdown": "text/markdown",
14
+ ".txt": "text/plain",
15
+ ".csv": "text/csv",
16
+ ".tsv": "text/tab-separated-values",
17
+ ".html": "text/html",
18
+ ".htm": "text/html",
19
+ ".pdf": "application/pdf",
20
+ ".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
21
+ ".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
22
+ ".pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation",
23
+ ".doc": "application/msword",
24
+ ".xls": "application/vnd.ms-excel",
25
+ ".odt": "application/vnd.oasis.opendocument.text",
26
+ ".ods": "application/vnd.oasis.opendocument.spreadsheet",
27
+ ".epub": "application/epub+zip",
28
+ ".rtf": "application/rtf",
29
+ ".vtt": "text/vtt",
30
+ ".srt": "application/x-subrip",
31
+ ".png": "image/png",
32
+ ".jpg": "image/jpeg",
33
+ ".jpeg": "image/jpeg",
34
+ ".gif": "image/gif",
35
+ ".webp": "image/webp",
36
+ };
37
+ const NEXT = {
38
+ "source.unsupported": "save it as PDF, Word or plain text and add that file",
39
+ "source.no-text": "nothing was saved; add a file that holds text, or paste the text with files sources add -",
40
+ "source.unreadable": "open it and save it again, or as PDF or plain text, and add that file",
41
+ "source.engine-missing": "files installs its readers on first use: run the same command once this computer can reach registry.npmjs.org",
42
+ "source.too-large": "add a smaller part of it, or save only its text and add that",
43
+ "source.url-refused": "give an http or https address of a public page",
44
+ "source.url-status": "check the address in a browser; if it opens only for you, save the page as a file and add it",
45
+ "source.url-timeout": "try again later, or save the page as a file and add it",
46
+ "source.url-redirects": "open the address in a browser and add the address it ends at",
47
+ "source.url-unreachable": "check the address and the connection, or save the page as a file and add it",
48
+ "source.needs-sign-in": "add it through your signed-in Google account: drive documents add <url> --profiles <names|all> (or drive <profile> documents add <url>)",
49
+ };
50
+ /** cli-core's refusal, with the plain next step files knows for it; its code and reason stay as they were. */
51
+ export const withNextStep = (error) => {
52
+ if (!isCliError(error))
53
+ return error;
54
+ const reason = error.details.reason;
55
+ const step = typeof reason === "string" ? NEXT[reason] : undefined;
56
+ return step === undefined ? error : new CliError(error.code, `${error.message} — ${step}`, error.details);
57
+ };
58
+ const refusal = (extraction, name) => {
59
+ switch (extraction.status) {
60
+ case "unsupported":
61
+ return new CliError("validation_error", `no reader takes ${name}`, { reason: "source.unsupported" });
62
+ case "unreadable":
63
+ return new CliError("validation_error", `the ${extraction.extractor} reader could not read ${name}`, {
64
+ reason: "source.unreadable",
65
+ });
66
+ case "engine-missing":
67
+ return new CliError("configuration_error", `reading ${name} needs ${extraction.engine}, which is not installed`, {
68
+ reason: "source.engine-missing",
69
+ });
70
+ case "too-large":
71
+ return new CliError("validation_error", `${name} is larger than its reader reads`, { reason: "source.too-large" });
72
+ }
73
+ };
74
+ const tooLarge = (what) => new CliError("validation_error", `${what} is larger than ${sizeText(attachmentMaxBytes())}; configure MESSAGING_ATTACHMENT_MAX_MIB`, {
75
+ reason: "source.too-large",
76
+ });
77
+ const noText = (what) => new CliError("validation_error", `${what} holds no text to keep`, { reason: "source.no-text" });
78
+ /** Line ends as one `\n`, and at most `maxChars`: what the reader found, as the store keeps it. */
79
+ const bounded = (text, maxChars) => {
80
+ const normalized = text.replace(/\r\n?/g, "\n");
81
+ return { text: normalized.slice(0, maxChars), cut: normalized.length > maxChars };
82
+ };
83
+ const firstLine = (text) => {
84
+ const line = text.trimStart().split("\n", 1)[0]?.trim() ?? "";
85
+ return line ? line.slice(0, 120) : null;
86
+ };
87
+ /** A metadata value as one line of text: the first non-empty one when the page gave several. */
88
+ const metaText = (metadata, key) => {
89
+ const value = metadata?.[key];
90
+ const first = (Array.isArray(value) ? value : [value]).find((v) => typeof v === "string" && v.trim());
91
+ return first ? first.trim().slice(0, 500) : null;
92
+ };
93
+ const titleIn = (metadata) => metaText(metadata, "title");
94
+ const readStdin = async (stdin) => {
95
+ const max = attachmentMaxBytes();
96
+ const chunks = [];
97
+ let size = 0;
98
+ for await (const chunk of stdin) {
99
+ const bytes = typeof chunk === "string" ? Buffer.from(chunk) : Buffer.from(chunk);
100
+ size += bytes.byteLength;
101
+ if (size > max)
102
+ throw tooLarge("the text on stdin");
103
+ chunks.push(bytes);
104
+ }
105
+ return Buffer.concat(chunks).toString("utf8");
106
+ };
107
+ export const readText = async (stdin, { maxChars }) => {
108
+ const raw = await readStdin(stdin);
109
+ const { text, cut } = bounded(raw, maxChars);
110
+ if (!text.trim())
111
+ throw noText("the text on stdin");
112
+ return {
113
+ kind: "text",
114
+ text,
115
+ read: "extracted",
116
+ url: null,
117
+ fileName: null,
118
+ mime: "text/plain",
119
+ size: Buffer.byteLength(raw),
120
+ extractor: null,
121
+ truncated: cut,
122
+ title: firstLine(text),
123
+ };
124
+ };
125
+ export const readFile = async (path, { maxChars, load = importEngine, image }) => {
126
+ const stat = statSync(path, { throwIfNoEntry: false });
127
+ const name = basename(path);
128
+ if (!stat)
129
+ throw new CliError("not_found", `no file ${path}`, { path });
130
+ if (!stat.isFile())
131
+ throw new CliError("validation_error", `${path} is not a file`, { path });
132
+ if (stat.size > attachmentMaxBytes())
133
+ throw tooLarge(name);
134
+ const read = await readWhole(path);
135
+ const bytes = new Uint8Array(read.buffer, read.byteOffset, read.byteLength);
136
+ const extension = extname(name).toLowerCase();
137
+ const mime = MIMES[extension] ?? null;
138
+ const base = {
139
+ kind: "file",
140
+ url: null,
141
+ fileName: name,
142
+ mime,
143
+ bytes,
144
+ size: bytes.byteLength,
145
+ };
146
+ const byName = name.replace(/\.[^.]+$/, "") || name;
147
+ if (extension === ".vtt" || extension === ".srt") {
148
+ const { text, cut } = bounded(transcriptText(new TextDecoder().decode(bytes)), maxChars);
149
+ if (!text.trim())
150
+ throw noText(name);
151
+ return { ...base, text, read: "extracted", extractor: "transcript", truncated: cut, title: byName };
152
+ }
153
+ const found = await extractText(bytes, { kind: "file", name, mime, path }, load);
154
+ if (found.status === "needs-agent" && mime?.startsWith("image/") && image) {
155
+ const reader = image();
156
+ if ("refused" in reader)
157
+ return {
158
+ ...base,
159
+ text: "",
160
+ read: "no-text",
161
+ extractor: found.extractor ?? null,
162
+ truncated: false,
163
+ title: byName,
164
+ image: { read_by: null, reason: reader.refused },
165
+ };
166
+ const seen = await ocrImage(bytes, reader.pipeline);
167
+ if (seen.status === "extracted") {
168
+ const { text, cut } = bounded(seen.text, maxChars);
169
+ return {
170
+ ...base,
171
+ text,
172
+ read: "extracted",
173
+ extractor: seen.extractor,
174
+ truncated: cut,
175
+ title: byName,
176
+ image: { read_by: reader.by, reason: null },
177
+ };
178
+ }
179
+ return {
180
+ ...base,
181
+ text: "",
182
+ read: "no-text",
183
+ extractor: reader.pipeline.extractor,
184
+ truncated: false,
185
+ title: byName,
186
+ image: {
187
+ read_by: null,
188
+ reason: seen.status === "needs-agent"
189
+ ? "image.unsupported"
190
+ : seen.status === "unreadable" && seen.error === "empty_answer"
191
+ ? "ai.empty-answer"
192
+ : "ai.failed",
193
+ },
194
+ };
195
+ }
196
+ if (found.status === "needs-agent")
197
+ return {
198
+ ...base,
199
+ text: "",
200
+ read: "no-text",
201
+ extractor: found.extractor ?? null,
202
+ truncated: false,
203
+ title: byName,
204
+ };
205
+ if (found.status !== "extracted")
206
+ throw refusal(found, name);
207
+ const { text, cut } = bounded(found.text, maxChars);
208
+ if (!text.trim())
209
+ throw noText(name);
210
+ return {
211
+ ...base,
212
+ text,
213
+ read: "extracted",
214
+ extractor: found.extractor,
215
+ truncated: cut || found.truncated === true,
216
+ title: titleIn(found.metadata) ?? byName,
217
+ ...(found.metadata ? { metadata: found.metadata } : {}),
218
+ ...(found.sections ? { sections: found.sections } : {}),
219
+ };
220
+ };
221
+ /** The page as read from its address; only the address as given is kept, never where its redirects ended. */
222
+ export const readPage = async (address, { maxChars, fetch }) => {
223
+ const page = await fetchPage(address, fetch);
224
+ const { text, cut } = bounded(page.text, maxChars);
225
+ const mime = page.contentType?.split(";")[0]?.trim().toLowerCase() || null;
226
+ return {
227
+ kind: "page",
228
+ text,
229
+ read: page.read,
230
+ url: page.requestedUrl,
231
+ fileName: null,
232
+ mime,
233
+ size: page.bytes,
234
+ extractor: page.extractor,
235
+ truncated: cut || page.truncated,
236
+ title: titleIn(page.metadata) ?? new URL(page.requestedUrl).hostname,
237
+ ...(page.metadata ? { metadata: page.metadata } : {}),
238
+ ...(page.sections ? { sections: page.sections } : {}),
239
+ };
240
+ };
241
+ /** Enough of the text to recognise the page; the app shows a few lines of it. */
242
+ const EXCERPT_CHARS = 800;
243
+ /** What `sources preview` answers: the page as `sources add` would keep it, without the text itself. */
244
+ export const previewOf = (read) => {
245
+ const flat = read.text.replace(/\s+/g, " ").trim();
246
+ return {
247
+ url: read.url ?? null,
248
+ title: read.title,
249
+ site: read.url ? new URL(read.url).hostname : null,
250
+ description: metaText(read.metadata, "description"),
251
+ // By code point, so an emoji at the cut is never split into half a character.
252
+ excerpt: flat ? Array.from(flat).slice(0, EXCERPT_CHARS).join("") : null,
253
+ kind: read.kind,
254
+ mime: read.mime ?? null,
255
+ read: read.read,
256
+ // The store keeps the text trimmed, and sources add answers its length.
257
+ chars: read.text.trim().length,
258
+ truncated: read.truncated,
259
+ };
260
+ };
261
+ //# sourceMappingURL=read.js.map
@@ -0,0 +1,74 @@
1
+ import { CliError, isCliError } from "@wirecat/cli-base";
2
+ import { aiLeavesComputer, aiSettingPath, aiTextReader, readAiSetting } from "@wirecat/cli-core/documents";
3
+ import { APP } from "../../app.js";
4
+ const SET = "wcat models ai set";
5
+ const chosen = (context) => aiTextReader({
6
+ app: APP,
7
+ env: context.env,
8
+ fetch: context.fetch,
9
+ ...(context.keyring ? { keyring: context.keyring } : {}),
10
+ ...(context.signal ? { signal: context.signal } : {}),
11
+ });
12
+ /** A shared setting this files cannot read (a newer tool wrote it) counts as none, so the other readers still work. */
13
+ const setting = (env) => {
14
+ try {
15
+ return readAiSetting(aiSettingPath(env));
16
+ }
17
+ catch {
18
+ return undefined;
19
+ }
20
+ };
21
+ const reader = (context) => {
22
+ try {
23
+ return chosen(context);
24
+ }
25
+ catch {
26
+ return { refused: "ai.not-set" };
27
+ }
28
+ };
29
+ const problemOf = (refused) => refused === "ai.not-set" ? `no AI model is chosen: ${SET}` : `the AI model has no key: ${SET} --secret-stdin`;
30
+ /** The model the owner chose for every WireCat tool (`models ai set`), with its one key. */
31
+ export const aiModel = {
32
+ id: "ai-model",
33
+ title: "AI model",
34
+ provider: "ai-model",
35
+ leavesComputer: (env) => {
36
+ const found = setting(env);
37
+ return found === undefined || aiLeavesComputer(found);
38
+ },
39
+ modelOf: (env) => {
40
+ const found = setting(env);
41
+ return found ? `${found.provider}/${found.model}` : null;
42
+ },
43
+ readsFiles: false,
44
+ needsModel: false,
45
+ probe: async (context) => {
46
+ const found = reader(context);
47
+ const refused = "refused" in found ? found.refused : undefined;
48
+ return {
49
+ available: refused !== "ai.not-set",
50
+ signedIn: refused === undefined,
51
+ version: null,
52
+ models: "refused" in found ? null : [found.by],
53
+ problem: refused === undefined ? null : problemOf(refused),
54
+ };
55
+ },
56
+ read: async (context, { system, prompt }) => {
57
+ const found = reader(context);
58
+ if ("refused" in found)
59
+ throw found.refused === "ai.not-set"
60
+ ? new CliError("configuration_error", problemOf(found.refused), { reason: "reader.ai-not-set" })
61
+ : new CliError("authentication_error", problemOf(found.refused), { reason: "reader.no-key" });
62
+ try {
63
+ return await found.complete({ purpose: "sources", system, prompt, maxTokens: 4096 });
64
+ }
65
+ catch (error) {
66
+ if (isCliError(error) && error.code === "rate_limited")
67
+ throw new CliError("rate_limited", `${found.by} says the limit is reached; try later`, {
68
+ reason: "reader.limit",
69
+ });
70
+ throw new CliError("invalid_response", `${found.by} failed: wcat models ai check names the cause (key, model, credit or address)`, { reason: "reader.failed" });
71
+ }
72
+ },
73
+ };
74
+ //# sourceMappingURL=ai-model.js.map
@@ -0,0 +1,48 @@
1
+ import { CliError, isCliError } from "@wirecat/cli-base";
2
+ import { modelGateway } from "@wirecat/cli-core";
3
+ import { providerKeys } from "./keys.js";
4
+ /** A provider's API with the owner's own key from the keyring, through cli-core's model gateway. */
5
+ const apiReader = (provider, title) => ({
6
+ id: provider,
7
+ title,
8
+ provider,
9
+ leavesComputer: true,
10
+ readsFiles: false,
11
+ needsModel: true,
12
+ probe: async (context) => {
13
+ const kept = providerKeys(context).read(provider) !== undefined;
14
+ return {
15
+ available: true,
16
+ signedIn: kept,
17
+ version: null,
18
+ models: null,
19
+ problem: kept ? null : `no ${title} key: wcat models ai set ${provider} --secret-stdin`,
20
+ };
21
+ },
22
+ read: async (context, { system, prompt, model }) => {
23
+ const key = providerKeys(context).read(provider);
24
+ if (key === undefined)
25
+ throw new CliError("authentication_error", `no ${title} key: wcat models ai set ${provider} --secret-stdin`, {
26
+ reason: "reader.no-key",
27
+ });
28
+ const gateway = modelGateway({
29
+ resolve: () => ({ provider, model: model ?? "" }),
30
+ // The owner chose this reader for sources by name; that choice is the consent.
31
+ consent: () => true,
32
+ key: () => key,
33
+ fetch: context.fetch,
34
+ ...(context.signal ? { signal: context.signal } : {}),
35
+ });
36
+ try {
37
+ return (await gateway.complete({ purpose: "sources", system, prompt, maxTokens: 4096 })).text;
38
+ }
39
+ catch (error) {
40
+ if (isCliError(error) && error.code === "rate_limited")
41
+ throw new CliError("rate_limited", `${title} says the limit is reached; try later`, { reason: "reader.limit" });
42
+ throw new CliError("invalid_response", `${title} failed: check the key (wcat models ai set ${provider} --secret-stdin), the model and the account's credit`, { reason: "reader.failed" });
43
+ }
44
+ },
45
+ });
46
+ export const openaiReader = apiReader("openai", "OpenAI");
47
+ export const anthropicReader = apiReader("anthropic", "Anthropic");
48
+ //# sourceMappingURL=api.js.map
@@ -0,0 +1,74 @@
1
+ import { mkdtempSync, rmSync } from "node:fs";
2
+ import { tmpdir } from "node:os";
3
+ import { join } from "node:path";
4
+ import { CliError } from "@wirecat/cli-base";
5
+ import { firstLine, runProgram } from "./process.js";
6
+ /**
7
+ * The owner's own signed-in Claude Code, with every tool, MCP server, hook, slash command and saved session off,
8
+ * started in an empty folder: it only reads the text on stdin and answers.
9
+ */
10
+ export const claudeCode = {
11
+ id: "claude-code",
12
+ title: "Claude Code",
13
+ provider: "anthropic",
14
+ leavesComputer: true,
15
+ readsFiles: false,
16
+ needsModel: false,
17
+ probe: async ({ env, signal }) => {
18
+ const version = await runProgram("claude", ["--version"], { env, ...(signal ? { signal } : {}) });
19
+ if (version?.code !== 0)
20
+ return {
21
+ available: false,
22
+ signedIn: null,
23
+ version: null,
24
+ models: null,
25
+ problem: "Claude Code is not installed",
26
+ };
27
+ const status = await runProgram("claude", ["auth", "status", "--json"], { env, ...(signal ? { signal } : {}) });
28
+ let signedIn = false;
29
+ try {
30
+ signedIn = JSON.parse(status?.stdout ?? "").loggedIn === true;
31
+ }
32
+ catch { }
33
+ return {
34
+ available: true,
35
+ signedIn,
36
+ version: firstLine(version.stdout),
37
+ models: null,
38
+ problem: signedIn ? null : "Claude Code is not signed in: run claude auth login",
39
+ };
40
+ },
41
+ read: async ({ env, signal }, { system, prompt, model }) => {
42
+ const folder = mkdtempSync(join(tmpdir(), "files-reader-"));
43
+ try {
44
+ const ran = await runProgram("claude", [
45
+ "--print",
46
+ "--output-format",
47
+ "text",
48
+ "--tools",
49
+ "",
50
+ "--disallowedTools",
51
+ "mcp__*",
52
+ "--strict-mcp-config",
53
+ "--settings",
54
+ '{"disableAllHooks":true}',
55
+ "--disable-slash-commands",
56
+ "--no-session-persistence",
57
+ "--system-prompt",
58
+ system,
59
+ ...(model ? ["--model", model] : []),
60
+ ], { env, cwd: folder, stdin: prompt, ...(signal ? { signal } : {}) });
61
+ if (!ran)
62
+ throw new CliError("configuration_error", "Claude Code is not installed", { reason: "reader.unavailable" });
63
+ if (ran.code !== 0)
64
+ throw new CliError("invalid_response", `Claude Code failed: ${firstLine(ran.stderr || ran.stdout)}`, {
65
+ reason: "reader.failed",
66
+ });
67
+ return ran.stdout;
68
+ }
69
+ finally {
70
+ rmSync(folder, { recursive: true, force: true });
71
+ }
72
+ },
73
+ };
74
+ //# sourceMappingURL=claude-code.js.map
@@ -0,0 +1,72 @@
1
+ import { mkdtempSync, readFileSync, rmSync } from "node:fs";
2
+ import { tmpdir } from "node:os";
3
+ import { join } from "node:path";
4
+ import { CliError } from "@wirecat/cli-base";
5
+ import { firstLine, runProgram } from "./process.js";
6
+ /**
7
+ * The owner's own signed-in Codex CLI in a read-only sandbox and an empty folder. It is an agent that can still read
8
+ * files of this computer, which `readers` says.
9
+ */
10
+ export const codex = {
11
+ id: "codex",
12
+ title: "Codex CLI",
13
+ provider: "openai",
14
+ leavesComputer: true,
15
+ readsFiles: true,
16
+ needsModel: false,
17
+ probe: async ({ env, signal }) => {
18
+ const version = await runProgram("codex", ["--version"], { env, ...(signal ? { signal } : {}) });
19
+ if (version?.code !== 0)
20
+ return { available: false, signedIn: null, version: null, models: null, problem: "Codex CLI is not installed" };
21
+ const status = await runProgram("codex", ["login", "status"], { env, ...(signal ? { signal } : {}) });
22
+ const signedIn = status?.code === 0;
23
+ return {
24
+ available: true,
25
+ signedIn,
26
+ version: firstLine(version.stdout),
27
+ models: null,
28
+ problem: signedIn ? null : "Codex CLI is not signed in: run codex login",
29
+ };
30
+ },
31
+ read: async ({ env, signal }, { system, prompt, model }) => {
32
+ const folder = mkdtempSync(join(tmpdir(), "files-reader-"));
33
+ const answer = join(folder, "answer.txt");
34
+ try {
35
+ const ran = await runProgram("codex", [
36
+ "exec",
37
+ "--sandbox",
38
+ "read-only",
39
+ "--skip-git-repo-check",
40
+ "--ephemeral",
41
+ "--ignore-user-config",
42
+ "--ignore-rules",
43
+ "--color",
44
+ "never",
45
+ "--cd",
46
+ folder,
47
+ "--output-last-message",
48
+ answer,
49
+ ...(model ? ["--model", model] : []),
50
+ "-",
51
+ ],
52
+ // codex exec has no system prompt of its own; the instructions lead the input.
53
+ { env, cwd: folder, stdin: `${system}\n\n${prompt}`, ...(signal ? { signal } : {}) });
54
+ if (!ran)
55
+ throw new CliError("configuration_error", "Codex CLI is not installed", { reason: "reader.unavailable" });
56
+ if (ran.code !== 0)
57
+ throw new CliError("invalid_response", `Codex CLI failed: ${firstLine(ran.stderr || ran.stdout)}`, {
58
+ reason: "reader.failed",
59
+ });
60
+ try {
61
+ return readFileSync(answer, "utf8");
62
+ }
63
+ catch {
64
+ return ran.stdout;
65
+ }
66
+ }
67
+ finally {
68
+ rmSync(folder, { recursive: true, force: true });
69
+ }
70
+ },
71
+ };
72
+ //# sourceMappingURL=codex.js.map
@@ -0,0 +1,10 @@
1
+ import { aiModel } from "./ai-model.js";
2
+ import { anthropicReader, openaiReader } from "./api.js";
3
+ import { claudeCode } from "./claude-code.js";
4
+ import { codex } from "./codex.js";
5
+ import { ollama } from "./ollama.js";
6
+ export { leavesComputer } from "./types.js";
7
+ export const READERS = [aiModel, claudeCode, codex, ollama, openaiReader, anthropicReader];
8
+ export const READER_IDS = READERS.map((reader) => reader.id);
9
+ export const readerOf = (id) => READERS.find((reader) => reader.id === id);
10
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,31 @@
1
+ import { Credentials, isMovedRun, resolvePaths } from "@wirecat/cli-base";
2
+ import { APP } from "../../app.js";
3
+ /** Providers whose API a reader calls with the owner's own key. */
4
+ export const KEY_PROVIDERS = ["openai", "anthropic"];
5
+ const ORIGIN = {
6
+ openai: "https://api.openai.com",
7
+ anthropic: "https://api.anthropic.com",
8
+ };
9
+ /**
10
+ * The owner's key for a provider, in the one entry every WireCat tool shares: service `WireCat`, account
11
+ * `ai:<origin>`, which `wcat models ai set` writes. files keeps no key of its own. cli-core 2.0.0 does not export its
12
+ * `aiKeys`, so the entry is named here the same way. No environment variable is read: a key in the environment may be
13
+ * another tool's.
14
+ */
15
+ export const providerKeys = ({ env, keyring }) => {
16
+ const shared = { appName: "WireCat", prefix: "WIRECAT", env };
17
+ const credentials = new Credentials({
18
+ configDir: resolvePaths(shared).config,
19
+ service: "WireCat",
20
+ isolated: isMovedRun(shared) || isMovedRun({ appName: APP.appName, prefix: APP.envPrefix, env }),
21
+ env,
22
+ ...(keyring ? { keyring } : {}),
23
+ warn: (message) => process.stderr.write(`${message}\n`),
24
+ });
25
+ const account = (provider) => `ai:${ORIGIN[provider]}`;
26
+ return {
27
+ read: (provider) => credentials.read(account(provider))?.secret,
28
+ write: (provider, key) => credentials.write(account(provider), key, { signIn: true }),
29
+ };
30
+ };
31
+ //# sourceMappingURL=keys.js.map