diff --git a/guide.md b/guide.md new file mode 100644 index 0000000..42f0a67 --- /dev/null +++ b/guide.md @@ -0,0 +1,222 @@ +# DSH 邮件网关插件 — 完整开发计划 + +插件形态:**函数形态常驻入口**(`export const name / inject / Config` + `export function apply`,无 default export)。核心链路沿用已确认的模块划分,本计划把 **UI 配置页**作为第一优先级展开,服务商适配收敛为“探测 IDLE → 提示 → 不支持则轮询”,代码中不出现服务商名。 + +--- + +## 一、模块清单 + +``` +src/ +├── index.ts # 入口:name / inject / Config / apply + RPC 注册 +├── gateway.ts # MailGateway:唯一持有 ctx 的编排层,转发状态 +├── receiver.ts # ImapReceiver:能力探测、IDLE/轮询、游标、重连 +├── sender.ts # SmtpSender:transporter 池、线程头 +├── policy.ts # AccessPolicy:纯函数,白名单 + 防环 +├── deliver.ts # 唯一触碰 ctx.agents 的地方 +└── client/ + ├── index.ts # client 入口:注册 settings.section + └── MailGatewaySection.tsx # 配置页主体 +``` + +`receiver` 只产出 `MailJob | null` 和状态;`sender` 只接收 `ReplyMessage`;`policy` 无 IO;`deliver` 是 `ctx.agents` 的唯一适配点。`MailGateway` 是唯一同时持有四者并做编排的地方,也是状态的唯一出口。 + +--- + +## 二、UI 配置页(本计划重点) + +### 2.1 注册方式 + +DSH ≥ 0.1.6-alpha.2 起,插件配置从设置页迁到侧边栏「插件」页,`settings.plugin.item` 已退役。走 **`settings.section` 槽位**,与「通用设置」平级: + +```ts +// client/index.ts +export function apply(ctx: ClientContext) { + ctx.slots.inject('settings.section', () => ctx.slots.register( + { name: 'settings.section', id: 'mail-gateway', order: 50, label: '邮件网关' }, + MailGatewaySection, + )) +} +``` + +约束(来自 DSH 侧边栏规范): + +- `id` 必填,`label` 直接作为可见文字;**图标由外壳按 `id` 查表,未知 id 回退齿轮图标**,插件无法自定义图标。 +- 内容区宽度约 **559px**(800 − 188 左栏 − 48 padding − 滚动条)。 +- 根节点**不要**写 `height: 100%` 或 `overflow-y: auto`,滚动由外壳负责。 + +### 2.2 页面分区(自上而下) + +``` +┌──────────────────────────────────────────────┐ +│ ① 连接状态卡片(只读) │ +│ ● 已连接 · 支持实时推送(IDLE) │ +│ 或 ● 已连接 · 服务器不支持 IDLE,轮询 60s │ +│ 或 ○ 正在连接… / ✕ 连接失败:原因 │ +├──────────────────────────────────────────────┤ +│ ② 邮箱绑定表格(IMAP 收信 / SMTP 发信) │ +│ ┌──────────┬──────────────┬─────────┐ │ +│ │ 字段 │ 输入 │ 说明 │ │ +│ ├──────────┼──────────────┼─────────┤ │ +│ │ IMAP 主机 │ [__________] │ SSL 993 │ │ +│ │ ... │ │ │ │ +│ └──────────┴──────────────┴─────────┘ │ +│ [ 测试连接 ] [ 保存 ] │ +├──────────────────────────────────────────────┤ +│ ③ 白名单表格(可增删) │ +│ ┌────────────────────┬──────┐ │ +│ │ 发件地址 │ 操作 │ │ +│ ├────────────────────┼──────┤ │ +│ │ alice@corp.com │ 删除 │ │ +│ │ bob@partner.io │ 删除 │ │ +│ └────────────────────┴──────┘ │ +│ [ 输入地址回车添加________________ ] │ +│ [ 保存白名单 ] │ +└──────────────────────────────────────────────┘ +``` + +### 2.3 ① 连接状态卡片 + +只读展示,数据来自 `mail-gateway.status` RPC。四种状态对应四种文案与颜色: + +| 状态 | 文案 | 视觉 | +| :--- | :--- | :--- | +| `connecting` | 正在连接… | 灰点,脉冲动画 | +| `connected` + `idle: true` | 已连接 · 支持实时推送(IDLE) | 绿点 | +| `connected` + `idle: false` | 已连接 · 服务器不支持 IDLE,使用 60 秒轮询,收信延迟最长约 1 分钟 | 黄点 + 说明 | +| `error` | 连接失败:{message} | 红点 | + +这张卡片是用户判断“为什么收信慢”的唯一入口,`idle: false` 的说明文字必须完整,不能只写“不支持 IDLE”。卡片在页面加载时拉一次状态,并在 `test` / `save` 成功后刷新。 + +### 2.4 ② 邮箱绑定表格 + +用真正的 `` 布局,每行一个字段,三列:**字段名 / 输入控件 / 说明**。说明列固定文案,不随输入变化。 + +**IMAP 收信** + +| 字段 | 控件 | 说明 | +| :--- | :--- | :--- | +| IMAP 主机 | text | 如 `imap.larksuite.com` | +| 端口 | number,默认 993 | SSL 通常 993 | +| SSL | checkbox,默认勾选 | | +| 用户名 | text | 完整邮箱地址 | +| 密码 / 授权码 | password | 保存后只回显“已设置” | + +**SMTP 发信** + +| 字段 | 控件 | 说明 | +| :--- | :--- | :--- | +| SMTP 主机 | text | 如 `imap.larksuite.com` | +| 端口 | number,默认 465 | SSL 通常 465 | +| SSL | checkbox,默认勾选 | | +| 发件人显示名 | text,默认 `DSH Assistant` | 回信 `From` 的显示名 | + +密码字段:读接口返回 `{ set: true }` 而非明文,输入框 `placeholder` 显示“已设置,留空则不修改”;用户输入新值才覆盖,留空则保留原密码。这是 UI 的标准做法,不是防御性编程。 + +**两个按钮** + +- **测试连接**:调 `mail-gateway.test`,后端用当前表单值临时建一次 IMAP 连接、登录、`capability()`,返回 `{ ok, idle, error }`。结果直接写进 ① 状态卡片,用户填完配置**立刻**知道是否支持 IDLE,不必等保存后被动刷新。这是本页最重要的交互——IDLE 支持情况在用户决策点上就可见。 +- **保存**:调 `mail-gateway.save`,写回 `ctx.settings`,触发 `settings/updated` → `gateway.reload`。保存成功后刷新 ① 状态卡片。 + +### 2.5 ③ 白名单表格 + +两列表格:**发件地址 / 操作**。每行末尾一个删除按钮。表格下方一个输入框 + “添加”按钮,回车或点击添加即插入一行(本地状态,未提交)。底部“保存白名单”按钮调 `mail-gateway.save-whitelist`,`policy.update` 立即生效,**不断开 IMAP 连接**。 + +地址校验只做一项:`normalize` 后非空即接受(`normalize` 与后端 `AccessPolicy` 共用同一函数,保证两侧匹配语义一致)。不写邮箱正则——后端精确匹配,正则只会制造前后端不一致。空列表允许保存,此时 ① 卡片下方追加一行提示:“白名单为空,不会接收任何邮件”。 + +### 2.6 组件树 + +``` +MailGatewaySection +├── StatusCard # 读 status,纯展示 +├── MailboxFormTable # 受控表单,本地 state +│ ├── ImapFields +│ ├── SmtpFields +│ └── FormActions # 测试连接 / 保存 +└── WhitelistTable + ├── AddressRow[] # 地址 + 删除 + └── AddAddressInput # 输入 + 添加 +``` + +`StatusCard` 只接收 props,不发请求;数据由 `MailGatewaySection` 统一拉取和刷新,避免每个子组件各自轮询。 + +### 2.7 RPC 契约 + +| RPC | 入参 | 返回 | +| :--- | :--- | :--- | +| `mail-gateway.get` | — | `{ mailbox: MaskedMailbox, whitelist: string[], reply: {...} }` | +| `mail-gateway.save` | `MailboxInput` | `{ ok: true }` | +| `mail-gateway.test` | `MailboxInput` | `{ ok: boolean, idle?: boolean, error?: string }` | +| `mail-gateway.save-whitelist` | `string[]` | `{ ok: true }` | +| `mail-gateway.status` | — | `ReceiverStatus` | + +`MailboxInput` 中 `password` 为 `string | undefined`,`undefined` 表示“不修改”。`test` 用临时连接,不触碰正在运行的 `ImapReceiver`,测试完 `logout`。 + +--- + +## 三、状态模型 + +```ts +export type ReceiverStatus = + | { state: 'connecting' } + | { state: 'connected'; idle: boolean; since: number } + | { state: 'error'; message: string } +``` + +`ImapReceiver` 在 `connect()` 登录完成后写入 `connected`,重连退避期间写 `error`,`reload` 重建时写 `connecting`。`MailGateway.getStatus()` 直接转发,RPC 读它。状态只此一处产生,`test` RPC 的结果是独立返回值,不写回 `receiver`——测试的是表单值,不是运行中的连接。 + +--- + +## 四、后端要点(承接已确认设计) + +**能力探测与分支**(`receiver.ts`): + +```ts +await this.client.connect() // 含登录 +const caps = await this.client.capability() +const idle = caps.has('IDLE') +this.status = { state: 'connected', idle, since: Date.now() } + +if (idle) { + this.client.on('exists', () => this.fetchNew()) + this.idleTimer = setInterval(() => this.client?.exec('NOOP').catch(() => {}), 29 * 60 * 1000) +} else { + this.pollTimer = setInterval(() => this.fetchNew(), 60_000) +} +``` + +必须在**认证之后**探测,覆盖 iCloud 这类登录后才公告 IDLE 的服务器。分支只取决于 `caps.has('IDLE')`,不出现服务商名。 + +**准入与提取**(`toJob`):白名单不通过或 `Auto-Submitted` / `Precedence` 命中则返回 `null`,静默丢弃。`fetching` 守卫防轮询重入。UID 游标持久化,首次配置建基线不回放历史。 + +**会话**(`deliver.ts`):`sessionId = mail:${normalize(from)}` 是纯函数;`get` → 不存在则探测 → `resume` 或 `create`;`followup(text)` 投递;监听 `session/event` 的 `assistant/message` durable 事件取回复,不订阅流。 + +**发送**(`sender.ts`):单例 transporter + `pool: true`,`maxConnections: 3`,`maxMessages: 50`;`In-Reply-To` / `References` 保证线程归并;出站不做白名单二次校验。 + +**编排**(`gateway.ts`):`drain` 串行消费带必要 `try/catch`;`reload(next)` 不接 `ctx`,白名单变更只 `policy.update`,`mailbox` 变更才重连;`stop()` 依次 `receiver.stop()` → `sender.close()`。 + +--- + +## 五、实施顺序 + +| 阶段 | 内容 | 验证点 | +| :--- | :--- | :--- | +| 1 | 入口 + Config + `ctx.effect` 清理骨架 | Fiber 进入 ACTIVE,卸载无残留 | +| 2 | `AccessPolicy` 单测 | 精确命中、自动流量拦截、`normalize` 前后端一致 | +| 3 | `ImapReceiver` + 认证后探测 + 轮询回退 + 状态写入 | Zoho 显示 `idle: true`;Lark 显示 `idle: false` 且 60s 内收到新邮件 | +| 4 | `SmtpSender` + 连接池 + 线程头 | 回信归入原线程,池连接复用 | +| 5 | `deliver` + `MailGateway` 编排 + 五个 RPC | 同地址续接会话,重启 `resume` 不 `create` | +| 6 | **UI:`settings.section` 注册 + 三张卡片/表格 + 测试连接** | 填表 → 测试连接 → 状态卡显示 IDLE 结果;白名单增删保存不断连 | +| 7 | 热重载与并发边界 | 改白名单不断连、多封信不丢推送、测试连接不影响运行中连接 | + +阶段 6 依赖 5 的 RPC 就绪,但**UI 的静态布局(三张卡片、两张表格的 DOM 结构与样式)可以在阶段 1 之后并行开发**,用 mock 数据填充,RPC 就绪后替换数据源。`test` RPC 与 `status` RPC 的返回结构在阶段 5 与前端对齐一次即可,避免 UI 联调时反复改契约。 + +--- + +## 六、明确不做的 + +- **不按服务商名硬编码分支**:只认 `caps.has('IDLE')`。 +- **不做发送频率限制**:按需求,没有发送墙。 +- **不处理附件**:`toJob` 只取 `text/plain`,HTML 降级,附件丢弃。 +- **不做白名单正则校验**:精确地址匹配,前端只做 `normalize` 非空校验。 +- **不在 UI 里重复轮询**:状态由 `MailGatewaySection` 统一拉取,`StatusCard` 纯展示。 \ No newline at end of file diff --git a/package-lock.json b/package-lock.json index 28a077e..f421fe3 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,30 +1,48 @@ { "name": "dsh-mail-sender", - "version": "0.1.0", + "version": "0.2.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "dsh-mail-sender", - "version": "0.1.0", + "version": "0.2.0", "dependencies": { "imapflow": "^1.0.171", "mailparser": "^3.7.1", - "nodemailer": "^6.9.16" + "nodemailer": "^6.9.16", + "zod": "4.6.6" }, "devDependencies": { "@deepseek-ai/cordis": "4.1.0", - "@deepseek-ai/dsh-agent": "0.1.0-rc.6", - "@deepseek-ai/dsh-llm": "0.0.1-rc.1", + "@deepseek-ai/cordis-plugin-loader": "~1.1.0", + "@deepseek-ai/dsh-agent": "0.2.2-rc.2", + "@deepseek-ai/dsh-api-remotes": "0.2.2-rc.2", + "@deepseek-ai/dsh-client-ui-renderer": "0.2.2-rc.2", + "@deepseek-ai/dsh-client-ui-settings": "0.2.2-rc.2", + "@deepseek-ai/dsh-client-ui-slots": "0.2.2-rc.2", + "@deepseek-ai/dsh-llm": "0.2.2-rc.2", + "@deepseek-ai/dsh-session": "0.2.2-rc.2", + "@deepseek-ai/dsh-settings": "0.2.2-rc.2", + "@deepseek-ai/dsh-typert-protocol": "0.2.2-rc.2", "@deepseek-ai/schemastery": "3.19.0", + "@types/node": "^22.10.0", "@types/nodemailer": "^6.4.17", + "@types/react": "^18.3.12", + "esbuild": "^0.28.2", + "react": "^18.3.1", "typescript": "^5.6.0" }, + "engines": { + "dsh": ">=0.2.2-rc.2" + }, "peerDependencies": { - "@deepseek-ai/cordis": "^4.0.1", - "@deepseek-ai/dsh-agent": "^0.1.0-rc.0", - "@deepseek-ai/dsh-llm": "^0.0.1-rc.0", - "@deepseek-ai/schemastery": "^3.0.0" + "@deepseek-ai/cordis": "^4.1.0", + "@deepseek-ai/dsh-agent": ">=0.2.2-rc.2", + "@deepseek-ai/dsh-llm": ">=0.2.2-rc.2", + "@deepseek-ai/dsh-settings": ">=0.2.2-rc.2", + "@deepseek-ai/dsh-typert-protocol": ">=0.2.2-rc.2", + "@deepseek-ai/schemastery": "^3.19.0" } }, "node_modules/@deepseek-ai/cordis": { @@ -53,6 +71,26 @@ } } }, + "node_modules/@deepseek-ai/cordis-plugin-loader": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@deepseek-ai/cordis-plugin-loader/-/cordis-plugin-loader-1.1.0.tgz", + "integrity": "sha512-154u0LnADauDvOdQ41QtoOrRFQtvP2Ih68aYYaXzI/l7gRPwX/5MDtDDsJWeDffQA3ELn2xt3MUYsyizi+O9KA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@deepseek-ai/cosmokit": "~1.9.0", + "@deepseek-ai/schemastery": "~3.19.0" + }, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.1.0", + "node-addon-require-builtin": "^0.1.9" + }, + "peerDependenciesMeta": { + "node-addon-require-builtin": { + "optional": true + } + } + }, "node_modules/@deepseek-ai/cosmokit": { "version": "1.9.0", "resolved": "https://registry.npmjs.org/@deepseek-ai/cosmokit/-/cosmokit-1.9.0.tgz", @@ -61,36 +99,232 @@ "license": "MIT" }, "node_modules/@deepseek-ai/dsh-agent": { - "version": "0.1.0-rc.6", - "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-agent/-/dsh-agent-0.1.0-rc.6.tgz", - "integrity": "sha512-vtqq2pWTrzn0dKfj5kREZRpP82AwtGjGx9V1lYnKvF+Uc/a8zyWbSvjDE7V1d3YQAQJzs2cWO31hURWDekDXIA==", + "version": "0.2.2-rc.2", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-agent/-/dsh-agent-0.2.2-rc.2.tgz", + "integrity": "sha512-UsbQ3QBB8Gl8YTzQ7ScuXHuuI8o+1m1vZktAA3ayzxZHxvX1uRAG3kYkKf8sDRlkhue63Zb+DfAw3VPjd3PSpw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@deepseek-ai/dsh-brand": "0.2.2-rc.2", + "zod": "4.6.6" + }, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.1.0", + "@deepseek-ai/dsh-llm": "0.2.2-rc.2", + "@deepseek-ai/dsh-scope": "0.2.2-rc.2", + "@deepseek-ai/dsh-session": "0.2.2-rc.2", + "@deepseek-ai/dsh-session-projection": "0.2.2-rc.2", + "@deepseek-ai/dsh-system-prompt": "0.2.2-rc.2", + "@deepseek-ai/dsh-typert-protocol": "0.2.2-rc.2", + "@deepseek-ai/dsh-util-values": "0.2.2-rc.2", + "@deepseek-ai/dsh-workspace": "0.2.2-rc.2" + }, + "peerDependenciesMeta": { + "@deepseek-ai/dsh-workspace": { + "optional": true + } + } + }, + "node_modules/@deepseek-ai/dsh-api-remotes": { + "version": "0.2.2-rc.2", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-api-remotes/-/dsh-api-remotes-0.2.2-rc.2.tgz", + "integrity": "sha512-FSTcY/dN+qf8sicZ/YEd3h4awGGSKyAuWz/q71V0wwAleUsNBM+Tx7HHwdCe4BSJT5ZZewB49pHMH817DGvMaA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@deepseek-ai/dsh-deque": "0.2.2-rc.2", + "@deepseek-ai/dsh-util-values": "0.2.2-rc.2" + }, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.1.0", + "@deepseek-ai/dsh-scope": "0.2.2-rc.2" + } + }, + "node_modules/@deepseek-ai/dsh-atomic-write": { + "version": "0.2.2-rc.2", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-atomic-write/-/dsh-atomic-write-0.2.2-rc.2.tgz", + "integrity": "sha512-uSXsB2Jr1sAONYEF40lrNc9fXkxtdeBsaxAsXV1+zEkO/3tSvx2AWfOEBwIQD2pFk54df2fGW9nrJXI9lLIQ1g==", "dev": true, "license": "MIT", "peerDependencies": { - "@deepseek-ai/cordis": "^4.0.1", - "@deepseek-ai/dsh-invariants": "^0.1.0-rc.6", - "@deepseek-ai/dsh-llm": "^0.1.0-rc.6", - "@deepseek-ai/dsh-scope": "^0.1.0-rc.6", - "@deepseek-ai/dsh-session": "^0.1.0-rc.6", - "@deepseek-ai/dsh-system-prompt": "^0.1.0-rc.6", - "@deepseek-ai/dsh-typert-protocol": "^0.1.0-rc.6" + "@deepseek-ai/cordis": "~4.1.0" + } + }, + "node_modules/@deepseek-ai/dsh-brand": { + "version": "0.2.2-rc.2", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-brand/-/dsh-brand-0.2.2-rc.2.tgz", + "integrity": "sha512-K3hntZPkzBLTjp+2yF3zMRltjropMeRpJGedQGBl1pO1Bm35Uc3auhzV3SPZ1UcoDPdTu0dhK2+TSOVCOTIySg==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "@deepseek-ai/cordis": "~4.1.0" + } + }, + "node_modules/@deepseek-ai/dsh-client-ui-renderer": { + "version": "0.2.2-rc.2", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-client-ui-renderer/-/dsh-client-ui-renderer-0.2.2-rc.2.tgz", + "integrity": "sha512-zHNs2DGq8WYUM9VxzRlmcwe9j8QQbJ9GfavD+l9gUVqdOjikshxn0oaP4UQcC7hOp4PTLC6QYB+YjiilMCQrNg==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "@deepseek-ai/cordis": "~4.1.0" + } + }, + "node_modules/@deepseek-ai/dsh-client-ui-settings": { + "version": "0.2.2-rc.2", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-client-ui-settings/-/dsh-client-ui-settings-0.2.2-rc.2.tgz", + "integrity": "sha512-bOv+zFJYrI4CvcyussujlPClPL4wjP9iejIDe5Jqgk4qLJk9V/QOeCmRR8x1NNHFjUhMFjtHe+CuF3lfcguijA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@deepseek-ai/schemastery": "~3.19.0" + }, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.1.0" + } + }, + "node_modules/@deepseek-ai/dsh-client-ui-slots": { + "version": "0.2.2-rc.2", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-client-ui-slots/-/dsh-client-ui-slots-0.2.2-rc.2.tgz", + "integrity": "sha512-uOiuDbP8p4qmrACNBvvZqB5Dzhuh3ybpaRN3vUi/cMhdO5ibXyR0vBiv+Cu9RzcCHOv0Kn+PQjO7wCW2hKkiqg==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "@deepseek-ai/cordis": "~4.1.0" + } + }, + "node_modules/@deepseek-ai/dsh-config-editor": { + "version": "0.2.2-rc.2", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-config-editor/-/dsh-config-editor-0.2.2-rc.2.tgz", + "integrity": "sha512-Eu9fKMBNHes7gOyFlLk7IZTTYMHlPnuYJeGWcCm+2eWUsJ9EIDz8e/tp+e43RXzHIdrseInLL67b65mjnpxm3w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@deepseek-ai/dsh-atomic-write": "0.2.2-rc.2", + "js-yaml": "^4.3.2", + "yaml": "^2.8.1" + }, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.1.0", + "@deepseek-ai/cordis-plugin-include": "~1.1.0", + "@deepseek-ai/cordis-plugin-loader": "~1.1.0", + "@deepseek-ai/dsh-app-boot": "0.2.2-rc.2", + "@deepseek-ai/dsh-hmr": "0.2.2-rc.2" + }, + "peerDependenciesMeta": { + "@deepseek-ai/dsh-hmr": { + "optional": true + } + } + }, + "node_modules/@deepseek-ai/dsh-deque": { + "version": "0.2.2-rc.2", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-deque/-/dsh-deque-0.2.2-rc.2.tgz", + "integrity": "sha512-rbnifxWJvOZYh/gXJwXbu90zGgPedw2FYJBECEfIP3PMPnOKOraaKw1wtUHNXemCrEYeFwtLe5+neG2HDi7q5w==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "@deepseek-ai/cordis": "~4.1.0" } }, "node_modules/@deepseek-ai/dsh-llm": { - "version": "0.0.1-rc.1", - "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-llm/-/dsh-llm-0.0.1-rc.1.tgz", - "integrity": "sha512-mRJj07IQNfRReGrhpMpL8AONiYKqfwzxvepg/ut9Wkj8oH2BuoftPS4cMnnXFFCUlYql04/sezwDLriYks/bmw==", + "version": "0.2.2-rc.2", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-llm/-/dsh-llm-0.2.2-rc.2.tgz", + "integrity": "sha512-JPUhqQP4Z/XGX0t7fNvzPUoCSzBRar1ZLbpbZ/evCCvoBVFKtONbKLUyIyS2GOw6Z8bnCEbCIs2Da25SZ6aiVQ==", "dev": true, - "license": "BSD-3-Clause", + "license": "MIT", "dependencies": { - "@deepseek-ai/schemastery": "^3.18.1-rc.1" + "@deepseek-ai/dsh-brand": "0.2.2-rc.2", + "@deepseek-ai/dsh-timeout": "0.2.2-rc.2", + "@deepseek-ai/dsh-typert-protocol": "0.2.2-rc.2", + "@deepseek-ai/dsh-util-crypto": "0.2.2-rc.2", + "@deepseek-ai/dsh-util-values": "0.2.2-rc.2", + "@deepseek-ai/schemastery": "~3.19.0", + "zod": "4.6.6" }, "peerDependencies": { - "@deepseek-ai/cordis": "^4.0.1-rc.1", - "@deepseek-ai/dsh-attachment": "^0.0.1-rc.1", - "@deepseek-ai/dsh-brand": "^0.0.1-rc.1", - "@deepseek-ai/dsh-invariants": "^0.0.1-rc.1", - "@deepseek-ai/dsh-timeout": "^0.0.1-rc.1" + "@deepseek-ai/cordis": "~4.1.0", + "@deepseek-ai/dsh-error": "0.2.2-rc.2" + } + }, + "node_modules/@deepseek-ai/dsh-session": { + "version": "0.2.2-rc.2", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-session/-/dsh-session-0.2.2-rc.2.tgz", + "integrity": "sha512-OiVq3aZWfGjV3/YxebTKo3WozOUz9aGSG/IZnN0medfciAhprh5VkZTCWvwxQCFCN1I9b38Y5RZbwqcCX+m7Eg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@deepseek-ai/dsh-brand": "0.2.2-rc.2", + "@deepseek-ai/dsh-llm": "0.2.2-rc.2", + "@deepseek-ai/dsh-util-values": "0.2.2-rc.2" + }, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.1.0", + "@deepseek-ai/dsh-scope": "0.2.2-rc.2" + } + }, + "node_modules/@deepseek-ai/dsh-settings": { + "version": "0.2.2-rc.2", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-settings/-/dsh-settings-0.2.2-rc.2.tgz", + "integrity": "sha512-jB+26gcmm6iJoyYg06YmilwL/1lD+8KipR5IYOIJci+NG9pgpt34T5U41JkmNEbbTSzcZVDT+RxT76fjP+HQ2w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@deepseek-ai/cordis-plugin-loader": "~1.1.0", + "@deepseek-ai/cosmokit": "~1.9.0", + "@deepseek-ai/dsh-config-editor": "0.2.2-rc.2", + "@deepseek-ai/dsh-util-values": "0.2.2-rc.2", + "yaml": "^2.8.1" + }, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.1.0", + "@deepseek-ai/dsh-brand": "0.2.2-rc.2", + "@deepseek-ai/dsh-session": "0.2.2-rc.2", + "@deepseek-ai/schemastery": "~3.19.0" + } + }, + "node_modules/@deepseek-ai/dsh-timeout": { + "version": "0.2.2-rc.2", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-timeout/-/dsh-timeout-0.2.2-rc.2.tgz", + "integrity": "sha512-GU366m+4SJjX1xWL3+gJ7gVPoQwonV3YMfNR19DmKjF55vaqGRD7rpkt/9Q7oklbJn8VFNajd9NfzA0WPjm/5g==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "@deepseek-ai/cordis": "~4.1.0" + } + }, + "node_modules/@deepseek-ai/dsh-typert-protocol": { + "version": "0.2.2-rc.2", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-typert-protocol/-/dsh-typert-protocol-0.2.2-rc.2.tgz", + "integrity": "sha512-yluiJ1nIkZ4oAtEnknHCIi75mlT2/0Ov8+JGXYM7K9Bu2BoazR6Twv6HALh5yCMLEig9TW+NnUfzPRTUfm9tKw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@deepseek-ai/dsh-brand": "0.2.2-rc.2", + "zod": "4.6.6" + }, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.1.0" + } + }, + "node_modules/@deepseek-ai/dsh-util-crypto": { + "version": "0.2.2-rc.2", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-util-crypto/-/dsh-util-crypto-0.2.2-rc.2.tgz", + "integrity": "sha512-nmPF4brPb7Qgl5h5mG4JWeTqtXbvk4pCS5dVOyCQ5mDm7e0OcEYTUWlCb8C90CNxnqwGM1bEWe3sZZObA+FM4w==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "@deepseek-ai/cordis": "~4.1.0" + } + }, + "node_modules/@deepseek-ai/dsh-util-values": { + "version": "0.2.2-rc.2", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-util-values/-/dsh-util-values-0.2.2-rc.2.tgz", + "integrity": "sha512-a3sZ9xyE9CMReeNJ0jkaSy/h2C8Hqw1ktOIPaP5A8Z1liaWf66Uoy/1IXuweUSHksUN+1bQnRfn5TZQV4SyU1A==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "@deepseek-ai/cordis": "~4.1.0" } }, "node_modules/@deepseek-ai/schemastery": { @@ -104,6 +338,448 @@ "@standard-schema/spec": "^1.1.0" } }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.2.tgz", + "integrity": "sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.2.tgz", + "integrity": "sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.2.tgz", + "integrity": "sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.2.tgz", + "integrity": "sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.2.tgz", + "integrity": "sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.2.tgz", + "integrity": "sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.2.tgz", + "integrity": "sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.2.tgz", + "integrity": "sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.2.tgz", + "integrity": "sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.2.tgz", + "integrity": "sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.2.tgz", + "integrity": "sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.2.tgz", + "integrity": "sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.2.tgz", + "integrity": "sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.2.tgz", + "integrity": "sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.2.tgz", + "integrity": "sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.2.tgz", + "integrity": "sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.2.tgz", + "integrity": "sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.2.tgz", + "integrity": "sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.2.tgz", + "integrity": "sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.2.tgz", + "integrity": "sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.2.tgz", + "integrity": "sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.2.tgz", + "integrity": "sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.2.tgz", + "integrity": "sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.2.tgz", + "integrity": "sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.2.tgz", + "integrity": "sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.2.tgz", + "integrity": "sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, "node_modules/@pinojs/redact": { "version": "0.4.0", "resolved": "https://registry.npmjs.org/@pinojs/redact/-/redact-0.4.0.tgz", @@ -134,13 +810,13 @@ "license": "MIT" }, "node_modules/@types/node": { - "version": "26.6.6", - "resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.6.tgz", - "integrity": "sha512-MzQj+8Kx3XI40OmUAE6Qoh58ZMNstNNMwn2nfd3qWsfe7nDNSqJNzes4njhz6AHwrSHOffSLwXU6yb474Q4aog==", + "version": "22.20.5", + "resolved": "https://registry.npmjs.org/@types/node/-/node-22.20.5.tgz", + "integrity": "sha512-U2+DNr+wSjpsTS/wZGYHq7GcwfuSmKiKvoPvK22zwTlRhU91yOniN4qRR5KhIjvif7ysw/dz/hKmfDH0Ris4aA==", "dev": true, "license": "MIT", "dependencies": { - "undici-types": "~8.9.0" + "undici-types": "~6.21.0" } }, "node_modules/@types/nodemailer": { @@ -153,6 +829,24 @@ "@types/node": "*" } }, + "node_modules/@types/prop-types": { + "version": "15.7.15", + "resolved": "https://registry.npmjs.org/@types/prop-types/-/prop-types-15.7.15.tgz", + "integrity": "sha512-F6bEyamV9jKGAFBEmlQnesRPGOQqS2+Uwi0Em15xenOxHaf2hv6L8YCVn3rPdPJOiJfPiCnLIRyvwVaqMY3MIw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/react": { + "version": "18.3.31", + "resolved": "https://registry.npmjs.org/@types/react/-/react-18.3.31.tgz", + "integrity": "sha512-vfEqpXTvwT91yhmwdfouStN2hSKwTvyRs8qpLfADyrq/kxDw0hZM7Wk9Ug1FELj8hIby+S/+kQCSRFF32nv2Qw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/prop-types": "*", + "csstype": "^3.2.2" + } + }, "node_modules/@zone-eu/mailsplit": { "version": "5.4.16", "resolved": "https://registry.npmjs.org/@zone-eu/mailsplit/-/mailsplit-5.4.16.tgz", @@ -164,6 +858,13 @@ "libqp": "2.1.1" } }, + "node_modules/argparse": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", + "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", + "dev": true, + "license": "Python-2.0" + }, "node_modules/atomic-sleep": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/atomic-sleep/-/atomic-sleep-1.0.0.tgz", @@ -173,6 +874,13 @@ "node": ">=8.0.0" } }, + "node_modules/csstype": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz", + "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==", + "dev": true, + "license": "MIT" + }, "node_modules/deepmerge-ts": { "version": "8.0.2", "resolved": "https://registry.npmjs.org/deepmerge-ts/-/deepmerge-ts-8.0.2.tgz", @@ -268,6 +976,48 @@ "url": "https://github.com/fb55/entities?sponsor=1" } }, + "node_modules/esbuild": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.2.tgz", + "integrity": "sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.28.2", + "@esbuild/android-arm": "0.28.2", + "@esbuild/android-arm64": "0.28.2", + "@esbuild/android-x64": "0.28.2", + "@esbuild/darwin-arm64": "0.28.2", + "@esbuild/darwin-x64": "0.28.2", + "@esbuild/freebsd-arm64": "0.28.2", + "@esbuild/freebsd-x64": "0.28.2", + "@esbuild/linux-arm": "0.28.2", + "@esbuild/linux-arm64": "0.28.2", + "@esbuild/linux-ia32": "0.28.2", + "@esbuild/linux-loong64": "0.28.2", + "@esbuild/linux-mips64el": "0.28.2", + "@esbuild/linux-ppc64": "0.28.2", + "@esbuild/linux-riscv64": "0.28.2", + "@esbuild/linux-s390x": "0.28.2", + "@esbuild/linux-x64": "0.28.2", + "@esbuild/netbsd-arm64": "0.28.2", + "@esbuild/netbsd-x64": "0.28.2", + "@esbuild/openbsd-arm64": "0.28.2", + "@esbuild/openbsd-x64": "0.28.2", + "@esbuild/openharmony-arm64": "0.28.2", + "@esbuild/sunos-x64": "0.28.2", + "@esbuild/win32-arm64": "0.28.2", + "@esbuild/win32-ia32": "0.28.2", + "@esbuild/win32-x64": "0.28.2" + } + }, "node_modules/he": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/he/-/he-1.2.0.tgz", @@ -368,6 +1118,36 @@ "node": ">= 12" } }, + "node_modules/js-tokens": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/js-yaml": { + "version": "4.3.2", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.2.tgz", + "integrity": "sha512-SFNOvSJ+Dgf/9An904Yx+CgSlIPCkIpao4qo51lpee25TIRejdH3rhR4EZMGoNx3/TP3O+wzWuiTFl4sqbltzA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/puzrin" + }, + { + "type": "github", + "url": "https://github.com/sponsors/nodeca" + } + ], + "license": "MIT", + "dependencies": { + "argparse": "^2.0.1" + }, + "bin": { + "js-yaml": "bin/js-yaml.js" + } + }, "node_modules/leac": { "version": "0.7.0", "resolved": "https://registry.npmjs.org/leac/-/leac-0.7.0.tgz", @@ -420,6 +1200,19 @@ "uc.micro": "^2.0.0" } }, + "node_modules/loose-envify": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz", + "integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "js-tokens": "^3.0.0 || ^4.0.0" + }, + "bin": { + "loose-envify": "cli.js" + } + }, "node_modules/mailparser": { "version": "3.14.2", "resolved": "https://registry.npmjs.org/mailparser/-/mailparser-3.14.2.tgz", @@ -612,6 +1405,19 @@ "integrity": "sha512-tYC1Q1hgyRuHgloV/YXs2w15unPVh8qfu/qCTfhTYamaw7fyhumKa2yGpdSo87vY32rIclj+4fWYQXUMs9EHvg==", "license": "MIT" }, + "node_modules/react": { + "version": "18.3.1", + "resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz", + "integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "loose-envify": "^1.1.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/real-require": { "version": "0.2.0", "resolved": "https://registry.npmjs.org/real-require/-/real-require-0.2.0.tgz", @@ -738,11 +1544,36 @@ "license": "MIT" }, "node_modules/undici-types": { - "version": "8.9.0", - "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.9.0.tgz", - "integrity": "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==", + "version": "6.21.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", + "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", "dev": true, "license": "MIT" + }, + "node_modules/yaml": { + "version": "2.9.1", + "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.9.1.tgz", + "integrity": "sha512-3NxN8+78OdzbT7C/WjGsyfPAtJaN3FNDsWxv7Y7mcDsT/oOmgW8BpyQQFFBnvZE3j9Y2Sdz1ULFLezL7Eb2yFw==", + "dev": true, + "license": "ISC", + "bin": { + "yaml": "bin.mjs" + }, + "engines": { + "node": ">= 14.6" + }, + "funding": { + "url": "https://github.com/sponsors/eemeli" + } + }, + "node_modules/zod": { + "version": "4.6.6", + "resolved": "https://registry.npmjs.org/zod/-/zod-4.6.6.tgz", + "integrity": "sha512-4UmzQUF5fxvfcYHlbjBmejU+w+hbDnWFx4aS8kBx7nPBHcO2SqPbpAG8snbdg+Xse4pRefR98hgjFgIMCI/UhA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } } } } diff --git a/package.json b/package.json index 972e95f..b9321b6 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "dsh-mail-sender", - "version": "0.1.4", + "version": "0.2.0", "description": "inbound IMAP mail is delivered to an agent, whose reply is sent back over SMTP.", "type": "module", "main": "lib/index.js", @@ -10,36 +10,70 @@ "types": "./lib/index.d.ts", "default": "./lib/index.js" }, + "./client": { + "types": "./lib/client/index.d.ts", + "default": "./lib/client/index.js" + }, + "./remote": { + "types": "./lib/remote.d.ts", + "default": "./lib/remote.js" + }, + "./typert": { + "types": "./lib/typert.d.ts", + "default": "./lib/typert.js" + }, "./package.json": "./package.json" }, "files": ["lib", "cordis.patch.yml"], "keywords": ["dsh-plugin", "deepseek-harness", "mail", "imap", "smtp"], "dsh": { - "bundle": { "patch": "./cordis.patch.yml" } + "bundle": { "patch": "./cordis.patch.yml" }, + "client": { + "inject": [ + "@deepseek-ai/dsh-api-remotes", + "@deepseek-ai/dsh-client-ui-settings" + ], + "platform": "web" + } }, "engines": { - "dsh": ">=0.2.1-rc.2 <0.3.0-0" + "dsh": ">=0.2.2-rc.2" }, "scripts": { - "build": "tsc" + "build": "tsc && esbuild src/client/index.ts --bundle --format=esm --platform=browser --jsx=automatic --external:react --external:react/jsx-runtime --external:react-dom --external:@deepseek-ai/cordis --outfile=lib/client/index.js" }, "dependencies": { "imapflow": "^1.0.171", "mailparser": "^3.7.1", - "nodemailer": "^6.9.16" + "nodemailer": "^6.9.16", + "zod": "4.6.6" }, "peerDependencies": { "@deepseek-ai/cordis": "^4.1.0", - "@deepseek-ai/dsh-agent": ">=0.2.1-rc.2 <0.3.0-0", - "@deepseek-ai/dsh-llm": ">=0.2.1-rc.2 <0.3.0-0", + "@deepseek-ai/dsh-agent": ">=0.2.2-rc.2", + "@deepseek-ai/dsh-llm": ">=0.2.2-rc.2", + "@deepseek-ai/dsh-settings": ">=0.2.2-rc.2", + "@deepseek-ai/dsh-typert-protocol": ">=0.2.2-rc.2", "@deepseek-ai/schemastery": "^3.19.0" }, "devDependencies": { "@deepseek-ai/cordis": "4.1.0", - "@deepseek-ai/dsh-agent": "0.2.2-rc.1", - "@deepseek-ai/dsh-llm": "0.2.2-rc.1", + "@deepseek-ai/cordis-plugin-loader": "~1.1.0", + "@deepseek-ai/dsh-agent": "0.2.2-rc.2", + "@deepseek-ai/dsh-api-remotes": "0.2.2-rc.2", + "@deepseek-ai/dsh-client-ui-renderer": "0.2.2-rc.2", + "@deepseek-ai/dsh-client-ui-settings": "0.2.2-rc.2", + "@deepseek-ai/dsh-client-ui-slots": "0.2.2-rc.2", + "@deepseek-ai/dsh-llm": "0.2.2-rc.2", + "@deepseek-ai/dsh-session": "0.2.2-rc.2", + "@deepseek-ai/dsh-settings": "0.2.2-rc.2", + "@deepseek-ai/dsh-typert-protocol": "0.2.2-rc.2", "@deepseek-ai/schemastery": "3.19.0", + "@types/node": "^22.10.0", "@types/nodemailer": "^6.4.17", + "@types/react": "^18.3.12", + "esbuild": "^0.28.2", + "react": "^18.3.1", "typescript": "^5.6.0" }, "pnpm": { diff --git a/readme.md b/readme.md index 5c8a21b..d298204 100644 --- a/readme.md +++ b/readme.md @@ -1,30 +1,30 @@ # dsh-mail-sender -DeepSeek Harness (DSH) 邮件通道插件:用户发邮件 → DSH 接收并交给 agent → agent 的回复自动用邮件发回去。 +DeepSeek Harness (DSH) 邮件通道插件:用户发邮件 → DSH 交给 agent → 回复自动用邮件发回。 -- **入站**:IMAP IDLE 实时监听收件箱 -- **会话**:同一发件人 → 同一个 agent 会话(`sessionId = mail-<地址>`) -- **出站**:订阅 `session/event`,一轮 turn 正常结束后自动 SMTP 回信(`Re:` 主题 + `In-Reply-To`) -- **白名单**:`allowedAddresses` 同时控制入站与出站 -- **配置界面**:Host 从导出的 `Config` schema 自动渲染,无需自写前端 +- **常驻入口**:被动接收邮件驱动会话,不是等待模型调用的 Tool +- **标准协议**:IMAP IDLE 收信 / SMTP 回信,不绑定托管邮件服务 +- **双向白名单**:同一份精确地址列表同时校验入站发件人与出站回复对象 +- **每地址一个会话**:`sessionId = mail:<规范化地址>`,上下文连续 +- **设置页 UI**:邮箱绑定表格、可增删白名单、IDLE 状态卡与测试连接 ## 工作原理 ``` -来信 (IMAP) - │ mailparser 解析 from / subject / body / messageId +来信 (IMAP IDLE / 60s 轮询) + │ 认证后探测 capability,决定 IDLE 或轮询 ▼ -白名单过滤 ── 不在 allowedAddresses → 丢弃 - │ +AccessPolicy(纯函数)── 自动流量 / 非白名单 → 静默丢弃 + │ toJob 一次解析发件地址并生成 MailJob ▼ -ctx.agents.create / resume (sessionId = `mail-${from}`) - │ agent.followup(createUserMessage(...)) +串行消费队列 → ctx.agents.get / resume / create + │ agent.followup(正文) ▼ -订阅 session/event - │ assistant/message → 累积 text 块 - │ turn/end (reason.kind === 'completed') → 取出本轮文本 +session/event(durable) + │ assistant/message → 累积本轮 text + │ turn/end completed → 取出回复 ▼ -SMTP 回复 (Re: 原主题, In-Reply-To: 原 Message-ID) +SMTP 连接池回信(Re: + In-Reply-To + References) ``` ## 安装 @@ -33,46 +33,47 @@ SMTP 回复 (Re: 原主题, In-Reply-To: 原 Message-ID) dsh plugin --profile web add dsh-mail-sender ``` -安装后重启 `dsh web`,用 `dsh --profile web --dump-config` 确认插件行已进入配置树。 +安装后重启 `dsh web`。 -## 在设置页填写配置 +## 设置页 -打开 **Settings(设置)→ Plugins(插件)→ dsh-mail-sender**,表单由 Host 根据插件导出的 `Config` schema 自动生成。 +打开 **Settings(设置)→ 邮件网关**: -> 该表单依赖两点,本插件已满足: -> 1. patch 行 `id` 与包名一致(`dsh-mail-sender`),设置表单按行 id 定位; -> 2. 每个可编辑字段声明为 `.volatile()`,DSH 才会把它投影成可编辑项并把改动写回 profile 的 `cordis.patch.yml`。 - -| 字段 | 说明 | +| 区域 | 行为 | |---|---| -| `email` | 机器人邮箱,如 `agent@qq.com`(同时用于 IMAP/SMTP 登录与回信 From) | -| `password` | 邮箱密码或授权码 | -| `imapHost` | IMAP 服务器,如 `imap.qq.com`(固定 993 + SSL) | -| `smtpHost` | SMTP 服务器,如 `smtp.qq.com` | -| `smtpPort` | 默认 `465`(SSL);填 `587` 时自动走 STARTTLS | -| `allowedAddresses` | 允许与 agent 通信的邮箱地址列表 | +| 邮箱绑定 | IMAP / SMTP 主机、端口、TLS、用户名、显示名;密码保存后只显示“已设置”,留空表示不修改 | +| 测试连接 | 用当前表单值临时建连并探测 IDLE,结果直接写入状态卡 | +| 白名单 | 输入回车添加、行尾删除、独立保存;保存只更新内存策略,不断开 IMAP | +| 状态卡 | 正在连接 / 支持 IDLE / 不支持 IDLE(轮询 60s,延迟最长约 1 分钟)/ 连接失败原因 | -服务器地址按你的邮箱服务商填写,插件不做猜测。 +密码字段声明为 `role('secret')`,由 credential provider 保存,不落 `settings` 明文。 -白名单同时控制两个方向:非名单内发件人的来信直接丢弃;agent 的回复目标就是来信人,因此也天然限定在名单内。 +## 关键约束 -所有字段都是 `.volatile()`:保存后即时生效,IMAP 会按新配置自动重连,无需重启 host。 +- 不处理附件,只取 `text/plain`(缺失时用 HTML 降级) +- 不设发送频率或发送量限制 +- 拦截 `Auto-Submitted`(非 `no`)与 `Precedence: bulk/junk/list`,防邮件环 +- UID 游标持久化;首次配置建立基线,不回放历史邮件 +- 断线重连退避:5s → 10s → 30s → 1min → 5min +- SMTP 单例连接池(`pool: true`,`maxConnections: 3`) ## 包结构 ``` -. -├── package.json # dsh.bundle 声明(无 dsh.client,纯 Host 插件) -├── cordis.patch.yml # 顶层 YAML 数组:插入插件行 -├── src/index.ts -├── tsconfig.json -└── .npmrc # legacy-peer-deps=true(本地开发) +src/ +├── index.ts # name / inject / Config / apply +├── config.ts # schemastery(volatile + secret 密码) +├── policy.ts # AccessPolicy 纯函数、toJob 一次解析 +├── mailbox.ts # 绑定信息规范化与连接键 +├── cursor.ts # UID 游标持久化 +├── receiver.ts # ImapReceiver:IDLE/轮询、能力探测、退避 +├── sender.ts # SmtpSender:连接池回信 +├── deliver.ts # ctx.agents 与 session/event 的唯一适配点 +├── gateway.ts # 编排、串行队列、reload +├── service.ts # Typert Remote(get/save/test/status) +├── remote.ts # Remote 契约与类型声明 +├── typert.ts # source-mode 发现占位 +└── client/ # settings.section UI ``` -`cordis.patch.yml` 必须是**顶层数组**的 loader patch 条目: - -```yaml -- insert: - - id: dsh-mail-sender - name: dsh-mail-sender -``` \ No newline at end of file +客户端入口为 `./client`,由 esbuild 打包为单文件;宿主入口为 `./index.js`。 diff --git a/spec.md b/spec.md new file mode 100644 index 0000000..6881de5 --- /dev/null +++ b/spec.md @@ -0,0 +1,72 @@ +# dsh-mail-sender 收尾规格 + +## 1. 目标 + +在 `f:\git\dsh-mail-sender` 交付 DSH 邮件通道插件:标准 IMAP/SMTP 常驻入口,邮件驱动 agent 会话,回复自动回信。实现范围以 [guide.md](file:///f:/git/dsh-mail-sender/guide.md) 的 F1–F9、U1–U7、T1–T20 与“边界与不做的事”为准。 + +## 2. 当前状态 + +插件代码已完整实现,文件与职责: + +| 文件 | 职责 | +|---|---| +| `src/index.ts` | `name / inject / Config / apply`,无 default export;资源收进 `ctx.effect` | +| `src/config.ts` | schemastery 配置,`mailbox` / `allowedAddresses` 为 volatile,密码 `role('secret')` | +| `src/policy.ts` | `AccessPolicy` 纯函数、`toJob` 一次解析、防环、正文提取 | +| `src/mailbox.ts` | 绑定规范化、`mailboxKey`、`publicMailbox`、发件人头 | +| `src/cursor.ts` | UID 游标持久化(`~/.dsh/mail-gateway/.json`) | +| `src/receiver.ts` | `ImapReceiver`、`probeIdle`、IDLE/60s 轮询、指数退避 | +| `src/sender.ts` | `SmtpSender` 单例连接池,`In-Reply-To` / `References` | +| `src/deliver.ts` | `ctx.agents` 与 `session/event` 唯一适配点 | +| `src/gateway.ts` | 编排、串行 `drain`、`reload`、`updatePolicy` | +| `src/service.ts` | Typert Remote:`get / status / saveMailbox / saveWhitelist / testConnection` | +| `src/remote.ts` | 手写 Remote 契约与 `TypertRemote*` 模块增强 | +| `src/client/` | `settings.section` UI:状态卡、三列表单、白名单表格 | + +## 3. 已静态确认的契约(未运行任何命令) + +- `RemoteError` 支持 `gateway/bad-request`、`gateway/internal`,构造签名 `(code, message, details)`。 +- `TypertRemoteService(ctx, serviceKey, { namespace })`、`@Remote(name)`、`createTypertRemoteInfo(spec, zod)` 与 `src/remote.ts` 的 spec 形状一致。 +- `assistant/message.data` 含 `turn` / `message`;`turn/end.data` 含 `turn` / `reason`,`reason.kind` 含 `completed`。 +- `ctx.agents.get(id)`、`create({ sessionId })`、`resume({ resumeSessionId })`、`AgentHandle{agent,dispose}`、`followup(UserMessage)` 与调用一致。 +- 源码不存在已移除依赖(`react-dom`、`@deepseek-ai/dsh-api-remote-access`)的引用。 + +## 4. 待修复缺陷(唯一代码改动) + +**文件**:`src/deliver.ts` + +**问题**:`jobs: Map` 每个会话只保留最新一封;`pending: Set` 无法表达“一封信对应一轮”。同一发件人连发两封且第一轮未结束时: + +1. 第一轮 `turn/end` 用第二封的 `messageId` / 主题回信,线程归并错乱; +2. `pending` 被删除,第二轮结束时不再回信,第二封永久丢失回复。 + +**改法(决策已定)**: + +- 将 `pending: Set` + `jobs: Map` 合并为 `pending: Map`。 +- `deliver(job)`:`ensure()` 后把 job 推入该会话队列,再 `followup`。 +- `handleEvent` 的 `turn/end` 分支: + - 始终取出该会话队列头部一封(`shift`),队列空则删除键; + - 仅当 `reason.kind === 'completed'` 且本轮累积文本非空时才 `onReply(job, text)`; + - 非 completed 也出队,避免失败轮次与后续邮件错位。 +- `assistant/message` 累积逻辑与 `turnBuffers` 保持不变。 +- `dispose()` 对 Map 执行 `clear()`。 + +**验收**:连发两封邮件时,两轮各回一封信,主题与 `In-Reply-To` 分别对应各自来信;失败轮次不产生回复且不吞掉下一封。 + +## 5. 明确不做 + +- 不执行 `npm install`、`npm run build`、任何 dsh 相关命令(本机无 dsh,用户明确要求)。 +- 不修改 `guide.md`、`package.json` 依赖集合、`cordis.patch.yml`。 +- 不发送频率限制、不处理附件、不做白名单正则校验、不自定义图标、UI 不重复轮询。 + +## 6. 验证方式 + +仅静态验证: + +1. 逐行复核 `src/deliver.ts` 修改后的类型与控制流(`Map`、`shift()` 后空队列删除、`completed` 判定)。 +2. 全仓检索 `pending` / `jobs` 无残留引用。 +3. 核对 `src/types.ts` 的 `MailJob` 与 `MailSnapshot` 未被改动。 + +## 7. 审批 + +确认本规格后按其执行 `tasks.md`;若不同意“失败轮次也出队”或 FIFO 映射方式,请先指出再改。 diff --git a/src/client/MailGatewaySection.tsx b/src/client/MailGatewaySection.tsx new file mode 100644 index 0000000..0556aeb --- /dev/null +++ b/src/client/MailGatewaySection.tsx @@ -0,0 +1,328 @@ +import { useEffect, useState } from 'react' +import type { ChangeEvent, CSSProperties, KeyboardEvent } from 'react' +import type { MailGatewayApi } from './api.js' +import { StatusCard } from './StatusCard.js' +import type { + ConnectionTestResult, + MailSnapshot, + MailboxPatch, + MailboxSettings, +} from '../types.js' + +export interface MailGatewaySectionProps { + api: MailGatewayApi +} + +type Busy = 'mailbox' | 'whitelist' | 'test' | null + +const table: CSSProperties = { + width: '100%', + borderCollapse: 'collapse', + fontSize: 13, +} + +const cell: CSSProperties = { + borderBottom: '1px solid var(--dsh-border, #e5e7eb)', + padding: '8px 10px', + verticalAlign: 'middle', + textAlign: 'left', +} + +const input: CSSProperties = { + width: '100%', + boxSizing: 'border-box', + padding: '6px 8px', + border: '1px solid var(--dsh-border, #d1d5db)', + borderRadius: 6, + background: 'transparent', + color: 'inherit', + fontSize: 13, +} + +const button: CSSProperties = { + padding: '6px 12px', + border: '1px solid var(--dsh-border, #d1d5db)', + borderRadius: 6, + background: 'transparent', + color: 'inherit', + cursor: 'pointer', + fontSize: 13, +} + +const primary: CSSProperties = { + ...button, + borderColor: '#2563eb', + background: '#2563eb', + color: '#fff', +} + +const muted: CSSProperties = { color: '#6b7280', fontSize: 12 } +const section: CSSProperties = { display: 'grid', gap: 16, maxWidth: 760 } +const row: CSSProperties = { display: 'flex', gap: 8, alignItems: 'center' } + +export function MailGatewaySection({ api }: MailGatewaySectionProps) { + const [snapshot, setSnapshot] = useState() + const [mailbox, setMailbox] = useState() + const [password, setPassword] = useState('') + const [allowed, setAllowed] = useState([]) + const [entry, setEntry] = useState('') + const [test, setTest] = useState() + const [busy, setBusy] = useState(null) + const [notice, setNotice] = useState<{ kind: 'ok' | 'error'; text: string }>() + + const applySnapshot = (next: MailSnapshot, resetMailbox: boolean) => { + setSnapshot(next) + setAllowed([...next.allowedAddresses]) + if (resetMailbox) { + setMailbox({ ...next.mailbox }) + setPassword('') + } + } + + useEffect(() => { + let alive = true + void api.get().then(result => { + if (!alive) return + if (result.ok) applySnapshot(result.value, true) + else setNotice({ kind: 'error', text: result.error.message }) + }) + return () => { + alive = false + } + }, [api]) + + const setField = (key: K, value: MailboxSettings[K]) => { + setMailbox(current => (current ? { ...current, [key]: value } : current)) + } + + const patch = (source: MailboxSettings): MailboxPatch => ({ + ...source, + password: password ? password : undefined, + }) + + const saveMailbox = async () => { + if (!mailbox) return + setBusy('mailbox') + setNotice(undefined) + const result = await api.saveMailbox(patch(mailbox)) + setBusy(null) + if (result.ok) { + applySnapshot(result.value, true) + setTest(undefined) + setNotice({ kind: 'ok', text: '邮箱绑定已保存,连接已按新配置重建。' }) + } else { + setNotice({ kind: 'error', text: result.error.message }) + } + } + + const testConnection = async () => { + if (!mailbox) return + setBusy('test') + setNotice(undefined) + const result = await api.testConnection(patch(mailbox)) + setBusy(null) + if (result.ok) { + setTest(result.value) + } else { + setNotice({ kind: 'error', text: result.error.message }) + } + } + + const addAddress = () => { + const address = entry.trim().toLowerCase() + if (!address) return + setAllowed(current => (current.includes(address) ? current : [...current, address])) + setEntry('') + } + + const onEntryKey = (event: KeyboardEvent) => { + if (event.key !== 'Enter') return + event.preventDefault() + addAddress() + } + + const removeAddress = (address: string) => { + setAllowed(current => current.filter(item => item !== address)) + } + + const saveWhitelist = async () => { + setBusy('whitelist') + setNotice(undefined) + const result = await api.saveWhitelist(allowed) + setBusy(null) + if (result.ok) { + applySnapshot(result.value, false) + setNotice({ kind: 'ok', text: '白名单已保存,收信策略立即生效,连接保持不变。' }) + } else { + setNotice({ kind: 'error', text: result.error.message }) + } + } + + const numberField = (key: 'imapPort' | 'smtpPort') => (event: ChangeEvent) => { + setField(key, Number(event.target.value) || 0) + } + + const textField = ( + key: 'email' | 'displayName' | 'imapHost' | 'smtpHost' | 'username', + ) => (event: ChangeEvent) => { + setField(key, event.target.value) + } + + const boolField = (key: 'imapSecure' | 'smtpSecure') => (event: ChangeEvent) => { + setField(key, event.target.checked) + } + + return ( +
+ + +
+

