@oyasmi/pipiclaw 0.9.1 → 0.9.2-beta.1

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 (149) hide show
  1. package/dist/agent/channel-runner.d.ts +2 -1
  2. package/dist/agent/channel-runner.js +9 -5
  3. package/dist/agent/effect-ledger.js +9 -2
  4. package/dist/agent/job-manager.d.ts +4 -0
  5. package/dist/agent/job-manager.js +17 -2
  6. package/dist/agent/prompt/manifest.d.ts +1 -1
  7. package/dist/agent/prompt/manifest.js +1 -1
  8. package/dist/agent/prompt/sections.js +8 -5
  9. package/dist/agent/session-events.d.ts +2 -0
  10. package/dist/agent/session-events.js +29 -14
  11. package/dist/agent/turn-recovery.js +2 -2
  12. package/dist/agent/type-guards.js +5 -1
  13. package/dist/agent/workspace-resources.d.ts +2 -2
  14. package/dist/agent/workspace-resources.js +41 -3
  15. package/dist/executor.d.ts +14 -0
  16. package/dist/executor.js +96 -24
  17. package/dist/file-store.d.ts +96 -0
  18. package/dist/file-store.js +189 -0
  19. package/dist/memory/consolidation.js +2 -26
  20. package/dist/memory/files.js +7 -7
  21. package/dist/memory/maintenance-jobs.js +2 -34
  22. package/dist/memory/maintenance-state.js +2 -1
  23. package/dist/memory/recall.d.ts +10 -0
  24. package/dist/memory/recall.js +15 -7
  25. package/dist/memory/session-search.js +6 -22
  26. package/dist/memory/transcript.d.ts +10 -0
  27. package/dist/memory/transcript.js +39 -0
  28. package/dist/playbooks/agent-delegation.md +6 -4
  29. package/dist/playbooks/background-jobs.md +1 -1
  30. package/dist/playbooks/catalog.d.ts +1 -1
  31. package/dist/playbooks/catalog.js +1 -1
  32. package/dist/playbooks/event-scheduling.md +2 -0
  33. package/dist/playbooks/memory-and-learning.md +11 -11
  34. package/dist/playbooks/runtime-orientation.md +3 -3
  35. package/dist/playbooks/task-driving.md +5 -5
  36. package/dist/playbooks/task-planning.md +5 -5
  37. package/dist/runtime/app-home.js +1 -1
  38. package/dist/runtime/bootstrap.js +10 -0
  39. package/dist/runtime/dingtalk.js +3 -2
  40. package/dist/runtime/durable-dispatch.d.ts +26 -1
  41. package/dist/runtime/durable-dispatch.js +51 -5
  42. package/dist/runtime/event-commands.js +7 -16
  43. package/dist/runtime/events.d.ts +4 -2
  44. package/dist/runtime/events.js +15 -20
  45. package/dist/runtime/subagent-commands.js +1 -1
  46. package/dist/runtime/task-commands.d.ts +1 -1
  47. package/dist/runtime/task-commands.js +10 -10
  48. package/dist/runtime/task-driver.js +2 -2
  49. package/dist/security/block-message.d.ts +11 -0
  50. package/dist/security/block-message.js +12 -0
  51. package/dist/security/path-guard-check.d.ts +13 -0
  52. package/dist/security/path-guard-check.js +39 -0
  53. package/dist/security/path-guard.js +32 -14
  54. package/dist/settings.js +3 -2
  55. package/dist/shared/atomic-file.d.ts +17 -1
  56. package/dist/shared/atomic-file.js +50 -3
  57. package/dist/shared/duration.d.ts +2 -0
  58. package/dist/shared/duration.js +7 -0
  59. package/dist/shared/safe-id.d.ts +19 -0
  60. package/dist/shared/safe-id.js +24 -0
  61. package/dist/shared/text-utils.d.ts +1 -1
  62. package/dist/shared/text-utils.js +3 -8
  63. package/dist/shared/type-guards.d.ts +2 -0
  64. package/dist/shared/type-guards.js +4 -0
  65. package/dist/subagents/discovery.d.ts +44 -17
  66. package/dist/subagents/discovery.js +82 -111
  67. package/dist/subagents/external/claude-code.js +1 -3
  68. package/dist/subagents/external/harness.d.ts +1 -1
  69. package/dist/subagents/format.d.ts +3 -2
  70. package/dist/subagents/format.js +3 -7
  71. package/dist/subagents/runs.d.ts +1 -1
  72. package/dist/subagents/runs.js +4 -9
  73. package/dist/subagents/tool.d.ts +31 -19
  74. package/dist/subagents/tool.js +582 -561
  75. package/dist/subagents/workspace-lease.js +1 -1
  76. package/dist/tasks/control.js +7 -9
  77. package/dist/tasks/ledger.d.ts +2 -2
  78. package/dist/tasks/ledger.js +3 -7
  79. package/dist/tasks/transitions.d.ts +5 -1
  80. package/dist/tasks/transitions.js +2 -2
  81. package/dist/tools/bash.d.ts +0 -1
  82. package/dist/tools/bash.js +45 -40
  83. package/dist/tools/config.d.ts +6 -1
  84. package/dist/tools/config.js +9 -0
  85. package/dist/tools/edit.d.ts +2 -3
  86. package/dist/tools/edit.js +274 -86
  87. package/dist/tools/event-manage.d.ts +13 -7
  88. package/dist/tools/event-manage.js +52 -14
  89. package/dist/tools/glob-match.d.ts +11 -0
  90. package/dist/tools/glob-match.js +75 -0
  91. package/dist/tools/glob.d.ts +15 -0
  92. package/dist/tools/glob.js +113 -0
  93. package/dist/tools/grep.d.ts +0 -1
  94. package/dist/tools/grep.js +57 -42
  95. package/dist/tools/ignore-dirs.d.ts +6 -0
  96. package/dist/tools/ignore-dirs.js +15 -0
  97. package/dist/tools/index.d.ts +3 -0
  98. package/dist/tools/index.js +50 -40
  99. package/dist/tools/job.d.ts +0 -1
  100. package/dist/tools/job.js +1 -8
  101. package/dist/tools/line-index.d.ts +16 -0
  102. package/dist/tools/line-index.js +76 -0
  103. package/dist/tools/memory-manage.d.ts +20 -8
  104. package/dist/tools/memory-manage.js +65 -92
  105. package/dist/tools/presentation.d.ts +2 -0
  106. package/dist/tools/presentation.js +109 -0
  107. package/dist/tools/read.d.ts +2 -2
  108. package/dist/tools/read.js +97 -133
  109. package/dist/tools/registry.d.ts +4 -1
  110. package/dist/tools/registry.js +89 -22
  111. package/dist/tools/send-media.d.ts +6 -6
  112. package/dist/tools/send-media.js +16 -49
  113. package/dist/tools/session-search.d.ts +0 -1
  114. package/dist/tools/session-search.js +0 -1
  115. package/dist/tools/skill-security.d.ts +0 -2
  116. package/dist/tools/skill-security.js +0 -24
  117. package/dist/tools/skill.d.ts +31 -0
  118. package/dist/tools/skill.js +153 -0
  119. package/dist/tools/subagent-manage.d.ts +6 -5
  120. package/dist/tools/subagent-manage.js +47 -47
  121. package/dist/tools/task-manage/create.d.ts +2 -2
  122. package/dist/tools/task-manage/create.js +1 -3
  123. package/dist/tools/task-manage/lifecycle.d.ts +9 -6
  124. package/dist/tools/task-manage/lifecycle.js +49 -56
  125. package/dist/tools/task-manage/schema.d.ts +27 -15
  126. package/dist/tools/task-manage/schema.js +58 -74
  127. package/dist/tools/task-manage/shared.d.ts +11 -6
  128. package/dist/tools/task-manage/shared.js +30 -21
  129. package/dist/tools/task-manage/types.d.ts +14 -15
  130. package/dist/tools/task-manage/verification.d.ts +4 -4
  131. package/dist/tools/task-manage/verification.js +6 -8
  132. package/dist/tools/task-manage.d.ts +8 -11
  133. package/dist/tools/task-manage.js +63 -50
  134. package/dist/tools/tool-details.d.ts +17 -1
  135. package/dist/tools/tool-details.js +24 -0
  136. package/dist/tools/truncate.d.ts +5 -5
  137. package/dist/tools/truncate.js +5 -5
  138. package/dist/tools/web-fetch.d.ts +0 -1
  139. package/dist/tools/web-fetch.js +0 -1
  140. package/dist/tools/web-search.d.ts +0 -1
  141. package/dist/tools/web-search.js +0 -1
  142. package/dist/tools/write-content.d.ts +3 -3
  143. package/dist/tools/write-content.js +12 -51
  144. package/dist/tools/write.d.ts +2 -3
  145. package/dist/tools/write.js +3 -4
  146. package/dist/usage/ledger.js +7 -4
  147. package/package.json +1 -1
  148. package/dist/tools/skill-manage.d.ts +0 -41
  149. package/dist/tools/skill-manage.js +0 -232
