@wirecat/cli-core 0.605.0 → 0.607.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 (260) hide show
  1. package/CHANGELOG.md +284 -1
  2. package/dist/calendar/index.d.ts +1 -0
  3. package/dist/calendar/index.js +1 -0
  4. package/dist/calendar/reads.js +5 -0
  5. package/dist/cli/app-mcp-command.d.ts +6 -2
  6. package/dist/cli/app-mcp-command.js +11 -2
  7. package/dist/cli/csv.d.ts +10 -0
  8. package/dist/cli/csv.js +22 -0
  9. package/dist/cli/early-refusal.d.ts +10 -0
  10. package/dist/cli/early-refusal.js +19 -0
  11. package/dist/cli/index.d.ts +4 -1
  12. package/dist/cli/index.js +4 -0
  13. package/dist/cli/profile-token.d.ts +29 -0
  14. package/dist/cli/profile-token.js +65 -0
  15. package/dist/cli/program.js +4 -2
  16. package/dist/cli/store-settings.js +38 -4
  17. package/dist/crm/cli/csv.d.ts +23 -0
  18. package/dist/crm/cli/csv.js +135 -0
  19. package/dist/crm/cli/index.d.ts +1 -1
  20. package/dist/crm/cli/index.js +36 -22
  21. package/dist/crm/cli/pipeline-view.d.ts +3 -0
  22. package/dist/crm/cli/pipeline-view.js +36 -0
  23. package/dist/crm/index.d.ts +2 -2
  24. package/dist/crm/index.js +1 -1
  25. package/dist/crm/source.d.ts +35 -5
  26. package/dist/crm/sync.d.ts +15 -7
  27. package/dist/crm/sync.js +169 -11
  28. package/dist/crm/writes.d.ts +6 -4
  29. package/dist/crm/writes.js +17 -13
  30. package/dist/documents.d.ts +2 -0
  31. package/dist/documents.js +2 -0
  32. package/dist/domain/business.d.ts +79 -0
  33. package/dist/domain/business.js +42 -0
  34. package/dist/domain/crm.d.ts +41 -2
  35. package/dist/domain/deals.d.ts +5 -2
  36. package/dist/domain/deals.js +5 -2
  37. package/dist/domain/finance.d.ts +2 -0
  38. package/dist/domain/finance.js +2 -2
  39. package/dist/domain/google-documents.d.ts +2 -0
  40. package/dist/domain/google-documents.js +3 -1
  41. package/dist/domain/money.d.ts +2 -0
  42. package/dist/domain/money.js +11 -3
  43. package/dist/domain/providers.d.ts +36 -1
  44. package/dist/domain/providers.js +69 -7
  45. package/dist/domain/record-fields.d.ts +42 -0
  46. package/dist/domain/record-fields.js +122 -0
  47. package/dist/domain/record-types.d.ts +489 -16
  48. package/dist/domain/record-types.js +374 -7
  49. package/dist/domain/records.d.ts +96 -5
  50. package/dist/domain/records.js +178 -32
  51. package/dist/domain/ref-summaries.js +5 -0
  52. package/dist/domain/references.d.ts +1 -1
  53. package/dist/domain/references.js +5 -0
  54. package/dist/domain/relations.d.ts +125 -0
  55. package/dist/domain/relations.js +107 -0
  56. package/dist/domain/vcard.d.ts +25 -0
  57. package/dist/domain/vcard.js +267 -0
  58. package/dist/entities/deal.d.ts +16 -2
  59. package/dist/entities/deal.js +5 -1
  60. package/dist/entities/index.d.ts +29 -13
  61. package/dist/entities/relationship.d.ts +8 -2
  62. package/dist/entities/relationship.js +8 -2
  63. package/dist/entities/task-results.d.ts +10 -10
  64. package/dist/errors/reasons.js +73 -2
  65. package/dist/fetch/addresses.d.ts +5 -0
  66. package/dist/fetch/addresses.js +76 -0
  67. package/dist/fetch/page.d.ts +64 -0
  68. package/dist/fetch/page.js +256 -0
  69. package/dist/index.d.ts +7 -4
  70. package/dist/index.js +6 -3
  71. package/dist/mail/cli/review.js +20 -6
  72. package/dist/mail/index.d.ts +1 -1
  73. package/dist/mail/marks.d.ts +10 -5
  74. package/dist/mail/marks.js +16 -8
  75. package/dist/mail/review.d.ts +5 -0
  76. package/dist/meetings/calendar-text.d.ts +1 -1
  77. package/dist/meetings/calendar-text.js +4 -0
  78. package/dist/meetings/event-store.d.ts +2 -2
  79. package/dist/search/account-list.d.ts +4 -0
  80. package/dist/search/account-list.js +19 -8
  81. package/dist/search/query.js +2 -2
  82. package/dist/services/events-search.js +2 -2
  83. package/dist/services/index.d.ts +1 -1
  84. package/dist/services/index.js +1 -1
  85. package/dist/services/ingest.d.ts +56 -8
  86. package/dist/services/ingest.js +95 -61
  87. package/dist/services/link-scorers/scan.js +2 -1
  88. package/dist/services/link-scorers/shared.js +2 -1
  89. package/dist/services/messages-search.js +3 -2
  90. package/dist/services/metadata.d.ts +1 -1
  91. package/dist/services/notes-search.js +1 -0
  92. package/dist/services/project-status/index.js +2 -1
  93. package/dist/services/proposals/kinds/contracts.d.ts +4 -0
  94. package/dist/services/proposals/kinds/contracts.js +9 -0
  95. package/dist/services/proposals/kinds/finance.d.ts +4 -0
  96. package/dist/services/proposals/kinds/finance.js +14 -35
  97. package/dist/services/proposals/kinds/orders.js +7 -30
  98. package/dist/services/proposals/kinds/shared.d.ts +27 -1
  99. package/dist/services/proposals/kinds/shared.js +34 -0
  100. package/dist/services/proposals/kinds/source-review.d.ts +4 -0
  101. package/dist/services/proposals/kinds/source-review.js +45 -0
  102. package/dist/services/proposals/kinds/subscriptions.d.ts +9 -0
  103. package/dist/services/proposals/kinds/subscriptions.js +24 -0
  104. package/dist/services/proposals/kinds/transactions.d.ts +4 -0
  105. package/dist/services/proposals/kinds/transactions.js +10 -0
  106. package/dist/services/proposals/registry.js +9 -0
  107. package/dist/services/search-all-meetings.js +2 -2
  108. package/dist/services/search-all.js +4 -3
  109. package/dist/services/search-kind.js +3 -3
  110. package/dist/services/stored-project-gathering.js +4 -3
  111. package/dist/store/decisions.js +5 -1
  112. package/dist/store/exports.d.ts +1 -0
  113. package/dist/store/exports.js +1 -0
  114. package/dist/store/index.d.ts +20 -4
  115. package/dist/store/index.js +4 -0
  116. package/dist/store/people.js +1 -1
  117. package/dist/store/project-transfer/request.d.ts +4 -1
  118. package/dist/store/project-transfer/schema.d.ts +9 -2
  119. package/dist/store/project-transfer/schema.js +4 -0
  120. package/dist/store/project-transfer/snapshot-model.d.ts +8 -2
  121. package/dist/store/source-review.d.ts +64 -0
  122. package/dist/store/source-review.js +7 -0
  123. package/dist/store/sqlite/accounts.d.ts +1 -1
  124. package/dist/store/sqlite/accounts.js +24 -1
  125. package/dist/store/sqlite/added-sources.d.ts +82 -0
  126. package/dist/store/sqlite/added-sources.js +237 -0
  127. package/dist/store/sqlite/business-contracts.d.ts +90 -0
  128. package/dist/store/sqlite/business-contracts.js +182 -0
  129. package/dist/store/sqlite/calendar-events.js +7 -3
  130. package/dist/store/sqlite/calendar-forget.js +3 -0
  131. package/dist/store/sqlite/calendar.d.ts +21 -1
  132. package/dist/store/sqlite/calendar.js +27 -7
  133. package/dist/store/sqlite/chat-rekey.js +7 -0
  134. package/dist/store/sqlite/chats.d.ts +3 -1
  135. package/dist/store/sqlite/chats.js +15 -1
  136. package/dist/store/sqlite/crm-rows.d.ts +44 -0
  137. package/dist/store/sqlite/crm-rows.js +195 -0
  138. package/dist/store/sqlite/crm-settings.d.ts +28 -0
  139. package/dist/store/sqlite/crm-settings.js +80 -0
  140. package/dist/store/sqlite/crm.d.ts +42 -11
  141. package/dist/store/sqlite/crm.js +402 -196
  142. package/dist/store/sqlite/deals.d.ts +4 -8
  143. package/dist/store/sqlite/deals.js +8 -5
  144. package/dist/store/sqlite/document-transfer/snapshot.js +2 -2
  145. package/dist/store/sqlite/emails.js +2 -0
  146. package/dist/store/sqlite/entity-types.d.ts +14 -9
  147. package/dist/store/sqlite/entity-types.js +4 -10
  148. package/dist/store/sqlite/evidence-signature.d.ts +114 -0
  149. package/dist/store/sqlite/evidence-signature.js +349 -0
  150. package/dist/store/sqlite/evidence-sources.d.ts +2 -1
  151. package/dist/store/sqlite/evidence-sources.js +7 -3
  152. package/dist/store/sqlite/facts.d.ts +7 -2
  153. package/dist/store/sqlite/facts.js +21 -5
  154. package/dist/store/sqlite/finance.d.ts +18 -105
  155. package/dist/store/sqlite/finance.js +100 -219
  156. package/dist/store/sqlite/involvement-queue.js +4 -3
  157. package/dist/store/sqlite/knowledge.d.ts +14 -4
  158. package/dist/store/sqlite/knowledge.js +108 -102
  159. package/dist/store/sqlite/labelled.d.ts +3 -0
  160. package/dist/store/sqlite/labelled.js +11 -0
  161. package/dist/store/sqlite/link-kinds.d.ts +4 -3
  162. package/dist/store/sqlite/link-kinds.js +6 -2
  163. package/dist/store/sqlite/manifest.js +7 -0
  164. package/dist/store/sqlite/memories.d.ts +24 -10
  165. package/dist/store/sqlite/memories.js +73 -19
  166. package/dist/store/sqlite/messages.js +2 -0
  167. package/dist/store/sqlite/migrations.generated.js +134 -0
  168. package/dist/store/sqlite/money-lines.d.ts +48 -0
  169. package/dist/store/sqlite/money-lines.js +76 -0
  170. package/dist/store/sqlite/money-transactions.d.ts +132 -0
  171. package/dist/store/sqlite/money-transactions.js +295 -0
  172. package/dist/store/sqlite/notes.d.ts +14 -4
  173. package/dist/store/sqlite/notes.js +43 -31
  174. package/dist/store/sqlite/orders.d.ts +36 -6
  175. package/dist/store/sqlite/orders.js +126 -46
  176. package/dist/store/sqlite/organizations.d.ts +8 -0
  177. package/dist/store/sqlite/organizations.js +14 -0
  178. package/dist/store/sqlite/payment-facts.js +1 -1
  179. package/dist/store/sqlite/person-preparation.d.ts +1 -1
  180. package/dist/store/sqlite/person-preparation.js +3 -2
  181. package/dist/store/sqlite/private-people.js +2 -0
  182. package/dist/store/sqlite/products.d.ts +78 -0
  183. package/dist/store/sqlite/products.js +131 -0
  184. package/dist/store/sqlite/project-transfer/records.js +39 -3
  185. package/dist/store/sqlite/project-transfer/snapshot.d.ts +4 -1
  186. package/dist/store/sqlite/project-transfer/snapshot.js +11 -3
  187. package/dist/store/sqlite/proposed-actions.d.ts +1 -1
  188. package/dist/store/sqlite/proposed-actions.js +24 -7
  189. package/dist/store/sqlite/providers.d.ts +0 -4
  190. package/dist/store/sqlite/providers.js +20 -2
  191. package/dist/store/sqlite/record-matching.d.ts +80 -0
  192. package/dist/store/sqlite/record-matching.js +264 -0
  193. package/dist/store/sqlite/record-projection.d.ts +89 -0
  194. package/dist/store/sqlite/record-projection.js +50 -0
  195. package/dist/store/sqlite/record-projectors-direct.d.ts +17 -0
  196. package/dist/store/sqlite/record-projectors-direct.js +125 -0
  197. package/dist/store/sqlite/record-projectors-money.d.ts +26 -0
  198. package/dist/store/sqlite/record-projectors-money.js +214 -0
  199. package/dist/store/sqlite/record-projectors-phone.d.ts +28 -0
  200. package/dist/store/sqlite/record-projectors-phone.js +212 -0
  201. package/dist/store/sqlite/record-projectors.d.ts +3 -44
  202. package/dist/store/sqlite/record-projectors.js +7 -67
  203. package/dist/store/sqlite/record-relations.d.ts +24 -0
  204. package/dist/store/sqlite/record-relations.js +92 -0
  205. package/dist/store/sqlite/record-remap.d.ts +12 -0
  206. package/dist/store/sqlite/record-remap.js +92 -0
  207. package/dist/store/sqlite/record-run.d.ts +71 -0
  208. package/dist/store/sqlite/record-run.js +179 -0
  209. package/dist/store/sqlite/record-settling.d.ts +9 -0
  210. package/dist/store/sqlite/record-settling.js +74 -0
  211. package/dist/store/sqlite/record-stamps.d.ts +13 -0
  212. package/dist/store/sqlite/record-stamps.js +30 -0
  213. package/dist/store/sqlite/record-writes.d.ts +43 -0
  214. package/dist/store/sqlite/record-writes.js +307 -0
  215. package/dist/store/sqlite/records.d.ts +52 -42
  216. package/dist/store/sqlite/records.js +123 -353
  217. package/dist/store/sqlite/ref-summaries.d.ts +6 -5
  218. package/dist/store/sqlite/ref-summaries.js +60 -8
  219. package/dist/store/sqlite/refunds.d.ts +31 -0
  220. package/dist/store/sqlite/refunds.js +112 -0
  221. package/dist/store/sqlite/relation-list.d.ts +43 -0
  222. package/dist/store/sqlite/relation-list.js +133 -0
  223. package/dist/store/sqlite/relation-proposals.d.ts +28 -6
  224. package/dist/store/sqlite/relation-proposals.js +134 -10
  225. package/dist/store/sqlite/relation-reads.d.ts +8 -0
  226. package/dist/store/sqlite/relation-reads.js +7 -0
  227. package/dist/store/sqlite/relation-roles.d.ts +26 -0
  228. package/dist/store/sqlite/relation-roles.js +91 -0
  229. package/dist/store/sqlite/reported-relations.d.ts +63 -0
  230. package/dist/store/sqlite/reported-relations.js +132 -0
  231. package/dist/store/sqlite/reviewed.d.ts +109 -0
  232. package/dist/store/sqlite/reviewed.js +173 -0
  233. package/dist/store/sqlite/schema/link-revisions.d.ts +136 -0
  234. package/dist/store/sqlite/schema/link-revisions.js +11 -0
  235. package/dist/store/sqlite/schema/links.d.ts +360 -0
  236. package/dist/store/sqlite/schema/links.js +32 -0
  237. package/dist/store/sqlite/schema.d.ts +2769 -306
  238. package/dist/store/sqlite/schema.js +258 -25
  239. package/dist/store/sqlite/source-review-marks.d.ts +54 -0
  240. package/dist/store/sqlite/source-review-marks.js +143 -0
  241. package/dist/store/sqlite/source-review.d.ts +54 -0
  242. package/dist/store/sqlite/source-review.js +221 -0
  243. package/dist/store/sqlite/stage-amounts.d.ts +14 -0
  244. package/dist/store/sqlite/stage-amounts.js +23 -0
  245. package/dist/store/sqlite/subscriptions.d.ts +135 -0
  246. package/dist/store/sqlite/subscriptions.js +294 -0
  247. package/dist/store/sqlite/text-input.d.ts +3 -0
  248. package/dist/store/sqlite/text-input.js +13 -0
  249. package/dist/store/sqlite/things.js +2 -9
  250. package/dist/store/sqlite/transaction.d.ts +15 -0
  251. package/dist/store/sqlite/transaction.js +57 -0
  252. package/dist/store/sqlite/wallets.d.ts +88 -0
  253. package/dist/store/sqlite/wallets.js +143 -0
  254. package/dist/store/store-errors.d.ts +1 -0
  255. package/dist/store/store-errors.js +45 -0
  256. package/dist/store/store.d.ts +19 -1
  257. package/dist/store/store.js +35 -6
  258. package/package.json +6 -3
  259. package/schemas/examples/records-business.jsonl +11 -0
  260. package/schemas/records-envelope.v1.schema.json +1160 -5
