@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
@@ -1,21 +1,23 @@
1
1
  import assert from "node:assert/strict";
2
2
  import { isCliError } from "@wirecat/cli-base";
3
3
  import { ANSWER_RESERVE_MS, runBudget } from "../../../background/budget.js";
4
+ import { feedOf, } from "../../../documents.js";
4
5
  import { DEFAULT_AGENT_COOPERATIVE_MS } from "../../execution.js";
5
6
  const MAX_ENTRIES = 500;
7
+ // Each listing is given the folder as listed, as the sync gives it: a source that addresses by path reads it there.
6
8
  const walk = async ({ source, root, isFolder }) => {
7
9
  const seen = new Map();
8
- const stack = [root];
10
+ const stack = [await source.metadata(root)];
9
11
  while (stack.length) {
10
12
  const parent = stack.pop();
11
- for (const child of await source.children(parent)) {
12
- assert.ok(child.parents.includes(parent), `${child.id} is a child of ${parent} and names it among its parents`);
13
+ for (const child of await source.children(parent.id, parent)) {
14
+ assert.ok(child.parents.includes(parent.id), `${child.id} is a child of ${parent.id} and names it among its parents`);
13
15
  if (seen.has(child.id))
14
16
  continue;
15
17
  seen.set(child.id, child);
16
18
  assert.ok(seen.size <= MAX_ENTRIES, `more than ${MAX_ENTRIES} entries under the fixture's root`);
17
19
  if (isFolder(child))
18
- stack.push(child.id);
20
+ stack.push(child);
19
21
  }
20
22
  }
21
23
  return [...seen.values()];
@@ -98,7 +100,7 @@ export const documentSourceContract = (make) => {
98
100
  assert.equal(typeof entry.url, "string", `${entry.id} has a URL`);
99
101
  assert.equal(typeof entry.canDownload, "boolean", `${entry.id} says whether it can be downloaded`);
100
102
  assert.ok(isTime(entry.modifiedAt) && isTime(entry.createdAt), `${entry.id}'s times parse`);
101
- assert.equal((await fixture.source.metadata(entry.id)).id, entry.id, `metadata(${entry.id}) is the same file`);
103
+ assert.equal((await fixture.source.metadata(entry.id, entry)).id, entry.id, `metadata(${entry.id}) is the same file`);
102
104
  }
103
105
  },
104
106
  },
@@ -109,14 +111,14 @@ export const documentSourceContract = (make) => {
109
111
  const files = (await walk(fixture)).filter((entry) => isImported(fixture, entry) && entry.canDownload);
110
112
  assert.ok(files.length > 0, "the root has a file that can be downloaded");
111
113
  for (const file of files.slice(0, 5)) {
112
- const content = await fixture.source.content(file.id);
114
+ const content = await fixture.source.content(file.id, undefined, file);
113
115
  assert.equal(content.metadata.id, file.id);
114
116
  assert.equal(typeof content.text, "string");
115
117
  assert.equal(typeof content.markdown, "string");
116
118
  assert.ok(Array.isArray(content.tabs), "tabs is a list, empty for a document without tabs");
117
119
  for (const tab of content.tabs)
118
120
  assert.ok(typeof tab.id === "string" && typeof tab.title === "string" && typeof tab.text === "string");
119
- const bytes = await fixture.source.bytes(file.id);
121
+ const bytes = await fixture.source.bytes(file.id, file);
120
122
  assert.ok(bytes instanceof Uint8Array, `bytes(${file.id}) is a Uint8Array`);
121
123
  }
122
124
  },