@@ -76,7 +76,7 @@ export function loadRuntimePlaybookCatalog(directory = PLAYBOOKS_DIR) {
76
76
  }
77
77
  /**
78
78
  * Drop playbooks whose mechanism is unreachable with the current tool set: the task
79
- * playbooks are pure noise for a runtime with `task_manage` switched off.
79
+ * playbooks are pure noise for a runtime with the task_* tools switched off.
80
80
  */
81
81
  export function selectRuntimePlaybooks(catalog, toolNames) {
82
82
  const tools = new Set(toolNames);
@@ -44,4 +44,6 @@ preAction 的 bash 命令退出 0 才唤醒 agent,非 0 静默跳过。它用
44
44
 
45
45
  ## 维护纪律
46
46
 
47
+ 闭环或改期之前先 `event_manage action=list` 确认本频道事件的真实名字,不要凭 `task.<channelId>.<taskId>.<use>` 约定拼。`list` 只返回当前 channel 的事件,无法解析的文件也会列出并标记,便于清理。名字确定时直接 create / update / delete,不必每次先 list。
48
+
47
49
  更新事件时整体替换 definition,不再需要就及时删除。周期事件跑完没有新结果时按唤醒文本的要求回复 `[SILENT]`,不发空状态卡。排查触发与 gate 结果要看事件历史(用户命令:`/events history`)。
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  name: memory-and-learning
3
3
  description: 记住或忘记事实(memory)、在记忆文件之间取舍,或把经验沉淀成技能(skill)。
4
- requires-tools: memory_manage, skill_manage
4
+ requires-tools: memory_save, memory_search, memory_forget, skill
5
5
  order: 20
6
6
  ---
7
7
 
@@ -12,24 +12,24 @@ order: 20
12
12
  | 信息 | 目标位置 | 入口 |
13
13
  |---|---|---|
14
14
  | 当前回合断点、眼下计划 | channel `SESSION.md` | runtime 自动维护,不手工编辑 |
15
- | 稳定事实、偏好、约束、决定 | channel `MEMORY.md` | `memory_manage save` / `forget` |
16
- | 单个长程工作的状态和证据 | `tasks/<id>.md` | `task_manage`,正文大改才用 `edit` |
15
+ | 稳定事实、偏好、约束、决定 | channel `MEMORY.md` | `memory_save` / `memory_forget` |
16
+ | 单个长程工作的状态和证据 | `tasks/<id>.md` | `task_create`/`task_update`/`task_close`,正文大改才用 `edit` |
17
17
  | 机器依赖、安装、配置位置 | workspace `ENVIRONMENT.md` | `read` / `edit`,受项目边界约束 |
18
- | 跨任务可复用的操作流程 | workspace `skills/` | `skill_manage` |
18
+ | 跨任务可复用的操作流程 | workspace `skills/` | `write`/`edit` 创建或修改,`skill` 只读列出/加载 |
19
19
  | Pipiclaw 自身机制 | runtime playbook | 只读 |
20
20
  | 原始对话 | `log.jsonl` / `context.jsonl` | `session_search` |
21
21
 
22
- channel 的 `SESSION.md`、`MEMORY.md`、`HISTORY.md` 由 runtime 和后台维护队列共同持有:可以 `read`,但写入一律走 `memory_manage`,用文件工具改会与后台写入相撞(项目边界下 path guard 会直接拒绝)。各文件的位置和访问入口见 `runtime-orientation.md`。
22
+ channel 的 `SESSION.md`、`MEMORY.md`、`HISTORY.md` 由 runtime 和后台维护队列共同持有:可以 `read`,但写入一律走 `memory_save`/`memory_forget`,用文件工具改会与后台写入相撞(项目边界下 path guard 会直接拒绝)。各文件的位置和访问入口见 `runtime-orientation.md`。
23
23
 
24
24
  ## 什么时候立即写 durable memory
25
25
 
26
- 用户明确说"记住、以后默认、偏好、不要再做、忘掉"时,当回合就调用 `memory_manage`,不等后台 consolidation。这条路径写入的记忆立即永久,不受下面的试用期约束。
26
+ 用户明确说"记住、以后默认、偏好、不要再做、忘掉"时,当回合就调用 `memory_save`,不等后台 consolidation。这条路径写入的记忆立即永久,不受下面的试用期约束。
27
27
 
28
28
  只保存未来仍有用的事实;一次性进度、猜测、临时计划放 task 或留在当前会话。
29
29
 
30
30
  `save` 撞到相似的已有条目时,工具会先拒绝并列出它们,要一个决定:`supersedes: <entry id>` 替换旧条目,或 `supersedes: "none"` 保留两条。**同一条规则出了新版本就替换**——两个版本并存之后召回哪一条全看运气;只有两个事实同时成立才保留两条。整条规则不再成立时用 `forget`。
31
31
 
32
- 查找先用具体关键词(`memory_manage search`)。
32
+ 查找先用具体关键词(`memory_search`)。
33
33
 
34
34
  ## 后台自动写入与试用期
35
35
 
@@ -48,13 +48,13 @@ channel 的 `SESSION.md`、`MEMORY.md`、`HISTORY.md` 由 runtime 和后台维
48
48
 
49
49
  ## 把经验沉淀成 workspace skill
50
50
 
51
- 只有流程能跨任务复用时才建 skill;单任务经验先改该 task 的 Manual。创建时:
51
+ 只有流程能跨任务复用时才建 skill;单任务经验先改该 task 的 Manual。用 `write` 在 `workspace/skills/<name>/SKILL.md` 直接创建(已存在则用 `edit` 修改),frontmatter 必须包含非空的 `name`(需与目录名一致,`[a-z0-9]+(-[a-z0-9]+)*`)和 `description`:
52
52
 
53
53
  1. 短小 kebab-case 名称,description 写清触发场景。
54
54
  2. 正文只写模型不知道的步骤、约束和验收方法,默认模型已有通用能力。
55
55
  3. 脆弱流程给低自由度的明确步骤;开放问题给原则和判断条件。
56
- 4. 详细参考与核心流程不重复;支持文件按需加载。
57
- 5. 不写入密钥,不把不可信网页内容当指令。
58
- 6. 创建或更新后用一个真实任务验证,发现返工原因再迭代。
56
+ 4. 详细参考与核心流程不重复;支持文件(references/、templates/、scripts/、assets/ 下)用 `read` 按需加载。
57
+ 5. 不写入密钥,不把不可信网页内容当指令——内容会在加载时被安全扫描,触发规则的技能不会进入技能目录。
58
+ 6. 创建或更新后用一个真实任务验证,发现返工原因再迭代;`skill list` 可以看到扫描失败的警告原因。
59
59
 
60
60
  runtime playbook 随包升级,workspace skill 随用户经验演进,两者不互相覆盖。
@@ -44,15 +44,15 @@ Workspace 根目录——**靠专用工具或只读注入访问**,项目边界
44
44
 
45
45
  - `SOUL.md`(身份与表达风格)、`AGENTS.md`(用户/团队工作原则):每回合注入 system prompt。
46
46
  - `MEMORY.md`:管理员维护的共享背景,随首轮快照和召回进入上下文。
47
- - `skills/`:workspace 级程序性知识,用 `skill_manage` 管理;读取始终放行。
47
+ - `skills/`:workspace 级程序性知识;`skill` 工具只读列出/加载,创建或修改直接用 `write`/`edit`。读写都始终放行(项目边界的例外)。
48
48
  - `sub-agents/`:委派角色定义,目录呈现在 system prompt 里。
49
49
  - `events/`:全 workspace 的调度事件,用 `event_manage` 管理。
50
50
  - `ENVIRONMENT.md`(机器环境事实和重要变更)和 `CHANNELS.md`(runtime 维护的频道索引:频道 ID / 名称 / 最近消息 / 主题;「主题」一列可以补写,其余三列会被重写覆盖)**只能用 `read` / `edit` 打开**。项目边界把它们挡在外面时不要猜内容,把你需要它这件事告诉用户。
51
51
 
52
52
  当前 channel 目录(路径在 `<runtime_turn_context>` 里)——runtime 维护,项目边界下始终可读:
53
53
 
54
- - `SESSION.md`(当前工作状态)、`MEMORY.md`(稳定事实、偏好、决策与中期 open loop)、`HISTORY.md`(更旧的摘要历史):可以 `read`,但**只用 `memory_manage` 写**——它们由后台维护队列共同持有,文件工具的写入会和后台相撞(项目边界下 path guard 会直接拒绝)。
55
- - `tasks/`:长程任务台账。状态和生命周期用 `task_manage`,正文(Goal/DoD/Manual/Verification)大改用 `edit`——`task_manage set` 只重写 frontmatter,原样保留正文。
54
+ - `SESSION.md`(当前工作状态)、`MEMORY.md`(稳定事实、偏好、决策与中期 open loop)、`HISTORY.md`(更旧的摘要历史):可以 `read`,但**只用 `memory_save`/`memory_forget` 写**——它们由后台维护队列共同持有,文件工具的写入会和后台相撞(项目边界下 path guard 会直接拒绝)。
55
+ - `tasks/`:长程任务台账。状态和生命周期用 `task_create`/`task_update`/`task_close`/`task_verify`,正文(Goal/DoD/Manual/Verification)大改用 `edit`——不带 `note` 的 `task_update` 只重写 frontmatter,原样保留正文。
56
56
  - `log.jsonl` / `context.jsonl`:冷存储,用 `session_search` 检索。
57
57
 
58
58
  ## 读取顺序
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  name: task-driving
3
3
  description: 被 TASK_DRIVER 唤醒推进任务,或处理任务等待、验收(verify)、闭环、停滞、停用及元数据损坏时。
4
- requires-tools: task_manage
4
+ requires-tools: task_update, task_close, task_verify
5
5
  order: 80
6
6
  ---
7
7
 
@@ -25,7 +25,7 @@ order: 80
25
25
 
26
26
  ## 回合结束必须留下状态
27
27
 
28
- 仍需继续时,用 `task_manage progress` 原子记录发生了什么、证据、下一步、status/wake;Plan 变化放在同一次 `planSteps` 里。生命周期动作 `complete`、`skip`、`cancel` 本身就是 checkpoint。
28
+ 仍需继续时,用带 `note` 的 `task_update` 原子记录发生了什么、证据、下一步、status/wake;Plan 变化放在同一次 `planSteps` 里。`task_close`(complete/skip/cancel)本身就是 checkpoint。
29
29
 
30
30
  - 当前可继续:`active`,清除 wake。
31
31
  - 等待真实条件:按上一节设置 `waiting`、wake 和 waitingFor。
@@ -46,9 +46,9 @@ task scope 就是 authority:不要扩大目标、渠道、环境或对象范
46
46
  ## 独立验收
47
47
 
48
48
  1. 只有证据成立后才勾选 DoD / Verification checklist。
49
- 2. 像任何其他委派一样,派发一个 `purpose: verify`、带 `taskId` 的 sub-agent,然后用 `task_manage progress` 把任务停泊为 `waiting`(不设 wake,`waitingFor: external-signal`)——没有单独的 `request-verification` 动作,也没有 `waiting + waitingFor: verification` 这种状态。
49
+ 2. 像任何其他委派一样,派发一个 `purpose: verify`、带 `taskId` 的 sub-agent,然后用带 `note` 的 `task_update` 把任务停泊为 `waiting`(不设 wake,`waitingFor: external-signal`)——没有单独的 `request-verification` 动作,也没有 `waiting + waitingFor: verification` 这种状态。
50
50
  3. checker 只读检查,结尾返回 `VERDICT: PASS` 或 `VERDICT: FAIL`;完成后 runtime 通过完成唤醒恢复所属 task,依据是 run 记录里的 `taskId`。
51
- 4. 主回合用 `task_manage verify` 导入 runId;attestation 必须属于当前 task、未改变 workspace,且 contract body hash 与 artifact subject 新鲜。
51
+ 4. 主回合用 `task_verify` 导入 runId;attestation 必须属于当前 task、未改变 workspace,且 contract body hash 与 artifact subject 新鲜。
52
52
  5. PASS/FAIL 都恢复 active;PASS 后 complete 仍会重新校验 attestation、contract hash 和 artifact subject。
53
53
  6. attestation 标 `advisory` 时(带 `bash` 的内置验收者,以及所有外部验收者),结论只是参考而非结构性保证,仍要按风险抽查;判定强度的来源见 `agent-delegation.md`。
54
54
 
@@ -89,4 +89,4 @@ control: {"version":3,...,"stop":{"by":"governor","reason":"<确定性原因>","
89
89
  - required verification 的 attestation、contract hash、artifact subject;
90
90
  - 不可读 frontmatter 或不可解析的 control(旧版本的 control 直接判为不可读)。
91
91
 
92
- 修 metadata 不执行外部动作。坏 frontmatter 会 fail-open 让问题显现;坏 control 用 `task_manage set` 传结构化的 `control` 重写,不要手工拼 JSON 字符串。要改的是正文契约(Goal/DoD/Manual/Verification)时才用 `edit`——`set` 原样保留正文,改完记得重新验收。daemon 重启后按任务文件重新恢复,仍须遵守幂等检查。
92
+ 修 metadata 不执行外部动作。坏 frontmatter 会 fail-open 让问题显现;坏 control 用不带 `note` 的 `task_update` 传结构化的 `control` 重写,不要手工拼 JSON 字符串。要改的是正文契约(Goal/DoD/Manual/Verification)时才用 `edit`——不带 `note` 的 `task_update` 原样保留正文,改完记得重新验收。daemon 重启后按任务文件重新恢复,仍须遵守幂等检查。
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  name: task-planning
3
3
  description: 判断该建长程任务(task)还是事件(event)、写任务契约,或设定周期节奏(schedule)。
4
- requires-tools: task_manage
4
+ requires-tools: task_create, task_update
5
5
  order: 70
6
6
  ---
7
7
 
@@ -17,7 +17,7 @@ order: 70
17
17
 
18
18
  ## 创建内容
19
19
 
20
- 调用 `task_manage create`:
20
+ 调用 `task_create`:
21
21
 
22
22
  - `id`:稳定的 kebab-case。
23
23
  - `title`:一句话标题。
@@ -38,11 +38,11 @@ Task 创建即持续委托:能触达什么由可用工具、security 配置和
38
38
  - `nextAction`:下一条可执行动作,避免抽象愿望;等待时"等什么、条件、下一步"也写在这里,没有单独的 blockedReason 字段。
39
39
  - `waitingFor`:等待来源的记录性展示(`time` / `user` / `job` / `external-signal`)。它不决定任务能否恢复,语义见 `task-driving.md`。
40
40
  - `wake`:最早回访时间。带 future wake 的任务应当是 `waiting`;`active` 配 future wake 是非法组合,会被任务体检报出来。
41
- - `schedule`:五字段 cron,存在即 recurring,最小间隔 30 分钟。
41
+ - `schedule`:五字段 cron,存在即 recurring,最小间隔 30 分钟。改动已有任务的 `schedule` 会把 `wake` 重算到新节奏的下一次时间点,除非同一次调用也显式设置了 `wake`。
42
42
 
43
43
  ## Plan:手段层
44
44
 
45
- 预计需要多次唤醒时,用 `plan` 创建步骤,或用 `task_manage progress` 的 `planSteps` 更新。Plan 是手段,不是第二份 DoD;每步写可验证产出,可选 `→ dod:1,2` 引用。四态为 `[ ]` todo、`[x]` done、`[!]` blocked、`[~]` dropped。当前步骤由 runtime 从文档顺序推导。
45
+ 预计需要多次唤醒时,用 `plan` 创建步骤,或用 `task_update` 的 `planSteps` 更新。`planSteps` 要求任务已有 `## Plan` 小节——首次调用即创建它。Plan 是手段,不是第二份 DoD;每步写可验证产出,可选 `→ dod:1,2` 引用。四态为 `[ ]` todo、`[x]` done、`[!]` blocked、`[~]` dropped。当前步骤由 runtime 从文档顺序推导。
46
46
 
47
47
  ## 三态与周期
48
48
 
@@ -55,4 +55,4 @@ Task 创建即持续委托:能触达什么由可用工具、security 配置和
55
55
 
56
56
  ## 建档后自检
57
57
 
58
- 创建后读取落盘文件,确认 Goal、DoD、Manual、Verification、status、enabled、wake 和 control 与真实意图一致;正文要改用 `edit`,`task_manage set` 只动 frontmatter。后续推进、等待、验收和闭环都按 `task-driving.md`。
58
+ 创建后读取落盘文件,确认 Goal、DoD、Manual、Verification、status、enabled、wake 和 control 与真实意图一致;正文要改用 `edit`,不带 `note` 的 `task_update` 只动 frontmatter。后续推进、等待、验收和闭环都按 `task-driving.md`。
@@ -86,7 +86,7 @@ const TOOLS_CONFIG_TEMPLATE = {
86
86
  "Set tools.web.enable to true to register web_search and web_fetch.",
87
87
  "Replace tools.web.search.apiKey with your Brave API key before enabling web tools.",
88
88
  "If needed, copy _examples.proxy to tools.web.proxy.",
89
- "tools.tasks.enabled is the master switch for autonomous long-running tasks (task_manage tool + task driver + task digest).",
89
+ "tools.tasks.enabled is the master switch for autonomous long-running tasks (task_* tools + task driver + task digest).",
90
90
  ],
91
91
  };
92
92
  const SECURITY_CONFIG_TEMPLATE = {
@@ -646,6 +646,16 @@ export async function createRuntimeContext(options) {
646
646
  durableDispatch = new DurableDispatchService({
647
647
  stateDir: join(options.paths.appHomeDir, "state", "dispatch"),
648
648
  bot,
649
+ // A structured wake (job/subagent completion, task-driver) that keeps failing before it can
650
+ // ever mark itself complete would otherwise redeliver forever (30s tick, no backoff prior to
651
+ // this notice). Surface it once instead of looping silently; the record stays on disk for
652
+ // inspection until a human clears it.
653
+ onExhausted: async (record) => {
654
+ log.logWarning(`[${record.event.channelId}] Dispatch ${record.id} exhausted after ${record.deliveries} deliveries`, record.event.text.slice(0, 500));
655
+ await bot.sendPlain(record.event.channelId, `一个后台唤醒(${record.event.user})连续 ${record.deliveries} 次投递均未能完成,已停止自动重试:\n` +
656
+ `${record.event.text.slice(0, 300)}\n` +
657
+ `记录文件:state/dispatch/${record.id}.json(已保留,供排查)。`);
658
+ },
649
659
  });
650
660
  const executor = createExecutor();
651
661
  // Background jobs get their persistence root and their way to wake a channel before any turn
@@ -9,10 +9,11 @@
9
9
  */
10
10
  import axios from "axios";
11
11
  import { DWClient, TOPIC_ROBOT } from "dingtalk-stream";
12
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
12
+ import { existsSync, mkdirSync, readFileSync } from "fs";
13
13
  import { dirname, join } from "path";
14
14
  import { formatBusyCommandList, parseBuiltInCommand, renderBuiltInHelp, slashCommandName, } from "../agent/commands.js";
15
15
  import * as log from "../log.js";
16
+ import { writeFileAtomicallySync } from "../shared/atomic-file.js";
16
17
  import { errorMessage } from "../shared/text-utils.js";
17
18
  import { isRecord } from "../shared/type-guards.js";
18
19
  import { getChannelDir } from "./channel-paths.js";
@@ -1206,7 +1207,7 @@ export class DingTalkBot {
1206
1207
  return;
1207
1208
  try {
1208
1209
  mkdirSync(dirname(metaPath), { recursive: true });
1209
- writeFileSync(metaPath, JSON.stringify(meta, null, 2), "utf-8");
1210
+ writeFileAtomicallySync(metaPath, JSON.stringify(meta, null, 2));
1210
1211
  }
1211
1212
  catch (err) {
1212
1213
  log.logWarning(`Failed to persist conversation metadata for ${channelId}`, errorMessage(err));
@@ -1,10 +1,28 @@
1
1
  import type { ChannelEvent } from "./channel-event.js";
2
2
  import type { DingTalkBot } from "./dingtalk.js";
3
+ type DispatchStatus = "pending" | "queued" | "running" | "exhausted";
4
+ export interface DurableDispatchRecord {
5
+ version: 1;
6
+ id: string;
7
+ createdAt: string;
8
+ status: DispatchStatus;
9
+ event: ChannelEvent;
10
+ deliveries: number;
11
+ leaseExpiresAt?: string;
12
+ /** Set by `markRetryable` to back off a repeatedly-failing structured wake instead of
13
+ * redelivering on the very next drain tick (spec 031's redelivery has no such gate). */
14
+ nextAttemptAt?: string;
15
+ }
3
16
  export interface DurableDispatchOptions {
4
17
  stateDir: string;
5
18
  bot: Pick<DingTalkBot, "enqueueEvent">;
6
19
  leaseMs?: number;
7
20
  intervalMs?: number;
21
+ /** Called once, at most, when a dispatch id hits `MAX_DELIVERIES` without ever completing —
22
+ * e.g. a structured wake whose claim/finish step fails deterministically (disk full,
23
+ * permissions). The record is left on disk (not deleted) so the failure is inspectable; the
24
+ * caller is expected to notify the channel. */
25
+ onExhausted?: (record: DurableDispatchRecord) => void | Promise<void>;
8
26
  }
9
27
  /**
10
28
  * Tiny file-backed outbox for synthetic work. It intentionally provides
@@ -37,10 +55,17 @@ export declare class DurableDispatchService {
37
55
  markCompleted(id: string | undefined): Promise<void>;
38
56
  /** Release a failed handler's in-process claim without deleting its durable record. Structured
39
57
  * wake activation uses this for transient task/job/run persistence failures so the next drain
40
- * can retry the same dispatch id instead of losing the only completion signal. */
58
+ * can retry the same dispatch id instead of losing the only completion signal.
59
+ *
60
+ * A failure here means the handler itself is broken for this wake (a claim or finish step
61
+ * threw), not that the outbox lost a race — redelivering on the very next 30s tick would just
62
+ * repeat the same failure forever. Back off exponentially by delivery count instead; `deliveries`
63
+ * doubles as the poison-pill counter in `drainRecord`, so a wake that keeps failing here still
64
+ * eventually hits `MAX_DELIVERIES` and stops. */
41
65
  markRetryable(id: string | undefined): Promise<void>;
42
66
  drainOnce(now?: number): Promise<void>;
43
67
  private drainRecord;
44
68
  private read;
45
69
  private write;
46
70
  }
71
+ export {};
@@ -1,11 +1,18 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { readdir, readFile, unlink } from "node:fs/promises";
3
3
  import { join } from "node:path";
4
+ import * as log from "../log.js";
4
5
  import { writeFileAtomically } from "../shared/atomic-file.js";
5
6
  import { createSerialQueue } from "../shared/serial-queue.js";
7
+ import { errorMessage } from "../shared/text-utils.js";
6
8
  import { isRecord } from "../shared/type-guards.js";
7
9
  const DEFAULT_LEASE_MS = 15 * 60_000;
8
10
  const DEFAULT_INTERVAL_MS = 30_000;
11
+ /** Total delivery attempts (crash-lease redelivery and `markRetryable` failures combined) before
12
+ * a dispatch id is given up on as a poison pill rather than retried forever. */
13
+ const MAX_DELIVERIES = 8;
14
+ const MIN_RETRY_BACKOFF_MS = 30_000;
15
+ const MAX_RETRY_BACKOFF_MS = 10 * 60_000;
9
16
  function recordPath(stateDir, id) {
10
17
  return join(stateDir, `${id}.json`);
11
18
  }
@@ -40,11 +47,15 @@ function parseRecord(raw) {
40
47
  value.version !== 1 ||
41
48
  typeof value.id !== "string" ||
42
49
  typeof value.createdAt !== "string" ||
43
- (value.status !== "pending" && value.status !== "queued" && value.status !== "running") ||
50
+ (value.status !== "pending" &&
51
+ value.status !== "queued" &&
52
+ value.status !== "running" &&
53
+ value.status !== "exhausted") ||
44
54
  !isRecord(value.event) ||
45
55
  typeof value.event.channelId !== "string" ||
46
56
  typeof value.event.text !== "string" ||
47
- typeof value.deliveries !== "number") {
57
+ typeof value.deliveries !== "number" ||
58
+ (value.nextAttemptAt !== undefined && typeof value.nextAttemptAt !== "string")) {
48
59
  return undefined;
49
60
  }
50
61
  return value;
@@ -109,9 +120,13 @@ export class DurableDispatchService {
109
120
  // channel's outstanding record just to learn the outcome of the one just written.
110
121
  await this.drainRecord(id, Date.now());
111
122
  // The record is gone (delivered+completed already) or no longer "pending"
112
- // (drainRecord only reverts to "pending" when bot.enqueueEvent rejected it).
123
+ // (drainRecord only reverts to "pending" when bot.enqueueEvent rejected it). "exhausted"
124
+ // is reported as not-accepted too: the poison pill is durably recorded and its owner
125
+ // notified via onExhausted, but this dispatch id will never be delivered again.
113
126
  const after = await this.read(id);
114
- return after?.status !== "pending";
127
+ if (!after)
128
+ return true;
129
+ return after.status !== "pending" && after.status !== "exhausted";
115
130
  }
116
131
  /** Reset any in-flight records for a channel so a stop/abort can redeliver on the next tick, not after the lease expires. */
117
132
  async cancelChannel(channelId) {
@@ -164,7 +179,13 @@ export class DurableDispatchService {
164
179
  }
165
180
  /** Release a failed handler's in-process claim without deleting its durable record. Structured
166
181
  * wake activation uses this for transient task/job/run persistence failures so the next drain
167
- * can retry the same dispatch id instead of losing the only completion signal. */
182
+ * can retry the same dispatch id instead of losing the only completion signal.
183
+ *
184
+ * A failure here means the handler itself is broken for this wake (a claim or finish step
185
+ * threw), not that the outbox lost a race — redelivering on the very next 30s tick would just
186
+ * repeat the same failure forever. Back off exponentially by delivery count instead; `deliveries`
187
+ * doubles as the poison-pill counter in `drainRecord`, so a wake that keeps failing here still
188
+ * eventually hits `MAX_DELIVERIES` and stops. */
168
189
  async markRetryable(id) {
169
190
  if (!id)
170
191
  return;
@@ -173,8 +194,10 @@ export class DurableDispatchService {
173
194
  const record = await this.read(id);
174
195
  if (!record)
175
196
  return;
197
+ const backoffMs = Math.min(MIN_RETRY_BACKOFF_MS * 2 ** Math.max(0, record.deliveries - 1), MAX_RETRY_BACKOFF_MS);
176
198
  record.status = "pending";
177
199
  record.leaseExpiresAt = undefined;
200
+ record.nextAttemptAt = new Date(Date.now() + backoffMs).toISOString();
178
201
  await this.write(record);
179
202
  });
180
203
  }
@@ -196,6 +219,10 @@ export class DurableDispatchService {
196
219
  const record = await this.read(id);
197
220
  if (!record)
198
221
  return;
222
+ // A poison pill: give up on redelivery for good, once. Left on disk (not deleted) so
223
+ // `onExhausted`'s notice stays inspectable and the record is available for manual retry.
224
+ if (record.status === "exhausted")
225
+ return;
199
226
  // The turn is still running in this process: renew its lease rather than treating a
200
227
  // long turn as a lost one and redelivering the wake underneath it (D2).
201
228
  if (record.status === "running" && this.running.has(id)) {
@@ -212,9 +239,28 @@ export class DurableDispatchService {
212
239
  const leaseMs = record.leaseExpiresAt ? new Date(record.leaseExpiresAt).getTime() : undefined;
213
240
  if ((record.status === "queued" || record.status === "running") && leaseMs && leaseMs > now)
214
241
  return;
242
+ // markRetryable's backoff window; a plain enqueueEvent-rejected "pending" (no
243
+ // nextAttemptAt) still retries on the very next tick, as before.
244
+ const nextAttemptMs = record.nextAttemptAt ? new Date(record.nextAttemptAt).getTime() : undefined;
245
+ if (record.status === "pending" && nextAttemptMs && nextAttemptMs > now)
246
+ return;
247
+ if (record.deliveries >= MAX_DELIVERIES) {
248
+ record.status = "exhausted";
249
+ record.leaseExpiresAt = undefined;
250
+ record.nextAttemptAt = undefined;
251
+ await this.write(record);
252
+ try {
253
+ await this.options.onExhausted?.(record);
254
+ }
255
+ catch (err) {
256
+ log.logWarning(`Dispatch onExhausted handler failed for ${id}`, errorMessage(err));
257
+ }
258
+ return;
259
+ }
215
260
  record.status = "queued";
216
261
  record.deliveries++;
217
262
  record.leaseExpiresAt = new Date(now + this.leaseMs).toISOString();
263
+ record.nextAttemptAt = undefined;
218
264
  await this.write(record);
219
265
  const accepted = this.options.bot.enqueueEvent(withRedeliveryNotice({ ...record.event, dispatchId: record.id }, record.deliveries));
220
266
  if (accepted)
@@ -1,9 +1,10 @@
1
1
  import { existsSync } from "fs";
2
2
  import { readdir, readFile, unlink } from "fs/promises";
3
- import { join, resolve, sep } from "path";
3
+ import { join } from "path";
4
4
  import { renderSubcommandUsage } from "../agent/commands.js";
5
5
  import { capReply } from "../agent/reply-limits.js";
6
- import { errorMessage, eventNameFromFilename } from "../shared/text-utils.js";
6
+ import { normalizeSafeId, resolveSafeIdPath } from "../shared/safe-id.js";
7
+ import { errorMessage, eventNameFromFilename, clipText as sharedClipText } from "../shared/text-utils.js";
7
8
  import { parseScheduledEventContent } from "./events.js";
8
9
  const EVENT_NAME_PATTERN = /^[A-Za-z0-9._-]+$/;
9
10
  const DEFAULT_HISTORY_LIMIT = 20;
@@ -41,28 +42,18 @@ export function parseEventsCommand(args) {
41
42
  function eventsDir(workspaceDir) {
42
43
  return join(workspaceDir, "events");
43
44
  }
45
+ const SAFE_ID_OPTIONS = { suffix: ".json", pattern: EVENT_NAME_PATTERN, label: "event name" };
44
46
  // English on purpose: shared with the model-facing `event_manage` tool (src/tools/event-manage.ts),
45
47
  // which follows the tool-error convention elsewhere in the codebase, not the command-reply one.
46
48
  export function normalizeEventName(name) {
47
- const trimmed = name.trim();
48
- const normalized = trimmed.endsWith(".json") ? trimmed.slice(0, -".json".length) : trimmed;
49
- if (!normalized || normalized === "." || normalized === ".." || !EVENT_NAME_PATTERN.test(normalized)) {
50
- throw new Error(`Invalid event name: ${name}`);
51
- }
52
- return normalized;
49
+ return normalizeSafeId(name, SAFE_ID_OPTIONS);
53
50
  }
54
51
  export function resolveEventPath(workspaceDir, name) {
55
- const eventName = normalizeEventName(name);
56
- const dir = resolve(eventsDir(workspaceDir));
57
- const eventPath = resolve(dir, `${eventName}.json`);
58
- if (eventPath !== join(dir, `${eventName}.json`) || !eventPath.startsWith(`${dir}${sep}`)) {
59
- throw new Error(`Invalid event name: ${name}`);
60
- }
52
+ const { id: eventName, path: eventPath } = resolveSafeIdPath(eventsDir(workspaceDir), name, SAFE_ID_OPTIONS);
61
53
  return { eventName, eventPath };
62
54
  }
63
55
  function clipText(text, maxChars = TEXT_PREVIEW_MAX_CHARS) {
64
- const normalized = text.replace(/\s+/g, " ").trim();
65
- return normalized.length > maxChars ? `${normalized.slice(0, maxChars - 1)}...` : normalized;
56
+ return sharedClipText(text, maxChars, { headRatio: 1, omitHint: "...", collapseWhitespace: true });
66
57
  }
67
58
  function formatEventSummary(name, event) {
68
59
  const lines = [`**${name}**`, `- 类型:${event.type}`, `- channelId:${event.channelId}`];
@@ -102,8 +102,10 @@ export declare class EventsWatcher {
102
102
  * by hand, and then wakes the channel forever about work that no longer exists. Checking the
103
103
  * owner at trigger time turns that permanent noise into self-healing (spec 031, D5).
104
104
  *
105
- * The name alone is ambiguous (a channelId may contain dots), so the owning channel is taken
106
- * from the event definition and only the task id is parsed out of the remainder.
105
+ * The name alone is ambiguous (a channelId may contain dots, and so may a task id), so the
106
+ * owning channel is taken from the event definition and the id is parsed with the same
107
+ * last-dot rule the rest of the task-event code uses (`parseTaskEventName`), not a hand-rolled
108
+ * split that would cut a dotted task id short.
107
109
  */
108
110
  private orphanedOwnerReason;
109
111
  private execute;
@@ -4,11 +4,13 @@ import { readFile } from "fs/promises";
4
4
  import { dirname, join, resolve } from "path";
5
5
  import * as log from "../log.js";
6
6
  import { guardCommand } from "../security/command-guard.js";
7
+ import { writeFileAtomicallySync } from "../shared/atomic-file.js";
7
8
  import { createJsonlAppender } from "../shared/jsonl-appender.js";
8
9
  import { formatLocalTime, parseLocalTime } from "../shared/local-time.js";
9
- import { errorMessage, eventNameFromFilename } from "../shared/text-utils.js";
10
+ import { clipText, errorMessage, eventNameFromFilename } from "../shared/text-utils.js";
11
+ import { isPlainObject } from "../shared/type-guards.js";
10
12
  import { parseTaskFrontmatter } from "../tasks/ledger.js";
11
- import { taskEventPrefix } from "../tasks/task-events.js";
13
+ import { parseTaskEventName } from "../tasks/task-events.js";
12
14
  import { MAX_EVENT_FILES, MAX_ONE_SHOT_DELAY_MS, validateScheduledEvent } from "./event-validation.js";
13
15
  // ============================================================================
14
16
  // EventsWatcher
@@ -20,13 +22,7 @@ const SCAN_CONCURRENCY = 4;
20
22
  const DEFAULT_PRE_ACTION_TIMEOUT_MS = 10_000;
21
23
  const TEXT_PREVIEW_MAX_CHARS = 160;
22
24
  function truncateTextPreview(text) {
23
- const normalized = text.replace(/\s+/g, " ").trim();
24
- return normalized.length > TEXT_PREVIEW_MAX_CHARS
25
- ? `${normalized.slice(0, TEXT_PREVIEW_MAX_CHARS - 1)}…`
26
- : normalized;
27
- }
28
- function isRecord(value) {
29
- return typeof value === "object" && value !== null && !Array.isArray(value);
25
+ return clipText(text, TEXT_PREVIEW_MAX_CHARS, { headRatio: 1, omitHint: "…", collapseWhitespace: true });
30
26
  }
31
27
  function readRequiredString(data, field, filename) {
32
28
  const value = data[field];
@@ -38,7 +34,7 @@ function readRequiredString(data, field, filename) {
38
34
  function parsePreAction(data, filename) {
39
35
  if (!data.preAction)
40
36
  return undefined;
41
- if (!isRecord(data.preAction)) {
37
+ if (!isPlainObject(data.preAction)) {
42
38
  throw new Error(`Invalid 'preAction' field in ${filename}, expected an object`);
43
39
  }
44
40
  const action = data.preAction;
@@ -61,7 +57,7 @@ function parsePreAction(data, filename) {
61
57
  }
62
58
  export function parseScheduledEventContent(content, filename) {
63
59
  const data = JSON.parse(content);
64
- if (!isRecord(data)) {
60
+ if (!isPlainObject(data)) {
65
61
  throw new Error(`Missing required fields (type, channelId, text) in ${filename}`);
66
62
  }
67
63
  const type = readRequiredString(data, "type", filename);
@@ -479,17 +475,16 @@ export class EventsWatcher {
479
475
  * by hand, and then wakes the channel forever about work that no longer exists. Checking the
480
476
  * owner at trigger time turns that permanent noise into self-healing (spec 031, D5).
481
477
  *
482
- * The name alone is ambiguous (a channelId may contain dots), so the owning channel is taken
483
- * from the event definition and only the task id is parsed out of the remainder.
478
+ * The name alone is ambiguous (a channelId may contain dots, and so may a task id), so the
479
+ * owning channel is taken from the event definition and the id is parsed with the same
480
+ * last-dot rule the rest of the task-event code uses (`parseTaskEventName`), not a hand-rolled
481
+ * split that would cut a dotted task id short.
484
482
  */
485
483
  async orphanedOwnerReason(filename, event) {
486
- const prefix = taskEventPrefix(event.channelId);
487
- const name = eventNameFromFilename(filename);
488
- if (!name.startsWith(prefix))
489
- return undefined;
490
- const taskId = name.slice(prefix.length).split(".")[0];
491
- if (!taskId)
484
+ const parsed = parseTaskEventName(eventNameFromFilename(filename), event.channelId);
485
+ if (!parsed)
492
486
  return undefined;
487
+ const taskId = parsed.id;
493
488
  const taskPath = join(dirname(this.eventsDir), event.channelId, "tasks", `${taskId}.md`);
494
489
  let content;
495
490
  try {
@@ -655,7 +650,7 @@ export class EventsWatcher {
655
650
  }
656
651
  markInvalid(filename, message) {
657
652
  try {
658
- writeFileSync(this.getInvalidMarkerPath(filename), [`timestamp: ${new Date().toISOString()}`, `file: ${filename}`, "", message.trim()].join("\n"), "utf-8");
653
+ writeFileAtomicallySync(this.getInvalidMarkerPath(filename), [`timestamp: ${formatLocalTime()}`, `file: ${filename}`, "", message.trim()].join("\n"));
659
654
  }
660
655
  catch (err) {
661
656
  log.logWarning(`Failed to write event error marker: ${filename}`, String(err));
@@ -213,7 +213,7 @@ async function showRun(channelId, ref) {
213
213
  lines.push("", "⚠ 派发时的警告:", ...record.invocationWarnings.map((warning) => `- ${warning}`));
214
214
  }
215
215
  if (record.sessionId)
216
- lines.push(`- sessionId:\`${record.sessionId}\`(可用于 subagent_manage op=follow_up)`);
216
+ lines.push(`- sessionId:\`${record.sessionId}\`(可用于 subagent_run op=follow_up)`);
217
217
  if (record.runtime === "external") {
218
218
  const stderrTail = await readFile(join(record.artifactDir, "stderr.log"), "utf-8")
219
219
  .then((text) => text.slice(-STDERR_TAIL_CHARS))
@@ -13,7 +13,7 @@ export interface HandleTasksCommandOptions {
13
13
  *
14
14
  * Deliberately a small, flat set: the ones a user already knows they want to change (when it
15
15
  * should wake, what it should do next, how much rope it has). Everything structural — status
16
- * transitions and verification — stays with `task_manage`, whose state
16
+ * transitions and verification — stays with `task_update`/`task_close`/`task_verify`, whose state
17
17
  * machine those fields belong to. The value is the rest of the line, so it may contain spaces.
18
18
  */
19
19
  declare const SETTABLE_TASK_FIELDS: readonly ["wake", "next", "deadline"];