@wirecat/cli-core 1.3.0 → 2.0.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 (134) hide show
  1. package/CHANGELOG.md +145 -0
  2. package/dist/attachments/container.d.ts +1 -1
  3. package/dist/attachments/container.js +16 -7
  4. package/dist/attachments/limits.d.ts +10 -0
  5. package/dist/attachments/limits.js +30 -1
  6. package/dist/attachments/transfer.js +2 -2
  7. package/dist/cli/app-doctor-command.d.ts +61 -7
  8. package/dist/cli/app-doctor-command.js +24 -11
  9. package/dist/cli/documents/file-edit.js +6 -6
  10. package/dist/cli/documents/library.js +4 -2
  11. package/dist/cli/index.d.ts +6 -5
  12. package/dist/cli/index.js +2 -1
  13. package/dist/cli/messenger/context.d.ts +16 -0
  14. package/dist/cli/messenger/doctor-command.js +16 -1
  15. package/dist/cli/messenger/flooded.js +9 -1
  16. package/dist/cli/messenger/serve-relay.d.ts +2 -0
  17. package/dist/cli/oauth-session.d.ts +3 -2
  18. package/dist/cli/oauth-session.js +19 -3
  19. package/dist/cli/profile-store.d.ts +24 -10
  20. package/dist/cli/profile-store.js +43 -28
  21. package/dist/cli/shared-command-exports.d.ts +1 -1
  22. package/dist/cli/token-session.d.ts +21 -2
  23. package/dist/cli/token-session.js +27 -11
  24. package/dist/crm/cli/files.js +7 -7
  25. package/dist/documents.d.ts +1 -1
  26. package/dist/documents.js +1 -1
  27. package/dist/domain/person-kinds.d.ts +7 -3
  28. package/dist/domain/person-kinds.js +7 -3
  29. package/dist/domain/ref-summaries.js +1 -0
  30. package/dist/domain/references.d.ts +3 -2
  31. package/dist/domain/references.js +19 -10
  32. package/dist/entities/deal.d.ts +2 -2
  33. package/dist/entities/deal.js +1 -1
  34. package/dist/entities/fact.d.ts +2 -2
  35. package/dist/entities/fact.js +1 -1
  36. package/dist/entities/fields.d.ts +1 -1
  37. package/dist/entities/fields.js +1 -1
  38. package/dist/entities/index.d.ts +15 -15
  39. package/dist/entities/mail-findings.d.ts +2 -2
  40. package/dist/entities/mail-findings.js +1 -1
  41. package/dist/entities/meeting-findings.d.ts +2 -2
  42. package/dist/entities/meeting-findings.js +1 -1
  43. package/dist/entities/memory.d.ts +1 -1
  44. package/dist/entities/task-results.d.ts +5 -5
  45. package/dist/entities/task-results.js +1 -1
  46. package/dist/entities/task.d.ts +1 -1
  47. package/dist/entities/task.js +1 -1
  48. package/dist/errors/reasons.js +2 -1
  49. package/dist/fetch/page.js +1 -2
  50. package/dist/mail/headers.d.ts +4 -3
  51. package/dist/mail/headers.js +21 -3
  52. package/dist/mail/sort-rules.d.ts +13 -6
  53. package/dist/mail/sort-rules.js +20 -16
  54. package/dist/mail/sync.js +2 -0
  55. package/dist/mcp/tools/attachments.js +1 -1
  56. package/dist/office/zip.js +1 -1
  57. package/dist/ports/messenger.d.ts +31 -1
  58. package/dist/services/archive.js +61 -11
  59. package/dist/services/attachments.js +4 -4
  60. package/dist/services/documents/file-text.js +2 -2
  61. package/dist/services/metadata.d.ts +1 -1
  62. package/dist/services/proposals/kinds/shared.d.ts +1 -1
  63. package/dist/services/proposals/kinds/shared.js +2 -2
  64. package/dist/services/proposals/kinds/task-close.js +1 -1
  65. package/dist/store/areas.d.ts +2 -0
  66. package/dist/store/areas.js +1 -0
  67. package/dist/store/decisions.d.ts +1 -1
  68. package/dist/store/decisions.js +4 -4
  69. package/dist/store/evidence-findings.d.ts +2 -2
  70. package/dist/store/index.d.ts +3 -1
  71. package/dist/store/index.js +2 -1
  72. package/dist/store/mail-findings.d.ts +2 -2
  73. package/dist/store/meeting-findings.d.ts +2 -2
  74. package/dist/store/people.d.ts +4 -4
  75. package/dist/store/people.js +2 -1
  76. package/dist/store/project-transfer/manifest.js +3 -3
  77. package/dist/store/public.d.ts +1 -1
  78. package/dist/store/public.js +1 -1
  79. package/dist/store/sqlite/actors.d.ts +1 -1
  80. package/dist/store/sqlite/actors.js +6 -6
  81. package/dist/store/sqlite/agent-actions.js +2 -2
  82. package/dist/store/sqlite/agent-links.js +1 -1
  83. package/dist/store/sqlite/bot-sends.d.ts +19 -0
  84. package/dist/store/sqlite/bot-sends.js +36 -0
  85. package/dist/store/sqlite/business-contracts.js +1 -1
  86. package/dist/store/sqlite/deals.js +1 -1
  87. package/dist/store/sqlite/document-transfer/plan.js +1 -1
  88. package/dist/store/sqlite/document-transfer/snapshot.js +1 -1
  89. package/dist/store/sqlite/email-index.d.ts +11 -2
  90. package/dist/store/sqlite/email-index.js +56 -5
  91. package/dist/store/sqlite/email-types.d.ts +15 -3
  92. package/dist/store/sqlite/email-types.js +32 -1
  93. package/dist/store/sqlite/emails.d.ts +2 -1
  94. package/dist/store/sqlite/emails.js +6 -1
  95. package/dist/store/sqlite/entity-types.d.ts +1 -1
  96. package/dist/store/sqlite/entity-types.js +1 -1
  97. package/dist/store/sqlite/evidence-findings.js +1 -1
  98. package/dist/store/sqlite/facts.js +1 -1
  99. package/dist/store/sqlite/finance.js +2 -2
  100. package/dist/store/sqlite/knowledge.js +1 -0
  101. package/dist/store/sqlite/mail-findings.js +1 -1
  102. package/dist/store/sqlite/mail-sorting.d.ts +1 -1
  103. package/dist/store/sqlite/mail-sorting.js +96 -60
  104. package/dist/store/sqlite/mail-subscriptions.d.ts +70 -0
  105. package/dist/store/sqlite/mail-subscriptions.js +132 -0
  106. package/dist/store/sqlite/manifest.js +45 -0
  107. package/dist/store/sqlite/meeting-findings.js +1 -1
  108. package/dist/store/sqlite/memories.js +3 -3
  109. package/dist/store/sqlite/migrations.generated.js +80 -0
  110. package/dist/store/sqlite/money-transactions.js +1 -1
  111. package/dist/store/sqlite/note-index.d.ts +4 -1
  112. package/dist/store/sqlite/note-index.js +40 -17
  113. package/dist/store/sqlite/orders.js +1 -1
  114. package/dist/store/sqlite/payment-facts.js +2 -2
  115. package/dist/store/sqlite/products.js +1 -1
  116. package/dist/store/sqlite/project-transfer/sources.js +2 -2
  117. package/dist/store/sqlite/proposed-actions.js +3 -3
  118. package/dist/store/sqlite/record-projection.js +1 -1
  119. package/dist/store/sqlite/ref-summaries.js +2 -1
  120. package/dist/store/sqlite/relation-proposals.js +1 -1
  121. package/dist/store/sqlite/reviewed.d.ts +2 -2
  122. package/dist/store/sqlite/reviewed.js +1 -1
  123. package/dist/store/sqlite/sender-bots.d.ts +19 -4
  124. package/dist/store/sqlite/sender-bots.js +48 -4
  125. package/dist/store/sqlite/subscriptions.js +2 -2
  126. package/dist/store/sqlite/task-close.js +1 -1
  127. package/dist/store/sqlite/task-comments.js +1 -1
  128. package/dist/store/sqlite/things.js +1 -1
  129. package/dist/store/sqlite/transaction.d.ts +5 -0
  130. package/dist/store/sqlite/transaction.js +6 -1
  131. package/dist/store/sqlite/wallets.js +1 -1
  132. package/dist/store/sqlite/work-tasks.js +2 -2
  133. package/dist/tracker/tasks.js +4 -2
  134. package/package.json +7 -5
