langmail-mcp 0.1.0 → 0.2.1

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 (137) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +89 -169
  3. package/dist/chunk-ad2666h8.js +12696 -0
  4. package/dist/langmail-mcp.js +7 -0
  5. package/package.json +94 -98
  6. package/THIRD_PARTY_NOTICES.md +0 -388
  7. package/dist/attachments/download.js +0 -69
  8. package/dist/attachments/routes.js +0 -42
  9. package/dist/attachments/tickets.js +0 -45
  10. package/dist/attachments/upload-tickets.js +0 -43
  11. package/dist/attachments/upload.js +0 -136
  12. package/dist/caldav/account-settings.js +0 -92
  13. package/dist/caldav/agenda.js +0 -277
  14. package/dist/caldav/alarm.js +0 -97
  15. package/dist/caldav/client.js +0 -408
  16. package/dist/caldav/ical.js +0 -248
  17. package/dist/caldav/occurrence.js +0 -534
  18. package/dist/caldav/recurrence.js +0 -313
  19. package/dist/caldav/rsvp.js +0 -107
  20. package/dist/caldav/scheduling-handover.js +0 -22
  21. package/dist/caldav/timezone.js +0 -103
  22. package/dist/caldav/types.js +0 -5
  23. package/dist/config.js +0 -219
  24. package/dist/contacts/address-class.js +0 -79
  25. package/dist/contacts/birthdays.js +0 -81
  26. package/dist/contacts/card.js +0 -58
  27. package/dist/contacts/constants.js +0 -46
  28. package/dist/contacts/fold.js +0 -309
  29. package/dist/contacts/index.js +0 -10
  30. package/dist/contacts/merge.js +0 -388
  31. package/dist/contacts/observations.js +0 -115
  32. package/dist/contacts/profile.js +0 -402
  33. package/dist/contacts/scoring.js +0 -146
  34. package/dist/contacts/types.js +0 -7
  35. package/dist/contacts/upsert.js +0 -131
  36. package/dist/drafts/attachments.js +0 -254
  37. package/dist/drafts/idempotency.js +0 -60
  38. package/dist/drafts/send-guard.js +0 -184
  39. package/dist/email-render/email-viewer.html +0 -143
  40. package/dist/email-render/image-proxy.js +0 -389
  41. package/dist/email-render/meta.js +0 -48
  42. package/dist/email-render/sanitize.js +0 -93
  43. package/dist/email-render/viewer-resource.js +0 -104
  44. package/dist/http/bearer.js +0 -30
  45. package/dist/http/guard.js +0 -57
  46. package/dist/http/hosts.js +0 -10
  47. package/dist/http/listener.js +0 -170
  48. package/dist/http/routes.js +0 -72
  49. package/dist/ical/ical-parse.js +0 -357
  50. package/dist/ical/index.js +0 -4
  51. package/dist/ical/timezone.js +0 -22
  52. package/dist/ical/windows-zones.js +0 -155
  53. package/dist/index.js +0 -79
  54. package/dist/jmap/blob.js +0 -49
  55. package/dist/jmap/contacts.js +0 -226
  56. package/dist/jmap/drafts.js +0 -480
  57. package/dist/jmap/email.js +0 -668
  58. package/dist/jmap/index.js +0 -12
  59. package/dist/jmap/keywords.js +0 -22
  60. package/dist/jmap/live.js +0 -21
  61. package/dist/jmap/origin.js +0 -113
  62. package/dist/jmap/patch.js +0 -29
  63. package/dist/jmap/request.js +0 -37
  64. package/dist/jmap/session.js +0 -89
  65. package/dist/jmap/sieve.js +0 -71
  66. package/dist/jmap/submission.js +0 -107
  67. package/dist/jmap/timeout.js +0 -30
  68. package/dist/jmap/types.js +0 -6
  69. package/dist/logger.js +0 -48
  70. package/dist/mcp/handler.js +0 -255
  71. package/dist/mcp/http.js +0 -29
  72. package/dist/mcp/instructions.js +0 -44
  73. package/dist/mcp/links.js +0 -64
  74. package/dist/mcp/tool-logging.js +0 -67
  75. package/dist/observability/errors.js +0 -41
  76. package/dist/rules/apply.js +0 -236
  77. package/dist/rules/rule.js +0 -280
  78. package/dist/rules/store.js +0 -92
  79. package/dist/tools/annotations.js +0 -71
  80. package/dist/tools/archive-emails.js +0 -40
  81. package/dist/tools/calendar-lookup.js +0 -64
  82. package/dist/tools/contact-common.js +0 -146
  83. package/dist/tools/contact-format.js +0 -72
  84. package/dist/tools/contact-write-through.js +0 -37
  85. package/dist/tools/create-calendar-event.js +0 -231
  86. package/dist/tools/create-calendar.js +0 -54
  87. package/dist/tools/create-contact.js +0 -172
  88. package/dist/tools/create-draft.js +0 -369
  89. package/dist/tools/create-mail-rule.js +0 -101
  90. package/dist/tools/delete-calendar-event.js +0 -165
  91. package/dist/tools/delete-contact.js +0 -60
  92. package/dist/tools/delete-draft.js +0 -129
  93. package/dist/tools/delete-mail-rule.js +0 -38
  94. package/dist/tools/download-attachment.js +0 -90
  95. package/dist/tools/download-email.js +0 -112
  96. package/dist/tools/draft-common.js +0 -600
  97. package/dist/tools/email-types.js +0 -58
  98. package/dist/tools/error-detail.js +0 -10
  99. package/dist/tools/file-emails-common.js +0 -75
  100. package/dist/tools/format.js +0 -131
  101. package/dist/tools/forward-message.js +0 -237
  102. package/dist/tools/forward-quote.js +0 -179
  103. package/dist/tools/get-draft.js +0 -61
  104. package/dist/tools/get-email.js +0 -164
  105. package/dist/tools/get-thread.js +0 -67
  106. package/dist/tools/keywords.js +0 -43
  107. package/dist/tools/list-calendar-events.js +0 -180
  108. package/dist/tools/list-calendars.js +0 -44
  109. package/dist/tools/list-drafts.js +0 -134
  110. package/dist/tools/list-mail-rules.js +0 -28
  111. package/dist/tools/list-unsubscribe.js +0 -152
  112. package/dist/tools/list-upcoming-birthdays.js +0 -165
  113. package/dist/tools/mail-rule-common.js +0 -43
  114. package/dist/tools/mail-rule-format.js +0 -79
  115. package/dist/tools/mailbox-lookup.js +0 -13
  116. package/dist/tools/mark-emails.js +0 -78
  117. package/dist/tools/merge-contacts.js +0 -145
  118. package/dist/tools/move-calendar-events.js +0 -340
  119. package/dist/tools/move-emails.js +0 -64
  120. package/dist/tools/one-click-post.js +0 -275
  121. package/dist/tools/preview-email.js +0 -204
  122. package/dist/tools/preview-mail-rule.js +0 -79
  123. package/dist/tools/reply-quote.js +0 -426
  124. package/dist/tools/reply-to-message.js +0 -292
  125. package/dist/tools/respond-to-event.js +0 -110
  126. package/dist/tools/result.js +0 -9
  127. package/dist/tools/search-contacts.js +0 -431
  128. package/dist/tools/search-emails.js +0 -570
  129. package/dist/tools/send-draft.js +0 -308
  130. package/dist/tools/trash-emails.js +0 -36
  131. package/dist/tools/unsubscribe-from-list.js +0 -249
  132. package/dist/tools/update-calendar-event.js +0 -973
  133. package/dist/tools/update-calendar.js +0 -100
  134. package/dist/tools/update-contact.js +0 -382
  135. package/dist/tools/update-draft.js +0 -714
  136. package/dist/tools/update-mail-rule.js +0 -103
  137. package/dist/tools/upload-attachments.js +0 -126
