@cuylabs/agent-core 4.9.0 → 5.0.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 (658) hide show
  1. package/README.md +11 -12
  2. package/dist/agent/chat-loop/commit-batch.d.ts +10 -0
  3. package/dist/agent/chat-loop/commit-batch.d.ts.map +1 -0
  4. package/dist/agent/chat-loop/context-recovery.d.ts +33 -0
  5. package/dist/agent/chat-loop/context-recovery.d.ts.map +1 -0
  6. package/dist/agent/chat-loop/finalize-turn.d.ts +19 -0
  7. package/dist/agent/chat-loop/finalize-turn.d.ts.map +1 -0
  8. package/dist/agent/chat-loop/index.d.ts +7 -0
  9. package/dist/agent/chat-loop/index.d.ts.map +1 -0
  10. package/dist/agent/chat-loop/loop.d.ts +8 -0
  11. package/dist/agent/chat-loop/loop.d.ts.map +1 -0
  12. package/dist/agent/chat-loop/model-step-runner.d.ts +26 -0
  13. package/dist/agent/chat-loop/model-step-runner.d.ts.map +1 -0
  14. package/dist/agent/chat-loop/model-step-snapshot.d.ts +49 -0
  15. package/dist/agent/chat-loop/model-step-snapshot.d.ts.map +1 -0
  16. package/dist/agent/chat-loop/turn-tools.d.ts +19 -0
  17. package/dist/agent/chat-loop/turn-tools.d.ts.map +1 -0
  18. package/dist/agent/chat-loop/types.d.ts +60 -0
  19. package/dist/agent/chat-loop/types.d.ts.map +1 -0
  20. package/dist/agent/defaults.d.ts +69 -0
  21. package/dist/agent/defaults.d.ts.map +1 -0
  22. package/dist/agent/event-printer.d.ts +94 -0
  23. package/dist/agent/event-printer.d.ts.map +1 -0
  24. package/dist/agent/fork.d.ts +59 -0
  25. package/dist/agent/fork.d.ts.map +1 -0
  26. package/dist/agent/index.d.ts +17 -0
  27. package/dist/agent/index.d.ts.map +1 -0
  28. package/dist/agent/instance/context-management.d.ts +42 -0
  29. package/dist/agent/instance/context-management.d.ts.map +1 -0
  30. package/dist/agent/instance/forking.d.ts +26 -0
  31. package/dist/agent/instance/forking.d.ts.map +1 -0
  32. package/dist/agent/instance/index.d.ts +182 -0
  33. package/dist/agent/instance/index.d.ts.map +1 -0
  34. package/dist/agent/instance/interventions.d.ts +10 -0
  35. package/dist/agent/instance/interventions.d.ts.map +1 -0
  36. package/dist/agent/instance/mcp.d.ts +21 -0
  37. package/dist/agent/instance/mcp.d.ts.map +1 -0
  38. package/dist/agent/instance/sessions.d.ts +8 -0
  39. package/dist/agent/instance/sessions.d.ts.map +1 -0
  40. package/dist/agent/instance/tools.d.ts +16 -0
  41. package/dist/agent/instance/tools.d.ts.map +1 -0
  42. package/dist/agent/instance/turn-lifecycle.d.ts +61 -0
  43. package/dist/agent/instance/turn-lifecycle.d.ts.map +1 -0
  44. package/dist/agent/session.d.ts +16 -0
  45. package/dist/agent/session.d.ts.map +1 -0
  46. package/dist/agent/setup/config.d.ts +8 -0
  47. package/dist/agent/setup/config.d.ts.map +1 -0
  48. package/dist/agent/setup/context-window.d.ts +4 -0
  49. package/dist/agent/setup/context-window.d.ts.map +1 -0
  50. package/dist/agent/setup/environment.d.ts +5 -0
  51. package/dist/agent/setup/environment.d.ts.map +1 -0
  52. package/dist/agent/setup/middleware.d.ts +9 -0
  53. package/dist/agent/setup/middleware.d.ts.map +1 -0
  54. package/dist/agent/setup/runtime-config.d.ts +9 -0
  55. package/dist/agent/setup/runtime-config.d.ts.map +1 -0
  56. package/dist/agent/setup/state.d.ts +4 -0
  57. package/dist/agent/setup/state.d.ts.map +1 -0
  58. package/dist/agent/setup/tools.d.ts +8 -0
  59. package/dist/agent/setup/tools.d.ts.map +1 -0
  60. package/dist/agent/setup.d.ts +47 -0
  61. package/dist/agent/setup.d.ts.map +1 -0
  62. package/dist/agent/stream-provider.d.ts +27 -0
  63. package/dist/agent/stream-provider.d.ts.map +1 -0
  64. package/dist/agent/turn-context/compaction/agent-context.d.ts +76 -0
  65. package/dist/agent/turn-context/compaction/agent-context.d.ts.map +1 -0
  66. package/dist/agent/turn-context/compaction/budget.d.ts +4 -0
  67. package/dist/agent/turn-context/compaction/budget.d.ts.map +1 -0
  68. package/dist/agent/turn-context/compaction/check.d.ts +45 -0
  69. package/dist/agent/turn-context/compaction/check.d.ts.map +1 -0
  70. package/dist/agent/turn-context/compaction/fragments.d.ts +4 -0
  71. package/dist/agent/turn-context/compaction/fragments.d.ts.map +1 -0
  72. package/dist/agent/turn-context/compaction/index.d.ts +5 -0
  73. package/dist/agent/turn-context/compaction/index.d.ts.map +1 -0
  74. package/dist/agent/turn-context/compaction/memory.d.ts +18 -0
  75. package/dist/agent/turn-context/compaction/memory.d.ts.map +1 -0
  76. package/dist/agent/turn-context/compaction/results.d.ts +25 -0
  77. package/dist/agent/turn-context/compaction/results.d.ts.map +1 -0
  78. package/dist/agent/turn-context/compaction/summary.d.ts +3 -0
  79. package/dist/agent/turn-context/compaction/summary.d.ts.map +1 -0
  80. package/dist/agent/turn-context/compaction/types.d.ts +30 -0
  81. package/dist/agent/turn-context/compaction/types.d.ts.map +1 -0
  82. package/dist/agent/turn-context/fit-model-context.d.ts +29 -0
  83. package/dist/agent/turn-context/fit-model-context.d.ts.map +1 -0
  84. package/dist/agent/turn-context/index.d.ts +5 -0
  85. package/dist/agent/turn-context/index.d.ts.map +1 -0
  86. package/dist/agent/turn-context/system-prompts.d.ts +12 -0
  87. package/dist/agent/turn-context/system-prompts.d.ts.map +1 -0
  88. package/dist/agent/types/config.d.ts +206 -0
  89. package/dist/agent/types/config.d.ts.map +1 -0
  90. package/dist/agent/types/index.d.ts +11 -0
  91. package/dist/agent/types/index.d.ts.map +1 -0
  92. package/dist/agent/types/state.d.ts +16 -0
  93. package/dist/agent/types/state.d.ts.map +1 -0
  94. package/dist/agent/types/tracing.d.ts +12 -0
  95. package/dist/agent/types/tracing.d.ts.map +1 -0
  96. package/dist/{chunk-KYLPMBHD.js → chunk-336EDIBL.js} +1 -1
  97. package/dist/chunk-346FIYKT.js +960 -0
  98. package/dist/{chunk-HSUPTXNV.js → chunk-556CPZ3J.js} +13 -10
  99. package/dist/chunk-AHDCR7SX.js +83 -0
  100. package/dist/{chunk-CSR75JVC.js → chunk-ASXF5AC6.js} +1 -1
  101. package/dist/{chunk-BJC46FIF.js → chunk-BKHWKKSG.js} +2 -2
  102. package/dist/{chunk-2TTOLHBT.js → chunk-CFBSQLP5.js} +1 -1
  103. package/dist/chunk-CGP6UNCQ.js +554 -0
  104. package/dist/{chunk-GJFP5L2V.js → chunk-CNM6OROH.js} +15 -3
  105. package/dist/chunk-DD7S7ZG4.js +274 -0
  106. package/dist/chunk-DYZGHHDB.js +1458 -0
  107. package/dist/chunk-E66PKKDL.js +772 -0
  108. package/dist/{chunk-H3GRHFFG.js → chunk-EDKZOPUV.js} +63 -306
  109. package/dist/{chunk-GEBFHREI.js → chunk-GHVW7L4P.js} +71 -5
  110. package/dist/chunk-JFH6HBUG.js +227 -0
  111. package/dist/{chunk-MWPU2EVV.js → chunk-JUIL2NJC.js} +4 -81
  112. package/dist/{chunk-NS7D7JJU.js → chunk-K453AFTL.js} +35 -16
  113. package/dist/chunk-MJRZ2ZRI.js +498 -0
  114. package/dist/{chunk-UMIVJDEJ.js → chunk-SAWRDGBE.js} +30 -7
  115. package/dist/chunk-TYQWH6XH.js +88 -0
  116. package/dist/{chunk-QJV5XPPS.js → chunk-UEEHZ4QH.js} +1 -1
  117. package/dist/chunk-UG5PVNZV.js +53 -0
  118. package/dist/{chunk-BGG2HVIR.js → chunk-V4MIDL5B.js} +9 -0
  119. package/dist/chunk-W6LWIMIX.js +8 -0
  120. package/dist/context/assembly/index.d.ts +3 -0
  121. package/dist/context/assembly/index.d.ts.map +1 -0
  122. package/dist/context/assembly/prepare.d.ts +11 -0
  123. package/dist/context/assembly/prepare.d.ts.map +1 -0
  124. package/dist/context/assembly/types.d.ts +64 -0
  125. package/dist/context/assembly/types.d.ts.map +1 -0
  126. package/dist/context/config.d.ts +20 -0
  127. package/dist/context/config.d.ts.map +1 -0
  128. package/dist/context/fragments/index.d.ts +4 -0
  129. package/dist/context/fragments/index.d.ts.map +1 -0
  130. package/dist/context/fragments/messages.d.ts +12 -0
  131. package/dist/context/fragments/messages.d.ts.map +1 -0
  132. package/dist/context/fragments/render.d.ts +16 -0
  133. package/dist/context/fragments/render.d.ts.map +1 -0
  134. package/dist/context/fragments/types.d.ts +87 -0
  135. package/dist/context/fragments/types.d.ts.map +1 -0
  136. package/dist/context/index.d.ts +13 -0
  137. package/dist/context/index.d.ts.map +1 -0
  138. package/dist/context/index.js +96 -0
  139. package/dist/context/text/truncation.d.ts +13 -0
  140. package/dist/context/text/truncation.d.ts.map +1 -0
  141. package/dist/context/window/budget.d.ts +135 -0
  142. package/dist/context/window/budget.d.ts.map +1 -0
  143. package/dist/context/window/compactor.d.ts +89 -0
  144. package/dist/context/window/compactor.d.ts.map +1 -0
  145. package/dist/context/window/cut-planner.d.ts +67 -0
  146. package/dist/context/window/cut-planner.d.ts.map +1 -0
  147. package/dist/context/window/decision.d.ts +50 -0
  148. package/dist/context/window/decision.d.ts.map +1 -0
  149. package/dist/context/window/estimation.d.ts +60 -0
  150. package/dist/context/window/estimation.d.ts.map +1 -0
  151. package/dist/context/window/index.d.ts +28 -0
  152. package/dist/context/window/index.d.ts.map +1 -0
  153. package/dist/context/window/manager.d.ts +113 -0
  154. package/dist/context/window/manager.d.ts.map +1 -0
  155. package/dist/context/window/summary-policy.d.ts +50 -0
  156. package/dist/context/window/summary-policy.d.ts.map +1 -0
  157. package/dist/context/window/summary.d.ts +65 -0
  158. package/dist/context/window/summary.d.ts.map +1 -0
  159. package/dist/context/window/tool-pruning.d.ts +73 -0
  160. package/dist/context/window/tool-pruning.d.ts.map +1 -0
  161. package/dist/dispatch/executor.d.ts +56 -0
  162. package/dist/dispatch/executor.d.ts.map +1 -0
  163. package/dist/dispatch/index.d.ts +7 -95
  164. package/dist/dispatch/index.d.ts.map +1 -0
  165. package/dist/dispatch/index.js +4 -3
  166. package/dist/dispatch/results.d.ts +9 -0
  167. package/dist/dispatch/results.d.ts.map +1 -0
  168. package/dist/dispatch/runtime.d.ts +19 -0
  169. package/dist/dispatch/runtime.d.ts.map +1 -0
  170. package/dist/dispatch/tool-factories.d.ts +8 -0
  171. package/dist/dispatch/tool-factories.d.ts.map +1 -0
  172. package/dist/dispatch/tools.d.ts +10 -0
  173. package/dist/dispatch/tools.d.ts.map +1 -0
  174. package/dist/dispatch/types.d.ts +131 -0
  175. package/dist/dispatch/types.d.ts.map +1 -0
  176. package/dist/events/event-bus/index.d.ts +13 -0
  177. package/dist/events/event-bus/index.d.ts.map +1 -0
  178. package/dist/events/event-bus/index.js +6 -0
  179. package/dist/events/event-bus/local.d.ts +14 -0
  180. package/dist/events/event-bus/local.d.ts.map +1 -0
  181. package/dist/events/event-bus/types.d.ts +78 -0
  182. package/dist/events/event-bus/types.d.ts.map +1 -0
  183. package/dist/events/index.d.ts +10 -89
  184. package/dist/events/index.d.ts.map +1 -0
  185. package/dist/events/index.js +6 -1
  186. package/dist/events/signal/index.d.ts +18 -0
  187. package/dist/events/signal/index.d.ts.map +1 -0
  188. package/dist/events/signal/index.js +6 -0
  189. package/dist/events/signal/local.d.ts +22 -0
  190. package/dist/events/signal/local.d.ts.map +1 -0
  191. package/dist/events/signal/types.d.ts +69 -0
  192. package/dist/events/signal/types.d.ts.map +1 -0
  193. package/dist/execution/index.d.ts +33 -481
  194. package/dist/execution/index.d.ts.map +1 -0
  195. package/dist/execution/index.js +45 -19
  196. package/dist/execution/scope/index.d.ts +10 -0
  197. package/dist/execution/scope/index.d.ts.map +1 -0
  198. package/dist/execution/scope/index.js +12 -0
  199. package/dist/execution/scope/run.d.ts +8 -0
  200. package/dist/execution/scope/run.d.ts.map +1 -0
  201. package/dist/execution/scope/store.d.ts +6 -0
  202. package/dist/execution/scope/store.d.ts.map +1 -0
  203. package/dist/execution/scope/types.d.ts +28 -0
  204. package/dist/execution/scope/types.d.ts.map +1 -0
  205. package/dist/execution/shared/usage.d.ts +9 -0
  206. package/dist/execution/shared/usage.d.ts.map +1 -0
  207. package/dist/execution/task/index.d.ts +6 -0
  208. package/dist/execution/task/index.d.ts.map +1 -0
  209. package/dist/execution/task/observer.d.ts +80 -0
  210. package/dist/execution/task/observer.d.ts.map +1 -0
  211. package/dist/execution/task/runner.d.ts +39 -0
  212. package/dist/execution/task/runner.d.ts.map +1 -0
  213. package/dist/execution/task/types.d.ts +85 -0
  214. package/dist/execution/task/types.d.ts.map +1 -0
  215. package/dist/execution/turn/engine/commit-batch.d.ts +16 -0
  216. package/dist/execution/turn/engine/commit-batch.d.ts.map +1 -0
  217. package/dist/execution/turn/engine/engine.d.ts +32 -0
  218. package/dist/execution/turn/engine/engine.d.ts.map +1 -0
  219. package/dist/execution/turn/engine/index.d.ts +12 -0
  220. package/dist/execution/turn/engine/index.d.ts.map +1 -0
  221. package/dist/execution/turn/engine/types.d.ts +67 -0
  222. package/dist/execution/turn/engine/types.d.ts.map +1 -0
  223. package/dist/execution/turn/index.d.ts +18 -0
  224. package/dist/execution/turn/index.d.ts.map +1 -0
  225. package/dist/execution/turn/index.js +52 -0
  226. package/dist/execution/turn/runner/commit.d.ts +11 -0
  227. package/dist/execution/turn/runner/commit.d.ts.map +1 -0
  228. package/dist/execution/turn/runner/index.d.ts +16 -0
  229. package/dist/execution/turn/runner/index.d.ts.map +1 -0
  230. package/dist/execution/turn/runner/prepare.d.ts +6 -0
  231. package/dist/execution/turn/runner/prepare.d.ts.map +1 -0
  232. package/dist/execution/turn/runner/stream-step.d.ts +8 -0
  233. package/dist/execution/turn/runner/stream-step.d.ts.map +1 -0
  234. package/dist/execution/turn/runner/tool-batch.d.ts +13 -0
  235. package/dist/execution/turn/runner/tool-batch.d.ts.map +1 -0
  236. package/dist/execution/turn/runner/types.d.ts +111 -0
  237. package/dist/execution/turn/runner/types.d.ts.map +1 -0
  238. package/dist/execution/turn/state.d.ts +110 -0
  239. package/dist/execution/turn/state.d.ts.map +1 -0
  240. package/dist/execution/turn/step-ledger.d.ts +89 -0
  241. package/dist/execution/turn/step-ledger.d.ts.map +1 -0
  242. package/dist/execution/turn/step-processing/doom-loop.d.ts +28 -0
  243. package/dist/execution/turn/step-processing/doom-loop.d.ts.map +1 -0
  244. package/dist/execution/turn/step-processing/index.d.ts +14 -0
  245. package/dist/execution/turn/step-processing/index.d.ts.map +1 -0
  246. package/dist/execution/turn/step-processing/overflow.d.ts +17 -0
  247. package/dist/execution/turn/step-processing/overflow.d.ts.map +1 -0
  248. package/dist/execution/turn/step-processing/process.d.ts +7 -0
  249. package/dist/execution/turn/step-processing/process.d.ts.map +1 -0
  250. package/dist/execution/turn/step-processing/types.d.ts +65 -0
  251. package/dist/execution/turn/step-processing/types.d.ts.map +1 -0
  252. package/dist/execution/workflow/index.d.ts +12 -0
  253. package/dist/execution/workflow/index.d.ts.map +1 -0
  254. package/dist/execution/workflow/index.js +39 -0
  255. package/dist/execution/workflow/planner/apply.d.ts +30 -0
  256. package/dist/execution/workflow/planner/apply.d.ts.map +1 -0
  257. package/dist/execution/workflow/planner/helpers.d.ts +6 -0
  258. package/dist/execution/workflow/planner/helpers.d.ts.map +1 -0
  259. package/dist/execution/workflow/planner/index.d.ts +13 -0
  260. package/dist/execution/workflow/planner/index.d.ts.map +1 -0
  261. package/dist/execution/workflow/planner/plan.d.ts +7 -0
  262. package/dist/execution/workflow/planner/plan.d.ts.map +1 -0
  263. package/dist/execution/workflow/planner/types.d.ts +49 -0
  264. package/dist/execution/workflow/planner/types.d.ts.map +1 -0
  265. package/dist/execution/workflow/snapshot.d.ts +11 -0
  266. package/dist/execution/workflow/snapshot.d.ts.map +1 -0
  267. package/dist/execution/workflow/state.d.ts +161 -0
  268. package/dist/execution/workflow/state.d.ts.map +1 -0
  269. package/dist/human/controller.d.ts +24 -0
  270. package/dist/human/controller.d.ts.map +1 -0
  271. package/dist/human/handler.d.ts +15 -0
  272. package/dist/human/handler.d.ts.map +1 -0
  273. package/dist/human/index.d.ts +5 -0
  274. package/dist/human/index.d.ts.map +1 -0
  275. package/dist/human/tool.d.ts +17 -0
  276. package/dist/human/tool.d.ts.map +1 -0
  277. package/dist/human/types.d.ts +62 -0
  278. package/dist/human/types.d.ts.map +1 -0
  279. package/dist/index.d.ts +66 -567
  280. package/dist/index.d.ts.map +1 -0
  281. package/dist/index.js +2681 -1859
  282. package/dist/inference/defaults.d.ts +8 -0
  283. package/dist/inference/defaults.d.ts.map +1 -0
  284. package/dist/inference/errors/classify.d.ts +5 -0
  285. package/dist/inference/errors/classify.d.ts.map +1 -0
  286. package/dist/inference/errors/extract.d.ts +3 -0
  287. package/dist/inference/errors/extract.d.ts.map +1 -0
  288. package/dist/inference/errors/index.d.ts +8 -11
  289. package/dist/inference/errors/index.d.ts.map +1 -0
  290. package/dist/inference/errors/llm-error.d.ts +14 -0
  291. package/dist/inference/errors/llm-error.d.ts.map +1 -0
  292. package/dist/inference/errors/types.d.ts +18 -0
  293. package/dist/inference/errors/types.d.ts.map +1 -0
  294. package/dist/inference/errors/utils.d.ts +5 -0
  295. package/dist/inference/errors/utils.d.ts.map +1 -0
  296. package/dist/inference/index.d.ts +17 -49
  297. package/dist/inference/index.d.ts.map +1 -0
  298. package/dist/inference/index.js +7 -7
  299. package/dist/inference/middleware-support.d.ts +14 -0
  300. package/dist/inference/middleware-support.d.ts.map +1 -0
  301. package/dist/{model-messages-n_ZMZwIm.d.ts → inference/model-messages.d.ts} +4 -6
  302. package/dist/inference/model-messages.d.ts.map +1 -0
  303. package/dist/inference/retry.d.ts +73 -0
  304. package/dist/inference/retry.d.ts.map +1 -0
  305. package/dist/inference/stream.d.ts +16 -0
  306. package/dist/inference/stream.d.ts.map +1 -0
  307. package/dist/inference/toolset.d.ts +26 -0
  308. package/dist/inference/toolset.d.ts.map +1 -0
  309. package/dist/inference/types.d.ts +129 -0
  310. package/dist/inference/types.d.ts.map +1 -0
  311. package/dist/intervention/follow-up-policy.d.ts +41 -0
  312. package/dist/intervention/follow-up-policy.d.ts.map +1 -0
  313. package/dist/intervention/index.d.ts +5 -0
  314. package/dist/intervention/index.d.ts.map +1 -0
  315. package/dist/intervention/intervention.d.ts +130 -0
  316. package/dist/intervention/intervention.d.ts.map +1 -0
  317. package/dist/intervention/types.d.ts +74 -0
  318. package/dist/intervention/types.d.ts.map +1 -0
  319. package/dist/logger/index.d.ts +5 -47
  320. package/dist/logger/index.d.ts.map +1 -0
  321. package/dist/logger/logger.d.ts +46 -0
  322. package/dist/logger/logger.d.ts.map +1 -0
  323. package/dist/{types-RSCv7nQ4.d.ts → logger/types.d.ts} +6 -7
  324. package/dist/logger/types.d.ts.map +1 -0
  325. package/dist/mcp/auth.d.ts +109 -0
  326. package/dist/mcp/auth.d.ts.map +1 -0
  327. package/dist/mcp/diagnostics.d.ts +23 -0
  328. package/dist/mcp/diagnostics.d.ts.map +1 -0
  329. package/dist/mcp/factories.d.ts +47 -0
  330. package/dist/mcp/factories.d.ts.map +1 -0
  331. package/dist/mcp/index.d.ts +14 -175
  332. package/dist/mcp/index.d.ts.map +1 -0
  333. package/dist/mcp/index.js +1 -1
  334. package/dist/mcp/manager.d.ts +45 -0
  335. package/dist/mcp/manager.d.ts.map +1 -0
  336. package/dist/mcp/modules.d.ts +6 -0
  337. package/dist/mcp/modules.d.ts.map +1 -0
  338. package/dist/{types-DMjoFKKv.d.ts → mcp/types.d.ts} +18 -19
  339. package/dist/mcp/types.d.ts.map +1 -0
  340. package/dist/memory/config.d.ts +4 -0
  341. package/dist/memory/config.d.ts.map +1 -0
  342. package/dist/memory/format.d.ts +8 -0
  343. package/dist/memory/format.d.ts.map +1 -0
  344. package/dist/memory/index.d.ts +5 -0
  345. package/dist/memory/index.d.ts.map +1 -0
  346. package/dist/memory/index.js +14 -0
  347. package/dist/memory/middleware.d.ts +14 -0
  348. package/dist/memory/middleware.d.ts.map +1 -0
  349. package/dist/memory/types.d.ts +251 -0
  350. package/dist/memory/types.d.ts.map +1 -0
  351. package/dist/middleware/approval.d.ts +70 -0
  352. package/dist/middleware/approval.d.ts.map +1 -0
  353. package/dist/middleware/index.d.ts +25 -110
  354. package/dist/middleware/index.d.ts.map +1 -0
  355. package/dist/middleware/index.js +2 -2
  356. package/dist/middleware/prompt-cache/cache.d.ts +44 -0
  357. package/dist/middleware/prompt-cache/cache.d.ts.map +1 -0
  358. package/dist/middleware/prompt-cache/index.d.ts +14 -0
  359. package/dist/middleware/prompt-cache/index.d.ts.map +1 -0
  360. package/dist/middleware/prompt-cache/types.d.ts +50 -0
  361. package/dist/middleware/prompt-cache/types.d.ts.map +1 -0
  362. package/dist/middleware/runner.d.ts +115 -0
  363. package/dist/middleware/runner.d.ts.map +1 -0
  364. package/dist/middleware/telemetry/index.d.ts +12 -0
  365. package/dist/middleware/telemetry/index.d.ts.map +1 -0
  366. package/dist/middleware/telemetry/otel.d.ts +4 -0
  367. package/dist/middleware/telemetry/otel.d.ts.map +1 -0
  368. package/dist/middleware/telemetry/provider.d.ts +3 -0
  369. package/dist/middleware/telemetry/provider.d.ts.map +1 -0
  370. package/dist/middleware/telemetry/types.d.ts +150 -0
  371. package/dist/middleware/telemetry/types.d.ts.map +1 -0
  372. package/dist/middleware/types.d.ts +426 -0
  373. package/dist/middleware/types.d.ts.map +1 -0
  374. package/dist/models/cache/adapters.d.ts +4 -0
  375. package/dist/models/cache/adapters.d.ts.map +1 -0
  376. package/dist/models/cache/index.d.ts +5 -0
  377. package/dist/models/cache/index.d.ts.map +1 -0
  378. package/dist/models/cache/manager.d.ts +32 -0
  379. package/dist/models/cache/manager.d.ts.map +1 -0
  380. package/dist/models/cache/types.d.ts +17 -0
  381. package/dist/models/cache/types.d.ts.map +1 -0
  382. package/dist/models/capability-resolver.d.ts +104 -0
  383. package/dist/models/capability-resolver.d.ts.map +1 -0
  384. package/dist/models/identifiers.d.ts +23 -0
  385. package/dist/models/identifiers.d.ts.map +1 -0
  386. package/dist/models/index.d.ts +35 -256
  387. package/dist/models/index.d.ts.map +1 -0
  388. package/dist/models/index.js +1 -1
  389. package/dist/models/overrides.d.ts +10 -0
  390. package/dist/models/overrides.d.ts.map +1 -0
  391. package/dist/models/profiles.d.ts +38 -0
  392. package/dist/models/profiles.d.ts.map +1 -0
  393. package/dist/models/reasoning/config.d.ts +49 -0
  394. package/dist/models/reasoning/config.d.ts.map +1 -0
  395. package/dist/models/reasoning/index.d.ts +12 -4
  396. package/dist/models/reasoning/index.d.ts.map +1 -0
  397. package/dist/models/reasoning/index.js +1 -1
  398. package/dist/models/reasoning/providers.d.ts +63 -0
  399. package/dist/models/reasoning/providers.d.ts.map +1 -0
  400. package/dist/{types-CQaXbRsS.d.ts → models/reasoning/types.d.ts} +7 -8
  401. package/dist/models/reasoning/types.d.ts.map +1 -0
  402. package/dist/models/remote/fetcher.d.ts +13 -0
  403. package/dist/models/remote/fetcher.d.ts.map +1 -0
  404. package/dist/models/remote/index.d.ts +8 -0
  405. package/dist/models/remote/index.d.ts.map +1 -0
  406. package/dist/models/remote/network.d.ts +6 -0
  407. package/dist/models/remote/network.d.ts.map +1 -0
  408. package/dist/models/remote/source.d.ts +16 -0
  409. package/dist/models/remote/source.d.ts.map +1 -0
  410. package/dist/models/remote/transform.d.ts +4 -0
  411. package/dist/models/remote/transform.d.ts.map +1 -0
  412. package/dist/models/remote/types.d.ts +28 -0
  413. package/dist/models/remote/types.d.ts.map +1 -0
  414. package/dist/models/resolver.d.ts +26 -0
  415. package/dist/models/resolver.d.ts.map +1 -0
  416. package/dist/models/types.d.ts +137 -0
  417. package/dist/models/types.d.ts.map +1 -0
  418. package/dist/plugin/compatibility.d.ts +11 -0
  419. package/dist/plugin/compatibility.d.ts.map +1 -0
  420. package/dist/plugin/define.d.ts +77 -0
  421. package/dist/plugin/define.d.ts.map +1 -0
  422. package/dist/plugin/event-bus.d.ts +31 -0
  423. package/dist/plugin/event-bus.d.ts.map +1 -0
  424. package/dist/plugin/index.d.ts +9 -458
  425. package/dist/plugin/index.d.ts.map +1 -0
  426. package/dist/plugin/loader.d.ts +63 -0
  427. package/dist/plugin/loader.d.ts.map +1 -0
  428. package/dist/plugin/registry.d.ts +81 -0
  429. package/dist/plugin/registry.d.ts.map +1 -0
  430. package/dist/plugin/settings.d.ts +36 -0
  431. package/dist/plugin/settings.d.ts.map +1 -0
  432. package/dist/plugin/types.d.ts +168 -0
  433. package/dist/plugin/types.d.ts.map +1 -0
  434. package/dist/profiles/apply.d.ts +17 -0
  435. package/dist/profiles/apply.d.ts.map +1 -0
  436. package/dist/profiles/builtins.d.ts +18 -0
  437. package/dist/profiles/builtins.d.ts.map +1 -0
  438. package/dist/profiles/index.d.ts +12 -55
  439. package/dist/profiles/index.d.ts.map +1 -0
  440. package/dist/profiles/patterns.d.ts +12 -0
  441. package/dist/profiles/patterns.d.ts.map +1 -0
  442. package/dist/profiles/types.d.ts +48 -0
  443. package/dist/profiles/types.d.ts.map +1 -0
  444. package/dist/prompt/builder/builder.d.ts +27 -0
  445. package/dist/prompt/builder/builder.d.ts.map +1 -0
  446. package/dist/prompt/builder/index.d.ts +11 -0
  447. package/dist/prompt/builder/index.d.ts.map +1 -0
  448. package/dist/prompt/builder/priorities.d.ts +13 -0
  449. package/dist/prompt/builder/priorities.d.ts.map +1 -0
  450. package/dist/prompt/builder/sections.d.ts +30 -0
  451. package/dist/prompt/builder/sections.d.ts.map +1 -0
  452. package/dist/prompt/environment.d.ts +46 -0
  453. package/dist/prompt/environment.d.ts.map +1 -0
  454. package/dist/prompt/index.d.ts +31 -220
  455. package/dist/prompt/index.d.ts.map +1 -0
  456. package/dist/prompt/index.js +3 -1
  457. package/dist/prompt/instructions.d.ts +104 -0
  458. package/dist/prompt/instructions.d.ts.map +1 -0
  459. package/dist/prompt/templates.d.ts +56 -0
  460. package/dist/prompt/templates.d.ts.map +1 -0
  461. package/dist/prompt/types.d.ts +218 -0
  462. package/dist/prompt/types.d.ts.map +1 -0
  463. package/dist/safety/errors.d.ts +18 -0
  464. package/dist/safety/errors.d.ts.map +1 -0
  465. package/dist/safety/handler.d.ts +16 -0
  466. package/dist/safety/handler.d.ts.map +1 -0
  467. package/dist/safety/index.d.ts +11 -133
  468. package/dist/safety/index.d.ts.map +1 -0
  469. package/dist/safety/patterns.d.ts +17 -0
  470. package/dist/safety/patterns.d.ts.map +1 -0
  471. package/dist/safety/policy.d.ts +31 -0
  472. package/dist/safety/policy.d.ts.map +1 -0
  473. package/dist/safety/presets.d.ts +43 -0
  474. package/dist/safety/presets.d.ts.map +1 -0
  475. package/dist/safety/risk.d.ts +14 -0
  476. package/dist/safety/risk.d.ts.map +1 -0
  477. package/dist/safety/types.d.ts +165 -0
  478. package/dist/safety/types.d.ts.map +1 -0
  479. package/dist/sandbox/index.d.ts +2 -81
  480. package/dist/sandbox/index.d.ts.map +1 -0
  481. package/dist/sandbox/types.d.ts +79 -0
  482. package/dist/sandbox/types.d.ts.map +1 -0
  483. package/dist/sessions/index.d.ts +13 -0
  484. package/dist/sessions/index.d.ts.map +1 -0
  485. package/dist/{storage → sessions}/index.js +6 -17
  486. package/dist/sessions/manager/default.d.ts +11 -0
  487. package/dist/sessions/manager/default.d.ts.map +1 -0
  488. package/dist/sessions/manager/index.d.ts +12 -0
  489. package/dist/sessions/manager/index.d.ts.map +1 -0
  490. package/dist/sessions/manager/session-manager.d.ts +67 -0
  491. package/dist/sessions/manager/session-manager.d.ts.map +1 -0
  492. package/dist/sessions/manager/types.d.ts +42 -0
  493. package/dist/sessions/manager/types.d.ts.map +1 -0
  494. package/dist/sessions/store/lock.d.ts +18 -0
  495. package/dist/sessions/store/lock.d.ts.map +1 -0
  496. package/dist/sessions/store/memory.d.ts +22 -0
  497. package/dist/sessions/store/memory.d.ts.map +1 -0
  498. package/dist/sessions/types.d.ts +215 -0
  499. package/dist/sessions/types.d.ts.map +1 -0
  500. package/dist/sessions/utils.d.ts +77 -0
  501. package/dist/sessions/utils.d.ts.map +1 -0
  502. package/dist/skill/discovery/constants.d.ts +6 -0
  503. package/dist/skill/discovery/constants.d.ts.map +1 -0
  504. package/dist/skill/discovery/dedupe.d.ts +3 -0
  505. package/dist/skill/discovery/dedupe.d.ts.map +1 -0
  506. package/dist/skill/discovery/discover.d.ts +3 -0
  507. package/dist/skill/discovery/discover.d.ts.map +1 -0
  508. package/dist/skill/discovery/fs.d.ts +4 -0
  509. package/dist/skill/discovery/fs.d.ts.map +1 -0
  510. package/dist/skill/discovery/index.d.ts +6 -0
  511. package/dist/skill/discovery/index.d.ts.map +1 -0
  512. package/dist/skill/discovery/scan.d.ts +3 -0
  513. package/dist/skill/discovery/scan.d.ts.map +1 -0
  514. package/dist/skill/discovery/types.d.ts +15 -0
  515. package/dist/skill/discovery/types.d.ts.map +1 -0
  516. package/dist/skill/index.d.ts +67 -89
  517. package/dist/skill/index.d.ts.map +1 -0
  518. package/dist/skill/index.js +2 -2
  519. package/dist/skill/loader/constants.d.ts +5 -0
  520. package/dist/skill/loader/constants.d.ts.map +1 -0
  521. package/dist/skill/loader/frontmatter.d.ts +5 -0
  522. package/dist/skill/loader/frontmatter.d.ts.map +1 -0
  523. package/dist/skill/loader/index.d.ts +8 -0
  524. package/dist/skill/loader/index.d.ts.map +1 -0
  525. package/dist/skill/loader/metadata.d.ts +3 -0
  526. package/dist/skill/loader/metadata.d.ts.map +1 -0
  527. package/dist/skill/loader/resources.d.ts +5 -0
  528. package/dist/skill/loader/resources.d.ts.map +1 -0
  529. package/dist/skill/registry.d.ts +177 -0
  530. package/dist/skill/registry.d.ts.map +1 -0
  531. package/dist/skill/tools.d.ts +77 -0
  532. package/dist/skill/tools.d.ts.map +1 -0
  533. package/dist/skill/types.d.ts +291 -0
  534. package/dist/skill/types.d.ts.map +1 -0
  535. package/dist/subagents/index.d.ts +8 -179
  536. package/dist/subagents/index.d.ts.map +1 -0
  537. package/dist/subagents/index.js +5 -4
  538. package/dist/subagents/installation.d.ts +23 -0
  539. package/dist/subagents/installation.d.ts.map +1 -0
  540. package/dist/subagents/results.d.ts +15 -0
  541. package/dist/subagents/results.d.ts.map +1 -0
  542. package/dist/subagents/roles/discovery.d.ts +38 -0
  543. package/dist/subagents/roles/discovery.d.ts.map +1 -0
  544. package/dist/subagents/roles/index.d.ts +5 -0
  545. package/dist/subagents/roles/index.d.ts.map +1 -0
  546. package/dist/subagents/roles/markdown-profile.d.ts +61 -0
  547. package/dist/subagents/roles/markdown-profile.d.ts.map +1 -0
  548. package/dist/subagents/tool-factories.d.ts +11 -0
  549. package/dist/subagents/tool-factories.d.ts.map +1 -0
  550. package/dist/subagents/tools.d.ts +13 -0
  551. package/dist/subagents/tools.d.ts.map +1 -0
  552. package/dist/subagents/types.d.ts +21 -0
  553. package/dist/subagents/types.d.ts.map +1 -0
  554. package/dist/team/coordinator/coordinator.d.ts +342 -0
  555. package/dist/team/coordinator/coordinator.d.ts.map +1 -0
  556. package/dist/team/coordinator/inbox.d.ts +99 -0
  557. package/dist/team/coordinator/inbox.d.ts.map +1 -0
  558. package/dist/team/coordinator/index.d.ts +19 -0
  559. package/dist/team/coordinator/index.d.ts.map +1 -0
  560. package/dist/team/coordinator/planning.d.ts +33 -0
  561. package/dist/team/coordinator/planning.d.ts.map +1 -0
  562. package/dist/team/coordinator/policy.d.ts +31 -0
  563. package/dist/team/coordinator/policy.d.ts.map +1 -0
  564. package/dist/team/coordinator/round-engine.d.ts +25 -0
  565. package/dist/team/coordinator/round-engine.d.ts.map +1 -0
  566. package/dist/team/coordinator/synthesis.d.ts +20 -0
  567. package/dist/team/coordinator/synthesis.d.ts.map +1 -0
  568. package/dist/team/coordinator/turn.d.ts +107 -0
  569. package/dist/team/coordinator/turn.d.ts.map +1 -0
  570. package/dist/team/coordinator/types.d.ts +344 -0
  571. package/dist/team/coordinator/types.d.ts.map +1 -0
  572. package/dist/team/events.d.ts +148 -0
  573. package/dist/team/events.d.ts.map +1 -0
  574. package/dist/team/execution.d.ts +51 -0
  575. package/dist/team/execution.d.ts.map +1 -0
  576. package/dist/team/index.d.ts +23 -545
  577. package/dist/team/index.d.ts.map +1 -0
  578. package/dist/team/index.js +2 -2
  579. package/dist/team/mailbox.d.ts +91 -0
  580. package/dist/team/mailbox.d.ts.map +1 -0
  581. package/dist/team/notifications.d.ts +23 -0
  582. package/dist/team/notifications.d.ts.map +1 -0
  583. package/dist/team/permissions.d.ts +88 -0
  584. package/dist/team/permissions.d.ts.map +1 -0
  585. package/dist/team/shutdown.d.ts +38 -0
  586. package/dist/team/shutdown.d.ts.map +1 -0
  587. package/dist/team/task-board.d.ts +161 -0
  588. package/dist/team/task-board.d.ts.map +1 -0
  589. package/dist/team/types.d.ts +233 -0
  590. package/dist/team/types.d.ts.map +1 -0
  591. package/dist/team/work-loop.d.ts +30 -0
  592. package/dist/team/work-loop.d.ts.map +1 -0
  593. package/dist/tool/executor.d.ts +59 -0
  594. package/dist/tool/executor.d.ts.map +1 -0
  595. package/dist/tool/host/index.d.ts +7 -38
  596. package/dist/tool/host/index.d.ts.map +1 -0
  597. package/dist/tool/host/local.d.ts +15 -0
  598. package/dist/tool/host/local.d.ts.map +1 -0
  599. package/dist/tool/host/registry.d.ts +17 -0
  600. package/dist/tool/host/registry.d.ts.map +1 -0
  601. package/dist/{types-C_LCeYNg.d.ts → tool/host/types.d.ts} +6 -7
  602. package/dist/tool/host/types.d.ts.map +1 -0
  603. package/dist/tool/index.d.ts +21 -285
  604. package/dist/tool/index.d.ts.map +1 -0
  605. package/dist/tool/index.js +4 -3
  606. package/dist/tool/registry.d.ts +130 -0
  607. package/dist/tool/registry.d.ts.map +1 -0
  608. package/dist/tool/replay.d.ts +11 -0
  609. package/dist/tool/replay.d.ts.map +1 -0
  610. package/dist/tool/tool-search.d.ts +50 -0
  611. package/dist/tool/tool-search.d.ts.map +1 -0
  612. package/dist/tool/tool.d.ts +308 -0
  613. package/dist/tool/tool.d.ts.map +1 -0
  614. package/dist/tool/truncation.d.ts +34 -0
  615. package/dist/tool/truncation.d.ts.map +1 -0
  616. package/dist/tool/turn-tools.d.ts +71 -0
  617. package/dist/tool/turn-tools.d.ts.map +1 -0
  618. package/dist/tracking/file-tracking.d.ts +25 -0
  619. package/dist/tracking/file-tracking.d.ts.map +1 -0
  620. package/dist/tracking/index.d.ts +9 -0
  621. package/dist/tracking/index.d.ts.map +1 -0
  622. package/dist/tracking/turn-tracker/diff.d.ts +11 -0
  623. package/dist/tracking/turn-tracker/diff.d.ts.map +1 -0
  624. package/dist/tracking/turn-tracker/index.d.ts +11 -0
  625. package/dist/tracking/turn-tracker/index.d.ts.map +1 -0
  626. package/dist/tracking/turn-tracker/tracker.d.ts +31 -0
  627. package/dist/tracking/turn-tracker/tracker.d.ts.map +1 -0
  628. package/dist/tracking/turn-tracker/types.d.ts +66 -0
  629. package/dist/tracking/turn-tracker/types.d.ts.map +1 -0
  630. package/dist/types/compaction.d.ts +191 -0
  631. package/dist/types/compaction.d.ts.map +1 -0
  632. package/dist/types/doom-loop.d.ts +25 -0
  633. package/dist/types/doom-loop.d.ts.map +1 -0
  634. package/dist/types/events.d.ts +196 -0
  635. package/dist/types/events.d.ts.map +1 -0
  636. package/dist/types/index.d.ts +17 -0
  637. package/dist/types/index.d.ts.map +1 -0
  638. package/dist/types/messages.d.ts +119 -0
  639. package/dist/types/messages.d.ts.map +1 -0
  640. package/dist/types/stream.d.ts +172 -0
  641. package/dist/types/stream.d.ts.map +1 -0
  642. package/dist/types/tool.d.ts +309 -0
  643. package/dist/types/tool.d.ts.map +1 -0
  644. package/dist/types/turn-source.d.ts +36 -0
  645. package/dist/types/turn-source.d.ts.map +1 -0
  646. package/dist/utils/sleep.d.ts +7 -0
  647. package/dist/utils/sleep.d.ts.map +1 -0
  648. package/package.json +49 -12
  649. package/dist/chunk-CJI7PVS2.js +0 -58
  650. package/dist/chunk-V6ETEYST.js +0 -2091
  651. package/dist/index-BCqEGzBj.d.ts +0 -251
  652. package/dist/instance-Bg61WSyz.d.ts +0 -6004
  653. package/dist/llm-error-D93FNNLY.d.ts +0 -32
  654. package/dist/storage/index.d.ts +0 -191
  655. package/dist/turn-tools/index.d.ts +0 -12
  656. package/dist/turn-tools/index.js +0 -1
  657. package/dist/{chunk-O2WCYSXQ.js → chunk-3NBTQHVV.js} +0 -0
  658. package/dist/{chunk-Q742PSH3.js → chunk-MJML3A2F.js} +36 -36
