dsh-team-bots 0.2.347 → 0.2.393

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 (52) hide show
  1. package/README.md +12 -2
  2. package/docs/README.zh.md +12 -2
  3. package/docs/assets/global-config.png +0 -0
  4. package/docs/assets/global-config.zh.png +0 -0
  5. package/docs/assets/tasks.png +0 -0
  6. package/docs/assets/tasks.zh.png +0 -0
  7. package/docs/assets/usage.png +0 -0
  8. package/docs/assets/usage.zh.png +0 -0
  9. package/index.js +2 -0
  10. package/package.json +2 -1
  11. package/src/config.js +55 -10
  12. package/src/db-migrations.js +144 -9
  13. package/src/paths.js +12 -0
  14. package/src/services/approvals.js +12 -2
  15. package/src/services/core.js +2 -1
  16. package/src/services/notify.js +71 -1
  17. package/src/services/proposals.js +36 -1
  18. package/src/services/questions.js +16 -3
  19. package/src/services/run-finish.js +18 -3
  20. package/src/services/runs.js +369 -34
  21. package/src/services/runtime/prompt.js +135 -88
  22. package/src/services/runtime/session.js +260 -72
  23. package/src/services/scheduler.js +135 -97
  24. package/src/services/task-dispatch.js +112 -5
  25. package/src/services/task-review.js +19 -1
  26. package/src/services/task-runs.js +53 -15
  27. package/src/services/tasks.js +81 -0
  28. package/src/services/wechat.js +23 -21
  29. package/src/subagent-ledger.js +165 -0
  30. package/src/tools.js +5 -5
  31. package/src/wechat/commands.js +3 -1
  32. package/ui/app.js +4 -14
  33. package/ui/i18n/en/chat.js +11 -11
  34. package/ui/i18n/en/common.js +0 -12
  35. package/ui/i18n/en/nav.js +0 -4
  36. package/ui/i18n/en/settings.js +14 -9
  37. package/ui/i18n/en/tasks.js +0 -1
  38. package/ui/i18n/en/usage.js +4 -7
  39. package/ui/i18n/zh/chat.js +11 -11
  40. package/ui/i18n/zh/common.js +0 -12
  41. package/ui/i18n/zh/nav.js +0 -4
  42. package/ui/i18n/zh/settings.js +13 -9
  43. package/ui/i18n/zh/tasks.js +0 -1
  44. package/ui/i18n/zh/usage.js +4 -7
  45. package/ui/modules/cards.js +19 -5
  46. package/ui/modules/composer.js +16 -3
  47. package/ui/modules/i18n.js +10 -0
  48. package/ui/modules/modal-forms.js +15 -8
  49. package/ui/modules/settings.js +9 -0
  50. package/ui/modules/util.js +0 -2
  51. package/ui/styles/frame.css +0 -28
  52. package/ui/styles/wide.css +0 -3
@@ -1,49 +1,50 @@
1
- // src/services/runtime/prompt.js —— 提示词构造域
1
+ // src/services/runtime/prompt.ts —— 提示词构造域
2
2
  // 按运行类型拼装系统提示词、单聊提示词与引用行,并套用文件权限档位。
3
3
  // 本文件只放方法体,方法挂到 DshRuntime 原型上(见 src/runtime.js 的 defineMethods 调用),
4
4
  // 因此方法体内的 this 与拆分前完全一致。
5
5
  //
6
- // 模板段序原则:各运行提示词一律「静态指令段前置、每卡/每消息变化字段后置」。
7
- // 前缀缓存按最长公共前缀匹配,静态段在变体之后会导致跨卡派发在描述处分叉、
8
- // 固定段吃不到缓存。调整任一模板段顺序时必须保持该原则(tests/prompt-prefix-order.test.js 守门)。
6
+ // 段序原则:运行提示词一律「静态指令段前置、随卡/随消息变化的字段后置」。
7
+ // 前缀缓存按最长公共前缀匹配,静态段放在变化段之后会让跨卡派发在描述处分叉、
8
+ // 固定段吃不到缓存。调整任何模板段顺序都必须保持该原则(tests/prompt-prefix-order.test.ts 守门)。
9
9
 
10
10
  import { join } from 'node:path'
11
11
  import { scanProjectSkills } from '../../project-skills.js'
12
12
  import { id, nowIso, parseDisabledSkills } from '../../util.js'
13
13
  import { dmPrompt, replyDeliveryPrompt } from '../../botmsg.js'
14
14
  import { rolloverPendingKey, rolloverSummaryKey } from '../../config.js'
15
+ import { taskDeadlineInfo } from '../tasks.js'
15
16
  import { readWriteScopes } from '../write-scopes.js'
16
- import { sanitizeTmpBotDirName } from '../../paths.js'
17
+ import { displayPath, sanitizeTmpBotDirName } from '../../paths.js'
17
18
 
18
19
  // 与 DSH 宿主 dsh-sandbox-policy 的 SANDBOX_MODES 保持一致;库里值不合法时不向宿主写覆盖。
19
20
  export const SANDBOX_MODES = ['read-only', 'workspace-write', 'danger-full-access']
20
21
 
21
- // system 区按 session id 冻结的 LRU 上限:防会话累积泄漏(session_bindings 只增不改,
22
- // 死会话不再求值,条目只会等 LRU 淘汰)。
22
+ // 系统提示词按会话 id 冻结的 LRU 上限:session_bindings 只增不改,死会话不再求值,
23
+ // 靠上限淘汰防会话累积泄漏。
23
24
  export const PROMPT_FREEZE_LIMIT = 256
24
25
 
