@wirecat/cli-core 0.687.0 → 0.689.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 (99) hide show
  1. package/CHANGELOG.md +96 -0
  2. package/dist/background/daily-archive-timer.d.ts +1 -1
  3. package/dist/cli/documents/index.d.ts +1 -0
  4. package/dist/cli/documents/index.js +1 -0
  5. package/dist/cli/documents/library.d.ts +107 -0
  6. package/dist/cli/documents/library.js +514 -0
  7. package/dist/cli/documents/testing/source-contract.d.ts +11 -6
  8. package/dist/cli/documents/testing/source-contract.js +54 -23
  9. package/dist/cli/documents/testing/source.d.ts +11 -3
  10. package/dist/cli/documents/testing/source.js +15 -10
  11. package/dist/cli/documents/words.d.ts +1 -1
  12. package/dist/cli/envelope.js +2 -3
  13. package/dist/cli/meeting-batch.js +5 -1
  14. package/dist/cli/meeting-passage-text.d.ts +1 -1
  15. package/dist/cli/meeting-passage-text.js +3 -5
  16. package/dist/cli/messenger/conversations-command.js +4 -0
  17. package/dist/cli/messenger/messages-search-command.js +6 -1
  18. package/dist/cli/messenger/search-answers.js +2 -0
  19. package/dist/cli/search-left-out.d.ts +3 -0
  20. package/dist/cli/search-left-out.js +12 -0
  21. package/dist/cli/store-settings.js +23 -4
  22. package/dist/cli/untrusted-marks.d.ts +2 -0
  23. package/dist/cli/untrusted-marks.js +6 -0
  24. package/dist/crm/cli/files.d.ts +68 -0
  25. package/dist/crm/cli/files.js +616 -0
  26. package/dist/crm/cli/index.d.ts +1 -0
  27. package/dist/crm/cli/index.js +3 -0
  28. package/dist/crm/cli/search-all.js +3 -2
  29. package/dist/crm/file-fetch.d.ts +15 -0
  30. package/dist/crm/file-fetch.js +61 -0
  31. package/dist/crm/index.d.ts +1 -0
  32. package/dist/crm/index.js +1 -0
  33. package/dist/crm/testing/files-contract.d.ts +17 -0
  34. package/dist/crm/testing/files-contract.js +142 -0
  35. package/dist/crm/testing/index.d.ts +1 -0
  36. package/dist/crm/testing/index.js +1 -0
  37. package/dist/crm/testing/source.d.ts +5 -0
  38. package/dist/crm/testing/source.js +3 -1
  39. package/dist/documents/index.d.ts +3 -1
  40. package/dist/documents/index.js +2 -0
  41. package/dist/documents/model.d.ts +20 -6
  42. package/dist/documents/model.js +2 -1
  43. package/dist/entities/hit.d.ts +3 -3
  44. package/dist/entities/hit.js +14 -3
  45. package/dist/entities/index.d.ts +1 -1
  46. package/dist/errors/reasons.d.ts +1 -1
  47. package/dist/errors/reasons.js +23 -1
  48. package/dist/files/safe-name.d.ts +2 -1
  49. package/dist/files/safe-name.js +21 -3
  50. package/dist/meetings/mcp/passage.d.ts +6 -2
  51. package/dist/meetings/mcp/passage.js +7 -3
  52. package/dist/resolve.d.ts +1 -1
  53. package/dist/resolve.js +1 -1
  54. package/dist/search/account-list.d.ts +2 -0
  55. package/dist/search/account-list.js +32 -4
  56. package/dist/search/respell.d.ts +10 -0
  57. package/dist/search/respell.js +63 -0
  58. package/dist/search/stem.d.ts +16 -3
  59. package/dist/search/stem.js +32 -4
  60. package/dist/services/documents/file-text.d.ts +13 -0
  61. package/dist/services/documents/file-text.js +33 -0
  62. package/dist/services/documents/plan.d.ts +3 -2
  63. package/dist/services/documents/plan.js +50 -16
  64. package/dist/services/documents/ports.d.ts +2 -2
  65. package/dist/services/documents/sync.js +2 -2
  66. package/dist/services/embeddings-search.js +169 -141
  67. package/dist/services/embeddings.d.ts +8 -0
  68. package/dist/services/message-resolution.d.ts +1 -1
  69. package/dist/services/message-resolution.js +1 -1
  70. package/dist/services/messages-archive-search.js +55 -3
  71. package/dist/services/messages-search.d.ts +2 -1
  72. package/dist/services/messages-search.js +19 -7
  73. package/dist/services/messages.d.ts +8 -0
  74. package/dist/services/metadata.d.ts +1 -1
  75. package/dist/services/named-chat.d.ts +20 -0
  76. package/dist/services/named-chat.js +63 -0
  77. package/dist/services/search-all.d.ts +7 -2
  78. package/dist/services/search-all.js +35 -1
  79. package/dist/store/exports.d.ts +1 -1
  80. package/dist/store/exports.js +1 -1
  81. package/dist/store/search-index.d.ts +2 -0
  82. package/dist/store/search-index.js +1 -0
  83. package/dist/store/sqlite/crm-files.d.ts +3 -0
  84. package/dist/store/sqlite/crm-files.js +2 -0
  85. package/dist/store/sqlite/crm-settings.d.ts +42 -1
  86. package/dist/store/sqlite/crm-settings.js +46 -2
  87. package/dist/store/sqlite/lucene-fields.d.ts +2 -0
  88. package/dist/store/sqlite/lucene-fields.js +6 -2
  89. package/dist/store/sqlite/lucene.js +2 -2
  90. package/dist/store/sqlite/manifest.js +2 -0
  91. package/dist/store/sqlite/migrations.generated.js +20 -0
  92. package/dist/store/sqlite/schema.d.ts +169 -0
  93. package/dist/store/sqlite/schema.js +18 -0
  94. package/dist/store/sqlite/stems.d.ts +2 -0
  95. package/dist/store/sqlite/stems.js +5 -0
  96. package/dist/store/sqlite/vectors.d.ts +26 -1
  97. package/dist/store/sqlite/vectors.js +72 -15
  98. package/dist/store/vectors.js +6 -2
  99. package/package.json +2 -2
