Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat: add whitelist tool for agent

Gus45fb2a86ad91
diff --git a/src/cli/commands/email.test.ts b/src/cli/commands/email.test.ts
index c4742e5ae..cac5f5999 100644
--- a/src/cli/commands/email.test.ts
+++ b/src/cli/commands/email.test.ts
@@ -4,9 +4,11 @@ import { join } from "path";
import PostalMime from "postal-mime";
import { Command } from "commander";
-const { postMultipartMock, postJSONMock } = vi.hoisted(() => ({
+const { postMultipartMock, postJSONMock, getJSONMock, deleteJSONMock } = vi.hoisted(() => ({
postMultipartMock: vi.fn(),
postJSONMock: vi.fn(),
+ getJSONMock: vi.fn(),
+ deleteJSONMock: vi.fn(),
}));
vi.mock("../lib/client.js", () => ({
@@ -17,6 +19,12 @@ vi.mock("../lib/client.js", () => ({
postJSON(...a: unknown[]) {
return postJSONMock(...a);
}
+ getJSON(...a: unknown[]) {
+ return getJSONMock(...a);
+ }
+ deleteJSON(...a: unknown[]) {
+ return deleteJSONMock(...a);
+ }
},
}));
@@ -466,3 +474,234 @@ describe("email send behavior", () => {
expect(postJSONMock).not.toHaveBeenCalled();
});
});
+
+// --- Whitelist tests ---
+
+async function runWhitelist(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", "whitelist", ...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 };
+}
+
+describe("whitelist command registration", () => {
+ const cmd = emailCommand();
+ const whitelistCmd = cmd.commands.find((c) => c.name() === "whitelist")!;
+
+ it("whitelist subcommand group exists under email", () => {
+ expect(whitelistCmd).toBeDefined();
+ expect(whitelistCmd.description()).toBe("Manage email whitelist (allowed senders)");
+ });
+
+ it("list, add, delete subcommands exist under whitelist", () => {
+ const subNames = whitelistCmd.commands.map((c) => c.name());
+ expect(subNames).toContain("list");
+ expect(subNames).toContain("add");
+ expect(subNames).toContain("delete");
+ });
+
+ it("--agent_id is required on all three subcommands", () => {
+ for (const name of ["list", "add", "delete"]) {
+ const sub = whitelistCmd.commands.find((c) => c.name() === name)!;
+ const opts = (sub 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");
+ }
+ });
+
+ it("--workspace is optional on all three subcommands", () => {
+ for (const name of ["list", "add", "delete"]) {
+ const sub = whitelistCmd.commands.find((c) => c.name() === name)!;
+ const opts = (sub 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("--workspace");
+ expect(mandatory).not.toContain("--workspace");
+ }
+ });
+
+ it("--json is optional on list only", () => {
+ const listCmd = whitelistCmd.commands.find((c) => c.name() === "list")!;
+ const listOpts = (listCmd as unknown as { options: { long: string; mandatory?: boolean }[] }).options;
+ expect(listOpts.map((o) => o.long)).toContain("--json");
+
+ for (const name of ["add", "delete"]) {
+ const sub = whitelistCmd.commands.find((c) => c.name() === name)!;
+ const opts = (sub as unknown as { options: { long: string; mandatory?: boolean }[] }).options;
+ expect(opts.map((o) => o.long)).not.toContain("--json");
+ }
+ });
+});
+
+describe("whitelist list behavior", () => {
+ beforeEach(() => {
+ getJSONMock.mockReset();
+ });
+
+ it("returns table output with entries", async () => {
+ getJSONMock.mockResolvedValueOnce([
+ { id: "wl_abc123", email: "[email protected]", created_at: "2026-04-20T10:00:00Z" },
+ { id: "wl_def456", email: "[email protected]", created_at: "2026-04-21T14:30:00Z" },
+ ]);
+
+ const { out, exitCode } = await runWhitelist(["list", "--agent_id", "ag_1"]);
+
+ expect(exitCode).toBeNull();
+ expect(getJSONMock).toHaveBeenCalledWith("/api/agents/ag_1/whitelist");
+ const output = out.join("\n");
+ expect(output).toContain("ID");
+ expect(output).toContain("EMAIL");
+ expect(output).toContain("CREATED AT");
+ expect(output).toContain("[email protected]");
+ expect(output).toContain("[email protected]");
+ });
+
+ it("returns JSON output with --json", async () => {
+ const entries = [
+ { id: "wl_abc123", email: "[email protected]", created_at: "2026-04-20T10:00:00Z" },
+ ];
+ getJSONMock.mockResolvedValueOnce(entries);
+
+ const { out, exitCode } = await runWhitelist(["list", "--agent_id", "ag_1", "--json"]);
+
+ expect(exitCode).toBeNull();
+ const parsed = JSON.parse(out.join("\n"));
+ expect(parsed).toEqual(entries);
+ });
+
+ it("prints 'No whitelisted emails.' when empty", async () => {
+ getJSONMock.mockResolvedValueOnce([]);
+
+ const { out, exitCode } = await runWhitelist(["list", "--agent_id", "ag_1"]);
+
+ expect(exitCode).toBeNull();
+ expect(out.join("\n")).toContain("No whitelisted emails.");
+ });
+
+ it("exits 1 on API error", async () => {
+ getJSONMock.mockRejectedValueOnce(new Error("HTTP 500: Internal Server Error"));
+
+ const { err, exitCode } = await runWhitelist(["list", "--agent_id", "ag_1"]);
+
+ expect(exitCode).toBe(1);
+ expect(err.join("\n")).toContain("HTTP 500");
+ });
+});
+
+describe("whitelist add behavior", () => {
+ beforeEach(() => {
+ postJSONMock.mockReset();
+ });
+
+ it("posts email and prints confirmation", async () => {
+ postJSONMock.mockResolvedValueOnce({ id: "wl_new1", email: "[email protected]", created_at: "2026-04-22T00:00:00Z" });
+
+ const { out, exitCode } = await runWhitelist(["add", "--agent_id", "ag_1", "[email protected]"]);
+
+ expect(exitCode).toBeNull();
+ expect(postJSONMock).toHaveBeenCalledWith("/api/agents/ag_1/whitelist", { email: "[email protected]" });
+ expect(out.join("\n")).toContain("Added [email protected] to whitelist (id: wl_new1)");
+ });
+
+ it("normalizes email to lowercase before sending", async () => {
+ postJSONMock.mockResolvedValueOnce({ id: "wl_new2", email: "[email protected]", created_at: "2026-04-22T00:00:00Z" });
+
+ const { exitCode } = await runWhitelist(["add", "--agent_id", "ag_1", "[email protected]"]);
+
+ expect(exitCode).toBeNull();
+ expect(postJSONMock).toHaveBeenCalledWith("/api/agents/ag_1/whitelist", { email: "[email protected]" });
+ });
+
+ it("exits 1 with message on 409 duplicate", async () => {
+ postJSONMock.mockRejectedValueOnce(new Error("HTTP 409: already exists"));
+
+ const { err, exitCode } = await runWhitelist(["add", "--agent_id", "ag_1", "[email protected]"]);
+
+ expect(exitCode).toBe(1);
+ expect(err.join("\n")).toContain("[email protected] is already whitelisted");
+ });
+
+ it("exits 1 with message on 404 agent not found", async () => {
+ postJSONMock.mockRejectedValueOnce(new Error("HTTP 404: agent not found"));
+
+ const { err, exitCode } = await runWhitelist(["add", "--agent_id", "ag_999", "[email protected]"]);
+
+ expect(exitCode).toBe(1);
+ expect(err.join("\n")).toContain("404");
+ });
+
+ it("exits 1 with message on invalid email format (400 from API)", async () => {
+ postJSONMock.mockRejectedValueOnce(new Error("HTTP 400: invalid email format"));
+
+ const { err, exitCode } = await runWhitelist(["add", "--agent_id", "ag_1", "not-an-email"]);
+
+ expect(exitCode).toBe(1);
+ expect(err.join("\n")).toContain("400");
+ });
+});
+
+describe("whitelist delete behavior", () => {
+ beforeEach(() => {
+ getJSONMock.mockReset();
+ deleteJSONMock.mockReset();
+ });
+
+ it("fetches list, finds entry, sends DELETE with correct whitelistId, prints confirmation", async () => {
+ getJSONMock.mockResolvedValueOnce([
+ { id: "wl_abc123", email: "[email protected]", created_at: "2026-04-20T10:00:00Z" },
+ { id: "wl_def456", email: "[email protected]", created_at: "2026-04-21T14:30:00Z" },
+ ]);
+ deleteJSONMock.mockResolvedValueOnce(undefined);
+
+ const { out, exitCode } = await runWhitelist(["delete", "--agent_id", "ag_1", "[email protected]"]);
+
+ expect(exitCode).toBeNull();
+ expect(getJSONMock).toHaveBeenCalledWith("/api/agents/ag_1/whitelist");
+ expect(deleteJSONMock).toHaveBeenCalledWith("/api/agents/ag_1/whitelist/wl_abc123");
+ expect(out.join("\n")).toContain("Removed [email protected] from whitelist");
+ });
+
+ it("exits 1 with message when email not in whitelist", async () => {
+ getJSONMock.mockResolvedValueOnce([
+ { id: "wl_abc123", email: "[email protected]", created_at: "2026-04-20T10:00:00Z" },
+ ]);
+
+ const { err, exitCode } = await runWhitelist(["delete", "--agent_id", "ag_1", "[email protected]"]);
+
+ expect(exitCode).toBe(1);
+ expect(err.join("\n")).toContain("[email protected] is not in the whitelist");
+ });
+
+ it("exits 1 on API error", async () => {
+ getJSONMock.mockRejectedValueOnce(new Error("HTTP 500: Internal Server Error"));
+
+ const { err, exitCode } = await runWhitelist(["delete", "--agent_id", "ag_1", "[email protected]"]);
+
+ expect(exitCode).toBe(1);
+ expect(err.join("\n")).toContain("HTTP 500");
+ });
+});
diff --git a/src/cli/commands/email.ts b/src/cli/commands/email.ts
index 59630b481..61decaeb0 100644
--- a/src/cli/commands/email.ts
+++ b/src/cli/commands/email.ts
@@ -4,7 +4,7 @@ import { basename, join } from "path";
import PostalMime from "postal-mime";
import { APIClient } from "../lib/client.js";
import { loadCLIConfigForProfile } from "../lib/config.js";
-import { printJSON } from "../lib/output.js";
+import { printJSON, printTable } from "../lib/output.js";
import { cmdPrefix } from "../lib/env.js";
interface EmailResponse {
@@ -68,8 +68,16 @@ interface SendResponse {
to_email: string;
}
+interface WhitelistEntry {
+ id: string;
+ email: string;
+ created_at: string;
+}
+
function resolveClientOpts(command: Command, opts: { workspace?: string; agentId?: string }) {
- const parentOpts = command.parent?.parent?.opts() || {};
+ let root = command;
+ while (root.parent) root = root.parent;
+ const parentOpts = root.opts() || {};
const profile: string | undefined = parentOpts.profile;
const cfg = loadCLIConfigForProfile(profile);
const serverUrl = parentOpts.server || cfg.server_url;
@@ -361,5 +369,116 @@ export function emailCommand(): Command {
}
});
+ const whitelistCmd = new Command("whitelist").description(
+ "Manage email whitelist (allowed senders)",
+ );
+
+ whitelistCmd
+ .command("list")
+ .description("List all whitelisted emails for an agent")
+ .requiredOption("--agent_id <id>", "Agent ID")
+ .option("--workspace <id>", "Workspace ID")
+ .option("--json", "Output as JSON")
+ .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 {
+ const entries = await client.getJSON<WhitelistEntry[]>(
+ `/api/agents/${opts.agent_id}/whitelist`,
+ );
+
+ if (!entries.length) {
+ console.log("No whitelisted emails.");
+ return;
+ }
+
+ if (opts.json) {
+ printJSON(entries);
+ return;
+ }
+
+ printTable(
+ ["ID", "EMAIL", "CREATED AT"],
+ entries.map((e) => [e.id, e.email, e.created_at]),
+ );
+ } catch (err) {
+ console.error(`Error: ${err instanceof Error ? err.message : err}`);
+ process.exit(1);
+ }
+ });
+
+ whitelistCmd
+ .command("add")
+ .description("Add an email to the whitelist")
+ .requiredOption("--agent_id <id>", "Agent ID")
+ .option("--workspace <id>", "Workspace ID")
+ .argument("<email>", "Email address to whitelist")
+ .action(async (email, opts, command) => {
+ const { serverUrl, token, workspaceId } = resolveClientOpts(command, {
+ workspace: opts.workspace,
+ agentId: opts.agent_id,
+ });
+ const client = new APIClient(serverUrl, token, workspaceId);
+
+ try {
+ const entry = await client.postJSON<WhitelistEntry>(
+ `/api/agents/${opts.agent_id}/whitelist`,
+ { email: email.toLowerCase() },
+ );
+ console.log(`Added ${entry.email} to whitelist (id: ${entry.id})`);
+ } catch (err) {
+ const msg = err instanceof Error ? err.message : String(err);
+ if (msg.includes("409")) {
+ console.error(`Error: ${email.toLowerCase()} is already whitelisted`);
+ } else {
+ console.error(`Error: ${msg}`);
+ }
+ process.exit(1);
+ }
+ });
+
+ whitelistCmd
+ .command("delete")
+ .description("Remove an email from the whitelist")
+ .requiredOption("--agent_id <id>", "Agent ID")
+ .option("--workspace <id>", "Workspace ID")
+ .argument("<email>", "Email address to remove")
+ .action(async (email, opts, command) => {
+ const { serverUrl, token, workspaceId } = resolveClientOpts(command, {
+ workspace: opts.workspace,
+ agentId: opts.agent_id,
+ });
+ const client = new APIClient(serverUrl, token, workspaceId);
+ const normalizedEmail = email.toLowerCase();
+
+ try {
+ const entries = await client.getJSON<WhitelistEntry[]>(
+ `/api/agents/${opts.agent_id}/whitelist`,
+ );
+ const entry = entries.find((e) => e.email === normalizedEmail);
+
+ if (!entry) {
+ console.error(`Error: ${normalizedEmail} is not in the whitelist`);
+ process.exit(1);
+ }
+
+ await client.deleteJSON(
+ `/api/agents/${opts.agent_id}/whitelist/${entry.id}`,
+ );
+ console.log(`Removed ${normalizedEmail} from whitelist`);
+ } catch (err) {
+ const msg = err instanceof Error ? err.message : String(err);
+ if (msg === "__exit__") throw err;
+ console.error(`Error: ${msg}`);
+ process.exit(1);
+ }
+ });
+
+ cmd.addCommand(whitelistCmd);
+
return cmd;
}
diff --git a/src/cli/daemon/execenv/context.test.ts b/src/cli/daemon/execenv/context.test.ts
index 10d9e2e16..cb838fa8d 100644
--- a/src/cli/daemon/execenv/context.test.ts
+++ b/src/cli/daemon/execenv/context.test.ts
@@ -25,8 +25,8 @@ describe("buildInstructionContent email tool injection", () => {
});
const content = buildInstructionContent(task);
- expect(content).toContain("npx @alook/cli email pull --agent_id agent-123 --workspace ws1 --status unread");
- expect(content).toContain("npx @alook/cli email set --agent_id agent-123 --workspace ws1 --email_id <EMAIL_ID> --status read");
+ expect(content).toContain("npx @alook/cli email pull --agent_id agent-123 --status unread");
+ expect(content).toContain("npx @alook/cli email set --agent_id agent-123 --email_id <EMAIL_ID> --status read");
expect(content).toContain("/tmp/alook-emails/ws1/agent-123/");
expect(content).toContain("metadata.json");
expect(content).toContain("'[email protected]' (default, Alook platform address)");
diff --git a/src/cli/daemon/execenv/context.ts b/src/cli/daemon/execenv/context.ts
index 1157978f3..4aedc0351 100644
--- a/src/cli/daemon/execenv/context.ts
+++ b/src/cli/daemon/execenv/context.ts
@@ -91,7 +91,7 @@ ${task.agent?.userEmail ? `Your owner's email address is '${task.agent.userEmail
### Emails
---
-Run 'npx @alook/cli email pull --agent_id ${task.agentId} --workspace ${task.workspaceId} --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 to '/tmp/alook-emails/${task.workspaceId}/${task.agentId}/'.
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
@@ -99,22 +99,29 @@ Each email is saved to '/tmp/alook-emails/${task.workspaceId}/${task.agentId}/<e
- 'attachments/' — extracted attachment files (if any)
---
Before starting to process an email, mark it as read:
-- Run 'npx @alook/cli email set --agent_id ${task.agentId} --workspace ${task.workspaceId} --email_id <EMAIL_ID> --status read'
+- Run 'npx @alook/cli email set --agent_id ${task.agentId} --email_id <EMAIL_ID> --status read'
---
#### Sending a new 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} --workspace ${task.workspaceId} --to <ADDRESS> --subject "<SUBJECT>" --body-file <PATH_TO_HTML>'
+- Run 'npx @alook/cli email send --agent_id ${task.agentId} --to <ADDRESS> --subject "<SUBJECT>" --body-file <PATH_TO_HTML>'
- To send from a specific mailbox, add '--from <YOUR_EMAIL_ADDRESS>'. Without '--from', the default Alook address is used.
- 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} --workspace ${task.workspaceId} --to [email protected] --subject "Weekly report" --body-file /tmp/body.html --from [email protected] --attachment /tmp/report.pdf'
+- Example: 'npx @alook/cli email send --agent_id ${task.agentId} --to [email protected] --subject "Weekly report" --body-file /tmp/body.html --from [email protected] --attachment /tmp/report.pdf'
#### Replying to an email
To reply to an email, add '--in-reply-to <EMAIL_ID>' to the send command. This sets the correct email threading headers so the recipient's email client groups the reply into the same conversation thread.
- Use 'Re: <original subject>' as the subject.
- Quote the original email body in your reply (wrap it in a blockquote).
- The <EMAIL_ID> is the Alook email id from metadata.json (not the message_id header).
-- Example: 'npx @alook/cli email send --agent_id ${task.agentId} --workspace ${task.workspaceId} --to [email protected] --subject "Re: Bug report" --body-file /tmp/reply.html --in-reply-to <EMAIL_ID>'
+- Example: 'npx @alook/cli email send --agent_id ${task.agentId} --to [email protected] --subject "Re: Bug report" --body-file /tmp/reply.html --in-reply-to <EMAIL_ID>'
+---
+
+#### 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)
+- Add: 'npx @alook/cli email whitelist add --agent_id ${task.agentId} <EMAIL_ADDRESS>'
+- Remove: 'npx @alook/cli email whitelist delete --agent_id ${task.agentId} <EMAIL_ADDRESS>'
---
`;
}