@caupulican/pi-adaptative 0.81.37 → 0.81.39

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 (451) hide show
  1. package/CHANGELOG.md +91 -0
  2. package/README.md +1 -1
  3. package/dist/bundled-resources/extensions/tmux-agent-manager/README.md +18 -1
  4. package/dist/bundled-resources/extensions/tmux-agent-manager/dispatch-grant.d.ts +131 -0
  5. package/dist/bundled-resources/extensions/tmux-agent-manager/dispatch-grant.d.ts.map +1 -0
  6. package/dist/bundled-resources/extensions/tmux-agent-manager/dispatch-grant.js +196 -0
  7. package/dist/bundled-resources/extensions/tmux-agent-manager/dispatch-grant.js.map +1 -0
  8. package/dist/bundled-resources/extensions/tmux-agent-manager/dispatch-grant.ts +308 -0
  9. package/dist/bundled-resources/extensions/tmux-agent-manager/index.d.ts +22 -2
  10. package/dist/bundled-resources/extensions/tmux-agent-manager/index.d.ts.map +1 -1
  11. package/dist/bundled-resources/extensions/tmux-agent-manager/index.js +585 -24
  12. package/dist/bundled-resources/extensions/tmux-agent-manager/index.js.map +1 -1
  13. package/dist/bundled-resources/extensions/tmux-agent-manager/index.ts +749 -27
  14. package/dist/bundled-resources/runtimes/pi-shell-engine/commands/__init__.py +43 -0
  15. package/dist/bundled-resources/runtimes/pi-shell-engine/commands/fs.py +270 -0
  16. package/dist/bundled-resources/runtimes/pi-shell-engine/commands/search.py +252 -0
  17. package/dist/bundled-resources/runtimes/pi-shell-engine/commands/strings.py +399 -0
  18. package/dist/bundled-resources/runtimes/pi-shell-engine/commands/text.py +575 -0
  19. package/dist/bundled-resources/runtimes/pi-shell-engine/context.py +52 -0
  20. package/dist/bundled-resources/runtimes/pi-shell-engine/errors.py +49 -0
  21. package/dist/bundled-resources/runtimes/pi-shell-engine/exec.py +734 -0
  22. package/dist/bundled-resources/runtimes/pi-shell-engine/expand.py +238 -0
  23. package/dist/bundled-resources/runtimes/pi-shell-engine/main.py +132 -0
  24. package/dist/bundled-resources/runtimes/pi-shell-engine/nodes.py +116 -0
  25. package/dist/bundled-resources/runtimes/pi-shell-engine/parser.py +287 -0
  26. package/dist/bundled-resources/runtimes/pi-shell-engine/proc.py +137 -0
  27. package/dist/bundled-resources/runtimes/pi-shell-engine/state.py +100 -0
  28. package/dist/bundled-resources/runtimes/pi-shell-engine/tokens.py +579 -0
  29. package/dist/bundled-resources/skills/tool-call-repair/SKILL.md +19 -9
  30. package/dist/bundled-resources/skills/tool-call-repair/references/failure-grammar.md +22 -5
  31. package/dist/bundled-resources/skills/tool-call-repair/references/repair-catalogue.md +5 -5
  32. package/dist/bundled-resources/skills/tool-call-repair/references/text-protocol-grammar.md +28 -7
  33. package/dist/cli/args.d.ts +3 -0
  34. package/dist/cli/args.d.ts.map +1 -1
  35. package/dist/cli/args.js +15 -0
  36. package/dist/cli/args.js.map +1 -1
  37. package/dist/core/agent-paths.d.ts +49 -0
  38. package/dist/core/agent-paths.d.ts.map +1 -0
  39. package/dist/core/agent-paths.js +107 -0
  40. package/dist/core/agent-paths.js.map +1 -0
  41. package/dist/core/agent-session-services.d.ts.map +1 -1
  42. package/dist/core/agent-session-services.js +3 -3
  43. package/dist/core/agent-session-services.js.map +1 -1
  44. package/dist/core/agent-session.d.ts +234 -17
  45. package/dist/core/agent-session.d.ts.map +1 -1
  46. package/dist/core/agent-session.js +484 -62
  47. package/dist/core/agent-session.js.map +1 -1
  48. package/dist/core/autonomy/contracts.d.ts +9 -0
  49. package/dist/core/autonomy/contracts.d.ts.map +1 -1
  50. package/dist/core/autonomy/contracts.js.map +1 -1
  51. package/dist/core/autonomy/lane-tracker.d.ts +10 -1
  52. package/dist/core/autonomy/lane-tracker.d.ts.map +1 -1
  53. package/dist/core/autonomy/lane-tracker.js +5 -1
  54. package/dist/core/autonomy/lane-tracker.js.map +1 -1
  55. package/dist/core/background-lane-controller.d.ts +122 -6
  56. package/dist/core/background-lane-controller.d.ts.map +1 -1
  57. package/dist/core/background-lane-controller.js +447 -90
  58. package/dist/core/background-lane-controller.js.map +1 -1
  59. package/dist/core/bash-execution-controller.d.ts +4 -0
  60. package/dist/core/bash-execution-controller.d.ts.map +1 -1
  61. package/dist/core/bash-execution-controller.js +7 -1
  62. package/dist/core/bash-execution-controller.js.map +1 -1
  63. package/dist/core/compaction-support.d.ts +13 -3
  64. package/dist/core/compaction-support.d.ts.map +1 -1
  65. package/dist/core/compaction-support.js +43 -7
  66. package/dist/core/compaction-support.js.map +1 -1
  67. package/dist/core/context/context-audit.d.ts +33 -1
  68. package/dist/core/context/context-audit.d.ts.map +1 -1
  69. package/dist/core/context/context-audit.js +31 -5
  70. package/dist/core/context/context-audit.js.map +1 -1
  71. package/dist/core/context/sqlite-runtime-index.d.ts.map +1 -1
  72. package/dist/core/context/sqlite-runtime-index.js +13 -7
  73. package/dist/core/context/sqlite-runtime-index.js.map +1 -1
  74. package/dist/core/context-gc.d.ts.map +1 -1
  75. package/dist/core/context-gc.js +16 -1
  76. package/dist/core/context-gc.js.map +1 -1
  77. package/dist/core/context-pipeline.d.ts +26 -4
  78. package/dist/core/context-pipeline.d.ts.map +1 -1
  79. package/dist/core/context-pipeline.js +137 -14
  80. package/dist/core/context-pipeline.js.map +1 -1
  81. package/dist/core/cost-guard.d.ts +19 -3
  82. package/dist/core/cost-guard.d.ts.map +1 -1
  83. package/dist/core/cost-guard.js +18 -3
  84. package/dist/core/cost-guard.js.map +1 -1
  85. package/dist/core/delegation/session-worker-result.d.ts +34 -4
  86. package/dist/core/delegation/session-worker-result.d.ts.map +1 -1
  87. package/dist/core/delegation/session-worker-result.js +64 -4
  88. package/dist/core/delegation/session-worker-result.js.map +1 -1
  89. package/dist/core/delegation/worker-actions.d.ts.map +1 -1
  90. package/dist/core/delegation/worker-actions.js +1 -1
  91. package/dist/core/delegation/worker-actions.js.map +1 -1
  92. package/dist/core/delegation/worker-result.d.ts +42 -1
  93. package/dist/core/delegation/worker-result.d.ts.map +1 -1
  94. package/dist/core/delegation/worker-result.js +68 -0
  95. package/dist/core/delegation/worker-result.js.map +1 -1
  96. package/dist/core/extensions/loader.d.ts.map +1 -1
  97. package/dist/core/extensions/loader.js +23 -7
  98. package/dist/core/extensions/loader.js.map +1 -1
  99. package/dist/core/extensions/runner.d.ts.map +1 -1
  100. package/dist/core/extensions/runner.js +1 -0
  101. package/dist/core/extensions/runner.js.map +1 -1
  102. package/dist/core/extensions/types.d.ts +51 -0
  103. package/dist/core/extensions/types.d.ts.map +1 -1
  104. package/dist/core/extensions/types.js.map +1 -1
  105. package/dist/core/goal-loop-controller.d.ts +17 -1
  106. package/dist/core/goal-loop-controller.d.ts.map +1 -1
  107. package/dist/core/goal-loop-controller.js +79 -11
  108. package/dist/core/goal-loop-controller.js.map +1 -1
  109. package/dist/core/goals/goal-continuation-controller.d.ts +48 -2
  110. package/dist/core/goals/goal-continuation-controller.d.ts.map +1 -1
  111. package/dist/core/goals/goal-continuation-controller.js +77 -0
  112. package/dist/core/goals/goal-continuation-controller.js.map +1 -1
  113. package/dist/core/goals/goal-continuation-defaults.d.ts +39 -0
  114. package/dist/core/goals/goal-continuation-defaults.d.ts.map +1 -1
  115. package/dist/core/goals/goal-continuation-defaults.js +42 -0
  116. package/dist/core/goals/goal-continuation-defaults.js.map +1 -1
  117. package/dist/core/goals/goal-continuation-prompt.d.ts +4 -0
  118. package/dist/core/goals/goal-continuation-prompt.d.ts.map +1 -1
  119. package/dist/core/goals/goal-continuation-prompt.js +51 -10
  120. package/dist/core/goals/goal-continuation-prompt.js.map +1 -1
  121. package/dist/core/goals/goal-runtime-snapshot.d.ts +101 -2
  122. package/dist/core/goals/goal-runtime-snapshot.d.ts.map +1 -1
  123. package/dist/core/goals/goal-runtime-snapshot.js +87 -4
  124. package/dist/core/goals/goal-runtime-snapshot.js.map +1 -1
  125. package/dist/core/goals/goal-state.d.ts +89 -1
  126. package/dist/core/goals/goal-state.d.ts.map +1 -1
  127. package/dist/core/goals/goal-state.js +71 -5
  128. package/dist/core/goals/goal-state.js.map +1 -1
  129. package/dist/core/goals/goal-tool-core.d.ts +56 -2
  130. package/dist/core/goals/goal-tool-core.d.ts.map +1 -1
  131. package/dist/core/goals/goal-tool-core.js +111 -5
  132. package/dist/core/goals/goal-tool-core.js.map +1 -1
  133. package/dist/core/goals/session-goal-state.d.ts +11 -2
  134. package/dist/core/goals/session-goal-state.d.ts.map +1 -1
  135. package/dist/core/goals/session-goal-state.js +32 -17
  136. package/dist/core/goals/session-goal-state.js.map +1 -1
  137. package/dist/core/keybindings.d.ts +10 -0
  138. package/dist/core/keybindings.d.ts.map +1 -1
  139. package/dist/core/keybindings.js +10 -2
  140. package/dist/core/keybindings.js.map +1 -1
  141. package/dist/core/learning/observation-store.d.ts +12 -3
  142. package/dist/core/learning/observation-store.d.ts.map +1 -1
  143. package/dist/core/learning/observation-store.js +30 -15
  144. package/dist/core/learning/observation-store.js.map +1 -1
  145. package/dist/core/learning/skill-curator.d.ts +5 -1
  146. package/dist/core/learning/skill-curator.d.ts.map +1 -1
  147. package/dist/core/learning/skill-curator.js +21 -19
  148. package/dist/core/learning/skill-curator.js.map +1 -1
  149. package/dist/core/local-runtime-controller.d.ts +65 -3
  150. package/dist/core/local-runtime-controller.d.ts.map +1 -1
  151. package/dist/core/local-runtime-controller.js +186 -26
  152. package/dist/core/local-runtime-controller.js.map +1 -1
  153. package/dist/core/memory/providers/file-store.d.ts +1 -1
  154. package/dist/core/memory/providers/file-store.d.ts.map +1 -1
  155. package/dist/core/memory/providers/file-store.js +6 -6
  156. package/dist/core/memory/providers/file-store.js.map +1 -1
  157. package/dist/core/model-capability.d.ts +34 -0
  158. package/dist/core/model-capability.d.ts.map +1 -1
  159. package/dist/core/model-capability.js +42 -1
  160. package/dist/core/model-capability.js.map +1 -1
  161. package/dist/core/model-router/tool-escalation.d.ts +15 -0
  162. package/dist/core/model-router/tool-escalation.d.ts.map +1 -1
  163. package/dist/core/model-router/tool-escalation.js +23 -1
  164. package/dist/core/model-router/tool-escalation.js.map +1 -1
  165. package/dist/core/model-router-controller.d.ts +34 -7
  166. package/dist/core/model-router-controller.d.ts.map +1 -1
  167. package/dist/core/model-router-controller.js +95 -16
  168. package/dist/core/model-router-controller.js.map +1 -1
  169. package/dist/core/models/adaptation-store.d.ts +7 -0
  170. package/dist/core/models/adaptation-store.d.ts.map +1 -1
  171. package/dist/core/models/adaptation-store.js +47 -11
  172. package/dist/core/models/adaptation-store.js.map +1 -1
  173. package/dist/core/models/default-model-suggestions.d.ts.map +1 -1
  174. package/dist/core/models/default-model-suggestions.js +17 -0
  175. package/dist/core/models/default-model-suggestions.js.map +1 -1
  176. package/dist/core/models/fitness-store.d.ts +3 -0
  177. package/dist/core/models/fitness-store.d.ts.map +1 -1
  178. package/dist/core/models/fitness-store.js +11 -2
  179. package/dist/core/models/fitness-store.js.map +1 -1
  180. package/dist/core/models/llamacpp-runtime.d.ts +180 -0
  181. package/dist/core/models/llamacpp-runtime.d.ts.map +1 -0
  182. package/dist/core/models/llamacpp-runtime.js +475 -0
  183. package/dist/core/models/llamacpp-runtime.js.map +1 -0
  184. package/dist/core/models/local-registration.d.ts +40 -0
  185. package/dist/core/models/local-registration.d.ts.map +1 -1
  186. package/dist/core/models/local-registration.js +94 -5
  187. package/dist/core/models/local-registration.js.map +1 -1
  188. package/dist/core/models/local-runtime.d.ts.map +1 -1
  189. package/dist/core/models/local-runtime.js +9 -7
  190. package/dist/core/models/local-runtime.js.map +1 -1
  191. package/dist/core/models/model-ref.d.ts +7 -0
  192. package/dist/core/models/model-ref.d.ts.map +1 -1
  193. package/dist/core/models/model-ref.js +26 -0
  194. package/dist/core/models/model-ref.js.map +1 -1
  195. package/dist/core/models/needle-runtime.d.ts +257 -0
  196. package/dist/core/models/needle-runtime.d.ts.map +1 -0
  197. package/dist/core/models/needle-runtime.js +519 -0
  198. package/dist/core/models/needle-runtime.js.map +1 -0
  199. package/dist/core/models/prism-llamacpp-lifecycle.d.ts +89 -0
  200. package/dist/core/models/prism-llamacpp-lifecycle.d.ts.map +1 -0
  201. package/dist/core/models/prism-llamacpp-lifecycle.js +121 -0
  202. package/dist/core/models/prism-llamacpp-lifecycle.js.map +1 -0
  203. package/dist/core/package-manager.d.ts.map +1 -1
  204. package/dist/core/package-manager.js +11 -10
  205. package/dist/core/package-manager.js.map +1 -1
  206. package/dist/core/process-matrix/codes.d.ts +72 -0
  207. package/dist/core/process-matrix/codes.d.ts.map +1 -0
  208. package/dist/core/process-matrix/codes.js +15 -0
  209. package/dist/core/process-matrix/codes.js.map +1 -0
  210. package/dist/core/process-matrix/runtime.d.ts +63 -0
  211. package/dist/core/process-matrix/runtime.d.ts.map +1 -0
  212. package/dist/core/process-matrix/runtime.js +310 -0
  213. package/dist/core/process-matrix/runtime.js.map +1 -0
  214. package/dist/core/process-matrix/store.d.ts +22 -0
  215. package/dist/core/process-matrix/store.d.ts.map +1 -0
  216. package/dist/core/process-matrix/store.js +80 -0
  217. package/dist/core/process-matrix/store.js.map +1 -0
  218. package/dist/core/process-matrix/supervisor.d.ts +72 -0
  219. package/dist/core/process-matrix/supervisor.d.ts.map +1 -0
  220. package/dist/core/process-matrix/supervisor.js +130 -0
  221. package/dist/core/process-matrix/supervisor.js.map +1 -0
  222. package/dist/core/profile-registry.d.ts +7 -0
  223. package/dist/core/profile-registry.d.ts.map +1 -1
  224. package/dist/core/profile-registry.js +20 -0
  225. package/dist/core/profile-registry.js.map +1 -1
  226. package/dist/core/python-runtime.d.ts.map +1 -1
  227. package/dist/core/python-runtime.js +3 -3
  228. package/dist/core/python-runtime.js.map +1 -1
  229. package/dist/core/reflection-controller.d.ts +29 -5
  230. package/dist/core/reflection-controller.d.ts.map +1 -1
  231. package/dist/core/reflection-controller.js +215 -126
  232. package/dist/core/reflection-controller.js.map +1 -1
  233. package/dist/core/reload-blockers.d.ts +36 -0
  234. package/dist/core/reload-blockers.d.ts.map +1 -1
  235. package/dist/core/reload-blockers.js +44 -0
  236. package/dist/core/reload-blockers.js.map +1 -1
  237. package/dist/core/resource-loader.d.ts.map +1 -1
  238. package/dist/core/resource-loader.js +8 -7
  239. package/dist/core/resource-loader.js.map +1 -1
  240. package/dist/core/runtime-builder.d.ts +58 -5
  241. package/dist/core/runtime-builder.d.ts.map +1 -1
  242. package/dist/core/runtime-builder.js +209 -25
  243. package/dist/core/runtime-builder.js.map +1 -1
  244. package/dist/core/scout-controller.d.ts +6 -0
  245. package/dist/core/scout-controller.d.ts.map +1 -1
  246. package/dist/core/scout-controller.js +66 -52
  247. package/dist/core/scout-controller.js.map +1 -1
  248. package/dist/core/sdk.d.ts.map +1 -1
  249. package/dist/core/sdk.js +3 -3
  250. package/dist/core/sdk.js.map +1 -1
  251. package/dist/core/session-role.d.ts +31 -0
  252. package/dist/core/session-role.d.ts.map +1 -0
  253. package/dist/core/session-role.js +52 -0
  254. package/dist/core/session-role.js.map +1 -0
  255. package/dist/core/settings-manager.d.ts +42 -3
  256. package/dist/core/settings-manager.d.ts.map +1 -1
  257. package/dist/core/settings-manager.js +94 -60
  258. package/dist/core/settings-manager.js.map +1 -1
  259. package/dist/core/system-prompt-builder.d.ts +12 -0
  260. package/dist/core/system-prompt-builder.d.ts.map +1 -1
  261. package/dist/core/system-prompt-builder.js +6 -0
  262. package/dist/core/system-prompt-builder.js.map +1 -1
  263. package/dist/core/system-prompt.d.ts +14 -1
  264. package/dist/core/system-prompt.d.ts.map +1 -1
  265. package/dist/core/system-prompt.js +20 -3
  266. package/dist/core/system-prompt.js.map +1 -1
  267. package/dist/core/tasks/session-task-state.d.ts +11 -2
  268. package/dist/core/tasks/session-task-state.d.ts.map +1 -1
  269. package/dist/core/tasks/session-task-state.js +27 -11
  270. package/dist/core/tasks/session-task-state.js.map +1 -1
  271. package/dist/core/tasks/task-contract-monitor.d.ts +45 -0
  272. package/dist/core/tasks/task-contract-monitor.d.ts.map +1 -0
  273. package/dist/core/tasks/task-contract-monitor.js +56 -0
  274. package/dist/core/tasks/task-contract-monitor.js.map +1 -0
  275. package/dist/core/tasks/task-state.d.ts +8 -0
  276. package/dist/core/tasks/task-state.d.ts.map +1 -1
  277. package/dist/core/tasks/task-state.js +28 -1
  278. package/dist/core/tasks/task-state.js.map +1 -1
  279. package/dist/core/tool-gate-controller.d.ts.map +1 -1
  280. package/dist/core/tool-gate-controller.js +5 -0
  281. package/dist/core/tool-gate-controller.js.map +1 -1
  282. package/dist/core/tool-recovery-log-records.d.ts +7 -0
  283. package/dist/core/tool-recovery-log-records.d.ts.map +1 -1
  284. package/dist/core/tool-recovery-log-records.js +14 -6
  285. package/dist/core/tool-recovery-log-records.js.map +1 -1
  286. package/dist/core/tool-selection/promotion.d.ts +54 -0
  287. package/dist/core/tool-selection/promotion.d.ts.map +1 -0
  288. package/dist/core/tool-selection/promotion.js +81 -0
  289. package/dist/core/tool-selection/promotion.js.map +1 -0
  290. package/dist/core/tool-selection/tool-performance-store.d.ts +37 -0
  291. package/dist/core/tool-selection/tool-performance-store.d.ts.map +1 -1
  292. package/dist/core/tool-selection/tool-performance-store.js +87 -3
  293. package/dist/core/tool-selection/tool-performance-store.js.map +1 -1
  294. package/dist/core/tool-selection/tool-selection-controller.d.ts +45 -0
  295. package/dist/core/tool-selection/tool-selection-controller.d.ts.map +1 -1
  296. package/dist/core/tool-selection/tool-selection-controller.js +96 -0
  297. package/dist/core/tool-selection/tool-selection-controller.js.map +1 -1
  298. package/dist/core/tools/bash.d.ts +18 -0
  299. package/dist/core/tools/bash.d.ts.map +1 -1
  300. package/dist/core/tools/bash.js +97 -18
  301. package/dist/core/tools/bash.js.map +1 -1
  302. package/dist/core/tools/delegate-status.d.ts +14 -0
  303. package/dist/core/tools/delegate-status.d.ts.map +1 -1
  304. package/dist/core/tools/delegate-status.js +82 -7
  305. package/dist/core/tools/delegate-status.js.map +1 -1
  306. package/dist/core/tools/delegate.d.ts.map +1 -1
  307. package/dist/core/tools/delegate.js +25 -8
  308. package/dist/core/tools/delegate.js.map +1 -1
  309. package/dist/core/tools/find.d.ts.map +1 -1
  310. package/dist/core/tools/find.js +52 -44
  311. package/dist/core/tools/find.js.map +1 -1
  312. package/dist/core/tools/goal.d.ts +94 -3
  313. package/dist/core/tools/goal.d.ts.map +1 -1
  314. package/dist/core/tools/goal.js +165 -15
  315. package/dist/core/tools/goal.js.map +1 -1
  316. package/dist/core/tools/grep.d.ts.map +1 -1
  317. package/dist/core/tools/grep.js +5 -4
  318. package/dist/core/tools/grep.js.map +1 -1
  319. package/dist/core/tools/model-fitness.d.ts +7 -0
  320. package/dist/core/tools/model-fitness.d.ts.map +1 -1
  321. package/dist/core/tools/model-fitness.js +2 -2
  322. package/dist/core/tools/model-fitness.js.map +1 -1
  323. package/dist/core/tools/render-utils.d.ts.map +1 -1
  324. package/dist/core/tools/render-utils.js +1 -1
  325. package/dist/core/tools/render-utils.js.map +1 -1
  326. package/dist/core/tools/shell-contract-router.d.ts +6 -1
  327. package/dist/core/tools/shell-contract-router.d.ts.map +1 -1
  328. package/dist/core/tools/shell-contract-router.js +69 -13
  329. package/dist/core/tools/shell-contract-router.js.map +1 -1
  330. package/dist/core/tools/shell-session.d.ts +89 -0
  331. package/dist/core/tools/shell-session.d.ts.map +1 -0
  332. package/dist/core/tools/shell-session.js +432 -0
  333. package/dist/core/tools/shell-session.js.map +1 -0
  334. package/dist/core/tools/task-steps.d.ts +4 -0
  335. package/dist/core/tools/task-steps.d.ts.map +1 -1
  336. package/dist/core/tools/task-steps.js +63 -8
  337. package/dist/core/tools/task-steps.js.map +1 -1
  338. package/dist/core/tools/tmux-dispatch.d.ts +86 -0
  339. package/dist/core/tools/tmux-dispatch.d.ts.map +1 -0
  340. package/dist/core/tools/tmux-dispatch.js +91 -0
  341. package/dist/core/tools/tmux-dispatch.js.map +1 -0
  342. package/dist/core/tools/windows-shell-engine.d.ts +42 -0
  343. package/dist/core/tools/windows-shell-engine.d.ts.map +1 -0
  344. package/dist/core/tools/windows-shell-engine.js +153 -0
  345. package/dist/core/tools/windows-shell-engine.js.map +1 -0
  346. package/dist/core/tools/windows-shell-state.d.ts +40 -0
  347. package/dist/core/tools/windows-shell-state.d.ts.map +1 -0
  348. package/dist/core/tools/windows-shell-state.js +59 -0
  349. package/dist/core/tools/windows-shell-state.js.map +1 -0
  350. package/dist/core/tools/worktree-sync.d.ts +24 -0
  351. package/dist/core/tools/worktree-sync.d.ts.map +1 -0
  352. package/dist/core/tools/worktree-sync.js +338 -0
  353. package/dist/core/tools/worktree-sync.js.map +1 -0
  354. package/dist/core/trust-manager.d.ts +4 -1
  355. package/dist/core/trust-manager.d.ts.map +1 -1
  356. package/dist/core/trust-manager.js +20 -2
  357. package/dist/core/trust-manager.js.map +1 -1
  358. package/dist/core/util/atomic-file.d.ts +55 -0
  359. package/dist/core/util/atomic-file.d.ts.map +1 -0
  360. package/dist/core/util/atomic-file.js +255 -0
  361. package/dist/core/util/atomic-file.js.map +1 -0
  362. package/dist/core/util/minimatch-cache.d.ts +33 -0
  363. package/dist/core/util/minimatch-cache.d.ts.map +1 -0
  364. package/dist/core/util/minimatch-cache.js +0 -0
  365. package/dist/core/util/minimatch-cache.js.map +1 -0
  366. package/dist/core/worktree-sync/codes.d.ts +227 -0
  367. package/dist/core/worktree-sync/codes.d.ts.map +1 -0
  368. package/dist/core/worktree-sync/codes.js +14 -0
  369. package/dist/core/worktree-sync/codes.js.map +1 -0
  370. package/dist/core/worktree-sync/git-engine.d.ts +156 -0
  371. package/dist/core/worktree-sync/git-engine.d.ts.map +1 -0
  372. package/dist/core/worktree-sync/git-engine.js +1191 -0
  373. package/dist/core/worktree-sync/git-engine.js.map +1 -0
  374. package/dist/core/worktree-sync/lane-gate.d.ts +75 -0
  375. package/dist/core/worktree-sync/lane-gate.d.ts.map +1 -0
  376. package/dist/core/worktree-sync/lane-gate.js +360 -0
  377. package/dist/core/worktree-sync/lane-gate.js.map +1 -0
  378. package/dist/core/worktree-sync/runtime.d.ts +47 -0
  379. package/dist/core/worktree-sync/runtime.d.ts.map +1 -0
  380. package/dist/core/worktree-sync/runtime.js +96 -0
  381. package/dist/core/worktree-sync/runtime.js.map +1 -0
  382. package/dist/core/worktree-sync/store.d.ts +69 -0
  383. package/dist/core/worktree-sync/store.d.ts.map +1 -0
  384. package/dist/core/worktree-sync/store.js +247 -0
  385. package/dist/core/worktree-sync/store.js.map +1 -0
  386. package/dist/core/worktree-sync/watcher.d.ts +29 -0
  387. package/dist/core/worktree-sync/watcher.d.ts.map +1 -0
  388. package/dist/core/worktree-sync/watcher.js +93 -0
  389. package/dist/core/worktree-sync/watcher.js.map +1 -0
  390. package/dist/main.d.ts.map +1 -1
  391. package/dist/main.js +94 -0
  392. package/dist/main.js.map +1 -1
  393. package/dist/migrations.d.ts +9 -0
  394. package/dist/migrations.d.ts.map +1 -1
  395. package/dist/migrations.js +38 -0
  396. package/dist/migrations.js.map +1 -1
  397. package/dist/modes/interactive/auto-learn-controller.d.ts +16 -1
  398. package/dist/modes/interactive/auto-learn-controller.d.ts.map +1 -1
  399. package/dist/modes/interactive/auto-learn-controller.js +50 -8
  400. package/dist/modes/interactive/auto-learn-controller.js.map +1 -1
  401. package/dist/modes/interactive/components/profile-resource-editor.d.ts.map +1 -1
  402. package/dist/modes/interactive/components/profile-resource-editor.js +23 -1
  403. package/dist/modes/interactive/components/profile-resource-editor.js.map +1 -1
  404. package/dist/modes/interactive/interactive-mode.d.ts +1 -0
  405. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  406. package/dist/modes/interactive/interactive-mode.js +4 -0
  407. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  408. package/dist/modes/interactive/local-model-commands.d.ts +43 -0
  409. package/dist/modes/interactive/local-model-commands.d.ts.map +1 -1
  410. package/dist/modes/interactive/local-model-commands.js +290 -3
  411. package/dist/modes/interactive/local-model-commands.js.map +1 -1
  412. package/dist/modes/interactive/session-flow-commands.d.ts.map +1 -1
  413. package/dist/modes/interactive/session-flow-commands.js +24 -4
  414. package/dist/modes/interactive/session-flow-commands.js.map +1 -1
  415. package/dist/utils/fs-watch.d.ts +11 -0
  416. package/dist/utils/fs-watch.d.ts.map +1 -1
  417. package/dist/utils/fs-watch.js +20 -2
  418. package/dist/utils/fs-watch.js.map +1 -1
  419. package/dist/utils/highlight-js-languages.d.ts +4 -0
  420. package/dist/utils/highlight-js-languages.d.ts.map +1 -0
  421. package/dist/utils/highlight-js-languages.js +573 -0
  422. package/dist/utils/highlight-js-languages.js.map +1 -0
  423. package/dist/utils/shell.d.ts +7 -1
  424. package/dist/utils/shell.d.ts.map +1 -1
  425. package/dist/utils/shell.js +39 -9
  426. package/dist/utils/shell.js.map +1 -1
  427. package/dist/utils/syntax-highlight.d.ts.map +1 -1
  428. package/dist/utils/syntax-highlight.js +53 -5
  429. package/dist/utils/syntax-highlight.js.map +1 -1
  430. package/dist/utils/tools-manager.d.ts.map +1 -1
  431. package/dist/utils/tools-manager.js +112 -1
  432. package/dist/utils/tools-manager.js.map +1 -1
  433. package/docs/development.md +2 -0
  434. package/docs/packages.md +1 -1
  435. package/docs/process-matrix.md +120 -0
  436. package/docs/settings.md +5 -2
  437. package/docs/tmux-agent-manager.md +85 -2
  438. package/docs/windows.md +52 -3
  439. package/docs/work-directory.md +29 -0
  440. package/docs/worktree-sync.md +250 -0
  441. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  442. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  443. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  444. package/examples/extensions/sandbox/package-lock.json +2 -2
  445. package/examples/extensions/sandbox/package.json +1 -1
  446. package/examples/extensions/with-deps/package-lock.json +2 -2
  447. package/examples/extensions/with-deps/package.json +1 -1
  448. package/npm-shrinkwrap.json +12 -12
  449. package/package.json +10 -4
  450. package/docs/integration-sweep-builder-blueprint-2026-07-09.md +0 -365
  451. package/docs/integration-sweep-resume-2026-07-09.md +0 -407