@@ -0,0 +1,616 @@
1
+ import { createHash } from "node:crypto";
2
+ import { chmodSync, constants, copyFileSync, existsSync, linkSync, mkdirSync, readFileSync, renameSync, rmSync, } from "node:fs";
3
+ import { open } from "node:fs/promises";
4
+ import { join, resolve, sep } from "node:path";
5
+ import { CliError, isCliError, resolvePaths } from "@wirecat/cli-base";
6
+ import { annotate } from "@wirecat/cli-base/commands";
7
+ import * as v from "valibot";
8
+ import { extractText, importEngine, MAX_TEXT_CHARS } from "../../attachments/extract.js";
9
+ import { attachmentMaxBytes } from "../../attachments/limits.js";
10
+ import { answerEntity } from "../../cli/answer-entity.js";
11
+ import { environmentOf, outputFor, runBudgetOf } from "../../cli/context.js";
12
+ import { FETCH, REMOTE_READ } from "../../cli/effects.js";
13
+ import { itemOf, listOf } from "../../cli/envelope.js";
14
+ import { commandLevel } from "../../cli/search-left-out.js";
15
+ import { lineOf } from "../../cli/steps.js";
16
+ import { normalCrmUserId } from "../../domain/crm.js";
17
+ import { safeName } from "../../files/safe-name.js";
18
+ import { crmIdentityId } from "../../store/sqlite/crm-rows.js";
19
+ import { parseCrmFileId } from "../files.js";
20
+ import { foreignContacts, foreignContactsPathFor } from "../foreign-contacts.js";
21
+ import { integer } from "./records.js";
22
+ const MB = 1024 * 1024;
23
+ const PAGE = 500;
24
+ const DAY = 24 * 60 * 60 * 1000;
25
+ /** `files download`'s own cap, and the most `--max-size` takes: Bitrix24's own largest file. */
26
+ export const DOWNLOAD_MB = 100;
27
+ export const MOST_DOWNLOAD_MB = 2048;
28
+ /** The text `files download` answers; the store keeps it all. */
29
+ const SHOWN_TEXT = 4000;
30
+ /** Where `files sync` is in its round, a sync state `config` never sets. */
31
+ export const FILES_ROUND = "crm:files-round";
32
+ export const FILES_DOWNLOAD_KEY = "files.download";
33
+ const SKIP_REASONS = ["too-large", "run-files", "run-mb", "deadline", "disk-full", "unavailable"];
34
+ const crmFile = v.strictObject({
35
+ id: v.string(),
36
+ name: v.string(),
37
+ size: v.nullable(v.number()),
38
+ mime: v.nullable(v.string()),
39
+ created_at: v.nullable(v.string()),
40
+ owner: v.strictObject({ kind: v.string(), id: v.string() }),
41
+ source: v.string(),
42
+ downloaded: v.boolean(),
43
+ path: v.nullable(v.string()),
44
+ untrusted: v.array(v.string()),
45
+ });
46
+ const crmFileDownload = v.strictObject({
47
+ ...crmFile.entries,
48
+ text_status: v.string(),
49
+ text: v.nullable(v.string()),
50
+ text_truncated: v.boolean(),
51
+ });
52
+ const crmFilesSync = v.strictObject({
53
+ owners: v.number(),
54
+ downloaded: v.array(v.strictObject({ id: v.string(), name: v.string(), size: v.number(), path: v.string(), text_status: v.string() })),
55
+ skipped: v.array(v.strictObject({
56
+ id: v.string(),
57
+ name: v.string(),
58
+ size: v.nullable(v.number()),
59
+ reason: v.picklist(SKIP_REASONS),
60
+ step: v.string(),
61
+ })),
62
+ complete: v.boolean(),
63
+ stopped: v.optional(v.picklist(SKIP_REASONS)),
64
+ untrusted: v.array(v.string()),
65
+ });
66
+ const OWNER_FLAGS = [
67
+ ["deal", "--deal <id>"],
68
+ ["lead", "--lead <id>"],
69
+ ["person", "--person <id>"],
70
+ ["organization", "--organization <id>"],
71
+ ];
72
+ const iso = (ms) => (ms === null ? null : new Date(ms).toISOString());
73
+ const segment = (text) => text.replace(/[^\w.-]+/gu, "_");
74
+ /** The account's own folder of downloads: what the disk cap counts and drops. */
75
+ const accountFolder = (app, run) => join(resolvePaths({ appName: app.appName, prefix: app.envPrefix, env: run.env ?? process.env }).state, "crm", "files", segment(`${run.account.provider}-${run.account.account}`));
76
+ /** Each folder from `top` down to `folder` is the OS user's alone, whatever the umask or an earlier run left. */
77
+ const ownFolder = (top, folder) => {
78
+ mkdirSync(folder, { recursive: true, mode: 0o700 });
79
+ for (let at = resolve(folder); at.startsWith(resolve(top)); at = resolve(at, "..")) {
80
+ chmodSync(at, 0o700);
81
+ if (at === resolve(top))
82
+ break;
83
+ }
84
+ };
85
+ class TooLarge extends Error {
86
+ }
87
+ class Taken extends Error {
88
+ }
89
+ const errnoOf = (error) => error?.code;
90
+ /** The whole part file becomes `target` only if no file is there: a hard link, or a copy where links are refused. */
91
+ const placeNew = (part, target) => {
92
+ try {
93
+ linkSync(part, target);
94
+ }
95
+ catch (error) {
96
+ if (errnoOf(error) === "EEXIST")
97
+ throw new Taken();
98
+ try {
99
+ copyFileSync(part, target, constants.COPYFILE_EXCL);
100
+ }
101
+ catch (copying) {
102
+ if (errnoOf(copying) === "EEXIST")
103
+ throw new Taken();
104
+ throw copying;
105
+ }
106
+ }
107
+ rmSync(part, { force: true });
108
+ };
109
+ /**
110
+ * Streams into a part file beside the target and moves it there once whole; any stop leaves no part behind. With
111
+ * `exclusive`, a file that appeared at the target meanwhile is never replaced.
112
+ */
113
+ const saveStream = async (stream, target, { cap, signal, exclusive }) => {
114
+ const part = `${target}.part-${process.pid}`;
115
+ const handle = await open(part, "wx", 0o600);
116
+ const hash = createHash("sha256");
117
+ const reader = stream.getReader();
118
+ let bytes = 0;
119
+ try {
120
+ for (;;) {
121
+ if (signal?.aborted)
122
+ throw signal.reason ?? new Error("aborted");
123
+ const { done, value } = await reader.read();
124
+ if (done)
125
+ break;
126
+ bytes += value.byteLength;
127
+ if (bytes > cap)
128
+ throw new TooLarge();
129
+ hash.update(value);
130
+ await handle.write(value);
131
+ }
132
+ await handle.close();
133
+ if (exclusive)
134
+ placeNew(part, target);
135
+ else
136
+ renameSync(part, target);
137
+ chmodSync(target, 0o600);
138
+ return { bytes, sha256: hash.digest("hex") };
139
+ }
140
+ catch (error) {
141
+ await reader.cancel().catch(() => { });
142
+ await handle.close().catch(() => { });
143
+ rmSync(part, { force: true });
144
+ throw error;
145
+ }
146
+ };
147
+ const tooLarge = (id, size, capMb, flag) => new CliError("validation_error", `${id} is ${size === null ? "larger than" : `${Math.ceil(size / MB)} MB, over`} the ${capMb} MB a download takes` +
148
+ (flag ? `: --max-size raises it up to ${MOST_DOWNLOAD_MB}` : ""), { reason: "crm.file-too-large", limit: capMb, ...(size === null ? {} : { total: size }) });
149
+ /** The CRM's answer for one record; `null` from the source is `not_found`. */
150
+ const listed = async ({ run }, owner, gaps = []) => {
151
+ const source = run.source();
152
+ if (!source.files)
153
+ throw new CliError("configuration_error", "this CRM does not list its records' files");
154
+ const context = { spend: () => { }, gap: (gap) => gaps.push(gap) };
155
+ const found = await source.files(owner, context);
156
+ if (!found)
157
+ throw new CliError("not_found", `the CRM has no ${owner.kind} ${owner.id}, or this sign-in cannot see it`);
158
+ return found;
159
+ };
160
+ const quotaOf = (context) => {
161
+ const { run, app, now } = context;
162
+ return foreignContacts(run.source(), async () => {
163
+ const self = run.source().self;
164
+ return foreignContactsPathFor(app, run.account, run.env, self ? String(await self()) : undefined);
165
+ }, { now });
166
+ };
167
+ /**
168
+ * Whether `need` more bytes of the file `own` fit under the cap, its own earlier copy not counted, once the oldest
169
+ * other saved files whose text is stored are dropped; a scan is never dropped. Only with `drop` are they dropped:
170
+ * before a download it only asks, so a download that fails costs no file.
171
+ */
172
+ const roomFor = async ({ run }, folder, { need, capBytes, own, target, drop, }) => {
173
+ const files = run.store.crmFiles;
174
+ const prefix = `${folder}${sep}`;
175
+ const earlier = await files.get(run.account, own);
176
+ let total = (await files.storedBytes(run.account, prefix)) - (earlier?.localPath?.startsWith(prefix) ? (earlier.size ?? 0) : 0);
177
+ if (total + need <= capBytes)
178
+ return true;
179
+ // Never the file itself, by its id or its path: a stale row may name the path this download just wrote.
180
+ const droppable = (await files.droppable(run.account, prefix)).filter((one) => one.externalId !== own && one.localPath !== target);
181
+ // Nothing is dropped for a file that would not fit even then.
182
+ if (total - droppable.reduce((sum, one) => sum + (one.size ?? 0), 0) + need > capBytes)
183
+ return false;
184
+ if (!drop)
185
+ return true;
186
+ for (const one of droppable) {
187
+ if (one.localPath)
188
+ rmSync(one.localPath, { force: true });
189
+ await files.forgetFile(run.account, one.externalId);
190
+ total -= one.size ?? 0;
191
+ if (total + need <= capBytes)
192
+ return true;
193
+ }
194
+ return false;
195
+ };
196
+ const diskFull = (limits, folder, setting) => new CliError("validation_error", `the CRM files folder ${folder} is at its ${limits.max_total_mb} MB even after dropping every file whose text is ` +
197
+ `kept; raise ${setting} or free files there`, { reason: "crm.files-disk-full", limit: limits.max_total_mb, path: folder });
198
+ /**
199
+ * Where a file goes: its own name, or with the provider's id in front when another file holds that name, as an
200
+ * activity's and a field's contract.pdf of one record do. Under `--dir` the folder is the owner's: a file there that
201
+ * is not this one's earlier copy is never overwritten.
202
+ */
203
+ const targetOf = (folder, file, earlier, held, capped) => {
204
+ const providerId = segment(parseCrmFileId(file.id).providerId);
205
+ const name = safeName(file.name) ?? `file-${providerId}`;
206
+ // A path another row names is taken even when its file is gone: that row would drop or report this file.
207
+ const free = (path) => path === earlier || (!held.has(path) && !existsSync(path));
208
+ for (const candidate of [join(folder, name), join(folder, `${providerId}-${name}`)])
209
+ if (free(candidate))
210
+ return candidate;
211
+ if (capped)
212
+ for (let at = 2;; at += 1) {
213
+ const candidate = join(folder, `${providerId}-${at}-${name}`);
214
+ if (free(candidate))
215
+ return candidate;
216
+ }
217
+ throw new CliError("conflict", `${folder} already holds ${name} and ${providerId}-${name}: choose another --dir`, {
218
+ reason: "crm.file-exists",
219
+ path: folder,
220
+ });
221
+ };
222
+ /**
223
+ * One file saved and read: under the account's folder (folders 700, file 600) or `dir`, its text through
224
+ * `extractText`, its row stored. A cut-off or refused download keeps no part, and no error names the link.
225
+ */
226
+ export const downloadCrmFile = async (context, file, assignee, { capBytes, capMb, flag, dir, limits, }) => {
227
+ const { run, app, now, signal } = context;
228
+ if (file.size !== null && file.size > capBytes)
229
+ throw tooLarge(file.id, file.size, capMb, flag);
230
+ const top = accountFolder(app, run);
231
+ const folder = dir ? resolve(dir) : join(top, segment(`${file.owner.kind}-${file.owner.id}`));
232
+ const setting = `crm.${run.account.provider}:${run.account.account}.files.max_total_mb`;
233
+ const capped = dir === undefined;
234
+ const room = (need, target, drop) => roomFor(context, top, { need, capBytes: limits.max_total_mb * MB, own: file.id, target, drop });
235
+ if (capped && !(await room(file.size ?? 0, null, false)))
236
+ throw diskFull(limits, top, setting);
237
+ if (capped)
238
+ ownFolder(join(top, ".."), folder);
239
+ else
240
+ mkdirSync(folder, { recursive: true, mode: 0o700 });
241
+ const earlier = await run.store.crmFiles.get(run.account, file.id);
242
+ const held = new Set(await run.store.crmFiles.savedPaths(run.account));
243
+ if (earlier?.localPath)
244
+ held.delete(earlier.localPath);
245
+ const target = targetOf(folder, file, earlier?.localPath ?? null, held, capped);
246
+ // Cut off before the row is saved: nothing of this download stays, and an earlier row naming the path forgets it.
247
+ const discard = async () => {
248
+ rmSync(target, { force: true });
249
+ if (earlier?.localPath === target)
250
+ await run.store.crmFiles.forgetFile(run.account, file.id);
251
+ };
252
+ let saved;
253
+ try {
254
+ saved = await saveStream(await file.open(signal), target, {
255
+ cap: capBytes,
256
+ ...(signal ? { signal } : {}),
257
+ exclusive: !capped && target !== earlier?.localPath,
258
+ });
259
+ }
260
+ catch (error) {
261
+ if (error instanceof TooLarge)
262
+ throw tooLarge(file.id, file.size, capMb, flag);
263
+ if (error instanceof Taken)
264
+ throw new CliError("conflict", `a file appeared at the name ${file.id} was to take in ${folder}; run it again`, {
265
+ reason: "crm.file-exists",
266
+ path: folder,
267
+ });
268
+ if (signal?.aborted)
269
+ throw new CliError("timeout", `the download of ${file.id} was cut off at the time limit and nothing was kept: run it again with a longer ` +
270
+ "--timeout, such as --timeout 10m", { reason: "crm.file-unavailable" });
271
+ // The adapter's error may carry the tokened link: only its code passes on.
272
+ throw new CliError(isCliError(error) ? error.code : "provider_error", `the CRM did not give the file ${file.id}, and nothing was kept`, { reason: "crm.file-unavailable" });
273
+ }
274
+ if (capped && !(await room(saved.bytes, target, true))) {
275
+ await discard();
276
+ throw diskFull(limits, top, setting);
277
+ }
278
+ let bytes;
279
+ try {
280
+ bytes = readFileSync(target);
281
+ }
282
+ catch {
283
+ await discard();
284
+ // The error would name the local path; the file was removed under the download.
285
+ throw new CliError("not_found", `the saved copy of ${file.id} was removed before its text was read; run it again`, {
286
+ reason: "crm.file-unavailable",
287
+ });
288
+ }
289
+ const cutOff = async () => {
290
+ await discard();
291
+ return new CliError("cancelled", `the time limit stopped reading the text of ${file.id}, and nothing was kept: run it again with a longer ` +
292
+ "--timeout, such as --timeout 10m", { reason: "crm.file-unavailable" });
293
+ };
294
+ let extraction;
295
+ try {
296
+ extraction =
297
+ saved.bytes > attachmentMaxBytes(run.env ?? process.env)
298
+ ? { status: "too-large" }
299
+ : await extractText(bytes, { kind: "file", name: file.name, mime: file.mime, path: target }, importEngine, signal, run.env ?? process.env);
300
+ }
301
+ catch (error) {
302
+ if (signal?.aborted)
303
+ throw await cutOff();
304
+ await discard();
305
+ throw error;
306
+ }
307
+ // A reading stopped by the time limit says nothing of the file: it is not kept as unreadable.
308
+ if (signal?.aborted)
309
+ throw await cutOff();
310
+ const self = run.source().self ? String(await run.source().self?.()) : null;
311
+ const row = {
312
+ externalId: file.id,
313
+ ownerKind: file.owner.kind,
314
+ ownerId: file.owner.id,
315
+ ownerAssignee: assignee === null ? null : crmIdentityId(run.account, normalCrmUserId(assignee), "user"),
316
+ source: file.source,
317
+ name: file.name,
318
+ mime: file.mime,
319
+ size: saved.bytes,
320
+ externalCreatedAt: file.created,
321
+ localPath: target,
322
+ contentSha256: saved.sha256,
323
+ text: extraction.status === "extracted" ? extraction.text.slice(0, MAX_TEXT_CHARS) : null,
324
+ extraction: extraction.status,
325
+ extractionError: extraction.status === "unreadable" ? extraction.error : null,
326
+ downloadedBy: self,
327
+ downloadedAt: now(),
328
+ };
329
+ await run.store.crmFiles.save(run.account, row);
330
+ // The copy an earlier download left in the account's folder is the CLI's own; this one replaces it.
331
+ if (earlier?.localPath && earlier.localPath !== target && earlier.localPath.startsWith(`${top}${sep}`))
332
+ rmSync(earlier.localPath, { force: true });
333
+ return { row, textStatus: extraction.status };
334
+ };
335
+ const itemOfFile = (file, saved) => {
336
+ const listed = "owner" in file;
337
+ return {
338
+ id: listed ? file.id : file.externalId,
339
+ name: file.name,
340
+ size: file.size,
341
+ mime: file.mime,
342
+ created_at: iso(listed ? file.created : file.externalCreatedAt),
343
+ owner: listed ? { kind: file.owner.kind, id: file.owner.id } : { kind: file.ownerKind, id: file.ownerId },
344
+ source: file.source,
345
+ downloaded: saved !== undefined && saved.localPath !== null,
346
+ path: saved?.localPath ?? null,
347
+ untrusted: ["name", "mime", "path"],
348
+ };
349
+ };
350
+ /** `files list`, `files download` and `files sync` (NEED-2701 C, NEED-2708 B). */
351
+ export const addCrmFileCommands = (program, options) => {
352
+ const { within, example, app, now } = options;
353
+ const kinds = OWNER_FLAGS.filter(([kind]) => kind !== "lead" || options.leads !== false);
354
+ const contextOf = (run, command) => {
355
+ const { signal } = environmentOf(command);
356
+ return { app, run, now, ...(signal ? { signal } : {}) };
357
+ };
358
+ const group = annotate(program.command("files"), { effects: REMOTE_READ }).description("the files of the CRM's deals, leads, contacts and companies: listed live, downloaded on demand, their text " +
359
+ "found by search all");
360
+ const list = example(answerEntity(annotate(group.command("list"), { effects: REMOTE_READ, offline: false }), "crm_file", crmFile).description("one record's files, read live from the CRM, with the path of each already downloaded; another user's " +
361
+ "record counts toward the day's limit when the CRM sets one"), "files list --deal 12", "files list --person 42 --json");
362
+ for (const [, flag] of kinds)
363
+ list.option(flag, `the ${flag.slice(2, flag.indexOf(" "))} whose files to list`);
364
+ list.action(async (opts, command) => {
365
+ const given = kinds.filter(([kind]) => opts[kind] !== undefined);
366
+ const [chosen] = given;
367
+ if (given.length !== 1 || !chosen)
368
+ throw new CliError("validation_error", `name one record: ${kinds.map(([, flag]) => flag).join(", ")}`, {
369
+ reason: "ref.malformed",
370
+ });
371
+ const owner = { kind: chosen[0], id: String(opts[chosen[0]]).trim() };
372
+ await within(command, async (run) => {
373
+ const context = contextOf(run, command);
374
+ const gaps = [];
375
+ const found = await listed(context, owner, gaps);
376
+ await quotaOf(context).spend(owner.kind, { externalId: owner.id, assignee: found.assignee });
377
+ const saved = new Map((await run.store.crmFiles.ofOwner(run.account, owner.kind, owner.id)).map((one) => [one.externalId, one]));
378
+ for (const gap of gaps)
379
+ outputFor(command).renderer.note(gap.message);
380
+ const items = found.files.map((file) => itemOfFile(file, saved.get(file.id)));
381
+ return listOf("files list", {
382
+ items,
383
+ limit: Math.max(1, items.length),
384
+ page: 1,
385
+ has_more: false,
386
+ ...(gaps.length
387
+ ? {
388
+ meta: {
389
+ complete: false,
390
+ issues: gaps.map((gap) => ({
391
+ code: "permission_error",
392
+ reason: "crm.scope-missing",
393
+ source: `crm:files${gap.scope ? `/${gap.scope}` : ""}`,
394
+ })),
395
+ },
396
+ }
397
+ : {}),
398
+ });
399
+ });
400
+ });
401
+ example(answerEntity(annotate(group.command("download"), { effects: FETCH, offline: false }), "crm_file_download", crmFileDownload)
402
+ .description(`save one file under the state folder (or --dir) and read its text, which search all then finds; ` +
403
+ `${DOWNLOAD_MB} MB at most unless --max-size; another user's record counts toward the day's limit`)
404
+ .argument("<file>", "the file's id, as files list prints it")
405
+ .option("--max-size <MB>", `the largest file to take, up to ${MOST_DOWNLOAD_MB}`, integer(MOST_DOWNLOAD_MB))
406
+ .option("--dir <folder>", "save it here instead, as the owner's own copy: not counted, never dropped"), "files download deal:12:record:345", "files download deal:12:document:7 --max-size 500 --dir ~/Contracts").action(async (given, opts, command) => {
407
+ const id = given.trim().replace(/^crmfile:/u, "");
408
+ const { owner } = parseCrmFileId(id);
409
+ const capMb = opts.maxSize ?? DOWNLOAD_MB;
410
+ await within(command, async (run) => {
411
+ const context = contextOf(run, command);
412
+ const found = await listed(context, owner);
413
+ // Spent before the id is looked up: a made-up id on a colleague's record still costs its slot.
414
+ await quotaOf(context).spend(owner.kind, { externalId: owner.id, assignee: found.assignee });
415
+ const file = found.files.find((one) => one.id === id);
416
+ if (!file)
417
+ throw new CliError("not_found", `${owner.kind} ${owner.id} has no file ${id}; files list names them`);
418
+ const done = await downloadCrmFile(context, file, found.assignee, {
419
+ capBytes: capMb * MB,
420
+ capMb,
421
+ flag: capMb < MOST_DOWNLOAD_MB,
422
+ limits: await run.store.crmFiles.limits(run.account),
423
+ ...(opts.dir === undefined ? {} : { dir: opts.dir }),
424
+ });
425
+ const text = done.row.text;
426
+ return itemOf({
427
+ ...itemOfFile(file, done.row),
428
+ size: done.row.size,
429
+ text_status: done.textStatus,
430
+ text: text === null ? null : text.slice(0, SHOWN_TEXT),
431
+ text_truncated: text !== null && text.length > SHOWN_TEXT,
432
+ untrusted: ["name", "mime", "path", "text"],
433
+ });
434
+ });
435
+ });
436
+ example(answerEntity(annotate(group.command("sync"), { effects: FETCH, offline: false, cooperative: true, partial: true }), "crm_files_sync", crmFilesSync).description("download the files of your own deals and leads that changed lately, newest first, within the account's " +
437
+ "files.* limits; stops at its deadline and the next run goes on. Never another user's files. Run it on a " +
438
+ `schedule: ${app.command} schedule command crm-files --every 1h -- files sync`), "files sync").action(async (_opts, command) => {
439
+ const level = commandLevel(command, app, FILES_DOWNLOAD_KEY);
440
+ if (level === "deny" || level === "readonly")
441
+ throw new CliError("permission_error", `files sync downloads files, which ${FILES_DOWNLOAD_KEY} ${level}s`, {
442
+ reason: "crm.files-denied",
443
+ permission: FILES_DOWNLOAD_KEY,
444
+ });
445
+ const budget = runBudgetOf(command);
446
+ await within(command, async (run) => {
447
+ const report = await syncFiles(contextOf(run, command), () => budget.take() !== null);
448
+ const next = report.complete
449
+ ? undefined
450
+ : [
451
+ {
452
+ kind: "command",
453
+ step: "crm.files-sync",
454
+ command: "files sync",
455
+ args: {},
456
+ why: "the run stopped at a limit; the next run goes on from there",
457
+ safe_to_auto_execute: true,
458
+ },
459
+ ];
460
+ return itemOf({
461
+ ...report,
462
+ skipped: report.skipped.map((one) => ({ ...one, step: lineOf(command, `files download ${one.id}`) })),
463
+ untrusted: ["downloaded.name", "downloaded.path", "skipped.name"],
464
+ }, { ...(report.complete ? {} : { meta: { complete: false } }), ...(next ? { next } : {}) });
465
+ });
466
+ });
467
+ };
468
+ /** Runs a file may be unavailable in before the round closes without it. */
469
+ const MOST_TRIES = 3;
470
+ const roundOf = async (run) => {
471
+ try {
472
+ const found = JSON.parse((await run.store.sync.syncState(run.account, FILES_ROUND))?.value ?? "null");
473
+ if (found && Array.isArray(found.done))
474
+ return found;
475
+ }
476
+ catch { }
477
+ return { after: null, started: null, done: [] };
478
+ };
479
+ /**
480
+ * One `files sync` run: the files of the sign-in's own deals and leads changed since the last complete round, and at
481
+ * most `files.days` back, newest first, under the run's limits. It stops at the first run limit and saves its place.
482
+ */
483
+ export const syncFiles = async (context, outOfTime, deadline = (ms) => AbortSignal.timeout(ms)) => {
484
+ const { run, now } = context;
485
+ const source = run.source();
486
+ if (!source.self)
487
+ throw new CliError("configuration_error", "this CRM names no user for the sign-in, so no deal is yours");
488
+ const self = normalCrmUserId(String(await source.self()));
489
+ const limits = await run.store.crmFiles.limits(run.account);
490
+ const started = now();
491
+ const ends = started + limits.run_minutes * 60_000;
492
+ const round = await roundOf(run);
493
+ const roundStart = round.started ?? started;
494
+ const since = Math.max(round.after ?? 0, roundStart - limits.days * DAY);
495
+ const assignee = crmIdentityId(run.account, self, "user");
496
+ const candidates = [];
497
+ for (const kind of ["deal", "lead"])
498
+ for (let offset = 0;; offset += PAGE) {
499
+ const found = await run.store.deals.list({
500
+ kind,
501
+ account: run.account,
502
+ owner: assignee,
503
+ updated: { since },
504
+ limit: PAGE,
505
+ offset,
506
+ });
507
+ for (const one of found.items)
508
+ candidates.push({ kind, id: one.externalId ?? "", updated: Date.parse(one.updatedAt) });
509
+ if (!found.hasMore)
510
+ break;
511
+ }
512
+ const owners = candidates
513
+ .filter((one) => one.id && !round.done.includes(`${one.kind}:${one.id}`))
514
+ .sort((a, b) => b.updated - a.updated);
515
+ const report = { owners: owners.length, downloaded: [], skipped: [], complete: true };
516
+ const done = [...round.done];
517
+ // A record whose file could not be had is not done: the next run asks again, so the round stays open.
518
+ let retry = false;
519
+ const tries = { ...(round.tries ?? {}) };
520
+ let runBytes = 0;
521
+ const stop = (reason, file) => {
522
+ report.skipped.push({ id: file.id, name: file.name, size: file.size, reason });
523
+ report.stopped = reason;
524
+ report.complete = false;
525
+ };
526
+ outer: for (const owner of owners) {
527
+ if (now() >= ends || outOfTime()) {
528
+ report.stopped = "deadline";
529
+ report.complete = false;
530
+ break;
531
+ }
532
+ const found = await source.files?.({ kind: owner.kind, id: owner.id }, { spend: () => { }, gap: () => { } });
533
+ // The copy may be behind the CRM: a deal given to a colleague since the last sync is theirs, and so are its files.
534
+ if (!found || found.assignee === null || normalCrmUserId(found.assignee) !== self) {
535
+ done.push(`${owner.kind}:${owner.id}`);
536
+ continue;
537
+ }
538
+ const files = [...found.files].sort((a, b) => (b.created ?? 0) - (a.created ?? 0));
539
+ let available = true;
540
+ for (const file of files) {
541
+ if (await run.store.crmFiles.get(run.account, file.id))
542
+ continue;
543
+ const fileCap = limits.max_file_mb * MB;
544
+ if (file.size !== null && file.size > fileCap) {
545
+ report.skipped.push({ id: file.id, name: file.name, size: file.size, reason: "too-large" });
546
+ continue;
547
+ }
548
+ if (report.downloaded.length >= limits.max_files) {
549
+ stop("run-files", file);
550
+ break outer;
551
+ }
552
+ const left = limits.max_run_mb * MB - runBytes;
553
+ if (file.size !== null && file.size > left) {
554
+ stop("run-mb", file);
555
+ break outer;
556
+ }
557
+ if (now() >= ends || outOfTime()) {
558
+ stop("deadline", file);
559
+ break outer;
560
+ }
561
+ const remaining = deadline(Math.max(1, ends - now()));
562
+ const signal = context.signal ? AbortSignal.any([context.signal, remaining]) : remaining;
563
+ try {
564
+ const saved = await downloadCrmFile({ ...context, signal }, file, found.assignee, {
565
+ capBytes: Math.min(fileCap, left),
566
+ capMb: limits.max_file_mb,
567
+ flag: false,
568
+ limits,
569
+ });
570
+ delete tries[file.id];
571
+ runBytes += saved.row.size ?? 0;
572
+ report.downloaded.push({
573
+ id: file.id,
574
+ name: file.name,
575
+ size: saved.row.size ?? 0,
576
+ path: saved.row.localPath ?? "",
577
+ text_status: saved.textStatus,
578
+ });
579
+ }
580
+ catch (error) {
581
+ const reason = isCliError(error) ? error.details.reason : undefined;
582
+ if (reason === "crm.files-disk-full") {
583
+ stop("disk-full", file);
584
+ break outer;
585
+ }
586
+ if (reason === "crm.file-too-large") {
587
+ // An unknown size stopped at the cap: the file or what is left of the run.
588
+ if (left < fileCap) {
589
+ stop("run-mb", file);
590
+ break outer;
591
+ }
592
+ report.skipped.push({ id: file.id, name: file.name, size: file.size, reason: "too-large" });
593
+ continue;
594
+ }
595
+ if (signal.aborted || (isCliError(error) && error.code === "timeout")) {
596
+ stop("deadline", file);
597
+ break outer;
598
+ }
599
+ report.skipped.push({ id: file.id, name: file.name, size: file.size, reason: "unavailable" });
600
+ tries[file.id] = (tries[file.id] ?? 0) + 1;
601
+ // A file the CRM keeps refusing is given up, so the round can close.
602
+ if ((tries[file.id] ?? 0) < MOST_TRIES)
603
+ available = false;
604
+ }
605
+ }
606
+ if (available)
607
+ done.push(`${owner.kind}:${owner.id}`);
608
+ else
609
+ retry = true;
610
+ }
611
+ const next = report.complete && !retry
612
+ ? { after: roundStart, started: null, done: [] }
613
+ : { after: round.after, started: roundStart, done, tries };
614
+ await run.store.sync.setSyncState(run.account, FILES_ROUND, JSON.stringify(next));
615
+ return report;
616
+ };
@@ -55,6 +55,7 @@ export interface CrmCommandOptions {
55
55
  */
56
56
  live?: readonly CrmLiveRecord[];
57
57
  activities?: boolean;
58
+ files?: boolean;
58
59
  now?: () => number;
59
60
  }
