dsh-team-bots 0.2.289 → 0.2.338

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. package/README.md +12 -136
  2. package/docs/README.zh.md +15 -139
  3. package/docs/assets/channel-redesign.png +0 -0
  4. package/docs/assets/global-config-dark.png +0 -0
  5. package/docs/assets/global-config-light.png +0 -0
  6. package/docs/assets/global-config-light.zh.png +0 -0
  7. package/docs/assets/global-config-redesign.png +0 -0
  8. package/docs/assets/secrets-redesign.png +0 -0
  9. package/docs/assets/tasks.png +0 -0
  10. package/docs/assets/tasks.zh.png +0 -0
  11. package/docs/assets/usage-redesign-global.png +0 -0
  12. package/docs/assets/usage.png +0 -0
  13. package/docs/assets/usage.zh.png +0 -0
  14. package/package.json +17 -5
  15. package/scripts/doctor.mjs +4 -4
  16. package/src/api.js +6 -3
  17. package/src/botmsg.js +1 -1
  18. package/src/config.js +18 -8
  19. package/src/db-migrations.js +76 -9
  20. package/src/db.js +28 -2
  21. package/src/http.js +22 -3
  22. package/src/paths.js +32 -1
  23. package/src/pricing.js +2 -2
  24. package/src/runtime.js +1 -1
  25. package/src/secrets.js +4 -4
  26. package/src/service.js +10 -5
  27. package/src/services/approvals.js +109 -24
  28. package/src/services/bot-quota.js +242 -0
  29. package/src/services/bots.js +35 -6
  30. package/src/services/chat.js +15 -9
  31. package/src/services/core.js +33 -5
  32. package/src/services/hygiene.js +8 -4
  33. package/src/services/locale.js +17 -0
  34. package/src/services/memory.js +112 -1
  35. package/src/services/message-images.js +3 -3
  36. package/src/services/notify.js +99 -0
  37. package/src/services/projects.js +119 -10
  38. package/src/services/proposals.js +2 -3
  39. package/src/services/questions.js +75 -32
  40. package/src/services/review-watchdog.js +261 -30
  41. package/src/services/run-finish.js +119 -7
  42. package/src/services/runs.js +42 -13
  43. package/src/services/runtime/lifecycle.js +3 -1
  44. package/src/services/runtime/model-restore.js +5 -5
  45. package/src/services/runtime/prompt.js +106 -45
  46. package/src/services/runtime/session.js +38 -14
  47. package/src/services/runtime/trajectory.js +1 -1
  48. package/src/services/scheduler.js +139 -13
  49. package/src/services/secrets.js +1 -1
  50. package/src/services/system.js +23 -6
  51. package/src/services/task-notify.js +49 -7
  52. package/src/services/task-stage.js +4 -0
  53. package/src/services/tasks.js +121 -12
  54. package/src/services/terminal.js +2 -2
  55. package/src/services/vision-proxy.js +3 -3
  56. package/src/services/wechat.js +228 -7
  57. package/src/services/workspace-groups.js +4 -3
  58. package/src/skill-parse.js +1 -1
  59. package/src/skills.js +1 -1
  60. package/src/tools.js +275 -6
  61. package/src/updater.js +52 -0
  62. package/src/usage-reconcile.js +1 -1
  63. package/src/usage.js +52 -11
  64. package/src/wechat/channel.js +14 -20
  65. package/src/wechat/commands.js +129 -81
  66. package/src/wechat/format.js +247 -0
  67. package/src/wechat/store.js +30 -2
  68. package/ui/app.js +56 -52
  69. package/ui/i18n/en/chat.js +140 -0
  70. package/ui/i18n/en/common.js +189 -0
  71. package/ui/i18n/en/nav.js +90 -0
  72. package/ui/i18n/en/settings.js +354 -0
  73. package/ui/i18n/en/tasks.js +232 -0
  74. package/ui/i18n/en/usage.js +141 -0
  75. package/ui/i18n/en/wechat.js +24 -0
  76. package/ui/i18n/en.js +17 -237
  77. package/ui/i18n/zh/chat.js +140 -0
  78. package/ui/i18n/zh/common.js +189 -0
  79. package/ui/i18n/zh/nav.js +90 -0
  80. package/ui/i18n/zh/settings.js +354 -0
  81. package/ui/i18n/zh/tasks.js +232 -0
  82. package/ui/i18n/zh/usage.js +141 -0
  83. package/ui/i18n/zh/wechat.js +24 -0
  84. package/ui/i18n/zh.js +17 -236
  85. package/ui/modules/api.js +4 -3
  86. package/ui/modules/bot-quota.js +27 -0
  87. package/ui/modules/cards.js +96 -58
  88. package/ui/modules/chat.js +28 -30
  89. package/ui/modules/composer.js +41 -37
  90. package/ui/modules/dom-morph.js +292 -0
  91. package/ui/modules/events-board.js +22 -22
  92. package/ui/modules/events-click.js +100 -68
  93. package/ui/modules/events-misc.js +34 -34
  94. package/ui/modules/events-submit.js +28 -28
  95. package/ui/modules/global-pages.js +127 -116
  96. package/ui/modules/i18n.js +0 -5
  97. package/ui/modules/icons.js +0 -1
  98. package/ui/modules/markdown.js +1 -1
  99. package/ui/modules/modal-forms.js +195 -202
  100. package/ui/modules/modal-layer.js +6 -9
  101. package/ui/modules/page-shell.js +62 -0
  102. package/ui/modules/settings.js +211 -198
  103. package/ui/modules/solo-archive.js +0 -4
  104. package/ui/modules/state.js +57 -50
  105. package/ui/modules/tasks.js +168 -171
  106. package/ui/modules/typing-linger.js +1 -4
  107. package/ui/modules/usage.js +65 -78
  108. package/ui/modules/util.js +92 -25
  109. package/ui/styles/avatars.css +14 -0
  110. package/ui/styles/cards.css +49 -0
  111. package/ui/styles/chat-cards.css +17 -21
  112. package/ui/styles/global-config.css +59 -2
  113. package/ui/styles/modal.css +13 -0
  114. package/ui/styles/usage.css +3 -61
  115. package/CONTRIBUTING.md +0 -20
  116. package/docs/assets/usage-dark.png +0 -0
