dsh-team-bots 0.3.79 → 0.3.98

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 (46) hide show
  1. package/cordis.patch.yml +100 -0
  2. package/index.js +5 -2
  3. package/package.json +1 -1
  4. package/src/api.js +5 -1
  5. package/src/db-migrations.js +3 -0
  6. package/src/db.js +53 -0
  7. package/src/runtime.js +13 -1
  8. package/src/service.js +5 -0
  9. package/src/services/approvals.js +7 -2
  10. package/src/services/bots.js +8 -1
  11. package/src/services/chat-stores.js +564 -0
  12. package/src/services/chat.js +60 -28
  13. package/src/services/core.js +30 -10
  14. package/src/services/feishu.js +1 -1
  15. package/src/services/memory.js +14 -12
  16. package/src/services/model-fallback.js +3 -1
  17. package/src/services/notify.js +18 -8
  18. package/src/services/projects.js +25 -19
  19. package/src/services/questions.js +2 -1
  20. package/src/services/review-watchdog.js +31 -12
  21. package/src/services/run-finish.js +17 -13
  22. package/src/services/runs.js +29 -41
  23. package/src/services/runtime/context-window.js +6 -4
  24. package/src/services/runtime/lifecycle.js +1 -0
  25. package/src/services/runtime/prompt.js +21 -9
  26. package/src/services/runtime/sandbox-policy.js +1 -1
  27. package/src/services/runtime/session.js +22 -13
  28. package/src/services/runtime/trajectory.js +3 -1
  29. package/src/services/scheduler.js +63 -54
  30. package/src/services/system.js +9 -7
  31. package/src/services/task-dispatch.js +28 -21
  32. package/src/services/task-review.js +34 -25
  33. package/src/services/task-runs.js +40 -21
  34. package/src/services/tasks.js +34 -18
  35. package/src/services/terminal.js +25 -14
  36. package/src/services/vision-proxy.js +9 -6
  37. package/src/services/wechat.js +1 -1
  38. package/src/subagent-ledger.js +23 -6
  39. package/src/usage-reconcile.js +93 -32
  40. package/src/usage.js +125 -50
  41. package/ui/i18n/en/settings.js +1 -0
  42. package/ui/i18n/zh/settings.js +1 -0
  43. package/ui/modules/modal-forms.js +8 -8
  44. package/ui/modules/tasks.js +1 -1
  45. package/ui/styles/cards.css +13 -0
  46. package/ui/styles/modal.css +2 -0
