@astralyn/pi 1.4.5 → 1.4.7

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 (324) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/dist/bundle/chunks/chunk-FODCTZXW.js +230 -0
  3. package/dist/bundle/chunks/{chunk-I5S7H7GA.js → chunk-FYKNSJG6.js} +1 -1
  4. package/dist/bundle/chunks/{chunk-AXFWZIHH.js → chunk-MG5XDTXV.js} +1 -1
  5. package/dist/bundle/chunks/{chunk-ALHAFUHP.js → chunk-PU2IWWXV.js} +1 -1
  6. package/dist/bundle/chunks/{chunk-5M3YJ54Z.js → chunk-RO2VH6UZ.js} +1 -1
  7. package/dist/bundle/chunks/chunk-YJTSOLP2.js +1499 -0
  8. package/dist/bundle/chunks/{cli-FH77R7JR.js → cli-MEL7SGJD.js} +1 -1
  9. package/dist/bundle/chunks/{execute-GMFGC27P.js → execute-4CWRNHPO.js} +1 -1
  10. package/dist/bundle/chunks/{runtime-R5CMHJ5P.js → runtime-R3X67XMR.js} +1 -1
  11. package/dist/bundle/chunks/{virtual-modules-6FUV7ZDV.js → virtual-modules-PKEOKGYI.js} +1 -1
  12. package/dist/bundle/cli.js +1 -1
  13. package/dist/bundle/index.js +1 -1
  14. package/dist/bundle/rpc-entry.js +1 -1
  15. package/dist/core/agent-session.d.ts +0 -3
  16. package/dist/core/agent-session.d.ts.map +1 -1
  17. package/dist/core/agent-session.js +0 -4
  18. package/dist/core/agent-session.js.map +1 -1
  19. package/dist/core/extensions/index.d.ts +1 -1
  20. package/dist/core/extensions/index.d.ts.map +1 -1
  21. package/dist/core/extensions/index.js.map +1 -1
  22. package/dist/core/isolated-session.d.ts +23 -0
  23. package/dist/core/isolated-session.d.ts.map +1 -0
  24. package/dist/core/isolated-session.js +55 -0
  25. package/dist/core/isolated-session.js.map +1 -0
  26. package/dist/core/package-manager.d.ts +7 -1
  27. package/dist/core/package-manager.d.ts.map +1 -1
  28. package/dist/core/package-manager.js +72 -1
  29. package/dist/core/package-manager.js.map +1 -1
  30. package/dist/core/resource-loader.d.ts +1 -0
  31. package/dist/core/resource-loader.d.ts.map +1 -1
  32. package/dist/core/resource-loader.js +23 -7
  33. package/dist/core/resource-loader.js.map +1 -1
  34. package/dist/core/settings-manager.d.ts +4 -2
  35. package/dist/core/settings-manager.d.ts.map +1 -1
  36. package/dist/core/settings-manager.js +11 -0
  37. package/dist/core/settings-manager.js.map +1 -1
  38. package/dist/core/settings-schema.d.ts +7 -0
  39. package/dist/core/settings-schema.d.ts.map +1 -1
  40. package/dist/core/settings-schema.js +6 -0
  41. package/dist/core/settings-schema.js.map +1 -1
  42. package/dist/core/skills.d.ts +10 -0
  43. package/dist/core/skills.d.ts.map +1 -1
  44. package/dist/core/skills.js +23 -0
  45. package/dist/core/skills.js.map +1 -1
  46. package/dist/core/tasks/codec.d.ts +12 -0
  47. package/dist/core/tasks/codec.d.ts.map +1 -0
  48. package/dist/core/tasks/codec.js +139 -0
  49. package/dist/core/tasks/codec.js.map +1 -0
  50. package/dist/core/tasks/delivery.d.ts +11 -4
  51. package/dist/core/tasks/delivery.d.ts.map +1 -1
  52. package/dist/core/tasks/delivery.js +9 -9
  53. package/dist/core/tasks/delivery.js.map +1 -1
  54. package/dist/core/tasks/execution.d.ts +71 -0
  55. package/dist/core/tasks/execution.d.ts.map +1 -0
  56. package/dist/core/tasks/execution.js +292 -0
  57. package/dist/core/tasks/execution.js.map +1 -0
  58. package/dist/core/tasks/format.d.ts +0 -2
  59. package/dist/core/tasks/format.d.ts.map +1 -1
  60. package/dist/core/tasks/format.js +1 -16
  61. package/dist/core/tasks/format.js.map +1 -1
  62. package/dist/core/tasks/limits.d.ts +12 -1
  63. package/dist/core/tasks/limits.d.ts.map +1 -1
  64. package/dist/core/tasks/limits.js +20 -1
  65. package/dist/core/tasks/limits.js.map +1 -1
  66. package/dist/core/tasks/output.d.ts +17 -17
  67. package/dist/core/tasks/output.d.ts.map +1 -1
  68. package/dist/core/tasks/output.js +72 -69
  69. package/dist/core/tasks/output.js.map +1 -1
  70. package/dist/core/tasks/presentation.d.ts +14 -5
  71. package/dist/core/tasks/presentation.d.ts.map +1 -1
  72. package/dist/core/tasks/presentation.js +56 -185
  73. package/dist/core/tasks/presentation.js.map +1 -1
  74. package/dist/core/tasks/record.d.ts +45 -0
  75. package/dist/core/tasks/record.d.ts.map +1 -0
  76. package/dist/core/tasks/record.js +80 -0
  77. package/dist/core/tasks/record.js.map +1 -0
  78. package/dist/core/tasks/runtime.d.ts +22 -22
  79. package/dist/core/tasks/runtime.d.ts.map +1 -1
  80. package/dist/core/tasks/runtime.js +170 -343
  81. package/dist/core/tasks/runtime.js.map +1 -1
  82. package/dist/core/tasks/scheduler.d.ts +16 -0
  83. package/dist/core/tasks/scheduler.d.ts.map +1 -0
  84. package/dist/core/tasks/scheduler.js +42 -0
  85. package/dist/core/tasks/scheduler.js.map +1 -0
  86. package/dist/core/tasks/session.d.ts +1 -1
  87. package/dist/core/tasks/session.d.ts.map +1 -1
  88. package/dist/core/tasks/session.js +22 -35
  89. package/dist/core/tasks/session.js.map +1 -1
  90. package/dist/core/tasks/store.d.ts +18 -25
  91. package/dist/core/tasks/store.d.ts.map +1 -1
  92. package/dist/core/tasks/store.js +45 -43
  93. package/dist/core/tasks/store.js.map +1 -1
  94. package/dist/core/tasks/types.d.ts +159 -70
  95. package/dist/core/tasks/types.d.ts.map +1 -1
  96. package/dist/core/tasks/types.js +3 -9
  97. package/dist/core/tasks/types.js.map +1 -1
  98. package/dist/core/tools/shell-execution.d.ts +8 -7
  99. package/dist/core/tools/shell-execution.d.ts.map +1 -1
  100. package/dist/core/tools/shell-execution.js +19 -27
  101. package/dist/core/tools/shell-execution.js.map +1 -1
  102. package/dist/core/tools/shell-tool.d.ts.map +1 -1
  103. package/dist/core/tools/shell-tool.js +42 -47
  104. package/dist/core/tools/shell-tool.js.map +1 -1
  105. package/dist/core/usage-totals.d.ts +4 -3
  106. package/dist/core/usage-totals.d.ts.map +1 -1
  107. package/dist/core/usage-totals.js +32 -8
  108. package/dist/core/usage-totals.js.map +1 -1
  109. package/dist/extensions/agent/activity.d.ts +4 -4
  110. package/dist/extensions/agent/activity.d.ts.map +1 -1
  111. package/dist/extensions/agent/activity.js +15 -24
  112. package/dist/extensions/agent/activity.js.map +1 -1
  113. package/dist/extensions/agent/index.d.ts +2 -11
  114. package/dist/extensions/agent/index.d.ts.map +1 -1
  115. package/dist/extensions/agent/index.js +3 -88
  116. package/dist/extensions/agent/index.js.map +1 -1
  117. package/dist/extensions/agent/progress.d.ts +31 -0
  118. package/dist/extensions/agent/progress.d.ts.map +1 -0
  119. package/dist/extensions/agent/progress.js +135 -0
  120. package/dist/extensions/agent/progress.js.map +1 -0
  121. package/dist/extensions/agent/render.d.ts.map +1 -1
  122. package/dist/extensions/agent/render.js +8 -17
  123. package/dist/extensions/agent/render.js.map +1 -1
  124. package/dist/extensions/agent/report.d.ts +9 -0
  125. package/dist/extensions/agent/report.d.ts.map +1 -0
  126. package/dist/extensions/agent/report.js +40 -0
  127. package/dist/extensions/agent/report.js.map +1 -0
  128. package/dist/extensions/agent/settings-panel.d.ts +43 -0
  129. package/dist/extensions/agent/settings-panel.d.ts.map +1 -0
  130. package/dist/extensions/agent/settings-panel.js +125 -0
  131. package/dist/extensions/agent/settings-panel.js.map +1 -0
  132. package/dist/extensions/agent/settings.d.ts +1 -1
  133. package/dist/extensions/agent/settings.d.ts.map +1 -1
  134. package/dist/extensions/agent/settings.js +101 -83
  135. package/dist/extensions/agent/settings.js.map +1 -1
  136. package/dist/extensions/agent/tool.d.ts +13 -0
  137. package/dist/extensions/agent/tool.d.ts.map +1 -0
  138. package/dist/extensions/agent/tool.js +88 -0
  139. package/dist/extensions/agent/tool.js.map +1 -0
  140. package/dist/extensions/agent/types.d.ts +19 -21
  141. package/dist/extensions/agent/types.d.ts.map +1 -1
  142. package/dist/extensions/agent/types.js +2 -10
  143. package/dist/extensions/agent/types.js.map +1 -1
  144. package/dist/extensions/agent/worker.d.ts +16 -0
  145. package/dist/extensions/agent/worker.d.ts.map +1 -0
  146. package/dist/extensions/agent/worker.js +66 -0
  147. package/dist/extensions/agent/worker.js.map +1 -0
  148. package/dist/extensions/btw/agent.d.ts +1 -1
  149. package/dist/extensions/btw/agent.d.ts.map +1 -1
  150. package/dist/extensions/btw/agent.js +3 -20
  151. package/dist/extensions/btw/agent.js.map +1 -1
  152. package/dist/extensions/cached-compaction/index.d.ts.map +1 -1
  153. package/dist/extensions/cached-compaction/index.js +3 -22
  154. package/dist/extensions/cached-compaction/index.js.map +1 -1
  155. package/dist/extensions/cached-compaction/render.d.ts +1 -0
  156. package/dist/extensions/cached-compaction/render.d.ts.map +1 -1
  157. package/dist/extensions/cached-compaction/render.js +42 -14
  158. package/dist/extensions/cached-compaction/render.js.map +1 -1
  159. package/dist/extensions/deepwiki/client.d.ts.map +1 -1
  160. package/dist/extensions/deepwiki/client.js +6 -78
  161. package/dist/extensions/deepwiki/client.js.map +1 -1
  162. package/dist/extensions/deepwiki/transport.d.ts +3 -0
  163. package/dist/extensions/deepwiki/transport.d.ts.map +1 -0
  164. package/dist/extensions/deepwiki/transport.js +96 -0
  165. package/dist/extensions/deepwiki/transport.js.map +1 -0
  166. package/dist/extensions/provider/ui/builtin-data.d.ts +3 -3
  167. package/dist/extensions/provider/ui/builtin-data.d.ts.map +1 -1
  168. package/dist/extensions/provider/ui/builtin-data.js.map +1 -1
  169. package/dist/extensions/provider/ui/compat.d.ts +3 -3
  170. package/dist/extensions/provider/ui/compat.d.ts.map +1 -1
  171. package/dist/extensions/provider/ui/compat.js.map +1 -1
  172. package/dist/extensions/provider/ui/controls.d.ts +2 -2
  173. package/dist/extensions/provider/ui/controls.d.ts.map +1 -1
  174. package/dist/extensions/provider/ui/controls.js.map +1 -1
  175. package/dist/extensions/provider/ui/dialogs.d.ts +3 -3
  176. package/dist/extensions/provider/ui/dialogs.d.ts.map +1 -1
  177. package/dist/extensions/provider/ui/dialogs.js.map +1 -1
  178. package/dist/extensions/provider/ui/dictionary.d.ts +2 -2
  179. package/dist/extensions/provider/ui/dictionary.d.ts.map +1 -1
  180. package/dist/extensions/provider/ui/dictionary.js.map +1 -1
  181. package/dist/extensions/provider/ui/editor.d.ts.map +1 -1
  182. package/dist/extensions/provider/ui/editor.js +1 -3
  183. package/dist/extensions/provider/ui/editor.js.map +1 -1
  184. package/dist/extensions/provider/ui/fetch-models.d.ts +2 -2
  185. package/dist/extensions/provider/ui/fetch-models.d.ts.map +1 -1
  186. package/dist/extensions/provider/ui/fetch-models.js.map +1 -1
  187. package/dist/extensions/provider/ui/model-fields.d.ts +2 -2
  188. package/dist/extensions/provider/ui/model-fields.d.ts.map +1 -1
  189. package/dist/extensions/provider/ui/model-fields.js.map +1 -1
  190. package/dist/extensions/provider/ui/model-options.d.ts +6 -6
  191. package/dist/extensions/provider/ui/model-options.d.ts.map +1 -1
  192. package/dist/extensions/provider/ui/model-options.js.map +1 -1
  193. package/dist/extensions/provider/ui/pane.d.ts +21 -12
  194. package/dist/extensions/provider/ui/pane.d.ts.map +1 -1
  195. package/dist/extensions/provider/ui/pane.js.map +1 -1
  196. package/dist/extensions/provider/ui/provider-fields.d.ts +3 -3
  197. package/dist/extensions/provider/ui/provider-fields.d.ts.map +1 -1
  198. package/dist/extensions/provider/ui/provider-fields.js.map +1 -1
  199. package/dist/extensions/provider/ui/thinking-map.d.ts +2 -2
  200. package/dist/extensions/provider/ui/thinking-map.d.ts.map +1 -1
  201. package/dist/extensions/provider/ui/thinking-map.js.map +1 -1
  202. package/dist/extensions/run-summary/format.js +1 -1
  203. package/dist/extensions/run-summary/format.js.map +1 -1
  204. package/dist/extensions/statusline/usage.d.ts.map +1 -1
  205. package/dist/extensions/statusline/usage.js +2 -6
  206. package/dist/extensions/statusline/usage.js.map +1 -1
  207. package/dist/extensions/tasks/tool/actions.d.ts +1 -1
  208. package/dist/extensions/tasks/tool/actions.d.ts.map +1 -1
  209. package/dist/extensions/tasks/tool/actions.js +50 -115
  210. package/dist/extensions/tasks/tool/actions.js.map +1 -1
  211. package/dist/extensions/tasks/tool/constants.d.ts +1 -6
  212. package/dist/extensions/tasks/tool/constants.d.ts.map +1 -1
  213. package/dist/extensions/tasks/tool/constants.js +1 -6
  214. package/dist/extensions/tasks/tool/constants.js.map +1 -1
  215. package/dist/extensions/tasks/tool/schema.d.ts +0 -3
  216. package/dist/extensions/tasks/tool/schema.d.ts.map +1 -1
  217. package/dist/extensions/tasks/tool/schema.js +5 -14
  218. package/dist/extensions/tasks/tool/schema.js.map +1 -1
  219. package/dist/extensions/tasks/tool/types.d.ts +2 -8
  220. package/dist/extensions/tasks/tool/types.d.ts.map +1 -1
  221. package/dist/extensions/tasks/tool/types.js +0 -2
  222. package/dist/extensions/tasks/tool/types.js.map +1 -1
  223. package/dist/extensions/tasks/tool.d.ts.map +1 -1
  224. package/dist/extensions/tasks/tool.js +2 -2
  225. package/dist/extensions/tasks/tool.js.map +1 -1
  226. package/dist/extensions/tasks/ui/completion-render.d.ts.map +1 -1
  227. package/dist/extensions/tasks/ui/completion-render.js +46 -47
  228. package/dist/extensions/tasks/ui/completion-render.js.map +1 -1
  229. package/dist/extensions/tasks/ui/inspector.d.ts +5 -3
  230. package/dist/extensions/tasks/ui/inspector.d.ts.map +1 -1
  231. package/dist/extensions/tasks/ui/inspector.js +18 -6
  232. package/dist/extensions/tasks/ui/inspector.js.map +1 -1
  233. package/dist/extensions/tasks/ui/layout.d.ts +7 -7
  234. package/dist/extensions/tasks/ui/layout.d.ts.map +1 -1
  235. package/dist/extensions/tasks/ui/layout.js +118 -84
  236. package/dist/extensions/tasks/ui/layout.js.map +1 -1
  237. package/dist/extensions/tasks/ui/list.d.ts.map +1 -1
  238. package/dist/extensions/tasks/ui/list.js +45 -31
  239. package/dist/extensions/tasks/ui/list.js.map +1 -1
  240. package/dist/extensions/tasks/ui/manager.d.ts +16 -7
  241. package/dist/extensions/tasks/ui/manager.d.ts.map +1 -1
  242. package/dist/extensions/tasks/ui/manager.js +167 -129
  243. package/dist/extensions/tasks/ui/manager.js.map +1 -1
  244. package/dist/extensions/tasks/ui/model.d.ts +29 -0
  245. package/dist/extensions/tasks/ui/model.d.ts.map +1 -1
  246. package/dist/extensions/tasks/ui/model.js +16 -1
  247. package/dist/extensions/tasks/ui/model.js.map +1 -1
  248. package/dist/extensions/tasks/ui/render.d.ts +1 -1
  249. package/dist/extensions/tasks/ui/render.d.ts.map +1 -1
  250. package/dist/extensions/tasks/ui/render.js +12 -9
  251. package/dist/extensions/tasks/ui/render.js.map +1 -1
  252. package/dist/extensions/tasks/ui/status.d.ts +15 -0
  253. package/dist/extensions/tasks/ui/status.d.ts.map +1 -0
  254. package/dist/extensions/tasks/ui/status.js +16 -0
  255. package/dist/extensions/tasks/ui/status.js.map +1 -0
  256. package/dist/extensions/tasks/ui/tree.js +1 -1
  257. package/dist/extensions/tasks/ui/tree.js.map +1 -1
  258. package/dist/extensions/tasks/ui/views.d.ts +10 -5
  259. package/dist/extensions/tasks/ui/views.d.ts.map +1 -1
  260. package/dist/extensions/tasks/ui/views.js +61 -36
  261. package/dist/extensions/tasks/ui/views.js.map +1 -1
  262. package/dist/index.d.ts +2 -1
  263. package/dist/index.d.ts.map +1 -1
  264. package/dist/index.js.map +1 -1
  265. package/dist/modes/interactive/components/config-selector.d.ts +14 -1
  266. package/dist/modes/interactive/components/config-selector.d.ts.map +1 -1
  267. package/dist/modes/interactive/components/config-selector.js +258 -7
  268. package/dist/modes/interactive/components/config-selector.js.map +1 -1
  269. package/dist/modes/interactive/components/keybinding-hints.d.ts.map +1 -1
  270. package/dist/modes/interactive/components/keybinding-hints.js +2 -1
  271. package/dist/modes/interactive/components/keybinding-hints.js.map +1 -1
  272. package/dist/modes/interactive/components/model-selector.d.ts.map +1 -1
  273. package/dist/modes/interactive/components/model-selector.js +7 -4
  274. package/dist/modes/interactive/components/model-selector.js.map +1 -1
  275. package/dist/modes/interactive/components/status-marker.d.ts +2 -1
  276. package/dist/modes/interactive/components/status-marker.d.ts.map +1 -1
  277. package/dist/modes/interactive/components/status-marker.js +0 -1
  278. package/dist/modes/interactive/components/status-marker.js.map +1 -1
  279. package/dist/modes/interactive/components/thinking-selector.d.ts.map +1 -1
  280. package/dist/modes/interactive/components/thinking-selector.js +10 -3
  281. package/dist/modes/interactive/components/thinking-selector.js.map +1 -1
  282. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  283. package/dist/modes/interactive/interactive-mode.js +7 -1
  284. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  285. package/dist/utils/duration.d.ts +3 -0
  286. package/dist/utils/duration.d.ts.map +1 -0
  287. package/dist/utils/duration.js +17 -0
  288. package/dist/utils/duration.js.map +1 -0
  289. package/dist/utils/number.d.ts +3 -0
  290. package/dist/utils/number.d.ts.map +1 -0
  291. package/dist/utils/number.js +5 -0
  292. package/dist/utils/number.js.map +1 -0
  293. package/docs/bundled/extensions/agent.md +14 -12
  294. package/docs/bundled/extensions/cached-compaction.md +13 -4
  295. package/docs/bundled/extensions/deepwiki.md +3 -1
  296. package/docs/bundled/extensions/statusline.md +1 -1
  297. package/docs/bundled/tasks.md +15 -14
  298. package/docs/extensions.md +26 -10
  299. package/docs/packages.md +5 -3
  300. package/docs/sdk.md +3 -3
  301. package/docs/session-format.md +28 -24
  302. package/docs/settings.md +11 -0
  303. package/docs/skills.md +23 -0
  304. package/npm-shrinkwrap.json +2 -2
  305. package/package.json +1 -1
  306. package/schemas/settings.schema.json +36 -0
  307. package/dist/bundle/chunks/chunk-FSJ45CRP.js +0 -229
  308. package/dist/bundle/chunks/chunk-W3FIUMGM.js +0 -1501
  309. package/dist/core/tasks/history.d.ts +0 -4
  310. package/dist/core/tasks/history.d.ts.map +0 -1
  311. package/dist/core/tasks/history.js +0 -131
  312. package/dist/core/tasks/history.js.map +0 -1
  313. package/dist/extensions/agent/runner.d.ts +0 -24
  314. package/dist/extensions/agent/runner.d.ts.map +0 -1
  315. package/dist/extensions/agent/runner.js +0 -274
  316. package/dist/extensions/agent/runner.js.map +0 -1
  317. package/dist/extensions/deepwiki/http.d.ts +0 -13
  318. package/dist/extensions/deepwiki/http.d.ts.map +0 -1
  319. package/dist/extensions/deepwiki/http.js +0 -88
  320. package/dist/extensions/deepwiki/http.js.map +0 -1
  321. package/dist/extensions/tasks/ui/task-view.d.ts +0 -13
  322. package/dist/extensions/tasks/ui/task-view.d.ts.map +0 -1
  323. package/dist/extensions/tasks/ui/task-view.js +0 -20
  324. package/dist/extensions/tasks/ui/task-view.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/core/tasks/types.ts"],"names":[],"mappings":"AA+KA,MAAM,CAAC,MAAM,yBAAyB,GACrC,yHAAyH,CAAC;AAE3H,MAAM,UAAU,cAAc,CAAC,MAAkB;IAChD,OAAO,MAAM,KAAK,QAAQ,IAAI,MAAM,KAAK,SAAS,IAAI,MAAM,KAAK,UAAU,CAAC;AAC7E,CAAC;AAED,0FAA0F;AAC1F,MAAM,OAAO,kBAAmB,SAAQ,KAAK;IAE5C,YAAY,OAAe,EAAE,MAA0B;QACtD,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,oBAAoB,CAAC;QACjC,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACtB,CAAC;CACD;AAED;;;;;GAKG;AACH,MAAM,OAAO,eAAgB,SAAQ,KAAK;IAGzC,YAAY,IAA6B,EAAE,OAAuB;QACjE,KAAK,CAAC,IAAI,KAAK,WAAW,CAAC,CAAC,CAAC,mBAAmB,CAAC,CAAC,CAAC,iBAAiB,CAAC,CAAC;QACtE,IAAI,CAAC,IAAI,GAAG,iBAAiB,CAAC;QAC9B,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;IACxB,CAAC;CACD","sourcesContent":["import type { AgentToolResult } from \"@earendil-works/pi-agent-core\";\nimport type { Usage } from \"@earendil-works/pi-ai/compat\";\n\n/** An executor-owned source label, never a dispatch key for the runtime. */\nexport type TaskKind = string;\nexport type TaskMode = \"foreground\" | \"background\";\nexport type TaskTerminalStatus = \"completed\" | \"partial\" | \"failed\" | \"cancelled\" | \"timeout\";\nexport type TaskStatus = \"queued\" | \"running\" | \"stopping\" | TaskTerminalStatus;\n\n/** A bounded snapshot; truncation is recorded at the source, never inferred from text. */\nexport interface TaskText {\n\ttext: string;\n\ttruncated: boolean;\n}\n\n/** Self-contained completion-message details. No live handles, tool-private details or accounting. */\nexport interface TaskCompletionSnapshot {\n\tversion: 2;\n\tkind: string;\n\ttaskId: string;\n\ttitle: string;\n\tstatus: TaskTerminalStatus;\n\tstartedAt: number;\n\tendedAt: number;\n\terror?: string;\n\tcommand?: TaskText;\n\tcwd?: string;\n\toutputPath?: string;\n\t/** Process exit code: a number, or null when signal-reaped. */\n\texitCode?: number | null;\n\t/** The tail of the final result text. */\n\toutput: TaskText;\n}\n\n/** A read-only view of one task; the runtime returns frozen snapshots. */\nexport interface TaskSnapshot {\n\tid: string;\n\tkind: TaskKind;\n\ttitle: string;\n\ttoolCallId: string;\n\tanchorId: string | null;\n\tmode: TaskMode;\n\tstatus: TaskStatus;\n\tstartedAt: number;\n\tendedAt?: number;\n\tcommand?: string;\n\tcommandTruncated?: boolean;\n\tcwd?: string;\n\t/** Executor-owned, human-readable Details tab content. */\n\tinfo?: TaskText;\n\t/** Process exit code (bash): a number, or null when signal-reaped. Absent while running or unreported. */\n\texitCode?: number | null;\n\toutputPath?: string;\n\tresult?: AgentToolResult<unknown>;\n\tresultTruncated?: boolean;\n\terror?: string;\n}\n\nexport interface TaskCompletion<T> {\n\tresult: AgentToolResult<T>;\n\tstatus?: TaskTerminalStatus;\n\t/** Terminal diagnostic, stored independently of log slices and bounded to 4096 bytes. */\n\terror?: string;\n\t/** Process exit code (bash): a number, or null when signal-reaped. */\n\texitCode?: number | null;\n\t/** Authoritative cumulative usage; overrides result.usage and any published snapshot. */\n\tusage?: Usage;\n}\n\nexport interface TaskControl<T> {\n\treadonly id: string;\n\treadonly signal: AbortSignal;\n\treadonly mode: TaskMode;\n\tonModeChange(listener: (mode: TaskMode) => void): () => void;\n\trequestCancel(): boolean;\n\t/** Accept only after whole-invocation preflight; required before returning a handoff. */\n\taccept(): void;\n\t/**\n\t * result.usage is a cumulative snapshot, never a delta. The most recent explicitly\n\t * published usage is settled once on rejection (never inferred from details).\n\t * Final completion.usage, then completion.result.usage, override that snapshot.\n\t */\n\tpublish(result: AgentToolResult<T>): void;\n\t/** Register once; cleanup must own only this exclusively-created file and close its writer first. */\n\tsetOutputPath(path: string, cleanup?: () => void | Promise<void>): void;\n}\n\nexport interface TaskExecution<T> {\n\tkind: TaskKind;\n\ttitle: string;\n\ttoolCallId: string;\n\tcommand?: string;\n\tcwd?: string;\n\t/** Static Details tab text; published results remain the Output tab. */\n\tinfo?: string;\n\tbackground?: boolean;\n\tsignal?: AbortSignal;\n\tonUpdate?: (result: AgentToolResult<T>) => void;\n\trun(control: TaskControl<T>): Promise<TaskCompletion<T>>;\n}\n\nexport type TaskToolOutcome<T> =\n\t| { kind: \"result\"; result: AgentToolResult<T>; status?: TaskTerminalStatus; error?: string }\n\t| { kind: \"background\"; task: TaskSnapshot };\n\nexport interface TaskRead {\n\ttask: TaskSnapshot;\n\ttext: string;\n\t/** Bounded log-read/expiry diagnostic, independent of text slicing and byte offsets. */\n\treadError?: string;\n\ttotalBytes: number;\n\ttruncated: boolean;\n\tfromByte?: number;\n}\n\n/** Optional host integration for products built on the execution runtime. */\nexport interface TasksSessionContext {\n\t/** Ends only management-tool waits when new steering arrives. */\n\treadonly waitInterruptSignal?: AbortSignal;\n\t/** Hold a settled result until the wait's tool result has been persisted. */\n\tprepareWait(toolCallId: string, taskId: string): void;\n\t/** Running tasks that navigating to `targetId` would cancel on this session branch. */\n\tstoppedByTreeNavigation(targetId: string): TaskSnapshot[];\n}\n\n/** Session-bound public capability. Captured instances close on runtime replacement. */\nexport interface TasksContext {\n\treadonly enabled: boolean;\n\treadonly closed?: boolean;\n\t/** Present when the runtime is attached to Pi's durable session lifecycle. */\n\treadonly session?: TasksSessionContext;\n\texecute<T>(execution: TaskExecution<T>): Promise<TaskToolOutcome<T>>;\n\tlist(): TaskSnapshot[];\n\tget(id: string): TaskSnapshot;\n\tread(id: string, options?: { mode?: \"head\" | \"tail\"; bytes?: number; sinceBytes?: number }): Promise<TaskRead>;\n\t/** Observation only: terminal delivery is acknowledged by the host via markDelivered after result persistence. */\n\twait(id: string, timeoutMs?: number, signal?: AbortSignal, interruptSignal?: AbortSignal): Promise<TaskSnapshot>;\n\t/**\n\t * Observe the first task running at call time to settle. Returns undefined when there is\n\t * no such task, the window ends, or interruptSignal fires. Tasks started later are excluded.\n\t */\n\twaitAny(timeoutMs?: number, signal?: AbortSignal, interruptSignal?: AbortSignal): Promise<TaskSnapshot | undefined>;\n\tkill(id: string): boolean;\n\t/**\n\t * Move running foreground executions to the background while background slots remain;\n\t * returns how many moved. Throws when eligible work exists but every slot is taken.\n\t */\n\tdetachForeground(): number;\n\t/** Whether this execution can move now, including host policy and available background slots. */\n\tcanDetach(id: string): boolean;\n\t/** Returns false when the task cannot move; throws when every background slot is taken. */\n\tdetach(id: string): boolean;\n\tsubscribe(listener: () => void): () => void;\n\t/** Keep retained output available without delaying completion delivery. */\n\tretain(id: string): () => void;\n\t/** Hold automatic delivery while preparing a result for the host to persist. */\n\tholdDelivery(id: string): () => void;\n}\n\nexport interface TaskRuntimeOptions {\n\tenabled?: boolean;\n\tbackgroundAllowed?: boolean;\n\t/** Durable host integration; standalone runtimes leave waits observational. */\n\tsession?: TasksSessionContext;\n\tanchor?: () => string | null;\n\t/** Concurrent background executions. Foreground work is bounded by its caller instead. */\n\tmaxActive?: number;\n\t/** Per-history limit: foreground and background tasks each get this allowance. */\n\tmaxHistory?: number;\n\t/** Best-effort cleanup errors, bounded to 4096 bytes; no retries or execution failure. */\n\tonCleanupError?: (message: string) => void;\n\t/** Synchronous persistence before terminal observers or notifications. */\n\tonSettled?: (task: TaskSnapshot, usage: Usage | undefined) => void;\n}\n\nexport const TASK_BACKGROUND_REJECTION =\n\t\"Background execution is not permitted in this host. Run with background: false or omit background. No work was started.\";\n\nexport function isTaskTerminal(status: TaskStatus): boolean {\n\treturn status !== \"queued\" && status !== \"running\" && status !== \"stopping\";\n}\n\n/** Preserve the foreground throwing contract without guessing status from output text. */\nexport class TaskExecutionError extends Error {\n\treadonly status: TaskTerminalStatus;\n\tconstructor(message: string, status: TaskTerminalStatus) {\n\t\tsuper(message);\n\t\tthis.name = \"TaskExecutionError\";\n\t\tthis.status = status;\n\t}\n}\n\n/**\n * A failed id lookup, typed so hosts can enrich the message without matching\n * on message text. `matches` snapshots exactly the records the id or prefix\n * resolved against — including records outside the current branch, which\n * list() hides but prefix matching still collides with.\n */\nexport class TaskLookupError extends Error {\n\treadonly kind: \"unknown\" | \"ambiguous\";\n\treadonly matches: TaskSnapshot[];\n\tconstructor(kind: \"unknown\" | \"ambiguous\", matches: TaskSnapshot[]) {\n\t\tsuper(kind === \"ambiguous\" ? \"Ambiguous task ID\" : \"Unknown task ID\");\n\t\tthis.name = \"TaskLookupError\";\n\t\tthis.kind = kind;\n\t\tthis.matches = matches;\n\t}\n}\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/core/tasks/types.ts"],"names":[],"mappings":"AAMA,MAAM,CAAC,MAAM,sBAAsB,GAAG,CAAC,WAAW,EAAE,SAAS,EAAE,QAAQ,EAAE,WAAW,EAAE,SAAS,CAAU,CAAC;AAG1G,MAAM,CAAC,MAAM,iBAAiB,GAAG,wBAAwB,CAAC;AAgR1D,MAAM,CAAC,MAAM,yBAAyB,GACrC,yHAAyH,CAAC;AAE3H,MAAM,UAAU,cAAc,CAAC,MAAkB;IAChD,OAAQ,sBAA4C,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;AACvE,CAAC;AAED;;;;;GAKG;AACH,MAAM,OAAO,eAAgB,SAAQ,KAAK;IAGzC,YAAY,IAA6B,EAAE,OAAuB;QACjE,KAAK,CAAC,IAAI,KAAK,WAAW,CAAC,CAAC,CAAC,mBAAmB,CAAC,CAAC,CAAC,iBAAiB,CAAC,CAAC;QACtE,IAAI,CAAC,IAAI,GAAG,iBAAiB,CAAC;QAC9B,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;IACxB,CAAC;CACD","sourcesContent":["import type { AgentToolResult } from \"@earendil-works/pi-agent-core\";\nimport type { Usage } from \"@earendil-works/pi-ai/compat\";\n\n/** An executor-owned machine source: the task ID prefix, never a dispatch key for the runtime. */\nexport type TaskKind = string;\nexport type TaskMode = \"foreground\" | \"background\";\nexport const TASK_TERMINAL_STATUSES = [\"completed\", \"partial\", \"failed\", \"cancelled\", \"timeout\"] as const;\nexport type TaskTerminalStatus = (typeof TASK_TERMINAL_STATUSES)[number];\nexport type TaskStatus = \"queued\" | \"running\" | \"stopping\" | TaskTerminalStatus;\nexport const TASK_KIND_PATTERN = /^[a-z][a-z0-9-]{0,63}$/;\n\n/**\n * How a task's output is shaped, declared by its executor:\n * a `log` streams and carries its outcome at the end; a `report` is one finished document.\n */\nexport type TaskOutputKind = \"log\" | \"report\";\n\n/** A bounded snapshot; truncation is recorded at the source, never inferred from text. */\nexport interface TaskText {\n\ttext: string;\n\ttruncated: boolean;\n}\n\n/** What the task was asked to do, such as a shell command or a delegated briefing. */\nexport interface TaskInput extends TaskText {\n\t/** Human label for the input, such as \"Command\" or \"Prompt\". */\n\tlabel: string;\n\t/** Optional syntax-highlighting language. */\n\tlanguage?: string;\n}\n\n/** One labelled Details row, such as [\"Directory\", \"/repo\"] or [\"Exit\", \"1\"]. */\nexport type TaskFact = readonly [label: string, value: string];\n\n/** A read-only view of one task; the runtime returns frozen snapshots. */\nexport interface TaskSnapshot {\n\tid: string;\n\tkind: TaskKind;\n\t/** Human source name, such as \"Bash\" or \"Agent\". */\n\tlabel: string;\n\ttitle: string;\n\toutput: TaskOutputKind;\n\tinput?: TaskInput;\n\tfacts?: TaskFact[];\n\ttoolCallId: string;\n\tanchorId: string | null;\n\tmode: TaskMode;\n\tstatus: TaskStatus;\n\tstartedAt: number;\n\tendedAt?: number;\n\toutputPath?: string;\n\t/** Bounded model-readable result text. */\n\tresult?: TaskText;\n\t/** Additional human-only Output text; model-facing reads use the result instead. */\n\tdisplay?: TaskText;\n\terror?: string;\n}\n\nexport interface TaskUpdate<T> {\n\t/** Model-readable progress; also forwarded to a foreground caller's onUpdate. */\n\tresult: AgentToolResult<T>;\n\t/** Additional human-only Output text. */\n\tdisplay?: string;\n\t/** Cumulative usage so far, settled once if the execution ends without a final usage. */\n\tusage?: Usage;\n}\n\nexport interface TaskCompletion<T> {\n\tresult: AgentToolResult<T>;\n\t/** Defaults to completed, or cancelled when the task was already cancelled. */\n\tstatus?: TaskTerminalStatus;\n\t/** Additional human-only Output text, excluded from tasks read and completion context. */\n\tdisplay?: string;\n\t/** Terminal diagnostic, stored independently of log slices and bounded to 4096 bytes. */\n\terror?: string;\n\t/** Terminal Details rows; a label replaces the same label given at launch. */\n\tfacts?: TaskFact[];\n\t/** Authoritative cumulative usage; overrides the result's usage and the latest published usage. */\n\tusage?: Usage;\n}\n\nexport interface TaskControl<T> {\n\treadonly id: string;\n\treadonly signal: AbortSignal;\n\treadonly mode: TaskMode;\n\tonModeChange(listener: (mode: TaskMode) => void): () => void;\n\t/** The executor's own preflight passed; from now on the caller may be handed off to the background. */\n\taccept(): void;\n\tpublish(update: TaskUpdate<T>): void;\n\t/** Register once; cleanup must own only this exclusively-created file and close its writer first. */\n\tattachOutput(path: string, cleanup?: () => void | Promise<void>): void;\n\t/** Cancel this execution, for example when an executor policy limit is exceeded. */\n\tcancel(): void;\n}\n\nexport interface TaskExecution<T> {\n\tkind: TaskKind;\n\t/** Human source name; defaults to `kind`. */\n\tlabel?: string;\n\ttitle: string;\n\t/** Defaults to `log`. */\n\toutput?: TaskOutputKind;\n\tinput?: TaskInput;\n\tfacts?: TaskFact[];\n\ttoolCallId: string;\n\tbackground?: boolean;\n\t/**\n\t * At most `limit` executions sharing `key` run at once. Later ones wait as queued tasks\n\t * whose `run` starts when a slot frees; a queued task can be handed off or cancelled.\n\t */\n\tconcurrency?: { key: string; limit: number };\n\tsignal?: AbortSignal;\n\tonUpdate?: (result: AgentToolResult<T>) => void;\n\trun(control: TaskControl<T>): Promise<TaskCompletion<T>>;\n}\n\nexport type TaskToolOutcome<T> =\n\t| { kind: \"result\"; result: AgentToolResult<T>; status: TaskTerminalStatus; error?: string }\n\t| { kind: \"background\"; task: TaskSnapshot };\n\n/** Which slice of a task's output to read. Defaults to the last 8 KiB. */\nexport interface TaskReadOptions {\n\t/** `tail` (default) reads the end of the output, `head` its start. */\n\tmode?: \"head\" | \"tail\";\n\t/** Maximum bytes to return, bounded by the runtime. */\n\tbytes?: number;\n\t/** Only output written after this byte offset; takes precedence over `mode`. */\n\tsinceBytes?: number;\n}\n\nexport interface TaskRead {\n\ttask: TaskSnapshot;\n\ttext: string;\n\t/** Bounded log-read/expiry diagnostic, independent of text slicing and byte offsets. */\n\treadError?: string;\n\ttotalBytes: number;\n\ttruncated: boolean;\n\tfromByte?: number;\n}\n\n/** Optional host integration for products built on the execution runtime. */\nexport interface TasksSessionContext {\n\t/** Running tasks that navigating to `targetId` would cancel on this session branch. */\n\tstoppedByTreeNavigation(targetId: string): TaskSnapshot[];\n}\n\n/** How a wait ended. `closed` means the host shut down, so execution state is unconfirmed. */\nexport type TaskWaitOutcome = \"settled\" | \"interrupted\" | \"timed_out\" | \"closed\";\n\ninterface TaskObservationOptions {\n\t/** Defaults to 20 seconds and is bounded by the runtime. A timeout never cancels execution. */\n\ttimeoutMs?: number;\n\t/** Rejects the wait with the signal's reason; execution continues. */\n\tsignal?: AbortSignal;\n\t/**\n\t * The tool call whose result carries this observation to the model. With a session host, a\n\t * settled background task stays out of automatic notifications until that result is persisted.\n\t * Without it, or in a standalone runtime, the wait is purely observational.\n\t */\n\ttoolCallId?: string;\n}\n\nexport interface TaskWaitOptions extends TaskObservationOptions {\n\t/** Read output while delivery is still held; skipped when steering interrupted the wait. */\n\tread?: Pick<TaskReadOptions, \"bytes\" | \"sinceBytes\">;\n}\n\nexport interface TaskWaitResult {\n\toutcome: TaskWaitOutcome;\n\twaitedMs: number;\n\t/** The task when the wait ended, before `read` was taken. */\n\ttask: TaskSnapshot;\n\tread?: TaskRead;\n}\n\nexport interface TaskWaitAnyOptions extends TaskObservationOptions {\n\t/** Read the settled task's output while delivery is still held. */\n\tread?: Pick<TaskReadOptions, \"bytes\">;\n}\n\nexport interface TaskWaitAnyResult {\n\t/** `no_tasks`: no background task was running at call time, so nothing was observed. */\n\toutcome: TaskWaitOutcome | \"no_tasks\";\n\twaitedMs: number;\n\t/** The first cohort member to settle; present only for `settled`. */\n\ttask?: TaskSnapshot;\n\tread?: TaskRead;\n\t/** Cohort members still running when the wait ended. */\n\trunning: TaskSnapshot[];\n}\n\n/**\n * Host hooks that make waits part of a durable session. TaskSession supplies them; products\n * embedding a bare TaskRuntime omit them and keep waits observational.\n */\nexport interface TaskWaitHost {\n\t/** Current steering signal. Aborting it ends management waits only, never execution. */\n\treadonly interruptSignal: AbortSignal;\n\t/**\n\t * A wait observed a settled background task and its `toolCallId` is known. Called while the\n\t * runtime still holds delivery; the host takes over until that tool result persists.\n\t */\n\tbind(toolCallId: string, taskId: string): void;\n}\n\n/**\n * What TaskDelivery consumes from the runtime. The runtime keeps only the per-record facts that\n * retention and admission need (a settled handoff is undelivered, claimed or delivered, and a\n * record under a hold is never a candidate); pausing, failure tracking, the in-flight delivery\n * and wait receipts belong to TaskDelivery.\n */\nexport interface TaskDeliveryLedger {\n\treadonly enabled: boolean;\n\tlist(): TaskSnapshot[];\n\t/** Settled handoffs eligible for automatic delivery: visible, unclaimed, unobserved and unheld. */\n\tpendingNotifications(): TaskSnapshot[];\n\t/** Take a pending notification; false when it is no longer a candidate. */\n\tclaimNotification(id: string): boolean;\n\t/** Return a claimed notification to pending after a failed delivery. */\n\treleaseNotification(id: string): void;\n\t/** Acknowledge a persisted delivery or wait result. */\n\tmarkDelivered(id: string): void;\n\t/** Keep a record out of automatic delivery, and its output retained, until released. */\n\tholdDelivery(id: string): () => void;\n}\n\n/** Session-bound public capability. Captured instances close on runtime replacement. */\nexport interface TasksContext {\n\treadonly enabled: boolean;\n\treadonly closed?: boolean;\n\t/** Present when the runtime is attached to Pi's durable session lifecycle. */\n\treadonly session?: TasksSessionContext;\n\texecute<T>(execution: TaskExecution<T>): Promise<TaskToolOutcome<T>>;\n\tlist(): TaskSnapshot[];\n\tget(id: string): TaskSnapshot;\n\tread(id: string, options?: TaskReadOptions): Promise<TaskRead>;\n\t/**\n\t * Observe one task. With `toolCallId` in a session host, the whole observation (wait, read,\n\t * receipt) is atomic with respect to automatic delivery; a standalone runtime never\n\t * acknowledges delivery. Rejects with `TaskLookupError` for an unknown or ambiguous id.\n\t */\n\twait(id: string, options?: TaskWaitOptions): Promise<TaskWaitResult>;\n\t/**\n\t * Observe the first task running at call time to settle. Tasks started later are excluded,\n\t * and `no_tasks` is returned for an empty cohort. Delivery holds cover the whole cohort until\n\t * the observation completes; members other than the winner then resume ordinary notification.\n\t */\n\twaitAny(options?: TaskWaitAnyOptions): Promise<TaskWaitAnyResult>;\n\tkill(id: string): boolean;\n\t/**\n\t * Move running foreground executions to the background while background slots remain;\n\t * returns how many moved. Throws when eligible work exists but every slot is taken.\n\t */\n\tdetachForeground(): number;\n\t/** Whether this execution can move now, including host policy and available background slots. */\n\tcanDetach(id: string): boolean;\n\t/** Returns false when the task cannot move; throws when every background slot is taken. */\n\tdetach(id: string): boolean;\n\tsubscribe(listener: () => void): () => void;\n\t/** Keep retained output available without delaying completion delivery. */\n\tretain(id: string): () => void;\n}\n\nexport interface TaskRuntimeOptions {\n\tenabled?: boolean;\n\tbackgroundAllowed?: boolean;\n\t/** Branch-impact queries for a durable host; standalone runtimes omit it. */\n\tsession?: TasksSessionContext;\n\t/** Wait receipts and steering interruption for a durable host; standalone runtimes leave waits observational. */\n\twaits?: TaskWaitHost;\n\tanchor?: () => string | null;\n\t/** Admission limit for unsettled background tasks; foreground work is bounded by its caller. */\n\tmaxBackground?: number;\n\t/** Per-history limit: foreground and background tasks each get this allowance. */\n\tmaxHistory?: number;\n\t/** Best-effort cleanup errors, bounded to 4096 bytes; no retries or execution failure. */\n\tonCleanupError?: (message: string) => void;\n\t/** Synchronous persistence before terminal observers or notifications. */\n\tonSettled?: (task: TaskSnapshot, usage: Usage | undefined) => void;\n}\n\nexport const TASK_BACKGROUND_REJECTION =\n\t\"Background execution is not permitted in this host. Run with background: false or omit background. No work was started.\";\n\nexport function isTaskTerminal(status: TaskStatus): status is TaskTerminalStatus {\n\treturn (TASK_TERMINAL_STATUSES as readonly string[]).includes(status);\n}\n\n/**\n * A failed id lookup, typed so hosts can enrich the message without matching\n * on message text. `matches` snapshots exactly the records the id or prefix\n * resolved against — including records outside the current branch, which\n * list() hides but prefix matching still collides with.\n */\nexport class TaskLookupError extends Error {\n\treadonly kind: \"unknown\" | \"ambiguous\";\n\treadonly matches: TaskSnapshot[];\n\tconstructor(kind: \"unknown\" | \"ambiguous\", matches: TaskSnapshot[]) {\n\t\tsuper(kind === \"ambiguous\" ? \"Ambiguous task ID\" : \"Unknown task ID\");\n\t\tthis.name = \"TaskLookupError\";\n\t\tthis.kind = kind;\n\t\tthis.matches = matches;\n\t}\n}\n"]}