@@ -3,7 +3,7 @@
3
3
  // 本文件只放方法体,方法挂到 TeamService 原型上(见 src/service.js 的 defineMethods 调用),
4
4
  // 因此方法体内的 this 与拆分前完全一致。
5
5
 
6
- import { effectiveReviewIdleMinutes, effectiveRunLimits, RUN_LIMIT_RANGES, RUN_TIMEOUT_KEY, STALL_WATCHDOG_KEY, UI_LANGUAGE_KEY, UI_LANGUAGE_VALUES } from '../config.js'
6
+ import { effectiveReviewIdleMinutes, effectiveRunLimits, RUN_LIMIT_RANGES, RUN_TIMEOUT_KEY, STALL_WATCHDOG_KEY, UI_LANGUAGE_KEY, UI_LANGUAGE_VALUES, REVIEW_AUTO_CLOSE_KEY, REVIEW_ESCALATE_KEY, REVIEW_ESCALATE_RANGE, REVIEW_IDLE_MINUTES_KEY, REVIEW_IDLE_MINUTES_RANGE } from '../config.js'
7
7
  import { badRequest, notFound } from '../errors.js'
8
8
  import { ensureDirResilient, ensureSkillRoot } from '../paths.js'
9
9
  import { seedModelPrices } from '../pricing.js'
@@ -51,7 +51,7 @@ export const coreMethods = {
51
51
  try {
52
52
  const catalog = await this.runtime?.catalog(true) ?? []
53
53
  model = catalog[0]
54
- } catch (error) {
54
+ } catch (error ) {
55
55
  // 取不到模型目录也要留痕:否则种子 Bot 带着空模型上线,问题会被埋掉。
56
56
  this.logger.warn?.(`dsh-team: 取模型目录失败,种子 Bot 将不带模型:${error?.message ?? error}`)
57
57
  }
@@ -125,7 +125,7 @@ export const coreMethods = {
125
125
  await this.wechat.start().catch(error => {
126
126
  this.logger.warn?.(`[wechat] 通道启动失败: ${error?.message ?? error}`)
127
127
  })
128
- } catch (error) {
128
+ } catch (error ) {
129
129
  this.logger.warn?.(`[wechat] 通道加载失败,已跳过: ${error?.message ?? error}`)
130
130
  }
131
131
  }
