dsh-team-bots 0.3.80 → 0.3.105

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 (50) 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 +5 -1
  6. package/src/db.js +52 -0
  7. package/src/feishu/channel.js +15 -11
  8. package/src/feishu/format.js +37 -1
  9. package/src/runtime.js +13 -1
  10. package/src/service.js +5 -0
  11. package/src/services/approvals.js +7 -2
  12. package/src/services/bots.js +8 -1
  13. package/src/services/chat-stores.js +564 -0
  14. package/src/services/chat.js +60 -28
  15. package/src/services/core.js +33 -12
  16. package/src/services/feishu.js +1 -1
  17. package/src/services/memory.js +14 -12
  18. package/src/services/model-fallback.js +3 -1
  19. package/src/services/notify.js +18 -8
  20. package/src/services/projects.js +25 -19
  21. package/src/services/questions.js +37 -12
  22. package/src/services/review-watchdog.js +31 -12
  23. package/src/services/run-finish.js +21 -14
  24. package/src/services/runs.js +29 -41
  25. package/src/services/runtime/context-window.js +6 -4
  26. package/src/services/runtime/lifecycle.js +1 -0
  27. package/src/services/runtime/prompt.js +21 -9
  28. package/src/services/runtime/sandbox-policy.js +1 -1
  29. package/src/services/runtime/session.js +27 -15
  30. package/src/services/runtime/trajectory.js +3 -1
  31. package/src/services/scheduler.js +48 -49
  32. package/src/services/system.js +9 -7
  33. package/src/services/task-review.js +27 -19
  34. package/src/services/task-runs.js +40 -21
  35. package/src/services/tasks.js +18 -10
  36. package/src/services/terminal.js +25 -14
  37. package/src/services/vision-proxy.js +67 -9
  38. package/src/services/wechat.js +24 -8
  39. package/src/subagent-ledger.js +23 -6
  40. package/src/usage-reconcile.js +93 -32
  41. package/src/usage.js +125 -50
  42. package/src/util.js +17 -0
  43. package/src/wechat/channel.js +3 -1
  44. package/src/wechat/commands.js +13 -1
  45. package/ui/modules/events-click.js +14 -1
  46. package/ui/modules/file-preview.js +22 -10
  47. package/ui/modules/markdown.js +10 -8
  48. package/ui/modules/tasks.js +1 -1
  49. package/ui/styles/cards.css +13 -0
  50. package/ui/styles/modal.css +4 -0
@@ -6,7 +6,7 @@
6
6
  // questionTimeoutMs 窗口,窗口内迟到作答经宿主 userQuestions.answer 回投原 agent;其余 abort 立即失效。
7
7
  // 注意:本域自管迁移(db.js 已贴 800 行上限,一行不加),手法与 approvals.js 一致。
8
8
  import { badRequest, conflict, forbidden, notFound } from '../errors.js'
9
- import { id, jsonParse, nowIso, text as textValue } from '../util.js'
9
+ import { flattenWhitespace, id, jsonParse, nowIso, text as textValue } from '../util.js'
10
10
  import { effectiveQuestionTimeoutMs } from '../config.js'
11
11
  import { columnNotNull, rebuildTable } from '../db-migrations.js'
12
12
 