@@ -0,0 +1,256 @@
1
+ import { lookup as dnsLookup } from "node:dns/promises";
2
+ import { request as httpRequest } from "node:http";
3
+ import { request as httpsRequest } from "node:https";
4
+ import { isIP } from "node:net";
5
+ import { CliError, isCliError } from "@wirecat/cli-base";
6
+ import { importEngine } from "../attachments/extract.js";
7
+ import { MAX_FILE_BYTES } from "../attachments/limits.js";
8
+ import { isGoogleDocumentHost } from "../domain/google-documents.js";
9
+ import { timeLimit } from "../http/time-limit.js";
10
+ import { readWithRegistry } from "../readers/registry.js";
11
+ import { isPublicAddress } from "./addresses.js";
12
+ export const PAGE_LIMITS = { maxBytes: MAX_FILE_BYTES, timeoutMs: 30_000, redirects: 5 };
13
+ /** Names the tool, never the owner. */
14
+ export const PAGE_USER_AGENT = "Mozilla/5.0 (compatible; WireCat)";
15
+ const HEADERS = {
16
+ "user-agent": PAGE_USER_AGENT,
17
+ accept: "text/html,application/xhtml+xml,application/pdf;q=0.9,text/plain;q=0.9,*/*;q=0.5",
18
+ "accept-encoding": "identity",
19
+ };
20
+ const REDIRECTS = new Set([301, 302, 303, 307, 308]);
21
+ const refused = (message) => new CliError("validation_error", message, { reason: "source.url-refused" });
22
+ /** The address checked for its scheme and login: what every hop is checked by. */
23
+ const pageUrl = (address, base) => {
24
+ let url;
25
+ try {
26
+ url = new URL(address, base);
27
+ }
28
+ catch {
29
+ throw refused("the link is not an address");
30
+ }
31
+ if (url.protocol !== "http:" && url.protocol !== "https:")
32
+ throw refused(`only http and https pages are read, not ${url.protocol.replace(/:$/, "")}`);
33
+ if (url.username || url.password)
34
+ throw refused("a link with a user name or password in it is not read");
35
+ return url;
36
+ };
37
+ const systemLookup = async (hostname) => (await dnsLookup(hostname, { all: true, verbatim: true })).map(({ address, family }) => ({
38
+ address,
39
+ family: family === 6 ? 6 : 4,
40
+ }));
41
+ /** Every address the name has must be public: the first is the one connected to. */
42
+ const checkedAddress = async (url, lookup) => {
43
+ const host = url.hostname.replace(/^\[(.*)\]$/, "$1");
44
+ const family = isIP(host);
45
+ let found;
46
+ try {
47
+ found = family ? [{ address: host, family: family === 6 ? 6 : 4 }] : await lookup(host);
48
+ }
49
+ catch {
50
+ throw new CliError("network_error", `${url.hostname} could not be found`, {
51
+ reason: "source.url-unreachable",
52
+ retryable: true,
53
+ });
54
+ }
55
+ const [first] = found;
56
+ if (!first || found.some(({ address }) => !isPublicAddress(address)))
57
+ throw refused(`${url.hostname} is not on the public internet, so it is not read`);
58
+ return first;
59
+ };
60
+ const pinnedTo = ({ address, family }) => (_hostname, options, callback) => {
61
+ if (options.all)
62
+ callback(null, [{ address, family }]);
63
+ else
64
+ callback(null, address, family);
65
+ };
66
+ const headerOf = (message) => (name) => {
67
+ const value = message.headers[name.toLowerCase()];
68
+ return Array.isArray(value) ? value.join(", ") : (value ?? null);
69
+ };
70
+ /** node's own client, so the connection goes to the checked address and the TLS name stays the page's. */
71
+ export const nodeTransport = ({ url, address, headers, signal }) => new Promise((resolve, reject) => {
72
+ const send = url.protocol === "https:" ? httpsRequest : httpRequest;
73
+ const request = send(url, { method: "GET", headers, signal, agent: false, lookup: pinnedTo(address) }, (message) => resolve({
74
+ status: message.statusCode ?? 0,
75
+ header: headerOf(message),
76
+ body: message,
77
+ cancel: () => message.destroy(),
78
+ }));
79
+ request.on("error", reject);
80
+ request.end();
81
+ });
82
+ const tooLarge = (limit) => new CliError("validation_error", `the page is larger than ${Math.round(limit / 1024 / 1024)} MiB`, {
83
+ reason: "source.too-large",
84
+ });
85
+ const readBody = async (response, limit) => {
86
+ const declared = Number(response.header("content-length"));
87
+ if (Number.isFinite(declared) && declared > limit) {
88
+ response.cancel();
89
+ throw tooLarge(limit);
90
+ }
91
+ const chunks = [];
92
+ let size = 0;
93
+ for await (const chunk of response.body) {
94
+ size += chunk.byteLength;
95
+ if (size > limit) {
96
+ response.cancel();
97
+ throw tooLarge(limit);
98
+ }
99
+ chunks.push(chunk);
100
+ }
101
+ const bytes = new Uint8Array(size);
102
+ let at = 0;
103
+ for (const chunk of chunks) {
104
+ bytes.set(chunk, at);
105
+ at += chunk.byteLength;
106
+ }
107
+ return bytes;
108
+ };
109
+ const needsSignIn = (url) => new CliError("authentication_error", `${url.hostname} asks for a sign-in: read a private Google document through Drive`, {
110
+ reason: "source.needs-sign-in",
111
+ });
112
+ /**
113
+ * Google's sign-in page, as a private document may answer with 200: a form that posts to accounts.google.com's sign-in.
114
+ * Only both markers together count, so a page that merely links to a sign-in is read.
115
+ */
116
+ const isSignInPage = (bytes, contentType) => {
117
+ if (!contentType?.toLowerCase().includes("html"))
118
+ return false;
119
+ const head = new TextDecoder().decode(bytes.subarray(0, 256 * 1024));
120
+ return /<form[^>]+action="https:\/\/accounts\.google\.com\/[^"]*/i.test(head) && /ServiceLogin|\/signin\//.test(head);
121
+ };
122
+ const nameOf = (url) => {
123
+ const raw = url.pathname.split("/").pop() ?? "";
124
+ let last = raw;
125
+ try {
126
+ last = decodeURIComponent(raw);
127
+ }
128
+ catch { }
129
+ return last || null;
130
+ };
131
+ const readPage = async (bytes, url, contentType, load, signal) => {
132
+ const mime = contentType?.split(";")[0]?.trim().toLowerCase() || null;
133
+ const found = await readWithRegistry(bytes, { kind: "file", name: nameOf(url), mime, path: url.pathname }, { load, signal });
134
+ switch (found.status) {
135
+ case "extracted":
136
+ if (!found.text.trim())
137
+ throw new CliError("validation_error", "the page holds no text to keep", { reason: "source.no-text" });
138
+ return {
139
+ text: found.text,
140
+ extractor: found.extractor,
141
+ read: "extracted",
142
+ truncated: found.truncated ?? false,
143
+ ...(found.metadata ? { metadata: found.metadata } : {}),
144
+ ...(found.sections ? { sections: found.sections } : {}),
145
+ };
146
+ case "needs-agent":
147
+ return { text: "", extractor: found.extractor ?? null, read: "no-text", truncated: false };
148
+ case "unsupported":
149
+ throw new CliError("validation_error", `no reader takes ${mime ?? "this kind of page"}`, {
150
+ reason: "source.unsupported",
151
+ });
152
+ case "unreadable":
153
+ throw new CliError("validation_error", `the ${found.extractor} reader could not read the page`, {
154
+ reason: "source.unreadable",
155
+ });
156
+ case "engine-missing":
157
+ throw new CliError("configuration_error", `reading this page needs ${found.engine}, which is not installed`, {
158
+ reason: "source.engine-missing",
159
+ });
160
+ case "too-large":
161
+ throw new CliError("validation_error", "the page is larger than its reader reads", { reason: "source.too-large" });
162
+ }
163
+ };
164
+ /**
165
+ * One page read from the internet, for a source the owner adds by hand: http(s) only, every hop's address checked to
166
+ * be public and connected to as checked, at most `redirects` redirects followed by hand, no cookies, no credentials,
167
+ * and the reader chosen by the content type. Errors name the host only: an address may carry a token.
168
+ */
169
+ export const fetchPage = async (address, options = {}) => {
170
+ const limits = { ...PAGE_LIMITS, ...options.limits };
171
+ const { lookup = systemLookup, transport = nodeTransport, load = importEngine } = options;
172
+ const deadline = timeLimit(limits.timeoutMs);
173
+ const signal = options.signal ? AbortSignal.any([options.signal, deadline.signal]) : deadline.signal;
174
+ const timedOut = () => new CliError("timeout", `the page did not arrive within ${Math.round(limits.timeoutMs / 1000)} s`, {
175
+ reason: "source.url-timeout",
176
+ retryable: true,
177
+ });
178
+ const cancelled = new Promise((_, reject) => {
179
+ const stop = () => reject(signal.reason);
180
+ if (signal.aborted)
181
+ stop();
182
+ else
183
+ signal.addEventListener("abort", stop, { once: true });
184
+ });
185
+ cancelled.catch(() => { });
186
+ let url = pageUrl(address);
187
+ const requested = url.href;
188
+ const google = isGoogleDocumentHost(url.hostname);
189
+ try {
190
+ for (let hop = 0;; hop++) {
191
+ const pinned = await Promise.race([checkedAddress(url, lookup), cancelled]);
192
+ const response = await Promise.race([transport({ url, address: pinned, headers: HEADERS, signal }), cancelled]);
193
+ const location = response.header("location");
194
+ if (REDIRECTS.has(response.status) && location) {
195
+ response.cancel();
196
+ const next = pageUrl(location, url);
197
+ if (google && next.hostname === "accounts.google.com")
198
+ throw needsSignIn(url);
199
+ if (url.protocol === "https:" && next.protocol === "http:")
200
+ throw new CliError("validation_error", `${url.hostname} sent the request on from https to plain http`, {
201
+ reason: "source.url-refused",
202
+ kind: "downgrade",
203
+ });
204
+ if (hop >= limits.redirects)
205
+ throw new CliError("provider_error", `${url.hostname} sent the request on more than ${limits.redirects} times`, {
206
+ reason: "source.url-redirects",
207
+ });
208
+ url = next;
209
+ continue;
210
+ }
211
+ if (google && (response.status === 401 || response.status === 403)) {
212
+ response.cancel();
213
+ throw needsSignIn(url);
214
+ }
215
+ if (response.status < 200 || response.status > 299) {
216
+ response.cancel();
217
+ throw new CliError("provider_error", `${url.hostname} answered HTTP ${response.status}`, {
218
+ reason: "source.url-status",
219
+ status: response.status,
220
+ retryable: response.status >= 500 || response.status === 429,
221
+ });
222
+ }
223
+ const contentType = response.header("content-type");
224
+ const bytes = await Promise.race([readBody(response, limits.maxBytes), cancelled]);
225
+ if (google && isSignInPage(bytes, contentType))
226
+ throw needsSignIn(url);
227
+ const page = await Promise.race([readPage(bytes, url, contentType, load, signal), cancelled]);
228
+ return {
229
+ requestedUrl: requested,
230
+ finalUrl: url.href,
231
+ status: response.status,
232
+ contentType,
233
+ bytes: bytes.byteLength,
234
+ ...page,
235
+ };
236
+ }
237
+ }
238
+ catch (error) {
239
+ if (deadline.signal.aborted && !(isCliError(error) && error.code !== "cancelled"))
240
+ throw timedOut();
241
+ if (isCliError(error))
242
+ throw error;
243
+ if (options.signal?.aborted)
244
+ throw new CliError("cancelled", "reading the page was cancelled");
245
+ // The cause's code only: a fetch error's message may quote the address.
246
+ const cause = error.code ??
247
+ error.cause?.code;
248
+ throw new CliError("network_error", `${url.hostname} could not be reached${typeof cause === "string" ? ` (${cause})` : ""}`, {
249
+ reason: "source.url-unreachable",
250
+ retryable: true,
251
+ });
252
+ }
253
+ finally {
254
+ deadline.clear();
255
+ }
256
+ };
package/dist/index.d.ts CHANGED
@@ -1,7 +1,8 @@
1
+ export { CATALOG_KINDS, type CatalogKind, CONTRACT_KINDS, CONTRACT_STATUSES, type ContractKind, type ContractStatus, type Interval, intervalOf, intervalText, ORDER_DIRECTIONS, type OrderDirection, PERIOD_UNITS, type PeriodUnit, SUBSCRIPTION_STATUSES, type SubscriptionStatus, TRANSACTION_STATUSES, type TransactionStatus, WALLET_KINDS, type WalletKind, } from "./domain/business.js";
1
2
  export { bareCheck, type CheckWords, checkWords } from "./domain/checks.js";