@@ -168,8 +168,9 @@ export const coreMethods = {
168
168
  'memory_review', 'chat_memory_review',
169
169
  RUN_TIMEOUT_KEY, STALL_WATCHDOG_KEY,
170
170
  UI_LANGUAGE_KEY,
171
+ REVIEW_IDLE_MINUTES_KEY, REVIEW_AUTO_CLOSE_KEY, REVIEW_ESCALATE_KEY,
171
172
  ]
172
- const values = {}
173
+ const values = {}
173
174
  for (const key of keys) values[key] = this.store.setting(key, '')
174
175
  return values
175
176
  },
@@ -189,7 +190,7 @@ export const coreMethods = {
189
190
  }
190
191
  },
191
192
  updateSettings(patch, actor = this.actor()) {
192
- const values = {}
193
+ const values = {}
193
194
  for (const [key, value] of Object.entries(patch ?? {})) {
194
195
  if (!Object.keys(this.settingsView()).includes(key)) throw badRequest(`不支持的设置项:${key}`)
195
196
  values[key] = String(value ?? '').trim()
@@ -220,6 +221,33 @@ export const coreMethods = {
220
221
  }
221
222
  values[key] = String(num)
222
223
  }
224
+ // 验收滞留守门三键(DSHBOTS-194/235):阈值 0–1440(0 = 关闭);自动收口 0/1;
225
+ // 二次催办倍数 2–10。空串 = 清除保存值回退默认,与运行时效同口径。
226
+ {
227
+ const [idleMin, idleMax] = REVIEW_IDLE_MINUTES_RANGE
228
+ const key = REVIEW_IDLE_MINUTES_KEY
229
+ if (values[key] !== undefined && values[key] !== '') {
230
+ const num = Number(values[key])
231
+ if (!Number.isInteger(num) || num < idleMin || num > idleMax) {
232
+ throw badRequest(`${key} 必须是 ${idleMin}–${idleMax} 的整数分钟`)
233
+ }
234
+ values[key] = String(num)
235
+ }
236
+ }
237
+ if (values[REVIEW_AUTO_CLOSE_KEY] !== undefined && values[REVIEW_AUTO_CLOSE_KEY] !== '') {
238
+ if (!['0', '1'].includes(values[REVIEW_AUTO_CLOSE_KEY])) throw badRequest(`${REVIEW_AUTO_CLOSE_KEY} 必须是 0 或 1`)
239
+ }
240
+ {
241
+ const [escMin, escMax] = REVIEW_ESCALATE_RANGE
242
+ const key = REVIEW_ESCALATE_KEY
243
+ if (values[key] !== undefined && values[key] !== '') {
244
+ const num = Number(values[key])
245
+ if (!Number.isInteger(num) || num < escMin || num > escMax) {
246
+ throw badRequest(`${key} 必须是 ${escMin}–${escMax} 的整数`)
247
+ }
248
+ values[key] = String(num)
249
+ }
250
+ }
223
251
  // UI 语言(DSHBOTS-162):auto = 跟随 DSH 宿主(缺省),zh/en = 显式覆盖。
224
252
  // 非法输入 badRequest,不静默钳制(与运行时效同口径);外部写入的非法值由
225
253
  // effectiveUiLanguage 收敛回 'auto'。
@@ -1,7 +1,8 @@
1
1
  // src/services/hygiene.js —— 代码卫生域(DSHBOTS-172)
2
2
  // 单文件行数约定:项目设置 code_hygiene_limit_lines(NULL = 默认 800,0 = 关闭)。
3
3
  // 每轮运行结束(run-finish 钩子)扫描项目工作区内的文本源码文件,超过约定上限
4
- // 110% 即向项目群发一条【系统指令】系统消息(列出文件+行数+上限,要求总监安排
4
+ // 110% 即向项目群发一条系统告警消息(前缀按 locale:缺省 [SYSTEM ALERT],中文环境
5
+ // 【系统指令】,见 locale.js 的 systemAlertLabel;列出文件+行数+上限,要求总监安排
5
6
  // 拆分卡)。同一文件告警一次后,在其行数回落到判定线以内之前不重复告警。
6
7
  // 本文件只放方法体,方法挂到 TeamService 原型上(见 src/service.js 的 defineMethods),
7
8
  // 方法体内的 this 与其他域一致(this.store / this.config / this.logger)。
@@ -9,6 +10,7 @@
9
10
  import { readdirSync, readFileSync, statSync } from 'node:fs'
10
11
  import { extname, join } from 'node:path'
11
12
  import { jsonParse } from '../util.js'
13
+ import { messageLocale, systemAlertLabel } from './locale.js'
12
14
 
13
15
  // 约定默认上限(项目未设置时);0 = 关闭检查。
14
16
  export const CODE_HYGIENE_DEFAULT_LIMIT = 800
@@ -77,7 +79,7 @@ export function countTextLines(content) {
77
79
 
78
80
  // 遍历工作区收集白名单内文件的行数(相对路径 → 行数)。
79
81
  // 纯函数(只依赖入参),目录不可读/文件读失败逐项跳过不抛出。
80
- export function scanCodeHygieneFiles(dir, { exts, ignoredDirs = CODE_HYGIENE_IGNORED_DIRS, ignoredFiles = CODE_HYGIENE_IGNORED_FILES, maxFileBytes = CODE_HYGIENE_MAX_FILE_BYTES } = {}) {
82
+ export function scanCodeHygieneFiles(dir, { exts, ignoredDirs = CODE_HYGIENE_IGNORED_DIRS, ignoredFiles = CODE_HYGIENE_IGNORED_FILES, maxFileBytes = CODE_HYGIENE_MAX_FILE_BYTES } = {} ) {
81
83
  const files = []
82
84
  const walk = (current, prefix) => {
83
85
  let entries
@@ -137,8 +139,10 @@ export const hygieneMethods = {
137
139
  if (toAlert.length > 0) {
138
140
  const listed = toAlert.slice(0, CODE_HYGIENE_LIST_MAX)
139
141
  const more = toAlert.length - listed.length
142
+ // 前缀按 locale 落库(DSHBOTS-228):缺省英文 [SYSTEM ALERT],中文环境【系统指令】。
143
+ const alertPrefix = systemAlertLabel(messageLocale(this.config, key => this.store.setting(key), this.runtime?.ctx?.get?.('loader')))
140
144
  const body = [
141
- `【系统指令】代码卫生告警:${toAlert.length} 个文件超过单文件行数约定(约定上限 ${limit} 行,判定线 ${threshold} 行 = ${Math.round(CODE_HYGIENE_OVER_RATIO * 100)}%)。`,
145
+ `${alertPrefix}代码卫生告警:${toAlert.length} 个文件超过单文件行数约定(约定上限 ${limit} 行,判定线 ${threshold} 行 = ${Math.round(CODE_HYGIENE_OVER_RATIO * 100)}%)。`,
142
146
  ...listed.map(file => `- ${file.path}(${file.lines} 行)`),
143
147
  more > 0 ? `……等共 ${toAlert.length} 个超标文件` : '',
144
148
  '请项目总监安排拆分卡,将超标文件按职责拆分到约定上限以内。',
@@ -156,7 +160,7 @@ export const hygieneMethods = {
156
160
  }
157
161
  this.store.setSetting(settingKey, JSON.stringify(alerted))
158
162
  return { limit, threshold, scanned: files.length, over: over.length, alerted: toAlert.map(file => file.path), recovered }
159
- } catch (error) {
163
+ } catch (error ) {
160
164
  this.logger?.warn?.(`dsh-team: 代码卫生扫描失败(${project?.key ?? project?.id ?? 'unknown'}):${error?.message ?? error}`)
161
165
  return { error: String(error?.message ?? error) }
162
166
  }
@@ -9,6 +9,7 @@
9
9
  import { readFile } from 'node:fs/promises'
10
10
  import { homedir } from 'node:os'
11
11
  import { join, resolve } from 'node:path'
12
+ import { effectiveUiLanguage } from '../config.js'
12
13
 
13
14
  export const LOCALE_PLUGIN_ID = 'locale'
14
15
  export const LOCALE_PLUGIN_PACKAGE = '@deepseek-ai/dsh-client-locale'
@@ -111,3 +112,19 @@ export async function resolveUiLanguage({ loader = null, dshHome = null, profile
111
112
  if (explicit) return explicit
112
113
  return resolveDshUiLanguage({ loader, dshHome, profile })
113
114
  }
115
+
116
+ // ── 出站系统消息的系统告警前缀(DSHBOTS-228)─────────────────────────────────
117
+ // 用户拍板:前缀缺省英文 SYSTEM ALERT(注意拼写 ALERT),中文环境显示【系统指令】。
118
+ // zh* → 【系统指令】;其余(en/未知/未设定)→ [SYSTEM ALERT] (缺省英文)。
119
+ export function systemAlertLabel(locale) {
120
+ return clampLocaleId(locale) === 'zh' ? '【系统指令】' : '[SYSTEM ALERT] '
121
+ }
122
+
123
+ // 消息产生点的同步 locale 解析:run-finish 钩子与 scheduler tick 都在同步段发消息,
124
+ // 不能走 async resolveUiLanguage。显式 ui_language(env > 保存值 > config 缺省)优先;
125
+ // 'auto' 时 loader 直读 DSH 宿主活配置(同步);仍不可判定按缺省英文(en)。
126
+ export function messageLocale(config, getSetting = key => null, loader = null) {
127
+ const effective = effectiveUiLanguage(config, getSetting)
128
+ if (effective === 'auto') return clampLocaleId(localePreferenceFromLoader(loader)) ?? 'en'
129
+ return effective
130
+ }
@@ -209,7 +209,7 @@ export const memoryMethods = {
209
209
  sourceRefs: sourceRunId ? [sourceRunId] : [],
210
210
  })
211
211
  applied += 1
212
- } catch (writeError) {
212
+ } catch (writeError ) {
213
213
  this.logger.warn?.('dsh-team: 记忆审查写入失败:%s', writeError?.message ?? writeError)
214
214
  }
215
215
  }
@@ -432,4 +432,115 @@ export const memoryMethods = {
432
432
  actor: { type: 'bot', id: binding.bot_id },
433
433
  })
434
434
  },
435
+
436
+ // ── 总监记忆管理(DSHBOTS-239):list / 同名覆盖写 / 批量清理 ──
437
+ // 三入口共用 ownerContextFor 权威鉴权(仅项目总监,单聊/成员拒绝);
438
+ // 不改宿主 team_remember 语义,插件层独立封装。
439
+
440
+ // 把 scope 枚举解析到总监会话所在的具体作用域:bot=总监自己,project=会话项目,team=全团队。
441
+ resolveOwnerMemoryScope(ownerCtx, scope) {
442
+ const scopeType = ['bot', 'project', 'team'].includes(scope) ? scope : null
443
+ if (!scopeType) throw badRequest('记忆作用域无效')
444
+ const scopeId = scopeType === 'bot' ? ownerCtx.binding.bot_id : scopeType === 'project' ? ownerCtx.project.id : 'team'
445
+ return { scopeType, scopeId }
446
+ },
447
+
448
+ memoryListFromBot(sessionId, input = {}) {
449
+ const ownerCtx = this.ownerContextFor(sessionId)
450
+ const { scopeType, scopeId } = this.resolveOwnerMemoryScope(ownerCtx, input.scope ?? 'project')
451
+ const keyword = text(input.topic, 200).trim()
452
+ const limitN = Math.min(200, Math.max(1, Number(input.limit) || 50))
453
+ const like = `%${keyword}%`
454
+ const rows = this.store.all(
455
+ `SELECT * FROM memories
456
+ WHERE scope_type = ? AND scope_id = ? AND status = 'active'
457
+ ${keyword ? 'AND topic LIKE ?' : ''}
458
+ ORDER BY updated_at DESC LIMIT ?`,
459
+ scopeType, scopeId, ...(keyword ? [like] : []), limitN,
460
+ )
461
+ return rows.map(row => this.memoryView(row))
462
+ },
463
+
464
+ // 写入/同名覆盖:同 scope+topic 已有 active 记忆时原地更新(revision+1、事件留痕),
465
+ // 不再叠新条;无同名时走 createMemory 正常创建。
466
+ memoryWriteFromBot(sessionId, input) {
467
+ const ownerCtx = this.ownerContextFor(sessionId)
468
+ const { scopeType, scopeId } = this.resolveOwnerMemoryScope(ownerCtx, input.scope)
469
+ const actor = ownerCtx.actor
470
+ const topic = text(input.topic, 120)
471
+ if (!topic) throw badRequest('缺少记忆主题')
472
+ const existing = this.store.get(
473
+ "SELECT * FROM memories WHERE scope_type = ? AND scope_id = ? AND topic = ? AND status = 'active'",
474
+ scopeType, scopeId, topic,
475
+ )
476
+ if (!existing) {
477
+ const memory = this.createMemory({
478
+ scopeType,
479
+ scopeId,
480
+ topic,
481
+ content: input.content,
482
+ source: `session:${sessionId}`,
483
+ confidence: 0.9,
484
+ createdBy: `bot:${actor.id}`,
485
+ actor,
486
+ })
487
+ return { memory: this.memoryView(memory), overwritten: false }
488
+ }
489
+ const content = redactSecrets(text(input.content, 8000))
490
+ if (!content) throw badRequest('记忆内容不能为空')
491
+ const now = nowIso()
492
+ this.store.run(
493
+ 'UPDATE memories SET content = ?, source = ?, revision = revision + 1, updated_at = ? WHERE id = ?',
494
+ content, `session:${sessionId}`, now, existing.id,
495
+ )
496
+ this.store.run(
497
+ 'INSERT INTO memory_events(id, memory_id, action, actor_type, actor_id, before_text, after_text, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)',
498
+ id('mevt'), existing.id, 'updated', actor.type, actor.id, existing.content, content, now,
499
+ )
500
+ this.audit(actor, 'memory.overwrite', 'memory', existing.id, { scopeType, scopeId, topic })
501
+ this.writeMemoryMirror(existing.id)
502
+ return { memory: this.memoryView(this.store.get('SELECT * FROM memories WHERE id = ?', existing.id)), overwritten: true }
503
+ },
504
+
505
+ // 批量清理:按过期口径把 active 记忆终态化(archived,检索即不再回灌)。
506
+ // 口径两选一(可并用):task=已闭环卡(done/canceled)的过程记录主题,topics=点名主题。
507
+ // 逐条 memory_events 留痕 + 一笔 memory.cleanup 审计列出被清条目。
508
+ memoryCleanupFromBot(sessionId, input) {
509
+ const ownerCtx = this.ownerContextFor(sessionId)
510
+ const { project, actor } = ownerCtx
511
+ const { scopeType, scopeId } = this.resolveOwnerMemoryScope(ownerCtx, input.scope)
512
+ const topics = (Array.isArray(input.topics) ? input.topics : []).map(item => text(item, 120)).filter(Boolean)
513
+ let taskLabel = null
514
+ let taskTopics = []
515
+ if (input.task) {
516
+ const task = this.resolveBotTask(project, input.task)
517
+ if (!['done', 'canceled'].includes(task.status)) {
518
+ throw badRequest(`仅已闭环(done/canceled)任务的历史记录可清理,${project.key}-${task.number} 当前为 ${task.status}`)
519
+ }
520
+ taskLabel = `${project.key}-${task.number}`
521
+ // learnFromTask 的两类过程记录主题形态:任务 KEY-N(bot 域)/ KEY-N 交付记录(项目域)。
522
+ taskTopics = [`任务 ${taskLabel}`, `${taskLabel} 交付记录`]
523
+ }
524
+ const wanted = [...new Set([...topics, ...taskTopics])]
525
+ if (!wanted.length) throw badRequest('cleanup 需要 topics 或 task 至少一项')
526
+ const placeholders = wanted.map(() => '?').join(', ')
527
+ const rows = this.store.all(
528
+ `SELECT * FROM memories WHERE scope_type = ? AND scope_id = ? AND status = 'active' AND topic IN (${placeholders})`,
529
+ scopeType, scopeId, ...wanted,
530
+ )
531
+ const now = nowIso()
532
+ const cleaned = []
533
+ this.store.transaction(() => {
534
+ for (const row of rows) {
535
+ this.store.run("UPDATE memories SET status = 'archived', updated_at = ? WHERE id = ?", now, row.id)
536
+ this.store.run(
537
+ 'INSERT INTO memory_events(id, memory_id, action, actor_type, actor_id, before_text, after_text, created_at) VALUES (?, ?, ?, ?, ?, ?, NULL, ?)',
538
+ id('mevt'), row.id, 'archived', actor.type, actor.id, row.content, now,
539
+ )
540
+ cleaned.push({ id: row.id, topic: row.topic })
541
+ }
542
+ this.audit(actor, 'memory.cleanup', 'memory', `${scopeType}:${scopeId}`, { scope: scopeType, task: taskLabel, cleaned })
543
+ })
544
+ return { cleaned, archived: cleaned.length, missed: wanted.filter(topic => !cleaned.some(item => item.topic === topic)) }
545
+ },
435
546
  }
@@ -94,7 +94,7 @@ export function normalizeImageInputs(input) {
94
94
  export function toImageContentParts(images) {
95
95
  const list = Array.isArray(images) ? images : []
96
96
  return list.map(image => {
97
- const part = { type: 'image', mediaType: image.mediaType, data: image.data }
97
+ const part = { type: 'image', mediaType: image.mediaType, data: image.data }
98
98
  if (image.name) part.name = image.name
99
99
  return part
100
100
  })
@@ -235,7 +235,7 @@ export async function convertImagesForUpload(images, thresholdBytes, logger = nu
235
235
  try {
236
236
  const converted = await convertPngToJpeg(sharp, image.data, logger)
237
237
  out.push(converted ? { ...image, ...converted } : image)
238
- } catch (error) {
238
+ } catch (error ) {
239
239
  // 转码失败回退原图,不阻塞发送。
240
240
  logger?.warn?.('dsh-team: PNG 转 JPEG 失败,回退原图:%s', error?.message ?? error)
241
241
  out.push(image)
@@ -245,7 +245,7 @@ export async function convertImagesForUpload(images, thresholdBytes, logger = nu
245
245
  }
246
246
 
247
247
  // 外部输入 → 校验 + 转码,落库前的完整归一入口(sendMessage / sendSoloMessage 用)。
248
- export async function prepareImagesForStorage(input, thresholdBytes, logger = null, sharpFactory) {
248
+ export async function prepareImagesForStorage(input, thresholdBytes, logger = null, sharpFactory ) {
249
249
  const images = normalizeImageInputs(input)
250
250
  return convertImagesForUpload(images, thresholdBytes, logger, sharpFactory)
251
251
  }
@@ -0,0 +1,99 @@
1
+ // 通知通道域(DSHBOTS-243):成员通知与任务提醒。
2
+ // 投递面与留痕分离——宿主会话通道(runtime.steer,即时可达)负责投递,插件 messages
3
+ // 落库(进群聊流 / 任务线程)为准绳;任一通道失败只 warn,不阻塞另一通道。
4
+ // 宿主 send_message 工具是 Agent Team 作用域的(花名册按根会话隔离,每个项目 bot
5
+ // 会话都是自己的 Team Lead),寻址不到另一个项目 bot 的会话;服务层可达的宿主原生
6
+ // 投递通道是 sessionController.prompt(runtime.steer 的封装),成员通知的即时投递
7
+ // 走它,句柄不可达或目标无绑定会话时降级为群聊流(insertMessage + chat_run)。
8
+
9
+ import { badRequest, notFound } from '../errors.js'
10
+ import { text } from '../util.js'
11
+
12
+ export const notifyMethods = {
13
+ // 工具入口:target=member 通知本项目另一成员;target=task 提醒本项目执行中任务。
14
+ // 鉴权:调用者必须是本项目成员(memberContextFor),目标成员/任务都锁在本项目内,
15
+ // 跨项目 ref 一律解析不到(notFound),不泄露他项目是否存在同名目标。
16
+ async notifyFromBot(sessionId, input) {
17
+ const target = String(input?.target ?? '')
18
+ if (target !== 'member' && target !== 'task') throw badRequest('target 只能是 member 或 task')
19
+ const body = text(input?.message, 5_000)
20
+ if (!body) throw badRequest('通知内容不能为空')
21
+ const { project, bot } = this.memberContextFor(sessionId)
22
+ return target === 'member'
23
+ ? this.notifyMemberFromBot({ project, from: bot, memberName: input?.member, body })
24
+ : this.notifyTaskFromBot({ project, from: bot, ref: input?.task, body })
25
+ },
26
+
27
+ // 成员通知:宿主通道(目标项目会话 steer)+ 插件落库双写。
28
+ // 留痕恒定先落(来源 bot、@目标、进群聊流);投递失败只 warn,转群聊流兜底。
29
+ async notifyMemberFromBot({ project, from, memberName, body }) {
30
+ const name = String(memberName ?? '').trim()
31
+ const target = this.membersOf(project.id)
32
+ .find(member => member.name.toLowerCase() === name.toLowerCase())
33
+ if (!target) throw notFound(`项目 ${project.name} 里没有叫 ${memberName} 的成员 Bot`)
34
+ if (target.id === from.id) throw badRequest('不能给自己发通知')
35
+ const notice = `【通知】${from.name}:${body}`
36
+ const messageId = this.insertMessage({
37
+ projectId: project.id,
38
+ senderType: 'bot',
39
+ senderId: from.id,
40
+ body: notice,
41
+ mentions: [target.id],
42
+ })
43
+ const binding = this.store.get(
44
+ "SELECT * FROM session_bindings WHERE bot_id = ? AND project_id = ? AND kind = 'project' AND alias = 0",
45
+ target.id,
46
+ project.id,
47
+ )
48
+ if (binding && typeof this.runtime?.steer === 'function') {
49
+ try {
50
+ await this.runtime.steer(binding.session_id, notice)
51
+ return `已通知 ${target.name}(宿主通道投递${messageId ? `,群聊留痕 ${messageId.slice(-6)}` : ''})。`
52
+ } catch (error ) {
53
+ this.logger.warn?.('dsh-team: 成员通知宿主通道投递失败 %s: %s', target.name, error?.message ?? error)
54
+ }
55
+ }
56
+ // 降级:群聊流可达(成员会话经 chat_run 监听群消息)。
57
+ if (messageId) {
58
+ this.enqueueOutbox({
59
+ kind: 'chat_run',
60
+ payload: { projectId: project.id, botId: target.id, messageId },
61
+ projectId: project.id,
62
+ sourceId: messageId,
63
+ idempotencyKey: `chat:${messageId}:${target.id}`,
64
+ })
65
+ // enqueueOutbox 同事务落库后立即 applyOutboxRow(chat_run → enqueueChatRun),无需再触发 tick。
66
+ }
67
+ return `已通知 ${target.name}(群聊流投递${messageId ? `,留痕 ${messageId.slice(-6)}` : ''})。`
68
+ },
69
+
70
+ // 任务提醒:留痕落任务线程(owner 验收面板可见);有活跃运行(running + 会话)
71
+ // 再经宿主通道 steer 注入(复用 D-232 改卡通知第二段机制)。
72
+ async notifyTaskFromBot({ project, from, ref, body }) {
73
+ const task = this.resolveBotTask(project, ref)
74
+ const identifier = `${project.key}-${task.number}`
75
+ const notice = `【任务提醒】${from.name}:${body}`
76
+ const messageId = this.insertMessage({
77
+ projectId: project.id,
78
+ senderType: 'bot',
79
+ senderId: from.id,
80
+ body: notice,
81
+ taskId: task.id,
82
+ mentions: task.assignee_bot_id ? [task.assignee_bot_id] : [],
83
+ })
84
+ const run = this.store.get(
85
+ "SELECT id, session_id FROM runs WHERE task_id = ? AND status = 'running' AND session_id IS NOT NULL ORDER BY started_at DESC LIMIT 1",
86
+ task.id,
87
+ )
88
+ if (run && typeof this.runtime?.steer === 'function') {
89
+ try {
90
+ await this.runtime.steer(run.session_id, `Task reminder from ${from.name}: ${body}`)
91
+ this.insertRunEvent(run.id, 'notified', `任务提醒已注入(${identifier})`)
92
+ return `已向任务 ${identifier} 的活跃运行注入提醒(留痕 ${messageId?.slice(-6) ?? '无'})。`
93
+ } catch (error ) {
94
+ this.logger.warn?.('dsh-team: 任务提醒注入失败 %s: %s', identifier, error?.message ?? error)
95
+ }
96
+ }
97
+ return `已向任务 ${identifier} 落线程提醒(无活跃运行可注入;留痕 ${messageId?.slice(-6) ?? '无'})。`
98
+ },
99
+ }
@@ -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(