@caupulican/pi-adaptative 0.80.103 → 0.81.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (401) hide show
  1. package/CHANGELOG.md +120 -0
  2. package/dist/cli/session-picker.d.ts +1 -1
  3. package/dist/cli/session-picker.d.ts.map +1 -1
  4. package/dist/cli/session-picker.js.map +1 -1
  5. package/dist/cli.d.ts.map +1 -1
  6. package/dist/cli.js +7 -1
  7. package/dist/cli.js.map +1 -1
  8. package/dist/core/agent-session-runtime.d.ts +1 -1
  9. package/dist/core/agent-session-runtime.d.ts.map +1 -1
  10. package/dist/core/agent-session-runtime.js +6 -6
  11. package/dist/core/agent-session-runtime.js.map +1 -1
  12. package/dist/core/agent-session-services.d.ts +1 -1
  13. package/dist/core/agent-session-services.d.ts.map +1 -1
  14. package/dist/core/agent-session-services.js.map +1 -1
  15. package/dist/core/agent-session.d.ts +152 -512
  16. package/dist/core/agent-session.d.ts.map +1 -1
  17. package/dist/core/agent-session.js +635 -4590
  18. package/dist/core/agent-session.js.map +1 -1
  19. package/dist/core/autonomy/session-lane-record.d.ts +1 -1
  20. package/dist/core/autonomy/session-lane-record.d.ts.map +1 -1
  21. package/dist/core/autonomy/session-lane-record.js.map +1 -1
  22. package/dist/core/autonomy/status.d.ts +1 -0
  23. package/dist/core/autonomy/status.d.ts.map +1 -1
  24. package/dist/core/autonomy/status.js +1 -0
  25. package/dist/core/autonomy/status.js.map +1 -1
  26. package/dist/core/autonomy-telemetry.d.ts +80 -0
  27. package/dist/core/autonomy-telemetry.d.ts.map +1 -0
  28. package/dist/core/autonomy-telemetry.js +266 -0
  29. package/dist/core/autonomy-telemetry.js.map +1 -0
  30. package/dist/core/background-lane-controller.d.ts +186 -0
  31. package/dist/core/background-lane-controller.d.ts.map +1 -0
  32. package/dist/core/background-lane-controller.js +691 -0
  33. package/dist/core/background-lane-controller.js.map +1 -0
  34. package/dist/core/bash-execution-controller.d.ts +51 -0
  35. package/dist/core/bash-execution-controller.d.ts.map +1 -0
  36. package/dist/core/bash-execution-controller.js +96 -0
  37. package/dist/core/bash-execution-controller.js.map +1 -0
  38. package/dist/core/bash-executor.d.ts.map +1 -1
  39. package/dist/core/bash-executor.js +9 -2
  40. package/dist/core/bash-executor.js.map +1 -1
  41. package/dist/core/compaction-support.d.ts +56 -0
  42. package/dist/core/compaction-support.d.ts.map +1 -0
  43. package/dist/core/compaction-support.js +99 -0
  44. package/dist/core/compaction-support.js.map +1 -0
  45. package/dist/core/context/artifact-retrieval.d.ts +1 -1
  46. package/dist/core/context/artifact-retrieval.d.ts.map +1 -1
  47. package/dist/core/context/artifact-retrieval.js +1 -1
  48. package/dist/core/context/artifact-retrieval.js.map +1 -1
  49. package/dist/core/context/context-composition.d.ts.map +1 -1
  50. package/dist/core/context/context-composition.js +1 -1
  51. package/dist/core/context/context-composition.js.map +1 -1
  52. package/dist/core/context/tool-output-packer.d.ts +1 -1
  53. package/dist/core/context/tool-output-packer.d.ts.map +1 -1
  54. package/dist/core/context/tool-output-packer.js +1 -1
  55. package/dist/core/context/tool-output-packer.js.map +1 -1
  56. package/dist/core/context-gc.d.ts.map +1 -1
  57. package/dist/core/context-gc.js +1 -1
  58. package/dist/core/context-gc.js.map +1 -1
  59. package/dist/core/context-pipeline.d.ts +223 -0
  60. package/dist/core/context-pipeline.d.ts.map +1 -0
  61. package/dist/core/context-pipeline.js +594 -0
  62. package/dist/core/context-pipeline.js.map +1 -0
  63. package/dist/core/cost/daily-usage.d.ts +1 -1
  64. package/dist/core/cost/daily-usage.d.ts.map +1 -1
  65. package/dist/core/cost/daily-usage.js +1 -1
  66. package/dist/core/cost/daily-usage.js.map +1 -1
  67. package/dist/core/cost/session-usage.d.ts +1 -1
  68. package/dist/core/cost/session-usage.d.ts.map +1 -1
  69. package/dist/core/cost/session-usage.js +1 -1
  70. package/dist/core/cost/session-usage.js.map +1 -1
  71. package/dist/core/delegation/session-worker-result.d.ts +1 -1
  72. package/dist/core/delegation/session-worker-result.d.ts.map +1 -1
  73. package/dist/core/delegation/session-worker-result.js.map +1 -1
  74. package/dist/core/exec.d.ts +2 -0
  75. package/dist/core/exec.d.ts.map +1 -1
  76. package/dist/core/exec.js +15 -9
  77. package/dist/core/exec.js.map +1 -1
  78. package/dist/core/export-html/index.d.ts +1 -1
  79. package/dist/core/export-html/index.d.ts.map +1 -1
  80. package/dist/core/export-html/index.js +2 -2
  81. package/dist/core/export-html/index.js.map +1 -1
  82. package/dist/core/extensions/builtin.d.ts.map +1 -1
  83. package/dist/core/extensions/builtin.js +2 -2
  84. package/dist/core/extensions/builtin.js.map +1 -1
  85. package/dist/core/extensions/runner.d.ts +1 -1
  86. package/dist/core/extensions/runner.d.ts.map +1 -1
  87. package/dist/core/extensions/runner.js.map +1 -1
  88. package/dist/core/extensions/types.d.ts +2 -4
  89. package/dist/core/extensions/types.d.ts.map +1 -1
  90. package/dist/core/extensions/types.js.map +1 -1
  91. package/dist/core/goal-loop-controller.d.ts +24 -0
  92. package/dist/core/goal-loop-controller.d.ts.map +1 -0
  93. package/dist/core/goal-loop-controller.js +83 -0
  94. package/dist/core/goal-loop-controller.js.map +1 -0
  95. package/dist/core/goals/goal-runtime-snapshot.d.ts +1 -1
  96. package/dist/core/goals/goal-runtime-snapshot.d.ts.map +1 -1
  97. package/dist/core/goals/goal-runtime-snapshot.js.map +1 -1
  98. package/dist/core/goals/session-goal-state.d.ts +1 -1
  99. package/dist/core/goals/session-goal-state.d.ts.map +1 -1
  100. package/dist/core/goals/session-goal-state.js.map +1 -1
  101. package/dist/core/index.d.ts +1 -1
  102. package/dist/core/index.d.ts.map +1 -1
  103. package/dist/core/index.js.map +1 -1
  104. package/dist/core/learning/learning-audit.d.ts +1 -1
  105. package/dist/core/learning/learning-audit.d.ts.map +1 -1
  106. package/dist/core/learning/learning-audit.js.map +1 -1
  107. package/dist/core/learning/session-learning-decision.d.ts +1 -1
  108. package/dist/core/learning/session-learning-decision.d.ts.map +1 -1
  109. package/dist/core/learning/session-learning-decision.js.map +1 -1
  110. package/dist/core/local-runtime-controller.d.ts +99 -0
  111. package/dist/core/local-runtime-controller.d.ts.map +1 -0
  112. package/dist/core/local-runtime-controller.js +214 -0
  113. package/dist/core/local-runtime-controller.js.map +1 -0
  114. package/dist/core/memory/providers/transcript-recall.d.ts.map +1 -1
  115. package/dist/core/memory/providers/transcript-recall.js +1 -1
  116. package/dist/core/memory/providers/transcript-recall.js.map +1 -1
  117. package/dist/core/memory-controller.d.ts +139 -0
  118. package/dist/core/memory-controller.d.ts.map +1 -0
  119. package/dist/core/memory-controller.js +323 -0
  120. package/dist/core/memory-controller.js.map +1 -0
  121. package/dist/core/model-router/status.d.ts +1 -1
  122. package/dist/core/model-router/status.d.ts.map +1 -1
  123. package/dist/core/model-router/status.js.map +1 -1
  124. package/dist/core/model-router-controller.d.ts +140 -0
  125. package/dist/core/model-router-controller.d.ts.map +1 -0
  126. package/dist/core/model-router-controller.js +623 -0
  127. package/dist/core/model-router-controller.js.map +1 -0
  128. package/dist/core/model-selection-controller.d.ts +95 -0
  129. package/dist/core/model-selection-controller.d.ts.map +1 -0
  130. package/dist/core/model-selection-controller.js +252 -0
  131. package/dist/core/model-selection-controller.js.map +1 -0
  132. package/dist/core/models/model-ref.d.ts +13 -0
  133. package/dist/core/models/model-ref.d.ts.map +1 -1
  134. package/dist/core/models/model-ref.js +22 -0
  135. package/dist/core/models/model-ref.js.map +1 -1
  136. package/dist/core/profile-filter-controller.d.ts +77 -0
  137. package/dist/core/profile-filter-controller.d.ts.map +1 -0
  138. package/dist/core/profile-filter-controller.js +159 -0
  139. package/dist/core/profile-filter-controller.js.map +1 -0
  140. package/dist/core/reflection-controller.d.ts +111 -0
  141. package/dist/core/reflection-controller.d.ts.map +1 -0
  142. package/dist/core/reflection-controller.js +412 -0
  143. package/dist/core/reflection-controller.js.map +1 -0
  144. package/dist/core/research/model-fitness.d.ts +12 -0
  145. package/dist/core/research/model-fitness.d.ts.map +1 -1
  146. package/dist/core/research/model-fitness.js +21 -0
  147. package/dist/core/research/model-fitness.js.map +1 -1
  148. package/dist/core/research/session-evidence-bundle.d.ts +1 -1
  149. package/dist/core/research/session-evidence-bundle.d.ts.map +1 -1
  150. package/dist/core/research/session-evidence-bundle.js.map +1 -1
  151. package/dist/core/runtime-builder.d.ts +222 -0
  152. package/dist/core/runtime-builder.d.ts.map +1 -0
  153. package/dist/core/runtime-builder.js +640 -0
  154. package/dist/core/runtime-builder.js.map +1 -0
  155. package/dist/core/sdk.d.ts +2 -2
  156. package/dist/core/sdk.d.ts.map +1 -1
  157. package/dist/core/sdk.js +3 -4
  158. package/dist/core/sdk.js.map +1 -1
  159. package/dist/core/session-analytics.d.ts +96 -0
  160. package/dist/core/session-analytics.d.ts.map +1 -0
  161. package/dist/core/session-analytics.js +331 -0
  162. package/dist/core/session-analytics.js.map +1 -0
  163. package/dist/core/session-manager-factory.d.ts +18 -0
  164. package/dist/core/session-manager-factory.d.ts.map +1 -0
  165. package/dist/core/session-manager-factory.js +32 -0
  166. package/dist/core/session-manager-factory.js.map +1 -0
  167. package/dist/core/session-tree-navigator.d.ts +68 -0
  168. package/dist/core/session-tree-navigator.d.ts.map +1 -0
  169. package/dist/core/session-tree-navigator.js +217 -0
  170. package/dist/core/session-tree-navigator.js.map +1 -0
  171. package/dist/core/system-prompt-builder.d.ts +63 -0
  172. package/dist/core/system-prompt-builder.d.ts.map +1 -0
  173. package/dist/core/system-prompt-builder.js +181 -0
  174. package/dist/core/system-prompt-builder.js.map +1 -0
  175. package/dist/core/tool-gate-controller.d.ts +36 -0
  176. package/dist/core/tool-gate-controller.d.ts.map +1 -0
  177. package/dist/core/tool-gate-controller.js +94 -0
  178. package/dist/core/tool-gate-controller.js.map +1 -0
  179. package/dist/core/tools/artifact-retrieve.d.ts.map +1 -1
  180. package/dist/core/tools/artifact-retrieve.js +1 -1
  181. package/dist/core/tools/artifact-retrieve.js.map +1 -1
  182. package/dist/core/tools/bash.d.ts +4 -2
  183. package/dist/core/tools/bash.d.ts.map +1 -1
  184. package/dist/core/tools/bash.js +49 -7
  185. package/dist/core/tools/bash.js.map +1 -1
  186. package/dist/core/tools/file-mutation-queue.d.ts +6 -0
  187. package/dist/core/tools/file-mutation-queue.d.ts.map +1 -1
  188. package/dist/core/tools/file-mutation-queue.js +61 -1
  189. package/dist/core/tools/file-mutation-queue.js.map +1 -1
  190. package/dist/core/tools/find.d.ts +1 -1
  191. package/dist/core/tools/find.d.ts.map +1 -1
  192. package/dist/core/tools/find.js +1 -1
  193. package/dist/core/tools/find.js.map +1 -1
  194. package/dist/core/tools/grep.d.ts +1 -1
  195. package/dist/core/tools/grep.d.ts.map +1 -1
  196. package/dist/core/tools/grep.js +1 -1
  197. package/dist/core/tools/grep.js.map +1 -1
  198. package/dist/core/tools/index.d.ts +1 -1
  199. package/dist/core/tools/index.d.ts.map +1 -1
  200. package/dist/core/tools/index.js +1 -1
  201. package/dist/core/tools/index.js.map +1 -1
  202. package/dist/core/tools/ls.d.ts +1 -1
  203. package/dist/core/tools/ls.d.ts.map +1 -1
  204. package/dist/core/tools/ls.js +1 -1
  205. package/dist/core/tools/ls.js.map +1 -1
  206. package/dist/core/tools/output-accumulator.d.ts +1 -1
  207. package/dist/core/tools/output-accumulator.d.ts.map +1 -1
  208. package/dist/core/tools/output-accumulator.js +1 -1
  209. package/dist/core/tools/output-accumulator.js.map +1 -1
  210. package/dist/core/tools/read.d.ts +1 -1
  211. package/dist/core/tools/read.d.ts.map +1 -1
  212. package/dist/core/tools/read.js +1 -1
  213. package/dist/core/tools/read.js.map +1 -1
  214. package/dist/core/tools/render-utils.d.ts.map +1 -1
  215. package/dist/core/tools/render-utils.js +1 -1
  216. package/dist/core/tools/render-utils.js.map +1 -1
  217. package/dist/index.d.ts +2 -3
  218. package/dist/index.d.ts.map +1 -1
  219. package/dist/index.js +3 -4
  220. package/dist/index.js.map +1 -1
  221. package/dist/main.d.ts.map +1 -1
  222. package/dist/main.js +13 -12
  223. package/dist/main.js.map +1 -1
  224. package/dist/modes/interactive/auth-dialogs-controller.d.ts +59 -0
  225. package/dist/modes/interactive/auth-dialogs-controller.d.ts.map +1 -0
  226. package/dist/modes/interactive/auth-dialogs-controller.js +398 -0
  227. package/dist/modes/interactive/auth-dialogs-controller.js.map +1 -0
  228. package/dist/modes/interactive/auto-learn-controller.d.ts +168 -0
  229. package/dist/modes/interactive/auto-learn-controller.d.ts.map +1 -0
  230. package/dist/modes/interactive/auto-learn-controller.js +1239 -0
  231. package/dist/modes/interactive/auto-learn-controller.js.map +1 -0
  232. package/dist/modes/interactive/autocomplete-provider.d.ts +26 -0
  233. package/dist/modes/interactive/autocomplete-provider.d.ts.map +1 -0
  234. package/dist/modes/interactive/autocomplete-provider.js +103 -0
  235. package/dist/modes/interactive/autocomplete-provider.js.map +1 -0
  236. package/dist/modes/interactive/autonomy-commands.d.ts +38 -0
  237. package/dist/modes/interactive/autonomy-commands.d.ts.map +1 -0
  238. package/dist/modes/interactive/autonomy-commands.js +142 -0
  239. package/dist/modes/interactive/autonomy-commands.js.map +1 -0
  240. package/dist/modes/interactive/clipboard-input.d.ts +37 -0
  241. package/dist/modes/interactive/clipboard-input.d.ts.map +1 -0
  242. package/dist/modes/interactive/clipboard-input.js +59 -0
  243. package/dist/modes/interactive/clipboard-input.js.map +1 -0
  244. package/dist/modes/interactive/compaction-queue.d.ts +30 -0
  245. package/dist/modes/interactive/compaction-queue.d.ts.map +1 -0
  246. package/dist/modes/interactive/compaction-queue.js +91 -0
  247. package/dist/modes/interactive/compaction-queue.js.map +1 -0
  248. package/dist/modes/interactive/components/bash-execution.d.ts +1 -1
  249. package/dist/modes/interactive/components/bash-execution.d.ts.map +1 -1
  250. package/dist/modes/interactive/components/bash-execution.js +1 -1
  251. package/dist/modes/interactive/components/bash-execution.js.map +1 -1
  252. package/dist/modes/interactive/components/branch-summary-message.d.ts +1 -1
  253. package/dist/modes/interactive/components/branch-summary-message.d.ts.map +1 -1
  254. package/dist/modes/interactive/components/branch-summary-message.js.map +1 -1
  255. package/dist/modes/interactive/components/compaction-summary-message.d.ts +1 -1
  256. package/dist/modes/interactive/components/compaction-summary-message.d.ts.map +1 -1
  257. package/dist/modes/interactive/components/compaction-summary-message.js.map +1 -1
  258. package/dist/modes/interactive/components/custom-message.d.ts +1 -1
  259. package/dist/modes/interactive/components/custom-message.d.ts.map +1 -1
  260. package/dist/modes/interactive/components/custom-message.js.map +1 -1
  261. package/dist/modes/interactive/components/session-selector-search.d.ts +1 -1
  262. package/dist/modes/interactive/components/session-selector-search.d.ts.map +1 -1
  263. package/dist/modes/interactive/components/session-selector-search.js.map +1 -1
  264. package/dist/modes/interactive/components/session-selector.d.ts +1 -1
  265. package/dist/modes/interactive/components/session-selector.d.ts.map +1 -1
  266. package/dist/modes/interactive/components/session-selector.js.map +1 -1
  267. package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
  268. package/dist/modes/interactive/components/tool-execution.js +2 -2
  269. package/dist/modes/interactive/components/tool-execution.js.map +1 -1
  270. package/dist/modes/interactive/components/tree-selector.d.ts +1 -1
  271. package/dist/modes/interactive/components/tree-selector.d.ts.map +1 -1
  272. package/dist/modes/interactive/components/tree-selector.js.map +1 -1
  273. package/dist/modes/interactive/config-backup.d.ts +27 -0
  274. package/dist/modes/interactive/config-backup.d.ts.map +1 -0
  275. package/dist/modes/interactive/config-backup.js +146 -0
  276. package/dist/modes/interactive/config-backup.js.map +1 -0
  277. package/dist/modes/interactive/editor-overlay-host.d.ts +48 -0
  278. package/dist/modes/interactive/editor-overlay-host.d.ts.map +1 -0
  279. package/dist/modes/interactive/editor-overlay-host.js +43 -0
  280. package/dist/modes/interactive/editor-overlay-host.js.map +1 -0
  281. package/dist/modes/interactive/extension-ui-host.d.ts +165 -0
  282. package/dist/modes/interactive/extension-ui-host.d.ts.map +1 -0
  283. package/dist/modes/interactive/extension-ui-host.js +610 -0
  284. package/dist/modes/interactive/extension-ui-host.js.map +1 -0
  285. package/dist/modes/interactive/external-editor.d.ts +18 -0
  286. package/dist/modes/interactive/external-editor.d.ts.map +1 -0
  287. package/dist/modes/interactive/external-editor.js +107 -0
  288. package/dist/modes/interactive/external-editor.js.map +1 -0
  289. package/dist/modes/interactive/history-reload-math.d.ts +24 -0
  290. package/dist/modes/interactive/history-reload-math.d.ts.map +1 -0
  291. package/dist/modes/interactive/history-reload-math.js +129 -0
  292. package/dist/modes/interactive/history-reload-math.js.map +1 -0
  293. package/dist/modes/interactive/interactive-mode.d.ts +22 -238
  294. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  295. package/dist/modes/interactive/interactive-mode.js +714 -5910
  296. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  297. package/dist/modes/interactive/key-handlers.d.ts +46 -0
  298. package/dist/modes/interactive/key-handlers.d.ts.map +1 -0
  299. package/dist/modes/interactive/key-handlers.js +80 -0
  300. package/dist/modes/interactive/key-handlers.js.map +1 -0
  301. package/dist/modes/interactive/local-model-commands.d.ts +68 -0
  302. package/dist/modes/interactive/local-model-commands.d.ts.map +1 -0
  303. package/dist/modes/interactive/local-model-commands.js +288 -0
  304. package/dist/modes/interactive/local-model-commands.js.map +1 -0
  305. package/dist/modes/interactive/profile-menu-controller.d.ts +77 -0
  306. package/dist/modes/interactive/profile-menu-controller.d.ts.map +1 -0
  307. package/dist/modes/interactive/profile-menu-controller.js +917 -0
  308. package/dist/modes/interactive/profile-menu-controller.js.map +1 -0
  309. package/dist/modes/interactive/report-commands.d.ts +46 -0
  310. package/dist/modes/interactive/report-commands.d.ts.map +1 -0
  311. package/dist/modes/interactive/report-commands.js +255 -0
  312. package/dist/modes/interactive/report-commands.js.map +1 -0
  313. package/dist/modes/interactive/resource-display.d.ts +73 -0
  314. package/dist/modes/interactive/resource-display.d.ts.map +1 -0
  315. package/dist/modes/interactive/resource-display.js +278 -0
  316. package/dist/modes/interactive/resource-display.js.map +1 -0
  317. package/dist/modes/interactive/resource-shell-commands.d.ts +64 -0
  318. package/dist/modes/interactive/resource-shell-commands.d.ts.map +1 -0
  319. package/dist/modes/interactive/resource-shell-commands.js +202 -0
  320. package/dist/modes/interactive/resource-shell-commands.js.map +1 -0
  321. package/dist/modes/interactive/session-flow-commands.d.ts +139 -0
  322. package/dist/modes/interactive/session-flow-commands.d.ts.map +1 -0
  323. package/dist/modes/interactive/session-flow-commands.js +458 -0
  324. package/dist/modes/interactive/session-flow-commands.js.map +1 -0
  325. package/dist/modes/interactive/session-io-commands.d.ts +73 -0
  326. package/dist/modes/interactive/session-io-commands.d.ts.map +1 -0
  327. package/dist/modes/interactive/session-io-commands.js +202 -0
  328. package/dist/modes/interactive/session-io-commands.js.map +1 -0
  329. package/dist/modes/interactive/settings-selector-flow.d.ts +42 -0
  330. package/dist/modes/interactive/settings-selector-flow.d.ts.map +1 -0
  331. package/dist/modes/interactive/settings-selector-flow.js +287 -0
  332. package/dist/modes/interactive/settings-selector-flow.js.map +1 -0
  333. package/dist/modes/interactive/signal-lifecycle.d.ts +55 -0
  334. package/dist/modes/interactive/signal-lifecycle.d.ts.map +1 -0
  335. package/dist/modes/interactive/signal-lifecycle.js +177 -0
  336. package/dist/modes/interactive/signal-lifecycle.js.map +1 -0
  337. package/dist/modes/interactive/startup-checks.d.ts +38 -0
  338. package/dist/modes/interactive/startup-checks.d.ts.map +1 -0
  339. package/dist/modes/interactive/startup-checks.js +189 -0
  340. package/dist/modes/interactive/startup-checks.js.map +1 -0
  341. package/dist/modes/rpc/rpc-client.d.ts +1 -1
  342. package/dist/modes/rpc/rpc-client.d.ts.map +1 -1
  343. package/dist/modes/rpc/rpc-client.js.map +1 -1
  344. package/dist/modes/rpc/rpc-types.d.ts +1 -1
  345. package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
  346. package/dist/modes/rpc/rpc-types.js.map +1 -1
  347. package/dist/utils/paths.d.ts +2 -14
  348. package/dist/utils/paths.d.ts.map +1 -1
  349. package/dist/utils/paths.js +5 -30
  350. package/dist/utils/paths.js.map +1 -1
  351. package/dist/utils/process-memory.d.ts +8 -0
  352. package/dist/utils/process-memory.d.ts.map +1 -0
  353. package/dist/utils/process-memory.js +11 -0
  354. package/dist/utils/process-memory.js.map +1 -0
  355. package/dist/utils/shell.d.ts +0 -9
  356. package/dist/utils/shell.d.ts.map +1 -1
  357. package/dist/utils/shell.js +0 -37
  358. package/dist/utils/shell.js.map +1 -1
  359. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  360. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  361. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  362. package/examples/extensions/sandbox/package-lock.json +2 -2
  363. package/examples/extensions/sandbox/package.json +1 -1
  364. package/examples/extensions/with-deps/package-lock.json +2 -2
  365. package/examples/extensions/with-deps/package.json +1 -1
  366. package/examples/sdk/11-sessions.ts +8 -8
  367. package/examples/sdk/13-session-runtime.ts +1 -1
  368. package/npm-shrinkwrap.json +12 -12
  369. package/package.json +4 -4
  370. package/dist/core/compaction/branch-summarization.d.ts +0 -88
  371. package/dist/core/compaction/branch-summarization.d.ts.map +0 -1
  372. package/dist/core/compaction/branch-summarization.js +0 -243
  373. package/dist/core/compaction/branch-summarization.js.map +0 -1
  374. package/dist/core/compaction/compaction.d.ts +0 -143
  375. package/dist/core/compaction/compaction.d.ts.map +0 -1
  376. package/dist/core/compaction/compaction.js +0 -659
  377. package/dist/core/compaction/compaction.js.map +0 -1
  378. package/dist/core/compaction/index.d.ts +0 -7
  379. package/dist/core/compaction/index.d.ts.map +0 -1
  380. package/dist/core/compaction/index.js +0 -7
  381. package/dist/core/compaction/index.js.map +0 -1
  382. package/dist/core/compaction/utils.d.ts +0 -38
  383. package/dist/core/compaction/utils.d.ts.map +0 -1
  384. package/dist/core/compaction/utils.js +0 -153
  385. package/dist/core/compaction/utils.js.map +0 -1
  386. package/dist/core/message-retention.d.ts +0 -26
  387. package/dist/core/message-retention.d.ts.map +0 -1
  388. package/dist/core/message-retention.js +0 -95
  389. package/dist/core/message-retention.js.map +0 -1
  390. package/dist/core/messages.d.ts +0 -77
  391. package/dist/core/messages.d.ts.map +0 -1
  392. package/dist/core/messages.js +0 -123
  393. package/dist/core/messages.js.map +0 -1
  394. package/dist/core/session-manager.d.ts +0 -337
  395. package/dist/core/session-manager.d.ts.map +0 -1
  396. package/dist/core/session-manager.js +0 -1328
  397. package/dist/core/session-manager.js.map +0 -1
  398. package/dist/core/tools/truncate.d.ts +0 -70
  399. package/dist/core/tools/truncate.d.ts.map +0 -1
  400. package/dist/core/tools/truncate.js +0 -215
  401. package/dist/core/tools/truncate.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"background-lane-controller.js","sourceRoot":"","sources":["../../src/core/background-lane-controller.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAeH,OAAO,EAAmB,WAAW,EAAE,MAAM,4BAA4B,CAAC;AAC1E,OAAO,EAAE,wBAAwB,EAAE,sBAAsB,EAAE,MAAM,mCAAmC,CAAC;AACrG,OAAO,EAAE,2BAA2B,EAAE,MAAM,+BAA+B,CAAC;AAC5E,OAAO,EAAE,8BAA8B,EAA+B,MAAM,gCAAgC,CAAC;AAC7G,OAAO,EAAE,kBAAkB,EAAE,MAAM,gCAAgC,CAAC;AACpE,OAAO,EAAE,SAAS,EAAE,MAAM,+BAA+B,CAAC;AAG1D,OAAO,EACN,4BAA4B,EAE5B,qCAAqC,GACrC,MAAM,uBAAuB,CAAC;AAE/B,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EAAE,YAAY,EAA4B,MAAM,2BAA2B,CAAC;AAEnF,OAAO,EAA2B,oBAAoB,EAAE,MAAM,6BAA6B,CAAC;AAC5F,OAAO,EAAE,WAAW,EAAE,MAAM,+BAA+B,CAAC;AAsD5D,MAAM,OAAO,wBAAwB;IACpC,+FAA+F;IACvF,sBAAsB,CAA4C;IAC1E,mGAAmG;IAC3F,qBAAqB,GAAG,KAAK,CAAC;IACtC,iGAAiG;IACzF,kBAAkB,CAA4C;IACtE,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,EAAE,MAAM,EAAE,CAAC;IAAA,CAClD;IAED,mGAAmG;IACnG,uBAAuB,GAA0B;QAChD,IAAI,CAAC;YACJ,OAAO,YAAY,CAAC,WAAW,CAAC,IAAI,CAAC,IAAI,CAAC,WAAW,EAAE,CAAC,CAAC,UAAU,EAAE,CAAC;QACvE,CAAC;QAAC,MAAM,CAAC;YACR,OAAO,EAAE,CAAC;QACX,CAAC;IAAA,CACD;CACD","sourcesContent":["/**\n * Background-lane controller: goal auto-continue, the research lane, scout-worker delegation, and\n * the model-fitness probe.\n *\n * Extracted verbatim from agent-session.ts (god-file decomposition). Owns the lane timers, the\n * single-flight guards, the last research-lane skip reason, the live {@link LaneTracker}, and the\n * session-lifetime abort controllers for in-flight research/worker passes. Everything else it needs\n * — the session manager, settings, model registry, live model, capability envelope, the goal\n * continuation LOOP, the isolated-completion primitive, spawned-usage accounting, and the telemetry\n * sink — is reached through narrow deps accessors rather than the whole AgentSession.\n *\n * Drive-loop boundary (deliberate): the idle triggers ({@link scheduleGoalAutoContinueFromIdle},\n * {@link scheduleResearchLaneFromIdle}) are invoked from the session's prompt tail as one-line\n * delegations; goal auto-continue itself only ever asks the session to `continueGoalLoop`, so this\n * controller never touches `prompt()`, the last-assistant-message, retry, or streaming state.\n */\n\nimport type { SessionManager } from \"@caupulican/pi-agent-core/node\";\nimport type { Api, Model, Usage } from \"@caupulican/pi-ai\";\nimport type {\n\tAgentSessionEvent,\n\tGoalContinuationLoopOptions,\n\tGoalContinuationLoopResult,\n\tIsolatedCompletionOptions,\n\tIsolatedCompletionResult,\n\tPromptOptions,\n\tResearchLaneRunOutcome,\n\tWorkerDelegationRunOutcome,\n} from \"./agent-session.ts\";\nimport type { CapabilityEnvelope, EvidenceBundle, WorkerRequest, WorkerResult } from \"./autonomy/contracts.ts\";\nimport { type LaneRecord, LaneTracker } from \"./autonomy/lane-tracker.ts\";\nimport { appendLaneRecordSnapshot, getLaneRecordSnapshots } from \"./autonomy/session-lane-record.ts\";\nimport { composeSubagentSystemPrompt } from \"./autonomy/subagent-prompt.ts\";\nimport { AUTONOMY_TELEMETRY_EVENT_TYPES, type AutonomyTelemetryEvent } from \"./autonomy/telemetry-events.ts\";\nimport { applyWorkerActions } from \"./delegation/worker-actions.ts\";\nimport { runWorker } from \"./delegation/worker-runner.ts\";\nimport type { GoalRuntimeSnapshot, GoalRuntimeSnapshotSettings } from \"./goals/goal-runtime-snapshot.ts\";\nimport type { GoalState } from \"./goals/goal-state.ts\";\nimport {\n\tderiveModelCapabilityProfile,\n\ttype ModelCapabilityProfile,\n\tscaleContinuationBudgetsForCapability,\n} from \"./model-capability.ts\";\nimport type { ModelRegistry } from \"./model-registry.ts\";\nimport { resolveCliModel } from \"./model-resolver.ts\";\nimport { FitnessStore, type StoredFitnessReport } from \"./models/fitness-store.ts\";\nimport type { NormalizedProfile } from \"./profile-registry.ts\";\nimport { type ModelFitnessReport, runModelFitnessProbe } from \"./research/model-fitness.ts\";\nimport { runResearch } from \"./research/research-runner.ts\";\nimport type { collectWorkspaceSources } from \"./research/workspace-collector.ts\";\nimport type { SettingsManager } from \"./settings-manager.ts\";\n\nexport interface BackgroundLaneControllerDeps {\n\t/** A disposed session must never schedule/persist a lane or continuation. */\n\tisDisposed(): boolean;\n\t/** Child sessions never run the idle research lane (only the top-level session drives autonomy). */\n\tisChildSession(): boolean;\n\t/** This session's id, for lane envelope ids and spawned-usage report ids. */\n\tgetSessionId(): string;\n\t/** The workspace root a lane runs relative to (worker path scope + research source collection). */\n\tgetCwd(): string;\n\t/** Root dir the host-keyed {@link FitnessStore} persists under. */\n\tgetAgentDir(): string;\n\t/** Session log: lane records read/append here and feed lane-history dedupe. */\n\tgetSessionManager(): SessionManager;\n\t/** Autonomy / research-lane / worker-delegation / model-capability settings + the profile registry. */\n\tgetSettingsManager(): SettingsManager;\n\t/** Resolves a configured lane model pattern against configured auth. */\n\tgetModelRegistry(): ModelRegistry;\n\t/** The session's current model — lanes inherit it unless a lane model is explicitly configured. */\n\tgetModel(): Model<Api> | undefined;\n\t/** Foreground cost ceiling — a lane budget is clamped to it, never exceeds it. */\n\tgetCapabilityEnvelope(): CapabilityEnvelope | undefined;\n\t/** Capability profile of the SESSION model (gates background lanes, scales continuation budgets). */\n\tgetModelCapabilityProfile(): ModelCapabilityProfile;\n\t/** Emits a session event (only `warning` from this controller). */\n\temit(event: AgentSessionEvent): void;\n\t/** G3/G8 telemetry sink (codes/ids only — never lane product text). */\n\temitAutonomyTelemetry(event: AutonomyTelemetryEvent): void;\n\t/** Durable goal state, if a goal is active (the research lane's demand source). */\n\tgetGoalStateSnapshot(): GoalState | undefined;\n\t/** Continuation gate + goal state for the idle autosteer scheduler. */\n\tgetGoalRuntimeSnapshot(settings: GoalRuntimeSnapshotSettings): GoalRuntimeSnapshot;\n\t/** Latest persisted evidence bundle, for research-lane dedupe. */\n\tgetEvidenceBundleSnapshot(): EvidenceBundle | undefined;\n\t/** Persist a research lane's evidence bundle to the session log. */\n\tsaveEvidenceBundleSnapshot(bundle: EvidenceBundle): string;\n\t/** Persist a worker delegation's result snapshot to the session log. */\n\tsaveWorkerResultSnapshot(result: WorkerResult, request?: WorkerRequest): string;\n\t/** Roll a lane's spawned usage into session accounting (idempotent per reportId). */\n\taddSpawnedUsage(\n\t\tusage: Usage,\n\t\topts?: { label?: string; sourceSessionId?: string; reportId?: string },\n\t): string | undefined;\n\t/** One-shot LLM call fully isolated from the main session — the lane execution primitive. */\n\trunIsolatedCompletion(opts: IsolatedCompletionOptions): Promise<IsolatedCompletionResult>;\n\t/** Drive-loop boundary: the session's bounded goal-continuation loop (owns `prompt()`, not us). */\n\tcontinueGoalLoop(options: GoalContinuationLoopOptions): Promise<GoalContinuationLoopResult>;\n\t/** Best-effort workspace evidence collection (silent-on-failure; [] preserves prior behavior). */\n\tcollectWorkspaceSources: typeof collectWorkspaceSources;\n}\n\nexport class BackgroundLaneController {\n\t/** Pending idle timer that starts bounded goal continuation after the session becomes idle. */\n\tprivate _goalAutoContinueTimer: ReturnType<typeof setTimeout> | undefined;\n\t/** Guards bounded idle autosteer so continuation prompts do not recursively trigger themselves. */\n\tprivate _isGoalAutoContinuing = false;\n\t/** Pending idle timer that starts an autonomous research pass after the session becomes idle. */\n\tprivate _researchLaneTimer: ReturnType<typeof setTimeout> | undefined;\n\t/** Single-flight guard: at most one research pass runs at a time per session. */\n\tprivate _isResearchLaneRunning = false;\n\t/** Why the last idle research-lane evaluation skipped, for /autonomy diagnostics. */\n\tprivate _lastResearchLaneSkipReason: string | undefined;\n\t/** Live lane registry — the real source for AutonomyStatusSnapshot.activeLaneCount. */\n\tprivate readonly _laneTracker = new LaneTracker();\n\t/** Session-lifetime abort for in-flight research passes (same pattern as _reflectionAbort). */\n\tprivate readonly _researchLaneAbort = new AbortController();\n\t/** Session-lifetime abort for in-flight delegated workers. */\n\tprivate readonly _workerDelegationAbort = new AbortController();\n\n\tprivate readonly deps: BackgroundLaneControllerDeps;\n\n\tconstructor(deps: BackgroundLaneControllerDeps) {\n\t\tthis.deps = deps;\n\t}\n\n\t/** Live lane records tracked by this process (running and terminal). */\n\tgetLaneRecords(): LaneRecord[] {\n\t\treturn this._laneTracker.getRecords();\n\t}\n\n\t/** Live count of active lanes — the real source for AutonomyStatusSnapshot.activeLaneCount. */\n\tgetActiveLaneCount(): number {\n\t\treturn this._laneTracker.getActiveCount();\n\t}\n\n\t/** Why the last idle research-lane evaluation skipped, for /autonomy diagnostics. */\n\tgetLastResearchLaneSkipReason(): string | undefined {\n\t\treturn this._lastResearchLaneSkipReason;\n\t}\n\n\t/** Abort any in-flight research pass or delegated worker (called on session dispose). */\n\tabortInFlightLanes(): void {\n\t\tthis._researchLaneAbort.abort();\n\t\tthis._workerDelegationAbort.abort();\n\t}\n\n\tclearGoalAutoContinueTimer(): void {\n\t\tif (this._goalAutoContinueTimer !== undefined) {\n\t\t\tclearTimeout(this._goalAutoContinueTimer);\n\t\t\tthis._goalAutoContinueTimer = undefined;\n\t\t}\n\t}\n\n\tscheduleGoalAutoContinueFromIdle(options?: PromptOptions): void {\n\t\tif (options?.autoContinueGoal === false || this._isGoalAutoContinuing || this.deps.isDisposed()) return;\n\n\t\t// Small-window models cannot afford multi-thousand-token continuation prompts per idle turn.\n\t\tif (!this.deps.getModelCapabilityProfile().backgroundLanesEnabled) return;\n\n\t\tconst { maxStallTurns, goalAutoContinue, goalAutoContinueDelayMs } = this.deps\n\t\t\t.getSettingsManager()\n\t\t\t.getAutonomySettings();\n\t\tif (!goalAutoContinue) return;\n\n\t\tconst snapshot = this.deps.getGoalRuntimeSnapshot({ maxStallTurns });\n\t\tif (snapshot.continuation.action !== \"continue\") return;\n\n\t\tthis.clearGoalAutoContinueTimer();\n\t\tthis._goalAutoContinueTimer = setTimeout(() => {\n\t\t\tthis._goalAutoContinueTimer = undefined;\n\t\t\tvoid this._runScheduledGoalAutoContinue();\n\t\t}, goalAutoContinueDelayMs);\n\n\t\tconst timer = this._goalAutoContinueTimer;\n\t\tif (typeof timer === \"object\" && timer && \"unref\" in timer) {\n\t\t\tconst { unref } = timer as { unref?: () => void };\n\t\t\tunref?.call(timer);\n\t\t}\n\t}\n\n\tprivate async _runScheduledGoalAutoContinue(): Promise<void> {\n\t\tif (this._isGoalAutoContinuing || this.deps.isDisposed()) return;\n\n\t\tconst { maxStallTurns, goalContinueTurns, goalContinueMaxWallClockMinutes, goalAutoContinue } = this.deps\n\t\t\t.getSettingsManager()\n\t\t\t.getAutonomySettings();\n\t\tif (!goalAutoContinue) return;\n\n\t\tconst snapshot = this.deps.getGoalRuntimeSnapshot({ maxStallTurns });\n\t\tif (snapshot.continuation.action !== \"continue\") return;\n\n\t\t// Lean-window models (16-32k) keep autosteer but at a reduced budget; full passes through.\n\t\tconst scaled = scaleContinuationBudgetsForCapability(this.deps.getModelCapabilityProfile(), {\n\t\t\tmaxTurns: goalContinueTurns,\n\t\t\tmaxWallClockMinutes: goalContinueMaxWallClockMinutes,\n\t\t});\n\n\t\tthis._isGoalAutoContinuing = true;\n\t\ttry {\n\t\t\tawait this.deps.continueGoalLoop({\n\t\t\t\tmaxTurns: scaled.maxTurns,\n\t\t\t\tmaxStallTurns,\n\t\t\t\tmaxWallClockMinutes: scaled.maxWallClockMinutes,\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\tthis.deps.emit({ type: \"warning\", message: `Goal auto-continuation failed: ${message}` });\n\t\t} finally {\n\t\t\tthis._isGoalAutoContinuing = false;\n\t\t}\n\t}\n\n\tclearResearchLaneTimer(): void {\n\t\tif (this._researchLaneTimer !== undefined) {\n\t\t\tclearTimeout(this._researchLaneTimer);\n\t\t\tthis._researchLaneTimer = undefined;\n\t\t}\n\t}\n\n\t/**\n\t * Derive the research demand from durable goal state: an active goal with open requirements,\n\t * deduplicated against the latest persisted bundle so the same requirement set is never\n\t * researched twice (the query is deterministic, so dedupe survives session reload).\n\t */\n\tprivate _buildResearchLaneDemand(): { query: string; context: string; goalId: string } | undefined {\n\t\tconst goal = this.deps.getGoalStateSnapshot();\n\t\tif (!goal || goal.status !== \"active\") {\n\t\t\tthis._lastResearchLaneSkipReason = \"no_active_goal\";\n\t\t\treturn undefined;\n\t\t}\n\t\tconst open = goal.requirements.filter((requirement) => requirement.status === \"open\");\n\t\tif (open.length === 0) {\n\t\t\tthis._lastResearchLaneSkipReason = \"no_open_requirements\";\n\t\t\treturn undefined;\n\t\t}\n\t\tconst query = `goal:${goal.goalId} requirements:${open\n\t\t\t.map((requirement) => requirement.id)\n\t\t\t.sort()\n\t\t\t.join(\",\")}`;\n\t\tif (this.deps.getEvidenceBundleSnapshot()?.query === query) {\n\t\t\tthis._lastResearchLaneSkipReason = \"recent_evidence_sufficient\";\n\t\t\treturn undefined;\n\t\t}\n\t\tconst context = [\n\t\t\t`Goal: ${goal.userGoal}`,\n\t\t\t\"Open requirements:\",\n\t\t\t...open.slice(0, 20).map((requirement) => `- ${requirement.text}`),\n\t\t].join(\"\\n\");\n\t\treturn { query, context, goalId: goal.goalId };\n\t}\n\n\t/**\n\t * Idle trigger for the autonomous research lane (mirrors {@link scheduleGoalAutoContinueFromIdle}).\n\t * All skips are recorded in `_lastResearchLaneSkipReason` and surfaced via diagnostics — the lane\n\t * informs, it never prompts or blocks the foreground.\n\t */\n\tscheduleResearchLaneFromIdle(): void {\n\t\tif (this._isResearchLaneRunning || this.deps.isDisposed() || this.deps.isChildSession()) return;\n\n\t\tif (!this.deps.getModelCapabilityProfile().backgroundLanesEnabled) {\n\t\t\tthis._lastResearchLaneSkipReason = \"model_context_too_small\";\n\t\t\treturn;\n\t\t}\n\n\t\tconst research = this.deps.getSettingsManager().getResearchLaneSettings();\n\t\tif (!research.enabled) {\n\t\t\tthis._lastResearchLaneSkipReason = \"research_lane_disabled\";\n\t\t\treturn;\n\t\t}\n\t\tconst { mode } = this.deps.getSettingsManager().getAutonomySettings();\n\t\tif (mode === \"off\") {\n\t\t\tthis._lastResearchLaneSkipReason = \"autonomy_mode_off\";\n\t\t\treturn;\n\t\t}\n\t\tconst priorRuns = getLaneRecordSnapshots(this.deps.getSessionManager().getEntries()).filter(\n\t\t\t(record) => record.type === \"research\",\n\t\t).length;\n\t\tif (priorRuns >= research.maxRunsPerSession) {\n\t\t\tthis._lastResearchLaneSkipReason = \"max_runs_reached\";\n\t\t\treturn;\n\t\t}\n\t\tif (!this._buildResearchLaneDemand()) return;\n\n\t\tthis.clearResearchLaneTimer();\n\t\tthis._researchLaneTimer = setTimeout(() => {\n\t\t\tthis._researchLaneTimer = undefined;\n\t\t\tvoid this._runScheduledResearchLane();\n\t\t}, research.idleDelayMs);\n\n\t\tconst timer = this._researchLaneTimer;\n\t\tif (typeof timer === \"object\" && timer && \"unref\" in timer) {\n\t\t\tconst { unref } = timer as { unref?: () => void };\n\t\t\tunref?.call(timer);\n\t\t}\n\t}\n\n\tprivate async _runScheduledResearchLane(): Promise<void> {\n\t\tif (this._isResearchLaneRunning || this.deps.isDisposed()) return;\n\n\t\tconst research = this.deps.getSettingsManager().getResearchLaneSettings();\n\t\tconst { mode } = this.deps.getSettingsManager().getAutonomySettings();\n\t\tif (!research.enabled || mode === \"off\") return;\n\n\t\ttry {\n\t\t\tawait this.runResearchLaneOnce();\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\tthis.deps.emit({ type: \"warning\", message: `Research lane failed: ${message}` });\n\t\t}\n\t}\n\n\t/** Capability profile for a specific lane model (lane budgets scale to the lane model's window). */\n\tprivate _laneCapabilityProfile(model: Model<Api>): ModelCapabilityProfile {\n\t\treturn deriveModelCapabilityProfile({\n\t\t\tcontextWindow: model.contextWindow,\n\t\t\tmode: this.deps.getSettingsManager().getModelCapabilitySettings().mode,\n\t\t});\n\t}\n\n\t/**\n\t * Resolve the model for a background lane. Lanes are shipped BY this session, so they inherit\n\t * the session's own model unless a lane-specific model is explicitly configured — a single-model\n\t * setup (e.g. one local open model) runs its lanes on that same model. An explicitly configured\n\t * pattern that cannot resolve/authenticate is a visible skip, not a silent fallback.\n\t */\n\tresolveLaneModel(configuredPattern: string | undefined): Model<Api> | undefined {\n\t\tif (configuredPattern) {\n\t\t\tconst resolved = resolveCliModel({ cliModel: configuredPattern, modelRegistry: this.deps.getModelRegistry() });\n\t\t\tif (resolved.model && this.deps.getModelRegistry().hasConfiguredAuth(resolved.model)) {\n\t\t\t\treturn resolved.model;\n\t\t\t}\n\t\t\treturn undefined;\n\t\t}\n\t\treturn this.deps.getModel() ?? undefined;\n\t}\n\n\t/**\n\t * Resolve what a lane ships with. Precedence: explicit lane model setting, then the lane\n\t * profile's model (a shipped profile with a model MUST be obeyed — unresolvable is a visible\n\t * skip, never a fallback), then generic inheritance of the session model.\n\t */\n\tprivate _resolveLaneShipment(\n\t\tlaneSettings: { model?: string; profile?: string },\n\t\tmissingModelReason: string,\n\t): { ok: true; model: Model<Api>; laneProfile?: NormalizedProfile } | { ok: false; skipReason: string } {\n\t\tlet laneProfile: NormalizedProfile | undefined;\n\t\tif (laneSettings.profile) {\n\t\t\tlaneProfile = this.deps.getSettingsManager().getProfileRegistry().getProfile(laneSettings.profile);\n\t\t\tif (!laneProfile) {\n\t\t\t\treturn { ok: false, skipReason: \"lane_profile_not_found\" };\n\t\t\t}\n\t\t}\n\n\t\tlet model: Model<Api> | undefined;\n\t\tif (laneSettings.model) {\n\t\t\tmodel = this.resolveLaneModel(laneSettings.model);\n\t\t\tif (!model) return { ok: false, skipReason: missingModelReason };\n\t\t} else if (laneProfile?.model) {\n\t\t\tmodel = this.resolveLaneModel(laneProfile.model);\n\t\t\tif (!model) return { ok: false, skipReason: \"no_lane_profile_model\" };\n\t\t} else {\n\t\t\tmodel = this.deps.getModel() ?? undefined;\n\t\t\tif (!model) return { ok: false, skipReason: missingModelReason };\n\t\t}\n\t\treturn { ok: true, model, laneProfile };\n\t}\n\n\t/** UAC tool grants from a shipped lane profile, recorded on the lane envelope. */\n\tprivate _laneProfileToolGrants(\n\t\tlaneProfile?: NormalizedProfile,\n\t): Pick<CapabilityEnvelope, \"allowedTools\" | \"deniedTools\"> {\n\t\tconst toolsFilter = laneProfile?.resources.tools;\n\t\treturn {\n\t\t\t...(toolsFilter?.allow && toolsFilter.allow.length > 0 ? { allowedTools: [...toolsFilter.allow] } : {}),\n\t\t\t...(toolsFilter?.block && toolsFilter.block.length > 0 ? { deniedTools: [...toolsFilter.block] } : {}),\n\t\t};\n\t}\n\n\t/** Stripped research envelope — never the foreground/architect envelope. */\n\tprivate _buildResearchLaneEnvelope(maxUsd: number, laneProfile?: NormalizedProfile): CapabilityEnvelope {\n\t\treturn {\n\t\t\tid: `research-${this.deps.getSessionId()}-${Date.now()}`,\n\t\t\tprofileId: laneProfile?.name,\n\t\t\tcapabilities: [\"research\", \"read_files\", \"memory_read\"],\n\t\t\t...this._laneProfileToolGrants(laneProfile),\n\t\t\tmaxEstimatedUsd: Math.min(\n\t\t\t\tmaxUsd,\n\t\t\t\tthis.deps.getCapabilityEnvelope()?.maxEstimatedUsd ?? Number.POSITIVE_INFINITY,\n\t\t\t),\n\t\t\tcreatedAt: new Date().toISOString(),\n\t\t};\n\t}\n\n\t/**\n\t * Run one bounded, read-only research pass and persist its results: evidence bundle snapshot,\n\t * terminal lane record, and spawned-usage cost report (single-hop invariant, idempotent on the\n\t * lane's reportId). Explicit calls (e.g. `/autonomy research`) express user intent and bypass the\n\t * enabled/mode/dedupe gates the idle scheduler enforces; budget and capability gates always apply.\n\t */\n\tasync runResearchLaneOnce(request?: {\n\t\tquery?: string;\n\t\tcontext?: string;\n\t\tgoalId?: string;\n\t}): Promise<ResearchLaneRunOutcome> {\n\t\tif (this._isResearchLaneRunning) {\n\t\t\treturn { started: false, skipReason: \"research_lane_already_running\" };\n\t\t}\n\t\tif (this.deps.isDisposed()) {\n\t\t\treturn { started: false, skipReason: \"session_disposed\" };\n\t\t}\n\n\t\tconst settings = this.deps.getSettingsManager().getResearchLaneSettings();\n\t\tconst demand = request?.query\n\t\t\t? { query: request.query, context: request.context ?? \"\", goalId: request.goalId }\n\t\t\t: this._buildResearchLaneDemand();\n\t\tif (!demand) {\n\t\t\treturn { started: false, skipReason: this._lastResearchLaneSkipReason ?? \"no_research_demand\" };\n\t\t}\n\n\t\tconst shipment = this._resolveLaneShipment(settings, \"no_research_model\");\n\t\tif (!shipment.ok) {\n\t\t\tthis._lastResearchLaneSkipReason = shipment.skipReason;\n\t\t\treturn { started: false, skipReason: shipment.skipReason };\n\t\t}\n\t\tconst { model, laneProfile } = shipment;\n\n\t\tthis._isResearchLaneRunning = true;\n\t\tthis._laneTracker.ensureCounterAtLeast(\n\t\t\tgetLaneRecordSnapshots(this.deps.getSessionManager().getEntries()).length + 1,\n\t\t);\n\t\tconst startedRecord = this._laneTracker.start({ type: \"research\", goalId: demand.goalId });\n\t\ttry {\n\t\t\tlet spentUsage: Usage | undefined;\n\t\t\t// Best-effort, pointer-first workspace evidence. Derives search terms from the goal/requirement\n\t\t\t// text (not the identity-key query) and is bounded + silent-on-failure: [] == today's behavior.\n\t\t\tconst workspaceSources = await this.deps.collectWorkspaceSources({\n\t\t\t\tquery: `${demand.context}\\n${demand.query}`,\n\t\t\t\tcwd: this.deps.getCwd(),\n\t\t\t\tmaxSources: settings.maxSources,\n\t\t\t});\n\t\t\tconst result = await runResearch({\n\t\t\t\tquery: demand.query,\n\t\t\t\tcontext: demand.context,\n\t\t\t\tsources: workspaceSources,\n\t\t\t\tenvelope: this._buildResearchLaneEnvelope(settings.maxUsd, laneProfile),\n\t\t\t\tmaxUsd: settings.maxUsd,\n\t\t\t\tmaxSources: settings.maxSources,\n\t\t\t\tmaxFindings: settings.maxFindings,\n\t\t\t\tmaxWallClockMs: settings.maxWallClockMs,\n\t\t\t\tsignal: this._researchLaneAbort.signal,\n\t\t\t\tcomplete: async ({ systemPrompt, userPrompt, signal }) => {\n\t\t\t\t\tconst completion = await this.deps.runIsolatedCompletion({\n\t\t\t\t\t\t// Level-0 core always survives; profile soul and role prompt are the replaceable\n\t\t\t\t\t\t// layers; a settings-provided prompt replaces everything above the core.\n\t\t\t\t\t\tsystemPrompt: composeSubagentSystemPrompt({\n\t\t\t\t\t\t\tsoul: laneProfile?.soul,\n\t\t\t\t\t\t\trolePrompt: systemPrompt,\n\t\t\t\t\t\t\toverride: settings.systemPrompt,\n\t\t\t\t\t\t}),\n\t\t\t\t\t\tmessages: [{ role: \"user\", content: [{ type: \"text\", text: userPrompt }], timestamp: Date.now() }],\n\t\t\t\t\t\tmodel,\n\t\t\t\t\t\tthinkingLevel: laneProfile?.thinking ?? \"off\",\n\t\t\t\t\t\tmaxTokens: this._laneCapabilityProfile(model).laneMaxOutputTokens,\n\t\t\t\t\t\tsignal,\n\t\t\t\t\t\t// Core/soul/role are all static per configuration — the provider can cache the prefix.\n\t\t\t\t\t\tcacheRetention: \"short\",\n\t\t\t\t\t});\n\t\t\t\t\tspentUsage = completion.usage;\n\t\t\t\t\treturn {\n\t\t\t\t\t\ttext: completion.text,\n\t\t\t\t\t\tcostUsd: completion.usage.cost.total,\n\t\t\t\t\t\tstopReason: String(completion.stopReason),\n\t\t\t\t\t};\n\t\t\t\t},\n\t\t\t});\n\n\t\t\t// Bug #21 pattern: if the session was disposed while the completion was in flight, do NOT\n\t\t\t// persist evidence/records/usage against the dead session.\n\t\t\tif (this.deps.isDisposed()) {\n\t\t\t\tconst record = this._laneTracker.complete(startedRecord.laneId, {\n\t\t\t\t\tstatus: \"canceled\",\n\t\t\t\t\treasonCode: \"session_disposed\",\n\t\t\t\t});\n\t\t\t\treturn { started: true, record, result };\n\t\t\t}\n\n\t\t\tlet evidenceEntryId: string | undefined;\n\t\t\tif (result.bundle) {\n\t\t\t\tevidenceEntryId = this.deps.saveEvidenceBundleSnapshot(result.bundle);\n\t\t\t}\n\t\t\tif (spentUsage && (spentUsage.cost.total > 0 || spentUsage.totalTokens > 0)) {\n\t\t\t\tthis.deps.addSpawnedUsage(spentUsage, {\n\t\t\t\t\tlabel: \"research-lane\",\n\t\t\t\t\treportId: `research:${this.deps.getSessionId()}:${startedRecord.laneId}`,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tconst record = this._laneTracker.complete(startedRecord.laneId, {\n\t\t\t\tstatus: result.status,\n\t\t\t\treasonCode: result.reasonCode,\n\t\t\t\tcostUsd: result.costUsd,\n\t\t\t\tevidenceEntryId,\n\t\t\t});\n\t\t\tif (record) {\n\t\t\t\tappendLaneRecordSnapshot(this.deps.getSessionManager(), record);\n\t\t\t\t// G3: a research lane's product is an evidence bundle, so its terminal record maps to\n\t\t\t\t// the evidence_bundle event. Lane outcome only (status/reasonCode/cost) — no findings text.\n\t\t\t\tthis.deps.emitAutonomyTelemetry({\n\t\t\t\t\ttype: AUTONOMY_TELEMETRY_EVENT_TYPES.evidenceBundle,\n\t\t\t\t\ttimestamp: new Date().toISOString(),\n\t\t\t\t\tpayload: {\n\t\t\t\t\t\tlaneId: record.laneId,\n\t\t\t\t\t\tlaneType: record.type,\n\t\t\t\t\t\tstatus: record.status,\n\t\t\t\t\t\treasonCode: record.reasonCode ?? null,\n\t\t\t\t\t\tcostUsd: record.costUsd ?? null,\n\t\t\t\t\t\thasEvidence: record.evidenceEntryId !== undefined,\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn { started: true, record, result };\n\t\t} catch (error) {\n\t\t\tconst record = this._laneTracker.complete(startedRecord.laneId, {\n\t\t\t\tstatus: \"failed\",\n\t\t\t\treasonCode: \"research_lane_error\",\n\t\t\t});\n\t\t\tif (record && !this.deps.isDisposed()) {\n\t\t\t\tappendLaneRecordSnapshot(this.deps.getSessionManager(), record);\n\t\t\t\tthis.deps.emitAutonomyTelemetry({\n\t\t\t\t\ttype: AUTONOMY_TELEMETRY_EVENT_TYPES.evidenceBundle,\n\t\t\t\t\ttimestamp: new Date().toISOString(),\n\t\t\t\t\tpayload: {\n\t\t\t\t\t\tlaneId: record.laneId,\n\t\t\t\t\t\tlaneType: record.type,\n\t\t\t\t\t\tstatus: record.status,\n\t\t\t\t\t\treasonCode: record.reasonCode ?? null,\n\t\t\t\t\t\tcostUsd: record.costUsd ?? null,\n\t\t\t\t\t\thasEvidence: record.evidenceEntryId !== undefined,\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t}\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\tthis.deps.emit({ type: \"warning\", message: `Research lane failed: ${message}` });\n\t\t\treturn { started: true, record };\n\t\t} finally {\n\t\t\tthis._isResearchLaneRunning = false;\n\t\t}\n\t}\n\n\t/**\n\t * Run one bounded scout-worker delegation: build a WorkerRequest with a stripped read-only\n\t * envelope, execute it as an isolated completion on a cheap lane, validate the result via\n\t * {@link validateWorkerResult} before acceptance, and persist result + lane record + spawned\n\t * usage (idempotent per-lane reportId). Consumed by the `delegate` tool.\n\t */\n\tasync runWorkerDelegationOnce(request: {\n\t\tinstructions: string;\n\t\t/** Model-provided replacement for the worker role prompt (the level-0 core always remains). */\n\t\tsystemPrompt?: string;\n\t}): Promise<WorkerDelegationRunOutcome> {\n\t\tconst delegationSettings = this.deps.getSettingsManager().getWorkerDelegationSettings();\n\t\tif (this._laneTracker.getActiveCount(\"worker\") >= delegationSettings.maxConcurrent) {\n\t\t\treturn { started: false, skipReason: \"worker_delegation_already_running\" };\n\t\t}\n\t\tif (this.deps.isDisposed()) {\n\t\t\treturn { started: false, skipReason: \"session_disposed\" };\n\t\t}\n\t\tconst instructions = request.instructions.trim();\n\t\tif (instructions.length === 0) {\n\t\t\treturn { started: false, skipReason: \"missing_instructions\" };\n\t\t}\n\n\t\tconst settings = delegationSettings;\n\t\tif (!settings.enabled) {\n\t\t\treturn { started: false, skipReason: \"worker_delegation_disabled\" };\n\t\t}\n\n\t\tconst shipment = this._resolveLaneShipment(settings, \"no_worker_model\");\n\t\tif (!shipment.ok) {\n\t\t\treturn { started: false, skipReason: shipment.skipReason };\n\t\t}\n\t\tconst { model, laneProfile } = shipment;\n\n\t\tthis._laneTracker.ensureCounterAtLeast(\n\t\t\tgetLaneRecordSnapshots(this.deps.getSessionManager().getEntries()).length + 1,\n\t\t);\n\t\tconst startedRecord = this._laneTracker.start({ type: \"worker\" });\n\t\tconst maxUsd = Math.min(\n\t\t\tsettings.maxUsd,\n\t\t\tthis.deps.getCapabilityEnvelope()?.maxEstimatedUsd ?? Number.POSITIVE_INFINITY,\n\t\t);\n\t\tconst workerRequest: WorkerRequest = {\n\t\t\tid: startedRecord.laneId,\n\t\t\tinstructions,\n\t\t\troute: {\n\t\t\t\ttier: \"cheap\",\n\t\t\t\trisk: \"read-only\",\n\t\t\t\tconfidence: 1,\n\t\t\t\treasonCode: \"scout_worker\",\n\t\t\t\treasons: [\"Read-only scout delegation\"],\n\t\t\t},\n\t\t\tenvelope: {\n\t\t\t\tid: `worker-${this.deps.getSessionId()}-${startedRecord.laneId}`,\n\t\t\t\tprofileId: laneProfile?.name,\n\t\t\t\t// write_files requires BOTH the opt-in AND an explicit non-empty path scope —\n\t\t\t\t// an unscoped write grant is refused here, not discovered at validation time.\n\t\t\t\tcapabilities:\n\t\t\t\t\tsettings.writeEnabled && settings.writePaths.length > 0 ? [\"read_files\", \"write_files\"] : [\"read_files\"],\n\t\t\t\t...(settings.writeEnabled && settings.writePaths.length > 0\n\t\t\t\t\t? { allowedPaths: [...settings.writePaths] }\n\t\t\t\t\t: {}),\n\t\t\t\t...this._laneProfileToolGrants(laneProfile),\n\t\t\t\tmaxEstimatedUsd: maxUsd,\n\t\t\t\tcreatedAt: new Date().toISOString(),\n\t\t\t},\n\t\t\tmaxEstimatedUsd: maxUsd,\n\t\t\tcreatedAt: new Date().toISOString(),\n\t\t};\n\t\t// G8: worker delegation START. Routing/scope codes + budget only — never the instructions text.\n\t\tthis.deps.emitAutonomyTelemetry({\n\t\t\ttype: AUTONOMY_TELEMETRY_EVENT_TYPES.workerRequest,\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\tpayload: {\n\t\t\t\tid: workerRequest.id,\n\t\t\t\ttier: workerRequest.route.tier,\n\t\t\t\tcapabilities: [...workerRequest.envelope.capabilities],\n\t\t\t\tmaxEstimatedUsd: workerRequest.maxEstimatedUsd ?? null,\n\t\t\t},\n\t\t});\n\t\tconst usageReportId = `worker:${this.deps.getSessionId()}:${startedRecord.laneId}`;\n\n\t\ttry {\n\t\t\tlet spentUsage: Usage | undefined;\n\t\t\tconst outcome = await runWorker({\n\t\t\t\trequest: workerRequest,\n\t\t\t\tmaxUsd,\n\t\t\t\tmaxWallClockMs: settings.maxWallClockMs,\n\t\t\t\tusageReportId,\n\t\t\t\tsignal: this._workerDelegationAbort.signal,\n\t\t\t\t// Parent validation must use the same relative-path baseline the runner reports in.\n\t\t\t\tcwd: this.deps.getCwd(),\n\t\t\t\t// Write lane (G2): runner-side action application through the envelope path scope.\n\t\t\t\tapplyActions: workerRequest.envelope.capabilities.includes(\"write_files\")\n\t\t\t\t\t? (actions) => applyWorkerActions({ actions, envelope: workerRequest.envelope, cwd: this.deps.getCwd() })\n\t\t\t\t\t: undefined,\n\t\t\t\tcomplete: async ({ systemPrompt, userPrompt, signal }) => {\n\t\t\t\t\tconst completion = await this.deps.runIsolatedCompletion({\n\t\t\t\t\t\t// Level-0 core always survives. A model-provided prompt (delegate tool) is the most\n\t\t\t\t\t\t// specific override, then the settings-level prompt, then profile soul + role prompt.\n\t\t\t\t\t\tsystemPrompt: composeSubagentSystemPrompt({\n\t\t\t\t\t\t\tsoul: laneProfile?.soul,\n\t\t\t\t\t\t\trolePrompt: systemPrompt,\n\t\t\t\t\t\t\toverride: request.systemPrompt ?? settings.systemPrompt,\n\t\t\t\t\t\t}),\n\t\t\t\t\t\tmessages: [{ role: \"user\", content: [{ type: \"text\", text: userPrompt }], timestamp: Date.now() }],\n\t\t\t\t\t\tmodel,\n\t\t\t\t\t\tthinkingLevel: laneProfile?.thinking ?? \"off\",\n\t\t\t\t\t\tmaxTokens: this._laneCapabilityProfile(model).laneMaxOutputTokens,\n\t\t\t\t\t\tsignal,\n\t\t\t\t\t\t// Core/soul/role are all static per configuration — the provider can cache the prefix.\n\t\t\t\t\t\tcacheRetention: \"short\",\n\t\t\t\t\t});\n\t\t\t\t\tspentUsage = completion.usage;\n\t\t\t\t\treturn {\n\t\t\t\t\t\ttext: completion.text,\n\t\t\t\t\t\tcostUsd: completion.usage.cost.total,\n\t\t\t\t\t\tstopReason: String(completion.stopReason),\n\t\t\t\t\t};\n\t\t\t\t},\n\t\t\t});\n\n\t\t\t// Bug #21 pattern: never persist against a disposed session.\n\t\t\tif (this.deps.isDisposed()) {\n\t\t\t\tconst record = this._laneTracker.complete(startedRecord.laneId, {\n\t\t\t\t\tstatus: \"canceled\",\n\t\t\t\t\treasonCode: \"session_disposed\",\n\t\t\t\t});\n\t\t\t\treturn { started: true, record, outcome };\n\t\t\t}\n\n\t\t\tthis.deps.saveWorkerResultSnapshot(outcome.result, workerRequest);\n\t\t\tif (spentUsage && (spentUsage.cost.total > 0 || spentUsage.totalTokens > 0)) {\n\t\t\t\tthis.deps.addSpawnedUsage(spentUsage, { label: \"worker-delegation\", reportId: usageReportId });\n\t\t\t}\n\n\t\t\tconst record = this._laneTracker.complete(startedRecord.laneId, {\n\t\t\t\tstatus: outcome.laneStatus,\n\t\t\t\treasonCode: outcome.reasonCode,\n\t\t\t\tcostUsd: outcome.costUsd,\n\t\t\t});\n\t\t\tif (record) {\n\t\t\t\tappendLaneRecordSnapshot(this.deps.getSessionManager(), record);\n\t\t\t\t// G3: worker lane terminal record -> worker_result event. Lane outcome only\n\t\t\t\t// (status/reasonCode/cost) — never the worker's summary/changed-file text.\n\t\t\t\tthis.deps.emitAutonomyTelemetry({\n\t\t\t\t\ttype: AUTONOMY_TELEMETRY_EVENT_TYPES.workerResult,\n\t\t\t\t\ttimestamp: new Date().toISOString(),\n\t\t\t\t\tpayload: {\n\t\t\t\t\t\tlaneId: record.laneId,\n\t\t\t\t\t\tlaneType: record.type,\n\t\t\t\t\t\tstatus: record.status,\n\t\t\t\t\t\treasonCode: record.reasonCode ?? null,\n\t\t\t\t\t\tcostUsd: record.costUsd ?? null,\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn { started: true, record, outcome };\n\t\t} catch (error) {\n\t\t\tconst record = this._laneTracker.complete(startedRecord.laneId, {\n\t\t\t\tstatus: \"failed\",\n\t\t\t\treasonCode: \"worker_delegation_error\",\n\t\t\t});\n\t\t\tif (record && !this.deps.isDisposed()) {\n\t\t\t\tappendLaneRecordSnapshot(this.deps.getSessionManager(), record);\n\t\t\t\tthis.deps.emitAutonomyTelemetry({\n\t\t\t\t\ttype: AUTONOMY_TELEMETRY_EVENT_TYPES.workerResult,\n\t\t\t\t\ttimestamp: new Date().toISOString(),\n\t\t\t\t\tpayload: {\n\t\t\t\t\t\tlaneId: record.laneId,\n\t\t\t\t\t\tlaneType: record.type,\n\t\t\t\t\t\tstatus: record.status,\n\t\t\t\t\t\treasonCode: record.reasonCode ?? null,\n\t\t\t\t\t\tcostUsd: record.costUsd ?? null,\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t}\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\tthis.deps.emit({ type: \"warning\", message: `Worker delegation failed: ${message}` });\n\t\t\treturn { started: true, record };\n\t\t} finally {\n\t\t}\n\t}\n\n\t/**\n\t * Probe a candidate model against the subagent contracts (research/worker/judge/search/\n\t * tool-call surfaces) via {@link runModelFitnessProbe}. The model must resolve and\n\t * authenticate; every probe call runs as an isolated completion on that model, and probe\n\t * spend is reported through spawned-usage accounting.\n\t */\n\tasync runModelFitness(args: {\n\t\tmodel: string;\n\t\ttrials?: number;\n\t}): Promise<{ started: true; model: string; report: ModelFitnessReport } | { started: false; skipReason: string }> {\n\t\tif (this.deps.isDisposed()) return { started: false, skipReason: \"session_disposed\" };\n\t\tconst resolved = this.resolveLaneModel(args.model.trim() || undefined);\n\t\tif (!resolved) return { started: false, skipReason: \"model_unresolved_or_unauthenticated\" };\n\t\tconst capability = this._laneCapabilityProfile(resolved);\n\n\t\tconst spent: Usage = {\n\t\t\tinput: 0,\n\t\t\toutput: 0,\n\t\t\tcacheRead: 0,\n\t\t\tcacheWrite: 0,\n\t\t\ttotalTokens: 0,\n\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t};\n\t\tconst report = await runModelFitnessProbe({\n\t\t\ttrials: args.trials,\n\t\t\tsignal: this._researchLaneAbort.signal,\n\t\t\tcomplete: async ({ systemPrompt, userPrompt, signal }) => {\n\t\t\t\tconst callStarted = Date.now();\n\t\t\t\tconst completion = await this.deps.runIsolatedCompletion({\n\t\t\t\t\tsystemPrompt,\n\t\t\t\t\tmessages: [{ role: \"user\", content: [{ type: \"text\", text: userPrompt }], timestamp: Date.now() }],\n\t\t\t\t\tmodel: resolved,\n\t\t\t\t\tthinkingLevel: \"off\",\n\t\t\t\t\tmaxTokens: capability.laneMaxOutputTokens,\n\t\t\t\t\tsignal,\n\t\t\t\t\tcacheRetention: \"short\",\n\t\t\t\t});\n\t\t\t\tconst callMs = Date.now() - callStarted;\n\t\t\t\tspent.input += completion.usage.input;\n\t\t\t\tspent.output += completion.usage.output;\n\t\t\t\tspent.cacheRead += completion.usage.cacheRead;\n\t\t\t\tspent.cacheWrite += completion.usage.cacheWrite;\n\t\t\t\tspent.totalTokens += completion.usage.totalTokens;\n\t\t\t\tspent.cost.input += completion.usage.cost.input;\n\t\t\t\tspent.cost.output += completion.usage.cost.output;\n\t\t\t\tspent.cost.cacheRead += completion.usage.cost.cacheRead;\n\t\t\t\tspent.cost.cacheWrite += completion.usage.cost.cacheWrite;\n\t\t\t\tspent.cost.total += completion.usage.cost.total;\n\t\t\t\treturn {\n\t\t\t\t\ttext: completion.text,\n\t\t\t\t\tcostUsd: completion.usage.cost.total,\n\t\t\t\t\tstopReason: String(completion.stopReason),\n\t\t\t\t\t// Wall-clock fallback for tok/s: providers don't expose pure eval time, so the\n\t\t\t\t\t// measured call time stands in — slightly conservative (includes network/queue).\n\t\t\t\t\toutputTokens: completion.usage.output,\n\t\t\t\t\tevalMs: callMs,\n\t\t\t\t};\n\t\t\t},\n\t\t});\n\t\tif (!this.deps.isDisposed() && (spent.cost.total > 0 || spent.totalTokens > 0)) {\n\t\t\tthis.deps.addSpawnedUsage(spent, { label: \"model-fitness\" });\n\t\t}\n\t\tconst modelRef = `${resolved.provider}/${resolved.id}`;\n\t\t// Fitness is a property of a model ON a host — persist the report host-keyed so role\n\t\t// assignments stay per-machine (a model can await better hardware without being forgotten).\n\t\t// Best-effort: a disk problem must not fail the probe itself.\n\t\ttry {\n\t\t\tif (!this.deps.isDisposed()) {\n\t\t\t\tFitnessStore.forAgentDir(this.deps.getAgentDir()).save(modelRef, report);\n\t\t\t}\n\t\t} catch {\n\t\t\t// best-effort persistence\n\t\t}\n\t\treturn { started: true, model: modelRef, report };\n\t}\n\n\t/** Fitness reports persisted for THIS host (measured evidence for architect/profile decisions). */\n\tgetStoredFitnessReports(): StoredFitnessReport[] {\n\t\ttry {\n\t\t\treturn FitnessStore.forAgentDir(this.deps.getAgentDir()).getForHost();\n\t\t} catch {\n\t\t\treturn [];\n\t\t}\n\t}\n}\n"]}
