dsh-team-bots 0.2.465 → 0.3.12

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.
package/NOTICE CHANGED
@@ -9,6 +9,12 @@ Architecture and DSH integration were informed by:
9
9
  - Cindy, Copyright Cindy contributors, Apache-2.0
10
10
  https://github.com/makecindy/cindy
11
11
 
12
+ Collaboration protocol ideas (builder-verifier separation, mutation fence,
13
+ tiered notifications, ledger-authoritative task events, acceptance-boundary
14
+ memory reminder) were informed by dsh-agent-team, Copyright Contexera
15
+ contributors, MIT License:
16
+ https://github.com/Contexera/dsh-agent-team
17
+
12
18
  Runtime dependency:
13
19
  - DeepSeek Harness (DSH), Copyright (c) 2026 DeepSeek, MIT License
14
20
  https://github.com/deepseek-ai/deepseek-harness
package/README.md CHANGED
@@ -42,17 +42,23 @@ The first visit exchanges the current startup token for a 30-day login cookie. A
42
42
 
43
43
  Every project is a group chat. A bot can also be addressed one-to-one in a dispatch view. All traffic for one bot — task dispatch, group chat, direct message, one-to-one chat — lands on a single control-plane session, and that bot runs one task at a time; different bots still run in parallel.
44
44
 