2
3
  export type { CounterField, CounterObservation, CounterObservations, CounterState } from "./domain/counters.js";
3
4
  export { COUNTER_FIELDS, counterValue, observedCounters } from "./domain/counters.js";
4
- export { CRM_KINDS, type CrmField, type CrmItem, type CrmKind, type CrmOrganization, type CrmPerson, type CrmPipeline, type CrmRecords, type CrmStage, type CrmValue, isItemKind, } from "./domain/crm.js";
5
+ export { CRM_KINDS, type CrmDepartment, type CrmField, type CrmItem, type CrmKind, type CrmOrganization, type CrmPerson, type CrmPipeline, type CrmRecords, type CrmStage, type CrmUser, type CrmValue, isItemKind, } from "./domain/crm.js";
5
6
  export { DEAL_KINDS, DEAL_ROLES, DEAL_STATUSES, type DealKind, type DealRole, type DealStatus, STAGE_OUTCOMES, type StageOutcome, } from "./domain/deals.js";
6
7
  export { FINANCE_REVIEWS, type FinanceReview, INVOICE_DIRECTIONS, INVOICE_STATUSES, type InvoiceDirection, type InvoiceStatus, MONEY_DIRECTIONS, type MoneyDirection, } from "./domain/finance.js";
7
8
  export { type FormattedText, type HtmlFormatting, type MarkdownFormatting, type TextSpan, validateFormattedText, } from "./domain/formatting.js";
