@oyasmi/pipiclaw 0.9.3-beta.2 → 0.9.3-beta.3

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 (79) hide show
  1. package/dist/agent/job-manager.d.ts +9 -0
  2. package/dist/agent/job-manager.js +20 -6
  3. package/dist/agent/prompt/builder.d.ts +1 -1
  4. package/dist/agent/prompt/builder.js +1 -1
  5. package/dist/agent/prompt/sections.js +3 -3
  6. package/dist/executor.d.ts +5 -1
  7. package/dist/executor.js +35 -5
  8. package/dist/file-store.d.ts +4 -1
  9. package/dist/file-store.js +5 -0
  10. package/dist/memory/journal.d.ts +13 -0
  11. package/dist/memory/journal.js +47 -4
  12. package/dist/memory/search.js +13 -6
  13. package/dist/memory/session-corpus.d.ts +11 -0
  14. package/dist/memory/session-corpus.js +15 -4
  15. package/dist/memory/session-search.d.ts +3 -0
  16. package/dist/memory/session-search.js +45 -8
  17. package/dist/memory/store.d.ts +9 -0
  18. package/dist/memory/store.js +25 -2
  19. package/dist/playbooks/agent-delegation.md +35 -76
  20. package/dist/playbooks/background-jobs.md +14 -16
  21. package/dist/playbooks/event-scheduling.md +20 -25
  22. package/dist/playbooks/memory-and-learning.md +28 -61
  23. package/dist/playbooks/outbound-media.md +10 -12
  24. package/dist/playbooks/runtime-orientation.md +34 -53
  25. package/dist/playbooks/task-loop.md +49 -69
  26. package/dist/runtime/bootstrap.js +25 -11
  27. package/dist/security/path-guard-filter.d.ts +22 -0
  28. package/dist/security/path-guard-filter.js +35 -0
  29. package/dist/subagents/discovery.d.ts +2 -3
  30. package/dist/subagents/discovery.js +3 -1
  31. package/dist/subagents/tool.d.ts +6 -0
  32. package/dist/subagents/tool.js +10 -2
  33. package/dist/tasks/brief.d.ts +1 -1
  34. package/dist/tasks/brief.js +11 -2
  35. package/dist/tasks/log.d.ts +4 -0
  36. package/dist/tasks/log.js +13 -1
  37. package/dist/tools/bash.d.ts +13 -0
  38. package/dist/tools/bash.js +123 -20
  39. package/dist/tools/edit.js +36 -5
  40. package/dist/tools/event-manage.d.ts +25 -4
  41. package/dist/tools/event-manage.js +81 -33
  42. package/dist/tools/glob.js +57 -4
  43. package/dist/tools/grep.d.ts +2 -0
  44. package/dist/tools/grep.js +187 -14
  45. package/dist/tools/job.js +16 -4
  46. package/dist/tools/memory-manage.js +80 -41
  47. package/dist/tools/read.js +42 -5
  48. package/dist/tools/registry.d.ts +6 -0
  49. package/dist/tools/registry.js +4 -1
  50. package/dist/tools/send-media.js +6 -4
  51. package/dist/tools/session-search.js +4 -1
  52. package/dist/tools/skill.d.ts +2 -0
  53. package/dist/tools/skill.js +12 -0
  54. package/dist/tools/subagent-manage.js +1 -1
  55. package/dist/tools/subagent-tool-names.d.ts +11 -0
  56. package/dist/tools/subagent-tool-names.js +19 -0
  57. package/dist/tools/task-manage/log-view.js +6 -3
  58. package/dist/tools/task-manage/schema.d.ts +6 -6
  59. package/dist/tools/task-manage/schema.js +5 -12
  60. package/dist/tools/task-manage/shared.js +16 -2
  61. package/dist/tools/task-manage/step-end.js +22 -5
  62. package/dist/tools/task-manage.js +9 -1
  63. package/dist/tools/web-cache.d.ts +11 -3
  64. package/dist/tools/web-cache.js +26 -8
  65. package/dist/tools/web-fetch.d.ts +1 -0
  66. package/dist/tools/web-fetch.js +68 -15
  67. package/dist/tools/write.js +3 -0
  68. package/dist/web/fetch.d.ts +5 -0
  69. package/dist/web/fetch.js +36 -1
  70. package/examples/sub-agents/README.md +14 -4
  71. package/examples/sub-agents/builder-hard.md +12 -34
  72. package/examples/sub-agents/builder.md +11 -31
  73. package/examples/sub-agents/explorer.md +10 -16
  74. package/examples/sub-agents/git-committer.md +15 -20
  75. package/examples/sub-agents/planner.md +11 -21
  76. package/examples/sub-agents/reviewer.md +10 -31
  77. package/examples/sub-agents/verifier.md +12 -27
  78. package/examples/sub-agents/worker.md +11 -35
  79. package/package.json +7 -3
@@ -1,110 +1,90 @@
1
1
  ---
2
2
  name: task-loop
3
- description: 判断该不该建长程任务(task)、怎么写任务契约,以及在任务循环里推进、等待、验收和闭环。
3
+ description: 判断是否建长程任务(task)、编写契约,或在 TASK_STEP 中推进、等待、验收、完成和恢复时。
4
4
  requires-tools: task_create, task_step_end
5
5
  order: 70
6
6
  ---
7
7
 
8
- # 长程任务:建档与循环
8
+ # 长程任务:契约与循环
9
9
 
10
- 任务是**跨回合恢复**的工作单元。运行时负责调度和兜底,你负责判断。每一步的 brief 已经给了契约全文、最近日志和当前预算;这里讲的是这些数字之外需要你判断的部分。
10
+ 只为需要跨回合恢复、等待外部结果或周期性产出的工作建 task;当前回合可完成的请求、一次临时委派不建。纯提醒或条件传感器用 event,需要创建时读 `event-scheduling.md`。
11
11
 
