dsh-team-bots 0.2.289 → 0.2.347

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 (119) hide show
  1. package/README.md +60 -122
  2. package/docs/README.zh.md +61 -123
  3. package/docs/assets/channel-redesign.png +0 -0
  4. package/docs/assets/global-config-dark.png +0 -0
  5. package/docs/assets/global-config-light.png +0 -0
  6. package/docs/assets/global-config-light.zh.png +0 -0
  7. package/docs/assets/global-config-redesign.png +0 -0
  8. package/docs/assets/secrets-redesign.png +0 -0
  9. package/docs/assets/tasks.png +0 -0
  10. package/docs/assets/tasks.zh.png +0 -0
  11. package/docs/assets/usage-redesign-global.png +0 -0
  12. package/docs/assets/usage.png +0 -0
  13. package/docs/assets/usage.zh.png +0 -0
  14. package/package.json +17 -5
  15. package/scripts/doctor.mjs +4 -4
  16. package/src/api.js +6 -3
  17. package/src/botmsg.js +1 -1
  18. package/src/config.js +18 -8
  19. package/src/db-migrations.js +76 -9
  20. package/src/db.js +28 -2
  21. package/src/http.js +22 -3
  22. package/src/paths.js +32 -1
  23. package/src/pricing.js +2 -2
  24. package/src/runtime.js +1 -1
  25. package/src/secrets.js +4 -4
  26. package/src/service.js +14 -5
  27. package/src/services/approvals.js +109 -24
  28. package/src/services/backoff.js +34 -0
  29. package/src/services/bot-quota.js +242 -0
  30. package/src/services/bots.js +35 -6
  31. package/src/services/chat.js +15 -9
  32. package/src/services/core.js +33 -5
  33. package/src/services/hygiene.js +8 -4
  34. package/src/services/locale.js +17 -0
  35. package/src/services/memory.js +112 -1
  36. package/src/services/message-images.js +3 -3
  37. package/src/services/notify.js +169 -0
  38. package/src/services/projects.js +119 -10
  39. package/src/services/proposals.js +2 -3
  40. package/src/services/questions.js +75 -32
  41. package/src/services/review-watchdog.js +261 -30
  42. package/src/services/run-finish.js +186 -17
  43. package/src/services/runs.js +42 -13
  44. package/src/services/runtime/lifecycle.js +3 -1
  45. package/src/services/runtime/model-restore.js +5 -5
  46. package/src/services/runtime/prompt.js +106 -45
  47. package/src/services/runtime/session.js +38 -14
  48. package/src/services/runtime/trajectory.js +1 -1
  49. package/src/services/scheduler.js +146 -19
  50. package/src/services/secrets.js +1 -1
  51. package/src/services/system.js +23 -6
  52. package/src/services/task-dispatch.js +315 -0
  53. package/src/services/task-notify.js +55 -11
  54. package/src/services/task-runs.js +179 -0
  55. package/src/services/task-stage.js +4 -0
  56. package/src/services/tasks.js +51 -399
  57. package/src/services/terminal.js +2 -2
  58. package/src/services/vision-proxy.js +3 -3
  59. package/src/services/wechat.js +228 -7
  60. package/src/services/workspace-groups.js +4 -3
  61. package/src/skill-parse.js +1 -1
  62. package/src/skills.js +1 -1
  63. package/src/tools.js +275 -6
  64. package/src/updater.js +52 -0
  65. package/src/usage-reconcile.js +1 -1
  66. package/src/usage.js +52 -11
  67. package/src/wechat/channel.js +14 -20
  68. package/src/wechat/commands.js +129 -81
  69. package/src/wechat/format.js +247 -0
  70. package/src/wechat/store.js +30 -2
  71. package/ui/app.js +57 -53
  72. package/ui/i18n/en/chat.js +140 -0
  73. package/ui/i18n/en/common.js +187 -0
  74. package/ui/i18n/en/nav.js +89 -0
  75. package/ui/i18n/en/settings.js +352 -0
  76. package/ui/i18n/en/tasks.js +229 -0
  77. package/ui/i18n/en/usage.js +141 -0
  78. package/ui/i18n/en/wechat.js +23 -0
  79. package/ui/i18n/en.js +17 -237
  80. package/ui/i18n/zh/chat.js +140 -0
  81. package/ui/i18n/zh/common.js +187 -0
  82. package/ui/i18n/zh/nav.js +89 -0
  83. package/ui/i18n/zh/settings.js +352 -0
  84. package/ui/i18n/zh/tasks.js +229 -0
  85. package/ui/i18n/zh/usage.js +141 -0
  86. package/ui/i18n/zh/wechat.js +23 -0
  87. package/ui/i18n/zh.js +17 -236
  88. package/ui/modules/api.js +4 -3
  89. package/ui/modules/bot-quota.js +27 -0
  90. package/ui/modules/cards.js +96 -58
  91. package/ui/modules/chat.js +28 -30
  92. package/ui/modules/composer.js +41 -37
  93. package/ui/modules/dom-morph.js +292 -0
  94. package/ui/modules/events-board.js +22 -22
  95. package/ui/modules/events-click.js +100 -68
  96. package/ui/modules/events-misc.js +34 -34
  97. package/ui/modules/events-submit.js +28 -28
  98. package/ui/modules/global-pages.js +125 -116
  99. package/ui/modules/i18n.js +0 -5
  100. package/ui/modules/icons.js +0 -1
  101. package/ui/modules/markdown.js +1 -1
  102. package/ui/modules/modal-forms.js +196 -203
  103. package/ui/modules/modal-layer.js +6 -9
  104. package/ui/modules/page-shell.js +62 -0
  105. package/ui/modules/settings.js +211 -198
  106. package/ui/modules/solo-archive.js +0 -4
  107. package/ui/modules/state.js +57 -50
  108. package/ui/modules/tasks.js +167 -171
  109. package/ui/modules/typing-linger.js +1 -4
  110. package/ui/modules/usage.js +65 -78
  111. package/ui/modules/util.js +92 -25
  112. package/ui/styles/avatars.css +14 -0
  113. package/ui/styles/cards.css +49 -0
  114. package/ui/styles/chat-cards.css +17 -21
  115. package/ui/styles/global-config.css +56 -2
  116. package/ui/styles/modal.css +13 -0
  117. package/ui/styles/usage.css +3 -61
  118. package/CONTRIBUTING.md +0 -20
  119. package/docs/assets/usage-dark.png +0 -0
