Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,13 @@ extension/popup.html
*.db
offeru-data/

# ---- 环境配置 ----
# ---- 环境配置 / 本地凭据 ----
.env
.env.local
.env.*.local
.scratch/
offeru-mail.json
mimo.env

# ---- IDE / 编辑器 ----
.vscode/
Expand Down
67 changes: 56 additions & 11 deletions backend-ts/src/routes/career-os.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,9 @@ import {
getPerceptibleInboxFeed,
globalPromptCache,
ingestJobEmails,
loadMailboxState,
resolvePendingInboxItem,
undoInboxItem,
listCareerGoals,
listCareerSchedules,
listDistilledSkills,
Expand Down Expand Up @@ -616,14 +619,19 @@ export function registerCareerOs(app: Hono<AppEnv>): void {

app.get("/api/agent/inbox/feed", async (c) => {
const deps = c.get("deps");
const [feed, mailStatus] = await Promise.all([
getPerceptibleInboxFeed(deps.store),
deps.mail ? deps.mail.status().catch(() => null) : Promise.resolve(null),
]);
const mailStatus = deps.mail ? await deps.mail.status().catch(() => null) : null;
const account = mailStatus?.account?.address ?? null;
const loaded = await loadMailboxState(deps.store, account);
const state = loaded.state;
return c.json({
connected: Boolean(mailStatus?.connected),
account: mailStatus?.account?.address ?? null,
...feed,
account,
cursor: state.uid_validity && state.head_uid !== null ? `${state.uid_validity}:${state.head_uid}` : null,
last_synced_at: state.last_synced_at,
items: state.recent_feed,
pending_confirmations: state.pending_confirmations,
backfill_done: state.backfill_done,
has_more: Boolean(mailStatus?.connected) && !state.backfill_done,
});
});

Expand All @@ -633,8 +641,9 @@ export function registerCareerOs(app: Hono<AppEnv>): void {
const policy = await currentAutonomyPolicy(deps);
const engine = resolveReasoningEngine(deps, policy);
const ctx = requestContext(c);
const mailStatus = deps.mail ? await deps.mail.status().catch(() => null) : null;
const account = mailStatus?.account?.address ?? null;

// Support both pasted/batch emails (web + desktop) AND incremental connected IMAP sync (desktop)
if (Array.isArray(body.emails) && body.emails.length > 0) {
const emails: RawInboxEmail[] = body.emails.map((item, idx) => {
const obj = (item && typeof item === "object" ? item : {}) as Record<string, unknown>;
Expand All @@ -645,19 +654,55 @@ export function registerCareerOs(app: Hono<AppEnv>): void {
date: typeof obj.date === "string" ? obj.date : ctx.now,
text: String(obj.text ?? ""),
html: typeof obj.html === "string" ? obj.html : null,
message_id: typeof obj.message_id === "string" ? obj.message_id : null,
account,
};
});
return c.json(await ingestJobEmails(deps.store, emails, ctx, { engine: body.use_model === true ? engine : null }));
return c.json(await ingestJobEmails(deps.store, emails, ctx, {
engine: body.use_model === false ? null : engine,
account,
useModel: body.use_model !== false,
bodyPolicy: body.body_policy === "full" || body.body_policy === "compact" ? body.body_policy : "smart",
}));
}

const client = deps.mail?.client() ?? null;
return c.json(await syncConnectedMailbox(deps.store, client, ctx, {
days: typeof body.days === "number" ? body.days : 14,
limit: typeof body.limit === "number" ? body.limit : 30,
engine: body.use_model === true ? engine : null,
days: typeof body.days === "number" ? body.days : 90,
pageSize: typeof body.page_size === "number" ? body.page_size : typeof body.limit === "number" ? body.limit : 50,
maxPages: typeof body.max_pages === "number" ? body.max_pages : 4,
backfill: body.backfill !== false,
useModel: body.use_model !== false,
bodyPolicy: body.body_policy === "full" || body.body_policy === "compact" ? body.body_policy : "smart",
engine: body.use_model === false ? null : engine,
}));
});

app.post("/api/agent/inbox/confirm", async (c) => {
const deps = c.get("deps");
const body = await jsonBody(c) as Json;
const emailKey = typeof body.email_key === "string" ? body.email_key : "";
const action = body.action;
if (!emailKey || (action !== "attach_job" && action !== "create_job" && action !== "ignore")) {
throw new CoreError("confirm 需要 email_key 和 action(attach_job / create_job / ignore)", "invalid");
}
return c.json(await resolvePendingInboxItem(deps.store, emailKey, {
action,
job_id: typeof body.job_id === "number" ? body.job_id : null,
company: typeof body.company === "string" ? body.company : null,
role_title: typeof body.role_title === "string" ? body.role_title : null,
application_cycle: typeof body.application_cycle === "string" ? body.application_cycle : null,
}, requestContext(c)));
});

app.post("/api/agent/inbox/undo", async (c) => {
const deps = c.get("deps");
const body = await jsonBody(c) as Json;
const emailKey = typeof body.email_key === "string" ? body.email_key : "";
if (!emailKey) throw new CoreError("undo 需要 email_key", "invalid");
return c.json(await undoInboxItem(deps.store, emailKey, requestContext(c)));
});

// ---- 9. P1 CareerOps Two-Stage Zero-Token Triage & Daily Focus Budget ----

app.get("/api/agent/triage", async (c) => {
Expand Down
144 changes: 122 additions & 22 deletions backend-ts/src/routes/companion/mail.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
mailHtmlText,
mailPreview,
type MailAccount,
type MailAttachmentMeta,
type MailClient,
type MailDraftRef,
type MailMessage,
Expand All @@ -34,6 +35,7 @@ import { APP_VERSION } from "../../runtime-identity";
const TIMEOUTS = { connectionTimeout: 15_000, greetingTimeout: 10_000, socketTimeout: 60_000 };
const PREVIEW_BYTES = 4096;
const READ_BYTES = 10 * 1024 * 1024;
const CALENDAR_BYTES = 128 * 1024;

export function nodeMailAccountFile(path: string) {
return {
Expand Down Expand Up @@ -127,9 +129,56 @@ function textPart(node: MessageStructureObject | undefined): { part: string; htm
return parts.find((item) => !item.html) ?? parts[0] ?? null;
}

function attachmentName(node: MessageStructureObject): string | null {
const name = node.dispositionParameters?.filename || node.parameters?.name;
return name || null;
}

/** Attachment / calendar parts of the current message (metadata only, no body download). */
function attachmentParts(node: MessageStructureObject | undefined): MessageStructureObject[] {
const parts: MessageStructureObject[] = [];
const walk = (item: MessageStructureObject) => {
if (item.childNodes?.length) return item.childNodes.forEach(walk);
if (item.disposition === "attachment" || item.type === "text/calendar" || attachmentName(item)) parts.push(item);
};
if (node) walk(node);
return parts;
}

const person = (item: { name?: string; address?: string } | undefined) => (item ? (item.name ? `${item.name} <${item.address ?? ""}>` : item.address ?? "") : "");
const people = (value: AddressObject | AddressObject[] | undefined) => (Array.isArray(value) ? value : value ? [value] : []).flatMap((group) => group.value.map(person));

/**
* One UID page: `afterUid` walks forward (ascending) and `beforeUid` walks backward
* (descending). Pure so the paging contract is testable without an IMAP server.
*/
export function pageUids(
all: number[],
options: { afterUid?: number | null; beforeUid?: number | null; max: number },
): { page: number[]; next_before_uid: number | null; next_after_uid: number | null; has_more: boolean } {
const max = Math.max(1, Math.trunc(options.max));
if (options.afterUid != null) {
const sorted = all.filter((uid) => uid > options.afterUid!).sort((a, b) => a - b);
const page = sorted.slice(0, max);
return {
page,
next_before_uid: page.length ? page[0] : null,
next_after_uid: page.length ? page[page.length - 1] : null,
has_more: sorted.length > page.length,
};
}
const sorted = all
.filter((uid) => options.beforeUid == null || uid < options.beforeUid)
.sort((a, b) => b - a);
const page = sorted.slice(0, max);
return {
page,
next_before_uid: page.length ? page[page.length - 1] : null,
next_after_uid: null,
has_more: sorted.length > page.length,
};
}

function parseCursor(cursor: string | null): { validity: string; uid: number } | null {
const match = /^(\d+):(\d+)$/.exec(cursor ?? "");
return match ? { validity: match[1], uid: Number(match[2]) } : null;
Expand Down Expand Up @@ -159,39 +208,102 @@ async function compose(account: MailAccount, mail: OutgoingMail): Promise<{ raw:
return { raw: await node.build(), messageId };
}

/**
* MIME source → MailMessage. `skipHtmlToText` keeps an HTML-only body as HTML so
* the pure-TS extractor (table rows, hidden previews) handles it instead of
* mailparser's lossy plain-text rendering.
*/
export async function parseMailSource(id: string, source: Buffer | Readable): Promise<MailMessage> {
const parsed = await simpleParser(source, { keepCidLinks: true, skipHtmlToText: true });
const attachmentMeta: MailAttachmentMeta[] = parsed.attachments.map((item) => ({
filename: (item.filename ?? item.contentType) || "attachment",
content_type: item.contentType || "application/octet-stream",
size_bytes: item.size ?? item.content?.length ?? 0,
}));
const calendarPart = parsed.attachments.find((item) =>
item.contentType?.toLowerCase().startsWith("text/calendar") || /\.ics$/i.test(item.filename ?? ""));
const calendarBytes = calendarPart?.content;
const calendarText = calendarBytes && calendarBytes.length <= CALENDAR_BYTES
? calendarBytes.toString("utf8")
: (!calendarPart && parsed.text && /BEGIN:VCALENDAR/i.test(parsed.text) ? parsed.text.slice(0, CALENDAR_BYTES) : null);
const references = Array.isArray(parsed.references)
? parsed.references
: parsed.references ? [parsed.references] : [];
return {
id,
from: parsed.from ? people(parsed.from).join(", ") : "",
to: people(parsed.to),
cc: people(parsed.cc),
subject: parsed.subject ?? "",
date: parsed.date ? parsed.date.toISOString() : null,
text: parsed.text ?? "",
html: typeof parsed.html === "string" ? parsed.html : null,
attachments: parsed.attachments.map((item) => item.filename ?? item.contentType),
message_id: parsed.messageId ?? null,
in_reply_to: parsed.inReplyTo ?? null,
references,
attachment_meta: attachmentMeta,
calendar_ics: calendarText,
};
}

/** The MailClient the mail tool gets for one saved account. */
export function imapSmtpMail(account: MailAccount): MailClient {
return {
address: account.address,

list: ({ sinceDays, cursor, max }) => withImap(account, async (client) => {
list: ({ sinceDays, cursor, beforeUid, afterUid, max }) => withImap(account, async (client) => {
const lock = await client.getMailboxLock("INBOX", { readOnly: true });
try {
const box = client.mailbox;
const validity = box ? String(box.uidValidity) : "";
const after = parseCursor(cursor);
const found = after && after.validity === validity
? await client.search({ uid: `${after.uid + 1}:*` }, { uid: true })
: await client.search({ since: new Date(Date.now() - sinceDays * 86_400_000) }, { uid: true });
const uids = (found || []).filter((uid) => !after || after.validity !== validity || uid > after.uid).sort((a, b) => b - a).slice(0, max);
const rows = uids.length ? await client.fetchAll(uids, { uid: true, envelope: true, flags: true, bodyStructure: true, internalDate: true }, { uid: true }) : [];
const before = typeof beforeUid === "string" && /^\d+$/.test(beforeUid) ? Number(beforeUid) : null;
const afterNumber = typeof afterUid === "string" && /^\d+$/.test(afterUid) ? Number(afterUid) : null;
if (before !== null && afterNumber !== null) throw new CoreError("beforeUid 和 afterUid 不能同时使用");
const incremental = afterNumber === null && before === null && after && after.validity === validity;
const found = afterNumber !== null
? await client.search({ uid: `${afterNumber + 1}:*` }, { uid: true })
: incremental
? await client.search({ uid: `${after.uid + 1}:*` }, { uid: true })
: await client.search({ since: new Date(Date.now() - sinceDays * 86_400_000) }, { uid: true });
const all = found || [];
const page = pageUids(all, { afterUid: afterNumber, beforeUid: before, max });
const rows = page.page.length
? await client.fetchAll(page.page, { uid: true, envelope: true, flags: true, bodyStructure: true, internalDate: true }, { uid: true })
: [];
const byUid = new Map(rows.map((row) => [Number(row.uid), row]));
const messages: MailSummary[] = [];
for (const row of rows.sort((a, b) => b.uid - a.uid)) {
for (const uid of page.page) {
const row = byUid.get(uid);
if (!row) continue;
const part = textPart(row.bodyStructure);
const download = part ? await client.download(String(row.uid), part.part, { uid: true, maxBytes: PREVIEW_BYTES }) : null;
const body = download?.content ? await text(download.content) : "";
const date = row.envelope?.date ?? row.internalDate;
const attachments = attachmentParts(row.bodyStructure);
messages.push({
id: String(row.uid),
from: person(row.envelope?.from?.[0]),
subject: row.envelope?.subject ?? "",
date: date ? new Date(date).toISOString() : null,
preview: mailPreview(part?.html ? mailHtmlText(body) : body),
seen: Boolean(row.flags?.has("\\Seen")),
message_id: row.envelope?.messageId ?? null,
has_attachments: attachments.length > 0,
attachment_names: [...new Set(attachments.map((item) => attachmentName(item) ?? item.type))],
});
}
const newest = uids[0] ?? after?.uid ?? (box ? Number(box.uidNext) - 1 : 0);
return { messages, cursor: validity ? `${validity}:${newest}` : null };
const newestUid = afterNumber !== null
? page.next_after_uid ?? afterNumber
: all.length ? Math.max(...all) : after?.uid ?? (box ? Number(box.uidNext) - 1 : 0);
return {
messages,
cursor: validity ? `${validity}:${newestUid}` : null,
next_before_uid: page.next_before_uid === null ? null : String(page.next_before_uid),
next_after_uid: page.next_after_uid === null ? null : String(page.next_after_uid),
has_more: page.has_more,
};
} finally {
lock.release();
}
Expand All @@ -203,19 +315,7 @@ export function imapSmtpMail(account: MailAccount): MailClient {
try {
const download = await client.download(id, undefined, { uid: true, maxBytes: READ_BYTES });
if (!download?.content) throw new CoreError(`收件箱里没有邮件 ${id}`, "not_found");
const parsed = await simpleParser(download.content, { keepCidLinks: true });
const message: MailMessage = {
id,
from: parsed.from ? people(parsed.from).join(", ") : "",
to: people(parsed.to),
cc: people(parsed.cc),
subject: parsed.subject ?? "",
date: parsed.date ? parsed.date.toISOString() : null,
text: parsed.text ?? "",
html: typeof parsed.html === "string" ? parsed.html : null,
attachments: parsed.attachments.map((item) => item.filename ?? item.contentType),
};
return message;
return parseMailSource(id, download.content);
} finally {
lock.release();
}
Expand Down
8 changes: 6 additions & 2 deletions backend-ts/test/agent-permission-mode.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,12 +111,16 @@ describe("Part 1 read_only two-layer defense", () => {
address: "me@example.com",
async list() {
return {
messages: [{ id: "m1", subject: "面试通知", from: "hr@example.com", date: "2026-12-01", preview: "请准备", seen: false }],
messages: [{ id: "m1", subject: "面试通知", from: "hr@example.com", date: "2026-12-01", preview: "请准备", seen: false, message_id: "<m1@example.com>", has_attachments: false, attachment_names: [] }],
cursor: "1:1",
};
},
async read() {
return { id: "m1", subject: "面试通知", from: "hr@example.com", to: ["me@example.com"], cc: [], date: "2026-12-01", text: "明天 14:00 一面", html: null, attachments: [] };
return {
id: "m1", subject: "面试通知", from: "hr@example.com", to: ["me@example.com"], cc: [], date: "2026-12-01",
text: "明天 14:00 一面", html: null, attachments: [], message_id: "<m1@example.com>", in_reply_to: null,
references: [], attachment_meta: [], calendar_ics: null,
};
},
async saveDraft() {
throw new Error("should not create draft in read_only");
Expand Down
Loading