@wirecat/cli-core 1.2.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 (150) hide show
  1. package/CHANGELOG.md +170 -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/contract-templates.js +3 -0
  10. package/dist/cli/documents/file-edit.js +6 -6
  11. package/dist/cli/documents/library.js +4 -2
  12. package/dist/cli/help/first-screen.js +2 -2
  13. package/dist/cli/index.d.ts +7 -6
  14. package/dist/cli/index.js +3 -2
  15. package/dist/cli/messenger/account-command.js +0 -10
  16. package/dist/cli/messenger/accounts.d.ts +1 -1
  17. package/dist/cli/messenger/accounts.js +1 -1
  18. package/dist/cli/messenger/context.d.ts +17 -1
  19. package/dist/cli/messenger/doctor-command.js +16 -1
  20. package/dist/cli/messenger/flooded.js +9 -1
  21. package/dist/cli/messenger/serve-relay.d.ts +2 -0
  22. package/dist/cli/messenger/session-commands.d.ts +1 -1
  23. package/dist/cli/messenger/session-commands.js +1 -1
  24. package/dist/cli/oauth-session.d.ts +3 -2
  25. package/dist/cli/oauth-session.js +19 -3
  26. package/dist/cli/profile-store.d.ts +24 -10
  27. package/dist/cli/profile-store.js +43 -28
  28. package/dist/cli/program.js +2 -2
  29. package/dist/cli/settings.d.ts +3 -3
  30. package/dist/cli/shared-command-exports.d.ts +1 -1
  31. package/dist/cli/token-session.d.ts +21 -2
  32. package/dist/cli/token-session.js +27 -11
  33. package/dist/crm/cli/files.js +7 -7
  34. package/dist/documents.d.ts +1 -1
  35. package/dist/documents.js +1 -1
  36. package/dist/domain/person-kinds.d.ts +7 -3
  37. package/dist/domain/person-kinds.js +7 -3
  38. package/dist/domain/ref-summaries.js +1 -0
  39. package/dist/domain/references.d.ts +3 -2
  40. package/dist/domain/references.js +19 -10
  41. package/dist/entities/deal.d.ts +2 -2
  42. package/dist/entities/deal.js +1 -1
  43. package/dist/entities/fact.d.ts +2 -2
  44. package/dist/entities/fact.js +1 -1
  45. package/dist/entities/fields.d.ts +1 -1
  46. package/dist/entities/fields.js +1 -1
  47. package/dist/entities/index.d.ts +15 -15
  48. package/dist/entities/mail-findings.d.ts +2 -2
  49. package/dist/entities/mail-findings.js +1 -1
  50. package/dist/entities/meeting-findings.d.ts +2 -2
  51. package/dist/entities/meeting-findings.js +1 -1
  52. package/dist/entities/memory.d.ts +1 -1
  53. package/dist/entities/store-maintenance.js +1 -1
  54. package/dist/entities/task-results.d.ts +5 -5
  55. package/dist/entities/task-results.js +1 -1
  56. package/dist/entities/task.d.ts +1 -1
  57. package/dist/entities/task.js +1 -1
  58. package/dist/errors/failures.d.ts +6 -0
  59. package/dist/errors/failures.js +18 -4
  60. package/dist/errors/reasons.js +2 -1
  61. package/dist/errors/store-reasons.js +1 -0
  62. package/dist/fetch/page.js +1 -2
  63. package/dist/mail/headers.d.ts +4 -3
  64. package/dist/mail/headers.js +21 -3
  65. package/dist/mail/sort-rules.d.ts +13 -6
  66. package/dist/mail/sort-rules.js +20 -16
  67. package/dist/mail/sync.js +2 -0
  68. package/dist/mcp/tool.js +2 -2
  69. package/dist/mcp/tools/attachments.js +1 -1
  70. package/dist/office/zip.js +1 -1
  71. package/dist/ports/messenger.d.ts +31 -1
  72. package/dist/runs/recording.js +2 -2
  73. package/dist/services/archive.js +61 -11
  74. package/dist/services/attachments.js +4 -4
  75. package/dist/services/documents/file-text.js +2 -2
  76. package/dist/services/metadata.d.ts +1 -1
  77. package/dist/services/proposals/kinds/shared.d.ts +1 -1
  78. package/dist/services/proposals/kinds/shared.js +2 -2
  79. package/dist/services/proposals/kinds/task-close.js +1 -1
  80. package/dist/store/areas.d.ts +2 -0
  81. package/dist/store/areas.js +1 -0
  82. package/dist/store/decisions.d.ts +1 -1
  83. package/dist/store/decisions.js +4 -4
  84. package/dist/store/evidence-findings.d.ts +2 -2
  85. package/dist/store/index.d.ts +3 -1
  86. package/dist/store/index.js +2 -1
  87. package/dist/store/mail-findings.d.ts +2 -2
  88. package/dist/store/meeting-findings.d.ts +2 -2
  89. package/dist/store/people.d.ts +4 -4
  90. package/dist/store/people.js +2 -1
  91. package/dist/store/project-transfer/manifest.js +3 -3
  92. package/dist/store/public.d.ts +1 -1
  93. package/dist/store/public.js +1 -1
  94. package/dist/store/sqlite/actors.d.ts +1 -1
  95. package/dist/store/sqlite/actors.js +6 -6
  96. package/dist/store/sqlite/agent-actions.js +2 -2
  97. package/dist/store/sqlite/agent-links.js +1 -1
  98. package/dist/store/sqlite/bot-sends.d.ts +19 -0
  99. package/dist/store/sqlite/bot-sends.js +36 -0
  100. package/dist/store/sqlite/business-contracts.js +1 -1
  101. package/dist/store/sqlite/deals.js +1 -1
  102. package/dist/store/sqlite/document-transfer/plan.js +1 -1
  103. package/dist/store/sqlite/document-transfer/snapshot.js +1 -1
  104. package/dist/store/sqlite/email-index.d.ts +11 -2
  105. package/dist/store/sqlite/email-index.js +56 -5
  106. package/dist/store/sqlite/email-types.d.ts +15 -3
  107. package/dist/store/sqlite/email-types.js +32 -1
  108. package/dist/store/sqlite/emails.d.ts +2 -1
  109. package/dist/store/sqlite/emails.js +6 -1
  110. package/dist/store/sqlite/entity-types.d.ts +1 -1
  111. package/dist/store/sqlite/entity-types.js +1 -1
  112. package/dist/store/sqlite/evidence-findings.js +1 -1
  113. package/dist/store/sqlite/facts.js +1 -1
  114. package/dist/store/sqlite/finance.js +2 -2
  115. package/dist/store/sqlite/knowledge.js +1 -0
  116. package/dist/store/sqlite/mail-findings.js +1 -1
  117. package/dist/store/sqlite/mail-sorting.d.ts +1 -1
  118. package/dist/store/sqlite/mail-sorting.js +96 -60
  119. package/dist/store/sqlite/mail-subscriptions.d.ts +70 -0
  120. package/dist/store/sqlite/mail-subscriptions.js +132 -0
  121. package/dist/store/sqlite/manifest.js +45 -0
  122. package/dist/store/sqlite/meeting-findings.js +1 -1
  123. package/dist/store/sqlite/memories.js +3 -3
  124. package/dist/store/sqlite/migrations.generated.js +80 -0
  125. package/dist/store/sqlite/money-transactions.js +1 -1
  126. package/dist/store/sqlite/note-index.d.ts +4 -1
  127. package/dist/store/sqlite/note-index.js +40 -17
  128. package/dist/store/sqlite/orders.js +1 -1
  129. package/dist/store/sqlite/payment-facts.js +2 -2
  130. package/dist/store/sqlite/products.js +1 -1
  131. package/dist/store/sqlite/project-transfer/sources.js +2 -2
  132. package/dist/store/sqlite/proposed-actions.js +3 -3
  133. package/dist/store/sqlite/record-projection.js +1 -1
  134. package/dist/store/sqlite/ref-summaries.js +2 -1
  135. package/dist/store/sqlite/relation-proposals.js +1 -1
  136. package/dist/store/sqlite/reviewed.d.ts +2 -2
  137. package/dist/store/sqlite/reviewed.js +1 -1
  138. package/dist/store/sqlite/sender-bots.d.ts +19 -4
  139. package/dist/store/sqlite/sender-bots.js +48 -4
  140. package/dist/store/sqlite/subscriptions.js +2 -2
  141. package/dist/store/sqlite/task-close.js +1 -1
  142. package/dist/store/sqlite/task-comments.js +1 -1
  143. package/dist/store/sqlite/things.js +1 -1
  144. package/dist/store/sqlite/transaction.d.ts +5 -0
  145. package/dist/store/sqlite/transaction.js +6 -1
  146. package/dist/store/sqlite/wallets.js +1 -1
  147. package/dist/store/sqlite/work-tasks.js +2 -2
  148. package/dist/tracker/tasks.js +4 -2
  149. package/package.json +7 -5
  150. package/parity.json +9 -3
