@wirecat/cli-core 0.660.0 → 0.662.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 (79) hide show
  1. package/CHANGELOG.md +89 -0
  2. package/dist/attachments/markup.js +2 -11
  3. package/dist/calendar/mcp/index.js +23 -17
  4. package/dist/cli/ai-model-command.js +3 -3
  5. package/dist/cli/bot/api-http.d.ts +43 -0
  6. package/dist/cli/bot/api-http.js +160 -0
  7. package/dist/cli/command-availability.d.ts +1 -1
  8. package/dist/cli/command-availability.js +4 -4
  9. package/dist/cli/dry-run-guard.js +7 -5
  10. package/dist/cli/early-refusal.d.ts +1 -1
  11. package/dist/cli/early-refusal.js +2 -2
  12. package/dist/cli/effects.d.ts +9 -2
  13. package/dist/cli/effects.js +16 -4
  14. package/dist/cli/index.d.ts +2 -1
  15. package/dist/cli/index.js +2 -1
  16. package/dist/cli/messenger/admin-moderation-command.js +2 -2
  17. package/dist/cli/messenger/archive-commands.js +2 -2
  18. package/dist/cli/messenger/context.d.ts +2 -2
  19. package/dist/cli/messenger/context.js +5 -3
  20. package/dist/cli/messenger/rankings-command.js +2 -1
  21. package/dist/cli/messenger/serve-command.js +7 -2
  22. package/dist/cli/messenger/tasks-command.d.ts +7 -2
  23. package/dist/cli/messenger/tasks-command.js +8 -4
  24. package/dist/cli/preview.js +3 -5
  25. package/dist/cli/program.js +2 -2
  26. package/dist/cli/schedule/schedule-command.js +3 -0
  27. package/dist/cli/shadowed-options.d.ts +7 -0
  28. package/dist/cli/shadowed-options.js +26 -0
  29. package/dist/crm/cli/index.js +4 -2
  30. package/dist/domain/html-entities.d.ts +5 -0
  31. package/dist/domain/html-entities.js +56 -0
  32. package/dist/domain/locator.js +12 -4
  33. package/dist/domain/references.js +11 -3
  34. package/dist/entities/listings.d.ts +4 -4
  35. package/dist/entities/listings.js +2 -2
  36. package/dist/kit/sync-after-install.d.ts +10 -1
  37. package/dist/kit/sync-after-install.js +35 -11
  38. package/dist/mail/headers.js +3 -3
  39. package/dist/mail/parse.js +9 -8
  40. package/dist/mail/resume.d.ts +4 -1
  41. package/dist/mail/resume.js +11 -2
  42. package/dist/mail/retry.d.ts +2 -1
  43. package/dist/mail/retry.js +6 -4
  44. package/dist/mail/sender-scores.js +1 -6
  45. package/dist/mail/server-search.js +3 -3
  46. package/dist/mail/stored.d.ts +4 -1
  47. package/dist/mail/stored.js +6 -1
  48. package/dist/mail/sync.js +8 -3
  49. package/dist/mail/testing/fake.d.ts +2 -0
  50. package/dist/mail/testing/fake.js +3 -1
  51. package/dist/mcp/all-profiles.js +8 -18
  52. package/dist/mcp/app-server.js +1 -16
  53. package/dist/mcp/bot/server.js +9 -7
  54. package/dist/mcp/caller.js +2 -1
  55. package/dist/mcp/prompts.js +17 -2
  56. package/dist/mcp/server.js +14 -20
  57. package/dist/mcp/stdio-wire.d.ts +5 -2
  58. package/dist/mcp/stdio-wire.js +39 -12
  59. package/dist/mcp/tool.js +6 -4
  60. package/dist/mcp/tools/messages-photo.js +4 -2
  61. package/dist/meetings/cli/search.js +8 -2
  62. package/dist/meetings/hit-query.js +11 -6
  63. package/dist/meetings/mcp/index.d.ts +15 -15
  64. package/dist/sends/guard.js +11 -21
  65. package/dist/sends/keyed-guard.d.ts +1 -1
  66. package/dist/sends/keyed-guard.js +2 -1
  67. package/dist/sends/permissions.d.ts +14 -0
  68. package/dist/sends/permissions.js +32 -0
  69. package/dist/services/listings.js +2 -1
  70. package/dist/services/message-resolution.js +6 -3
  71. package/dist/services/server-search.js +1 -1
  72. package/dist/store/sqlite/mention-drain.d.ts +4 -1
  73. package/dist/store/sqlite/mention-drain.js +7 -3
  74. package/dist/store/sqlite/messages.js +12 -1
  75. package/dist/store/sqlite/query-filter.d.ts +1 -0
  76. package/dist/store/sqlite/query-filter.js +2 -2
  77. package/dist/store/sqlite/tags.js +1 -1
  78. package/package.json +1 -1
  79. package/parity.json +2 -1
