@oyasmi/pipiclaw 0.9.5 → 0.9.6-beta.2

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 (345) hide show
  1. package/README.en.md +300 -142
  2. package/README.md +295 -140
  3. package/dist/agent/builtin-commands.d.ts +1 -1
  4. package/dist/agent/builtin-commands.js +1 -1
  5. package/dist/agent/channel-runner.d.ts +4 -3
  6. package/dist/agent/channel-runner.js +17 -28
  7. package/dist/agent/maintenance-context.js +2 -2
  8. package/dist/agent/prompt/builder.d.ts +1 -1
  9. package/dist/agent/prompt/builder.js +1 -1
  10. package/dist/agent/prompt/extension.d.ts +1 -1
  11. package/dist/agent/prompt/extension.js +1 -1
  12. package/dist/agent/prompt/manifest.d.ts +6 -1
  13. package/dist/agent/prompt/manifest.js +12 -5
  14. package/dist/agent/prompt/resources.d.ts +0 -3
  15. package/dist/agent/prompt/resources.js +0 -6
  16. package/dist/agent/prompt/sections.d.ts +2 -2
  17. package/dist/agent/prompt/sections.js +36 -26
  18. package/dist/agent/prompt/types.d.ts +3 -2
  19. package/dist/agent/runner-factory.js +1 -1
  20. package/dist/agent/session/command-extension.js +3 -1
  21. package/dist/agent/session/compaction-summary.js +3 -6
  22. package/dist/agent/session/compaction.d.ts +2 -0
  23. package/dist/agent/session/compaction.js +22 -14
  24. package/dist/agent/session/event-guards.d.ts +2 -1
  25. package/dist/agent/session/event-guards.js +6 -0
  26. package/dist/agent/session/model-selection.d.ts +2 -1
  27. package/dist/agent/session/model-selection.js +5 -5
  28. package/dist/agent/session/session-events.js +31 -4
  29. package/dist/agent/session/session-host.d.ts +5 -3
  30. package/dist/agent/session/session-host.js +20 -16
  31. package/dist/agent/status-render.js +3 -0
  32. package/dist/agent/stop-watchdog.js +5 -1
  33. package/dist/agent/turn/task-digest.d.ts +2 -5
  34. package/dist/agent/turn/task-digest.js +25 -45
  35. package/dist/agent/turn/turn-context.js +4 -6
  36. package/dist/agent/turn/turn-error.d.ts +1 -1
  37. package/dist/agent/turn/turn-error.js +9 -0
  38. package/dist/agent/turn/turn-pipeline.d.ts +10 -5
  39. package/dist/agent/turn/turn-pipeline.js +36 -7
  40. package/dist/agent/turn/turn-prompt.d.ts +2 -0
  41. package/dist/agent/turn/turn-prompt.js +2 -1
  42. package/dist/agent/turn/turn-recovery.js +4 -1
  43. package/dist/agent/turn/turn-state.d.ts +2 -0
  44. package/dist/agent/turn/turn-state.js +2 -1
  45. package/dist/agent/types.d.ts +23 -3
  46. package/dist/agent/types.js +2 -0
  47. package/dist/app/auth-command.d.ts +25 -0
  48. package/dist/app/auth-command.js +200 -67
  49. package/dist/app/home.d.ts +7 -8
  50. package/dist/app/home.js +143 -56
  51. package/dist/channel/attachments.d.ts +4 -0
  52. package/dist/channel/attachments.js +4 -0
  53. package/dist/channel/channel-context.d.ts +6 -0
  54. package/dist/channel/config.d.ts +3 -0
  55. package/dist/channel/config.js +11 -5
  56. package/dist/channel/store.d.ts +1 -1
  57. package/dist/commands/catalog.js +42 -10
  58. package/dist/commands/router.js +5 -1
  59. package/dist/desk/commands.d.ts +44 -5
  60. package/dist/desk/commands.js +162 -28
  61. package/dist/desk/paths.d.ts +6 -0
  62. package/dist/desk/paths.js +21 -1
  63. package/dist/desk/registry.d.ts +17 -2
  64. package/dist/desk/registry.js +122 -12
  65. package/dist/desk/types.d.ts +83 -1
  66. package/dist/dingtalk/bot.d.ts +1 -1
  67. package/dist/dingtalk/bot.js +4 -3
  68. package/dist/dingtalk/config.js +10 -10
  69. package/dist/dingtalk/delivery.js +15 -8
  70. package/dist/dingtalk/inbound-media.d.ts +36 -14
  71. package/dist/dingtalk/inbound-media.js +71 -12
  72. package/dist/dingtalk/inbound.d.ts +9 -2
  73. package/dist/dingtalk/inbound.js +17 -2
  74. package/dist/dingtalk/media.d.ts +4 -10
  75. package/dist/dingtalk/media.js +58 -32
  76. package/dist/events/commands.d.ts +2 -0
  77. package/dist/events/commands.js +13 -8
  78. package/dist/events/history.d.ts +9 -0
  79. package/dist/events/history.js +66 -0
  80. package/dist/events/parse.js +7 -3
  81. package/dist/events/types.d.ts +3 -0
  82. package/dist/events/watcher.d.ts +4 -8
  83. package/dist/events/watcher.js +53 -58
  84. package/dist/jobs/kill.d.ts +23 -0
  85. package/dist/jobs/kill.js +65 -0
  86. package/dist/jobs/manager.d.ts +19 -18
  87. package/dist/jobs/manager.js +36 -103
  88. package/dist/main.js +15 -3
  89. package/dist/memory/boundary-work.d.ts +2 -1
  90. package/dist/memory/boundary-work.js +1 -1
  91. package/dist/memory/lifecycle.d.ts +2 -1
  92. package/dist/memory/lifecycle.js +2 -2
  93. package/dist/memory/reflect-job.d.ts +2 -1
  94. package/dist/memory/reflect-job.js +1 -1
  95. package/dist/memory/reflect.d.ts +2 -1
  96. package/dist/memory/reflect.js +25 -4
  97. package/dist/memory/scheduler.d.ts +2 -1
  98. package/dist/memory/scheduler.js +1 -1
  99. package/dist/memory/session-corpus.d.ts +1 -1
  100. package/dist/memory/session-corpus.js +76 -1
  101. package/dist/memory/session-search.d.ts +2 -1
  102. package/dist/memory/session-search.js +14 -12
  103. package/dist/memory/sidecar-worker.d.ts +2 -1
  104. package/dist/memory/sidecar-worker.js +2 -4
  105. package/dist/memory/store.d.ts +2 -0
  106. package/dist/memory/store.js +19 -9
  107. package/dist/models/credential-work.d.ts +7 -0
  108. package/dist/models/credential-work.js +36 -0
  109. package/dist/models/login-ui.js +4 -4
  110. package/dist/models/provider-login.js +7 -6
  111. package/dist/models/requests.d.ts +8 -0
  112. package/dist/models/requests.js +69 -0
  113. package/dist/models/runtime.d.ts +3 -1
  114. package/dist/models/runtime.js +9 -2
  115. package/dist/playbooks/agent-delegation.md +20 -45
  116. package/dist/playbooks/background-jobs.md +1 -1
  117. package/dist/playbooks/catalog.js +1 -1
  118. package/dist/playbooks/delegation-inline.md +25 -0
  119. package/dist/playbooks/delegation-recovery.md +28 -0
  120. package/dist/playbooks/event-scheduling.md +18 -37
  121. package/dist/playbooks/event-sensors.md +26 -0
  122. package/dist/playbooks/event-task-template.md +22 -0
  123. package/dist/playbooks/learning-and-skills.md +26 -0
  124. package/dist/playbooks/memory-operations.md +36 -0
  125. package/dist/playbooks/outbound-media.md +2 -2
  126. package/dist/playbooks/runtime-files.md +29 -0
  127. package/dist/playbooks/runtime-operations.md +25 -0
  128. package/dist/playbooks/runtime-orientation.md +18 -53
  129. package/dist/playbooks/task-lead.md +22 -68
  130. package/dist/playbooks/task-manage.md +38 -0
  131. package/dist/playbooks/task-recovery.md +24 -0
  132. package/dist/playbooks/task-verify.md +22 -0
  133. package/dist/runtime/bootstrap.d.ts +10 -0
  134. package/dist/runtime/bootstrap.js +93 -29
  135. package/dist/runtime/daemon-lock.js +3 -3
  136. package/dist/runtime/desk-runtime.d.ts +40 -7
  137. package/dist/runtime/desk-runtime.js +330 -44
  138. package/dist/runtime/durable-dispatch.d.ts +14 -2
  139. package/dist/runtime/durable-dispatch.js +207 -65
  140. package/dist/runtime/ingress-busy.js +17 -8
  141. package/dist/runtime/ingress-commands.js +24 -4
  142. package/dist/runtime/ingress-deps.d.ts +4 -1
  143. package/dist/runtime/ingress.js +6 -1
  144. package/dist/runtime/request-execution.js +7 -6
  145. package/dist/runtime/shutdown.d.ts +4 -1
  146. package/dist/runtime/shutdown.js +88 -35
  147. package/dist/runtime/task-close.d.ts +1 -1
  148. package/dist/runtime/task-close.js +6 -3
  149. package/dist/runtime/task-control.d.ts +2 -3
  150. package/dist/runtime/task-control.js +38 -11
  151. package/dist/runtime/task-input.js +1 -1
  152. package/dist/runtime/task-lane-types.d.ts +12 -2
  153. package/dist/runtime/task-lane-types.js +9 -0
  154. package/dist/runtime/task-lane.d.ts +2 -0
  155. package/dist/runtime/task-lane.js +38 -20
  156. package/dist/runtime/task-step.d.ts +3 -3
  157. package/dist/runtime/task-step.js +34 -16
  158. package/dist/runtime/transports.js +6 -5
  159. package/dist/runtime/turn-run.js +103 -66
  160. package/dist/security/command-guard.d.ts +1 -1
  161. package/dist/security/command-guard.js +259 -314
  162. package/dist/security/path-guard.js +48 -7
  163. package/dist/security/shell-parse.d.ts +10 -0
  164. package/dist/security/shell-parse.js +224 -0
  165. package/dist/security/types.d.ts +2 -0
  166. package/dist/subagents/commands.d.ts +1 -1
  167. package/dist/subagents/commands.js +14 -5
  168. package/dist/subagents/completion-wake.js +6 -0
  169. package/dist/subagents/detached-discovery.d.ts +1 -1
  170. package/dist/subagents/discovery.d.ts +18 -199
  171. package/dist/subagents/discovery.js +35 -289
  172. package/dist/subagents/dispatch.d.ts +1 -2
  173. package/dist/subagents/dispatch.js +50 -29
  174. package/dist/subagents/external/antigravity-cli.d.ts +2 -0
  175. package/dist/subagents/external/antigravity-cli.js +517 -0
  176. package/dist/subagents/external/claude-code.js +8 -17
  177. package/dist/subagents/external/codex-cli.js +8 -18
  178. package/dist/subagents/external/cursor-cli.js +34 -31
  179. package/dist/subagents/external/dispatch.d.ts +21 -7
  180. package/dist/subagents/external/dispatch.js +146 -12
  181. package/dist/subagents/external/exec.js +3 -0
  182. package/dist/subagents/external/harness.d.ts +57 -33
  183. package/dist/subagents/external/harness.js +69 -40
  184. package/dist/subagents/external/reconciliation.js +1 -0
  185. package/dist/subagents/external/registry.js +4 -1
  186. package/dist/subagents/external/role-warnings.d.ts +4 -13
  187. package/dist/subagents/external/role-warnings.js +4 -28
  188. package/dist/subagents/external/run.d.ts +1 -2
  189. package/dist/subagents/external/run.js +16 -26
  190. package/dist/subagents/external/settlement.d.ts +2 -0
  191. package/dist/subagents/external/settlement.js +13 -3
  192. package/dist/subagents/format.d.ts +1 -1
  193. package/dist/subagents/format.js +1 -1
  194. package/dist/subagents/internal/outcome.d.ts +1 -2
  195. package/dist/subagents/internal/outcome.js +19 -12
  196. package/dist/subagents/internal/provider-retry.d.ts +1 -2
  197. package/dist/subagents/internal/provider-retry.js +2 -4
  198. package/dist/subagents/internal/run.d.ts +2 -3
  199. package/dist/subagents/internal/run.js +27 -4
  200. package/dist/subagents/internal/state.d.ts +2 -5
  201. package/dist/subagents/internal/state.js +1 -2
  202. package/dist/subagents/internal/worker.d.ts +1 -2
  203. package/dist/subagents/internal/worker.js +20 -10
  204. package/dist/subagents/resolve.d.ts +56 -0
  205. package/dist/subagents/resolve.js +202 -0
  206. package/dist/subagents/result.d.ts +6 -4
  207. package/dist/subagents/result.js +39 -6
  208. package/dist/subagents/run-record.d.ts +54 -2
  209. package/dist/subagents/run-record.js +7 -0
  210. package/dist/subagents/runs.d.ts +6 -31
  211. package/dist/subagents/runs.js +26 -31
  212. package/dist/subagents/task-envelope.d.ts +1 -2
  213. package/dist/subagents/task-envelope.js +13 -4
  214. package/dist/subagents/task-settlement.js +1 -0
  215. package/dist/subagents/types.d.ts +105 -6
  216. package/dist/subagents/types.js +16 -1
  217. package/dist/subagents/workspace-lease.d.ts +41 -24
  218. package/dist/subagents/workspace-lease.js +159 -24
  219. package/dist/subagents/worktree.d.ts +52 -0
  220. package/dist/subagents/worktree.js +363 -0
  221. package/dist/tasks/archive.js +4 -0
  222. package/dist/tasks/brief.d.ts +5 -1
  223. package/dist/tasks/brief.js +19 -5
  224. package/dist/tasks/commands.d.ts +6 -1
  225. package/dist/tasks/commands.js +32 -7
  226. package/dist/tasks/control.d.ts +11 -0
  227. package/dist/tasks/delivery.d.ts +2 -0
  228. package/dist/tasks/delivery.js +141 -21
  229. package/dist/tasks/loop-log.d.ts +12 -0
  230. package/dist/tasks/loop-log.js +10 -1
  231. package/dist/tasks/receipts.d.ts +7 -3
  232. package/dist/tasks/receipts.js +34 -5
  233. package/dist/tools/bash.d.ts +3 -0
  234. package/dist/tools/bash.js +29 -15
  235. package/dist/tools/contract/presentation.js +7 -5
  236. package/dist/tools/edit-diff.d.ts +11 -0
  237. package/dist/tools/edit-diff.js +148 -0
  238. package/dist/tools/edit-match.d.ts +18 -0
  239. package/dist/tools/edit-match.js +242 -0
  240. package/dist/tools/edit.d.ts +10 -2
  241. package/dist/tools/edit.js +91 -361
  242. package/dist/tools/event-manage.d.ts +2 -1
  243. package/dist/tools/event-manage.js +46 -39
  244. package/dist/tools/file-observations.d.ts +9 -0
  245. package/dist/tools/file-observations.js +50 -0
  246. package/dist/tools/glob-match.d.ts +3 -1
  247. package/dist/tools/glob-match.js +40 -17
  248. package/dist/tools/glob.d.ts +1 -0
  249. package/dist/tools/glob.js +39 -19
  250. package/dist/tools/grep-command.d.ts +13 -0
  251. package/dist/tools/grep-command.js +77 -0
  252. package/dist/tools/grep.js +96 -201
  253. package/dist/tools/index.d.ts +6 -2
  254. package/dist/tools/index.js +9 -4
  255. package/dist/tools/job.js +12 -11
  256. package/dist/tools/read.d.ts +2 -0
  257. package/dist/tools/read.js +10 -2
  258. package/dist/tools/registry.d.ts +16 -11
  259. package/dist/tools/registry.js +32 -12
  260. package/dist/tools/send-media.js +9 -5
  261. package/dist/tools/session-search.d.ts +2 -1
  262. package/dist/tools/session-search.js +15 -5
  263. package/dist/tools/skill.js +13 -12
  264. package/dist/tools/subagent-manage.d.ts +1 -1
  265. package/dist/tools/subagent-manage.js +25 -152
  266. package/dist/tools/subagent.d.ts +24 -2
  267. package/dist/tools/subagent.js +24 -18
  268. package/dist/tools/task-manage/control-tools.js +1 -1
  269. package/dist/tools/task-manage/factory.d.ts +2 -2
  270. package/dist/tools/task-manage/factory.js +40 -4
  271. package/dist/tools/task-manage/lifecycle.d.ts +3 -3
  272. package/dist/tools/task-manage/lifecycle.js +56 -13
  273. package/dist/tools/task-manage/schema.d.ts +4 -1
  274. package/dist/tools/task-manage/schema.js +4 -1
  275. package/dist/tools/task-manage/shared.d.ts +1 -1
  276. package/dist/tools/task-manage/types.d.ts +5 -1
  277. package/dist/tools/write-content.d.ts +7 -1
  278. package/dist/tools/write-content.js +18 -6
  279. package/dist/tools/write.d.ts +3 -0
  280. package/dist/tools/write.js +6 -2
  281. package/dist/tui/cli.d.ts +6 -6
  282. package/dist/tui/cli.js +120 -28
  283. package/dist/tui/client.d.ts +7 -0
  284. package/dist/tui/client.js +67 -16
  285. package/dist/tui/frontend.d.ts +2 -0
  286. package/dist/tui/pitui-frontend.d.ts +4 -0
  287. package/dist/tui/pitui-frontend.js +27 -0
  288. package/dist/tui/render.d.ts +1 -0
  289. package/dist/tui/render.js +5 -0
  290. package/dist/tui/session.js +6 -0
  291. package/dist/usage/ledger.d.ts +1 -1
  292. package/dist/usage/render.js +1 -1
  293. package/dist/web/client.d.ts +1 -0
  294. package/dist/web/client.js +11 -0
  295. package/dist/web/fetch.js +6 -3
  296. package/dist/webapi/auth.d.ts +0 -3
  297. package/dist/webapi/auth.js +3 -7
  298. package/dist/webapi/config.js +17 -14
  299. package/dist/webapi/key-command.js +41 -41
  300. package/dist/webapi/response-state.d.ts +7 -1
  301. package/dist/webapi/response-state.js +166 -3
  302. package/dist/webapi/routes/websocket.js +24 -1
  303. package/dist/webapi/server.d.ts +3 -1
  304. package/dist/webapi/server.js +32 -1
  305. package/dist/webapi/service.js +8 -0
  306. package/dist/webapi/transport.d.ts +2 -0
  307. package/dist/webapi/transport.js +11 -1
  308. package/examples/sub-agents/README.md +43 -75
  309. package/examples/sub-agents/agy-main.md +21 -0
  310. package/examples/sub-agents/claude-high.md +21 -0
  311. package/examples/sub-agents/claude-main.md +21 -0
  312. package/examples/sub-agents/codex-flash.md +21 -0
  313. package/examples/sub-agents/codex-high.md +21 -0
  314. package/examples/sub-agents/codex-main.md +21 -0
  315. package/examples/sub-agents/codex-review.md +20 -0
  316. package/examples/sub-agents/cursor-high.md +20 -0
  317. package/examples/sub-agents/cursor-main.md +20 -0
  318. package/examples/sub-agents/glm-flash.md +21 -0
  319. package/examples/sub-agents/glm-high.md +21 -0
  320. package/examples/sub-agents/pi-scout.md +20 -0
  321. package/package.json +11 -12
  322. package/dist/agent/session/request-tools.d.ts +0 -3
  323. package/dist/agent/session/request-tools.js +0 -20
  324. package/dist/models/api-keys.d.ts +0 -11
  325. package/dist/models/api-keys.js +0 -22
  326. package/dist/playbooks/memory-and-learning.md +0 -55
  327. package/examples/sub-agents/agents/claude-high.md +0 -23
  328. package/examples/sub-agents/agents/claude-main.md +0 -23
  329. package/examples/sub-agents/agents/codex-flash.md +0 -23
  330. package/examples/sub-agents/agents/codex-high.md +0 -23
  331. package/examples/sub-agents/agents/codex-main.md +0 -23
  332. package/examples/sub-agents/agents/codex-review.md +0 -23
  333. package/examples/sub-agents/agents/cursor-high.md +0 -22
  334. package/examples/sub-agents/agents/cursor-main.md +0 -22
  335. package/examples/sub-agents/agents/glm-flash.md +0 -23
  336. package/examples/sub-agents/agents/glm-high.md +0 -23
  337. package/examples/sub-agents/agents/scout.md +0 -30
  338. package/examples/sub-agents/roles/builder-hard.md +0 -34
  339. package/examples/sub-agents/roles/builder.md +0 -34
  340. package/examples/sub-agents/roles/explorer.md +0 -39
  341. package/examples/sub-agents/roles/git-committer.md +0 -43
  342. package/examples/sub-agents/roles/planner.md +0 -33
  343. package/examples/sub-agents/roles/reviewer.md +0 -33
  344. package/examples/sub-agents/roles/verifier.md +0 -35
  345. package/examples/sub-agents/roles/worker.md +0 -34
