Skip to content
Merged
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
20 changes: 20 additions & 0 deletions vika/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,26 @@ Agent 可用 `list_chat_members` 分页查询当前频道或私聊的成员,

每个文件夹独立记录 UIDVALIDITY 和 UID。某个目录临时无权限或被删除不会阻塞其他目录,断线后退避重连并续接游标;目录重编号时只重置该目录,按首次监听规则从新邮件开始。每轮每目录最多处理最新 50 封待处理邮件,超出部分跳过(SEARCH 响应本身未限量);附件处理也会延长轮询周期。跨文件夹移动/复制邮件可能再次提醒,因为它在目标目录获得新的 IMAP 身份,不按 Message-ID 全局去重。

需要发现后来新建的文件夹时,改用 `imap.discovery`(不能与 `mailbox` / `mailboxes` 并用):

```json
{
"host": "imap.example.com",
"port": 993,
"pollIntervalSeconds": 60,
"discovery": {
"roots": ["INBOX", "Projects"],
"exclude": ["Projects/Trash"],
"refreshIntervalSeconds": 300
}
}
```

以上是账号文件中的 `imap` 对象。通过 `LIST "" "*"` 获取可选择目录,按服务器返回的层级分隔符选择根目录及子目录;`Projects` 不会误匹配 `ProjectsOld`。`roots` 留空表示所有可选择目录,排除项也作用于其子目录。垃圾箱、已发送目录的名字由供应商决定,请明确填写排除项;不会猜测文件夹的用途。发现模式始终轮询,默认每 300 秒刷新列表(可设 15–86400 秒,实际还受轮询和处理时间影响)。最多匹配 100 个目录,超过时拒绝该次刷新,请缩小范围。刷新失败保留最近一次成功列表,删除目录保留游标以便重现后续接;新发现目录仍只提醒之后的新邮件。日志中的 `email_mailboxes_discovered` 记录匹配数量,失败会记录 `email_mailbox_discovery_failed`,不会静默切回 INBOX。