60
61
  /** What `deals list` and `leads list` narrow by, the same in memo and every CRM CLI (WC-OUT-11). */
@@ -27,6 +27,7 @@ import { ownerOf, shortened, viewerOf, withReadableDeal } from "../viewer.js";
27
27
  import { closeCrmItem, createCrmItem, fieldPairsOf, moveCrmItem, pipelineOf, removeCrmItem, updateCrmItem, } from "../writes.js";
28
28
  import { addCrmChangeCommands } from "./changes.js";
29
29
  import { csvFormatOption, renderCsv } from "./csv.js";
30
+ import { addCrmFileCommands } from "./files.js";
30
31
  import { pipelineView } from "./pipeline-view.js";
31
32
  import { addCrmRecordCommands, integer } from "./records.js";
32
33
  import { addCrmSearchAll } from "./search-all.js";
@@ -639,6 +640,8 @@ const addCrmCommandsDefinition = (program, options) => {
639
640
  now,
640
641
  });
641
642
  addCrmChangeCommands(program, { ...options, within, example, now, ownerOf, pathOf });
643
+ if (options.files)
644
+ addCrmFileCommands(program, { ...options, within, example, now });
642
645
  const fieldKinds = Object.keys(FIELD_KINDS).filter((word) => word !== "leads" || options.leads !== false);