@@ -7,7 +7,7 @@ import { readdirSync, rmSync, statSync } from 'node:fs'
7
7
  import { dirname, join, resolve } from 'node:path'
8
8
  import { homedir } from 'node:os'
9
9
  import { badRequest, conflict, forbidden, notFound } from '../errors.js'
10
- import { ensureExternalDir, ensureProjectWorkspace } from '../paths.js'
10
+ import { ensureBotTmpDirs, ensureExternalDir, ensureProjectWorkspace } from '../paths.js'
11
11
  import { clampNumber, id, nowIso, parseDisabledSkills, projectKey, slugify, text } from '../util.js'
12
12
 
13
13
 
@@ -158,6 +158,30 @@ export const projectsMethods = {
158
158
  return bot
159
159
  },
160
160
 
161
+ // 成员会话上下文(DSHBOTS-229):项目群内任意成员 bot 可用;非项目成员、单聊会话一律 forbidden。
162
+ // 与 ownerContextFor 同口径,但不要求总监身份。
163
+ memberContextFor(sessionId) {
164
+ const binding = this.store.get('SELECT * FROM session_bindings WHERE session_id = ?', sessionId)
165
+ if (!binding || !binding.project_id) throw forbidden('只有项目群中的 Bot 可以执行该操作')
166
+ const project = this.projectRow(binding.project_id)
167
+ const bot = this.assertMember(project.id, binding.bot_id)
168
+ return { binding, project, bot, actor: { type: 'bot', id: binding.bot_id } }
169
+ },
170
+
171
+ // 成员查询工具入口(DSHBOTS-229):项目群内任意成员可查本项目名单/角色/状态。
172
+ // 数据源是 membersOf(本项目成员表),不触其他项目数据;输出纯文本。
173
+ listMembersFromBot(sessionId) {
174
+ const { project, bot } = this.memberContextFor(sessionId)
175
+ const members = this.membersOf(project.id)
176
+ const lines = members.map(member => {
177
+ const tags = [`${member.name}`, member.id === bot.id ? '(你)' : '', `项目角色 ${member.member_role}`]
178
+ if (member.bot_role) tags.push(`职责 ${member.bot_role}`)
179
+ tags.push(`状态 ${member.status}`)
180
+ return `- ${tags.filter(Boolean).join(',')}`
181
+ })
182
+ return [`项目 ${project.key} 成员(${members.length}):`, ...lines].join('\n')
183
+ },
184
+
161
185
  // 项目生产目录:显式指定的外部目录优先(Bot 的 cwd、密钥物化、产物清单),
