dsh-team-bots 0.2.289 → 0.2.338

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.
Files changed (116) hide show
  1. package/README.md +12 -136
  2. package/docs/README.zh.md +15 -139
  3. package/docs/assets/channel-redesign.png +0 -0
  4. package/docs/assets/global-config-dark.png +0 -0
  5. package/docs/assets/global-config-light.png +0 -0
  6. package/docs/assets/global-config-light.zh.png +0 -0
  7. package/docs/assets/global-config-redesign.png +0 -0
  8. package/docs/assets/secrets-redesign.png +0 -0
  9. package/docs/assets/tasks.png +0 -0
  10. package/docs/assets/tasks.zh.png +0 -0
  11. package/docs/assets/usage-redesign-global.png +0 -0
  12. package/docs/assets/usage.png +0 -0
  13. package/docs/assets/usage.zh.png +0 -0
  14. package/package.json +17 -5
  15. package/scripts/doctor.mjs +4 -4
  16. package/src/api.js +6 -3
  17. package/src/botmsg.js +1 -1
  18. package/src/config.js +18 -8
  19. package/src/db-migrations.js +76 -9
  20. package/src/db.js +28 -2
  21. package/src/http.js +22 -3
  22. package/src/paths.js +32 -1
  23. package/src/pricing.js +2 -2
  24. package/src/runtime.js +1 -1
  25. package/src/secrets.js +4 -4
  26. package/src/service.js +10 -5
  27. package/src/services/approvals.js +109 -24
  28. package/src/services/bot-quota.js +242 -0
  29. package/src/services/bots.js +35 -6
  30. package/src/services/chat.js +15 -9
  31. package/src/services/core.js +33 -5
  32. package/src/services/hygiene.js +8 -4
  33. package/src/services/locale.js +17 -0
  34. package/src/services/memory.js +112 -1
  35. package/src/services/message-images.js +3 -3
  36. package/src/services/notify.js +99 -0
  37. package/src/services/projects.js +119 -10
  38. package/src/services/proposals.js +2 -3
  39. package/src/services/questions.js +75 -32
  40. package/src/services/review-watchdog.js +261 -30
  41. package/src/services/run-finish.js +119 -7
  42. package/src/services/runs.js +42 -13
  43. package/src/services/runtime/lifecycle.js +3 -1
  44. package/src/services/runtime/model-restore.js +5 -5
  45. package/src/services/runtime/prompt.js +106 -45
  46. package/src/services/runtime/session.js +38 -14
  47. package/src/services/runtime/trajectory.js +1 -1
  48. package/src/services/scheduler.js +139 -13
  49. package/src/services/secrets.js +1 -1
  50. package/src/services/system.js +23 -6
  51. package/src/services/task-notify.js +49 -7
  52. package/src/services/task-stage.js +4 -0
  53. package/src/services/tasks.js +121 -12
  54. package/src/services/terminal.js +2 -2
  55. package/src/services/vision-proxy.js +3 -3
  56. package/src/services/wechat.js +228 -7
  57. package/src/services/workspace-groups.js +4 -3
  58. package/src/skill-parse.js +1 -1
  59. package/src/skills.js +1 -1
  60. package/src/tools.js +275 -6
  61. package/src/updater.js +52 -0
  62. package/src/usage-reconcile.js +1 -1
  63. package/src/usage.js +52 -11
  64. package/src/wechat/channel.js +14 -20
  65. package/src/wechat/commands.js +129 -81
  66. package/src/wechat/format.js +247 -0
  67. package/src/wechat/store.js +30 -2
  68. package/ui/app.js +56 -52
  69. package/ui/i18n/en/chat.js +140 -0
  70. package/ui/i18n/en/common.js +189 -0
  71. package/ui/i18n/en/nav.js +90 -0
  72. package/ui/i18n/en/settings.js +354 -0
  73. package/ui/i18n/en/tasks.js +232 -0
  74. package/ui/i18n/en/usage.js +141 -0
  75. package/ui/i18n/en/wechat.js +24 -0
  76. package/ui/i18n/en.js +17 -237
  77. package/ui/i18n/zh/chat.js +140 -0
  78. package/ui/i18n/zh/common.js +189 -0
  79. package/ui/i18n/zh/nav.js +90 -0
  80. package/ui/i18n/zh/settings.js +354 -0
  81. package/ui/i18n/zh/tasks.js +232 -0
  82. package/ui/i18n/zh/usage.js +141 -0
  83. package/ui/i18n/zh/wechat.js +24 -0
  84. package/ui/i18n/zh.js +17 -236
  85. package/ui/modules/api.js +4 -3
  86. package/ui/modules/bot-quota.js +27 -0
  87. package/ui/modules/cards.js +96 -58
  88. package/ui/modules/chat.js +28 -30
  89. package/ui/modules/composer.js +41 -37
  90. package/ui/modules/dom-morph.js +292 -0
  91. package/ui/modules/events-board.js +22 -22
  92. package/ui/modules/events-click.js +100 -68
  93. package/ui/modules/events-misc.js +34 -34
  94. package/ui/modules/events-submit.js +28 -28
  95. package/ui/modules/global-pages.js +127 -116
  96. package/ui/modules/i18n.js +0 -5
  97. package/ui/modules/icons.js +0 -1
  98. package/ui/modules/markdown.js +1 -1
  99. package/ui/modules/modal-forms.js +195 -202
  100. package/ui/modules/modal-layer.js +6 -9
  101. package/ui/modules/page-shell.js +62 -0
  102. package/ui/modules/settings.js +211 -198
  103. package/ui/modules/solo-archive.js +0 -4
  104. package/ui/modules/state.js +57 -50
  105. package/ui/modules/tasks.js +168 -171
  106. package/ui/modules/typing-linger.js +1 -4
  107. package/ui/modules/usage.js +65 -78
  108. package/ui/modules/util.js +92 -25
  109. package/ui/styles/avatars.css +14 -0
  110. package/ui/styles/cards.css +49 -0
  111. package/ui/styles/chat-cards.css +17 -21
  112. package/ui/styles/global-config.css +59 -2
  113. package/ui/styles/modal.css +13 -0
  114. package/ui/styles/usage.css +3 -61
  115. package/CONTRIBUTING.md +0 -20
  116. package/docs/assets/usage-dark.png +0 -0