12
- ## 什么时候建 task
12
+ ## 先识别入口
13
13
 
14
- 只有工作需要跨回合恢复时才建:多步骤目标、要等人或外部系统、要委派、周期性产出。当前回合能做完的请求不建台账。纯提醒或外部条件探测用 event(见 `event-scheduling.md`);只在当前回合委派一次也不需要 task。
15
-
16
- 只把**可独立推进、可独立验收**的长期工作拆成多个 task。任务之间没有依赖字段:先后条件写进后继任务的 Goal/Manual。
17
-
18
- ## 写契约
14
+ | 当前环境 | 可做什么 |
15
+ |---|---|
16
+ | 普通聊天 | task_create 建档,task_update 改 Plan/节奏/预算/验收要求,task_close 完成/跳过/取消;传感器在这里用 event_manage 预先创建 |
17
+ | `[TASK_STEP:<id>]` / 有 task_step_end | 推进当前契约并用 task_step_end 收尾;没有 task_create、memory_save、event_manage,不绕过这些边界 |
19
18
 
20
- `task_create` 的四段是整个循环唯一的长期真相,每一步都会完整读到它,所以要短、要准:
19
+ 创建后由 runtime 在独立的 cycle 会话推进。带 taskId 的普通聊天仍是聊天,不因此获得 task_step_end。只拆分可独立推进和验收的长期任务;没有任务依赖字段,前置条件写进后继 Goal/Manual。
21
20
 
22
- - `goal`:最终要成立的**结果**,不写行动清单;范围和对外动作边界写在这里。
23
- - `dod`:客观验收标准,每项必须是 `- [ ]` checkbox。写不出 checkbox 说明目标还没想清楚。**用户的适用要求要在这里变成检查项**——"用户喜欢简单"不是 DoD,"不新增依赖和持久状态,除非说明本次为什么必要"才是。
24
- - `manual`:可复用的执行步骤、预检、幂等方法、返工教训。这是任务自己的记忆——学到什么就更新它。
25
- - `verificationPlan`:独立验收者能执行的确定性检查。功能之外,把适用要求和复杂度也写成可判真假的检查。
21
+ ## 写短而自足的契约
26
22
 
27
- **同一条适用要求必须同时进入执行者和验收者的上下文**,不能等代码写完再补标准。
23
+ 每一步都会得到完整契约,写得越长,每步成本越高。约 4 KB 是作者应控制的目标;代码只裁剪“上次结果”,不会替你压缩 Goal/Manual。
28
24
 
29
- 有代码、配置或可复现产物时设 `verificationRequired: true`;纯提醒、沟通和主观写作保持默认。
25
+ - **goal**:要成立的结果、范围、允许的外部动作。创建即持续委托,Goal 与工具/security 共同限制授权边界,不存在逐次授权字段。
26
+ - **dod**:客观验收标准,必须是 `- [ ]` checklist;将适用用户要求变成检查项。
27
+ - **manual**:本任务可复用的步骤、预检、幂等办法和已验证的返工教训。
28
+ - **verificationPlan**:可执行的检查及证据要求,执行者和验收者拿到同一标准。
30
29
 
31
- 契约有 4 KB 预算,但它约束的是运行时写的 `## 上次结果`,不会删你写的段落。**每一步的记录不写进契约**,写进 `task_step_end` 的 `note`;历史用 `task_log` 查。
30
+ 用户明确要求、实质实现改动、高后果或难以自查的工作设 `verificationRequired:true`。稳定流程的低风险产物若已有充分确定性检查,可以保留默认;不能通过关闭既定验收要求来绕过失败。
32
31
 
33
- `schedule`(五字段 cron,最小 30 分钟)让任务变成周期性的:每个 occurrence 一个 cycle,闭环后自动停到下一次。
32
+ `plan` / `planSteps` 表达手段与可验证产出,不复抄 DoD;四态 todo/done/blocked/dropped,可用 `→ dod:1,2` 指向验收项。改契约正文或勾选 checklist 用 `edit` 打开 brief 中的绝对文件路径;task_update 只改其暴露的字段和 Plan。
34
33
 
35
- Task 创建即持续委托:能触达什么由可用工具、security 配置和 Goal 共同约束,没有逐次授权的字段。**Goal 的边界就是授权的边界,宁可写窄。**
34
+ schedule 是主机时区的五段 cron,最小 30 分钟。首周期创建后立即就绪;若首次应等待约定时刻,在任务里明确并用 time 票等待。预算含 steps、wallMin、usd、rounds,可按需设 until;**wallMin 是 cycle 开始后的经过时间,包含 park 等待**,建档时计入等待跨度。
36
35
 
37
- ## Plan:手段层
36
+ ## 推进一步并收尾
38
37
 
39
- 预计需要多步时用 `plan` 创建步骤,或用 `task_update` 的 `planSteps` 更新。Plan 是手段,不是第二份 DoD;每步写可验证产出,可选 `→ dod:1,2` 引用。四态 `[ ]` todo、`[x]` done、`[!]` blocked、`[~]` dropped。周期任务每个新 cycle 会把 Plan 和 DoD 复位。
38
+ 先看 `<task_contract>`、最近 `<task_log>` 和 `<task_state>`,用已有契约,不再重复打开。历史或证据不够才 task_log;round 摘要只有 verdict/runId/拒绝原因,失败细节在该 run 的 output.md,不能凭一行 FAIL 猜根因。
40
39
 
41
- ## 在循环里推进
40
+ | 判断 | task_step_end outcome |
41
+ |---|---|
42
+ | 完成这一阶段,还有可推进工作 | continue,note 留下证据和下一步 |
43
+ | 必须等待真实来源 | park,附 run/job/time/signal 票 |
44
+ | 本周期达标 | done,必须有 summary 和 evidence;周期任务由 runtime 自动停到下一次 |
45
+ | 需要用户决定 | blocked,reason 写清问题;runtime 建 ask 票并通知用户 |
42
46
 