@@ -143,19 +143,29 @@ const judgeCard = (service, row) => {
143
143
  ORDER BY COALESCE(ended_at, queued_at) DESC LIMIT 1`,
144
144
  row.id,
145
145
  )
146
- const delivery = service.store.get(
147
- `SELECT output FROM runs WHERE task_id = ? AND kind = 'task' AND status = 'succeeded'
146
+ const deliveryRun = service.store.get(
147
+ `SELECT id, project_id, bot_id FROM runs WHERE task_id = ? AND kind = 'task' AND status = 'succeeded'
148
148
  AND COALESCE(error_code, '') <> 'SUPERSEDED'
149
149
  ORDER BY ended_at DESC LIMIT 1`,
150
150
  row.id,
151
151
  )
152
+ // Phase 3:output 住运行归属聊天库的 run_payload(顶库 runs 已瘦身)。
153
+ const delivery = deliveryRun
154
+ ? service.runChatStore(deliveryRun).get('SELECT output FROM run_payload WHERE run_id = ?', deliveryRun.id)
155
+ : null
152
156
  // 子代理核验结论(DSHBOTS-235 用户拍板):最近一次成功核验委派运行的 output(含结束时间,
153
157
  // 供 B 压 A 时序降级比较「建议 accept」是否晚于失败 run)。
154
- const review = service.store.get(
155
- `SELECT output, ended_at FROM runs WHERE task_id = ? AND trigger_type = 'review_delegate' AND status = 'succeeded'
158
+ const reviewRun = service.store.get(
159
+ `SELECT id, project_id, bot_id, ended_at FROM runs WHERE task_id = ? AND trigger_type = 'review_delegate' AND status = 'succeeded'
156
160
  ORDER BY ended_at DESC LIMIT 1`,
157
161
  row.id,
158
162
  )
163
+ const review = reviewRun
164
+ ? {
165
+ ended_at: reviewRun.ended_at,
166
+ output: service.runChatStore(reviewRun).get('SELECT output FROM run_payload WHERE run_id = ?', reviewRun.id)?.output ?? '',
167
+ }
168
+ : null
159
169
  const report = delivery?.output ?? ''
160
170
  const verify = report
161
171
  ? commitOnDevVerifier(service.projectWorkDir(service.projectRow(row.project_id)))
@@ -203,12 +213,17 @@ export function runReviewWatchdog(service) {
203
213
  const rows = service.store.all(`
204
214
  SELECT t.id, t.project_id, t.updated_at, t.assignee_bot_id, p.key AS project_key, t.number,
205
215
  t.review_target,
206
- (SELECT MAX(c.created_at) FROM task_comments c WHERE c.task_id = t.id) AS last_comment_at,
207
216
  (SELECT MAX(COALESCE(r.last_progress_at, r.ended_at, r.started_at, r.queued_at))
208
217
  FROM runs r WHERE r.task_id = t.id) AS last_run_at
209
218
  FROM tasks t JOIN projects p ON p.id = t.project_id
210
219
  WHERE t.status = 'in_review' AND p.status = 'active'
211
220
  `)
221
+ // 评论锚点住各项目聊天库(chat-db-split Phase 3):逐卡按 project_id 取,行字段形状不变。
222
+ for (const row of rows) {
223
+ row.last_comment_at = service.groupChatStore(row.project_id).get(
224
+ 'SELECT MAX(created_at) AS v FROM task_comments WHERE task_id = ?', row.id,
225
+ )?.v ?? null
226
+ }
212
227
  const map = JSON.parse(service.store.setting(REVIEW_IDLE_ALERTED_KEY) ?? '{}')
213
228
  const inReviewIds = new Set(rows.map(row => row.id))
214
229
  // 去重表回收:已离开 in_review(或已删除)的卡摘除,恢复再报资格。
@@ -295,13 +310,17 @@ export function runReviewWatchdog(service) {
295
310
  // (含最新评论与 run 活动,UI badge 不再自算口径)+ 生效阈值/升级线 + 最近一次判定与依据。
296
311
  export const reviewWatchdogMethods = {
297
312
  reviewIdleView(task) {
298
- const anchors = this.store.get(
299
- `SELECT
300
- (SELECT MAX(c.created_at) FROM task_comments c WHERE c.task_id = ?) AS last_comment_at,
301
- (SELECT MAX(COALESCE(r.last_progress_at, r.ended_at, r.started_at, r.queued_at))
302
- FROM runs r WHERE r.task_id = ?) AS last_run_at`,
303
- task.id, task.id,
304
- )
313
+ // 评论锚点住任务所属项目的聊天库(chat-db-split Phase 3);runs 锚点仍在顶库。
314
+ const anchors = {
315
+ last_comment_at: this.groupChatStore(task.project_id).get(
316
+ 'SELECT MAX(created_at) AS v FROM task_comments WHERE task_id = ?', task.id,
317
+ )?.v ?? null,
318
+ last_run_at: this.store.get(
319
+ `SELECT MAX(COALESCE(r.last_progress_at, r.ended_at, r.started_at, r.queued_at)) AS v
320
+ FROM runs r WHERE r.task_id = ?`,
321
+ task.id,
322
+ )?.v ?? null,
323
+ }
305
324
  const anchorMs = latestAnchorMs({
306
325
  updated_at: task.updated_at,
307
326
  last_comment_at: anchors?.last_comment_at ?? null,
@@ -104,7 +104,7 @@ export const runFinishMethods = {
104
104
  const bot = this.store.get('SELECT * FROM bots WHERE id = ?', run.bot_id)
105
105
  const project = this.store.get('SELECT * FROM projects WHERE id = ?', run.project_id)
106
106
  this.auditReadRunWrites(run, project)
107
- const usage = runUsageTotals(this.store, runId, this.budgetCurrency())
107
+ const usage = runUsageTotals(this.runChatStore(run), runId, this.budgetCurrency(), this.store)
108
108
  const cleanOutput = this.maskSecretValues(text(output, 120_000))
109
109
  const artifactsJson = status === 'succeeded' && run.mode === 'write' && project
110
110
  ? this.captureRunArtifacts(run, project)
@@ -126,18 +126,20 @@ export const runFinishMethods = {
126
126
  // 额度耗尽时 provider 真给的重置时间照样保留(信息不丢,供 UI 显示额度恢复时间),
127
127
  // 但它不再触发对主模型的自动重试(见下方失败分支与 scheduler.retryExpiredPlanWaits)。
128
128
  const retryAfterMs = Number(error?.retryAfterMs) > 0 ? Number(error.retryAfterMs) : synthesizedMs
129
- this.store.run(
130
- `UPDATE runs SET status = ?, output = ?, artifacts = ?, error_code = ?, error_message = ?, retry_after_ms = ?, ended_at = ?,
129
+ const changed = this.store.run(
130
+ `UPDATE runs SET status = ?, error_code = ?, error_message = ?, retry_after_ms = ?, ended_at = ?,
131
131
  usage_input = ?, usage_cache_read = ?, usage_cache_write = ?, usage_output = ?, usage_cost = ?
132
132
  WHERE id = ? AND status IN ('running', 'queued')`,
133
- status, cleanOutput, artifactsJson, error?.code ?? null, error?.message ?? null, retryAfterMs, endedAt,
133
+ status, error?.code ?? null, error?.message ?? null, retryAfterMs, endedAt,
134
134
  usage.inputTokens, usage.cacheReadTokens, usage.cacheWriteTokens, usage.outputTokens, usage.cost,
135
135
  runId,
136
136
  )
137
- this.store.run(
138
- 'INSERT INTO run_events(id, run_id, type, message, created_at) VALUES (?, ?, ?, ?, ?)',
139
- id('evt'), runId, status, error?.message ?? (status === 'succeeded' ? '完成' : ''), endedAt,
140
- )
137
+ // Phase 3:output/artifacts 住运行归属聊天库的 run_payload(顶库 runs 已瘦身)。
138
+ // 收尾 UPDATE 未命中(运行已终态)时不写载荷,避免覆盖既有结果。
139
+ if (Number(changed?.changes ?? 0) === 1) {
140
+ this.saveRunPayload(run, { output: cleanOutput, artifacts: artifactsJson })
141
+ }
142
+ this.insertRunEvent(runId, status, error?.message ?? (status === 'succeeded' ? '完成' : ''))
141
143
  // DSHBOTS-241:撞 provider 额度墙时记录该 bot 的额度状态(含恢复时间),
142
144
  // 供派发前路由(耗尽期走备用模型/排队)与 UI 手动解除;审计 bot.quota_exhausted。
143
145
  // DSHBOTS-246:事件与状态记录同条件——只有真撞墙才写「额度耗尽」,成功运行或
@@ -384,12 +386,12 @@ export const runFinishMethods = {
384
386
  // 施工方式由 bot 自选(亲做或派「bot 名+任务号」子代理),账本(D-294)仍照记。
385
387
  this.store.transaction(() => {
386
388
  this.setTaskStatus(task.id, 'in_review', { type: 'bot', id: bot.id })
387
- this.store.run(
389
+ this.store.afterCommit(() => this.groupChatStore(task.project_id).run(
388
390
  'INSERT INTO task_comments(id, task_id, author_type, author_id, body, created_at) VALUES (?, ?, ?, ?, ?, ?)',
389
391
  id('cmt'), task.id, 'bot', bot.id,
390
392
  cleanOutput || '运行完成,但模型未返回文本。',
391
393
  endedAt,
392
- )
394
+ ))
393
395
  this.addTaskEvent(task.id, 'run_succeeded', { type: 'bot', id: bot.id }, { runId, identifier: `${project.key}-${task.number}` })
394
396
  // 自动核验委派(DSHBOTS-113):与 in_review 迁移同一事务触发留痕;实际派生由
395
397
  // review_delegate_auto outbox 承接(幂等键绑定本次交付运行),守卫冲突的退避重试
@@ -607,9 +609,10 @@ export const runFinishMethods = {
607
609
  let depth = 0
608
610
  let ref = run?.trigger_ref
609
611
  const seen = new Set()
612
+ const chatStore = this.runChatStore(run)
610
613
  while (depth < 2 && ref && !seen.has(ref)) {
611
614
  seen.add(ref)
612
- const message = this.store.get('SELECT sender_type, run_id FROM messages WHERE id = ?', ref)
615
+ const message = chatStore.get('SELECT sender_type, run_id FROM messages WHERE id = ?', ref)
613
616
  // 人发消息与结构化 bot 落库(notify 等无 run_id 的 bot 消息)都是链根,回溯到此为止。
614
617
  if (!message || message.sender_type !== 'bot' || !message.run_id) break
615
618
  const parent = this.store.get('SELECT kind, trigger_ref FROM runs WHERE id = ?', message.run_id)
@@ -625,7 +628,8 @@ export const runFinishMethods = {
625
628
  dispatchBotMentionRuns(project, run, bot, messageId) {
626
629
  if (!messageId) return []
627
630
  // 护栏三双保险:唯一调用点不带 taskId,这里按落库行复核,兜未来调用面扩张。
628
- const message = this.store.get('SELECT id, task_id, body FROM messages WHERE id = ?', messageId)
631
+ const chatStore = this.groupChatStore(project.id)
632
+ const message = chatStore.get('SELECT id, task_id, body FROM messages WHERE id = ?', messageId)
629
633
  if (!message || message.task_id) return []
630
634
  const members = this.membersOf(project.id).filter(member => member.status === 'active')
631
635
  // 护栏一:禁自唤醒——剔除回复 bot 自身。
@@ -633,7 +637,7 @@ export const runFinishMethods = {
633
637
  if (targets.length === 0) return []
634
638
  // mentions_json 记录过滤后的全部 @ 目标(对齐用户路径的 UI mention 渲染口径),
635
639
  // 与实际派发数(slice(0,3))允许在 >3 目标时不同。
636
- this.store.run(
640
+ chatStore.run(
637
641
  'UPDATE messages SET mentions_json = ? WHERE id = ?',
638
642
  JSON.stringify(targets.map(member => member.id)), messageId,
639
643
  )
@@ -255,13 +255,13 @@ export const runsMethods = {
255
255
  // dm/dm_reply 查 bot_messages(DSHBOTS-291 覆盖补测实测)——该表无 sender_type 列且
256
256
  // from_bot_id 恒为 bot(bot 间私信),不存在用户触发形态,恒为 false(逐条放行不参与合批,
257
257
  // 该标记对 dm 组也无分组意义)。
258
- heldItemIsUserQuestion(item) {
258
+ heldItemIsUserQuestion(item, botId = null) {
259
259
  if (item?.kind === 'chat') {
260
- const row = this.store.get('SELECT sender_type FROM messages WHERE id = ?', item.messageId)
260
+ const row = this.groupChatStore(item.projectId).get('SELECT sender_type FROM messages WHERE id = ?', item.messageId)
261
261
  return row?.sender_type === 'user'
262
262
  }
263
263
  if (item?.kind === 'solo_chat') {
264
- const row = this.store.get('SELECT sender_type FROM solo_messages WHERE id = ?', item.messageId)
264
+ const row = this.soloChatStore(botId).get('SELECT sender_type FROM solo_messages WHERE id = ?', item.messageId)
265
265
  return row?.sender_type === 'user'
266
266
  }
267
267
  return false
@@ -337,14 +337,14 @@ export const runsMethods = {
337
337
  && last.first.projectId === item.projectId
338
338
  && last.merge.length + 1 < cap
339
339
  && withinWindow
340
- && this.heldItemIsUserQuestion(item) === this.heldItemIsUserQuestion(last.first)) {
340
+ && this.heldItemIsUserQuestion(item, botId) === this.heldItemIsUserQuestion(last.first, botId)) {
341
341
  last.merge.push(item)
342
342
  } else {
343
343
  groups.push({ first: item, merge: [] })
344
344
  }
345
345
  }
346
346
  // 用户提问组优先放行(D-272 出队优先的队列侧对偶),sort 稳定保住组间先后。
347
- groups.sort((a, b) => Number(this.heldItemIsUserQuestion(b.first)) - Number(this.heldItemIsUserQuestion(a.first)))
347
+ groups.sort((a, b) => Number(this.heldItemIsUserQuestion(b.first, botId)) - Number(this.heldItemIsUserQuestion(a.first, botId)))
348
348
  const consumed = new Set()
349
349
  for (const group of groups) {
350
350
  if (this.botBusy(botId, domain)) break
@@ -498,16 +498,12 @@ export const runsMethods = {
498
498
  }
499
499
  throw error
500
500
  }
501
- this.store.run(
502
- 'INSERT INTO run_events(id, run_id, type, message, created_at) VALUES (?, ?, ?, ?, ?)',
503
- id('evt'), runId, 'queued',
501
+ this.insertRunEvent(runId, 'queued',
504
502
  triggerType === 'wechat'
505
503
  ? '微信消息触发(项目外单聊直达)'
506
504
  : triggerType === 'feishu'
507
505
  ? '飞书消息触发(项目外单聊直达)'
508
- : '单聊消息触发',
509
- createdAt,
510
- )
506
+ : '单聊消息触发')
511
507
  return runId
512
508
  },
513
509
  enqueueChatRun(project, bot, messageId, origin = null) {
@@ -545,16 +541,12 @@ export const runsMethods = {
545
541
  }
546
542
  throw error
547
543
  }
548
- this.store.run(
549
- 'INSERT INTO run_events(id, run_id, type, message, created_at) VALUES (?, ?, ?, ?, ?)',
550
- id('evt'), runId, 'queued',
544
+ this.insertRunEvent(runId, 'queued',
551
545
  triggerType === 'wechat'
552
546
  ? '微信群聊消息触发(直达)'
553
547
  : triggerType === 'feishu'
554
548
  ? '飞书群聊消息触发(直达)'
555
- : '群聊消息触发',
556
- createdAt,
557
- )
549
+ : '群聊消息触发')
558
550
  return runId
559
551
  },
560
552
  async cancelRunInternal(runId, updateTask = true) {
@@ -566,10 +558,7 @@ export const runsMethods = {
566
558
  nowIso(),
567
559
  runId,
568
560
  )
569
- this.store.run(
570
- 'INSERT INTO run_events(id, run_id, type, message, created_at) VALUES (?, ?, ?, ?, ?)',
571
- id('evt'), runId, 'canceled', '运行已取消', nowIso(),
572
- )
561
+ this.insertRunEvent(runId, 'canceled', '运行已取消')
573
562
  if (updateTask && run.task_id) {
574
563
  this.setTaskStatus(run.task_id, 'todo', { type: 'system', id: 'system' }, { ifIs: 'in_progress' })
575
564
  this.addTaskEvent(run.task_id, 'run_canceled', { type: 'system', id: 'system' }, { runId })
@@ -584,9 +573,10 @@ export const runsMethods = {
584
573
  },
585
574
 
586
575
  // 运行轨迹:模型回合、思考文本、助手文本、工具调用与工具结果的展示账本。
576
+ // 轨迹住运行归属的聊天库(chat-db-split Phase 1)。
587
577
  runTrajectory(runId) {
588
578
  const run = this.runRow(runId)
589
- const rows = this.store.all(
579
+ const rows = this.runChatStore(run).all(
590
580
  'SELECT seq, kind, title, detail, turn, step, created_at FROM run_trajectory WHERE run_id = ? ORDER BY seq ASC',
591
581
  run.id,
592
582
  )
@@ -644,10 +634,7 @@ export const runsMethods = {
644
634
  newRunId, task.project_id, task.assignee_bot_id, task.id, task.id,
645
635
  Number(run.attempt) + 1, `retry:${task.id}:${Date.now()}:${newRunId}`, writeScopes, createdAt,
646
636
  )
647
- this.store.run(
648
- 'INSERT INTO run_events(id, run_id, type, message, created_at) VALUES (?, ?, ?, ?, ?)',
649
- id('evt'), newRunId, 'queued', `重试 ${run.attempt}`, createdAt,
650
- )
637
+ this.insertRunEvent(newRunId, 'queued', `重试 ${run.attempt}`)
651
638
  this.addTaskEvent(task.id, 'retried', actor, { runId: newRunId, previousRunId: runId })
652
639
  void this.tick()
653
640
  return this.store.get('SELECT * FROM runs WHERE id = ?', newRunId)
@@ -670,12 +657,8 @@ export const runsMethods = {
670
657
  const model = run.model_provider
671
658
  ? { provider: run.model_provider, model: run.model_model, effort: run.model_effort ?? null }
672
659
  : { provider: bot.provider, model: bot.model, effort: bot.effort ?? null }
673
- this.store.run(
674
- 'INSERT INTO run_events(id, run_id, type, message, created_at) VALUES (?, ?, ?, ?, ?)',
675
- id('evt'), run.id, 'config_snapshot',
676
- JSON.stringify({ bot_revision: Number(bot.current_revision) || 0, model, prompt_segment_overrides: segments }),
677
- nowIso(),
678
- )
660
+ this.insertRunEvent(run.id, 'config_snapshot',
661
+ JSON.stringify({ bot_revision: Number(bot.current_revision) || 0, model, prompt_segment_overrides: segments }))
679
662
  }
680
663
  try {
681
664
  const task = run.task_id ? this.taskRow(run.task_id) : null
@@ -683,9 +666,9 @@ export const runsMethods = {
683
666
  // solo_messages),trigger_ref 即原消息 id——startRun 据此把附图随首条 prompt
684
667
  // 带给代理模型(与 chat/solo_chat 同一链路)。
685
668
  const chatMessage = (run.kind === 'chat' || (run.kind === 'vision' && run.project_id)) && run.trigger_ref
686
- ? this.store.get('SELECT * FROM messages WHERE id = ?', run.trigger_ref)
669
+ ? this.runChatStore(run).get('SELECT * FROM messages WHERE id = ?', run.trigger_ref)
687
670
  : (run.kind === 'solo_chat' || (run.kind === 'vision' && !run.project_id)) && run.trigger_ref
688
- ? this.store.get('SELECT * FROM solo_messages WHERE id = ?', run.trigger_ref)
671
+ ? this.runChatStore(run).get('SELECT * FROM solo_messages WHERE id = ?', run.trigger_ref)
689
672
  : null
690
673
  // 合批消息(DSHBOTS-231):领取时合并进来的同通道排队消息,与触发消息同一轮注入。
691
674
  const extraMessages = this.mergedMessagesFor(run)
@@ -754,16 +737,21 @@ if (run.kind === 'dm_reply') {
754
737
  ? 'id, sender_type, sender_id, body'
755
738
  : 'id, sender_type, sender_id, body, reply_to_id'
756
739
  const table = run.kind === 'solo_chat' ? 'solo_messages' : 'messages'
740
+ const chatStore = this.runChatStore(run)
757
741
  const rows = []
758
742
  for (const messageId of ids) {
759
- const row = this.store.get(`SELECT ${columns} FROM ${table} WHERE id = ?`, messageId)
743
+ const row = chatStore.get(`SELECT ${columns} FROM ${table} WHERE id = ?`, messageId)
760
744
  if (row) rows.push(row)
761
745
  }
762
746
  return rows
763
747
  },
764
748
  insertRunEvent(runId, type, message) {
765
749
  if (!runId) return
766
- this.store.run(
750
+ // Phase 3:事件住运行归属的聊天库(全站写入的统一收口点,调用方无感)。
751
+ // 运行行已不在(删除竞态的孤儿事件)时回落顶库留痕,不丢审计线索。
752
+ const run = this.store.get('SELECT id, project_id, bot_id FROM runs WHERE id = ?', runId)
753
+ const target = run ? this.runChatStore(run) : this.store
754
+ target.run(
767
755
  'INSERT INTO run_events(id, run_id, type, message, created_at) VALUES (?, ?, ?, ?, ?)',
768
756
  id('evt'), runId, type, this.maskSecretValues(message), nowIso(),
769
757
  )
@@ -933,7 +921,8 @@ if (run.kind === 'dm_reply') {
933
921
  const usedRef = run.model_provider && run.model_model ? `${run.model_provider}/${run.model_model}` : null
934
922
  return {
935
923
  ...rest,
936
- artifacts: jsonParse(run.artifacts, []),
924
+ output: this.runOutputOf(run) || null,
925
+ artifacts: this.runArtifactsOf(run),
937
926
  attention: parseAttention(attentionJson),
938
927
  mergedMessageIds: Array.isArray(jsonParse(mergedRaw, [])) ? jsonParse(mergedRaw, []) : [],
939
928
  botName: bot?.name ?? 'Bot',
@@ -1014,8 +1003,7 @@ if (run.kind === 'dm_reply') {
1014
1003
  // 产物清单视图:HTTP 端点与运行详情面板共用。
1015
1004
  listRunArtifacts(runId) {
1016
1005
  const run = this.runRow(runId)
1017
- const list = jsonParse(run.artifacts, [])
1018
- return { runId, artifacts: Array.isArray(list) ? list : [] }
1006
+ return { runId, artifacts: this.runArtifactsOf(run) }
1019
1007
  },
1020
1008
 
1021
1009
  // 产物文件定位:仅允许读取该运行清单里的相对路径,且必须落在项目工作区内(含符号链接校验)。
@@ -1025,8 +1013,8 @@ if (run.kind === 'dm_reply') {
1025
1013
  ? this.store.get('SELECT * FROM projects WHERE id = ?', run.project_id)
1026
1014
  : null
1027
1015
  if (!project?.slug) throw notFound('运行没有关联的项目工作区')
1028
- const list = jsonParse(run.artifacts, [])
1029
- if (!Array.isArray(list) || !list.some(item => item?.path === relPath)) {
1016
+ const list = this.runArtifactsOf(run)
1017
+ if (!list.some(item => item?.path === relPath)) {
1030
1018
  throw forbidden('文件不在该运行的产物清单中')
1031
1019
  }
1032
1020
  const dir = this.projectWorkDir(project)
@@ -29,15 +29,17 @@ export const contextMethods = {
29
29
  // 两条提示词进同一宿主会话历史,消息不丢不重;
30
30
  // - excludeId 排除本轮触发消息(正文已在 # Group message / # Solo message 完整呈现,不再双份)。
31
31
  // 无会话上下文时不读不写水位,等价旧的固定尾窗。
32
- watermarkWindow({ sessionId, table, columns, where, params, excludeId }) {
33
- const advance = this.store.get(`SELECT MAX(rowid) AS m FROM ${table} WHERE ${where}`, ...params)?.m ?? null
32
+ // store(chat-db-split Phase 1):消息尾窗读聊天库;缺省回落顶库(测试桩/独立构造)。
33
+ watermarkWindow({ sessionId, table, columns, where, params, excludeId, store = null }) {
34
+ const readFrom = store ?? this.store
35
+ const advance = readFrom.get(`SELECT MAX(rowid) AS m FROM ${table} WHERE ${where}`, ...params)?.m ?? null
34
36
  const watermark = sessionId ? this.messageWatermarks.get(sessionId) : undefined
35
37
  const rows = watermark === undefined
36
- ? this.store.all(
38
+ ? readFrom.all(
37
39
  `SELECT ${columns} FROM ${table} WHERE ${where} ORDER BY rowid DESC LIMIT ?`,
38
40
  ...params, RECENT_FALLBACK_LIMIT,
39
41
  ).reverse()
40
- : this.store.all(
42
+ : readFrom.all(
41
43
  `SELECT ${columns} FROM ${table} WHERE ${where} AND rowid > ? ORDER BY rowid DESC LIMIT ?`,
42
44
  ...params, watermark, RECENT_INCREMENTAL_LIMIT,
43
45
  ).reverse()
@@ -179,6 +179,7 @@ export const lifecycleMethods = {
179
179
  pending.usageCounters.set(fingerprint, ordinal + 1)
180
180
  const sourceKey = `run:${pending.runId}:sess:${sessionId}:turn:${pending.turn ?? 0}:msg:${fingerprint}:${ordinal}`
181
181
  const row = recordUsage(this.store, {
182
+ chatStore: this.chatStoreForRun({ project_id: pending.projectId, bot_id: pending.bot.id }),
182
183
  sourceKey,
183
184
  sourceEventId: messageId || null,
184
185
  // task_id(DSHBOTS-212):任务运行的用量归因到任务,支撑任务级端到端成本聚合
@@ -414,6 +414,7 @@ This message is from the project owner on Feishu — a real multi-turn conversat
414
414
  where: 'bot_id = ?',
415
415
  params: [bot.id],
416
416
  excludeId: chatMessage?.id,
417
+ store: this.chatStoreForRun(run ?? { project_id: null, bot_id: bot.id }),
417
418
  })
418
419
  // P3-1:单聊同款,无信息量 system 短状态不进尾窗。
419
420
  const mergedIds = new Set((extraMessages ?? []).map(item => item.id))
@@ -463,7 +464,7 @@ Transcription requirements:
463
464
  Original message from ${chatMessage?.sender_type ?? 'user'}:${chatMessage?.sender_id ?? ''}
464
465
  ${(chatMessage?.body ?? '(no text)').slice(0, 2_000)}`
465
466
  },
466
- promptFor({ run, bot, project, task, chatMessage, extraMessages, sessionId } ) {
467
+ promptFor({ run, bot, project, task, chatMessage, extraMessages, sessionId } ) {
467
468
  if (run.kind === 'solo_chat') return this.soloRunPrompt({ run, bot, chatMessage, extraMessages, sessionId })
468
469
  if (run.kind === 'vision') return this.visionRunPrompt({ run, bot, project, chatMessage })
469
470
  // 结转摘要(DSHBOTS-145):先于 header 判定——单聊摘要运行没有项目,
@@ -477,8 +478,9 @@ ${(chatMessage?.body ?? '(no text)').slice(0, 2_000)}`
477
478
  ].join('\n')
478
479
  // 任务评论注入(DSHBOTS-254 收口):最近 3 条、合计 ≤1.5k——每条正文 500 上限
479
480
  // (按 1.5k/3 比例缩减)+ 拼接后 1500 硬顶(兜住行前缀开销),最坏 ~4k 压到 1.5k。
481
+ // Phase 3:任务评论住项目聊天库(顶库已迁空)。
480
482
  const taskComments = task
481
- ? this.store.all(
483
+ ? this.chatStoreForRun({ project_id: task.project_id, bot_id: run.bot_id }).all(
482
484
  'SELECT id, author_type, author_id, body FROM task_comments WHERE task_id = ? ORDER BY created_at DESC LIMIT 3',
483
485
  task.id,
484
486
  ).reverse()
@@ -600,8 +602,10 @@ Last failure: ${failure?.error_message ?? 'unknown'}`
600
602
  return `${header}\n\n[Direct-message delivery record missing; nothing to do. Reply with a short note only.]`
601
603
  }
602
604
  if (run.kind === 'memory_review') {
605
+ // 路由列(project_id/bot_id)必须选出来:chatStoreForRun 靠它们定位聊天库,
606
+ // 缺列会以 undefined 落进单聊分支,凭空造出 solo-undefined.sqlite。
603
607
  const sourceRun = run.trigger_ref
604
- ? this.store.get('SELECT id, kind, task_id, trigger_ref, output FROM runs WHERE id = ?', run.trigger_ref)
608
+ ? this.store.get('SELECT id, kind, task_id, trigger_ref, output, project_id, bot_id FROM runs WHERE id = ?', run.trigger_ref)
605
609
  : null
606
610
  if (sourceRun?.task_id) {
607
611
  const sourceTask = this.store.get('SELECT number, title, time_budget_minutes FROM tasks WHERE id = ?', sourceRun.task_id)
@@ -619,10 +623,15 @@ Rules:
619
623
 
620
624
  Task: ${sourceTask ? `${project.key}-${sourceTask.number} ${sourceTask.title}` : '(unknown task)'}
621
625
  Delivery output:
622
- ${(sourceRun.output ?? '').slice(0, 6000)}${timeBudgetBlockFor(sourceTask)}`
626
+ ${(sourceRun ? (this.chatStoreForRun(sourceRun).get('SELECT output FROM run_payload WHERE run_id = ?', sourceRun.id)?.output ?? sourceRun.output ?? '') : '').slice(0, 6000)}${timeBudgetBlockFor(sourceTask)}`
623
627
  }
624
628
  const userMessage = sourceRun?.trigger_ref
625
- ? this.store.get('SELECT body FROM messages WHERE id = ?', sourceRun.trigger_ref)
629
+ ? this.chatStoreForRun(sourceRun).get(
630
+ sourceRun.project_id
631
+ ? 'SELECT body FROM messages WHERE id = ?'
632
+ : 'SELECT body FROM solo_messages WHERE id = ?',
633
+ sourceRun.trigger_ref,
634
+ )
626
635
  : null
627
636
  return `${header}
628
637
 
@@ -638,7 +647,7 @@ Rules:
638
647
  User message:
639
648
  ${(userMessage?.body ?? '(missing)').slice(0, 2000)}
640
649
  Your reply:
641
- ${(sourceRun?.output ?? '').slice(0, 4000)}`
650
+ ${(sourceRun ? (this.chatStoreForRun(sourceRun).get('SELECT output FROM run_payload WHERE run_id = ?', sourceRun.id)?.output ?? sourceRun.output ?? '') : '').slice(0, 4000)}`
642
651
  }
643
652
  if (task) {
644
653
  // 超长防护(DSHBOTS-254):任务分支与 review/handle 同口径复用 truncateTaskDescription
@@ -722,6 +731,7 @@ ${description}${threads}${timeBudgetBlock}${urgentExemptionBlock}${recoveryNoteB
722
731
  where: "project_id = ? AND kind = 'text'",
723
732
  params: [project.id],
724
733
  excludeId: chatMessage?.id,
734
+ store: this.chatStoreForRun(run),
725
735
  })
726
736
  // P3-1:无信息量 system 短状态不进尾窗;合批消息已在专门段落呈现,同样不进尾窗(不双份)。
727
737
  const mergedIds = new Set((extraMessages ?? []).map(item => item.id))
@@ -750,7 +760,7 @@ ${description}${threads}${timeBudgetBlock}${urgentExemptionBlock}${recoveryNoteB
750
760
  ? 'none'
751
761
  : openTasks.map(item => `- ${project.key}-${item.number} [${item.status}] ${item.title}`).join('\n')
752
762
  // 引用回复上下文:本次消息带 reply_to 时,明确告知 bot 用户在回哪条消息(含 m_ 短 id 供 team_recall 取全文)。
753
- const quoteLine = this.quotedLineFor(chatMessage)
763
+ const quoteLine = this.quotedLineFor(chatMessage, this.chatStoreForRun(run))
754
764
  // 通道直达语境块(DSHBOTS-215 微信 / DSHBOTS-330 飞书):按 trigger_type 分流。
755
765
  // 两版同结构:多轮连续对话(项目会话复用),不要每条当新指令;派活意图要真建卡/派单;
756
766
  // 需要用户决策时用 ask_user_question(会转发到对应通道,回复回到本轮)。
@@ -798,9 +808,11 @@ ${taskList}`
798
808
  },
799
809
 
800
810
  // 引用行:正文控制在 200 字内;bot 发送者查名字,其余回退 sender_type:sender_id 展示。
801
- quotedLineFor(chatMessage) {
811
+ // chatStore(chat-db-split Phase 1):被引消息与触发消息同库;缺省回落顶库。
812
+ quotedLineFor(chatMessage, chatStore = null) {
802
813
  if (!chatMessage?.reply_to_id) return ''
803
- const quoted = this.store.get('SELECT id, sender_type, sender_id, body FROM messages WHERE id = ?', chatMessage.reply_to_id)
814
+ const readFrom = chatStore ?? this.store
815
+ const quoted = readFrom.get('SELECT id, sender_type, sender_id, body FROM messages WHERE id = ?', chatMessage.reply_to_id)
804
816
  if (!quoted) return '\n(The quoted message no longer exists.)\n'
805
817
  const senderName = quoted.sender_type === 'bot'
806
818
  ? this.store.get('SELECT name FROM bots WHERE id = ?', quoted.sender_id)?.name ?? `bot:${quoted.sender_id}`
@@ -43,7 +43,7 @@ export const sandboxMethods = {
43
43
  const { mode, source } = effectiveSandbox(run, bot, task)
44
44
  if (!SANDBOX_MODES.includes(mode)) return
45
45
  if (run?.id) {
46
- this.store.run(
46
+ this.chatStoreForRun(run).run(
47
47
  'INSERT INTO run_events(id, run_id, type, message, created_at) VALUES (?, ?, ?, ?, ?)',
48
48
  id('evt'), run.id, 'sandbox_mode', `沙箱档位 ${mode}(来源:${source})`, nowIso(),
49
49
  )
@@ -234,8 +234,9 @@ export const sessionMethods = {
234
234
  return run
235
235
  },
236
236
  // kind 'task' = 任务 worker 会话(全局链走 workerPreset);其余 = 控制面/单聊/核验会话
237
- //(全局链走 routerPreset)。bot.agent_preset 非空时逐 bot 覆盖,两级都留空时 kind
238
- // 决定用哪个全局链。可选 preset 只从宿主 roster 里实际可用(非 broken)的里挑。
237
+ //(全局链走 routerPreset)。bot.agent_preset 非空时逐 bot 覆盖,两级都留空或指向不可用
238
+ // preset 时用插件自带预设,再回落 standard。可选 preset 只从宿主 roster 里实际可用
239
+ //(非 broken)的里挑;插件不改动宿主全局默认。
239
240
  async defaultAgentPreset(kind, bot = null) {
240
241
  const botPreset = String(bot?.agent_preset ?? '').trim()
241
242
  const wanted = botPreset
@@ -247,8 +248,8 @@ export const sessionMethods = {
247
248
  if (!presets) return {}
248
249
  const list = await presets.list()
249
250
  const available = (list ?? []).filter(preset => preset.broken === undefined).map(preset => preset.id)
250
- // 只有确认存在的 preset 才会被选中;Router 缺省沿用 standard,避免装错配置直接起不来。
251
- const pick = [wanted, 'standard'].find(id => id && available.includes(id))
251
+ // 未配置(或配置失效)时用插件自带预设,再回落 standard,避免装错配置直接起不来。
252
+ const pick = [wanted, 'team-bots', 'standard'].find(id => id && available.includes(id))
252
253
  return pick ? { agentPreset: pick } : {}
253
254
  } catch {
254
255
  return {}
@@ -289,11 +290,16 @@ export const sessionMethods = {
289
290
  // type='subagent_spawned' 计数(DSHBOTS-294 账本落账)。无账本记录返回 0,不误触发。
290
291
  sessionSubagentCount(sessionId) {
291
292
  if (!sessionId) return 0
292
- return this.store.get(
293
- `SELECT COUNT(*) AS n FROM run_events re JOIN runs r ON r.id = re.run_id
294
- WHERE r.session_id = ? AND re.type = 'subagent_spawned'`,
295
- sessionId,
296
- )?.n ?? 0
293
+ // 事件住各运行归属的聊天库(chat-db-split Phase 3):按会话名下运行逐库计数合并。
294
+ const runs = this.store.all('SELECT id, project_id, bot_id FROM runs WHERE session_id = ?', sessionId)
295
+ let n = 0
296
+ for (const run of runs) {
297
+ n += this.chatStoreForRun(run).get(
298
+ "SELECT COUNT(*) AS n FROM run_events WHERE run_id = ? AND type = 'subagent_spawned'",
299
+ run.id,
300
+ )?.n ?? 0
301
+ }
302
+ return n
297
303
  },
298
304
  // 结转判定(DSHBOTS-145 / DSHBOTS-286):旧会话是否该让位。返回 true 表示旧绑定已
299
305
  // alias 化、调用方走新建路径;false 表示继续复用旧会话。
@@ -357,7 +363,7 @@ export const sessionMethods = {
357
363
  queuedAt,
358
364
  )
359
365
  if (!inserted.changes) return runId
360
- this.store.run(
366
+ this.chatStoreForRun({ project_id: project?.id ?? null, bot_id: bot.id }).run(
361
367
  'INSERT INTO run_events(id, run_id, type, message, created_at) VALUES (?, ?, ?, ?, ?)',
362
368
  id('evt'),
363
369
  runId,
@@ -422,7 +428,7 @@ export const sessionMethods = {
422
428
  queuedAt,
423
429
  )
424
430
  if (!inserted.changes) return runId
425
- this.store.run(
431
+ this.chatStoreForRun({ project_id: project?.id ?? null, bot_id: bot.id }).run(
426
432
  'INSERT INTO run_events(id, run_id, type, message, created_at) VALUES (?, ?, ?, ?, ?)',
427
433
  id('evt'),
428
434
  runId,
@@ -836,6 +842,8 @@ export const sessionMethods = {
836
842
  sessionId,
837
843
  bot: effectiveBot,
838
844
  projectId: project?.id ?? null,
845
+ // 聊天分库(chat-db-split Phase 1):本运行的正文库(轨迹记账/附图读取用)。
846
+ chatStore: this.chatStoreForRun(run),
839
847
  // 任务归因(DSHBOTS-212):记账时透传到 usage_events.task_id;
840
848
  // 非任务运行为 null,沿用既有「无任务归因」口径。
841
849
  taskId: run.task_id ?? null,
@@ -874,14 +882,15 @@ export const sessionMethods = {
874
882
  'UPDATE runs SET session_id = ?, started_at = ?, last_progress_at = ? WHERE id = ?',
875
883
  sessionId, startedAt, startedAt, run.id,
876
884
  )
877
- this.store.run(
885
+ this.chatStoreForRun(run).run(
878
886
  'INSERT INTO run_events(id, run_id, type, message, created_at) VALUES (?, ?, ?, ?, ?)',
879
887
  id('evt'), run.id, 'started', `Session ${sessionId}`, new Date().toISOString(),
880
888
  )
881
889
  try {
882
890
  // 聊天附图:首条 prompt 一并带上 image 分片,模型这轮就能看到用户发的图。
883
891
  // 宿主会把不能吃图片的模型降级成占位文本,插件不判模型能力。
884
- const imageParts = chatMessage?.id ? imageContentPartsForMessage(this.store, chatMessage.id) : []
892
+ // 附图随消息住在聊天库里(chat-db-split Phase 1)。
893
+ const imageParts = chatMessage?.id ? imageContentPartsForMessage(pending.chatStore ?? this.store, chatMessage.id) : []
885
894
  await this.ctx.sessionController.prompt({
886
895
  requestId: randomUUID(),
887
896
  sessionId,
@@ -119,12 +119,14 @@ export const trajectoryMethods = {
119
119
  if (!pending.toolNames) pending.toolNames = new Map()
120
120
  const entries = this.trajectoryEntries(pending, event, options)
121
121
  if (!entries.length) return
122
+ // 聊天分库(chat-db-split Phase 1):轨迹落运行归属的聊天库;无归属信息时回落顶库。
123
+ const store = pending.chatStore ?? this.store
122
124
  const createdAt = Number.isFinite(event?.time) ? new Date(event.time).toISOString() : nowIso()
123
125
  for (const entry of entries) {
124
126
  if ((pending.trajectoryCount ?? 0) >= TRAJECTORY_MAX_ENTRIES) return
125
127
  pending.trajectoryCount = (pending.trajectoryCount ?? 0) + 1
126
128
  pending.trajectorySeq = (pending.trajectorySeq ?? 0) + 1
127
- this.store.run(
129
+ store.run(
128
130
  'INSERT INTO run_trajectory(id, run_id, seq, kind, title, detail, turn, step, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)',
129
131
  id('traj'), pending.runId, pending.trajectorySeq, entry.kind, entry.title,
130
132
  truncateDetail(this.maskForStorage(entry.detail)),