@wirecat/wirecat 0.0.0-stage → 1.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 (230) hide show
  1. package/LICENSE +204 -0
  2. package/README.md +400 -2
  3. package/THIRD_PARTY_NOTICES +2 -0
  4. package/contracts/wirecat.json +4612 -0
  5. package/dist/actions/actions.js +269 -0
  6. package/dist/actions/command.js +102 -0
  7. package/dist/agents/command.js +17 -0
  8. package/dist/agents/log.js +23 -0
  9. package/dist/answer.js +100 -0
  10. package/dist/answers/command.js +128 -0
  11. package/dist/app.js +15 -0
  12. package/dist/author.js +109 -0
  13. package/dist/bin/wcat-wirecat.js +40 -0
  14. package/dist/bots/command.js +175 -0
  15. package/dist/bundle/auto-YETGUQ2J.js +43 -0
  16. package/dist/bundle/chunk-3ME37WWB.js +31 -0
  17. package/dist/bundle/chunk-4WI3FO7T.js +395 -0
  18. package/dist/bundle/chunk-7O7XM37N.js +2 -0
  19. package/dist/bundle/chunk-DWQQRBQV.js +51 -0
  20. package/dist/bundle/chunk-FOWR5KJS.js +72 -0
  21. package/dist/bundle/chunk-GGRL6DTE.js +120 -0
  22. package/dist/bundle/chunk-KNFSW562.js +312 -0
  23. package/dist/bundle/chunk-KPJVVFQF.js +416 -0
  24. package/dist/bundle/chunk-WMPDRWVF.js +222 -0
  25. package/dist/bundle/chunk-X5OK73GU.js +807 -0
  26. package/dist/bundle/chunk-ZC4PRE6C.js +38 -0
  27. package/dist/bundle/entry-S4DSYEAY.js +64 -0
  28. package/dist/bundle/failure-FALOD7QW.js +19 -0
  29. package/dist/bundle/from-memo-XVOLSUOM.js +314 -0
  30. package/dist/bundle/program-XSZSINBU.js +14994 -0
  31. package/dist/bundle/server-GQ4NZUDL.js +303 -0
  32. package/dist/bundle/update-2EH5KHTV.js +22 -0
  33. package/dist/bundle/wcat-wirecat.js +83 -0
  34. package/dist/config-command.js +39 -0
  35. package/dist/config-issues.js +15 -0
  36. package/dist/config.js +187 -0
  37. package/dist/context/command.js +162 -0
  38. package/dist/context/context.js +197 -0
  39. package/dist/contract-overrides/commands.js +81 -0
  40. package/dist/contract-overrides/mcp.js +241 -0
  41. package/dist/contract-overrides/meetings.js +344 -0
  42. package/dist/contract-overrides/search.js +508 -0
  43. package/dist/contract-overrides/skill.js +85 -0
  44. package/dist/contract-overrides.js +7 -0
  45. package/dist/digest/backfill.js +175 -0
  46. package/dist/digest/brief.js +189 -0
  47. package/dist/digest/catch-up-record.js +30 -0
  48. package/dist/digest/catch-up.js +86 -0
  49. package/dist/digest/command.js +110 -0
  50. package/dist/digest/digest-commands.js +327 -0
  51. package/dist/digest/digest.js +560 -0
  52. package/dist/digest/digests.js +213 -0
  53. package/dist/digest/history.js +202 -0
  54. package/dist/digest/input.js +30 -0
  55. package/dist/digest/known.js +28 -0
  56. package/dist/digest/sources.js +155 -0
  57. package/dist/digest/sync-health.js +158 -0
  58. package/dist/digest/task-proposals.js +67 -0
  59. package/dist/digest/tasks.js +145 -0
  60. package/dist/digest/text.js +49 -0
  61. package/dist/discovery/command.js +107 -0
  62. package/dist/doctor/command.js +167 -0
  63. package/dist/documents/command.js +107 -0
  64. package/dist/domain-lists/command.js +13 -0
  65. package/dist/events/command.js +35 -0
  66. package/dist/events/events.js +196 -0
  67. package/dist/examples.js +609 -0
  68. package/dist/facts/command.js +100 -0
  69. package/dist/facts/fact.js +54 -0
  70. package/dist/facts/facts.js +15 -0
  71. package/dist/failure.js +58 -0
  72. package/dist/finance/command.js +121 -0
  73. package/dist/finance/contracts-command.js +109 -0
  74. package/dist/finance/deal-text.js +34 -0
  75. package/dist/finance/deals-command.js +346 -0
  76. package/dist/finance/finance.js +129 -0
  77. package/dist/finance/lines-command.js +70 -0
  78. package/dist/finance/orders-command.js +94 -0
  79. package/dist/finance/products-command.js +98 -0
  80. package/dist/finance/subscriptions-command.js +152 -0
  81. package/dist/finance/transactions-command.js +136 -0
  82. package/dist/finance/wallets-command.js +105 -0
  83. package/dist/finance/written.js +36 -0
  84. package/dist/findings/command.js +102 -0
  85. package/dist/findings-input.js +23 -0
  86. package/dist/identity.js +20 -0
  87. package/dist/install/postinstall.js +47 -0
  88. package/dist/json-fields.js +48 -0
  89. package/dist/knowledge/business-text.js +19 -0
  90. package/dist/knowledge/command.js +435 -0
  91. package/dist/knowledge/document-context.js +33 -0
  92. package/dist/knowledge/key-documents.js +120 -0
  93. package/dist/knowledge/list-queries.js +20 -0
  94. package/dist/knowledge/meeting-projects-command.js +61 -0
  95. package/dist/knowledge/messenger-sync.js +253 -0
  96. package/dist/knowledge/money-text.js +16 -0
  97. package/dist/knowledge/notes-about.js +81 -0
  98. package/dist/knowledge/organization-delete-command.js +44 -0
  99. package/dist/knowledge/organization-text.js +27 -0
  100. package/dist/knowledge/project-actions-command.js +130 -0
  101. package/dist/knowledge/project-actions.js +104 -0
  102. package/dist/knowledge/project-activity-command.js +70 -0
  103. package/dist/knowledge/project-context.js +101 -0
  104. package/dist/knowledge/project-findings.js +41 -0
  105. package/dist/knowledge/project-gather-command.js +100 -0
  106. package/dist/knowledge/project-status-command.js +129 -0
  107. package/dist/knowledge/project-transfer-command.js +58 -0
  108. package/dist/knowledge/project-transfer.js +107 -0
  109. package/dist/knowledge/relationships-scan.js +116 -0
  110. package/dist/knowledge/relationships.js +115 -0
  111. package/dist/knowledge/roles-command.js +67 -0
  112. package/dist/mail/command.js +20 -0
  113. package/dist/mail/findings-command.js +143 -0
  114. package/dist/mail/findings-duplicates.js +159 -0
  115. package/dist/mail/messages-command.js +77 -0
  116. package/dist/mail/review-command.js +59 -0
  117. package/dist/mail/subscriptions-command.js +84 -0
  118. package/dist/mcp/catalogue.js +159 -0
  119. package/dist/mcp/command.js +125 -0
  120. package/dist/mcp/granted.js +18 -0
  121. package/dist/mcp/permissions.js +61 -0
  122. package/dist/mcp/server.js +128 -0
  123. package/dist/meetings/command.js +31 -0
  124. package/dist/meetings/list-command.js +59 -0
  125. package/dist/meetings/preparation-command.js +42 -0
  126. package/dist/meetings/preparation-text.js +44 -0
  127. package/dist/meetings/preparation.js +50 -0
  128. package/dist/meetings/read.js +32 -0
  129. package/dist/memories/command.js +105 -0
  130. package/dist/memories/memories.js +17 -0
  131. package/dist/memories/memory.js +89 -0
  132. package/dist/memories/sources.js +111 -0
  133. package/dist/mentions/command.js +91 -0
  134. package/dist/migrate/check.js +48 -0
  135. package/dist/migrate/from-memo.js +345 -0
  136. package/dist/migrate/skill.js +35 -0
  137. package/dist/models/command.js +19 -0
  138. package/dist/options.js +35 -0
  139. package/dist/output.js +17 -0
  140. package/dist/page.js +14 -0
  141. package/dist/people/command.js +144 -0
  142. package/dist/people/delete-command.js +53 -0
  143. package/dist/people/doubts-command.js +81 -0
  144. package/dist/people/identities-command.js +188 -0
  145. package/dist/people/identity.js +42 -0
  146. package/dist/people/owner.js +14 -0
  147. package/dist/people/proposal-rows.js +70 -0
  148. package/dist/people/proposals-command.js +248 -0
  149. package/dist/people/review-context.js +108 -0
  150. package/dist/people/subject.js +19 -0
  151. package/dist/program.js +875 -0
  152. package/dist/read-only.js +51 -0
  153. package/dist/reasons.js +368 -0
  154. package/dist/records/import.js +135 -0
  155. package/dist/records/input.js +210 -0
  156. package/dist/records/mapping.js +80 -0
  157. package/dist/records/record-commands.js +125 -0
  158. package/dist/records/sources.js +73 -0
  159. package/dist/refs.js +28 -0
  160. package/dist/review/command.js +171 -0
  161. package/dist/review/kinds.js +44 -0
  162. package/dist/review/review.js +299 -0
  163. package/dist/review/status.js +93 -0
  164. package/dist/rows.js +219 -0
  165. package/dist/run/auto.js +237 -0
  166. package/dist/run/entry.js +62 -0
  167. package/dist/run/files.js +51 -0
  168. package/dist/run/import.js +253 -0
  169. package/dist/run/lock.js +20 -0
  170. package/dist/save-help.js +3 -0
  171. package/dist/schedule/command.js +58 -0
  172. package/dist/schedule/mail-triage-input.js +152 -0
  173. package/dist/schedule/task-triage-input.js +152 -0
  174. package/dist/search/answers.js +176 -0
  175. package/dist/search/command.js +257 -0
  176. package/dist/search/denied.js +9 -0
  177. package/dist/search/embed.js +126 -0
  178. package/dist/search/hits.js +4 -0
  179. package/dist/search/lane-gates.js +76 -0
  180. package/dist/search/notes-text.js +18 -0
  181. package/dist/search/people.js +88 -0
  182. package/dist/search/search.js +306 -0
  183. package/dist/show/command.js +179 -0
  184. package/dist/store/crm-viewer.js +102 -0
  185. package/dist/store/group.js +112 -0
  186. package/dist/store/groups-command.js +136 -0
  187. package/dist/store/guard.js +94 -0
  188. package/dist/store/held.js +21 -0
  189. package/dist/store/info-command.js +37 -0
  190. package/dist/store/scope.js +53 -0
  191. package/dist/store/source-list.js +222 -0
  192. package/dist/store/source-target.js +28 -0
  193. package/dist/tags/command.js +176 -0
  194. package/dist/tasks/command.js +174 -0
  195. package/dist/tasks/context.js +74 -0
  196. package/dist/tasks/list.js +199 -0
  197. package/dist/tasks/proposal-duplicates.js +70 -0
  198. package/dist/tasks/relations-command.js +28 -0
  199. package/dist/tasks/shared.js +105 -0
  200. package/dist/tasks/tasks.js +197 -0
  201. package/dist/templates/command.js +18 -0
  202. package/dist/terminal.js +23 -0
  203. package/dist/update.js +35 -0
  204. package/dist/version.js +2 -0
  205. package/dist/vocabulary/command.js +103 -0
  206. package/dist/vocabulary/inspect.js +23 -0
  207. package/dist/vocabulary/inspection.js +18 -0
  208. package/dist/vocabulary/list.js +18 -0
  209. package/dist/vocabulary/project.js +19 -0
  210. package/dist/wcat.js +3 -0
  211. package/install/postinstall.mjs +9 -0
  212. package/package.json +89 -4
  213. package/scenarios/decision-trail.md +21 -0
  214. package/scenarios/person-brief.md +35 -0
  215. package/scenarios/prepare-meeting.md +17 -0
  216. package/scenarios/project-state.md +26 -0
  217. package/scenarios/set-up.md +18 -0
  218. package/scenarios/start-the-day.md +19 -0
  219. package/skills/mail-triage/SKILL.md +208 -0
  220. package/skills/morning-digest/SKILL.md +147 -0
  221. package/skills/task-triage/SKILL.md +79 -0
  222. package/skills/wcat/SKILL.md +65 -0
  223. package/skills/wcat/topics/mail.md +32 -0
  224. package/skills/wcat/topics/mcp.md +22 -0
  225. package/skills/wcat/topics/meetings.md +37 -0
  226. package/skills/wcat/topics/money.md +52 -0
  227. package/skills/wcat/topics/projects.md +54 -0
  228. package/skills/wcat/topics/proposals.md +113 -0
  229. package/skills/wcat/topics/search.md +85 -0
  230. package/skills/wcat/topics/vocabulary.md +8 -0