@@ -62,28 +62,50 @@ export function ensureQuestionSchema(store) {
62
62
 
63
63
  // 问题条目清洗:文案统一过密钥掩码(会进群聊与 bot 可见范围),并夹取长度防单条撑爆卡片。
64
64
  // intent 只保留 plan-review 的展示字段;未知 intent 一律按通用选项列表渲染(协议允许)。
65
- function cleanQuestionItem(item) {
65
+ // 文案再过一道单行化:模型工具入参偶发把空格写成 CR(U+000D),渲染器把 CR 当行尾,
66
+ // 一句话会被劈成多段(飞书卡片里「(推荐)」裂成两行)。此处折成单行,落库即干净。
67
+ export function cleanQuestionItem(item) {
66
68
  const cleaned = {
67
69
  id: String(item?.id ?? '').slice(0, 100),
68
- question: textValue(item?.question, 4_000),
70
+ question: textValue(flattenWhitespace(item?.question), 4_000),
69
71
  }
70
- if (item?.detail) cleaned.detail = textValue(item.detail, 20_000)
71
- if (item?.header) cleaned.header = textValue(item.header, 200)
72
+ if (item?.detail) cleaned.detail = textValue(flattenWhitespace(item.detail), 20_000)
73
+ if (item?.header) cleaned.header = textValue(flattenWhitespace(item.header), 200)
72
74
  if (Array.isArray(item?.options)) {
73
75
  cleaned.options = item.options.slice(0, 20).map(option => {
74
- const row = { label: textValue(option?.label, 200) }
75
- if (option?.description) row.description = textValue(option.description, 1_000)
76
+ const row = { label: textValue(flattenWhitespace(option?.label), 200) }
77
+ if (option?.description) row.description = textValue(flattenWhitespace(option.description), 1_000)
76
78
  return row
77
79
  })
78
80
  }
79
81
  if (item?.multiSelect === true) cleaned.multiSelect = true
80
82
  if (item?.intent?.kind === 'plan-review') {
81
- cleaned.intent = { kind: 'plan-review', approve: textValue(item.intent.approve, 200) }
83
+ // approve 标签必须与选项 label 同一口径(宿主按「approve ∈ options」校验 intent)。
84
+ cleaned.intent = { kind: 'plan-review', approve: textValue(flattenWhitespace(item.intent.approve), 200) }
82
85
  if (item.intent.callId) cleaned.intent.callId = String(item.intent.callId)
83
86
  }
84
87
  return cleaned
85
88
  }
86
89
 
90
+ // 答案条目清洗:selected 是选项 label(与 cleanQuestionItem 同口径,保证前端高亮匹配),
91
+ // custom 是自由文本——同样折成单行,答复回宿主时不再带坏版面。
92
+ export function cleanAnswerItem(answer) {
93
+ const cleaned = { id: String(answer?.id ?? '') }
94
+ cleaned.selected = (Array.isArray(answer?.selected) ? answer.selected : [])
95
+ .map(value => flattenWhitespace(value))
96
+ .filter(Boolean)
97
+ .slice(0, 20)
98
+ const custom = answer?.custom ? flattenWhitespace(answer.custom) : ''
99
+ if (custom) cleaned.custom = custom
100
+ return cleaned
101
+ }
102
+
103
+ // 答复批次清洗:{answers:[...]} 结构逐条过 cleanAnswerItem;非批次结构原样返回。
104
+ export function cleanAnswerPayload(answer) {
105
+ if (!answer || !Array.isArray(answer.answers)) return answer
106
+ return { ...answer, answers: answer.answers.map(cleanAnswerItem) }
107
+ }
108
+
87
109
  // DSHBOTS-294:该 bot 是否仍有活跃项目语境(成员或总监)。无语境的控制面会话按单聊承接。
88
110
  export function botInActiveProject(store, botId) {
89
111
  if (!botId) return false
@@ -189,7 +211,8 @@ export const questionsMethods = {
189
211
  })
190
212
  } else {
191
213
  const group = this.groupOf(project.id)
192
- store.run(
214
+ // 卡片锚点住项目聊天库(chat-db-split Phase 1)。
215
+ this.groupChatStore(project.id).run(
193
216
  `INSERT INTO messages(id, project_id, group_chat_id, sender_type, sender_id, body, mentions_json, kind, question_id, created_at)
194
217
  VALUES (?, ?, ?, 'system', ?, ?, '[]', 'question', ?, ?)`,
195
218
  id('msg'), project.id, group?.id ?? null, bot.id, anchorBody, questionId, createdAt,
@@ -307,7 +330,7 @@ export const questionsMethods = {
307
330
  const selected = (Array.isArray(answer?.selected) ? answer.selected : [])
308
331
  .map(value => String(value)).filter(Boolean).slice(0, 20)
309
332
  const custom = answer?.custom ? String(answer.custom).slice(0, 2_000) : undefined
310
- return { id: String(item.id), selected, ...(custom ? { custom } : {}) }
333
+ return cleanAnswerItem({ id: String(item.id), selected, custom })
311
334
  })
312
335
  const decidedBy = `${actor.type}:${actor.id}`
313
336
  const hostAnswer = { answers }
@@ -326,8 +349,10 @@ export const questionsMethods = {
326
349
  // 视图缺该字段时,提交作答后的服务端终态覆盖乐观对象即丢键,下一轮旧 pending
327
350
  // 轮询快照会把「已回答」卡闪回问题卡;提问卡 pill 的作答时间戳也读它。
328
351
  ...(row.status === 'answered' ? { answered_at: row.ended_at } : {}),
329
- questions: jsonParse(row.questions, []),
330
- answer: jsonParse(row.answer, null),
352
+ // 存量行可能带 CR 坏空白(模型工具入参污染,落库前的老数据):读出时再洗一遍,
353
+ // 历史提问卡与答复展示同步恢复单行版面;洗后 label 与 selected 仍是同一口径。
354
+ questions: jsonParse(row.questions, []).map(cleanQuestionItem),
355
+ answer: cleanAnswerPayload(jsonParse(row.answer, null)),
331
356
  botName: bot?.name ?? 'Bot',
332
357
  // 会话归属(DSHBOTS-218):单聊提问没有项目,UI 据此显示来源列并决定跳转目标。
333
358
  scope: row.project_id ? 'project' : 'solo',
@@ -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,
@@ -19,7 +19,7 @@ import {
19
19
  transientBackoffMs,
20
20
  } from './backoff.js'
21
21
  import { ensureAttentionSchema, normalizeAttention } from './attention-schema.js'
22
- import { completeVisionRun, maybeSpawnVisionAfterFailure } from './vision-proxy.js'
22
+ import { completeVisionRun, isImageUnsupportedError, maybeSpawnVisionAfterFailure } from './vision-proxy.js'
23
23
  import { chatReply } from '../wechat/format.js'
24
24
 
25
25
  // ── 失败终态白名单分类(DSHBOTS-267)──────────────────────────────────────
@@ -42,6 +42,8 @@ const FAILURE_CATEGORY_NOTICES = {
42
42
  stalled: { label: '停滞', summary: '运行长时间无进展,已被看门狗中止。' },
43
43
  network: { label: '网络', summary: '网络瞬态失败,已按退避策略自动重试。' },
44
44
  blocked: { label: '会话受阻', summary: '宿主拒绝执行该会话(可能已被归档),未产生任何模型输出。' },
45
+ // DSHBOTS-112:主模型无视觉导致带图消息失败,与「未知」区分——读图代理已接手转写。
46
+ no_vision: { label: '模型无视觉', summary: '主模型不支持图片输入,已转交读图代理转写。' },
45
47
  internal: { label: '内部错误', summary: '服务内部错误。' },
46
48
  unknown: { label: '未知', summary: '运行失败,完整原因见运行日志。' },
47
49
  }
@@ -49,6 +51,7 @@ export function classifyFailure(error) {
49
51
  const raw = `${String(error?.code ?? '')} ${String(error?.message ?? '')}`
50
52
  if (isQuotaExhausted(error)) return FAILURE_CATEGORY_NOTICES.quota
51
53
  if (isRateLimitError(error)) return FAILURE_CATEGORY_NOTICES.rate_limited
54
+ if (isImageUnsupportedError(error)) return FAILURE_CATEGORY_NOTICES.no_vision
52
55
  if (SANDBOX_DENIED_PATTERN.test(raw)) return FAILURE_CATEGORY_NOTICES.sandbox_denied
53
56
  if (error?.code === 'RUN_TIMEOUT') return FAILURE_CATEGORY_NOTICES.run_timeout
54
57
  if (error?.code === 'RUN_STALLED') return FAILURE_CATEGORY_NOTICES.stalled
@@ -104,7 +107,7 @@ export const runFinishMethods = {
104
107
  const bot = this.store.get('SELECT * FROM bots WHERE id = ?', run.bot_id)
105
108
  const project = this.store.get('SELECT * FROM projects WHERE id = ?', run.project_id)
106
109
  this.auditReadRunWrites(run, project)
107
- const usage = runUsageTotals(this.store, runId, this.budgetCurrency())
110
+ const usage = runUsageTotals(this.runChatStore(run), runId, this.budgetCurrency(), this.store)
108
111
  const cleanOutput = this.maskSecretValues(text(output, 120_000))
109
112
  const artifactsJson = status === 'succeeded' && run.mode === 'write' && project
110
113
  ? this.captureRunArtifacts(run, project)
@@ -126,18 +129,20 @@ export const runFinishMethods = {
126
129
  // 额度耗尽时 provider 真给的重置时间照样保留(信息不丢,供 UI 显示额度恢复时间),
127
130
  // 但它不再触发对主模型的自动重试(见下方失败分支与 scheduler.retryExpiredPlanWaits)。
128
131
  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 = ?,
132
+ const changed = this.store.run(
133
+ `UPDATE runs SET status = ?, error_code = ?, error_message = ?, retry_after_ms = ?, ended_at = ?,
131
134
  usage_input = ?, usage_cache_read = ?, usage_cache_write = ?, usage_output = ?, usage_cost = ?
132
135
  WHERE id = ? AND status IN ('running', 'queued')`,
133
- status, cleanOutput, artifactsJson, error?.code ?? null, error?.message ?? null, retryAfterMs, endedAt,
136
+ status, error?.code ?? null, error?.message ?? null, retryAfterMs, endedAt,
134
137
  usage.inputTokens, usage.cacheReadTokens, usage.cacheWriteTokens, usage.outputTokens, usage.cost,
135
138
  runId,
136
139
  )
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
- )
140
+ // Phase 3:output/artifacts 住运行归属聊天库的 run_payload(顶库 runs 已瘦身)。
141
+ // 收尾 UPDATE 未命中(运行已终态)时不写载荷,避免覆盖既有结果。
142
+ if (Number(changed?.changes ?? 0) === 1) {
143
+ this.saveRunPayload(run, { output: cleanOutput, artifacts: artifactsJson })
144
+ }
145
+ this.insertRunEvent(runId, status, error?.message ?? (status === 'succeeded' ? '完成' : ''))
141
146
  // DSHBOTS-241:撞 provider 额度墙时记录该 bot 的额度状态(含恢复时间),
142
147
  // 供派发前路由(耗尽期走备用模型/排队)与 UI 手动解除;审计 bot.quota_exhausted。
143
148
  // DSHBOTS-246:事件与状态记录同条件——只有真撞墙才写「额度耗尽」,成功运行或
@@ -384,12 +389,12 @@ export const runFinishMethods = {
384
389
  // 施工方式由 bot 自选(亲做或派「bot 名+任务号」子代理),账本(D-294)仍照记。
385
390
  this.store.transaction(() => {
386
391
  this.setTaskStatus(task.id, 'in_review', { type: 'bot', id: bot.id })
387
- this.store.run(
392
+ this.store.afterCommit(() => this.groupChatStore(task.project_id).run(
388
393
  'INSERT INTO task_comments(id, task_id, author_type, author_id, body, created_at) VALUES (?, ?, ?, ?, ?, ?)',
389
394
  id('cmt'), task.id, 'bot', bot.id,
390
395
  cleanOutput || '运行完成,但模型未返回文本。',
391
396
  endedAt,
392
- )
397
+ ))
393
398
  this.addTaskEvent(task.id, 'run_succeeded', { type: 'bot', id: bot.id }, { runId, identifier: `${project.key}-${task.number}` })
394
399
  // 自动核验委派(DSHBOTS-113):与 in_review 迁移同一事务触发留痕;实际派生由
395
400
  // review_delegate_auto outbox 承接(幂等键绑定本次交付运行),守卫冲突的退避重试
@@ -607,9 +612,10 @@ export const runFinishMethods = {
607
612
  let depth = 0
608
613
  let ref = run?.trigger_ref
609
614
  const seen = new Set()
615
+ const chatStore = this.runChatStore(run)
610
616
  while (depth < 2 && ref && !seen.has(ref)) {
611
617
  seen.add(ref)
612
- const message = this.store.get('SELECT sender_type, run_id FROM messages WHERE id = ?', ref)
618
+ const message = chatStore.get('SELECT sender_type, run_id FROM messages WHERE id = ?', ref)
613
619
  // 人发消息与结构化 bot 落库(notify 等无 run_id 的 bot 消息)都是链根,回溯到此为止。
614
620
  if (!message || message.sender_type !== 'bot' || !message.run_id) break
615
621
  const parent = this.store.get('SELECT kind, trigger_ref FROM runs WHERE id = ?', message.run_id)
@@ -625,7 +631,8 @@ export const runFinishMethods = {
625
631
  dispatchBotMentionRuns(project, run, bot, messageId) {
626
632
  if (!messageId) return []
627
633
  // 护栏三双保险:唯一调用点不带 taskId,这里按落库行复核,兜未来调用面扩张。
628
- const message = this.store.get('SELECT id, task_id, body FROM messages WHERE id = ?', messageId)
634
+ const chatStore = this.groupChatStore(project.id)
635
+ const message = chatStore.get('SELECT id, task_id, body FROM messages WHERE id = ?', messageId)
629
636
  if (!message || message.task_id) return []
630
637
  const members = this.membersOf(project.id).filter(member => member.status === 'active')
631
638
  // 护栏一:禁自唤醒——剔除回复 bot 自身。
@@ -633,7 +640,7 @@ export const runFinishMethods = {
633
640
  if (targets.length === 0) return []
634
641
  // mentions_json 记录过滤后的全部 @ 目标(对齐用户路径的 UI mention 渲染口径),
635
642
  // 与实际派发数(slice(0,3))允许在 >3 目标时不同。
636
- this.store.run(
643
+ chatStore.run(
637
644
  'UPDATE messages SET mentions_json = ? WHERE id = ?',
638
645
  JSON.stringify(targets.map(member => member.id)), messageId,
639
646
  )
@@ -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
  )