43
- 每一步先看清 brief 里的 `<task_contract>`、`<task_log>` 和 `<task_state>`,再动手。派发是 at-least-once,**外部动作前先查真实状态**,别重复发送、发布或部署。
47
+ **本周期完成一律 done,不用 park + schedule 代替。** 明确跳过一次用 task_close outcome=skip 并给 reason;放弃整个任务用 cancel。关闭/取消不会代替你取消仍在运行的委派或 job。
44
48
 
45
- `<task_log>` 给的是最近若干条记录,**不是全部结论**:round 记录只有 verdict、runId 和被拒原因,真正的失败现象在委派的 `output.md` 里。要判断"这次到底哪儿不对",读那份实际产物和实际报错,别拿一行 verdict 当根因。更早的历史用 `task_log` 翻。
49
+ 任务步骤默认静默;确有交付或需告知的变化才用 notify。若 Goal/DoD 要求“交付、告知、汇报、回复”结果,notify 必须包含要发给用户的实际内容;note 只是内部循环记录,不会发送给用户。note 只写真实做过什么、证据和下一步;不把每步过程追加到契约。Plan 可在 task_step_end 中一并更新。**每个任务步骤,包括 run/job 完成后的唤醒步骤,都必须以一次成功的 task_step_end 结束;读取到结果后直接输出普通文本会被丢弃,任务也不会结算。**
46
50
 
47
- 只推进一个清晰的下一阶段,然后用 `task_step_end` 收尾:
51
+ ## 等待与恢复
48
52
 
49
- - 还能接着干 → `continue`。运行时立刻排下一步,没有等待。
50
- - 在等一个真实来源 → `park`,带上对应的票。委派用 `run`、后台作业用 `job`、单纯过一阵再看用 `time`、周期任务闭环用 `schedule`、task-owned 传感器事件用 `signal`。
51
- - 本周期做完了 → `done`,必须给 `summary` 和 `evidence`。
52
- - 需要用户决定 → `blocked`,写清在等什么。
53
+ run/job 派发时即带 taskId;先完成独立工作和必要的并行派发,只剩等待才 park。run 用 `{"kind":"run","id":"<runId>"}`,job 同形;定时复查用 `{"kind":"time","at":"+2h"}`;预置传感器用 `{"kind":"signal","event":"<事件名>"}`。
53
54
 
54
- **票必须指向真实存在的东西**:运行时会当场校验,指不到就拒绝。这是设计——一次指不到的等待就是一次永久静默。
55
+ 票只接受真实、未结束且属于本任务的来源。结果同步返回或 park 时已结算,就读结果继续,不等待第二次通知;id/归属错误按工具指引纠正,不能手改 ticket frontmatter。已有 job/run 完成通知,不另建回访事件。
55
56
 
56
- **默认不向用户发言。** 确实要说才给 `notify`;`blocked` 一定会说。
57
+ signal 事件必须在聊天侧预建为 task.<channelId>.<taskId>.<use> 的 periodic;循环先检查条件,未满足才等待。缺少事件且不能自主继续时 blocked 说明缺什么,不绕过工具限制。
57
58
 
58
- ## 外部动作的幂等闭环
59
+ 票自带 runtime 兜底。过期后的 brief 会标明等待来源:先检查真实状态,再继续或换票;同 cycle 第二次过期停止并通知用户。预算任一项耗尽也会停止;这些回执由 runtime 发出,无需再花模型回合解释。用户命令 `/tasks resume <id>` 恢复、`/tasks reply <id> ...` 回答阻塞问题。
59
60
 
60
- 外部发送、发布、部署或修改前:
61
+ ## 外部动作
61
62
 
62
- 1. 读 Goal 和 DoD 确认动作仍在范围内,并查询目标真实状态。
63
- 2. 确认此前没有已成功的同一动作;用稳定的 request / message / idempotency key 执行。
64
- 3. 查询并记录真实结果、目标标识、时间和证据到 `note`。
65
- 4. 只有结果已满足 DoD 才 `done`;失败就 `continue` 或 `park` 并写清恢复来源。
63
+ 派发是 at-least-once。发送、发布、部署或修改外部对象前,核对 Goal/DoD 与目标真实状态,排除此前已成功的同一动作;能用稳定 request/message/idempotency key 就使用。操作后记录真实结果、目标标识、时间和证据,达标才 done。结果未知先核查,不盲目重放。
66
64
 
67
- 附件交付的 receipt 规则见 `outbound-media.md`。
65
+ 交付附件时读 `outbound-media.md`:send_media 成功回执可作证据,但接口没有消息 id 或二次状态查询,不能虚构。
68
66
 
69
67
  ## 独立验收
70
68
 