@@ -10,16 +11,18 @@ export { type Markup, parseMarkdown } from "./domain/markdown.js";
10
11
  export { parseMarkdownSpans } from "./domain/markdown-spans.js";
11
12
  export type { MessageLink, MessagePermalink } from "./domain/message-link.js";
12
13
  export type * from "./domain/models.js";
13
- export { CURRENCY_SCALES, currencyOf, type Money, minorUnits, moneyLabel, moneyOf, } from "./domain/money.js";
14
+ export { CURRENCY_SCALES, currencyOf, formatDecimal, type Money, minorUnits, moneyLabel, moneyOf, signedMinorUnits, } from "./domain/money.js";
14
15
  export { ORDER_PURPOSES, ORDER_STATUSES, type OrderPurpose, type OrderStatus, } from "./domain/orders.js";
15
16
  export { countedPoll } from "./domain/polls.js";
16
- export { CRM_OPENS, FOLDER_PROVIDERS, isFolderProvider, isKind, KINDS, type Kind, kindIn, kindOf, PROVIDERS, type ProviderEntry, providerNamed, providers, UNKNOWN_PROVIDER, useProviders, } from "./domain/providers.js";
17
+ export { ADDED_ACCOUNT, ADDED_PROVIDER, CRM_OPENS, FOLDER_PROVIDERS, holdsKind, isFolderProvider, isKind, KINDS, type Kind, kindIn, kindOf, kindsIn, PROVIDERS, type ProviderEntry, providerNamed, providers, UNKNOWN_PROVIDER, useProviders, } from "./domain/providers.js";
17
18
  export type { RankingGraphEvidence, RankingGraphLink } from "./domain/rankings-graph.js";
