@caupulican/pi-adaptative 0.80.102 → 0.81.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (405) hide show
  1. package/CHANGELOG.md +131 -0
  2. package/dist/cli/session-picker.d.ts +1 -1
  3. package/dist/cli/session-picker.d.ts.map +1 -1
  4. package/dist/cli/session-picker.js.map +1 -1
  5. package/dist/cli.d.ts.map +1 -1
  6. package/dist/cli.js +7 -1
  7. package/dist/cli.js.map +1 -1
  8. package/dist/config.d.ts +11 -0
  9. package/dist/config.d.ts.map +1 -1
  10. package/dist/config.js +17 -3
  11. package/dist/config.js.map +1 -1
  12. package/dist/core/agent-session-runtime.d.ts +1 -1
  13. package/dist/core/agent-session-runtime.d.ts.map +1 -1
  14. package/dist/core/agent-session-runtime.js +6 -6
  15. package/dist/core/agent-session-runtime.js.map +1 -1
  16. package/dist/core/agent-session-services.d.ts +1 -1
  17. package/dist/core/agent-session-services.d.ts.map +1 -1
  18. package/dist/core/agent-session-services.js.map +1 -1
  19. package/dist/core/agent-session.d.ts +152 -512
  20. package/dist/core/agent-session.d.ts.map +1 -1
  21. package/dist/core/agent-session.js +635 -4590
  22. package/dist/core/agent-session.js.map +1 -1
  23. package/dist/core/autonomy/session-lane-record.d.ts +1 -1
  24. package/dist/core/autonomy/session-lane-record.d.ts.map +1 -1
  25. package/dist/core/autonomy/session-lane-record.js.map +1 -1
  26. package/dist/core/autonomy/status.d.ts +1 -0
  27. package/dist/core/autonomy/status.d.ts.map +1 -1
  28. package/dist/core/autonomy/status.js +1 -0
  29. package/dist/core/autonomy/status.js.map +1 -1
  30. package/dist/core/autonomy-telemetry.d.ts +80 -0
  31. package/dist/core/autonomy-telemetry.d.ts.map +1 -0
  32. package/dist/core/autonomy-telemetry.js +266 -0
  33. package/dist/core/autonomy-telemetry.js.map +1 -0
  34. package/dist/core/background-lane-controller.d.ts +186 -0
  35. package/dist/core/background-lane-controller.d.ts.map +1 -0
  36. package/dist/core/background-lane-controller.js +691 -0
  37. package/dist/core/background-lane-controller.js.map +1 -0
  38. package/dist/core/bash-execution-controller.d.ts +51 -0
  39. package/dist/core/bash-execution-controller.d.ts.map +1 -0
  40. package/dist/core/bash-execution-controller.js +96 -0
  41. package/dist/core/bash-execution-controller.js.map +1 -0
  42. package/dist/core/bash-executor.d.ts.map +1 -1
  43. package/dist/core/bash-executor.js +9 -2
  44. package/dist/core/bash-executor.js.map +1 -1
  45. package/dist/core/compaction-support.d.ts +56 -0
  46. package/dist/core/compaction-support.d.ts.map +1 -0
  47. package/dist/core/compaction-support.js +99 -0
  48. package/dist/core/compaction-support.js.map +1 -0
  49. package/dist/core/context/artifact-retrieval.d.ts +1 -1
  50. package/dist/core/context/artifact-retrieval.d.ts.map +1 -1
  51. package/dist/core/context/artifact-retrieval.js +1 -1
  52. package/dist/core/context/artifact-retrieval.js.map +1 -1
  53. package/dist/core/context/context-composition.d.ts.map +1 -1
  54. package/dist/core/context/context-composition.js +1 -1
  55. package/dist/core/context/context-composition.js.map +1 -1
  56. package/dist/core/context/tool-output-packer.d.ts +1 -1
  57. package/dist/core/context/tool-output-packer.d.ts.map +1 -1
  58. package/dist/core/context/tool-output-packer.js +1 -1
  59. package/dist/core/context/tool-output-packer.js.map +1 -1
  60. package/dist/core/context-gc.d.ts.map +1 -1
  61. package/dist/core/context-gc.js +1 -1
  62. package/dist/core/context-gc.js.map +1 -1
  63. package/dist/core/context-pipeline.d.ts +223 -0
  64. package/dist/core/context-pipeline.d.ts.map +1 -0
  65. package/dist/core/context-pipeline.js +594 -0
  66. package/dist/core/context-pipeline.js.map +1 -0
  67. package/dist/core/cost/daily-usage.d.ts +1 -1
  68. package/dist/core/cost/daily-usage.d.ts.map +1 -1
  69. package/dist/core/cost/daily-usage.js +1 -1
  70. package/dist/core/cost/daily-usage.js.map +1 -1
  71. package/dist/core/cost/session-usage.d.ts +1 -1
  72. package/dist/core/cost/session-usage.d.ts.map +1 -1
  73. package/dist/core/cost/session-usage.js +1 -1
  74. package/dist/core/cost/session-usage.js.map +1 -1
  75. package/dist/core/delegation/session-worker-result.d.ts +1 -1
  76. package/dist/core/delegation/session-worker-result.d.ts.map +1 -1
  77. package/dist/core/delegation/session-worker-result.js.map +1 -1
  78. package/dist/core/exec.d.ts +2 -0
  79. package/dist/core/exec.d.ts.map +1 -1
  80. package/dist/core/exec.js +15 -9
  81. package/dist/core/exec.js.map +1 -1
  82. package/dist/core/export-html/index.d.ts +1 -1
  83. package/dist/core/export-html/index.d.ts.map +1 -1
  84. package/dist/core/export-html/index.js +2 -2
  85. package/dist/core/export-html/index.js.map +1 -1
  86. package/dist/core/extensions/builtin.d.ts.map +1 -1
  87. package/dist/core/extensions/builtin.js +2 -2
  88. package/dist/core/extensions/builtin.js.map +1 -1
  89. package/dist/core/extensions/runner.d.ts +1 -1
  90. package/dist/core/extensions/runner.d.ts.map +1 -1
  91. package/dist/core/extensions/runner.js.map +1 -1
  92. package/dist/core/extensions/types.d.ts +2 -4
  93. package/dist/core/extensions/types.d.ts.map +1 -1
  94. package/dist/core/extensions/types.js.map +1 -1
  95. package/dist/core/goal-loop-controller.d.ts +24 -0
  96. package/dist/core/goal-loop-controller.d.ts.map +1 -0
  97. package/dist/core/goal-loop-controller.js +83 -0
  98. package/dist/core/goal-loop-controller.js.map +1 -0
  99. package/dist/core/goals/goal-runtime-snapshot.d.ts +1 -1
  100. package/dist/core/goals/goal-runtime-snapshot.d.ts.map +1 -1
  101. package/dist/core/goals/goal-runtime-snapshot.js.map +1 -1
  102. package/dist/core/goals/session-goal-state.d.ts +1 -1
  103. package/dist/core/goals/session-goal-state.d.ts.map +1 -1
  104. package/dist/core/goals/session-goal-state.js.map +1 -1
  105. package/dist/core/index.d.ts +1 -1
  106. package/dist/core/index.d.ts.map +1 -1
  107. package/dist/core/index.js.map +1 -1
  108. package/dist/core/learning/learning-audit.d.ts +1 -1
  109. package/dist/core/learning/learning-audit.d.ts.map +1 -1
  110. package/dist/core/learning/learning-audit.js.map +1 -1
  111. package/dist/core/learning/session-learning-decision.d.ts +1 -1
  112. package/dist/core/learning/session-learning-decision.d.ts.map +1 -1
  113. package/dist/core/learning/session-learning-decision.js.map +1 -1
  114. package/dist/core/local-runtime-controller.d.ts +99 -0
  115. package/dist/core/local-runtime-controller.d.ts.map +1 -0
  116. package/dist/core/local-runtime-controller.js +214 -0
  117. package/dist/core/local-runtime-controller.js.map +1 -0
  118. package/dist/core/memory/providers/transcript-recall.d.ts.map +1 -1
  119. package/dist/core/memory/providers/transcript-recall.js +1 -1
  120. package/dist/core/memory/providers/transcript-recall.js.map +1 -1
  121. package/dist/core/memory-controller.d.ts +139 -0
  122. package/dist/core/memory-controller.d.ts.map +1 -0
  123. package/dist/core/memory-controller.js +323 -0
  124. package/dist/core/memory-controller.js.map +1 -0
  125. package/dist/core/model-router/status.d.ts +1 -1
  126. package/dist/core/model-router/status.d.ts.map +1 -1
  127. package/dist/core/model-router/status.js.map +1 -1
  128. package/dist/core/model-router-controller.d.ts +140 -0
  129. package/dist/core/model-router-controller.d.ts.map +1 -0
  130. package/dist/core/model-router-controller.js +623 -0
  131. package/dist/core/model-router-controller.js.map +1 -0
  132. package/dist/core/model-selection-controller.d.ts +95 -0
  133. package/dist/core/model-selection-controller.d.ts.map +1 -0
  134. package/dist/core/model-selection-controller.js +252 -0
  135. package/dist/core/model-selection-controller.js.map +1 -0
  136. package/dist/core/models/model-ref.d.ts +13 -0
  137. package/dist/core/models/model-ref.d.ts.map +1 -1
  138. package/dist/core/models/model-ref.js +22 -0
  139. package/dist/core/models/model-ref.js.map +1 -1
  140. package/dist/core/profile-filter-controller.d.ts +77 -0
  141. package/dist/core/profile-filter-controller.d.ts.map +1 -0
  142. package/dist/core/profile-filter-controller.js +159 -0
  143. package/dist/core/profile-filter-controller.js.map +1 -0
  144. package/dist/core/reflection-controller.d.ts +111 -0
  145. package/dist/core/reflection-controller.d.ts.map +1 -0
  146. package/dist/core/reflection-controller.js +412 -0
  147. package/dist/core/reflection-controller.js.map +1 -0
  148. package/dist/core/research/model-fitness.d.ts +12 -0
  149. package/dist/core/research/model-fitness.d.ts.map +1 -1
  150. package/dist/core/research/model-fitness.js +21 -0
  151. package/dist/core/research/model-fitness.js.map +1 -1
  152. package/dist/core/research/session-evidence-bundle.d.ts +1 -1
  153. package/dist/core/research/session-evidence-bundle.d.ts.map +1 -1
  154. package/dist/core/research/session-evidence-bundle.js.map +1 -1
  155. package/dist/core/runtime-builder.d.ts +222 -0
  156. package/dist/core/runtime-builder.d.ts.map +1 -0
  157. package/dist/core/runtime-builder.js +640 -0
  158. package/dist/core/runtime-builder.js.map +1 -0
  159. package/dist/core/sdk.d.ts +2 -2
  160. package/dist/core/sdk.d.ts.map +1 -1
  161. package/dist/core/sdk.js +3 -4
  162. package/dist/core/sdk.js.map +1 -1
  163. package/dist/core/session-analytics.d.ts +96 -0
  164. package/dist/core/session-analytics.d.ts.map +1 -0
  165. package/dist/core/session-analytics.js +331 -0
  166. package/dist/core/session-analytics.js.map +1 -0
  167. package/dist/core/session-manager-factory.d.ts +18 -0
  168. package/dist/core/session-manager-factory.d.ts.map +1 -0
  169. package/dist/core/session-manager-factory.js +32 -0
  170. package/dist/core/session-manager-factory.js.map +1 -0
  171. package/dist/core/session-tree-navigator.d.ts +68 -0
  172. package/dist/core/session-tree-navigator.d.ts.map +1 -0
  173. package/dist/core/session-tree-navigator.js +217 -0
  174. package/dist/core/session-tree-navigator.js.map +1 -0
  175. package/dist/core/system-prompt-builder.d.ts +63 -0
  176. package/dist/core/system-prompt-builder.d.ts.map +1 -0
  177. package/dist/core/system-prompt-builder.js +181 -0
  178. package/dist/core/system-prompt-builder.js.map +1 -0
  179. package/dist/core/tool-gate-controller.d.ts +36 -0
  180. package/dist/core/tool-gate-controller.d.ts.map +1 -0
  181. package/dist/core/tool-gate-controller.js +94 -0
  182. package/dist/core/tool-gate-controller.js.map +1 -0
  183. package/dist/core/tools/artifact-retrieve.d.ts.map +1 -1
  184. package/dist/core/tools/artifact-retrieve.js +1 -1
  185. package/dist/core/tools/artifact-retrieve.js.map +1 -1
  186. package/dist/core/tools/bash.d.ts +4 -2
  187. package/dist/core/tools/bash.d.ts.map +1 -1
  188. package/dist/core/tools/bash.js +49 -7
  189. package/dist/core/tools/bash.js.map +1 -1
  190. package/dist/core/tools/file-mutation-queue.d.ts +6 -0
  191. package/dist/core/tools/file-mutation-queue.d.ts.map +1 -1
  192. package/dist/core/tools/file-mutation-queue.js +61 -1
  193. package/dist/core/tools/file-mutation-queue.js.map +1 -1
  194. package/dist/core/tools/find.d.ts +1 -1
  195. package/dist/core/tools/find.d.ts.map +1 -1
  196. package/dist/core/tools/find.js +1 -1
  197. package/dist/core/tools/find.js.map +1 -1
  198. package/dist/core/tools/grep.d.ts +1 -1
  199. package/dist/core/tools/grep.d.ts.map +1 -1
  200. package/dist/core/tools/grep.js +1 -1
  201. package/dist/core/tools/grep.js.map +1 -1
  202. package/dist/core/tools/index.d.ts +1 -1
  203. package/dist/core/tools/index.d.ts.map +1 -1
  204. package/dist/core/tools/index.js +1 -1
  205. package/dist/core/tools/index.js.map +1 -1
  206. package/dist/core/tools/ls.d.ts +1 -1
  207. package/dist/core/tools/ls.d.ts.map +1 -1
  208. package/dist/core/tools/ls.js +1 -1
  209. package/dist/core/tools/ls.js.map +1 -1
  210. package/dist/core/tools/output-accumulator.d.ts +1 -1
  211. package/dist/core/tools/output-accumulator.d.ts.map +1 -1
  212. package/dist/core/tools/output-accumulator.js +1 -1
  213. package/dist/core/tools/output-accumulator.js.map +1 -1
  214. package/dist/core/tools/read.d.ts +1 -1
  215. package/dist/core/tools/read.d.ts.map +1 -1
  216. package/dist/core/tools/read.js +1 -1
  217. package/dist/core/tools/read.js.map +1 -1
  218. package/dist/core/tools/render-utils.d.ts.map +1 -1
  219. package/dist/core/tools/render-utils.js +1 -1
  220. package/dist/core/tools/render-utils.js.map +1 -1
  221. package/dist/index.d.ts +2 -3
  222. package/dist/index.d.ts.map +1 -1
  223. package/dist/index.js +3 -4
  224. package/dist/index.js.map +1 -1
  225. package/dist/main.d.ts.map +1 -1
  226. package/dist/main.js +13 -12
  227. package/dist/main.js.map +1 -1
  228. package/dist/modes/interactive/auth-dialogs-controller.d.ts +59 -0
  229. package/dist/modes/interactive/auth-dialogs-controller.d.ts.map +1 -0
  230. package/dist/modes/interactive/auth-dialogs-controller.js +398 -0
  231. package/dist/modes/interactive/auth-dialogs-controller.js.map +1 -0
  232. package/dist/modes/interactive/auto-learn-controller.d.ts +168 -0
  233. package/dist/modes/interactive/auto-learn-controller.d.ts.map +1 -0
  234. package/dist/modes/interactive/auto-learn-controller.js +1239 -0
  235. package/dist/modes/interactive/auto-learn-controller.js.map +1 -0
  236. package/dist/modes/interactive/autocomplete-provider.d.ts +26 -0
  237. package/dist/modes/interactive/autocomplete-provider.d.ts.map +1 -0
  238. package/dist/modes/interactive/autocomplete-provider.js +103 -0
  239. package/dist/modes/interactive/autocomplete-provider.js.map +1 -0
  240. package/dist/modes/interactive/autonomy-commands.d.ts +38 -0
  241. package/dist/modes/interactive/autonomy-commands.d.ts.map +1 -0
  242. package/dist/modes/interactive/autonomy-commands.js +142 -0
  243. package/dist/modes/interactive/autonomy-commands.js.map +1 -0
  244. package/dist/modes/interactive/clipboard-input.d.ts +37 -0
  245. package/dist/modes/interactive/clipboard-input.d.ts.map +1 -0
  246. package/dist/modes/interactive/clipboard-input.js +59 -0
  247. package/dist/modes/interactive/clipboard-input.js.map +1 -0
  248. package/dist/modes/interactive/compaction-queue.d.ts +30 -0
  249. package/dist/modes/interactive/compaction-queue.d.ts.map +1 -0
  250. package/dist/modes/interactive/compaction-queue.js +91 -0
  251. package/dist/modes/interactive/compaction-queue.js.map +1 -0
  252. package/dist/modes/interactive/components/bash-execution.d.ts +1 -1
  253. package/dist/modes/interactive/components/bash-execution.d.ts.map +1 -1
  254. package/dist/modes/interactive/components/bash-execution.js +1 -1
  255. package/dist/modes/interactive/components/bash-execution.js.map +1 -1
  256. package/dist/modes/interactive/components/branch-summary-message.d.ts +1 -1
  257. package/dist/modes/interactive/components/branch-summary-message.d.ts.map +1 -1
  258. package/dist/modes/interactive/components/branch-summary-message.js.map +1 -1
  259. package/dist/modes/interactive/components/compaction-summary-message.d.ts +1 -1
  260. package/dist/modes/interactive/components/compaction-summary-message.d.ts.map +1 -1
  261. package/dist/modes/interactive/components/compaction-summary-message.js.map +1 -1
  262. package/dist/modes/interactive/components/custom-message.d.ts +1 -1
  263. package/dist/modes/interactive/components/custom-message.d.ts.map +1 -1
  264. package/dist/modes/interactive/components/custom-message.js.map +1 -1
  265. package/dist/modes/interactive/components/session-selector-search.d.ts +1 -1
  266. package/dist/modes/interactive/components/session-selector-search.d.ts.map +1 -1
  267. package/dist/modes/interactive/components/session-selector-search.js.map +1 -1
  268. package/dist/modes/interactive/components/session-selector.d.ts +1 -1
  269. package/dist/modes/interactive/components/session-selector.d.ts.map +1 -1
  270. package/dist/modes/interactive/components/session-selector.js.map +1 -1
  271. package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
  272. package/dist/modes/interactive/components/tool-execution.js +2 -2
  273. package/dist/modes/interactive/components/tool-execution.js.map +1 -1
  274. package/dist/modes/interactive/components/tree-selector.d.ts +1 -1
  275. package/dist/modes/interactive/components/tree-selector.d.ts.map +1 -1
  276. package/dist/modes/interactive/components/tree-selector.js.map +1 -1
  277. package/dist/modes/interactive/config-backup.d.ts +27 -0
  278. package/dist/modes/interactive/config-backup.d.ts.map +1 -0
  279. package/dist/modes/interactive/config-backup.js +146 -0
  280. package/dist/modes/interactive/config-backup.js.map +1 -0
  281. package/dist/modes/interactive/editor-overlay-host.d.ts +48 -0
  282. package/dist/modes/interactive/editor-overlay-host.d.ts.map +1 -0
  283. package/dist/modes/interactive/editor-overlay-host.js +43 -0
  284. package/dist/modes/interactive/editor-overlay-host.js.map +1 -0
  285. package/dist/modes/interactive/extension-ui-host.d.ts +165 -0
  286. package/dist/modes/interactive/extension-ui-host.d.ts.map +1 -0
  287. package/dist/modes/interactive/extension-ui-host.js +610 -0
  288. package/dist/modes/interactive/extension-ui-host.js.map +1 -0
  289. package/dist/modes/interactive/external-editor.d.ts +18 -0
  290. package/dist/modes/interactive/external-editor.d.ts.map +1 -0
  291. package/dist/modes/interactive/external-editor.js +107 -0
  292. package/dist/modes/interactive/external-editor.js.map +1 -0
  293. package/dist/modes/interactive/history-reload-math.d.ts +24 -0
  294. package/dist/modes/interactive/history-reload-math.d.ts.map +1 -0
  295. package/dist/modes/interactive/history-reload-math.js +129 -0
  296. package/dist/modes/interactive/history-reload-math.js.map +1 -0
  297. package/dist/modes/interactive/interactive-mode.d.ts +22 -238
  298. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  299. package/dist/modes/interactive/interactive-mode.js +714 -5910
  300. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  301. package/dist/modes/interactive/key-handlers.d.ts +46 -0
  302. package/dist/modes/interactive/key-handlers.d.ts.map +1 -0
  303. package/dist/modes/interactive/key-handlers.js +80 -0
  304. package/dist/modes/interactive/key-handlers.js.map +1 -0
  305. package/dist/modes/interactive/local-model-commands.d.ts +68 -0
  306. package/dist/modes/interactive/local-model-commands.d.ts.map +1 -0
  307. package/dist/modes/interactive/local-model-commands.js +288 -0
  308. package/dist/modes/interactive/local-model-commands.js.map +1 -0
  309. package/dist/modes/interactive/profile-menu-controller.d.ts +77 -0
  310. package/dist/modes/interactive/profile-menu-controller.d.ts.map +1 -0
  311. package/dist/modes/interactive/profile-menu-controller.js +917 -0
  312. package/dist/modes/interactive/profile-menu-controller.js.map +1 -0
  313. package/dist/modes/interactive/report-commands.d.ts +46 -0
  314. package/dist/modes/interactive/report-commands.d.ts.map +1 -0
  315. package/dist/modes/interactive/report-commands.js +255 -0
  316. package/dist/modes/interactive/report-commands.js.map +1 -0
  317. package/dist/modes/interactive/resource-display.d.ts +73 -0
  318. package/dist/modes/interactive/resource-display.d.ts.map +1 -0
  319. package/dist/modes/interactive/resource-display.js +278 -0
  320. package/dist/modes/interactive/resource-display.js.map +1 -0
  321. package/dist/modes/interactive/resource-shell-commands.d.ts +64 -0
  322. package/dist/modes/interactive/resource-shell-commands.d.ts.map +1 -0
  323. package/dist/modes/interactive/resource-shell-commands.js +202 -0
  324. package/dist/modes/interactive/resource-shell-commands.js.map +1 -0
  325. package/dist/modes/interactive/session-flow-commands.d.ts +139 -0
  326. package/dist/modes/interactive/session-flow-commands.d.ts.map +1 -0
  327. package/dist/modes/interactive/session-flow-commands.js +458 -0
  328. package/dist/modes/interactive/session-flow-commands.js.map +1 -0
  329. package/dist/modes/interactive/session-io-commands.d.ts +73 -0
  330. package/dist/modes/interactive/session-io-commands.d.ts.map +1 -0
  331. package/dist/modes/interactive/session-io-commands.js +202 -0
  332. package/dist/modes/interactive/session-io-commands.js.map +1 -0
  333. package/dist/modes/interactive/settings-selector-flow.d.ts +42 -0
  334. package/dist/modes/interactive/settings-selector-flow.d.ts.map +1 -0
  335. package/dist/modes/interactive/settings-selector-flow.js +287 -0
  336. package/dist/modes/interactive/settings-selector-flow.js.map +1 -0
  337. package/dist/modes/interactive/signal-lifecycle.d.ts +55 -0
  338. package/dist/modes/interactive/signal-lifecycle.d.ts.map +1 -0
  339. package/dist/modes/interactive/signal-lifecycle.js +177 -0
  340. package/dist/modes/interactive/signal-lifecycle.js.map +1 -0
  341. package/dist/modes/interactive/startup-checks.d.ts +38 -0
  342. package/dist/modes/interactive/startup-checks.d.ts.map +1 -0
  343. package/dist/modes/interactive/startup-checks.js +189 -0
  344. package/dist/modes/interactive/startup-checks.js.map +1 -0
  345. package/dist/modes/rpc/rpc-client.d.ts +1 -1
  346. package/dist/modes/rpc/rpc-client.d.ts.map +1 -1
  347. package/dist/modes/rpc/rpc-client.js.map +1 -1
  348. package/dist/modes/rpc/rpc-types.d.ts +1 -1
  349. package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
  350. package/dist/modes/rpc/rpc-types.js.map +1 -1
  351. package/dist/utils/paths.d.ts +2 -14
  352. package/dist/utils/paths.d.ts.map +1 -1
  353. package/dist/utils/paths.js +5 -30
  354. package/dist/utils/paths.js.map +1 -1
  355. package/dist/utils/process-memory.d.ts +8 -0
  356. package/dist/utils/process-memory.d.ts.map +1 -0
  357. package/dist/utils/process-memory.js +11 -0
  358. package/dist/utils/process-memory.js.map +1 -0
  359. package/dist/utils/shell.d.ts +0 -9
  360. package/dist/utils/shell.d.ts.map +1 -1
  361. package/dist/utils/shell.js +0 -37
  362. package/dist/utils/shell.js.map +1 -1
  363. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  364. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  365. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  366. package/examples/extensions/sandbox/package-lock.json +2 -2
  367. package/examples/extensions/sandbox/package.json +1 -1
  368. package/examples/extensions/with-deps/package-lock.json +2 -2
  369. package/examples/extensions/with-deps/package.json +1 -1
  370. package/examples/sdk/11-sessions.ts +8 -8
  371. package/examples/sdk/13-session-runtime.ts +1 -1
  372. package/npm-shrinkwrap.json +12 -12
  373. package/package.json +4 -4
  374. package/dist/core/compaction/branch-summarization.d.ts +0 -88
  375. package/dist/core/compaction/branch-summarization.d.ts.map +0 -1
  376. package/dist/core/compaction/branch-summarization.js +0 -243
  377. package/dist/core/compaction/branch-summarization.js.map +0 -1
  378. package/dist/core/compaction/compaction.d.ts +0 -143
  379. package/dist/core/compaction/compaction.d.ts.map +0 -1
  380. package/dist/core/compaction/compaction.js +0 -659
  381. package/dist/core/compaction/compaction.js.map +0 -1
  382. package/dist/core/compaction/index.d.ts +0 -7
  383. package/dist/core/compaction/index.d.ts.map +0 -1
  384. package/dist/core/compaction/index.js +0 -7
  385. package/dist/core/compaction/index.js.map +0 -1
  386. package/dist/core/compaction/utils.d.ts +0 -38
  387. package/dist/core/compaction/utils.d.ts.map +0 -1
  388. package/dist/core/compaction/utils.js +0 -153
  389. package/dist/core/compaction/utils.js.map +0 -1
  390. package/dist/core/message-retention.d.ts +0 -26
  391. package/dist/core/message-retention.d.ts.map +0 -1
  392. package/dist/core/message-retention.js +0 -95
  393. package/dist/core/message-retention.js.map +0 -1
  394. package/dist/core/messages.d.ts +0 -77
  395. package/dist/core/messages.d.ts.map +0 -1
  396. package/dist/core/messages.js +0 -123
  397. package/dist/core/messages.js.map +0 -1
  398. package/dist/core/session-manager.d.ts +0 -337
  399. package/dist/core/session-manager.d.ts.map +0 -1
  400. package/dist/core/session-manager.js +0 -1328
  401. package/dist/core/session-manager.js.map +0 -1
  402. package/dist/core/tools/truncate.d.ts +0 -70
  403. package/dist/core/tools/truncate.d.ts.map +0 -1
  404. package/dist/core/tools/truncate.js +0 -215
  405. package/dist/core/tools/truncate.js.map +0 -1