@@ -1,11 +1,11 @@
1
- // src/services/run-finish.js —— 运行收尾与交付派发域
1
+ // src/services/run-finish.ts —— 运行收尾与交付派发域
2
2
  // 运行结束后的用量记账、限流退避、attention 落库,以及按运行类别分发的后续动作
3
3
  // (任务交付与退回重派、私信回信、群聊/单聊回复、模型备用切换、失败转总监处理)。
4
- // 本文件只放方法体,方法挂到 TeamService 原型上(见 src/service.js 的 defineMethods 调用),
4
+ // 本文件只放方法体,方法挂到 TeamService 原型上(见 src/service.ts 的 defineMethods 调用),
5
5
  // 因此方法体内的 this 与拆分前完全一致。
6
6
 
7
7
  import { runUsageTotals } from '../usage.js'
8
- import { id, nowIso, text } from '../util.js'
8
+ import { id, nowIso, parseMentions, text } from '../util.js'
9
9
  import { rolloverSummaryKey } from '../config.js'
10
10
  import {
11
11
  isQuotaExhausted,
@@ -16,6 +16,7 @@ import {
16
16
  } from './backoff.js'
17
17
  import { ensureAttentionSchema, normalizeAttention } from './attention-schema.js'
18
18
  import { completeVisionRun, maybeSpawnVisionAfterFailure } from './vision-proxy.js'
19
+ import { chatReply } from '../wechat/format.js'
19
20
 
20
21
  export const runFinishMethods = {
21
22
  // 自动核验委派(DSHBOTS-113):交付迁移 in_review 的同一事务内调用。开关关闭或
@@ -49,7 +50,7 @@ export const runFinishMethods = {
49
50
  })
50
51
  return true
51
52
  },