@@ -2,15 +2,16 @@ import { createHash } from "node:crypto";
2
2
  import { CliError } from "@wirecat/cli-base";
3
3
  import { isPackFreeMailDomain } from "../../domain/domain-lists.js";
4
4
  import { isFreeMailDomain } from "../../domain/organization-sectors.js";
5
- import { SENDER_BOT_PREFIX } from "../../domain/person-kinds.js";
5
+ import { SENDER_BOT_PREFIX, senderBotRef } from "../../domain/person-kinds.js";
6
6
  import { listIdOf } from "../../mail/headers.js";
7
7
  import { MAIL_TYPES } from "../../mail/mail-types.js";
8
8
  import { FREE_MAIL, isDisposableDomain } from "../../mail/score.js";
9
9
  import { SORT_SCOPES, sortIndexOf, sortRuleFor, sortValueOf, } from "../../mail/sort-rules.js";
10
10
  import { holdAddress } from "./address-organization.js";
11
- import { moveToBot, moveToPerson } from "./sender-bots.js";
11
+ import { currentPerson } from "./merged-persons.js";
12
+ import { holdingAuthorOf, moveToBot, moveToPerson, putBack } from "./sender-bots.js";
12
13
  import { LIST_ID } from "./sender-signals.js";
13
- import { read, write } from "./transaction.js";
14
+ import { letWaitersIn, read, write } from "./transaction.js";
14
15
  const COLUMNS = "id, scope, value, mail_type, sender, organization_id, over_addresses, past, author, decided_by, reason, " +
15
16
  "created_at, updated_at, removed_at";