@@ -0,0 +1,143 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ import { annotate } from "@wirecat/cli-base/commands";
3
+ import { environmentOf, LOCAL_READ, LOCAL_WRITE, mailFindingFieldsHelp, parseMailFindingsJson, proposesOnly, queryTerms, readMailFindingsJson, termField, withQuery, } from "@wirecat/cli-core";
4
+ import { answers, itemAnswer, listAnswer } from "../answer.js";
5
+ import { whoRuns } from "../author.js";
6
+ import { FINDINGS_INPUT_HELP, readFindingsInput } from "../findings-input.js";
7
+ import { positive } from "../options.js";
8
+ import { withoutDuplicates } from "./findings-duplicates.js";
9
+ import { MAILBOX_HELP, oneMailboxOf } from "./review-command.js";
10
+ const FINDINGS_QUERY = {
11
+ entity: "mail_findings",
12
+ backend: "native",
13
+ fields: [termField("status", "enum", "status:proposed", { values: ["proposed", "reviewed"] })],
14
+ };
15
+ const INPUT_HELP = `
16
+ Input: schema_version 1, key, extractor, findings. key is the one \`review mail --holder\` gave in its
17
+ mail-findings.add step (mail-triage:9123456, or mail-triage:9123456-r1 after the owner moved the mark back); pass it
18
+ as --key or in the JSON. The same key and input give the same batch, the same key with another input is refused. 1–30 findings, at most 5 from one sender; each cites 1–8 msg:email/… references with the
19
+ fingerprint review gave, and at least one email of this mailbox.
20
+ Every finding gives id, kind, evidence and the fields its kind needs, reason among them; the others are optional:
21
+ ${mailFindingFieldsHelp()}
22
+ A task's due_at is a timestamp with a timezone and comes with due_evidence, the cited refs that give the date:
23
+ "due_at":"2026-11-09T09:00:00Z","due_evidence":["msg:email/…"]; assignee comes with assignee_evidence the same way.
24
+ An invoice names counterparty (person:N or organization:N) or counterparty_name. A task_update's due change gives
25
+ due_at, its detail change gives detail; a link goes contact:email/<address> → person:N, person:N → organization:N or
26
+ chat:email/… → project:N; a memory is about a subject or a project; an order_update names a stored order, with date
27
+ only when delivered.
28
+ A finding whose order, invoice, payment, task or fact is stored, already waits in a proposed batch or came earlier in
29
+ the batch is a duplicate: it is not staged and the answer lists it in duplicates with duplicate_of, the reference that
30
+ holds it, and reason findings.duplicate. The rest of the batch stages. An order is the same by shop and number or
31
+ source_url, an invoice by counterparty and number, a payment by amount, currency, date and party, a task by external_id
32
+ or source_url, a fact by its text and subject.
33
+ An invoice, payment or order is checked as wcat invoices|payments|orders add checks yours; a refusal names why.
34
+ A cited email that changed since review refuses the batch (mail-findings.stale), one still partial too
35
+ (mail-findings.partial). Nothing is created until the owner confirms: wcat review confirm <batch>/<finding>.
36
+ A party the store does not hold yet goes by name: counterparty_name, payer_name, payee_name or customer_name in
37
+ place of the reference, with an optional <party>_email that sent or received a cited email; the owner's accept finds
38
+ its organization by that address, its domain or the exact name, or makes one. An order whose shop and number are
39
+ stored (order.duplicate) or already wait in a proposed batch (order.proposed) is refused.
40
+ --dry-run checks it all and stages nothing: valid, and problems with each refused finding's id, kind and message.
41
+ Build the whole batch, check it, fix every problem, then stage it once: a staged key takes no other input.
42
+ `;
43
+ /** The batch with `--key` as its key; the JSON may leave key out, and may not name another. */
44
+ const keyed = (text, key) => {
45
+ if (key === undefined)
46
+ return text;
47
+ let raw;
48
+ try {
49
+ raw = JSON.parse(text);
50
+ }
51
+ catch {
52
+ return text;
53
+ }
54
+ if (!raw || typeof raw !== "object" || Array.isArray(raw))
55
+ return text;
56
+ const named = raw.key;
57
+ if (named !== undefined && named !== key)
58
+ throw new CliError("validation_error", `the batch's key ${String(named)} is not --key ${key}; give the key once`, {
59
+ reason: "findings.key-mismatch",
60
+ key: String(named),
61
+ given: key,
62
+ });
63
+ return JSON.stringify({ ...raw, key });
64
+ };
65
+ const json = (command) => command.option("--json", "print JSON; --json=id,status keeps only those fields");
66
+ /**
67
+ * `wcat review findings`: what an agent read in one mailbox's new mail, staged for the owner. `add` is of cli-core's
68
+ * propose tier, so a read-only scheduled agent may stage; deciding is the proposal registry's, owner only.
69
+ */
70
+ export const mailFindingsCommand = (program, review, streams, env) => {
71
+ const { run } = answers(program, streams, env);
72
+ const findings = review
73
+ .command("findings")
74
+ .description("cited tasks, task updates, facts, memories, links, contacts, invoices, payments and orders an agent read in new mail")
75
+ .summary("what an agent read in new mail, cited, waiting for the owner");
76
+ json(proposesOnly(annotate(findings.command("add"), { effects: LOCAL_WRITE, output: { entity: "mail_findings" } })))
77
+ .description("stage one mailbox's findings for the owner; nothing is created until the owner confirms")
78
+ .summary("stage one mailbox's findings; the owner confirms them")
79
+ .argument("<file>", FINDINGS_INPUT_HELP)
80
+ .option("--source <accounts>", MAILBOX_HELP)
81
+ .option("--key <key>", "the findings key `review mail --holder` gave in its mail-findings.add step")
82
+ .option("--dry-run", "check the batch as staging would, invoices, payments and orders tried and rolled back, and stage nothing; " +
83
+ "answers valid and every finding's problem at once")
84
+ .addHelpText("after", INPUT_HELP)
85
+ .action(async (file, given) => {
86
+ const read = await readFindingsInput(file, environmentOf(program).stdin ?? process.stdin);
87
+ const text = keyed(read, given.key);
88
+ const input = given.dryRun ? readMailFindingsJson(text) : parseMailFindingsJson(text);
89
+ const author = await whoRuns(program, env, { question: "" });
90
+ const agent = author === "owner" ? { bot: "wcat-mail-findings" } : author;
91
+ await run(given.json, async (store) => {
92
+ const mailbox = await oneMailboxOf(store, env, given.source);
93
+ const { input: kept, duplicates } = await withoutDuplicates(store, input);
94
+ const noted = duplicates.length ? { duplicates } : {};
95
+ if (duplicates.length > 0 && kept.findings.length === 0)
96
+ return itemAnswer({
97
+ dryRun: Boolean(given.dryRun),
98
+ valid: true,
99
+ staged: false,
100
+ findings: 0,
101
+ problems: [],
102
+ ...noted,
103
+ });
104
+ if (!given.dryRun)
105
+ return itemAnswer({ ...(await store.mailFindings.stage(mailbox, kept, agent)), ...noted });
106
+ const checked = await store.mailFindings.check(mailbox, kept, agent);
107
+ const issues = checked.problems.map((one) => ({
108
+ code: one.code,
109
+ source: one.finding ?? "batch",
110
+ reason: one.details?.reason ?? one.message,
111
+ }));
112
+ return itemAnswer({ dryRun: true, ...checked, ...noted }, issues.length ? { meta: { complete: false, issues } } : undefined);
113
+ });
114
+ });
115
+ json(annotate(findings.command("show"), { effects: LOCAL_READ, output: { entity: "mail_findings" } }))
116
+ .description("one findings batch: its findings with their evidence, earlier decisions and the review receipt")
117
+ .summary("one findings batch with its evidence and decisions")
118
+ .argument("<id>", "the batch id `review findings add` or `list` gave")
119
+ .action((id, given) => run(given.json, async (store) => itemAnswer(await store.mailFindings.get(id))));
120
+ withQuery(json(annotate(findings.command("list"), { effects: LOCAL_READ, output: { entity: "mail_findings" } })), FINDINGS_QUERY)
121
+ .description("review findings batches, newest first; status:proposed is what waits for the owner")
122
+ .option("--source <accounts>", "only this mailbox's batches: email:<address>")
123
+ .option("--limit <n>", "batches per page, at most 50", positive, 20)
124
+ .option("--page <n>", "which page, from 1", positive, 1)
125
+ .action((words, given) => run(given.json, async (store) => {
126
+ const status = queryTerms(words, FINDINGS_QUERY, "review findings list").get("status");
127
+ const account = given.source ? await oneMailboxOf(store, env, given.source) : undefined;
128
+ const found = await store.mailFindings.list({
129
+ limit: given.limit,
130
+ offset: (given.page - 1) * given.limit,
131
+ ...(account === undefined ? {} : { account }),
132
+ ...(status === undefined ? {} : { status }),
133
+ });
134
+ return listAnswer("review findings list", {
135
+ items: found.items,
136
+ limit: given.limit,
137
+ page: given.page,
138
+ has_more: found.hasMore,
139
+ args: { query: words.join(" "), ...(given.source ? { source: given.source } : {}), limit: given.limit },
140
+ });
141
+ }));
142
+ };
143
+ //# sourceMappingURL=findings-command.js.map
@@ -0,0 +1,159 @@
1
+ export const DUPLICATE_REASON = "findings.duplicate";
2
+ const PAGE = 50;
3
+ const NEWEST = 500;
4
+ const fold = (text) => text
5
+ .normalize("NFKD")
6
+ .replace(/\p{M}/gu, "")
7
+ .toLowerCase()
8
+ .replace(/[^\p{L}\p{N}]+/gu, " ")
9
+ .trim();
10
+ const amount = (value) => {
11
+ const plain = value.replace(/\s/g, "").replace(",", ".");
12
+ return plain.includes(".") ? plain.replace(/0+$/, "").replace(/\.$/, "") : plain;
13
+ };
14
+ const link = (url) => url.trim().replace(/#.*$/, "").replace(/\/+$/, "").toLowerCase();
15
+ /** Party keys of a stored or proposed side: the reference and the folded name, so either spelling finds the other. */
16
+ const party = (reference, name) => [
17
+ ...(reference ? [reference] : []),
18
+ ...(name && fold(name) ? [`name:${fold(name)}`] : []),
19
+ ];
20
+ /** A dry run reads the batch unvalidated, so any field may be missing or not text; such a finding has no key. */
21
+ const text = (value) => (typeof value === "string" && value.trim() ? value : undefined);
22
+ const present = (parts) => parts.filter((part) => part !== undefined);
23
+ /** The keys a finding is the same record under; two findings sharing one key describe one thing. */
24
+ const keysOf = (finding) => {
25
+ const raw = (finding ?? {});
26
+ const [shop, number, url, id] = [raw.supplierName, raw.number, raw.sourceUrl, raw.externalId].map(text);
27
+ switch (raw.kind) {
28
+ case "order":
29
+ return present([shop && number && `order:${fold(shop)}/${fold(number)}`, url && `url:${link(url)}`]);
30
+ case "invoice": {
31
+ const [reference, name] = [raw.counterparty, raw.counterpartyName].map(text);
32
+ return number ? party(reference, name).map((side) => `invoice:${side}/${fold(number)}`) : [];
33
+ }
34
+ case "payment": {
35
+ const [direction, sum, currency, date] = [raw.direction, raw.amount, raw.currency, raw.date].map(text);
36
+ if (!direction || !sum || !currency || !date)
37
+ return [];
38
+ const [payer, payerName, payee, payeeName] = [raw.payer, raw.payerName, raw.payee, raw.payeeName].map(text);
39
+ return [...party(payer, payerName), ...party(payee, payeeName)].map((side) => `payment:${direction}/${amount(sum)}/${currency.toUpperCase()}/${date}/${side}`);
40
+ }
41
+ case "task":
42
+ return present([id && `task-id:${id.toLowerCase()}`, url && `url:${link(url)}`]);
43
+ case "fact": {
44
+ const statement = text(raw.statement);
45
+ return statement ? [`fact:${fold(statement)}/${text(raw.subject) ?? ""}`] : [];
46
+ }
47
+ default:
48
+ return [];
49
+ }
50
+ };
51
+ const remember = (seen, keys, ref) => {
52
+ for (const key of keys)
53
+ if (!seen.has(key))
54
+ seen.set(key, ref);
55
+ };
56
+ const CHECKED = new Set(["order", "invoice", "payment", "task", "fact"]);
57
+ /** What the store already holds or has waiting, as key → the reference that holds it; only the kinds the batch has. */
58
+ const known = async (store, kinds) => {
59
+ const seen = new Map();
60
+ const live = (rows) => rows.filter((row) => row.review !== "rejected");
61
+ const tasks = [];
62
+ if (kinds.has("order"))
63
+ tasks.push(store.orders.list({ limit: NEWEST }).then(({ items: orders }) => {
64
+ for (const one of live(orders))
65
+ remember(seen, [
66
+ ...(one.number ? [`order:${fold(one.supplierName)}/${fold(one.number)}`] : []),
67
+ ...(one.sourceUrl ? [`url:${link(one.sourceUrl)}`] : []),
68
+ ], one.ref);
69
+ }));
70
+ if (kinds.has("invoice"))
71
+ tasks.push(store.finance.invoices({ limit: NEWEST }).then(({ items: invoices }) => {
72
+ for (const one of live(invoices))
73
+ if (one.number)
74
+ remember(seen, party(one.counterparty.ref, one.counterparty.name).map((side) => `invoice:${side}/${fold(one.number)}`), one.ref);
75
+ }));
76
+ if (kinds.has("payment"))
77
+ tasks.push(store.finance.payments({ limit: NEWEST }).then(({ items: payments }) => {
78
+ for (const one of live(payments)) {
79
+ const sides = [one.payer, one.payee].filter((side) => side && !side.owner);
80
+ remember(seen, sides
81
+ .flatMap((side) => party(side?.ref, side?.name))
82
+ .map((side) => `payment:${one.direction}/${amount(one.amount)}/${one.currency.toUpperCase()}/${one.date}/${side}`), one.ref);
83
+ }
84
+ }));
85
+ if (kinds.has("task"))
86
+ tasks.push(store.tasks.find({ limit: NEWEST }).then(({ items: found }) => {
87
+ for (const one of found)
88
+ remember(seen, [
89
+ ...(one.externalId ? [`task-id:${one.externalId.toLowerCase()}`] : []),
90
+ ...(one.sourceUrl ? [`url:${link(one.sourceUrl)}`] : []),
91
+ ], one.ref);
92
+ }));
93
+ if (kinds.has("fact"))
94
+ tasks.push(store.facts.list({ limit: NEWEST, order: "created" }).then(({ items: facts }) => {
95
+ for (const one of facts)
96
+ if (one.status === "proposed" || one.status === "accepted")
97
+ remember(seen, [`fact:${fold(one.statement)}/${one.subject ?? ""}`], one.ref);
98
+ }));
99
+ await Promise.all(tasks);
100
+ return seen;
101
+ };
102
+ /**
103
+ * Every proposed batch's findings, newest batch first, so the nearest holder of a thing is the one named. The batch
104
+ * staged under `key` is this run's own and holds nothing against it.
105
+ */
106
+ const waiting = async (store, seen, key, own) => {
107
+ for (let offset = 0;; offset += PAGE) {
108
+ const { items, hasMore } = await store.mailFindings.list({ status: "proposed", limit: PAGE, offset });
109
+ for (const batch of items) {
110
+ if (batch.input.key === key)
111
+ for (const finding of batch.input.findings)
112
+ own.add(finding.id);
113
+ else
114
+ for (const finding of batch.input.findings)
115
+ remember(seen, keysOf(finding), `${batch.id}/${finding.id}`);
116
+ }
117
+ if (!hasMore)
118
+ return;
119
+ }
120
+ };
121
+ /** The findings of a batch already staged or decided under this key: a rerun of the run must not lose them. */
122
+ const ownFindings = async (store, key) => {
123
+ const { items } = await store.mailFindings.list({ limit: PAGE });
124
+ const held = items.find((batch) => batch.input.key === key);
125
+ return new Set(held?.input.findings.map((finding) => finding.id));
126
+ };
127
+ /**
128
+ * Splits a batch into the findings worth staging and the duplicates: a finding whose order, invoice, payment, task or
129
+ * fact is stored, waits in a proposed batch, or came earlier in this batch. A finding the batch already staged under
130
+ * this key stays, so a rerun gets the same batch back.
131
+ */
132
+ export const withoutDuplicates = async (store, input) => {
133
+ if (!Array.isArray(input.findings))
134
+ return { input, duplicates: [] };
135
+ const kinds = new Set(input.findings.map((finding) => finding?.kind));
136
+ if (![...kinds].some((kind) => CHECKED.has(kind)))
137
+ return { input, duplicates: [] };
138
+ const own = await ownFindings(store, input.key);
139
+ const seen = await known(store, kinds);
140
+ await waiting(store, seen, input.key, own);
141
+ const kept = [];
142
+ const duplicates = [];
143
+ for (const finding of input.findings) {
144
+ if (!finding || typeof finding !== "object") {
145
+ kept.push(finding);
146
+ continue;
147
+ }
148
+ const keys = keysOf(finding);
149
+ const held = own.has(finding.id) ? undefined : keys.map((key) => seen.get(key)).find((ref) => ref !== undefined);
150
+ if (held)
151
+ duplicates.push({ finding: finding.id, kind: finding.kind, duplicateOf: held, reason: DUPLICATE_REASON });
152
+ else {
153
+ kept.push(finding);
154
+ remember(seen, keys, `finding:${finding.id}`);
155
+ }
156
+ }
157
+ return { input: { ...input, findings: kept }, duplicates };
158
+ };
159
+ //# sourceMappingURL=findings-duplicates.js.map
@@ -0,0 +1,77 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ import { annotate } from "@wirecat/cli-base/commands";
3
+ import { contextEvidenceFingerprint, formatLocator, LOCAL_READ, parseLocator, } from "@wirecat/cli-core";
4
+ import { ATTACHMENT_CHARS, attachmentsText, hitText, mailOwnText, showMail } from "@wirecat/cli-core/mail";
5
+ import { answers, itemAnswer, wholeList, withStore } from "../answer.js";
6
+ import { whole } from "../options.js";
7
+ import { atDetail } from "../output.js";
8
+ /** The fingerprint a finding cites this email by, the one `review mail --holder` gives: a finding
9
+ * cites what the agent read, so both must hash the same record. */
10
+ const citedBy = async (store, ref) => {
11
+ const record = await store.contextRecords?.read(ref);
12
+ return record ? contextEvidenceFingerprint(record) : null;
13
+ };
14
+ export const messagesCommand = (program, streams, env) => {
15
+ const { print } = answers(program, streams, env);
16
+ const messages = program.command("messages").description("stored messenger messages and emails");
17
+ annotate(messages.command("show"), { effects: LOCAL_READ })
18
+ .description("one stored message or email whole, with optional stored neighbours")
19
+ .argument("<message>", "the msg:provider/account/chat/message reference a search gives")
20
+ .option("--before-n <n>", "also this many earlier emails of its thread", whole, 0)
21
+ .option("--after-n <n>", "also this many later emails of its thread", whole, 0)
22
+ .option("--full", `whole attachment text, not the first ${ATTACHMENT_CHARS} characters of each, and the HTML and AMP versions of the body`)
23
+ .option("--trimmed", "each email's own text, without quoted earlier mail or the signature — for an agent's reads")
24
+ .option("--json", "print JSON; --json=id,title keeps only those fields")
25
+ .action(async (reference, options) => {
26
+ if (options.trimmed && options.full)
27
+ throw new CliError("validation_error", "--trimmed shows less of an email and --full more — give one", {
28
+ param: "trimmed",
29
+ });
30
+ const locator = parseLocator(reference);
31
+ if (locator.provider !== "email") {
32
+ const key = { provider: locator.provider, account: locator.account };
33
+ const messages = await withStore(env, async (store) => {
34
+ const message = await store.messages.message(key, locator.message, { chatId: locator.chat });
35
+ if (!message)
36
+ throw new CliError("not_found", `${reference} is not in the local store`);
37
+ return options.beforeN || options.afterN
38
+ ? store.messages.around(key, locator.chat, locator.message, {
39
+ before: options.beforeN,
40
+ after: options.afterN,
41
+ })
42
+ : [message];
43
+ });
44
+ const items = messages.map((message) => ({
45
+ ...message,
46
+ ref: formatLocator({ ...locator, message: message.id }),
47
+ }));
48
+ print(options.json, options.beforeN || options.afterN ? wholeList("messages show", items) : itemAnswer(items[0]));
49
+ return;
50
+ }
51
+ const emails = await withStore(env, async (store) => {
52
+ const shown = await showMail(store, reference, {
53
+ before: options.beforeN,
54
+ after: options.afterN,
55
+ full: options.full === true,
56
+ });
57
+ return Promise.all(shown.map(async (email) => ({
58
+ ...email,
59
+ ...(options.trimmed ? { text: mailOwnText(email.text) } : {}),
60
+ ref: email.locator,
61
+ fingerprint: await citedBy(store, email.locator),
62
+ })));
63
+ });
64
+ print(options.json, options.beforeN || options.afterN
65
+ ? wholeList("messages show", atDetail(emails))
66
+ : itemAnswer(atDetail(emails[0])), emails
67
+ .map((email) => [
68
+ hitText(email, "full"),
69
+ attachmentsText(email),
70
+ email.fingerprint ? `fingerprint ${email.fingerprint}` : "",
71
+ ]
72
+ .filter(Boolean)
73
+ .join("\n"))
74
+ .join("\n\n"));
75
+ });
76
+ };
77
+ //# sourceMappingURL=messages-command.js.map
@@ -0,0 +1,59 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ import { overrideSharedContract } from "@wirecat/cli-core";
3
+ import { mailReadCommands } from "@wirecat/cli-core/mail";
4
+ import { withStore } from "../answer.js";
5
+ import { APP } from "../app.js";
6
+ import { bulkTriage } from "../config.js";
7
+ import { MAIL_SOURCES, oneAccountOf } from "../store/source-list.js";
8
+ export const MAILBOX_HELP = `the one mailbox: ${MAIL_SOURCES}; may be left out when the store holds one mailbox`;
9
+ /** cli-core's mail commands read one mailbox per call; wcat holds several, so the caller names it. */
10
+ export const oneMailboxOf = async (store, env, source) => {
11
+ const key = await oneAccountOf(store, env, source ?? "email");
12
+ if (key.provider !== "email")
13
+ throw new CliError("validation_error", `${source} is not a mailbox — ${MAIL_SOURCES}`, { param: "source" });
14
+ return key;
15
+ };
16
+ const named = (commands, name) => {
17
+ const found = commands.find((command) => command.name() === name);
18
+ if (!found)
19
+ throw new Error(`cli-core's mail commands have no ${name}`);
20
+ return found;
21
+ };
22
+ /**
23
+ * `wcat review mail`, `wcat messages acknowledge` and `wcat messages reset`: cli-core's, over the mailbox `--source`
24
+ * names. The holder read and the acknowledge are what the mail-triage agent runs; acknowledge is of cli-core's propose
25
+ * tier, the one store change WCAT_READ_ONLY lets through besides `review findings add`. Reset, which moves a mark back,
26
+ * is the owner's alone.
27
+ */
28
+ export const mailReviewCommands = (parent, messages, env) => {
29
+ const reads = {
30
+ app: APP,
31
+ read: (command, work) => withStore(env, async (store) => work(store, await oneMailboxOf(store, env, command.opts().source))),
32
+ bulkTriage: () => bulkTriage(env),
33
+ mount: {
34
+ review: "review mail",
35
+ acknowledge: "messages acknowledge",
36
+ findings: "review findings add",
37
+ conversation: null,
38
+ mailbox: { option: "source", value: (mailbox) => `email:${mailbox.account}` },
39
+ },
40
+ };
41
+ const shared = mailReadCommands(reads);
42
+ const review = named(shared, "review");
43
+ const sharedMessages = named(shared, "messages").commands;
44
+ const acknowledge = named(sharedMessages, "acknowledge");
45
+ const reset = named(sharedMessages, "reset");
46
+ for (const command of [review, acknowledge, reset])
47
+ overrideSharedContract(command, "wcat holds several mailboxes and no profile, so --source names the one mailbox; its --json is per command.", (one) => {
48
+ one
49
+ .option("--source <accounts>", MAILBOX_HELP)
50
+ .option("--json", "print JSON; --json=id,title keeps only those fields");
51
+ });
52
+ overrideSharedContract(review, "wcat has no mail group: the mail word belongs to the mail CLI, so the review of new mail is review mail.", (one) => {
53
+ one.name("mail");
54
+ });
55
+ parent.addCommand(review);
56
+ messages.addCommand(acknowledge);
57
+ messages.addCommand(reset);
58
+ };
59
+ //# sourceMappingURL=review-command.js.map
@@ -0,0 +1,84 @@
1
+ import { annotate } from "@wirecat/cli-base/commands";
2
+ import { LOCAL_READ, MAIL_TYPES, queryTerms, termField, withQuery, } from "@wirecat/cli-core";
3
+ import { answers, listAnswer, withStore } from "../answer.js";
4
+ import { positive } from "../options.js";
5
+ import { groupOf } from "../store/group.js";
6
+ import { MAIL_SOURCES, mailboxesOf } from "../store/source-list.js";
7
+ const subscriptionRow = (subscription) => ({
8
+ key: subscription.key,
9
+ list_id: subscription.listId,
10
+ name: subscription.name,
11
+ sender: subscription.sender,
12
+ address: subscription.address,
13
+ emails: subscription.emails,
14
+ newest: {
15
+ email_id: subscription.newest.id,
16
+ message_id: subscription.newest.externalId,
17
+ subject: subscription.newest.subject,
18
+ at: subscription.newest.at === null ? null : new Date(subscription.newest.at).toISOString(),
19
+ },
20
+ can_unsubscribe: subscription.unsubscribe !== null,
21
+ unsubscribe: subscription.unsubscribe === null
22
+ ? null
23
+ : {
24
+ https: subscription.unsubscribe.https,
25
+ mailto: subscription.unsubscribe.mailto,
26
+ one_click: subscription.unsubscribe.oneClick,
27
+ email_id: subscription.unsubscribe.emailId,
28
+ },
29
+ });
30
+ const QUERY = {
31
+ entity: "mail_subscription",
32
+ backend: "native",
33
+ fields: [termField("type", "enum", "type:promotion", { values: [...MAIL_TYPES] })],
34
+ };
35
+ export const mailSubscriptionsCommand = (review, program, streams, env) => {
36
+ const { print } = answers(program, streams, env);
37
+ const subscriptions = review
38
+ .command("subscriptions")
39
+ .description("what is sent to you and you may leave: broadcast mail grouped by its list (List-Id), else by its sender. Not " +
40
+ "the subscriptions you bill or pay (subscriptions list)")
41
+ .summary("newsletters and lists you get, by list");
42
+ withQuery(annotate(subscriptions.command("list"), { effects: LOCAL_READ })
43
+ .summary("broadcast mail by list, newest first")
44
+ .description("broadcast mail grouped by List-Id, else by its sender, newest first: each with its mail count, its newest " +
45
+ "email and where to unsubscribe (an https or mailto target its sender's DKIM signature vouches for, and " +
46
+ "whether one click does it). Nothing is unsubscribed. Open a row's mail with search mail list:<list_id> " +
47
+ "reach:broadcast, or from:<address> reach:broadcast for a row with no list"), QUERY)
48
+ .option("--source <accounts>", `the mailboxes to read (default: every one): ${MAIL_SOURCES}`)
49
+ .option("--limit <n>", "most lists on a page, up to 500", positive, 100)
50
+ .option("--page <n>", "which page, from 1", positive, 1)
51
+ .option("--json", "print JSON; --json=id,title keeps only those fields")
52
+ .action(async (words, options) => {
53
+ const type = queryTerms(words, QUERY, "review subscriptions list").get("type");
54
+ const limit = Math.min(options.limit, 500);
55
+ const group = groupOf(env);
56
+ const found = await withStore(env, async (store) => {
57
+ const source = options.source ?? (group === undefined ? undefined : `group:${group.name}`);
58
+ const mailboxes = source === undefined ? undefined : await mailboxesOf(store, env, source);
59
+ const accountIds = mailboxes === undefined
60
+ ? undefined
61
+ : await Promise.all(mailboxes.map(async (key) => (await store.accounts.storedAccount(key)).id));
62
+ return store.mail.subscriptions({
63
+ limit,
64
+ offset: (options.page - 1) * limit,
65
+ ...(type === undefined ? {} : { types: [type] }),
66
+ ...(accountIds === undefined ? {} : { accountIds }),
67
+ });
68
+ });
69
+ const items = found.items.map(subscriptionRow);
70
+ print(options.json, listAnswer("review subscriptions list", {
71
+ items,
72
+ limit,
73
+ has_more: found.hasMore,
74
+ page: options.page,
75
+ total: { value: found.total, relation: "eq" },
76
+ args: words.length ? { query: words.join(" ") } : {},
77
+ }), items
78
+ .map((row) => `${row.name ?? row.key} ${row.emails} emails, newest ${row.newest.at?.slice(0, 10) ?? "?"}` +
79
+ `${row.can_unsubscribe ? (row.unsubscribe?.one_click ? " one-click unsubscribe" : " unsubscribe") : ""}` +
80
+ `\n ${row.key}`)
81
+ .join("\n"));
82
+ });
83
+ };
84
+ //# sourceMappingURL=subscriptions-command.js.map