52
- async finishRun({ runId, status, output, error, attention }) {
53
+ async finishRun({ runId, status, output, error, attention } ) {
53
54
  const run = this.runRow(runId)
54
55
  if (!['running', 'queued'].includes(run.status)) return
55
56
  ensureAttentionSchema(this.store)
@@ -83,6 +84,30 @@ export const runFinishMethods = {
83
84
  'INSERT INTO run_events(id, run_id, type, message, created_at) VALUES (?, ?, ?, ?, ?)',
84
85
  id('evt'), runId, status, error?.message ?? (status === 'succeeded' ? '完成' : ''), endedAt,
85
86
  )
87
+ // DSHBOTS-241:撞 provider 额度墙时记录该 bot 的额度状态(含恢复时间),
88
+ // 供派发前路由(耗尽期走备用模型/排队)与 UI 手动解除;审计 bot.quota_exhausted。
89
+ // DSHBOTS-246:事件与状态记录同条件——只有真撞墙才写「额度耗尽」,成功运行或
90
+ // 非额度失败一律不记,否则每个 run 收尾都污染一条额度耗尽时间线。
91
+ if (quotaExhausted && run.bot_id && bot) {
92
+ const effectiveProvider = run.model_provider || bot.provider
93
+ if (effectiveProvider) {
94
+ const quotaRecorded = this.recordBotQuotaExhaustion({
95
+ botId: run.bot_id,
96
+ provider: effectiveProvider,
97
+ errorCode: error?.code ?? null,
98
+ errorMessage: error?.message ?? '',
99
+ retryAfterMs: Number(error?.retryAfterMs) > 0 ? Number(error.retryAfterMs) : null,
100
+ })
101
+ if (quotaRecorded) {
102
+ const resetNote = quotaRecorded.resetAt ? `,预计 ${quotaRecorded.resetAt} 恢复` : ''
103
+ this.insertRunEvent(
104
+ runId,
105
+ 'quota_exhausted',
106
+ `额度耗尽(${quotaRecorded.provider})${resetNote},耗尽期内新任务改走备用模型或排队等待`,
107
+ )
108
+ }
109
+ }
110
+ }
86
111
  // DSHBOTS-172 代码卫生:每轮运行结束扫一次项目工作区行数约定,超标即发系统指令告警
87
112
  // (去重与阈值见 hygiene.js);扫描自身全量兜错,不阻塞收尾主流程。
88
113
  this.runCodeHygieneScan(project, runId)
@@ -296,25 +321,35 @@ export const runFinishMethods = {
296
321
  }
297
322
  }
298
323
  } else if (run.kind === 'chat') {
299
- this.insertMessage({
324
+ const replyMessageId = this.insertMessage({
300
325
  projectId: project.id,
301
326
  senderType: 'bot',
302
327
  senderId: bot.id,
303
328
  body: cleanOutput || '模型未返回文本。',
304
329
  runId,
305
330
  })
331
+ // DSHBOTS-252:chat 运行成功回复正文与用户消息同语义解析 @mention 并派发 chat_run
332
+ // 唤醒目标 bot。触发面仅此一处(验收/受阻摘要、失败提示、通知、任务卡、solo/dm
333
+ // 落库一律不触发);剥空不落库的回复(insertMessage 返回 null)同样不派发。
334
+ const wokenBotIds = this.dispatchBotMentionRuns(project, run, bot, replyMessageId)
335
+ if (wokenBotIds.length > 0) void this.tick()
336
+ this.notifyWechatChat(bot, run, cleanOutput || '模型未返回文本。')
306
337
  // 群聊回复后的自动记忆审查(可在设置关闭;与任务交付审查同一队列同一幂等键规则)。
307
338
  if (this.chatMemoryReviewEnabled()) {
308
339
  this.enqueueMemoryReview(project, bot, null, runId)
309
340
  }
310
341
  } else if (run.kind === 'solo_chat') {
342
+ const reply = cleanOutput || '模型未返回文本。'
311
343
  this.insertSoloMessage({
312
344
  botId: bot.id,
313
345
  senderType: 'bot',
314
346
  senderId: bot.id,
315
- body: cleanOutput || '模型未返回文本。',
347
+ body: reply,
316
348
  runId,
317
349
  })
350
+ // DSHBOTS-258:微信通道投的项目外 director 单聊(trigger_type='wechat'),
351
+ // 回复同样推回微信管理员;普通 UI 单聊(mention)不推。
352
+ this.notifyWechatChat(bot, run, reply)
318
353
  }
319
354
  } else {
320
355
  // DSHBOTS-112:无视觉模型收图失败的兜底信号——错误表明模型无视觉且消息带图时补派生
@@ -400,16 +435,93 @@ export const runFinishMethods = {
400
435
  body: `运行失败:${error?.message ?? '未知错误'}`,
401
436
  runId,
402
437
  })
438
+ this.notifyWechatChat(bot, run, `运行失败:${error?.message ?? '未知错误'}`, true)
403
439
  } else if (run.kind === 'solo_chat') {
440
+ const failure = `运行失败:${error?.message ?? '未知错误'}`
404
441
  this.insertSoloMessage({
405
442
  botId: bot.id,
406
443
  senderType: 'bot',
407
444
  senderId: bot.id,
408
- body: `运行失败:${error?.message ?? '未知错误'}`,
445
+ body: failure,
409
446
  runId,
410
447
  })
448
+ // DSHBOTS-258:微信通道的 solo 直达失败提示同样推回(notifyWechatChat 内部按
449
+ // trigger_type='wechat' 门禁,普通 UI 单聊不推)。
450
+ this.notifyWechatChat(bot, run, failure, true)
411
451
  }