协议依据:[RFC 9051](https://www.rfc-editor.org/rfc/rfc9051.html) 的 mailbox、UIDVALIDITY、UID 身份与 LIST;[RFC 2177](https://www.rfc-editor.org/rfc/rfc2177.html) 的 IDLE;IMAP4rev1 非 ASCII 名称按 [RFC 3501 §5.1.3](https://www.rfc-editor.org/rfc/rfc3501.html#section-5.1.3) 编码。NOTIFY / OBJECTID 不属于这一版实现。



`password` 是邮箱给第三方客户端用的专用密码,按邮箱账号生成一次,IMAP 和 SMTP 共用:Gmail 叫应用密码(需先开两步验证,填写时去掉空格),QQ/163 叫授权码(需先在设置里开启 IMAP/SMTP)。SMTP 在 465 端口用直连 TLS,其他端口用 STARTTLS,可用 `smtp.secure` 覆盖;可选 `username`(默认同 `address`)和 `name`(回信的发件人名)。只用 OAuth 的邮箱(如 Outlook)暂不支持。方舟 Self-hosted Ark 用不了 Agent 工具,因此不支持邮箱。

Expand Down
41 changes: 34 additions & 7 deletions vika/packages/daemon/src/email/client.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ import { eventMessage } from '../connectors/protocol.mjs';
import { safeError } from '../logger.mjs';
import { MailArchive, parsesAttachment } from './archive.mjs';
import { ImapConnection } from './imap.mjs';
import { configuredMailboxes, mailboxIdentity, mailboxPollSeconds } from './mailbox.mjs';
import { configuredMailboxes, mailboxDiscovery, mailboxIdentity, mailboxPollSeconds } from './mailbox.mjs';
import { listMailboxes, selectMailboxes } from './list-mailboxes.mjs';
import { buildReply, decodeCharset, isOwnMessageId, parseMail, replyMessageId } from './mime.mjs';
import { sendMail, verifySmtp } from './smtp.mjs';
import { EmailState } from './state.mjs';
Expand Down Expand Up @@ -56,7 +57,7 @@ export function loadAccount(file) {
user: typeof value.username === 'string' && value.username.trim() ? value.username.trim() : address,
password: value.password,
imap: { ...server('imap'), mailbox: configuredMailboxes(value.imap)[0],
mailboxes: configuredMailboxes(value.imap), pollIntervalSeconds: mailboxPollSeconds(value.imap?.pollIntervalSeconds) },
mailboxes: configuredMailboxes(value.imap), discovery: mailboxDiscovery(value.imap), pollIntervalSeconds: mailboxPollSeconds(value.imap?.pollIntervalSeconds) },
smtp: server('smtp'),
});
}
Expand All @@ -75,9 +76,12 @@ export async function verifyAccount(account, { connectTls } = {}) {
try {
await imap.connect();
await imap.login(account.user, account.password);
let selected = false;
const names = account.imap.discovery
? discoveredNames(await listMailboxes(imap), account.imap.discovery)
: account.imap.mailboxes ?? [account.imap.mailbox];
let selected = names.length === 0 && !!account.imap.discovery;
let selectionError;
for (const name of account.imap.mailboxes ?? [account.imap.mailbox]) {
for (const name of names) {
try { await imap.examine(name); selected = true; } catch (error) {
if (imap.closed) throw error;
selectionError = error;
Expand All @@ -93,6 +97,12 @@ export async function verifyAccount(account, { connectTls } = {}) {
return { idle };
}

function discoveredNames(entries, discovery) {
const names = selectMailboxes(entries, discovery).map((entry) => entry.name);
if (names.length > 100) throw new Error('Email discovery matched more than 100 folders; narrow imap.discovery.roots or exclude');
return names;
}

function people(list) {
const shown = list.slice(0, MAX_LISTED).map(({ name, address }) => (name ? `${name} <${address}>` : address));
if (list.length > MAX_LISTED) shown.push(`+${list.length - MAX_LISTED} more`);
Expand Down Expand Up @@ -226,11 +236,12 @@ function sleep(ms, stopped) {
// an event; replies to a reported mail over SMTP. Never marks, moves or
// deletes mail.
export class EmailClient {
constructor(config, _registry, logger, { connectTls, archive = null, attachmentWaitMs = ATTACHMENT_WAIT_MS, pollMs, reconnectMs = 1_000 } = {}) {
constructor(config, _registry, logger, { connectTls, archive = null, attachmentWaitMs = ATTACHMENT_WAIT_MS, pollMs, discoveryMs, reconnectMs = 1_000 } = {}) {
this.config = config;
this.logger = logger;
this.connectTls = connectTls;
this.pollMs = pollMs;
this.discoveryMs = discoveryMs;
this.reconnectMs = reconnectMs;
this.state = new EmailState(config.dataDir, config.instance ?? 'email');
this.archive = archive;
Expand Down Expand Up @@ -287,7 +298,10 @@ export class EmailClient {
}

async watch(onLine) {
const names = this.account.imap.mailboxes ?? [this.account.imap.mailbox];
const discovery = this.account.imap.discovery;
let names = discovery ? [] : this.account.imap.mailboxes ?? [this.account.imap.mailbox];
let refreshedAt = null;
const discoveryMs = this.discoveryMs ?? (discovery?.refreshIntervalSeconds ?? 300) * 1_000;
const pollMs = this.pollMs ?? this.account.imap.pollIntervalSeconds * 1_000;
let next = 0;
let failures = 0;
Expand All @@ -298,6 +312,19 @@ export class EmailClient {
if (this.stopping) break;
while (!this.stopping) {
let idled = false;
if (discovery && (refreshedAt === null || Date.now() - refreshedAt >= discoveryMs)) {
try {
const found = discoveredNames(await listMailboxes(imap), discovery);
names = found;
next = names.length ? next % names.length : 0;
this.logger.info('email_mailboxes_discovered', { count: names.length });
} catch (error) {
if (imap.closed) throw error;
// Preserve the last successful snapshot on a failed LIST.
this.logger.warn('email_mailbox_discovery_failed', { error: safeError(error) });
}
refreshedAt = Date.now();
}
// Advance before opening a folder. A broken folder or connection
// cannot indefinitely starve the folders after it.
for (let count = 0; count < names.length && !this.stopping; count += 1) {
Expand All @@ -320,7 +347,7 @@ export class EmailClient {
this.logger.warn('email_mailbox_unavailable', { mailbox: name, error: safeError(error) });
continue;
}
if (names.length === 1 && imap.capabilities.has('IDLE') && !this.stopping) {
if (!discovery && names.length === 1 && imap.capabilities.has('IDLE') && !this.stopping) {
await imap.idle(IDLE_MS, () => this.stopping);
idled = true;
}
Expand Down
72 changes: 72 additions & 0 deletions vika/packages/daemon/src/email/list-mailboxes.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
// Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
// SPDX-License-Identifier: AGPL-3.0

import { parseResponse } from './imap.mjs';
import { mailboxName } from './mailbox.mjs';

// Response text arrives as latin1 byte-preserving strings; literals are Buffers.
function wireBytes(value) {
if (Buffer.isBuffer(value)) return value;
if (typeof value === 'string') return Buffer.from(value, 'latin1');
if (value && typeof value.string === 'string') return Buffer.from(value.string, 'latin1');
throw new Error('Invalid IMAP LIST string');
}

export function decodeMailboxName(value, { utf8 = false } = {}) {
const bytes = wireBytes(value);
if (utf8) return new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes);
if ([...bytes].some((byte) => byte < 0x20 || byte > 0x7e)) throw new Error('Invalid IMAP modified UTF-7 mailbox name');
return bytes.toString('ascii').replace(/&([^-]*)-|&/g, (_, encoded) => {
if (encoded === undefined) throw new Error('Unterminated IMAP modified UTF-7 shift');
if (!encoded) return '&';
if (!/^[A-Za-z0-9+,]+$/.test(encoded)) throw new Error('Invalid IMAP modified UTF-7 shift');
const decoded = Buffer.from(encoded.replace(/,/g, '/'), 'base64');
if (!decoded.length || decoded.length % 2 || decoded.toString('base64').replace(/\//g, ',').replace(/=+$/, '') !== encoded) {
throw new Error('Invalid IMAP modified UTF-7 shift');
}
return new TextDecoder('utf-16be', { fatal: true, ignoreBOM: true }).decode(decoded);
}).replace(/\u0000/g, () => { throw new Error('Invalid IMAP mailbox name'); });
}

// Return null for unrelated unsolicited responses. Malformed LIST results fail
// the refresh so the caller can keep its previous successful discovery snapshot.
export function parseListResponse(parts, { utf8 = false } = {}) {
const tokens = parseResponse(parts);
if (tokens[0] !== '*' || String(tokens[1]).toUpperCase() !== 'LIST') return null;
const [, , attributes, separator, mailbox] = tokens;
if (!Array.isArray(attributes) || mailbox === undefined || attributes.some((flag) => typeof flag !== 'string')) {
throw new Error('Invalid IMAP LIST response');
}
const delimiter = typeof separator === 'string' && separator.toUpperCase() === 'NIL' ? null : new TextDecoder(utf8 ? 'utf-8' : 'latin1', { fatal: true }).decode(wireBytes(separator));
if (delimiter !== null && [...delimiter].length !== 1) throw new Error('Invalid IMAP LIST delimiter');
const name = mailboxName(decodeMailboxName(mailbox, { utf8 }));
return { name, delimiter, flags: attributes.map((flag) => flag.toLowerCase()) };
}

export async function listMailboxes(imap) {
const { untagged } = await imap.command('LIST', '"" "*"');
const utf8 = imap.capabilities.has('IMAP4REV2');
return untagged.map((parts) => parseListResponse(parts, { utf8 })).filter(Boolean);
}

// Match the root itself or a child separated by the server's hierarchy delimiter.
// A missing root may still have children; use the candidate's delimiter then.
export function selectMailboxes(entries, { roots = [], exclude = [] } = {}) {
const included = roots.map((name) => mailboxName(name));
const excluded = exclude.map((name) => mailboxName(name));
const known = new Map(entries.map((entry) => [entry.name, entry]));
const under = (entry, root) => {
if (entry.name === root) return true;
const delimiter = known.has(root) ? known.get(root).delimiter : entry.delimiter;
return delimiter !== null && entry.name.startsWith(`${root}${delimiter}`);
};
const seen = new Set();
return entries.filter((entry) => {
if (seen.has(entry.name)) return false;
if (entry.flags.some((flag) => ['\\noselect', '\\nonexistent'].includes(flag.toLowerCase()))) return false;
if (included.length && !included.some((root) => under(entry, root))) return false;
if (excluded.some((root) => under(entry, root))) return false;
seen.add(entry.name);
return true;
});
}
19 changes: 19 additions & 0 deletions vika/packages/daemon/src/email/mailbox.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -46,3 +46,22 @@ export function mailboxPollSeconds(value = 60) {
}
return value;
}

// Discovery is opt-in and replaces the explicit set, rather than silently
// subscribing existing accounts to all folders.
export function mailboxDiscovery(imap = {}) {
const value = imap.discovery;
if (value === undefined) return null;
if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('imap.discovery must be an object');
if (imap.mailbox !== undefined || imap.mailboxes !== undefined) throw new Error('imap.discovery cannot be combined with mailbox or mailboxes');
const names = (key) => {
const items = value[key] ?? [];
if (!Array.isArray(items) || items.length > 100) throw new Error(`imap.discovery.${key} must be an array of at most 100 names`);
return [...new Set(items.map(mailboxName))];
};
const refreshIntervalSeconds = value.refreshIntervalSeconds ?? 300;
if (!Number.isInteger(refreshIntervalSeconds) || refreshIntervalSeconds < 15 || refreshIntervalSeconds > 86400) {
throw new Error('imap.discovery.refreshIntervalSeconds must be an integer from 15 to 86400');
}
return { roots: names('roots'), exclude: names('exclude'), refreshIntervalSeconds };
}
67 changes: 67 additions & 0 deletions vika/packages/daemon/test/email-list.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
// Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
// SPDX-License-Identifier: AGPL-3.0

import assert from 'node:assert/strict';
import { test } from 'node:test';
import { decodeMailboxName, listMailboxes, parseListResponse, selectMailboxes } from '../src/email/list-mailboxes.mjs';
import { mailboxWireName } from '../src/email/mailbox.mjs';

const entry = (name, delimiter = '/', flags = []) => ({ name, delimiter, flags });

test('LIST parses quoted names, escaped strings, literals and unsolicited responses', () => {
assert.deepEqual(parseListResponse([String.raw`* LIST (\HasNoChildren) "/" "Work \"quoted\""`]),
entry('Work "quoted"', '/', ['\\hasnochildren']));
assert.deepEqual(parseListResponse(['* LIST () NIL {10}', Buffer.from(' A\\folder '), '']), entry(' A\\folder ', null));
assert.deepEqual(parseListResponse(['* LIST (\\Noselect) "." Archive']), entry('Archive', '.', ['\\noselect']));
assert.deepEqual(parseListResponse(['* LIST () "&" inbox']), entry('INBOX', '&'));
assert.equal(parseListResponse(['* 3 EXISTS']), null);
assert.equal(parseListResponse(['* OK hello']), null);
});

test('mailbox decoding handles modified UTF-7 and byte-preserving rev2 UTF-8', () => {
for (const name of ['台北', '邮件 & 工作', 'emoji 📬', '\ufefffolder']) {
assert.equal(decodeMailboxName(mailboxWireName(name)), name);
const wire = Buffer.from(name);
assert.equal(decodeMailboxName(wire, { utf8: true }), name);
assert.equal(parseListResponse([`* LIST () "/" "${wire.toString('latin1')}"`], { utf8: true }).name, name);
assert.equal(parseListResponse(['* LIST () "/" {999}', wire, ''], { utf8: true }).name, name);
}
assert.equal(decodeMailboxName('&-'), '&');
for (const bad of ['&unterminated', '&A-', '&AA=-', '&/w-', '&2AA-']) {
assert.throws(() => decodeMailboxName(bad));
}
assert.throws(() => decodeMailboxName(Buffer.from([0xff]), { utf8: true }));
assert.throws(() => parseListResponse(['* LIST () "/" ""']));
});

test('selection uses hierarchy boundaries, skips nonselectable folders, and preserves order', () => {
const entries = [entry('INBOX'), entry('Work', '/', ['\\Noselect']), entry('Work/Inbox'),
entry('Work/Trash'), entry('Work/Trash/Old'), entry('Work/Trashcan'), entry('Workshops'),
entry('Work/Gone', '/', ['\\NonExistent']), entry('Work/Inbox'), entry('work/lower')];
assert.deepEqual(selectMailboxes(entries, { roots: ['Work'], exclude: ['Work/Trash'] }).map((box) => box.name),
['Work/Inbox', 'Work/Trashcan']);
assert.deepEqual(selectMailboxes(entries, { roots: ['inbox'] }).map((box) => box.name), ['INBOX']);
assert.deepEqual(selectMailboxes(entries, { roots: ['Missing'] }), []);
assert.equal(selectMailboxes(entries).length, 7);
});

test('dot and NIL hierarchies and absent parents have exact subtree semantics', () => {
const entries = [entry('Root', '.'), entry('Root.Child', '.'), entry('Rootish.Child', '.'),
entry('Flat', null), entry('Flat.Child', null), entry('Absent/Child'), entry('Absent/Trash')];
assert.deepEqual(selectMailboxes(entries, { roots: ['Root'] }).map((box) => box.name), ['Root', 'Root.Child']);
assert.deepEqual(selectMailboxes(entries, { exclude: ['Flat'] }).map((box) => box.name),
['Root', 'Root.Child', 'Rootish.Child', 'Flat.Child', 'Absent/Child', 'Absent/Trash']);
assert.deepEqual(selectMailboxes(entries, { roots: ['Absent'], exclude: ['Absent/Trash'] }).map((box) => box.name), ['Absent/Child']);
});

test('discovery uses LIST and fails malformed refreshes instead of returning partial snapshots', async () => {
const calls = [];
const imap = { capabilities: new Set(['IMAP4REV2']), command: async (...args) => {
calls.push(args);
return { untagged: [['* OK ignored'], ['* LIST () "/" {6}', Buffer.from('工作'), '']] };
} };
assert.deepEqual(await listMailboxes(imap), [entry('工作')]);
assert.deepEqual(calls, [['LIST', '"" "*"']]);
imap.command = async () => ({ untagged: [['* LIST () "/" Inbox'], ['* LIST broken']] });
await assert.rejects(listMailboxes(imap), /Invalid IMAP LIST/);
});
Loading