dsh-team-bots 0.3.12 → 0.3.64

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 (74) hide show
  1. package/NOTICE +3 -4
  2. package/README.md +2 -2
  3. package/docs/README.zh.md +2 -2
  4. package/docs/assets/global-config.png +0 -0
  5. package/docs/assets/global-config.zh.png +0 -0
  6. package/docs/assets/tasks.png +0 -0
  7. package/docs/assets/tasks.zh.png +0 -0
  8. package/docs/assets/usage.png +0 -0
  9. package/docs/assets/usage.zh.png +0 -0
  10. package/package.json +8 -2
  11. package/src/api.js +10 -1
  12. package/src/config.js +180 -2
  13. package/src/db-migrations.js +53 -4
  14. package/src/db.js +28 -3
  15. package/src/http.js +20 -1
  16. package/src/runtime.js +16 -1
  17. package/src/seed-bots.js +4 -0
  18. package/src/service.js +21 -2
  19. package/src/services/approvals.js +276 -8
  20. package/src/services/core.js +31 -2
  21. package/src/services/memory.js +24 -8
  22. package/src/services/projects.js +12 -1
  23. package/src/services/run-finish.js +11 -0
  24. package/src/services/runtime/session.js +87 -25
  25. package/src/services/scheduler.js +20 -0
  26. package/src/services/system.js +162 -10
  27. package/src/services/task-review.js +90 -55
  28. package/src/services/tasks.js +5 -2
  29. package/ui/app.js +7 -10
  30. package/ui/i18n/en/chat.js +2 -0
  31. package/ui/i18n/en/common.js +10 -0
  32. package/ui/i18n/en/settings.js +75 -1
  33. package/ui/i18n/en/tasks.js +3 -0
  34. package/ui/i18n/zh/chat.js +2 -0
  35. package/ui/i18n/zh/common.js +10 -0
  36. package/ui/i18n/zh/settings.js +75 -1
  37. package/ui/i18n/zh/tasks.js +3 -0
  38. package/ui/modules/api.js +9 -1
  39. package/ui/modules/cards.js +6 -3
  40. package/ui/modules/chat.js +1 -1
  41. package/ui/modules/composer.js +6 -1
  42. package/ui/modules/events-board.js +48 -0
  43. package/ui/modules/events-misc.js +43 -0
  44. package/ui/modules/events-submit.js +20 -0
  45. package/ui/modules/form-validation.js +204 -0
  46. package/ui/modules/global-pages.js +8 -5
  47. package/ui/modules/modal-forms.js +1 -1
  48. package/ui/modules/modal-layer.js +4 -1
  49. package/ui/modules/page-shell.js +10 -7
  50. package/ui/modules/permissions.js +99 -0
  51. package/ui/modules/settings.js +103 -21
  52. package/ui/modules/state.js +10 -0
  53. package/ui/modules/task-menu.js +147 -0
  54. package/ui/modules/tasks.js +9 -8
  55. package/ui/modules/util.js +43 -6
  56. package/ui/styles/a11y.css +13 -0
  57. package/ui/styles/base.css +57 -11
  58. package/ui/styles/buttons.css +46 -6
  59. package/ui/styles/cards.css +90 -0
  60. package/ui/styles/chat.css +23 -2
  61. package/ui/styles/global-config.css +7 -4
  62. package/ui/styles/modal.css +28 -0
  63. package/ui/styles/settings.css +23 -1
  64. package/ui/styles/tasks.css +51 -1
  65. package/ui/styles/toast.css +18 -11
  66. package/ui/styles/usage.css +2 -0
  67. package/ui/styles/wide.css +5 -0
  68. package/docs/assets/channel-redesign.png +0 -0
  69. package/docs/assets/global-config-dark.png +0 -0
  70. package/docs/assets/global-config-light.png +0 -0
  71. package/docs/assets/global-config-light.zh.png +0 -0
  72. package/docs/assets/global-config-redesign.png +0 -0
  73. package/docs/assets/secrets-redesign.png +0 -0
  74. package/docs/assets/usage-redesign-global.png +0 -0
package/src/runtime.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { defineMethods } from './services/mixin.js'
2
+ import { applyRuntimeSettingOverrides } from './config.js'
2
3
  import { promptMethods } from './services/runtime/prompt.js'
3
4
  import { sessionMethods } from './services/runtime/session.js'
4
5
  import { trajectoryMethods } from './services/runtime/trajectory.js'
