@astralyn/pi 0.85.3 → 0.86.1

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 (335) hide show
  1. package/CHANGELOG.md +52 -0
  2. package/dist/bundle/chunks/anthropic-messages-R2LYJUDD.js +6 -0
  3. package/dist/bundle/chunks/azure-openai-responses-HS35BQV6.js +2 -0
  4. package/dist/bundle/chunks/bedrock-converse-stream.js +36 -32
  5. package/dist/bundle/chunks/{chunk-S2DJQQI2.js → chunk-2IO5GDBS.js} +10 -1
  6. package/dist/bundle/chunks/chunk-DAEM5JIZ.js +2 -0
  7. package/dist/bundle/chunks/{chunk-LB4P77SH.js → chunk-GTBMYBFG.js} +777 -762
  8. package/dist/bundle/chunks/{chunk-7LO5Z4WE.js → chunk-I5IVW2WS.js} +1 -1
  9. package/dist/bundle/chunks/chunk-JI4WGISU.js +2 -0
  10. package/dist/bundle/chunks/chunk-LPQCB2VJ.js +44 -0
  11. package/dist/bundle/chunks/chunk-NW5FIDD7.js +11 -0
  12. package/dist/bundle/chunks/chunk-PJVFYVHE.js +42 -0
  13. package/dist/bundle/chunks/github-copilot.js +1 -1
  14. package/dist/bundle/chunks/google-generative-ai-NOVAJBFC.js +2 -0
  15. package/dist/bundle/chunks/google-vertex-4VHCZJV5.js +2 -0
  16. package/dist/bundle/chunks/https-proxy-agent-JOOPB4RE.js +16 -0
  17. package/dist/bundle/chunks/jiti-loader-BFSSLU7G.js +21 -0
  18. package/dist/bundle/chunks/jiti-static-loader-CLT3YR3B.js +2 -0
  19. package/dist/bundle/chunks/mistral-conversations-WC6A2WCJ.js +5 -0
  20. package/dist/bundle/chunks/{node-G4XOIDPH.js → node-CXWYTK2I.js} +1 -1
  21. package/dist/bundle/chunks/openai-codex-responses-XCDG75W2.js +10 -0
  22. package/dist/bundle/chunks/openai-completions-6SMWQWQN.js +7 -0
  23. package/dist/bundle/chunks/openai-responses-UT6XFKC7.js +2 -0
  24. package/dist/bundle/chunks/{pi-messages-PE6B42TG.js → pi-messages-MQMPIPNC.js} +1 -1
  25. package/dist/bundle/chunks/virtual-modules-OHUZ2T7X.js +2 -0
  26. package/dist/bundle/cli.js +1 -1
  27. package/dist/bundle/index.js +1 -1
  28. package/dist/bundle/rpc-entry.js +1 -1
  29. package/dist/cli/args.d.ts.map +1 -1
  30. package/dist/cli/args.js +1 -0
  31. package/dist/cli/args.js.map +1 -1
  32. package/dist/cli/session-picker.d.ts +1 -1
  33. package/dist/cli/session-picker.d.ts.map +1 -1
  34. package/dist/cli/session-picker.js +13 -11
  35. package/dist/cli/session-picker.js.map +1 -1
  36. package/dist/config.js +1 -1
  37. package/dist/config.js.map +1 -1
  38. package/dist/core/agent-session.d.ts +56 -14
  39. package/dist/core/agent-session.d.ts.map +1 -1
  40. package/dist/core/agent-session.js +305 -176
  41. package/dist/core/agent-session.js.map +1 -1
  42. package/dist/core/bug-report-upload.d.ts +12 -0
  43. package/dist/core/bug-report-upload.d.ts.map +1 -0
  44. package/dist/core/bug-report-upload.js +22 -0
  45. package/dist/core/bug-report-upload.js.map +1 -0
  46. package/dist/core/bug-report.d.ts +176 -0
  47. package/dist/core/bug-report.d.ts.map +1 -0
  48. package/dist/core/bug-report.js +292 -0
  49. package/dist/core/bug-report.js.map +1 -0
  50. package/dist/core/cache-stats.d.ts.map +1 -1
  51. package/dist/core/cache-stats.js +12 -1
  52. package/dist/core/cache-stats.js.map +1 -1
  53. package/dist/core/cache-warmer.d.ts +102 -0
  54. package/dist/core/cache-warmer.d.ts.map +1 -0
  55. package/dist/core/cache-warmer.js +333 -0
  56. package/dist/core/cache-warmer.js.map +1 -0
  57. package/dist/core/compaction/branch-summarization.js +2 -2
  58. package/dist/core/compaction/branch-summarization.js.map +1 -1
  59. package/dist/core/compaction/compaction.d.ts +14 -9
  60. package/dist/core/compaction/compaction.d.ts.map +1 -1
  61. package/dist/core/compaction/compaction.js +30 -23
  62. package/dist/core/compaction/compaction.js.map +1 -1
  63. package/dist/core/compaction/settings.d.ts +17 -20
  64. package/dist/core/compaction/settings.d.ts.map +1 -1
  65. package/dist/core/compaction/settings.js +19 -26
  66. package/dist/core/compaction/settings.js.map +1 -1
  67. package/dist/core/context-snapshot.d.ts +16 -5
  68. package/dist/core/context-snapshot.d.ts.map +1 -1
  69. package/dist/core/context-snapshot.js +20 -10
  70. package/dist/core/context-snapshot.js.map +1 -1
  71. package/dist/core/crash-log.d.ts +22 -0
  72. package/dist/core/crash-log.d.ts.map +1 -0
  73. package/dist/core/crash-log.js +71 -0
  74. package/dist/core/crash-log.js.map +1 -0
  75. package/dist/core/experimental.d.ts +0 -4
  76. package/dist/core/experimental.d.ts.map +1 -1
  77. package/dist/core/experimental.js +0 -4
  78. package/dist/core/experimental.js.map +1 -1
  79. package/dist/core/extensions/index.d.ts +1 -1
  80. package/dist/core/extensions/index.d.ts.map +1 -1
  81. package/dist/core/extensions/index.js.map +1 -1
  82. package/dist/core/extensions/jiti-loader.d.ts +2 -0
  83. package/dist/core/extensions/jiti-loader.d.ts.map +1 -0
  84. package/dist/core/extensions/jiti-loader.js +4 -0
  85. package/dist/core/extensions/jiti-loader.js.map +1 -0
  86. package/dist/core/extensions/jiti-static-loader.d.ts +2 -0
  87. package/dist/core/extensions/jiti-static-loader.d.ts.map +1 -0
  88. package/dist/core/extensions/jiti-static-loader.js +4 -0
  89. package/dist/core/extensions/jiti-static-loader.js.map +1 -0
  90. package/dist/core/extensions/loader.d.ts.map +1 -1
  91. package/dist/core/extensions/loader.js +38 -51
  92. package/dist/core/extensions/loader.js.map +1 -1
  93. package/dist/core/extensions/runner.d.ts +10 -7
  94. package/dist/core/extensions/runner.d.ts.map +1 -1
  95. package/dist/core/extensions/runner.js +85 -67
  96. package/dist/core/extensions/runner.js.map +1 -1
  97. package/dist/core/extensions/types.d.ts +60 -50
  98. package/dist/core/extensions/types.d.ts.map +1 -1
  99. package/dist/core/extensions/types.js.map +1 -1
  100. package/dist/core/extensions/virtual-modules.d.ts +3 -0
  101. package/dist/core/extensions/virtual-modules.d.ts.map +1 -0
  102. package/dist/core/extensions/virtual-modules.js +39 -0
  103. package/dist/core/extensions/virtual-modules.js.map +1 -0
  104. package/dist/core/extensions/wrapper.d.ts.map +1 -1
  105. package/dist/core/extensions/wrapper.js +1 -20
  106. package/dist/core/extensions/wrapper.js.map +1 -1
  107. package/dist/core/index.d.ts +2 -1
  108. package/dist/core/index.d.ts.map +1 -1
  109. package/dist/core/index.js.map +1 -1
  110. package/dist/core/keybindings.d.ts +1 -1
  111. package/dist/core/keybindings.js +1 -1
  112. package/dist/core/keybindings.js.map +1 -1
  113. package/dist/core/messages.d.ts.map +1 -1
  114. package/dist/core/messages.js +1 -0
  115. package/dist/core/messages.js.map +1 -1
  116. package/dist/core/model-config.d.ts +101 -20
  117. package/dist/core/model-config.d.ts.map +1 -1
  118. package/dist/core/model-config.js +25 -18
  119. package/dist/core/model-config.js.map +1 -1
  120. package/dist/core/model-registry.d.ts +5 -1
  121. package/dist/core/model-registry.d.ts.map +1 -1
  122. package/dist/core/model-registry.js +8 -0
  123. package/dist/core/model-registry.js.map +1 -1
  124. package/dist/core/model-resolver.d.ts.map +1 -1
  125. package/dist/core/model-resolver.js +2 -1
  126. package/dist/core/model-resolver.js.map +1 -1
  127. package/dist/core/model-runtime.d.ts.map +1 -1
  128. package/dist/core/model-runtime.js +5 -3
  129. package/dist/core/model-runtime.js.map +1 -1
  130. package/dist/core/provider-composer.d.ts +3 -2
  131. package/dist/core/provider-composer.d.ts.map +1 -1
  132. package/dist/core/provider-composer.js +2 -0
  133. package/dist/core/provider-composer.js.map +1 -1
  134. package/dist/core/radius.d.ts +3 -0
  135. package/dist/core/radius.d.ts.map +1 -1
  136. package/dist/core/radius.js +6 -0
  137. package/dist/core/radius.js.map +1 -1
  138. package/dist/core/sdk.d.ts.map +1 -1
  139. package/dist/core/sdk.js +46 -18
  140. package/dist/core/sdk.js.map +1 -1
  141. package/dist/core/session-export.d.ts +6 -2
  142. package/dist/core/session-export.d.ts.map +1 -1
  143. package/dist/core/session-export.js +14 -13
  144. package/dist/core/session-export.js.map +1 -1
  145. package/dist/core/session-manager.d.ts +29 -6
  146. package/dist/core/session-manager.d.ts.map +1 -1
  147. package/dist/core/session-manager.js +159 -96
  148. package/dist/core/session-manager.js.map +1 -1
  149. package/dist/core/settings-manager.d.ts +31 -4
  150. package/dist/core/settings-manager.d.ts.map +1 -1
  151. package/dist/core/settings-manager.js +65 -8
  152. package/dist/core/settings-manager.js.map +1 -1
  153. package/dist/core/slash-commands.d.ts.map +1 -1
  154. package/dist/core/slash-commands.js +1 -0
  155. package/dist/core/slash-commands.js.map +1 -1
  156. package/dist/core/system-prompt.d.ts +49 -6
  157. package/dist/core/system-prompt.d.ts.map +1 -1
  158. package/dist/core/system-prompt.js +121 -92
  159. package/dist/core/system-prompt.js.map +1 -1
  160. package/dist/core/tools/bash.d.ts +2 -1
  161. package/dist/core/tools/bash.d.ts.map +1 -1
  162. package/dist/core/tools/bash.js +6 -3
  163. package/dist/core/tools/bash.js.map +1 -1
  164. package/dist/core/tools/edit.d.ts.map +1 -1
  165. package/dist/core/tools/edit.js +1 -2
  166. package/dist/core/tools/edit.js.map +1 -1
  167. package/dist/core/tools/read.d.ts.map +1 -1
  168. package/dist/core/tools/read.js +1 -2
  169. package/dist/core/tools/read.js.map +1 -1
  170. package/dist/core/tools/shell-execution.js +2 -2
  171. package/dist/core/tools/shell-execution.js.map +1 -1
  172. package/dist/core/tools/write.d.ts.map +1 -1
  173. package/dist/core/tools/write.js +1 -2
  174. package/dist/core/tools/write.js.map +1 -1
  175. package/dist/core/usage-totals.d.ts +1 -1
  176. package/dist/core/usage-totals.d.ts.map +1 -1
  177. package/dist/core/usage-totals.js +4 -1
  178. package/dist/core/usage-totals.js.map +1 -1
  179. package/dist/extensions/background/schema.d.ts +1 -1
  180. package/dist/extensions/btw/agent.d.ts.map +1 -1
  181. package/dist/extensions/btw/agent.js +3 -2
  182. package/dist/extensions/btw/agent.js.map +1 -1
  183. package/dist/extensions/llama/client.d.ts +2 -0
  184. package/dist/extensions/llama/client.d.ts.map +1 -1
  185. package/dist/extensions/llama/client.js +7 -3
  186. package/dist/extensions/llama/client.js.map +1 -1
  187. package/dist/extensions/llama/provider.d.ts.map +1 -1
  188. package/dist/extensions/llama/provider.js +20 -5
  189. package/dist/extensions/llama/provider.js.map +1 -1
  190. package/dist/extensions/provider/compat-fields.d.ts.map +1 -1
  191. package/dist/extensions/provider/compat-fields.js +5 -2
  192. package/dist/extensions/provider/compat-fields.js.map +1 -1
  193. package/dist/extensions/provider/ui/app.js +2 -2
  194. package/dist/extensions/provider/ui/app.js.map +1 -1
  195. package/dist/extensions/todo/schema.d.ts +1 -1
  196. package/dist/index.d.ts +3 -2
  197. package/dist/index.d.ts.map +1 -1
  198. package/dist/index.js.map +1 -1
  199. package/dist/main.d.ts.map +1 -1
  200. package/dist/main.js +13 -9
  201. package/dist/main.js.map +1 -1
  202. package/dist/migrations.d.ts.map +1 -1
  203. package/dist/migrations.js +2 -2
  204. package/dist/migrations.js.map +1 -1
  205. package/dist/modes/interactive/bug-report.d.ts +16 -0
  206. package/dist/modes/interactive/bug-report.d.ts.map +1 -0
  207. package/dist/modes/interactive/bug-report.js +206 -0
  208. package/dist/modes/interactive/bug-report.js.map +1 -0
  209. package/dist/modes/interactive/chat-viewport.js +1 -1
  210. package/dist/modes/interactive/chat-viewport.js.map +1 -1
  211. package/dist/modes/interactive/components/armin.d.ts.map +1 -1
  212. package/dist/modes/interactive/components/armin.js +0 -5
  213. package/dist/modes/interactive/components/armin.js.map +1 -1
  214. package/dist/modes/interactive/components/bash-execution.d.ts +0 -1
  215. package/dist/modes/interactive/components/bash-execution.d.ts.map +1 -1
  216. package/dist/modes/interactive/components/bash-execution.js +2 -3
  217. package/dist/modes/interactive/components/bash-execution.js.map +1 -1
  218. package/dist/modes/interactive/components/branch-summary-message.d.ts.map +1 -1
  219. package/dist/modes/interactive/components/branch-summary-message.js +12 -5
  220. package/dist/modes/interactive/components/branch-summary-message.js.map +1 -1
  221. package/dist/modes/interactive/components/compaction-summary-message.d.ts.map +1 -1
  222. package/dist/modes/interactive/components/compaction-summary-message.js +12 -5
  223. package/dist/modes/interactive/components/compaction-summary-message.js.map +1 -1
  224. package/dist/modes/interactive/components/countdown-timer.d.ts +6 -13
  225. package/dist/modes/interactive/components/countdown-timer.d.ts.map +1 -1
  226. package/dist/modes/interactive/components/countdown-timer.js +15 -51
  227. package/dist/modes/interactive/components/countdown-timer.js.map +1 -1
  228. package/dist/modes/interactive/components/custom-editor.d.ts +3 -3
  229. package/dist/modes/interactive/components/custom-editor.d.ts.map +1 -1
  230. package/dist/modes/interactive/components/custom-editor.js.map +1 -1
  231. package/dist/modes/interactive/components/extension-editor.d.ts +4 -1
  232. package/dist/modes/interactive/components/extension-editor.d.ts.map +1 -1
  233. package/dist/modes/interactive/components/extension-editor.js +7 -2
  234. package/dist/modes/interactive/components/extension-editor.js.map +1 -1
  235. package/dist/modes/interactive/components/extension-input.d.ts +2 -0
  236. package/dist/modes/interactive/components/extension-input.d.ts.map +1 -1
  237. package/dist/modes/interactive/components/extension-input.js +6 -0
  238. package/dist/modes/interactive/components/extension-input.js.map +1 -1
  239. package/dist/modes/interactive/components/extension-selector.d.ts +1 -2
  240. package/dist/modes/interactive/components/extension-selector.d.ts.map +1 -1
  241. package/dist/modes/interactive/components/extension-selector.js +4 -2
  242. package/dist/modes/interactive/components/extension-selector.js.map +1 -1
  243. package/dist/modes/interactive/components/session-selector.d.ts +5 -8
  244. package/dist/modes/interactive/components/session-selector.d.ts.map +1 -1
  245. package/dist/modes/interactive/components/session-selector.js +72 -95
  246. package/dist/modes/interactive/components/session-selector.js.map +1 -1
  247. package/dist/modes/interactive/components/settings-selector.d.ts +3 -1
  248. package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
  249. package/dist/modes/interactive/components/settings-selector.js +11 -0
  250. package/dist/modes/interactive/components/settings-selector.js.map +1 -1
  251. package/dist/modes/interactive/components/skill-invocation-message.d.ts.map +1 -1
  252. package/dist/modes/interactive/components/skill-invocation-message.js +11 -4
  253. package/dist/modes/interactive/components/skill-invocation-message.js.map +1 -1
  254. package/dist/modes/interactive/components/status-indicator.d.ts +2 -2
  255. package/dist/modes/interactive/components/status-indicator.d.ts.map +1 -1
  256. package/dist/modes/interactive/components/status-indicator.js +7 -7
  257. package/dist/modes/interactive/components/status-indicator.js.map +1 -1
  258. package/dist/modes/interactive/components/tool-chrome.d.ts.map +1 -1
  259. package/dist/modes/interactive/components/tool-chrome.js +4 -1
  260. package/dist/modes/interactive/components/tool-chrome.js.map +1 -1
  261. package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
  262. package/dist/modes/interactive/components/tool-execution.js +4 -3
  263. package/dist/modes/interactive/components/tool-execution.js.map +1 -1
  264. package/dist/modes/interactive/components/tree-selector.d.ts +1 -10
  265. package/dist/modes/interactive/components/tree-selector.d.ts.map +1 -1
  266. package/dist/modes/interactive/components/tree-selector.js +4 -51
  267. package/dist/modes/interactive/components/tree-selector.js.map +1 -1
  268. package/dist/modes/interactive/interactive-mode.d.ts +15 -2
  269. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  270. package/dist/modes/interactive/interactive-mode.js +234 -91
  271. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  272. package/dist/modes/interactive/session-share.d.ts +2 -0
  273. package/dist/modes/interactive/session-share.d.ts.map +1 -1
  274. package/dist/modes/interactive/session-share.js +8 -4
  275. package/dist/modes/interactive/session-share.js.map +1 -1
  276. package/dist/modes/interactive/tui-renderer.js +2 -2
  277. package/dist/modes/interactive/tui-renderer.js.map +1 -1
  278. package/dist/modes/rpc/rpc-mode.js +2 -2
  279. package/dist/modes/rpc/rpc-mode.js.map +1 -1
  280. package/dist/utils/clipboard-command.d.ts +7 -0
  281. package/dist/utils/clipboard-command.d.ts.map +1 -0
  282. package/dist/utils/clipboard-command.js +45 -0
  283. package/dist/utils/clipboard-command.js.map +1 -0
  284. package/dist/utils/clipboard-image.d.ts.map +1 -1
  285. package/dist/utils/clipboard-image.js +53 -81
  286. package/dist/utils/clipboard-image.js.map +1 -1
  287. package/dist/utils/clipboard.d.ts.map +1 -1
  288. package/dist/utils/clipboard.js +111 -121
  289. package/dist/utils/clipboard.js.map +1 -1
  290. package/dist/utils/wsl.d.ts +3 -0
  291. package/dist/utils/wsl.d.ts.map +1 -0
  292. package/dist/utils/wsl.js +15 -0
  293. package/dist/utils/wsl.js.map +1 -0
  294. package/dist/utils/zip.d.ts +7 -0
  295. package/dist/utils/zip.d.ts.map +1 -0
  296. package/dist/utils/zip.js +60 -0
  297. package/dist/utils/zip.js.map +1 -0
  298. package/docs/compaction.md +32 -11
  299. package/docs/custom-provider.md +19 -8
  300. package/docs/environment-variables.md +1 -0
  301. package/docs/extensions.md +50 -34
  302. package/docs/models.md +38 -3
  303. package/docs/providers.md +9 -1
  304. package/docs/sdk.md +4 -2
  305. package/docs/session-format.md +63 -24
  306. package/docs/sessions.md +28 -1
  307. package/docs/settings.md +58 -4
  308. package/docs/termux.md +0 -1
  309. package/docs/tui.md +2 -0
  310. package/docs/usage.md +1 -0
  311. package/examples/extensions/README.md +0 -1
  312. package/examples/extensions/custom-provider-anthropic/index.ts +18 -12
  313. package/examples/extensions/custom-provider-gitlab-duo/index.ts +2 -2
  314. package/examples/extensions/prompt-customizer.ts +19 -67
  315. package/npm-shrinkwrap.json +275 -1028
  316. package/package.json +17 -23
  317. package/dist/bundle/chunks/anthropic-messages-IHRRITCV.js +0 -6
  318. package/dist/bundle/chunks/azure-openai-responses-QXBIDYXO.js +0 -2
  319. package/dist/bundle/chunks/chunk-JSJPY26N.js +0 -2
  320. package/dist/bundle/chunks/chunk-KI6LC764.js +0 -42
  321. package/dist/bundle/chunks/chunk-OWESLY5T.js +0 -11
  322. package/dist/bundle/chunks/chunk-RRBI7OUG.js +0 -50
  323. package/dist/bundle/chunks/chunk-YZJWMPUI.js +0 -2
  324. package/dist/bundle/chunks/google-generative-ai-NBOR3IQR.js +0 -2
  325. package/dist/bundle/chunks/google-vertex-VTHX3SUB.js +0 -2
  326. package/dist/bundle/chunks/https-proxy-agent-2VXB7436.js +0 -13
  327. package/dist/bundle/chunks/mistral-conversations-NO4ANAA5.js +0 -5
  328. package/dist/bundle/chunks/openai-codex-responses-5S3T3HMA.js +0 -10
  329. package/dist/bundle/chunks/openai-completions-CXRRTRWE.js +0 -7
  330. package/dist/bundle/chunks/openai-responses-CV3MH6VP.js +0 -2
  331. package/dist/utils/clipboard-native.d.ts +0 -11
  332. package/dist/utils/clipboard-native.d.ts.map +0 -1
  333. package/dist/utils/clipboard-native.js +0 -20
  334. package/dist/utils/clipboard-native.js.map +0 -1
  335. package/examples/extensions/kimi-deferred-tools.ts +0 -61