@@ -126,10 +128,15 @@ export const documentSourceContract = (make) => {
126
128
  async run() {
127
129
  const fixture = await make();
128
130
  const { source } = fixture;
129
- const token = await source.startToken();
131
+ const feed = feedOf(source);
132
+ if (!feed) {
133
+ assert.ok(!("startToken" in source), "a source has both startToken() and changes(), or neither");
134
+ return;
135
+ }
136
+ const token = await feed.startToken();
130
137
  assert.ok(typeof token === "string" && token, "startToken() gives a cursor");
131
138
  await fixture.change?.();
132
- const page = await source.changes(token);
139
+ const page = await feed.changes(token);
133
140
  assert.ok(Array.isArray(page.items), "a change page has items");
134
141
  if (fixture.change)
135
142
  assert.ok(page.items.length > 0, "the change made after startToken() is in the feed");
@@ -146,11 +153,12 @@ export const documentSourceContract = (make) => {
146
153
  name: "changes: a file added deep in the tree is named in the feed, itself or by its own folder",
147
154
  async run() {
148
155
  const { source, addNested } = await make();
149
- if (!addNested)
156
+ const feed = feedOf(source);
157
+ if (!addNested || !feed)
150
158
  return;
151
- const token = await source.startToken();
159
+ const token = await feed.startToken();
152
160
  const { file, folder } = await addNested();
153
- const named = new Set((await source.changes(token)).items.map((item) => item.id));
161
+ const named = new Set((await feed.changes(token)).items.map((item) => item.id));
154
162
  assert.ok(named.has(file) || named.has(folder), `the feed names ${file} or its folder ${folder}`);
155
163
  },
156
164
  });
@@ -161,30 +169,51 @@ export const documentSourceContract = (make) => {
161
169
  const { source } = fixture;
162
170
  if (!source.childrenPage)
163
171
  return;
164
- const stack = [fixture.root];
172
+ const stack = [await source.metadata(fixture.root)];
165
173
  while (stack.length) {
166
174
  const parent = stack.pop();
167
175
  const paged = [];
168
176
  let cursor;
169
177
  for (let pages = 1;; pages++) {
170
- assert.ok(pages <= MAX_ENTRIES, `childrenPage(${parent}) ends`);
171
- const page = await source.childrenPage(parent, cursor);
178
+ assert.ok(pages <= MAX_ENTRIES, `childrenPage(${parent.id}) ends`);
179
+ const page = await source.childrenPage(parent.id, cursor, parent);
172
180
  assert.ok(Array.isArray(page.files), "a page has files");
173
181
  paged.push(...page.files.map((file) => file.id));
174
182
  for (const file of page.files)
175
183
  if (fixture.isFolder(file))
176
- stack.push(file.id);
184
+ stack.push(file);
177
185
  if (page.cursor === undefined)
178
186
  break;
179
187
  assert.ok(typeof page.cursor === "string" && page.cursor !== cursor, "a page gives a new cursor or none");
180
188
  cursor = page.cursor;
181
189
  }
182
- assert.equal(new Set(paged).size, paged.length, `childrenPage(${parent}) lists each entry once`);
183
- const listed = (await source.children(parent)).map((file) => file.id);
184
- assert.deepEqual([...paged].sort(), [...listed].sort(), `childrenPage(${parent}) lists what children() does`);
190
+ assert.equal(new Set(paged).size, paged.length, `childrenPage(${parent.id}) lists each entry once`);
191
+ const listed = (await source.children(parent.id, parent)).map((file) => file.id);
192
+ assert.deepEqual([...paged].sort(), [...listed].sort(), `childrenPage(${parent.id}) lists what children() does`);
185
193
  }
186
194
  },
187
195
  });
