inboxer 0.0.0-stage → 0.2.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.
- package/LICENSE +21 -0
- package/README.md +376 -2
- package/dist/app.d.ts +6 -0
- package/dist/app.js +56 -0
- package/dist/auth.d.ts +33 -0
- package/dist/auth.js +111 -0
- package/dist/config.d.ts +23 -0
- package/dist/config.js +90 -0
- package/dist/core/address.d.ts +6 -0
- package/dist/core/address.js +16 -0
- package/dist/core/attachments.d.ts +9 -0
- package/dist/core/attachments.js +30 -0
- package/dist/core/context.d.ts +10 -0
- package/dist/core/context.js +21 -0
- package/dist/core/mail.d.ts +170 -0
- package/dist/core/mail.js +656 -0
- package/dist/core/sync.d.ts +16 -0
- package/dist/core/sync.js +44 -0
- package/dist/core/text.d.ts +8 -0
- package/dist/core/text.js +45 -0
- package/dist/core/threads.d.ts +21 -0
- package/dist/core/threads.js +81 -0
- package/dist/index.d.ts +35 -0
- package/dist/index.js +51 -0
- package/dist/mcp.d.ts +5 -0
- package/dist/mcp.js +198 -0
- package/dist/provider/index.d.ts +3 -0
- package/dist/provider/index.js +11 -0
- package/dist/provider/resend.d.ts +8 -0
- package/dist/provider/resend.js +184 -0
- package/dist/provider/types.d.ts +77 -0
- package/dist/provider/types.js +6 -0
- package/dist/store.d.ts +54 -0
- package/dist/store.js +148 -0
- package/dist/types.d.ts +138 -0
- package/dist/types.js +1 -0
- package/dist/ui/assets.d.ts +8 -0
- package/dist/ui/assets.js +13 -0
- package/dist/ui/routes.d.ts +11 -0
- package/dist/ui/routes.js +232 -0
- package/dist/ui/static/app.js +27 -0
- package/dist/ui/static/htmx.min.js +1 -0
- package/dist/ui/static/style.css +179 -0
- package/dist/ui/strings.d.ts +67 -0
- package/dist/ui/strings.js +67 -0
- package/dist/ui/views.d.ts +45 -0
- package/dist/ui/views.js +275 -0
- package/package.json +81 -4
- package/skills/inboxer/SKILL.md +118 -0
- package/src/app.ts +56 -0
- package/src/auth.ts +119 -0
- package/src/config.ts +92 -0
- package/src/core/address.ts +19 -0
- package/src/core/attachments.ts +33 -0
- package/src/core/context.ts +28 -0
- package/src/core/mail.ts +737 -0
- package/src/core/sync.ts +51 -0
- package/src/core/text.ts +52 -0
- package/src/core/threads.ts +102 -0
- package/src/index.ts +93 -0
- package/src/mcp.ts +233 -0
- package/src/provider/index.ts +14 -0
- package/src/provider/resend.ts +235 -0
- package/src/provider/types.ts +82 -0
- package/src/store.ts +187 -0
- package/src/types.ts +140 -0
- package/src/ui/assets.ts +21 -0
- package/src/ui/routes.ts +252 -0
- package/src/ui/static/app.js +27 -0
- package/src/ui/static/htmx.min.js +1 -0
- package/src/ui/static/style.css +179 -0
- package/src/ui/strings.ts +73 -0
- package/src/ui/views.ts +315 -0
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Backup for missed webhooks. Each run looks back to one interval before the previous run started,
|
|
3
|
+
* so consecutive windows overlap; ingest and status updates are idempotent.
|
|
4
|
+
*/
|
|
5
|
+
export class Sync {
|
|
6
|
+
mail;
|
|
7
|
+
intervalMs;
|
|
8
|
+
timer = null;
|
|
9
|
+
running = null;
|
|
10
|
+
constructor(mail, intervalMin) {
|
|
11
|
+
this.mail = mail;
|
|
12
|
+
this.intervalMs = intervalMin * 60_000;
|
|
13
|
+
}
|
|
14
|
+
start() {
|
|
15
|
+
this.timer = setInterval(() => {
|
|
16
|
+
this.run().catch(err => console.error("inboxer: sync failed", err));
|
|
17
|
+
}, this.intervalMs);
|
|
18
|
+
this.timer.unref?.();
|
|
19
|
+
}
|
|
20
|
+
async stop() {
|
|
21
|
+
if (this.timer)
|
|
22
|
+
clearInterval(this.timer);
|
|
23
|
+
this.timer = null;
|
|
24
|
+
await this.running?.catch(() => { });
|
|
25
|
+
}
|
|
26
|
+
run() {
|
|
27
|
+
this.running ??= this.runOnce().finally(() => {
|
|
28
|
+
this.running = null;
|
|
29
|
+
});
|
|
30
|
+
return this.running;
|
|
31
|
+
}
|
|
32
|
+
async runOnce() {
|
|
33
|
+
const startedAt = new Date();
|
|
34
|
+
const cursor = await this.mail.store.getSyncCursor();
|
|
35
|
+
const since = new Date((cursor ? new Date(cursor).getTime() : startedAt.getTime()) - this.intervalMs);
|
|
36
|
+
for await (const providerId of this.mail.provider.listInbound(since)) {
|
|
37
|
+
await this.mail.ingest(providerId);
|
|
38
|
+
}
|
|
39
|
+
for await (const { providerId, status } of this.mail.provider.listOutbound(since)) {
|
|
40
|
+
await this.mail.applyStatus(providerId, status, null);
|
|
41
|
+
}
|
|
42
|
+
await this.mail.store.setSyncCursor(startedAt.toISOString());
|
|
43
|
+
}
|
|
44
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/** Readable plain text from an HTML body. Never used for rendering. */
|
|
2
|
+
export declare function htmlToText(html: string): string;
|
|
3
|
+
export declare function escapeHtml(value: string): string;
|
|
4
|
+
export declare function textToHtml(text: string): string;
|
|
5
|
+
/** Lowercase, accent-free tokens used by search. */
|
|
6
|
+
export declare function tokenize(value: string): string[];
|
|
7
|
+
export declare function normalizeSubject(subject: string): string;
|
|
8
|
+
export declare function replySubject(subject: string): string;
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
const ENTITIES = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", nbsp: " " };
|
|
2
|
+
/** Readable plain text from an HTML body. Never used for rendering. */
|
|
3
|
+
export function htmlToText(html) {
|
|
4
|
+
return html
|
|
5
|
+
.replace(/<(script|style|head)[\s\S]*?<\/\1>/gi, "")
|
|
6
|
+
.replace(/<br\s*\/?>/gi, "\n")
|
|
7
|
+
.replace(/<\/(p|div|tr|li|h[1-6]|blockquote)>/gi, "\n")
|
|
8
|
+
.replace(/<li[^>]*>/gi, "- ")
|
|
9
|
+
.replace(/<[^>]+>/g, "")
|
|
10
|
+
.replace(/&(#x[0-9a-f]+|#\d+|[a-z]+);/gi, (match, code) => {
|
|
11
|
+
if (code[0] === "#") {
|
|
12
|
+
const n = code[1]?.toLowerCase() === "x" ? parseInt(code.slice(2), 16) : parseInt(code.slice(1), 10);
|
|
13
|
+
return Number.isFinite(n) ? String.fromCodePoint(n) : match;
|
|
14
|
+
}
|
|
15
|
+
return ENTITIES[code.toLowerCase()] ?? match;
|
|
16
|
+
})
|
|
17
|
+
.replace(/[ \t]+\n/g, "\n")
|
|
18
|
+
.replace(/\n{3,}/g, "\n\n")
|
|
19
|
+
.trim();
|
|
20
|
+
}
|
|
21
|
+
export function escapeHtml(value) {
|
|
22
|
+
return value.replace(/[&<>"']/g, ch => `&${{ "&": "amp", "<": "lt", ">": "gt", '"': "quot", "'": "#39" }[ch]};`);
|
|
23
|
+
}
|
|
24
|
+
export function textToHtml(text) {
|
|
25
|
+
return text
|
|
26
|
+
.split(/\n{2,}/)
|
|
27
|
+
.map(paragraph => `<p>${escapeHtml(paragraph).replace(/\n/g, "<br>")}</p>`)
|
|
28
|
+
.join("\n");
|
|
29
|
+
}
|
|
30
|
+
/** Lowercase, accent-free tokens used by search. */
|
|
31
|
+
export function tokenize(value) {
|
|
32
|
+
return value
|
|
33
|
+
.normalize("NFD")
|
|
34
|
+
.replace(/\p{M}/gu, "")
|
|
35
|
+
.toLowerCase()
|
|
36
|
+
.split(/[^\p{L}\p{N}@._+-]+/u)
|
|
37
|
+
.filter(Boolean);
|
|
38
|
+
}
|
|
39
|
+
const REPLY_PREFIX = /^\s*((re|fw|fwd|rv|aw|sv|tr|res|enc)\s*(\[\d+\])?\s*:\s*)+/i;
|
|
40
|
+
export function normalizeSubject(subject) {
|
|
41
|
+
return subject.replace(REPLY_PREFIX, "").replace(/\s+/g, " ").trim().toLowerCase();
|
|
42
|
+
}
|
|
43
|
+
export function replySubject(subject) {
|
|
44
|
+
return /^\s*re\s*:/i.test(subject) ? subject : `Re: ${subject}`;
|
|
45
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { type Store } from "../store.ts";
|
|
2
|
+
import type { Message, Thread } from "../types.ts";
|
|
3
|
+
export declare function messageTime(message: Message): string;
|
|
4
|
+
export declare function participantsOf(message: Pick<Message, "from" | "to" | "cc">): string[];
|
|
5
|
+
export interface ThreadLookup {
|
|
6
|
+
mailbox: string;
|
|
7
|
+
inReplyTo: string | null;
|
|
8
|
+
references: string[];
|
|
9
|
+
subject: string;
|
|
10
|
+
participants: string[];
|
|
11
|
+
at: string;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* 1. In-Reply-To / References against a stored Message-ID.
|
|
15
|
+
* 2. Same normalized subject and a shared external participant, within the window.
|
|
16
|
+
* 3. A new thread.
|
|
17
|
+
*/
|
|
18
|
+
export declare function resolveThreadId(store: Store, lookup: ThreadLookup, ownAddresses: Set<string>, windowDays: number): Promise<string>;
|
|
19
|
+
export declare function threadMessages(store: Store, thread: Thread): Promise<Message[]>;
|
|
20
|
+
/** Recomputes the thread summary, adding `newMessageId` when given. A thread left with only discarded drafts is removed. */
|
|
21
|
+
export declare function refreshThread(store: Store, threadId: string, newMessageId?: string): Promise<Thread | null>;
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { nid } from "../store.js";
|
|
2
|
+
import { bareAddress } from "./address.js";
|
|
3
|
+
import { normalizeSubject } from "./text.js";
|
|
4
|
+
const DAY_MS = 24 * 60 * 60 * 1000;
|
|
5
|
+
export function messageTime(message) {
|
|
6
|
+
return message.sent_at ?? message.created_at;
|
|
7
|
+
}
|
|
8
|
+
export function participantsOf(message) {
|
|
9
|
+
return [message.from, ...message.to, ...message.cc].filter(Boolean).map(bareAddress);
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* 1. In-Reply-To / References against a stored Message-ID.
|
|
13
|
+
* 2. Same normalized subject and a shared external participant, within the window.
|
|
14
|
+
* 3. A new thread.
|
|
15
|
+
*/
|
|
16
|
+
export async function resolveThreadId(store, lookup, ownAddresses, windowDays) {
|
|
17
|
+
for (const ref of [lookup.inReplyTo, ...[...lookup.references].reverse()]) {
|
|
18
|
+
if (!ref)
|
|
19
|
+
continue;
|
|
20
|
+
const id = await store.lookupMessageId(ref);
|
|
21
|
+
const message = id ? await store.getMessage(id) : null;
|
|
22
|
+
if (message)
|
|
23
|
+
return message.thread_id;
|
|
24
|
+
}
|
|
25
|
+
const subject = normalizeSubject(lookup.subject);
|
|
26
|
+
const external = new Set(lookup.participants.filter(p => !ownAddresses.has(p)));
|
|
27
|
+
if (subject && external.size) {
|
|
28
|
+
const since = new Date(lookup.at).getTime() - windowDays * DAY_MS;
|
|
29
|
+
const match = (await store.allThreads())
|
|
30
|
+
.filter(t => t.mailbox === lookup.mailbox && t.norm_subject === subject && new Date(t.last_at).getTime() >= since)
|
|
31
|
+
.filter(t => t.participants.some(p => external.has(p)))
|
|
32
|
+
.sort((a, b) => b.last_at.localeCompare(a.last_at))[0];
|
|
33
|
+
if (match)
|
|
34
|
+
return match.id;
|
|
35
|
+
}
|
|
36
|
+
return nid();
|
|
37
|
+
}
|
|
38
|
+
export async function threadMessages(store, thread) {
|
|
39
|
+
const messages = await Promise.all(thread.message_ids.map(id => store.requireMessage(id)));
|
|
40
|
+
return messages.filter(m => m.status !== "discarded").sort((a, b) => messageTime(a).localeCompare(messageTime(b)));
|
|
41
|
+
}
|
|
42
|
+
/** Recomputes the thread summary, adding `newMessageId` when given. A thread left with only discarded drafts is removed. */
|
|
43
|
+
export async function refreshThread(store, threadId, newMessageId) {
|
|
44
|
+
const existing = await store.getThread(threadId);
|
|
45
|
+
const ids = existing?.message_ids ?? [];
|
|
46
|
+
const thread = {
|
|
47
|
+
id: threadId,
|
|
48
|
+
mailbox: "",
|
|
49
|
+
subject: "",
|
|
50
|
+
norm_subject: "",
|
|
51
|
+
participants: [],
|
|
52
|
+
last_at: "",
|
|
53
|
+
last_direction: "in",
|
|
54
|
+
has_draft: false,
|
|
55
|
+
unread: 0,
|
|
56
|
+
archived: false,
|
|
57
|
+
labels: {},
|
|
58
|
+
message_ids: newMessageId && !ids.includes(newMessageId) ? [...ids, newMessageId] : ids,
|
|
59
|
+
};
|
|
60
|
+
const messages = await threadMessages(store, thread);
|
|
61
|
+
if (!messages.length) {
|
|
62
|
+
await store.deleteThread(threadId);
|
|
63
|
+
return null;
|
|
64
|
+
}
|
|
65
|
+
const settled = messages.filter(m => m.status !== "draft");
|
|
66
|
+
const first = settled[0] ?? messages[0];
|
|
67
|
+
const last = settled.at(-1) ?? messages.at(-1);
|
|
68
|
+
thread.mailbox = first.mailbox;
|
|
69
|
+
thread.subject = first.subject;
|
|
70
|
+
thread.norm_subject = normalizeSubject(first.subject);
|
|
71
|
+
thread.participants = [...new Set(messages.flatMap(participantsOf))];
|
|
72
|
+
thread.last_at = messageTime(last);
|
|
73
|
+
thread.last_direction = last.direction;
|
|
74
|
+
thread.has_draft = messages.some(m => m.status === "draft");
|
|
75
|
+
thread.unread = messages.filter(m => m.direction === "in" && !m.read).length;
|
|
76
|
+
thread.archived = settled.length > 0 && settled.every(m => m.archived);
|
|
77
|
+
for (const m of messages)
|
|
78
|
+
Object.assign(thread.labels, m.labels);
|
|
79
|
+
await store.putThread(thread);
|
|
80
|
+
return thread;
|
|
81
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import type { IncomingMessage, ServerResponse } from "node:http";
|
|
2
|
+
import type { MailProvider } from "./provider/types.ts";
|
|
3
|
+
import type { InboxerConfig } from "./types.ts";
|
|
4
|
+
export interface InboxerOptions {
|
|
5
|
+
/** A provider instance to use instead of resolving `cfg.provider.type`. */
|
|
6
|
+
provider?: MailProvider;
|
|
7
|
+
}
|
|
8
|
+
export interface Inboxer {
|
|
9
|
+
/** Web-standard handler for `Bun.serve`, Hono, Deno or any fetch-based server. */
|
|
10
|
+
fetch: (req: Request) => Promise<Response>;
|
|
11
|
+
/** Node-style `(req, res)` handler, e.g. for a roster-server site. */
|
|
12
|
+
handler: (req: IncomingMessage, res: ServerResponse) => void;
|
|
13
|
+
/** Resolves once the database is open and the first sync has run. Requests wait for it. */
|
|
14
|
+
ready: Promise<void>;
|
|
15
|
+
/** Stops the sync timer and closes the database. */
|
|
16
|
+
close: () => Promise<void>;
|
|
17
|
+
}
|
|
18
|
+
export declare function createInboxer(cfg: InboxerConfig, options?: InboxerOptions): Inboxer;
|
|
19
|
+
export interface LoginLinkOptions {
|
|
20
|
+
/** Shown in the device list, e.g. "Ana's phone". */
|
|
21
|
+
label?: string;
|
|
22
|
+
/** Thread to open after signing in. */
|
|
23
|
+
threadId?: string;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* One-time login link for the review UI, minted from a script on the server without an MCP client.
|
|
27
|
+
* Opens the database, stores the link and closes it; the session it creates reaches every mailbox.
|
|
28
|
+
*/
|
|
29
|
+
export declare function createLoginLink(cfg: InboxerConfig, options?: LoginLinkOptions): Promise<{
|
|
30
|
+
url: string;
|
|
31
|
+
expires_at: string;
|
|
32
|
+
}>;
|
|
33
|
+
export { WebhookSignatureError } from "./provider/types.ts";
|
|
34
|
+
export type { DeliveryStatus, InboundMessage, MailProvider, OutboundAttachment, OutboundMessage, OutboundStatus, ProviderEvent, WebhookRequest, } from "./provider/types.ts";
|
|
35
|
+
export type { InboxerConfig, MailboxConfig, ProviderConfig } from "./types.ts";
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { getRequestListener } from "@hono/node-server";
|
|
2
|
+
import { buildApp } from "./app.js";
|
|
3
|
+
import { Access } from "./auth.js";
|
|
4
|
+
import { assertConfig } from "./config.js";
|
|
5
|
+
import { Mail } from "./core/mail.js";
|
|
6
|
+
import { Sync } from "./core/sync.js";
|
|
7
|
+
import { resolveProvider } from "./provider/index.js";
|
|
8
|
+
import { Store } from "./store.js";
|
|
9
|
+
export function createInboxer(cfg, options = {}) {
|
|
10
|
+
assertConfig(cfg, { requireProvider: !options.provider });
|
|
11
|
+
const provider = options.provider ?? resolveProvider(cfg.provider);
|
|
12
|
+
const store = new Store(cfg.dataDir);
|
|
13
|
+
const mail = new Mail(store, provider, cfg);
|
|
14
|
+
const access = new Access(store, cfg);
|
|
15
|
+
const sync = new Sync(mail, cfg.syncIntervalMin);
|
|
16
|
+
const ready = (async () => {
|
|
17
|
+
await store.connect();
|
|
18
|
+
await mail.resumePending();
|
|
19
|
+
await sync.run().catch(err => console.error("inboxer: initial sync failed", err));
|
|
20
|
+
sync.start();
|
|
21
|
+
})();
|
|
22
|
+
const app = buildApp(mail, access, cfg, ready);
|
|
23
|
+
const fetch = async (req) => app.fetch(req);
|
|
24
|
+
return {
|
|
25
|
+
fetch,
|
|
26
|
+
handler: getRequestListener(fetch, { overrideGlobalObjects: false }),
|
|
27
|
+
ready,
|
|
28
|
+
async close() {
|
|
29
|
+
await ready.catch(() => { });
|
|
30
|
+
mail.stopPending();
|
|
31
|
+
await sync.stop();
|
|
32
|
+
await store.close();
|
|
33
|
+
},
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* One-time login link for the review UI, minted from a script on the server without an MCP client.
|
|
38
|
+
* Opens the database, stores the link and closes it; the session it creates reaches every mailbox.
|
|
39
|
+
*/
|
|
40
|
+
export async function createLoginLink(cfg, options = {}) {
|
|
41
|
+
assertConfig(cfg, { requireProvider: false });
|
|
42
|
+
const store = new Store(cfg.dataDir);
|
|
43
|
+
await store.connect();
|
|
44
|
+
try {
|
|
45
|
+
return await new Access(store, cfg).createLoginLink({ kind: "cli", name: "cli", scope: null }, options.label ?? null, options.threadId ?? null);
|
|
46
|
+
}
|
|
47
|
+
finally {
|
|
48
|
+
await store.close();
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
export { WebhookSignatureError } from "./provider/types.js";
|
package/dist/mcp.d.ts
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import type { Access } from "./auth.ts";
|
|
2
|
+
import { type Mail } from "./core/mail.ts";
|
|
3
|
+
import type { Actor } from "./types.ts";
|
|
4
|
+
/** Stateless Streamable HTTP: a fresh server and transport per request. */
|
|
5
|
+
export declare function handleMcp(req: Request, mail: Mail, access: Access, actor: Actor): Promise<Response>;
|
package/dist/mcp.js
ADDED
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
import { createRequire } from "node:module";
|
|
2
|
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
3
|
+
import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";
|
|
4
|
+
import { z } from "zod";
|
|
5
|
+
import { appUrl, threadPath } from "./config.js";
|
|
6
|
+
import { ConflictError, toView } from "./core/mail.js";
|
|
7
|
+
const { version: VERSION } = createRequire(import.meta.url)("../package.json");
|
|
8
|
+
function json(value) {
|
|
9
|
+
return { content: [{ type: "text", text: JSON.stringify(value, null, 2) }] };
|
|
10
|
+
}
|
|
11
|
+
/** `url` opens the message's thread in the review UI, scrolled to the draft when it is one. */
|
|
12
|
+
function messageView(cfg, m) {
|
|
13
|
+
return { ...m, url: appUrl(cfg, threadPath(m.thread_id, m.status === "draft" ? m.id : undefined)) };
|
|
14
|
+
}
|
|
15
|
+
function draftView(cfg, d) {
|
|
16
|
+
return { ...messageView(cfg, toView(d)), bcc: d.bcc, html: d.html, pending: d.pending };
|
|
17
|
+
}
|
|
18
|
+
function threadView(cfg, t) {
|
|
19
|
+
return { ...t, url: appUrl(cfg, threadPath(t.id)) };
|
|
20
|
+
}
|
|
21
|
+
function wrap(cfg, fn) {
|
|
22
|
+
return async (args) => {
|
|
23
|
+
try {
|
|
24
|
+
return json(await fn(args));
|
|
25
|
+
}
|
|
26
|
+
catch (err) {
|
|
27
|
+
const body = { error: err.message };
|
|
28
|
+
if (err instanceof ConflictError)
|
|
29
|
+
body.current = draftView(cfg, err.current);
|
|
30
|
+
return { ...json(body), isError: true };
|
|
31
|
+
}
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
const IMAGE_TYPES = new Set(["image/png", "image/jpeg", "image/gif", "image/webp"]);
|
|
35
|
+
const TEXT_TYPES = /^(text\/|application\/(json|xml|csv)$)/;
|
|
36
|
+
function attachmentContent(cfg, messageId, meta, body) {
|
|
37
|
+
const data = Buffer.from(body).toString("base64");
|
|
38
|
+
if (IMAGE_TYPES.has(meta.content_type))
|
|
39
|
+
return { type: "image", data, mimeType: meta.content_type };
|
|
40
|
+
if (TEXT_TYPES.test(meta.content_type))
|
|
41
|
+
return { type: "text", text: new TextDecoder().decode(body) };
|
|
42
|
+
const uri = appUrl(cfg, `/attachments/${encodeURIComponent(messageId)}/${encodeURIComponent(meta.id)}`);
|
|
43
|
+
return { type: "resource", resource: { uri, mimeType: meta.content_type, blob: data } };
|
|
44
|
+
}
|
|
45
|
+
const addresses = z.array(z.string()).describe("Addresses, e.g. \"Ana <ana@example.com>\" or \"ana@example.com\"");
|
|
46
|
+
const isoDate = z.string().describe("ISO 8601 timestamp");
|
|
47
|
+
const metaFilter = z.record(z.string(), z.union([z.string(), z.number(), z.boolean()]))
|
|
48
|
+
.describe("Every pair must match the thread's context or a participant's contact; values compare as text");
|
|
49
|
+
const metaPatch = z.record(z.string().min(1), z.union([z.string(), z.number(), z.boolean(), z.null()]))
|
|
50
|
+
.describe("Keys to set; null removes a key; keys not sent are kept");
|
|
51
|
+
const notePatch = z.string().nullable().describe("Replaces the note; null clears it");
|
|
52
|
+
function buildServer(mail, access, actor) {
|
|
53
|
+
const server = new McpServer({ name: "inboxer", version: VERSION });
|
|
54
|
+
const cfg = mail.cfg;
|
|
55
|
+
server.registerTool("list_mailboxes", { description: "Mailboxes this token reaches; tokens for every mailbox also see the catch-all for unknown recipients." }, wrap(cfg, async () => mail.listMailboxes(actor.scope)));
|
|
56
|
+
server.registerTool("list_threads", {
|
|
57
|
+
description: "Threads, newest first. status: unanswered (last message inbound and no pending draft), all (not archived), archived.",
|
|
58
|
+
inputSchema: {
|
|
59
|
+
mailbox: z.string().optional(),
|
|
60
|
+
status: z.enum(["unanswered", "all", "archived"]).optional().describe("Default: unanswered"),
|
|
61
|
+
label: z.string().optional(),
|
|
62
|
+
since: isoDate.optional(),
|
|
63
|
+
meta: metaFilter.optional(),
|
|
64
|
+
limit: z.number().int().positive().optional().describe("Default: 50"),
|
|
65
|
+
},
|
|
66
|
+
}, wrap(cfg, async (args) => (await mail.listThreads(args, actor.scope)).map(t => threadView(cfg, t))));
|
|
67
|
+
server.registerTool("search", {
|
|
68
|
+
description: "Full-text search over subject, body, from and to. Accent and case insensitive; every term must match. Pass query, meta, or both.",
|
|
69
|
+
inputSchema: {
|
|
70
|
+
query: z.string().optional(),
|
|
71
|
+
meta: metaFilter.optional(),
|
|
72
|
+
mailbox: z.string().optional(),
|
|
73
|
+
from: z.string().optional().describe("Substring of the sender address"),
|
|
74
|
+
since: isoDate.optional(),
|
|
75
|
+
until: isoDate.optional(),
|
|
76
|
+
limit: z.number().int().positive().optional().describe("Default: 50"),
|
|
77
|
+
},
|
|
78
|
+
}, wrap(cfg, async (args) => (await mail.search(args, actor.scope)).map(m => messageView(cfg, m))));
|
|
79
|
+
server.registerTool("get_thread", {
|
|
80
|
+
description: "A thread with its messages as plain text, pending drafts included, plus the thread's context and the contacts of its participants.",
|
|
81
|
+
inputSchema: { thread_id: z.string() },
|
|
82
|
+
}, wrap(cfg, async ({ thread_id }) => {
|
|
83
|
+
const { thread, messages, ...context } = await mail.getThread(thread_id, actor.scope);
|
|
84
|
+
return { thread: threadView(cfg, thread), ...context, messages: messages.map(m => messageView(cfg, m)) };
|
|
85
|
+
}));
|
|
86
|
+
server.registerTool("get_contact", {
|
|
87
|
+
description: "Context stored for an email address: meta (e.g. ids in other systems) and a note. null when there is none.",
|
|
88
|
+
inputSchema: { address: z.string() },
|
|
89
|
+
}, wrap(cfg, async ({ address }) => mail.getContact(address, actor.scope)));
|
|
90
|
+
server.registerTool("set_contact", {
|
|
91
|
+
description: "Attach context to an email address, e.g. meta { license_id: \"BL-2231\" } or a note. Merges with what is stored. Shown in get_thread and in the review UI, and searchable with meta filters.",
|
|
92
|
+
inputSchema: { address: z.string(), meta: metaPatch.optional(), note: notePatch.optional() },
|
|
93
|
+
}, wrap(cfg, async ({ address, meta, note }) => mail.setContact(address, { meta, note }, actor)));
|
|
94
|
+
server.registerTool("set_thread_meta", {
|
|
95
|
+
description: "Attach context to a thread, e.g. meta { ticket: 45 } or a note such as \"promised an answer on Monday\". Merges with what is stored.",
|
|
96
|
+
inputSchema: { thread_id: z.string(), meta: metaPatch.optional(), note: notePatch.optional() },
|
|
97
|
+
}, wrap(cfg, async ({ thread_id, meta, note }) => mail.setThreadContext(thread_id, { meta, note }, actor)));
|
|
98
|
+
server.registerTool("label", {
|
|
99
|
+
description: "Add or remove labels. ids are message ids or thread ids (applies to every message in the thread).",
|
|
100
|
+
inputSchema: { ids: z.array(z.string()), add: z.array(z.string()).optional(), remove: z.array(z.string()).optional() },
|
|
101
|
+
}, wrap(cfg, async ({ ids, add, remove }) => ({ updated: await mail.label(ids, add ?? [], remove ?? [], actor) })));
|
|
102
|
+
server.registerTool("mark", {
|
|
103
|
+
description: "Set read and/or archived. ids are message ids or thread ids.",
|
|
104
|
+
inputSchema: { ids: z.array(z.string()), read: z.boolean().optional(), archived: z.boolean().optional() },
|
|
105
|
+
}, wrap(cfg, async ({ ids, read, archived }) => ({ updated: await mail.mark(ids, { read, archived }, actor) })));
|
|
106
|
+
server.registerTool("create_draft", {
|
|
107
|
+
description: "Create a draft for a human to review. Pass reply_to_id to reply (recipients, subject and threading are derived), or mailbox + to + subject for a new conversation. note is shown to the reviewer. The result's url opens the draft in the review UI; share it with the user.",
|
|
108
|
+
inputSchema: {
|
|
109
|
+
mailbox: z.string().optional(),
|
|
110
|
+
reply_to_id: z.string().optional().describe("Message id to reply to"),
|
|
111
|
+
reply_all: z.boolean().optional(),
|
|
112
|
+
to: addresses.optional(),
|
|
113
|
+
cc: addresses.optional(),
|
|
114
|
+
bcc: addresses.optional(),
|
|
115
|
+
subject: z.string().optional(),
|
|
116
|
+
text: z.string(),
|
|
117
|
+
html: z.string().optional(),
|
|
118
|
+
note: z.string().optional(),
|
|
119
|
+
},
|
|
120
|
+
}, wrap(cfg, async (a) => draftView(cfg, await mail.createDraft({
|
|
121
|
+
mailbox: a.mailbox, replyToId: a.reply_to_id, replyAll: a.reply_all, to: a.to, cc: a.cc, bcc: a.bcc,
|
|
122
|
+
subject: a.subject, text: a.text, html: a.html, note: a.note,
|
|
123
|
+
}, actor))));
|
|
124
|
+
server.registerTool("update_draft", {
|
|
125
|
+
description: "Update a pending draft. version must be the current one. Fails if a human edited the draft unless force is true.",
|
|
126
|
+
inputSchema: {
|
|
127
|
+
id: z.string(),
|
|
128
|
+
version: z.number().int(),
|
|
129
|
+
to: addresses.optional(),
|
|
130
|
+
cc: addresses.optional(),
|
|
131
|
+
bcc: addresses.optional(),
|
|
132
|
+
subject: z.string().optional(),
|
|
133
|
+
text: z.string().optional(),
|
|
134
|
+
html: z.string().nullable().optional(),
|
|
135
|
+
note: z.string().nullable().optional(),
|
|
136
|
+
force: z.boolean().optional(),
|
|
137
|
+
},
|
|
138
|
+
}, wrap(cfg, async ({ id, version, force, ...patch }) => draftView(cfg, await mail.updateDraft(id, version, patch, actor, force ?? false))));
|
|
139
|
+
server.registerTool("list_drafts", {
|
|
140
|
+
description: "Pending drafts, newest first.",
|
|
141
|
+
inputSchema: { mailbox: z.string().optional() },
|
|
142
|
+
}, wrap(cfg, async ({ mailbox }) => (await mail.listDrafts(mailbox, actor.scope)).map(d => draftView(cfg, d))));
|
|
143
|
+
server.registerTool("discard_draft", { description: "Discard a pending draft.", inputSchema: { id: z.string() } }, wrap(cfg, async ({ id }) => { await mail.discardDraft(id, actor); return { discarded: id }; }));
|
|
144
|
+
server.registerTool("send_draft", { description: "Send the last saved version of a draft.", inputSchema: { id: z.string() } }, wrap(cfg, async ({ id }) => messageView(cfg, toView(await mail.sendDraft(id, actor)))));
|
|
145
|
+
server.registerTool("send", {
|
|
146
|
+
description: "Send a new message directly, without review. Use only when your rules allow it.",
|
|
147
|
+
inputSchema: {
|
|
148
|
+
mailbox: z.string(),
|
|
149
|
+
to: addresses,
|
|
150
|
+
cc: addresses.optional(),
|
|
151
|
+
bcc: addresses.optional(),
|
|
152
|
+
subject: z.string(),
|
|
153
|
+
text: z.string(),
|
|
154
|
+
html: z.string().optional(),
|
|
155
|
+
},
|
|
156
|
+
}, wrap(cfg, async (a) => messageView(cfg, toView(await mail.send({ ...a }, actor)))));
|
|
157
|
+
server.registerTool("reply", {
|
|
158
|
+
description: "Reply directly to a message, without review. Use only when your rules allow it.",
|
|
159
|
+
inputSchema: { message_id: z.string().describe("Inboxer message id"), text: z.string(), reply_all: z.boolean().optional() },
|
|
160
|
+
}, wrap(cfg, async ({ message_id, text, reply_all }) => messageView(cfg, toView(await mail.reply(message_id, text, reply_all ?? false, actor)))));
|
|
161
|
+
server.registerTool("get_attachment", {
|
|
162
|
+
description: "Content of an inbound attachment: images as images, text as text, anything else (e.g. PDF) as an embedded resource. Larger than the server's limit returns an error.",
|
|
163
|
+
inputSchema: { message_id: z.string(), attachment_id: z.string() },
|
|
164
|
+
}, async ({ message_id, attachment_id }) => {
|
|
165
|
+
try {
|
|
166
|
+
const { meta, body } = await mail.getAttachment(message_id, attachment_id, actor.scope);
|
|
167
|
+
if (body.byteLength > cfg.mcp.maxAttachmentMb * 1024 * 1024) {
|
|
168
|
+
throw new Error(`Attachment is ${(body.byteLength / 1048576).toFixed(1)} MB, over the ${cfg.mcp.maxAttachmentMb} MB limit`);
|
|
169
|
+
}
|
|
170
|
+
return { content: [{ type: "text", text: JSON.stringify(meta) }, attachmentContent(cfg, message_id, meta, body)] };
|
|
171
|
+
}
|
|
172
|
+
catch (err) {
|
|
173
|
+
return { ...json({ error: err.message }), isError: true };
|
|
174
|
+
}
|
|
175
|
+
});
|
|
176
|
+
server.registerTool("create_login_link", {
|
|
177
|
+
description: "One-time link that signs one browser into the review UI, limited to the mailboxes this token reaches. Expires unused after a few minutes. Pass thread_id to land on that thread after signing in. Browsers already signed in can open a result's url directly.",
|
|
178
|
+
inputSchema: {
|
|
179
|
+
label: z.string().optional().describe("Shown in the device list, e.g. \"Martin's phone\""),
|
|
180
|
+
thread_id: z.string().optional().describe("Thread to open after signing in"),
|
|
181
|
+
},
|
|
182
|
+
}, wrap(cfg, async ({ label, thread_id }) => access.createLoginLink(actor, label ?? null, thread_id ?? null)));
|
|
183
|
+
server.registerTool("list_sessions", { description: "Browsers signed into the UI." }, wrap(cfg, async () => access.listSessions(actor.scope)));
|
|
184
|
+
server.registerTool("revoke_session", { description: "Sign a browser out of the UI.", inputSchema: { id: z.string() } }, wrap(cfg, async ({ id }) => ({ revoked: await access.revokeSession(id, actor) })));
|
|
185
|
+
return server;
|
|
186
|
+
}
|
|
187
|
+
/** Stateless Streamable HTTP: a fresh server and transport per request. */
|
|
188
|
+
export async function handleMcp(req, mail, access, actor) {
|
|
189
|
+
const server = buildServer(mail, access, actor);
|
|
190
|
+
const transport = new WebStandardStreamableHTTPServerTransport({ sessionIdGenerator: undefined, enableJsonResponse: true });
|
|
191
|
+
await server.connect(transport);
|
|
192
|
+
try {
|
|
193
|
+
return await transport.handleRequest(req);
|
|
194
|
+
}
|
|
195
|
+
finally {
|
|
196
|
+
await server.close();
|
|
197
|
+
}
|
|
198
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { createResendProvider } from "./resend.js";
|
|
2
|
+
const PROVIDERS = {
|
|
3
|
+
resend: createResendProvider,
|
|
4
|
+
};
|
|
5
|
+
export function resolveProvider(config) {
|
|
6
|
+
const { type, ...options } = config;
|
|
7
|
+
const factory = PROVIDERS[type];
|
|
8
|
+
if (!factory)
|
|
9
|
+
throw new Error(`Unknown provider type "${type}". Available: ${Object.keys(PROVIDERS).join(", ")}`);
|
|
10
|
+
return factory(options);
|
|
11
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { type MailProvider } from "./types.ts";
|
|
2
|
+
export interface ResendProviderConfig {
|
|
3
|
+
apiKey: string;
|
|
4
|
+
webhookSecret: string;
|
|
5
|
+
}
|
|
6
|
+
export declare function createResendProvider(config: Record<string, unknown>): MailProvider;
|
|
7
|
+
/** The sent-email list uses `YYYY-MM-DD HH:MM:SS.ffffff+00`; the receiving API uses ISO 8601. */
|
|
8
|
+
export declare function parseResendDate(value: string): Date;
|