dsh-collab-pair 1.2.3 → 1.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
@@ -56,13 +56,50 @@ Once a round is dispatched, the worker finishing wakes the manager automatically
56
56
 
57
57
  Set `autoNudge: false` to disable reminders.
58
58
 
59
+ ## Cross-device collaboration
60
+
61
+ DSH is local-first: the signed-in account identifies devices but does not relay messages between them, so the plugin ships a tiny relay hub and connects **out** to it. That works across networks with a tunnel, and no inbound port is needed on worker devices.
62
+
63
+ On one machine or a small VPS (the hub keeps recent messages in memory only):
64
+
65
+ ```bash
66
+ node node_modules/dsh-collab-pair/hub.js --port 8787 --token <long-random-secret>
67
+ # expose it with HTTPS, e.g.
68
+ cloudflared tunnel --url http://127.0.0.1:8787
69
+ ```
70
+
71
+ On **both** devices, set the same `hubUrl`, `hubToken` and `hubRoom`, and a distinct `deviceName`:
72
+
73
+ ```yaml
74
+ hubUrl: https://your-tunnel.example
75
+ hubRoom: my-project
76
+ hubToken: <the same secret>
77
+ deviceName: desktop # or laptop
78
+ ```
79
+
80
+ On the worker device, in the conversation that should work remotely:
81
+
82
+ ```text
83
+ collab_remote({ action: "alias", alias: "frontend" })
84
+ ```
85
+
86
+ On the manager device:
87
+
88
+ ```text
89
+ collab_remote({ action: "link", device: "laptop", worker: "frontend", name: "前端" })
90
+ collab_dispatch({ worker: "前端", task: "…" })
91
+ ```
92
+
93
+ The manager dispatches through the hub; the worker device prompts its local conversation, captures the final reply at turn end, and sends it back. `collab_done` / `collab_unlink` notify the remote device as well.
94
+
95
+ Security: the token is a shared secret for the room; anyone holding it can deliver prompts to devices in that room. Use a long random token, HTTPS (a tunnel), and a dedicated room. The hub keeps messages in memory only (15 minutes, 1000 per room) and is not a durable queue.
96
+
59
97
  ## Projects
60
98
 
61
99
  A project is the set of workers managed by one project-manager conversation. Different managers are different projects, so nothing mixes:
62
100
 
63
101
  - On the first link the project name defaults to the manager conversation title (role prefix removed).
64
- - Rename it in the manager card or with `collab_project({ name })` / `/collab project {"name":"…"}
65
- /collab create {"name":"前端","preset":"standard"}`; every worker of that manager follows the project.
102
+ - Rename it in the manager card or with `collab_project({ name })` / `/collab project {"name":"…"}`; every worker of that manager follows the project.
66
103
  - The board groups tasks by project (project name + manager).
67
104
  - A worker belongs to exactly one project at a time; unlink it before linking it to another manager.
68
105
 