@@ -7,7 +8,21 @@ import { lifecycleMethods } from './services/runtime/lifecycle.js'
7
8
  export class DshRuntime {
8
9
  constructor({ ctx, config, store, logger = console , mask = null }) {
9
10
  this.ctx = ctx
10
- this.config = config
11
+ // config 存活覆盖视图(与 TeamService 同款):workerPreset/routerPreset 等
12
+ // 运行参数经全局设置改值后,下一次会话创建即用新值,无需重启。
13
+ this.baseConfig = config
14
+ this.configCache = null
15
+ this.configCacheRev = -1
16
+ Object.defineProperty(this, 'config', {
17
+ get() {
18
+ const rev = Number(this.store?.setting?.('settings_revision', '0')) || 0
19
+ if (this.configCache && this.configCacheRev === rev) return this.configCache
20
+ this.configCache = applyRuntimeSettingOverrides(this.baseConfig, key => this.store?.setting(key))
21
+ this.configCacheRev = rev
22
+ return this.configCache
23
+ },
24
+ configurable: true,
25
+ })
11
26
  this.store = store
12
27
  this.logger = logger
13
28
  // 密钥掩码钩子:service 层注入,轨迹等落库内容在写入前先脱敏。
package/src/seed-bots.js CHANGED
@@ -1,4 +1,8 @@
1
1
  // 默认出场的总监与六个通用团队伙伴。
2
+ // 种子 reviewer 的产品默认(DSHBOTS-365):不显式指定成员的新群自动带入,验收核验
3
+ // 优先由它承接;识别只认这个固定名——用户改名或移除即失效,核验回落总监兜底。
4
+ export const REVIEWER_BOT_NAME = 'reviewer'
5
+
2
6
  export const SEED_OWNER = {
3
7
  name: 'director',
4
8
  role: '总监',
package/src/service.js CHANGED
@@ -3,7 +3,7 @@ import { execFileSync, spawn } from 'node:child_process'
3
3
  import { createRequire } from 'node:module'
4
4
  import { dirname, extname, join, resolve, sep } from 'node:path'
5
5
  import { homedir } from 'node:os'
6
- import { effectiveRunLimits, RUN_LIMIT_RANGES, RUN_TIMEOUT_KEY, STALL_WATCHDOG_KEY } from './config.js'
6
+ import { effectiveRunLimits, RUN_LIMIT_RANGES, RUN_TIMEOUT_KEY, STALL_WATCHDOG_KEY, applyRuntimeSettingOverrides } from './config.js'
7
7
  import { AppError, badRequest, conflict, forbidden, hotUpgradeUnsupported, notFound } from './errors.js'
8
8
  import { assertInside, botWorkspaceDir, botsHome, ensureDirResilient, ensureExternalDir, ensureProjectWorkspace, ensureSkillRoot, projectDir, SLUG_MAX } from './paths.js'
9
9
  import { runUsageTotals, usageSnapshot } from './usage.js'
@@ -54,7 +54,22 @@ export { FILE_POLICIES, FILE_POLICY_LABELS } from './services/file-policy.js'
54
54
  export class TeamService {
55
55
  constructor({ store, config, logger = console }) {
56
56
  this.store = store
57
- this.config = config
57
+ // config 是存活覆盖视图(全局设置「运行参数」卡):settings 表保存值在 env 未
58
+ // 显式时覆盖启动默认,所有 this.config.* 读点即时生效,无需改各消费点。
59
+ // 按 settings_revision 缓存:保存一次才重算,调度热路径零开销。
60
+ this.baseConfig = config
61
+ this.configCache = null
62
+ this.configCacheRev = -1
63
+ Object.defineProperty(this, 'config', {
64
+ get() {
65
+ const rev = Number(this.store?.setting?.('settings_revision', '0')) || 0
66
+ if (this.configCache && this.configCacheRev === rev) return this.configCache
67
+ this.configCache = applyRuntimeSettingOverrides(this.baseConfig, key => this.store?.setting(key))
68
+ this.configCacheRev = rev
69
+ return this.configCache
70
+ },
71
+ configurable: true,
72
+ })
58
73
  this.logger = logger
59
74
  this.runtime = null
60
75
  this.localUserId = 'user_local'
@@ -69,6 +84,10 @@ export class TeamService {
69
84
  // 同一指纹跨运行只点名一次,重复只记 run_event,不重复插群消息。
70
85
  this.readAuditAlerted = new Map()
71
86
  this.lastMaintenanceAt = 0
87
+ // 最近一次全量调度拍的时间戳(空载门 tickIdleGate 的基准;0 = 首拍必全量)。
88
+ this.lastFullTickAt = 0
89
+ // state 轮询版本短路缓存(system.state):单槽存最近一次组装的 key/版本/时间。
90
+ this.stateCache = null
72
91
  this.wechat = null
73
92
  // GitHub 触发源的 gh 执行钩子(B4-②/DSHBOTS-335):生产用 spawnSync('gh', ...),
74
93
  // 测试注入桩替换;未设置时走真实 gh CLI。
@@ -2,8 +2,14 @@
2
2
  // 认领 session_bindings 命中的 bot 会话:绑定到项目的走群聊卡片;绑定为单聊(kind='solo'、
3
3
  // project_id 为空)的走单聊卡片(DSHBOTS-218);其余 next() 透传(人类会话审批继续走 Web UI)。
4
4
  // 决策权仅用户(type=user)持有,bot 一律 forbidden 不能自批;pending 之外拒绝重复应答,动作写审计。
5
+ // DSHBOTS-365 免审白名单:命中规则的提权请求不落待办卡,插件在认领入口即时替 owner 应答
6
+ // allowed-once;approvals 行照落(status='allowed'、decided_by='auto:rule:<id>')+ 审计事件
7
+ // approval.auto_allow,免审不免留痕。规则存 settings 'approval_auto_rules'(JSON 数组,仿
8
+ // prompt_overrides 独立编辑面先例,不进 settingsView 单值键域),仅 type=user 可写。
5
9
  // 注意:本域自管迁移(db.js 已贴 800 行上限,一行不加),手法与 db.js 的 addColumn/recordMigration 一致。
6
10
  import { badRequest, conflict, forbidden, notFound } from '../errors.js'
11
+ import { homedir, tmpdir } from 'node:os'
12
+ import { join } from 'node:path'
7
13
  import { id, nowIso } from '../util.js'
8
14
  import { effectiveApprovalTimeoutMs } from '../config.js'
9
15
  import { botInActiveProject } from './questions.js'
@@ -70,6 +76,15 @@ export function ensureApprovalSchema(store) {
70
76
  store.run(
71
77
  "UPDATE approvals SET status = 'timeout' WHERE status = 'pending'",
72
78
  )
79
+ // 出厂预置默认免审规则(DSHBOTS-365 增量):仅键未初始化(null)时播种一次;非-null
80
+ // 一律不动——'[]' 是 owner 显式清空,永不回播;重复执行幂等,不做回填迁移。
81
+ if (store.setting(APPROVAL_RULES_SETTING) === null) {
82
+ store.setSetting(APPROVAL_RULES_SETTING, JSON.stringify(DEFAULT_APPROVAL_AUTO_RULES))
83
+ }
84
+ // 存量预置行迁移(口径改 glob):仍是出厂原样的预置行替换为三条关键词 glob;owner 自建或
85
+ // 改过的行不动,显式清空([])不回播。迁移后预置行都带通配符,重复执行不再命中。
86
+ const migrated = migrateApprovalPresetRules(store.setting(APPROVAL_RULES_SETTING))
87
+ if (migrated) store.setSetting(APPROVAL_RULES_SETTING, migrated)
73
88
  }
74
89
 
75
90
  // 目标提取(纯函数):按参数形状判别,不按工具名——宿主工具族会扩展,形状更稳。
@@ -90,6 +105,168 @@ export function toolTargetOf(arguments_) {
90
105
  // pre-execute 目标缓存上限:只记最近若干次调用的目标,防长会话里无界增长。
91
106
  const APPROVAL_TARGET_CACHE_LIMIT = 200
92
107
 
108
+ // ── 免审规则(DSHBOTS-365)──────────────────────────────────────────────────
109
+ // 结构化规则列表:主维度 path_prefix(工作区外目录前缀)/ command(命令首行前缀),
110
+ // 辅维度 bot_id / tool_name / sandbox(目标沙箱档;danger-full-access 可配、默认规则集为空
111
+ // 自然不含)。存储仿 prompt_overrides:settings 键 'approval_auto_rules' 存 JSON 数组,
112
+ // 独立编辑面(approvalRulesView / updateApprovalRules),不进 settingsView 单值键域。
113
+ export const APPROVAL_RULES_SETTING = 'approval_auto_rules'
114
+ export const APPROVAL_RULES_LIMIT = 50
115
+ // 规则可配的沙箱档:宿主 bash 族提权重试时的 sandbox_permissions 取值;空串 = 任意档。
116
+ export const APPROVAL_RULE_SANDBOXES = ['workspace-write', 'danger-full-access']
117
+
118
+ // 系统临时目录($TMPDIR):macOS 是 /var/folders/<user>/<hash>/T,名字不含 temp/tmp,
119
+ // 关键词 glob 覆盖不到——单独一行兜底;Linux 的 tmpdir() 就是 /tmp,已被覆盖就不重复一行。
120
+ const OS_TMPDIR = tmpdir().replace(/[/\\]+$/, '')
121
+
122
+ // 出厂预置默认规则(DSHBOTS-365 增量改口径):关键词 glob 三条——
123
+ // **/temp/**、**/.tmp/**、**/tmp/** 命中即免审(路径与命令同一套 glob 方言),
124
+ // 再加系统临时目录一行(未被关键词覆盖时)。预置行仍是普通规则行,owner 可自行删改。
125
+ const KEYWORD_APPROVAL_AUTO_RULES = [
126
+ { glob: '**/temp/**', key: 'temp' },
127
+ { glob: '**/.tmp/**', key: 'dot_tmp' },
128
+ { glob: '**/tmp/**', key: 'tmp' },
129
+ ]
130
+ const TMPDIR_COVERED = KEYWORD_APPROVAL_AUTO_RULES.some(item => approvalGlobMatch(item.glob, OS_TMPDIR))
131
+ export const DEFAULT_APPROVAL_AUTO_RULES = [
132
+ ...KEYWORD_APPROVAL_AUTO_RULES,
133
+ ...(TMPDIR_COVERED ? [] : [{ glob: `${OS_TMPDIR}/**`, key: 'tmpdir' }]),
134
+ ].map(item => ({
135
+ id: `arul_default_${item.key}`,
136
+ path_prefix: item.glob,
137
+ command: '',
138
+ bot_id: '',
139
+ tool_name: '',
140
+ sandbox: '',
141
+ note: '',
142
+ updated_at: nowIso(),
143
+ updated_by: 'system:preset',
144
+ }))
145
+
146
+ // 系统预置行的「出厂原样」形态:id → 可接受的路径形态(口径迭代换过形态的都列进来)。
147
+ // 迁移时按这张表认出仍是出厂样的预置行换成当前默认集合;owner 改过路径的预置行不在表内,
148
+ // 视为 owner 自有行保留。owner 自建行(id 不在这张表)同样保留。
149
+ const SYSTEM_PRESET_PATTERNS = new Map ([
150
+ ['arul_default_tmp', ['/tmp', '**/tmp/**']],
151
+ ['arul_default_private_tmp', ['/private/tmp']],
152
+ ['arul_default_var_tmp', ['/var/tmp']],
153
+ ['arul_default_tmpdir', [OS_TMPDIR, `${OS_TMPDIR}/**`]],
154
+ ['arul_default_home_dot_tmp', [join(homedir(), '.tmp').replace(/[/\\]+$/, '')]],
155
+ ['arul_default_home_tmp', [join(homedir(), 'tmp').replace(/[/\\]+$/, '')]],
156
+ ['arul_default_temp', ['**/temp/**']],
157
+ ['arul_default_dot_tmp', ['**/.tmp/**']],
158
+ ])
159
+
160
+ // settings 'approval_auto_rules' 解析:坏数据一律降级为空规则(不抛错,原卡流程兜底)。
161
+ export function parseApprovalRules(raw) {
162
+ let parsed
163
+ try {
164
+ parsed = JSON.parse(String(raw ?? ''))
165
+ } catch {
166
+ return []
167
+ }
168
+ if (!Array.isArray(parsed)) return []
169
+ return parsed.filter(item => item && typeof item === 'object')
170
+ }
171
+
172
+ // glob 方言(路径与命令共用):** 跨任意层级(含 '/')、* 跨任意字符但不跨 '/'、
173
+ // ? 单字符(不跨 '/')、其余按字面量;整串命中才算匹配。尾部 '/**' 额外允许匹配目录自身
174
+ // ('/tmp/**' 命中 '/tmp' 与 '/tmp/a/b',但不命中 '/tmpfoo')。
175
+ export function approvalGlobToRegExp(pattern) {
176
+ let text = String(pattern ?? '')
177
+ let tail = ''
178
+ if (text.endsWith('/**')) {
179
+ text = text.slice(0, -3)
180
+ tail = '(?:/.*)?'
181
+ }
182
+ let out = '^'
183
+ let index = 0
184
+ while (index < text.length) {
185
+ const char = text[index]
186
+ if (char === '*') {
187
+ const doubled = text[index + 1] === '*'
188
+ if (!doubled) {
189
+ out += '[^/]*'
190
+ index += 1
191
+ continue
192
+ }
193
+ index += 2
194
+ if (text[index] === '/') {
195
+ index += 1
196
+ out += '(?:.*/)?'
197
+ } else {
198
+ out += '.*'
199
+ }
200
+ continue
201
+ }
202
+ if (char === '?') {
203
+ out += '[^/]'
204
+ index += 1
205
+ continue
206
+ }
207
+ out += char.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
208
+ index += 1
209
+ }
210
+ return new RegExp(`${out}${tail}$`)
211
+ }
212
+
213
+ export function approvalGlobMatch(pattern, value) {
214
+ const text = String(value ?? '')
215
+ if (!String(pattern ?? '') || !text) return false
216
+ return approvalGlobToRegExp(pattern).test(text)
217
+ }
218
+
219
+ // 单条规则匹配(纯函数):目标为空不命中;主维度二选一命中即中——
220
+ // 路径规则与命令规则都用 glob 整串匹配;不含通配符的存量规则保留旧前缀语义
221
+ // (路径按目录边界、命令按词边界),口径切换不静默废掉已配规则。
222
+ // 辅维度留空 = 通配,填了必须精确相等。
223
+ export function approvalRuleMatches(rule, { botId, toolName, target, sandbox }) {
224
+ const value = String(target ?? '')
225
+ if (!value) return false
226
+ if (rule.bot_id && rule.bot_id !== botId) return false
227
+ if (rule.tool_name && rule.tool_name !== toolName) return false
228
+ if (rule.sandbox && rule.sandbox !== sandbox) return false
229
+ const pathPattern = String(rule.path_prefix ?? '').trim()
230
+ if (pathPattern && matchesRulePattern(pathPattern, value, 'path')) return true
231
+ const commandPattern = String(rule.command ?? '').trim()
232
+ if (commandPattern && matchesRulePattern(commandPattern, value, 'command')) return true
233
+ return false
234
+ }
235
+
236
+ // 含通配符 → glob;不含通配符 → 存量前缀语义(路径按目录边界、命令按词边界)。
237
+ function matchesRulePattern(pattern, value, dimension) {
238
+ if (/[*?]/.test(pattern)) return approvalGlobMatch(pattern, value)
239
+ if (dimension === 'path') return value === pattern || value.startsWith(`${pattern}/`)
240
+ return value === pattern || value.startsWith(`${pattern} `)
241
+ }
242
+
243
+ // 存量预置行迁移:仍是出厂原样的预置行换成当前默认集合(口径迭代换过形态的都算「原样」),
244
+ // owner 自建行与改过路径的预置行不动,显式清空 '[]' 依然永不回播。
245
+ // 返回迁移后的 JSON 字符串,无需迁移时返回 null。
246
+ export function migrateApprovalPresetRules(raw) {
247
+ let parsed
248
+ try {
249
+ parsed = JSON.parse(String(raw ?? ''))
250
+ } catch {
251
+ return null
252
+ }
253
+ if (!Array.isArray(parsed)) return null
254
+ const rows = parsed.filter(item => item && typeof item === 'object')
255
+ const isSystemPreset = row => {
256
+ const id = typeof row.id === 'string' ? row.id : ''
257
+ const patterns = SYSTEM_PRESET_PATTERNS.get(id)
258
+ if (!patterns || String(row.command ?? '').trim()) return false
259
+ const path = String(row.path_prefix ?? '').replace(/[/\\]+$/, '')
260
+ return patterns.some(pattern => pattern.replace(/[/\\]+$/, '') === path)
261
+ }
262
+ if (!rows.some(isSystemPreset)) return null
263
+ const firstIndex = rows.findIndex(isSystemPreset)
264
+ const kept = rows.filter(row => !isSystemPreset(row))
265
+ const before = rows.slice(0, firstIndex).filter(row => !isSystemPreset(row)).length
266
+ const presets = DEFAULT_APPROVAL_AUTO_RULES.map(rule => ({ ...rule }))
267
+ return JSON.stringify([...kept.slice(0, before), ...presets, ...kept.slice(before)])
268
+ }
269
+
93
270
  // 来源定位字段(DSHBOTS-240):审批行 → 来源群聊(项目名/KEY)+ 任务 ID/标识/标题。
94
271
  // 列表查询用 JOIN 一次取齐(approvalsPending / approvalsForProject / approvalsForBot 共用),
95
272
  // 避免逐行 N+1;缺任务时任务字段留空,不猜。
@@ -120,12 +297,14 @@ export const approvalsMethods = {
120
297
  const off = runtime.ctx.on('approval/request', (req, next) => this.handleApprovalRequest(req, next), { prepend: true })
121
298
  // approval/request 事件不带工具参数,目标取数只能从 tools/pre-execute 透传监听来:
122
299
  // 宿主先过 pre-execute 网关、gate 返回 ask 才发起审批,此刻 exec 里带着 callId/name/arguments。
123
- // 按 callId 记已提取目标(先提短串再掩码,只存小字符串),审批发起时一次性取走;超量 FIFO 驱逐。
300
+ // 按 callId 记已提取目标与目标沙箱档(DSHBOTS-365 辅维度;先提短串再掩码,只存小字符串),
301
+ // 审批发起时一次性取走;超量 FIFO 驱逐。
124
302
  const offPreExecute = runtime.ctx.on('tools/pre-execute', (exec, next) => {
125
303
  const callId = exec?.callId ? String(exec.callId) : ''
126
304
  const target = callId ? toolTargetOf(exec.arguments) : null
127
305
  if (callId && target) {
128
- this.approvalTargets.set(callId, this.maskSecretValues(target))
306
+ const sandbox = typeof exec.arguments?.sandbox_permissions === 'string' ? exec.arguments.sandbox_permissions : ''
307
+ this.approvalTargets.set(callId, { target: this.maskSecretValues(target), sandbox })
129
308
  if (this.approvalTargets.size > APPROVAL_TARGET_CACHE_LIMIT) {
130
309
  this.approvalTargets.delete(this.approvalTargets.keys().next().value)
131
310
  }
@@ -168,9 +347,11 @@ export const approvalsMethods = {
168
347
  const displayReason = req.displayReason?.zh ? this.maskSecretValues(String(req.displayReason.zh).slice(0, 2_000)) : null
169
348
  const reason = this.maskSecretValues(String(req.reason ?? '').slice(0, 2_000))
170
349
  // 本次调用的操作目标:pre-execute 阶段按 callId 记下,这里一次性取走(不留残页);没有则为 NULL,
171
- // UI 回退到从摘要正则猜测的旧口径。
350
+ // UI 回退到从摘要正则猜测的旧口径。sandbox 是目标沙箱档(免审规则辅维度,DSHBOTS-365)。
172
351
  const callId = req.callId ? String(req.callId) : null
173
- const toolTarget = callId ? (this.approvalTargets.get(callId) ?? null) : null
352
+ const cachedTarget = callId ? (this.approvalTargets.get(callId) ?? null) : null
353
+ const toolTarget = cachedTarget?.target ?? null
354
+ const targetSandbox = cachedTarget?.sandbox ?? ''
174
355
  if (callId) this.approvalTargets.delete(callId)
175
356
 
176
357
  store.run(
@@ -181,6 +362,21 @@ export const approvalsMethods = {
181
362
  createdAt, new Date(Date.parse(createdAt) + timeoutMs).toISOString(),
182
363
  )
183
364
 
365
+ // DSHBOTS-365 免审白名单:命中规则的提权请求不落待办卡、不发群聊锚点/微信转发/通知,
366
+ // 插件即时替 owner 应答 allowed-once。留痕两件套缺一不可:approvals 行 status='allowed'
367
+ // + decided_by='auto:rule:<id>'(复用 settleApproval,decided_at 同步落库),审计事件
368
+ // approval.auto_allow。每次调用一放行一结:规则每次现读,改规则即时生效,无持久授权。
369
+ // 不进 approvalPending、不挂超时 timer、不挂 abort 监听——超时与轮次中止对已决条目天然不触。
370
+ const autoRule = this.matchApprovalAutoRule({ botId: bot.id, toolName, target: toolTarget, sandbox: targetSandbox })
371
+ if (autoRule) {
372
+ this.settleApproval(approvalId, 'allowed', 'allowed-once', `auto:rule:${autoRule.id}`)
373
+ this.audit(
374
+ { type: 'system', id: 'system' }, 'approval.auto_allow', 'approval', approvalId,
375
+ { ruleId: autoRule.id, toolName, botId: bot.id, target: toolTarget },
376
+ )
377
+ return 'allowed-once'
378
+ }
379
+
184
380
  // 卡片锚点:群聊落 messages(kind=approval),单聊落 solo_messages(DSHBOTS-218)。
185
381
  // 状态渲染时查 approvals 表,消息体只是纯文本兜底,不承载状态。
186
382
  const summary = displayReason || reason || '请求执行需要授权的操作'
@@ -225,16 +421,22 @@ export const approvalsMethods = {
225
421
  },
226
422
 
227
423
  // 统一结算:清定时器、出 pending 表、写终态。hostAnswer 非空才向宿主应答(abort 分支不答)。
424
+ // 写库容错:结算可能由轮次取消的 abort 监听或超时定时器在插件重载(store.close())之后
425
+ // 迟到触发——曾在 abort 分发里裸抛 statement has been finalized,把整个 dsh 宿主打成 fatal 退出。
228
426
  settleApproval(approvalId, status, hostAnswer, decidedBy) {
229
427
  const pending = this.approvalPending?.get(approvalId)
230
428
  if (pending) {
231
429
  clearTimeout(pending.timer)
232
430
  this.approvalPending.delete(approvalId)
233
431
  }
234
- this.store.run(
235
- 'UPDATE approvals SET status = ?, decided_by = ?, decided_at = ? WHERE id = ? AND status = ?',
236
- status, decidedBy, nowIso(), approvalId, 'pending',
237
- )
432
+ try {
433
+ this.store.run(
434
+ 'UPDATE approvals SET status = ?, decided_by = ?, decided_at = ? WHERE id = ? AND status = ?',
435
+ status, decidedBy, nowIso(), approvalId, 'pending',
436
+ )
437
+ } catch (error ) {
438
+ this.logger?.warn?.('dsh-team: 审批结算写库失败(插件可能已重载): %s', error?.message ?? error)
439
+ }
238
440
  if (pending && hostAnswer) pending.resolve(hostAnswer)
239
441
  },
240
442
 
@@ -252,6 +454,72 @@ export const approvalsMethods = {
252
454
  return this.approvalView(this.store.get('SELECT * FROM approvals WHERE id = ?', approvalId))
253
455
  },
254
456
 
457
+ // 免审规则取数(DSHBOTS-365):每次现读现解析——无缓存,改规则对下一次提权请求即时生效。
458
+ approvalRulesView() {
459
+ return parseApprovalRules(this.store.setting(APPROVAL_RULES_SETTING, ''))
460
+ },
461
+
462
+ // 免审规则匹配入口:按规则表顺序首中即返(表序即优先级)。目标为空(无 callId 缓存)
463
+ // 一律不命中,保守回落原卡流程。
464
+ matchApprovalAutoRule(input) {
465
+ const target = String(input.target ?? '')
466
+ if (!target) return null
467
+ for (const rule of this.approvalRulesView()) {
468
+ if (approvalRuleMatches(rule, input)) return rule
469
+ }
470
+ return null
471
+ },
472
+
473
+ // 免审规则保存(DSHBOTS-365):独立编辑面(仿 updatePromptSegment 先例),仅 type=user
474
+ // 可写——bot 写免审规则必须被拒,维持「bot 不能自批」边界。整表替换(UI 全量收集后提交),
475
+ // 逐条校验:主维度至少一项、路径前缀必须是绝对路径、sandbox 档枚举收口、bot 必须存在。
476
+ // 保存即审计;id 复用已有(编辑保 id),新条目发 arul_*。
477
+ async updateApprovalRules(rulesInput, actor = this.actor()) {
478
+ if (actor?.type !== 'user') throw forbidden('仅工作台 owner 可配置审批免审规则,bot 不能自批')
479
+ if (!Array.isArray(rulesInput)) throw badRequest('免审规则必须是数组')
480
+ if (rulesInput.length > APPROVAL_RULES_LIMIT) throw badRequest(`免审规则最多 ${APPROVAL_RULES_LIMIT} 条`)
481
+ const knownIds = new Set(this.approvalRulesView().map(rule => rule.id))
482
+ const usedIds = new Set ()
483
+ const rules = rulesInput.map((raw, index) => {
484
+ const item = raw && typeof raw === 'object' ? raw : {}
485
+ const label = `第 ${index + 1} 条规则`
486
+ const pathPrefix = String(item.path_prefix ?? '').trim().replace(/\/+$/, '')
487
+ const command = String(item.command ?? '').trim().split('\n')[0].trim().slice(0, 200)
488
+ if (!pathPrefix && !command) throw badRequest(`${label}缺少路径规则或命令规则(至少填一项)`)
489
+ // 路径规则:绝对路径,或含通配符的 glob(关键词规则如 **/tmp/** 不必是绝对路径)。
490
+ if (pathPrefix && !pathPrefix.startsWith('/') && !/[*?]/.test(pathPrefix)) {
491
+ throw badRequest(`${label}路径规则必须是以 / 开头的绝对路径或含通配符的 glob`)
492
+ }
493
+ if (pathPrefix.length > 500) throw badRequest(`${label}路径规则超长(上限 500 字符)`)
494
+ const botId = String(item.bot_id ?? '').trim()
495
+ if (botId && !this.store.get('SELECT id FROM bots WHERE id = ?', botId)) throw badRequest(`${label}限定的 Bot 不存在`)
496
+ const sandbox = String(item.sandbox ?? '').trim()
497
+ if (sandbox && !APPROVAL_RULE_SANDBOXES.includes(sandbox)) {
498
+ throw badRequest(`${label}沙箱档必须是 ${APPROVAL_RULE_SANDBOXES.join('/')} 或留空`)
499
+ }
500
+ // id 复用已有(编辑保 id);新条目或输入撞 id(重复行)一律发新 id,保证表内 id 唯一。
501
+ let ruleId = item.id && knownIds.has(String(item.id)) && !usedIds.has(String(item.id)) ? String(item.id) : id('arul')
502
+ usedIds.add(ruleId)
503
+ return {
504
+ id: ruleId,
505
+ path_prefix: pathPrefix,
506
+ command,
507
+ bot_id: botId,
508
+ tool_name: String(item.tool_name ?? '').trim().slice(0, 100),
509
+ sandbox,
510
+ note: String(item.note ?? '').trim().slice(0, 200),
511
+ updated_at: nowIso(),
512
+ updated_by: `${actor.type}:${actor.id}`,
513
+ }
514
+ })
515
+ this.store.setSetting(APPROVAL_RULES_SETTING, JSON.stringify(rules))
516
+ this.audit(actor, 'approval_rules.update', 'settings', APPROVAL_RULES_SETTING, {
517
+ count: rules.length,
518
+ rules: rules.map(rule => ({ id: rule.id, path_prefix: rule.path_prefix, command: rule.command, sandbox: rule.sandbox })),
519
+ })
520
+ return this.approvalRulesView()
521
+ },
522
+
255
523
  // 目标展示形:绝对路径落在项目工作区内且剩余段非空、不含空白时收成相对路径(chip 少占宽);
256
524
  // 命令、带空白的路径或库外路径原样返回。title 层恒用原始值,鼠标悬停可见全貌。
257
525
  toolTargetDisplay(target) {
@@ -3,7 +3,8 @@
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, APPROVAL_TIMEOUT_KEY, QUESTION_TIMEOUT_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'
6
+ import { validateRuntimeSettingValue, RUNTIME_SETTING_DEFS, RUNTIME_SETTING_KEYS, runtimeSettingsView as runtimeSettingsRows,
7
+ effectiveReviewIdleMinutes, effectiveRunLimits, envExplicit, RUN_LIMIT_RANGES, RUN_TIMEOUT_KEY, STALL_WATCHDOG_KEY, APPROVAL_TIMEOUT_KEY, QUESTION_TIMEOUT_KEY, REVIEW_TIMEOUT_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
8
  import { badRequest, conflict, notFound } from '../errors.js'
8
9
  import { ensureDirResilient, ensureSkillRoot } from '../paths.js'
9
10
  import { seedModelPrices } from '../pricing.js'
@@ -19,6 +20,7 @@ import { ensureTaskSandboxSchema } from './task-sandbox-schema.js'
19
20
  import { ensureWechatTriggerSchema } from './wechat-trigger-schema.js'
20
21
  import { ensureExternalTriggerSchema } from './external-trigger-schema.js'
21
22
  import { PROMPT_SEGMENT_DEFAULTS, PROMPT_SEGMENT_MAX_CHARS, PROMPT_TRIO_BUDGET, parsePromptOverrides, promptOverridesHash, taskGuidanceTrioLength } from './runtime/prompt.js'
23
+ import { effectiveReviewTimeoutMinutes } from './runtime/session.js'
22
24
  import { id, jsonParse, nowIso } from '../util.js'
23
25
 
24
26
 
@@ -213,8 +215,11 @@ export const coreMethods = {
213
215
  'memory_review', 'chat_memory_review',
214
216
  RUN_TIMEOUT_KEY, STALL_WATCHDOG_KEY,
215
217
  APPROVAL_TIMEOUT_KEY, QUESTION_TIMEOUT_KEY,
218
+ REVIEW_TIMEOUT_KEY,
216
219
  UI_LANGUAGE_KEY,
217
220
  REVIEW_IDLE_MINUTES_KEY, REVIEW_AUTO_CLOSE_KEY, REVIEW_ESCALATE_KEY,
221
+ // 运行参数目录(全局设置「运行参数」卡):所有运行期 DSH_TEAM_* 变量的可配置键域。
222
+ ...RUNTIME_SETTING_KEYS,
218
223
  ]
219
224
  const values = {}
220
225
  for (const key of keys) values[key] = this.store.setting(key, '')
@@ -233,6 +238,9 @@ export const coreMethods = {
233
238
  runTimeoutEnv: limits.runTimeoutEnv,
234
239
  stallTimeoutEnv: limits.stallTimeoutEnv,
235
240
  reviewIdleMinutes,
241
+ // 验收分档时效(DSHBOTS-364):默认 0 = 关闭分档、跟随全局;设置页随行回显。
242
+ reviewTimeoutMinutes: effectiveReviewTimeoutMinutes(key => this.store.setting(key)),
243
+ reviewTimeoutEnv: envExplicit('DSH_TEAM_REVIEW_TIMEOUT_MINUTES'),
236
244
  }
237
245
  },
238
246
  updateSettings(patch, actor = this.actor(), expectedRevision = undefined) {
@@ -312,6 +320,14 @@ export const coreMethods = {
312
320
  if (!UI_LANGUAGE_VALUES.includes(raw)) throw badRequest(`${UI_LANGUAGE_KEY} 必须是 ${UI_LANGUAGE_VALUES.join('/')}`)
313
321
  values[UI_LANGUAGE_KEY] = raw
314
322
  }
323
+ // 运行参数目录通用校验:空串 = 清除保存值回默认;非空按 kind 校验并规范化落库。
324
+ for (const def of RUNTIME_SETTING_DEFS) {
325
+ const value = values[def.key]
326
+ if (value === undefined || value === '') continue
327
+ const check = validateRuntimeSettingValue(def, value)
328
+ if (!check.ok) throw badRequest(`运行参数 ${def.key}(${def.env}):${check.error}`)
329
+ values[def.key] = check.normalized
330
+ }
315
331
  this.store.transaction(() => {
316
332
  for (const [key, value] of Object.entries(values)) this.store.setSetting(key, value)
317
333
  // 乐观并发令牌随保存推进(B2/DSHBOTS-325):settings_revision 不是 settingsView 键,
@@ -330,6 +346,13 @@ export const coreMethods = {
330
346
  return this.settingsView()
331
347
  },
332
348
 
349
+ // 运行参数目录展示视图(全局设置「运行参数」卡):每条 env 的保存值/生效值/默认值/
350
+ // env 覆盖标志。effective 取自存活覆盖视图,与所有消费点同源。
351
+ runtimeSettingsView() {
352
+ // default 列必须取启动配置(baseConfig),不能取覆盖视图,否则「默认值」列会跟着保存值变。
353
+ return { rows: runtimeSettingsRows(this.baseConfig ?? this.config, key => this.store.setting(key)) }
354
+ },
355
+
333
356
  // 可编辑提示词段(B1/DSHBOTS-324):只读视图。defaultChanged = 覆盖保存时的内置默认
334
357
  // 指纹与当前默认不一致(升级改了默认文本),UI 据此给「保留我的文本 / 恢复新默认」取舍。
335
358
  promptSegmentsView() {
@@ -389,7 +412,9 @@ export const coreMethods = {
389
412
  start() {
390
413
  if (this.started) return
391
414
  this.started = true
392
- this.timer = setInterval(() => void this.tick(), this.config.schedulerIntervalMs)
415
+ // 周期拍走空载门:空闲时降频为一次索引计数,有工作立即恢复全量拍;
416
+ // 事件唤醒(各入队路径的 void this.tick())不经此门。
417
+ this.timer = setInterval(() => void this.tickIdleGate(), this.config.schedulerIntervalMs)
393
418
  this.timer.unref?.()
394
419
  setTimeout(() => void this.tick(), 300).unref?.()
395
420
  },
@@ -397,6 +422,10 @@ export const coreMethods = {
397
422
  if (this.timer) clearInterval(this.timer)
398
423
  this.timer = null
399
424
  this.started = false
425
+ // 在途审批定时器一并清空:abort 监听由宿主信号持有无法摘除(迟到结算已由
426
+ // settleApproval 容错),但停机后不得再由自身定时器主动触发写库。
427
+ for (const pending of this.approvalPending?.values() ?? []) clearTimeout(pending.timer)
428
+ this.approvalPending?.clear()
400
429
  void this.wechat?.stop()
401
430
  void this.feishu?.stop()
402
431
  },
@@ -179,13 +179,28 @@ export const memoryMethods = {
179
179
  }
180
180
  const reviewRunId = id('run')
181
181
  const createdAt = nowIso()
182
- this.store.run(
183
- `INSERT INTO runs(id, project_id, bot_id, task_id, kind, mode, trigger_type, trigger_ref, status,
184
- attempt, idempotency_key, model_provider, model_model, model_effort, queued_at)
185
- VALUES (?, ?, ?, NULL, 'memory_review', 'read', 'memory_review', ?, 'queued', 1, ?, ?, ?, ?, ?)`,
186
- reviewRunId, project.id, bot.id, sourceRunId, `memory_review:${sourceRunId}`,
187
- reviewProvider, reviewModel, reviewEffort, createdAt,
188
- )
182
+ try {
183
+ this.store.run(
184
+ `INSERT INTO runs(id, project_id, bot_id, task_id, kind, mode, trigger_type, trigger_ref, status,
185
+ attempt, idempotency_key, model_provider, model_model, model_effort, queued_at)
186
+ VALUES (?, ?, ?, NULL, 'memory_review', 'read', 'memory_review', ?, 'queued', 1, ?, ?, ?, ?, ?)`,
187
+ reviewRunId, project.id, bot.id, sourceRunId, `memory_review:${sourceRunId}`,
188
+ reviewProvider, reviewModel, reviewEffort, createdAt,
189
+ )
190
+ } catch (error) {
191
+ // memory_review 占 bot 串行域但入队点无 busy 闸(来源运行收尾/交付路径):同 (bot,
192
+ // 工作区) 已有活跃运行(如任务交付后新 chat 已排队)时 INSERT 撞 one_active_run_per_bot。
193
+ // 审查是尽力而为的治理动作,撞车降级为跳过(调用方按 null 走沉淀兜底/忽略),不把
194
+ // 收尾路径打成异常(生产实测:finishRun 尾部抛 UNIQUE 导致运行收尾报「异常」)。
195
+ if (this.isRunBotUniqueViolation(error)) {
196
+ this.logger?.warn?.(
197
+ 'dsh-team: 记忆审查入队撞 bot 串行域(bot=%s run=%s source=%s),本次跳过',
198
+ bot?.id, reviewRunId, sourceRunId,
199
+ )
200
+ return null
201
+ }
202
+ throw error
203
+ }
189
204
  this.store.run(
190
205
  'INSERT INTO run_events(id, run_id, type, message, created_at) VALUES (?, ?, ?, ?, ?)',
191
206
  id('evt'), reviewRunId, 'queued', '任务交付完成,触发记忆审查', createdAt,
@@ -447,7 +462,8 @@ export const memoryMethods = {
447
462
  const keyword = text(query, 200).trim()
448
463
  const limitN = Math.min(100, Math.max(1, Number(limit) || 20))
449
464
  let rows
450
- if (keyword && this.store.ftsEnabled) {
465
+ // trigram 分词器无法匹配不足 3 字符的关键词(如中文「发版」两字),短词走 LIKE 子串兜底。
466
+ if (keyword && this.store.ftsEnabled && keyword.length >= 3) {
451
467
  const match = `"${keyword.replace(/"/g, '""')}"`
452
468
  rows = this.store.all(
453
469
  `SELECT m.* FROM memories_fts f JOIN memories m ON m.id = f.memory_id
@@ -7,6 +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 { REVIEWER_BOT_NAME } from '../seed-bots.js'
10
11
  import { ensureBotTmpDirs, ensureExternalDir, ensureProjectWorkspace } from '../paths.js'
11
12
  import { clampNumber, id, nowIso, parseDisabledSkills, projectKey, slugify, text } from '../util.js'
12
13
 
@@ -277,7 +278,17 @@ export const projectsMethods = {
277
278
  const projectId = id('prj')
278
279
  const groupId = id('grp')
279
280
  const createdAt = nowIso()
280
- const memberIds = [...new Set([owner.id, ...(Array.isArray(input.memberIds) ? input.memberIds : [])])]
281
+ // 成员默认(DSHBOTS-365):不显式指定成员的新群自动带入种子 reviewer——验收核验
282
+ // 优先落到质量评审角色上,总监只裁决。显式 memberIds 是用户裁剪过的名单,不擅自加人;
283
+ // 用户事后移除 reviewer 即回落总监自行核验(spawnReviewDelegate 兜底)。
284
+ const explicitMembers = Array.isArray(input.memberIds)
285
+ const memberIds = [...new Set([owner.id, ...(explicitMembers ? input.memberIds : [])])]
286
+ if (!explicitMembers) {
287
+ const reviewer = this.store.get(
288
+ "SELECT id FROM bots WHERE name = ? AND status = 'active'", REVIEWER_BOT_NAME,
289
+ )
290
+ if (reviewer && reviewer.id !== owner.id) memberIds.push(reviewer.id)
291
+ }
281
292
  for (const botId of memberIds) this.botRow(botId)
282
293
  await ensureProjectWorkspace(this.config.workspace, slug)
283
294
  const productionDir = await this.resolveProductionDir(input.productionDir)
@@ -36,6 +36,10 @@ const FAILURE_CATEGORY_NOTICES = {
36
36
  rate_limited: { label: '限流', summary: '上游限流,已按退避策略自动处理。' },
37
37
  sandbox_denied: { label: '沙箱拒绝', summary: '文件或命令操作被沙箱策略拒绝。' },
38
38
  timeout: { label: '超时', summary: '上游响应超时。' },
39
+ // DSHBOTS-364:本机时效中止/停滞收割与上游超时分开报——此前一律归「上游响应超时」,
40
+ // 把自家看门狗/分档时效的动作误报成 provider 故障,误导排查方向。
41
+ run_timeout: { label: '时效', summary: '运行超过时效上限被中止(非上游故障)。' },
42
+ stalled: { label: '停滞', summary: '运行长时间无进展,已被看门狗中止。' },
39
43
  network: { label: '网络', summary: '网络瞬态失败,已按退避策略自动重试。' },
40
44
  blocked: { label: '会话受阻', summary: '宿主拒绝执行该会话(可能已被归档),未产生任何模型输出。' },
41
45
  internal: { label: '内部错误', summary: '服务内部错误。' },
@@ -46,6 +50,8 @@ export function classifyFailure(error) {
46
50
  if (isQuotaExhausted(error)) return FAILURE_CATEGORY_NOTICES.quota
47
51
  if (isRateLimitError(error)) return FAILURE_CATEGORY_NOTICES.rate_limited
48
52
  if (SANDBOX_DENIED_PATTERN.test(raw)) return FAILURE_CATEGORY_NOTICES.sandbox_denied
53
+ if (error?.code === 'RUN_TIMEOUT') return FAILURE_CATEGORY_NOTICES.run_timeout
54
+ if (error?.code === 'RUN_STALLED') return FAILURE_CATEGORY_NOTICES.stalled
49
55
  if (TIMEOUT_PATTERN.test(raw)) return FAILURE_CATEGORY_NOTICES.timeout
50
56
  if (isTransientNetworkError(error)) return FAILURE_CATEGORY_NOTICES.network
51
57
  if (error?.code === 'SESSION_BLOCKED') return FAILURE_CATEGORY_NOTICES.blocked
@@ -67,6 +73,11 @@ export const runFinishMethods = {
67
73
  if (attentionPending) return false
68
74
  const current = this.taskRow(task.id)
69
75
  if (current.status !== 'in_review') return false
76
+ // 核验分档:只读档交付免自动核验(与验收闸门豁免同口径);审计留痕便于核对漏审。
77
+ if (this.readOnlyDelivery(run, current)) {
78
+ this.audit({ type: 'system', id: 'system' }, 'review.auto_delegate', 'task', task.id, { skipped: 'read_only' })
79
+ return false
80
+ }
70
81
  const owner = project.owner_bot_id
71
82
  ? this.store.get("SELECT id FROM bots WHERE id = ? AND status = 'active'", project.owner_bot_id)
72
83
  : null