18
19
  export type { RankingComponent, RankingInput, RankingMeasure, RankingOptions, RankingTarget, RankingWeights, ScorePreset, } from "./domain/rankings-options.js";
19
20
  export { rankingOptions } from "./domain/rankings-options.js";
20
- export { type EnvelopeRecord, type EnvelopeSource, envelopeOfJsonl, type IngestError, RECORD_ENTITY_TYPES, RECORD_OPERATIONS, RECORDS_ENVELOPE_SCHEMA, RECORDS_SCHEMA_VERSION, type RecordEntityType, type RecordOperation, type RecordRelation, type RecordsEnvelope, } from "./domain/records.js";
21
+ export { type EnvelopeOptions, type EnvelopeRecord, type EnvelopeSource, envelopeOfJsonl, envelopeOfText, type IngestError, RECORD_ENTITY_TYPES, RECORD_OPERATIONS, RECORDS_ENVELOPE_SCHEMA, RECORDS_SCHEMA_VERSION, type RecordEntityType, type RecordOperation, type RecordRelation, type RecordsEnvelope, } from "./domain/records.js";
21
22
  export { canonicalReference, formatReference, looksLikeReference, parseReference, REF_KINDS, type Reference, type RefKindName, type RefKindSpec, } from "./domain/references.js";
23
+ export { inverseOf, isUsable, ORGANIZATION_ROLES, PROJECT_ROLES, RELATION_KINDS, RELATIONS, type RelationKind, ROLE_LISTS, type RoleList, rolesOf, STANDINGS, type Standing, standingOf, usableLink, } from "./domain/relations.js";
22
24
  export { normalizeTag, TAG_TYPES, type TagType } from "./domain/tags.js";
25
+ export { envelopeOfVcard, isVcard, type VcardIssue, type VcardOptions } from "./domain/vcard.js";
23
26
  export { type AppErrors, DETAILS as CORE_DETAILS, failureContext, REASONS as CORE_REASONS } from "./errors/reasons.js";
24
27
  export { canonicalMeetingReference, formatMeetingReference, type MeetingReference, parseMeetingReference, } from "./meetings/index.js";
25
28
  export type { CheckRow, Finding, Moderator } from "./moderation/check.js";
package/dist/index.js CHANGED
@@ -1,3 +1,4 @@
1
+ export { CATALOG_KINDS, CONTRACT_KINDS, CONTRACT_STATUSES, intervalOf, intervalText, ORDER_DIRECTIONS, PERIOD_UNITS, SUBSCRIPTION_STATUSES, TRANSACTION_STATUSES, WALLET_KINDS, } from "./domain/business.js";
1
2
  export { bareCheck, checkWords } from "./domain/checks.js";
2
3
  export { COUNTER_FIELDS, counterValue, observedCounters } from "./domain/counters.js";
3
4
  export { CRM_KINDS, isItemKind, } from "./domain/crm.js";
@@ -7,14 +8,16 @@ export { validateFormattedText, } from "./domain/formatting.js";
7
8
  export { formatLocator, isLocator, parseLocator } from "./domain/locator.js";
8
9
  export { parseMarkdown } from "./domain/markdown.js";
9
10
  export { parseMarkdownSpans } from "./domain/markdown-spans.js";
10
- export { CURRENCY_SCALES, currencyOf, minorUnits, moneyLabel, moneyOf, } from "./domain/money.js";
11
+ export { CURRENCY_SCALES, currencyOf, formatDecimal, minorUnits, moneyLabel, moneyOf, signedMinorUnits, } from "./domain/money.js";
11
12
  export { ORDER_PURPOSES, ORDER_STATUSES, } from "./domain/orders.js";
12
13
  export { countedPoll } from "./domain/polls.js";
13
- export { CRM_OPENS, FOLDER_PROVIDERS, isFolderProvider, isKind, KINDS, kindIn, kindOf, PROVIDERS, providerNamed, providers, UNKNOWN_PROVIDER, useProviders, } from "./domain/providers.js";
14
+ export { ADDED_ACCOUNT, ADDED_PROVIDER, CRM_OPENS, FOLDER_PROVIDERS, holdsKind, isFolderProvider, isKind, KINDS, kindIn, kindOf, kindsIn, PROVIDERS, providerNamed, providers, UNKNOWN_PROVIDER, useProviders, } from "./domain/providers.js";
14
15
  export { rankingOptions } from "./domain/rankings-options.js";
