#!/usr/bin/env node /** * tb — Thunderbird AI CLI * * AI-agent-friendly CLI for managing email via Thunderbird. * All output is JSON by default. */ import { createRequire } from "module"; import { Command } from "commander"; import { api, output, outputError, getConfig, parseRelativeDate } from "./client.js"; import { attachDir, listAttachable, loadAttachments } from "./attachments.js"; const { version } = createRequire(import.meta.url)("../package.json"); const program = new Command(); program .name("tb") .description("AI-agent email management via Thunderbird") .version(version) .option("-f, --format ", "output format: json, compact, table", "json") .option("--fields ", "comma-separated fields to include in output") .option("--compact", "strip null values and minimize output") .option("--max-body ", "truncate message bodies to N characters") .option("--timeout ", "request timeout in milliseconds", "30000"); // ─── Helpers ────────────────────────────────────────────────────────── function getOutputOpts(globalOpts) { const opts = {}; if (globalOpts.fields) opts.fields = globalOpts.fields.split(",").map(s => s.trim()); if (globalOpts.compact) opts.compact = true; if (globalOpts.maxBody) opts.maxBody = parseInt(globalOpts.maxBody); return opts; } function getTimeout(globalOpts) { return parseInt(globalOpts.timeout) || 30000; } function run(fn) { return async (...args) => { try { await fn(...args); } catch (err) { outputError(err, program.opts().format); } }; } function parseMessageId(id) { const text = String(id).trim(); const value = Number(text); if (!/^\d+$/.test(text) || !Number.isSafeInteger(value) || value <= 0) { throw Object.assign(new Error(`Message IDs must be positive integers: ${id}`), { code: "INVALID_ARGS" }); } return value; } function parseIds(str) { return str.split(",").map(parseMessageId); } function parseCount(value, label = "Count") { const text = String(value).trim(); const number = Number(text); if (!/^\d+$/.test(text) || !Number.isSafeInteger(number)) { throw Object.assign(new Error(`${label} must be a nonnegative integer: ${value}`), { code: "INVALID_ARGS" }); } return number; } // ─── Health ─────────────────────────────────────────────────────────── program .command("health") .description("Check if Thunderbird bridge is running") .action(run(async () => { const g = program.opts(); const data = await api("GET", "/health", null, getTimeout(g)); output(data, g.format, getOutputOpts(g)); })); // ─── Bridge Status ──────────────────────────────────────────────────── program .command("bridge-status") .description("Get bridge status (works without extension)") .action(run(async () => { const g = program.opts(); const data = await api("GET", "/bridge/status", null, getTimeout(g)); output(data, g.format, getOutputOpts(g)); })); // ─── Accounts ───────────────────────────────────────────────────────── program .command("accounts") .description("List all email accounts") .action(run(async () => { const g = program.opts(); const data = await api("GET", "/accounts", null, getTimeout(g)); output(data, g.format, getOutputOpts(g)); })); program .command("account ") .description("Get account details") .action(run(async (accountId) => { const g = program.opts(); const data = await api("GET", `/accounts/${accountId}`, null, getTimeout(g)); output(data, g.format, getOutputOpts(g)); })); // ─── Account access (#18) ───────────────────────────────────────────── program .command("account-access") .description("Show which accounts the add-on lets agents see (set in the add-on's options in Thunderbird)") .action(run(async () => { const g = program.opts(); output(await api("GET", "/access", null, getTimeout(g)), g.format, getOutputOpts(g)); })); // ─── Identities ─────────────────────────────────────────────────────── program .command("identities") .description("List all identities") .action(run(async () => { const g = program.opts(); const data = await api("GET", "/identities", null, getTimeout(g)); output(data, g.format, getOutputOpts(g)); })); // ─── Folders ────────────────────────────────────────────────────────── program .command("folders [accountId]") .description("List folders for an account") .option("--all", "list folders across all accounts") .action(run(async (accountId, opts) => { const g = program.opts(); const fmt = g.format; const outOpts = getOutputOpts(g); const timeout = getTimeout(g); if (opts.all) { const accounts = await api("GET", "/accounts", null, timeout); const allFolders = []; for (const acct of accounts) { const folders = await api("GET", `/accounts/${acct.id}/folders`, null, timeout); for (const f of folders) allFolders.push({ ...f, accountId: acct.id }); } output(allFolders, fmt, outOpts); } else { if (!accountId) { outputError({ message: "Provide accountId or use --all", code: "INVALID_ARGS" }, fmt); return; } const data = await api("GET", `/accounts/${accountId}/folders`, null, timeout); output(data, fmt, outOpts); } })); // ─── Folder Info ────────────────────────────────────────────────────── program .command("folder-info ") .description("Get folder details") .action(run(async (folderId) => { const g = program.opts(); const data = await api("POST", "/folders/info", { folderId }, getTimeout(g)); output(data, g.format, getOutputOpts(g)); })); // ─── Folder Create ──────────────────────────────────────────────────── program .command("folder-create ") .description("Create a subfolder") .action(run(async (parentFolderId, name) => { const g = program.opts(); const data = await api("POST", "/folders/create", { parentFolderId, name }, getTimeout(g)); output(data, g.format, getOutputOpts(g)); })); // ─── Folder Rename ──────────────────────────────────────────────────── program .command("folder-rename ") .description("Rename a folder") .action(run(async (folderId, newName) => { const g = program.opts(); const data = await api("POST", "/folders/rename", { folderId, newName }, getTimeout(g)); output(data, g.format, getOutputOpts(g)); })); // ─── Folder Delete ──────────────────────────────────────────────────── program .command("folder-delete ") .description("Delete a folder") .option("--confirm", "required to confirm deletion") .action(run(async (folderId, opts) => { const g = program.opts(); const fmt = g.format; if (!opts.confirm) { outputError({ message: "Use --confirm to delete", code: "INVALID_ARGS" }, fmt); return; } const data = await api("POST", "/folders/delete", { folderId }, getTimeout(g)); output(data, fmt, getOutputOpts(g)); })); // ─── Stats ──────────────────────────────────────────────────────────── program .command("stats [accountId]") .description("Overview of all accounts (unread counts, totals)") .option("--folders", "include per-folder breakdown") .action(run(async (accountId, opts) => { const g = program.opts(); const timeout = getTimeout(g); if (accountId || opts.folders) { const body = {}; if (accountId) body.accountId = accountId; if (opts.folders) body.folders = true; const data = await api("POST", "/stats", body, timeout); output(data, g.format, getOutputOpts(g)); } else { const data = await api("GET", "/stats", null, timeout); output(data, g.format, getOutputOpts(g)); } })); // ─── Search ─────────────────────────────────────────────────────────── program .command("search ") .description("Search messages across all accounts") .option("-a, --account ", "limit to specific account") .option("--folder ", "limit to specific folder") .option("--from
", "filter by sender") .option("--to
", "filter by recipient") .option("--subject ", "filter by subject") .option("--unread", "unread only") .option("--flagged", "flagged only") .option("--tag ", "filter by tag") .option("--since ", "from date (ISO or relative: 7d, 2w, 3m, today, yesterday)") .option("--until ", "to date (ISO or relative)") .option("--has-attachment", "only messages with attachments") .option("--size-min ", "minimum message size") .option("--size-max ", "maximum message size") .option("--include-junk", "include junk/spam messages") .option("--body-only", "scan message bodies instead of Thunderbird's full-text index (slower)") .option("-l, --limit ", "max results", "25") .action(run(async (query, opts) => { const g = program.opts(); const body = { query, limit: parseInt(opts.limit), }; if (opts.account) body.accountId = opts.account; if (opts.folder) body.folderId = opts.folder; if (opts.from) body.fromAddress = opts.from; if (opts.to) body.toAddress = opts.to; if (opts.subject) body.subject = opts.subject; if (opts.unread) body.unreadOnly = true; if (opts.flagged) body.flagged = true; if (opts.tag) body.tag = opts.tag; if (opts.bodyOnly) body.searchMode = "body"; if (opts.since) body.fromDate = parseRelativeDate(opts.since); if (opts.until) body.toDate = parseRelativeDate(opts.until); if (opts.hasAttachment) body.hasAttachment = true; if (opts.sizeMin) body.sizeMin = parseInt(opts.sizeMin); if (opts.sizeMax) body.sizeMax = parseInt(opts.sizeMax); if (opts.includeJunk) body.includeJunk = true; const data = await api("POST", "/messages/search", body, getTimeout(g)); output(data, g.format, getOutputOpts(g)); })); // ─── List Messages ──────────────────────────────────────────────────── program .command("list ") .description("List messages in a folder") .option("--unread", "unread only") .option("--flagged", "flagged only") .option("--offset ", "skip first N messages") .option("--sort ", "sort by: date|from|subject|size") .option("--sort-order ", "sort direction: asc|desc") .option("-l, --limit ", "max results", "25") .action(run(async (folderId, opts) => { const g = program.opts(); const body = { folderId, limit: parseInt(opts.limit), }; if (opts.unread) body.unreadOnly = true; if (opts.flagged) body.flagged = true; if (opts.offset) body.offset = parseInt(opts.offset); if (opts.sort) body.sort = opts.sort; if (opts.sortOrder) body.sortOrder = opts.sortOrder; const data = await api("POST", "/messages/list", body, getTimeout(g)); output(data, g.format, getOutputOpts(g)); })); // ─── Read Message ───────────────────────────────────────────────────── program .command("read ") .description("Read a full message") .option("--raw", "get raw RFC822") .option("--headers", "headers only") .option("--full", "include HTML body") .option("--body-only", "just text body, no JSON wrapper") .option("--check-download", "check download state") .action(run(async (messageId, opts) => { const g = program.opts(); const timeout = getTimeout(g); const outOpts = getOutputOpts(g); if (opts.raw) { const data = await api("GET", `/messages/${parseMessageId(messageId)}/raw`, null, timeout); output(data, g.format, outOpts); } else if (opts.headers) { const data = await api("GET", `/messages/${parseMessageId(messageId)}/headers`, null, timeout); output(data, g.format, outOpts); } else if (opts.full) { const data = await api("GET", `/messages/${parseMessageId(messageId)}/full`, null, timeout); output(data, g.format, outOpts); } else if (opts.checkDownload) { const data = await api("GET", `/messages/${parseMessageId(messageId)}/check-download`, null, timeout); output(data, g.format, outOpts); } else if (opts.bodyOnly) { const data = await api("GET", `/messages/${parseMessageId(messageId)}`, null, timeout); output(data.parts?.text || data.body || "", g.format, { ...outOpts, raw: true }); } else { const data = await api("GET", `/messages/${parseMessageId(messageId)}`, null, timeout); output(data, g.format, outOpts); } })); // ─── Read Batch ─────────────────────────────────────────────────────── program .command("read-batch ") .description("Read multiple messages at once (comma-separated IDs)") .action(run(async (messageIds) => { const g = program.opts(); const ids = parseIds(messageIds); const data = await api("POST", "/messages/read-batch", { messageIds: ids }, getTimeout(g)); output(data, g.format, getOutputOpts(g)); })); // ─── Thread ─────────────────────────────────────────────────────────── program .command("thread ") .description("Get full conversation thread for a message") .option("--headers", "headers only for each message") .action(run(async (messageId) => { const g = program.opts(); const data = await api("GET", `/messages/${parseMessageId(messageId)}/thread`, null, getTimeout(g)); output(data, g.format, getOutputOpts(g)); })); // ─── Recent ─────────────────────────────────────────────────────────── program .command("recent") .description("Recent messages across all accounts") .option("--hours ", "hours to look back", "24") .option("--unread", "unread only") .option("--account ", "limit to specific account") .option("-l, --limit ", "max results", "50") .action(run(async (opts) => { const g = program.opts(); const body = { hours: parseInt(opts.hours), limit: parseInt(opts.limit), }; if (opts.unread) body.unreadOnly = true; if (opts.account) body.accountId = opts.account; const data = await api("POST", "/recent", body, getTimeout(g)); output(data, g.format, getOutputOpts(g)); })); // ─── Move ───────────────────────────────────────────────────────────── program .command("move ") .description("Move message(s) to folder (comma-separated IDs)") .action(run(async (messageIds, folderId) => { const g = program.opts(); const ids = parseIds(messageIds); const data = await api("POST", "/messages/move", { messageIds: ids, destinationFolderId: folderId, }, getTimeout(g)); output(data, g.format, getOutputOpts(g)); })); // ─── Copy ───────────────────────────────────────────────────────────── program .command("copy ") .description("Copy message(s) to folder (comma-separated IDs)") .action(run(async (messageIds, folderId) => { const g = program.opts(); const ids = parseIds(messageIds); const data = await api("POST", "/messages/copy", { messageIds: ids, destinationFolderId: folderId, }, getTimeout(g)); output(data, g.format, getOutputOpts(g)); })); // ─── Delete ─────────────────────────────────────────────────────────── program .command("delete ") .description("Delete message(s) (to trash)") .option("--permanent", "permanently delete (skip trash)") .option("--confirm", "required for permanent delete") .action(run(async (messageIds, opts) => { const g = program.opts(); const fmt = g.format; if (opts.permanent && !opts.confirm) { outputError({ message: "Use --confirm for permanent delete", code: "INVALID_ARGS" }, fmt); return; } const ids = parseIds(messageIds); const data = await api("POST", "/messages/delete", { messageIds: ids, permanent: opts.permanent || false, }, getTimeout(g)); output(data, fmt, getOutputOpts(g)); })); // ─── Archive ────────────────────────────────────────────────────────── program .command("archive ") .description("Archive message(s) (comma-separated IDs)") .action(run(async (messageIds) => { const g = program.opts(); const ids = parseIds(messageIds); const data = await api("POST", "/messages/archive", { messageIds: ids }, getTimeout(g)); output(data, g.format, getOutputOpts(g)); })); // ─── Mark ───────────────────────────────────────────────────────────── program .command("mark ") .description("Update message flags (comma-separated IDs for batch)") .option("--read", "mark as read") .option("--unread", "mark as unread") .option("--flagged", "flag message") .option("--unflagged", "remove flag") .option("--junk", "mark as junk") .option("--not-junk", "mark as not junk") .action(run(async (messageIds, opts) => { const g = program.opts(); const ids = parseIds(messageIds); const timeout = getTimeout(g); const flags = {}; if (opts.read) flags.read = true; if (opts.unread) flags.read = false; if (opts.flagged) flags.flagged = true; if (opts.unflagged) flags.flagged = false; if (opts.junk) flags.junk = true; if (opts.notJunk) flags.junk = false; if (ids.length === 1) { const data = await api("POST", "/messages/update", { messageId: ids[0], ...flags }, timeout); output(data, g.format, getOutputOpts(g)); } else { const results = []; for (const id of ids) { const data = await api("POST", "/messages/update", { messageId: id, ...flags }, timeout); results.push(data); } output(results, g.format, getOutputOpts(g)); } })); // ─── Tags ───────────────────────────────────────────────────────────── program .command("tags") .description("List available tags") .action(run(async () => { const g = program.opts(); const data = await api("GET", "/tags", null, getTimeout(g)); output(data, g.format, getOutputOpts(g)); })); // ─── Tag ────────────────────────────────────────────────────────────── program .command("tag ") .description("Add/remove tag on a message") .option("--remove", "remove tag instead of adding") .action(run(async (messageId, tag, opts) => { const g = program.opts(); const timeout = getTimeout(g); const msg = await api("GET", `/messages/${parseMessageId(messageId)}`, null, timeout); let tags = msg.tags || []; if (opts.remove) { tags = tags.filter(t => t !== tag); } else { if (!tags.includes(tag)) tags.push(tag); } const data = await api("POST", "/messages/update", { messageId: parseMessageId(messageId), tags, }, timeout); output(data, g.format, getOutputOpts(g)); })); // ─── Tag Create ─────────────────────────────────────────────────────── program .command("tag-create