25
- // 增量尾窗(DSHBOTS-96 P1-1):无水位(新会话/进程重启)回退尾 12 条全量窗给足上下文;
26
- // 有水位只注入其后新消息;上限 24 条兜住多 run 并发共用 session 时的积压。
26
+ // 增量尾窗(DSHBOTS-96 P1-1):无水位(新会话或进程重启)回退尾 12 条全量窗给足上下文;
27
+ // 有水位只注入其后的新消息;上限 24 条兜住多运行并发共用会话时的积压。
27
28
  export const RECENT_FALLBACK_LIMIT = 12
28
29
  export const RECENT_INCREMENTAL_LIMIT = 24
29
30
 
30
- // 无信息量的 system 短状态通知(DSHBOTS-96 P3-1):状态已由 Open tasks 与任务评论通道
31
- // 覆盖,不再重复进尾窗(命中即整条跳过,不占窗位)。
31
+ // 无信息量的系统短状态通知(DSHBOTS-96 P3-1):状态已由 Open tasks 与任务评论通道覆盖,
32
+ // 不再重复进尾窗(命中即整条跳过,不占窗位)。
32
33
  export const NOISE_SYSTEM_BODY = /^(已写入.+记忆。|任务 \S+ 验收通过。|密钥 \S+ 的请求被拒绝。)$/
33
34
 
34
- // 沙箱档位按运行类型收紧:一切非写运行(dm/dm_reply/chat/memory_review/solo_chat/review/handle
35
- // 等 mode!=='write')物理降只读,越权写入由宿主沙箱层拒绝;写运行沿用 bot.file_policy;
36
- // run 为空(无运行上下文的会话建立)保持 bot.file_policy 现行为。
35
+ // 沙箱档位按运行类型收紧:一切非写运行(mode!=='write',如 dm/dm_reply/chat/review 等)
36
+ // 物理降只读,越权写入由宿主沙箱层拒绝;写运行沿用 bot.file_policy;
37
+ // 无运行上下文(run 为空)时同样保持 bot.file_policy。
37
38
  export function sandboxModeForRun(run, bot) {
38
39
  return run && run.mode !== 'write' ? 'read-only' : bot?.file_policy
39
40
  }
40
41
 
41
42
  // 生效沙箱档(DSHBOTS-156):任务派发可选 sandbox 覆盖后的最终口径,run_events 与视图共用。
42
- // - 非 write 运行恒 read-only(来源 run_type):覆盖只作用于任务写运行,dm_reply 回投
43
- // 任务会话等读运行不得因任务带覆盖而放宽只读;
44
- // - 写运行取 tasks.sandbox_override(来源 override),且只在不比 bot 配置档更宽时生效
43
+ // - 非写运行恒 read-only(来源 run_type):覆盖只作用于写运行,dm_reply 回投任务会话等
44
+ // 读运行不得因任务带覆盖而放宽只读;
45
+ // - 写运行取 tasks.sandbox_override(来源 override),只在不比 bot 配置档更宽时生效
45
46
  // (只收紧不放大:运行侧兜底,防旁路落库的旧覆盖在换负责人后放大权限);
46
- // - 其余回落 bot.file_policy(来源 bot_config);run 为空保持 bot.file_policy 现行为。
47
+ // - 其余回落 bot.file_policy(来源 bot_config)。
47
48
  // 覆盖或配置档不合法(不在 SANDBOX_MODES)时不采用,落 bot_config 由 applyFilePolicy 拦截。
