Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat(cli): add 'email send' with attachment support

Gener14d57bcaa417
diff --git a/src/cli/commands/email.test.ts b/src/cli/commands/email.test.ts
index a6a07836f..1532008d6 100644
--- a/src/cli/commands/email.test.ts
+++ b/src/cli/commands/email.test.ts
@@ -2,6 +2,34 @@ import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { mkdirSync, writeFileSync, readFileSync, existsSync, rmSync } from "fs";
import { join } from "path";
import PostalMime from "postal-mime";
+import { Command } from "commander";
+
+const { postMultipartMock, postJSONMock } = vi.hoisted(() => ({
+ postMultipartMock: vi.fn(),
+ postJSONMock: vi.fn(),
+}));
+
+vi.mock("../lib/client.js", () => ({
+ APIClient: class {
+ postMultipart(...a: unknown[]) {
+ return postMultipartMock(...a);
+ }
+ postJSON(...a: unknown[]) {
+ return postJSONMock(...a);
+ }
+ },
+}));
+
+vi.mock("../lib/config.js", () => ({
+ loadCLIConfigForProfile: vi.fn(() => ({
+ server_url: "http://localhost:3000",
+ watched_workspaces: [
+ { id: "w1", token: "tok", agent_ids: ["ag_1"] },
+ ],
+ })),
+}));
+
+import { emailCommand } from "./email.js";
// Test the PostalMime parsing and file writing logic in isolation
// (CLI commands themselves depend on network + config which we don't mock here)
@@ -227,3 +255,177 @@ describe("email status validation", () => {
expect(VALID_STATUSES.includes("")).toBe(false);
});
});
+
+describe("email send subcommand shape", () => {
+ const cmd = emailCommand();
+ const send = cmd.commands.find((c) => c.name() === "send")!;
+
+ it("is registered", () => {
+ expect(send).toBeDefined();
+ });
+
+ it("requires --agent_id, --to, --subject, --body-file", () => {
+ const opts = (send 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("--to");
+ expect(mandatory).toContain("--subject");
+ expect(mandatory).toContain("--body-file");
+ });
+
+ it("accepts --attachment and --workspace as optional", () => {
+ const opts = (send 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("--attachment");
+ expect(longs).toContain("--workspace");
+ expect(mandatory).not.toContain("--attachment");
+ expect(mandatory).not.toContain("--workspace");
+ });
+});
+
+describe("email send behavior", () => {
+ const SEND_TMP = "/tmp/alook-email-send-test";
+
+ async function runSend(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", "send", ...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 };
+ }
+
+ beforeEach(() => {
+ mkdirSync(SEND_TMP, { recursive: true });
+ postMultipartMock.mockReset();
+ postJSONMock.mockReset();
+ });
+
+ afterEach(() => {
+ rmSync(SEND_TMP, { recursive: true, force: true });
+ });
+
+ it("uploads each attachment then sends", async () => {
+ const bodyPath = join(SEND_TMP, "body.html");
+ const att1 = join(SEND_TMP, "report.pdf");
+ const att2 = join(SEND_TMP, "chart.png");
+ writeFileSync(bodyPath, "<p>Hi</p>");
+ writeFileSync(att1, Buffer.from("pdf-bytes"));
+ writeFileSync(att2, Buffer.from("png-bytes"));
+
+ postMultipartMock
+ .mockResolvedValueOnce({ key: "emails/drafts/abc/report.pdf", filename: "report.pdf", size: 9, contentType: "application/pdf" })
+ .mockResolvedValueOnce({ key: "emails/drafts/def/chart.png", filename: "chart.png", size: 9, contentType: "image/png" });
+ postJSONMock.mockResolvedValueOnce({ id: "em_1", to_email: "[email protected]" });
+
+ const { out, exitCode } = await runSend([
+ "--agent_id", "ag_1",
+ "--to", "[email protected]",
+ "--subject", "Weekly report",
+ "--body-file", bodyPath,
+ "--attachment", att1,
+ "--attachment", att2,
+ ]);
+
+ expect(exitCode).toBeNull();
+ expect(postMultipartMock).toHaveBeenCalledTimes(2);
+ expect(postMultipartMock.mock.calls[0][0]).toBe("/api/email/upload");
+ expect(postMultipartMock.mock.calls[0][1]).toBeInstanceOf(FormData);
+ const form1 = postMultipartMock.mock.calls[0][1] as FormData;
+ const file1 = form1.get("file") as File;
+ expect(file1).toBeInstanceOf(Blob);
+ // Blob.type carries our guessed content-type
+ expect(file1.type).toBe("application/pdf");
+
+ expect(postJSONMock).toHaveBeenCalledTimes(1);
+ expect(postJSONMock.mock.calls[0][0]).toBe("/api/email/send");
+ const payload = postJSONMock.mock.calls[0][1] as {
+ agentId: string;
+ to: string;
+ subject: string;
+ htmlBody: string;
+ attachments: Array<{ key: string; filename: string; contentType: string }>;
+ };
+ expect(payload.agentId).toBe("ag_1");
+ expect(payload.to).toBe("[email protected]");
+ expect(payload.subject).toBe("Weekly report");
+ expect(payload.htmlBody).toBe("<p>Hi</p>");
+ expect(payload.attachments).toHaveLength(2);
+ expect(payload.attachments[0].key).toBe("emails/drafts/abc/report.pdf");
+ expect(payload.attachments[1].key).toBe("emails/drafts/def/chart.png");
+
+ expect(out.join("\n")).toContain("Sent email to [email protected]");
+ });
+
+ it("sends with empty attachments when none provided", async () => {
+ const bodyPath = join(SEND_TMP, "body.html");
+ writeFileSync(bodyPath, "<p>No attachments</p>");
+ postJSONMock.mockResolvedValueOnce({ id: "em_2", to_email: "[email protected]" });
+
+ const { exitCode } = await runSend([
+ "--agent_id", "ag_1",
+ "--to", "[email protected]",
+ "--subject", "Hi",
+ "--body-file", bodyPath,
+ ]);
+
+ expect(exitCode).toBeNull();
+ expect(postMultipartMock).not.toHaveBeenCalled();
+ const payload = postJSONMock.mock.calls[0][1] as { attachments: unknown[] };
+ expect(payload.attachments).toEqual([]);
+ });
+
+ it("errors when body file does not exist", async () => {
+ const { err, exitCode } = await runSend([
+ "--agent_id", "ag_1",
+ "--to", "[email protected]",
+ "--subject", "Hi",
+ "--body-file", join(SEND_TMP, "missing.html"),
+ ]);
+
+ expect(exitCode).toBe(1);
+ expect(err.join("\n")).toContain("cannot read body file");
+ expect(postMultipartMock).not.toHaveBeenCalled();
+ expect(postJSONMock).not.toHaveBeenCalled();
+ });
+
+ it("errors when body file is empty", async () => {
+ const bodyPath = join(SEND_TMP, "empty.html");
+ writeFileSync(bodyPath, "");
+
+ const { err, exitCode } = await runSend([
+ "--agent_id", "ag_1",
+ "--to", "[email protected]",
+ "--subject", "Hi",
+ "--body-file", bodyPath,
+ ]);
+
+ expect(exitCode).toBe(1);
+ expect(err.join("\n")).toContain("is empty");
+ expect(postMultipartMock).not.toHaveBeenCalled();
+ expect(postJSONMock).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/cli/commands/email.ts b/src/cli/commands/email.ts
index d1f975e03..7fff6ef06 100644
--- a/src/cli/commands/email.ts
+++ b/src/cli/commands/email.ts
@@ -1,6 +1,6 @@
import { Command } from "commander";
-import { writeFileSync, mkdirSync } from "fs";
-import { join } from "path";
+import { writeFileSync, mkdirSync, readFileSync, statSync } from "fs";
+import { basename, join } from "path";
import PostalMime from "postal-mime";
import { APIClient } from "../lib/client.js";
import { loadCLIConfigForProfile } from "../lib/config.js";
@@ -25,6 +25,46 @@ interface EmailResponse {
const VALID_STATUSES = ["unread", "read", "archived"];
const EMAIL_DIR = "/tmp/alook-emails";
+const MIME_BY_EXT: Record<string, string> = {
+ ".pdf": "application/pdf",
+ ".png": "image/png",
+ ".jpg": "image/jpeg",
+ ".jpeg": "image/jpeg",
+ ".gif": "image/gif",
+ ".webp": "image/webp",
+ ".svg": "image/svg+xml",
+ ".txt": "text/plain",
+ ".html": "text/html",
+ ".htm": "text/html",
+ ".json": "application/json",
+ ".csv": "text/csv",
+ ".md": "text/markdown",
+ ".zip": "application/zip",
+};
+
+function guessContentType(filename: string): string {
+ const idx = filename.lastIndexOf(".");
+ if (idx < 0) return "application/octet-stream";
+ const ext = filename.slice(idx).toLowerCase();
+ return MIME_BY_EXT[ext] ?? "application/octet-stream";
+}
+
+function collectRepeated(value: string, previous: string[]): string[] {
+ return previous.concat([value]);
+}
+
+interface AttachmentDescriptor {
+ key: string;
+ filename: string;
+ size: number;
+ contentType: string;
+}
+
+interface SendResponse {
+ id: string;
+ to_email: string;
+}
+
function resolveClientOpts(command: Command, opts: { workspace?: string; agentId?: string }) {
const parentOpts = command.parent?.parent?.opts() || {};
const profile: string | undefined = parentOpts.profile;
@@ -209,5 +249,90 @@ export function emailCommand(): Command {
}
});
+ cmd
+ .command("send")
+ .description("Send an email from the agent")
+ .requiredOption("--agent_id <id>", "Agent ID")
+ .requiredOption("--to <addr>", "Recipient email address")
+ .requiredOption("--subject <s>", "Subject line")
+ .requiredOption("--body-file <path>", "Path to HTML body file")
+ .option(
+ "--attachment <path>",
+ "Path to a 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);
+
+ let htmlBody: string;
+ try {
+ htmlBody = readFileSync(opts.bodyFile, "utf-8");
+ } catch (err) {
+ console.error(
+ `Error: cannot read body file "${opts.bodyFile}": ${err instanceof Error ? err.message : err}`,
+ );
+ process.exit(1);
+ }
+ if (!htmlBody) {
+ console.error(`Error: body file "${opts.bodyFile}" is empty`);
+ process.exit(1);
+ }
+
+ const attachmentPaths: string[] = opts.attachment ?? [];
+ const attachments: AttachmentDescriptor[] = [];
+
+ try {
+ for (const path of attachmentPaths) {
+ 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,
+ });
+ }
+
+ const res = await client.postJSON<SendResponse>("/api/email/send", {
+ agentId: opts.agent_id,
+ to: opts.to,
+ subject: opts.subject,
+ htmlBody,
+ attachments,
+ });
+ console.log(`Sent email to ${res.to_email} (id: ${res.id})`);
+ } catch (err) {
+ console.error(`Error: ${err instanceof Error ? err.message : err}`);
+ process.exit(1);
+ }
+ });
+
return cmd;
}
diff --git a/src/cli/daemon/execenv/context.test.ts b/src/cli/daemon/execenv/context.test.ts
index a5c62d43c..02fe86be0 100644
--- a/src/cli/daemon/execenv/context.test.ts
+++ b/src/cli/daemon/execenv/context.test.ts
@@ -32,6 +32,26 @@ describe("buildInstructionContent email tool injection", () => {
expect(content).toContain("Your email address is '[email protected]'");
});
+ it("includes send-email docs when agent has email handle", () => {
+ const task = makeTask({
+ agent: { name: "test", instructions: "do stuff", emailHandle: "myagent" },
+ });
+ const content = buildInstructionContent(task);
+
+ expect(content).toContain("npx @alook/cli email send --agent_id agent-123");
+ expect(content).toContain("--body-file");
+ expect(content).toContain("--attachment");
+ });
+
+ it("omits send-email docs when agent has no email handle", () => {
+ const task = makeTask({
+ agent: { name: "test", instructions: "do stuff" },
+ });
+ const content = buildInstructionContent(task);
+
+ expect(content).not.toContain("email send --agent_id");
+ });
+
it("includes owner email when user email is provided", () => {
const task = makeTask({
agent: { name: "test", instructions: "do stuff", emailHandle: "myagent", userEmail: "[email protected]" },
diff --git a/src/cli/daemon/execenv/context.ts b/src/cli/daemon/execenv/context.ts
index d1d5668b1..c36974472 100644
--- a/src/cli/daemon/execenv/context.ts
+++ b/src/cli/daemon/execenv/context.ts
@@ -94,6 +94,13 @@ Each email is saved to '/tmp/alook-emails/<emailId>/' with:
Before starting to process an email, mark it as read:
- Run 'npx @alook/cli set --agent_id ${task.agentId} --email_id <EMAIL_ID> --status read'
---
+
+#### Sending email
+Write the HTML body to a file first, then send it. The body is forwarded as-is (HTML).
+- Run 'npx @alook/cli email send --agent_id ${task.agentId} --to <ADDRESS> --subject "<SUBJECT>" --body-file <PATH_TO_HTML>'
+- Attach files with '--attachment <PATH>' — repeat the flag for multiple attachments. Each file is uploaded before sending.
+- Example: 'npx @alook/cli email send --agent_id ${task.agentId} --to [email protected] --subject "Weekly report" --body-file /tmp/body.html --attachment /tmp/report.pdf --attachment /tmp/chart.png'
+---
`;
}
diff --git a/src/cli/lib/client.ts b/src/cli/lib/client.ts
index 0c9aa4948..9d746f016 100644
--- a/src/cli/lib/client.ts
+++ b/src/cli/lib/client.ts
@@ -45,6 +45,25 @@ export class APIClient {
return this.request("PATCH", path, body);
}
+ async postMultipart<T>(path: string, form: FormData): Promise<T> {
+ const headers: Record<string, string> = {
+ Authorization: `Bearer ${this.token}`,
+ };
+ if (this.workspaceId) headers["X-Workspace-ID"] = this.workspaceId;
+
+ const res = await fetch(this.baseURL + path, {
+ method: "POST",
+ headers,
+ body: form,
+ });
+ if (!res.ok) {
+ const text = await res.text();
+ throw new Error(`HTTP ${res.status}: ${text}`);
+ }
+ if (res.status === 204) return undefined as T;
+ return res.json();
+ }
+
async getText(path: string): Promise<string> {
const headers: Record<string, string> = {
Authorization: `Bearer ${this.token}`,