@@ -107,6 +144,7 @@ For an existing conversation, call `collab_sessions` to get its id, then `collab
107
144
  | `collab_sessions` | anyone | List recent conversations (id / title / activity / link state) |
108
145
  | `collab_link` | anyone | Link a worker; `role=worker` makes the current conversation the worker; `peer="new"` creates one; `mode` picks temporary/permanent; `project` names the project |
109
146
  | `collab_worker_create` | manager | Create a new worker conversation (name, preset/model), linked automatically; can dispatch the first round |
147
+ | `collab_remote` | anyone | Cross-device: `alias` registers this conversation on the worker device; `link` binds a remote device/alias on the manager device |
110
148
  | `collab_dispatch` | manager | Dispatch one round; `worker` selects the worker (optional with a single worker), `acceptance` optional |
111
149
  | `collab_report` | worker | Report `summary` / `status`(done\|partial\|blocked) / `details` / `next` |
112
150
  | `collab_status` | anyone | A manager sees every worker's progress; a worker sees its manager and pending task |
@@ -127,6 +165,7 @@ The settings page uses it; it can also be typed manually:
127
165
  /collab link {"peer":"session-…"}
128
166
  /collab project {"name":"…"}
129
167
  /collab create {"name":"前端","preset":"standard"}
168
+ /collab remote {"action":"link","device":"laptop","worker":"frontend"}
130
169
  /collab configure {"worker":"session-…","preset":"ptc"}
131
170
  /collab configure {"worker":"session-…","provider":"deepseek-account","model":"deepseek-flash"}
132
171
  /collab dispatch {"worker":"session-…","task":"…","acceptance":"…"}
@@ -155,6 +194,10 @@ The `collab-pair` row in `cordis.patch.yml`:
155
194
  autoNudge: true # wake an idle manager when a worker stalls
156
195
  nudgeAfterMinutes: 20 # minutes of no progress before a reminder
157
196
  maxNudges: 3 # reminders per link before leaving it to a human
197
+ hubUrl: '' # relay base URL; empty = local-only
198
+ hubRoom: 'default'
199
+ hubToken: ''
200
+ deviceName: '' # defaults to the host name
158
201
  addPrefix: true # add the title prefix to linked conversations
159
202
  prefixManager: '【项目经理】'
160
203
  prefixWorker: '【员工】'
@@ -169,6 +212,7 @@ One record per worker lives in `$DSH_HOME/storages/collab_pair.json` (storage-do
169
212
  - A worker conversation belongs to one collaboration at a time; a manager can own several workers.
170
213
  - Rounds are unlimited by default (`maxRounds: 0`); set a positive number to cap each worker.
171
214
  - A conversation cannot be both manager and worker.
215
+ - Cross-device runs require `hubUrl` + `hubToken` on both devices (the signed-in account is not a message relay).
172
216
  - Worker conversations need a configured model (new conversations inherit the deployment default).
173
217
  - Relayed results arrive as user messages in the manager conversation, with a report header and round marker. The generated text follows `language`; tool descriptions and internal error messages are Chinese in this release.
174
218
  - With a PTC preset the worker calls `collab_report` inside `run_code`; the plugin still reads the structured report.
@@ -231,13 +275,50 @@ dsh plugin add dsh-collab-pair
231
275
 
232
276
  不需要提醒时设 `autoNudge: false`。
233
277
 
278
+ ## 跨设备协作
279
+
280
+ DSH 是本地优先的:登录账号只用来识别设备,并不会在设备之间转发消息。所以插件自带一个很小的中继 hub,各设备**向外连接**它。配合内网穿透即可跨网络使用,员工设备不需要开放入站端口。
281
+
282
+ 在一台机器或小 VPS 上启动 hub(消息只存内存):
283
+
284
+ ```bash
285
+ node node_modules/dsh-collab-pair/hub.js --port 8787 --token <足够长的随机密钥>
286
+ # 再用 HTTPS 暴露,例如
287
+ cloudflared tunnel --url http://127.0.0.1:8787
288
+ ```
289
+
290
+ **两台设备**都配置相同的 `hubUrl`、`hubToken`、`hubRoom`,以及不同的 `deviceName`:
291
+
292
+ ```yaml
293
+ hubUrl: https://your-tunnel.example
294
+ hubRoom: my-project
295
+ hubToken: <同一个密钥>
296
+ deviceName: desktop # 另一台写 laptop
297
+ ```
298
+
299
+ 员工设备上,在要远程工作的对话里:
300
+
301
+ ```text
302
+ collab_remote({ action: "alias", alias: "frontend" })
303
+ ```
304
+
305
+ 项目经理设备上:
306
+
307
+ ```text
308
+ collab_remote({ action: "link", device: "laptop", worker: "frontend", name: "前端" })
309
+ collab_dispatch({ worker: "前端", task: "…" })
310
+ ```
311
+
312
+ 经理通过 hub 派发;员工设备在本机对话里执行,回合结束时抓取最终回复并发回。`collab_done` / `collab_unlink` 也会通知远端设备。
313
+
314
+ 安全:token 是整个房间的共享密钥,持有它的人可以向该房间的设备投递提示词。请用足够长的随机 token、HTTPS(隧道)和专用房间。hub 只在内存里保留 15 分钟 / 每房间最多 1000 条消息,不是持久队列。
315
+
234
316
  ## 项目
235
317
 
236
318
  一个项目就是「一个项目经理对话所管理的员工集合」。不同项目经理就是不同项目,互不混淆:
237
319
 
238
320
  - 第一次关联时,项目名默认取项目经理对话的标题(去掉角色前缀)。
239
- - 可在项目经理卡片里改名,或用 `collab_project({ name })` / `/collab project {"name":"…"}
240
- /collab create {"name":"前端","preset":"standard"}`;该经理的所有员工会一起归到新项目名。
321
+ - 可在项目经理卡片里改名,或用 `collab_project({ name })` / `/collab project {"name":"…"}`;该经理的所有员工会一起归到新项目名。
241
322
  - 看板按项目分组(项目名 + 项目经理)。
242
323
  - 一个员工同一时间只属于一个项目;要换项目经理,先解除原关联。
243
324
 
@@ -278,6 +359,7 @@ dsh plugin add dsh-collab-pair
278
359
  | `collab_sessions` | 任何人 | 列出最近对话(id / 标题 / 活跃 / 是否已关联) |
279
360
  | `collab_link` | 任何人 | 关联员工;`role=worker` 表示当前对话成为对方的员工;`peer="new"` 新建;`mode` 选临时/永久;`project` 指定项目名 |
280
361
  | `collab_worker_create` | 项目经理 | 新建员工对话(可命名、设预设/模型),默认自动关联,可顺便派发第一轮 |
362
+ | `collab_remote` | 任何人 | 跨设备:员工设备用 `alias` 注册对话;经理设备用 `link` 绑定远端设备/别名 |
281
363
  | `collab_dispatch` | 项目经理 | 派发一轮;`worker` 指定员工(只有一个时可省略),`acceptance` 可选 |
282
364
  | `collab_report` | 员工 | 汇报 `summary` / `status`(done\|partial\|blocked) / `details` / `next` |
283
365
  | `collab_status` | 任何人 | 经理看所有员工进度;员工看自己的经理与待办 |
@@ -298,6 +380,7 @@ dsh plugin add dsh-collab-pair
298
380
  /collab link {"peer":"session-…"}
299
381
  /collab project {"name":"…"}
300
382
  /collab create {"name":"前端","preset":"standard"}
383
+ /collab remote {"action":"link","device":"laptop","worker":"frontend"}
301
384
  /collab configure {"worker":"session-…","preset":"ptc"}
302
385
  /collab configure {"worker":"session-…","provider":"deepseek-account","model":"deepseek-flash"}
303
386
  /collab dispatch {"worker":"session-…","task":"…","acceptance":"…"}
@@ -326,6 +409,10 @@ dsh plugin add dsh-collab-pair
326
409
  autoNudge: true # 员工停滞时唤醒空闲的项目经理
327
410
  nudgeAfterMinutes: 20 # 多久无推进后提醒(分钟)
328
411
  maxNudges: 3 # 每条关联最多提醒几次
412
+ hubUrl: '' # 中继地址;留空 = 只用本机
413
+ hubRoom: 'default'
414
+ hubToken: ''
415
+ deviceName: '' # 默认取主机名
329
416
  addPrefix: true # 是否给关联对话加标题前缀
330
417
  prefixManager: '【项目经理】'
331
418
  prefixWorker: '【员工】'
@@ -340,6 +427,7 @@ dsh plugin add dsh-collab-pair
340
427
  - 员工对话同时只能属于一个协作;项目经理可以关联多个员工。
341
428
  - 默认不限制轮次(`maxRounds: 0`);填正数才会给每个员工设上限。
342
429
  - 一个对话不能同时是项目经理和员工。
430
+ - 跨设备需要两台设备都配置 `hubUrl` + `hubToken`(登录账号本身不转发消息)。
343
431
  - 员工对话需要已配置模型(新建对话继承部署默认模型)。
344
432
  - 回传以用户消息形式进入项目经理对话(带【协作回报】标题与轮次标记)。生成文本跟随 `language`;工具描述与内部错误信息本版本仍为中文。
345
433
  - 员工用 PTC 预设时 `collab_report` 会在 `run_code` 里调用,插件仍能读到结构化汇报。
package/client.js CHANGED
@@ -1,5 +1,5 @@
1
1
  window.__ModuleLoader__.load({
2
- id: '@local/collab-pair',
2
+ id: 'dsh-collab-pair',
3
3
  factory(require) {
4
4
  const React = require('react')
5
5
  const h = React.createElement
@@ -34,6 +34,7 @@ window.__ModuleLoader__.load({
34
34
  modeTempShort: '临时',
35
35
  modePermShort: '永久',
36
36
  projectLabel: '项目',
37
+ remoteLabel: '远程',
37
38
  projectUnnamed: '未命名项目',
38
39
  projectSave: '保存项目名',
39
40
  projectSaved: '项目名已更新',
@@ -96,6 +97,7 @@ window.__ModuleLoader__.load({
96
97
  modeTempShort: 'Temporary',
97
98
  modePermShort: 'Permanent',
98
99
  projectLabel: 'Project',
100
+ remoteLabel: 'remote',
99
101
  projectUnnamed: 'Unnamed project',
100
102
  projectSave: 'Save project name',
101
103
  projectSaved: 'Project name updated',
@@ -420,7 +422,7 @@ window.__ModuleLoader__.load({
420
422
  h('div', { style: S.taskTitle }, link.workerTitle || link.worker),
421
423
  h('div', { style: S.mono }, link.worker),
422
424
  h('div', { style: S.muted },
423
- `${link.managerTitle || link.manager} · ${roundText(link)}${reminderText(link)} · ${modeText(link)}`,
425
+ `${link.remote ? `${t('remoteLabel')} ${link.remote.device}/${link.remote.alias} · ` : ''}${link.managerTitle || link.manager} · ${roundText(link)}${reminderText(link)} · ${modeText(link)}`,
424
426
  ),
425
427
  link.pending === null || link.pending === undefined
426
428
  ? null
@@ -473,7 +475,7 @@ window.__ModuleLoader__.load({
473
475
  h('div', { style: S.workerMain },
474
476
  h('div', { style: S.workerName }, link.workerTitle || link.worker),
475
477
  h('div', { style: S.mono }, link.worker),
476
- h('div', { style: S.muted }, `${roundText(link)}${reminderText(link)} · ${modeText(link)}`),
478
+ h('div', { style: S.muted }, `${roundText(link)}${reminderText(link)} · ${modeText(link)}${link.remote ? ` · ${t('remoteLabel')}` : ''}`),
477
479
  link.pending === null || link.pending === undefined
478
480
  ? null
479
481
  : h('p', { style: S.taskText }, link.pending.task),
package/cordis.patch.yml CHANGED
@@ -13,3 +13,7 @@
13
13
  autoNudge: true
14
14
  nudgeAfterMinutes: 20
15
15
  maxNudges: 3
16
+ hubUrl: ''
17
+ hubRoom: 'default'
18
+ hubToken: ''
19
+ deviceName: ''
package/hub.js ADDED
@@ -0,0 +1,197 @@
1
+ #!/usr/bin/env node
2
+ // collab-pair hub: a tiny store-and-forward relay for cross-device collaboration.
3
+ //
4
+ // One device (or a small VPS) runs this; every DSH that wants to collaborate
5
+ // connects out to it. Clients only need outbound HTTP, so a tunnel (cloudflared,
6
+ // ngrok, frp, Tailscale) is enough on the hub side; no inbound port on workers.
7
+ //
8
+ // node hub.js --port 8787 --token <shared-secret> [--host 0.0.0.0]
9
+ //
10
+ // Protocol (all JSON, token in `Authorization: Bearer <token>`):
11
+ // POST /v1/send {room, from, to, type, payload} -> {ok, id}
12
+ // GET /v1/poll?room=&device=&since= (long-poll, 15s) -> {ok, cursor, messages}
13
+ // GET /v1/head?room= -> {ok, cursor}
14
+ // GET /v1/health -> {ok, service, rooms}
15
+ //
16
+ // Messages live in memory only, for 15 minutes / 1000 per room. That is enough
17
+ // for dispatch/report round trips; it is deliberately not a durable queue.
18
+
19
+ import { createHash, randomBytes, timingSafeEqual } from 'node:crypto'
20
+ import { createServer } from 'node:http'
21
+
22
+ const args = new Map()
23
+ for (let index = 2; index < process.argv.length; index++) {
24
+ const arg = process.argv[index]
25
+ if (!arg.startsWith('--')) continue
26
+ const key = arg.slice(2)
27
+ const next = process.argv[index + 1]
28
+ if (next === undefined || next.startsWith('--')) args.set(key, 'true')
29
+ else {
30
+ args.set(key, next)
31
+ index++
32
+ }
33
+ }
34
+
35
+ const port = Number(args.get('port') ?? process.env.PORT ?? 8787)
36
+ const host = args.get('host') ?? '0.0.0.0'
37
+ const token = args.get('token') ?? process.env.COLLAB_HUB_TOKEN ?? randomBytes(12).toString('hex')
38
+ const tokenHash = createHash('sha256').update(token).digest()
39
+ const TTL_MS = 15 * 60 * 1000
40
+ const MAX_MESSAGES = 1000
41
+ const MAX_BODY = 256 * 1024
42
+
43
+ const rooms = new Map()
44
+ const waiters = new Map()
45
+
46
+ function stateOf(room) {
47
+ let state = rooms.get(room)
48
+ if (state === undefined) {
49
+ state = { messages: [], nextId: 0 }
50
+ rooms.set(room, state)
51
+ }
52
+ return state
53
+ }
54
+
55
+ function prune(state) {
56
+ const cutoff = Date.now() - TTL_MS
57
+ while (state.messages.length > 0 && (state.messages[0].at < cutoff || state.messages.length > MAX_MESSAGES)) state.messages.shift()
58
+ }
59
+
60
+ function notify(room) {
61
+ const set = waiters.get(room)
62
+ if (set === undefined) return
63
+ for (const resolve of [...set]) resolve()
64
+ }
65
+
66
+ function waitForMessage(room, timeoutMs) {
67
+ return new Promise((resolve) => {
68
+ let set = waiters.get(room)
69
+ if (set === undefined) {
70
+ set = new Set()
71
+ waiters.set(room, set)
72
+ }
73
+ const done = () => {
74
+ clearTimeout(timer)
75
+ set.delete(done)
76
+ resolve()
77
+ }
78
+ const timer = setTimeout(done, timeoutMs)
79
+ set.add(done)
80
+ })
81
+ }
82
+
83
+ function json(response, status, value) {
84
+ const body = JSON.stringify(value)
85
+ response.writeHead(status, {
86
+ 'content-type': 'application/json; charset=utf-8',
87
+ 'content-length': Buffer.byteLength(body),
88
+ 'cache-control': 'no-store',
89
+ })
90
+ response.end(body)
91
+ }
92
+
93
+ function authorized(request) {
94
+ const header = request.headers.authorization ?? ''
95
+ const value = header.startsWith('Bearer ') ? header.slice(7) : ''
96
+ const candidate = createHash('sha256').update(value).digest()
97
+ return candidate.length === tokenHash.length && timingSafeEqual(candidate, tokenHash)
98
+ }
99
+
100
+ async function readJson(request) {
101
+ let size = 0
102
+ const chunks = []
103
+ for await (const chunk of request) {
104
+ size += chunk.length
105
+ if (size > MAX_BODY) throw new Error('body too large')
106
+ chunks.push(chunk)
107
+ }
108
+ if (chunks.length === 0) return {}
109
+ return JSON.parse(Buffer.concat(chunks).toString('utf8'))
110
+ }
111
+
112
+ function roomName(value) {
113
+ return typeof value === 'string' && /^[A-Za-z0-9_-]{1,64}$/.test(value) ? value : undefined
114
+ }
115
+
116
+ const server = createServer(async (request, response) => {
117
+ try {
118
+ const url = new URL(request.url ?? '/', `http://${request.headers.host ?? 'localhost'}`)
119
+ if (url.pathname === '/v1/health') {
120
+ json(response, 200, { ok: true, service: 'collab-pair-hub', rooms: rooms.size })
121
+ return
122
+ }
123
+ if (!authorized(request)) {
124
+ json(response, 401, { ok: false, error: 'unauthorized' })
125
+ return
126
+ }
127
+ if (url.pathname === '/v1/head') {
128
+ const room = roomName(url.searchParams.get('room'))
129
+ if (room === undefined) return json(response, 400, { ok: false, error: 'bad room' })
130
+ const state = stateOf(room)
131
+ prune(state)
132
+ json(response, 200, { ok: true, cursor: state.nextId })
133
+ return
134
+ }
135
+ if (url.pathname === '/v1/poll') {
136
+ const room = roomName(url.searchParams.get('room'))
137
+ const device = url.searchParams.get('device') ?? ''
138
+ const since = Number(url.searchParams.get('since') ?? 0)
139
+ if (room === undefined || device === '' || !Number.isFinite(since)) {
140
+ json(response, 400, { ok: false, error: 'bad poll parameters' })
141
+ return
142
+ }
143
+ const state = stateOf(room)
144
+ const deadline = Date.now() + 15000
145
+ for (;;) {
146
+ prune(state)
147
+ const messages = state.messages.filter((message) => message.id > since && (message.to === device || message.to === '*'))
148
+ if (messages.length > 0) {
149
+ json(response, 200, { ok: true, cursor: messages[messages.length - 1].id, messages })
150
+ return
151
+ }
152
+ const remaining = deadline - Date.now()
153
+ if (remaining <= 0) {
154
+ json(response, 200, { ok: true, cursor: since, messages: [] })
155
+ return
156
+ }
157
+ await waitForMessage(room, Math.min(remaining, 15000))
158
+ }
159
+ }
160
+ if (url.pathname === '/v1/send' && request.method === 'POST') {
161
+ const body = await readJson(request)
162
+ const room = roomName(body.room)
163
+ const from = typeof body.from === 'string' ? body.from.trim() : ''
164
+ const to = typeof body.to === 'string' ? body.to.trim() : ''
165
+ const type = typeof body.type === 'string' ? body.type.trim() : ''
166
+ if (room === undefined || from === '' || from.length > 64 || to === '' || to.length > 64 || type === '' || type.length > 32) {
167
+ json(response, 400, { ok: false, error: 'bad message' })
168
+ return
169
+ }
170
+ const state = stateOf(room)
171
+ prune(state)
172
+ state.nextId += 1
173
+ const message = {
174
+ id: state.nextId,
175
+ from,
176
+ to,
177
+ type,
178
+ payload: body.payload ?? null,
179
+ at: Date.now(),
180
+ }
181
+ state.messages.push(message)
182
+ prune(state)
183
+ notify(room)
184
+ json(response, 200, { ok: true, id: message.id, cursor: state.nextId })
185
+ return
186
+ }
187
+ json(response, 404, { ok: false, error: 'not found' })
188
+ } catch (error) {
189
+ json(response, 400, { ok: false, error: String(error?.message ?? error) })
190
+ }
191
+ })
192
+
193
+ server.listen(port, host, () => {
194
+ console.log(`collab-pair hub listening on http://${host}:${port}`)
195
+ console.log(`token: ${token}`)
196
+ console.log('put the hub behind HTTPS before using it across untrusted networks')
197
+ })
package/index.js CHANGED
@@ -17,6 +17,7 @@
17
17
  * @module @local/collab-pair