162
186
  // 未指定时与 <工作区>/{slug} 管理目录一致。
163
187
  projectWorkDir(project) {
@@ -170,7 +194,7 @@ export const projectsMethods = {
170
194
  if (!raw) return null
171
195
  try {
172
196
  return await ensureExternalDir(raw)
173
- } catch (error) {
197
+ } catch (error ) {
174
198
  throw badRequest(error.message || '生产目录无效')
175
199
  }
176
200
  },
@@ -183,7 +207,7 @@ export const projectsMethods = {
183
207
  let entries
184
208
  try {
185
209
  entries = readdirSync(target, { withFileTypes: true })
186
- } catch (error) {
210
+ } catch (error ) {
187
211
  throw badRequest(`无法读取目录 ${target}:${error?.message ?? error}`)
188
212
  }
189
213
  const dirs = []
@@ -282,15 +306,25 @@ export const projectsMethods = {
282
306
  if (Number(teamSecrets?.n) > 0) {
283
307
  try {
284
308
  await this.materializeProjectSecrets(this.projectRow(projectId))
285
- } catch (error) {
309
+ } catch (error ) {
286
310
  this.logger.warn?.(`dsh-team: 新项目 ${projectId} 清理旧 .team/secrets.env 残留失败:${error?.message ?? error}`)
287
311
  }
288
312
  }
313
+ // DSHBOTS-225 临时文件纪律:建群即落 .tmp/bots/(ignore 文件 + 各成员目录)。
314
+ // 创建失败只告警,不阻塞建群主流程。
315
+ try {
316
+ await ensureBotTmpDirs(
317
+ this.projectWorkDir(this.projectRow(projectId)),
318
+ this.membersOf(projectId).map(member => member.name),
319
+ )
320
+ } catch (error ) {
321
+ this.logger.warn?.(`dsh-team: 项目 ${key} 初始化 .tmp/bots 失败:${error?.message ?? error}`)
322
+ }
289
323
  return this.projectView(this.projectRow(projectId))
290
324
  },
291
325
  async updateProject(projectId, patch, actor = this.actor()) {
292
326
  const project = this.projectRow(projectId)
293
- const updates = {}
327
+ const updates = {}
294
328
  if (patch.name !== undefined) {
295
329
  const name = text(patch.name, 80)
296
330
  if (!name) throw badRequest('项目名称不能为空')
@@ -418,7 +452,7 @@ export const projectsMethods = {
418
452
  if (productionDirChanged && project.production_dir) {
419
453
  try {
420
454
  rmSync(join(project.production_dir, '.team', 'secrets.env'), { force: true })
421
- } catch (error) {
455
+ } catch (error ) {
422
456
  this.logger.warn?.(`dsh-team: 切换生产目录后清理旧目录密钥失败:${error?.message ?? error}`)
423
457
  }
424
458
  }
@@ -427,7 +461,7 @@ export const projectsMethods = {
427
461
  if (Number(teamSecrets?.n) > 0) {
428
462
  try {
429
463
  await this.materializeProjectSecrets(this.projectRow(projectId))
430
- } catch (error) {
464
+ } catch (error ) {
431
465
  this.logger.warn?.(`dsh-team: 切换生产目录后清理旧密钥残留失败:${error?.message ?? error}`)
432
466
  }
433
467
  }
@@ -451,7 +485,7 @@ export const projectsMethods = {
451
485
  // 移除已归档项目的全部管理数据(含项目行本身)。全局口径不动的三张表:usage_events(FK 置空,
452
486
  // 用量是全局历史)、audit_log(append-only,本次移除本身要可审计)、solo_messages(Bot 域,与项目无关)。
453
487
  // 逐表显式删除(子表先于父表),不依赖隐式级联;proposals 的 FK 是 SET NULL,必须在项目行删除前清掉。
454
- removeProjectTracking(projectId, input = {}, actor = this.actor()) {
488
+ removeProjectTracking(projectId, input = {} , actor = this.actor()) {
455
489
  const project = this.projectRow(projectId)
456
490
  if (project.status !== 'archived') throw badRequest('项目未归档,先归档再移除追踪')
457
491
  const confirmName = typeof input.confirmName === 'string' ? input.confirmName.trim() : ''
@@ -500,7 +534,7 @@ export const projectsMethods = {
500
534
  if (input.deleteProductionDir === true) {
501
535
  try {
502
536
  rmSync(dir, { recursive: true, force: true })
503
- } catch (error) {
537
+ } catch (error ) {
504
538
  this.logger.warn?.(`dsh-team: 移除项目 ${project.key} 生产目录失败:${error?.message ?? error}`)
505
539
  this.audit(actor, 'project.remove_tracking_dir', 'project', projectId, { dir, deleted: false })
506
540
  }
@@ -509,7 +543,7 @@ export const projectsMethods = {
509
543
  },
510
544
 
511
545
  // 邀请已有 bot 加入项目。与 updateProject 的 memberIds 全量替换不同,这里做增量并给出精确错误语义。
512
- addProjectMember(projectId, botId, actor = this.actor()) {
546
+ async addProjectMember(projectId, botId, actor = this.actor()) {
513
547
  const project = this.projectRow(projectId)
514
548
  if (project.status !== 'active') throw badRequest('项目已归档,不能添加成员')
515
549
  const bot = this.botRow(botId)
@@ -526,6 +560,29 @@ export const projectsMethods = {
526
560
  )
527
561
  this.audit(actor, 'project.add_member', 'project', projectId, { botId, botName: bot.name })
528
562
  })
563
+ // DSHBOTS-225 临时文件纪律:新成员入群即有自己的 .tmp/bots/{bot名}/ 目录;
564
+ // 创建失败只告警,不阻塞入群主流程。
565
+ try {
566
+ await ensureBotTmpDirs(this.projectWorkDir(project), [bot.name])
567
+ } catch (error ) {
568
+ this.logger.warn?.(`dsh-team: 项目 ${project.key} 为成员 ${bot.name} 创建临时目录失败:${error?.message ?? error}`)
569
+ }
570
+ // DSHBOTS-229 入群通知:新成员入群后向其他成员发群系统消息(纯文本,无 emoji)。
571
+ // 与临时目录同口径:通知失败只告警,不阻塞入群主流程。
572
+ try {
573
+ const others = this.membersOf(projectId).filter(member => member.id !== botId)
574
+ if (others.length > 0) {
575
+ this.insertMessage({
576
+ projectId,
577
+ senderType: 'system',
578
+ senderId: 'system',
579
+ body: `成员 ${bot.name} 已加入项目群。`,
580
+ mentions: others.map(member => member.id),
581
+ })
582
+ }
583
+ } catch (error ) {
584
+ this.logger.warn?.(`dsh-team: 项目 ${project.key} 为成员 ${bot.name} 发送入群通知失败:${error?.message ?? error}`)
585
+ }
529
586
  return this.projectView(this.projectRow(projectId))
530
587
  },
531
588
 
@@ -549,4 +606,56 @@ export const projectsMethods = {
549
606
  })
550
607
  return this.projectView(this.projectRow(projectId))
551
608
  },
609
+
610
+ // bots 池视图(DSHBOTS-229):总监视角列出全部未移除 bot,标注是否已在本项目及成员角色。
611
+ // 只暴露 bot 自身档案与本项目成员关系,不透露该 bot 在其他项目的成员关系或数据。
612
+ botsPoolFor(projectId) {
613
+ const project = this.projectRow(projectId)
614
+ const membership = new Map(
615
+ this.store.all(
616
+ "SELECT member_id, member_role FROM project_members WHERE project_id = ? AND member_type = 'bot'",
617
+ projectId,
618
+ ).map(row => [row.member_id, row.member_role]),
619
+ )
620
+ const bots = this.store.all(
621
+ "SELECT id, name, role, provider, model, status FROM bots WHERE status <> 'removed' ORDER BY created_at, name",
622
+ )
623
+ return {
624
+ project: { id: project.id, key: project.key, name: project.name },
625
+ bots: bots.map(bot => ({
626
+ id: bot.id,
627
+ name: bot.name,
628
+ role: bot.role,
629
+ modelRef: bot.provider && bot.model ? `${bot.provider}/${bot.model}` : null,
630
+ status: bot.status,
631
+ inProject: membership.has(bot.id),
632
+ memberRole: membership.get(bot.id) ?? null,
633
+ })),
634
+ }
635
+ },
636
+
637
+ // 池查询工具入口(DSHBOTS-229):仅总监可用(ownerContextFor 权威校验)。
638
+ listBotsPoolFromBot(sessionId) {
639
+ const { project } = this.ownerContextFor(sessionId)
640
+ const pool = this.botsPoolFor(project.id)
641
+ const lines = pool.bots.map(bot => {
642
+ const membership = bot.inProject
643
+ ? (bot.memberRole === 'owner' ? '本项目总监' : '本项目成员')
644
+ : '未入群'
645
+ return `- ${bot.name} [${bot.status}] ${bot.role || '未设职责'},${membership}`
646
+ })
647
+ return [`项目 ${project.key} 的 bots 池(${pool.bots.length}):`, ...lines].join('\n')
648
+ },
649
+
650
+ // 加人申请入口(DSHBOTS-229):总监按名称邀请 bot 入群,复用 addProjectMember 的校验、审计与入群通知。
651
+ async addMemberFromBot(sessionId, input) {
652
+ const { project, actor } = this.ownerContextFor(sessionId)
653
+ const name = String(input?.bot ?? input?.name ?? '').trim()
654
+ if (!name) throw badRequest('缺少 Bot 名称')
655
+ const bot = this.store.get('SELECT * FROM bots WHERE lower(name) = lower(?)', name)
656
+ if (!bot) throw notFound(`找不到 Bot ${name}`)
657
+ const view = await this.addProjectMember(project.id, bot.id, actor)
658
+ const member = view.members.find(row => row.id === bot.id)
659
+ return { project: { id: project.id, key: project.key, name: project.name }, member }
660
+ },
552
661
  }
@@ -92,7 +92,8 @@ export const proposalsMethods = {
92
92
  }
93
93
  },
94
94
 
95
- // 评估:提案必须先有评估结论,结论为 pass 才允许批准。
95
+ // 评估:记录对提案的评估结论,供审批参考与留痕;评估不是审批的前置条件,
96
+ // 人工批准/拒绝即最终决定(评估人与审批人是同一用户,两步门槛只会造成死锁)。
96
97
  async evaluateProposal(proposalId, evaluation, actor = this.actor()) {
97
98
  const proposal = this.store.get('SELECT * FROM proposals WHERE id = ?', proposalId)
98
99
  if (!proposal) throw notFound('提案不存在')
@@ -114,10 +115,8 @@ export const proposalsMethods = {
114
115
  if (!proposal) throw notFound('提案不存在')
115
116
  if (proposal.status !== 'pending') throw conflict('提案已处理')
116
117
  const payload = jsonParse(proposal.payload_json, {})
117
- const evaluation = jsonParse(proposal.evaluation_json, {})
118
118
  const canary = jsonParse(proposal.canary_json, null)
119
119
  if (decision === 'approved') {
120
- if (evaluation?.verdict !== 'pass') throw conflict('提案缺少通过的评估结果,请先完成评估')
121
120
  const applied = await this.applyProposal(proposal, payload, canary, actor)
122
121
  const nextStatus = applied.canary ? 'canary' : 'approved'
123
122
  this.store.run(
@@ -1,16 +1,18 @@
1
1
  // DSHBOTS-116 群聊提问:宿主 user-questions/request waterfall 的插件侧应答器。
2
- // 只认领 session_bindings 命中且绑定到项目的 bot 会话;其余 next() 透传(人类会话提问继续走原生界面)。
3
- // 应答权仅项目负责人(type=user)持有,bot 一律 forbidden 不能自答;pending 之外拒绝重复应答,动作写审计。
2
+ // 认领 session_bindings 命中的 bot 会话:绑定到项目的走群聊卡片;绑定为单聊(kind='solo'、
3
+ // project_id 为空)的走单聊卡片(DSHBOTS-218);其余 next() 透传(人类会话提问继续走原生界面)。
4
+ // 应答权仅用户(type=user)持有,bot 一律 forbidden 不能自答;pending 之外拒绝重复应答,动作写审计。
4
5
  // DSHBOTS-177:宿主 timed 前台等待到期(ASK_TIMED_OUT abort)不杀卡——条目保持可答至插件
5
6
  // questionTimeoutMs 窗口,窗口内迟到作答经宿主 userQuestions.answer 回投原 agent;其余 abort 立即失效。
6
7
  // 注意:本域自管迁移(db.js 已贴 800 行上限,一行不加),手法与 approvals.js 一致。
7
8
  import { badRequest, conflict, forbidden, notFound } from '../errors.js'
8
9
  import { id, jsonParse, nowIso, text as textValue } from '../util.js'
10
+ import { columnNotNull, rebuildTable } from '../db-migrations.js'
9
11
 
10
- const QUESTIONS_DDL = `
11
- CREATE TABLE IF NOT EXISTS questions (
12
+ // project_id 可空:单聊会话没有项目归属(DSHBOTS-218),卡片锚点改落 solo_messages。
13
+ const QUESTIONS_TABLE_DDL = `
12
14
  id TEXT PRIMARY KEY,
13
- project_id TEXT NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
15
+ project_id TEXT REFERENCES projects(id) ON DELETE CASCADE,
14
16
  run_id TEXT,
15
17
  bot_id TEXT NOT NULL,
16
18
  session_id TEXT,
@@ -22,7 +24,9 @@ CREATE TABLE IF NOT EXISTS questions (
22
24
  created_at TEXT NOT NULL,
23
25
  expires_at TEXT NOT NULL,
24
26
  ended_at TEXT
25
- );
27
+ `
28
+ const QUESTIONS_DDL = `
29
+ CREATE TABLE IF NOT EXISTS questions (${QUESTIONS_TABLE_DDL});
26
30
  CREATE INDEX IF NOT EXISTS questions_status_idx ON questions(status, created_at);
27
31
  CREATE INDEX IF NOT EXISTS questions_project_idx ON questions(project_id, created_at);
28
32
  `
@@ -31,6 +35,12 @@ CREATE INDEX IF NOT EXISTS questions_project_idx ON questions(project_id, create
31
35
  // 重启清理也在此——宿主侧请求随进程消失,不可能再被应答,库里残留的 pending 一律置 timeout。
32
36
  export function ensureQuestionSchema(store) {
33
37
  store.exec(QUESTIONS_DDL)
38
+ // 旧库 questions.project_id 是 NOT NULL(群聊专用时期),单聊会话无处归属:重建放宽为可空。
39
+ if (columnNotNull(store.db, 'questions', 'project_id')) {
40
+ rebuildTable(store.db, 'questions', `CREATE TABLE questions (${QUESTIONS_TABLE_DDL})`)
41
+ store.exec('CREATE INDEX IF NOT EXISTS questions_status_idx ON questions(status, created_at)')
42
+ store.exec('CREATE INDEX IF NOT EXISTS questions_project_idx ON questions(project_id, created_at)')
43
+ }
34
44
  const messageColumns = store.all('PRAGMA table_info(messages)').map(column => column.name)
35
45
  if (!messageColumns.includes('question_id')) {
36
46
  store.exec('ALTER TABLE messages ADD COLUMN question_id TEXT')
@@ -52,7 +62,7 @@ export function ensureQuestionSchema(store) {
52
62
  // 问题条目清洗:文案统一过密钥掩码(会进群聊与 bot 可见范围),并夹取长度防单条撑爆卡片。
53
63
  // intent 只保留 plan-review 的展示字段;未知 intent 一律按通用选项列表渲染(协议允许)。
54
64
  function cleanQuestionItem(item) {
55
- const cleaned = {
65
+ const cleaned = {
56
66
  id: String(item?.id ?? '').slice(0, 100),
57
67
  question: textValue(item?.question, 4_000),
58
68
  }
@@ -60,7 +70,7 @@ function cleanQuestionItem(item) {
60
70
  if (item?.header) cleaned.header = textValue(item.header, 200)
61
71
  if (Array.isArray(item?.options)) {
62
72
  cleaned.options = item.options.slice(0, 20).map(option => {
63
- const row = { label: textValue(option?.label, 200) }
73
+ const row = { label: textValue(option?.label, 200) }
64
74
  if (option?.description) row.description = textValue(option.description, 1_000)
65
75
  return row
66
76
  })
@@ -92,10 +102,12 @@ export const questionsMethods = {
92
102
  }, 'dsh-team: user question request binding')
93
103
  },
94
104
 
95
- // waterfall 监听器:DSHBOTS-190 起,提问能力收紧为项目总监(owner bot)专属。
96
- // 未绑定会话无法归因,保持透传原生界面;命中 bot 会话一律先过所有权闸门,不再透传——
105
+ // waterfall 监听器:DSHBOTS-190 起,项目会话的提问能力收紧为项目总监(owner bot)专属。
106
+ // 未绑定会话无法归因,保持透传原生界面;命中 bot 会话一律先过归属闸门,不再透传——
97
107
  // 透传会把提问落回宿主面板,收紧形同虚设。拒绝以 rejected promise 回宿主,错误文案
98
108
  // 即调用 bot 收到的 ask_user_question 工具结果。
109
+ // DSHBOTS-218:单聊会话(kind='solo')由工作台单聊卡片承接——单聊里 bot 就是对话方,
110
+ // 没有群聊可发,无需总监归属闸门;bot 间私信(kind='dm')没有人类作答方,照旧透传。
99
111
  async handleQuestionRequest(req, next) {
100
112
  const sessionId = req?.agent?.session?.id
101
113
  // bindingOfSession 在 DshRuntime 原型上,服务层拿不到 this 绑定,这里直查同款 SQL。
@@ -104,21 +116,17 @@ export const questionsMethods = {
104
116
  : undefined
105
117
  if (!binding) return next()
106
118
 
107
- if (!binding.project_id) {
108
- return Promise.reject(new Error(
109
- 'ask_user_question 仅限项目总监 Bot 在项目群中使用;当前是单聊会话。如需向用户提问,请在项目群中由总监 Bot 发起。',
110
- ))
111
- }
112
-
113
119
  const store = this.store
120
+ const isSolo = binding.kind === 'solo' && !binding.project_id
121
+ if (!binding.project_id && !isSolo) return next()
114
122
  const bot = store.get('SELECT * FROM bots WHERE id = ?', binding.bot_id)
115
- const project = store.get('SELECT * FROM projects WHERE id = ?', binding.project_id)
116
- if (!bot || !project) {
123
+ const project = isSolo ? null : store.get('SELECT * FROM projects WHERE id = ?', binding.project_id)
124
+ if (!bot || (!isSolo && !project)) {
117
125
  return Promise.reject(new Error(
118
- 'ask_user_question 会话绑定失效,无法确认项目归属;请在项目群中由总监 Bot 发起提问。',
126
+ 'ask_user_question 会话绑定失效,无法确认会话归属;请在项目群中由总监 Bot 发起提问,或与 Bot 单聊时重试。',
119
127
  ))
120
128
  }
121
- if (project.owner_bot_id !== binding.bot_id) {
129
+ if (!isSolo && project.owner_bot_id !== binding.bot_id) {
122
130
  return Promise.reject(new Error(
123
131
  `ask_user_question 仅限项目总监 Bot 使用;${bot.name} 不是本项目总监。需要用户决策时,请把问题交给总监 Bot 发起。`,
124
132
  ))
@@ -149,7 +157,7 @@ export const questionsMethods = {
149
157
  store.run(
150
158
  `INSERT INTO questions(id, project_id, run_id, bot_id, session_id, call_id, questions, status, created_at, expires_at)
151
159
  VALUES (?, ?, ?, ?, ?, ?, ?, 'pending', ?, ?)`,
152
- questionId, project.id, run?.id ?? null, bot.id, sessionId, callId,
160
+ questionId, project?.id ?? null, run?.id ?? null, bot.id, sessionId, callId,
153
161
  JSON.stringify(masked), createdAt, new Date(Date.parse(createdAt) + timeoutMs).toISOString(),
154
162
  )
155
163
 
@@ -158,14 +166,33 @@ export const questionsMethods = {
158
166
  sessionId, callId, count: masked.length,
159
167
  })
160
168
 
161
- // 群聊里写一条提问卡片消息:状态渲染时查 questions 表,消息体只是纯文本兜底,不承载状态。
162
- const group = this.groupOf(project.id)
163
- store.run(
164
- `INSERT INTO messages(id, project_id, group_chat_id, sender_type, sender_id, body, mentions_json, kind, question_id, created_at)
165
- VALUES (?, ?, ?, 'system', ?, ?, '[]', 'question', ?, ?)`,
166
- id('msg'), project.id, group?.id ?? null, bot.id,
167
- `【提问】${bot.name} 发起提问(${masked.length} 个问题)`, questionId, createdAt,
168
- )
169
+ // 卡片锚点:群聊落 messages(kind=question),单聊落 solo_messages(DSHBOTS-218)。
170
+ // 状态渲染时查 questions 表,消息体只是纯文本兜底,不承载状态。
171
+ const anchorBody = `【提问】${bot.name} 发起提问(${masked.length} 个问题)`
172
+ if (isSolo) {
173
+ this.insertSoloMessage?.({
174
+ botId: bot.id, senderType: 'system', senderId: 'system',
175
+ body: anchorBody, runId: run?.id ?? null, createdAt, kind: 'question', questionId,
176
+ })
177
+ } else {
178
+ const group = this.groupOf(project.id)
179
+ store.run(
180
+ `INSERT INTO messages(id, project_id, group_chat_id, sender_type, sender_id, body, mentions_json, kind, question_id, created_at)
181
+ VALUES (?, ?, ?, 'system', ?, ?, '[]', 'question', ?, ?)`,
182
+ id('msg'), project.id, group?.id ?? null, bot.id, anchorBody, questionId, createdAt,
183
+ )
184
+ }
185
+
186
+ // DSHBOTS-215 问答回路:提问转发微信管理员(通道可用时)。只推纯文本镜像,
187
+ // 状态仍由群卡片/工作台承载;管理员答复经「答 <token> …」路由回本条目。
188
+ // 单聊没有项目语境,不转发(微信侧只服务项目管理者)。
189
+ if (project) {
190
+ try {
191
+ this.wechatQuestion?.(project, { id: questionId, bot_name: bot.name }, masked)
192
+ } catch (error ) {
193
+ this.logger?.warn?.('dsh-team: 微信提问转发失败: %s', error?.message ?? error)
194
+ }
195
+ }
169
196
 
170
197
  return new Promise((resolve, reject) => {
171
198
  this.questionPending ??= new Map()
@@ -239,7 +266,7 @@ export const questionsMethods = {
239
266
  const accepted = await userQuestions.answer(agent, callId, hostAnswer)
240
267
  if (accepted !== true) throw new Error('question no longer answerable at host')
241
268
  this.audit({ type: 'system', id: 'system' }, 'question.steer', 'question', questionId, { callId })
242
- } catch (error) {
269
+ } catch (error ) {
243
270
  this.audit({ type: 'system', id: 'system' }, 'question.steer_failed', 'question', questionId, {
244
271
  callId,
245
272
  reason: error?.message ?? String(error),
@@ -263,7 +290,7 @@ export const questionsMethods = {
263
290
  .map(item => [String(item?.id), item]),
264
291
  )
265
292
  const answers = items.map(item => {
266
- const answer = given.get(String(item.id))
293
+ const answer = given.get(String(item.id))
267
294
  const selected = (Array.isArray(answer?.selected) ? answer.selected : [])
268
295
  .map(value => String(value)).filter(Boolean).slice(0, 20)
269
296
  const custom = answer?.custom ? String(answer.custom).slice(0, 2_000) : undefined
@@ -289,6 +316,8 @@ export const questionsMethods = {
289
316
  questions: jsonParse(row.questions, []),
290
317
  answer: jsonParse(row.answer, null),
291
318
  botName: bot?.name ?? 'Bot',
319
+ // 会话归属(DSHBOTS-218):单聊提问没有项目,UI 据此显示来源列并决定跳转目标。
320
+ scope: row.project_id ? 'project' : 'solo',
292
321
  remainingMs: row.status === 'pending'
293
322
  ? Math.max(0, (Number.isFinite(expiresAt) ? expiresAt : Date.parse(row.created_at) + this.config.questionTimeoutMs) - Date.now())
294
323
  : 0,
@@ -305,8 +334,19 @@ export const questionsMethods = {
305
334
  return rows.map(row => this.questionView(row))
306
335
  },
307
336
 
337
+ // 单聊视图的提问条目(DSHBOTS-218):口径与 questionsForProject 一致,按 bot 取项目外条目。
338
+ questionsForBot(botId) {
339
+ const rows = this.store.all(
340
+ `SELECT * FROM questions WHERE project_id IS NULL AND bot_id = ?
341
+ ORDER BY CASE status WHEN 'pending' THEN 0 ELSE 1 END, created_at DESC LIMIT 30`,
342
+ botId,
343
+ )
344
+ return rows.map(row => this.questionView(row))
345
+ },
346
+
308
347
  // 全局待答视图:跨项目聚合 status='pending',按创建时间倒序。
309
348
  // count 是全库 pending 总数(徽标口径,已决一律不计),items 最多 50 条供顶部入口列明细。
349
+ // scope 区分项目群聊 / 单聊(DSHBOTS-218):顶部入口据此决定点击后跳哪个会话。
310
350
  questionsPending(limit = 50) {
311
351
  const rows = this.store.all(
312
352
  `SELECT q.*, p.name AS project_name FROM questions q LEFT JOIN projects p ON p.id = q.project_id
@@ -316,7 +356,10 @@ export const questionsMethods = {
316
356
  const count = Number(this.store.get("SELECT COUNT(*) AS count FROM questions WHERE status = 'pending'")?.count ?? 0)
317
357
  return {
318
358
  count,
319
- items: rows.map(row => ({ ...this.questionView(row), projectName: row.project_name ?? '' })),
359
+ items: rows.map(row => ({
360
+ ...this.questionView(row),
361
+ projectName: row.project_name ?? '',
362
+ })),
320
363
  }
321
364
  },
322
365
  }