@@ -1,19 +1,20 @@
1
- import type { AgentToolResult } from "@earendil-works/pi-agent-core";
2
1
  import type { TaskCompletion, TaskControl } from "../tasks/types.ts";
3
2
  import type { BashOperations, BashSpawnContext } from "./bash.ts";
4
3
  import type { BashToolDetails } from "./shell-tool.ts";
5
4
  export declare const MAX_BACKGROUND_OUTPUT_BYTES: number;
6
- export interface ManagedShellExecution {
7
- control: TaskControl<BashToolDetails | undefined>;
8
- }
9
5
  interface ShellExecutionOptions {
10
6
  operations: BashOperations;
11
7
  context: BashSpawnContext;
12
8
  tempFilePrefix: string;
13
9
  timeout?: number;
14
- signal?: AbortSignal;
15
- onUpdate?: (result: AgentToolResult<BashToolDetails | undefined>) => void;
16
- managed?: ManagedShellExecution;
10
+ /** The task this command runs as; its signal cancels the process. */
11
+ control: TaskControl<BashToolDetails | undefined>;
12
+ /**
13
+ * The command belongs to a session task, which may leave the foreground: its output log is
14
+ * created and attached to the task from the first byte, and a final snapshot is always
15
+ * published. Otherwise the log is created only if output is truncated.
16
+ */
17
+ taskLog: boolean;
17
18
  }