@@ -1,74 +1,28 @@
1
+ /**
2
+ * Workspace role discovery (`workspace/sub-agents/*.md`): frontmatter parsing, per-runtime field
3
+ * legality checks, static security/role warnings, `workspace/sub-agents/` write-deny guard, and
4
+ * external role fingerprinting. Call-time invocation resolution lives in `resolve.ts`.
5
+ */
1
6
  import { createHash } from "node:crypto";
2
- import { existsSync as existsSyncFs } from "node:fs";
3
- import { join as joinPath, delimiter as pathDelimiter } from "node:path";
7
+ import { existsSync, readdirSync, readFileSync } from "node:fs";
8
+ import { join, delimiter as pathDelimiter } from "node:path";
4
9
  import { parseFrontmatter } from "@earendil-works/pi-coding-agent";
5
- import { existsSync, readdirSync, readFileSync } from "fs";
6
- import { join } from "path";
7
10
  import { findExactModelReferenceMatch, formatModelReference } from "../models/reference.js";
8
11
  import { SUB_AGENTS_DIR_NAME } from "../paths.js";
9
12
  import { splitShellWords } from "../shared/shell-words.js";
10
13
  import { errorMessage } from "../shared/text-utils.js";
11
14
  import { SUBAGENT_TOOL_NAMES } from "../tools/contract/names.js";
