[feat] rebuild

This commit is contained in:
zhhe committed 2026-11-16 12:05:30 +08:00
1 parent e9bc31fe01
commit 9bd8e0a06f
24 files changed
+2921 -330

No files matched your search

+328
View File
@@ -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>
)
}
+64
View File
@@ -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>
)
}
+30
View File
@@ -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(),
}
}
+32
View File
@@ -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
}
+56
View File
@@ -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() ?? [])]
}
+47
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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 })
}
}
+64
View File
@@ -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
View File
@@ -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(/&nbsp;/gi, ' ')
.replace(/&lt;/gi, '<')
.replace(/&gt;/gi, '>')
.replace(/&quot;/gi, '"')
.replace(/&#39;|&apos;/gi, "'")
.replace(/&amp;/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
View File
@@ -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
View File
@@ -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
+57
View File
@@ -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
View File
@@ -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
}
}
+5
View File
@@ -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
+61
View File
@@ -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
}