@@ -1 +1 @@
1
- {"version":3,"file":"render-utils.js","sourceRoot":"","sources":["../../../src/core/tools/render-utils.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,SAAS,CAAC;AAC9B,OAAO,EAAE,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CAAC,SAAS,CAAC;YAClG,OAAO,aAAa,CAAC,QAAQ,EAAE,IAAI,CAAC,CAAC;QAAA,CACrC,CAAC;aACD,IAAI,CAAC,IAAI,CAAC,CAAC;QACb,MAAM,GAAG,MAAM,CAAC,CAAC,CAAC,GAAG,MAAM,KAAK,eAAe,EAAE,CAAC,CAAC,CAAC,eAAe,CAAC;IACrE,CAAC;IAED,OAAO,MAAM,CAAC;AAAA,CACd;AAOD,MAAM,UAAU,cAAc,CAAC,KAAY,EAAU;IACpD,OAAO,KAAK,CAAC,EAAE,CAAC,OAAO,EAAE,eAAe,CAAC,CAAC;AAAA,CAC1C;AAED,MAAM,UAAU,cAAc,CAC7B,OAAsB,EACtB,KAAY,EACZ,GAAW,EACX,OAAoC,EAC3B;IACT,IAAI,OAAO,KAAK,IAAI;QAAE,OAAO,cAAc,CAAC,KAAK,CAAC,CAAC;IACnD,MAAM,KAAK,GAAG,OAAO,IAAI,OAAO,EAAE,aAAa,CAAC;IAChD,IAAI,CAAC,KAAK;QAAE,OAAO,KAAK,CAAC,EAAE,CAAC,YAAY,EAAE,KAAK,CAAC,CAAC;IACjD,OAAO,QAAQ,CAAC,KAAK,CAAC,EAAE,CAAC,QAAQ,EAAE,WAAW,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC,EAAE,KAAK,EAAE,GAAG,CAAC,CAAC;AAAA,CACzE","sourcesContent":["import * as os from \"node:os\";\nimport { relative, sep } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { sanitizeBinaryOutput } from \"@caupulican/pi-agent-core\";\nimport type { ImageContent, TextContent } from \"@caupulican/pi-ai\";\nimport { getCapabilities, getImageDimensions, hyperlink, imageFallback } from \"@caupulican/pi-tui\";\nimport type { Theme } from \"../../modes/interactive/theme/theme.ts\";\nimport { stripAnsi } from \"../../utils/ansi.ts\";\nimport { resolvePath } from \"../../utils/paths.ts\";\n\nfunction toDisplaySeparators(path: string): string {\n\treturn path.split(sep).join(\"/\");\n}\n\nfunction looksLikeWindowsAbsolutePath(path: string): boolean {\n\treturn /^[a-zA-Z]:[\\\\/]/.test(path);\n}\n\nfunction addCandidate(candidates: string[], value: string | undefined): void {\n\tif (!value || candidates.includes(value)) return;\n\tcandidates.push(value);\n}\n\nexport function shortenPath(path: unknown, cwd?: string): string {\n\tif (typeof path !== \"string\") return \"\";\n\tconst candidates: string[] = [];\n\taddCandidate(candidates, toDisplaySeparators(path));\n\n\tconst home = os.homedir();\n\tif (path.startsWith(home)) {\n\t\taddCandidate(candidates, `~${toDisplaySeparators(path.slice(home.length))}`);\n\t}\n\n\tif (cwd && !looksLikeWindowsAbsolutePath(path)) {\n\t\ttry {\n\t\t\tconst absolutePath = resolvePath(path, cwd);\n\t\t\tconst resolvedCwd = resolvePath(cwd);\n\t\t\tconst relativePath = relative(resolvedCwd, absolutePath) || \".\";\n\t\t\taddCandidate(candidates, toDisplaySeparators(relativePath));\n\t\t} catch {\n\t\t\t// Keep the raw/home-shortened candidates when a path cannot be resolved for display.\n\t\t}\n\t}\n\n\treturn candidates.reduce((shortest, candidate) => (candidate.length < shortest.length ? candidate : shortest));\n}\n\nexport function linkPath(styledText: string, rawPath: string, cwd: string): string {\n\tif (!getCapabilities().hyperlinks) return styledText;\n\tconst absolutePath = resolvePath(rawPath, cwd);\n\treturn hyperlink(styledText, pathToFileURL(absolutePath).href);\n}\n\nexport function str(value: unknown): string | null {\n\tif (typeof value === \"string\") return value;\n\tif (value == null) return \"\";\n\treturn null;\n}\n\nexport function replaceTabs(text: string): string {\n\treturn text.replace(/\\t/g, \" \");\n}\n\nexport function normalizeDisplayText(text: string): string {\n\treturn text.replace(/\\r/g, \"\");\n}\n\nexport function getTextOutput(\n\tresult: { content: Array<{ type: string; text?: string; data?: string; mimeType?: string }> } | undefined,\n\tshowImages: boolean,\n): string {\n\tif (!result) return \"\";\n\n\tconst textBlocks = result.content.filter((c) => c.type === \"text\");\n\tconst imageBlocks = result.content.filter((c) => c.type === \"image\");\n\n\tlet output = textBlocks.map((c) => sanitizeBinaryOutput(stripAnsi(c.text || \"\")).replace(/\\r/g, \"\")).join(\"\\n\");\n\n\tconst caps = getCapabilities();\n\tif (imageBlocks.length > 0 && (!caps.images || !showImages)) {\n\t\tconst imageIndicators = imageBlocks\n\t\t\t.map((img) => {\n\t\t\t\tconst mimeType = img.mimeType ?? \"image/unknown\";\n\t\t\t\tconst dims =\n\t\t\t\t\timg.data && img.mimeType ? (getImageDimensions(img.data, img.mimeType) ?? undefined) : undefined;\n\t\t\t\treturn imageFallback(mimeType, dims);\n\t\t\t})\n\t\t\t.join(\"\\n\");\n\t\toutput = output ? `${output}\\n${imageIndicators}` : imageIndicators;\n\t}\n\n\treturn output;\n}\n\nexport type ToolRenderResultLike<TDetails> = {\n\tcontent: (TextContent | ImageContent)[];\n\tdetails: TDetails;\n};\n\nexport function invalidArgText(theme: Theme): string {\n\treturn theme.fg(\"error\", \"[invalid arg]\");\n}\n\nexport function renderToolPath(\n\trawPath: string | null,\n\ttheme: Theme,\n\tcwd: string,\n\toptions?: { emptyFallback?: string },\n): string {\n\tif (rawPath === null) return invalidArgText(theme);\n\tconst value = rawPath || options?.emptyFallback;\n\tif (!value) return theme.fg(\"toolOutput\", \"...\");\n\treturn linkPath(theme.fg(\"accent\", shortenPath(value, cwd)), value, cwd);\n}\n"]}
1
+ {"version":3,"file":"render-utils.js","sourceRoot":"","sources":["../../../src/core/tools/render-utils.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,SAAS,CAAC;AAC9B,OAAO,EAAE,QAAQ,EAAE,GAAG,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACzC,OAAO,EAAE,oBAAoB,EAAE,MAAM,2BAA2B,CAAC;AAEjE,OAAO,EAAE,eAAe,EAAE,kBAAkB,EAAE,SAAS,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAEnG,OAAO,EAAE,SAAS,EAAE,MAAM,qBAAqB,CA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AAC;IAED,OAAO,MAAM,CAAC;AAAA,CACd;AAOD,MAAM,UAAU,cAAc,CAAC,KAAY,EAAU;IACpD,OAAO,KAAK,CAAC,EAAE,CAAC,OAAO,EAAE,eAAe,CAAC,CAAC;AAAA,CAC1C;AAED,MAAM,UAAU,cAAc,CAC7B,OAAsB,EACtB,KAAY,EACZ,GAAW,EACX,OAAoC,EAC3B;IACT,IAAI,OAAO,KAAK,IAAI;QAAE,OAAO,cAAc,CAAC,KAAK,CAAC,CAAC;IACnD,MAAM,KAAK,GAAG,OAAO,IAAI,OAAO,EAAE,aAAa,CAAC;IAChD,IAAI,CAAC,KAAK;QAAE,OAAO,KAAK,CAAC,EAAE,CAAC,YAAY,EAAE,KAAK,CAAC,CAAC;IACjD,OAAO,QAAQ,CAAC,KAAK,CAAC,EAAE,CAAC,QAAQ,EAAE,WAAW,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC,EAAE,KAAK,EAAE,GAAG,CAAC,CAAC;AAAA,CACzE","sourcesContent":["import * as os from \"node:os\";\nimport { relative, sep } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { sanitizeBinaryOutput } from \"@caupulican/pi-agent-core\";\nimport type { ImageContent, TextContent } from \"@caupulican/pi-ai\";\nimport { getCapabilities, getImageDimensions, hyperlink, imageFallback } from \"@caupulican/pi-tui\";\nimport type { Theme } from \"../../modes/interactive/theme/theme.ts\";\nimport { stripAnsi } from \"../../utils/ansi.ts\";\nimport { resolvePath } from \"../../utils/paths.ts\";\n\nfunction toDisplaySeparators(path: string): string {\n\treturn path.split(sep).join(\"/\");\n}\n\nfunction looksLikeWindowsAbsolutePath(path: string): boolean {\n\treturn /^[a-zA-Z]:[\\\\/]/.test(path);\n}\n\nfunction addCandidate(candidates: string[], value: string | undefined): void {\n\tif (!value || candidates.includes(value)) return;\n\tcandidates.push(value);\n}\n\nexport function shortenPath(path: unknown, cwd?: string): string {\n\tif (typeof path !== \"string\") return \"\";\n\tconst candidates: string[] = [];\n\taddCandidate(candidates, toDisplaySeparators(path));\n\n\tconst home = os.homedir();\n\tif (path.startsWith(home)) {\n\t\taddCandidate(candidates, `~${toDisplaySeparators(path.slice(home.length))}`);\n\t}\n\n\tif (cwd && (process.platform === \"win32\" || !looksLikeWindowsAbsolutePath(path))) {\n\t\ttry {\n\t\t\tconst absolutePath = resolvePath(path, cwd);\n\t\t\tconst resolvedCwd = resolvePath(cwd);\n\t\t\tconst relativePath = relative(resolvedCwd, absolutePath) || \".\";\n\t\t\taddCandidate(candidates, toDisplaySeparators(relativePath));\n\t\t} catch {\n\t\t\t// Keep the raw/home-shortened candidates when a path cannot be resolved for display.\n\t\t}\n\t}\n\n\treturn candidates.reduce((shortest, candidate) => (candidate.length < shortest.length ? candidate : shortest));\n}\n\nexport function linkPath(styledText: string, rawPath: string, cwd: string): string {\n\tif (!getCapabilities().hyperlinks) return styledText;\n\tconst absolutePath = resolvePath(rawPath, cwd);\n\treturn hyperlink(styledText, pathToFileURL(absolutePath).href);\n}\n\nexport function str(value: unknown): string | null {\n\tif (typeof value === \"string\") return value;\n\tif (value == null) return \"\";\n\treturn null;\n}\n\nexport function replaceTabs(text: string): string {\n\treturn text.replace(/\\t/g, \" \");\n}\n\nexport function normalizeDisplayText(text: string): string {\n\treturn text.replace(/\\r/g, \"\");\n}\n\nexport function getTextOutput(\n\tresult: { content: Array<{ type: string; text?: string; data?: string; mimeType?: string }> } | undefined,\n\tshowImages: boolean,\n): string {\n\tif (!result) return \"\";\n\n\tconst textBlocks = result.content.filter((c) => c.type === \"text\");\n\tconst imageBlocks = result.content.filter((c) => c.type === \"image\");\n\n\tlet output = textBlocks.map((c) => sanitizeBinaryOutput(stripAnsi(c.text || \"\")).replace(/\\r/g, \"\")).join(\"\\n\");\n\n\tconst caps = getCapabilities();\n\tif (imageBlocks.length > 0 && (!caps.images || !showImages)) {\n\t\tconst imageIndicators = imageBlocks\n\t\t\t.map((img) => {\n\t\t\t\tconst mimeType = img.mimeType ?? \"image/unknown\";\n\t\t\t\tconst dims =\n\t\t\t\t\timg.data && img.mimeType ? (getImageDimensions(img.data, img.mimeType) ?? undefined) : undefined;\n\t\t\t\treturn imageFallback(mimeType, dims);\n\t\t\t})\n\t\t\t.join(\"\\n\");\n\t\toutput = output ? `${output}\\n${imageIndicators}` : imageIndicators;\n\t}\n\n\treturn output;\n}\n\nexport type ToolRenderResultLike<TDetails> = {\n\tcontent: (TextContent | ImageContent)[];\n\tdetails: TDetails;\n};\n\nexport function invalidArgText(theme: Theme): string {\n\treturn theme.fg(\"error\", \"[invalid arg]\");\n}\n\nexport function renderToolPath(\n\trawPath: string | null,\n\ttheme: Theme,\n\tcwd: string,\n\toptions?: { emptyFallback?: string },\n): string {\n\tif (rawPath === null) return invalidArgText(theme);\n\tconst value = rawPath || options?.emptyFallback;\n\tif (!value) return theme.fg(\"toolOutput\", \"...\");\n\treturn linkPath(theme.fg(\"accent\", shortenPath(value, cwd)), value, cwd);\n}\n"]}
@@ -5,9 +5,14 @@ export type ShellContractRoute = {
5
5
  kind: "powershell";
6
6
  command: string;
7
7
  argv: readonly string[];
8
+ } | {
9
+ kind: "python-engine";
10
+ command: string;
8
11
  } | {
9
12
  kind: "unsupported";
10
13
  error: string;
11
14
  };
12
- export declare function routeShellContract(command: string, platform?: NodeJS.Platform): ShellContractRoute;
15
+ export declare function routeShellContract(command: string, platform?: NodeJS.Platform, options?: {
16
+ pythonEngine?: boolean;
17
+ }): ShellContractRoute;
13
18
  //# sourceMappingURL=shell-contract-router.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"shell-contract-router.d.ts","sourceRoot":"","sources":["../../../src/core/tools/shell-contract-router.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,kBAAkB,GAC3B;IAAE,IAAI,EAAE,aAAa,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,GACxC;IAAE,IAAI,EAAE,YAAY,CAAC;IAAC,OAAO,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,SAAS,MAAM,EAAE,CAAA;CAAE,GAChE;IAAE,IAAI,EAAE,aAAa,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,CAAC;AAmQ1C,wBAAgB,kBAAkB,CAAC,OAAO,EAAE,MAAM,EAAE,QAAQ,GAAE,MAAM,CAAC,QAA2B,GAAG,kBAAkB,CAkCpH","sourcesContent":["export type ShellContractRoute =\n\t| { kind: \"passthrough\"; command: string }\n\t| { kind: \"powershell\"; command: string; argv: readonly string[] }\n\t| { kind: \"unsupported\"; error: string };\n\ninterface TokenizeResult {\n\tok: boolean;\n\targv?: string[];\n\terror?: string;\n}\n\nconst BLOCKED_NESTED_SHELLS = new Set([\n\t\"bash\",\n\t\"sh\",\n\t\"zsh\",\n\t\"fish\",\n\t\"cmd\",\n\t\"cmd.exe\",\n\t\"powershell\",\n\t\"powershell.exe\",\n\t\"pwsh\",\n\t\"pwsh.exe\",\n\t\"wsl\",\n\t\"wsl.exe\",\n]);\nconst UNSUPPORTED_OPERATOR_MESSAGE =\n\t\"Unsupported Bash construct on Windows. Use one simple command per call; pipelines, redirection, command substitution, variable expansion, shell chaining, and nested shells are not translated.\";\n\nfunction tokenizePortableCommand(command: string): TokenizeResult {\n\tconst argv: string[] = [];\n\tlet token = \"\";\n\tlet tokenStarted = false;\n\tlet quote: \"single\" | \"double\" | undefined;\n\tlet escaping = false;\n\n\tconst finishToken = () => {\n\t\tif (!tokenStarted) return;\n\t\targv.push(token);\n\t\ttoken = \"\";\n\t\ttokenStarted = false;\n\t};\n\n\tfor (const character of command.trim()) {\n\t\tif (escaping) {\n\t\t\ttoken += character;\n\t\t\ttokenStarted = true;\n\t\t\tescaping = false;\n\t\t\tcontinue;\n\t\t}\n\t\tif (quote === \"single\") {\n\t\t\tif (character === \"'\") quote = undefined;\n\t\t\telse token += character;\n\t\t\ttokenStarted = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (quote === \"double\") {\n\t\t\tif (character === '\"') {\n\t\t\t\tquote = undefined;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (character === \"\\\\\") {\n\t\t\t\tescaping = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (character === \"$\" || character === \"`\") {\n\t\t\t\treturn { ok: false, error: UNSUPPORTED_OPERATOR_MESSAGE };\n\t\t\t}\n\t\t\ttoken += character;\n\t\t\ttokenStarted = true;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (character === \"'\") {\n\t\t\tquote = \"single\";\n\t\t\ttokenStarted = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (character === '\"') {\n\t\t\tquote = \"double\";\n\t\t\ttokenStarted = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (character === \"\\\\\") {\n\t\t\tescaping = true;\n\t\t\ttokenStarted = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (/\\s/u.test(character)) {\n\t\t\tfinishToken();\n\t\t\tcontinue;\n\t\t}\n\t\tif (\"|><&;\\n\\r$`()\".includes(character) || character === \"#\") {\n\t\t\treturn { ok: false, error: UNSUPPORTED_OPERATOR_MESSAGE };\n\t\t}\n\t\ttoken += character;\n\t\ttokenStarted = true;\n\t}\n\n\tif (escaping) return { ok: false, error: \"Unsupported trailing escape in Bash-like command.\" };\n\tif (quote) return { ok: false, error: \"Unclosed quote in Bash-like command.\" };\n\tfinishToken();\n\treturn argv.length > 0 ? { ok: true, argv } : { ok: false, error: \"Shell command is empty.\" };\n}\n\nfunction quotePowerShell(value: string): string {\n\treturn `'${value.replaceAll(\"'\", \"''\")}'`;\n}\n\nfunction powershellArray(values: readonly string[]): string {\n\treturn `@(${values.map(quotePowerShell).join(\", \")})`;\n}\n\nfunction externalCommand(argv: readonly string[]): string {\n\tconst invocation = `& ${argv.map(quotePowerShell).join(\" \")}`;\n\treturn `${invocation}\\nif ($null -ne $LASTEXITCODE) { exit $LASTEXITCODE }\\nif (-not $?) { exit 1 }`;\n}\n\nfunction parseFlags(\n\targv: readonly string[],\n\tallowedFlags: ReadonlySet<string>,\n): { flags: Set<string>; operands: string[] } | undefined {\n\tconst flags = new Set<string>();\n\tconst operands: string[] = [];\n\tlet optionsEnded = false;\n\tfor (const value of argv) {\n\t\tif (!optionsEnded && value === \"--\") {\n\t\t\toptionsEnded = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (!optionsEnded && value.startsWith(\"-\") && value !== \"-\") {\n\t\t\tif (!allowedFlags.has(value)) return undefined;\n\t\t\tflags.add(value);\n\t\t\tcontinue;\n\t\t}\n\t\toperands.push(value);\n\t}\n\treturn { flags, operands };\n}\n\nfunction routeLs(argv: readonly string[]): string | undefined {\n\tconst parsed = parseFlags(argv.slice(1), new Set([\"-a\", \"-A\", \"-l\", \"-1\", \"-la\", \"-al\"]));\n\tif (!parsed || parsed.operands.length > 1) return undefined;\n\tconst target = parsed.operands[0] ?? \".\";\n\treturn `[string[]]$items = @(Get-ChildItem -LiteralPath ${quotePowerShell(target)} -Force -ErrorAction Stop | ForEach-Object { if ($_.PSIsContainer) { $_.Name + '/' } else { $_.Name } }); [Array]::Sort($items, [StringComparer]::Ordinal); $items`;\n}\n\nfunction routeCat(argv: readonly string[]): string | undefined {\n\tconst parsed = parseFlags(argv.slice(1), new Set([\"--\"]));\n\tif (!parsed || parsed.operands.length === 0) return undefined;\n\treturn `Get-Content -LiteralPath ${powershellArray(parsed.operands)} -Raw -ErrorAction Stop`;\n}\n\nfunction routeHeadOrTail(argv: readonly string[], tail: boolean): string | undefined {\n\tlet count = 10;\n\tlet operands = argv.slice(1);\n\tif (operands[0] === \"-n\") {\n\t\tconst parsedCount = Number(operands[1]);\n\t\tif (!Number.isInteger(parsedCount) || parsedCount < 0) return undefined;\n\t\tcount = parsedCount;\n\t\toperands = operands.slice(2);\n\t}\n\tif (operands.length !== 1 || operands[0].startsWith(\"-\")) return undefined;\n\treturn `Get-Content -LiteralPath ${quotePowerShell(operands[0])} ${tail ? \"-Tail\" : \"-TotalCount\"} ${count} -ErrorAction Stop`;\n}\n\nfunction routeGrep(argv: readonly string[]): string | undefined {\n\tif (argv.length !== 3 || argv[1].startsWith(\"-\") || argv[2].startsWith(\"-\")) return undefined;\n\treturn `Select-String -LiteralPath ${quotePowerShell(argv[2])} -SimpleMatch -Pattern ${quotePowerShell(argv[1])} -ErrorAction Stop | ForEach-Object { $_.Line }`;\n}\n\nfunction routeFind(argv: readonly string[]): string | undefined {\n\tlet searchPath = \".\";\n\tlet type: \"File\" | \"Directory\" | undefined;\n\tlet filter: string | undefined;\n\tlet index = 1;\n\tif (argv[index] && !argv[index].startsWith(\"-\")) searchPath = argv[index++];\n\twhile (index < argv.length) {\n\t\tconst option = argv[index++];\n\t\tif (option === \"-type\" && (argv[index] === \"f\" || argv[index] === \"d\")) {\n\t\t\ttype = argv[index++] === \"f\" ? \"File\" : \"Directory\";\n\t\t\tcontinue;\n\t\t}\n\t\tif (option === \"-name\" && argv[index]) {\n\t\t\tfilter = argv[index++];\n\t\t\tcontinue;\n\t\t}\n\t\treturn undefined;\n\t}\n\tconst typeFlag = type ? ` -${type}` : \"\";\n\tconst filterFlag = filter ? ` -Filter ${quotePowerShell(filter)}` : \"\";\n\treturn `[string[]]$paths = @(Get-ChildItem -LiteralPath ${quotePowerShell(searchPath)} -Recurse -Force${typeFlag}${filterFlag} -ErrorAction Stop | ForEach-Object { $_.FullName.Replace('\\\\', '/') }); [Array]::Sort($paths, [StringComparer]::Ordinal); $paths`;\n}\n\nfunction routeRemove(argv: readonly string[]): string | undefined {\n\tconst parsed = parseFlags(argv.slice(1), new Set([\"-f\", \"-r\", \"-rf\", \"-fr\"]));\n\tif (!parsed || parsed.operands.length === 0) return undefined;\n\tconst recursive = [...parsed.flags].some((flag) => flag.includes(\"r\"));\n\treturn `Remove-Item -LiteralPath ${powershellArray(parsed.operands)} -Force${recursive ? \" -Recurse\" : \"\"} -ErrorAction Stop`;\n}\n\nfunction routeCopyOrMove(argv: readonly string[], move: boolean): string | undefined {\n\tconst parsed = parseFlags(argv.slice(1), move ? new Set<string>() : new Set([\"-r\", \"-R\"]));\n\tif (!parsed || parsed.operands.length !== 2) return undefined;\n\tconst [source, destination] = parsed.operands;\n\tconst recurse = !move && parsed.flags.size > 0 ? \" -Recurse\" : \"\";\n\treturn `${move ? \"Move-Item\" : \"Copy-Item\"} -LiteralPath ${quotePowerShell(source)} -Destination ${quotePowerShell(destination)}${recurse} -ErrorAction Stop`;\n}\n\nfunction routeMkdir(argv: readonly string[]): string | undefined {\n\tconst parsed = parseFlags(argv.slice(1), new Set([\"-p\"]));\n\tif (!parsed || parsed.operands.length === 0) return undefined;\n\treturn `${powershellArray(parsed.operands)} | ForEach-Object { New-Item -ItemType Directory -Path $_ -Force -ErrorAction Stop | Out-Null }`;\n}\n\nfunction routeTouch(argv: readonly string[]): string | undefined {\n\tconst parsed = parseFlags(argv.slice(1), new Set());\n\tif (!parsed || parsed.operands.length === 0) return undefined;\n\treturn `${powershellArray(parsed.operands)} | ForEach-Object { if (Test-Path -LiteralPath $_) { (Get-Item -LiteralPath $_ -ErrorAction Stop).LastWriteTime = Get-Date } else { New-Item -ItemType File -Path $_ -ErrorAction Stop | Out-Null } }`;\n}\n\nfunction routeBuiltIn(argv: readonly string[]): string | undefined {\n\tconst command = argv[0].toLowerCase();\n\tif (command === \"pwd\" && argv.length === 1) return \"(Get-Location).Path\";\n\tif (command === \"echo\") return `[Console]::Out.WriteLine((${powershellArray(argv.slice(1))} -join ' '))`;\n\tif (command === \"true\" && argv.length === 1) return \"exit 0\";\n\tif (command === \"false\" && argv.length === 1) return \"exit 1\";\n\tif (command === \"which\" && argv.length === 2) {\n\t\treturn `(Get-Command -Name ${quotePowerShell(argv[1])} -CommandType Application -ErrorAction Stop).Source`;\n\t}\n\tif (command === \"ls\") return routeLs(argv);\n\tif (command === \"cat\") return routeCat(argv);\n\tif (command === \"head\") return routeHeadOrTail(argv, false);\n\tif (command === \"tail\") return routeHeadOrTail(argv, true);\n\tif (command === \"grep\") return routeGrep(argv);\n\tif (command === \"find\") return routeFind(argv);\n\tif (command === \"rm\") return routeRemove(argv);\n\tif (command === \"cp\") return routeCopyOrMove(argv, false);\n\tif (command === \"mv\") return routeCopyOrMove(argv, true);\n\tif (command === \"mkdir\") return routeMkdir(argv);\n\tif (command === \"touch\") return routeTouch(argv);\n\treturn undefined;\n}\n\nconst ROUTED_BUILTIN_NAMES = new Set([\n\t\"pwd\",\n\t\"echo\",\n\t\"true\",\n\t\"false\",\n\t\"which\",\n\t\"ls\",\n\t\"cat\",\n\t\"head\",\n\t\"tail\",\n\t\"grep\",\n\t\"find\",\n\t\"rm\",\n\t\"cp\",\n\t\"mv\",\n\t\"mkdir\",\n\t\"touch\",\n]);\n\nexport function routeShellContract(command: string, platform: NodeJS.Platform = process.platform): ShellContractRoute {\n\tif (platform !== \"win32\") return { kind: \"passthrough\", command };\n\tconst tokenized = tokenizePortableCommand(command);\n\tif (!tokenized.ok || !tokenized.argv)\n\t\treturn { kind: \"unsupported\", error: tokenized.error ?? UNSUPPORTED_OPERATOR_MESSAGE };\n\tconst argv = tokenized.argv;\n\tconst commandName = argv[0].toLowerCase();\n\tif (/^[A-Za-z_][A-Za-z0-9_]*=/u.test(argv[0])) {\n\t\treturn {\n\t\t\tkind: \"unsupported\",\n\t\t\terror: \"Inline environment assignments are not supported. Configure the environment outside the shell command.\",\n\t\t};\n\t}\n\tif (BLOCKED_NESTED_SHELLS.has(commandName)) {\n\t\treturn {\n\t\t\tkind: \"unsupported\",\n\t\t\terror: \"Nested shell execution is not supported by the Windows shell contract router.\",\n\t\t};\n\t}\n\tconst builtIn = routeBuiltIn(argv);\n\tif (builtIn) return { kind: \"powershell\", command: builtIn, argv };\n\tif (ROUTED_BUILTIN_NAMES.has(commandName)) {\n\t\treturn {\n\t\t\tkind: \"unsupported\",\n\t\t\terror: `Unsupported ${argv[0]} form on Windows. Use a simpler Bash-like form or Pi's dedicated read/search/edit tools.`,\n\t\t};\n\t}\n\tif (commandName.endsWith(\".sh\") || commandName.includes(\"/bin/\")) {\n\t\treturn {\n\t\t\tkind: \"unsupported\",\n\t\t\terror: \"POSIX shell scripts are not supported by the Windows shell contract router.\",\n\t\t};\n\t}\n\treturn { kind: \"powershell\", command: externalCommand(argv), argv };\n}\n"]}
1
+ {"version":3,"file":"shell-contract-router.d.ts","sourceRoot":"","sources":["../../../src/core/tools/shell-contract-router.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,kBAAkB,GAC3B;IAAE,IAAI,EAAE,aAAa,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,GACxC;IAAE,IAAI,EAAE,YAAY,CAAC;IAAC,OAAO,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,SAAS,MAAM,EAAE,CAAA;CAAE,GAChE;IAAE,IAAI,EAAE,eAAe,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,GAC1C;IAAE,IAAI,EAAE,aAAa,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,CAAC;AAuS1C,wBAAgB,kBAAkB,CACjC,OAAO,EAAE,MAAM,EACf,QAAQ,GAAE,MAAM,CAAC,QAA2B,EAC5C,OAAO,CAAC,EAAE;IAAE,YAAY,CAAC,EAAE,OAAO,CAAA;CAAE,GAClC,kBAAkB,CAwDpB","sourcesContent":["export type ShellContractRoute =\n\t| { kind: \"passthrough\"; command: string }\n\t| { kind: \"powershell\"; command: string; argv: readonly string[] }\n\t| { kind: \"python-engine\"; command: string }\n\t| { kind: \"unsupported\"; error: string };\n\nconst STATE_MUTATOR_BUILTINS = new Set([\"cd\", \"export\", \"unset\"]);\n\ninterface TokenizeResult {\n\tok: boolean;\n\targv?: string[];\n\terror?: string;\n}\n\nconst BLOCKED_NESTED_SHELLS = new Set([\n\t\"bash\",\n\t\"sh\",\n\t\"zsh\",\n\t\"fish\",\n\t\"cmd\",\n\t\"cmd.exe\",\n\t\"powershell\",\n\t\"powershell.exe\",\n\t\"pwsh\",\n\t\"pwsh.exe\",\n\t\"wsl\",\n\t\"wsl.exe\",\n]);\nconst UNSUPPORTED_OPERATOR_MESSAGE =\n\t\"Unsupported Bash construct on Windows. Use one simple command per call; pipelines, redirection, command substitution, variable expansion, shell chaining, and nested shells are not translated.\";\n\nfunction tokenizePortableCommand(command: string): TokenizeResult {\n\tconst argv: string[] = [];\n\tlet token = \"\";\n\tlet tokenStarted = false;\n\tlet quote: \"single\" | \"double\" | undefined;\n\tlet escaping = false;\n\n\tconst finishToken = () => {\n\t\tif (!tokenStarted) return;\n\t\targv.push(token);\n\t\ttoken = \"\";\n\t\ttokenStarted = false;\n\t};\n\n\tconst source = command.trim();\n\tfor (let index = 0; index < source.length; index++) {\n\t\tconst character = source[index];\n\t\tconst nextCharacter = source[index + 1];\n\t\tif (escaping) {\n\t\t\ttoken += character;\n\t\t\ttokenStarted = true;\n\t\t\tescaping = false;\n\t\t\tcontinue;\n\t\t}\n\t\tif (quote === \"single\") {\n\t\t\tif (character === \"'\") quote = undefined;\n\t\t\telse token += character;\n\t\t\ttokenStarted = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (quote === \"double\") {\n\t\t\tif (character === '\"') {\n\t\t\t\tquote = undefined;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (character === \"\\\\\") {\n\t\t\t\tif (nextCharacter && '\"$`\\\\'.includes(nextCharacter)) {\n\t\t\t\t\ttoken += nextCharacter;\n\t\t\t\t\ttokenStarted = true;\n\t\t\t\t\tindex++;\n\t\t\t\t} else {\n\t\t\t\t\ttoken += character;\n\t\t\t\t\ttokenStarted = true;\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (character === \"$\" || character === \"`\") {\n\t\t\t\treturn { ok: false, error: UNSUPPORTED_OPERATOR_MESSAGE };\n\t\t\t}\n\t\t\ttoken += character;\n\t\t\ttokenStarted = true;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (character === \"'\") {\n\t\t\tquote = \"single\";\n\t\t\ttokenStarted = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (character === '\"') {\n\t\t\tquote = \"double\";\n\t\t\ttokenStarted = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (character === \"\\\\\") {\n\t\t\tif (/^[A-Za-z]:/u.test(token) || token.startsWith(\"\\\\\\\\\")) {\n\t\t\t\ttoken += character;\n\t\t\t\ttokenStarted = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (token === \"\" && nextCharacter === \"\\\\\") {\n\t\t\t\ttoken = \"\\\\\\\\\";\n\t\t\t\ttokenStarted = true;\n\t\t\t\tindex++;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tescaping = true;\n\t\t\ttokenStarted = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (/\\s/u.test(character)) {\n\t\t\tfinishToken();\n\t\t\tcontinue;\n\t\t}\n\t\tif (\"|><&;\\n\\r$`(){}*?[]\".includes(character) || character === \"#\" || (character === \"~\" && token === \"\")) {\n\t\t\treturn { ok: false, error: UNSUPPORTED_OPERATOR_MESSAGE };\n\t\t}\n\t\ttoken += character;\n\t\ttokenStarted = true;\n\t}\n\n\tif (escaping) return { ok: false, error: \"Unsupported trailing escape in Bash-like command.\" };\n\tif (quote) return { ok: false, error: \"Unclosed quote in Bash-like command.\" };\n\tfinishToken();\n\treturn argv.length > 0 ? { ok: true, argv } : { ok: false, error: \"Shell command is empty.\" };\n}\n\nfunction quotePowerShell(value: string): string {\n\treturn `'${value.replaceAll(\"'\", \"''\")}'`;\n}\n\nfunction powershellArray(values: readonly string[]): string {\n\treturn `@(${values.map(quotePowerShell).join(\", \")})`;\n}\n\nfunction externalCommand(argv: readonly string[]): string {\n\tconst invocation = `& ${argv.map(quotePowerShell).join(\" \")}`;\n\treturn `${invocation}\\nif ($null -ne $LASTEXITCODE) { exit $LASTEXITCODE }\\nif (-not $?) { exit 1 }`;\n}\n\nfunction parseFlags(\n\targv: readonly string[],\n\tallowedFlags: ReadonlySet<string>,\n): { flags: Set<string>; operands: string[] } | undefined {\n\tconst flags = new Set<string>();\n\tconst operands: string[] = [];\n\tlet optionsEnded = false;\n\tfor (const value of argv) {\n\t\tif (!optionsEnded && value === \"--\") {\n\t\t\toptionsEnded = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (!optionsEnded && value.startsWith(\"-\") && value !== \"-\") {\n\t\t\tif (!allowedFlags.has(value)) return undefined;\n\t\t\tflags.add(value);\n\t\t\tcontinue;\n\t\t}\n\t\toperands.push(value);\n\t}\n\treturn { flags, operands };\n}\n\nfunction routeLs(argv: readonly string[]): string | undefined {\n\tconst parsed = parseFlags(argv.slice(1), new Set([\"-a\", \"-A\", \"-l\", \"-1\", \"-la\", \"-al\"]));\n\tif (!parsed || parsed.operands.length > 1) return undefined;\n\tconst target = parsed.operands[0] ?? \".\";\n\tconst includeHidden = [...parsed.flags].some((flag) => flag.includes(\"a\") || flag.includes(\"A\"));\n\tconst hiddenFilter = includeHidden ? \"\" : \" | Where-Object { -not $_.Name.StartsWith('.') }\";\n\treturn `[string[]]$items = @(Get-ChildItem -LiteralPath ${quotePowerShell(target)}${includeHidden ? \" -Force\" : \"\"} -ErrorAction Stop${hiddenFilter} | ForEach-Object { if ($_.PSIsContainer) { $_.Name + '/' } else { $_.Name } }); [Array]::Sort($items, [StringComparer]::Ordinal); $items`;\n}\n\nfunction routeCat(argv: readonly string[]): string | undefined {\n\tconst parsed = parseFlags(argv.slice(1), new Set([\"--\"]));\n\tif (!parsed || parsed.operands.length === 0) return undefined;\n\treturn `foreach ($path in ${powershellArray(parsed.operands)}) { [Console]::Out.Write([IO.File]::ReadAllText($path)) }`;\n}\n\nfunction routeHeadOrTail(argv: readonly string[], tail: boolean): string | undefined {\n\tlet count = 10;\n\tlet operands = argv.slice(1);\n\tif (operands[0] === \"-n\") {\n\t\tconst parsedCount = Number(operands[1]);\n\t\tif (!Number.isInteger(parsedCount) || parsedCount < 0) return undefined;\n\t\tcount = parsedCount;\n\t\toperands = operands.slice(2);\n\t}\n\tif (operands.length !== 1 || operands[0].startsWith(\"-\")) return undefined;\n\treturn `Get-Content -LiteralPath ${quotePowerShell(operands[0])} ${tail ? \"-Tail\" : \"-TotalCount\"} ${count} -ErrorAction Stop`;\n}\n\nfunction routeGrep(argv: readonly string[]): string | undefined {\n\tif (argv.length !== 3 || argv[1].startsWith(\"-\") || argv[2].startsWith(\"-\")) return undefined;\n\treturn `[string[]]$matches = @(Select-String -LiteralPath ${quotePowerShell(argv[2])} -Pattern ${quotePowerShell(argv[1])} -CaseSensitive -ErrorAction Stop | ForEach-Object { $_.Line }); if ($matches.Count -eq 0) { exit 1 }; $matches`;\n}\n\nfunction routeFind(argv: readonly string[]): string | undefined {\n\tlet searchPath = \".\";\n\tlet type: \"File\" | \"Directory\" | undefined;\n\tlet filter: string | undefined;\n\tlet index = 1;\n\tif (argv[index] && !argv[index].startsWith(\"-\")) searchPath = argv[index++];\n\twhile (index < argv.length) {\n\t\tconst option = argv[index++];\n\t\tif (option === \"-type\" && (argv[index] === \"f\" || argv[index] === \"d\")) {\n\t\t\ttype = argv[index++] === \"f\" ? \"File\" : \"Directory\";\n\t\t\tcontinue;\n\t\t}\n\t\tif (option === \"-name\" && argv[index]) {\n\t\t\tfilter = argv[index++];\n\t\t\tcontinue;\n\t\t}\n\t\treturn undefined;\n\t}\n\tconst typeFlag = type ? ` -${type}` : \"\";\n\tconst filterFlag = filter ? ` -Filter ${quotePowerShell(filter)}` : \"\";\n\treturn `[string[]]$paths = @(Get-ChildItem -LiteralPath ${quotePowerShell(searchPath)} -Recurse -Force${typeFlag}${filterFlag} -ErrorAction Stop | ForEach-Object { $_.FullName.Replace('\\\\', '/') }); [Array]::Sort($paths, [StringComparer]::Ordinal); $paths`;\n}\n\nfunction routeRemove(argv: readonly string[]): string | undefined {\n\tconst parsed = parseFlags(argv.slice(1), new Set([\"-f\", \"-r\", \"-rf\", \"-fr\"]));\n\tif (!parsed || parsed.operands.length === 0) return undefined;\n\tconst recursive = [...parsed.flags].some((flag) => flag.includes(\"r\"));\n\tconst force = [...parsed.flags].some((flag) => flag.includes(\"f\"));\n\treturn `foreach ($path in ${powershellArray(parsed.operands)}) { if (Test-Path -LiteralPath $path) { Remove-Item -LiteralPath $path -Force${recursive ? \" -Recurse\" : \"\"} -ErrorAction Stop }${force ? \"\" : ' else { throw \"rm: path not found: $path\" }'} }`;\n}\n\nfunction routeCopyOrMove(argv: readonly string[], move: boolean): string | undefined {\n\tconst parsed = parseFlags(argv.slice(1), move ? new Set<string>() : new Set([\"-r\", \"-R\"]));\n\tif (!parsed || parsed.operands.length !== 2) return undefined;\n\tconst [source, destination] = parsed.operands;\n\tconst recurse = !move && parsed.flags.size > 0 ? \" -Recurse\" : \"\";\n\tconst rejectDirectoryWithoutRecursion =\n\t\t!move && parsed.flags.size === 0\n\t\t\t? `$sourceItem = Get-Item -LiteralPath ${quotePowerShell(source)} -Force -ErrorAction Stop; if ($sourceItem.PSIsContainer) { throw 'cp: source is a directory; use -r' }; `\n\t\t\t: \"\";\n\treturn `${rejectDirectoryWithoutRecursion}${move ? \"Move-Item\" : \"Copy-Item\"} -LiteralPath ${quotePowerShell(source)} -Destination ${quotePowerShell(destination)}${recurse} -ErrorAction Stop`;\n}\n\nfunction routeMkdir(argv: readonly string[]): string | undefined {\n\tconst parsed = parseFlags(argv.slice(1), new Set([\"-p\"]));\n\tif (!parsed || parsed.operands.length === 0) return undefined;\n\treturn `${powershellArray(parsed.operands)} | ForEach-Object { New-Item -ItemType Directory -Path $_${parsed.flags.has(\"-p\") ? \" -Force\" : \"\"} -ErrorAction Stop | Out-Null }`;\n}\n\nfunction routeTouch(argv: readonly string[]): string | undefined {\n\tconst parsed = parseFlags(argv.slice(1), new Set());\n\tif (!parsed || parsed.operands.length === 0) return undefined;\n\treturn `${powershellArray(parsed.operands)} | ForEach-Object { if (Test-Path -LiteralPath $_) { (Get-Item -LiteralPath $_ -ErrorAction Stop).LastWriteTime = Get-Date } else { New-Item -ItemType File -Path $_ -ErrorAction Stop | Out-Null } }`;\n}\n\nfunction routeBuiltIn(argv: readonly string[]): string | undefined {\n\tconst command = argv[0].toLowerCase();\n\tif (command === \"pwd\" && argv.length === 1) return \"(Get-Location).Path\";\n\tif (command === \"echo\") {\n\t\tlet valueIndex = 1;\n\t\twhile (/^-n+$/u.test(argv[valueIndex] ?? \"\")) valueIndex++;\n\t\tif (/^-[neE]+$/u.test(argv[valueIndex] ?? \"\") && /[eE]/u.test(argv[valueIndex] ?? \"\")) return undefined;\n\t\tconst method = valueIndex > 1 ? \"Write\" : \"WriteLine\";\n\t\treturn `[Console]::Out.${method}((${powershellArray(argv.slice(valueIndex))} -join ' '))`;\n\t}\n\tif (command === \"true\" && argv.length === 1) return \"exit 0\";\n\tif (command === \"false\" && argv.length === 1) return \"exit 1\";\n\tif (command === \"which\" && argv.length === 2) {\n\t\treturn `(Get-Command -Name ${quotePowerShell(argv[1])} -CommandType Application -ErrorAction Stop).Source`;\n\t}\n\tif (command === \"ls\") return routeLs(argv);\n\tif (command === \"cat\") return routeCat(argv);\n\tif (command === \"head\") return routeHeadOrTail(argv, false);\n\tif (command === \"tail\") return routeHeadOrTail(argv, true);\n\tif (command === \"grep\") return routeGrep(argv);\n\tif (command === \"find\") return routeFind(argv);\n\tif (command === \"rm\") return routeRemove(argv);\n\tif (command === \"cp\") return routeCopyOrMove(argv, false);\n\tif (command === \"mv\") return routeCopyOrMove(argv, true);\n\tif (command === \"mkdir\") return routeMkdir(argv);\n\tif (command === \"touch\") return routeTouch(argv);\n\treturn undefined;\n}\n\nconst ROUTED_BUILTIN_NAMES = new Set([\n\t\"pwd\",\n\t\"echo\",\n\t\"true\",\n\t\"false\",\n\t\"which\",\n\t\"ls\",\n\t\"cat\",\n\t\"head\",\n\t\"tail\",\n\t\"grep\",\n\t\"find\",\n\t\"rm\",\n\t\"cp\",\n\t\"mv\",\n\t\"mkdir\",\n\t\"touch\",\n]);\n\nexport function routeShellContract(\n\tcommand: string,\n\tplatform: NodeJS.Platform = process.platform,\n\toptions?: { pythonEngine?: boolean },\n): ShellContractRoute {\n\tif (platform !== \"win32\") return { kind: \"passthrough\", command };\n\tconst pythonEngine = options?.pythonEngine === true;\n\tconst tokenized = tokenizePortableCommand(command);\n\n\t// Complex constructs (pipelines, redirection, expansion, quoting the tokenizer refuses, …) are\n\t// exactly the grammar the Python engine owns; with the engine off this is the original\n\t// fail-closed floor verbatim.\n\tif (!tokenized.ok || !tokenized.argv) {\n\t\tif (pythonEngine) return { kind: \"python-engine\", command };\n\t\treturn { kind: \"unsupported\", error: tokenized.error ?? UNSUPPORTED_OPERATOR_MESSAGE };\n\t}\n\n\tconst argv = tokenized.argv;\n\tconst commandName = argv[0].toLowerCase();\n\n\t// Inline env assignments (`NAME=value [cmd]`) are a state-mutating/expansion form the engine\n\t// supports (§2.1); with the engine off this is the original fail-closed floor verbatim.\n\tif (/^[A-Za-z_][A-Za-z0-9_]*=/u.test(argv[0])) {\n\t\tif (pythonEngine) return { kind: \"python-engine\", command };\n\t\treturn {\n\t\t\tkind: \"unsupported\",\n\t\t\terror: \"Inline environment assignments are not supported. Configure the environment outside the shell command.\",\n\t\t};\n\t}\n\n\t// State mutators route to the engine unconditionally when it is enabled: the engine is the\n\t// sole state owner (D4), so `cd`/`export`/`unset` never execute against the PS floor.\n\tif (pythonEngine && STATE_MUTATOR_BUILTINS.has(commandName)) {\n\t\treturn { kind: \"python-engine\", command };\n\t}\n\n\tif (BLOCKED_NESTED_SHELLS.has(commandName)) {\n\t\treturn {\n\t\t\tkind: \"unsupported\",\n\t\t\terror: \"Nested shell execution is not supported by the Windows shell contract router.\",\n\t\t};\n\t}\n\tconst builtIn = routeBuiltIn(argv);\n\tif (builtIn) return { kind: \"powershell\", command: builtIn, argv };\n\tif (ROUTED_BUILTIN_NAMES.has(commandName)) {\n\t\t// The PS floor rejected the FORM (flags/argument shape); the engine supports the fuller\n\t\t// flag set for the same builtin (§2.2).\n\t\tif (pythonEngine) return { kind: \"python-engine\", command };\n\t\treturn {\n\t\t\tkind: \"unsupported\",\n\t\t\terror: `Unsupported ${argv[0]} form on Windows. Use a simpler Bash-like form or Pi's dedicated read/search/edit tools.`,\n\t\t};\n\t}\n\tif (commandName.endsWith(\".sh\") || commandName.includes(\"/bin/\")) {\n\t\treturn {\n\t\t\tkind: \"unsupported\",\n\t\t\terror: \"POSIX shell scripts are not supported by the Windows shell contract router.\",\n\t\t};\n\t}\n\treturn { kind: \"powershell\", command: externalCommand(argv), argv };\n}\n"]}
@@ -1,3 +1,4 @@
1
+ const STATE_MUTATOR_BUILTINS = new Set(["cd", "export", "unset"]);
1
2
  const BLOCKED_NESTED_SHELLS = new Set([
2
3
  "bash",
3
4
  "sh",
@@ -26,7 +27,10 @@ function tokenizePortableCommand(command) {
26
27
  token = "";
27
28
  tokenStarted = false;
28
29
  };
29
- for (const character of command.trim()) {
30
+ const source = command.trim();
31
+ for (let index = 0; index < source.length; index++) {
32
+ const character = source[index];
33
+ const nextCharacter = source[index + 1];
30
34
  if (escaping) {
31
35
  token += character;
32
36
  tokenStarted = true;
@@ -47,7 +51,15 @@ function tokenizePortableCommand(command) {
47
51
  continue;
48
52
  }
49
53
  if (character === "\\") {
50
- escaping = true;
54
+ if (nextCharacter && '"$`\\'.includes(nextCharacter)) {
55
+ token += nextCharacter;
56
+ tokenStarted = true;
57
+ index++;
58
+ }
59
+ else {
60
+ token += character;
61
+ tokenStarted = true;
62
+ }
51
63
  continue;
52
64
  }
53
65
  if (character === "$" || character === "`") {
@@ -68,6 +80,17 @@ function tokenizePortableCommand(command) {
68
80
  continue;
69
81
  }
70
82
  if (character === "\\") {
83
+ if (/^[A-Za-z]:/u.test(token) || token.startsWith("\\\\")) {
84
+ token += character;
85
+ tokenStarted = true;
86
+ continue;
87
+ }
88
+ if (token === "" && nextCharacter === "\\") {
89
+ token = "\\\\";
90
+ tokenStarted = true;
91
+ index++;
92
+ continue;
93
+ }
71
94
  escaping = true;
72
95
  tokenStarted = true;
73
96
  continue;
@@ -76,7 +99,7 @@ function tokenizePortableCommand(command) {
76
99
  finishToken();
77
100
  continue;
78
101
  }
79
- if ("|><&;\n\r$`()".includes(character) || character === "#") {
102
+ if ("|><&;\n\r$`(){}*?[]".includes(character) || character === "#" || (character === "~" && token === "")) {
80
103
  return { ok: false, error: UNSUPPORTED_OPERATOR_MESSAGE };
81
104
  }
82
105
  token += character;
@@ -123,13 +146,15 @@ function routeLs(argv) {
123
146
  if (!parsed || parsed.operands.length > 1)
124
147
  return undefined;
125
148
  const target = parsed.operands[0] ?? ".";
126
- return `[string[]]$items = @(Get-ChildItem -LiteralPath ${quotePowerShell(target)} -Force -ErrorAction Stop | ForEach-Object { if ($_.PSIsContainer) { $_.Name + '/' } else { $_.Name } }); [Array]::Sort($items, [StringComparer]::Ordinal); $items`;
149
+ const includeHidden = [...parsed.flags].some((flag) => flag.includes("a") || flag.includes("A"));
150
+ const hiddenFilter = includeHidden ? "" : " | Where-Object { -not $_.Name.StartsWith('.') }";
151
+ return `[string[]]$items = @(Get-ChildItem -LiteralPath ${quotePowerShell(target)}${includeHidden ? " -Force" : ""} -ErrorAction Stop${hiddenFilter} | ForEach-Object { if ($_.PSIsContainer) { $_.Name + '/' } else { $_.Name } }); [Array]::Sort($items, [StringComparer]::Ordinal); $items`;
127
152
  }
128
153
  function routeCat(argv) {
129
154
  const parsed = parseFlags(argv.slice(1), new Set(["--"]));
130
155
  if (!parsed || parsed.operands.length === 0)
131
156
  return undefined;
132
- return `Get-Content -LiteralPath ${powershellArray(parsed.operands)} -Raw -ErrorAction Stop`;
157
+ return `foreach ($path in ${powershellArray(parsed.operands)}) { [Console]::Out.Write([IO.File]::ReadAllText($path)) }`;
133
158
  }
134
159
  function routeHeadOrTail(argv, tail) {
135
160
  let count = 10;
@@ -148,7 +173,7 @@ function routeHeadOrTail(argv, tail) {
148
173
  function routeGrep(argv) {
149
174
  if (argv.length !== 3 || argv[1].startsWith("-") || argv[2].startsWith("-"))
150
175
  return undefined;
151
- return `Select-String -LiteralPath ${quotePowerShell(argv[2])} -SimpleMatch -Pattern ${quotePowerShell(argv[1])} -ErrorAction Stop | ForEach-Object { $_.Line }`;
176
+ return `[string[]]$matches = @(Select-String -LiteralPath ${quotePowerShell(argv[2])} -Pattern ${quotePowerShell(argv[1])} -CaseSensitive -ErrorAction Stop | ForEach-Object { $_.Line }); if ($matches.Count -eq 0) { exit 1 }; $matches`;
152
177
  }
153
178
  function routeFind(argv) {
154
179
  let searchPath = ".";
@@ -178,7 +203,8 @@ function routeRemove(argv) {
178
203
  if (!parsed || parsed.operands.length === 0)
179
204
  return undefined;
180
205
  const recursive = [...parsed.flags].some((flag) => flag.includes("r"));
181
- return `Remove-Item -LiteralPath ${powershellArray(parsed.operands)} -Force${recursive ? " -Recurse" : ""} -ErrorAction Stop`;
206
+ const force = [...parsed.flags].some((flag) => flag.includes("f"));
207
+ return `foreach ($path in ${powershellArray(parsed.operands)}) { if (Test-Path -LiteralPath $path) { Remove-Item -LiteralPath $path -Force${recursive ? " -Recurse" : ""} -ErrorAction Stop }${force ? "" : ' else { throw "rm: path not found: $path" }'} }`;
182
208
  }
183
209
  function routeCopyOrMove(argv, move) {
184
210
  const parsed = parseFlags(argv.slice(1), move ? new Set() : new Set(["-r", "-R"]));
@@ -186,13 +212,16 @@ function routeCopyOrMove(argv, move) {
186
212
  return undefined;
187
213
  const [source, destination] = parsed.operands;
188
214
  const recurse = !move && parsed.flags.size > 0 ? " -Recurse" : "";
189
- return `${move ? "Move-Item" : "Copy-Item"} -LiteralPath ${quotePowerShell(source)} -Destination ${quotePowerShell(destination)}${recurse} -ErrorAction Stop`;
215
+ const rejectDirectoryWithoutRecursion = !move && parsed.flags.size === 0
216
+ ? `$sourceItem = Get-Item -LiteralPath ${quotePowerShell(source)} -Force -ErrorAction Stop; if ($sourceItem.PSIsContainer) { throw 'cp: source is a directory; use -r' }; `
217
+ : "";
218
+ return `${rejectDirectoryWithoutRecursion}${move ? "Move-Item" : "Copy-Item"} -LiteralPath ${quotePowerShell(source)} -Destination ${quotePowerShell(destination)}${recurse} -ErrorAction Stop`;
190
219
  }
191
220
  function routeMkdir(argv) {
192
221
  const parsed = parseFlags(argv.slice(1), new Set(["-p"]));
193
222
  if (!parsed || parsed.operands.length === 0)
194
223
  return undefined;
195
- return `${powershellArray(parsed.operands)} | ForEach-Object { New-Item -ItemType Directory -Path $_ -Force -ErrorAction Stop | Out-Null }`;
224
+ return `${powershellArray(parsed.operands)} | ForEach-Object { New-Item -ItemType Directory -Path $_${parsed.flags.has("-p") ? " -Force" : ""} -ErrorAction Stop | Out-Null }`;
196
225
  }
197
226
  function routeTouch(argv) {
198
227
  const parsed = parseFlags(argv.slice(1), new Set());
@@ -204,8 +233,15 @@ function routeBuiltIn(argv) {
204
233
  const command = argv[0].toLowerCase();
205
234
  if (command === "pwd" && argv.length === 1)
206
235
  return "(Get-Location).Path";
207
- if (command === "echo")
208
- return `[Console]::Out.WriteLine((${powershellArray(argv.slice(1))} -join ' '))`;
236
+ if (command === "echo") {
237
+ let valueIndex = 1;
238
+ while (/^-n+$/u.test(argv[valueIndex] ?? ""))
239
+ valueIndex++;
240
+ if (/^-[neE]+$/u.test(argv[valueIndex] ?? "") && /[eE]/u.test(argv[valueIndex] ?? ""))
241
+ return undefined;
242
+ const method = valueIndex > 1 ? "Write" : "WriteLine";
243
+ return `[Console]::Out.${method}((${powershellArray(argv.slice(valueIndex))} -join ' '))`;
244
+ }
209
245
  if (command === "true" && argv.length === 1)
210
246
  return "exit 0";
211
247
  if (command === "false" && argv.length === 1)
@@ -255,20 +291,36 @@ const ROUTED_BUILTIN_NAMES = new Set([
255
291
  "mkdir",
256
292
  "touch",
257
293
  ]);
258
- export function routeShellContract(command, platform = process.platform) {
294
+ export function routeShellContract(command, platform = process.platform, options) {
259
295
  if (platform !== "win32")
260
296
  return { kind: "passthrough", command };
297
+ const pythonEngine = options?.pythonEngine === true;
261
298
  const tokenized = tokenizePortableCommand(command);
262
- if (!tokenized.ok || !tokenized.argv)
299
+ // Complex constructs (pipelines, redirection, expansion, quoting the tokenizer refuses, …) are
300
+ // exactly the grammar the Python engine owns; with the engine off this is the original
301
+ // fail-closed floor verbatim.
302
+ if (!tokenized.ok || !tokenized.argv) {
303
+ if (pythonEngine)
304
+ return { kind: "python-engine", command };
263
305
  return { kind: "unsupported", error: tokenized.error ?? UNSUPPORTED_OPERATOR_MESSAGE };
306
+ }
264
307
  const argv = tokenized.argv;
265
308
  const commandName = argv[0].toLowerCase();
309
+ // Inline env assignments (`NAME=value [cmd]`) are a state-mutating/expansion form the engine
310
+ // supports (§2.1); with the engine off this is the original fail-closed floor verbatim.
266
311
  if (/^[A-Za-z_][A-Za-z0-9_]*=/u.test(argv[0])) {
312
+ if (pythonEngine)
313
+ return { kind: "python-engine", command };
267
314
  return {
268
315
  kind: "unsupported",
269
316
  error: "Inline environment assignments are not supported. Configure the environment outside the shell command.",
270
317
  };
271
318
  }
319
+ // State mutators route to the engine unconditionally when it is enabled: the engine is the
320
+ // sole state owner (D4), so `cd`/`export`/`unset` never execute against the PS floor.
321
+ if (pythonEngine && STATE_MUTATOR_BUILTINS.has(commandName)) {
322
+ return { kind: "python-engine", command };
323
+ }
272
324
  if (BLOCKED_NESTED_SHELLS.has(commandName)) {
273
325
  return {
274
326
  kind: "unsupported",
@@ -279,6 +331,10 @@ export function routeShellContract(command, platform = process.platform) {
279
331
  if (builtIn)
280
332
  return { kind: "powershell", command: builtIn, argv };
281
333
  if (ROUTED_BUILTIN_NAMES.has(commandName)) {
334
+ // The PS floor rejected the FORM (flags/argument shape); the engine supports the fuller
335
+ // flag set for the same builtin (§2.2).
336
+ if (pythonEngine)
337
+ return { kind: "python-engine", command };
282
338
  return {
283
339
  kind: "unsupported",
284
340
  error: `Unsupported ${argv[0]} form on Windows. Use a simpler Bash-like form or Pi's dedicated read/search/edit tools.`,
@@ -1 +1 @@
1
- {"version":3,"file":"shell-contract-router.js","sourceRoot":"","sources":["../../../src/core/tools/shell-contract-router.ts"],"names":[],"mappings":"AAWA,MAAM,qBAAqB,GAAG,IAAI,GAAG,CAAC;IACrC,MAAM;IACN,IAAI;IACJ,KAAK;IAC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"powershell\"; command: string; argv: readonly string[] }\n\t| { kind: \"unsupported\"; error: string };\n\ninterface TokenizeResult {\n\tok: boolean;\n\targv?: string[];\n\terror?: string;\n}\n\nconst BLOCKED_NESTED_SHELLS = new Set([\n\t\"bash\",\n\t\"sh\",\n\t\"zsh\",\n\t\"fish\",\n\t\"cmd\",\n\t\"cmd.exe\",\n\t\"powershell\",\n\t\"powershell.exe\",\n\t\"pwsh\",\n\t\"pwsh.exe\",\n\t\"wsl\",\n\t\"wsl.exe\",\n]);\nconst UNSUPPORTED_OPERATOR_MESSAGE =\n\t\"Unsupported Bash construct on Windows. Use one simple command per call; pipelines, redirection, command substitution, variable expansion, shell chaining, and nested shells are not translated.\";\n\nfunction tokenizePortableCommand(command: string): TokenizeResult {\n\tconst argv: string[] = [];\n\tlet token = \"\";\n\tlet tokenStarted = false;\n\tlet quote: \"single\" | \"double\" | undefined;\n\tlet escaping = false;\n\n\tconst finishToken = () => {\n\t\tif (!tokenStarted) return;\n\t\targv.push(token);\n\t\ttoken = \"\";\n\t\ttokenStarted = false;\n\t};\n\n\tfor (const character of command.trim()) {\n\t\tif (escaping) {\n\t\t\ttoken += character;\n\t\t\ttokenStarted = true;\n\t\t\tescaping = false;\n\t\t\tcontinue;\n\t\t}\n\t\tif (quote === \"single\") {\n\t\t\tif (character === \"'\") quote = undefined;\n\t\t\telse token += character;\n\t\t\ttokenStarted = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (quote === \"double\") {\n\t\t\tif (character === '\"') {\n\t\t\t\tquote = undefined;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (character === \"\\\\\") {\n\t\t\t\tescaping = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (character === \"$\" || character === \"`\") {\n\t\t\t\treturn { ok: false, error: UNSUPPORTED_OPERATOR_MESSAGE };\n\t\t\t}\n\t\t\ttoken += character;\n\t\t\ttokenStarted = true;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (character === \"'\") {\n\t\t\tquote = \"single\";\n\t\t\ttokenStarted = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (character === '\"') {\n\t\t\tquote = \"double\";\n\t\t\ttokenStarted = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (character === \"\\\\\") {\n\t\t\tescaping = true;\n\t\t\ttokenStarted = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (/\\s/u.test(character)) {\n\t\t\tfinishToken();\n\t\t\tcontinue;\n\t\t}\n\t\tif (\"|><&;\\n\\r$`()\".includes(character) || character === \"#\") {\n\t\t\treturn { ok: false, error: UNSUPPORTED_OPERATOR_MESSAGE };\n\t\t}\n\t\ttoken += character;\n\t\ttokenStarted = true;\n\t}\n\n\tif (escaping) return { ok: false, error: \"Unsupported trailing escape in Bash-like command.\" };\n\tif (quote) return { ok: false, error: \"Unclosed quote in Bash-like command.\" };\n\tfinishToken();\n\treturn argv.length > 0 ? { ok: true, argv } : { ok: false, error: \"Shell command is empty.\" };\n}\n\nfunction quotePowerShell(value: string): string {\n\treturn `'${value.replaceAll(\"'\", \"''\")}'`;\n}\n\nfunction powershellArray(values: readonly string[]): string {\n\treturn `@(${values.map(quotePowerShell).join(\", \")})`;\n}\n\nfunction externalCommand(argv: readonly string[]): string {\n\tconst invocation = `& ${argv.map(quotePowerShell).join(\" \")}`;\n\treturn `${invocation}\\nif ($null -ne $LASTEXITCODE) { exit $LASTEXITCODE }\\nif (-not $?) { exit 1 }`;\n}\n\nfunction parseFlags(\n\targv: readonly string[],\n\tallowedFlags: ReadonlySet<string>,\n): { flags: Set<string>; operands: string[] } | undefined {\n\tconst flags = new Set<string>();\n\tconst operands: string[] = [];\n\tlet optionsEnded = false;\n\tfor (const value of argv) {\n\t\tif (!optionsEnded && value === \"--\") {\n\t\t\toptionsEnded = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (!optionsEnded && value.startsWith(\"-\") && value !== \"-\") {\n\t\t\tif (!allowedFlags.has(value)) return undefined;\n\t\t\tflags.add(value);\n\t\t\tcontinue;\n\t\t}\n\t\toperands.push(value);\n\t}\n\treturn { flags, operands };\n}\n\nfunction routeLs(argv: readonly string[]): string | undefined {\n\tconst parsed = parseFlags(argv.slice(1), new Set([\"-a\", \"-A\", \"-l\", \"-1\", \"-la\", \"-al\"]));\n\tif (!parsed || parsed.operands.length > 1) return undefined;\n\tconst target = parsed.operands[0] ?? \".\";\n\treturn `[string[]]$items = @(Get-ChildItem -LiteralPath ${quotePowerShell(target)} -Force -ErrorAction Stop | ForEach-Object { if ($_.PSIsContainer) { $_.Name + '/' } else { $_.Name } }); [Array]::Sort($items, [StringComparer]::Ordinal); $items`;\n}\n\nfunction routeCat(argv: readonly string[]): string | undefined {\n\tconst parsed = parseFlags(argv.slice(1), new Set([\"--\"]));\n\tif (!parsed || parsed.operands.length === 0) return undefined;\n\treturn `Get-Content -LiteralPath ${powershellArray(parsed.operands)} -Raw -ErrorAction Stop`;\n}\n\nfunction routeHeadOrTail(argv: readonly string[], tail: boolean): string | undefined {\n\tlet count = 10;\n\tlet operands = argv.slice(1);\n\tif (operands[0] === \"-n\") {\n\t\tconst parsedCount = Number(operands[1]);\n\t\tif (!Number.isInteger(parsedCount) || parsedCount < 0) return undefined;\n\t\tcount = parsedCount;\n\t\toperands = operands.slice(2);\n\t}\n\tif (operands.length !== 1 || operands[0].startsWith(\"-\")) return undefined;\n\treturn `Get-Content -LiteralPath ${quotePowerShell(operands[0])} ${tail ? \"-Tail\" : \"-TotalCount\"} ${count} -ErrorAction Stop`;\n}\n\nfunction routeGrep(argv: readonly string[]): string | undefined {\n\tif (argv.length !== 3 || argv[1].startsWith(\"-\") || argv[2].startsWith(\"-\")) return undefined;\n\treturn `Select-String -LiteralPath ${quotePowerShell(argv[2])} -SimpleMatch -Pattern ${quotePowerShell(argv[1])} -ErrorAction Stop | ForEach-Object { $_.Line }`;\n}\n\nfunction routeFind(argv: readonly string[]): string | undefined {\n\tlet searchPath = \".\";\n\tlet type: \"File\" | \"Directory\" | undefined;\n\tlet filter: string | undefined;\n\tlet index = 1;\n\tif (argv[index] && !argv[index].startsWith(\"-\")) searchPath = argv[index++];\n\twhile (index < argv.length) {\n\t\tconst option = argv[index++];\n\t\tif (option === \"-type\" && (argv[index] === \"f\" || argv[index] === \"d\")) {\n\t\t\ttype = argv[index++] === \"f\" ? \"File\" : \"Directory\";\n\t\t\tcontinue;\n\t\t}\n\t\tif (option === \"-name\" && argv[index]) {\n\t\t\tfilter = argv[index++];\n\t\t\tcontinue;\n\t\t}\n\t\treturn undefined;\n\t}\n\tconst typeFlag = type ? ` -${type}` : \"\";\n\tconst filterFlag = filter ? ` -Filter ${quotePowerShell(filter)}` : \"\";\n\treturn `[string[]]$paths = @(Get-ChildItem -LiteralPath ${quotePowerShell(searchPath)} -Recurse -Force${typeFlag}${filterFlag} -ErrorAction Stop | ForEach-Object { $_.FullName.Replace('\\\\', '/') }); [Array]::Sort($paths, [StringComparer]::Ordinal); $paths`;\n}\n\nfunction routeRemove(argv: readonly string[]): string | undefined {\n\tconst parsed = parseFlags(argv.slice(1), new Set([\"-f\", \"-r\", \"-rf\", \"-fr\"]));\n\tif (!parsed || parsed.operands.length === 0) return undefined;\n\tconst recursive = [...parsed.flags].some((flag) => flag.includes(\"r\"));\n\treturn `Remove-Item -LiteralPath ${powershellArray(parsed.operands)} -Force${recursive ? \" -Recurse\" : \"\"} -ErrorAction Stop`;\n}\n\nfunction routeCopyOrMove(argv: readonly string[], move: boolean): string | undefined {\n\tconst parsed = parseFlags(argv.slice(1), move ? new Set<string>() : new Set([\"-r\", \"-R\"]));\n\tif (!parsed || parsed.operands.length !== 2) return undefined;\n\tconst [source, destination] = parsed.operands;\n\tconst recurse = !move && parsed.flags.size > 0 ? \" -Recurse\" : \"\";\n\treturn `${move ? \"Move-Item\" : \"Copy-Item\"} -LiteralPath ${quotePowerShell(source)} -Destination ${quotePowerShell(destination)}${recurse} -ErrorAction Stop`;\n}\n\nfunction routeMkdir(argv: readonly string[]): string | undefined {\n\tconst parsed = parseFlags(argv.slice(1), new Set([\"-p\"]));\n\tif (!parsed || parsed.operands.length === 0) return undefined;\n\treturn `${powershellArray(parsed.operands)} | ForEach-Object { New-Item -ItemType Directory -Path $_ -Force -ErrorAction Stop | Out-Null }`;\n}\n\nfunction routeTouch(argv: readonly string[]): string | undefined {\n\tconst parsed = parseFlags(argv.slice(1), new Set());\n\tif (!parsed || parsed.operands.length === 0) return undefined;\n\treturn `${powershellArray(parsed.operands)} | ForEach-Object { if (Test-Path -LiteralPath $_) { (Get-Item -LiteralPath $_ -ErrorAction Stop).LastWriteTime = Get-Date } else { New-Item -ItemType File -Path $_ -ErrorAction Stop | Out-Null } }`;\n}\n\nfunction routeBuiltIn(argv: readonly string[]): string | undefined {\n\tconst command = argv[0].toLowerCase();\n\tif (command === \"pwd\" && argv.length === 1) return \"(Get-Location).Path\";\n\tif (command === \"echo\") return `[Console]::Out.WriteLine((${powershellArray(argv.slice(1))} -join ' '))`;\n\tif (command === \"true\" && argv.length === 1) return \"exit 0\";\n\tif (command === \"false\" && argv.length === 1) return \"exit 1\";\n\tif (command === \"which\" && argv.length === 2) {\n\t\treturn `(Get-Command -Name ${quotePowerShell(argv[1])} -CommandType Application -ErrorAction Stop).Source`;\n\t}\n\tif (command === \"ls\") return routeLs(argv);\n\tif (command === \"cat\") return routeCat(argv);\n\tif (command === \"head\") return routeHeadOrTail(argv, false);\n\tif (command === \"tail\") return routeHeadOrTail(argv, true);\n\tif (command === \"grep\") return routeGrep(argv);\n\tif (command === \"find\") return routeFind(argv);\n\tif (command === \"rm\") return routeRemove(argv);\n\tif (command === \"cp\") return routeCopyOrMove(argv, false);\n\tif (command === \"mv\") return routeCopyOrMove(argv, true);\n\tif (command === \"mkdir\") return routeMkdir(argv);\n\tif (command === \"touch\") return routeTouch(argv);\n\treturn undefined;\n}\n\nconst ROUTED_BUILTIN_NAMES = new Set([\n\t\"pwd\",\n\t\"echo\",\n\t\"true\",\n\t\"false\",\n\t\"which\",\n\t\"ls\",\n\t\"cat\",\n\t\"head\",\n\t\"tail\",\n\t\"grep\",\n\t\"find\",\n\t\"rm\",\n\t\"cp\",\n\t\"mv\",\n\t\"mkdir\",\n\t\"touch\",\n]);\n\nexport function routeShellContract(command: string, platform: NodeJS.Platform = process.platform): ShellContractRoute {\n\tif (platform !== \"win32\") return { kind: \"passthrough\", command };\n\tconst tokenized = tokenizePortableCommand(command);\n\tif (!tokenized.ok || !tokenized.argv)\n\t\treturn { kind: \"unsupported\", error: tokenized.error ?? UNSUPPORTED_OPERATOR_MESSAGE };\n\tconst argv = tokenized.argv;\n\tconst commandName = argv[0].toLowerCase();\n\tif (/^[A-Za-z_][A-Za-z0-9_]*=/u.test(argv[0])) {\n\t\treturn {\n\t\t\tkind: \"unsupported\",\n\t\t\terror: \"Inline environment assignments are not supported. Configure the environment outside the shell command.\",\n\t\t};\n\t}\n\tif (BLOCKED_NESTED_SHELLS.has(commandName)) {\n\t\treturn {\n\t\t\tkind: \"unsupported\",\n\t\t\terror: \"Nested shell execution is not supported by the Windows shell contract router.\",\n\t\t};\n\t}\n\tconst builtIn = routeBuiltIn(argv);\n\tif (builtIn) return { kind: \"powershell\", command: builtIn, argv };\n\tif (ROUTED_BUILTIN_NAMES.has(commandName)) {\n\t\treturn {\n\t\t\tkind: \"unsupported\",\n\t\t\terror: `Unsupported ${argv[0]} form on Windows. Use a simpler Bash-like form or Pi's dedicated read/search/edit tools.`,\n\t\t};\n\t}\n\tif (commandName.endsWith(\".sh\") || commandName.includes(\"/bin/\")) {\n\t\treturn {\n\t\t\tkind: \"unsupported\",\n\t\t\terror: \"POSIX shell scripts are not supported by the Windows shell contract router.\",\n\t\t};\n\t}\n\treturn { kind: \"powershell\", command: externalCommand(argv), argv };\n}\n"]}
1
+ {"version":3,"file":"shell-contract-router.js","sourceRoot":"","sources":["../../../src/core/tools/shell-contract-router.ts"],"names":[],"mappings":"AAMA,MAAM,sBAAsB,GAAG,IAAI,GAAG,CAAC,CAAC,IAAI,EAAE,QAAQ,E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AAI,EAAE,aAAa;YACnB,KAAK,EAAE,eAAe,IAAI,CAAC,CAAC,CAAC,0FAA0F;SACvH,CAAC;IACH,CAAC;IACD,IAAI,WAAW,CAAC,QAAQ,CAAC,KAAK,CAAC,IAAI,WAAW,CAAC,QAAQ,CAAC,OAAO,CAAC,EAAE,CAAC;QAClE,OAAO;YACN,IAAI,EAAE,aAAa;YACnB,KAAK,EAAE,6EAA6E;SACpF,CAAC;IACH,CAAC;IACD,OAAO,EAAE,IAAI,EAAE,YAAY,EAAE,OAAO,EAAE,eAAe,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,CAAC;AAAA,CACpE","sourcesContent":["export type ShellContractRoute =\n\t| { kind: \"passthrough\"; command: string }\n\t| { kind: \"powershell\"; command: string; argv: readonly string[] }\n\t| { kind: \"python-engine\"; command: string }\n\t| { kind: \"unsupported\"; error: string };\n\nconst STATE_MUTATOR_BUILTINS = new Set([\"cd\", \"export\", \"unset\"]);\n\ninterface TokenizeResult {\n\tok: boolean;\n\targv?: string[];\n\terror?: string;\n}\n\nconst BLOCKED_NESTED_SHELLS = new Set([\n\t\"bash\",\n\t\"sh\",\n\t\"zsh\",\n\t\"fish\",\n\t\"cmd\",\n\t\"cmd.exe\",\n\t\"powershell\",\n\t\"powershell.exe\",\n\t\"pwsh\",\n\t\"pwsh.exe\",\n\t\"wsl\",\n\t\"wsl.exe\",\n]);\nconst UNSUPPORTED_OPERATOR_MESSAGE =\n\t\"Unsupported Bash construct on Windows. Use one simple command per call; pipelines, redirection, command substitution, variable expansion, shell chaining, and nested shells are not translated.\";\n\nfunction tokenizePortableCommand(command: string): TokenizeResult {\n\tconst argv: string[] = [];\n\tlet token = \"\";\n\tlet tokenStarted = false;\n\tlet quote: \"single\" | \"double\" | undefined;\n\tlet escaping = false;\n\n\tconst finishToken = () => {\n\t\tif (!tokenStarted) return;\n\t\targv.push(token);\n\t\ttoken = \"\";\n\t\ttokenStarted = false;\n\t};\n\n\tconst source = command.trim();\n\tfor (let index = 0; index < source.length; index++) {\n\t\tconst character = source[index];\n\t\tconst nextCharacter = source[index + 1];\n\t\tif (escaping) {\n\t\t\ttoken += character;\n\t\t\ttokenStarted = true;\n\t\t\tescaping = false;\n\t\t\tcontinue;\n\t\t}\n\t\tif (quote === \"single\") {\n\t\t\tif (character === \"'\") quote = undefined;\n\t\t\telse token += character;\n\t\t\ttokenStarted = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (quote === \"double\") {\n\t\t\tif (character === '\"') {\n\t\t\t\tquote = undefined;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (character === \"\\\\\") {\n\t\t\t\tif (nextCharacter && '\"$`\\\\'.includes(nextCharacter)) {\n\t\t\t\t\ttoken += nextCharacter;\n\t\t\t\t\ttokenStarted = true;\n\t\t\t\t\tindex++;\n\t\t\t\t} else {\n\t\t\t\t\ttoken += character;\n\t\t\t\t\ttokenStarted = true;\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (character === \"$\" || character === \"`\") {\n\t\t\t\treturn { ok: false, error: UNSUPPORTED_OPERATOR_MESSAGE };\n\t\t\t}\n\t\t\ttoken += character;\n\t\t\ttokenStarted = true;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (character === \"'\") {\n\t\t\tquote = \"single\";\n\t\t\ttokenStarted = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (character === '\"') {\n\t\t\tquote = \"double\";\n\t\t\ttokenStarted = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (character === \"\\\\\") {\n\t\t\tif (/^[A-Za-z]:/u.test(token) || token.startsWith(\"\\\\\\\\\")) {\n\t\t\t\ttoken += character;\n\t\t\t\ttokenStarted = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (token === \"\" && nextCharacter === \"\\\\\") {\n\t\t\t\ttoken = \"\\\\\\\\\";\n\t\t\t\ttokenStarted = true;\n\t\t\t\tindex++;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tescaping = true;\n\t\t\ttokenStarted = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (/\\s/u.test(character)) {\n\t\t\tfinishToken();\n\t\t\tcontinue;\n\t\t}\n\t\tif (\"|><&;\\n\\r$`(){}*?[]\".includes(character) || character === \"#\" || (character === \"~\" && token === \"\")) {\n\t\t\treturn { ok: false, error: UNSUPPORTED_OPERATOR_MESSAGE };\n\t\t}\n\t\ttoken += character;\n\t\ttokenStarted = true;\n\t}\n\n\tif (escaping) return { ok: false, error: \"Unsupported trailing escape in Bash-like command.\" };\n\tif (quote) return { ok: false, error: \"Unclosed quote in Bash-like command.\" };\n\tfinishToken();\n\treturn argv.length > 0 ? { ok: true, argv } : { ok: false, error: \"Shell command is empty.\" };\n}\n\nfunction quotePowerShell(value: string): string {\n\treturn `'${value.replaceAll(\"'\", \"''\")}'`;\n}\n\nfunction powershellArray(values: readonly string[]): string {\n\treturn `@(${values.map(quotePowerShell).join(\", \")})`;\n}\n\nfunction externalCommand(argv: readonly string[]): string {\n\tconst invocation = `& ${argv.map(quotePowerShell).join(\" \")}`;\n\treturn `${invocation}\\nif ($null -ne $LASTEXITCODE) { exit $LASTEXITCODE }\\nif (-not $?) { exit 1 }`;\n}\n\nfunction parseFlags(\n\targv: readonly string[],\n\tallowedFlags: ReadonlySet<string>,\n): { flags: Set<string>; operands: string[] } | undefined {\n\tconst flags = new Set<string>();\n\tconst operands: string[] = [];\n\tlet optionsEnded = false;\n\tfor (const value of argv) {\n\t\tif (!optionsEnded && value === \"--\") {\n\t\t\toptionsEnded = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (!optionsEnded && value.startsWith(\"-\") && value !== \"-\") {\n\t\t\tif (!allowedFlags.has(value)) return undefined;\n\t\t\tflags.add(value);\n\t\t\tcontinue;\n\t\t}\n\t\toperands.push(value);\n\t}\n\treturn { flags, operands };\n}\n\nfunction routeLs(argv: readonly string[]): string | undefined {\n\tconst parsed = parseFlags(argv.slice(1), new Set([\"-a\", \"-A\", \"-l\", \"-1\", \"-la\", \"-al\"]));\n\tif (!parsed || parsed.operands.length > 1) return undefined;\n\tconst target = parsed.operands[0] ?? \".\";\n\tconst includeHidden = [...parsed.flags].some((flag) => flag.includes(\"a\") || flag.includes(\"A\"));\n\tconst hiddenFilter = includeHidden ? \"\" : \" | Where-Object { -not $_.Name.StartsWith('.') }\";\n\treturn `[string[]]$items = @(Get-ChildItem -LiteralPath ${quotePowerShell(target)}${includeHidden ? \" -Force\" : \"\"} -ErrorAction Stop${hiddenFilter} | ForEach-Object { if ($_.PSIsContainer) { $_.Name + '/' } else { $_.Name } }); [Array]::Sort($items, [StringComparer]::Ordinal); $items`;\n}\n\nfunction routeCat(argv: readonly string[]): string | undefined {\n\tconst parsed = parseFlags(argv.slice(1), new Set([\"--\"]));\n\tif (!parsed || parsed.operands.length === 0) return undefined;\n\treturn `foreach ($path in ${powershellArray(parsed.operands)}) { [Console]::Out.Write([IO.File]::ReadAllText($path)) }`;\n}\n\nfunction routeHeadOrTail(argv: readonly string[], tail: boolean): string | undefined {\n\tlet count = 10;\n\tlet operands = argv.slice(1);\n\tif (operands[0] === \"-n\") {\n\t\tconst parsedCount = Number(operands[1]);\n\t\tif (!Number.isInteger(parsedCount) || parsedCount < 0) return undefined;\n\t\tcount = parsedCount;\n\t\toperands = operands.slice(2);\n\t}\n\tif (operands.length !== 1 || operands[0].startsWith(\"-\")) return undefined;\n\treturn `Get-Content -LiteralPath ${quotePowerShell(operands[0])} ${tail ? \"-Tail\" : \"-TotalCount\"} ${count} -ErrorAction Stop`;\n}\n\nfunction routeGrep(argv: readonly string[]): string | undefined {\n\tif (argv.length !== 3 || argv[1].startsWith(\"-\") || argv[2].startsWith(\"-\")) return undefined;\n\treturn `[string[]]$matches = @(Select-String -LiteralPath ${quotePowerShell(argv[2])} -Pattern ${quotePowerShell(argv[1])} -CaseSensitive -ErrorAction Stop | ForEach-Object { $_.Line }); if ($matches.Count -eq 0) { exit 1 }; $matches`;\n}\n\nfunction routeFind(argv: readonly string[]): string | undefined {\n\tlet searchPath = \".\";\n\tlet type: \"File\" | \"Directory\" | undefined;\n\tlet filter: string | undefined;\n\tlet index = 1;\n\tif (argv[index] && !argv[index].startsWith(\"-\")) searchPath = argv[index++];\n\twhile (index < argv.length) {\n\t\tconst option = argv[index++];\n\t\tif (option === \"-type\" && (argv[index] === \"f\" || argv[index] === \"d\")) {\n\t\t\ttype = argv[index++] === \"f\" ? \"File\" : \"Directory\";\n\t\t\tcontinue;\n\t\t}\n\t\tif (option === \"-name\" && argv[index]) {\n\t\t\tfilter = argv[index++];\n\t\t\tcontinue;\n\t\t}\n\t\treturn undefined;\n\t}\n\tconst typeFlag = type ? ` -${type}` : \"\";\n\tconst filterFlag = filter ? ` -Filter ${quotePowerShell(filter)}` : \"\";\n\treturn `[string[]]$paths = @(Get-ChildItem -LiteralPath ${quotePowerShell(searchPath)} -Recurse -Force${typeFlag}${filterFlag} -ErrorAction Stop | ForEach-Object { $_.FullName.Replace('\\\\', '/') }); [Array]::Sort($paths, [StringComparer]::Ordinal); $paths`;\n}\n\nfunction routeRemove(argv: readonly string[]): string | undefined {\n\tconst parsed = parseFlags(argv.slice(1), new Set([\"-f\", \"-r\", \"-rf\", \"-fr\"]));\n\tif (!parsed || parsed.operands.length === 0) return undefined;\n\tconst recursive = [...parsed.flags].some((flag) => flag.includes(\"r\"));\n\tconst force = [...parsed.flags].some((flag) => flag.includes(\"f\"));\n\treturn `foreach ($path in ${powershellArray(parsed.operands)}) { if (Test-Path -LiteralPath $path) { Remove-Item -LiteralPath $path -Force${recursive ? \" -Recurse\" : \"\"} -ErrorAction Stop }${force ? \"\" : ' else { throw \"rm: path not found: $path\" }'} }`;\n}\n\nfunction routeCopyOrMove(argv: readonly string[], move: boolean): string | undefined {\n\tconst parsed = parseFlags(argv.slice(1), move ? new Set<string>() : new Set([\"-r\", \"-R\"]));\n\tif (!parsed || parsed.operands.length !== 2) return undefined;\n\tconst [source, destination] = parsed.operands;\n\tconst recurse = !move && parsed.flags.size > 0 ? \" -Recurse\" : \"\";\n\tconst rejectDirectoryWithoutRecursion =\n\t\t!move && parsed.flags.size === 0\n\t\t\t? `$sourceItem = Get-Item -LiteralPath ${quotePowerShell(source)} -Force -ErrorAction Stop; if ($sourceItem.PSIsContainer) { throw 'cp: source is a directory; use -r' }; `\n\t\t\t: \"\";\n\treturn `${rejectDirectoryWithoutRecursion}${move ? \"Move-Item\" : \"Copy-Item\"} -LiteralPath ${quotePowerShell(source)} -Destination ${quotePowerShell(destination)}${recurse} -ErrorAction Stop`;\n}\n\nfunction routeMkdir(argv: readonly string[]): string | undefined {\n\tconst parsed = parseFlags(argv.slice(1), new Set([\"-p\"]));\n\tif (!parsed || parsed.operands.length === 0) return undefined;\n\treturn `${powershellArray(parsed.operands)} | ForEach-Object { New-Item -ItemType Directory -Path $_${parsed.flags.has(\"-p\") ? \" -Force\" : \"\"} -ErrorAction Stop | Out-Null }`;\n}\n\nfunction routeTouch(argv: readonly string[]): string | undefined {\n\tconst parsed = parseFlags(argv.slice(1), new Set());\n\tif (!parsed || parsed.operands.length === 0) return undefined;\n\treturn `${powershellArray(parsed.operands)} | ForEach-Object { if (Test-Path -LiteralPath $_) { (Get-Item -LiteralPath $_ -ErrorAction Stop).LastWriteTime = Get-Date } else { New-Item -ItemType File -Path $_ -ErrorAction Stop | Out-Null } }`;\n}\n\nfunction routeBuiltIn(argv: readonly string[]): string | undefined {\n\tconst command = argv[0].toLowerCase();\n\tif (command === \"pwd\" && argv.length === 1) return \"(Get-Location).Path\";\n\tif (command === \"echo\") {\n\t\tlet valueIndex = 1;\n\t\twhile (/^-n+$/u.test(argv[valueIndex] ?? \"\")) valueIndex++;\n\t\tif (/^-[neE]+$/u.test(argv[valueIndex] ?? \"\") && /[eE]/u.test(argv[valueIndex] ?? \"\")) return undefined;\n\t\tconst method = valueIndex > 1 ? \"Write\" : \"WriteLine\";\n\t\treturn `[Console]::Out.${method}((${powershellArray(argv.slice(valueIndex))} -join ' '))`;\n\t}\n\tif (command === \"true\" && argv.length === 1) return \"exit 0\";\n\tif (command === \"false\" && argv.length === 1) return \"exit 1\";\n\tif (command === \"which\" && argv.length === 2) {\n\t\treturn `(Get-Command -Name ${quotePowerShell(argv[1])} -CommandType Application -ErrorAction Stop).Source`;\n\t}\n\tif (command === \"ls\") return routeLs(argv);\n\tif (command === \"cat\") return routeCat(argv);\n\tif (command === \"head\") return routeHeadOrTail(argv, false);\n\tif (command === \"tail\") return routeHeadOrTail(argv, true);\n\tif (command === \"grep\") return routeGrep(argv);\n\tif (command === \"find\") return routeFind(argv);\n\tif (command === \"rm\") return routeRemove(argv);\n\tif (command === \"cp\") return routeCopyOrMove(argv, false);\n\tif (command === \"mv\") return routeCopyOrMove(argv, true);\n\tif (command === \"mkdir\") return routeMkdir(argv);\n\tif (command === \"touch\") return routeTouch(argv);\n\treturn undefined;\n}\n\nconst ROUTED_BUILTIN_NAMES = new Set([\n\t\"pwd\",\n\t\"echo\",\n\t\"true\",\n\t\"false\",\n\t\"which\",\n\t\"ls\",\n\t\"cat\",\n\t\"head\",\n\t\"tail\",\n\t\"grep\",\n\t\"find\",\n\t\"rm\",\n\t\"cp\",\n\t\"mv\",\n\t\"mkdir\",\n\t\"touch\",\n]);\n\nexport function routeShellContract(\n\tcommand: string,\n\tplatform: NodeJS.Platform = process.platform,\n\toptions?: { pythonEngine?: boolean },\n): ShellContractRoute {\n\tif (platform !== \"win32\") return { kind: \"passthrough\", command };\n\tconst pythonEngine = options?.pythonEngine === true;\n\tconst tokenized = tokenizePortableCommand(command);\n\n\t// Complex constructs (pipelines, redirection, expansion, quoting the tokenizer refuses, …) are\n\t// exactly the grammar the Python engine owns; with the engine off this is the original\n\t// fail-closed floor verbatim.\n\tif (!tokenized.ok || !tokenized.argv) {\n\t\tif (pythonEngine) return { kind: \"python-engine\", command };\n\t\treturn { kind: \"unsupported\", error: tokenized.error ?? UNSUPPORTED_OPERATOR_MESSAGE };\n\t}\n\n\tconst argv = tokenized.argv;\n\tconst commandName = argv[0].toLowerCase();\n\n\t// Inline env assignments (`NAME=value [cmd]`) are a state-mutating/expansion form the engine\n\t// supports (§2.1); with the engine off this is the original fail-closed floor verbatim.\n\tif (/^[A-Za-z_][A-Za-z0-9_]*=/u.test(argv[0])) {\n\t\tif (pythonEngine) return { kind: \"python-engine\", command };\n\t\treturn {\n\t\t\tkind: \"unsupported\",\n\t\t\terror: \"Inline environment assignments are not supported. Configure the environment outside the shell command.\",\n\t\t};\n\t}\n\n\t// State mutators route to the engine unconditionally when it is enabled: the engine is the\n\t// sole state owner (D4), so `cd`/`export`/`unset` never execute against the PS floor.\n\tif (pythonEngine && STATE_MUTATOR_BUILTINS.has(commandName)) {\n\t\treturn { kind: \"python-engine\", command };\n\t}\n\n\tif (BLOCKED_NESTED_SHELLS.has(commandName)) {\n\t\treturn {\n\t\t\tkind: \"unsupported\",\n\t\t\terror: \"Nested shell execution is not supported by the Windows shell contract router.\",\n\t\t};\n\t}\n\tconst builtIn = routeBuiltIn(argv);\n\tif (builtIn) return { kind: \"powershell\", command: builtIn, argv };\n\tif (ROUTED_BUILTIN_NAMES.has(commandName)) {\n\t\t// The PS floor rejected the FORM (flags/argument shape); the engine supports the fuller\n\t\t// flag set for the same builtin (§2.2).\n\t\tif (pythonEngine) return { kind: \"python-engine\", command };\n\t\treturn {\n\t\t\tkind: \"unsupported\",\n\t\t\terror: `Unsupported ${argv[0]} form on Windows. Use a simpler Bash-like form or Pi's dedicated read/search/edit tools.`,\n\t\t};\n\t}\n\tif (commandName.endsWith(\".sh\") || commandName.includes(\"/bin/\")) {\n\t\treturn {\n\t\t\tkind: \"unsupported\",\n\t\t\terror: \"POSIX shell scripts are not supported by the Windows shell contract router.\",\n\t\t};\n\t}\n\treturn { kind: \"powershell\", command: externalCommand(argv), argv };\n}\n"]}
@@ -0,0 +1,89 @@
1
+ /**
2
+ * Persistent shell sessions for the bash tool.
3
+ *
4
+ * One long-lived shell process per agent (keyed registry) replaces process-per-command spawning.
5
+ * On Windows every command previously paid a full PowerShell boot; a persistent session pays it
6
+ * once. Shell state (current directory, environment variables) persists across an agent's
7
+ * commands; each key gets an isolated session so concurrently running agents never share state.
8
+ *
9
+ * Protocol: commands stream to the session over stdin and are terminated by a per-command
10
+ * sentinel carrying a random nonce and the exit code. Bash wraps commands in an eval of a quoted
11
+ * heredoc (arbitrary content stays data; syntax errors stay contained in eval); PowerShell runs a
12
+ * ReadLine loop decoding base64 lines (no external binaries involved). On bash, command stderr is
13
+ * merged into stdout at the shell so sentinel ordering is guaranteed on one pipe.
14
+ *
15
+ * PowerShell runs each command as a bare `Invoke-Expression`, NOT piped into `Out-Default`: piping
16
+ * a native command's output into another pipeline stage forces PowerShell's NativeCommandProcessor
17
+ * to capture that child's stdout/stderr into an internal pipe and read it to EOF before the
18
+ * pipeline completes. A detached grandchild that inherited those handles (e.g. `start /b` holding
19
+ * stdio open) then keeps that internal pipe's write end open, so the sentinel — written after the
20
+ * pipeline "completes" — waits for the grandchild to die instead of the direct child. The bare
21
+ * invocation lets a native command's stdout/stderr handles be inherited directly by the child
22
+ * process; the direct child's own exit is what unblocks the sentinel line, exactly like the
23
+ * per-command backend and like bash's stdio inheritance above. The bounded consequence: a native
24
+ * command's stderr no longer merges into the session's stdout pipe (there is no capturing pipeline
25
+ * stage to merge it) — it arrives on the session's own stderr pipe instead, forwarded via
26
+ * `onStderr` -> `onData` same as the shell's own diagnostics. PowerShell 5.1's habit of wrapping
27
+ * redirected stderr text in a `NativeCommandError` record also disappears, which is an accuracy
28
+ * improvement (the raw stderr bytes are reported, not a wrapped/duplicated rendering of them).
29
+ *
30
+ * Kill semantics: timeout/abort/silence kill the WHOLE session process tree (a hung foreground
31
+ * command cannot be killed individually without job control) and the next exec respawns a fresh
32
+ * session, losing accumulated shell state by design. A command that exits the shell itself
33
+ * (`exit 3`) reports the shell's exit code and also respawns lazily afterwards.
34
+ */
35
+ import { type PlatformShellToolName } from "../../utils/shell.ts";
36
+ export interface ShellSessionExecOptions {
37
+ onData: (data: Buffer) => void;
38
+ signal?: AbortSignal;
39
+ /** Wall-clock bound in seconds; when set, a breach kills the session and throws `timeout:<s>`. */
40
+ timeoutSeconds?: number;
41
+ /** Output-silence bound in ms; when set, silence kills the session and throws `silence:<s>`. */
42
+ silenceMs?: number;
43
+ env?: NodeJS.ProcessEnv;
44
+ }
45
+ /**
46
+ * The whole command is heredoc-quoted data: eval keeps syntax errors contained (a raw syntax
47
+ * error on the session's stdin would abort the shell), and the random delimiter makes content
48
+ * collisions with agent output practically impossible. `< /dev/null` gives commands the same
49
+ * EOF-stdin the per-command backend's `stdio: ["ignore", ...]` provided.
50
+ */
51
+ export declare function buildBashWire(command: string, nonce: string, cdTo: string | null): string;
52
+ /** One protocol line: `<nonce> <base64(utf8 command)>`. Base64 keeps arbitrary multi-line commands line-safe. */
53
+ export declare function buildPowerShellWire(command: string, nonce: string, cdTo: string | null): string;
54
+ export declare class PersistentShellSession {
55
+ private readonly key;
56
+ private readonly kind;
57
+ private child;
58
+ private childEnv;
59
+ private lastRequestedCwd;
60
+ private activeExec;
61
+ private queue;
62
+ private disposed;
63
+ constructor(key: string, kind: PlatformShellToolName);
64
+ get sessionKind(): PlatformShellToolName;
65
+ /** Serialized: one command at a time per session, later calls queue behind earlier ones. */
66
+ exec(command: string, cwd: string, options: ShellSessionExecOptions): Promise<{
67
+ exitCode: number | null;
68
+ }>;
69
+ dispose(): void;
70
+ /** Synchronous best-effort kill for process-exit hooks (async spawn never runs during exit).
71
+ * `killProcessTree` is itself synchronous (blocking `spawnSync` on Windows, `process.kill` on
72
+ * POSIX), so it is safe to call directly from a `process.on("exit", ...)` handler. */
73
+ killForProcessExit(): void;
74
+ private execNow;
75
+ private spawnChild;
76
+ private clearChild;
77
+ private killChild;
78
+ /**
79
+ * An idle session must not keep the Node event loop alive (one-shot modes have to exit
80
+ * naturally); during a command the child and its pipes are re-referenced so the loop stays
81
+ * alive even without an armed timer.
82
+ */
83
+ private setLoopRef;
84
+ }
85
+ /** Get or lazily create the persistent session for a key. A kind change replaces the session. */
86
+ export declare function acquirePersistentShellSession(key: string, kind: PlatformShellToolName): PersistentShellSession;
87
+ /** Kill and forget a session (agent teardown). Safe to call for keys that never spawned. */
88
+ export declare function disposePersistentShellSession(key: string): void;
89
+ //# sourceMappingURL=shell-session.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"shell-session.d.ts","sourceRoot":"","sources":["../../../src/core/tools/shell-session.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiCG;AAMH,OAAO,EAIN,KAAK,qBAAqB,EAG1B,MAAM,sBAAsB,CAAC;AAM9B,MAAM,WAAW,uBAAuB;IACvC,MAAM,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAAC;IAC/B,MAAM,CAAC,EAAE,WAAW,CAAC;IACrB,kGAAkG;IAClG,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,gGAAgG;IAChG,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,GAAG,CAAC,EAAE,MAAM,CAAC,UAAU,CAAC;CACxB;AAUD;;;;;GAKG;AACH,wBAAgB,aAAa,CAAC,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,IAAI,GAAG,MAAM,CAUzF;AAED,iHAAiH;AACjH,wBAAgB,mBAAmB,CAAC,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,IAAI,GAAG,MAAM,CAK/F;AAkDD,qBAAa,sBAAsB;IAClC,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAS;IAC7B,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAwB;IAC7C,OAAO,CAAC,KAAK,CAA6B;IAC1C,OAAO,CAAC,QAAQ,CAAkC;IAClD,OAAO,CAAC,gBAAgB,CAAuB;IAC/C,OAAO,CAAC,UAAU,CAA2B;IAC7C,OAAO,CAAC,KAAK,CAAoC;IACjD,OAAO,CAAC,QAAQ,CAAS;IAEzB,YAAY,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,qBAAqB,EAGnD;IAED,IAAI,WAAW,IAAI,qBAAqB,CAEvC;IAED,4FAA4F;IAC5F,IAAI,CAAC,OAAO,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE,uBAAuB,GAAG,OAAO,CAAC;QAAE,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAA;KAAE,CAAC,CAOzG;IAED,OAAO,IAAI,IAAI,CAGd;IAED;;0FAEsF;IACtF,kBAAkB,IAAI,IAAI,CAMzB;YAEa,OAAO;IA6IrB,OAAO,CAAC,UAAU;IAyElB,OAAO,CAAC,UAAU;IAOlB,OAAO,CAAC,SAAS;IAOjB;;;;OAIG;IACH,OAAO,CAAC,UAAU;CAgBlB;AAiBD,iGAAiG;AACjG,wBAAgB,6BAA6B,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,qBAAqB,GAAG,sBAAsB,CAQ9G;AAED,4FAA4F;AAC5F,wBAAgB,6BAA6B,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI,CAK/D","sourcesContent":["/**\n * Persistent shell sessions for the bash tool.\n *\n * One long-lived shell process per agent (keyed registry) replaces process-per-command spawning.\n * On Windows every command previously paid a full PowerShell boot; a persistent session pays it\n * once. Shell state (current directory, environment variables) persists across an agent's\n * commands; each key gets an isolated session so concurrently running agents never share state.\n *\n * Protocol: commands stream to the session over stdin and are terminated by a per-command\n * sentinel carrying a random nonce and the exit code. Bash wraps commands in an eval of a quoted\n * heredoc (arbitrary content stays data; syntax errors stay contained in eval); PowerShell runs a\n * ReadLine loop decoding base64 lines (no external binaries involved). On bash, command stderr is\n * merged into stdout at the shell so sentinel ordering is guaranteed on one pipe.\n *\n * PowerShell runs each command as a bare `Invoke-Expression`, NOT piped into `Out-Default`: piping\n * a native command's output into another pipeline stage forces PowerShell's NativeCommandProcessor\n * to capture that child's stdout/stderr into an internal pipe and read it to EOF before the\n * pipeline completes. A detached grandchild that inherited those handles (e.g. `start /b` holding\n * stdio open) then keeps that internal pipe's write end open, so the sentinel — written after the\n * pipeline \"completes\" — waits for the grandchild to die instead of the direct child. The bare\n * invocation lets a native command's stdout/stderr handles be inherited directly by the child\n * process; the direct child's own exit is what unblocks the sentinel line, exactly like the\n * per-command backend and like bash's stdio inheritance above. The bounded consequence: a native\n * command's stderr no longer merges into the session's stdout pipe (there is no capturing pipeline\n * stage to merge it) — it arrives on the session's own stderr pipe instead, forwarded via\n * `onStderr` -> `onData` same as the shell's own diagnostics. PowerShell 5.1's habit of wrapping\n * redirected stderr text in a `NativeCommandError` record also disappears, which is an accuracy\n * improvement (the raw stderr bytes are reported, not a wrapped/duplicated rendering of them).\n *\n * Kill semantics: timeout/abort/silence kill the WHOLE session process tree (a hung foreground\n * command cannot be killed individually without job control) and the next exec respawns a fresh\n * session, losing accumulated shell state by design. A command that exits the shell itself\n * (`exit 3`) reports the shell's exit code and also respawns lazily afterwards.\n */\n\nimport { randomBytes } from \"node:crypto\";\nimport { basename } from \"node:path\";\nimport { createSilenceWatchdog } from \"@caupulican/pi-agent-core\";\nimport { type ChildProcess, spawn } from \"child_process\";\nimport {\n\tgetShellConfig,\n\tgetShellEnv,\n\tkillProcessTree,\n\ttype PlatformShellToolName,\n\ttrackDetachedChildPid,\n\tuntrackDetachedChildPid,\n} from \"../../utils/shell.ts\";\n\nconst SENTINEL_BYTE = 0x1e;\n/** Longest possible sentinel: \"\\n\" + 0x1e + 16-hex nonce + \":\" + exit code digits + 0x1e. */\nconst SENTINEL_HOLDBACK_BYTES = 64;\n\nexport interface ShellSessionExecOptions {\n\tonData: (data: Buffer) => void;\n\tsignal?: AbortSignal;\n\t/** Wall-clock bound in seconds; when set, a breach kills the session and throws `timeout:<s>`. */\n\ttimeoutSeconds?: number;\n\t/** Output-silence bound in ms; when set, silence kills the session and throws `silence:<s>`. */\n\tsilenceMs?: number;\n\tenv?: NodeJS.ProcessEnv;\n}\n\nfunction escapeSingleQuotesPosix(value: string): string {\n\treturn value.replace(/'/g, \"'\\\\''\");\n}\n\nfunction escapeSingleQuotesPowerShell(value: string): string {\n\treturn value.replace(/'/g, \"''\");\n}\n\n/**\n * The whole command is heredoc-quoted data: eval keeps syntax errors contained (a raw syntax\n * error on the session's stdin would abort the shell), and the random delimiter makes content\n * collisions with agent output practically impossible. `< /dev/null` gives commands the same\n * EOF-stdin the per-command backend's `stdio: [\"ignore\", ...]` provided.\n */\nexport function buildBashWire(command: string, nonce: string, cdTo: string | null): string {\n\tconst body = cdTo ? `command cd -- '${escapeSingleQuotesPosix(cdTo)}' && {\\n${command}\\n}` : command;\n\treturn [\n\t\t`{ eval \"$(cat <<'PI_EOF_${nonce}'`,\n\t\tbody,\n\t\t`PI_EOF_${nonce}`,\n\t\t`)\"; } < /dev/null 2>&1`,\n\t\t`printf '\\\\n\\\\036%s:%s\\\\036' '${nonce}' \"$?\"`,\n\t\t\"\",\n\t].join(\"\\n\");\n}\n\n/** One protocol line: `<nonce> <base64(utf8 command)>`. Base64 keeps arbitrary multi-line commands line-safe. */\nexport function buildPowerShellWire(command: string, nonce: string, cdTo: string | null): string {\n\tconst body = cdTo\n\t\t? `Set-Location -LiteralPath '${escapeSingleQuotesPowerShell(cdTo)}' -ErrorAction Stop\\n${command}`\n\t\t: command;\n\treturn `${nonce} ${Buffer.from(body, \"utf8\").toString(\"base64\")}\\n`;\n}\n\n/**\n * PowerShell 5.1-compatible REPL bootstrap. Exit code mirrors `-Command` semantics as closely as\n * a loop can: a native command's $LASTEXITCODE wins, a terminating error forces 1, otherwise 0.\n * Passed via -EncodedCommand so quoting and newlines never touch the process command line.\n *\n * The command runs as a bare `Invoke-Expression` (no `2>&1 | Out-Default` capture pipeline) — see\n * the module doc header for why: a native command's stdio handles are inherited directly by its\n * child process instead of being captured through a PowerShell-internal pipe, so the sentinel is\n * unblocked by the direct child's own exit rather than by any grandchild holding those handles.\n */\nconst POWERSHELL_BOOTSTRAP = [\n\t\"$ProgressPreference = 'SilentlyContinue'\",\n\t\"try { [Console]::OutputEncoding = [System.Text.Encoding]::UTF8 } catch {}\",\n\t\"$__pi_in = [Console]::In\",\n\t\"while ($true) {\",\n\t\"\\t$__pi_line = $__pi_in.ReadLine()\",\n\t\"\\tif ($null -eq $__pi_line) { break }\",\n\t\"\\t$__pi_sp = $__pi_line.IndexOf(' ')\",\n\t\"\\tif ($__pi_sp -lt 1) { continue }\",\n\t\"\\t$__pi_nonce = $__pi_line.Substring(0, $__pi_sp)\",\n\t\"\\t$__pi_cmd = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($__pi_line.Substring($__pi_sp + 1)))\",\n\t\"\\t$global:LASTEXITCODE = 0\",\n\t\"\\t$__pi_thrown = $false\",\n\t\"\\ttry { Invoke-Expression $__pi_cmd } catch { $__pi_thrown = $true; $__pi_msg = ($_ | Out-String).TrimEnd(); if ($__pi_msg) { [Console]::Out.WriteLine($__pi_msg) } }\",\n\t\"\\t$__pi_code = $global:LASTEXITCODE\",\n\t\"\\tif ($null -eq $__pi_code) { $__pi_code = 0 }\",\n\t\"\\tif ($__pi_thrown -and ($__pi_code -eq 0)) { $__pi_code = 1 }\",\n\t\"\\t[Console]::Out.Write(('{0}{1}{2}:{3}{1}' -f [char]10, [char]30, $__pi_nonce, $__pi_code))\",\n\t\"}\",\n].join(\"\\n\");\n\nfunction shallowEnvEquals(a: NodeJS.ProcessEnv, b: NodeJS.ProcessEnv): boolean {\n\tconst aKeys = Object.keys(a);\n\tconst bKeys = Object.keys(b);\n\tif (aKeys.length !== bKeys.length) return false;\n\tfor (const key of aKeys) {\n\t\tif (a[key] !== b[key]) return false;\n\t}\n\treturn true;\n}\n\ninterface ActiveExec {\n\tonStdout(data: Buffer): void;\n\tonStderr(data: Buffer): void;\n\tonChildClose(code: number | null): void;\n\tfail(error: Error): void;\n}\n\nexport class PersistentShellSession {\n\tprivate readonly key: string;\n\tprivate readonly kind: PlatformShellToolName;\n\tprivate child: ChildProcess | null = null;\n\tprivate childEnv: NodeJS.ProcessEnv | null = null;\n\tprivate lastRequestedCwd: string | null = null;\n\tprivate activeExec: ActiveExec | null = null;\n\tprivate queue: Promise<void> = Promise.resolve();\n\tprivate disposed = false;\n\n\tconstructor(key: string, kind: PlatformShellToolName) {\n\t\tthis.key = key;\n\t\tthis.kind = kind;\n\t}\n\n\tget sessionKind(): PlatformShellToolName {\n\t\treturn this.kind;\n\t}\n\n\t/** Serialized: one command at a time per session, later calls queue behind earlier ones. */\n\texec(command: string, cwd: string, options: ShellSessionExecOptions): Promise<{ exitCode: number | null }> {\n\t\tconst run = this.queue.then(() => this.execNow(command, cwd, options));\n\t\tthis.queue = run.then(\n\t\t\t() => undefined,\n\t\t\t() => undefined,\n\t\t);\n\t\treturn run;\n\t}\n\n\tdispose(): void {\n\t\tthis.disposed = true;\n\t\tthis.killChild();\n\t}\n\n\t/** Synchronous best-effort kill for process-exit hooks (async spawn never runs during exit).\n\t * `killProcessTree` is itself synchronous (blocking `spawnSync` on Windows, `process.kill` on\n\t * POSIX), so it is safe to call directly from a `process.on(\"exit\", ...)` handler. */\n\tkillForProcessExit(): void {\n\t\tconst pid = this.child?.pid;\n\t\tthis.child = null;\n\t\tif (!pid) return;\n\t\tuntrackDetachedChildPid(pid);\n\t\tkillProcessTree(pid);\n\t}\n\n\tprivate async execNow(\n\t\tcommand: string,\n\t\tcwd: string,\n\t\t{ onData, signal, timeoutSeconds, silenceMs, env }: ShellSessionExecOptions,\n\t): Promise<{ exitCode: number | null }> {\n\t\tif (this.disposed) throw new Error(`Shell session \"${this.key}\" is disposed`);\n\t\tif (signal?.aborted) throw new Error(\"aborted\");\n\n\t\tconst resolvedEnv = env ?? getShellEnv();\n\t\t// The environment is spawn-time shell config: an env that differs from the running\n\t\t// session's (e.g. a spawn hook rewriting it per command) requires a fresh shell.\n\t\tif (this.child && this.childEnv && !shallowEnvEquals(this.childEnv, resolvedEnv)) {\n\t\t\tthis.killChild();\n\t\t}\n\n\t\t// Re-enter the host-requested cwd only when it CHANGES between calls; an unchanged\n\t\t// request preserves the agent's own in-session `cd` (that persistence is the feature).\n\t\tlet cdTo: string | null = null;\n\t\tif (!this.child) {\n\t\t\tthis.spawnChild(cwd, resolvedEnv);\n\t\t} else if (this.lastRequestedCwd !== cwd) {\n\t\t\tcdTo = cwd;\n\t\t}\n\t\tthis.lastRequestedCwd = cwd;\n\n\t\tconst child = this.child;\n\t\tif (!child?.stdin || !child.stdout || !child.stderr) {\n\t\t\tthis.killChild();\n\t\t\tthrow new Error(`Failed to start ${this.kind} session`);\n\t\t}\n\n\t\tconst nonce = randomBytes(8).toString(\"hex\");\n\t\tconst wire =\n\t\t\tthis.kind === \"powershell\" ? buildPowerShellWire(command, nonce, cdTo) : buildBashWire(command, nonce, cdTo);\n\t\tconst sentinelPrefix = Buffer.from(`\\n\\x1e${nonce}:`, \"latin1\");\n\n\t\tthis.setLoopRef(true);\n\t\ttry {\n\t\t\treturn await new Promise<{ exitCode: number | null }>((resolve, reject) => {\n\t\t\t\tlet settled = false;\n\t\t\t\tlet pending: Buffer = Buffer.alloc(0);\n\t\t\t\tlet timeoutTimer: NodeJS.Timeout | undefined;\n\n\t\t\t\tconst silenceWatchdog =\n\t\t\t\t\ttimeoutSeconds === undefined && silenceMs !== undefined && silenceMs > 0\n\t\t\t\t\t\t? createSilenceWatchdog({\n\t\t\t\t\t\t\t\tsilenceMs,\n\t\t\t\t\t\t\t\tonSilence: () => {\n\t\t\t\t\t\t\t\t\tthis.killChild();\n\t\t\t\t\t\t\t\t\tsettle(() => reject(new Error(`silence:${silenceMs / 1000}`)));\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t: undefined;\n\n\t\t\t\tconst settle = (finish: () => void) => {\n\t\t\t\t\tif (settled) return;\n\t\t\t\t\tsettled = true;\n\t\t\t\t\tif (timeoutTimer) clearTimeout(timeoutTimer);\n\t\t\t\t\tsilenceWatchdog?.disarm();\n\t\t\t\t\tif (signal) signal.removeEventListener(\"abort\", onAbort);\n\t\t\t\t\tthis.activeExec = null;\n\t\t\t\t\tfinish();\n\t\t\t\t};\n\n\t\t\t\tconst onAbort = () => {\n\t\t\t\t\tthis.killChild();\n\t\t\t\t\tsettle(() => reject(new Error(\"aborted\")));\n\t\t\t\t};\n\n\t\t\t\tconst emitPending = (upTo: number) => {\n\t\t\t\t\tif (upTo <= 0) return;\n\t\t\t\t\tonData(pending.subarray(0, upTo));\n\t\t\t\t\tpending = pending.subarray(upTo);\n\t\t\t\t};\n\n\t\t\t\tthis.activeExec = {\n\t\t\t\t\tonStdout: (data) => {\n\t\t\t\t\t\tsilenceWatchdog?.touch();\n\t\t\t\t\t\tpending = pending.length === 0 ? data : Buffer.concat([pending, data]);\n\t\t\t\t\t\tconst prefixIndex = pending.indexOf(sentinelPrefix);\n\t\t\t\t\t\tif (prefixIndex !== -1) {\n\t\t\t\t\t\t\tconst closeIndex = pending.indexOf(SENTINEL_BYTE, prefixIndex + sentinelPrefix.length);\n\t\t\t\t\t\t\tif (closeIndex !== -1) {\n\t\t\t\t\t\t\t\tconst codeText = pending\n\t\t\t\t\t\t\t\t\t.subarray(prefixIndex + sentinelPrefix.length, closeIndex)\n\t\t\t\t\t\t\t\t\t.toString(\"latin1\");\n\t\t\t\t\t\t\t\temitPending(prefixIndex);\n\t\t\t\t\t\t\t\tconst parsed = Number.parseInt(codeText, 10);\n\t\t\t\t\t\t\t\t// Defer the settle by one microtask turn: with the bare Invoke-Expression\n\t\t\t\t\t\t\t\t// form a native command's stderr now arrives on the session's OWN stderr\n\t\t\t\t\t\t\t\t// pipe (see module doc header) instead of being pre-merged into the same\n\t\t\t\t\t\t\t\t// stdout bytes the sentinel rides on. Node fires already-queued stream\n\t\t\t\t\t\t\t\t// 'data' events in event-loop order; queueing the resolution behind a\n\t\t\t\t\t\t\t\t// microtask guarantees any stderr chunk the kernel delivered alongside (or\n\t\t\t\t\t\t\t\t// just before) this stdout chunk has already run its 'data' handler — and\n\t\t\t\t\t\t\t\t// thus reached `onData` — before the promise settles, so callers never see a\n\t\t\t\t\t\t\t\t// truncated stderr tail immediately after resolution.\n\t\t\t\t\t\t\t\tqueueMicrotask(() => settle(() => resolve({ exitCode: Number.isNaN(parsed) ? null : parsed })));\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// Stream promptly but retain a tail large enough to hold any split sentinel.\n\t\t\t\t\t\temitPending(pending.length - SENTINEL_HOLDBACK_BYTES);\n\t\t\t\t\t},\n\t\t\t\t\tonStderr: (data) => {\n\t\t\t\t\t\t// The command's stderr is merged into stdout at the shell; this pipe only\n\t\t\t\t\t\t// carries the session shell's own diagnostics. Forward for visibility.\n\t\t\t\t\t\tsilenceWatchdog?.touch();\n\t\t\t\t\t\tonData(data);\n\t\t\t\t\t},\n\t\t\t\t\tonChildClose: (code) => {\n\t\t\t\t\t\t// The command terminated the shell itself (e.g. `exit 3`) or the shell\n\t\t\t\t\t\t// crashed: report its exit code like the per-command backend would.\n\t\t\t\t\t\temitPending(pending.length);\n\t\t\t\t\t\tsettle(() => resolve({ exitCode: code }));\n\t\t\t\t\t},\n\t\t\t\t\tfail: (error) => {\n\t\t\t\t\t\tthis.killChild();\n\t\t\t\t\t\tsettle(() => reject(error));\n\t\t\t\t\t},\n\t\t\t\t};\n\n\t\t\t\tif (signal) signal.addEventListener(\"abort\", onAbort, { once: true });\n\t\t\t\tif (timeoutSeconds !== undefined && timeoutSeconds > 0) {\n\t\t\t\t\ttimeoutTimer = setTimeout(() => {\n\t\t\t\t\t\tthis.killChild();\n\t\t\t\t\t\tsettle(() => reject(new Error(`timeout:${timeoutSeconds}`)));\n\t\t\t\t\t}, timeoutSeconds * 1000);\n\t\t\t\t}\n\n\t\t\t\tchild.stdin?.write(wire, (error) => {\n\t\t\t\t\tif (!error) return;\n\t\t\t\t\tthis.killChild();\n\t\t\t\t\tsettle(() => reject(new Error(`Failed to write to ${this.kind} session: ${error.message}`)));\n\t\t\t\t});\n\t\t\t});\n\t\t} finally {\n\t\t\tthis.setLoopRef(false);\n\t\t}\n\t}\n\n\tprivate spawnChild(cwd: string, env: NodeJS.ProcessEnv): void {\n\t\tconst { shell } = getShellConfig(undefined, this.kind);\n\t\tconst args =\n\t\t\tthis.kind === \"powershell\"\n\t\t\t\t? [\n\t\t\t\t\t\t\"-NoLogo\",\n\t\t\t\t\t\t\"-NoProfile\",\n\t\t\t\t\t\t\"-NonInteractive\",\n\t\t\t\t\t\t\"-EncodedCommand\",\n\t\t\t\t\t\tBuffer.from(POWERSHELL_BOOTSTRAP, \"utf16le\").toString(\"base64\"),\n\t\t\t\t\t]\n\t\t\t\t: basename(shell).toLowerCase().includes(\"bash\")\n\t\t\t\t\t? [\"--noprofile\", \"--norc\"]\n\t\t\t\t\t: [];\n\t\tconst child = spawn(shell, args, {\n\t\t\tcwd,\n\t\t\tenv,\n\t\t\tdetached: process.platform !== \"win32\",\n\t\t\tstdio: [\"pipe\", \"pipe\", \"pipe\"],\n\t\t\twindowsHide: true,\n\t\t});\n\t\tif (child.pid) trackDetachedChildPid(child.pid);\n\t\t// Every listener gates on the child still being the session's current one: after a\n\t\t// timeout/abort kill replaced it, the dead shell's late data/close events are stale noise\n\t\t// that must never reach the NEXT command's handlers.\n\t\tchild.stdout?.on(\"data\", (data: Buffer) => {\n\t\t\tif (this.child === child) this.activeExec?.onStdout(data);\n\t\t});\n\t\tchild.stderr?.on(\"data\", (data: Buffer) => {\n\t\t\tif (this.child === child) this.activeExec?.onStderr(data);\n\t\t});\n\t\tchild.on(\"error\", (error) => {\n\t\t\tif (this.child !== child) return;\n\t\t\tthis.clearChild(child);\n\t\t\tthis.activeExec?.fail(error instanceof Error ? error : new Error(String(error)));\n\t\t});\n\t\t// Settle the shell-died path on \"exit\" (process death), not \"close\" (stdio streams ended):\n\t\t// a live detached grandchild that inherited these pipes (e.g. `sleep 30 &` before `exit 3`)\n\t\t// keeps them open indefinitely even though the shell itself is already gone, and Node only\n\t\t// fires \"close\" once every stdio stream has ended. Waiting for \"close\" here would hang for\n\t\t// as long as the grandchild lives. The per-command backend\n\t\t// (waitForChildProcessWithTermination in ../../utils/child-process.ts) faces the identical\n\t\t// hazard and settles on \"exit\" for the same reason.\n\t\t//\n\t\t// \"exit\" can fire before Node has delivered already-buffered stdout/stderr \"data\" events for\n\t\t// bytes the kernel handed over just before the process died (e.g. the sentinel line itself).\n\t\t// Defer the settlement by one setImmediate turn: Node drains the poll phase (which is where\n\t\t// pending stream \"data\" events run) before the check phase (where setImmediate callbacks\n\t\t// run), so by the time this callback executes, every \"data\" event for bytes already received\n\t\t// has already reached onStdout/onStderr, and thus onData, before we resolve/reject. This is\n\t\t// not a hang-fix timer — it never waits on anything and does not run if the grandchild is\n\t\t// gone and \"close\" (or a replacement child) got there first.\n\t\tchild.on(\"exit\", (code) => {\n\t\t\tif (this.child !== child) return;\n\t\t\tsetImmediate(() => {\n\t\t\t\tif (this.child !== child) return;\n\t\t\t\tthis.clearChild(child);\n\t\t\t\tthis.activeExec?.onChildClose(code);\n\t\t\t});\n\t\t});\n\t\t// Kept alongside \"exit\" for the genuine fast-close case (no lingering grandchild): whichever\n\t\t// event reaches its guard first wins and nulls out this.child, making the other a no-op, so\n\t\t// settlement stays idempotent regardless of which fires first or whether both fire.\n\t\tchild.on(\"close\", (code) => {\n\t\t\tif (this.child !== child) return;\n\t\t\tthis.clearChild(child);\n\t\t\tthis.activeExec?.onChildClose(code);\n\t\t});\n\t\tthis.child = child;\n\t\tthis.childEnv = env;\n\t\tthis.lastRequestedCwd = cwd;\n\t}\n\n\tprivate clearChild(child: ChildProcess): void {\n\t\tif (child.pid) untrackDetachedChildPid(child.pid);\n\t\tthis.child = null;\n\t\tthis.childEnv = null;\n\t\tthis.lastRequestedCwd = null;\n\t}\n\n\tprivate killChild(): void {\n\t\tconst child = this.child;\n\t\tif (!child) return;\n\t\tthis.clearChild(child);\n\t\tif (child.pid) killProcessTree(child.pid);\n\t}\n\n\t/**\n\t * An idle session must not keep the Node event loop alive (one-shot modes have to exit\n\t * naturally); during a command the child and its pipes are re-referenced so the loop stays\n\t * alive even without an armed timer.\n\t */\n\tprivate setLoopRef(active: boolean): void {\n\t\tconst child = this.child;\n\t\tif (!child) return;\n\t\t// Stdio pipes are Sockets at runtime (ref/unref exist) but are typed as plain streams.\n\t\tconst streams = [child.stdin, child.stdout, child.stderr] as unknown as Array<{\n\t\t\tref?: () => void;\n\t\t\tunref?: () => void;\n\t\t} | null>;\n\t\tif (active) {\n\t\t\tchild.ref();\n\t\t\tfor (const stream of streams) stream?.ref?.();\n\t\t} else {\n\t\t\tchild.unref();\n\t\t\tfor (const stream of streams) stream?.unref?.();\n\t\t}\n\t}\n}\n\nconst shellSessions = new Map<string, PersistentShellSession>();\nlet exitHookInstalled = false;\n\nfunction installExitHook(): void {\n\tif (exitHookInstalled) return;\n\texitHookInstalled = true;\n\t// Detached sessions outlive the parent on clean exits unless explicitly killed; shutdown\n\t// signals are already covered by the tracked-detached-children mechanism.\n\tprocess.on(\"exit\", () => {\n\t\tfor (const session of shellSessions.values()) {\n\t\t\tsession.killForProcessExit();\n\t\t}\n\t});\n}\n\n/** Get or lazily create the persistent session for a key. A kind change replaces the session. */\nexport function acquirePersistentShellSession(key: string, kind: PlatformShellToolName): PersistentShellSession {\n\tinstallExitHook();\n\tconst existing = shellSessions.get(key);\n\tif (existing && existing.sessionKind === kind) return existing;\n\texisting?.dispose();\n\tconst session = new PersistentShellSession(key, kind);\n\tshellSessions.set(key, session);\n\treturn session;\n}\n\n/** Kill and forget a session (agent teardown). Safe to call for keys that never spawned. */\nexport function disposePersistentShellSession(key: string): void {\n\tconst session = shellSessions.get(key);\n\tif (!session) return;\n\tshellSessions.delete(key);\n\tsession.dispose();\n}\n"]}