12
15
  import { externalRoleWarning } from "./external/role-warnings.js";
16
+ import { EXTERNAL_HARNESS_IDS as ALLOWED_HARNESSES, ALLOWED_THINKING_LEVELS, } from "./run-record.js";
17
+ import { ALLOWED_CONTEXT_MODES, ALLOWED_MEMORY_MODES, ALLOWED_MUTATES, ALLOWED_RUNTIMES, ALLOWED_WORKLOADS, DEFAULT_BASH_TIMEOUT_SEC, DEFAULT_EXTERNAL_MAX_WALL_TIME_SEC, DEFAULT_MAX_TOOL_CALLS, DEFAULT_MAX_TURNS, DEFAULT_MAX_WALL_TIME_SEC, DEFAULT_SUB_AGENT_TOOLS, } from "./types.js";
13
18
  /** Re-exported from the leaf source of truth so validation and the tool set never drift. */
14
19
  const ALLOWED_SUB_AGENT_TOOLS = SUBAGENT_TOOL_NAMES;
15
- const DEFAULT_SUB_AGENT_TOOLS = ["read", "bash"];
16
- const DEFAULT_MAX_TURNS = 32;
17
- const DEFAULT_MAX_TOOL_CALLS = 96;
18
- const DEFAULT_MAX_WALL_TIME_SEC = 600;
19
- const DEFAULT_BASH_TIMEOUT_SEC = 120;
20
- /** External runs have no turn/tool-call budget (D5); wall time is their only lever. */
21
- const DEFAULT_EXTERNAL_MAX_WALL_TIME_SEC = 3600;
22
- const MAX_SUB_AGENT_TASK_CHARS = 12000;
23
20
  const MAX_SUB_AGENT_SYSTEM_PROMPT_CHARS = 16000;