15
- export { envelopeOfJsonl, RECORD_ENTITY_TYPES, RECORD_OPERATIONS, RECORDS_ENVELOPE_SCHEMA, RECORDS_SCHEMA_VERSION, } from "./domain/records.js";
16
+ export { envelopeOfJsonl, envelopeOfText, RECORD_ENTITY_TYPES, RECORD_OPERATIONS, RECORDS_ENVELOPE_SCHEMA, RECORDS_SCHEMA_VERSION, } from "./domain/records.js";
16
17
  export { canonicalReference, formatReference, looksLikeReference, parseReference, REF_KINDS, } from "./domain/references.js";
18
+ export { inverseOf, isUsable, ORGANIZATION_ROLES, PROJECT_ROLES, RELATION_KINDS, RELATIONS, ROLE_LISTS, rolesOf, STANDINGS, standingOf, usableLink, } from "./domain/relations.js";
17
19
  export { normalizeTag, TAG_TYPES } from "./domain/tags.js";
20
+ export { envelopeOfVcard, isVcard } from "./domain/vcard.js";
18
21
  export { DETAILS as CORE_DETAILS, failureContext, REASONS as CORE_REASONS } from "./errors/reasons.js";
19
22
  export { canonicalMeetingReference, formatMeetingReference, parseMeetingReference, } from "./meetings/index.js";
20
23
  export { act, judge } from "./moderation/check.js";
@@ -19,7 +19,7 @@ import { parseDuration } from "../../domain/duration.js";
19
19
  import { formatReference } from "../../domain/references.js";
20
20
  import { AGENDA_DEFAULTS } from "../../services/agenda.js";
21
21
  import { REVIEW_DAYS, reviewStart } from "../../services/inbox.js";
22
- import { readPastMark } from "../marks.js";
22
+ import { cursorOf, findingsKeyOf, readPastMark } from "../marks.js";
23
23
  import { BULK_TRIAGE_DEFAULTS } from "../newsletter.js";
24
24
  import { hitText } from "../read.js";
25
25
  import { OWED_DAYS, REVIEW_THREADS, reviewMail } from "../review.js";
