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
@@ -92,7 +92,7 @@ export const chatMethods = {
92
92
  data: row.data,
93
93
  }
94
94
  },
95
- async sendMessage(projectId, bodyInput, actor = this.actor(), replyTo = null, imagesInput = []) {
95
+ async sendMessage(projectId, bodyInput, actor = this.actor(), replyTo = null, imagesInput = [], { origin = null } = {}) {
96
96
  const project = this.projectRow(projectId)
97
97
  if (project.status !== 'active') throw conflict('项目已归档')
98
98
  const body = text(bodyInput, 20_000)
@@ -167,7 +167,8 @@ export const chatMethods = {
167
167
  for (const bot of targets) {
168
168
  this.enqueueOutbox({
169
169
  kind: 'chat_run',
170
- payload: { projectId: project.id, botId: bot.id, messageId },
170
+ // origin('wechat'):标记消息来自微信直达(DSHBOTS-208),运行结束把 bot 回复推回微信。
171
+ payload: { projectId: project.id, botId: bot.id, messageId, origin },
171
172
  projectId: project.id,
172
173
  sourceId: messageId,
173
174
  idempotencyKey: `chat:${messageId}:${bot.id}`,
@@ -213,7 +214,9 @@ export const chatMethods = {
213
214
  },
214
215
 
215
216
  // ===== 单聊:项目外与单个 Bot 的一对一会话,工作目录 _the_bots/<solo_dir> =====
216
- insertSoloMessage({ botId, senderType, senderId, body, runId = null, images = [], createdAt = nowIso() }) {
217
+ // kind/questionId/approvalId 是卡片锚点(DSHBOTS-218):单聊里发起的提问/审批在会话流里
218
+ // 落一条 system 卡片消息,卡片状态渲染时查 questions/approvals 表,与群聊同口径。
219
+ insertSoloMessage({ botId, senderType, senderId, body, runId = null, images = [], createdAt = nowIso(), kind = 'text', questionId = null, approvalId = null }) {
217
220
  const messageId = id('msg')
218
221
  // 单聊 bot 回复同样剥残片:剥完整条为空就不落库。用户消息不动。
219
222
  const cleanedBody = senderType === 'bot' ? stripLeakedToolMarkup(body) : body
@@ -221,9 +224,9 @@ export const chatMethods = {
221
224
  // 单聊同样过密钥掩码:单聊正文会进模型上下文,明文密钥不该落库。
222
225
  const maskedBody = this.maskSecretValues(cleanedBody)
223
226
  this.store.run(
224
- `INSERT INTO solo_messages(id, bot_id, sender_type, sender_id, body, run_id, created_at)
225
- VALUES (?, ?, ?, ?, ?, ?, ?)`,
226
- messageId, botId, senderType, senderId, maskedBody, runId, createdAt,
227
+ `INSERT INTO solo_messages(id, bot_id, sender_type, sender_id, body, run_id, kind, question_id, approval_id, created_at)
228
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
229
+ messageId, botId, senderType, senderId, maskedBody, runId, kind, questionId, approvalId, createdAt,
227
230
  )
228
231
  if (images.length > 0) {
229
232
  insertMessageImages(this.store, { messageId, soloMessageId: messageId, images, botId })
@@ -250,7 +253,10 @@ export const chatMethods = {
250
253
  this.audit(actor, 'chat.solo_clear', 'bot', bot.id, { cleared: count })
251
254
  return count
252
255
  },
253
- async sendSoloMessage(botId, bodyInput, actor = this.actor(), imagesInput = []) {
256
+ // options.origin(DSHBOTS-258):'wechat' 表示消息来自微信通道(项目外 director 专属
257
+ // 工作区),随 solo_chat_run 载荷传递,scheduler 据此把 solo 运行打成 trigger_type='wechat',
258
+ // 运行收尾的回复才会推回微信;普通 UI 单聊不传,保持 'mention' 不推。
259
+ async sendSoloMessage(botId, bodyInput, actor = this.actor(), imagesInput = [], options = {}) {
254
260
  const bot = this.botRow(botId)
255
261
  if (bot.status !== 'active') throw conflict('Bot 已归档或暂停')
256
262
  const body = text(bodyInput, 20_000)
@@ -296,7 +302,7 @@ export const chatMethods = {
296
302
  })
297
303
  this.enqueueOutbox({
298
304
  kind: 'solo_chat_run',
299
- payload: { botId: bot.id, messageId },
305
+ payload: { botId: bot.id, messageId, ...(options.origin ? { origin: options.origin } : {}) },
300
306
  projectId: null,
301
307
  sourceId: messageId,
302
308
  idempotencyKey: `solo_chat:${messageId}`,
@@ -391,7 +397,7 @@ export const chatMethods = {
391
397
  // 定位聊天消息里 markdown 图片引用的工作区文件:只认项目工作目录或单聊 Bot
392
398
  // 工作区内的白名单图片,路径解析 + realpath 双重防穿越(与 artifactFile 同口径)。
393
399
  // SVG 可执行脚本,永不放行;尺寸上限由 HTTP 层把关(MAX_CHAT_IMAGE_BYTES)。
394
- chatFile({ projectId, soloBotId, path } = {}) {
400
+ chatFile({ projectId, soloBotId, path } = {} ) {
395
401
  const CHAT_IMAGE_TYPES = {
396
402
  '.png': 'image/png',
397
403
  '.jpg': 'image/jpeg',
@@ -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,169 @@
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
+ // ── 防循环三上限(DSHBOTS-267,配置默认值写死常量,KISS)──────────────────
13
+ // 真实事故背书:伙伴回执淹没主对话、委派续跑近百轮重发已推翻目标。
14
+ // ① 单 run 内经 notify/chat 产生的伙伴提醒(按去重目标计条数)上限:超出静默丢弃并记日志;
15
+ // ② 同类提醒事件(同 run + 同目标 bot)每日次数上限:超出静默丢弃并记日志。
16
+ // 每条放行的提醒在 run_events 记 type='partner_notice',message 存 partner_notice:<目标bot>,
17
+ // 两条上限都从这张事件流计数,不新建并行状态表。
18
+ export const RUN_PARTNER_NOTICE_CAP = 3
19
+ export const PARTNER_NOTICE_DAILY_CAP = 5
20
+
21
+ export const notifyMethods = {
22
+ // 伙伴提醒配额闸(DSHBOTS-267):放行返回 true;超限静默丢弃(warn 留痕)返回 false。
23
+ // run 归属不到(发起方无活跃运行)时不设限——空闲/人工会话的零星通知无循环风险。
24
+ allowPartnerNotice(runId, targetId) {
25
+ if (!runId || !targetId) return true
26
+ const distinctTargets = this.store.get(
27
+ "SELECT COUNT(DISTINCT message) AS n FROM run_events WHERE run_id = ? AND type = 'partner_notice'",
28
+ runId,
29
+ ).n
30
+ if (distinctTargets >= RUN_PARTNER_NOTICE_CAP) {
31
+ this.logger.warn?.('dsh-team: 伙伴提醒超单 run 上限(%s 个目标),静默丢弃:run=%s target=%s', RUN_PARTNER_NOTICE_CAP, runId, targetId)
32
+ return false
33
+ }
34
+ const todayCount = this.store.get(
35
+ "SELECT COUNT(*) AS n FROM run_events WHERE run_id = ? AND type = 'partner_notice' AND message = ? AND date(created_at) = date('now')",
36
+ runId, `partner_notice:${targetId}`,
37
+ ).n
38
+ if (todayCount >= PARTNER_NOTICE_DAILY_CAP) {
39
+ this.logger.warn?.('dsh-team: 伙伴提醒超每日上限(%s 次/日),静默丢弃:run=%s target=%s', PARTNER_NOTICE_DAILY_CAP, runId, targetId)
40
+ return false
41
+ }
42
+ return true
43
+ },
44
+
45
+ // 记一条放行的伙伴提醒事件(配额闸通过后调用;chat 唤醒路径共用同一事件流)。
46
+ recordPartnerNotice(runId, targetId) {
47
+ if (!runId || !targetId) return
48
+ this.insertRunEvent(runId, 'partner_notice', `partner_notice:${targetId}`)
49
+ },
50
+
51
+ // 工具入口:target=member 通知本项目另一成员;target=task 提醒本项目执行中任务。
52
+ // 鉴权:调用者必须是本项目成员(memberContextFor),目标成员/任务都锁在本项目内,
53
+ // 跨项目 ref 一律解析不到(notFound),不泄露他项目是否存在同名目标。
54
+ async notifyFromBot(sessionId, input) {
55
+ const target = String(input?.target ?? '')
56
+ if (target !== 'member' && target !== 'task') throw badRequest('target 只能是 member 或 task')
57
+ const body = text(input?.message, 5_000)
58
+ if (!body) throw badRequest('通知内容不能为空')
59
+ const { project, bot } = this.memberContextFor(sessionId)
60
+ return target === 'member'
61
+ ? this.notifyMemberFromBot({ project, from: bot, memberName: input?.member, body })
62
+ : this.notifyTaskFromBot({ project, from: bot, ref: input?.task, body })
63
+ },
64
+
65
+ // 成员通知:宿主通道(目标项目会话 steer)+ 插件落库双写。
66
+ // 留痕恒定先落(来源 bot、@目标、进群聊流);投递失败只 warn,转群聊流兜底。
67
+ async notifyMemberFromBot({ project, from, memberName, body }) {
68
+ const name = String(memberName ?? '').trim()
69
+ const target = this.membersOf(project.id)
70
+ .find(member => member.name.toLowerCase() === name.toLowerCase())
71
+ if (!target) throw notFound(`项目 ${project.name} 里没有叫 ${memberName} 的成员 Bot`)
72
+ if (target.id === from.id) throw badRequest('不能给自己发通知')
73
+ // 暂停/不可用目标不投递(DSHBOTS-262):通知即唤醒信号,暂停中先恢复再通知。
74
+ if (target.status === 'paused') throw badRequest(`Bot ${target.name} 已暂停,先恢复再通知`)
75
+ if (target.status !== 'active') throw badRequest(`Bot ${target.name} 当前不可用(${target.status})`)
76
+ // DSHBOTS-267 防循环上限:归属发起方当前活跃运行,配额闸不通过即静默丢弃(不落留痕不投递)。
77
+ const activeRun = this.store.get(
78
+ "SELECT id FROM runs WHERE bot_id = ? AND project_id = ? AND status = 'running' ORDER BY started_at DESC LIMIT 1",
79
+ from.id, project.id,
80
+ )
81
+ if (!this.allowPartnerNotice(activeRun?.id, target.id)) {
82
+ return `伙伴提醒已达防循环上限,本次已静默丢弃(详见运行日志)。`
83
+ }
84
+ this.recordPartnerNotice(activeRun?.id, target.id)
85
+ const notice = `【通知】${from.name}:${body}`
86
+ const messageId = this.insertMessage({
87
+ projectId: project.id,
88
+ senderType: 'bot',
89
+ senderId: from.id,
90
+ body: notice,
91
+ mentions: [target.id],
92
+ })
93
+ const binding = this.store.get(
94
+ "SELECT * FROM session_bindings WHERE bot_id = ? AND project_id = ? AND kind = 'project' AND alias = 0",
95
+ target.id,
96
+ project.id,
97
+ )
98
+ if (binding && typeof this.runtime?.steer === 'function') {
99
+ try {
100
+ await this.runtime.steer(binding.session_id, notice)
101
+ return `已通知 ${target.name}(宿主通道投递${messageId ? `,群聊留痕 ${messageId.slice(-6)}` : ''})。`
102
+ } catch (error ) {
103
+ this.logger.warn?.('dsh-team: 成员通知宿主通道投递失败 %s: %s', target.name, error?.message ?? error)
104
+ }
105
+ }
106
+ // 降级:群聊流可达(成员会话经 chat_run 监听群消息)。
107
+ if (messageId) {
108
+ this.enqueueOutbox({
109
+ kind: 'chat_run',
110
+ payload: { projectId: project.id, botId: target.id, messageId },
111
+ projectId: project.id,
112
+ sourceId: messageId,
113
+ idempotencyKey: `chat:${messageId}:${target.id}`,
114
+ })
115
+ // enqueueOutbox 同事务落库后立即 applyOutboxRow(chat_run → enqueueChatRun),无需再触发 tick。
116
+ }
117
+ return `已通知 ${target.name}(群聊流投递${messageId ? `,留痕 ${messageId.slice(-6)}` : ''})。`
118
+ },
119
+
120
+ // 任务提醒:留痕落任务线程(owner 验收面板可见);有活跃运行(running + 会话)
121
+ // 再经宿主通道 steer 注入(复用 D-232 改卡通知第二段机制)。
122
+ async notifyTaskFromBot({ project, from, ref, body }) {
123
+ const task = this.resolveBotTask(project, ref)
124
+ const identifier = `${project.key}-${task.number}`
125
+ // 负责人暂停/不可用时提醒不投递(DSHBOTS-262):提醒即唤醒信号,暂停中先恢复再提醒。
126
+ if (task.assignee_bot_id) {
127
+ const assignee = this.store.get('SELECT name, status FROM bots WHERE id = ?', task.assignee_bot_id)
128
+ if (assignee?.status === 'paused') throw badRequest(`任务 ${identifier} 负责人 ${assignee.name} 已暂停,先恢复再提醒`)
129
+ if (!assignee || assignee.status !== 'active') throw badRequest(`任务 ${identifier} 负责人当前不可用`)
130
+ }
131
+ // DSHBOTS-267 单跟进者在途幂等:每张任务同时只允许一个跟进提醒在途。
132
+ // 在途判定=最近一条任务提醒落库后,该任务没有启动过新运行(提醒尚未被任何运行消费);
133
+ // 重复提醒静默吸收(不落新留痕、不注入、不计新),warn 留痕。
134
+ const lastNotice = this.store.get(
135
+ "SELECT created_at FROM messages WHERE task_id = ? AND sender_type = 'bot' AND body LIKE '【任务提醒】%' ORDER BY created_at DESC, rowid DESC LIMIT 1",
136
+ task.id,
137
+ )
138
+ if (lastNotice && !this.store.get(
139
+ 'SELECT id FROM runs WHERE task_id = ? AND started_at > ? LIMIT 1',
140
+ task.id, lastNotice.created_at,
141
+ )) {
142
+ this.logger.warn?.('dsh-team: 任务 %s 已有在途跟进提醒,重复提醒静默吸收', identifier)
143
+ return `任务 ${identifier} 已有在途跟进提醒,本次重复未投递(幂等去重,不计数)。`
144
+ }
145
+ const notice = `【任务提醒】${from.name}:${body}`
146
+ const messageId = this.insertMessage({
147
+ projectId: project.id,
148
+ senderType: 'bot',
149
+ senderId: from.id,
150
+ body: notice,
151
+ taskId: task.id,
152
+ mentions: task.assignee_bot_id ? [task.assignee_bot_id] : [],
153
+ })
154
+ const run = this.store.get(
155
+ "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",
156
+ task.id,
157
+ )
158
+ if (run && typeof this.runtime?.steer === 'function') {
159
+ try {
160
+ await this.runtime.steer(run.session_id, `Task reminder from ${from.name}: ${body}`)
161
+ this.insertRunEvent(run.id, 'notified', `任务提醒已注入(${identifier})`)
162
+ return `已向任务 ${identifier} 的活跃运行注入提醒(留痕 ${messageId?.slice(-6) ?? '无'})。`
163
+ } catch (error ) {
164
+ this.logger.warn?.('dsh-team: 任务提醒注入失败 %s: %s', identifier, error?.message ?? error)
165
+ }
166
+ }
167
+ return `已向任务 ${identifier} 落线程提醒(无活跃运行可注入;留痕 ${messageId?.slice(-6) ?? '无'})。`
168
+ },
169
+ }