24
- const ALLOWED_CONTEXT_MODES = ["isolated", "contextual"];
25
- const ALLOWED_MEMORY_MODES = ["none", "index"];
26
- // "max" is a real SDK ThinkingLevel; pipiclaw's own whitelist previously omitted it (spec 040, D4).
27
- const ALLOWED_THINKING_LEVELS = ["off", "minimal", "low", "medium", "high", "xhigh", "max"];
28
- const ALLOWED_RUNTIMES = ["internal", "external"];
29
- const ALLOWED_HARNESSES = ["claude-code", "codex-cli", "cursor-cli", "exec"];
30
- const ALLOWED_WORKLOADS = ["light", "heavy"];
31
- const ALLOWED_MUTATES = ["read", "write"];
32
- /**
33
- * Execution budgets as a single named tuple. Frontmatter keeps the four numeric knobs
34
- * (a human editing a config file has grounds to pick numbers); the invocation surface
35
- * only offers these presets, because a model choosing `maxToolCalls` per delegation is
36
- * guessing. `standard` is byte-identical to the DEFAULT_* values, so omitting `effort`
37
- * leaves behavior unchanged.
38
- */
39
- export const SUB_AGENT_EFFORT_PRESETS = {
40
- quick: { maxTurns: 8, maxToolCalls: 16, maxWallTimeSec: 120, bashTimeoutSec: 60 },
41
- standard: {
42
- maxTurns: DEFAULT_MAX_TURNS,
43
- maxToolCalls: DEFAULT_MAX_TOOL_CALLS,
44
- maxWallTimeSec: DEFAULT_MAX_WALL_TIME_SEC,
45
- bashTimeoutSec: DEFAULT_BASH_TIMEOUT_SEC,
46
- },
47
- deep: { maxTurns: 64, maxToolCalls: 160, maxWallTimeSec: 1800, bashTimeoutSec: 300 },
48
- };
49
- const ALLOWED_EFFORTS = Object.keys(SUB_AGENT_EFFORT_PRESETS);
50
- /**
51
- * The invocation-side spelling of `contextMode` + `memory`. Those two frontmatter knobs
52
- * encode only four meaningful states (`isolated` implies `memory: none`), so the calling
53
- * surface collapses them into one enum. The dropped state — contextual with `memory: none`,
54
- * i.e. paths-only injection — remains expressible in frontmatter.
55
- */
56
- const ALLOWED_CONTEXT_CHOICES = ["none", "index"];
57
- /** Internal work/verify default, aligned with the main agent's DEFAULT_MAIN_THINKING_LEVEL
58
- * (channel-runner.ts). External work leaves thinkingLevel unset instead (see resolveSubAgentConfig):
59
- * pipiclaw has no standing to pick a reasoning effort for another CLI's own configuration. */
60
- export const DEFAULT_THINKING_LEVEL = "medium";
61
- function validateTextLength(value, maxChars, label) {
62
- if (value.length <= maxChars) {
21
+ export function validateSubAgentSystemPrompt(systemPrompt, label) {
22
+ if (systemPrompt.length <= MAX_SUB_AGENT_SYSTEM_PROMPT_CHARS) {
63
23
  return undefined;
64
24
  }
65
- return `${label} exceeds ${maxChars} characters (got ${value.length}).`;
66
- }
67
- export function validateSubAgentTask(task) {
68
- return validateTextLength(task, MAX_SUB_AGENT_TASK_CHARS, "Sub-agent task");
69
- }
70
- function validateSubAgentSystemPrompt(systemPrompt, label) {
71
- return validateTextLength(systemPrompt, MAX_SUB_AGENT_SYSTEM_PROMPT_CHARS, label);
25
+ return `${label} exceeds ${MAX_SUB_AGENT_SYSTEM_PROMPT_CHARS} characters (got ${systemPrompt.length}).`;
72
26
  }
73
27
  export function getSubAgentsDir(workspaceDir) {
74
28
  return join(workspaceDir, SUB_AGENTS_DIR_NAME);
@@ -92,7 +46,7 @@ export function withSubAgentsDirWriteDeny(config, workspaceDir) {
92
46
  },
93
47
  };
94
48
  }
95
- function readOptionalTrimmedString(value) {
49
+ export function readOptionalTrimmedString(value) {
96
50
  if (typeof value !== "string") {
97
51
  return undefined;
98
52
  }
@@ -151,10 +105,9 @@ function parseStringList(raw, label) {
151
105
  /**
152
106
  * Shared shape for every frontmatter/override field whose only validation is "one of a fixed
153
107
  * allow-list, else report an error and fall back": `contextMode`, `thinkingLevel`, `effort`,
154
- * `runtime`, `harness`, `workload`, `mutates` all had their own byte-identical copy of this
155
- * before (review 2026-08-29) — only the label, allow-list and fallback ever differed.
108
+ * `runtime`, `harness`, `workload`, `mutates` all share this logic.
156
109
  */
157
- function parseEnumField(raw, label, allowed, fallback) {
110
+ export function parseEnumField(raw, label, allowed, fallback) {
158
111
  const normalized = readOptionalTrimmedString(raw);
159
112
  if (!normalized) {
160
113
  return { value: fallback };
@@ -174,29 +127,12 @@ function parseContextMode(raw) {
174
127
  function parseThinkingLevel(raw) {
175
128
  return parseEnumField(raw, "thinkingLevel", ALLOWED_THINKING_LEVELS);
176
129
  }
177
- function parseEffort(raw) {
178
- return parseEnumField(raw, "effort", ALLOWED_EFFORTS);
179
- }
180
- function parseContextChoice(raw) {
181
- const normalized = readOptionalTrimmedString(raw);
182
- if (!normalized) {
183
- return {};
184
- }
185
- if (!ALLOWED_CONTEXT_CHOICES.includes(normalized)) {
186
- return {
187
- error: `Unknown context "${normalized}". Allowed values: ${ALLOWED_CONTEXT_CHOICES.join(", ")}`,
188
- };
189
- }
190
- if (normalized === "none") {
191
- return { value: { contextMode: "isolated", memory: "none" } };
192
- }
193
- return { value: { contextMode: "contextual", memory: normalized } };
194
- }
195
130
  /**
196
131
  * `defaultValue` is computed per call site rather than derived from `contextMode` inside this
197
- * function (spec 042 D4): internal keeps following `contextMode` (`contextual` → `index`), but an external role's default is always `none` regardless of `contextMode` — a role that
198
- * merely wants `paths` injected (via `contextMode: contextual`) should not also silently start
199
- * sending session/memory content to a third-party process.
132
+ * function (spec 042 D4): internal keeps following `contextMode` (`contextual` → `index`), but an
133
+ * external role's default is always `none` regardless of `contextMode` — a role that merely wants
134
+ * `paths` injected (via `contextMode: contextual`) should not also silently start sending
135
+ * session/memory content to a third-party process.
200
136
  */
201
137
  function parseMemoryMode(raw, defaultValue) {
202
138
  const normalized = readOptionalTrimmedString(raw);
@@ -255,7 +191,7 @@ function parsePositiveInteger(raw, fallback) {
255
191
  }
256
192
  return { value: parsed };
257
193
  }
258
- function resolveModelReference(modelRef, availableModels) {
194
+ export function resolveModelReference(modelRef, availableModels) {
259
195
  const { match, ambiguous } = findExactModelReferenceMatch(modelRef, availableModels);
260
196
  if (match) {
261
197
  return { model: match };
@@ -310,22 +246,19 @@ function firstCommandToken(command) {
310
246
  }
311
247
  /** Existence check only (no exec-bit probe): cheap, spawn-free, good enough for "is it installed". */
312
248
  function isExecutableAvailable(token) {
313
- if (token.includes("/")) {
314
- return existsSyncFs(token);
315
- }
249
+ if (token.includes("/"))
250
+ return existsSync(token);
316
251
  const pathEnv = process.env.PATH ?? "";
317
- return pathEnv.split(pathDelimiter).some((dir) => dir && existsSyncFs(joinPath(dir, token)));
252
+ return pathEnv.split(pathDelimiter).some((dir) => dir && existsSync(join(dir, token)));
318
253
  }
319
254
  /**
320
255
  * Which role-file fields mean something under which runtime (spec 040 D5's "对某种 runtime 无意义
321
256
  * 的字段一律驳回", made into data per spec 042 D3/F3). A field present under a runtime marked
322
- * `"rejected"` here is rejected outright, not silently ignored — silently ignoring one is a
323
- * defect, not a leniency (the review that produced spec 042 found `shell`/`env` on an internal
324
- * role doing exactly that before this table existed). `cwd` is deliberately absent: it is rejected
325
- * for *both* runtimes with a different message ("not a role field at all"), handled separately in
326
- * `loadAgentsFromDir` rather than as a per-runtime mismatch.
257
+ * `"rejected"` here is rejected outright, not silently ignored. `cwd` is deliberately absent: it
258
+ * is rejected for *both* runtimes with a different message ("not a role field at all"), handled
259
+ * separately in `loadAgentsFromDir` rather than as a per-runtime mismatch.
327
260
  */
328
- export const ROLE_FIELD_MATRIX = {
261
+ const ROLE_FIELD_MATRIX = {
329
262
  harness: { internal: "rejected", external: "supported" },
330
263
  command: { internal: "rejected", external: "supported" },
331
264
  shell: { internal: "rejected", external: "supported" },
@@ -338,7 +271,7 @@ export const ROLE_FIELD_MATRIX = {
338
271
  function rejectedFieldNames(frontmatter, runtime) {
339
272
  return Object.keys(ROLE_FIELD_MATRIX).filter((field) => frontmatter[field] !== undefined && ROLE_FIELD_MATRIX[field][runtime] === "rejected");
340
273
  }
341
- function inferMutatesFromTools(tools) {
274
+ export function inferMutatesFromTools(tools) {
342
275
  return tools.includes("write") || tools.includes("edit") ? "write" : "read";
343
276
  }
344
277
  function parseInternalAgent(entryName, filePath, frontmatter, body, name, description, availableModels) {
@@ -372,8 +305,6 @@ function parseInternalAgent(entryName, filePath, frontmatter, body, name, descri
372
305
  const maxWallTimeSec = parsePositiveInteger(frontmatter.maxWallTimeSec, DEFAULT_MAX_WALL_TIME_SEC);
373
306
  const bashTimeoutSec = parsePositiveInteger(frontmatter.bashTimeoutSec, DEFAULT_BASH_TIMEOUT_SEC);
374
307
  const numericWarning = [maxTurns.warning, maxToolCalls.warning, maxWallTimeSec.warning, bashTimeoutSec.warning].find(Boolean);
375
- // A malformed numeric field falls back to its default rather than dropping the whole role —
376
- // but it is still reported, via the first warning found.
377
308
  const modelRef = readOptionalTrimmedString(frontmatter.model);
378
309
  let model;
379
310
  if (modelRef) {
@@ -389,9 +320,7 @@ function parseInternalAgent(entryName, filePath, frontmatter, body, name, descri
389
320
  if (promptLengthError)
390
321
  return { warning: `${entryName}: ${promptLengthError}` };
391
322
  // Spec 042 D6: `bash` can write regardless of what `tools` otherwise implies, and the default
392
- // tool set (`read,bash`) is inferred "read" — a role that actually writes through bash and never
393
- // says so does not take the workspace write lease. Not rejected (`bash` is normal and common for
394
- // read-only inspection too) — just surfaced so the declaration is a conscious choice.
323
+ // tool set (`read,bash`) is inferred "read" — surface so the declaration is a conscious choice.
395
324
  const bashWithoutMutatesWarning = toolParse.tools.includes("bash") && mutates.value === undefined
396
325
  ? 'tools include bash but "mutates" is not declared; if this role writes to the workspace, declare mutates: write so it participates in the workspace write lease'
397
326
  : undefined;
@@ -416,7 +345,7 @@ function parseInternalAgent(entryName, filePath, frontmatter, body, name, descri
416
345
  filePath,
417
346
  source: "predefined",
418
347
  runtime: "internal",
419
- workload: workload.value ?? "light", // D11 default-by-runtime.
348
+ workload: workload.value ?? "light",
420
349
  mutates: mutates.value ?? inferMutatesFromTools(toolParse.tools),
421
350
  },
422
351
  };
@@ -462,25 +391,16 @@ function parseExternalAgent(entryName, filePath, frontmatter, body, name, descri
462
391
  const contextMode = parseContextMode(frontmatter.contextMode);
463
392
  if (contextMode.error)
464
393
  return { warning: `${entryName}: ${contextMode.error}` };
465
- // Spec 042 D4: external default is always "none", never following contextMode the way internal
466
- // does — a role that only wants `paths` injected (contextMode: contextual) should not also
467
- // silently start sending memory content to a third-party process. Explicitly declaring
468
- // `memory: index` is a real, informed choice; it gets a disclosure warning below.
394
+ // Spec 042 D4: external default is always "none", never following contextMode.
469
395
  const memoryMode = parseMemoryMode(frontmatter.memory, "none");
470
396
  if (memoryMode.error)
471
397
  return { warning: `${entryName}: ${memoryMode.error}` };
472
398
  const maxWallTimeSec = parsePositiveInteger(frontmatter.maxWallTimeSec, DEFAULT_EXTERNAL_MAX_WALL_TIME_SEC);
473
- // An empty body is a legitimate declaration for an external role, not a defect: a capability
474
- // entry ("this agent, this model, this reasoning level") deliberately carries no standing
475
- // instruction, because the only party that knows what this delegation is for is the main
476
- // agent writing `task`. Internal roles still require a body — they have no other prompt.
399
+ // An empty body is a legitimate declaration for an external role, not a defect.
477
400
  const trimmedBody = body.trim();
478
401
  const promptLengthError = validateSubAgentSystemPrompt(trimmedBody, "Sub-agent system prompt");
479
402
  if (promptLengthError)
480
403
  return { warning: `${entryName}: ${promptLengthError}` };
481
- // A missing binary never drops the role (that would silently push the model back onto
482
- // internal delegation, exactly the failure mode this spec exists to close) — it is listed,
483
- // marked unavailable, and only refuses at invocation time, with an installation hint.
484
404
  const executable = firstCommandToken(command);
485
405
  const unavailable = executable && !isExecutableAvailable(executable)
486
406
  ? `executable "${executable}" was not found on PATH; install it or fix "command" in ${filePath}`
@@ -518,7 +438,7 @@ function parseExternalAgent(entryName, filePath, frontmatter, body, name, descri
518
438
  command,
519
439
  shell: shell.value,
520
440
  env: env.value,
521
- workload: workload.value ?? "heavy", // D11 default-by-runtime.
441
+ workload: workload.value ?? "heavy",
522
442
  mutates: mutates.value,
523
443
  unavailable,
524
444
  },
@@ -536,8 +456,6 @@ function loadAgentsFromDir(directory, availableModels) {
536
456
  try {
537
457
  entries = readdirSync(directory, { withFileTypes: true })
538
458
  .filter((entry) => entry.name.endsWith(".md") && (entry.isFile() || entry.isSymbolicLink()))
539
- // A README is documentation about the directory, not a role in it — a warning about its
540
- // missing frontmatter is noise every time someone copies `examples/sub-agents/` wholesale.
541
459
  .filter((entry) => entry.name.toLowerCase() !== "readme.md")
542
460
  .sort((a, b) => a.name.localeCompare(b.name));
543
461
  }
@@ -565,11 +483,7 @@ function loadAgentsFromDir(directory, availableModels) {
565
483
  warnings.push(`${entry.name}: duplicate sub-agent name "${name}" ignored`);
566
484
  continue;
567
485
  }
568
- // Claim the name before later validation so a malformed duplicate cannot shadow a valid one.
569
486
  knownNames.add(name);
570
- // The working directory is a per-delegation decision (workingDirectory on the call), never
571
- // a role default — a `cwd` default would let a model skip the thinking it must do every
572
- // time (spec 040, D5), and would silently collide two parallel writers on one checkout.
573
487
  if (frontmatter.cwd !== undefined) {
574
488
  warnings.push(`${entry.name}: "cwd" is not a role field; pass workingDirectory on the delegation call instead`);
575
489
  continue;
@@ -594,179 +508,11 @@ export function discoverSubAgents(workspaceDir, availableModels) {
594
508
  const result = loadAgentsFromDir(directory, availableModels);
595
509
  return { directory, agents: result.agents, warnings: result.warnings };
596
510
  }
597
- /**
598
- * Resolve a `subagent` (role-based) invocation (spec 046, D2.1).
599
- *
600
- * Everything the old combined resolver used to override for a configured role — `tools`,
601
- * `model`, `effort`, `context`, `mutates` — now has nowhere to come from but the role file
602
- * itself, so this is a lookup plus the two facts a role file cannot pin down: the default model
603
- * (parent's current model, or `settings.subagentModel`) and the purpose-driven thinkingLevel
604
- * default. Spec 042 D3's three "external + override" rejections no longer apply: `ConfiguredRoleOverrides`
605
- * has no `tools`/`model`/`mutates` field to reject in the first place.
606
- */
607
- export function resolveConfiguredRole(availableModels, currentModel, predefinedAgents, overrides,
608
- /**
609
- * `settings.subagentModel` (spec 032 D5): used only when neither the role file's frontmatter
610
- * nor this call names a model (it cannot — there is no override field for it).
611
- */
612
- subagentDefaultModelRef) {
613
- const baseConfig = predefinedAgents.find((agent) => agent.name === overrides.agent);
614
- if (!baseConfig) {
615
- const available = predefinedAgents.length > 0 ? predefinedAgents.map((agent) => agent.name).join(", ") : "none";
616
- return { error: `Unknown sub-agent "${overrides.agent}". Available sub-agents: ${available}.` };
617
- }
618
- // Listed, never dropped (spec 040, D5) — but refused here with the reason, not a fallback.
619
- if (baseConfig.unavailable) {
620
- return { error: `Sub-agent "${baseConfig.name}" is currently unavailable: ${baseConfig.unavailable}` };
621
- }
622
- if (baseConfig.runtime === "external") {
623
- return {
624
- config: {
625
- ...baseConfig,
626
- thinkingLevel: baseConfig.thinkingLevel ?? (overrides.purpose === "verify" ? DEFAULT_THINKING_LEVEL : undefined),
627
- },
628
- };
629
- }
630
- let model = baseConfig.model;
631
- let modelRef = baseConfig.modelRef;
632
- if (!model && subagentDefaultModelRef) {
633
- const resolved = resolveModelReference(subagentDefaultModelRef, availableModels);
634
- if (!resolved.model) {
635
- return { error: resolved.error };
636
- }
637
- model = resolved.model;
638
- modelRef = formatModelReference(resolved.model);
639
- }
640
- const thinkingLevel = baseConfig.thinkingLevel ?? DEFAULT_THINKING_LEVEL;
641
- const mutates = baseConfig.mutates ?? inferMutatesFromTools(baseConfig.tools);
642
- return {
643
- config: {
644
- ...baseConfig,
645
- model: model ?? currentModel,
646
- modelRef: modelRef ?? formatModelReference(model ?? currentModel),
647
- thinkingLevel,
648
- source: "predefined",
649
- mutates,
650
- },
651
- };
652
- }
653
- /**
654
- * Resolve a `subagent_inline` invocation (spec 046, D2.1) — a one-off executor with no role
655
- * file. `runtime` is always `"internal"` here: only a configured role file can name `external`,
656
- * and `InlineAgentOverrides` has no field for it, so the old function's external branches
657
- * (budget table, unset-by-default thinkingLevel, model/tools/mutates rejections) simply do not
658
- * apply to this path and are not reproduced here.
659
- */
660
- export function resolveInlineAgent(availableModels, currentModel, overrides,
661
- /** `settings.subagentModel` (spec 032 D5): used only when this call does not name a model. */
662
- subagentDefaultModelRef) {
663
- const systemPrompt = overrides.systemPrompt.trim();
664
- if (!systemPrompt) {
665
- return { error: "Sub-agent system prompt cannot be empty." };
666
- }
667
- const promptLengthError = validateSubAgentSystemPrompt(systemPrompt, "Inline sub-agent systemPrompt");
668
- if (promptLengthError) {
669
- return { error: promptLengthError };
670
- }
671
- const tools = overrides.tools ? validateToolNames(overrides.tools) : { tools: [...DEFAULT_SUB_AGENT_TOOLS] };
672
- if (tools.error) {
673
- return { error: tools.error };
674
- }
675
- let model;
676
- let modelRef;
677
- if (overrides.model?.trim()) {
678
- const resolved = resolveModelReference(overrides.model.trim(), availableModels);
679
- if (!resolved.model) {
680
- return { error: resolved.error };
681
- }
682
- model = resolved.model;
683
- modelRef = formatModelReference(resolved.model);
684
- }
685
- else if (subagentDefaultModelRef) {
686
- const resolved = resolveModelReference(subagentDefaultModelRef, availableModels);
687
- if (!resolved.model) {
688
- return { error: resolved.error };
689
- }
690
- model = resolved.model;
691
- modelRef = formatModelReference(resolved.model);
692
- }
693
- const effortOverride = parseEffort(overrides.effort);
694
- if (effortOverride.error) {
695
- return { error: effortOverride.error };
696
- }
697
- const budget = effortOverride.value
698
- ? SUB_AGENT_EFFORT_PRESETS[effortOverride.value]
699
- : {
700
- maxTurns: DEFAULT_MAX_TURNS,
701
- maxToolCalls: DEFAULT_MAX_TOOL_CALLS,
702
- maxWallTimeSec: DEFAULT_MAX_WALL_TIME_SEC,
703
- bashTimeoutSec: DEFAULT_BASH_TIMEOUT_SEC,
704
- };
705
- const contextOverride = parseContextChoice(overrides.context);
706
- if (contextOverride.error) {
707
- return { error: contextOverride.error };
708
- }
709
- const contextMode = contextOverride.value?.contextMode ?? "isolated";
710
- const memory = contextOverride.value?.memory ?? (contextMode === "contextual" ? "index" : "none");
711
- const thinkingLevelOverride = overrides.thinkingLevel ? parseThinkingLevel(overrides.thinkingLevel) : undefined;
712
- if (thinkingLevelOverride?.error) {
713
- return { error: thinkingLevelOverride.error };
714
- }
715
- const thinkingLevel = thinkingLevelOverride?.value ?? DEFAULT_THINKING_LEVEL;
716
- const mutatesOverride = parseMutates(overrides.mutates);
717
- if (mutatesOverride.error) {
718
- return { error: mutatesOverride.error };
719
- }
720
- const mutates = mutatesOverride.value ?? inferMutatesFromTools(tools.tools);
721
- // Inline roles have no frontmatter to declare `mutates` in, so this warning goes back to the
722
- // model in the result text instead of a discovery-time log (D6 in the pre-split resolver).
723
- const bashWithoutMutatesWarning = tools.tools.includes("bash") && mutatesOverride.value === undefined
724
- ? 'tools include bash but "mutates" is not declared; if this task writes to the workspace, pass mutates: "write" so it takes the exclusive workspace write lease'
725
- : undefined;
726
- return {
727
- warning: bashWithoutMutatesWarning,
728
- config: {
729
- name: "dynamic-subagent",
730
- description: "Inline sub-agent",
731
- systemPrompt,
732
- tools: tools.tools,
733
- model: model ?? currentModel,
734
- modelRef: modelRef ?? formatModelReference(model ?? currentModel),
735
- maxTurns: budget.maxTurns,
736
- maxToolCalls: budget.maxToolCalls,
737
- maxWallTimeSec: budget.maxWallTimeSec,
738
- bashTimeoutSec: budget.bashTimeoutSec,
739
- contextMode,
740
- memory,
741
- paths: [],
742
- thinkingLevel,
743
- source: "inline",
744
- runtime: "internal",
745
- mutates,
746
- },
747
- };
748
- }
749
- export function formatSubAgentList(agents, maxItems = 12) {
750
- if (agents.length === 0) {
751
- return "none";
752
- }
753
- const listed = agents.slice(0, maxItems).map((agent) => `- \`${agent.name}\`: ${agent.description}`);
754
- if (agents.length <= maxItems) {
755
- return listed.join("\n");
756
- }
757
- return `${listed.join("\n")}\n- ... and ${agents.length - maxItems} more`;
758
- }
759
511
  /**
760
512
  * Spec 042 D7: a fingerprint of the parts of an external role that decide *how a launched process
761
513
  * is built* — `command`, `externalModelRef`, `shell`. Persisted on a run at launch and compared
762
- * against the role's current config on `follow_up`: a mismatch means the role was hot-edited in a
763
- * way that would resume under a harness or executable it never actually wrote, so `follow_up`
764
- * refuses rather than silently reinterpreting the old session with the new config.
765
- *
766
- * Deliberately narrow — `systemPrompt` and `maxWallTimeSec` are excluded on purpose. A resumed
767
- * session already carries its own context, and folding prompt edits in would mean "fix a typo in
768
- * the role" breaks every in-flight follow-up; a full invocation snapshot was considered and
769
- * rejected for the same reason (spec 042 design doc, "已驳回的方案").
514
+ * against the role's current config on `follow_up` so hot-edited roles cannot silently resume an
515
+ * older session under a changed executable/model/shell mode.
770
516
  */
771
517
  export function externalRoleFingerprint(role) {
772
518
  return createHash("sha256")
@@ -1,6 +1,5 @@
1
1
  import type { Api, Model } from "@earendil-works/pi-ai";
2
- import type { ResolvedSubAgentConfig } from "./discovery.js";
3
- import type { DelegationParams, DelegationResult, SubAgentToolFields, SubAgentToolOptions } from "./types.js";
2
+ import type { DelegationParams, DelegationResult, ResolvedSubAgentConfig, SubAgentToolFields, SubAgentToolOptions } from "./types.js";
4
3
  /**
5
4
  * A run's lifecycle is deliberately unlinked from the tool call's `AbortSignal` (spec 040, D2):
6
5
  * `/stop` ends the current turn but no longer kills an in-flight delegation, matching background
@@ -15,6 +15,7 @@ import { dispatchInternalRun } from "./internal/run.js";
15
15
  import { assertVerifyAdmissible } from "./task-envelope.js";
16
16
  import { acquireWorkspaceLease, formatWorkspaceLeaseConflict } from "./workspace-lease.js";
17
17
  import { snapshotWorkspace } from "./workspace-summary.js";
18
+ import { cleanupManagedWorktreeIfUnchanged, prepareManagedWorktree } from "./worktree.js";
18
19
  function safeRunSegment(value) {
19
20
  return value.replace(/[^A-Za-z0-9._-]/g, "-").slice(0, 48) || "run";
20
21
  }
@@ -113,52 +114,72 @@ export async function dispatchSubAgentRun(options, currentModel, config, warning
113
114
  // A short, human-typeable id (spec 041) — never the dispatching tool call's own id, which
114
115
  // on some providers is a long `call_<id>|fc_<id>` composite unreadable in a chat UI.
115
116
  const runContext = await prepareRunContext(runManager.mintRunId(), params, options);
117
+ if (params.worktree) {
118
+ if (runContext.purpose === "verify" || config.mutates !== "write") {
119
+ throw new RecoverableToolError('worktree=true is only valid for write delegations (mutates="write" and purpose="work"); omit worktree for read-only or verification runs.');
120
+ }
121
+ const prepared = await prepareManagedWorktree(runContext.workingDirectory, runContext.artifactDir, runContext.runId);
122
+ runContext.workingDirectory = prepared.workingDirectory;
123
+ runContext.managedWorktree = {
124
+ path: prepared.worktreeRoot,
125
+ baseDir: prepared.baseDir,
126
+ branch: prepared.branch,
127
+ baseHead: prepared.baseHead,
128
+ };
129
+ }
116
130
  // D9: an independent verifier checks against a target that isn't moving under it — shared
117
131
  // with `subagent_run op=follow_up` (spec 042 D7) so a verify run's admission rules
118
132
  // cannot drift between the two dispatch paths.
119
133
  assertVerifyAdmissible(config, runContext.purpose, runContext.workingDirectory);
120
- // Admission: every write-mutating run, including a write-capable verifier, takes an exclusive
121
- // workspace lease before it is even registered (spec 040, D10.1). A rejected delegation should
122
- // never count as "started"; the lease is handed to SubAgentRunManager as the settlement owner.
123
- let leaseKey;
124
- if (config.mutates === "write") {
125
- const lease = acquireWorkspaceLease({
126
- runId: runContext.runId,
127
- channelId: options.runtimeContext.channelId,
128
- workingDirectory: runContext.workingDirectory,
129
- });
130
- if (!lease.ok) {
131
- throw new RecoverableToolError(formatWorkspaceLeaseConflict(lease.heldBy));
134
+ // Every run pins its directory against cleanup; only writers and verifiers exclude mutations.
135
+ const lease = acquireWorkspaceLease({
136
+ runId: runContext.runId,
137
+ channelId: options.runtimeContext.channelId,
138
+ workingDirectory: runContext.workingDirectory,
139
+ mode: config.mutates === "write" ? "write" : runContext.purpose === "verify" ? "read" : "use",
140
+ });
141
+ if (!lease.ok) {
142
+ if (runContext.managedWorktree) {
143
+ await cleanupManagedWorktreeIfUnchanged(runContext.artifactDir).catch(() => undefined);
132
144
  }
133
- leaseKey = lease.leaseKey;
145
+ throw new RecoverableToolError(formatWorkspaceLeaseConflict(lease.heldBy));
134
146
  }
147
+ const leaseKey = lease.leaseKey;
135
148
  // Taken under the lease, before the run can write: what "already dirty" means for this run.
136
149
  const workspaceBaseline = config.mutates === "write" ? await snapshotWorkspace(runContext.workingDirectory) : undefined;
137
- if (config.runtime === "external") {
138
- return dispatchExternalRun({
150
+ try {
151
+ if (config.runtime === "external") {
152
+ return await dispatchExternalRun({
153
+ options,
154
+ currentModel,
155
+ config,
156
+ runLabel,
157
+ runContext,
158
+ leaseKey,
159
+ params,
160
+ runManager,
161
+ workspaceBaseline,
162
+ });
163
+ }
164
+ return await dispatchInternalRun({
139
165
  options,
140
166
  currentModel,
141
167
  config,
142
168
  runLabel,
169
+ mutatesNote,
143
170
  runContext,
144
171
  leaseKey,
145
172
  params,
173
+ signal,
174
+ onUpdate,
146
175
  runManager,
147
176
  workspaceBaseline,
148
177
  });
149
178
  }
150
- return dispatchInternalRun({
151
- options,
152
- currentModel,
153
- config,
154
- runLabel,
155
- mutatesNote,
156
- runContext,
157
- leaseKey,
158
- params,
159
- signal,
160
- onUpdate,
161
- runManager,
162
- workspaceBaseline,
163
- });
179
+ catch (error) {
180
+ if (runContext.managedWorktree) {
181
+ await cleanupManagedWorktreeIfUnchanged(runContext.artifactDir).catch(() => undefined);
182
+ }
183
+ throw error;
184
+ }
164
185
  }
@@ -0,0 +1,2 @@
1
+ import { type ExternalHarness } from "./harness.js";
2
+ export declare const antigravityCliHarness: ExternalHarness;