@caupulican/pi-adaptative 0.80.103 → 0.81.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (409) hide show
  1. package/CHANGELOG.md +128 -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 +154 -512
  16. package/dist/core/agent-session.d.ts.map +1 -1
  17. package/dist/core/agent-session.js +675 -4589
  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/http-dispatcher.d.ts +4 -1
  102. package/dist/core/http-dispatcher.d.ts.map +1 -1
  103. package/dist/core/http-dispatcher.js +6 -1
  104. package/dist/core/http-dispatcher.js.map +1 -1
  105. package/dist/core/index.d.ts +1 -1
  106. package/dist/core/index.d.ts.map +1 -1
  107. package/dist/core/index.js.map +1 -1
  108. package/dist/core/learning/learning-audit.d.ts +1 -1
  109. package/dist/core/learning/learning-audit.d.ts.map +1 -1
  110. package/dist/core/learning/learning-audit.js.map +1 -1
  111. package/dist/core/learning/session-learning-decision.d.ts +1 -1
  112. package/dist/core/learning/session-learning-decision.d.ts.map +1 -1
  113. package/dist/core/learning/session-learning-decision.js.map +1 -1
  114. package/dist/core/local-runtime-controller.d.ts +99 -0
  115. package/dist/core/local-runtime-controller.d.ts.map +1 -0
  116. package/dist/core/local-runtime-controller.js +214 -0
  117. package/dist/core/local-runtime-controller.js.map +1 -0
  118. package/dist/core/memory/providers/transcript-recall.d.ts.map +1 -1
  119. package/dist/core/memory/providers/transcript-recall.js +1 -1
  120. package/dist/core/memory/providers/transcript-recall.js.map +1 -1
  121. package/dist/core/memory-controller.d.ts +139 -0
  122. package/dist/core/memory-controller.d.ts.map +1 -0
  123. package/dist/core/memory-controller.js +323 -0
  124. package/dist/core/memory-controller.js.map +1 -0
  125. package/dist/core/model-router/status.d.ts +1 -1
  126. package/dist/core/model-router/status.d.ts.map +1 -1
  127. package/dist/core/model-router/status.js.map +1 -1
  128. package/dist/core/model-router-controller.d.ts +140 -0
  129. package/dist/core/model-router-controller.d.ts.map +1 -0
  130. package/dist/core/model-router-controller.js +623 -0
  131. package/dist/core/model-router-controller.js.map +1 -0
  132. package/dist/core/model-selection-controller.d.ts +95 -0
  133. package/dist/core/model-selection-controller.d.ts.map +1 -0
  134. package/dist/core/model-selection-controller.js +252 -0
  135. package/dist/core/model-selection-controller.js.map +1 -0
  136. package/dist/core/models/model-ref.d.ts +13 -0
  137. package/dist/core/models/model-ref.d.ts.map +1 -1
  138. package/dist/core/models/model-ref.js +22 -0
  139. package/dist/core/models/model-ref.js.map +1 -1
  140. package/dist/core/profile-filter-controller.d.ts +77 -0
  141. package/dist/core/profile-filter-controller.d.ts.map +1 -0
  142. package/dist/core/profile-filter-controller.js +159 -0
  143. package/dist/core/profile-filter-controller.js.map +1 -0
  144. package/dist/core/reflection-controller.d.ts +111 -0
  145. package/dist/core/reflection-controller.d.ts.map +1 -0
  146. package/dist/core/reflection-controller.js +412 -0
  147. package/dist/core/reflection-controller.js.map +1 -0
  148. package/dist/core/research/model-fitness.d.ts +12 -0
  149. package/dist/core/research/model-fitness.d.ts.map +1 -1
  150. package/dist/core/research/model-fitness.js +21 -0
  151. package/dist/core/research/model-fitness.js.map +1 -1
  152. package/dist/core/research/session-evidence-bundle.d.ts +1 -1
  153. package/dist/core/research/session-evidence-bundle.d.ts.map +1 -1
  154. package/dist/core/research/session-evidence-bundle.js.map +1 -1
  155. package/dist/core/runtime-builder.d.ts +222 -0
  156. package/dist/core/runtime-builder.d.ts.map +1 -0
  157. package/dist/core/runtime-builder.js +640 -0
  158. package/dist/core/runtime-builder.js.map +1 -0
  159. package/dist/core/sdk.d.ts +2 -2
  160. package/dist/core/sdk.d.ts.map +1 -1
  161. package/dist/core/sdk.js +3 -4
  162. package/dist/core/sdk.js.map +1 -1
  163. package/dist/core/session-analytics.d.ts +96 -0
  164. package/dist/core/session-analytics.d.ts.map +1 -0
  165. package/dist/core/session-analytics.js +331 -0
  166. package/dist/core/session-analytics.js.map +1 -0
  167. package/dist/core/session-manager-factory.d.ts +18 -0
  168. package/dist/core/session-manager-factory.d.ts.map +1 -0
  169. package/dist/core/session-manager-factory.js +32 -0
  170. package/dist/core/session-manager-factory.js.map +1 -0
  171. package/dist/core/session-tree-navigator.d.ts +68 -0
  172. package/dist/core/session-tree-navigator.d.ts.map +1 -0
  173. package/dist/core/session-tree-navigator.js +217 -0
  174. package/dist/core/session-tree-navigator.js.map +1 -0
  175. package/dist/core/settings-manager.d.ts +16 -0
  176. package/dist/core/settings-manager.d.ts.map +1 -1
  177. package/dist/core/settings-manager.js +22 -0
  178. package/dist/core/settings-manager.js.map +1 -1
  179. package/dist/core/system-prompt-builder.d.ts +63 -0
  180. package/dist/core/system-prompt-builder.d.ts.map +1 -0
  181. package/dist/core/system-prompt-builder.js +181 -0
  182. package/dist/core/system-prompt-builder.js.map +1 -0
  183. package/dist/core/tool-gate-controller.d.ts +36 -0
  184. package/dist/core/tool-gate-controller.d.ts.map +1 -0
  185. package/dist/core/tool-gate-controller.js +94 -0
  186. package/dist/core/tool-gate-controller.js.map +1 -0
  187. package/dist/core/tools/artifact-retrieve.d.ts.map +1 -1
  188. package/dist/core/tools/artifact-retrieve.js +1 -1
  189. package/dist/core/tools/artifact-retrieve.js.map +1 -1
  190. package/dist/core/tools/bash.d.ts +4 -2
  191. package/dist/core/tools/bash.d.ts.map +1 -1
  192. package/dist/core/tools/bash.js +49 -7
  193. package/dist/core/tools/bash.js.map +1 -1
  194. package/dist/core/tools/file-mutation-queue.d.ts +6 -0
  195. package/dist/core/tools/file-mutation-queue.d.ts.map +1 -1
  196. package/dist/core/tools/file-mutation-queue.js +61 -1
  197. package/dist/core/tools/file-mutation-queue.js.map +1 -1
  198. package/dist/core/tools/find.d.ts +1 -1
  199. package/dist/core/tools/find.d.ts.map +1 -1
  200. package/dist/core/tools/find.js +1 -1
  201. package/dist/core/tools/find.js.map +1 -1
  202. package/dist/core/tools/grep.d.ts +1 -1
  203. package/dist/core/tools/grep.d.ts.map +1 -1
  204. package/dist/core/tools/grep.js +1 -1
  205. package/dist/core/tools/grep.js.map +1 -1
  206. package/dist/core/tools/index.d.ts +1 -1
  207. package/dist/core/tools/index.d.ts.map +1 -1
  208. package/dist/core/tools/index.js +1 -1
  209. package/dist/core/tools/index.js.map +1 -1
  210. package/dist/core/tools/ls.d.ts +1 -1
  211. package/dist/core/tools/ls.d.ts.map +1 -1
  212. package/dist/core/tools/ls.js +1 -1
  213. package/dist/core/tools/ls.js.map +1 -1
  214. package/dist/core/tools/output-accumulator.d.ts +1 -1
  215. package/dist/core/tools/output-accumulator.d.ts.map +1 -1
  216. package/dist/core/tools/output-accumulator.js +1 -1
  217. package/dist/core/tools/output-accumulator.js.map +1 -1
  218. package/dist/core/tools/read.d.ts +1 -1
  219. package/dist/core/tools/read.d.ts.map +1 -1
  220. package/dist/core/tools/read.js +1 -1
  221. package/dist/core/tools/read.js.map +1 -1
  222. package/dist/core/tools/render-utils.d.ts.map +1 -1
  223. package/dist/core/tools/render-utils.js +1 -1
  224. package/dist/core/tools/render-utils.js.map +1 -1
  225. package/dist/index.d.ts +2 -3
  226. package/dist/index.d.ts.map +1 -1
  227. package/dist/index.js +3 -4
  228. package/dist/index.js.map +1 -1
  229. package/dist/main.d.ts.map +1 -1
  230. package/dist/main.js +13 -12
  231. package/dist/main.js.map +1 -1
  232. package/dist/modes/interactive/auth-dialogs-controller.d.ts +59 -0
  233. package/dist/modes/interactive/auth-dialogs-controller.d.ts.map +1 -0
  234. package/dist/modes/interactive/auth-dialogs-controller.js +398 -0
  235. package/dist/modes/interactive/auth-dialogs-controller.js.map +1 -0
  236. package/dist/modes/interactive/auto-learn-controller.d.ts +168 -0
  237. package/dist/modes/interactive/auto-learn-controller.d.ts.map +1 -0
  238. package/dist/modes/interactive/auto-learn-controller.js +1239 -0
  239. package/dist/modes/interactive/auto-learn-controller.js.map +1 -0
  240. package/dist/modes/interactive/autocomplete-provider.d.ts +26 -0
  241. package/dist/modes/interactive/autocomplete-provider.d.ts.map +1 -0
  242. package/dist/modes/interactive/autocomplete-provider.js +103 -0
  243. package/dist/modes/interactive/autocomplete-provider.js.map +1 -0
  244. package/dist/modes/interactive/autonomy-commands.d.ts +38 -0
  245. package/dist/modes/interactive/autonomy-commands.d.ts.map +1 -0
  246. package/dist/modes/interactive/autonomy-commands.js +142 -0
  247. package/dist/modes/interactive/autonomy-commands.js.map +1 -0
  248. package/dist/modes/interactive/clipboard-input.d.ts +37 -0
  249. package/dist/modes/interactive/clipboard-input.d.ts.map +1 -0
  250. package/dist/modes/interactive/clipboard-input.js +59 -0
  251. package/dist/modes/interactive/clipboard-input.js.map +1 -0
  252. package/dist/modes/interactive/compaction-queue.d.ts +30 -0
  253. package/dist/modes/interactive/compaction-queue.d.ts.map +1 -0
  254. package/dist/modes/interactive/compaction-queue.js +91 -0
  255. package/dist/modes/interactive/compaction-queue.js.map +1 -0
  256. package/dist/modes/interactive/components/bash-execution.d.ts +1 -1
  257. package/dist/modes/interactive/components/bash-execution.d.ts.map +1 -1
  258. package/dist/modes/interactive/components/bash-execution.js +1 -1
  259. package/dist/modes/interactive/components/bash-execution.js.map +1 -1
  260. package/dist/modes/interactive/components/branch-summary-message.d.ts +1 -1
  261. package/dist/modes/interactive/components/branch-summary-message.d.ts.map +1 -1
  262. package/dist/modes/interactive/components/branch-summary-message.js.map +1 -1
  263. package/dist/modes/interactive/components/compaction-summary-message.d.ts +1 -1
  264. package/dist/modes/interactive/components/compaction-summary-message.d.ts.map +1 -1
  265. package/dist/modes/interactive/components/compaction-summary-message.js.map +1 -1
  266. package/dist/modes/interactive/components/custom-message.d.ts +1 -1
  267. package/dist/modes/interactive/components/custom-message.d.ts.map +1 -1
  268. package/dist/modes/interactive/components/custom-message.js.map +1 -1
  269. package/dist/modes/interactive/components/session-selector-search.d.ts +1 -1
  270. package/dist/modes/interactive/components/session-selector-search.d.ts.map +1 -1
  271. package/dist/modes/interactive/components/session-selector-search.js.map +1 -1
  272. package/dist/modes/interactive/components/session-selector.d.ts +1 -1
  273. package/dist/modes/interactive/components/session-selector.d.ts.map +1 -1
  274. package/dist/modes/interactive/components/session-selector.js.map +1 -1
  275. package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
  276. package/dist/modes/interactive/components/tool-execution.js +2 -2
  277. package/dist/modes/interactive/components/tool-execution.js.map +1 -1
  278. package/dist/modes/interactive/components/tree-selector.d.ts +1 -1
  279. package/dist/modes/interactive/components/tree-selector.d.ts.map +1 -1
  280. package/dist/modes/interactive/components/tree-selector.js.map +1 -1
  281. package/dist/modes/interactive/config-backup.d.ts +27 -0
  282. package/dist/modes/interactive/config-backup.d.ts.map +1 -0
  283. package/dist/modes/interactive/config-backup.js +146 -0
  284. package/dist/modes/interactive/config-backup.js.map +1 -0
  285. package/dist/modes/interactive/editor-overlay-host.d.ts +48 -0
  286. package/dist/modes/interactive/editor-overlay-host.d.ts.map +1 -0
  287. package/dist/modes/interactive/editor-overlay-host.js +43 -0
  288. package/dist/modes/interactive/editor-overlay-host.js.map +1 -0
  289. package/dist/modes/interactive/extension-ui-host.d.ts +165 -0
  290. package/dist/modes/interactive/extension-ui-host.d.ts.map +1 -0
  291. package/dist/modes/interactive/extension-ui-host.js +610 -0
  292. package/dist/modes/interactive/extension-ui-host.js.map +1 -0
  293. package/dist/modes/interactive/external-editor.d.ts +18 -0
  294. package/dist/modes/interactive/external-editor.d.ts.map +1 -0
  295. package/dist/modes/interactive/external-editor.js +107 -0
  296. package/dist/modes/interactive/external-editor.js.map +1 -0
  297. package/dist/modes/interactive/history-reload-math.d.ts +24 -0
  298. package/dist/modes/interactive/history-reload-math.d.ts.map +1 -0
  299. package/dist/modes/interactive/history-reload-math.js +129 -0
  300. package/dist/modes/interactive/history-reload-math.js.map +1 -0
  301. package/dist/modes/interactive/interactive-mode.d.ts +22 -238
  302. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  303. package/dist/modes/interactive/interactive-mode.js +714 -5910
  304. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  305. package/dist/modes/interactive/key-handlers.d.ts +46 -0
  306. package/dist/modes/interactive/key-handlers.d.ts.map +1 -0
  307. package/dist/modes/interactive/key-handlers.js +80 -0
  308. package/dist/modes/interactive/key-handlers.js.map +1 -0
  309. package/dist/modes/interactive/local-model-commands.d.ts +68 -0
  310. package/dist/modes/interactive/local-model-commands.d.ts.map +1 -0
  311. package/dist/modes/interactive/local-model-commands.js +288 -0
  312. package/dist/modes/interactive/local-model-commands.js.map +1 -0
  313. package/dist/modes/interactive/profile-menu-controller.d.ts +77 -0
  314. package/dist/modes/interactive/profile-menu-controller.d.ts.map +1 -0
  315. package/dist/modes/interactive/profile-menu-controller.js +917 -0
  316. package/dist/modes/interactive/profile-menu-controller.js.map +1 -0
  317. package/dist/modes/interactive/report-commands.d.ts +46 -0
  318. package/dist/modes/interactive/report-commands.d.ts.map +1 -0
  319. package/dist/modes/interactive/report-commands.js +255 -0
  320. package/dist/modes/interactive/report-commands.js.map +1 -0
  321. package/dist/modes/interactive/resource-display.d.ts +73 -0
  322. package/dist/modes/interactive/resource-display.d.ts.map +1 -0
  323. package/dist/modes/interactive/resource-display.js +278 -0
  324. package/dist/modes/interactive/resource-display.js.map +1 -0
  325. package/dist/modes/interactive/resource-shell-commands.d.ts +64 -0
  326. package/dist/modes/interactive/resource-shell-commands.d.ts.map +1 -0
  327. package/dist/modes/interactive/resource-shell-commands.js +202 -0
  328. package/dist/modes/interactive/resource-shell-commands.js.map +1 -0
  329. package/dist/modes/interactive/session-flow-commands.d.ts +139 -0
  330. package/dist/modes/interactive/session-flow-commands.d.ts.map +1 -0
  331. package/dist/modes/interactive/session-flow-commands.js +458 -0
  332. package/dist/modes/interactive/session-flow-commands.js.map +1 -0
  333. package/dist/modes/interactive/session-io-commands.d.ts +73 -0
  334. package/dist/modes/interactive/session-io-commands.d.ts.map +1 -0
  335. package/dist/modes/interactive/session-io-commands.js +202 -0
  336. package/dist/modes/interactive/session-io-commands.js.map +1 -0
  337. package/dist/modes/interactive/settings-selector-flow.d.ts +42 -0
  338. package/dist/modes/interactive/settings-selector-flow.d.ts.map +1 -0
  339. package/dist/modes/interactive/settings-selector-flow.js +287 -0
  340. package/dist/modes/interactive/settings-selector-flow.js.map +1 -0
  341. package/dist/modes/interactive/signal-lifecycle.d.ts +55 -0
  342. package/dist/modes/interactive/signal-lifecycle.d.ts.map +1 -0
  343. package/dist/modes/interactive/signal-lifecycle.js +177 -0
  344. package/dist/modes/interactive/signal-lifecycle.js.map +1 -0
  345. package/dist/modes/interactive/startup-checks.d.ts +38 -0
  346. package/dist/modes/interactive/startup-checks.d.ts.map +1 -0
  347. package/dist/modes/interactive/startup-checks.js +189 -0
  348. package/dist/modes/interactive/startup-checks.js.map +1 -0
  349. package/dist/modes/rpc/rpc-client.d.ts +1 -1
  350. package/dist/modes/rpc/rpc-client.d.ts.map +1 -1
  351. package/dist/modes/rpc/rpc-client.js.map +1 -1
  352. package/dist/modes/rpc/rpc-types.d.ts +1 -1
  353. package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
  354. package/dist/modes/rpc/rpc-types.js.map +1 -1
  355. package/dist/utils/paths.d.ts +2 -14
  356. package/dist/utils/paths.d.ts.map +1 -1
  357. package/dist/utils/paths.js +5 -30
  358. package/dist/utils/paths.js.map +1 -1
  359. package/dist/utils/process-memory.d.ts +8 -0
  360. package/dist/utils/process-memory.d.ts.map +1 -0
  361. package/dist/utils/process-memory.js +11 -0
  362. package/dist/utils/process-memory.js.map +1 -0
  363. package/dist/utils/shell.d.ts +0 -9
  364. package/dist/utils/shell.d.ts.map +1 -1
  365. package/dist/utils/shell.js +0 -37
  366. package/dist/utils/shell.js.map +1 -1
  367. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  368. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  369. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  370. package/examples/extensions/sandbox/package-lock.json +2 -2
  371. package/examples/extensions/sandbox/package.json +1 -1
  372. package/examples/extensions/with-deps/package-lock.json +2 -2
  373. package/examples/extensions/with-deps/package.json +1 -1
  374. package/examples/sdk/11-sessions.ts +8 -8
  375. package/examples/sdk/13-session-runtime.ts +1 -1
  376. package/npm-shrinkwrap.json +12 -12
  377. package/package.json +4 -4
  378. package/dist/core/compaction/branch-summarization.d.ts +0 -88
  379. package/dist/core/compaction/branch-summarization.d.ts.map +0 -1
  380. package/dist/core/compaction/branch-summarization.js +0 -243
  381. package/dist/core/compaction/branch-summarization.js.map +0 -1
  382. package/dist/core/compaction/compaction.d.ts +0 -143
  383. package/dist/core/compaction/compaction.d.ts.map +0 -1
  384. package/dist/core/compaction/compaction.js +0 -659
  385. package/dist/core/compaction/compaction.js.map +0 -1
  386. package/dist/core/compaction/index.d.ts +0 -7
  387. package/dist/core/compaction/index.d.ts.map +0 -1
  388. package/dist/core/compaction/index.js +0 -7
  389. package/dist/core/compaction/index.js.map +0 -1
  390. package/dist/core/compaction/utils.d.ts +0 -38
  391. package/dist/core/compaction/utils.d.ts.map +0 -1
  392. package/dist/core/compaction/utils.js +0 -153
  393. package/dist/core/compaction/utils.js.map +0 -1
  394. package/dist/core/message-retention.d.ts +0 -26
  395. package/dist/core/message-retention.d.ts.map +0 -1
  396. package/dist/core/message-retention.js +0 -95
  397. package/dist/core/message-retention.js.map +0 -1
  398. package/dist/core/messages.d.ts +0 -77
  399. package/dist/core/messages.d.ts.map +0 -1
  400. package/dist/core/messages.js +0 -123
  401. package/dist/core/messages.js.map +0 -1
  402. package/dist/core/session-manager.d.ts +0 -337
  403. package/dist/core/session-manager.d.ts.map +0 -1
  404. package/dist/core/session-manager.js +0 -1328
  405. package/dist/core/session-manager.js.map +0 -1
  406. package/dist/core/tools/truncate.d.ts +0 -70
  407. package/dist/core/tools/truncate.d.ts.map +0 -1
  408. package/dist/core/tools/truncate.js +0 -215
  409. package/dist/core/tools/truncate.js.map +0 -1