@@ -0,0 +1,1458 @@
1
+ import {
2
+ estimateConversationTokens,
3
+ estimateMessageTokens,
4
+ estimateTokens,
5
+ isAgentContextFragmentMessage,
6
+ truncateTextMiddle,
7
+ truncateTextPrefix
8
+ } from "./chunk-CGP6UNCQ.js";
9
+
10
+ // src/context/window/budget.ts
11
+ var DEFAULT_CONTEXT_LIMITS = {
12
+ contextWindow: 128e3,
13
+ effectiveContextWindowPercent: 95,
14
+ reserveTokens: 16e3,
15
+ protectedTokens: 4e4,
16
+ pruneMinimum: 2e4
17
+ };
18
+ var MIN_EFFECTIVE_CONTEXT_WINDOW_PERCENT = 1;
19
+ var MAX_EFFECTIVE_CONTEXT_WINDOW_PERCENT = 100;
20
+ function finitePositiveInteger(value) {
21
+ if (typeof value !== "number" || !Number.isFinite(value)) return void 0;
22
+ const normalized = Math.floor(value);
23
+ return normalized > 0 ? normalized : void 0;
24
+ }
25
+ function normalizePercent(value, fallback) {
26
+ if (typeof value !== "number" || !Number.isFinite(value)) return fallback;
27
+ return Math.min(
28
+ MAX_EFFECTIVE_CONTEXT_WINDOW_PERCENT,
29
+ Math.max(MIN_EFFECTIVE_CONTEXT_WINDOW_PERCENT, Math.floor(value))
30
+ );
31
+ }
32
+ var DEFAULT_SUMMARY_MAX_OUTPUT_TOKENS = 2e3;
33
+ var DEFAULT_SUMMARY_MAX_INPUT_TOKENS = 24e3;
34
+ var DEFAULT_COMPACTION_EFFECTIVE_MIN_SAVINGS_RATIO = 0.02;
35
+ function getUsableTokenLimit(limits) {
36
+ const effectiveWindow = getEffectiveContextWindow(limits);
37
+ const reserveLimitedWindow = limits.contextWindow - limits.reserveTokens;
38
+ return Math.max(1, Math.min(effectiveWindow, reserveLimitedWindow));
39
+ }
40
+ function getEffectiveContextWindow(limits) {
41
+ const percent = normalizePercent(
42
+ limits.effectiveContextWindowPercent,
43
+ DEFAULT_CONTEXT_LIMITS.effectiveContextWindowPercent ?? 95
44
+ );
45
+ return Math.max(1, Math.floor(limits.contextWindow * percent / 100));
46
+ }
47
+ function getAutoCompactTokenLimit(limits) {
48
+ const usableLimit = getUsableTokenLimit(limits);
49
+ const configured = finitePositiveInteger(limits.autoCompactTokenLimit);
50
+ return Math.min(configured ?? usableLimit, usableLimit);
51
+ }
52
+ function isContextOverflowing(tokens, limits = DEFAULT_CONTEXT_LIMITS) {
53
+ return tokens > getUsableTokenLimit(limits);
54
+ }
55
+ function shouldPruneContext(tokens, limits = DEFAULT_CONTEXT_LIMITS) {
56
+ if (tokens < limits.pruneMinimum) return false;
57
+ return tokens > getAutoCompactTokenLimit(limits);
58
+ }
59
+ function finiteNonNegativeInteger(value) {
60
+ if (!Number.isFinite(value)) return 0;
61
+ return Math.max(0, Math.floor(value));
62
+ }
63
+ function createCompactionEffectiveness(tokensBefore, tokensAfter, minSavingsRatio = DEFAULT_COMPACTION_EFFECTIVE_MIN_SAVINGS_RATIO) {
64
+ const before = finiteNonNegativeInteger(tokensBefore);
65
+ const after = finiteNonNegativeInteger(tokensAfter);
66
+ const removed = Math.max(0, before - after);
67
+ const savingsRatio = before > 0 ? removed / before : 0;
68
+ const effective = removed > 0 && savingsRatio >= Math.max(0, Number.isFinite(minSavingsRatio) ? minSavingsRatio : 0);
69
+ return {
70
+ tokensBefore: before,
71
+ tokensAfter: after,
72
+ tokensRemoved: removed,
73
+ savingsRatio,
74
+ effective
75
+ };
76
+ }
77
+ function clampRatio(value) {
78
+ if (typeof value !== "number" || !Number.isFinite(value)) return void 0;
79
+ if (value <= 0) return void 0;
80
+ return Math.min(1, value);
81
+ }
82
+ function resolveSummaryOutputTokens(options) {
83
+ const limits = options.limits ?? DEFAULT_CONTEXT_LIMITS;
84
+ const configuredCap = finitePositiveInteger(options.summaryMaxOutputTokens) ?? DEFAULT_SUMMARY_MAX_OUTPUT_TOKENS;
85
+ const reserveCap = Math.max(1, Math.floor(limits.reserveTokens * 0.8));
86
+ const cap = Math.max(1, Math.min(configuredCap, reserveCap));
87
+ const ratio = clampRatio(options.summaryTargetRatio);
88
+ if (ratio === void 0) {
89
+ return cap;
90
+ }
91
+ const inputTokens = finitePositiveInteger(options.inputTokens) ?? 0;
92
+ const target = Math.max(1, Math.ceil(inputTokens * ratio));
93
+ return Math.min(cap, target);
94
+ }
95
+
96
+ // src/context/window/cut-planner.ts
97
+ function hasToolCalls(message) {
98
+ return message.role === "assistant" && Array.isArray(message.toolCalls) && message.toolCalls.length > 0;
99
+ }
100
+ function getToolCallIds(message) {
101
+ if (!hasToolCalls(message)) return [];
102
+ return message.toolCalls.map((toolCall) => toolCall.toolCallId).filter((id) => id.length > 0);
103
+ }
104
+ function hasValidToolResultShape(messages) {
105
+ const pendingToolCallIds = /* @__PURE__ */ new Set();
106
+ for (const message of messages) {
107
+ if (message.role === "tool") {
108
+ if (!pendingToolCallIds.has(message.toolCallId)) {
109
+ return false;
110
+ }
111
+ pendingToolCallIds.delete(message.toolCallId);
112
+ continue;
113
+ }
114
+ if (pendingToolCallIds.size > 0) {
115
+ return false;
116
+ }
117
+ for (const toolCallId of getToolCallIds(message)) {
118
+ pendingToolCallIds.add(toolCallId);
119
+ }
120
+ }
121
+ return pendingToolCallIds.size === 0;
122
+ }
123
+ function isLocallySafeCutBoundary(messages, index) {
124
+ if (index <= 0 || index >= messages.length) return false;
125
+ const firstKept = messages[index];
126
+ if (!firstKept || firstKept.role === "tool") return false;
127
+ if (hasToolCalls(firstKept)) {
128
+ const next = messages[index + 1];
129
+ return next?.role === "tool";
130
+ }
131
+ return true;
132
+ }
133
+ function isSafeCutBoundary(messages, index) {
134
+ return isLocallySafeCutBoundary(messages, index) && hasValidToolResultShape(messages.slice(index));
135
+ }
136
+ function isPreferredCutBoundary(messages, index) {
137
+ const firstKept = messages[index];
138
+ if (!firstKept) return false;
139
+ if (firstKept.role === "system") return true;
140
+ return firstKept.role === "user" && !isAgentContextFragmentMessage(firstKept);
141
+ }
142
+ function findLatestUserMessageIndex(messages) {
143
+ for (let i = messages.length - 1; i >= 0; i--) {
144
+ const message = messages[i];
145
+ if (message.role === "user" && !isAgentContextFragmentMessage(message)) {
146
+ return i;
147
+ }
148
+ }
149
+ return void 0;
150
+ }
151
+ function getAdjustedCutReason(options) {
152
+ if (options.cutIndex === options.targetCutIndex) {
153
+ return "protected-window";
154
+ }
155
+ if (options.latestUserIndex !== void 0 && options.targetCutIndex > options.latestUserIndex && options.cutIndex <= options.latestUserIndex) {
156
+ return "latest-user";
157
+ }
158
+ return options.targetBoundaryWasSafe ? "turn-boundary" : "tool-boundary";
159
+ }
160
+ function buildCutPlan(messages, cutIndex, protectedTokens, reason, tokenEstimator) {
161
+ if (cutIndex === 0) {
162
+ return {
163
+ kind: "conversation",
164
+ cutIndex: 0,
165
+ removedMessages: [],
166
+ keptMessages: [...messages],
167
+ tokensRemoved: 0,
168
+ tokensKept: estimateConversationTokens(messages, tokenEstimator),
169
+ protectedTokens,
170
+ reason,
171
+ historyMessages: [],
172
+ currentTurnPrefixMessages: []
173
+ };
174
+ }
175
+ const removedMessages = messages.slice(0, cutIndex);
176
+ const keptMessages = messages.slice(cutIndex);
177
+ return {
178
+ kind: "conversation",
179
+ cutIndex,
180
+ removedMessages,
181
+ keptMessages,
182
+ tokensRemoved: estimateConversationTokens(removedMessages, tokenEstimator),
183
+ tokensKept: estimateConversationTokens(keptMessages, tokenEstimator),
184
+ protectedTokens,
185
+ reason,
186
+ historyMessages: removedMessages,
187
+ currentTurnPrefixMessages: []
188
+ };
189
+ }
190
+ function buildSplitTurnPrefixPlan(messages, cutIndex, protectedTokens, currentTurnStartIndex, tokenEstimator) {
191
+ const removedMessages = messages.slice(0, cutIndex);
192
+ const keptMessages = messages.slice(cutIndex);
193
+ const historyMessages = messages.slice(0, currentTurnStartIndex);
194
+ const currentTurnPrefixMessages = messages.slice(
195
+ currentTurnStartIndex,
196
+ cutIndex
197
+ );
198
+ return {
199
+ kind: "split-turn-prefix",
200
+ cutIndex,
201
+ removedMessages,
202
+ keptMessages,
203
+ tokensRemoved: estimateConversationTokens(removedMessages, tokenEstimator),
204
+ tokensKept: estimateConversationTokens(keptMessages, tokenEstimator),
205
+ protectedTokens,
206
+ reason: "split-turn-prefix",
207
+ historyMessages,
208
+ currentTurnPrefixMessages,
209
+ currentTurnStartIndex
210
+ };
211
+ }
212
+ function getProtectedWindowStart(messages, protectedTokens, tokenEstimator) {
213
+ let tokensFromEnd = 0;
214
+ for (let i = messages.length - 1; i >= 0; i--) {
215
+ tokensFromEnd += estimateMessageTokens(messages[i], tokenEstimator);
216
+ if (tokensFromEnd >= protectedTokens) {
217
+ return i;
218
+ }
219
+ }
220
+ return messages.length;
221
+ }
222
+ function findSplitTurnPrefixPlan(messages, protectedTokens, maxKeptTokens, normalPlan, tokenEstimator) {
223
+ const currentTurnStartIndex = findLatestUserMessageIndex(messages);
224
+ if (currentTurnStartIndex === void 0 || currentTurnStartIndex >= messages.length - 1) {
225
+ return void 0;
226
+ }
227
+ const targetStart = Math.max(
228
+ getProtectedWindowStart(messages, protectedTokens, tokenEstimator),
229
+ currentTurnStartIndex + 1
230
+ );
231
+ let bestPlan;
232
+ const consider = (index) => {
233
+ if (!isSafeCutBoundary(messages, index)) return false;
234
+ const plan = buildSplitTurnPrefixPlan(
235
+ messages,
236
+ index,
237
+ protectedTokens,
238
+ currentTurnStartIndex,
239
+ tokenEstimator
240
+ );
241
+ if (plan.tokensKept >= normalPlan.tokensKept) return false;
242
+ if (maxKeptTokens === void 0 || plan.tokensKept <= maxKeptTokens) {
243
+ bestPlan = plan;
244
+ return true;
245
+ }
246
+ if (!bestPlan || plan.tokensKept < bestPlan.tokensKept) {
247
+ bestPlan = plan;
248
+ }
249
+ return false;
250
+ };
251
+ for (let i = targetStart; i >= currentTurnStartIndex + 1; i--) {
252
+ if (consider(i)) return bestPlan;
253
+ }
254
+ for (let i = targetStart + 1; i < messages.length; i++) {
255
+ if (consider(i)) return bestPlan;
256
+ }
257
+ return bestPlan;
258
+ }
259
+ function planCompactionCut(messages, protectedTokens = DEFAULT_CONTEXT_LIMITS.protectedTokens, options = {}) {
260
+ const tokenEstimator = options.tokenEstimator;
261
+ if (messages.length === 0) {
262
+ return buildCutPlan(
263
+ messages,
264
+ 0,
265
+ protectedTokens,
266
+ "no-safe-cut",
267
+ tokenEstimator
268
+ );
269
+ }
270
+ const targetCutIndex = getProtectedWindowStart(
271
+ messages,
272
+ protectedTokens,
273
+ tokenEstimator
274
+ );
275
+ if (targetCutIndex <= 1) {
276
+ const noSafePlan2 = buildCutPlan(
277
+ messages,
278
+ 0,
279
+ protectedTokens,
280
+ "no-safe-cut",
281
+ tokenEstimator
282
+ );
283
+ if (options.allowSplitTurn) {
284
+ return findSplitTurnPrefixPlan(
285
+ messages,
286
+ protectedTokens,
287
+ options.maxKeptTokens,
288
+ noSafePlan2,
289
+ tokenEstimator
290
+ ) ?? noSafePlan2;
291
+ }
292
+ return noSafePlan2;
293
+ }
294
+ const latestUserIndex = findLatestUserMessageIndex(messages);
295
+ const rawStartIndex = targetCutIndex >= messages.length ? messages.length - 1 : targetCutIndex;
296
+ const startIndex = latestUserIndex === void 0 ? rawStartIndex : Math.min(rawStartIndex, latestUserIndex);
297
+ const targetBoundaryWasSafe = targetCutIndex <= startIndex && isSafeCutBoundary(messages, targetCutIndex);
298
+ if (startIndex <= 0) {
299
+ const noSafePlan2 = buildCutPlan(
300
+ messages,
301
+ 0,
302
+ protectedTokens,
303
+ "no-safe-cut",
304
+ tokenEstimator
305
+ );
306
+ if (options.allowSplitTurn) {
307
+ return findSplitTurnPrefixPlan(
308
+ messages,
309
+ protectedTokens,
310
+ options.maxKeptTokens,
311
+ noSafePlan2,
312
+ tokenEstimator
313
+ ) ?? noSafePlan2;
314
+ }
315
+ return noSafePlan2;
316
+ }
317
+ for (let i = startIndex; i >= 1; i--) {
318
+ if (isPreferredCutBoundary(messages, i) && isSafeCutBoundary(messages, i)) {
319
+ const plan = buildCutPlan(
320
+ messages,
321
+ i,
322
+ protectedTokens,
323
+ getAdjustedCutReason({
324
+ cutIndex: i,
325
+ targetCutIndex,
326
+ latestUserIndex,
327
+ targetBoundaryWasSafe
328
+ }),
329
+ tokenEstimator
330
+ );
331
+ if (options.allowSplitTurn && options.maxKeptTokens !== void 0 && plan.tokensKept > options.maxKeptTokens) {
332
+ return findSplitTurnPrefixPlan(
333
+ messages,
334
+ protectedTokens,
335
+ options.maxKeptTokens,
336
+ plan,
337
+ tokenEstimator
338
+ ) ?? plan;
339
+ }
340
+ return plan;
341
+ }
342
+ }
343
+ for (let i = startIndex; i >= 1; i--) {
344
+ if (isSafeCutBoundary(messages, i)) {
345
+ const plan = buildCutPlan(
346
+ messages,
347
+ i,
348
+ protectedTokens,
349
+ getAdjustedCutReason({
350
+ cutIndex: i,
351
+ targetCutIndex,
352
+ latestUserIndex,
353
+ targetBoundaryWasSafe
354
+ }),
355
+ tokenEstimator
356
+ );
357
+ if (options.allowSplitTurn && options.maxKeptTokens !== void 0 && plan.tokensKept > options.maxKeptTokens) {
358
+ return findSplitTurnPrefixPlan(
359
+ messages,
360
+ protectedTokens,
361
+ options.maxKeptTokens,
362
+ plan,
363
+ tokenEstimator
364
+ ) ?? plan;
365
+ }
366
+ return plan;
367
+ }
368
+ }
369
+ const noSafePlan = buildCutPlan(
370
+ messages,
371
+ 0,
372
+ protectedTokens,
373
+ "no-safe-cut",
374
+ tokenEstimator
375
+ );
376
+ if (options.allowSplitTurn) {
377
+ return findSplitTurnPrefixPlan(
378
+ messages,
379
+ protectedTokens,
380
+ options.maxKeptTokens,
381
+ noSafePlan,
382
+ tokenEstimator
383
+ ) ?? noSafePlan;
384
+ }
385
+ return noSafePlan;
386
+ }
387
+
388
+ // src/context/window/decision.ts
389
+ function defaultCompactionReason(options) {
390
+ if (options.reason) return options.reason;
391
+ if (options.trigger === "manual") return "manual-request";
392
+ if (options.forced) return "provider-overflow";
393
+ return "context-limit";
394
+ }
395
+ function createDecision(params) {
396
+ return {
397
+ needed: params.needed,
398
+ reason: params.reason,
399
+ strategy: params.strategy,
400
+ forced: params.forced,
401
+ trigger: params.trigger,
402
+ compactionReason: params.compactionReason,
403
+ canSummarize: params.canSummarize,
404
+ inputTokens: params.inputTokens,
405
+ limit: params.limit,
406
+ overflowTokens: params.overflowTokens,
407
+ protectedTokens: params.protectedTokens,
408
+ pruneMinimum: params.pruneMinimum
409
+ };
410
+ }
411
+ function decideContextCompaction(messages, options = {}) {
412
+ const limits = options.limits ?? DEFAULT_CONTEXT_LIMITS;
413
+ const inputTokens = options.inputTokens ?? estimateConversationTokens(messages, options.tokenEstimator);
414
+ const limit = getAutoCompactTokenLimit(limits);
415
+ const overflowTokens = Math.max(0, inputTokens - limit);
416
+ const forced = options.force === true;
417
+ const trigger = options.trigger ?? (forced ? "recovery" : "auto");
418
+ const compactionReason = defaultCompactionReason({
419
+ forced,
420
+ trigger,
421
+ reason: options.reason
422
+ });
423
+ const canSummarize = options.canSummarize === true;
424
+ if (forced) {
425
+ return createDecision({
426
+ needed: true,
427
+ reason: "forced-recovery",
428
+ strategy: "tool-context-first",
429
+ forced,
430
+ trigger,
431
+ compactionReason,
432
+ canSummarize,
433
+ inputTokens,
434
+ limit,
435
+ overflowTokens,
436
+ protectedTokens: limits.protectedTokens,
437
+ pruneMinimum: limits.pruneMinimum
438
+ });
439
+ }
440
+ if (inputTokens < limits.pruneMinimum) {
441
+ return createDecision({
442
+ needed: false,
443
+ reason: "below-prune-minimum",
444
+ strategy: "none",
445
+ forced,
446
+ trigger,
447
+ compactionReason,
448
+ canSummarize,
449
+ inputTokens,
450
+ limit,
451
+ overflowTokens,
452
+ protectedTokens: limits.protectedTokens,
453
+ pruneMinimum: limits.pruneMinimum
454
+ });
455
+ }
456
+ if (!shouldPruneContext(inputTokens, limits)) {
457
+ return createDecision({
458
+ needed: false,
459
+ reason: "under-limit",
460
+ strategy: "none",
461
+ forced,
462
+ trigger,
463
+ compactionReason,
464
+ canSummarize,
465
+ inputTokens,
466
+ limit,
467
+ overflowTokens,
468
+ protectedTokens: limits.protectedTokens,
469
+ pruneMinimum: limits.pruneMinimum
470
+ });
471
+ }
472
+ return createDecision({
473
+ needed: true,
474
+ reason: "overflow",
475
+ strategy: "tool-context-first",
476
+ forced,
477
+ trigger,
478
+ compactionReason,
479
+ canSummarize,
480
+ inputTokens,
481
+ limit,
482
+ overflowTokens,
483
+ protectedTokens: limits.protectedTokens,
484
+ pruneMinimum: limits.pruneMinimum
485
+ });
486
+ }
487
+
488
+ // src/types/compaction.ts
489
+ var PRUNE_PROTECTED_TOOLS = ["skill"];
490
+
491
+ // src/context/window/summary.ts
492
+ import { generateText } from "ai";
493
+ var CHARS_PER_TOKEN = 4;
494
+ var DEFAULT_MESSAGE_INPUT_TOKENS = 1500;
495
+ var SUMMARY_HEADING = "## Previous Conversation Summary";
496
+ var SUMMARY_PREFIX = `${SUMMARY_HEADING}
497
+
498
+ `;
499
+ var DEFAULT_SUMMARY_PROMPT = `You are summarizing a conversation to continue it with context.
500
+
501
+ Create a structured summary that captures:
502
+ 1. **Goal**: What the user is trying to accomplish
503
+ 2. **Progress**: What has been done so far
504
+ 3. **Decisions**: Key decisions made during the conversation
505
+ 4. **Current State**: Where we left off
506
+ 5. **Next Steps**: What should happen next
507
+
508
+ Be concise but comprehensive. Include specific file paths, function names, and technical details that would be lost otherwise.
509
+
510
+ Format as a clear summary that could be given to another assistant to continue the work.`;
511
+ var UPDATE_SUMMARY_PROMPT = `You are updating an existing conversation handoff summary.
512
+
513
+ Preserve durable facts from the existing summary, incorporate the new conversation material, and remove only details that are clearly obsolete. Keep the result concise but specific enough for another assistant to continue the work without the removed messages.`;
514
+ var SPLIT_TURN_SUMMARY_PROMPT = `You are creating a context checkpoint for a conversation where the active turn became too large to keep as one contiguous block.
515
+
516
+ The later suffix of the active turn remains verbatim after this summary. Summarize only the removed material. The summary is reference context, not a new user instruction.
517
+
518
+ Preserve:
519
+ 1. The user's original active-turn request, if it appears in the removed prefix
520
+ 2. Early progress, decisions, file paths, commands, and tool results needed to understand the kept suffix
521
+ 3. Relevant older conversation state that still matters
522
+ 4. Open issues or blockers that the kept suffix depends on
523
+
524
+ Do not invent next steps. Do not ask or answer questions from the removed material. Return only the handoff summary body.`;
525
+ var DEFAULT_RECENT_MESSAGE_RATIO = 0.65;
526
+ function createCompactionSummaryContent(summary) {
527
+ return `${SUMMARY_PREFIX}${summary.trim()}`;
528
+ }
529
+ function extractCompactionSummaryText(message) {
530
+ if (message.role !== "system") return void 0;
531
+ if (!message.content.startsWith(SUMMARY_PREFIX)) return void 0;
532
+ return message.content.slice(SUMMARY_PREFIX.length).trim();
533
+ }
534
+ function estimateCharsFromTokens(tokens, fallback) {
535
+ if (tokens === void 0 || !Number.isFinite(tokens) || tokens <= 0) {
536
+ return fallback * CHARS_PER_TOKEN;
537
+ }
538
+ return Math.max(1, Math.floor(tokens) * CHARS_PER_TOKEN);
539
+ }
540
+ function stringifyForSummary(value) {
541
+ if (typeof value === "string") return value;
542
+ if (value === void 0) return "";
543
+ try {
544
+ return JSON.stringify(value);
545
+ } catch {
546
+ return String(value);
547
+ }
548
+ }
549
+ function redactSummaryText(text) {
550
+ return text.replace(/\bsk-[A-Za-z0-9_-]{12,}\b/g, "[REDACTED]").replace(/\bBearer\s+[A-Za-z0-9._~+/=-]{8,}/gi, "Bearer [REDACTED]").replace(
551
+ /((?:api[_-]?key|access[_-]?token|refresh[_-]?token|client[_-]?secret|password|secret|token)\s*[:=]\s*["']?)[^"',\s}]{8,}/gi,
552
+ "$1[REDACTED]"
553
+ );
554
+ }
555
+ function compactText(text, maxChars) {
556
+ if (maxChars <= 0) return "";
557
+ const redacted = redactSummaryText(text);
558
+ return truncateTextMiddle(redacted, maxChars, {
559
+ headRatio: 0.7,
560
+ marker: (omitted) => `
561
+
562
+ [...${omitted} characters omitted for compaction...]
563
+
564
+ `
565
+ });
566
+ }
567
+ function renderToolCalls(message, maxChars) {
568
+ if (message.role !== "assistant" || !message.toolCalls?.length) return "";
569
+ const lines = message.toolCalls.map((toolCall) => {
570
+ const args = compactText(stringifyForSummary(toolCall.args), maxChars);
571
+ return `- ${toolCall.toolName} (${toolCall.toolCallId}): ${args}`;
572
+ });
573
+ return `[TOOL CALLS]
574
+ ${lines.join("\n")}`;
575
+ }
576
+ function serializeMessageForSummary(message, maxChars) {
577
+ const role = message.role.toUpperCase();
578
+ if (message.role === "tool") {
579
+ const content2 = compactText(message.content, maxChars);
580
+ return `[TOOL RESULT: ${message.toolName} ${message.toolCallId}]
581
+ ${content2}`;
582
+ }
583
+ const content = compactText(message.content, maxChars);
584
+ const toolCalls = renderToolCalls(
585
+ message,
586
+ Math.max(512, Math.floor(maxChars / 2))
587
+ );
588
+ const parts = [`[${role}]
589
+ ${content}`];
590
+ if (toolCalls) parts.push(toolCalls);
591
+ return parts.join("\n\n");
592
+ }
593
+ function separatorLength(parts) {
594
+ return parts.length > 0 ? 2 : 0;
595
+ }
596
+ function joinedLength(parts) {
597
+ if (parts.length === 0) return 0;
598
+ return parts.reduce((total, part) => total + part.length, 0) + (parts.length - 1) * 2;
599
+ }
600
+ function clampRecentMessageRatio(value) {
601
+ if (typeof value !== "number" || !Number.isFinite(value)) {
602
+ return DEFAULT_RECENT_MESSAGE_RATIO;
603
+ }
604
+ return Math.min(0.9, Math.max(0.1, value));
605
+ }
606
+ function appendWithinBudget(params) {
607
+ const remaining = params.budget - joinedLength(params.parts) - separatorLength(params.parts);
608
+ if (remaining <= 0) return false;
609
+ if (params.text.length <= remaining) {
610
+ params.parts.push(params.text);
611
+ return true;
612
+ }
613
+ if (!params.allowPartial) return false;
614
+ const compacted = compactText(params.text, remaining);
615
+ if (!compacted) return false;
616
+ params.parts.push(compacted);
617
+ return true;
618
+ }
619
+ function prependWithinBudget(params) {
620
+ const remaining = params.budget - joinedLength(params.parts) - separatorLength(params.parts);
621
+ if (remaining <= 0) return false;
622
+ if (params.text.length <= remaining) {
623
+ params.parts.unshift(params.text);
624
+ return true;
625
+ }
626
+ if (!params.allowPartial) return false;
627
+ const compacted = compactText(params.text, remaining);
628
+ if (!compacted) return false;
629
+ params.parts.unshift(compacted);
630
+ return true;
631
+ }
632
+ function serializeBoundedMessages(serializedMessages, maxChars, recentMessageRatio) {
633
+ if (serializedMessages.length === 0) {
634
+ return "[No message content was available for summarization.]";
635
+ }
636
+ const fullTranscript = serializedMessages.join("\n\n");
637
+ if (fullTranscript.length <= maxChars) {
638
+ return fullTranscript;
639
+ }
640
+ if (serializedMessages.length === 1) {
641
+ return compactText(serializedMessages[0], maxChars);
642
+ }
643
+ const markerFor = (omittedCount2) => omittedCount2 > 0 ? `[...${omittedCount2} messages omitted for compaction; preserved beginning and most recent removed context...]` : "[...message content omitted for compaction; preserved beginning and most recent removed context...]";
644
+ const markerReserve = markerFor(serializedMessages.length).length + 4;
645
+ const contentBudget = Math.max(1, maxChars - markerReserve);
646
+ const tailBudget = Math.max(
647
+ 1,
648
+ Math.floor(contentBudget * recentMessageRatio)
649
+ );
650
+ const headBudget = Math.max(1, contentBudget - tailBudget);
651
+ const headParts = [];
652
+ let headEnd = 0;
653
+ for (let i = 0; i < serializedMessages.length; i++) {
654
+ const added = appendWithinBudget({
655
+ parts: headParts,
656
+ text: serializedMessages[i],
657
+ budget: headBudget,
658
+ allowPartial: headParts.length === 0
659
+ });
660
+ if (!added) break;
661
+ headEnd = i + 1;
662
+ if (joinedLength(headParts) >= headBudget) break;
663
+ }
664
+ const tailParts = [];
665
+ let tailStart = serializedMessages.length;
666
+ for (let i = serializedMessages.length - 1; i >= headEnd; i--) {
667
+ const added = prependWithinBudget({
668
+ parts: tailParts,
669
+ text: serializedMessages[i],
670
+ budget: tailBudget,
671
+ allowPartial: tailParts.length === 0
672
+ });
673
+ if (!added) break;
674
+ tailStart = i;
675
+ if (joinedLength(tailParts) >= tailBudget) break;
676
+ }
677
+ const omittedCount = Math.max(0, tailStart - headEnd);
678
+ const marker = markerFor(omittedCount);
679
+ const transcript = [...headParts, marker, ...tailParts].filter((part) => part.length > 0).join("\n\n");
680
+ return transcript.length <= maxChars ? transcript : compactText(transcript, maxChars);
681
+ }
682
+ function serializeMessagesForSummary(messages, options = {}) {
683
+ const maxChars = estimateCharsFromTokens(
684
+ options.maxInputTokens,
685
+ DEFAULT_SUMMARY_MAX_INPUT_TOKENS
686
+ );
687
+ const maxMessageChars = estimateCharsFromTokens(
688
+ options.maxMessageTokens,
689
+ DEFAULT_MESSAGE_INPUT_TOKENS
690
+ );
691
+ const serializedMessages = messages.map(
692
+ (message) => serializeMessageForSummary(message, maxMessageChars)
693
+ );
694
+ const transcript = serializeBoundedMessages(
695
+ serializedMessages,
696
+ maxChars,
697
+ clampRecentMessageRatio(options.recentMessageRatio)
698
+ );
699
+ if (messages.length > 0 && transcript.length >= maxChars) {
700
+ return `${transcript}
701
+
702
+ [Summary input reached its configured compaction cap.]`;
703
+ }
704
+ if (messages.length > 0 && serializedMessages.join("\n\n").length > transcript.length) {
705
+ return `${transcript}
706
+
707
+ [Summary input reached its configured compaction cap.]`;
708
+ }
709
+ return transcript;
710
+ }
711
+ async function generateSummary(messages, options) {
712
+ const conversationText = serializeMessagesForSummary(messages, {
713
+ maxInputTokens: options.maxInputTokens
714
+ });
715
+ const previousSummary = options.previousSummary ? redactSummaryText(options.previousSummary) : void 0;
716
+ const systemPrompt = options.customPrompt ?? (previousSummary ? UPDATE_SUMMARY_PROMPT : DEFAULT_SUMMARY_PROMPT);
717
+ const prompt = previousSummary ? `Existing handoff summary:
718
+
719
+ ${previousSummary}
720
+
721
+ New conversation material to incorporate:
722
+
723
+ ${conversationText}
724
+
725
+ Return the updated handoff summary only.` : `Conversation material to summarize:
726
+
727
+ ${conversationText}
728
+
729
+ Return the handoff summary only.`;
730
+ const { text } = await generateText({
731
+ model: options.model,
732
+ maxOutputTokens: options.maxTokens ?? 2e3,
733
+ system: systemPrompt,
734
+ prompt
735
+ });
736
+ return redactSummaryText(text);
737
+ }
738
+ async function generateSplitTurnSummary(options) {
739
+ const historyText = serializeMessagesForSummary(options.historyMessages, {
740
+ maxInputTokens: options.maxInputTokens
741
+ });
742
+ const currentTurnPrefixText = serializeMessagesForSummary(
743
+ options.currentTurnPrefixMessages,
744
+ {
745
+ maxInputTokens: options.maxInputTokens
746
+ }
747
+ );
748
+ const previousSummary = options.previousSummary ? redactSummaryText(options.previousSummary) : void 0;
749
+ const systemPrompt = options.customPrompt ?? SPLIT_TURN_SUMMARY_PROMPT;
750
+ const promptParts = [
751
+ previousSummary ? `Existing handoff summary:
752
+
753
+ ${previousSummary}` : void 0,
754
+ options.historyMessages.length > 0 ? `Removed earlier conversation material:
755
+
756
+ ${historyText}` : void 0,
757
+ `Removed early active-turn material:
758
+
759
+ ${currentTurnPrefixText}`,
760
+ `Return a compact handoff summary with sections for prior conversation context and "Earlier In This Turn".`
761
+ ].filter((part) => part !== void 0);
762
+ const { text } = await generateText({
763
+ model: options.model,
764
+ maxOutputTokens: options.maxTokens ?? 2e3,
765
+ system: systemPrompt,
766
+ prompt: promptParts.join("\n\n---\n\n")
767
+ });
768
+ return redactSummaryText(text);
769
+ }
770
+
771
+ // src/context/window/tool-pruning.ts
772
+ var DEFAULT_TOOL_CONTEXT_PRUNE_POLICY = {
773
+ outputThresholdTokens: 500,
774
+ argumentThresholdTokens: 500,
775
+ argumentPreviewChars: 240,
776
+ argumentMaxStringChars: 1800,
777
+ argumentStringHeadChars: 1200,
778
+ argumentStringTailChars: 400,
779
+ argumentArrayHeadItems: 24,
780
+ argumentArrayTailItems: 8,
781
+ argumentObjectMaxKeys: 80,
782
+ argumentMaxDepth: 8
783
+ };
784
+ function positiveIntegerOrDefault(value, fallback) {
785
+ if (typeof value !== "number" || !Number.isFinite(value)) return fallback;
786
+ const normalized = Math.floor(value);
787
+ return normalized > 0 ? normalized : fallback;
788
+ }
789
+ function resolveToolContextPrunePolicy(policy) {
790
+ return {
791
+ outputThresholdTokens: positiveIntegerOrDefault(
792
+ policy?.outputThresholdTokens,
793
+ DEFAULT_TOOL_CONTEXT_PRUNE_POLICY.outputThresholdTokens
794
+ ),
795
+ argumentThresholdTokens: positiveIntegerOrDefault(
796
+ policy?.argumentThresholdTokens,
797
+ DEFAULT_TOOL_CONTEXT_PRUNE_POLICY.argumentThresholdTokens
798
+ ),
799
+ argumentPreviewChars: positiveIntegerOrDefault(
800
+ policy?.argumentPreviewChars,
801
+ DEFAULT_TOOL_CONTEXT_PRUNE_POLICY.argumentPreviewChars
802
+ ),
803
+ argumentMaxStringChars: positiveIntegerOrDefault(
804
+ policy?.argumentMaxStringChars,
805
+ DEFAULT_TOOL_CONTEXT_PRUNE_POLICY.argumentMaxStringChars
806
+ ),
807
+ argumentStringHeadChars: positiveIntegerOrDefault(
808
+ policy?.argumentStringHeadChars,
809
+ DEFAULT_TOOL_CONTEXT_PRUNE_POLICY.argumentStringHeadChars
810
+ ),
811
+ argumentStringTailChars: positiveIntegerOrDefault(
812
+ policy?.argumentStringTailChars,
813
+ DEFAULT_TOOL_CONTEXT_PRUNE_POLICY.argumentStringTailChars
814
+ ),
815
+ argumentArrayHeadItems: positiveIntegerOrDefault(
816
+ policy?.argumentArrayHeadItems,
817
+ DEFAULT_TOOL_CONTEXT_PRUNE_POLICY.argumentArrayHeadItems
818
+ ),
819
+ argumentArrayTailItems: positiveIntegerOrDefault(
820
+ policy?.argumentArrayTailItems,
821
+ DEFAULT_TOOL_CONTEXT_PRUNE_POLICY.argumentArrayTailItems
822
+ ),
823
+ argumentObjectMaxKeys: positiveIntegerOrDefault(
824
+ policy?.argumentObjectMaxKeys,
825
+ DEFAULT_TOOL_CONTEXT_PRUNE_POLICY.argumentObjectMaxKeys
826
+ ),
827
+ argumentMaxDepth: positiveIntegerOrDefault(
828
+ policy?.argumentMaxDepth,
829
+ DEFAULT_TOOL_CONTEXT_PRUNE_POLICY.argumentMaxDepth
830
+ )
831
+ };
832
+ }
833
+ function stringifyToolValue(value) {
834
+ if (typeof value === "string") return value;
835
+ if (value === void 0) return "";
836
+ try {
837
+ return JSON.stringify(value);
838
+ } catch {
839
+ return String(value);
840
+ }
841
+ }
842
+ function compactPreview(value, maxChars) {
843
+ const text = redactSummaryText(
844
+ stringifyToolValue(value).replace(/\s+/g, " ").trim()
845
+ );
846
+ return truncateTextPrefix(text, maxChars, {
847
+ boundary: "word",
848
+ marker: "...",
849
+ separator: ""
850
+ });
851
+ }
852
+ function compactLongArgumentString(value, policy) {
853
+ if (value.length <= policy.argumentMaxStringChars) return value;
854
+ const totalKeptArgumentChars = policy.argumentStringHeadChars + policy.argumentStringTailChars;
855
+ return truncateTextMiddle(value, policy.argumentMaxStringChars, {
856
+ headRatio: policy.argumentStringHeadChars / totalKeptArgumentChars,
857
+ marker: (omitted) => `
858
+ [${omitted} characters omitted by context compaction]
859
+ `
860
+ });
861
+ }
862
+ function compactToolArgumentValue(value, depth, seen, policy) {
863
+ if (typeof value === "string")
864
+ return compactLongArgumentString(value, policy);
865
+ if (value === null || typeof value !== "object") return value;
866
+ if (depth >= policy.argumentMaxDepth) {
867
+ return {
868
+ __contextWindowCompaction: {
869
+ reason: "max-depth",
870
+ preview: compactPreview(value, policy.argumentPreviewChars)
871
+ }
872
+ };
873
+ }
874
+ if (seen.has(value)) {
875
+ return {
876
+ __contextWindowCompaction: {
877
+ reason: "circular-reference"
878
+ }
879
+ };
880
+ }
881
+ seen.add(value);
882
+ if (Array.isArray(value)) {
883
+ const shouldSlice = value.length > policy.argumentArrayHeadItems + policy.argumentArrayTailItems;
884
+ const head = shouldSlice ? value.slice(0, policy.argumentArrayHeadItems) : value;
885
+ const tail = shouldSlice ? value.slice(-policy.argumentArrayTailItems) : [];
886
+ const compacted2 = head.map(
887
+ (item) => compactToolArgumentValue(item, depth + 1, seen, policy)
888
+ );
889
+ if (shouldSlice) {
890
+ compacted2.push({
891
+ __contextWindowCompaction: {
892
+ reason: "array-length",
893
+ omittedItems: value.length - policy.argumentArrayHeadItems - policy.argumentArrayTailItems
894
+ }
895
+ });
896
+ compacted2.push(
897
+ ...tail.map(
898
+ (item) => compactToolArgumentValue(item, depth + 1, seen, policy)
899
+ )
900
+ );
901
+ }
902
+ seen.delete(value);
903
+ return compacted2;
904
+ }
905
+ const entries = Object.entries(value);
906
+ const compacted = {};
907
+ const keptEntries = entries.slice(0, policy.argumentObjectMaxKeys);
908
+ for (const [key, entryValue] of keptEntries) {
909
+ compacted[key] = compactToolArgumentValue(
910
+ entryValue,
911
+ depth + 1,
912
+ seen,
913
+ policy
914
+ );
915
+ }
916
+ if (entries.length > keptEntries.length) {
917
+ compacted.__contextWindowCompaction = {
918
+ reason: "object-size",
919
+ omittedKeys: entries.length - keptEntries.length
920
+ };
921
+ }
922
+ seen.delete(value);
923
+ return compacted;
924
+ }
925
+ function compactToolCallArgs(args, policy, tokenEstimator) {
926
+ const beforeText = stringifyToolValue(args);
927
+ if (estimateTokens(beforeText, tokenEstimator) < policy.argumentThresholdTokens) {
928
+ return { args, compacted: false };
929
+ }
930
+ const compactedArgs = compactToolArgumentValue(
931
+ args,
932
+ 0,
933
+ /* @__PURE__ */ new WeakSet(),
934
+ policy
935
+ );
936
+ const afterText = stringifyToolValue(compactedArgs);
937
+ if (afterText.length < beforeText.length) {
938
+ return { args: compactedArgs, compacted: true };
939
+ }
940
+ return {
941
+ args: {
942
+ __contextWindowCompaction: {
943
+ reason: "argument-size",
944
+ originalEstimatedTokens: estimateTokens(beforeText, tokenEstimator),
945
+ preview: compactPreview(args, policy.argumentMaxStringChars)
946
+ }
947
+ },
948
+ compacted: true
949
+ };
950
+ }
951
+ function collectToolCallArgs(messages) {
952
+ const argsByCallId = /* @__PURE__ */ new Map();
953
+ for (const message of messages) {
954
+ if (message.role !== "assistant" || !message.toolCalls) continue;
955
+ for (const toolCall of message.toolCalls) {
956
+ argsByCallId.set(toolCall.toolCallId, toolCall.args);
957
+ }
958
+ }
959
+ return argsByCallId;
960
+ }
961
+ function summarizeToolOutput(options) {
962
+ const { tool, args, currentTokens, policy, duplicateOf } = options;
963
+ if (duplicateOf) {
964
+ return `[Tool output compacted] ${tool.toolName} produced duplicate output already retained in call ${duplicateOf}. Original output was ${currentTokens} estimated tokens.`;
965
+ }
966
+ const lines = tool.content.split(/\r?\n/).filter((line) => line.trim());
967
+ const lineCount = lines.length;
968
+ const argsPreview = compactPreview(args, policy.argumentPreviewChars);
969
+ const rawFirstLine = lines[0] ?? "";
970
+ const firstLine = rawFirstLine.length > 0 && rawFirstLine.length <= 160 ? compactPreview(rawFirstLine, 160) : "";
971
+ const details = [
972
+ `tool=${tool.toolName}`,
973
+ `call=${tool.toolCallId}`,
974
+ `estimatedTokens=${currentTokens}`,
975
+ `lines=${lineCount}`
976
+ ];
977
+ if (argsPreview) {
978
+ details.push(`args=${argsPreview}`);
979
+ }
980
+ if (firstLine) {
981
+ details.push(`preview=${firstLine}`);
982
+ }
983
+ return `[Tool output compacted] ${details.join("; ")}`;
984
+ }
985
+ function maybeCompactAssistantToolCalls(message, protectedToolSet, policy, tokenEstimator) {
986
+ if (!message.toolCalls || message.toolCalls.length === 0) {
987
+ return { message, compactedCount: 0 };
988
+ }
989
+ let compactedCount = 0;
990
+ const toolCalls = message.toolCalls.map((toolCall) => {
991
+ if (protectedToolSet.has(toolCall.toolName)) return toolCall;
992
+ const result = compactToolCallArgs(toolCall.args, policy, tokenEstimator);
993
+ if (!result.compacted) return toolCall;
994
+ compactedCount++;
995
+ return {
996
+ ...toolCall,
997
+ args: result.args
998
+ };
999
+ });
1000
+ if (compactedCount === 0) return { message, compactedCount };
1001
+ return {
1002
+ message: {
1003
+ ...message,
1004
+ toolCalls
1005
+ },
1006
+ compactedCount
1007
+ };
1008
+ }
1009
+ function pruneToolContextWithReport(messages, protectedTokens = DEFAULT_CONTEXT_LIMITS.protectedTokens, options) {
1010
+ const policy = resolveToolContextPrunePolicy(options?.policy);
1011
+ const tokenEstimator = options?.tokenEstimator;
1012
+ const protectedToolSet = /* @__PURE__ */ new Set([
1013
+ ...PRUNE_PROTECTED_TOOLS,
1014
+ ...options?.protectedTools ?? []
1015
+ ]);
1016
+ const argsByCallId = collectToolCallArgs(messages);
1017
+ const newestFullOutputByContent = /* @__PURE__ */ new Map();
1018
+ const tokensBefore = messages.reduce(
1019
+ (total, message) => total + estimateMessageTokens(message, tokenEstimator),
1020
+ 0
1021
+ );
1022
+ let tokensFromEnd = 0;
1023
+ const tokenPositions = [];
1024
+ for (let i = messages.length - 1; i >= 0; i--) {
1025
+ tokensFromEnd += estimateMessageTokens(messages[i], tokenEstimator);
1026
+ tokenPositions[i] = tokensFromEnd;
1027
+ }
1028
+ for (let i = messages.length - 1; i >= 0; i--) {
1029
+ const message = messages[i];
1030
+ if (message.role !== "tool") continue;
1031
+ if (typeof message.content !== "string" || message.content.length < 200) {
1032
+ continue;
1033
+ }
1034
+ const isRetained = tokenPositions[i] < protectedTokens || Boolean(message.compactedAt) || message.toolName !== void 0 && protectedToolSet.has(message.toolName) || estimateTokens(message.content, tokenEstimator) < policy.outputThresholdTokens;
1035
+ if (!isRetained) continue;
1036
+ if (!newestFullOutputByContent.has(message.content)) {
1037
+ newestFullOutputByContent.set(message.content, message.toolCallId);
1038
+ }
1039
+ }
1040
+ let outputCompactedCount = 0;
1041
+ let argumentCompactedCount = 0;
1042
+ const nextMessages = messages.map((msg, i) => {
1043
+ if (tokenPositions[i] < protectedTokens) return msg;
1044
+ if (!("role" in msg)) return msg;
1045
+ if (msg.role === "assistant") {
1046
+ const result = maybeCompactAssistantToolCalls(
1047
+ msg,
1048
+ protectedToolSet,
1049
+ policy,
1050
+ tokenEstimator
1051
+ );
1052
+ argumentCompactedCount += result.compactedCount;
1053
+ return result.message;
1054
+ }
1055
+ if (msg.role !== "tool") return msg;
1056
+ const toolMsg = msg;
1057
+ if ("compactedAt" in toolMsg && toolMsg.compactedAt) return msg;
1058
+ if (toolMsg.toolName && protectedToolSet.has(toolMsg.toolName)) return msg;
1059
+ const currentTokens = estimateTokens(toolMsg.content, tokenEstimator);
1060
+ if (currentTokens < policy.outputThresholdTokens) return msg;
1061
+ const duplicateOf = newestFullOutputByContent.get(toolMsg.content);
1062
+ const compactedContent = summarizeToolOutput({
1063
+ tool: toolMsg,
1064
+ args: argsByCallId.get(toolMsg.toolCallId),
1065
+ currentTokens,
1066
+ policy,
1067
+ duplicateOf: duplicateOf && duplicateOf !== toolMsg.toolCallId ? duplicateOf : void 0
1068
+ });
1069
+ outputCompactedCount++;
1070
+ return {
1071
+ ...toolMsg,
1072
+ content: compactedContent,
1073
+ result: compactedContent,
1074
+ compactedAt: Date.now()
1075
+ };
1076
+ });
1077
+ const tokensAfter = nextMessages.reduce(
1078
+ (total, message) => total + estimateMessageTokens(message, tokenEstimator),
1079
+ 0
1080
+ );
1081
+ return {
1082
+ messages: nextMessages,
1083
+ report: {
1084
+ outputCompactedCount,
1085
+ argumentCompactedCount,
1086
+ tokensBefore,
1087
+ tokensAfter,
1088
+ tokensRemoved: Math.max(0, tokensBefore - tokensAfter)
1089
+ }
1090
+ };
1091
+ }
1092
+ function pruneToolContext(messages, protectedTokens = DEFAULT_CONTEXT_LIMITS.protectedTokens, options) {
1093
+ return pruneToolContextWithReport(messages, protectedTokens, options).messages;
1094
+ }
1095
+
1096
+ // src/context/window/summary-policy.ts
1097
+ var ContextSummaryModelRequiredError = class extends Error {
1098
+ constructor() {
1099
+ super(
1100
+ "Context compaction removed conversation history, but no summary model is configured."
1101
+ );
1102
+ this.name = "ContextSummaryModelRequiredError";
1103
+ }
1104
+ };
1105
+ function resolveContextSummaryPolicy(policy, activeModel) {
1106
+ const mode = policy?.mode ?? "required";
1107
+ const model = mode === "disabled" ? void 0 : policy?.model ?? activeModel;
1108
+ return {
1109
+ mode,
1110
+ model,
1111
+ prompt: policy?.prompt,
1112
+ maxInputTokens: policy?.maxInputTokens,
1113
+ maxOutputTokens: policy?.maxOutputTokens,
1114
+ targetRatio: policy?.targetRatio
1115
+ };
1116
+ }
1117
+ function canGenerateCompactionSummary(policy) {
1118
+ return policy.mode !== "disabled" && policy.model !== void 0;
1119
+ }
1120
+ function shouldFallbackOnSummaryFailure(options) {
1121
+ return options.force === true || options.policy.mode === "best-effort";
1122
+ }
1123
+
1124
+ // src/context/window/compactor.ts
1125
+ function prepareSummarySource(messages) {
1126
+ let previousSummary;
1127
+ const messagesToSummarize = [];
1128
+ for (const message of messages) {
1129
+ const summary = extractCompactionSummaryText(message);
1130
+ if (summary !== void 0) {
1131
+ previousSummary = summary;
1132
+ continue;
1133
+ }
1134
+ messagesToSummarize.push(message);
1135
+ }
1136
+ return { previousSummary, messagesToSummarize };
1137
+ }
1138
+ async function pruneContext(messages, options = {}) {
1139
+ const limits = options.limits ?? DEFAULT_CONTEXT_LIMITS;
1140
+ let currentMessages = [...messages];
1141
+ let tokensRemoved = 0;
1142
+ let removedCount = 0;
1143
+ let summarized = false;
1144
+ let summary;
1145
+ let summaryOutputTokens;
1146
+ const summaryPolicy = resolveContextSummaryPolicy(options.summary);
1147
+ const tokenEstimator = options.tokenEstimator;
1148
+ const initialTokens = estimateConversationTokens(
1149
+ currentMessages,
1150
+ tokenEstimator
1151
+ );
1152
+ const decision = decideContextCompaction(currentMessages, {
1153
+ limits,
1154
+ force: options.force,
1155
+ canSummarize: canGenerateCompactionSummary(summaryPolicy),
1156
+ inputTokens: initialTokens,
1157
+ trigger: options.trigger,
1158
+ reason: options.reason,
1159
+ tokenEstimator
1160
+ });
1161
+ if (!decision.needed) {
1162
+ return {
1163
+ messages: currentMessages,
1164
+ decision,
1165
+ effectiveness: createCompactionEffectiveness(
1166
+ initialTokens,
1167
+ initialTokens
1168
+ ),
1169
+ removedCount: 0,
1170
+ tokensRemoved: 0,
1171
+ summarized: false,
1172
+ summaryPolicy,
1173
+ cutIndex: 0,
1174
+ cutReason: "no-safe-cut"
1175
+ };
1176
+ }
1177
+ let toolContext;
1178
+ let afterPruneTokens = initialTokens;
1179
+ if (options.toolPruning?.enabled !== false) {
1180
+ const toolContextResult = pruneToolContextWithReport(
1181
+ currentMessages,
1182
+ limits.protectedTokens,
1183
+ {
1184
+ policy: options.toolPruning?.policy,
1185
+ tokenEstimator
1186
+ }
1187
+ );
1188
+ toolContext = toolContextResult.report;
1189
+ const prunedMessages = toolContextResult.messages;
1190
+ afterPruneTokens = estimateConversationTokens(
1191
+ prunedMessages,
1192
+ tokenEstimator
1193
+ );
1194
+ tokensRemoved = Math.max(0, initialTokens - afterPruneTokens);
1195
+ currentMessages = prunedMessages;
1196
+ }
1197
+ if (!isContextOverflowing(afterPruneTokens, limits)) {
1198
+ return {
1199
+ messages: currentMessages,
1200
+ decision,
1201
+ effectiveness: createCompactionEffectiveness(
1202
+ initialTokens,
1203
+ afterPruneTokens
1204
+ ),
1205
+ removedCount: 0,
1206
+ tokensRemoved,
1207
+ summarized: false,
1208
+ summaryPolicy,
1209
+ cutIndex: 0,
1210
+ cutReason: "no-safe-cut",
1211
+ toolContext
1212
+ };
1213
+ }
1214
+ const cutPlan = planCompactionCut(currentMessages, limits.protectedTokens, {
1215
+ allowSplitTurn: summaryPolicy.mode !== "disabled",
1216
+ maxKeptTokens: getUsableTokenLimit(limits),
1217
+ tokenEstimator
1218
+ });
1219
+ if (cutPlan.cutIndex === 0) {
1220
+ return {
1221
+ messages: currentMessages,
1222
+ decision,
1223
+ effectiveness: createCompactionEffectiveness(
1224
+ initialTokens,
1225
+ afterPruneTokens
1226
+ ),
1227
+ removedCount: 0,
1228
+ tokensRemoved,
1229
+ summarized: false,
1230
+ summaryPolicy,
1231
+ cutIndex: 0,
1232
+ cutReason: cutPlan.reason,
1233
+ toolContext
1234
+ };
1235
+ }
1236
+ const removedMessages = cutPlan.removedMessages;
1237
+ const toKeep = cutPlan.keptMessages;
1238
+ const { previousSummary, messagesToSummarize } = prepareSummarySource(
1239
+ cutPlan.historyMessages
1240
+ );
1241
+ const currentTurnPrefixMessages = cutPlan.currentTurnPrefixMessages;
1242
+ removedCount = removedMessages.length;
1243
+ tokensRemoved += cutPlan.tokensRemoved;
1244
+ if (summaryPolicy.mode === "disabled") {
1245
+ currentMessages = toKeep;
1246
+ } else {
1247
+ if (!summaryPolicy.model) {
1248
+ throw new ContextSummaryModelRequiredError();
1249
+ }
1250
+ const summaryInputMessages = [
1251
+ ...messagesToSummarize,
1252
+ ...currentTurnPrefixMessages
1253
+ ];
1254
+ const summaryInputTokens = summaryInputMessages.length > 0 ? estimateConversationTokens(summaryInputMessages, tokenEstimator) : cutPlan.tokensRemoved;
1255
+ summaryOutputTokens = resolveSummaryOutputTokens({
1256
+ inputTokens: summaryInputTokens,
1257
+ limits,
1258
+ summaryMaxOutputTokens: summaryPolicy.maxOutputTokens,
1259
+ summaryTargetRatio: summaryPolicy.targetRatio
1260
+ });
1261
+ if (cutPlan.kind === "split-turn-prefix") {
1262
+ summary = await generateSplitTurnSummary({
1263
+ model: summaryPolicy.model,
1264
+ historyMessages: messagesToSummarize,
1265
+ currentTurnPrefixMessages,
1266
+ maxInputTokens: summaryPolicy.maxInputTokens,
1267
+ maxTokens: summaryOutputTokens,
1268
+ customPrompt: summaryPolicy.prompt,
1269
+ previousSummary
1270
+ });
1271
+ summarized = true;
1272
+ } else if (messagesToSummarize.length > 0 || previousSummary !== void 0) {
1273
+ summary = await generateSummary(messagesToSummarize, {
1274
+ model: summaryPolicy.model,
1275
+ maxInputTokens: summaryPolicy.maxInputTokens,
1276
+ maxTokens: summaryOutputTokens,
1277
+ customPrompt: summaryPolicy.prompt,
1278
+ previousSummary
1279
+ });
1280
+ summarized = true;
1281
+ }
1282
+ const summaryMessage = {
1283
+ id: crypto.randomUUID(),
1284
+ role: "system",
1285
+ content: createCompactionSummaryContent(
1286
+ summary ?? previousSummary ?? "Earlier conversation context was compacted."
1287
+ ),
1288
+ createdAt: /* @__PURE__ */ new Date()
1289
+ };
1290
+ currentMessages = [summaryMessage, ...toKeep];
1291
+ }
1292
+ return {
1293
+ messages: currentMessages,
1294
+ decision,
1295
+ effectiveness: createCompactionEffectiveness(
1296
+ initialTokens,
1297
+ estimateConversationTokens(currentMessages, tokenEstimator)
1298
+ ),
1299
+ removedCount,
1300
+ tokensRemoved,
1301
+ summarized,
1302
+ summary,
1303
+ summaryPolicy,
1304
+ removedMessages,
1305
+ keptMessages: toKeep,
1306
+ summaryOutputTokens,
1307
+ ...previousSummary !== void 0 ? { previousSummary } : {},
1308
+ cutIndex: cutPlan.cutIndex,
1309
+ cutReason: cutPlan.reason,
1310
+ toolContext
1311
+ };
1312
+ }
1313
+
1314
+ // src/context/window/manager.ts
1315
+ var ContextWindowManager = class {
1316
+ limits;
1317
+ activeModel;
1318
+ summaryPolicy;
1319
+ toolPruning;
1320
+ tokenEstimator;
1321
+ constructor(options) {
1322
+ this.limits = { ...DEFAULT_CONTEXT_LIMITS, ...options?.limits };
1323
+ this.activeModel = options?.model;
1324
+ this.summaryPolicy = options?.summary;
1325
+ this.toolPruning = options?.toolPruning;
1326
+ this.tokenEstimator = options?.tokenEstimator;
1327
+ }
1328
+ /** Get a copy of the current context limits. */
1329
+ getLimits() {
1330
+ return { ...this.limits };
1331
+ }
1332
+ /** Update context limits (e.g. when switching models). */
1333
+ setLimits(limits) {
1334
+ this.limits = { ...this.limits, ...limits };
1335
+ }
1336
+ /** Set the active agent model used for summaries unless overridden. */
1337
+ setModel(model) {
1338
+ this.activeModel = model;
1339
+ }
1340
+ /** Set the summary policy used when conversation history must be cut. */
1341
+ setSummaryPolicy(policy) {
1342
+ this.summaryPolicy = policy;
1343
+ }
1344
+ /** Set deterministic tool-context pruning behavior. */
1345
+ setToolPruning(options) {
1346
+ this.toolPruning = options;
1347
+ }
1348
+ /** Get deterministic tool-context pruning behavior. */
1349
+ getToolPruning() {
1350
+ return this.toolPruning ? { ...this.toolPruning } : void 0;
1351
+ }
1352
+ /** Set the token estimator used for context-window planning. */
1353
+ setTokenEstimator(estimator) {
1354
+ this.tokenEstimator = estimator;
1355
+ }
1356
+ /** Get the token estimator used for context-window planning. */
1357
+ getTokenEstimator() {
1358
+ return this.tokenEstimator;
1359
+ }
1360
+ /** Resolve summary policy against the active agent model. */
1361
+ getSummaryPolicy() {
1362
+ return resolveContextSummaryPolicy(this.summaryPolicy, this.activeModel);
1363
+ }
1364
+ /** Estimate total tokens for a message array. */
1365
+ estimateTokens(messages) {
1366
+ return estimateConversationTokens(messages, this.tokenEstimator);
1367
+ }
1368
+ /** Check whether the context is overflowing. */
1369
+ isOverflowing(messages) {
1370
+ const tokens = this.estimateTokens(messages);
1371
+ return isContextOverflowing(tokens, this.limits);
1372
+ }
1373
+ /** Check whether pruning should be triggered. */
1374
+ shouldPrune(messages) {
1375
+ const tokens = this.estimateTokens(messages);
1376
+ return shouldPruneContext(tokens, this.limits);
1377
+ }
1378
+ /** Explain whether context compaction should run. */
1379
+ decide(messages, options) {
1380
+ const summaryPolicy = this.getSummaryPolicy();
1381
+ return decideContextCompaction(messages, {
1382
+ limits: this.limits,
1383
+ force: options?.force,
1384
+ inputTokens: options?.inputTokens,
1385
+ trigger: options?.trigger,
1386
+ reason: options?.reason,
1387
+ canSummarize: canGenerateCompactionSummary(summaryPolicy),
1388
+ tokenEstimator: this.tokenEstimator
1389
+ });
1390
+ }
1391
+ /** Prune context to fit within limits. */
1392
+ async prune(messages, options) {
1393
+ return pruneContext(messages, {
1394
+ limits: this.limits,
1395
+ summary: this.getSummaryPolicy(),
1396
+ force: options?.force,
1397
+ trigger: options?.trigger,
1398
+ reason: options?.reason,
1399
+ toolPruning: options?.toolPruning ?? this.toolPruning,
1400
+ tokenEstimator: this.tokenEstimator
1401
+ });
1402
+ }
1403
+ /**
1404
+ * Get a snapshot of token statistics.
1405
+ *
1406
+ * Useful for dashboards, logging, or deciding whether to prune.
1407
+ */
1408
+ getStats(messages) {
1409
+ const tokens = this.estimateTokens(messages);
1410
+ const effectiveContextWindow = getEffectiveContextWindow(this.limits);
1411
+ const usableLimit = getUsableTokenLimit(this.limits);
1412
+ const autoCompactLimit = getAutoCompactTokenLimit(this.limits);
1413
+ const limit = autoCompactLimit;
1414
+ return {
1415
+ tokens,
1416
+ limit,
1417
+ effectiveContextWindow,
1418
+ usableLimit,
1419
+ autoCompactLimit,
1420
+ available: Math.max(0, usableLimit - tokens),
1421
+ utilizationPercent: Math.round(tokens / limit * 100),
1422
+ isOverflowing: isContextOverflowing(tokens, this.limits),
1423
+ shouldPrune: shouldPruneContext(tokens, this.limits)
1424
+ };
1425
+ }
1426
+ };
1427
+
1428
+ export {
1429
+ DEFAULT_CONTEXT_LIMITS,
1430
+ DEFAULT_SUMMARY_MAX_OUTPUT_TOKENS,
1431
+ DEFAULT_SUMMARY_MAX_INPUT_TOKENS,
1432
+ DEFAULT_COMPACTION_EFFECTIVE_MIN_SAVINGS_RATIO,
1433
+ getUsableTokenLimit,
1434
+ getEffectiveContextWindow,
1435
+ getAutoCompactTokenLimit,
1436
+ isContextOverflowing,
1437
+ shouldPruneContext,
1438
+ createCompactionEffectiveness,
1439
+ resolveSummaryOutputTokens,
1440
+ planCompactionCut,
1441
+ decideContextCompaction,
1442
+ PRUNE_PROTECTED_TOOLS,
1443
+ createCompactionSummaryContent,
1444
+ extractCompactionSummaryText,
1445
+ redactSummaryText,
1446
+ serializeMessagesForSummary,
1447
+ generateSummary,
1448
+ generateSplitTurnSummary,
1449
+ DEFAULT_TOOL_CONTEXT_PRUNE_POLICY,
1450
+ pruneToolContextWithReport,
1451
+ pruneToolContext,
1452
+ ContextSummaryModelRequiredError,
1453
+ resolveContextSummaryPolicy,
1454
+ canGenerateCompactionSummary,
1455
+ shouldFallbackOnSummaryFailure,
1456
+ pruneContext,
1457
+ ContextWindowManager
1458
+ };