48
49
  export function effectiveSandbox(run, bot, task) {
49
50
  if (run && run.mode !== 'write') return { mode: 'read-only', source: 'run_type' }
@@ -57,9 +58,9 @@ export function effectiveSandbox(run, bot, task) {
57
58
 
58
59
  const sessionIdOf = context => context?.agent?.id ?? context?.session?.id ?? context?.sessionId
59
60
 
60
- // 任务描述超长截断管线(DSHBOTS-113,事故 m_33bddb;DSHBOTS-254 起任务分支与 review/handle 同口径):
61
- // 任务全文拼进提示词可能顶爆 400 上下文,超过 8K 字符截断并注明,消费方据此只基于
62
- // 截断内可见的部分下结论并声明盲区;标题/状态/写范围/任务评论在截断点之外恒在场。
61
+ // 任务描述截断(DSHBOTS-113 事故 m_33bddb;DSHBOTS-254 起任务分支与 review/handle 同口径):
62
+ // 全文拼进提示词可能顶爆 400 上下文,超过 8K 字符即截断并注明,消费方只基于可见部分
63
+ // 下结论并声明盲区;标题/状态/写范围/任务评论在截断点之外恒在场。
63
64
  function truncateTaskDescription(raw) {
64
65
  const text = raw || '(no description)'
65
66
  return text.length > 8_000
@@ -68,11 +69,10 @@ function truncateTaskDescription(raw) {
68
69
  }
69
70
 
70
71
  export const promptMethods = {
71
- // system 区会话级冻结(D-85 方案 B):首次求值后按 session id 缓存字节,
72
- // 同会话后续每次宿主 assemble 都命中缓存,保证 system 区逐字节稳定,
73
- // 前缀缓存不被本插件作废;连带把 secrets/skill_bindings/项目技能扫描
74
- // 等求值压缩到每会话一次。空结果不冻结(会话建立早期 binding 未落库时
75
- // 返回 '',等首次非空结果再定格)。易变的记忆块不走这里,见 memoryContextFor。
72
+ // 系统提示词会话级冻结(D-85 方案 B):首次求值后按会话 id 缓存字节,同会话此后逐字节
73
+ // 稳定,前缀缓存不被本插件作废;密钥、技能绑定、项目技能扫描等求值也随之压缩到每会话
74
+ // 一次。空结果不冻结(会话建立早期绑定未落库时返回 '',等首次非空结果再定格)。
75
+ // 易变的记忆块不走这里,见 memoryContextFor。
76
76
  systemPromptFor(context) {
77
77
  const sessionId = sessionIdOf(context)
78
78
  if (sessionId) {
@@ -134,13 +134,13 @@ export const promptMethods = {
134
134
  const sharedSkills = this.config.skillRoot
135
135
  const sharedRules = [
136
136
  disabledSkills.length === 0
137
- ? `- The shared skill library is mounted at \`${sharedSkills}/skills\`; use installed skills when relevant.`
138
- : `- The shared skill library is mounted at \`${sharedSkills}/skills\`; use installed skills when relevant. The following skills are disabled for this project and must not be invoked: ${disabledSkills.map(slug => `\`${slug}\``).join(', ')}.`,
137
+ ? `- The shared skill library is mounted at \`${displayPath(sharedSkills)}/skills\`; use installed skills when relevant.`
138
+ : `- The shared skill library is mounted at \`${displayPath(sharedSkills)}/skills\`; use installed skills when relevant. The following skills are disabled for this project and must not be invoked: ${disabledSkills.map(slug => `\`${slug}\``).join(', ')}.`,
139
139
  bindings.length > 0
140
140
  ? `- Pinned skill versions for this project: ${bindings.map(item => `\`${item.slug}\`@${item.version ?? 'latest'}`).join(', ')}.`
141
141
  : '- No skill version is pinned for this project; use the current published version.',
142
142
  '- Work only inside this project workspace unless the user explicitly authorizes another mounted path.',
143
- `- The shared skill library at \`${sharedSkills}\` is read-only for you; publish skill changes through \`team_propose_evolution\` so the user can approve them.`,
143
+ `- The shared skill library at \`${displayPath(sharedSkills)}\` is read-only for you; publish skill changes through \`team_propose_evolution\` so the user can approve them.`,
144
144
  '- You cannot change your own role, model, instructions or skills directly; propose the change instead.',
145
145
  '- Never invent file changes or tool results. Report blockers precisely.',
146
146
  '- Reply in the user’s language.',
@@ -149,7 +149,7 @@ export const promptMethods = {
149
149
  const projectSkillRules = projectSkills.length === 0
150
150
  ? []
151
151
  : [
152
- `- Project skill pools are mounted at \`${projectDir}/.agents/skills\`, \`${projectDir}/.claude/skills\`, \`${projectDir}/.codex/skills\`; skills found there are available in this project and take precedence over a shared skill with the same name.`,
152
+ `- Project skill pools are mounted at \`${displayPath(projectDir)}/.agents/skills\`, \`${displayPath(projectDir)}/.claude/skills\`, \`${displayPath(projectDir)}/.codex/skills\`; skills found there are available in this project and take precedence over a shared skill with the same name.`,
153
153
  `- Project skills available here: ${projectSkills.map(skill => `\`${skill.name}\``).join(', ')}.`,
154
154
  ]
155
155
  const collaborationRules = taskSession
@@ -202,7 +202,7 @@ You can spawn child agents (\`subagent\` / \`subagent_fork\`) or named teammates
202
202
  '## Current project',
203
203
  `- Name: ${project.name}`,
204
204
  `- Key: ${project.key}`,
205
- `- Workspace: ${project.production_dir || join(this.config.workspace, project.slug)}`,
205
+ `- Workspace: ${displayPath(project.production_dir || join(this.config.workspace, project.slug))}`,
206
206
  `- Temp files discipline: write every temporary or intermediate file (scratch scripts, probe outputs, downloaded artifacts) under \`.tmp/bots/${sanitizeTmpBotDirName(bot.name)}/\` inside the workspace; create that directory if it is missing. Never scatter temp files elsewhere in the project.`,
207
207
  roleLine,
208
208
  '',
@@ -211,10 +211,10 @@ You can spawn child agents (\`subagent\` / \`subagent_fork\`) or named teammates
211
211
  ].filter(Boolean).join('\n')
212
212
  },
213
213
 
214
- // 记忆块(D-85 方案 A):不再进 system 区(那会每步重烧全前缀缓存),改注册为
215
- // 宿主 systemPrompt.context() 的动态贡献——宿主把它渲染成历史尾部的 user 快照,
216
- // 文本变化时才追加新快照,前缀缓存不动,进行中会话仍能看到新落库的记忆。
217
- // 因此本方法不做会话冻结:宿主每步重求值是有意为之,只有这一条小 SQL。
214
+ // 记忆块(D-85 方案 A):不进系统区(那会每步重烧全前缀缓存),改注册为宿主
215
+ // systemPrompt.context() 的动态贡献——宿主把它渲染成历史尾部的用户快照,文本变化时
216
+ // 才追加新快照,前缀缓存不动,进行中会话仍能看到新落库的记忆。因此本方法不做会话
217
+ // 冻结:宿主每步重求值是有意为之,只有一条小查询。
218
218
  memoryContextFor(context) {
219
219
  const sessionId = sessionIdOf(context)
220
220
  const binding = this.bindingOfSession(sessionId)
@@ -264,23 +264,22 @@ You can spawn child agents (\`subagent\` / \`subagent_fork\`) or named teammates
264
264
  '',
265
265
  '## Solo conversation',
266
266
  `- This is a one-on-one conversation with the user, outside any project.`,
267
- `- Your workspace for this conversation is \`${workspace}\`; work inside it when the user asks you to produce or store files.`,
267
+ `- Your workspace for this conversation is \`${displayPath(workspace)}\`; work inside it when the user asks you to produce or store files.`,
268
268
  '- Project tools (team_assign_task, team_review_task) do not apply here because there is no project context. If the user wants project work, suggest opening that project instead.',
269
269
  '- Use `team_remember` with scope bot or team for durable facts worth keeping; scope project is unavailable in this conversation. Never store secrets or credentials.',
270
- `- The shared skill library is mounted at \`${this.config.skillRoot}/skills\`; use installed skills when relevant. The library at \`${this.config.skillRoot}\` is read-only for you; publish skill changes through \`team_propose_evolution\`.`,
270
+ `- The shared skill library is mounted at \`${displayPath(this.config.skillRoot)}/skills\`; use installed skills when relevant. The library at \`${displayPath(this.config.skillRoot)}\` is read-only for you; publish skill changes through \`team_propose_evolution\`.`,
271
271
  '- You cannot change your own role, model, instructions or skills directly; propose the change instead.',
272
272
  '- Never invent file changes or tool results. Report blockers precisely.',
273
273
  '- Reply in the user’s language.',
274
274
  ].filter(Boolean).join('\n')
275
275
  },
276
276
 
277
- // 把按运行类型收紧后的档位(effectiveSandbox)写成宿主 session 的文件沙箱覆盖。
278
- // 宿主原生写路径 setSandboxMode(session, mode) 就是 session.append('sandbox/mode', { mode }),
279
- // 这里等价直调(插件不依赖宿主包),事件 log-only、replay 持久、下次受限调用生效。
280
- // 会话已是目标档位就不重复追加;设置失败只告警不阻断会话(沙箱回落宿主默认)。
281
- // DSHBOTS-156:档位口径含任务派发覆盖(只收紧不放大);带运行上下文时把生效档与来源
282
- // 落 run_events(type='sandbox_mode',复用会话也每次留档——run_events 是运行时间线,
283
- // 每条运行都该有自己的一档记录,与 sandbox/mode 追加的去重无关)。
277
+ // 把收紧后的档位(effectiveSandbox)写成宿主会话的文件沙箱覆盖:等价直调宿主的
278
+ // setSandboxMode(session, mode),即 session.append('sandbox/mode', { mode })(插件不依赖
279
+ // 宿主包),事件 log-only、replay 持久、下次受限调用生效。已是目标档位就不重复追加;
280
+ // 失败只告警不阻断会话(沙箱回落宿主默认)。
281
+ // DSHBOTS-156:带运行上下文时把生效档与来源落 run_events(type='sandbox_mode')——
282
+ // run_events 是运行时间线,复用会话的每条运行也各自留档,与 sandbox/mode 追加的去重无关。
284
283
  applyFilePolicy(agent, bot, run , task ) {
285
284
  const { mode, source } = effectiveSandbox(run, bot, task)
286
285
  if (!SANDBOX_MODES.includes(mode)) return
@@ -305,15 +304,15 @@ You can spawn child agents (\`subagent\` / \`subagent_fork\`) or named teammates
305
304
  }
306
305
  },
307
306
 
308
- // 增量水位尾窗(DSHBOTS-96 P1-1):每 session 维护已注入的 rowid 水位,此后每轮只注入
307
+ // 增量水位尾窗(DSHBOTS-96 P1-1):每会话维护已注入的 rowid 水位,此后每轮只注入
309
308
  // 水位之后的新消息,替代旧的「尾 12 条×240 摘录每轮重烧」。语义:
310
- // - 无水位(新会话首次注入/进程重启)→ 回退尾 RECENT_FALLBACK_LIMIT 条全量窗;
311
- // - 有水位 → rowid > 水位的新消息(rowid 单调递增,与 created_at 排序一致);
312
- // - 水位推进到取窗时刻该表 scope 内最大 rowid,只前进不回退;空窗也推进(越过触发消息);
313
- // - 多 run 并发共用同一 session:先取窗者把积压新消息一次带走并前移水位,后取窗者窗口
314
- // 为空——两条 prompt 进同一宿主 session 历史,消息不丢不重;
309
+ // - 无水位(新会话或进程重启)→ 回退尾 RECENT_FALLBACK_LIMIT 条全量窗;
310
+ // - 有水位 → 取 rowid > 水位的新消息(rowid 单调递增,与 created_at 排序一致);
311
+ // - 水位推进到取窗时刻该表 scope 内最大 rowid,只进不退;空窗也推进(越过触发消息);
312
+ // - 多运行并发共用同一会话:先取窗者带走积压并前移水位,后取窗者窗口为空——
313
+ // 两条提示词进同一宿主会话历史,消息不丢不重;
315
314
  // - excludeId 排除本轮触发消息(正文已在 # Group message / # Solo message 完整呈现,不再双份)。
316
- // sessionId 为空(无会话上下文的直接调用)时不读不写水位,等价旧的固定尾窗。
315
+ // 无会话上下文时不读不写水位,等价旧的固定尾窗。
317
316
  watermarkWindow({ sessionId, table, columns, where, params, excludeId }) {
318
317
  const advance = this.store.get(`SELECT MAX(rowid) AS m FROM ${table} WHERE ${where}`, ...params)?.m ?? null
319
318
  const watermark = sessionId ? this.messageWatermarks.get(sessionId) : undefined
@@ -337,7 +336,7 @@ You can spawn child agents (\`subagent\` / \`subagent_fork\`) or named teammates
337
336
  },
338
337
 
339
338
  // 结转摘要块(DSHBOTS-145):新会话首轮提示词注入旧会话的交接摘要。
340
- // 一次性语义(照 recovery note 手法):读到的同时即刻清零,同一摘要只注入一次。
339
+ // 一次性语义(同 recovery note 手法):读到即清零,同一摘要只注入一次。
341
340
  // 消费闸(DSHBOTS-213):仅当本轮会话就是结转新建的目标会话(pending 标记命中)才消费;
342
341
  // 无摘要或目标不是本会话时返回空串,摘要保留到真正的结转,防止被无关轮次提前清零。
343
342
  rolloverSummaryBlock(bot, project, sessionId) {
@@ -365,13 +364,29 @@ This conversation has reached its turn limit and will be rolled over to a fresh
365
364
  - Cover: work in progress (what was being done and where it stopped), key decisions already made, and open questions or blockers.
366
365
  - Do not repeat the task description or anything already recorded in long-term memory.
367
366
  - Do not call any tool and do not write files. Reply with the summary text only.`
367
+ },
368
+ // 闲时总结压缩运行提示词(DSHBOTS-286):在原会话上下文里让 bot 自写连续性总结。
369
+ // 压缩不等于结转:会话不换,总结只为收敛上下文头绪;宿主未暴露历史截断接口,
370
+ // 持久事实应趁此轮落记忆或任务评论(能力边界见 ADR「结转与压缩」)。
371
+ sessionCompactPrompt({ bot, project }) {
372
+ const header = project
373
+ ? [`Project: ${project.name} (${project.key})`, `You are: ${bot.name}`].join('\n')
374
+ : [`You are: ${bot.name}`, 'Mode: one-on-one conversation (outside projects)'].join('\n')
375
+ return `${header}
376
+
377
+ # Session compaction request
378
+ This conversation has grown long and is now idle. Write a working summary to keep future turns focused.
379
+ - Write in Chinese, plain prose, at most 300 characters.
380
+ - Cover: current focus, work in progress with its exact state, and the next concrete steps.
381
+ - If any durable fact, decision or lesson emerged that is not yet recorded, persist it now with your memory tools (team_remember); everything else stays in this reply only.
382
+ - Do not write files. Reply with the summary text only.`
368
383
  },
369
384
  // 单聊运行提示词:没有项目上下文,只带本会话增量新消息。
370
385
  soloRunPrompt({ bot, chatMessage, extraMessages, sessionId }) {
371
386
  const header = [
372
387
  `You are: ${bot.name}`,
373
388
  'Mode: one-on-one conversation (outside projects)',
374
- `Workspace: ${join(this.config.workspace, '_the_bots', bot.solo_dir)}`,
389
+ `Workspace: ${displayPath(join(this.config.workspace, '_the_bots', bot.solo_dir))}`,
375
390
  ].join('\n')
376
391
  const { rows: recent, incremental } = this.watermarkWindow({
377
392
  sessionId,
@@ -401,8 +416,8 @@ ${(chatMessage?.body ?? '(no message)').slice(0, 4_000)}${this.mergedMessagesBlo
401
416
  ${recentBlock}`
402
417
  },
403
418
  // 读图代理运行提示词(DSHBOTS-112):代理模型把消息附图转写成中文结构化文本,
404
- // 供无视觉能力的主模型在后续轮次消费。图片分片由 startRun 随首条 prompt 自动
405
- // 附带(imageContentPartsForMessage 统一群聊/单聊口径),这里只出指令。
419
+ // 供无视觉能力的主模型在后续轮次消费。图片分片由 startRun 随首条提示词自动附带
420
+ // (imageContentPartsForMessage 统一群聊/单聊口径),这里只出指令。
406
421
  visionRunPrompt({ bot, project, chatMessage }) {
407
422
  const header = [
408
423
  project ? `Project: ${project.name} (${project.key})` : 'Mode: one-on-one conversation (outside projects)',
@@ -426,15 +441,16 @@ ${(chatMessage?.body ?? '(no text)').slice(0, 2_000)}`
426
441
  if (run.kind === 'solo_chat') return this.soloRunPrompt({ run, bot, chatMessage, extraMessages, sessionId })
427
442
  if (run.kind === 'vision') return this.visionRunPrompt({ run, bot, project, chatMessage })
428
443
  // 结转摘要(DSHBOTS-145):先于 header 判定——单聊摘要运行没有项目,
429
- // header 直接解引用 project 会炸。
444
+ // header 直接解引用 project 会炸。闲时压缩(DSHBOTS-286)同理。
430
445
  if (run.kind === 'rollover_summary') return this.rolloverSummaryPrompt({ run, bot, project })
446
+ if (run.kind === 'session_compact') return this.sessionCompactPrompt({ bot, project })
431
447
  const header = [
432
448
  `Project: ${project.name} (${project.key})`,
433
- `Workspace: ${project.production_dir || join(this.config.workspace, project.slug)}`,
449
+ `Workspace: ${displayPath(project.production_dir || join(this.config.workspace, project.slug))}`,
434
450
  `You are: ${bot.name}`,
435
451
  ].join('\n')
436
- // 任务评论注入(DSHBOTS-254 收口):最近 3 条、合计 ≤1.5k——每条正文 500 上限(1.5k/3 的
437
- // 按比例缩减)+ 拼接后 1500 硬顶(兜住行前缀开销),最坏 ~4k → 1.5k。
452
+ // 任务评论注入(DSHBOTS-254 收口):最近 3 条、合计 ≤1.5k——每条正文 500 上限
453
+ // (按 1.5k/3 比例缩减)+ 拼接后 1500 硬顶(兜住行前缀开销),最坏 ~4k 压到 1.5k。
438
454
  const taskComments = task
439
455
  ? this.store.all(
440
456
  'SELECT id, author_type, author_id, body FROM task_comments WHERE task_id = ? ORDER BY created_at DESC LIMIT 3',
@@ -447,27 +463,38 @@ ${(chatMessage?.body ?? '(no text)').slice(0, 2_000)}`
447
463
  .map(item => `- [c_${item.id.slice(-6)}] ${item.author_type}:${item.author_id}: ${item.body.length > 500 ? `${item.body.slice(0, 500)}…` : item.body}`)
448
464
  .join('\n')
449
465
  .slice(0, 1_500)}`
450
- // 时效要求(DSHBOTS-125/131):time_budget_minutes 未传/NULL 则完全不注入。
451
- // 任务派生运行(review/handle/memory_review)与该任务共用同一时效上限,提示词必须同步告知,
452
- // 否则运行会在代理不知情的情况下被超时中止。
453
- const timeBudgetBlockFor = (row) => {
466
+ // 时效要求(DSHBOTS-125/131):time_budget_minutes 未传或为 NULL 则完全不注入。
467
+ // 任务派生运行(review/handle/memory_review)与该任务共用同一时效上限,提示词必须同步
468
+ // 告知,否则运行会在代理不知情的情况下被超时中止。
469
+ // 任务级死线(DSHBOTS-274):死线只由施工分支(下方 if (task))传入,追加剩余时间一行;
470
+ // 预算耗尽改收尾轮口径。review/handle/memory_review 分支不传死线(豁免,不注入该行)。
471
+ const timeBudgetBlockFor = (row, deadline = null) => {
454
472
  const timeBudget = Number(row?.timeBudgetMinutes ?? row?.time_budget_minutes)
455
- return Number.isFinite(timeBudget) && timeBudget > 0 ? `
473
+ if (!(Number.isFinite(timeBudget) && timeBudget > 0)) return ''
474
+ let deadlineLine = ''
475
+ if (deadline?.deadlineMs !== null && deadline?.deadlineMs !== undefined) {
476
+ const remainingMs = deadline.deadlineMs - Date.now()
477
+ deadlineLine = remainingMs > 0
478
+ ? `Deadline: ${new Date(deadline.deadlineMs).toISOString()} / ${Math.ceil(remainingMs / 60_000)} min remaining.`
479
+ : `Deadline: ${new Date(deadline.deadlineMs).toISOString()} passed — the budget is exhausted; this is a wrap-up turn, prioritize a small deliverable step.`
480
+ }
481
+ return `
456
482
 
457
483
  # Time budget
458
484
  This task must be delivered within ${timeBudget} minutes; the run is aborted when the budget expires.
459
485
  Plan the depth of your work accordingly. If you judge the task cannot be finished within that time, deliver a usable partial result on schedule and state clearly in your delivery report the remaining work and why the budget could not be met.
460
- The effective timeout is the smaller of this budget and the global run timeout (runTimeoutMs).` : ''
486
+ The effective timeout is the smaller of this budget and the global run timeout (runTimeoutMs).
487
+ ${deadlineLine}`.trimEnd()
461
488
  }
462
489
  if ((run.kind === 'review' || run.kind === 'handle') && task) {
463
- // 超长防护(DSHBOTS-113,事故 m_33bddb;DSHBOTS-140 扩到 owner review / handle):
490
+ // 超长防护(DSHBOTS-113 事故 m_33bddb;DSHBOTS-140 扩到 owner review/handle):
464
491
  // 任务派生分支共用 truncateTaskDescription 的同一截断点与盲区口径(任务分支见 DSHBOTS-254)。
465
492
  const writeScopes = readWriteScopes(task.write_scopes)
466
493
  const declaredScopes = writeScopes.length ? writeScopes.join(', ') : '(none declared)'
467
494
  const description = truncateTaskDescription(task.description)
468
495
  if (run.kind === 'review') {
469
- // 委派核验模板(DSHBOTS-107 review-verification):核验工作由 subagent 并行完成,
470
- // 结论以「子代理核验:」开头落任务评论(finishRun 自动写回),不代 owner 裁决。
496
+ // 委派核验模板(DSHBOTS-107 review-verification):核验工作由子代理并行完成,
497
+ // 结论以「子代理核验:」开头落任务评论(finishRun 自动写回),不代负责人裁决。
471
498
  if (run.trigger_type === 'review_delegate') {
472
499
  return `${header}
473
500
 
@@ -585,32 +612,41 @@ ${(sourceRun?.output ?? '').slice(0, 4000)}`
585
612
  // 超长防护(DSHBOTS-254):任务分支与 review/handle 同口径复用 truncateTaskDescription
586
613
  // (8k 截断 + 盲区标记),建卡上限 40k 的长卡不再整段进提示词。
587
614
  const description = truncateTaskDescription(task.description)
588
- // 时效要求(DSHBOTS-125/131):time_budget_minutes 未传/NULL 则完全不注入,提示词与无时效任务一致。
589
- const timeBudgetBlock = timeBudgetBlockFor(task)
615
+ // 时效要求(DSHBOTS-125/131):time_budget_minutes 未传或为 NULL 则完全不注入,提示词与无时效任务一致。
616
+ // 任务级死线(DSHBOTS-274):施工分支传入整卡死线,时效段追加剩余时间或收尾轮口径。
617
+ const timeBudgetBlock = timeBudgetBlockFor(task, taskDeadlineInfo(this.store, task))
590
618
  // 紧急豁免(DSHBOTS-126):urgent 任务卡追加豁免指令(用户口径 m08196-2)——
591
619
  // 无视车道排队立即开工;非 urgent 完全不注入,保持既有车道纪律。
592
620
  const urgentExemptionBlock = task.priority === 'urgent' ? `
593
621
 
594
622
  # Urgent exemption
595
623
  This task is urgent and exempt from lane queuing discipline: start immediately, without waiting for other tasks' file lanes to clear. If in-flight edits to the same files exist in the workspace, first run git status to record the scene, then commit only this card's files by exact pathspec — never add/checkout/stash others' changes.` : ''
596
- // subtask-discipline:start —— 子任务拆解纪律(DSHBOTS-132;DSHBOTS-254 与提速拆分/并行段
597
- // 语义去重,三段合计 ≤1200 字符,tests/prompt-budget.test.ts 守门):主项做不完或出现新
598
- // 收口条件 → 立产品级子卡。所有任务卡无条件注入,与时效段(D-125)、紧急豁免段(D-126)
624
+ // 子任务拆解纪律(DSHBOTS-132;DSHBOTS-254 与提速拆分/并行段语义去重,三段合计
625
+ // ≤1200 字符,tests/prompt-budget.test.ts 守门):主项做不完或出现新收口条件就
626
+ // 立产品级子卡。所有任务卡无条件注入,与时效段(D-125)、紧急豁免段(D-126)
599
627
  // 互不干扰:本段不读 priority/time_budget,后两者不读本段。
600
628
  const subtaskDisciplineBlock = `
601
629
 
602
630
  # Subtask discipline
603
631
  Before closing: if this task cannot be finished in one run or new closing conditions emerge, file subtasks via team_assign_task with parent_task_id and report in the group — no verbal-only follow-ups. Subtasks are product-grade (general capability, full tests, real persistence), no throwaway patches. Do not split what one run can finish. List every subtask KEY-N in the closing report.`
604
- // subtask-discipline:end
605
- // splitting-guidance:start —— 提速拆分引导(DSHBOTS-212;DSHBOTS-254 去重收口):
606
- // 拆分判据(2+ 独立部分 + 写范围不相交 + 拆后合并成本更低)+ 角色现实(无派单权限就在
607
- // 交付报告里提拆分方案)。静态段(不随卡变化):与纪律段同为全局前缀,置于 # Assigned task
608
- // 之前,护住前缀缓存。
632
+ // 提速拆分引导(DSHBOTS-212;DSHBOTS-254 去重收口):
633
+ // 拆分判据(2+ 独立部分 + 写范围不相交 + 拆后合并成本更低)+ 角色现实(无派单权限
634
+ // 就在交付报告里提拆分方案)。静态段(不随卡变化):与纪律段同为全局前缀,置于
635
+ // # Assigned task 之前,护住前缀缓存。
609
636
  const splittingGuidanceBlock = `
610
637
 
611
638
  # Splitting for speed
612
639
  Split only when all hold: the task has 2+ independent parts, parts have disjoint write scopes, and the joined cost of split cards stays below one-run delivery. One card per part: parent_task_id to this task, blocked_by where order matters. Not the project owner? Propose the split in your delivery report. Example: API card (src/api/) + docs card, run concurrently.`
613
- // splitting-guidance:end
640
+ // delivery-selfcheck:start —— 交付前自校段(DSHBOTS-276,P1 派单质量前置):治 GS 实测
641
+ // 34% 补丁/返工卡——交付报告缺自跑验证证据。所有任务卡无条件注入,置于卡头
642
+ // Status 与 Description 之间(D-269 只追加手法):不动既有锚点前缀与 D-274 时效段
643
+ // (tests/prompt-budget ≤1900 静态前缀、8k 截断「描述后即结尾」、tests/prompt-prefix-order
644
+ // 段序三守门实测后选定此位)。
645
+ const deliverySelfcheckBlock = `
646
+
647
+ # Delivery self-check
648
+ Before reporting delivery, self-run the reproducible verification and put the evidence in the delivery report: the exact test/build commands you ran with their results, the list of files you changed, and the counts or links the acceptance criteria name (grep hits, test pass counts, commit hashes). Verify your own claims first — re-run the target tests and re-check the anchors yourself; do not report delivery on unverified work. Self-checking is always cheaper than rework: a delivery report without evidence will be returned.`
649
+ // delivery-selfcheck:end
614
650
  // recovery note(DSHBOTS-135):宿主重启重排队的运行(core.js 置 recovery=1)追加恢复提醒,
615
651
  // 对齐 superagent 原型语义——核实现状再续做、不重复外部动作。startRun 注入后即刻清零,
616
652
  // 本段只在重排队后的第一次执行出现。与时效段(D-125)、豁免段(D-126)、纪律段(D-132)互不干扰。
@@ -618,23 +654,25 @@ Split only when all hold: the task has 2+ independent parts, parts have disjoint
618
654
 
619
655
  # Recovery note
620
656
  The previous run was interrupted by a host restart. Check the workspace and git status first to verify the current state, then resume from where it stopped; do not repeat external actions already performed (commits/publishes/messages).` : ''
621
- // agentTeam 门控(DSHBOTS-254 收口):单卡内并行的执行口径——teammates/子代理、
657
+ // agentTeam 门控(DSHBOTS-254 收口):单卡内并行的执行口径——队友/子代理、
622
658
  // 部件落项目 KEY-N 卡、交付前 wait_agent 汇总。拆分判据不在此重复(见上方提速拆分段)。
659
+ // 子代理化解除(DSHBOTS-311 硬闸撤销):亲做与派子代理均可,派时命名 bot 名+任务号。
623
660
  const parallel = this.config.agentTeam ? `
624
661
 
662
+ # Child agents by task number
663
+ Execute each card yourself, or hand it to a dedicated child agent (subagent/subagent_fork) named <your bot name>-<task number> (e.g. Builder-ORD-3); never merge cards into one agent. Child writes inherit your session sandbox, not the task write-scope gates: pass the card's declared write scopes as the child's write boundary. Children report changed paths, verification with results, risks; merge and review their output yourself before delivering.` : ''
664
+ const parallelMerge = this.config.agentTeam ? `
665
+
625
666
  # Parallel work inside this task
626
- - Parallelize independent parts via teammates (at most ${this.config.maxTeammates}) or child agents (subagent/subagent_fork).
627
- - Record every part as a project task card (project KEY-N) with a disjoint write_scope, never on the host shared task board (task-N).
628
- - Before delivering: list_agents, wait_agent until idle, merge results into your report; resolve conflicting edits yourself.` : ''
667
+ Parallelize independent parts via teammates (at most ${this.config.maxTeammates}) or the child agents above; keep every part on project KEY-N cards, never on the host shared task board (task-N). Before delivering: list_agents, wait_agent until idle, merge results; resolve conflicting edits yourself.` : ''
629
668
  return `${header}${subtaskDisciplineBlock}${splittingGuidanceBlock}
630
669
 
631
- Do the task in the project workspace. Use tools as needed. End with a concise delivery report containing what changed, verification performed, and blockers or risks. Do not just describe what you would do.
632
- When the deliverable includes images, put the files in the workspace and reference them with markdown image syntax using workspace-relative paths (e.g. ![preview](assets/preview.png)); chat renders them as thumbnails. Only png/jpg/jpeg/gif/webp are served.${parallel}
670
+ Do the task in the project workspace. End with a concise delivery report containing what changed, verification performed, and blockers or risks — not just a plan.${parallel}${parallelMerge}
633
671
 
634
672
  # Assigned task ${project.key}-${task.number}
635
673
  Title: ${task.title}
636
674
  Priority: ${task.priority}
637
- Status: ${task.status}
675
+ Status: ${task.status}${deliverySelfcheckBlock}
638
676
  Description:
639
677
  ${description}${threads}${timeBudgetBlock}${urgentExemptionBlock}${recoveryNoteBlock}`
640
678
  }
@@ -670,13 +708,22 @@ ${description}${threads}${timeBudgetBlock}${urgentExemptionBlock}${recoveryNoteB
670
708
  const quoteLine = this.quotedLineFor(chatMessage)
671
709
  // DSHBOTS-215 微信直达语境:多轮连续对话(项目会话复用),不要每条当新指令;
672
710
  // 派活意图要真建卡/派单;需要用户决策时用 ask_user_question(会转发到微信)。
711
+ // DSHBOTS-283 微信不渲染 Markdown:纯文本版式(空行+符号列表),禁 * # 原样字符。
673
712
  const wechatBlock = run.trigger_type === 'wechat' ? `
674
713
 
675
714
  # WeChat direct conversation
676
- This message is from the project owner on WeChat — a real multi-turn conversation, not a one-off command. The project session is shared, so keep continuity across turns instead of restarting context each time. If the owner asks you to get work done, actually create and assign the task (team_assign_task — cards carry the project KEY-N number; do not create project-less task-N cards on the host shared board) instead of only acknowledging it. If you need the owner to decide something, use ask_user_question: it is forwarded to their WeChat and their reply comes back to you.` : ''
715
+ This message is from the project owner on WeChat — a real multi-turn conversation, not a one-off command. The project session is shared, so keep continuity across turns instead of restarting context each time. If the owner asks you to get work done, actually create and assign the task (team_assign_task — cards carry the project KEY-N number; do not create project-less task-N cards on the host shared board) instead of only acknowledging it. If you need the owner to decide something, use ask_user_question: it is forwarded to their WeChat and their reply comes back to you. WeChat renders no Markdown: use plain text with blank lines and - lists, never * or #.` : ''
716
+ // DSHBOTS-272 用户提问锚点:触发消息是人发的(sender_type='user')才注入;通知降级与
717
+ // bot @mention 唤醒触发的运行(sender_type='bot')不注入——事故根因之一是通知内容与用户
718
+ // 提问同窗时无优先级指示,bot 回了条轻备忘就算处理完。
719
+ const ownerQuestionBlock = chatMessage?.sender_type === 'user' ? `
720
+
721
+ # Owner question priority
722
+ This message is from the project owner — answer it directly in this reply. Background notifications in context must not substitute for the answer; handle them only after (or skip to next turn).` : ''
723
+ // DSHBOTS-283 回复分级:长文(交付/进展/评估)用 Markdown 固定小标题,短回复保持自然语言。
677
724
  return `${header}
678
725
 
679
- Reply as ${bot.name} in the project group. Keep it under ${this.config.chatReplyMaxChars} characters unless the user asked for a full write-up. If the message requires another bot to do work, use team_assign_task instead of pretending to assign it. Use team_recall with a m_/c_/run id when you need the full text of a truncated item.${wechatBlock}
726
+ Reply as ${bot.name} in the project group. Keep it under ${this.config.chatReplyMaxChars} characters unless the user asked for a full write-up. If the message requires another bot to do work, use team_assign_task instead of pretending to assign it. Use team_recall with a m_/c_/run id when you need the full text of a truncated item. Long replies (deliveries, progress updates, assessments) use Markdown headings 结论/证据/风险/下一步; short replies stay natural.${wechatBlock}${ownerQuestionBlock}
680
727
 
681
728
  # Group message
682
729
  ${(chatMessage?.body ?? '(no message)').slice(0, 4_000)}