@@ -146,6 +146,7 @@ const reviewAnswer = (found, mailbox, fresh, step) => {
146
146
  bulk: (message.marks?.bulk ?? false) || message.excerptOnly === true,
147
147
  ...(message.excerptOnly ? { excerpt_only: true } : {}),
148
148
  ...(message.partialExcerpt ? { partial: true } : {}),
149
+ ...(message.through ? { cursor: message.through.cursor, findings_key: message.through.findingsKey } : {}),
149
150
  list_id: message.marks?.listId ?? null,
150
151
  rule_id: message.marks?.ruleId ?? null,
151
152
  ...(message.marks
@@ -170,15 +171,27 @@ const holderReview = async (command, mail, holder, query) => {
170
171
  if (typedQuery(query).trim() || unanswered !== undefined || waiting !== undefined)
171
172
  throw new CliError("validation_error", "--holder reads past its own mark — not with a query, --unanswered or --waiting");
172
173
  const triage = mail.bulkTriage?.(command) ?? BULK_TRIAGE_DEFAULTS;
174
+ const now = Date.now();
173
175
  const { read, mailbox, marks } = await mail.read(command, async (store, mailbox) => {
174
- const read = await readPastMark(store, mailbox, holder, { triage });
176
+ const read = await readPastMark(store, mailbox, holder, { triage, now });
175
177
  const ids = [...read.emails, ...read.excerpts.map(({ email }) => email)].map((one) => one.id);
176
178
  const account = ids.length ? await store.accounts.storedAccount(mailbox) : undefined;
177
179
  const marks = account ? await store.mail.emailMarks(account.id, ids) : new Map();
178
180
  return { read, mailbox, marks };
179
181
  });
182
+ const markedThrough = read.mark?.throughId ?? 0;
183
+ const heldThrough = [...read.emails, ...read.excerpts.map(({ email }) => email)].reduce((most, { storeId }) => (storeId <= markedThrough ? Math.max(most, storeId) : most), 0);
184
+ // A held email is older than the mark, and a cursor never moves the mark back.
185
+ const through = (id) => {
186
+ const held = id <= markedThrough;
187
+ const at = held ? markedThrough : id;
188
+ return {
189
+ cursor: cursorOf(at, now),
190
+ findingsKey: findingsKeyOf(holder, at, read.mark?.resets ?? 0, held ? heldThrough : undefined),
191
+ };
192
+ };
180
193
  // An agent reads this: earlier mail and signatures stay out of its text; the fingerprint is over the stored body.
181
- const emails = [
194
+ const listed = [
182
195
  ...read.emails.map((email) => ({ ...email, text: mailOwnText(email.text) })),
183
196
  ...read.excerpts.map(({ email, excerpt, partial }) => {
184
197
  const subject = email.email?.subject;
@@ -190,6 +203,7 @@ const holderReview = async (command, mail, holder, query) => {
190
203
  };
191
204
  }),
192
205
  ];
206
+ const emails = listed.map(({ storeId, ...email }) => ({ ...email, through: through(storeId) }));
193
207
  const chats = new Map();
194
208
  for (const email of emails) {
195
209
  const chat = chats.get(email.chatId) ?? {
@@ -203,10 +217,10 @@ const holderReview = async (command, mail, holder, query) => {
203
217
  chat.messages.push(mark ? { ...email, marks: mark } : email);
204
218
  chats.set(email.chatId, chat);
205
219
  }
206
- const now = new Date().toISOString();
220
+ const until = new Date(now).toISOString();
207
221
  const found = {
208
- since: read.mark?.throughAt ? new Date(read.mark.throughAt).toISOString() : now,
209
- until: now,
222
+ since: read.mark?.throughAt ? new Date(read.mark.throughAt).toISOString() : until,
223
+ until,
210
224
  complete: !read.more,
211
225
  chats: [...chats.values()],
212
226
  skipped: [],
@@ -9,7 +9,7 @@ export { dropMissing, type Gone, tooManyGone } from "./gone.js";
9
9
  export { type AuthVerdicts, HEADER_FIELDS, headersOf, type MailHeaders, mailHeadersOf } from "./headers.js";
10
10
  export { type MailIdsInput, mailIds } from "./ids.js";
11
11
  export { decodedLabelName, decodeMailboxName, labelName, systemLabel } from "./labels.js";
12
- export { acknowledgeMark, advancePastSkipped, type BulkExcerpt, cursorOf, HOLD_PARTIAL_MS, HOLDER, MARK_BATCH, type MailMark, type MailWaiting, type MarkRead, type MarkRewind, mailWaiting, markOf, marksOf, type RewoundMark, readPastMark, rewindMark, type SkipReason, } from "./marks.js";
12
+ export { acknowledgeMark, advancePastSkipped, type BulkExcerpt, cursorOf, HOLD_PARTIAL_MS, HOLDER, MARK_BATCH, type MailMark, type MailWaiting, type MarkedHit, type MarkRead, type MarkRewind, mailWaiting, markOf, marksOf, type RewoundMark, readPastMark, rewindMark, type SkipReason, } from "./marks.js";
13
13
  export { BULK_TRIAGE_DEFAULTS, type BulkSorted, type BulkTriage, excerptOf, NEWSLETTER_DEFAULTS, NEWSLETTER_SENDERS, NEWSLETTER_WORDS, type NewsletterCues, newsletterSorter, ORDER_WORDS, } from "./newsletter.js";
14
14
  export { type MailTurn, mailTurn } from "./owed.js";
15
15
  export { type Address, htmlToText, looksLikeHtml, MAX_ATTACHMENTS, MAX_BODY_CHARS, type ParsedMail, parseMail, } from "./parse.js";
@@ -34,13 +34,18 @@ export declare const marksOf: (store: MessageStore, mailbox: AccountKey) => Prom
34
34
  export declare const cursorOf: (throughId: number, readAt: number) => string;
35
35
  /**
36
36
  * The findings key of one run: `<holder>:<through_id>`, and `-r<resets>` once the owner moved the mark back, so the
37
- * runs after a reset never reach a key a batch staged before it holds. The same review gives the same key: a retry
38
- * of one run stages nothing twice.
37
+ * runs after a reset never reach a key a batch staged before it holds. A batch that ends at the mark itself, held
38
+ * emails only, adds `-h<highest held id>`: the run that set the mark already holds the plain key. The same review
39
+ * gives the same key: a retry of one run stages nothing twice.
39
40
  */
40
- export declare const findingsKeyOf: (holder: string, throughId: number, resets: number) => string;
41
+ export declare const findingsKeyOf: (holder: string, throughId: number, resets: number, heldThrough?: number) => string;
41
42
  /** A bulk email that is not surely a newsletter: the holder gets its subject and first lines only. */
43
+ /** An email as a hit, with its store id: the order a mark counts by. */
44
+ export type MarkedHit = StoredHit & {
45
+ storeId: number;
46
+ };
42
47
  export interface BulkExcerpt {
43
- email: StoredHit;
48
+ email: MarkedHit;
44
49
  /** The first lines of its own text, without the subject. */
45
50
  excerpt: string;
46
51
  /** What kept it, or the newsletter signs too few to leave it out. */
@@ -50,7 +55,7 @@ export interface BulkExcerpt {
50
55
  }
51
56
  export interface MarkRead {
52
57
  /** The emails for the holder, oldest first; bulk, envelopes, drafts, suspicious senders and partial mail left out. */
53
- emails: StoredHit[];
58
+ emails: MarkedHit[];
54
59
  /** Bulk mail past the mark that is not surely a newsletter, oldest first; none when the triage gives no excerpts. */
55
60
  excerpts: BulkExcerpt[];
56
61
  /** What `acknowledge --cursor` takes once the holder is done with these. */
@@ -85,10 +85,11 @@ const verdict = (email, now) => {
85
85
  export const cursorOf = (throughId, readAt) => `${throughId}.${readAt}`;
86
86
  /**
87
87
  * The findings key of one run: `<holder>:<through_id>`, and `-r<resets>` once the owner moved the mark back, so the
88
- * runs after a reset never reach a key a batch staged before it holds. The same review gives the same key: a retry
89
- * of one run stages nothing twice.
88
+ * runs after a reset never reach a key a batch staged before it holds. A batch that ends at the mark itself, held
89
+ * emails only, adds `-h<highest held id>`: the run that set the mark already holds the plain key. The same review
90
+ * gives the same key: a retry of one run stages nothing twice.
90
91
  */
91
- export const findingsKeyOf = (holder, throughId, resets) => `${holder}:${throughId}${resets > 0 ? `-r${resets}` : ""}`;
92
+ export const findingsKeyOf = (holder, throughId, resets, heldThrough) => `${holder}:${throughId}${heldThrough === undefined ? "" : `-h${heldThrough}`}${resets > 0 ? `-r${resets}` : ""}`;
92
93
  const parseCursor = (cursor) => {
93
94
  const match = /^(\d+)\.(\d+)$/.exec(cursor.trim());
94
95
  if (!match)
@@ -106,7 +107,14 @@ export const readPastMark = async (store, mailbox, holder, options = {}) => {
106
107
  const one = sorted.get(id);
107
108
  return one ? [{ email: one.email, excerpt: one.excerpt, cues: one.cues, partial: one.partial }] : [];
108
109
  });
109
- const emails = await store.mail.emailHits(wanted.filter((id) => !sorted.has(id)));
110
+ const ids = wanted.filter((one) => !sorted.has(one));
111
+ const hits = await store.mail.emailHits(ids);
112
+ // emailHits keeps the ids' order and drops an email deleted since; only then is each one asked for alone.
113
+ const emails = hits.length === ids.length ? hits.map((hit, index) => ({ ...hit, storeId: ids[index] })) : [];
114
+ if (hits.length !== ids.length)
115
+ for (const id of ids)
116
+ for (const hit of await store.mail.emailHits([id]))
117
+ emails.push({ ...hit, storeId: id });
110
118
  return { emails, excerpts, ...read };
111
119
  };
112
120
  /**
@@ -132,7 +140,7 @@ const sortBulk = async (store, batch, triage) => {
132
140
  return { sorted, end: index };
133
141
  if (one.verdict === "excerpt")
134
142
  excerpts += 1;
135
- sorted.set(marked.id, { ...one, email, partial: marked.partial });
143
+ sorted.set(marked.id, { ...one, email: { ...email, storeId: marked.id }, partial: marked.partial });
136
144
  }
137
145
  return { sorted, end: batch.length };
138
146
  };
@@ -149,9 +157,9 @@ const examine = async (store, mailbox, holder, { now = Date.now(), limit = MARK_
149
157
  skipped: noneSkipped(),
150
158
  mark: saved,
151
159
  };
152
- const keyed = (throughId) => ({
160
+ const keyed = (throughId, heldThrough) => ({
153
161
  cursor: cursorOf(throughId, now),
154
- findingsKey: throughId > 0 ? findingsKeyOf(holder, throughId, saved?.resets ?? 0) : undefined,
162
+ findingsKey: throughId > 0 ? findingsKeyOf(holder, throughId, saved?.resets ?? 0, heldThrough) : undefined,
155
163
  });
156
164
  if (!account)
157
165
  return { ...empty, ...keyed(0) };
@@ -192,7 +200,7 @@ const examine = async (store, mailbox, holder, { now = Date.now(), limit = MARK_
192
200
  wanted: wanted.sort((a, b) => a - b),
193
201
  sorted: new Map([...sorted].filter(([, one]) => one.verdict === "excerpt")),
194
202
  oldestStoredAt,
195
- ...keyed(batch.at(-1)?.id ?? mark.throughId),
203
+ ...(batch.length > 0 ? keyed(batch.at(-1)?.id ?? mark.throughId) : keyed(mark.throughId, wanted.at(-1))),
196
204
  more: newer.length > batch.length,
197
205
  held,
198
206
  skipped,
@@ -23,6 +23,11 @@ export type MailHit = StoredHit & {
23
23
  marks?: EmailMarks;
24
24
  excerptOnly?: true;
25
25
  partialExcerpt?: true;
26
+ /** A holder's read: the cursor and findings key that end the batch at this email. */
27
+ through?: {
28
+ cursor: string;
29
+ findingsKey: string;
30
+ };
26
31
  };
27
32
  export interface MailReview extends Review {
28
33
  chats: (Omit<ReviewChat, "messages"> & {
@@ -9,5 +9,5 @@ export declare const calendarText: (text: string | null | undefined, { dropSecre
9
9
  dropSecretLines?: boolean;
10
10
  }) => string | null;
11
11
  /** The provider fields a calendar entry may keep in `metadata`: none of them can open a meeting. */
12
- export declare const ENTRY_METADATA_KEYS: readonly ["colorId", "guestsCanInviteOthers", "guestsCanModify", "guestsCanSeeOtherGuests", "hangoutLink", "locked", "privateCopy"];
12
+ export declare const ENTRY_METADATA_KEYS: readonly ["colorId", "guestsCanInviteOthers", "guestsCanModify", "guestsCanSeeOtherGuests", "hangoutLink", "locked", "privateCopy", "callDirection", "callSeconds", "callNumber"];
13
13
  export declare const entryMetadata: (metadata: Record<string, unknown> | null | undefined) => Record<string, unknown>;
@@ -42,6 +42,10 @@ export const ENTRY_METADATA_KEYS = [
42
42
  "hangoutLink",
43
43
  "locked",
44
44
  "privateCopy",
45
+ // A phone call's, from a records import: the entry's other columns have no place for them.
46
+ "callDirection",
47
+ "callSeconds",
48
+ "callNumber",
45
49
  ];
46
50
  export const entryMetadata = (metadata) => {
47
51
  const kept = {};
@@ -1,8 +1,8 @@
1
1
  import type { Event } from "./model.js";
2
2
  /** RFC 5545 PARTSTAT: a participant's answer, and the owner's own. */
3
3
  export type ParticipantResponse = "needs-action" | "accepted" | "tentative" | "declined" | "delegated";
4
- /** What kind of entry it is. Only `default` and `from-mail` are searched (requirements 3.4). */
5
- export type EntryEventType = "default" | "out-of-office" | "focus" | "working-location" | "birthday" | "from-mail";
4
+ /** What kind of entry it is. `default`, `from-mail` and `call` are searched (requirements 3.4); `call` is a phone's. */
5
+ export type EntryEventType = "default" | "out-of-office" | "focus" | "working-location" | "birthday" | "from-mail" | "call";
6
6
  /** RFC 5545 TRANSP. */
7
7
  export type EntryTransparency = "opaque" | "transparent";
8
8
  /** RFC 5545 CLASS, plus `default`: the calendar's own setting. */
@@ -30,7 +30,11 @@ export interface ListContext {
30
30
  */
31
31
  export interface ListedAccount extends AccountKey {
32
32
  kind: Kind | undefined;
33
+ /** Only when it holds more than `kind`: a phone account holds messages and events. */
34
+ kinds?: readonly Kind[];
33
35
  }
36
+ /** Whether a listed account holds `kind`. */
37
+ export declare const listedHolds: (account: Pick<ListedAccount, "kind" | "kinds">, kind: Kind) => boolean;
34
38
  /** One entry of the list as written, a group's member included, and the accounts it named. */
35
39
  export interface ListedEntry {
36
40
  entry: string;
@@ -1,5 +1,5 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
- import { INTERNAL_NOTES, isDocumentAccountProvider, isFolderProvider, isKind, kindIn, kindOf, providerNamed, providers as registered, UNKNOWN_PROVIDER, } from "../domain/providers.js";
2
+ import { ADDED_PROVIDER, INTERNAL_NOTES, isDocumentAccountProvider, isFolderProvider, isKind, kindIn, kindOf, kindsIn, providerNamed, providers as registered, UNKNOWN_PROVIDER, } from "../domain/providers.js";
3
3
  import { isBotProvider } from "./query.js";
4
4
  /** Store-wide: every profile, tg, MAX and memo reads the same groups. */
5
5
  export const ACCOUNT_GROUPS = "accountGroups";
@@ -25,12 +25,18 @@ export const groupMembers = (value) => itemsOf(value).map((item) => item.toLower
25
25
  ? fail(`"${item}" names no account after the colon`)
26
26
  : item);
27
27
  const describe = (accounts) => accounts.map(({ provider, account, name }) => `${provider}:${account}${name ? ` (${name})` : ""}`).join(", ");
28
+ /** Whether a listed account holds `kind`. */
29
+ export const listedHolds = (account, kind) => (account.kinds ?? (account.kind === undefined ? [] : [account.kind])).includes(kind);
28
30
  /** The app running knows its own provider is a messenger, entry or not. */
29
31
  const kindHere = (provider, running) => provider === running.provider ? kindOf(provider) : kindIn(provider);
32
+ const kindsOfHere = (provider, running) => {
33
+ const kinds = kindsIn(provider);
34
+ return { kind: kindHere(provider, running), ...(kinds.length > 1 ? { kinds } : {}) };
35
+ };
30
36
  const heldOf = (stored, running) => [
31
37
  ...stored
32
38
  .filter(({ provider }) => kindIn(provider) !== "notes" && !isDocumentAccountProvider(provider))
33
- .map(({ provider, account, name }) => ({ provider, account, name, kind: kindHere(provider, running) })),
39
+ .map(({ provider, account, name }) => ({ provider, account, name, ...kindsOfHere(provider, running) })),
34
40
  { provider: "notes", account: INTERNAL_NOTES, name: null, kind: "notes" },
35
41
  ...stored
36
42
  .filter(({ provider }) => isFolderProvider(provider))
@@ -42,7 +48,7 @@ const heldOf = (stored, running) => [
42
48
  stored: { provider, account },
43
49
  })),
44
50
  ...stored
45
- .filter(({ provider }) => isDocumentAccountProvider(provider))
51
+ .filter(({ provider }) => isDocumentAccountProvider(provider) || provider === ADDED_PROVIDER)
46
52
  .map(({ id, provider, account, name }) => ({
47
53
  provider: "notes",
48
54
  account: String(id),
@@ -88,7 +94,7 @@ const accountOf = (prefix, ref, held, context) => {
88
94
  const keyed = (key) => ofProvider.find(({ account }) => account === key.account) ?? {
89
95
  ...key,
90
96
  name: null,
91
- kind: kindHere(key.provider, context.running),
97
+ ...kindsOfHere(key.provider, context.running),
92
98
  };
93
99
  const recorded = context.profiles[prefix.toLowerCase()]?.[ref];
94
100
  if (recorded && isFolderProvider(recorded.provider)) {
@@ -127,9 +133,9 @@ const accountsOfWord = (word, held, context) => {
127
133
  if (wanted === "all")
128
134
  return [...held];
129
135
  if (wanted === "personal" || wanted === "bots")
130
- return held.filter(({ provider, kind }) => kind === "messages" && isBotProvider(provider) === (wanted === "bots"));
136
+ return held.filter((one) => listedHolds(one, "messages") && isBotProvider(one.provider) === (wanted === "bots"));
131
137
  if (isKind(wanted))
132
- return held.filter(({ kind }) => kind === wanted);
138
+ return held.filter((one) => listedHolds(one, wanted));
133
139
  const recorded = context.profiles[wanted];
134
140
  if (recorded &&
135
141
  Object.values(recorded).every((key) => isFolderProvider(key.provider) || isDocumentAccountProvider(key.provider)))
@@ -184,7 +190,12 @@ export const entriesOfList = (value, context) => {
184
190
  entry(item);
185
191
  return entries.map(({ entry, accounts }) => ({
186
192
  entry,
187
- accounts: accounts.map(({ provider, account, kind }) => ({ provider, account, kind })),
193
+ accounts: accounts.map(({ provider, account, kind, kinds }) => ({
194
+ provider,
195
+ account,
196
+ kind,
197
+ ...(kinds === undefined ? {} : { kinds }),
198
+ })),
188
199
  }));
189
200
  };
190
201
  /** Every account the list names, in order and once each. */
@@ -213,7 +224,7 @@ export const fitting = (entries, kinds, what, reasonOf = (kind) => READS[kind])
213
224
  const chosen = new Map();
214
225
  const skipped = [];
215
226
  for (const { entry, accounts } of entries) {
216
- const fits = accounts.filter(({ kind }) => kind !== undefined && kinds.includes(kind));
227
+ const fits = accounts.filter((one) => kinds.some((kind) => listedHolds(one, kind)));
217
228
  for (const { provider, account } of fits)
218
229
  if (!chosen.has(keyOf({ provider, account })))
219
230
  chosen.set(keyOf({ provider, account }), { provider, account });