@@ -22,14 +22,16 @@ export const messagesPhotoTools = (messenger) => ({
22
22
  input: v.object({
23
23
  chat: chatOf(messenger),
24
24
  message,
25
- index: v.optional(v.pipe(v.number(), v.integer(), v.minValue(0), v.description("attachment index from 0; omit for the first photo"))),
25
+ attachment: v.optional(v.pipe(v.number(), v.integer(), v.minValue(1), v.description("which file of the message, from 1; omit for the first photo"))),
26
26
  }),
27
27
  annotations: READ,
28
28
  online: async (adapter, args, defaults) => {
29
29
  const { id: chatId } = await adapter.resolve(args.chat);
30
30
  const saveIt = `the owner can save it with \`${typedCommand(messenger.app.command, `messages download ${chatId} ${args.message}`)}\``;
31
31
  const { files } = await capability(adapter, "download", "download attachments")(chatId, args.message);
32
- const photo = args.index === undefined ? files.find((file) => file.kind === "photo") : files[args.index];
32
+ if (args.attachment !== undefined && args.attachment > files.length)
33
+ throw new CliError("not_found", `message ${args.message} has ${files.length} file${files.length === 1 ? "" : "s"}, no file ${args.attachment}`);
34
+ const photo = args.attachment === undefined ? files.find((file) => file.kind === "photo") : files[args.attachment - 1];
33
35
  if (!photo) {
34
36
  const kinds = files.map((file) => file.kind).join(", ");
35
37
  throw new CliError(files.length === 0 ? "not_found" : "validation_error", files.length === 0
@@ -6,14 +6,20 @@ import { meetingHitsList } from "../answers.js";
6
6
  import { validateMeetingHitSearch } from "../search-validation.js";
7
7
  export { validateMeetingHitSearch } from "../search-validation.js";
8
8
  const ZONED = /(?:Z|[+-]\d{2}:?\d{2})$/i;
9
+ // `30m`, `2h`, `7d` ago, as the messenger commands' --since-time reads them and this command's `date>=7d` does.
10
+ const AGO = /^(\d+)(m|h|d)$/;
11
+ const AGO_MS = { m: 60_000, h: 3_600_000, d: 86_400_000 };
9
12
  const moment = (flag, end, readIn) => (value) => {
13
+ const [, amount, unit] = AGO.exec(value.trim()) ?? [];
14
+ if (amount && unit)
15
+ return Date.now() - Number(amount) * (AGO_MS[unit] ?? 0);
10
16
  const zone = timezoneOf();
11
17
  let time;
12
18
  try {
13
19
  time = zonedMoment(value, zone, { start: 0, end: value.length }, { end });
14
20
  }
15
21
  catch {
16
- throw new CliError("validation_error", `${flag} takes an ISO date, or a time with or without an offset`);
22
+ throw new CliError("validation_error", `${flag} takes an ISO date, a time with or without an offset, or 30m, 2h, 7d ago`);
17
23
  }
18
24
  if (!ZONED.test(value.trim()))
19
25
  readIn(zone);
@@ -44,7 +50,7 @@ const createMeetingSearchCommandDefinition = (program) => {
44
50
  .option("--project <project>", "meetings confirmed in this project, by name, key or alias")
45
51
  .option("--tag <name>", "meetings with this tag, by name or alias")
46
52
  .option("--topic-name <name>", "meetings with this topic, by name or alias")
47
- .option("--since-time <time>", "meetings starting at or after this ISO 8601 date or time", moment("--since-time", false, readIn))
53
+ .option("--since-time <time>", "meetings starting at or after this ISO 8601 date or time, or 30m, 2h, 7d ago", moment("--since-time", false, readIn))
48
54
  .option("--until-time <time>", "meetings starting at or before this ISO 8601 date or time; a date alone covers that whole local day", moment("--until-time", true, readIn))
49
55
  .option("--limit <n>", "how many hits, 1 through 1000 (default 100)", integer)
50
56
  .option("--cursor <cursor>", "continue from the previous page's page.next_cursor, with the same query and filters")
@@ -101,13 +101,16 @@ export const liftMeetingFields = (query, request, now, timezone) => {
101
101
  };
102
102
  for (const { node } of lifted) {
103
103
  if (node.field === "date") {
104
- once("since", "--since-time");
105
- once("until", "--until-time");
106
104
  const range = dateRange(node.value, node.operator === "range" ? (node.upper ?? "*") : node.value, node.lower_inclusive !== false, node.upper_inclusive !== false, timezoneOf(timezone), node.span, now);
107
- if (range.lower !== undefined)
105
+ // Only the bound the query sets clashes with a flag: `date>=30d --until-time …` is one window.
106
+ if (range.lower !== undefined) {
107
+ once("since", "--since-time");
108
108
  next.since = range.lower + (range.lower_inclusive ? 0 : 1);
109
- if (range.upper !== undefined)
109
+ }
110
+ if (range.upper !== undefined) {
111
+ once("until", "--until-time");
110
112
  next.until = range.upper - (range.upper_inclusive ? 0 : 1);
113
+ }
111
114
  }
112
115
  else {
113
116
  const field = node.field;
@@ -118,9 +121,11 @@ export const liftMeetingFields = (query, request, now, timezone) => {
118
121
  let rest = query;
119
122
  for (const { node } of [...lifted].sort((a, b) => b.node.span.start - a.node.span.start))
120
123
  rest = `${rest.slice(0, node.span.start)}${rest.slice(node.span.end)}`;
124
+ // The parser joins with AND, && or a leading +; a lifted field must not leave its joiner behind.
121
125
  rest = rest
122
- .replace(/^(?:\s*AND\b)+|(?:\bAND\s*)+$/g, "")
123
- .replace(/\bAND(\s+AND\b)+/g, "AND")
126
+ .replace(/(^|\s)\+(?=\s|$)/g, "$1")
127
+ .replace(/^(?:\s*(?:AND\b|&&))+|(?:(?:\bAND|&&)\s*)+$/g, "")
128
+ .replace(/(?:\bAND|&&)(\s+(?:AND\b|&&))+/g, "AND")
124
129
  .trim();
125
130
  if (!rest)
126
131
  throw new CliError("validation_error", "give words to find besides date:, project:, tag: and topic:");
@@ -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;
@@ -3,25 +3,9 @@ import { CliError } from "@wirecat/cli-base";
3
3
  import { MESSENGER_CHANGE_REFUSAL, readOnlyRefusal } from "../ports/app.js";
4
4
  import { FloodMemory, floodPathFor, holdEnd } from "./flood.js";
5
5
  import { SendJournal, sendsPathFor, } from "./journal.js";
6
- import { CEILING_KEY, keyForWrite, levelFor, skipFlagFor } from "./permissions.js";
6
+ import { CEILING_KEY, keyForWrite, levelFor, STORE_ONLY_KEYS, skipFlagFor, stops, } from "./permissions.js";
7
7
  import { RecipientList, recipientsPathFor } from "./recipients.js";
8
8
  const HOUR_MS = 60 * 60 * 1000;
9
- /**
10
- * Asked of the guard for their permission level, yet they only read from the messenger or work here: reads go on
11
- * during a hold and under the read-only lock, which promises reads and syncs.
12
- */
13
- const READS = new Set([
14
- "attachments.extract",
15
- "conversations.embeddings",
16
- "conversations.links",
17
- "messages.server-search",
18
- "messages.sync-first",
19
- "stats.contacts.top.sync-first",
20
- "stats.messages.counters.sync",
21
- "stats.messages.show.sync-first",
22
- "stats.messages.top.sync-first",
23
- "store.gaps.repair",
24
- ]);
25
9
  /**
26
10
  * What puts something in front of somebody (max-cli `NEED-168`, widened by `NEED-282`). A message, a
27
11
  * forward, an edit, a pin that notifies, a new group and people added to one all do. A reaction,
@@ -49,7 +33,11 @@ const weightOf = ({ kind = "message", action, count, people }) => kind === "dele
49
33
  ? Math.max(1, people ?? count ?? 1)
50
34
  : 1;
51
35
  /** A scheduled message counts in the hour the provider sends it. */
52
- const timeOf = (entry) => Date.parse(entry.scheduledFor ?? entry.at);
36
+ const timeOf = (entry) => {
37
+ const scheduled = entry.scheduledFor === undefined ? Number.NaN : Date.parse(entry.scheduledFor);
38
+ // A journal line with an unreadable time still counts, in the hour it was written: never in no hour at all.
39
+ return Number.isNaN(scheduled) ? Date.parse(entry.at) : scheduled;
40
+ };
53
41
  /** A write the profile's level refuses, worded alike by the guard and by the check before connecting. */
54
42
  /** A write the first-run answer stops, whatever the profile allows. */
55
43
  export const ceilingRefusal = (key, command) => new CliError("permission_error", `${key} is not allowed: setup's answer keeps every WireCat tool read-only; ` +
@@ -68,14 +56,14 @@ export const sendGuard = ({ profile, recipients, command = recipients.command, r
68
56
  let reservation;
69
57
  const answered = new WeakSet();
70
58
  const refuseReadOnly = ({ key }) => {
71
- if (key !== undefined && READS.has(key))
59
+ if (key !== undefined && STORE_ONLY_KEYS.has(key))
72
60
  return;
73
61
  if (readOnlyLock)
74
62
  throw readOnlyRefusal(readOnlyLock, MESSENGER_CHANGE_REFUSAL);
75
63
  };
76
64
  // Every write, counted or not: a reaction or a read receipt sent through a ban is what makes the ban stick.
77
65
  const refuseHeld = ({ key }) => {
78
- if (key !== undefined && READS.has(key))
66
+ if (key !== undefined && STORE_ONLY_KEYS.has(key))
79
67
  return;
80
68
  const block = flood?.sendBlock();
81
69
  if (!block)
@@ -91,7 +79,7 @@ export const sendGuard = ({ profile, recipients, command = recipients.command, r
91
79
  if (levels !== undefined) {
92
80
  const key = request.key ?? keyForWrite(kind, action);
93
81
  const { level, key: named } = levelFor(levels, key, permissionDefaults);
94
- if (level === "deny" || level === "readonly")
82
+ if (stops(level, key))
95
83
  throw levelRefusal({ profile, command, key, level, named, permissionSources }, permissionFix?.(request, key));
96
84
  if (level === "ask" && !answered.has(request)) {
97
85
  throw new CliError("confirmation_required", `${key} asks before it acts, and it was not asked`);
@@ -119,6 +107,8 @@ export const sendGuard = ({ profile, recipients, command = recipients.command, r
119
107
  "do fewer at a time");
120
108
  }
121
109
  const at = request.scheduledFor ? Date.parse(request.scheduledFor) : now().getTime();
110
+ if (Number.isNaN(at))
111
+ throw new CliError("validation_error", `"${request.scheduledFor}" is not a time to send at — use ISO 8601`);
122
112
  const counted = entries
123
113
  .filter(countsTowardLimit)
124
114
  .filter((entry) => entry.outcome === "sent" || entry.outcome === "outcome_unknown" || entry.outcome === "reserved")
@@ -1,5 +1,5 @@
1
1
  import type { Asker, GuardRequest, SendGuard } from "./guard.js";
2
- import type { Level, PermissionKey } from "./permissions.js";
2
+ import { type Level, type PermissionKey } from "./permissions.js";
3
3
  export type KeyedGuard = SendGuard & {
4
4
  /** Refuses the write when one of its keys denies it or is read-only; asks nothing. */
5
5
  refuse(request: GuardRequest): void;
@@ -1,3 +1,4 @@
1
+ import { stops } from "./permissions.js";
1
2
  /**
2
3
  * A guard over a write's main key and its extra keys. A key that refuses refuses before anything is asked, so nobody
3
4
  * answers yes to a write that a stricter key then stops, and one question names every key at `ask`. The extra keys are
@@ -23,7 +24,7 @@ export const keyedGuard = (build, ask, levelOf, extra) => {
23
24
  };
24
25
  const levelOfRequest = ({ key }) => levelOf(key ?? "");
25
26
  const refuse = (request) => {
26
- const refused = all(request).find((one) => ["deny", "readonly"].includes(levelOfRequest(one)));
27
+ const refused = all(request).find((one) => stops(levelOfRequest(one), one.key ?? ""));
27
28
  if (refused)
28
29
  guard.check(refused, { reserve: false });
29
30
  };
@@ -39,6 +39,20 @@ export declare const layerPermissions: (layers: readonly [string, Readonly<Recor
39
39
  * at a terminal writes it, so an agent cannot lift it with `config set`.
40
40
  */
41
41
  export declare const CEILING_KEY = "*";
42
+ /**
43
+ * Asked of the guard for their permission level, yet they only read from the messenger or work here: reads go on
44
+ * during a hold and under the read-only lock, which promises reads and syncs.
45
+ */
46
+ export declare const STORE_ONLY_KEYS: Set<string>;
47
+ /** Whether `level` lets a key that only fetches into the store run: `readonly` does, `deny` and `ask` decide alone. */
48
+ export declare const fetchesUnder: (level: Level, key: PermissionKey) => boolean;
49
+ /**
50
+ * Whether a fetch a read adds on its own (a sync first, a server search) runs at `level`: it is never asked, so `ask`
51
+ * does not, and `readonly` still fetches.
52
+ */
53
+ export declare const fetchesAt: (level: Level) => boolean;
54
+ /** Whether `level` stops a write under `key` outright: `deny` always, `readonly` unless the key only fetches. */
55
+ export declare const stops: (level: Level, key: PermissionKey) => boolean;
42
56
  /**
43
57
  * The most specific key the owner set wins. A built-in default (`DEFAULT_PERMISSIONS`) only ever
44
58
  * tightens: against a broader key of the owner's, the stricter of the two holds — so
@@ -121,6 +121,38 @@ export const layerPermissions = (layers) => {
121
121
  * at a terminal writes it, so an agent cannot lift it with `config set`.
122
122
  */
123
123
  export const CEILING_KEY = "*";
124
+ /**
125
+ * Asked of the guard for their permission level, yet they only read from the messenger or work here: reads go on
126
+ * during a hold and under the read-only lock, which promises reads and syncs.
127
+ */
128
+ export const STORE_ONLY_KEYS = new Set([
129
+ "attachments.extract",
130
+ "conversations.embeddings",
131
+ "conversations.links",
132
+ "messages.server-search",
133
+ "messages.sync-first",
134
+ "metadata.sync",
135
+ "stats.contacts.top.sync-first",
136
+ "stats.messages.counters.sync",
137
+ "stats.messages.show.sync-first",
138
+ "stats.messages.top.sync-first",
139
+ "store.gaps.repair",
140
+ ]);
141
+ /**
142
+ * Those of `STORE_ONLY_KEYS` that only fetch from the messenger into the store: a `readonly` level lets them run, as it
143
+ * lets a sync (owner ruling, 2026-11-14). Work done here on what is stored, such as a file's text or a link between
144
+ * conversations, stays a write that `readonly` stops.
145
+ */
146
+ const FETCH_KEYS = new Set([...STORE_ONLY_KEYS].filter((key) => !["attachments.extract", "conversations.embeddings", "conversations.links"].includes(key)));
147
+ /** Whether `level` lets a key that only fetches into the store run: `readonly` does, `deny` and `ask` decide alone. */
148
+ export const fetchesUnder = (level, key) => level === "readonly" && FETCH_KEYS.has(key);
149
+ /**
150
+ * Whether a fetch a read adds on its own (a sync first, a server search) runs at `level`: it is never asked, so `ask`
151
+ * does not, and `readonly` still fetches.
152
+ */
153
+ export const fetchesAt = (level) => level === "allow" || level === "readonly";
154
+ /** Whether `level` stops a write under `key` outright: `deny` always, `readonly` unless the key only fetches. */
155
+ export const stops = (level, key) => level === "deny" || (level === "readonly" && !FETCH_KEYS.has(key));
124
156
  const ALLOWED = { level: "allow", key: null };
125
157
  const ORDER = { deny: 0, readonly: 1, ask: 2, allow: 3 };
126
158
  const nearest = (levels, key) => {
@@ -123,7 +123,8 @@ export const showDocument = async (store, reference, text) => {
123
123
  text: found.text,
124
124
  text_offset: Math.min(text.offset, found.textLength),
125
125
  text_length: found.textLength,
126
- has_more: found.text !== null && text.offset + found.text.length < found.textLength,
126
+ // SQLite's substr and length count code points; a JavaScript string's length counts UTF-16 units.
127
+ has_more: found.text !== null && text.offset + [...found.text].length < found.textLength,
127
128
  extraction: found.extraction,
128
129
  extraction_error: found.extractionError,
129
130
  language: found.language,
@@ -131,12 +131,15 @@ export const chatAmong = async (messenger, store, accounts, reference) => {
131
131
  const [only] = accounts;
132
132
  if (accounts.length === 1 && only)
133
133
  return { account: only, chatId: await storedChatId(messenger, reference, store, only, { includeLeft: true }) };
134
- const found = (await Promise.all(accounts.map(async (account) => {
135
- const held = (await store.chats.chats(account, {})).items;
136
- const chatId = await storedChatId(messenger, reference, store, account).catch(missing);
134
+ const among = async (includeLeft) => (await Promise.all(accounts.map(async (account) => {
135
+ const held = (await store.chats.chats(account, includeLeft ? { includeLeft } : {})).items;
136
+ const chatId = await storedChatId(messenger, reference, store, account, { includeLeft }).catch(missing);
137
137
  const chat = held.find((one) => one.id === chatId);
138
138
  return chat ? [{ account, chat }] : [];
139
139
  }))).flat();
140
+ // As with one account, a chat left behind is found when no account still holds one by that name.
141
+ const current = await among(false);
142
+ const found = current.length > 0 ? current : await among(true);
140
143
  const [one] = found;
141
144
  if (found.length === 1 && one)
142
145
  return { account: one.account, chatId: one.chat.id };
@@ -110,7 +110,7 @@ export const searchServer = async (deps, request) => {
110
110
  if (deps.offline)
111
111
  return skip("offline");
112
112
  const guardRequest = { chatId: null, kind: "reaction", key: SERVER_SEARCH_KEY };
113
- // Never asked, as sync-first: over MCP an `ask` goes ahead, and the server search needs `allow`.
113
+ // Never asked, as sync-first: over MCP an `ask` goes ahead, and the server search needs `allow` or `readonly`.
114
114
  try {
115
115
  deps.guard.check(guardRequest, { reserve: false });
116
116
  }
@@ -9,7 +9,10 @@ type Decision = {
9
9
  target_id: unknown;
10
10
  author: unknown;
11
11
  };
12
- /** The stored chat or Telegram account a `t.me` link names, as a rules decision; nothing for any other link. */
12
+ /**
13
+ * The stored Telegram chat or account a `t.me` link names, as a rules decision; nothing for any other link. Never a
14
+ * chat of another messenger that happens to share the username.
15
+ */
13
16
  export declare const telegramLink: (database: CacheDatabase) => (value: string) => Decision | undefined;
14
17
  /**
15
18
  * People whose names are looked for: not the owner, and only people met in a messenger, a meeting or a confirmed
@@ -8,10 +8,14 @@ import { placeOf } from "./place-key.js";
8
8
  /** Mentions a store write finds before it commits: an older binary may have queued thousands. */
9
9
  export const DRAIN_ON_WRITE = 500;
10
10
  const METHOD = "rules";
11
- /** The stored chat or Telegram account a `t.me` link names, as a rules decision; nothing for any other link. */
11
+ /**
12
+ * The stored Telegram chat or account a `t.me` link names, as a rules decision; nothing for any other link. Never a
13
+ * chat of another messenger that happens to share the username.
14
+ */
12
15
  export const telegramLink = (database) => {
13
- const chat = database.prepare("SELECT 'linked' AS status, 'chat' AS target_type, id AS target_id, 'rules' AS author FROM chats " +
14
- "WHERE (? IS NOT NULL AND lower(username) = lower(?)) OR external_id = ? ORDER BY id LIMIT 1");
16
+ const chat = database.prepare("SELECT 'linked' AS status, 'chat' AS target_type, c.id AS target_id, 'rules' AS author FROM chats c " +
17
+ "JOIN accounts a ON a.id = c.account_id WHERE a.provider = 'telegram' " +
18
+ "AND ((? IS NOT NULL AND lower(c.username) = lower(?)) OR c.external_id = ?) ORDER BY c.id LIMIT 1");
15
19
  const account = database.prepare("SELECT 'linked' AS status, 'identity' AS target_type, id AS target_id, 'rules' AS author FROM identities " +
16
20
  "WHERE provider = 'telegram' AND lower(username) = lower(?) ORDER BY id LIMIT 1");
17
21
  return (value) => {
@@ -143,6 +143,17 @@ export const upsertMessage = (context, key, accountKey, chatKey, received, via,
143
143
  else {
144
144
  pk = found.pk;
145
145
  const edit = message.editedAt !== null;
146
+ // A copy from before the stored edit (a history page fetched before serve saw the edit, a late edit event)
147
+ // keeps the newer text; its reactions and counters may still be fresher.
148
+ const stale = !revived &&
149
+ found.editedAt !== null &&
150
+ (fields.editedAt !== null
151
+ ? Number(fields.editedAt) < found.editedAt
152
+ : seenAt !== undefined && seenAt < found.editedAt);
153
+ if (stale) {
154
+ fields.editedAt = null;
155
+ fields.normalizedText = null;
156
+ }
146
157
  // An edit event may carry only the new text, stamped with the edit's time: a send time never moves later,
147
158
  // and an edit that counts no reactions has not seen them.
148
159
  if (edit) {
@@ -169,7 +180,7 @@ export const upsertMessage = (context, key, accountKey, chatKey, received, via,
169
180
  }
170
181
  statements.update.run({ ...fields, pk });
171
182
  // A tombstone emptied the text: there is no earlier version to keep.
172
- if (found.text !== message.text && !revived) {
183
+ if (found.text !== message.text && !revived && !stale) {
173
184
  orm
174
185
  .insert(messageRevisions)
175
186
  .values({ messageId: pk, text: found.text, editedAt: found.editedAt, createdAt: now() })
@@ -21,6 +21,7 @@ export type ColumnMap = Readonly<Record<string, {
21
21
  where: (node: Predicate) => Where;
22
22
  }>>;
23
23
  export interface FilterOptions extends QueryContext {
24
+ /** Where `today` and a bare date start; the machine's zone when absent, as search reads them. */
24
25
  zone?: string;
25
26
  now?: number;
26
27
  }
@@ -1,4 +1,4 @@
1
- import { dateRange, queryError, } from "@wirecat/cli-base/query";
1
+ import { dateRange, queryError, timezoneOf, } from "@wirecat/cli-base/query";
2
2
  import { fold } from "../normalize.js";
3
3
  import { sql } from "./drizzle/core.js";
4
4
  /** A wildcard term as a GLOB pattern: `\x` is a literal x, and a literal `*`, `?` or `[` is bracketed. */
@@ -53,7 +53,7 @@ const leaf = (node, columns, options) => {
53
53
  const range = node.operator === "range"
54
54
  ? [node.value, node.upper ?? "*", node.lower_inclusive ?? true, node.upper_inclusive ?? true]
55
55
  : [node.value, node.value, true, true];
56
- const { lower, upper, lower_inclusive, upper_inclusive } = dateRange(range[0], range[1], range[2], range[3], options.zone ?? "UTC", node.span, options.now);
56
+ const { lower, upper, lower_inclusive, upper_inclusive } = dateRange(range[0], range[1], range[2], range[3], timezoneOf(options.zone), node.span, options.now);
57
57
  return all([
58
58
  { sql: `${sql} IS NOT NULL`, params: [] },
59
59
  ...(lower === undefined ? [] : [{ sql: `${sql} ${lower_inclusive ? ">=" : ">"} ?`, params: [lower] }]),
@@ -282,7 +282,7 @@ export const tagsOf = ({ database }, key, filter) => {
282
282
  "WHEN 'email' THEN 'message' ELSE u.type END AS tag_type, (u.type = 'chat' AND EXISTS (SELECT 1 FROM " +
283
283
  `canonical_auto_tag_claims ac JOIN resolved_tags rt ON rt.id=ac.tag_id WHERE ac.chat_id = u.target_id AND rt.canonical_id = u.tag_id)) AS auto FROM (${union}) u) GROUP BY tag,type,target_id) x ` +
284
284
  `WHERE ${where.length === 0 ? "1" : where.map(({ sql }) => `(${sql})`).join(" AND ")} ` +
285
- "ORDER BY x.tag, x.type, x.created_at, x.chat_id, x.person_id, x.message_id" +
285
+ "ORDER BY x.tag, x.type, x.created_at, x.chat_id, x.person_id, x.message_id, x.target_id" +
286
286
  (filter.window ? " LIMIT ? OFFSET ?" : ""))
287
287
  .all(...chosen.flatMap(({ params }) => (selectedTag === undefined ? params : [...params, selectedTag])), ...where.flatMap(({ params }) => params), ...(filter.window ? [filter.window.limit, filter.window.offset] : []));
288
288
  const result = rows.map((row) => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wirecat/cli-core",
3
- "version": "0.660.0",
3
+ "version": "0.662.0",
4
4
  "description": "The messenger-neutral half of a messaging CLI: domain model, message locators, rendering, name resolution, the SQLite seam, the command skeleton and shared read commands, the send guard, run records and the message store",
5
5
  "license": "Apache-2.0",
6
6
  "author": "Viacheslav Ptsarev",
package/parity.json CHANGED
@@ -5152,7 +5152,8 @@
5152
5152
  "tasks scan": {
5153
5153
  "in": "all",
5154
5154
  "options": {
5155
- "--last": "all"
5155
+ "--last": "all",
5156
+ "--yes": "all"
5156
5157
  }
5157
5158
  },
5158
5159
  "tasks show": {