Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat: add email cli subcommands

Gus9ef8e7fd3a3f
diff --git a/src/cli/commands/email.test.ts b/src/cli/commands/email.test.ts
index 532f20765..340ebfaa3 100644
--- a/src/cli/commands/email.test.ts
+++ b/src/cli/commands/email.test.ts
@@ -4,10 +4,11 @@ import { join } from "path";
import PostalMime from "postal-mime";
import { Command } from "commander";
-const { postMultipartMock, postJSONMock, getJSONMock, deleteJSONMock } = vi.hoisted(() => ({
+const { postMultipartMock, postJSONMock, getJSONMock, getTextMock, deleteJSONMock } = vi.hoisted(() => ({
postMultipartMock: vi.fn(),
postJSONMock: vi.fn(),
getJSONMock: vi.fn(),
+ getTextMock: vi.fn(),
deleteJSONMock: vi.fn(),
}));
@@ -22,6 +23,9 @@ vi.mock("../lib/client.js", () => ({
getJSON(...a: unknown[]) {
return getJSONMock(...a);
}
+ getText(...a: unknown[]) {
+ return getTextMock(...a);
+ }
deleteJSON(...a: unknown[]) {
return deleteJSONMock(...a);
}
@@ -475,6 +479,445 @@ describe("email send behavior", () => {
});
});
+// --- Forward tests ---
+
+async function runForward(args: string[]): Promise<{ out: string[]; err: string[]; exitCode: number | null }> {
+ const out: string[] = [];
+ const err: string[] = [];
+ let exitCode: number | null = null;
+ const logSpy = vi.spyOn(console, "log").mockImplementation((m: unknown) => {
+ out.push(String(m));
+ });
+ const errSpy = vi.spyOn(console, "error").mockImplementation((m: unknown) => {
+ err.push(String(m));
+ });
+ const exitSpy = vi.spyOn(process, "exit").mockImplementation(((code?: number) => {
+ exitCode = code ?? 0;
+ throw new Error("__exit__");
+ }) as never);
+ try {
+ const program = new Command()
+ .name("alook")
+ .option("--server <url>", "Server URL")
+ .option("--profile <name>", "Profile name");
+ program.addCommand(emailCommand());
+ await program.parseAsync(["email", "forward", ...args], { from: "user" });
+ } catch (e) {
+ if (!(e instanceof Error) || e.message !== "__exit__") throw e;
+ } finally {
+ logSpy.mockRestore();
+ errSpy.mockRestore();
+ exitSpy.mockRestore();
+ }
+ return { out, err, exitCode };
+}
+
+async function runPull(args: string[]): Promise<{ out: string[]; err: string[]; exitCode: number | null }> {
+ const out: string[] = [];
+ const err: string[] = [];
+ let exitCode: number | null = null;
+ const logSpy = vi.spyOn(console, "log").mockImplementation((m: unknown) => {
+ out.push(String(m));
+ });
+ const errSpy = vi.spyOn(console, "error").mockImplementation((m: unknown) => {
+ err.push(String(m));
+ });
+ const exitSpy = vi.spyOn(process, "exit").mockImplementation(((code?: number) => {
+ exitCode = code ?? 0;
+ throw new Error("__exit__");
+ }) as never);
+ try {
+ const program = new Command()
+ .name("alook")
+ .option("--server <url>", "Server URL")
+ .option("--profile <name>", "Profile name");
+ program.addCommand(emailCommand());
+ await program.parseAsync(["email", "pull", ...args], { from: "user" });
+ } catch (e) {
+ if (!(e instanceof Error) || e.message !== "__exit__") throw e;
+ } finally {
+ logSpy.mockRestore();
+ errSpy.mockRestore();
+ exitSpy.mockRestore();
+ }
+ return { out, err, exitCode };
+}
+
+const FORWARD_TMP = "/tmp/alook-email-forward-test";
+
+function makeOriginalEmail(overrides: Partial<Record<string, unknown>> = {}) {
+ return {
+ id: "em_orig",
+ agent_id: "ag_1",
+ from_email: "[email protected]",
+ to_email: "[email protected]",
+ subject: "Original Subject",
+ r2_key: "emails/em_orig",
+ is_whitelisted: true,
+ forwarded: false,
+ message_id: "<[email protected]>",
+ in_reply_to: "",
+ references: "",
+ html_body: "<p>Hello</p>",
+ attachments: [],
+ status: "read",
+ created_at: "2026-04-20T10:00:00Z",
+ ...overrides,
+ };
+}
+
+function makeRawMime(opts: { html?: string; text?: string; attachment?: boolean } = {}) {
+ if (opts.attachment) {
+ const boundary = "----=_Part_fwd";
+ const parts = [];
+ if (opts.html) {
+ parts.push(
+ `--${boundary}\r\nContent-Type: text/html; charset=utf-8\r\n\r\n${opts.html}`,
+ );
+ } else if (opts.text) {
+ parts.push(
+ `--${boundary}\r\nContent-Type: text/plain\r\n\r\n${opts.text}`,
+ );
+ }
+ parts.push(
+ `--${boundary}\r\nContent-Type: application/pdf\r\nContent-Disposition: attachment; filename="original.pdf"\r\nContent-Transfer-Encoding: base64\r\n\r\n${Buffer.from("pdf-content").toString("base64")}`,
+ );
+ return `From: [email protected]\r\nTo: [email protected]\r\nSubject: Original Subject\r\nContent-Type: multipart/mixed; boundary="${boundary}"\r\n\r\n${parts.join("\r\n")}\r\n--${boundary}--`;
+ }
+ if (opts.html) {
+ return `From: [email protected]\r\nTo: [email protected]\r\nSubject: Original Subject\r\nContent-Type: text/html; charset=utf-8\r\n\r\n${opts.html}`;
+ }
+ return `From: [email protected]\r\nTo: [email protected]\r\nSubject: Original Subject\r\nContent-Type: text/plain\r\n\r\n${opts.text || "Hello world"}`;
+}
+
+describe("email forward subcommand shape", () => {
+ const cmd = emailCommand();
+ const forward = cmd.commands.find((c) => c.name() === "forward")!;
+
+ it("is registered", () => {
+ expect(forward).toBeDefined();
+ });
+
+ it("requires --agent_id, --email_id, --to", () => {
+ const opts = (forward as unknown as { options: { long: string; mandatory?: boolean }[] }).options;
+ const mandatory = opts.filter((o) => o.mandatory).map((o) => o.long);
+ expect(mandatory).toContain("--agent_id");
+ expect(mandatory).toContain("--email_id");
+ expect(mandatory).toContain("--to");
+ });
+
+ it("accepts --from, --note, --attachment, --workspace as optional", () => {
+ const opts = (forward as unknown as { options: { long: string; mandatory?: boolean }[] }).options;
+ const longs = opts.map((o) => o.long);
+ const mandatory = opts.filter((o) => o.mandatory).map((o) => o.long);
+ expect(longs).toContain("--from");
+ expect(longs).toContain("--note");
+ expect(longs).toContain("--attachment");
+ expect(longs).toContain("--workspace");
+ expect(mandatory).not.toContain("--from");
+ expect(mandatory).not.toContain("--note");
+ expect(mandatory).not.toContain("--attachment");
+ expect(mandatory).not.toContain("--workspace");
+ });
+});
+
+describe("email forward behavior", () => {
+ beforeEach(() => {
+ mkdirSync(FORWARD_TMP, { recursive: true });
+ postMultipartMock.mockReset();
+ postJSONMock.mockReset();
+ getJSONMock.mockReset();
+ getTextMock.mockReset();
+ });
+
+ afterEach(() => {
+ rmSync(FORWARD_TMP, { recursive: true, force: true });
+ });
+
+ it("fetches original email, parses MIME, re-uploads attachments, and sends", async () => {
+ getJSONMock.mockResolvedValueOnce(makeOriginalEmail());
+ getTextMock.mockResolvedValueOnce(makeRawMime({ html: "<p>Hello</p>", attachment: true }));
+ postMultipartMock.mockResolvedValueOnce({
+ key: "emails/drafts/x/original.pdf",
+ filename: "original.pdf",
+ size: 11,
+ contentType: "application/pdf",
+ });
+ postJSONMock.mockResolvedValueOnce({ id: "em_fwd1", to_email: "[email protected]" });
+
+ const { out, exitCode } = await runForward([
+ "--agent_id", "ag_1",
+ "--email_id", "em_orig",
+ "--to", "[email protected]",
+ ]);
+
+ expect(exitCode).toBeNull();
+ expect(getJSONMock).toHaveBeenCalledWith("/api/email/em_orig");
+ expect(getTextMock).toHaveBeenCalledWith("/api/email/em_orig/raw");
+ expect(postMultipartMock).toHaveBeenCalledTimes(1);
+ expect(postJSONMock).toHaveBeenCalledTimes(1);
+
+ const payload = postJSONMock.mock.calls[0][1] as Record<string, unknown>;
+ expect(payload.subject).toBe("Fwd: Original Subject");
+ expect((payload.htmlBody as string)).toContain("---------- Forwarded message ----------");
+ expect((payload.htmlBody as string)).toContain("[email protected]");
+ expect((payload.attachments as unknown[]).length).toBe(1);
+ expect(out.join("\n")).toContain("Forwarded email to [email protected]");
+ });
+
+ it("prepends note when --note is provided", async () => {
+ getJSONMock.mockResolvedValueOnce(makeOriginalEmail());
+ getTextMock.mockResolvedValueOnce(makeRawMime({ html: "<p>Content</p>" }));
+ postJSONMock.mockResolvedValueOnce({ id: "em_fwd2", to_email: "[email protected]" });
+
+ const { exitCode } = await runForward([
+ "--agent_id", "ag_1",
+ "--email_id", "em_orig",
+ "--to", "[email protected]",
+ "--note", "FYI see below",
+ ]);
+
+ expect(exitCode).toBeNull();
+ const payload = postJSONMock.mock.calls[0][1] as Record<string, unknown>;
+ const body = payload.htmlBody as string;
+ expect(body).toMatch(/^<p>FYI see below<\/p>/);
+ expect(body).toContain("---------- Forwarded message ----------");
+ });
+
+ it("has no extra prefix without --note", async () => {
+ getJSONMock.mockResolvedValueOnce(makeOriginalEmail());
+ getTextMock.mockResolvedValueOnce(makeRawMime({ html: "<p>Content</p>" }));
+ postJSONMock.mockResolvedValueOnce({ id: "em_fwd3", to_email: "[email protected]" });
+
+ const { exitCode } = await runForward([
+ "--agent_id", "ag_1",
+ "--email_id", "em_orig",
+ "--to", "[email protected]",
+ ]);
+
+ expect(exitCode).toBeNull();
+ const payload = postJSONMock.mock.calls[0][1] as Record<string, unknown>;
+ const body = payload.htmlBody as string;
+ expect(body).not.toMatch(/^<p>/);
+ expect(body).toMatch(/^<br><br>---------- Forwarded message ----------/);
+ });
+
+ it("handles plain-text-only original email", async () => {
+ getJSONMock.mockResolvedValueOnce(makeOriginalEmail());
+ getTextMock.mockResolvedValueOnce(makeRawMime({ text: "Plain text body" }));
+ postJSONMock.mockResolvedValueOnce({ id: "em_fwd4", to_email: "[email protected]" });
+
+ const { exitCode } = await runForward([
+ "--agent_id", "ag_1",
+ "--email_id", "em_orig",
+ "--to", "[email protected]",
+ ]);
+
+ expect(exitCode).toBeNull();
+ const payload = postJSONMock.mock.calls[0][1] as Record<string, unknown>;
+ const body = payload.htmlBody as string;
+ expect(body).toContain("<pre>Plain text body");
+ expect(body).toContain("</pre>");
+ });
+
+ it("preserves subject prefix — no double Fwd:", async () => {
+ getJSONMock.mockResolvedValueOnce(makeOriginalEmail({ subject: "Fwd: Already forwarded" }));
+ getTextMock.mockResolvedValueOnce(makeRawMime({ html: "<p>Hi</p>" }));
+ postJSONMock.mockResolvedValueOnce({ id: "em_fwd5", to_email: "[email protected]" });
+
+ const { exitCode } = await runForward([
+ "--agent_id", "ag_1",
+ "--email_id", "em_orig",
+ "--to", "[email protected]",
+ ]);
+
+ expect(exitCode).toBeNull();
+ const payload = postJSONMock.mock.calls[0][1] as Record<string, unknown>;
+ expect(payload.subject).toBe("Fwd: Already forwarded");
+ });
+
+ it("passes --from to send payload when provided", async () => {
+ getJSONMock.mockResolvedValueOnce(makeOriginalEmail());
+ getTextMock.mockResolvedValueOnce(makeRawMime({ html: "<p>Hi</p>" }));
+ postJSONMock.mockResolvedValueOnce({ id: "em_fwd6", to_email: "[email protected]" });
+
+ const { exitCode } = await runForward([
+ "--agent_id", "ag_1",
+ "--email_id", "em_orig",
+ "--to", "[email protected]",
+ "--from", "[email protected]",
+ ]);
+
+ expect(exitCode).toBeNull();
+ const payload = postJSONMock.mock.calls[0][1] as Record<string, unknown>;
+ expect(payload.from).toBe("[email protected]");
+ });
+
+ it("adds extra --attachment files alongside original attachments", async () => {
+ getJSONMock.mockResolvedValueOnce(makeOriginalEmail());
+ getTextMock.mockResolvedValueOnce(makeRawMime({ html: "<p>Hi</p>", attachment: true }));
+ postMultipartMock
+ .mockResolvedValueOnce({ key: "emails/drafts/x/original.pdf", filename: "original.pdf", size: 11, contentType: "application/pdf" })
+ .mockResolvedValueOnce({ key: "emails/drafts/y/extra.pdf", filename: "extra.pdf", size: 5, contentType: "application/pdf" });
+ postJSONMock.mockResolvedValueOnce({ id: "em_fwd7", to_email: "[email protected]" });
+
+ const extraPath = join(FORWARD_TMP, "extra.pdf");
+ writeFileSync(extraPath, "extra");
+
+ const { exitCode } = await runForward([
+ "--agent_id", "ag_1",
+ "--email_id", "em_orig",
+ "--to", "[email protected]",
+ "--attachment", extraPath,
+ ]);
+
+ expect(exitCode).toBeNull();
+ expect(postMultipartMock).toHaveBeenCalledTimes(2);
+ const payload = postJSONMock.mock.calls[0][1] as Record<string, unknown>;
+ expect((payload.attachments as unknown[]).length).toBe(2);
+ });
+
+ it("errors when original email not found (404)", async () => {
+ getJSONMock.mockRejectedValueOnce(new Error("HTTP 404: not found"));
+
+ const { err, exitCode } = await runForward([
+ "--agent_id", "ag_1",
+ "--email_id", "em_missing",
+ "--to", "[email protected]",
+ ]);
+
+ expect(exitCode).toBe(1);
+ expect(err.join("\n")).toContain("not found");
+ });
+
+ it("errors when raw MIME not available (404)", async () => {
+ getJSONMock.mockResolvedValueOnce(makeOriginalEmail());
+ getTextMock.mockRejectedValueOnce(new Error("HTTP 404: not found"));
+
+ const { err, exitCode } = await runForward([
+ "--agent_id", "ag_1",
+ "--email_id", "em_orig",
+ "--to", "[email protected]",
+ ]);
+
+ expect(exitCode).toBe(1);
+ expect(err.join("\n")).toContain("raw email body not available");
+ });
+});
+
+describe("email pull with --folder", () => {
+ beforeEach(() => {
+ getJSONMock.mockReset();
+ getTextMock.mockReset();
+ });
+
+ it("passes folder param to API when --folder sent", async () => {
+ getJSONMock.mockResolvedValueOnce([]);
+
+ const { exitCode } = await runPull(["--agent_id", "ag_1", "--folder", "sent"]);
+
+ expect(exitCode).toBeNull();
+ expect(getJSONMock).toHaveBeenCalledWith("/api/email?agentId=ag_1&folder=sent");
+ });
+
+ it("rejects invalid --folder value", async () => {
+ const { err, exitCode } = await runPull(["--agent_id", "ag_1", "--folder", "invalid"]);
+
+ expect(exitCode).toBe(1);
+ expect(err.join("\n")).toContain("invalid folder");
+ expect(err.join("\n")).toContain("inbox, sent, untrust");
+ });
+
+ it("does not include folder param without --folder (preserves default)", async () => {
+ getJSONMock.mockResolvedValueOnce([]);
+
+ const { exitCode } = await runPull(["--agent_id", "ag_1"]);
+
+ expect(exitCode).toBeNull();
+ expect(getJSONMock).toHaveBeenCalledWith("/api/email?agentId=ag_1");
+ });
+});
+
+describe("email pull with --limit and --offset", () => {
+ beforeEach(() => {
+ getJSONMock.mockReset();
+ getTextMock.mockReset();
+ });
+
+ it("passes limit param to API when --limit 10", async () => {
+ getJSONMock.mockResolvedValueOnce([]);
+
+ const { exitCode } = await runPull(["--agent_id", "ag_1", "--limit", "10"]);
+
+ expect(exitCode).toBeNull();
+ expect(getJSONMock).toHaveBeenCalledWith("/api/email?agentId=ag_1&limit=10");
+ });
+
+ it("passes both limit and offset to API", async () => {
+ getJSONMock.mockResolvedValueOnce([]);
+
+ const { exitCode } = await runPull(["--agent_id", "ag_1", "--limit", "10", "--offset", "20"]);
+
+ expect(exitCode).toBeNull();
+ expect(getJSONMock).toHaveBeenCalledWith("/api/email?agentId=ag_1&limit=10&offset=20");
+ });
+
+ it("rejects --limit 0", async () => {
+ const { err, exitCode } = await runPull(["--agent_id", "ag_1", "--limit", "0"]);
+
+ expect(exitCode).toBe(1);
+ expect(err.join("\n")).toContain("--limit must be an integer between 1 and 100");
+ });
+
+ it("rejects negative --limit", async () => {
+ const { err, exitCode } = await runPull(["--agent_id", "ag_1", "--limit", "-5"]);
+
+ expect(exitCode).toBe(1);
+ expect(err.join("\n")).toContain("--limit must be an integer between 1 and 100");
+ });
+
+ it("rejects non-numeric --limit", async () => {
+ const { err, exitCode } = await runPull(["--agent_id", "ag_1", "--limit", "abc"]);
+
+ expect(exitCode).toBe(1);
+ expect(err.join("\n")).toContain("--limit must be an integer between 1 and 100");
+ });
+
+ it("rejects --limit over 100", async () => {
+ const { err, exitCode } = await runPull(["--agent_id", "ag_1", "--limit", "200"]);
+
+ expect(exitCode).toBe(1);
+ expect(err.join("\n")).toContain("--limit must be an integer between 1 and 100");
+ });
+
+ it("rejects negative --offset", async () => {
+ const { err, exitCode } = await runPull(["--agent_id", "ag_1", "--offset", "-1"]);
+
+ expect(exitCode).toBe(1);
+ expect(err.join("\n")).toContain("--offset must be a non-negative integer");
+ });
+
+ it("does not include limit/offset params when not specified", async () => {
+ getJSONMock.mockResolvedValueOnce([]);
+
+ const { exitCode } = await runPull(["--agent_id", "ag_1"]);
+
+ expect(exitCode).toBeNull();
+ const calledUrl = getJSONMock.mock.calls[0][0] as string;
+ expect(calledUrl).not.toContain("limit");
+ expect(calledUrl).not.toContain("offset");
+ });
+
+ it("combines --limit with --folder and --status", async () => {
+ getJSONMock.mockResolvedValueOnce([]);
+
+ const { exitCode } = await runPull(["--agent_id", "ag_1", "--status", "unread", "--folder", "sent", "--limit", "5"]);
+
+ expect(exitCode).toBeNull();
+ expect(getJSONMock).toHaveBeenCalledWith("/api/email?agentId=ag_1&status=unread&folder=sent&limit=5");
+ });
+});
+
// --- Whitelist tests ---
async function runWhitelist(args: string[]): Promise<{ out: string[]; err: string[]; exitCode: number | null }> {
diff --git a/src/cli/commands/email.ts b/src/cli/commands/email.ts
index 10c942749..b0bb33486 100644
--- a/src/cli/commands/email.ts
+++ b/src/cli/commands/email.ts
@@ -26,6 +26,7 @@ interface EmailResponse {
}
const VALID_STATUSES = ["unread", "read", "archived", "sent"];
+const VALID_FOLDERS = ["inbox", "sent", "untrust"];
const EMAIL_BASE = "/tmp/alook-emails";
const MIME_BY_EXT: Record<string, string> = {
@@ -132,6 +133,9 @@ export function emailCommand(): Command {
.description("Download and parse emails to /tmp/alook-emails/{workspaceId}/{agentId}/")
.requiredOption("--agent_id <id>", "Agent ID")
.option("--status <status>", "Filter by status (unread, read, archived)")
+ .option("--folder <folder>", "Email folder (inbox, sent, untrust)")
+ .option("--limit <n>", "Maximum number of emails to download")
+ .option("--offset <n>", "Number of emails to skip")
.option("--workspace <id>", "Workspace ID")
.option("--json", "Output as JSON instead of files")
.action(async (opts, command) => {
@@ -145,11 +149,37 @@ export function emailCommand(): Command {
process.exit(1);
}
+ if (opts.folder && !VALID_FOLDERS.includes(opts.folder)) {
+ console.error(
+ `Error: invalid folder "${opts.folder}", must be one of: ${VALID_FOLDERS.join(", ")}`,
+ );
+ process.exit(1);
+ }
+
+ if (opts.limit != null) {
+ const n = parseInt(opts.limit, 10);
+ if (isNaN(n) || n < 1 || n > 100) {
+ console.error(`Error: --limit must be an integer between 1 and 100`);
+ process.exit(1);
+ }
+ }
+
+ if (opts.offset != null) {
+ const n = parseInt(opts.offset, 10);
+ if (isNaN(n) || n < 0) {
+ console.error(`Error: --offset must be a non-negative integer`);
+ process.exit(1);
+ }
+ }
+
const emailDir_base = join(EMAIL_BASE, workspaceId, opts.agent_id);
try {
let query = `/api/email?agentId=${opts.agent_id}`;
if (opts.status) query += `&status=${opts.status}`;
+ if (opts.folder) query += `&folder=${opts.folder}`;
+ if (opts.limit) query += `&limit=${opts.limit}`;
+ if (opts.offset) query += `&offset=${opts.offset}`;
const emails = await client.getJSON<EmailResponse[]>(query);
@@ -391,6 +421,167 @@ export function emailCommand(): Command {
}
});
+ cmd
+ .command("forward")
+ .description("Forward an email to a new recipient")
+ .requiredOption("--agent_id <id>", "Agent ID")
+ .requiredOption("--email_id <id>", "Source email ID to forward")
+ .requiredOption("--to <addr>", "Recipient email address")
+ .option("--from <addr>", "Send from a specific email address (custom mailbox)")
+ .option("--note <text>", "Text to prepend above the forwarded message")
+ .option(
+ "--attachment <path>",
+ "Extra file to attach (repeatable)",
+ collectRepeated,
+ [] as string[],
+ )
+ .option("--workspace <id>", "Workspace ID")
+ .action(async (opts, command) => {
+ const { serverUrl, token, workspaceId } = resolveClientOpts(command, {
+ workspace: opts.workspace,
+ agentId: opts.agent_id,
+ });
+ const client = new APIClient(serverUrl, token, workspaceId);
+
+ try {
+ // 1. Fetch original email metadata
+ let original: EmailResponse;
+ try {
+ original = await client.getJSON<EmailResponse>(`/api/email/${opts.email_id}`);
+ } catch (err) {
+ const msg = err instanceof Error ? err.message : String(err);
+ if (msg.includes("404")) {
+ console.error(`Error: email ${opts.email_id} not found`);
+ process.exit(1);
+ }
+ throw err;
+ }
+
+ // 2. Fetch raw MIME
+ let rawMime: string;
+ try {
+ rawMime = await client.getText(`/api/email/${opts.email_id}/raw`);
+ } catch (err) {
+ const msg = err instanceof Error ? err.message : String(err);
+ if (msg.includes("404")) {
+ console.error(`Error: raw email body not available for ${opts.email_id}`);
+ process.exit(1);
+ }
+ throw err;
+ }
+
+ // 3. Parse MIME to extract body and attachments
+ const parsed = await new PostalMime().parse(rawMime);
+
+ // 4. Re-upload original attachments
+ const attachments: AttachmentDescriptor[] = [];
+ if (parsed.attachments && parsed.attachments.length > 0) {
+ for (const att of parsed.attachments) {
+ const filename = att.filename || "attachment.bin";
+ const contentType = att.mimeType || "application/octet-stream";
+ const content = att.content;
+ let buf: Buffer;
+ if (typeof content === "string") {
+ buf = Buffer.from(content, "base64");
+ } else if (content instanceof ArrayBuffer) {
+ buf = Buffer.from(new Uint8Array(content));
+ } else {
+ buf = Buffer.from(content as Uint8Array);
+ }
+ const form = new FormData();
+ form.append(
+ "file",
+ new Blob([new Uint8Array(buf)], { type: contentType }),
+ filename,
+ );
+ const uploaded = await client.postMultipart<AttachmentDescriptor>(
+ "/api/email/upload",
+ form,
+ );
+ attachments.push({
+ key: uploaded.key,
+ filename: uploaded.filename,
+ size: uploaded.size ?? buf.byteLength,
+ contentType: uploaded.contentType ?? contentType,
+ });
+ }
+ }
+
+ // 5. Upload extra --attachment files
+ const extraPaths: string[] = opts.attachment ?? [];
+ for (const path of extraPaths) {
+ let bytes: Buffer;
+ let size: number;
+ try {
+ bytes = readFileSync(path);
+ size = statSync(path).size;
+ } catch (err) {
+ console.error(
+ `Error: cannot read attachment "${path}": ${err instanceof Error ? err.message : err}`,
+ );
+ process.exit(1);
+ }
+ const filename = basename(path);
+ const contentType = guessContentType(filename);
+ const form = new FormData();
+ form.append(
+ "file",
+ new Blob([new Uint8Array(bytes)], { type: contentType }),
+ filename,
+ );
+ const uploaded = await client.postMultipart<AttachmentDescriptor>(
+ "/api/email/upload",
+ form,
+ );
+ attachments.push({
+ key: uploaded.key,
+ filename: uploaded.filename,
+ size: uploaded.size ?? size,
+ contentType: uploaded.contentType ?? contentType,
+ });
+ }
+
+ // 6. Compose forwarded HTML body
+ let htmlBody = "";
+ if (opts.note) {
+ htmlBody += `<p>${opts.note}</p>`;
+ }
+ htmlBody += `<br><br>---------- Forwarded message ----------<br>`;
+ htmlBody += `From: ${original.from_email}<br>`;
+ htmlBody += `Date: ${original.created_at}<br>`;
+ htmlBody += `Subject: ${original.subject}<br>`;
+ htmlBody += `To: ${original.to_email}<br><br>`;
+ if (parsed.html) {
+ htmlBody += parsed.html;
+ } else if (parsed.text) {
+ htmlBody += `<pre>${parsed.text}</pre>`;
+ }
+
+ // 7. Build subject
+ const subject = /^fwd:/i.test(original.subject)
+ ? original.subject
+ : `Fwd: ${original.subject}`;
+
+ // 8. Send
+ const conversationId = process.env.ALOOK_CONVERSATION_ID;
+ const res = await client.postJSON<SendResponse>("/api/email/send", {
+ agentId: opts.agent_id,
+ to: opts.to,
+ subject,
+ htmlBody,
+ attachments,
+ ...(opts.from ? { from: opts.from } : {}),
+ ...(conversationId ? { conversationId } : {}),
+ });
+ console.log(`Forwarded email to ${res.to_email} (id: ${res.id})`);
+ } catch (err) {
+ const msg = err instanceof Error ? err.message : String(err);
+ if (msg === "__exit__") throw err;
+ console.error(`Error: ${msg}`);
+ process.exit(1);
+ }
+ });
+
const whitelistCmd = new Command("whitelist").description(
"Manage email whitelist (allowed senders)",
);
diff --git a/src/cli/daemon/execenv/context.ts b/src/cli/daemon/execenv/context.ts
index 1b4f16646..4d00f66c4 100644
--- a/src/cli/daemon/execenv/context.ts
+++ b/src/cli/daemon/execenv/context.ts
@@ -102,14 +102,20 @@ Your alook agent id is '${task.agentId}'. remember this, most of alook cli will
### Emails
---
-Run 'npx @alook/cli email pull --agent_id ${task.agentId} --status unread' to download unread emails to '/tmp/alook-emails/${task.workspaceId}/${task.agentId}/'.
+Run 'npx @alook/cli email pull --agent_id ${task.agentId} --status unread' to download unread emails from inbox to '/tmp/alook-emails/${task.workspaceId}/${task.agentId}/'.
+---
+To download sent emails, add '--folder sent': 'npx @alook/cli email pull --agent_id ${task.agentId} --folder sent'
+Valid folders: inbox (default), sent, untrust.
+To limit the number of emails downloaded, add '--limit <N>' (e.g. '--limit 20'). Use '--offset <N>' to skip emails for pagination.
+Example: 'npx @alook/cli email pull --agent_id ${task.agentId} --status unread --limit 20 --offset 0'
+---
Each email is saved to '/tmp/alook-emails/${task.workspaceId}/${task.agentId}/<emailId>/' with:
- 'metadata.json' — sender, recipient, subject, date, status, message_id, in_reply_to, references
- 'body.txt' — plain text body
- 'body.html' — HTML body (if available)
- 'attachments/' — extracted attachment files (if any)
---
-Before starting to process an email, mark it as read:
+Before starting to process an INBOX email, mark it as read:
- Run 'npx @alook/cli email set --agent_id ${task.agentId} --email_id <EMAIL_ID> --status read'
---
@@ -130,6 +136,15 @@ Tips:
- If you think the task will take a while, consider sending a short "I'm on it" style email reply first to reassure the sender.
---
+#### Forwarding an email
+Forward any email to a new recipient, with an optional note prepended above the original content. All original attachments are re-attached automatically.
+- Run 'npx @alook/cli email forward --agent_id ${task.agentId} --email_id <EMAIL_ID> --to <RECIPIENT>'
+- Add '--note "FYI, see the request below."' to prepend a note above the forwarded body.
+- Add '--from <YOUR_EMAIL_ADDRESS>' to send from a specific mailbox.
+- Add '--attachment <PATH>' to attach extra files (repeatable).
+- Example: 'npx @alook/cli email forward --agent_id ${task.agentId} --email_id em_abc --to [email protected] --note "FYI" --attachment /tmp/summary.pdf'
+---
+
#### Email Whitelist (Allowed Senders)
Manage which email addresses are allowed to send you emails.
- List: 'npx @alook/cli email whitelist list --agent_id ${task.agentId}' (add '--json' for machine-readable output)
diff --git a/src/shared/src/db/queries/email.ts b/src/shared/src/db/queries/email.ts
index 436d19a74..29b432655 100644
--- a/src/shared/src/db/queries/email.ts
+++ b/src/shared/src/db/queries/email.ts
@@ -3,6 +3,11 @@ import { emails } from "../schema";
import type { Database } from "../index";
import type { EmailDirection } from "../../types";
+export interface EmailPagination {
+ limit: number;
+ offset: number;
+}
+
export async function createEmail(
db: Database,
data: { agentId: string; workspaceId: string; fromEmail: string; toEmail: string; subject: string; r2Key: string; isWhitelisted: boolean; forwarded: boolean; direction: EmailDirection; messageId?: string; inReplyTo?: string; references?: string; htmlBody?: string; attachments?: string; status?: string }
@@ -16,46 +21,56 @@ export async function getEmailById(db: Database, id: string, workspaceId: string
return rows[0] ?? null;
}
-export async function getEmailsByAgent(db: Database, agentId: string, workspaceId: string, status?: string) {
+export async function getEmailsByAgent(db: Database, agentId: string, workspaceId: string, status?: string, pagination?: EmailPagination) {
const conditions = [eq(emails.agentId, agentId), eq(emails.workspaceId, workspaceId)];
if (status) conditions.push(eq(emails.status, status));
- return db
+ const q = db
.select()
.from(emails)
.where(and(...conditions))
.orderBy(desc(emails.createdAt));
+ if (pagination) return q.limit(pagination.limit).offset(pagination.offset);
+ return q;
}
-export async function getInboxEmails(db: Database, agentId: string, agentEmail: string, workspaceId: string, status?: string) {
+export async function getInboxEmails(db: Database, agentId: string, agentEmail: string, workspaceId: string, status?: string, pagination?: EmailPagination) {
const conditions = [eq(emails.agentId, agentId), eq(emails.toEmail, agentEmail), eq(emails.workspaceId, workspaceId), eq(emails.direction, "inbound")];
if (status) conditions.push(eq(emails.status, status));
- return db.select().from(emails)
+ const q = db.select().from(emails)
.where(and(...conditions))
.orderBy(desc(emails.createdAt));
+ if (pagination) return q.limit(pagination.limit).offset(pagination.offset);
+ return q;
}
-export async function getSentEmails(db: Database, agentId: string, agentEmail: string, workspaceId: string, status?: string) {
+export async function getSentEmails(db: Database, agentId: string, agentEmail: string, workspaceId: string, status?: string, pagination?: EmailPagination) {
const conditions = [eq(emails.agentId, agentId), eq(emails.fromEmail, agentEmail), eq(emails.workspaceId, workspaceId), eq(emails.direction, "outbound")];
if (status) conditions.push(eq(emails.status, status));
- return db.select().from(emails)
+ const q = db.select().from(emails)
.where(and(...conditions))
.orderBy(desc(emails.createdAt));
+ if (pagination) return q.limit(pagination.limit).offset(pagination.offset);
+ return q;
}
-export async function getTrustedEmails(db: Database, agentId: string, agentEmail: string, workspaceId: string, status?: string) {
+export async function getTrustedEmails(db: Database, agentId: string, agentEmail: string, workspaceId: string, status?: string, pagination?: EmailPagination) {
const conditions = [eq(emails.agentId, agentId), eq(emails.toEmail, agentEmail), eq(emails.workspaceId, workspaceId), eq(emails.isWhitelisted, true), eq(emails.direction, "inbound")];
if (status) conditions.push(eq(emails.status, status));
- return db.select().from(emails)
+ const q = db.select().from(emails)
.where(and(...conditions))
.orderBy(desc(emails.createdAt));
+ if (pagination) return q.limit(pagination.limit).offset(pagination.offset);
+ return q;
}
-export async function getRejectedEmails(db: Database, agentId: string, agentEmail: string, workspaceId: string, status?: string) {
+export async function getRejectedEmails(db: Database, agentId: string, agentEmail: string, workspaceId: string, status?: string, pagination?: EmailPagination) {
const conditions = [eq(emails.agentId, agentId), eq(emails.toEmail, agentEmail), eq(emails.workspaceId, workspaceId), eq(emails.isWhitelisted, false), eq(emails.direction, "inbound")];
if (status) conditions.push(eq(emails.status, status));
- return db.select().from(emails)
+ const q = db.select().from(emails)
.where(and(...conditions))
.orderBy(desc(emails.createdAt));
+ if (pagination) return q.limit(pagination.limit).offset(pagination.offset);
+ return q;
}
export async function getEmailByMessageId(db: Database, messageId: string, workspaceId: string) {
diff --git a/src/shared/test/queries/email.test.ts b/src/shared/test/queries/email.test.ts
index 7c9de6b42..e016d4eca 100644
--- a/src/shared/test/queries/email.test.ts
+++ b/src/shared/test/queries/email.test.ts
@@ -40,17 +40,17 @@ describe("email query module exports", () => {
});
describe("email query function signatures", () => {
- it("getEmailsByAgent accepts optional status parameter", () => {
- // The function should accept 4 parameters (db, agentId, workspaceId, status?)
- expect(emailQueries.getEmailsByAgent.length).toBeLessThanOrEqual(4);
+ it("getEmailsByAgent accepts optional status and pagination parameters", () => {
+ // (db, agentId, workspaceId, status?, pagination?)
+ expect(emailQueries.getEmailsByAgent.length).toBeLessThanOrEqual(5);
});
- it("getInboxEmails accepts optional status parameter", () => {
- expect(emailQueries.getInboxEmails.length).toBeLessThanOrEqual(5);
+ it("getInboxEmails accepts optional status and pagination parameters", () => {
+ expect(emailQueries.getInboxEmails.length).toBeLessThanOrEqual(6);
});
- it("getSentEmails accepts optional status parameter", () => {
- expect(emailQueries.getSentEmails.length).toBeLessThanOrEqual(5);
+ it("getSentEmails accepts optional status and pagination parameters", () => {
+ expect(emailQueries.getSentEmails.length).toBeLessThanOrEqual(6);
});
it("getRejectedEmails requires agentEmail parameter to exclude outbound", () => {
diff --git a/src/web/src/app/api/daemon/tasks/poll/route.test.ts b/src/web/src/app/api/daemon/tasks/poll/route.test.ts
index 08a6618d8..9d9f01da0 100644
--- a/src/web/src/app/api/daemon/tasks/poll/route.test.ts
+++ b/src/web/src/app/api/daemon/tasks/poll/route.test.ts
@@ -204,6 +204,7 @@ describe("POST /api/daemon/tasks/poll", () => {
email_handle: null,
email_addresses: [],
user_email: "[email protected]",
+ user_name: null,
});
});
@@ -616,7 +617,7 @@ describe("POST /api/daemon/tasks/poll", () => {
expect(body.tasks[0].sender).toEqual({ name: "Gus", email: "[email protected]", is_owner: false });
expect(body.tasks[1].sender).toEqual({ name: "Gus", email: "[email protected]", is_owner: false });
- expect(mockGetUser).toHaveBeenCalledTimes(1);
+ expect(mockGetUser).toHaveBeenCalledTimes(2);
});
// --- Workspace file requests ---
diff --git a/src/web/src/app/api/email/route.test.ts b/src/web/src/app/api/email/route.test.ts
index 35ea6f77b..07e9eb0e5 100644
--- a/src/web/src/app/api/email/route.test.ts
+++ b/src/web/src/app/api/email/route.test.ts
@@ -3,6 +3,7 @@ import { NextRequest } from "next/server";
const mockGetAgent = vi.fn();
const mockGetEmailsByAgent = vi.fn();
+const mockGetInboxEmails = vi.fn();
const mockGetTrustedEmails = vi.fn();
const mockGetSentEmails = vi.fn();
const mockGetRejectedEmails = vi.fn();
@@ -19,6 +20,7 @@ vi.mock("@alook/shared", () => ({
agent: { getAgent: (...args: unknown[]) => mockGetAgent(...args) },
email: {
getEmailsByAgent: (...args: unknown[]) => mockGetEmailsByAgent(...args),
+ getInboxEmails: (...args: unknown[]) => mockGetInboxEmails(...args),
getTrustedEmails: (...args: unknown[]) => mockGetTrustedEmails(...args),
getSentEmails: (...args: unknown[]) => mockGetSentEmails(...args),
getRejectedEmails: (...args: unknown[]) => mockGetRejectedEmails(...args),
@@ -56,7 +58,7 @@ describe("GET /api/email", () => {
it("returns all emails for agent (no status filter)", async () => {
mockGetAgent.mockResolvedValue({ id: "a1", emailHandle: "test" });
- mockGetEmailsByAgent.mockResolvedValue([{ id: "e1" }, { id: "e2" }]);
+ mockGetInboxEmails.mockResolvedValue([{ id: "e1" }, { id: "e2" }]);
const req = new NextRequest("http://localhost/api/email?agentId=a1");
const res = await GET(req, {} as any);
@@ -64,12 +66,12 @@ describe("GET /api/email", () => {
expect(res.status).toBe(200);
expect(body).toHaveLength(2);
- expect(mockGetEmailsByAgent).toHaveBeenCalledWith({}, "a1", "ws1", undefined);
+ expect(mockGetInboxEmails).toHaveBeenCalledWith({}, "a1", "[email protected]", "ws1", undefined, undefined);
});
it("filters by status=unread", async () => {
mockGetAgent.mockResolvedValue({ id: "a1", emailHandle: "test" });
- mockGetEmailsByAgent.mockResolvedValue([{ id: "e1", status: "unread" }]);
+ mockGetInboxEmails.mockResolvedValue([{ id: "e1", status: "unread" }]);
const req = new NextRequest("http://localhost/api/email?agentId=a1&status=unread");
const res = await GET(req, {} as any);
@@ -77,7 +79,7 @@ describe("GET /api/email", () => {
expect(res.status).toBe(200);
expect(body).toHaveLength(1);
- expect(mockGetEmailsByAgent).toHaveBeenCalledWith({}, "a1", "ws1", "unread");
+ expect(mockGetInboxEmails).toHaveBeenCalledWith({}, "a1", "[email protected]", "ws1", "unread", undefined);
});
it("filters by status and folder=inbox (whitelisted inbound)", async () => {
@@ -88,7 +90,7 @@ describe("GET /api/email", () => {
const res = await GET(req, {} as any);
expect(res.status).toBe(200);
- expect(mockGetTrustedEmails).toHaveBeenCalledWith({}, "a1", "[email protected]", "ws1", "unread");
+ expect(mockGetTrustedEmails).toHaveBeenCalledWith({}, "a1", "[email protected]", "ws1", "unread", undefined);
});
it("filters by folder=untrust (non-whitelisted inbound)", async () => {
@@ -99,7 +101,7 @@ describe("GET /api/email", () => {
const res = await GET(req, {} as any);
expect(res.status).toBe(200);
- expect(mockGetRejectedEmails).toHaveBeenCalledWith({}, "a1", "[email protected]", "ws1", undefined);
+ expect(mockGetRejectedEmails).toHaveBeenCalledWith({}, "a1", "[email protected]", "ws1", undefined, undefined);
});
it("filters by status and folder=sent", async () => {
@@ -110,7 +112,7 @@ describe("GET /api/email", () => {
const res = await GET(req, {} as any);
expect(res.status).toBe(200);
- expect(mockGetSentEmails).toHaveBeenCalledWith({}, "a1", "[email protected]", "ws1", "read");
+ expect(mockGetSentEmails).toHaveBeenCalledWith({}, "a1", "[email protected]", "ws1", "read", undefined);
});
it("returns 400 for invalid status value", async () => {
@@ -123,4 +125,75 @@ describe("GET /api/email", () => {
const body = await res.json();
expect(body.error).toBe("invalid status");
});
+
+ it("passes limit and offset to query function", async () => {
+ mockGetAgent.mockResolvedValue({ id: "a1", emailHandle: "test" });
+ mockGetInboxEmails.mockResolvedValue([{ id: "e1" }]);
+
+ const req = new NextRequest("http://localhost/api/email?agentId=a1&limit=10&offset=5");
+ const res = await GET(req, {} as any);
+
+ expect(res.status).toBe(200);
+ expect(mockGetInboxEmails).toHaveBeenCalledWith({}, "a1", "[email protected]", "ws1", undefined, { limit: 10, offset: 5 });
+ });
+
+ it("passes pagination to folder-specific queries", async () => {
+ mockGetAgent.mockResolvedValue({ id: "a1", emailHandle: "test" });
+ mockGetSentEmails.mockResolvedValue([]);
+
+ const req = new NextRequest("http://localhost/api/email?agentId=a1&folder=sent&limit=20&offset=10");
+ const res = await GET(req, {} as any);
+
+ expect(res.status).toBe(200);
+ expect(mockGetSentEmails).toHaveBeenCalledWith({}, "a1", "[email protected]", "ws1", undefined, { limit: 20, offset: 10 });
+ });
+
+ it("returns 400 for non-numeric limit", async () => {
+ mockGetAgent.mockResolvedValue({ id: "a1", emailHandle: "test" });
+
+ const req = new NextRequest("http://localhost/api/email?agentId=a1&limit=abc");
+ const res = await GET(req, {} as any);
+
+ expect(res.status).toBe(400);
+ const body = await res.json();
+ expect(body.error).toContain("limit");
+ });
+
+ it("returns 400 for negative limit", async () => {
+ mockGetAgent.mockResolvedValue({ id: "a1", emailHandle: "test" });
+
+ const req = new NextRequest("http://localhost/api/email?agentId=a1&limit=-1");
+ const res = await GET(req, {} as any);
+
+ expect(res.status).toBe(400);
+ });
+
+ it("returns 400 for limit exceeding 100", async () => {
+ mockGetAgent.mockResolvedValue({ id: "a1", emailHandle: "test" });
+
+ const req = new NextRequest("http://localhost/api/email?agentId=a1&limit=101");
+ const res = await GET(req, {} as any);
+
+ expect(res.status).toBe(400);
+ });
+
+ it("returns 400 for negative offset", async () => {
+ mockGetAgent.mockResolvedValue({ id: "a1", emailHandle: "test" });
+
+ const req = new NextRequest("http://localhost/api/email?agentId=a1&limit=10&offset=-5");
+ const res = await GET(req, {} as any);
+
+ expect(res.status).toBe(400);
+ });
+
+ it("does not pass pagination when limit is omitted (backward compat)", async () => {
+ mockGetAgent.mockResolvedValue({ id: "a1", emailHandle: "test" });
+ mockGetInboxEmails.mockResolvedValue([{ id: "e1" }]);
+
+ const req = new NextRequest("http://localhost/api/email?agentId=a1");
+ const res = await GET(req, {} as any);
+
+ expect(res.status).toBe(200);
+ expect(mockGetInboxEmails).toHaveBeenCalledWith({}, "a1", "[email protected]", "ws1", undefined, undefined);
+ });
});
diff --git a/src/web/src/app/api/email/route.ts b/src/web/src/app/api/email/route.ts
index b59ad4cca..03ab7909e 100644
--- a/src/web/src/app/api/email/route.ts
+++ b/src/web/src/app/api/email/route.ts
@@ -31,17 +31,28 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {
const address = req.nextUrl.searchParams.get("address");
const agentEmail = address || (agent.emailHandle ? `${agent.emailHandle}@alook.ai` : "");
+ const limitParam = req.nextUrl.searchParams.get("limit");
+ const offsetParam = req.nextUrl.searchParams.get("offset");
+ let pagination: { limit: number; offset: number } | undefined;
+ if (limitParam != null) {
+ const limit = parseInt(limitParam, 10);
+ if (isNaN(limit) || limit < 1 || limit > 100) return writeError("limit must be an integer between 1 and 100", 400);
+ const offset = offsetParam != null ? parseInt(offsetParam, 10) : 0;
+ if (isNaN(offset) || offset < 0) return writeError("offset must be a non-negative integer", 400);
+ pagination = { limit, offset };
+ }
+
let emailList;
if (folder === "inbox" && agentEmail) {
- emailList = await queries.email.getTrustedEmails(db, agentId, agentEmail, ws.workspaceId, status);
+ emailList = await queries.email.getTrustedEmails(db, agentId, agentEmail, ws.workspaceId, status, pagination);
} else if (folder === "sent" && agentEmail) {
- emailList = await queries.email.getSentEmails(db, agentId, agentEmail, ws.workspaceId, status);
+ emailList = await queries.email.getSentEmails(db, agentId, agentEmail, ws.workspaceId, status, pagination);
} else if (folder === "untrust" && agentEmail) {
- emailList = await queries.email.getRejectedEmails(db, agentId, agentEmail, ws.workspaceId, status);
+ emailList = await queries.email.getRejectedEmails(db, agentId, agentEmail, ws.workspaceId, status, pagination);
} else if (folder === "all") {
- emailList = await queries.email.getEmailsByAgent(db, agentId, ws.workspaceId, status);
+ emailList = await queries.email.getEmailsByAgent(db, agentId, ws.workspaceId, status, pagination);
} else {
- emailList = await queries.email.getInboxEmails(db, agentId, agentEmail, ws.workspaceId, status);
+ emailList = await queries.email.getInboxEmails(db, agentId, agentEmail, ws.workspaceId, status, pagination);
}
return writeJSON(emailList.map(emailToResponse));