Email Organizer v0.1.2 · claude-code
Archive SHA-256 7a4d147fa8307973542ae8b9b01c7716550b73cede62314210845cb969e444d6 · 40.2 KB · built Nov 27, 2026
src/index.js
// Email Organizer — AgentRove native agent (MIT). Offline: parses mail text you supply, never sends or modifies mail.
import { defineAgent, AgentError, runCli, runMcpStdio, handleMcpMessage, validateManifest } from "../sdk/index.js";
import { readFileSync } from "node:fs";
import { parseMessage, normalizeNewlines, looksLikeMbox, splitMbox } from "./mime.js";
import { triageMessages, suggestFilters } from "./triage.js";
const manifest = JSON.parse(readFileSync(new URL("../agent.json", import.meta.url), "utf8"));
function nowMs(input, ctx) {
if (input.now) return Date.parse(input.now);
const n = ctx.now();
return n instanceof Date ? n.getTime() : Date.parse(String(n));
}
const handlers = {
async parse_messages(input) {
const maxMessages = input.max_messages ?? 1000;
const maxBodyChars = input.max_body_chars ?? 20000;
const sources = Array.isArray(input.raw) ? input.raw : [input.raw];
const warnings = [];
const raws = [];
const requested = input.format ?? "auto";
let anyMbox = false;
for (const [i, src] of sources.entries()) {
if (typeof src !== "string") throw new AgentError("invalid_input", `raw[${i}] must be a string`);
const text = normalizeNewlines(src);
if (!text.trim()) { warnings.push(`Source ${i + 1} is empty`); continue; }
const asMbox = requested === "mbox" || (requested === "auto" && looksLikeMbox(text));
if (asMbox) {
anyMbox = true;
const parts = splitMbox(text);
if (!parts.length) warnings.push(`Source ${i + 1}: no messages found in mbox text`);
raws.push(...parts);
} else raws.push(text);
}
const format = anyMbox ? "mbox" : "eml";
const truncated = raws.length > maxMessages;
if (truncated) warnings.push(`Only the first ${maxMessages} of ${raws.length} messages were parsed`);
const seen = new Map();
const messages = raws.slice(0, maxMessages).map((raw) => {
const msg = parseMessage(raw, { maxBodyChars });
const n = (seen.get(msg.id) ?? 0) + 1;
seen.set(msg.id, n);
if (n > 1) {
msg.warnings.push(`Duplicate id ${msg.id}; renamed to ${msg.id}~${n}`);
msg.id = `${msg.id}~${n}`;
}
return msg;
});
return { count: messages.length, format, truncated, warnings, messages };
},
async triage(input, ctx) {
const now = nowMs(input, ctx);
if (Number.isNaN(now)) throw new AgentError("invalid_input", "now is not a valid date-time");
return triageMessages(input.messages, input.rules ?? {}, now);
},
async suggest_filters(input) {
const filters = suggestFilters(input.messages, input.triage ?? null, input.min_group_size ?? 2);
return {
applied: false,
note: "Suggestions only. Nothing was changed in any mailbox; review each rule and create it yourself in your mail client.",
filters,
};
},
};
const agent = defineAgent(manifest, handlers);
export default agent;
export { manifest, runCli, runMcpStdio, handleMcpMessage, validateManifest };