16
17
  const ruleOf = (row) => ({
@@ -73,7 +74,7 @@ const inScope = (database, scope, value) => {
73
74
  .filter((row) => sortRuleFor(alone, row) !== undefined);
74
75
  };
75
76
  const ADDRESS_ONLY = { subject: null, list: null, at: Number.MAX_SAFE_INTEGER };
76
- /** Where an identity sits now: `sender-bot:<id>`, `person:<id>` or `null`. */
77
+ /** Where an identity sits now: `bot:<id>`, `person:<id>` or `null`. */
77
78
  const holderOf = (database, identity) => {
78
79
  const bot = database.prepare("SELECT bot_id FROM sender_bot_identities WHERE identity_id = ?").get(identity);
79
80
  if (bot !== undefined)
@@ -81,6 +82,12 @@ const holderOf = (database, identity) => {
81
82
  const person = database.prepare("SELECT person_id FROM identity_links WHERE identity_id = ?").get(identity);
82
83
  return person === undefined ? null : `person:${person.person_id}`;
83
84
  };
85
+ /** Where an identity sits now and who put it there, as an effect's `before` keeps it: `bot:4 rules`. */
86
+ const heldOf = (database, identity) => {
87
+ const holder = holderOf(database, identity);
88
+ return holder === null ? null : `${holder} ${holdingAuthorOf(database, identity)}`;
89
+ };
90
+ const holderIn = (held) => (held === null ? null : (held.split(" ")[0] ?? null));
84
91
  const isWhere = (holder, sender) => holder?.startsWith(sender === "bot" ? SENDER_BOT_PREFIX : "person:") === true;
85
92
  const sendersOf = (database, identities) => database
86
93
  .prepare("SELECT DISTINCT e.from_identity_id AS identity, i.external_id AS address FROM emails e " +
@@ -122,7 +129,7 @@ export const settleSenders = (context, identities) => {
122
129
  const at = context.now();
123
130
  const mover = sortRuleFor(rules.sender, mail);
124
131
  if (mover?.sender && !hasEffect(database, mover.id, identity, "sender")) {
125
- const before = holderOf(database, identity);
132
+ const before = heldOf(database, identity);
126
133
  if (!isWhere(before, mover.sender))
127
134
  moveSender(context, address, mover);
128
135
  recordEffect(database, {
@@ -168,41 +175,59 @@ const moveSender = (context, address, rule) => {
168
175
  throw error;
169
176
  }
170
177
  };
171
- /** Puts back what a rule did to its senders, then lets the rules still live settle them. */
172
- const undoEffects = (context, rule) => {
178
+ /**
179
+ * Senders per write. A move to a bot takes about 10 ms, so 100 keep one write near 1 s, far from another writer's 5 s
180
+ * wait; putting one back is cheaper, but a write's commit costs the same.
181
+ */
182
+ const SETTLE_CHUNK = 100;
183
+ /** Whether the sender is still where the rule put it: else the owner moved it since, and that stands. */
184
+ const stillAfter = (database, identity, after) => {
185
+ const now = holderOf(database, identity);
186
+ if (now === after)
187
+ return true;
188
+ return (after?.startsWith("person:") === true &&
189
+ now === `person:${currentPerson(database, Number(after.slice("person:".length)))}`);
190
+ };
191
+ /**
192
+ * Puts back what removed rules did to up to `SETTLE_CHUNK` senders, newest effect first, each to its holder and author
193
+ * before the rule, then lets the rules still live settle them. Answers whether more may be left. The caller holds
194
+ * the write lock.
195
+ */
196
+ const putBackChunk = (context) => {
173
197
  const { database } = context;
198
+ const identities = database
199
+ .prepare("SELECT DISTINCT f.identity_id AS identity FROM mail_sort_effects f JOIN mail_sort_rules r ON r.id = f.rule_id " +
200
+ "WHERE r.removed_at IS NOT NULL AND f.undone_at IS NULL ORDER BY f.identity_id LIMIT ?")
201
+ .all(SETTLE_CHUNK)
202
+ .map((row) => Number(row.identity));
203
+ if (identities.length === 0)
204
+ return false;
174
205
  const effects = database
175
- .prepare("SELECT f.id, f.identity_id, f.action, f.before, f.after, i.external_id AS address FROM mail_sort_effects f " +
176
- "JOIN identities i ON i.id = f.identity_id WHERE f.rule_id = ? AND f.undone_at IS NULL ORDER BY f.id DESC")
177
- .all(rule);
206
+ .prepare("SELECT f.id, f.identity_id, f.action, f.before, f.after FROM mail_sort_effects f " +
207
+ "JOIN mail_sort_rules r ON r.id = f.rule_id WHERE r.removed_at IS NOT NULL AND f.undone_at IS NULL " +
208
+ "AND f.identity_id IN (SELECT value FROM json_each(?)) ORDER BY f.id DESC")
209
+ .all(JSON.stringify(identities));
178
210
  const at = context.now();
179
211
  for (const effect of effects) {
180
212
  const identity = Number(effect.identity_id);
181
- const subject = { provider: "email", id: String(effect.address) };
182
213
  const before = effect.before == null ? null : String(effect.before);
183
- if (effect.action === "sender" && before !== effect.after && before !== null) {
184
- const now = holderOf(database, identity);
185
- if (before.startsWith("person:") && !isWhere(now, "person"))
186
- moveToPerson(context, subject, { reason: "undo" });
187
- if (before.startsWith(SENDER_BOT_PREFIX) && !isWhere(now, "bot"))
188
- moveToBot(context, subject, {
189
- reason: "undo",
190
- ...(database
191
- .prepare("SELECT 1 FROM sender_bots WHERE id = ?")
192
- .get(Number(before.slice(SENDER_BOT_PREFIX.length)))
193
- ? { bot: before }
194
- : {}),
195
- });
196
- }
214
+ const after = effect.after == null ? null : String(effect.after);
215
+ const holder = holderIn(before);
216
+ if (effect.action === "sender" && holder !== null && holder !== after && stillAfter(database, identity, after))
217
+ putBack(context, identity, holder, before?.endsWith(" owner") ? "owner" : "rules");
197
218
  if (effect.action === "organization" && before === null)
198
219
  database
199
220
  .prepare("DELETE FROM organization_identities WHERE identity_id = ? AND organization_id = ? AND method = ?")
200
- .run(identity, Number(String(effect.after).slice("organization:".length)), SORT_METHOD);
221
+ .run(identity, Number(String(after).slice("organization:".length)), SORT_METHOD);
201
222
  database.prepare("UPDATE mail_sort_effects SET undone_at = ? WHERE id = ?").run(at, Number(effect.id));
202
223
  }
203
- const identities = [...new Set(effects.map((effect) => Number(effect.identity_id)))];
204
- if (identities.length > 0)
205
- settleSenders(context, identities);
224
+ settleSenders(context, identities);
225
+ return identities.length === SETTLE_CHUNK;
226
+ };
227
+ /** Each removed rule's senders put back a write at a time; a stopped run resumes on the next change of rules. */
228
+ const putBackInChunks = (context) => {
229
+ while (write(context.database, () => putBackChunk(context)))
230
+ letWaitersIn();
206
231
  };
207
232
  const clearTypes = (database, ids) => database
208
233
  .prepare("UPDATE emails SET mail_type = NULL, reach = NULL, type_signal = NULL " +
@@ -325,24 +350,26 @@ const applyRule = (context, rule) => {
325
350
  if (!rule.past)
326
351
  for (const { identity } of sendersOf(database, identities)) {
327
352
  const holder = holderOf(database, identity);
353
+ const held = heldOf(database, identity);
328
354
  for (const action of [...(rule.sender ? ["sender"] : []), ...(rule.organization ? ["organization"] : [])])
329
355
  recordEffect(database, {
330
356
  rule: rule.id,
331
357
  identity,
332
358
  action,
333
- before: action === "sender" ? holder : "held",
359
+ before: action === "sender" ? held : "held",
334
360
  after: action === "sender" ? holder : "held",
335
361
  at: context.now(),
336
362
  });
337
363
  }
338
364
  return identities;
339
365
  };
340
- /** Each move takes about 10 ms: 100 per write keeps another writer's 5 s wait for the lock far away. */
341
- const SETTLE_CHUNK = 100;
342
366
  /** Settles senders a write at a time; a sender already settled is skipped, so a stopped run resumes on the next. */
343
367
  const settleInChunks = (context, identities) => {
344
- for (let at = 0; at < identities.length; at += SETTLE_CHUNK)
368
+ for (let at = 0; at < identities.length; at += SETTLE_CHUNK) {
369
+ if (at > 0)
370
+ letWaitersIn();
345
371
  write(context.database, () => settleSenders(context, identities.slice(at, at + SETTLE_CHUNK)));
372
+ }
346
373
  };
347
374
  /** A change's time, later than every change before it, so undo takes changes back in order within one millisecond. */
348
375
  const stampOf = ({ database, now }) => Math.max(now(), Number(database.prepare("SELECT coalesce(max(updated_at), 0) + 1 AS at FROM mail_sort_rules").get()?.at));
@@ -353,20 +380,20 @@ const takeOut = (context, rule, undone) => {
353
380
  .run(at, at, undone ? at : null, rule.id);
354
381
  const removed = ruleById(context.database, rule.id);
355
382
  clearRuleTypes(context.database, removed);
356
- undoEffects(context, rule.id);
357
383
  return removed;
358
384
  };
359
385
  const ownerOnly = (by, what) => {
360
386
  if (by !== "owner")
361
387
  fail(`only the owner ${what}`, "mail-sort.owner-only");
362
388
  };
363
- const addressesOf = (database, sender) => {
364
- if (sender.includes("@") && !sender.includes(":"))
365
- return [sender.trim().toLowerCase()];
389
+ const addressesOf = (database, given) => {
390
+ if (given.includes("@") && !given.includes(":"))
391
+ return [given.trim().toLowerCase()];
392
+ const sender = senderBotRef(given);
366
393
  const bot = sender.startsWith(SENDER_BOT_PREFIX) ? Number(sender.slice(SENDER_BOT_PREFIX.length)) : undefined;
367
394
  const person = sender.startsWith("person:") ? Number(sender.slice("person:".length)) : undefined;
368
395
  if (bot === undefined && person === undefined)
369
- return fail(`${sender} names no sender: give an address, a person: or a sender-bot: ref`, "mail-sort.sender-ref");
396
+ return fail(`${sender} names no sender: give an address, a person: or a bot: ref`, "mail-sort.sender-ref");
370
397
  return database
371
398
  .prepare("SELECT lower(i.external_id) AS address FROM identities i WHERE i.provider = 'email' AND i.id IN " +
372
399
  (bot === undefined
@@ -422,14 +449,18 @@ export const mailSortingOver = (context) => {
422
449
  settleInChunks(context, identities);
423
450
  return result;
424
451
  },
425
- remove: async (id, by) => write(database, () => {
426
- const rule = ruleById(database, id);
427
- if (by !== "owner" && (rule.author !== "program" || rule.decidedBy !== by.bot))
428
- fail("a program removes only the rules it made", "mail-sort.owner-only");
429
- if (rule.removedAt !== null)
430
- return rule;
431
- return takeOut(context, rule, false);
432
- }),
452
+ remove: async (id, by) => {
453
+ const removed = write(database, () => {
454
+ const rule = ruleById(database, id);
455
+ if (by !== "owner" && (rule.author !== "program" || rule.decidedBy !== by.bot))
456
+ fail("a program removes only the rules it made", "mail-sort.owner-only");
457
+ if (rule.removedAt !== null)
458
+ return rule;
459
+ return takeOut(context, rule, false);
460
+ });
461
+ putBackInChunks(context);
462
+ return removed;
463
+ },
433
464
  undo: async (by) => {
434
465
  const { identities, undone } = write(database, () => {
435
466
  ownerOnly(by, "undoes a sorting change");
@@ -449,23 +480,28 @@ export const mailSortingOver = (context) => {
449
480
  const back = ruleById(database, rule.id);
450
481
  return { identities: applyRule(context, back), undone: { undid: "remove", rule: back } };
451
482
  });
483
+ putBackInChunks(context);
452
484
  settleInChunks(context, identities);
453
485
  return undone;
454
486
  },
455
- reset: async (sender, by) => write(database, () => {
456
- ownerOnly(by, "resets the manual sorting of a sender");
457
- const addresses = addressesOf(database, sender);
458
- const mails = database
459
- .prepare("SELECT id FROM emails WHERE lower(from_address) IN (SELECT value FROM json_each(?)) AND outgoing IS NOT 1")
460
- .all(JSON.stringify(addresses))
461
- .map((row) => String(row.id));
462
- return database
463
- .prepare(`SELECT ${COLUMNS} FROM mail_sort_rules WHERE removed_at IS NULL AND author = 'owner' AND ` +
464
- "((scope = 'address' AND value IN (SELECT value FROM json_each(?))) OR " +
465
- "(scope = 'mail' AND value IN (SELECT value FROM json_each(?)))) ORDER BY id DESC")
466
- .all(JSON.stringify(addresses), JSON.stringify(mails))
467
- .map((row) => takeOut(context, ruleOf(row), false));
468
- }),
487
+ reset: async (sender, by) => {
488
+ const removed = write(database, () => {
489
+ ownerOnly(by, "resets the manual sorting of a sender");
490
+ const addresses = addressesOf(database, sender);
491
+ const mails = database
492
+ .prepare("SELECT id FROM emails WHERE lower(from_address) IN (SELECT value FROM json_each(?)) AND outgoing IS NOT 1")
493
+ .all(JSON.stringify(addresses))
494
+ .map((row) => String(row.id));
495
+ return database
496
+ .prepare(`SELECT ${COLUMNS} FROM mail_sort_rules WHERE removed_at IS NULL AND author = 'owner' AND ` +
497
+ "((scope = 'address' AND value IN (SELECT value FROM json_each(?))) OR " +
498
+ "(scope = 'mail' AND value IN (SELECT value FROM json_each(?)))) ORDER BY id DESC")
499
+ .all(JSON.stringify(addresses), JSON.stringify(mails))
500
+ .map((row) => takeOut(context, ruleOf(row), false));
501
+ });
502
+ putBackInChunks(context);
503
+ return removed;
504
+ },
469
505
  };
470
506
  };
471
507
  /** The senders of mail just saved in these threads, settled by the rules that move or file senders. */
@@ -0,0 +1,70 @@
1
+ import type { MailType } from "../../mail/mail-types.js";
2
+ import type { CacheDatabase } from "../driver.js";
3
+ /** Where an unsubscribe goes, as the newest mail of a subscription that names one gave it. @experimental */
4
+ export interface UnsubscribeTarget {
5
+ /** The https target of List-Unsubscribe. */
6
+ https: string | null;
7
+ /** The mailto target of List-Unsubscribe. */
8
+ mailto: string | null;
9
+ /**
10
+ * RFC 8058 one-click: the mail also carries `List-Unsubscribe-Post: List-Unsubscribe=One-Click`, and its From
11
+ * domain signed both fields, so a POST to `https` unsubscribes without opening a page.
12
+ */
13
+ oneClick: boolean;
14
+ /** The mail the target was read from. */
15
+ emailId: number;
16
+ }
17
+ /** One list, or one sender of broadcast mail with no List-Id: a row of Subscriptions. @experimental */
18
+ export interface MailSubscription {
19
+ /** `list:<List-Id>`, else the sender: `bot:<id>`, `person:<id>` or `address:<address>`. */
20
+ key: string;
21
+ listId: string | null;
22
+ /** The display name on its newest email, else its address. */
23
+ name: string | null;
24
+ /** Who sent its newest email: `bot:<id>`, `person:<id>`, or `null` when the address is linked to neither. */
25
+ sender: string | null;
26
+ /** The From address of its newest email, lower case. */
27
+ address: string | null;
28
+ /** Its broadcast emails the filter takes in. */
29
+ emails: number;
30
+ newest: {
31
+ id: number;
32
+ externalId: string;
33
+ subject: string | null;
34
+ at: number | null;
35
+ };
36
+ /** `null` when none of its emails names a target its sender's DKIM signature vouches for. */
37
+ unsubscribe: UnsubscribeTarget | null;
38
+ }
39
+ /** @experimental */
40
+ export interface MailSubscriptionFilter {
41
+ /** Only mail of these accounts; every account when left out. */
42
+ accountIds?: readonly number[];
43
+ since?: number;
44
+ /** Exclusive. */
45
+ until?: number;
46
+ /** Only emails of these types: the promotions of a shop, without its receipts. */
47
+ types?: readonly MailType[];
48
+ limit?: number;
49
+ offset?: number;
50
+ }
51
+ /** @experimental */
52
+ export interface MailSubscriptionList {
53
+ items: MailSubscription[];
54
+ total: number;
55
+ hasMore: boolean;
56
+ }
57
+ /**
58
+ * Broadcast mail grouped by List-Id, else by its sender, newest group first, grouped, counted and paged in SQL. Each
59
+ * group carries its newest email and the unsubscribe target of its newest email that names one.
60
+ */
61
+ export declare const mailSubscriptions: (database: CacheDatabase, filter: MailSubscriptionFilter) => MailSubscriptionList;
62
+ /** @experimental */
63
+ export interface MailSubscriptionStore {
64
+ /**
65
+ * Subscriptions: broadcast mail grouped by List-Id, else by sender, newest first, each with its mail count, newest
66
+ * email and unsubscribe target. Nothing is unsubscribed.
67
+ */
68
+ subscriptions(filter?: MailSubscriptionFilter): Promise<MailSubscriptionList>;
69
+ }
70
+ export declare const mailSubscriptionStore: (database: CacheDatabase) => MailSubscriptionStore;
@@ -0,0 +1,132 @@
1
+ import { SENDER_BOT_PREFIX } from "../../domain/person-kinds.js";
2
+ import { typeWhere } from "./email-types.js";
3
+ import { LIST_ID } from "./sender-signals.js";
4
+ import { read } from "./transaction.js";
5
+ const LIMIT = 100;
6
+ const HTTPS = "json_extract(e.headers, '$.\"list-unsubscribe-https\"')";
7
+ const MAILTO = "json_extract(e.headers, '$.\"list-unsubscribe-mailto\"')";
8
+ const KEY = `CASE WHEN ${LIST_ID} IS NOT NULL THEN 'list:' || ${LIST_ID} ` +
9
+ `WHEN b.bot_id IS NOT NULL THEN '${SENDER_BOT_PREFIX}' || b.bot_id ` +
10
+ "WHEN l.person_id IS NOT NULL THEN 'person:' || l.person_id " +
11
+ "ELSE 'address:' || lower(e.from_address) END";
12
+ const SENDERS = "FROM emails e LEFT JOIN sender_bot_identities b ON b.identity_id = e.from_identity_id " +
13
+ "LEFT JOIN identity_links l ON l.identity_id = e.from_identity_id AND b.bot_id IS NULL";
14
+ /** The bare `id` is the row of `max(at)`, SQLite's rule for a bare column beside a single max(). */
15
+ const groupsSql = (where) => `SELECT key, count(*) AS emails, max(at) AS last, id AS newest, count(*) OVER () AS total FROM ` +
16
+ `(SELECT e.id, coalesce(e.received_at, e.sent_at) AS at, ${KEY} AS key ${SENDERS} WHERE ${where}) ` +
17
+ "GROUP BY key ORDER BY last DESC, key LIMIT ? OFFSET ?";
18
+ const EMAILS = `SELECT e.id, e.external_id, e.subject, lower(e.from_address) AS address, e.from_name, ${LIST_ID} AS list, ` +
19
+ `coalesce(e.received_at, e.sent_at) AS at, ${HTTPS} AS https, ${MAILTO} AS mailto, e.from_identity_id, ` +
20
+ "json_extract(e.headers, '$.\"list-unsubscribe-post\"') IS 1 AS post, b.bot_id, l.person_id " +
21
+ `${SENDERS} WHERE e.id IN (SELECT value FROM json_each(?))`;
22
+ /**
23
+ * Where a group's mail comes from, through an index: its List-Id, or its sender's identities and no List-Id. A target
24
+ * belongs to the list or the sender, so any of its mail in these accounts may name it, whatever its type or date. The
25
+ * `+` keeps SQLite off `emails_by_list_id` for "no List-Id", which holds most of the mail: 10 ms a group, not 0.05.
26
+ */
27
+ const SOURCES = {
28
+ list: `${LIST_ID} = ?`,
29
+ bot: `e.from_identity_id IN (SELECT identity_id FROM sender_bot_identities WHERE bot_id = ?) AND +${LIST_ID} IS NULL`,
30
+ person: `e.from_identity_id IN (SELECT identity_id FROM identity_links WHERE person_id = ?) AND +${LIST_ID} IS NULL`,
31
+ address: `e.from_identity_id = ? AND +${LIST_ID} IS NULL`,
32
+ };
33
+ const sourceOf = (newest) => typeof newest.list === "string"
34
+ ? ["list", newest.list]
35
+ : newest.bot_id != null
36
+ ? ["bot", Number(newest.bot_id)]
37
+ : newest.person_id != null
38
+ ? ["person", Number(newest.person_id)]
39
+ : newest.from_identity_id != null
40
+ ? ["address", Number(newest.from_identity_id)]
41
+ : undefined;
42
+ const str = (value) => (typeof value === "string" ? value : null);
43
+ /**
44
+ * Broadcast mail grouped by List-Id, else by its sender, newest group first, grouped, counted and paged in SQL. Each
45
+ * group carries its newest email and the unsubscribe target of its newest email that names one.
46
+ */
47
+ export const mailSubscriptions = (database, filter) => {
48
+ const limit = filter.limit ?? LIMIT;
49
+ const offset = filter.offset ?? 0;
50
+ const typed = typeWhere(database, { reaches: ["broadcast"], ...(filter.types ? { types: filter.types } : {}) });
51
+ const where = ["e.deleted_at IS NULL", "e.outgoing IS NOT 1", "e.from_address IS NOT NULL", ...typed.sql];
52
+ const params = [...typed.params];
53
+ const add = (sql, value) => {
54
+ if (value === undefined)
55
+ return;
56
+ where.push(sql);
57
+ params.push(value);
58
+ };
59
+ if (filter.accountIds !== undefined) {
60
+ where.push("e.account_id IN (SELECT value FROM json_each(?))");
61
+ params.push(JSON.stringify(filter.accountIds));
62
+ }
63
+ add("coalesce(e.received_at, e.sent_at) >= ?", filter.since);
64
+ add("coalesce(e.received_at, e.sent_at) < ?", filter.until);
65
+ return read(database, () => {
66
+ const groups = database.prepare(groupsSql(where.join(" AND "))).all(...params, limit, offset);
67
+ const total = groups.length > 0
68
+ ? Number(groups[0]?.total)
69
+ : offset === 0
70
+ ? 0
71
+ : Number(database
72
+ .prepare(`SELECT count(DISTINCT ${KEY}) AS n ${SENDERS} WHERE ${where.join(" AND ")}`)
73
+ .get(...params)?.n);
74
+ const emailsOf = (ids) => new Map(database
75
+ .prepare(EMAILS)
76
+ .all(JSON.stringify(ids))
77
+ .map((row) => [Number(row.id), row]));
78
+ const newestOf = emailsOf(groups.map((group) => Number(group.newest)));
79
+ const accounts = filter.accountIds === undefined ? "" : " AND e.account_id IN (SELECT value FROM json_each(?))";
80
+ const targetSql = (source) => `SELECT e.id FROM emails e WHERE ${source} AND e.deleted_at IS NULL AND e.outgoing IS NOT 1${accounts} ` +
81
+ `AND (${HTTPS} IS NOT NULL OR ${MAILTO} IS NOT NULL) ORDER BY coalesce(e.received_at, e.sent_at) DESC, e.id DESC LIMIT 1`;
82
+ const statements = new Map();
83
+ const targetIdOf = (newest) => {
84
+ const source = newest === undefined ? undefined : sourceOf(newest);
85
+ if (source === undefined)
86
+ return undefined;
87
+ const [kind, value] = source;
88
+ const statement = statements.get(kind) ?? database.prepare(targetSql(SOURCES[kind]));
89
+ statements.set(kind, statement);
90
+ const found = statement.get(value, ...(filter.accountIds === undefined ? [] : [JSON.stringify(filter.accountIds)]));
91
+ return found === undefined ? undefined : Number(found.id);
92
+ };
93
+ const targets = groups.map((group) => targetIdOf(newestOf.get(Number(group.newest))));
94
+ const targetOf = emailsOf(targets.filter((id) => id !== undefined));
95
+ const items = groups.map((group, at) => {
96
+ const newest = newestOf.get(Number(group.newest)) ?? {};
97
+ const targetId = targets[at];
98
+ const target = targetId === undefined ? undefined : targetOf.get(targetId);
99
+ const https = str(target?.https);
100
+ return {
101
+ key: String(group.key),
102
+ listId: str(newest.list),
103
+ name: str(newest.from_name) ?? str(newest.address),
104
+ sender: newest.bot_id != null
105
+ ? `${SENDER_BOT_PREFIX}${newest.bot_id}`
106
+ : newest.person_id != null
107
+ ? `person:${newest.person_id}`
108
+ : null,
109
+ address: str(newest.address),
110
+ emails: Number(group.emails),
111
+ newest: {
112
+ id: Number(group.newest),
113
+ externalId: String(newest.external_id),
114
+ subject: str(newest.subject),
115
+ at: newest.at == null ? null : Number(newest.at),
116
+ },
117
+ unsubscribe: target === undefined
118
+ ? null
119
+ : {
120
+ https,
121
+ mailto: str(target.mailto),
122
+ oneClick: https !== null && Number(target.post) === 1,
123
+ emailId: Number(target.id),
124
+ },
125
+ };
126
+ });
127
+ return { items, total, hasMore: total > offset + groups.length };
128
+ });
129
+ };
130
+ export const mailSubscriptionStore = (database) => ({
131
+ subscriptions: async (filter = {}) => mailSubscriptions(database, filter),
132
+ });
@@ -30,6 +30,50 @@ const V31_TABLES = [
30
30
  ];
31
31
  /** Version 56 rewrites CRM links and folds duplicates, which an older build would write again. */
32
32
  const V56_TABLES = ["links", "proposed_actions"];
33
+ /**
34
+ * Version 78 renames the agents' `bot` to `agent` in every pointer pair and ref, so `bot:` can name sender bots: a build
35
+ * before it would read a sender bot's `bot:` as an agent and write agents as `bot` again. `persons` is here for the
36
+ * triggers that clear a person's kind when a record, an assignment or a deal link they hold changes type.
37
+ */
38
+ const V78_TABLES = [
39
+ "agent_actions",
40
+ "aliases",
41
+ "attachments",
42
+ "catalog_items",
43
+ "contracts",
44
+ "deals",
45
+ "decisions",
46
+ "document_annotation_transfers",
47
+ "enrichments",
48
+ "entity_link_events",
49
+ "facts",
50
+ "financial_accounts",
51
+ "financial_transactions",
52
+ "invoices",
53
+ "leads",
54
+ "link_reviews",
55
+ "links",
56
+ "mail_sort_effects",
57
+ "memories",
58
+ "notes",
59
+ "orders",
60
+ "payment_allocations",
61
+ "payments",
62
+ "persons",
63
+ "pipeline_stage_changes",
64
+ "projects",
65
+ "proposed_actions",
66
+ "record_relations",
67
+ "records",
68
+ "subscription_prices",
69
+ "subscriptions",
70
+ "tag_consolidations",
71
+ "taggings",
72
+ "task_assignments",
73
+ "task_events",
74
+ "task_pairs",
75
+ "tasks",
76
+ ];
33
77
  /** Version 73 makes every base table with an integer `id` AUTOINCREMENT, by copying it: all of them change. */
34
78
  const V73_TABLES = [
35
79
  "accounts",
@@ -255,6 +299,7 @@ export const MANIFEST = [
255
299
  { name: "20261125183555_version-76-mail-type-triggers", version: 76, minCompatible: 73 },
256
300
  { name: "20261125205013_version-77-mail-sort-rules", version: 77, minCompatible: 73 },
257
301
  { name: "20261125205014_version-77-mail-sort-triggers", version: 77, minCompatible: 73 },
302
+ { name: "20261125231505_version-78-agent-refs", version: 78, minCompatible: 78, tables: V78_TABLES },
258
303
  ];
259
304
  export const generatedMigrations = (manifest = MANIFEST, generated = GENERATED) => {
260
305
  const migrations = [];
@@ -191,7 +191,7 @@ export const meetingFindingsStoreOver = (context) => {
191
191
  // Rejecting creates nothing, so a batch whose evidence changed can still be closed.
192
192
  if (accepted.length && snapshot(account, pendingOf(batch.input, input.decided)) !== input.snapshotHash)
193
193
  return stale();
194
- if (proposal.proposedBy.type !== "bot" || !proposal.proposedBy.name)
194
+ if (proposal.proposedBy.type !== "agent" || !proposal.proposedBy.name)
195
195
  return invalid("a findings author must be an agent");
196
196
  const agent = {
197
197
  bot: proposal.proposedBy.name,
@@ -14,7 +14,7 @@ import { closeSourceReviews, eraseSourceReviews, sourceReviewOf } from "./source
14
14
  import { stemmerCache } from "./stems.js";
15
15
  import { referenceOfThing, storedThing } from "./things.js";
16
16
  import { write } from "./transaction.js";
17
- const NAMED = "SELECT m.*, b.name AS author_name, b.kind AS author_kind FROM memories m LEFT JOIN bots b ON m.author_type = 'bot' AND b.id = m.author_id";
17
+ const NAMED = "SELECT m.*, b.name AS author_name, b.kind AS author_kind FROM memories m LEFT JOIN bots b ON m.author_type = 'agent' AND b.id = m.author_id";
18
18
  const iso = (value) => new Date(Number(value)).toISOString();
19
19
  const oneOf = (value, allowed, what) => {
20
20
  if (typeof value !== "string" || !allowed.includes(value))
@@ -33,7 +33,7 @@ export const authorOf = (row) => ({
33
33
  type: row.author_type,
34
34
  id: String(row.author_id),
35
35
  name: row.author_name == null ? null : String(row.author_name),
36
- kind: row.author_type !== "bot" ? null : row.author_kind === "rule" || row.author_name === "rule" ? "rule" : "agent",
36
+ kind: row.author_type !== "agent" ? null : row.author_kind === "rule" || row.author_name === "rule" ? "rule" : "agent",
37
37
  });
38
38
  /**
39
39
  * Writes `evidence` links from a row to each reference, refusing one the store does not hold. Each link keeps the
@@ -332,7 +332,7 @@ export const memoriesStoreOver = (context) => {
332
332
  const offset = Math.max(from, 0);
333
333
  const rows = database
334
334
  .prepare("SELECT m.*, b.name AS author_name, b.kind AS author_kind FROM memory_words w JOIN memories m ON m.id = w.rowid " +
335
- "LEFT JOIN bots b ON m.author_type = 'bot' AND b.id = m.author_id WHERE memory_words MATCH ? " +
335
+ "LEFT JOIN bots b ON m.author_type = 'agent' AND b.id = m.author_id WHERE memory_words MATCH ? " +
336
336
  "AND m.deleted_at IS NULL AND (? IS NULL OR (m.subject_type = ? AND m.subject_id IN (SELECT value FROM json_each(?)))) " +
337
337
  "AND (? IS NULL OR m.scope = ?) ORDER BY bm25(memory_words), m.id LIMIT ? OFFSET ?")
338
338
  .all(match, subject?.type ?? null, subject?.type ?? null, subject ? idsOf(database, subject.type, subject.id) : null, scope ?? null, scope ?? null, limit + 1, offset)