@caupulican/pi-adaptative 0.81.32 → 0.81.35

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 (237) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/dist/bundled-resources/extensions/tmux-agent-manager/README.md +69 -0
  3. package/dist/bundled-resources/extensions/tmux-agent-manager/index.d.ts +53 -0
  4. package/dist/bundled-resources/extensions/tmux-agent-manager/index.d.ts.map +1 -0
  5. package/dist/bundled-resources/extensions/tmux-agent-manager/index.js +1282 -0
  6. package/dist/bundled-resources/extensions/tmux-agent-manager/index.js.map +1 -0
  7. package/dist/bundled-resources/extensions/tmux-agent-manager/index.ts +1453 -0
  8. package/dist/bundled-resources/extensions/tmux-agent-manager/templates/builder-validator.json +14 -0
  9. package/dist/bundled-resources/extensions/tmux-agent-manager/templates/claude-trio.json +32 -0
  10. package/dist/bundled-resources/extensions/tmux-agent-manager/templates/full-provider-review.json +15 -0
  11. package/dist/bundled-resources/extensions/tmux-agent-manager/templates/provider-prompt-smoke.json +14 -0
  12. package/dist/bundled-resources/prompts/extensionify.md +5 -4
  13. package/dist/bundled-resources/prompts/skillify.md +5 -5
  14. package/dist/bundled-resources/skills/pi-harness-learning/SKILL.md +6 -3
  15. package/dist/config.d.ts +5 -1
  16. package/dist/config.d.ts.map +1 -1
  17. package/dist/config.js +10 -2
  18. package/dist/config.js.map +1 -1
  19. package/dist/core/agent-session.d.ts +7 -0
  20. package/dist/core/agent-session.d.ts.map +1 -1
  21. package/dist/core/agent-session.js +25 -2
  22. package/dist/core/agent-session.js.map +1 -1
  23. package/dist/core/background-lane-controller.d.ts +12 -3
  24. package/dist/core/background-lane-controller.d.ts.map +1 -1
  25. package/dist/core/background-lane-controller.js +67 -26
  26. package/dist/core/background-lane-controller.js.map +1 -1
  27. package/dist/core/bash-executor.d.ts.map +1 -1
  28. package/dist/core/bash-executor.js +7 -3
  29. package/dist/core/bash-executor.js.map +1 -1
  30. package/dist/core/context/context-store-retention.d.ts +4 -1
  31. package/dist/core/context/context-store-retention.d.ts.map +1 -1
  32. package/dist/core/context/context-store-retention.js +42 -151
  33. package/dist/core/context/context-store-retention.js.map +1 -1
  34. package/dist/core/context-pipeline.d.ts.map +1 -1
  35. package/dist/core/context-pipeline.js +6 -6
  36. package/dist/core/context-pipeline.js.map +1 -1
  37. package/dist/core/exec.d.ts.map +1 -1
  38. package/dist/core/exec.js +25 -39
  39. package/dist/core/exec.js.map +1 -1
  40. package/dist/core/extensions/loader.d.ts +9 -2
  41. package/dist/core/extensions/loader.d.ts.map +1 -1
  42. package/dist/core/extensions/loader.js +105 -21
  43. package/dist/core/extensions/loader.js.map +1 -1
  44. package/dist/core/footer-data-provider.d.ts.map +1 -1
  45. package/dist/core/footer-data-provider.js +2 -0
  46. package/dist/core/footer-data-provider.js.map +1 -1
  47. package/dist/core/goals/goal-state.d.ts +10 -0
  48. package/dist/core/goals/goal-state.d.ts.map +1 -1
  49. package/dist/core/goals/goal-state.js +37 -0
  50. package/dist/core/goals/goal-state.js.map +1 -1
  51. package/dist/core/goals/goal-tool-core.d.ts +11 -0
  52. package/dist/core/goals/goal-tool-core.d.ts.map +1 -1
  53. package/dist/core/goals/goal-tool-core.js +51 -1
  54. package/dist/core/goals/goal-tool-core.js.map +1 -1
  55. package/dist/core/improvement-loop.d.ts.map +1 -1
  56. package/dist/core/improvement-loop.js +26 -5
  57. package/dist/core/improvement-loop.js.map +1 -1
  58. package/dist/core/models/fitness-store.d.ts.map +1 -1
  59. package/dist/core/models/fitness-store.js +1 -1
  60. package/dist/core/models/fitness-store.js.map +1 -1
  61. package/dist/core/models/local-runtime.d.ts +6 -4
  62. package/dist/core/models/local-runtime.d.ts.map +1 -1
  63. package/dist/core/models/local-runtime.js +108 -36
  64. package/dist/core/models/local-runtime.js.map +1 -1
  65. package/dist/core/output-guard.d.ts.map +1 -1
  66. package/dist/core/output-guard.js +23 -8
  67. package/dist/core/output-guard.js.map +1 -1
  68. package/dist/core/package-manager.d.ts.map +1 -1
  69. package/dist/core/package-manager.js +44 -59
  70. package/dist/core/package-manager.js.map +1 -1
  71. package/dist/core/profile-resource-selection.d.ts +16 -0
  72. package/dist/core/profile-resource-selection.d.ts.map +1 -1
  73. package/dist/core/profile-resource-selection.js +41 -0
  74. package/dist/core/profile-resource-selection.js.map +1 -1
  75. package/dist/core/reflection-controller.d.ts.map +1 -1
  76. package/dist/core/reflection-controller.js +18 -1
  77. package/dist/core/reflection-controller.js.map +1 -1
  78. package/dist/core/reload-blockers.d.ts +1 -0
  79. package/dist/core/reload-blockers.d.ts.map +1 -1
  80. package/dist/core/reload-blockers.js +6 -2
  81. package/dist/core/reload-blockers.js.map +1 -1
  82. package/dist/core/resource-loader.d.ts +2 -0
  83. package/dist/core/resource-loader.d.ts.map +1 -1
  84. package/dist/core/resource-loader.js +50 -28
  85. package/dist/core/resource-loader.js.map +1 -1
  86. package/dist/core/settings-manager.d.ts.map +1 -1
  87. package/dist/core/settings-manager.js +1 -1
  88. package/dist/core/settings-manager.js.map +1 -1
  89. package/dist/core/slash-commands.d.ts.map +1 -1
  90. package/dist/core/slash-commands.js +1 -1
  91. package/dist/core/slash-commands.js.map +1 -1
  92. package/dist/core/toolkit/script-runner.d.ts.map +1 -1
  93. package/dist/core/toolkit/script-runner.js +58 -24
  94. package/dist/core/toolkit/script-runner.js.map +1 -1
  95. package/dist/core/tools/bash.d.ts.map +1 -1
  96. package/dist/core/tools/bash.js +13 -26
  97. package/dist/core/tools/bash.js.map +1 -1
  98. package/dist/core/tools/extensionify.d.ts +2 -1
  99. package/dist/core/tools/extensionify.d.ts.map +1 -1
  100. package/dist/core/tools/extensionify.js +11 -8
  101. package/dist/core/tools/extensionify.js.map +1 -1
  102. package/dist/core/tools/find.d.ts.map +1 -1
  103. package/dist/core/tools/find.js +54 -48
  104. package/dist/core/tools/find.js.map +1 -1
  105. package/dist/core/tools/git-filter.d.ts.map +1 -1
  106. package/dist/core/tools/git-filter.js +20 -32
  107. package/dist/core/tools/git-filter.js.map +1 -1
  108. package/dist/core/tools/goal.d.ts +1 -1
  109. package/dist/core/tools/goal.d.ts.map +1 -1
  110. package/dist/core/tools/goal.js +10 -3
  111. package/dist/core/tools/goal.js.map +1 -1
  112. package/dist/core/tools/grep.d.ts.map +1 -1
  113. package/dist/core/tools/grep.js +89 -80
  114. package/dist/core/tools/grep.js.map +1 -1
  115. package/dist/core/tools/output-accumulator.d.ts +2 -0
  116. package/dist/core/tools/output-accumulator.d.ts.map +1 -1
  117. package/dist/core/tools/output-accumulator.js +7 -4
  118. package/dist/core/tools/output-accumulator.js.map +1 -1
  119. package/dist/core/tools/read.d.ts.map +1 -1
  120. package/dist/core/tools/read.js +4 -3
  121. package/dist/core/tools/read.js.map +1 -1
  122. package/dist/index.d.ts +2 -1
  123. package/dist/index.d.ts.map +1 -1
  124. package/dist/index.js +2 -1
  125. package/dist/index.js.map +1 -1
  126. package/dist/main.d.ts +2 -0
  127. package/dist/main.d.ts.map +1 -1
  128. package/dist/main.js +23 -4
  129. package/dist/main.js.map +1 -1
  130. package/dist/migrations.d.ts.map +1 -1
  131. package/dist/migrations.js +18 -4
  132. package/dist/migrations.js.map +1 -1
  133. package/dist/modes/interactive/auth-dialogs-controller.d.ts +10 -0
  134. package/dist/modes/interactive/auth-dialogs-controller.d.ts.map +1 -1
  135. package/dist/modes/interactive/auth-dialogs-controller.js +94 -27
  136. package/dist/modes/interactive/auth-dialogs-controller.js.map +1 -1
  137. package/dist/modes/interactive/auto-learn-controller.d.ts.map +1 -1
  138. package/dist/modes/interactive/auto-learn-controller.js +2 -1
  139. package/dist/modes/interactive/auto-learn-controller.js.map +1 -1
  140. package/dist/modes/interactive/components/bordered-loader.d.ts +1 -0
  141. package/dist/modes/interactive/components/bordered-loader.d.ts.map +1 -1
  142. package/dist/modes/interactive/components/bordered-loader.js +8 -0
  143. package/dist/modes/interactive/components/bordered-loader.js.map +1 -1
  144. package/dist/modes/interactive/components/extension-editor.d.ts.map +1 -1
  145. package/dist/modes/interactive/components/extension-editor.js +6 -15
  146. package/dist/modes/interactive/components/extension-editor.js.map +1 -1
  147. package/dist/modes/interactive/components/login-dialog.d.ts +3 -1
  148. package/dist/modes/interactive/components/login-dialog.d.ts.map +1 -1
  149. package/dist/modes/interactive/components/login-dialog.js +20 -8
  150. package/dist/modes/interactive/components/login-dialog.js.map +1 -1
  151. package/dist/modes/interactive/components/profile-resource-editor.d.ts +4 -1
  152. package/dist/modes/interactive/components/profile-resource-editor.d.ts.map +1 -1
  153. package/dist/modes/interactive/components/profile-resource-editor.js +22 -39
  154. package/dist/modes/interactive/components/profile-resource-editor.js.map +1 -1
  155. package/dist/modes/interactive/components/session-selector.d.ts.map +1 -1
  156. package/dist/modes/interactive/components/session-selector.js +1 -1
  157. package/dist/modes/interactive/components/session-selector.js.map +1 -1
  158. package/dist/modes/interactive/config-backup.d.ts +1 -0
  159. package/dist/modes/interactive/config-backup.d.ts.map +1 -1
  160. package/dist/modes/interactive/config-backup.js +14 -3
  161. package/dist/modes/interactive/config-backup.js.map +1 -1
  162. package/dist/modes/interactive/editor-overlay-host.d.ts +12 -0
  163. package/dist/modes/interactive/editor-overlay-host.d.ts.map +1 -1
  164. package/dist/modes/interactive/editor-overlay-host.js +55 -0
  165. package/dist/modes/interactive/editor-overlay-host.js.map +1 -1
  166. package/dist/modes/interactive/extension-ui-host.d.ts +2 -1
  167. package/dist/modes/interactive/extension-ui-host.d.ts.map +1 -1
  168. package/dist/modes/interactive/extension-ui-host.js +161 -96
  169. package/dist/modes/interactive/extension-ui-host.js.map +1 -1
  170. package/dist/modes/interactive/external-editor.d.ts.map +1 -1
  171. package/dist/modes/interactive/external-editor.js +23 -28
  172. package/dist/modes/interactive/external-editor.js.map +1 -1
  173. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  174. package/dist/modes/interactive/interactive-mode.js +14 -8
  175. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  176. package/dist/modes/interactive/profile-menu-controller.d.ts +5 -1
  177. package/dist/modes/interactive/profile-menu-controller.d.ts.map +1 -1
  178. package/dist/modes/interactive/profile-menu-controller.js +118 -24
  179. package/dist/modes/interactive/profile-menu-controller.js.map +1 -1
  180. package/dist/modes/interactive/resource-shell-commands.d.ts +1 -0
  181. package/dist/modes/interactive/resource-shell-commands.d.ts.map +1 -1
  182. package/dist/modes/interactive/resource-shell-commands.js +5 -1
  183. package/dist/modes/interactive/resource-shell-commands.js.map +1 -1
  184. package/dist/modes/interactive/session-flow-commands.d.ts.map +1 -1
  185. package/dist/modes/interactive/session-flow-commands.js +100 -7
  186. package/dist/modes/interactive/session-flow-commands.js.map +1 -1
  187. package/dist/modes/interactive/session-io-commands.d.ts.map +1 -1
  188. package/dist/modes/interactive/session-io-commands.js +80 -50
  189. package/dist/modes/interactive/session-io-commands.js.map +1 -1
  190. package/dist/modes/interactive/startup-checks.d.ts.map +1 -1
  191. package/dist/modes/interactive/startup-checks.js +14 -17
  192. package/dist/modes/interactive/startup-checks.js.map +1 -1
  193. package/dist/modes/rpc/rpc-client.d.ts.map +1 -1
  194. package/dist/modes/rpc/rpc-client.js +20 -19
  195. package/dist/modes/rpc/rpc-client.js.map +1 -1
  196. package/dist/package-manager-cli.d.ts.map +1 -1
  197. package/dist/package-manager-cli.js +10 -19
  198. package/dist/package-manager-cli.js.map +1 -1
  199. package/dist/utils/child-process.d.ts +13 -7
  200. package/dist/utils/child-process.d.ts.map +1 -1
  201. package/dist/utils/child-process.js +56 -3
  202. package/dist/utils/child-process.js.map +1 -1
  203. package/dist/utils/clipboard-image.d.ts.map +1 -1
  204. package/dist/utils/clipboard-image.js +3 -2
  205. package/dist/utils/clipboard-image.js.map +1 -1
  206. package/dist/utils/clipboard.d.ts.map +1 -1
  207. package/dist/utils/clipboard.js +17 -10
  208. package/dist/utils/clipboard.js.map +1 -1
  209. package/dist/utils/external-editor-command.d.ts +8 -0
  210. package/dist/utils/external-editor-command.d.ts.map +1 -0
  211. package/dist/utils/external-editor-command.js +60 -0
  212. package/dist/utils/external-editor-command.js.map +1 -0
  213. package/dist/utils/paths.d.ts.map +1 -1
  214. package/dist/utils/paths.js +10 -2
  215. package/dist/utils/paths.js.map +1 -1
  216. package/dist/utils/tools-manager.d.ts.map +1 -1
  217. package/dist/utils/tools-manager.js +23 -10
  218. package/dist/utils/tools-manager.js.map +1 -1
  219. package/dist/utils/work-directory.d.ts +36 -0
  220. package/dist/utils/work-directory.d.ts.map +1 -0
  221. package/dist/utils/work-directory.js +462 -0
  222. package/dist/utils/work-directory.js.map +1 -0
  223. package/docs/index.md +2 -0
  224. package/docs/resources.md +2 -2
  225. package/docs/rpc.md +1 -1
  226. package/docs/tmux-agent-manager.md +48 -0
  227. package/docs/windows.md +100 -7
  228. package/docs/work-directory.md +41 -0
  229. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  230. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  231. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  232. package/examples/extensions/sandbox/package-lock.json +2 -2
  233. package/examples/extensions/sandbox/package.json +1 -1
  234. package/examples/extensions/with-deps/package-lock.json +2 -2
  235. package/examples/extensions/with-deps/package.json +1 -1
  236. package/npm-shrinkwrap.json +12 -12
  237. package/package.json +4 -4
