@cuylabs/agent-core 4.8.1 → 4.10.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 (667) 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 +29 -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 +29 -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 +170 -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 +53 -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 +39 -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 +17 -0
  75. package/dist/agent/turn-context/compaction/memory.d.ts.map +1 -0
  76. package/dist/agent/turn-context/compaction/results.d.ts +19 -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 +24 -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 +199 -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-AAGKWUXR.js +539 -0
  98. package/dist/chunk-AHDCR7SX.js +83 -0
  99. package/dist/{chunk-CSR75JVC.js → chunk-ASXF5AC6.js} +1 -1
  100. package/dist/{chunk-2TTOLHBT.js → chunk-CFBSQLP5.js} +1 -1
  101. package/dist/{chunk-GJFP5L2V.js → chunk-CNM6OROH.js} +15 -3
  102. package/dist/chunk-E66PKKDL.js +772 -0
  103. package/dist/{chunk-HSUPTXNV.js → chunk-EBVSPHXA.js} +13 -10
  104. package/dist/chunk-EEAGM5MS.js +257 -0
  105. package/dist/chunk-IQA64CAO.js +84 -0
  106. package/dist/chunk-JFH6HBUG.js +227 -0
  107. package/dist/{chunk-MWPU2EVV.js → chunk-JUIL2NJC.js} +4 -81
  108. package/dist/{chunk-NS7D7JJU.js → chunk-K453AFTL.js} +35 -16
  109. package/dist/chunk-LX4AHGI3.js +960 -0
  110. package/dist/chunk-MJRZ2ZRI.js +498 -0
  111. package/dist/chunk-NMJNN6LS.js +1155 -0
  112. package/dist/{chunk-UMIVJDEJ.js → chunk-SAWRDGBE.js} +30 -7
  113. package/dist/{chunk-GEBFHREI.js → chunk-TU5KDFWI.js} +30 -5
  114. package/dist/{chunk-QJV5XPPS.js → chunk-UEEHZ4QH.js} +1 -1
  115. package/dist/chunk-UG5PVNZV.js +53 -0
  116. package/dist/{chunk-BGG2HVIR.js → chunk-V4MIDL5B.js} +9 -0
  117. package/dist/{chunk-BJC46FIF.js → chunk-V4YQ6MBK.js} +2 -2
  118. package/dist/{chunk-H3GRHFFG.js → chunk-VMGZKIFT.js} +30 -9
  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 +60 -0
  125. package/dist/context/assembly/types.d.ts.map +1 -0
  126. package/dist/context/config.d.ts +11 -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 +10 -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 +90 -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 +108 -0
  142. package/dist/context/window/budget.d.ts.map +1 -0
  143. package/dist/context/window/compactor.d.ts +74 -0
  144. package/dist/context/window/compactor.d.ts.map +1 -0
  145. package/dist/context/window/cut-planner.d.ts +64 -0
  146. package/dist/context/window/cut-planner.d.ts.map +1 -0
  147. package/dist/context/window/decision.d.ts +41 -0
  148. package/dist/context/window/decision.d.ts.map +1 -0
  149. package/dist/context/window/estimation.d.ts +45 -0
  150. package/dist/context/window/estimation.d.ts.map +1 -0
  151. package/dist/context/window/index.d.ts +26 -0
  152. package/dist/context/window/index.d.ts.map +1 -0
  153. package/dist/context/window/manager.d.ts +80 -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 +56 -0
  158. package/dist/context/window/summary.d.ts.map +1 -0
  159. package/dist/context/window/tool-pruning.d.ts +62 -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 +2482 -1846
  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 +232 -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 +24 -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 +100 -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 +371 -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/skill/discovery/constants.d.ts +6 -0
  484. package/dist/skill/discovery/constants.d.ts.map +1 -0
  485. package/dist/skill/discovery/dedupe.d.ts +3 -0
  486. package/dist/skill/discovery/dedupe.d.ts.map +1 -0
  487. package/dist/skill/discovery/discover.d.ts +3 -0
  488. package/dist/skill/discovery/discover.d.ts.map +1 -0
  489. package/dist/skill/discovery/fs.d.ts +4 -0
  490. package/dist/skill/discovery/fs.d.ts.map +1 -0
  491. package/dist/skill/discovery/index.d.ts +6 -0
  492. package/dist/skill/discovery/index.d.ts.map +1 -0
  493. package/dist/skill/discovery/scan.d.ts +3 -0
  494. package/dist/skill/discovery/scan.d.ts.map +1 -0
  495. package/dist/skill/discovery/types.d.ts +15 -0
  496. package/dist/skill/discovery/types.d.ts.map +1 -0
  497. package/dist/skill/index.d.ts +67 -89
  498. package/dist/skill/index.d.ts.map +1 -0
  499. package/dist/skill/index.js +2 -2
  500. package/dist/skill/loader/constants.d.ts +5 -0
  501. package/dist/skill/loader/constants.d.ts.map +1 -0
  502. package/dist/skill/loader/frontmatter.d.ts +5 -0
  503. package/dist/skill/loader/frontmatter.d.ts.map +1 -0
  504. package/dist/skill/loader/index.d.ts +8 -0
  505. package/dist/skill/loader/index.d.ts.map +1 -0
  506. package/dist/skill/loader/metadata.d.ts +3 -0
  507. package/dist/skill/loader/metadata.d.ts.map +1 -0
  508. package/dist/skill/loader/resources.d.ts +5 -0
  509. package/dist/skill/loader/resources.d.ts.map +1 -0
  510. package/dist/skill/registry.d.ts +177 -0
  511. package/dist/skill/registry.d.ts.map +1 -0
  512. package/dist/skill/tools.d.ts +77 -0
  513. package/dist/skill/tools.d.ts.map +1 -0
  514. package/dist/skill/types.d.ts +291 -0
  515. package/dist/skill/types.d.ts.map +1 -0
  516. package/dist/storage/file/helpers.d.ts +16 -0
  517. package/dist/storage/file/helpers.d.ts.map +1 -0
  518. package/dist/storage/file/index.d.ts +6 -0
  519. package/dist/storage/file/index.d.ts.map +1 -0
  520. package/dist/storage/file/storage.d.ts +29 -0
  521. package/dist/storage/file/storage.d.ts.map +1 -0
  522. package/dist/storage/file/types.d.ts +6 -0
  523. package/dist/storage/file/types.d.ts.map +1 -0
  524. package/dist/storage/index.d.ts +11 -188
  525. package/dist/storage/index.d.ts.map +1 -0
  526. package/dist/storage/index.js +2 -1
  527. package/dist/storage/lock.d.ts +18 -0
  528. package/dist/storage/lock.d.ts.map +1 -0
  529. package/dist/storage/manager/default.d.ts +11 -0
  530. package/dist/storage/manager/default.d.ts.map +1 -0
  531. package/dist/storage/manager/index.d.ts +12 -0
  532. package/dist/storage/manager/index.d.ts.map +1 -0
  533. package/dist/storage/manager/session-manager.d.ts +57 -0
  534. package/dist/storage/manager/session-manager.d.ts.map +1 -0
  535. package/dist/storage/manager/types.d.ts +42 -0
  536. package/dist/storage/manager/types.d.ts.map +1 -0
  537. package/dist/storage/memory.d.ts +22 -0
  538. package/dist/storage/memory.d.ts.map +1 -0
  539. package/dist/storage/paths.d.ts +37 -0
  540. package/dist/storage/paths.d.ts.map +1 -0
  541. package/dist/storage/types.d.ts +205 -0
  542. package/dist/storage/types.d.ts.map +1 -0
  543. package/dist/storage/utils.d.ts +77 -0
  544. package/dist/storage/utils.d.ts.map +1 -0
  545. package/dist/subagents/index.d.ts +8 -179
  546. package/dist/subagents/index.d.ts.map +1 -0
  547. package/dist/subagents/index.js +5 -4
  548. package/dist/subagents/installation.d.ts +23 -0
  549. package/dist/subagents/installation.d.ts.map +1 -0
  550. package/dist/subagents/results.d.ts +15 -0
  551. package/dist/subagents/results.d.ts.map +1 -0
  552. package/dist/subagents/roles/discovery.d.ts +38 -0
  553. package/dist/subagents/roles/discovery.d.ts.map +1 -0
  554. package/dist/subagents/roles/index.d.ts +5 -0
  555. package/dist/subagents/roles/index.d.ts.map +1 -0
  556. package/dist/subagents/roles/markdown-profile.d.ts +61 -0
  557. package/dist/subagents/roles/markdown-profile.d.ts.map +1 -0
  558. package/dist/subagents/tool-factories.d.ts +11 -0
  559. package/dist/subagents/tool-factories.d.ts.map +1 -0
  560. package/dist/subagents/tools.d.ts +13 -0
  561. package/dist/subagents/tools.d.ts.map +1 -0
  562. package/dist/subagents/types.d.ts +21 -0
  563. package/dist/subagents/types.d.ts.map +1 -0
  564. package/dist/team/coordinator/coordinator.d.ts +342 -0
  565. package/dist/team/coordinator/coordinator.d.ts.map +1 -0
  566. package/dist/team/coordinator/inbox.d.ts +99 -0
  567. package/dist/team/coordinator/inbox.d.ts.map +1 -0
  568. package/dist/team/coordinator/index.d.ts +19 -0
  569. package/dist/team/coordinator/index.d.ts.map +1 -0
  570. package/dist/team/coordinator/planning.d.ts +33 -0
  571. package/dist/team/coordinator/planning.d.ts.map +1 -0
  572. package/dist/team/coordinator/policy.d.ts +31 -0
  573. package/dist/team/coordinator/policy.d.ts.map +1 -0
  574. package/dist/team/coordinator/round-engine.d.ts +25 -0
  575. package/dist/team/coordinator/round-engine.d.ts.map +1 -0
  576. package/dist/team/coordinator/synthesis.d.ts +20 -0
  577. package/dist/team/coordinator/synthesis.d.ts.map +1 -0
  578. package/dist/team/coordinator/turn.d.ts +107 -0
  579. package/dist/team/coordinator/turn.d.ts.map +1 -0
  580. package/dist/team/coordinator/types.d.ts +344 -0
  581. package/dist/team/coordinator/types.d.ts.map +1 -0
  582. package/dist/team/events.d.ts +148 -0
  583. package/dist/team/events.d.ts.map +1 -0
  584. package/dist/team/execution.d.ts +51 -0
  585. package/dist/team/execution.d.ts.map +1 -0
  586. package/dist/team/index.d.ts +23 -545
  587. package/dist/team/index.d.ts.map +1 -0
  588. package/dist/team/index.js +2 -2
  589. package/dist/team/mailbox.d.ts +91 -0
  590. package/dist/team/mailbox.d.ts.map +1 -0
  591. package/dist/team/notifications.d.ts +23 -0
  592. package/dist/team/notifications.d.ts.map +1 -0
  593. package/dist/team/permissions.d.ts +88 -0
  594. package/dist/team/permissions.d.ts.map +1 -0
  595. package/dist/team/shutdown.d.ts +38 -0
  596. package/dist/team/shutdown.d.ts.map +1 -0
  597. package/dist/team/task-board.d.ts +161 -0
  598. package/dist/team/task-board.d.ts.map +1 -0
  599. package/dist/team/types.d.ts +233 -0
  600. package/dist/team/types.d.ts.map +1 -0
  601. package/dist/team/work-loop.d.ts +30 -0
  602. package/dist/team/work-loop.d.ts.map +1 -0
  603. package/dist/tool/executor.d.ts +59 -0
  604. package/dist/tool/executor.d.ts.map +1 -0
  605. package/dist/tool/host/index.d.ts +7 -38
  606. package/dist/tool/host/index.d.ts.map +1 -0
  607. package/dist/tool/host/local.d.ts +15 -0
  608. package/dist/tool/host/local.d.ts.map +1 -0
  609. package/dist/tool/host/registry.d.ts +17 -0
  610. package/dist/tool/host/registry.d.ts.map +1 -0
  611. package/dist/{types-C_LCeYNg.d.ts → tool/host/types.d.ts} +6 -7
  612. package/dist/tool/host/types.d.ts.map +1 -0
  613. package/dist/tool/index.d.ts +21 -285
  614. package/dist/tool/index.d.ts.map +1 -0
  615. package/dist/tool/index.js +4 -3
  616. package/dist/tool/registry.d.ts +130 -0
  617. package/dist/tool/registry.d.ts.map +1 -0
  618. package/dist/tool/replay.d.ts +11 -0
  619. package/dist/tool/replay.d.ts.map +1 -0
  620. package/dist/tool/tool-search.d.ts +50 -0
  621. package/dist/tool/tool-search.d.ts.map +1 -0
  622. package/dist/tool/tool.d.ts +308 -0
  623. package/dist/tool/tool.d.ts.map +1 -0
  624. package/dist/tool/truncation.d.ts +34 -0
  625. package/dist/tool/truncation.d.ts.map +1 -0
  626. package/dist/tool/turn-tools.d.ts +71 -0
  627. package/dist/tool/turn-tools.d.ts.map +1 -0
  628. package/dist/tracking/file-tracking.d.ts +25 -0
  629. package/dist/tracking/file-tracking.d.ts.map +1 -0
  630. package/dist/tracking/index.d.ts +9 -0
  631. package/dist/tracking/index.d.ts.map +1 -0
  632. package/dist/tracking/turn-tracker/diff.d.ts +11 -0
  633. package/dist/tracking/turn-tracker/diff.d.ts.map +1 -0
  634. package/dist/tracking/turn-tracker/index.d.ts +11 -0
  635. package/dist/tracking/turn-tracker/index.d.ts.map +1 -0
  636. package/dist/tracking/turn-tracker/tracker.d.ts +31 -0
  637. package/dist/tracking/turn-tracker/tracker.d.ts.map +1 -0
  638. package/dist/tracking/turn-tracker/types.d.ts +66 -0
  639. package/dist/tracking/turn-tracker/types.d.ts.map +1 -0
  640. package/dist/types/compaction.d.ts +142 -0
  641. package/dist/types/compaction.d.ts.map +1 -0
  642. package/dist/types/doom-loop.d.ts +25 -0
  643. package/dist/types/doom-loop.d.ts.map +1 -0
  644. package/dist/types/events.d.ts +194 -0
  645. package/dist/types/events.d.ts.map +1 -0
  646. package/dist/types/index.d.ts +17 -0
  647. package/dist/types/index.d.ts.map +1 -0
  648. package/dist/types/messages.d.ts +119 -0
  649. package/dist/types/messages.d.ts.map +1 -0
  650. package/dist/types/stream.d.ts +172 -0
  651. package/dist/types/stream.d.ts.map +1 -0
  652. package/dist/types/tool.d.ts +309 -0
  653. package/dist/types/tool.d.ts.map +1 -0
  654. package/dist/types/turn-source.d.ts +36 -0
  655. package/dist/types/turn-source.d.ts.map +1 -0
  656. package/dist/utils/sleep.d.ts +7 -0
  657. package/dist/utils/sleep.d.ts.map +1 -0
  658. package/package.json +45 -8
  659. package/dist/chunk-CJI7PVS2.js +0 -58
  660. package/dist/chunk-V6ETEYST.js +0 -2091
  661. package/dist/index-BCqEGzBj.d.ts +0 -251
  662. package/dist/instance-Bg61WSyz.d.ts +0 -6004
  663. package/dist/llm-error-D93FNNLY.d.ts +0 -32
  664. package/dist/turn-tools/index.d.ts +0 -12
  665. package/dist/turn-tools/index.js +0 -1
  666. package/dist/{chunk-O2WCYSXQ.js → chunk-3NBTQHVV.js} +0 -0
  667. package/dist/{chunk-Q742PSH3.js → chunk-MJML3A2F.js} +36 -36
package/dist/index.js CHANGED
@@ -1,3 +1,8 @@
1
+ import {
2
+ createSkillResourceTool,
3
+ createSkillTool,
4
+ createSkillTools
5
+ } from "./chunk-ASXF5AC6.js";
1
6
  import {
2
7
  DEFAULT_SUBAGENT_CONCURRENCY,
3
8
  DEFAULT_SUBAGENT_DEPTH,
@@ -34,7 +39,7 @@ import {
34
39
  parseSubAgentRoleFrontmatter,
35
40
  parseSubAgentToolSpec,
36
41
  toSubAgentRole
37
- } from "./chunk-BJC46FIF.js";
42
+ } from "./chunk-V4YQ6MBK.js";
38
43
  import {
39
44
  InMemoryMailboxStore,
40
45
  InMemoryTaskBoardStore,
@@ -53,18 +58,32 @@ import {
53
58
  formatCoordinatorTaskNotifications,
54
59
  formatCoordinatorWorkerReports,
55
60
  teamPermissionPolicy
56
- } from "./chunk-QJV5XPPS.js";
61
+ } from "./chunk-UEEHZ4QH.js";
57
62
  import {
58
63
  ToolRegistry,
59
64
  createToolSearchTool,
60
65
  defaultRegistry
61
- } from "./chunk-KYLPMBHD.js";
62
- import "./chunk-O2WCYSXQ.js";
66
+ } from "./chunk-336EDIBL.js";
63
67
  import {
64
68
  ToolHostRegistry,
65
69
  defaultToolHostRegistry,
66
70
  localHost
67
71
  } from "./chunk-X4VN4GIJ.js";