196
+ cases.push({
197
+ name: "without a change feed: the next sync finds a new or edited file and drops a removed one",
198
+ async run() {
199
+ const fixture = await make();
200
+ const sync = fixture.faults?.sync;
201
+ if (feedOf(fixture.source) || !sync || (!fixture.change && !fixture.remove))
202
+ return;
203
+ const before = await finish(sync);
204
+ const idle = await finish(sync);
205
+ assert.equal(idle.result.saved, 0, "a sync with nothing changed on the provider saves nothing again");
206
+ const removed = await fixture.remove?.();
207
+ if (removed !== undefined)
208
+ assert.ok(before.saved.includes(removed), `the first sync holds ${removed} before it is removed`);
209
+ await fixture.change?.();
210
+ const after = await finish(sync);
211
+ if (removed !== undefined)
212
+ assert.ok(!after.saved.includes(removed), `the next sync drops the removed ${removed}`);
213
+ if (fixture.change)
214
+ assert.ok(after.result.saved > 0, "the next sync saves the new or edited file, though no feed named it");
215
+ },
216
+ });
188
217
  cases.push({
189
218
  name: "metadata: an id the provider does not know is not_found",
190
219
  async run() {
@@ -204,9 +233,10 @@ const faultCases = (make) => [
204
233
  const deny = fixture.faults?.deny;
205
234
  if (!deny)
206
235
  return;
236
+ const listed = new Map((await walk(fixture)).map((entry) => [entry.id, entry]));
207
237
  const id = await deny(status);
208
238
  const code = status === 403 ? "permission_error" : "not_found";
209
- await assert.rejects(fixture.source.content(id), (error) => isCliError(error) && error.code === code, `content(${id}) after a ${status} is ${code}`);
239
+ await assert.rejects(fixture.source.content(id, undefined, listed.get(id)), (error) => isCliError(error) && error.code === code, `content(${id}) after a ${status} is ${code}`);
210
240
  const sync = fixture.faults?.sync;
211
241
  if (!sync)
212
242
  return;
@@ -227,14 +257,15 @@ const faultCases = (make) => [
227
257
  name: "faults: a clock off by ten minutes either way loses no change",
228
258
  async run() {
229
259
  const first = await make();
230
- if (!first.faults?.skewed || !first.change)
260
+ if (!first.faults?.skewed || !first.change || !feedOf(first.source))
231
261
  return;
232
262
  for (const ms of [SKEW_MS, -SKEW_MS]) {
233
263
  const fixture = ms === SKEW_MS ? first : await make();
234
264
  const source = (await fixture.faults?.skewed?.(ms));
235
- const token = await source.startToken();
265
+ const { startToken, changes } = source;
266
+ const token = await startToken.call(source);
236
267
  await fixture.change?.();
237
- const page = await source.changes(token);
268
+ const page = await changes.call(source, token);
238
269
  assert.ok(page.items.length > 0, `a change is in the feed with this computer's clock ${ms / 60_000} min off`);
239
270
  }
240
271
  },
@@ -1,8 +1,14 @@
1
- import type { DocumentSource, SourceFile } from "../../../documents.js";
1
+ import type { FeedlessDocumentSource, SourceChange, SourceFile } from "../../../documents.js";
2
2
  /** The folder type of the fake source: no provider's own. */
3
3
  export declare const FAKE_FOLDER = "inode/directory";
4
4
  export declare const fakeFile: (id: string, parents?: string[], mime?: string) => SourceFile;
5
- export interface FakeDocumentSource extends DocumentSource {
5
+ export interface FakeDocumentSource extends FeedlessDocumentSource {
6
+ /** Absent with `feed: false`. */
7
+ startToken?(): Promise<string>;
8
+ changes?(token: string): Promise<{
9
+ items: SourceChange[];
10
+ cursor: string;
11
+ }>;
6
12
  files: Map<string, SourceFile>;
7
13
  /** Puts a file or folder in, or changes it, and lists it in the next change feed. */
8
14
  put(file: SourceFile, text?: string): void;
@@ -13,8 +19,10 @@ export interface FakeDocumentSource extends DocumentSource {
13
19
  }
14
20
  /**
15
21
  * A provider in memory: a root folder, a nested folder and two text files, with a change feed and a cursor. With
16
- * `pageSize` it also lists a folder's children a page at a time through `childrenPage`.
22
+ * `pageSize` it also lists a folder's children a page at a time through `childrenPage`; with `feed: false` it has no
23
+ * change feed, as Yandex Disk.
17
24
  */
18
25
  export declare const fakeDocumentSource: (account?: string, options?: {
19
26
  pageSize?: number;
27
+ feed?: boolean;
20
28
  }) => FakeDocumentSource;
@@ -14,7 +14,8 @@ export const fakeFile = (id, parents = ["root"], mime = "text/plain") => ({
14
14
  });
15
15
  /**
16
16
  * A provider in memory: a root folder, a nested folder and two text files, with a change feed and a cursor. With
17
- * `pageSize` it also lists a folder's children a page at a time through `childrenPage`.
17
+ * `pageSize` it also lists a folder's children a page at a time through `childrenPage`; with `feed: false` it has no
18
+ * change feed, as Yandex Disk.
18
19
  */
19
20
  export const fakeDocumentSource = (account = "alpha", options = {}) => {
20
21
  const files = new Map();
@@ -64,15 +65,19 @@ export const fakeDocumentSource = (account = "alpha", options = {}) => {
64
65
  },
65
66
  }
66
67
  : {}),
67
- startToken: async () => `cursor-${cursor}`,
68
- changes: async (token) => {
69
- if (!/^cursor-\d+$/.test(token))
70
- throw new CliError("validation_error", "unknown synthetic cursor");
71
- const items = feed;
72
- feed = [];
73
- cursor += 1;
74
- return { items, cursor: `cursor-${cursor}` };
75
- },
68
+ ...(options.feed === false
69
+ ? {}
70
+ : {
71
+ startToken: async () => `cursor-${cursor}`,
72
+ changes: async (token) => {
73
+ if (!/^cursor-\d+$/.test(token))
74
+ throw new CliError("validation_error", "unknown synthetic cursor");
75
+ const items = feed;
76
+ feed = [];
77
+ cursor += 1;
78
+ return { items, cursor: `cursor-${cursor}` };
79
+ },
80
+ }),
76
81
  content: async (id, maxChars) => {
77
82
  const file = await metadata(id);
78
83
  if (file.mime === FAKE_FOLDER)
@@ -56,8 +56,8 @@ export interface CopyAge {
56
56
  }
57
57
  export declare const ageOf: (lastSync: string | undefined, now?: number) => CopyAge;
58
58
  export declare const staleCopy: (provider: string, lastSync: string | undefined, now?: number) => {
59
- missing?: undefined;
60
59
  next?: undefined;
60
+ missing?: undefined;
61
61
  meta?: undefined;
62
62
  } | {
63
63
  missing: {
@@ -10,7 +10,7 @@ import { environmentOf, setExitCode } from "./context.js";
10
10
  import { largeAnswerSteps, SOFT_OUTPUT_BYTES } from "./output-budget.js";
11
11
  import { withoutProviderRefs } from "./provider-refs.js";
12
12
  import { nextStep, rootOf, runnable, stepLine, withLines, withSafety } from "./steps.js";
13
- import { untrustedFieldsOf, untrustedMarkOf, withFieldsMarked, withUntrustedMarked } from "./untrusted-marks.js";
13
+ import { runMarkOf, untrustedFieldsOf, withFieldsMarked, withUntrustedMarked } from "./untrusted-marks.js";
14
14
  /** Every answer: a list or one thing, with items of `item` — any value where the command declares no entity. */
15
15
  export const answerSchema = (item = v.unknown()) => v.union([listEnvelopeSchema(item), itemEnvelopeSchema(item)]);
16
16
  const capped = (steps) => (steps.length > 0 ? { next: steps.slice(0, MAX_NEXT_STEPS) } : {});
@@ -185,8 +185,7 @@ export const renderAnswer = (command, { renderer, format, streams, compact, full
185
185
  const root = rootOf(command);
186
186
  const runnableSteps = runnable(root, body.next);
187
187
  const next = environmentOf(command).agent ? runnableSteps : withLines(root, runnableSteps);
188
- const { app, env } = environmentOf(command);
189
- const mark = app ? untrustedMarkOf(app, env ?? process.env) : undefined;
188
+ const mark = runMarkOf(command);
190
189
  const declared = untrustedFieldsOf(command);
191
190
  const shown = mark === undefined ? body : withUntrustedMarked(declared ? withFieldsMarked(body, declared, mark) : body, mark);
192
191
  const kept = withoutProviderRefs({ ...shown, ...(next.length > 0 ? { next } : {}) });
@@ -12,6 +12,7 @@ import { answerEntity } from "./answer-entity.js";
12
12
  import { destroysNothing } from "./effects.js";
13
13
  import { answerSchema, itemOf, listOf } from "./envelope.js";
14
14
  import { pagingOf } from "./paging.js";
15
+ import { runMarkOf, withUntrustedMarked } from "./untrusted-marks.js";
15
16
  const INDEX_BYTES = 4194304;
16
17
  const parse = (command, args) => {
17
18
  command
@@ -148,6 +149,9 @@ export const addMeetingBatchCommand = (program, deps) => {
148
149
  fields,
149
150
  failureContext: failureContext(),
150
151
  });
152
+ // The host formats text and Markdown from the report; JSON is marked by `renderAnswer`.
153
+ const mark = format === "json" ? undefined : runMarkOf(action);
154
+ const shown = mark === undefined ? report : withUntrustedMarked(report, mark);
151
155
  const issues = report.items
152
156
  .filter((item) => !item.complete)
153
157
  .map((item) => ({
@@ -167,7 +171,7 @@ export const addMeetingBatchCommand = (program, deps) => {
167
171
  ...(issues.length ? { issues } : {}),
168
172
  ...(report.output_limited ? { truncated: true } : {}),
169
173
  },
170
- }), report, format);
174
+ }), shown, format);
171
175
  });
172
176
  destroysNothing(command);
173
177
  annotate(command, {
@@ -1,7 +1,7 @@
1
1
  import type { Command } from "commander";
2
2
  import type { MeetingPassageOutputFormat, MeetingPassageResult } from "../meetings/index.js";
3
3
  /**
4
- * The passage as the host prints it from `meetings passage`'s `output`: in a scheduled agent's run, text and Markdown
4
+ * The passage as the host prints it from `meetings passage`'s `output`, or as `callMeetingPassageTool` answers it: in a scheduled agent's run, text and Markdown
5
5
  * are formatted again from the marked cues. The meetings module cannot read the run's mark; JSON is marked by
6
6
  * `renderAnswer`.
7
7
  */
@@ -1,14 +1,12 @@
1
1
  import { formatMeetingPassage } from "../services/meeting-passage-format.js";
2
- import { environmentOf } from "./context.js";
3
- import { untrustedMarkOf, withUntrustedMarked } from "./untrusted-marks.js";
2
+ import { runMarkOf, withUntrustedMarked } from "./untrusted-marks.js";
4
3
  /**
5
- * The passage as the host prints it from `meetings passage`'s `output`: in a scheduled agent's run, text and Markdown
4
+ * The passage as the host prints it from `meetings passage`'s `output`, or as `callMeetingPassageTool` answers it: in a scheduled agent's run, text and Markdown
6
5
  * are formatted again from the marked cues. The meetings module cannot read the run's mark; JSON is marked by
7
6
  * `renderAnswer`.
8
7
  */
9
8
  export const passageForRun = (command, result, format) => {
10
- const { app, env } = environmentOf(command);
11
- const mark = app ? untrustedMarkOf(app, env ?? process.env) : undefined;
9
+ const mark = runMarkOf(command);
12
10
  if (mark === undefined || format === "json")
13
11
  return result;
14
12
  return { ...result, content: formatMeetingPassage(withUntrustedMarked(result.packet, mark), format) };
@@ -626,6 +626,10 @@ export const conversationsSearchCommand = (messenger) => syncOptions(boundOption
626
626
  if (refreshed)
627
627
  for (const note of leftNotes(refreshed, rootOf(this)))
628
628
  context.renderer.note(note);
629
+ for (const [word, forms] of Object.entries(found.respelled ?? {}))
630
+ context.renderer.note(`no message holds «${word}»: searched ${forms.map((form) => `«${form}»`).join(", ")} instead`);
631
+ if (found.named)
632
+ context.renderer.note(`«${found.named.word}» is a name in chat ${found.named.title ?? found.named.chatId} (${found.named.chatId}): its hits come first`);
629
633
  if (found.words === "out-of-time")
630
634
  context.renderer.note("the word half ran out of time, so these are by meaning alone; --timeout gives it longer");
631
635
  renderAnswer(this, context, foundConversations("search conversations", found, limit, messenger, chat, window.meta), () => found.hits.map((hit) => `${hitLine(hit)}\n`).join(""));
@@ -7,6 +7,7 @@ import { syncsOneChat } from "../../ports/traits.js";
7
7
  import { renderMessages } from "../../render/messages.js";
8
8
  import { renderThreadLinks } from "../../render/thread-context.js";
9
9
  import { searchTimeLimit } from "../../search/lucene/types.js";
10
+ import { START_LETTERS } from "../../search/stem.js";
10
11
  import { environmentOf } from "../context.js";
11
12
  import { REMOTE_READ } from "../effects.js";
12
13
  import { renderAnswer } from "../envelope.js";
@@ -133,6 +134,10 @@ const searchAction = (messenger) => async function (given) {
133
134
  const { command } = messenger.app;
134
135
  for (const { from, to } of found.corrections)
135
136
  context.renderer.note(`${from} → ${to.join(", ")}`);
137
+ for (const [word, forms] of Object.entries(found.respelled ?? {}))
138
+ context.renderer.note(`no message holds «${word}»: also searched ${forms.map((form) => `«${form}»`).join(", ")}`);
139
+ if (found.named)
140
+ context.renderer.note(`«${found.named.word}» is a name in chat ${found.named.title ?? found.named.chatId} (${found.named.chatId}): its hits come first`);
136
141
  for (const { source, reason } of found.skipped ?? [])
137
142
  context.renderer.note(`${source} not searched: ${reason}`);
138
143
  if (found.meaningSkipped)
@@ -145,7 +150,7 @@ const searchAction = (messenger) => async function (given) {
145
150
  const stemming = found.query?.stemming;
146
151
  const forms = (stemming?.applied ? stemming.terms : []).filter(({ stemmer }) => stemmer !== "none");
147
152
  if (forms.length > 0)
148
- context.renderer.note(`also found other forms: ${forms.map(({ word, stem, stemmer }) => `${word} → ${stem}* (${stemmer})`).join(", ")} — --exact for the exact words only`);
153
+ context.renderer.note(`also found other forms: ${forms.map(({ word, stem, stemmer }) => `${word} → ${[...word].length >= START_LETTERS ? `${word}… and ` : ""}words stemmed to ${stem} (${stemmer})`).join(", ")} — --exact for the exact words only`);
149
154
  if (stemming?.applied === false)
150
155
  context.renderer.note(stemming.reason === "building"
151
156
  ? `other forms of words are not searched yet: the stems are ${Math.floor((stemming.done / Math.max(stemming.total, 1)) * 100)}% built — \`${command} store migrate\` finishes them`
@@ -295,6 +295,8 @@ const ALL_HIT_UNTRUSTED = {
295
295
  // A CRM's copy is typed by the CRM's users; the owner's own deal is his, but one rule keeps a hit's marking simple.
296
296
  deal: ["title", "excerpt"],
297
297
  lead: ["title", "excerpt"],
298
+ // A client's file: its name and every word of it are someone else's.
299
+ crm_file: ["title", "excerpt"],
298
300
  ...BUSINESS_UNTRUSTED,
299
301
  };
300
302
  export const allHitItem = (item) => item.kind === "meeting"
@@ -11,6 +11,7 @@ declare const LIST_KEYS: {
11
11
  readonly notes: "notes.list";
12
12
  readonly events: "events.list";
13
13
  readonly meetings: "meetings.list";
14
+ readonly crm_file: "files.list";
14
15
  };
15
16
  export type SearchedKind = keyof typeof LIST_KEYS;
16
17
  export interface LeftOut<K extends SearchedKind> {
@@ -30,4 +31,6 @@ export declare const deniedKindsOf: <K extends SearchedKind>(permissions: Readon
30
31
  * server's own stricter ones.
31
32
  */
32
33
  export declare const deniedKinds: <K extends SearchedKind>(command: Command, app: AppIdentity, kinds: readonly K[]) => LeftOut<K>[];
34
+ /** The level the profile, `--permission` and an MCP server's own levels give `key` for this run. */
35
+ export declare const commandLevel: (command: Command, app: AppIdentity, key: PermissionKey) => Level;
33
36
  export {};
@@ -12,6 +12,7 @@ const LIST_KEYS = {
12
12
  notes: "notes.list",
13
13
  events: "events.list",
14
14
  meetings: "meetings.list",
15
+ crm_file: "files.list",
15
16
  };
16
17
  /**
17
18
  * The kinds whose list `permissions` deny, for a CLI with levels of its own, such as memo's: `by` names who denies in
@@ -36,3 +37,14 @@ export const deniedKinds = (command, app, kinds) => {
36
37
  });
37
38
  return deniedKindsOf(permissions, kinds, `profile ${profile}`, environment.permissionDefaults);
38
39
  };
40
+ /** The level the profile, `--permission` and an MCP server's own levels give `key` for this run. */
41
+ export const commandLevel = (command, app, key) => {
42
+ const environment = environmentOf(command);
43
+ const resolve = environment.resolveSettings ?? settingsFor(app).resolveSettings;
44
+ const { permissions } = resolve(withAgentLevels(command, command.optsWithGlobals()), {
45
+ env: environment.env ?? process.env,
46
+ needsProfile: false,
47
+ readOnly: true,
48
+ });
49
+ return levelFor(permissions, key, environment.permissionDefaults).level;
50
+ };
@@ -9,7 +9,7 @@ import { DEFAULT_STEMMERS, parseStemmers } from "../search/stem.js";
9
9
  import { openCache } from "../store/open.js";
10
10
  import { storePath } from "../store/path.js";
11
11
  import { applyTaskCategoryEdits, editsFrom, readTaskCategoryEdits, sharedConfigPath, writeTaskCategoryEdits, } from "../store/shared-config.js";
12
- import { accountGroupsOf, crmSettingsOf, DEFAULT_AGENT_CLOSE, DEFAULT_FIRST_PASS_PER_CHAT, DEFAULT_OWNER_LANGUAGES, firstPassPerChatOf, openStore, parseCrmSetting, parseCrmSettingValue, parseOwnerLanguages, saveCrmSetting, savedAgentClose, savedFirstPassPerChat, savedOwnerLanguages, savedPhoneCountries, savedStemmers, savedTaskCategories, saveOwnerLanguages, saveStorePhoneCountries, stemmersOrigin, } from "../store/store.js";
12
+ import { accountGroupsOf, CRM_FILE_LIMITS, crmSettingsOf, DEFAULT_AGENT_CLOSE, DEFAULT_FIRST_PASS_PER_CHAT, DEFAULT_OWNER_LANGUAGES, firstPassPerChatOf, openStore, parseCrmSetting, parseCrmSettingValue, parseOwnerLanguages, saveCrmSetting, savedAgentClose, savedFirstPassPerChat, savedOwnerLanguages, savedPhoneCountries, savedStemmers, savedTaskCategories, saveOwnerLanguages, saveStorePhoneCountries, stemmersOrigin, } from "../store/store.js";
13
13
  const SCRIPTS = {
14
14
  "search_stemmers.cyrillic": "cyrillic",
15
15
  "search_stemmers.latin": "latin",
@@ -34,9 +34,19 @@ export const STORE_SETTINGS = [
34
34
  const GROUP_PREFIX = `${ACCOUNT_GROUPS_SETTING}.`;
35
35
  /**
36
36
  * A CRM account's: whether what it reports is a relationship or waits for review, what its company types mean, whose
37
- * deals and leads its sync copies, which stages open a task, and whether activities and tasks are read.
37
+ * deals and leads its sync copies, which stages open a task, whether activities and tasks are read, and the limits
38
+ * of downloading its files.
38
39
  */
39
- const CRM_SETTINGS = ["links", "company-types", "scope", "unassigned", "self", "stage-tasks", "activities"].map((name) => `crm.<provider>:<account>.${name}`);
40
+ const CRM_SETTINGS = [
41
+ "links",
42
+ "company-types",
43
+ "scope",
44
+ "unassigned",
45
+ "self",
46
+ "stage-tasks",
47
+ "activities",
48
+ ...Object.keys(CRM_FILE_LIMITS).map((name) => `files.${name}`),
49
+ ].map((name) => `crm.<provider>:<account>.${name}`);
40
50
  /**
41
51
  * The store settings a CLI offers. Phone countries, task rules and account groups belong to messages; a CLI that is
42
52
  * not a messenger would change them for tg and MAX without reading them itself.
@@ -51,7 +61,13 @@ export const offersStoreSetting = (app, setting) => app.messenger !== false || s
51
61
  */
52
62
  export const isOwnerOnlyStoreSetting = (setting) => {
53
63
  const name = parseCrmSetting(setting)?.name;
54
- return name === "scope" || name === "self" || name === "unassigned" || name === "stage-tasks" || name === "activities";
64
+ return (name === "scope" ||
65
+ name === "self" ||
66
+ name === "unassigned" ||
67
+ name === "stage-tasks" ||
68
+ name === "activities" ||
69
+ // An agent must not lift the limits on what it may download.
70
+ name?.startsWith("files.") === true);
55
71
  };
56
72
  export const isStoreSetting = (setting) => setting in SCRIPTS ||
57
73
  setting === OWNER_LANGUAGES ||
@@ -277,8 +293,11 @@ const CRM_DEFAULTS = {
277
293
  self: "",
278
294
  "stage-tasks": {},
279
295
  activities: "off",
296
+ ...Object.fromEntries(Object.entries(CRM_FILE_LIMITS).map(([name, range]) => [`files.${name}`, range.default])),
280
297
  };
281
298
  const crmNote = (name, now) => {
299
+ if (name.startsWith("files."))
300
+ return `store-wide — files sync and files download of that account keep to it from the next run`;
282
301
  if (name === "links")
283
302
  return `store-wide — the next sync of that account writes what it reports as ${now === "review" ? "proposals for the owner to review" : "reported relationships"}; relationships already stored stay`;
284
303
  if (name === "company-types")
@@ -5,6 +5,8 @@ import { type AppIdentity } from "../ports/app.js";
5
5
  * agent's own start, so a command the agent runs cannot name another, and only a locked run has one.
6
6
  */
7
7
  export declare const untrustedMarkOf: (app: AppIdentity, env: NodeJS.ProcessEnv) => string | undefined;
8
+ /** `untrustedMarkOf` for the app and environment the command runs in. */
9
+ export declare const runMarkOf: (command: Command) => string | undefined;
8
10
  /** Other people's text between the run's markers, with every bracket and the mark taken out, so it can close none. */
9
11
  export declare const marked: (text: string, mark: string, source: string, id?: string) => string;
10
12
  /**
@@ -1,4 +1,5 @@
1
1
  import { ancestorValue, envName, readOnlyLockOf } from "../ports/app.js";
2
+ import { environmentOf } from "./context.js";
2
3
  const OPEN = "⟦";
3
4
  const CLOSE = "⟧";
4
5
  /**
@@ -11,6 +12,11 @@ export const untrustedMarkOf = (app, env) => {
11
12
  const mark = ancestorValue(envName(app, "UNTRUSTED_MARK"), env);
12
13
  return mark && /^[0-9a-f]{16}$/.test(mark) ? mark : undefined;
13
14
  };
15
+ /** `untrustedMarkOf` for the app and environment the command runs in. */
16
+ export const runMarkOf = (command) => {
17
+ const { app, env } = environmentOf(command);
18
+ return app ? untrustedMarkOf(app, env ?? process.env) : undefined;
19
+ };
14
20
  /** Other people's text between the run's markers, with every bracket and the mark taken out, so it can close none. */
15
21
  export const marked = (text, mark, source, id) => {
16
22
  const inside = text.replaceAll(OPEN, "").replaceAll(CLOSE, "").replaceAll(mark, "");
@@ -0,0 +1,68 @@
1
+ import type { Command } from "commander";
2
+ import type { AppIdentity } from "../../ports/app.js";
3
+ import type { CrmFileLimits, CrmFileRow } from "../../store/store.js";
4
+ import type { CrmOpenableFile } from "../source.js";
5
+ import type { CrmRun, CrmWithin } from "./index.js";
6
+ /** `files download`'s own cap, and the most `--max-size` takes: Bitrix24's own largest file. */
7
+ export declare const DOWNLOAD_MB = 100;
8
+ export declare const MOST_DOWNLOAD_MB = 2048;
9
+ /** Where `files sync` is in its round, a sync state `config` never sets. */
10
+ export declare const FILES_ROUND = "crm:files-round";
11
+ export declare const FILES_DOWNLOAD_KEY = "files.download";
12
+ declare const SKIP_REASONS: readonly ["too-large", "run-files", "run-mb", "deadline", "disk-full", "unavailable"];
13
+ type SkipReason = (typeof SKIP_REASONS)[number];
14
+ export interface CrmFileContext {
15
+ app: AppIdentity;
16
+ run: CrmRun;
17
+ now: () => number;
18
+ signal?: AbortSignal;
19
+ }
20
+ export interface Downloaded {
21
+ row: CrmFileRow;
22
+ textStatus: string;
23
+ }
24
+ /**
25
+ * One file saved and read: under the account's folder (folders 700, file 600) or `dir`, its text through
26
+ * `extractText`, its row stored. A cut-off or refused download keeps no part, and no error names the link.
27
+ */
28
+ export declare const downloadCrmFile: (context: CrmFileContext, file: CrmOpenableFile, assignee: string | null, { capBytes, capMb, flag, dir, limits, }: {
29
+ capBytes: number;
30
+ capMb: number;
31
+ flag: boolean;
32
+ dir?: string;
33
+ limits: CrmFileLimits;
34
+ }) => Promise<Downloaded>;
35
+ export interface CrmFileCommandOptions {
36
+ within: CrmWithin;
37
+ example: (command: Command, ...lines: string[]) => Command;
38
+ app: AppIdentity;
39
+ /** The CRM has leads: `--lead` is offered. True when absent. */
40
+ leads?: boolean;
41
+ now: () => number;
42
+ }
43
+ /** `files list`, `files download` and `files sync` (NEED-2701 C, NEED-2708 B). */
44
+ export declare const addCrmFileCommands: (program: Command, options: CrmFileCommandOptions) => void;
45
+ export interface FilesSyncReport {
46
+ owners: number;
47
+ downloaded: {
48
+ id: string;
49
+ name: string;
50
+ size: number;
51
+ path: string;
52
+ text_status: string;
53
+ }[];
54
+ skipped: {
55
+ id: string;
56
+ name: string;
57
+ size: number | null;
58
+ reason: SkipReason;
59
+ }[];
60
+ complete: boolean;
61
+ stopped?: SkipReason;
62
+ }
63
+ /**
64
+ * One `files sync` run: the files of the sign-in's own deals and leads changed since the last complete round, and at
65
+ * most `files.days` back, newest first, under the run's limits. It stops at the first run limit and saves its place.
66
+ */
67
+ export declare const syncFiles: (context: CrmFileContext, outOfTime: () => boolean, deadline?: (ms: number) => AbortSignal) => Promise<FilesSyncReport>;
68
+ export {};