18
18
  */
19
19
  import { randomUUID } from 'node:crypto'
20
+ import { hostname } from 'node:os'
20
21
 
21
22
  export const inject = ['tools', 'systemPrompt', 'agents', 'sessions', 'commands']
22
23
 
@@ -27,12 +28,20 @@ const STORAGE_DOMAIN = {
27
28
  version: 1,
28
29
  tables: { links: { valueSchema: { parse: (value) => value } } },
29
30
  }
31
+ const REMOTE_DOMAIN = {
32
+ name: 'collab_pair_remote',
33
+ version: 1,
34
+ tables: {
35
+ aliases: { valueSchema: { parse: (value) => value } },
36
+ state: { valueSchema: { parse: (value) => value } },
37
+ },
38
+ }
30
39
  const ACTIVE = 'active'
31
40
  const DONE = 'done'
32
41
  const STOPPED = 'stopped'
33
42
  const REPORTS = new Set(['done', 'partial', 'blocked'])
34
43
  const PROMPT_TIMEOUT_MS = 180000
35
- const ENGINE = 'collab-pair/1.2.2'
44
+ const ENGINE = 'collab-pair/1.3.0'
36
45
 
37
46
  /** A recoverable failure whose message is meant for the model. */
38
47
  class CollabError extends Error {}
