Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat(cli): add --email_id option for direct email fetch in agent context

Gusf4562bcef79f
diff --git a/src/cli/commands/email.test.ts b/src/cli/commands/email.test.ts
index a39c0b9d1..dabd674c3 100644
--- a/src/cli/commands/email.test.ts
+++ b/src/cli/commands/email.test.ts
@@ -805,6 +805,92 @@ describe("email forward behavior", () => {
});
});
+describe("email pull with --email_id", () => {
+ beforeEach(() => {
+ getJSONMock.mockReset();
+ getTextMock.mockReset();
+ });
+
+ it("registers --email_id option on pull command", () => {
+ const cmd = emailCommand();
+ const pullCmd = cmd.commands.find((c) => c.name() === "pull")!;
+ const optNames = pullCmd.options.map((o) => o.long);
+ expect(optNames).toContain("--email_id");
+ });
+
+ it("calls single-email endpoint when --email_id is provided", async () => {
+ getJSONMock.mockResolvedValueOnce({
+ id: "em_123",
+ agent_id: "ag_1",
+ from_email: "[email protected]",
+ to_email: "[email protected]",
+ subject: "Test",
+ r2_key: "emails/em_123",
+ is_whitelisted: true,
+ forwarded: false,
+ message_id: "",
+ in_reply_to: "",
+ references: "",
+ html_body: "",
+ attachments: [],
+ status: "unread",
+ created_at: "2026-05-26T00:00:00Z",
+ });
+ getTextMock.mockResolvedValueOnce("From: [email protected]\r\nTo: [email protected]\r\nSubject: Test\r\nContent-Type: text/plain\r\n\r\nHello");
+
+ const { exitCode } = await runPull(["--agent_id", "ag_1", "--email_id", "em_123"]);
+
+ expect(exitCode).toBeNull();
+ expect(getJSONMock).toHaveBeenCalledWith("/api/email/em_123");
+ });
+
+ it("errors when --email_id combined with --status", async () => {
+ const { err, exitCode } = await runPull(["--agent_id", "ag_1", "--email_id", "em_1", "--status", "unread"]);
+
+ expect(exitCode).toBe(1);
+ expect(err.join("\n")).toContain("--email_id cannot be combined");
+ });
+
+ it("errors when --email_id combined with --folder", async () => {
+ const { err, exitCode } = await runPull(["--agent_id", "ag_1", "--email_id", "em_1", "--folder", "sent"]);
+
+ expect(exitCode).toBe(1);
+ expect(err.join("\n")).toContain("--email_id cannot be combined");
+ });
+
+ it("errors when --email_id combined with --limit", async () => {
+ const { err, exitCode } = await runPull(["--agent_id", "ag_1", "--email_id", "em_1", "--limit", "5"]);
+
+ expect(exitCode).toBe(1);
+ expect(err.join("\n")).toContain("--email_id cannot be combined");
+ });
+
+ it("errors when --email_id combined with --offset", async () => {
+ const { err, exitCode } = await runPull(["--agent_id", "ag_1", "--email_id", "em_1", "--offset", "10"]);
+
+ expect(exitCode).toBe(1);
+ expect(err.join("\n")).toContain("--email_id cannot be combined");
+ });
+
+ it("handles not-found error gracefully", async () => {
+ getJSONMock.mockRejectedValueOnce(new Error("HTTP 404: email not found"));
+
+ const { err, exitCode } = await runPull(["--agent_id", "ag_1", "--email_id", "em_nonexistent"]);
+
+ expect(exitCode).toBe(1);
+ expect(err.join("\n")).toContain("404");
+ });
+
+ it("does not use --email_id endpoint when flag is absent (backward compatible)", async () => {
+ getJSONMock.mockResolvedValueOnce([]);
+
+ const { exitCode } = await runPull(["--agent_id", "ag_1", "--status", "unread"]);
+
+ expect(exitCode).toBeNull();
+ expect(getJSONMock).toHaveBeenCalledWith("/api/email?agentId=ag_1&status=unread");
+ });
+});
+
describe("email pull with --folder", () => {
beforeEach(() => {
getJSONMock.mockReset();
diff --git a/src/cli/commands/email.ts b/src/cli/commands/email.ts
index 8f59eca29..641aaabdb 100644
--- a/src/cli/commands/email.ts
+++ b/src/cli/commands/email.ts
@@ -55,6 +55,7 @@ export function emailCommand(): Command {
.command("pull")
.description("Download and parse emails to /tmp/alook-emails/{workspaceId}/{agentId}/")
.option("--agent_id <id>", "Agent ID")
+ .option("--email_id <id>", "Fetch a single email by ID (mutually exclusive with --status/--folder/--limit/--offset)")
.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")
@@ -66,6 +67,11 @@ export function emailCommand(): Command {
const { serverUrl, token, workspaceId } = resolveClientOpts(command, { workspace: opts.workspace, agentId });
const client = new APIClient(serverUrl, token, workspaceId);
+ if (opts.email_id && (opts.status || opts.folder || opts.limit || opts.offset)) {
+ console.error("Error: --email_id cannot be combined with --status, --folder, --limit, or --offset");
+ process.exit(1);
+ }
+
if (opts.status && !VALID_STATUSES.includes(opts.status)) {
console.error(
`Error: invalid status "${opts.status}", must be one of: ${VALID_STATUSES.join(", ")}`,
@@ -99,13 +105,18 @@ export function emailCommand(): Command {
const emailDir_base = join(EMAIL_BASE, workspaceId, agentId);
try {
- let query = `/api/email?agentId=${agentId}`;
- 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);
+ let emails: EmailResponse[];
+ if (opts.email_id) {
+ const single = await client.getJSON<EmailResponse>(`/api/email/${opts.email_id}`);
+ emails = [single];
+ } else {
+ let query = `/api/email?agentId=${agentId}`;
+ 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}`;
+ emails = await client.getJSON<EmailResponse[]>(query);
+ }
if (!emails.length) {
console.log("No emails found.");
diff --git a/src/cli/daemon/execenv/context.test.ts b/src/cli/daemon/execenv/context.test.ts
index 603346e8e..69cefb49f 100644
--- a/src/cli/daemon/execenv/context.test.ts
+++ b/src/cli/daemon/execenv/context.test.ts
@@ -35,6 +35,17 @@ describe("buildInstructionContent email tool injection", () => {
expect(content).toContain("'[email protected]' (default, Alook platform address)");
});
+ it("includes --email_id pull instruction for ID-based fetching", () => {
+ const task = makeTask({
+ agent: { name: "test", instructions: "", emailHandle: "myagent" },
+ });
+ const content = buildInstructionContent(task);
+
+ expect(content).toContain("email pull --email_id <EMAIL_ID>");
+ expect(content).toContain("fetch ONLY that specific email");
+ expect(content).toContain("no `email_id` is present");
+ });
+
it("includes send-email docs when agent has email handle", () => {
const task = makeTask({
agent: { name: "test", instructions: "do stuff", emailHandle: "myagent" },
@@ -157,6 +168,23 @@ describe("buildInstructionContent email tool injection", () => {
expect(content).toContain("**DELEGATE when:** Draft blog posts");
});
+ it("includes isolated workspaces warning when agent has colleagues", () => {
+ const task = makeTask({
+ agent: {
+ name: "test",
+ instructions: "",
+ colleagues: [
+ { name: "Scout", email: "[email protected]", description: "", instruction: "Research" },
+ ],
+ },
+ });
+ const content = buildInstructionContent(task);
+
+ expect(content).toContain("**Isolated workspaces:**");
+ expect(content).toContain("Colleagues CANNOT read your local files");
+ expect(content).toContain("MUST attach the file to the email");
+ });
+
it("omits colleagues section when no colleagues", () => {
const task = makeTask({
agent: { name: "test", instructions: "", colleagues: [] },
diff --git a/src/cli/daemon/execenv/context.ts b/src/cli/daemon/execenv/context.ts
index 78fd744cb..97793c59f 100644
--- a/src/cli/daemon/execenv/context.ts
+++ b/src/cli/daemon/execenv/context.ts
@@ -123,6 +123,10 @@ ${task.agent.instructions}
if (i < task.agent.colleagues.length - 1) content += "\n";
}
content += `
+**Isolated workspaces:**
+- Each agent runs in its own isolated workspace directory. Colleagues CANNOT read your local files — even in the same workspace.
+- When sending plans, code, or any file to a colleague, you MUST attach the file to the email (use --attachment). Never reference local file paths expecting them to read it.
+
**Email threading rules:**
- When communicating with a colleague on the **same topic** as an existing email thread, reply to that thread (use --in-reply-to) to keep context together.
- **When starting a NEW topic or task that is unrelated to any previous email thread, you MUST compose a brand new email (do NOT use --in-reply-to). Never hijack an unrelated thread just because you recently emailed that colleague.** Judge by topic/task relevance, not by recency of communication.
@@ -143,7 +147,10 @@ The CLI auto-detects your identity from the environment. No need to pass \`--age
### Emails
---
-Run '${cmdPrefix()} email pull --status unread' to download unread emails from inbox to '${tempDir("alook-emails")}/${task.workspaceId}/${task.agentId}/'.
+When your task prompt includes an \`email_id\` field, fetch ONLY that specific email:
+- Run '${cmdPrefix()} email pull --email_id <EMAIL_ID>' (uses the email_id from the prompt)
+When no \`email_id\` is present, fall back to listing unread:
+- Run '${cmdPrefix()} email pull --status unread' to download unread emails from inbox to '${tempDir("alook-emails")}/${task.workspaceId}/${task.agentId}/'.
---
To download sent emails, add '--folder sent': '${cmdPrefix()} email pull --folder sent'
Valid folders: inbox (default), sent, untrust.
diff --git a/src/cli/daemon/prompt.test.ts b/src/cli/daemon/prompt.test.ts
index 6e4966007..1ce693d28 100644
--- a/src/cli/daemon/prompt.test.ts
+++ b/src/cli/daemon/prompt.test.ts
@@ -211,6 +211,39 @@ describe("buildPrompt", () => {
expect(parsed.repeat_interval).toBe("1week");
});
+ it("includes email_id in prompt JSON when context has emailId", () => {
+ const task: Task = {
+ ...makeTask("New email from [email protected]: Hi", "email_notification"),
+ context: { conversationType: "email_notification", emailId: "em_abc123" },
+ };
+ const parsed = JSON.parse(buildPrompt(task));
+ expect(parsed.email_id).toBe("em_abc123");
+ });
+
+ it("omits email_id when context has no emailId", () => {
+ const task: Task = {
+ ...makeTask("New email from [email protected]: Hi", "email_notification"),
+ context: { conversationType: "email_notification" },
+ };
+ const parsed = JSON.parse(buildPrompt(task));
+ expect(parsed.email_id).toBeUndefined();
+ });
+
+ it("omits email_id when context is undefined", () => {
+ const task = makeTask("New email from [email protected]: Hi", "email_notification");
+ const parsed = JSON.parse(buildPrompt(task));
+ expect(parsed.email_id).toBeUndefined();
+ });
+
+ it("omits email_id when emailId is null in context", () => {
+ const task: Task = {
+ ...makeTask("New email from [email protected]: Hi", "email_notification"),
+ context: { conversationType: "email_notification", emailId: null },
+ };
+ const parsed = JSON.parse(buildPrompt(task));
+ expect(parsed.email_id).toBeUndefined();
+ });
+
it("does not add notice for unknown task types", () => {
const task = makeTask("Check inbox", "some_other_type");
const parsed = JSON.parse(buildPrompt(task));
diff --git a/src/cli/daemon/prompt.ts b/src/cli/daemon/prompt.ts
index 1164a159a..47ffa4654 100644
--- a/src/cli/daemon/prompt.ts
+++ b/src/cli/daemon/prompt.ts
@@ -50,6 +50,9 @@ export function buildPrompt(task: Task, attachments?: Attachment[]): string {
} else {
obj.notice = EMAIL_NOTICE;
}
+ if (ctx?.emailId != null) {
+ obj.email_id = ctx.emailId;
+ }
}
if (task.type === "calendar_event") {
obj.notice = CALENDAR_NOTICE;
diff --git a/src/web/src/app/api/email/notify/route.test.ts b/src/web/src/app/api/email/notify/route.test.ts
index f9c08bb04..adcbfe5cb 100644
--- a/src/web/src/app/api/email/notify/route.test.ts
+++ b/src/web/src/app/api/email/notify/route.test.ts
@@ -134,7 +134,7 @@ describe("POST /api/email/notify", () => {
"a1", "conv_new", "ws1",
expect.any(String),
"email_notification",
- expect.objectContaining({ contextKey: "conv_new", context: { conversationType: "email_notification" }, traceId: expect.stringMatching(/^tr_/), parentTaskId: null }),
+ expect.objectContaining({ contextKey: "conv_new", context: { conversationType: "email_notification", emailId: "e1" }, traceId: expect.stringMatching(/^tr_/), parentTaskId: null }),
);
});
@@ -153,7 +153,7 @@ describe("POST /api/email/notify", () => {
"a1", "conv_existing", "ws1",
expect.any(String),
"email_notification",
- expect.objectContaining({ contextKey: "conv_existing", context: { conversationType: "email_notification" }, traceId: expect.stringMatching(/^tr_/), parentTaskId: null }),
+ expect.objectContaining({ contextKey: "conv_existing", context: { conversationType: "email_notification", emailId: "e1" }, traceId: expect.stringMatching(/^tr_/), parentTaskId: null }),
);
});
@@ -173,7 +173,7 @@ describe("POST /api/email/notify", () => {
"a1", "conv_dm", "ws1",
expect.any(String),
"email_notification",
- expect.objectContaining({ contextKey: "conv_dm", context: { conversationType: "user_dm_message", dmUser: { name: "Alice", email: "[email protected]" } }, traceId: expect.stringMatching(/^tr_/), parentTaskId: null }),
+ expect.objectContaining({ contextKey: "conv_dm", context: { conversationType: "user_dm_message", dmUser: { name: "Alice", email: "[email protected]" }, emailId: "e1" }, traceId: expect.stringMatching(/^tr_/), parentTaskId: null }),
);
});
@@ -191,7 +191,7 @@ describe("POST /api/email/notify", () => {
"a1", "conv_dm", "ws1",
expect.any(String),
"email_notification",
- expect.objectContaining({ contextKey: "conv_dm", context: { conversationType: "user_dm_message" }, traceId: expect.stringMatching(/^tr_/), parentTaskId: null }),
+ expect.objectContaining({ contextKey: "conv_dm", context: { conversationType: "user_dm_message", emailId: "e1" }, traceId: expect.stringMatching(/^tr_/), parentTaskId: null }),
);
});
diff --git a/src/web/src/app/api/email/notify/route.ts b/src/web/src/app/api/email/notify/route.ts
index 4d43359bf..b81dc033a 100644
--- a/src/web/src/app/api/email/notify/route.ts
+++ b/src/web/src/app/api/email/notify/route.ts
@@ -128,6 +128,7 @@ export async function POST(req: NextRequest) {
const context: Record<string, unknown> = { conversationType };
if (dmUser) context.dmUser = dmUser;
if (body.isInternal) context.isInternal = true;
+ context.emailId = email.id;
const traceId = body.traceId || ("tr_" + nanoid());
const parentTaskId = body.traceId ? (body.sourceTaskId || null) : null;
const task = await taskService.enqueueTask(agent.id, conversationId, agent.workspaceId, prompt, TASK_TYPES.EMAIL_NOTIFICATION, { contextKey: conversationId, context, traceId, parentTaskId })