[feat] rebuild
This commit is contained in:
24 files changed
+2921
-330
No files matched your search
@@ -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 ② 邮箱绑定表格
|
||||
|
||||
用真正的 `<table>` 布局,每行一个字段,三列:**字段名 / 输入控件 / 说明**。说明列固定文案,不随输入变化。
|
||||
|
||||
**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` 纯展示。
|
||||
Generated
+867
-36
File diff suppressed because it is too large.
Load diff
+43
-9
@@ -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": {
|
||||
|
||||
@@ -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
|
||||
```
|
||||
客户端入口为 `./client`,由 esbuild 打包为单文件;宿主入口为 `./index.js`。
|
||||
@@ -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/<sha1>.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<string, MailJob>` 每个会话只保留最新一封;`pending: Set<string>` 无法表达“一封信对应一轮”。同一发件人连发两封且第一轮未结束时:
|
||||
|
||||
1. 第一轮 `turn/end` 用第二封的 `messageId` / 主题回信,线程归并错乱;
|
||||
2. `pending` 被删除,第二轮结束时不再回信,第二封永久丢失回复。
|
||||
|
||||
**改法(决策已定)**:
|
||||
|
||||
- 将 `pending: Set<string>` + `jobs: Map<string, MailJob>` 合并为 `pending: Map<string, MailJob[]>`。
|
||||
- `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<string, MailJob[]>`、`shift()` 后空队列删除、`completed` 判定)。
|
||||
2. 全仓检索 `pending` / `jobs` 无残留引用。
|
||||
3. 核对 `src/types.ts` 的 `MailJob` 与 `MailSnapshot` 未被改动。
|
||||
|
||||
## 7. 审批
|
||||
|
||||
确认本规格后按其执行 `tasks.md`;若不同意“失败轮次也出队”或 FIFO 映射方式,请先指出再改。
|
||||
@@ -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<MailSnapshot>()
|
||||
const [mailbox, setMailbox] = useState<MailboxSettings>()
|
||||
const [password, setPassword] = useState('')
|
||||
const [allowed, setAllowed] = useState<string[]>([])
|
||||
const [entry, setEntry] = useState('')
|
||||
const [test, setTest] = useState<ConnectionTestResult>()
|
||||
const [busy, setBusy] = useState<Busy>(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 = <K extends keyof MailboxSettings>(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<HTMLInputElement>) => {
|
||||
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<HTMLInputElement>) => {
|
||||
setField(key, Number(event.target.value) || 0)
|
||||
}
|
||||
|
||||
const textField = (
|
||||
key: 'email' | 'displayName' | 'imapHost' | 'smtpHost' | 'username',
|
||||
) => (event: ChangeEvent<HTMLInputElement>) => {
|
||||
setField(key, event.target.value)
|
||||
}
|
||||
|
||||
const boolField = (key: 'imapSecure' | 'smtpSecure') => (event: ChangeEvent<HTMLInputElement>) => {
|
||||
setField(key, event.target.checked)
|
||||
}
|
||||
|
||||
return (
|
||||
<div style={section}>
|
||||
<StatusCard status={snapshot?.status} allowedCount={allowed.length} test={test} />
|
||||
|
||||
<div>
|
||||
<h3 style={{ margin: '0 0 8px', fontSize: 15 }}>邮箱绑定</h3>
|
||||
<table style={table}>
|
||||
<thead>
|
||||
<tr>
|
||||
<th style={{ ...cell, ...muted, width: 140 }}>字段</th>
|
||||
<th style={{ ...cell, ...muted }}>值</th>
|
||||
<th style={{ ...cell, ...muted, width: 240 }}>说明</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr>
|
||||
<td style={cell}>邮箱地址</td>
|
||||
<td style={cell}>
|
||||
<input style={input} value={mailbox?.email ?? ''} onChange={textField('email')} />
|
||||
</td>
|
||||
<td style={{ ...cell, ...muted }}>接收邮件与回信使用的地址。</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td style={cell}>显示名</td>
|
||||
<td style={cell}>
|
||||
<input style={input} value={mailbox?.displayName ?? ''} onChange={textField('displayName')} />
|
||||
</td>
|
||||
<td style={{ ...cell, ...muted }}>回信时的发件人名称,可留空。</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td style={cell}>IMAP 主机</td>
|
||||
<td style={cell}>
|
||||
<input style={input} value={mailbox?.imapHost ?? ''} onChange={textField('imapHost')} />
|
||||
</td>
|
||||
<td style={{ ...cell, ...muted }}>标准 IMAP 服务器地址。</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td style={cell}>IMAP 端口</td>
|
||||
<td style={cell}>
|
||||
<input style={input} value={mailbox?.imapPort ?? 993} onChange={numberField('imapPort')} />
|
||||
</td>
|
||||
<td style={{ ...cell, ...muted }}>SSL 一般为 993。</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td style={cell}>IMAP TLS</td>
|
||||
<td style={cell}>
|
||||
<input type="checkbox" checked={mailbox?.imapSecure ?? true} onChange={boolField('imapSecure')} />
|
||||
</td>
|
||||
<td style={{ ...cell, ...muted }}>勾选表示使用 SSL/TLS。</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td style={cell}>SMTP 主机</td>
|
||||
<td style={cell}>
|
||||
<input style={input} value={mailbox?.smtpHost ?? ''} onChange={textField('smtpHost')} />
|
||||
</td>
|
||||
<td style={{ ...cell, ...muted }}>标准 SMTP 服务器地址。</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td style={cell}>SMTP 端口</td>
|
||||
<td style={cell}>
|
||||
<input style={input} value={mailbox?.smtpPort ?? 465} onChange={numberField('smtpPort')} />
|
||||
</td>
|
||||
<td style={{ ...cell, ...muted }}>SSL 一般为 465。</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td style={cell}>SMTP TLS</td>
|
||||
<td style={cell}>
|
||||
<input type="checkbox" checked={mailbox?.smtpSecure ?? true} onChange={boolField('smtpSecure')} />
|
||||
</td>
|
||||
<td style={{ ...cell, ...muted }}>勾选表示使用 SSL/TLS。</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td style={cell}>登录用户名</td>
|
||||
<td style={cell}>
|
||||
<input style={input} value={mailbox?.username ?? ''} onChange={textField('username')} />
|
||||
</td>
|
||||
<td style={{ ...cell, ...muted }}>留空时使用邮箱地址。</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td style={cell}>密码</td>
|
||||
<td style={cell}>
|
||||
<input
|
||||
style={input}
|
||||
type="password"
|
||||
value={password}
|
||||
placeholder={snapshot?.passwordSet ? '已设置,留空表示不修改' : '未设置'}
|
||||
onChange={event => setPassword(event.target.value)}
|
||||
/>
|
||||
</td>
|
||||
<td style={{ ...cell, ...muted }}>保存后只显示“已设置”,不会回显明文。</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<div style={{ ...row, marginTop: 10 }}>
|
||||
<button style={primary} disabled={busy !== null} onClick={() => void saveMailbox()}>
|
||||
{busy === 'mailbox' ? '保存中…' : '保存邮箱绑定'}
|
||||
</button>
|
||||
<button style={button} disabled={busy !== null} onClick={() => void testConnection()}>
|
||||
{busy === 'test' ? '测试中…' : '测试连接'}
|
||||
</button>
|
||||
<span style={muted}>保存邮箱绑定时会按新配置重建连接。</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<h3 style={{ margin: '0 0 8px', fontSize: 15 }}>白名单</h3>
|
||||
<div style={{ ...row, marginBottom: 8 }}>
|
||||
<input
|
||||
style={{ ...input, maxWidth: 320 }}
|
||||
value={entry}
|
||||
placeholder="输入邮箱地址后回车添加"
|
||||
onChange={event => setEntry(event.target.value)}
|
||||
onKeyDown={onEntryKey}
|
||||
/>
|
||||
<button style={button} onClick={addAddress}>
|
||||
添加
|
||||
</button>
|
||||
</div>
|
||||
<table style={table}>
|
||||
<tbody>
|
||||
{allowed.length === 0 ? (
|
||||
<tr>
|
||||
<td style={{ ...cell, ...muted }}>暂无地址,白名单为空时不会接收任何邮件。</td>
|
||||
</tr>
|
||||
) : (
|
||||
allowed.map(address => (
|
||||
<tr key={address}>
|
||||
<td style={cell}>{address}</td>
|
||||
<td style={{ ...cell, width: 80, textAlign: 'right' }}>
|
||||
<button style={button} onClick={() => removeAddress(address)}>
|
||||
删除
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
))
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
<div style={{ ...row, marginTop: 10 }}>
|
||||
<button style={primary} disabled={busy !== null} onClick={() => void saveWhitelist()}>
|
||||
{busy === 'whitelist' ? '保存中…' : '保存白名单'}
|
||||
</button>
|
||||
<span style={muted}>同一份白名单同时校验入站发件地址与出站回复地址。</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{notice ? (
|
||||
<div style={{ color: notice.kind === 'ok' ? '#047857' : '#b91c1c', fontSize: 13 }}>
|
||||
{notice.text}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -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 (
|
||||
<div style={card}>
|
||||
<div style={{ color: state.color, fontWeight: 600 }}>{state.text}</div>
|
||||
{status?.phase === 'idle' || status?.phase === 'polling' ? (
|
||||
<div style={{ color: '#6b7280' }}>
|
||||
收信策略:{allowedCount > 0 ? `仅接收白名单内 ${allowedCount} 个地址的邮件。` : '白名单为空,不会接收任何邮件。'}
|
||||
{status.since ? ` 连接建立于 ${new Date(status.since).toLocaleString()}。` : ''}
|
||||
</div>
|
||||
) : null}
|
||||
{allowedCount === 0 && status?.phase !== 'idle' && status?.phase !== 'polling' ? (
|
||||
<div style={{ color: '#b45309' }}>白名单为空:不会接收任何邮件。</div>
|
||||
) : null}
|
||||
{test ? (
|
||||
<div style={{ color: test.ok ? '#047857' : '#b91c1c' }}>
|
||||
{test.ok
|
||||
? test.supportsIdle
|
||||
? '测试连接成功:服务器支持 IDLE。'
|
||||
: '测试连接成功:服务器不支持 IDLE,将使用轮询。'
|
||||
: `测试连接失败:${test.error ?? '未知原因'}`}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -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<RemoteResult<MailSnapshot>>
|
||||
saveMailbox(patch: MailboxPatch): Promise<RemoteResult<MailSnapshot>>
|
||||
saveWhitelist(addresses: string[]): Promise<RemoteResult<MailSnapshot>>
|
||||
testConnection(patch: MailboxPatch): Promise<RemoteResult<ConnectionTestResult>>
|
||||
status(): Promise<RemoteResult<MailStatus>>
|
||||
}
|
||||
|
||||
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(),
|
||||
}
|
||||
}
|
||||
@@ -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<void>> {
|
||||
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
|
||||
}
|
||||
@@ -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<T> {
|
||||
get(): T
|
||||
}
|
||||
|
||||
export interface Config {
|
||||
mailbox: Ref<MailboxSettings>
|
||||
allowedAddresses: Ref<string[]>
|
||||
}
|
||||
|
||||
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() ?? [])]
|
||||
}
|
||||
@@ -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<CursorRecord | undefined> {
|
||||
if (this.cache) return this.cache
|
||||
try {
|
||||
const raw = await readFile(this.file, 'utf8')
|
||||
const parsed = JSON.parse(raw) as Partial<CursorRecord>
|
||||
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<void> {
|
||||
this.cache = record
|
||||
try {
|
||||
await mkdir(dirname(this.file), { recursive: true })
|
||||
await writeFile(this.file, JSON.stringify(record), 'utf8')
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
+124
@@ -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<void>
|
||||
}
|
||||
|
||||
/**
|
||||
* 邮件会话适配层:ctx.agents / session/event 的全部调用都收在这里,
|
||||
* Agent API 变化时只需改这一个文件。
|
||||
*/
|
||||
export class MailDeliverer {
|
||||
private readonly handles = new Map<string, DriveHandle>()
|
||||
private readonly turnBuffers = new Map<string, string[]>()
|
||||
/** 每个会话按投递顺序排队,一轮回复对应队首的一封来信。 */
|
||||
private readonly pending = new Map<string, MailJob[]>()
|
||||
private readonly off: () => void
|
||||
|
||||
constructor(
|
||||
private readonly ctx: Context,
|
||||
private readonly onReply: (job: MailJob, text: string) => Promise<void>,
|
||||
private readonly onLog?: (message: string) => void,
|
||||
) {
|
||||
this.off = ctx.on('session/event', (session, event) => {
|
||||
this.handleEvent(session, event)
|
||||
})
|
||||
}
|
||||
|
||||
async deliver(job: MailJob): Promise<void> {
|
||||
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<DriveHandle> {
|
||||
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)}`)
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
+149
@@ -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<void> {
|
||||
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<void> {
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
+20
-238
@@ -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<T> {
|
||||
get(): T
|
||||
}
|
||||
|
||||
export interface Config {
|
||||
/** 机器人邮箱,同时用于 IMAP/SMTP 登录与回信 From */
|
||||
email: Ref<string>
|
||||
/** 邮箱密码或授权码 */
|
||||
password: Ref<string>
|
||||
imapHost: Ref<string>
|
||||
smtpHost: Ref<string>
|
||||
/** SMTP 端口,465 走 SSL,其余走 STARTTLS */
|
||||
smtpPort: Ref<number>
|
||||
/** 入站+出站白名单 */
|
||||
allowedAddresses: Ref<string[]>
|
||||
}
|
||||
|
||||
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<string, { dispose(): void; agent: { followup(m: unknown): void } }>()
|
||||
// sessionId -> 最近一封来信(用于回复)
|
||||
const lastMail = new Map<string, MailInfo>()
|
||||
// `${sessionId}:${turn}` -> 该 turn 内累积的 assistant 文本
|
||||
const turnBuffers = new Map<string, string[]>()
|
||||
|
||||
let client: ImapFlow | undefined
|
||||
let lock: { release(): void } | undefined
|
||||
let startedKey = ''
|
||||
|
||||
let smtp: ReturnType<typeof nodemailer.createTransport> | 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 })
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import type { MailboxPatch, MailboxSettings } from './types.js'
|
||||
|
||||
export function createMailbox(settings: Partial<MailboxSettings> = {}): 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
|
||||
}
|
||||
+109
@@ -0,0 +1,109 @@
|
||||
import type { ParsedMail } from 'mailparser'
|
||||
import type { MailJob } from './types.js'
|
||||
|
||||
/** 规范化后的精确地址集合;只由白名单生成。 */
|
||||
export type AccessPolicy = ReadonlySet<string>
|
||||
|
||||
export function normalizeAddress(address: string): string {
|
||||
return address.trim().toLowerCase()
|
||||
}
|
||||
|
||||
/** 生成纯策略快照,不改动入参。 */
|
||||
export function createPolicy(addresses: readonly string[]): AccessPolicy {
|
||||
const allowed = new Set<string>()
|
||||
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(/<br\s*\/?>/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}`,
|
||||
}
|
||||
}
|
||||
+230
@@ -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<boolean> {
|
||||
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<void> {
|
||||
this.running = false
|
||||
this.wake()
|
||||
const client = this.client
|
||||
this.client = undefined
|
||||
if (client) await client.logout().catch(() => {})
|
||||
}
|
||||
|
||||
private report(patch: Partial<MailStatus>): void {
|
||||
this.status = { ...this.status, ...patch }
|
||||
this.hooks.onStatus(this.status)
|
||||
}
|
||||
|
||||
private async run(): Promise<void> {
|
||||
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<void> {
|
||||
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<void> {
|
||||
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<void> {
|
||||
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?.()
|
||||
}
|
||||
}
|
||||
+133
@@ -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<RemoteResult<MailSnapshot>>
|
||||
saveMailbox: (patch: MailboxPatch) => Promise<RemoteResult<MailSnapshot>>
|
||||
saveWhitelist: (addresses: string[]) => Promise<RemoteResult<MailSnapshot>>
|
||||
testConnection: (patch: MailboxPatch) => Promise<RemoteResult<ConnectionTestResult>>
|
||||
status: () => Promise<RemoteResult<MailStatus>>
|
||||
}
|
||||
interface TypertRemoteMap {
|
||||
'mail-gateway/get': () => Promise<RemoteResult<MailSnapshot>>
|
||||
'mail-gateway/saveMailbox': (patch: MailboxPatch) => Promise<RemoteResult<MailSnapshot>>
|
||||
'mail-gateway/saveWhitelist': (addresses: string[]) => Promise<RemoteResult<MailSnapshot>>
|
||||
'mail-gateway/testConnection': (patch: MailboxPatch) => Promise<RemoteResult<ConnectionTestResult>>
|
||||
'mail-gateway/status': () => Promise<RemoteResult<MailStatus>>
|
||||
}
|
||||
interface TypertRemoteNamespaceMap {
|
||||
'mail-gateway': TypertRemoteNamespace$6d61696c2d67617465776179
|
||||
}
|
||||
}
|
||||
|
||||
export default TYPERT_REMOTE
|
||||
@@ -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<void> {
|
||||
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
|
||||
}
|
||||
}
|
||||
+138
@@ -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<MailSnapshot> {
|
||||
return this.gateway.snapshot()
|
||||
}
|
||||
|
||||
@Remote('status')
|
||||
async status(): Promise<MailStatus> {
|
||||
return this.gateway.snapshot().status
|
||||
}
|
||||
|
||||
@Remote('saveMailbox')
|
||||
async saveMailbox(patch: MailboxPatch): Promise<MailSnapshot> {
|
||||
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<MailSnapshot> {
|
||||
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<ConnectionTestResult> {
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
@@ -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
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
# 任务清单
|
||||
|
||||
## [x] T1 修复同会话多封邮件的回复映射
|
||||
|
||||
- 文件:`src/deliver.ts`
|
||||
- `pending: Set<string>` 与 `jobs: Map<string, MailJob>` 合并为 `pending: Map<string, MailJob[]>`
|
||||
- `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 字段的落地
|
||||
+2
-1
@@ -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,
|
||||
|
||||
Reference in new issue
Block a user