@@ -58,7 +67,40 @@ function resolveConfig(raw) {
58
67
  autoNudge: value.autoNudge !== false,
59
68
  nudgeAfterMinutes: clampInt(value.nudgeAfterMinutes, 5, 1440, 20),
60
69
  maxNudges: clampInt(value.maxNudges, 1, 20, 3),
70
+ hubUrl: normalizeHubUrl(value.hubUrl),
71
+ hubRoom: typeof value.hubRoom === 'string' && /^[A-Za-z0-9_-]{1,64}$/.test(value.hubRoom) ? value.hubRoom : 'default',
72
+ hubToken: typeof value.hubToken === 'string' ? value.hubToken.trim() : '',
73
+ deviceName: deviceText(value.deviceName),
74
+ }
75
+ }
76
+
77
+ /** One HTTP(S) base URL for the relay, without a trailing slash. */
78
+ function normalizeHubUrl(candidate) {
79
+ if (typeof candidate !== 'string') return ''
80
+ const value = candidate.trim().replace(/\/+$/, '')
81
+ if (value === '') return ''
82
+ try {
83
+ const url = new URL(value)
84
+ if (url.protocol !== 'http:' && url.protocol !== 'https:') return ''
85
+ return value
86
+ } catch {
87
+ return ''
88
+ }
89
+ }
90
+
91
+ /** A stable, URL-safe device label; defaults to the host name. */
92
+ function deviceText(candidate) {
93
+ let raw = typeof candidate === 'string' ? candidate.trim() : ''
94
+ if (raw === '') {
95
+ try {
96
+ raw = hostname()
97
+ } catch {
98
+ raw = ''
99
+ }
61
100
  }
101
+ if (raw === '') raw = `dsh-${randomUUID().slice(0, 6)}`
102
+ const cleaned = raw.replace(/[^A-Za-z0-9_-]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 64)
103
+ return cleaned === '' ? `dsh-${randomUUID().slice(0, 6)}` : cleaned
62
104
  }
63
105
 
64
106
  /** One non-empty prefix string, clamped to a title-safe length. */
