dsh-collab-pair 1.0.1 → 1.2.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/index.js CHANGED
@@ -14,7 +14,7 @@
14
14
  * opened through the optional `storageDomain` service, with an in-memory
15
15
  * fallback when it is unavailable.
16
16
  *
17
- * @module dsh-collab-pair
17
+ * @module @local/collab-pair
18
18
  */
19
19
  import { randomUUID } from 'node:crypto'
20
20
 
@@ -32,7 +32,7 @@ const DONE = 'done'
32
32
  const STOPPED = 'stopped'
33
33
  const REPORTS = new Set(['done', 'partial', 'blocked'])
34
34
  const PROMPT_TIMEOUT_MS = 180000
35
- const ENGINE = 'collab-pair/1.0.8'
35
+ const ENGINE = 'collab-pair/1.2.0'
36
36
 
37
37
  /** A recoverable failure whose message is meant for the model. */
38
38
  class CollabError extends Error {}
@@ -54,6 +54,10 @@ function resolveConfig(raw) {
54
54
  addPrefix: value.addPrefix !== false,
55
55
  prefixManager: prefixText(value.prefixManager, '【项目经理】'),
56
56
  prefixWorker: prefixText(value.prefixWorker, '【员工】'),
57
+ language: value.language === 'en' ? 'en' : 'zh',
58
+ autoNudge: value.autoNudge !== false,
59
+ nudgeAfterMinutes: clampInt(value.nudgeAfterMinutes, 5, 1440, 20),
60
+ maxNudges: clampInt(value.maxNudges, 1, 20, 3),
57
61
  }
58
62
  }
59
63
 
@@ -92,26 +96,6 @@ function messageText(message) {
92
96
  return parts.join('\n').trim()
93
97
  }
94
98
 
95
- /** Human description of a turn end reason. */
96
- function reasonText(reason) {
97
- const kind = reason?.kind
98
- if (kind === 'completed') return '正常结束'
99
- if (kind === 'blocked') return '等待输入(blocked)'
100
- if (kind === 'max-tokens') return '达到输出上限'
101
- if (kind === 'interrupted') return '被中断'
102
- if (kind === 'forked') return '会话已分叉'
103
- if (kind === 'aborted') {
104
- const cause = reason?.reason?.kind
105
- if (cause === 'user') return '被用户中止'
106
- if (cause === 'parent') return '被父级中止'
107
- if (cause === 'disposed') return '会话被关闭'
108
- if (cause === 'hook') return '被钩子中止'
109
- return '被中止'
110
- }
111
- if (kind === 'error') return `出错:${reason?.error?.message ?? '未知错误'}`
112
- return typeof kind === 'string' ? kind : '未知'
113
- }
114
-
115
99
  /** Best-effort readable delivery failure. */
116
100
  function deliveryFailure(error) {
117
101
  const code = error?.code ?? error?.details?.code
@@ -152,6 +136,7 @@ function parseCommandBody(rawInput) {
152
136
  if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) throw new CollabError('参数必须是 JSON 对象。')
153
137
  return { action, args: parsed }
154
138
  }
139
+ if (!rest.startsWith('--')) return { action, args: { value: rest } }
155
140
  return { action, args: parseFlags(rest) }
156
141
  }
157
142
 
@@ -190,8 +175,289 @@ function parseFlags(text) {
190
175
  return args
191
176
  }
192
177
 