邮箱绑定

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
字段值说明
邮箱地址 + + 接收邮件与回信使用的地址。
显示名 + + 回信时的发件人名称,可留空。
IMAP 主机 + + 标准 IMAP 服务器地址。
IMAP 端口 + + SSL 一般为 993。
IMAP TLS + + 勾选表示使用 SSL/TLS。
SMTP 主机 + + 标准 SMTP 服务器地址。
SMTP 端口 + + SSL 一般为 465。
SMTP TLS + + 勾选表示使用 SSL/TLS。
登录用户名 + + 留空时使用邮箱地址。
密码 + setPassword(event.target.value)} + /> + 保存后只显示“已设置”,不会回显明文。
+
+ + + 保存邮箱绑定时会按新配置重建连接。 +
+ + +
+

白名单

+
+ setEntry(event.target.value)} + onKeyDown={onEntryKey} + /> + +
+ + + {allowed.length === 0 ? ( + + + + ) : ( + allowed.map(address => ( + + + + + )) + )} + +
暂无地址,白名单为空时不会接收任何邮件。
{address} + +
+
+ + 同一份白名单同时校验入站发件地址与出站回复地址。 +
+
+ + {notice ? ( +
+ {notice.text} +
+ ) : null} + + ) +} diff --git a/src/client/StatusCard.tsx b/src/client/StatusCard.tsx new file mode 100644 index 0000000..6828ec0 --- /dev/null +++ b/src/client/StatusCard.tsx @@ -0,0 +1,64 @@ +import type { CSSProperties } from 'react' +import type { ConnectionTestResult, MailStatus } from '../types.js' + +export interface StatusCardProps { + status?: MailStatus + allowedCount: number + test?: ConnectionTestResult +} + +const card: CSSProperties = { + border: '1px solid var(--dsh-border, #e5e7eb)', + borderRadius: 8, + padding: '12px 14px', + display: 'grid', + gap: 6, + fontSize: 13, + lineHeight: 1.6, +} + +function summary(status?: MailStatus): { text: string; color: string } { + switch (status?.phase) { + case 'connecting': + return { text: '正在连接…', color: '#6b7280' } + case 'idle': + return { text: '已连接,服务器支持 IDLE,新邮件会即时唤醒。', color: '#047857' } + case 'polling': + return { + text: '已连接,服务器不支持 IDLE,自动改为轮询 60s,延迟最长约 1 分钟。', + color: '#b45309', + } + case 'error': + return { text: `连接失败:${status.lastError ?? '未知原因'}`, color: '#b91c1c' } + default: + return { text: '未启用:请先填写完整的邮箱绑定信息。', color: '#6b7280' } + } +} + +/** 纯展示:状态由 MailGatewaySection 统一拉取,这里不发起任何请求。 */ +export function StatusCard({ status, allowedCount, test }: StatusCardProps) { + const state = summary(status) + return ( +
+
{state.text}
+ {status?.phase === 'idle' || status?.phase === 'polling' ? ( +
+ 收信策略:{allowedCount > 0 ? `仅接收白名单内 ${allowedCount} 个地址的邮件。` : '白名单为空,不会接收任何邮件。'} + {status.since ? ` 连接建立于 ${new Date(status.since).toLocaleString()}。` : ''} +
+ ) : null} + {allowedCount === 0 && status?.phase !== 'idle' && status?.phase !== 'polling' ? ( +
白名单为空:不会接收任何邮件。
+ ) : null} + {test ? ( +
+ {test.ok + ? test.supportsIdle + ? '测试连接成功:服务器支持 IDLE。' + : '测试连接成功:服务器不支持 IDLE,将使用轮询。' + : `测试连接失败:${test.error ?? '未知原因'}`} +
+ ) : null} +
+ ) +} diff --git a/src/client/api.ts b/src/client/api.ts new file mode 100644 index 0000000..94c8787 --- /dev/null +++ b/src/client/api.ts @@ -0,0 +1,30 @@ +import type { Context } from '@deepseek-ai/cordis' +import type {} from '@deepseek-ai/dsh-api-remotes/client' +import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol' +import type {} from '../remote.js' +import type { + ConnectionTestResult, + MailSnapshot, + MailStatus, + MailboxPatch, +} from '../types.js' + +/** 设置页使用的全部宿主能力;组件只依赖这个接口。 */ +export interface MailGatewayApi { + get(): Promise> + saveMailbox(patch: MailboxPatch): Promise> + saveWhitelist(addresses: string[]): Promise> + testConnection(patch: MailboxPatch): Promise> + status(): Promise> +} + +export function createApi(ctx: Context): MailGatewayApi { + const remote = ctx.remote['mail-gateway'] + return { + get: () => remote.get(), + saveMailbox: patch => remote.saveMailbox(patch), + saveWhitelist: addresses => remote.saveWhitelist(addresses), + testConnection: patch => remote.testConnection(patch), + status: () => remote.status(), + } +} diff --git a/src/client/index.ts b/src/client/index.ts new file mode 100644 index 0000000..9d76b9a --- /dev/null +++ b/src/client/index.ts @@ -0,0 +1,32 @@ +import type { Context } from '@deepseek-ai/cordis' +import type {} from '@deepseek-ai/dsh-api-remotes/client' +import type {} from '@deepseek-ai/dsh-client-ui-renderer/client' +import type {} from '@deepseek-ai/dsh-client-ui-settings/client' +import type {} from '../remote.js' +import TYPERT_REMOTE from '../remote.js' +import { createApi } from './api.js' +import { MailGatewaySection } from './MailGatewaySection.js' + +export const name = 'dsh-mail-sender' +export const inject = ['slots', 'remote'] + +/** 挂载本插件的 Remote 命名空间,并在设置页注册“邮件网关”分区。 */ +export async function apply(ctx: Context): Promise<() => Promise> { + const disposeRemote = await ctx.remote.$mount(TYPERT_REMOTE) + + const api = createApi(ctx) + ctx.slots.inject('settings.section', () => + ctx.slots.register( + { + name: 'settings.section', + id: 'mail-gateway', + order: 120, + label: () => '邮件网关', + inject: () => ({ api }), + }, + MailGatewaySection, + ), + ) + + return disposeRemote +} diff --git a/src/config.ts b/src/config.ts new file mode 100644 index 0000000..4f2d895 --- /dev/null +++ b/src/config.ts @@ -0,0 +1,56 @@ +import Schema from '@deepseek-ai/schemastery' +import { createMailbox } from './mailbox.js' +import type { MailboxSettings } from './types.js' + +/** schemastery `.volatile()` 字段解析后的稳定引用。 */ +interface Ref { + get(): T +} + +export interface Config { + mailbox: Ref + allowedAddresses: Ref +} + +const DEFAULT_MAILBOX: MailboxSettings = { + email: '', + displayName: '', + imapHost: '', + imapPort: 993, + imapSecure: true, + smtpHost: '', + smtpPort: 465, + smtpSecure: true, + username: '', + password: '', +} + +export const Config = Schema.object({ + mailbox: Schema.object({ + email: Schema.string().default('').description('接收邮件与回信使用的地址'), + displayName: Schema.string().default('').description('回信时显示的发件人名称,可留空'), + imapHost: Schema.string().default('').description('IMAP 服务器地址'), + imapPort: Schema.natural().default(993).description('IMAP 端口,SSL 一般为 993'), + imapSecure: Schema.boolean().default(true).description('IMAP 是否使用 TLS'), + smtpHost: Schema.string().default('').description('SMTP 服务器地址'), + smtpPort: Schema.natural().default(465).description('SMTP 端口,SSL 一般为 465'), + smtpSecure: Schema.boolean().default(true).description('SMTP 是否使用 TLS'), + username: Schema.string().default('').description('登录用户名,留空时使用邮箱地址'), + password: Schema.string().role('secret').default('').description('邮箱密码或应用专用密码'), + }) + .default(DEFAULT_MAILBOX) + .volatile() + .description('dsh-mail-sender 邮箱绑定'), + allowedAddresses: Schema.array(Schema.string()) + .default([]) + .volatile() + .description('双向白名单:同时校验入站发件地址与出站回复地址'), +}) + +export function mailboxOf(config: Config): MailboxSettings { + return createMailbox(config.mailbox.get()) +} + +export function addressesOf(config: Config): string[] { + return [...(config.allowedAddresses.get() ?? [])] +} diff --git a/src/cursor.ts b/src/cursor.ts new file mode 100644 index 0000000..25d05c8 --- /dev/null +++ b/src/cursor.ts @@ -0,0 +1,47 @@ +import { createHash } from 'node:crypto' +import { mkdir, readFile, writeFile } from 'node:fs/promises' +import { homedir } from 'node:os' +import { dirname, join } from 'node:path' + +export interface CursorRecord { + /** IMAP UIDVALIDITY,变化表示邮箱被重建,需要重新建基线。 */ + uidValidity: string + /** 已处理到的最大 UID。 */ + uid: number +} + +function cursorPath(account: string): string { + const digest = createHash('sha1').update(account).digest('hex').slice(0, 16) + return join(homedir(), '.dsh', 'mail-gateway', `${digest}.json`) +} + +/** UID 游标持久化;读写失败时退化为内存游标,不阻塞收信。 */ +export class CursorStore { + private readonly file: string + private cache?: CursorRecord + + constructor(account: string) { + this.file = cursorPath(account) + } + + async read(): Promise { + if (this.cache) return this.cache + try { + const raw = await readFile(this.file, 'utf8') + const parsed = JSON.parse(raw) as Partial + if (typeof parsed.uidValidity === 'string' && typeof parsed.uid === 'number') { + this.cache = { uidValidity: parsed.uidValidity, uid: parsed.uid } + return this.cache + } + } catch {} + return undefined + } + + async write(record: CursorRecord): Promise { + this.cache = record + try { + await mkdir(dirname(this.file), { recursive: true }) + await writeFile(this.file, JSON.stringify(record), 'utf8') + } catch {} + } +} diff --git a/src/deliver.ts b/src/deliver.ts new file mode 100644 index 0000000..f68b346 --- /dev/null +++ b/src/deliver.ts @@ -0,0 +1,124 @@ +import type { Context } from '@deepseek-ai/cordis' +import type { Agent, AgentHandle } from '@deepseek-ai/dsh-agent' +import type { Session, SessionEvent, SessionId } from '@deepseek-ai/dsh-session' +import { createUserMessage } from '@deepseek-ai/dsh-llm' +import type { MailJob } from './types.js' + +interface DrivableAgent extends Agent { + followup(message: unknown): void +} + +interface DriveHandle { + agent: DrivableAgent + owned: boolean + dispose(): Promise +} + +/** + * 邮件会话适配层:ctx.agents / session/event 的全部调用都收在这里, + * Agent API 变化时只需改这一个文件。 + */ +export class MailDeliverer { + private readonly handles = new Map() + private readonly turnBuffers = new Map() + /** 每个会话按投递顺序排队,一轮回复对应队首的一封来信。 */ + private readonly pending = new Map() + private readonly off: () => void + + constructor( + private readonly ctx: Context, + private readonly onReply: (job: MailJob, text: string) => Promise, + private readonly onLog?: (message: string) => void, + ) { + this.off = ctx.on('session/event', (session, event) => { + this.handleEvent(session, event) + }) + } + + async deliver(job: MailJob): Promise { + const handle = await this.ensure(job.sessionId) + const queue = this.pending.get(job.sessionId) ?? [] + queue.push(job) + this.pending.set(job.sessionId, queue) + handle.agent.followup( + createUserMessage({ + content: [{ type: 'text', text: job.text }], + source: { kind: 'user' }, + }), + ) + } + + dispose(): void { + this.off() + for (const handle of this.handles.values()) { + if (handle.owned) void handle.dispose().catch(() => {}) + } + this.handles.clear() + this.turnBuffers.clear() + this.pending.clear() + } + + private async ensure(sessionId: string): Promise { + const cached = this.handles.get(sessionId) + if (cached) return cached + + const id = sessionId as SessionId + const live = this.ctx.agents.get(id) + if (live) { + const borrowed: DriveHandle = { + agent: live as DrivableAgent, + owned: false, + dispose: async () => {}, + } + this.handles.set(sessionId, borrowed) + return borrowed + } + + let handle: AgentHandle + try { + handle = await this.ctx.agents.resume({ resumeSessionId: id }) + } catch { + handle = await this.ctx.agents.create({ sessionId: id }) + } + + const owned: DriveHandle = { + agent: handle.agent as DrivableAgent, + owned: true, + dispose: () => handle.dispose(), + } + this.handles.set(sessionId, owned) + return owned + } + + private handleEvent(session: Session, event: SessionEvent): void { + const sessionId = session.header.id as string + if (!sessionId.startsWith('mail:') || !this.handles.has(sessionId)) return + if (event.type === 'assistant/message') { + const text = event.data.message.content + .filter(block => block.type === 'text') + .map(block => (block.type === 'text' ? block.text : '')) + .join('') + if (!text) return + const key = `${sessionId}:${event.data.turn}` + this.turnBuffers.set(key, [...(this.turnBuffers.get(key) ?? []), text]) + return + } + + if (event.type === 'turn/end') { + const key = `${sessionId}:${event.data.turn}` + const text = (this.turnBuffers.get(key) ?? []).join('\n\n').trim() + this.turnBuffers.delete(key) + + // 无论本轮成败都出队一封,保持“一封信对应一轮”的 FIFO 对齐。 + const queue = this.pending.get(sessionId) + const job = queue?.shift() + if (queue && queue.length === 0) this.pending.delete(sessionId) + if (!job) return + + if (event.data.reason.kind !== 'completed' || !text) return + void this.onReply(job, text).catch(error => { + this.onLog?.(`[mail] 回信失败: ${error instanceof Error ? error.message : String(error)}`) + }) + } + } +} diff --git a/src/gateway.ts b/src/gateway.ts new file mode 100644 index 0000000..7e84a97 --- /dev/null +++ b/src/gateway.ts @@ -0,0 +1,149 @@ +import type { Context } from '@deepseek-ai/cordis' +import { createPolicy } from './policy.js' +import type { AccessPolicy } from './policy.js' +import { ImapReceiver, POLL_INTERVAL_MS } from './receiver.js' +import { CursorStore } from './cursor.js' +import { MailDeliverer } from './deliver.js' +import { SmtpSender } from './sender.js' +import { isMailboxConfigured, mailboxKey, publicMailbox } from './mailbox.js' +import type { MailJob, MailSnapshot, MailStatus, MailboxSettings } from './types.js' + +function errorMessage(error: unknown): string { + return error instanceof Error ? error.message : String(error) +} + +/** + * 常驻邮件的编排层:收信 → 串行队列 → 会话 → 回信。 + * 白名单保存只更新内存策略,邮箱绑定变化才重连。 + */ +export class MailGateway { + private receiver?: ImapReceiver + private sender?: SmtpSender + private readonly deliverer: MailDeliverer + private readonly queue: MailJob[] = [] + private draining = false + private mailbox: MailboxSettings + private policy: AccessPolicy + private allowed: string[] + private accountKey = '' + private generation = 0 + private status: MailStatus = { + phase: 'disabled', + supportsIdle: false, + pollIntervalMs: POLL_INTERVAL_MS, + } + + constructor( + ctx: Context, + mailbox: MailboxSettings, + allowed: readonly string[], + private readonly onLog: (message: string) => void = message => console.warn(message), + ) { + this.mailbox = mailbox + this.allowed = [...allowed] + this.policy = createPolicy(allowed) + this.deliverer = new MailDeliverer( + ctx, + async (job, text) => { + if (!this.sender) throw new Error('SMTP 尚未配置') + await this.sender.send(job, text) + }, + onLog, + ) + } + + start(): () => Promise { + this.restart() + return async () => { + this.deliverer.dispose() + await this.receiver?.stop() + this.receiver = undefined + this.sender?.close() + this.sender = undefined + } + } + + /** 只接受新的绑定与白名单;ctx 不参与重载。 */ + reload(mailbox: MailboxSettings, allowed: readonly string[]): void { + const nextKey = mailboxKey(mailbox) + this.allowed = [...allowed] + this.policy = createPolicy(allowed) + + if (nextKey !== this.accountKey) { + this.mailbox = mailbox + this.restart() + return + } + + this.mailbox = mailbox + this.sender?.update(mailbox) + } + + updatePolicy(allowed: readonly string[]): void { + this.allowed = [...allowed] + this.policy = createPolicy(allowed) + } + + snapshot(): MailSnapshot { + return { + mailbox: publicMailbox(this.mailbox), + passwordSet: Boolean(this.mailbox.password), + allowedAddresses: [...this.allowed], + status: this.status, + } + } + + private restart(): void { + const generation = ++this.generation + void this.receiver?.stop() + this.receiver = undefined + this.sender?.close() + this.sender = undefined + + if (!isMailboxConfigured(this.mailbox)) { + this.accountKey = '' + this.status = { phase: 'disabled', supportsIdle: false, pollIntervalMs: POLL_INTERVAL_MS } + this.onLog('[mail] 未配置完整邮箱,收信入口保持关闭') + return + } + + this.accountKey = mailboxKey(this.mailbox) + this.sender = new SmtpSender(this.mailbox) + this.receiver = new ImapReceiver( + this.mailbox, + () => this.policy, + new CursorStore(`${this.mailbox.email}@${this.mailbox.imapHost}`), + { + onJob: job => this.enqueue(job), + onStatus: status => { + if (generation === this.generation) this.status = status + }, + onLog: this.onLog, + }, + ) + this.receiver.start() + } + + private enqueue(job: MailJob): void { + this.queue.push(job) + void this.drain() + } + + /** 串行消费;单封失败只记录,不拖垮常驻循环。 */ + private async drain(): Promise { + if (this.draining) return + this.draining = true + try { + while (this.queue.length) { + const job = this.queue.shift()! + try { + await this.deliverer.deliver(job) + } catch (error) { + this.onLog(`[mail] 投递 ${job.from} 失败: ${errorMessage(error)}`) + } + } + } finally { + this.draining = false + } + } +} diff --git a/src/index.ts b/src/index.ts index e75aaef..d5c0447 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,248 +1,30 @@ -import { ImapFlow } from 'imapflow' -import nodemailer from 'nodemailer' -import { simpleParser } from 'mailparser' import type { Context } from '@deepseek-ai/cordis' -import { createUserMessage } from '@deepseek-ai/dsh-llm' -import Schema from '@deepseek-ai/schemastery' +import { Config, addressesOf, mailboxOf } from './config.js' +import { MailGateway } from './gateway.js' +import { MailGatewayService } from './service.js' + +export { Config } from './config.js' export const name = 'dsh-mail-sender' -export const inject = ['agents'] - -/** schemastery `.volatile()` 字段解析后的稳定引用 */ -interface Ref { - get(): T -} - -export interface Config { - /** 机器人邮箱,同时用于 IMAP/SMTP 登录与回信 From */ - email: Ref - /** 邮箱密码或授权码 */ - password: Ref - imapHost: Ref - smtpHost: Ref - /** SMTP 端口,465 走 SSL,其余走 STARTTLS */ - smtpPort: Ref - /** 入站+出站白名单 */ - allowedAddresses: Ref -} - -export const Config = Schema.object({ - email: Schema.string().volatile().default('').description('机器人邮箱,如 agent@qq.com'), - password: Schema.string().volatile().default('').description('邮箱密码或授权码'), - imapHost: Schema.string().volatile().default('').description('IMAP 服务器,如 imap.qq.com'), - smtpHost: Schema.string().volatile().default('').description('SMTP 服务器,如 smtp.qq.com'), - smtpPort: Schema.number().volatile().default(465).description('SMTP 端口,465 走 SSL,587 走 STARTTLS'), - allowedAddresses: Schema.array(Schema.string()) - .volatile() - .default([]) - .description('允许与 agent 通信的邮箱地址'), -}) - -interface Servers { - email: string - password: string - imapHost: string - imapPort: number - smtpHost: string - smtpPort: number - smtpSecure: boolean -} - -function resolveServers(config: Config): Servers { - const smtpPort = config.smtpPort.get() - return { - email: config.email.get().trim(), - password: config.password.get(), - imapHost: config.imapHost.get().trim(), - imapPort: 993, - smtpHost: config.smtpHost.get().trim(), - smtpPort, - smtpSecure: smtpPort === 465, - } -} - -interface MailInfo { - from: string - subject: string - messageId?: string -} +export const inject = ['agents', 'settings'] +/** + * 常驻入口:邮件驱动会话,而不是等待模型调用的 Tool。 + * 所有 IMAP/SMTP 资源与监听都收在 ctx.effect 里按序回收。 + */ export function apply(ctx: Context, config: Config): void { - // sessionId -> agent handle - const handles = new Map() - // sessionId -> 最近一封来信(用于回复) - const lastMail = new Map() - // `${sessionId}:${turn}` -> 该 turn 内累积的 assistant 文本 - const turnBuffers = new Map() - - let client: ImapFlow | undefined - let lock: { release(): void } | undefined - let startedKey = '' - - let smtp: ReturnType | undefined - let smtpKey = '' - - const stopImap = async () => { - startedKey = '' - try { lock?.release() } catch {} - lock = undefined - const current = client - client = undefined - if (current) await current.logout().catch(() => {}) - } - - const ensureStarted = async () => { - const servers = resolveServers(config) - const key = JSON.stringify(servers) - if (key === startedKey) return - await stopImap() - - if (!servers.email || !servers.password || !servers.imapHost || !servers.smtpHost) { - console.warn('[mail-bot] 请在 设置 → 插件 → dsh-mail-sender 填写邮箱、密码与 IMAP/SMTP 服务器') - return - } - - const next = new ImapFlow({ - host: servers.imapHost, - port: servers.imapPort, - secure: true, - auth: { user: servers.email, pass: servers.password }, - logger: false, - }) - client = next - startedKey = key - - next.on('exists', async () => { - try { - const mb = next.mailbox - if (mb === false) return - const fetched = await next.fetchOne(mb.exists, { source: true }) - if (fetched === false || !fetched.source) return - - const parsed = await simpleParser(fetched.source) - const from = (parsed.from?.value?.[0]?.address || '').toLowerCase() - if (!from) return - - // 白名单:不在名单内直接丢弃 - const allowed = new Set(config.allowedAddresses.get().map(a => a.toLowerCase().trim())) - if (!allowed.has(from)) return - - const sessionId = `mail-${from}` - lastMail.set(sessionId, { - from, - subject: parsed.subject || '(no subject)', - messageId: parsed.messageId, - }) - - // 同一发件人同一会话 - let handle = handles.get(sessionId) - if (!handle) { - handle = await getOrCreateAgent(ctx, sessionId) - handles.set(sessionId, handle) - } - - handle.agent.followup(createUserMessage({ - content: [{ type: 'text', text: parsed.text || '' }], - source: { kind: 'plugin', plugin: name }, - })) - } catch (err) { - console.error('[mail-bot] 收信失败', err) - } - }) - - try { - await next.connect() - if (client !== next) return void next.logout().catch(() => {}) - lock = await next.getMailboxLock('INBOX') - } catch (err) { - console.error('[mail-bot] IMAP 连接失败', err) - if (client === next) await stopImap() - } - } - - const getSmtp = (servers: Servers) => { - const key = `${servers.smtpHost}:${servers.smtpPort}:${servers.smtpSecure}:${servers.email}` - if (smtpKey !== key) { - smtp = nodemailer.createTransport({ - host: servers.smtpHost, - port: servers.smtpPort, - secure: servers.smtpSecure, - requireTLS: !servers.smtpSecure, - auth: { user: servers.email, pass: servers.password }, - }) - smtpKey = key - } - return smtp! - } - - // 设置保存后(volatile 更新)自动按新配置重连 - ;(ctx as any).on('loader/volatile-update', () => { void ensureStarted() }) - - // 只处理本插件创建的邮件会话 - ;(ctx as any).on('session/event', (session: any, event: any) => { - const id = session?.header?.id - if (typeof id === 'string' && handles.has(id)) handleSessionEvent(id, event) - }) + const gateway = new MailGateway(ctx, mailboxOf(config), addressesOf(config)) + new MailGatewayService(ctx, gateway, config, name) ctx.effect(() => { - void ensureStarted() - return () => { - for (const h of handles.values()) { - try { h.dispose() } catch {} - } - handles.clear() - turnBuffers.clear() - lastMail.clear() - void stopImap() + const disposeGateway = gateway.start() + const on = ctx.on as unknown as (event: string, listener: () => void) => () => void + const off = on('loader/volatile-update', () => { + gateway.reload(mailboxOf(config), addressesOf(config)) + }) + return async () => { + off() + await disposeGateway() } }) - - function handleSessionEvent(sessionId: string, event: any): void { - const data = event?.data ?? {} - const turn = data.turn - const key = `${sessionId}:${turn}` - - if (event.type === 'assistant/message') { - const text = (data.message?.content ?? []) - .filter((b: any) => b.type === 'text') - .map((b: any) => b.text) - .join('') - if (!text) return - turnBuffers.set(key, [...(turnBuffers.get(key) ?? []), text]) - return - } - - // 一轮完整结束后才回信;一个 turn 可能含多个 step - if (event.type === 'turn/end' && data.reason?.kind === 'completed') { - const replyText = (turnBuffers.get(key) ?? []).join('\n\n').trim() - turnBuffers.delete(key) - if (!replyText) return - - const mail = lastMail.get(sessionId) - if (!mail) return - - const servers = resolveServers(config) - const subject = mail.subject.startsWith('Re:') ? mail.subject : `Re: ${mail.subject}` - getSmtp(servers).sendMail({ - from: servers.email, - to: mail.from, - subject, - text: replyText, - inReplyTo: mail.messageId, - references: mail.messageId, - }).catch(err => console.error('[mail-bot] 回信失败', err)) - } - } -} - -async function getOrCreateAgent( - ctx: Context, - sessionId: string, -): Promise<{ dispose(): void; agent: { followup(m: unknown): void } }> { - const agents = (ctx as any).agents - try { - return await agents.resume({ resumeSessionId: sessionId }) - } catch { - return await agents.create({ sessionId }) - } } diff --git a/src/mailbox.ts b/src/mailbox.ts new file mode 100644 index 0000000..2ddabbc --- /dev/null +++ b/src/mailbox.ts @@ -0,0 +1,64 @@ +import type { MailboxPatch, MailboxSettings } from './types.js' + +export function createMailbox(settings: Partial = {}): MailboxSettings { + return { + email: settings.email?.trim() ?? '', + displayName: settings.displayName?.trim() ?? '', + imapHost: settings.imapHost?.trim() ?? '', + imapPort: settings.imapPort ?? 993, + imapSecure: settings.imapSecure ?? true, + smtpHost: settings.smtpHost?.trim() ?? '', + smtpPort: settings.smtpPort ?? 465, + smtpSecure: settings.smtpSecure ?? true, + username: settings.username?.trim() ?? '', + password: settings.password ?? '', + } +} + +/** 合并补丁;password 留空时沿用原密码。 */ +export function mergeMailbox(current: MailboxSettings, patch: MailboxPatch): MailboxSettings { + return createMailbox({ + ...current, + ...patch, + password: patch.password ? patch.password : current.password, + }) +} + +export function isMailboxConfigured(mailbox: MailboxSettings): boolean { + return Boolean( + mailbox.email && + mailbox.imapHost && + mailbox.smtpHost && + (mailbox.username || mailbox.email) && + mailbox.password, + ) +} + +/** 影响连接的身份键;白名单变化不会出现在这里。 */ +export function mailboxKey(mailbox: MailboxSettings): string { + return [ + mailbox.email, + mailbox.username, + mailbox.password, + mailbox.imapHost, + mailbox.imapPort, + mailbox.imapSecure, + mailbox.smtpHost, + mailbox.smtpPort, + mailbox.smtpSecure, + ].join('\u0000') +} + +/** 对外展示的邮箱信息,密码始终清空。 */ +export function publicMailbox(mailbox: MailboxSettings): MailboxSettings { + return { ...mailbox, password: '' } +} + +export function fromHeader(mailbox: MailboxSettings): string { + if (!mailbox.displayName) return mailbox.email + return `"${mailbox.displayName.replace(/"/g, '')}" <${mailbox.email}>` +} + +export function smtpUser(mailbox: MailboxSettings): string { + return mailbox.username || mailbox.email +} diff --git a/src/policy.ts b/src/policy.ts new file mode 100644 index 0000000..b68628d --- /dev/null +++ b/src/policy.ts @@ -0,0 +1,109 @@ +import type { ParsedMail } from 'mailparser' +import type { MailJob } from './types.js' + +/** 规范化后的精确地址集合;只由白名单生成。 */ +export type AccessPolicy = ReadonlySet + +export function normalizeAddress(address: string): string { + return address.trim().toLowerCase() +} + +/** 生成纯策略快照,不改动入参。 */ +export function createPolicy(addresses: readonly string[]): AccessPolicy { + const allowed = new Set() + for (const address of addresses) { + const normalized = normalizeAddress(address) + if (normalized) allowed.add(normalized) + } + return allowed +} + +export function isAllowed(policy: AccessPolicy, address: string): boolean { + return policy.has(normalizeAddress(address)) +} + +function headerText(mail: ParsedMail, name: string): string { + const value = mail.headers.get(name) + if (typeof value === 'string') return value + if (Array.isArray(value)) return value.filter(item => typeof item === 'string').join(', ') + return '' +} + +/** 拦截自动回复 / 批量邮件,避免邮件环。 */ +export function isAutoReply(mail: ParsedMail): boolean { + const autoSubmitted = headerText(mail, 'auto-submitted').toLowerCase() + if (autoSubmitted && autoSubmitted !== 'no') return true + + const precedence = headerText(mail, 'precedence').toLowerCase() + if (/(^|[\s,;])(bulk|junk|list)([\s,;]|$)/.test(precedence)) return true + + return false +} + +function decodeEntities(text: string): string { + return text + .replace(/ /gi, ' ') + .replace(/</gi, '<') + .replace(/>/gi, '>') + .replace(/"/gi, '"') + .replace(/'|'/gi, "'") + .replace(/&/gi, '&') +} + +function htmlToText(html: string): string { + return decodeEntities( + html + .replace(/<(script|style)[\s\S]*?<\/\1>/gi, '') + .replace(//gi, '\n') + .replace(/<\/(p|div|li|tr|h[1-6])>/gi, '\n') + .replace(/<[^>]+>/g, ''), + ) + .replace(/\r\n/g, '\n') + .replace(/[ \t]+\n/g, '\n') + .replace(/\n{3,}/g, '\n\n') + .trim() +} + +/** 正文只取 text/plain,缺失时用 HTML 降级;附件一律丢弃。 */ +export function bodyText(mail: ParsedMail): string { + const plain = mail.text?.trim() + if (plain) return plain + if (mail.html) return htmlToText(mail.html) + return '' +} + +function referencesOf(mail: ParsedMail): string | undefined { + const parts = mail.references + ? Array.isArray(mail.references) + ? mail.references + : [mail.references] + : [] + const all = [...parts] + if (mail.messageId && !all.includes(mail.messageId)) all.push(mail.messageId) + return all.length ? all.join(' ') : undefined +} + +/** + * 一次解析完成准入判断与字段提取:发件地址只解析一次, + * 不在白名单或命中自动流量时返回 null(静默丢弃)。 + */ +export function toJob(policy: AccessPolicy, mail: ParsedMail): MailJob | null { + const sender = mail.from?.value?.[0]?.address + if (!sender) return null + + const from = normalizeAddress(sender) + if (!isAllowed(policy, from)) return null + if (isAutoReply(mail)) return null + + const text = bodyText(mail) + if (!text) return null + + return { + from, + subject: mail.subject?.trim() || '(无主题)', + text, + messageId: mail.messageId, + references: referencesOf(mail), + sessionId: `mail:${from}`, + } +} diff --git a/src/receiver.ts b/src/receiver.ts new file mode 100644 index 0000000..7b877ab --- /dev/null +++ b/src/receiver.ts @@ -0,0 +1,230 @@ +import { ImapFlow } from 'imapflow' +import { simpleParser } from 'mailparser' +import type { AccessPolicy } from './policy.js' +import { toJob } from './policy.js' +import type { CursorStore } from './cursor.js' +import type { MailJob, MailStatus, MailboxSettings } from './types.js' + +/** 不支持的服务器按 60s 轮询,延迟上限约 1 分钟。 */ +export const POLL_INTERVAL_MS = 60_000 +/** 断线重连退避:5s → 10s → 30s → 1min → 5min。 */ +export const BACKOFF_MS = [5_000, 10_000, 30_000, 60_000, 300_000] as const + +export interface ReceiverHooks { + onJob(job: MailJob): void + onStatus(status: MailStatus): void + onLog?(message: string): void +} + +function errorMessage(error: unknown): string { + if (error instanceof Error) return error.message + return String(error) +} + +/** 用临时连接探测 IDLE 能力;登录完成后才读取能力表。 */ +export async function probeIdle(mailbox: MailboxSettings): Promise { + const client = new ImapFlow({ + host: mailbox.imapHost, + port: mailbox.imapPort, + secure: mailbox.imapSecure, + auth: { user: mailbox.username || mailbox.email, pass: mailbox.password }, + logger: false, + disableAutoIdle: true, + greetingTimeout: 10_000, + socketTimeout: 15_000, + }) + try { + await client.connect() + return client.capabilities.get('IDLE') === true + } finally { + await client.logout().catch(() => {}) + } +} + +export class ImapReceiver { + private running = false + private client?: ImapFlow + private wakeSleep?: () => void + private fetching = false + private cursor = 0 + private uidValidity = '' + private status: MailStatus = { + phase: 'disabled', + supportsIdle: false, + pollIntervalMs: POLL_INTERVAL_MS, + } + + constructor( + private readonly mailbox: MailboxSettings, + private readonly policy: () => AccessPolicy, + private readonly cursors: CursorStore, + private readonly hooks: ReceiverHooks, + ) {} + + get currentStatus(): MailStatus { + return this.status + } + + start(): void { + if (this.running) return + this.running = true + void this.run() + } + + async stop(): Promise { + this.running = false + this.wake() + const client = this.client + this.client = undefined + if (client) await client.logout().catch(() => {}) + } + + private report(patch: Partial): void { + this.status = { ...this.status, ...patch } + this.hooks.onStatus(this.status) + } + + private async run(): Promise { + let attempt = 0 + + while (this.running) { + this.report({ phase: 'connecting', lastError: undefined, since: undefined }) + + const client = new ImapFlow({ + host: this.mailbox.imapHost, + port: this.mailbox.imapPort, + secure: this.mailbox.imapSecure, + auth: { user: this.mailbox.username || this.mailbox.email, pass: this.mailbox.password }, + logger: false, + disableAutoIdle: true, + maxIdleTime: POLL_INTERVAL_MS, + }) + this.client = client + + let lock: { release(): void } | undefined + try { + await client.connect() + if (!this.running || this.client !== client) break + + // 认证完成后再探测能力,覆盖 iCloud 一类仅在登录后公布 IDLE 的服务器。 + const supportsIdle = client.capabilities.get('IDLE') === true + lock = await client.getMailboxLock('INBOX') + await this.prime(client) + attempt = 0 + this.report({ + phase: supportsIdle ? 'idle' : 'polling', + supportsIdle, + lastError: undefined, + since: new Date().toISOString(), + }) + + while (this.running && this.client === client) { + if (supportsIdle) { + const found = await client.idle() + if (!found && this.running) await this.sleep(1_000) + } else { + await this.sleep(POLL_INTERVAL_MS) + } + if (!this.running || this.client !== client) break + await this.collect(client) + } + } catch (error) { + if (this.running) { + attempt = Math.min(attempt + 1, BACKOFF_MS.length) + this.report({ + phase: 'error', + lastError: errorMessage(error), + since: undefined, + }) + this.hooks.onLog?.(`[mail] IMAP 连接失败: ${errorMessage(error)}`) + } + } finally { + try { + lock?.release() + } catch {} + if (this.client === client) this.client = undefined + await client.logout().catch(() => {}) + } + + if (!this.running) break + const delay = BACKOFF_MS[Math.max(0, attempt - 1)] ?? BACKOFF_MS[BACKOFF_MS.length - 1] + await this.sleep(delay) + } + + this.report({ phase: 'disabled', since: undefined }) + } + + /** 首次配置或 UIDVALIDITY 变化时建立基线,不回放历史邮件。 */ + private async prime(client: ImapFlow): Promise { + const mailbox = client.mailbox + if (!mailbox) return + + const uidValidity = String(mailbox.uidValidity) + const stored = await this.cursors.read() + const cursor = + stored && stored.uidValidity === uidValidity ? stored.uid : Math.max(0, mailbox.uidNext - 1) + + this.uidValidity = uidValidity + this.cursor = cursor + await this.cursors.write({ uidValidity, uid: cursor }) + } + + private async collect(client: ImapFlow): Promise { + if (this.fetching) return + this.fetching = true + try { + const mailbox = client.mailbox + if (!mailbox) return + + if (String(mailbox.uidValidity) !== this.uidValidity) { + await this.prime(client) + return + } + + const range = `${this.cursor + 1}:*` + for await (const message of client.fetch( + { uid: range }, + { uid: true, source: true }, + { uid: true }, + )) { + const uid = message.uid + if (typeof uid !== 'number' || uid <= this.cursor || !message.source) continue + + try { + const parsed = await simpleParser(message.source) + const job = toJob(this.policy(), parsed) + if (job) this.hooks.onJob(job) + } catch (error) { + this.hooks.onLog?.(`[mail] 解析 UID ${uid} 失败: ${errorMessage(error)}`) + } + + if (uid > this.cursor) { + this.cursor = uid + void this.cursors.write({ uidValidity: this.uidValidity, uid }) + } + } + } catch (error) { + if (this.running) this.hooks.onLog?.(`[mail] 收信失败: ${errorMessage(error)}`) + } finally { + this.fetching = false + } + } + + private sleep(ms: number): Promise { + return new Promise(resolve => { + const timer = setTimeout(() => { + this.wakeSleep = undefined + resolve() + }, ms) + this.wakeSleep = () => { + clearTimeout(timer) + this.wakeSleep = undefined + resolve() + } + }) + } + + private wake(): void { + this.wakeSleep?.() + } +} diff --git a/src/remote.ts b/src/remote.ts new file mode 100644 index 0000000..252d719 --- /dev/null +++ b/src/remote.ts @@ -0,0 +1,133 @@ +import { z } from 'zod' +import { createTypertRemoteInfo } from '@deepseek-ai/dsh-typert-protocol/remote-info' +import type { RemoteResult, TypertRemoteInfo, TypertRemoteMethod } from '@deepseek-ai/dsh-typert-protocol' +import type { ConnectionTestResult, MailSnapshot, MailStatus, MailboxPatch } from './types.js' + +const mailboxSchema = () => + z.object({ + email: z.string(), + displayName: z.string(), + imapHost: z.string(), + imapPort: z.number(), + imapSecure: z.boolean(), + smtpHost: z.string(), + smtpPort: z.number(), + smtpSecure: z.boolean(), + username: z.string(), + password: z.string(), + }) + +const statusSchema = () => + z.object({ + phase: z.enum(['disabled', 'connecting', 'idle', 'polling', 'error']), + supportsIdle: z.boolean(), + pollIntervalMs: z.number(), + lastError: z.string().optional(), + since: z.string().optional(), + }) + +const snapshotSchema = () => + z.object({ + mailbox: mailboxSchema(), + passwordSet: z.boolean(), + allowedAddresses: z.array(z.string()), + status: statusSchema(), + }) + +const patchSchema = () => + z.object({ + email: z.string().optional(), + displayName: z.string().optional(), + imapHost: z.string().optional(), + imapPort: z.number().optional(), + imapSecure: z.boolean().optional(), + smtpHost: z.string().optional(), + smtpPort: z.number().optional(), + smtpSecure: z.boolean().optional(), + username: z.string().optional(), + password: z.string().optional(), + }) + +const testResultSchema = () => + z.object({ + ok: z.boolean(), + supportsIdle: z.boolean(), + error: z.string().optional(), + }) + +function codec(typeSymbol: string, create: () => z.ZodType) { + return { mode: 'strict' as const, typeSymbol, create } +} + +function jsonParameter(name: string, typeSymbol: string, create: () => z.ZodType) { + return { + name, + source: 'json' as const, + codec: codec(typeSymbol, create), + strictCodec: codec(`${typeSymbol}#strict`, create), + } +} + +export const TYPERT_REMOTE = createTypertRemoteInfo({ + package: 'dsh-mail-sender', + methods: { + 'mail-gateway/get': { + service: 'mailGateway', + invocation: { kind: 'direct' }, + parameters: [], + result: codec('dsh-mail-sender#MailSnapshot', snapshotSchema), + }, + 'mail-gateway/saveMailbox': { + service: 'mailGateway', + invocation: { kind: 'direct' }, + parameters: [jsonParameter('patch', 'dsh-mail-sender#MailboxPatch', patchSchema)], + result: codec('dsh-mail-sender#MailSnapshot', snapshotSchema), + }, + 'mail-gateway/saveWhitelist': { + service: 'mailGateway', + invocation: { kind: 'direct' }, + parameters: [jsonParameter('addresses', 'dsh-mail-sender#AddressList', () => z.array(z.string()))], + result: codec('dsh-mail-sender#MailSnapshot', snapshotSchema), + }, + 'mail-gateway/testConnection': { + service: 'mailGateway', + invocation: { kind: 'direct' }, + parameters: [jsonParameter('patch', 'dsh-mail-sender#MailboxPatch', patchSchema)], + result: codec('dsh-mail-sender#ConnectionTestResult', testResultSchema), + }, + 'mail-gateway/status': { + service: 'mailGateway', + invocation: { kind: 'direct' }, + parameters: [], + result: codec('dsh-mail-sender#MailStatus', statusSchema), + }, + }, +}, z) as TypertRemoteInfo<{ + readonly 'mail-gateway/get': TypertRemoteMethod<{}, MailSnapshot> + readonly 'mail-gateway/saveMailbox': TypertRemoteMethod<{ patch: MailboxPatch }, MailSnapshot> + readonly 'mail-gateway/saveWhitelist': TypertRemoteMethod<{ addresses: readonly string[] }, MailSnapshot> + readonly 'mail-gateway/testConnection': TypertRemoteMethod<{ patch: MailboxPatch }, ConnectionTestResult> + readonly 'mail-gateway/status': TypertRemoteMethod<{}, MailStatus> +}> + +declare module '@deepseek-ai/dsh-typert-protocol' { + interface TypertRemoteNamespace$6d61696c2d67617465776179 { + get: () => Promise> + saveMailbox: (patch: MailboxPatch) => Promise> + saveWhitelist: (addresses: string[]) => Promise> + testConnection: (patch: MailboxPatch) => Promise> + status: () => Promise> + } + interface TypertRemoteMap { + 'mail-gateway/get': () => Promise> + 'mail-gateway/saveMailbox': (patch: MailboxPatch) => Promise> + 'mail-gateway/saveWhitelist': (addresses: string[]) => Promise> + 'mail-gateway/testConnection': (patch: MailboxPatch) => Promise> + 'mail-gateway/status': () => Promise> + } + interface TypertRemoteNamespaceMap { + 'mail-gateway': TypertRemoteNamespace$6d61696c2d67617465776179 + } +} + +export default TYPERT_REMOTE diff --git a/src/sender.ts b/src/sender.ts new file mode 100644 index 0000000..b70fa82 --- /dev/null +++ b/src/sender.ts @@ -0,0 +1,57 @@ +import nodemailer from 'nodemailer' +import type { Transporter } from 'nodemailer' +import { fromHeader, mailboxKey, smtpUser } from './mailbox.js' +import type { MailJob, MailboxSettings } from './types.js' + +function replySubject(subject: string): string { + return /^re\s*:/i.test(subject) ? subject : `Re: ${subject}` +} + +/** SMTP 发送器:单例连接池,每封信复用连接。 */ +export class SmtpSender { + private transporter?: Transporter + private key = '' + + constructor(private mailbox: MailboxSettings) { + this.sync() + } + + update(mailbox: MailboxSettings): void { + const next = `${mailboxKey(mailbox)}\u0000${mailbox.displayName}` + if (next === this.key) return + this.close() + this.mailbox = mailbox + this.sync() + } + + private sync(): void { + this.key = `${mailboxKey(this.mailbox)}\u0000${this.mailbox.displayName}` + this.transporter = nodemailer.createTransport({ + host: this.mailbox.smtpHost, + port: this.mailbox.smtpPort, + secure: this.mailbox.smtpSecure, + requireTLS: !this.mailbox.smtpSecure, + pool: true, + maxConnections: 3, + auth: { user: smtpUser(this.mailbox), pass: this.mailbox.password }, + }) + } + + async send(job: MailJob, text: string): Promise { + if (!this.transporter) this.sync() + await this.transporter!.sendMail({ + from: fromHeader(this.mailbox), + to: job.from, + subject: replySubject(job.subject), + text, + inReplyTo: job.messageId, + references: job.references ?? job.messageId, + }) + } + + /** 关闭连接池;不等待在途邮件的重试。 */ + close(): void { + this.transporter?.close() + this.transporter = undefined + } +} diff --git a/src/service.ts b/src/service.ts new file mode 100644 index 0000000..2582015 --- /dev/null +++ b/src/service.ts @@ -0,0 +1,138 @@ +import type { Context } from '@deepseek-ai/cordis' +import type {} from '@deepseek-ai/dsh-settings' +import { Remote, RemoteError, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol' +import type { Config } from './config.js' +import type { MailGateway } from './gateway.js' +import { createMailbox, mergeMailbox } from './mailbox.js' +import { normalizeAddress } from './policy.js' +import { probeIdle } from './receiver.js' +import type { + ConnectionTestResult, + MailSnapshot, + MailStatus, + MailboxPatch, + MailboxSettings, +} from './types.js' + +function messageOf(error: unknown): string { + return error instanceof Error ? error.message : String(error) +} + +function validate(mailbox: MailboxSettings): string | undefined { + if (!mailbox.email) return '请填写邮箱地址' + if (!mailbox.imapHost) return '请填写 IMAP 主机' + if (!mailbox.smtpHost) return '请填写 SMTP 主机' + if (!(mailbox.username || mailbox.email)) return '请填写登录用户名' + if (!mailbox.password) return '请填写密码' + if (!Number.isInteger(mailbox.imapPort) || mailbox.imapPort <= 0) return 'IMAP 端口无效' + if (!Number.isInteger(mailbox.smtpPort) || mailbox.smtpPort <= 0) return 'SMTP 端口无效' + return undefined +} + +/** Remote 面:设置页的读写、测试与状态查询。 */ +export class MailGatewayService extends TypertRemoteService { + static inject = ['settings'] + + private namespace?: string + + constructor( + private readonly context: Context, + private readonly gateway: MailGateway, + private readonly config: Config, + private readonly defaultNamespace: string, + ) { + super(context, 'mailGateway', { namespace: 'mail-gateway' }) + } + + @Remote('get') + async get(): Promise { + return this.gateway.snapshot() + } + + @Remote('status') + async status(): Promise { + return this.gateway.snapshot().status + } + + @Remote('saveMailbox') + async saveMailbox(patch: MailboxPatch): Promise { + const current = createMailbox(this.config.mailbox.get()) + const next = mergeMailbox(current, patch) + const invalid = validate(next) + if (invalid) throw new RemoteError('gateway/bad-request', invalid, {}) + + const ops: { op: 'set'; path: string[]; value: unknown }[] = [] + for (const field of [ + 'email', + 'displayName', + 'imapHost', + 'imapPort', + 'imapSecure', + 'smtpHost', + 'smtpPort', + 'smtpSecure', + 'username', + ] as const) { + if (next[field] !== current[field]) ops.push({ op: 'set', path: ['mailbox', field], value: next[field] }) + } + // 密码留空表示不修改,且绝不把已存密码回写到表单。 + if (next.password !== current.password) { + ops.push({ op: 'set', path: ['mailbox', 'password'], value: next.password }) + } + + try { + if (ops.length) await this.context.settings.mutate(this.resolveNamespace(), ops) + } catch (error) { + throw new RemoteError('gateway/internal', messageOf(error), {}) + } + + this.gateway.reload(next, this.config.allowedAddresses.get() ?? []) + return this.gateway.snapshot() + } + + @Remote('saveWhitelist') + async saveWhitelist(addresses: string[]): Promise { + const normalized = [...new Set(addresses.map(normalizeAddress).filter(Boolean))] + + try { + await this.context.settings.mutate(this.resolveNamespace(), [ + { op: 'set', path: ['allowedAddresses'], value: normalized }, + ]) + } catch (error) { + throw new RemoteError('gateway/internal', messageOf(error), {}) + } + + // 只更新内存策略,不断开 IMAP 连接。 + this.gateway.updatePolicy(normalized) + return this.gateway.snapshot() + } + + @Remote('testConnection') + async testConnection(patch: MailboxPatch): Promise { + const mailbox = mergeMailbox(createMailbox(this.config.mailbox.get()), patch) + if (!mailbox.imapHost || !(mailbox.username || mailbox.email) || !mailbox.password) { + return { ok: false, supportsIdle: false, error: '请先填写 IMAP 主机、用户名和密码' } + } + + try { + return { ok: true, supportsIdle: await probeIdle(mailbox) } + } catch (error) { + return { ok: false, supportsIdle: false, error: messageOf(error) } + } + } + + /** profile 里的实例 id 通常就是包名;回退用 schema 里的字段名定位。 */ + private resolveNamespace(): string { + if (this.namespace) return this.namespace + const descriptors = this.context.settings.describe() + const own = + descriptors.find(item => item.ns === this.defaultNamespace) ?? + descriptors.find(item => JSON.stringify(item.schema ?? '').includes('imapHost')) + + if (!own) { + throw new RemoteError('gateway/bad-request', '未找到 dsh-mail-sender 的配置项', {}) + } + this.namespace = own.ns + return own.ns + } +} diff --git a/src/typert.ts b/src/typert.ts new file mode 100644 index 0000000..d612fa2 --- /dev/null +++ b/src/typert.ts @@ -0,0 +1,5 @@ +/** + * Source-mode Typert artifact. Decorated Service methods are discovered from + * the live prototype, so no generated compiler facts are required. + */ +export const TYPERT: unknown = undefined diff --git a/src/types.ts b/src/types.ts new file mode 100644 index 0000000..deb4dae --- /dev/null +++ b/src/types.ts @@ -0,0 +1,61 @@ +/** 邮箱绑定信息,宿主与客户端共用。 */ +export interface MailboxSettings { + email: string + displayName: string + imapHost: string + imapPort: number + imapSecure: boolean + smtpHost: string + smtpPort: number + smtpSecure: boolean + username: string + password: string +} + +/** 表单提交的邮箱补丁;空 password 表示不修改已存密码。 */ +export interface MailboxPatch { + email?: string + displayName?: string + imapHost?: string + imapPort?: number + imapSecure?: boolean + smtpHost?: string + smtpPort?: number + smtpSecure?: boolean + username?: string + password?: string +} + +/** 一次被准入的来信。 */ +export interface MailJob { + readonly from: string + readonly subject: string + readonly text: string + readonly messageId?: string + readonly references?: string + readonly sessionId: string +} + +export type MailPhase = 'disabled' | 'connecting' | 'idle' | 'polling' | 'error' + +export interface MailStatus { + readonly phase: MailPhase + readonly supportsIdle: boolean + readonly pollIntervalMs: number + readonly lastError?: string + readonly since?: string +} + +/** 设置页一次读取的完整快照(不含密码明文)。 */ +export interface MailSnapshot { + readonly mailbox: MailboxSettings + readonly passwordSet: boolean + readonly allowedAddresses: readonly string[] + readonly status: MailStatus +} + +export interface ConnectionTestResult { + readonly ok: boolean + readonly supportsIdle: boolean + readonly error?: string +} diff --git a/tasks.md b/tasks.md new file mode 100644 index 0000000..445d90f --- /dev/null +++ b/tasks.md @@ -0,0 +1,21 @@ +# 任务清单 + +## [x] T1 修复同会话多封邮件的回复映射 + +- 文件:`src/deliver.ts` +- `pending: Set` 与 `jobs: Map` 合并为 `pending: Map` +- `deliver()`:`ensure()` 后 `queue.push(job)`,再 `followup` +- `turn/end`:始终从队首 `shift()` 一封(空队列则 `delete`),仅在 `reason.kind === 'completed'` 且文本非空时 `onReply` +- `dispose()`:`pending.clear()` +- 验证:已静态检查队列入队/出队/清理路径,`jobs` 引用已清零 + +## [x] T2 静态一致性复核 + +- 全仓检索 `pending`、`jobs`、`onReply`:仅 `deliver.ts` 使用,语义一致,无残留 `jobs` +- `src/types.ts`、`src/gateway.ts` 未改动 + +## [x] T3 约束确认 + +- 未执行 `npm install` / `npm run build` / 任何 dsh 命令 +- 未改 `guide.md`、`package.json`、`cordis.patch.yml` +- 真实 DSH 宿主上仍需验证:客户端 Remote `$mount` 与 `settings.section` 渲染、`settings.mutate` 对嵌套 volatile / secret 字段的落地 diff --git a/tsconfig.json b/tsconfig.json index 7b19493..65b0387 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -3,7 +3,8 @@ "target": "ES2022", "module": "ESNext", "moduleResolution": "Bundler", - "lib": ["ES2022"], + "lib": ["ES2022", "DOM", "DOM.Iterable"], + "jsx": "react-jsx", "outDir": "lib", "rootDir": "src", "declaration": true,