dsh-mailbox-local 0.0.0-stage → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,99 @@
1
- # Temporary Holding Version
1
+ # 同机信箱 · dsh-mailbox-local
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ 同一台机器上的两只 agent 互相留信、派活、回执——不靠人转手,也不靠复制粘贴。
4
+
5
+ > 一只鱼把活写成一封信,另一只在它自己的对话里收到一句提醒,点开就是全文;干完把信搬进 `done`,回执写回去。人是旁观者,不是中间人。
6
+
7
+ ## 它做的事
8
+
9
+ - **发信**:`mailbox_send` 给某条会话留一封(派活 / 留言 / 问一句),落成 `inbox/` 下的一个 `.md`
10
+ - **收信**:收件方在它自己的会话里收到一条 notice,正文是「谁给你留了一封信(派活):前 60 字」
11
+ - **抢锁**:处理前先 `mailbox_done`——用 `rename` 把信搬进 `done/`,两只同时点只有一个成功,谁搬走谁处理
12
+ - **过期**:超过 `expireHours`(默认 24)没人收,自动挪进 `expired/`
13
+ - **送达**:投不出去标 `undeliverable` 并每分钟重试,等那条会话开起来自动补投;投到了标 `delivered`
14
+ - **看板**:设置页里附一个只读的工单看板,把同一台机器上的活看见走到哪了
15
+
16
+ ## 装
17
+
18
+ ```
19
+ dsh plugin add dsh-mailbox-local
20
+ ```
21
+
22
+ 装完在 设置 → 信箱 里能看到「工单看板」一页;五个工具在工具列表里。
23
+
24
+ ## 五个工具
25
+
26
+ | 工具 | 干什么 |
27
+ | --- | --- |
28
+ | `mailbox_who` | 这台机器上还活着的会话(收件人按这些名字找) |
29
+ | `mailbox_send` | 给某条会话留一封信:`to`(会话名或 id)、`text`、`kind`(派活 / 留言 / 问一句)、`ref`(可选,附一个文件路径) |
30
+ | `mailbox_list` | 看信箱:默认只看发给我的,`box` 可看 `done` / `expired`,`all` 看全部 |
31
+ | `mailbox_read` | 读一封(`id` 可以只给前缀) |
32
+ | `mailbox_done` | 收下这封:搬进 `done/`,写 `status: done` 与 `doneAt` |
33
+
34
+ ## 配置
35
+
36
+ `cordis.patch.yml` 里这几项都能改,写空了就用默认值:
37
+
38
+ ```yaml
39
+ dir: "" # 信箱目录,默认 ~/.dsh/mailbox
40
+ ordersFile: "" # 工单看板那个 .md;不填就用 <dir>/工单看板.md
41
+ expireHours: 24 # 多久没人收就挪进 expired
42
+ scanSeconds: 20 # 多久扫一遍 inbox
43
+ notify: true # 收到新信要不要在对方会话里说一句
44
+ ```
45
+
46
+ **换机器不用改代码**:所有路径都在配置里。Windows / macOS / Linux 都能用,只依赖 Node 与 DSH 插件接口,不调 PowerShell、不写注册表。
47
+
48
+ ## 工单看板
49
+
50
+ 设置页那一页只读一个 markdown:表格里「状态」列是 `进行中 / 待办 / 搁置 / 已完成`,第一列后面跟回执、最近改动、文件名。每行末尾的「原文」按钮会打开那份 `.md` 的全文(只认同一目录下的文件,越界会被挡)。
51
+
52
+ 看板是谁生成都行:自己手写、脚本生成、或者抄一份模板。默认位置是 `<信箱目录>/工单看板.md`;想放别处就把 `ordersFile` 指过去。文件不存在时面板不会崩,只会告诉你它期望的位置。
53
+
54
+ ## 落盘长什么样
55
+
56
+ ```
57
+ ~/.dsh/mailbox/
58
+ inbox/
59
+ 20261127-062836-工作的鹿野__鹿野(主对话)-1941.md
60
+ done/
61
+ expired/
62
+ logs/ # 手动跑脚本时的输出(如果有)
63
+ ```
64
+
65
+ 一封信就是一个 markdown,头部是 front-matter:
66
+
67
+ ```markdown
68
+ ---
69
+ from: 工作的鹿野
70
+ to: 鹿野(主对话)
71
+ at: 2026-11-27T06:28:36+08:00
72
+ kind: note
73
+ ref: D:\dsh work\self\工作记录\工单-同机信箱.md
74
+ status: delivered
75
+ ---
76
+
77
+ 正文……
78
+ ```
79
+
80
+ `status` 会从 `delivered` → `done` 走;投不出去时是 `undeliverable`,并带一行 `note` 说明原因。
81
+
82
+ ## 和别的方案差在哪
83
+
84
+ - **不靠人转手**:不像复制粘贴,也不需要人在两个窗口之间搬。
85
+ - **会唤醒对方**:信投进去,对方那一轮就会被触发;邮件类插件不会。
86
+ - **谁先搬谁处理**:文件系统当锁,不需要额外的服务或数据库。
87
+ - **只管同机**:不做跨机器、不做群聊、不做实时。
88
+
89
+ ## 开发
90
+
91
+ ```
92
+ node --check index.js
93
+ node --check client.js
94
+ ELECTRON_RUN_AS_NODE=1 "D:\deepseek\DeepSeek Harness.exe" --test test/store.test.mjs
95
+ ```
96
+
97
+ 客户端改完要按界面的刷新按钮(或重启 DSH);宿主侧改完 disable → enable 一次。
98
+
99
+ MIT · 作者:鹿野
package/client.js ADDED
@@ -0,0 +1,241 @@
1
+ // 同机信箱 · 设置页:工单看板(只读)
2
+ // 看板由 toolkit/work-orders.mjs 生成;这里只读它,不写。
3
+ window.__ModuleLoader__.load({
4
+ id: 'dsh-mailbox-local',
5
+ factory(require) {
6
+ const React = require('react')
7
+ const h = React.createElement
8
+ const { useState, useEffect, useMemo } = React
9
+
10
+ const C = {
11
+ text: '#1c2430',
12
+ dim: '#6b7785',
13
+ line: '#e3e8ef',
14
+ accent: '#2563eb',
15
+ ok: '#0f9d58',
16
+ warn: '#b26a00',
17
+ bg: '#fff',
18
+ soft: '#f7f9fc',
19
+ }
20
+ const S = {
21
+ wrap: { display: 'flex', flexDirection: 'column', gap: 12, color: C.text, fontSize: 13, fontFamily: 'inherit' },
22
+ row: { display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap' },
23
+ card: { border: '1px solid ' + C.line, borderRadius: 10, padding: '12px 14px', background: C.bg },
24
+ chip: { display: 'inline-block', padding: '1px 8px', borderRadius: 999, background: C.soft, color: C.dim, fontSize: 11, border: '1px solid ' + C.line },
25
+ chipWarn: { display: 'inline-block', padding: '1px 8px', borderRadius: 999, background: '#fff4e5', color: C.warn, fontSize: 11, border: '1px solid #f0dcc0' },
26
+ chipOk: { display: 'inline-block', padding: '1px 8px', borderRadius: 999, background: '#eaf7ef', color: C.ok, fontSize: 11, border: '1px solid #cfe9d8' },
27
+ dim: { color: C.dim, fontSize: 12 },
28
+ btn: { padding: '4px 10px', borderRadius: 6, border: '1px solid ' + C.line, background: C.bg, color: C.text, fontSize: 12, cursor: 'pointer' },
29
+ btnTiny: { padding: '1px 7px', borderRadius: 5, border: '1px solid ' + C.line, background: C.bg, color: C.accent, fontSize: 11, cursor: 'pointer' },
30
+ }
31
+
32
+ const ts = (v) => (typeof v === 'number' ? v : Date.parse(String(v || '')) || 0)
33
+ const fmtTime = (ms) => {
34
+ if (!ms) return '—'
35
+ const d = new Date(ms)
36
+ const p = (n) => String(n).padStart(2, '0')
37
+ return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`
38
+ }
39
+
40
+ function statusChip(s) {
41
+ if (s === '进行中') return h('span', { style: S.chipWarn }, s)
42
+ if (s === '已完成') return h('span', { style: S.chipOk }, s)
43
+ return h('span', { style: S.chip }, s || '—')
44
+ }
45
+
46
+ function parseBoard(text) {
47
+ const rows = []
48
+ for (const line of String(text || '').split(/\r?\n/)) {
49
+ if (!line.startsWith('|')) continue
50
+ if (/^\|[\s:|-]+\|$/.test(line.replace(/ /g, ''))) continue
51
+ const cells = line.split('|').slice(1, -1).map((s) => s.trim().replace(/`/g, ''))
52
+ if (!cells.length) continue
53
+ if (cells[0] === '状态') continue
54
+ rows.push({ status: cells[0] || '', title: cells[1] || '', receipt: cells[2] || '', changed: cells[3] || '', file: cells[4] || '' })
55
+ }
56
+ return rows
57
+ }
58
+
59
+ function Orders() {
60
+ const [data, setData] = useState(null)
61
+ const [err, setErr] = useState('')
62
+ const [docView, setDocView] = useState(null)
63
+ const [cfgInfo, setCfgInfo] = useState(null)
64
+ const [pathInput, setPathInput] = useState('')
65
+ const [savingPath, setSavingPath] = useState(false)
66
+
67
+ const load = async () => {
68
+ try {
69
+ const r = await fetch('/dsh-mailbox.orders', { cache: 'no-store' })
70
+ const j = await r.json()
71
+ if (j && j.ok) setData(j)
72
+ else setErr(String((j && j.error) || '读取失败'))
73
+ } catch (e) {
74
+ setErr(String((e && e.message) || e))
75
+ }
76
+ }
77
+ const loadCfg = async () => {
78
+ try {
79
+ const r = await fetch('/dsh-mailbox.board', { cache: 'no-store' })
80
+ const j = await r.json()
81
+ if (j && j.ok) {
82
+ setCfgInfo(j)
83
+ setPathInput(j.source === 'override' ? j.override : '')
84
+ }
85
+ } catch {}
86
+ }
87
+ useEffect(() => {
88
+ load()
89
+ loadCfg()
90
+ }, [])
91
+
92
+ const savePath = async (value) => {
93
+ setSavingPath(true)
94
+ try {
95
+ const r = await fetch('/dsh-mailbox.board', {
96
+ method: 'POST',
97
+ headers: { 'content-type': 'application/json' },
98
+ body: JSON.stringify({ ordersFile: value }),
99
+ })
100
+ const j = await r.json()
101
+ if (j && j.ok) {
102
+ setErr('')
103
+ await loadCfg()
104
+ await load()
105
+ } else {
106
+ setErr(String((j && j.error) || '存不进去'))
107
+ }
108
+ } catch (e) {
109
+ setErr(String((e && e.message) || e))
110
+ } finally {
111
+ setSavingPath(false)
112
+ }
113
+ }
114
+
115
+ const openDoc = async (file) => {
116
+ if (!file) return
117
+ try {
118
+ const r = await fetch('/dsh-mailbox.order?file=' + encodeURIComponent(file), { cache: 'no-store' })
119
+ const j = await r.json()
120
+ if (j && j.ok) setDocView({ file, text: j.text })
121
+ else setErr(String((j && j.error) || '读不到原文'))
122
+ } catch (e) {
123
+ setErr(String((e && e.message) || e))
124
+ }
125
+ }
126
+
127
+ const c = (data && data.counts) || {}
128
+ const rows = data ? parseBoard(data.text) : []
129
+ const group = (s) => rows.filter((r) => r.status === s)
130
+
131
+ const table = (list, empty) =>
132
+ list.length
133
+ ? h('div', { style: { display: 'flex', flexDirection: 'column' } },
134
+ list.map((r) =>
135
+ h('div', { key: r.title + r.file, style: { padding: '7px 2px', borderBottom: '1px solid ' + C.line, display: 'flex', flexDirection: 'column', gap: 3 } },
136
+ h('div', { style: { display: 'flex', gap: 8, alignItems: 'baseline' } },
137
+ statusChip(r.status),
138
+ h('div', { style: { flex: 1, whiteSpace: 'normal', wordBreak: 'break-word', lineHeight: 1.5 } }, r.title),
139
+ ),
140
+ h('div', { style: { color: C.dim, fontSize: 11, display: 'flex', gap: 10, flexWrap: 'wrap', paddingLeft: 2, alignItems: 'baseline' } },
141
+ h('span', null, '改动 ' + ((r.changed || '').slice(0, 16) || '—')),
142
+ r.receipt ? h('span', null, '回执 ' + r.receipt) : null,
143
+ h('span', { style: { wordBreak: 'break-all' }, title: r.file }, r.file),
144
+ r.file ? h('button', { style: S.btnTiny, onClick: () => openDoc(r.file) }, '原文') : null,
145
+ ),
146
+ )),
147
+ )
148
+ : h('div', { style: S.dim }, empty)
149
+
150
+ const block = (label, list, empty) =>
151
+ h('div', { style: S.card },
152
+ h('div', { style: { ...S.dim, marginBottom: 6 } }, label + '(' + list.length + ')'),
153
+ table(list, empty),
154
+ )
155
+
156
+ return h('div', { style: S.wrap },
157
+ h('div', { style: S.row },
158
+ h('div', { style: { fontWeight: 600 } }, '工单看板'),
159
+ h('span', { style: S.chip }, '只读'),
160
+ h('div', { style: { flex: 1 } }),
161
+ h('button', { style: S.btn, onClick: load }, '刷新'),
162
+ ),
163
+ h('div', { style: { fontSize: 12, color: '#555', lineHeight: 1.7, marginBottom: 10 } },
164
+ '同一台机器上的两只 agent 互相留信的地方:一只把事写成信投进去,另一只在它那段对话里收到一句提醒,点开就是全文。谁先搬走那封信,谁负责回执——人不用在窗口之间来回搬运,也不用复制粘贴。',
165
+ ),
166
+ h('div', { style: { fontSize: 12, color: '#555', lineHeight: 1.7, marginBottom: 10 } },
167
+ '下面这块看板只读一个 markdown 表格:一行一件事,状态是进行中 / 待办 / 搁置 / 已完成,后面跟回执、最近改动和文件名。点每行右边「原文」能看那一份的全文。',
168
+ ),
169
+ h('div', { style: S.card },
170
+ h('div', { style: { ...S.dim, marginBottom: 6 } }, '看板文件'),
171
+ h('div', { style: { display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap' } },
172
+ h('code', { style: { fontSize: 11, color: C.dim, wordBreak: 'break-all', flex: 1, minWidth: 220 } }, (cfgInfo && cfgInfo.path) || '…'),
173
+ h('span', { style: S.chip },
174
+ cfgInfo && cfgInfo.source === 'override' ? '面板里改的' : cfgInfo && cfgInfo.source === 'config' ? '插件配置' : '默认位置'),
175
+ ),
176
+ h('div', { style: { display: 'flex', gap: 8, alignItems: 'center', marginTop: 8, flexWrap: 'wrap' } },
177
+ h('input', {
178
+ value: pathInput,
179
+ placeholder: (cfgInfo && cfgInfo.defaultPath) || '留空 = 默认位置',
180
+ onChange: (e) => setPathInput(e.target.value),
181
+ style: { flex: 1, minWidth: 240, padding: '4px 8px', border: '1px solid ' + C.line, borderRadius: 6, fontSize: 12, fontFamily: 'inherit' },
182
+ }),
183
+ h('button', { style: S.btn, disabled: savingPath, onClick: () => savePath(pathInput.trim()) }, savingPath ? '保存中…' : '保存'),
184
+ h('button', { style: S.btn, disabled: savingPath, onClick: () => savePath('') }, '恢复默认'),
185
+ ),
186
+ h('div', { style: { ...S.dim, marginTop: 6 } }, '填一个 .md 的完整路径;留空就用默认位置。改完立刻生效。'),
187
+ ),
188
+ data
189
+ ? h('div', { style: S.row },
190
+ h('span', { style: S.chipWarn }, '进行中 ' + (c.doing || 0)),
191
+ h('span', { style: S.chip }, '待办 ' + (c.todo || 0)),
192
+ h('span', { style: S.chipOk }, '已完成 ' + (c.done || 0)),
193
+ h('span', { style: S.dim }, '更新于 ' + fmtTime(data.at)),
194
+ )
195
+ : h('div', { style: S.dim }, '读取中…'),
196
+ err
197
+ ? h('div', { style: { color: '#c0392b', fontSize: 12, lineHeight: 1.6 } },
198
+ err,
199
+ data && data.file ? h('div', { style: { color: C.dim } }, '期望的位置:' + data.file) : null,
200
+ h('div', { style: { color: C.dim } }, '把 work-orders 生成的 markdown 放到上面这个位置,或在插件配置里把 ordersFile 指过去。'),
201
+ )
202
+ : null,
203
+ h('div', { style: { display: 'flex', flexDirection: 'column', gap: 10 } },
204
+ block('进行中', group('进行中'), '没有正在做的'),
205
+ block('待办', group('待办'), '没有待办的'),
206
+ block('搁置', group('搁置'), '没有搁置的'),
207
+ block('已完成', group('已完成'), '还没有完成的'),
208
+ ),
209
+ docView
210
+ ? h('div', { style: { position: 'fixed', inset: 0, zIndex: 9999, background: 'rgba(10,14,22,0.86)', display: 'flex', flexDirection: 'column', padding: 18, gap: 10 } },
211
+ h('div', { style: { display: 'flex', gap: 10, alignItems: 'center', color: '#cfd8e3', fontSize: 12 } },
212
+ h('span', { style: { flex: 1, wordBreak: 'break-all' } }, docView.file + '(Esc 或点「关闭」)'),
213
+ h('button', { style: S.btn, onClick: () => setDocView(null) }, '关闭'),
214
+ ),
215
+ h('pre', { style: { flex: 1, margin: 0, overflow: 'auto', background: '#0f1620', color: '#dbe4ee', border: '1px solid #2a3644', borderRadius: 6, padding: 12, fontSize: 12, whiteSpace: 'pre-wrap', wordBreak: 'break-word' } }, docView.text),
216
+ )
217
+ : null,
218
+ h('div', { style: S.dim }, '这个面板只读一个 markdown 看板:表格里「状态」那列是进行中 / 待办 / 搁置 / 已完成,一行一件事,后面跟回执、最近改动、文件名。谁生成、放在哪都能配——默认找信箱目录下的「工单看板.md」。'),
219
+ )
220
+ }
221
+
222
+ function Boundary() {
223
+ try {
224
+ return h(Orders)
225
+ } catch (e) {
226
+ return h('div', { style: { padding: 14, color: '#c0392b', fontSize: 12 } }, '工单看板出错了:' + String((e && e.message) || e))
227
+ }
228
+ }
229
+
230
+ return {
231
+ inject: ['slots'],
232
+ apply(ctx) {
233
+ const slots = (typeof ctx.get === 'function' ? ctx.get('slots') : undefined) || ctx.slots
234
+ if (!slots) return
235
+ slots.inject('settings.section', () =>
236
+ slots.register({ name: 'settings.section', id: 'dsh-mailbox-local', order: 70, label: '工单看板' }, () => h(Boundary)),
237
+ )
238
+ },
239
+ }
240
+ },
241
+ })
package/icon.svg ADDED
@@ -0,0 +1,8 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" width="40" height="40" viewBox="0 0 40 40" role="img" aria-label="信箱">
2
+ <rect x="0" y="0" width="40" height="40" rx="10" fill="#1d2f45"/>
3
+ <rect x="8" y="13" width="24" height="16" rx="2.5" fill="none" stroke="#7fd1ff" stroke-width="2"/>
4
+ <path d="M9 14.5 L20 22.5 L31 14.5" fill="none" stroke="#7fd1ff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
5
+ <rect x="12" y="9.5" width="13" height="8" rx="1.5" fill="#ff8fa3"/>
6
+ <rect x="14" y="12" width="9" height="1.4" rx="0.7" fill="#1d2f45" opacity="0.65"/>
7
+ <rect x="14" y="14.4" width="6" height="1.4" rx="0.7" fill="#1d2f45" opacity="0.45"/>
8
+ </svg>
package/index.js ADDED
@@ -0,0 +1,512 @@
1
+ // 同机信箱:两只鱼之间派活 / 回执,不靠人转手。
2
+ //
3
+ // · 信落在 <dir>/{inbox,done,expired},一条一个 .md
4
+ // · 收件人按「名字」找(会话标题),找不到再当会话 id
5
+ // · 每 scanSeconds 扫一遍:过期的挪走;新信给收件会话投一句 notice
6
+ // · 收信方用 mailbox_done 把信搬进 done —— rename 抢锁,谁先搬谁处理
7
+ import { join, dirname, resolve, basename } from 'node:path'
8
+ import {
9
+ readFile,
10
+ readdir,
11
+ stat,
12
+ mkdir,
13
+ writeFile,
14
+ } from 'node:fs/promises'
15
+ import * as store from './lib/store.js'
16
+ import { buildMessage, fallbackTextSummary } from './lib/message.js'
17
+
18
+ export const name = 'dsh-mailbox'
19
+ export const inject = ['tools', 'agents', 'sessions', 'webServer']
20
+
21
+ const DSH_HOME = process.env.DSH_HOME || join(process.env.USERPROFILE || process.env.HOME || '.', '.dsh')
22
+ const PROJ_DIR = join(DSH_HOME, 'storages', 'session_projcache', 'sessions')
23
+
24
+ const DEFAULTS = {
25
+ dir: '',
26
+ ordersFile: '',
27
+ expireHours: store.MAX_AGE_HOURS,
28
+ scanSeconds: 20,
29
+ notify: true,
30
+ }
31
+
32
+ function normaliseConfig(raw) {
33
+ const cfg = { ...DEFAULTS, ...(raw || {}) }
34
+ if (!cfg.dir) cfg.dir = join(DSH_HOME, 'mailbox')
35
+ cfg.expireHours = Math.max(1, Math.floor(Number(cfg.expireHours) || store.MAX_AGE_HOURS))
36
+ cfg.scanSeconds = Math.min(300, Math.max(5, Math.floor(Number(cfg.scanSeconds) || 20)))
37
+ cfg.notify = cfg.notify !== false
38
+ return cfg
39
+ }
40
+
41
+ const titleCache = new Map()
42
+
43
+ export async function sessionTitleOf(sessionId) {
44
+ if (!sessionId) return ''
45
+ if (titleCache.has(sessionId)) return titleCache.get(sessionId)
46
+ let title = ''
47
+ try {
48
+ const raw = await readFile(join(PROJ_DIR, `${sessionId}.json`), 'utf8')
49
+ const val = JSON.parse(raw)?.record?.rows?.title?.val
50
+ if (typeof val === 'string' && val.trim()) title = val.trim()
51
+ } catch {}
52
+ titleCache.set(sessionId, title)
53
+ return title
54
+ }
55
+
56
+ function liveAgents(ctx) {
57
+ try {
58
+ const arr = typeof ctx.agents?.list === 'function' ? ctx.agents.list() : []
59
+ return Array.from(arr || []).filter((a) => {
60
+ const origin = a?.session?.header?.origin
61
+ return origin !== 'subagent'
62
+ })
63
+ } catch {
64
+ return []
65
+ }
66
+ }
67
+
68
+ async function liveSessions(ctx) {
69
+ const out = []
70
+ const seen = new Set()
71
+ for (const agent of liveAgents(ctx)) {
72
+ const sid = agent?.session?.id || agent?.id
73
+ if (!sid || seen.has(sid)) continue
74
+ seen.add(sid)
75
+ const title = agent?.session?.header?.title || (await sessionTitleOf(sid)) || `会话 ${sid.slice(-8)}`
76
+ out.push({ sessionId: sid, title: String(title).trim(), agent })
77
+ }
78
+ return out
79
+ }
80
+
81
+ export async function resolveTarget(ctx, to) {
82
+ const want = String(to || '').trim()
83
+ if (!want) return { error: 'to 不能空' }
84
+ const sessions = await liveSessions(ctx)
85
+ const exactId = sessions.find((s) => s.sessionId === want)
86
+ if (exactId) return { target: exactId, by: 'id' }
87
+ const byName = sessions.find((s) => s.title === want)
88
+ if (byName) return { target: byName, by: 'name' }
89
+ const byPrefix = sessions.find((s) => s.title.startsWith(want) || s.sessionId.endsWith(want))
90
+ if (byPrefix) return { target: byPrefix, by: 'fuzzy' }
91
+ if (typeof ctx.agents?.get === 'function') {
92
+ try {
93
+ const agent = ctx.agents.get(want)
94
+ if (agent) {
95
+ const title = agent?.session?.header?.title || (await sessionTitleOf(want)) || `会话 ${want.slice(-8)}`
96
+ return { target: { sessionId: want, title, agent }, by: 'id' }
97
+ }
98
+ } catch {}
99
+ }
100
+ return { error: `找不到收件人:${want}(名字要对得上一条活着的会话,或直接给会话 id)` }
101
+ }
102
+
103
+ async function resolveAgentFor(ctx, sessionId) {
104
+ const direct = typeof ctx.agents?.get === 'function' ? ctx.agents.get(sessionId) : undefined
105
+ if (direct) return direct
106
+ if (typeof ctx.sessionController?.resolveAgent === 'function') {
107
+ const resolved = await ctx.sessionController.resolveAgent(sessionId)
108
+ if (resolved && !('error' in resolved)) return resolved.agent
109
+ }
110
+ return undefined
111
+ }
112
+
113
+ export async function deliver(ctx, sessionId, mail, log = () => {}) {
114
+ const agent = await resolveAgentFor(ctx, sessionId)
115
+ if (!agent) return { ok: false, error: `会话不在了:${sessionId}` }
116
+ const text = `${mail.from} 给你留了一封信${mail.kind === 'task' ? '(派活)' : ''}:${fallbackTextSummary(mail.body, 60)}`
117
+ const message = await buildMessage({
118
+ text,
119
+ summary: `同机信箱 · ${mail.from}${mail.kind === 'task' ? ' · 派活' : ''}`,
120
+ }, log)
121
+ try {
122
+ agent.followup(message)
123
+ const flushed = await ctx.sessions.flush(agent.session)
124
+ if (flushed === false) return { ok: false, error: 'flush 返回 false' }
125
+ return { ok: true }
126
+ } catch (error) {
127
+ return { ok: false, error: String(error?.message || error) }
128
+ }
129
+ }
130
+
131
+
132
+ // 默认看板:装好就有东西可看,而不是一片「读不到」。
133
+ const BOARD_TEMPLATE = [
134
+ '# 工单看板',
135
+ '',
136
+ '这个文件是信箱第一次运行时创建的。你可以随便改,也可以换生成方式——',
137
+ '只要还是个 markdown 表格,面板就认得。',
138
+ '',
139
+ '**第 1 列是状态**:\`进行中\` / \`待办\` / \`搁置\` / \`已完成\`。',
140
+ '**第 2 列是标题**,后面三列分别是回执、最近改动、文件名。',
141
+ '',
142
+ '| 状态 | 工单 | 回执 | 最近改动 | 文件 |',
143
+ '| --- | --- | --- | --- | --- |',
144
+ '| 待办 | 示例:把这件事写清楚,做完在工单末尾加「## 回执」 | — | — | 工单-示例.md |',
145
+ '',
146
+ ].join('\n')
147
+
148
+ async function ensureBoardFile(cfg, log) {
149
+ const override = await readBoardOverride(cfg)
150
+ if (String(cfg.ordersFile || '').trim() || override) return // 指定过路径就不去碰
151
+ const file = ordersPathOf(cfg)
152
+ try {
153
+ await stat(file)
154
+ return
155
+ } catch {}
156
+ try {
157
+ await mkdir(dirname(file), { recursive: true })
158
+ await writeFile(file, BOARD_TEMPLATE, 'utf8')
159
+ log('已创建工单看板:' + file)
160
+ } catch (e) {
161
+ log('建看板失败:' + String((e && e.message) || e))
162
+ }
163
+ }
164
+
165
+ // ---------- 工单看板(只读) ----------
166
+ // 跟着「信箱」走:信箱管派活与回执,这里看工单进度。与「脚本与计划」无关。
167
+ function sameSiteAuth(request) {
168
+ const headers = (request && request.headers) || {}
169
+ const host = String(headers.host || '').toLowerCase()
170
+ const origin = String(headers.origin || headers.referer || '').toLowerCase()
171
+ if (!origin) return 'anonymous'
172
+ if (origin === 'null') return 'deny'
173
+ try {
174
+ const o = new URL(origin)
175
+ if (host && o.host.toLowerCase() === host) return 'anonymous'
176
+ if (!host && (o.hostname === '127.0.0.1' || o.hostname === 'localhost')) return 'anonymous'
177
+ } catch {}
178
+ return 'deny'
179
+ }
180
+
181
+
182
+ // 面板里改路径时落在这里;优先级:运行时覆写 > 插件配置 ordersFile > 默认 <dir>/工单看板.md
183
+ function boardConfigPath(cfg) {
184
+ return join(cfg.dir, 'board.json')
185
+ }
186
+
187
+ async function readBoardOverride(cfg) {
188
+ try {
189
+ const raw = await readFile(boardConfigPath(cfg), 'utf8')
190
+ const j = JSON.parse(raw)
191
+ const v = String((j && j.ordersFile) || '').trim()
192
+ return v
193
+ } catch {
194
+ return ''
195
+ }
196
+ }
197
+
198
+ async function writeBoardOverride(cfg, value) {
199
+ const file = boardConfigPath(cfg)
200
+ await mkdir(dirname(file), { recursive: true })
201
+ await writeFile(file, JSON.stringify({ ordersFile: value }, null, 2) + '\n', 'utf8')
202
+ }
203
+
204
+ function resolveBoardPath(cfg, override) {
205
+ const v = String(override || '').trim()
206
+ if (v) return resolve(v)
207
+ const custom = String(cfg.ordersFile || '').trim()
208
+ if (custom) return resolve(custom)
209
+ return resolve(join(cfg.dir, '工单看板.md'))
210
+ }
211
+
212
+ function ordersPathOf(cfg, override = '') {
213
+ return resolveBoardPath(cfg, override)
214
+ }
215
+
216
+ function countBoard(text) {
217
+ const counts = { doing: 0, todo: 0, held: 0, done: 0 }
218
+ for (const line of String(text || '').split(/\r?\n/)) {
219
+ if (!line.startsWith('|')) continue
220
+ if (/^\|[\s:|-]+\|$/.test(line.replace(/ /g, ''))) continue
221
+ const first = String(line.split('|')[1] || '').trim().replace(/`/g, '')
222
+ if (first === '进行中') counts.doing++
223
+ else if (first === '待办') counts.todo++
224
+ else if (first === '搁置') counts.held++
225
+ else if (first === '已完成') counts.done++
226
+ }
227
+ return counts
228
+ }
229
+
230
+ function registerOrders(ctx, cfg, log) {
231
+ const send = (res, obj) => {
232
+ res.setHeader('content-type', 'application/json; charset=utf-8')
233
+ res.setHeader('cache-control', 'no-store')
234
+ res.end(JSON.stringify(obj))
235
+ }
236
+ ctx.effect(() =>
237
+ ctx.webServer.register({
238
+ auth: sameSiteAuth,
239
+ kind: 'exact',
240
+ path: '/dsh-mailbox.orders',
241
+ async handler(req, res) {
242
+ const file = ordersPathOf(cfg, await readBoardOverride(cfg))
243
+ try {
244
+ const st = await stat(file)
245
+ const text = await readFile(file, 'utf8')
246
+ return send(res, { ok: true, file, at: st.mtimeMs, counts: countBoard(text), text })
247
+ } catch (e) {
248
+ log('orders: ' + String((e && e.message) || e))
249
+ return send(res, { ok: false, error: '读不到工单看板:' + String((e && e.message) || e), file })
250
+ }
251
+ },
252
+ }),
253
+ )
254
+ ctx.effect(() =>
255
+ ctx.webServer.register({
256
+ auth: sameSiteAuth,
257
+ kind: 'exact',
258
+ path: '/dsh-mailbox.order',
259
+ async handler(req, res) {
260
+ const u = new URL(req.url || '/', 'http://localhost')
261
+ const name = String(u.searchParams.get('file') || '')
262
+ if (!name || basename(name) !== name || !/\.md$/i.test(name)) {
263
+ return send(res, { ok: false, error: '只认同目录下的 .md 文件名' })
264
+ }
265
+ const dir = dirname(ordersPathOf(cfg, await readBoardOverride(cfg)))
266
+ const full = join(dir, name)
267
+ try {
268
+ const st = await stat(full)
269
+ if (!st.isFile()) throw new Error('不是文件')
270
+ const text = await readFile(full, 'utf8')
271
+ return send(res, { ok: true, file: name, text })
272
+ } catch (e) {
273
+ return send(res, { ok: false, error: '读不到:' + String((e && e.message) || e), file: name })
274
+ }
275
+ },
276
+ }),
277
+ )
278
+ }
279
+
280
+
281
+ export function apply(ctx, rawConfig) {
282
+ const cfg = normaliseConfig(rawConfig)
283
+ const log = (line) => ctx.logger?.info?.(`[信箱] ${line}`)
284
+ let disposed = false
285
+ let timer = null
286
+ let busy = false
287
+ const notified = new Map()
288
+ const output = (schema) => ({
289
+ schema,
290
+ render: (_args, value) => [{ type: 'text', text: JSON.stringify(value, null, 2) }],
291
+ })
292
+
293
+ registerOrders(ctx, cfg, log)
294
+
295
+ async function readBody(req) {
296
+ const chunks = []
297
+ for await (const c of req) chunks.push(c)
298
+ const raw = Buffer.concat(chunks).toString('utf8')
299
+ try {
300
+ return JSON.parse(raw || '{}')
301
+ } catch {
302
+ return {}
303
+ }
304
+ }
305
+
306
+ ctx.effect(() =>
307
+ ctx.webServer.register({
308
+ auth: sameSiteAuth,
309
+ kind: 'exact',
310
+ path: '/dsh-mailbox.board',
311
+ async handler(req, res) {
312
+ const send = (obj) => {
313
+ res.setHeader('content-type', 'application/json; charset=utf-8')
314
+ res.setHeader('cache-control', 'no-store')
315
+ res.end(JSON.stringify(obj))
316
+ }
317
+ if (String(req.method || 'GET').toUpperCase() === 'POST') {
318
+ const body = await readBody(req)
319
+ const value = String(body && body.ordersFile !== undefined ? body.ordersFile : '').trim()
320
+ try {
321
+ await writeBoardOverride(cfg, value)
322
+ const path = ordersPathOf(cfg, value)
323
+ log('看板路径改为:' + (value || '(默认)'))
324
+ return send({ ok: true, path, source: value ? 'override' : (String(cfg.ordersFile || '').trim() ? 'config' : 'default') })
325
+ } catch (e) {
326
+ return send({ ok: false, error: '存不进去:' + String((e && e.message) || e) })
327
+ }
328
+ }
329
+ const override = await readBoardOverride(cfg)
330
+ const config = String(cfg.ordersFile || '').trim()
331
+ return send({
332
+ ok: true,
333
+ path: ordersPathOf(cfg, override),
334
+ defaultPath: resolve(join(cfg.dir, '工单看板.md')),
335
+ override,
336
+ config,
337
+ source: override ? 'override' : (config ? 'config' : 'default'),
338
+ })
339
+ },
340
+ }),
341
+ )
342
+
343
+
344
+ ensureBoardFile(cfg, log)
345
+
346
+ const dir = () => cfg.dir
347
+
348
+ async function selfName(exec) {
349
+ const sid = exec?.agent?.session?.id || exec?.agent?.id || ''
350
+ const title = exec?.agent?.session?.header?.title || (sid ? await sessionTitleOf(sid) : '')
351
+ return { sessionId: sid, name: String(title || (sid ? `会话 ${sid.slice(-8)}` : '匿名')).trim() }
352
+ }
353
+
354
+ /* ---------------- 定时扫 ---------------- */
355
+ async function scanOnce() {
356
+ if (busy || disposed) return
357
+ busy = true
358
+ try {
359
+ await store.sweepTmp(dir())
360
+ const expired = await store.expire({ hours: cfg.expireHours }, dir())
361
+ if (expired.moved.length) log(`过期 ${expired.moved.length} 封`)
362
+ if (!cfg.notify) return
363
+ const mails = await store.pending(dir())
364
+ const now = Date.now()
365
+ for (const mail of mails) {
366
+ if (disposed) return
367
+ // 已经投到对方会话的信不再重复喊(重启也不会重喊,靠文件头里的 status 判)
368
+ if (mail.status === 'delivered' || mail.status === 'done') { notified.set(mail.id, now); continue }
369
+ // 投不出去的信每分钟重试一次:同机的「找不到」多半是「那条会话还没开」
370
+ const last = notified.get(mail.id) || 0
371
+ if (now - last < 60 * 1000) continue
372
+ notified.set(mail.id, now)
373
+ const found = await resolveTarget(ctx, mail.to)
374
+ if (found.error) {
375
+ if (mail.status !== 'undeliverable') {
376
+ await store.setMeta(mail.id, { status: 'undeliverable', note: found.error }, dir()).catch(() => {})
377
+ log(`${mail.id} 暂时投不出去:${found.error}`)
378
+ }
379
+ continue
380
+ }
381
+ const sent = await deliver(ctx, found.target.sessionId, mail, log)
382
+ if (sent.ok) {
383
+ await store.setMeta(mail.id, { status: 'delivered', note: '' }, dir()).catch(() => {})
384
+ log(`投给 ${found.target.title}:${mail.from} → ${mail.to}`)
385
+ } else {
386
+ await store.setMeta(mail.id, { status: 'undeliverable', note: sent.error }, dir()).catch(() => {})
387
+ log(`投失败(${found.target.title}):${sent.error}`)
388
+ }
389
+ }
390
+ for (const [id, ts] of notified) if (now - ts > 3 * 3600 * 1000) notified.delete(id)
391
+ } catch (error) {
392
+ log(`扫描出错:${error?.message || error}`)
393
+ } finally {
394
+ busy = false
395
+ }
396
+ }
397
+
398
+ function schedule() {
399
+ if (disposed) return
400
+ timer = setTimeout(async () => {
401
+ timer = null
402
+ await scanOnce()
403
+ schedule()
404
+ }, cfg.scanSeconds * 1000)
405
+ timer.unref?.()
406
+ }
407
+
408
+ ctx.effect(() => {
409
+ store.ensure(dir()).then(() => scanOnce()).catch(() => {})
410
+ schedule()
411
+ return () => {
412
+ disposed = true
413
+ if (timer) clearTimeout(timer)
414
+ timer = null
415
+ }
416
+ })
417
+
418
+ /* ---------------- 工具 ---------------- */
419
+ ctx.effect(() => ctx.tools.register({
420
+ name: 'mailbox_send',
421
+ description: '给同机的另一只鱼留一封信(不用人转手)。to 写对方的会话名(如「主对话」「工作鱼」),或直接给会话 id;对方会话活着的话会立刻收到一句 notice。',
422
+ parameters: {
423
+ to: { type: 'string', description: '收件人:会话名或会话 id' },
424
+ text: { type: 'string', description: '正文(写清楚要对方做什么、要看哪个文件)' },
425
+ kind: { type: 'string', enum: ['task', 'note', 'question'], description: 'task=派活 note=留言 question=问一句' },
426
+ ref: { type: 'string', description: '可选:关联的工单/文件路径' },
427
+ },
428
+ output: output({ type: 'object', additionalProperties: true }),
429
+ async execute(args, exec) {
430
+ const me = await selfName(exec)
431
+ const to = String(args?.to || '').trim()
432
+ const found = await resolveTarget(ctx, to)
433
+ const sent = await store.send({
434
+ from: me.name,
435
+ to,
436
+ kind: args?.kind || 'note',
437
+ ref: args?.ref || '',
438
+ text: args?.text || '',
439
+ }, dir())
440
+ const result = { ...sent, from: me.name, to }
441
+ if (found.error) {
442
+ await store.setMeta(sent.id, { status: 'undeliverable', note: found.error }, dir()).catch(() => {})
443
+ result.warning = `${found.error};信已放在信箱里,等它出现再投。`
444
+ } else {
445
+ const delivered = await deliver(ctx, found.target.sessionId, { from: me.name, to, kind: args?.kind || 'note', body: args?.text || '' }, log)
446
+ result.delivered = delivered.ok
447
+ result.target = { sessionId: found.target.sessionId, title: found.target.title, by: found.by }
448
+ if (!delivered.ok) result.deliveryError = delivered.error
449
+ await store.setMeta(
450
+ sent.id,
451
+ delivered.ok ? { status: 'delivered' } : { status: 'undeliverable', note: delivered.error },
452
+ dir(),
453
+ ).catch(() => {})
454
+ notified.set(sent.id, Date.now())
455
+ }
456
+ return result
457
+ },
458
+ }))
459
+
460
+ ctx.effect(() => ctx.tools.register({
461
+ name: 'mailbox_list',
462
+ description: '看信箱里有什么。默认只列「发给我的」;给 box 看 done/expired,给 all:true 连别人的也列。',
463
+ parameters: {
464
+ box: { type: 'string', enum: ['inbox', 'done', 'expired'], description: '默认 inbox' },
465
+ all: { type: 'boolean', description: 'true = 连别人的信也列出来' },
466
+ },
467
+ output: output({ type: 'object', additionalProperties: true }),
468
+ async execute(args, exec) {
469
+ const me = await selfName(exec)
470
+ const res = await store.list({ to: args?.all ? '' : me.name, box: args?.box || 'inbox' }, dir())
471
+ return { ...res, me: me.name, items: res.items.map(({ body, ...rest }) => ({ ...rest, preview: fallbackTextSummary(body, 80) })) }
472
+ },
473
+ }))
474
+
475
+ ctx.effect(() => ctx.tools.register({
476
+ name: 'mailbox_read',
477
+ description: '读一封信的全文(id 可以只给前缀)。',
478
+ parameters: { id: { type: 'string', description: '信 id,或它的前缀' } },
479
+ output: output({ type: 'object', additionalProperties: true }),
480
+ async execute(args) {
481
+ return await store.read(args?.id, dir())
482
+ },
483
+ }))
484
+
485
+ ctx.effect(() => ctx.tools.register({
486
+ name: 'mailbox_done',
487
+ description: '收下这封信:搬进 done,表示「我来处理」。谁先搬谁处理,不会两边各做一遍。',
488
+ parameters: { id: { type: 'string', description: '信 id,或它的前缀' } },
489
+ output: output({ type: 'object', additionalProperties: true }),
490
+ async execute(args) {
491
+ const res = await store.done(args?.id, dir())
492
+ if (res.ok && res.moved) {
493
+ await store.setMeta(args?.id, { status: 'done', doneAt: store.stamp() }, dir()).catch(() => {})
494
+ }
495
+ return res
496
+ },
497
+ }))
498
+
499
+ ctx.effect(() => ctx.tools.register({
500
+ name: 'mailbox_who',
501
+ description: '看现在有哪些会话活着(能收信的名字),以及自己的名字。',
502
+ parameters: {},
503
+ output: output({ type: 'object', additionalProperties: true }),
504
+ async execute(_args, exec) {
505
+ const me = await selfName(exec)
506
+ const sessions = await liveSessions(ctx)
507
+ return { me: me.name, meId: me.sessionId, sessions: sessions.map(({ sessionId, title }) => ({ sessionId, title })) }
508
+ },
509
+ }))
510
+
511
+ log(`就位:${dir()}`)
512
+ }
package/lib/message.js ADDED
@@ -0,0 +1,62 @@
1
+ // 投递用的消息构造:优先用宿主自己的 createUserMessage,拿不到就用等价对象。
2
+ // (跟心跳插件同一套路:profile 里没有 @deepseek-ai/dsh-llm,只能从宿主树里找。)
3
+ import { randomUUID } from 'node:crypto'
4
+ import { pathToFileURL } from 'node:url'
5
+ import { join } from 'node:path'
6
+
7
+ let cached = null
8
+ let tried = false
9
+
10
+ const CANDIDATES = () => {
11
+ const list = []
12
+ const res = process.resourcesPath
13
+ if (res) list.push(join(res, 'app.asar', 'dsh', 'node_modules', '@deepseek-ai', 'dsh-llm', 'lib', 'index.js'))
14
+ const appData = process.env.APPDATA
15
+ if (appData) list.push(join(appData, 'npm', 'node_modules', '@deepseek-ai', 'dsh-llm', 'lib', 'index.js'))
16
+ const home = process.env.DSH_HOME || join(process.env.USERPROFILE || process.env.HOME || '.', '.dsh')
17
+ list.push(join(home, 'profiles', 'desktop', 'node_modules', '@deepseek-ai', 'dsh-llm', 'lib', 'index.js'))
18
+ return list
19
+ }
20
+
21
+ export function fallbackTextSummary(text, max = 120) {
22
+ const flat = String(text || '').replace(/\s+/g, ' ').trim()
23
+ return flat.length <= max ? flat : flat.slice(0, max - 1) + '…'
24
+ }
25
+
26
+ export async function loadCreateUserMessage(log = () => {}) {
27
+ if (tried) return cached
28
+ tried = true
29
+ for (const p of CANDIDATES()) {
30
+ try {
31
+ const mod = await import(pathToFileURL(p).href)
32
+ const fn = mod?.createUserMessage
33
+ if (typeof fn === 'function') { cached = fn; return cached }
34
+ } catch {}
35
+ }
36
+ log('信箱:没找到宿主的 createUserMessage,用本地等价实现')
37
+ cached = null
38
+ return cached
39
+ }
40
+
41
+ export function fallback(input) {
42
+ const content = Array.isArray(input?.content)
43
+ ? input.content
44
+ : [{ type: 'text', text: String(input?.text || '') }]
45
+ return {
46
+ id: randomUUID(),
47
+ role: 'user',
48
+ content,
49
+ source: input?.source || { kind: 'mailbox', form: 'notice', summary: '' },
50
+ }
51
+ }
52
+
53
+ export async function buildMessage({ text, summary }, log) {
54
+ const create = await loadCreateUserMessage(log)
55
+ const source = { kind: 'mailbox', form: 'notice', summary: summary || fallbackTextSummary(text) }
56
+ if (typeof create === 'function') {
57
+ try {
58
+ return create({ content: [{ type: 'text', text }], source })
59
+ } catch {}
60
+ }
61
+ return fallback({ content: [{ type: 'text', text }], source })
62
+ }
package/lib/store.js ADDED
@@ -0,0 +1,205 @@
1
+ // 信箱的存储层:跟 toolkit/mailbox.mjs 同一套格式,插件自带一份,不跨目录依赖。
2
+ import { readdir, readFile, writeFile, rename, mkdir, stat, unlink } from 'node:fs/promises'
3
+ import { join } from 'node:path'
4
+ import { randomBytes } from 'node:crypto'
5
+
6
+ export const MAX_AGE_HOURS = 24
7
+
8
+ export const dirOf = (root) => ({
9
+ root,
10
+ inbox: join(root, 'inbox'),
11
+ done: join(root, 'done'),
12
+ expired: join(root, 'expired'),
13
+ })
14
+
15
+ const pad = (n) => String(n).padStart(2, '0')
16
+
17
+ export function stamp(ms = Date.now()) {
18
+ const d = new Date(ms)
19
+ const off = -d.getTimezoneOffset()
20
+ const sign = off >= 0 ? '+' : '-'
21
+ return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}${sign}${pad(Math.floor(Math.abs(off) / 60))}:${pad(Math.abs(off) % 60)}`
22
+ }
23
+
24
+ const clean = (s, max = 40) => String(s || '').replace(/[\\/:*?"<>|\r\n]/g, '_').trim().slice(0, max) || '匿名'
25
+
26
+ export function fileNameOf(from, to, ms = Date.now()) {
27
+ const d = new Date(ms)
28
+ const ts = `${d.getFullYear()}${pad(d.getMonth() + 1)}${pad(d.getDate())}-${pad(d.getHours())}${pad(d.getMinutes())}${pad(d.getSeconds())}`
29
+ return `${ts}-${clean(from)}__${clean(to)}-${randomBytes(2).toString('hex')}.md`
30
+ }
31
+
32
+ export function render(msg) {
33
+ const head = ['---', `from: ${msg.from}`, `to: ${msg.to}`, `at: ${msg.at}`, `kind: ${msg.kind || 'note'}`]
34
+ if (msg.ref) head.push(`ref: ${String(msg.ref).replace(/\r?\n/g, ' ')}`)
35
+ head.push('status: new', '---', '')
36
+ return head.join('\n') + String(msg.text || '').trimEnd() + '\n'
37
+ }
38
+
39
+ export function parse(raw, name = '') {
40
+ const text = String(raw || '')
41
+ const m = text.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?/)
42
+ if (!m) return { name, id: name.replace(/\.md$/, ''), from: '', to: '', at: '', kind: 'note', ref: '', status: 'new', body: text.trim() }
43
+ const meta = {}
44
+ for (const line of m[1].split(/\r?\n/)) {
45
+ const i = line.indexOf(':')
46
+ if (i > 0) meta[line.slice(0, i).trim()] = line.slice(i + 1).trim()
47
+ }
48
+ return {
49
+ name,
50
+ id: name.replace(/\.md$/, ''),
51
+ from: meta.from || '',
52
+ to: meta.to || '',
53
+ at: meta.at || '',
54
+ kind: meta.kind || 'note',
55
+ ref: meta.ref || '',
56
+ status: meta.status || 'new',
57
+ note: meta.note || '',
58
+ doneAt: meta.doneAt || '',
59
+ body: text.slice(m[0].length).trim(),
60
+ }
61
+ }
62
+
63
+ const HEAD_ORDER = ['from', 'to', 'at', 'kind', 'ref', 'status', 'note', 'doneAt']
64
+
65
+ /** 改文件头(送达状态、处理时间)。只动 front-matter,正文一个字不改。 */
66
+ export async function setMeta(id, patch = {}, root) {
67
+ const f = await find(id, root)
68
+ const raw = await readFile(f.path, 'utf8')
69
+ const msg = parse(raw, f.name)
70
+ const meta = {
71
+ from: msg.from,
72
+ to: msg.to,
73
+ at: msg.at,
74
+ kind: msg.kind,
75
+ ref: msg.ref,
76
+ status: msg.status,
77
+ ...(msg.note ? { note: msg.note } : {}),
78
+ ...(msg.doneAt ? { doneAt: msg.doneAt } : {}),
79
+ ...patch,
80
+ }
81
+ const one = (v) => String(v).replace(/\r?\n/g, ' ').trim()
82
+ const head = ['---']
83
+ for (const k of HEAD_ORDER) {
84
+ if (meta[k] !== undefined && meta[k] !== '') head.push(`${k}: ${one(meta[k])}`)
85
+ }
86
+ for (const [k, v] of Object.entries(meta)) {
87
+ if (HEAD_ORDER.includes(k)) continue
88
+ if (v === undefined || v === '') continue
89
+ head.push(`${k}: ${one(v)}`)
90
+ }
91
+ head.push('---', '')
92
+ const out = head.join('\n') + msg.body + '\n'
93
+ const tmp = f.path + '.tmp'
94
+ await writeFile(tmp, out, 'utf8')
95
+ await rename(tmp, f.path)
96
+ return { ok: true, id: msg.id, status: meta.status || '', path: f.path }
97
+ }
98
+
99
+ export async function ensure(root) {
100
+ const d = dirOf(root)
101
+ for (const p of [d.inbox, d.done, d.expired]) await mkdir(p, { recursive: true })
102
+ return d
103
+ }
104
+
105
+ export async function send({ from, to, kind = 'note', ref = '', text = '' }, root) {
106
+ const f = String(from || '').trim()
107
+ const t = String(to || '').trim()
108
+ if (!f) throw new Error('要写 from(谁发的)')
109
+ if (!t) throw new Error('要写 to(发给谁)')
110
+ if (!String(text).trim()) throw new Error('正文不能为空')
111
+ const d = await ensure(root)
112
+ const at = stamp()
113
+ const name = fileNameOf(f, t)
114
+ const p = join(d.inbox, name)
115
+ const tmp = p + '.tmp'
116
+ await writeFile(tmp, render({ from: f, to: t, at, kind, ref, text }), 'utf8')
117
+ await rename(tmp, p)
118
+ return { ok: true, path: p, id: name.replace(/\.md$/, ''), at }
119
+ }
120
+
121
+ async function readDir(folder) {
122
+ let names = []
123
+ try { names = await readdir(folder) } catch { return [] }
124
+ const out = []
125
+ for (const n of names.filter((x) => x.endsWith('.md'))) {
126
+ try { out.push(parse(await readFile(join(folder, n), 'utf8'), n)) } catch {}
127
+ }
128
+ return out.sort((a, b) => String(b.at).localeCompare(String(a.at)))
129
+ }
130
+
131
+ export async function list({ to = '', from = '', box = 'inbox' } = {}, root) {
132
+ const d = dirOf(root)
133
+ const folder = box === 'done' ? d.done : box === 'expired' ? d.expired : d.inbox
134
+ const all = await readDir(folder)
135
+ const wantTo = String(to || '').trim()
136
+ const wantFrom = String(from || '').trim()
137
+ let items = all
138
+ if (wantTo) items = items.filter((m) => m.to === wantTo)
139
+ if (wantFrom) items = items.filter((m) => m.from === wantFrom)
140
+ return { ok: true, box, folder, count: items.length, items }
141
+ }
142
+
143
+ export async function find(id, root) {
144
+ const d = dirOf(root)
145
+ const key = String(id || '').replace(/\.md$/, '').trim()
146
+ if (!key) throw new Error('要一个 id')
147
+ for (const folder of [d.inbox, d.done, d.expired]) {
148
+ let names = []
149
+ try { names = await readdir(folder) } catch {}
150
+ const hit = names.find((n) => n === key + '.md') || names.find((n) => n.startsWith(key))
151
+ if (hit) return { folder, name: hit, path: join(folder, hit), msg: parse(await readFile(join(folder, hit), 'utf8'), hit) }
152
+ }
153
+ throw new Error(`没有这封信:${key}`)
154
+ }
155
+
156
+ export async function read(id, root) {
157
+ const d = dirOf(root)
158
+ const f = await find(id, root)
159
+ const box = f.folder === d.done ? 'done' : f.folder === d.expired ? 'expired' : 'inbox'
160
+ return { ok: true, box, ...f.msg }
161
+ }
162
+
163
+ export async function done(id, root) {
164
+ const f = await find(id, root)
165
+ const d = dirOf(root)
166
+ if (f.folder !== d.inbox) return { ok: true, moved: false, box: f.folder === d.done ? 'done' : 'expired', name: f.name }
167
+ const target = join(d.done, f.name)
168
+ try { await rename(f.path, target) } catch (error) { return { ok: false, error: String(error?.message || error) } }
169
+ return { ok: true, moved: true, name: f.name, path: target }
170
+ }
171
+
172
+ export async function expire({ hours = MAX_AGE_HOURS } = {}, root) {
173
+ const d = await ensure(root)
174
+ let names = []
175
+ try { names = await readdir(d.inbox) } catch { return { ok: true, moved: [] } }
176
+ const moved = []
177
+ const cutoff = Date.now() - hours * 3600 * 1000
178
+ for (const n of names.filter((x) => x.endsWith('.md'))) {
179
+ const p = join(d.inbox, n)
180
+ try {
181
+ const info = await stat(p)
182
+ if (info.mtimeMs < cutoff) { await rename(p, join(d.expired, n)); moved.push(n) }
183
+ } catch {}
184
+ }
185
+ return { ok: true, moved }
186
+ }
187
+
188
+ export async function sweepTmp(root) {
189
+ const d = dirOf(root)
190
+ const gone = []
191
+ for (const folder of [d.inbox, d.done, d.expired]) {
192
+ let names = []
193
+ try { names = await readdir(folder) } catch { continue }
194
+ for (const n of names.filter((x) => x.endsWith('.tmp'))) {
195
+ try { await unlink(join(folder, n)); gone.push(n) } catch {}
196
+ }
197
+ }
198
+ return gone
199
+ }
200
+
201
+ /** 还没收下的信(给「到点扫一遍」用) */
202
+ export async function pending(root) {
203
+ const d = dirOf(root)
204
+ return readDir(d.inbox)
205
+ }
package/locale/en.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Same-machine mailbox",
4
+ "description": "Where two agents on the same machine leave each other letters: one writes down a job, the other gets a one-line notice inside its own conversation and opens the full text; whoever moves the letter first owns the reply. No copy-paste, no human in the middle. The panel also shows a read-only work-order board."
5
+ }
6
+ }
package/locale/zh.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "同机信箱",
4
+ "description": "同一台机器上的两只 agent 互相留信的地方:一只写好一件事,另一只在自己那段对话里收到一句提醒,点开就是全文;谁先搬走那封信,谁负责回执。人不用在窗口之间来回搬运,也不用复制粘贴。面板里还有一块工单看板,能看见这些事走到了哪一步。"
5
+ }
6
+ }
package/package.json CHANGED
@@ -1,6 +1,53 @@
1
1
  {
2
2
  "name": "dsh-mailbox-local",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.3.0",
4
+ "description": "同机信箱:同一台机器上的两只 agent 互相留信、派活、回执,不靠人转手;附一个只读的工单看板。Mailbox for agents on one machine, plus a read-only work-order board.",
5
+ "type": "module",
6
+ "main": "index.js",
7
+ "exports": {
8
+ ".": "./index.js",
9
+ "./client": "./client.js",
10
+ "./icon": "./icon.svg",
11
+ "./locale/*.json": "./locale/*.json"
12
+ },
13
+ "files": [
14
+ "index.js",
15
+ "client.js",
16
+ "icon.svg",
17
+ "lib",
18
+ "locale/*.json",
19
+ "README.md"
20
+ ],
21
+ "engines": {
22
+ "dsh": ">=0.2.3-alpha.0 <0.4.0-0"
23
+ },
24
+ "keywords": [
25
+ "dsh-plugin",
26
+ "deepseek-harness",
27
+ "mailbox",
28
+ "agent",
29
+ "handoff",
30
+ "work-orders",
31
+ "task-board"
32
+ ],
33
+ "author": "鹿野 <luye@dsh.local>",
34
+ "license": "MIT",
35
+ "homepage": "https://github.com/heiyedehen/dsh-mailbox-local",
36
+ "repository": {
37
+ "type": "git",
38
+ "url": "git+https://github.com/heiyedehen/dsh-mailbox-local.git"
39
+ },
40
+ "dsh": {
41
+ "bundle": {
42
+ "patch": "./cordis.patch.yml"
43
+ },
44
+ "client": {
45
+ "platform": "web",
46
+ "inject": [
47
+ "@deepseek-ai/dsh-client-runtime",
48
+ "@deepseek-ai/dsh-client-ui-slots",
49
+ "@deepseek-ai/dsh-client-ui-primitives"
50
+ ]
51
+ }
52
+ }
53
+ }