@@ -1 +1 @@
1
- {"version":3,"file":"slash-commands.js","sourceRoot":"","sources":["../../src/core/slash-commands.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AAkBxC,MAAM,CAAC,MAAM,sBAAsB,GAAuC;IACzE,EAAE,IAAI,EAAE,UAAU,EAAE,WAAW,EAAE,oBAAoB,EAAE;IACvD,EAAE,IAAI,EAAE,OAAO,EAAE,WAAW,EAAE,kCAAkC,EAAE,YAAY,EAAE,kBAAkB,EAAE;IACpG,EAAE,IAAI,EAAE,MAAM,EAAE,WAAW,EAAE,yCAAyC,EAAE;IACxE,EAAE,IAAI,EAAE,UAAU,EAAE,WAAW,EAAE,oBAAoB,EAAE,YAAY,EAAE,SAAS,EAAE;IAChF,EAAE,IAAI,EAAE,eAAe,EAAE,WAAW,EAAE,0CAA0C,EAAE;IAClF,EAAE,IAAI,EAAE,QAAQ,EAAE,WAAW,EAAE,8DAA8D,EAAE;IAC/F,EAAE,IAAI,EAAE,QAAQ,EAAE,WAAW,EAAE,+CAA+C,EAAE;IAChF,EAAE,IAAI,EAAE,OAAO,EAAE,WAAW,EAAE,uCAAuC,EAAE;IACvE,EAAE,IAAI,EAAE,MAAM,EAAE,WAAW,EAAE,sCAAsC,EAAE;IACrE,EAAE,IAAI,EAAE,MAAM,EAAE,WAAW,EAAE,0BAA0B,EAAE;IACzD,EAAE,IAAI,EAAE,SAAS,EAAE,WAAW,EAAE,6BAA6B,EAAE;IAC/D,EAAE,IAAI,EAAE,WAAW,EAAE,WAAW,EAAE,wBAAwB,EAAE;IAC5D,EAAE,IAAI,EAAE,SAAS,EAAE,WAAW,EAAE,6BAA6B,EAAE;IAC/D,EAAE,IAAI,EAAE,MAAM,EAAE,WAAW,EAAE,gDAAgD,EAAE;IAC/E,EAAE,IAAI,EAAE,OAAO,EAAE,WAAW,EAAE,uDAAuD,EAAE;IACvF,EAAE,IAAI,EAAE,OAAO,EAAE,WAAW,EAAE,iDAAiD,EAAE;IACjF,EAAE,IAAI,EAAE,OAAO,EAAE,WAAW,EAAE,mCAAmC,EAAE,YAAY,EAAE,YAAY,EAAE;IAC/F,EAAE,IAAI,EAAE,QAAQ,EAAE,WAAW,EAAE,gCAAgC,EAAE;IACjE,EAAE,IAAI,EAAE,KAAK,EAAE,WAAW,EAAE,qBAAqB,EAAE;IACnD,EAAE,IAAI,EAAE,SAAS,EAAE,WAAW,EAAE,sCAAsC,EAAE;IACxE,EAAE,IAAI,EAAE,QAAQ,EAAE,WAAW,EAAE,4BAA4B,EAAE;IAC7D,EAAE,IAAI,EAAE,QAAQ,EAAE,WAAW,EAAE,4EAA4E,EAAE;IAC7G,EAAE,IAAI,EAAE,MAAM,EAAE,WAAW,EAAE,QAAQ,QAAQ,EAAE,EAAE;CACjD,CAAC","sourcesContent":["import { APP_NAME } from \"../config.ts\";\nimport type { SourceInfo } from \"./source-info.ts\";\n\nexport type SlashCommandSource = \"extension\" | \"prompt\" | \"skill\";\n\nexport interface SlashCommandInfo {\n\tname: string;\n\tdescription?: string;\n\tsource: SlashCommandSource;\n\tsourceInfo: SourceInfo;\n}\n\nexport interface BuiltinSlashCommand {\n\tname: string;\n\tdescription: string;\n\targumentHint?: string;\n}\n\nexport const BUILTIN_SLASH_COMMANDS: ReadonlyArray<BuiltinSlashCommand> = [\n\t{ name: \"settings\", description: \"Open settings menu\" },\n\t{ name: \"model\", description: \"Select model (opens selector UI)\", argumentHint: \"<provider/model>\" },\n\t{ name: \"tree\", description: \"Navigate session tree (switch branches)\" },\n\t{ name: \"thinking\", description: \"Set thinking level\", argumentHint: \"<level>\" },\n\t{ name: \"scoped-models\", description: \"Enable/disable models for Ctrl+P cycling\" },\n\t{ name: \"export\", description: \"Export session (HTML default, or specify path: .html/.jsonl)\" },\n\t{ name: \"import\", description: \"Import and resume a session from a JSONL file\" },\n\t{ name: \"share\", description: \"Share session as a secret GitHub gist\" },\n\t{ name: \"copy\", description: \"Copy last agent message to clipboard\" },\n\t{ name: \"name\", description: \"Set session display name\" },\n\t{ name: \"session\", description: \"Show session info and stats\" },\n\t{ name: \"changelog\", description: \"Show changelog entries\" },\n\t{ name: \"hotkeys\", description: \"Show all keyboard shortcuts\" },\n\t{ name: \"fork\", description: \"Create a new fork from a previous user message\" },\n\t{ name: \"clone\", description: \"Duplicate the current session at the current position\" },\n\t{ name: \"trust\", description: \"Save project trust decision for future sessions\" },\n\t{ name: \"login\", description: \"Configure provider authentication\", argumentHint: \"<provider>\" },\n\t{ name: \"logout\", description: \"Remove provider authentication\" },\n\t{ name: \"new\", description: \"Start a new session\" },\n\t{ name: \"compact\", description: \"Manually compact the session context\" },\n\t{ name: \"resume\", description: \"Resume a different session\" },\n\t{ name: \"reload\", description: \"Reload keybindings, extensions, skills, prompts, themes, and context files\" },\n\t{ name: \"quit\", description: `Quit ${APP_NAME}` },\n];\n"]}
1
+ {"version":3,"file":"slash-commands.js","sourceRoot":"","sources":["../../src/core/slash-commands.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AAkBxC,MAAM,CAAC,MAAM,sBAAsB,GAAuC;IACzE,EAAE,IAAI,EAAE,UAAU,EAAE,WAAW,EAAE,oBAAoB,EAAE;IACvD,EAAE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AAE,IAAI,EAAE,KAAK,EAAE,WAAW,EAAE,qBAAqB,EAAE;IACnD,EAAE,IAAI,EAAE,SAAS,EAAE,WAAW,EAAE,sCAAsC,EAAE;IACxE,EAAE,IAAI,EAAE,QAAQ,EAAE,WAAW,EAAE,4BAA4B,EAAE;IAC7D,EAAE,IAAI,EAAE,QAAQ,EAAE,WAAW,EAAE,4EAA4E,EAAE;IAC7G,EAAE,IAAI,EAAE,MAAM,EAAE,WAAW,EAAE,QAAQ,QAAQ,EAAE,EAAE;CACjD,CAAC","sourcesContent":["import { APP_NAME } from \"../config.ts\";\nimport type { SourceInfo } from \"./source-info.ts\";\n\nexport type SlashCommandSource = \"extension\" | \"prompt\" | \"skill\";\n\nexport interface SlashCommandInfo {\n\tname: string;\n\tdescription?: string;\n\tsource: SlashCommandSource;\n\tsourceInfo: SourceInfo;\n}\n\nexport interface BuiltinSlashCommand {\n\tname: string;\n\tdescription: string;\n\targumentHint?: string;\n}\n\nexport const BUILTIN_SLASH_COMMANDS: ReadonlyArray<BuiltinSlashCommand> = [\n\t{ name: \"settings\", description: \"Open settings menu\" },\n\t{ name: \"model\", description: \"Select model (opens selector UI)\", argumentHint: \"<provider/model>\" },\n\t{ name: \"tree\", description: \"Navigate session tree (switch branches)\" },\n\t{ name: \"thinking\", description: \"Set thinking level\", argumentHint: \"<level>\" },\n\t{ name: \"scoped-models\", description: \"Enable/disable models for Ctrl+P cycling\" },\n\t{ name: \"export\", description: \"Export session (HTML default, or specify path: .html/.jsonl)\" },\n\t{ name: \"import\", description: \"Import and resume a session from a JSONL file\" },\n\t{ name: \"share\", description: \"Share session as a secret GitHub gist\" },\n\t{ name: \"bug\", description: \"Report a bug to the Pi developers\", argumentHint: \"<description>\" },\n\t{ name: \"copy\", description: \"Copy last agent message to clipboard\" },\n\t{ name: \"name\", description: \"Set session display name\" },\n\t{ name: \"session\", description: \"Show session info and stats\" },\n\t{ name: \"changelog\", description: \"Show changelog entries\" },\n\t{ name: \"hotkeys\", description: \"Show all keyboard shortcuts\" },\n\t{ name: \"fork\", description: \"Create a new fork from a previous user message\" },\n\t{ name: \"clone\", description: \"Duplicate the current session at the current position\" },\n\t{ name: \"trust\", description: \"Save project trust decision for future sessions\" },\n\t{ name: \"login\", description: \"Configure provider authentication\", argumentHint: \"<provider>\" },\n\t{ name: \"logout\", description: \"Remove provider authentication\" },\n\t{ name: \"new\", description: \"Start a new session\" },\n\t{ name: \"compact\", description: \"Manually compact the session context\" },\n\t{ name: \"resume\", description: \"Resume a different session\" },\n\t{ name: \"reload\", description: \"Reload keybindings, extensions, skills, prompts, themes, and context files\" },\n\t{ name: \"quit\", description: `Quit ${APP_NAME}` },\n];\n"]}
@@ -3,16 +3,22 @@
3
3
  */
4
4
  import { type Skill } from "./skills.ts";
5
5
  export interface BuildSystemPromptOptions {
6
- /** Custom system prompt (replaces default). */
6
+ /** Custom system prompt (replaces the default prefix). */
7
7
  customPrompt?: string;
8
- /** Tools to include in prompt. Default: [read, bash, edit, write] */
8
+ /** Exact full prompt replacement set by a before_agent_start handler. */
9
+ forceSystemPrompt?: string;
10
+ /** Tools to include in prompt. Default: [read, bash, edit, write]. */
9
11
  selectedTools?: string[];
10
12
  /** Optional one-line tool snippets keyed by tool name. */
11
13
  toolSnippets?: Record<string, string>;
12
- /** Additional guideline bullets appended to the default system prompt guidelines. */
14
+ /** Guideline bullets contributed by each tool, keyed by tool name. */
15
+ toolGuidelines?: Record<string, string[]>;
16
+ /** Additional guideline bullets appended to the default system prompt rules. */
13
17
  promptGuidelines?: string[];
14
- /** Text to append to system prompt. */
18
+ /** Text appended from user configuration before project context, skills, and cwd. */
15
19
  appendSystemPrompt?: string;
20
+ /** Additional XML-wrapped prompt sections keyed by tag name. */
21
+ sections?: Record<string, string>;
16
22
  /** Working directory. */
17
23
  cwd: string;
18
24
  /** Pre-loaded context files. */
@@ -23,6 +29,43 @@ export interface BuildSystemPromptOptions {
23
29
  /** Pre-loaded skills. */
24
30
  skills?: Skill[];
25
31
  }
26
- /** Build the system prompt with tools, guidelines, and context */
27
- export declare function buildSystemPrompt(options: BuildSystemPromptOptions): string;
32
+ export type NormalizedBuildSystemPromptOptions = BuildSystemPromptOptions & {
33
+ selectedTools: string[];
34
+ toolSnippets: Record<string, string>;
35
+ toolGuidelines: Record<string, string[]>;
36
+ promptGuidelines: string[];
37
+ appendSystemPrompt: string;
38
+ sections: Record<string, string>;
39
+ contextFiles: Array<{
40
+ path: string;
41
+ content: string;
42
+ }>;
43
+ skills: Skill[];
44
+ };
45
+ /**
46
+ * Ordered system prompt sections, keyed by name. `preamble` is untagged text; every other
47
+ * section is wrapped in a tag of the same name so the model can match later updates to it.
48
+ * These become `SystemMessage.sections` in the transcript.
49
+ */
50
+ export type SystemPromptSections = Record<string, string>;
51
+ /** Normalize prompt input into the mutable, collection-complete shape exposed to extensions. */
52
+ export declare function normalizeBuildSystemPromptOptions(input: BuildSystemPromptOptions): NormalizedBuildSystemPromptOptions;
53
+ /** Build the ordered, independently replaceable sections of the structured system prompt. */
54
+ export declare function buildSystemPromptSections(input: BuildSystemPromptOptions): SystemPromptSections;
55
+ /**
56
+ * The complete prompt state for `input`. A forced prompt is opaque and lives in `content`
57
+ * with no sections; otherwise `content` is empty and the structured sections carry the prompt.
58
+ */
59
+ export declare function buildSystemPromptState(input: BuildSystemPromptOptions): {
60
+ content: string;
61
+ sections?: SystemPromptSections;
62
+ };
63
+ /** Build the system prompt text, rendered exactly as the transcript's system message replays it. */
64
+ export declare function buildSystemPrompt(input: BuildSystemPromptOptions): string;
65
+ /**
66
+ * Diff the sections the model currently has (replayed from the transcript, so never null)
67
+ * against the desired ones. Returns a `SystemMessage.sections` patch, or undefined when
68
+ * nothing changed.
69
+ */
70
+ export declare function diffSystemPromptSections(previous: Record<string, string | null>, current: SystemPromptSections): Record<string, string | null> | undefined;
28
71
  //# sourceMappingURL=system-prompt.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"system-prompt.d.ts","sourceRoot":"","sources":["../../src/core/system-prompt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wBAAgB,sBAAsB,CAAC,KAAK,EAAE,wBAAwB,GAAG;IACxE,OAAO,EAAE,MAAM,CAAC;IAChB,QAAQ,CAAC,EAAE,oBAAoB,CAAC;CAChC,CAGA;AAED,oGAAoG;AACpG,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,wBAAwB,GAAG,MAAM,CAEzE;AAED;;;;GAIG;AACH,wBAAgB,wBAAwB,CACvC,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC,EACvC,OAAO,EAAE,oBAAoB,GAC3B,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC,GAAG,SAAS,CAS3C"}
@@ -1,118 +1,147 @@
1
1
  /**
2
2
  * System prompt construction and project context loading
3
3
  */
4
+ import { getSystemMessageText } from "@earendil-works/pi-ai";
4
5
  import { getDocsPath, getExamplesPath, getReadmePath } from "../config.js";
5
6
  import { formatSkillsForPrompt } from "./skills.js";
6
- /** Build the system prompt with tools, guidelines, and context */
7
- export function buildSystemPrompt(options) {
8
- const { customPrompt, selectedTools, toolSnippets, promptGuidelines, appendSystemPrompt, cwd, contextFiles: providedContextFiles, skills: providedSkills, } = options;
9
- const promptCwd = cwd.replace(/\\/g, "/");
10
- const appendSection = appendSystemPrompt ? `\n\n${appendSystemPrompt}` : "";
11
- const contextFiles = providedContextFiles ?? [];
12
- const skills = providedSkills ?? [];
13
- const tools = selectedTools || ["read", "bash", "edit", "write"];
14
- const skillFileReadTool = ["read", "bash"].find((tool) => tools.includes(tool));
15
- if (customPrompt) {
16
- let prompt = customPrompt;
17
- if (appendSection) {
18
- prompt += appendSection;
19
- }
20
- // Append project context files
21
- if (contextFiles.length > 0) {
22
- prompt += "\n\n<project_context>\n\n";
23
- prompt += "Project-specific instructions and guidelines:\n\n";
24
- for (const { path: filePath, content } of contextFiles) {
25
- prompt += `<project_instructions path="${filePath}">\n${content}\n</project_instructions>\n\n`;
26
- }
27
- prompt += "</project_context>\n";
28
- }
29
- // Append skills when a tool capable of reading their files is available.
30
- if (skillFileReadTool && skills.length > 0) {
31
- prompt += formatSkillsForPrompt(skills, skillFileReadTool);
32
- }
33
- prompt += `\nCurrent working directory: ${promptCwd}\n`;
34
- return prompt;
35
- }
36
- // Get absolute paths to documentation and examples
37
- const readmePath = getReadmePath();
38
- const docsPath = getDocsPath();
39
- const examplesPath = getExamplesPath();
40
- // Build tools list based on selected tools.
41
- // A tool appears in Available tools only when the caller provides a one-line snippet.
42
- const visibleTools = tools.filter((name) => !!toolSnippets?.[name]);
43
- const toolsList = visibleTools.length > 0 ? visibleTools.map((name) => `- ${name}: ${toolSnippets[name]}`).join("\n") : "(none)";
44
- // Build guidelines based on which tools are actually available
45
- const guidelinesList = [];
46
- const guidelinesSet = new Set();
47
- const addGuideline = (guideline) => {
48
- if (guidelinesSet.has(guideline)) {
7
+ const SYSTEM_PROMPT_SECTION_NAME = /^[a-z][a-z0-9_-]*$/;
8
+ /** Normalize prompt input into the mutable, collection-complete shape exposed to extensions. */
9
+ export function normalizeBuildSystemPromptOptions(input) {
10
+ return {
11
+ customPrompt: input.customPrompt,
12
+ forceSystemPrompt: input.forceSystemPrompt,
13
+ selectedTools: [...(input.selectedTools ?? ["read", "bash", "edit", "write"])],
14
+ toolSnippets: { ...(input.toolSnippets ?? {}) },
15
+ toolGuidelines: Object.fromEntries(Object.entries(input.toolGuidelines ?? {}).map(([name, guidelines]) => [name, [...guidelines]])),
16
+ promptGuidelines: [...(input.promptGuidelines ?? [])],
17
+ appendSystemPrompt: input.appendSystemPrompt ?? "",
18
+ sections: { ...(input.sections ?? {}) },
19
+ cwd: input.cwd,
20
+ contextFiles: (input.contextFiles ?? []).map((file) => ({ ...file })),
21
+ skills: (input.skills ?? []).map((skill) => ({ ...skill })),
22
+ };
23
+ }
24
+ function renderProjectContext(contextFiles) {
25
+ return [
26
+ "Project-specific instructions and guidelines:",
27
+ ...contextFiles.map(({ path, content }) => `<project_instructions path="${path}">\n${content}\n</project_instructions>`),
28
+ ].join("\n\n");
29
+ }
30
+ function buildRules(selectedTools, toolGuidelines, promptGuidelines) {
31
+ const rules = [];
32
+ const seen = new Set();
33
+ const addRule = (rule) => {
34
+ const normalized = rule.trim();
35
+ if (!normalized || seen.has(normalized))
49
36
  return;
50
- }
51
- guidelinesSet.add(guideline);
52
- guidelinesList.push(guideline);
37
+ seen.add(normalized);
38
+ rules.push(normalized);
53
39
  };
54
- const hasBash = tools.includes("bash");
55
- const hasPowerShell = tools.includes("powershell");
56
- const hasGrep = tools.includes("grep");
57
- const hasFind = tools.includes("find");
58
- const hasLs = tools.includes("ls");
59
- // File exploration guidelines
40
+ const hasBash = selectedTools.includes("bash");
41
+ const hasPowerShell = selectedTools.includes("powershell");
42
+ const hasGrep = selectedTools.includes("grep");
43
+ const hasFind = selectedTools.includes("find");
44
+ const hasLs = selectedTools.includes("ls");
60
45
  if ((hasBash || hasPowerShell) && !hasGrep && !hasFind && !hasLs) {
61
46
  if (hasBash && hasPowerShell) {
62
- addGuideline("Use bash or PowerShell for file operations like listing, searching, and finding files");
47
+ addRule("Use bash or PowerShell for file operations like listing, searching, and finding files");
63
48
  }
64
49
  else if (hasPowerShell) {
65
- addGuideline("Use PowerShell for file operations like listing, searching, and finding files");
50
+ addRule("Use PowerShell for file operations like listing, searching, and finding files");
66
51
  }
67
52
  else {
68
- addGuideline("Use bash for file operations like ls, rg, find");
53
+ addRule("Use bash for file operations like ls, rg, find");
69
54
  }
70
55
  }
71
- for (const guideline of promptGuidelines ?? []) {
72
- const normalized = guideline.trim();
73
- if (normalized.length > 0) {
74
- addGuideline(normalized);
56
+ for (const name of selectedTools) {
57
+ for (const rule of toolGuidelines[name] ?? [])
58
+ addRule(rule);
59
+ }
60
+ for (const rule of promptGuidelines)
61
+ addRule(rule);
62
+ addRule("Be concise in your responses");
63
+ addRule("Show file paths clearly when working with files");
64
+ return rules.map((rule) => `- ${rule}`).join("\n");
65
+ }
66
+ /** Build the ordered, independently replaceable sections of the structured system prompt. */
67
+ export function buildSystemPromptSections(input) {
68
+ const options = normalizeBuildSystemPromptOptions(input);
69
+ const { customPrompt, selectedTools, toolSnippets, toolGuidelines, promptGuidelines, appendSystemPrompt, sections: customSections, cwd, contextFiles, skills, } = options;
70
+ for (const name of Object.keys(customSections)) {
71
+ if (!SYSTEM_PROMPT_SECTION_NAME.test(name) || name === "preamble") {
72
+ throw new Error(`Invalid system prompt section name: ${name}`);
75
73
  }
76
74
  }
77
- // Always include these
78
- addGuideline("Be concise in your responses");
79
- addGuideline("Show file paths clearly when working with files");
80
- const guidelines = guidelinesList.map((g) => `- ${g}`).join("\n");
81
- let prompt = `You are an expert coding assistant operating inside pi, a coding agent harness. You help users by reading files, executing commands, editing code, and writing new files.
82
-
83
- Available tools:
84
- ${toolsList}
85
-
86
- In addition to the tools above, you may have access to other custom tools depending on the project.
87
-
88
- Guidelines:
89
- ${guidelines}
90
-
91
- Pi documentation (read only when the user asks about pi itself, its SDK, extensions, themes, skills, or TUI):
92
- - Main documentation: ${readmePath}
93
- - Additional docs: ${docsPath}
94
- - Examples: ${examplesPath} (extensions, custom tools, SDK)
75
+ const promptSections = {};
76
+ if (customPrompt) {
77
+ promptSections.preamble = customPrompt;
78
+ }
79
+ else {
80
+ promptSections.preamble =
81
+ "You are an expert coding assistant operating inside pi, a coding agent harness. You help users by reading files, executing commands, editing code, and writing new files.";
82
+ const visibleTools = selectedTools.filter((name) => !!toolSnippets[name]);
83
+ const tools = visibleTools.length > 0 ? visibleTools.map((name) => `- ${name}: ${toolSnippets[name]}`).join("\n") : "(none)";
84
+ promptSections.tools = `${tools}\n\nIn addition to the tools above, you may have access to other custom tools depending on the project.`;
85
+ promptSections.rules = buildRules(selectedTools, toolGuidelines, promptGuidelines);
86
+ promptSections.docs = `Pi documentation (read only when the user asks about pi itself, its SDK, extensions, themes, skills, or TUI):
87
+ - Main documentation: ${getReadmePath()}
88
+ - Additional docs: ${getDocsPath()}
89
+ - Examples: ${getExamplesPath()} (extensions, custom tools, SDK)
95
90
  - When reading pi docs or examples, resolve docs/... under Additional docs and examples/... under Examples, not the current working directory
96
91
  - When asked about: extensions (docs/extensions.md, examples/extensions/), themes (docs/themes.md), skills (docs/skills.md), prompt templates (docs/prompt-templates.md), TUI components (docs/tui.md), keybindings (docs/keybindings.md), SDK integrations (docs/sdk.md), custom providers (docs/custom-provider.md), adding models (docs/models.md), pi packages (docs/packages.md), environment variables (docs/environment-variables.md)
97
92
  - When working on pi topics, read the docs and examples, and follow .md cross-references before implementing
98
93
  - Always read pi .md files completely and follow links to related docs (e.g., tui.md for TUI API details)`;
99
- if (appendSection) {
100
- prompt += appendSection;
101
94
  }
102
- // Append project context files
103
- if (contextFiles.length > 0) {
104
- prompt += "\n\n<project_context>\n\n";
105
- prompt += "Project-specific instructions and guidelines:\n\n";
106
- for (const { path: filePath, content } of contextFiles) {
107
- prompt += `<project_instructions path="${filePath}">\n${content}\n</project_instructions>\n\n`;
108
- }
109
- prompt += "</project_context>\n";
110
- }
111
- // Append skills when a tool capable of reading their files is available.
95
+ if (appendSystemPrompt)
96
+ promptSections.addendum = appendSystemPrompt;
97
+ if (contextFiles.length > 0)
98
+ promptSections.project_context = renderProjectContext(contextFiles);
99
+ const skillFileReadTool = ["read", "bash"].find((tool) => selectedTools.includes(tool));
112
100
  if (skillFileReadTool && skills.length > 0) {
113
- prompt += formatSkillsForPrompt(skills, skillFileReadTool);
101
+ const skillsPrompt = formatSkillsForPrompt(skills, skillFileReadTool).trim();
102
+ if (skillsPrompt)
103
+ promptSections.skills = skillsPrompt;
104
+ }
105
+ promptSections.cwd = cwd.replace(/\\/g, "/");
106
+ for (const [name, content] of Object.entries(customSections)) {
107
+ if (content)
108
+ promptSections[name] = content;
109
+ }
110
+ const sections = { preamble: promptSections.preamble };
111
+ for (const [name, content] of Object.entries(promptSections)) {
112
+ if (name !== "preamble")
113
+ sections[name] = `<${name}>\n${content}\n</${name}>`;
114
+ }
115
+ return sections;
116
+ }
117
+ /**
118
+ * The complete prompt state for `input`. A forced prompt is opaque and lives in `content`
119
+ * with no sections; otherwise `content` is empty and the structured sections carry the prompt.
120
+ */
121
+ export function buildSystemPromptState(input) {
122
+ if (input.forceSystemPrompt !== undefined)
123
+ return { content: input.forceSystemPrompt };
124
+ return { content: "", sections: buildSystemPromptSections(input) };
125
+ }
126
+ /** Build the system prompt text, rendered exactly as the transcript's system message replays it. */
127
+ export function buildSystemPrompt(input) {
128
+ return getSystemMessageText({ role: "system", ...buildSystemPromptState(input), timestamp: 0 });
129
+ }
130
+ /**
131
+ * Diff the sections the model currently has (replayed from the transcript, so never null)
132
+ * against the desired ones. Returns a `SystemMessage.sections` patch, or undefined when
133
+ * nothing changed.
134
+ */
135
+ export function diffSystemPromptSections(previous, current) {
136
+ const patch = {};
137
+ for (const [name, text] of Object.entries(current)) {
138
+ if (previous[name] !== text)
139
+ patch[name] = text;
140
+ }
141
+ for (const name of Object.keys(previous)) {
142
+ if (current[name] === undefined)
143
+ patch[name] = null;
114
144
  }
115
- prompt += `\nCurrent working directory: ${promptCwd}`;
116
- return prompt;
145
+ return Object.keys(patch).length > 0 ? patch : undefined;
117
146
  }
118
147
  //# sourceMappingURL=system-prompt.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"system-prompt.js","sourceRoot":"","sources":["../../src/core/system-prompt.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,WAAW,EAAE,eAAe,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAC3E,OAAO,EAAE,qBAAqB,EAAc,MAAM,aAAa,CAAC;AAqBhE,kEAAkE;AAClE,MAAM,UAAU,iBAAiB,CAAC,OAAiC;IAClE,MAAM,EACL,YAAY,EACZ,aAAa,EACb,YAAY,EACZ,gBAAgB,EAChB,kBAAkB,EAClB,GAAG,EACH,YAAY,EAAE,oBAAoB,EAClC,MAAM,EAAE,cAAc,GACtB,GAAG,OAAO,CAAC;IACZ,MAAM,SAAS,GAAG,GAAG,CAAC,OAAO,CAAC,KAAK,EAAE,GAAG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AAO,OAAO,+BAA+B,CAAC;QAChG,CAAC;QACD,MAAM,IAAI,sBAAsB,CAAC;IAClC,CAAC;IAED,yEAAyE;IACzE,IAAI,iBAAiB,IAAI,MAAM,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QAC5C,MAAM,IAAI,qBAAqB,CAAC,MAAM,EAAE,iBAAiB,CAAC,CAAC;IAC5D,CAAC;IAED,MAAM,IAAI,gCAAgC,SAAS,EAAE,CAAC;IAEtD,OAAO,MAAM,CAAC;AACf,CAAC","sourcesContent":["/**\n * System prompt construction and project context loading\n */\n\nimport { getDocsPath, getExamplesPath, getReadmePath } from \"../config.ts\";\nimport { formatSkillsForPrompt, type Skill } from \"./skills.ts\";\n\nexport interface BuildSystemPromptOptions {\n\t/** Custom system prompt (replaces default). */\n\tcustomPrompt?: string;\n\t/** Tools to include in prompt. Default: [read, bash, edit, write] */\n\tselectedTools?: string[];\n\t/** Optional one-line tool snippets keyed by tool name. */\n\ttoolSnippets?: Record<string, string>;\n\t/** Additional guideline bullets appended to the default system prompt guidelines. */\n\tpromptGuidelines?: string[];\n\t/** Text to append to system prompt. */\n\tappendSystemPrompt?: string;\n\t/** Working directory. */\n\tcwd: string;\n\t/** Pre-loaded context files. */\n\tcontextFiles?: Array<{ path: string; content: string }>;\n\t/** Pre-loaded skills. */\n\tskills?: Skill[];\n}\n\n/** Build the system prompt with tools, guidelines, and context */\nexport function buildSystemPrompt(options: BuildSystemPromptOptions): string {\n\tconst {\n\t\tcustomPrompt,\n\t\tselectedTools,\n\t\ttoolSnippets,\n\t\tpromptGuidelines,\n\t\tappendSystemPrompt,\n\t\tcwd,\n\t\tcontextFiles: providedContextFiles,\n\t\tskills: providedSkills,\n\t} = options;\n\tconst promptCwd = cwd.replace(/\\\\/g, \"/\");\n\n\tconst appendSection = appendSystemPrompt ? `\\n\\n${appendSystemPrompt}` : \"\";\n\n\tconst contextFiles = providedContextFiles ?? [];\n\tconst skills = providedSkills ?? [];\n\tconst tools = selectedTools || [\"read\", \"bash\", \"edit\", \"write\"];\n\tconst skillFileReadTool = ([\"read\", \"bash\"] as const).find((tool) => tools.includes(tool));\n\n\tif (customPrompt) {\n\t\tlet prompt = customPrompt;\n\n\t\tif (appendSection) {\n\t\t\tprompt += appendSection;\n\t\t}\n\n\t\t// Append project context files\n\t\tif (contextFiles.length > 0) {\n\t\t\tprompt += \"\\n\\n<project_context>\\n\\n\";\n\t\t\tprompt += \"Project-specific instructions and guidelines:\\n\\n\";\n\t\t\tfor (const { path: filePath, content } of contextFiles) {\n\t\t\t\tprompt += `<project_instructions path=\"${filePath}\">\\n${content}\\n</project_instructions>\\n\\n`;\n\t\t\t}\n\t\t\tprompt += \"</project_context>\\n\";\n\t\t}\n\n\t\t// Append skills when a tool capable of reading their files is available.\n\t\tif (skillFileReadTool && skills.length > 0) {\n\t\t\tprompt += formatSkillsForPrompt(skills, skillFileReadTool);\n\t\t}\n\n\t\tprompt += `\\nCurrent working directory: ${promptCwd}\\n`;\n\n\t\treturn prompt;\n\t}\n\n\t// Get absolute paths to documentation and examples\n\tconst readmePath = getReadmePath();\n\tconst docsPath = getDocsPath();\n\tconst examplesPath = getExamplesPath();\n\n\t// Build tools list based on selected tools.\n\t// A tool appears in Available tools only when the caller provides a one-line snippet.\n\tconst visibleTools = tools.filter((name) => !!toolSnippets?.[name]);\n\tconst toolsList =\n\t\tvisibleTools.length > 0 ? visibleTools.map((name) => `- ${name}: ${toolSnippets![name]}`).join(\"\\n\") : \"(none)\";\n\n\t// Build guidelines based on which tools are actually available\n\tconst guidelinesList: string[] = [];\n\tconst guidelinesSet = new Set<string>();\n\tconst addGuideline = (guideline: string): void => {\n\t\tif (guidelinesSet.has(guideline)) {\n\t\t\treturn;\n\t\t}\n\t\tguidelinesSet.add(guideline);\n\t\tguidelinesList.push(guideline);\n\t};\n\n\tconst hasBash = tools.includes(\"bash\");\n\tconst hasPowerShell = tools.includes(\"powershell\");\n\tconst hasGrep = tools.includes(\"grep\");\n\tconst hasFind = tools.includes(\"find\");\n\tconst hasLs = tools.includes(\"ls\");\n\n\t// File exploration guidelines\n\tif ((hasBash || hasPowerShell) && !hasGrep && !hasFind && !hasLs) {\n\t\tif (hasBash && hasPowerShell) {\n\t\t\taddGuideline(\"Use bash or PowerShell for file operations like listing, searching, and finding files\");\n\t\t} else if (hasPowerShell) {\n\t\t\taddGuideline(\"Use PowerShell for file operations like listing, searching, and finding files\");\n\t\t} else {\n\t\t\taddGuideline(\"Use bash for file operations like ls, rg, find\");\n\t\t}\n\t}\n\n\tfor (const guideline of promptGuidelines ?? []) {\n\t\tconst normalized = guideline.trim();\n\t\tif (normalized.length > 0) {\n\t\t\taddGuideline(normalized);\n\t\t}\n\t}\n\n\t// Always include these\n\taddGuideline(\"Be concise in your responses\");\n\taddGuideline(\"Show file paths clearly when working with files\");\n\n\tconst guidelines = guidelinesList.map((g) => `- ${g}`).join(\"\\n\");\n\n\tlet prompt = `You are an expert coding assistant operating inside pi, a coding agent harness. You help users by reading files, executing commands, editing code, and writing new files.\n\nAvailable tools:\n${toolsList}\n\nIn addition to the tools above, you may have access to other custom tools depending on the project.\n\nGuidelines:\n${guidelines}\n\nPi documentation (read only when the user asks about pi itself, its SDK, extensions, themes, skills, or TUI):\n- Main documentation: ${readmePath}\n- Additional docs: ${docsPath}\n- Examples: ${examplesPath} (extensions, custom tools, SDK)\n- When reading pi docs or examples, resolve docs/... under Additional docs and examples/... under Examples, not the current working directory\n- When asked about: extensions (docs/extensions.md, examples/extensions/), themes (docs/themes.md), skills (docs/skills.md), prompt templates (docs/prompt-templates.md), TUI components (docs/tui.md), keybindings (docs/keybindings.md), SDK integrations (docs/sdk.md), custom providers (docs/custom-provider.md), adding models (docs/models.md), pi packages (docs/packages.md), environment variables (docs/environment-variables.md)\n- When working on pi topics, read the docs and examples, and follow .md cross-references before implementing\n- Always read pi .md files completely and follow links to related docs (e.g., tui.md for TUI API details)`;\n\n\tif (appendSection) {\n\t\tprompt += appendSection;\n\t}\n\n\t// Append project context files\n\tif (contextFiles.length > 0) {\n\t\tprompt += \"\\n\\n<project_context>\\n\\n\";\n\t\tprompt += \"Project-specific instructions and guidelines:\\n\\n\";\n\t\tfor (const { path: filePath, content } of contextFiles) {\n\t\t\tprompt += `<project_instructions path=\"${filePath}\">\\n${content}\\n</project_instructions>\\n\\n`;\n\t\t}\n\t\tprompt += \"</project_context>\\n\";\n\t}\n\n\t// Append skills when a tool capable of reading their files is available.\n\tif (skillFileReadTool && skills.length > 0) {\n\t\tprompt += formatSkillsForPrompt(skills, skillFileReadTool);\n\t}\n\n\tprompt += `\\nCurrent working directory: ${promptCwd}`;\n\n\treturn prompt;\n}\n"]}
1
+ {"version":3,"file":"system-prompt.js","sourceRoot":"","sources":["../../src/core/system-prompt.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,oBAAoB,EAAE,MAAM,uBAAuB,CAAC;AAC7D,OAAO,EAAE,WAAW,EAAE,eAAe,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAC3E,OAAO,EAAE,qBAAqB,EAAc,MAAM,aAAa,CAAC;AA6ChE,MAAM,0BAA0B,GAAG,oBAAoB,CAAC;AACxD,gGAAgG;AAChG,MAAM,UAAU,iCAAiC,CAAC,KAA+B;IAChF,OAAO;QACN,YAAY,EAAE,KAAK,CAAC,YAAY;QAChC,iBAAiB,EAAE,KAAK,CAAC,iBAAiB;QAC1C,aAAa,EAAE,CAAC,GAAG,CAAC,KAAK,CAAC,aAAa,IAAI,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC;QAC9E,YAAY,EAAE,EAAE,GAAG,CAAC,KAAK,CAAC,YAAY,IAAI,EAAE,CAAC,EAAE;QAC/C,cAAc,EAAE,MAAM,CAAC,WAAW,CACjC,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,cAAc,IAAI,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,EAAE,UAAU,CAAC,EAAE,EAAE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IAAI,GAAG,CAAC;IAC/E,CAAC;IACD,OAAO,QAAQ,CAAC;AACjB,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,sBAAsB,CAAC,KAA+B;IAIrE,IAAI,KAAK,CAAC,iBAAiB,KAAK,SAAS;QAAE,OAAO,EAAE,OAAO,EAAE,KAAK,CAAC,iBAAiB,EAAE,CAAC;IACvF,OAAO,EAAE,OAAO,EAAE,EAAE,EAAE,QAAQ,EAAE,yBAAyB,CAAC,KAAK,CAAC,EAAE,CAAC;AACpE,CAAC;AAED,oGAAoG;AACpG,MAAM,UAAU,iBAAiB,CAAC,KAA+B;IAChE,OAAO,oBAAoB,CAAC,EAAE,IAAI,EAAE,QAAQ,EAAE,GAAG,sBAAsB,CAAC,KAAK,CAAC,EAAE,SAAS,EAAE,CAAC,EAAE,CAAC,CAAC;AACjG,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,wBAAwB,CACvC,QAAuC,EACvC,OAA6B;IAE7B,MAAM,KAAK,GAAkC,EAAE,CAAC;IAChD,KAAK,MAAM,CAAC,IAAI,EAAE,IAAI,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC;QACpD,IAAI,QAAQ,CAAC,IAAI,CAAC,KAAK,IAAI;YAAE,KAAK,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC;IACjD,CAAC;IACD,KAAK,MAAM,IAAI,IAAI,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC;QAC1C,IAAI,OAAO,CAAC,IAAI,CAAC,KAAK,SAAS;YAAE,KAAK,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC;IACrD,CAAC;IACD,OAAO,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS,CAAC;AAC1D,CAAC","sourcesContent":["/**\n * System prompt construction and project context loading\n */\n\nimport { getSystemMessageText } from \"@earendil-works/pi-ai\";\nimport { getDocsPath, getExamplesPath, getReadmePath } from \"../config.ts\";\nimport { formatSkillsForPrompt, type Skill } from \"./skills.ts\";\n\nexport interface BuildSystemPromptOptions {\n\t/** Custom system prompt (replaces the default prefix). */\n\tcustomPrompt?: string;\n\t/** Exact full prompt replacement set by a before_agent_start handler. */\n\tforceSystemPrompt?: string;\n\t/** Tools to include in prompt. Default: [read, bash, edit, write]. */\n\tselectedTools?: string[];\n\t/** Optional one-line tool snippets keyed by tool name. */\n\ttoolSnippets?: Record<string, string>;\n\t/** Guideline bullets contributed by each tool, keyed by tool name. */\n\ttoolGuidelines?: Record<string, string[]>;\n\t/** Additional guideline bullets appended to the default system prompt rules. */\n\tpromptGuidelines?: string[];\n\t/** Text appended from user configuration before project context, skills, and cwd. */\n\tappendSystemPrompt?: string;\n\t/** Additional XML-wrapped prompt sections keyed by tag name. */\n\tsections?: Record<string, string>;\n\t/** Working directory. */\n\tcwd: string;\n\t/** Pre-loaded context files. */\n\tcontextFiles?: Array<{ path: string; content: string }>;\n\t/** Pre-loaded skills. */\n\tskills?: Skill[];\n}\n\nexport type NormalizedBuildSystemPromptOptions = BuildSystemPromptOptions & {\n\tselectedTools: string[];\n\ttoolSnippets: Record<string, string>;\n\ttoolGuidelines: Record<string, string[]>;\n\tpromptGuidelines: string[];\n\tappendSystemPrompt: string;\n\tsections: Record<string, string>;\n\tcontextFiles: Array<{ path: string; content: string }>;\n\tskills: Skill[];\n};\n\n/**\n * Ordered system prompt sections, keyed by name. `preamble` is untagged text; every other\n * section is wrapped in a tag of the same name so the model can match later updates to it.\n * These become `SystemMessage.sections` in the transcript.\n */\nexport type SystemPromptSections = Record<string, string>;\n\nconst SYSTEM_PROMPT_SECTION_NAME = /^[a-z][a-z0-9_-]*$/;\n/** Normalize prompt input into the mutable, collection-complete shape exposed to extensions. */\nexport function normalizeBuildSystemPromptOptions(input: BuildSystemPromptOptions): NormalizedBuildSystemPromptOptions {\n\treturn {\n\t\tcustomPrompt: input.customPrompt,\n\t\tforceSystemPrompt: input.forceSystemPrompt,\n\t\tselectedTools: [...(input.selectedTools ?? [\"read\", \"bash\", \"edit\", \"write\"])],\n\t\ttoolSnippets: { ...(input.toolSnippets ?? {}) },\n\t\ttoolGuidelines: Object.fromEntries(\n\t\t\tObject.entries(input.toolGuidelines ?? {}).map(([name, guidelines]) => [name, [...guidelines]]),\n\t\t),\n\t\tpromptGuidelines: [...(input.promptGuidelines ?? [])],\n\t\tappendSystemPrompt: input.appendSystemPrompt ?? \"\",\n\t\tsections: { ...(input.sections ?? {}) },\n\t\tcwd: input.cwd,\n\t\tcontextFiles: (input.contextFiles ?? []).map((file) => ({ ...file })),\n\t\tskills: (input.skills ?? []).map((skill) => ({ ...skill })),\n\t};\n}\n\nfunction renderProjectContext(contextFiles: Array<{ path: string; content: string }>): string {\n\treturn [\n\t\t\"Project-specific instructions and guidelines:\",\n\t\t...contextFiles.map(\n\t\t\t({ path, content }) => `<project_instructions path=\"${path}\">\\n${content}\\n</project_instructions>`,\n\t\t),\n\t].join(\"\\n\\n\");\n}\n\nfunction buildRules(\n\tselectedTools: string[],\n\ttoolGuidelines: Record<string, string[]>,\n\tpromptGuidelines: string[],\n): string {\n\tconst rules: string[] = [];\n\tconst seen = new Set<string>();\n\tconst addRule = (rule: string): void => {\n\t\tconst normalized = rule.trim();\n\t\tif (!normalized || seen.has(normalized)) return;\n\t\tseen.add(normalized);\n\t\trules.push(normalized);\n\t};\n\n\tconst hasBash = selectedTools.includes(\"bash\");\n\tconst hasPowerShell = selectedTools.includes(\"powershell\");\n\tconst hasGrep = selectedTools.includes(\"grep\");\n\tconst hasFind = selectedTools.includes(\"find\");\n\tconst hasLs = selectedTools.includes(\"ls\");\n\n\tif ((hasBash || hasPowerShell) && !hasGrep && !hasFind && !hasLs) {\n\t\tif (hasBash && hasPowerShell) {\n\t\t\taddRule(\"Use bash or PowerShell for file operations like listing, searching, and finding files\");\n\t\t} else if (hasPowerShell) {\n\t\t\taddRule(\"Use PowerShell for file operations like listing, searching, and finding files\");\n\t\t} else {\n\t\t\taddRule(\"Use bash for file operations like ls, rg, find\");\n\t\t}\n\t}\n\n\tfor (const name of selectedTools) {\n\t\tfor (const rule of toolGuidelines[name] ?? []) addRule(rule);\n\t}\n\tfor (const rule of promptGuidelines) addRule(rule);\n\taddRule(\"Be concise in your responses\");\n\taddRule(\"Show file paths clearly when working with files\");\n\treturn rules.map((rule) => `- ${rule}`).join(\"\\n\");\n}\n\n/** Build the ordered, independently replaceable sections of the structured system prompt. */\nexport function buildSystemPromptSections(input: BuildSystemPromptOptions): SystemPromptSections {\n\tconst options = normalizeBuildSystemPromptOptions(input);\n\tconst {\n\t\tcustomPrompt,\n\t\tselectedTools,\n\t\ttoolSnippets,\n\t\ttoolGuidelines,\n\t\tpromptGuidelines,\n\t\tappendSystemPrompt,\n\t\tsections: customSections,\n\t\tcwd,\n\t\tcontextFiles,\n\t\tskills,\n\t} = options;\n\n\tfor (const name of Object.keys(customSections)) {\n\t\tif (!SYSTEM_PROMPT_SECTION_NAME.test(name) || name === \"preamble\") {\n\t\t\tthrow new Error(`Invalid system prompt section name: ${name}`);\n\t\t}\n\t}\n\n\tconst promptSections: Record<string, string> = {};\n\tif (customPrompt) {\n\t\tpromptSections.preamble = customPrompt;\n\t} else {\n\t\tpromptSections.preamble =\n\t\t\t\"You are an expert coding assistant operating inside pi, a coding agent harness. You help users by reading files, executing commands, editing code, and writing new files.\";\n\t\tconst visibleTools = selectedTools.filter((name) => !!toolSnippets[name]);\n\t\tconst tools =\n\t\t\tvisibleTools.length > 0 ? visibleTools.map((name) => `- ${name}: ${toolSnippets[name]}`).join(\"\\n\") : \"(none)\";\n\t\tpromptSections.tools = `${tools}\\n\\nIn addition to the tools above, you may have access to other custom tools depending on the project.`;\n\t\tpromptSections.rules = buildRules(selectedTools, toolGuidelines, promptGuidelines);\n\t\tpromptSections.docs = `Pi documentation (read only when the user asks about pi itself, its SDK, extensions, themes, skills, or TUI):\n- Main documentation: ${getReadmePath()}\n- Additional docs: ${getDocsPath()}\n- Examples: ${getExamplesPath()} (extensions, custom tools, SDK)\n- When reading pi docs or examples, resolve docs/... under Additional docs and examples/... under Examples, not the current working directory\n- When asked about: extensions (docs/extensions.md, examples/extensions/), themes (docs/themes.md), skills (docs/skills.md), prompt templates (docs/prompt-templates.md), TUI components (docs/tui.md), keybindings (docs/keybindings.md), SDK integrations (docs/sdk.md), custom providers (docs/custom-provider.md), adding models (docs/models.md), pi packages (docs/packages.md), environment variables (docs/environment-variables.md)\n- When working on pi topics, read the docs and examples, and follow .md cross-references before implementing\n- Always read pi .md files completely and follow links to related docs (e.g., tui.md for TUI API details)`;\n\t}\n\n\tif (appendSystemPrompt) promptSections.addendum = appendSystemPrompt;\n\tif (contextFiles.length > 0) promptSections.project_context = renderProjectContext(contextFiles);\n\tconst skillFileReadTool = ([\"read\", \"bash\"] as const).find((tool) => selectedTools.includes(tool));\n\tif (skillFileReadTool && skills.length > 0) {\n\t\tconst skillsPrompt = formatSkillsForPrompt(skills, skillFileReadTool).trim();\n\t\tif (skillsPrompt) promptSections.skills = skillsPrompt;\n\t}\n\tpromptSections.cwd = cwd.replace(/\\\\/g, \"/\");\n\tfor (const [name, content] of Object.entries(customSections)) {\n\t\tif (content) promptSections[name] = content;\n\t}\n\n\tconst sections: SystemPromptSections = { preamble: promptSections.preamble };\n\tfor (const [name, content] of Object.entries(promptSections)) {\n\t\tif (name !== \"preamble\") sections[name] = `<${name}>\\n${content}\\n</${name}>`;\n\t}\n\treturn sections;\n}\n\n/**\n * The complete prompt state for `input`. A forced prompt is opaque and lives in `content`\n * with no sections; otherwise `content` is empty and the structured sections carry the prompt.\n */\nexport function buildSystemPromptState(input: BuildSystemPromptOptions): {\n\tcontent: string;\n\tsections?: SystemPromptSections;\n} {\n\tif (input.forceSystemPrompt !== undefined) return { content: input.forceSystemPrompt };\n\treturn { content: \"\", sections: buildSystemPromptSections(input) };\n}\n\n/** Build the system prompt text, rendered exactly as the transcript's system message replays it. */\nexport function buildSystemPrompt(input: BuildSystemPromptOptions): string {\n\treturn getSystemMessageText({ role: \"system\", ...buildSystemPromptState(input), timestamp: 0 });\n}\n\n/**\n * Diff the sections the model currently has (replayed from the transcript, so never null)\n * against the desired ones. Returns a `SystemMessage.sections` patch, or undefined when\n * nothing changed.\n */\nexport function diffSystemPromptSections(\n\tprevious: Record<string, string | null>,\n\tcurrent: SystemPromptSections,\n): Record<string, string | null> | undefined {\n\tconst patch: Record<string, string | null> = {};\n\tfor (const [name, text] of Object.entries(current)) {\n\t\tif (previous[name] !== text) patch[name] = text;\n\t}\n\tfor (const name of Object.keys(previous)) {\n\t\tif (current[name] === undefined) patch[name] = null;\n\t}\n\treturn Object.keys(patch).length > 0 ? patch : undefined;\n}\n"]}
@@ -32,7 +32,8 @@ export interface BashOperations {
32
32
  * @param command The command to execute
33
33
  * @param cwd Working directory
34
34
  * @param options Execution options
35
- * @returns Promise resolving to exit code (null if killed)
35
+ * @returns Promise resolving to the exit code. Report signal terminations as 128 + signal number;
36
+ * a null exit code is treated as a failed command.
36
37
  *
37
38
  * Error contract: reject with `new Error("aborted")` when aborted via `signal`,
38
39
  * and `new Error("timeout:<seconds>")` on timeout expiry. The shared shell
@@ -1 +1 @@
1
- {"version":3,"file":"bash.d.ts","sourceRoot":"","sources":["../../../src/core/tools/bash.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,+BAA+B,CAAC;AAE/D,OAAO,EAAE,KAAK,MAAM,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAE5C,OAAO,EAKN,KAAK,WAAW,EAGhB,MAAM,sBAAsB,CAAC;AAG9B,OAAO,KAAK,EAAE,gBAAgB,EAAE,cAAc,EAAE,MAAM,wBAAwB,CAAC;AAI/E,OAAO,EAAwC,KAAK,gBAAgB,EAAE,MAAM,eAAe,CAAC;AAkB5F,QAAA,MAAM,UAAU;;;;EASd,CAAC;AAEH,eAAO,MAAM,gCAAgC;;;CAGn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,EAAE,aAAa,CAAC;CAC1B;AAED,MAAM,MAAM,eAAe,GAAG;IAC7B,SAAS,EAAE,MAAM,GAAG,SAAS,CAAC;IAC9B,OAAO,EAAE,MAAM,GAAG,SAAS,CAAC;IAC5B,QAAQ,EAAE,MAAM,CAAC,OAAO,GAAG,SAAS,CAAC;CACrC,CAAC;AAEF,MAAM,WAAW,eAAe;IAC/B,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,MAAM,CAAC;IACd,SAAS,EAAE,MAAM,CAAC;IAClB,MAAM,EAAE,MAAM,CAAC;IACf,aAAa,EAAE,MAAM,CAAC;IACtB,gBAAgB,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IACrC,cAAc,EAAE,MAAM,CAAC;CACvB;AAgBD,wBAAgB,yBAAyB,CACxC,GAAG,EAAE,MAAM,EACX,MAAM,EAAE,eAAe,EACvB,OAAO,CAAC,EAAE,eAAe,GACvB,cAAc,CAAC,OAAO,UAAU,EAAE,eAAe,GAAG,SAAS,EAAE,eAAe,CAAC,CA0FjF;AAYD,wBAAgB,wBAAwB,CACvC,GAAG,EAAE,MAAM,EACX,OAAO,CAAC,EAAE,eAAe,GACvB,cAAc,CAAC,OAAO,UAAU,EAAE,eAAe,GAAG,SAAS,EAAE,eAAe,CAAC,CAEjF;AAED,wBAAgB,cAAc,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,eAAe,GAAG,SAAS,CAAC,OAAO,UAAU,CAAC,CAQnG"}
@@ -1,11 +1,11 @@
1
1
  import { constants } from "node:fs";
2
2
  import { access as fsAccess } from "node:fs/promises";
3
+ import { constants as osConstants } from "node:os";
3
4
  import { spawn } from "child_process";
4
5
  import { Type } from "typebox";
5
6
  import { waitForChildProcess } from "../../utils/child-process.js";
6
7
  import { getShellConfig, getShellEnv, killProcessTree, rewriteCmdNulRedirects, trackDetachedChildPid, untrackDetachedChildPid, } from "../../utils/shell.js";
7
8
  import { BackgroundExecutionError } from "../background/types.js";
8
- import { getExperimentalToolSampling } from "../experimental.js";
9
9
  import { createShellRenderers } from "./renderers/bash.js";
10
10
  import { runShellCommand } from "./shell-execution.js";
11
11
  import { wrapToolDefinition } from "./tool-definition-wrapper.js";
@@ -101,7 +101,10 @@ export function createLocalShellOperations(shellName, resolveShellConfig, normal
101
101
  if (timedOut) {
102
102
  throw new Error(`timeout:${timeout}`);
103
103
  }
104
- return { exitCode };
104
+ // A signal-killed shell has no exit code. Use the standard shell convention so
105
+ // callers do not mistake the termination for a successful command.
106
+ const signalCode = child.signalCode;
107
+ return { exitCode: exitCode ?? (signalCode ? 128 + (osConstants.signals[signalCode] ?? 0) : 1) };
105
108
  }
106
109
  finally {
107
110
  if (child.pid)
@@ -174,7 +177,7 @@ export function createShellToolDefinition(cwd, config, options) {
174
177
  promptSnippet: config.promptSnippet,
175
178
  promptGuidelines: exposeSessionEnvironment && config.promptGuidelines ? [...config.promptGuidelines] : undefined,
176
179
  parameters: bashSchema,
177
- constrainedSampling: getExperimentalToolSampling(),
180
+ constrainedSampling: { type: "json_schema", strict: "prefer" },
178
181
  async execute(toolCallId, { command, timeout, background }, parentSignal, originalUpdate, ctx) {
179
182
  const host = ctx?.background;
180
183
  if (host?.closed)
@@ -1 +1 @@
1
- {"version":3,"file":"bash.js","sourceRoot":"","sources":["../../../src/core/tools/bash.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AACpC,OAAO,EAAE,MAAM,IAAI,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAEtD,OAAO,EAAE,KAAK,EAAE,MAAM,eAAe,CAAC;AACtC,OAAO,EAAe,IAAI,EAAE,MAAM,SAAS,CAAC;AAC5C,OAAO,EAAE,mBAAmB,EAAE,MAAM,8BAA8B,CAAC;AACnE,OAAO,EACN,cAAc,EACd,WAAW,EACX,eAAe,EACf,sBAAsB,EAEtB,qBAAqB,EACrB,uBAAuB,GACvB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,E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CAAC,IAAI,CAAC,UAAU,EAAE,CAAC,CAAC,CAAC,EAAE,EAAE;qBAC1d;iBACD;gBACD,OAAO,EAAE;oBACR,UAAU,EAAE,EAAE,IAAI,EAAE,YAAY,EAAE,MAAM,EAAE,OAAO,CAAC,IAAI,CAAC,EAAE,EAAE;oBAC3D,cAAc,EAAE,OAAO,CAAC,IAAI,CAAC,UAAU;iBACvC;aACD,CAAC;QACH,CAAC;QACD,GAAG,oBAAoB,CAAC,MAAM,CAAC;KAC/B,CAAC;AACH,CAAC;AAED,MAAM,cAAc,GAAoB;IACvC,IAAI,EAAE,MAAM;IACZ,KAAK,EAAE,MAAM;IACb,SAAS,EAAE,MAAM;IACjB,MAAM,EAAE,GAAG;IACX,aAAa,EAAE,gCAAgC,CAAC,OAAO;IACvD,gBAAgB,EAAE,gCAAgC,CAAC,UAAU;IAC7D,cAAc,EAAE,SAAS;CACzB,CAAC;AAEF,MAAM,UAAU,wBAAwB,CACvC,GAAW,EACX,OAAyB;IAEzB,OAAO,yBAAyB,CAAC,GAAG,EAAE,cAAc,EAAE,OAAO,CAAC,CAAC;AAChE,CAAC;AAED,MAAM,UAAU,cAAc,CAAC,GAAW,EAAE,OAAyB;IACpE,MAAM,UAAU,GAAG,wBAAwB,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC;IAC1D,MAAM,IAAI,GAAG,kBAAkB,CAAC,UAAU,CAAC,CAAC;IAC5C,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE;QACnB,aAAa,EAAE,UAAU,CAAC,aAAa;QACvC,gBAAgB,EAAE,UAAU,CAAC,gBAAgB;KAC7C,CAAC,CAAC;IACH,OAAO,IAAI,CAAC;AACb,CAAC","sourcesContent":["import { constants } from \"node:fs\";\nimport { access as fsAccess } from \"node:fs/promises\";\nimport type { AgentTool } from \"@earendil-works/pi-agent-core\";\nimport { spawn } from \"child_process\";\nimport { type Static, Type } from \"typebox\";\nimport { waitForChildProcess } from \"../../utils/child-process.ts\";\nimport {\n\tgetShellConfig,\n\tgetShellEnv,\n\tkillProcessTree,\n\trewriteCmdNulRedirects,\n\ttype ShellConfig,\n\ttrackDetachedChildPid,\n\tuntrackDetachedChildPid,\n} from \"../../utils/shell.ts\";\nimport { type BackgroundCompletion, BackgroundExecutionError } from \"../background/types.ts\";\nimport { getExperimentalToolSampling } from \"../experimental.ts\";\nimport type { ExtensionContext, ToolDefinition } from \"../extensions/types.ts\";\nimport { createShellRenderers } from \"./renderers/bash.ts\";\nimport { type ManagedShellExecution, runShellCommand } from \"./shell-execution.ts\";\nimport { wrapToolDefinition } from \"./tool-definition-wrapper.ts\";\nimport { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, type TruncationResult } from \"./truncate.ts\";\n\nconst MAX_TIMEOUT_MS = 2_147_483_647;\nconst MAX_TIMEOUT_SECONDS = MAX_TIMEOUT_MS / 1000;\n\nfunction resolveTimeoutMs(timeout: number | undefined): number | undefined {\n\tif (timeout === undefined) return undefined;\n\tif (!Number.isFinite(timeout) || timeout <= 0) {\n\t\tthrow new Error(\"Invalid timeout: must be a finite number of seconds\");\n\t}\n\n\tconst timeoutMs = timeout * 1000;\n\tif (timeoutMs > MAX_TIMEOUT_MS) {\n\t\tthrow new Error(`Invalid timeout: maximum is ${MAX_TIMEOUT_SECONDS} seconds`);\n\t}\n\treturn timeoutMs;\n}\n\nconst bashSchema = Type.Object({\n\tcommand: Type.String({ description: \"Shell command to execute\" }),\n\ttimeout: Type.Optional(Type.Number({ description: \"Timeout in seconds (optional, no default timeout)\" })),\n\tbackground: Type.Optional(\n\t\tType.Boolean({\n\t\t\tdescription:\n\t\t\t\t\"true returns a managed task ID immediately and runs the command in the background; omit or false to block until exit\",\n\t\t}),\n\t),\n});\n\nexport const bashToolSystemPromptContribution = {\n\tsnippet: \"Execute bash commands, foreground or background\",\n\tguidelines: [\"You can inspect PI_* environment variables for current model and session details.\"],\n} as const;\n\nexport type BashToolInput = Static<typeof bashSchema>;\n\nexport interface BashToolDetails {\n\ttruncation?: TruncationResult;\n\tfullOutputPath?: string;\n\t/** Settled handoff snapshot, not a command completion or exit code. */\n\tbackground?: { kind: \"background\"; taskId: string };\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\t * Error contract: reject with `new Error(\"aborted\")` when aborted via `signal`,\n\t * and `new Error(\"timeout:<seconds>\")` on timeout expiry. The shared shell\n\t * execution pipeline classifies outcomes from these exact markers.\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/** Shared process execution used by the built-in shell tools. */\nexport function createLocalShellOperations(\n\tshellName: string,\n\tresolveShellConfig: () => ShellConfig,\n\tnormalizeCommand: (command: string) => string = (command) => command,\n): BashOperations {\n\treturn {\n\t\texec: async (command, cwd, { onData, signal, timeout, env }) => {\n\t\t\tconst timeoutMs = resolveTimeoutMs(timeout);\n\t\t\tif (signal?.aborted) {\n\t\t\t\tthrow new Error(\"aborted\");\n\t\t\t}\n\t\t\tconst shellConfig = resolveShellConfig();\n\t\t\ttry {\n\t\t\t\tawait fsAccess(cwd, constants.F_OK);\n\t\t\t} catch {\n\t\t\t\tthrow new Error(`Working directory does not exist: ${cwd}\\nCannot execute ${shellName} commands.`);\n\t\t\t}\n\n\t\t\tif (signal?.aborted) throw new Error(\"aborted\");\n\t\t\tconst commandFromStdin = shellConfig.commandTransport === \"stdin\";\n\t\t\tconst normalizedCommand = normalizeCommand(command);\n\t\t\tconst child = spawn(\n\t\t\t\tshellConfig.shell,\n\t\t\t\tcommandFromStdin ? shellConfig.args : [...shellConfig.args, normalizedCommand],\n\t\t\t\t{\n\t\t\t\t\tcwd,\n\t\t\t\t\tdetached: process.platform !== \"win32\",\n\t\t\t\t\tenv: env ?? getShellEnv(),\n\t\t\t\t\tstdio: [commandFromStdin ? \"pipe\" : \"ignore\", \"pipe\", \"pipe\"],\n\t\t\t\t\twindowsHide: true,\n\t\t\t\t},\n\t\t\t);\n\t\t\tif (commandFromStdin) {\n\t\t\t\tchild.stdin?.on(\"error\", () => {});\n\t\t\t\tchild.stdin?.end(normalizedCommand);\n\t\t\t}\n\t\t\tif (child.pid) trackDetachedChildPid(child.pid);\n\t\t\tlet timedOut = false;\n\t\t\tlet timeoutHandle: NodeJS.Timeout | undefined;\n\t\t\tconst onAbort = () => {\n\t\t\t\tif (child.pid) killProcessTree(child.pid);\n\t\t\t};\n\n\t\t\ttry {\n\t\t\t\t// Set timeout if provided.\n\t\t\t\tif (timeoutMs !== undefined) {\n\t\t\t\t\ttimeoutHandle = setTimeout(() => {\n\t\t\t\t\t\ttimedOut = true;\n\t\t\t\t\t\tif (child.pid) killProcessTree(child.pid);\n\t\t\t\t\t}, timeoutMs);\n\t\t\t\t}\n\t\t\t\t// Stream stdout and stderr.\n\t\t\t\tchild.stdout?.on(\"data\", onData);\n\t\t\t\tchild.stderr?.on(\"data\", onData);\n\t\t\t\t// Handle abort signal by killing the entire process tree.\n\t\t\t\tif (signal) {\n\t\t\t\t\tif (signal.aborted) onAbort();\n\t\t\t\t\telse signal.addEventListener(\"abort\", onAbort, { once: true });\n\t\t\t\t}\n\t\t\t\t// Handle shell spawn errors and wait for the process to terminate without hanging\n\t\t\t\t// on inherited stdio handles held by detached descendants.\n\t\t\t\tconst exitCode = await waitForChildProcess(child);\n\t\t\t\tif (signal?.aborted) {\n\t\t\t\t\tthrow new Error(\"aborted\");\n\t\t\t\t}\n\t\t\t\tif (timedOut) {\n\t\t\t\t\tthrow new Error(`timeout:${timeout}`);\n\t\t\t\t}\n\t\t\t\treturn { 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\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 normalizeLocalBashCommand(command: string, platform: NodeJS.Platform = process.platform): string {\n\treturn platform === \"win32\" ? rewriteCmdNulRedirects(command) : command;\n}\n\nexport function createLocalBashOperations(options?: { shellPath?: string }): BashOperations {\n\treturn createLocalShellOperations(\"bash\", () => getShellConfig(options?.shellPath), normalizeLocalBashCommand);\n}\n\nexport interface BashSpawnContext {\n\tcommand: string;\n\tcwd: string;\n\tenv: NodeJS.ProcessEnv;\n}\n\nexport type BashSpawnHook = (context: BashSpawnContext) => BashSpawnContext;\n\nexport function resolveSpawnContext(\n\tcommand: string,\n\tcwd: string,\n\tspawnHook: BashSpawnHook | undefined,\n\texposeSessionEnvironment: boolean,\n\tctx: ExtensionContext | undefined,\n): BashSpawnContext {\n\tconst env = { ...getShellEnv() };\n\tdelete env.PI_SESSION_ID;\n\tdelete env.PI_SESSION_FILE;\n\tdelete env.PI_PROVIDER;\n\tdelete env.PI_MODEL;\n\tdelete env.PI_REASONING_LEVEL;\n\tif (exposeSessionEnvironment && ctx) {\n\t\tconst model = ctx.model;\n\t\tenv.PI_SESSION_ID = ctx.sessionManager.getSessionId();\n\t\tconst sessionFile = ctx.sessionManager.getSessionFile();\n\t\tif (sessionFile) env.PI_SESSION_FILE = sessionFile;\n\t\tif (model) {\n\t\t\tenv.PI_PROVIDER = model.provider;\n\t\t\tenv.PI_MODEL = model.id;\n\t\t}\n\t\tif (ctx.thinkingLevel) env.PI_REASONING_LEVEL = ctx.thinkingLevel;\n\t}\n\tconst baseContext: BashSpawnContext = { command, cwd, env };\n\treturn spawnHook ? spawnHook(baseContext) : baseContext;\n}\n\nexport interface BashToolOptions {\n\t/** Custom operations for command execution. Default: local shell */\n\toperations?: BashOperations;\n\t/** Command prefix prepended to every command (for example shell setup commands) */\n\tcommandPrefix?: string;\n\t/** Optional explicit shell path from settings */\n\tshellPath?: string;\n\t/** Expose current Pi session metadata as PI_* environment variables. Default: true */\n\texposeSessionEnvironment?: boolean;\n\t/** Hook to adjust command, cwd, or env before execution */\n\tspawnHook?: BashSpawnHook;\n}\n\nexport type BashRenderState = {\n\tstartedAt: number | undefined;\n\tendedAt: number | undefined;\n\tinterval: NodeJS.Timeout | undefined;\n};\n\nexport interface ShellToolConfig {\n\tname: string;\n\tlabel: string;\n\tshellName: string;\n\tprompt: string;\n\tpromptSnippet: string;\n\tpromptGuidelines?: readonly string[];\n\ttempFilePrefix: string;\n}\n\n/** Translate terminal shell failures to the native foreground tool contract once. */\nfunction shellToolResult(completion: BackgroundCompletion<BashToolDetails | undefined>, managed: boolean) {\n\tconst status = completion.status;\n\tif (status === \"failed\" || status === \"timeout\" || status === \"cancelled\") {\n\t\tconst text = completion.result.content\n\t\t\t.filter((part) => part.type === \"text\")\n\t\t\t.map((part) => part.text)\n\t\t\t.join(\"\\n\");\n\t\tconst message = completion.error ? text || completion.error : `${text ? `${text}\\n\\n` : \"\"}Command ${status}`;\n\t\tthrow managed ? new BackgroundExecutionError(message, status) : new Error(message);\n\t}\n\treturn completion.result;\n}\n\nexport function createShellToolDefinition(\n\tcwd: string,\n\tconfig: ShellToolConfig,\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 exposeSessionEnvironment = options?.exposeSessionEnvironment ?? true;\n\tconst spawnHook = options?.spawnHook;\n\treturn {\n\t\tname: config.name,\n\t\tlabel: config.label,\n\t\tdescription: `Execute a ${config.shellName} command in the current working directory. Returns stdout and stderr, truncated to the last ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first); the full output is saved to a temp file. Optionally provide a timeout in seconds (no default). Choose the mode per call: foreground (default) blocks until the command exits — use it when your next step needs the output; background: true returns immediately with a task ID — use it for long-running work (builds, servers, watchers, big test suites) or when you have independent work to continue. A handoff is not completion: the result arrives later as an automatic completion notification; meanwhile use bg read to inspect output, bg wait to block until it settles, bg kill to stop it. Background output is limited to 20 MiB; an expired bg wait window never stops the command.`,\n\t\tpromptSnippet: config.promptSnippet,\n\t\tpromptGuidelines: exposeSessionEnvironment && config.promptGuidelines ? [...config.promptGuidelines] : undefined,\n\t\tparameters: bashSchema,\n\t\tconstrainedSampling: getExperimentalToolSampling(),\n\t\tasync execute(\n\t\t\ttoolCallId,\n\t\t\t{ command, timeout, background }: BashToolInput,\n\t\t\tparentSignal?: AbortSignal,\n\t\t\toriginalUpdate?,\n\t\t\tctx?: ExtensionContext,\n\t\t) {\n\t\t\tconst host = ctx?.background;\n\t\t\tif (host?.closed) throw new Error(\"Background service is closed\");\n\t\t\tconst run = async (\n\t\t\t\tmanaged?: ManagedShellExecution,\n\t\t\t): Promise<BackgroundCompletion<BashToolDetails | undefined>> => {\n\t\t\t\tconst signal = managed?.control.signal ?? parentSignal;\n\t\t\t\ttry {\n\t\t\t\t\tif (managed) {\n\t\t\t\t\t\tif (signal?.aborted) throw new Error(\"Command aborted\");\n\t\t\t\t\t\tresolveTimeoutMs(timeout);\n\t\t\t\t\t}\n\t\t\t\t\tconst resolvedCommand = commandPrefix ? `${commandPrefix}\\n${command}` : command;\n\t\t\t\t\tconst spawnContext = resolveSpawnContext(\n\t\t\t\t\t\tresolvedCommand,\n\t\t\t\t\t\tctx?.cwd || cwd,\n\t\t\t\t\t\tspawnHook,\n\t\t\t\t\t\texposeSessionEnvironment,\n\t\t\t\t\t\tctx,\n\t\t\t\t\t);\n\t\t\t\t\treturn await runShellCommand({\n\t\t\t\t\t\toperations: ops,\n\t\t\t\t\t\tshellName: config.shellName,\n\t\t\t\t\t\tcontext: spawnContext,\n\t\t\t\t\t\ttempFilePrefix: config.tempFilePrefix,\n\t\t\t\t\t\ttimeout,\n\t\t\t\t\t\tsignal,\n\t\t\t\t\t\tonUpdate: originalUpdate,\n\t\t\t\t\t\tmanaged,\n\t\t\t\t\t});\n\t\t\t\t} catch (error) {\n\t\t\t\t\t// Setup and cleanup exceptions carry an explicit terminal status.\n\t\t\t\t\tif (!managed) throw error;\n\t\t\t\t\tthrow new BackgroundExecutionError(\n\t\t\t\t\t\terror instanceof Error ? error.message : String(error),\n\t\t\t\t\t\tmanaged.control.signal.aborted ? \"cancelled\" : \"failed\",\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t};\n\t\t\tif (!host || (!host.enabled && !background)) {\n\t\t\t\tif (background)\n\t\t\t\t\tthrow new Error(\"Background execution is not available in this host. No command was started.\");\n\t\t\t\treturn shellToolResult(await run(), false);\n\t\t\t}\n\t\t\tconst outcome = await host.execute<BashToolDetails | undefined>({\n\t\t\t\tkind: \"bash\",\n\t\t\t\ttitle: `${config.label}: ${command}`,\n\t\t\t\ttoolCallId,\n\t\t\t\tcommand,\n\t\t\t\tcwd: ctx?.cwd || cwd,\n\t\t\t\tbackground,\n\t\t\t\tsignal: parentSignal,\n\t\t\t\tonUpdate: originalUpdate,\n\t\t\t\trun: (control) => run({ host, control }),\n\t\t\t});\n\t\t\tif (outcome.kind === \"result\") return shellToolResult(outcome, true);\n\t\t\treturn {\n\t\t\t\tcontent: [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext: `Command handed to background. Task ID: ${outcome.task.id}. Status: ${outcome.task.status}. Completion arrives automatically as a notification — do not poll or immediately wait on it; continue with other work or hand back to the user. Use bg read to inspect output, bg wait only when your next step is blocked on the result (prefer foreground next time in that case), or bg kill to stop it.${outcome.task.outputPath ? `\\nFull output: ${outcome.task.outputPath}` : \"\"}`,\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t\tdetails: {\n\t\t\t\t\tbackground: { kind: \"background\", taskId: outcome.task.id },\n\t\t\t\t\tfullOutputPath: outcome.task.outputPath,\n\t\t\t\t},\n\t\t\t};\n\t\t},\n\t\t...createShellRenderers(config),\n\t};\n}\n\nconst bashToolConfig: ShellToolConfig = {\n\tname: \"bash\",\n\tlabel: \"bash\",\n\tshellName: \"bash\",\n\tprompt: \"$\",\n\tpromptSnippet: bashToolSystemPromptContribution.snippet,\n\tpromptGuidelines: bashToolSystemPromptContribution.guidelines,\n\ttempFilePrefix: \"pi-bash\",\n};\n\nexport function createBashToolDefinition(\n\tcwd: string,\n\toptions?: BashToolOptions,\n): ToolDefinition<typeof bashSchema, BashToolDetails | undefined, BashRenderState> {\n\treturn createShellToolDefinition(cwd, bashToolConfig, options);\n}\n\nexport function createBashTool(cwd: string, options?: BashToolOptions): AgentTool<typeof bashSchema> {\n\tconst definition = createBashToolDefinition(cwd, options);\n\tconst tool = wrapToolDefinition(definition);\n\tObject.assign(tool, {\n\t\tpromptSnippet: definition.promptSnippet,\n\t\tpromptGuidelines: definition.promptGuidelines,\n\t});\n\treturn tool;\n}\n"]}
1
+ {"version":3,"file":"bash.js","sourceRoot":"","sources":["../../../src/core/tools/bash.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AACpC,OAAO,EAAE,MAAM,IAAI,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AACtD,OAAO,EAAE,SAAS,IAAI,WAAW,EAAE,MAAM,SAAS,CAAC;AAEnD,OAAO,EAAE,KAAK,EAAE,MAAM,eAAe,CAAC;AACtC,OAAO,EAAe,IAAI,EAAE,MAAM,SAAS,CAAC;AAC5C,OAAO,EAAE,mBAAmB,EAAE,MAAM,8BAA8B,CAAC;AACnE,OAAO,EACN,cAAc,EACd,WAAW,EACX,eAAe,EACf,sBAAsB,EAEtB,qBAAqB,EACrB,uBAAuB,GACvB,MAAM,sBAA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AgB;KAC7C,CAAC,CAAC;IACH,OAAO,IAAI,CAAC;AACb,CAAC","sourcesContent":["import { constants } from \"node:fs\";\nimport { access as fsAccess } from \"node:fs/promises\";\nimport { constants as osConstants } from \"node:os\";\nimport type { AgentTool } from \"@earendil-works/pi-agent-core\";\nimport { spawn } from \"child_process\";\nimport { type Static, Type } from \"typebox\";\nimport { waitForChildProcess } from \"../../utils/child-process.ts\";\nimport {\n\tgetShellConfig,\n\tgetShellEnv,\n\tkillProcessTree,\n\trewriteCmdNulRedirects,\n\ttype ShellConfig,\n\ttrackDetachedChildPid,\n\tuntrackDetachedChildPid,\n} from \"../../utils/shell.ts\";\nimport { type BackgroundCompletion, BackgroundExecutionError } from \"../background/types.ts\";\nimport type { ExtensionContext, ToolDefinition } from \"../extensions/types.ts\";\nimport { createShellRenderers } from \"./renderers/bash.ts\";\nimport { type ManagedShellExecution, runShellCommand } from \"./shell-execution.ts\";\nimport { wrapToolDefinition } from \"./tool-definition-wrapper.ts\";\nimport { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, type TruncationResult } from \"./truncate.ts\";\n\nconst MAX_TIMEOUT_MS = 2_147_483_647;\nconst MAX_TIMEOUT_SECONDS = MAX_TIMEOUT_MS / 1000;\n\nfunction resolveTimeoutMs(timeout: number | undefined): number | undefined {\n\tif (timeout === undefined) return undefined;\n\tif (!Number.isFinite(timeout) || timeout <= 0) {\n\t\tthrow new Error(\"Invalid timeout: must be a finite number of seconds\");\n\t}\n\n\tconst timeoutMs = timeout * 1000;\n\tif (timeoutMs > MAX_TIMEOUT_MS) {\n\t\tthrow new Error(`Invalid timeout: maximum is ${MAX_TIMEOUT_SECONDS} seconds`);\n\t}\n\treturn timeoutMs;\n}\n\nconst bashSchema = Type.Object({\n\tcommand: Type.String({ description: \"Shell command to execute\" }),\n\ttimeout: Type.Optional(Type.Number({ description: \"Timeout in seconds (optional, no default timeout)\" })),\n\tbackground: Type.Optional(\n\t\tType.Boolean({\n\t\t\tdescription:\n\t\t\t\t\"true returns a managed task ID immediately and runs the command in the background; omit or false to block until exit\",\n\t\t}),\n\t),\n});\n\nexport const bashToolSystemPromptContribution = {\n\tsnippet: \"Execute bash commands, foreground or background\",\n\tguidelines: [\"You can inspect PI_* environment variables for current model and session details.\"],\n} as const;\n\nexport type BashToolInput = Static<typeof bashSchema>;\n\nexport interface BashToolDetails {\n\ttruncation?: TruncationResult;\n\tfullOutputPath?: string;\n\t/** Settled handoff snapshot, not a command completion or exit code. */\n\tbackground?: { kind: \"background\"; taskId: string };\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 the exit code. Report signal terminations as 128 + signal number;\n\t * a null exit code is treated as a failed command.\n\t *\n\t * Error contract: reject with `new Error(\"aborted\")` when aborted via `signal`,\n\t * and `new Error(\"timeout:<seconds>\")` on timeout expiry. The shared shell\n\t * execution pipeline classifies outcomes from these exact markers.\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/** Shared process execution used by the built-in shell tools. */\nexport function createLocalShellOperations(\n\tshellName: string,\n\tresolveShellConfig: () => ShellConfig,\n\tnormalizeCommand: (command: string) => string = (command) => command,\n): BashOperations {\n\treturn {\n\t\texec: async (command, cwd, { onData, signal, timeout, env }) => {\n\t\t\tconst timeoutMs = resolveTimeoutMs(timeout);\n\t\t\tif (signal?.aborted) {\n\t\t\t\tthrow new Error(\"aborted\");\n\t\t\t}\n\t\t\tconst shellConfig = resolveShellConfig();\n\t\t\ttry {\n\t\t\t\tawait fsAccess(cwd, constants.F_OK);\n\t\t\t} catch {\n\t\t\t\tthrow new Error(`Working directory does not exist: ${cwd}\\nCannot execute ${shellName} commands.`);\n\t\t\t}\n\n\t\t\tif (signal?.aborted) throw new Error(\"aborted\");\n\t\t\tconst commandFromStdin = shellConfig.commandTransport === \"stdin\";\n\t\t\tconst normalizedCommand = normalizeCommand(command);\n\t\t\tconst child = spawn(\n\t\t\t\tshellConfig.shell,\n\t\t\t\tcommandFromStdin ? shellConfig.args : [...shellConfig.args, normalizedCommand],\n\t\t\t\t{\n\t\t\t\t\tcwd,\n\t\t\t\t\tdetached: process.platform !== \"win32\",\n\t\t\t\t\tenv: env ?? getShellEnv(),\n\t\t\t\t\tstdio: [commandFromStdin ? \"pipe\" : \"ignore\", \"pipe\", \"pipe\"],\n\t\t\t\t\twindowsHide: true,\n\t\t\t\t},\n\t\t\t);\n\t\t\tif (commandFromStdin) {\n\t\t\t\tchild.stdin?.on(\"error\", () => {});\n\t\t\t\tchild.stdin?.end(normalizedCommand);\n\t\t\t}\n\t\t\tif (child.pid) trackDetachedChildPid(child.pid);\n\t\t\tlet timedOut = false;\n\t\t\tlet timeoutHandle: NodeJS.Timeout | undefined;\n\t\t\tconst onAbort = () => {\n\t\t\t\tif (child.pid) killProcessTree(child.pid);\n\t\t\t};\n\n\t\t\ttry {\n\t\t\t\t// Set timeout if provided.\n\t\t\t\tif (timeoutMs !== undefined) {\n\t\t\t\t\ttimeoutHandle = setTimeout(() => {\n\t\t\t\t\t\ttimedOut = true;\n\t\t\t\t\t\tif (child.pid) killProcessTree(child.pid);\n\t\t\t\t\t}, timeoutMs);\n\t\t\t\t}\n\t\t\t\t// Stream stdout and stderr.\n\t\t\t\tchild.stdout?.on(\"data\", onData);\n\t\t\t\tchild.stderr?.on(\"data\", onData);\n\t\t\t\t// Handle abort signal by killing the entire process tree.\n\t\t\t\tif (signal) {\n\t\t\t\t\tif (signal.aborted) onAbort();\n\t\t\t\t\telse signal.addEventListener(\"abort\", onAbort, { once: true });\n\t\t\t\t}\n\t\t\t\t// Handle shell spawn errors and wait for the process to terminate without hanging\n\t\t\t\t// on inherited stdio handles held by detached descendants.\n\t\t\t\tconst exitCode = await waitForChildProcess(child);\n\t\t\t\tif (signal?.aborted) {\n\t\t\t\t\tthrow new Error(\"aborted\");\n\t\t\t\t}\n\t\t\t\tif (timedOut) {\n\t\t\t\t\tthrow new Error(`timeout:${timeout}`);\n\t\t\t\t}\n\t\t\t\t// A signal-killed shell has no exit code. Use the standard shell convention so\n\t\t\t\t// callers do not mistake the termination for a successful command.\n\t\t\t\tconst signalCode = child.signalCode;\n\t\t\t\treturn { exitCode: exitCode ?? (signalCode ? 128 + (osConstants.signals[signalCode] ?? 0) : 1) };\n\t\t\t} finally {\n\t\t\t\tif (child.pid) untrackDetachedChildPid(child.pid);\n\t\t\t\tif (timeoutHandle) clearTimeout(timeoutHandle);\n\t\t\t\tif (signal) signal.removeEventListener(\"abort\", onAbort);\n\t\t\t}\n\t\t},\n\t};\n}\n\n/**\n * Create bash operations using pi's built-in local shell execution backend.\n *\n * This is useful for extensions that intercept user_bash and still want pi's\n * standard local shell behavior while wrapping or rewriting commands.\n */\nexport function normalizeLocalBashCommand(command: string, platform: NodeJS.Platform = process.platform): string {\n\treturn platform === \"win32\" ? rewriteCmdNulRedirects(command) : command;\n}\n\nexport function createLocalBashOperations(options?: { shellPath?: string }): BashOperations {\n\treturn createLocalShellOperations(\"bash\", () => getShellConfig(options?.shellPath), normalizeLocalBashCommand);\n}\n\nexport interface BashSpawnContext {\n\tcommand: string;\n\tcwd: string;\n\tenv: NodeJS.ProcessEnv;\n}\n\nexport type BashSpawnHook = (context: BashSpawnContext) => BashSpawnContext;\n\nexport function resolveSpawnContext(\n\tcommand: string,\n\tcwd: string,\n\tspawnHook: BashSpawnHook | undefined,\n\texposeSessionEnvironment: boolean,\n\tctx: ExtensionContext | undefined,\n): BashSpawnContext {\n\tconst env = { ...getShellEnv() };\n\tdelete env.PI_SESSION_ID;\n\tdelete env.PI_SESSION_FILE;\n\tdelete env.PI_PROVIDER;\n\tdelete env.PI_MODEL;\n\tdelete env.PI_REASONING_LEVEL;\n\tif (exposeSessionEnvironment && ctx) {\n\t\tconst model = ctx.model;\n\t\tenv.PI_SESSION_ID = ctx.sessionManager.getSessionId();\n\t\tconst sessionFile = ctx.sessionManager.getSessionFile();\n\t\tif (sessionFile) env.PI_SESSION_FILE = sessionFile;\n\t\tif (model) {\n\t\t\tenv.PI_PROVIDER = model.provider;\n\t\t\tenv.PI_MODEL = model.id;\n\t\t}\n\t\tif (ctx.thinkingLevel) env.PI_REASONING_LEVEL = ctx.thinkingLevel;\n\t}\n\tconst baseContext: BashSpawnContext = { command, cwd, env };\n\treturn spawnHook ? spawnHook(baseContext) : baseContext;\n}\n\nexport interface BashToolOptions {\n\t/** Custom operations for command execution. Default: local shell */\n\toperations?: BashOperations;\n\t/** Command prefix prepended to every command (for example shell setup commands) */\n\tcommandPrefix?: string;\n\t/** Optional explicit shell path from settings */\n\tshellPath?: string;\n\t/** Expose current Pi session metadata as PI_* environment variables. Default: true */\n\texposeSessionEnvironment?: boolean;\n\t/** Hook to adjust command, cwd, or env before execution */\n\tspawnHook?: BashSpawnHook;\n}\n\nexport type BashRenderState = {\n\tstartedAt: number | undefined;\n\tendedAt: number | undefined;\n\tinterval: NodeJS.Timeout | undefined;\n};\n\nexport interface ShellToolConfig {\n\tname: string;\n\tlabel: string;\n\tshellName: string;\n\tprompt: string;\n\tpromptSnippet: string;\n\tpromptGuidelines?: readonly string[];\n\ttempFilePrefix: string;\n}\n\n/** Translate terminal shell failures to the native foreground tool contract once. */\nfunction shellToolResult(completion: BackgroundCompletion<BashToolDetails | undefined>, managed: boolean) {\n\tconst status = completion.status;\n\tif (status === \"failed\" || status === \"timeout\" || status === \"cancelled\") {\n\t\tconst text = completion.result.content\n\t\t\t.filter((part) => part.type === \"text\")\n\t\t\t.map((part) => part.text)\n\t\t\t.join(\"\\n\");\n\t\tconst message = completion.error ? text || completion.error : `${text ? `${text}\\n\\n` : \"\"}Command ${status}`;\n\t\tthrow managed ? new BackgroundExecutionError(message, status) : new Error(message);\n\t}\n\treturn completion.result;\n}\n\nexport function createShellToolDefinition(\n\tcwd: string,\n\tconfig: ShellToolConfig,\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 exposeSessionEnvironment = options?.exposeSessionEnvironment ?? true;\n\tconst spawnHook = options?.spawnHook;\n\treturn {\n\t\tname: config.name,\n\t\tlabel: config.label,\n\t\tdescription: `Execute a ${config.shellName} command in the current working directory. Returns stdout and stderr, truncated to the last ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first); the full output is saved to a temp file. Optionally provide a timeout in seconds (no default). Choose the mode per call: foreground (default) blocks until the command exits — use it when your next step needs the output; background: true returns immediately with a task ID — use it for long-running work (builds, servers, watchers, big test suites) or when you have independent work to continue. A handoff is not completion: the result arrives later as an automatic completion notification; meanwhile use bg read to inspect output, bg wait to block until it settles, bg kill to stop it. Background output is limited to 20 MiB; an expired bg wait window never stops the command.`,\n\t\tpromptSnippet: config.promptSnippet,\n\t\tpromptGuidelines: exposeSessionEnvironment && config.promptGuidelines ? [...config.promptGuidelines] : undefined,\n\t\tparameters: bashSchema,\n\t\tconstrainedSampling: { type: \"json_schema\", strict: \"prefer\" },\n\t\tasync execute(\n\t\t\ttoolCallId,\n\t\t\t{ command, timeout, background }: BashToolInput,\n\t\t\tparentSignal?: AbortSignal,\n\t\t\toriginalUpdate?,\n\t\t\tctx?: ExtensionContext,\n\t\t) {\n\t\t\tconst host = ctx?.background;\n\t\t\tif (host?.closed) throw new Error(\"Background service is closed\");\n\t\t\tconst run = async (\n\t\t\t\tmanaged?: ManagedShellExecution,\n\t\t\t): Promise<BackgroundCompletion<BashToolDetails | undefined>> => {\n\t\t\t\tconst signal = managed?.control.signal ?? parentSignal;\n\t\t\t\ttry {\n\t\t\t\t\tif (managed) {\n\t\t\t\t\t\tif (signal?.aborted) throw new Error(\"Command aborted\");\n\t\t\t\t\t\tresolveTimeoutMs(timeout);\n\t\t\t\t\t}\n\t\t\t\t\tconst resolvedCommand = commandPrefix ? `${commandPrefix}\\n${command}` : command;\n\t\t\t\t\tconst spawnContext = resolveSpawnContext(\n\t\t\t\t\t\tresolvedCommand,\n\t\t\t\t\t\tctx?.cwd || cwd,\n\t\t\t\t\t\tspawnHook,\n\t\t\t\t\t\texposeSessionEnvironment,\n\t\t\t\t\t\tctx,\n\t\t\t\t\t);\n\t\t\t\t\treturn await runShellCommand({\n\t\t\t\t\t\toperations: ops,\n\t\t\t\t\t\tshellName: config.shellName,\n\t\t\t\t\t\tcontext: spawnContext,\n\t\t\t\t\t\ttempFilePrefix: config.tempFilePrefix,\n\t\t\t\t\t\ttimeout,\n\t\t\t\t\t\tsignal,\n\t\t\t\t\t\tonUpdate: originalUpdate,\n\t\t\t\t\t\tmanaged,\n\t\t\t\t\t});\n\t\t\t\t} catch (error) {\n\t\t\t\t\t// Setup and cleanup exceptions carry an explicit terminal status.\n\t\t\t\t\tif (!managed) throw error;\n\t\t\t\t\tthrow new BackgroundExecutionError(\n\t\t\t\t\t\terror instanceof Error ? error.message : String(error),\n\t\t\t\t\t\tmanaged.control.signal.aborted ? \"cancelled\" : \"failed\",\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t};\n\t\t\tif (!host || (!host.enabled && !background)) {\n\t\t\t\tif (background)\n\t\t\t\t\tthrow new Error(\"Background execution is not available in this host. No command was started.\");\n\t\t\t\treturn shellToolResult(await run(), false);\n\t\t\t}\n\t\t\tconst outcome = await host.execute<BashToolDetails | undefined>({\n\t\t\t\tkind: \"bash\",\n\t\t\t\ttitle: `${config.label}: ${command}`,\n\t\t\t\ttoolCallId,\n\t\t\t\tcommand,\n\t\t\t\tcwd: ctx?.cwd || cwd,\n\t\t\t\tbackground,\n\t\t\t\tsignal: parentSignal,\n\t\t\t\tonUpdate: originalUpdate,\n\t\t\t\trun: (control) => run({ host, control }),\n\t\t\t});\n\t\t\tif (outcome.kind === \"result\") return shellToolResult(outcome, true);\n\t\t\treturn {\n\t\t\t\tcontent: [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext: `Command handed to background. Task ID: ${outcome.task.id}. Status: ${outcome.task.status}. Completion arrives automatically as a notification — do not poll or immediately wait on it; continue with other work or hand back to the user. Use bg read to inspect output, bg wait only when your next step is blocked on the result (prefer foreground next time in that case), or bg kill to stop it.${outcome.task.outputPath ? `\\nFull output: ${outcome.task.outputPath}` : \"\"}`,\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t\tdetails: {\n\t\t\t\t\tbackground: { kind: \"background\", taskId: outcome.task.id },\n\t\t\t\t\tfullOutputPath: outcome.task.outputPath,\n\t\t\t\t},\n\t\t\t};\n\t\t},\n\t\t...createShellRenderers(config),\n\t};\n}\n\nconst bashToolConfig: ShellToolConfig = {\n\tname: \"bash\",\n\tlabel: \"bash\",\n\tshellName: \"bash\",\n\tprompt: \"$\",\n\tpromptSnippet: bashToolSystemPromptContribution.snippet,\n\tpromptGuidelines: bashToolSystemPromptContribution.guidelines,\n\ttempFilePrefix: \"pi-bash\",\n};\n\nexport function createBashToolDefinition(\n\tcwd: string,\n\toptions?: BashToolOptions,\n): ToolDefinition<typeof bashSchema, BashToolDetails | undefined, BashRenderState> {\n\treturn createShellToolDefinition(cwd, bashToolConfig, options);\n}\n\nexport function createBashTool(cwd: string, options?: BashToolOptions): AgentTool<typeof bashSchema> {\n\tconst definition = createBashToolDefinition(cwd, options);\n\tconst tool = wrapToolDefinition(definition);\n\tObject.assign(tool, {\n\t\tpromptSnippet: definition.promptSnippet,\n\t\tpromptGuidelines: definition.promptGuidelines,\n\t});\n\treturn tool;\n}\n"]}