@prestyj/cli 5.33.0 → 5.35.0

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 (327) hide show
  1. package/README.md +18 -18
  2. package/assets/motion/skills/source-ingest/SKILL.md +1 -1
  3. package/dist/app-sidecar/app-settings.js +3 -0
  4. package/dist/app-sidecar/app-settings.js.map +1 -1
  5. package/dist/app-sidecar/autopilot-runner.d.ts +7 -0
  6. package/dist/app-sidecar/autopilot-runner.js +79 -19
  7. package/dist/app-sidecar/autopilot-runner.js.map +1 -1
  8. package/dist/app-sidecar/live-preview/dev-url.d.ts +32 -0
  9. package/dist/app-sidecar/live-preview/dev-url.js +97 -0
  10. package/dist/app-sidecar/live-preview/dev-url.js.map +1 -0
  11. package/dist/app-sidecar/live-preview/frame-server.d.ts +31 -0
  12. package/dist/app-sidecar/live-preview/frame-server.js +193 -0
  13. package/dist/app-sidecar/live-preview/frame-server.js.map +1 -0
  14. package/dist/app-sidecar/live-preview/manager.d.ts +44 -0
  15. package/dist/app-sidecar/live-preview/manager.js +215 -0
  16. package/dist/app-sidecar/live-preview/manager.js.map +1 -0
  17. package/dist/app-sidecar/live-preview/proxy.d.ts +30 -0
  18. package/dist/app-sidecar/live-preview/proxy.js +235 -0
  19. package/dist/app-sidecar/live-preview/proxy.js.map +1 -0
  20. package/dist/app-sidecar/live-preview/routes.d.ts +4 -0
  21. package/dist/app-sidecar/live-preview/routes.js +52 -0
  22. package/dist/app-sidecar/live-preview/routes.js.map +1 -0
  23. package/dist/app-sidecar/live-preview/servers.d.ts +36 -0
  24. package/dist/app-sidecar/live-preview/servers.js +228 -0
  25. package/dist/app-sidecar/live-preview/servers.js.map +1 -0
  26. package/dist/app-sidecar/mcp-routes.js +9 -0
  27. package/dist/app-sidecar/mcp-routes.js.map +1 -1
  28. package/dist/app-sidecar/mcp-shell-command.d.ts +36 -0
  29. package/dist/app-sidecar/mcp-shell-command.js +302 -0
  30. package/dist/app-sidecar/mcp-shell-command.js.map +1 -0
  31. package/dist/app-sidecar/mcp-sync.d.ts +18 -0
  32. package/dist/app-sidecar/mcp-sync.js +38 -0
  33. package/dist/app-sidecar/mcp-sync.js.map +1 -0
  34. package/dist/app-sidecar/nolan-context.js +1 -1
  35. package/dist/app-sidecar/nolan-context.js.map +1 -1
  36. package/dist/app-sidecar/prompt-routes.js +31 -26
  37. package/dist/app-sidecar/prompt-routes.js.map +1 -1
  38. package/dist/app-sidecar/route-context.d.ts +3 -1
  39. package/dist/app-sidecar/run-control-routes.js +8 -1
  40. package/dist/app-sidecar/run-control-routes.js.map +1 -1
  41. package/dist/app-sidecar/shell-routes.js +7 -0
  42. package/dist/app-sidecar/shell-routes.js.map +1 -1
  43. package/dist/app-sidecar/task-routes.js +1 -1
  44. package/dist/app-sidecar/task-routes.js.map +1 -1
  45. package/dist/app-sidecar/workspace-routes.js +35 -37
  46. package/dist/app-sidecar/workspace-routes.js.map +1 -1
  47. package/dist/app-sidecar.js +136 -38
  48. package/dist/app-sidecar.js.map +1 -1
  49. package/dist/cli/mcp.js +19 -5
  50. package/dist/cli/mcp.js.map +1 -1
  51. package/dist/cli/shared.js +4 -0
  52. package/dist/cli/shared.js.map +1 -1
  53. package/dist/cli.js +16 -4
  54. package/dist/cli.js.map +1 -1
  55. package/dist/config.js +2 -0
  56. package/dist/config.js.map +1 -1
  57. package/dist/core/agent-session/mcp-tools.d.ts +20 -1
  58. package/dist/core/agent-session/mcp-tools.js +34 -2
  59. package/dist/core/agent-session/mcp-tools.js.map +1 -1
  60. package/dist/core/agent-session/verification-tracker.js +2 -10
  61. package/dist/core/agent-session/verification-tracker.js.map +1 -1
  62. package/dist/core/agent-session.d.ts +30 -0
  63. package/dist/core/agent-session.js +205 -14
  64. package/dist/core/agent-session.js.map +1 -1
  65. package/dist/core/agents.d.ts +2 -12
  66. package/dist/core/agents.js +5 -1
  67. package/dist/core/agents.js.map +1 -1
  68. package/dist/core/ask-user.d.ts +2 -0
  69. package/dist/core/ask-user.js +8 -1
  70. package/dist/core/ask-user.js.map +1 -1
  71. package/dist/core/autopilot-cycle.js +1 -1
  72. package/dist/core/autopilot-cycle.js.map +1 -1
  73. package/dist/core/autopilot-gate.js +3 -3
  74. package/dist/core/autopilot-gate.js.map +1 -1
  75. package/dist/core/checklist-items.d.ts +2 -2
  76. package/dist/core/checklist-items.js +14 -2
  77. package/dist/core/checklist-items.js.map +1 -1
  78. package/dist/core/checklist-prompt.d.ts +1 -1
  79. package/dist/core/checklist-prompt.js +1 -1
  80. package/dist/core/claude-code/complete.d.ts +2 -0
  81. package/dist/core/claude-code/complete.js +3 -0
  82. package/dist/core/claude-code/complete.js.map +1 -1
  83. package/dist/core/claude-code/transcripts.d.ts +29 -0
  84. package/dist/core/claude-code/transcripts.js +117 -0
  85. package/dist/core/claude-code/transcripts.js.map +1 -0
  86. package/dist/core/codex-request-shape.js +1 -1
  87. package/dist/core/compaction/compactor.d.ts +2 -0
  88. package/dist/core/compaction/compactor.js +7 -3
  89. package/dist/core/compaction/compactor.js.map +1 -1
  90. package/dist/core/compaction/plan-step-policy.d.ts +1 -1
  91. package/dist/core/compaction/plan-step-policy.js +1 -1
  92. package/dist/core/compaction/policy.js +3 -2
  93. package/dist/core/compaction/policy.js.map +1 -1
  94. package/dist/core/compaction/tool-result-pruner.d.ts +12 -2
  95. package/dist/core/compaction/tool-result-pruner.js +14 -3
  96. package/dist/core/compaction/tool-result-pruner.js.map +1 -1
  97. package/dist/core/extensions/plugin-bundles.d.ts +0 -9
  98. package/dist/core/extensions/plugin-bundles.js +0 -185
  99. package/dist/core/extensions/plugin-bundles.js.map +1 -1
  100. package/dist/core/goals-store.d.ts +0 -2
  101. package/dist/core/goals-store.js +0 -5
  102. package/dist/core/goals-store.js.map +1 -1
  103. package/dist/core/live-preview.d.ts +24 -0
  104. package/dist/core/live-preview.js +76 -0
  105. package/dist/core/live-preview.js.map +1 -0
  106. package/dist/core/mcp/client.d.ts +19 -0
  107. package/dist/core/mcp/client.js +60 -5
  108. package/dist/core/mcp/client.js.map +1 -1
  109. package/dist/core/mcp/deferred-catalog.d.ts +7 -1
  110. package/dist/core/mcp/deferred-catalog.js +6 -2
  111. package/dist/core/mcp/deferred-catalog.js.map +1 -1
  112. package/dist/core/mcp/index.d.ts +1 -1
  113. package/dist/core/mcp/index.js.map +1 -1
  114. package/dist/core/mcp/oauth-provider.d.ts +7 -1
  115. package/dist/core/mcp/oauth-provider.js +11 -4
  116. package/dist/core/mcp/oauth-provider.js.map +1 -1
  117. package/dist/core/mcp/oauth-store.d.ts +6 -0
  118. package/dist/core/mcp/oauth-store.js +14 -0
  119. package/dist/core/mcp/oauth-store.js.map +1 -1
  120. package/dist/core/mcp/parse-add-command.d.ts +29 -3
  121. package/dist/core/mcp/parse-add-command.js +196 -26
  122. package/dist/core/mcp/parse-add-command.js.map +1 -1
  123. package/dist/core/mcp/store.d.ts +16 -0
  124. package/dist/core/mcp/store.js +28 -0
  125. package/dist/core/mcp/store.js.map +1 -1
  126. package/dist/core/mcp/types.d.ts +9 -0
  127. package/dist/core/nolan-ask-answer.d.ts +24 -0
  128. package/dist/core/nolan-ask-answer.js +96 -0
  129. package/dist/core/nolan-ask-answer.js.map +1 -0
  130. package/dist/core/nolan-context.d.ts +21 -1
  131. package/dist/core/nolan-context.js +55 -0
  132. package/dist/core/nolan-context.js.map +1 -1
  133. package/dist/core/nolan-prompt.d.ts +1 -1
  134. package/dist/core/nolan-prompt.js +14 -7
  135. package/dist/core/nolan-prompt.js.map +1 -1
  136. package/dist/core/opencode-catalog-store.d.ts +20 -0
  137. package/dist/core/opencode-catalog-store.js +82 -0
  138. package/dist/core/opencode-catalog-store.js.map +1 -0
  139. package/dist/core/package-cooldown.d.ts +0 -2
  140. package/dist/core/package-cooldown.js +0 -4
  141. package/dist/core/package-cooldown.js.map +1 -1
  142. package/dist/core/process-manager.d.ts +1 -1
  143. package/dist/core/process-manager.js +1 -1
  144. package/dist/core/prompt-commands.js +83 -44
  145. package/dist/core/prompt-commands.js.map +1 -1
  146. package/dist/core/runtime-mode.d.ts +0 -8
  147. package/dist/core/runtime-mode.js.map +1 -1
  148. package/dist/core/session-history.d.ts +2 -1
  149. package/dist/core/session-history.js +20 -4
  150. package/dist/core/session-history.js.map +1 -1
  151. package/dist/core/session-manager.d.ts +5 -0
  152. package/dist/core/session-manager.js +12 -7
  153. package/dist/core/session-manager.js.map +1 -1
  154. package/dist/core/session-storage.d.ts +0 -2
  155. package/dist/core/session-storage.js +0 -2
  156. package/dist/core/session-storage.js.map +1 -1
  157. package/dist/core/settings-manager.d.ts +2 -0
  158. package/dist/core/settings-manager.js +3 -1
  159. package/dist/core/settings-manager.js.map +1 -1
  160. package/dist/core/shell-path.d.ts +2 -0
  161. package/dist/core/shell-path.js +10 -1
  162. package/dist/core/shell-path.js.map +1 -1
  163. package/dist/core/skills.d.ts +2 -0
  164. package/dist/core/skills.js +5 -0
  165. package/dist/core/skills.js.map +1 -1
  166. package/dist/core/subagent-policy.js +1 -1
  167. package/dist/core/subagent-policy.js.map +1 -1
  168. package/dist/core/task-store.d.ts +0 -1
  169. package/dist/core/task-store.js +0 -3
  170. package/dist/core/task-store.js.map +1 -1
  171. package/dist/core/trophies/catalog-more.js +5 -5
  172. package/dist/core/trophies/catalog-more.js.map +1 -1
  173. package/dist/core/trophies/catalog.js +3 -3
  174. package/dist/core/trophies/catalog.js.map +1 -1
  175. package/dist/core/trophies/engine.js +1 -1
  176. package/dist/core/trophies/engine.js.map +1 -1
  177. package/dist/modes/acp-mode.d.ts +1 -1
  178. package/dist/modes/acp-mode.js +1 -1
  179. package/dist/modes/acp-mode.js.map +1 -1
  180. package/dist/motion-agent/motion-agent.d.ts +1 -1
  181. package/dist/motion-agent/motion-agent.js +1 -1
  182. package/dist/motion-agent/motion-agent.js.map +1 -1
  183. package/dist/motion-agent/motion-review.d.ts +0 -75
  184. package/dist/motion-agent/motion-review.js +0 -189
  185. package/dist/motion-agent/motion-review.js.map +1 -1
  186. package/dist/system-prompt.d.ts +5 -1
  187. package/dist/system-prompt.js +16 -8
  188. package/dist/system-prompt.js.map +1 -1
  189. package/dist/test-support/system-tools.d.ts +6 -0
  190. package/dist/test-support/system-tools.js +36 -0
  191. package/dist/test-support/system-tools.js.map +1 -0
  192. package/dist/tools/ask-user.js +3 -2
  193. package/dist/tools/ask-user.js.map +1 -1
  194. package/dist/tools/bash.d.ts +2 -2
  195. package/dist/tools/bash.js +363 -358
  196. package/dist/tools/bash.js.map +1 -1
  197. package/dist/tools/browser-api.d.ts +27 -0
  198. package/dist/tools/browser-api.js +449 -0
  199. package/dist/tools/browser-api.js.map +1 -0
  200. package/dist/tools/browser-sandbox.d.ts +16 -0
  201. package/dist/tools/browser-sandbox.js +158 -0
  202. package/dist/tools/browser-sandbox.js.map +1 -0
  203. package/dist/tools/browser-session.d.ts +69 -0
  204. package/dist/tools/browser-session.js +220 -0
  205. package/dist/tools/browser-session.js.map +1 -0
  206. package/dist/tools/browser-snapshot.d.ts +19 -0
  207. package/dist/tools/browser-snapshot.js +109 -0
  208. package/dist/tools/browser-snapshot.js.map +1 -0
  209. package/dist/tools/browser.d.ts +11 -0
  210. package/dist/tools/browser.js +106 -0
  211. package/dist/tools/browser.js.map +1 -0
  212. package/dist/tools/goals.d.ts +3 -3
  213. package/dist/tools/html-extract.d.ts +1 -1
  214. package/dist/tools/html-extract.js +1 -1
  215. package/dist/tools/index.d.ts +4 -1
  216. package/dist/tools/index.js +6 -3
  217. package/dist/tools/index.js.map +1 -1
  218. package/dist/tools/live-preview.d.ts +21 -0
  219. package/dist/tools/live-preview.js +37 -0
  220. package/dist/tools/live-preview.js.map +1 -0
  221. package/dist/tools/path-utils.d.ts +0 -15
  222. package/dist/tools/path-utils.js +0 -17
  223. package/dist/tools/path-utils.js.map +1 -1
  224. package/dist/tools/prompt-hints.js +3 -2
  225. package/dist/tools/prompt-hints.js.map +1 -1
  226. package/dist/tools/subagent-shared.d.ts +3 -4
  227. package/dist/tools/subagent-shared.js +8 -9
  228. package/dist/tools/subagent-shared.js.map +1 -1
  229. package/dist/tools/tool-tiers.d.ts +1 -1
  230. package/dist/tools/tool-tiers.js +2 -2
  231. package/dist/tools/tool-tiers.js.map +1 -1
  232. package/dist/tools/truncate.d.ts +0 -2
  233. package/dist/tools/truncate.js +0 -2
  234. package/dist/tools/truncate.js.map +1 -1
  235. package/dist/tools/web-fetch.d.ts +7 -1
  236. package/dist/tools/web-fetch.js +15 -4
  237. package/dist/tools/web-fetch.js.map +1 -1
  238. package/dist/ui/App.d.ts +2 -1
  239. package/dist/ui/App.js +0 -1
  240. package/dist/ui/App.js.map +1 -1
  241. package/dist/ui/app-items.d.ts +0 -2
  242. package/dist/ui/app-items.js +0 -2
  243. package/dist/ui/app-items.js.map +1 -1
  244. package/dist/ui/components/ActivityIndicator.d.ts +1 -1
  245. package/dist/ui/components/AnimationContext.d.ts +1 -1
  246. package/dist/ui/components/AssistantMessage.d.ts +1 -1
  247. package/dist/ui/components/BackgroundTasksBar.d.ts +2 -1
  248. package/dist/ui/components/Banner.d.ts +2 -1
  249. package/dist/ui/components/ChatFooterPane.d.ts +2 -1
  250. package/dist/ui/components/ChatInputStack.d.ts +1 -1
  251. package/dist/ui/components/ChatLayout.d.ts +4 -4
  252. package/dist/ui/components/ChatLivePane.d.ts +1 -1
  253. package/dist/ui/components/ChatScreen.d.ts +1 -1
  254. package/dist/ui/components/ChatStatusRow.d.ts +1 -1
  255. package/dist/ui/components/CompactionNotice.d.ts +3 -2
  256. package/dist/ui/components/DiffFrame.d.ts +1 -1
  257. package/dist/ui/components/DiffView.d.ts +2 -1
  258. package/dist/ui/components/Footer.d.ts +2 -1
  259. package/dist/ui/components/Footer.js +4 -4
  260. package/dist/ui/components/Footer.js.map +1 -1
  261. package/dist/ui/components/FooterStatusRow.d.ts +2 -1
  262. package/dist/ui/components/FullScreenOverlayRouter.d.ts +2 -1
  263. package/dist/ui/components/GoalOverlay.d.ts +2 -1
  264. package/dist/ui/components/GoalStatusBar.d.ts +2 -1
  265. package/dist/ui/components/IdealHookMessage.d.ts +1 -1
  266. package/dist/ui/components/InputArea.d.ts +1 -1
  267. package/dist/ui/components/LiveToolPanel.d.ts +2 -1
  268. package/dist/ui/components/Markdown.d.ts +2 -2
  269. package/dist/ui/components/ModelSelector.d.ts +2 -1
  270. package/dist/ui/components/ModelSelector.js +2 -0
  271. package/dist/ui/components/ModelSelector.js.map +1 -1
  272. package/dist/ui/components/Overlay.d.ts +1 -1
  273. package/dist/ui/components/PixelOverlay.d.ts +2 -1
  274. package/dist/ui/components/PlanModeLogo.d.ts +2 -1
  275. package/dist/ui/components/PlanOverlay.d.ts +3 -2
  276. package/dist/ui/components/QueueIndicator.d.ts +2 -1
  277. package/dist/ui/components/RewindOverlay.d.ts +2 -1
  278. package/dist/ui/components/SelectList.d.ts +2 -1
  279. package/dist/ui/components/ServerToolExecution.d.ts +2 -1
  280. package/dist/ui/components/SessionSelector.d.ts +2 -1
  281. package/dist/ui/components/SessionSummary.d.ts +2 -1
  282. package/dist/ui/components/SettingsSelector.d.ts +2 -1
  283. package/dist/ui/components/SkillsOverlay.d.ts +2 -1
  284. package/dist/ui/components/SlashCommandMenu.d.ts +2 -1
  285. package/dist/ui/components/SlashStyledSelectList.d.ts +2 -1
  286. package/dist/ui/components/Spinner.d.ts +2 -1
  287. package/dist/ui/components/StreamingArea.d.ts +1 -1
  288. package/dist/ui/components/SubAgentPanel.d.ts +2 -1
  289. package/dist/ui/components/TaskOverlay.d.ts +2 -1
  290. package/dist/ui/components/TaskPickerMenu.d.ts +2 -1
  291. package/dist/ui/components/ThemeSelector.d.ts +2 -1
  292. package/dist/ui/components/ThinkingBlock.d.ts +1 -1
  293. package/dist/ui/components/ToolExecution.d.ts +2 -1
  294. package/dist/ui/components/ToolGroupExecution.d.ts +2 -1
  295. package/dist/ui/components/TranscriptViewport.d.ts +1 -1
  296. package/dist/ui/components/UserMessage.d.ts +2 -1
  297. package/dist/ui/constants/figures.d.ts +0 -8
  298. package/dist/ui/constants/figures.js +0 -8
  299. package/dist/ui/constants/figures.js.map +1 -1
  300. package/dist/ui/layout-decisions.d.ts +0 -5
  301. package/dist/ui/layout-decisions.js +1 -10
  302. package/dist/ui/layout-decisions.js.map +1 -1
  303. package/dist/ui/terminal-history-status-renderers.d.ts +0 -1
  304. package/dist/ui/terminal-history-status-renderers.js +0 -12
  305. package/dist/ui/terminal-history-status-renderers.js.map +1 -1
  306. package/dist/ui/tool-line-summary.js +1 -0
  307. package/dist/ui/tool-line-summary.js.map +1 -1
  308. package/dist/ui/transcript/MiscRows.d.ts +8 -7
  309. package/dist/ui/transcript/StatusRow.d.ts +1 -1
  310. package/dist/ui/transcript/ToolRows.d.ts +7 -6
  311. package/dist/ui/transcript/TranscriptItemFrame.d.ts +1 -1
  312. package/dist/ui/transcript/presentation.d.ts +1 -2
  313. package/dist/ui/transcript/presentation.js +0 -4
  314. package/dist/ui/transcript/presentation.js.map +1 -1
  315. package/dist/utils/image.d.ts +0 -4
  316. package/dist/utils/image.js +0 -10
  317. package/dist/utils/image.js.map +1 -1
  318. package/dist/web.d.ts +5 -0
  319. package/dist/web.js +5 -0
  320. package/dist/web.js.map +1 -0
  321. package/package.json +13 -5
  322. package/dist/motion-agent/motion-review-gate.d.ts +0 -48
  323. package/dist/motion-agent/motion-review-gate.js +0 -88
  324. package/dist/motion-agent/motion-review-gate.js.map +0 -1
  325. package/dist/tools/screenshot.d.ts +0 -24
  326. package/dist/tools/screenshot.js +0 -161
  327. package/dist/tools/screenshot.js.map +0 -1