412
452
  }
413
453
  if (run.project_id && this.rate[run.project_id]) delete this.rate[run.project_id]
414
454
  },
455
+
456
+ // 微信直达对话回程(DSHBOTS-208/258):trigger_type='wechat' 的运行(项目群聊直达、
457
+ // 项目外 director 专属工作区 solo 直达)结束时,把 bot 回复(或失败提示)推回微信管理员,出站走通道既有合批/重试治理;
458
+ // 只推微信触发的运行,工作台群聊回复不受影响。推送失败不阻塞收尾主流程。
459
+ // 排版(头部标记/分隔线)集中在 wechat/format.js 的 chatReply(DSHBOTS-211)。
460
+ notifyWechatChat(bot, run, body, failed = false) {
461
+ if (run?.trigger_type !== 'wechat' || !this.wechat) return
462
+ try {
463
+ this.wechat.notify(chatReply(bot?.name ?? 'Bot', body, failed))
464
+ } catch (error ) {
465
+ this.logger.warn?.('dsh-team: 微信直达回复推送失败: %s', error?.message ?? error)
466
+ }
467
+ },
468
+
469
+ // ── Bot 群聊回复 mention 唤醒(DSHBOTS-252)────────────────────────────
470
+ // 与用户消息同语义(chat.ts sendMessage):@xxx 用 parseMentions 解析 active 成员、
471
+ // 显式 @ 优先(bot 路径无引用兜底道)、目标 slice(0,3);派发走既有 chat_run outbox →
472
+ // enqueueChatRun,串行车道沿用 D-219 的 project lane(sessionLaneKey 对 kind='chat'
473
+ // 恒为 project:<bot>:<project>),不新建串行道。防循环三护栏:
474
+ // ① 禁自唤醒——解析结果剔除回复 bot 自身;
475
+ // ② 链路深度 ≤2——chatMentionChainDepth 回溯来源链,本回复链深达 2 即不再派发;
476
+ // ③ 任务卡双保险——taskId 非空的消息不参与派发(群聊 messages 表无 kind 列,
477
+ // 「kind 恒为 text」由结构保证;带 kind 的 solo 落库点不触发本派发)。
478
+ chatMentionChainDepth(run) {
479
+ let depth = 0
480
+ let ref = run?.trigger_ref
481
+ const seen = new Set()
482
+ while (depth < 2 && ref && !seen.has(ref)) {
483
+ seen.add(ref)
484
+ const message = this.store.get('SELECT sender_type, run_id FROM messages WHERE id = ?', ref)
485
+ // 人发消息与结构化 bot 落库(notify 等无 run_id 的 bot 消息)都是链根,回溯到此为止。
486
+ if (!message || message.sender_type !== 'bot' || !message.run_id) break
487
+ const parent = this.store.get('SELECT kind, trigger_ref FROM runs WHERE id = ?', message.run_id)
488
+ if (!parent || parent.kind !== 'chat' || !parent.trigger_ref) break
489
+ depth += 1
490
+ ref = parent.trigger_ref
491
+ }
492
+ return depth
493
+ },
494
+
495
+ // 对 bot 回复正文解析 @mention 并派发 chat_run;返回被唤醒的 bot id 列表。
496
+ // 解析对象是落库行正文(已过剥残片+密钥掩码两道清洗),与所有成员读到的转录一致。
497
+ dispatchBotMentionRuns(project, run, bot, messageId) {
498
+ if (!messageId) return []
499
+ // 护栏三双保险:唯一调用点不带 taskId,这里按落库行复核,兜未来调用面扩张。
500
+ const message = this.store.get('SELECT id, task_id, body FROM messages WHERE id = ?', messageId)
501
+ if (!message || message.task_id) return []
502
+ const members = this.membersOf(project.id).filter(member => member.status === 'active')
503
+ // 护栏一:禁自唤醒——剔除回复 bot 自身。
504
+ const targets = parseMentions(message.body, members).filter(member => member.id !== bot.id)
505
+ if (targets.length === 0) return []
506
+ // mentions_json 记录过滤后的全部 @ 目标(对齐用户路径的 UI mention 渲染口径),
507
+ // 与实际派发数(slice(0,3))允许在 >3 目标时不同。
508
+ this.store.run(
509
+ 'UPDATE messages SET mentions_json = ? WHERE id = ?',
510
+ JSON.stringify(targets.map(member => member.id)), messageId,
511
+ )
512
+ // 护栏二:链路深度 ≤2——深度达 2 的 bot 回复不再派发。
513
+ if (this.chatMentionChainDepth(run) >= 2) return []
514
+ const dispatched = targets.slice(0, 3)
515
+ for (const target of dispatched) {
516
+ this.enqueueOutbox({
517
+ kind: 'chat_run',
518
+ payload: { projectId: project.id, botId: target.id, messageId, origin: null },
519
+ projectId: project.id,
520
+ sourceId: messageId,
521
+ // 幂等键与用户路径(chat:<id>:<bot>)前缀区分,outbox 一眼可辨唤醒来源。
522
+ idempotencyKey: `chat_bot:${messageId}:${target.id}`,
523
+ })
524
+ }
525
+ return dispatched.map(member => member.id)
526
+ },
415
527
  }
