@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,5 +1,6 @@
1
+ import { splitShellWords } from "../../shared/shell-words.js";
1
2
  import { isPlainObject } from "../../shared/type-guards.js";
2
- import { detectExistingFlags, expandPlaceholders, formatDroppedPlaceholderWarnings, } from "./harness.js";
3
+ import { detectExistingFlags, expandPlaceholders, formatDroppedPlaceholderWarnings, outputFormatConflicts, parseJsonObjectLines, } from "./harness.js";
3
4
  /**
4
5
  * `cursor-cli` harness (spec 066). One prompt, one short-lived `agent -p` process. The CLI assigns
5
6
  * the session id in `system/init`; this adapter never invents one. Effort is not a separate flag:
@@ -23,8 +24,14 @@ const TOOL_SUBJECT_FIELDS = ["command", "path", "file_path", "target_file", "pat
23
24
  function toCursorEffort(level) {
24
25
  return THINKING_LEVEL_TO_CURSOR_EFFORT[level] ?? level;
25
26
  }
26
- /** A single trailing `[...]` list. Anything else that contains `[` is left untouched. */
27
+ /** A single trailing `[...]` list. `auto` and anything else that contains `[` is left untouched. */
27
28
  function decorateCursorModel(model, effort) {
29
+ if (model.trim() === "auto") {
30
+ return {
31
+ model,
32
+ warning: 'Left model id "auto" unchanged: the auto router does not accept [effort=...] overrides.',
33
+ };
34
+ }
28
35
  if (!model.includes("["))
29
36
  return { model: `${model}[effort=${effort}]` };
30
37
  const match = /^([^[\]]*)\[([^[\]]*)\]$/.exec(model);
@@ -44,23 +51,13 @@ function decorateCursorModel(model, effort) {
44
51
  const nextInner = inner.trim() === "" ? `effort=${effort}` : `${inner},effort=${effort}`;
45
52
  return { model: `${match[1]}[${nextInner}]` };
46
53
  }
54
+ const FORCE_TOKENS = new Set(["-f", "--force", "--yolo"]);
55
+ function hasWorktreeToken(token) {
56
+ return token === "--worktree" || token === "-w" || token.startsWith("--worktree=");
57
+ }
47
58
  function hasTrustFlag(argv) {
48
59
  return argv.some((token) => token === "--trust" || token.startsWith("--trust="));
49
60
  }
50
- /** True when the command already chose an output format other than the one settlement parses. */
51
- function outputFormatConflicts(argv) {
52
- for (let i = 0; i < argv.length; i++) {
53
- const token = argv[i];
54
- if (token === "--output-format") {
55
- if (argv[i + 1] !== "stream-json")
56
- return true;
57
- }
58
- else if (token?.startsWith("--output-format=") && token.slice("--output-format=".length) !== "stream-json") {
59
- return true;
60
- }
61
- }
62
- return false;
63
- }
64
61
  function collapseWhitespace(text) {
65
62
  return text.replace(/\s+/g, " ").trim();
66
63
  }
@@ -128,6 +125,24 @@ function assistantText(record) {
128
125
  export const cursorCliHarness = {
129
126
  id: "cursor-cli",
130
127
  parserVersion: 1,
128
+ resumable: true,
129
+ requiresProtocolTerminal: true,
130
+ supportsImplicitVerifyThinking: false,
131
+ roleWarnings(input) {
132
+ const tokens = splitShellWords(input.command);
133
+ const hasForce = tokens.some((token) => FORCE_TOKENS.has(token));
134
+ const warnings = [];
135
+ if (input.mutates === "write" && !hasForce) {
136
+ warnings.push(`${input.entryName}: print mode does not write changes to files unless command includes -f, --force, or --yolo`);
137
+ }
138
+ if (input.mutates === "read" && hasForce) {
139
+ warnings.push(`${input.entryName}: command includes -f, --force, or --yolo, so the CLI can modify files and the workspace write lock will not stop it`);
140
+ }
141
+ if (tokens.some(hasWorktreeToken)) {
142
+ warnings.push(`${input.entryName}: --worktree writes under ~/.cursor/worktrees/, outside the delegation working directory, so the workspace write lock does not cover those files`);
143
+ }
144
+ return warnings;
145
+ },
131
146
  buildInvocation(input) {
132
147
  if (input.argv.length === 0) {
133
148
  throw new Error("cursor-cli: command produced no argv tokens");
@@ -181,23 +196,11 @@ export const cursorCliHarness = {
181
196
  let terminalSeen = false;
182
197
  let protocolStatus = "absent";
183
198
  let errorMessage;
184
- let parsedAnyObject = false;
185
199
  let assistantCandidate;
186
200
  let resultText;
187
- for (const line of input.eventsText.split("\n")) {
188
- const trimmed = line.trim();
189
- if (!trimmed)
190
- continue;
191
- let event;
192
- try {
193
- event = JSON.parse(trimmed);
194
- }
195
- catch {
196
- continue;
197
- }
198
- if (!isPlainObject(event))
199
- continue;
200
- parsedAnyObject = true;
201
+ const events = parseJsonObjectLines(input.eventsText);
202
+ const parsedAnyObject = events.length > 0;
203
+ for (const event of events) {
201
204
  if (typeof event.session_id === "string")
202
205
  sessionId = event.session_id;
203
206
  if (event.type === "assistant") {
@@ -1,12 +1,9 @@
1
- /**
2
- * The `runtime: external` half of delegation dispatch: launches the harness process through
3
- * `external/run.ts`. Always returns the "[Dispatched]" placeholder.
4
- */
5
1
  import type { Api, Model } from "@earendil-works/pi-ai";
6
- import { type ExternalSubAgentConfig } from "../discovery.js";
2
+ import type { SecurityConfig } from "../../security/types.js";
3
+ import type { RunRecord } from "../run-record.js";
7
4
  import type { SubAgentRunManager } from "../runs.js";
8
- import type { DelegationParams, DelegationResult, SubAgentRunContext, SubAgentToolOptions } from "../types.js";
9
- import type { WorkspaceBaseline } from "../workspace-summary.js";
5
+ import type { DelegationParams, DelegationResult, ExternalSubAgentConfig, SubAgentDiscoveryResult, SubAgentRunContext, SubAgentToolOptions } from "../types.js";
6
+ import { type WorkspaceBaseline } from "../workspace-summary.js";
10
7
  /**
11
8
  * The `runtime: external` half of `dispatchSubAgentRun` (spec 046, D2.5): launches the harness
12
9
  * process and always returns the "[Dispatched]" placeholder — external's sync grace window is
@@ -23,3 +20,20 @@ export declare function dispatchExternalRun(input: {
23
20
  params: DelegationParams;
24
21
  workspaceBaseline: WorkspaceBaseline | undefined;
25
22
  }): Promise<DelegationResult>;
23
+ /**
24
+ * Resumes a finished external run on a resumable harness under a fresh `runId`, re-validating role
25
+ * availability, harness identity, verify admissibility, role fingerprint, and workspace leases.
26
+ */
27
+ export declare function dispatchExternalFollowUp(input: {
28
+ runManager: SubAgentRunManager;
29
+ record: RunRecord;
30
+ task: string;
31
+ channelId: string;
32
+ workspaceDir: string;
33
+ desk: string;
34
+ deskDir: string;
35
+ discovery?: SubAgentDiscoveryResult;
36
+ securityConfig?: SecurityConfig;
37
+ }): Promise<{
38
+ newRunId: string;
39
+ }>;
@@ -1,11 +1,32 @@
1
+ /**
2
+ * The `runtime: external` half of delegation dispatch and `follow_up` continuation: launches the
3
+ * harness process through `external/run.ts` and converts pre-spawn launch failures into tool errors.
4
+ */
5
+ import { existsSync } from "node:fs";
6
+ import { dirname, join } from "node:path";
1
7
  import { DEFAULT_SECURITY_CONFIG } from "../../security/config.js";
2
8
  import { RecoverableToolError } from "../../shared/recoverable-error.js";
3
9
  import { createEmptyUsageTotals } from "../../usage/totals.js";
4
10
  import { externalRoleFingerprint } from "../discovery.js";
5
11
  import { buildDispatchedText, createDetails } from "../result.js";
6
- import { buildSubAgentTask, resolveContextualBlocks } from "../task-envelope.js";
7
- import { releaseWorkspaceLease } from "../workspace-lease.js";
12
+ import { assertVerifyAdmissible, buildFollowUpTask, buildSubAgentTask, resolveContextualBlocks, } from "../task-envelope.js";
13
+ import { acquireWorkspaceLease, formatWorkspaceLeaseConflict, releaseWorkspaceLease } from "../workspace-lease.js";
14
+ import { snapshotWorkspace } from "../workspace-summary.js";
15
+ import { copyManagedWorktreeMeta } from "../worktree.js";
16
+ import { getExternalHarness } from "./registry.js";
8
17
  import { launchExternalRun } from "./run.js";
18
+ /**
19
+ * Spec 042 D2: a pre-spawn failure is reported in the dispatching turn instead of returning a
20
+ * "[Dispatched]" placeholder the model would wait on forever. `settle()` already released any lease.
21
+ */
22
+ function throwOnExternalLaunchFailure(launchResult, subjectLabel, targetNoun) {
23
+ if (launchResult.ok)
24
+ return;
25
+ if (launchResult.kind === "missing-binary") {
26
+ throw new Error(`${subjectLabel} failed to launch: ${launchResult.reason} Install the CLI or fix "command" in its role file; the ${targetNoun} was not dispatched.`);
27
+ }
28
+ throw new RecoverableToolError(`${subjectLabel} failed to launch: ${launchResult.reason} The ${targetNoun} was not dispatched.`);
29
+ }
9
30
  /**
10
31
  * The `runtime: external` half of `dispatchSubAgentRun` (spec 046, D2.5): launches the harness
11
32
  * process and always returns the "[Dispatched]" placeholder — external's sync grace window is
@@ -57,22 +78,14 @@ export async function dispatchExternalRun(input) {
57
78
  releaseWorkspaceLease(leaseKey, runContext.runId);
58
79
  throw error;
59
80
  }
60
- // Spec 042 D2: a pre-spawn failure is reported in this same turn instead of a
61
- // "[Dispatched]" placeholder the model would wait on forever — two of the three
62
- // failure kinds never used to announce at all. `settle()` already released the lease.
63
- if (!launchResult.ok) {
64
- if (launchResult.kind === "missing-binary") {
65
- throw new Error(`Sub-agent "${config.name}" failed to launch: ${launchResult.reason} Install the CLI or fix "command" in its role file; the run was not dispatched.`);
66
- }
67
- throw new RecoverableToolError(`Sub-agent "${config.name}" failed to launch: ${launchResult.reason} The run was not dispatched.`);
68
- }
81
+ throwOnExternalLaunchFailure(launchResult, `Sub-agent "${config.name}"`, "run");
69
82
  // D2: external's sync grace window is always 0 — always the dispatched placeholder,
70
83
  // never an inline wait. The run keeps going in the background and wakes the channel.
71
84
  return {
72
85
  content: [
73
86
  {
74
87
  type: "text",
75
- text: buildDispatchedText(runContext.runId, config.name, `external, ${config.harness}`, runContext.workingDirectory),
88
+ text: buildDispatchedText(runContext.runId, config.name, `external, ${config.harness}`, runContext.workingDirectory, runContext.managedWorktree),
76
89
  },
77
90
  ],
78
91
  details: createDetails({
@@ -88,3 +101,124 @@ export async function dispatchExternalRun(input) {
88
101
  }),
89
102
  };
90
103
  }
104
+ /**
105
+ * Resumes a finished external run on a resumable harness under a fresh `runId`, re-validating role
106
+ * availability, harness identity, verify admissibility, role fingerprint, and workspace leases.
107
+ */
108
+ export async function dispatchExternalFollowUp(input) {
109
+ const { runManager, record, task } = input;
110
+ const resolvedRunId = record.runId;
111
+ const harness = record.runtime === "external" && record.harness && getExternalHarness(record.harness)?.resumable
112
+ ? record.harness
113
+ : undefined;
114
+ if (!harness) {
115
+ // Internal runs have no persisted transcript to resume — the isolated-context design
116
+ // is the point, not a gap. Non-resumable harnesses (`exec`) have no session concept.
117
+ throw new RecoverableToolError(`Run "${resolvedRunId}" (${record.runtime}${record.harness ? `/${record.harness}` : ""}) does not support ` +
118
+ "follow_up yet. Delegate a new run instead, carrying forward whatever context or prior output it needs.");
119
+ }
120
+ if (record.status === "running") {
121
+ throw new RecoverableToolError(`Run "${resolvedRunId}" is still running; wait for it to finish before following up.`);
122
+ }
123
+ if (!record.sessionId) {
124
+ throw new RecoverableToolError(`Run "${resolvedRunId}" never reported a session id (it likely failed before producing one); it cannot be resumed. Delegate a new run instead.`);
125
+ }
126
+ const role = input.discovery?.agents.find((agent) => agent.name === record.agent && agent.runtime === "external");
127
+ if (!role) {
128
+ throw new RecoverableToolError(`Role "${record.agent}" is no longer configured as an external role; cannot follow up run "${resolvedRunId}".`);
129
+ }
130
+ if (role.unavailable) {
131
+ throw new RecoverableToolError(`Role "${record.agent}" is currently unavailable: ${role.unavailable}`);
132
+ }
133
+ // P1-2: a role hot-edited between the original run and this follow-up must not silently
134
+ // resume under a stale harness (the wrong CLI would parse a command it never wrote), or
135
+ // masquerade a shell role as resumable (there is no flag to carry `resumeSessionId` into
136
+ // `/bin/sh -lc`, so the run would silently start a fresh, unrelated session anyway).
137
+ if (role.harness !== harness) {
138
+ throw new RecoverableToolError(`Role "${record.agent}" now uses harness "${role.harness}", but run "${resolvedRunId}" was started on "${harness}". Delegate a new run instead of resuming across a harness change.`);
139
+ }
140
+ if (role.shell) {
141
+ throw new RecoverableToolError(`Role "${record.agent}" runs its command through a shell, which has no way to carry a resume session id. Delegate a new run instead, carrying forward whatever context it needs.`);
142
+ }
143
+ if (!existsSync(record.workingDirectory)) {
144
+ throw new RecoverableToolError(`Run "${resolvedRunId}"'s working directory "${record.workingDirectory}" no longer exists (for example, an unchanged managed worktree was cleaned up on settlement). Delegate a new run instead.`);
145
+ }
146
+ assertVerifyAdmissible(role, record.purpose, record.workingDirectory);
147
+ // Spec 042 D7: a role hot-edited since the original dispatch (different command, model,
148
+ // or shell mode) would resume the old session under a harness invocation it never wrote.
149
+ const currentFingerprint = externalRoleFingerprint(role);
150
+ if (record.roleFingerprint !== undefined && record.roleFingerprint !== currentFingerprint) {
151
+ throw new RecoverableToolError(`Role "${record.agent}" has changed (command, model, or shell mode) since run "${resolvedRunId}" was dispatched; resuming under the new config could reinterpret the old session incorrectly. Delegate a new run instead.`);
152
+ }
153
+ const newRunId = runManager.mintRunId();
154
+ const lease = acquireWorkspaceLease({
155
+ runId: newRunId,
156
+ channelId: input.channelId,
157
+ workingDirectory: record.workingDirectory,
158
+ mode: role.mutates === "write" ? "write" : record.purpose === "verify" ? "read" : "use",
159
+ });
160
+ if (!lease.ok)
161
+ throw new RecoverableToolError(formatWorkspaceLeaseConflict(lease.heldBy));
162
+ const leaseKey = lease.leaseKey;
163
+ // Spec 042 D7: `<subagent-artifacts>/<runId>` computed with path join rather than regex substitution.
164
+ const artifactDir = join(dirname(record.artifactDir), newRunId);
165
+ const runContext = {
166
+ runId: newRunId,
167
+ purpose: record.purpose,
168
+ taskId: record.taskId,
169
+ item: record.item,
170
+ workingDirectory: record.workingDirectory,
171
+ artifactDir,
172
+ };
173
+ let launchResult;
174
+ try {
175
+ // Cleanup may have won admission since the earlier preflight. Recheck while pinned.
176
+ if (!existsSync(record.workingDirectory)) {
177
+ throw new RecoverableToolError(`Run "${resolvedRunId}"'s working directory was removed; delegate a new run instead.`);
178
+ }
179
+ await copyManagedWorktreeMeta(record.artifactDir, artifactDir).catch(() => false);
180
+ const envelopedTask = buildFollowUpTask(task, {
181
+ workspaceDir: input.workspaceDir,
182
+ desk: input.desk,
183
+ deskDir: input.deskDir,
184
+ channelId: input.channelId,
185
+ }, runContext);
186
+ const workspaceBaseline = role.mutates === "write" ? await snapshotWorkspace(record.workingDirectory) : undefined;
187
+ launchResult = await launchExternalRun({
188
+ runManager,
189
+ runId: newRunId,
190
+ channelId: input.channelId,
191
+ deskDir: input.deskDir,
192
+ label: `follow-up: ${task.slice(0, 80)}`,
193
+ agent: role.name,
194
+ source: role.source,
195
+ harness,
196
+ command: role.command,
197
+ shell: role.shell,
198
+ env: role.env,
199
+ externalModelRef: role.externalModelRef,
200
+ thinkingLevel: role.thinkingLevel,
201
+ maxWallTimeSec: role.maxWallTimeSec,
202
+ systemPrompt: role.systemPrompt,
203
+ task: envelopedTask,
204
+ workingDirectory: record.workingDirectory,
205
+ artifactDir,
206
+ purpose: record.purpose,
207
+ taskId: record.taskId,
208
+ item: record.item,
209
+ leaseKey,
210
+ resumeSessionId: record.sessionId,
211
+ mutates: role.mutates,
212
+ workspaceBaseline,
213
+ roleFingerprint: currentFingerprint,
214
+ workspaceDir: input.workspaceDir,
215
+ securityConfig: input.securityConfig ?? DEFAULT_SECURITY_CONFIG,
216
+ });
217
+ }
218
+ catch (error) {
219
+ releaseWorkspaceLease(leaseKey, newRunId);
220
+ throw error;
221
+ }
222
+ throwOnExternalLaunchFailure(launchResult, `Follow-up on run "${resolvedRunId}"`, "follow-up");
223
+ return { newRunId };
224
+ }
@@ -13,6 +13,9 @@ const MAX_OUTPUT_CHARS = 16_000;
13
13
  export const execHarness = {
14
14
  id: "exec",
15
15
  parserVersion: 1,
16
+ resumable: false,
17
+ requiresProtocolTerminal: false,
18
+ supportsImplicitVerifyThinking: false,
16
19
  buildInvocation(input) {
17
20
  if (input.argv.length === 0) {
18
21
  throw new Error("exec: command produced no argv tokens");
@@ -1,10 +1,10 @@
1
1
  import type { UsageTotals } from "../../usage/totals.js";
2
- import type { SubAgentThinkingLevel } from "../discovery.js";
2
+ import type { RunHarness, SubAgentThinkingLevel } from "../run-record.js";
3
3
  /**
4
4
  * The harness adapter seam (spec 040, D4). Every external run is reduced to the same process
5
- * model (D3: one prompt, one short-lived process); what differs between `claude-code`,
6
- * `codex-cli`, `cursor-cli`, and `exec` is only argv assembly and stdout parsing, and that is exactly what this
7
- * interface covers. It carries no state machine of its own — `runs.ts` owns that.
5
+ * model (D3: one prompt, one short-lived process); what differs between harnesses is argv
6
+ * assembly, static role checks, capability flags, and stdout parsing — all owned here rather than
7
+ * scattered as harness-name branches across discovery, tools, and orchestration.
8
8
  */
9
9
  export interface ExternalInvocationInput {
10
10
  /** The role's `command`, already shell-word-split (D4) — never re-parsed here, never shelled out. */
@@ -26,7 +26,7 @@ export interface ExternalInvocationInput {
26
26
  export interface BuildInvocationResult {
27
27
  executable: string;
28
28
  args: string[];
29
- /** Whether this harness can be continued later via `resumeSessionId` (claude-code/codex-cli/cursor-cli). */
29
+ /** Whether this harness can be continued later via `resumeSessionId`. */
30
30
  resumable: boolean;
31
31
  /**
32
32
  * claude-code only (D4): a session id it picked and passed via `--session-id` *before* running,
@@ -52,7 +52,7 @@ export interface ExternalOutcome {
52
52
  usage?: Partial<UsageTotals>;
53
53
  /** `cursor-cli`/`exec` are always false: neither reports tokens. */
54
54
  usageKnown: boolean;
55
- /** `cursor-cli`/`codex-cli`/`exec` are always false: none of them reports a cost field. */
55
+ /** `cursor-cli`/`codex-cli`/`antigravity-cli`/`exec` are always false: none of them reports a cost field. */
56
56
  costKnown: boolean;
57
57
  stderrTail?: string;
58
58
  errorMessage?: string;
@@ -63,38 +63,57 @@ export interface ParseOutcomeInput {
63
63
  /** `undefined` when the process was killed by a signal rather than exiting normally. */
64
64
  exitCode?: number;
65
65
  stderrTail?: string;
66
+ /** Spec 068 D8: expected resumed conversation id for harnesses that verify resumed sessions. */
67
+ expectedResumeSessionId?: string;
68
+ }
69
+ export interface ExternalRoleWarningInput {
70
+ /** Role filename, so a warning can be traced back to the file that produced it. */
71
+ entryName: string;
72
+ harness: string;
73
+ command: string;
74
+ mutates: "read" | "write";
75
+ /** Resolved memory mode. Anything other than `none` discloses desk memory to the external process. */
76
+ memory: string;
77
+ /** True when frontmatter `model` is set. External models are never taken from the invocation. */
78
+ modelConfigured: boolean;
66
79
  }
67
80
  export interface ExternalHarness {
68
- readonly id: "claude-code" | "codex-cli" | "cursor-cli" | "exec";
81
+ readonly id: RunHarness;
69
82
  /**
70
83
  * Spec 042 D12: bumped by hand whenever this adapter's `parseOutcome` schema assumptions
71
84
  * change. Persisted on the run and shown by `/subagents show`, so a failure caused by upstream
72
- * CLI schema drift is distinguishable from a failure the target CLI itself reported — "the
73
- * adapter is stale" and "the agent failed" look identical from a run's status alone otherwise.
85
+ * CLI schema drift is distinguishable from a failure the target CLI itself reported.
74
86
  */
75
87
  readonly parserVersion: number;
88
+ /** Whether `subagent_run op=follow_up` can resume a finished run on this harness. */
89
+ readonly resumable: boolean;
90
+ /** Whether completion requires a protocol terminal event (false only for raw `exec`, D4/D9). */
91
+ readonly requiresProtocolTerminal: boolean;
92
+ /** Whether `purpose=verify` supplies the default thinking level when the role omits one. */
93
+ readonly supportsImplicitVerifyThinking: boolean;
94
+ /** True when `systemPrompt` is passed via a CLI flag rather than prepended on stdin (`claude-code`). */
95
+ readonly acceptsSystemPromptFlag?: boolean;
96
+ /** True when resumed runs persist and verify `expectedResumeSessionId` in `parseOutcome` (spec 068 D8). */
97
+ readonly verifiesResumeSession?: boolean;
76
98
  /** Assemble argv. The command line is never joined into a single shell string (D4). */
77
99
  buildInvocation(input: ExternalInvocationInput): BuildInvocationResult;
78
100
  /** Parse stdout into a unified outcome. Must never throw — a parse failure degrades to
79
101
  * `protocolStatus: "unparsable"`, not an exception (D4). */
80
102
  parseOutcome(input: ParseOutcomeInput): ExternalOutcome;
81
103
  /**
82
- * P1a: map one raw output line, still mid-run, to a short human-readable step label — e.g. the
83
- * command a coding CLI just started, or a todo-list progress count. Same contract as
84
- * `parseOutcome`: must never throw, and returns `undefined` for a line that carries no
85
- * progress-worthy information (most lines). Optional — `exec` has no structured protocol to
86
- * read mid-run, so it omits this entirely rather than implement a no-op.
104
+ * P1a: map one raw output line, still mid-run, to a short human-readable step label. Must never
105
+ * throw, and returns `undefined` for a line that carries no progress-worthy information.
87
106
  */
88
107
  toProgressLabel?(line: string): string | undefined;
108
+ /** Optional discovery-time static role warnings owned by this harness. */
109
+ roleWarnings?(input: ExternalRoleWarningInput): string[];
89
110
  }
90
111
  /**
91
112
  * The D4 status table, shared by the live post-exit path and restart reconciliation (D10.3) so
92
- * both judge a run identically. `exec` is the table's explicit exception (D4/D9): it has no
93
- * protocol terminal at all, so its own `parseOutcome` already folds the exit code into
94
- * `protocolStatus` directly — `terminalSeen` stays `false` even on success, so it must not be
95
- * checked here for that one harness.
113
+ * both judge a run identically. Harnesses with `requiresProtocolTerminal: false` (`exec`) fold
114
+ * exit code directly into `protocolStatus` because they emit no protocol terminal event.
96
115
  */
97
- export declare function classifyExternalOutcome(harnessId: ExternalHarness["id"], outcome: ExternalOutcome): {
116
+ export declare function classifyExternalOutcome(harnessOrId: Pick<ExternalHarness, "requiresProtocolTerminal"> | RunHarness, outcome: ExternalOutcome): {
98
117
  status: "completed" | "failed";
99
118
  failureReason?: string;
100
119
  };
@@ -103,29 +122,34 @@ export interface ExistingFlags {
103
122
  model: boolean;
104
123
  effort: boolean;
105
124
  }
106
- /** Which flags the user's own `command` already spells out, so a harness never injects a duplicate (D4). */
107
- export declare function detectExistingFlags(argv: string[]): ExistingFlags;
125
+ export interface DetectExistingFlagsOptions {
126
+ /** Recognize `-m` / `-m=...` as a short model flag (default true; `agy` supports `--model` only). */
127
+ shortModelFlag?: boolean;
128
+ /** Recognize `--thinking` / `--thinking=...` as an effort alias (default true; `agy` supports `--effort` only). */
129
+ thinkingAlias?: boolean;
130
+ /** Recognize Codex CLI's `-c` / `--config` `model=...` and `model_reasoning_effort=...` overrides (default false). */
131
+ codexConfigFlag?: boolean;
132
+ }
133
+ /** Which flags the user's own `command` already spells out, scoped to the target CLI's flag grammar (D4). */
134
+ export declare function detectExistingFlags(argv: readonly string[], options?: DetectExistingFlagsOptions): ExistingFlags;
135
+ /** True when `argv` already specifies `--output-format` with a value other than `expected`. */
136
+ export declare function outputFormatConflicts(argv: readonly string[], expected?: string): boolean;
137
+ /**
138
+ * Parse NDJSON lines into plain JSON objects, tolerating blank, torn, or non-object lines.
139
+ * Returning an array keeps each adapter's loop imperative so TypeScript tracks state narrowing.
140
+ */
141
+ export declare function parseJsonObjectLines(eventsText: string): Record<string, unknown>[];
108
142
  declare const PLACEHOLDERS: readonly ["$MODEL", "$EFFORT", "$PROMPT_FILE", "$SYSTEM_PROMPT_FILE"];
109
143
  export type Placeholder = (typeof PLACEHOLDERS)[number];
110
144
  /**
111
145
  * Expand `$MODEL`/`$EFFORT`/`$PROMPT_FILE`/`$SYSTEM_PROMPT_FILE` wherever they appear in argv
112
- * (D4). Returns which placeholders were actually found, so a harness knows whether it still needs
113
- * to *append* the corresponding flag (a placeholder present ⇒ never append; absent ⇒ append per
114
- * the harness's own rule).
115
- *
116
- * Spec 042 D10: a token that still references a placeholder after substitution (its value was
117
- * `undefined`, e.g. `--model $MODEL` on a role with no `model:` configured) is dropped from argv
118
- * entirely rather than reaching the process as a literal `"$MODEL"` string — that literal-string
119
- * failure is exactly what D4's "argv, not a shell string" design exists to prevent, just arriving
120
- * through a different door (a missing value instead of a shell-quoting bug). `dropped` carries the
121
- * original tokens so the caller can turn them into a run-visible warning.
146
+ * (D4). Unresolved placeholder tokens are dropped and returned in `dropped` (spec 042 D10).
122
147
  */
123
148
  export declare function expandPlaceholders(argv: string[], values: Partial<Record<Placeholder, string>>): {
124
149
  argv: string[];
125
150
  used: Set<Placeholder>;
126
151
  dropped: string[];
127
152
  };
128
- /** Turn `expandPlaceholders`'s `dropped` tokens into run-visible warning strings (spec 042 D10),
129
- * shared so every structured harness reports the same wording. */
153
+ /** Turn `expandPlaceholders`'s `dropped` tokens into run-visible warning strings (spec 042 D10). */
130
154
  export declare function formatDroppedPlaceholderWarnings(dropped: string[]): string[];
131
155
  export {};
@@ -1,12 +1,12 @@
1
+ import { isPlainObject } from "../../shared/type-guards.js";
1
2
  /**
2
3
  * The D4 status table, shared by the live post-exit path and restart reconciliation (D10.3) so
3
- * both judge a run identically. `exec` is the table's explicit exception (D4/D9): it has no
4
- * protocol terminal at all, so its own `parseOutcome` already folds the exit code into
5
- * `protocolStatus` directly — `terminalSeen` stays `false` even on success, so it must not be
6
- * checked here for that one harness.
4
+ * both judge a run identically. Harnesses with `requiresProtocolTerminal: false` (`exec`) fold
5
+ * exit code directly into `protocolStatus` because they emit no protocol terminal event.
7
6
  */
8
- export function classifyExternalOutcome(harnessId, outcome) {
9
- if (harnessId === "exec") {
7
+ export function classifyExternalOutcome(harnessOrId, outcome) {
8
+ const requiresTerminal = typeof harnessOrId === "string" ? harnessOrId !== "exec" : harnessOrId.requiresProtocolTerminal;
9
+ if (!requiresTerminal) {
10
10
  return outcome.protocolStatus === "completed"
11
11
  ? { status: "completed" }
12
12
  : { status: "failed", failureReason: outcome.errorMessage ?? `exec exited with code ${outcome.exitCode}` };
@@ -31,55 +31,85 @@ export function classifyExternalOutcome(harnessId, outcome) {
31
31
  failureReason: outcome.errorMessage ?? "The process ended without a recognized terminal state.",
32
32
  };
33
33
  }
34
- const MODEL_FLAG_PATTERN = /^(--model|-m)$/;
35
- const EFFORT_FLAG_PATTERN = /^(--effort|--thinking)$/;
36
34
  const CODEX_CONFIG_FLAG_PATTERN = /^(-c|--config)$/;
37
35
  const CODEX_MODEL_VALUE_PREFIX = "model=";
38
36
  const CODEX_EFFORT_VALUE_PREFIX = "model_reasoning_effort=";
39
- /** Which flags the user's own `command` already spells out, so a harness never injects a duplicate (D4). */
40
- export function detectExistingFlags(argv) {
37
+ /** Which flags the user's own `command` already spells out, scoped to the target CLI's flag grammar (D4). */
38
+ export function detectExistingFlags(argv, options = {}) {
39
+ const shortModel = options.shortModelFlag ?? true;
40
+ const thinkingAlias = options.thinkingAlias ?? true;
41
+ const codexConfig = options.codexConfigFlag ?? false;
41
42
  let model = false;
42
43
  let effort = false;
43
44
  for (let i = 0; i < argv.length; i++) {
44
45
  const token = argv[i];
45
- if (MODEL_FLAG_PATTERN.test(token))
46
+ if (token === "--model" || token.startsWith("--model="))
46
47
  model = true;
47
- if (EFFORT_FLAG_PATTERN.test(token))
48
- effort = true;
49
- if (CODEX_CONFIG_FLAG_PATTERN.test(token)) {
50
- const value = argv[i + 1];
51
- if (value?.startsWith(CODEX_MODEL_VALUE_PREFIX))
52
- model = true;
53
- if (value?.startsWith(CODEX_EFFORT_VALUE_PREFIX))
54
- effort = true;
55
- }
56
- if (token.startsWith("--model=") || token.startsWith("-m="))
48
+ if (shortModel && (token === "-m" || token.startsWith("-m=")))
57
49
  model = true;
58
- if (token.startsWith("--effort=") || token.startsWith("--thinking="))
50
+ if (token === "--effort" || token.startsWith("--effort="))
51
+ effort = true;
52
+ if (thinkingAlias && (token === "--thinking" || token.startsWith("--thinking=")))
59
53
  effort = true;
60
- if (token.startsWith("-c=") || token.startsWith("--config=")) {
61
- const value = token.slice(token.indexOf("=") + 1);
62
- if (value.startsWith(CODEX_MODEL_VALUE_PREFIX))
63
- model = true;
64
- if (value.startsWith(CODEX_EFFORT_VALUE_PREFIX))
65
- effort = true;
54
+ if (codexConfig) {
55
+ if (CODEX_CONFIG_FLAG_PATTERN.test(token)) {
56
+ const value = argv[i + 1];
57
+ if (value?.startsWith(CODEX_MODEL_VALUE_PREFIX))
58
+ model = true;
59
+ if (value?.startsWith(CODEX_EFFORT_VALUE_PREFIX))
60
+ effort = true;
61
+ }
62
+ else if (token.startsWith("-c=") || token.startsWith("--config=")) {
63
+ const value = token.slice(token.indexOf("=") + 1);
64
+ if (value.startsWith(CODEX_MODEL_VALUE_PREFIX))
65
+ model = true;
66
+ if (value.startsWith(CODEX_EFFORT_VALUE_PREFIX))
67
+ effort = true;
68
+ }
66
69
  }
67
70
  }
68
71
  return { model, effort };
69
72
  }
73
+ /** True when `argv` already specifies `--output-format` with a value other than `expected`. */
74
+ export function outputFormatConflicts(argv, expected = "stream-json") {
75
+ for (let i = 0; i < argv.length; i++) {
76
+ const token = argv[i];
77
+ if (token === "--output-format") {
78
+ if (argv[i + 1] !== expected)
79
+ return true;
80
+ }
81
+ else if (token?.startsWith("--output-format=") && token.slice("--output-format=".length) !== expected) {
82
+ return true;
83
+ }
84
+ }
85
+ return false;
86
+ }
87
+ /**
88
+ * Parse NDJSON lines into plain JSON objects, tolerating blank, torn, or non-object lines.
89
+ * Returning an array keeps each adapter's loop imperative so TypeScript tracks state narrowing.
90
+ */
91
+ export function parseJsonObjectLines(eventsText) {
92
+ const records = [];
93
+ for (const line of eventsText.split("\n")) {
94
+ const trimmed = line.trim();
95
+ if (!trimmed)
96
+ continue;
97
+ let event;
98
+ try {
99
+ event = JSON.parse(trimmed);
100
+ }
101
+ catch {
102
+ continue;
103
+ }
104
+ if (isPlainObject(event))
105
+ records.push(event);
106
+ }
107
+ return records;
108
+ }
70
109
  const PLACEHOLDERS = ["$MODEL", "$EFFORT", "$PROMPT_FILE", "$SYSTEM_PROMPT_FILE"];
71
110
  /**
72
111
  * Expand `$MODEL`/`$EFFORT`/`$PROMPT_FILE`/`$SYSTEM_PROMPT_FILE` wherever they appear in argv
73
- * (D4). Returns which placeholders were actually found, so a harness knows whether it still needs
74
- * to *append* the corresponding flag (a placeholder present ⇒ never append; absent ⇒ append per
75
- * the harness's own rule).
76
- *
77
- * Spec 042 D10: a token that still references a placeholder after substitution (its value was
78
- * `undefined`, e.g. `--model $MODEL` on a role with no `model:` configured) is dropped from argv
79
- * entirely rather than reaching the process as a literal `"$MODEL"` string — that literal-string
80
- * failure is exactly what D4's "argv, not a shell string" design exists to prevent, just arriving
81
- * through a different door (a missing value instead of a shell-quoting bug). `dropped` carries the
82
- * original tokens so the caller can turn them into a run-visible warning.
112
+ * (D4). Unresolved placeholder tokens are dropped and returned in `dropped` (spec 042 D10).
83
113
  */
84
114
  export function expandPlaceholders(argv, values) {
85
115
  const used = new Set();
@@ -102,8 +132,7 @@ export function expandPlaceholders(argv, values) {
102
132
  }
103
133
  return { argv: expanded, used, dropped };
104
134
  }
105
- /** Turn `expandPlaceholders`'s `dropped` tokens into run-visible warning strings (spec 042 D10),
106
- * shared so every structured harness reports the same wording. */
135
+ /** Turn `expandPlaceholders`'s `dropped` tokens into run-visible warning strings (spec 042 D10). */
107
136
  export function formatDroppedPlaceholderWarnings(dropped) {
108
137
  return dropped.map((token) => `Dropped argv token "${token}": it references a placeholder with no value configured for this run (e.g. no "model:" set for $MODEL).`);
109
138
  }
@@ -101,5 +101,6 @@ export async function reconcileExternalRun(record, settle, active) {
101
101
  maxWallTimeSec,
102
102
  mutates: record.mutates,
103
103
  workspaceBaseline: record.workspaceBaseline,
104
+ expectedResumeSessionId: record.expectedResumeSessionId,
104
105
  }, (settleInput, options) => (active() ? settle(record.runId, settleInput, options) : Promise.resolve()), { announce: record.terminationReason !== "cancelled" });
105
106
  }