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,69 +0,0 @@
1
- // Redeem an attachment ticket: fetch the blob from Stalwart with the
2
- // ticket's stored bearer and stream it through. Routing lives in
3
- // routes.ts; this file owns the response shaping.
4
- //
5
- // Logging deliberately carries only status/size — never tokens or
6
- // filenames.
7
- import { blobDownload, JmapError } from "../jmap/index.js";
8
- import { logger } from "../logger.js";
9
- const CONTROL_QUOTE_RE = /[\p{Cc}"\\]/gu;
10
- const NON_ASCII_RE = /[^ -~]/gu;
11
- // RFC 5987 attr-char does NOT include !'()* — encodeURIComponent leaves
12
- // those bare, so they get a second pass.
13
- const RFC5987_EXTRA_RE = /[!'()*]/gu;
14
- const rfc5987Encode = (value) => encodeURIComponent(value).replaceAll(RFC5987_EXTRA_RE, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`);
15
- // Build a header-safe content-disposition. Strip quotes/backslashes/control
16
- // chars (header smuggling), then — because fetch header values are Latin-1
17
- // ByteStrings and the Headers constructor throws on anything above U+00FF
18
- // (an em dash or CJK filename would 500 the route) — send an ASCII fallback
19
- // in filename= and the real UTF-8 name via RFC 6266/5987 filename*.
20
- const contentDisposition = (name) => {
21
- const cleaned = name.replaceAll(CONTROL_QUOTE_RE, "").trim() || "attachment";
22
- const ascii = cleaned.replaceAll(NON_ASCII_RE, "_").trim() || "attachment";
23
- return `attachment; filename="${ascii}"; filename*=UTF-8''${rfc5987Encode(cleaned)}`;
24
- };
25
- const notFound = () => new Response("not found\n", { status: 404 });
26
- export const createAttachmentDownload = (live, tickets) => {
27
- return async (token) => {
28
- // Unknown and expired tokens are indistinguishable on purpose.
29
- const ticket = tickets.lookup(token);
30
- if (!ticket) {
31
- return notFound();
32
- }
33
- let upstream;
34
- try {
35
- const session = await live.getSession(ticket.authorization);
36
- upstream = await blobDownload({
37
- accountId: ticket.accountId,
38
- authorization: ticket.authorization,
39
- blobId: ticket.blobId,
40
- downloadUrl: session.downloadUrl,
41
- name: ticket.name,
42
- type: ticket.type,
43
- });
44
- }
45
- catch (err) {
46
- // E.g. the bound bearer expired before the ticket did — the agent
47
- // re-calls download_attachment or download_email for a fresh URL.
48
- const status = err instanceof JmapError ? err.status : 502;
49
- logger.warn({ status }, "attachment blob fetch failed");
50
- return new Response("upstream error\n", { status: 502 });
51
- }
52
- const headers = new Headers({
53
- "cache-control": "no-store",
54
- "content-disposition": contentDisposition(ticket.name),
55
- "content-type": upstream.headers.get("content-type") ?? ticket.type,
56
- // The type is the sender's claim. A browser that opens the link
57
- // must take it as given and not guess a more dangerous one from
58
- // the bytes.
59
- "x-content-type-options": "nosniff",
60
- });
61
- const contentLength = upstream.headers.get("content-length");
62
- if (contentLength) {
63
- headers.set("content-length", contentLength);
64
- }
65
- logger.info({ size: contentLength ? Number(contentLength) : null, status: 200 }, "attachment downloaded");
66
- // Pass the upstream body through as a stream — never buffered.
67
- return new Response(upstream.body, { headers });
68
- };
69
- };
@@ -1,42 +0,0 @@
1
- // The routes that redeem attachment tickets: `GET /attachments/<ticket>`
2
- // streams a file out, `PUT /attachments/uploads/<ticket>` takes one in.
3
- //
4
- // Neither asks for the bearer token: the unguessable ticket in the path is
5
- // the credential, the same model as a presigned URL. That is what lets the
6
- // agent move a file with plain `curl`, so its bytes never pass through the
7
- // conversation.
8
- const ATTACHMENTS_PREFIX = "/attachments/";
9
- const UPLOADS_PREFIX = "/attachments/uploads/";
10
- const HTTP_NOT_FOUND = 404;
11
- const notFound = () => new Response("not found\n", { status: HTTP_NOT_FOUND });
12
- // Anything but a clean GET (download) or PUT (upload) of a single token
13
- // segment is a plain 404 — indistinguishable from an unknown/expired token,
14
- // on purpose.
15
- const attachmentsRoute = (req, pathname, download, upload) => {
16
- // Both under /attachments/, so one rule in a reverse proxy keeps every
17
- // ticket out of its access log. A download token is base64url and so never
18
- // contains a slash, which keeps the two shapes apart.
19
- if (pathname.startsWith(UPLOADS_PREFIX)) {
20
- const uploadToken = pathname.slice(UPLOADS_PREFIX.length);
21
- if (req.method === "PUT" && uploadToken && !uploadToken.includes("/")) {
22
- return upload(uploadToken, req);
23
- }
24
- return notFound();
25
- }
26
- const token = pathname.slice(ATTACHMENTS_PREFIX.length);
27
- if (req.method === "GET" && token && !token.includes("/")) {
28
- return download(token);
29
- }
30
- return notFound();
31
- };
32
- /**
33
- * The attachment routes for a listener. No `logAs`: the path is the
34
- * credential, and the download and upload handlers log their own line (status
35
- * and size only).
36
- */
37
- export const attachmentRoutes = (download, upload) => [
38
- {
39
- handle: (req, url) => attachmentsRoute(req, url.pathname, download, upload),
40
- path: ATTACHMENTS_PREFIX,
41
- },
42
- ];
@@ -1,45 +0,0 @@
1
- // In-memory store of short-lived attachment download tickets.
2
- //
3
- // download_attachment (and download_email, for a whole message) mints a ticket binding an unguessable token to
4
- // (bearer, accountId, blobId, name, type); GET /attachments/:token redeems
5
- // it — the token *is* the credential, same model as a presigned URL. The
6
- // bearer therefore never reaches the model or the wire. Single-process
7
- // state is fine: the server is one process, and a restart merely
8
- // invalidates outstanding URLs (the agent re-calls the tool).
9
- // A day: preview_email embeds these URLs (cid inline images) in a rendering
10
- // the user re-opens from scrollback, and 15 minutes turned them into broken
11
- // icons almost immediately. Redeeming still forwards the stored credential,
12
- // so one that has been revoked since is refused by Stalwart regardless of the
13
- // ticket.
14
- export const TICKET_TTL_HOURS = 24;
15
- const TICKET_TTL_MS = TICKET_TTL_HOURS * 60 * 60 * 1000;
16
- export const mintToken = () => {
17
- const bytes = new Uint8Array(32);
18
- crypto.getRandomValues(bytes);
19
- // base64url, unpadded — URL-safe without further encoding.
20
- return Buffer.from(bytes).toString("base64url");
21
- };
22
- export const createTicketStore = (now = Date.now) => {
23
- const tickets = new Map();
24
- // Lazy sweep on mint/lookup keeps the map bounded without a timer.
25
- const sweep = () => {
26
- const t = now();
27
- for (const [token, ticket] of tickets) {
28
- if (ticket.expiresAt <= t) {
29
- tickets.delete(token);
30
- }
31
- }
32
- };
33
- return {
34
- lookup: (token) => {
35
- sweep();
36
- return tickets.get(token) ?? null;
37
- },
38
- mint: (input) => {
39
- sweep();
40
- const token = mintToken();
41
- tickets.set(token, { ...input, expiresAt: now() + TICKET_TTL_MS });
42
- return token;
43
- },
44
- };
45
- };
@@ -1,43 +0,0 @@
1
- // In-memory store of short-lived attachment *upload* tickets — the mirror of
2
- // tickets.ts for the other direction.
3
- //
4
- // upload_attachments mints a ticket binding an unguessable token to
5
- // (bearer, accountId, filename, type); PUT /attachments/uploads/:token
6
- // redeems it by streaming the request body into the account's JMAP blob store.
7
- // As with downloads, the token is the credential and the bearer never reaches
8
- // the model. Unlike downloads, a ticket is single-use: `take` removes it, so a
9
- // leaked URL is worth at most one blob, and the TTL is short because the agent
10
- // uploads straight after asking.
11
- import { mintToken } from "./tickets.js";
12
- export const UPLOAD_TICKET_TTL_MINUTES = 15;
13
- const UPLOAD_TICKET_TTL_MS = UPLOAD_TICKET_TTL_MINUTES * 60 * 1000;
14
- export const createUploadTicketStore = (now = Date.now) => {
15
- const tickets = new Map();
16
- const sweep = () => {
17
- const t = now();
18
- for (const [token, ticket] of tickets) {
19
- if (ticket.expiresAt <= t) {
20
- tickets.delete(token);
21
- }
22
- }
23
- };
24
- return {
25
- lookup: (token) => {
26
- sweep();
27
- return tickets.get(token) ?? null;
28
- },
29
- mint: (input) => {
30
- sweep();
31
- const token = mintToken();
32
- const expiresAt = now() + UPLOAD_TICKET_TTL_MS;
33
- tickets.set(token, { ...input, expiresAt });
34
- return { expiresAt, token };
35
- },
36
- take: (token) => {
37
- sweep();
38
- const ticket = tickets.get(token) ?? null;
39
- tickets.delete(token);
40
- return ticket;
41
- },
42
- };
43
- };
@@ -1,136 +0,0 @@
1
- // Redeem an attachment upload ticket: read the PUT body (capped), store it as
2
- // a blob in the ticket's account with the ticket's stored bearer, and answer
3
- // with the blobId create_draft / update_draft take. Routing lives in
4
- // routes.ts; this file owns the response shaping.
5
- //
6
- // The answer is JSON on purpose: the agent reads it from curl's stdout, and
7
- // the `next` line tells it what to do with the blobId without going back to
8
- // the tool description.
9
- //
10
- // Logging carries only status/size — never tokens or filenames.
11
- import { MAX_ATTACHMENT_BYTES } from "../drafts/attachments.js";
12
- import { blobUpload } from "../jmap/index.js";
13
- import { logger } from "../logger.js";
14
- import { describeError } from "../observability/errors.js";
15
- // How long Stalwart keeps a blob no message references yet: its JMAP
16
- // `uploadTtl`, which we leave at its default of one hour
17
- // (crates/registry/src/schema/structs_impl.rs, `Duration::from_millis(3600000)`).
18
- // Past that the blobId names nothing and create_draft is refused, so the
19
- // response states the window.
20
- export const UNREFERENCED_BLOB_TTL_MINUTES = 60;
21
- const MAX_MB = MAX_ATTACHMENT_BYTES / (1024 * 1024);
22
- // The `attachments` entry create_draft needs for an uploaded file. `mimeType`
23
- // rides along because create_draft derives a part's type from the entry, not
24
- // from the blob: without it, a `scan` uploaded as image/tiff would arrive as
25
- // application/octet-stream.
26
- export const attachEntry = (blobId, filename, mimeType) => JSON.stringify({ blobId, filename, mimeType });
27
- const json = (body, status) => new Response(`${JSON.stringify(body)}\n`, {
28
- headers: {
29
- "cache-control": "no-store",
30
- "content-type": "application/json",
31
- },
32
- status,
33
- });
34
- const USED_NOW = "This URL is now used; call upload_attachments for a new one.";
35
- const notFound = () => json({
36
- error: "not_found",
37
- message: "This upload URL is unknown, expired, or already used. Call upload_attachments for a new one.",
38
- }, 404);
39
- // `spent` says whether the URL still works: a declared oversize body is refused
40
- // before the ticket is taken, one found oversize while reading is not.
41
- const tooLarge = (spent) => json({
42
- error: "too_large",
43
- message: `The file is over the ${MAX_MB} MB an attachment can be. Nothing was stored. ` +
44
- (spent ? USED_NOW : "Retry this URL with a smaller file."),
45
- }, 413);
46
- // The body, or null once it runs past `limit` — read chunk by chunk, so an
47
- // oversized upload that lied about (or omitted) its Content-Length is cut off
48
- // at the cap rather than buffered whole.
49
- const readCapped = async (body, limit) => {
50
- const chunks = [];
51
- let total = 0;
52
- for await (const chunk of body) {
53
- total += chunk.byteLength;
54
- if (total > limit) {
55
- return null;
56
- }
57
- chunks.push(chunk);
58
- }
59
- return Buffer.concat(chunks);
60
- };
61
- export const createAttachmentUpload = (live, tickets) => {
62
- return async (token, req) => {
63
- // Unknown, used, and expired tokens are indistinguishable on purpose.
64
- if (!tickets.lookup(token)) {
65
- return notFound();
66
- }
67
- // Refused before the ticket is spent, so a caller who picked the wrong
68
- // file can retry the same URL with the right one.
69
- if (Number(req.headers.get("content-length") ?? 0) > MAX_ATTACHMENT_BYTES) {
70
- return tooLarge(false);
71
- }
72
- const ticket = tickets.take(token);
73
- if (!ticket) {
74
- return notFound();
75
- }
76
- let bytes;
77
- try {
78
- bytes = req.body
79
- ? await readCapped(req.body, MAX_ATTACHMENT_BYTES)
80
- : new Uint8Array();
81
- }
82
- catch (err) {
83
- // The client went away mid-PUT (reset, curl killed). Routine on a flaky
84
- // network, so a warn and a plain answer rather than the server's
85
- // error-level handler and an error-tracking alert.
86
- logger.warn({ ...describeError(err), status: 400 }, "attachment upload body incomplete");
87
- return json({
88
- error: "incomplete",
89
- message: `The upload was cut off before it finished, so nothing was stored. ${USED_NOW}`,
90
- }, 400);
91
- }
92
- if (!bytes) {
93
- return tooLarge(true);
94
- }
95
- if (bytes.byteLength === 0) {
96
- return json({
97
- error: "empty",
98
- message: "The upload had no bytes, so nothing was stored. Send the file as the request body, e.g. " +
99
- `curl -T '<file>' '<url>'. ${USED_NOW}`,
100
- }, 400);
101
- }
102
- let blobId;
103
- try {
104
- const session = await live.getSession(ticket.authorization);
105
- blobId = await blobUpload({
106
- accountId: ticket.accountId,
107
- authorization: ticket.authorization,
108
- content: bytes,
109
- type: ticket.type,
110
- uploadUrl: session.uploadUrl,
111
- });
112
- }
113
- catch (err) {
114
- // E.g. the bound bearer expired, or Stalwart's upload quota is spent.
115
- // `status` is what we answered, as on every other line here; Stalwart's
116
- // own status, when it gave one, is `upstreamStatus`.
117
- const detail = describeError(err);
118
- logger.warn({ ...detail, status: 502, upstreamStatus: detail.status }, "attachment blob upload failed");
119
- return json({
120
- error: "upstream_error",
121
- message: "The mail server did not accept the file, so nothing was stored. Call upload_attachments " +
122
- "for a new URL and try again.",
123
- }, 502);
124
- }
125
- logger.info({ size: bytes.byteLength, status: 200 }, "attachment uploaded");
126
- return json({
127
- blobId,
128
- filename: ticket.filename,
129
- mimeType: ticket.type,
130
- next: `Attach it within ${UNREFERENCED_BLOB_TTL_MINUTES} minutes by passing ` +
131
- `${attachEntry(blobId, ticket.filename, ticket.type)} in the \`attachments\` of ` +
132
- "create_draft or update_draft. An upload no draft references by then is discarded.",
133
- size: bytes.byteLength,
134
- }, 200);
135
- };
136
- };
@@ -1,92 +0,0 @@
1
- // Reads the authenticated user's per-account time-zone preference from
2
- // Stalwart, so the calendar tools can fall back to it when the caller omits an
3
- // explicit `timeZone` (see the resolution chain in create-calendar-event.ts).
4
- //
5
- // Stalwart stores an optional IANA `timeZone` on the `AccountSettings` registry
6
- // singleton (v0.16.13). The `sysAccountSettings*` permission is in the default
7
- // `user` role, so the request's own bearer — the same one forwarded to CalDAV —
8
- // can Get it. We discover the JMAP apiUrl from the session (the proven path all
9
- // the other JMAP consumers use) and POST a single `x:AccountSettings/get`.
10
- //
11
- // Every failure mode here is non-fatal: an unset preference, a rejected method,
12
- // a transport error, or an unrecognized zone all resolve to `null`, and the
13
- // caller falls through to UTC. Failing open keeps event creation working even if
14
- // this read breaks — the only cost is the historical UTC rendering.
15
- import { accountIdForMail, authorizationHeader, fetchSession, jmapFetch, jmapTimeoutSignal, } from "../jmap/index.js";
16
- import { logger } from "../logger.js";
17
- import { describeError } from "../observability/errors.js";
18
- import { isValidTimeZone } from "./timezone.js";
19
- const USING = ["urn:ietf:params:jmap:core", "urn:stalwart:jmap"];
20
- // Performs the JMAP read and returns the stored IANA zone, or null when it is
21
- // unset / not a zone we can resolve. Throws only on transport/protocol errors,
22
- // which the cache layer catches.
23
- const fetchAccountTimeZone = async (cfg, token) => {
24
- const authorization = authorizationHeader(token);
25
- const session = await fetchSession(cfg.serverUrl, authorization);
26
- const res = await jmapFetch(session.apiUrl, {
27
- body: JSON.stringify({
28
- methodCalls: [
29
- [
30
- "x:AccountSettings/get",
31
- { accountId: accountIdForMail(session), ids: ["singleton"] },
32
- "0",
33
- ],
34
- ],
35
- using: USING,
36
- }),
37
- headers: { authorization, "content-type": "application/json" },
38
- method: "POST",
39
- // Bounded like every other JMAP call: this read fails open, but only if it
40
- // fails — an unbounded one would hang event creation behind a stalled Stalwart.
41
- signal: jmapTimeoutSignal(),
42
- });
43
- if (res.status !== 200) {
44
- throw new Error(`x:AccountSettings/get returned ${res.status}`);
45
- }
46
- const body = (await res.json());
47
- const [name, payload] = body.methodResponses?.[0] ?? [];
48
- if (name !== "x:AccountSettings/get") {
49
- // An `error` response (e.g. the bearer lacks the registry Get) — no zone.
50
- return null;
51
- }
52
- const zone = payload?.list?.[0]?.timeZone;
53
- return typeof zone === "string" && isValidTimeZone(zone) ? zone : null;
54
- };
55
- // A per-token cache of the resolved zone, alongside the request-scoped token
56
- // caches. The preference changes rarely and only matters when the tool input
57
- // omits `timeZone`, so a short TTL keeps the extra JMAP round-trip off the hot
58
- // path without pinning a stale zone for long. `null` (no preference) is cached
59
- // too, so a user without one doesn't re-hit Stalwart on every create.
60
- // One resolver (and cache) is shared across the calendar tools — see mcp/handler.ts.
61
- const DEFAULT_TTL_SECONDS = 300;
62
- export const makeAccountTimeZoneResolver = (cfg, ttlSeconds = DEFAULT_TTL_SECONDS) => {
63
- const cache = new Map();
64
- return async (token) => {
65
- const nowSec = Math.floor(Date.now() / 1000);
66
- const hit = cache.get(token);
67
- if (hit && hit.exp > nowSec) {
68
- return hit.zone;
69
- }
70
- // A miss (new or expired token) is the only moment the map grows, so sweep
71
- // expired entries here — bounds the cache to active tokens rather than one
72
- // entry per distinct bearer for the life of the process. O(n) only on misses.
73
- for (const [key, entry] of cache) {
74
- if (entry.exp <= nowSec) {
75
- cache.delete(key);
76
- }
77
- }
78
- let zone = null;
79
- try {
80
- zone = await fetchAccountTimeZone(cfg, token);
81
- }
82
- catch (err) {
83
- // Failure-open: log once and fall through to UTC. Never surface this to
84
- // the tool caller — a broken preference read must not fail event creation.
85
- // Through describeError like every other error line: an upstream
86
- // message can carry the mailbox address.
87
- logger.warn(describeError(err), "account time-zone preference read failed; falling back to UTC");
88
- }
89
- cache.set(token, { exp: nowSec + ttlSeconds, zone });
90
- return zone;
91
- };
92
- };