643
646
  const fields = annotate(program.command("fields"), { effects: NO_EFFECTS }).description("the CRM's own fields on deals, leads, people and organizations, as last synced");
644
647
  example(withQuery(answerEntity(annotate(fields.command("list"), { effects: LOCAL_READ }), "crm_field", crmField)
@@ -37,7 +37,7 @@ export const addCrmSearchAll = (searches, { within, app, example, viewerOf, }) =
37
37
  throw new CliError("permission_error", "this process is locked to one profile; search all reads its own CRM account only, without --source", { reason: "profile.locked" });
38
38
  const asked = opts.only ?? SEARCHED;
39
39
  const denied = deniedKinds(leaf, app, [
40
- ...(asked.includes("crm") ? DEAL_KINDS : []),
40
+ ...(asked.includes("crm") ? [...DEAL_KINDS, "crm_file"] : []),
41
41
  ...asked.filter((one) => one !== "crm" && one !== "mail"),
42
42
  ]);
43
43
  const out = new Set(denied.map(({ kind }) => kind));
@@ -68,7 +68,8 @@ export const addCrmSearchAll = (searches, { within, app, example, viewerOf, }) =
68
68
  only,
69
69
  ...(opts.only?.includes("meetings") ? { meetingsAsked: true } : {}),
70
70
  ...(crmKinds.length < DEAL_KINDS.length ? { crmKinds } : {}),
71
- ...(viewers.length ? { crmViewers: viewers } : {}),
71
+ crmViewers: viewers,
72
+ ...(out.has("crm_file") ? { crmFiles: false } : {}),
72
73
  ...(opts.source === undefined ? {} : { source: opts.source }),
73
74
  ...(alone ? { scope: { crm: [run.account] } } : {}),
74
75
  }, { app, hintCommand: commandAt(rootOf(leaf), "models download") ? app.command : null }, undefined, meaningLane({ env, messenger: { app }, store: async () => run.store }));