71
- 1. 只有证据成立后才勾选 DoD / Verification checklist。
72
- 2. 像任何委派一样派一个 `purpose: verify`、带 `taskId` 的 sub-agent,然后 `park` 到那个 run 的票上。
73
- 3. checker 只判断、不修复被验收实现,结尾返回 `VERDICT: PASS` 或 `VERDICT: FAIL`。
74
- 4. **结算时运行时自动记账**:校验 attestation(归属、契约 hash、产物 subject),把这一轮写进返工账本,然后兑现你的票。你不需要导入任何东西——醒来时结论已经在 `<task_log>` 里。
75
- 5. attestation 校验不过的 PASS 会被记成 FAIL 并写明原因。标 `advisory` 的结论(带 `bash` 的内置验收者、`mutates: write` 的 verifier、所有外部验收者)只是参考,仍要按风险抽查;强度来源见 `agent-delegation.md`。
76
- 6. `verify: required` 的任务,关闭时会**重新校验**本周期最后一条 round:它必须是 PASS,且 attestation 此刻仍绑定当前契约和当前产物。所以「先通过验收、再改 Goal 或再改代码」不会被放行;后来的 FAIL 也不会被更早的 PASS 覆盖。返工轮次有预算,到顶会停下来问用户。
77
-
78
- PASS 绑定 Goal/DoD/Manual/Verification 这段契约,不绑定 Plan 和历史。**改动契约或被验收产物后必须重新验收**——包括为了记录教训去改 Manual。产物从一棵 worktree 整合到另一处之后,要针对最终交付的位置重新确认覆盖,源 worktree 的证明不为目标产物背书。
79
-
80
- ### 裁决反馈,再返工
81
-
82
- 验收和审查的输出是待裁决的材料,不是待执行的清单。先分类:
83
-
84
- | 反馈 | 处理 |
85
- |---|---|
86
- | 违反 DoD/明确约束,且有复现证据 | 返工,并写明哪些已通过的行为必须保持 |
87
- | 疑似缺陷,证据不足 | 先做一次窄范围调查或补验证,不直接大改 |
88
- | 缺前置条件 | 能解决的先解决;要等外部条件就 `park` 到对应来源 |
89
- | 风格建议、任务外增强 | 不作为本轮失败理由;有价值另记候选 |
90
- | 两条反馈互相冲突 | 回到契约和真实产物判断,必要时补一个有区分力的实验 |
91
-
92
- 给执行者的返工文本按**现象 → 证据 → 违反了哪条标准 → 本轮修复边界 → 怎么重验**写,不要只说"审查者不满意,再改好一点"。
69
+ 需要委派但还未准备好执行者、上下文或工作目录时,读 `agent-delegation.md` 对应部分。
93
70
 
94
- 同一个问题连续两轮失败又没有新证据时,改变调查方式、缩小复现,或换一个执行者——重复同一次尝试只是在花钱。**过了约定标准、没有未解决的必修项就交付**;预算还有余额不会把可选优化变成任务目标。
71
+ 1. 实施、正式测试、文档和收尾改动全部完成,自查证据成立后勾选 DoD/Verification。
72
+ 2. 派 purpose=verify 且带 taskId 的角色,给同一契约、适用要求、最终交付位置与版本。验收者只判断,不修复实现;结尾输出 `VERDICT: PASS` 或 `VERDICT: FAIL`。
73
+ 3. 同步完成直接处理,异步才 park 到 run。结算自动校验归属、契约 hash 和产物 subject,并写入 round,无需手动导入。
74
+ 4. 关闭要求本周期最后一条 round 为 PASS,且证明仍绑定当前契约和产物;后来的 FAIL 不会被更早 PASS 覆盖。
95
75
 
96
- ## 预算与停止
76
+ 证明强度:内置 mutates=read 且无 bash 的 verifier 才是 enforced;带 bash、mutates=write 或任何外部 verifier 都是 advisory,按风险核对关键证据。write verifier 会持有写 lease,能跑生成临时文件的检查;exec 没有协议终态,不支持正式验收。mutates 不是 sandbox。
97
77
 
98
- 每个 cycle 有四维预算:步数、墙钟、成本、返工轮次(可在 `task_create`/`task_update` 的 `budget` 里按任务调整)。任一项到顶,运行时停掉任务并给用户一条确定性回执,附加预算的命令。连续两步没有任何工具调用也会被停下——那说明循环在自言自语。
78
+ 验收不得修改被验收实现或为了通过而修代码。取证脚本可放 `.run/`、coverage/build/dist 或系统临时目录;往正式源码或测试目录新增文件也会改变 subject,要交回实现者处理并重验。
99
79
 
100
- **只记录真实工作**:`note` 写做了什么、证据是什么、下一步是什么,不写愿望。失败的一轮也写一条:失败原因、哪些反馈采纳了、这一轮准备改变什么。
80
+ PASS 绑定 Goal/DoD/Manual/Verification 与实际产物,不绑定 Plan 或历史。修改这些契约段落、补代码/文档/测试、commit hook 改内容都会要求重验;base-relative subject 允许原样提交已验收内容。跨 worktree 整合后,要对最终交付位置重新确认覆盖。
101
81
 
102
- 学到的东西按三个落点分:任务内的执行经验先进 `note`;需要约束**后续实施**的,在最终验收前更新 `manual`;多次验证有效的跨任务流程才整理成 workspace skill(见 `memory-and-learning.md`)。**PASS 之后的新教训先留在循环日志里**——改 Manual 会改变契约、让这条 PASS 失效,下个周期真要采纳时再更新。
82
+ ## 先裁决反馈,再返工
103
83
 
104
- ## 等待票过期
84
+ 违反 DoD/明确约束且有复现证据的才返工;疑似问题先窄范围调查;任务外增强和风格建议不作为失败理由;冲突意见回到契约与实际产物,用有区分力的检查裁决。
105
85
 
106
- 票有兜底时限。到点还没兑现,运行时会把任务重新打开,并在 brief 开头告诉你票过期了。这时**先确认真实状态**(那个 run 到底结束没有?那个条件到底成立没有?),再决定继续还是换一张票。同一 cycle 内第二次过期会停掉任务并通知用户。
86
+ 返工指令写 **现象 → 证据 → 违反标准 → 修复边界与已通过项 → 重验办法**。同一问题连续两轮失败且无新证据时,缩小复现、换调查方法或执行者。达到约定标准、没有未解决必修项就交付,预算余额不代表需要继续润色。
107
87
 
108
- ## 契约损坏
88
+ 教训先写 note;影响后续实施的,在最终验收前更新 Manual。PASS 后新教训留日志,真正采纳再改契约并重验。多次验证有效且跨任务复用时,再按 `memory-and-learning.md` 的 skill 晋升规则处理。
109
89
 