@@ -0,0 +1,51 @@
1
+ /**
2
+ * Standalone bash-command execution (the `/bash` path + extension-driven bash).
3
+ *
4
+ * Extracted verbatim from agent-session.ts (god-file decomposition). Owns the bash abort controller
5
+ * and the pending-message queue that defers appending a bash result while the agent is streaming (so
6
+ * tool_use/tool_result ordering is never broken); the deferred messages are flushed by the session on
7
+ * agent turn completion. Persists results through the session log via deps.
8
+ */
9
+ import type { Agent } from "@caupulican/pi-agent-core";
10
+ import type { SessionManager } from "@caupulican/pi-agent-core/node";
11
+ import { type BashResult } from "./bash-executor.ts";
12
+ import type { SettingsManager } from "./settings-manager.ts";
13
+ import { type BashOperations } from "./tools/bash.ts";
14
+ export interface BashExecutionControllerDeps {
15
+ getAgent(): Agent;
16
+ getSessionManager(): SessionManager;
17
+ getSettingsManager(): SettingsManager;
18
+ /** Whether the agent is currently streaming — defers appending a bash result if so. */
19
+ isStreaming(): boolean;
20
+ }
21
+ export declare class BashExecutionController {
22
+ private _bashAbortController;
23
+ private _pendingBashMessages;
24
+ private readonly deps;
25
+ constructor(deps: BashExecutionControllerDeps);
26
+ executeBash(command: string, onChunk?: (chunk: string) => void, options?: {
27
+ excludeFromContext?: boolean;
28
+ operations?: BashOperations;
29
+ }): Promise<BashResult>;
30
+ /**
31
+ * Record a bash execution result in session history.
32
+ * Used by executeBash and by extensions that handle bash execution themselves.
33
+ */
34
+ recordBashResult(command: string, result: BashResult, options?: {
35
+ excludeFromContext?: boolean;
36
+ }): void;
37
+ /**
38
+ * Cancel running bash command.
39
+ */
40
+ abortBash(): void;
41
+ /** Whether a bash command is currently running */
42
+ get isBashRunning(): boolean;
43
+ /** Whether there are pending bash messages waiting to be flushed */
44
+ get hasPendingBashMessages(): boolean;
45
+ /**
46
+ * Flush pending bash messages to agent state and session.
47
+ * Called after agent turn completes to maintain proper message ordering.
48
+ */
49
+ flushPendingBashMessages(): void;
50
+ }
51
+ //# sourceMappingURL=bash-execution-controller.d.ts.map
@@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,IAAI,OAAO,CAE3B;IAED,oEAAoE;IACpE,IAAI,sBAAsB,IAAI,OAAO,CAEpC;IAED;;;OAGG;IACH,wBAAwB,IAAI,IAAI,CAY/B;CACD","sourcesContent":["/**\n * Standalone bash-command execution (the `/bash` path + extension-driven bash).\n *\n * Extracted verbatim from agent-session.ts (god-file decomposition). Owns the bash abort controller\n * and the pending-message queue that defers appending a bash result while the agent is streaming (so\n * tool_use/tool_result ordering is never broken); the deferred messages are flushed by the session on\n * agent turn completion. Persists results through the session log via deps.\n */\n\nimport type { Agent, BashExecutionMessage } from \"@caupulican/pi-agent-core\";\nimport type { SessionManager } from \"@caupulican/pi-agent-core/node\";\nimport { type BashResult, executeBashWithOperations } from \"./bash-executor.ts\";\nimport type { SettingsManager } from \"./settings-manager.ts\";\nimport { type BashOperations, createLocalBashOperations } from \"./tools/bash.ts\";\n\nexport interface BashExecutionControllerDeps {\n\tgetAgent(): Agent;\n\tgetSessionManager(): SessionManager;\n\tgetSettingsManager(): SettingsManager;\n\t/** Whether the agent is currently streaming — defers appending a bash result if so. */\n\tisStreaming(): boolean;\n}\n\nexport class BashExecutionController {\n\tprivate _bashAbortController: AbortController | undefined = undefined;\n\tprivate _pendingBashMessages: BashExecutionMessage[] = [];\n\n\tprivate readonly deps: BashExecutionControllerDeps;\n\n\tconstructor(deps: BashExecutionControllerDeps) {\n\t\tthis.deps = deps;\n\t}\n\n\tasync executeBash(\n\t\tcommand: string,\n\t\tonChunk?: (chunk: string) => void,\n\t\toptions?: { excludeFromContext?: boolean; operations?: BashOperations },\n\t): Promise<BashResult> {\n\t\tthis._bashAbortController = new AbortController();\n\n\t\t// Apply command prefix if configured (e.g., \"shopt -s expand_aliases\" for alias support)\n\t\tconst prefix = this.deps.getSettingsManager().getShellCommandPrefix();\n\t\tconst shellPath = this.deps.getSettingsManager().getShellPath();\n\t\tconst resolvedCommand = prefix ? `${prefix}\\n${command}` : command;\n\t\tconst enableGitFilter = !options?.operations && !prefix && !shellPath;\n\n\t\ttry {\n\t\t\tconst result = await executeBashWithOperations(\n\t\t\t\tresolvedCommand,\n\t\t\t\tthis.deps.getSessionManager().getCwd(),\n\t\t\t\toptions?.operations ?? createLocalBashOperations({ shellPath }),\n\t\t\t\t{\n\t\t\t\t\tonChunk,\n\t\t\t\t\tsignal: this._bashAbortController.signal,\n\t\t\t\t\tenableGitFilter,\n\t\t\t\t},\n\t\t\t);\n\n\t\t\tthis.recordBashResult(command, result, options);\n\t\t\treturn result;\n\t\t} finally {\n\t\t\tthis._bashAbortController = undefined;\n\t\t}\n\t}\n\n\t/**\n\t * Record a bash execution result in session history.\n\t * Used by executeBash and by extensions that handle bash execution themselves.\n\t */\n\trecordBashResult(command: string, result: BashResult, options?: { excludeFromContext?: boolean }): void {\n\t\tconst bashMessage: BashExecutionMessage = {\n\t\t\trole: \"bashExecution\",\n\t\t\tcommand,\n\t\t\toutput: result.output,\n\t\t\texitCode: result.exitCode,\n\t\t\tcancelled: result.cancelled,\n\t\t\ttruncated: result.truncated,\n\t\t\tfullOutputPath: result.fullOutputPath,\n\t\t\ttimestamp: Date.now(),\n\t\t\texcludeFromContext: options?.excludeFromContext,\n\t\t};\n\n\t\t// If agent is streaming, defer adding to avoid breaking tool_use/tool_result ordering\n\t\tif (this.deps.isStreaming()) {\n\t\t\t// Queue for later - will be flushed on agent_end\n\t\t\tthis._pendingBashMessages.push(bashMessage);\n\t\t} else {\n\t\t\t// Add to agent state immediately\n\t\t\tthis.deps.getAgent().state.messages.push(bashMessage);\n\n\t\t\t// Save to session\n\t\t\tthis.deps.getSessionManager().appendMessage(bashMessage);\n\t\t}\n\t}\n\n\t/**\n\t * Cancel running bash command.\n\t */\n\tabortBash(): void {\n\t\tthis._bashAbortController?.abort();\n\t}\n\n\t/** Whether a bash command is currently running */\n\tget isBashRunning(): boolean {\n\t\treturn this._bashAbortController !== undefined;\n\t}\n\n\t/** Whether there are pending bash messages waiting to be flushed */\n\tget hasPendingBashMessages(): boolean {\n\t\treturn this._pendingBashMessages.length > 0;\n\t}\n\n\t/**\n\t * Flush pending bash messages to agent state and session.\n\t * Called after agent turn completes to maintain proper message ordering.\n\t */\n\tflushPendingBashMessages(): void {\n\t\tif (this._pendingBashMessages.length === 0) return;\n\n\t\tfor (const bashMessage of this._pendingBashMessages) {\n\t\t\t// Add to agent state\n\t\t\tthis.deps.getAgent().state.messages.push(bashMessage);\n\n\t\t\t// Save to session\n\t\t\tthis.deps.getSessionManager().appendMessage(bashMessage);\n\t\t}\n\n\t\tthis._pendingBashMessages = [];\n\t}\n}\n"]}
@@ -0,0 +1,96 @@
1
+ /**
2
+ * Standalone bash-command execution (the `/bash` path + extension-driven bash).
3
+ *
4
+ * Extracted verbatim from agent-session.ts (god-file decomposition). Owns the bash abort controller
5
+ * and the pending-message queue that defers appending a bash result while the agent is streaming (so
6
+ * tool_use/tool_result ordering is never broken); the deferred messages are flushed by the session on
7
+ * agent turn completion. Persists results through the session log via deps.
8
+ */
9
+ import { executeBashWithOperations } from "./bash-executor.js";
10
+ import { createLocalBashOperations } from "./tools/bash.js";
11
+ export class BashExecutionController {
12
+ _bashAbortController = undefined;
13
+ _pendingBashMessages = [];
14
+ deps;
15
+ constructor(deps) {
16
+ this.deps = deps;
17
+ }
18
+ async executeBash(command, onChunk, options) {
19
+ this._bashAbortController = new AbortController();
20
+ // Apply command prefix if configured (e.g., "shopt -s expand_aliases" for alias support)
21
+ const prefix = this.deps.getSettingsManager().getShellCommandPrefix();
22
+ const shellPath = this.deps.getSettingsManager().getShellPath();
23
+ const resolvedCommand = prefix ? `${prefix}\n${command}` : command;
24
+ const enableGitFilter = !options?.operations && !prefix && !shellPath;
25
+ try {
26
+ const result = await executeBashWithOperations(resolvedCommand, this.deps.getSessionManager().getCwd(), options?.operations ?? createLocalBashOperations({ shellPath }), {
27
+ onChunk,
28
+ signal: this._bashAbortController.signal,
29
+ enableGitFilter,
30
+ });
31
+ this.recordBashResult(command, result, options);
32
+ return result;
33
+ }
34
+ finally {
35
+ this._bashAbortController = undefined;
36
+ }
37
+ }
38
+ /**
39
+ * Record a bash execution result in session history.
40
+ * Used by executeBash and by extensions that handle bash execution themselves.
41
+ */
42
+ recordBashResult(command, result, options) {
43
+ const bashMessage = {
44
+ role: "bashExecution",
45
+ command,
46
+ output: result.output,
47
+ exitCode: result.exitCode,
48
+ cancelled: result.cancelled,
49
+ truncated: result.truncated,
50
+ fullOutputPath: result.fullOutputPath,
51
+ timestamp: Date.now(),
52
+ excludeFromContext: options?.excludeFromContext,
53
+ };
54
+ // If agent is streaming, defer adding to avoid breaking tool_use/tool_result ordering
55
+ if (this.deps.isStreaming()) {
56
+ // Queue for later - will be flushed on agent_end
57
+ this._pendingBashMessages.push(bashMessage);
58
+ }
59
+ else {
60
+ // Add to agent state immediately
61
+ this.deps.getAgent().state.messages.push(bashMessage);
62
+ // Save to session
63
+ this.deps.getSessionManager().appendMessage(bashMessage);
64
+ }
65
+ }
66
+ /**
67
+ * Cancel running bash command.
68
+ */
69
+ abortBash() {
70
+ this._bashAbortController?.abort();
71
+ }
72
+ /** Whether a bash command is currently running */
73
+ get isBashRunning() {
74
+ return this._bashAbortController !== undefined;
75
+ }
76
+ /** Whether there are pending bash messages waiting to be flushed */
77
+ get hasPendingBashMessages() {
78
+ return this._pendingBashMessages.length > 0;
79
+ }
80
+ /**
81
+ * Flush pending bash messages to agent state and session.
82
+ * Called after agent turn completes to maintain proper message ordering.
83
+ */
84
+ flushPendingBashMessages() {
85
+ if (this._pendingBashMessages.length === 0)
86
+ return;
87
+ for (const bashMessage of this._pendingBashMessages) {
88
+ // Add to agent state
89
+ this.deps.getAgent().state.messages.push(bashMessage);
90
+ // Save to session
91
+ this.deps.getSessionManager().appendMessage(bashMessage);
92
+ }
93
+ this._pendingBashMessages = [];
94
+ }
95
+ }
96
+ //# sourceMappingURL=bash-execution-controller.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bash-execution-controller.js","sourceRoot":"","sources":["../../src/core/bash-execution-controller.ts"],"names":[],"mappings":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C5C;IAED;;;OAGG;IACH,wBAAwB,GAAS;QAChC,IAAI,IAAI,CAAC,oBAAoB,CAAC,MAAM,KAAK,CAAC;YAAE,OAAO;QAEnD,KAAK,MAAM,WAAW,IAAI,IAAI,CAAC,oBAAoB,EAAE,CAAC;YACrD,qBAAqB;YACrB,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,CAAC,KAAK,CAAC,QAAQ,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;YAEtD,kBAAkB;YAClB,IAAI,CAAC,IAAI,CAAC,iBAAiB,EAAE,CAAC,aAAa,CAAC,WAAW,CAAC,CAAC;QAC1D,CAAC;QAED,IAAI,CAAC,oBAAoB,GAAG,EAAE,CAAC;IAAA,CAC/B;CACD","sourcesContent":["/**\n * Standalone bash-command execution (the `/bash` path + extension-driven bash).\n *\n * Extracted verbatim from agent-session.ts (god-file decomposition). Owns the bash abort controller\n * and the pending-message queue that defers appending a bash result while the agent is streaming (so\n * tool_use/tool_result ordering is never broken); the deferred messages are flushed by the session on\n * agent turn completion. Persists results through the session log via deps.\n */\n\nimport type { Agent, BashExecutionMessage } from \"@caupulican/pi-agent-core\";\nimport type { SessionManager } from \"@caupulican/pi-agent-core/node\";\nimport { type BashResult, executeBashWithOperations } from \"./bash-executor.ts\";\nimport type { SettingsManager } from \"./settings-manager.ts\";\nimport { type BashOperations, createLocalBashOperations } from \"./tools/bash.ts\";\n\nexport interface BashExecutionControllerDeps {\n\tgetAgent(): Agent;\n\tgetSessionManager(): SessionManager;\n\tgetSettingsManager(): SettingsManager;\n\t/** Whether the agent is currently streaming — defers appending a bash result if so. */\n\tisStreaming(): boolean;\n}\n\nexport class BashExecutionController {\n\tprivate _bashAbortController: AbortController | undefined = undefined;\n\tprivate _pendingBashMessages: BashExecutionMessage[] = [];\n\n\tprivate readonly deps: BashExecutionControllerDeps;\n\n\tconstructor(deps: BashExecutionControllerDeps) {\n\t\tthis.deps = deps;\n\t}\n\n\tasync executeBash(\n\t\tcommand: string,\n\t\tonChunk?: (chunk: string) => void,\n\t\toptions?: { excludeFromContext?: boolean; operations?: BashOperations },\n\t): Promise<BashResult> {\n\t\tthis._bashAbortController = new AbortController();\n\n\t\t// Apply command prefix if configured (e.g., \"shopt -s expand_aliases\" for alias support)\n\t\tconst prefix = this.deps.getSettingsManager().getShellCommandPrefix();\n\t\tconst shellPath = this.deps.getSettingsManager().getShellPath();\n\t\tconst resolvedCommand = prefix ? `${prefix}\\n${command}` : command;\n\t\tconst enableGitFilter = !options?.operations && !prefix && !shellPath;\n\n\t\ttry {\n\t\t\tconst result = await executeBashWithOperations(\n\t\t\t\tresolvedCommand,\n\t\t\t\tthis.deps.getSessionManager().getCwd(),\n\t\t\t\toptions?.operations ?? createLocalBashOperations({ shellPath }),\n\t\t\t\t{\n\t\t\t\t\tonChunk,\n\t\t\t\t\tsignal: this._bashAbortController.signal,\n\t\t\t\t\tenableGitFilter,\n\t\t\t\t},\n\t\t\t);\n\n\t\t\tthis.recordBashResult(command, result, options);\n\t\t\treturn result;\n\t\t} finally {\n\t\t\tthis._bashAbortController = undefined;\n\t\t}\n\t}\n\n\t/**\n\t * Record a bash execution result in session history.\n\t * Used by executeBash and by extensions that handle bash execution themselves.\n\t */\n\trecordBashResult(command: string, result: BashResult, options?: { excludeFromContext?: boolean }): void {\n\t\tconst bashMessage: BashExecutionMessage = {\n\t\t\trole: \"bashExecution\",\n\t\t\tcommand,\n\t\t\toutput: result.output,\n\t\t\texitCode: result.exitCode,\n\t\t\tcancelled: result.cancelled,\n\t\t\ttruncated: result.truncated,\n\t\t\tfullOutputPath: result.fullOutputPath,\n\t\t\ttimestamp: Date.now(),\n\t\t\texcludeFromContext: options?.excludeFromContext,\n\t\t};\n\n\t\t// If agent is streaming, defer adding to avoid breaking tool_use/tool_result ordering\n\t\tif (this.deps.isStreaming()) {\n\t\t\t// Queue for later - will be flushed on agent_end\n\t\t\tthis._pendingBashMessages.push(bashMessage);\n\t\t} else {\n\t\t\t// Add to agent state immediately\n\t\t\tthis.deps.getAgent().state.messages.push(bashMessage);\n\n\t\t\t// Save to session\n\t\t\tthis.deps.getSessionManager().appendMessage(bashMessage);\n\t\t}\n\t}\n\n\t/**\n\t * Cancel running bash command.\n\t */\n\tabortBash(): void {\n\t\tthis._bashAbortController?.abort();\n\t}\n\n\t/** Whether a bash command is currently running */\n\tget isBashRunning(): boolean {\n\t\treturn this._bashAbortController !== undefined;\n\t}\n\n\t/** Whether there are pending bash messages waiting to be flushed */\n\tget hasPendingBashMessages(): boolean {\n\t\treturn this._pendingBashMessages.length > 0;\n\t}\n\n\t/**\n\t * Flush pending bash messages to agent state and session.\n\t * Called after agent turn completes to maintain proper message ordering.\n\t */\n\tflushPendingBashMessages(): void {\n\t\tif (this._pendingBashMessages.length === 0) return;\n\n\t\tfor (const bashMessage of this._pendingBashMessages) {\n\t\t\t// Add to agent state\n\t\t\tthis.deps.getAgent().state.messages.push(bashMessage);\n\n\t\t\t// Save to session\n\t\t\tthis.deps.getSessionManager().appendMessage(bashMessage);\n\t\t}\n\n\t\tthis._pendingBashMessages = [];\n\t}\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"bash-executor.d.ts","sourceRoot":"","sources":["../../src/core/bash-executor.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AASH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAQtD,MAAM,WAAW,mBAAmB;IACnC,+DAA+D;IAC/D,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,CAAC;IAClC,mCAAmC;IACnC,MAAM,CAAC,EAAE,WAAW,CAAC;IACrB,2FAA2F;IAC3F,eAAe,CAAC,EAAE,OAAO,CAAC;CAC1B;AAED,MAAM,WAAW,UAAU;IAC1B,sEAAsE;IACtE,MAAM,EAAE,MAAM,CAAC;IACf,wDAAwD;IACxD,QAAQ,EAAE,MAAM,GAAG,SAAS,CAAC;IAC7B,mDAAmD;IACnD,SAAS,EAAE,OAAO,CAAC;IACnB,uCAAuC;IACvC,SAAS,EAAE,OAAO,CAAC;IACnB,yFAAyF;IACzF,cAAc,CAAC,EAAE,MAAM,CAAC;CACxB;AAMD;;;GAGG;AACH,wBAAsB,yBAAyB,CAC9C,OAAO,EAAE,MAAM,EACf,GAAG,EAAE,MAAM,EACX,UAAU,EAAE,cAAc,EAC1B,OAAO,CAAC,EAAE,mBAAmB,GAC3B,OAAO,CAAC,UAAU,CAAC,CAsJrB","sourcesContent":["/**\n * Bash command execution with streaming support and cancellation.\n *\n * This module provides a unified bash execution implementation used by:\n * - AgentSession.executeBash() for interactive and RPC modes\n * - Direct calls from modes that need bash execution\n */\n\nimport { randomBytes } from \"node:crypto\";\nimport type { WriteStream } from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { stripAnsi } from \"../utils/ansi.ts\";\nimport { createSafeWriteStream, endWriteStream } from \"../utils/safe-write-stream.ts\";\nimport { sanitizeBinaryOutput } from \"../utils/shell.ts\";\nimport type { BashOperations } from \"./tools/bash.ts\";\nimport { classifyGitCommand, executeFilteredGit } from \"./tools/git-filter.ts\";\nimport { DEFAULT_MAX_BYTES, truncateTail } from \"./tools/truncate.ts\";\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport interface BashExecutorOptions {\n\t/** Callback for streaming output chunks (already sanitized) */\n\tonChunk?: (chunk: string) => void;\n\t/** AbortSignal for cancellation */\n\tsignal?: AbortSignal;\n\t/** Enable conservative pi-native git output filtering for local default execution paths */\n\tenableGitFilter?: boolean;\n}\n\nexport interface BashResult {\n\t/** Combined stdout + stderr output (sanitized, possibly truncated) */\n\toutput: string;\n\t/** Process exit code (undefined if killed/cancelled) */\n\texitCode: number | undefined;\n\t/** Whether the command was cancelled via signal */\n\tcancelled: boolean;\n\t/** Whether the output was truncated */\n\ttruncated: boolean;\n\t/** Path to temp file containing full output (if output exceeded truncation threshold) */\n\tfullOutputPath?: string;\n}\n\n// ============================================================================\n// Implementation\n// ============================================================================\n\n/**\n * Execute a bash command using custom BashOperations.\n * Used for remote execution (SSH, containers, etc.).\n */\nexport async function executeBashWithOperations(\n\tcommand: string,\n\tcwd: string,\n\toperations: BashOperations,\n\toptions?: BashExecutorOptions,\n): Promise<BashResult> {\n\tif (options?.enableGitFilter) {\n\t\tconst classification = classifyGitCommand(command, process.env);\n\t\tif (classification.eligible && classification.subcommand) {\n\t\t\tconst res = await executeFilteredGit(\n\t\t\t\tcwd,\n\t\t\t\tclassification.subcommand,\n\t\t\t\tclassification.globalOptions || [],\n\t\t\t\tclassification.subcommandArgs || [],\n\t\t\t\t{ signal: options.signal },\n\t\t\t);\n\t\t\tif (res.exitCode !== -100) {\n\t\t\t\tconst rawBytes = res.rawBytes ?? Buffer.from(res.rawOut, \"utf-8\");\n\t\t\t\t// The filter already spills oversized output to a temp file; reuse it\n\t\t\t\t// instead of materializing another full copy here.\n\t\t\t\tlet fullOutputPath = res.fullOutputPath;\n\t\t\t\tif (fullOutputPath === undefined && rawBytes.length > DEFAULT_MAX_BYTES) {\n\t\t\t\t\tconst id = randomBytes(8).toString(\"hex\");\n\t\t\t\t\tconst spillPath = join(tmpdir(), `pi-bash-${id}.log`);\n\t\t\t\t\tfullOutputPath = spillPath;\n\t\t\t\t\t// On stream failure (e.g. disk full), drop the advertised path instead of\n\t\t\t\t\t// pointing at a partial/missing file.\n\t\t\t\t\tconst tempFileStream = createSafeWriteStream(spillPath, () => {\n\t\t\t\t\t\tfullOutputPath = undefined;\n\t\t\t\t\t});\n\t\t\t\t\ttempFileStream.write(rawBytes);\n\t\t\t\t\t// Await the flush so the returned path points at a COMPLETE file, not one mid-write.\n\t\t\t\t\tawait endWriteStream(tempFileStream);\n\t\t\t\t}\n\t\t\t\toptions.onChunk?.(res.output);\n\t\t\t\treturn {\n\t\t\t\t\toutput: res.output,\n\t\t\t\t\texitCode: res.exitCode,\n\t\t\t\t\tcancelled: options.signal?.aborted ?? false,\n\t\t\t\t\ttruncated: res.fullOutputPath !== undefined || rawBytes.length > DEFAULT_MAX_BYTES,\n\t\t\t\t\tfullOutputPath,\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t}\n\n\tconst outputChunks: string[] = [];\n\tlet outputBytes = 0;\n\tconst maxOutputBytes = DEFAULT_MAX_BYTES * 2;\n\n\tlet tempFilePath: string | undefined;\n\tlet tempFileStream: WriteStream | undefined;\n\tlet totalBytes = 0;\n\n\tconst ensureTempFile = () => {\n\t\tif (tempFilePath) {\n\t\t\treturn;\n\t\t}\n\t\tconst id = randomBytes(8).toString(\"hex\");\n\t\ttempFilePath = join(tmpdir(), `pi-bash-${id}.log`);\n\t\t// On stream failure (e.g. disk full), drop the artifact instead of\n\t\t// crashing the process; the rolling in-memory output is still returned.\n\t\ttempFileStream = createSafeWriteStream(tempFilePath, () => {\n\t\t\ttempFileStream = undefined;\n\t\t\ttempFilePath = undefined;\n\t\t});\n\t\tfor (const chunk of outputChunks) {\n\t\t\ttempFileStream.write(chunk);\n\t\t}\n\t};\n\n\tconst decoder = new TextDecoder();\n\n\tconst onData = (data: Buffer) => {\n\t\ttotalBytes += data.length;\n\n\t\t// Sanitize: strip ANSI, replace binary garbage, normalize newlines\n\t\tconst text = sanitizeBinaryOutput(stripAnsi(decoder.decode(data, { stream: true }))).replace(/\\r/g, \"\");\n\n\t\t// Start writing to temp file if exceeds threshold\n\t\tif (totalBytes > DEFAULT_MAX_BYTES) {\n\t\t\tensureTempFile();\n\t\t}\n\n\t\t// Guard writableEnded: custom BashOperations may deliver late onData\n\t\t// callbacks after an abort path has already ended the stream.\n\t\tif (tempFileStream && !tempFileStream.writableEnded) {\n\t\t\ttempFileStream.write(text);\n\t\t}\n\n\t\t// Keep rolling buffer\n\t\toutputChunks.push(text);\n\t\toutputBytes += text.length;\n\t\twhile (outputBytes > maxOutputBytes && outputChunks.length > 1) {\n\t\t\tconst removed = outputChunks.shift()!;\n\t\t\toutputBytes -= removed.length;\n\t\t}\n\n\t\t// Stream to callback\n\t\tif (options?.onChunk) {\n\t\t\toptions.onChunk(text);\n\t\t}\n\t};\n\n\ttry {\n\t\tconst result = await operations.exec(command, cwd, {\n\t\t\tonData,\n\t\t\tsignal: options?.signal,\n\t\t});\n\n\t\tconst fullOutput = outputChunks.join(\"\");\n\t\tconst truncationResult = truncateTail(fullOutput);\n\t\tif (truncationResult.truncated) {\n\t\t\tensureTempFile();\n\t\t}\n\t\tif (tempFileStream) {\n\t\t\t// Await the flush so fullOutputPath refers to a fully-written file on return, not one still\n\t\t\t// draining its buffer — otherwise a fast reader can see partial/empty content.\n\t\t\tawait endWriteStream(tempFileStream);\n\t\t}\n\t\tconst cancelled = options?.signal?.aborted ?? false;\n\n\t\treturn {\n\t\t\toutput: truncationResult.truncated ? truncationResult.content : fullOutput,\n\t\t\texitCode: cancelled ? undefined : (result.exitCode ?? undefined),\n\t\t\tcancelled,\n\t\t\ttruncated: truncationResult.truncated,\n\t\t\tfullOutputPath: tempFilePath,\n\t\t};\n\t} catch (err) {\n\t\t// Check if it was an abort\n\t\tif (options?.signal?.aborted) {\n\t\t\tconst fullOutput = outputChunks.join(\"\");\n\t\t\tconst truncationResult = truncateTail(fullOutput);\n\t\t\tif (truncationResult.truncated) {\n\t\t\t\tensureTempFile();\n\t\t\t}\n\t\t\tif (tempFileStream) {\n\t\t\t\tawait endWriteStream(tempFileStream);\n\t\t\t}\n\t\t\treturn {\n\t\t\t\toutput: truncationResult.truncated ? truncationResult.content : fullOutput,\n\t\t\t\texitCode: undefined,\n\t\t\t\tcancelled: true,\n\t\t\t\ttruncated: truncationResult.truncated,\n\t\t\t\tfullOutputPath: tempFilePath,\n\t\t\t};\n\t\t}\n\n\t\tif (tempFileStream) {\n\t\t\tawait endWriteStream(tempFileStream);\n\t\t}\n\n\t\tthrow err;\n\t}\n}\n"]}
1
+ {"version":3,"file":"bash-executor.d.ts","sourceRoot":"","sources":["../../src/core/bash-executor.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAUH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAOtD,MAAM,WAAW,mBAAmB;IACnC,+DAA+D;IAC/D,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,CAAC;IAClC,mCAAmC;IACnC,MAAM,CAAC,EAAE,WAAW,CAAC;IACrB,2FAA2F;IAC3F,eAAe,CAAC,EAAE,OAAO,CAAC;CAC1B;AAED,MAAM,WAAW,UAAU;IAC1B,sEAAsE;IACtE,MAAM,EAAE,MAAM,CAAC;IACf,wDAAwD;IACxD,QAAQ,EAAE,MAAM,GAAG,SAAS,CAAC;IAC7B,mDAAmD;IACnD,SAAS,EAAE,OAAO,CAAC;IACnB,uCAAuC;IACvC,SAAS,EAAE,OAAO,CAAC;IACnB,yFAAyF;IACzF,cAAc,CAAC,EAAE,MAAM,CAAC;CACxB;AAMD;;;GAGG;AACH,wBAAsB,yBAAyB,CAC9C,OAAO,EAAE,MAAM,EACf,GAAG,EAAE,MAAM,EACX,UAAU,EAAE,cAAc,EAC1B,OAAO,CAAC,EAAE,mBAAmB,GAC3B,OAAO,CAAC,UAAU,CAAC,CAgKrB","sourcesContent":["/**\n * Bash command execution with streaming support and cancellation.\n *\n * This module provides a unified bash execution implementation used by:\n * - AgentSession.executeBash() for interactive and RPC modes\n * - Direct calls from modes that need bash execution\n */\n\nimport { randomBytes } from \"node:crypto\";\nimport type { WriteStream } from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { sanitizeBinaryOutput } from \"@caupulican/pi-agent-core\";\nimport { DEFAULT_MAX_BYTES, truncateTail } from \"@caupulican/pi-agent-core/node\";\nimport { stripAnsi } from \"../utils/ansi.ts\";\nimport { createSafeWriteStream, endWriteStream } from \"../utils/safe-write-stream.ts\";\nimport type { BashOperations } from \"./tools/bash.ts\";\nimport { classifyGitCommand, executeFilteredGit } from \"./tools/git-filter.ts\";\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport interface BashExecutorOptions {\n\t/** Callback for streaming output chunks (already sanitized) */\n\tonChunk?: (chunk: string) => void;\n\t/** AbortSignal for cancellation */\n\tsignal?: AbortSignal;\n\t/** Enable conservative pi-native git output filtering for local default execution paths */\n\tenableGitFilter?: boolean;\n}\n\nexport interface BashResult {\n\t/** Combined stdout + stderr output (sanitized, possibly truncated) */\n\toutput: string;\n\t/** Process exit code (undefined if killed/cancelled) */\n\texitCode: number | undefined;\n\t/** Whether the command was cancelled via signal */\n\tcancelled: boolean;\n\t/** Whether the output was truncated */\n\ttruncated: boolean;\n\t/** Path to temp file containing full output (if output exceeded truncation threshold) */\n\tfullOutputPath?: string;\n}\n\n// ============================================================================\n// Implementation\n// ============================================================================\n\n/**\n * Execute a bash command using custom BashOperations.\n * Used for remote execution (SSH, containers, etc.).\n */\nexport async function executeBashWithOperations(\n\tcommand: string,\n\tcwd: string,\n\toperations: BashOperations,\n\toptions?: BashExecutorOptions,\n): Promise<BashResult> {\n\tif (options?.enableGitFilter) {\n\t\tconst classification = classifyGitCommand(command, process.env);\n\t\tif (classification.eligible && classification.subcommand) {\n\t\t\tconst res = await executeFilteredGit(\n\t\t\t\tcwd,\n\t\t\t\tclassification.subcommand,\n\t\t\t\tclassification.globalOptions || [],\n\t\t\t\tclassification.subcommandArgs || [],\n\t\t\t\t{ signal: options.signal },\n\t\t\t);\n\t\t\tif (res.exitCode !== -100) {\n\t\t\t\tconst rawBytes = res.rawBytes ?? Buffer.from(res.rawOut, \"utf-8\");\n\t\t\t\t// The filter already spills oversized output to a temp file; reuse it\n\t\t\t\t// instead of materializing another full copy here.\n\t\t\t\tlet fullOutputPath = res.fullOutputPath;\n\t\t\t\tif (fullOutputPath === undefined && rawBytes.length > DEFAULT_MAX_BYTES) {\n\t\t\t\t\tconst id = randomBytes(8).toString(\"hex\");\n\t\t\t\t\tconst spillPath = join(tmpdir(), `pi-bash-${id}.log`);\n\t\t\t\t\tfullOutputPath = spillPath;\n\t\t\t\t\t// On stream failure (e.g. disk full), drop the advertised path instead of\n\t\t\t\t\t// pointing at a partial/missing file.\n\t\t\t\t\tconst tempFileStream = createSafeWriteStream(spillPath, () => {\n\t\t\t\t\t\tfullOutputPath = undefined;\n\t\t\t\t\t});\n\t\t\t\t\ttempFileStream.write(rawBytes);\n\t\t\t\t\t// Await the flush so the returned path points at a COMPLETE file, not one mid-write.\n\t\t\t\t\tawait endWriteStream(tempFileStream);\n\t\t\t\t}\n\t\t\t\toptions.onChunk?.(res.output);\n\t\t\t\treturn {\n\t\t\t\t\toutput: res.output,\n\t\t\t\t\texitCode: res.exitCode,\n\t\t\t\t\tcancelled: options.signal?.aborted ?? false,\n\t\t\t\t\ttruncated: res.fullOutputPath !== undefined || rawBytes.length > DEFAULT_MAX_BYTES,\n\t\t\t\t\tfullOutputPath,\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t}\n\n\tconst outputChunks: string[] = [];\n\tlet outputBytes = 0;\n\tconst maxOutputBytes = DEFAULT_MAX_BYTES * 2;\n\n\tlet tempFilePath: string | undefined;\n\tlet tempFileStream: WriteStream | undefined;\n\tlet totalBytes = 0;\n\n\tconst ensureTempFile = () => {\n\t\tif (tempFilePath) {\n\t\t\treturn;\n\t\t}\n\t\tconst id = randomBytes(8).toString(\"hex\");\n\t\ttempFilePath = join(tmpdir(), `pi-bash-${id}.log`);\n\t\t// On stream failure (e.g. disk full), drop the artifact instead of\n\t\t// crashing the process; the rolling in-memory output is still returned.\n\t\ttempFileStream = createSafeWriteStream(tempFilePath, () => {\n\t\t\ttempFileStream = undefined;\n\t\t\ttempFilePath = undefined;\n\t\t});\n\t\tfor (const chunk of outputChunks) {\n\t\t\ttempFileStream.write(chunk);\n\t\t}\n\t};\n\n\tconst decoder = new TextDecoder();\n\n\tconst onData = (data: Buffer) => {\n\t\ttotalBytes += data.length;\n\n\t\t// Sanitize: strip ANSI, replace binary garbage, normalize newlines\n\t\tconst text = sanitizeBinaryOutput(stripAnsi(decoder.decode(data, { stream: true }))).replace(/\\r/g, \"\");\n\n\t\t// Start writing to temp file if exceeds threshold\n\t\tif (totalBytes > DEFAULT_MAX_BYTES) {\n\t\t\tensureTempFile();\n\t\t}\n\n\t\t// Guard writableEnded: custom BashOperations may deliver late onData\n\t\t// callbacks after an abort path has already ended the stream.\n\t\tif (tempFileStream && !tempFileStream.writableEnded) {\n\t\t\ttempFileStream.write(text);\n\t\t}\n\n\t\t// Keep rolling buffer\n\t\toutputChunks.push(text);\n\t\toutputBytes += text.length;\n\t\twhile (outputBytes > maxOutputBytes && outputChunks.length > 1) {\n\t\t\tconst removed = outputChunks.shift()!;\n\t\t\toutputBytes -= removed.length;\n\t\t}\n\n\t\t// Stream to callback\n\t\tif (options?.onChunk) {\n\t\t\toptions.onChunk(text);\n\t\t}\n\t};\n\n\ttry {\n\t\tconst result = await operations.exec(command, cwd, {\n\t\t\tonData,\n\t\t\tsignal: options?.signal,\n\t\t});\n\n\t\tconst fullOutput = outputChunks.join(\"\");\n\t\tconst truncationResult = truncateTail(fullOutput);\n\t\tif (truncationResult.truncated) {\n\t\t\tensureTempFile();\n\t\t}\n\t\tif (tempFileStream) {\n\t\t\t// Await the flush so fullOutputPath refers to a fully-written file on return, not one still\n\t\t\t// draining its buffer — otherwise a fast reader can see partial/empty content.\n\t\t\tawait endWriteStream(tempFileStream);\n\t\t}\n\t\tconst cancelled = options?.signal?.aborted ?? false;\n\n\t\treturn {\n\t\t\toutput: truncationResult.truncated ? truncationResult.content : fullOutput,\n\t\t\texitCode: cancelled ? undefined : (result.exitCode ?? undefined),\n\t\t\tcancelled,\n\t\t\ttruncated: truncationResult.truncated,\n\t\t\tfullOutputPath: tempFilePath,\n\t\t};\n\t} catch (err) {\n\t\t// Check if it was an abort\n\t\tif (options?.signal?.aborted) {\n\t\t\tconst fullOutput = outputChunks.join(\"\");\n\t\t\tconst truncationResult = truncateTail(fullOutput);\n\t\t\tif (truncationResult.truncated) {\n\t\t\t\tensureTempFile();\n\t\t\t}\n\t\t\tif (tempFileStream) {\n\t\t\t\tawait endWriteStream(tempFileStream);\n\t\t\t}\n\t\t\treturn {\n\t\t\t\toutput: truncationResult.truncated ? truncationResult.content : fullOutput,\n\t\t\t\texitCode: undefined,\n\t\t\t\tcancelled: true,\n\t\t\t\ttruncated: truncationResult.truncated,\n\t\t\t\tfullOutputPath: tempFilePath,\n\t\t\t};\n\t\t}\n\n\t\tif (tempFileStream) {\n\t\t\tawait endWriteStream(tempFileStream);\n\t\t}\n\n\t\t// The silence watchdog (see tools/bash.ts) throws a raw `silence:<secs>` sentinel.\n\t\t// Map it to the same user-facing message the interactive bash tool shows, instead of\n\t\t// leaking the sentinel to callers of this path (interactive !cmd, RPC).\n\t\tif (err instanceof Error && err.message.startsWith(\"silence:\")) {\n\t\t\tconst secs = err.message.split(\":\")[1];\n\t\t\tthrow new Error(\n\t\t\t\t`Command killed after ${secs}s of silence (no output). If the command is legitimately quiet for long stretches, re-run it with an explicit timeout, or run it in the background with '&'.`,\n\t\t\t);\n\t\t}\n\n\t\tthrow err;\n\t}\n}\n"]}
@@ -8,11 +8,11 @@
8
8
  import { randomBytes } from "node:crypto";
9
9
  import { tmpdir } from "node:os";
10
10
  import { join } from "node:path";
11
+ import { sanitizeBinaryOutput } from "@caupulican/pi-agent-core";
12
+ import { DEFAULT_MAX_BYTES, truncateTail } from "@caupulican/pi-agent-core/node";
11
13
  import { stripAnsi } from "../utils/ansi.js";
12
14
  import { createSafeWriteStream, endWriteStream } from "../utils/safe-write-stream.js";
13
- import { sanitizeBinaryOutput } from "../utils/shell.js";
14
15
  import { classifyGitCommand, executeFilteredGit } from "./tools/git-filter.js";
15
- import { DEFAULT_MAX_BYTES, truncateTail } from "./tools/truncate.js";
16
16
  // ============================================================================
17
17
  // Implementation
18
18
  // ============================================================================
@@ -148,6 +148,13 @@ export async function executeBashWithOperations(command, cwd, operations, option
148
148
  if (tempFileStream) {
149
149
  await endWriteStream(tempFileStream);
150
150
  }
151
+ // The silence watchdog (see tools/bash.ts) throws a raw `silence:<secs>` sentinel.
152
+ // Map it to the same user-facing message the interactive bash tool shows, instead of
153
+ // leaking the sentinel to callers of this path (interactive !cmd, RPC).
154
+ if (err instanceof Error && err.message.startsWith("silence:")) {
155
+ const secs = err.message.split(":")[1];
156
+ throw new Error(`Command killed after ${secs}s of silence (no output). If the command is legitimately quiet for long stretches, re-run it with an explicit timeout, or run it in the background with '&'.`);
157
+ }
151
158
  throw err;
152
159
  }
153
160
  }