@@ -98,7 +140,7 @@ function clip(text, limit) {
98
140
 
99
141
  /** Join assistant/user content blocks into plain text. */
100
142
  function messageText(message) {
101
- const content = message?.content
143
+ const content = message?.content ?? message?.message?.content
102
144
  if (!Array.isArray(content)) return ''
103
145
  const parts = []
104
146
  for (const block of content) if (block?.type === 'text' && typeof block.text === 'string') parts.push(block.text)
@@ -478,16 +520,33 @@ export function apply(ctx, rawConfig) {
478
520
  const toolExecutors = {}
479
521
  let storageState = 'pending'
480
522
  let storageError = null
523
+ const remoteAliases = new Map()
524
+ const remoteInbound = new Map()
525
+ let remoteState = 'pending'
526
+ let remoteCursor = 0
527
+ let remoteLastError = null
528
+ let remoteLastPollAt = 0
529
+ let remoteDomain = null
530
+ const remoteReady = openRemoteStorage()
481
531
 
482
532
  const domainReady = openStorage()
483
533
 
484
534
  ctx.effect(() => async () => {
485
535
  const domain = await domainReady.catch(() => undefined)
486
- if (domain === undefined) return
487
- try {
488
- await domain.close()
489
- } catch (error) {
490
- ctx.logger.warn(`collab-pair: closing the storage domain failed: ${String(error)}`)
536
+ if (domain !== undefined) {
537
+ try {
538
+ await domain.close()
539
+ } catch (error) {
540
+ ctx.logger.warn(`collab-pair: closing the storage domain failed: ${String(error)}`)
541
+ }
542
+ }
543
+ const remote = await remoteReady.catch(() => undefined)
544
+ if (remote !== undefined) {
545
+ try {
546
+ await remote.close()
547
+ } catch (error) {
548
+ ctx.logger.warn(`collab-pair: closing the remote storage domain failed: ${String(error)}`)
549
+ }
491
550
  }
492
551
  })
493
552
 
@@ -509,6 +568,7 @@ export function apply(ctx, rawConfig) {
509
568
  if (cfg.autoNudge) watchdogTimer = setInterval(() => { void runWatchdog() }, 60000)
510
569
  setTimeout(() => { void recoverPendingLinks() }, 5000)
511
570
  setTimeout(() => { void backfillProjects() }, 3000)
571
+ setTimeout(() => { if (alive) void remoteLoop() }, 2000)
512
572
 
513
573
  registerTools()
514
574
  registerCommand()
@@ -576,6 +636,11 @@ export function apply(ctx, rawConfig) {
576
636
  history: Array.isArray(value.history) ? value.history.slice(-cfg.maxHistory) : [],
577
637
  nudges: Number.isSafeInteger(value.nudges) && value.nudges >= 0 ? value.nudges : 0,
578
638
  ...(typeof value.lastNudgeAt === 'number' ? { lastNudgeAt: value.lastNudgeAt } : {}),
639
+ ...(value.remote !== null && typeof value.remote === 'object'
640
+ && typeof value.remote.device === 'string' && value.remote.device !== ''
641
+ && typeof value.remote.alias === 'string' && value.remote.alias !== ''
642
+ ? { remote: { device: value.remote.device, alias: value.remote.alias } }
643
+ : {}),
579
644
  createdAt: Number.isFinite(value.createdAt) ? value.createdAt : Date.now(),
580
645
  updatedAt: Number.isFinite(value.updatedAt) ? value.updatedAt : Date.now(),
581
646
  ...(typeof value.closedAt === 'number' ? { closedAt: value.closedAt } : {}),
@@ -622,6 +687,331 @@ export function apply(ctx, rawConfig) {
622
687
  }
623
688
  }
624
689
 
690
+ // --------------------------------------------------------- relay transport
691
+
692
+ /** Open the alias/cursor table used by the relay transport. */
693
+ async function openRemoteStorage() {
694
+ const facility = ctx.get('storageDomain')
695
+ if (facility === undefined) {
696
+ remoteState = 'memory'
697
+ return undefined
698
+ }
699
+ try {
700
+ const domain = await facility.open(REMOTE_DOMAIN)
701
+ for (const [key, value] of domain.table('aliases').entries()) adoptAlias(key, value)
702
+ for (const [key, value] of domain.table('state').entries()) {
703
+ if (key === 'cursor' && Number.isSafeInteger(value?.cursor) && value.cursor >= 0) remoteCursor = value.cursor
704
+ }
705
+ remoteDomain = domain
706
+ remoteState = 'ready'
707
+ return domain
708
+ } catch (error) {
709
+ remoteState = 'memory'
710
+ ctx.logger.warn(`collab-pair: remote storage is unavailable; aliases are kept in memory: ${String(error)}`)
711
+ return undefined
712
+ }
713
+ }
714
+
715
+ /** Validate one stored alias record. */
716
+ function adoptAlias(key, value) {
717
+ if (value === null || typeof value !== 'object') return
718
+ if (typeof value.alias !== 'string' || value.alias !== key) return
719
+ if (typeof value.session !== 'string' || value.session === '') return
720
+ remoteAliases.set(key, {
721
+ alias: key,
722
+ session: value.session,
723
+ updatedAt: Number.isFinite(value.updatedAt) ? value.updatedAt : Date.now(),
724
+ })
725
+ }
726
+
727
+ /** Persist one alias record. */
728
+ async function persistAlias(record) {
729
+ const domain = await remoteReady.catch(() => undefined)
730
+ if (domain === undefined) return
731
+ try {
732
+ await domain.table('aliases').put(record.alias, { ...record })
733
+ } catch (error) {
734
+ ctx.logger.warn(`collab-pair: persisting alias ${record.alias} failed: ${String(error)}`)
735
+ }
736
+ }
737
+
738
+ /** Delete one alias record. */
739
+ async function deleteAliasRecord(alias) {
740
+ const domain = await remoteReady.catch(() => undefined)
741
+ if (domain === undefined) return
742
+ try {
743
+ await domain.table('aliases').delete(alias)
744
+ } catch (error) {
745
+ ctx.logger.warn(`collab-pair: deleting alias ${alias} failed: ${String(error)}`)
746
+ }
747
+ }
748
+
749
+ /** Persist the poll cursor so a restart does not replay old rounds. */
750
+ async function saveRemoteCursor() {
751
+ const domain = await remoteReady.catch(() => undefined)
752
+ if (domain === undefined) return
753
+ try {
754
+ await domain.table('state').put('cursor', { cursor: remoteCursor, updatedAt: Date.now() })
755
+ } catch (error) {
756
+ ctx.logger.warn(`collab-pair: saving the relay cursor failed: ${String(error)}`)
757
+ }
758
+ }
759
+
760
+ function hubConfigured() {
761
+ return cfg.hubUrl !== '' && cfg.hubToken !== ''
762
+ }
763
+
764
+ /** One authenticated JSON request to the relay. */
765
+ async function hubFetch(path, options = {}) {
766
+ const controller = new AbortController()
767
+ const timer = setTimeout(() => controller.abort(), 25000)
768
+ try {
769
+ const response = await fetch(`${cfg.hubUrl}${path}`, {
770
+ ...options,
771
+ headers: {
772
+ authorization: `Bearer ${cfg.hubToken}`,
773
+ ...(options.body === undefined ? {} : { 'content-type': 'application/json' }),
774
+ ...(options.headers ?? {}),
775
+ },
776
+ signal: controller.signal,
777
+ })
778
+ const body = await response.json().catch(() => null)
779
+ if (!response.ok || body?.ok !== true) throw new Error(body?.error ?? `relay HTTP ${response.status}`)
780
+ return body
781
+ } finally {
782
+ clearTimeout(timer)
783
+ }
784
+ }
785
+
786
+ /** Queue one message for another device. */
787
+ async function sendRemote(to, type, payload) {
788
+ if (!hubConfigured()) throw new CollabError('尚未配置跨设备中继:请在插件配置中设置 hubUrl 与 hubToken。')
789
+ return hubFetch('/v1/send', {
790
+ method: 'POST',
791
+ body: JSON.stringify({ room: cfg.hubRoom, from: cfg.deviceName, to, type, payload }),
792
+ })
793
+ }
794
+
795
+ /** Long-poll the relay and dispatch incoming envelopes. */
796
+ async function remoteLoop() {
797
+ if (!hubConfigured()) return
798
+ ctx.logger.info(`collab-pair: relay transport for ${cfg.deviceName} on room ${cfg.hubRoom}`)
799
+ while (alive && hubConfigured()) {
800
+ try {
801
+ if (remoteCursor === 0) {
802
+ const head = await hubFetch(`/v1/head?room=${encodeURIComponent(cfg.hubRoom)}`)
803
+ remoteCursor = Number.isSafeInteger(head.cursor) ? head.cursor : 0
804
+ await saveRemoteCursor()
805
+ }
806
+ const query = `?room=${encodeURIComponent(cfg.hubRoom)}&device=${encodeURIComponent(cfg.deviceName)}&since=${remoteCursor}`
807
+ const result = await hubFetch(`/v1/poll${query}`)
808
+ remoteLastPollAt = Date.now()
809
+ remoteLastError = null
810
+ let advanced = false
811
+ for (const message of Array.isArray(result.messages) ? result.messages : []) {
812
+ if (!Number.isSafeInteger(message?.id) || message.id <= remoteCursor) continue
813
+ remoteCursor = message.id
814
+ advanced = true
815
+ try {
816
+ await handleRemoteMessage(message)
817
+ } catch (error) {
818
+ ctx.logger.warn(`collab-pair: handling relay message ${message.id} failed: ${String(error)}`)
819
+ }
820
+ }
821
+ if (advanced) await saveRemoteCursor()
822
+ } catch (error) {
823
+ remoteLastError = String(error instanceof Error ? error.message : error)
824
+ ctx.logger.warn(`collab-pair: relay poll failed: ${remoteLastError}`)
825
+ await new Promise((resolve) => setTimeout(resolve, 5000))
826
+ }
827
+ }
828
+ }
829
+
830
+ /** Route one relay envelope. */
831
+ async function handleRemoteMessage(message) {
832
+ if (message.from === cfg.deviceName) return
833
+ if (message.type === 'dispatch') await handleRemoteDispatch(message)
834
+ else if (message.type === 'report') await handleRemoteReport(message)
835
+ else if (message.type === 'done') await handleRemoteDone(message)
836
+ else if (message.type === 'error') await handleRemoteError(message)
837
+ }
838
+
839
+ /** Worker side: a manager dispatched a round to one local alias. */
840
+ async function handleRemoteDispatch(message) {
841
+ const payload = message.payload ?? {}
842
+ const alias = aliasText(payload.alias)
843
+ const linkId = typeof payload.linkId === 'string' ? payload.linkId : ''
844
+ const round = Number.isSafeInteger(payload.round) ? payload.round : 0
845
+ const reply = (type, extra) => sendRemote(message.from, type, { linkId, round, alias, device: cfg.deviceName, ...extra })
846
+ .catch((error) => ctx.logger.warn(`collab-pair: replying ${type} to ${message.from} failed: ${String(error)}`))
847
+ if (alias === '' || linkId === '' || round < 1) {
848
+ await reply('error', { code: 'bad-dispatch', message: '派发消息缺少 alias/linkId/round。' })
849
+ return
850
+ }
851
+ const record = remoteAliases.get(alias)
852
+ if (record === undefined) {
853
+ await reply('error', { code: 'no-alias', message: `本机没有别名 "${alias}";先在员工设备上注册这个别名。` })
854
+ return
855
+ }
856
+ const task = typeof payload.task === 'string' ? payload.task.trim() : ''
857
+ if (task === '') {
858
+ await reply('error', { code: 'empty-task', message: '任务为空。' })
859
+ return
860
+ }
861
+ const acceptance = typeof payload.acceptance === 'string' ? payload.acceptance.trim() : ''
862
+ const managerName = typeof payload.managerName === 'string' && payload.managerName !== '' ? payload.managerName : message.from
863
+ const text = [
864
+ `【远程协作任务 · 第 ${round} 轮】`,
865
+ ...(typeof payload.project === 'string' && payload.project !== '' ? [`项目:${payload.project}`] : []),
866
+ `来自:${managerName}(设备 ${message.from})`,
867
+ '',
868
+ task,
869
+ ...(acceptance === '' ? [] : ['', `验收标准:${acceptance}`]),
870
+ '',
871
+ '完成后直接在回复中给出结果与总结(改了哪些文件、如何验证);不需要调用协作工具。',
872
+ `[[collab:${linkId}:r${round}]]`,
873
+ ].join('\n')
874
+ const requestId = `cp-remote-${linkId}-r${round}`
875
+ remoteInbound.set(record.session, { linkId, round, requestId, managerDevice: message.from, managerName, alias, dispatchedAt: Date.now() })
876
+ try {
877
+ await deliver(record.session, text, requestId, 'queue', AbortSignal.timeout(PROMPT_TIMEOUT_MS))
878
+ } catch (error) {
879
+ remoteInbound.delete(record.session)
880
+ await reply('error', { code: 'deliver-failed', message: deliveryFailure(error) })
881
+ return
882
+ }
883
+ await reply('ack', {})
884
+ }
885
+
886
+ /** Manager side: a remote worker finished a round. */
887
+ async function handleRemoteReport(message) {
888
+ const payload = message.payload ?? {}
889
+ const link = remoteLink(payload.linkId)
890
+ if (link === undefined) return
891
+ const round = Number.isSafeInteger(payload.round) ? payload.round : 0
892
+ if (link.pending === null || link.pending.round !== round) return
893
+ const summary = clip(typeof payload.text === 'string' ? payload.text : '', cfg.maxRelayChars)
894
+ if (summary === '') return
895
+ const pending = { ...link.pending }
896
+ const report = {
897
+ summary,
898
+ status: REPORTS.has(payload.status) ? payload.status : 'done',
899
+ details: '',
900
+ next: '',
901
+ reportedAt: Date.now(),
902
+ }
903
+ link.pending = null
904
+ link.round = Math.max(link.round, round)
905
+ link.nudges = 0
906
+ delete link.lastNudgeAt
907
+ link.lastReport = {
908
+ round,
909
+ status: report.status,
910
+ summary,
911
+ details: '',
912
+ next: '',
913
+ text: summary,
914
+ turnReason: L.reasonText('远程回报'),
915
+ relayedAt: Date.now(),
916
+ relayRequestId: `cp-${link.id}-r${round}-to-manager`,
917
+ }
918
+ link.history = [
919
+ ...(link.history ?? []),
920
+ { round, task: clip(pending.task, 300), status: report.status, summary: clip(summary, 500), at: Date.now() },
921
+ ].slice(-cfg.maxHistory)
922
+ link.updatedAt = Date.now()
923
+ await persist(link)
924
+ const text = reportText({ link, pending, report, finalText: summary, reason: '远程回报', workerTitle: link.label || link.remote.alias })
925
+ if (!cfg.autoRelay) return
926
+ try {
927
+ await deliver(link.manager, text, link.lastReport.relayRequestId, 'queue', AbortSignal.timeout(PROMPT_TIMEOUT_MS))
928
+ } catch (error) {
929
+ link.lastReport.deliveryError = String(error instanceof Error ? error.message : error)
930
+ await persist(link)
931
+ ctx.logger.warn(`collab-pair: delivering a remote report for ${link.id} failed: ${String(error)}`)
932
+ setTimeout(() => {
933
+ if (!alive) return
934
+ void deliver(link.manager, text, link.lastReport.relayRequestId, 'queue', AbortSignal.timeout(PROMPT_TIMEOUT_MS))
935
+ .then(async () => {
936
+ if (link.lastReport !== null && link.lastReport.deliveryError !== undefined) {
937
+ delete link.lastReport.deliveryError
938
+ await persist(link)
939
+ }
940
+ })
941
+ .catch((retryError) => ctx.logger.warn(`collab-pair: remote relay retry for ${link.id} failed: ${String(retryError)}`))
942
+ }, 60000)
943
+ }
944
+ }
945
+
946
+ /** Worker side: the manager closed this collaboration. */
947
+ async function handleRemoteDone(message) {
948
+ const payload = message.payload ?? {}
949
+ if (!cfg.notifyWorkerOnDone) return
950
+ const record = remoteAliases.get(aliasText(payload.alias))
951
+ if (record === undefined) return
952
+ const summary = typeof payload.summary === 'string' ? clip(payload.summary, 2000) : ''
953
+ const text = ['【协作结束】', '项目经理已结束本次远程协作。', ...(summary === '' ? [] : ['', `总结:${summary}`])].join('\n')
954
+ try {
955
+ await deliver(record.session, text, `cp-remote-done-${payload.linkId ?? Date.now()}`, 'queue', AbortSignal.timeout(PROMPT_TIMEOUT_MS))
956
+ } catch (error) {
957
+ ctx.logger.warn(`collab-pair: notifying the remote worker of completion failed: ${String(error)}`)
958
+ }
959
+ }
960
+
961
+ /** Manager side: the remote device could not take the round. */
962
+ async function handleRemoteError(message) {
963
+ const payload = message.payload ?? {}
964
+ const link = remoteLink(payload.linkId)
965
+ if (link === undefined) return
966
+ const detail = typeof payload.message === 'string' && payload.message !== '' ? payload.message : String(payload.code ?? '未知错误')
967
+ const text = `【远程协作错误】\n设备 ${message.from} 无法接单:${detail}`
968
+ try {
969
+ await deliver(link.manager, text, `cp-${link.id}-remote-error-${Date.now()}`, 'queue', AbortSignal.timeout(PROMPT_TIMEOUT_MS))
970
+ } catch (error) {
971
+ ctx.logger.warn(`collab-pair: delivering a remote error for ${link.id} failed: ${String(error)}`)
972
+ }
973
+ }
974
+
975
+ /** Worker side: relay the finished remote turn back to its manager. */
976
+ async function handleRemoteTurnEnd(session, event, inbound) {
977
+ const turn = event.data?.turn
978
+ if (!Number.isSafeInteger(turn)) return
979
+ let events
980
+ try {
981
+ events = turnEvents(session, turn, event.seq)
982
+ } catch (error) {
983
+ ctx.logger.warn(`collab-pair: reading a remote worker turn failed: ${String(error)}`)
984
+ return
985
+ }
986
+ if (events === undefined) return
987
+ if (!claimedBy(events, inbound)) return
988
+ remoteInbound.delete(session.id)
989
+ const finalText = lastAssistantText(events)
990
+ const summary = clip(finalText === '' ? '(本轮没有返回文本)' : finalText, cfg.maxRelayChars)
991
+ try {
992
+ await sendRemote(inbound.managerDevice, 'report', {
993
+ linkId: inbound.linkId,
994
+ round: inbound.round,
995
+ alias: inbound.alias,
996
+ device: cfg.deviceName,
997
+ status: 'done',
998
+ text: summary,
999
+ })
1000
+ } catch (error) {
1001
+ ctx.logger.warn(`collab-pair: sending a remote report to ${inbound.managerDevice} failed: ${String(error)}`)
1002
+ }
1003
+ }
1004
+
1005
+ /** The remote link for a link id, or undefined for a local link. */
1006
+ function remoteLink(linkId) {
1007
+ const link = typeof linkId === 'string' ? links.get(linkId) : undefined
1008
+ return link?.remote === undefined ? undefined : link
1009
+ }
1010
+
1011
+ function aliasText(value) {
1012
+ return typeof value === 'string' && /^[A-Za-z0-9_-]{1,64}$/.test(value.trim()) ? value.trim() : ''
1013
+ }
1014
+
625
1015
  // ------------------------------------------------------------- prompt text
626
1016
 
627
1017
  /**
@@ -1019,8 +1409,8 @@ export function apply(ctx, rawConfig) {
1019
1409
  const rows = []
1020
1410
  for (const link of sorted) {
1021
1411
  const managerTitle = await titleFor(link.manager)
1022
- const workerTitle = (await titleFor(link.worker)) ?? (link.label || null)
1023
- const workerAgent = ctx.agents.get(link.worker)
1412
+ const workerTitle = link.remote === undefined ? (await titleFor(link.worker)) ?? (link.label || null) : (link.label || link.remote.alias)
1413
+ const workerAgent = link.remote === undefined ? ctx.agents.get(link.worker) : undefined
1024
1414
  const managerAgent = ctx.agents.get(link.manager)
1025
1415
  rows.push({
1026
1416
  linkId: link.id,
@@ -1031,6 +1421,7 @@ export function apply(ctx, rawConfig) {
1031
1421
  status: link.status,
1032
1422
  mode: link.mode,
1033
1423
  project: link.project || '',
1424
+ remote: link.remote ?? null,
1034
1425
  workerLive: workerAgent !== undefined,
1035
1426
  workerRunning: workerAgent !== undefined && workerAgent.status === 'running',
1036
1427
  managerRunning: managerAgent !== undefined && managerAgent.status === 'running',
@@ -1104,7 +1495,20 @@ export function apply(ctx, rawConfig) {
1104
1495
  link.updatedAt = Date.now()
1105
1496
  await persist(link)
1106
1497
  try {
1107
- await deliver(link.worker, dispatchText(link, round, task, acceptance), requestId, 'queue', signal)
1498
+ if (link.remote !== undefined) {
1499
+ await sendRemote(link.remote.device, 'dispatch', {
1500
+ alias: link.remote.alias,
1501
+ linkId: link.id,
1502
+ round,
1503
+ task,
1504
+ acceptance,
1505
+ managerDevice: cfg.deviceName,
1506
+ managerName: (await titleOf(link.manager)) ?? null,
1507
+ project: link.project,
1508
+ })
1509
+ } else {
1510
+ await deliver(link.worker, dispatchText(link, round, task, acceptance), requestId, 'queue', signal)
1511
+ }
1108
1512
  } catch (error) {
1109
1513
  link.round = previousRound
1110
1514
  link.pending = previous
@@ -1337,6 +1741,11 @@ export function apply(ctx, rawConfig) {
1337
1741
  /** Global post-commit listener: relay a worker turn that answered a dispatch. */
1338
1742
  function onSessionEvent(session, event) {
1339
1743
  if (event?.type !== 'turn/end') return
1744
+ const inbound = remoteInbound.get(session.id)
1745
+ if (inbound !== undefined) {
1746
+ void handleRemoteTurnEnd(session, event, inbound)
1747
+ return
1748
+ }
1340
1749
  const linkId = byWorker.get(session.id)
1341
1750
  if (linkId === undefined) return
1342
1751
  const link = links.get(linkId)
@@ -1614,6 +2023,143 @@ export function apply(ctx, rawConfig) {
1614
2023
  when: ({ agent }) => workerAssociation(agent.id) === undefined,
1615
2024
  })
1616
2025
 
2026
+ toolExecutors.remote = register({
2027
+ name: 'collab_remote',
2028
+ description:
2029
+ '跨设备协作(先在插件配置里设置 hubUrl 与 hubToken):action=alias 在员工设备上把当前对话注册成别名;action=link 在项目经理设备上关联远端设备上的别名;action=aliases / remove-alias / status 查看或维护。',
2030
+ parameters: {
2031
+ type: 'object',
2032
+ properties: {
2033
+ action: { type: 'string', enum: ['alias', 'aliases', 'remove-alias', 'link', 'status'], description: '要执行的操作。' },
2034
+ alias: { type: 'string', description: 'alias/remove-alias:本机别名(字母、数字、下划线、连字符)。' },
2035
+ session: { type: 'string', description: 'alias:要注册的本地 sessionId,默认当前对话。' },
2036
+ device: { type: 'string', description: 'link:远端设备名(与那台设备的 deviceName 一致)。' },
2037
+ worker: { type: 'string', description: 'link:远端设备上的员工别名。' },
2038
+ name: { type: 'string', description: 'link:显示名,默认“别名@设备”。' },
2039
+ mode: { type: 'string', enum: ['temporary', 'permanent'], description: 'link:关联模式,默认 temporary。' },
2040
+ project: { type: 'string', description: 'link:项目名,默认当前经理的项目名。' },
2041
+ },
2042
+ required: ['action'],
2043
+ },
2044
+ async execute(args, exec) {
2045
+ const agent = requireAgent(exec)
2046
+ if (!hubConfigured()) throw new CollabError('尚未配置跨设备中继:在插件配置中设置 hubUrl 与 hubToken(可选 hubRoom、deviceName)。')
2047
+ await remoteReady.catch(() => undefined)
2048
+ const action = typeof args?.action === 'string' ? args.action : ''
2049
+ if (action === 'alias') {
2050
+ const alias = aliasText(args?.alias)
2051
+ if (alias === '') throw new CollabError('alias 必须由字母、数字、下划线或连字符组成,且不为空。')
2052
+ const sessionId = typeof args?.session === 'string' && args.session.trim() !== '' ? args.session.trim() : agent.id
2053
+ if (ctx.sessions.get(sessionId) === undefined) throw new CollabError(`找不到对话 ${sessionId};请确认它当前是打开状态。`)
2054
+ const record = { alias, session: sessionId, updatedAt: Date.now() }
2055
+ remoteAliases.set(alias, record)
2056
+ await persistAlias(record)
2057
+ return {
2058
+ ok: true,
2059
+ action: 'alias',
2060
+ alias,
2061
+ session: sessionId,
2062
+ device: cfg.deviceName,
2063
+ hub: cfg.hubUrl,
2064
+ room: cfg.hubRoom,
2065
+ message: `已把本机对话 ${sessionId} 注册为远程员工别名 "${alias}"(设备 ${cfg.deviceName})。`,
2066
+ }
2067
+ }
2068
+ if (action === 'aliases') {
2069
+ return {
2070
+ ok: true,
2071
+ action: 'aliases',
2072
+ device: cfg.deviceName,
2073
+ hub: cfg.hubUrl,
2074
+ room: cfg.hubRoom,
2075
+ aliases: [...remoteAliases.values()].sort((left, right) => left.alias.localeCompare(right.alias)),
2076
+ cursor: remoteCursor,
2077
+ lastPollAt: remoteLastPollAt === 0 ? null : isoTime(remoteLastPollAt),
2078
+ lastError: remoteLastError,
2079
+ }
2080
+ }
2081
+ if (action === 'remove-alias') {
2082
+ const alias = aliasText(args?.alias)
2083
+ if (alias === '') throw new CollabError('alias 不能为空。')
2084
+ const existed = remoteAliases.delete(alias)
2085
+ if (existed) await deleteAliasRecord(alias)
2086
+ return { ok: true, action: 'remove-alias', alias, removed: existed }
2087
+ }
2088
+ if (action === 'link') {
2089
+ if (workerAssociation(agent.id) !== undefined) throw new CollabError('当前对话是员工,不能作为远程协作的项目经理。')
2090
+ const device = typeof args?.device === 'string' ? args.device.trim() : ''
2091
+ if (!/^[A-Za-z0-9_-]{1,64}$/.test(device)) throw new CollabError('device 必须由字母、数字、下划线或连字符组成。')
2092
+ const worker = aliasText(args?.worker)
2093
+ if (worker === '') throw new CollabError('worker 必须是远端设备上的别名。')
2094
+ const existing = managerLinks(agent.id).find((link) => link.remote?.device === device && link.remote?.alias === worker && link.status === ACTIVE)
2095
+ if (existing !== undefined) throw new CollabError(`已经关联过 ${worker}@${device}(${existing.id})。`)
2096
+ const name = typeof args?.name === 'string' ? args.name.trim() : ''
2097
+ const project = typeof args?.project === 'string' && args.project.trim() !== '' ? args.project.trim() : managerProjectName(agent.id)
2098
+ const link = {
2099
+ v: 1,
2100
+ id: `cp-${randomUUID().slice(0, 8)}`,
2101
+ manager: agent.id,
2102
+ worker: `remote:${device}:${worker}`,
2103
+ label: name === '' ? `${worker}@${device}` : name,
2104
+ mode: args?.mode === 'permanent' ? 'permanent' : 'temporary',
2105
+ project,
2106
+ goal: '',
2107
+ status: ACTIVE,
2108
+ round: 0,
2109
+ pending: null,
2110
+ lastReport: null,
2111
+ history: [],
2112
+ nudges: 0,
2113
+ remote: { device, alias: worker },
2114
+ createdAt: Date.now(),
2115
+ updatedAt: Date.now(),
2116
+ }
2117
+ index(link)
2118
+ await persist(link)
2119
+ await applyPrefix(agent.id, cfg.prefixManager)
2120
+ return {
2121
+ ok: true,
2122
+ action: 'link',
2123
+ linkId: link.id,
2124
+ worker: link.worker,
2125
+ label: link.label,
2126
+ mode: link.mode,
2127
+ project: link.project || null,
2128
+ remote: link.remote,
2129
+ hub: cfg.hubUrl,
2130
+ room: cfg.hubRoom,
2131
+ message: `已关联远程员工 ${link.label}(设备 ${device},别名 ${worker})。用 collab_dispatch 派发任务。`,
2132
+ }
2133
+ }
2134
+ if (action === 'status') {
2135
+ return {
2136
+ ok: true,
2137
+ action: 'status',
2138
+ device: cfg.deviceName,
2139
+ hub: cfg.hubUrl,
2140
+ room: cfg.hubRoom,
2141
+ cursor: remoteCursor,
2142
+ lastPollAt: remoteLastPollAt === 0 ? null : isoTime(remoteLastPollAt),
2143
+ lastError: remoteLastError,
2144
+ aliases: [...remoteAliases.values()],
2145
+ remoteLinks: managerLinks(agent.id)
2146
+ .filter((link) => link.remote !== undefined)
2147
+ .map((link) => ({
2148
+ linkId: link.id,
2149
+ label: link.label,
2150
+ device: link.remote.device,
2151
+ alias: link.remote.alias,
2152
+ status: link.status,
2153
+ mode: link.mode,
2154
+ round: link.round,
2155
+ pending: link.pending === null ? null : link.pending.round,
2156
+ })),
2157
+ }
2158
+ }
2159
+ throw new CollabError('action 必须是 alias | aliases | remove-alias | link | status。')
2160
+ },
2161
+ })
2162
+
1617
2163
  toolExecutors.dispatch = register({
1618
2164
  name: 'collab_dispatch',
1619
2165
  description:
@@ -1699,7 +2245,7 @@ export function apply(ctx, rawConfig) {
1699
2245
  if (visible.length > 0) {
1700
2246
  const workers = []
1701
2247
  for (const link of visible) {
1702
- const title = await titleOf(link.worker)
2248
+ const title = link.remote === undefined ? await titleOf(link.worker) : undefined
1703
2249
  if (title !== undefined && title !== link.label) link.label = title
1704
2250
  workers.push({
1705
2251
  linkId: link.id,
@@ -1708,6 +2254,7 @@ export function apply(ctx, rawConfig) {
1708
2254
  status: link.status,
1709
2255
  mode: link.mode,
1710
2256
  project: link.project || null,
2257
+ remote: link.remote ?? null,
1711
2258
  round: link.round,
1712
2259
  pending: link.pending === null
1713
2260
  ? null
@@ -1921,7 +2468,18 @@ export function apply(ctx, rawConfig) {
1921
2468
  index(link)
1922
2469
  await persist(link)
1923
2470
  closed.push({ linkId: link.id, worker: link.worker, mode: link.mode })
1924
- if (cfg.notifyWorkerOnDone) {
2471
+ if (link.remote !== undefined) {
2472
+ try {
2473
+ await sendRemote(link.remote.device, 'done', {
2474
+ linkId: link.id,
2475
+ round: link.round,
2476
+ alias: link.remote.alias,
2477
+ summary: link.finalSummary,
2478
+ })
2479
+ } catch (error) {
2480
+ ctx.logger.warn(`collab-pair: notifying the remote device of completion failed: ${String(error)}`)
2481
+ }
2482
+ } else if (cfg.notifyWorkerOnDone) {
1925
2483
  try {
1926
2484
  await deliver(link.worker, doneText(link, link.finalSummary), `cp-${link.id}-done-to-worker`, 'queue', AbortSignal.timeout(PROMPT_TIMEOUT_MS))
1927
2485
  notified.push(link.worker)
@@ -1931,7 +2489,7 @@ export function apply(ctx, rawConfig) {
1931
2489
  }
1932
2490
  if (temporary) {
1933
2491
  await forget(link)
1934
- await clearPrefix(link.worker)
2492
+ if (link.remote === undefined) await clearPrefix(link.worker)
1935
2493
  removed.push({ linkId: link.id, worker: link.worker })
1936
2494
  }
1937
2495
  }
@@ -2000,16 +2558,25 @@ export function apply(ctx, rawConfig) {
2000
2558
  for (const link of targets) {
2001
2559
  if (args?.notify === true) {
2002
2560
  const reason = typeof args?.reason === 'string' ? args.reason.trim() : ''
2003
- try {
2004
- await deliver(link.worker, ['【协作结束】', '项目经理已解除本次协作。', ...(reason === '' ? [] : ['', `原因:${reason}`]), `[[collab:${link.id}:unlink]]`].join('\n'), `cp-${link.id}-unlink-to-worker`, 'queue', AbortSignal.timeout(PROMPT_TIMEOUT_MS))
2005
- notified += 1
2006
- } catch (error) {
2007
- ctx.logger.warn(`collab-pair: notifying ${link.worker} of unlink failed: ${String(error)}`)
2561
+ if (link.remote !== undefined) {
2562
+ try {
2563
+ await sendRemote(link.remote.device, 'done', { linkId: link.id, alias: link.remote.alias, summary: reason })
2564
+ notified += 1
2565
+ } catch (error) {
2566
+ ctx.logger.warn(`collab-pair: notifying the remote device of unlink failed: ${String(error)}`)
2567
+ }
2568
+ } else {
2569
+ try {
2570
+ await deliver(link.worker, ['【协作结束】', '项目经理已解除本次协作。', ...(reason === '' ? [] : ['', `原因:${reason}`]), `[[collab:${link.id}:unlink]]`].join('\n'), `cp-${link.id}-unlink-to-worker`, 'queue', AbortSignal.timeout(PROMPT_TIMEOUT_MS))
2571
+ notified += 1
2572
+ } catch (error) {
2573
+ ctx.logger.warn(`collab-pair: notifying ${link.worker} of unlink failed: ${String(error)}`)
2574
+ }
2008
2575
  }
2009
2576
  }
2010
2577
  removed.push({ linkId: link.id, worker: link.worker })
2011
2578
  await forget(link)
2012
- await clearPrefix(link.worker)
2579
+ if (link.remote === undefined) await clearPrefix(link.worker)
2013
2580
  }
2014
2581
  if (managerLinks(agent.id).length === 0) await clearPrefix(agent.id)
2015
2582
  return { ok: true, removed, peerNotified: notified > 0 }
@@ -2061,6 +2628,7 @@ export function apply(ctx, rawConfig) {
2061
2628
  dispatch: 'dispatch',
2062
2629
  configure: 'configure',
2063
2630
  project: 'project',
2631
+ remote: 'remote',
2064
2632
  done: 'done',
2065
2633
  unlink: 'unlink',
2066
2634
  sessions: 'sessions',
@@ -2069,7 +2637,7 @@ export function apply(ctx, rawConfig) {
2069
2637
  name: 'collab',
2070
2638
  description: '双对话协作:查看全部任务、关联员工、设置项目名、配置预设与语言、派发任务、收尾或解除。',
2071
2639
  input: {
2072
- hint: 'tasks | status | link --peer <id|new> | create --name <名字> --preset <id> | project --name <项目名> | configure --preset <id> | language <zh|en> | dispatch --worker <id> --task ... | done --worker <id> --summary ... | unlink --worker <id>',
2640
+ hint: 'tasks | status | link --peer <id|new> | create --name <名字> --preset <id> | project --name <项目名> | remote --action link --device <名> --worker <别名> | configure --preset <id> | language <zh|en> | dispatch --worker <id> --task ... | done --worker <id> --summary ... | unlink --worker <id>',
2073
2641
  },
2074
2642
  handler: async (invocation) => {
2075
2643
  try {
package/package.json CHANGED
@@ -1,9 +1,12 @@
1
1
  {
2
2
  "name": "dsh-collab-pair",
3
- "version": "1.2.3",
4
- "description": "For large projects: link a project-manager conversation with one or more worker conversations (temporary links unbind when done, permanent links stay until unlinked), group managers and workers by project, dispatch each round from the manager instead of repeating prompts, relay results automatically, and keep unattended runs moving with a visual task board.",
3
+ "version": "1.3.0",
4
+ "description": "For large projects: link a project-manager conversation with local or remote workers across devices (temporary links unbind when done, permanent links stay until unlinked), group managers and workers by project, dispatch each round from the manager instead of repeating prompts, relay results automatically, and keep unattended runs moving with a visual task board. Includes a small relay hub for cross-device runs.",
5
5
  "type": "module",
6
6
  "license": "MIT",
7
+ "scripts": {
8
+ "prepack": "node ../sync.mjs"
9
+ },
7
10
  "keywords": [
8
11
  "dsh",
9
12
  "dsh-plugin",
@@ -24,6 +27,7 @@
24
27
  "files": [
25
28
  "index.js",
26
29
  "client.js",
30
+ "hub.js",
27
31
  "cordis.patch.yml",
28
32
  "locale/*.json",
29
33
  "icon.svg",