178
+ /** Localized collaboration messages. `language` in the plugin config selects one. */
179
+ const LANGUAGES = {
180
+ zh: {
181
+ idle: '空闲',
182
+ waiting: '等待回报',
183
+ finished: '已结束',
184
+ statusLabel(status) {
185
+ if (status === 'done') return '完成'
186
+ if (status === 'partial') return '部分完成'
187
+ if (status === 'blocked') return '受阻,需要决策'
188
+ if (status === 'unreported') return '未显式汇报'
189
+ return '未知'
190
+ },
191
+ reasonText(reason) {
192
+ const kind = reason?.kind
193
+ if (kind === 'completed') return '正常结束'
194
+ if (kind === 'blocked') return '等待输入(blocked)'
195
+ if (kind === 'max-tokens') return '达到输出上限'
196
+ if (kind === 'interrupted') return '被中断'
197
+ if (kind === 'forked') return '会话已分叉'
198
+ if (kind === 'aborted') {
199
+ const cause = reason?.reason?.kind
200
+ if (cause === 'user') return '被用户中止'
201
+ if (cause === 'parent') return '被父级中止'
202
+ if (cause === 'disposed') return '会话被关闭'
203
+ if (cause === 'hook') return '被钩子中止'
204
+ return '被中止'
205
+ }
206
+ if (kind === 'error') return `出错:${reason?.error?.message ?? '未知错误'}`
207
+ return typeof kind === 'string' ? kind : '未知'
208
+ },
209
+ managerRow({ label, worker, round, state, last }) {
210
+ return `- ${label}(${worker}):第 ${round} 轮 · ${state}${last === '' ? '' : ` · 最近:${last}`}`
211
+ },
212
+ moreWorkers(count) {
213
+ return `- …另有 ${count} 个员工,用 collab_status 查看`
214
+ },
215
+ managerSection({ count, rows, maxRounds, project }) {
216
+ return [
217
+ '## 双对话协作 · 你是项目经理',
218
+ ...(project ? [`项目:${project}`] : []),
219
+ `你正在协调 ${count} 个员工对话;项目目标、任务拆解与验收标准由你在对话中掌握。`,
220
+ '员工:',
221
+ ...rows,
222
+ '',
223
+ '规则:',
224
+ '- 用 `collab_dispatch` 派发任务;有多个员工时用 `worker` 指定员工(sessionId 或标题),只有一个时可省略。',
225
+ '- 需要调整某个员工的 agent 预设或模型时,用 `collab_configure`(worker 指定员工)。',
226
+ '- 收到以【协作回报】开头的消息后,继续派发,或对该员工调用 `collab_done`;`collab_status` 查看全部进度。',
227
+ '- 除非用户明确要求,不要自己执行员工的交付任务;你负责拆解、验收和决定下一步。',
228
+ `- 每个员工最多 ${maxRounds} 轮。`,
229
+ ].join('\n')
230
+ },
231
+ workerSection({ manager, round, pending, project }) {
232
+ return [
233
+ '## 双对话协作 · 你是员工',
234
+ ...(project ? [`项目:${project}`] : []),
235
+ `项目经理对话:${manager}`,
236
+ `进度:第 ${round} 轮${pending ? ',待你完成本轮任务' : ''}`,
237
+ '你负责执行项目经理派发的任务,并如实回报结果;项目目标与验收标准以派发消息为准,不要改变大方向或扩大范围。',
238
+ '',
239
+ '规则:',
240
+ '- 严格按本对话里最近一条【协作任务】执行。',
241
+ '- 完成后调用 `collab_report` 汇报:summary(交付物/结论)、status(done/partial/blocked)、details、next,然后结束本轮回复。',
242
+ '- 你的最终回复会连同汇报一起自动回传给项目经理;遇到阻塞用 blocked 写清需要什么决策。',
243
+ '- 项目经理可能连续派发多轮任务,每轮都按上述流程执行。',
244
+ ].join('\n')
245
+ },
246
+ dispatch({ round, goal, task, acceptance, marker }) {
247
+ const lines = [`【协作任务 · 第 ${round} 轮】`, '']
248
+ if (goal) lines.push(`项目目标:${goal}`, '')
249
+ lines.push(
250
+ '—— 本轮任务 ——',
251
+ task,
252
+ '',
253
+ '—— 验收标准 ——',
254
+ acceptance || '(未指定;按任务目标自行检查交付完整性)',
255
+ '',
256
+ '—— 交付要求 ——',
257
+ '1. 直接执行本轮任务,不要改变项目大方向,也不要扩大到任务之外。',
258
+ '2. 完成后调用 collab_report 汇报:summary / status(done 完成、partial 部分完成、blocked 受阻需决策)/ details / next。',
259
+ '3. 汇报后结束本轮回复;你的最终回复会作为「产出与反馈」自动回传给项目经理。',
260
+ marker,
261
+ )
262
+ return lines.join('\n')
263
+ },
264
+ report({ round, workerTitle, worker, report, reason, finalText, maxRounds, nextRound, marker }) {
265
+ const status = report === undefined ? this.statusLabel('unreported') : this.statusLabel(report.status)
266
+ const lines = [
267
+ `【协作回报 · 第 ${round} 轮】`,
268
+ `来自员工对话:${workerTitle || '(未命名对话)'}(${worker})`,
269
+ `本轮状态:${status}`,
270
+ `结束原因:${this.reasonText(reason)}`,
271
+ '',
272
+ ]
273
+ if (report !== undefined) {
274
+ lines.push('—— 员工汇报 ——', report.summary)
275
+ if (report.details) lines.push('', '细节:', report.details)
276
+ if (report.next) lines.push('', `员工建议:${report.next}`)
277
+ lines.push('')
278
+ }
279
+ lines.push(
280
+ '—— 员工最终产出 ——',
281
+ finalText || (report === undefined
282
+ ? '(本轮没有可读取的文本产出,可打开员工对话查看完整过程)'
283
+ : '(员工本轮没有额外文字总结,以上汇报即为其产出。)'),
284
+ '',
285
+ )
286
+ if (round >= maxRounds) lines.push(`⚠ 该员工已达到配置的最大轮次 ${maxRounds},无法再派发新一轮;请验收成果后调用 collab_done 收尾。`, '')
287
+ lines.push(
288
+ '—— 下一步 ——',
289
+ '请以项目经理身份审阅本轮结果:',
290
+ `- 需要继续:调用 collab_dispatch 下发第 ${nextRound} 轮任务,worker="${worker}"(可附验收标准)。`,
291
+ `- 该员工已完成:调用 collab_done,worker="${worker}",形成总结并收尾。`,
292
+ `- 需要了解过程细节:可打开员工对话 ${worker} 查看。`,
293
+ marker,
294
+ )
295
+ return lines.join('\n')
296
+ },
297
+ done({ summary, marker }) {
298
+ return [
299
+ '【协作结束】',
300
+ '项目经理已确认本项目完成,本轮协作到此结束。',
301
+ '',
302
+ `项目总结:${summary || '(无)'}`,
303
+ '',
304
+ '不需要再执行新的任务,也不要再调用协作工具;如果手上还有未完成的工作,请停止并简要说明当前状态。',
305
+ marker,
306
+ ].join('\n')
307
+ },
308
+ nudge({ worker, minutes, attempt, max }) {
309
+ return [
310
+ '【协作推进提醒】',
311
+ `员工 ${worker} 目前空闲,已经 ${minutes} 分钟没有推进(第 ${attempt}/${max} 次提醒)。`,
312
+ '',
313
+ '请继续推进:调用 `collab_dispatch` 派发下一轮,或调用 `collab_done` 对该员工收尾。',
314
+ '如果项目需要暂停,请告知用户并说明原因。',
315
+ ].join('\n')
316
+ },
317
+ },
318
+ en: {
319
+ idle: 'idle',
320
+ waiting: 'waiting for report',
321
+ finished: 'finished',
322
+ statusLabel(status) {
323
+ if (status === 'done') return 'done'
324
+ if (status === 'partial') return 'partially done'
325
+ if (status === 'blocked') return 'blocked, needs a decision'
326
+ if (status === 'unreported') return 'no explicit report'
327
+ return 'unknown'
328
+ },
329
+ reasonText(reason) {
330
+ const kind = reason?.kind
331
+ if (kind === 'completed') return 'completed'
332
+ if (kind === 'blocked') return 'blocked, waiting for input'
333
+ if (kind === 'max-tokens') return 'output limit reached'
334
+ if (kind === 'interrupted') return 'interrupted'
335
+ if (kind === 'forked') return 'conversation forked'
336
+ if (kind === 'aborted') {
337
+ const cause = reason?.reason?.kind
338
+ if (cause === 'user') return 'stopped by the user'
339
+ if (cause === 'parent') return 'stopped by the parent'
340
+ if (cause === 'disposed') return 'conversation closed'
341
+ if (cause === 'hook') return 'stopped by a hook'
342
+ return 'aborted'
343
+ }
344
+ if (kind === 'error') return `error: ${reason?.error?.message ?? 'unknown'}`
345
+ return typeof kind === 'string' ? kind : 'unknown'
346
+ },
347
+ managerRow({ label, worker, round, state, last }) {
348
+ return `- ${label} (${worker}): round ${round} · ${state}${last === '' ? '' : ` · latest: ${last}`}`
349
+ },
350
+ moreWorkers(count) {
351
+ return `- …and ${count} more workers; use collab_status to see all`
352
+ },
353
+ managerSection({ count, rows, maxRounds, project }) {
354
+ return [
355
+ '## Collaboration pair · You are the project manager',
356
+ ...(project ? [`Project: ${project}`] : []),
357
+ `You coordinate ${count} worker conversations. You own the project goal, the task breakdown, and the acceptance criteria.`,
358
+ 'Workers:',
359
+ ...rows,
360
+ '',
361
+ 'Rules:',
362
+ '- Dispatch a round with `collab_dispatch`; when several workers exist, select one with `worker` (session id or title). With a single worker you may omit it.',
363
+ '- To change a worker\'s agent preset or model, use `collab_configure` (select the worker with `worker`).',
364
+ '- When a message starting with [Collaboration report] arrives, dispatch the next round or call `collab_done` for that worker; `collab_status` shows every worker.',
365
+ '- Unless the user explicitly asks, do not do the workers\' delivery work yourself; you break down, review, and decide.',
366
+ `- At most ${maxRounds} rounds per worker.`,
367
+ ].join('\n')
368
+ },
369
+ workerSection({ manager, round, pending, project }) {
370
+ return [
371
+ '## Collaboration pair · You are a worker',
372
+ ...(project ? [`Project: ${project}`] : []),
373
+ `Manager conversation: ${manager}`,
374
+ `Progress: round ${round}${pending ? ', with a task waiting for you' : ''}`,
375
+ 'Execute the tasks the manager dispatches and report back honestly. The goal and acceptance criteria come from the dispatch message; do not change direction or expand the scope.',
376
+ '',
377
+ 'Rules:',
378
+ '- Follow the latest [Collaboration task] message in this conversation.',
379
+ '- When done, call `collab_report` with summary / status (done/partial/blocked) / details / next, then end your turn.',
380
+ '- Your final reply is relayed to the manager together with the report; use blocked and state the decision you need.',
381
+ '- The manager may dispatch further rounds; follow the same flow each time.',
382
+ ].join('\n')
383
+ },
384
+ dispatch({ round, goal, task, acceptance, marker }) {
385
+ const lines = [`[Collaboration task · Round ${round}]`, '']
386
+ if (goal) lines.push(`Project goal: ${goal}`, '')
387
+ lines.push(
388
+ '— Task —',
389
+ task,
390
+ '',
391
+ '— Acceptance criteria —',
392
+ acceptance || '(not specified; check the deliverable for completeness against the task)',
393
+ '',
394
+ '— Delivery —',
395
+ '1. Execute this round directly; do not change the project direction or expand beyond the task.',
396
+ '2. When done, call collab_report with summary / status (done, partial, blocked) / details / next.',
397
+ '3. End your turn after reporting; your final reply is relayed back to the manager as the output and feedback.',
398
+ marker,
399
+ )
400
+ return lines.join('\n')
401
+ },
402
+ report({ round, workerTitle, worker, report, reason, finalText, maxRounds, nextRound, marker }) {
403
+ const status = report === undefined ? this.statusLabel('unreported') : this.statusLabel(report.status)
404
+ const lines = [
405
+ `[Collaboration report · Round ${round}]`,
406
+ `Worker conversation: ${workerTitle || 'Unnamed'} (${worker})`,
407
+ `Status: ${status}`,
408
+ `Turn ended: ${this.reasonText(reason)}`,
409
+ '',
410
+ ]
411
+ if (report !== undefined) {
412
+ lines.push('— Worker report —', report.summary)
413
+ if (report.details) lines.push('', 'Details:', report.details)
414
+ if (report.next) lines.push('', `Worker suggestion: ${report.next}`)
415
+ lines.push('')
416
+ }
417
+ lines.push(
418
+ '— Final output —',
419
+ finalText || (report === undefined
420
+ ? '(no readable text output this round; open the worker conversation for the full process)'
421
+ : '(the worker added no text summary; the report above is its output.)'),
422
+ '',
423
+ )
424
+ if (round >= maxRounds) lines.push(`⚠ This worker reached the configured maximum of ${maxRounds} rounds and cannot receive another round; review the result and call collab_done.`, '')
425
+ lines.push(
426
+ '— Next —',
427
+ 'Review this result as the project manager:',
428
+ `- Continue: call collab_dispatch for round ${nextRound}, worker="${worker}" (acceptance optional).`,
429
+ `- This worker is done: call collab_done, worker="${worker}", with a summary.`,
430
+ `- Inspect the full process: open worker conversation ${worker}.`,
431
+ marker,
432
+ )
433
+ return lines.join('\n')
434
+ },
435
+ done({ summary, marker }) {
436
+ return [
437
+ '[Collaboration finished]',
438
+ 'The project manager confirmed this project is complete; this collaboration ends here.',
439
+ '',
440
+ `Project summary: ${summary || '(none)'}`,
441
+ '',
442
+ 'Do not start new tasks or call collaboration tools. If work is still unfinished, stop and briefly state the current status.',
443
+ marker,
444
+ ].join('\n')
445
+ },
446
+ nudge({ worker, minutes, attempt, max }) {
447
+ return [
448
+ '[Collaboration reminder]',
449
+ `Worker ${worker} is idle and nothing has progressed for ${minutes} minutes (reminder ${attempt}/${max}).`,
450
+ '',
451
+ 'Continue by calling `collab_dispatch` for the next round, or close that worker with `collab_done`.',
452
+ 'If the project should pause, tell the user and explain why.',
453
+ ].join('\n')
454
+ },
455
+ },
456
+ }
457
+
193
458
  export function apply(ctx, rawConfig) {
194
459
  const cfg = resolveConfig(rawConfig)
460
+ const L = LANGUAGES[cfg.language]
195
461
  const links = new Map()
196
462
  /** managerId -> Set<linkId>, every link the session manages (any status). */
197
463
  const byManager = new Map()
@@ -222,6 +488,16 @@ export function apply(ctx, rawConfig) {
222
488
 
223
489
  ctx.on('session/event', onSessionEvent)
224
490
 
491
+ // ------------------------------------------------------------- watchdog
492
+ let alive = true
493
+ let watchdogTimer
494
+ ctx.effect(() => () => {
495
+ alive = false
496
+ if (watchdogTimer !== undefined) clearInterval(watchdogTimer)
497
+ })
498
+ if (cfg.autoNudge) watchdogTimer = setInterval(() => { void runWatchdog() }, 60000)
499
+ setTimeout(() => { void recoverPendingLinks() }, 5000)
500
+
225
501
  registerTools()
226
502
  registerCommand()
227
503
 
@@ -278,12 +554,16 @@ export function apply(ctx, rawConfig) {
278
554
  manager: value.manager,
279
555
  worker: value.worker,
280
556
  label: typeof value.label === 'string' ? value.label : '',
557
+ mode: value.mode === 'permanent' ? 'permanent' : 'temporary',
558
+ project: typeof value.project === 'string' ? value.project : '',
281
559
  goal: typeof value.goal === 'string' ? value.goal : '',
282
560
  status,
283
561
  round: Number.isSafeInteger(value.round) && value.round >= 0 ? value.round : 0,
284
562
  pending: normalizePending(value.pending),
285
563
  lastReport: value.lastReport !== null && typeof value.lastReport === 'object' ? value.lastReport : null,
286
564
  history: Array.isArray(value.history) ? value.history.slice(-cfg.maxHistory) : [],
565
+ nudges: Number.isSafeInteger(value.nudges) && value.nudges >= 0 ? value.nudges : 0,
566
+ ...(typeof value.lastNudgeAt === 'number' ? { lastNudgeAt: value.lastNudgeAt } : {}),
287
567
  createdAt: Number.isFinite(value.createdAt) ? value.createdAt : Date.now(),
288
568
  updatedAt: Number.isFinite(value.updatedAt) ? value.updatedAt : Date.now(),
289
569
  ...(typeof value.closedAt === 'number' ? { closedAt: value.closedAt } : {}),
@@ -339,121 +619,51 @@ export function apply(ctx, rawConfig) {
339
619
  function sectionText(context) {
340
620
  const agentId = context?.agent?.id ?? context?.scope?.id
341
621
  if (typeof agentId !== 'string') return ''
342
- const managed = managerLinks(agentId, true)
622
+ const managed = usableManagerLinks(agentId)
343
623
  if (managed.length > 0) {
344
- const rows = managed.slice(0, 8).map((link) => {
345
- const state = link.pending === null ? '空闲' : '等待回报'
346
- const last = link.lastReport === null ? '' : ` · 最近:${statusLabel(link.lastReport.status)}`
347
- return `- ${link.label || '(未命名员工)'}(${link.worker}):第 ${link.round} 轮 · ${state}${last}`
348
- })
349
- if (managed.length > 8) rows.push(`- …另有 ${managed.length - 8} 个员工,用 collab_status 查看`)
350
- return [
351
- '## 双对话协作 · 你是项目经理',
352
- `你正在协调 ${managed.length} 个员工对话;项目目标、任务拆解与验收标准由你在对话中掌握。`,
353
- '员工:',
354
- ...rows,
355
- '',
356
- '规则:',
357
- '- 用 `collab_dispatch` 派发任务;有多个员工时用 `worker` 指定员工(sessionId 或标题),只有一个时可省略。',
358
- '- 需要调整某个员工的 agent 预设或模型时,用 `collab_configure`(worker 指定员工)。',
359
- '- 收到以【协作回报】开头的消息后,继续派发,或对该员工调用 `collab_done`;`collab_status` 查看全部进度。',
360
- '- 除非用户明确要求,不要自己执行员工的交付任务;你负责拆解、验收和决定下一步。',
361
- `- 每个员工最多 ${cfg.maxRounds} 轮。`,
362
- ].join('\n')
624
+ const rows = managed.slice(0, 8).map((link) => L.managerRow({
625
+ label: link.label || (cfg.language === 'en' ? '(unnamed worker)' : '(未命名员工)'),
626
+ worker: link.worker,
627
+ round: link.round,
628
+ state: link.status !== ACTIVE ? L.finished : link.pending === null ? L.idle : L.waiting,
629
+ last: link.lastReport === null ? '' : L.statusLabel(link.lastReport.status),
630
+ }))
631
+ if (managed.length > 8) rows.push(L.moreWorkers(managed.length - 8))
632
+ return L.managerSection({ count: managed.length, rows, maxRounds: cfg.maxRounds, project: managerProjectName(agentId) })
363
633
  }
364
- const link = workerLink(agentId)
634
+ const link = workerAssociation(agentId)
365
635
  if (link === undefined) return ''
366
- return [
367
- '## 双对话协作 · 你是员工',
368
- `项目经理对话:${link.manager}`,
369
- `进度:第 ${link.round} 轮${link.pending === null ? '' : ',待你完成本轮任务'}`,
370
- '你负责执行项目经理派发的任务,并如实回报结果;项目目标与验收标准以派发消息为准,不要改变大方向或扩大范围。',
371
- '',
372
- '规则:',
373
- '- 严格按本对话里最近一条【协作任务】执行。',
374
- '- 完成后调用 `collab_report` 汇报:summary(交付物/结论)、status(done/partial/blocked)、details、next,然后结束本轮回复。',
375
- '- 你的最终回复会连同汇报一起自动回传给项目经理;遇到阻塞用 blocked 写清需要什么决策。',
376
- '- 项目经理可能连续派发多轮任务,每轮都按上述流程执行。',
377
- ].join('\n')
636
+ return L.workerSection({ manager: link.manager, round: link.round, pending: link.pending !== null, project: link.project })
378
637
  }
379
638
 
380
639
  /** Render one dispatch message for a worker. */
381
640
  function dispatchText(link, round, task, acceptance) {
382
- const lines = [`【协作任务 · 第 ${round} 轮】`, '']
383
- if (link.goal) lines.push(`项目目标:${link.goal}`, '')
384
- lines.push(
385
- '—— 本轮任务 ——',
386
- task,
387
- '',
388
- '—— 验收标准 ——',
389
- acceptance || '(未指定;按任务目标自行检查交付完整性)',
390
- '',
391
- '—— 交付要求 ——',
392
- '1. 直接执行本轮任务,不要改变项目大方向,也不要扩大到任务之外。',
393
- '2. 完成后调用 collab_report 汇报:summary / status(done 完成、partial 部分完成、blocked 受阻需决策)/ details / next。',
394
- '3. 汇报后结束本轮回复;你的最终回复会作为「产出与反馈」自动回传给项目经理。',
395
- `[[collab:${link.id}:r${round}]]`,
396
- )
397
- return lines.join('\n')
641
+ return L.dispatch({ round, goal: link.goal, task, acceptance, marker: `[[collab:${link.id}:r${round}]]` })
398
642
  }
399
643
 
400
644
  /** Render the report the manager receives. */
401
645
  function reportText({ link, pending, report, finalText, reason, workerTitle }) {
402
- const status = report === undefined ? '未显式汇报' : statusLabel(report.status)
403
- const lines = [
404
- `【协作回报 · 第 ${pending.round} 轮】`,
405
- `来自员工对话:${workerTitle || link.label || '(未命名对话)'}(${link.worker})`,
406
- `本轮状态:${status}`,
407
- `结束原因:${reasonText(reason)}`,
408
- '',
409
- ]
410
- if (report !== undefined) {
411
- lines.push('—— 员工汇报 ——', report.summary)
412
- if (report.details) lines.push('', '细节:', report.details)
413
- if (report.next) lines.push('', `员工建议:${report.next}`)
414
- lines.push('')
415
- }
416
- lines.push(
417
- '—— 员工最终产出 ——',
418
- finalText || (report === undefined
419
- ? '(本轮没有可读取的文本产出,可打开员工对话查看完整过程)'
420
- : '(员工本轮没有额外文字总结,以上汇报即为其产出。)'),
421
- '',
422
- )
423
- if (link.round >= cfg.maxRounds) {
424
- lines.push(`⚠ 该员工已达到配置的最大轮次 ${cfg.maxRounds},无法再派发新一轮;请验收成果后调用 collab_done 收尾。`, '')
425
- }
426
- lines.push(
427
- '—— 下一步 ——',
428
- '请以项目经理身份审阅本轮结果:',
429
- `- 需要继续:调用 collab_dispatch 下发第 ${link.round + 1} 轮任务,worker="${link.worker}"(可附验收标准)。`,
430
- `- 该员工已完成:调用 collab_done,worker="${link.worker}",形成总结并收尾。`,
431
- `- 需要了解过程细节:可打开员工对话 ${link.worker} 查看。`,
432
- `[[collab:${link.id}:r${pending.round}:report]]`,
433
- )
434
- return lines.join('\n')
646
+ return L.report({
647
+ round: pending.round,
648
+ workerTitle,
649
+ worker: link.worker,
650
+ report,
651
+ reason,
652
+ finalText,
653
+ maxRounds: cfg.maxRounds,
654
+ nextRound: link.round + 1,
655
+ marker: `[[collab:${link.id}:r${pending.round}:report]]`,
656
+ })
435
657
  }
436
658
 
437
659
  /** Render the closing message for the worker. */
438
660
  function doneText(link, summary) {
439
- return [
440
- '【协作结束】',
441
- '项目经理已确认本项目完成,本轮协作到此结束。',
442
- '',
443
- `项目总结:${summary || '(无)'}`,
444
- '',
445
- '不需要再执行新的任务,也不要再调用协作工具;如果手上还有未完成的工作,请停止并简要说明当前状态。',
446
- `[[collab:${link.id}:done]]`,
447
- ].join('\n')
661
+ return L.done({ summary, marker: `[[collab:${link.id}:done]]` })
448
662
  }
449
663
 
450
- /** Chinese label for a report status. */
664
+ /** Localized label for a report status. */
451
665
  function statusLabel(status) {
452
- if (status === 'done') return '完成'
453
- if (status === 'partial') return '部分完成'
454
- if (status === 'blocked') return '受阻,需要决策'
455
- if (status === 'unreported') return '未显式汇报'
456
- return '未知'
666
+ return L.statusLabel(status)
457
667
  }
458
668
 
459
669
  // -------------------------------------------------------------- delivery
@@ -634,6 +844,44 @@ export function apply(ctx, rawConfig) {
634
844
  return linkId === undefined ? undefined : links.get(linkId)
635
845
  }
636
846
 
847
+ /** The worker link a session still belongs to, including a finished permanent one. */
848
+ function workerAssociation(sessionId) {
849
+ const active = workerLink(sessionId)
850
+ if (active !== undefined) return active
851
+ for (const link of links.values()) {
852
+ if (link.worker === sessionId && link.mode === 'permanent') return link
853
+ }
854
+ return undefined
855
+ }
856
+
857
+ /** Links a manager can still act on: active ones plus permanent associations. */
858
+ function usableManagerLinks(managerId) {
859
+ return managerLinks(managerId).filter((link) => link.status === ACTIVE || link.mode === 'permanent')
860
+ }
861
+
862
+ /** Whether a manager still has a usable worker association. */
863
+ function managerHasWork(managerId) {
864
+ return usableManagerLinks(managerId).length > 0
865
+ }
866
+
867
+ /** The project name shared by one manager's links, or ''. */
868
+ function managerProjectName(managerId) {
869
+ for (const link of managerLinks(managerId)) {
870
+ if (typeof link.project === 'string' && link.project !== '') return link.project
871
+ }
872
+ return ''
873
+ }
874
+
875
+ /** Rename the project shared by every link of one manager. */
876
+ async function renameProject(managerId, name) {
877
+ for (const link of managerLinks(managerId)) {
878
+ if (link.project === name) continue
879
+ link.project = name
880
+ link.updatedAt = Date.now()
881
+ await persist(link)
882
+ }
883
+ }
884
+
637
885
  /** Index one link by its manager and (while active) its worker. */
638
886
  function index(link) {
639
887
  links.set(link.id, link)
@@ -726,20 +974,20 @@ export function apply(ctx, rawConfig) {
726
974
 
727
975
  /** Resolve one of a manager's active workers by id, link id, or label. */
728
976
  function resolveManagedLink(managerId, selector) {
729
- const active = managerLinks(managerId, true)
730
- if (active.length === 0) throw new CollabError('当前对话没有进行中的员工协作;先用 collab_link 关联一个员工。')
977
+ const candidates = usableManagerLinks(managerId)
978
+ if (candidates.length === 0) throw new CollabError('当前对话没有可用的员工协作;先用 collab_link 关联一个员工。')
731
979
  const text = typeof selector === 'string' ? selector.trim() : ''
732
980
  if (text === '') {
733
- if (active.length === 1) return active[0]
734
- throw new CollabError(`当前对话有 ${active.length} 个员工,请用 worker 参数指定:\n${workerList(active)}`)
981
+ if (candidates.length === 1) return candidates[0]
982
+ throw new CollabError(`当前对话有 ${candidates.length} 个员工,请用 worker 参数指定:\n${workerList(candidates)}`)
735
983
  }
736
- const exact = active.find((link) => link.worker === text || link.id === text)
984
+ const exact = candidates.find((link) => link.worker === text || link.id === text)
737
985
  if (exact !== undefined) return exact
738
986
  const needle = text.toLowerCase()
739
- const matches = active.filter((link) => typeof link.label === 'string' && link.label !== '' && link.label.toLowerCase().includes(needle))
987
+ const matches = candidates.filter((link) => typeof link.label === 'string' && link.label !== '' && link.label.toLowerCase().includes(needle))
740
988
  if (matches.length === 1) return matches[0]
741
989
  if (matches.length > 1) throw new CollabError(`"${text}" 匹配到多个员工,请用 sessionId 指定:\n${workerList(matches)}`)
742
- throw new CollabError(`没有找到员工 "${text}"。当前员工:\n${workerList(active)}`)
990
+ throw new CollabError(`没有找到员工 "${text}"。当前员工:\n${workerList(candidates)}`)
743
991
  }
744
992
 
745
993
  /** Global board: every link, active first, with the labels a human needs. */
@@ -766,10 +1014,14 @@ export function apply(ctx, rawConfig) {
766
1014
  worker: link.worker,
767
1015
  workerTitle: workerTitle ?? null,
768
1016
  status: link.status,
1017
+ mode: link.mode,
1018
+ project: link.project || '',
769
1019
  workerLive: workerAgent !== undefined,
770
1020
  workerRunning: workerAgent !== undefined && workerAgent.status === 'running',
771
1021
  managerRunning: managerAgent !== undefined && managerAgent.status === 'running',
772
1022
  round: link.round,
1023
+ nudges: link.nudges,
1024
+ ...(link.lastNudgeAt === undefined ? {} : { lastNudgeAt: isoTime(link.lastNudgeAt) }),
773
1025
  waitedSeconds: link.pending === null ? null : Math.max(0, Math.round((Date.now() - link.pending.dispatchedAt) / 1000)),
774
1026
  pending: link.pending === null ? null : {
775
1027
  round: link.pending.round,
@@ -794,6 +1046,8 @@ export function apply(ctx, rawConfig) {
794
1046
  ok: true,
795
1047
  generatedAt: isoTime(Date.now()),
796
1048
  maxRounds: cfg.maxRounds,
1049
+ maxNudges: cfg.maxNudges,
1050
+ language: cfg.language,
797
1051
  activeCount: rows.filter((row) => row.status === ACTIVE).length,
798
1052
  totalCount: rows.length,
799
1053
  links: rows,
@@ -801,7 +1055,16 @@ export function apply(ctx, rawConfig) {
801
1055
  }
802
1056
 
803
1057
  /** Send one round to the worker and record it as pending. */
804
- async function dispatchRound(link, task, acceptance, signal, force) { if (link.status !== ACTIVE) throw new CollabError(`与该员工的协作已结束(${link.status}),不能继续派发。`)
1058
+ async function dispatchRound(link, task, acceptance, signal, force) {
1059
+ if (link.status !== ACTIVE) {
1060
+ if (link.mode === 'permanent' && link.status === DONE) {
1061
+ link.status = ACTIVE
1062
+ delete link.closedAt
1063
+ index(link)
1064
+ } else {
1065
+ throw new CollabError(`与该员工的协作已结束(${link.status}),不能继续派发。`)
1066
+ }
1067
+ }
805
1068
  if (link.pending !== null && !force) {
806
1069
  throw new CollabError(`第 ${link.pending.round} 轮仍在等待该员工回报,不要重复派发;需要覆盖请传 force=true。`)
807
1070
  }
@@ -821,6 +1084,8 @@ export function apply(ctx, rawConfig) {
821
1084
  dispatchedAt: Date.now(),
822
1085
  report: null,
823
1086
  }
1087
+ link.nudges = 0
1088
+ delete link.lastNudgeAt
824
1089
  link.updatedAt = Date.now()
825
1090
  await persist(link)
826
1091
  try {
@@ -849,6 +1114,8 @@ export function apply(ctx, rawConfig) {
849
1114
  if (workerTitle !== undefined && workerTitle !== current.label) current.label = workerTitle
850
1115
  const status = report?.status ?? 'unreported'
851
1116
  current.pending = null
1117
+ current.nudges = 0
1118
+ delete current.lastNudgeAt
852
1119
  current.lastReport = {
853
1120
  round: pending.round,
854
1121
  status,
@@ -856,7 +1123,7 @@ export function apply(ctx, rawConfig) {
856
1123
  details: report?.details ?? '',
857
1124
  next: report?.next ?? '',
858
1125
  text: finalText,
859
- turnReason: reasonText(reason),
1126
+ turnReason: L.reasonText(reason),
860
1127
  relayedAt: Date.now(),
861
1128
  relayRequestId: `cp-${current.id}-r${pending.round}-to-manager`,
862
1129
  }
@@ -873,24 +1140,102 @@ export function apply(ctx, rawConfig) {
873
1140
  current.updatedAt = Date.now()
874
1141
  await persist(current)
875
1142
  if (!cfg.autoRelay) return
1143
+ const text = reportText({ link: current, pending, report, finalText, reason, workerTitle })
1144
+ const relayRequestId = current.lastReport.relayRequestId
876
1145
  try {
877
- await deliver(
878
- current.manager,
879
- reportText({ link: current, pending, report, finalText, reason, workerTitle }),
880
- current.lastReport.relayRequestId,
881
- 'queue',
882
- AbortSignal.timeout(PROMPT_TIMEOUT_MS),
883
- )
1146
+ await deliver(current.manager, text, relayRequestId, 'queue', AbortSignal.timeout(PROMPT_TIMEOUT_MS))
884
1147
  } catch (error) {
885
1148
  current.lastReport.deliveryError = String(error instanceof Error ? error.message : error)
886
1149
  await persist(current)
887
1150
  ctx.logger.warn(`collab-pair: delivering round ${pending.round} for ${current.worker} to the manager failed: ${String(error)}`)
1151
+ // One bounded retry keeps an unattended run alive across a transient failure.
1152
+ setTimeout(() => {
1153
+ if (!alive) return
1154
+ void deliver(current.manager, text, relayRequestId, 'queue', AbortSignal.timeout(PROMPT_TIMEOUT_MS))
1155
+ .then(async () => {
1156
+ if (current.lastReport !== null && current.lastReport.deliveryError !== undefined) {
1157
+ delete current.lastReport.deliveryError
1158
+ await persist(current)
1159
+ }
1160
+ })
1161
+ .catch((retryError) => {
1162
+ ctx.logger.warn(`collab-pair: relay retry for ${current.id} failed: ${String(retryError)}`)
1163
+ })
1164
+ }, 60000)
1165
+ }
1166
+ }
1167
+
1168
+ /**
1169
+ * Wake an idle manager when a worker link makes no progress for a long time,
1170
+ * so an unattended project does not stall silently. Bounded per link.
1171
+ */
1172
+ async function runWatchdog() {
1173
+ if (!alive || !cfg.autoNudge) return
1174
+ const now = Date.now()
1175
+ for (const link of [...links.values()]) {
1176
+ if (!alive) return
1177
+ if (link.status !== ACTIVE) continue
1178
+ if (link.pending !== null) continue
1179
+ if (link.nudges >= cfg.maxNudges) continue
1180
+ const since = link.lastNudgeAt ?? link.updatedAt
1181
+ if (now - since < cfg.nudgeAfterMinutes * 60000) continue
1182
+ const managerAgent = ctx.agents.get(link.manager)
1183
+ if (managerAgent !== undefined && managerAgent.status === 'running') continue
1184
+ const workerAgent = ctx.agents.get(link.worker)
1185
+ if (workerAgent !== undefined && workerAgent.status === 'running') continue
1186
+ const minutes = Math.max(1, Math.round((now - since) / 60000))
1187
+ const attempt = link.nudges + 1
1188
+ link.nudges = attempt
1189
+ link.lastNudgeAt = now
1190
+ link.updatedAt = now
1191
+ await persist(link)
1192
+ try {
1193
+ await deliver(
1194
+ link.manager,
1195
+ L.nudge({ worker: link.label || link.worker, minutes, attempt, max: cfg.maxNudges }),
1196
+ `cp-${link.id}-nudge-${attempt}`,
1197
+ 'queue',
1198
+ AbortSignal.timeout(PROMPT_TIMEOUT_MS),
1199
+ )
1200
+ } catch (error) {
1201
+ ctx.logger.warn(`collab-pair: nudge for ${link.id} failed: ${String(error)}`)
1202
+ }
1203
+ }
1204
+ }
1205
+
1206
+ /**
1207
+ * Recover a relay that was missed while the plugin was reloading: a live
1208
+ * worker may have finished a dispatched round before the listener returned.
1209
+ * Runs once shortly after activation.
1210
+ */
1211
+ async function recoverPendingLinks() {
1212
+ if (!alive) return
1213
+ for (const link of [...links.values()]) {
1214
+ if (!alive) return
1215
+ if (link.status !== ACTIVE || link.pending === null) continue
1216
+ const session = ctx.sessions.get(link.worker)
1217
+ if (session === undefined) continue
1218
+ const all = session.ownEvents()
1219
+ for (let index = all.length - 1; index >= 0; index--) {
1220
+ const event = all[index]
1221
+ if (event.type !== 'turn/end') continue
1222
+ let scoped
1223
+ try {
1224
+ scoped = turnEvents(session, event.data?.turn, event.seq)
1225
+ } catch {
1226
+ scoped = undefined
1227
+ }
1228
+ if (scoped === undefined) continue
1229
+ if (!claimedBy(scoped, { ...link.pending, linkId: link.id })) continue
1230
+ const snapshot = { ...link.pending }
1231
+ enqueueRelay(link.id, () => relayReport(link, snapshot, scoped, event.data?.reason))
1232
+ break
1233
+ }
888
1234
  }
889
1235
  }
890
1236
 
891
1237
  /** Serialize relays per link so one turn cannot relay twice. */
892
- function enqueueRelay(linkId, run) {
893
- const previous = relays.get(linkId) ?? Promise.resolve()
1238
+ function enqueueRelay(linkId, run) { const previous = relays.get(linkId) ?? Promise.resolve()
894
1239
  const next = previous.then(run, run).catch((error) => {
895
1240
  ctx.logger.warn(`collab-pair: relay for ${linkId} failed: ${String(error)}`)
896
1241
  })
@@ -1010,7 +1355,7 @@ export function apply(ctx, rawConfig) {
1010
1355
  .filter((row) => query === '' || (row.title ?? '').toLowerCase().includes(query) || row.sessionId.toLowerCase().includes(query))
1011
1356
  .slice(0, limit)
1012
1357
  .map((row) => {
1013
- const worker = workerLink(row.sessionId)
1358
+ const worker = workerAssociation(row.sessionId)
1014
1359
  const managed = managerLinks(row.sessionId, true)
1015
1360
  return {
1016
1361
  sessionId: row.sessionId,
@@ -1028,7 +1373,7 @@ export function apply(ctx, rawConfig) {
1028
1373
  ok: true,
1029
1374
  current: {
1030
1375
  sessionId: agent.id,
1031
- role: managerLinks(agent.id, true).length > 0 ? 'manager' : workerLink(agent.id) === undefined ? null : 'worker',
1376
+ role: managerHasWork(agent.id) ? 'manager' : workerAssociation(agent.id) === undefined ? null : 'worker',
1032
1377
  },
1033
1378
  sessions,
1034
1379
  note: sessions.length === 0
@@ -1041,12 +1386,14 @@ export function apply(ctx, rawConfig) {
1041
1386
  toolExecutors.link = register({
1042
1387
  name: 'collab_link',
1043
1388
  description:
1044
- '把当前对话与另一个对话关联:role=manager(默认)表示当前对话是项目经理、对方成为新的员工;一个项目经理可以关联多个员工。role=worker 表示当前对话成为对方的员工。peer 传 sessionId、标题关键词,或 "new"(新建一个员工对话)。',
1389
+ '把当前对话与另一个对话关联:role=manager(默认)表示当前对话是项目经理、对方成为新的员工;一个项目经理可以关联多个员工。role=worker 表示当前对话成为对方的员工。mode=temporary(默认,完成即解绑)或 permanent(一直关联直到人工解除)。peer 传 sessionId、标题关键词,或 "new"(新建一个员工对话)。',
1045
1390
  parameters: {
1046
1391
  type: 'object',
1047
1392
  properties: {
1048
1393
  peer: { type: 'string', description: 'sessionId、标题关键词,或 "new"。' },
1049
1394
  role: { type: 'string', enum: ['manager', 'worker'], description: '当前对话的角色,默认 manager。' },
1395
+ mode: { type: 'string', enum: ['temporary', 'permanent'], description: '关联模式:temporary 完成后自动解绑(默认),permanent 保留到人工解除。' },
1396
+ project: { type: 'string', description: '可选:项目名。同一个项目经理的员工会归到同一个项目,不同项目经理的项目彼此独立。' },
1050
1397
  goal: { type: 'string', description: '可选:项目总目标;不填时由项目经理在对话中掌握。' },
1051
1398
  task: { type: 'string', description: '可选:关联成功后立即派发给该员工的第一轮任务。' },
1052
1399
  acceptance: { type: 'string', description: '可选:第一轮任务的验收标准。' },
@@ -1058,14 +1405,18 @@ export function apply(ctx, rawConfig) {
1058
1405
  const agent = requireAgent(exec)
1059
1406
  const role = args?.role === 'worker' ? 'worker' : 'manager'
1060
1407
  const managed = managerLinks(agent.id, true)
1061
- const ownWorker = workerLink(agent.id)
1408
+ const ownWorker = workerAssociation(agent.id)
1409
+ if (workerLink(agent.id) !== undefined) {
1410
+ throw new CollabError(`当前对话已经是协作 ${ownWorker?.id ?? ''} 的员工,不能再加入其他协作;请先 collab_unlink。`)
1411
+ }
1062
1412
  if (ownWorker !== undefined) {
1063
- throw new CollabError(`当前对话已经是协作 ${ownWorker.id} 的员工,不能再加入其他协作;请先 collab_unlink。`)
1413
+ throw new CollabError(`当前对话已永久关联到协作 ${ownWorker.id}(已结束);请先 collab_unlink。`)
1064
1414
  }
1065
1415
  if (role === 'worker' && managed.length > 0) {
1066
1416
  throw new CollabError(`当前对话正在管理 ${managed.length} 个员工,不能同时作为别人的员工。`)
1067
1417
  }
1068
1418
  const goal = typeof args?.goal === 'string' ? args.goal.trim() : ''
1419
+ const requestedProject = typeof args?.project === 'string' ? args.project.trim() : ''
1069
1420
  let peerId
1070
1421
  let peerTitle
1071
1422
  const resolved = await resolvePeer(args?.peer, exec.signal)
@@ -1076,7 +1427,7 @@ export function apply(ctx, rawConfig) {
1076
1427
  peerTitle = resolved.title
1077
1428
  }
1078
1429
  if (peerId === agent.id) throw new CollabError('不能把对话与它自己关联。')
1079
- if (workerLink(peerId) !== undefined) {
1430
+ if (workerAssociation(peerId) !== undefined) {
1080
1431
  throw new CollabError(`目标对话 ${peerId} 已经是另一个协作的员工,请先解除那边的关联。`)
1081
1432
  }
1082
1433
  if (managerLinks(peerId, true).length > 0) {
@@ -1084,12 +1435,19 @@ export function apply(ctx, rawConfig) {
1084
1435
  }
1085
1436
  const manager = role === 'manager' ? agent.id : peerId
1086
1437
  const worker = role === 'manager' ? peerId : agent.id
1438
+ let project = requestedProject || managerProjectName(manager)
1439
+ if (project === '') {
1440
+ const managerTitle = await titleOf(manager)
1441
+ if (typeof managerTitle === 'string') project = stripKnownPrefix(managerTitle)
1442
+ }
1087
1443
  const link = {
1088
1444
  v: 1,
1089
1445
  id: `cp-${randomUUID().slice(0, 8)}`,
1090
1446
  manager,
1091
1447
  worker,
1092
1448
  label: role === 'manager' ? (typeof peerTitle === 'string' ? peerTitle : '') : '',
1449
+ mode: args?.mode === 'permanent' ? 'permanent' : 'temporary',
1450
+ project,
1093
1451
  goal,
1094
1452
  status: ACTIVE,
1095
1453
  round: 0,
@@ -1101,6 +1459,7 @@ export function apply(ctx, rawConfig) {
1101
1459
  }
1102
1460
  index(link)
1103
1461
  await persist(link)
1462
+ if (project !== '') await renameProject(manager, project)
1104
1463
  await applyPrefix(manager, cfg.prefixManager)
1105
1464
  await applyPrefix(worker, cfg.prefixWorker)
1106
1465
  let receipt = null
@@ -1122,6 +1481,7 @@ export function apply(ctx, rawConfig) {
1122
1481
  ok: true,
1123
1482
  linkId: link.id,
1124
1483
  role,
1484
+ mode: link.mode,
1125
1485
  manager,
1126
1486
  worker: { sessionId: worker, title: workerTitle ?? null },
1127
1487
  goal,
@@ -1129,8 +1489,8 @@ export function apply(ctx, rawConfig) {
1129
1489
  receipt,
1130
1490
  message: role === 'manager'
1131
1491
  ? (receipt === null
1132
- ? `已关联员工 ${worker}${managedNow > 1 ? `(当前共 ${managedNow} 个员工)` : ''}。用 collab_dispatch 派发任务。`
1133
- : `已关联员工 ${worker}${managedNow > 1 ? `(当前共 ${managedNow} 个员工)` : ''},第一轮任务已派发。`)
1492
+ ? `已关联员工 ${worker}${link.mode === 'permanent' ? '(永久关联)' : '(临时关联,完成即解绑)'}${managedNow > 1 ? `,当前共 ${managedNow} 个员工` : ''}。用 collab_dispatch 派发任务。`
1493
+ : `已关联员工 ${worker}${link.mode === 'permanent' ? '(永久关联)' : '(临时关联,完成即解绑)'}${managedNow > 1 ? `,当前共 ${managedNow} 个员工` : ''},第一轮任务已派发。`)
1134
1494
  : '协作已建立,你被设为员工角色;项目经理派发任务后会收到【协作任务】消息。',
1135
1495
  }
1136
1496
  },
@@ -1165,7 +1525,7 @@ export function apply(ctx, rawConfig) {
1165
1525
  message: `第 ${sent.round} 轮任务已派发给员工 ${link.worker}。该员工完成后,产出与反馈会自动作为用户消息回到本对话。`,
1166
1526
  }
1167
1527
  },
1168
- when: ({ agent }) => managerLinks(agent.id, true).length > 0,
1528
+ when: ({ agent }) => managerHasWork(agent.id),
1169
1529
  })
1170
1530
 
1171
1531
  toolExecutors.report = register({
@@ -1217,10 +1577,10 @@ export function apply(ctx, rawConfig) {
1217
1577
  async execute(_args, exec) {
1218
1578
  const agent = requireAgent(exec)
1219
1579
  const managed = managerLinks(agent.id)
1220
- const active = managed.filter((link) => link.status === ACTIVE)
1221
- if (active.length > 0) {
1580
+ const visible = managed.filter((link) => link.status === ACTIVE || link.mode === 'permanent')
1581
+ if (visible.length > 0) {
1222
1582
  const workers = []
1223
- for (const link of managed) {
1583
+ for (const link of visible) {
1224
1584
  const title = await titleOf(link.worker)
1225
1585
  if (title !== undefined && title !== link.label) link.label = title
1226
1586
  workers.push({
@@ -1228,6 +1588,8 @@ export function apply(ctx, rawConfig) {
1228
1588
  worker: link.worker,
1229
1589
  title: title ?? (link.label || null),
1230
1590
  status: link.status,
1591
+ mode: link.mode,
1592
+ project: link.project || null,
1231
1593
  round: link.round,
1232
1594
  pending: link.pending === null
1233
1595
  ? null
@@ -1259,21 +1621,24 @@ export function apply(ctx, rawConfig) {
1259
1621
  storage: storageState,
1260
1622
  ...(storageError === null ? {} : { storageError }),
1261
1623
  engine: ENGINE,
1624
+ language: cfg.language,
1262
1625
  role: 'manager',
1626
+ project: managerProjectName(agent.id) || null,
1263
1627
  manager: { sessionId: agent.id, title: (await titleOf(agent.id)) ?? null },
1264
1628
  maxRounds: cfg.maxRounds,
1265
- activeCount: active.length,
1629
+ activeCount: visible.filter((link) => link.status === ACTIVE).length,
1266
1630
  totalCount: managed.length,
1267
1631
  workers,
1268
1632
  }
1269
1633
  }
1270
- const link = workerLink(agent.id)
1634
+ const link = workerAssociation(agent.id)
1271
1635
  if (link === undefined) {
1272
1636
  return {
1273
1637
  linked: false,
1274
1638
  storage: storageState,
1275
1639
  ...(storageError === null ? {} : { storageError }),
1276
1640
  engine: ENGINE,
1641
+ language: cfg.language,
1277
1642
  hint: '当前对话没有协作关联。用 collab_sessions 查看可关联的对话,再用 collab_link 建立关联(peer="new" 可新建员工对话)。',
1278
1643
  }
1279
1644
  }
@@ -1283,8 +1648,11 @@ export function apply(ctx, rawConfig) {
1283
1648
  storage: storageState,
1284
1649
  ...(storageError === null ? {} : { storageError }),
1285
1650
  engine: ENGINE,
1651
+ language: cfg.language,
1286
1652
  linkId: link.id,
1287
1653
  role: 'worker',
1654
+ mode: link.mode,
1655
+ project: link.project || null,
1288
1656
  manager: { sessionId: link.manager, title: managerTitle ?? null },
1289
1657
  goal: link.goal || null,
1290
1658
  status: link.status,
@@ -1369,13 +1737,34 @@ export function apply(ctx, rawConfig) {
1369
1737
  message: '配置已应用;该员工下一轮会按新配置运行。',
1370
1738
  }
1371
1739
  },
1372
- when: ({ agent }) => managerLinks(agent.id, true).length > 0,
1740
+ when: ({ agent }) => managerHasWork(agent.id),
1741
+ })
1742
+
1743
+ toolExecutors.project = register({
1744
+ name: 'collab_project',
1745
+ description:
1746
+ '(仅项目经理)设置或修改当前项目名。项目名用于把该项目经理的员工归到同一个项目;不同项目经理的项目彼此独立。',
1747
+ parameters: {
1748
+ type: 'object',
1749
+ properties: { name: { type: 'string', description: '新的项目名,不能为空。' } },
1750
+ required: ['name'],
1751
+ },
1752
+ async execute(args, exec) {
1753
+ const agent = requireAgent(exec)
1754
+ const name = typeof args?.name === 'string' ? args.name.trim() : ''
1755
+ if (name === '') throw new CollabError('项目名不能为空。')
1756
+ const existing = managerLinks(agent.id)
1757
+ if (existing.length === 0) throw new CollabError('当前对话还没有关联员工;先 collab_link 再设置项目名。')
1758
+ await renameProject(agent.id, name)
1759
+ return { ok: true, project: name, workers: existing.length }
1760
+ },
1761
+ when: ({ agent }) => managerLinks(agent.id).length > 0,
1373
1762
  })
1374
1763
 
1375
1764
  toolExecutors.done = register({
1376
1765
  name: 'collab_done',
1377
1766
  description:
1378
- '(仅项目经理)宣布某个员工的项目完成:记录总结并结束与该员工的协作。有多个员工时用 worker 指定;all=true 结束全部员工。请在验收通过后调用。',
1767
+ '(仅项目经理)宣布某个员工的项目完成:记录总结并结束本轮协作。临时关联会同时自动解绑;永久关联保留到 collab_unlink。有多个员工时用 worker 指定;all=true 结束全部进行中的员工。请在验收通过后调用。',
1379
1768
  parameters: {
1380
1769
  type: 'object',
1381
1770
  properties: {
@@ -1402,8 +1791,10 @@ export function apply(ctx, rawConfig) {
1402
1791
  throw new CollabError(`当前对话有 ${active.length} 个员工,请用 worker 指定或传 all=true:\n${workerList(active)}`)
1403
1792
  }
1404
1793
  const closed = []
1794
+ const removed = []
1405
1795
  const notified = []
1406
1796
  for (const link of targets) {
1797
+ const temporary = link.mode !== 'permanent'
1407
1798
  link.status = DONE
1408
1799
  link.pending = null
1409
1800
  link.finalSummary = clip(summary, 4000)
@@ -1411,8 +1802,7 @@ export function apply(ctx, rawConfig) {
1411
1802
  link.updatedAt = Date.now()
1412
1803
  index(link)
1413
1804
  await persist(link)
1414
- await clearPrefix(link.worker)
1415
- closed.push({ linkId: link.id, worker: link.worker })
1805
+ closed.push({ linkId: link.id, worker: link.worker, mode: link.mode })
1416
1806
  if (cfg.notifyWorkerOnDone) {
1417
1807
  try {
1418
1808
  await deliver(link.worker, doneText(link, link.finalSummary), `cp-${link.id}-done-to-worker`, 'queue', AbortSignal.timeout(PROMPT_TIMEOUT_MS))
@@ -1421,16 +1811,24 @@ export function apply(ctx, rawConfig) {
1421
1811
  ctx.logger.warn(`collab-pair: notifying ${link.worker} of completion failed: ${String(error)}`)
1422
1812
  }
1423
1813
  }
1814
+ if (temporary) {
1815
+ await forget(link)
1816
+ await clearPrefix(link.worker)
1817
+ removed.push({ linkId: link.id, worker: link.worker })
1818
+ }
1424
1819
  }
1425
- if (managerLinks(agent.id, true).length === 0) await clearPrefix(agent.id)
1820
+ if (managerLinks(agent.id).length === 0) await clearPrefix(agent.id)
1426
1821
  return {
1427
1822
  ok: true,
1428
1823
  closed,
1824
+ removed,
1429
1825
  workerNotified: notified,
1430
- message: `已结束 ${closed.length} 个员工协作;历史记录仍保留在 collab_status 中。`,
1826
+ message: removed.length === 0
1827
+ ? `已结束 ${closed.length} 个员工协作(永久关联保留,可继续派发或手动解除)。`
1828
+ : `已结束 ${closed.length} 个员工协作,其中 ${removed.length} 个临时关联已自动解绑。`,
1431
1829
  }
1432
1830
  },
1433
- when: ({ agent }) => managerLinks(agent.id, true).length > 0,
1831
+ when: ({ agent }) => managerHasWork(agent.id),
1434
1832
  })
1435
1833
 
1436
1834
  toolExecutors.unlink = register({
@@ -1448,7 +1846,7 @@ export function apply(ctx, rawConfig) {
1448
1846
  },
1449
1847
  async execute(args, exec) {
1450
1848
  const agent = requireAgent(exec)
1451
- const ownWorker = workerLink(agent.id)
1849
+ const ownWorker = workerAssociation(agent.id)
1452
1850
  if (ownWorker !== undefined) {
1453
1851
  let notified = false
1454
1852
  if (args?.notify === true) {
@@ -1464,20 +1862,20 @@ export function apply(ctx, rawConfig) {
1464
1862
  const managerId = ownWorker.manager
1465
1863
  await forget(ownWorker)
1466
1864
  await clearPrefix(agent.id)
1467
- if (managerLinks(managerId, true).length === 0) await clearPrefix(managerId)
1865
+ if (managerLinks(managerId).length === 0) await clearPrefix(managerId)
1468
1866
  return { ok: true, removed: [{ linkId, worker: agent.id }], peerNotified: notified }
1469
1867
  }
1470
- const active = managerLinks(agent.id, true)
1471
- if (active.length === 0) throw new CollabError('当前对话没有进行中的员工协作,无需解除。')
1868
+ const candidates = usableManagerLinks(agent.id)
1869
+ if (candidates.length === 0) throw new CollabError('当前对话没有可解除的员工协作。')
1472
1870
  let targets
1473
1871
  if (args?.all === true) {
1474
- targets = active
1872
+ targets = candidates
1475
1873
  } else if (typeof args?.worker === 'string' && args.worker.trim() !== '') {
1476
1874
  targets = [resolveManagedLink(agent.id, args.worker)]
1477
- } else if (active.length === 1) {
1478
- targets = [active[0]]
1875
+ } else if (candidates.length === 1) {
1876
+ targets = [candidates[0]]
1479
1877
  } else {
1480
- throw new CollabError(`当前对话有 ${active.length} 个员工,请用 worker 指定或传 all=true:\n${workerList(active)}`)
1878
+ throw new CollabError(`当前对话有 ${candidates.length} 个员工,请用 worker 指定或传 all=true:\n${workerList(candidates)}`)
1481
1879
  }
1482
1880
  const removed = []
1483
1881
  let notified = 0
@@ -1495,10 +1893,10 @@ export function apply(ctx, rawConfig) {
1495
1893
  await forget(link)
1496
1894
  await clearPrefix(link.worker)
1497
1895
  }
1498
- if (managerLinks(agent.id, true).length === 0) await clearPrefix(agent.id)
1896
+ if (managerLinks(agent.id).length === 0) await clearPrefix(agent.id)
1499
1897
  return { ok: true, removed, peerNotified: notified > 0 }
1500
1898
  },
1501
- when: ({ agent }) => managerLinks(agent.id, true).length > 0 || workerLink(agent.id) !== undefined,
1899
+ when: ({ agent }) => managerHasWork(agent.id) || workerAssociation(agent.id) !== undefined,
1502
1900
  })
1503
1901
  }
1504
1902
 
@@ -1509,7 +1907,7 @@ export function apply(ctx, rawConfig) {
1509
1907
 
1510
1908
  /** Whether one session is an active worker. */
1511
1909
  function isWorker(sessionId) {
1512
- return workerLink(sessionId) !== undefined
1910
+ return workerAssociation(sessionId) !== undefined
1513
1911
  }
1514
1912
 
1515
1913
  /** Require the calling agent. */
@@ -1543,15 +1941,16 @@ export function apply(ctx, rawConfig) {
1543
1941
  link: 'link',
1544
1942
  dispatch: 'dispatch',
1545
1943
  configure: 'configure',
1944
+ project: 'project',
1546
1945
  done: 'done',
1547
1946
  unlink: 'unlink',
1548
1947
  sessions: 'sessions',
1549
1948
  }
1550
1949
  ctx.commands.register({
1551
1950
  name: 'collab',
1552
- description: '双对话协作:查看全部任务、关联员工、配置预设、派发任务、收尾或解除。',
1951
+ description: '双对话协作:查看全部任务、关联员工、设置项目名、配置预设与语言、派发任务、收尾或解除。',
1553
1952
  input: {
1554
- hint: 'tasks | status | link --peer <id|new> | configure --preset <id> | dispatch --worker <id> --task ... | done --worker <id> --summary ... | unlink --worker <id>',
1953
+ hint: 'tasks | status | link --peer <id|new> | project --name <项目名> | configure --preset <id> | language <zh|en> | dispatch --worker <id> --task ... | done --worker <id> --summary ... | unlink --worker <id>',
1555
1954
  },
1556
1955
  handler: async (invocation) => {
1557
1956
  try {
@@ -1559,6 +1958,17 @@ export function apply(ctx, rawConfig) {
1559
1958
  if (action === 'tasks' || action === 'board') {
1560
1959
  return { kind: 'success', text: JSON.stringify(await tasksBoard()) }
1561
1960
  }
1961
+ if (action === 'language') {
1962
+ const next = typeof args?.language === 'string' ? args.language : typeof args?.value === 'string' ? args.value : ''
1963
+ if (next !== 'zh' && next !== 'en') return { kind: 'error', text: 'language must be zh or en' }
1964
+ const entry = ctx.fiber?.entry
1965
+ const editor = ctx.get('configEditor')
1966
+ if (entry === undefined || editor === undefined) {
1967
+ return { kind: 'error', text: '当前环境无法保存语言设置;请手动修改 cordis.patch.yml 里的 language。' }
1968
+ }
1969
+ await editor.edit(entry, (current) => ({ ...current, language: next }))
1970
+ return { kind: 'success', text: JSON.stringify({ ok: true, language: next }) }
1971
+ }
1562
1972
  const key = actions[action]
1563
1973
  const executor = key === undefined ? undefined : toolExecutors[key]
1564
1974
  if (executor === undefined) {