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
@@ -235,10 +235,14 @@ export const tasksMethods = {
235
235
  return this.taskView(this.taskRow(taskId))
236
236
  },
237
237
  addTaskEvent(taskId, type, actor, data = {}) {
238
- this.store.run(
238
+ // 任务事件住任务所属项目的聊天库(chat-db-split Phase 3):task 行在顶库,按 project_id 路由。
239
+ const projectId = this.store.get('SELECT * FROM tasks WHERE id = ?', taskId)?.project_id
240
+ // afterCommit:调用方常包在顶库事务里(setTaskStatus 等)——聊天库写跟随顶库
241
+ // 提交/回滚,外层回滚不残留事件(Phase 3 跨库原子性收口)。
242
+ this.store.afterCommit(() => this.groupChatStore(projectId).run(
239
243
  'INSERT INTO task_events(id, task_id, type, actor_type, actor_id, data_json, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)',
240
244
  id('tevt'), taskId, type, actor.type, actor.id, JSON.stringify(data), nowIso(),
241
- )
245
+ ))
242
246
  },
243
247
  // 统一状态迁移落点(吸收 dsh-agent-team「账本为权威、投影可重放」理念):所有直接改
244
248
  // tasks.status 的路径都经此走——同一事务内 UPDATE + 权威 'status' 事件(from/to),