@@ -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)
@@ -2190,5 +2190,85 @@ export const GENERATED = [
2190
2190
  "CREATE TRIGGER mail_sort_checked_au AFTER UPDATE OF mail_type ON emails\nWHEN NEW.mail_type IS NULL AND NEW.sort_checked IS NOT NULL BEGIN\n UPDATE emails SET sort_checked = NULL WHERE id = NEW.id;\nEND;",
2191
2191
  "CREATE TRIGGER mail_sort_effects_identity_ad AFTER DELETE ON identities BEGIN\n DELETE FROM mail_sort_effects WHERE identity_id = OLD.id;\nEND;"
2192
2192
  ]
2193
+ },
2194
+ {
2195
+ "name": "20261125231505_version-78-agent-refs",
2196
+ "statements": [
2197
+ "-- Until version 78 `bot` named the agents of the `bots` table, in every pointer pair and ref. Sender bots take\n-- `bot:` now, so the agents' values move to `agent` first, and `sender-bot:` refs become `bot:` after. Whole values\n-- only: a text replace would turn `sender-bot:5` and `telegram-bot:` into something else.\nUPDATE agent_actions SET actor_type = 'agent' WHERE actor_type = 'bot';",
2198
+ "UPDATE agent_actions SET target_type = 'agent' WHERE target_type = 'bot';",
2199
+ "UPDATE aliases SET aliasable_type = 'agent' WHERE aliasable_type = 'bot';",
2200
+ "UPDATE attachments SET attachable_type = 'agent' WHERE attachable_type = 'bot';",
2201
+ "UPDATE catalog_items SET supplier_type = 'agent' WHERE supplier_type = 'bot';",
2202
+ "UPDATE catalog_items SET author_type = 'agent' WHERE author_type = 'bot';",
2203
+ "UPDATE contracts SET author_type = 'agent' WHERE author_type = 'bot';",
2204
+ "UPDATE contracts SET confirmed_by_type = 'agent' WHERE confirmed_by_type = 'bot';",
2205
+ "UPDATE deals SET author_type = 'agent' WHERE author_type = 'bot';",
2206
+ "UPDATE decisions SET confirmed_by_type = 'agent' WHERE confirmed_by_type = 'bot';",
2207
+ "UPDATE enrichments SET subject_type = 'agent' WHERE subject_type = 'bot';",
2208
+ "UPDATE entity_link_events SET linkable_type = 'agent' WHERE linkable_type = 'bot';",
2209
+ "UPDATE facts SET subject_type = 'agent' WHERE subject_type = 'bot';",
2210
+ "UPDATE facts SET author_type = 'agent' WHERE author_type = 'bot';",
2211
+ "UPDATE facts SET confirmed_by_type = 'agent' WHERE confirmed_by_type = 'bot';",
2212
+ "UPDATE financial_accounts SET holder_type = 'agent' WHERE holder_type = 'bot';",
2213
+ "UPDATE financial_accounts SET author_type = 'agent' WHERE author_type = 'bot';",
2214
+ "UPDATE financial_transactions SET counterparty_type = 'agent' WHERE counterparty_type = 'bot';",
2215
+ "UPDATE financial_transactions SET author_type = 'agent' WHERE author_type = 'bot';",
2216
+ "UPDATE financial_transactions SET confirmed_by_type = 'agent' WHERE confirmed_by_type = 'bot';",
2217
+ "UPDATE invoices SET issuer_type = 'agent' WHERE issuer_type = 'bot';",
2218
+ "UPDATE invoices SET counterparty_type = 'agent' WHERE counterparty_type = 'bot';",
2219
+ "UPDATE invoices SET author_type = 'agent' WHERE author_type = 'bot';",
2220
+ "UPDATE invoices SET confirmed_by_type = 'agent' WHERE confirmed_by_type = 'bot';",
2221
+ "UPDATE involvements SET subject_type = 'agent' WHERE subject_type = 'bot';",
2222
+ "UPDATE leads SET author_type = 'agent' WHERE author_type = 'bot';",
2223
+ "UPDATE link_reviews SET linkable_type = 'agent' WHERE linkable_type = 'bot';",
2224
+ "UPDATE links SET from_type = 'agent' WHERE from_type = 'bot';",
2225
+ "UPDATE links SET to_type = 'agent' WHERE to_type = 'bot';",
2226
+ "UPDATE memories SET subject_type = 'agent' WHERE subject_type = 'bot';",
2227
+ "UPDATE memories SET author_type = 'agent' WHERE author_type = 'bot';",
2228
+ "UPDATE mentions SET source_type = 'agent' WHERE source_type = 'bot';",
2229
+ "UPDATE mentions SET target_type = 'agent' WHERE target_type = 'bot';",
2230
+ "UPDATE notes SET notable_type = 'agent' WHERE notable_type = 'bot';",
2231
+ "UPDATE notes SET author_type = 'agent' WHERE author_type = 'bot';",
2232
+ "UPDATE orders SET customer_type = 'agent' WHERE customer_type = 'bot';",
2233
+ "UPDATE orders SET supplier_type = 'agent' WHERE supplier_type = 'bot';",
2234
+ "UPDATE orders SET author_type = 'agent' WHERE author_type = 'bot';",
2235
+ "UPDATE orders SET confirmed_by_type = 'agent' WHERE confirmed_by_type = 'bot';",
2236
+ "UPDATE payment_allocations SET author_type = 'agent' WHERE author_type = 'bot';",
2237
+ "UPDATE payments SET payer_type = 'agent' WHERE payer_type = 'bot';",
2238
+ "UPDATE payments SET payee_type = 'agent' WHERE payee_type = 'bot';",
2239
+ "UPDATE payments SET author_type = 'agent' WHERE author_type = 'bot';",
2240
+ "UPDATE payments SET confirmed_by_type = 'agent' WHERE confirmed_by_type = 'bot';",
2241
+ "UPDATE pipeline_stage_changes SET item_type = 'agent' WHERE item_type = 'bot';",
2242
+ "UPDATE projects SET owner_type = 'agent' WHERE owner_type = 'bot';",
2243
+ "UPDATE proposed_actions SET target_type = 'agent' WHERE target_type = 'bot';",
2244
+ "UPDATE proposed_actions SET proposed_by_type = 'agent' WHERE proposed_by_type = 'bot';",
2245
+ "UPDATE proposed_actions SET decided_by_type = 'agent' WHERE decided_by_type = 'bot';",
2246
+ "UPDATE record_relations SET target_type = 'agent' WHERE target_type = 'bot';",
2247
+ "UPDATE records SET entity_type = 'agent' WHERE entity_type = 'bot';",
2248
+ "UPDATE subscription_prices SET author_type = 'agent' WHERE author_type = 'bot';",
2249
+ "UPDATE subscription_prices SET confirmed_by_type = 'agent' WHERE confirmed_by_type = 'bot';",
2250
+ "UPDATE subscriptions SET supplier_type = 'agent' WHERE supplier_type = 'bot';",
2251
+ "UPDATE subscriptions SET customer_type = 'agent' WHERE customer_type = 'bot';",
2252
+ "UPDATE subscriptions SET author_type = 'agent' WHERE author_type = 'bot';",
2253
+ "UPDATE subscriptions SET confirmed_by_type = 'agent' WHERE confirmed_by_type = 'bot';",
2254
+ "UPDATE tag_consolidations SET actor_type = 'agent' WHERE actor_type = 'bot';",
2255
+ "UPDATE taggings SET taggable_type = 'agent' WHERE taggable_type = 'bot';",
2256
+ "UPDATE taggings SET author_type = 'agent' WHERE author_type = 'bot';",
2257
+ "UPDATE task_assignments SET assignee_type = 'agent' WHERE assignee_type = 'bot';",
2258
+ "UPDATE task_events SET actor_type = 'agent' WHERE actor_type = 'bot';",
2259
+ "UPDATE task_pairs SET decided_by_type = 'agent' WHERE decided_by_type = 'bot';",
2260
+ "UPDATE tasks SET closed_by_type = 'agent' WHERE closed_by_type = 'bot';",
2261
+ "UPDATE tasks SET author_type = 'agent' WHERE author_type = 'bot';",
2262
+ "UPDATE tasks SET close_suggested_by_type = 'agent' WHERE close_suggested_by_type = 'bot';",
2263
+ "UPDATE links SET target_text = 'agent:' || substr(target_text, 5) WHERE target_text LIKE 'bot:%';",
2264
+ "UPDATE links SET metadata = json_set(metadata, '$.gone', 'agent') WHERE json_valid(metadata) AND json_extract(metadata, '$.gone') = 'bot';",
2265
+ "UPDATE record_relations SET target_external_id = 'agent:' || substr(target_external_id, 5) WHERE target_type = 'ref' AND target_external_id LIKE 'bot:%';",
2266
+ "UPDATE proposed_actions SET payload = json_set(payload, '$.from', 'agent:' || substr(json_extract(payload, '$.from'), 5)) WHERE json_valid(payload) AND json_type(payload, '$.from') = 'text' AND json_extract(payload, '$.from') LIKE 'bot:%';",
2267
+ "UPDATE proposed_actions SET payload = json_set(payload, '$.to', 'agent:' || substr(json_extract(payload, '$.to'), 5)) WHERE json_valid(payload) AND json_type(payload, '$.to') = 'text' AND json_extract(payload, '$.to') LIKE 'bot:%';",
2268
+ "UPDATE proposed_actions SET payload = json_set(payload, '$.ref', 'agent:' || substr(json_extract(payload, '$.ref'), 5)) WHERE json_valid(payload) AND json_type(payload, '$.ref') = 'text' AND json_extract(payload, '$.ref') LIKE 'bot:%';",
2269
+ "UPDATE document_annotation_transfers SET reference_map = (SELECT json_group_object(key, CASE WHEN type = 'text' AND value LIKE 'bot:%' THEN 'agent:' || substr(value, 5) ELSE value END) FROM json_each(document_annotation_transfers.reference_map)) WHERE json_valid(reference_map) AND reference_map LIKE '%\"bot:%'\n AND NOT EXISTS (SELECT 1 FROM json_each(document_annotation_transfers.reference_map) WHERE type NOT IN ('text', 'null'));",
2270
+ "UPDATE mail_sort_effects SET \"before\" = 'bot:' || substr(\"before\", 12) WHERE \"before\" LIKE 'sender-bot:%';",
2271
+ "UPDATE mail_sort_effects SET \"after\" = 'bot:' || substr(\"after\", 12) WHERE \"after\" LIKE 'sender-bot:%';"
2272
+ ]
2193
2273
  }
