dsh-rhine-lab-team 0.5.4 → 0.5.6

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
@@ -50,7 +50,7 @@ dsh plugin add https://github.com/vioeveann/dsh-rhine-lab-team
50
50
  - 不设 token 预算:任务卡会显示真实用量,但不会因为超预算自动停。需要控成本时用并发数、单任务超时和成员能力卡。
51
51
  - 防作弊只防手改 JSON:签名密钥在本机文件里,能读到密钥并自己重签的人仍可绕过;它是防误改,不是防本机管理员。
52
52
  - 界面目前只有中文;英文界面在计划中。
53
- - 测试:330 条(`npm test`)+ 2 条浏览器冒烟测试(`test/e2e`)。
53
+ - 测试:338 条(`npm test`)+ 2 条浏览器冒烟测试(`test/e2e`)。
54
54
 
55
55
  ## 现状(2026-11-23)
56
56
 
@@ -86,7 +86,7 @@ dsh plugin add https://github.com/vioeveann/dsh-rhine-lab-team
86
86
  - **成员组**:橙色锤子建组;每个组卡片最右边的锤子在组下面展开团队设置(同一个编辑器),顶部多一行「这个组」可以改名或删掉它
87
87
  - **界面**:成员面板(分组折叠、卡片扳手改成员、组内招募、头像裁剪、点卡片开子会话、任务详情、成长与晋升、橙色锤子进团队设置)、皮肤 classic / aurora
88
88
  - **子会话身份**:依赖 `dsh-avatar-frame`(声明为 `latest`,npm 上需 ≥ 0.15)时显示 Bot 自己的头像和 ID,点它进设置,语音关闭
89
- - **测试**:330 条(`npm test`)+ 2 条浏览器冒烟测试(`test/e2e`)
89
+ - **测试**:338 条(`npm test`)+ 2 条浏览器冒烟测试(`test/e2e`)
90
90
 
91
91
  ## 任务依赖
92
92
 
