@wirecat/cli-core 0.685.0 → 0.687.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 (50) hide show
  1. package/CHANGELOG.md +78 -0
  2. package/dist/cli/account-remove.js +21 -3
  3. package/dist/cli/documents/testing/source-contract.js +18 -9
  4. package/dist/cli/messenger/store-maintenance-command.js +3 -2
  5. package/dist/crm/files.d.ts +16 -0
  6. package/dist/crm/files.js +56 -0
  7. package/dist/crm/foreign-contacts.d.ts +16 -4
  8. package/dist/crm/foreign-contacts.js +8 -4
  9. package/dist/crm/index.d.ts +2 -1
  10. package/dist/crm/index.js +2 -0
  11. package/dist/crm/source.d.ts +37 -0
  12. package/dist/crm/source.js +2 -1
  13. package/dist/crm/testing/index.d.ts +1 -1
  14. package/dist/crm/testing/index.js +1 -1
  15. package/dist/crm/testing/source.d.ts +31 -1
  16. package/dist/crm/testing/source.js +53 -1
  17. package/dist/crm/values.d.ts +2 -1
  18. package/dist/crm/values.js +4 -2
  19. package/dist/documents/model.d.ts +1 -0
  20. package/dist/meetings/cli/index.d.ts +1 -1
  21. package/dist/meetings/cli/index.js +10 -6
  22. package/dist/meetings/mcp/index.d.ts +15 -15
  23. package/dist/meetings/read-through.d.ts +2 -0
  24. package/dist/meetings/read-through.js +7 -2
  25. package/dist/meetings/source.d.ts +2 -2
  26. package/dist/oauth/storage.js +21 -4
  27. package/dist/search/lucene/resolved.d.ts +2 -0
  28. package/dist/services/documents/ingestion.d.ts +4 -1
  29. package/dist/services/documents/ingestion.js +11 -0
  30. package/dist/services/documents/knowledge.js +18 -3
  31. package/dist/services/documents/plan.js +26 -5
  32. package/dist/services/documents/ports.d.ts +2 -0
  33. package/dist/services/documents/sync.js +6 -1
  34. package/dist/services/embeddings-search.js +33 -11
  35. package/dist/store/accounts.d.ts +2 -1
  36. package/dist/store/exports.d.ts +1 -0
  37. package/dist/store/exports.js +1 -0
  38. package/dist/store/recover.js +2 -0
  39. package/dist/store/sqlite/account-purge.js +1 -0
  40. package/dist/store/sqlite/crm-files.d.ts +67 -0
  41. package/dist/store/sqlite/crm-files.js +172 -0
  42. package/dist/store/sqlite/lucene.js +11 -5
  43. package/dist/store/sqlite/manifest.js +2 -0
  44. package/dist/store/sqlite/migrations.generated.js +17 -0
  45. package/dist/store/sqlite/note-search.js +4 -3
  46. package/dist/store/sqlite/schema.d.ts +329 -0
  47. package/dist/store/sqlite/schema.js +28 -0
  48. package/dist/store/store.d.ts +3 -0
  49. package/dist/store/store.js +5 -0
  50. package/package.json +2 -2
@@ -123,6 +123,7 @@ export interface SourceIndex<M extends SourceFile = SourceFile> {
123
123
  settle?(options: {
124
124
  until: () => boolean;
125
125
  }): Promise<unknown>;
126
+ registerProfile?(name: string, principal: string): Promise<void>;
126
127
  }