@@ -1,402 +0,0 @@
1
- // The authored half of a contact: the standard vCard fields a user keeps
2
- // about a person — phone numbers, postal addresses, an organization, a free
3
- // note — mapped between the JSContact card shape and a flat domain shape the
4
- // MCP tools can accept and render.
5
- //
6
- // Deliberately bounded to properties that appear on a standard vCard
7
- // (RFC 9553 §2.3.3 Phone, §2.5.1 Address, §2.2.3 Organization, §2.8.1 Note).
8
- // Notes, phones and organizations are where an email client starts growing a
9
- // CRM by accident; the vCard surface is the line that keeps that from
10
- // happening incrementally.
11
- //
12
- // Postal addresses are structured rather than one free-text block: address
13
- // formats are country-specific, and an agent addressing a letter needs the
14
- // components separately.
15
- import { daysInMonth } from "./birthdays.js";
16
- import { COLLECTED_UID_PREFIX, readCollected } from "./card.js";
17
- import { BIRTHDAY_KEY, COLLECTED_NOTE_KEY, USER_NOTE_KEY, } from "./constants.js";
18
- // --- postal addresses ------------------------------------------------------
19
- // JSContact has no `home` context — `private` is its spelling.
20
- const POSTAL_CONTEXT = {
21
- home: "private",
22
- other: undefined,
23
- work: "work",
24
- };
25
- // The RFC 9553 component kinds this flat model maps one-to-one. Everything
26
- // else a CardDAV client may have written — `number`, `apartment`, `building`,
27
- // `floor`, `district`, `postOfficeBox` — belongs to the street line: it is
28
- // read as part of `street` and rewritten as one component when `street` is
29
- // replaced, so a correction can neither lose it nor duplicate it.
30
- const LOCALITY_KIND = "locality";
31
- const POSTCODE_KIND = "postcode";
32
- const REGION_KIND = "region";
33
- const STREET_KIND = "name";
34
- const COUNTRY_KIND = "country";
35
- const NON_STREET_KINDS = new Set([
36
- LOCALITY_KIND,
37
- POSTCODE_KIND,
38
- REGION_KIND,
39
- COUNTRY_KIND,
40
- "separator",
41
- ]);
42
- const componentValue = (components, kind) => components?.find((c) => c.kind === kind && c.value)?.value;
43
- const componentList = (address) => address.components ?? [];
44
- // Everything that renders on the street line, in stored order — the house
45
- // number an imported card keeps separate from the street name included.
46
- const streetOf = (address) => {
47
- const line = componentList(address)
48
- .filter((c) => !NON_STREET_KINDS.has(c.kind) && c.value.trim().length > 0)
49
- .map((c) => c.value.trim())
50
- .join(" ");
51
- return line.length > 0 ? line : undefined;
52
- };
53
- const postalLabelOf = (contexts) => {
54
- if (contexts.work) {
55
- return "work";
56
- }
57
- return contexts.private ? "home" : "other";
58
- };
59
- // One-line rendering off the card itself, so it stays right for a card whose
60
- // components we do not model one-to-one. Written to `full` on every write so
61
- // CardDAV clients that only render the formatted form show something sensible.
62
- export const formatCardAddress = (address) => {
63
- const part = (kind) => componentValue(address.components, kind)?.trim() ?? "";
64
- const cityLine = [part(POSTCODE_KIND), part(LOCALITY_KIND)]
65
- .filter((p) => p.length > 0)
66
- .join(" ");
67
- const country = (address.countryCode ?? part(COUNTRY_KIND))
68
- .trim()
69
- .toUpperCase();
70
- return [streetOf(address) ?? "", cityLine, part(REGION_KIND), country]
71
- .filter((p) => p.length > 0)
72
- .join(", ");
73
- };
74
- const withFull = (address) => {
75
- const full = formatCardAddress(address);
76
- return full.length > 0 ? { ...address, full } : address;
77
- };
78
- export const toCardAddress = (address) => {
79
- const components = [];
80
- const push = (kind, value) => {
81
- if (value && value.trim().length > 0) {
82
- components.push({ kind, value: value.trim() });
83
- }
84
- };
85
- // RFC 9553 component kinds: `name` is the street name, not the person's.
86
- push(STREET_KIND, address.street);
87
- push(POSTCODE_KIND, address.postalCode);
88
- push(LOCALITY_KIND, address.city);
89
- push(REGION_KIND, address.region);
90
- const context = POSTAL_CONTEXT[address.label];
91
- return withFull({
92
- components,
93
- ...(context ? { contexts: { [context]: true } } : {}),
94
- ...(address.country ? { countryCode: address.country.toUpperCase() } : {}),
95
- });
96
- };
97
- // Merges a correction onto a stored address *in place on the card shape*
98
- // rather than rebuilding it from the flat read: a card written by another
99
- // CardDAV client can carry components this model has no field for, and
100
- // rebuilding would silently delete them from every synced device on a
101
- // postal-code-only edit. Named components are replaced, everything else is
102
- // left exactly where it was.
103
- export const patchCardAddress = (original, patch) => {
104
- let components = componentList(original);
105
- const replace = (kind, value) => {
106
- if (value === undefined) {
107
- return;
108
- }
109
- components = components.filter((c) => c.kind !== kind);
110
- if (value.trim().length > 0) {
111
- components.push({ kind, value: value.trim() });
112
- }
113
- };
114
- // Replacing the street replaces the whole street line — the read the caller
115
- // corrected against was that line joined, so anything less would leave a
116
- // stale house number stranded in front of the new street.
117
- if (patch.street !== undefined) {
118
- components = components.filter((c) => NON_STREET_KINDS.has(c.kind));
119
- replace(STREET_KIND, patch.street);
120
- }
121
- replace(POSTCODE_KIND, patch.postalCode);
122
- replace(LOCALITY_KIND, patch.city);
123
- replace(REGION_KIND, patch.region);
124
- if (patch.country !== undefined) {
125
- // The card carries the country in one place after this, never two.
126
- components = components.filter((c) => c.kind !== COUNTRY_KIND);
127
- }
128
- // Relabelling rewrites only the two contexts this model owns; a card's
129
- // `billing` / `delivery` markers are not ours to drop.
130
- const owned = new Set(Object.values(POSTAL_CONTEXT).filter(Boolean));
131
- const kept = Object.entries(original.contexts ?? {}).filter(([k]) => patch.label === undefined || !owned.has(k));
132
- const added = patch.label === undefined ? undefined : POSTAL_CONTEXT[patch.label];
133
- const contexts = Object.fromEntries(added ? [...kept, [added, true]] : kept);
134
- return withFull({
135
- ...original,
136
- components,
137
- ...(Object.keys(contexts).length > 0 ? { contexts } : {}),
138
- ...(patch.country === undefined
139
- ? {}
140
- : { countryCode: patch.country.toUpperCase() }),
141
- });
142
- };
143
- // Defensive: cards are editable in any CardDAV client, so every part may be
144
- // missing or shaped differently than we wrote it (a foreign client may carry
145
- // the country as a component rather than `countryCode`).
146
- const fromCardAddress = (key, address) => {
147
- const part = (kind) => componentValue(address.components, kind);
148
- const city = part(LOCALITY_KIND);
149
- const country = address.countryCode ?? part(COUNTRY_KIND);
150
- const postalCode = part(POSTCODE_KIND);
151
- const region = part(REGION_KIND);
152
- const street = streetOf(address);
153
- return {
154
- ...(city ? { city } : {}),
155
- ...(country ? { country: country.toUpperCase() } : {}),
156
- // What the tools print: the card's own formatted line where it has one,
157
- // so an address with components we do not model still reads correctly.
158
- display: address.full?.trim() || formatCardAddress(address),
159
- key,
160
- label: postalLabelOf(address.contexts ?? {}),
161
- ...(postalCode ? { postalCode } : {}),
162
- ...(region ? { region } : {}),
163
- ...(street ? { street } : {}),
164
- };
165
- };
166
- export const readPostalAddresses = (card) => Object.entries(card.addresses ?? {}).map(([key, address]) => fromCardAddress(key, address));
167
- // --- phones ----------------------------------------------------------------
168
- export const toCardPhone = (phone) => {
169
- const number = phone.number.trim();
170
- switch (phone.label) {
171
- case "fax":
172
- return { features: { fax: true }, number };
173
- case "home":
174
- return { contexts: { private: true }, features: { voice: true }, number };
175
- case "mobile":
176
- return { features: { mobile: true }, number };
177
- case "work":
178
- return { contexts: { work: true }, features: { voice: true }, number };
179
- default:
180
- return { number };
181
- }
182
- };
183
- // What the number is beats where it is used: a mobile stays `mobile` even on
184
- // a card that also marks it as the work context.
185
- const phoneLabelOf = (phone) => {
186
- const features = phone.features ?? {};
187
- const contexts = phone.contexts ?? {};
188
- if (features.mobile) {
189
- return "mobile";
190
- }
191
- if (features.fax) {
192
- return "fax";
193
- }
194
- if (contexts.work) {
195
- return "work";
196
- }
197
- return contexts.private ? "home" : "other";
198
- };
199
- const fromCardPhone = (key, phone) => ({
200
- key,
201
- label: phoneLabelOf(phone),
202
- number: phone.number,
203
- });
204
- export const readPhones = (card) => Object.entries(card.phones ?? {}).map(([key, phone]) => fromCardPhone(key, phone));
205
- // --- birthday --------------------------------------------------------------
206
- // The JSContact anniversary kind CardDAV maps to vCard `BDAY` (RFC 9555).
207
- // Every other kind (`wedding`, `death`, vendor values) is stored and
208
- // preserved but never read, written or listed by the tools.
209
- const BIRTH_KIND = "birth";
210
- // Older vCard 3 clients wrote a birthday with no known year as
211
- // `1604-MM-DD` (the Gregorian reform year, chosen as an obvious sentinel).
212
- // Read as "no year" so nobody is reported as turning 422.
213
- const UNKNOWN_YEAR_SENTINEL = 1604;
214
- // A leap year to validate a yearless date against: `--02-29` is a real
215
- // birthday, so February gets 29 days when no year says otherwise.
216
- const LEAP_REFERENCE_YEAR = 2000;
217
- // Month and day form a real calendar date (in the given year, or in any
218
- // leap year when the year is unknown). Shared by the read side and the
219
- // parser so an imported Feb 30 is skipped rather than clamped to Feb 28.
220
- const isCalendarDate = (month, day, year) => month >= 1 &&
221
- month <= 12 &&
222
- day >= 1 &&
223
- day <= daysInMonth(year ?? LEAP_REFERENCE_YEAR, month);
224
- // The one calendar scale this model interprets; RFC 9553 defaults to it.
225
- const GREGORIAN = "gregorian";
226
- const birthEntries = (card) => Object.entries(card.anniversaries ?? {}).filter(([, a]) => a.kind === BIRTH_KIND);
227
- // The first birth entry carrying at least a month and a day. A year-only
228
- // birthday (legal in JSContact) is unusable for "coming up" and is skipped.
229
- export const readBirthday = (card) => {
230
- for (const [, entry] of birthEntries(card)) {
231
- // Defensive on `date`: a malformed card from a foreign client must not
232
- // take down every contact read that renders a birthday line.
233
- const { calendarScale, day, month, year } = entry.date ?? {};
234
- // A month and day on another calendar scale (`chinese`, `hebrew`) mean
235
- // something else entirely; skipped rather than read as Gregorian.
236
- if (calendarScale && calendarScale !== GREGORIAN) {
237
- continue;
238
- }
239
- if (typeof month !== "number" || typeof day !== "number") {
240
- continue;
241
- }
242
- const known = typeof year === "number" && year !== UNKNOWN_YEAR_SENTINEL;
243
- // A foreign client can write a numerically shaped non-date (Feb 30);
244
- // that is no birthday, not one to clamp.
245
- if (isCalendarDate(month, day, known ? year : undefined)) {
246
- return { day, month, ...(known ? { year } : {}) };
247
- }
248
- }
249
- };
250
- const FULL_DATE = /^(\d{4})-(\d{2})-(\d{2})$/u;
251
- const YEARLESS_DATE = /^--(\d{2})-(\d{2})$/u;
252
- // What both write tools call on the caller's text. `YYYY-MM-DD`, or
253
- // `--MM-DD` when the year is unknown (the vCard 4 spelling, RFC 6350
254
- // §4.3.1). The calendar date is validated: Feb 30 is rejected, `--02-29`
255
- // is accepted because a leap-day birthday needs no particular year.
256
- export const parseBirthday = (text) => {
257
- const trimmed = text.trim();
258
- const full = FULL_DATE.exec(trimmed);
259
- const yearless = YEARLESS_DATE.exec(trimmed);
260
- if (!(full || yearless)) {
261
- return {
262
- error: `Birthday "${text}" is not a date. Use YYYY-MM-DD, or --MM-DD when the year is unknown.`,
263
- };
264
- }
265
- const year = full ? Number(full[1]) : undefined;
266
- const month = Number(full ? full[2] : yearless?.[1]);
267
- const day = Number(full ? full[3] : yearless?.[2]);
268
- if (!isCalendarDate(month, day, year)) {
269
- return {
270
- error: `Birthday "${text}" is not a calendar date — check the month and day.`,
271
- };
272
- }
273
- return { birthday: { day, month, ...(year === undefined ? {} : { year }) } };
274
- };
275
- // `1990-03-03`, or `--03-03` when the year is unknown — the spelling the
276
- // tools accept, so what they print can be sent straight back.
277
- export const formatBirthday = (birthday) => {
278
- const md = `${String(birthday.month).padStart(2, "0")}-${String(birthday.day).padStart(2, "0")}`;
279
- return birthday.year === undefined
280
- ? `--${md}`
281
- : `${String(birthday.year).padStart(4, "0")}-${md}`;
282
- };
283
- // One birth entry as the tools write it — shared by create_contact (a fresh
284
- // card) and withBirthday (a stored one), so the two can never diverge.
285
- export const birthAnniversary = (birthday) => {
286
- const { day, month, year } = birthday;
287
- return {
288
- date: { day, month, ...(year === undefined ? {} : { year }) },
289
- kind: BIRTH_KIND,
290
- };
291
- };
292
- const freeKey = (taken, wanted) => {
293
- let key = wanted;
294
- for (let n = 1; key in taken; n += 1) {
295
- key = `${wanted}-${n}`;
296
- }
297
- return key;
298
- };
299
- // The anniversaries map with the birth entry replaced (or removed when
300
- // `birthday` is undefined) and every other entry — a wedding date a phone
301
- // wrote, a vendor kind — left exactly where it was. A stored birth entry
302
- // keeps its key so the edit lands in place on every synced device; a card
303
- // without one takes the reserved key.
304
- export const withBirthday = (card, birthday) => {
305
- const stored = card.anniversaries ?? {};
306
- const births = birthEntries(card);
307
- const kept = Object.fromEntries(Object.entries(stored).filter(([, a]) => a.kind !== BIRTH_KIND));
308
- if (birthday === undefined) {
309
- return kept;
310
- }
311
- // A foreign entry may legally sit under the reserved key; it is never
312
- // overwritten — the birth entry takes the next free key instead.
313
- const [key, existing] = births[0] ?? [freeKey(kept, BIRTHDAY_KEY), undefined];
314
- return { ...kept, [key]: { ...existing, ...birthAnniversary(birthday) } };
315
- };
316
- // --- roles -----------------------------------------------------------------
317
- // What a person is to the user ("lawyer", "landlord"), as the user said or
318
- // confirmed it. Stored as a JSContact title of kind `role`, which CardDAV
319
- // serves as vCard `ROLE` (RFC 9555): an ordinary field on every device, not
320
- // a contact group the way `CATEGORIES` becomes one on a phone. Job titles
321
- // (kind `title`, vCard `TITLE`) share the property and are never touched.
322
- const ROLE_KIND = "role";
323
- export const MAX_ROLES = 10;
324
- const LEADING_MY = /^my\s+/u;
325
- const SPACES = /\s+/gu;
326
- const normalizeSpacing = (text) => text.trim().replace(SPACES, " ").toLowerCase();
327
- // "My Lawyer " and "lawyer" are the same role: the user's phrase is the
328
- // query, and a stored role is compared the same way.
329
- export const normalizeRole = (text) => normalizeSpacing(text).replace(LEADING_MY, "");
330
- // Whether the phrase names someone by what they are to the user ("my
331
- // landlord"): the leading "my" that `normalizeRole` drops.
332
- export const isRolePhrase = (text) => LEADING_MY.test(normalizeSpacing(text));
333
- const roleEntries = (card) => Object.entries(card.titles ?? {}).filter(([, t]) => t.kind === ROLE_KIND && typeof t.name === "string");
334
- export const readRoles = (card) => [
335
- ...new Set(roleEntries(card)
336
- .map(([, t]) => normalizeRole(t.name))
337
- .filter((r) => r.length > 0)),
338
- ];
339
- // Whether one of the card's roles has a word starting with the (normalized)
340
- // query: "lawyer" finds a "divorce lawyer", but a name search for "Ian"
341
- // does not turn up everyone whose role is "physician".
342
- export const hasRole = (card, query) => {
343
- const q = normalizeRole(query);
344
- return q.length > 0 && readRoles(card).some((r) => ` ${r}`.includes(` ${q}`));
345
- };
346
- // The card's whole `titles` map with `removed` roles dropped and `added` ones
347
- // appended under fresh keys, without duplicates. Every other title (a job
348
- // title a phone wrote) keeps its key and value.
349
- export const withRoles = (card, added, removed) => {
350
- const gone = new Set(removed.map(normalizeRole));
351
- const titles = Object.fromEntries(Object.entries(card.titles ?? {}).filter(([, t]) => !(t.kind === ROLE_KIND &&
352
- typeof t.name === "string" &&
353
- gone.has(normalizeRole(t.name)))));
354
- const present = new Set(readRoles({ titles }));
355
- for (const role of added.map(normalizeRole)) {
356
- if (role.length === 0 || present.has(role)) {
357
- continue;
358
- }
359
- present.add(role);
360
- titles[freeKey(titles, `r${Object.keys(titles).length}`)] = {
361
- kind: ROLE_KIND,
362
- name: role,
363
- };
364
- }
365
- return titles;
366
- };
367
- // --- organization, note, source -------------------------------------------
368
- export const readOrganization = (card) => Object.values(card.organizations ?? {}).find((o) => o.name)?.name ??
369
- undefined;
370
- // Every note entry except the machine-owned collection payload. A CardDAV
371
- // client may have written its own entries under keys we don't control, so
372
- // the read is "everything that isn't ours" rather than one fixed key.
373
- export const readNote = (card) => {
374
- const text = Object.entries(card.notes ?? {})
375
- .filter(([key]) => key !== COLLECTED_NOTE_KEY)
376
- .map(([, entry]) => entry.note)
377
- .filter((n) => typeof n === "string" && n.trim().length > 0)
378
- .join("\n\n");
379
- return text.length > 0 ? text : undefined;
380
- };
381
- // Which note entry a write lands in: the card's single existing user note if
382
- // there is exactly one, so editing a note authored in a CardDAV client edits
383
- // it in place instead of leaving two notes side by side.
384
- export const userNoteKey = (card) => {
385
- const keys = Object.keys(card.notes ?? {}).filter((key) => key !== COLLECTED_NOTE_KEY);
386
- return keys.length === 1 ? keys[0] : USER_NOTE_KEY;
387
- };
388
- export const userNoteEntry = (note) => ({ note });
389
- // A card without a marker either predates the marker or came in through an
390
- // address book we sync. Collection's own cards are recognisable without it,
391
- // by the uid it mints or by membership in the Collected book (when the
392
- // caller knows that book's id); anything else is imported.
393
- export const sourceOf = (card, collectedBookId) => {
394
- const marked = readCollected(card).source;
395
- if (marked) {
396
- return marked;
397
- }
398
- const collected = card.uid?.startsWith(COLLECTED_UID_PREFIX) === true ||
399
- (collectedBookId !== undefined &&
400
- card.addressBookIds[collectedBookId] === true);
401
- return collected ? "derived" : "imported";
402
- };
@@ -1,146 +0,0 @@
1
- // Read-time scoring: relationship tiers, person ranking, address choice,
2
- // and relative ages. Everything here derives from the stored counters at
3
- // query time, so tuning a threshold (constants.ts) never requires
4
- // re-collection. Raw totals stay internal — the tool exposes the computed
5
- // label plus concrete recent interactions, never counts the caller would
6
- // have to classify itself.
7
- import { classifyContext, normalizeAddress } from "./address-class.js";
8
- import { readCollected } from "./card.js";
9
- import { ACTIVE_MIN_INTERACTIONS, ACTIVE_RECENT_DAYS } from "./constants.js";
10
- const DAY_MS = 86_400_000;
11
- const totalInteractions = (ext) => Object.values(ext.addresses).reduce((sum, a) => sum + a.count, 0);
12
- const lastSeenOf = (ext) => {
13
- let latest;
14
- for (const a of Object.values(ext.addresses)) {
15
- if (!latest ||
16
- new Date(a.lastSeen).getTime() > new Date(latest).getTime()) {
17
- latest = a.lastSeen;
18
- }
19
- }
20
- return latest;
21
- };
22
- // `active`: enough interactions and a recent one. `incidental`: at most a
23
- // single sighting (including a personal-book card never observed at all).
24
- // `occasional`: everything in between.
25
- export const relationshipFor = (ext, now) => {
26
- const total = totalInteractions(ext);
27
- if (total <= 1) {
28
- return "incidental";
29
- }
30
- const last = lastSeenOf(ext);
31
- const recent = last !== undefined &&
32
- now.getTime() - new Date(last).getTime() <= ACTIVE_RECENT_DAYS * DAY_MS;
33
- return total >= ACTIVE_MIN_INTERACTIONS && recent ? "active" : "occasional";
34
- };
35
- const TIER_RANK = {
36
- active: 2,
37
- incidental: 0,
38
- occasional: 1,
39
- };
40
- // Rank: relationship tier, then last interaction, newest first. Ambiguity
41
- // between same-name people is preserved — the tool never merges or picks.
42
- export const rankCards = (cards, now) => [...cards].sort((a, b) => {
43
- const extA = readCollected(a);
44
- const extB = readCollected(b);
45
- const tier = TIER_RANK[relationshipFor(extB, now)] -
46
- TIER_RANK[relationshipFor(extA, now)];
47
- if (tier !== 0) {
48
- return tier;
49
- }
50
- const lastA = lastSeenOf(extA);
51
- const lastB = lastSeenOf(extB);
52
- return ((lastB ? new Date(lastB).getTime() : 0) -
53
- (lastA ? new Date(lastA).getTime() : 0));
54
- });
55
- const CONFIDENCE_RANK = {
56
- confirmed: 2,
57
- strong: 1,
58
- weak: 0,
59
- };
60
- // Every address on a card with its stored grade. An address the user added
61
- // by hand (no collection entry) counts as confirmed — the user asserting a
62
- // pairing outranks anything we inferred.
63
- export const addressCandidates = (card) => {
64
- const ext = readCollected(card);
65
- const prefs = Object.values(card.emails ?? {}).flatMap((e) => typeof e.pref === "number" ? [e.pref] : []);
66
- const topPref = prefs.length > 0 ? Math.min(...prefs) : undefined;
67
- return Object.values(card.emails ?? {}).map((e) => {
68
- const address = normalizeAddress(e.address);
69
- const entry = ext.addresses[address];
70
- let context = classifyContext(address);
71
- if (e.contexts?.work) {
72
- context = "work";
73
- }
74
- else if (e.contexts?.private) {
75
- context = "private";
76
- }
77
- return {
78
- address,
79
- confidence: entry?.confidence ?? "confirmed",
80
- context,
81
- ...(entry ? { lastSeen: entry.lastSeen } : {}),
82
- ...(topPref !== undefined && e.pref === topPref
83
- ? { preferred: true }
84
- : {}),
85
- };
86
- });
87
- };
88
- // Best address under a context bias: context match first (never filtering
89
- // anyone out — `any` skips the bias), then the address the card marks as
90
- // preferred, then confidence, then recency. The bias goes first because the
91
- // caller asked for it explicitly; the preference outranks the grades, which
92
- // are only inferred.
93
- export const bestAddress = (card, context) => [...addressCandidates(card)].sort((a, b) => {
94
- if (context !== "any" &&
95
- (a.context === context) !== (b.context === context)) {
96
- return a.context === context ? -1 : 1;
97
- }
98
- if (Boolean(a.preferred) !== Boolean(b.preferred)) {
99
- return a.preferred ? -1 : 1;
100
- }
101
- const conf = CONFIDENCE_RANK[b.confidence] - CONFIDENCE_RANK[a.confidence];
102
- if (conf !== 0) {
103
- return conf;
104
- }
105
- return ((b.lastSeen ? new Date(b.lastSeen).getTime() : 0) -
106
- (a.lastSeen ? new Date(a.lastSeen).getTime() : 0));
107
- })[0];
108
- // Relative age as prose, computed tool-side so the caller never does date
109
- // arithmetic. Mirrors the design examples: days up to a month, then weeks,
110
- // then months, then years; future dates (an upcoming event) read naturally.
111
- export const relativeAge = (iso, now) => {
112
- const then = new Date(iso).getTime();
113
- if (Number.isNaN(then)) {
114
- return "unknown date";
115
- }
116
- const days = Math.round((now.getTime() - then) / DAY_MS);
117
- if (days < 0) {
118
- const ahead = -days;
119
- if (ahead === 1) {
120
- return "tomorrow";
121
- }
122
- if (ahead < 30) {
123
- return `in ${ahead} days`;
124
- }
125
- return ahead < 84
126
- ? `in ${Math.round(ahead / 7)} weeks`
127
- : `in ${Math.round(ahead / 30)} months`;
128
- }
129
- if (days === 0) {
130
- return "today";
131
- }
132
- if (days === 1) {
133
- return "yesterday";
134
- }
135
- if (days < 30) {
136
- return `${days} days ago`;
137
- }
138
- if (days < 84) {
139
- return `${Math.round(days / 7)} weeks ago`;
140
- }
141
- if (days < 365) {
142
- return `${Math.round(days / 30)} months ago`;
143
- }
144
- const years = Math.round(days / 365);
145
- return years === 1 ? "a year ago" : `${years} years ago`;
146
- };
@@ -1,7 +0,0 @@
1
- // Domain types of the collection pipeline. Cards store only content-free
2
- // interaction tuples (date, channel, direction, record id) — never subjects
3
- // or event titles: cards sync to every CardDAV device the user connects,
4
- // where any app holding the contacts permission can read them, and
5
- // mail-derived content must not travel that path. Human-readable interaction
6
- // lines are hydrated from the record ids at query time by search_contacts.
7
- export {};