45
+ A group chat has three reply modes (switchable in project settings): **Director first** (default — the director answers when nobody is addressed), **Everyone responds** (all members answer when nobody is addressed), and **Mentioned only** (a message with no explicit @mention or bot reply wakes nobody immediately, but the director's thinking bubble appears at once and the director auto-claims it after 1 second; explicit mentions and replies deliver in every mode). The message tail window injected into bot context is tiered: messages that mention the bot keep their full text with a marker, while other bots' chatter collapses into short background digests.
46
+
45
47
  ### Task board
46
48
 
47
49
  States: backlog, todo, in progress, blocked, in review, done, canceled. A card carries assignee, priority, parent/child links, tags, write scopes, an optional time budget (a hard limit that aborts the run), comments, and its own usage. Rows are grouped by state and can be dragged onto another group to change status.
48
50
 
51
+ Acceptance has a mechanical gate: **whoever built does not verify** — a bot reviewer that has ever been the card's assignee (including past reassignments) is refused; hand the review to a bot that never executed the card, or accept from the workbench board as the human owner. Returning a card for rework is not gated. Amending a card (`team_assign_task` re-dispatch with card edits) accepts an optional `expected_version` mutation fence: if the card changed since you last saw it (delivery, transition, another edit) the write is refused with the most recent changes listed, so you can re-decide in place.
52
+
53
+ Task status transitions now write an authoritative `status` task event in the same transaction as the update, so the event stream fully replays the task state machine; the `task_projection_drift` API is a read-only check that replays the ledger and reports any drift from the projection.
54
+
49
55
  ### Write scopes and parallel scheduling
50
56
 
51
57
  A card declares the paths it will write, relative to the project working directory. Two runs of the same project run in parallel only when both declare scopes and the path prefixes do not overlap; a card with no declared scope is treated as serial. An urgent card may be exempted from the queue — the exemption is written into the card's creation message rather than applied silently.
52
58
 
53
59
  ### Memory, skills, evolution proposals
54
60
 
55
- Memory entries are written, reviewed, frozen and archived by the owner, and are readable by every bot in the project. Skills come from a shared skill root plus per-project skills; changing them goes through a proposal, an approval and an apply, with a canary stage before promotion to full effect. The same path can change a bot's role instructions.
61
+ Memory entries are written, reviewed, frozen and archived by the owner, and are readable by every bot in the project. After a task is accepted, the assignee's next run in that project carries a one-time reminder to persist durable conclusions into memory (`team_remember`) while they are fresh, instead of waiting for session rollover. Skills come from a shared skill root plus per-project skills; changing them goes through a proposal, an approval and an apply, with a canary stage before promotion to full effect. The same path can change a bot's role instructions.
56
62
 
57
63
  ### Approval and question cards
58
64
 
package/docs/README.zh.md CHANGED
@@ -42,17 +42,23 @@ http://<host>:<port>/api/dsh-team/ui 团队工作台本身
42
42
 
43
43
  每个项目是一个群聊;单个 Bot 也可以被单独一对一调度。同一个 bot 的全部流量——任务派发、群聊、私信、单聊——都落到它唯一的一条控制面会话上,同一 bot 同时只跑一条运行,不同 bot 之间照旧并行。
44
44
 
45
+ 群聊有三种回复模式(项目设置里切换):**总监优先**(默认,没人被点名时总监兜底响应)、**全员响应**(没人被点名时全员响应)、**仅被点名**(无显式 @/引用时不立即唤醒任何 bot,但发送后立刻亮起总监的思考气泡,总监默认 1 秒后自动接单;显式 @ 与引用回复在所有模式下都照旧直达)。Bot 上下文里的群消息尾窗按分级注入:点名本 bot 的消息保持全文并带标记,其他 bot 的闲聊折叠成短背景摘要。
46
+
45
47
  ### 任务板
46
48
 
47
49
  状态:待规划、待执行、进行中、受阻、待验收、已完成、已取消。一张卡带负责人、优先级、父子任务、标签、写范围、可选的时效要求(硬性时限,到期中止运行)、评论,以及本卡自己的用量。任务行按状态分组,可拖到别的分组直接改状态。
48
50
 
51
+ 验收有机械闸:**执行者不得验收自己执行过的卡**——bot 验收者若曾担任本卡负责人(含历史改派)即被拒,须转派未执行过本卡的 bot 或由工作台 owner 在看板验收;退回重做不受此限。改卡(`team_assign_task` 重派附卡面修正)可带 `expected_version` 做变更栅栏:卡在你读取之后被交付、流转或他人编辑过时写入被拒,拒绝附最近变更事实,可据此就地重新裁决。
52
+
53
+ 任务状态迁移统一落权威 `status` 事件(与状态更新同事务),事件流可完整重放状态机;`task_projection_drift` API 从事件流重放对照投影做只读巡检,漂移即报。
54
+
49
55
  ### 写范围与并行调度
50
56
 
51
57
  每张卡声明自己会写哪些路径(相对项目工作目录)。同一项目下两个运行只有在双方都声明了写范围、且路径前缀互不重叠时才并行;没声明写范围的卡按串行处理。紧急卡可以豁免排队,但豁免会写进建卡消息,不做静默处理。
52
58
 
53
59
  ### 记忆、技能与进化提案
54
60
 
55
- 记忆由 owner 写入、复核、冻结与归档,项目内所有 Bot 都能读到。技能来自共享技能根目录加项目级技能;改动走提案 → 审批 → 落地,先灰度再转全量。同一条路径也能改 Bot 的角色指令。
61
+ 记忆由 owner 写入、复核、冻结与归档,项目内所有 Bot 都能读到。任务验收通过后,负责人在该项目的下一次运行里会收到一段一次性提醒,指引把值得跨任务保留的结论趁热写进记忆(`team_remember`),不必等会话结转。技能来自共享技能根目录加项目级技能;改动走提案 → 审批 → 落地,先灰度再转全量。同一条路径也能改 Bot 的角色指令。
56
62
 
57
63
  ### 审批卡与提问卡
58
64
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-team-bots",
3
- "version": "0.2.465",
3
+ "version": "0.3.12",
4
4
  "description": "Project spaces, group chats, task boards, memory and usage for teams of DSH bots",
5
5
  "repository": {
6
6
  "type": "git",
package/src/api.js CHANGED
@@ -1,4 +1,4 @@
1
- import { AppError } from './errors.js'
1
+ import { AppError, forbidden } from './errors.js'
2
2
  import { exportUsageCsv } from './usage-reconcile.js'
3
3
 
4
4
  const ACTIONS = new Set([
@@ -7,6 +7,7 @@ const ACTIONS = new Set([
7
7
  'release_bot_quota',
8
8
  'create_project', 'update_project', 'archive_project', 'reopen_project', 'remove_project_tracking', 'browse_dirs',
9
9
  'mark_chat_read',
10
+ 'task_projection_drift',
10
11
  'add_member', 'remove_member',
11
12
  'send_message', 'send_solo_message', 'get_message_image', 'create_task', 'update_task', 'assign_task', 'transition_task', 'add_comment', 'task_detail', 'task_review_delegate', 'task_update_scopes',
12
13
  'retry_run', 'cancel_run', 'run_trajectory', 'answer_attention',
@@ -75,6 +76,10 @@ export async function handleAction(service, action , payload
75
76
  case 'mark_chat_read':
76
77
  // IM 式已读:水位只推到用户看到的那条消息,之后新到的仍算未读。
77
78
  return service.markChatRead(required(payload.projectId, 'projectId'), payload.readAt ?? '')
79
+ case 'task_projection_drift':
80
+ // 账本一致性巡检(只读诊断):从权威事件流重放任务状态对照投影,漂移即报。
81
+ if (actor.type !== 'user') throw forbidden('仅工作台用户可执行账本巡检')
82
+ return { drifted: service.taskProjectionDrift() }
78
83
  case 'browse_dirs':
79
84
  return service.browseDirectories(payload)
80
85
  case 'send_message':
package/src/config.js CHANGED
@@ -149,7 +149,7 @@ export function effectiveQuestionTimeoutMs(config, getSetting
149
149
  // 产品规则:每张任务卡必有预算。缺省链 = env 显式 > 无进展看门狗(分钟)生效值 >
150
150
  // 兜底 20(看门狗未配置与配 0 关闭同值,预算不得变 0/无限)。消费点(createTask
151
151
  // 建档、assignTask 给存量 NULL 卡补挂)每次现算,改值对之后建档/派发的卡生效。
152
- export const TASK_TIME_BUDGET_FALLBACK_MINUTES = 20
152
+ export const TASK_TIME_BUDGET_FALLBACK_MINUTES = 40
153
153
  export function effectiveTaskTimeBudgetMinutes(config, getSetting = () => null) {
154
154
  const env = envExplicit('DSH_TEAM_TASK_TIME_BUDGET_MINUTES')
155
155
  const stallMinutes = Math.round(effectiveRunLimits(config, getSetting).stallTimeoutMs / 60_000)
@@ -160,8 +160,10 @@ export function effectiveTaskTimeBudgetMinutes(config, getSetting
160
160
  // time_budget_minutes 时的卡级兜底档,按卡 priority 分档落库;显式值永远优先。
161
161
  // 与全局缺省链(effectiveTaskTimeBudgetMinutes)分工:本表只管派单路径,不经派单
162
162
  // 的直建卡仍走全局链。无效 priority 与 createTask 同口径回退 medium 档。
163
+ // 2026-11-13 放宽:生产实测任务运行大量顶死在旧 medium 档 30 分钟(max 恰为 1800s),
164
+ // 档位翻倍让大卡一轮做深,减少派生轮往返。
163
165
  export const PRIORITY_BUDGET_MINUTES = {
164
- urgent: 45, high: 45, medium: 30, low: 15, none: 15,
166
+ urgent: 90, high: 90, medium: 60, low: 30, none: 30,
165
167
  }
166
168
 
167
169
  // 会话结转阈值生效值(DSHBOTS-145):优先级与运行时效一致——env 显式 > settings 表
@@ -312,9 +314,14 @@ export function resolveConfig(config = {}) {
312
314
  // 共享技能池固定在本机 ~/.agents,与用户其他 agent 工具共用同一目录;测试可注入临时目录。
313
315
  skillRoot: resolve(config.skillRoot?.trim() || join(homedir(), '.agents')),
314
316
  // 并行的安全边界由写范围闸门保证(同项目写运行只在双方声明且路径不相交时才并行),
315
- // 这里的总数上限只防主机过载;读运行(chat/dm)与写运行共用一个池子,给到 6 才不至于让
316
- // 一两条对话运行把写任务的并发位吃干。
317
- maxConcurrentRuns: int(config.maxConcurrentRuns ?? process.env.DSH_TEAM_MAX_RUNS, 6, 1, 16),
317
+ // 这里的总数上限只防主机过载;读运行(chat/dm)与写运行共用一个池子。默认 10:
318
+ // 生产实测(2026-11-13 近 7 天)常态并发 2–3、峰值 7,原默认 6 偶尔成为硬约束,
319
+ // 且 quota_wait 7 天仅 1 次——并发位给足才可能吃满 coding plan 额度。
320
+ maxConcurrentRuns: int(config.maxConcurrentRuns ?? process.env.DSH_TEAM_MAX_RUNS, 10, 1, 16),
321
+ // 大卡拆分闸(写范围条目上限):单卡声明写范围超过该条数即拒绝派发,要求拆成
322
+ // 不相交写范围的子任务卡(parent_task_id 挂主卡)并行施工——超大范围卡与同项目
323
+ // 一切写运行互斥,是并行闸触发率低的主因(2026-11-13 生产实测 26%)。
324
+ maxWriteScopesPerTask: int(config.maxWriteScopesPerTask ?? process.env.DSH_TEAM_MAX_WRITE_SCOPES, 8, 1, 64),
318
325
  runTimeoutMs: int(config.runTimeoutMs ?? process.env.DSH_TEAM_RUN_TIMEOUT_MS, 60 * 60_000, 30_000, 6 * 60 * 60_000),
319
326
  // 0 关闭:单次运行的 token 上限,超出即中止,避免一个运行吃掉整月预算。
320
327
  maxRunTokens: int(config.maxRunTokens ?? process.env.DSH_TEAM_MAX_RUN_TOKENS, 0, 0, 500_000_000),
@@ -376,7 +383,7 @@ export function resolveConfig(config = {}) {
376
383
  githubWatch: parseGithubWatchEnv(config.githubWatch ?? process.env.DSH_TEAM_GITHUB_WATCH),
377
384
  githubPollMinutes: clampGithubPollMinutes(config.githubPollMinutes ?? process.env.DSH_TEAM_GITHUB_POLL_MINUTES),
378
385
  agentTeam: bool(config.agentTeam ?? process.env.DSH_TEAM_AGENT_TEAM, true),
379
- maxTeammates: int(config.maxTeammates ?? process.env.DSH_TEAM_MAX_TEAMMATES, 3, 1, 8),
386
+ maxTeammates: int(config.maxTeammates ?? process.env.DSH_TEAM_MAX_TEAMMATES, 5, 1, 8),
380
387
  // 会话使用的 agent preset:Router 会话不带写工具时,在这里指向一个受限 preset。
381
388
  routerPreset: String(config.routerPreset ?? process.env.DSH_TEAM_ROUTER_PRESET ?? '').trim(),
382
389
  workerPreset: String(config.workerPreset ?? process.env.DSH_TEAM_WORKER_PRESET ?? '').trim(),
package/src/db.js CHANGED
@@ -505,9 +505,12 @@ export function openDatabase(path) {
505
505
  }
506
506
 
507
507
  export class Store {
508
+ // 同连接事务深度(transaction 嵌套时内层加入外层,见 transaction 实现)。
509
+
508
510
  constructor(db, options = {} ) {
509
511
  this.db = db
510
512
  this.ftsEnabled = options.ftsEnabled === true
513
+ this.txDepth = 0
511
514
  }
512
515
 
513
516
  all(sql, ...params) {
@@ -532,12 +535,18 @@ export class Store {
532
535
  // 同栈投递」在事务内也只发生 runs/outbox 行写入(投递的宿主动作由提交后的 tick/领取
533
536
  // 路径执行)。tests/after-commit.test.ts 以源码扫描守门。
534
537
  transaction(fn) {
538
+ // 同连接嵌套事务直接加入外层(吸收账本化改造需要:setTaskStatus 等统一落点可能被
539
+ // 包在外层事务里调用);仅最外层 BEGIN/COMMIT,内层失败随外层一并回滚。
540
+ if (this.txDepth > 0) return fn()
535
541
  this.db.exec('BEGIN IMMEDIATE')
542
+ this.txDepth = 1
536
543
  try {
537
544
  const result = fn()
538
545
  this.db.exec('COMMIT')
546
+ this.txDepth = 0
539
547
  return result
540
548
  } catch (error) {
549
+ this.txDepth = 0
541
550
  try { this.db.exec('ROLLBACK') } catch {}
542
551
  throw error
543
552
  }
@@ -97,6 +97,17 @@ export function quotaRouteFor(bot , primary , fallback ) {
97
97
  return { mode: 'wait' , provider: primary.provider, resetAt: primary.resetAt }
98
98
  }
99
99
 
100
+ // 更严的一条额度记录(DSHBOTS-358):耗尽状态优先,其次恢复时间更晚者。
101
+ // Bot 换 provider 时用于合并旧键与新键的记录,避免迁移把正在生效的墙抹掉。
102
+ function stricterQuotaRow(a , b ) {
103
+ const aExhausted = quotaRowState(a).exhausted
104
+ const bExhausted = quotaRowState(b).exhausted
105
+ if (aExhausted !== bExhausted) return aExhausted ? a : b
106
+ const aAt = a?.reset_at ? Date.parse(a.reset_at) : 0
107
+ const bAt = b?.reset_at ? Date.parse(b.reset_at) : 0
108
+ return aAt >= bAt ? a : b
109
+ }
110
+
100
111
  export const botQuotaMethods = {
101
112
  // 单套 provider 的额度状态视图。provider 为空(bot 未配主模型)时视为无限制。
102
113
  botQuotaState(botId , provider ) {
@@ -223,6 +234,49 @@ export const botQuotaMethods = {
223
234
  return quotaRouteFor(bot, primary, fallback)
224
235
  },
225
236
 
237
+ // 换 provider 时迁移额度记录(DSHBOTS-358):额度墙按 (bot, provider) 存,
238
+ // Bot 改用别的 provider 后旧键会成孤儿(永远查不到、也永远清不掉)。
239
+ // 迁移口径:目标 provider 无记录 → 直接改键;目标已有记录 → 保留更严的一条(不抹掉
240
+ // 正在生效的墙),删掉旧键。仅 provider 真变才动,并落一条操作日志。
241
+ migrateBotQuotaProvider(botId , fromProvider , toProvider , actor = this.actor()) {
242
+ if (!botId || !fromProvider || !toProvider || fromProvider === toProvider) return null
243
+ const oldRow = this.store.get('SELECT * FROM bot_quota WHERE bot_id = ? AND provider = ?', botId, fromProvider)
244
+ const newRow = this.store.get('SELECT * FROM bot_quota WHERE bot_id = ? AND provider = ?', botId, toProvider)
245
+ if (!oldRow && !newRow) {
246
+ this.audit(actor, 'bot.quota_provider_changed', 'bot', botId, {
247
+ from: fromProvider, to: toProvider, migrated: false,
248
+ })
249
+ return null
250
+ }
251
+ const now = nowIso()
252
+ this.store.transaction(() => {
253
+ if (oldRow) {
254
+ if (!newRow) {
255
+ this.store.run(
256
+ 'UPDATE bot_quota SET provider = ?, updated_at = ? WHERE bot_id = ? AND provider = ?',
257
+ toProvider, now, botId, fromProvider,
258
+ )
259
+ } else {
260
+ const keep = stricterQuotaRow(oldRow, newRow)
261
+ if (keep === oldRow) {
262
+ this.store.run(
263
+ `UPDATE bot_quota SET state = ?, exhausted_at = ?, reset_at = ?, reset_source = ?, released_at = NULL,
264
+ released_by = NULL, error_code = ?, error_message = ?, updated_at = ?
265
+ WHERE bot_id = ? AND provider = ?`,
266
+ keep.state, keep.exhausted_at, keep.reset_at, keep.reset_source,
267
+ keep.error_code ?? null, keep.error_message ?? null, now, botId, toProvider,
268
+ )
269
+ }
270
+ this.store.run('DELETE FROM bot_quota WHERE bot_id = ? AND provider = ?', botId, fromProvider)
271
+ }
272
+ }
273
+ this.audit(actor, 'bot.quota_provider_changed', 'bot', botId, {
274
+ from: fromProvider, to: toProvider, migrated: Boolean(oldRow),
275
+ })
276
+ })
277
+ return this.botQuotaState(botId, toProvider)
278
+ },
279
+
226
280
  // 解析 bot 标识(id 或 name),供 director 工具按名字解除。
227
281
  resolveBotForQuota(input ) {
228
282
  const raw = String(input ?? '').trim()
@@ -288,6 +288,14 @@ export const botsMethods = {
288
288
  fields.push('provider = ?', 'model = ?', 'effort = ?', 'updated_at = ?')
289
289
  values.push(provider, model, effort, nowIso())
290
290
  this.store.run(`UPDATE bots SET ${fields.join(', ')} WHERE id = ?`, ...values, botId)
291
+ // DSHBOTS-358:provider 真变时迁移该 bot 的额度记录——额度墙按 (bot, provider) 存,
292
+ // 改 provider 后旧键会成孤儿。迁移保留更严的一条,不抹掉正在生效的墙。
293
+ if (provider !== bot.provider) {
294
+ this.migrateBotQuotaProvider(botId, bot.provider, provider, actor)
295
+ }
296
+ if (fallbackProvider !== bot.fallback_provider) {
297
+ this.migrateBotQuotaProvider(botId, bot.fallback_provider, fallbackProvider, actor)
298
+ }
291
299
  if (!snapshotUnchanged) {
292
300
  const version = (Number(bot.current_revision) || 0) + 1
293
301
  this.store.run(
@@ -150,11 +150,21 @@ export const chatMethods = {
150
150
  : null
151
151
  if (replyTo && !replyMessage) throw badRequest('引用的消息不存在')
152
152
  const mentions = parseMentions(body, members)
153
- // 目标解析:显式 @mention 优先(引用只作上下文);无显式 @ 时引用 bot 消息则定向该 bot(替换 owner 兜底);最后落 owner。
154
- const targets = (mentions.length > 0
153
+ // 群聊回复模式(吸收 dsh-agent-team 关注/取关理念,复用既有 reply_mode 字段):
154
+ // owner_first = 显式目标缺省时总监兜底(原行为);everyone = 无显式目标时全员响应;
155
+ // mentioned_only = 无显式 @/引用目标不唤醒任何 bot,消息留群给人看——直接信号
156
+ // (@mention、引用回复)在所有模式下都照旧直达。
157
+ const explicitTarget = mentions.length > 0
155
158
  ? mentions
156
- : members.filter(bot => bot.id === (replyMessage?.sender_type === 'bot' ? replyMessage.sender_id : project.owner_bot_id))
157
- ).slice(0, 3)
159
+ : members.filter(bot => bot.id === (replyMessage?.sender_type === 'bot' ? replyMessage.sender_id : null))
160
+ const group = this.groupOf(projectId)
161
+ const replyMode = group?.reply_mode ?? 'owner_first'
162
+ const fallback = replyMode === 'everyone'
163
+ ? members
164
+ : replyMode === 'mentioned_only'
165
+ ? []
166
+ : members.filter(bot => bot.id === project.owner_bot_id)
167
+ const targets = (explicitTarget.length > 0 ? explicitTarget : fallback).slice(0, 3)
158
168
  const messageId = this.insertMessage({
159
169
  projectId,
160
170
  senderType: actor.type,
@@ -164,6 +174,16 @@ export const chatMethods = {
164
174
  replyToId: replyMessage?.id ?? null,
165
175
  images,
166
176
  })
177
+ // mentioned_only 的环境消息(无显式 @/引用):不立即唤醒任何 bot,但总监默认 1 秒后
178
+ // 自动接单——发送回传带 runBots=[总监],UI 立刻立起总监的思考气泡(乐观排队行,
179
+ // typing-linger 复用),真实运行 1 秒后入列接管气泡。
180
+ const ambientDirectorClaim = replyMode === 'mentioned_only'
181
+ && explicitTarget.length === 0
182
+ && targets.length === 0
183
+ && members.some(bot => bot.id === project.owner_bot_id)
184
+ if (ambientDirectorClaim) {
185
+ setTimeout(() => { this.claimAmbientMessage(project.id, project.owner_bot_id, messageId) }, 1_000)
186
+ }
167
187
  for (const bot of targets) {
168
188
  this.enqueueOutbox({
169
189
  kind: 'chat_run',
@@ -179,7 +199,36 @@ export const chatMethods = {
179
199
  void considerVisionProxy(this, { bot, message: { id: messageId, project_id: project.id } })
180
200
  }
181
201
  void this.tick()
182
- return { messageId, runBots: targets.map(bot => bot.id) }
202
+ // 环境接单的回传:runBots 带总监供 UI 立思考气泡;真实运行由 1 秒后的接单入列。
203
+ // 保持与旧版一致的单一返回形态(条件展开会改变推断并破坏调用方类型)。
204
+ return {
205
+ messageId,
206
+ runBots: ambientDirectorClaim ? [project.owner_bot_id] : targets.map(bot => bot.id),
207
+ }
208
+ },
209
+
210
+ // mentioned_only 环境消息的延迟接单(1 秒):到点复核后按标准 chat_run 幂等键入列——
211
+ // 幂等键 `chat:<msg>:<bot>` 保证期间任何路径已派生同一运行时这里是 no-op。复核条件
212
+ // (总监可用、项目未归档、消息仍在)不满足则静默放弃,接单失败只 warn。
213
+ claimAmbientMessage(projectId, botId, messageId) {
214
+ try {
215
+ const project = this.store.get("SELECT id FROM projects WHERE id = ? AND status = 'active'", projectId)
216
+ const bot = this.store.get("SELECT id FROM bots WHERE id = ? AND status = 'active'", botId)
217
+ const message = this.store.get("SELECT id FROM messages WHERE id = ? AND project_id = ?", messageId, projectId)
218
+ if (!project || !bot || !message) return false
219
+ this.enqueueOutbox({
220
+ kind: 'chat_run',
221
+ payload: { projectId, botId, messageId },
222
+ projectId,
223
+ sourceId: messageId,
224
+ idempotencyKey: `chat:${messageId}:${botId}`,
225
+ })
226
+ void this.tick()
227
+ return true
228
+ } catch (error ) {
229
+ this.logger.warn?.('dsh-team: 环境消息延迟接单失败 %s: %s', messageId, error?.message ?? error)
230
+ return false
231
+ }
183
232
  },
184
233
 
185
234
  // /clear:清空本群全部聊天记录。任务、记忆等不受影响;操作进审计。
@@ -12,7 +12,12 @@ import { id, jsonParse, nowIso, redactSecrets, text, sanitizeFilename } from '..
12
12
  // 记忆上限(DSHBOTS-339):bot/project 作用域 active 记忆硬顶 MEMORY_CAP 条;触顶后新增被拒,
13
13
  // 须先整理到 MEMORY_COMPACT_TO 条以内才恢复放行(滞回,避免在阈值附近反复开关)。team 作用域不限。
14
14
  export const MEMORY_CAP = 64
15
- export const MEMORY_COMPACT_TO = 33
15
+ // 恢复线(DSHBOTS-360):触顶后须整理到 ≤MEMORY_COMPACT_TO 条才恢复新增(滞回带宽度 10 条)。
16
+ // 取 MEMORY_CAP−10:滞回带要宽过单轮最大突发,否则一轮自动沉淀就能把刚整理出的余量再次吃满。
17
+ // 10 条恰好覆盖记忆审查单轮最大突发(parseMemoryReview ≤10 条);规则沉淀(learnFromTask ≤2 条)
18
+ // 与审查同轮发生时会略超,属已知余量收紧,必要时可再放宽。早期取 33(≈CAP/2)等于强制腰斩,过苛:
19
+ // 61 条需清 28 条才解锁,恢复线本身成了新的阻塞源。
20
+ export const MEMORY_COMPACT_TO = MEMORY_CAP - 10
16
21
  // 单条记忆篇幅上限(owner 补充):content 不得超过 256 字。
17
22
  export const MEMORY_MAX_CHARS = 256
18
23
 
@@ -154,14 +159,32 @@ export const memoryMethods = {
154
159
  // 审查模型覆盖:配置了专用模型对时随运行下发(runs.model_* 三列既有通道,
155
160
  // startRun 的 modelOverrideFor 消费);未配置为 NULL,沿用 Bot 主模型。
156
161
  const target = memoryReviewModelTarget(this.config)
162
+ // DSHBOTS-358:记忆审查属内部运行,同样接额度路由——主 provider 耗尽时走备用模型;
163
+ // 主备都耗尽则不带模型覆盖,留 queued 等恢复(调度器额度闸门兜底)。
164
+ // 专用审查模型配在别的 provider 且该 provider 未耗尽时,专用模型优先。
165
+ const routing = this.quotaRoutingForBot(bot)
166
+ let reviewProvider = target?.provider ?? null
167
+ let reviewModel = target?.model ?? null
168
+ let reviewEffort = null
169
+ if (routing.mode === 'fallback') {
170
+ reviewProvider = routing.provider
171
+ reviewModel = routing.model
172
+ reviewEffort = routing.effort ?? null
173
+ } else if (routing.mode === 'wait') {
174
+ const dedicated = target ? this.botQuotaState(bot.id, target.provider) : null
175
+ if (!target || dedicated?.exhausted) {
176
+ reviewProvider = null
177
+ reviewModel = null
178
+ }
179
+ }
157
180
  const reviewRunId = id('run')
158
181
  const createdAt = nowIso()
159
182
  this.store.run(
160
183
  `INSERT INTO runs(id, project_id, bot_id, task_id, kind, mode, trigger_type, trigger_ref, status,
161
- attempt, idempotency_key, model_provider, model_model, queued_at)
162
- VALUES (?, ?, ?, NULL, 'memory_review', 'read', 'memory_review', ?, 'queued', 1, ?, ?, ?, ?)`,
184
+ attempt, idempotency_key, model_provider, model_model, model_effort, queued_at)
185
+ VALUES (?, ?, ?, NULL, 'memory_review', 'read', 'memory_review', ?, 'queued', 1, ?, ?, ?, ?, ?)`,
163
186
  reviewRunId, project.id, bot.id, sourceRunId, `memory_review:${sourceRunId}`,
164
- target?.provider ?? null, target?.model ?? null, createdAt,
187
+ reviewProvider, reviewModel, reviewEffort, createdAt,
165
188
  )
166
189
  this.store.run(
167
190
  'INSERT INTO run_events(id, run_id, type, message, created_at) VALUES (?, ?, ?, ?, ?)',
@@ -193,6 +216,11 @@ export const memoryMethods = {
193
216
  const source = `run:${sourceRunId}`
194
217
  let applied = 0
195
218
  let deduped = 0
219
+ // 拒写留痕(DSHBOTS-360):审查写入被拒时把拒因带内化——写进 run_events,
220
+ // 不再只丢一条系统日志(run_events 只说「写入 0 条」而无人知道为什么,锁定期会无限期无人处理)。
221
+ let rejected = 0
222
+ let capacityRejected = 0
223
+ const rejectReasons = []
196
224
  // 同一次审查里重复的条目、以及同一来源重复触发的审查,写入前都按来源+内容去重。
197
225
  const seen = new Set()
198
226
  for (const item of items) {
@@ -231,14 +259,23 @@ export const memoryMethods = {
231
259
  })
232
260
  applied += 1
233
261
  } catch (writeError ) {
234
- this.logger.warn?.('dsh-team: 记忆审查写入失败:%s', writeError?.message ?? writeError)
262
+ rejected += 1
263
+ const reason = String(writeError?.message ?? writeError)
264
+ // 容量锁(conflict 409)与其它拒因分开计数:容量锁意味着作用域处在整理锁定期,需要人处理。
265
+ if (writeError?.status === 409) capacityRejected += 1
266
+ if (rejectReasons.length < 3) rejectReasons.push(reason)
267
+ // 同主题覆盖写降级属可选能力:owner 未点头,本卡不实现(不改写既有条目、不把被拒条目转 pending 堆积)。
268
+ this.logger.warn?.('dsh-team: 记忆审查写入失败:%s', reason)
235
269
  }
236
270
  }
271
+ const rejectNote = rejected
272
+ ? `,拒写 ${rejected} 条${capacityRejected ? `(其中 ${capacityRejected} 条因容量锁被拒)` : ''}:${rejectReasons.join(';')}`
273
+ : ''
237
274
  this.store.run(
238
275
  'INSERT INTO run_events(id, run_id, type, message, created_at) VALUES (?, ?, ?, ?, ?)',
239
- id('evt'), reviewRun.id, 'reviewed', `记忆审查完成,写入 ${applied} 条${deduped ? `,去重 ${deduped} 条` : ''}`, nowIso(),
276
+ id('evt'), reviewRun.id, 'reviewed', `记忆审查完成,写入 ${applied} 条${deduped ? `,去重 ${deduped} 条` : ''}${rejectNote}`, nowIso(),
240
277
  )
241
- return { applied, deduped }
278
+ return { applied, deduped, rejected, capacityRejected }
242
279
  },
243
280
 
244
281
  // 记忆写入权限:用户可写任意作用域;Bot 只能写自己的记忆、是成员的项目记忆,
@@ -279,7 +316,8 @@ export const memoryMethods = {
279
316
  },
280
317
  memoryCapacityMessage(scopeType, scopeId, count, latched = false) {
281
318
  const label = scopeType === 'bot' ? `Bot(${scopeId})` : `项目(${scopeId})`
282
- // 锁定带(滞回标志在、34–63 条):如实说明此前触顶、现处整理锁定期,不得谎称「已达 N/64」。
319
+ // 锁定带(滞回标志在、(MEMORY_COMPACT_TO, MEMORY_CAP) 之间):如实说明此前触顶、现处整理锁定期,
320
+ // 不得谎称「已达 N/64」。
283
321
  if (latched) {
284
322
  return `${label}记忆此前触顶 ${MEMORY_CAP} 条上限,现处整理锁定期(当前 ${count} 条),新增被拒绝;需整理到 ≤${MEMORY_COMPACT_TO} 条恢复新增:去废弃(team_memory_cleanup 清理已闭环任务或过时主题)、去冗与融合(同主题 team_memory_write 覆盖写、合并相近条目);同主题覆盖写不受影响。`
285
323
  }
@@ -512,17 +550,53 @@ export const memoryMethods = {
512
550
  // 三入口共用 ownerContextFor 权威鉴权(仅项目总监,单聊/成员拒绝);
513
551
  // 不改宿主 team_remember 语义,插件层独立封装。
514
552
 
515
- // 把 scope 枚举解析到总监会话所在的具体作用域:bot=总监自己,project=会话项目,team=全团队。
516
- resolveOwnerMemoryScope(ownerCtx, scope) {
553
+ // 记忆工具上下文:任意项目群 Bot 可自管自己的 bot 域(成员 Bot 触顶后的合法自救通道,
554
+ // 总监可经 bot 点名代管任意 Bot);project/team 域仍只归总监(ownerContextFor 同款判定)。
555
+ memoryActorFor(sessionId) {
556
+ const binding = this.store.get('SELECT * FROM session_bindings WHERE session_id = ?', sessionId)
557
+ if (!binding) throw forbidden('只有项目群中的 Bot 可以执行该操作')
558
+ const project = binding.project_id ? this.projectRow(binding.project_id) : null
559
+ return {
560
+ binding,
561
+ project,
562
+ actor: { type: 'bot', id: binding.bot_id },
563
+ isOwner: Boolean(project && project.owner_bot_id === binding.bot_id),
564
+ }
565
+ },
566
+ resolveMemoryScopeFor(sessionId, input) {
567
+ const ctx = this.memoryActorFor(sessionId)
568
+ const scopeType = ['bot', 'project', 'team'].includes(input.scope) ? input.scope : null
569
+ if (!scopeType) throw badRequest('记忆作用域无效')
570
+ if (ctx.isOwner) {
571
+ const resolved = this.resolveOwnerMemoryScope(ctx, input.scope, input.bot)
572
+ return { ...resolved, actor: ctx.actor, project: ctx.project, isOwner: true }
573
+ }
574
+ // 成员:只放行自己的 bot 域;点名参数仅接受自己(点名他人即拒绝)。
575
+ if (scopeType !== 'bot') {
576
+ throw forbidden('成员只能管理自己的 bot 域记忆;项目/团队域的整理请由项目总监执行')
577
+ }
578
+ if (input.bot != null && String(input.bot).trim() !== '') {
579
+ const named = this.resolveBotForQuota(input.bot)
580
+ if (named.id !== ctx.binding.bot_id) throw forbidden('Bot 只能点名管理自己的记忆')
581
+ }
582
+ return { scopeType, scopeId: ctx.binding.bot_id, actor: ctx.actor, project: ctx.project, isOwner: false }
583
+ },
584
+
585
+ // 把 scope 枚举解析到总监会话所在的具体作用域:bot=总监自己(bot_ref 点名时为该 Bot,
586
+ // 成员 Bot 超限整理的合法通道——resolveBotForQuota 按 id 或精确名解析,任意总监可点名),
587
+ // project=会话项目,team=全团队。
588
+ resolveOwnerMemoryScope(ownerCtx, scope, botRef = null) {
517
589
  const scopeType = ['bot', 'project', 'team'].includes(scope) ? scope : null
518
590
  if (!scopeType) throw badRequest('记忆作用域无效')
519
- const scopeId = scopeType === 'bot' ? ownerCtx.binding.bot_id : scopeType === 'project' ? ownerCtx.project.id : 'team'
591
+ let scopeId = scopeType === 'project' ? ownerCtx.project.id : scopeType === 'team' ? 'team' : ownerCtx.binding.bot_id
592
+ if (scopeType === 'bot' && botRef != null && String(botRef).trim() !== '') {
593
+ scopeId = this.resolveBotForQuota(botRef).id
594
+ }
520
595
  return { scopeType, scopeId }
521
596
  },
522
597
 
523
- memoryListFromBot(sessionId, input = {}) {
524
- const ownerCtx = this.ownerContextFor(sessionId)
525
- const { scopeType, scopeId } = this.resolveOwnerMemoryScope(ownerCtx, input.scope ?? 'project')
598
+ memoryListFromBot(sessionId, input = {}) {
599
+ const { scopeType, scopeId } = this.resolveMemoryScopeFor(sessionId, { scope: 'project', ...input })
526
600
  const keyword = text(input.topic, 200).trim()
527
601
  const limitN = Math.min(200, Math.max(1, Number(input.limit) || 50))
528
602
  const like = `%${keyword}%`
@@ -539,9 +613,7 @@ export const memoryMethods = {
539
613
  // 写入/同名覆盖:同 scope+topic 已有 active 记忆时原地更新(revision+1、事件留痕),
540
614
  // 不再叠新条;无同名时走 createMemory 正常创建。
541
615
  memoryWriteFromBot(sessionId, input) {
542
- const ownerCtx = this.ownerContextFor(sessionId)
543
- const { scopeType, scopeId } = this.resolveOwnerMemoryScope(ownerCtx, input.scope)
544
- const actor = ownerCtx.actor
616
+ const { scopeType, scopeId, actor } = this.resolveMemoryScopeFor(sessionId, input)
545
617
  const topic = text(input.topic, 120)
546
618
  if (!topic) throw badRequest('缺少记忆主题')
547
619
  const existing = this.store.get(
@@ -584,13 +656,12 @@ export const memoryMethods = {
584
656
  // before 与 topics/task 可组合,按 AND 交集收窄;三者全缺即拒绝(不做「全清」缺省)。
585
657
  // 逐条 memory_events 留痕 + 一笔 memory.cleanup 审计列出被清条目。
586
658
  memoryCleanupFromBot(sessionId, input) {
587
- const ownerCtx = this.ownerContextFor(sessionId)
588
- const { project, actor } = ownerCtx
589
- const { scopeType, scopeId } = this.resolveOwnerMemoryScope(ownerCtx, input.scope)
659
+ const { scopeType, scopeId, project, actor } = this.resolveMemoryScopeFor(sessionId, input)
590
660
  const topics = (Array.isArray(input.topics) ? input.topics : []).map(item => text(item, 120)).filter(Boolean)
591
661
  let taskLabel = null
592
662
  let taskTopics = []
593
663
  if (input.task) {
664
+ if (!project) throw forbidden('单聊会话不在项目中,无法按任务口径清理')
594
665
  const task = this.resolveBotTask(project, input.task)
595
666
  if (!['done', 'canceled'].includes(task.status)) {
596
667
  throw badRequest(`仅已闭环(done/canceled)任务的历史记录可清理,${project.key}-${task.number} 当前为 ${task.status}`)