72
+ import {
73
+ createMemoryMiddleware,
74
+ formatMemoryContextFragment,
75
+ normalizeMemoryRecords,
76
+ resolveAgentMemoryConfig,
77
+ resolveAgentMemoryTurnConfig
78
+ } from "./chunk-EEAGM5MS.js";
79
+ import {
80
+ MiddlewareRunner,
81
+ approvalMiddleware,
82
+ createTelemetryConfig,
83
+ isApprovalMiddleware,
84
+ otelMiddleware,
85
+ promptCacheMiddleware
86
+ } from "./chunk-TU5KDFWI.js";
68
87
  import {
69
88
  LayeredSettings,
70
89
  NullSettings,
@@ -101,6 +120,7 @@ import {
101
120
  DEFAULT_INSTRUCTION_PATTERNS,
102
121
  DEFAULT_MAX_DEPTH,
103
122
  DEFAULT_MAX_FILE_SIZE,
123
+ DEFAULT_SYSTEM_PROMPT,
104
124
  PRIORITY_BASE,
105
125
  PRIORITY_CUSTOM,
106
126
  PRIORITY_ENVIRONMENT,
@@ -118,13 +138,7 @@ import {
118
138
  getTemplate,
119
139
  loadGlobalInstructions,
120
140
  summarizeEnvironment
121
- } from "./chunk-BGG2HVIR.js";
122
- import "./chunk-VOUEJSW6.js";
123
- import {
124
- createSkillResourceTool,
125
- createSkillTool,
126
- createSkillTools
127
- } from "./chunk-CSR75JVC.js";
141
+ } from "./chunk-V4MIDL5B.js";
128
142
  import {
129
143
  DEFAULT_EXTERNAL_DIRS,
130
144
  DEFAULT_MAX_SCAN_DEPTH,
@@ -140,6 +154,10 @@ import {
140
154
  loadSkillMetadata,
141
155
  parseFrontmatter
142
156
  } from "./chunk-I7EJGKUP.js";
157
+ import "./chunk-VOUEJSW6.js";
158
+ import {
159
+ assembleModelContext
160
+ } from "./chunk-IQA64CAO.js";
143
161
  import {
144
162
  createCompositeDispatchTaskExecutor,
145
163
  createDispatchExternalTaskControl,
@@ -161,17 +179,7 @@ import {
161
179
  ensureSessionLoaded,
162
180
  getVisibleSessionMessages,
163
181
  repairOrphanedToolCalls
164
- } from "./chunk-HSUPTXNV.js";
165
- import {
166
- sleep
167
- } from "./chunk-SZ2XBPTW.js";
168
- import {
169
- MAX_BYTES,
170
- MAX_LINES,
171
- Tool,
172
- normalizeToolReplayPolicy,
173
- truncateOutput
174
- } from "./chunk-Q742PSH3.js";
182
+ } from "./chunk-EBVSPHXA.js";
175
183
  import {
176
184
  FileStorage,
177
185
  LocalSessionTurnLock,
@@ -199,54 +207,117 @@ import {
199
207
  serializeMessage,
200
208
  toJSONL,
201
209
  toJSONLBatch
202
- } from "./chunk-H3GRHFFG.js";
210
+ } from "./chunk-VMGZKIFT.js";
211
+ import {
212
+ sleep
213
+ } from "./chunk-SZ2XBPTW.js";
214
+ import {
215
+ MAX_BYTES,
216
+ MAX_LINES,
217
+ Tool,
218
+ normalizeToolReplayPolicy,
219
+ truncateOutput
220
+ } from "./chunk-MJML3A2F.js";
221
+ import "./chunk-3NBTQHVV.js";
203
222
  import {
204
223
  createEventBus
205
- } from "./chunk-2TTOLHBT.js";
224
+ } from "./chunk-CFBSQLP5.js";
225
+ import {
226
+ LocalSignal
227
+ } from "./chunk-UG5PVNZV.js";
228
+ import {
229
+ createAgentTaskRunner,
230
+ defaultAgentTaskCheckpointStrategy
231
+ } from "./chunk-JFH6HBUG.js";
206
232
  import {
207
233
  AgentTurnEngine,
208
- ContextManager,
209
234
  ContextOverflowError,
210
- DEFAULT_CONTEXT_LIMITS,
211
235
  DoomLoopError,
212
- PRUNE_PROTECTED_TOOLS,
213
- accumulateUsage,
214
- advanceAgentTurnState,
236
+ commitOutput,
237
+ commitStep,
238
+ createAgentTurnEngine,
239
+ createAgentTurnStepCommitBatch,
240
+ prepareModelStep,
241
+ processStepStream,
242
+ runModelStep,
243
+ runToolBatch
244
+ } from "./chunk-LX4AHGI3.js";
245
+ import {
215
246
  applyAgentWorkflowCommitResult,
247
+ applyAgentWorkflowContextCompactionResult,
216
248
  applyAgentWorkflowModelStepResult,
217
249
  applyAgentWorkflowToolBatchResult,
218
250
  applyAgentWorkflowToolCallResult,
219
251
  applyWorkflowInterventions,
220
252
  cloneAgentWorkflowTurnState,
221
- commitOutput,
222
- commitStep,
223
- createAgentTaskRunner,
224
- createAgentTurnEngine,
225
- createAgentTurnState,
226
- createAgentTurnStepCommitBatch,
227
253
  createAgentWorkflowTurnState,
228
- defaultAgentTaskCheckpointStrategy,
229
254
  drainWorkflowInterventions,
230
- estimateConversationTokens,
231
- estimateMessageTokens,
232
- estimateTokens,
233
- failAgentTurnState,
234
255
  failAgentWorkflowTurnState,
235
- findCutPoint,
236
- getUsableTokenLimit,
237
256
  planNextAgentWorkflowOperation,
238
- prepareModelStep,
239
- processStepStream,
240
257
  queueWorkflowFollowUps,
241
258
  recordAgentWorkflowReplayDecision,
242
259
  restoreAgentWorkflowMessage,
243
260
  restoreAgentWorkflowMessages,
244
- runModelStep,
245
- runToolBatch,
246
261
  snapshotAgentWorkflowMessage,
247
262
  snapshotAgentWorkflowMessages
248
- } from "./chunk-V6ETEYST.js";
263
+ } from "./chunk-MJRZ2ZRI.js";
264
+ import {
265
+ AgentTurnStateConflictError,
266
+ accumulateUsage,
267
+ advanceAgentTurnState,
268
+ createAgentTurnState,
269
+ failAgentTurnState,
270
+ getCurrentAgentTurnStepRecord,
271
+ mergeAgentTurnStateProgress
272
+ } from "./chunk-E66PKKDL.js";
273
+ import {
274
+ ContextSummaryModelRequiredError,
275
+ ContextWindowManager,
276
+ DEFAULT_COMPACTION_EFFECTIVE_MIN_SAVINGS_RATIO,
277
+ DEFAULT_CONTEXT_LIMITS,
278
+ DEFAULT_SUMMARY_MAX_INPUT_TOKENS,
279
+ DEFAULT_SUMMARY_MAX_OUTPUT_TOKENS,
280
+ PRUNE_PROTECTED_TOOLS,
281
+ canGenerateCompactionSummary,
282
+ createCompactionEffectiveness,
283
+ createCompactionSummaryContent,
284
+ decideContextCompaction,
285
+ extractCompactionSummaryText,
286
+ generateSplitTurnSummary,
287
+ generateSummary,
288
+ getUsableTokenLimit,
289
+ isContextOverflowing,
290
+ planCompactionCut,
291
+ pruneContext,
292
+ pruneToolContext,
293
+ pruneToolContextWithReport,
294
+ redactSummaryText,
295
+ resolveContextSummaryPolicy,
296
+ resolveSummaryOutputTokens,
297
+ serializeMessagesForSummary,
298
+ shouldFallbackOnSummaryFailure,
299
+ shouldPruneContext
300
+ } from "./chunk-NMJNN6LS.js";
301
+ import {
302
+ AGENT_CONTEXT_FRAGMENT_CLOSE,
303
+ AGENT_CONTEXT_FRAGMENT_OPEN,
304
+ AGENT_CONTEXT_FRAGMENT_TAG,
305
+ applyAgentContextFragments,
306
+ applyAgentContextFragmentsWithReport,
307
+ createAgentContextFragmentMessage,
308
+ estimateConversationTokens,
309
+ estimateMessageTokens,
310
+ estimateTokens,
311
+ getAgentContextFragmentMetadata,
312
+ isAgentContextFragmentMessage,
313
+ isRenderedAgentContextFragment,
314
+ normalizeAgentContextFragment,
315
+ parseRenderedAgentContextFragment,
316
+ renderAgentContextFragment
317
+ } from "./chunk-AAGKWUXR.js";
249
318
  import {
319
+ DEFAULT_MAX_OUTPUT_TOKENS,
320
+ DEFAULT_MAX_STEPS,
250
321
  DEFAULT_RETRY_CONFIG,
251
322
  Inference,
252
323
  buildModelCallContext,
@@ -260,17 +331,7 @@ import {
260
331
  streamOnce,
261
332
  streamStep,
262
333
  withRetry
263
- } from "./chunk-NS7D7JJU.js";
264
- import {
265
- currentScope,
266
- executeAgentToolCall,
267
- extractFilePathsFromArgs,
268
- restoreScope,
269
- shouldCaptureBaseline,
270
- snapshotScope,
271
- streamWithinScope,
272
- withinScope
273
- } from "./chunk-MWPU2EVV.js";
334
+ } from "./chunk-K453AFTL.js";
274
335
  import {
275
336
  LLMError,
276
337
  getErrorCategory,
@@ -279,6 +340,21 @@ import {
279
340
  isRetryableCategory,
280
341
  parseRetryDelay
281
342
  } from "./chunk-STDJYXYK.js";
343
+ import {
344
+ executeAgentToolCall,
345
+ extractFilePathsFromArgs,
346
+ shouldCaptureBaseline
347
+ } from "./chunk-JUIL2NJC.js";
348
+ import {
349
+ currentScope,
350
+ restoreScope,
351
+ snapshotScope,
352
+ streamWithinScope,
353
+ withinScope
354
+ } from "./chunk-AHDCR7SX.js";
355
+ import {
356
+ isBlockedModelCall
357
+ } from "./chunk-W6LWIMIX.js";
282
358
  import {
283
359
  CacheCapabilitySource,
284
360
  CapabilityCache,
@@ -309,34 +385,7 @@ import {
309
385
  shouldIncludeReasoningSummary,
310
386
  supportsReasoning,
311
387
  supportsReasoningSync
312
- } from "./chunk-GJFP5L2V.js";
313
- import "./chunk-SPBFQXOT.js";
314
- import {
315
- ClientCredentialsProvider,
316
- createDiagnosticFetch,
317
- createMCPManager,
318
- httpServer,
319
- serviceAccountServer,
320
- sseServer,
321
- stdioServer
322
- } from "./chunk-UMIVJDEJ.js";
323
- import {
324
- MiddlewareRunner,
325
- approvalMiddleware,
326
- createTelemetryConfig,
327
- isApprovalMiddleware,
328
- otelMiddleware,
329
- promptCacheMiddleware
330
- } from "./chunk-GEBFHREI.js";
331
- import {
332
- DEFAULT_AGENT_NAME,
333
- DEFAULT_MAX_STEPS,
334
- DEFAULT_MAX_TOKENS,
335
- DEFAULT_SYSTEM_PROMPT,
336
- isBlockedModelCall,
337
- resolveAgentDefaults,
338
- sandboxDefaultsProvider
339
- } from "./chunk-CJI7PVS2.js";
388
+ } from "./chunk-CNM6OROH.js";
340
389
  import {
341
390
  DEFAULT_RESOLVER_OPTIONS,
342
391
  PatternCapabilitySource,
@@ -388,6 +437,16 @@ import {
388
437
  requiresToolHost,
389
438
  resolveCapability
390
439
  } from "./chunk-FII65CN7.js";
440
+ import "./chunk-SPBFQXOT.js";
441
+ import {
442
+ ClientCredentialsProvider,
443
+ createDiagnosticFetch,
444
+ createMCPManager,
445
+ httpServer,
446
+ serviceAccountServer,
447
+ sseServer,
448
+ stdioServer
449
+ } from "./chunk-SAWRDGBE.js";
391
450
  import {
392
451
  createConsoleLogger,
393
452
  createFileLogger,
@@ -878,1313 +937,2301 @@ var InterventionController = class {
878
937
  }
879
938
  };
880
939
 
881
- // src/agent/runtime-config.ts
882
- function createAgentToolRecord(tools) {
883
- const toolRecord = {};
884
- for (const [id, tool] of tools) {
885
- toolRecord[id] = tool;
940
+ // src/agent/stream-provider.ts
941
+ var DEFAULT_CUSTOM_STREAM_MODELS = [
942
+ "computer-use-preview",
943
+ "computer-use-preview-2025-03-11"
944
+ ];
945
+ function needsCustomStreamProvider(model, customPatterns) {
946
+ const modelId = extractModelId(model);
947
+ if (!modelId || modelId === "[object Object]") return false;
948
+ const patterns = customPatterns ?? DEFAULT_CUSTOM_STREAM_MODELS;
949
+ return patterns.some((pattern) => modelId.includes(pattern));
950
+ }
951
+ function hasStreamProviderFactory(tools) {
952
+ return Array.isArray(tools) && typeof tools.__streamProviderFactory === "function";
953
+ }
954
+ function autoDetectStreamProvider(model, tools, explicitProvider) {
955
+ if (explicitProvider) {
956
+ return explicitProvider;
886
957
  }
887
- return toolRecord;
958
+ if (!tools) return void 0;
959
+ const enhancedTools = tools;
960
+ const customPatterns = enhancedTools.__customStreamModels;
961
+ if (needsCustomStreamProvider(model, customPatterns) && hasStreamProviderFactory(enhancedTools)) {
962
+ const modelId = extractModelId(model);
963
+ if (modelId) {
964
+ const streamConfig = {
965
+ apiKey: process.env.OPENAI_API_KEY,
966
+ display: { width: 1024, height: 768 },
967
+ environment: "linux",
968
+ debug: false
969
+ };
970
+ return enhancedTools.__streamProviderFactory(modelId, streamConfig);
971
+ }
972
+ }
973
+ return void 0;
888
974
  }
889
- function buildFallbackCompactionSummary(messages) {
890
- const excerpt = messages.map((message) => {
891
- const role = message.role.toUpperCase();
892
- const content = typeof message.content === "string" ? message.content : JSON.stringify(message.content);
893
- return `[${role}] ${content}`;
894
- }).join("\n\n");
895
- const trimmed = excerpt.length > 8e3 ? `${excerpt.slice(0, 8e3)}
896
975
 
897
- ...[truncated during compaction]` : excerpt;
898
- return trimmed.length > 0 ? trimmed : "Earlier conversation context was compacted.";
976
+ // src/agent/defaults.ts
977
+ var DEFAULT_AGENT_NAME = "agent";
978
+ var DEFAULT_MAX_TOKENS = DEFAULT_MAX_OUTPUT_TOKENS;
979
+ function resolveAgentDefaults(context, providers) {
980
+ let merged = {
981
+ systemPrompt: DEFAULT_SYSTEM_PROMPT,
982
+ maxSteps: DEFAULT_MAX_STEPS,
983
+ maxOutputTokens: DEFAULT_MAX_TOKENS
984
+ };
985
+ if (providers) {
986
+ for (const provider of providers) {
987
+ const overrides = provider(context);
988
+ if (overrides) {
989
+ merged = {
990
+ systemPrompt: overrides.systemPrompt ?? merged.systemPrompt,
991
+ maxSteps: overrides.maxSteps ?? merged.maxSteps,
992
+ maxOutputTokens: overrides.maxOutputTokens ?? merged.maxOutputTokens
993
+ };
994
+ }
995
+ }
996
+ }
997
+ return merged;
899
998
  }
900
- async function compactAgentContext(options) {
901
- const { contextManager, sessions, logger } = options;
902
- const log = logger ?? silentLogger;
903
- const messages = getVisibleSessionMessages(sessions);
904
- if (!contextManager.shouldPrune(messages)) {
905
- return {
906
- removedCount: 0,
907
- tokensRemoved: 0,
908
- summarized: false,
909
- summary: void 0
910
- };
999
+ function sandboxDefaultsProvider(context) {
1000
+ const sandbox = context.sandbox;
1001
+ if (!sandbox) {
1002
+ return void 0;
911
1003
  }
912
- const tokensBefore = estimateConversationTokens(messages);
913
- let removedCount = 0;
914
- let summarized = false;
915
- let summary;
916
- try {
917
- const result = await contextManager.prune(messages);
918
- removedCount = result.removedCount;
919
- summarized = result.summarized;
920
- summary = result.summary;
921
- } catch (pruneError) {
922
- log.warn("Context compaction LLM summarisation failed, using fallback", {
923
- error: pruneError instanceof Error ? pruneError.message : String(pruneError)
924
- });
1004
+ const managed = sandbox.metadata?.managed === true;
1005
+ if (managed) {
1006
+ return { maxSteps: 100 };
925
1007
  }
926
- if (removedCount === 0) {
927
- removedCount = findCutPoint(
928
- messages,
929
- contextManager.getLimits().protectedTokens
930
- );
1008
+ return void 0;
1009
+ }
1010
+
1011
+ // src/agent/setup/config.ts
1012
+ function createAgentPromptBuilder(config) {
1013
+ if (config.prompt !== void 0) {
1014
+ return createPromptBuilder(config.prompt);
931
1015
  }
932
- if (removedCount === 0) {
933
- return {
934
- removedCount: 0,
935
- tokensRemoved: 0,
936
- summarized: false,
937
- summary: void 0
938
- };
1016
+ if (config.systemPrompt === void 0) {
1017
+ return createPromptBuilder();
939
1018
  }
940
- const summaryText = summary ?? buildFallbackCompactionSummary(messages.slice(0, removedCount));
941
- const keptMessages = messages.slice(removedCount);
942
- const persistedMessages = [
943
- {
944
- id: "compaction-preview",
945
- role: "system",
946
- content: `## Previous Conversation Summary
947
-
948
- ${summaryText}`,
949
- createdAt: /* @__PURE__ */ new Date()
950
- },
951
- ...keptMessages
1019
+ return void 0;
1020
+ }
1021
+ function createEffectiveAgentConfig(config) {
1022
+ const effectiveStreamProvider = autoDetectStreamProvider(
1023
+ config.model,
1024
+ config.tools,
1025
+ config.streamProvider
1026
+ );
1027
+ const resolvedCwd = config.cwd ?? config.sandbox?.metadata?.workingDirectory ?? process.cwd();
1028
+ const defaultsContext = {
1029
+ sandbox: config.sandbox,
1030
+ cwd: resolvedCwd,
1031
+ modelId: extractModelId(config.model)
1032
+ };
1033
+ const providers = [
1034
+ sandboxDefaultsProvider,
1035
+ ...config.defaultsProviders ?? []
952
1036
  ];
953
- const tokensAfter = estimateConversationTokens(persistedMessages);
954
- await sessions.replaceWithCompaction({
955
- summary: summaryText,
956
- messages: keptMessages,
957
- tokensBefore,
958
- tokensAfter
959
- });
1037
+ const defaults = resolveAgentDefaults(defaultsContext, providers);
960
1038
  return {
961
- removedCount,
962
- tokensRemoved: Math.max(0, tokensBefore - tokensAfter),
963
- summarized,
964
- summary: summaryText
1039
+ ...config,
1040
+ systemPrompt: config.systemPrompt ?? defaults.systemPrompt,
1041
+ cwd: resolvedCwd,
1042
+ reasoningLevel: config.reasoningLevel ?? "off",
1043
+ maxSteps: config.maxSteps ?? defaults.maxSteps,
1044
+ maxOutputTokens: config.maxOutputTokens ?? defaults.maxOutputTokens,
1045
+ streamProvider: effectiveStreamProvider
965
1046
  };
966
1047
  }
967
- async function buildAgentSystemPrompts(options) {
968
- const {
969
- config,
970
- toolIds,
971
- sessionId,
972
- override,
973
- promptBuilder,
974
- middlewareRunner
975
- } = options;
976
- if (promptBuilder) {
977
- const composedPrompt = await promptBuilder.build(
978
- {
979
- cwd: config.cwd,
980
- model: config.model,
981
- toolNames: toolIds,
982
- ...override ? { override } : {},
983
- sessionId
984
- },
985
- middlewareRunner
986
- );
987
- return [composedPrompt];
988
- }
989
- const prompts = [config.systemPrompt];
990
- if (override) {
991
- prompts.push(override);
992
- }
993
- return prompts;
994
- }
995
- function createAgentTurnRuntimeConfig(options) {
996
- const { config, telemetrySettings } = options;
1048
+ function resolveAgentContextLimits(contextWindow, compactionConfig = {}) {
1049
+ const proportionalReserve = Math.round(contextWindow * 0.12);
1050
+ const reserveTokens = contextWindow >= 64e3 ? Math.min(32e3, Math.max(8e3, proportionalReserve)) : Math.min(
1051
+ Math.max(1024, Math.round(contextWindow * 0.25)),
1052
+ Math.max(512, proportionalReserve)
1053
+ );
1054
+ const usableWindow = Math.max(
1055
+ 512,
1056
+ getUsableTokenLimit({ contextWindow, reserveTokens })
1057
+ );
1058
+ const requestedProtected = compactionConfig.protectedTokens ?? DEFAULT_CONTEXT_LIMITS.protectedTokens;
1059
+ const requestedPruneMinimum = compactionConfig.pruneMinimum ?? DEFAULT_CONTEXT_LIMITS.pruneMinimum;
997
1060
  return {
998
- model: config.model,
999
- cwd: config.cwd,
1000
- ...config.temperature !== void 0 ? { temperature: config.temperature } : {},
1001
- ...config.topP !== void 0 ? { topP: config.topP } : {},
1002
- ...config.maxOutputTokens !== void 0 ? { maxOutputTokens: config.maxOutputTokens } : {},
1003
- maxSteps: config.maxSteps,
1004
- ...config.doomLoopThreshold !== void 0 ? { doomLoopThreshold: config.doomLoopThreshold } : {},
1005
- ...config.enforceDoomLoop !== void 0 ? { enforceDoomLoop: config.enforceDoomLoop } : {},
1006
- ...config.onDoomLoop ? { onDoomLoop: config.onDoomLoop } : {},
1007
- ...config.contextWindow !== void 0 ? { contextWindow: config.contextWindow } : {},
1008
- ...options.reserveTokens !== void 0 ? { reserveTokens: options.reserveTokens } : {},
1009
- ...config.streamProvider ? { streamProvider: config.streamProvider } : {},
1010
- ...telemetrySettings ? { telemetry: telemetrySettings } : {}
1061
+ reserveTokens,
1062
+ protectedTokens: Math.min(
1063
+ requestedProtected,
1064
+ Math.max(512, Math.round(usableWindow * 0.6))
1065
+ ),
1066
+ pruneMinimum: Math.min(
1067
+ requestedPruneMinimum,
1068
+ Math.max(256, Math.round(usableWindow * 0.5))
1069
+ )
1011
1070
  };
1012
1071
  }
1013
1072
 
1014
- // src/agent/chat-loop/commit.ts
1015
- function createChatLoopCommitBatchApplier(params) {
1016
- const { turnEngine, sessions, middlewareRunner } = params;
1017
- return async function* applyCommitBatch(batch, options = {}) {
1018
- turnEngine.recordEvent(batch.startBoundary, (/* @__PURE__ */ new Date()).toISOString());
1019
- middlewareRunner.emitEvent(batch.startBoundary);
1020
- yield batch.startBoundary;
1021
- await sessions.addMessages(batch.messages);
1022
- turnEngine.recordEvent(batch.finishBoundary, (/* @__PURE__ */ new Date()).toISOString());
1023
- middlewareRunner.emitEvent(batch.finishBoundary);
1024
- yield batch.finishBoundary;
1025
- if (options.emitMessages) {
1026
- for (const committedMessage of batch.messages) {
1027
- yield { type: "message", message: committedMessage };
1028
- }
1073
+ // src/agent/setup/context-window.ts
1074
+ function createAgentContextWindowManager(config) {
1075
+ const compactionConfig = config.compaction ?? {};
1076
+ const modelId = extractModelId(config.model);
1077
+ const inferredWindow = inferContextWindow(modelId);
1078
+ const contextWindow = config.contextWindow ?? inferredWindow ?? DEFAULT_CONTEXT_LIMITS.contextWindow;
1079
+ return new ContextWindowManager({
1080
+ limits: {
1081
+ contextWindow,
1082
+ ...resolveAgentContextLimits(contextWindow, compactionConfig)
1083
+ },
1084
+ model: config.model,
1085
+ summary: {
1086
+ mode: compactionConfig.summaryMode ?? "required",
1087
+ model: compactionConfig.summaryModel,
1088
+ prompt: compactionConfig.summaryPrompt,
1089
+ maxInputTokens: compactionConfig.summaryMaxInputTokens,
1090
+ maxOutputTokens: compactionConfig.summaryMaxOutputTokens,
1091
+ targetRatio: compactionConfig.summaryTargetRatio
1029
1092
  }
1030
- };
1093
+ });
1031
1094
  }
1032
1095
 
1033
- // src/agent/chat-loop/compaction.ts
1034
- async function runAutoCompaction(params) {
1035
- const { contextManager, sessions, logger } = params;
1036
- const messages = sessions.getMessages();
1037
- if (!contextManager.shouldPrune(messages)) {
1038
- return [];
1096
+ // src/human/controller.ts
1097
+ var HumanInputTimeoutError = class extends Error {
1098
+ constructor(timeoutMs) {
1099
+ super(`Human input request timed out after ${timeoutMs}ms`);
1100
+ this.name = "HumanInputTimeoutError";
1039
1101
  }
1040
- const events = [{ type: "status", status: "processing" }];
1041
- try {
1042
- const pruneResult = await compactAgentContext({
1043
- contextManager,
1044
- sessions,
1045
- logger
1046
- });
1047
- if (pruneResult.removedCount > 0 || pruneResult.summarized) {
1048
- const limits = contextManager.getLimits();
1049
- events.push({
1050
- type: "context-overflow",
1051
- inputTokens: estimateConversationTokens(messages),
1052
- limit: getUsableTokenLimit(limits)
1053
- });
1054
- }
1055
- } catch (error) {
1056
- logger?.warn("Auto-compaction failed, continuing without compaction", {
1057
- error: error instanceof Error ? error.message : String(error)
1058
- });
1102
+ };
1103
+ var HumanInputUnavailableError = class extends Error {
1104
+ constructor() {
1105
+ super("No human input controller configured");
1106
+ this.name = "HumanInputUnavailableError";
1059
1107
  }
1060
- return events;
1061
- }
1062
-
1063
- // src/agent/chat-loop/prompts.ts
1064
- async function buildChatSystemPrompts(params) {
1065
- return buildAgentSystemPrompts({
1066
- config: params.config,
1067
- toolIds: Object.keys(params.tools),
1068
- sessionId: params.sessionId,
1069
- override: params.systemOverride,
1070
- promptBuilder: params.promptBuilder,
1071
- middlewareRunner: params.middlewareRunner
1072
- });
1108
+ };
1109
+ function cloneRecord(record) {
1110
+ return structuredClone(record);
1073
1111
  }
1074
-
1075
- // src/agent/chat-loop/turn-tools.ts
1076
- async function resolveTurnTools(options) {
1077
- const tools = /* @__PURE__ */ new Map();
1078
- const mcpTools = {};
1079
- const cleanup = [];
1080
- try {
1081
- for (const provider of options.providers) {
1082
- const resolved = await provider.resolveTools(options.context);
1083
- if (resolved.cleanup) {
1084
- cleanup.push(resolved.cleanup);
1085
- }
1086
- for (const tool of resolved.tools ?? []) {
1087
- if (options.baseTools.has(tool.id) || tools.has(tool.id)) {
1088
- throw new Error(
1089
- `Turn tool provider "${provider.name}" returned duplicate tool "${tool.id}"`
1090
- );
1091
- }
1092
- tools.set(tool.id, tool);
1093
- }
1094
- for (const [name, tool] of Object.entries(resolved.mcpTools ?? {})) {
1095
- if (options.baseMcpTools[name] || mcpTools[name]) {
1096
- throw new Error(
1097
- `Turn tool provider "${provider.name}" returned duplicate MCP tool "${name}"`
1098
- );
1099
- }
1100
- mcpTools[name] = tool;
1101
- }
1102
- }
1103
- } catch (error) {
1104
- try {
1105
- await cleanupTurnTools(cleanup);
1106
- } catch {
1107
- }
1108
- throw error;
1112
+ function normalizeStatuses(status) {
1113
+ if (!status) {
1114
+ return void 0;
1109
1115
  }
1110
- return { tools, mcpTools, cleanup };
1116
+ return new Set(Array.isArray(status) ? status : [status]);
1111
1117
  }
1112
- function mergeTurnTools(baseTools, turnTools) {
1113
- if (turnTools.size === 0) {
1114
- return baseTools;
1118
+ function inferKind(input) {
1119
+ if (input.kind) {
1120
+ return input.kind;
1115
1121
  }
1116
- const merged = new Map(baseTools);
1117
- for (const [id, tool] of turnTools) {
1118
- if (merged.has(id)) {
1119
- throw new Error(`Turn-scoped tool "${id}" conflicts with an agent tool`);
1120
- }
1121
- merged.set(id, tool);
1122
+ if (input.options && input.options.length > 0) {
1123
+ return "choice";
1122
1124
  }
1123
- return merged;
1125
+ return "text";
1124
1126
  }
1125
- async function cleanupTurnTools(cleanup) {
1126
- const errors = [];
1127
- for (const cleanupFn of [...cleanup].reverse()) {
1128
- try {
1129
- await cleanupFn();
1130
- } catch (error) {
1131
- errors.push(error);
1132
- }
1133
- }
1134
- if (errors.length === 1) {
1135
- throw errors[0];
1136
- }
1137
- if (errors.length > 1) {
1138
- throw new AggregateError(
1139
- errors,
1140
- "Multiple turn tool cleanup callbacks failed"
1141
- );
1127
+ function isHumanInputController(value) {
1128
+ if (!value || typeof value !== "object") {
1129
+ return false;
1142
1130
  }
1131
+ const candidate = value;
1132
+ return typeof candidate.request === "function" && typeof candidate.respondToRequest === "function" && typeof candidate.getRequest === "function" && typeof candidate.listRequests === "function" && typeof candidate.cancelAll === "function";
1143
1133
  }
1144
-
1145
- // src/agent/chat-loop/loop.ts
1146
- async function* runChatLoop(deps) {
1147
- yield* streamWithinScope(
1148
- {
1149
- kind: "turn",
1150
- name: "agent-turn",
1151
- sessionId: deps.sessionId
1152
- },
1153
- (async function* () {
1154
- const {
1155
- sessionId,
1156
- turnId,
1157
- message,
1158
- abort,
1159
- systemOverride,
1160
- sessions,
1161
- tools: liveTools,
1162
- config,
1163
- turnTracker,
1164
- interventionCtrl,
1165
- middlewareRunner,
1166
- contextManager,
1167
- rememberedDoomLoopTools,
1168
- reasoningLevel,
1169
- promptBuilder,
1170
- host,
1171
- humanInputController,
1172
- mcpTools,
1173
- toModelMessages,
1174
- setIsStreaming
1175
- } = deps;
1176
- let resolvedTurnTools;
1177
- try {
1178
- resolvedTurnTools = await resolveTurnTools({
1179
- providers: deps.turnToolProviders,
1180
- context: {
1181
- sessionId,
1182
- turnId,
1183
- message,
1184
- cwd: config.cwd,
1185
- abort
1186
- },
1187
- baseTools: liveTools,
1188
- baseMcpTools: mcpTools
1189
- });
1190
- } catch (error) {
1191
- const errorInstance = error instanceof Error ? error : new Error(String(error));
1192
- const statusEvent = { type: "status", status: "error" };
1193
- middlewareRunner.emitEvent(statusEvent);
1194
- yield statusEvent;
1195
- const errorEvent = {
1196
- type: "error",
1197
- error: errorInstance
1198
- };
1199
- middlewareRunner.emitEvent(errorEvent);
1200
- yield errorEvent;
1201
- throw errorInstance;
1202
- }
1203
- const turnMcpTools = {
1204
- ...mcpTools,
1205
- ...resolvedTurnTools.mcpTools
1206
- };
1207
- let toolRecord = createAgentToolRecord(
1208
- mergeTurnTools(liveTools, resolvedTurnTools.tools)
1209
- );
1210
- const prevOnApplied = interventionCtrl.onApplied;
1211
- let streamingStateStarted = false;
1212
- let chatUsage;
1213
- let chatError;
1214
- let chatOutput;
1215
- let chatEndError;
1216
- let rethrowError;
1217
- const lifecycleContext = {
1218
- sessionId,
1219
- turnId,
1220
- history: {
1221
- getRecentMessages: (options) => sessions.getRecentMessages(options)
1222
- }
1223
- };
1224
- try {
1225
- const isPlanMode = deps.toolExecutionMode === "plan";
1226
- const turnEngine = createAgentTurnEngine({
1227
- sessionId,
1228
- startedAt: (/* @__PURE__ */ new Date()).toISOString(),
1229
- getToolReplayPolicy: (toolName) => toolRecord[toolName] ? normalizeToolReplayPolicy(toolRecord[toolName].replayPolicy) : void 0
1230
- });
1231
- const applyCommitBatch = createChatLoopCommitBatchApplier({
1232
- turnEngine,
1233
- sessions,
1234
- middlewareRunner
1235
- });
1236
- yield* applyCommitBatch(
1237
- turnEngine.createInputCommit({
1238
- content: message,
1239
- system: systemOverride
1240
- }),
1241
- { emitMessages: true }
1242
- );
1243
- setIsStreaming(true);
1244
- streamingStateStarted = true;
1245
- if (middlewareRunner.hasMiddleware) {
1246
- await middlewareRunner.runChatStart(
1247
- sessionId,
1248
- message,
1249
- lifecycleContext
1250
- );
1251
- }
1252
- let step = 1;
1253
- let finalStepText = "";
1254
- let accumulatedUsage;
1255
- while (step <= config.maxSteps) {
1256
- toolRecord = createAgentToolRecord(
1257
- mergeTurnTools(liveTools, resolvedTurnTools.tools)
1258
- );
1259
- const systemPrompts = await buildChatSystemPrompts({
1260
- promptBuilder,
1261
- middlewareRunner,
1262
- systemOverride,
1263
- sessionId,
1264
- config,
1265
- tools: toolRecord
1266
- });
1267
- const preparedStep = prepareModelStep({
1268
- sessionId,
1269
- step,
1270
- systemPrompts,
1271
- messages: sessions.getMessages(),
1272
- toModelMessages,
1273
- abort,
1274
- tools: toolRecord,
1275
- mcpTools: turnMcpTools,
1276
- config,
1277
- host,
1278
- humanInputController,
1279
- turnTracker,
1280
- intervention: interventionCtrl,
1281
- middleware: middlewareRunner,
1282
- reasoningLevel,
1283
- toolExecutionMode: deps.toolExecutionMode
1284
- });
1285
- const stepResult = yield* runModelStep({
1286
- preparedStep,
1287
- turnEngine,
1288
- applyCommitBatch,
1289
- rememberedDoomLoopTools
1290
- });
1291
- accumulatedUsage = accumulateUsage(
1292
- accumulatedUsage,
1293
- stepResult.usage
1294
- );
1295
- if (stepResult.error) {
1296
- chatError = stepResult.error;
1134
+ async function emitHumanInputEvent(context, event) {
1135
+ await context?.emitEvent?.(event);
1136
+ }
1137
+ function createHumanInputController(config = {}) {
1138
+ const timeout = config.timeout ?? 5 * 60 * 1e3;
1139
+ let requestCounter = 0;
1140
+ const pending = /* @__PURE__ */ new Map();
1141
+ async function request(sessionId, input, context = {}) {
1142
+ const requestPayload = {
1143
+ id: `human-input-${++requestCounter}-${Date.now()}`,
1144
+ sessionId,
1145
+ kind: inferKind(input),
1146
+ title: input.title,
1147
+ question: input.question,
1148
+ ...input.options ? { options: input.options.map((option) => ({ ...option })) } : {},
1149
+ ...input.allowMultiple !== void 0 ? { allowMultiple: input.allowMultiple } : {},
1150
+ ...input.placeholder ? { placeholder: input.placeholder } : {},
1151
+ ...input.confirmLabel ? { confirmLabel: input.confirmLabel } : {},
1152
+ ...input.denyLabel ? { denyLabel: input.denyLabel } : {},
1153
+ ...input.toolCallId ? { toolCallId: input.toolCallId } : {},
1154
+ timestamp: Date.now()
1155
+ };
1156
+ const record = {
1157
+ id: requestPayload.id,
1158
+ sessionId,
1159
+ request: structuredClone(requestPayload),
1160
+ status: "pending",
1161
+ createdAt: requestPayload.timestamp,
1162
+ updatedAt: requestPayload.timestamp
1163
+ };
1164
+ const responsePromise = new Promise(
1165
+ (resolve2, reject) => {
1166
+ const timeoutId = setTimeout(() => {
1167
+ const current2 = pending.get(record.id);
1168
+ if (!current2) {
1297
1169
  return;
1298
1170
  }
1299
- const planSnapshot = isPlanMode && stepResult.finishReason === "tool-calls" ? turnEngine.createStepCommitSnapshot() : void 0;
1300
- yield* commitStep({
1301
- step,
1302
- finishReason: stepResult.finishReason,
1303
- turnEngine,
1304
- applyCommitBatch
1305
- });
1306
- if (stepResult.finishReason === "tool-calls") {
1307
- if (step >= config.maxSteps) {
1308
- const maxStepsError = new Error(
1309
- `Maximum steps (${config.maxSteps}) reached before the turn produced a final response`
1310
- );
1311
- chatError = maxStepsError;
1312
- const statusEvent = {
1313
- type: "status",
1314
- status: "error"
1315
- };
1316
- middlewareRunner.emitEvent(statusEvent);
1317
- yield statusEvent;
1318
- const errorEvent = {
1319
- type: "error",
1320
- error: maxStepsError
1321
- };
1322
- middlewareRunner.emitEvent(errorEvent);
1323
- yield errorEvent;
1324
- return;
1325
- }
1326
- if (isPlanMode && planSnapshot && planSnapshot.toolCalls.length > 0) {
1327
- const batchResult = await runToolBatch({
1328
- sessionId,
1329
- snapshot: planSnapshot,
1330
- tools: toolRecord,
1331
- cwd: config.cwd,
1332
- abort,
1333
- host,
1334
- humanInputController,
1335
- turnTracker,
1336
- middleware: middlewareRunner,
1337
- intervention: interventionCtrl
1338
- });
1339
- for (const event of batchResult.events) {
1340
- turnEngine.recordEvent(event, (/* @__PURE__ */ new Date()).toISOString());
1341
- middlewareRunner.emitEvent(event);
1342
- yield event;
1343
- }
1344
- yield* commitStep({
1345
- step,
1346
- finishReason: "tool-calls",
1347
- turnEngine,
1348
- applyCommitBatch
1349
- });
1350
- }
1351
- step += 1;
1352
- continue;
1171
+ pending.delete(record.id);
1172
+ current2.record = {
1173
+ ...current2.record,
1174
+ status: "timed-out",
1175
+ updatedAt: Date.now()
1176
+ };
1177
+ void emitHumanInputEvent(
1178
+ { emitEvent: current2.emitEvent },
1179
+ { type: "status", status: "processing" }
1180
+ );
1181
+ reject(new HumanInputTimeoutError(timeout));
1182
+ }, timeout);
1183
+ pending.set(record.id, {
1184
+ record,
1185
+ resolve: resolve2,
1186
+ reject,
1187
+ ready: Promise.resolve(),
1188
+ timeoutId,
1189
+ emitEvent: context.emitEvent
1190
+ });
1191
+ }
1192
+ );
1193
+ const current = pending.get(record.id);
1194
+ if (current) {
1195
+ current.ready = (async () => {
1196
+ await emitHumanInputEvent(context, {
1197
+ type: "status",
1198
+ status: "waiting-input"
1199
+ });
1200
+ await emitHumanInputEvent(context, {
1201
+ type: "human-input-request",
1202
+ request: {
1203
+ id: requestPayload.id,
1204
+ kind: requestPayload.kind,
1205
+ title: requestPayload.title,
1206
+ question: requestPayload.question,
1207
+ ...requestPayload.options ? { options: requestPayload.options } : {},
1208
+ ...requestPayload.allowMultiple !== void 0 ? { allowMultiple: requestPayload.allowMultiple } : {},
1209
+ ...requestPayload.placeholder ? { placeholder: requestPayload.placeholder } : {},
1210
+ ...requestPayload.confirmLabel ? { confirmLabel: requestPayload.confirmLabel } : {},
1211
+ ...requestPayload.denyLabel ? { denyLabel: requestPayload.denyLabel } : {}
1353
1212
  }
1354
- finalStepText = stepResult.text;
1355
- break;
1356
- }
1357
- yield* commitOutput({
1358
- text: finalStepText,
1359
- usage: accumulatedUsage,
1360
- turnEngine,
1361
- applyCommitBatch
1362
1213
  });
1363
- if (config.compaction?.auto !== false) {
1364
- const compactionEvents = await runAutoCompaction({
1365
- contextManager,
1366
- sessions,
1367
- logger: deps.logger
1368
- });
1369
- for (const event of compactionEvents) {
1370
- yield event;
1214
+ })();
1215
+ }
1216
+ if (config.onRequest) {
1217
+ void (async () => {
1218
+ try {
1219
+ await pending.get(record.id)?.ready;
1220
+ const response = await config.onRequest(requestPayload);
1221
+ await respondToRequest(record.id, response, context);
1222
+ } catch (error) {
1223
+ if (error instanceof HumanInputTimeoutError) {
1224
+ return;
1371
1225
  }
1372
- }
1373
- const turnSummary = await turnTracker.endTurn();
1374
- if (turnSummary.totalTracked > 0) {
1375
- yield {
1376
- type: "turn-summary",
1377
- turnId: turnSummary.turnId,
1378
- files: turnSummary.files.map((file) => ({
1379
- path: file.path,
1380
- type: file.type,
1381
- additions: file.additions,
1382
- deletions: file.deletions
1383
- })),
1384
- additions: turnSummary.additions,
1385
- deletions: turnSummary.deletions
1226
+ const current2 = pending.get(record.id);
1227
+ if (!current2) {
1228
+ return;
1229
+ }
1230
+ pending.delete(record.id);
1231
+ clearTimeout(current2.timeoutId);
1232
+ current2.record = {
1233
+ ...current2.record,
1234
+ status: "cancelled",
1235
+ updatedAt: Date.now()
1386
1236
  };
1237
+ current2.reject(
1238
+ error instanceof Error ? error : new Error(String(error))
1239
+ );
1240
+ await emitHumanInputEvent(
1241
+ { emitEvent: current2.emitEvent },
1242
+ { type: "status", status: "processing" }
1243
+ );
1387
1244
  }
1388
- chatUsage = accumulatedUsage;
1389
- chatOutput = finalStepText || void 0;
1390
- yield {
1391
- type: "complete",
1392
- usage: accumulatedUsage,
1393
- output: finalStepText || void 0
1394
- };
1395
- } catch (error) {
1396
- chatError = error instanceof Error ? error : new Error(String(error));
1397
- const statusEvent = { type: "status", status: "error" };
1398
- middlewareRunner.emitEvent(statusEvent);
1399
- yield statusEvent;
1400
- const errorEvent = { type: "error", error: chatError };
1401
- middlewareRunner.emitEvent(errorEvent);
1402
- yield errorEvent;
1403
- rethrowError = error;
1404
- } finally {
1405
- if (streamingStateStarted) {
1406
- setIsStreaming(false);
1407
- }
1408
- interventionCtrl.onApplied = prevOnApplied;
1409
- if (middlewareRunner.hasMiddleware) {
1410
- try {
1411
- await middlewareRunner.runChatEnd(
1412
- sessionId,
1413
- {
1414
- usage: chatUsage,
1415
- error: chatError,
1416
- output: chatOutput
1417
- },
1418
- lifecycleContext
1419
- );
1420
- } catch (error) {
1421
- chatEndError = error;
1422
- }
1245
+ })();
1246
+ }
1247
+ return await responsePromise;
1248
+ }
1249
+ async function respondToRequest(requestId, response, context = {}) {
1250
+ const current = pending.get(requestId);
1251
+ if (!current) {
1252
+ throw new Error(`Human input request not found: ${requestId}`);
1253
+ }
1254
+ await current.ready;
1255
+ pending.delete(requestId);
1256
+ clearTimeout(current.timeoutId);
1257
+ const respondedAt = Date.now();
1258
+ const next = {
1259
+ ...current.record,
1260
+ status: "answered",
1261
+ updatedAt: respondedAt,
1262
+ respondedAt,
1263
+ response: structuredClone(response)
1264
+ };
1265
+ current.resolve(response);
1266
+ const emitEvent = context.emitEvent ?? current.emitEvent;
1267
+ await emitHumanInputEvent(
1268
+ { emitEvent },
1269
+ {
1270
+ type: "human-input-resolved",
1271
+ id: requestId,
1272
+ response
1273
+ }
1274
+ );
1275
+ await emitHumanInputEvent(
1276
+ { emitEvent },
1277
+ { type: "status", status: "processing" }
1278
+ );
1279
+ return cloneRecord(next);
1280
+ }
1281
+ function getRequest(requestId) {
1282
+ const current = pending.get(requestId);
1283
+ return current ? cloneRecord(current.record) : void 0;
1284
+ }
1285
+ function listRequests(options = {}) {
1286
+ const statuses = normalizeStatuses(options.status);
1287
+ return [...pending.values()].map((entry) => cloneRecord(entry.record)).filter((record) => {
1288
+ if (options.sessionId && record.sessionId !== options.sessionId) {
1289
+ return false;
1290
+ }
1291
+ if (statuses && !statuses.has(record.status)) {
1292
+ return false;
1293
+ }
1294
+ return true;
1295
+ }).sort((left, right) => left.createdAt - right.createdAt);
1296
+ }
1297
+ function cancelAll(reason = "Cancelled") {
1298
+ for (const [requestId, current] of pending) {
1299
+ pending.delete(requestId);
1300
+ clearTimeout(current.timeoutId);
1301
+ current.record = {
1302
+ ...current.record,
1303
+ status: "cancelled",
1304
+ updatedAt: Date.now()
1305
+ };
1306
+ current.reject(new Error(reason));
1307
+ void emitHumanInputEvent(
1308
+ { emitEvent: current.emitEvent },
1309
+ { type: "status", status: "processing" }
1310
+ );
1311
+ }
1312
+ }
1313
+ return {
1314
+ get hasPendingRequests() {
1315
+ return pending.size > 0;
1316
+ },
1317
+ request,
1318
+ respondToRequest,
1319
+ getRequest,
1320
+ listRequests,
1321
+ cancelAll
1322
+ };
1323
+ }
1324
+
1325
+ // src/human/handler.ts
1326
+ function createHumanInputHandler(config = {}) {
1327
+ return createHumanInputController(config);
1328
+ }
1329
+
1330
+ // src/human/tool.ts
1331
+ import { z } from "zod";
1332
+ function createHumanInputTool(options = {}) {
1333
+ if (options.controller) {
1334
+ return createHumanInputToolWithController(options.controller, options);
1335
+ }
1336
+ if (options.onRequest || options.timeout !== void 0) {
1337
+ return createHumanInputToolWithController(
1338
+ createHumanInputController(options),
1339
+ options
1340
+ );
1341
+ }
1342
+ return createHumanInputToolWithController(void 0, options);
1343
+ }
1344
+ function createHumanInputToolWithController(controller, options = {}) {
1345
+ return Tool.define(
1346
+ options.name ?? "question",
1347
+ {
1348
+ description: options.description ?? "Ask a human for missing input, a decision, a confirmation, or a choice.",
1349
+ parameters: z.object({
1350
+ title: z.string().min(1).describe("Short heading for the request"),
1351
+ question: z.string().min(1).describe("What to ask the human"),
1352
+ kind: z.enum(["text", "confirm", "choice"]).optional(),
1353
+ options: z.array(
1354
+ z.object({
1355
+ label: z.string().min(1),
1356
+ value: z.string().optional(),
1357
+ description: z.string().optional()
1358
+ })
1359
+ ).optional(),
1360
+ allowMultiple: z.boolean().optional(),
1361
+ placeholder: z.string().optional(),
1362
+ confirmLabel: z.string().optional(),
1363
+ denyLabel: z.string().optional()
1364
+ }),
1365
+ validate: (params) => {
1366
+ const kind = params.kind ?? (params.options?.length ? "choice" : "text");
1367
+ if (kind === "choice" && (!params.options || params.options.length === 0)) {
1368
+ return {
1369
+ ok: false,
1370
+ reason: "Choice requests must include at least one option."
1371
+ };
1423
1372
  }
1373
+ if (kind !== "choice" && params.allowMultiple) {
1374
+ return {
1375
+ ok: false,
1376
+ reason: "allowMultiple is only valid for choice requests."
1377
+ };
1378
+ }
1379
+ return { ok: true };
1380
+ },
1381
+ capabilities: {
1382
+ readOnly: true,
1383
+ riskLevel: "safe",
1384
+ parallelSafe: false,
1385
+ humanInput: true
1386
+ },
1387
+ replayPolicy: {
1388
+ mode: "manual",
1389
+ sideEffectLevel: "external",
1390
+ reason: "Depends on a human response before execution can continue."
1391
+ },
1392
+ execute: async (params, ctx) => {
1393
+ let response;
1424
1394
  try {
1425
- await cleanupTurnTools(resolvedTurnTools.cleanup);
1395
+ const activeController = controller ?? ctx.humanInputController;
1396
+ if (!activeController) {
1397
+ throw new HumanInputUnavailableError();
1398
+ }
1399
+ response = await activeController.request(
1400
+ ctx.sessionID,
1401
+ {
1402
+ ...params,
1403
+ toolCallId: typeof ctx.extra?.toolCallId === "string" ? ctx.extra.toolCallId : ctx.messageID
1404
+ },
1405
+ {
1406
+ emitEvent: ctx.emitEvent
1407
+ }
1408
+ );
1426
1409
  } catch (error) {
1427
- const errorInstance = error instanceof Error ? error : new Error(String(error));
1428
- deps.logger?.warn("Turn tool provider cleanup failed", {
1429
- error: errorInstance,
1430
- message: errorInstance.message,
1431
- stack: errorInstance.stack
1432
- });
1410
+ if (error instanceof HumanInputUnavailableError) {
1411
+ throw error;
1412
+ }
1413
+ throw error;
1433
1414
  }
1415
+ return {
1416
+ title: params.title,
1417
+ output: response.text,
1418
+ metadata: { response }
1419
+ };
1434
1420
  }
1435
- if (chatEndError) {
1436
- throw chatEndError;
1437
- }
1438
- if (rethrowError) {
1439
- throw rethrowError;
1421
+ },
1422
+ {
1423
+ replayPolicy: {
1424
+ mode: "manual",
1425
+ sideEffectLevel: "external",
1426
+ reason: "Depends on a human response before execution can continue."
1427
+ },
1428
+ capabilitiesHint: {
1429
+ readOnly: true,
1430
+ riskLevel: "safe",
1431
+ parallelSafe: false,
1432
+ humanInput: true
1440
1433
  }
1441
- })()
1434
+ }
1442
1435
  );
1443
1436
  }
1437
+ var createHumanInputToolWithHandler = createHumanInputToolWithController;
1444
1438
 
1445
- // src/agent/fork.ts
1446
- function resolveForkOptions(options, parentTools, systemPrompt) {
1447
- if (!options.profile) {
1448
- return options;
1439
+ // src/agent/setup/environment.ts
1440
+ function resolveHumanInputController(input) {
1441
+ if (!input.humanInput) {
1442
+ return {};
1449
1443
  }
1450
- const applied = applyProfile(options.profile, parentTools, systemPrompt);
1451
1444
  return {
1452
- ...applied,
1453
- ...options,
1454
- tools: options.tools ?? applied.tools
1445
+ humanInputController: isHumanInputController(input.humanInput) ? input.humanInput : createHumanInputController(input.humanInput)
1455
1446
  };
1456
1447
  }
1457
- function resolveChildPromptConfig(options) {
1458
- const { forkOptions, promptBuilder, parentPromptConfig, parentSystemPrompt } = options;
1459
- if (forkOptions.systemPrompt) {
1460
- return { systemPrompt: forkOptions.systemPrompt };
1448
+ function resolveExecutionEnvironment(input, config) {
1449
+ if (input.host !== void 0 && input.sandbox !== void 0 && input.host !== input.sandbox.host) {
1450
+ throw new Error(
1451
+ "createAgent() received both `host` and `sandbox`, but `sandbox.host` does not match the provided host. Pass only one execution input, or reuse the same host instance for both."
1452
+ );
1461
1453
  }
1462
- if (forkOptions.prompt) {
1463
- return { prompt: forkOptions.prompt };
1454
+ if (input.host !== void 0) {
1455
+ return {
1456
+ host: input.host,
1457
+ ...input.sandbox ? { sandbox: input.sandbox } : {},
1458
+ ownsHost: false
1459
+ };
1464
1460
  }
1465
- if (promptBuilder) {
1466
- return { prompt: parentPromptConfig ?? {} };
1461
+ if (input.sandbox !== void 0) {
1462
+ return {
1463
+ host: input.sandbox.host,
1464
+ sandbox: input.sandbox,
1465
+ ownsHost: false
1466
+ };
1467
1467
  }
1468
- return { systemPrompt: parentSystemPrompt };
1468
+ return {
1469
+ host: localHost(config.cwd),
1470
+ ownsHost: true
1471
+ };
1469
1472
  }
1470
- function resolveForkMiddleware(options, middlewareRunner) {
1471
- if (options.middleware) {
1472
- return options.middleware;
1473
+
1474
+ // src/agent/setup/middleware.ts
1475
+ function createMiddlewareSetup(input, config) {
1476
+ const inputMiddleware = [...input.middleware ?? []];
1477
+ const hasManualApprovalMiddleware = inputMiddleware.some(
1478
+ (mw) => isApprovalMiddleware(mw)
1479
+ );
1480
+ if (input.approval && hasManualApprovalMiddleware) {
1481
+ throw new Error(
1482
+ "createAgent() received both `approval` config and an explicit approval middleware. Use `approval` for the built-in sugar, or install `approvalMiddleware(...)` manually, but not both."
1483
+ );
1473
1484
  }
1474
- if (options.additionalMiddleware) {
1475
- return [
1476
- ...middlewareRunner.getMiddleware(),
1477
- ...options.additionalMiddleware
1485
+ let effectiveMiddleware = inputMiddleware;
1486
+ let telemetrySettings;
1487
+ let tracingShutdown;
1488
+ const memory = resolveAgentMemoryConfig(input.memory);
1489
+ if (memory) {
1490
+ effectiveMiddleware.push(
1491
+ createMemoryMiddleware({
1492
+ provider: memory.provider,
1493
+ recall: memory.recall,
1494
+ turns: memory.turns,
1495
+ cwd: config.cwd
1496
+ })
1497
+ );
1498
+ }
1499
+ if (input.approval) {
1500
+ effectiveMiddleware.push(approvalMiddleware(input.approval));
1501
+ }
1502
+ if (input.tracing) {
1503
+ const agentName = config.name ?? DEFAULT_AGENT_NAME;
1504
+ const telemetryResult = createTelemetryConfig({
1505
+ ...input.tracing,
1506
+ agentName,
1507
+ serviceName: input.tracing.serviceName ?? agentName
1508
+ });
1509
+ effectiveMiddleware = [
1510
+ ...telemetryResult.middlewares.length > 0 ? telemetryResult.middlewares : [telemetryResult.middleware],
1511
+ ...effectiveMiddleware
1478
1512
  ];
1513
+ telemetrySettings = telemetryResult.telemetry;
1514
+ tracingShutdown = telemetryResult.shutdown;
1479
1515
  }
1480
- return [...middlewareRunner.getMiddleware()];
1516
+ return {
1517
+ middlewareRunner: new MiddlewareRunner(effectiveMiddleware, input.logger),
1518
+ ...telemetrySettings ? { telemetrySettings } : {},
1519
+ ...tracingShutdown ? { tracingShutdown } : {}
1520
+ };
1481
1521
  }
1482
- function createForkedAgentConfig(options) {
1483
- const {
1484
- forkOptions,
1485
- parentConfig,
1486
- parentTools,
1487
- reasoningLevel,
1488
- host,
1489
- sandbox,
1490
- humanInputController,
1491
- ownsHost,
1492
- sessions,
1493
- mcpManager,
1494
- middlewareRunner,
1495
- promptBuilder
1496
- } = options;
1497
- const tools = forkOptions.tools ?? parentTools;
1498
- const childPrompt = resolveChildPromptConfig({
1499
- forkOptions,
1500
- promptBuilder,
1501
- parentPromptConfig: parentConfig.prompt,
1502
- parentSystemPrompt: parentConfig.systemPrompt
1503
- });
1522
+
1523
+ // src/agent/setup/state.ts
1524
+ function resolveInitialReasoningLevel(config) {
1525
+ const reasoningConfig = getReasoningConfigSync(config.model);
1526
+ const requestedLevel = config.reasoningLevel ?? "off";
1527
+ return reasoningConfig.availableLevels.includes(requestedLevel) ? requestedLevel : reasoningConfig.availableLevels[0];
1528
+ }
1529
+ function createAgentState(config) {
1504
1530
  return {
1505
- model: forkOptions.model ?? parentConfig.model,
1506
- cwd: parentConfig.cwd,
1507
- ...ownsHost ? {} : sandbox !== void 0 ? { sandbox } : { host },
1508
- ...humanInputController ? { humanInput: humanInputController } : {},
1509
- maxOutputTokens: parentConfig.maxOutputTokens,
1510
- maxSteps: forkOptions.maxSteps ?? parentConfig.maxSteps,
1511
- temperature: forkOptions.temperature ?? parentConfig.temperature,
1512
- topP: parentConfig.topP,
1513
- reasoningLevel: forkOptions.reasoningLevel ?? reasoningLevel,
1514
- ...childPrompt,
1515
- sessionManager: new SessionManager(sessions.getStorage()),
1516
- tools,
1517
- onDoomLoop: parentConfig.onDoomLoop,
1518
- enforceDoomLoop: parentConfig.enforceDoomLoop,
1519
- doomLoopThreshold: parentConfig.doomLoopThreshold,
1520
- compaction: parentConfig.compaction,
1521
- contextWindow: parentConfig.contextWindow,
1522
- mcp: mcpManager,
1523
- turnToolProviders: forkOptions.turnToolProviders ?? parentConfig.turnToolProviders,
1524
- middleware: resolveForkMiddleware(forkOptions, middlewareRunner)
1531
+ model: config.model,
1532
+ reasoningLevel: resolveInitialReasoningLevel(config)
1525
1533
  };
1526
1534
  }
1527
1535
 
1528
- // src/agent/mcp-bridge.ts
1529
- async function ensureMcpTools(state, logger) {
1530
- if (!state.manager) {
1531
- return { connected: false, cachedTools: void 0 };
1536
+ // src/agent/setup/tools.ts
1537
+ function createToolMap(tools) {
1538
+ const toolMap = /* @__PURE__ */ new Map();
1539
+ for (const tool of tools ?? []) {
1540
+ toolMap.set(tool.id, tool);
1532
1541
  }
1533
- if (state.connected && state.cachedTools) {
1534
- return {
1535
- connected: state.connected,
1536
- cachedTools: state.cachedTools
1537
- };
1542
+ return toolMap;
1543
+ }
1544
+ function createAgentTools(input) {
1545
+ const memory = resolveAgentMemoryConfig(input.memory);
1546
+ const tools = [...input.tools ?? []];
1547
+ if (memory?.tools.enabled) {
1548
+ tools.push(
1549
+ ...memory.provider.getTools?.({
1550
+ deferred: memory.tools.deferred
1551
+ }) ?? []
1552
+ );
1538
1553
  }
1539
- const log = logger.child("mcp");
1540
- const statuses = await state.manager.connect();
1541
- let connectedCount = 0;
1542
- for (const [name, status] of statuses) {
1543
- if (status.status === "connected") {
1544
- connectedCount++;
1545
- } else if (status.status === "error") {
1546
- log.warn(`Failed to connect to ${name}: ${status.error}`);
1554
+ return {
1555
+ tools: createToolMap(tools),
1556
+ ...memory ? { memoryProvider: memory.provider } : {}
1557
+ };
1558
+ }
1559
+
1560
+ // src/agent/setup.ts
1561
+ function createAgentSetup(input) {
1562
+ const promptBuilder = createAgentPromptBuilder(input);
1563
+ const config = createEffectiveAgentConfig(input);
1564
+ const middlewareSetup = createMiddlewareSetup(input, config);
1565
+ const toolSetup = createAgentTools(input);
1566
+ const humanInputSetup = resolveHumanInputController(input);
1567
+ const executionEnvironment = resolveExecutionEnvironment(input, config);
1568
+ const logger = input.logger ?? silentLogger;
1569
+ return {
1570
+ config,
1571
+ tools: toolSetup.tools,
1572
+ sessions: input.sessionManager ?? getDefaultSessionManager(),
1573
+ sessionTurnLock: input.sessionTurnLock ?? new LocalSessionTurnLock(),
1574
+ state: createAgentState(config),
1575
+ contextManager: createAgentContextWindowManager(config),
1576
+ turnTracker: createTurnTracker({ cwd: config.cwd }, logger),
1577
+ ...input.mcp ? { mcpManager: input.mcp } : {},
1578
+ turnToolProviders: [...input.turnToolProviders ?? []],
1579
+ ...promptBuilder ? { promptBuilder } : {},
1580
+ interventionCtrl: new InterventionController(),
1581
+ ...humanInputSetup,
1582
+ ...executionEnvironment,
1583
+ middlewareRunner: middlewareSetup.middlewareRunner,
1584
+ ...toolSetup.memoryProvider ? { memoryProvider: toolSetup.memoryProvider } : {},
1585
+ logger,
1586
+ ...middlewareSetup.telemetrySettings ? { telemetrySettings: middlewareSetup.telemetrySettings } : {},
1587
+ ...middlewareSetup.tracingShutdown ? { tracingShutdown: middlewareSetup.tracingShutdown } : {}
1588
+ };
1589
+ }
1590
+
1591
+ // src/agent/turn-context/compaction/budget.ts
1592
+ function normalizeTransientContextTokens(value) {
1593
+ if (!Number.isFinite(value) || value === void 0 || value <= 0) return 0;
1594
+ return Math.floor(value);
1595
+ }
1596
+ function reserveTransientContextBudget(limits, transientContextTokens) {
1597
+ if (transientContextTokens <= 0) return limits;
1598
+ const usableLimit = getUsableTokenLimit(limits);
1599
+ const transientUsableLimit = Math.max(
1600
+ 1,
1601
+ usableLimit - transientContextTokens
1602
+ );
1603
+ return {
1604
+ ...limits,
1605
+ contextWindow: transientUsableLimit + limits.reserveTokens,
1606
+ protectedTokens: Math.min(
1607
+ limits.protectedTokens,
1608
+ Math.max(1, Math.round(transientUsableLimit * 0.6))
1609
+ ),
1610
+ pruneMinimum: Math.min(
1611
+ limits.pruneMinimum,
1612
+ Math.max(1, Math.round(transientUsableLimit * 0.5))
1613
+ )
1614
+ };
1615
+ }
1616
+
1617
+ // src/agent/turn-context/compaction/fragments.ts
1618
+ function stripSummaryPreviewMessage(messages, summary) {
1619
+ if (!summary) return messages;
1620
+ const firstMessage = messages[0];
1621
+ if (firstMessage && extractCompactionSummaryText(firstMessage) === summary) {
1622
+ return messages.slice(1);
1623
+ }
1624
+ return messages;
1625
+ }
1626
+ function contextFragmentIdentity(message) {
1627
+ const metadata = getAgentContextFragmentMetadata(message);
1628
+ if (!metadata) return void 0;
1629
+ return metadata.dedupeKey ?? metadata.id;
1630
+ }
1631
+ function collectDurableContextFragments(removedMessages, keptMessages) {
1632
+ const keptIdentities = new Set(
1633
+ keptMessages.map(contextFragmentIdentity).filter((identity) => identity !== void 0)
1634
+ );
1635
+ const preserved = [];
1636
+ const preservedIdentities = /* @__PURE__ */ new Set();
1637
+ for (const message of removedMessages) {
1638
+ const metadata = getAgentContextFragmentMetadata(message);
1639
+ if (!metadata || metadata.lifetime !== "session") continue;
1640
+ const identity = contextFragmentIdentity(message);
1641
+ if (identity && (keptIdentities.has(identity) || preservedIdentities.has(identity))) {
1642
+ continue;
1547
1643
  }
1644
+ if (identity) {
1645
+ preservedIdentities.add(identity);
1646
+ }
1647
+ preserved.push(message);
1548
1648
  }
1549
- if (connectedCount === 0 && statuses.size > 0) {
1550
- log.warn("No MCP servers connected successfully");
1649
+ return preserved;
1650
+ }
1651
+
1652
+ // src/agent/turn-context/compaction/memory.ts
1653
+ async function prepareMemoryForCompaction(options) {
1654
+ if (!options.provider?.prepareForCompaction) return;
1655
+ if (options.removedMessages.length === 0) return;
1656
+ try {
1657
+ await options.provider.prepareForCompaction({
1658
+ sessionId: options.sessionId ?? "unknown",
1659
+ ...options.turnId ? { turnId: options.turnId } : {},
1660
+ cwd: options.cwd ?? process.cwd(),
1661
+ ...options.phase ? { phase: options.phase } : {},
1662
+ removedMessages: options.removedMessages,
1663
+ keptMessages: options.keptMessages,
1664
+ ...options.summary ? { summary: options.summary } : {},
1665
+ ...options.abort ? { abort: options.abort } : {}
1666
+ });
1667
+ } catch (error) {
1668
+ options.logger.warn("Memory provider compaction hook failed", {
1669
+ providerId: options.provider.id,
1670
+ error: error instanceof Error ? error.message : String(error)
1671
+ });
1551
1672
  }
1552
- const cachedTools = await state.manager.getTools();
1673
+ }
1674
+
1675
+ // src/agent/turn-context/compaction/results.ts
1676
+ function createUnchangedCompactionResult(options) {
1553
1677
  return {
1554
- connected: true,
1555
- cachedTools
1678
+ compacted: false,
1679
+ messages: [...options.messages],
1680
+ persistedMessages: [...options.messages],
1681
+ decision: options.decision,
1682
+ effectiveness: createCompactionEffectiveness(
1683
+ options.tokensBefore,
1684
+ options.tokensBefore
1685
+ ),
1686
+ displaySummary: false,
1687
+ storageSummary: "No context compaction was needed.",
1688
+ removedCount: 0,
1689
+ tokensRemoved: 0,
1690
+ summarized: false,
1691
+ summary: void 0,
1692
+ cutIndex: options.cutIndex,
1693
+ cutReason: options.cutReason,
1694
+ tokensBefore: options.tokensBefore,
1695
+ tokensAfter: options.tokensBefore,
1696
+ limit: options.limit
1556
1697
  };
1557
1698
  }
1558
- async function closeMcpManager(manager) {
1559
- if (manager) {
1560
- await manager.close();
1561
- }
1699
+ function createToolContextCompactionResult(options) {
1700
+ const { messages, tokensBefore } = options;
1701
+ const tokensAfter = estimateConversationTokens(messages);
1562
1702
  return {
1563
- connected: false,
1564
- cachedTools: void 0
1703
+ compacted: true,
1704
+ messages,
1705
+ persistedMessages: messages,
1706
+ decision: options.decision,
1707
+ effectiveness: createCompactionEffectiveness(tokensBefore, tokensAfter),
1708
+ displaySummary: false,
1709
+ storageSummary: "Large historical tool context was compacted.",
1710
+ removedCount: 0,
1711
+ tokensRemoved: Math.max(0, tokensBefore - tokensAfter),
1712
+ summarized: false,
1713
+ summary: void 0,
1714
+ cutIndex: 0,
1715
+ cutReason: void 0,
1716
+ tokensBefore,
1717
+ tokensAfter,
1718
+ limit: options.limit
1565
1719
  };
1566
1720
  }
1567
1721
 
1568
- // src/signal/local.ts
1569
- var LocalSignal = class {
1570
- /** type Set<handler> for typed subscriptions */
1571
- typed = /* @__PURE__ */ new Map();
1572
- /** handlers that receive every event */
1573
- wildcard = /* @__PURE__ */ new Set();
1574
- on(type, handler) {
1575
- let set = this.typed.get(type);
1576
- if (!set) {
1577
- set = /* @__PURE__ */ new Set();
1578
- this.typed.set(type, set);
1579
- }
1580
- const wrapped = (event) => {
1581
- handler(event);
1582
- };
1583
- set.add(wrapped);
1584
- return () => {
1585
- set.delete(wrapped);
1586
- if (set.size === 0) this.typed.delete(type);
1587
- };
1588
- }
1589
- onAny(handler) {
1590
- this.wildcard.add(handler);
1591
- return () => {
1592
- this.wildcard.delete(handler);
1593
- };
1722
+ // src/agent/turn-context/compaction/summary.ts
1723
+ function buildFallbackCompactionSummary(messages) {
1724
+ const serialized = serializeMessagesForSummary(messages, {
1725
+ maxInputTokens: 2e3,
1726
+ maxMessageTokens: 750
1727
+ });
1728
+ return serialized.length > 0 ? serialized : "Earlier conversation context was compacted.";
1729
+ }
1730
+
1731
+ // src/agent/turn-context/compaction/agent-context.ts
1732
+ async function compactAgentMessages(options) {
1733
+ const { contextManager, messages, logger, force = false } = options;
1734
+ const log = logger ?? silentLogger;
1735
+ const visibleMessages = [...messages];
1736
+ const baseLimits = contextManager.getLimits();
1737
+ const transientContextTokens = normalizeTransientContextTokens(
1738
+ options.transientContextTokens
1739
+ );
1740
+ const compactionLimits = reserveTransientContextBudget(
1741
+ baseLimits,
1742
+ transientContextTokens
1743
+ );
1744
+ const limit = getUsableTokenLimit(compactionLimits);
1745
+ const tokensBefore = estimateConversationTokens(visibleMessages);
1746
+ const summaryPolicy = contextManager.getSummaryPolicy();
1747
+ const canSummarize = canGenerateCompactionSummary(summaryPolicy);
1748
+ const initialDecision = decideContextCompaction(visibleMessages, {
1749
+ limits: baseLimits,
1750
+ force,
1751
+ canSummarize,
1752
+ inputTokens: tokensBefore + transientContextTokens
1753
+ });
1754
+ if (!force && !initialDecision.needed) {
1755
+ return createUnchangedCompactionResult({
1756
+ messages: visibleMessages,
1757
+ decision: initialDecision,
1758
+ tokensBefore,
1759
+ limit: getUsableTokenLimit(baseLimits)
1760
+ });
1594
1761
  }
1595
- emit(event) {
1596
- const set = this.typed.get(event.type);
1597
- if (set) {
1598
- for (const fn of set) {
1599
- try {
1600
- fn(event);
1601
- } catch {
1602
- }
1603
- }
1762
+ let removedCount = 0;
1763
+ let summarized = false;
1764
+ let summary;
1765
+ let cutIndex;
1766
+ let cutReason;
1767
+ const decision = initialDecision;
1768
+ let prunedMessages;
1769
+ let pruneTokensRemoved = 0;
1770
+ let keptMessagesFromPrune;
1771
+ let fallbackRemovedMessages;
1772
+ let fallbackKeptMessages;
1773
+ try {
1774
+ const result = await pruneContext(visibleMessages, {
1775
+ limits: compactionLimits,
1776
+ summary: summaryPolicy,
1777
+ force
1778
+ });
1779
+ removedCount = result.removedCount;
1780
+ pruneTokensRemoved = result.effectiveness.tokensRemoved;
1781
+ summarized = result.summarized;
1782
+ summary = result.summary;
1783
+ cutIndex = result.cutIndex;
1784
+ cutReason = result.cutReason;
1785
+ prunedMessages = result.messages;
1786
+ fallbackRemovedMessages = result.removedMessages;
1787
+ if (removedCount > 0) {
1788
+ keptMessagesFromPrune = stripSummaryPreviewMessage(
1789
+ result.messages,
1790
+ summary
1791
+ );
1792
+ fallbackKeptMessages = result.keptMessages;
1604
1793
  }
1605
- for (const fn of this.wildcard) {
1606
- try {
1607
- fn(event);
1608
- } catch {
1609
- }
1794
+ } catch (pruneError) {
1795
+ if (!shouldFallbackOnSummaryFailure({ policy: summaryPolicy, force })) {
1796
+ throw pruneError;
1610
1797
  }
1798
+ log.warn("Context compaction LLM summarisation failed, using fallback", {
1799
+ error: pruneError instanceof Error ? pruneError.message : String(pruneError)
1800
+ });
1611
1801
  }
1612
- clear() {
1613
- this.typed.clear();
1614
- this.wildcard.clear();
1802
+ if (removedCount === 0 && prunedMessages && pruneTokensRemoved > 0 && !decideContextCompaction(prunedMessages, {
1803
+ limits: compactionLimits,
1804
+ canSummarize
1805
+ }).needed) {
1806
+ return createToolContextCompactionResult({
1807
+ messages: prunedMessages,
1808
+ decision,
1809
+ tokensBefore,
1810
+ limit
1811
+ });
1615
1812
  }
1616
- };
1617
-
1618
- // src/human/controller.ts
1619
- var HumanInputTimeoutError = class extends Error {
1620
- constructor(timeoutMs) {
1621
- super(`Human input request timed out after ${timeoutMs}ms`);
1622
- this.name = "HumanInputTimeoutError";
1813
+ if (removedCount === 0) {
1814
+ const fallbackMessages = prunedMessages ?? visibleMessages;
1815
+ const fallbackPlan = planCompactionCut(
1816
+ fallbackMessages,
1817
+ compactionLimits.protectedTokens,
1818
+ {
1819
+ allowSplitTurn: summaryPolicy.mode !== "disabled",
1820
+ maxKeptTokens: getUsableTokenLimit(compactionLimits)
1821
+ }
1822
+ );
1823
+ removedCount = fallbackPlan.cutIndex;
1824
+ cutIndex = fallbackPlan.cutIndex;
1825
+ cutReason = fallbackPlan.reason;
1826
+ fallbackRemovedMessages = fallbackPlan.removedMessages;
1827
+ fallbackKeptMessages = fallbackPlan.keptMessages;
1623
1828
  }
1624
- };
1625
- var HumanInputUnavailableError = class extends Error {
1626
- constructor() {
1627
- super("No human input controller configured");
1628
- this.name = "HumanInputUnavailableError";
1829
+ if (removedCount === 0) {
1830
+ if (prunedMessages && pruneTokensRemoved > 0) {
1831
+ return createToolContextCompactionResult({
1832
+ messages: prunedMessages,
1833
+ decision,
1834
+ tokensBefore,
1835
+ limit
1836
+ });
1837
+ }
1838
+ return createUnchangedCompactionResult({
1839
+ messages: visibleMessages,
1840
+ decision,
1841
+ tokensBefore,
1842
+ limit,
1843
+ cutIndex,
1844
+ cutReason
1845
+ });
1629
1846
  }
1630
- };
1631
- function cloneRecord(record) {
1632
- return structuredClone(record);
1633
- }
1634
- function normalizeStatuses(status) {
1635
- if (!status) {
1636
- return void 0;
1847
+ const removedMessages = fallbackRemovedMessages ?? visibleMessages.slice(0, removedCount);
1848
+ const keptMessages = keptMessagesFromPrune ?? fallbackKeptMessages ?? visibleMessages.slice(removedCount);
1849
+ const preservedContextFragments = collectDurableContextFragments(
1850
+ removedMessages,
1851
+ keptMessages
1852
+ );
1853
+ if (summaryPolicy.mode === "disabled" && !summary) {
1854
+ const persistedMessages2 = [...preservedContextFragments, ...keptMessages];
1855
+ const tokensAfter2 = estimateConversationTokens(persistedMessages2);
1856
+ await prepareMemoryForCompaction({
1857
+ provider: options.memoryProvider,
1858
+ sessionId: options.sessionId,
1859
+ turnId: options.turnId,
1860
+ cwd: options.cwd,
1861
+ abort: options.abort,
1862
+ phase: options.phase,
1863
+ removedMessages,
1864
+ keptMessages,
1865
+ logger: log
1866
+ });
1867
+ return {
1868
+ compacted: true,
1869
+ messages: persistedMessages2,
1870
+ persistedMessages: persistedMessages2,
1871
+ decision,
1872
+ effectiveness: createCompactionEffectiveness(tokensBefore, tokensAfter2),
1873
+ displaySummary: false,
1874
+ storageSummary: "Conversation history was compacted without a summary.",
1875
+ removedCount,
1876
+ tokensRemoved: Math.max(0, tokensBefore - tokensAfter2),
1877
+ summarized: false,
1878
+ summary: void 0,
1879
+ cutIndex,
1880
+ cutReason,
1881
+ tokensBefore,
1882
+ tokensAfter: tokensAfter2,
1883
+ limit
1884
+ };
1637
1885
  }
1638
- return new Set(Array.isArray(status) ? status : [status]);
1886
+ const summaryText = summary ?? buildFallbackCompactionSummary(removedMessages);
1887
+ const persistedMessages = [...preservedContextFragments, ...keptMessages];
1888
+ const summaryMessage = {
1889
+ id: crypto.randomUUID(),
1890
+ role: "system",
1891
+ content: createCompactionSummaryContent(summaryText),
1892
+ createdAt: /* @__PURE__ */ new Date()
1893
+ };
1894
+ const messagesWithSummary = [
1895
+ summaryMessage,
1896
+ ...preservedContextFragments,
1897
+ ...keptMessages
1898
+ ];
1899
+ const tokensAfter = estimateConversationTokens(messagesWithSummary);
1900
+ await prepareMemoryForCompaction({
1901
+ provider: options.memoryProvider,
1902
+ sessionId: options.sessionId,
1903
+ turnId: options.turnId,
1904
+ cwd: options.cwd,
1905
+ abort: options.abort,
1906
+ phase: options.phase,
1907
+ removedMessages,
1908
+ keptMessages,
1909
+ summary: summaryText,
1910
+ logger: log
1911
+ });
1912
+ return {
1913
+ compacted: true,
1914
+ messages: messagesWithSummary,
1915
+ persistedMessages,
1916
+ decision,
1917
+ effectiveness: createCompactionEffectiveness(tokensBefore, tokensAfter),
1918
+ displaySummary: true,
1919
+ storageSummary: summaryText,
1920
+ removedCount,
1921
+ tokensRemoved: Math.max(0, tokensBefore - tokensAfter),
1922
+ summarized,
1923
+ summary: summaryText,
1924
+ cutIndex,
1925
+ cutReason,
1926
+ tokensBefore,
1927
+ tokensAfter,
1928
+ limit
1929
+ };
1639
1930
  }
1640
- function inferKind(input) {
1641
- if (input.kind) {
1642
- return input.kind;
1931
+ async function compactAgentContext(options) {
1932
+ const result = await compactAgentMessages({
1933
+ contextManager: options.contextManager,
1934
+ messages: getVisibleSessionMessages(options.sessions),
1935
+ logger: options.logger,
1936
+ force: options.force,
1937
+ memoryProvider: options.memoryProvider,
1938
+ sessionId: options.sessionId ?? options.sessions.getSessionId() ?? void 0,
1939
+ turnId: options.turnId,
1940
+ cwd: options.cwd ?? options.sessions.getHeader()?.cwd,
1941
+ abort: options.abort,
1942
+ phase: options.phase,
1943
+ transientContextTokens: options.transientContextTokens
1944
+ });
1945
+ if (result.compacted) {
1946
+ await options.sessions.replaceWithCompaction({
1947
+ summary: result.storageSummary,
1948
+ displaySummary: result.displaySummary,
1949
+ messages: result.persistedMessages,
1950
+ tokensBefore: result.tokensBefore,
1951
+ tokensAfter: result.tokensAfter
1952
+ });
1643
1953
  }
1644
- if (input.options && input.options.length > 0) {
1645
- return "choice";
1646
- }
1647
- return "text";
1648
- }
1649
- function isHumanInputController(value) {
1650
- if (!value || typeof value !== "object") {
1651
- return false;
1652
- }
1653
- const candidate = value;
1654
- return typeof candidate.request === "function" && typeof candidate.respondToRequest === "function" && typeof candidate.getRequest === "function" && typeof candidate.listRequests === "function" && typeof candidate.cancelAll === "function";
1655
- }
1656
- async function emitHumanInputEvent(context, event) {
1657
- await context?.emitEvent?.(event);
1954
+ return {
1955
+ removedCount: result.removedCount,
1956
+ decision: result.decision,
1957
+ effectiveness: result.effectiveness,
1958
+ tokensRemoved: result.tokensRemoved,
1959
+ summarized: result.summarized,
1960
+ summary: result.summary,
1961
+ cutIndex: result.cutIndex,
1962
+ cutReason: result.cutReason
1963
+ };
1658
1964
  }
1659
- function createHumanInputController(config = {}) {
1660
- const timeout = config.timeout ?? 5 * 60 * 1e3;
1661
- let requestCounter = 0;
1662
- const pending = /* @__PURE__ */ new Map();
1663
- async function request(sessionId, input, context = {}) {
1664
- const requestPayload = {
1665
- id: `human-input-${++requestCounter}-${Date.now()}`,
1666
- sessionId,
1667
- kind: inferKind(input),
1668
- title: input.title,
1669
- question: input.question,
1670
- ...input.options ? { options: input.options.map((option) => ({ ...option })) } : {},
1671
- ...input.allowMultiple !== void 0 ? { allowMultiple: input.allowMultiple } : {},
1672
- ...input.placeholder ? { placeholder: input.placeholder } : {},
1673
- ...input.confirmLabel ? { confirmLabel: input.confirmLabel } : {},
1674
- ...input.denyLabel ? { denyLabel: input.denyLabel } : {},
1675
- ...input.toolCallId ? { toolCallId: input.toolCallId } : {},
1676
- timestamp: Date.now()
1677
- };
1678
- const record = {
1679
- id: requestPayload.id,
1680
- sessionId,
1681
- request: structuredClone(requestPayload),
1682
- status: "pending",
1683
- createdAt: requestPayload.timestamp,
1684
- updatedAt: requestPayload.timestamp
1685
- };
1686
- const responsePromise = new Promise(
1687
- (resolve2, reject) => {
1688
- const timeoutId = setTimeout(() => {
1689
- const current2 = pending.get(record.id);
1690
- if (!current2) {
1691
- return;
1692
- }
1693
- pending.delete(record.id);
1694
- current2.record = {
1695
- ...current2.record,
1696
- status: "timed-out",
1697
- updatedAt: Date.now()
1698
- };
1699
- void emitHumanInputEvent(
1700
- { emitEvent: current2.emitEvent },
1701
- { type: "status", status: "processing" }
1702
- );
1703
- reject(new HumanInputTimeoutError(timeout));
1704
- }, timeout);
1705
- pending.set(record.id, {
1706
- record,
1707
- resolve: resolve2,
1708
- reject,
1709
- ready: Promise.resolve(),
1710
- timeoutId,
1711
- emitEvent: context.emitEvent
1712
- });
1965
+
1966
+ // src/agent/turn-context/compaction/check.ts
1967
+ async function runCompactionCheck(params) {
1968
+ const {
1969
+ contextManager,
1970
+ sessions,
1971
+ logger,
1972
+ force = false,
1973
+ phase,
1974
+ sessionId,
1975
+ turnId,
1976
+ cwd,
1977
+ abort,
1978
+ memoryProvider,
1979
+ retryAttempt,
1980
+ transientContextTokens
1981
+ } = params;
1982
+ const messages = sessions.getMessages();
1983
+ const limits = contextManager.getLimits();
1984
+ const transientTokens = Number.isFinite(transientContextTokens) && transientContextTokens ? Math.max(0, Math.floor(transientContextTokens)) : 0;
1985
+ const inputTokens = estimateConversationTokens(messages) + transientTokens;
1986
+ const limit = getUsableTokenLimit(limits);
1987
+ const decision = contextManager.decide(messages, {
1988
+ force,
1989
+ inputTokens
1990
+ });
1991
+ if (!force && !decision.needed) {
1992
+ return {
1993
+ events: [],
1994
+ compacted: false,
1995
+ inputTokens,
1996
+ limit,
1997
+ report: {
1998
+ applied: false,
1999
+ phase,
2000
+ inputTokens,
2001
+ limit,
2002
+ decision,
2003
+ effectiveness: createCompactionEffectiveness(inputTokens, inputTokens),
2004
+ removedCount: 0,
2005
+ tokensRemoved: 0,
2006
+ summarized: false
1713
2007
  }
1714
- );
1715
- const current = pending.get(record.id);
1716
- if (current) {
1717
- current.ready = (async () => {
1718
- await emitHumanInputEvent(context, {
1719
- type: "status",
1720
- status: "waiting-input"
1721
- });
1722
- await emitHumanInputEvent(context, {
1723
- type: "human-input-request",
1724
- request: {
1725
- id: requestPayload.id,
1726
- kind: requestPayload.kind,
1727
- title: requestPayload.title,
1728
- question: requestPayload.question,
1729
- ...requestPayload.options ? { options: requestPayload.options } : {},
1730
- ...requestPayload.allowMultiple !== void 0 ? { allowMultiple: requestPayload.allowMultiple } : {},
1731
- ...requestPayload.placeholder ? { placeholder: requestPayload.placeholder } : {},
1732
- ...requestPayload.confirmLabel ? { confirmLabel: requestPayload.confirmLabel } : {},
1733
- ...requestPayload.denyLabel ? { denyLabel: requestPayload.denyLabel } : {}
1734
- }
1735
- });
1736
- })();
1737
- }
1738
- if (config.onRequest) {
1739
- void (async () => {
1740
- try {
1741
- await pending.get(record.id)?.ready;
1742
- const response = await config.onRequest(requestPayload);
1743
- await respondToRequest(record.id, response, context);
1744
- } catch (error) {
1745
- if (error instanceof HumanInputTimeoutError) {
1746
- return;
1747
- }
1748
- const current2 = pending.get(record.id);
1749
- if (!current2) {
1750
- return;
1751
- }
1752
- pending.delete(record.id);
1753
- clearTimeout(current2.timeoutId);
1754
- current2.record = {
1755
- ...current2.record,
1756
- status: "cancelled",
1757
- updatedAt: Date.now()
1758
- };
1759
- current2.reject(
1760
- error instanceof Error ? error : new Error(String(error))
1761
- );
1762
- await emitHumanInputEvent(
1763
- { emitEvent: current2.emitEvent },
1764
- { type: "status", status: "processing" }
1765
- );
1766
- }
1767
- })();
1768
- }
1769
- return await responsePromise;
1770
- }
1771
- async function respondToRequest(requestId, response, context = {}) {
1772
- const current = pending.get(requestId);
1773
- if (!current) {
1774
- throw new Error(`Human input request not found: ${requestId}`);
1775
- }
1776
- await current.ready;
1777
- pending.delete(requestId);
1778
- clearTimeout(current.timeoutId);
1779
- const respondedAt = Date.now();
1780
- const next = {
1781
- ...current.record,
1782
- status: "answered",
1783
- updatedAt: respondedAt,
1784
- respondedAt,
1785
- response: structuredClone(response)
1786
2008
  };
1787
- current.resolve(response);
1788
- const emitEvent = context.emitEvent ?? current.emitEvent;
1789
- await emitHumanInputEvent(
1790
- { emitEvent },
1791
- {
1792
- type: "human-input-resolved",
1793
- id: requestId,
1794
- response
1795
- }
1796
- );
1797
- await emitHumanInputEvent(
1798
- { emitEvent },
1799
- { type: "status", status: "processing" }
1800
- );
1801
- return cloneRecord(next);
1802
- }
1803
- function getRequest(requestId) {
1804
- const current = pending.get(requestId);
1805
- return current ? cloneRecord(current.record) : void 0;
1806
- }
1807
- function listRequests(options = {}) {
1808
- const statuses = normalizeStatuses(options.status);
1809
- return [...pending.values()].map((entry) => cloneRecord(entry.record)).filter((record) => {
1810
- if (options.sessionId && record.sessionId !== options.sessionId) {
1811
- return false;
1812
- }
1813
- if (statuses && !statuses.has(record.status)) {
1814
- return false;
1815
- }
1816
- return true;
1817
- }).sort((left, right) => left.createdAt - right.createdAt);
1818
2009
  }
1819
- function cancelAll(reason = "Cancelled") {
1820
- for (const [requestId, current] of pending) {
1821
- pending.delete(requestId);
1822
- clearTimeout(current.timeoutId);
1823
- current.record = {
1824
- ...current.record,
1825
- status: "cancelled",
1826
- updatedAt: Date.now()
2010
+ const events = [{ type: "status", status: "processing" }];
2011
+ try {
2012
+ const pruneResult = await compactAgentContext({
2013
+ contextManager,
2014
+ sessions,
2015
+ logger,
2016
+ force,
2017
+ sessionId,
2018
+ turnId,
2019
+ cwd,
2020
+ abort,
2021
+ memoryProvider,
2022
+ phase,
2023
+ transientContextTokens: transientTokens
2024
+ });
2025
+ if (pruneResult.removedCount > 0 || pruneResult.summarized || pruneResult.tokensRemoved > 0) {
2026
+ events.push({
2027
+ type: "context-compaction",
2028
+ phase,
2029
+ inputTokens,
2030
+ limit,
2031
+ decision: pruneResult.decision,
2032
+ effectiveness: pruneResult.effectiveness,
2033
+ removedCount: pruneResult.removedCount,
2034
+ tokensRemoved: pruneResult.tokensRemoved,
2035
+ summarized: pruneResult.summarized,
2036
+ ...pruneResult.cutReason ? { cutReason: pruneResult.cutReason } : {},
2037
+ ...retryAttempt !== void 0 ? { retryAttempt } : {}
2038
+ });
2039
+ events.push({
2040
+ type: "context-overflow",
2041
+ inputTokens,
2042
+ limit
2043
+ });
2044
+ return {
2045
+ events,
2046
+ compacted: true,
2047
+ inputTokens,
2048
+ limit,
2049
+ report: {
2050
+ applied: true,
2051
+ phase,
2052
+ inputTokens,
2053
+ limit,
2054
+ decision: pruneResult.decision,
2055
+ effectiveness: pruneResult.effectiveness,
2056
+ removedCount: pruneResult.removedCount,
2057
+ tokensRemoved: pruneResult.tokensRemoved,
2058
+ summarized: pruneResult.summarized,
2059
+ ...pruneResult.cutIndex !== void 0 ? { cutIndex: pruneResult.cutIndex } : {},
2060
+ ...pruneResult.cutReason ? { cutReason: pruneResult.cutReason } : {}
2061
+ }
1827
2062
  };
1828
- current.reject(new Error(reason));
1829
- void emitHumanInputEvent(
1830
- { emitEvent: current.emitEvent },
1831
- { type: "status", status: "processing" }
1832
- );
1833
2063
  }
2064
+ } catch (error) {
2065
+ logger?.warn("Context compaction failed, continuing without compaction", {
2066
+ error: error instanceof Error ? error.message : String(error),
2067
+ phase
2068
+ });
1834
2069
  }
1835
2070
  return {
1836
- get hasPendingRequests() {
1837
- return pending.size > 0;
1838
- },
1839
- request,
1840
- respondToRequest,
1841
- getRequest,
1842
- listRequests,
1843
- cancelAll
2071
+ events,
2072
+ compacted: false,
2073
+ inputTokens,
2074
+ limit,
2075
+ report: {
2076
+ applied: false,
2077
+ phase,
2078
+ inputTokens,
2079
+ limit,
2080
+ decision,
2081
+ effectiveness: createCompactionEffectiveness(inputTokens, inputTokens),
2082
+ removedCount: 0,
2083
+ tokensRemoved: 0,
2084
+ summarized: false
2085
+ }
1844
2086
  };
1845
2087
  }
1846
-
1847
- // src/human/handler.ts
1848
- function createHumanInputHandler(config = {}) {
1849
- return createHumanInputController(config);
2088
+ async function runAutoCompaction(params) {
2089
+ const result = await runCompactionCheck({
2090
+ ...params,
2091
+ phase: "post-turn"
2092
+ });
2093
+ return result.events;
1850
2094
  }
1851
2095
 
1852
- // src/human/tool.ts
1853
- import { z } from "zod";
1854
- function createHumanInputTool(options = {}) {
1855
- if (options.controller) {
1856
- return createHumanInputToolWithController(options.controller, options);
2096
+ // src/agent/turn-context/fit-model-context.ts
2097
+ function resolveConfiguredFragmentBudget(context) {
2098
+ const maxEstimatedTokens = context?.maxEstimatedFragmentTokens;
2099
+ if (maxEstimatedTokens === void 0 || !Number.isFinite(maxEstimatedTokens)) {
2100
+ return void 0;
1857
2101
  }
1858
- if (options.onRequest || options.timeout !== void 0) {
1859
- return createHumanInputToolWithController(
1860
- createHumanInputController(options),
1861
- options
2102
+ return {
2103
+ maxEstimatedTokens: Math.max(0, Math.floor(maxEstimatedTokens))
2104
+ };
2105
+ }
2106
+ async function assembleChatModelContextToFit(params) {
2107
+ let compactionReport = params.compactionReport;
2108
+ const events = [];
2109
+ let assembledContext;
2110
+ const contextFragmentBudget = resolveConfiguredFragmentBudget(params.context);
2111
+ for (let attempt = 0; ; attempt++) {
2112
+ assembledContext = await assembleModelContext({
2113
+ sessionId: params.sessionId,
2114
+ turnId: params.turnId,
2115
+ step: params.step,
2116
+ cwd: params.cwd,
2117
+ messages: params.sessions.getMessages(),
2118
+ toolNames: params.toolNames,
2119
+ mcpToolNames: params.mcpToolNames,
2120
+ ...params.abort ? { abort: params.abort } : {},
2121
+ contextFragmentCollector: params.middlewareRunner,
2122
+ window: params.contextManager,
2123
+ ...contextFragmentBudget ? { contextFragmentBudget } : {},
2124
+ ...compactionReport ? { compaction: compactionReport } : {}
2125
+ });
2126
+ const windowBefore = assembledContext.report.window.before;
2127
+ const windowAfter = assembledContext.report.window.after;
2128
+ if (!params.fitAssembledContext || attempt > 0 || !windowAfter?.shouldPrune) {
2129
+ break;
2130
+ }
2131
+ const transientContextTokens = Math.max(
2132
+ 0,
2133
+ windowAfter.tokens - (windowBefore?.tokens ?? 0)
1862
2134
  );
2135
+ const compaction = await runCompactionCheck({
2136
+ contextManager: params.contextManager,
2137
+ sessions: params.sessions,
2138
+ logger: params.logger,
2139
+ force: true,
2140
+ phase: "pre-step",
2141
+ sessionId: params.sessionId,
2142
+ turnId: params.turnId,
2143
+ cwd: params.cwd,
2144
+ ...params.abort ? { abort: params.abort } : {},
2145
+ memoryProvider: params.memoryProvider,
2146
+ transientContextTokens
2147
+ });
2148
+ events.push(...compaction.events);
2149
+ if (!compaction.compacted) {
2150
+ break;
2151
+ }
2152
+ compactionReport = compaction.report;
1863
2153
  }
1864
- return createHumanInputToolWithController(void 0, options);
2154
+ return { assembledContext, events };
1865
2155
  }
1866
- function createHumanInputToolWithController(controller, options = {}) {
1867
- return Tool.define(
1868
- options.name ?? "question",
1869
- {
1870
- description: options.description ?? "Ask a human for missing input, a decision, a confirmation, or a choice.",
1871
- parameters: z.object({
1872
- title: z.string().min(1).describe("Short heading for the request"),
1873
- question: z.string().min(1).describe("What to ask the human"),
1874
- kind: z.enum(["text", "confirm", "choice"]).optional(),
1875
- options: z.array(
1876
- z.object({
1877
- label: z.string().min(1),
1878
- value: z.string().optional(),
1879
- description: z.string().optional()
1880
- })
1881
- ).optional(),
1882
- allowMultiple: z.boolean().optional(),
1883
- placeholder: z.string().optional(),
1884
- confirmLabel: z.string().optional(),
1885
- denyLabel: z.string().optional()
1886
- }),
1887
- validate: (params) => {
1888
- const kind = params.kind ?? (params.options?.length ? "choice" : "text");
1889
- if (kind === "choice" && (!params.options || params.options.length === 0)) {
1890
- return {
1891
- ok: false,
1892
- reason: "Choice requests must include at least one option."
1893
- };
2156
+
2157
+ // src/agent/turn-context/system-prompts.ts
2158
+ async function buildAgentSystemPrompts(options) {
2159
+ const {
2160
+ config,
2161
+ toolIds,
2162
+ sessionId,
2163
+ override,
2164
+ promptBuilder,
2165
+ middlewareRunner
2166
+ } = options;
2167
+ if (promptBuilder) {
2168
+ const composedPrompt = await promptBuilder.build(
2169
+ {
2170
+ cwd: config.cwd,
2171
+ model: config.model,
2172
+ toolNames: toolIds,
2173
+ ...override ? { override } : {},
2174
+ sessionId
2175
+ },
2176
+ middlewareRunner
2177
+ );
2178
+ return [composedPrompt];
2179
+ }
2180
+ const prompts = [config.systemPrompt];
2181
+ if (override) {
2182
+ prompts.push(override);
2183
+ }
2184
+ return prompts;
2185
+ }
2186
+
2187
+ // src/agent/setup/runtime-config.ts
2188
+ function createAgentTurnRuntimeConfig(options) {
2189
+ const { config, telemetrySettings } = options;
2190
+ return {
2191
+ model: config.model,
2192
+ cwd: config.cwd,
2193
+ ...config.temperature !== void 0 ? { temperature: config.temperature } : {},
2194
+ ...config.topP !== void 0 ? { topP: config.topP } : {},
2195
+ ...config.maxOutputTokens !== void 0 ? { maxOutputTokens: config.maxOutputTokens } : {},
2196
+ maxSteps: config.maxSteps,
2197
+ ...config.doomLoopThreshold !== void 0 ? { doomLoopThreshold: config.doomLoopThreshold } : {},
2198
+ ...config.enforceDoomLoop !== void 0 ? { enforceDoomLoop: config.enforceDoomLoop } : {},
2199
+ ...config.onDoomLoop ? { onDoomLoop: config.onDoomLoop } : {},
2200
+ ...config.contextWindow !== void 0 ? { contextWindow: config.contextWindow } : {},
2201
+ ...options.reserveTokens !== void 0 ? { reserveTokens: options.reserveTokens } : {},
2202
+ ...config.streamProvider ? { streamProvider: config.streamProvider } : {},
2203
+ ...telemetrySettings ? { telemetry: telemetrySettings } : {}
2204
+ };
2205
+ }
2206
+
2207
+ // src/agent/instance/sessions.ts
2208
+ function createAgentSessionManager(sessions) {
2209
+ return new SessionManager(sessions.getStorage());
2210
+ }
2211
+ async function acquireAgentSessionLock(lock, sessionId, options) {
2212
+ return await lock.acquire(sessionId, options);
2213
+ }
2214
+ async function syncAgentSessionView(options) {
2215
+ const { sessions, sessionId } = options;
2216
+ if (!await sessions.sessionExists(sessionId)) {
2217
+ return;
2218
+ }
2219
+ await sessions.load(sessionId);
2220
+ }
2221
+
2222
+ // src/agent/instance/interventions.ts
2223
+ function getActiveAgentInterventionController(activeTurns) {
2224
+ const active = Array.from(activeTurns.values());
2225
+ if (active.length === 0) {
2226
+ return void 0;
2227
+ }
2228
+ if (active.length > 1) {
2229
+ throw new Error(
2230
+ "Interventions are ambiguous while multiple agent turns are active. Use separate Agent instances or wait for one turn to finish."
2231
+ );
2232
+ }
2233
+ return active[0].interventionCtrl;
2234
+ }
2235
+ function getAgentInterventionControllerForTurn(activeTurns, fallback) {
2236
+ return getActiveAgentInterventionController(activeTurns) ?? fallback;
2237
+ }
2238
+ function createAgentTurnInterventionController(activeTurns, fallback) {
2239
+ return activeTurns.size === 0 ? fallback : new InterventionController();
2240
+ }
2241
+ function releaseAgentTurnInterventions(fallback, controller) {
2242
+ if (controller === fallback) {
2243
+ controller.resetCallbacks();
2244
+ return;
2245
+ }
2246
+ fallback.adoptImmediate(controller.drainImmediate());
2247
+ fallback.adoptDeferred(controller.drainDeferred());
2248
+ controller.resetCallbacks();
2249
+ }
2250
+
2251
+ // src/agent/instance/mcp.ts
2252
+ async function ensureAgentMcpTools(state, logger) {
2253
+ if (!state.manager) {
2254
+ return { connected: false, cachedTools: void 0 };
2255
+ }
2256
+ if (state.connected && state.cachedTools) {
2257
+ return {
2258
+ connected: state.connected,
2259
+ cachedTools: state.cachedTools
2260
+ };
2261
+ }
2262
+ const log = logger.child("mcp");
2263
+ const statuses = await state.manager.connect();
2264
+ let connectedCount = 0;
2265
+ for (const [name, status] of statuses) {
2266
+ if (status.status === "connected") {
2267
+ connectedCount++;
2268
+ } else if (status.status === "error") {
2269
+ log.warn(`Failed to connect to ${name}: ${status.error}`);
2270
+ }
2271
+ }
2272
+ if (connectedCount === 0 && statuses.size > 0) {
2273
+ log.warn("No MCP servers connected successfully");
2274
+ }
2275
+ const cachedTools = await state.manager.getTools();
2276
+ return {
2277
+ connected: true,
2278
+ cachedTools
2279
+ };
2280
+ }
2281
+ async function reconnectAgentMcp(state, logger) {
2282
+ if (!state.manager) {
2283
+ return { connected: false, cachedTools: void 0 };
2284
+ }
2285
+ await state.manager.close();
2286
+ return await ensureAgentMcpTools(
2287
+ {
2288
+ manager: state.manager,
2289
+ connected: false,
2290
+ cachedTools: void 0
2291
+ },
2292
+ logger
2293
+ );
2294
+ }
2295
+ async function closeAgentMcp(manager) {
2296
+ if (manager) {
2297
+ await manager.close();
2298
+ }
2299
+ return {
2300
+ connected: false,
2301
+ cachedTools: void 0
2302
+ };
2303
+ }
2304
+
2305
+ // src/agent/instance/context-management.ts
2306
+ function getAgentContextStats(options) {
2307
+ return options.contextManager.getStats(options.sessions.getMessages());
2308
+ }
2309
+ async function compactLoadedAgentContext(options) {
2310
+ return await compactAgentContext(options);
2311
+ }
2312
+ async function compactAgentMessageList(options) {
2313
+ return await compactAgentMessages(options);
2314
+ }
2315
+
2316
+ // src/agent/instance/tools.ts
2317
+ async function ensureAgentSkillTools(options) {
2318
+ if (options.resolved || !options.promptBuilder) {
2319
+ return options.resolved;
2320
+ }
2321
+ const registry = await options.promptBuilder.getSkillRegistry(options.cwd);
2322
+ for (const tool of createSkillTools(registry)) {
2323
+ if (!options.tools.has(tool.id)) {
2324
+ options.tools.set(tool.id, tool);
2325
+ }
2326
+ }
2327
+ return true;
2328
+ }
2329
+ function resetPromptScopedTools(tools) {
2330
+ tools.delete("skill");
2331
+ tools.delete("skill_resource");
2332
+ }
2333
+ function addAgentTool(tools, tool) {
2334
+ tools.set(tool.id, tool);
2335
+ }
2336
+ function removeAgentTool(tools, toolId) {
2337
+ return tools.delete(toolId);
2338
+ }
2339
+ function getAgentToolIds(tools) {
2340
+ return Array.from(tools.keys());
2341
+ }
2342
+ function getAgentTools(tools) {
2343
+ return Array.from(tools.values());
2344
+ }
2345
+ function hasAgentTool(tools, toolId) {
2346
+ return tools.has(toolId);
2347
+ }
2348
+ function hasAgentHumanInputTools(tools) {
2349
+ return [...tools.values()].some(
2350
+ (tool) => tool.capabilitiesHint?.humanInput === true
2351
+ );
2352
+ }
2353
+
2354
+ // src/agent/fork.ts
2355
+ function resolveForkOptions(options, parentTools, systemPrompt) {
2356
+ if (!options.profile) {
2357
+ return options;
2358
+ }
2359
+ const applied = applyProfile(options.profile, parentTools, systemPrompt);
2360
+ return {
2361
+ ...applied,
2362
+ ...options,
2363
+ tools: options.tools ?? applied.tools
2364
+ };
2365
+ }
2366
+ function resolveChildPromptConfig(options) {
2367
+ const { forkOptions, promptBuilder, parentPromptConfig, parentSystemPrompt } = options;
2368
+ if (forkOptions.systemPrompt) {
2369
+ return { systemPrompt: forkOptions.systemPrompt };
2370
+ }
2371
+ if (forkOptions.prompt) {
2372
+ return { prompt: forkOptions.prompt };
2373
+ }
2374
+ if (promptBuilder) {
2375
+ return { prompt: parentPromptConfig ?? {} };
2376
+ }
2377
+ return { systemPrompt: parentSystemPrompt };
2378
+ }
2379
+ function resolveForkMiddleware(options, middlewareRunner) {
2380
+ if (options.middleware) {
2381
+ return options.middleware;
2382
+ }
2383
+ if (options.additionalMiddleware) {
2384
+ return [
2385
+ ...middlewareRunner.getMiddleware(),
2386
+ ...options.additionalMiddleware
2387
+ ];
2388
+ }
2389
+ return [...middlewareRunner.getMiddleware()];
2390
+ }
2391
+ function createForkedAgentConfig(options) {
2392
+ const {
2393
+ forkOptions,
2394
+ parentConfig,
2395
+ parentTools,
2396
+ reasoningLevel,
2397
+ host,
2398
+ sandbox,
2399
+ humanInputController,
2400
+ ownsHost,
2401
+ sessions,
2402
+ mcpManager,
2403
+ middlewareRunner,
2404
+ promptBuilder
2405
+ } = options;
2406
+ const tools = forkOptions.tools ?? parentTools;
2407
+ const childPrompt = resolveChildPromptConfig({
2408
+ forkOptions,
2409
+ promptBuilder,
2410
+ parentPromptConfig: parentConfig.prompt,
2411
+ parentSystemPrompt: parentConfig.systemPrompt
2412
+ });
2413
+ return {
2414
+ model: forkOptions.model ?? parentConfig.model,
2415
+ cwd: parentConfig.cwd,
2416
+ ...ownsHost ? {} : sandbox !== void 0 ? { sandbox } : { host },
2417
+ ...humanInputController ? { humanInput: humanInputController } : {},
2418
+ maxOutputTokens: parentConfig.maxOutputTokens,
2419
+ maxSteps: forkOptions.maxSteps ?? parentConfig.maxSteps,
2420
+ temperature: forkOptions.temperature ?? parentConfig.temperature,
2421
+ topP: parentConfig.topP,
2422
+ reasoningLevel: forkOptions.reasoningLevel ?? reasoningLevel,
2423
+ ...childPrompt,
2424
+ sessionManager: new SessionManager(sessions.getStorage()),
2425
+ tools,
2426
+ onDoomLoop: parentConfig.onDoomLoop,
2427
+ enforceDoomLoop: parentConfig.enforceDoomLoop,
2428
+ doomLoopThreshold: parentConfig.doomLoopThreshold,
2429
+ compaction: parentConfig.compaction,
2430
+ contextWindow: parentConfig.contextWindow,
2431
+ memory: parentConfig.memory,
2432
+ mcp: mcpManager,
2433
+ turnToolProviders: forkOptions.turnToolProviders ?? parentConfig.turnToolProviders,
2434
+ middleware: resolveForkMiddleware(forkOptions, middlewareRunner)
2435
+ };
2436
+ }
2437
+
2438
+ // src/agent/instance/forking.ts
2439
+ function createSubAgentConfig(options) {
2440
+ const effectiveOptions = resolveForkOptions(
2441
+ options.forkOptions,
2442
+ options.parentTools,
2443
+ options.parentConfig.systemPrompt
2444
+ );
2445
+ return createForkedAgentConfig({
2446
+ forkOptions: effectiveOptions,
2447
+ parentConfig: options.parentConfig,
2448
+ parentTools: options.parentTools,
2449
+ reasoningLevel: options.reasoningLevel,
2450
+ host: options.host,
2451
+ sandbox: options.sandbox,
2452
+ humanInputController: options.humanInputController,
2453
+ ownsHost: options.ownsHost,
2454
+ sessions: options.sessions,
2455
+ mcpManager: options.mcpManager,
2456
+ middlewareRunner: options.middlewareRunner,
2457
+ promptBuilder: options.promptBuilder
2458
+ });
2459
+ }
2460
+
2461
+ // src/agent/chat-loop/commit-batch.ts
2462
+ function createChatLoopCommitBatchApplier(params) {
2463
+ const { turnEngine, sessions, middlewareRunner } = params;
2464
+ return async function* applyCommitBatch(batch, options = {}) {
2465
+ turnEngine.recordEvent(batch.startBoundary, (/* @__PURE__ */ new Date()).toISOString());
2466
+ middlewareRunner.emitEvent(batch.startBoundary);
2467
+ yield batch.startBoundary;
2468
+ await sessions.addMessages(batch.messages);
2469
+ turnEngine.recordEvent(batch.finishBoundary, (/* @__PURE__ */ new Date()).toISOString());
2470
+ middlewareRunner.emitEvent(batch.finishBoundary);
2471
+ yield batch.finishBoundary;
2472
+ if (options.emitMessages) {
2473
+ for (const committedMessage of batch.messages) {
2474
+ yield { type: "message", message: committedMessage };
2475
+ }
2476
+ }
2477
+ };
2478
+ }
2479
+
2480
+ // src/agent/chat-loop/context-recovery.ts
2481
+ var DEFAULT_CONTEXT_RECOVERY_RETRIES = 2;
2482
+ function resolveContextRecoveryConfig(compaction) {
2483
+ const recovery = compaction?.recovery;
2484
+ const enabled = recovery?.enabled ?? compaction?.autoContinue ?? compaction?.auto !== false;
2485
+ const compactBeforeStep = recovery?.compactBeforeStep ?? true;
2486
+ const configuredRetries = recovery?.maxRetries ?? DEFAULT_CONTEXT_RECOVERY_RETRIES;
2487
+ return {
2488
+ enabled,
2489
+ compactBeforeStep,
2490
+ maxRetries: Math.max(0, Math.floor(configuredRetries))
2491
+ };
2492
+ }
2493
+ function errorMessage(error) {
2494
+ if (error instanceof Error) return error.message;
2495
+ if (error && typeof error === "object" && "message" in error && typeof error.message === "string") {
2496
+ return error.message;
2497
+ }
2498
+ return String(error);
2499
+ }
2500
+ function isContextOverflowError(error) {
2501
+ if (error instanceof LLMError) {
2502
+ return error.category === "context_overflow";
2503
+ }
2504
+ if (error instanceof Error && error.name === "ContextOverflowError") {
2505
+ return true;
2506
+ }
2507
+ const lowerMessage = errorMessage(error).toLowerCase();
2508
+ return lowerMessage.includes("context") && (lowerMessage.includes("length") || lowerMessage.includes("window") || lowerMessage.includes("overflow")) || lowerMessage.includes("input") && lowerMessage.includes("token") && lowerMessage.includes("exceed");
2509
+ }
2510
+ async function runContextRecoveryCompaction(params) {
2511
+ return await runCompactionCheck(params);
2512
+ }
2513
+
2514
+ // src/agent/chat-loop/turn-tools.ts
2515
+ async function resolveTurnTools(options) {
2516
+ const tools = /* @__PURE__ */ new Map();
2517
+ const mcpTools = {};
2518
+ const cleanup = [];
2519
+ try {
2520
+ for (const provider of options.providers) {
2521
+ const resolved = await provider.resolveTools(options.context);
2522
+ if (resolved.cleanup) {
2523
+ cleanup.push(resolved.cleanup);
2524
+ }
2525
+ for (const tool of resolved.tools ?? []) {
2526
+ if (options.baseTools.has(tool.id) || tools.has(tool.id)) {
2527
+ throw new Error(
2528
+ `Turn tool provider "${provider.name}" returned duplicate tool "${tool.id}"`
2529
+ );
2530
+ }
2531
+ tools.set(tool.id, tool);
2532
+ }
2533
+ for (const [name, tool] of Object.entries(resolved.mcpTools ?? {})) {
2534
+ if (options.baseMcpTools[name] || mcpTools[name]) {
2535
+ throw new Error(
2536
+ `Turn tool provider "${provider.name}" returned duplicate MCP tool "${name}"`
2537
+ );
2538
+ }
2539
+ mcpTools[name] = tool;
2540
+ }
2541
+ }
2542
+ } catch (error) {
2543
+ try {
2544
+ await cleanupTurnTools(cleanup);
2545
+ } catch {
2546
+ }
2547
+ throw error;
2548
+ }
2549
+ return { tools, mcpTools, cleanup };
2550
+ }
2551
+ function mergeTurnTools(baseTools, turnTools) {
2552
+ if (turnTools.size === 0) {
2553
+ return baseTools;
2554
+ }
2555
+ const merged = new Map(baseTools);
2556
+ for (const [id, tool] of turnTools) {
2557
+ if (merged.has(id)) {
2558
+ throw new Error(`Turn-scoped tool "${id}" conflicts with an agent tool`);
2559
+ }
2560
+ merged.set(id, tool);
2561
+ }
2562
+ return merged;
2563
+ }
2564
+ async function cleanupTurnTools(cleanup) {
2565
+ const errors = [];
2566
+ for (const cleanupFn of [...cleanup].reverse()) {
2567
+ try {
2568
+ await cleanupFn();
2569
+ } catch (error) {
2570
+ errors.push(error);
2571
+ }
2572
+ }
2573
+ if (errors.length === 1) {
2574
+ throw errors[0];
2575
+ }
2576
+ if (errors.length > 1) {
2577
+ throw new AggregateError(
2578
+ errors,
2579
+ "Multiple turn tool cleanup callbacks failed"
2580
+ );
2581
+ }
2582
+ }
2583
+
2584
+ // src/agent/chat-loop/model-step-snapshot.ts
2585
+ function createChatModelStepToolRecord(params) {
2586
+ return createAgentToolRecord(
2587
+ mergeTurnTools(params.liveTools, params.resolvedTurnTools.tools)
2588
+ );
2589
+ }
2590
+ function createAgentToolRecord(tools) {
2591
+ const toolRecord = {};
2592
+ for (const [id, tool] of tools) {
2593
+ toolRecord[id] = tool;
2594
+ }
2595
+ return toolRecord;
2596
+ }
2597
+ async function createChatModelStepSnapshot(params) {
2598
+ const tools = createChatModelStepToolRecord({
2599
+ liveTools: params.liveTools,
2600
+ resolvedTurnTools: params.resolvedTurnTools
2601
+ });
2602
+ const systemPrompts = await buildAgentSystemPrompts({
2603
+ config: params.config,
2604
+ toolIds: Object.keys(tools),
2605
+ sessionId: params.sessionId,
2606
+ override: params.systemOverride,
2607
+ promptBuilder: params.promptBuilder,
2608
+ middlewareRunner: params.middlewareRunner
2609
+ });
2610
+ const { assembledContext, events } = await assembleChatModelContextToFit({
2611
+ sessionId: params.sessionId,
2612
+ turnId: params.turnId,
2613
+ step: params.step,
2614
+ cwd: params.config.cwd,
2615
+ sessions: params.sessions,
2616
+ toolNames: Object.keys(tools),
2617
+ mcpToolNames: Object.keys(params.mcpTools),
2618
+ middlewareRunner: params.middlewareRunner,
2619
+ contextManager: params.contextManager,
2620
+ ...params.compactionReport ? { compactionReport: params.compactionReport } : {},
2621
+ fitAssembledContext: params.fitAssembledContext,
2622
+ context: params.config.context,
2623
+ ...params.abort ? { abort: params.abort } : {},
2624
+ ...params.logger ? { logger: params.logger } : {},
2625
+ ...params.memoryProvider ? { memoryProvider: params.memoryProvider } : {}
2626
+ });
2627
+ return {
2628
+ sessionId: params.sessionId,
2629
+ turnId: params.turnId,
2630
+ step: params.step,
2631
+ systemPrompts,
2632
+ messages: assembledContext.messages,
2633
+ contextReport: assembledContext.report,
2634
+ tools,
2635
+ mcpTools: { ...params.mcpTools },
2636
+ events
2637
+ };
2638
+ }
2639
+
2640
+ // src/agent/chat-loop/model-step-runner.ts
2641
+ async function* runChatModelStepWithRecovery(options) {
2642
+ const { deps, contextRecovery } = options;
2643
+ const {
2644
+ sessionId,
2645
+ turnId,
2646
+ abort,
2647
+ systemOverride,
2648
+ sessions,
2649
+ tools: liveTools,
2650
+ config,
2651
+ turnTracker,
2652
+ interventionCtrl,
2653
+ middlewareRunner,
2654
+ contextManager,
2655
+ rememberedDoomLoopTools,
2656
+ reasoningLevel,
2657
+ promptBuilder,
2658
+ host,
2659
+ humanInputController,
2660
+ toModelMessages
2661
+ } = deps;
2662
+ let stepResult;
2663
+ let contextRecoveryAttempts = 0;
2664
+ let latestCompactionReport = options.compactionReport;
2665
+ let toolRecord = options.toolRecord;
2666
+ while (!stepResult) {
2667
+ const stepSnapshot = await createChatModelStepSnapshot({
2668
+ sessionId,
2669
+ turnId,
2670
+ step: options.step,
2671
+ sessions,
2672
+ liveTools,
2673
+ resolvedTurnTools: options.resolvedTurnTools,
2674
+ mcpTools: options.turnMcpTools,
2675
+ promptBuilder,
2676
+ middlewareRunner,
2677
+ contextManager,
2678
+ ...latestCompactionReport ? { compactionReport: latestCompactionReport } : {},
2679
+ fitAssembledContext: contextRecovery.enabled && contextRecovery.compactBeforeStep,
2680
+ ...deps.logger ? { logger: deps.logger } : {},
2681
+ ...deps.memoryProvider ? { memoryProvider: deps.memoryProvider } : {},
2682
+ systemOverride,
2683
+ config,
2684
+ abort
2685
+ });
2686
+ toolRecord = stepSnapshot.tools;
2687
+ for (const event of stepSnapshot.events) {
2688
+ middlewareRunner.emitEvent(event);
2689
+ yield event;
2690
+ }
2691
+ const preparedStep = prepareModelStep({
2692
+ sessionId: stepSnapshot.sessionId,
2693
+ turnId: stepSnapshot.turnId,
2694
+ step: stepSnapshot.step,
2695
+ systemPrompts: stepSnapshot.systemPrompts,
2696
+ messages: stepSnapshot.messages,
2697
+ contextReport: stepSnapshot.contextReport,
2698
+ toModelMessages,
2699
+ abort,
2700
+ tools: stepSnapshot.tools,
2701
+ mcpTools: stepSnapshot.mcpTools,
2702
+ config,
2703
+ host,
2704
+ humanInputController,
2705
+ turnTracker,
2706
+ intervention: interventionCtrl,
2707
+ middleware: middlewareRunner,
2708
+ reasoningLevel,
2709
+ toolExecutionMode: deps.toolExecutionMode
2710
+ });
2711
+ try {
2712
+ stepResult = yield* runModelStep({
2713
+ preparedStep,
2714
+ turnEngine: options.turnEngine,
2715
+ applyCommitBatch: options.applyCommitBatch,
2716
+ rememberedDoomLoopTools,
2717
+ deferErrorEvent: contextRecovery.enabled ? isContextOverflowError : void 0
2718
+ });
2719
+ } catch (error) {
2720
+ const recovery = await maybeRunRecoveryCompaction({
2721
+ error,
2722
+ deps,
2723
+ contextRecovery,
2724
+ contextRecoveryAttempts
2725
+ });
2726
+ if (recovery) {
2727
+ yield* recovery.events;
2728
+ if (recovery.compacted) {
2729
+ contextRecoveryAttempts += 1;
2730
+ latestCompactionReport = recovery.report;
2731
+ continue;
2732
+ }
2733
+ }
2734
+ throw error;
2735
+ }
2736
+ if (stepResult.error) {
2737
+ const recovery = await maybeRunRecoveryCompaction({
2738
+ error: stepResult.error,
2739
+ deps,
2740
+ contextRecovery,
2741
+ contextRecoveryAttempts
2742
+ });
2743
+ if (recovery) {
2744
+ yield* recovery.events;
2745
+ if (recovery.compacted) {
2746
+ contextRecoveryAttempts += 1;
2747
+ latestCompactionReport = recovery.report;
2748
+ stepResult = void 0;
2749
+ }
2750
+ }
2751
+ }
2752
+ }
2753
+ return {
2754
+ stepResult,
2755
+ toolRecord,
2756
+ ...latestCompactionReport ? { compactionReport: latestCompactionReport } : {}
2757
+ };
2758
+ }
2759
+ async function maybeRunRecoveryCompaction(options) {
2760
+ const { error, deps, contextRecovery, contextRecoveryAttempts } = options;
2761
+ if (!contextRecovery.enabled || !isContextOverflowError(error) || contextRecoveryAttempts >= contextRecovery.maxRetries) {
2762
+ return void 0;
2763
+ }
2764
+ const recoveryCompaction = await runContextRecoveryCompaction({
2765
+ contextManager: deps.contextManager,
2766
+ sessions: deps.sessions,
2767
+ logger: deps.logger,
2768
+ force: true,
2769
+ phase: "recovery",
2770
+ sessionId: deps.sessionId,
2771
+ turnId: deps.turnId,
2772
+ cwd: deps.config.cwd,
2773
+ abort: deps.abort,
2774
+ memoryProvider: deps.memoryProvider,
2775
+ retryAttempt: contextRecoveryAttempts + 1
2776
+ });
2777
+ for (const event of recoveryCompaction.events) {
2778
+ deps.middlewareRunner.emitEvent(event);
2779
+ }
2780
+ return {
2781
+ events: recoveryCompaction.events,
2782
+ report: recoveryCompaction.report,
2783
+ compacted: recoveryCompaction.compacted
2784
+ };
2785
+ }
2786
+
2787
+ // src/agent/chat-loop/finalize-turn.ts
2788
+ async function* finalizeChatLoopTurn(options) {
2789
+ const { deps, turnEngine, applyCommitBatch, turnTracker, text, usage } = options;
2790
+ const {
2791
+ sessionId,
2792
+ turnId,
2793
+ abort,
2794
+ sessions,
2795
+ config,
2796
+ contextManager,
2797
+ middlewareRunner
2798
+ } = deps;
2799
+ yield* commitOutput({
2800
+ text,
2801
+ usage,
2802
+ turnEngine,
2803
+ applyCommitBatch
2804
+ });
2805
+ if (config.compaction?.auto !== false) {
2806
+ const compactionEvents = await runAutoCompaction({
2807
+ contextManager,
2808
+ sessions,
2809
+ logger: deps.logger,
2810
+ sessionId,
2811
+ turnId,
2812
+ cwd: config.cwd,
2813
+ abort,
2814
+ memoryProvider: deps.memoryProvider
2815
+ });
2816
+ for (const event of compactionEvents) {
2817
+ middlewareRunner.emitEvent(event);
2818
+ yield event;
2819
+ }
2820
+ }
2821
+ const turnSummary = await turnTracker.endTurn();
2822
+ if (turnSummary.totalTracked > 0) {
2823
+ yield {
2824
+ type: "turn-summary",
2825
+ turnId: turnSummary.turnId,
2826
+ files: turnSummary.files.map((file) => ({
2827
+ path: file.path,
2828
+ type: file.type,
2829
+ additions: file.additions,
2830
+ deletions: file.deletions
2831
+ })),
2832
+ additions: turnSummary.additions,
2833
+ deletions: turnSummary.deletions
2834
+ };
2835
+ }
2836
+ const output = text || void 0;
2837
+ yield {
2838
+ type: "complete",
2839
+ usage,
2840
+ output
2841
+ };
2842
+ return {
2843
+ ...output !== void 0 ? { output } : {},
2844
+ ...usage !== void 0 ? { usage } : {}
2845
+ };
2846
+ }
2847
+
2848
+ // src/agent/chat-loop/loop.ts
2849
+ async function* runChatLoop(deps) {
2850
+ yield* streamWithinScope(
2851
+ {
2852
+ kind: "turn",
2853
+ name: "agent-turn",
2854
+ sessionId: deps.sessionId
2855
+ },
2856
+ (async function* () {
2857
+ const {
2858
+ sessionId,
2859
+ turnId,
2860
+ message,
2861
+ abort,
2862
+ systemOverride,
2863
+ sessions,
2864
+ tools: liveTools,
2865
+ config,
2866
+ turnTracker,
2867
+ interventionCtrl,
2868
+ middlewareRunner,
2869
+ contextManager,
2870
+ host,
2871
+ humanInputController,
2872
+ mcpTools,
2873
+ setIsStreaming
2874
+ } = deps;
2875
+ let resolvedTurnTools;
2876
+ try {
2877
+ resolvedTurnTools = await resolveTurnTools({
2878
+ providers: deps.turnToolProviders,
2879
+ context: {
2880
+ sessionId,
2881
+ turnId,
2882
+ message,
2883
+ cwd: config.cwd,
2884
+ abort
2885
+ },
2886
+ baseTools: liveTools,
2887
+ baseMcpTools: mcpTools
2888
+ });
2889
+ } catch (error) {
2890
+ const errorInstance = error instanceof Error ? error : new Error(String(error));
2891
+ const statusEvent = { type: "status", status: "error" };
2892
+ middlewareRunner.emitEvent(statusEvent);
2893
+ yield statusEvent;
2894
+ const errorEvent = {
2895
+ type: "error",
2896
+ error: errorInstance
2897
+ };
2898
+ middlewareRunner.emitEvent(errorEvent);
2899
+ yield errorEvent;
2900
+ throw errorInstance;
2901
+ }
2902
+ const turnMcpTools = {
2903
+ ...mcpTools,
2904
+ ...resolvedTurnTools.mcpTools
2905
+ };
2906
+ let toolRecord = createChatModelStepToolRecord({
2907
+ liveTools,
2908
+ resolvedTurnTools
2909
+ });
2910
+ const prevOnApplied = interventionCtrl.onApplied;
2911
+ let streamingStateStarted = false;
2912
+ let chatUsage;
2913
+ let chatError;
2914
+ let chatOutput;
2915
+ let chatEndError;
2916
+ let rethrowError;
2917
+ const lifecycleContext = {
2918
+ sessionId,
2919
+ turnId,
2920
+ history: {
2921
+ getRecentMessages: (options) => sessions.getRecentMessages(options)
1894
2922
  }
1895
- if (kind !== "choice" && params.allowMultiple) {
1896
- return {
1897
- ok: false,
1898
- reason: "allowMultiple is only valid for choice requests."
1899
- };
2923
+ };
2924
+ try {
2925
+ const isPlanMode = deps.toolExecutionMode === "plan";
2926
+ const turnEngine = createAgentTurnEngine({
2927
+ sessionId,
2928
+ startedAt: (/* @__PURE__ */ new Date()).toISOString(),
2929
+ getToolReplayPolicy: (toolName) => toolRecord[toolName] ? normalizeToolReplayPolicy(toolRecord[toolName].replayPolicy) : void 0
2930
+ });
2931
+ const applyCommitBatch = createChatLoopCommitBatchApplier({
2932
+ turnEngine,
2933
+ sessions,
2934
+ middlewareRunner
2935
+ });
2936
+ yield* applyCommitBatch(
2937
+ turnEngine.createInputCommit({
2938
+ content: message,
2939
+ system: systemOverride
2940
+ }),
2941
+ { emitMessages: true }
2942
+ );
2943
+ setIsStreaming(true);
2944
+ streamingStateStarted = true;
2945
+ if (middlewareRunner.hasMiddleware) {
2946
+ await middlewareRunner.runChatStart(
2947
+ sessionId,
2948
+ message,
2949
+ lifecycleContext
2950
+ );
1900
2951
  }
1901
- return { ok: true };
1902
- },
1903
- capabilities: {
1904
- readOnly: true,
1905
- riskLevel: "safe",
1906
- parallelSafe: false,
1907
- humanInput: true
1908
- },
1909
- replayPolicy: {
1910
- mode: "manual",
1911
- sideEffectLevel: "external",
1912
- reason: "Depends on a human response before execution can continue."
1913
- },
1914
- execute: async (params, ctx) => {
1915
- let response;
1916
- try {
1917
- const activeController = controller ?? ctx.humanInputController;
1918
- if (!activeController) {
1919
- throw new HumanInputUnavailableError();
2952
+ let step = 1;
2953
+ let finalStepText = "";
2954
+ let accumulatedUsage;
2955
+ const contextRecovery = resolveContextRecoveryConfig(config.compaction);
2956
+ let latestContextCompactionReport;
2957
+ while (step <= config.maxSteps) {
2958
+ latestContextCompactionReport = void 0;
2959
+ if (contextRecovery.enabled && contextRecovery.compactBeforeStep) {
2960
+ const preStepCompaction = await runContextRecoveryCompaction({
2961
+ contextManager,
2962
+ sessions,
2963
+ logger: deps.logger,
2964
+ force: false,
2965
+ phase: "pre-step",
2966
+ sessionId,
2967
+ turnId,
2968
+ cwd: config.cwd,
2969
+ abort,
2970
+ memoryProvider: deps.memoryProvider
2971
+ });
2972
+ for (const event of preStepCompaction.events) {
2973
+ middlewareRunner.emitEvent(event);
2974
+ yield event;
2975
+ }
2976
+ latestContextCompactionReport = preStepCompaction.report;
2977
+ }
2978
+ const stepRun = yield* runChatModelStepWithRecovery({
2979
+ deps,
2980
+ step,
2981
+ turnEngine,
2982
+ applyCommitBatch,
2983
+ resolvedTurnTools,
2984
+ turnMcpTools,
2985
+ toolRecord,
2986
+ contextRecovery,
2987
+ ...latestContextCompactionReport ? { compactionReport: latestContextCompactionReport } : {}
2988
+ });
2989
+ const stepResult = stepRun.stepResult;
2990
+ toolRecord = stepRun.toolRecord;
2991
+ latestContextCompactionReport = stepRun.compactionReport;
2992
+ accumulatedUsage = accumulateUsage(
2993
+ accumulatedUsage,
2994
+ stepResult.usage
2995
+ );
2996
+ if (stepResult.error) {
2997
+ chatError = stepResult.error;
2998
+ if (contextRecovery.enabled && isContextOverflowError(stepResult.error)) {
2999
+ const statusEvent = {
3000
+ type: "status",
3001
+ status: "error"
3002
+ };
3003
+ middlewareRunner.emitEvent(statusEvent);
3004
+ yield statusEvent;
3005
+ const errorEvent = {
3006
+ type: "error",
3007
+ error: stepResult.error
3008
+ };
3009
+ middlewareRunner.emitEvent(errorEvent);
3010
+ yield errorEvent;
3011
+ }
3012
+ return;
3013
+ }
3014
+ const planSnapshot = isPlanMode && stepResult.finishReason === "tool-calls" ? turnEngine.createStepCommitSnapshot() : void 0;
3015
+ yield* commitStep({
3016
+ step,
3017
+ finishReason: stepResult.finishReason,
3018
+ turnEngine,
3019
+ applyCommitBatch
3020
+ });
3021
+ if (stepResult.finishReason === "tool-calls") {
3022
+ if (step >= config.maxSteps) {
3023
+ const maxStepsError = new Error(
3024
+ `Maximum steps (${config.maxSteps}) reached before the turn produced a final response`
3025
+ );
3026
+ chatError = maxStepsError;
3027
+ const statusEvent = {
3028
+ type: "status",
3029
+ status: "error"
3030
+ };
3031
+ middlewareRunner.emitEvent(statusEvent);
3032
+ yield statusEvent;
3033
+ const errorEvent = {
3034
+ type: "error",
3035
+ error: maxStepsError
3036
+ };
3037
+ middlewareRunner.emitEvent(errorEvent);
3038
+ yield errorEvent;
3039
+ return;
3040
+ }
3041
+ if (isPlanMode && planSnapshot && planSnapshot.toolCalls.length > 0) {
3042
+ const batchResult = await runToolBatch({
3043
+ sessionId,
3044
+ snapshot: planSnapshot,
3045
+ tools: toolRecord,
3046
+ cwd: config.cwd,
3047
+ abort,
3048
+ host,
3049
+ humanInputController,
3050
+ turnTracker,
3051
+ middleware: middlewareRunner,
3052
+ intervention: interventionCtrl
3053
+ });
3054
+ for (const event of batchResult.events) {
3055
+ turnEngine.recordEvent(event, (/* @__PURE__ */ new Date()).toISOString());
3056
+ middlewareRunner.emitEvent(event);
3057
+ yield event;
3058
+ }
3059
+ yield* commitStep({
3060
+ step,
3061
+ finishReason: "tool-calls",
3062
+ turnEngine,
3063
+ applyCommitBatch
3064
+ });
3065
+ }
3066
+ step += 1;
3067
+ continue;
3068
+ }
3069
+ finalStepText = stepResult.text;
3070
+ break;
3071
+ }
3072
+ const finalization = yield* finalizeChatLoopTurn({
3073
+ deps,
3074
+ turnEngine,
3075
+ applyCommitBatch,
3076
+ turnTracker,
3077
+ text: finalStepText,
3078
+ usage: accumulatedUsage
3079
+ });
3080
+ chatUsage = finalization.usage;
3081
+ chatOutput = finalization.output;
3082
+ } catch (error) {
3083
+ chatError = error instanceof Error ? error : new Error(String(error));
3084
+ const statusEvent = { type: "status", status: "error" };
3085
+ middlewareRunner.emitEvent(statusEvent);
3086
+ yield statusEvent;
3087
+ const errorEvent = { type: "error", error: chatError };
3088
+ middlewareRunner.emitEvent(errorEvent);
3089
+ yield errorEvent;
3090
+ rethrowError = error;
3091
+ } finally {
3092
+ if (streamingStateStarted) {
3093
+ setIsStreaming(false);
3094
+ }
3095
+ interventionCtrl.onApplied = prevOnApplied;
3096
+ if (middlewareRunner.hasMiddleware) {
3097
+ try {
3098
+ await middlewareRunner.runChatEnd(
3099
+ sessionId,
3100
+ {
3101
+ usage: chatUsage,
3102
+ error: chatError,
3103
+ output: chatOutput
3104
+ },
3105
+ lifecycleContext
3106
+ );
3107
+ } catch (error) {
3108
+ chatEndError = error;
1920
3109
  }
1921
- response = await activeController.request(
1922
- ctx.sessionID,
1923
- {
1924
- ...params,
1925
- toolCallId: typeof ctx.extra?.toolCallId === "string" ? ctx.extra.toolCallId : ctx.messageID
1926
- },
1927
- {
1928
- emitEvent: ctx.emitEvent
1929
- }
1930
- );
3110
+ }
3111
+ try {
3112
+ await cleanupTurnTools(resolvedTurnTools.cleanup);
1931
3113
  } catch (error) {
1932
- if (error instanceof HumanInputUnavailableError) {
1933
- throw error;
1934
- }
1935
- throw error;
3114
+ const errorInstance = error instanceof Error ? error : new Error(String(error));
3115
+ deps.logger?.warn("Turn tool provider cleanup failed", {
3116
+ error: errorInstance,
3117
+ message: errorInstance.message,
3118
+ stack: errorInstance.stack
3119
+ });
1936
3120
  }
1937
- return {
1938
- title: params.title,
1939
- output: response.text,
1940
- metadata: { response }
1941
- };
1942
3121
  }
1943
- },
1944
- {
1945
- replayPolicy: {
1946
- mode: "manual",
1947
- sideEffectLevel: "external",
1948
- reason: "Depends on a human response before execution can continue."
1949
- },
1950
- capabilitiesHint: {
1951
- readOnly: true,
1952
- riskLevel: "safe",
1953
- parallelSafe: false,
1954
- humanInput: true
3122
+ if (chatEndError) {
3123
+ throw chatEndError;
1955
3124
  }
1956
- }
3125
+ if (rethrowError) {
3126
+ throw rethrowError;
3127
+ }
3128
+ })()
1957
3129
  );
1958
3130
  }
1959
- var createHumanInputToolWithHandler = createHumanInputToolWithController;
1960
-
1961
- // src/agent/stream-provider.ts
1962
- var DEFAULT_CUSTOM_STREAM_MODELS = [
1963
- "computer-use-preview",
1964
- "computer-use-preview-2025-03-11"
1965
- ];
1966
- function needsCustomStreamProvider(model, customPatterns) {
1967
- const modelId = extractModelId(model);
1968
- if (!modelId || modelId === "[object Object]") return false;
1969
- const patterns = customPatterns ?? DEFAULT_CUSTOM_STREAM_MODELS;
1970
- return patterns.some((pattern) => modelId.includes(pattern));
1971
- }
1972
- function hasStreamProviderFactory(tools) {
1973
- return Array.isArray(tools) && typeof tools.__streamProviderFactory === "function";
1974
- }
1975
- function autoDetectStreamProvider(model, tools, explicitProvider) {
1976
- if (explicitProvider) {
1977
- return explicitProvider;
1978
- }
1979
- if (!tools) return void 0;
1980
- const enhancedTools = tools;
1981
- const customPatterns = enhancedTools.__customStreamModels;
1982
- if (needsCustomStreamProvider(model, customPatterns) && hasStreamProviderFactory(enhancedTools)) {
1983
- const modelId = extractModelId(model);
1984
- if (modelId) {
1985
- const streamConfig = {
1986
- apiKey: process.env.OPENAI_API_KEY,
1987
- display: { width: 1024, height: 768 },
1988
- environment: "linux",
1989
- debug: false
1990
- };
1991
- return enhancedTools.__streamProviderFactory(modelId, streamConfig);
1992
- }
1993
- }
1994
- return void 0;
1995
- }
1996
3131
 
1997
- // src/agent/setup.ts
1998
- function createAgentPromptBuilder(config) {
1999
- if (config.prompt !== void 0) {
2000
- return createPromptBuilder(config.prompt);
2001
- }
2002
- if (config.systemPrompt === void 0) {
2003
- return createPromptBuilder();
2004
- }
2005
- return void 0;
2006
- }
2007
- function createEffectiveAgentConfig(config) {
2008
- const effectiveStreamProvider = autoDetectStreamProvider(
2009
- config.model,
2010
- config.tools,
2011
- config.streamProvider
2012
- );
2013
- const resolvedCwd = config.cwd ?? config.sandbox?.metadata?.workingDirectory ?? process.cwd();
2014
- const defaultsContext = {
2015
- sandbox: config.sandbox,
2016
- cwd: resolvedCwd,
2017
- modelId: extractModelId(config.model)
2018
- };
2019
- const providers = [
2020
- sandboxDefaultsProvider,
2021
- ...config.defaultsProviders ?? []
2022
- ];
2023
- const defaults = resolveAgentDefaults(defaultsContext, providers);
2024
- return {
2025
- ...config,
2026
- systemPrompt: config.systemPrompt ?? defaults.systemPrompt,
2027
- cwd: resolvedCwd,
2028
- reasoningLevel: config.reasoningLevel ?? "off",
2029
- maxSteps: config.maxSteps ?? defaults.maxSteps,
2030
- maxOutputTokens: config.maxOutputTokens ?? defaults.maxOutputTokens,
2031
- streamProvider: effectiveStreamProvider
2032
- };
2033
- }
2034
- function createToolMap(tools) {
2035
- const toolMap = /* @__PURE__ */ new Map();
2036
- for (const tool of tools ?? []) {
2037
- toolMap.set(tool.id, tool);
2038
- }
2039
- return toolMap;
2040
- }
2041
- function resolveInitialReasoningLevel(config) {
2042
- const reasoningConfig = getReasoningConfigSync(config.model);
2043
- const requestedLevel = config.reasoningLevel ?? "off";
2044
- return reasoningConfig.availableLevels.includes(requestedLevel) ? requestedLevel : reasoningConfig.availableLevels[0];
2045
- }
2046
- function createAgentState(config) {
2047
- return {
2048
- model: config.model,
2049
- reasoningLevel: resolveInitialReasoningLevel(config)
2050
- };
2051
- }
2052
- function createAgentContextManager(config) {
2053
- const compactionConfig = config.compaction ?? {};
2054
- const modelId = extractModelId(config.model);
2055
- const inferredWindow = inferContextWindow(modelId);
2056
- const contextWindow = config.contextWindow ?? inferredWindow ?? DEFAULT_CONTEXT_LIMITS.contextWindow;
2057
- return new ContextManager({
2058
- limits: {
2059
- contextWindow,
2060
- ...resolveAgentContextLimits(contextWindow, compactionConfig)
2061
- },
2062
- model: compactionConfig.summaryModel ?? config.model,
2063
- summaryPrompt: compactionConfig.summaryPrompt
3132
+ // src/agent/instance/turn-lifecycle.ts
3133
+ async function* runAgentChatTurn(params) {
3134
+ const { runtime, sessionId, turnId, message, options } = params;
3135
+ const releaseSessionLock = await runtime.acquireSessionLock(sessionId, {
3136
+ signal: options?.abort
2064
3137
  });
2065
- }
2066
- function resolveAgentContextLimits(contextWindow, compactionConfig = {}) {
2067
- const proportionalReserve = Math.round(contextWindow * 0.12);
2068
- const reserveTokens = contextWindow >= 64e3 ? Math.min(32e3, Math.max(8e3, proportionalReserve)) : Math.min(
2069
- Math.max(1024, Math.round(contextWindow * 0.25)),
2070
- Math.max(512, proportionalReserve)
2071
- );
2072
- const usableWindow = Math.max(
2073
- 512,
2074
- getUsableTokenLimit({ contextWindow, reserveTokens })
2075
- );
2076
- const requestedProtected = compactionConfig.protectedTokens ?? DEFAULT_CONTEXT_LIMITS.protectedTokens;
2077
- const requestedPruneMinimum = compactionConfig.pruneMinimum ?? DEFAULT_CONTEXT_LIMITS.pruneMinimum;
2078
- return {
2079
- reserveTokens,
2080
- protectedTokens: Math.min(
2081
- requestedProtected,
2082
- Math.max(512, Math.round(usableWindow * 0.6))
2083
- ),
2084
- pruneMinimum: Math.min(
2085
- requestedPruneMinimum,
2086
- Math.max(256, Math.round(usableWindow * 0.5))
2087
- )
2088
- };
2089
- }
2090
- function createMiddlewareSetup(input, config) {
2091
- const inputMiddleware = [...input.middleware ?? []];
2092
- const hasManualApprovalMiddleware = inputMiddleware.some(
2093
- (mw) => isApprovalMiddleware(mw)
2094
- );
2095
- if (input.approval && hasManualApprovalMiddleware) {
2096
- throw new Error(
2097
- "createAgent() received both `approval` config and an explicit approval middleware. Use `approval` for the built-in sugar, or install `approvalMiddleware(...)` manually, but not both."
2098
- );
2099
- }
2100
- let effectiveMiddleware = inputMiddleware;
2101
- let telemetrySettings;
2102
- let tracingShutdown;
2103
- if (input.approval) {
2104
- effectiveMiddleware.push(approvalMiddleware(input.approval));
2105
- }
2106
- if (input.tracing) {
2107
- const agentName = config.name ?? DEFAULT_AGENT_NAME;
2108
- const telemetryResult = createTelemetryConfig({
2109
- ...input.tracing,
2110
- agentName,
2111
- serviceName: input.tracing.serviceName ?? agentName
3138
+ const sessions = runtime.createSessionManager();
3139
+ let turnTracker;
3140
+ const interventionCtrl = runtime.createTurnInterventionController();
3141
+ let streamingStateActive = false;
3142
+ let turnRegistered = false;
3143
+ try {
3144
+ await runtime.ensureSkillTools();
3145
+ const abort = options?.abort ?? new AbortController().signal;
3146
+ turnTracker = createTurnTracker({ cwd: runtime.config.cwd });
3147
+ runtime.activeTurns.set(turnId, { sessionId, interventionCtrl });
3148
+ turnRegistered = true;
3149
+ await ensureSessionLoaded({
3150
+ sessionId,
3151
+ sessions,
3152
+ cwd: runtime.config.cwd
2112
3153
  });
2113
- effectiveMiddleware = [
2114
- ...telemetryResult.middlewares.length > 0 ? telemetryResult.middlewares : [telemetryResult.middleware],
2115
- ...effectiveMiddleware
2116
- ];
2117
- telemetrySettings = telemetryResult.telemetry;
2118
- tracingShutdown = telemetryResult.shutdown;
2119
- }
2120
- return {
2121
- middlewareRunner: new MiddlewareRunner(effectiveMiddleware, input.logger),
2122
- ...telemetrySettings ? { telemetrySettings } : {},
2123
- ...tracingShutdown ? { tracingShutdown } : {}
2124
- };
2125
- }
2126
- function resolveHumanInputController(input) {
2127
- if (!input.humanInput) {
2128
- return {};
2129
- }
2130
- return {
2131
- humanInputController: isHumanInputController(input.humanInput) ? input.humanInput : createHumanInputController(input.humanInput)
2132
- };
2133
- }
2134
- function resolveExecutionEnvironment(input, config) {
2135
- if (input.host !== void 0 && input.sandbox !== void 0 && input.host !== input.sandbox.host) {
2136
- throw new Error(
2137
- "createAgent() received both `host` and `sandbox`, but `sandbox.host` does not match the provided host. Pass only one execution input, or reuse the same host instance for both."
2138
- );
2139
- }
2140
- if (input.host !== void 0) {
2141
- return {
2142
- host: input.host,
2143
- ...input.sandbox ? { sandbox: input.sandbox } : {},
2144
- ownsHost: false
2145
- };
2146
- }
2147
- if (input.sandbox !== void 0) {
2148
- return {
2149
- host: input.sandbox.host,
2150
- sandbox: input.sandbox,
2151
- ownsHost: false
2152
- };
3154
+ turnTracker.startTurn(turnId);
3155
+ await repairOrphanedToolCalls(sessions);
3156
+ const mcpTools = await runtime.ensureMcpConnected();
3157
+ const loop = runChatLoop({
3158
+ sessionId,
3159
+ turnId,
3160
+ message,
3161
+ abort,
3162
+ systemOverride: options?.system,
3163
+ sessions,
3164
+ tools: runtime.tools,
3165
+ config: runtime.config,
3166
+ turnTracker,
3167
+ interventionCtrl,
3168
+ middlewareRunner: runtime.middlewareRunner,
3169
+ contextManager: runtime.contextManager,
3170
+ rememberedDoomLoopTools: runtime.rememberedDoomLoopTools,
3171
+ reasoningLevel: runtime.reasoningLevel,
3172
+ promptBuilder: runtime.promptBuilder,
3173
+ host: runtime.host,
3174
+ humanInputController: runtime.humanInputController,
3175
+ memoryProvider: runtime.memoryProvider,
3176
+ mcpTools,
3177
+ turnToolProviders: runtime.turnToolProviders,
3178
+ telemetrySettings: runtime.telemetrySettings,
3179
+ toModelMessages: convertAgentMessagesToModelMessages,
3180
+ setIsStreaming: (value) => {
3181
+ if (value === streamingStateActive) return;
3182
+ streamingStateActive = value;
3183
+ runtime.syncStreamingState(value);
3184
+ },
3185
+ toolExecutionMode: runtime.config.toolExecutionMode,
3186
+ logger: runtime.logger
3187
+ });
3188
+ for await (const event of loop) {
3189
+ runtime.signal.emit(event);
3190
+ yield event;
3191
+ }
3192
+ } finally {
3193
+ try {
3194
+ if (streamingStateActive) {
3195
+ runtime.syncStreamingState(false);
3196
+ }
3197
+ if (turnRegistered) {
3198
+ runtime.activeTurns.delete(turnId);
3199
+ }
3200
+ runtime.releaseTurnInterventions(interventionCtrl);
3201
+ if (turnRegistered && turnTracker) {
3202
+ runtime.setTurnTracker(turnTracker);
3203
+ }
3204
+ await runtime.syncSessionView(sessionId);
3205
+ } finally {
3206
+ await releaseSessionLock();
3207
+ }
2153
3208
  }
2154
- return {
2155
- host: localHost(config.cwd),
2156
- ownsHost: true
2157
- };
2158
3209
  }
2159
- function createAgentSetup(input) {
2160
- const promptBuilder = createAgentPromptBuilder(input);
2161
- const config = createEffectiveAgentConfig(input);
2162
- const middlewareSetup = createMiddlewareSetup(input, config);
2163
- const humanInputSetup = resolveHumanInputController(input);
2164
- const executionEnvironment = resolveExecutionEnvironment(input, config);
2165
- const logger = input.logger ?? silentLogger;
2166
- return {
2167
- config,
2168
- tools: createToolMap(input.tools),
2169
- sessions: input.sessionManager ?? getDefaultSessionManager(),
2170
- sessionTurnLock: input.sessionTurnLock ?? new LocalSessionTurnLock(),
2171
- state: createAgentState(config),
2172
- contextManager: createAgentContextManager(config),
2173
- turnTracker: createTurnTracker({ cwd: config.cwd }, logger),
2174
- ...input.mcp ? { mcpManager: input.mcp } : {},
2175
- turnToolProviders: [...input.turnToolProviders ?? []],
2176
- ...promptBuilder ? { promptBuilder } : {},
2177
- interventionCtrl: new InterventionController(),
2178
- ...humanInputSetup,
2179
- ...executionEnvironment,
2180
- middlewareRunner: middlewareSetup.middlewareRunner,
2181
- logger,
2182
- ...middlewareSetup.telemetrySettings ? { telemetrySettings: middlewareSetup.telemetrySettings } : {},
2183
- ...middlewareSetup.tracingShutdown ? { tracingShutdown: middlewareSetup.tracingShutdown } : {}
2184
- };
3210
+ async function sendAgentMessage(chat, sessionId, message, options) {
3211
+ const events = chat(sessionId, message, options);
3212
+ let response = "";
3213
+ let usage = { inputTokens: 0, outputTokens: 0, totalTokens: 0 };
3214
+ const toolCalls = [];
3215
+ for await (const event of events) {
3216
+ switch (event.type) {
3217
+ case "text-delta":
3218
+ response += event.text;
3219
+ break;
3220
+ case "tool-result":
3221
+ toolCalls.push({ name: event.toolName, result: event.result });
3222
+ break;
3223
+ case "complete":
3224
+ if (event.usage) usage = event.usage;
3225
+ if (event.output !== void 0) response = event.output;
3226
+ break;
3227
+ case "error":
3228
+ throw event.error;
3229
+ }
3230
+ }
3231
+ return { response, usage, toolCalls };
2185
3232
  }
2186
3233
 
2187
- // src/agent/instance.ts
3234
+ // src/agent/instance/index.ts
2188
3235
  function createAgent(config) {
2189
3236
  return new Agent(config);
2190
3237
  }
@@ -2194,48 +3241,28 @@ var Agent = class _Agent {
2194
3241
  sessions;
2195
3242
  sessionTurnLock;
2196
3243
  state;
2197
- /** Context manager for overflow detection and compaction */
2198
3244
  contextManager;
2199
- /** Tools that user said "remember" for doom loop (don't ask again) */
2200
3245
  rememberedDoomLoopTools = /* @__PURE__ */ new Set();
2201
- /** Turn change tracker for file modification tracking */
2202
3246
  turnTracker;
2203
- /** Counter for turn IDs */
2204
3247
  turnCounter = 0;
2205
- /** MCP manager for external tool servers */
2206
3248
  mcpManager;
2207
3249
  turnToolProviders;
2208
- /** Whether MCP has been connected (lazy init) */
2209
3250
  mcpConnected = false;
2210
- /** Whether skill tools have been resolved (lazy init) */
2211
3251
  skillToolsResolved = false;
2212
- /** Cached MCP tools (refreshed on connect) */
2213
3252
  mcpToolsCache;
2214
- /** Prompt pipeline builder (when using layered prompt mode) */
2215
3253
  promptBuilder;
2216
- /** Intervention controller for mid-turn message injection */
2217
3254
  interventionCtrl;
2218
- /** Execution environment for tool operations */
2219
3255
  host;
2220
- /** Managed sandbox session, when the agent was created from one */
2221
3256
  sandbox;
2222
- /** Managed human-input controller for question-style tools */
2223
3257
  humanInputController;
2224
- /** Whether the agent owns the host and can safely recreate it on cwd changes */
3258
+ memoryProvider;
2225
3259
  ownsHost;
2226
- /** Middleware runner for lifecycle hooks */
2227
3260
  middlewareRunner;
2228
- /** AI SDK telemetry settings (auto-created from `tracing` config) */
2229
3261
  telemetrySettings;
2230
- /** Tracing shutdown function (from `tracing` config auto-setup) */
2231
3262
  tracingShutdown;
2232
- /** Multi-consumer event dispatch */
2233
3263
  _signal;
2234
- /** Number of active turns across all sessions */
2235
3264
  activeTurnCount = 0;
2236
- /** Active turn intervention controllers, keyed by turn id */
2237
3265
  activeTurns = /* @__PURE__ */ new Map();
2238
- /** Structured logger for diagnostic output */
2239
3266
  _logger;
2240
3267
  constructor(config) {
2241
3268
  const setup = createAgentSetup(config);
@@ -2253,6 +3280,7 @@ var Agent = class _Agent {
2253
3280
  this.host = setup.host;
2254
3281
  this.sandbox = setup.sandbox;
2255
3282
  this.humanInputController = setup.humanInputController;
3283
+ this.memoryProvider = setup.memoryProvider;
2256
3284
  this.ownsHost = setup.ownsHost;
2257
3285
  this.middlewareRunner = setup.middlewareRunner;
2258
3286
  this._logger = setup.logger;
@@ -2260,142 +3288,83 @@ var Agent = class _Agent {
2260
3288
  this.tracingShutdown = setup.tracingShutdown;
2261
3289
  this._signal = config.signal ?? new LocalSignal();
2262
3290
  }
2263
- /**
2264
- * Event signal — subscribe to events without consuming the generator.
2265
- *
2266
- * Every event yielded by `chat()` is also dispatched here, allowing
2267
- * multiple passive observers (SSE routes, TUI, plugins) to listen
2268
- * concurrently.
2269
- */
2270
3291
  get signal() {
2271
3292
  return this._signal;
2272
3293
  }
2273
- /** Structured logger — silent by default, configurable via `createAgent({ logger })`. */
2274
3294
  get logger() {
2275
3295
  return this._logger;
2276
3296
  }
2277
- /** Agent name (identity for spans, Dapr workflows, etc.) */
2278
3297
  get name() {
2279
3298
  return this.config.name ?? DEFAULT_AGENT_NAME;
2280
3299
  }
2281
- /** Working directory for file operations */
2282
3300
  get cwd() {
2283
3301
  return this.config.cwd;
2284
3302
  }
2285
- /** Current model */
2286
3303
  get model() {
2287
3304
  return this.config.model;
2288
3305
  }
2289
- /** System prompt */
2290
3306
  get systemPrompt() {
2291
3307
  return this.config.systemPrompt;
2292
3308
  }
2293
- /** Is currently streaming */
2294
3309
  get isStreaming() {
2295
3310
  return this.activeTurnCount > 0;
2296
3311
  }
2297
- /** Current reasoning level */
2298
3312
  get reasoningLevel() {
2299
3313
  return this.state.reasoningLevel;
2300
3314
  }
2301
- /**
2302
- * Set reasoning level
2303
- * Will be clamped to available levels for the current model
2304
- */
2305
3315
  setReasoningLevel(level) {
2306
3316
  const config = getReasoningConfigSync(this.state.model);
2307
3317
  const effectiveLevel = config.availableLevels.includes(level) ? level : config.availableLevels[config.availableLevels.length - 1];
2308
3318
  this.state.reasoningLevel = effectiveLevel;
2309
3319
  }
2310
- /**
2311
- * Get available reasoning levels for the current model
2312
- */
2313
3320
  getAvailableReasoningLevels() {
2314
3321
  return getReasoningConfigSync(this.state.model).availableLevels;
2315
3322
  }
2316
- /**
2317
- * Check if current model supports reasoning
2318
- */
2319
3323
  supportsReasoning() {
2320
3324
  return supportsReasoningSync(this.state.model);
2321
3325
  }
2322
- /**
2323
- * Ensure skill tools are registered when `prompt.skills` is configured.
2324
- * Lazy initialization — resolves the registry and adds tools on first use.
2325
- */
2326
3326
  async ensureSkillTools() {
2327
- if (this.skillToolsResolved || !this.promptBuilder) return;
2328
- this.skillToolsResolved = true;
2329
- const registry = await this.promptBuilder.getSkillRegistry(this.config.cwd);
2330
- if (registry.size > 0) {
2331
- for (const tool of createSkillTools(registry)) {
2332
- if (!this.tools.has(tool.id)) {
2333
- this.tools.set(tool.id, tool);
2334
- }
2335
- }
2336
- }
3327
+ this.skillToolsResolved = await ensureAgentSkillTools({
3328
+ tools: this.tools,
3329
+ promptBuilder: this.promptBuilder,
3330
+ cwd: this.config.cwd,
3331
+ resolved: this.skillToolsResolved
3332
+ });
2337
3333
  }
2338
3334
  resetPromptScopedTools() {
2339
- this.tools.delete("skill");
2340
- this.tools.delete("skill_resource");
3335
+ resetPromptScopedTools(this.tools);
2341
3336
  this.skillToolsResolved = false;
2342
3337
  }
2343
3338
  createSessionManager() {
2344
- return new SessionManager(this.sessions.getStorage());
3339
+ return createAgentSessionManager(this.sessions);
2345
3340
  }
2346
3341
  async acquireSessionLock(sessionId, options) {
2347
- return await this.sessionTurnLock.acquire(sessionId, options);
3342
+ return await acquireAgentSessionLock(
3343
+ this.sessionTurnLock,
3344
+ sessionId,
3345
+ options
3346
+ );
2348
3347
  }
2349
- /**
2350
- * Force-clear all pending session locks for a given session.
2351
- *
2352
- * This is an escape hatch for callers that manage sequencing
2353
- * externally (e.g. the coordinator loop) and need to guarantee a
2354
- * prior `chat()` generator's lock won't block the next call — even
2355
- * if the generator's cleanup is stuck on a network read.
2356
- *
2357
- * **Only use when you are certain no concurrent `chat()` calls are
2358
- * active on this session.**
2359
- */
2360
3348
  clearSessionLock(sessionId) {
2361
3349
  this.sessionTurnLock.clear?.(sessionId);
2362
3350
  }
2363
- /**
2364
- * Acquire the same per-session turn lock used by `chat()`.
2365
- *
2366
- * External durable runtimes can hold this lock across a workflow-backed
2367
- * turn so direct `chat()` calls cannot interleave with the same session.
2368
- */
2369
3351
  async acquireSessionTurnLock(sessionId) {
2370
3352
  return await this.acquireSessionLock(sessionId);
2371
3353
  }
2372
- getActiveInterventionController() {
2373
- const active = Array.from(this.activeTurns.values());
2374
- if (active.length === 0) {
2375
- return void 0;
2376
- }
2377
- if (active.length > 1) {
2378
- throw new Error(
2379
- "Interventions are ambiguous while multiple agent turns are active. Use separate Agent instances or wait for one turn to finish."
2380
- );
2381
- }
2382
- return active[0].interventionCtrl;
2383
- }
2384
3354
  getInterventionControllerForTurn() {
2385
- const activeController = this.getActiveInterventionController();
2386
- return activeController ?? this.interventionCtrl;
3355
+ return getAgentInterventionControllerForTurn(
3356
+ this.activeTurns,
3357
+ this.interventionCtrl
3358
+ );
2387
3359
  }
2388
3360
  createTurnInterventionController() {
2389
- return this.activeTurns.size === 0 ? this.interventionCtrl : new InterventionController();
3361
+ return createAgentTurnInterventionController(
3362
+ this.activeTurns,
3363
+ this.interventionCtrl
3364
+ );
2390
3365
  }
2391
3366
  releaseTurnInterventions(controller) {
2392
- if (controller === this.interventionCtrl) {
2393
- controller.resetCallbacks();
2394
- return;
2395
- }
2396
- this.interventionCtrl.adoptImmediate(controller.drainImmediate());
2397
- this.interventionCtrl.adoptDeferred(controller.drainDeferred());
2398
- controller.resetCallbacks();
3367
+ releaseAgentTurnInterventions(this.interventionCtrl, controller);
2399
3368
  }
2400
3369
  syncStreamingState(active) {
2401
3370
  this.activeTurnCount = Math.max(
@@ -2404,17 +3373,10 @@ var Agent = class _Agent {
2404
3373
  );
2405
3374
  }
2406
3375
  async syncSessionView(sessionId) {
2407
- if (!await this.sessions.sessionExists(sessionId)) {
2408
- return;
2409
- }
2410
- await this.sessions.load(sessionId);
3376
+ await syncAgentSessionView({ sessions: this.sessions, sessionId });
2411
3377
  }
2412
- /**
2413
- * Ensure MCP is connected and return tools
2414
- * Lazy initialization - only connects on first use
2415
- */
2416
3378
  async ensureMCPConnected() {
2417
- const nextState = await ensureMcpTools(
3379
+ const nextState = await ensureAgentMcpTools(
2418
3380
  {
2419
3381
  manager: this.mcpManager,
2420
3382
  connected: this.mcpConnected,
@@ -2426,184 +3388,87 @@ var Agent = class _Agent {
2426
3388
  this.mcpToolsCache = nextState.cachedTools;
2427
3389
  return nextState.cachedTools ?? {};
2428
3390
  }
2429
- /**
2430
- * Stream a chat response.
2431
- *
2432
- * Sends a user message and yields real-time {@link AgentEvent}s as the
2433
- * model responds, calls tools, and finishes. Conversation state is
2434
- * persisted to the session automatically.
2435
- *
2436
- * @param sessionId - Session identifier for conversation history
2437
- * @param message - User message to send
2438
- * @param options - Abort signal, system prompt override, and approval handler
2439
- * @yields {AgentEvent} Events as they occur during processing
2440
- */
2441
3391
  async *chat(sessionId, message, options) {
2442
- const releaseSessionLock = await this.acquireSessionLock(sessionId, {
2443
- signal: options?.abort
2444
- });
2445
- const sessions = this.createSessionManager();
2446
3392
  const turnId = `${sessionId}-turn-${++this.turnCounter}`;
2447
- let turnTracker;
2448
- let interventionCtrl = this.interventionCtrl;
2449
- let streamingStateActive = false;
2450
- let turnRegistered = false;
2451
- try {
2452
- await this.ensureSkillTools();
2453
- const abort = options?.abort ?? new AbortController().signal;
2454
- turnTracker = createTurnTracker({ cwd: this.config.cwd });
2455
- interventionCtrl = this.createTurnInterventionController();
2456
- this.activeTurns.set(turnId, { sessionId, interventionCtrl });
2457
- turnRegistered = true;
2458
- await ensureSessionLoaded({
2459
- sessionId,
2460
- sessions,
2461
- cwd: this.config.cwd
2462
- });
2463
- turnTracker.startTurn(turnId);
2464
- await repairOrphanedToolCalls(sessions);
2465
- const mcpTools = await this.ensureMCPConnected();
2466
- const loop = runChatLoop({
2467
- sessionId,
2468
- turnId,
2469
- message,
2470
- abort,
2471
- systemOverride: options?.system,
2472
- sessions,
2473
- tools: this.tools,
3393
+ yield* runAgentChatTurn({
3394
+ runtime: {
2474
3395
  config: this.config,
2475
- turnTracker,
2476
- interventionCtrl,
2477
- middlewareRunner: this.middlewareRunner,
3396
+ tools: this.tools,
2478
3397
  contextManager: this.contextManager,
2479
3398
  rememberedDoomLoopTools: this.rememberedDoomLoopTools,
2480
3399
  reasoningLevel: this.state.reasoningLevel,
2481
3400
  promptBuilder: this.promptBuilder,
2482
3401
  host: this.host,
2483
3402
  humanInputController: this.humanInputController,
2484
- mcpTools,
3403
+ memoryProvider: this.memoryProvider,
2485
3404
  turnToolProviders: this.turnToolProviders,
2486
3405
  telemetrySettings: this.telemetrySettings,
2487
- toModelMessages: convertAgentMessagesToModelMessages,
2488
- setIsStreaming: (value) => {
2489
- if (value === streamingStateActive) return;
2490
- streamingStateActive = value;
2491
- this.syncStreamingState(value);
2492
- },
2493
- toolExecutionMode: this.config.toolExecutionMode,
2494
- logger: this._logger
2495
- });
2496
- for await (const event of loop) {
2497
- this._signal.emit(event);
2498
- yield event;
2499
- }
2500
- } finally {
2501
- try {
2502
- if (streamingStateActive) {
2503
- this.syncStreamingState(false);
2504
- }
2505
- if (turnRegistered) {
2506
- this.activeTurns.delete(turnId);
2507
- }
2508
- this.releaseTurnInterventions(interventionCtrl);
2509
- if (turnRegistered && turnTracker) {
2510
- this.turnTracker = turnTracker;
3406
+ middlewareRunner: this.middlewareRunner,
3407
+ signal: this._signal,
3408
+ logger: this._logger,
3409
+ activeTurns: this.activeTurns,
3410
+ acquireSessionLock: (id, lockOptions) => this.acquireSessionLock(id, lockOptions),
3411
+ createSessionManager: () => this.createSessionManager(),
3412
+ ensureSkillTools: () => this.ensureSkillTools(),
3413
+ createTurnInterventionController: () => this.createTurnInterventionController(),
3414
+ releaseTurnInterventions: (controller) => this.releaseTurnInterventions(controller),
3415
+ ensureMcpConnected: () => this.ensureMCPConnected(),
3416
+ syncStreamingState: (active) => this.syncStreamingState(active),
3417
+ syncSessionView: (id) => this.syncSessionView(id),
3418
+ setTurnTracker: (tracker) => {
3419
+ this.turnTracker = tracker;
2511
3420
  }
2512
- await this.syncSessionView(sessionId);
2513
- } finally {
2514
- await releaseSessionLock();
2515
- }
2516
- }
3421
+ },
3422
+ sessionId,
3423
+ turnId,
3424
+ message,
3425
+ options
3426
+ });
2517
3427
  }
2518
- /**
2519
- * Send a message and wait for the complete response (non-streaming).
2520
- *
2521
- * This is a convenience wrapper around {@link chat} that buffers all
2522
- * events internally and returns the final response, usage, and tool
2523
- * call results. Prefer `chat()` when you need real-time streaming.
2524
- *
2525
- * @param sessionId - Session identifier
2526
- * @param message - User message
2527
- * @param options - Abort signal and optional system prompt override
2528
- */
2529
3428
  async send(sessionId, message, options) {
2530
- const events = this.chat(sessionId, message, options);
2531
- let response = "";
2532
- let usage = { inputTokens: 0, outputTokens: 0, totalTokens: 0 };
2533
- const toolCalls = [];
2534
- for await (const event of events) {
2535
- switch (event.type) {
2536
- case "text-delta":
2537
- response += event.text;
2538
- break;
2539
- case "tool-result":
2540
- toolCalls.push({ name: event.toolName, result: event.result });
2541
- break;
2542
- case "complete":
2543
- if (event.usage) usage = event.usage;
2544
- if (event.output !== void 0) response = event.output;
2545
- break;
2546
- case "error":
2547
- throw event.error;
2548
- }
2549
- }
2550
- return { response, usage, toolCalls };
3429
+ return await sendAgentMessage(
3430
+ (id, text, chatOptions) => this.chat(id, text, chatOptions),
3431
+ sessionId,
3432
+ message,
3433
+ options
3434
+ );
2551
3435
  }
2552
3436
  // ============================================================================
2553
3437
  // Tool Management
2554
3438
  // ============================================================================
2555
- /** Add a tool at runtime */
2556
3439
  addTool(tool) {
2557
- this.tools.set(tool.id, tool);
3440
+ addAgentTool(this.tools, tool);
2558
3441
  }
2559
- /** Remove a tool by ID */
2560
3442
  removeTool(toolId) {
2561
- return this.tools.delete(toolId);
3443
+ return removeAgentTool(this.tools, toolId);
2562
3444
  }
2563
- /** Get all tool IDs */
2564
3445
  getToolIds() {
2565
- return Array.from(this.tools.keys());
3446
+ return getAgentToolIds(this.tools);
2566
3447
  }
2567
- /** Get all tools */
2568
3448
  getTools() {
2569
- return Array.from(this.tools.values());
3449
+ return getAgentTools(this.tools);
2570
3450
  }
2571
- /** Check if a tool exists */
2572
3451
  hasTool(toolId) {
2573
- return this.tools.has(toolId);
3452
+ return hasAgentTool(this.tools, toolId);
2574
3453
  }
2575
3454
  // ============================================================================
2576
3455
  // Session Management
2577
3456
  // ============================================================================
2578
- /** Get session manager */
2579
3457
  getSessionManager() {
2580
3458
  return this.sessions;
2581
3459
  }
2582
- /** Get current session context */
2583
3460
  getSessionContext() {
2584
3461
  return this.sessions.getContext();
2585
3462
  }
2586
- /**
2587
- * Get messages from current session.
2588
- *
2589
- * NOTE: during an active `chat()` turn, messages are accumulated in a
2590
- * per-turn SessionManager and synced back after the turn completes.
2591
- * Calling this mid-turn returns the shared view, which may lag behind
2592
- * the in-progress turn. Use `send()` or consume the `chat()` generator
2593
- * for real-time access to turn messages.
2594
- */
2595
3463
  getMessages() {
2596
3464
  return this.sessions.getMessages();
2597
3465
  }
2598
- /** Delete a session */
2599
3466
  async deleteSession(sessionId) {
2600
3467
  return this.sessions.deleteSession(sessionId);
2601
3468
  }
2602
- /** List all sessions */
2603
3469
  async listSessions() {
2604
3470
  return this.sessions.listSessions();
2605
3471
  }
2606
- /** Branch from current point */
2607
3472
  async branch(summary) {
2608
3473
  const leafId = this.sessions.getLeafId();
2609
3474
  if (!leafId) {
@@ -2614,226 +3479,83 @@ var Agent = class _Agent {
2614
3479
  // ============================================================================
2615
3480
  // Context Management
2616
3481
  // ============================================================================
2617
- /**
2618
- * Get context window statistics.
2619
- *
2620
- * Useful for UI to display context utilization like:
2621
- * - Progress bar showing how full the context is
2622
- * - Warning when approaching limit
2623
- * - Info about when compaction will trigger
2624
- *
2625
- * @example
2626
- * ```typescript
2627
- * const stats = agent.getContextStats();
2628
- * console.log(`Context: ${stats.utilizationPercent}% used`);
2629
- * if (stats.shouldPrune) {
2630
- * console.log('Context will be compacted soon');
2631
- * }
2632
- * ```
2633
- */
2634
3482
  getContextStats() {
2635
- return this.contextManager.getStats(this.sessions.getMessages());
3483
+ return getAgentContextStats({
3484
+ contextManager: this.contextManager,
3485
+ sessions: this.sessions
3486
+ });
2636
3487
  }
2637
- /**
2638
- * Manually trigger context compaction.
2639
- *
2640
- * Usually auto-compaction handles this, but you can trigger it manually
2641
- * if needed (e.g., before a long operation).
2642
- *
2643
- * @returns Pruning result with details about what was removed/summarized
2644
- */
2645
3488
  async compactContext() {
2646
- return await compactAgentContext({
3489
+ return await compactLoadedAgentContext({
2647
3490
  contextManager: this.contextManager,
2648
3491
  sessions: this.sessions,
2649
- logger: this._logger
3492
+ logger: this._logger,
3493
+ memoryProvider: this.memoryProvider,
3494
+ sessionId: this.sessions.getSessionId() ?? void 0,
3495
+ cwd: this.config.cwd
3496
+ });
3497
+ }
3498
+ async compactMessages(messages, options = {}) {
3499
+ return await compactAgentMessageList({
3500
+ contextManager: this.contextManager,
3501
+ messages,
3502
+ logger: this._logger,
3503
+ force: options.force,
3504
+ memoryProvider: this.memoryProvider,
3505
+ sessionId: this.sessions.getSessionId() ?? void 0,
3506
+ cwd: this.config.cwd
2650
3507
  });
2651
3508
  }
2652
- /**
2653
- * Clear remembered doom loop tools.
2654
- *
2655
- * When a user says "remember" for a doom loop, that tool is added
2656
- * to a set that skips future doom loop checks. Call this to reset.
2657
- */
2658
3509
  clearRememberedDoomLoopTools() {
2659
3510
  this.rememberedDoomLoopTools.clear();
2660
3511
  }
2661
3512
  // ============================================================================
2662
3513
  // Intervention (Mid-Turn Message Injection)
2663
3514
  // ============================================================================
2664
- /**
2665
- * Inject a message at the next step boundary of a running turn.
2666
- *
2667
- * This is the primary redirection mechanism. When the agent is
2668
- * streaming a multi-step response (calling tools, reasoning, etc.),
2669
- * this injects a user message before the next LLM call. The LLM
2670
- * sees the intervention and can adjust its behavior.
2671
- *
2672
- * Uses Vercel AI SDK v6's `prepareStep` hook — no polling, no
2673
- * custom loop code. The SDK handles the injection naturally.
2674
- *
2675
- * Safe to call from any async context (UI event handlers, WebSocket
2676
- * callbacks, timers, etc.) while `chat()` is running.
2677
- *
2678
- * If called when no turn is active, the message will be picked up
2679
- * by the first step of the next `chat()` call.
2680
- * If multiple turns are active concurrently, this throws because the
2681
- * target turn would be ambiguous.
2682
- *
2683
- * @param message - The user message to inject mid-turn
2684
- * @returns Intervention ID for tracking
2685
- *
2686
- * @example
2687
- * ```typescript
2688
- * // Start a streaming turn
2689
- * const stream = agent.chat("session-1", "refactor the auth module");
2690
- *
2691
- * // From a UI handler (another async context):
2692
- * agent.intervene("stop, focus only on JWT validation in auth.ts");
2693
- *
2694
- * // The stream will yield an intervention-applied event
2695
- * for await (const event of stream) {
2696
- * if (event.type === "intervention-applied") {
2697
- * console.log(`Redirected: ${event.message}`);
2698
- * }
2699
- * }
2700
- * ```
2701
- */
2702
3515
  intervene(message) {
2703
3516
  return this.getInterventionControllerForTurn().intervene(message);
2704
3517
  }
2705
- /**
2706
- * Queue a message for after the current turn completes.
2707
- *
2708
- * Unlike `intervene()`, this does **not** interrupt the current turn.
2709
- * The message is held and available via `drainQueuedNext()` after
2710
- * `chat()` finishes. The consumer decides whether to send it as a
2711
- * new turn.
2712
- *
2713
- * If multiple turns are active concurrently, this throws because the
2714
- * target turn would be ambiguous.
2715
- *
2716
- * @param message - The message to queue
2717
- * @returns Intervention ID for tracking
2718
- *
2719
- * @example
2720
- * ```typescript
2721
- * agent.queueNext("now run the test suite");
2722
- *
2723
- * for await (const event of agent.chat("s1", "fix the bug")) {
2724
- * // ... handle events
2725
- * }
2726
- *
2727
- * // After turn completes, check for queued messages
2728
- * if (agent.hasQueuedNext()) {
2729
- * const next = agent.drainQueuedNext();
2730
- * for (const item of next) {
2731
- * // Send as a new turn
2732
- * for await (const ev of agent.chat("s1", item.message)) { ... }
2733
- * }
2734
- * }
2735
- * ```
2736
- */
2737
3518
  queueNext(message) {
2738
3519
  return this.getInterventionControllerForTurn().queueNext(message);
2739
3520
  }
2740
- /** Whether there are deferred messages queued for after the turn */
2741
3521
  hasQueuedNext() {
2742
3522
  return this.getInterventionControllerForTurn().hasDeferred;
2743
3523
  }
2744
- /** Drain and return all deferred messages (clears the queue) */
2745
3524
  drainQueuedNext() {
2746
3525
  return this.getInterventionControllerForTurn().drainDeferred();
2747
3526
  }
2748
- /**
2749
- * Get the raw intervention controller for advanced use cases.
2750
- *
2751
- * Use this when you need fine-grained control over the intervention
2752
- * lifecycle (e.g., checking pending count, clearing queues, setting
2753
- * custom `onApplied` callbacks).
2754
- *
2755
- * @internal
2756
- */
2757
3527
  getInterventionController() {
2758
3528
  return this.getInterventionControllerForTurn();
2759
3529
  }
2760
3530
  // ============================================================================
2761
3531
  // Turn Tracking
2762
3532
  // ============================================================================
2763
- /**
2764
- * Get the unified diff for all file changes in the current/last turn.
2765
- *
2766
- * @example
2767
- * ```typescript
2768
- * const diff = await agent.getTurnDiff();
2769
- * if (diff) {
2770
- * console.log('Changes this turn:\n', diff);
2771
- * }
2772
- * ```
2773
- */
2774
3533
  async getTurnDiff() {
2775
3534
  return this.turnTracker.getDiff();
2776
3535
  }
2777
- /**
2778
- * Get list of files being tracked in the current turn.
2779
- */
2780
3536
  getTrackedFiles() {
2781
3537
  return this.turnTracker.getTrackedFiles();
2782
3538
  }
2783
- /**
2784
- * Undo all file changes from the current turn.
2785
- * Restores files to their state before the turn started.
2786
- *
2787
- * @example
2788
- * ```typescript
2789
- * const result = await agent.undoTurn();
2790
- * console.log(`Restored ${result.restored.length} files`);
2791
- * if (result.failed.length > 0) {
2792
- * console.log('Failed to restore:', result.failed);
2793
- * }
2794
- * ```
2795
- */
2796
3539
  async undoTurn() {
2797
3540
  return this.turnTracker.undoTurn();
2798
3541
  }
2799
- /**
2800
- * Undo changes to specific files only.
2801
- *
2802
- * @param files - Array of file paths to restore (relative to cwd)
2803
- */
2804
3542
  async undoFiles(files) {
2805
3543
  return this.turnTracker.undoFiles(files);
2806
3544
  }
2807
- /**
2808
- * Check if currently tracking a turn.
2809
- */
2810
3545
  isTrackingTurn() {
2811
3546
  return this.turnTracker.isInTurn();
2812
3547
  }
2813
- /**
2814
- * Get access to the raw turn tracker for advanced use cases.
2815
- *
2816
- * @internal
2817
- */
2818
3548
  getTurnTracker() {
2819
3549
  return this.turnTracker;
2820
3550
  }
2821
3551
  // ============================================================================
2822
3552
  // Configuration
2823
3553
  // ============================================================================
2824
- /**
2825
- * Update system prompt.
2826
- *
2827
- * If the agent is using the prompt pipeline, calling this switches
2828
- * to flat string mode (disabling the pipeline). To modify the pipeline
2829
- * instead, use `getPromptBuilder()`.
2830
- */
2831
3554
  setSystemPrompt(prompt) {
2832
3555
  this.config.systemPrompt = prompt;
2833
3556
  this.promptBuilder = void 0;
2834
3557
  this.resetPromptScopedTools();
2835
3558
  }
2836
- /** Update working directory */
2837
3559
  setCwd(cwd) {
2838
3560
  this.config.cwd = cwd;
2839
3561
  this.turnTracker = createTurnTracker({ cwd });
@@ -2843,13 +3565,10 @@ var Agent = class _Agent {
2843
3565
  this.resetPromptScopedTools();
2844
3566
  this.promptBuilder?.clearCache();
2845
3567
  }
2846
- /** Update model */
2847
3568
  setModel(model) {
2848
3569
  this.config.model = model;
2849
3570
  this.state.model = model;
2850
- if (this.config.compaction?.summaryModel === void 0) {
2851
- this.contextManager.setModel(model);
2852
- }
3571
+ this.contextManager.setModel(model);
2853
3572
  if (this.config.contextWindow === void 0) {
2854
3573
  const modelId = extractModelId(model);
2855
3574
  const inferred = inferContextWindow(modelId);
@@ -2861,41 +3580,12 @@ var Agent = class _Agent {
2861
3580
  }
2862
3581
  }
2863
3582
  }
2864
- /**
2865
- * Get the prompt builder (when using pipeline mode).
2866
- * Returns undefined if using flat string mode.
2867
- *
2868
- * Use this to add/remove sections, clear caches, or inspect
2869
- * the prompt composition without switching to flat mode.
2870
- *
2871
- * @example
2872
- * ```typescript
2873
- * const builder = agent.getPromptBuilder();
2874
- * if (builder) {
2875
- * builder.addSection({
2876
- * id: "task-context",
2877
- * label: "Task Context",
2878
- * content: "Focus on fixing authentication bugs.",
2879
- * priority: 60,
2880
- * });
2881
- * }
2882
- * ```
2883
- */
2884
3583
  getPromptBuilder() {
2885
3584
  return this.promptBuilder;
2886
3585
  }
2887
- /**
2888
- * Check if the agent is using the prompt pipeline.
2889
- */
2890
3586
  isUsingPromptPipeline() {
2891
3587
  return this.promptBuilder !== void 0;
2892
3588
  }
2893
- /**
2894
- * Build the effective system prompts for a turn.
2895
- *
2896
- * This mirrors the prompt resolution path used by `chat()` so external host
2897
- * runtimes can start durable turns without duplicating prompt assembly.
2898
- */
2899
3589
  async buildSystemPrompts(sessionId, override) {
2900
3590
  await this.ensureSkillTools();
2901
3591
  return await buildAgentSystemPrompts({
@@ -2907,10 +3597,6 @@ var Agent = class _Agent {
2907
3597
  middlewareRunner: this.middlewareRunner
2908
3598
  });
2909
3599
  }
2910
- /**
2911
- * Return the runtime configuration required by the extracted turn-step
2912
- * helpers.
2913
- */
2914
3600
  getTurnRuntimeConfig() {
2915
3601
  return createAgentTurnRuntimeConfig({
2916
3602
  config: this.config,
@@ -2918,90 +3604,37 @@ var Agent = class _Agent {
2918
3604
  reserveTokens: this.contextManager.getLimits().reserveTokens
2919
3605
  });
2920
3606
  }
2921
- /**
2922
- * Get the configured tool host.
2923
- */
2924
3607
  getHost() {
2925
3608
  return this.host;
2926
3609
  }
2927
- /**
2928
- * Get the configured sandbox session, if one was provided.
2929
- */
2930
3610
  getSandbox() {
2931
3611
  return this.sandbox;
2932
3612
  }
2933
- /**
2934
- * Get the configured human-input controller, if one was provided.
2935
- */
2936
3613
  getHumanInputController() {
2937
3614
  return this.humanInputController;
2938
3615
  }
2939
- /**
2940
- * Whether any registered tool advertises human-input semantics.
2941
- */
3616
+ getMemoryProvider() {
3617
+ return this.memoryProvider;
3618
+ }
2942
3619
  hasHumanInputTools() {
2943
- return [...this.tools.values()].some(
2944
- (tool) => tool.capabilitiesHint?.humanInput === true
2945
- );
3620
+ return hasAgentHumanInputTools(this.tools);
2946
3621
  }
2947
- /**
2948
- * Get the configured middleware runner.
2949
- *
2950
- * The runner is immutable after construction, so it is safe to reuse in
2951
- * durable activity helpers that need the same middleware stack.
2952
- */
2953
3622
  getMiddlewareRunner() {
2954
3623
  return this.middlewareRunner;
2955
3624
  }
2956
- /**
2957
- * Get the configured middleware stack.
2958
- */
2959
3625
  getMiddleware() {
2960
3626
  return this.middlewareRunner.getMiddleware();
2961
3627
  }
2962
- /**
2963
- * Ensure MCP is connected and return the current MCP tool set.
2964
- */
2965
3628
  async getMcpTools() {
2966
3629
  return await this.ensureMCPConnected();
2967
3630
  }
2968
3631
  // ============================================================================
2969
3632
  // Sub-Agents (Forking)
2970
3633
  // ============================================================================
2971
- /**
2972
- * Fork this agent to create a sub-agent with modified configuration.
2973
- *
2974
- * Sub-agents share the same session manager but can have different:
2975
- * - System prompts (specialized for tasks)
2976
- * - Tools (restricted subset)
2977
- * - Models (cheaper/faster for simple tasks)
2978
- * - Reasoning levels
2979
- *
2980
- * @example
2981
- * ```typescript
2982
- * // Create an exploration sub-agent with read-only tools
2983
- * const explorer = agent.fork({
2984
- * name: "explore",
2985
- * systemPrompt: "You explore codebases. Only use read and search tools.",
2986
- * tools: [readTool, grepTool, globTool],
2987
- * });
2988
- *
2989
- * // Run the sub-agent
2990
- * const result = await explorer.run({
2991
- * parentSessionId: "main-session",
2992
- * message: "Find all API endpoints",
2993
- * });
2994
- * ```
2995
- */
2996
3634
  fork(options = {}) {
2997
- const effectiveOptions = resolveForkOptions(
2998
- options,
2999
- Array.from(this.tools.values()),
3000
- this.config.systemPrompt
3001
- );
3002
3635
  return new _Agent(
3003
- createForkedAgentConfig({
3004
- forkOptions: effectiveOptions,
3636
+ createSubAgentConfig({
3637
+ forkOptions: options,
3005
3638
  parentConfig: this.config,
3006
3639
  parentTools: Array.from(this.tools.values()),
3007
3640
  reasoningLevel: this.state.reasoningLevel,
@@ -3016,49 +3649,9 @@ var Agent = class _Agent {
3016
3649
  })
3017
3650
  );
3018
3651
  }
3019
- /**
3020
- * Create a sub-agent with a profile.
3021
- *
3022
- * Convenience method that applies a profile and returns a forked agent.
3023
- *
3024
- * @example
3025
- * ```typescript
3026
- * import { Profiles } from "@cuylabs/agent-core";
3027
- *
3028
- * // Create an exploration sub-agent
3029
- * const explorer = agent.withProfile(Profiles.explore);
3030
- * const result = await explorer.run({
3031
- * message: "Find all API routes in this project",
3032
- * });
3033
- *
3034
- * // Create a careful review sub-agent
3035
- * const reviewer = agent.withProfile(Profiles.review);
3036
- * const review = await reviewer.run({
3037
- * message: "Review src/auth.ts for security issues",
3038
- * });
3039
- * ```
3040
- */
3041
3652
  withProfile(profile) {
3042
3653
  return this.fork({ profile });
3043
3654
  }
3044
- /**
3045
- * Run a task in an isolated sub-agent session.
3046
- *
3047
- * Creates a new session linked to the parent, runs the task to completion,
3048
- * and returns the result. The sub-agent session is preserved for inspection.
3049
- *
3050
- * @example
3051
- * ```typescript
3052
- * const result = await agent.run({
3053
- * parentSessionId: "main-session",
3054
- * message: "Review this code for security issues",
3055
- * title: "Security Review",
3056
- * });
3057
- *
3058
- * console.log(result.response);
3059
- * console.log(`Sub-agent session: ${result.sessionId}`);
3060
- * ```
3061
- */
3062
3655
  async run(options) {
3063
3656
  const sessions = this.createSessionManager();
3064
3657
  const sessionId = await createSubAgentRunSession({
@@ -3078,54 +3671,50 @@ var Agent = class _Agent {
3078
3671
  // =========================================================================
3079
3672
  // MCP Methods
3080
3673
  // =========================================================================
3081
- /**
3082
- * Get the MCP manager (if configured)
3083
- */
3084
3674
  getMCP() {
3085
3675
  return this.mcpManager;
3086
3676
  }
3087
- /**
3088
- * Check if MCP is configured
3089
- */
3090
3677
  hasMCP() {
3091
3678
  return this.mcpManager !== void 0;
3092
3679
  }
3093
- /**
3094
- * Reconnect to MCP servers
3095
- *
3096
- * Use this after network issues or when server availability changes.
3097
- * Clears tool cache and reconnects all servers.
3098
- */
3099
3680
  async reconnectMCP() {
3100
- if (!this.mcpManager) return;
3101
- const nextState = await closeMcpManager(this.mcpManager);
3681
+ const nextState = await reconnectAgentMcp(
3682
+ {
3683
+ manager: this.mcpManager,
3684
+ connected: this.mcpConnected,
3685
+ cachedTools: this.mcpToolsCache
3686
+ },
3687
+ this._logger
3688
+ );
3102
3689
  this.mcpConnected = nextState.connected;
3103
3690
  this.mcpToolsCache = nextState.cachedTools;
3104
- await this.ensureMCPConnected();
3105
3691
  }
3106
3692
  // =========================================================================
3107
3693
  // Cleanup
3108
3694
  // =========================================================================
3109
- /**
3110
- * Close the agent and clean up resources
3111
- *
3112
- * Flushes and shuts down the tracing provider (when `tracing` was configured),
3113
- * closes MCP connections if configured.
3114
- * After calling close(), the agent should not be used.
3115
- */
3116
3695
  async close() {
3117
3696
  this._signal.clear();
3118
3697
  this.humanInputController?.cancelAll("Agent closed");
3698
+ await this.memoryProvider?.shutdown?.();
3119
3699
  if (this.tracingShutdown) {
3120
3700
  await this.tracingShutdown();
3121
3701
  }
3122
- const nextState = await closeMcpManager(this.mcpManager);
3702
+ const nextState = await closeAgentMcp(this.mcpManager);
3123
3703
  this.mcpConnected = nextState.connected;
3124
3704
  this.mcpToolsCache = nextState.cachedTools;
3125
3705
  }
3126
3706
  };
3127
3707
 
3128
3708
  // src/agent/event-printer.ts
3709
+ function formatContextCompactionEvent(event) {
3710
+ if (event.removedCount === 0 && event.tokensRemoved > 0 && !event.cutReason) {
3711
+ return `\u{1F4E6} Context compaction (${event.phase}): compacted tool context, ${event.tokensRemoved} tokens
3712
+ `;
3713
+ }
3714
+ const cutReason = event.cutReason ? `, reason=${event.cutReason}` : "";
3715
+ return `\u{1F4E6} Context compaction (${event.phase}): removed ${event.removedCount} message(s), ${event.tokensRemoved} tokens${cutReason}
3716
+ `;
3717
+ }
3129
3718
  function createEventPrinter(options = {}) {
3130
3719
  const {
3131
3720
  tools = true,
@@ -3230,6 +3819,9 @@ function createEventPrinter(options = {}) {
3230
3819
  `
3231
3820
  );
3232
3821
  break;
3822
+ case "context-compaction":
3823
+ if (safety) stderr.write(formatContextCompactionEvent(event));
3824
+ break;
3233
3825
  case "turn-summary":
3234
3826
  if (safety)
3235
3827
  stderr.write(
@@ -3348,16 +3940,22 @@ function canSeedQueuedFollowUp(record) {
3348
3940
  return record.status === "queued" && record.mode === "auto-run";
3349
3941
  }
3350
3942
  export {
3943
+ AGENT_CONTEXT_FRAGMENT_CLOSE,
3944
+ AGENT_CONTEXT_FRAGMENT_OPEN,
3945
+ AGENT_CONTEXT_FRAGMENT_TAG,
3351
3946
  Agent,
3352
3947
  AgentTurnEngine,
3948
+ AgentTurnStateConflictError,
3353
3949
  ApprovalDeniedError,
3354
3950
  ApprovalTimeoutError,
3355
3951
  CacheCapabilitySource,
3356
3952
  CapabilityCache,
3357
3953
  ClientCredentialsProvider,
3358
- ContextManager,
3359
3954
  ContextOverflowError,
3955
+ ContextSummaryModelRequiredError,
3956
+ ContextWindowManager,
3360
3957
  DEFAULT_AGENT_NAME,
3958
+ DEFAULT_COMPACTION_EFFECTIVE_MIN_SAVINGS_RATIO,
3361
3959
  DEFAULT_CONTEXT_LIMITS,
3362
3960
  DEFAULT_DISPATCH_TOOL_IDS,
3363
3961
  DEFAULT_EXTERNAL_DIRS,
@@ -3367,7 +3965,7 @@ export {
3367
3965
  DEFAULT_LOCAL_DISPATCH_TITLE_PREFIX,
3368
3966
  DEFAULT_MAX_DEPTH,
3369
3967
  DEFAULT_MAX_FILE_SIZE,
3370
- DEFAULT_MAX_TOKENS as DEFAULT_MAX_OUTPUT_TOKENS,
3968
+ DEFAULT_MAX_OUTPUT_TOKENS,
3371
3969
  DEFAULT_MAX_SCAN_DEPTH,
3372
3970
  DEFAULT_MAX_STEPS,
3373
3971
  DEFAULT_MAX_TOKENS,
@@ -3377,6 +3975,8 @@ export {
3377
3975
  DEFAULT_SUBAGENT_CONCURRENCY,
3378
3976
  DEFAULT_SUBAGENT_DEPTH,
3379
3977
  DEFAULT_SUBAGENT_SESSION_PREFIX,
3978
+ DEFAULT_SUMMARY_MAX_INPUT_TOKENS,
3979
+ DEFAULT_SUMMARY_MAX_OUTPUT_TOKENS,
3380
3980
  DEFAULT_SYSTEM_PROMPT,
3381
3981
  DISPATCH_STATES,
3382
3982
  DoomLoopError,
@@ -3437,7 +4037,10 @@ export {
3437
4037
  advanceAgentTurnState,
3438
4038
  allApprovalConditions,
3439
4039
  anyApprovalConditions,
4040
+ applyAgentContextFragments,
4041
+ applyAgentContextFragmentsWithReport,
3440
4042
  applyAgentWorkflowCommitResult,
4043
+ applyAgentWorkflowContextCompactionResult,
3441
4044
  applyAgentWorkflowModelStepResult,
3442
4045
  applyAgentWorkflowToolBatchResult,
3443
4046
  applyAgentWorkflowToolCallResult,
@@ -3446,6 +4049,7 @@ export {
3446
4049
  applyWorkflowInterventions,
3447
4050
  approvalMiddleware,
3448
4051
  approvalRequestsOverlap,
4052
+ assembleModelContext,
3449
4053
  autoDetectStreamProvider,
3450
4054
  buildAnthropicOptions,
3451
4055
  buildApprovalRuleContext,
@@ -3466,6 +4070,7 @@ export {
3466
4070
  buildToolSet,
3467
4071
  buildXAIOptions,
3468
4072
  calculateDelay,
4073
+ canGenerateCompactionSummary,
3469
4074
  canSeedQueuedFollowUp,
3470
4075
  careful,
3471
4076
  clearInstalledSubAgents,
@@ -3473,12 +4078,14 @@ export {
3473
4078
  code,
3474
4079
  commitOutput,
3475
4080
  commitStep,
4081
+ compactAgentMessages,
3476
4082
  configureDefaultSessionManager,
3477
4083
  configureResolver,
3478
4084
  configureSubAgents,
3479
4085
  convertAgentMessagesToModelMessages,
3480
4086
  coordinatorToolDescriptions,
3481
4087
  createAgent,
4088
+ createAgentContextFragmentMessage,
3482
4089
  createAgentTaskRunner,
3483
4090
  createAgentTurnEngine,
3484
4091
  createAgentTurnState,
@@ -3488,6 +4095,8 @@ export {
3488
4095
  createApprovalHandler,
3489
4096
  createApprovalPolicyPreset,
3490
4097
  createCloseAgentTool,
4098
+ createCompactionEffectiveness,
4099
+ createCompactionSummaryContent,
3491
4100
  createCompositeDispatchTaskExecutor,
3492
4101
  createConditionalApprovalRule,
3493
4102
  createConsoleLogger,
@@ -3509,6 +4118,7 @@ export {
3509
4118
  createInvokeAgentTool,
3510
4119
  createLocalDispatchRuntime,
3511
4120
  createMCPManager,
4121
+ createMemoryMiddleware,
3512
4122
  createMessageEntry,
3513
4123
  createMetadataEntry,
3514
4124
  createProfile,
@@ -3534,6 +4144,7 @@ export {
3534
4144
  createTurnTracker,
3535
4145
  createWaitAgentTool,
3536
4146
  currentScope,
4147
+ decideContextCompaction,
3537
4148
  defaultAgentTaskCheckpointStrategy,
3538
4149
  defaultRegistry,
3539
4150
  defaultToolHostRegistry,
@@ -3556,6 +4167,7 @@ export {
3556
4167
  executeAgentToolCall,
3557
4168
  explore,
3558
4169
  extractApprovalPatterns,
4170
+ extractCompactionSummaryText,
3559
4171
  extractFilePathsFromArgs,
3560
4172
  extractModelId,
3561
4173
  extractProvider,
@@ -3564,7 +4176,6 @@ export {
3564
4176
  failAgentWorkflowTurnState,
3565
4177
  filterTools,
3566
4178
  findCapabilityOverride,
3567
- findCutPoint,
3568
4179
  formatApprovalDeniedReason,
3569
4180
  formatAsyncSpawnedResult,
3570
4181
  formatCancelledAgentResult,
@@ -3576,6 +4187,7 @@ export {
3576
4187
  formatEnvironment,
3577
4188
  formatInstructions,
3578
4189
  formatInvalidAgentTypeResult,
4190
+ formatMemoryContextFragment,
3579
4191
  formatMissingAgentsResult,
3580
4192
  formatSpawnBlockedResult,
3581
4193
  formatSyncSubAgentErrorResult,
@@ -3585,8 +4197,12 @@ export {
3585
4197
  formatWaitTimeoutResult,
3586
4198
  gatherEnvironment,
3587
4199
  generateEntryId,
4200
+ generateSplitTurnSummary,
4201
+ generateSummary,
4202
+ getAgentContextFragmentMetadata,
3588
4203
  getAvailableFamilies,
3589
4204
  getConfiguredSubAgents,
4205
+ getCurrentAgentTurnStepRecord,
3590
4206
  getDataDir,
3591
4207
  getDefaultResolver,
3592
4208
  getDefaultSessionManager,
@@ -3618,11 +4234,14 @@ export {
3618
4234
  inferResourceType,
3619
4235
  installLocalSubAgents,
3620
4236
  installSubAgentTools,
4237
+ isAgentContextFragmentMessage,
3621
4238
  isApprovalMiddleware,
3622
4239
  isBlockedModelCall,
4240
+ isContextOverflowing,
3623
4241
  isDefinedPlugin,
3624
4242
  isHumanInputController,
3625
4243
  isMarkdownSubAgentRole,
4244
+ isRenderedAgentContextFragment,
3626
4245
  isRetryable,
3627
4246
  isRetryableCategory,
3628
4247
  likelySupportsReasoning,
@@ -3639,34 +4258,48 @@ export {
3639
4258
  matchApprovalRisks,
3640
4259
  matchApprovalSessions,
3641
4260
  matchApprovalStringPrefixes,
4261
+ mergeAgentTurnStateProgress,
3642
4262
  mergeInspection,
3643
4263
  mergeProfiles,
4264
+ normalizeAgentContextFragment,
3644
4265
  normalizeApprovalCascadePolicy,
3645
4266
  normalizeFollowUpMode,
4267
+ normalizeMemoryRecords,
3646
4268
  normalizeRememberScopes,
3647
4269
  normalizeToolReplayPolicy,
3648
4270
  otelMiddleware,
3649
4271
  parseFrontmatter,
3650
4272
  parseJSONL,
3651
4273
  parseMarkdownSubAgentRole,
4274
+ parseRenderedAgentContextFragment,
3652
4275
  parseRetryDelay,
3653
4276
  parseSubAgentRoleFrontmatter,
3654
4277
  parseSubAgentToolSpec,
3655
4278
  plan,
4279
+ planCompactionCut,
3656
4280
  planNextAgentWorkflowOperation,
3657
4281
  prepareModelStep,
3658
4282
  processStepStream,
3659
4283
  promptCacheMiddleware,
4284
+ pruneContext,
4285
+ pruneToolContext,
4286
+ pruneToolContextWithReport,
3660
4287
  queueWorkflowFollowUps,
3661
4288
  quick,
3662
4289
  recordAgentWorkflowReplayDecision,
4290
+ redactSummaryText,
4291
+ renderAgentContextFragment,
3663
4292
  requiresToolHost,
3664
4293
  resetFrameworkAliases,
3665
4294
  resetPluginLoader,
3666
4295
  resolveAgentDefaults,
4296
+ resolveAgentMemoryConfig,
4297
+ resolveAgentMemoryTurnConfig,
3667
4298
  resolveCapability,
4299
+ resolveContextSummaryPolicy,
3668
4300
  resolveFrameworkAliases,
3669
4301
  resolveQueuedFollowUp,
4302
+ resolveSummaryOutputTokens,
3670
4303
  restoreAgentWorkflowMessage,
3671
4304
  restoreAgentWorkflowMessages,
3672
4305
  restoreScope,
@@ -3677,10 +4310,13 @@ export {
3677
4310
  sandboxDefaultsProvider,
3678
4311
  selectRememberScope,
3679
4312
  serializeMessage,
4313
+ serializeMessagesForSummary,
3680
4314
  serviceAccountServer,
3681
4315
  shouldCaptureBaseline,
3682
4316
  shouldCascadeApprovalDecision,
4317
+ shouldFallbackOnSummaryFailure,
3683
4318
  shouldIncludeReasoningSummary,
4319
+ shouldPruneContext,
3684
4320
  shouldRetry,
3685
4321
  silentLogger,
3686
4322
  sleep,