@@ -96,11 +96,11 @@ export const runsMethods = {
96
96
  const kind = message.origin_kind === 'task' ? 'task' : message.origin_kind === 'dm' ? 'dm' : 'project'
97
97
  const binding = message.origin_kind === 'task' && message.origin_task_id
98
98
  ? this.store.get(
99
- "SELECT * FROM session_bindings WHERE bot_id = ? AND project_id = ? AND kind = 'task' AND task_id = ?",
99
+ "SELECT * FROM session_bindings WHERE bot_id = ? AND project_id = ? AND kind = 'task' AND task_id = ? AND alias = 0",
100
100
  caller.id, message.project_id, message.origin_task_id,
101
101
  )
102
102
  : this.store.get(
103
- 'SELECT * FROM session_bindings WHERE bot_id = ? AND project_id = ? AND kind = ?',
103
+ 'SELECT * FROM session_bindings WHERE bot_id = ? AND project_id = ? AND kind = ? AND alias = 0',
104
104
  caller.id, message.project_id, kind,
105
105
  )
106
106
  // 无绑定(会话被轮换清理或首次私信):走 dm_reply 运行,由 startRun 重建会话。
@@ -110,7 +110,7 @@ export const runsMethods = {
110
110
  } else {
111
111
  try {
112
112
  plan = deliveryPlan({ row: message, callerSessionBusy: this.runtime.sessionBusy(binding.session_id) })
113
- } catch (error) {
113
+ } catch (error ) {
114
114
  this.logger.warn?.('dsh-team: 私信 %s 投递计划失败:%s', message.id, error?.message ?? error)
115
115
  return null
116
116
  }
@@ -142,7 +142,9 @@ export const runsMethods = {
142
142
  this.insertRunEvent(runId, 'queued', '私信回信排队投递给发送方会话')
143
143
  return runId
144
144
  },
145
- enqueueSoloChatRun(bot, messageId) {
145
+ // triggerType(DSHBOTS-258):'wechat' 表示消息来自微信通道(项目外 director 专属工作区),
146
+ // 与群聊直达(enqueueChatRun 的 origin 口径)同语义——运行收尾据此把 solo 回复推回微信管理员。
147
+ enqueueSoloChatRun(bot, messageId, { triggerType = 'mention' } = {}) {
146
148
  const existing = this.store.get(
147
149
  "SELECT id FROM runs WHERE trigger_ref = ? AND bot_id = ? AND kind = 'solo_chat'",
148
150
  messageId,
@@ -154,16 +156,18 @@ export const runsMethods = {
154
156
  this.store.run(
155
157
  `INSERT INTO runs(id, project_id, bot_id, kind, mode, trigger_type, trigger_ref, status,
156
158
  attempt, idempotency_key, queued_at)
157
- VALUES (?, NULL, ?, 'solo_chat', 'write', 'mention', ?, 'queued', 1, ?, ?)`,
158
- runId, bot.id, messageId, `solo_chat:${messageId}`, createdAt,
159
+ VALUES (?, NULL, ?, 'solo_chat', 'write', ?, ?, 'queued', 1, ?, ?)`,
160
+ runId, bot.id, triggerType, messageId, `solo_chat:${messageId}`, createdAt,
159
161
  )
160
162
  this.store.run(
161
163
  'INSERT INTO run_events(id, run_id, type, message, created_at) VALUES (?, ?, ?, ?, ?)',
162
- id('evt'), runId, 'queued', '单聊消息触发', createdAt,
164
+ id('evt'), runId, 'queued',
165
+ triggerType === 'wechat' ? '微信消息触发(项目外单聊直达)' : '单聊消息触发',
166
+ createdAt,
163
167
  )
164
168
  return runId
165
169
  },
166
- enqueueChatRun(project, bot, messageId) {
170
+ enqueueChatRun(project, bot, messageId, origin = null) {
167
171
  if (bot.status !== 'active') return null
168
172
  const existing = this.store.get(
169
173
  "SELECT id FROM runs WHERE trigger_ref = ? AND bot_id = ? AND kind = 'chat'",
@@ -173,15 +177,17 @@ export const runsMethods = {
173
177
  if (existing) return existing.id
174
178
  const runId = id('run')
175
179
  const createdAt = nowIso()
180
+ // 微信直达(DSHBOTS-208):trigger_type 记 'wechat',运行收尾据此把 bot 回复推回微信管理员。
181
+ const triggerType = origin === 'wechat' ? 'wechat' : 'mention'
176
182
  this.store.run(
177
183
  `INSERT INTO runs(id, project_id, bot_id, kind, mode, trigger_type, trigger_ref, status,
178
184
  attempt, idempotency_key, queued_at)
179
- VALUES (?, ?, ?, 'chat', 'read', 'mention', ?, 'queued', 1, ?, ?)`,
180
- runId, project.id, bot.id, messageId, `chat:${messageId}:${bot.id}`, createdAt,
185
+ VALUES (?, ?, ?, 'chat', 'read', ?, ?, 'queued', 1, ?, ?)`,
186
+ runId, project.id, bot.id, triggerType, messageId, `chat:${messageId}:${bot.id}`, createdAt,
181
187
  )
182
188
  this.store.run(
183
189
  'INSERT INTO run_events(id, run_id, type, message, created_at) VALUES (?, ?, ?, ?, ?)',
184
- id('evt'), runId, 'queued', '群聊消息触发', createdAt,
190
+ id('evt'), runId, 'queued', triggerType === 'wechat' ? '微信群聊消息触发(直达)' : '群聊消息触发', createdAt,
185
191
  )
186
192
  return runId
187
193
  },
@@ -297,6 +303,8 @@ export const runsMethods = {
297
303
  : (run.kind === 'solo_chat' || (run.kind === 'vision' && !run.project_id)) && run.trigger_ref
298
304
  ? this.store.get('SELECT * FROM solo_messages WHERE id = ?', run.trigger_ref)
299
305
  : null
306
+ // 合批消息(DSHBOTS-231):领取时合并进来的同通道排队消息,与触发消息同一轮注入。
307
+ const extraMessages = this.mergedMessagesFor(run)
300
308
  if (run.mode === 'read') this.fingerprints.set(runId, this.workspaceFingerprint(project))
301
309
  const sessionKind = this.sessionKindFor(run)
302
310
  await this.runtime.startRun({
@@ -305,9 +313,10 @@ export const runsMethods = {
305
313
  project,
306
314
  task: task ?? this.sessionTaskFor(run, sessionKind),
307
315
  chatMessage,
316
+ extraMessages,
308
317
  sessionKind,
309
318
  })
310
- } catch (error) {
319
+ } catch (error ) {
311
320
  this.logger.warn?.('dsh-team: run %s failed to start: %s', runId, error)
312
321
  this.fingerprints.delete(runId)
313
322
  await this.finishRun({
@@ -350,6 +359,24 @@ if (run.kind === 'dm_reply') {
350
359
  if (!taskId) return null
351
360
  return this.store.get('SELECT * FROM tasks WHERE id = ?', taskId) ?? null
352
361
  },
362
+
363
+ // 合批消息(DSHBOTS-231):本运行领取时合并进来的同通道排队消息。
364
+ // 按 merged_messages 记录的消息 id 顺序取回;消息已被删除的条目跳过,不阻塞本次运行。
365
+ // 两张消息表的列不完全一致(solo_messages 没有 reply_to_id),按运行类别选列。
366
+ mergedMessagesFor(run) {
367
+ const ids = jsonParse(run.merged_messages, [])
368
+ if (!Array.isArray(ids) || !ids.length) return []
369
+ const columns = run.kind === 'solo_chat'
370
+ ? 'id, sender_type, sender_id, body'
371
+ : 'id, sender_type, sender_id, body, reply_to_id'
372
+ const table = run.kind === 'solo_chat' ? 'solo_messages' : 'messages'
373
+ const rows = []
374
+ for (const messageId of ids) {
375
+ const row = this.store.get(`SELECT ${columns} FROM ${table} WHERE id = ?`, messageId)
376
+ if (row) rows.push(row)
377
+ }
378
+ return rows
379
+ },
353
380
  insertRunEvent(runId, type, message) {
354
381
  if (!runId) return
355
382
  this.store.run(
@@ -516,13 +543,15 @@ if (run.kind === 'dm_reply') {
516
543
  const task = run.task_id ? this.store.get('SELECT number, title, sandbox_override FROM tasks WHERE id = ?', run.task_id) : undefined
517
544
  const project = run.project_id ? this.store.get('SELECT key FROM projects WHERE id = ?', run.project_id) : undefined
518
545
  // recovery 是重启恢复的内部瞬态标记(置位→注入→清零),不属于 API 视图,随 attention_json 一并剥出。
519
- const { write_scopes: rawScopes, attention_json: attentionJson, recovery: _recovery, ...rest } = run
546
+ // merged_messages 是合批消息 id 列表(DSHBOTS-231),同样剥出原始 JSON,只给解析后的 id。
547
+ const { write_scopes: rawScopes, attention_json: attentionJson, merged_messages: mergedRaw, recovery: _recovery, ...rest } = run
520
548
  const fallbackRef = bot?.fallback_provider && bot?.fallback_model ? `${bot.fallback_provider}/${bot.fallback_model}` : null
521
549
  const usedRef = run.model_provider && run.model_model ? `${run.model_provider}/${run.model_model}` : null
522
550
  return {
523
551
  ...rest,
524
552
  artifacts: jsonParse(run.artifacts, []),
525
553
  attention: parseAttention(attentionJson),
554
+ mergedMessageIds: Array.isArray(jsonParse(mergedRaw, [])) ? jsonParse(mergedRaw, []) : [],
526
555
  botName: bot?.name ?? 'Bot',
527
556
  taskIdentifier: task ? `${project?.key ?? 'T'}-${task.number}` : null,
528
557
  taskTitle: task?.title ?? null,
@@ -181,7 +181,9 @@ export const lifecycleMethods = {
181
181
  const row = recordUsage(this.store, {
182
182
  sourceKey,
183
183
  sourceEventId: messageId || null,
184
- run: { id: pending.runId, project_id: pending.projectId, bot_id: pending.bot.id },
184
+ // task_id(DSHBOTS-212):任务运行的用量归因到任务,支撑任务级端到端成本聚合
185
+ // (taskUsageTotals 经 COALESCE(u.task_id, r.task_id) 同时追认历史行)。
186
+ run: { id: pending.runId, project_id: pending.projectId, bot_id: pending.bot.id, task_id: pending.taskId ?? null },
185
187
  provider: pending.bot.provider ?? '',
186
188
  model: pending.bot.model ?? '',
187
189
  usage,
@@ -76,8 +76,8 @@ const HOST_NESTED_REJECTION = /^HMR transactions cannot be nested$/
76
76
  // 超时错误单独标记,便于与业务失败区分(超时不再重试:重试只会再排一次队)。
77
77
  // cause 保留最后一次真实失败原因:超时/预算耗尽只是「没等到」,不是失败本身,
78
78
  // 审计与 warn 必须同时看得见真正的业务错误。
79
- class RestoreTimeoutError extends Error {
80
- constructor(ms, cause) {
79
+ class RestoreTimeoutError extends Error {
80
+ constructor(ms, cause ) {
81
81
  const detail = describeCause(cause)
82
82
  super(`restore default model timed out after ${ms}ms${detail ? ` (last error: ${detail})` : ''}`)
83
83
  this.name = 'RestoreTimeoutError'
@@ -130,7 +130,7 @@ const withTimeout = async (fn, waitMs, onLate) => {
130
130
  // 返回是否恢复成功。失败必须可见:重试穷尽后 warn 一次并写审计 model_restore_failed,
131
131
  // 审计自身异常只 warn,不把失败抛回 selectModel 的串行链。
132
132
  // hooks.hmr:宿主 HMR 服务实例(ctx.get('hmr')),用于拿到 executing 做事务逃逸。
133
- export async function restoreDefaultModel(defaults, before, hooks = {}) {
133
+ export async function restoreDefaultModel(defaults, before, hooks = {} ) {
134
134
  const {
135
135
  logger,
136
136
  audit,
@@ -216,7 +216,7 @@ export async function restoreDefaultModel(defaults, before, hooks = {}) {
216
216
  logger?.debug?.('dsh-team: restore default model ok via %s', escape)
217
217
  } catch {}
218
218
  return true
219
- } catch (error) {
219
+ } catch (error ) {
220
220
  lastError = error
221
221
  if (error instanceof RestoreTimeoutError) {
222
222
  // 调用排在宿主事务队列尾且迟迟不落地:重试只会再排一次队,直接收口。
@@ -266,7 +266,7 @@ export async function restoreDefaultModel(defaults, before, hooks = {}) {
266
266
  ...(budgetExhausted ? { budgetExhausted: true } : {}),
267
267
  ...(cause ? { cause } : {}),
268
268
  })
269
- } catch (error) {
269
+ } catch (error ) {
270
270
  try {
271
271
  logger?.warn?.('dsh-team: model restore audit failed: %s', error)
272
272
  } catch {}