110
- frontmatter 不可读或仍是旧版契约时,唤醒会明确要求**只修元数据、不执行任务目标**。用 `edit` 修好首部后就停下,任务工作留给下一步。
90
+ frontmatter 损坏或仍是旧契约时只修元数据,修好后停下,工作留给下一步;不要手造等待票或借修复扩大任务范围。
@@ -160,9 +160,9 @@ function createDingTalkHandler(deps) {
160
160
  */
161
161
  const prepareTaskStep = async (event, runner) => {
162
162
  const match = /^\[TASK_DRIVER:([A-Za-z0-9._-]+)\]/.exec(event.text);
163
- if (!match?.[1] || !runner.bindTaskSession)
163
+ const taskId = match?.[1] ?? event.internalWake?.taskId;
164
+ if (!taskId || !runner.bindTaskSession)
164
165
  return undefined;
165
- const taskId = match[1];
166
166
  const channelDir = ensureChannelDir(options.paths.workspaceDir, event.channelId);
167
167
  try {
168
168
  const document = await readStoredTask(channelDir, taskId);
@@ -180,12 +180,19 @@ function createDingTalkHandler(deps) {
180
180
  }
181
181
  };
182
182
  /** Deliver whatever the step asked to say, then hand the runner back to the chat session. */
183
- const finishTaskStep = async (channelId, taskId, ctx) => {
183
+ const finishTaskStep = async (channelId, taskId, bot) => {
184
184
  const channelDir = ensureChannelDir(options.paths.workspaceDir, channelId);
185
185
  try {
186
186
  const notice = await consumeTaskNotice(channelDir, taskId);
187
- if (notice)
188
- await ctx.respond(notice, true);
187
+ if (notice) {
188
+ // runner.run closes its per-turn delivery context before returning. Sending through that
189
+ // closed context silently dropped successful task_step_end notifications (T-run-01).
190
+ const delivered = await bot.sendPlain(channelId, notice);
191
+ if (delivered)
192
+ await store.logBotResponse(channelId, notice, Date.now().toString());
193
+ else
194
+ log.logWarning(`[${channelId}] Failed to deliver task notice for ${taskId}`);
195
+ }
189
196
  }
190
197
  catch (error) {
191
198
  log.logWarning(`[${channelId}] Could not deliver task notice for ${taskId}`, errorMessage(error));
@@ -525,15 +532,13 @@ function createDingTalkHandler(deps) {
525
532
  // wake (a delegation or job finishing) is the opposite — a human is actually waiting
526
533
  // on it — so it renders progress the same way a normal message does (P0-2).
527
534
  const backgroundOnly = Boolean(_isEvent) && event.presentation !== "awaited";
528
- const baseCtx = createDingTalkContext(event, bot, store, backgroundOnly ? "none" : undefined);
529
535
  // Spec 051, D3: a task-driver dispatch runs as a *task step* — in the task cycle's
530
536
  // own session, with a brief instead of the wake text, and silent unless the step
531
537
  // asked for a notify. Everything below (busy state, /stop, delivery) is unchanged;
532
538
  // only which session the turn is bound to, and what reaches the channel, differ.
533
- const taskStep = await prepareTaskStep(event, runner);
534
- const ctx = taskStep ? muteChannelContext(baseCtx) : baseCtx;
535
- if (taskStep)
536
- event = { ...event, text: taskStep.brief };
539
+ let taskStep;
540
+ let baseCtx = createDingTalkContext(event, bot, store, backgroundOnly ? "none" : undefined);
541
+ let ctx = baseCtx;
537
542
  if (builtInCommand) {
538
543
  const commandStartedAt = Date.now();
539
544
  const logCtx = { channelId: event.channelId, userName: event.userName };
@@ -648,9 +653,17 @@ function createDingTalkHandler(deps) {
648
653
  }
649
654
  }
650
655
  }
656
+ // Verified job/run wakes that activate a task are task steps too. Verification must happen
657
+ // first: routing directly from user-controlled wake text would grant task-only tools.
658
+ taskStep = await prepareTaskStep(event, runner);
659
+ if (taskStep) {
660
+ event = { ...event, text: taskStep.brief };
661
+ baseCtx = createDingTalkContext(event, bot, store, backgroundOnly ? "none" : undefined);
662
+ ctx = muteChannelContext(baseCtx);
663
+ }
651
664
  const result = await runner.run(ctx, store);
652
665
  if (taskStep)
653
- await finishTaskStep(event.channelId, taskStep.taskId, baseCtx);
666
+ await finishTaskStep(event.channelId, taskStep.taskId, bot);
654
667
  if (result.stopReason === "aborted" && runner.getTurnStatus().stopRequested) {
655
668
  log.logInfo(`[${event.channelId}] Stopped`);
656
669
  }
@@ -782,6 +795,7 @@ export async function createRuntimeContext(options) {
782
795
  // can start one, then re-adopt whatever survived the last shutdown (spec 031, D6).
783
796
  configureJobRuntime({
784
797
  jobsStateDir: join(options.paths.appHomeDir, "state", "jobs"),
798
+ workspaceDir: options.paths.workspaceDir,
785
799
  dispatch: (event) => durableDispatch?.dispatch(event) ?? false,
786
800
  ...(options.jobSweepIntervalMs ? { sweepIntervalMs: options.jobSweepIntervalMs } : {}),
787
801
  });
@@ -0,0 +1,22 @@
1
+ import type { SecurityConfig, SecurityRuntimeContext } from "./types.js";
2
+ /**
3
+ * Backstop read-guard filter for the recursive discovery tools (`grep`, `glob`, `skill list`).
4
+ *
5
+ * A direct `read`/`grep` on a denied path is refused by the per-path guard, but a *recursive*
6
+ * walk rooted at an allowed directory descends straight into denied subtrees — so `grep` would
7
+ * return the contents of a `readDeny`'d file and `glob` would leak its path. Every candidate hit
8
+ * is re-checked here against the read guard and denied entries are dropped before anything is
9
+ * rendered or counted.
10
+ *
11
+ * Residual risk, recorded honestly: for `grep` the child process has already read those files'
12
+ * bytes by the time this JS filter runs. The boundary this actually enforces is "no denied
13
+ * content reaches the model or the tool result". The push-down `--exclude`/`--exclude-dir` flags
14
+ * are what additionally keep `grep` from opening the file at all; this filter is the guarantee,
15
+ * those flags are the optimization. Do not claim the `grep` process never touches a denied file.
16
+ */
17
+ export declare function partitionByReadGuard(absolutePaths: string[], securityConfig: SecurityConfig, securityContext: SecurityRuntimeContext): {
18
+ allowed: string[];
19
+ deniedCount: number;
20
+ };
21
+ /** True when the read guard would allow this single absolute path. */
22
+ export declare function readGuardAllows(absolutePath: string, securityConfig: SecurityConfig, securityContext: SecurityRuntimeContext): boolean;
@@ -0,0 +1,35 @@
1
+ import { guardPath } from "./path-guard.js";
2
+ /**
3
+ * Backstop read-guard filter for the recursive discovery tools (`grep`, `glob`, `skill list`).
4
+ *
5
+ * A direct `read`/`grep` on a denied path is refused by the per-path guard, but a *recursive*
6
+ * walk rooted at an allowed directory descends straight into denied subtrees — so `grep` would
7
+ * return the contents of a `readDeny`'d file and `glob` would leak its path. Every candidate hit
8
+ * is re-checked here against the read guard and denied entries are dropped before anything is
9
+ * rendered or counted.
10
+ *
11
+ * Residual risk, recorded honestly: for `grep` the child process has already read those files'
12
+ * bytes by the time this JS filter runs. The boundary this actually enforces is "no denied
13
+ * content reaches the model or the tool result". The push-down `--exclude`/`--exclude-dir` flags
14
+ * are what additionally keep `grep` from opening the file at all; this filter is the guarantee,
15
+ * those flags are the optimization. Do not claim the `grep` process never touches a denied file.
16
+ */
17
+ export function partitionByReadGuard(absolutePaths, securityConfig, securityContext) {
18
+ const config = securityConfig.enabled ? securityConfig.pathGuard : { ...securityConfig.pathGuard, enabled: false };
19
+ const allowed = [];
20
+ let deniedCount = 0;
21
+ for (const path of absolutePaths) {
22
+ if (guardPath(path, "read", { ...securityContext, config }).allowed) {
23
+ allowed.push(path);
24
+ }
25
+ else {
26
+ deniedCount++;
27
+ }
28
+ }
29
+ return { allowed, deniedCount };
30
+ }
31
+ /** True when the read guard would allow this single absolute path. */
32
+ export function readGuardAllows(absolutePath, securityConfig, securityContext) {
33
+ const config = securityConfig.enabled ? securityConfig.pathGuard : { ...securityConfig.pathGuard, enabled: false };
34
+ return guardPath(absolutePath, "read", { ...securityContext, config }).allowed;
35
+ }
@@ -1,6 +1,6 @@
1
1
  import type { Api, Model } from "@earendil-works/pi-ai";
2
2
  import type { SecurityConfig } from "../security/types.js";
3
- declare const ALLOWED_SUB_AGENT_TOOLS: readonly ["read", "grep", "bash", "edit", "write", "web_search", "web_fetch"];
3
+ import { type SubAgentToolName } from "../tools/subagent-tool-names.js";
4
4
  declare const ALLOWED_CONTEXT_MODES: readonly ["isolated", "contextual"];
5
5
  declare const ALLOWED_MEMORY_MODES: readonly ["none", "index"];
6
6
  declare const ALLOWED_THINKING_LEVELS: readonly ["off", "minimal", "low", "medium", "high", "xhigh", "max"];
@@ -8,7 +8,7 @@ declare const ALLOWED_RUNTIMES: readonly ["internal", "external"];
8
8
  declare const ALLOWED_HARNESSES: readonly ["claude-code", "codex-cli", "exec"];
9
9
  declare const ALLOWED_WORKLOADS: readonly ["light", "heavy"];
10
10
  declare const ALLOWED_MUTATES: readonly ["read", "write"];
11
- export type SubAgentToolName = (typeof ALLOWED_SUB_AGENT_TOOLS)[number];
11
+ export type { SubAgentToolName };
12
12
  export type SubAgentContextMode = (typeof ALLOWED_CONTEXT_MODES)[number];
13
13
  export type SubAgentMemoryMode = (typeof ALLOWED_MEMORY_MODES)[number];
14
14
  export type SubAgentThinkingLevel = (typeof ALLOWED_THINKING_LEVELS)[number];
@@ -210,4 +210,3 @@ export declare function formatSubAgentList(agents: SubAgentConfig[], maxItems?:
210
210
  * rejected for the same reason (spec 042 design doc, "已驳回的方案").
211
211
  */
212
212
  export declare function externalRoleFingerprint(role: Pick<SubAgentConfig, "command" | "externalModelRef" | "shell">): string;
213
- export {};
@@ -8,7 +8,9 @@ import { findExactModelReferenceMatch, formatModelReference } from "../models/ut
8
8
  import { SUB_AGENTS_DIR_NAME } from "../paths.js";
9
9
  import { splitShellWords } from "../shared/shell-words.js";
10
10
  import { errorMessage } from "../shared/text-utils.js";
11
- const ALLOWED_SUB_AGENT_TOOLS = ["read", "grep", "bash", "edit", "write", "web_search", "web_fetch"];
11
+ import { SUBAGENT_TOOL_NAMES } from "../tools/subagent-tool-names.js";
12
+ /** Re-exported from the leaf source of truth so validation and the tool set never drift. */
13
+ const ALLOWED_SUB_AGENT_TOOLS = SUBAGENT_TOOL_NAMES;
12
14
  const DEFAULT_SUB_AGENT_TOOLS = ["read", "bash"];
13
15
  const DEFAULT_MAX_TURNS = 32;
14
16
  const DEFAULT_MAX_TOOL_CALLS = 96;
@@ -124,6 +124,12 @@ interface SubAgentWorker {
124
124
  * only caps what gets echoed into the parent's context.
125
125
  */
126
126
  export declare const MAX_SUBAGENT_RESULT_UNITS = 1200;
127
+ /**
128
+ * Character ceiling paired with the unit ceiling. `prompt-units.ts` notes that a long
129
+ * separator-free run of letters/digits counts as a single unit, so a units-only budget can still
130
+ * pass through an unbounded blob — every budget must bound units *and* chars (fix plan §2.4).
131
+ */
132
+ export declare const MAX_SUBAGENT_RESULT_CHARS = 12000;
127
133
  /** Exported for `subagent_run op=follow_up` (spec 042 D7), which constructs one of these for
128
134
  * its own new run rather than a hand-rolled envelope. */
129
135
  export interface SubAgentRunContext {
@@ -91,6 +91,12 @@ const TASK_ID_PATTERN = /^[A-Za-z0-9._-]+$/;
91
91
  * only caps what gets echoed into the parent's context.
92
92
  */
93
93
  export const MAX_SUBAGENT_RESULT_UNITS = 1_200;
94
+ /**
95
+ * Character ceiling paired with the unit ceiling. `prompt-units.ts` notes that a long
96
+ * separator-free run of letters/digits counts as a single unit, so a units-only budget can still
97
+ * pass through an unbounded blob — every budget must bound units *and* chars (fix plan §2.4).
98
+ */
99
+ export const MAX_SUBAGENT_RESULT_CHARS = 12_000;
94
100
  const RESULT_TRUNCATION_HEAD_RATIO = 1;
95
101
  /**
96
102
  * Spec 032 D6: when a turn/tool/wall-time budget is hit, the sub-agent gets one more,
@@ -224,7 +230,8 @@ function formatStatus(agentName, text) {
224
230
  function buildDispatchedText(runId, agentName, runtimeLabel, workingDirectory) {
225
231
  return (`[Dispatched] runId=${runId}, agent ${agentName} (${runtimeLabel}), working directory ${workingDirectory}.\n` +
226
232
  "Status: running. This channel will be woken with the result and artifact path once it finishes.\n" +
227
- "Do not dispatch it again or poll for it now -- end this turn. If it belongs to a task, mark it waiting with task_update.");
233
+ "Finish independent work and dispatches, then end the turn when only waiting remains; do not re-dispatch or poll to wait. " +
234
+ "Inside a task step, use task_step_end outcome=park with this run id.");
228
235
  }
229
236
  /**
230
237
  * `buildContextualBlocks` shared by the external dispatch path and `runToCompletion`'s internal
@@ -268,11 +275,12 @@ function buildStoppedText(config, reason, finalText) {
268
275
  */
269
276
  function finalizeSubAgentOutput(runContext, finalText) {
270
277
  const outputPath = join(runContext.artifactDir, "output.md");
271
- if (countPromptUnits(finalText) <= MAX_SUBAGENT_RESULT_UNITS) {
278
+ if (countPromptUnits(finalText) <= MAX_SUBAGENT_RESULT_UNITS && finalText.length <= MAX_SUBAGENT_RESULT_CHARS) {
272
279
  return { replyText: finalText, truncated: false };
273
280
  }
274
281
  const clipped = clipTextByPromptUnits(finalText, MAX_SUBAGENT_RESULT_UNITS, {
275
282
  headRatio: RESULT_TRUNCATION_HEAD_RATIO,
283
+ maxChars: MAX_SUBAGENT_RESULT_CHARS,
276
284
  marker: `\n\n[... truncated; full output saved at ${outputPath} ...]\n\n`,
277
285
  });
278
286
  return { replyText: clipped.text, truncated: true };
@@ -9,7 +9,7 @@ export interface TaskBriefInput {
9
9
  /**
10
10
  * The turn input for one task loop step (spec 051, D3).
11
11
  *
12
- * The contract is injected whole because it is small by construction (INV-6, 4 KB); the history
12
+ * The authored contract is injected whole; authors must keep it short. The history
13
13
  * is the last few log lines rather than the 24 KB of closed cycles v3 pasted into every wake. Any
14
14
  * pending `/tasks steer` or `/tasks reply` is consumed here and put first — it is the one thing in
15
15
  * the brief that is genuinely new since the previous step.
@@ -1,3 +1,5 @@
1
+ import { join } from "node:path";
2
+ import { PLAYBOOKS_DIR } from "../paths.js";
1
3
  import { effectiveBudget } from "./budget.js";
2
4
  import { readTaskLog, renderTaskLogLine } from "./log.js";
3
5
  import { consumeTaskSteer } from "./steer.js";
@@ -8,7 +10,7 @@ export const BRIEF_LOG_LINES = 8;
8
10
  /**
9
11
  * The turn input for one task loop step (spec 051, D3).
10
12
  *
11
- * The contract is injected whole because it is small by construction (INV-6, 4 KB); the history
13
+ * The authored contract is injected whole; authors must keep it short. The history
12
14
  * is the last few log lines rather than the 24 KB of closed cycles v3 pasted into every wake. Any
13
15
  * pending `/tasks steer` or `/tasks reply` is consumed here and put first — it is the one thing in
14
16
  * the brief that is genuinely new since the previous step.
@@ -25,8 +27,15 @@ export async function buildTaskStepBrief(input) {
25
27
  const blocks = [`[TASK_STEP:${input.taskId}]`];
26
28
  if (input.reason)
27
29
  blocks.push(input.reason);
30
+ // Reuse durable history instead of a new pending-wake flag. An expiry remains relevant until
31
+ // a later step records what recovery did; a verifier round in between does not consume it.
32
+ const lastTransition = [...log].reverse().find((record) => record.kind === "expired" || record.kind === "step");
33
+ if (lastTransition?.kind === "expired") {
34
+ blocks.push(`<task_recovery kind="expired">\n等待票过期:${lastTransition.ticket}。先核对来源的真实状态,再决定继续、换票或请求用户决定。\n</task_recovery>`);
35
+ }
28
36
  if (steer)
29
37
  blocks.push(`<user_guidance>\n${steer}\n</user_guidance>`);
38
+ blocks.push(`契约文件:${document.path}\n首次执行前读取 ${join(PLAYBOOKS_DIR, "task-loop.md")};已在当前上下文中完整读过则复用。`);
30
39
  blocks.push(`<task_contract id="${input.taskId}">\n${document.body.trim()}\n</task_contract>`);
31
40
  if (log.length > 0) {
32
41
  blocks.push(`<task_log recent="${log.length}">\n${log.map(renderTaskLogLine).join("\n")}\n</task_log>`);
@@ -34,7 +43,7 @@ export async function buildTaskStepBrief(input) {
34
43
  blocks.push(`<task_state>\n${renderState(document.fields)}\n</task_state>`);
35
44
  blocks.push("推进这个任务的下一个具体步骤,然后必须调用 task_step_end 收尾:" +
36
45
  "continue(还能继续)/ park(等一个真实来源)/ done(本周期完成)/ blocked(需要用户决定)。" +
37
- "默认不向用户发言;确实需要告诉用户时用 notify。");
46
+ "默认不向用户发言;契约要求交付、告知、汇报或回复时,必须把实际内容放进 notify,note 不会发送给用户。");
38
47
  return blocks.join("\n\n");
39
48
  }
40
49
  function renderState(fields) {
@@ -56,6 +56,10 @@ export interface TaskCloseRecord {
56
56
  }
57
57
  export type TaskLogRecord = TaskStepRecord | TaskRoundRecord | TaskExpiredRecord | TaskCloseRecord;
58
58
  export declare function taskLogPath(channelDir: string, id: string): string;
59
+ /** Where `archiveTask` moves a closed task's `.jsonl`. */
60
+ export declare function taskArchiveLogPath(channelDir: string, id: string): string;
61
+ /** True when the loop log for `id` lives only in the archive (the task is closed). */
62
+ export declare function taskLogIsArchived(channelDir: string, id: string): boolean;
59
63
  /** Test seam: drop cached appenders so a temp-dir fixture does not leak into the next case. */
60
64
  export declare function resetTaskLogAppenders(): Promise<void>;
61
65
  export type TaskLogInput = (Omit<TaskStepRecord, "ts"> & {
package/dist/tasks/log.js CHANGED
@@ -12,6 +12,14 @@ const NOTE_MAX_CHARS = 4_000;
12
12
  export function taskLogPath(channelDir, id) {
13
13
  return join(channelDir, "tasks", `${normalizeTaskId(id)}.jsonl`);
14
14
  }
15
+ /** Where `archiveTask` moves a closed task's `.jsonl`. */
16
+ export function taskArchiveLogPath(channelDir, id) {
17
+ return join(channelDir, "tasks", "archive", `${normalizeTaskId(id)}.jsonl`);
18
+ }
19
+ /** True when the loop log for `id` lives only in the archive (the task is closed). */
20
+ export function taskLogIsArchived(channelDir, id) {
21
+ return !existsSync(taskLogPath(channelDir, id)) && existsSync(taskArchiveLogPath(channelDir, id));
22
+ }
15
23
  const appenders = new Map();
16
24
  function appenderFor(path) {
17
25
  const existing = appenders.get(path);
@@ -50,7 +58,11 @@ function toRecord(value) {
50
58
  * hand-edited or half-written line must not make a task's whole history unreadable.
51
59
  */
52
60
  export async function readTaskLog(channelDir, id, options = {}) {
53
- const path = taskLogPath(channelDir, id);
61
+ // Fall back to the archived copy so `task_log` on a completed task returns its history rather
62
+ // than "暂无日志" — a task that finished still has a loop log worth reading.
63
+ const path = existsSync(taskLogPath(channelDir, id))
64
+ ? taskLogPath(channelDir, id)
65
+ : taskArchiveLogPath(channelDir, id);
54
66
  if (!existsSync(path))
55
67
  return [];
56
68
  let content;
@@ -22,6 +22,12 @@ export interface BashToolOptions {
22
22
  securityConfig?: SecurityConfig;
23
23
  securityContext?: SecurityRuntimeContext;
24
24
  channelId?: string;
25
+ /**
26
+ * The channel directory. When set, the "full output" spill file lives under
27
+ * `<channelDir>/logs/` so the pointer the tool hands back is one the model's `read` can open
28
+ * under both path-guard boundaries. Absent on the sub-agent path (spill falls back to tmpdir).
29
+ */
30
+ channelDir?: string;
25
31
  /**
26
32
  * When true, route each command through the `rtk` command optimizer before executing
27
33
  * (best-effort; falls back to the raw command when rtk is unavailable or declines).
@@ -33,6 +39,13 @@ export interface BashToolOptions {
33
39
  * background execution. Absent on the sub-agent path, so sub-agents cannot background jobs.
34
40
  */
35
41
  jobManager?: ChannelJobManager;
42
+ /**
43
+ * Set inside a task cycle's session. A background job started here belongs to this task, so the
44
+ * runtime binds the id rather than asking the model to repeat it (and rejects a conflicting one
45
+ * before the job launches — the old "relaunch with taskId=…" told the model to re-run a command
46
+ * that may have side effects). Chat sessions leave this unset and keep the optional `taskId`.
47
+ */
48
+ boundTaskId?: string;
36
49
  /**
37
50
  * When true (`tools.bashInterceptor.enabled`), block a few bare shell patterns that have a
38
51
  * better dedicated tool and steer the model to it. Off by default; main path only.