@@ -1 +1 @@
1
- {"version":3,"file":"bash-executor.js","sourceRoot":"","sources":["../../src/core/bash-executor.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAE1C,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AACjC,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EAAE,qBAAqB,EAAE,cAAc,EAAE,MAAM,+BAA+B,CAAC;AACtF,OAAO,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAC;AAEzD,OAAO,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAC/E,OAAO,EAAE,iBAAiB,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AA4BtE,+EAA+E;AAC/E,iBAAiB;AACjB,+EAA+E;AAE/E;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,yBAAyB,CAC9C,OAAe,EACf,GAAW,EACX,UAA0B,EAC1B,OAA6B,EACP;IACtB,IAAI,OAAO,EAAE,eAAe,EAAE,CAAC;QAC9B,MAAM,cAAc,GAAG,kBAAkB,CAAC,OAAO,EAAE,OAAO,CAAC,GAAG,CAAC,CAAC;QAChE,IAAI,cAAc,CAAC,QAAQ,IAAI,cAAc,CAAC,UAAU,EAAE,CAAC;YAC1D,MAAM,GAAG,GAAG,MAAM,kBAAkB,CACnC,GAAG,EACH,cAAc,CAAC,UAAU,EACzB,cAAc,CAAC,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SAAS,CAAC,CAAC,CAAC,gBAAgB,CAAC,OAAO,CAAC,CAAC,CAAC,UAAU;YAC1E,QAAQ,EAAE,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,QAAQ,IAAI,SAAS,CAAC;YAChE,SAAS;YACT,SAAS,EAAE,gBAAgB,CAAC,SAAS;YACrC,cAAc,EAAE,YAAY;SAC5B,CAAC;IACH,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACd,2BAA2B;QAC3B,IAAI,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC;YAC9B,MAAM,UAAU,GAAG,YAAY,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;YACzC,MAAM,gBAAgB,GAAG,YAAY,CAAC,UAAU,CAAC,CAAC;YAClD,IAAI,gBAAgB,CAAC,SAAS,EAAE,CAAC;gBAChC,cAAc,EAAE,CAAC;YAClB,CAAC;YACD,IAAI,cAAc,EAAE,CAAC;gBACpB,MAAM,cAAc,CAAC,cAAc,CAAC,CAAC;YACtC,CAAC;YACD,OAAO;gBACN,MAAM,EAAE,gBAAgB,CAAC,SAAS,CAAC,CAAC,CAAC,gBAAgB,CAAC,OAAO,CAAC,CAAC,CAAC,UAAU;gBAC1E,QAAQ,EAAE,SAAS;gBACnB,SAAS,EAAE,IAAI;gBACf,SAAS,EAAE,gBAAgB,CAAC,SAAS;gBACrC,cAAc,EAAE,YAAY;aAC5B,CAAC;QACH,CAAC;QAED,IAAI,cAAc,EAAE,CAAC;YACpB,MAAM,cAAc,CAAC,cAAc,CAAC,CAAC;QACtC,CAAC;QAED,MAAM,GAAG,CAAC;IACX,CAAC;AAAA,CACD","sourcesContent":["/**\n * Bash command execution with streaming support and cancellation.\n *\n * This module provides a unified bash execution implementation used by:\n * - AgentSession.executeBash() for interactive and RPC modes\n * - Direct calls from modes that need bash execution\n */\n\nimport { randomBytes } from \"node:crypto\";\nimport type { WriteStream } from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { stripAnsi } from \"../utils/ansi.ts\";\nimport { createSafeWriteStream, endWriteStream } from \"../utils/safe-write-stream.ts\";\nimport { sanitizeBinaryOutput } from \"../utils/shell.ts\";\nimport type { BashOperations } from \"./tools/bash.ts\";\nimport { classifyGitCommand, executeFilteredGit } from \"./tools/git-filter.ts\";\nimport { DEFAULT_MAX_BYTES, truncateTail } from \"./tools/truncate.ts\";\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport interface BashExecutorOptions {\n\t/** Callback for streaming output chunks (already sanitized) */\n\tonChunk?: (chunk: string) => void;\n\t/** AbortSignal for cancellation */\n\tsignal?: AbortSignal;\n\t/** Enable conservative pi-native git output filtering for local default execution paths */\n\tenableGitFilter?: boolean;\n}\n\nexport interface BashResult {\n\t/** Combined stdout + stderr output (sanitized, possibly truncated) */\n\toutput: string;\n\t/** Process exit code (undefined if killed/cancelled) */\n\texitCode: number | undefined;\n\t/** Whether the command was cancelled via signal */\n\tcancelled: boolean;\n\t/** Whether the output was truncated */\n\ttruncated: boolean;\n\t/** Path to temp file containing full output (if output exceeded truncation threshold) */\n\tfullOutputPath?: string;\n}\n\n// ============================================================================\n// Implementation\n// ============================================================================\n\n/**\n * Execute a bash command using custom BashOperations.\n * Used for remote execution (SSH, containers, etc.).\n */\nexport async function executeBashWithOperations(\n\tcommand: string,\n\tcwd: string,\n\toperations: BashOperations,\n\toptions?: BashExecutorOptions,\n): Promise<BashResult> {\n\tif (options?.enableGitFilter) {\n\t\tconst classification = classifyGitCommand(command, process.env);\n\t\tif (classification.eligible && classification.subcommand) {\n\t\t\tconst res = await executeFilteredGit(\n\t\t\t\tcwd,\n\t\t\t\tclassification.subcommand,\n\t\t\t\tclassification.globalOptions || [],\n\t\t\t\tclassification.subcommandArgs || [],\n\t\t\t\t{ signal: options.signal },\n\t\t\t);\n\t\t\tif (res.exitCode !== -100) {\n\t\t\t\tconst rawBytes = res.rawBytes ?? Buffer.from(res.rawOut, \"utf-8\");\n\t\t\t\t// The filter already spills oversized output to a temp file; reuse it\n\t\t\t\t// instead of materializing another full copy here.\n\t\t\t\tlet fullOutputPath = res.fullOutputPath;\n\t\t\t\tif (fullOutputPath === undefined && rawBytes.length > DEFAULT_MAX_BYTES) {\n\t\t\t\t\tconst id = randomBytes(8).toString(\"hex\");\n\t\t\t\t\tconst spillPath = join(tmpdir(), `pi-bash-${id}.log`);\n\t\t\t\t\tfullOutputPath = spillPath;\n\t\t\t\t\t// On stream failure (e.g. disk full), drop the advertised path instead of\n\t\t\t\t\t// pointing at a partial/missing file.\n\t\t\t\t\tconst tempFileStream = createSafeWriteStream(spillPath, () => {\n\t\t\t\t\t\tfullOutputPath = undefined;\n\t\t\t\t\t});\n\t\t\t\t\ttempFileStream.write(rawBytes);\n\t\t\t\t\t// Await the flush so the returned path points at a COMPLETE file, not one mid-write.\n\t\t\t\t\tawait endWriteStream(tempFileStream);\n\t\t\t\t}\n\t\t\t\toptions.onChunk?.(res.output);\n\t\t\t\treturn {\n\t\t\t\t\toutput: res.output,\n\t\t\t\t\texitCode: res.exitCode,\n\t\t\t\t\tcancelled: options.signal?.aborted ?? false,\n\t\t\t\t\ttruncated: res.fullOutputPath !== undefined || rawBytes.length > DEFAULT_MAX_BYTES,\n\t\t\t\t\tfullOutputPath,\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t}\n\n\tconst outputChunks: string[] = [];\n\tlet outputBytes = 0;\n\tconst maxOutputBytes = DEFAULT_MAX_BYTES * 2;\n\n\tlet tempFilePath: string | undefined;\n\tlet tempFileStream: WriteStream | undefined;\n\tlet totalBytes = 0;\n\n\tconst ensureTempFile = () => {\n\t\tif (tempFilePath) {\n\t\t\treturn;\n\t\t}\n\t\tconst id = randomBytes(8).toString(\"hex\");\n\t\ttempFilePath = join(tmpdir(), `pi-bash-${id}.log`);\n\t\t// On stream failure (e.g. disk full), drop the artifact instead of\n\t\t// crashing the process; the rolling in-memory output is still returned.\n\t\ttempFileStream = createSafeWriteStream(tempFilePath, () => {\n\t\t\ttempFileStream = undefined;\n\t\t\ttempFilePath = undefined;\n\t\t});\n\t\tfor (const chunk of outputChunks) {\n\t\t\ttempFileStream.write(chunk);\n\t\t}\n\t};\n\n\tconst decoder = new TextDecoder();\n\n\tconst onData = (data: Buffer) => {\n\t\ttotalBytes += data.length;\n\n\t\t// Sanitize: strip ANSI, replace binary garbage, normalize newlines\n\t\tconst text = sanitizeBinaryOutput(stripAnsi(decoder.decode(data, { stream: true }))).replace(/\\r/g, \"\");\n\n\t\t// Start writing to temp file if exceeds threshold\n\t\tif (totalBytes > DEFAULT_MAX_BYTES) {\n\t\t\tensureTempFile();\n\t\t}\n\n\t\t// Guard writableEnded: custom BashOperations may deliver late onData\n\t\t// callbacks after an abort path has already ended the stream.\n\t\tif (tempFileStream && !tempFileStream.writableEnded) {\n\t\t\ttempFileStream.write(text);\n\t\t}\n\n\t\t// Keep rolling buffer\n\t\toutputChunks.push(text);\n\t\toutputBytes += text.length;\n\t\twhile (outputBytes > maxOutputBytes && outputChunks.length > 1) {\n\t\t\tconst removed = outputChunks.shift()!;\n\t\t\toutputBytes -= removed.length;\n\t\t}\n\n\t\t// Stream to callback\n\t\tif (options?.onChunk) {\n\t\t\toptions.onChunk(text);\n\t\t}\n\t};\n\n\ttry {\n\t\tconst result = await operations.exec(command, cwd, {\n\t\t\tonData,\n\t\t\tsignal: options?.signal,\n\t\t});\n\n\t\tconst fullOutput = outputChunks.join(\"\");\n\t\tconst truncationResult = truncateTail(fullOutput);\n\t\tif (truncationResult.truncated) {\n\t\t\tensureTempFile();\n\t\t}\n\t\tif (tempFileStream) {\n\t\t\t// Await the flush so fullOutputPath refers to a fully-written file on return, not one still\n\t\t\t// draining its buffer — otherwise a fast reader can see partial/empty content.\n\t\t\tawait endWriteStream(tempFileStream);\n\t\t}\n\t\tconst cancelled = options?.signal?.aborted ?? false;\n\n\t\treturn {\n\t\t\toutput: truncationResult.truncated ? truncationResult.content : fullOutput,\n\t\t\texitCode: cancelled ? undefined : (result.exitCode ?? undefined),\n\t\t\tcancelled,\n\t\t\ttruncated: truncationResult.truncated,\n\t\t\tfullOutputPath: tempFilePath,\n\t\t};\n\t} catch (err) {\n\t\t// Check if it was an abort\n\t\tif (options?.signal?.aborted) {\n\t\t\tconst fullOutput = outputChunks.join(\"\");\n\t\t\tconst truncationResult = truncateTail(fullOutput);\n\t\t\tif (truncationResult.truncated) {\n\t\t\t\tensureTempFile();\n\t\t\t}\n\t\t\tif (tempFileStream) {\n\t\t\t\tawait endWriteStream(tempFileStream);\n\t\t\t}\n\t\t\treturn {\n\t\t\t\toutput: truncationResult.truncated ? truncationResult.content : fullOutput,\n\t\t\t\texitCode: undefined,\n\t\t\t\tcancelled: true,\n\t\t\t\ttruncated: truncationResult.truncated,\n\t\t\t\tfullOutputPath: tempFilePath,\n\t\t\t};\n\t\t}\n\n\t\tif (tempFileStream) {\n\t\t\tawait endWriteStream(tempFileStream);\n\t\t}\n\n\t\tthrow err;\n\t}\n}\n"]}
1
+ {"version":3,"file":"bash-executor.js","sourceRoot":"","sources":["../../src/core/bash-executor.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAE1C,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AACjC,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,oBAAoB,EAAE,MAAM,2BAA2B,CAAC;AACjE,OAAO,EAAE,iBAAiB,EAAE,YAAY,EAAE,MAAM,gCAAgC,CAAC;AACjF,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EAAE,qBAAqB,EAAE,cAAc,EAAE,MAAM,+BAA+B,CAAC;AAEtF,OAAO,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AA4B/E,+EAA+E;AAC/E,iBAAiB;AACjB,+EAA+E;AAE/E;;;GAGG;A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,CAAC,SAAS;gBACrC,cAAc,EAAE,YAAY;aAC5B,CAAC;QACH,CAAC;QAED,IAAI,cAAc,EAAE,CAAC;YACpB,MAAM,cAAc,CAAC,cAAc,CAAC,CAAC;QACtC,CAAC;QAED,mFAAmF;QACnF,qFAAqF;QACrF,wEAAwE;QACxE,IAAI,GAAG,YAAY,KAAK,IAAI,GAAG,CAAC,OAAO,CAAC,UAAU,CAAC,UAAU,CAAC,EAAE,CAAC;YAChE,MAAM,IAAI,GAAG,GAAG,CAAC,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;YACvC,MAAM,IAAI,KAAK,CACd,wBAAwB,IAAI,8JAA8J,CAC1L,CAAC;QACH,CAAC;QAED,MAAM,GAAG,CAAC;IACX,CAAC;AAAA,CACD","sourcesContent":["/**\n * Bash command execution with streaming support and cancellation.\n *\n * This module provides a unified bash execution implementation used by:\n * - AgentSession.executeBash() for interactive and RPC modes\n * - Direct calls from modes that need bash execution\n */\n\nimport { randomBytes } from \"node:crypto\";\nimport type { WriteStream } from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { sanitizeBinaryOutput } from \"@caupulican/pi-agent-core\";\nimport { DEFAULT_MAX_BYTES, truncateTail } from \"@caupulican/pi-agent-core/node\";\nimport { stripAnsi } from \"../utils/ansi.ts\";\nimport { createSafeWriteStream, endWriteStream } from \"../utils/safe-write-stream.ts\";\nimport type { BashOperations } from \"./tools/bash.ts\";\nimport { classifyGitCommand, executeFilteredGit } from \"./tools/git-filter.ts\";\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport interface BashExecutorOptions {\n\t/** Callback for streaming output chunks (already sanitized) */\n\tonChunk?: (chunk: string) => void;\n\t/** AbortSignal for cancellation */\n\tsignal?: AbortSignal;\n\t/** Enable conservative pi-native git output filtering for local default execution paths */\n\tenableGitFilter?: boolean;\n}\n\nexport interface BashResult {\n\t/** Combined stdout + stderr output (sanitized, possibly truncated) */\n\toutput: string;\n\t/** Process exit code (undefined if killed/cancelled) */\n\texitCode: number | undefined;\n\t/** Whether the command was cancelled via signal */\n\tcancelled: boolean;\n\t/** Whether the output was truncated */\n\ttruncated: boolean;\n\t/** Path to temp file containing full output (if output exceeded truncation threshold) */\n\tfullOutputPath?: string;\n}\n\n// ============================================================================\n// Implementation\n// ============================================================================\n\n/**\n * Execute a bash command using custom BashOperations.\n * Used for remote execution (SSH, containers, etc.).\n */\nexport async function executeBashWithOperations(\n\tcommand: string,\n\tcwd: string,\n\toperations: BashOperations,\n\toptions?: BashExecutorOptions,\n): Promise<BashResult> {\n\tif (options?.enableGitFilter) {\n\t\tconst classification = classifyGitCommand(command, process.env);\n\t\tif (classification.eligible && classification.subcommand) {\n\t\t\tconst res = await executeFilteredGit(\n\t\t\t\tcwd,\n\t\t\t\tclassification.subcommand,\n\t\t\t\tclassification.globalOptions || [],\n\t\t\t\tclassification.subcommandArgs || [],\n\t\t\t\t{ signal: options.signal },\n\t\t\t);\n\t\t\tif (res.exitCode !== -100) {\n\t\t\t\tconst rawBytes = res.rawBytes ?? Buffer.from(res.rawOut, \"utf-8\");\n\t\t\t\t// The filter already spills oversized output to a temp file; reuse it\n\t\t\t\t// instead of materializing another full copy here.\n\t\t\t\tlet fullOutputPath = res.fullOutputPath;\n\t\t\t\tif (fullOutputPath === undefined && rawBytes.length > DEFAULT_MAX_BYTES) {\n\t\t\t\t\tconst id = randomBytes(8).toString(\"hex\");\n\t\t\t\t\tconst spillPath = join(tmpdir(), `pi-bash-${id}.log`);\n\t\t\t\t\tfullOutputPath = spillPath;\n\t\t\t\t\t// On stream failure (e.g. disk full), drop the advertised path instead of\n\t\t\t\t\t// pointing at a partial/missing file.\n\t\t\t\t\tconst tempFileStream = createSafeWriteStream(spillPath, () => {\n\t\t\t\t\t\tfullOutputPath = undefined;\n\t\t\t\t\t});\n\t\t\t\t\ttempFileStream.write(rawBytes);\n\t\t\t\t\t// Await the flush so the returned path points at a COMPLETE file, not one mid-write.\n\t\t\t\t\tawait endWriteStream(tempFileStream);\n\t\t\t\t}\n\t\t\t\toptions.onChunk?.(res.output);\n\t\t\t\treturn {\n\t\t\t\t\toutput: res.output,\n\t\t\t\t\texitCode: res.exitCode,\n\t\t\t\t\tcancelled: options.signal?.aborted ?? false,\n\t\t\t\t\ttruncated: res.fullOutputPath !== undefined || rawBytes.length > DEFAULT_MAX_BYTES,\n\t\t\t\t\tfullOutputPath,\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t}\n\n\tconst outputChunks: string[] = [];\n\tlet outputBytes = 0;\n\tconst maxOutputBytes = DEFAULT_MAX_BYTES * 2;\n\n\tlet tempFilePath: string | undefined;\n\tlet tempFileStream: WriteStream | undefined;\n\tlet totalBytes = 0;\n\n\tconst ensureTempFile = () => {\n\t\tif (tempFilePath) {\n\t\t\treturn;\n\t\t}\n\t\tconst id = randomBytes(8).toString(\"hex\");\n\t\ttempFilePath = join(tmpdir(), `pi-bash-${id}.log`);\n\t\t// On stream failure (e.g. disk full), drop the artifact instead of\n\t\t// crashing the process; the rolling in-memory output is still returned.\n\t\ttempFileStream = createSafeWriteStream(tempFilePath, () => {\n\t\t\ttempFileStream = undefined;\n\t\t\ttempFilePath = undefined;\n\t\t});\n\t\tfor (const chunk of outputChunks) {\n\t\t\ttempFileStream.write(chunk);\n\t\t}\n\t};\n\n\tconst decoder = new TextDecoder();\n\n\tconst onData = (data: Buffer) => {\n\t\ttotalBytes += data.length;\n\n\t\t// Sanitize: strip ANSI, replace binary garbage, normalize newlines\n\t\tconst text = sanitizeBinaryOutput(stripAnsi(decoder.decode(data, { stream: true }))).replace(/\\r/g, \"\");\n\n\t\t// Start writing to temp file if exceeds threshold\n\t\tif (totalBytes > DEFAULT_MAX_BYTES) {\n\t\t\tensureTempFile();\n\t\t}\n\n\t\t// Guard writableEnded: custom BashOperations may deliver late onData\n\t\t// callbacks after an abort path has already ended the stream.\n\t\tif (tempFileStream && !tempFileStream.writableEnded) {\n\t\t\ttempFileStream.write(text);\n\t\t}\n\n\t\t// Keep rolling buffer\n\t\toutputChunks.push(text);\n\t\toutputBytes += text.length;\n\t\twhile (outputBytes > maxOutputBytes && outputChunks.length > 1) {\n\t\t\tconst removed = outputChunks.shift()!;\n\t\t\toutputBytes -= removed.length;\n\t\t}\n\n\t\t// Stream to callback\n\t\tif (options?.onChunk) {\n\t\t\toptions.onChunk(text);\n\t\t}\n\t};\n\n\ttry {\n\t\tconst result = await operations.exec(command, cwd, {\n\t\t\tonData,\n\t\t\tsignal: options?.signal,\n\t\t});\n\n\t\tconst fullOutput = outputChunks.join(\"\");\n\t\tconst truncationResult = truncateTail(fullOutput);\n\t\tif (truncationResult.truncated) {\n\t\t\tensureTempFile();\n\t\t}\n\t\tif (tempFileStream) {\n\t\t\t// Await the flush so fullOutputPath refers to a fully-written file on return, not one still\n\t\t\t// draining its buffer — otherwise a fast reader can see partial/empty content.\n\t\t\tawait endWriteStream(tempFileStream);\n\t\t}\n\t\tconst cancelled = options?.signal?.aborted ?? false;\n\n\t\treturn {\n\t\t\toutput: truncationResult.truncated ? truncationResult.content : fullOutput,\n\t\t\texitCode: cancelled ? undefined : (result.exitCode ?? undefined),\n\t\t\tcancelled,\n\t\t\ttruncated: truncationResult.truncated,\n\t\t\tfullOutputPath: tempFilePath,\n\t\t};\n\t} catch (err) {\n\t\t// Check if it was an abort\n\t\tif (options?.signal?.aborted) {\n\t\t\tconst fullOutput = outputChunks.join(\"\");\n\t\t\tconst truncationResult = truncateTail(fullOutput);\n\t\t\tif (truncationResult.truncated) {\n\t\t\t\tensureTempFile();\n\t\t\t}\n\t\t\tif (tempFileStream) {\n\t\t\t\tawait endWriteStream(tempFileStream);\n\t\t\t}\n\t\t\treturn {\n\t\t\t\toutput: truncationResult.truncated ? truncationResult.content : fullOutput,\n\t\t\t\texitCode: undefined,\n\t\t\t\tcancelled: true,\n\t\t\t\ttruncated: truncationResult.truncated,\n\t\t\t\tfullOutputPath: tempFilePath,\n\t\t\t};\n\t\t}\n\n\t\tif (tempFileStream) {\n\t\t\tawait endWriteStream(tempFileStream);\n\t\t}\n\n\t\t// The silence watchdog (see tools/bash.ts) throws a raw `silence:<secs>` sentinel.\n\t\t// Map it to the same user-facing message the interactive bash tool shows, instead of\n\t\t// leaking the sentinel to callers of this path (interactive !cmd, RPC).\n\t\tif (err instanceof Error && err.message.startsWith(\"silence:\")) {\n\t\t\tconst secs = err.message.split(\":\")[1];\n\t\t\tthrow new Error(\n\t\t\t\t`Command killed after ${secs}s of silence (no output). If the command is legitimately quiet for long stretches, re-run it with an explicit timeout, or run it in the background with '&'.`,\n\t\t\t);\n\t\t}\n\n\t\tthrow err;\n\t}\n}\n"]}
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Compaction support: summarizer model selection (#30 cost guard), request-auth resolution
3
+ * with session-model fallback, and window-adapted compaction settings.
4
+ *
5
+ * Extracted verbatim from AgentSession (agent-session.ts) as a narrow-deps collaborator; the
6
+ * session keeps same-signature private delegations at every call-in point.
7
+ */
8
+ import type { CompactionSettings } from "@caupulican/pi-agent-core/node";
9
+ import type { Model } from "@caupulican/pi-ai";
10
+ import type { ModelRegistry } from "./model-registry.ts";
11
+ import type { SettingsManager } from "./settings-manager.ts";
12
+ export interface CompactionSupportDeps {
13
+ getModel(): Model<any> | undefined;
14
+ getSettingsManager(): SettingsManager;
15
+ getModelRegistry(): ModelRegistry;
16
+ /** True when the agent's streamFn is (or wraps) the raw streamSimple — auth must be explicit then. */
17
+ isRawStream(): boolean;
18
+ /** Host auth resolution that THROWS with a user-actionable message when no key exists. */
19
+ getRequiredRequestAuth(model: Model<any>): Promise<{
20
+ apiKey?: string;
21
+ headers?: Record<string, string>;
22
+ }>;
23
+ }
24
+ export declare class CompactionSupport {
25
+ private readonly deps;
26
+ constructor(deps: CompactionSupportDeps);
27
+ getAdaptedSettings(): CompactionSettings;
28
+ getRequestAuth(model: Model<any>): Promise<{
29
+ apiKey?: string;
30
+ headers?: Record<string, string>;
31
+ }>;
32
+ /**
33
+ * Resolve the summarizer model AND its request auth for auto-compaction. The cheap auxiliary
34
+ * model (#30) can be nominally available yet fail key resolution at request time (expired
35
+ * OAuth, revoked key). Falling back to the session model keeps auto-compaction working in
36
+ * exactly the situations where manual /compact works; only when neither resolves do we fail —
37
+ * and then with a concrete message instead of a silent no-op.
38
+ */
39
+ resolveModelAndAuth(compactionModel: Model<any>, sessionModel: Model<any>): Promise<{
40
+ model: Model<any>;
41
+ apiKey?: string;
42
+ headers?: Record<string, string>;
43
+ failure?: string;
44
+ }>;
45
+ /**
46
+ * Resolve the model used to SUMMARIZE during compaction (cost guard, #30). A compaction summary is an
47
+ * extraction task — it does not need the main (expensive) model. Selection:
48
+ * - an explicit `compaction.model` setting wins, but only if its provider is authed (else fall back);
49
+ * - `"auto"` (default) picks the CHEAPEST authed model whose context window can hold a compaction
50
+ * (capability floor), and ONLY if it is strictly cheaper than the session model — so we never
51
+ * downgrade to an equally-priced but weaker summarizer (agy's floor: don't degrade the checkpoint);
52
+ * - otherwise the session model is used (safe default).
53
+ */
54
+ resolveModel(sessionModel: Model<any>): Model<any>;
55
+ }
56
+ //# sourceMappingURL=compaction-support.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"compaction-support.d.ts","sourceRoot":"","sources":["../../src/core/compaction-support.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,gCAAgC,CAAC;AACzE,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAC;AAC/C,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAEzD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAE7D,MAAM,WAAW,qBAAqB;IACrC,QAAQ,IAAI,KAAK,CAAC,GAAG,CAAC,GAAG,SAAS,CAAC;IACnC,kBAAkB,IAAI,eAAe,CAAC;IACtC,gBAAgB,IAAI,aAAa,CAAC;IAClC,wGAAsG;IACtG,WAAW,IAAI,OAAO,CAAC;IACvB,0FAA0F;IAC1F,sBAAsB,CAAC,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,GAAG,OAAO,CAAC;QAAE,MAAM,CAAC,EAAE,MAAM,CAAC;QAAC,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;KAAE,CAAC,CAAC;CAC1G;AAED,qBAAa,iBAAiB;IAC7B,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAwB;IAE7C,YAAY,IAAI,EAAE,qBAAqB,EAEtC;IAED,kBAAkB,IAAI,kBAAkB,CAoBvC;IAEK,cAAc,CAAC,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,GAAG,OAAO,CAAC;QAChD,MAAM,CAAC,EAAE,MAAM,CAAC;QAChB,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;KACjC,CAAC,CAOD;IAED;;;;;;OAMG;IACG,mBAAmB,CACxB,eAAe,EAAE,KAAK,CAAC,GAAG,CAAC,EAC3B,YAAY,EAAE,KAAK,CAAC,GAAG,CAAC,GACtB,OAAO,CAAC;QAAE,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,CAAC;QAAC,MAAM,CAAC,EAAE,MAAM,CAAC;QAAC,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;QAAC,OAAO,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC,CAwBrG;IAED;;;;;;;;OAQG;IACH,YAAY,CAAC,YAAY,EAAE,KAAK,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC,GAAG,CAAC,CAoBjD;CACD","sourcesContent":["/**\n * Compaction support: summarizer model selection (#30 cost guard), request-auth resolution\n * with session-model fallback, and window-adapted compaction settings.\n *\n * Extracted verbatim from AgentSession (agent-session.ts) as a narrow-deps collaborator; the\n * session keeps same-signature private delegations at every call-in point.\n */\nimport type { CompactionSettings } from \"@caupulican/pi-agent-core/node\";\nimport type { Model } from \"@caupulican/pi-ai\";\nimport type { ModelRegistry } from \"./model-registry.ts\";\nimport { resolveCliModel } from \"./model-resolver.ts\";\nimport type { SettingsManager } from \"./settings-manager.ts\";\n\nexport interface CompactionSupportDeps {\n\tgetModel(): Model<any> | undefined;\n\tgetSettingsManager(): SettingsManager;\n\tgetModelRegistry(): ModelRegistry;\n\t/** True when the agent's streamFn is (or wraps) the raw streamSimple — auth must be explicit then. */\n\tisRawStream(): boolean;\n\t/** Host auth resolution that THROWS with a user-actionable message when no key exists. */\n\tgetRequiredRequestAuth(model: Model<any>): Promise<{ apiKey?: string; headers?: Record<string, string> }>;\n}\n\nexport class CompactionSupport {\n\tprivate readonly deps: CompactionSupportDeps;\n\n\tconstructor(deps: CompactionSupportDeps) {\n\t\tthis.deps = deps;\n\t}\n\n\tgetAdaptedSettings(): CompactionSettings {\n\t\tconst settings = this.deps.getSettingsManager().getCompactionSettings();\n\t\tconst model = this.deps.getModel();\n\t\tif (!model) return settings;\n\t\tconst contextWindow = model.contextWindow ?? 0;\n\t\tif (contextWindow <= 0) return settings;\n\n\t\t// Adapt reserveTokens: at most 25% of context window\n\t\tconst maxReserve = Math.floor(contextWindow * 0.25);\n\t\tconst reserveTokens = Math.min(settings.reserveTokens, maxReserve);\n\n\t\t// Adapt keepRecentTokens: at most 50% of context window\n\t\tconst maxKeepRecent = Math.floor(contextWindow * 0.5);\n\t\tconst keepRecentTokens = Math.min(settings.keepRecentTokens, maxKeepRecent);\n\n\t\treturn {\n\t\t\t...settings,\n\t\t\treserveTokens,\n\t\t\tkeepRecentTokens,\n\t\t};\n\t}\n\n\tasync getRequestAuth(model: Model<any>): Promise<{\n\t\tapiKey?: string;\n\t\theaders?: Record<string, string>;\n\t}> {\n\t\tif (this.deps.isRawStream()) {\n\t\t\treturn this.deps.getRequiredRequestAuth(model);\n\t\t}\n\n\t\tconst result = await this.deps.getModelRegistry().getApiKeyAndHeaders(model);\n\t\treturn result.ok ? { apiKey: result.apiKey, headers: result.headers } : {};\n\t}\n\n\t/**\n\t * Resolve the summarizer model AND its request auth for auto-compaction. The cheap auxiliary\n\t * model (#30) can be nominally available yet fail key resolution at request time (expired\n\t * OAuth, revoked key). Falling back to the session model keeps auto-compaction working in\n\t * exactly the situations where manual /compact works; only when neither resolves do we fail —\n\t * and then with a concrete message instead of a silent no-op.\n\t */\n\tasync resolveModelAndAuth(\n\t\tcompactionModel: Model<any>,\n\t\tsessionModel: Model<any>,\n\t): Promise<{ model: Model<any>; apiKey?: string; headers?: Record<string, string>; failure?: string }> {\n\t\tif (this.deps.isRawStream()) {\n\t\t\tconst registry = this.deps.getModelRegistry();\n\t\t\tlet auth = await registry.getApiKeyAndHeaders(compactionModel);\n\t\t\tif (auth.ok && auth.apiKey) {\n\t\t\t\treturn { model: compactionModel, apiKey: auth.apiKey, headers: auth.headers };\n\t\t\t}\n\t\t\tconst isSameModel =\n\t\t\t\tcompactionModel.provider === sessionModel.provider && compactionModel.id === sessionModel.id;\n\t\t\tif (!isSameModel) {\n\t\t\t\tauth = await registry.getApiKeyAndHeaders(sessionModel);\n\t\t\t\tif (auth.ok && auth.apiKey) {\n\t\t\t\t\treturn { model: sessionModel, apiKey: auth.apiKey, headers: auth.headers };\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tmodel: sessionModel,\n\t\t\t\tfailure: `no usable API key for the summarizer (tried ${compactionModel.id}${isSameModel ? \"\" : ` and ${sessionModel.id}`})`,\n\t\t\t};\n\t\t}\n\n\t\t// Custom streamFn owns auth injection (CLI path) — resolve best-effort, never fail here.\n\t\tconst { apiKey, headers } = await this.getRequestAuth(compactionModel);\n\t\treturn { model: compactionModel, apiKey, headers };\n\t}\n\n\t/**\n\t * Resolve the model used to SUMMARIZE during compaction (cost guard, #30). A compaction summary is an\n\t * extraction task — it does not need the main (expensive) model. Selection:\n\t * - an explicit `compaction.model` setting wins, but only if its provider is authed (else fall back);\n\t * - `\"auto\"` (default) picks the CHEAPEST authed model whose context window can hold a compaction\n\t * (capability floor), and ONLY if it is strictly cheaper than the session model — so we never\n\t * downgrade to an equally-priced but weaker summarizer (agy's floor: don't degrade the checkpoint);\n\t * - otherwise the session model is used (safe default).\n\t */\n\tresolveModel(sessionModel: Model<any>): Model<any> {\n\t\tconst registry = this.deps.getModelRegistry();\n\t\tconst setting = this.deps.getSettingsManager().getCompactionModel();\n\t\tif (setting && setting !== \"auto\") {\n\t\t\tconst resolved = resolveCliModel({ cliModel: setting, modelRegistry: registry });\n\t\t\tif (resolved.model && registry.hasConfiguredAuth(resolved.model)) return resolved.model;\n\t\t\treturn sessionModel; // configured but unusable → don't break compaction\n\t\t}\n\t\t// \"auto\": cheapest authed model that can summarize a large context AND is cheaper than the session\n\t\t// model. The context-window floor keeps a tiny local model from being picked for a big summary.\n\t\tconst FLOOR_CONTEXT = 64_000;\n\t\tconst sessionInputCost = sessionModel.cost?.input ?? Number.POSITIVE_INFINITY;\n\t\tlet best: Model<any> | undefined;\n\t\tfor (const m of registry.getAvailable()) {\n\t\t\tif ((m.contextWindow ?? 0) < FLOOR_CONTEXT) continue;\n\t\t\tconst cost = m.cost?.input ?? Number.POSITIVE_INFINITY;\n\t\t\tif (cost >= sessionInputCost) continue; // only ever pick something cheaper than the session model\n\t\t\tif (!best || cost < (best.cost?.input ?? Number.POSITIVE_INFINITY)) best = m;\n\t\t}\n\t\treturn best ?? sessionModel;\n\t}\n}\n"]}