@@ -1 +1 @@
1
- {"version":3,"file":"slash-commands.d.ts","sourceRoot":"","sources":["../../src/core/slash-commands.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAEnD,MAAM,MAAM,kBAAkB,GAAG,WAAW,GAAG,QAAQ,GAAG,OAAO,CAAC;AAElE,MAAM,WAAW,gBAAgB;IAChC,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,MAAM,EAAE,kBAAkB,CAAC;IAC3B,UAAU,EAAE,UAAU,CAAC;CACvB;AAED,MAAM,WAAW,mBAAmB;IACnC,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,EAAE,MAAM,CAAC;CACpB;AAED,eAAO,MAAM,sBAAsB,EAAE,aAAa,CAAC,mBAAmB,CAwErE,CAAC","sourcesContent":["import { APP_NAME } from \"../config.ts\";\nimport type { SourceInfo } from \"./source-info.ts\";\n\nexport type SlashCommandSource = \"extension\" | \"prompt\" | \"skill\";\n\nexport interface SlashCommandInfo {\n\tname: string;\n\tdescription?: string;\n\tsource: SlashCommandSource;\n\tsourceInfo: SourceInfo;\n}\n\nexport interface BuiltinSlashCommand {\n\tname: string;\n\tdescription: string;\n}\n\nexport const BUILTIN_SLASH_COMMANDS: ReadonlyArray<BuiltinSlashCommand> = [\n\t{ name: \"settings\", description: \"Open settings menu\" },\n\t{ name: \"autonomy\", description: \"Autonomy mode, diagnostics, research, fitness (/autonomy status)\" },\n\t{\n\t\tname: \"models\",\n\t\tdescription: \"Local model lifecycle: /models [list|suggest|add <ref>|remove <ref> confirm|stop]\",\n\t},\n\t{\n\t\tname: \"fitness\",\n\t\tdescription: \"Pick and probe a model for local/heavy-lifter roles, then assign it (/fitness [model] [trials])\",\n\t},\n\t{ name: \"context\", description: \"Context composition dashboard: what rides on every request\" },\n\t{ name: \"toolhealth\", description: \"Show tool repair diagnostics and learned standing rules\" },\n\t{ name: \"toolprobe\", description: \"Probe native/text tool-call support (/toolprobe [provider/model])\" },\n\t{\n\t\tname: \"toolrule-remove\",\n\t\tdescription: \"Remove a learned tool repair standing rule (/toolrule-remove <model> <mode>)\",\n\t},\n\t{\n\t\tname: \"toolprotocol-reset\",\n\t\tdescription: \"Reset text tool protocol calibration for a model (/toolprotocol-reset <provider/model>)\",\n\t},\n\t{ name: \"auto-learn\", description: \"Show Auto Learn/reflection status or run now (/auto-learn run)\" },\n\t{\n\t\tname: \"goal\",\n\t\tdescription: \"Start or show the goal ledger (/goal <text> to start, /goal to show status)\",\n\t},\n\t{\n\t\tname: \"goal-continue\",\n\t\tdescription: \"Continue the current goal loop explicitly (/goal-continue [turns] [stalls])\",\n\t},\n\t{ name: \"model\", description: \"Select model (opens selector UI)\" },\n\t{ name: \"profiles\", description: \"Select a runtime profile for this session\" },\n\t{ name: \"scoped-models\", description: \"Enable/disable models for Ctrl+P cycling\" },\n\t{ name: \"export\", description: \"Export session (HTML default, or specify path: .html/.jsonl)\" },\n\t{ name: \"import\", description: \"Import and resume a session from a JSONL file\" },\n\t{ name: \"share\", description: \"Share session as a secret GitHub gist\" },\n\t{ name: \"copy\", description: \"Copy last agent message to clipboard\" },\n\t{ name: \"name\", description: \"Set session display name\" },\n\t{ name: \"session\", description: \"Show session info and stats\" },\n\t{ name: \"usage\", description: \"Show tokens, cost, and optimization controls\" },\n\t{ name: \"changelog\", description: \"Show changelog entries\" },\n\t{ name: \"hotkeys\", description: \"Show all keyboard shortcuts\" },\n\t{ name: \"fork\", description: \"Create a new fork from a previous user message (optional name: /fork <name>)\" },\n\t{\n\t\tname: \"clone\",\n\t\tdescription: \"Duplicate the current session at the current position (optional name: /clone <name>)\",\n\t},\n\t{ name: \"tree\", description: \"Navigate session tree (switch branches)\" },\n\t{ name: \"trust\", description: \"Trust or untrust this project folder\" },\n\t{ name: \"login\", description: \"Configure provider authentication\" },\n\t{ name: \"logout\", description: \"Remove provider authentication\" },\n\t{ name: \"new\", description: \"Start a new session (optional name: /new <name>)\" },\n\t{ name: \"compact\", description: \"Manually compact the session context\" },\n\t{ name: \"curate\", description: \"Review/archive stale or overlapping reflection-promoted skills\" },\n\t{ name: \"resume\", description: \"Resume a different session\" },\n\t{ name: \"reload\", description: \"Reload keybindings, extensions, skills, prompts, and themes\" },\n\t{ name: \"exit\", description: `Quit ${APP_NAME}` },\n\t{\n\t\tname: \"install-resources\",\n\t\tdescription:\n\t\t\t\"Copy resources from a trusted directory to user local settings (/install-resources <dir> [--force])\",\n\t},\n\t{\n\t\tname: \"config-backup\",\n\t\tdescription: \"Backup profiles and resource settings to a JSON file (/config-backup [file])\",\n\t},\n\t{\n\t\tname: \"config-restore\",\n\t\tdescription: \"Restore profiles and resource settings from a JSON file (/config-restore <file>)\",\n\t},\n\t{ name: \"quit\", description: `Quit ${APP_NAME}` },\n];\n"]}
1
+ {"version":3,"file":"slash-commands.d.ts","sourceRoot":"","sources":["../../src/core/slash-commands.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAEnD,MAAM,MAAM,kBAAkB,GAAG,WAAW,GAAG,QAAQ,GAAG,OAAO,CAAC;AAElE,MAAM,WAAW,gBAAgB;IAChC,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,MAAM,EAAE,kBAAkB,CAAC;IAC3B,UAAU,EAAE,UAAU,CAAC;CACvB;AAED,MAAM,WAAW,mBAAmB;IACnC,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,EAAE,MAAM,CAAC;CACpB;AAED,eAAO,MAAM,sBAAsB,EAAE,aAAa,CAAC,mBAAmB,CAwErE,CAAC","sourcesContent":["import { APP_NAME } from \"../config.ts\";\nimport type { SourceInfo } from \"./source-info.ts\";\n\nexport type SlashCommandSource = \"extension\" | \"prompt\" | \"skill\";\n\nexport interface SlashCommandInfo {\n\tname: string;\n\tdescription?: string;\n\tsource: SlashCommandSource;\n\tsourceInfo: SourceInfo;\n}\n\nexport interface BuiltinSlashCommand {\n\tname: string;\n\tdescription: string;\n}\n\nexport const BUILTIN_SLASH_COMMANDS: ReadonlyArray<BuiltinSlashCommand> = [\n\t{ name: \"settings\", description: \"Open settings menu\" },\n\t{ name: \"autonomy\", description: \"Autonomy mode, diagnostics, research, fitness (/autonomy status)\" },\n\t{\n\t\tname: \"models\",\n\t\tdescription: \"Local model lifecycle: /models [list|suggest|add <ref>|remove <ref> confirm|stop]\",\n\t},\n\t{\n\t\tname: \"fitness\",\n\t\tdescription: \"Pick and probe a model for local/heavy-lifter roles, then assign it (/fitness [model] [trials])\",\n\t},\n\t{ name: \"context\", description: \"Context composition dashboard: what rides on every request\" },\n\t{ name: \"toolhealth\", description: \"Show tool repair diagnostics and learned standing rules\" },\n\t{ name: \"toolprobe\", description: \"Probe native/text tool-call support (/toolprobe [provider/model])\" },\n\t{\n\t\tname: \"toolrule-remove\",\n\t\tdescription: \"Remove a learned tool repair standing rule (/toolrule-remove <model> <mode>)\",\n\t},\n\t{\n\t\tname: \"toolprotocol-reset\",\n\t\tdescription: \"Reset text tool protocol calibration for a model (/toolprotocol-reset <provider/model>)\",\n\t},\n\t{ name: \"auto-learn\", description: \"Show Auto Learn/reflection status or run now (/auto-learn run)\" },\n\t{\n\t\tname: \"goal\",\n\t\tdescription: \"Goal lifecycle: status, resume, reopen, complete, close, or override (/goal to show controls)\",\n\t},\n\t{\n\t\tname: \"goal-continue\",\n\t\tdescription: \"Continue the current goal loop explicitly (/goal-continue [turns] [stalls])\",\n\t},\n\t{ name: \"model\", description: \"Select model (opens selector UI)\" },\n\t{ name: \"profiles\", description: \"Select a runtime profile for this session\" },\n\t{ name: \"scoped-models\", description: \"Enable/disable models for Ctrl+P cycling\" },\n\t{ name: \"export\", description: \"Export session (HTML default, or specify path: .html/.jsonl)\" },\n\t{ name: \"import\", description: \"Import and resume a session from a JSONL file\" },\n\t{ name: \"share\", description: \"Share session as a secret GitHub gist\" },\n\t{ name: \"copy\", description: \"Copy last agent message to clipboard\" },\n\t{ name: \"name\", description: \"Set session display name\" },\n\t{ name: \"session\", description: \"Show session info and stats\" },\n\t{ name: \"usage\", description: \"Show tokens, cost, and optimization controls\" },\n\t{ name: \"changelog\", description: \"Show changelog entries\" },\n\t{ name: \"hotkeys\", description: \"Show all keyboard shortcuts\" },\n\t{ name: \"fork\", description: \"Create a new fork from a previous user message (optional name: /fork <name>)\" },\n\t{\n\t\tname: \"clone\",\n\t\tdescription: \"Duplicate the current session at the current position (optional name: /clone <name>)\",\n\t},\n\t{ name: \"tree\", description: \"Navigate session tree (switch branches)\" },\n\t{ name: \"trust\", description: \"Trust or untrust this project folder\" },\n\t{ name: \"login\", description: \"Configure provider authentication\" },\n\t{ name: \"logout\", description: \"Remove provider authentication\" },\n\t{ name: \"new\", description: \"Start a new session (optional name: /new <name>)\" },\n\t{ name: \"compact\", description: \"Manually compact the session context\" },\n\t{ name: \"curate\", description: \"Review/archive stale or overlapping reflection-promoted skills\" },\n\t{ name: \"resume\", description: \"Resume a different session\" },\n\t{ name: \"reload\", description: \"Reload keybindings, extensions, skills, prompts, and themes\" },\n\t{ name: \"exit\", description: `Quit ${APP_NAME}` },\n\t{\n\t\tname: \"install-resources\",\n\t\tdescription:\n\t\t\t\"Copy resources from a trusted directory to user local settings (/install-resources <dir> [--force])\",\n\t},\n\t{\n\t\tname: \"config-backup\",\n\t\tdescription: \"Backup profiles and resource settings to a JSON file (/config-backup [file])\",\n\t},\n\t{\n\t\tname: \"config-restore\",\n\t\tdescription: \"Restore profiles and resource settings from a JSON file (/config-restore <file>)\",\n\t},\n\t{ name: \"quit\", description: `Quit ${APP_NAME}` },\n];\n"]}
@@ -24,7 +24,7 @@ export const BUILTIN_SLASH_COMMANDS = [
24
24
  { name: "auto-learn", description: "Show Auto Learn/reflection status or run now (/auto-learn run)" },
25
25
  {
26
26
  name: "goal",
27
- description: "Start or show the goal ledger (/goal <text> to start, /goal to show status)",
27
+ description: "Goal lifecycle: status, resume, reopen, complete, close, or override (/goal to show controls)",
28
28
  },
29
29
  {
30
30
  name: "goal-continue",
@@ -1 +1 @@
1
- {"version":3,"file":"slash-commands.js","sourceRoot":"","sources":["../../src/core/slash-commands.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AAiBxC,MAAM,CAAC,MAAM,sBAAsB,GAAuC;IACzE,EAAE,IAAI,EAAE,UAAU,EAAE,WAAW,EAAE,oBAAoB,EAAE;IACvD,EAAE,IAAI,EAAE,UAAU,EAAE,WAAW,EAAE,kEAAkE,EAAE;IACrG;QACC,IAAI,EAAE,QAAQ;QACd,WAAW,EAAE,mFAAmF;KAChG;IACD;QACC,IAAI,EAAE,SAAS;QACf,WAAW,EAA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I,EAAE,SAAS,EAAE,WAAW,EAAE,6BAA6B,EAAE;IAC/D,EAAE,IAAI,EAAE,MAAM,EAAE,WAAW,EAAE,8EAA8E,EAAE;IAC7G;QACC,IAAI,EAAE,OAAO;QACb,WAAW,EAAE,sFAAsF;KACnG;IACD,EAAE,IAAI,EAAE,MAAM,EAAE,WAAW,EAAE,yCAAyC,EAAE;IACxE,EAAE,IAAI,EAAE,OAAO,EAAE,WAAW,EAAE,sCAAsC,EAAE;IACtE,EAAE,IAAI,EAAE,OAAO,EAAE,WAAW,EAAE,mCAAmC,EAAE;IACnE,EAAE,IAAI,EAAE,QAAQ,EAAE,WAAW,EAAE,gCAAgC,EAAE;IACjE,EAAE,IAAI,EAAE,KAAK,EAAE,WAAW,EAAE,kDAAkD,EAAE;IAChF,EAAE,IAAI,EAAE,SAAS,EAAE,WAAW,EAAE,sCAAsC,EAAE;IACxE,EAAE,IAAI,EAAE,QAAQ,EAAE,WAAW,EAAE,gEAAgE,EAAE;IACjG,EAAE,IAAI,EAAE,QAAQ,EAAE,WAAW,EAAE,4BAA4B,EAAE;IAC7D,EAAE,IAAI,EAAE,QAAQ,EAAE,WAAW,EAAE,6DAA6D,EAAE;IAC9F,EAAE,IAAI,EAAE,MAAM,EAAE,WAAW,EAAE,QAAQ,QAAQ,EAAE,EAAE;IACjD;QACC,IAAI,EAAE,mBAAmB;QACzB,WAAW,EACV,qGAAqG;KACtG;IACD;QACC,IAAI,EAAE,eAAe;QACrB,WAAW,EAAE,8EAA8E;KAC3F;IACD;QACC,IAAI,EAAE,gBAAgB;QACtB,WAAW,EAAE,kFAAkF;KAC/F;IACD,EAAE,IAAI,EAAE,MAAM,EAAE,WAAW,EAAE,QAAQ,QAAQ,EAAE,EAAE;CACjD,CAAC","sourcesContent":["import { APP_NAME } from \"../config.ts\";\nimport type { SourceInfo } from \"./source-info.ts\";\n\nexport type SlashCommandSource = \"extension\" | \"prompt\" | \"skill\";\n\nexport interface SlashCommandInfo {\n\tname: string;\n\tdescription?: string;\n\tsource: SlashCommandSource;\n\tsourceInfo: SourceInfo;\n}\n\nexport interface BuiltinSlashCommand {\n\tname: string;\n\tdescription: string;\n}\n\nexport const BUILTIN_SLASH_COMMANDS: ReadonlyArray<BuiltinSlashCommand> = [\n\t{ name: \"settings\", description: \"Open settings menu\" },\n\t{ name: \"autonomy\", description: \"Autonomy mode, diagnostics, research, fitness (/autonomy status)\" },\n\t{\n\t\tname: \"models\",\n\t\tdescription: \"Local model lifecycle: /models [list|suggest|add <ref>|remove <ref> confirm|stop]\",\n\t},\n\t{\n\t\tname: \"fitness\",\n\t\tdescription: \"Pick and probe a model for local/heavy-lifter roles, then assign it (/fitness [model] [trials])\",\n\t},\n\t{ name: \"context\", description: \"Context composition dashboard: what rides on every request\" },\n\t{ name: \"toolhealth\", description: \"Show tool repair diagnostics and learned standing rules\" },\n\t{ name: \"toolprobe\", description: \"Probe native/text tool-call support (/toolprobe [provider/model])\" },\n\t{\n\t\tname: \"toolrule-remove\",\n\t\tdescription: \"Remove a learned tool repair standing rule (/toolrule-remove <model> <mode>)\",\n\t},\n\t{\n\t\tname: \"toolprotocol-reset\",\n\t\tdescription: \"Reset text tool protocol calibration for a model (/toolprotocol-reset <provider/model>)\",\n\t},\n\t{ name: \"auto-learn\", description: \"Show Auto Learn/reflection status or run now (/auto-learn run)\" },\n\t{\n\t\tname: \"goal\",\n\t\tdescription: \"Start or show the goal ledger (/goal <text> to start, /goal to show status)\",\n\t},\n\t{\n\t\tname: \"goal-continue\",\n\t\tdescription: \"Continue the current goal loop explicitly (/goal-continue [turns] [stalls])\",\n\t},\n\t{ name: \"model\", description: \"Select model (opens selector UI)\" },\n\t{ name: \"profiles\", description: \"Select a runtime profile for this session\" },\n\t{ name: \"scoped-models\", description: \"Enable/disable models for Ctrl+P cycling\" },\n\t{ name: \"export\", description: \"Export session (HTML default, or specify path: .html/.jsonl)\" },\n\t{ name: \"import\", description: \"Import and resume a session from a JSONL file\" },\n\t{ name: \"share\", description: \"Share session as a secret GitHub gist\" },\n\t{ name: \"copy\", description: \"Copy last agent message to clipboard\" },\n\t{ name: \"name\", description: \"Set session display name\" },\n\t{ name: \"session\", description: \"Show session info and stats\" },\n\t{ name: \"usage\", description: \"Show tokens, cost, and optimization controls\" },\n\t{ name: \"changelog\", description: \"Show changelog entries\" },\n\t{ name: \"hotkeys\", description: \"Show all keyboard shortcuts\" },\n\t{ name: \"fork\", description: \"Create a new fork from a previous user message (optional name: /fork <name>)\" },\n\t{\n\t\tname: \"clone\",\n\t\tdescription: \"Duplicate the current session at the current position (optional name: /clone <name>)\",\n\t},\n\t{ name: \"tree\", description: \"Navigate session tree (switch branches)\" },\n\t{ name: \"trust\", description: \"Trust or untrust this project folder\" },\n\t{ name: \"login\", description: \"Configure provider authentication\" },\n\t{ name: \"logout\", description: \"Remove provider authentication\" },\n\t{ name: \"new\", description: \"Start a new session (optional name: /new <name>)\" },\n\t{ name: \"compact\", description: \"Manually compact the session context\" },\n\t{ name: \"curate\", description: \"Review/archive stale or overlapping reflection-promoted skills\" },\n\t{ name: \"resume\", description: \"Resume a different session\" },\n\t{ name: \"reload\", description: \"Reload keybindings, extensions, skills, prompts, and themes\" },\n\t{ name: \"exit\", description: `Quit ${APP_NAME}` },\n\t{\n\t\tname: \"install-resources\",\n\t\tdescription:\n\t\t\t\"Copy resources from a trusted directory to user local settings (/install-resources <dir> [--force])\",\n\t},\n\t{\n\t\tname: \"config-backup\",\n\t\tdescription: \"Backup profiles and resource settings to a JSON file (/config-backup [file])\",\n\t},\n\t{\n\t\tname: \"config-restore\",\n\t\tdescription: \"Restore profiles and resource settings from a JSON file (/config-restore <file>)\",\n\t},\n\t{ name: \"quit\", description: `Quit ${APP_NAME}` },\n];\n"]}
1
+ {"version":3,"file":"slash-commands.js","sourceRoot":"","sources":["../../src/core/slash-commands.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AAiBxC,MAAM,CAAC,MAAM,sBAAsB,GA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C/F;IACD,EAAE,IAAI,EAAE,MAAM,EAAE,WAAW,EAAE,QAAQ,QAAQ,EAAE,EAAE;CACjD,CAAC","sourcesContent":["import { APP_NAME } from \"../config.ts\";\nimport type { SourceInfo } from \"./source-info.ts\";\n\nexport type SlashCommandSource = \"extension\" | \"prompt\" | \"skill\";\n\nexport interface SlashCommandInfo {\n\tname: string;\n\tdescription?: string;\n\tsource: SlashCommandSource;\n\tsourceInfo: SourceInfo;\n}\n\nexport interface BuiltinSlashCommand {\n\tname: string;\n\tdescription: string;\n}\n\nexport const BUILTIN_SLASH_COMMANDS: ReadonlyArray<BuiltinSlashCommand> = [\n\t{ name: \"settings\", description: \"Open settings menu\" },\n\t{ name: \"autonomy\", description: \"Autonomy mode, diagnostics, research, fitness (/autonomy status)\" },\n\t{\n\t\tname: \"models\",\n\t\tdescription: \"Local model lifecycle: /models [list|suggest|add <ref>|remove <ref> confirm|stop]\",\n\t},\n\t{\n\t\tname: \"fitness\",\n\t\tdescription: \"Pick and probe a model for local/heavy-lifter roles, then assign it (/fitness [model] [trials])\",\n\t},\n\t{ name: \"context\", description: \"Context composition dashboard: what rides on every request\" },\n\t{ name: \"toolhealth\", description: \"Show tool repair diagnostics and learned standing rules\" },\n\t{ name: \"toolprobe\", description: \"Probe native/text tool-call support (/toolprobe [provider/model])\" },\n\t{\n\t\tname: \"toolrule-remove\",\n\t\tdescription: \"Remove a learned tool repair standing rule (/toolrule-remove <model> <mode>)\",\n\t},\n\t{\n\t\tname: \"toolprotocol-reset\",\n\t\tdescription: \"Reset text tool protocol calibration for a model (/toolprotocol-reset <provider/model>)\",\n\t},\n\t{ name: \"auto-learn\", description: \"Show Auto Learn/reflection status or run now (/auto-learn run)\" },\n\t{\n\t\tname: \"goal\",\n\t\tdescription: \"Goal lifecycle: status, resume, reopen, complete, close, or override (/goal to show controls)\",\n\t},\n\t{\n\t\tname: \"goal-continue\",\n\t\tdescription: \"Continue the current goal loop explicitly (/goal-continue [turns] [stalls])\",\n\t},\n\t{ name: \"model\", description: \"Select model (opens selector UI)\" },\n\t{ name: \"profiles\", description: \"Select a runtime profile for this session\" },\n\t{ name: \"scoped-models\", description: \"Enable/disable models for Ctrl+P cycling\" },\n\t{ name: \"export\", description: \"Export session (HTML default, or specify path: .html/.jsonl)\" },\n\t{ name: \"import\", description: \"Import and resume a session from a JSONL file\" },\n\t{ name: \"share\", description: \"Share session as a secret GitHub gist\" },\n\t{ name: \"copy\", description: \"Copy last agent message to clipboard\" },\n\t{ name: \"name\", description: \"Set session display name\" },\n\t{ name: \"session\", description: \"Show session info and stats\" },\n\t{ name: \"usage\", description: \"Show tokens, cost, and optimization controls\" },\n\t{ name: \"changelog\", description: \"Show changelog entries\" },\n\t{ name: \"hotkeys\", description: \"Show all keyboard shortcuts\" },\n\t{ name: \"fork\", description: \"Create a new fork from a previous user message (optional name: /fork <name>)\" },\n\t{\n\t\tname: \"clone\",\n\t\tdescription: \"Duplicate the current session at the current position (optional name: /clone <name>)\",\n\t},\n\t{ name: \"tree\", description: \"Navigate session tree (switch branches)\" },\n\t{ name: \"trust\", description: \"Trust or untrust this project folder\" },\n\t{ name: \"login\", description: \"Configure provider authentication\" },\n\t{ name: \"logout\", description: \"Remove provider authentication\" },\n\t{ name: \"new\", description: \"Start a new session (optional name: /new <name>)\" },\n\t{ name: \"compact\", description: \"Manually compact the session context\" },\n\t{ name: \"curate\", description: \"Review/archive stale or overlapping reflection-promoted skills\" },\n\t{ name: \"resume\", description: \"Resume a different session\" },\n\t{ name: \"reload\", description: \"Reload keybindings, extensions, skills, prompts, and themes\" },\n\t{ name: \"exit\", description: `Quit ${APP_NAME}` },\n\t{\n\t\tname: \"install-resources\",\n\t\tdescription:\n\t\t\t\"Copy resources from a trusted directory to user local settings (/install-resources <dir> [--force])\",\n\t},\n\t{\n\t\tname: \"config-backup\",\n\t\tdescription: \"Backup profiles and resource settings to a JSON file (/config-backup [file])\",\n\t},\n\t{\n\t\tname: \"config-restore\",\n\t\tdescription: \"Restore profiles and resource settings from a JSON file (/config-restore <file>)\",\n\t},\n\t{ name: \"quit\", description: `Quit ${APP_NAME}` },\n];\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"script-runner.d.ts","sourceRoot":"","sources":["../../../src/core/toolkit/script-runner.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAE1D;;;;GAIG;AAEH,MAAM,WAAW,eAAe;IAC/B,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAC;IACxB,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;IACf,UAAU,EAAE,MAAM,CAAC;IACnB,QAAQ,EAAE,OAAO,CAAC;CAClB;AAED,MAAM,MAAM,cAAc,GAAG,CAC5B,OAAO,EAAE,MAAM,EACf,IAAI,EAAE,MAAM,EAAE,EACd,GAAG,EAAE,MAAM,EACX,SAAS,EAAE,MAAM,KACb,OAAO,CAAC,eAAe,CAAC,CAAC;AAE9B,wBAAgB,eAAe,CAAC,MAAM,EAAE,aAAa,EAAE,IAAI,EAAE,SAAS,MAAM,EAAE,GAAG;IAAE,OAAO,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,EAAE,CAAA;CAAE,CAYnH;AAID,6FAA6F;AAC7F,eAAO,MAAM,mBAAmB,EAAE,cA+B/B,CAAC;AAEJ,wBAAsB,oBAAoB,CAAC,IAAI,EAAE;IAChD,MAAM,EAAE,aAAa,CAAC;IACtB,UAAU,EAAE,SAAS,MAAM,EAAE,CAAC;IAC9B,GAAG,EAAE,MAAM,CAAC;IACZ,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,QAAQ,CAAC,EAAE,cAAc,CAAC;CAC1B,GAAG,OAAO,CAAC,eAAe,CAAC,CAI3B","sourcesContent":["import { execFile } from \"node:child_process\";\nimport type { ToolkitScript } from \"./script-registry.ts\";\n\n/**\n * Toolkit script invocation: the harness owns execution. Fixed argv per runner (never a shell\n * string), captured exit/stdout/stderr ALWAYS — the structural error contract that makes\n * false-success impossible regardless of what the model narrates.\n */\n\nexport interface ScriptExecution {\n\texitCode: number | null;\n\tstdout: string;\n\tstderr: string;\n\tdurationMs: number;\n\ttimedOut: boolean;\n}\n\nexport type ScriptExecutor = (\n\tcommand: string,\n\targv: string[],\n\tcwd: string,\n\ttimeoutMs: number,\n) => Promise<ScriptExecution>;\n\nexport function buildScriptArgv(script: ToolkitScript, args: readonly string[]): { command: string; argv: string[] } {\n\tswitch (script.runner) {\n\t\tcase \"uv\":\n\t\t\treturn { command: \"uv\", argv: [\"run\", script.path, ...args] };\n\t\tcase \"powershell\":\n\t\t\treturn {\n\t\t\t\tcommand: \"powershell.exe\",\n\t\t\t\targv: [\"-NoProfile\", \"-ExecutionPolicy\", \"Bypass\", \"-File\", script.path, ...args],\n\t\t\t};\n\t\tcase \"bash\":\n\t\t\treturn { command: \"bash\", argv: [script.path, ...args] };\n\t}\n}\n\nconst MAX_OUTPUT_BYTES = 512 * 1024;\n\n/** Default executor: real process spawn, no shell interpolation, bounded output and time. */\nexport const spawnScriptExecutor: ScriptExecutor = (command, argv, cwd, timeoutMs) =>\n\tnew Promise((resolve) => {\n\t\tconst started = Date.now();\n\t\texecFile(\n\t\t\tcommand,\n\t\t\targv,\n\t\t\t{ cwd, timeout: timeoutMs, maxBuffer: MAX_OUTPUT_BYTES, encoding: \"utf-8\" },\n\t\t\t(error, stdout, stderr) => {\n\t\t\t\tconst durationMs = Date.now() - started;\n\t\t\t\tconst err = error as (Error & { killed?: boolean; code?: number | string }) | null;\n\t\t\t\t// error.code is a NUMBER for a non-zero exit but a STRING for spawn-level failures\n\t\t\t\t// (ENOENT, EACCES) and for the maxBuffer kill — which also sets killed=true and must\n\t\t\t\t// not be mislabeled as a timeout.\n\t\t\t\tconst maxBufferExceeded = err?.code === \"ERR_CHILD_PROCESS_STDIO_MAXBUFFER\";\n\t\t\t\tconst timedOut = Boolean(err?.killed) && !maxBufferExceeded;\n\t\t\t\tconst exitCode = err ? (typeof err.code === \"number\" ? err.code : null) : 0;\n\t\t\t\t// Spawn-level failures never produce their own stderr; surface the error message so\n\t\t\t\t// the cause (missing runner, permission, output overflow) is never silently dropped.\n\t\t\t\tlet capturedStderr = stderr ?? \"\";\n\t\t\t\tif (err && !timedOut && typeof err.code !== \"number\" && capturedStderr.length === 0) {\n\t\t\t\t\tcapturedStderr = err.message;\n\t\t\t\t}\n\t\t\t\tresolve({\n\t\t\t\t\texitCode,\n\t\t\t\t\tstdout: stdout ?? \"\",\n\t\t\t\t\tstderr: capturedStderr,\n\t\t\t\t\tdurationMs,\n\t\t\t\t\ttimedOut,\n\t\t\t\t});\n\t\t\t},\n\t\t);\n\t});\n\nexport async function executeToolkitScript(args: {\n\tscript: ToolkitScript;\n\tscriptArgs: readonly string[];\n\tcwd: string;\n\ttimeoutMs?: number;\n\texecutor?: ScriptExecutor;\n}): Promise<ScriptExecution> {\n\tconst { command, argv } = buildScriptArgv(args.script, args.scriptArgs);\n\tconst executor = args.executor ?? spawnScriptExecutor;\n\treturn executor(command, argv, args.cwd, args.timeoutMs ?? 120_000);\n}\n"]}
1
+ {"version":3,"file":"script-runner.d.ts","sourceRoot":"","sources":["../../../src/core/toolkit/script-runner.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAE1D;;;;GAIG;AAEH,MAAM,WAAW,eAAe;IAC/B,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAC;IACxB,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;IACf,UAAU,EAAE,MAAM,CAAC;IACnB,QAAQ,EAAE,OAAO,CAAC;CAClB;AAED,MAAM,MAAM,cAAc,GAAG,CAC5B,OAAO,EAAE,MAAM,EACf,IAAI,EAAE,MAAM,EAAE,EACd,GAAG,EAAE,MAAM,EACX,SAAS,EAAE,MAAM,KACb,OAAO,CAAC,eAAe,CAAC,CAAC;AAE9B,wBAAgB,eAAe,CAAC,MAAM,EAAE,aAAa,EAAE,IAAI,EAAE,SAAS,MAAM,EAAE,GAAG;IAAE,OAAO,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,EAAE,CAAA;CAAE,CAYnH;AAKD,6FAA6F;AAC7F,eAAO,MAAM,mBAAmB,EAAE,cAyDjC,CAAC;AAEF,wBAAsB,oBAAoB,CAAC,IAAI,EAAE;IAChD,MAAM,EAAE,aAAa,CAAC;IACtB,UAAU,EAAE,SAAS,MAAM,EAAE,CAAC;IAC9B,GAAG,EAAE,MAAM,CAAC;IACZ,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,QAAQ,CAAC,EAAE,cAAc,CAAC;CAC1B,GAAG,OAAO,CAAC,eAAe,CAAC,CAI3B","sourcesContent":["import { spawnProcess, waitForChildProcessWithTermination } from \"../../utils/child-process.ts\";\nimport type { ToolkitScript } from \"./script-registry.ts\";\n\n/**\n * Toolkit script invocation: the harness owns execution. Fixed argv per runner (never a shell\n * string), captured exit/stdout/stderr ALWAYS — the structural error contract that makes\n * false-success impossible regardless of what the model narrates.\n */\n\nexport interface ScriptExecution {\n\texitCode: number | null;\n\tstdout: string;\n\tstderr: string;\n\tdurationMs: number;\n\ttimedOut: boolean;\n}\n\nexport type ScriptExecutor = (\n\tcommand: string,\n\targv: string[],\n\tcwd: string,\n\ttimeoutMs: number,\n) => Promise<ScriptExecution>;\n\nexport function buildScriptArgv(script: ToolkitScript, args: readonly string[]): { command: string; argv: string[] } {\n\tswitch (script.runner) {\n\t\tcase \"uv\":\n\t\t\treturn { command: \"uv\", argv: [\"run\", script.path, ...args] };\n\t\tcase \"powershell\":\n\t\t\treturn {\n\t\t\t\tcommand: \"powershell.exe\",\n\t\t\t\targv: [\"-NoProfile\", \"-ExecutionPolicy\", \"Bypass\", \"-File\", script.path, ...args],\n\t\t\t};\n\t\tcase \"bash\":\n\t\t\treturn { command: \"bash\", argv: [script.path, ...args] };\n\t}\n}\n\nconst MAX_OUTPUT_BYTES = 512 * 1024;\nconst SCRIPT_KILL_GRACE_MS = 2_000;\n\n/** Default executor: real process spawn, no shell interpolation, bounded output and time. */\nexport const spawnScriptExecutor: ScriptExecutor = async (command, argv, cwd, timeoutMs) => {\n\tconst started = Date.now();\n\tconst terminationController = new AbortController();\n\tconst stdoutChunks: Buffer[] = [];\n\tconst stderrChunks: Buffer[] = [];\n\tlet stdoutBytes = 0;\n\tlet stderrBytes = 0;\n\tlet outputExceeded = false;\n\tconst appendChunk = (chunks: Buffer[], chunk: Buffer, streamBytes: number): number => {\n\t\tconst remaining = Math.max(0, MAX_OUTPUT_BYTES - streamBytes);\n\t\tif (remaining > 0) chunks.push(chunk.subarray(0, remaining));\n\t\tconst nextBytes = streamBytes + chunk.length;\n\t\tif (nextBytes > MAX_OUTPUT_BYTES) {\n\t\t\toutputExceeded = true;\n\t\t\tterminationController.abort();\n\t\t}\n\t\treturn nextBytes;\n\t};\n\n\ttry {\n\t\tconst child = spawnProcess(command, argv, {\n\t\t\tcwd,\n\t\t\tdetached: process.platform !== \"win32\",\n\t\t\tstdio: [\"ignore\", \"pipe\", \"pipe\"],\n\t\t});\n\t\tchild.stdout?.on(\"data\", (chunk: Buffer) => {\n\t\t\tstdoutBytes = appendChunk(stdoutChunks, chunk, stdoutBytes);\n\t\t});\n\t\tchild.stderr?.on(\"data\", (chunk: Buffer) => {\n\t\t\tstderrBytes = appendChunk(stderrChunks, chunk, stderrBytes);\n\t\t});\n\t\tconst terminal = await waitForChildProcessWithTermination(child, {\n\t\t\tsignal: terminationController.signal,\n\t\t\ttimeoutMs,\n\t\t\tkillGraceMs: SCRIPT_KILL_GRACE_MS,\n\t\t});\n\t\tconst stdout = Buffer.concat(stdoutChunks).toString(\"utf8\");\n\t\tlet stderr = Buffer.concat(stderrChunks).toString(\"utf8\");\n\t\tif (outputExceeded) {\n\t\t\tstderr = `${stderr}${stderr ? \"\\n\" : \"\"}Command output exceeded maxBuffer (${MAX_OUTPUT_BYTES} bytes)`;\n\t\t}\n\t\treturn {\n\t\t\texitCode: outputExceeded ? null : terminal.code,\n\t\t\tstdout,\n\t\t\tstderr,\n\t\t\tdurationMs: Date.now() - started,\n\t\t\ttimedOut: terminal.reason === \"timeout\",\n\t\t};\n\t} catch (error) {\n\t\treturn {\n\t\t\texitCode: null,\n\t\t\tstdout: Buffer.concat(stdoutChunks).toString(\"utf8\"),\n\t\t\tstderr: error instanceof Error ? error.message : String(error),\n\t\t\tdurationMs: Date.now() - started,\n\t\t\ttimedOut: false,\n\t\t};\n\t}\n};\n\nexport async function executeToolkitScript(args: {\n\tscript: ToolkitScript;\n\tscriptArgs: readonly string[];\n\tcwd: string;\n\ttimeoutMs?: number;\n\texecutor?: ScriptExecutor;\n}): Promise<ScriptExecution> {\n\tconst { command, argv } = buildScriptArgv(args.script, args.scriptArgs);\n\tconst executor = args.executor ?? spawnScriptExecutor;\n\treturn executor(command, argv, args.cwd, args.timeoutMs ?? 120_000);\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { execFile } from "node:child_process";
1
+ import { spawnProcess, waitForChildProcessWithTermination } from "../../utils/child-process.js";
2
2
  export function buildScriptArgv(script, args) {
3
3
  switch (script.runner) {
4
4
  case "uv":
@@ -13,33 +13,67 @@ export function buildScriptArgv(script, args) {
13
13
  }
14
14
  }
15
15
  const MAX_OUTPUT_BYTES = 512 * 1024;
16
+ const SCRIPT_KILL_GRACE_MS = 2_000;
16
17
  /** Default executor: real process spawn, no shell interpolation, bounded output and time. */
17
- export const spawnScriptExecutor = (command, argv, cwd, timeoutMs) => new Promise((resolve) => {
18
+ export const spawnScriptExecutor = async (command, argv, cwd, timeoutMs) => {
18
19
  const started = Date.now();
19
- execFile(command, argv, { cwd, timeout: timeoutMs, maxBuffer: MAX_OUTPUT_BYTES, encoding: "utf-8" }, (error, stdout, stderr) => {
20
- const durationMs = Date.now() - started;
21
- const err = error;
22
- // error.code is a NUMBER for a non-zero exit but a STRING for spawn-level failures
23
- // (ENOENT, EACCES) and for the maxBuffer kill — which also sets killed=true and must
24
- // not be mislabeled as a timeout.
25
- const maxBufferExceeded = err?.code === "ERR_CHILD_PROCESS_STDIO_MAXBUFFER";
26
- const timedOut = Boolean(err?.killed) && !maxBufferExceeded;
27
- const exitCode = err ? (typeof err.code === "number" ? err.code : null) : 0;
28
- // Spawn-level failures never produce their own stderr; surface the error message so
29
- // the cause (missing runner, permission, output overflow) is never silently dropped.
30
- let capturedStderr = stderr ?? "";
31
- if (err && !timedOut && typeof err.code !== "number" && capturedStderr.length === 0) {
32
- capturedStderr = err.message;
20
+ const terminationController = new AbortController();
21
+ const stdoutChunks = [];
22
+ const stderrChunks = [];
23
+ let stdoutBytes = 0;
24
+ let stderrBytes = 0;
25
+ let outputExceeded = false;
26
+ const appendChunk = (chunks, chunk, streamBytes) => {
27
+ const remaining = Math.max(0, MAX_OUTPUT_BYTES - streamBytes);
28
+ if (remaining > 0)
29
+ chunks.push(chunk.subarray(0, remaining));
30
+ const nextBytes = streamBytes + chunk.length;
31
+ if (nextBytes > MAX_OUTPUT_BYTES) {
32
+ outputExceeded = true;
33
+ terminationController.abort();
33
34
  }
34
- resolve({
35
- exitCode,
36
- stdout: stdout ?? "",
37
- stderr: capturedStderr,
38
- durationMs,
39
- timedOut,
35
+ return nextBytes;
36
+ };
37
+ try {
38
+ const child = spawnProcess(command, argv, {
39
+ cwd,
40
+ detached: process.platform !== "win32",
41
+ stdio: ["ignore", "pipe", "pipe"],
40
42
  });
41
- });
42
- });
43
+ child.stdout?.on("data", (chunk) => {
44
+ stdoutBytes = appendChunk(stdoutChunks, chunk, stdoutBytes);
45
+ });
46
+ child.stderr?.on("data", (chunk) => {
47
+ stderrBytes = appendChunk(stderrChunks, chunk, stderrBytes);
48
+ });
49
+ const terminal = await waitForChildProcessWithTermination(child, {
50
+ signal: terminationController.signal,
51
+ timeoutMs,
52
+ killGraceMs: SCRIPT_KILL_GRACE_MS,
53
+ });
54
+ const stdout = Buffer.concat(stdoutChunks).toString("utf8");
55
+ let stderr = Buffer.concat(stderrChunks).toString("utf8");
56
+ if (outputExceeded) {
57
+ stderr = `${stderr}${stderr ? "\n" : ""}Command output exceeded maxBuffer (${MAX_OUTPUT_BYTES} bytes)`;
58
+ }
59
+ return {
60
+ exitCode: outputExceeded ? null : terminal.code,
61
+ stdout,
62
+ stderr,
63
+ durationMs: Date.now() - started,
64
+ timedOut: terminal.reason === "timeout",
65
+ };
66
+ }
67
+ catch (error) {
68
+ return {
69
+ exitCode: null,
70
+ stdout: Buffer.concat(stdoutChunks).toString("utf8"),
71
+ stderr: error instanceof Error ? error.message : String(error),
72
+ durationMs: Date.now() - started,
73
+ timedOut: false,
74
+ };
75
+ }
76
+ };
43
77
  export async function executeToolkitScript(args) {
44
78
  const { command, argv } = buildScriptArgv(args.script, args.scriptArgs);
45
79
  const executor = args.executor ?? spawnScriptExecutor;
@@ -1 +1 @@
1
- {"version":3,"file":"script-runner.js","sourceRoot":"","sources":["../../../src/core/toolkit/script-runner.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,oBAAoB,CAAC;AAwB9C,MAAM,UAAU,eAAe,CAAC,MAAqB,EAAE,IAAuB,EAAuC;IACpH,QAAQ,MAAM,CAAC,MAAM,EAAE,CAAC;QACvB,KAAK,IAAI;YACR,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,KAAK,EAAE,MAAM,CAAC,IAAI,EAAE,GAAG,IAAI,CAAC,EAAE,CAAC;QAC/D,KAAK,YAAY;YAChB,OAAO;gBACN,OAAO,EAAE,gBAAgB;gBACzB,IAAI,EAAE,CAAC,YAAY,EAAE,kBAAkB,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,CAAC,IAAI,EAAE,GAAG,IAAI,CAAC;aACjF,CAAC;QACH,KAAK,MAAM;YACV,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,MAAM,CAAC,IAAI,EAAE,GAAG,IAAI,CAAC,EAAE,CAAC;IAC3D,CAAC;AA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C;QACD,OAAO,CAAC;YACP,QAAQ;YACR,MAAM,EAAE,MAAM,IAAI,EAAE;YACpB,MAAM,EAAE,cAAc;YACtB,UAAU;YACV,QAAQ;SACR,CAAC,CAAC;IAAA,CACH,CACD,CAAC;AAAA,CACF,CAAC,CAAC;AAEJ,MAAM,CAAC,KAAK,UAAU,oBAAoB,CAAC,IAM1C,EAA4B;IAC5B,MAAM,EAAE,OAAO,EAAE,IAAI,EAAE,GAAG,eAAe,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,UAAU,CAAC,CAAC;IACxE,MAAM,QAAQ,GAAG,IAAI,CAAC,QAAQ,IAAI,mBAAmB,CAAC;IACtD,OAAO,QAAQ,CAAC,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC,GAAG,EAAE,IAAI,CAAC,SAAS,IAAI,OAAO,CAAC,CAAC;AAAA,CACpE","sourcesContent":["import { execFile } from \"node:child_process\";\nimport type { ToolkitScript } from \"./script-registry.ts\";\n\n/**\n * Toolkit script invocation: the harness owns execution. Fixed argv per runner (never a shell\n * string), captured exit/stdout/stderr ALWAYS — the structural error contract that makes\n * false-success impossible regardless of what the model narrates.\n */\n\nexport interface ScriptExecution {\n\texitCode: number | null;\n\tstdout: string;\n\tstderr: string;\n\tdurationMs: number;\n\ttimedOut: boolean;\n}\n\nexport type ScriptExecutor = (\n\tcommand: string,\n\targv: string[],\n\tcwd: string,\n\ttimeoutMs: number,\n) => Promise<ScriptExecution>;\n\nexport function buildScriptArgv(script: ToolkitScript, args: readonly string[]): { command: string; argv: string[] } {\n\tswitch (script.runner) {\n\t\tcase \"uv\":\n\t\t\treturn { command: \"uv\", argv: [\"run\", script.path, ...args] };\n\t\tcase \"powershell\":\n\t\t\treturn {\n\t\t\t\tcommand: \"powershell.exe\",\n\t\t\t\targv: [\"-NoProfile\", \"-ExecutionPolicy\", \"Bypass\", \"-File\", script.path, ...args],\n\t\t\t};\n\t\tcase \"bash\":\n\t\t\treturn { command: \"bash\", argv: [script.path, ...args] };\n\t}\n}\n\nconst MAX_OUTPUT_BYTES = 512 * 1024;\n\n/** Default executor: real process spawn, no shell interpolation, bounded output and time. */\nexport const spawnScriptExecutor: ScriptExecutor = (command, argv, cwd, timeoutMs) =>\n\tnew Promise((resolve) => {\n\t\tconst started = Date.now();\n\t\texecFile(\n\t\t\tcommand,\n\t\t\targv,\n\t\t\t{ cwd, timeout: timeoutMs, maxBuffer: MAX_OUTPUT_BYTES, encoding: \"utf-8\" },\n\t\t\t(error, stdout, stderr) => {\n\t\t\t\tconst durationMs = Date.now() - started;\n\t\t\t\tconst err = error as (Error & { killed?: boolean; code?: number | string }) | null;\n\t\t\t\t// error.code is a NUMBER for a non-zero exit but a STRING for spawn-level failures\n\t\t\t\t// (ENOENT, EACCES) and for the maxBuffer kill — which also sets killed=true and must\n\t\t\t\t// not be mislabeled as a timeout.\n\t\t\t\tconst maxBufferExceeded = err?.code === \"ERR_CHILD_PROCESS_STDIO_MAXBUFFER\";\n\t\t\t\tconst timedOut = Boolean(err?.killed) && !maxBufferExceeded;\n\t\t\t\tconst exitCode = err ? (typeof err.code === \"number\" ? err.code : null) : 0;\n\t\t\t\t// Spawn-level failures never produce their own stderr; surface the error message so\n\t\t\t\t// the cause (missing runner, permission, output overflow) is never silently dropped.\n\t\t\t\tlet capturedStderr = stderr ?? \"\";\n\t\t\t\tif (err && !timedOut && typeof err.code !== \"number\" && capturedStderr.length === 0) {\n\t\t\t\t\tcapturedStderr = err.message;\n\t\t\t\t}\n\t\t\t\tresolve({\n\t\t\t\t\texitCode,\n\t\t\t\t\tstdout: stdout ?? \"\",\n\t\t\t\t\tstderr: capturedStderr,\n\t\t\t\t\tdurationMs,\n\t\t\t\t\ttimedOut,\n\t\t\t\t});\n\t\t\t},\n\t\t);\n\t});\n\nexport async function executeToolkitScript(args: {\n\tscript: ToolkitScript;\n\tscriptArgs: readonly string[];\n\tcwd: string;\n\ttimeoutMs?: number;\n\texecutor?: ScriptExecutor;\n}): Promise<ScriptExecution> {\n\tconst { command, argv } = buildScriptArgv(args.script, args.scriptArgs);\n\tconst executor = args.executor ?? spawnScriptExecutor;\n\treturn executor(command, argv, args.cwd, args.timeoutMs ?? 120_000);\n}\n"]}
1
+ {"version":3,"file":"script-runner.js","sourceRoot":"","sources":["../../../src/core/toolkit/script-runner.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,kCAAkC,EAAE,MAAM,8BAA8B,CAAC;AAwBhG,MAAM,UAAU,eAAe,CAAC,MAAqB,EAAE,IAAuB,EAAuC;IACpH,QAAQ,MAAM,CAAC,MAAM,EAAE,CAAC;QACvB,KAAK,IAAI;YACR,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,KAAK,EAAE,MAAM,CAAC,IAAI,EAAE,GAAG,IAAI,CAAC,EAAE,CAAC;QAC/D,KAAK,YAAY;YAChB,OAAO;gBACN,OAAO,EAAE,gBAAgB;gBACzB,IAAI,EAAE,CAAC,YAAY,EAAE,kBAAkB,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,CAAC,IAAI,EAAE,GAAG,IAAI,CAAC;aACjF,CAAC;QACH,KAAK,MAAM;YACV,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,MAAM,CAAC,IAAI,EAAE,GAAG,IAAI,CAAC,EAAE,CAAC;IAC3D,CAAC;AAAA,CACD;AAED,MAAM,gBAAgB,GAAG,GAAG,GAAG,IAAI,CAAC;AACpC,MAAM,oBAAoB,GAAG,KAAK,CAAC;AAEnC,6FAA6F;AAC7F,MAAM,CAAC,MAAM,mBAAmB,GAAmB,KAAK,EAAE,OAAO,EAAE,IAAI,EAAE,GAAG,EAAE,SAAS,EAAE,EAAE,CAAC;IAC3F,MAAM,OAAO,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;IAC3B,MAAM,qBAAqB,GAAG,IAAI,eAAe,EAAE,CAAC;IACpD,MAAM,YAAY,GAAa,EAAE,CAAC;IAClC,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OAAO,EAAE,IAAI,EAAE,GAAG,eAAe,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,UAAU,CAAC,CAAC;IACxE,MAAM,QAAQ,GAAG,IAAI,CAAC,QAAQ,IAAI,mBAAmB,CAAC;IACtD,OAAO,QAAQ,CAAC,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC,GAAG,EAAE,IAAI,CAAC,SAAS,IAAI,OAAO,CAAC,CAAC;AAAA,CACpE","sourcesContent":["import { spawnProcess, waitForChildProcessWithTermination } from \"../../utils/child-process.ts\";\nimport type { ToolkitScript } from \"./script-registry.ts\";\n\n/**\n * Toolkit script invocation: the harness owns execution. Fixed argv per runner (never a shell\n * string), captured exit/stdout/stderr ALWAYS — the structural error contract that makes\n * false-success impossible regardless of what the model narrates.\n */\n\nexport interface ScriptExecution {\n\texitCode: number | null;\n\tstdout: string;\n\tstderr: string;\n\tdurationMs: number;\n\ttimedOut: boolean;\n}\n\nexport type ScriptExecutor = (\n\tcommand: string,\n\targv: string[],\n\tcwd: string,\n\ttimeoutMs: number,\n) => Promise<ScriptExecution>;\n\nexport function buildScriptArgv(script: ToolkitScript, args: readonly string[]): { command: string; argv: string[] } {\n\tswitch (script.runner) {\n\t\tcase \"uv\":\n\t\t\treturn { command: \"uv\", argv: [\"run\", script.path, ...args] };\n\t\tcase \"powershell\":\n\t\t\treturn {\n\t\t\t\tcommand: \"powershell.exe\",\n\t\t\t\targv: [\"-NoProfile\", \"-ExecutionPolicy\", \"Bypass\", \"-File\", script.path, ...args],\n\t\t\t};\n\t\tcase \"bash\":\n\t\t\treturn { command: \"bash\", argv: [script.path, ...args] };\n\t}\n}\n\nconst MAX_OUTPUT_BYTES = 512 * 1024;\nconst SCRIPT_KILL_GRACE_MS = 2_000;\n\n/** Default executor: real process spawn, no shell interpolation, bounded output and time. */\nexport const spawnScriptExecutor: ScriptExecutor = async (command, argv, cwd, timeoutMs) => {\n\tconst started = Date.now();\n\tconst terminationController = new AbortController();\n\tconst stdoutChunks: Buffer[] = [];\n\tconst stderrChunks: Buffer[] = [];\n\tlet stdoutBytes = 0;\n\tlet stderrBytes = 0;\n\tlet outputExceeded = false;\n\tconst appendChunk = (chunks: Buffer[], chunk: Buffer, streamBytes: number): number => {\n\t\tconst remaining = Math.max(0, MAX_OUTPUT_BYTES - streamBytes);\n\t\tif (remaining > 0) chunks.push(chunk.subarray(0, remaining));\n\t\tconst nextBytes = streamBytes + chunk.length;\n\t\tif (nextBytes > MAX_OUTPUT_BYTES) {\n\t\t\toutputExceeded = true;\n\t\t\tterminationController.abort();\n\t\t}\n\t\treturn nextBytes;\n\t};\n\n\ttry {\n\t\tconst child = spawnProcess(command, argv, {\n\t\t\tcwd,\n\t\t\tdetached: process.platform !== \"win32\",\n\t\t\tstdio: [\"ignore\", \"pipe\", \"pipe\"],\n\t\t});\n\t\tchild.stdout?.on(\"data\", (chunk: Buffer) => {\n\t\t\tstdoutBytes = appendChunk(stdoutChunks, chunk, stdoutBytes);\n\t\t});\n\t\tchild.stderr?.on(\"data\", (chunk: Buffer) => {\n\t\t\tstderrBytes = appendChunk(stderrChunks, chunk, stderrBytes);\n\t\t});\n\t\tconst terminal = await waitForChildProcessWithTermination(child, {\n\t\t\tsignal: terminationController.signal,\n\t\t\ttimeoutMs,\n\t\t\tkillGraceMs: SCRIPT_KILL_GRACE_MS,\n\t\t});\n\t\tconst stdout = Buffer.concat(stdoutChunks).toString(\"utf8\");\n\t\tlet stderr = Buffer.concat(stderrChunks).toString(\"utf8\");\n\t\tif (outputExceeded) {\n\t\t\tstderr = `${stderr}${stderr ? \"\\n\" : \"\"}Command output exceeded maxBuffer (${MAX_OUTPUT_BYTES} bytes)`;\n\t\t}\n\t\treturn {\n\t\t\texitCode: outputExceeded ? null : terminal.code,\n\t\t\tstdout,\n\t\t\tstderr,\n\t\t\tdurationMs: Date.now() - started,\n\t\t\ttimedOut: terminal.reason === \"timeout\",\n\t\t};\n\t} catch (error) {\n\t\treturn {\n\t\t\texitCode: null,\n\t\t\tstdout: Buffer.concat(stdoutChunks).toString(\"utf8\"),\n\t\t\tstderr: error instanceof Error ? error.message : String(error),\n\t\t\tdurationMs: Date.now() - started,\n\t\t\ttimedOut: false,\n\t\t};\n\t}\n};\n\nexport async function executeToolkitScript(args: {\n\tscript: ToolkitScript;\n\tscriptArgs: readonly string[];\n\tcwd: string;\n\ttimeoutMs?: number;\n\texecutor?: ScriptExecutor;\n}): Promise<ScriptExecution> {\n\tconst { command, argv } = buildScriptArgv(args.script, args.scriptArgs);\n\tconst executor = args.executor ?? spawnScriptExecutor;\n\treturn executor(command, argv, args.cwd, args.timeoutMs ?? 120_000);\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"bash.d.ts","sourceRoot":"","sources":["../../../src/core/tools/bash.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,KAAK,SAAS,EAAyB,MAAM,2BAA2B,CAAC;AAClF,OAAO,EAIN,KAAK,gBAAgB,EACrB,MAAM,gCAAgC,CAAC;AAGxC,OAAO,EAAE,KAAK,MAAM,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAY5C,OAAO,KAAK,EAAE,cAAc,EAA2B,MAAM,wBAAwB,CAAC;AAWtF,wFAAwF;AACxF,wBAAgB,2BAA2B,CAAC,EAAE,EAAE,MAAM,GAAG,SAAS,GAAG,IAAI,CAExE;AAED,QAAA,MAAM,UAAU;;;EAQd,CAAC;AAEH,MAAM,MAAM,aAAa,GAAG,MAAM,CAAC,OAAO,UAAU,CAAC,CAAC;AAEtD,MAAM,WAAW,eAAe;IAC/B,UAAU,CAAC,EAAE,gBAAgB,CAAC;IAC9B,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,OAAO,CAAC,EAAE;QACT,OAAO,EAAE,MAAM,CAAC;QAChB,YAAY,EAAE,MAAM,CAAC;KACrB,CAAC;CACF;AAED;;;GAGG;AACH,MAAM,WAAW,cAAc;IAC9B;;;;;;OAMG;IAC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AE,eAAe,CAAC,CAiQjF;AAED,wBAAgB,cAAc,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,eAAe,GAAG,SAAS,CAAC,OAAO,UAAU,CAAC,CAEnG","sourcesContent":["import { constants } from \"node:fs\";\nimport { access as fsAccess, readdir as fsReaddir, readFile as fsReadFile, stat as fsStat } from \"node:fs/promises\";\nimport { relative as relativePath, resolve as resolvePath } from \"node:path\";\nimport { type AgentTool, createSilenceWatchdog } from \"@caupulican/pi-agent-core\";\nimport {\n\tDEFAULT_MAX_BYTES,\n\tDEFAULT_MAX_LINES,\n\tformatSize,\n\ttype TruncationResult,\n} from \"@caupulican/pi-agent-core/node\";\nimport { Container, Text, truncateToWidth } from \"@caupulican/pi-tui\";\nimport { spawn } from \"child_process\";\nimport { type Static, Type } from \"typebox\";\nimport { keyHint } from \"../../modes/interactive/components/keybinding-hints.ts\";\nimport { truncateToVisualLines } from \"../../modes/interactive/components/visual-truncate.ts\";\nimport { theme } from \"../../modes/interactive/theme/theme.ts\";\nimport { waitForChildProcess } from \"../../utils/child-process.ts\";\nimport {\n\tgetShellConfig,\n\tgetShellEnv,\n\tkillProcessTree,\n\ttrackDetachedChildPid,\n\tuntrackDetachedChildPid,\n} from \"../../utils/shell.ts\";\nimport type { ToolDefinition, ToolRenderResultOptions } from \"../extensions/types.ts\";\nimport { withExclusiveMutationBarrier } from \"./file-mutation-queue.ts\";\nimport { classifyGitCommand, executeFilteredGit } from \"./git-filter.ts\";\nimport { OutputAccumulator } from \"./output-accumulator.ts\";\nimport { getTextOutput, invalidArgText, str } from \"./render-utils.ts\";\nimport { wrapToolDefinition } from \"./tool-definition-wrapper.ts\";\n\n/** Default silence bound for foreground commands without an explicit timeout (spec §2: ~10 min). */\nconst DEFAULT_COMMAND_SILENCE_MS = 600_000;\nlet commandSilenceMsOverride: number | undefined;\n\n/** Test hook: override the silence threshold. Pass undefined to restore the default. */\nexport function setCommandSilenceMsForTests(ms: number | undefined): void {\n\tcommandSilenceMsOverride = ms;\n}\n\nconst bashSchema = Type.Object({\n\tcommand: Type.String({ description: \"Bash command to execute\" }),\n\ttimeout: Type.Optional(\n\t\tType.Number({\n\t\t\tdescription:\n\t\t\t\t\"Timeout in seconds (optional). When set to a positive value, this wall-clock limit replaces the default silence watchdog. Zero or negative values are treated as unset, so the silence watchdog still applies.\",\n\t\t}),\n\t),\n});\n\nexport type BashToolInput = Static<typeof bashSchema>;\n\nexport interface BashToolDetails {\n\ttruncation?: TruncationResult;\n\tfullOutputPath?: string;\n\tfullOutputError?: string;\n\tpreview?: {\n\t\tcontent: string;\n\t\tskippedLines: number;\n\t};\n}\n\n/**\n * Pluggable operations for the bash tool.\n * Override these to delegate command execution to remote systems (for example SSH).\n */\nexport interface BashOperations {\n\t/**\n\t * Execute a command and stream output.\n\t * @param command The command to execute\n\t * @param cwd Working directory\n\t * @param options Execution options\n\t * @returns Promise resolving to exit code (null if killed)\n\t */\n\texec: (\n\t\tcommand: string,\n\t\tcwd: string,\n\t\toptions: {\n\t\t\tonData: (data: Buffer) => void;\n\t\t\tsignal?: AbortSignal;\n\t\t\ttimeout?: number;\n\t\t\tenv?: NodeJS.ProcessEnv;\n\t\t},\n\t) => Promise<{ exitCode: number | null }>;\n}\n\n/**\n * Create bash operations using pi's built-in local shell execution backend.\n *\n * This is useful for extensions that intercept user_bash and still want pi's\n * standard local shell behavior while wrapping or rewriting commands.\n */\nexport function createLocalBashOperations(options?: { shellPath?: string }): BashOperations {\n\treturn {\n\t\texec: async (command, cwd, { onData, signal, timeout, env }) => {\n\t\t\tconst { shell, args } = getShellConfig(options?.shellPath);\n\t\t\ttry {\n\t\t\t\tawait fsAccess(cwd, constants.F_OK);\n\t\t\t} catch {\n\t\t\t\tthrow new Error(`Working directory does not exist: ${cwd}\\nCannot execute bash commands.`);\n\t\t\t}\n\t\t\tif (signal?.aborted) {\n\t\t\t\tthrow new Error(\"aborted\");\n\t\t\t}\n\n\t\t\tconst child = spawn(shell, [...args, command], {\n\t\t\t\tcwd,\n\t\t\t\tdetached: process.platform !== \"win32\",\n\t\t\t\tenv: env ?? getShellEnv(),\n\t\t\t\tstdio: [\"ignore\", \"pipe\", \"pipe\"],\n\t\t\t\twindowsHide: true,\n\t\t\t});\n\t\t\tif (child.pid) trackDetachedChildPid(child.pid);\n\t\t\tlet timedOut = false;\n\t\t\tlet timeoutHandle: NodeJS.Timeout | undefined;\n\t\t\tconst onAbort = () => {\n\t\t\t\tif (child.pid) killProcessTree(child.pid);\n\t\t\t};\n\n\t\t\t// A command that keeps producing output must never be killed by this mechanism:\n\t\t\t// silence bounds mute-ness, not duration. It arms when the caller left `timeout`\n\t\t\t// unset or non-positive (treated as unset) — an explicit positive timeout means\n\t\t\t// the model took responsibility for the wall clock.\n\t\t\tlet silenceKilled = false;\n\t\t\tconst silenceMs = commandSilenceMsOverride ?? DEFAULT_COMMAND_SILENCE_MS;\n\t\t\tconst silenceWatchdog =\n\t\t\t\t(timeout === undefined || timeout <= 0) && silenceMs > 0\n\t\t\t\t\t? createSilenceWatchdog({\n\t\t\t\t\t\t\tsilenceMs,\n\t\t\t\t\t\t\tonSilence: () => {\n\t\t\t\t\t\t\t\tsilenceKilled = true;\n\t\t\t\t\t\t\t\tif (child.pid) killProcessTree(child.pid);\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t})\n\t\t\t\t\t: undefined;\n\t\t\tconst onChunk = (data: Buffer) => {\n\t\t\t\tsilenceWatchdog?.touch();\n\t\t\t\tonData(data);\n\t\t\t};\n\n\t\t\ttry {\n\t\t\t\t// Set timeout if provided.\n\t\t\t\tif (timeout !== undefined && timeout > 0) {\n\t\t\t\t\ttimeoutHandle = setTimeout(() => {\n\t\t\t\t\t\ttimedOut = true;\n\t\t\t\t\t\tif (child.pid) killProcessTree(child.pid);\n\t\t\t\t\t}, timeout * 1000);\n\t\t\t\t}\n\t\t\t\t// Stream stdout and stderr.\n\t\t\t\tchild.stdout?.on(\"data\", onChunk);\n\t\t\t\tchild.stderr?.on(\"data\", onChunk);\n\t\t\t\t// Handle abort signal by killing the entire process tree.\n\t\t\t\tif (signal) {\n\t\t\t\t\tif (signal.aborted) onAbort();\n\t\t\t\t\telse signal.addEventListener(\"abort\", onAbort, { once: true });\n\t\t\t\t}\n\t\t\t\t// Handle shell spawn errors and wait for the process to terminate without hanging\n\t\t\t\t// on inherited stdio handles held by detached descendants.\n\t\t\t\tconst exitCode = await waitForChildProcess(child);\n\t\t\t\tif (signal?.aborted) {\n\t\t\t\t\tthrow new Error(\"aborted\");\n\t\t\t\t}\n\t\t\t\tif (timedOut) {\n\t\t\t\t\tthrow new Error(`timeout:${timeout}`);\n\t\t\t\t}\n\t\t\t\tif (silenceKilled) {\n\t\t\t\t\tthrow new Error(`silence:${silenceMs / 1000}`);\n\t\t\t\t}\n\t\t\t\treturn { exitCode };\n\t\t\t} finally {\n\t\t\t\tsilenceWatchdog?.disarm();\n\t\t\t\tif (child.pid) untrackDetachedChildPid(child.pid);\n\t\t\t\tif (timeoutHandle) clearTimeout(timeoutHandle);\n\t\t\t\tif (signal) signal.removeEventListener(\"abort\", onAbort);\n\t\t\t}\n\t\t},\n\t};\n}\n\nexport interface BashSpawnContext {\n\tcommand: string;\n\tcwd: string;\n\tenv: NodeJS.ProcessEnv;\n}\n\nexport type BashSpawnHook = (context: BashSpawnContext) => BashSpawnContext;\n\nfunction resolveSpawnContext(command: string, cwd: string, spawnHook?: BashSpawnHook): BashSpawnContext {\n\tconst baseContext: BashSpawnContext = { command, cwd, env: { ...getShellEnv() } };\n\treturn spawnHook ? spawnHook(baseContext) : baseContext;\n}\n\nexport interface BashToolOptions {\n\t/** Custom operations for command execution. Default: local shell */\n\toperations?: BashOperations;\n\t/** Command prefix prepended to every command (for example shell setup commands) */\n\tcommandPrefix?: string;\n\t/** Optional explicit shell path from settings */\n\tshellPath?: string;\n\t/** Hook to adjust command, cwd, or env before execution */\n\tspawnHook?: BashSpawnHook;\n}\n\nconst BASH_PREVIEW_LINES = 5;\nconst BASH_PREVIEW_BYTES = 8 * 1024;\nconst BASH_UPDATE_THROTTLE_MS = 100;\n\ntype BashRenderState = {\n\tstartedAt: number | undefined;\n\tendedAt: number | undefined;\n\tinterval: NodeJS.Timeout | undefined;\n};\n\ntype BashResultRenderState = {\n\tcachedWidth: number | undefined;\n\tcachedLines: string[] | undefined;\n\tcachedSkipped: number | undefined;\n};\n\nclass BashResultRenderComponent extends Container {\n\tstate: BashResultRenderState = {\n\t\tcachedWidth: undefined,\n\t\tcachedLines: undefined,\n\t\tcachedSkipped: undefined,\n\t};\n}\n\nfunction formatDuration(ms: number): string {\n\treturn `${(ms / 1000).toFixed(1)}s`;\n}\n\nfunction formatBashCall(args: { command?: string; timeout?: number } | undefined): string {\n\tconst command = str(args?.command);\n\tconst timeout = args?.timeout as number | undefined;\n\tconst timeoutSuffix = timeout ? theme.fg(\"muted\", ` (timeout ${timeout}s)`) : \"\";\n\tconst commandDisplay = command === null ? invalidArgText(theme) : command ? command : theme.fg(\"toolOutput\", \"...\");\n\treturn theme.fg(\"toolTitle\", theme.bold(`$ ${commandDisplay}`)) + timeoutSuffix;\n}\n\nfunction rebuildBashResultRenderComponent(\n\tcomponent: BashResultRenderComponent,\n\tresult: {\n\t\tcontent: Array<{ type: string; text?: string; data?: string; mimeType?: string }>;\n\t\tdetails?: BashToolDetails;\n\t},\n\toptions: ToolRenderResultOptions,\n\tshowImages: boolean,\n\tstartedAt: number | undefined,\n\tendedAt: number | undefined,\n): void {\n\tconst state = component.state;\n\tcomponent.clear();\n\n\tconst renderPreview = !options.expanded ? result.details?.preview : undefined;\n\tlet output = (renderPreview ? renderPreview.content : getTextOutput(result as any, showImages)).trim();\n\tconst truncation = result.details?.truncation;\n\tconst fullOutputPath = result.details?.fullOutputPath;\n\tconst fullOutputError = result.details?.fullOutputError;\n\tif (!options.isPartial && truncation?.truncated && fullOutputPath && output.endsWith(\"]\")) {\n\t\tconst footerStart = output.lastIndexOf(\"\\n\\n[\");\n\t\tif (footerStart !== -1 && output.slice(footerStart).includes(fullOutputPath)) {\n\t\t\toutput = output.slice(0, footerStart).trimEnd();\n\t\t}\n\t}\n\n\tif (output) {\n\t\tif (options.expanded) {\n\t\t\tconst styledOutput = output\n\t\t\t\t.split(\"\\n\")\n\t\t\t\t.map((line) => theme.fg(\"toolOutput\", line))\n\t\t\t\t.join(\"\\n\");\n\t\t\tcomponent.addChild(new Text(`\\n${styledOutput}`, 0, 0));\n\t\t} else {\n\t\t\tcomponent.addChild({\n\t\t\t\trender: (width: number) => {\n\t\t\t\t\tif (state.cachedLines === undefined || state.cachedWidth !== width) {\n\t\t\t\t\t\tconst preview = truncateToVisualLines(output, BASH_PREVIEW_LINES, width);\n\t\t\t\t\t\tstate.cachedLines = preview.visualLines.map((line) => theme.fg(\"toolOutput\", line));\n\t\t\t\t\t\tstate.cachedSkipped = (result.details?.preview?.skippedLines ?? 0) + preview.skippedCount;\n\t\t\t\t\t\tstate.cachedWidth = width;\n\t\t\t\t\t}\n\t\t\t\t\tif (state.cachedSkipped && state.cachedSkipped > 0) {\n\t\t\t\t\t\tconst hint =\n\t\t\t\t\t\t\ttheme.fg(\"muted\", `... (${state.cachedSkipped} earlier lines,`) +\n\t\t\t\t\t\t\t` ${keyHint(\"app.tools.expand\", \"to expand\")})`;\n\t\t\t\t\t\treturn [\"\", truncateToWidth(hint, width, \"...\"), ...(state.cachedLines ?? [])];\n\t\t\t\t\t}\n\t\t\t\t\treturn [\"\", ...(state.cachedLines ?? [])];\n\t\t\t\t},\n\t\t\t\tinvalidate: () => {\n\t\t\t\t\tstate.cachedWidth = undefined;\n\t\t\t\t\tstate.cachedLines = undefined;\n\t\t\t\t\tstate.cachedSkipped = undefined;\n\t\t\t\t},\n\t\t\t});\n\t\t}\n\t}\n\n\tif (truncation?.truncated || fullOutputPath || fullOutputError) {\n\t\tconst warnings: string[] = [];\n\t\tif (fullOutputPath) {\n\t\t\twarnings.push(`Full output: ${fullOutputPath}`);\n\t\t} else if (fullOutputError) {\n\t\t\twarnings.push(`Full output unavailable: ${fullOutputError}`);\n\t\t}\n\t\tif (truncation?.truncated) {\n\t\t\tif (truncation.truncatedBy === \"lines\") {\n\t\t\t\twarnings.push(`Truncated: showing ${truncation.outputLines} of ${truncation.totalLines} lines`);\n\t\t\t} else {\n\t\t\t\twarnings.push(\n\t\t\t\t\t`Truncated: ${truncation.outputLines} lines shown (${formatSize(truncation.maxBytes ?? DEFAULT_MAX_BYTES)} limit)`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tcomponent.addChild(new Text(`\\n${theme.fg(\"warning\", `[${warnings.join(\". \")}]`)}`, 0, 0));\n\t}\n\n\tif (startedAt !== undefined) {\n\t\tconst label = options.isPartial ? \"Elapsed\" : \"Took\";\n\t\tconst endTime = endedAt ?? Date.now();\n\t\tcomponent.addChild(new Text(`\\n${theme.fg(\"muted\", `${label} ${formatDuration(endTime - startedAt)}`)}`, 0, 0));\n\t}\n}\n\nasync function tryOptimizeCommand(\n\tcommand: string,\n\tcwd: string,\n): Promise<{ optimized: boolean; output?: string; exitCode?: number }> {\n\tif (process.env.PI_TOOL_OPTIMIZER_DISABLED === \"1\") {\n\t\treturn { optimized: false };\n\t}\n\n\tconst trimmed = command.trim();\n\tif (!trimmed) {\n\t\treturn { optimized: false };\n\t}\n\n\t// Reject if there are shell operators or pipes/redirects\n\tconst shellOperators = [\"|\", \">\", \"<\", \"&\", \";\", \"\\n\", \"\\r\", \"$\", \"`\", \"(\", \")\", \"*\", \"?\", \"[\", \"]\"];\n\tif (shellOperators.some((op) => trimmed.includes(op))) {\n\t\treturn { optimized: false };\n\t}\n\n\t// Simple tokenizer split by whitespace\n\tconst args = trimmed.split(/\\s+/);\n\tif (args.length === 0) {\n\t\treturn { optimized: false };\n\t}\n\n\tconst cmd = args[0];\n\tconst unquote = (s: string) => {\n\t\tif ((s.startsWith('\"') && s.endsWith('\"')) || (s.startsWith(\"'\") && s.endsWith(\"'\"))) {\n\t\t\treturn s.slice(1, -1);\n\t\t}\n\t\treturn s;\n\t};\n\n\tconst resolveToCwd = (p: string, base: string) => {\n\t\tconst clean = unquote(p);\n\t\tif (clean.startsWith(\"/\")) return clean;\n\t\treturn resolvePath(base, clean);\n\t};\n\n\ttry {\n\t\tif (cmd === \"cat\") {\n\t\t\tif (args.length === 2 && !args[1].startsWith(\"-\")) {\n\t\t\t\tconst filePath = resolveToCwd(args[1], cwd);\n\t\t\t\tconst content = await fsReadFile(filePath, \"utf-8\");\n\t\t\t\treturn { optimized: true, output: content, exitCode: 0 };\n\t\t\t}\n\t\t} else if (cmd === \"head\") {\n\t\t\tif (args.length === 2 && !args[1].startsWith(\"-\")) {\n\t\t\t\tconst filePath = resolveToCwd(args[1], cwd);\n\t\t\t\tconst content = await fsReadFile(filePath, \"utf-8\");\n\t\t\t\tconst lines = content.split(\"\\n\").slice(0, 10).join(\"\\n\");\n\t\t\t\treturn { optimized: true, output: lines, exitCode: 0 };\n\t\t\t} else if (args.length === 4 && args[1] === \"-n\" && !args[3].startsWith(\"-\")) {\n\t\t\t\tconst count = parseInt(args[2], 10);\n\t\t\t\tif (!Number.isNaN(count) && count >= 0) {\n\t\t\t\t\tconst filePath = resolveToCwd(args[3], cwd);\n\t\t\t\t\tconst content = await fsReadFile(filePath, \"utf-8\");\n\t\t\t\t\tconst lines = content.split(\"\\n\").slice(0, count).join(\"\\n\");\n\t\t\t\t\treturn { optimized: true, output: lines, exitCode: 0 };\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (cmd === \"tail\") {\n\t\t\tif (args.length === 2 && !args[1].startsWith(\"-\")) {\n\t\t\t\tconst filePath = resolveToCwd(args[1], cwd);\n\t\t\t\tconst content = await fsReadFile(filePath, \"utf-8\");\n\t\t\t\tconst allLines = content.split(\"\\n\");\n\t\t\t\tconst lines = allLines.slice(Math.max(0, allLines.length - 10)).join(\"\\n\");\n\t\t\t\treturn { optimized: true, output: lines, exitCode: 0 };\n\t\t\t} else if (args.length === 4 && args[1] === \"-n\" && !args[3].startsWith(\"-\")) {\n\t\t\t\tconst count = parseInt(args[2], 10);\n\t\t\t\tif (!Number.isNaN(count) && count >= 0) {\n\t\t\t\t\tconst filePath = resolveToCwd(args[3], cwd);\n\t\t\t\t\tconst content = await fsReadFile(filePath, \"utf-8\");\n\t\t\t\t\tconst allLines = content.split(\"\\n\");\n\t\t\t\t\tconst lines = allLines.slice(Math.max(0, allLines.length - count)).join(\"\\n\");\n\t\t\t\t\treturn { optimized: true, output: lines, exitCode: 0 };\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (cmd === \"ls\") {\n\t\t\tif (args.length === 1 || (args.length === 2 && !args[1].startsWith(\"-\"))) {\n\t\t\t\tconst targetDir = args.length === 2 ? resolveToCwd(args[1], cwd) : cwd;\n\t\t\t\tconst entries = await fsReaddir(targetDir);\n\t\t\t\tentries.sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase()));\n\t\t\t\tconst results: string[] = [];\n\t\t\t\tfor (const entry of entries) {\n\t\t\t\t\tlet suffix = \"\";\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst entryStat = await fsStat(resolvePath(targetDir, entry));\n\t\t\t\t\t\tif (entryStat.isDirectory()) suffix = \"/\";\n\t\t\t\t\t} catch {}\n\t\t\t\t\tresults.push(entry + suffix);\n\t\t\t\t}\n\t\t\t\treturn { optimized: true, output: results.join(\"\\n\"), exitCode: 0 };\n\t\t\t}\n\t\t} else if (cmd === \"grep\" || cmd === \"rg\") {\n\t\t\tif (args.length === 3 && !args[1].startsWith(\"-\") && !args[2].startsWith(\"-\")) {\n\t\t\t\tconst patternStr = unquote(args[1]);\n\t\t\t\tif (/[\\\\^$.|?*+()[\\]{}]/.test(patternStr)) return { optimized: false };\n\t\t\t\tconst filePath = resolveToCwd(args[2], cwd);\n\t\t\t\tconst content = await fsReadFile(filePath, \"utf-8\");\n\t\t\t\tconst lines = content.split(\"\\n\");\n\t\t\t\tconst matches: string[] = [];\n\t\t\t\tfor (let i = 0; i < lines.length; i++) {\n\t\t\t\t\tif (lines[i].includes(patternStr)) {\n\t\t\t\t\t\tmatches.push(lines[i]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn { optimized: true, output: matches.join(\"\\n\"), exitCode: matches.length > 0 ? 0 : 1 };\n\t\t\t}\n\t\t} else if (cmd === \"find\") {\n\t\t\tif (args.length === 1 || (args.length === 2 && !args[1].startsWith(\"-\"))) {\n\t\t\t\tconst searchPath = args.length === 2 ? resolveToCwd(args[1], cwd) : cwd;\n\t\t\t\tconst walk = async (dir: string): Promise<string[]> => {\n\t\t\t\t\tlet results: string[] = [];\n\t\t\t\t\tconst entries = await fsReaddir(dir, { withFileTypes: true });\n\t\t\t\t\tfor (const entry of entries) {\n\t\t\t\t\t\tconst full = resolvePath(dir, entry.name);\n\t\t\t\t\t\tresults.push(full);\n\t\t\t\t\t\tif (entry.isDirectory()) {\n\t\t\t\t\t\t\tresults = results.concat(await walk(full));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn results;\n\t\t\t\t};\n\t\t\t\tconst all = (await walk(searchPath)).map((p) => relativePath(searchPath, p).replace(/\\\\/g, \"/\"));\n\t\t\t\treturn { optimized: true, output: all.join(\"\\n\"), exitCode: 0 };\n\t\t\t}\n\t\t}\n\t} catch {\n\t\treturn { optimized: false };\n\t}\n\n\treturn { optimized: false };\n}\n\nexport function createBashToolDefinition(\n\tcwd: string,\n\toptions?: BashToolOptions,\n): ToolDefinition<typeof bashSchema, BashToolDetails | undefined, BashRenderState> {\n\tconst ops = options?.operations ?? createLocalBashOperations({ shellPath: options?.shellPath });\n\tconst commandPrefix = options?.commandPrefix;\n\tconst spawnHook = options?.spawnHook;\n\tconst canOptimizeCommand = !options?.operations && !options?.shellPath && !commandPrefix && !spawnHook;\n\tconst canFilterCommand = canOptimizeCommand;\n\treturn {\n\t\tname: \"bash\",\n\t\tlabel: \"bash\",\n\t\tdescription: `Execute a bash command in the current working directory. Returns stdout and stderr. Output is truncated to last ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). If truncated, full output is saved to a temp file. Optionally provide a timeout in seconds. Without an explicit timeout, the command is killed after ${DEFAULT_COMMAND_SILENCE_MS / 1000}s of continuous silence (no stdout/stderr output) rather than being bounded by total runtime; commands that keep producing output are never killed by this. Provide an explicit timeout to replace the silence watchdog with a wall-clock limit, or background long, quiet work with '&'.`,\n\t\tpromptSnippet: \"Execute bash commands (ls, grep, find, etc.)\",\n\t\tparameters: bashSchema,\n\t\tasync execute(\n\t\t\t_toolCallId,\n\t\t\t{ command, timeout }: { command: string; timeout?: number },\n\t\t\tsignal?: AbortSignal,\n\t\t\tonUpdate?,\n\t\t\t_ctx?,\n\t\t) {\n\t\t\tconst resolvedCommand = commandPrefix ? `${commandPrefix}\\n${command}` : command;\n\t\t\tconst spawnContext = resolveSpawnContext(resolvedCommand, cwd, spawnHook);\n\t\t\tconst output = new OutputAccumulator({ tempFilePrefix: \"pi-bash\" });\n\t\t\tlet updateTimer: NodeJS.Timeout | undefined;\n\t\t\tlet updateDirty = false;\n\t\t\tlet lastUpdateAt = 0;\n\n\t\t\tconst emitOutputUpdate = () => {\n\t\t\t\tif (!onUpdate || !updateDirty) return;\n\t\t\t\tupdateDirty = false;\n\t\t\t\tlastUpdateAt = Date.now();\n\t\t\t\tconst snapshot = output.previewSnapshot(BASH_PREVIEW_LINES, BASH_PREVIEW_BYTES, {\n\t\t\t\t\tpersistIfFullTruncated: true,\n\t\t\t\t});\n\t\t\t\tconst preview = {\n\t\t\t\t\tcontent: snapshot.content,\n\t\t\t\t\tskippedLines: Math.max(0, snapshot.truncation.totalLines - snapshot.truncation.outputLines),\n\t\t\t\t};\n\t\t\t\tonUpdate({\n\t\t\t\t\tcontent: [{ type: \"text\", text: preview.content || \"\" }],\n\t\t\t\t\tdetails: {\n\t\t\t\t\t\ttruncation: snapshot.truncation.truncated ? snapshot.truncation : undefined,\n\t\t\t\t\t\tfullOutputPath: snapshot.fullOutputPath,\n\t\t\t\t\t\tfullOutputError: snapshot.fullOutputError,\n\t\t\t\t\t\tpreview,\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t};\n\n\t\t\tconst clearUpdateTimer = () => {\n\t\t\t\tif (updateTimer) {\n\t\t\t\t\tclearTimeout(updateTimer);\n\t\t\t\t\tupdateTimer = undefined;\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tconst scheduleOutputUpdate = () => {\n\t\t\t\tif (!onUpdate) return;\n\t\t\t\tupdateDirty = true;\n\t\t\t\tconst delay = BASH_UPDATE_THROTTLE_MS - (Date.now() - lastUpdateAt);\n\t\t\t\tif (delay <= 0) {\n\t\t\t\t\tclearUpdateTimer();\n\t\t\t\t\temitOutputUpdate();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tupdateTimer ??= setTimeout(() => {\n\t\t\t\t\tupdateTimer = undefined;\n\t\t\t\t\temitOutputUpdate();\n\t\t\t\t}, delay);\n\t\t\t};\n\n\t\t\tif (onUpdate) {\n\t\t\t\tonUpdate({ content: [], details: undefined });\n\t\t\t}\n\n\t\t\tconst handleData = (data: Buffer) => {\n\t\t\t\toutput.append(data);\n\t\t\t\tscheduleOutputUpdate();\n\t\t\t};\n\n\t\t\tconst finishOutput = async () => {\n\t\t\t\toutput.finish();\n\t\t\t\tclearUpdateTimer();\n\t\t\t\temitOutputUpdate();\n\t\t\t\treturn output.snapshot({ persistIfTruncated: true });\n\t\t\t};\n\n\t\t\tconst formatOutput = (snapshot: Awaited<ReturnType<typeof finishOutput>>, emptyText = \"(no output)\") => {\n\t\t\t\tconst truncation = snapshot.truncation;\n\t\t\t\tlet text = snapshot.content || emptyText;\n\t\t\t\tlet details: BashToolDetails | undefined;\n\t\t\t\tconst preview = output.preview(BASH_PREVIEW_LINES, BASH_PREVIEW_BYTES);\n\t\t\t\tconst fullOutputNotice = snapshot.fullOutputPath\n\t\t\t\t\t? `Full output: ${snapshot.fullOutputPath}`\n\t\t\t\t\t: snapshot.fullOutputError\n\t\t\t\t\t\t? `Full output unavailable: ${snapshot.fullOutputError}`\n\t\t\t\t\t\t: \"Full output unavailable\";\n\t\t\t\tif (truncation.truncated || preview.skippedLines > 0) {\n\t\t\t\t\tdetails = { preview };\n\t\t\t\t}\n\t\t\t\tif (snapshot.fullOutputPath || snapshot.fullOutputError) {\n\t\t\t\t\tdetails = {\n\t\t\t\t\t\t...(details ?? {}),\n\t\t\t\t\t\tfullOutputPath: snapshot.fullOutputPath,\n\t\t\t\t\t\tfullOutputError: snapshot.fullOutputError,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tif (truncation.truncated) {\n\t\t\t\t\tdetails = {\n\t\t\t\t\t\t...(details ?? {}),\n\t\t\t\t\t\ttruncation,\n\t\t\t\t\t\tfullOutputPath: snapshot.fullOutputPath,\n\t\t\t\t\t\tfullOutputError: snapshot.fullOutputError,\n\t\t\t\t\t};\n\t\t\t\t\tconst startLine = truncation.totalLines - truncation.outputLines + 1;\n\t\t\t\t\tconst endLine = truncation.totalLines;\n\t\t\t\t\tif (truncation.lastLinePartial) {\n\t\t\t\t\t\tconst lastLineSize = formatSize(output.getLastLineBytes());\n\t\t\t\t\t\ttext += `\\n\\n[Showing last ${formatSize(truncation.outputBytes)} of line ${endLine} (line is ${lastLineSize}). ${fullOutputNotice}]`;\n\t\t\t\t\t} else if (truncation.truncatedBy === \"lines\") {\n\t\t\t\t\t\ttext += `\\n\\n[Showing lines ${startLine}-${endLine} of ${truncation.totalLines}. ${fullOutputNotice}]`;\n\t\t\t\t\t} else {\n\t\t\t\t\t\ttext += `\\n\\n[Showing lines ${startLine}-${endLine} of ${truncation.totalLines} (${formatSize(DEFAULT_MAX_BYTES)} limit). ${fullOutputNotice}]`;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn { text, details };\n\t\t\t};\n\n\t\t\tconst appendStatus = (text: string, status: string) => `${text ? `${text}\\n\\n` : \"\"}${status}`;\n\n\t\t\ttry {\n\t\t\t\tif (canFilterCommand) {\n\t\t\t\t\tconst classification = classifyGitCommand(command, spawnContext.env);\n\t\t\t\t\tif (classification.eligible && classification.subcommand) {\n\t\t\t\t\t\tconst res = await executeFilteredGit(\n\t\t\t\t\t\t\tcwd,\n\t\t\t\t\t\t\tclassification.subcommand,\n\t\t\t\t\t\t\tclassification.globalOptions || [],\n\t\t\t\t\t\t\tclassification.subcommandArgs || [],\n\t\t\t\t\t\t\t{ signal, timeout },\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (res.exitCode !== -100) {\n\t\t\t\t\t\t\toutput.append(res.rawBytes ?? Buffer.from(res.rawOut, \"utf-8\"));\n\t\t\t\t\t\t\tconst snapshot = await finishOutput();\n\t\t\t\t\t\t\tif (res.exitCode !== 0) {\n\t\t\t\t\t\t\t\tconst { text: rawOutputText } = formatOutput(snapshot);\n\t\t\t\t\t\t\t\tthrow new Error(appendStatus(rawOutputText, `Command exited with code ${res.exitCode}`));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tconst details = snapshot.truncation.truncated\n\t\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\t\ttruncation: snapshot.truncation,\n\t\t\t\t\t\t\t\t\t\tfullOutputPath: snapshot.fullOutputPath,\n\t\t\t\t\t\t\t\t\t\tfullOutputError: snapshot.fullOutputError,\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t: snapshot.fullOutputPath || snapshot.fullOutputError\n\t\t\t\t\t\t\t\t\t? { fullOutputPath: snapshot.fullOutputPath, fullOutputError: snapshot.fullOutputError }\n\t\t\t\t\t\t\t\t\t: undefined;\n\t\t\t\t\t\t\treturn { content: [{ type: \"text\", text: res.output }], details };\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (canOptimizeCommand) {\n\t\t\t\t\tconst optResult = await tryOptimizeCommand(command, cwd);\n\t\t\t\t\tif (optResult.optimized) {\n\t\t\t\t\t\toutput.append(Buffer.from(optResult.output ?? \"\", \"utf-8\"));\n\t\t\t\t\t\tconst snapshot = await finishOutput();\n\t\t\t\t\t\tconst { text: outputText, details } = formatOutput(snapshot);\n\t\t\t\t\t\tif (optResult.exitCode !== 0 && optResult.exitCode !== undefined) {\n\t\t\t\t\t\t\tthrow new Error(appendStatus(outputText, `Command exited with code ${optResult.exitCode}`));\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn { content: [{ type: \"text\", text: outputText }], details };\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tlet exitCode: number | null;\n\t\t\t\ttry {\n\t\t\t\t\t// Bash cannot statically declare which files a command mutates, so the\n\t\t\t\t\t// actual shell execution takes the coarse exclusive barrier: it waits for\n\t\t\t\t\t// in-flight edit/write mutations to drain and blocks new ones meanwhile.\n\t\t\t\t\tconst result = await withExclusiveMutationBarrier(() =>\n\t\t\t\t\t\tops.exec(spawnContext.command, spawnContext.cwd, {\n\t\t\t\t\t\t\tonData: handleData,\n\t\t\t\t\t\t\tsignal,\n\t\t\t\t\t\t\ttimeout,\n\t\t\t\t\t\t\tenv: spawnContext.env,\n\t\t\t\t\t\t}),\n\t\t\t\t\t);\n\t\t\t\t\texitCode = result.exitCode;\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst snapshot = await finishOutput();\n\t\t\t\t\tconst { text } = formatOutput(snapshot, \"\");\n\t\t\t\t\tif (err instanceof Error && err.message === \"aborted\") {\n\t\t\t\t\t\tthrow new Error(appendStatus(text, \"Command aborted\"));\n\t\t\t\t\t}\n\t\t\t\t\tif (err instanceof Error && err.message.startsWith(\"timeout:\")) {\n\t\t\t\t\t\tconst timeoutSecs = err.message.split(\":\")[1];\n\t\t\t\t\t\tthrow new Error(appendStatus(text, `Command timed out after ${timeoutSecs} seconds`));\n\t\t\t\t\t}\n\t\t\t\t\tif (err instanceof Error && err.message.startsWith(\"silence:\")) {\n\t\t\t\t\t\tconst secs = err.message.split(\":\")[1];\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\tappendStatus(\n\t\t\t\t\t\t\t\ttext,\n\t\t\t\t\t\t\t\t`Command killed after ${secs}s of silence (no output). If the command is legitimately quiet for long stretches, re-run it with an explicit timeout, or run it in the background with '&'.`,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tthrow err;\n\t\t\t\t}\n\n\t\t\t\tconst snapshot = await finishOutput();\n\t\t\t\tconst { text: outputText, details } = formatOutput(snapshot);\n\t\t\t\tif (exitCode !== 0 && exitCode !== null) {\n\t\t\t\t\tthrow new Error(appendStatus(outputText, `Command exited with code ${exitCode}`));\n\t\t\t\t}\n\t\t\t\treturn { content: [{ type: \"text\", text: outputText }], details };\n\t\t\t} finally {\n\t\t\t\tclearUpdateTimer();\n\t\t\t\tawait output.closeTempFile();\n\t\t\t}\n\t\t},\n\t\trenderCall(args, _theme, context) {\n\t\t\tconst state = context.state;\n\t\t\tif (context.executionStarted && state.startedAt === undefined) {\n\t\t\t\tstate.startedAt = Date.now();\n\t\t\t\tstate.endedAt = undefined;\n\t\t\t}\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(formatBashCall(args));\n\t\t\treturn text;\n\t\t},\n\t\trenderResult(result, options, _theme, context) {\n\t\t\tconst state = context.state;\n\t\t\tif (state.startedAt !== undefined && options.isPartial && !state.interval) {\n\t\t\t\tstate.interval = setInterval(() => context.invalidate(), 1000);\n\t\t\t}\n\t\t\tif (!options.isPartial || context.isError) {\n\t\t\t\tstate.endedAt ??= Date.now();\n\t\t\t\tif (state.interval) {\n\t\t\t\t\tclearInterval(state.interval);\n\t\t\t\t\tstate.interval = undefined;\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst component =\n\t\t\t\t(context.lastComponent as BashResultRenderComponent | undefined) ?? new BashResultRenderComponent();\n\t\t\trebuildBashResultRenderComponent(\n\t\t\t\tcomponent,\n\t\t\t\tresult as any,\n\t\t\t\toptions,\n\t\t\t\tcontext.showImages,\n\t\t\t\tstate.startedAt,\n\t\t\t\tstate.endedAt,\n\t\t\t);\n\t\t\tcomponent.invalidate();\n\t\t\treturn component;\n\t\t},\n\t};\n}\n\nexport function createBashTool(cwd: string, options?: BashToolOptions): AgentTool<typeof bashSchema> {\n\treturn wrapToolDefinition(createBashToolDefinition(cwd, options));\n}\n"]}
1
+ {"version":3,"file":"bash.d.ts","sourceRoot":"","sources":["../../../src/core/tools/bash.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,KAAK,SAAS,EAAyB,MAAM,2BAA2B,CAAC;AAClF,OAAO,EAIN,KAAK,gBAAgB,EACrB,MAAM,gCAAgC,CAAC;AAGxC,OAAO,EAAE,KAAK,MAAM,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAM5C,OAAO,KAAK,EAAE,cAAc,EAA2B,MAAM,wBAAwB,CAAC;AAWtF,wFAAwF;AACxF,wBAAgB,2BAA2B,CAAC,EAAE,EAAE,MAAM,GAAG,SAAS,GAAG,IAAI,CAExE;AAED,QAAA,MAAM,UAAU;;;EAQd,CAAC;AAEH,MAAM,MAAM,aAAa,GAAG,MAAM,CAAC,OAAO,UAAU,CAAC,CAAC;AAEtD,MAAM,WAAW,eAAe;IAC/B,UAAU,CAAC,EAAE,gBAAgB,CAAC;IAC9B,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,OAAO,CAAC,EAAE;QACT,OAAO,EAAE,MAAM,CAAC;QAChB,YAAY,EAAE,MAAM,CAAC;KACrB,CAAC;CACF;AAED;;;GAGG;AACH,MAAM,WAAW,cAAc;IAC9B;;;;;;OAMG;IACH,IAAI,EAAE,CACL,OAAO,EAAE,MAAM,EACf,GAAG,EAAE,MAAM,EACX,OAAO,EAAE;QACR,MAAM,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAAC;QAC/B,MAAM,CAAC,EAAE,WAAW,CAAC;QACrB,OAAO,CAAC,EAAE,MAAM,CAAC;QACjB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sStat } from \"node:fs/promises\";\nimport { relative as relativePath, resolve as resolvePath } from \"node:path\";\nimport { type AgentTool, createSilenceWatchdog } from \"@caupulican/pi-agent-core\";\nimport {\n\tDEFAULT_MAX_BYTES,\n\tDEFAULT_MAX_LINES,\n\tformatSize,\n\ttype TruncationResult,\n} from \"@caupulican/pi-agent-core/node\";\nimport { Container, Text, truncateToWidth } from \"@caupulican/pi-tui\";\nimport { spawn } from \"child_process\";\nimport { type Static, Type } from \"typebox\";\nimport { keyHint } from \"../../modes/interactive/components/keybinding-hints.ts\";\nimport { truncateToVisualLines } from \"../../modes/interactive/components/visual-truncate.ts\";\nimport { theme } from \"../../modes/interactive/theme/theme.ts\";\nimport { waitForChildProcessWithTermination } from \"../../utils/child-process.ts\";\nimport { getShellConfig, getShellEnv, trackDetachedChildPid, untrackDetachedChildPid } from \"../../utils/shell.ts\";\nimport type { ToolDefinition, ToolRenderResultOptions } from \"../extensions/types.ts\";\nimport { withExclusiveMutationBarrier } from \"./file-mutation-queue.ts\";\nimport { classifyGitCommand, executeFilteredGit } from \"./git-filter.ts\";\nimport { OutputAccumulator } from \"./output-accumulator.ts\";\nimport { getTextOutput, invalidArgText, str } from \"./render-utils.ts\";\nimport { wrapToolDefinition } from \"./tool-definition-wrapper.ts\";\n\n/** Default silence bound for foreground commands without an explicit timeout (spec §2: ~10 min). */\nconst DEFAULT_COMMAND_SILENCE_MS = 600_000;\nlet commandSilenceMsOverride: number | undefined;\n\n/** Test hook: override the silence threshold. Pass undefined to restore the default. */\nexport function setCommandSilenceMsForTests(ms: number | undefined): void {\n\tcommandSilenceMsOverride = ms;\n}\n\nconst bashSchema = Type.Object({\n\tcommand: Type.String({ description: \"Bash command to execute\" }),\n\ttimeout: Type.Optional(\n\t\tType.Number({\n\t\t\tdescription:\n\t\t\t\t\"Timeout in seconds (optional). When set to a positive value, this wall-clock limit replaces the default silence watchdog. Zero or negative values are treated as unset, so the silence watchdog still applies.\",\n\t\t}),\n\t),\n});\n\nexport type BashToolInput = Static<typeof bashSchema>;\n\nexport interface BashToolDetails {\n\ttruncation?: TruncationResult;\n\tfullOutputPath?: string;\n\tfullOutputError?: string;\n\tpreview?: {\n\t\tcontent: string;\n\t\tskippedLines: number;\n\t};\n}\n\n/**\n * Pluggable operations for the bash tool.\n * Override these to delegate command execution to remote systems (for example SSH).\n */\nexport interface BashOperations {\n\t/**\n\t * Execute a command and stream output.\n\t * @param command The command to execute\n\t * @param cwd Working directory\n\t * @param options Execution options\n\t * @returns Promise resolving to exit code (null if killed)\n\t */\n\texec: (\n\t\tcommand: string,\n\t\tcwd: string,\n\t\toptions: {\n\t\t\tonData: (data: Buffer) => void;\n\t\t\tsignal?: AbortSignal;\n\t\t\ttimeout?: number;\n\t\t\tenv?: NodeJS.ProcessEnv;\n\t\t},\n\t) => Promise<{ exitCode: number | null }>;\n}\n\n/**\n * Create bash operations using pi's built-in local shell execution backend.\n *\n * This is useful for extensions that intercept user_bash and still want pi's\n * standard local shell behavior while wrapping or rewriting commands.\n */\nexport function createLocalBashOperations(options?: { shellPath?: string }): BashOperations {\n\treturn {\n\t\texec: async (command, cwd, { onData, signal, timeout, env }) => {\n\t\t\tconst { shell, args } = getShellConfig(options?.shellPath);\n\t\t\ttry {\n\t\t\t\tawait fsAccess(cwd, constants.F_OK);\n\t\t\t} catch {\n\t\t\t\tthrow new Error(`Working directory does not exist: ${cwd}\\nCannot execute bash commands.`);\n\t\t\t}\n\t\t\tif (signal?.aborted) {\n\t\t\t\tthrow new Error(\"aborted\");\n\t\t\t}\n\n\t\t\tconst child = spawn(shell, [...args, command], {\n\t\t\t\tcwd,\n\t\t\t\tdetached: process.platform !== \"win32\",\n\t\t\t\tenv: env ?? getShellEnv(),\n\t\t\t\tstdio: [\"ignore\", \"pipe\", \"pipe\"],\n\t\t\t\twindowsHide: true,\n\t\t\t});\n\t\t\tif (child.pid) trackDetachedChildPid(child.pid);\n\t\t\tconst terminationController = new AbortController();\n\t\t\tconst onAbort = () => terminationController.abort();\n\n\t\t\t// A command that keeps producing output must never be killed by this mechanism:\n\t\t\t// silence bounds mute-ness, not duration. It arms when the caller left `timeout`\n\t\t\t// unset or non-positive (treated as unset) — an explicit positive timeout means\n\t\t\t// the model took responsibility for the wall clock.\n\t\t\tlet silenceKilled = false;\n\t\t\tconst silenceMs = commandSilenceMsOverride ?? DEFAULT_COMMAND_SILENCE_MS;\n\t\t\tconst silenceWatchdog =\n\t\t\t\t(timeout === undefined || timeout <= 0) && silenceMs > 0\n\t\t\t\t\t? createSilenceWatchdog({\n\t\t\t\t\t\t\tsilenceMs,\n\t\t\t\t\t\t\tonSilence: () => {\n\t\t\t\t\t\t\t\tsilenceKilled = true;\n\t\t\t\t\t\t\t\tterminationController.abort();\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t})\n\t\t\t\t\t: undefined;\n\t\t\tconst onChunk = (data: Buffer) => {\n\t\t\t\tsilenceWatchdog?.touch();\n\t\t\t\tonData(data);\n\t\t\t};\n\n\t\t\ttry {\n\t\t\t\t// Stream stdout and stderr.\n\t\t\t\tchild.stdout?.on(\"data\", onChunk);\n\t\t\t\tchild.stderr?.on(\"data\", onChunk);\n\t\t\t\t// Forward caller cancellation into the shared bounded termination path.\n\t\t\t\tif (signal) {\n\t\t\t\t\tif (signal.aborted) onAbort();\n\t\t\t\t\telse signal.addEventListener(\"abort\", onAbort, { once: true });\n\t\t\t\t}\n\t\t\t\tconst terminal = await waitForChildProcessWithTermination(child, {\n\t\t\t\t\tsignal: terminationController.signal,\n\t\t\t\t\ttimeoutMs: timeout !== undefined && timeout > 0 ? timeout * 1000 : undefined,\n\t\t\t\t\tkillGraceMs: 2_000,\n\t\t\t\t});\n\t\t\t\tif (signal?.aborted) {\n\t\t\t\t\tthrow new Error(\"aborted\");\n\t\t\t\t}\n\t\t\t\tif (terminal.reason === \"timeout\") {\n\t\t\t\t\tthrow new Error(`timeout:${timeout}`);\n\t\t\t\t}\n\t\t\t\tif (silenceKilled) {\n\t\t\t\t\tthrow new Error(`silence:${silenceMs / 1000}`);\n\t\t\t\t}\n\t\t\t\treturn { exitCode: terminal.code };\n\t\t\t} finally {\n\t\t\t\tsilenceWatchdog?.disarm();\n\t\t\t\tif (child.pid) untrackDetachedChildPid(child.pid);\n\t\t\t\tif (signal) signal.removeEventListener(\"abort\", onAbort);\n\t\t\t}\n\t\t},\n\t};\n}\n\nexport interface BashSpawnContext {\n\tcommand: string;\n\tcwd: string;\n\tenv: NodeJS.ProcessEnv;\n}\n\nexport type BashSpawnHook = (context: BashSpawnContext) => BashSpawnContext;\n\nfunction resolveSpawnContext(command: string, cwd: string, spawnHook?: BashSpawnHook): BashSpawnContext {\n\tconst baseContext: BashSpawnContext = { command, cwd, env: { ...getShellEnv() } };\n\treturn spawnHook ? spawnHook(baseContext) : baseContext;\n}\n\nexport interface BashToolOptions {\n\t/** Custom operations for command execution. Default: local shell */\n\toperations?: BashOperations;\n\t/** Command prefix prepended to every command (for example shell setup commands) */\n\tcommandPrefix?: string;\n\t/** Optional explicit shell path from settings */\n\tshellPath?: string;\n\t/** Hook to adjust command, cwd, or env before execution */\n\tspawnHook?: BashSpawnHook;\n}\n\nconst BASH_PREVIEW_LINES = 5;\nconst BASH_PREVIEW_BYTES = 8 * 1024;\nconst BASH_UPDATE_THROTTLE_MS = 100;\n\ntype BashRenderState = {\n\tstartedAt: number | undefined;\n\tendedAt: number | undefined;\n\tinterval: NodeJS.Timeout | undefined;\n};\n\ntype BashResultRenderState = {\n\tcachedWidth: number | undefined;\n\tcachedLines: string[] | undefined;\n\tcachedSkipped: number | undefined;\n};\n\nclass BashResultRenderComponent extends Container {\n\tstate: BashResultRenderState = {\n\t\tcachedWidth: undefined,\n\t\tcachedLines: undefined,\n\t\tcachedSkipped: undefined,\n\t};\n}\n\nfunction formatDuration(ms: number): string {\n\treturn `${(ms / 1000).toFixed(1)}s`;\n}\n\nfunction formatBashCall(args: { command?: string; timeout?: number } | undefined): string {\n\tconst command = str(args?.command);\n\tconst timeout = args?.timeout as number | undefined;\n\tconst timeoutSuffix = timeout ? theme.fg(\"muted\", ` (timeout ${timeout}s)`) : \"\";\n\tconst commandDisplay = command === null ? invalidArgText(theme) : command ? command : theme.fg(\"toolOutput\", \"...\");\n\treturn theme.fg(\"toolTitle\", theme.bold(`$ ${commandDisplay}`)) + timeoutSuffix;\n}\n\nfunction rebuildBashResultRenderComponent(\n\tcomponent: BashResultRenderComponent,\n\tresult: {\n\t\tcontent: Array<{ type: string; text?: string; data?: string; mimeType?: string }>;\n\t\tdetails?: BashToolDetails;\n\t},\n\toptions: ToolRenderResultOptions,\n\tshowImages: boolean,\n\tstartedAt: number | undefined,\n\tendedAt: number | undefined,\n): void {\n\tconst state = component.state;\n\tcomponent.clear();\n\n\tconst renderPreview = !options.expanded ? result.details?.preview : undefined;\n\tlet output = (renderPreview ? renderPreview.content : getTextOutput(result as any, showImages)).trim();\n\tconst truncation = result.details?.truncation;\n\tconst fullOutputPath = result.details?.fullOutputPath;\n\tconst fullOutputError = result.details?.fullOutputError;\n\tif (!options.isPartial && truncation?.truncated && fullOutputPath && output.endsWith(\"]\")) {\n\t\tconst footerStart = output.lastIndexOf(\"\\n\\n[\");\n\t\tif (footerStart !== -1 && output.slice(footerStart).includes(fullOutputPath)) {\n\t\t\toutput = output.slice(0, footerStart).trimEnd();\n\t\t}\n\t}\n\n\tif (output) {\n\t\tif (options.expanded) {\n\t\t\tconst styledOutput = output\n\t\t\t\t.split(\"\\n\")\n\t\t\t\t.map((line) => theme.fg(\"toolOutput\", line))\n\t\t\t\t.join(\"\\n\");\n\t\t\tcomponent.addChild(new Text(`\\n${styledOutput}`, 0, 0));\n\t\t} else {\n\t\t\tcomponent.addChild({\n\t\t\t\trender: (width: number) => {\n\t\t\t\t\tif (state.cachedLines === undefined || state.cachedWidth !== width) {\n\t\t\t\t\t\tconst preview = truncateToVisualLines(output, BASH_PREVIEW_LINES, width);\n\t\t\t\t\t\tstate.cachedLines = preview.visualLines.map((line) => theme.fg(\"toolOutput\", line));\n\t\t\t\t\t\tstate.cachedSkipped = (result.details?.preview?.skippedLines ?? 0) + preview.skippedCount;\n\t\t\t\t\t\tstate.cachedWidth = width;\n\t\t\t\t\t}\n\t\t\t\t\tif (state.cachedSkipped && state.cachedSkipped > 0) {\n\t\t\t\t\t\tconst hint =\n\t\t\t\t\t\t\ttheme.fg(\"muted\", `... (${state.cachedSkipped} earlier lines,`) +\n\t\t\t\t\t\t\t` ${keyHint(\"app.tools.expand\", \"to expand\")})`;\n\t\t\t\t\t\treturn [\"\", truncateToWidth(hint, width, \"...\"), ...(state.cachedLines ?? [])];\n\t\t\t\t\t}\n\t\t\t\t\treturn [\"\", ...(state.cachedLines ?? [])];\n\t\t\t\t},\n\t\t\t\tinvalidate: () => {\n\t\t\t\t\tstate.cachedWidth = undefined;\n\t\t\t\t\tstate.cachedLines = undefined;\n\t\t\t\t\tstate.cachedSkipped = undefined;\n\t\t\t\t},\n\t\t\t});\n\t\t}\n\t}\n\n\tif (truncation?.truncated || fullOutputPath || fullOutputError) {\n\t\tconst warnings: string[] = [];\n\t\tif (fullOutputPath) {\n\t\t\twarnings.push(`Full output: ${fullOutputPath}`);\n\t\t} else if (fullOutputError) {\n\t\t\twarnings.push(`Full output unavailable: ${fullOutputError}`);\n\t\t}\n\t\tif (truncation?.truncated) {\n\t\t\tif (truncation.truncatedBy === \"lines\") {\n\t\t\t\twarnings.push(`Truncated: showing ${truncation.outputLines} of ${truncation.totalLines} lines`);\n\t\t\t} else {\n\t\t\t\twarnings.push(\n\t\t\t\t\t`Truncated: ${truncation.outputLines} lines shown (${formatSize(truncation.maxBytes ?? DEFAULT_MAX_BYTES)} limit)`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tcomponent.addChild(new Text(`\\n${theme.fg(\"warning\", `[${warnings.join(\". \")}]`)}`, 0, 0));\n\t}\n\n\tif (startedAt !== undefined) {\n\t\tconst label = options.isPartial ? \"Elapsed\" : \"Took\";\n\t\tconst endTime = endedAt ?? Date.now();\n\t\tcomponent.addChild(new Text(`\\n${theme.fg(\"muted\", `${label} ${formatDuration(endTime - startedAt)}`)}`, 0, 0));\n\t}\n}\n\nasync function tryOptimizeCommand(\n\tcommand: string,\n\tcwd: string,\n): Promise<{ optimized: boolean; output?: string; exitCode?: number }> {\n\tif (process.env.PI_TOOL_OPTIMIZER_DISABLED === \"1\") {\n\t\treturn { optimized: false };\n\t}\n\n\tconst trimmed = command.trim();\n\tif (!trimmed) {\n\t\treturn { optimized: false };\n\t}\n\n\t// Reject if there are shell operators or pipes/redirects\n\tconst shellOperators = [\"|\", \">\", \"<\", \"&\", \";\", \"\\n\", \"\\r\", \"$\", \"`\", \"(\", \")\", \"*\", \"?\", \"[\", \"]\"];\n\tif (shellOperators.some((op) => trimmed.includes(op))) {\n\t\treturn { optimized: false };\n\t}\n\n\t// Simple tokenizer split by whitespace\n\tconst args = trimmed.split(/\\s+/);\n\tif (args.length === 0) {\n\t\treturn { optimized: false };\n\t}\n\n\tconst cmd = args[0];\n\tconst unquote = (s: string) => {\n\t\tif ((s.startsWith('\"') && s.endsWith('\"')) || (s.startsWith(\"'\") && s.endsWith(\"'\"))) {\n\t\t\treturn s.slice(1, -1);\n\t\t}\n\t\treturn s;\n\t};\n\n\tconst resolveToCwd = (p: string, base: string) => {\n\t\tconst clean = unquote(p);\n\t\tif (clean.startsWith(\"/\")) return clean;\n\t\treturn resolvePath(base, clean);\n\t};\n\n\ttry {\n\t\tif (cmd === \"cat\") {\n\t\t\tif (args.length === 2 && !args[1].startsWith(\"-\")) {\n\t\t\t\tconst filePath = resolveToCwd(args[1], cwd);\n\t\t\t\tconst content = await fsReadFile(filePath, \"utf-8\");\n\t\t\t\treturn { optimized: true, output: content, exitCode: 0 };\n\t\t\t}\n\t\t} else if (cmd === \"head\") {\n\t\t\tif (args.length === 2 && !args[1].startsWith(\"-\")) {\n\t\t\t\tconst filePath = resolveToCwd(args[1], cwd);\n\t\t\t\tconst content = await fsReadFile(filePath, \"utf-8\");\n\t\t\t\tconst lines = content.split(\"\\n\").slice(0, 10).join(\"\\n\");\n\t\t\t\treturn { optimized: true, output: lines, exitCode: 0 };\n\t\t\t} else if (args.length === 4 && args[1] === \"-n\" && !args[3].startsWith(\"-\")) {\n\t\t\t\tconst count = parseInt(args[2], 10);\n\t\t\t\tif (!Number.isNaN(count) && count >= 0) {\n\t\t\t\t\tconst filePath = resolveToCwd(args[3], cwd);\n\t\t\t\t\tconst content = await fsReadFile(filePath, \"utf-8\");\n\t\t\t\t\tconst lines = content.split(\"\\n\").slice(0, count).join(\"\\n\");\n\t\t\t\t\treturn { optimized: true, output: lines, exitCode: 0 };\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (cmd === \"tail\") {\n\t\t\tif (args.length === 2 && !args[1].startsWith(\"-\")) {\n\t\t\t\tconst filePath = resolveToCwd(args[1], cwd);\n\t\t\t\tconst content = await fsReadFile(filePath, \"utf-8\");\n\t\t\t\tconst allLines = content.split(\"\\n\");\n\t\t\t\tconst lines = allLines.slice(Math.max(0, allLines.length - 10)).join(\"\\n\");\n\t\t\t\treturn { optimized: true, output: lines, exitCode: 0 };\n\t\t\t} else if (args.length === 4 && args[1] === \"-n\" && !args[3].startsWith(\"-\")) {\n\t\t\t\tconst count = parseInt(args[2], 10);\n\t\t\t\tif (!Number.isNaN(count) && count >= 0) {\n\t\t\t\t\tconst filePath = resolveToCwd(args[3], cwd);\n\t\t\t\t\tconst content = await fsReadFile(filePath, \"utf-8\");\n\t\t\t\t\tconst allLines = content.split(\"\\n\");\n\t\t\t\t\tconst lines = allLines.slice(Math.max(0, allLines.length - count)).join(\"\\n\");\n\t\t\t\t\treturn { optimized: true, output: lines, exitCode: 0 };\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (cmd === \"ls\") {\n\t\t\tif (args.length === 1 || (args.length === 2 && !args[1].startsWith(\"-\"))) {\n\t\t\t\tconst targetDir = args.length === 2 ? resolveToCwd(args[1], cwd) : cwd;\n\t\t\t\tconst entries = await fsReaddir(targetDir);\n\t\t\t\tentries.sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase()));\n\t\t\t\tconst results: string[] = [];\n\t\t\t\tfor (const entry of entries) {\n\t\t\t\t\tlet suffix = \"\";\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst entryStat = await fsStat(resolvePath(targetDir, entry));\n\t\t\t\t\t\tif (entryStat.isDirectory()) suffix = \"/\";\n\t\t\t\t\t} catch {}\n\t\t\t\t\tresults.push(entry + suffix);\n\t\t\t\t}\n\t\t\t\treturn { optimized: true, output: results.join(\"\\n\"), exitCode: 0 };\n\t\t\t}\n\t\t} else if (cmd === \"grep\" || cmd === \"rg\") {\n\t\t\tif (args.length === 3 && !args[1].startsWith(\"-\") && !args[2].startsWith(\"-\")) {\n\t\t\t\tconst patternStr = unquote(args[1]);\n\t\t\t\tif (/[\\\\^$.|?*+()[\\]{}]/.test(patternStr)) return { optimized: false };\n\t\t\t\tconst filePath = resolveToCwd(args[2], cwd);\n\t\t\t\tconst content = await fsReadFile(filePath, \"utf-8\");\n\t\t\t\tconst lines = content.split(\"\\n\");\n\t\t\t\tconst matches: string[] = [];\n\t\t\t\tfor (let i = 0; i < lines.length; i++) {\n\t\t\t\t\tif (lines[i].includes(patternStr)) {\n\t\t\t\t\t\tmatches.push(lines[i]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn { optimized: true, output: matches.join(\"\\n\"), exitCode: matches.length > 0 ? 0 : 1 };\n\t\t\t}\n\t\t} else if (cmd === \"find\") {\n\t\t\tif (args.length === 1 || (args.length === 2 && !args[1].startsWith(\"-\"))) {\n\t\t\t\tconst searchPath = args.length === 2 ? resolveToCwd(args[1], cwd) : cwd;\n\t\t\t\tconst walk = async (dir: string): Promise<string[]> => {\n\t\t\t\t\tlet results: string[] = [];\n\t\t\t\t\tconst entries = await fsReaddir(dir, { withFileTypes: true });\n\t\t\t\t\tfor (const entry of entries) {\n\t\t\t\t\t\tconst full = resolvePath(dir, entry.name);\n\t\t\t\t\t\tresults.push(full);\n\t\t\t\t\t\tif (entry.isDirectory()) {\n\t\t\t\t\t\t\tresults = results.concat(await walk(full));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn results;\n\t\t\t\t};\n\t\t\t\tconst all = (await walk(searchPath)).map((p) => relativePath(searchPath, p).replace(/\\\\/g, \"/\"));\n\t\t\t\treturn { optimized: true, output: all.join(\"\\n\"), exitCode: 0 };\n\t\t\t}\n\t\t}\n\t} catch {\n\t\treturn { optimized: false };\n\t}\n\n\treturn { optimized: false };\n}\n\nexport function createBashToolDefinition(\n\tcwd: string,\n\toptions?: BashToolOptions,\n): ToolDefinition<typeof bashSchema, BashToolDetails | undefined, BashRenderState> {\n\tconst ops = options?.operations ?? createLocalBashOperations({ shellPath: options?.shellPath });\n\tconst commandPrefix = options?.commandPrefix;\n\tconst spawnHook = options?.spawnHook;\n\tconst canOptimizeCommand = !options?.operations && !options?.shellPath && !commandPrefix && !spawnHook;\n\tconst canFilterCommand = canOptimizeCommand;\n\treturn {\n\t\tname: \"bash\",\n\t\tlabel: \"bash\",\n\t\tdescription: `Execute a bash command in the current working directory. Returns stdout and stderr. Output is truncated to last ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). If truncated, full output is saved to a temp file. Optionally provide a timeout in seconds. Without an explicit timeout, the command is killed after ${DEFAULT_COMMAND_SILENCE_MS / 1000}s of continuous silence (no stdout/stderr output) rather than being bounded by total runtime; commands that keep producing output are never killed by this. Provide an explicit timeout to replace the silence watchdog with a wall-clock limit, or background long, quiet work with '&'.`,\n\t\tpromptSnippet: \"Execute bash commands (ls, grep, find, etc.)\",\n\t\tparameters: bashSchema,\n\t\tasync execute(\n\t\t\t_toolCallId,\n\t\t\t{ command, timeout }: { command: string; timeout?: number },\n\t\t\tsignal?: AbortSignal,\n\t\t\tonUpdate?,\n\t\t\t_ctx?,\n\t\t) {\n\t\t\tconst resolvedCommand = commandPrefix ? `${commandPrefix}\\n${command}` : command;\n\t\t\tconst spawnContext = resolveSpawnContext(resolvedCommand, cwd, spawnHook);\n\t\t\tconst output = new OutputAccumulator({ tempFilePrefix: \"pi-bash\" });\n\t\t\tlet updateTimer: NodeJS.Timeout | undefined;\n\t\t\tlet updateDirty = false;\n\t\t\tlet lastUpdateAt = 0;\n\n\t\t\tconst emitOutputUpdate = () => {\n\t\t\t\tif (!onUpdate || !updateDirty) return;\n\t\t\t\tupdateDirty = false;\n\t\t\t\tlastUpdateAt = Date.now();\n\t\t\t\tconst snapshot = output.previewSnapshot(BASH_PREVIEW_LINES, BASH_PREVIEW_BYTES, {\n\t\t\t\t\tpersistIfFullTruncated: true,\n\t\t\t\t});\n\t\t\t\tconst preview = {\n\t\t\t\t\tcontent: snapshot.content,\n\t\t\t\t\tskippedLines: Math.max(0, snapshot.truncation.totalLines - snapshot.truncation.outputLines),\n\t\t\t\t};\n\t\t\t\tonUpdate({\n\t\t\t\t\tcontent: [{ type: \"text\", text: preview.content || \"\" }],\n\t\t\t\t\tdetails: {\n\t\t\t\t\t\ttruncation: snapshot.truncation.truncated ? snapshot.truncation : undefined,\n\t\t\t\t\t\tfullOutputPath: snapshot.fullOutputPath,\n\t\t\t\t\t\tfullOutputError: snapshot.fullOutputError,\n\t\t\t\t\t\tpreview,\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t};\n\n\t\t\tconst clearUpdateTimer = () => {\n\t\t\t\tif (updateTimer) {\n\t\t\t\t\tclearTimeout(updateTimer);\n\t\t\t\t\tupdateTimer = undefined;\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tconst scheduleOutputUpdate = () => {\n\t\t\t\tif (!onUpdate) return;\n\t\t\t\tupdateDirty = true;\n\t\t\t\tconst delay = BASH_UPDATE_THROTTLE_MS - (Date.now() - lastUpdateAt);\n\t\t\t\tif (delay <= 0) {\n\t\t\t\t\tclearUpdateTimer();\n\t\t\t\t\temitOutputUpdate();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tupdateTimer ??= setTimeout(() => {\n\t\t\t\t\tupdateTimer = undefined;\n\t\t\t\t\temitOutputUpdate();\n\t\t\t\t}, delay);\n\t\t\t};\n\n\t\t\tif (onUpdate) {\n\t\t\t\tonUpdate({ content: [], details: undefined });\n\t\t\t}\n\n\t\t\tconst handleData = (data: Buffer) => {\n\t\t\t\toutput.append(data);\n\t\t\t\tscheduleOutputUpdate();\n\t\t\t};\n\n\t\t\tconst finishOutput = async () => {\n\t\t\t\toutput.finish();\n\t\t\t\tclearUpdateTimer();\n\t\t\t\temitOutputUpdate();\n\t\t\t\treturn output.snapshot({ persistIfTruncated: true });\n\t\t\t};\n\n\t\t\tconst formatOutput = (snapshot: Awaited<ReturnType<typeof finishOutput>>, emptyText = \"(no output)\") => {\n\t\t\t\tconst truncation = snapshot.truncation;\n\t\t\t\tlet text = snapshot.content || emptyText;\n\t\t\t\tlet details: BashToolDetails | undefined;\n\t\t\t\tconst preview = output.preview(BASH_PREVIEW_LINES, BASH_PREVIEW_BYTES);\n\t\t\t\tconst fullOutputNotice = snapshot.fullOutputPath\n\t\t\t\t\t? `Full output: ${snapshot.fullOutputPath}`\n\t\t\t\t\t: snapshot.fullOutputError\n\t\t\t\t\t\t? `Full output unavailable: ${snapshot.fullOutputError}`\n\t\t\t\t\t\t: \"Full output unavailable\";\n\t\t\t\tif (truncation.truncated || preview.skippedLines > 0) {\n\t\t\t\t\tdetails = { preview };\n\t\t\t\t}\n\t\t\t\tif (snapshot.fullOutputPath || snapshot.fullOutputError) {\n\t\t\t\t\tdetails = {\n\t\t\t\t\t\t...(details ?? {}),\n\t\t\t\t\t\tfullOutputPath: snapshot.fullOutputPath,\n\t\t\t\t\t\tfullOutputError: snapshot.fullOutputError,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tif (truncation.truncated) {\n\t\t\t\t\tdetails = {\n\t\t\t\t\t\t...(details ?? {}),\n\t\t\t\t\t\ttruncation,\n\t\t\t\t\t\tfullOutputPath: snapshot.fullOutputPath,\n\t\t\t\t\t\tfullOutputError: snapshot.fullOutputError,\n\t\t\t\t\t};\n\t\t\t\t\tconst startLine = truncation.totalLines - truncation.outputLines + 1;\n\t\t\t\t\tconst endLine = truncation.totalLines;\n\t\t\t\t\tif (truncation.lastLinePartial) {\n\t\t\t\t\t\tconst lastLineSize = formatSize(output.getLastLineBytes());\n\t\t\t\t\t\ttext += `\\n\\n[Showing last ${formatSize(truncation.outputBytes)} of line ${endLine} (line is ${lastLineSize}). ${fullOutputNotice}]`;\n\t\t\t\t\t} else if (truncation.truncatedBy === \"lines\") {\n\t\t\t\t\t\ttext += `\\n\\n[Showing lines ${startLine}-${endLine} of ${truncation.totalLines}. ${fullOutputNotice}]`;\n\t\t\t\t\t} else {\n\t\t\t\t\t\ttext += `\\n\\n[Showing lines ${startLine}-${endLine} of ${truncation.totalLines} (${formatSize(DEFAULT_MAX_BYTES)} limit). ${fullOutputNotice}]`;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn { text, details };\n\t\t\t};\n\n\t\t\tconst appendStatus = (text: string, status: string) => `${text ? `${text}\\n\\n` : \"\"}${status}`;\n\n\t\t\ttry {\n\t\t\t\tif (canFilterCommand) {\n\t\t\t\t\tconst classification = classifyGitCommand(command, spawnContext.env);\n\t\t\t\t\tif (classification.eligible && classification.subcommand) {\n\t\t\t\t\t\tconst res = await executeFilteredGit(\n\t\t\t\t\t\t\tcwd,\n\t\t\t\t\t\t\tclassification.subcommand,\n\t\t\t\t\t\t\tclassification.globalOptions || [],\n\t\t\t\t\t\t\tclassification.subcommandArgs || [],\n\t\t\t\t\t\t\t{ signal, timeout },\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (res.exitCode !== -100) {\n\t\t\t\t\t\t\toutput.append(res.rawBytes ?? Buffer.from(res.rawOut, \"utf-8\"));\n\t\t\t\t\t\t\tconst snapshot = await finishOutput();\n\t\t\t\t\t\t\tif (res.exitCode !== 0) {\n\t\t\t\t\t\t\t\tconst { text: rawOutputText } = formatOutput(snapshot);\n\t\t\t\t\t\t\t\tthrow new Error(appendStatus(rawOutputText, `Command exited with code ${res.exitCode}`));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tconst details = snapshot.truncation.truncated\n\t\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\t\ttruncation: snapshot.truncation,\n\t\t\t\t\t\t\t\t\t\tfullOutputPath: snapshot.fullOutputPath,\n\t\t\t\t\t\t\t\t\t\tfullOutputError: snapshot.fullOutputError,\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t: snapshot.fullOutputPath || snapshot.fullOutputError\n\t\t\t\t\t\t\t\t\t? { fullOutputPath: snapshot.fullOutputPath, fullOutputError: snapshot.fullOutputError }\n\t\t\t\t\t\t\t\t\t: undefined;\n\t\t\t\t\t\t\treturn { content: [{ type: \"text\", text: res.output }], details };\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (canOptimizeCommand) {\n\t\t\t\t\tconst optResult = await tryOptimizeCommand(command, cwd);\n\t\t\t\t\tif (optResult.optimized) {\n\t\t\t\t\t\toutput.append(Buffer.from(optResult.output ?? \"\", \"utf-8\"));\n\t\t\t\t\t\tconst snapshot = await finishOutput();\n\t\t\t\t\t\tconst { text: outputText, details } = formatOutput(snapshot);\n\t\t\t\t\t\tif (optResult.exitCode !== 0 && optResult.exitCode !== undefined) {\n\t\t\t\t\t\t\tthrow new Error(appendStatus(outputText, `Command exited with code ${optResult.exitCode}`));\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn { content: [{ type: \"text\", text: outputText }], details };\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tlet exitCode: number | null;\n\t\t\t\ttry {\n\t\t\t\t\t// Bash cannot statically declare which files a command mutates, so the\n\t\t\t\t\t// actual shell execution takes the coarse exclusive barrier: it waits for\n\t\t\t\t\t// in-flight edit/write mutations to drain and blocks new ones meanwhile.\n\t\t\t\t\tconst result = await withExclusiveMutationBarrier(() =>\n\t\t\t\t\t\tops.exec(spawnContext.command, spawnContext.cwd, {\n\t\t\t\t\t\t\tonData: handleData,\n\t\t\t\t\t\t\tsignal,\n\t\t\t\t\t\t\ttimeout,\n\t\t\t\t\t\t\tenv: spawnContext.env,\n\t\t\t\t\t\t}),\n\t\t\t\t\t);\n\t\t\t\t\texitCode = result.exitCode;\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst snapshot = await finishOutput();\n\t\t\t\t\tconst { text } = formatOutput(snapshot, \"\");\n\t\t\t\t\tif (err instanceof Error && err.message === \"aborted\") {\n\t\t\t\t\t\tthrow new Error(appendStatus(text, \"Command aborted\"));\n\t\t\t\t\t}\n\t\t\t\t\tif (err instanceof Error && err.message.startsWith(\"timeout:\")) {\n\t\t\t\t\t\tconst timeoutSecs = err.message.split(\":\")[1];\n\t\t\t\t\t\tthrow new Error(appendStatus(text, `Command timed out after ${timeoutSecs} seconds`));\n\t\t\t\t\t}\n\t\t\t\t\tif (err instanceof Error && err.message.startsWith(\"silence:\")) {\n\t\t\t\t\t\tconst secs = err.message.split(\":\")[1];\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\tappendStatus(\n\t\t\t\t\t\t\t\ttext,\n\t\t\t\t\t\t\t\t`Command killed after ${secs}s of silence (no output). If the command is legitimately quiet for long stretches, re-run it with an explicit timeout, or run it in the background with '&'.`,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tthrow err;\n\t\t\t\t}\n\n\t\t\t\tconst snapshot = await finishOutput();\n\t\t\t\tconst { text: outputText, details } = formatOutput(snapshot);\n\t\t\t\tif (exitCode !== 0 && exitCode !== null) {\n\t\t\t\t\tthrow new Error(appendStatus(outputText, `Command exited with code ${exitCode}`));\n\t\t\t\t}\n\t\t\t\treturn { content: [{ type: \"text\", text: outputText }], details };\n\t\t\t} finally {\n\t\t\t\tclearUpdateTimer();\n\t\t\t\tawait output.closeTempFile();\n\t\t\t}\n\t\t},\n\t\trenderCall(args, _theme, context) {\n\t\t\tconst state = context.state;\n\t\t\tif (context.executionStarted && state.startedAt === undefined) {\n\t\t\t\tstate.startedAt = Date.now();\n\t\t\t\tstate.endedAt = undefined;\n\t\t\t}\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(formatBashCall(args));\n\t\t\treturn text;\n\t\t},\n\t\trenderResult(result, options, _theme, context) {\n\t\t\tconst state = context.state;\n\t\t\tif (state.startedAt !== undefined && options.isPartial && !state.interval) {\n\t\t\t\tstate.interval = setInterval(() => context.invalidate(), 1000);\n\t\t\t}\n\t\t\tif (!options.isPartial || context.isError) {\n\t\t\t\tstate.endedAt ??= Date.now();\n\t\t\t\tif (state.interval) {\n\t\t\t\t\tclearInterval(state.interval);\n\t\t\t\t\tstate.interval = undefined;\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst component =\n\t\t\t\t(context.lastComponent as BashResultRenderComponent | undefined) ?? new BashResultRenderComponent();\n\t\t\trebuildBashResultRenderComponent(\n\t\t\t\tcomponent,\n\t\t\t\tresult as any,\n\t\t\t\toptions,\n\t\t\t\tcontext.showImages,\n\t\t\t\tstate.startedAt,\n\t\t\t\tstate.endedAt,\n\t\t\t);\n\t\t\tcomponent.invalidate();\n\t\t\treturn component;\n\t\t},\n\t};\n}\n\nexport function createBashTool(cwd: string, options?: BashToolOptions): AgentTool<typeof bashSchema> {\n\treturn wrapToolDefinition(createBashToolDefinition(cwd, options));\n}\n"]}
@@ -9,8 +9,8 @@ import { Type } from "typebox";
9
9
  import { keyHint } from "../../modes/interactive/components/keybinding-hints.js";
10
10
  import { truncateToVisualLines } from "../../modes/interactive/components/visual-truncate.js";
11
11
  import { theme } from "../../modes/interactive/theme/theme.js";
12
- import { waitForChildProcess } from "../../utils/child-process.js";
13
- import { getShellConfig, getShellEnv, killProcessTree, trackDetachedChildPid, untrackDetachedChildPid, } from "../../utils/shell.js";
12
+ import { waitForChildProcessWithTermination } from "../../utils/child-process.js";
13
+ import { getShellConfig, getShellEnv, trackDetachedChildPid, untrackDetachedChildPid } from "../../utils/shell.js";
14
14
  import { withExclusiveMutationBarrier } from "./file-mutation-queue.js";
15
15
  import { classifyGitCommand, executeFilteredGit } from "./git-filter.js";
16
16
  import { OutputAccumulator } from "./output-accumulator.js";
@@ -57,12 +57,8 @@ export function createLocalBashOperations(options) {
57
57
  });
58
58
  if (child.pid)
59
59
  trackDetachedChildPid(child.pid);
60
- let timedOut = false;
61
- let timeoutHandle;
62
- const onAbort = () => {
63
- if (child.pid)
64
- killProcessTree(child.pid);
65
- };
60
+ const terminationController = new AbortController();
61
+ const onAbort = () => terminationController.abort();
66
62
  // A command that keeps producing output must never be killed by this mechanism:
67
63
  // silence bounds mute-ness, not duration. It arms when the caller left `timeout`
68
64
  // unset or non-positive (treated as unset) — an explicit positive timeout means
@@ -74,8 +70,7 @@ export function createLocalBashOperations(options) {
74
70
  silenceMs,
75
71
  onSilence: () => {
76
72
  silenceKilled = true;
77
- if (child.pid)
78
- killProcessTree(child.pid);
73
+ terminationController.abort();
79
74
  },
80
75
  })
81
76
  : undefined;
@@ -84,44 +79,36 @@ export function createLocalBashOperations(options) {
84
79
  onData(data);
85
80
  };
86
81
  try {
87
- // Set timeout if provided.
88
- if (timeout !== undefined && timeout > 0) {
89
- timeoutHandle = setTimeout(() => {
90
- timedOut = true;
91
- if (child.pid)
92
- killProcessTree(child.pid);
93
- }, timeout * 1000);
94
- }
95
82
  // Stream stdout and stderr.
96
83
  child.stdout?.on("data", onChunk);
97
84
  child.stderr?.on("data", onChunk);
98
- // Handle abort signal by killing the entire process tree.
85
+ // Forward caller cancellation into the shared bounded termination path.
99
86
  if (signal) {
100
87
  if (signal.aborted)
101
88
  onAbort();
102
89
  else
103
90
  signal.addEventListener("abort", onAbort, { once: true });
104
91
  }
105
- // Handle shell spawn errors and wait for the process to terminate without hanging
106
- // on inherited stdio handles held by detached descendants.
107
- const exitCode = await waitForChildProcess(child);
92
+ const terminal = await waitForChildProcessWithTermination(child, {
93
+ signal: terminationController.signal,
94
+ timeoutMs: timeout !== undefined && timeout > 0 ? timeout * 1000 : undefined,
95
+ killGraceMs: 2_000,
96
+ });
108
97
  if (signal?.aborted) {
109
98
  throw new Error("aborted");
110
99
  }
111
- if (timedOut) {
100
+ if (terminal.reason === "timeout") {
112
101
  throw new Error(`timeout:${timeout}`);
113
102
  }
114
103
  if (silenceKilled) {
115
104
  throw new Error(`silence:${silenceMs / 1000}`);
116
105
  }
117
- return { exitCode };
106
+ return { exitCode: terminal.code };
118
107
  }
119
108
  finally {
120
109
  silenceWatchdog?.disarm();
121
110
  if (child.pid)
122
111
  untrackDetachedChildPid(child.pid);
123
- if (timeoutHandle)
124
- clearTimeout(timeoutHandle);
125
112
  if (signal)
126
113
  signal.removeEventListener("abort", onAbort);
127
114
  }