@@ -27,8 +27,8 @@ function sandboxAwareEnv(sandboxed, cooldown = {}) {
27
27
  return sandboxed ? { ...env, ...SANDBOX_ENV_PATCH } : env;
28
28
  }
29
29
  const DEFAULT_TIMEOUT = 120_000; // 120 seconds
30
- /** Host-authored rejection: no process started, so this is not a failed check. */
31
- export const REVIEW_REJECTED_BEFORE_START = "Error: review requires a local, non-persistent foreground verification check. Pass only the check in command; do not combine it with edits or diff inspection. Nothing was run.";
30
+ /** Appended when `review` was set on a command that cannot carry one; the command itself still ran. */
31
+ export const REVIEW_SKIPPED_NOTE = "Review skipped: it runs only after a command that is just the final check, in the foreground. The command above ran normally.";
32
32
  const AUTO_BACKGROUND_RE = /^Still running after \d+(?:\.\d+)?s, so it was moved to the background\b/;
33
33
  /**
34
34
  * Background process id when a bash result reports that a foreground command
@@ -182,380 +182,385 @@ getPackageCooldownDays = () => 2) {
182
182
  ? "Run a Windows cmd.exe command (no bash on this system) in the project root. Use cmd " +
183
183
  "syntax (dir, findstr, type); POSIX commands and $(...) fail. Output tail is kept."
184
184
  : "Run a non-interactive bash command (TERM=dumb, pipefail) in the project root.";
185
- return {
186
- name: "bash",
187
- description: description +
188
- " Servers/watchers/REPLs: run_in_background + wake.pattern, then task_output wait_ms; " +
189
- // "Never by name or pattern" moved here from the lean skill, which only
190
- // loads for perf work: a pattern kill took down the host daemon and every
191
- // sibling session.
192
- "never `&`, nohup or sleep. Leave servers running. Kill by exact PID, never by name or pattern (pkill, killall, taskkill /IM): you run inside a host process.",
193
- parameters: BashParams,
194
- executionMode: "sequential",
195
- async execute({ command, timeout: timeoutMs, run_in_background, persist, wake, review }, context) {
196
- const goalModeRestriction = goalModeBashRestriction(getActiveGoalMode(goalModeRef), run_in_background === true);
197
- if (goalModeRestriction) {
198
- return goalModeRestriction;
199
- }
200
- if (review &&
201
- (persist ||
202
- run_in_background ||
203
- ops !== localOperations ||
204
- !classifyVerificationCommand(command).accepted)) {
205
- return REVIEW_REJECTED_BEFORE_START;
206
- }
207
- if (wake && !run_in_background) {
208
- return "Error: wake conditions require run_in_background=true — there is nothing to watch on a foreground call.";
209
- }
210
- let wakeRules;
211
- if (wake?.pattern) {
212
- try {
213
- // No flags: lastIndex-free exec/test keeps the watcher's scans pure.
214
- wakeRules = { pattern: new RegExp(wake.pattern) };
215
- }
216
- catch (error) {
217
- return `Error: wake.pattern is not a valid regex (${error.message}). Fix the pattern and retry.`;
218
- }
219
- }
220
- if (wake?.silence_seconds) {
221
- wakeRules = { ...wakeRules, silenceMs: wake.silence_seconds * 1000 };
222
- }
223
- // A long sleep-only foreground call while something runs in the
224
- // background is a guessed wait: too short wastes a turn, too long wastes
225
- // wall-clock. Redirect rather than run it — descriptions alone do not
226
- // reliably beat the habit. Brief sleeps stay allowed, because letting a
227
- // just-started dev server settle before curling it is legitimate and no
228
- // exit is ever coming for it.
229
- const napSeconds = run_in_background ? null : sleepOnlySeconds(command);
230
- if (napSeconds !== null && napSeconds >= GUESSED_WAIT_SECONDS) {
231
- const running = processManager.list().filter((proc) => proc.exitCode === null);
232
- if (running.length > 0) {
233
- const ids = running.map((proc) => proc.id).join(", ");
234
- return (`Error: refusing to sleep ${napSeconds}s while ${running.length} background ` +
235
- `process(es) are running (${ids}). Sleeping guesses at a finish time. Call ` +
236
- `task_output with wait_ms instead \u2014 it returns on exit or a declared wake. ` +
237
- `For something that never exits, such as a dev server, run it with a wake ` +
238
- `pattern and wait for that line.`);
239
- }
240
- }
241
- if (isPlanModeActive(planModeRef) && !isReadOnlyCommand(command)) {
242
- return planModeRestriction("bash");
243
- }
244
- // Catastrophic-command guard — enforced in code, before every execution
245
- // path (persistent shell, background, and normal spawn).
246
- const catastrophic = isCatastrophicCommand(command, cwd);
247
- if (catastrophic) {
248
- return `Error: ${catastrophic}`;
249
- }
250
- // Destructive-git guard — refuses reset --hard / checkout -- / restore /
251
- // clean -f / stash drop / branch -D / force push when work would be lost.
252
- // A persist:true call runs wherever the session shell last cd'd to.
253
- const liveShell = persist && process.platform !== "win32" ? sessionShell : null;
254
- const gitBlocked = await checkDestructiveGit(command, {
255
- cwd,
256
- resolveCwd: liveShell && !liveShell.isBusy
257
- ? async () => (await liveShell.run("pwd", 2_000, context.signal)).output.trim() || null
258
- : undefined,
259
- });
260
- if (gitBlocked) {
261
- return `Error: ${gitBlocked}`;
185
+ const runBash = async ({ command, timeout: timeoutMs, run_in_background, persist, wake, review }, context) => {
186
+ const goalModeRestriction = goalModeBashRestriction(getActiveGoalMode(goalModeRef), run_in_background === true);
187
+ if (goalModeRestriction) {
188
+ return goalModeRestriction;
189
+ }
190
+ if (wake && !run_in_background) {
191
+ return "Error: wake conditions require run_in_background=true — there is nothing to watch on a foreground call.";
192
+ }
193
+ let wakeRules;
194
+ if (wake?.pattern) {
195
+ try {
196
+ // No flags: lastIndex-free exec/test keeps the watcher's scans pure.
197
+ wakeRules = { pattern: new RegExp(wake.pattern) };
262
198
  }
263
- // Shell-threat guard — pipe-to-shell, reverse shells, secret exfiltration,
264
- // lookalike hosts and terminal-escape tricks (core/shell-threats.ts).
265
- const threatBlocked = shellThreatBlockMessage(command);
266
- if (threatBlocked) {
267
- return `Error: ${threatBlocked}`;
199
+ catch (error) {
200
+ return `Error: wake.pattern is not a valid regex (${error.message}). Fix the pattern and retry.`;
268
201
  }
269
- // Package-install guard: known malware (local feed + version-aware OSV),
270
- // lockfile contents, provenance downgrade, release age and precise
271
- // typosquats. A catch is a block; network only for installs, fail-open.
272
- const cooldownDays = getPackageCooldownDays();
273
- // Version detection starts now, in parallel with the check (shared, once per process).
274
- const install = mayInstall(command);
275
- const versionsReady = install
276
- ? detectMentionedVersions(command, cwd)
277
- : Promise.resolve({});
278
- const packageThreats = install
279
- ? await checkPackageInstall(command, { signal: context.signal, cwd, cooldownDays })
280
- : [];
281
- const packageBlocked = packageBlockMessage(packageThreats);
282
- if (packageBlocked) {
283
- // `details` carries the refused packages to the session, which records
284
- // them in the project's "don't install" list (core/blocked-packages-file.ts).
285
- const blocked = packageThreats.flatMap((t) => t.blocked ?? []);
286
- return {
287
- content: `Error: ${packageBlocked}`,
288
- ...(blocked.length > 0 ? { details: { safetyBlock: { packages: blocked } } } : {}),
289
- };
202
+ }
203
+ if (wake?.silence_seconds) {
204
+ wakeRules = { ...wakeRules, silenceMs: wake.silence_seconds * 1000 };
205
+ }
206
+ // A long sleep-only foreground call while something runs in the
207
+ // background is a guessed wait: too short wastes a turn, too long wastes
208
+ // wall-clock. Redirect rather than run it — descriptions alone do not
209
+ // reliably beat the habit. Brief sleeps stay allowed, because letting a
210
+ // just-started dev server settle before curling it is legitimate and no
211
+ // exit is ever coming for it.
212
+ const napSeconds = run_in_background ? null : sleepOnlySeconds(command);
213
+ if (napSeconds !== null && napSeconds >= GUESSED_WAIT_SECONDS) {
214
+ const running = processManager.list().filter((proc) => proc.exitCode === null);
215
+ if (running.length > 0) {
216
+ const ids = running.map((proc) => proc.id).join(", ");
217
+ return (`Error: refusing to sleep ${napSeconds}s while ${running.length} background ` +
218
+ `process(es) are running (${ids}). Sleeping guesses at a finish time. Call ` +
219
+ `task_output with wait_ms instead \u2014 it returns on exit or a declared wake. ` +
220
+ `For something that never exits, such as a dev server, run it with a wake ` +
221
+ `pattern and wait for that line.`);
290
222
  }
291
- // Native release-age cooldown for every install (transitive deps too).
292
- const versions = await versionsReady;
293
- const cooldownEnv = install
294
- ? packageCooldownEnv(command, { days: cooldownDays, now: Date.now(), cwd, versions })
295
- : {};
296
- // bun has no env setting: the cooldown goes in as a flag.
297
- const runCommand = install
298
- ? bunCooldownCommand(command, cooldownDays, versions.bun ?? null)
299
- : command;
300
- // Network allowlist — defence in depth only. Recognises the common egress
301
- // command shapes; an unrecognised command is never blocked (see
302
- // core/network-guard.ts for why this is not a sandbox).
303
- const networkBlocked = checkCommandPolicy(command, getNetworkPolicy);
304
- if (networkBlocked) {
305
- return `Error: ${networkBlocked}`;
223
+ }
224
+ if (isPlanModeActive(planModeRef) && !isReadOnlyCommand(command)) {
225
+ return planModeRestriction("bash");
226
+ }
227
+ // Catastrophic-command guard — enforced in code, before every execution
228
+ // path (persistent shell, background, and normal spawn).
229
+ const catastrophic = isCatastrophicCommand(command, cwd);
230
+ if (catastrophic) {
231
+ return `Error: ${catastrophic}`;
232
+ }
233
+ // Destructive-git guard — refuses reset --hard / checkout -- / restore /
234
+ // clean -f / stash drop / branch -D / force push when work would be lost.
235
+ // A persist:true call runs wherever the session shell last cd'd to.
236
+ const liveShell = persist && process.platform !== "win32" ? sessionShell : null;
237
+ const gitBlocked = await checkDestructiveGit(command, {
238
+ cwd,
239
+ resolveCwd: liveShell && !liveShell.isBusy
240
+ ? async () => (await liveShell.run("pwd", 2_000, context.signal)).output.trim() || null
241
+ : undefined,
242
+ });
243
+ if (gitBlocked) {
244
+ return `Error: ${gitBlocked}`;
245
+ }
246
+ // Shell-threat guard — pipe-to-shell, reverse shells, secret exfiltration,
247
+ // lookalike hosts and terminal-escape tricks (core/shell-threats.ts).
248
+ const threatBlocked = shellThreatBlockMessage(command);
249
+ if (threatBlocked) {
250
+ return `Error: ${threatBlocked}`;
251
+ }
252
+ // Package-install guard: known malware (local feed + version-aware OSV),
253
+ // lockfile contents, provenance downgrade, release age and precise
254
+ // typosquats. A catch is a block; network only for installs, fail-open.
255
+ const cooldownDays = getPackageCooldownDays();
256
+ // Version detection starts now, in parallel with the check (shared, once per process).
257
+ const install = mayInstall(command);
258
+ const versionsReady = install
259
+ ? detectMentionedVersions(command, cwd)
260
+ : Promise.resolve({});
261
+ const packageThreats = install
262
+ ? await checkPackageInstall(command, { signal: context.signal, cwd, cooldownDays })
263
+ : [];
264
+ const packageBlocked = packageBlockMessage(packageThreats);
265
+ if (packageBlocked) {
266
+ // `details` carries the refused packages to the session, which records
267
+ // them in the project's "don't install" list (core/blocked-packages-file.ts).
268
+ const blocked = packageThreats.flatMap((t) => t.blocked ?? []);
269
+ return {
270
+ content: `Error: ${packageBlocked}`,
271
+ ...(blocked.length > 0 ? { details: { safetyBlock: { packages: blocked } } } : {}),
272
+ };
273
+ }
274
+ // Native release-age cooldown for every install (transitive deps too).
275
+ const versions = await versionsReady;
276
+ const cooldownEnv = install
277
+ ? packageCooldownEnv(command, { days: cooldownDays, now: Date.now(), cwd, versions })
278
+ : {};
279
+ // bun has no env setting: the cooldown goes in as a flag.
280
+ const runCommand = install
281
+ ? bunCooldownCommand(command, cooldownDays, versions.bun ?? null)
282
+ : command;
283
+ // Network allowlist — defence in depth only. Recognises the common egress
284
+ // command shapes; an unrecognised command is never blocked (see
285
+ // core/network-guard.ts for why this is not a sandbox).
286
+ const networkBlocked = checkCommandPolicy(command, getNetworkPolicy);
287
+ if (networkBlocked) {
288
+ return `Error: ${networkBlocked}`;
289
+ }
290
+ const sandboxPolicy = getSandboxPolicy?.() ?? { mode: "off", allowedDomains: [] };
291
+ const prepareLaunch = async (shell) => prepareSandboxLaunch(shell, cwd, sandboxPolicy);
292
+ // Persistent session mode — POSIX only; Windows-without-bash falls through
293
+ // to the normal spawn path (cmd.exe fallback) below.
294
+ if (persist && !run_in_background && !resolveShell(command, shellOpts).isCmdFallback) {
295
+ const sandboxKey = JSON.stringify(sandboxPolicy);
296
+ if (sessionShell && sessionSandboxKey !== sandboxKey) {
297
+ sessionShell.kill();
298
+ sessionShell = null;
306
299
  }
307
- const sandboxPolicy = getSandboxPolicy?.() ?? { mode: "off", allowedDomains: [] };
308
- const prepareLaunch = async (shell) => prepareSandboxLaunch(shell, cwd, sandboxPolicy);
309
- // Persistent session mode — POSIX only; Windows-without-bash falls through
310
- // to the normal spawn path (cmd.exe fallback) below.
311
- if (persist && !run_in_background && !resolveShell(command, shellOpts).isCmdFallback) {
312
- const sandboxKey = JSON.stringify(sandboxPolicy);
313
- if (sessionShell && sessionSandboxKey !== sandboxKey) {
314
- sessionShell.kill();
315
- sessionShell = null;
316
- }
317
- if (!sessionShell) {
318
- try {
319
- const shell = resolveShell("", shellOpts);
320
- const launch = await prepareLaunch({
321
- ...shell,
322
- args: ["--norc", "--noprofile", "-o", "pipefail"],
323
- });
324
- sessionShell = new PersistentShell(cwd,
325
- // Env is fixed at shell start: only pip's (always safe) here;
326
- // the others are scoped per command below.
327
- sandboxAwareEnv(launch.sandboxed, cooldownDays > 0 ? { PIP_UPLOADED_PRIOR_TO: `P${cooldownDays}D` } : {}), MAX_OUTPUT_BYTES, shellOpts, launch);
328
- sessionSandboxKey = sandboxKey;
329
- sessionSandboxed = launch.sandboxed;
330
- }
331
- catch (error) {
332
- return `Error: OS sandbox unavailable; command was not run: ${error.message}`;
333
- }
334
- }
335
- if (context.signal.aborted)
336
- return CANCELLED_BEFORE_START;
337
- const res = await sessionShell.run(scopeCooldown(runCommand, cooldownEnv), timeoutMs ?? DEFAULT_TIMEOUT, context.signal, context.onUpdate
338
- ? (text) => context.onUpdate?.({ type: "bash_progress", output: text, totalBytes: 0 })
339
- : undefined);
340
- const hint = install && res.exitCode !== 0 ? cooldownFailureHint(res.output, cooldownDays) : null;
341
- const output = (hint ? `[${hint}]\n` : "") + (await renderBashOutput(res.output));
342
- const exitCode = res.exitCode === "TIMEOUT"
343
- ? `TIMEOUT (${timeoutMs ?? DEFAULT_TIMEOUT}ms)` +
344
- (res.shellKept
345
- ? " — the command was stopped; the session shell kept its cwd/env"
346
- : "")
347
- : String(res.exitCode);
348
- // The restart note sits right under the exit code so output truncation
349
- // can never drop it.
350
- const restartNote = sessionShell.takeRestartNote();
351
- const note = restartNote ? `${restartNote}\n` : "";
352
- return annotateSandboxDenial(`Exit code: ${exitCode}\n${note}${output}`, sessionSandboxed);
353
- }
354
- if (run_in_background) {
355
- let launch;
300
+ if (!sessionShell) {
356
301
  try {
357
- launch = await prepareLaunch(resolveShell(runCommand, shellOpts));
302
+ const shell = resolveShell("", shellOpts);
303
+ const launch = await prepareLaunch({
304
+ ...shell,
305
+ args: ["--norc", "--noprofile", "-o", "pipefail"],
306
+ });
307
+ sessionShell = new PersistentShell(cwd,
308
+ // Env is fixed at shell start: only pip's (always safe) here;
309
+ // the others are scoped per command below.
310
+ sandboxAwareEnv(launch.sandboxed, cooldownDays > 0 ? { PIP_UPLOADED_PRIOR_TO: `P${cooldownDays}D` } : {}), MAX_OUTPUT_BYTES, shellOpts, launch);
311
+ sessionSandboxKey = sandboxKey;
312
+ sessionSandboxed = launch.sandboxed;
358
313
  }
359
314
  catch (error) {
360
315
  return `Error: OS sandbox unavailable; command was not run: ${error.message}`;
361
316
  }
362
- if (context.signal.aborted)
363
- return CANCELLED_BEFORE_START;
364
- const result = await processManager.start(runCommand, cwd, launch, wakeRules, cooldownEnv);
365
- const watchWarnings = backgroundWatchWarnings(command);
366
- return (`Background process started.\n` +
367
- `ID: ${result.id}\n` +
368
- `PID: ${result.pid}\n` +
369
- `Log: ${result.logFile}\n` +
370
- (wakeRules
371
- ? result.wakeArmed
372
- ? `Wake rules armed: ${[
373
- wakeRules.pattern ? `pattern /${wakeRules.pattern.source}/` : null,
374
- wakeRules.silenceMs ? `silence ${wakeRules.silenceMs / 1000}s` : null,
375
- ]
376
- .filter(Boolean)
377
- .join(" + ")}. You will be notified automatically when one fires or the process exits.\n`
378
- : `Wake conditions were NOT armed: this session has no notification path, so nothing will wake you automatically. Poll task_output periodically instead.\n`
379
- : "") +
380
- `Use task_output with id="${result.id}" to read output, ` +
381
- `task_send to type input/answer prompts, task_stop to stop it.` +
382
- watchWarnings.map((warning) => `\nWarning: ${warning}`).join(""));
383
317
  }
384
- const effectiveTimeout = timeoutMs ?? defaultTimeoutMs;
385
- // Cross-platform shell: bash on macOS/Linux, Git Bash on Windows (or
386
- // cmd.exe fallback), wrapped by the OS sandbox before any child starts.
387
- const shell = resolveShell(runCommand, shellOpts);
318
+ if (context.signal.aborted)
319
+ return CANCELLED_BEFORE_START;
320
+ const res = await sessionShell.run(scopeCooldown(runCommand, cooldownEnv), timeoutMs ?? DEFAULT_TIMEOUT, context.signal, context.onUpdate
321
+ ? (text) => context.onUpdate?.({ type: "bash_progress", output: text, totalBytes: 0 })
322
+ : undefined);
323
+ const hint = install && res.exitCode !== 0 ? cooldownFailureHint(res.output, cooldownDays) : null;
324
+ const output = (hint ? `[${hint}]\n` : "") + (await renderBashOutput(res.output));
325
+ const exitCode = res.exitCode === "TIMEOUT"
326
+ ? `TIMEOUT (${timeoutMs ?? DEFAULT_TIMEOUT}ms)` +
327
+ (res.shellKept ? " — the command was stopped; the session shell kept its cwd/env" : "")
328
+ : String(res.exitCode);
329
+ // The restart note sits right under the exit code so output truncation
330
+ // can never drop it.
331
+ const restartNote = sessionShell.takeRestartNote();
332
+ const note = restartNote ? `${restartNote}\n` : "";
333
+ return annotateSandboxDenial(`Exit code: ${exitCode}\n${note}${output}`, sessionSandboxed);
334
+ }
335
+ if (run_in_background) {
388
336
  let launch;
389
337
  try {
390
- launch = await prepareLaunch(shell);
338
+ launch = await prepareLaunch(resolveShell(runCommand, shellOpts));
391
339
  }
392
340
  catch (error) {
393
- return `Exit code: 1\nOS sandbox unavailable; command was not run: ${error.message}`;
341
+ return `Error: OS sandbox unavailable; command was not run: ${error.message}`;
394
342
  }
395
- // Stop may have landed while the launch was being prepared. The abort
396
- // listener below would never fire for an already-aborted signal.
397
343
  if (context.signal.aborted)
398
344
  return CANCELLED_BEFORE_START;
399
- const result = await new Promise((resolve, reject) => {
400
- const child = ops.spawn(launch.file, launch.args, {
401
- cwd,
402
- detached: true,
403
- stdio: ["ignore", "pipe", "pipe"],
404
- env: sandboxAwareEnv(launch.sandboxed, cooldownEnv),
405
- });
406
- const chunks = [];
407
- let totalBytes = 0;
408
- let outputCapped = false;
409
- const onData = (data) => {
410
- if (outputCapped)
411
- return;
412
- totalBytes += data.length;
413
- if (totalBytes > MAX_OUTPUT_BYTES) {
414
- outputCapped = true;
415
- return;
416
- }
417
- chunks.push(data);
418
- // Stream progress to UI for live output display
419
- if (context.onUpdate) {
420
- context.onUpdate({
421
- type: "bash_progress",
422
- output: data.toString("utf-8"),
423
- totalBytes,
424
- });
425
- }
426
- };
427
- child.stdout?.on("data", onData);
428
- child.stderr?.on("data", onData);
429
- let killed = false;
430
- let timedOut = false;
431
- let backgrounded = false;
432
- const startedAt = Date.now();
433
- /**
434
- * Hand a still-running command to the process manager instead of
435
- * killing it, so a slow build or test run keeps going (same process,
436
- * same cwd) while the agent moves on. Only for the default budget: an
437
- * explicit `timeout` is the model saying when to give up. Returns
438
- * false when adoption is not possible, leaving the kill path to run.
439
- */
440
- const moveToBackground = () => {
441
- // The shell already exited and only leftovers hold the pipes; the
442
- // drain path owns that case.
443
- if (timeoutMs !== undefined || child.exitCode !== null || !child.pid)
444
- return false;
445
- child.stdout?.off("data", onData);
446
- child.stderr?.off("data", onData);
447
- let adopted;
448
- try {
449
- adopted = processManager.adopt(child, command, startedAt, Buffer.concat(chunks));
450
- }
451
- catch {
452
- child.stdout?.on("data", onData);
453
- child.stderr?.on("data", onData);
454
- return false;
455
- }
456
- backgrounded = true;
457
- context.signal.removeEventListener("abort", onAbort);
458
- void (async () => {
459
- const soFar = await renderBashOutput(Buffer.concat(chunks).toString("utf-8"));
460
- resolve(`Still running after ${effectiveTimeout / 1000}s, so it was moved to the background ` +
461
- `instead of being stopped. It keeps its working directory and output.\n` +
462
- `ID: ${adopted.id}\n` +
463
- `PID: ${adopted.pid}\n` +
464
- `Log: ${adopted.logFile}\n` +
465
- `You will be notified when it exits or prints a failure. Use task_output with id="${adopted.id}" ` +
466
- `(wait_ms to block until it exits) to read output, task_stop to stop it. ` +
467
- `Pass an explicit timeout to have a command stopped instead.\n` +
468
- (soFar ? `Output so far:\n${soFar}` : "No output so far."));
469
- })();
470
- return true;
471
- };
472
- // Timeout handling
473
- const timer = setTimeout(() => {
474
- if (moveToBackground())
475
- return;
476
- timedOut = true;
477
- killed = true;
478
- if (child.pid)
479
- killProcessTree(child.pid);
480
- }, effectiveTimeout);
481
- // Abort signal handling
482
- const onAbort = () => {
483
- killed = true;
484
- if (child.pid)
485
- killProcessTree(child.pid);
486
- };
487
- context.signal.addEventListener("abort", onAbort, { once: true });
488
- // "close" waits for every holder of the stdout/stderr pipes, and a
489
- // process the command left running (`cmd &`, `nohup cmd`) inherits them,
490
- // so without this the call hangs until the timeout. Once the shell
491
- // itself exits, let late output drain briefly, then stop the leftovers
492
- // and release the pipes so "close" fires.
493
- let leftover;
494
- let drainTimer;
495
- child.on("exit", () => {
496
- drainTimer = setTimeout(() => {
497
- leftover = child.pid && killLeftoverGroup(child.pid) ? "stopped" : "detached";
498
- child.stdout?.destroy();
499
- child.stderr?.destroy();
500
- }, LEFTOVER_DRAIN_MS);
501
- });
502
- child.on("close", async (code) => {
503
- clearTimeout(timer);
504
- clearTimeout(drainTimer);
505
- context.signal.removeEventListener("abort", onAbort);
506
- // The process manager owns an adopted command's exit.
507
- if (backgrounded)
508
- return;
509
- const rawOutput = Buffer.concat(chunks).toString("utf-8");
510
- let output = await renderBashOutput(rawOutput);
511
- if (outputCapped) {
512
- output =
513
- `[Output capped at ${MAX_OUTPUT_BYTES / 1024 / 1024} MB to prevent memory exhaustion]\n` +
514
- output;
515
- }
516
- // Windows without Git Bash: commands ran under cmd.exe, NOT bash. Tell
517
- // the model so it uses cmd syntax (no `ls`/`grep`/pipes/single-quotes)
518
- // and doesn't misread failures as a wrong directory / environment.
519
- if (shell.isCmdFallback) {
520
- output =
521
- "[Ran under Windows cmd.exe — bash is unavailable. Use cmd syntax " +
522
- "(dir, findstr, type); POSIX commands and quoting will fail. " +
523
- "Install Git for Windows to get bash.]\n" +
524
- output;
525
- }
526
- const hint = install && code !== 0 && !killed ? cooldownFailureHint(rawOutput, cooldownDays) : null;
527
- if (hint)
528
- output = `[${hint}]\n` + output;
529
- if (leftover && !killed) {
530
- const fate = leftover === "stopped"
531
- ? "so it was stopped"
532
- : "so its later output was not captured; it may still be running";
533
- output =
534
- `[The command exited, but a process it left running in the background ` +
535
- `(& or nohup) still held its output ${LEFTOVER_DRAIN_MS / 1000}s later, ${fate}. ` +
536
- `Use run_in_background=true for anything that should keep running.]\n` +
537
- output;
538
- }
539
- const exitCode = timedOut
540
- ? `TIMEOUT (${effectiveTimeout}ms)`
541
- : killed
542
- ? "KILLED"
543
- : String(code ?? 1);
544
- resolve(annotateSandboxDenial(`Exit code: ${exitCode}\n${output}`, launch.sandboxed));
545
- });
546
- child.on("error", (err) => {
547
- if (backgrounded)
548
- return;
549
- clearTimeout(timer);
550
- clearTimeout(drainTimer);
551
- context.signal.removeEventListener("abort", onAbort);
552
- reject(new Error(`Exit code: 1\nFailed to spawn: ${err.message}`));
553
- });
345
+ const result = await processManager.start(runCommand, cwd, launch, wakeRules, cooldownEnv);
346
+ const watchWarnings = backgroundWatchWarnings(command);
347
+ return (`Background process started.\n` +
348
+ `ID: ${result.id}\n` +
349
+ `PID: ${result.pid}\n` +
350
+ `Log: ${result.logFile}\n` +
351
+ (wakeRules
352
+ ? result.wakeArmed
353
+ ? `Wake rules armed: ${[
354
+ wakeRules.pattern ? `pattern /${wakeRules.pattern.source}/` : null,
355
+ wakeRules.silenceMs ? `silence ${wakeRules.silenceMs / 1000}s` : null,
356
+ ]
357
+ .filter(Boolean)
358
+ .join(" + ")}. You will be notified automatically when one fires or the process exits.\n`
359
+ : `Wake conditions were NOT armed: this session has no notification path, so nothing will wake you automatically. Poll task_output periodically instead.\n`
360
+ : "") +
361
+ `Use task_output with id="${result.id}" to read output, ` +
362
+ `task_send to type input/answer prompts, task_stop to stop it.` +
363
+ watchWarnings.map((warning) => `\nWarning: ${warning}`).join(""));
364
+ }
365
+ const effectiveTimeout = timeoutMs ?? defaultTimeoutMs;
366
+ // Cross-platform shell: bash on macOS/Linux, Git Bash on Windows (or
367
+ // cmd.exe fallback), wrapped by the OS sandbox before any child starts.
368
+ const shell = resolveShell(runCommand, shellOpts);
369
+ let launch;
370
+ try {
371
+ launch = await prepareLaunch(shell);
372
+ }
373
+ catch (error) {
374
+ return `Exit code: 1\nOS sandbox unavailable; command was not run: ${error.message}`;
375
+ }
376
+ // Stop may have landed while the launch was being prepared. The abort
377
+ // listener below would never fire for an already-aborted signal.
378
+ if (context.signal.aborted)
379
+ return CANCELLED_BEFORE_START;
380
+ const result = await new Promise((resolve, reject) => {
381
+ const child = ops.spawn(launch.file, launch.args, {
382
+ cwd,
383
+ detached: true,
384
+ stdio: ["ignore", "pipe", "pipe"],
385
+ env: sandboxAwareEnv(launch.sandboxed, cooldownEnv),
386
+ });
387
+ const chunks = [];
388
+ let totalBytes = 0;
389
+ let outputCapped = false;
390
+ const onData = (data) => {
391
+ if (outputCapped)
392
+ return;
393
+ totalBytes += data.length;
394
+ if (totalBytes > MAX_OUTPUT_BYTES) {
395
+ outputCapped = true;
396
+ return;
397
+ }
398
+ chunks.push(data);
399
+ // Stream progress to UI for live output display
400
+ if (context.onUpdate) {
401
+ context.onUpdate({
402
+ type: "bash_progress",
403
+ output: data.toString("utf-8"),
404
+ totalBytes,
405
+ });
406
+ }
407
+ };
408
+ child.stdout?.on("data", onData);
409
+ child.stderr?.on("data", onData);
410
+ let killed = false;
411
+ let timedOut = false;
412
+ let backgrounded = false;
413
+ const startedAt = Date.now();
414
+ /**
415
+ * Hand a still-running command to the process manager instead of
416
+ * killing it, so a slow build or test run keeps going (same process,
417
+ * same cwd) while the agent moves on. Only for the default budget: an
418
+ * explicit `timeout` is the model saying when to give up. Returns
419
+ * false when adoption is not possible, leaving the kill path to run.
420
+ */
421
+ const moveToBackground = () => {
422
+ // The shell already exited and only leftovers hold the pipes; the
423
+ // drain path owns that case.
424
+ if (timeoutMs !== undefined || child.exitCode !== null || !child.pid)
425
+ return false;
426
+ child.stdout?.off("data", onData);
427
+ child.stderr?.off("data", onData);
428
+ let adopted;
429
+ try {
430
+ adopted = processManager.adopt(child, command, startedAt, Buffer.concat(chunks));
431
+ }
432
+ catch {
433
+ child.stdout?.on("data", onData);
434
+ child.stderr?.on("data", onData);
435
+ return false;
436
+ }
437
+ backgrounded = true;
438
+ context.signal.removeEventListener("abort", onAbort);
439
+ void (async () => {
440
+ const soFar = await renderBashOutput(Buffer.concat(chunks).toString("utf-8"));
441
+ resolve(`Still running after ${effectiveTimeout / 1000}s, so it was moved to the background ` +
442
+ `instead of being stopped. It keeps its working directory and output.\n` +
443
+ `ID: ${adopted.id}\n` +
444
+ `PID: ${adopted.pid}\n` +
445
+ `Log: ${adopted.logFile}\n` +
446
+ `You will be notified when it exits or prints a failure. Use task_output with id="${adopted.id}" ` +
447
+ `(wait_ms to block until it exits) to read output, task_stop to stop it. ` +
448
+ `Pass an explicit timeout to have a command stopped instead.\n` +
449
+ (soFar ? `Output so far:\n${soFar}` : "No output so far."));
450
+ })();
451
+ return true;
452
+ };
453
+ // Timeout handling
454
+ const timer = setTimeout(() => {
455
+ if (moveToBackground())
456
+ return;
457
+ timedOut = true;
458
+ killed = true;
459
+ if (child.pid)
460
+ killProcessTree(child.pid);
461
+ }, effectiveTimeout);
462
+ // Abort signal handling
463
+ const onAbort = () => {
464
+ killed = true;
465
+ if (child.pid)
466
+ killProcessTree(child.pid);
467
+ };
468
+ context.signal.addEventListener("abort", onAbort, { once: true });
469
+ // "close" waits for every holder of the stdout/stderr pipes, and a
470
+ // process the command left running (`cmd &`, `nohup cmd`) inherits them,
471
+ // so without this the call hangs until the timeout. Once the shell
472
+ // itself exits, let late output drain briefly, then stop the leftovers
473
+ // and release the pipes so "close" fires.
474
+ let leftover;
475
+ let drainTimer;
476
+ child.on("exit", () => {
477
+ drainTimer = setTimeout(() => {
478
+ leftover = child.pid && killLeftoverGroup(child.pid) ? "stopped" : "detached";
479
+ child.stdout?.destroy();
480
+ child.stderr?.destroy();
481
+ }, LEFTOVER_DRAIN_MS);
482
+ });
483
+ child.on("close", async (code) => {
484
+ clearTimeout(timer);
485
+ clearTimeout(drainTimer);
486
+ context.signal.removeEventListener("abort", onAbort);
487
+ // The process manager owns an adopted command's exit.
488
+ if (backgrounded)
489
+ return;
490
+ const rawOutput = Buffer.concat(chunks).toString("utf-8");
491
+ let output = await renderBashOutput(rawOutput);
492
+ if (outputCapped) {
493
+ output =
494
+ `[Output capped at ${MAX_OUTPUT_BYTES / 1024 / 1024} MB to prevent memory exhaustion]\n` +
495
+ output;
496
+ }
497
+ // Windows without Git Bash: commands ran under cmd.exe, NOT bash. Tell
498
+ // the model so it uses cmd syntax (no `ls`/`grep`/pipes/single-quotes)
499
+ // and doesn't misread failures as a wrong directory / environment.
500
+ if (shell.isCmdFallback) {
501
+ output =
502
+ "[Ran under Windows cmd.exe — bash is unavailable. Use cmd syntax " +
503
+ "(dir, findstr, type); POSIX commands and quoting will fail. " +
504
+ "Install Git for Windows to get bash.]\n" +
505
+ output;
506
+ }
507
+ const hint = install && code !== 0 && !killed ? cooldownFailureHint(rawOutput, cooldownDays) : null;
508
+ if (hint)
509
+ output = `[${hint}]\n` + output;
510
+ if (leftover && !killed) {
511
+ const fate = leftover === "stopped"
512
+ ? "so it was stopped"
513
+ : "so its later output was not captured; it may still be running";
514
+ output =
515
+ `[The command exited, but a process it left running in the background ` +
516
+ `(& or nohup) still held its output ${LEFTOVER_DRAIN_MS / 1000}s later, ${fate}. ` +
517
+ `Use run_in_background=true for anything that should keep running.]\n` +
518
+ output;
519
+ }
520
+ const exitCode = timedOut
521
+ ? `TIMEOUT (${effectiveTimeout}ms)`
522
+ : killed
523
+ ? "KILLED"
524
+ : String(code ?? 1);
525
+ resolve(annotateSandboxDenial(`Exit code: ${exitCode}\n${output}`, launch.sandboxed));
526
+ });
527
+ child.on("error", (err) => {
528
+ if (backgrounded)
529
+ return;
530
+ clearTimeout(timer);
531
+ clearTimeout(drainTimer);
532
+ context.signal.removeEventListener("abort", onAbort);
533
+ reject(new Error(`Exit code: 1\nFailed to spawn: ${err.message}`));
554
534
  });
555
- if (!review || context.signal.aborted || !/^Exit code: 0(?:\s|$)/.test(result))
556
- return result;
557
- const inspection = await collectVerificationReview(cwd, context.signal);
558
- return `${result}\n\n--- Independent read-only review ---\n${await renderBashOutput(inspection)}`;
535
+ });
536
+ if (!review || context.signal.aborted || !/^Exit code: 0(?:\s|$)/.test(result))
537
+ return result;
538
+ const inspection = await collectVerificationReview(cwd, context.signal);
539
+ return `${result}\n\n--- Independent read-only review ---\n${await renderBashOutput(inspection)}`;
540
+ };
541
+ return {
542
+ name: "bash",
543
+ description: description +
544
+ " Servers/watchers/REPLs: run_in_background + wake.pattern, then task_output wait_ms; " +
545
+ // "Never by name or pattern" moved here from the lean skill, which only
546
+ // loads for perf work: a pattern kill took down the host daemon and every
547
+ // sibling session.
548
+ "never `&`, nohup or sleep. Leave servers running. Kill by exact PID, never by name or pattern (pkill, killall, taskkill /IM): you run inside a host process.",
549
+ parameters: BashParams,
550
+ executionMode: "sequential",
551
+ async execute(args, context) {
552
+ // Rejecting a review-flagged edit+test command threw the edits away, and the
553
+ // model re-sent them without review every time (24/24 bench cases), so run
554
+ // the command as asked and skip only the review.
555
+ const skipReview = args.review === true &&
556
+ (args.persist === true ||
557
+ args.run_in_background === true ||
558
+ ops !== localOperations ||
559
+ !classifyVerificationCommand(args.command).accepted);
560
+ if (!skipReview)
561
+ return runBash(args, context);
562
+ const result = await runBash({ ...args, review: false }, context);
563
+ return typeof result === "string" ? `${result}\n\n${REVIEW_SKIPPED_NOTE}` : result;
559
564
  },
560
565
  };
561
566
  }