@wirecat/cli-core 0.660.0 → 0.661.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 (52) hide show
  1. package/CHANGELOG.md +68 -0
  2. package/dist/attachments/markup.js +2 -11
  3. package/dist/calendar/mcp/index.js +23 -17
  4. package/dist/cli/bot/api-http.d.ts +43 -0
  5. package/dist/cli/bot/api-http.js +160 -0
  6. package/dist/cli/index.d.ts +1 -0
  7. package/dist/cli/index.js +1 -0
  8. package/dist/cli/messenger/rankings-command.js +2 -1
  9. package/dist/cli/messenger/serve-command.js +7 -2
  10. package/dist/cli/messenger/tasks-command.d.ts +7 -2
  11. package/dist/cli/messenger/tasks-command.js +6 -3
  12. package/dist/cli/schedule/schedule-command.js +3 -0
  13. package/dist/domain/html-entities.d.ts +5 -0
  14. package/dist/domain/html-entities.js +56 -0
  15. package/dist/domain/locator.js +12 -4
  16. package/dist/domain/references.js +11 -3
  17. package/dist/entities/listings.d.ts +4 -4
  18. package/dist/entities/listings.js +2 -2
  19. package/dist/mail/headers.js +3 -3
  20. package/dist/mail/parse.js +9 -8
  21. package/dist/mail/resume.d.ts +4 -1
  22. package/dist/mail/resume.js +11 -2
  23. package/dist/mail/retry.d.ts +2 -1
  24. package/dist/mail/retry.js +6 -4
  25. package/dist/mail/sender-scores.js +1 -6
  26. package/dist/mail/stored.d.ts +4 -1
  27. package/dist/mail/stored.js +6 -1
  28. package/dist/mail/sync.js +8 -3
  29. package/dist/mail/testing/fake.d.ts +2 -0
  30. package/dist/mail/testing/fake.js +3 -1
  31. package/dist/mcp/all-profiles.js +8 -18
  32. package/dist/mcp/app-server.js +1 -16
  33. package/dist/mcp/bot/server.js +9 -7
  34. package/dist/mcp/caller.js +2 -1
  35. package/dist/mcp/prompts.js +17 -2
  36. package/dist/mcp/server.js +10 -16
  37. package/dist/mcp/stdio-wire.d.ts +5 -2
  38. package/dist/mcp/stdio-wire.js +39 -12
  39. package/dist/mcp/tool.js +3 -1
  40. package/dist/mcp/tools/messages-photo.js +4 -2
  41. package/dist/meetings/cli/search.js +8 -2
  42. package/dist/meetings/hit-query.js +11 -6
  43. package/dist/sends/guard.js +7 -1
  44. package/dist/services/listings.js +2 -1
  45. package/dist/services/message-resolution.js +6 -3
  46. package/dist/store/sqlite/mention-drain.d.ts +4 -1
  47. package/dist/store/sqlite/mention-drain.js +7 -3
  48. package/dist/store/sqlite/messages.js +12 -1
  49. package/dist/store/sqlite/query-filter.d.ts +1 -0
  50. package/dist/store/sqlite/query-filter.js +2 -2
  51. package/dist/store/sqlite/tags.js +1 -1
  52. package/package.json +1 -1
package/dist/mcp/tool.js CHANGED
@@ -279,7 +279,9 @@ export class BinaryResource {
279
279
  }
280
280
  export const answered = (answer, maxBytes = DEFAULT_OUTPUT_BYTES, targets) => {
281
281
  const bounded = (result) => {
282
- if (maxBytes !== 0 && Buffer.byteLength(JSON.stringify(result)) > maxBytes)
282
+ // Measured as the CLI measures what it prints: `structuredContent` repeats the text, and counting both halved the
283
+ // limit for MCP alone.
284
+ if (maxBytes !== 0 && Buffer.byteLength(JSON.stringify(result.content)) > maxBytes)
283
285
  throw new CliError("invalid_response", "tool output exceeds its byte limit — reduce limit or use a narrower request", { reason: "output.too-large", max_bytes: maxBytes, retryable: false });
284
286
  return result;
285
287
  };
@@ -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:");
@@ -49,7 +49,11 @@ const weightOf = ({ kind = "message", action, count, people }) => kind === "dele
49
49
  ? Math.max(1, people ?? count ?? 1)
50
50
  : 1;
51
51
  /** A scheduled message counts in the hour the provider sends it. */
52
- const timeOf = (entry) => Date.parse(entry.scheduledFor ?? entry.at);
52
+ const timeOf = (entry) => {
53
+ const scheduled = entry.scheduledFor === undefined ? Number.NaN : Date.parse(entry.scheduledFor);
54
+ // A journal line with an unreadable time still counts, in the hour it was written: never in no hour at all.
55
+ return Number.isNaN(scheduled) ? Date.parse(entry.at) : scheduled;
56
+ };
53
57
  /** A write the profile's level refuses, worded alike by the guard and by the check before connecting. */
54
58
  /** A write the first-run answer stops, whatever the profile allows. */
55
59
  export const ceilingRefusal = (key, command) => new CliError("permission_error", `${key} is not allowed: setup's answer keeps every WireCat tool read-only; ` +
@@ -119,6 +123,8 @@ export const sendGuard = ({ profile, recipients, command = recipients.command, r
119
123
  "do fewer at a time");
120
124
  }
121
125
  const at = request.scheduledFor ? Date.parse(request.scheduledFor) : now().getTime();
126
+ if (Number.isNaN(at))
127
+ throw new CliError("validation_error", `"${request.scheduledFor}" is not a time to send at — use ISO 8601`);
122
128
  const counted = entries
123
129
  .filter(countsTowardLimit)
124
130
  .filter((entry) => entry.outcome === "sent" || entry.outcome === "outcome_unknown" || entry.outcome === "reserved")
@@ -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 };
@@ -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.661.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",