18
19
  /** One process and one output owner across foreground/background handoff. */
19
20
  export declare function runShellCommand(options: ShellExecutionOptions): Promise<TaskCompletion<BashToolDetails | undefined>>;
@@ -1 +1 @@
1
- {"version":3,"file":"shell-execution.d.ts","sourceRoot":"","sources":["../../../src/core/tools/shell-execution.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,+BAA+B,CAAC;AAErE,OAAO,KAAK,EAAE,cAAc,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AACrE,OAAO,KAAK,EAAE,cAAc,EAAE,gBAAgB,EAAE,MAAM,WAAW,CAAC;AAGlE,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAGvD,eAAO,MAAM,2BAA2B,QAAmB,CAAC;AAE5D,MAAM,WAAW,qBAAqB;IACrC,OAAO,EAAE,WAAW,CAAC,eAAe,GAAG,SAAS,CAAC,CAAC;CAClD;AAED,UAAU,qBAAqB;IAC9B,UAAU,EAAE,cAAc,CAAC;IAC3B,OAAO,EAAE,gBAAgB,CAAC;IAC1B,cAAc,EAAE,MAAM,CAAC;IACvB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,MAAM,CAAC,EAAE,WAAW,CAAC;IACrB,QAAQ,CAAC,EAAE,CAAC,MAAM,EAAE,eAAe,CAAC,eAAe,GAAG,SAAS,CAAC,KAAK,IAAI,CAAC;IAC1E,OAAO,CAAC,EAAE,qBAAqB,CAAC;CAChC;AAwCD,6EAA6E;AAC7E,wBAAsB,eAAe,CACpC,OAAO,EAAE,qBAAqB,GAC5B,OAAO,CAAC,cAAc,CAAC,eAAe,GAAG,SAAS,CAAC,CAAC,CAsKtD"}
1
+ {"version":3,"file":"shell-execution.d.ts","sourceRoot":"","sources":["../../../src/core/tools/shell-execution.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,cAAc,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AACrE,OAAO,KAAK,EAAE,cAAc,EAAE,gBAAgB,EAAE,MAAM,WAAW,CAAC;AAGlE,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAGvD,eAAO,MAAM,2BAA2B,QAAmB,CAAC;AAE5D,UAAU,qBAAqB;IAC9B,UAAU,EAAE,cAAc,CAAC;IAC3B,OAAO,EAAE,gBAAgB,CAAC;IAC1B,cAAc,EAAE,MAAM,CAAC;IACvB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,qEAAqE;IACrE,OAAO,EAAE,WAAW,CAAC,eAAe,GAAG,SAAS,CAAC,CAAC;IAClD;;;;OAIG;IACH,OAAO,EAAE,OAAO,CAAC;CACjB;AAwCD,6EAA6E;AAC7E,wBAAsB,eAAe,CACpC,OAAO,EAAE,qBAAqB,GAC5B,OAAO,CAAC,cAAc,CAAC,eAAe,GAAG,SAAS,CAAC,CAAC,CAiKtD"}
@@ -12,10 +12,10 @@ function shellFailure(error) {
12
12
  return { status: "timeout", error: `Command timed out after ${error.message.split(":")[1]} seconds` };
13
13
  return { status: "failed", error: boundText(error instanceof Error ? error.message : String(error), 4096) };
14
14
  }
15
- function formatOutput(output, snapshot, managed, emptyText) {
15
+ function formatOutput(output, snapshot, taskLog, emptyText) {
16
16
  const truncation = snapshot.truncation;
17
17
  let text = snapshot.content || emptyText;
18
- let details = managed ? { fullOutputPath: snapshot.fullOutputPath } : undefined;
18
+ let details = taskLog ? { fullOutputPath: snapshot.fullOutputPath } : undefined;
19
19
  if (truncation.truncated) {
20
20
  details = { truncation, fullOutputPath: snapshot.fullOutputPath };
21
21
  const startLine = truncation.totalLines - truncation.outputLines + 1;
@@ -35,8 +35,9 @@ function formatOutput(output, snapshot, managed, emptyText) {
35
35
  }
36
36
  /** One process and one output owner across foreground/background handoff. */
37
37
  export async function runShellCommand(options) {
38
- const { operations, context, managed, signal, timeout } = options;
39
- const output = new OutputAccumulator({ tempFilePrefix: options.tempFilePrefix, persistFromStart: !!managed });
38
+ const { operations, context, control, taskLog, timeout } = options;
39
+ const signal = control.signal;
40
+ const output = new OutputAccumulator({ tempFilePrefix: options.tempFilePrefix, persistFromStart: taskLog });
40
41
  const startedAt = performance.now();
41
42
  let outputError;
42
43
  let acceptingOutput = true;
@@ -49,21 +50,20 @@ export async function runShellCommand(options) {
49
50
  return;
50
51
  outputError = error instanceof Error ? error : new Error(String(error));
51
52
  try {
52
- if (managed)
53
- managed.control.requestCancel();
53
+ control.cancel();
54
54
  }
55
55
  catch {
56
56
  // Late data must not throw through a process observer.
57
57
  }
58
58
  };
59
59
  const checkOutputLimit = () => {
60
- if (managed?.control.mode === "background" && output.getTotalBytes() > MAX_BACKGROUND_OUTPUT_BYTES) {
60
+ if (control.mode === "background" && output.getTotalBytes() > MAX_BACKGROUND_OUTPUT_BYTES) {
61
61
  failOutput(new Error("Background command exceeded the 20 MiB output limit"));
62
62
  }
63
63
  };
64
64
  const snapshot = () => output.snapshot({
65
65
  persistIfTruncated: true,
66
- maxBytes: managed?.control.mode === "background" ? 40 * 1024 : undefined,
66
+ maxBytes: control.mode === "background" ? 40 * 1024 : undefined,
67
67
  });
68
68
  const publish = (snapshot) => {
69
69
  const result = {
@@ -75,13 +75,10 @@ export async function runShellCommand(options) {
75
75
  }
76
76
  : undefined,
77
77
  };
78
- if (managed)
79
- managed.control.publish(result);
80
- else
81
- options.onUpdate?.(result);
78
+ control.publish({ result });
82
79
  };
83
80
  const emitOutputUpdate = () => {
84
- if ((!managed && !options.onUpdate) || !updateDirty)
81
+ if (!updateDirty)
85
82
  return;
86
83
  updateDirty = false;
87
84
  lastUpdateAt = Date.now();
@@ -93,8 +90,6 @@ export async function runShellCommand(options) {
93
90
  updateTimer = undefined;
94
91
  };
95
92
  const scheduleOutputUpdate = () => {
96
- if (!managed && !options.onUpdate)
97
- return;
98
93
  updateDirty = true;
99
94
  const delay = BASH_UPDATE_THROTTLE_MS - (Date.now() - lastUpdateAt);
100
95
  if (delay <= 0) {
@@ -112,8 +107,7 @@ export async function runShellCommand(options) {
112
107
  if (!acceptingOutput || outputError)
113
108
  return;
114
109
  try {
115
- if (managed?.control.mode === "background" &&
116
- output.getTotalBytes() + data.length > MAX_BACKGROUND_OUTPUT_BYTES) {
110
+ if (control.mode === "background" && output.getTotalBytes() + data.length > MAX_BACKGROUND_OUTPUT_BYTES) {
117
111
  const remaining = Math.max(0, MAX_BACKGROUND_OUTPUT_BYTES - output.getTotalBytes());
118
112
  output.append(data.subarray(0, remaining));
119
113
  failOutput(new Error("Background command exceeded the 20 MiB output limit"));
@@ -123,13 +117,11 @@ export async function runShellCommand(options) {
123
117
  scheduleOutputUpdate();
124
118
  }
125
119
  catch (error) {
126
- if (!managed)
127
- throw error;
128
120
  failOutput(error);
129
121
  }
130
122
  };
131
123
  try {
132
- if (managed) {
124
+ if (taskLog) {
133
125
  const path = output.snapshot().fullOutputPath;
134
126
  const cleanup = async () => {
135
127
  await output.closeTempFile();
@@ -139,15 +131,15 @@ export async function runShellCommand(options) {
139
131
  });
140
132
  };
141
133
  try {
142
- managed.control.setOutputPath(path, cleanup);
134
+ control.attachOutput(path, cleanup);
143
135
  }
144
136
  catch (error) {
145
137
  await cleanup();
146
138
  throw error;
147
139
  }
148
- // Detach must check a silent foreground log too, preserving bytes already written.
149
- unsubscribe = managed.control.onModeChange(checkOutputLimit);
150
140
  }
141
+ // Detach must check a silent foreground log too, preserving bytes already written.
142
+ unsubscribe = control.onModeChange(checkOutputLimit);
151
143
  publish();
152
144
  let failure;
153
145
  let exitCode;
@@ -160,7 +152,7 @@ export async function runShellCommand(options) {
160
152
  timeout,
161
153
  env: context.env,
162
154
  });
163
- managed?.control.accept();
155
+ control.accept();
164
156
  ({ exitCode } = await execution);
165
157
  if (exitCode === null) {
166
158
  failure = { status: "failed", error: "Command terminated without an exit code" };
@@ -175,7 +167,7 @@ export async function runShellCommand(options) {
175
167
  acceptingOutput = false;
176
168
  output.finish();
177
169
  clearUpdateTimer();
178
- if (managed)
170
+ if (taskLog)
179
171
  publish(snapshot());
180
172
  else
181
173
  emitOutputUpdate();
@@ -185,12 +177,12 @@ export async function runShellCommand(options) {
185
177
  // after those callbacks, independently of the process's abort marker.
186
178
  if (outputError)
187
179
  failure = { status: "failed", error: boundText(outputError.message, 4096) };
188
- const { text, details } = formatOutput(output, final, !!managed, failure ? "" : "(no output)");
180
+ const { text, details } = formatOutput(output, final, taskLog, failure ? "" : "(no output)");
189
181
  const fullOutput = typeof exitCode === "number" && !outputError ? await output.readFullOutput(1024 * 1024) : undefined;
190
182
  return {
191
183
  status: failure?.status,
192
184
  error: failure?.error,
193
- ...(exitCode !== undefined ? { exitCode } : {}),
185
+ ...(exitCode !== undefined ? { facts: [["Exit", exitCode === null ? "signal" : String(exitCode)]] } : {}),
194
186
  result: {
195
187
  ...(fullOutput && typeof exitCode === "number"
196
188
  ? {
@@ -1 +1 @@
1
- {"version":3,"file":"shell-execution.js","sourceRoot":"","sources":["../../../src/core/tools/shell-execution.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAE1C,OAAO,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AAG/C,OAAO,EAAE,iBAAiB,EAAuB,MAAM,yBAAyB,CAAC;AACjF,OAAO,EAAE,uBAAuB,EAAE,MAAM,qBAAqB,CAAC;AAE9D,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAE3C,MAAM,CAAC,MAAM,2BAA2B,GAAG,EAAE,GA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,CAAC,GAAG,EAAE;yBACzE;wBACD,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;qBACrC;oBACF,CAAC,CAAC,EAAE,CAAC;gBACN,OAAO,EAAE,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC,GAAG,IAAI,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,OAAO,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;gBAClG,OAAO;aACP;SACD,CAAC;IACH,CAAC;YAAS,CAAC;QACV,eAAe,GAAG,KAAK,CAAC;QACxB,WAAW,EAAE,EAAE,CAAC;QAChB,gBAAgB,EAAE,CAAC;QACnB,MAAM,MAAM,CAAC,aAAa,EAAE,CAAC;IAC9B,CAAC;AACF,CAAC","sourcesContent":["import { unlink } from \"node:fs/promises\";\nimport type { AgentToolResult } from \"@earendil-works/pi-agent-core\";\nimport { boundText } from \"../tasks/output.ts\";\nimport type { TaskCompletion, TaskControl } from \"../tasks/types.ts\";\nimport type { BashOperations, BashSpawnContext } from \"./bash.ts\";\nimport { OutputAccumulator, type OutputSnapshot } from \"./output-accumulator.ts\";\nimport { BASH_UPDATE_THROTTLE_MS } from \"./renderers/bash.ts\";\nimport type { BashToolDetails } from \"./shell-tool.ts\";\nimport { formatSize } from \"./truncate.ts\";\n\nexport const MAX_BACKGROUND_OUTPUT_BYTES = 20 * 1024 * 1024;\n\nexport interface ManagedShellExecution {\n\tcontrol: TaskControl<BashToolDetails | undefined>;\n}\n\ninterface ShellExecutionOptions {\n\toperations: BashOperations;\n\tcontext: BashSpawnContext;\n\ttempFilePrefix: string;\n\ttimeout?: number;\n\tsignal?: AbortSignal;\n\tonUpdate?: (result: AgentToolResult<BashToolDetails | undefined>) => void;\n\tmanaged?: ManagedShellExecution;\n}\n\ninterface ShellFailure {\n\tstatus: \"failed\" | \"cancelled\" | \"timeout\";\n\terror: string;\n}\n\n/** Interpret the documented BashOperations error markers once, before formatting output. */\nfunction shellFailure(error: unknown): ShellFailure {\n\tif (error instanceof Error && error.message === \"aborted\") return { status: \"cancelled\", error: \"Command aborted\" };\n\tif (error instanceof Error && error.message.startsWith(\"timeout:\"))\n\t\treturn { status: \"timeout\", error: `Command timed out after ${error.message.split(\":\")[1]} seconds` };\n\treturn { status: \"failed\", error: boundText(error instanceof Error ? error.message : String(error), 4096) };\n}\n\nfunction formatOutput(\n\toutput: OutputAccumulator,\n\tsnapshot: OutputSnapshot,\n\tmanaged: boolean,\n\temptyText: string,\n): { text: string; details: BashToolDetails | undefined } {\n\tconst truncation = snapshot.truncation;\n\tlet text = snapshot.content || emptyText;\n\tlet details: BashToolDetails | undefined = managed ? { fullOutputPath: snapshot.fullOutputPath } : undefined;\n\tif (truncation.truncated) {\n\t\tdetails = { truncation, fullOutputPath: snapshot.fullOutputPath };\n\t\tconst startLine = truncation.totalLines - truncation.outputLines + 1;\n\t\tconst endLine = truncation.totalLines;\n\t\tif (truncation.lastLinePartial) {\n\t\t\tconst lastLineSize = formatSize(output.getLastLineBytes());\n\t\t\ttext += `\\n\\n[Showing last ${formatSize(truncation.outputBytes)} of line ${endLine} (line is ${lastLineSize}). Full output: ${snapshot.fullOutputPath}]`;\n\t\t} else if (truncation.truncatedBy === \"lines\") {\n\t\t\ttext += `\\n\\n[Showing lines ${startLine}-${endLine} of ${truncation.totalLines}. Full output: ${snapshot.fullOutputPath}]`;\n\t\t} else {\n\t\t\ttext += `\\n\\n[Showing lines ${startLine}-${endLine} of ${truncation.totalLines} (${formatSize(truncation.maxBytes)} limit). Full output: ${snapshot.fullOutputPath}]`;\n\t\t}\n\t}\n\treturn { text, details };\n}\n\n/** One process and one output owner across foreground/background handoff. */\nexport async function runShellCommand(\n\toptions: ShellExecutionOptions,\n): Promise<TaskCompletion<BashToolDetails | undefined>> {\n\tconst { operations, context, managed, signal, timeout } = options;\n\tconst output = new OutputAccumulator({ tempFilePrefix: options.tempFilePrefix, persistFromStart: !!managed });\n\tconst startedAt = performance.now();\n\tlet outputError: Error | undefined;\n\tlet acceptingOutput = true;\n\tlet unsubscribe: (() => void) | undefined;\n\tlet updateTimer: NodeJS.Timeout | undefined;\n\tlet updateDirty = false;\n\tlet lastUpdateAt = 0;\n\n\tconst failOutput = (error: unknown) => {\n\t\tif (outputError) return;\n\t\toutputError = error instanceof Error ? error : new Error(String(error));\n\t\ttry {\n\t\t\tif (managed) managed.control.requestCancel();\n\t\t} catch {\n\t\t\t// Late data must not throw through a process observer.\n\t\t}\n\t};\n\tconst checkOutputLimit = () => {\n\t\tif (managed?.control.mode === \"background\" && output.getTotalBytes() > MAX_BACKGROUND_OUTPUT_BYTES) {\n\t\t\tfailOutput(new Error(\"Background command exceeded the 20 MiB output limit\"));\n\t\t}\n\t};\n\tconst snapshot = () =>\n\t\toutput.snapshot({\n\t\t\tpersistIfTruncated: true,\n\t\t\tmaxBytes: managed?.control.mode === \"background\" ? 40 * 1024 : undefined,\n\t\t});\n\tconst publish = (snapshot?: OutputSnapshot) => {\n\t\tconst result: AgentToolResult<BashToolDetails | undefined> = {\n\t\t\tcontent: snapshot ? [{ type: \"text\", text: snapshot.content }] : [],\n\t\t\tdetails: snapshot\n\t\t\t\t? {\n\t\t\t\t\t\ttruncation: snapshot.truncation.truncated ? snapshot.truncation : undefined,\n\t\t\t\t\t\tfullOutputPath: snapshot.fullOutputPath,\n\t\t\t\t\t}\n\t\t\t\t: undefined,\n\t\t};\n\t\tif (managed) managed.control.publish(result);\n\t\telse options.onUpdate?.(result);\n\t};\n\tconst emitOutputUpdate = () => {\n\t\tif ((!managed && !options.onUpdate) || !updateDirty) return;\n\t\tupdateDirty = false;\n\t\tlastUpdateAt = Date.now();\n\t\tpublish(snapshot());\n\t};\n\tconst clearUpdateTimer = () => {\n\t\tif (updateTimer) clearTimeout(updateTimer);\n\t\tupdateTimer = undefined;\n\t};\n\tconst scheduleOutputUpdate = () => {\n\t\tif (!managed && !options.onUpdate) return;\n\t\tupdateDirty = true;\n\t\tconst delay = BASH_UPDATE_THROTTLE_MS - (Date.now() - lastUpdateAt);\n\t\tif (delay <= 0) {\n\t\t\tclearUpdateTimer();\n\t\t\temitOutputUpdate();\n\t\t} else {\n\t\t\tupdateTimer ??= setTimeout(() => {\n\t\t\t\tupdateTimer = undefined;\n\t\t\t\temitOutputUpdate();\n\t\t\t}, delay);\n\t\t}\n\t};\n\tconst handleData = (data: Buffer) => {\n\t\tif (!acceptingOutput || outputError) return;\n\t\ttry {\n\t\t\tif (\n\t\t\t\tmanaged?.control.mode === \"background\" &&\n\t\t\t\toutput.getTotalBytes() + data.length > MAX_BACKGROUND_OUTPUT_BYTES\n\t\t\t) {\n\t\t\t\tconst remaining = Math.max(0, MAX_BACKGROUND_OUTPUT_BYTES - output.getTotalBytes());\n\t\t\t\toutput.append(data.subarray(0, remaining));\n\t\t\t\tfailOutput(new Error(\"Background command exceeded the 20 MiB output limit\"));\n\t\t\t} else output.append(data);\n\t\t\tscheduleOutputUpdate();\n\t\t} catch (error) {\n\t\t\tif (!managed) throw error;\n\t\t\tfailOutput(error);\n\t\t}\n\t};\n\n\ttry {\n\t\tif (managed) {\n\t\t\tconst path = output.snapshot().fullOutputPath!;\n\t\t\tconst cleanup = async () => {\n\t\t\t\tawait output.closeTempFile();\n\t\t\t\tawait unlink(path).catch((error: NodeJS.ErrnoException) => {\n\t\t\t\t\tif (error.code !== \"ENOENT\") throw error;\n\t\t\t\t});\n\t\t\t};\n\t\t\ttry {\n\t\t\t\tmanaged.control.setOutputPath(path, cleanup);\n\t\t\t} catch (error) {\n\t\t\t\tawait cleanup();\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\t// Detach must check a silent foreground log too, preserving bytes already written.\n\t\t\tunsubscribe = managed.control.onModeChange(checkOutputLimit);\n\t\t}\n\t\tpublish();\n\t\tlet failure: ShellFailure | undefined;\n\t\tlet exitCode: number | null | undefined;\n\t\ttry {\n\t\t\tif (signal?.aborted) throw new Error(\"aborted\");\n\t\t\tconst execution = operations.exec(context.command, context.cwd, {\n\t\t\t\tonData: handleData,\n\t\t\t\tsignal,\n\t\t\t\ttimeout,\n\t\t\t\tenv: context.env,\n\t\t\t});\n\t\t\tmanaged?.control.accept();\n\t\t\t({ exitCode } = await execution);\n\t\t\tif (exitCode === null) {\n\t\t\t\tfailure = { status: \"failed\", error: \"Command terminated without an exit code\" };\n\t\t\t} else if (exitCode !== 0) {\n\t\t\t\tfailure = { status: \"failed\", error: `Command exited with code ${exitCode}` };\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tfailure = shellFailure(error);\n\t\t}\n\t\tacceptingOutput = false;\n\t\toutput.finish();\n\t\tclearUpdateTimer();\n\t\tif (managed) publish(snapshot());\n\t\telse emitOutputUpdate();\n\t\tconst final = snapshot();\n\t\tawait output.closeTempFile();\n\t\t// Final progress/cleanup can re-enter handoff. Classify policy cancellation\n\t\t// after those callbacks, independently of the process's abort marker.\n\t\tif (outputError) failure = { status: \"failed\", error: boundText(outputError.message, 4096) };\n\t\tconst { text, details } = formatOutput(output, final, !!managed, failure ? \"\" : \"(no output)\");\n\t\tconst fullOutput =\n\t\t\ttypeof exitCode === \"number\" && !outputError ? await output.readFullOutput(1024 * 1024) : undefined;\n\t\treturn {\n\t\t\tstatus: failure?.status,\n\t\t\terror: failure?.error,\n\t\t\t...(exitCode !== undefined ? { exitCode } : {}),\n\t\t\tresult: {\n\t\t\t\t...(fullOutput && typeof exitCode === \"number\"\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tstructuredContent: {\n\t\t\t\t\t\t\t\toutput: fullOutput.content,\n\t\t\t\t\t\t\t\ttruncated: fullOutput.truncated,\n\t\t\t\t\t\t\t\t...(fullOutput.truncated && final.fullOutputPath\n\t\t\t\t\t\t\t\t\t? { full_output_path: final.fullOutputPath }\n\t\t\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\t\t\texit_code: exitCode,\n\t\t\t\t\t\t\t\twall_time_seconds: Math.round((performance.now() - startedAt) / 100) / 10,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t...(failure ? { isError: true } : {}),\n\t\t\t\t\t\t}\n\t\t\t\t\t: {}),\n\t\t\t\tcontent: [{ type: \"text\", text: failure ? `${text ? `${text}\\n\\n` : \"\"}${failure.error}` : text }],\n\t\t\t\tdetails,\n\t\t\t},\n\t\t};\n\t} finally {\n\t\tacceptingOutput = false;\n\t\tunsubscribe?.();\n\t\tclearUpdateTimer();\n\t\tawait output.closeTempFile();\n\t}\n}\n"]}
1
+ {"version":3,"file":"shell-execution.js","sourceRoot":"","sources":["../../../src/core/tools/shell-execution.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAE1C,OAAO,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AAG/C,OAAO,EAAE,iBAAiB,EAAuB,MAAM,yBAAyB,CAAC;AACjF,OAAO,EAAE,uBAAuB,EAAE,MAAM,qBAAqB,CAAC;AAE9D,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAE3C,MAAM,CAAC,MAAM,2BAA2B,GAAG,EAAE,GAAG,IAAI,GAAG,IAAI,CAAC;AAsB5D,4FAA4F;AAC5F,SAAS,YAAY,CAAC,KAAc;IACnC,IAAI,KAAK,YAAY,KAAK,IAAI,KAAK,CAAC,OAAO,KAAK,SAAS;QAAE,OAAO,EAAE,MAAM,EAAE,WAAW,EAAE,KAAK,EAAE,iBAAiB,EAAE,CAAC;IACpH,IAAI,KAAK,YAAY,KAAK,IAAI,KAAK,CAAC,OAAO,CAAC,UAAU,CAAC,UAAU,CAAC;QACjE,OAAO,EAAE,MAAM,EAAE,SAAS,EAAE,KAAK,EAAE,2BAA2B,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,UAAU,EAAE,CAAC;IACvG,OAAO,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\";\nimport { boundText } from \"../tasks/output.ts\";\nimport type { TaskCompletion, TaskControl } from \"../tasks/types.ts\";\nimport type { BashOperations, BashSpawnContext } from \"./bash.ts\";\nimport { OutputAccumulator, type OutputSnapshot } from \"./output-accumulator.ts\";\nimport { BASH_UPDATE_THROTTLE_MS } from \"./renderers/bash.ts\";\nimport type { BashToolDetails } from \"./shell-tool.ts\";\nimport { formatSize } from \"./truncate.ts\";\n\nexport const MAX_BACKGROUND_OUTPUT_BYTES = 20 * 1024 * 1024;\n\ninterface ShellExecutionOptions {\n\toperations: BashOperations;\n\tcontext: BashSpawnContext;\n\ttempFilePrefix: string;\n\ttimeout?: number;\n\t/** The task this command runs as; its signal cancels the process. */\n\tcontrol: TaskControl<BashToolDetails | undefined>;\n\t/**\n\t * The command belongs to a session task, which may leave the foreground: its output log is\n\t * created and attached to the task from the first byte, and a final snapshot is always\n\t * published. Otherwise the log is created only if output is truncated.\n\t */\n\ttaskLog: boolean;\n}\n\ninterface ShellFailure {\n\tstatus: \"failed\" | \"cancelled\" | \"timeout\";\n\terror: string;\n}\n\n/** Interpret the documented BashOperations error markers once, before formatting output. */\nfunction shellFailure(error: unknown): ShellFailure {\n\tif (error instanceof Error && error.message === \"aborted\") return { status: \"cancelled\", error: \"Command aborted\" };\n\tif (error instanceof Error && error.message.startsWith(\"timeout:\"))\n\t\treturn { status: \"timeout\", error: `Command timed out after ${error.message.split(\":\")[1]} seconds` };\n\treturn { status: \"failed\", error: boundText(error instanceof Error ? error.message : String(error), 4096) };\n}\n\nfunction formatOutput(\n\toutput: OutputAccumulator,\n\tsnapshot: OutputSnapshot,\n\ttaskLog: boolean,\n\temptyText: string,\n): { text: string; details: BashToolDetails | undefined } {\n\tconst truncation = snapshot.truncation;\n\tlet text = snapshot.content || emptyText;\n\tlet details: BashToolDetails | undefined = taskLog ? { fullOutputPath: snapshot.fullOutputPath } : undefined;\n\tif (truncation.truncated) {\n\t\tdetails = { truncation, fullOutputPath: snapshot.fullOutputPath };\n\t\tconst startLine = truncation.totalLines - truncation.outputLines + 1;\n\t\tconst endLine = truncation.totalLines;\n\t\tif (truncation.lastLinePartial) {\n\t\t\tconst lastLineSize = formatSize(output.getLastLineBytes());\n\t\t\ttext += `\\n\\n[Showing last ${formatSize(truncation.outputBytes)} of line ${endLine} (line is ${lastLineSize}). Full output: ${snapshot.fullOutputPath}]`;\n\t\t} else if (truncation.truncatedBy === \"lines\") {\n\t\t\ttext += `\\n\\n[Showing lines ${startLine}-${endLine} of ${truncation.totalLines}. Full output: ${snapshot.fullOutputPath}]`;\n\t\t} else {\n\t\t\ttext += `\\n\\n[Showing lines ${startLine}-${endLine} of ${truncation.totalLines} (${formatSize(truncation.maxBytes)} limit). Full output: ${snapshot.fullOutputPath}]`;\n\t\t}\n\t}\n\treturn { text, details };\n}\n\n/** One process and one output owner across foreground/background handoff. */\nexport async function runShellCommand(\n\toptions: ShellExecutionOptions,\n): Promise<TaskCompletion<BashToolDetails | undefined>> {\n\tconst { operations, context, control, taskLog, timeout } = options;\n\tconst signal = control.signal;\n\tconst output = new OutputAccumulator({ tempFilePrefix: options.tempFilePrefix, persistFromStart: taskLog });\n\tconst startedAt = performance.now();\n\tlet outputError: Error | undefined;\n\tlet acceptingOutput = true;\n\tlet unsubscribe: (() => void) | undefined;\n\tlet updateTimer: NodeJS.Timeout | undefined;\n\tlet updateDirty = false;\n\tlet lastUpdateAt = 0;\n\n\tconst failOutput = (error: unknown) => {\n\t\tif (outputError) return;\n\t\toutputError = error instanceof Error ? error : new Error(String(error));\n\t\ttry {\n\t\t\tcontrol.cancel();\n\t\t} catch {\n\t\t\t// Late data must not throw through a process observer.\n\t\t}\n\t};\n\tconst checkOutputLimit = () => {\n\t\tif (control.mode === \"background\" && output.getTotalBytes() > MAX_BACKGROUND_OUTPUT_BYTES) {\n\t\t\tfailOutput(new Error(\"Background command exceeded the 20 MiB output limit\"));\n\t\t}\n\t};\n\tconst snapshot = () =>\n\t\toutput.snapshot({\n\t\t\tpersistIfTruncated: true,\n\t\t\tmaxBytes: control.mode === \"background\" ? 40 * 1024 : undefined,\n\t\t});\n\tconst publish = (snapshot?: OutputSnapshot) => {\n\t\tconst result: AgentToolResult<BashToolDetails | undefined> = {\n\t\t\tcontent: snapshot ? [{ type: \"text\", text: snapshot.content }] : [],\n\t\t\tdetails: snapshot\n\t\t\t\t? {\n\t\t\t\t\t\ttruncation: snapshot.truncation.truncated ? snapshot.truncation : undefined,\n\t\t\t\t\t\tfullOutputPath: snapshot.fullOutputPath,\n\t\t\t\t\t}\n\t\t\t\t: undefined,\n\t\t};\n\t\tcontrol.publish({ result });\n\t};\n\tconst emitOutputUpdate = () => {\n\t\tif (!updateDirty) return;\n\t\tupdateDirty = false;\n\t\tlastUpdateAt = Date.now();\n\t\tpublish(snapshot());\n\t};\n\tconst clearUpdateTimer = () => {\n\t\tif (updateTimer) clearTimeout(updateTimer);\n\t\tupdateTimer = undefined;\n\t};\n\tconst scheduleOutputUpdate = () => {\n\t\tupdateDirty = true;\n\t\tconst delay = BASH_UPDATE_THROTTLE_MS - (Date.now() - lastUpdateAt);\n\t\tif (delay <= 0) {\n\t\t\tclearUpdateTimer();\n\t\t\temitOutputUpdate();\n\t\t} else {\n\t\t\tupdateTimer ??= setTimeout(() => {\n\t\t\t\tupdateTimer = undefined;\n\t\t\t\temitOutputUpdate();\n\t\t\t}, delay);\n\t\t}\n\t};\n\tconst handleData = (data: Buffer) => {\n\t\tif (!acceptingOutput || outputError) return;\n\t\ttry {\n\t\t\tif (control.mode === \"background\" && output.getTotalBytes() + data.length > MAX_BACKGROUND_OUTPUT_BYTES) {\n\t\t\t\tconst remaining = Math.max(0, MAX_BACKGROUND_OUTPUT_BYTES - output.getTotalBytes());\n\t\t\t\toutput.append(data.subarray(0, remaining));\n\t\t\t\tfailOutput(new Error(\"Background command exceeded the 20 MiB output limit\"));\n\t\t\t} else output.append(data);\n\t\t\tscheduleOutputUpdate();\n\t\t} catch (error) {\n\t\t\tfailOutput(error);\n\t\t}\n\t};\n\n\ttry {\n\t\tif (taskLog) {\n\t\t\tconst path = output.snapshot().fullOutputPath!;\n\t\t\tconst cleanup = async () => {\n\t\t\t\tawait output.closeTempFile();\n\t\t\t\tawait unlink(path).catch((error: NodeJS.ErrnoException) => {\n\t\t\t\t\tif (error.code !== \"ENOENT\") throw error;\n\t\t\t\t});\n\t\t\t};\n\t\t\ttry {\n\t\t\t\tcontrol.attachOutput(path, cleanup);\n\t\t\t} catch (error) {\n\t\t\t\tawait cleanup();\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t}\n\t\t// Detach must check a silent foreground log too, preserving bytes already written.\n\t\tunsubscribe = control.onModeChange(checkOutputLimit);\n\t\tpublish();\n\t\tlet failure: ShellFailure | undefined;\n\t\tlet exitCode: number | null | undefined;\n\t\ttry {\n\t\t\tif (signal?.aborted) throw new Error(\"aborted\");\n\t\t\tconst execution = operations.exec(context.command, context.cwd, {\n\t\t\t\tonData: handleData,\n\t\t\t\tsignal,\n\t\t\t\ttimeout,\n\t\t\t\tenv: context.env,\n\t\t\t});\n\t\t\tcontrol.accept();\n\t\t\t({ exitCode } = await execution);\n\t\t\tif (exitCode === null) {\n\t\t\t\tfailure = { status: \"failed\", error: \"Command terminated without an exit code\" };\n\t\t\t} else if (exitCode !== 0) {\n\t\t\t\tfailure = { status: \"failed\", error: `Command exited with code ${exitCode}` };\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tfailure = shellFailure(error);\n\t\t}\n\t\tacceptingOutput = false;\n\t\toutput.finish();\n\t\tclearUpdateTimer();\n\t\tif (taskLog) publish(snapshot());\n\t\telse emitOutputUpdate();\n\t\tconst final = snapshot();\n\t\tawait output.closeTempFile();\n\t\t// Final progress/cleanup can re-enter handoff. Classify policy cancellation\n\t\t// after those callbacks, independently of the process's abort marker.\n\t\tif (outputError) failure = { status: \"failed\", error: boundText(outputError.message, 4096) };\n\t\tconst { text, details } = formatOutput(output, final, taskLog, failure ? \"\" : \"(no output)\");\n\t\tconst fullOutput =\n\t\t\ttypeof exitCode === \"number\" && !outputError ? await output.readFullOutput(1024 * 1024) : undefined;\n\t\treturn {\n\t\t\tstatus: failure?.status,\n\t\t\terror: failure?.error,\n\t\t\t...(exitCode !== undefined ? { facts: [[\"Exit\", exitCode === null ? \"signal\" : String(exitCode)]] } : {}),\n\t\t\tresult: {\n\t\t\t\t...(fullOutput && typeof exitCode === \"number\"\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tstructuredContent: {\n\t\t\t\t\t\t\t\toutput: fullOutput.content,\n\t\t\t\t\t\t\t\ttruncated: fullOutput.truncated,\n\t\t\t\t\t\t\t\t...(fullOutput.truncated && final.fullOutputPath\n\t\t\t\t\t\t\t\t\t? { full_output_path: final.fullOutputPath }\n\t\t\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\t\t\texit_code: exitCode,\n\t\t\t\t\t\t\t\twall_time_seconds: Math.round((performance.now() - startedAt) / 100) / 10,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t...(failure ? { isError: true } : {}),\n\t\t\t\t\t\t}\n\t\t\t\t\t: {}),\n\t\t\t\tcontent: [{ type: \"text\", text: failure ? `${text ? `${text}\\n\\n` : \"\"}${failure.error}` : text }],\n\t\t\t\tdetails,\n\t\t\t},\n\t\t};\n\t} finally {\n\t\tacceptingOutput = false;\n\t\tunsubscribe?.();\n\t\tclearUpdateTimer();\n\t\tawait output.closeTempFile();\n\t}\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"shell-tool.d.ts","sourceRoot":"","sources":["../../../src/core/tools/shell-tool.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,MAAM,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAC5C,OAAO,KAAK,EAAoB,cAAc,EAAE,MAAM,wBAAwB,CAAC;AAE/E,OAAO,EACN,KAAK,cAAc,EACnB,KAAK,eAAe,EAGpB,KAAK,eAAe,EACpB,MAAM,WAAW,CAAC;AAKnB,OAAO,EAAwC,KAAK,gBAAgB,E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B,EAAE,MAAM,eAAe,CAAC;AAE5F,QAAA,MAAM,UAAU;;;;EASd,CAAC;AAEH,eAAO,MAAM,gCAAgC;;;CAGnC,CAAC;AAEX,MAAM,MAAM,aAAa,GAAG,MAAM,CAAC,OAAO,UAAU,CAAC,CAAC;AAetD,MAAM,WAAW,eAAe;IAC/B,UAAU,CAAC,EAAE,gBAAgB,CAAC;IAC9B,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,uEAAuE;IACvE,UAAU,CAAC,EAAE;QAAE,IAAI,EAAE,YAAY,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAE,CAAC;CACpD;AAED,MAAM,MAAM,eAAe,GAAG;IAC7B,OAAO,CAAC,EAAE,MAAM,IAAI,CAAC;CACrB,CAAC;AAiBF,wBAAgB,yBAAyB,CACxC,GAAG,EAAE,MAAM,EACX,MAAM,EAAE,eAAe,EACvB,OAAO,EAAE,eAAe,GAAG;IAAE,UAAU,EAAE,cAAc,CAAA;CAAE,GACvD,cAAc,CAAC,OAAO,UAAU,EAAE,eAAe,GAAG,SAAS,EAAE,eAAe,CAAC,CA4FjF;AAYD,wBAAgB,wBAAwB,CACvC,GAAG,EAAE,MAAM,EACX,OAAO,CAAC,EAAE,eAAe,GACvB,UAAU,CAAC,OAAO,yBAAyB,CAAC,CAK9C;AAED,wBAAgB,cAAc,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,eAAe;;;;iCAQpE"}
@@ -1,5 +1,5 @@
1
1
  import { Type } from "typebox";
2
- import { TaskExecutionError } from "../tasks/types.js";
2
+ import { TaskRuntime } from "../tasks/runtime.js";
3
3
  import { resolveSpawnContext, resolveTimeoutMs, } from "./bash.js";
4
4
  import { createShellRenderers } from "./renderers/bash.js";
5
5
  import { runShellCommand } from "./shell-execution.js";
@@ -30,7 +30,7 @@ const bashOutputSchema = Type.Union([
30
30
  Type.Object({ task_id: Type.String(), status: Type.String() }),
31
31
  ]);
32
32
  /** Translate terminal shell failures to the native foreground tool contract once. */
33
- function shellToolResult(completion, managed) {
33
+ function shellToolResult(completion) {
34
34
  const status = completion.status;
35
35
  if (completion.result.structuredContent)
36
36
  return completion.result;
@@ -40,7 +40,7 @@ function shellToolResult(completion, managed) {
40
40
  .map((part) => part.text)
41
41
  .join("\n");
42
42
  const message = completion.error ? text || completion.error : `${text ? `${text}\n\n` : ""}Command ${status}`;
43
- throw managed ? new TaskExecutionError(message, status) : new Error(message);
43
+ throw new Error(message);
44
44
  }
45
45
  return completion.result;
46
46
  }
@@ -59,54 +59,49 @@ export function createShellToolDefinition(cwd, config, options) {
59
59
  outputSchema: bashOutputSchema,
60
60
  constrainedSampling: { type: "json_schema", strict: "prefer" },
61
61
  async execute(toolCallId, { command, timeout, background }, parentSignal, originalUpdate, ctx) {
62
- const host = ctx?.tasks;
63
- if (host?.closed)
62
+ const sessionTasks = ctx?.tasks;
63
+ if (sessionTasks?.closed)
64
64
  throw new Error("Task service is closed");
65
- const run = async (managed) => {
66
- const signal = managed?.control.signal ?? parentSignal;
67
- try {
68
- if (managed) {
69
- if (signal?.aborted)
70
- throw new Error("Command aborted");
71
- resolveTimeoutMs(timeout);
72
- }
73
- const resolvedCommand = commandPrefix ? `${commandPrefix}\n${command}` : command;
74
- const spawnContext = resolveSpawnContext(resolvedCommand, ctx?.cwd || cwd, spawnHook, exposeSessionEnvironment, ctx);
75
- return await runShellCommand({
76
- operations: ops,
77
- context: spawnContext,
78
- tempFilePrefix: config.tempFilePrefix,
79
- timeout,
80
- signal,
81
- onUpdate: originalUpdate,
82
- managed,
83
- });
84
- }
85
- catch (error) {
86
- // Setup and cleanup exceptions carry an explicit terminal status.
87
- if (!managed)
88
- throw error;
89
- throw new TaskExecutionError(error instanceof Error ? error.message : String(error), managed.control.signal.aborted ? "cancelled" : "failed");
90
- }
65
+ if (!sessionTasks && background)
66
+ throw new Error("Background execution is not available in this host. No command was started.");
67
+ // Without a session the command still runs as a task, on a throwaway runtime that never backgrounds.
68
+ const standalone = sessionTasks ? undefined : new TaskRuntime();
69
+ const run = async (control) => {
70
+ if (control.signal.aborted)
71
+ throw new Error("Command aborted");
72
+ resolveTimeoutMs(timeout);
73
+ const resolvedCommand = commandPrefix ? `${commandPrefix}\n${command}` : command;
74
+ const spawnContext = resolveSpawnContext(resolvedCommand, ctx?.cwd || cwd, spawnHook, exposeSessionEnvironment, ctx);
75
+ // A setup throw settles the task as failed, or cancelled once its signal fired.
76
+ return await runShellCommand({
77
+ operations: ops,
78
+ context: spawnContext,
79
+ tempFilePrefix: config.tempFilePrefix,
80
+ timeout,
81
+ control,
82
+ taskLog: sessionTasks !== undefined,
83
+ });
91
84
  };
92
- if (!host) {
93
- if (background)
94
- throw new Error("Background execution is not available in this host. No command was started.");
95
- return shellToolResult(await run(), false);
85
+ let outcome;
86
+ try {
87
+ outcome = await (sessionTasks ?? standalone).execute({
88
+ kind: config.name,
89
+ label: config.shellName[0].toUpperCase() + config.shellName.slice(1),
90
+ title: command,
91
+ input: { label: "Command", text: command, truncated: false, language: config.name },
92
+ facts: [["Directory", ctx?.cwd || cwd]],
93
+ toolCallId,
94
+ background,
95
+ signal: parentSignal,
96
+ onUpdate: originalUpdate,
97
+ run,
98
+ });
99
+ }
100
+ finally {
101
+ standalone?.close();
96
102
  }
97
- const outcome = await host.execute({
98
- kind: config.name,
99
- title: command,
100
- toolCallId,
101
- command,
102
- cwd: ctx?.cwd || cwd,
103
- background,
104
- signal: parentSignal,
105
- onUpdate: originalUpdate,
106
- run: (control) => run({ control }),
107
- });
108
103
  if (outcome.kind === "result")
109
- return shellToolResult(outcome, true);
104
+ return shellToolResult(outcome);
110
105
  const tail = `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 tasks read to inspect output, tasks wait only when your next step is blocked on a result (one ID or any running task; prefer foreground next time in that case), or tasks kill to stop it.`;
111
106
  // Shell execution can become background work in two ways, and the model has to know which
112
107
  // one it got: a submitted background command starts from an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/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;QACrD,GAAG,OAAO;QACV,UAAU,EAAE,OAAO,EAAE,UAAU,IAAI,yBAAyB,CAAC,EAAE,SAAS,EAAE,OAAO,EAAE,SAAS,EAAE,CAAC;KAC/F,CAAC,CAAC;AACJ,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 { type Static, Type } from \"typebox\";\nimport type { ExtensionContext, ToolDefinition } from \"../extensions/types.ts\";\nimport { type TaskCompletion, TaskExecutionError } from \"../tasks/types.ts\";\nimport {\n\ttype BashOperations,\n\ttype BashToolOptions,\n\tresolveSpawnContext,\n\tresolveTimeoutMs,\n\ttype ShellToolConfig,\n} from \"./bash.ts\";\nimport { createShellRenderers } from \"./renderers/bash.ts\";\nimport { type ManagedShellExecution, runShellCommand } from \"./shell-execution.ts\";\nimport { createLocalBashOperations } from \"./shell-operations.ts\";\nimport { wrapToolDefinition } from \"./tool-definition-wrapper.ts\";\nimport { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, type TruncationResult } from \"./truncate.ts\";\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, and you are notified when it completes — do not poll for its result; 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\nconst bashOutputSchema = Type.Union([\n\tType.Object({\n\t\toutput: Type.String({\n\t\t\tdescription: \"Combined stdout and stderr, up to 1 MiB, keeping head and tail when truncated.\",\n\t\t}),\n\t\ttruncated: Type.Boolean(),\n\t\tfull_output_path: Type.Optional(Type.String()),\n\t\texit_code: Type.Number(),\n\t\twall_time_seconds: Type.Number(),\n\t}),\n\tType.Object({ task_id: Type.String(), status: Type.String() }),\n]);\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\nexport type BashRenderState = {\n\tdispose?: () => void;\n};\n\n/** Translate terminal shell failures to the native foreground tool contract once. */\nfunction shellToolResult(completion: TaskCompletion<BashToolDetails | undefined>, managed: boolean) {\n\tconst status = completion.status;\n\tif (completion.result.structuredContent) return completion.result;\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 TaskExecutionError(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 & { operations: BashOperations },\n): ToolDefinition<typeof bashSchema, BashToolDetails | undefined, BashRenderState> {\n\tconst ops = options.operations;\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 tasks read to inspect output, tasks wait with an ID for one task or without one for any running task, and tasks kill to stop it. Steering interrupts only a wait, never execution. Background output is limited to 20 MiB; an expired tasks 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\toutputSchema: bashOutputSchema,\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?.tasks;\n\t\t\tif (host?.closed) throw new Error(\"Task service is closed\");\n\t\t\tconst run = async (managed?: ManagedShellExecution): Promise<TaskCompletion<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\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 TaskExecutionError(\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) {\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: config.name,\n\t\t\t\ttitle: 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({ control }),\n\t\t\t});\n\t\t\tif (outcome.kind === \"result\") return shellToolResult(outcome, true);\n\t\t\tconst tail = `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 tasks read to inspect output, tasks wait only when your next step is blocked on a result (one ID or any running task; prefer foreground next time in that case), or tasks kill to stop it.`;\n\t\t\t// Shell execution can become background work in two ways, and the model has to know which\n\t\t\t// one it got: a submitted background command starts from an empty log, while a detached\n\t\t\t// one already holds output and keeps its original timeout.\n\t\t\tconst handoff =\n\t\t\t\tbackground === true\n\t\t\t\t\t? `Command handed to background. ${tail}`\n\t\t\t\t\t: `Command moved to the background while it was running, by the user. The execution continues unchanged — no restart, and a supplied timeout is still measured from command startup. Output produced so far is already in the log, so tasks read now returns partial output, not a fresh start. ${tail}`;\n\t\t\treturn {\n\t\t\t\tstructuredContent: { task_id: outcome.task.id, status: outcome.task.status },\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: `${handoff}${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): ReturnType<typeof createShellToolDefinition> {\n\treturn createShellToolDefinition(cwd, bashToolConfig, {\n\t\t...options,\n\t\toperations: options?.operations ?? createLocalBashOperations({ shellPath: options?.shellPath }),\n\t});\n}\n\nexport function createBashTool(cwd: string, options?: BashToolOptions) {\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":"shell-tool.js","sourceRoot":"","sources":["../../../src/core/tools/shell-tool.ts"],"names":[],"mappings":"AAAA,OAAO,EAAe,IAAI,EAAE,MAAM,SAAS,CAAC;AAE5C,OAAO,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AAElD,OAAO,EAGN,mBAAmB,EACnB,gBAAgB,GAEhB,MAAM,WAAW,CAAC;AACnB,OAAO,EAAE,oBAAoB,EAAE,MAAM,qBAAqB,CAAC;AAC3D,OAAO,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AACvD,OAAO,EAAE,yBAAyB,EAAE,MAAM,uBAAuB,CAAC;AAClE,OAAO,EAAE,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AAClE,OAAO,EAAE,iBAAiB,EAAE,iBAAiB,EAAyB,MAAM,eAAe,CAAC;AAE5F,MAAM,UAAU,GAAG,IAAI,CAAC,MAAM,CAAC;IAC9B,OAAO,EAAE,IAAI,CAAC,MAAM,CAAC,EAAE,WAAW,EAAE,0BAA0B,EAAE,CAAC;IACjE,OAAO,EAAE,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,MAAM,CAAC,EAAE,WAAW,EAAE,mDAAmD,EAAE,CAAC,CAAC;IACzG,UAAU,EAAE,IAAI,CAAC,QAAQ,CACxB,IAAI,CAAC,OAAO,CAAC;QACZ,WAAW,EACV,2LAA2L;KAC5L,CAAC,CACF;CACD,CAAC,CAAC;AAEH,MAAM,CAAC,MAAM,gCAAgC,GAAG;IAC/C,OAAO,EAAE,iDAAiD;IAC1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AC,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;QACrD,GAAG,OAAO;QACV,UAAU,EAAE,OAAO,EAAE,UAAU,IAAI,yBAAyB,CAAC,EAAE,SAAS,EAAE,OAAO,EAAE,SAAS,EAAE,CAAC;KAC/F,CAAC,CAAC;AACJ,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 { type Static, Type } from \"typebox\";\nimport type { ExtensionContext, ToolDefinition } from \"../extensions/types.ts\";\nimport { TaskRuntime } from \"../tasks/runtime.ts\";\nimport type { TaskCompletion, TaskControl, TaskToolOutcome } from \"../tasks/types.ts\";\nimport {\n\ttype BashOperations,\n\ttype BashToolOptions,\n\tresolveSpawnContext,\n\tresolveTimeoutMs,\n\ttype ShellToolConfig,\n} from \"./bash.ts\";\nimport { createShellRenderers } from \"./renderers/bash.ts\";\nimport { runShellCommand } from \"./shell-execution.ts\";\nimport { createLocalBashOperations } from \"./shell-operations.ts\";\nimport { wrapToolDefinition } from \"./tool-definition-wrapper.ts\";\nimport { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, type TruncationResult } from \"./truncate.ts\";\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, and you are notified when it completes — do not poll for its result; 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\nconst bashOutputSchema = Type.Union([\n\tType.Object({\n\t\toutput: Type.String({\n\t\t\tdescription: \"Combined stdout and stderr, up to 1 MiB, keeping head and tail when truncated.\",\n\t\t}),\n\t\ttruncated: Type.Boolean(),\n\t\tfull_output_path: Type.Optional(Type.String()),\n\t\texit_code: Type.Number(),\n\t\twall_time_seconds: Type.Number(),\n\t}),\n\tType.Object({ task_id: Type.String(), status: Type.String() }),\n]);\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\nexport type BashRenderState = {\n\tdispose?: () => void;\n};\n\n/** Translate terminal shell failures to the native foreground tool contract once. */\nfunction shellToolResult(completion: TaskCompletion<BashToolDetails | undefined>) {\n\tconst status = completion.status;\n\tif (completion.result.structuredContent) return completion.result;\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 new Error(message);\n\t}\n\treturn completion.result;\n}\n\nexport function createShellToolDefinition(\n\tcwd: string,\n\tconfig: ShellToolConfig,\n\toptions: BashToolOptions & { operations: BashOperations },\n): ToolDefinition<typeof bashSchema, BashToolDetails | undefined, BashRenderState> {\n\tconst ops = options.operations;\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 tasks read to inspect output, tasks wait with an ID for one task or without one for any running task, and tasks kill to stop it. Steering interrupts only a wait, never execution. Background output is limited to 20 MiB; an expired tasks 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\toutputSchema: bashOutputSchema,\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 sessionTasks = ctx?.tasks;\n\t\t\tif (sessionTasks?.closed) throw new Error(\"Task service is closed\");\n\t\t\tif (!sessionTasks && background)\n\t\t\t\tthrow new Error(\"Background execution is not available in this host. No command was started.\");\n\t\t\t// Without a session the command still runs as a task, on a throwaway runtime that never backgrounds.\n\t\t\tconst standalone = sessionTasks ? undefined : new TaskRuntime();\n\t\t\tconst run = async (\n\t\t\t\tcontrol: TaskControl<BashToolDetails | undefined>,\n\t\t\t): Promise<TaskCompletion<BashToolDetails | undefined>> => {\n\t\t\t\tif (control.signal.aborted) throw new Error(\"Command aborted\");\n\t\t\t\tresolveTimeoutMs(timeout);\n\t\t\t\tconst resolvedCommand = commandPrefix ? `${commandPrefix}\\n${command}` : command;\n\t\t\t\tconst spawnContext = resolveSpawnContext(\n\t\t\t\t\tresolvedCommand,\n\t\t\t\t\tctx?.cwd || cwd,\n\t\t\t\t\tspawnHook,\n\t\t\t\t\texposeSessionEnvironment,\n\t\t\t\t\tctx,\n\t\t\t\t);\n\t\t\t\t// A setup throw settles the task as failed, or cancelled once its signal fired.\n\t\t\t\treturn await runShellCommand({\n\t\t\t\t\toperations: ops,\n\t\t\t\t\tcontext: spawnContext,\n\t\t\t\t\ttempFilePrefix: config.tempFilePrefix,\n\t\t\t\t\ttimeout,\n\t\t\t\t\tcontrol,\n\t\t\t\t\ttaskLog: sessionTasks !== undefined,\n\t\t\t\t});\n\t\t\t};\n\t\t\tlet outcome: TaskToolOutcome<BashToolDetails | undefined>;\n\t\t\ttry {\n\t\t\t\toutcome = await (sessionTasks ?? standalone!).execute<BashToolDetails | undefined>({\n\t\t\t\t\tkind: config.name,\n\t\t\t\t\tlabel: config.shellName[0]!.toUpperCase() + config.shellName.slice(1),\n\t\t\t\t\ttitle: command,\n\t\t\t\t\tinput: { label: \"Command\", text: command, truncated: false, language: config.name },\n\t\t\t\t\tfacts: [[\"Directory\", ctx?.cwd || cwd]],\n\t\t\t\t\ttoolCallId,\n\t\t\t\t\tbackground,\n\t\t\t\t\tsignal: parentSignal,\n\t\t\t\t\tonUpdate: originalUpdate,\n\t\t\t\t\trun,\n\t\t\t\t});\n\t\t\t} finally {\n\t\t\t\tstandalone?.close();\n\t\t\t}\n\t\t\tif (outcome.kind === \"result\") return shellToolResult(outcome);\n\t\t\tconst tail = `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 tasks read to inspect output, tasks wait only when your next step is blocked on a result (one ID or any running task; prefer foreground next time in that case), or tasks kill to stop it.`;\n\t\t\t// Shell execution can become background work in two ways, and the model has to know which\n\t\t\t// one it got: a submitted background command starts from an empty log, while a detached\n\t\t\t// one already holds output and keeps its original timeout.\n\t\t\tconst handoff =\n\t\t\t\tbackground === true\n\t\t\t\t\t? `Command handed to background. ${tail}`\n\t\t\t\t\t: `Command moved to the background while it was running, by the user. The execution continues unchanged — no restart, and a supplied timeout is still measured from command startup. Output produced so far is already in the log, so tasks read now returns partial output, not a fresh start. ${tail}`;\n\t\t\treturn {\n\t\t\t\tstructuredContent: { task_id: outcome.task.id, status: outcome.task.status },\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: `${handoff}${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): ReturnType<typeof createShellToolDefinition> {\n\treturn createShellToolDefinition(cwd, bashToolConfig, {\n\t\t...options,\n\t\toperations: options?.operations ?? createLocalBashOperations({ shellPath: options?.shellPath }),\n\t});\n}\n\nexport function createBashTool(cwd: string, options?: BashToolOptions) {\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"]}
@@ -11,18 +11,19 @@ export declare function createUsageTotals(): UsageTotals;
11
11
  export declare function addUsageToTotals(totals: UsageTotals, usage: Usage): void;
12
12
  /** Sum of two usages, keeping the optional token splits when either side reports them. */
13
13
  export declare function combineUsage(first: Usage, second: Usage): Usage;
14
+ export declare function emptyUsage(): Usage;
15
+ /** Share of one request's prompt served from cache, or undefined when it reported no cache activity. */
16
+ export declare function cacheHitPercent({ input, cacheRead, cacheWrite, }: Pick<Usage, "input" | "cacheRead" | "cacheWrite">): number | undefined;
14
17
  export interface UsageCostBreakdownEntry {
15
18
  key: string;
16
19
  cost: number;
17
20
  tokens: number;
18
21
  }
19
- export declare const TASK_USAGE_TYPE = "task-usage";
20
22
  export interface TaskUsageRecord {
21
- version: 1;
22
23
  taskId: string;
23
24
  usage: Usage;
24
25
  }
25
- /** Validate persisted ledger data and return only its serializable accounting fields. */
26
+ /** Validate a task record's usage settlement and return only its serializable accounting fields. */
26
27
  export declare function getTaskUsageRecord(entry: SessionEntry): TaskUsageRecord | undefined;
27
28
  /** Legacy usage plus the first valid ledger record per task. Managed results omit usage. */
28
29
  export declare function getAccountedUsages(entries: readonly SessionEntry[]): Usage[];
@@ -1 +1 @@
1
- {"version":3,"file":"usage-totals.d.ts","sourceRoot":"","sources":["../../src/core/usage-totals.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,8BAA8B,CAAC;AAC1D,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAC;AAEzD,MAAM,WAAW,WAAW;IAC3B,KAAK,EAAE,MAAM,CAAC;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