@@ -0,0 +1,94 @@
1
+ /**
2
+ * Agent tool-call gate: model-router escalation, autonomy gating, extension tool hooks, and the
3
+ * untrusted-content output boundary.
4
+ *
5
+ * Extracted verbatim from agent-session.ts (god-file decomposition). Provides the two agent-core
6
+ * hooks (`beforeToolCall`/`afterToolCall`) as bound arrow-field members the session installs onto its
7
+ * agent. `beforeToolCall` runs the router escalation, then the autonomy tool gate (recording the
8
+ * outcome when a capability envelope is active), then extension `tool_call` handlers. `afterToolCall`
9
+ * runs extension `tool_result` handlers and structurally fences output from untrusted-content sources.
10
+ */
11
+ import { evaluateToolGate } from "./autonomy/gates.js";
12
+ import { classifyToolTrust, wrapUntrustedText } from "./security/untrusted-boundary.js";
13
+ export class ToolGateController {
14
+ deps;
15
+ constructor(deps) {
16
+ this.deps = deps;
17
+ }
18
+ beforeToolCall = async ({ toolCall, args }) => {
19
+ const escalation = this.deps.maybeEscalateToolCall(toolCall.name, args);
20
+ if (escalation) {
21
+ return escalation;
22
+ }
23
+ // Autonomy tool gating
24
+ const envelope = this.deps.getCapabilityEnvelope();
25
+ const gateResult = evaluateToolGate({
26
+ toolName: toolCall.name,
27
+ args,
28
+ cwd: this.deps.getCwd(),
29
+ envelope,
30
+ });
31
+ if (envelope) {
32
+ this.deps.recordGateOutcome(gateResult);
33
+ }
34
+ if (gateResult.outcome === "block" || gateResult.outcome === "ask-user") {
35
+ return {
36
+ block: true,
37
+ reason: `Tool execution blocked by autonomy gate [${gateResult.gate}]: ${gateResult.message} (${gateResult.reasonCode})`,
38
+ };
39
+ }
40
+ const runner = this.deps.getExtensionRunner();
41
+ if (!runner.hasHandlers("tool_call")) {
42
+ return undefined;
43
+ }
44
+ try {
45
+ return await runner.emitToolCall({
46
+ type: "tool_call",
47
+ toolName: toolCall.name,
48
+ toolCallId: toolCall.id,
49
+ input: args,
50
+ });
51
+ }
52
+ catch (err) {
53
+ if (err instanceof Error) {
54
+ throw err;
55
+ }
56
+ throw new Error(`Extension failed, blocking execution: ${String(err)}`);
57
+ }
58
+ };
59
+ afterToolCall = async ({ toolCall, args, result, isError }) => {
60
+ const runner = this.deps.getExtensionRunner();
61
+ let content = result.content;
62
+ let details = result.details;
63
+ let resolvedIsError = isError;
64
+ if (runner.hasHandlers("tool_result")) {
65
+ const hookResult = await runner.emitToolResult({
66
+ type: "tool_result",
67
+ toolName: toolCall.name,
68
+ toolCallId: toolCall.id,
69
+ input: args,
70
+ content,
71
+ details,
72
+ isError,
73
+ });
74
+ if (hookResult) {
75
+ content = hookResult.content ?? content;
76
+ details = hookResult.details;
77
+ resolvedIsError = hookResult.isError ?? isError;
78
+ }
79
+ }
80
+ // Untrusted-content boundary: structurally fence output from attacker-controllable sources
81
+ // (web/search, subagents, recall, third-party tools) so injection payloads are framed as data.
82
+ // First-party tools (read/grep/find/ls/edit/write/bash) are trusted and pass through unchanged.
83
+ if (classifyToolTrust(toolCall.name) === "untrusted") {
84
+ const source = `tool:${toolCall.name}`;
85
+ const wrapped = content.map((block) => block.type === "text" ? { ...block, text: wrapUntrustedText(block.text, source) } : block);
86
+ content = wrapped;
87
+ }
88
+ if (content === result.content && details === result.details && resolvedIsError === isError) {
89
+ return undefined;
90
+ }
91
+ return { content, details, isError: resolvedIsError };
92
+ };
93
+ }
94
+ //# sourceMappingURL=tool-gate-controller.js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U,EAAE,CAAC;gBAChB,OAAO,GAAG,UAAU,CAAC,OAAO,IAAI,OAAO,CAAC;gBACxC,OAAO,GAAG,UAAU,CAAC,OAAO,CAAC;gBAC7B,eAAe,GAAG,UAAU,CAAC,OAAO,IAAI,OAAO,CAAC;YACjD,CAAC;QACF,CAAC;QAED,2FAA2F;QAC3F,+FAA+F;QAC/F,gGAAgG;QAChG,IAAI,iBAAiB,CAAC,QAAQ,CAAC,IAAI,CAAC,KAAK,WAAW,EAAE,CAAC;YACtD,MAAM,MAAM,GAAG,QAAQ,QAAQ,CAAC,IAAI,EAAE,CAAC;YACvC,MAAM,OAAO,GAAG,OAAO,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CACrC,KAAK,CAAC,IAAI,KAAK,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,KAAK,EAAE,IAAI,EAAE,iBAAiB,CAAC,KAAK,CAAC,IAAI,EAAE,MAAM,CAAC,EAAE,CAAC,CAAC,CAAC,KAAK,CACzF,CAAC;YACF,OAAO,GAAG,OAAO,CAAC;QACnB,CAAC;QAED,IAAI,OAAO,KAAK,MAAM,CAAC,OAAO,IAAI,OAAO,KAAK,MAAM,CAAC,OAAO,IAAI,eAAe,KAAK,OAAO,EAAE,CAAC;YAC7F,OAAO,SAAS,CAAC;QAClB,CAAC;QACD,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,eAAe,EAAE,CAAC;IAAA,CACtD,CAAC;CACF","sourcesContent":["/**\n * Agent tool-call gate: model-router escalation, autonomy gating, extension tool hooks, and the\n * untrusted-content output boundary.\n *\n * Extracted verbatim from agent-session.ts (god-file decomposition). Provides the two agent-core\n * hooks (`beforeToolCall`/`afterToolCall`) as bound arrow-field members the session installs onto its\n * agent. `beforeToolCall` runs the router escalation, then the autonomy tool gate (recording the\n * outcome when a capability envelope is active), then extension `tool_call` handlers. `afterToolCall`\n * runs extension `tool_result` handlers and structurally fences output from untrusted-content sources.\n */\n\nimport type { Agent } from \"@caupulican/pi-agent-core\";\nimport type { CapabilityEnvelope, GateOutcome } from \"./autonomy/contracts.ts\";\nimport { evaluateToolGate } from \"./autonomy/gates.ts\";\nimport type { ExtensionRunner } from \"./extensions/index.ts\";\nimport { classifyToolTrust, wrapUntrustedText } from \"./security/untrusted-boundary.ts\";\n\ntype BeforeToolCall = NonNullable<Agent[\"beforeToolCall\"]>;\ntype AfterToolCall = NonNullable<Agent[\"afterToolCall\"]>;\n\nexport interface ToolGateControllerDeps {\n\t/** Router escalation: block a tool the active cheap route is not allowed to run. */\n\tmaybeEscalateToolCall(toolName: string, args: unknown): { block: true; reason: string } | undefined;\n\tgetCwd(): string;\n\t/** Active foreground capability envelope, if any — presence enables gate-outcome recording. */\n\tgetCapabilityEnvelope(): CapabilityEnvelope | undefined;\n\t/** Record an autonomy gate outcome (only when a capability envelope is active). */\n\trecordGateOutcome(outcome: GateOutcome): void;\n\tgetExtensionRunner(): ExtensionRunner;\n}\n\nexport class ToolGateController {\n\tprivate readonly deps: ToolGateControllerDeps;\n\n\tconstructor(deps: ToolGateControllerDeps) {\n\t\tthis.deps = deps;\n\t}\n\n\treadonly beforeToolCall: BeforeToolCall = async ({ toolCall, args }) => {\n\t\tconst escalation = this.deps.maybeEscalateToolCall(toolCall.name, args);\n\t\tif (escalation) {\n\t\t\treturn escalation;\n\t\t}\n\n\t\t// Autonomy tool gating\n\t\tconst envelope = this.deps.getCapabilityEnvelope();\n\t\tconst gateResult = evaluateToolGate({\n\t\t\ttoolName: toolCall.name,\n\t\t\targs,\n\t\t\tcwd: this.deps.getCwd(),\n\t\t\tenvelope,\n\t\t});\n\n\t\tif (envelope) {\n\t\t\tthis.deps.recordGateOutcome(gateResult);\n\t\t}\n\n\t\tif (gateResult.outcome === \"block\" || gateResult.outcome === \"ask-user\") {\n\t\t\treturn {\n\t\t\t\tblock: true,\n\t\t\t\treason: `Tool execution blocked by autonomy gate [${gateResult.gate}]: ${gateResult.message} (${gateResult.reasonCode})`,\n\t\t\t};\n\t\t}\n\n\t\tconst runner = this.deps.getExtensionRunner();\n\t\tif (!runner.hasHandlers(\"tool_call\")) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\ttry {\n\t\t\treturn await runner.emitToolCall({\n\t\t\t\ttype: \"tool_call\",\n\t\t\t\ttoolName: toolCall.name,\n\t\t\t\ttoolCallId: toolCall.id,\n\t\t\t\tinput: args as Record<string, unknown>,\n\t\t\t});\n\t\t} catch (err) {\n\t\t\tif (err instanceof Error) {\n\t\t\t\tthrow err;\n\t\t\t}\n\t\t\tthrow new Error(`Extension failed, blocking execution: ${String(err)}`);\n\t\t}\n\t};\n\n\treadonly afterToolCall: AfterToolCall = async ({ toolCall, args, result, isError }) => {\n\t\tconst runner = this.deps.getExtensionRunner();\n\t\tlet content = result.content;\n\t\tlet details = result.details;\n\t\tlet resolvedIsError = isError;\n\n\t\tif (runner.hasHandlers(\"tool_result\")) {\n\t\t\tconst hookResult = await runner.emitToolResult({\n\t\t\t\ttype: \"tool_result\",\n\t\t\t\ttoolName: toolCall.name,\n\t\t\t\ttoolCallId: toolCall.id,\n\t\t\t\tinput: args as Record<string, unknown>,\n\t\t\t\tcontent,\n\t\t\t\tdetails,\n\t\t\t\tisError,\n\t\t\t});\n\t\t\tif (hookResult) {\n\t\t\t\tcontent = hookResult.content ?? content;\n\t\t\t\tdetails = hookResult.details;\n\t\t\t\tresolvedIsError = hookResult.isError ?? isError;\n\t\t\t}\n\t\t}\n\n\t\t// Untrusted-content boundary: structurally fence output from attacker-controllable sources\n\t\t// (web/search, subagents, recall, third-party tools) so injection payloads are framed as data.\n\t\t// First-party tools (read/grep/find/ls/edit/write/bash) are trusted and pass through unchanged.\n\t\tif (classifyToolTrust(toolCall.name) === \"untrusted\") {\n\t\t\tconst source = `tool:${toolCall.name}`;\n\t\t\tconst wrapped = content.map((block) =>\n\t\t\t\tblock.type === \"text\" ? { ...block, text: wrapUntrustedText(block.text, source) } : block,\n\t\t\t);\n\t\t\tcontent = wrapped;\n\t\t}\n\n\t\tif (content === result.content && details === result.details && resolvedIsError === isError) {\n\t\t\treturn undefined;\n\t\t}\n\t\treturn { content, details, isError: resolvedIsError };\n\t};\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"artifact-retrieve.d.ts","sourceRoot":"","sources":["../../../src/core/tools/artifact-retrieve.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,2BAA2B,CAAC;AAE3D,OAAO,EAAE,KAAK,MAAM,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAE5C,OAAO,EACN,KAAK,qBAAqB,EAG1B,MAAM,kCAAkC,CAAC;AAC1C,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,iCAAiC,CAAC;AACrE,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,wBAAwB,CAAC;AAO7D,QAAA,MAAM,sBAAsB;;;;EAc1B,CAAC;AAEH,MAAM,MAAM,yBAAyB,GAAG,MAAM,CAAC,OAAO,sBAAsB,CAAC,CAAC;AAE9E,MAAM,WAAW,2BAA2B;IAC3C,KAAK,EAAE,OAAO,CAAC;IACf,IAAI,EAAE,qBAAqB,CAAC;CAC5B;AAED,MAAM,WAAW,2BAA2B;IAC3C,mGAAmG;IACnG,aAAa,CAAC,EAAE,aAAa,CAAC;CAC9B;AAkCD,wBAAgB,oCAAoC,CACnD,IAAI,EAAE,MAAM,EACZ,OAAO,CAAC,EAAE,2BAA2B,GACnC,cAAc,CAAC,OAAO,sBAAsB,EAAE,2BAA2B,GAAG,SAAS,CAAC,CA2ExF;AAED,wBAAgB,0BAA0B,CACzC,GAAG,EAAE,MAAM,EACX,OAAO,CAAC,EAAE,2BAA2B,GACnC,SAAS,CAAC,OAAO,sBAAsB,CAAC,CAE1C","sourcesContent":["import type { AgentTool } from \"@caupulican/pi-agent-core\";\nimport { Text } from \"@caupulican/pi-tui\";\nimport { type Static, Type } from \"typebox\";\nimport type { Theme } from \"../../modes/interactive/theme/theme.ts\";\nimport {\n\ttype ArtifactRetrievalMode,\n\tDEFAULT_RETRIEVAL_MAX_LINES,\n\tretrieveArtifactSlice,\n} from \"../context/artifact-retrieval.ts\";\nimport type { ArtifactStore } from \"../context/context-artifacts.ts\";\nimport type { ToolDefinition } from \"../extensions/types.ts\";\nimport { invalidArgText, str } from \"./render-utils.ts\";\nimport { wrapToolDefinition } from \"./tool-definition-wrapper.ts\";\nimport { formatSize } from \"./truncate.ts\";\n\nconst ARTIFACT_ID_PREFIX = \"tool-output:\";\n\nconst artifactRetrieveSchema = Type.Object({\n\tartifactId: Type.String({\n\t\tdescription:\n\t\t\t\"Artifact id from a 'Full output: artifact tool-output:<id>' reference in a prior tool result. The 'tool-output:' prefix is optional.\",\n\t}),\n\tmode: Type.Optional(\n\t\tType.Union([Type.Literal(\"metadata\"), Type.Literal(\"head\"), Type.Literal(\"tail\")], {\n\t\t\tdescription:\n\t\t\t\t\"'metadata' for tool/path/size info only (no content); 'head' (default) for the first lines; 'tail' for the last lines.\",\n\t\t}),\n\t),\n\tmaxLines: Type.Optional(\n\t\tType.Number({ description: `Maximum lines to return for head/tail (default: ${DEFAULT_RETRIEVAL_MAX_LINES})` }),\n\t),\n});\n\nexport type ArtifactRetrieveToolInput = Static<typeof artifactRetrieveSchema>;\n\nexport interface ArtifactRetrieveToolDetails {\n\tfound: boolean;\n\tmode: ArtifactRetrievalMode;\n}\n\nexport interface ArtifactRetrieveToolOptions {\n\t/** Session-scoped artifact store to resolve ids against. Omitted: the tool reports unavailable. */\n\tartifactStore?: ArtifactStore;\n}\n\nfunction normalizeArtifactId(input: string): string {\n\treturn input.startsWith(ARTIFACT_ID_PREFIX) ? input.slice(ARTIFACT_ID_PREFIX.length) : input;\n}\n\nfunction formatMetadataText(ref: {\n\tkind: string;\n\ttoolName?: string;\n\tcommand?: string;\n\tpath?: string;\n\tbyteLength: number;\n\tlineCount?: number;\n\treproducible: boolean;\n}): string {\n\tconst lines = [\n\t\t`kind: ${ref.kind}`,\n\t\tref.toolName ? `tool: ${ref.toolName}` : undefined,\n\t\tref.command ? `command: ${ref.command}` : undefined,\n\t\tref.path ? `path: ${ref.path}` : undefined,\n\t\t`size: ${formatSize(ref.byteLength)}`,\n\t\tref.lineCount !== undefined ? `lines: ${ref.lineCount}` : undefined,\n\t\t`reproducible: ${ref.reproducible}`,\n\t];\n\treturn lines.filter((line): line is string => line !== undefined).join(\"\\n\");\n}\n\nfunction formatCall(args: { artifactId: string; mode?: string } | undefined, theme: Theme): string {\n\tconst artifactId = str(args?.artifactId);\n\tconst mode = args?.mode ?? \"head\";\n\tconst idText = artifactId === null ? invalidArgText(theme) : theme.fg(\"accent\", artifactId);\n\treturn `${theme.fg(\"toolTitle\", theme.bold(\"artifact_retrieve\"))} ${idText}${theme.fg(\"toolOutput\", ` (${mode})`)}`;\n}\n\nexport function createArtifactRetrieveToolDefinition(\n\t_cwd: string,\n\toptions?: ArtifactRetrieveToolOptions,\n): ToolDefinition<typeof artifactRetrieveSchema, ArtifactRetrieveToolDetails | undefined> {\n\tconst artifactStore = options?.artifactStore;\n\treturn {\n\t\tname: \"artifact_retrieve\",\n\t\tlabel: \"artifact_retrieve\",\n\t\tdescription:\n\t\t\t\"Retrieve a bounded slice of a packed tool-output artifact by id, from a 'Full output: artifact tool-output:<id>' reference in a prior tool result. Returns metadata, or a bounded head/tail slice -- never the full raw payload in one call.\",\n\t\tpromptSnippet: \"Retrieve a bounded slice of a packed tool-output artifact\",\n\t\tparameters: artifactRetrieveSchema,\n\t\ttoolGroup: \"explore\",\n\t\tasync execute(\n\t\t\t_toolCallId,\n\t\t\t{ artifactId, mode, maxLines }: { artifactId: string; mode?: ArtifactRetrievalMode; maxLines?: number },\n\t\t) {\n\t\t\tconst effectiveMode = mode ?? \"head\";\n\t\t\tif (!artifactStore) {\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [{ type: \"text\", text: \"No artifact store is configured for this session.\" }],\n\t\t\t\t\tdetails: { found: false, mode: effectiveMode },\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tconst result = retrieveArtifactSlice(artifactStore, {\n\t\t\t\tartifactId: normalizeArtifactId(artifactId),\n\t\t\t\tmode,\n\t\t\t\tmaxLines,\n\t\t\t});\n\n\t\t\tif (!result.found) {\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\ttext: `Artifact not found: ${artifactId} (${result.missingReason}). It may have been cleaned up, or the id may be incorrect.`,\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t\tdetails: { found: false, mode: effectiveMode },\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tif (result.mode === \"metadata\") {\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [{ type: \"text\", text: formatMetadataText(result.ref) }],\n\t\t\t\t\tdetails: { found: true, mode: \"metadata\" },\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tlet text = result.slice;\n\t\t\tif (result.truncation.truncated) {\n\t\t\t\ttext += `\\n\\n[Showing ${result.mode} ${result.truncation.outputLines} of ${result.truncation.totalLines} lines. Full artifact: ${formatSize(result.ref.byteLength)}. Retrieve again with a different mode/maxLines for another slice.]`;\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tcontent: [{ type: \"text\", text }],\n\t\t\t\tdetails: { found: true, mode: result.mode },\n\t\t\t};\n\t\t},\n\t\trenderCall(args, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(formatCall(args, theme));\n\t\t\treturn text;\n\t\t},\n\t\trenderResult(result, options, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\tconst content = result.content.find((part) => part.type === \"text\");\n\t\t\tconst body = content && \"text\" in content ? content.text : \"\";\n\t\t\tconst lines = body.split(\"\\n\");\n\t\t\tconst maxLines = options.expanded ? lines.length : 20;\n\t\t\tconst displayLines = lines.slice(0, maxLines);\n\t\t\tconst remaining = lines.length - maxLines;\n\t\t\tlet rendered = displayLines.map((line) => theme.fg(\"toolOutput\", line)).join(\"\\n\");\n\t\t\tif (remaining > 0) rendered += `\\n${theme.fg(\"muted\", `... (${remaining} more lines)`)}`;\n\t\t\ttext.setText(rendered);\n\t\t\treturn text;\n\t\t},\n\t};\n}\n\nexport function createArtifactRetrieveTool(\n\tcwd: string,\n\toptions?: ArtifactRetrieveToolOptions,\n): AgentTool<typeof artifactRetrieveSchema> {\n\treturn wrapToolDefinition(createArtifactRetrieveToolDefinition(cwd, options));\n}\n"]}
1
+ {"version":3,"file":"artifact-retrieve.d.ts","sourceRoot":"","sources":["../../../src/core/tools/artifact-retrieve.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,2BAA2B,CAAC;AAG3D,OAAO,EAAE,KAAK,MAAM,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAE5C,OAAO,EACN,KAAK,qBAAqB,EAG1B,MAAM,kCAAkC,CAAC;AAC1C,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,iCAAiC,CAAC;AACrE,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,wBAAwB,CAAC;AAM7D,QAAA,MAAM,sBAAsB;;;;EAc1B,CAAC;AAEH,MAAM,MAAM,yBAAyB,GAAG,MAAM,CAAC,OAAO,sBAAsB,CAAC,CAAC;AAE9E,MAAM,WAAW,2BAA2B;IAC3C,KAAK,EAAE,OAAO,CAAC;IACf,IAAI,EAAE,qBAAqB,CAAC;CAC5B;AAED,MAAM,WAAW,2BAA2B;IAC3C,mGAAmG;IACnG,aAAa,CAAC,EAAE,aAAa,CAAC;CAC9B;AAkCD,wBAAgB,oCAAoC,CACnD,IAAI,EAAE,MAAM,EACZ,OAAO,CAAC,EAAE,2BAA2B,GACnC,cAAc,CAAC,OAAO,sBAAsB,EAAE,2BAA2B,GAAG,SAAS,CAAC,CA2ExF;AAED,wBAAgB,0BAA0B,CACzC,GAAG,EAAE,MAAM,EACX,OAAO,CAAC,EAAE,2BAA2B,GACnC,SAAS,CAAC,OAAO,sBAAsB,CAAC,CAE1C","sourcesContent":["import type { AgentTool } from \"@caupulican/pi-agent-core\";\nimport { formatSize } from \"@caupulican/pi-agent-core/node\";\nimport { Text } from \"@caupulican/pi-tui\";\nimport { type Static, Type } from \"typebox\";\nimport type { Theme } from \"../../modes/interactive/theme/theme.ts\";\nimport {\n\ttype ArtifactRetrievalMode,\n\tDEFAULT_RETRIEVAL_MAX_LINES,\n\tretrieveArtifactSlice,\n} from \"../context/artifact-retrieval.ts\";\nimport type { ArtifactStore } from \"../context/context-artifacts.ts\";\nimport type { ToolDefinition } from \"../extensions/types.ts\";\nimport { invalidArgText, str } from \"./render-utils.ts\";\nimport { wrapToolDefinition } from \"./tool-definition-wrapper.ts\";\n\nconst ARTIFACT_ID_PREFIX = \"tool-output:\";\n\nconst artifactRetrieveSchema = Type.Object({\n\tartifactId: Type.String({\n\t\tdescription:\n\t\t\t\"Artifact id from a 'Full output: artifact tool-output:<id>' reference in a prior tool result. The 'tool-output:' prefix is optional.\",\n\t}),\n\tmode: Type.Optional(\n\t\tType.Union([Type.Literal(\"metadata\"), Type.Literal(\"head\"), Type.Literal(\"tail\")], {\n\t\t\tdescription:\n\t\t\t\t\"'metadata' for tool/path/size info only (no content); 'head' (default) for the first lines; 'tail' for the last lines.\",\n\t\t}),\n\t),\n\tmaxLines: Type.Optional(\n\t\tType.Number({ description: `Maximum lines to return for head/tail (default: ${DEFAULT_RETRIEVAL_MAX_LINES})` }),\n\t),\n});\n\nexport type ArtifactRetrieveToolInput = Static<typeof artifactRetrieveSchema>;\n\nexport interface ArtifactRetrieveToolDetails {\n\tfound: boolean;\n\tmode: ArtifactRetrievalMode;\n}\n\nexport interface ArtifactRetrieveToolOptions {\n\t/** Session-scoped artifact store to resolve ids against. Omitted: the tool reports unavailable. */\n\tartifactStore?: ArtifactStore;\n}\n\nfunction normalizeArtifactId(input: string): string {\n\treturn input.startsWith(ARTIFACT_ID_PREFIX) ? input.slice(ARTIFACT_ID_PREFIX.length) : input;\n}\n\nfunction formatMetadataText(ref: {\n\tkind: string;\n\ttoolName?: string;\n\tcommand?: string;\n\tpath?: string;\n\tbyteLength: number;\n\tlineCount?: number;\n\treproducible: boolean;\n}): string {\n\tconst lines = [\n\t\t`kind: ${ref.kind}`,\n\t\tref.toolName ? `tool: ${ref.toolName}` : undefined,\n\t\tref.command ? `command: ${ref.command}` : undefined,\n\t\tref.path ? `path: ${ref.path}` : undefined,\n\t\t`size: ${formatSize(ref.byteLength)}`,\n\t\tref.lineCount !== undefined ? `lines: ${ref.lineCount}` : undefined,\n\t\t`reproducible: ${ref.reproducible}`,\n\t];\n\treturn lines.filter((line): line is string => line !== undefined).join(\"\\n\");\n}\n\nfunction formatCall(args: { artifactId: string; mode?: string } | undefined, theme: Theme): string {\n\tconst artifactId = str(args?.artifactId);\n\tconst mode = args?.mode ?? \"head\";\n\tconst idText = artifactId === null ? invalidArgText(theme) : theme.fg(\"accent\", artifactId);\n\treturn `${theme.fg(\"toolTitle\", theme.bold(\"artifact_retrieve\"))} ${idText}${theme.fg(\"toolOutput\", ` (${mode})`)}`;\n}\n\nexport function createArtifactRetrieveToolDefinition(\n\t_cwd: string,\n\toptions?: ArtifactRetrieveToolOptions,\n): ToolDefinition<typeof artifactRetrieveSchema, ArtifactRetrieveToolDetails | undefined> {\n\tconst artifactStore = options?.artifactStore;\n\treturn {\n\t\tname: \"artifact_retrieve\",\n\t\tlabel: \"artifact_retrieve\",\n\t\tdescription:\n\t\t\t\"Retrieve a bounded slice of a packed tool-output artifact by id, from a 'Full output: artifact tool-output:<id>' reference in a prior tool result. Returns metadata, or a bounded head/tail slice -- never the full raw payload in one call.\",\n\t\tpromptSnippet: \"Retrieve a bounded slice of a packed tool-output artifact\",\n\t\tparameters: artifactRetrieveSchema,\n\t\ttoolGroup: \"explore\",\n\t\tasync execute(\n\t\t\t_toolCallId,\n\t\t\t{ artifactId, mode, maxLines }: { artifactId: string; mode?: ArtifactRetrievalMode; maxLines?: number },\n\t\t) {\n\t\t\tconst effectiveMode = mode ?? \"head\";\n\t\t\tif (!artifactStore) {\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [{ type: \"text\", text: \"No artifact store is configured for this session.\" }],\n\t\t\t\t\tdetails: { found: false, mode: effectiveMode },\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tconst result = retrieveArtifactSlice(artifactStore, {\n\t\t\t\tartifactId: normalizeArtifactId(artifactId),\n\t\t\t\tmode,\n\t\t\t\tmaxLines,\n\t\t\t});\n\n\t\t\tif (!result.found) {\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\ttext: `Artifact not found: ${artifactId} (${result.missingReason}). It may have been cleaned up, or the id may be incorrect.`,\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t\tdetails: { found: false, mode: effectiveMode },\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tif (result.mode === \"metadata\") {\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [{ type: \"text\", text: formatMetadataText(result.ref) }],\n\t\t\t\t\tdetails: { found: true, mode: \"metadata\" },\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tlet text = result.slice;\n\t\t\tif (result.truncation.truncated) {\n\t\t\t\ttext += `\\n\\n[Showing ${result.mode} ${result.truncation.outputLines} of ${result.truncation.totalLines} lines. Full artifact: ${formatSize(result.ref.byteLength)}. Retrieve again with a different mode/maxLines for another slice.]`;\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tcontent: [{ type: \"text\", text }],\n\t\t\t\tdetails: { found: true, mode: result.mode },\n\t\t\t};\n\t\t},\n\t\trenderCall(args, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(formatCall(args, theme));\n\t\t\treturn text;\n\t\t},\n\t\trenderResult(result, options, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\tconst content = result.content.find((part) => part.type === \"text\");\n\t\t\tconst body = content && \"text\" in content ? content.text : \"\";\n\t\t\tconst lines = body.split(\"\\n\");\n\t\t\tconst maxLines = options.expanded ? lines.length : 20;\n\t\t\tconst displayLines = lines.slice(0, maxLines);\n\t\t\tconst remaining = lines.length - maxLines;\n\t\t\tlet rendered = displayLines.map((line) => theme.fg(\"toolOutput\", line)).join(\"\\n\");\n\t\t\tif (remaining > 0) rendered += `\\n${theme.fg(\"muted\", `... (${remaining} more lines)`)}`;\n\t\t\ttext.setText(rendered);\n\t\t\treturn text;\n\t\t},\n\t};\n}\n\nexport function createArtifactRetrieveTool(\n\tcwd: string,\n\toptions?: ArtifactRetrieveToolOptions,\n): AgentTool<typeof artifactRetrieveSchema> {\n\treturn wrapToolDefinition(createArtifactRetrieveToolDefinition(cwd, options));\n}\n"]}
@@ -1,9 +1,9 @@
1
+ import { formatSize } from "@caupulican/pi-agent-core/node";
1
2
  import { Text } from "@caupulican/pi-tui";
2
3
  import { Type } from "typebox";
3
4
  import { DEFAULT_RETRIEVAL_MAX_LINES, retrieveArtifactSlice, } from "../context/artifact-retrieval.js";
4
5
  import { invalidArgText, str } from "./render-utils.js";
5
6
  import { wrapToolDefinition } from "./tool-definition-wrapper.js";
6
- import { formatSize } from "./truncate.js";
7
7
  const ARTIFACT_ID_PREFIX = "tool-output:";
8
8
  const artifactRetrieveSchema = Type.Object({
9
9
  artifactId: Type.String({
@@ -1 +1 @@
1
- {"version":3,"file":"artifact-retrieve.js","sourceRoot":"","sources":["../../../src/core/tools/artifact-retrieve.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,IAAI,EAAE,MAAM,oBAAoB,CAAC;AAC1C,OAAO,EAAe,IAAI,EAAE,MAAM,SAAS,CAAC;AAE5C,OAAO,EAEN,2BAA2B,EAC3B,qBAAqB,GACrB,MAAM,kCA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AC,CAAC,CAAC,EAAE,CAAC;YACtD,MAAM,YAAY,GAAG,KAAK,CAAC,KAAK,CAAC,CAAC,EAAE,QAAQ,CAAC,CAAC;YAC9C,MAAM,SAAS,GAAG,KAAK,CAAC,MAAM,GAAG,QAAQ,CAAC;YAC1C,IAAI,QAAQ,GAAG,YAAY,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,KAAK,CAAC,EAAE,CAAC,YAAY,EAAE,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;YACnF,IAAI,SAAS,GAAG,CAAC;gBAAE,QAAQ,IAAI,KAAK,KAAK,CAAC,EAAE,CAAC,OAAO,EAAE,QAAQ,SAAS,cAAc,CAAC,EAAE,CAAC;YACzF,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC;YACvB,OAAO,IAAI,CAAC;QAAA,CACZ;KACD,CAAC;AAAA,CACF;AAED,MAAM,UAAU,0BAA0B,CACzC,GAAW,EACX,OAAqC,EACM;IAC3C,OAAO,kBAAkB,CAAC,oCAAoC,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC,CAAC;AAAA,CAC9E","sourcesContent":["import type { AgentTool } from \"@caupulican/pi-agent-core\";\nimport { Text } from \"@caupulican/pi-tui\";\nimport { type Static, Type } from \"typebox\";\nimport type { Theme } from \"../../modes/interactive/theme/theme.ts\";\nimport {\n\ttype ArtifactRetrievalMode,\n\tDEFAULT_RETRIEVAL_MAX_LINES,\n\tretrieveArtifactSlice,\n} from \"../context/artifact-retrieval.ts\";\nimport type { ArtifactStore } from \"../context/context-artifacts.ts\";\nimport type { ToolDefinition } from \"../extensions/types.ts\";\nimport { invalidArgText, str } from \"./render-utils.ts\";\nimport { wrapToolDefinition } from \"./tool-definition-wrapper.ts\";\nimport { formatSize } from \"./truncate.ts\";\n\nconst ARTIFACT_ID_PREFIX = \"tool-output:\";\n\nconst artifactRetrieveSchema = Type.Object({\n\tartifactId: Type.String({\n\t\tdescription:\n\t\t\t\"Artifact id from a 'Full output: artifact tool-output:<id>' reference in a prior tool result. The 'tool-output:' prefix is optional.\",\n\t}),\n\tmode: Type.Optional(\n\t\tType.Union([Type.Literal(\"metadata\"), Type.Literal(\"head\"), Type.Literal(\"tail\")], {\n\t\t\tdescription:\n\t\t\t\t\"'metadata' for tool/path/size info only (no content); 'head' (default) for the first lines; 'tail' for the last lines.\",\n\t\t}),\n\t),\n\tmaxLines: Type.Optional(\n\t\tType.Number({ description: `Maximum lines to return for head/tail (default: ${DEFAULT_RETRIEVAL_MAX_LINES})` }),\n\t),\n});\n\nexport type ArtifactRetrieveToolInput = Static<typeof artifactRetrieveSchema>;\n\nexport interface ArtifactRetrieveToolDetails {\n\tfound: boolean;\n\tmode: ArtifactRetrievalMode;\n}\n\nexport interface ArtifactRetrieveToolOptions {\n\t/** Session-scoped artifact store to resolve ids against. Omitted: the tool reports unavailable. */\n\tartifactStore?: ArtifactStore;\n}\n\nfunction normalizeArtifactId(input: string): string {\n\treturn input.startsWith(ARTIFACT_ID_PREFIX) ? input.slice(ARTIFACT_ID_PREFIX.length) : input;\n}\n\nfunction formatMetadataText(ref: {\n\tkind: string;\n\ttoolName?: string;\n\tcommand?: string;\n\tpath?: string;\n\tbyteLength: number;\n\tlineCount?: number;\n\treproducible: boolean;\n}): string {\n\tconst lines = [\n\t\t`kind: ${ref.kind}`,\n\t\tref.toolName ? `tool: ${ref.toolName}` : undefined,\n\t\tref.command ? `command: ${ref.command}` : undefined,\n\t\tref.path ? `path: ${ref.path}` : undefined,\n\t\t`size: ${formatSize(ref.byteLength)}`,\n\t\tref.lineCount !== undefined ? `lines: ${ref.lineCount}` : undefined,\n\t\t`reproducible: ${ref.reproducible}`,\n\t];\n\treturn lines.filter((line): line is string => line !== undefined).join(\"\\n\");\n}\n\nfunction formatCall(args: { artifactId: string; mode?: string } | undefined, theme: Theme): string {\n\tconst artifactId = str(args?.artifactId);\n\tconst mode = args?.mode ?? \"head\";\n\tconst idText = artifactId === null ? invalidArgText(theme) : theme.fg(\"accent\", artifactId);\n\treturn `${theme.fg(\"toolTitle\", theme.bold(\"artifact_retrieve\"))} ${idText}${theme.fg(\"toolOutput\", ` (${mode})`)}`;\n}\n\nexport function createArtifactRetrieveToolDefinition(\n\t_cwd: string,\n\toptions?: ArtifactRetrieveToolOptions,\n): ToolDefinition<typeof artifactRetrieveSchema, ArtifactRetrieveToolDetails | undefined> {\n\tconst artifactStore = options?.artifactStore;\n\treturn {\n\t\tname: \"artifact_retrieve\",\n\t\tlabel: \"artifact_retrieve\",\n\t\tdescription:\n\t\t\t\"Retrieve a bounded slice of a packed tool-output artifact by id, from a 'Full output: artifact tool-output:<id>' reference in a prior tool result. Returns metadata, or a bounded head/tail slice -- never the full raw payload in one call.\",\n\t\tpromptSnippet: \"Retrieve a bounded slice of a packed tool-output artifact\",\n\t\tparameters: artifactRetrieveSchema,\n\t\ttoolGroup: \"explore\",\n\t\tasync execute(\n\t\t\t_toolCallId,\n\t\t\t{ artifactId, mode, maxLines }: { artifactId: string; mode?: ArtifactRetrievalMode; maxLines?: number },\n\t\t) {\n\t\t\tconst effectiveMode = mode ?? \"head\";\n\t\t\tif (!artifactStore) {\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [{ type: \"text\", text: \"No artifact store is configured for this session.\" }],\n\t\t\t\t\tdetails: { found: false, mode: effectiveMode },\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tconst result = retrieveArtifactSlice(artifactStore, {\n\t\t\t\tartifactId: normalizeArtifactId(artifactId),\n\t\t\t\tmode,\n\t\t\t\tmaxLines,\n\t\t\t});\n\n\t\t\tif (!result.found) {\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\ttext: `Artifact not found: ${artifactId} (${result.missingReason}). It may have been cleaned up, or the id may be incorrect.`,\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t\tdetails: { found: false, mode: effectiveMode },\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tif (result.mode === \"metadata\") {\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [{ type: \"text\", text: formatMetadataText(result.ref) }],\n\t\t\t\t\tdetails: { found: true, mode: \"metadata\" },\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tlet text = result.slice;\n\t\t\tif (result.truncation.truncated) {\n\t\t\t\ttext += `\\n\\n[Showing ${result.mode} ${result.truncation.outputLines} of ${result.truncation.totalLines} lines. Full artifact: ${formatSize(result.ref.byteLength)}. Retrieve again with a different mode/maxLines for another slice.]`;\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tcontent: [{ type: \"text\", text }],\n\t\t\t\tdetails: { found: true, mode: result.mode },\n\t\t\t};\n\t\t},\n\t\trenderCall(args, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(formatCall(args, theme));\n\t\t\treturn text;\n\t\t},\n\t\trenderResult(result, options, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\tconst content = result.content.find((part) => part.type === \"text\");\n\t\t\tconst body = content && \"text\" in content ? content.text : \"\";\n\t\t\tconst lines = body.split(\"\\n\");\n\t\t\tconst maxLines = options.expanded ? lines.length : 20;\n\t\t\tconst displayLines = lines.slice(0, maxLines);\n\t\t\tconst remaining = lines.length - maxLines;\n\t\t\tlet rendered = displayLines.map((line) => theme.fg(\"toolOutput\", line)).join(\"\\n\");\n\t\t\tif (remaining > 0) rendered += `\\n${theme.fg(\"muted\", `... (${remaining} more lines)`)}`;\n\t\t\ttext.setText(rendered);\n\t\t\treturn text;\n\t\t},\n\t};\n}\n\nexport function createArtifactRetrieveTool(\n\tcwd: string,\n\toptions?: ArtifactRetrieveToolOptions,\n): AgentTool<typeof artifactRetrieveSchema> {\n\treturn wrapToolDefinition(createArtifactRetrieveToolDefinition(cwd, options));\n}\n"]}
1
+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IAAI,MAAM,IAAI,OAAO,CAAC,CAAC,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC;YAC9D,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;YAC/B,MAAM,QAAQ,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC;YACtD,MAAM,YAAY,GAAG,KAAK,CAAC,KAAK,CAAC,CAAC,EAAE,QAAQ,CAAC,CAAC;YAC9C,MAAM,SAAS,GAAG,KAAK,CAAC,MAAM,GAAG,QAAQ,CAAC;YAC1C,IAAI,QAAQ,GAAG,YAAY,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,KAAK,CAAC,EAAE,CAAC,YAAY,EAAE,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;YACnF,IAAI,SAAS,GAAG,CAAC;gBAAE,QAAQ,IAAI,KAAK,KAAK,CAAC,EAAE,CAAC,OAAO,EAAE,QAAQ,SAAS,cAAc,CAAC,EAAE,CAAC;YACzF,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC;YACvB,OAAO,IAAI,CAAC;QAAA,CACZ;KACD,CAAC;AAAA,CACF;AAED,MAAM,UAAU,0BAA0B,CACzC,GAAW,EACX,OAAqC,EACM;IAC3C,OAAO,kBAAkB,CAAC,oCAAoC,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC,CAAC;AAAA,CAC9E","sourcesContent":["import type { AgentTool } from \"@caupulican/pi-agent-core\";\nimport { formatSize } from \"@caupulican/pi-agent-core/node\";\nimport { Text } from \"@caupulican/pi-tui\";\nimport { type Static, Type } from \"typebox\";\nimport type { Theme } from \"../../modes/interactive/theme/theme.ts\";\nimport {\n\ttype ArtifactRetrievalMode,\n\tDEFAULT_RETRIEVAL_MAX_LINES,\n\tretrieveArtifactSlice,\n} from \"../context/artifact-retrieval.ts\";\nimport type { ArtifactStore } from \"../context/context-artifacts.ts\";\nimport type { ToolDefinition } from \"../extensions/types.ts\";\nimport { invalidArgText, str } from \"./render-utils.ts\";\nimport { wrapToolDefinition } from \"./tool-definition-wrapper.ts\";\n\nconst ARTIFACT_ID_PREFIX = \"tool-output:\";\n\nconst artifactRetrieveSchema = Type.Object({\n\tartifactId: Type.String({\n\t\tdescription:\n\t\t\t\"Artifact id from a 'Full output: artifact tool-output:<id>' reference in a prior tool result. The 'tool-output:' prefix is optional.\",\n\t}),\n\tmode: Type.Optional(\n\t\tType.Union([Type.Literal(\"metadata\"), Type.Literal(\"head\"), Type.Literal(\"tail\")], {\n\t\t\tdescription:\n\t\t\t\t\"'metadata' for tool/path/size info only (no content); 'head' (default) for the first lines; 'tail' for the last lines.\",\n\t\t}),\n\t),\n\tmaxLines: Type.Optional(\n\t\tType.Number({ description: `Maximum lines to return for head/tail (default: ${DEFAULT_RETRIEVAL_MAX_LINES})` }),\n\t),\n});\n\nexport type ArtifactRetrieveToolInput = Static<typeof artifactRetrieveSchema>;\n\nexport interface ArtifactRetrieveToolDetails {\n\tfound: boolean;\n\tmode: ArtifactRetrievalMode;\n}\n\nexport interface ArtifactRetrieveToolOptions {\n\t/** Session-scoped artifact store to resolve ids against. Omitted: the tool reports unavailable. */\n\tartifactStore?: ArtifactStore;\n}\n\nfunction normalizeArtifactId(input: string): string {\n\treturn input.startsWith(ARTIFACT_ID_PREFIX) ? input.slice(ARTIFACT_ID_PREFIX.length) : input;\n}\n\nfunction formatMetadataText(ref: {\n\tkind: string;\n\ttoolName?: string;\n\tcommand?: string;\n\tpath?: string;\n\tbyteLength: number;\n\tlineCount?: number;\n\treproducible: boolean;\n}): string {\n\tconst lines = [\n\t\t`kind: ${ref.kind}`,\n\t\tref.toolName ? `tool: ${ref.toolName}` : undefined,\n\t\tref.command ? `command: ${ref.command}` : undefined,\n\t\tref.path ? `path: ${ref.path}` : undefined,\n\t\t`size: ${formatSize(ref.byteLength)}`,\n\t\tref.lineCount !== undefined ? `lines: ${ref.lineCount}` : undefined,\n\t\t`reproducible: ${ref.reproducible}`,\n\t];\n\treturn lines.filter((line): line is string => line !== undefined).join(\"\\n\");\n}\n\nfunction formatCall(args: { artifactId: string; mode?: string } | undefined, theme: Theme): string {\n\tconst artifactId = str(args?.artifactId);\n\tconst mode = args?.mode ?? \"head\";\n\tconst idText = artifactId === null ? invalidArgText(theme) : theme.fg(\"accent\", artifactId);\n\treturn `${theme.fg(\"toolTitle\", theme.bold(\"artifact_retrieve\"))} ${idText}${theme.fg(\"toolOutput\", ` (${mode})`)}`;\n}\n\nexport function createArtifactRetrieveToolDefinition(\n\t_cwd: string,\n\toptions?: ArtifactRetrieveToolOptions,\n): ToolDefinition<typeof artifactRetrieveSchema, ArtifactRetrieveToolDetails | undefined> {\n\tconst artifactStore = options?.artifactStore;\n\treturn {\n\t\tname: \"artifact_retrieve\",\n\t\tlabel: \"artifact_retrieve\",\n\t\tdescription:\n\t\t\t\"Retrieve a bounded slice of a packed tool-output artifact by id, from a 'Full output: artifact tool-output:<id>' reference in a prior tool result. Returns metadata, or a bounded head/tail slice -- never the full raw payload in one call.\",\n\t\tpromptSnippet: \"Retrieve a bounded slice of a packed tool-output artifact\",\n\t\tparameters: artifactRetrieveSchema,\n\t\ttoolGroup: \"explore\",\n\t\tasync execute(\n\t\t\t_toolCallId,\n\t\t\t{ artifactId, mode, maxLines }: { artifactId: string; mode?: ArtifactRetrievalMode; maxLines?: number },\n\t\t) {\n\t\t\tconst effectiveMode = mode ?? \"head\";\n\t\t\tif (!artifactStore) {\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [{ type: \"text\", text: \"No artifact store is configured for this session.\" }],\n\t\t\t\t\tdetails: { found: false, mode: effectiveMode },\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tconst result = retrieveArtifactSlice(artifactStore, {\n\t\t\t\tartifactId: normalizeArtifactId(artifactId),\n\t\t\t\tmode,\n\t\t\t\tmaxLines,\n\t\t\t});\n\n\t\t\tif (!result.found) {\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\ttext: `Artifact not found: ${artifactId} (${result.missingReason}). It may have been cleaned up, or the id may be incorrect.`,\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t\tdetails: { found: false, mode: effectiveMode },\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tif (result.mode === \"metadata\") {\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [{ type: \"text\", text: formatMetadataText(result.ref) }],\n\t\t\t\t\tdetails: { found: true, mode: \"metadata\" },\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tlet text = result.slice;\n\t\t\tif (result.truncation.truncated) {\n\t\t\t\ttext += `\\n\\n[Showing ${result.mode} ${result.truncation.outputLines} of ${result.truncation.totalLines} lines. Full artifact: ${formatSize(result.ref.byteLength)}. Retrieve again with a different mode/maxLines for another slice.]`;\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tcontent: [{ type: \"text\", text }],\n\t\t\t\tdetails: { found: true, mode: result.mode },\n\t\t\t};\n\t\t},\n\t\trenderCall(args, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(formatCall(args, theme));\n\t\t\treturn text;\n\t\t},\n\t\trenderResult(result, options, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\tconst content = result.content.find((part) => part.type === \"text\");\n\t\t\tconst body = content && \"text\" in content ? content.text : \"\";\n\t\t\tconst lines = body.split(\"\\n\");\n\t\t\tconst maxLines = options.expanded ? lines.length : 20;\n\t\t\tconst displayLines = lines.slice(0, maxLines);\n\t\t\tconst remaining = lines.length - maxLines;\n\t\t\tlet rendered = displayLines.map((line) => theme.fg(\"toolOutput\", line)).join(\"\\n\");\n\t\t\tif (remaining > 0) rendered += `\\n${theme.fg(\"muted\", `... (${remaining} more lines)`)}`;\n\t\t\ttext.setText(rendered);\n\t\t\treturn text;\n\t\t},\n\t};\n}\n\nexport function createArtifactRetrieveTool(\n\tcwd: string,\n\toptions?: ArtifactRetrieveToolOptions,\n): AgentTool<typeof artifactRetrieveSchema> {\n\treturn wrapToolDefinition(createArtifactRetrieveToolDefinition(cwd, options));\n}\n"]}
@@ -1,7 +1,9 @@
1
- import type { AgentTool } from "@caupulican/pi-agent-core";
1
+ import { type AgentTool } from "@caupulican/pi-agent-core";
2
+ import { type TruncationResult } from "@caupulican/pi-agent-core/node";
2
3
  import { type Static, Type } from "typebox";
3
4
  import type { ToolDefinition } from "../extensions/types.ts";
4
- import { type TruncationResult } from "./truncate.ts";
5
+ /** Test hook: override the silence threshold. Pass undefined to restore the default. */
6
+ export declare function setCommandSilenceMsForTests(ms: number | undefined): void;
5
7
  declare const bashSchema: Type.TObject<{
6
8
  command: Type.TString;
7
9
  timeout: Type.TOptional<Type.TNumber>;
@@ -1 +1 @@
1
- {"version":3,"file":"bash.d.ts","sourceRoot":"","sources":["../../../src/core/tools/bash.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,2BAA2B,CAAC;AAG3D,OAAO,EAAE,KAAK,MAAM,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAY5C,OAAO,KAAK,EAAE,cAAc,EAA2B,MAAM,wBAAwB,CAAC;AAKtF,OAAO,EAAoD,KAAK,gBAAgB,EAAE,MAAM,eAAe,CAAC;AAExG,QAAA,MAAM,UAAU;;;EAGd,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,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AgB,wBAAwB,CACvC,GAAG,EAAE,MAAM,EACX,OAAO,CAAC,EAAE,eAAe,GACvB,cAAc,CAAC,OAAO,UAAU,EAAE,eAAe,GAAG,SAAS,EAAE,eAAe,CAAC,CAmPjF;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 } from \"@caupulican/pi-agent-core\";\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 { 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\";\nimport { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, formatSize, type TruncationResult } from \"./truncate.ts\";\n\nconst bashSchema = Type.Object({\n\tcommand: Type.String({ description: \"Bash command to execute\" }),\n\ttimeout: Type.Optional(Type.Number({ description: \"Timeout in seconds (optional, no default timeout)\" })),\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\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\", onData);\n\t\t\t\tchild.stderr?.on(\"data\", onData);\n\t\t\t\t// Handle abort signal by killing the entire process tree.\n\t\t\t\tif (signal) {\n\t\t\t\t\tif (signal.aborted) onAbort();\n\t\t\t\t\telse signal.addEventListener(\"abort\", onAbort, { once: true });\n\t\t\t\t}\n\t\t\t\t// Handle shell spawn errors and wait for the process to terminate without hanging\n\t\t\t\t// on inherited stdio handles held by detached descendants.\n\t\t\t\tconst exitCode = await waitForChildProcess(child);\n\t\t\t\tif (signal?.aborted) {\n\t\t\t\t\tthrow new Error(\"aborted\");\n\t\t\t\t}\n\t\t\t\tif (timedOut) {\n\t\t\t\t\tthrow new Error(`timeout:${timeout}`);\n\t\t\t\t}\n\t\t\t\treturn { exitCode };\n\t\t\t} finally {\n\t\t\t\tif (child.pid) untrackDetachedChildPid(child.pid);\n\t\t\t\tif (timeoutHandle) clearTimeout(timeoutHandle);\n\t\t\t\tif (signal) signal.removeEventListener(\"abort\", onAbort);\n\t\t\t}\n\t\t},\n\t};\n}\n\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\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);\n\t\t\t\t\tfor (const entry of entries) {\n\t\t\t\t\t\tconst full = resolvePath(dir, entry);\n\t\t\t\t\t\tconst entryStat = await fsStat(full);\n\t\t\t\t\t\tif (entryStat.isDirectory()) {\n\t\t\t\t\t\t\tresults.push(full);\n\t\t\t\t\t\t\tresults = results.concat(await walk(full));\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tresults.push(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.`,\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\tconst result = await ops.exec(spawnContext.command, spawnContext.cwd, {\n\t\t\t\t\t\tonData: handleData,\n\t\t\t\t\t\tsignal,\n\t\t\t\t\t\ttimeout,\n\t\t\t\t\t\tenv: spawnContext.env,\n\t\t\t\t\t});\n\t\t\t\t\texitCode = result.exitCode;\n\t\t\t\t} 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\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,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E,gBAAgB,KAAK,gBAAgB,CAAC;AAO5E,MAAM,WAAW,eAAe;IAC/B,oEAAoE;IACpE,UAAU,CAAC,EAAE,cAAc,CAAC;IAC5B,mFAAmF;IACnF,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,iDAAiD;IACjD,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,2DAA2D;IAC3D,SAAS,CAAC,EAAE,aAAa,CAAC;CAC1B;AAMD,KAAK,eAAe,GAAG;IACtB,SAAS,EAAE,MAAM,GAAG,SAAS,CAAC;IAC9B,OAAO,EAAE,MAAM,GAAG,SAAS,CAAC;IAC5B,QAAQ,EAAE,MAAM,CAAC,OAAO,GAAG,SAAS,CAAC;CACrC,CAAC;AA0PF,wBAAgB,wBAAwB,CACvC,GAAG,EAAE,MAAM,EACX,OAAO,CAAC,EAAE,eAAe,GACvB,cAAc,CAAC,OAAO,UAAU,EAAE,eAAe,GAAG,SAAS,EAAE,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\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);\n\t\t\t\t\tfor (const entry of entries) {\n\t\t\t\t\t\tconst full = resolvePath(dir, entry);\n\t\t\t\t\t\tconst entryStat = await fsStat(full);\n\t\t\t\t\t\tif (entryStat.isDirectory()) {\n\t\t\t\t\t\t\tresults.push(full);\n\t\t\t\t\t\t\tresults = results.concat(await walk(full));\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tresults.push(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,6 +1,8 @@
1
1
  import { constants } from "node:fs";
2
2
  import { access as fsAccess, readdir as fsReaddir, readFile as fsReadFile, stat as fsStat } from "node:fs/promises";
3
3
  import { relative as relativePath, resolve as resolvePath } from "node:path";
4
+ import { createSilenceWatchdog } from "@caupulican/pi-agent-core";
5
+ import { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, formatSize, } from "@caupulican/pi-agent-core/node";
4
6
  import { Container, Text, truncateToWidth } from "@caupulican/pi-tui";
5
7
  import { spawn } from "child_process";
6
8
  import { Type } from "typebox";
@@ -9,14 +11,23 @@ import { truncateToVisualLines } from "../../modes/interactive/components/visual
9
11
  import { theme } from "../../modes/interactive/theme/theme.js";
10
12
  import { waitForChildProcess } from "../../utils/child-process.js";
11
13
  import { getShellConfig, getShellEnv, killProcessTree, trackDetachedChildPid, untrackDetachedChildPid, } from "../../utils/shell.js";
14
+ import { withExclusiveMutationBarrier } from "./file-mutation-queue.js";
12
15
  import { classifyGitCommand, executeFilteredGit } from "./git-filter.js";
13
16
  import { OutputAccumulator } from "./output-accumulator.js";
14
17
  import { getTextOutput, invalidArgText, str } from "./render-utils.js";
15
18
  import { wrapToolDefinition } from "./tool-definition-wrapper.js";
16
- import { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, formatSize } from "./truncate.js";
19
+ /** Default silence bound for foreground commands without an explicit timeout (spec §2: ~10 min). */
20
+ const DEFAULT_COMMAND_SILENCE_MS = 600_000;
21
+ let commandSilenceMsOverride;
22
+ /** Test hook: override the silence threshold. Pass undefined to restore the default. */
23
+ export function setCommandSilenceMsForTests(ms) {
24
+ commandSilenceMsOverride = ms;
25
+ }
17
26
  const bashSchema = Type.Object({
18
27
  command: Type.String({ description: "Bash command to execute" }),
19
- timeout: Type.Optional(Type.Number({ description: "Timeout in seconds (optional, no default timeout)" })),
28
+ timeout: Type.Optional(Type.Number({
29
+ description: "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.",
30
+ })),
20
31
  });
21
32
  /**
22
33
  * Create bash operations using pi's built-in local shell execution backend.
@@ -52,6 +63,26 @@ export function createLocalBashOperations(options) {
52
63
  if (child.pid)
53
64
  killProcessTree(child.pid);
54
65
  };
66
+ // A command that keeps producing output must never be killed by this mechanism:
67
+ // silence bounds mute-ness, not duration. It arms when the caller left `timeout`
68
+ // unset or non-positive (treated as unset) — an explicit positive timeout means
69
+ // the model took responsibility for the wall clock.
70
+ let silenceKilled = false;
71
+ const silenceMs = commandSilenceMsOverride ?? DEFAULT_COMMAND_SILENCE_MS;
72
+ const silenceWatchdog = (timeout === undefined || timeout <= 0) && silenceMs > 0
73
+ ? createSilenceWatchdog({
74
+ silenceMs,
75
+ onSilence: () => {
76
+ silenceKilled = true;
77
+ if (child.pid)
78
+ killProcessTree(child.pid);
79
+ },
80
+ })
81
+ : undefined;
82
+ const onChunk = (data) => {
83
+ silenceWatchdog?.touch();
84
+ onData(data);
85
+ };
55
86
  try {
56
87
  // Set timeout if provided.
57
88
  if (timeout !== undefined && timeout > 0) {
@@ -62,8 +93,8 @@ export function createLocalBashOperations(options) {
62
93
  }, timeout * 1000);
63
94
  }
64
95
  // Stream stdout and stderr.
65
- child.stdout?.on("data", onData);
66
- child.stderr?.on("data", onData);
96
+ child.stdout?.on("data", onChunk);
97
+ child.stderr?.on("data", onChunk);
67
98
  // Handle abort signal by killing the entire process tree.
68
99
  if (signal) {
69
100
  if (signal.aborted)
@@ -80,9 +111,13 @@ export function createLocalBashOperations(options) {
80
111
  if (timedOut) {
81
112
  throw new Error(`timeout:${timeout}`);
82
113
  }
114
+ if (silenceKilled) {
115
+ throw new Error(`silence:${silenceMs / 1000}`);
116
+ }
83
117
  return { exitCode };
84
118
  }
85
119
  finally {
120
+ silenceWatchdog?.disarm();
86
121
  if (child.pid)
87
122
  untrackDetachedChildPid(child.pid);
88
123
  if (timeoutHandle)
@@ -334,7 +369,7 @@ export function createBashToolDefinition(cwd, options) {
334
369
  return {
335
370
  name: "bash",
336
371
  label: "bash",
337
- description: `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.`,
372
+ description: `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 '&'.`,
338
373
  promptSnippet: "Execute bash commands (ls, grep, find, etc.)",
339
374
  parameters: bashSchema,
340
375
  async execute(_toolCallId, { command, timeout }, signal, onUpdate, _ctx) {
@@ -482,12 +517,15 @@ export function createBashToolDefinition(cwd, options) {
482
517
  }
483
518
  let exitCode;
484
519
  try {
485
- const result = await ops.exec(spawnContext.command, spawnContext.cwd, {
520
+ // Bash cannot statically declare which files a command mutates, so the
521
+ // actual shell execution takes the coarse exclusive barrier: it waits for
522
+ // in-flight edit/write mutations to drain and blocks new ones meanwhile.
523
+ const result = await withExclusiveMutationBarrier(() => ops.exec(spawnContext.command, spawnContext.cwd, {
486
524
  onData: handleData,
487
525
  signal,
488
526
  timeout,
489
527
  env: spawnContext.env,
490
- });
528
+ }));
491
529
  exitCode = result.exitCode;
492
530
  }
493
531
  catch (err) {
@@ -500,6 +538,10 @@ export function createBashToolDefinition(cwd, options) {
500
538
  const timeoutSecs = err.message.split(":")[1];
501
539
  throw new Error(appendStatus(text, `Command timed out after ${timeoutSecs} seconds`));
502
540
  }
541
+ if (err instanceof Error && err.message.startsWith("silence:")) {
542
+ const secs = err.message.split(":")[1];
543
+ throw new Error(appendStatus(text, `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 '&'.`));
544
+ }
503
545
  throw err;
504
546
  }
505
547
  const snapshot = await finishOutput();