@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
@@ -322,7 +322,8 @@ export interface UnreadChats {
322
322
  left?: string[];
323
323
  }>;
324
324
  }
325
- export interface ThreadReplies {
325
+ /** Also the group of `ThreadRefresh`, which a messenger may implement instead of `threadReplies`. */
326
+ export interface ThreadReplies extends Partial<ThreadRefresh> {
326
327
  /**
327
328
  * Replies `history` leaves out, such as Slack's thread replies: those sent after `since` (epoch milliseconds, left
328
329
  * out on the chat's first read) to the roots the adapter picks, oldest first. `messages sync` asks after the chat's
@@ -333,6 +334,35 @@ export interface ThreadReplies {
333
334
  since?: number;
334
335
  }): Promise<Message[] | AsyncIterable<Message[]>> | AsyncIterable<Message[]>;
335
336
  }
337
+ /**
338
+ * A message that has replies. `lastReplyAt`: when its newest reply was sent, by the messenger's clock (ISO 8601).
339
+ * Without it, a later sync reads the thread again only when it shows up on an older history page.
340
+ * @experimental
341
+ */
342
+ export interface ThreadRoot {
343
+ id: Id;
344
+ lastReplyAt?: string;
345
+ }
346
+ /**
347
+ * Thread replies `history` leaves out, read one thread at a time, for a messenger that says which messages have them.
348
+ * `messages sync` picks the threads: on a chat's first read every root it saw, after that a root from an older history
349
+ * page whole, and any other root only when its newest reply came after the last read. An adapter has all three
350
+ * methods or none. A messenger with both this and `ThreadReplies` is read through this one.
351
+ * @experimental
352
+ */
353
+ export interface ThreadRefresh {
354
+ /** The roots among one page `history` answered, from the page alone: it is not paced, so it asks nothing. */
355
+ threadRootsIn(chatId: Id, messages: readonly Message[]): Promise<ThreadRoot[]>;
356
+ /**
357
+ * The roots a messenger lists cheaply that may have new replies, however old the root: Slack's are those sent in the
358
+ * last `thread_window_days`. The sync compares each `lastReplyAt` with the last read itself.
359
+ */
360
+ recentThreadRoots(chatId: Id): Promise<ThreadRoot[]>;
361
+ /** One thread's replies sent after `after` (epoch milliseconds), or all of them, oldest first, without the root. */
362
+ rootReplies(chatId: Id, rootId: Id, window: {
363
+ after?: number;
364
+ }): Promise<Message[] | AsyncIterable<Message[]>> | AsyncIterable<Message[]>;
365
+ }
336
366
  /** @experimental */
337
367
  export interface MessageButtons {
338
368
  /** The keyboard one message carries, row by row; a message without one answers `[]`. */
@@ -123,15 +123,24 @@ export const archiveService = (deps) => {
123
123
  return { chat: limit.chatId ?? null, fetched: 0, complete: false, ranges: [], limited: "group_too_large" };
124
124
  }
125
125
  const windowed = limit?.keepFrom !== undefined && !(limit.keepFrom <= (options.sinceMs ?? Number.NEGATIVE_INFINITY));
126
+ const roots = new Map();
127
+ const startedAt = Date.now();
126
128
  const fetched = await fetchInto({
127
- history: (window) => history(chat, { ...window, reactions: false }),
129
+ history: async (window) => {
130
+ const page = await history(chat, { ...window, reactions: false });
131
+ if (refreshes(connection) && !options.window && page.items[0])
132
+ pagedRoots(roots, await connection.threadRootsIn(page.items[0].chatId, page.items), window.before);
133
+ return page;
134
+ },
128
135
  store,
129
136
  account,
130
137
  fetching: deps.messenger.fetching ?? FETCHING,
131
138
  ...options,
132
139
  ...(windowed ? { sinceMs: limit.keepFrom } : {}),
133
140
  });
134
- const replies = fetched.chat && !options.window ? await savedReplies(connection, store, account, fetched.chat, options.stop) : 0;
141
+ const replies = fetched.chat && !options.window
142
+ ? await savedReplies(connection, store, account, fetched.chat, { roots, startedAt }, options.stop)
143
+ : 0;
135
144
  const read = replies > 0 ? { ...fetched, fetched: fetched.fetched + replies } : fetched;
136
145
  const result = windowed && read.reachedSince ? { ...read, limited: "older_than_window" } : read;
137
146
  if (result.limited && limit?.keepFrom !== undefined)
@@ -169,7 +178,7 @@ export const archiveService = (deps) => {
169
178
  const upToDate = heldToNewest(await deps.store(), await deps.account(), deps.messenger.fetching ?? FETCHING, {
170
179
  ...options,
171
180
  catchUp: catchingUp ? (options.catchUp ?? {}) : false,
172
- threads: connection.threadReplies !== undefined,
181
+ threads: connection.threadReplies !== undefined || refreshes(connection),
173
182
  });
174
183
  const finished = () => options.onChat?.({ chats: chats.length, done: answer.items.length, fetched: answer.fetched });
175
184
  finished();
@@ -428,18 +437,32 @@ const heldToNewest = (store, account, fetching, options) => async (chat) => {
428
437
  return !Number.isNaN(startedAt) && startedAt < options.sinceMs;
429
438
  };
430
439
  const threadsKey = (chatId) => `threads:${chatId}`;
440
+ const refreshes = (connection) => connection.threadRootsIn !== undefined &&
441
+ connection.recentThreadRoots !== undefined &&
442
+ connection.rootReplies !== undefined;
443
+ const pagedRoots = (into, roots, before) => {
444
+ for (const root of roots)
445
+ into.set(root.id, { ...root, whole: before !== undefined || into.get(root.id)?.whole === true });
446
+ };
447
+ /** `since` is this machine's clock, a reply's time the messenger's: the overlap keeps one sent while they differ. */
448
+ const THREAD_CLOCK_SKEW_MS = 60_000;
431
449
  /**
432
450
  * The replies a messenger's history pages leave out, saved without a held stretch: they say nothing of the history
433
- * around them. `since` is when the last read of them started.
451
+ * around them. `since` is when the last read of them started: before its history pages, so a reply sent while they
452
+ * were read is asked for again.
434
453
  */
435
- const savedReplies = async (connection, store, account, chatId, stop) => {
436
- if (!connection.threadReplies || stop.aborted)
454
+ const savedReplies = async (connection, store, account, chatId, { roots, startedAt }, stop) => {
455
+ if (stop.aborted)
456
+ return 0;
457
+ const stored = Number((await store.sync.syncState(account, threadsKey(chatId)))?.value);
458
+ const point = Number.isFinite(stored) ? stored : undefined;
459
+ const batches = refreshes(connection)
460
+ ? refreshedThreads(connection, chatId, roots, point, stop)
461
+ : connection.threadReplies
462
+ ? await readyBatches(connection.threadReplies(chatId, point === undefined ? {} : { since: point }))
463
+ : undefined;
464
+ if (!batches)
437
465
  return 0;
438
- const startedAt = Date.now();
439
- const point = Number((await store.sync.syncState(account, threadsKey(chatId)))?.value);
440
- // Awaited first: the flood wrapper turns every adapter method async, so batches arrive inside a promise.
441
- const answer = await connection.threadReplies(chatId, Number.isFinite(point) ? { since: point } : {});
442
- const batches = Symbol.asyncIterator in answer ? answer : [answer];
443
466
  let saved = 0;
444
467
  for await (const replies of batches) {
445
468
  if (replies.length > 0)
@@ -452,6 +475,33 @@ const savedReplies = async (connection, store, account, chatId, stop) => {
452
475
  await store.sync.setSyncState(account, threadsKey(chatId), String(startedAt));
453
476
  return saved;
454
477
  };
478
+ // Awaited first: the flood wrapper turns every adapter method async, so batches arrive inside a promise.
479
+ const readyBatches = async (answer) => {
480
+ const ready = await answer;
481
+ return Symbol.asyncIterator in ready ? ready : [ready];
482
+ };
483
+ /** One thread at a time, so each is saved as it comes: the roots the pages showed, then the messenger's recent ones. */
484
+ async function* refreshedThreads(connection, chatId, roots, point, stop) {
485
+ const after = point === undefined ? undefined : point - THREAD_CLOCK_SKEW_MS;
486
+ const all = new Map(roots);
487
+ for (const root of await connection.recentThreadRoots(chatId)) {
488
+ const paged = all.get(root.id);
489
+ all.set(root.id, {
490
+ ...root,
491
+ lastReplyAt: newest(paged?.lastReplyAt, root.lastReplyAt),
492
+ whole: paged?.whole ?? false,
493
+ });
494
+ }
495
+ for (const root of all.values()) {
496
+ if (stop.aborted)
497
+ return;
498
+ const replied = Date.parse(root.lastReplyAt ?? "");
499
+ if (after !== undefined && !root.whole && !(replied > after))
500
+ continue;
501
+ yield* await readyBatches(connection.rootReplies(chatId, root.id, after === undefined || root.whole ? {} : { after }));
502
+ }
503
+ }
504
+ const newest = (one, other) => one === undefined || (other !== undefined && Date.parse(other) > Date.parse(one)) ? other : one;
455
505
  /** When the message a held stretch starts at was sent: by time the key is the time; by id, the stored message says. */
456
506
  const timeOfKey = async (store, account, chatId, key, byTime, fallback) => {
457
507
  if (byTime)
@@ -1,12 +1,12 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { constants, mkdirSync } from "node:fs";
3
- import { lstat, open, readFile, stat } from "node:fs/promises";
3
+ import { lstat, open, stat } from "node:fs/promises";
4
4
  import { CliError } from "@wirecat/cli-base";
5
5
  import { queryFieldsOf, timezoneOf, walkQuery } from "@wirecat/cli-base/query";
6
6
  import { directoryPaths } from "../attachments/directory.js";
7
7
  import { documentExtractor, documentKind } from "../attachments/documents.js";
8
8
  import { classify, engineMissing, extractText, importEngine, MAX_TEXT_CHARS, } from "../attachments/extract.js";
9
- import { attachmentMaxBytes } from "../attachments/limits.js";
9
+ import { asBytes, attachmentMaxBytes, readWhole, sizeText } from "../attachments/limits.js";
10
10
  import { ocrImage, ocrPdf } from "../attachments/ocr.js";
11
11
  import { pdfPreview } from "../attachments/pdf-preview.js";
12
12
  import { pictureExtractor, pictureReaderOf, readPictureReading, readPictureWithAgent, } from "../attachments/picture-reading.js";
@@ -47,7 +47,7 @@ const outcome = async (file, path, load, signal, noFollow = false, ocr, env = pr
47
47
  status: "too-large",
48
48
  issue: withRecovery({
49
49
  code: "validation_error",
50
- message: `attachment exceeds ${maxBytes / 1024 / 1024} MiB; configure MESSAGING_ATTACHMENT_MAX_MIB`,
50
+ message: `attachment exceeds ${sizeText(maxBytes)}; configure MESSAGING_ATTACHMENT_MAX_MIB`,
51
51
  setting: "MESSAGING_ATTACHMENT_MAX_MIB",
52
52
  }),
53
53
  });
@@ -68,7 +68,7 @@ const outcome = async (file, path, load, signal, noFollow = false, ocr, env = pr
68
68
  return { status: "missing" };
69
69
  if (opened.size > maxBytes)
70
70
  return tooLarge();
71
- bytes = new Uint8Array(await readFile(handle, { signal }));
71
+ bytes = asBytes(await readWhole(handle, signal));
72
72
  }
73
73
  finally {
74
74
  await handle.close();
@@ -1,6 +1,6 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
2
  import { engineHint, extractText, importEngine, MAX_TEXT_CHARS } from "../../attachments/extract.js";
3
- import { attachmentMaxBytes } from "../../attachments/limits.js";
3
+ import { attachmentMaxBytes, sizeText } from "../../attachments/limits.js";
4
4
  const READABLE = new Set([
5
5
  "application/pdf",
6
6
  "application/msword",
@@ -46,6 +46,6 @@ export const fileText = async (bytes, file, command, env = process.env) => {
46
46
  ? "file could not be read as text; it may be damaged or protected"
47
47
  : read.status === "unsupported"
48
48
  ? "file contents do not match its type"
49
- : `file is too large for the document readers (over ${Math.round(attachmentMaxBytes(env) / 1024 / 1024)} MB, or over ${MAX_TEXT_CHARS} characters of text)`;
49
+ : `file is too large for the document readers (over ${sizeText(attachmentMaxBytes(env))}, or over ${MAX_TEXT_CHARS} characters of text)`;
50
50
  throw new CliError("validation_error", reason);
51
51
  };
@@ -14,12 +14,12 @@ export declare const metadataService: (deps: ServiceDeps) => {
14
14
  dryRun?: boolean;
15
15
  }) => Promise<{
16
16
  items: ({
17
+ error?: undefined;
17
18
  chatId: string;
18
19
  tags: import("../domain/channel-tags.js").ChannelTagMatch[];
19
20
  algorithm: string;
20
21
  fetchedAt: string | null;
21
22
  source: string;
22
- error?: undefined;
23
23
  } | {
24
24
  tags?: undefined;
25
25
  algorithm?: undefined;
@@ -4,7 +4,7 @@ import type { Proposer } from "../../../store/decisions.js";
4
4
  import type { Decision, ProposalFilter, ProposalKind, ProposalRow } from "../types.js";
5
5
  /** A stored author as a proposer, with the kind read from its bot row. */
6
6
  export declare const proposerOfAuthor: (author: {
7
- type: "person" | "bot";
7
+ type: "person" | "agent";
8
8
  id: string;
9
9
  name: string | null;
10
10
  kind: "agent" | "rule" | null;
@@ -4,13 +4,13 @@ export const proposerOfAuthor = (author) => {
4
4
  return { type: "person", id: author.id };
5
5
  if (author.name === null)
6
6
  return { type: "unknown" };
7
- return { type: "bot", id: author.id, name: author.name, kind: author.kind ?? "agent" };
7
+ return { type: "agent", id: author.id, name: author.name, kind: author.kind ?? "agent" };
8
8
  };
9
9
  const byMatches = (row, by) => {
10
10
  if (by === undefined)
11
11
  return true;
12
12
  const proposer = row.proposedBy;
13
- if (proposer.type !== "bot")
13
+ if (proposer.type !== "agent")
14
14
  return false;
15
15
  if (by === "agent" || by === "rule")
16
16
  return proposer.kind === by;
@@ -14,7 +14,7 @@ const rowOf = (task) => {
14
14
  subject: task.ref,
15
15
  object: null,
16
16
  summary: `close as ${suggestion.as}: ${task.title}`,
17
- proposedBy: { type: "bot", id: suggestion.by, name: suggestion.by, kind: "agent" },
17
+ proposedBy: { type: "agent", id: suggestion.by, name: suggestion.by, kind: "agent" },
18
18
  reason: suggestion.reason,
19
19
  evidence: task.source === null ? [] : [task.source],
20
20
  score: suggestion.certainty,
@@ -4,6 +4,7 @@
4
4
  */
5
5
  export { MAIL_TYPES, type MailType } from "../mail/mail-types.js";
6
6
  export { type AddedSource, type AddedSourceContent, type AddedSourceInput, addedSourceKeyOf, } from "./sqlite/added-sources.js";
7
+ export { BOT_SENDS, type BotSends } from "./sqlite/bot-sends.js";
7
8
  export type { ContractFilter } from "./sqlite/business-contracts.js";
8
9
  export type { CatalogEntry, CatalogInput, CatalogQuery } from "./sqlite/catalog.js";
9
10
  export type { CrmChange, CrmChangeKind } from "./sqlite/crm-changes.js";
@@ -17,6 +18,7 @@ export type { Invoice, Payment as FinancePayment } from "./sqlite/finance.js";
17
18
  export type { IdentityRekey } from "./sqlite/identity-rekey.js";
18
19
  export { IMPORTED_DOCUMENT_QUERY } from "./sqlite/imported-documents.js";
19
20
  export { type KnowledgeRelation, type KnowledgeTarget, ORGANIZATION_KINDS, type Organization, PROJECT_TYPES, type Project, SCOPES, } from "./sqlite/knowledge.js";
21
+ export type { MailSubscription, MailSubscriptionFilter, MailSubscriptionList, UnsubscribeTarget, } from "./sqlite/mail-subscriptions.js";
20
22
  export type { MeetingVectors } from "./sqlite/meeting-vectors.js";
21
23
  export type { Author, Memory } from "./sqlite/memories.js";
22
24
  export type { TransactionFilter } from "./sqlite/money-transactions.js";
@@ -4,6 +4,7 @@
4
4
  */
5
5
  export { MAIL_TYPES } from "../mail/mail-types.js";
6
6
  export { addedSourceKeyOf, } from "./sqlite/added-sources.js";
7
+ export { BOT_SENDS } from "./sqlite/bot-sends.js";
7
8
  export { crmIdentityId } from "./sqlite/crm-rows.js";
8
9
  export { crmSettingKey } from "./sqlite/crm-settings.js";
9
10
  export { QUOTE_LIMIT, quoteKept } from "./sqlite/evidence-signature.js";
@@ -9,7 +9,7 @@ export type Proposer = {
9
9
  type: "person";
10
10
  id: string;
11
11
  } | {
12
- type: "bot";
12
+ type: "agent";
13
13
  id: string;
14
14
  name: string;
15
15
  kind: "agent" | "rule";
@@ -44,11 +44,11 @@ row, by, policy = DEFAULT_DECISION_POLICY) => {
44
44
  const proposer = row.proposedBy;
45
45
  if (proposer.type === "unknown")
46
46
  return refuse("permission_error", "proposal.owner-only", "this proposal names no author; only the owner decides it");
47
- if (proposer.type === "bot" && proposer.verified === false)
47
+ if (proposer.type === "agent" && proposer.verified === false)
48
48
  return refuse("permission_error", "proposal.owner-only", `${proposer.name} is named only by an old link's provenance; only the owner decides it`);
49
- if (proposer.type === "bot" && proposer.kind === "rule" && policy.ruleProposalsOwnerOnly)
49
+ if (proposer.type === "agent" && proposer.kind === "rule" && policy.ruleProposalsOwnerOnly)
50
50
  return refuse("permission_error", "proposal.owner-only", `proposed by ${proposer.name}: only the owner decides it`);
51
- if (proposer.type === "bot" && proposer.kind === "agent" && botKey(proposer.name) === botKey(by.bot))
51
+ if (proposer.type === "agent" && proposer.kind === "agent" && botKey(proposer.name) === botKey(by.bot))
52
52
  return refuse("permission_error", "proposal.own", `${by.bot} proposed this; another decider must decide it`);
53
53
  return null;
54
54
  };
@@ -66,7 +66,7 @@ export const assertMayWithdraw = (row, by) => {
66
66
  return;
67
67
  const proposer = row.proposedBy;
68
68
  if (row.proposed &&
69
- proposer.type === "bot" &&
69
+ proposer.type === "agent" &&
70
70
  proposer.kind === "agent" &&
71
71
  proposer.verified !== false &&
72
72
  botKey(proposer.name) === botKey(by.bot))
@@ -32,13 +32,13 @@ export interface EvidenceFindingsBatch {
32
32
  /** Only the owner decides it, whatever `agent_decisions` says: it was staged so, or it records a payment. */
33
33
  ownerOnly: boolean;
34
34
  author: {
35
- type: "person" | "bot";
35
+ type: "person" | "agent";
36
36
  id: string;
37
37
  name: string | null;
38
38
  kind: "agent" | "rule" | null;
39
39
  };
40
40
  decidedBy: {
41
- type: "person" | "bot";
41
+ type: "person" | "agent";
42
42
  id: string;
43
43
  } | null;
44
44
  decidedAt: string | null;
@@ -1,7 +1,7 @@
1
1
  export type { ContextEvidenceItem, ContextEvidencePage, ContextEvidenceReader, ContextEvidenceRequest, ContextEvidenceSender, ContextSource, } from "../context/evidence.js";
2
2
  export { BUSINESS_KINDS, type BusinessKind } from "../domain/business.js";
3
3
  export { FACT_STATUSES, FACT_TYPES, MEMORY_KINDS, MEMORY_SCOPES, MEMORY_STATUSES, TASK_TYPES, WORK_TASK_TYPES, } from "../domain/knowledge.js";
4
- export { type KindSignal, PERSON_KINDS, type PersonKind, SENDER_BOT_PREFIX } from "../domain/person-kinds.js";
4
+ export { type KindSignal, OLD_SENDER_BOT_PREFIX, PERSON_KINDS, type PersonKind, SENDER_BOT_PREFIX, senderBotRef, } from "../domain/person-kinds.js";
5
5
  export type { RefState, RefSummary, RefSummaryKind, RefsStore } from "../domain/ref-summaries.js";
6
6
  export type { TagConsolidationApplyOptions, TagConsolidationOptions, TagConsolidationPreview, TagConsolidationReceipt, TagConsolidationStore, } from "../domain/tag-consolidation.js";
7
7
  export type { TagRedirectIndex, TagRedirectResolution, TagRedirectSnapshot } from "../domain/tag-redirects.js";
@@ -43,6 +43,7 @@ export { resetAttachmentWords } from "./sqlite/attachment-texts.js";
43
43
  export { backfillNormalized, pendingNormalization } from "./sqlite/backfill.js";
44
44
  export type { BaseColumn, BaseScope, BaseSet, BaseStagesStore, MappingFilter, StageMapping, StageName, } from "./sqlite/base-stages.js";
45
45
  export { baseSettingKey } from "./sqlite/base-suggest.js";
46
+ export { BOT_SENDS, type BotSends } from "./sqlite/bot-sends.js";
46
47
  export type { BotUpdate, BotUpdateStore } from "./sqlite/bot-updates.js";
47
48
  export type { Contract, ContractFields, ContractFilter, ContractInput, ContractsStore, ContractUpdate, } from "./sqlite/business-contracts.js";
48
49
  export type { BusinessHit, BusinessSearch, BusinessSearchStore, BusinessSource } from "./sqlite/business-search.js";
@@ -72,6 +73,7 @@ export type { Involvement, InvolvementStore } from "./sqlite/involvements.js";
72
73
  export type { Annotation, KnowledgeRelation, KnowledgeStore, KnowledgeTarget, LabelledType, Organization, Project, Reminder, } from "./sqlite/knowledge.js";
73
74
  export { ORGANIZATION_KINDS, PROJECT_TYPES, SCOPES } from "./sqlite/knowledge.js";
74
75
  export type { MailRule, MailRuleCount, MailRuleInput, MailRulesStore } from "./sqlite/mail-rules.js";
76
+ export type { MailSubscription, MailSubscriptionFilter, MailSubscriptionList, UnsubscribeTarget, } from "./sqlite/mail-subscriptions.js";
75
77
  export { type ListedAccount, MEETING_ROW_KINDS, type MeetingListFilter, type MeetingListing, type MeetingRow, type MeetingRowDocument, type MeetingRowKind, type MeetingRowParticipant, type MeetingRowSource, } from "./sqlite/meeting-listing.js";
76
78
  export type { MeetingProjectLink, MeetingProjectsStore } from "./sqlite/meeting-projects.js";
77
79
  export type { MeetingContextReadCapabilities, MeetingReadCapabilities, MeetingReadScope, TranscriptContextInput, TranscriptContextPage, TranscriptPage, TranscriptReadScope, TranscriptRowPage, } from "./sqlite/meeting-reads.js";
@@ -1,6 +1,6 @@
1
1
  export { BUSINESS_KINDS } from "../domain/business.js";
2
2
  export { FACT_STATUSES, FACT_TYPES, MEMORY_KINDS, MEMORY_SCOPES, MEMORY_STATUSES, TASK_TYPES, WORK_TASK_TYPES, } from "../domain/knowledge.js";
3
- export { PERSON_KINDS, SENDER_BOT_PREFIX } from "../domain/person-kinds.js";
3
+ export { OLD_SENDER_BOT_PREFIX, PERSON_KINDS, SENDER_BOT_PREFIX, senderBotRef, } from "../domain/person-kinds.js";
4
4
  export { createTagRedirectIndex } from "../domain/tag-redirects.js";
5
5
  export { note } from "../entities/note.js";
6
6
  export { PAYMENT_DIRECTIONS, PAYMENT_STATES, paymentTitle, validatePayment } from "../meetings/index.js";
@@ -31,6 +31,7 @@ export { ADDED_KINDS, addedSourceKeyOf, } from "./sqlite/added-sources.js";
31
31
  export { resetAttachmentWords } from "./sqlite/attachment-texts.js";
32
32
  export { backfillNormalized, pendingNormalization } from "./sqlite/backfill.js";
33
33
  export { baseSettingKey } from "./sqlite/base-suggest.js";
34
+ export { BOT_SENDS } from "./sqlite/bot-sends.js";
34
35
  export { BUSINESS_FIND_MAX } from "./sqlite/business-search.js";
35
36
  export { CATALOG_QUERY } from "./sqlite/catalog.js";
36
37
  export { crmIdentityId, } from "./sqlite/crm.js";
@@ -12,13 +12,13 @@ export interface MailFindingsBatch {
12
12
  fingerprint: string;
13
13
  status: "proposed" | "reviewed";
14
14
  author: {
15
- type: "person" | "bot";
15
+ type: "person" | "agent";
16
16
  id: string;
17
17
  name: string | null;
18
18
  kind: "agent" | "rule" | null;
19
19
  };
20
20
  decidedBy: {
21
- type: "person" | "bot";
21
+ type: "person" | "agent";
22
22
  id: string;
23
23
  } | null;
24
24
  decidedAt: string | null;
@@ -9,12 +9,12 @@ export interface MeetingFindingsBatch {
9
9
  fingerprint: string;
10
10
  status: "proposed" | "reviewed";
11
11
  author: {
12
- type: "person" | "bot";
12
+ type: "person" | "agent";
13
13
  id: string;
14
14
  name: string | null;
15
15
  };
16
16
  decidedBy: {
17
- type: "person" | "bot";
17
+ type: "person" | "agent";
18
18
  id: string;
19
19
  } | null;
20
20
  decidedAt: string | null;
@@ -210,15 +210,15 @@ export interface PeopleStore extends AccountPeople {
210
210
  /** Why each `person:<uid>` is shown by default, as `list` gives it; an empty list for one with no tie. */
211
211
  ties(people: readonly string[]): Promise<Record<string, ShownBecause[]>>;
212
212
  /**
213
- * The sender bots: programs that write to the owner, apart from people (`sender-bot:<id>`), by name. `query` looks in
213
+ * The sender bots: programs that write to the owner, apart from people (`bot:<id>`), by name. `query` looks in
214
214
  * their names, addresses and usernames; `organization` (`organization:<id>`) keeps the ones that send for it.
215
215
  * @experimental
216
216
  */
217
217
  listBots(options: BotListOptions): Promise<BotList>;
218
- /** One sender bot (`sender-bot:<id>`), its identities and every move to or from it. @experimental */
218
+ /** One sender bot (`bot:<id>`), its identities and every move to or from it. @experimental */
219
219
  showBot(bot: string): Promise<SenderBotDetails>;
220
220
  /**
221
- * The owner says a sender is a program: a person (`person:<uid>`), a bot (`sender-bot:<id>`) or one identity moves
221
+ * The owner says a sender is a program: a person (`person:<uid>`), a bot (`bot:<id>`) or one identity moves
222
222
  * to a sender bot for its whole history, and no rule gives it back. Its messages keep pointing at the identity. `bot`
223
223
  * joins a stored bot; else a bot already holding it keeps it, or a new one takes it. A person every identity left is
224
224
  * hidden from lists, and a move back gives their uid back. The owner's alone; refused for the owner's own person.
@@ -230,7 +230,7 @@ export interface PeopleStore extends AccountPeople {
230
230
  reason?: string;
231
231
  }): Promise<SenderBot>;
232
232
  /**
233
- * The owner says a sender is a person: a bot (`sender-bot:<id>`) or one identity of it moves to a person for its
233
+ * The owner says a sender is a person: a bot (`bot:<id>`) or one identity of it moves to a person for its
234
234
  * whole history, and no rule makes it a bot again. `person` takes it; else each identity goes back to the person it
235
235
  * came from, or a person of its own. Said of a person, it keeps them one. The owner's alone. @experimental
236
236
  */
@@ -2,6 +2,7 @@ import { CliError } from "@wirecat/cli-base";
2
2
  import { keysOver } from "./keys.js";
3
3
  import { ownerPerson } from "./sqlite/actors.js";
4
4
  import { agentLink, agentMergeOf, agentMerges, linkEvidenceOver } from "./sqlite/agent-links.js";
5
+ import { sendsWhere } from "./sqlite/bot-sends.js";
5
6
  import * as identities from "./sqlite/identities.js";
6
7
  import * as identityProposals from "./sqlite/identity-proposals.js";
7
8
  import { rekeyIdentities } from "./sqlite/identity-rekey.js";
@@ -169,7 +170,7 @@ export const peopleStoreOver = (context, keyed) => {
169
170
  },
170
171
  listBots: async (options) => {
171
172
  storeKinds(database);
172
- return listBots(database, options);
173
+ return listBots(database, options, options.sends === undefined ? undefined : sendsWhere(database, options.sends));
173
174
  },
174
175
  showBot: async (bot) => showBot(database, bot),
175
176
  moveToBot: async (subject, by, options) => {
@@ -32,9 +32,9 @@ export const validateProjectAnnotationsGraph = (manifest, additionalActors = [])
32
32
  if (owned.has(fact.ref))
33
33
  invalid("facts.duplicate");
34
34
  owned.add(fact.ref);
35
- kind(fact.author, ["person", "bot"]);
35
+ kind(fact.author, ["person", "agent"]);
36
36
  if (fact.confirmed_by !== null)
37
- kind(fact.confirmed_by, ["person", "bot"]);
37
+ kind(fact.confirmed_by, ["person", "agent"]);
38
38
  if (fact.updated_at < fact.created_at)
39
39
  invalid("facts.updated_at");
40
40
  if (fact.type !== "decision" && (fact.supersedes !== null || ["superseded", "reversed"].includes(fact.status)))
@@ -61,7 +61,7 @@ export const validateProjectAnnotationsGraph = (manifest, additionalActors = [])
61
61
  kind(manifest.project.organization, ["organization"]);
62
62
  dependency(manifest.project.organization);
63
63
  for (const actor of additionalActors) {
64
- kind(actor, ["person", "bot"]);
64
+ kind(actor, ["person", "agent"]);
65
65
  dependency(actor);
66
66
  }
67
67
  const aliases = new Set([manifest.project.name, manifest.project.key].map(normalizeVocabularyName));
@@ -1,7 +1,7 @@
1
1
  export type { ContextEvidenceItem, ContextEvidencePage, ContextEvidenceReader, ContextEvidenceRequest, ContextEvidenceSender, ContextSource, } from "../context/evidence.js";
2
2
  export { BUSINESS_KINDS, type BusinessKind } from "../domain/business.js";
3
3
  export { FACT_STATUSES, FACT_TYPES, MEMORY_KINDS, MEMORY_SCOPES, MEMORY_STATUSES, TASK_TYPES, WORK_TASK_TYPES, } from "../domain/knowledge.js";
4
- export { type KindSignal, PERSON_KINDS, type PersonKind, SENDER_BOT_PREFIX } from "../domain/person-kinds.js";
4
+ export { type KindSignal, OLD_SENDER_BOT_PREFIX, PERSON_KINDS, type PersonKind, SENDER_BOT_PREFIX, senderBotRef, } from "../domain/person-kinds.js";
5
5
  export type { RefState, RefSummary, RefSummaryKind, RefsStore } from "../domain/ref-summaries.js";
6
6
  export type { TagConsolidationApplyOptions, TagConsolidationOptions, TagConsolidationPreview, TagConsolidationReceipt, TagConsolidationStore, } from "../domain/tag-consolidation.js";
7
7
  export type { TagRedirectIndex, TagRedirectResolution, TagRedirectSnapshot } from "../domain/tag-redirects.js";
@@ -1,6 +1,6 @@
1
1
  export { BUSINESS_KINDS } from "../domain/business.js";
2
2
  export { FACT_STATUSES, FACT_TYPES, MEMORY_KINDS, MEMORY_SCOPES, MEMORY_STATUSES, TASK_TYPES, WORK_TASK_TYPES, } from "../domain/knowledge.js";
3
- export { PERSON_KINDS, SENDER_BOT_PREFIX } from "../domain/person-kinds.js";
3
+ export { OLD_SENDER_BOT_PREFIX, PERSON_KINDS, SENDER_BOT_PREFIX, senderBotRef, } from "../domain/person-kinds.js";
4
4
  export { createTagRedirectIndex } from "../domain/tag-redirects.js";
5
5
  export { note } from "../entities/note.js";
6
6
  export { PAYMENT_DIRECTIONS, PAYMENT_STATES, paymentTitle, validatePayment } from "../meetings/index.js";
@@ -2,7 +2,7 @@ import type { Proposer } from "../decisions.js";
2
2
  import type { CacheDatabase } from "../driver.js";
3
3
  /** Who made or owns something: the store's polymorphic actor pair. */
4
4
  export interface Actor {
5
- type: "person" | "bot";
5
+ type: "person" | "agent";
6
6
  id: number;
7
7
  }
8
8
  /** How the task package names who acted; each maps to one stable actor row. */
@@ -16,11 +16,11 @@ export const botNamed = (database, name, now, kind = "agent") => {
16
16
  throw new CliError("validation_error", `a bot's kind is one of ${BOT_KINDS.join(", ")}`);
17
17
  const found = database.prepare("SELECT id FROM bots WHERE name = ?").get(handle);
18
18
  if (found)
19
- return { type: "bot", id: Number(found.id) };
19
+ return { type: "agent", id: Number(found.id) };
20
20
  const made = database
21
21
  .prepare("INSERT INTO bots (name, kind, created_at, updated_at) VALUES (?, ?, ?, ?) RETURNING id")
22
22
  .get(handle, kind, now, now);
23
- return { type: "bot", id: Number(made?.id) };
23
+ return { type: "agent", id: Number(made?.id) };
24
24
  };
25
25
  /**
26
26
  * The task package's origins as actors: the owner is the owner's person, a rule and an unnamed agent are
@@ -32,7 +32,7 @@ export const actorOfOrigin = (database, origin) => {
32
32
  const found = database.prepare("SELECT id FROM bots WHERE name = ?").get(origin);
33
33
  if (!found)
34
34
  throw new CliError("configuration_error", `the store has no bot ${origin}`);
35
- return { type: "bot", id: Number(found.id) };
35
+ return { type: "agent", id: Number(found.id) };
36
36
  };
37
37
  export const originOfActor = (database, type, id) => {
38
38
  if (type == null || id == null)
@@ -45,19 +45,19 @@ export const originOfActor = (database, type, id) => {
45
45
  export const proposerOf = (database, type, id) => {
46
46
  if (type === "person" && id != null)
47
47
  return { type: "person", id: String(id) };
48
- if (type !== "bot" || id == null)
48
+ if (type !== "agent" || id == null)
49
49
  return { type: "unknown" };
50
50
  const bot = database.prepare("SELECT name, kind FROM bots WHERE id = ?").get(Number(id));
51
51
  if (!bot)
52
52
  return { type: "unknown" };
53
53
  const name = String(bot.name);
54
- return { type: "bot", id: String(id), name, kind: bot.kind === "rule" || name === "rule" ? "rule" : "agent" };
54
+ return { type: "agent", id: String(id), name, kind: bot.kind === "rule" || name === "rule" ? "rule" : "agent" };
55
55
  };
56
56
  /** The SQL that keeps rows whose actor pair matches `by`; the seeded bot `rule` counts as a rule. */
57
57
  export const proposedBySql = (type, id, by) => {
58
58
  if (by === undefined)
59
59
  return { sql: "1", params: [] };
60
- const bot = (condition) => `${type} = 'bot' AND EXISTS (SELECT 1 FROM bots pb WHERE pb.id = ${id} AND ${condition})`;
60
+ const bot = (condition) => `${type} = 'agent' AND EXISTS (SELECT 1 FROM bots pb WHERE pb.id = ${id} AND ${condition})`;
61
61
  if (by === "rule")
62
62
  return { sql: bot("(pb.kind = 'rule' OR pb.name = 'rule')"), params: [] };
63
63
  if (by === "agent")
@@ -5,7 +5,7 @@ import { thingOf } from "./things.js";
5
5
  export const ACTION_TIERS = ["read", "draft", "write-private", "write-public", "destructive", "admin"];
6
6
  export const ACTION_OUTCOMES = ["ok", "refused", "failed"];
7
7
  const CODE = /^[a-z][a-z0-9_]{0,63}$/;
8
- const NAMED = "SELECT a.*, b.name AS actor_name FROM agent_actions a LEFT JOIN bots b ON a.actor_type = 'bot' AND b.id = a.actor_id";
8
+ const NAMED = "SELECT a.*, b.name AS actor_name FROM agent_actions a LEFT JOIN bots b ON a.actor_type = 'agent' AND b.id = a.actor_id";
9
9
  export const agentActionsStoreOver = (context, afterRecord = () => { }) => {
10
10
  const { database, now } = context;
11
11
  const actionOf = (row) => ({
@@ -38,7 +38,7 @@ export const agentActionsStoreOver = (context, afterRecord = () => { }) => {
38
38
  .prepare("INSERT INTO agent_actions (actor_type, actor_id, tool, tier, target_type, target_id, status, error, started_at, finished_at, created_at) " +
39
39
  "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING id")
40
40
  .get(actor.type, actor.id, input.tool, input.tier, target?.type ?? null, target?.id ?? null, input.status, error, input.startedAt, input.finishedAt, now());
41
- database.prepare("UPDATE bots SET last_seen_at = ? WHERE ? = 'bot' AND id = ?").run(now(), actor.type, actor.id);
41
+ database.prepare("UPDATE bots SET last_seen_at = ? WHERE ? = 'agent' AND id = ?").run(now(), actor.type, actor.id);
42
42
  afterRecord();
43
43
  return actionOf(database.prepare(`${NAMED} WHERE a.id = ?`).get(Number(row?.id)));
44
44
  },
@@ -159,7 +159,7 @@ export const agentMergeOf = (context, merge) => {
159
159
  const proposer = proposerOfAction(action);
160
160
  return {
161
161
  proposal: action.id,
162
- bot: proposer.type === "bot" ? proposer.name : "unknown",
162
+ bot: proposer.type === "agent" ? proposer.name : "unknown",
163
163
  run: payload.run ?? null,
164
164
  reason: action.reason,
165
165
  evidence: payload.strength ?? null,
@@ -0,0 +1,19 @@
1
+ import type { CacheDatabase, SqlValue } from "../driver.js";
2
+ /**
3
+ * What a bot sends, as the Bots tab filters it: the mail types that put a bot under each name. `messenger` is a bot
4
+ * with an account in a messenger, whatever it sends. @experimental
5
+ */
6
+ export declare const BOT_SENDS: {
7
+ readonly alerts: readonly ["security", "system_alert", "account_notice"];
8
+ readonly receipts: readonly ["order", "bill", "shipping"];
9
+ readonly newsletters: readonly ["newsletter"];
10
+ readonly marketing: readonly ["promotion"];
11
+ readonly messenger: null;
12
+ };
13
+ /** @experimental */
14
+ export type BotSends = keyof typeof BOT_SENDS;
15
+ /** Which bots send any of these, over `b`: by the type of their mail, or a messenger account. */
16
+ export declare const sendsWhere: (database: CacheDatabase, sends: readonly BotSends[]) => {
17
+ sql: string;
18
+ params: SqlValue[];
19
+ };