127
128
  export interface SourceStatePort<M extends SourceFile = SourceFile> {
128
129
  read(): SourceState<M>;
@@ -52,7 +52,7 @@ export interface MeetingCommandDeps {
52
52
  * asks when the command's key is at `ask` and refuses when nobody can answer. Without it the writes refuse.
53
53
  */
54
54
  askFirst?: (command: Command) => Promise<void>;
55
- /** The run's stop signal; the meeting writes and `meetings invitation` pass it to the service. */
55
+ /** The run's stop signal; `list`, `show`, the meeting writes and `meetings invitation` pass it to the service. */
56
56
  signal?: () => AbortSignal | undefined;
57
57
  }
58
58
  export { addMeetingPassageCommand, createMeetingPassageCommand, type MeetingPassageFlags, meetingPassageRequest, } from "./passage.js";
@@ -50,12 +50,16 @@ const addMeetingCommandsDefinition = (program, deps) => {
50
50
  const opts = command.optsWithGlobals();
51
51
  deps.write(value, opts.json ? "json" : opts.jsonl ? "jsonl" : "text");
52
52
  };
53
- const access = (command, backend) => ({
54
- ...(backend === undefined ? {} : { backend }),
55
- offline: command.optsWithGlobals().offline === true,
56
- timezone: timezoneOf(deps.timezone),
57
- ...(deps.now ? { now: deps.now() } : {}),
58
- });
53
+ const access = (command, backend) => {
54
+ const signal = deps.signal?.();
55
+ return {
56
+ ...(backend === undefined ? {} : { backend }),
57
+ offline: command.optsWithGlobals().offline === true,
58
+ timezone: timezoneOf(deps.timezone),
59
+ ...(deps.now ? { now: deps.now() } : {}),
60
+ ...(signal ? { signal } : {}),
61
+ };
62
+ };
59
63
  const list = queryWordsAfterOptions(group.command("list").description("meetings, newest first: the service's and the stored ones, kept in the store"))
60
64
  .argument("[query...]", "field:value terms that narrow the list — the fields are below")
61
65
  .addHelpText("after", `\n${fieldsHelp(MEETING_QUERY, MEETING_QUERY_GUIDE)}\n${BACKEND_HELP}`);
@@ -38,7 +38,6 @@ export declare const meetingTools: ({
38
38
  max_read_bytes?: undefined;
39
39
  cursor?: undefined;
40
40
  } | {
41
- limit?: undefined;
42
41
  event_id?: undefined;
43
42
  series_id?: undefined;
44
43
  page?: undefined;
@@ -54,11 +53,11 @@ export declare const meetingTools: ({
54
53
  format?: undefined;
55
54
  transcript_id?: undefined;
56
55
  query?: undefined;
56
+ limit?: undefined;
57
57
  scan_limit?: undefined;
58
58
  max_read_bytes?: undefined;
59
59
  cursor?: undefined;
60
60
  } | {
61
- limit?: undefined;
62
61
  event_id?: undefined;
63
62
  series_id?: undefined;
64
63
  page?: undefined;
@@ -76,11 +75,11 @@ export declare const meetingTools: ({
76
75
  format?: undefined;
77
76
  transcript_id?: undefined;
78
77
  query?: undefined;
78
+ limit?: undefined;
79
79
  scan_limit?: undefined;
80
80
  max_read_bytes?: undefined;
81
81
  cursor?: undefined;
82
82
  } | {
83
- limit?: undefined;
84
83
  event_id?: undefined;
85
84
  series_id?: undefined;
86
85
  page?: undefined;
@@ -102,6 +101,7 @@ export declare const meetingTools: ({
102
101
  minimum: number;
103
102
  };
104
103
  query?: undefined;
104
+ limit?: undefined;
105
105
  scan_limit?: undefined;
106
106
  max_read_bytes?: undefined;
107
107
  cursor?: undefined;
@@ -188,7 +188,6 @@ export declare const meetingTools: ({
188
188
  max_read_bytes?: undefined;
189
189
  cursor?: undefined;
190
190
  } | {
191
- limit?: undefined;
192
191
  event_id?: undefined;
193
192
  series_id?: undefined;
194
193
  page?: undefined;
@@ -204,11 +203,11 @@ export declare const meetingTools: ({
204
203
  format?: undefined;
205
204
  transcript_id?: undefined;
206
205
  query?: undefined;
206
+ limit?: undefined;
207
207
  scan_limit?: undefined;
208
208
  max_read_bytes?: undefined;
209
209
  cursor?: undefined;
210
210
  } | {
211
- limit?: undefined;
212
211
  event_id?: undefined;
213
212
  series_id?: undefined;
214
213
  page?: undefined;
@@ -226,11 +225,11 @@ export declare const meetingTools: ({
226
225
  format?: undefined;
227
226
  transcript_id?: undefined;
228
227
  query?: undefined;
228
+ limit?: undefined;
229
229
  scan_limit?: undefined;
230
230
  max_read_bytes?: undefined;
231
231
  cursor?: undefined;
232
232
  } | {
233
- limit?: undefined;
234
233
  event_id?: undefined;
235
234
  series_id?: undefined;
236
235
  page?: undefined;
@@ -252,6 +251,7 @@ export declare const meetingTools: ({
252
251
  minimum: number;
253
252
  };
254
253
  query?: undefined;
254
+ limit?: undefined;
255
255
  scan_limit?: undefined;
256
256
  max_read_bytes?: undefined;
257
257
  cursor?: undefined;
@@ -338,7 +338,6 @@ export declare const meetingTools: ({
338
338
  max_read_bytes?: undefined;
339
339
  cursor?: undefined;
340
340
  } | {
341
- limit?: undefined;
342
341
  event_id?: undefined;
343
342
  series_id?: undefined;
344
343
  page?: undefined;
@@ -354,11 +353,11 @@ export declare const meetingTools: ({
354
353
  format?: undefined;
355
354
  transcript_id?: undefined;
356
355
  query?: undefined;
356
+ limit?: undefined;
357
357
  scan_limit?: undefined;
358
358
  max_read_bytes?: undefined;
359
359
  cursor?: undefined;
360
360
  } | {
361
- limit?: undefined;
362
361
  event_id?: undefined;
363
362
  series_id?: undefined;
364
363
  page?: undefined;
@@ -376,11 +375,11 @@ export declare const meetingTools: ({
376
375
  format?: undefined;
377
376
  transcript_id?: undefined;
378
377
  query?: undefined;
378
+ limit?: undefined;
379
379
  scan_limit?: undefined;
380
380
  max_read_bytes?: undefined;
381
381
  cursor?: undefined;
382
382
  } | {
383
- limit?: undefined;
384
383
  event_id?: undefined;
385
384
  series_id?: undefined;
386
385
  page?: undefined;
@@ -402,6 +401,7 @@ export declare const meetingTools: ({
402
401
  minimum: number;
403
402
  };
404
403
  query?: undefined;
404
+ limit?: undefined;
405
405
  scan_limit?: undefined;
406
406
  max_read_bytes?: undefined;
407
407
  cursor?: undefined;
@@ -488,7 +488,6 @@ export declare const meetingTools: ({
488
488
  max_read_bytes?: undefined;
489
489
  cursor?: undefined;
490
490
  } | {
491
- limit?: undefined;
492
491
  event_id?: undefined;
493
492
  series_id?: undefined;
494
493
  page?: undefined;
@@ -504,11 +503,11 @@ export declare const meetingTools: ({
504
503
  format?: undefined;
505
504
  transcript_id?: undefined;
506
505
  query?: undefined;
506
+ limit?: undefined;
507
507
  scan_limit?: undefined;
508
508
  max_read_bytes?: undefined;
509
509
  cursor?: undefined;
510
510
  } | {
511
- limit?: undefined;
512
511
  event_id?: undefined;
513
512
  series_id?: undefined;
514
513
  page?: undefined;
@@ -526,11 +525,11 @@ export declare const meetingTools: ({
526
525
  format?: undefined;
527
526
  transcript_id?: undefined;
528
527
  query?: undefined;
528
+ limit?: undefined;
529
529
  scan_limit?: undefined;
530
530
  max_read_bytes?: undefined;
531
531
  cursor?: undefined;
532
532
  } | {
533
- limit?: undefined;
534
533
  event_id?: undefined;
535
534
  series_id?: undefined;
536
535
  page?: undefined;
@@ -552,6 +551,7 @@ export declare const meetingTools: ({
552
551
  minimum: number;
553
552
  };
554
553
  query?: undefined;
554
+ limit?: undefined;
555
555
  scan_limit?: undefined;
556
556
  max_read_bytes?: undefined;
557
557
  cursor?: undefined;
@@ -638,7 +638,6 @@ export declare const meetingTools: ({
638
638
  max_read_bytes?: undefined;
639
639
  cursor?: undefined;
640
640
  } | {
641
- limit?: undefined;
642
641
  event_id?: undefined;
643
642
  series_id?: undefined;
644
643
  page?: undefined;
@@ -654,11 +653,11 @@ export declare const meetingTools: ({
654
653
  format?: undefined;
655
654
  transcript_id?: undefined;
656
655
  query?: undefined;
656
+ limit?: undefined;
657
657
  scan_limit?: undefined;
658
658
  max_read_bytes?: undefined;
659
659
  cursor?: undefined;
660
660
  } | {
661
- limit?: undefined;
662
661
  event_id?: undefined;
663
662
  series_id?: undefined;
664
663
  page?: undefined;
@@ -676,11 +675,11 @@ export declare const meetingTools: ({
676
675
  format?: undefined;
677
676
  transcript_id?: undefined;
678
677
  query?: undefined;
678
+ limit?: undefined;
679
679
  scan_limit?: undefined;
680
680
  max_read_bytes?: undefined;
681
681
  cursor?: undefined;
682
682
  } | {
683
- limit?: undefined;
684
683
  event_id?: undefined;
685
684
  series_id?: undefined;
686
685
  page?: undefined;
@@ -702,6 +701,7 @@ export declare const meetingTools: ({
702
701
  minimum: number;
703
702
  };
704
703
  query?: undefined;
704
+ limit?: undefined;
705
705
  scan_limit?: undefined;
706
706
  max_read_bytes?: undefined;
707
707
  cursor?: undefined;
@@ -35,6 +35,8 @@ export interface MeetingServerAccess {
35
35
  offline?: boolean;
36
36
  now?: number;
37
37
  timezone?: string;
38
+ /** The run's stop signal: handed to the service, and a stopped read never answers from the store instead. */
39
+ signal?: AbortSignal;
38
40
  }
39
41
  type FoundIn = NonNullable<MeetingItem["found_in"]>;
40
42
  interface ServerStep {
@@ -183,15 +183,18 @@ export const askServerForList = async (source, store, accountId, query, access)
183
183
  for (const call of asked) {
184
184
  let cursor = null;
185
185
  for (let page = 0; page < MEETING_SERVER_BOUNDS.pages; page++) {
186
+ access.signal?.throwIfAborted();
186
187
  step.report.calls += 1;
187
188
  let answer;
188
189
  try {
189
- answer = await source.find(call.window, call.terms, cursor);
190
+ answer = await source.find(call.window, call.terms, cursor, access.signal);
190
191
  }
191
192
  catch (error) {
193
+ access.signal?.throwIfAborted();
192
194
  return skip(reasonOf(error), error);
193
195
  }
194
196
  for (const found of answer.meetings) {
197
+ access.signal?.throwIfAborted();
195
198
  if (seen.has(found.meeting.occurrence.id))
196
199
  continue;
197
200
  seen.add(found.meeting.occurrence.id);
@@ -324,12 +327,14 @@ export const meetingShowThrough = async (source, store, accountId, meeting, acce
324
327
  return fromStore("unsupported");
325
328
  if (access.offline)
326
329
  return fromStore("offline");
330
+ access.signal?.throwIfAborted();
327
331
  step.report.calls = 1;
328
332
  let full;
329
333
  try {
330
- full = await source.get(providerId);
334
+ full = await source.get(providerId, access.signal);
331
335
  }
332
336
  catch (error) {
337
+ access.signal?.throwIfAborted();
333
338
  return fromStore(reasonOf(error), error);
334
339
  }
335
340
  if (!full) {
@@ -84,7 +84,7 @@ export interface MeetingSource {
84
84
  * The meetings that may match, for `meetings list`: one page from `cursor` (`null` first). Each meeting's
85
85
  * `occurrence.id` is the one `meetings()` gives, so the row it is kept as is the row `sync` writes.
86
86
  */
87
- find?(window: MeetingWindow, terms: readonly MeetingTerm[], cursor: string | null): Promise<FoundMeetings>;
87
+ find?(window: MeetingWindow, terms: readonly MeetingTerm[], cursor: string | null, signal?: AbortSignal): Promise<FoundMeetings>;
88
88
  /** One meeting by the service's id, for `meetings show`; `null` when the service has none. */
89
- get?(id: string): Promise<FullMeeting | null>;
89
+ get?(id: string, signal?: AbortSignal): Promise<FullMeeting | null>;
90
90
  }
@@ -198,8 +198,9 @@ export const zoomTokenCodec = {
198
198
  });
199
199
  },
200
200
  };
201
- // The keyring's own words go to `--debug` and the run record as the cause, never into the answer; a store that
202
- // echoes what it was handed loses the secret from them first.
201
+ // On a write or a removal the keyring's own words go to `--debug` and the run record as the cause, never into the
202
+ // answer; a store that echoes what it was handed loses the secret from them first. A read's failure is cli-base's own
203
+ // keyring.unreachable, which names the platform's reason.
203
204
  const keyringFailure = (thrown, secret) => {
204
205
  const failure = new CliError("configuration_error", "could not reach the saved sign-in; use an available keyring or file storage", { reason: "oauth.not-saved" });
205
206
  const words = thrown instanceof Error ? thrown.message : String(thrown);
@@ -221,9 +222,25 @@ export const credentialStorage = (options) => {
221
222
  return credentials.read(name)?.secret;
222
223
  }
223
224
  catch (error) {
225
+ // cli-base's own error already says what to do, in words safe for the answer.
226
+ if (error instanceof CliError)
227
+ throw error;
224
228
  throw keyringFailure(error);
225
229
  }
226
230
  };
231
+ // A sign-in on a machine with no keyring writes to the file, so an old entry it cannot read is no old entry. With
232
+ // `storage: "keyring"` there is no file to fall back on: the save would fail too, after the browser.
233
+ const fallsBack = options.credentials.storage !== "keyring";
234
+ const replaced = (name) => {
235
+ try {
236
+ return raw(name);
237
+ }
238
+ catch (error) {
239
+ if (fallsBack && error instanceof CliError && error.details.reason === "keyring.unreachable")
240
+ return undefined;
241
+ throw error;
242
+ }
243
+ };
227
244
  const save = (value, writeOptions) => {
228
245
  try {
229
246
  credentials.write(account, value, writeOptions);
@@ -252,13 +269,13 @@ export const credentialStorage = (options) => {
252
269
  moved,
253
270
  ...(codec.rotating ? { rotating: true } : {}),
254
271
  probe: () => {
255
- raw(account);
272
+ replaced(account);
256
273
  },
257
274
  read: () => {
258
275
  const value = current();
259
276
  return value === undefined ? undefined : codec.decode(value);
260
277
  },
261
- write: (input, writeOptions) => save(codec.encode({ ...input, previous: raw(account), ...(writeOptions?.signIn ? { signIn: true } : {}) }), writeOptions),
278
+ write: (input, writeOptions) => save(codec.encode({ ...input, previous: replaced(account), ...(writeOptions?.signIn ? { signIn: true } : {}) }), writeOptions),
262
279
  remove: () => {
263
280
  try {
264
281
  return credentials.remove(account);
@@ -38,6 +38,8 @@ export interface QueryExecution {
38
38
  id: string;
39
39
  }[];
40
40
  limit: number;
41
+ /** At most this many hits from one chat, so a large chat cannot fill the page; counts and groups ignore it. */
42
+ perChat?: number;
41
43
  newest?: boolean;
42
44
  signal?: AbortSignal;
43
45
  timeLimitMs?: number;
@@ -6,13 +6,16 @@ export interface IngestionOptions<M extends SourceFile> {
6
6
  * `{ provider, account: principal }`. Without it they live in a notes folder named `collectionName(principal)`.
7
7
  */
8
8
  provider?: string;
9
+ /** The CLI's command (`notion`), which names its profiles: with `provider`, a sync records which account each is. */
10
+ command?: string;
9
11
  collectionName?(principal: string): string;
10
12
  externalId(id: string): string;
11
13
  catalogInput(file: M): CatalogInput;
12
14
  frontMatter(content: SourceContent<M>): Record<string, unknown>;
13
15
  observed?(principal: string, file: M, documentId: string): Promise<void>;
14
16
  }
15
- export declare const documentIngestion: <M extends SourceFile>(store: Pick<MessageStore, "notes" | "catalog" | "memories">, options: IngestionOptions<M>) => {
17
+ export declare const documentIngestion: <M extends SourceFile>(store: Pick<MessageStore, "notes" | "catalog" | "memories" | "accounts">, options: IngestionOptions<M>) => {
18
+ registerProfile?: ((name: string, principal: string) => Promise<void>) | undefined;
16
19
  catalog: {
17
20
  import: (principal: string, files: M[]) => Promise<{
18
21
  entries: number;
@@ -25,7 +25,18 @@ export const documentIngestion = (store, options) => {
25
25
  }
26
26
  }
27
27
  };
28
+ const { provider, command } = options;
28
29
  return {
30
+ // Only where both are known: a sync calls it whenever it is there and a profile is given.
31
+ ...(provider && command
32
+ ? {
33
+ /** Names the profile's account in the store, so a search hit says `notion`/`work`, not `notes`/`1`. */
34
+ registerProfile: async (name, principal) => {
35
+ await folder(principal, true);
36
+ await store.accounts.saveProfile(command, name, { provider, account: principal });
37
+ },
38
+ }
39
+ : {}),
29
40
  catalog: {
30
41
  import: async (principal, files) => {
31
42
  const selected = await folder(principal, true);
@@ -76,11 +76,26 @@ export const documentKnowledge = (store, folder) => {
76
76
  },
77
77
  addLink: async (principal, ref, input) => {
78
78
  await document(principal, ref);
79
- return store.notes.addLink({ ...input, from: ref, origin: input.by === "owner" ? "owner" : "suggested" });
79
+ const by = writer(input.by);
80
+ const link = await store.notes.addLink({
81
+ ...input,
82
+ from: ref,
83
+ ...(by === "owner"
84
+ ? { origin: "owner" }
85
+ : { origin: "suggested", confirmed: false, provenance: `agent:${by.bot}: ${by.reason.trim()}` }),
86
+ });
87
+ // The store answers an agent's pending link for the same pair; the owner adding it is the owner confirming it.
88
+ if (by !== "owner" || link.confirmed)
89
+ return link;
90
+ return (await store.knowledge.decideSuggestedLink(link.id, { confirm: true, by })) ?? link;
80
91
  },
81
92
  removeLink: async (principal, ref, id, by) => {
82
- const links = await port.links(principal, ref);
83
- if (!links.some((link) => link.id === id && link.origin === "owner"))
93
+ const link = (await port.links(principal, ref)).find((item) => item.id === id);
94
+ if (link && !link.confirmed) {
95
+ await store.knowledge.decideSuggestedLink(id, { confirm: false, by });
96
+ return { id, removed: true };
97
+ }
98
+ if (link?.origin !== "owner")
84
99
  throw new CliError("not_found", "owner link is not attached to this document");
85
100
  return store.notes.removeLink(id, by);
86
101
  },
@@ -78,7 +78,16 @@ export const planDocuments = async (options, source, state, roots, limit, pictur
78
78
  const walked = (id) => !initial && state.folders[id] !== undefined && !state.folders[id]?.trashed;
79
79
  let walk = resumed;
80
80
  let cursor = state.cursor ?? "";
81
+ // Each read takes a request from the budget, the start token and a root's own metadata as much as a listing: a run
82
+ // that left them out would reach its deadline with no margin.
83
+ const charge = () => {
84
+ const taken = options.signal?.aborted ? "cancelled" : budget?.take();
85
+ return taken === "deadline" && budget?.first?.() ? null : (taken ?? null);
86
+ };
81
87
  if (!walk && initial) {
88
+ const before = charge();
89
+ if (before)
90
+ return { walk: { folders_left: roots.length, entries: 0, listed: 0, stopped: before } };
82
91
  const start = await source.startToken();
83
92
  walk = {
84
93
  scope,
@@ -91,6 +100,11 @@ export const planDocuments = async (options, source, state, roots, limit, pictur
91
100
  };
92
101
  }
93
102
  else if (!walk) {
103
+ // The roots' metadata below stays free: a run stopped between them and the changes would read the same page again
104
+ // in every call.
105
+ const before = charge();
106
+ if (before)
107
+ return { walk: { folders_left: 0, entries: 0, listed: 0, stopped: before } };
94
108
  const page = await source.changes(cursor);
95
109
  const latest = new Map(page.items.map((change) => [change.id, change]));
96
110
  const entering = [];
@@ -195,11 +209,18 @@ export const planDocuments = async (options, source, state, roots, limit, pictur
195
209
  stopped = taken === "deadline" && budget?.first?.() ? null : (taken ?? null);
196
210
  if (stopped)
197
211
  break;
198
- const folder = step.folder ?? (await source.metadata(step.id));
199
- if (!step.folder && (!isFolder(folder) || folder.trashed))
200
- throw new CliError("validation_error", "configured root is not an accessible folder");
201
- if (!step.folder)
202
- container(folder);
212
+ if (!step.folder) {
213
+ const root = await source.metadata(step.id);
214
+ if (!isFolder(root) || root.trashed)
215
+ throw new CliError("validation_error", "configured root is not an accessible folder");
216
+ container(root);
217
+ // Kept on the step, so a call stopped before the listing does not read the root again.
218
+ step.folder = root;
219
+ stopped = charge();
220
+ if (stopped)
221
+ break;
222
+ }
223
+ const folder = step.folder;
203
224
  let children;
204
225
  let more;
205
226
  try {
@@ -7,6 +7,8 @@ export interface SyncOptions<M extends SourceFile> {
7
7
  index: SourceIndex<M>;
8
8
  state: SourceStatePort<M>;
9
9
  principal: string;
10
+ /** The profile being synced, recorded against `principal` once the signed-in account is checked. */
11
+ profile?: string;
10
12
  roots: string[];
11
13
  query?: SourceQuery<M>;
12
14
  textLimit: number;
@@ -46,6 +46,8 @@ export const syncDocuments = async (options) => {
46
46
  const state = statePort.read();
47
47
  if (state.principal !== principal)
48
48
  throw new CliError("configuration_error", "sync state belongs to another source account");
49
+ if (options.profile !== undefined)
50
+ await index.registerProfile?.(options.profile, principal);
49
51
  const currentScope = scopeHash(profile.roots, query, options.isDocument !== undefined);
50
52
  if (state.pending && (state.pending.scope !== currentScope || rescan)) {
51
53
  // Work the new plan cannot see: a file saved to the index before its state was.
@@ -219,7 +221,10 @@ export const syncDocuments = async (options) => {
219
221
  const safe = errorOf(error);
220
222
  if (safe.code === "cancelled")
221
223
  throw safe;
222
- if (job.kind === "save" && (safe.code === "not_found" || safe.code === "validation_error")) {
224
+ // A file the sign-in may not read is skipped as a gone one is: retried on every sync, it would hold the pass,
225
+ // and the change cursor with it, for good.
226
+ if (job.kind === "save" &&
227
+ (safe.code === "not_found" || safe.code === "permission_error" || safe.code === "validation_error")) {
223
228
  const skipped = {
224
229
  id: job.id,
225
230
  reason: safe.message,
@@ -13,6 +13,14 @@ import { MAIL } from "./search-kind.js";
13
13
  import { refreshSearch } from "./search-refresh.js";
14
14
  /** How deep each list is read before the two are merged. */
15
15
  const CANDIDATES = 50;
16
+ /** Conversations the meaning half reads across chats before it gives each chat its share. */
17
+ const ACROSS_CHATS = 500;
18
+ /**
19
+ * What one chat brings to each list when several are searched, so a large chat cannot fill them. Its meaning hits
20
+ * count by how far they lead its 20th best: a large chat holds some text near any question, and a small chat's
21
+ * clear best must not lose to that.
22
+ */
23
+ const PER_CHAT = 20;
16
24
  /** Messages the word search reads: one long thread can hold many of them. */
17
25
  const WORD_HITS = 200;
18
26
  /** Reciprocal rank fusion's usual constant (phase 5 E9). */
@@ -42,6 +50,7 @@ export const embeddingsSearch = (deps) => {
42
50
  }, deps.messenger);
43
51
  const { items } = await store.queries.matchQuery({
44
52
  ...lexical.execution,
53
+ perChat: PER_CHAT,
45
54
  ...(prepared.selectedChat ? { chat: prepared.selectedChat } : {}),
46
55
  ...(conversations === undefined ? {} : { conversationIds: conversations }),
47
56
  ...(since === undefined ? {} : { conversationSince: Date.parse(since) }),
@@ -184,17 +193,16 @@ export const embeddingsSearch = (deps) => {
184
193
  const scope = scopeOf(one);
185
194
  if (scope === null)
186
195
  continue;
196
+ // One chat needs no share, and mail's threads are too many to share among.
197
+ const whole = "chatId" in scope || one.provider === MAIL;
187
198
  const hits = await store.vectors.nearestConversations(one, {
188
199
  ...scope,
189
200
  ...(since === undefined ? {} : { since }),
190
201
  model: target.key,
191
- limit: Math.max(limit, CANDIDATES),
202
+ limit: whole ? Math.max(limit, CANDIDATES) : Math.max(limit, ACROSS_CHATS),
192
203
  query: vector,
193
204
  ...(eligibility ? { conversations: eligibility.conversations } : {}),
194
205
  });
195
- for (const hit of hits)
196
- sources.set(hit.summary.id, one);
197
- meaning.push(...hits);
198
206
  const images = await store.vectors.nearestImages(one, {
199
207
  ...scope,
200
208
  ...(since === undefined ? {} : { since }),
@@ -202,16 +210,17 @@ export const embeddingsSearch = (deps) => {
202
210
  limit: Math.max(limit, CANDIDATES),
203
211
  query: vector,
204
212
  });
205
- for (const hit of images) {
206
- if (eligibility && !eligibility.conversations.includes(hit.summary.id))
207
- continue;
213
+ const found = [
214
+ ...hits,
215
+ ...images.filter((hit) => !eligibility || eligibility.conversations.includes(hit.summary.id)),
216
+ ].sort((a, b) => b.score - a.score);
217
+ for (const hit of found)
208
218
  sources.set(hit.summary.id, one);
209
- meaning.push(hit);
210
- }
219
+ meaning.push(...(whole ? found.map((hit) => ({ hit, lead: hit.score })) : shared(found, limit)));
211
220
  }
212
221
  });
213
222
  }
214
- meaning.sort((a, b) => b.score - a.score);
223
+ meaning.sort((a, b) => b.lead - a.lead);
215
224
  const scoped = [];
216
225
  const elsewhere = [];
217
226
  for (const one of prepared.scopeAccounts) {
@@ -245,7 +254,7 @@ export const embeddingsSearch = (deps) => {
245
254
  model: target.id,
246
255
  meaning: target.installed ? "searched" : "unavailable",
247
256
  ...(wordsOutOfTime ? { words: "out-of-time" } : {}),
248
- hits: fused(meaning, words.hits, meaningFloor(target.key))
257
+ hits: fused(meaning.map(({ hit }) => hit), words.hits, meaningFloor(target.key))
249
258
  .slice(0, limit)
250
259
  .map((hit) => {
251
260
  const source = sources.get(hit.summary.id);
@@ -298,6 +307,19 @@ export const embeddingsSearch = (deps) => {
298
307
  },
299
308
  };
300
309
  };
310
+ /**
311
+ * Each chat's best hits, as many as the page holds, with each one's lead over the chat's `PER_CHAT`th best (or its
312
+ * last, in a chat with fewer).
313
+ */
314
+ const shared = (hits, limit) => {
315
+ const chats = new Map();
316
+ for (const hit of hits)
317
+ chats.set(hit.summary.chatId, [...(chats.get(hit.summary.chatId) ?? []), hit]);
318
+ return [...chats.values()].flatMap((own) => {
319
+ const level = own[Math.min(PER_CHAT, own.length) - 1]?.score ?? 0;
320
+ return own.slice(0, Math.max(limit, PER_CHAT)).map((hit) => ({ hit, lead: hit.score - level }));
321
+ });
322
+ };
301
323
  /** Reciprocal rank fusion of the two lists: each conversation scores 1 / (k + rank) in every list it is in. */
302
324
  const fused = (meaning, words, minimumCosine) => {
303
325
  const merged = new Map();
@@ -17,7 +17,8 @@ export interface AccountAccounts {
17
17
  accountName(key: AccountKey): Promise<string | null>;
18
18
  /**
19
19
  * Everything one account holds — its chats, messages, members, state, leases, transcripts and whom
20
- * it has seen — for `cache clear`. Other accounts, and identities they share, stay.
20
+ * it has seen — for `cache clear`. Other accounts, and identities they share, stay. The store never touches a file
21
+ * on disk: `account remove` deletes the downloaded CRM files `crmFiles.savedPaths` names.
21
22
  */
22
23
  purge(key: AccountKey): Promise<void>;
23
24
  }
@@ -28,6 +28,7 @@ export { CHAT_LIST_KEY, type ChatCompleteness, type ChatCoverage, fetchedKey, hi
28
28
  export { CONVERSATION_COLUMNS } from "./sqlite/conversations.js";
29
29
  export { type CopyViewer, seenBy } from "./sqlite/copy-viewer.js";
30
30
  export type { CounterTarget } from "./sqlite/counters.js";
31
+ export { type CrmFileHit, type CrmFileRow, type CrmFileSearch, type CrmFileStore, resetCrmFileWords, } from "./sqlite/crm-files.js";
31
32
  export { crmSettingsOf, parseCrmSetting, parseCrmSettingValue, saveCrmSetting } from "./sqlite/crm-settings.js";
32
33
  export { type EmailMarks, MAIL_AGENDA_COLUMNS, type MarkedEmail, type NewestEmail, type ThreadActivity, } from "./sqlite/email-activity.js";
33
34
  export { messageOfEmail, threadConversation } from "./sqlite/emails.js";
@@ -9,6 +9,7 @@ export { storeClients } from "./sqlite/clients.js";
9
9
  export { CHAT_LIST_KEY, fetchedKey, historyStartKey, } from "./sqlite/completeness.js";
10
10
  export { CONVERSATION_COLUMNS } from "./sqlite/conversations.js";
11
11
  export { seenBy } from "./sqlite/copy-viewer.js";
12
+ export { resetCrmFileWords, } from "./sqlite/crm-files.js";
12
13
  export { crmSettingsOf, parseCrmSetting, parseCrmSettingValue, saveCrmSetting } from "./sqlite/crm-settings.js";
13
14
  export { MAIL_AGENDA_COLUMNS, } from "./sqlite/email-activity.js";
14
15
  export { messageOfEmail, threadConversation } from "./sqlite/emails.js";