@@ -267,7 +271,7 @@ export const tasksMethods = {
267
271
  taskProjectionDrift() {
268
272
  const drifted = []
269
273
  for (const task of this.store.all('SELECT id, number, project_id, status FROM tasks')) {
270
- const events = this.store.all(
274
+ const events = this.groupChatStore(task.project_id).all(
271
275
  `SELECT type, data_json FROM task_events WHERE task_id = ?
272
276
  AND (type = 'created' OR (type = 'status' AND json_extract(data_json, '$.field') = 'status'))
273
277
  ORDER BY created_at, rowid`,
@@ -292,7 +296,8 @@ export const tasksMethods = {
292
296
  // 增量非一一对应(交付是一事件一增量,updateTask 是一增量多事件),故按时间取最近
293
297
  // N 条而非按版本切割。
294
298
  taskChangesSince(taskId, limit = 5) {
295
- const rows = this.store.all(
299
+ const projectId = this.store.get('SELECT * FROM tasks WHERE id = ?', taskId)?.project_id
300
+ const rows = this.groupChatStore(projectId).all(
296
301
  'SELECT type, actor_type, actor_id, data_json, created_at FROM task_events WHERE task_id = ? ORDER BY created_at DESC, rowid DESC LIMIT ?',
297
302
  taskId, limit,
298
303
  )
@@ -356,7 +361,7 @@ export const tasksMethods = {
356
361
  blockedBy: deps.blockedBy,
357
362
  depsSatisfied: deps.depsSatisfied,
358
363
  blockedByNames: deps.blockedByNames,
359
- comments: Number(this.store.get('SELECT COUNT(*) AS count FROM task_comments WHERE task_id = ?', task.id)?.count ?? 0),
364
+ comments: Number(this.groupChatStore(task.project_id).get('SELECT COUNT(*) AS count FROM task_comments WHERE task_id = ?', task.id)?.count ?? 0),
360
365
  latestRun: runs[0] ?? null,
361
366
  runs,
362
367
  stage,
@@ -565,7 +570,7 @@ export const tasksMethods = {
565
570
  // 指派者名(DSHBOTS-257):/detail 卡片直读 assigneeName,在此按 assignee_bot_id
566
571
  // 解析(同 task-notify 口径),不进 taskView 列表热路径(每卡一次 bots 查询)。
567
572
  assigneeName: task.assignee_bot_id ? this.botRow(task.assignee_bot_id)?.name ?? null : null,
568
- comments: this.store.all(
573
+ comments: this.groupChatStore(task.project_id).all(
569
574
  'SELECT author_type, author_id, body, created_at FROM task_comments WHERE task_id = ? ORDER BY created_at DESC LIMIT 3',
570
575
  task.id,
571
576
  ).reverse(),
@@ -574,8 +579,9 @@ export const tasksMethods = {
574
579
  async taskDetail(taskId) {
575
580
  const task = this.taskRow(taskId)
576
581
  const project = this.projectRow(task.project_id)
577
- const comments = this.store.all('SELECT * FROM task_comments WHERE task_id = ? ORDER BY created_at', taskId)
578
- const events = this.store.all('SELECT * FROM task_events WHERE task_id = ? ORDER BY created_at', taskId)
582
+ // 评论与事件住任务所属项目的聊天库(chat-db-split Phase 3);runs/依赖仍在顶库。
583
+ const comments = this.groupChatStore(task.project_id).all('SELECT * FROM task_comments WHERE task_id = ? ORDER BY created_at', taskId)
584
+ const events = this.groupChatStore(task.project_id).all('SELECT * FROM task_events WHERE task_id = ? ORDER BY created_at', taskId)
579
585
  const runs = this.store.all("SELECT * FROM runs WHERE task_id = ? AND COALESCE(error_code, '') <> 'SUPERSEDED' ORDER BY queued_at DESC", taskId)
580
586
  const dependencies = this.store.all(
581
587
  'SELECT t.id, t.number, t.title, t.status FROM task_dependencies d JOIN tasks t ON t.id = d.depends_on_task_id WHERE d.task_id = ?',
@@ -587,12 +593,14 @@ export const tasksMethods = {
587
593
  // 只挂 taskDetail 单卡详情,不进 taskView 列表热路径(每卡一次聚合会放大列表查询)。
588
594
  const subtreeIds = taskSubtreeIds(this.store, taskId)
589
595
  const budgetCurrency = this.budgetCurrency()
596
+ // 任务用量明细住该任务项目的聊天库(chat-db-split Phase 2);子树 id 集来自顶库 tasks。
597
+ const usageStore = this.groupChatStore(project.id)
590
598
  return {
591
599
  ...this.taskView(task),
592
600
  projectKey: project.key,
593
601
  usage: {
594
- own: taskUsageTotals(this.store, taskId, budgetCurrency),
595
- total: taskTreeUsageTotals(this.store, taskId, budgetCurrency),
602
+ own: taskUsageTotals(usageStore, taskId, budgetCurrency, this.store),
603
+ total: taskTreeUsageTotals(usageStore, taskId, budgetCurrency, subtreeIds, this.store),
596
604
  subtaskCount: subtreeIds.length - 1,
597
605
  },
598
606
  comments: comments.map(comment => ({
@@ -44,14 +44,15 @@ export const terminalMethods = {
44
44
  if (!clean) throw badRequest('命令不能为空')
45
45
  if (clean.length > TERMINAL_COMMAND_MAX) throw badRequest(`命令过长(最多 ${TERMINAL_COMMAND_MAX} 字符)`)
46
46
  // 同项目同时只允许一条运行:检查与插入之间无 await,单线程内不会交错。
47
- if (this.store.get("SELECT id FROM terminal_commands WHERE project_id = ? AND status = 'running'", project.id)) {
47
+ if (this.groupChatStore(project.id).get("SELECT id FROM terminal_commands WHERE project_id = ? AND status = 'running'", project.id)) {
48
48
  throw conflict('该项目已有终端命令在运行,请先停止或等待它结束')
49
49
  }
50
50
  const commandId = id('term')
51
51
  const createdAt = nowIso()
52
52
  // 命令与聊天消息同一姿势:可能拼进密钥值,入库(行、审计)前先过掩码,密钥原文不落库。
53
53
  const storableCommand = this.maskSecretValues(clean)
54
- this.store.run(
54
+ // 终端命令住各项目聊天库(chat-db-split Phase 3):按 project_id 路由。
55
+ this.groupChatStore(project.id).run(
55
56
  `INSERT INTO terminal_commands(id, project_id, command, status, created_at) VALUES (?, ?, ?, 'running', ?)`,
56
57
  commandId, project.id, storableCommand, createdAt,
57
58
  )
@@ -87,10 +88,18 @@ export const terminalMethods = {
87
88
  this.finishTerminalCommand(commandId, 'failed', null, `命令执行失败:${error?.message ?? error}`)
88
89
  })
89
90
  this.audit(actor, 'terminal.run', 'project', project.id, { command: storableCommand })
90
- return this.terminalCommandView(this.store.get('SELECT * FROM terminal_commands WHERE id = ?', commandId))
91
+ return this.terminalCommandView(this.groupChatStore(project.id).get('SELECT * FROM terminal_commands WHERE id = ?', commandId))
92
+ },
93
+ // 命令行住各项目聊天库,commandId 不含项目信息:跨库扇出找行(库数是个位数、主键查)。
94
+ terminalCommandRow(commandId) {
95
+ for (const chatStore of this.allChatStores()) {
96
+ const row = chatStore.get('SELECT * FROM terminal_commands WHERE id = ?', commandId)
97
+ if (row) return row
98
+ }
99
+ return null
91
100
  },
92
101
  cancelTerminalCommand(commandId, actor = this.actor()) {
93
- const row = this.store.get('SELECT * FROM terminal_commands WHERE id = ?', commandId)
102
+ const row = this.terminalCommandRow(commandId)
94
103
  if (!row) throw notFound('终端命令不存在')
95
104
  if (row.status !== 'running') throw conflict('命令已结束,无需停止')
96
105
  const entry = this.terminalActive.get(commandId)
@@ -102,16 +111,16 @@ export const terminalMethods = {
102
111
  killTerminalGroup(entry.child)
103
112
  }
104
113
  this.audit(actor, 'terminal.cancel', 'terminal_command', commandId, {})
105
- return this.terminalCommandView(this.store.get('SELECT * FROM terminal_commands WHERE id = ?', commandId))
114
+ return this.terminalCommandView(this.groupChatStore(row.project_id).get('SELECT * FROM terminal_commands WHERE id = ?', commandId))
106
115
  },
107
116
  terminalState(projectId) {
108
117
  // 顺手清理:每项目只保留最近 TERMINAL_HISTORY_LIMIT 条,不新增定时器。
109
- this.store.run(
118
+ this.groupChatStore(projectId).run(
110
119
  `DELETE FROM terminal_commands WHERE project_id = ? AND id NOT IN (
111
120
  SELECT id FROM terminal_commands WHERE project_id = ? ORDER BY created_at DESC LIMIT ?)`,
112
121
  projectId, projectId, TERMINAL_HISTORY_LIMIT,
113
122
  )
114
- const history = this.store.all(
123
+ const history = this.groupChatStore(projectId).all(
115
124
  'SELECT * FROM terminal_commands WHERE project_id = ? ORDER BY created_at DESC LIMIT ?',
116
125
  projectId, TERMINAL_HISTORY_LIMIT,
117
126
  ).map(row => this.terminalCommandView(row))
@@ -140,18 +149,20 @@ export const terminalMethods = {
140
149
  const output = this.maskSecretValues(String(entry?.buffer ?? '').slice(-TERMINAL_OUTPUT_CAP))
141
150
  // 服务停机竞态:子进程在 store 关闭后才退出时,收尾写库失败只告警,不再炸进程。
142
151
  try {
143
- const row = this.store.get('SELECT project_id FROM terminal_commands WHERE id = ?', commandId)
144
- this.store.run(
145
- `UPDATE terminal_commands SET status = ?, exit_code = ?, output = ?, error_message = ?, ended_at = ? WHERE id = ?`,
146
- status, exitCode, output, errorMessage, nowIso(), commandId,
147
- )
148
- if (row) this.trimTerminalHistory(row.project_id)
152
+ const row = this.terminalCommandRow(commandId)
153
+ if (row) {
154
+ this.groupChatStore(row.project_id).run(
155
+ `UPDATE terminal_commands SET status = ?, exit_code = ?, output = ?, error_message = ?, ended_at = ? WHERE id = ?`,
156
+ status, exitCode, output, errorMessage, nowIso(), commandId,
157
+ )
158
+ this.trimTerminalHistory(row.project_id)
159
+ }
149
160
  } catch (error ) {
150
161
  this.logger.warn?.(`dsh-team: terminal command ${commandId} 收尾落库失败:${error?.message ?? error}`)
151
162
  }
152
163
  },
153
164
  trimTerminalHistory(projectId) {
154
- this.store.run(
165
+ this.groupChatStore(projectId).run(
155
166
  `DELETE FROM terminal_commands WHERE project_id = ? AND id NOT IN (
156
167
  SELECT id FROM terminal_commands WHERE project_id = ? ORDER BY created_at DESC LIMIT ?)`,
157
168
  projectId, projectId, TERMINAL_HISTORY_LIMIT,
@@ -1,8 +1,9 @@
1
1
  // src/services/vision-proxy.js —— 读图代理域(DSHBOTS-112)
2
2
  // Bot 主模型无视觉能力却收到带图消息时,自动派生 kind='vision'、mode='read' 的
3
3
  // 只读转写运行:用配置的代理模型(visionProxyProvider/visionProxyModel)把图片
4
- // 转写成中文结构化文本,以「[图片转写] …」system 消息写回原消息所在会话,
5
- // Bot 下一轮上下文即可见。原对话不受派生阻塞:原 chat 运行照常带图下发,
4
+ // 转写成中文结构化文本,以「[图片转写] …」system 消息写回原消息所在会话,并给同
5
+ // 一条消息派生续答运行(image_offload=1,不再下发二进制图),主模型当轮即可基于
6
+ // 转写正文回答用户。原对话不受派生阻塞:原 chat 运行照常带图下发,
6
7
  // 宿主仍按现状报「模型不支持图片」(不静默);转写失败或代理未配置时同样
7
8
  // 只留审计(vision.fallback),不重试、不刷额度。
8
9
  // 本文件是纯函数模块(手法同 message-images.js):service 实例由调用方显式传入,
@@ -76,7 +77,9 @@ export function spawnVisionProxyRun(service, { bot, message, target }) {
76
77
  runId, message.project_id ?? null, bot.id, message.id, idempotencyKey,
77
78
  proxy.provider, proxy.model, createdAt,
78
79
  )
79
- service.store.run(
80
+ // run_events 住运行归属的聊天库(chat-db-split Phase 3):路由行取自本回调刚
81
+ // 插入的 runs 参数(project_id/bot_id),与 runs 插入同回调保持撞车不落事件。
82
+ service.runChatStore({ id: runId, project_id: message.project_id ?? null, bot_id: bot.id }).run(
80
83
  'INSERT INTO run_events(id, run_id, type, message, created_at) VALUES (?, ?, ?, ?, ?)',
81
84
  id('evt'), runId, 'queued',
82
85
  `主模型无视觉,派生读图代理运行(${proxy.ref})转写消息 ${message.id} 的图片`,
@@ -97,11 +100,12 @@ export function spawnVisionProxyRun(service, { bot, message, target }) {
97
100
  // 主动评估入口(sendMessage / sendSoloMessage 落库投递后 fire-and-forget 调用):
98
101
  // 消息带图 && 主模型确定无视觉 → 已配置代理则派生转写运行;未配置则只记
99
102
  // vision.fallback 审计(按现状报错,不派生不重试)。任何异常只告警,绝不阻塞发送。
100
- export async function considerVisionProxy(service, { bot, message }) {
103
+ // messageStore(chat-db-split Phase 1):附图所在聊天库,由调用方随消息上下文带入。
104
+ export async function considerVisionProxy(service, { bot, message, messageStore = null }) {
101
105
  try {
102
106
  if (!bot || !message?.id) return null
103
107
  if (bot.status !== 'active') return null
104
- if (!messageHasImages(service.store, message.id)) return null
108
+ if (!messageHasImages(messageStore ?? service.store, message.id)) return null
105
109
  if (!await modelLacksImageSupport(service.runtime, bot)) return null
106
110
  const target = visionProxyTarget(service.config)
107
111
  if (!target) {
@@ -125,14 +129,14 @@ export function maybeSpawnVisionAfterFailure(service, { run, bot, error }) {
125
129
  if (!isImageUnsupportedError(error)) return null
126
130
  if (run?.kind !== 'chat' && run?.kind !== 'solo_chat') return null
127
131
  const message = run.trigger_ref
128
- ? service.store.get(
132
+ ? service.runChatStore(run).get(
129
133
  run.kind === 'chat'
130
134
  ? 'SELECT * FROM messages WHERE id = ?'
131
135
  : 'SELECT * FROM solo_messages WHERE id = ?',
132
136
  run.trigger_ref,
133
137
  )
134
138
  : null
135
- if (!message || !messageHasImages(service.store, message.id)) return null
139
+ if (!message || !messageHasImages(service.runChatStore(run), message.id)) return null
136
140
  const target = visionProxyTarget(service.config)
137
141
  if (!target) {
138
142
  service.audit({ type: 'bot', id: bot.id }, 'vision.fallback', 'bot', bot.id, {
@@ -147,14 +151,61 @@ export function maybeSpawnVisionAfterFailure(service, { run, bot, error }) {
147
151
  }
148
152
  }
149
153
 
154
+ // 续答派生(闭环):转写写回后同一条消息再排一次 chat/solo_chat 运行,让主模型基于
155
+ // 转写正文回答用户。首发运行已因主模型无视觉失败,其幂等键(chat:<msg>:<bot>)会被
156
+ // enqueueChatRun 的既有行查询挡下,所以续答自带新键;image_offload=1 让 startRun
157
+ // 跳过二进制附图,转写正文由提示词近期窗口带入。
158
+ export function spawnVisionFollowupRun(service, { run, bot, message }) {
159
+ if (!bot || !message?.id) return null
160
+ const isSolo = !run?.project_id
161
+ const idempotencyKey = isSolo
162
+ ? `solo_chat:${message.id}:vision`
163
+ : `chat:${message.id}:${bot.id}:vision`
164
+ const existing = service.store.get('SELECT * FROM runs WHERE idempotency_key = ?', idempotencyKey)
165
+ if (existing) return existing
166
+ // 沿用首发运行的 trigger_type:通道直达(微信/飞书)的回推语义不能丢。
167
+ const source = service.store.get(
168
+ `SELECT trigger_type FROM runs WHERE trigger_ref = ? AND bot_id = ?
169
+ AND kind IN ('chat', 'solo_chat') ORDER BY queued_at DESC LIMIT 1`,
170
+ message.id, bot.id,
171
+ )
172
+ const runId = id('run')
173
+ const createdAt = nowIso()
174
+ try {
175
+ service.store.transaction(() => {
176
+ service.store.run(
177
+ `INSERT INTO runs(id, project_id, bot_id, kind, mode, trigger_type, trigger_ref,
178
+ status, attempt, idempotency_key, image_offload, queued_at)
179
+ VALUES (?, ?, ?, ?, 'read', ?, ?, 'queued', 1, ?, 1, ?)`,
180
+ runId, run?.project_id ?? null, bot.id, isSolo ? 'solo_chat' : 'chat',
181
+ source?.trigger_type ?? 'mention', message.id, idempotencyKey, createdAt,
182
+ )
183
+ service.runChatStore({ id: runId, project_id: run?.project_id ?? null, bot_id: bot.id }).run(
184
+ 'INSERT INTO run_events(id, run_id, type, message, created_at) VALUES (?, ?, ?, ?, ?)',
185
+ id('evt'), runId, 'queued',
186
+ `转写完成,续答消息 ${message.id}(本轮不下发二进制图)`,
187
+ createdAt,
188
+ )
189
+ })
190
+ } catch (insertError ) {
191
+ if (String(insertError).includes('UNIQUE')) {
192
+ return service.store.get('SELECT * FROM runs WHERE idempotency_key = ?', idempotencyKey) ?? null
193
+ }
194
+ throw insertError
195
+ }
196
+ service.logger?.info?.('dsh-team: vision followup run %s queued for message %s', runId, message.id)
197
+ void service.tick()
198
+ return service.store.get('SELECT * FROM runs WHERE id = ?', runId)
199
+ }
200
+
150
201
  // 转写运行收尾(runs.finishRun 的 kind='vision' 分支):成功且产出非空 → 以
151
202
  // 「[图片转写] …」system 消息写回原消息所在会话(群聊挂 reply_to 原消息,单聊
152
- // 落 solo_messages),并审计 vision.transcribe;失败或空产出 → 只审计
203
+ // 落 solo_messages),并审计 vision.transcribe,随后派生续答运行;失败或空产出 → 只审计
153
204
  // vision.fallback(原对话已按现状报过「模型不支持图片」,这里不再插消息、不重试)。
154
205
  export async function completeVisionRun(service, { run, bot, status, output, error }) {
155
206
  const actor = { type: 'bot', id: bot?.id }
156
207
  const message = run.trigger_ref
157
- ? service.store.get(
208
+ ? service.runChatStore(run).get(
158
209
  run.project_id
159
210
  ? 'SELECT * FROM messages WHERE id = ?'
160
211
  : 'SELECT * FROM solo_messages WHERE id = ?',
@@ -185,6 +236,13 @@ export async function completeVisionRun(service, { run, bot, status, output, err
185
236
  service.audit(actor, 'vision.transcribe', 'bot', bot.id, {
186
237
  runId: run.id, messageId: message?.id ?? run.trigger_ref,
187
238
  })
239
+ // 闭环:转写已写回,同一条消息再排一次续答运行,让主模型基于转写正文回答用户
240
+ // (首发运行已因主模型无视觉失败,不会自己产出正文)。派生失败只告警,不拖累收尾。
241
+ try {
242
+ if (message) spawnVisionFollowupRun(service, { run, bot, message })
243
+ } catch (followupError ) {
244
+ service.logger?.warn?.('dsh-team: vision followup spawn failed: %s', followupError?.message ?? followupError)
245
+ }
188
246
  return
189
247
  }
190
248
  service.audit(actor, 'vision.fallback', 'bot', bot.id, {
@@ -7,8 +7,10 @@ import { createRequire } from 'node:module'
7
7
  import { effectiveWechatEnabled } from '../config.js'
8
8
  import { AppError, conflict } from '../errors.js'
9
9
  import { WechatIlinkError } from '../wechat/commands.js'
10
- import { jsonParse, nowIso, parseMentions } from '../util.js'
10
+ import { flattenWhitespace, jsonParse, nowIso, parseMentions } from '../util.js'
11
11
  import { answerFailed, answerReceipt, approvalCard, questionCard, wechatToken } from '../wechat/format.js'
12
+ import { approvalCard as feishuApprovalCard, questionCard as feishuQuestionCard } from '../feishu/format.js'
13
+ import { cleanQuestionItem } from './questions.js'
12
14
  import { recordWechatTriggerRow } from './wechat-trigger-schema.js'
13
15
 
14
16
  // 微信登录二维码:服务端直接出 SVG,UI 注入即可,无需前端 QR 库(vendor/qrcode,MIT)。
@@ -160,7 +162,7 @@ export const wechatMethods = {
160
162
  async wechatDirectorChat(director, body) {
161
163
  const adminPeerId = this.wechat?.status?.()?.adminPeerId ?? null
162
164
  const actor = { type: 'user', id: adminPeerId ?? 'user:wechat' }
163
- const firstContact = !this.store.get(
165
+ const firstContact = !this.soloChatStore(director.id).get(
164
166
  "SELECT id FROM solo_messages WHERE bot_id = ? AND sender_type = 'user' AND sender_id = ? LIMIT 1",
165
167
  director.id,
166
168
  actor.id,
@@ -243,9 +245,16 @@ export const wechatMethods = {
243
245
  * (各通道 outbox 库彼此独立,同键在两套库里各自幂等,互不干扰)。
244
246
  * DSHBOTS-326:出站经 channelNotify 扇出到微信与飞书,单通道失败不阻断另一通道。 */
245
247
  wechatQuestion(project, row, items) {
248
+ const token = wechatToken(row.id)
249
+ const projectName = project.name || project.key
250
+ const botName = row.bot_name ?? 'Bot'
246
251
  const results = this.channelNotify?.(
247
- questionCard(project.name || project.key, row.bot_name ?? 'Bot', items, wechatToken(row.id)),
248
- { receiptKey: `question:${row.id}` },
252
+ questionCard(projectName, botName, items, token),
253
+ {
254
+ receiptKey: `question:${row.id}`,
255
+ // 飞书原生渲染 markdown:给 markdown 卡片;微信仍走纯文本镜像(窄屏、字数受限)。
256
+ texts: { feishu: feishuQuestionCard(projectName, botName, items, token) },
257
+ },
249
258
  ) ?? []
250
259
  return results.some(result => result.ok)
251
260
  },
@@ -254,9 +263,15 @@ export const wechatMethods = {
254
263
  * 幂等收据键(A3/DSHBOTS-323):approval:<row.id>(各通道 outbox 库内各自幂等)。
255
264
  * DSHBOTS-326:出站经 channelNotify 扇出,单通道失败只留痕不阻断另一通道。 */
256
265
  wechatApproval(project, row) {
266
+ const token = wechatToken(row.id)
267
+ const projectName = project.name || project.key
268
+ const botName = row.bot_name ?? 'Bot'
257
269
  const results = this.channelNotify?.(
258
- approvalCard(project.name || project.key, row.bot_name ?? 'Bot', row.tool_name, row.reason, wechatToken(row.id)),
259
- { receiptKey: `approval:${row.id}` },
270
+ approvalCard(projectName, botName, row.tool_name, row.reason, token),
271
+ {
272
+ receiptKey: `approval:${row.id}`,
273
+ texts: { feishu: feishuApprovalCard(projectName, botName, row.tool_name, row.reason, token) },
274
+ },
260
275
  ) ?? []
261
276
  return results.some(result => result.ok)
262
277
  },
@@ -345,7 +360,8 @@ export const wechatMethods = {
345
360
  async wechatAnswerQuestion(token, body, fallbackKey = null) {
346
361
  const row = this.pendingWechatRow('questions', token, fallbackKey)
347
362
  if (!row) return answerFailed(token, '没有匹配的待答提问(可能已作答或已过期)')
348
- const items = jsonParse(row.questions, [])
363
+ // 选项 label 与工作台同口径(单行化):存量行带 CR 时也能按清洗后的文字命中。
364
+ const items = jsonParse(row.questions, []).map(cleanQuestionItem)
349
365
  const parsed = parseWechatAnswers(items, body)
350
366
  if (parsed.error) return answerFailed(token, parsed.error)
351
367
  this.settleQuestion(row.id, 'answered', { answers: parsed.answers }, 'user:wechat')
@@ -427,7 +443,7 @@ function parseWechatAnswers(items, body) {
427
443
  answers.push({ id: String(item.id), selected })
428
444
  parts.push(`Q${i + 1}: ${selected.join('、')}`)
429
445
  } else {
430
- answers.push({ id: String(item.id), selected: [], ...(raw ? { custom: raw } : {}) })
446
+ answers.push({ id: String(item.id), selected: [], ...(raw ? { custom: flattenWhitespace(raw) } : {}) })
431
447
  parts.push(`Q${i + 1}: ${raw || '(未填)'}`)
432
448
  }
433
449
  }
@@ -1,4 +1,6 @@
1
- // DSHBOTS-294 子代理账本(ADR §4.2.1):宿主事件缝 → 所属 task 运行的 run_events。
1
+ // DSHBOTS-294 子代理账本(ADR §4.2.1):宿主事件缝 → 所属 task 运行的 run_events
2
+ // (chat-db-split Phase 3 起事件住运行归属聊天库,路由器 { forRun } 由调用方注入,
3
+ // 未注入时回落顶库,行为与分库前一致)。
2
4
  // 双缝互补:tools 瀑布带 caller agent(父归属权威源,任务号标签在参数里);
3
5
  // subagent/start|end 带 stopReason+lastAssistantMessage(终态摘要源,载荷无父身份,
4
6
  // 靠 tools/result 配对或唯一 running task 运行兜底归属)。子代理不占 runs 行(§4.2)。
@@ -8,6 +10,13 @@ const SUBAGENT_TOOLS = new Set(['subagent', 'subagent_fork'])
8
10
  const SUMMARY_LIMIT = 400
9
11
  const STASH_LIMIT = 64
10
12
 
13
+ // bot → 在跑子代理计数(内存态,仅本轮进程内准确):总览 bots 页的「任务中」判定用。
14
+ const runningByBot = new Map()
15
+
16
+ export function runningSubagentCount(botId) {
17
+ return runningByBot.get(botId) ?? 0
18
+ }
19
+
11
20
  // 任务号标签(DSHBOTS-292 约定标签=任务号,如 DSHBOTS-294):优先 description,其次 prompt。
12
21
  export function taskLabelOf(args) {
13
22
  const source = typeof args?.description === 'string' ? args.description
@@ -24,7 +33,7 @@ const truncate = (text) => {
24
33
  }
25
34
 
26
35
  // 在插件根 ctx 注册事件监听(根级注册面实测见 tests/subagent-ledger.test.ts)。
27
- export function installSubagentLedger(ctx, store, logger) {
36
+ export function installSubagentLedger(ctx, store, logger, chatStores = null) {
28
37
  // callId → 派发时快照(tools/result 按 callId 配对父归属)
29
38
  const byCall = new Map()
30
39
  // botId → 未消费的标签栈(subagent/end 兜底归属时取最近一次派发的标签)
@@ -51,10 +60,16 @@ export function installSubagentLedger(ctx, store, logger) {
51
60
  return run ? { botId: binding.bot_id, runId: run.id } : null
52
61
  }
53
62
 
54
- const record = (runId, type, message) => store.run(
55
- 'INSERT INTO run_events(id, run_id, type, message, created_at) VALUES (?, ?, ?, ?, ?)',
56
- id('rev'), runId, type, message, nowIso(),
57
- )
63
+ // 事件住运行归属聊天库(Phase 3):只有 runId,先取路由列再走注入的路由器;
64
+ // 运行行已不在(删除竞态)或未注入路由器时回落顶库留痕,不丢审计线索。
65
+ const record = (runId, type, message) => {
66
+ const run = store.get('SELECT id, project_id, bot_id FROM runs WHERE id = ?', runId)
67
+ const target = run && chatStores?.forRun ? chatStores.forRun(run) : store
68
+ target.run(
69
+ 'INSERT INTO run_events(id, run_id, type, message, created_at) VALUES (?, ?, ?, ?, ?)',
70
+ id('rev'), runId, type, message, nowIso(),
71
+ )
72
+ }
58
73
 
59
74
  const stashLabel = (botId, label) => {
60
75
  const list = labelsByBot.get(botId) ?? []
@@ -108,6 +123,7 @@ export function installSubagentLedger(ctx, store, logger) {
108
123
  record(owner.runId, 'subagent_spawned', `${exec.name} label=${label ?? '-'} bot=${owner.botId}`)
109
124
  byCall.set(exec.callId, { ...owner, label })
110
125
  stashLabel(owner.botId, label)
126
+ runningByBot.set(owner.botId, (runningByBot.get(owner.botId) ?? 0) + 1)
111
127
  }
112
128
  }
113
129
  } catch (error) {
@@ -144,6 +160,7 @@ export function installSubagentLedger(ctx, store, logger) {
144
160
  const entry = byCall.get(exec?.callId)
145
161
  if (!entry) return
146
162
  byCall.delete(exec?.callId)
163
+ runningByBot.set(entry.botId, Math.max(0, (runningByBot.get(entry.botId) ?? 1) - 1))
147
164
  // 配对暂存的 subagent/end:child id 出现在结果 JSON 里即认领其终态摘要
148
165
  let matched = null
149
166
  const haystack = JSON.stringify(result ?? {})