@@ -1,659 +0,0 @@
1
- /**
2
- * Context compaction for long sessions.
3
- *
4
- * Pure functions for compaction logic. The session manager handles I/O,
5
- * and after compaction the session is reloaded.
6
- */
7
- import { completeSimple } from "@caupulican/pi-ai";
8
- import { convertToLlm, createBranchSummaryMessage, createCompactionSummaryMessage, createCustomMessage, } from "../messages.js";
9
- import { buildSessionContext } from "../session-manager.js";
10
- import { computeFileLists, createFileOps, extractFileOpsFromMessage, formatFileOperations, SUMMARIZATION_SYSTEM_PROMPT, serializeConversation, } from "./utils.js";
11
- /**
12
- * Extract file operations from messages and previous compaction entries.
13
- */
14
- function extractFileOperations(messages, entries, prevCompactionIndex) {
15
- const fileOps = createFileOps();
16
- // Collect from previous compaction's details (if pi-generated)
17
- if (prevCompactionIndex >= 0) {
18
- const prevCompaction = entries[prevCompactionIndex];
19
- if (!prevCompaction.fromHook && prevCompaction.details) {
20
- // fromHook field kept for session file compatibility
21
- const details = prevCompaction.details;
22
- if (Array.isArray(details.readFiles)) {
23
- for (const f of details.readFiles)
24
- fileOps.read.add(f);
25
- }
26
- if (Array.isArray(details.modifiedFiles)) {
27
- for (const f of details.modifiedFiles)
28
- fileOps.edited.add(f);
29
- }
30
- }
31
- }
32
- // Extract from tool calls in messages
33
- for (const msg of messages) {
34
- extractFileOpsFromMessage(msg, fileOps);
35
- }
36
- return fileOps;
37
- }
38
- // ============================================================================
39
- // Message Extraction
40
- // ============================================================================
41
- /**
42
- * Extract AgentMessage from an entry if it produces one.
43
- * Returns undefined for entries that don't contribute to LLM context.
44
- */
45
- function getMessageFromEntry(entry) {
46
- if (entry.type === "message") {
47
- return entry.message;
48
- }
49
- if (entry.type === "custom_message") {
50
- return createCustomMessage(entry.customType, entry.content, entry.display, entry.details, entry.timestamp);
51
- }
52
- if (entry.type === "branch_summary") {
53
- return createBranchSummaryMessage(entry.summary, entry.fromId, entry.timestamp);
54
- }
55
- if (entry.type === "compaction") {
56
- return createCompactionSummaryMessage(entry.summary, entry.tokensBefore, entry.timestamp);
57
- }
58
- return undefined;
59
- }
60
- function getMessageFromEntryForCompaction(entry) {
61
- if (entry.type === "compaction") {
62
- return undefined;
63
- }
64
- return getMessageFromEntry(entry);
65
- }
66
- export const DEFAULT_COMPACTION_SETTINGS = {
67
- enabled: true,
68
- reserveTokens: 16384,
69
- keepRecentTokens: 20000,
70
- triggerPercent: 0.7,
71
- };
72
- // ============================================================================
73
- // Token calculation
74
- // ============================================================================
75
- /**
76
- * Calculate total context tokens from usage.
77
- * Uses the native totalTokens field when available, falls back to computing from components.
78
- */
79
- export function calculateContextTokens(usage) {
80
- return usage.totalTokens || usage.input + usage.output + usage.cacheRead + usage.cacheWrite;
81
- }
82
- /**
83
- * Get usage from an assistant message if available.
84
- * Skips aborted and error messages as they don't have valid usage data.
85
- */
86
- function getAssistantUsage(msg) {
87
- if (msg.role === "assistant" && "usage" in msg) {
88
- const assistantMsg = msg;
89
- if (assistantMsg.stopReason !== "aborted" && assistantMsg.stopReason !== "error" && assistantMsg.usage) {
90
- return assistantMsg.usage;
91
- }
92
- }
93
- return undefined;
94
- }
95
- /**
96
- * Find the last non-aborted assistant message usage from session entries.
97
- */
98
- export function getLastAssistantUsage(entries) {
99
- for (let i = entries.length - 1; i >= 0; i--) {
100
- const entry = entries[i];
101
- if (entry.type === "message") {
102
- const usage = getAssistantUsage(entry.message);
103
- if (usage)
104
- return usage;
105
- }
106
- }
107
- return undefined;
108
- }
109
- function getLastAssistantUsageInfo(messages) {
110
- for (let i = messages.length - 1; i >= 0; i--) {
111
- const usage = getAssistantUsage(messages[i]);
112
- if (usage)
113
- return { usage, index: i };
114
- }
115
- return undefined;
116
- }
117
- /**
118
- * Estimate context tokens from messages, using the last assistant usage when available.
119
- * If there are messages after the last usage, estimate their tokens with estimateTokens.
120
- */
121
- export function estimateContextTokens(messages) {
122
- const usageInfo = getLastAssistantUsageInfo(messages);
123
- if (!usageInfo) {
124
- let estimated = 0;
125
- for (const message of messages) {
126
- estimated += estimateTokens(message);
127
- }
128
- return {
129
- tokens: estimated,
130
- usageTokens: 0,
131
- trailingTokens: estimated,
132
- lastUsageIndex: null,
133
- };
134
- }
135
- const usageTokens = calculateContextTokens(usageInfo.usage);
136
- let trailingTokens = 0;
137
- for (let i = usageInfo.index + 1; i < messages.length; i++) {
138
- trailingTokens += estimateTokens(messages[i]);
139
- }
140
- return {
141
- tokens: usageTokens + trailingTokens,
142
- usageTokens,
143
- trailingTokens,
144
- lastUsageIndex: usageInfo.index,
145
- };
146
- }
147
- /**
148
- * Minimum projected space saving for the EARLY (fractional) compaction trigger to fire. Anti-thrashing
149
- * (cost guard, #30): an early compaction whose summary would barely shrink the context (mostly recent,
150
- * protected content) just burns a summarization call for little gain — skip it and let the context grow
151
- * until either the saving is worthwhile or the hard (near-full) trigger forces it. Does NOT gate the
152
- * hard trigger, so overflow is always avoided.
153
- */
154
- export const MIN_COMPACTION_SAVINGS = 0.12;
155
- /**
156
- * Check if compaction should trigger based on context usage.
157
- *
158
- * Two triggers:
159
- * - HARD: context exceeds `contextWindow - reserveTokens` (near-full) or an explicit `triggerTokens`
160
- * override — always compact (prevents overflow).
161
- * - EARLY (fractional, cost guard): context exceeds `contextWindow * triggerPercent` — compact only if
162
- * the summary would actually save enough (`MIN_COMPACTION_SAVINGS`), so we don't thrash for tiny gains.
163
- */
164
- export function shouldCompact(contextTokens, contextWindow, settings, triggerTokens) {
165
- if (!settings.enabled)
166
- return false;
167
- // Hard trigger: near-full, or a caller-supplied lower override. Always compacts (avoid overflow).
168
- const reserveTrigger = contextWindow - settings.reserveTokens;
169
- const hardTrigger = triggerTokens === undefined ? reserveTrigger : Math.min(reserveTrigger, triggerTokens);
170
- if (contextTokens > hardTrigger)
171
- return true;
172
- // Early fractional trigger: bounds per-turn input cost on large-window models, gated by anti-thrashing.
173
- const pct = settings.triggerPercent ?? 0;
174
- if (pct > 0 && pct < 1) {
175
- const fractionalTrigger = Math.floor(contextWindow * pct);
176
- if (contextTokens > fractionalTrigger) {
177
- // Projected saving ≈ the non-protected fraction (everything but the recent tail we keep).
178
- const projectedSavings = contextTokens > 0 ? 1 - settings.keepRecentTokens / contextTokens : 0;
179
- return projectedSavings >= MIN_COMPACTION_SAVINGS;
180
- }
181
- }
182
- return false;
183
- }
184
- // ============================================================================
185
- // Cut point detection
186
- // ============================================================================
187
- const ESTIMATED_IMAGE_CHARS = 4800;
188
- function estimateTextAndImageContentChars(content) {
189
- if (typeof content === "string") {
190
- return content.length;
191
- }
192
- let chars = 0;
193
- for (const block of content) {
194
- if (block.type === "text" && block.text) {
195
- chars += block.text.length;
196
- }
197
- else if (block.type === "image") {
198
- chars += ESTIMATED_IMAGE_CHARS;
199
- }
200
- }
201
- return chars;
202
- }
203
- /**
204
- * Estimate token count for a message using chars/4 heuristic.
205
- * This is conservative (overestimates tokens).
206
- */
207
- export function estimateTokens(message) {
208
- let chars = 0;
209
- switch (message.role) {
210
- case "user": {
211
- chars = estimateTextAndImageContentChars(message.content);
212
- return Math.ceil(chars / 4);
213
- }
214
- case "assistant": {
215
- const assistant = message;
216
- for (const block of assistant.content) {
217
- if (block.type === "text") {
218
- chars += block.text.length;
219
- }
220
- else if (block.type === "thinking") {
221
- chars += block.thinking.length;
222
- }
223
- else if (block.type === "toolCall") {
224
- chars += block.name.length + JSON.stringify(block.arguments).length;
225
- }
226
- }
227
- return Math.ceil(chars / 4);
228
- }
229
- case "custom":
230
- case "toolResult": {
231
- chars = estimateTextAndImageContentChars(message.content);
232
- return Math.ceil(chars / 4);
233
- }
234
- case "bashExecution": {
235
- chars = message.command.length + message.output.length;
236
- return Math.ceil(chars / 4);
237
- }
238
- case "branchSummary":
239
- case "compactionSummary": {
240
- chars = message.summary.length;
241
- return Math.ceil(chars / 4);
242
- }
243
- }
244
- return 0;
245
- }
246
- /**
247
- * Find valid cut points: indices of user, assistant, custom, or bashExecution messages.
248
- * Never cut at tool results (they must follow their tool call).
249
- * When we cut at an assistant message with tool calls, its tool results follow it
250
- * and will be kept.
251
- * BashExecutionMessage is treated like a user message (user-initiated context).
252
- */
253
- function findValidCutPoints(entries, startIndex, endIndex) {
254
- const cutPoints = [];
255
- for (let i = startIndex; i < endIndex; i++) {
256
- const entry = entries[i];
257
- switch (entry.type) {
258
- case "message": {
259
- const role = entry.message.role;
260
- switch (role) {
261
- case "bashExecution":
262
- case "custom":
263
- case "branchSummary":
264
- case "compactionSummary":
265
- case "user":
266
- case "assistant":
267
- cutPoints.push(i);
268
- break;
269
- case "toolResult":
270
- break;
271
- }
272
- break;
273
- }
274
- case "thinking_level_change":
275
- case "model_change":
276
- case "compaction":
277
- case "branch_summary":
278
- case "custom":
279
- case "custom_message":
280
- case "label":
281
- case "session_info":
282
- break;
283
- }
284
- // branch_summary and custom_message are user-role messages, valid cut points
285
- if (entry.type === "branch_summary" || entry.type === "custom_message") {
286
- cutPoints.push(i);
287
- }
288
- }
289
- return cutPoints;
290
- }
291
- /**
292
- * Find the user message (or bashExecution) that starts the turn containing the given entry index.
293
- * Returns -1 if no turn start found before the index.
294
- * BashExecutionMessage is treated like a user message for turn boundaries.
295
- */
296
- export function findTurnStartIndex(entries, entryIndex, startIndex) {
297
- for (let i = entryIndex; i >= startIndex; i--) {
298
- const entry = entries[i];
299
- // branch_summary and custom_message are user-role messages, can start a turn
300
- if (entry.type === "branch_summary" || entry.type === "custom_message") {
301
- return i;
302
- }
303
- if (entry.type === "message") {
304
- const role = entry.message.role;
305
- if (role === "user" || role === "bashExecution") {
306
- return i;
307
- }
308
- }
309
- }
310
- return -1;
311
- }
312
- /**
313
- * Find the cut point in session entries that keeps approximately `keepRecentTokens`.
314
- *
315
- * Algorithm: Walk backwards from newest, accumulating estimated message sizes.
316
- * Stop when we've accumulated >= keepRecentTokens. Cut at that point.
317
- *
318
- * Can cut at user OR assistant messages (never tool results). When cutting at an
319
- * assistant message with tool calls, its tool results come after and will be kept.
320
- *
321
- * Returns CutPointResult with:
322
- * - firstKeptEntryIndex: the entry index to start keeping from
323
- * - turnStartIndex: if cutting mid-turn, the user message that started that turn
324
- * - isSplitTurn: whether we're cutting in the middle of a turn
325
- *
326
- * Only considers entries between `startIndex` and `endIndex` (exclusive).
327
- */
328
- export function findCutPoint(entries, startIndex, endIndex, keepRecentTokens) {
329
- const cutPoints = findValidCutPoints(entries, startIndex, endIndex);
330
- if (cutPoints.length === 0) {
331
- return { firstKeptEntryIndex: startIndex, turnStartIndex: -1, isSplitTurn: false };
332
- }
333
- // Walk backwards from newest, accumulating estimated message sizes
334
- let accumulatedTokens = 0;
335
- let cutIndex = cutPoints[0]; // Default: keep from first message (not header)
336
- for (let i = endIndex - 1; i >= startIndex; i--) {
337
- const entry = entries[i];
338
- if (entry.type !== "message")
339
- continue;
340
- // Estimate this message's size
341
- const messageTokens = estimateTokens(entry.message);
342
- accumulatedTokens += messageTokens;
343
- // Check if we've exceeded the budget
344
- if (accumulatedTokens >= keepRecentTokens) {
345
- // Find the closest valid cut point at or after this entry
346
- for (let c = 0; c < cutPoints.length; c++) {
347
- if (cutPoints[c] >= i) {
348
- cutIndex = cutPoints[c];
349
- break;
350
- }
351
- }
352
- break;
353
- }
354
- }
355
- // Scan backwards from cutIndex to include any non-message entries (bash, settings, etc.)
356
- while (cutIndex > startIndex) {
357
- const prevEntry = entries[cutIndex - 1];
358
- // Stop at session header or compaction boundaries
359
- if (prevEntry.type === "compaction") {
360
- break;
361
- }
362
- if (prevEntry.type === "message") {
363
- // Stop if we hit any message
364
- break;
365
- }
366
- // Include this non-message entry (bash, settings change, etc.)
367
- cutIndex--;
368
- }
369
- // Determine if this is a split turn
370
- const cutEntry = entries[cutIndex];
371
- const isUserMessage = cutEntry.type === "message" && cutEntry.message.role === "user";
372
- const turnStartIndex = isUserMessage ? -1 : findTurnStartIndex(entries, cutIndex, startIndex);
373
- return {
374
- firstKeptEntryIndex: cutIndex,
375
- turnStartIndex,
376
- isSplitTurn: !isUserMessage && turnStartIndex !== -1,
377
- };
378
- }
379
- // ============================================================================
380
- // Summarization
381
- // ============================================================================
382
- const SUMMARIZATION_PROMPT = `The messages above are a conversation to summarize. Create a structured context checkpoint summary that another LLM will use to continue the work.
383
-
384
- Use this EXACT format:
385
-
386
- ## Goal
387
- [What is the user trying to accomplish? Can be multiple items if the session covers different tasks.]
388
-
389
- ## Constraints & Preferences
390
- - [Any constraints, preferences, or requirements mentioned by user]
391
- - [Or "(none)" if none were mentioned]
392
-
393
- ## Progress
394
- ### Done
395
- - [x] [Completed tasks/changes]
396
-
397
- ### In Progress
398
- - [ ] [Current work]
399
-
400
- ### Blocked
401
- - [Issues preventing progress, if any]
402
-
403
- ## Key Decisions
404
- - **[Decision]**: [Brief rationale]
405
-
406
- ## Next Steps
407
- 1. [Ordered list of what should happen next]
408
-
409
- ## Critical Context
410
- - [Any data, examples, or references needed to continue]
411
- - [Or "(none)" if not applicable]
412
-
413
- Keep each section concise. Preserve exact file paths, function names, and error messages.`;
414
- const UPDATE_SUMMARIZATION_PROMPT = `The messages above are NEW conversation messages to incorporate into the existing summary provided in <previous-summary> tags.
415
-
416
- Update the existing structured summary with new information. RULES:
417
- - PRESERVE all existing information from the previous summary
418
- - ADD new progress, decisions, and context from the new messages
419
- - UPDATE the Progress section: move items from "In Progress" to "Done" when completed
420
- - UPDATE "Next Steps" based on what was accomplished
421
- - PRESERVE exact file paths, function names, and error messages
422
- - If something is no longer relevant, you may remove it
423
-
424
- Use this EXACT format:
425
-
426
- ## Goal
427
- [Preserve existing goals, add new ones if the task expanded]
428
-
429
- ## Constraints & Preferences
430
- - [Preserve existing, add new ones discovered]
431
-
432
- ## Progress
433
- ### Done
434
- - [x] [Include previously done items AND newly completed items]
435
-
436
- ### In Progress
437
- - [ ] [Current work - update based on progress]
438
-
439
- ### Blocked
440
- - [Current blockers - remove if resolved]
441
-
442
- ## Key Decisions
443
- - **[Decision]**: [Brief rationale] (preserve all previous, add new)
444
-
445
- ## Next Steps
446
- 1. [Update based on current state]
447
-
448
- ## Critical Context
449
- - [Preserve important context, add new if needed]
450
-
451
- Keep each section concise. Preserve exact file paths, function names, and error messages.`;
452
- function createSummarizationOptions(model, maxTokens, apiKey, headers, signal, thinkingLevel) {
453
- const options = { maxTokens, signal, apiKey, headers };
454
- if (model.reasoning && thinkingLevel && thinkingLevel !== "off") {
455
- options.reasoning = thinkingLevel;
456
- }
457
- return options;
458
- }
459
- async function completeSummarization(model, context, options, streamFn) {
460
- if (!streamFn) {
461
- return completeSimple(model, context, options);
462
- }
463
- const stream = await streamFn(model, context, options);
464
- return stream.result();
465
- }
466
- /**
467
- * Generate a summary of the conversation using the LLM.
468
- * If previousSummary is provided, uses the update prompt to merge.
469
- */
470
- export async function generateSummary(currentMessages, model, reserveTokens, apiKey, headers, signal, customInstructions, previousSummary, thinkingLevel, streamFn, preDigest) {
471
- const maxTokens = Math.min(Math.floor(0.8 * reserveTokens), model.maxTokens > 0 ? model.maxTokens : Number.POSITIVE_INFINITY);
472
- // Use update prompt if we have a previous summary, otherwise initial prompt
473
- let basePrompt = previousSummary ? UPDATE_SUMMARIZATION_PROMPT : SUMMARIZATION_PROMPT;
474
- if (customInstructions) {
475
- basePrompt = `${basePrompt}\n\nAdditional focus: ${customInstructions}`;
476
- }
477
- // Serialize conversation to text so model doesn't try to continue it
478
- // Convert to LLM messages first (handles custom types like bashExecution, custom, etc.)
479
- const llmMessages = convertToLlm(currentMessages);
480
- let conversationText = serializeConversation(llmMessages);
481
- // Brain-curation surface 3 (opt-in, injected by the session): pre-digest old chunks locally
482
- // before the frontier summarization call. Best-effort — failure keeps the verbatim text.
483
- if (preDigest) {
484
- try {
485
- conversationText = await preDigest(conversationText, signal);
486
- }
487
- catch {
488
- // verbatim fallback
489
- }
490
- }
491
- // Build the prompt with conversation wrapped in tags
492
- let promptText = `<conversation>\n${conversationText}\n</conversation>\n\n`;
493
- if (previousSummary) {
494
- promptText += `<previous-summary>\n${previousSummary}\n</previous-summary>\n\n`;
495
- }
496
- promptText += basePrompt;
497
- const summarizationMessages = [
498
- {
499
- role: "user",
500
- content: [{ type: "text", text: promptText }],
501
- timestamp: Date.now(),
502
- },
503
- ];
504
- const completionOptions = createSummarizationOptions(model, maxTokens, apiKey, headers, signal, thinkingLevel);
505
- const response = await completeSummarization(model, { systemPrompt: SUMMARIZATION_SYSTEM_PROMPT, messages: summarizationMessages }, completionOptions, streamFn);
506
- if (response.stopReason === "error") {
507
- throw new Error(`Summarization failed: ${response.errorMessage || "Unknown error"}`);
508
- }
509
- const textContent = response.content
510
- .filter((c) => c.type === "text")
511
- .map((c) => c.text)
512
- .join("\n");
513
- return textContent;
514
- }
515
- export function prepareCompaction(pathEntries, settings) {
516
- if (pathEntries.length > 0 && pathEntries[pathEntries.length - 1].type === "compaction") {
517
- return undefined;
518
- }
519
- let prevCompactionIndex = -1;
520
- for (let i = pathEntries.length - 1; i >= 0; i--) {
521
- if (pathEntries[i].type === "compaction") {
522
- prevCompactionIndex = i;
523
- break;
524
- }
525
- }
526
- let previousSummary;
527
- let boundaryStart = 0;
528
- if (prevCompactionIndex >= 0) {
529
- const prevCompaction = pathEntries[prevCompactionIndex];
530
- previousSummary = prevCompaction.summary;
531
- const firstKeptEntryIndex = pathEntries.findIndex((entry) => entry.id === prevCompaction.firstKeptEntryId);
532
- boundaryStart = firstKeptEntryIndex >= 0 ? firstKeptEntryIndex : prevCompactionIndex + 1;
533
- }
534
- const boundaryEnd = pathEntries.length;
535
- const tokensBefore = estimateContextTokens(buildSessionContext(pathEntries).messages).tokens;
536
- const cutPoint = findCutPoint(pathEntries, boundaryStart, boundaryEnd, settings.keepRecentTokens);
537
- // Get UUID of first kept entry
538
- const firstKeptEntry = pathEntries[cutPoint.firstKeptEntryIndex];
539
- if (!firstKeptEntry?.id) {
540
- return undefined; // Session needs migration
541
- }
542
- const firstKeptEntryId = firstKeptEntry.id;
543
- const historyEnd = cutPoint.isSplitTurn ? cutPoint.turnStartIndex : cutPoint.firstKeptEntryIndex;
544
- // Messages to summarize (will be discarded after summary)
545
- const messagesToSummarize = [];
546
- for (let i = boundaryStart; i < historyEnd; i++) {
547
- const msg = getMessageFromEntryForCompaction(pathEntries[i]);
548
- if (msg)
549
- messagesToSummarize.push(msg);
550
- }
551
- // Messages for turn prefix summary (if splitting a turn)
552
- const turnPrefixMessages = [];
553
- if (cutPoint.isSplitTurn) {
554
- for (let i = cutPoint.turnStartIndex; i < cutPoint.firstKeptEntryIndex; i++) {
555
- const msg = getMessageFromEntryForCompaction(pathEntries[i]);
556
- if (msg)
557
- turnPrefixMessages.push(msg);
558
- }
559
- }
560
- // Extract file operations from messages and previous compaction
561
- const fileOps = extractFileOperations(messagesToSummarize, pathEntries, prevCompactionIndex);
562
- // Also extract file ops from turn prefix if splitting
563
- if (cutPoint.isSplitTurn) {
564
- for (const msg of turnPrefixMessages) {
565
- extractFileOpsFromMessage(msg, fileOps);
566
- }
567
- }
568
- return {
569
- firstKeptEntryId,
570
- messagesToSummarize,
571
- turnPrefixMessages,
572
- isSplitTurn: cutPoint.isSplitTurn,
573
- tokensBefore,
574
- previousSummary,
575
- fileOps,
576
- settings,
577
- };
578
- }
579
- // ============================================================================
580
- // Main compaction function
581
- // ============================================================================
582
- const TURN_PREFIX_SUMMARIZATION_PROMPT = `This is the PREFIX of a turn that was too large to keep. The SUFFIX (recent work) is retained.
583
-
584
- Summarize the prefix to provide context for the retained suffix:
585
-
586
- ## Original Request
587
- [What did the user ask for in this turn?]
588
-
589
- ## Early Progress
590
- - [Key decisions and work done in the prefix]
591
-
592
- ## Context for Suffix
593
- - [Information needed to understand the retained recent work]
594
-
595
- Be concise. Focus on what's needed to understand the kept suffix.`;
596
- /**
597
- * Generate summaries for compaction using prepared data.
598
- * Returns CompactionResult - SessionManager adds uuid/parentUuid when saving.
599
- *
600
- * @param preparation - Pre-calculated preparation from prepareCompaction()
601
- * @param customInstructions - Optional custom focus for the summary
602
- */
603
- export async function compact(preparation, model, apiKey, headers, customInstructions, signal, thinkingLevel, streamFn, preDigest) {
604
- const { firstKeptEntryId, messagesToSummarize, turnPrefixMessages, isSplitTurn, tokensBefore, previousSummary, fileOps, settings, } = preparation;
605
- // Generate summaries (can be parallel if both needed) and merge into one
606
- let summary;
607
- if (isSplitTurn && turnPrefixMessages.length > 0) {
608
- // Generate both summaries in parallel
609
- const [historyResult, turnPrefixResult] = await Promise.all([
610
- messagesToSummarize.length > 0
611
- ? generateSummary(messagesToSummarize, model, settings.reserveTokens, apiKey, headers, signal, customInstructions, previousSummary, thinkingLevel, streamFn, preDigest)
612
- : Promise.resolve("No prior history."),
613
- generateTurnPrefixSummary(turnPrefixMessages, model, settings.reserveTokens, apiKey, headers, signal, thinkingLevel, streamFn),
614
- ]);
615
- // Merge into single summary
616
- summary = `${historyResult}\n\n---\n\n**Turn Context (split turn):**\n\n${turnPrefixResult}`;
617
- }
618
- else {
619
- // Just generate history summary
620
- summary = await generateSummary(messagesToSummarize, model, settings.reserveTokens, apiKey, headers, signal, customInstructions, previousSummary, thinkingLevel, streamFn, preDigest);
621
- }
622
- // Compute file lists and append to summary
623
- const { readFiles, modifiedFiles } = computeFileLists(fileOps);
624
- summary += formatFileOperations(readFiles, modifiedFiles);
625
- if (!firstKeptEntryId) {
626
- throw new Error("First kept entry has no UUID - session may need migration");
627
- }
628
- return {
629
- summary,
630
- firstKeptEntryId,
631
- tokensBefore,
632
- details: { readFiles, modifiedFiles },
633
- };
634
- }
635
- /**
636
- * Generate a summary for a turn prefix (when splitting a turn).
637
- */
638
- async function generateTurnPrefixSummary(messages, model, reserveTokens, apiKey, headers, signal, thinkingLevel, streamFn) {
639
- const maxTokens = Math.min(Math.floor(0.5 * reserveTokens), model.maxTokens > 0 ? model.maxTokens : Number.POSITIVE_INFINITY); // Smaller budget for turn prefix
640
- const llmMessages = convertToLlm(messages);
641
- const conversationText = serializeConversation(llmMessages);
642
- const promptText = `<conversation>\n${conversationText}\n</conversation>\n\n${TURN_PREFIX_SUMMARIZATION_PROMPT}`;
643
- const summarizationMessages = [
644
- {
645
- role: "user",
646
- content: [{ type: "text", text: promptText }],
647
- timestamp: Date.now(),
648
- },
649
- ];
650
- const response = await completeSummarization(model, { systemPrompt: SUMMARIZATION_SYSTEM_PROMPT, messages: summarizationMessages }, createSummarizationOptions(model, maxTokens, apiKey, headers, signal, thinkingLevel), streamFn);
651
- if (response.stopReason === "error") {
652
- throw new Error(`Turn prefix summarization failed: ${response.errorMessage || "Unknown error"}`);
653
- }
654
- return response.content
655
- .filter((c) => c.type === "text")
656
- .map((c) => c.text)
657
- .join("\n");
658
- }
659
- //# sourceMappingURL=compaction.js.map