2194
2274
  ];
@@ -12,7 +12,7 @@ import { write } from "./transaction.js";
12
12
  const TRANSACTIONS = "SELECT t.*, w.name AS wallet_name, b.name AS author_name, b.kind AS author_kind, " +
13
13
  "(SELECT coalesce(sum(amount), 0) FROM transaction_splits WHERE transaction_id = t.id) AS split " +
14
14
  "FROM financial_transactions t JOIN financial_accounts w ON w.id = t.financial_account_id " +
15
- "LEFT JOIN bots b ON t.author_type = 'bot' AND b.id = t.author_id";
15
+ "LEFT JOIN bots b ON t.author_type = 'agent' AND b.id = t.author_id";
16
16
  const MAX_SPLITS = 100;
17
17
  export const transactionOperationsOver = (context) => {
18
18
  const { database, now } = context;
@@ -123,10 +123,13 @@ export declare const noteIndexState: (database: CacheDatabase) => NoteIndexState
123
123
  * Indexes one corpus's rows written since the last drain, in short write transactions. These corpora are
124
124
  * small, so a change of stemmer choices simply queues every row again instead of waiting for `store rebuild`.
125
125
  */
126
- export declare const drainCorpus: (database: CacheDatabase, corpus: Corpus, stemmerFor: (stemmers: Stemmers) => Stemmer, { batch, until }?: {
126
+ export declare const drainCorpus: (database: CacheDatabase, corpus: Corpus, stemmerFor: (stemmers: Stemmers) => Stemmer, { batch, until, budgetMs }?: {
127
127
  batch?: number;
128
128
  until?: () => boolean;
129
+ budgetMs?: number;
129
130
  }) => number;
131
+ /** Indexes these queued rows now, inside the caller's write, so they share its commit. */
132
+ export declare const indexQueued: (database: CacheDatabase, corpus: Corpus, stemmerFor: (stemmers: Stemmers) => Stemmer, ids: readonly number[]) => number;
130
133
  /** Documents, then notes: what a notes search reads; then the trigrams still to fill. */
131
134
  export declare const drainNoteIndex: (database: CacheDatabase, stemmerFor: (stemmers: Stemmers) => Stemmer, options?: {
132
135
  batch?: number;
@@ -266,13 +266,8 @@ const writer = (database, corpus, stemmer) => {
266
266
  statements.dequeue.run(queuedAs(corpus), id);
267
267
  };
268
268
  };
269
- /**
270
- * Indexes one corpus's rows written since the last drain, in short write transactions. These corpora are
271
- * small, so a change of stemmer choices simply queues every row again instead of waiting for `store rebuild`.
272
- */
273
- export const drainCorpus = (database, corpus, stemmerFor, { batch = 200, until = () => false } = {}) => {
274
- if (isQueryOnly(database))
275
- return 0;
269
+ /** The corpus's writer once its index state is set up, or `undefined` when the store wants no index for it. */
270
+ const readyWriter = (database, corpus, stemmerFor) => {
276
271
  // Pieces written before they carried their account get it, once: purge and vector search filter by it.
277
272
  if ((corpus.type === "email" || corpus.type === "document") &&
278
273
  database.prepare("SELECT 1 FROM chunks WHERE chunkable_type = ? AND account_id IS NULL LIMIT 1").get(corpus.type))
@@ -287,31 +282,48 @@ export const drainCorpus = (database, corpus, stemmerFor, { batch = 200, until =
287
282
  .run(corpus.index));
288
283
  const state = corpusIndexState(database, corpus);
289
284
  if (state.wanted === null)
290
- return 0;
285
+ return undefined;
291
286
  const stemmer = stemmerFor(savedStemmers(database) ?? DEFAULT_STEMMERS);
292
- const queue = `${corpus.type}_index_pending`;
293
287
  if (state.built !== stemmer.identity) {
294
288
  write(database, () => {
295
289
  if (state.built !== null)
296
290
  database
297
- .prepare(`INSERT OR IGNORE INTO ${queue} (indexable_type, id) SELECT ?, id FROM ${corpus.table}`)
291
+ .prepare(`INSERT OR IGNORE INTO ${corpus.type}_index_pending (indexable_type, id) SELECT ?, id FROM ${corpus.table}`)
298
292
  .run(queuedAs(corpus));
299
293
  database.prepare("UPDATE search_index_state SET analyzer = ? WHERE name = ?").run(stemmer.identity, corpus.index);
300
294
  });
301
295
  }
302
- if (state.pending === 0 && state.built === stemmer.identity)
296
+ else if (state.pending === 0)
297
+ return undefined;
298
+ return writer(database, corpus, stemmer);
299
+ };
300
+ /**
301
+ * Indexes one corpus's rows written since the last drain, in short write transactions. These corpora are
302
+ * small, so a change of stemmer choices simply queues every row again instead of waiting for `store rebuild`.
303
+ */
304
+ export const drainCorpus = (database, corpus, stemmerFor, { batch = 200, until = () => false, budgetMs = 0 } = {}) => {
305
+ if (isQueryOnly(database))
303
306
  return 0;
304
- const next = database.prepare(`SELECT id FROM ${queue} WHERE indexable_type = ? ORDER BY id LIMIT ?`);
305
- const index = writer(database, corpus, stemmer);
307
+ const index = readyWriter(database, corpus, stemmerFor);
308
+ if (index === undefined)
309
+ return 0;
310
+ const next = database.prepare(`SELECT id FROM ${corpus.type}_index_pending WHERE indexable_type = ? ORDER BY id LIMIT ?`);
306
311
  let done = 0;
307
312
  for (;;) {
308
313
  if (until())
309
314
  break;
315
+ // Batches go on in one write until the budget is spent: each commit syncs to disk, which under load costs more
316
+ // than indexing 200 short emails (cli-testing performance/mail/types).
310
317
  const count = write(database, () => {
311
- const ids = next.all(queuedAs(corpus), batch).map((row) => Number(row.id));
312
- for (const id of ids)
313
- index(id);
314
- return ids.length;
318
+ const started = performance.now();
319
+ for (let indexed = 0;;) {
320
+ const ids = next.all(queuedAs(corpus), batch).map((row) => Number(row.id));
321
+ for (const id of ids)
322
+ index(id);
323
+ indexed += ids.length;
324
+ if (ids.length < batch || performance.now() - started >= budgetMs)
325
+ return indexed;
326
+ }
315
327
  });
316
328
  if (count === 0)
317
329
  break;
@@ -319,6 +331,17 @@ export const drainCorpus = (database, corpus, stemmerFor, { batch = 200, until =
319
331
  }
320
332
  return done;
321
333
  };
334
+ /** Indexes these queued rows now, inside the caller's write, so they share its commit. */
335
+ export const indexQueued = (database, corpus, stemmerFor, ids) => {
336
+ if (ids.length === 0)
337
+ return 0;
338
+ const index = readyWriter(database, corpus, stemmerFor);
339
+ if (index === undefined)
340
+ return 0;
341
+ for (const id of ids)
342
+ index(id);
343
+ return ids.length;
344
+ };
322
345
  /** Documents, then notes: what a notes search reads; then the trigrams still to fill. */
323
346
  export const drainNoteIndex = (database, stemmerFor, options = {}) => drainCorpus(database, CORPORA.document, stemmerFor, options) +
324
347
  drainCorpus(database, CORPORA.note, stemmerFor, options) +
@@ -13,7 +13,7 @@ import { isoDate, limitOf, oneOf, refuse, reviewedRowsOver, text, } from "./revi
13
13
  import { pageOfRows } from "./rows-page.js";
14
14
  import { write } from "./transaction.js";
15
15
  const ORDERS = "SELECT o.*, b.name AS author_name, b.kind AS author_kind FROM orders o " +
16
- "LEFT JOIN bots b ON o.author_type = 'bot' AND b.id = o.author_id";
16
+ "LEFT JOIN bots b ON o.author_type = 'agent' AND b.id = o.author_id";
17
17
  export const orderOperationsOver = (context) => {
18
18
  const { database, now } = context;
19
19
  const { partyOf, partyThing, reviewedOf, written, keepEvidence, ownerOnly, linkedId, decideRow, mayChangeParts } = reviewedRowsOver(context);
@@ -28,7 +28,7 @@ export const movePaymentFacts = (context) => {
28
28
  return write(database, () => {
29
29
  const rows = database
30
30
  .prepare("SELECT f.*, b.name AS bot_name, b.kind AS bot_kind FROM facts f " +
31
- "LEFT JOIN bots b ON f.author_type = 'bot' AND b.id = f.author_id WHERE f.type = 'payment' ORDER BY f.id")
31
+ "LEFT JOIN bots b ON f.author_type = 'agent' AND b.id = f.author_id WHERE f.type = 'payment' ORDER BY f.id")
32
32
  .all();
33
33
  const nextState = (id) => paymentOf(database
34
34
  .prepare("SELECT metadata FROM facts WHERE supersedes_id = ? AND type = 'payment' ORDER BY id DESC LIMIT 1")
@@ -47,7 +47,7 @@ export const movePaymentFacts = (context) => {
47
47
  const payment = paymentOf(row.metadata);
48
48
  if (!payment)
49
49
  continue;
50
- const by = row.author_type === "bot" && row.bot_name != null
50
+ const by = row.author_type === "agent" && row.bot_name != null
51
51
  ? {
52
52
  bot: String(row.bot_name),
53
53
  kind: row.bot_kind === "rule" ? "rule" : "agent",
@@ -7,7 +7,7 @@ import { iso, isoDate, limitOf, oneOf, refuse, reviewedRowsOver, text, } from ".
7
7
  import { pageOfRows } from "./rows-page.js";
8
8
  import { write } from "./transaction.js";
9
9
  const PRODUCTS = "SELECT c.*, b.name AS author_name, b.kind AS author_kind FROM catalog_items c " +
10
- "LEFT JOIN bots b ON c.author_type = 'bot' AND b.id = c.author_id";
10
+ "LEFT JOIN bots b ON c.author_type = 'agent' AND b.id = c.author_id";
11
11
  export const productOperationsOver = (context) => {
12
12
  const { database, now } = context;
13
13
  const { partyOf, partyThing } = reviewedRowsOver(context);
@@ -6,7 +6,7 @@ const invalid = () => {
6
6
  };
7
7
  const scalar = new Set([
8
8
  "person",
9
- "bot",
9
+ "agent",
10
10
  "organization",
11
11
  "project",
12
12
  "fact",
@@ -23,7 +23,7 @@ const scalar = new Set([
23
23
  "meeting_transcript",
24
24
  "meeting_transcript_row",
25
25
  ]);
26
- const noText = new Set(["person", "bot", "organization", "project", "chat", "identity", "account"]);
26
+ const noText = new Set(["person", "agent", "organization", "project", "chat", "identity", "account"]);
27
27
  const texts = {
28
28
  document: {
29
29
  table: "documents",
@@ -23,14 +23,14 @@ const json = (value) => (value == null ? null : JSON.parse(String(value)));
23
23
  const STATUS = `CASE WHEN p.status = 'approved' AND p.kind IN ('${MEETING_FINDINGS_KIND}', '${EVIDENCE_FINDINGS_KIND}', '${MAIL_FINDINGS_KIND}') ` +
24
24
  "AND json_array_length(p.result, '$.accepted') = 0 THEN 'rejected' ELSE p.status END";
25
25
  const NAMED = `SELECT p.*, ${STATUS} AS shown_status, b.name AS proposer_name, b.kind AS proposer_kind FROM proposed_actions p ` +
26
- "LEFT JOIN bots b ON p.proposed_by_type = 'bot' AND b.id = p.proposed_by_id";
26
+ "LEFT JOIN bots b ON p.proposed_by_type = 'agent' AND b.id = p.proposed_by_id";
27
27
  /** Who proposed an action, for `mayDecide`. */
28
28
  export const proposerOfAction = ({ proposedBy, payload }) => proposedBy.type === "person"
29
29
  ? { type: "person", id: proposedBy.id }
30
30
  : proposedBy.name === null
31
31
  ? { type: "unknown" }
32
32
  : {
33
- type: "bot",
33
+ type: "agent",
34
34
  id: proposedBy.id,
35
35
  name: proposedBy.name,
36
36
  kind: proposedBy.kind ?? "agent",
@@ -58,7 +58,7 @@ export const proposalOperationsOver = (context) => {
58
58
  type: row.proposed_by_type,
59
59
  id: String(row.proposed_by_id),
60
60
  name: row.proposer_name == null ? null : String(row.proposer_name),
61
- kind: row.proposed_by_type !== "bot"
61
+ kind: row.proposed_by_type !== "agent"
62
62
  ? null
63
63
  : row.proposer_kind === "rule" || row.proposer_name === "rule"
64
64
  ? "rule"
@@ -1,7 +1,7 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
2
  export const IMPORTER = { bot: "import" };
3
3
  /** A proposal the import made that the owner has not decided yet: the import may still change it. */
4
- export const importersProposal = (entity) => entity.review === "proposed" && entity.author.type === "bot" && entity.author.name === IMPORTER.bot;
4
+ export const importersProposal = (entity) => entity.review === "proposed" && entity.author.type === "agent" && entity.author.name === IMPORTER.bot;
5
5
  /** The stable word a store refusal carries, for the receipt. */
6
6
  export const codeOf = (error) => {
7
7
  const reason = error.details?.reason;
@@ -196,7 +196,8 @@ const READERS = {
196
196
  deleted: "x.deleted_at",
197
197
  body: bodyOr(body, "x.statement"),
198
198
  })),
199
- bot: byId("bot", "bots", () => ({ title: "x.name" })),
199
+ agent: byId("agent", "bots", () => ({ title: "x.name" })),
200
+ bot: byId("bot", "sender_bots", () => ({ title: "x.name" })),
200
201
  // Money is formatted with its currency's scale in JS, so SQL hands `titleOf` the fields as JSON.
201
202
  invoice: byId("invoice", "invoices", () => ({
202
203
  title: "json_object('id', x.id, 'number', x.number, 'direction', x.direction, 'total', x.total, " +
@@ -157,7 +157,7 @@ export const relationProposalsOver = (context) => {
157
157
  */
158
158
  const rescored = (action, input, scored, by) => {
159
159
  const proposer = proposerOfAction(action);
160
- const own = proposer.type === "bot" && proposer.kind === "rule" && botKey(proposer.name) === botKey(by.bot);
160
+ const own = proposer.type === "agent" && proposer.kind === "rule" && botKey(proposer.name) === botKey(by.bot);
161
161
  const before = action.payload;
162
162
  const payload = own
163
163
  ? {
@@ -85,7 +85,7 @@ export declare const reviewedRowsOver: (context: StoreContext) => {
85
85
  model: string | null;
86
86
  source: string;
87
87
  review: string;
88
- confirmedType: "bot" | "person" | null;
88
+ confirmedType: "agent" | "person" | null;
89
89
  confirmedId: number | null;
90
90
  metadata: string | null;
91
91
  project: number | null;
@@ -97,7 +97,7 @@ export declare const reviewedRowsOver: (context: StoreContext) => {
97
97
  model: string | null;
98
98
  source: string;
99
99
  review: string;
100
- confirmedType: "bot" | "person" | null;
100
+ confirmedType: "agent" | "person" | null;
101
101
  confirmedId: number | null;
102
102
  metadata: string | null;
103
103
  project: number | null;
@@ -97,7 +97,7 @@ export const decisionsOver = (context) => {
97
97
  const mayChangeParts = (row, by, message, reason = "finance.owner-only") => {
98
98
  if (by === "owner")
99
99
  return;
100
- const own = row.author_type === "bot" && row.author_name != null && botKey(String(row.author_name)) === botKey(by.bot);
100
+ const own = row.author_type === "agent" && row.author_name != null && botKey(String(row.author_name)) === botKey(by.bot);
101
101
  if (row.review !== "proposed" || !own)
102
102
  throw new CliError("permission_error", message, { reason });
103
103
  };