package/client.js CHANGED
@@ -739,7 +739,7 @@ window.__ModuleLoader__.load({
739
739
  const MEMBERS_TAB_ID = 'dsh-team/members'
740
740
 
741
741
  /** 每次改客户端都改这个戳,用来判断页面拿到的是不是新 bundle。 */
742
- const BUILD_STAMP = 'a15'
742
+ const BUILD_STAMP = 'a16'
743
743
 
744
744
  /**
745
745
  * 把「子会话 → Bot」的映射发布给 dsh-avatar-frame:
@@ -770,9 +770,30 @@ let lastIdentityRaw = null
770
770
  async function publishTeamIdentity(force = false) {
771
771
  try {
772
772
  // 账本全量:每个子会话都能对上 Bot(不只每个 Bot 的最近一次)。
773
- const response = await fetch('/dsh-team/identity-map')
774
- const data = await response.json()
775
- const map = data?.map ?? {}
773
+ // 映射现拼自 tasks + roster,identity-map 只作为补充:那条路由曾经因为
774
+ // 重载时漏撤而由旧实例一直供着,数据停在重载那一刻,新会话全漏。
775
+ const [identity, list, roster] = await Promise.all([
776
+ fetch('/dsh-team/identity-map').then((response) => (response.ok ? response.json() : null)).catch(() => null),
777
+ fetch('/dsh-team/tasks').then((response) => (response.ok ? response.json() : null)).catch(() => null),
778
+ fetch('/dsh-team/roster').then((response) => (response.ok ? response.json() : null)).catch(() => null),
779
+ ])
780
+ const map = { ...(identity?.map ?? {}) }
781
+ const names = new Map()
782
+ for (const member of roster?.members ?? []) {
783
+ if (member?.id) names.set(String(member.id), member.name ?? member.id)
784
+ }
785
+ for (const task of list?.tasks ?? []) {
786
+ const sessionId = String(task?.sessionId ?? '').trim()
787
+ const bot = String(task?.bot ?? '').trim()
788
+ if (sessionId === '' || bot === '') continue
789
+ map[sessionId] = {
790
+ id: bot,
791
+ name: names.get(bot) ?? bot,
792
+ src: `/dsh-team/avatar?bot=${encodeURIComponent(bot)}&v=3`,
793
+ onOpen: true,
794
+ speech: false,
795
+ }
796
+ }
776
797
  const raw = JSON.stringify(map)
777
798
  if (!force && raw === lastIdentityRaw) return
778
799
  lastIdentityRaw = raw
@@ -5511,36 +5532,40 @@ function createMembersPanel(React, host) {
5511
5532
  }, [noSessionHint])
5512
5533
 
5513
5534
  const openChat = async (member) => {
5514
- let sessionId = member?.sessionId
5535
+ // 单聊一律交给宿主判断:旧会话的根还活着就复用,根停了就新开一条。
5536
+ // 面板拿到的 member.sessionId 可能来自昨天那个已经停掉的根会话,
5537
+ // 客户端自己拍板去开,就会走到「发消息不可用」。
5538
+ let sessionId = ''
5515
5539
  // 刚开出来的会话,名册还没刷新,父会话 id 只能从开会话的返回值里拿。
5516
5540
  let openedParent = ''
5517
5541
  // 宿主连身份一起给:开页前写进头像映射,第一帧就是 Bot 自己。
5518
5542
  let openedIdentity
5519
- if (!sessionId) {
5520
- // 还没有会话:先开一个单聊会话,再把它打开。
5521
- setNoSessionHint(member?.id ?? null)
5522
- setNotice(`正在给 ${member?.name || member?.id} 开会话…`)
5523
- try {
5524
- const response = await fetch('/dsh-team/open', {
5525
- method: 'POST',
5526
- headers: { 'content-type': 'application/json' },
5527
- body: JSON.stringify({ bot: member?.id, sessionId: sessionForRoster }),
5528
- })
5529
- const data = await response.json()
5530
- if (!data?.ok) {
5531
- setNotice(data?.error ?? '开会话失败')
5532
- setNoSessionHint(null)
5533
- return
5534
- }
5535
- sessionId = data.sessionId
5536
- openedParent = String(data.parentSessionId ?? '')
5537
- openedIdentity = data.identity
5538
- setNotice('')
5539
- } catch (error) {
5540
- setNotice(`开会话失败:${error?.message ?? error}`)
5543
+ setNoSessionHint(member?.id ?? null)
5544
+ setNotice(`正在打开 ${member?.name || member?.id} 的会话…`)
5545
+ try {
5546
+ const response = await fetch('/dsh-team/open', {
5547
+ method: 'POST',
5548
+ headers: { 'content-type': 'application/json' },
5549
+ body: JSON.stringify({
5550
+ bot: member?.id,
5551
+ sessionId: sessionForRoster,
5552
+ chatSessionId: member?.sessionId ?? '',
5553
+ }),
5554
+ })
5555
+ const data = await response.json()
5556
+ if (!data?.ok) {
5557
+ setNotice(data?.error ?? '开会话失败')
5541
5558
  setNoSessionHint(null)
5542
5559
  return
5543
5560
  }
5561
+ sessionId = data.sessionId
5562
+ openedParent = String(data.parentSessionId ?? '')
5563
+ openedIdentity = data.identity
5564
+ setNotice('')
5565
+ } catch (error) {
5566
+ setNotice(`开会话失败:${error?.message ?? error}`)
5567
+ setNoSessionHint(null)
5568
+ return
5544
5569
  }
5545
5570
  setNoSessionHint(null)
5546
5571
  const service = (name) => {
package/docs/RELEASE.md CHANGED
@@ -41,7 +41,9 @@ dsh plugin add <包名或本地路径>
41
41
 
42
42
  ## 版本
43
43
 
44
- - `0.5.4`(当前):任务依赖图(验收门、整链超时/取消、重启恢复)、强制审查链、成员信箱、窄版工作区、P1 三项、第 7 步文档;修复监考提醒被当成任务结果、晋升感言串段、窄面板名字截断。
44
+ - `0.5.6`(当前):修单聊在根会话失效后发不出去。DSH 要求子会话的根会话在线,旧实现把单聊挂在当时的会话下,重启后根已停止,`sendMessage` 返回 `subagent/delivery-unavailable`。现在客户端一律走 `/dsh-team/open`:服务端先判断原单聊的根是否活着,活着复用,死了在当前会话新开一条;账本同时记 `parentSession` 与 `rootSession`。另补进程级路由撤单,避免热重载时 `identity-map` / `session-bot` 重复注册。
45
+ - `0.5.5`:修两处状态错位。①「待命」误判:成员卡原先只认账本里的 `running` 行,派活那次工具调用一旦被打断(用户在派活途中插话),账本被记成 `ready`,子会话却还在后台跑——面板显示「待命」、看门狗关机、干完也没有任何回报。现在成员繁忙状态同时看会话实际运行态(新增 `host/live-watch.js` 订阅子会话 `agent/status`);派活被打断时不再收 `ready`,任务保留 `running` 并标 `detached`,由后台接力每 3 秒查子会话是否真说完,拿到答复再收尾并广播 `task-done`。②热重载后新子会话头像回落主会话:`team-mode.js` 的 `dispose()` 漏撤 `identity-map` 与 `session-bot` 两条 exact 路由,重载时新实例撞 `duplicate exact route` 注册失败,`/dsh-team/identity-map` 一直由已卸载的旧实例供数、数据冻结在重载那一刻。现已补进撤单清单;客户端身份映射改为并行拉 `tasks`/`roster` 现拼,不再单依赖 `identity-map`。另:`host/runtime.js` 的 `tools.js`/`team-mode.js` 改成带版本参数的动态 import,翻开关即可热加载。
46
+ - `0.5.4`:任务依赖图(验收门、整链超时/取消、重启恢复)、强制审查链、成员信箱、窄版工作区、P1 三项、第 7 步文档;修复监考提醒被当成任务结果、晋升感言串段、窄面板名字截断。
45
47
  - `0.5.3`:团队设置面板三处 —— 称谓框不再被限定成数字;「超时」改名「单任务最长运行(秒)」,卡住提醒的三个参数收进设置不再摆在面板上;新建组面板里还没建组时,导出/导入先提示「请先创建组」。交付目录说明更正为文档目录。
46
48
  - `0.5.2`:0.5.1 的数据迁移清单补上 `.team-work/`(单聊与任务的工作目录)。用户自建的 Bot、分组、设置、知识库、账本全部随数据目录走,升级不再丢。
47
49
  - `0.5.1`:**运行期数据搬出包目录**(`$DSH_HOME/rhine-lab-team`,可用 `DSH_TEAM_HOME` 覆盖;包目录里的旧数据(bots/、.state/、.team-work/、.debug/)启动时自动搬一次)。0.5.0 升级曾把用户自建的 Bot 连带记忆一起抹掉,这一版修掉了。
@@ -51,4 +53,4 @@ dsh plugin add <包名或本地路径>
51
53
  - `0.2.0`:任务详情与重试、成本统计、能力卡与团队记忆编辑、Bot 交接、系统通知、模板、近实时刷新。
52
54
  - `0.1.0`:派活、验收、产物收集、记忆快照、名册与面板。
53
55
 
54
- `package.json` 现在是 `0.5.4`。发的时候跑一遍上面的检查。
56
+ `package.json` 现在是 `0.5.6`。发的时候跑一遍上面的检查。
@@ -0,0 +1,33 @@
1
+ /**
2
+ * 单聊会话的存活判断。
3
+ *
4
+ * DSH 只允许往「根会话还活着」的子会话里发消息;创建它的会话离线没关系。
5
+ * 单聊记录里存 rootSession(创建时所在的根),老记录没有就退回 parentSession。
6
+ *
7
+ * @param {object} entry 账本里的单聊行。
8
+ * @returns {string} 根会话 id;没有就空串。
9
+ */
10
+ export function chatRootId(entry) {
11
+ return String(entry?.rootSession || entry?.parentSession || '')
12
+ }
13
+
14
+ /**
15
+ * 根会话是否还活着。
16
+ *
17
+ * 当前会话一定是活的;不在当前会话时,只有 agents.get 还能拿到这个根才算活。
18
+ * 拿不到 agent 就当作失效——宁可重开一条单聊,也不要让用户点开发不出去。
19
+ *
20
+ * @param {object} entry 账本里的单聊行。
21
+ * @param {{ currentSession?: string, getAgent?: (id: string) => unknown }} options
22
+ * @returns {boolean}
23
+ */
24
+ export function chatRootAlive(entry, options = {}) {
25
+ const root = chatRootId(entry)
26
+ if (root === '') return false
27
+ if (options.currentSession && root === options.currentSession) return true
28
+ try {
29
+ return Boolean(options.getAgent?.(root))
30
+ } catch {
31
+ return false
32
+ }
33
+ }
@@ -0,0 +1,93 @@
1
+ /**
2
+ * 子会话「现在是不是在干活」的实时登记。
3
+ *
4
+ * 为什么单独一张表:账本(tasks)里的状态是派活那次工具调用写下来的,
5
+ * 一旦派活调用被中止(秘书正等结果时用户插话),账本会被提前收成 ready,
6
+ * 但子会话其实还在后台跑——面板于是显示「待命」,看门狗也跟着关了。
7
+ * 这里只认子会话自己发出来的 `agent/status`,与账本无关,面板以它为准。
8
+ */
9
+
10
+ /** sessionId -> { state, botId, at } */
11
+ const states = new Map()
12
+
13
+ /**
14
+ * 超过这个时间没再报过状态的登记,一律当成失效。
15
+ *
16
+ * 子会话正常会发 `idle`;真崩了可能一个字都不发,那就得靠时间兜底,
17
+ * 否则一个死会话能把 Bot 永久钉在「繁忙」上——跟原来那个「待命」是同一类错。
18
+ * 四小时与后台接力的放弃期限对齐。
19
+ */
20
+ const STALE_MS = 4 * 60 * 60 * 1000
21
+
22
+ /** 这条登记还作不作数。 */
23
+ function fresh(row) {
24
+ return Date.now() - (row?.at ?? 0) <= STALE_MS
25
+ }
26
+
27
+ /**
28
+ * 记一次子会话状态。
29
+ * @param sessionId - 子会话 id。
30
+ * @param state - `agent/status` 给的值(idle / running / …)。
31
+ * @param botId - 这个子会话属于哪个 Bot。
32
+ */
33
+ export function noteChildState(sessionId, state, botId) {
34
+ const id = String(sessionId ?? '').trim()
35
+ if (id === '') return
36
+ states.set(id, {
37
+ state: String(state ?? '').trim(),
38
+ botId: botId ? String(botId) : null,
39
+ at: Date.now(),
40
+ })
41
+ }
42
+
43
+ /**
44
+ * 忘掉一个子会话(会话被删 / 任务收了)。
45
+ * @param sessionId - 子会话 id。
46
+ */
47
+ export function forgetChild(sessionId) {
48
+ states.delete(String(sessionId ?? ''))
49
+ }
50
+
51
+ /**
52
+ * 现在正在干活的 Bot。
53
+ * @returns Bot id 的集合;`idle` 之外的任何状态都算在干活。
54
+ */
55
+ export function runningBots() {
56
+ const out = new Set()
57
+ for (const row of states.values()) {
58
+ if (!fresh(row)) continue
59
+ if (row.botId && row.state !== '' && row.state !== 'idle') out.add(row.botId)
60
+ }
61
+ return out
62
+ }
63
+
64
+ /**
65
+ * 一个子会话当前的状态。
66
+ * @param sessionId - 子会话 id。
67
+ * @returns 状态字符串;没登记过就是空串。
68
+ */
69
+ export function childStateOf(sessionId) {
70
+ const row = states.get(String(sessionId ?? ''))
71
+ return row && fresh(row) ? row.state : ''
72
+ }
73
+
74
+ /**
75
+ * 某个 Bot 名下正在跑的会话。
76
+ * @param botId - Bot id。
77
+ * @returns 会话 id 数组。
78
+ */
79
+ export function runningSessions(botId) {
80
+ const out = []
81
+ for (const [id, row] of states) {
82
+ if (!fresh(row)) continue
83
+ if (row.botId === botId && row.state !== '' && row.state !== 'idle') out.push(id)
84
+ }
85
+ return out
86
+ }
87
+
88
+ /**
89
+ * 清空登记。只给测试用——撑起现场再演练,别让上一次的残留把这次判成繁忙。
90
+ */
91
+ export function resetChildStates() {
92
+ states.clear()
93
+ }
package/host/runtime.js CHANGED
@@ -13,15 +13,28 @@
13
13
  import { appendFile, mkdir, readFile, writeFile } from 'node:fs/promises'
14
14
  import { join } from 'node:path'
15
15
  import { fileURLToPath } from 'node:url'
16
- import { installChildDecoration, readTeamMemory, registerMemoryTools, registerTeamTools, SECRETARY_RULES } from './tools.js'
17
16
  import { createWorkspaceGuard } from './guard.js'
18
17
  import { adoptSoulFile, loadBots, migratePersona } from './bots.js'
19
18
  import { ensureBuiltinBots } from './builtin-bots.js'
20
- import { installTeamMode, readRoster } from './team-mode.js'
21
19
  import { loadSettings, resolveDeliverableRoot, saveSettings } from './settings.js'
22
20
  import { createUsageBook } from './usage.js'
23
21
  import { createMailbox } from './mailbox.js'
24
22
  import { migrateDataRoot, resolveDataRoot } from './paths.js'
23
+ /**
24
+ * 工具层和面板路由这两块改得最勤,所以带缓存戳动态 import:
25
+ * 静态 import 会命中 ESM 模块缓存,改完翻开关也不会重新加载,只能重启 DSH。
26
+ * 里面的 ./bots.js 之类仍是普通 import——它们没改,共用一份就行。
27
+ */
28
+ const toolsModule = await import(`./tools.js?v=${Date.now()}`)
29
+ const teamModeModule = await import(`./team-mode.js?v=${Date.now()}`)
30
+ const {
31
+ installChildDecoration,
32
+ readTeamMemory,
33
+ registerMemoryTools,
34
+ registerTeamTools,
35
+ SECRETARY_RULES,
36
+ } = toolsModule
37
+ const { installTeamMode, readRoster } = teamModeModule
25
38
 
26
39
  /** 插件包目录:只放代码,不放数据。升级时它会被整个替换。 */
27
40
  const PACKAGE_ROOT = fileURLToPath(new URL('..', import.meta.url))
@@ -378,7 +391,8 @@ export async function apply(ctx, config = {}) {
378
391
  let pluginVersion = ''
379
392
  let dshEngine = ''
380
393
  try {
381
- const pkg = JSON.parse(await readFile(join(ROOT, 'package.json'), 'utf8'))
394
+ // 版本号在包目录里,不在数据目录里——以前读错了地方,体检报告永远是空的。
395
+ const pkg = JSON.parse(await readFile(join(PACKAGE_ROOT, 'package.json'), 'utf8'))
382
396
  pluginVersion = String(pkg.version ?? '')
383
397
  dshEngine = String(pkg.engines?.dsh ?? '')
384
398
  } catch {
package/host/team-mode.js CHANGED
@@ -19,6 +19,7 @@ import { growthSummary, normalizeGrowth } from './growth.js'
19
19
  import { sumTaskTokens } from './usage.js'
20
20
  import { updateGrowth } from './growth-store.js'
21
21
  import { commitMemory } from './memory.js'
22
+ import { runningBots } from './live-watch.js'
22
23
 
23
24
  const SWITCH_ROUTE = '/dsh-team/team-mode'
24
25
  const ROSTER_ROUTE = '/dsh-team/roster'
@@ -206,6 +207,15 @@ export function installTeamMode(ctx, options) {
206
207
  const { root, debug, tasks, mailbox, getRoster, getSettings, saveSettings, api, persistTasks, getModels, getInstanceConflict } = options
207
208
  const storeFile = join(root, '.state', 'team-mode.json')
208
209
 
210
+ // 热重载时旧模块的 disposer 可能没跑到,路由会撞 duplicate exact route。
211
+ // 在进程级留一个上一份安装的清理函数,新的一份安装前先撤旧的。
212
+ const ROUTE_OWNER = Symbol.for('dsh-rhine-lab-team.team-mode.dispose')
213
+ try {
214
+ globalThis[ROUTE_OWNER]?.()
215
+ } catch {
216
+ // 旧模块已经撤过或参数不兼容,继续装新的
217
+ }
218
+
209
219
  /** 在线的 SSE 客户端。 */
210
220
  const eventClients = new Set()
211
221
 
@@ -387,6 +397,9 @@ export function installTeamMode(ctx, options) {
387
397
  .map((entry) => ({
388
398
  taskId: entry.taskId,
389
399
  bot: entry.bot,
400
+ // 客户端要按「子会话 → Bot」拼头像映射:这条不发,头像就只能靠
401
+ // identity-map 那条路由,一旦它没注册上,新会话就顶主会话的脸。
402
+ sessionId: entry.sessionId ?? '',
390
403
  status: entry.status ?? 'running',
391
404
  startedAt: entry.startedAt ?? null,
392
405
  doneAt: entry.doneAt ?? null,
@@ -1113,6 +1126,7 @@ export function installTeamMode(ctx, options) {
1113
1126
  const result = await api?.openChat?.({
1114
1127
  botId: String(body.bot ?? ''),
1115
1128
  parentSession: String(body.sessionId ?? ''),
1129
+ chatSessionId: String(body.chatSessionId ?? ''),
1116
1130
  })
1117
1131
  json(res, 200, result ?? { ok: false, error: '单聊接口没接上' })
1118
1132
  } catch (error) {
@@ -1586,9 +1600,7 @@ export function installTeamMode(ctx, options) {
1586
1600
  },
1587
1601
  })
1588
1602
 
1589
- return {
1590
- isEnabled: (sessionId) => state.get(String(sessionId)) === true,
1591
- dispose: () => {
1603
+ const disposeAll = () => {
1592
1604
  // 新加的路由也要撤;漏一个,下次重载就会撞「duplicate exact route」。
1593
1605
  for (const dispose of [
1594
1606
  disposeExportPack,
@@ -1596,6 +1608,8 @@ export function installTeamMode(ctx, options) {
1596
1608
  disposeImportBot,
1597
1609
  disposeImportBotFiles,
1598
1610
  disposeQuickstart,
1611
+ disposeIdentityMap,
1612
+ disposeSessionBot,
1599
1613
  ]) {
1600
1614
  try {
1601
1615
  dispose?.()
@@ -1635,6 +1649,19 @@ export function installTeamMode(ctx, options) {
1635
1649
  disposeAvatar()
1636
1650
  disposeMemoryRoute()
1637
1651
  disposePersona()
1652
+ }
1653
+ globalThis[ROUTE_OWNER] = disposeAll
1654
+ return {
1655
+ isEnabled: (sessionId) => state.get(String(sessionId)) === true,
1656
+ dispose: () => {
1657
+ if (globalThis[ROUTE_OWNER] === disposeAll) {
1658
+ try {
1659
+ delete globalThis[ROUTE_OWNER]
1660
+ } catch {
1661
+ // 删不掉也不影响
1662
+ }
1663
+ }
1664
+ disposeAll()
1638
1665
  },
1639
1666
  }
1640
1667
  }
@@ -1691,11 +1718,14 @@ export async function readRoster(options) {
1691
1718
  continue
1692
1719
  }
1693
1720
  const running = live.get(bot.id) ?? []
1721
+ // 账本里的 running 只在派活那一次调用没被打断时才可靠;被打断时账本被提前收成
1722
+ // ready,子会话却还在跑,面板就会误显示「待命」。所以再看一眼子会话自己报的状态。
1723
+ const busyNow = runningBots()
1694
1724
  members.push({
1695
1725
  id: bot.id,
1696
1726
  name: bot.name ?? bot.id,
1697
1727
  role: bot.role ?? '',
1698
- status: bot.status === 'disabled' ? 'disabled' : running.length > 0 ? 'busy' : 'idle',
1728
+ status: bot.status === 'disabled' ? 'disabled' : running.length > 0 || busyNow.has(bot.id) ? 'busy' : 'idle',
1699
1729
  group: bot.group ?? '',
1700
1730
  stars: bot.stars ?? 0,
1701
1731
  // 插件自带的 Bot;limited 表示「限定」(带标签、删了能恢复)。
package/host/tools.js CHANGED
@@ -33,7 +33,9 @@ import { confirmImprovement, promoteBot, savePromotionSpeech, updateGrowth } fro
33
33
  import { growthDetail, growthSummary, promote, regrade, settleRepeat, settleTask, settleTeaching } from './growth.js'
34
34
  import { taskGain } from './progress.js'
35
35
  import { loadBots, stripSoulPlaceholder } from './bots.js'
36
+ import { chatRootAlive } from './chat-session.js'
36
37
  import { formatMailPrompt } from './mailbox.js'
38
+ import { forgetChild, noteChildState } from './live-watch.js'
37
39
 
38
40
  /** 插件自带审计员的 id;打 excellent 前必须先有它的审计记录。 */
39
41
  const AUDITOR_ID = 'auditor'
@@ -1320,6 +1322,94 @@ export function registerTeamTools(ctx, options) {
1320
1322
  return bot
1321
1323
  }
1322
1324
 
1325
+ /**
1326
+ * 派活那次调用被中止(秘书正等结果时用户插话)后,子会话其实还在后台跑。
1327
+ * 这里接力盯它:每 3 秒看一眼落盘会话有没有新的 turn/end,等到就把账本收成
1328
+ * ready、推一张卡片,再让这个 Bot 的子会话给秘书发一条消息把秘书叫醒。
1329
+ * 只读不打断——它在干活,别去碰它。
1330
+ */
1331
+ function watchDetachedTask({ taskId, bot, sessionId, startedAt, exec }) {
1332
+ const deadline = Date.now() + 4 * 60 * 60 * 1000
1333
+ let ticking = false
1334
+ const timer = setInterval(async () => {
1335
+ if (ticking) return
1336
+ ticking = true
1337
+ try {
1338
+ const row = tasks?.get(taskId)
1339
+ if (!row || !row.detached || row.status !== 'running') {
1340
+ clearInterval(timer)
1341
+ return
1342
+ }
1343
+ if (Date.now() > deadline) {
1344
+ row.status = 'timeout'
1345
+ row.doneAt = Date.now()
1346
+ row.note = '派活调用被中断后一直没等到这一轮说完,后台接力放弃'
1347
+ delete row.detached
1348
+ forgetChild(sessionId)
1349
+ void persistTasks?.()
1350
+ options.api?.broadcast?.({ type: 'tasks' })
1351
+ void debug?.({ event: 'detached-timeout', taskId, bot: bot.id })
1352
+ clearInterval(timer)
1353
+ return
1354
+ }
1355
+ const text = await readSessionTurnReply(sessionId, startedAt)
1356
+ if (!text) return
1357
+ const usage = usageBook?.take?.(sessionId)
1358
+ if (usage) row.tokens = usage
1359
+ row.status = 'ready'
1360
+ row.doneAt = Date.now()
1361
+ row.output = text.slice(0, 4000)
1362
+ row.note = '派活调用被中断,这一轮结果是后台接力补记的'
1363
+ delete row.detached
1364
+ forgetChild(sessionId)
1365
+ void persistTasks?.()
1366
+ options.api?.broadcast?.({ type: 'tasks' })
1367
+ options.api?.broadcast?.({
1368
+ type: 'task-done',
1369
+ taskId,
1370
+ bot: bot.id,
1371
+ status: 'ready',
1372
+ text: text.slice(0, 600),
1373
+ })
1374
+ void maybeQueueReview(row, exec)
1375
+ void debug?.({ event: 'detached-finish', taskId, bot: bot.id, bytes: text.length })
1376
+ // 账本变了不会自己开一轮,所以让子会话给秘书发一条消息,把秘书叫醒。
1377
+ // sendMessage 不允许自己发给自己,发送方必须是那个子会话本身。
1378
+ try {
1379
+ const child = liveChildren.get(sessionId)
1380
+ if (child && row.parentSession && subagents?.sendMessage) {
1381
+ await subagents.sendMessage(
1382
+ child,
1383
+ row.parentSession,
1384
+ [
1385
+ {
1386
+ type: 'text',
1387
+ text: `【团队】${bot.name ?? bot.id} 的 ${taskId} 已经干完(派活调用被中断,这条是后台补报的):\n${String(text).slice(0, 800)}`,
1388
+ },
1389
+ ],
1390
+ { signal: new AbortController().signal },
1391
+ )
1392
+ void debug?.({ event: 'detached-notify', taskId, ok: true })
1393
+ } else {
1394
+ void debug?.({
1395
+ event: 'detached-notify',
1396
+ taskId,
1397
+ ok: false,
1398
+ reason: child ? 'no-parent' : 'no-child',
1399
+ })
1400
+ }
1401
+ } catch (error) {
1402
+ void debug?.({ event: 'detached-notify', taskId, ok: false, error: String(error?.message ?? error) })
1403
+ }
1404
+ clearInterval(timer)
1405
+ } finally {
1406
+ ticking = false
1407
+ }
1408
+ }, 3000)
1409
+ // 别让这个定时器把进程钉住。
1410
+ timer.unref?.()
1411
+ }
1412
+
1323
1413
  const reviewQueued = new Set()
1324
1414
 
1325
1415
  // 有交付物的任务完成后,自动给它建一张审计子任务;终审仍由秘书做。
@@ -2182,26 +2272,54 @@ export function registerTeamTools(ctx, options) {
2182
2272
  const usage = usageBook?.take?.(started?.childId ?? childId)
2183
2273
  if (usage) entry.tokens = usage
2184
2274
  }
2185
- // 只把「还在跑」的行收成 ready:失败 / 超时 / 取消已经写过自己的状态,别覆盖。
2186
- if (entry && (!entry.status || entry.status === 'running')) {
2187
- entry.doneAt = Date.now()
2188
- entry.status = 'ready'
2189
- } else if (entry && !entry.doneAt) {
2190
- entry.doneAt = Date.now()
2191
- }
2192
- // 留下这一轮的回复:返工续聊时用来判断「这是不是新回复」。
2193
- if (entry && finalText !== '') entry.output = finalText.slice(0, 4000)
2194
- void persistTasks?.()
2195
- // 干完就推一张实时卡片:不等秘书收尾再贴。
2196
- if (entry?.status === 'ready') void maybeQueueReview(entry, exec)
2197
- if (entry) {
2198
- options.api?.broadcast?.({
2199
- type: 'task-done',
2275
+ const interrupted = exec?.signal?.aborted === true
2276
+ const stillRunning = Boolean(entry) && (!entry.status || entry.status === 'running')
2277
+ // 用户在秘书等结果时插话 → 这一次工具调用被判 aborted,但子会话没停。
2278
+ // 这时候不能把账本收成 ready:成员卡会显示「待命」,看门狗也跟着关掉。
2279
+ // 保留 running,交给后台接力,等这一轮真说完再收。
2280
+ if (entry && interrupted && stillRunning) {
2281
+ entry.detached = true
2282
+ entry.status = 'running'
2283
+ delete entry.doneAt
2284
+ void persistTasks?.()
2285
+ options.api?.broadcast?.({ type: 'tasks' })
2286
+ void debug?.({
2287
+ event: 'dispatch-interrupted',
2200
2288
  taskId,
2201
2289
  bot: bot.id,
2202
- status: entry.status,
2203
- text: String(entry.output ?? entry.note ?? '').slice(0, 600),
2290
+ sessionId: started?.childId ?? childId,
2291
+ })
2292
+ watchDetachedTask({
2293
+ taskId,
2294
+ bot,
2295
+ sessionId: started?.childId ?? childId,
2296
+ startedAt: entry.startedAt ?? Date.now(),
2297
+ exec,
2204
2298
  })
2299
+ } else {
2300
+ // 只把「还在跑」的行收成 ready:失败 / 超时 / 取消已经写过自己的状态,别覆盖。
2301
+ if (entry && (!entry.status || entry.status === 'running')) {
2302
+ entry.doneAt = Date.now()
2303
+ entry.status = 'ready'
2304
+ } else if (entry && !entry.doneAt) {
2305
+ entry.doneAt = Date.now()
2306
+ }
2307
+ // 留下这一轮的回复:返工续聊时用来判断「这是不是新回复」。
2308
+ if (entry && finalText !== '') entry.output = finalText.slice(0, 4000)
2309
+ // 这一趟收了尾,实时登记也撤掉,别让它一直算在「在干活」里。
2310
+ forgetChild(started?.childId ?? childId)
2311
+ void persistTasks?.()
2312
+ // 干完就推一张实时卡片:不等秘书收尾再贴。
2313
+ if (entry?.status === 'ready') void maybeQueueReview(entry, exec)
2314
+ if (entry) {
2315
+ options.api?.broadcast?.({
2316
+ type: 'task-done',
2317
+ taskId,
2318
+ bot: bot.id,
2319
+ status: entry.status,
2320
+ text: String(entry.output ?? entry.note ?? '').slice(0, 600),
2321
+ })
2322
+ }
2205
2323
  }
2206
2324
  }
2207
2325
  }
@@ -3914,18 +4032,73 @@ export function registerTeamTools(ctx, options) {
3914
4032
  }
3915
4033
  }
3916
4034
 
3917
- // 给没有会话的 Bot 开一个单聊:起个子会话,让它只问一句好,然后等你说话。
3918
- options.api.openChat = async ({ botId, parentSession }) => {
4035
+ // 给 Bot 开单聊;已有会话还活着的就复用,根会话死了就重开一条。
4036
+ //
4037
+ // DSH 的硬约束:往子会话发消息时,它的根会话必须活着;创建者可以离线。
4038
+ // 所以按根会话判断,不按 parentSession 判断——旧单聊的根一旦停了,
4039
+ // 这条会话就发不出消息,只能新开,并把旧账本留作记录。
4040
+ const chatIdentityOf = (bot) => ({
4041
+ id: bot.id,
4042
+ name: bot.name ?? bot.id,
4043
+ src: `/dsh-team/avatar?bot=${encodeURIComponent(bot.id)}&v=3`,
4044
+ onOpen: true,
4045
+ speech: false,
4046
+ })
4047
+
4048
+ options.api.openChat = async ({ botId, parentSession, chatSessionId }) => {
3919
4049
  const bot = await readBot(root, String(botId ?? '').trim())
3920
4050
  if (!bot) return { ok: false, error: '没有这个 Bot' }
3921
4051
  if (bot.status === 'disabled') return { ok: false, error: '这个 Bot 已停用' }
3922
4052
  const parent = String(parentSession ?? '').trim()
3923
4053
  const parentAgent = parent === '' ? null : agents?.get?.(parent)
3924
4054
  if (!parentAgent) return { ok: false, error: '拿不到当前会话' }
4055
+
4056
+ // 面板点的是已有单聊:先看它的根还活着没有。活着就复用,
4057
+ // 死了就走下面新开一条,用户不需要知道“为什么发不出去”。
4058
+ const requested = String(chatSessionId ?? '').trim()
4059
+ if (requested !== '') {
4060
+ const entry = [...tasks.values()].find(
4061
+ (row) => row.sessionId === requested && row.bot === bot.id,
4062
+ )
4063
+ const alive = entry
4064
+ ? chatRootAlive(entry, {
4065
+ currentSession: parent,
4066
+ getAgent: (id) => agents?.get?.(id),
4067
+ })
4068
+ : false
4069
+ if (alive) {
4070
+ return {
4071
+ ok: true,
4072
+ sessionId: requested,
4073
+ parentSessionId: String(entry?.parentSession ?? parent),
4074
+ identity: chatIdentityOf(bot),
4075
+ bot: bot.id,
4076
+ reused: true,
4077
+ }
4078
+ }
4079
+ if (entry) {
4080
+ await debug?.({
4081
+ event: 'chat-stale',
4082
+ bot: bot.id,
4083
+ sessionId: requested,
4084
+ root: String(entry.rootSession ?? entry.parentSession ?? ''),
4085
+ })
4086
+ }
4087
+ }
4088
+
3925
4089
  const childId = `session-${randomUUID()}`
3926
4090
  const dir = join(root, '.team-work', bot.id, `chat-${Date.now().toString(36)}`)
3927
4091
  await mkdir(dir, { recursive: true })
3928
4092
  pending.set(childId, { bot, taskDir: dir })
4093
+ // 记下创建时所在的根会话:以后判断这条单聊还能不能发消息,就看它。
4094
+ // 拿不到 rootOf 就退回当前会话;当前会话本身一定是活的。
4095
+ let rootSession = parent
4096
+ try {
4097
+ const rootAgent = subagents?.rootOf?.(parentAgent)
4098
+ rootSession = String(rootAgent?.session?.header?.id ?? rootAgent?.id ?? parent)
4099
+ } catch {
4100
+ rootSession = parent
4101
+ }
3929
4102
  const prompt = `主动打开这个会话想和你说话,不是派任务:不要调用任何工具,不要写文件,也不要给自己派活。只回一句「在」,然后等${address()}开口。`
3930
4103
  const base = {
3931
4104
  provider: 'spawn',
@@ -3951,6 +4124,7 @@ export function registerTeamTools(ctx, options) {
3951
4124
  taskId: chatId,
3952
4125
  bot: bot.id,
3953
4126
  parentSession: parent,
4127
+ rootSession,
3954
4128
  cwd: dir,
3955
4129
  startedAt: Date.now(),
3956
4130
  // 这是「入口标记」,不是在跑的活:立刻收尾,免得名册一直显示忙。
@@ -3961,19 +4135,12 @@ export function registerTeamTools(ctx, options) {
3961
4135
  })
3962
4136
  void persistTasks?.()
3963
4137
  options.api?.broadcast?.({ type: 'tasks' })
3964
- await debug?.({ event: 'chat-open', bot: bot.id, sessionId: childId })
4138
+ await debug?.({ event: 'chat-open', bot: bot.id, sessionId: childId, rootSession })
3965
4139
  // 父会话 id 一起回去:面板拿到就能直接开出「子会话」标签,
3966
4140
  // 不用等名册刷新(等那一下,用户第一次点必然失败)。
3967
4141
  // identity 也一起回去:面板拿它先写进头像映射,第一帧就不会顶着主会话的头像。
3968
4142
  // 字段跟 `/dsh-team/identity-map` 那份保持一致,改的时候两边一起改。
3969
- const identity = {
3970
- id: bot.id,
3971
- name: bot.name ?? bot.id,
3972
- src: `/dsh-team/avatar?bot=${encodeURIComponent(bot.id)}&v=3`,
3973
- onOpen: true,
3974
- speech: false,
3975
- }
3976
- return { ok: true, sessionId: childId, parentSessionId: parent, identity, bot: bot.id }
4143
+ return { ok: true, sessionId: childId, parentSessionId: parent, identity: chatIdentityOf(bot), bot: bot.id }
3977
4144
  } catch (error) {
3978
4145
  pending.delete(childId)
3979
4146
  return { ok: false, error: String(error?.message ?? error) }
@@ -4228,7 +4395,21 @@ export function installChildDecoration(ctx, options) {
4228
4395
  })
4229
4396
  pending.delete(header.id)
4230
4397
  // 恢复出来的子会话进这里:续聊等回复时 agents.get 可能拿不到它。
4231
- if (hit) liveChildren.set(header.id, agent)
4398
+ if (hit) {
4399
+ liveChildren.set(header.id, agent)
4400
+ // 面板的「在不在干活」以子会话自己报的状态为准:账本那行可能因为派活调用
4401
+ // 被中止而提前收成 ready,只认账本就会出现「人在干活、卡上写待命」。
4402
+ try {
4403
+ const botId = hit.bot?.id
4404
+ noteChildState(header.id, 'running', botId)
4405
+ agent.ctx.on('agent/status', (event) => {
4406
+ const state = typeof event === 'string' ? event : event?.status
4407
+ noteChildState(header.id, state, botId)
4408
+ })
4409
+ } catch (error) {
4410
+ void debug?.({ event: 'live-watch-failed', error: String(error?.message ?? error) })
4411
+ }
4412
+ }
4232
4413
  if (!hit) {
4233
4414
  // 没有派活记录也不一定是普通会话:根会话就是秘书,它也要知道知识库。
4234
4415
  if (!header.parentSession) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-rhine-lab-team",
3
- "version": "0.5.4",
3
+ "version": "0.5.6",
4
4
  "type": "module",
5
5
  "description": "给 DeepSeek Harness 配一个工作团队:每个 Bot 有自己的记忆、分工、头像和 ID;在你的指导下或自己干活,都能积累经验、升级成长,成为你最放心可靠的团队成员。灵感与 UI 参考《明日方舟》,与官方无关。",
6
6
  "license": "MIT",