@theokit/sdk 5.14.0 → 5.15.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (214) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/dist/{agent-T34LCGQM.js → agent-66U5QCPF.js} +18 -17
  3. package/dist/{agent-T34LCGQM.js.map → agent-66U5QCPF.js.map} +1 -1
  4. package/dist/{agent-DExqjqYy.d.cts → agent-BL4kxgwq.d.cts} +30 -214
  5. package/dist/{agent-Dfw3VsIX.d.ts → agent-ByDx7K30.d.ts} +30 -214
  6. package/dist/{agent-TL4K7BTG.cjs → agent-CB27KF6O.cjs} +19 -18
  7. package/dist/{agent-TL4K7BTG.cjs.map → agent-CB27KF6O.cjs.map} +1 -1
  8. package/dist/agent.d.ts +2 -3
  9. package/dist/{batch-EP3FCL6D.js → batch-N2XDYZED.js} +4 -4
  10. package/dist/{batch-EP3FCL6D.js.map → batch-N2XDYZED.js.map} +1 -1
  11. package/dist/{batch-IZ5EDKJ5.cjs → batch-VFR2MAUE.cjs} +7 -7
  12. package/dist/{batch-IZ5EDKJ5.cjs.map → batch-VFR2MAUE.cjs.map} +1 -1
  13. package/dist/{chunk-ZOL3L4EH.js → chunk-26GI3OYA.js} +118 -21
  14. package/dist/chunk-26GI3OYA.js.map +1 -0
  15. package/dist/{chunk-2WY2OFSC.cjs → chunk-26UQG242.cjs} +616 -318
  16. package/dist/chunk-26UQG242.cjs.map +1 -0
  17. package/dist/{chunk-2C24NSNV.js → chunk-3BBTHFGJ.js} +3 -3
  18. package/dist/{chunk-2C24NSNV.js.map → chunk-3BBTHFGJ.js.map} +1 -1
  19. package/dist/{chunk-SNVYOX46.cjs → chunk-3E3VSMB6.cjs} +160 -63
  20. package/dist/chunk-3E3VSMB6.cjs.map +1 -0
  21. package/dist/{chunk-NP362THY.cjs → chunk-3F53FLQ7.cjs} +5 -7
  22. package/dist/chunk-3F53FLQ7.cjs.map +1 -0
  23. package/dist/{chunk-SXH37C7X.cjs → chunk-55LLQFHW.cjs} +6 -6
  24. package/dist/{chunk-SXH37C7X.cjs.map → chunk-55LLQFHW.cjs.map} +1 -1
  25. package/dist/{chunk-ZJAYFSVI.js → chunk-7ACS6P5Z.js} +5 -7
  26. package/dist/chunk-7ACS6P5Z.js.map +1 -0
  27. package/dist/{chunk-WDVG5R2Q.cjs → chunk-AUH2EVWY.cjs} +4 -3
  28. package/dist/chunk-AUH2EVWY.cjs.map +1 -0
  29. package/dist/chunk-BNEUB52I.cjs +55 -0
  30. package/dist/chunk-BNEUB52I.cjs.map +1 -0
  31. package/dist/chunk-BPL5CVZ5.js +53 -0
  32. package/dist/chunk-BPL5CVZ5.js.map +1 -0
  33. package/dist/{chunk-NVQSBRG6.js → chunk-CBBT42VX.js} +3 -3
  34. package/dist/{chunk-NVQSBRG6.js.map → chunk-CBBT42VX.js.map} +1 -1
  35. package/dist/chunk-CHKV2L2Y.cjs +416 -0
  36. package/dist/chunk-CHKV2L2Y.cjs.map +1 -0
  37. package/dist/{chunk-LXG6VL6R.cjs → chunk-FBIDOOJM.cjs} +3 -3
  38. package/dist/{chunk-LXG6VL6R.cjs.map → chunk-FBIDOOJM.cjs.map} +1 -1
  39. package/dist/{chunk-354F3OF5.js → chunk-FGGVSHDW.js} +3 -3
  40. package/dist/{chunk-354F3OF5.js.map → chunk-FGGVSHDW.js.map} +1 -1
  41. package/dist/{chunk-6OCJWGVD.cjs → chunk-FTXY4D44.cjs} +4 -4
  42. package/dist/{chunk-6OCJWGVD.cjs.map → chunk-FTXY4D44.cjs.map} +1 -1
  43. package/dist/chunk-INVEGVGO.js +405 -0
  44. package/dist/chunk-INVEGVGO.js.map +1 -0
  45. package/dist/{chunk-DF77RBF4.js → chunk-LCCT5ZXJ.js} +6 -6
  46. package/dist/{chunk-DF77RBF4.js.map → chunk-LCCT5ZXJ.js.map} +1 -1
  47. package/dist/{chunk-G7XBVM3T.cjs → chunk-MHUOVS5I.cjs} +5 -5
  48. package/dist/{chunk-G7XBVM3T.cjs.map → chunk-MHUOVS5I.cjs.map} +1 -1
  49. package/dist/{chunk-CWQPQTUZ.cjs → chunk-NEH3BPFD.cjs} +15 -15
  50. package/dist/{chunk-CWQPQTUZ.cjs.map → chunk-NEH3BPFD.cjs.map} +1 -1
  51. package/dist/{chunk-5AR6O7GW.js → chunk-NK5EOTDY.js} +3 -3
  52. package/dist/{chunk-5AR6O7GW.js.map → chunk-NK5EOTDY.js.map} +1 -1
  53. package/dist/{chunk-NAVUTK6X.js → chunk-O2RCS3SJ.js} +3 -3
  54. package/dist/{chunk-NAVUTK6X.js.map → chunk-O2RCS3SJ.js.map} +1 -1
  55. package/dist/{chunk-4TEGFMSP.cjs → chunk-P7QYG4RZ.cjs} +23 -15
  56. package/dist/chunk-P7QYG4RZ.cjs.map +1 -0
  57. package/dist/chunk-PPU2D4FZ.js +19 -0
  58. package/dist/chunk-PPU2D4FZ.js.map +1 -0
  59. package/dist/{chunk-AB4OPJLD.js → chunk-RGVMJU57.js} +3 -3
  60. package/dist/{chunk-AB4OPJLD.js.map → chunk-RGVMJU57.js.map} +1 -1
  61. package/dist/{chunk-4KBI37F3.cjs → chunk-RTDVSHJR.cjs} +5 -5
  62. package/dist/{chunk-4KBI37F3.cjs.map → chunk-RTDVSHJR.cjs.map} +1 -1
  63. package/dist/{chunk-CJN5CEI3.js → chunk-RZL2W4C3.js} +23 -15
  64. package/dist/chunk-RZL2W4C3.js.map +1 -0
  65. package/dist/chunk-SPEN7RJU.cjs +18 -0
  66. package/dist/{chunk-R5UQL2R5.cjs.map → chunk-SPEN7RJU.cjs.map} +1 -1
  67. package/dist/{chunk-BZK5QL3N.cjs → chunk-TRPRTZEH.cjs} +4 -4
  68. package/dist/{chunk-BZK5QL3N.cjs.map → chunk-TRPRTZEH.cjs.map} +1 -1
  69. package/dist/{chunk-ZF2LDKQQ.cjs → chunk-U3DW3WDE.cjs} +9 -8
  70. package/dist/chunk-U3DW3WDE.cjs.map +1 -0
  71. package/dist/{chunk-H7G65PNI.js → chunk-VCQ37TC5.js} +3 -3
  72. package/dist/{chunk-H7G65PNI.js.map → chunk-VCQ37TC5.js.map} +1 -1
  73. package/dist/{chunk-3ONIVO2I.js → chunk-VNRNZ3WI.js} +3 -3
  74. package/dist/{chunk-3ONIVO2I.js.map → chunk-VNRNZ3WI.js.map} +1 -1
  75. package/dist/{chunk-SDZ4XDWS.cjs → chunk-VWYFGE27.cjs} +9 -9
  76. package/dist/{chunk-SDZ4XDWS.cjs.map → chunk-VWYFGE27.cjs.map} +1 -1
  77. package/dist/{chunk-RN3XDZGS.js → chunk-WM646HEN.js} +4 -3
  78. package/dist/chunk-WM646HEN.js.map +1 -0
  79. package/dist/chunk-X7CE7Y5W.js +305 -0
  80. package/dist/chunk-X7CE7Y5W.js.map +1 -0
  81. package/dist/{chunk-CGH4BCIY.cjs → chunk-XE3CAY6Z.cjs} +5 -5
  82. package/dist/{chunk-CGH4BCIY.cjs.map → chunk-XE3CAY6Z.cjs.map} +1 -1
  83. package/dist/chunk-XOU3CL7S.cjs +312 -0
  84. package/dist/chunk-XOU3CL7S.cjs.map +1 -0
  85. package/dist/{chunk-ULEK4OM4.js → chunk-YKNBTHMD.js} +3 -3
  86. package/dist/{chunk-ULEK4OM4.js.map → chunk-YKNBTHMD.js.map} +1 -1
  87. package/dist/{chunk-GARVAUCU.js → chunk-ZQWRUJHE.js} +534 -236
  88. package/dist/chunk-ZQWRUJHE.js.map +1 -0
  89. package/dist/{compact-session-D2MQDB6G.cjs → compact-session-CHBJOYWP.cjs} +16 -16
  90. package/dist/{compact-session-D2MQDB6G.cjs.map → compact-session-CHBJOYWP.cjs.map} +1 -1
  91. package/dist/{compact-session-N2PPHQO6.js → compact-session-F3J3FMEU.js} +7 -7
  92. package/dist/{compact-session-N2PPHQO6.js.map → compact-session-F3J3FMEU.js.map} +1 -1
  93. package/dist/{cron-CK2v0VWA.d.cts → cron-B7KH9sHW.d.cts} +2 -2
  94. package/dist/{cron-BubDpFJG.d.ts → cron-FEO7UAQF.d.ts} +2 -2
  95. package/dist/cron.cjs +18 -17
  96. package/dist/cron.d.cts +4 -3
  97. package/dist/cron.d.ts +4 -3
  98. package/dist/cron.js +17 -16
  99. package/dist/eval.cjs +17 -16
  100. package/dist/eval.cjs.map +1 -1
  101. package/dist/eval.js +16 -15
  102. package/dist/eval.js.map +1 -1
  103. package/dist/fs-session-store-CYNTEPJZ.cjs +20 -0
  104. package/dist/{fs-session-store-S2AXVJIX.cjs.map → fs-session-store-CYNTEPJZ.cjs.map} +1 -1
  105. package/dist/fs-session-store-MYQEVUFL.js +11 -0
  106. package/dist/{fs-session-store-6ZCCJX3K.js.map → fs-session-store-MYQEVUFL.js.map} +1 -1
  107. package/dist/{index-manager-HO456AVW.cjs → index-manager-2KH75BRW.cjs} +7 -7
  108. package/dist/{index-manager-HO456AVW.cjs.map → index-manager-2KH75BRW.cjs.map} +1 -1
  109. package/dist/{index-manager-QDH56FER.js → index-manager-NF2WRLOU.js} +6 -6
  110. package/dist/{index-manager-QDH56FER.js.map → index-manager-NF2WRLOU.js.map} +1 -1
  111. package/dist/index.cjs +66 -262
  112. package/dist/index.cjs.map +1 -1
  113. package/dist/index.d.cts +10 -46
  114. package/dist/index.d.ts +10 -46
  115. package/dist/index.js +27 -227
  116. package/dist/index.js.map +1 -1
  117. package/dist/{inject-session-J26SHHIO.js → inject-session-LC2TROHM.js} +3 -3
  118. package/dist/{inject-session-J26SHHIO.js.map → inject-session-LC2TROHM.js.map} +1 -1
  119. package/dist/{inject-session-3ICZIJ2N.cjs → inject-session-T4RXANG3.cjs} +4 -4
  120. package/dist/{inject-session-3ICZIJ2N.cjs.map → inject-session-T4RXANG3.cjs.map} +1 -1
  121. package/dist/internal/agent-loop/doom-loop-tracker.d.ts +3 -0
  122. package/dist/internal/agent-loop/types.d.ts +6 -0
  123. package/dist/internal/error-mappers/anthropic.d.ts +3 -0
  124. package/dist/internal/error-mappers/openai-compatible.d.ts +2 -3
  125. package/dist/internal/llm/hermes-tool-extract.d.ts +2 -0
  126. package/dist/internal/local-agent/local-agent-dispatch.d.ts +3 -1
  127. package/dist/internal/local-agent/send-queue.d.ts +31 -0
  128. package/dist/internal/mcp/client.d.ts +2 -0
  129. package/dist/internal/mcp/oauth-bearer.d.ts +2 -0
  130. package/dist/internal/memory/adapters/index.cjs +3 -3
  131. package/dist/internal/memory/adapters/index.js +2 -2
  132. package/dist/internal/memory/dreaming/phases.d.ts +15 -0
  133. package/dist/internal/memory/dreaming/run.d.ts +29 -0
  134. package/dist/internal/memory/sdk-memory-peer-loader.d.ts +2 -0
  135. package/dist/internal/memory/storage/index.cjs +51 -35
  136. package/dist/internal/memory/storage/index.d.cts +2 -0
  137. package/dist/internal/memory/storage/index.d.ts +2 -0
  138. package/dist/internal/memory/storage/index.js +4 -4
  139. package/dist/internal/persistence/cwd-mutex.d.cts +4 -2
  140. package/dist/internal/persistence/cwd-mutex.d.ts +4 -2
  141. package/dist/internal/persistence/index.cjs +4 -4
  142. package/dist/internal/persistence/index.js +2 -2
  143. package/dist/internal/persistence/sqlite-session-store.d.cts +25 -0
  144. package/dist/internal/persistence/sqlite-session-store.d.ts +25 -0
  145. package/dist/internal/providers/registry.d.ts +5 -1
  146. package/dist/mcp-auth.cjs +25 -307
  147. package/dist/mcp-auth.cjs.map +1 -1
  148. package/dist/mcp-auth.js +5 -305
  149. package/dist/mcp-auth.js.map +1 -1
  150. package/dist/models.cjs +9 -9
  151. package/dist/models.js +2 -2
  152. package/dist/persistence.cjs +9 -4
  153. package/dist/persistence.cjs.map +1 -1
  154. package/dist/persistence.d.cts +744 -40
  155. package/dist/persistence.d.ts +744 -40
  156. package/dist/persistence.js +3 -2
  157. package/dist/persistence.js.map +1 -1
  158. package/dist/providers.cjs +4 -4
  159. package/dist/providers.js +2 -2
  160. package/dist/sandbox/docker-sandbox.d.cts +58 -0
  161. package/dist/sandbox/docker-sandbox.d.ts +58 -0
  162. package/dist/sandbox/index.cjs +129 -1
  163. package/dist/sandbox/index.cjs.map +1 -1
  164. package/dist/sandbox/index.d.cts +1 -0
  165. package/dist/sandbox/index.d.ts +1 -0
  166. package/dist/sandbox/index.js +132 -5
  167. package/dist/sandbox/index.js.map +1 -1
  168. package/dist/{sdk-agent-DwzHcuxy.d.cts → sdk-agent-BA_6_wtc.d.cts} +30 -2
  169. package/dist/{sdk-agent-a3fW1xUK.d.ts → sdk-agent-CnwPODYH.d.ts} +30 -2
  170. package/dist/session-store-Dh07jr9N.d.cts +209 -0
  171. package/dist/session-store-Dh07jr9N.d.ts +209 -0
  172. package/dist/sqlite-session-store-BbcpKY1L.d.ts +64 -0
  173. package/dist/sqlite-session-store-TKXtT4ON.d.cts +64 -0
  174. package/dist/subagents-loader-KLWF4QPD.cjs +16 -0
  175. package/dist/{subagents-loader-TXOA5EJJ.cjs.map → subagents-loader-KLWF4QPD.cjs.map} +1 -1
  176. package/dist/subagents-loader-SXETS2F2.js +7 -0
  177. package/dist/{subagents-loader-Z744TAKD.js.map → subagents-loader-SXETS2F2.js.map} +1 -1
  178. package/dist/subagents-loader.cjs +2 -2
  179. package/dist/subagents-loader.d.cts +3 -2
  180. package/dist/subagents-loader.d.ts +3 -2
  181. package/dist/subagents-loader.js +1 -1
  182. package/dist/types/agent.d.ts +14 -1
  183. package/dist/types/budget-tracker.d.ts +6 -2
  184. package/dist/types/hooks.d.ts +7 -1
  185. package/dist/types/mcp.d.ts +14 -0
  186. package/dist/types/run.d.ts +15 -1
  187. package/dist/workflow.d.cts +1 -1
  188. package/dist/workflow.d.ts +1 -1
  189. package/docs/adr/mutation-testing-scope.md +12 -2
  190. package/docs/error-codes.md +41 -40
  191. package/docs/harness-capability-map.md +32 -6
  192. package/package.json +1 -1
  193. package/dist/chunk-2WY2OFSC.cjs.map +0 -1
  194. package/dist/chunk-4TEGFMSP.cjs.map +0 -1
  195. package/dist/chunk-6CXRYPG7.cjs +0 -211
  196. package/dist/chunk-6CXRYPG7.cjs.map +0 -1
  197. package/dist/chunk-CJN5CEI3.js.map +0 -1
  198. package/dist/chunk-GARVAUCU.js.map +0 -1
  199. package/dist/chunk-MSEL5E5P.js +0 -204
  200. package/dist/chunk-MSEL5E5P.js.map +0 -1
  201. package/dist/chunk-NP362THY.cjs.map +0 -1
  202. package/dist/chunk-Q5EWJPRY.js +0 -18
  203. package/dist/chunk-Q5EWJPRY.js.map +0 -1
  204. package/dist/chunk-R5UQL2R5.cjs +0 -18
  205. package/dist/chunk-RN3XDZGS.js.map +0 -1
  206. package/dist/chunk-SNVYOX46.cjs.map +0 -1
  207. package/dist/chunk-WDVG5R2Q.cjs.map +0 -1
  208. package/dist/chunk-ZF2LDKQQ.cjs.map +0 -1
  209. package/dist/chunk-ZJAYFSVI.js.map +0 -1
  210. package/dist/chunk-ZOL3L4EH.js.map +0 -1
  211. package/dist/fs-session-store-6ZCCJX3K.js +0 -11
  212. package/dist/fs-session-store-S2AXVJIX.cjs +0 -20
  213. package/dist/subagents-loader-TXOA5EJJ.cjs +0 -16
  214. package/dist/subagents-loader-Z744TAKD.js +0 -7
@@ -1,18 +1,19 @@
1
1
  'use strict';
2
2
 
3
3
  var chunkL7JPXZ2C_cjs = require('./chunk-L7JPXZ2C.cjs');
4
- var chunkLXG6VL6R_cjs = require('./chunk-LXG6VL6R.cjs');
5
- var chunkCWQPQTUZ_cjs = require('./chunk-CWQPQTUZ.cjs');
4
+ var chunkFBIDOOJM_cjs = require('./chunk-FBIDOOJM.cjs');
5
+ var chunkNEH3BPFD_cjs = require('./chunk-NEH3BPFD.cjs');
6
6
  var chunk7YUPSBDV_cjs = require('./chunk-7YUPSBDV.cjs');
7
7
  var chunkBV2MWEMV_cjs = require('./chunk-BV2MWEMV.cjs');
8
- var chunkCGH4BCIY_cjs = require('./chunk-CGH4BCIY.cjs');
8
+ var chunkXE3CAY6Z_cjs = require('./chunk-XE3CAY6Z.cjs');
9
9
  var chunkRS7YQR4X_cjs = require('./chunk-RS7YQR4X.cjs');
10
- var chunkSDZ4XDWS_cjs = require('./chunk-SDZ4XDWS.cjs');
11
- var chunk6OCJWGVD_cjs = require('./chunk-6OCJWGVD.cjs');
12
- var chunkSNVYOX46_cjs = require('./chunk-SNVYOX46.cjs');
10
+ var chunkVWYFGE27_cjs = require('./chunk-VWYFGE27.cjs');
11
+ var chunkFTXY4D44_cjs = require('./chunk-FTXY4D44.cjs');
12
+ var chunk3E3VSMB6_cjs = require('./chunk-3E3VSMB6.cjs');
13
13
  var chunk2ZPEDVLM_cjs = require('./chunk-2ZPEDVLM.cjs');
14
14
  var chunkQG4SXZ2A_cjs = require('./chunk-QG4SXZ2A.cjs');
15
15
  var chunkUDAKAE4Z_cjs = require('./chunk-UDAKAE4Z.cjs');
16
+ var chunkXOU3CL7S_cjs = require('./chunk-XOU3CL7S.cjs');
16
17
  var chunk3HA7N2BB_cjs = require('./chunk-3HA7N2BB.cjs');
17
18
  var chunkAA27GEYS_cjs = require('./chunk-AA27GEYS.cjs');
18
19
  var chunkYSTXFWQE_cjs = require('./chunk-YSTXFWQE.cjs');
@@ -24,17 +25,17 @@ var chunk3KIUY67P_cjs = require('./chunk-3KIUY67P.cjs');
24
25
  var chunkSA6K24NB_cjs = require('./chunk-SA6K24NB.cjs');
25
26
  var chunk27V5I2WW_cjs = require('./chunk-27V5I2WW.cjs');
26
27
  var chunk3WKWBYPO_cjs = require('./chunk-3WKWBYPO.cjs');
27
- var chunkG7XBVM3T_cjs = require('./chunk-G7XBVM3T.cjs');
28
- var chunkZF2LDKQQ_cjs = require('./chunk-ZF2LDKQQ.cjs');
28
+ var chunkMHUOVS5I_cjs = require('./chunk-MHUOVS5I.cjs');
29
+ var chunkU3DW3WDE_cjs = require('./chunk-U3DW3WDE.cjs');
29
30
  var chunkZOFRNNZD_cjs = require('./chunk-ZOFRNNZD.cjs');
30
- var chunkWDVG5R2Q_cjs = require('./chunk-WDVG5R2Q.cjs');
31
+ var chunkAUH2EVWY_cjs = require('./chunk-AUH2EVWY.cjs');
31
32
  var chunkYQ3XC6C2_cjs = require('./chunk-YQ3XC6C2.cjs');
32
33
  var chunk6XQLTQB6_cjs = require('./chunk-6XQLTQB6.cjs');
33
34
  var chunkKX5QXLBS_cjs = require('./chunk-KX5QXLBS.cjs');
34
- var chunk4KBI37F3_cjs = require('./chunk-4KBI37F3.cjs');
35
+ var chunkRTDVSHJR_cjs = require('./chunk-RTDVSHJR.cjs');
35
36
  var chunk3EE6LVWT_cjs = require('./chunk-3EE6LVWT.cjs');
36
- var chunkR5UQL2R5_cjs = require('./chunk-R5UQL2R5.cjs');
37
- var chunk4TEGFMSP_cjs = require('./chunk-4TEGFMSP.cjs');
37
+ var chunkSPEN7RJU_cjs = require('./chunk-SPEN7RJU.cjs');
38
+ var chunkP7QYG4RZ_cjs = require('./chunk-P7QYG4RZ.cjs');
38
39
  var chunkNVXXWAU7_cjs = require('./chunk-NVXXWAU7.cjs');
39
40
  var chunkEHD25JBZ_cjs = require('./chunk-EHD25JBZ.cjs');
40
41
  var chunkCEGU5AVD_cjs = require('./chunk-CEGU5AVD.cjs');
@@ -458,7 +459,7 @@ async function saveRegistry(cwd, agents2) {
458
459
  serialized[id] = toSerialized(agent);
459
460
  }
460
461
  const path = registryPath(cwd);
461
- await chunkZF2LDKQQ_cjs.withCwdMutex(`registry:${cwd}`, async () => {
462
+ await chunkU3DW3WDE_cjs.withCwdMutex(`registry:${cwd}`, async () => {
462
463
  await chunk3HA7N2BB_cjs.writeVersionedJson(path, serialized, SCHEMA_VERSION);
463
464
  });
464
465
  }
@@ -866,7 +867,7 @@ async function readLegacyFacts(jsonPath) {
866
867
  }
867
868
  async function writeMigratedFacts(cwd, jsonPath, facts) {
868
869
  try {
869
- for (const fact of facts) await chunkSDZ4XDWS_cjs.appendFactToMarkdown(cwd, fact);
870
+ for (const fact of facts) await chunkVWYFGE27_cjs.appendFactToMarkdown(cwd, fact);
870
871
  await promises.unlink(jsonPath).catch(() => void 0);
871
872
  chunkRNXXYF22_cjs.diag(`[theokit-sdk] migrated ${facts.length} fact(s) from ${jsonPath} to MEMORY.md
872
873
  `);
@@ -883,11 +884,11 @@ async function migrateLegacyJson(cwd, config) {
883
884
  const key = `${cwd}::${config.namespace ?? "default"}::${config.scope ?? "agent"}::${config.userId ?? "default"}`;
884
885
  if (migrationRun.has(key)) return { migrated: false, factCount: 0, reason: "already-migrated" };
885
886
  migrationRun.add(key);
886
- const jsonPath = chunkSDZ4XDWS_cjs.legacyMemoryJsonPath(cwd, config);
887
+ const jsonPath = chunkVWYFGE27_cjs.legacyMemoryJsonPath(cwd, config);
887
888
  if (!await fileExists(jsonPath)) {
888
889
  return { migrated: false, factCount: 0, reason: "no-legacy-json" };
889
890
  }
890
- if (await fileExists(chunkSDZ4XDWS_cjs.memoryMdPath(chunkSDZ4XDWS_cjs.resolveMemoryRoot(cwd, config)))) {
891
+ if (await fileExists(chunkVWYFGE27_cjs.memoryMdPath(chunkVWYFGE27_cjs.resolveMemoryRoot(cwd, config)))) {
891
892
  chunkRNXXYF22_cjs.diag(
892
893
  `[theokit-sdk] memory migration skipped: both MEMORY.md and legacy JSON exist at ${jsonPath}; leaving both intact
893
894
  `
@@ -916,29 +917,29 @@ function unstoredRememberWarning(message) {
916
917
  if (isMemoryWritePrompt(message) && extractMemoryFact(message).length > 0) return void 0;
917
918
  const trimmed = message.trim();
918
919
  const quoted = trimmed.length > QUOTED_MESSAGE_MAX ? `${trimmed.slice(0, QUOTED_MESSAGE_MAX)}\u2026` : trimmed;
919
- return `[theokit-sdk] NOTHING WAS STORED \u2014 this message does not match the memory capture pattern: ${JSON.stringify(quoted)}. Supported: "Remember: <fact>" or "Remember (${chunkSDZ4XDWS_cjs.MEMORY_KINDS.join("|")}): <fact>". It still reaches the session transcript, so a follow-up may answer from it \u2014 that is search over transcripts, not a durable memory.`;
920
+ return `[theokit-sdk] NOTHING WAS STORED \u2014 this message does not match the memory capture pattern: ${JSON.stringify(quoted)}. Supported: "Remember: <fact>" or "Remember (${chunkVWYFGE27_cjs.MEMORY_KINDS.join("|")}): <fact>". It still reaches the session transcript, so a follow-up may answer from it \u2014 that is search over transcripts, not a durable memory.`;
920
921
  }
921
922
  function extractMemoryKind(message) {
922
923
  const match = REMEMBER_PATTERN.exec(message);
923
924
  const declared = match?.[1];
924
925
  if (declared === void 0) return void 0;
925
926
  const lowered = declared.toLowerCase();
926
- return chunkSDZ4XDWS_cjs.MEMORY_KINDS.includes(lowered) ? lowered : void 0;
927
+ return chunkVWYFGE27_cjs.MEMORY_KINDS.includes(lowered) ? lowered : void 0;
927
928
  }
928
929
  async function readMemoryFacts(cwd, config) {
929
930
  if (!config.enabled) return [];
930
931
  await migrateLegacyJson(cwd, config);
931
- return chunkSDZ4XDWS_cjs.readFacts(cwd, config);
932
+ return chunkVWYFGE27_cjs.readFacts(cwd, config);
932
933
  }
933
934
  async function appendMemoryFact(cwd, config, fact) {
934
935
  if (!config.enabled) return;
935
- chunkSDZ4XDWS_cjs.resolveMaxFacts(config.maxFacts);
936
+ chunkVWYFGE27_cjs.resolveMaxFacts(config.maxFacts);
936
937
  await migrateLegacyJson(cwd, config);
937
938
  const sanitized = {
938
939
  text: chunkRNXXYF22_cjs.redactSecrets(fact.text),
939
940
  ...fact.kind === void 0 ? {} : { kind: fact.kind }
940
941
  };
941
- await chunkSDZ4XDWS_cjs.appendFact(cwd, config, sanitized);
942
+ await chunkVWYFGE27_cjs.appendFact(cwd, config, sanitized);
942
943
  }
943
944
 
944
945
  // src/internal/runtime/fixtures/fixture-scripts.ts
@@ -1624,7 +1625,7 @@ function createRealCloudRun(options) {
1624
1625
  conversation: []
1625
1626
  };
1626
1627
  const apiKey = chunkRNXXYF22_cjs.resolveApiKey(options.agentOptions.apiKey);
1627
- const baseUrl = chunkSNVYOX46_cjs.getConfiguredBaseUrl();
1628
+ const baseUrl = chunk3E3VSMB6_cjs.getConfiguredBaseUrl();
1628
1629
  const handle = new RealCloudRun(
1629
1630
  {
1630
1631
  id,
@@ -1676,7 +1677,10 @@ var RealCloudRun = class extends FixtureRunBase {
1676
1677
  await this.consumeStream(response);
1677
1678
  } catch (cause) {
1678
1679
  if (this.terminated) return;
1679
- this.fail(cause instanceof Error ? cause.message : String(cause));
1680
+ this.fail(
1681
+ cause instanceof Error ? cause.message : String(cause),
1682
+ cause instanceof chunkCEGU5AVD_cjs.TheokitAgentError ? cause : void 0
1683
+ );
1680
1684
  }
1681
1685
  }
1682
1686
  async postRun(apiKey, baseUrl) {
@@ -1707,7 +1711,7 @@ var RealCloudRun = class extends FixtureRunBase {
1707
1711
  async consumeStream(response) {
1708
1712
  let finalStatus = "finished";
1709
1713
  let finalText = "";
1710
- for await (const record of chunkSNVYOX46_cjs.parseSseStream(response.body, this.controller.signal)) {
1714
+ for await (const record of chunk3E3VSMB6_cjs.parseSseStream(response.body, this.controller.signal)) {
1711
1715
  const parsed = safeParse(record.data);
1712
1716
  if (parsed === void 0) continue;
1713
1717
  const update = this.applyRecord(record.event, parsed);
@@ -1754,13 +1758,17 @@ var RealCloudRun = class extends FixtureRunBase {
1754
1758
  message: { role: "assistant", content: [{ type: "text", text }] }
1755
1759
  };
1756
1760
  }
1757
- fail(message, code) {
1761
+ fail(message, cause) {
1758
1762
  const event = this.buildAssistantEvent(message);
1759
1763
  this.script.events.push(event);
1760
1764
  this.notifyNewEvents();
1761
1765
  this.script.result = message;
1762
1766
  if (this.script.errorDetail === void 0) {
1763
- this.script.errorDetail = { message, ...code !== void 0 ? { code } : {} };
1767
+ this.script.errorDetail = {
1768
+ message,
1769
+ ...cause?.code !== void 0 ? { code: cause.code } : {},
1770
+ ...cause !== void 0 ? { cause } : {}
1771
+ };
1764
1772
  }
1765
1773
  this.transitionTo("error");
1766
1774
  }
@@ -1874,7 +1882,7 @@ var CloudAgent = class _CloudAgent {
1874
1882
  */
1875
1883
  isFixtureMode() {
1876
1884
  const apiKey = chunkRNXXYF22_cjs.resolveApiKey(this.options.apiKey);
1877
- return chunkSNVYOX46_cjs.isFixtureApiKey(apiKey) && chunkSNVYOX46_cjs.getConfiguredBaseUrl() === void 0;
1885
+ return chunk3E3VSMB6_cjs.isFixtureApiKey(apiKey) && chunk3E3VSMB6_cjs.getConfiguredBaseUrl() === void 0;
1878
1886
  }
1879
1887
  // SE9 — integrated structured output; delegates to the shared helper.
1880
1888
  generate(message, options) {
@@ -1900,7 +1908,7 @@ var CloudAgent = class _CloudAgent {
1900
1908
  throw new UnsupportedTaskOperationError("send", { cause: void 0 });
1901
1909
  }
1902
1910
  return new Promise((resolve, reject) => {
1903
- void chunkZF2LDKQQ_cjs.withCwdMutex(`agent-send:${this.agentId}`, async () => {
1911
+ void chunkU3DW3WDE_cjs.withCwdMutex(`agent-send:${this.agentId}`, async () => {
1904
1912
  let run;
1905
1913
  try {
1906
1914
  run = await this.sendLocked(message, options);
@@ -1929,7 +1937,7 @@ var CloudAgent = class _CloudAgent {
1929
1937
  const userText = typeof message === "string" ? message : message.text;
1930
1938
  const systemPrompt = await this.resolveSystemPromptForSend(userText, options);
1931
1939
  const apiKey = chunkRNXXYF22_cjs.resolveApiKey(this.options.apiKey);
1932
- const useRealRuntime = apiKey !== void 0 && !chunkSNVYOX46_cjs.isFixtureApiKey(apiKey) && chunkSNVYOX46_cjs.getConfiguredBaseUrl() !== void 0;
1940
+ const useRealRuntime = apiKey !== void 0 && !chunk3E3VSMB6_cjs.isFixtureApiKey(apiKey) && chunk3E3VSMB6_cjs.getConfiguredBaseUrl() !== void 0;
1933
1941
  return useRealRuntime ? createRealCloudRun({
1934
1942
  agentId: this.agentId,
1935
1943
  model: this.model ?? { id: DEFAULT_AGENTIC_MODEL_ID },
@@ -2263,7 +2271,7 @@ var PersonalityStore = class {
2263
2271
  async #persist(agentId, slug) {
2264
2272
  const filePath = this.#filePath();
2265
2273
  await promises.mkdir(path.dirname(filePath), { recursive: true });
2266
- await chunkG7XBVM3T_cjs.withFileLock(filePath, async () => {
2274
+ await chunkMHUOVS5I_cjs.withFileLock(filePath, async () => {
2267
2275
  const current = await readState(filePath);
2268
2276
  const nextAgents = { ...current.agents };
2269
2277
  if (slug === void 0) delete nextAgents[agentId];
@@ -2969,7 +2977,7 @@ function resolveWindowForRun(model, contextWindow) {
2969
2977
  const override = contextWindow !== void 0 && contextWindow > 0 ? contextWindow : void 0;
2970
2978
  return chunkKX5QXLBS_cjs.resolveEffectiveContextWindow({
2971
2979
  ...override !== void 0 ? { override } : {},
2972
- catalog: chunk4TEGFMSP_cjs.getCatalogModelInfo(model)?.limit?.context,
2980
+ catalog: chunkP7QYG4RZ_cjs.getCatalogModelInfo(model)?.limit?.context,
2973
2981
  margin: chunkKX5QXLBS_cjs.CONTEXT_WINDOW_MARGIN,
2974
2982
  floor: chunkKX5QXLBS_cjs.CONTEXT_WINDOW_FLOOR
2975
2983
  });
@@ -2994,7 +3002,7 @@ async function runPostRunLifecycle(inputs) {
2994
3002
  try {
2995
3003
  const partial = await safeConversation(run);
2996
3004
  if (partial !== void 0) {
2997
- chunkLXG6VL6R_cjs.persistTurnToTranscript(sessionStore, { cwd: workspaceCwd, agentId, model }, agentId, {
3005
+ chunkFBIDOOJM_cjs.persistTurnToTranscript(sessionStore, { cwd: workspaceCwd, agentId, model }, agentId, {
2998
3006
  userText,
2999
3007
  conversation: partial
3000
3008
  });
@@ -3004,11 +3012,11 @@ async function runPostRunLifecycle(inputs) {
3004
3012
  chunkRNXXYF22_cjs.diag(`[theokit-sdk] partial transcript write failed (${agentId}): ${msg}
3005
3013
  `);
3006
3014
  }
3007
- await chunkLXG6VL6R_cjs.flushSessionWrites();
3015
+ await chunkFBIDOOJM_cjs.flushSessionWrites();
3008
3016
  return;
3009
3017
  }
3010
3018
  if (result.result !== void 0) {
3011
- chunkLXG6VL6R_cjs.appendSessionMessage(agentId, { role: "assistant", text: result.result });
3019
+ chunkFBIDOOJM_cjs.appendSessionMessage(agentId, { role: "assistant", text: result.result });
3012
3020
  }
3013
3021
  const conversation = await safeConversation(run);
3014
3022
  const resolvedWindow = resolveWindowForRun(model, contextWindow);
@@ -3019,7 +3027,7 @@ async function runPostRunLifecycle(inputs) {
3019
3027
  }
3020
3028
  const lastRequestUsage = result.usage?.requests?.at(-1)?.totalTokens;
3021
3029
  const usageForTrigger = lastRequestUsage ?? result.usage?.totalTokens;
3022
- chunkLXG6VL6R_cjs.persistTurnToTranscript(
3030
+ chunkFBIDOOJM_cjs.persistTurnToTranscript(
3023
3031
  sessionStore,
3024
3032
  { cwd: workspaceCwd, agentId, model },
3025
3033
  agentId,
@@ -3031,7 +3039,7 @@ async function runPostRunLifecycle(inputs) {
3031
3039
  // The EFFECTIVE window (after override, clamp and margin) — not the declared one. Swapping for
3032
3040
  // `contextWindow` here would budget against a number the clamp already rejected.
3033
3041
  contextWindow: effectiveWindow,
3034
- summarize: chunkSNVYOX46_cjs.buildDefaultSummarizer({
3042
+ summarize: chunk3E3VSMB6_cjs.buildDefaultSummarizer({
3035
3043
  agentModel: model,
3036
3044
  ...inputs.apiKey !== void 0 ? { apiKey: inputs.apiKey } : {}
3037
3045
  })
@@ -3044,7 +3052,7 @@ async function runPostRunLifecycle(inputs) {
3044
3052
  cwd: workspaceCwd,
3045
3053
  // Resolved once, here, and handed to both writers. Recomputing it inside either one is how
3046
3054
  // the summary ended up in a directory the indexer never scanned (#463).
3047
- memoryRoot: chunkSDZ4XDWS_cjs.resolveMemoryRoot(workspaceCwd, inputs.memory),
3055
+ memoryRoot: chunkVWYFGE27_cjs.resolveMemoryRoot(workspaceCwd, inputs.memory),
3048
3056
  runId: result.id,
3049
3057
  agentId,
3050
3058
  userText,
@@ -3056,7 +3064,7 @@ async function runPostRunLifecycle(inputs) {
3056
3064
  if (memoryProvider?.recordSessionSummary !== void 0) {
3057
3065
  await memoryProvider.recordSessionSummary(summaryArgs);
3058
3066
  } else {
3059
- await chunkSDZ4XDWS_cjs.writeSessionSummary(summaryArgs);
3067
+ await chunkVWYFGE27_cjs.writeSessionSummary(summaryArgs);
3060
3068
  }
3061
3069
  } catch (cause) {
3062
3070
  const message = cause instanceof Error ? cause.message : String(cause);
@@ -3073,7 +3081,7 @@ async function runPostRunLifecycle(inputs) {
3073
3081
  agentId,
3074
3082
  runId: result.id
3075
3083
  });
3076
- await chunkLXG6VL6R_cjs.flushSessionWrites();
3084
+ await chunkFBIDOOJM_cjs.flushSessionWrites();
3077
3085
  }
3078
3086
  async function safeConversation(run) {
3079
3087
  try {
@@ -3090,12 +3098,12 @@ var WORKSPACE_TRUST = {
3090
3098
  entries: "absolute folder realpaths"
3091
3099
  };
3092
3100
  function workspaceTrustRecordPath() {
3093
- return path.join(path.dirname(chunkSNVYOX46_cjs.trustFilePath()), "trusted-workspace-plugins.json");
3101
+ return path.join(path.dirname(chunk3E3VSMB6_cjs.trustFilePath()), "trusted-workspace-plugins.json");
3094
3102
  }
3095
3103
  function readTrustedWorkspaceFolders() {
3096
3104
  const path$1 = workspaceTrustRecordPath();
3097
3105
  const trusted = /* @__PURE__ */ new Set();
3098
- for (const entry of chunkSNVYOX46_cjs.readTrustArray(path$1, WORKSPACE_TRUST)) {
3106
+ for (const entry of chunk3E3VSMB6_cjs.readTrustArray(path$1, WORKSPACE_TRUST)) {
3099
3107
  if (path.isAbsolute(entry)) {
3100
3108
  trusted.add(entry);
3101
3109
  continue;
@@ -3166,6 +3174,177 @@ async function importEntry(candidate) {
3166
3174
  function isGeneralPlugin(value) {
3167
3175
  return chunkBV2MWEMV_cjs.isCodePlugin(value) && value.kind === "general" && typeof value.name === "string";
3168
3176
  }
3177
+
3178
+ // src/internal/runtime/registry/live-agent-registry.ts
3179
+ var DEFAULT_MAX_AGENTS = 100;
3180
+ var DEFAULT_IDLE_TIMEOUT_MS = 30 * 60 * 1e3;
3181
+ var DEFAULT_SWEEP_INTERVAL_MS = 6e4;
3182
+ var LiveAgentRegistry = class {
3183
+ #agents = /* @__PURE__ */ new Map();
3184
+ #maxAgents = DEFAULT_MAX_AGENTS;
3185
+ #idleTimeoutMs = DEFAULT_IDLE_TIMEOUT_MS;
3186
+ #sweepIntervalMs = DEFAULT_SWEEP_INTERVAL_MS;
3187
+ #onEvict;
3188
+ #sweepTimer;
3189
+ /**
3190
+ * Reconfigure registry behavior. Process-wide singleton (D310) — last
3191
+ * configure call wins for all subsequent operations.
3192
+ */
3193
+ configure(opts) {
3194
+ if (opts.maxAgents !== void 0) this.#maxAgents = Math.max(0, opts.maxAgents);
3195
+ if (opts.idleTimeoutMs !== void 0) this.#idleTimeoutMs = Math.max(0, opts.idleTimeoutMs);
3196
+ if (opts.sweepIntervalMs !== void 0)
3197
+ this.#sweepIntervalMs = Math.max(1e3, opts.sweepIntervalMs);
3198
+ this.#onEvict = opts.onEvict;
3199
+ this.#stopSweep();
3200
+ if (this.#idleTimeoutMs > 0) this.#startSweep();
3201
+ }
3202
+ /**
3203
+ * Lookup a cached agent. `get` is a use — refreshes `lastUsedAt` so the
3204
+ * entry survives LRU eviction.
3205
+ */
3206
+ get(id) {
3207
+ const entry = this.#agents.get(id);
3208
+ if (entry === void 0) return void 0;
3209
+ entry.lastUsedAt = Date.now();
3210
+ return entry.agent;
3211
+ }
3212
+ /**
3213
+ * Insert or overwrite an agent in the cache. Triggers fire-and-forget LRU
3214
+ * eviction when `size > maxAgents`.
3215
+ *
3216
+ * EC-4: when `id` already maps to a DIFFERENT agent instance, dispose the
3217
+ * old one before overwriting (race protection against two `getOrCreate`
3218
+ * calls creating two agents but only the second being cached — the first
3219
+ * would leak file handles + lifecycle controllers).
3220
+ */
3221
+ set(id, agent) {
3222
+ if (this.#maxAgents === 0) return;
3223
+ const existing = this.#agents.get(id);
3224
+ if (existing !== void 0 && existing.agent !== agent) {
3225
+ void existing.agent.dispose().catch(() => {
3226
+ chunkRNXXYF22_cjs.diag(`[theokit-sdk] dispose during overwrite failed (${id})
3227
+ `);
3228
+ });
3229
+ }
3230
+ this.#agents.set(id, { agent, lastUsedAt: Date.now() });
3231
+ if (this.#agents.size > this.#maxAgents) void this.#evictLRU();
3232
+ }
3233
+ /**
3234
+ * Remove the entry from the cache WITHOUT calling `dispose()` or
3235
+ * `onEvict`. Used by `LocalAgent.dispose()` itself so the disposed
3236
+ * instance can never be returned by a subsequent `get(id)` (dispose-cache
3237
+ * race fix). Idempotent — calling on an unknown id is a no-op.
3238
+ *
3239
+ * @internal
3240
+ */
3241
+ forget(id) {
3242
+ this.#agents.delete(id);
3243
+ }
3244
+ /**
3245
+ * Explicitly evict an agent by id. Returns `true` when the entry was
3246
+ * present (false = already gone). Calls `agent.dispose()` + `onEvict`
3247
+ * with reason `"explicit"`.
3248
+ */
3249
+ async evict(id) {
3250
+ const entry = this.#agents.get(id);
3251
+ if (entry === void 0) return false;
3252
+ this.#agents.delete(id);
3253
+ await this.#disposeAndNotify(id, entry.agent, "explicit");
3254
+ return true;
3255
+ }
3256
+ /**
3257
+ * Evict every cached agent. Used by graceful shutdown (`process.on('SIGTERM')`)
3258
+ * or end-of-test cleanup.
3259
+ */
3260
+ async evictAll() {
3261
+ const entries = Array.from(this.#agents.entries());
3262
+ this.#agents.clear();
3263
+ this.#stopSweep();
3264
+ for (const [id, entry] of entries) {
3265
+ await this.#disposeAndNotify(id, entry.agent, "explicit");
3266
+ }
3267
+ }
3268
+ /** Number of currently cached agents. */
3269
+ size() {
3270
+ return this.#agents.size;
3271
+ }
3272
+ /** Ids of cached agents, newest first (by lastUsedAt). */
3273
+ ids() {
3274
+ return Array.from(this.#agents.entries()).sort((a, b) => b[1].lastUsedAt - a[1].lastUsedAt).map(([id]) => id);
3275
+ }
3276
+ /**
3277
+ * LRU eviction: drop the entry with the smallest `lastUsedAt`. Runs only
3278
+ * when `size > maxAgents`. Asynchronous because `dispose()` is a Promise;
3279
+ * the hot-path caller (`set`) does not await.
3280
+ *
3281
+ * @internal
3282
+ */
3283
+ async #evictLRU() {
3284
+ if (this.#agents.size <= this.#maxAgents) return;
3285
+ let oldestId;
3286
+ let oldestAt = Infinity;
3287
+ for (const [id, entry2] of this.#agents) {
3288
+ if (entry2.lastUsedAt < oldestAt) {
3289
+ oldestAt = entry2.lastUsedAt;
3290
+ oldestId = id;
3291
+ }
3292
+ }
3293
+ if (oldestId === void 0) return;
3294
+ const entry = this.#agents.get(oldestId);
3295
+ if (entry === void 0) return;
3296
+ this.#agents.delete(oldestId);
3297
+ await this.#disposeAndNotify(oldestId, entry.agent, "lru");
3298
+ }
3299
+ /** Background sweep — drops entries whose `lastUsedAt < now - idleTimeoutMs`. */
3300
+ async #sweepIdle() {
3301
+ if (this.#idleTimeoutMs === 0) return;
3302
+ const threshold = Date.now() - this.#idleTimeoutMs;
3303
+ const toEvict = [];
3304
+ for (const [id, entry] of this.#agents) {
3305
+ if (entry.lastUsedAt < threshold) toEvict.push([id, entry]);
3306
+ }
3307
+ for (const [id, entry] of toEvict) {
3308
+ const current = this.#agents.get(id);
3309
+ if (current === void 0 || current.agent !== entry.agent) continue;
3310
+ this.#agents.delete(id);
3311
+ await this.#disposeAndNotify(id, entry.agent, "idle");
3312
+ }
3313
+ }
3314
+ #startSweep() {
3315
+ this.#sweepTimer = setInterval(() => void this.#sweepIdle(), this.#sweepIntervalMs);
3316
+ this.#sweepTimer.unref?.();
3317
+ }
3318
+ #stopSweep() {
3319
+ if (this.#sweepTimer !== void 0) {
3320
+ clearInterval(this.#sweepTimer);
3321
+ this.#sweepTimer = void 0;
3322
+ }
3323
+ }
3324
+ /** Dispose + notify with errors swallowed (D309). Single chokepoint. */
3325
+ async #disposeAndNotify(id, agent, reason) {
3326
+ try {
3327
+ await agent.dispose();
3328
+ } catch (cause) {
3329
+ const msg = cause instanceof Error ? cause.message : String(cause);
3330
+ chunkRNXXYF22_cjs.diag(`[theokit-sdk] dispose during eviction failed (${id}): ${msg}
3331
+ `);
3332
+ }
3333
+ if (this.#onEvict !== void 0) {
3334
+ try {
3335
+ this.#onEvict(id, reason);
3336
+ } catch (cause) {
3337
+ const msg = cause instanceof Error ? cause.message : String(cause);
3338
+ chunkRNXXYF22_cjs.diag(`[theokit-sdk] onEvict listener threw (${id}): ${msg}
3339
+ `);
3340
+ }
3341
+ }
3342
+ }
3343
+ };
3344
+ var liveAgentRegistry = chunkNVXXWAU7_cjs.globalSingleton(
3345
+ "theokit-sdk.runtime.live-agents",
3346
+ () => new LiveAgentRegistry()
3347
+ );
3169
3348
  function executableExtensions() {
3170
3349
  return process.platform === "win32" ? ["", ...(process.env.PATHEXT ?? ".EXE;.CMD").split(";")] : [""];
3171
3350
  }
@@ -3185,8 +3364,9 @@ function binaryOnPath(bin) {
3185
3364
  );
3186
3365
  }
3187
3366
  var SkillsManager = class {
3188
- constructor(cwd, _enabled, settingSourcesIncludeProject, skillsDir, inline, compatSources = [], bundledDirs = []) {
3367
+ constructor(cwd, enabled, settingSourcesIncludeProject, skillsDir, inline, compatSources = [], bundledDirs = []) {
3189
3368
  this.cwd = cwd;
3369
+ this.enabled = enabled;
3190
3370
  this.settingSourcesIncludeProject = settingSourcesIncludeProject;
3191
3371
  this.skillsDir = skillsDir;
3192
3372
  this.inline = inline;
@@ -3194,6 +3374,7 @@ var SkillsManager = class {
3194
3374
  this.bundledDirs = bundledDirs;
3195
3375
  }
3196
3376
  cwd;
3377
+ enabled;
3197
3378
  settingSourcesIncludeProject;
3198
3379
  skillsDir;
3199
3380
  inline;
@@ -3212,7 +3393,7 @@ var SkillsManager = class {
3212
3393
  ...chunkYQ3XC6C2_cjs.projectConfigRoots(this.cwd, this.compatSources, "skills").map(
3213
3394
  (root) => path.join(root, "skills")
3214
3395
  ),
3215
- ...(await chunkWDVG5R2Q_cjs.pluginBundleDirs(this.cwd, this.compatSources)).map((b) => path.join(b, "skills"))
3396
+ ...(await chunkAUH2EVWY_cjs.pluginBundleDirs(this.cwd, this.compatSources)).map((b) => path.join(b, "skills"))
3216
3397
  ] : [this.skillsDir];
3217
3398
  this.skills = this.mergeInline(await this.discoverFrom([...ownRoots, ...this.bundledDirs]));
3218
3399
  }
@@ -3239,8 +3420,12 @@ var SkillsManager = class {
3239
3420
  const inlineNames = new Set(this.inline.map((s) => s.name));
3240
3421
  return [...discovered.filter((s) => !inlineNames.has(s.name)), ...this.inline];
3241
3422
  }
3423
+ visible() {
3424
+ const allowed = this.enabled;
3425
+ return allowed === void 0 ? this.skills : this.skills.filter((s) => allowed.includes(s.name));
3426
+ }
3242
3427
  list() {
3243
- return Promise.resolve(this.skills);
3428
+ return Promise.resolve(this.visible());
3244
3429
  }
3245
3430
  /**
3246
3431
  * SE20 — resolve a skill by name INCLUDING its body. Inline (`createSkill`)
@@ -3249,7 +3434,7 @@ var SkillsManager = class {
3249
3434
  * enabled skill matches (malformed skills were already excluded at discovery).
3250
3435
  */
3251
3436
  async get(name) {
3252
- const skill = this.skills.find((s) => s.name === name);
3437
+ const skill = this.visible().find((s) => s.name === name);
3253
3438
  if (skill === void 0) return void 0;
3254
3439
  const instructions = typeof skill.instructions === "string" ? skill.instructions : chunk3UMPP553_cjs.stripSkillFrontmatter(await promises.readFile(skill.source, "utf8"));
3255
3440
  const references = skill.references;
@@ -3677,6 +3862,23 @@ function validateMcpServers(options) {
3677
3862
  { code: "cloud_stdio_cwd_rejected" }
3678
3863
  );
3679
3864
  }
3865
+ rejectUnhonourableAuth(name, config, options.cloud !== void 0);
3866
+ }
3867
+ }
3868
+ function rejectUnhonourableAuth(name, config, cloud) {
3869
+ const auth = config.auth;
3870
+ if (auth === void 0) return;
3871
+ if (auth.oauth === void 0) {
3872
+ throw new chunkCEGU5AVD_cjs.ConfigurationError(
3873
+ `MCP server "${name}" declares auth without auth.oauth, which the SDK cannot honour; use auth.oauth or set an Authorization header`,
3874
+ { code: "mcp_auth_unsupported" }
3875
+ );
3876
+ }
3877
+ if (cloud) {
3878
+ throw new chunkCEGU5AVD_cjs.ConfigurationError(
3879
+ `MCP server "${name}" declares auth.oauth, which the SDK cannot run for a cloud agent`,
3880
+ { code: "mcp_auth_unsupported" }
3881
+ );
3680
3882
  }
3681
3883
  }
3682
3884
  function isStdioWithCwd(config) {
@@ -3785,7 +3987,7 @@ function validateToolSchema(tool) {
3785
3987
  }
3786
3988
  function validateMemory(options) {
3787
3989
  const memory = options.memory;
3788
- chunkSDZ4XDWS_cjs.resolveMaxFacts(memory?.maxFacts);
3990
+ chunkVWYFGE27_cjs.resolveMaxFacts(memory?.maxFacts);
3789
3991
  if (memory?.storePath === void 0) return;
3790
3992
  const storePath = memory.storePath;
3791
3993
  if (storePath.includes("..") || storePath.startsWith("/") || /^[A-Z]:/i.test(storePath)) {
@@ -3811,7 +4013,7 @@ var HISTOGRAM_NAMES = {
3811
4013
  };
3812
4014
  function safeRequire(moduleName) {
3813
4015
  try {
3814
- const r = module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('chunk-2WY2OFSC.cjs', document.baseURI).href)));
4016
+ const r = module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('chunk-26UQG242.cjs', document.baseURI).href)));
3815
4017
  return r(moduleName);
3816
4018
  } catch {
3817
4019
  return void 0;
@@ -4054,7 +4256,7 @@ var cachedOtel;
4054
4256
  function loadOtel() {
4055
4257
  if (cachedOtel === void 0) {
4056
4258
  try {
4057
- const r = module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('chunk-2WY2OFSC.cjs', document.baseURI).href)));
4259
+ const r = module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('chunk-26UQG242.cjs', document.baseURI).href)));
4058
4260
  const mod = r("@opentelemetry/api");
4059
4261
  cachedOtel = mod;
4060
4262
  } catch {
@@ -4193,8 +4395,13 @@ function wrapSpan(span, openSpans) {
4193
4395
  setAttribute: (k, v) => safe(() => span.setAttribute(k, redactAttrValue(v)), void 0),
4194
4396
  setAttributes: (attrs) => safe(() => span.setAttributes(redactAttrs(attrs)), void 0),
4195
4397
  addEvent: (name, attrs) => safe(() => span.addEvent(name, attrs ? redactAttrs(attrs) : void 0), void 0),
4196
- setStatus: (status) => safe(() => span.setStatus(status), void 0),
4197
- recordException: (err) => safe(() => span.recordException(err), void 0),
4398
+ setStatus: (status) => safe(
4399
+ () => span.setStatus(
4400
+ status.message === void 0 ? status : { ...status, message: chunkRNXXYF22_cjs.redactSecrets(status.message) }
4401
+ ),
4402
+ void 0
4403
+ ),
4404
+ recordException: (err) => safe(() => span.recordException(redactException(err)), void 0),
4198
4405
  end: (endTime) => {
4199
4406
  safe(() => span.end(endTime), void 0);
4200
4407
  openSpans.delete(span);
@@ -4203,6 +4410,18 @@ function wrapSpan(span, openSpans) {
4203
4410
  isRecording: () => safe(() => span.isRecording(), false)
4204
4411
  };
4205
4412
  }
4413
+ function redactException(err) {
4414
+ if (typeof err === "string") return chunkRNXXYF22_cjs.redactSecrets(err);
4415
+ if (typeof err !== "object" || err === null) return err;
4416
+ const src = err;
4417
+ const out = {};
4418
+ for (const k of ["name", "code", "message", "stack"]) {
4419
+ const v = src[k];
4420
+ if (typeof v === "string") out[k] = chunkRNXXYF22_cjs.redactSecrets(v);
4421
+ else if (typeof v === "number") out[k] = v;
4422
+ }
4423
+ return out;
4424
+ }
4206
4425
  function redactAttrValue(value) {
4207
4426
  if (typeof value !== "string") return value;
4208
4427
  return chunkRNXXYF22_cjs.redactSecrets(value);
@@ -5167,7 +5386,9 @@ function evaluateBudgetGate(tracker) {
5167
5386
  return {
5168
5387
  allowed: false,
5169
5388
  reason: "custom",
5170
- detail: `budget_tracker_check_threw: ${message}`
5389
+ detail: `budget_tracker_check_threw: ${message}`,
5390
+ // Keep the thrown value so the run's error can carry it as its cause.
5391
+ cause: error
5171
5392
  };
5172
5393
  }
5173
5394
  }
@@ -5177,11 +5398,12 @@ function createDoomLoopTracker(option) {
5177
5398
  if (option === false) return void 0;
5178
5399
  return new DoomLoopTracker(option);
5179
5400
  }
5180
- var DEFAULT_CONFIG = { softThreshold: 3, hardThreshold: 5 };
5181
- function assertValidThresholds(soft, hard) {
5401
+ var DEFAULT_CONFIG = { softThreshold: 3, hardThreshold: 5, churnThreshold: 6 };
5402
+ function assertValidThresholds(soft, hard, churn) {
5182
5403
  for (const [label, value] of [
5183
5404
  ["softThreshold", soft],
5184
- ["hardThreshold", hard]
5405
+ ["hardThreshold", hard],
5406
+ ["churnThreshold", churn]
5185
5407
  ]) {
5186
5408
  if (!Number.isInteger(value) || value < 1) {
5187
5409
  throw new chunkCEGU5AVD_cjs.ConfigurationError(
@@ -5218,17 +5440,40 @@ var DoomLoopTracker = class {
5218
5440
  #config;
5219
5441
  #lastSignature = "";
5220
5442
  #count = 0;
5443
+ #lastName = "";
5444
+ #lastResult;
5445
+ #churn = 0;
5221
5446
  constructor(config) {
5222
5447
  const softThreshold = config?.softThreshold ?? DEFAULT_CONFIG.softThreshold;
5223
5448
  const hardThreshold = config?.hardThreshold ?? DEFAULT_CONFIG.hardThreshold;
5224
- assertValidThresholds(softThreshold, hardThreshold);
5225
- this.#config = { softThreshold, hardThreshold };
5449
+ const churnThreshold = config?.churnThreshold ?? DEFAULT_CONFIG.churnThreshold;
5450
+ assertValidThresholds(softThreshold, hardThreshold, churnThreshold);
5451
+ this.#config = { softThreshold, hardThreshold, churnThreshold };
5226
5452
  }
5227
5453
  inspect(call) {
5228
5454
  const signature = signatureOf(call);
5229
- this.#count = signature === this.#lastSignature ? this.#count + 1 : 1;
5455
+ const identical = signature === this.#lastSignature;
5456
+ const churning = !identical && call.name === this.#lastName && call.result !== void 0 && call.result === this.#lastResult;
5457
+ this.#churn = churning ? this.#churn + 1 : 1;
5458
+ this.#lastName = call.name;
5459
+ this.#lastResult = call.result;
5460
+ this.#count = identical ? this.#count + 1 : 1;
5230
5461
  this.#lastSignature = signature;
5231
5462
  const count = this.#count;
5463
+ const churn = this.#churn;
5464
+ const churnHard = this.#config.churnThreshold;
5465
+ if (churn >= churnHard) {
5466
+ return {
5467
+ kind: "hard",
5468
+ message: `Detected argument churn: ${churn} consecutive calls to \`${call.name}\` with different arguments and no change in the result; stopping to avoid a loop.`
5469
+ };
5470
+ }
5471
+ if (churn > 1 && churn === Math.max(2, churnHard - 2)) {
5472
+ return {
5473
+ kind: "soft",
5474
+ message: `Detected argument churn: ${churn} consecutive calls to \`${call.name}\` with different arguments and no change in the result; try a different approach.`
5475
+ };
5476
+ }
5232
5477
  if (count >= this.#config.hardThreshold) {
5233
5478
  return {
5234
5479
  kind: "hard",
@@ -5246,6 +5491,9 @@ var DoomLoopTracker = class {
5246
5491
  reset() {
5247
5492
  this.#lastSignature = "";
5248
5493
  this.#count = 0;
5494
+ this.#lastName = "";
5495
+ this.#lastResult = void 0;
5496
+ this.#churn = 0;
5249
5497
  }
5250
5498
  };
5251
5499
  function firstDoomLoopVerdict(tracker, calls) {
@@ -5490,7 +5738,16 @@ async function initLoopContext(inputs) {
5490
5738
  ),
5491
5739
  buildUserEvent(inputs)
5492
5740
  ]);
5493
- if (inputs.onLoopEvent !== void 0) events.subscribe(inputs.onLoopEvent);
5741
+ if (inputs.onLoopEvent !== void 0) {
5742
+ const sink = inputs.onLoopEvent;
5743
+ for (const seeded of events) {
5744
+ try {
5745
+ sink(seeded);
5746
+ } catch {
5747
+ }
5748
+ }
5749
+ events.subscribe(sink);
5750
+ }
5494
5751
  const priorMessages = replayMessages(inputs.priorMessages ?? []);
5495
5752
  let memorySystemPromptAdditions;
5496
5753
  if (inputs.memoryProvider !== void 0 && memoryProviderHandle !== void 0) {
@@ -5579,7 +5836,8 @@ async function collectTools(mcp, withheld, sink) {
5579
5836
  inputSchema: tool.inputSchema,
5580
5837
  origin: "mcp",
5581
5838
  mcpServerName: serverName,
5582
- mcpToolName: tool.name
5839
+ mcpToolName: tool.name,
5840
+ ...client.sequential === true ? { mcpSequential: true } : {}
5583
5841
  });
5584
5842
  }
5585
5843
  }
@@ -5779,7 +6037,7 @@ function catalogCostFallback(provider, cleanedModel) {
5779
6037
  const candidates = [`${provider}/${cleanedModel}`, cleanedModel];
5780
6038
  if (stripped !== cleanedModel) candidates.push(`${provider}/${stripped}`, stripped);
5781
6039
  for (const key of candidates) {
5782
- const info = chunk4TEGFMSP_cjs.getCatalogModelInfo(key);
6040
+ const info = chunkP7QYG4RZ_cjs.getCatalogModelInfo(key);
5783
6041
  const cost = info?.cost;
5784
6042
  if (cost === void 0) continue;
5785
6043
  const [prov, ...modelParts] = key.split("/");
@@ -5791,7 +6049,7 @@ function catalogCostFallback(provider, cleanedModel) {
5791
6049
  ...cost.cache_read !== void 0 ? { cacheReadCostPerMillion: cost.cache_read } : {},
5792
6050
  ...cost.cache_write !== void 0 ? { cacheWriteCostPerMillion: cost.cache_write } : {},
5793
6051
  // M44 M5 fix — honest provenance: a key patched by the LIVE models-dev source is not "vendored".
5794
- pricingVersion: chunk4TEGFMSP_cjs.isPatchedModelKey(key) ? "catalog-models-dev" : "catalog-vendored"
6052
+ pricingVersion: chunkP7QYG4RZ_cjs.isPatchedModelKey(key) ? "catalog-models-dev" : "catalog-vendored"
5795
6053
  };
5796
6054
  }
5797
6055
  return void 0;
@@ -6045,7 +6303,7 @@ ${chunk3UMPP553_cjs.escapeBlockBody(additions)}
6045
6303
  </active-memory>`;
6046
6304
  }
6047
6305
  function buildLoopSystem(systemPrompt, additions, modelId) {
6048
- if (!chunk4KBI37F3_cjs.isAnthropicFamilyModel(modelId) || systemPrompt === void 0 || systemPrompt.length === 0) {
6306
+ if (!chunkRTDVSHJR_cjs.isAnthropicFamilyModel(modelId) || systemPrompt === void 0 || systemPrompt.length === 0) {
6049
6307
  return resolveSystemPromptWithMemoryAdditions(systemPrompt, additions);
6050
6308
  }
6051
6309
  const blocks = [{ text: systemPrompt, cacheable: true }];
@@ -6566,11 +6824,35 @@ function raceToolExecution(exec, opts) {
6566
6824
  // src/internal/agent-loop/tool-dispatch.ts
6567
6825
  async function dispatchTools(inputs, tools, toolCalls, events, parentSpan) {
6568
6826
  const maxConcurrent = inputs.maxConcurrentTools ?? 4;
6569
- return chunk27V5I2WW_cjs.mapWithConcurrency(
6570
- toolCalls,
6571
- maxConcurrent,
6572
- (call) => dispatchSingleCall(inputs, tools, call, events, parentSpan)
6573
- );
6827
+ const units = [];
6828
+ const bySequentialServer = /* @__PURE__ */ new Map();
6829
+ toolCalls.forEach((call, index) => {
6830
+ const tool = tools.find((t) => t.name === call.name);
6831
+ if (tool?.mcpSequential === true && tool.mcpServerName !== void 0) {
6832
+ let unit = bySequentialServer.get(tool.mcpServerName);
6833
+ if (unit === void 0) {
6834
+ unit = { indexes: [] };
6835
+ bySequentialServer.set(tool.mcpServerName, unit);
6836
+ units.push(unit);
6837
+ }
6838
+ unit.indexes.push(index);
6839
+ } else {
6840
+ units.push({ indexes: [index] });
6841
+ }
6842
+ });
6843
+ const results = new Array(toolCalls.length);
6844
+ await chunk27V5I2WW_cjs.mapWithConcurrency(units, maxConcurrent, async (unit) => {
6845
+ for (const index of unit.indexes) {
6846
+ results[index] = await dispatchSingleCall(
6847
+ inputs,
6848
+ tools,
6849
+ toolCalls[index],
6850
+ events,
6851
+ parentSpan
6852
+ );
6853
+ }
6854
+ });
6855
+ return results;
6574
6856
  }
6575
6857
  async function dispatchSingleCall(inputs, tools, call, events, parentSpan) {
6576
6858
  const { call: workingCall, repairs } = applyRepairAndExtractCall(tools, call);
@@ -6910,7 +7192,7 @@ function applyToolResultGuard(parts, opts) {
6910
7192
  (p) => (
6911
7193
  // SE7 — guard the TEXT of a tool result (string or the text blocks of a
6912
7194
  // structured content); image blocks pass through untouched.
6913
- p.type === "tool_result" ? { ...p, content: chunkSNVYOX46_cjs.renderToolResultContentText(p.content, (t) => guardText(t, opts)) } : p
7195
+ p.type === "tool_result" ? { ...p, content: chunk3E3VSMB6_cjs.renderToolResultContentText(p.content, (t) => guardText(t, opts)) } : p
6914
7196
  )
6915
7197
  );
6916
7198
  }
@@ -6947,12 +7229,17 @@ async function runAgentLoop(inputs) {
6947
7229
  const budget = inputs.budget ?? new IterationBudget({ maxIterations: inputs.maxIterations ?? 8 });
6948
7230
  let lastTurnDecision;
6949
7231
  while (budget.shouldContinue()) {
7232
+ injectSteered(ctx, inputs.steerQueue?.drain());
6950
7233
  if (inputs.budgetTracker !== void 0) {
6951
7234
  const decision2 = evaluateBudgetGate(inputs.budgetTracker);
6952
7235
  if (decision2.allowed === false) {
6953
7236
  ctx.finalStatus = "error";
6954
7237
  if (decision2.detail !== void 0) {
6955
- ctx.error = { message: decision2.detail, code: decision2.reason ?? "budget" };
7238
+ ctx.error = {
7239
+ message: decision2.detail,
7240
+ code: decision2.reason ?? "budget",
7241
+ ...decision2.cause !== void 0 ? { cause: decision2.cause } : {}
7242
+ };
6956
7243
  }
6957
7244
  if (decision2.reason === "iteration_limit") {
6958
7245
  ctx.stoppedAtIterationLimit = true;
@@ -6964,7 +7251,13 @@ async function runAgentLoop(inputs) {
6964
7251
  if (usingGrace) budget.useGraceCall();
6965
7252
  const decision = await runIteration(inputs, ctx);
6966
7253
  lastTurnDecision = decision;
6967
- if (decision === "done") break;
7254
+ if (decision === "done") {
7255
+ const late = inputs.steerQueue?.drainOrClose() ?? [];
7256
+ if (late.length === 0) break;
7257
+ injectSteered(ctx, late);
7258
+ budget.consume();
7259
+ continue;
7260
+ }
6968
7261
  if (decision === "error") {
6969
7262
  ctx.finalStatus = "error";
6970
7263
  break;
@@ -7092,6 +7385,10 @@ async function finishOrReflect(inputs, ctx, llmOutput) {
7092
7385
  ctx.finalStatus = "finished";
7093
7386
  return "done";
7094
7387
  }
7388
+ function injectSteered(ctx, texts) {
7389
+ if (texts === void 0) return;
7390
+ for (const text of texts) ctx.messages.push({ role: "user", content: [{ type: "text", text }] });
7391
+ }
7095
7392
  async function runIteration(inputs, ctx) {
7096
7393
  const hookCtx = { agentId: inputs.agentId, runId: inputs.runId };
7097
7394
  await inputs.pluginManager?.runPreLlmCallHooks(hookCtx);
@@ -7105,12 +7402,11 @@ function trackTurnUsage(inputs, llmOutput) {
7105
7402
  const tracker = inputs.budgetTracker;
7106
7403
  if (tracker === void 0) return;
7107
7404
  const model = inputs.model.id ?? "auto";
7108
- trackEvent(tracker, { tokens: promptTokens(llmOutput), model, type: "input" });
7405
+ trackEvent(tracker, { tokens: llmOutput.inputTokens ?? 0, model, type: "input" });
7406
+ trackEvent(tracker, { tokens: llmOutput.cacheReadTokens ?? 0, model, type: "cache_read" });
7407
+ trackEvent(tracker, { tokens: llmOutput.cacheWriteTokens ?? 0, model, type: "cache_write" });
7109
7408
  trackEvent(tracker, { tokens: llmOutput.outputTokens ?? 0, model, type: "output" });
7110
7409
  }
7111
- function promptTokens(llmOutput) {
7112
- return (llmOutput.inputTokens ?? 0) + (llmOutput.cacheReadTokens ?? 0) + (llmOutput.cacheWriteTokens ?? 0);
7113
- }
7114
7410
  function trackEvent(tracker, event) {
7115
7411
  if (event.tokens <= 0) return;
7116
7412
  try {
@@ -7169,12 +7465,22 @@ async function continueOrTerminate(inputs, ctx, llmOutput) {
7169
7465
  }
7170
7466
  }
7171
7467
  pushToolConversationSteps(ctx, llmOutput.toolCalls, toolResults);
7172
- if (await inspectDoomLoop(inputs, ctx, llmOutput.toolCalls) === "stop") return "done";
7468
+ if (await inspectDoomLoop(inputs, ctx, llmOutput.toolCalls, toolResults) === "stop")
7469
+ return "done";
7173
7470
  return handleToolErrorContinuation(inputs, ctx, toolResults);
7174
7471
  }
7175
- async function inspectDoomLoop(inputs, ctx, toolCalls) {
7472
+ async function inspectDoomLoop(inputs, ctx, toolCalls, toolResults) {
7176
7473
  if (ctx.doomLoop === void 0) return "continue";
7177
- const verdict = firstDoomLoopVerdict(ctx.doomLoop, toolCalls);
7474
+ const resultById = /* @__PURE__ */ new Map();
7475
+ for (const part of toolResults) {
7476
+ if (part.type === "tool_result") {
7477
+ resultById.set(part.toolUseId, JSON.stringify([part.content, part.isError === true]));
7478
+ }
7479
+ }
7480
+ const verdict = firstDoomLoopVerdict(
7481
+ ctx.doomLoop,
7482
+ toolCalls.map((c) => ({ name: c.name, input: c.input, result: resultById.get(c.id) }))
7483
+ );
7178
7484
  if (verdict.kind === "hard") {
7179
7485
  ctx.stoppedByDoomLoop = true;
7180
7486
  await emitAssistantTextStep(
@@ -7228,13 +7534,13 @@ var FallbackLlmClient = class {
7228
7534
  async *stream(request, signal) {
7229
7535
  let lastError;
7230
7536
  for (const client of this.clients) {
7231
- if (signal.aborted) throw chunkSNVYOX46_cjs.abortError(signal);
7232
- const attempt = await chunkSNVYOX46_cjs.tryFirstEvent(client, request, signal, true);
7537
+ if (signal.aborted) throw chunk3E3VSMB6_cjs.abortError(signal);
7538
+ const attempt = await chunk3E3VSMB6_cjs.tryFirstEvent(client, request, signal, true);
7233
7539
  if (attempt.kind === "handshake_error") {
7234
7540
  lastError = attempt.error;
7235
7541
  continue;
7236
7542
  }
7237
- return yield* chunkSNVYOX46_cjs.relayStream(attempt.generator, attempt.firstResult);
7543
+ return yield* chunk3E3VSMB6_cjs.relayStream(attempt.generator, attempt.firstResult);
7238
7544
  }
7239
7545
  if (lastError !== void 0) throw lastError;
7240
7546
  throw new chunkCEGU5AVD_cjs.NetworkError("FallbackLlmClient has no providers configured", {
@@ -7251,6 +7557,34 @@ function handshakeAwareTimeout(input) {
7251
7557
  return isReconnectHandshake ? Math.max(input.requestTimeoutMs, HANDSHAKE_FLOOR_MS) : input.requestTimeoutMs;
7252
7558
  }
7253
7559
 
7560
+ // src/internal/mcp/oauth-bearer.ts
7561
+ var EXPIRY_SKEW_MS = 3e4;
7562
+ async function obtain(serverName, clientId, scopes, oauth) {
7563
+ const stored = await chunkXOU3CL7S_cjs.getTokens(serverName);
7564
+ if (stored?.accessToken !== void 0 && stored.expiresAt - EXPIRY_SKEW_MS > Date.now()) {
7565
+ return stored;
7566
+ }
7567
+ const refreshToken = stored?.refreshToken;
7568
+ if (refreshToken !== void 0) {
7569
+ try {
7570
+ return await chunkXOU3CL7S_cjs.lockedRefresh(
7571
+ serverName,
7572
+ () => chunkXOU3CL7S_cjs.refreshAccessToken(serverName, clientId, refreshToken, oauth)
7573
+ );
7574
+ } catch {
7575
+ }
7576
+ }
7577
+ const fresh = await chunkXOU3CL7S_cjs.runPkceFlow(serverName, clientId, scopes, oauth);
7578
+ await chunkXOU3CL7S_cjs.setTokens(serverName, fresh);
7579
+ return fresh;
7580
+ }
7581
+ async function resolveBearer(serverName, auth) {
7582
+ if (auth.oauth === void 0)
7583
+ throw new Error(`MCP server "${serverName}" declares no auth.oauth`);
7584
+ const tokens = await obtain(serverName, auth.CLIENT_ID, auth.scopes, auth.oauth);
7585
+ return `Bearer ${tokens.accessToken}`;
7586
+ }
7587
+
7254
7588
  // src/internal/mcp/client.ts
7255
7589
  function createMcpClient(name, config, fetchImpl = fetch) {
7256
7590
  if (isStdio(config)) return new StdioMcpClient(name, config);
@@ -7331,6 +7665,9 @@ var StdioMcpClient = class extends BaseMcpClient {
7331
7665
  reconnectPromise;
7332
7666
  /** True only while `reconnect()`'s handshake is in flight — see `timeoutFor`. */
7333
7667
  reconnecting = false;
7668
+ get sequential() {
7669
+ return this.config.sequential === true;
7670
+ }
7334
7671
  get timeoutMs() {
7335
7672
  return this.config.requestTimeoutMs ?? DEFAULT_MCP_TIMEOUT_MS;
7336
7673
  }
@@ -7537,6 +7874,9 @@ var HttpMcpClient = class extends BaseMcpClient {
7537
7874
  */
7538
7875
  sessionId;
7539
7876
  fetchImpl;
7877
+ get sequential() {
7878
+ return this.config.sequential === true;
7879
+ }
7540
7880
  close() {
7541
7881
  return Promise.resolve();
7542
7882
  }
@@ -7549,7 +7889,9 @@ var HttpMcpClient = class extends BaseMcpClient {
7549
7889
  * override contract predates this change and is the only escape a user has while a server
7550
7890
  * misbehaves.
7551
7891
  */
7552
- buildHeaders() {
7892
+ async buildHeaders() {
7893
+ const auth = this.config.auth;
7894
+ const bearer = auth?.oauth !== void 0 ? await resolveBearer(this.name, auth) : void 0;
7553
7895
  return {
7554
7896
  "content-type": "application/json",
7555
7897
  // Streamable HTTP asks for BOTH media types. Declaring only `application/json` makes a
@@ -7558,6 +7900,7 @@ var HttpMcpClient = class extends BaseMcpClient {
7558
7900
  // Present only for a STATEFUL server. For a stateless one nothing is sent — inventing a
7559
7901
  // header would trade one broken transport for another.
7560
7902
  ...this.sessionId !== void 0 ? { "mcp-session-id": this.sessionId } : {},
7903
+ ...bearer !== void 0 ? { authorization: bearer } : {},
7561
7904
  ...this.config.headers ?? {}
7562
7905
  };
7563
7906
  }
@@ -7600,7 +7943,7 @@ var HttpMcpClient = class extends BaseMcpClient {
7600
7943
  async request(method, params) {
7601
7944
  const id = this.nextId++;
7602
7945
  const payload = { jsonrpc: "2.0", id, method, params };
7603
- const headers = this.buildHeaders();
7946
+ const headers = await this.buildHeaders();
7604
7947
  const timeoutMs = this.config.requestTimeoutMs ?? DEFAULT_MCP_TIMEOUT_MS;
7605
7948
  let response;
7606
7949
  try {
@@ -7878,9 +8221,9 @@ function buildLoopInputs(options, runId, userText, userImages) {
7878
8221
  );
7879
8222
  }
7880
8223
  validatePruneToolResults(options.sendOptions.pruneToolResults);
7881
- const { primary, effectiveModelId } = chunkSNVYOX46_cjs.resolveRunProvider(options);
8224
+ const { primary, effectiveModelId } = chunk3E3VSMB6_cjs.resolveRunProvider(options);
7882
8225
  const fallback = options.agentOptions.providers?.fallback;
7883
- const apiKeys = chunkSNVYOX46_cjs.mergeExplicitApiKey(
8226
+ const apiKeys = chunk3E3VSMB6_cjs.mergeExplicitApiKey(
7884
8227
  options.agentOptions.providers?.apiKeys,
7885
8228
  primary,
7886
8229
  options.agentOptions.apiKey
@@ -7889,7 +8232,7 @@ function buildLoopInputs(options, runId, userText, userImages) {
7889
8232
  const extractToolCallsFromContent = options.agentOptions.providers?.routes?.[0]?.extractToolCallsFromContent;
7890
8233
  const rateLimitSink = options.sendOptions.onRunEvent;
7891
8234
  const modelBaseUrl = options.model?.url;
7892
- const chain = chunkSNVYOX46_cjs.resolveProviderChain({
8235
+ const chain = chunk3E3VSMB6_cjs.resolveProviderChain({
7893
8236
  primary,
7894
8237
  ...modelBaseUrl !== void 0 ? { baseUrl: modelBaseUrl } : {},
7895
8238
  ...fallback !== void 0 ? { fallback } : {},
@@ -7947,6 +8290,7 @@ function buildLoopInputs(options, runId, userText, userImages) {
7947
8290
  ...options.sendOptions.context !== void 0 ? { context: options.sendOptions.context } : {},
7948
8291
  // SE2 — forward the opt-in typed runtime-event sink to the loop.
7949
8292
  ...options.sendOptions.onRunEvent !== void 0 ? { runEventSink: options.sendOptions.onRunEvent } : {},
8293
+ ...options.steerQueue !== void 0 ? { steerQueue: options.steerQueue } : {},
7950
8294
  ...toolResultPolicyInputs(options.sendOptions),
7951
8295
  // M1-2: per-send iteration ceiling (validated above). The loop reads
7952
8296
  // inputs.maxIterations (default 8 when unset).
@@ -8168,11 +8512,12 @@ function buildRealRunOptions(args) {
8168
8512
  ...args.priorMessages.length > 0 ? { priorMessages: args.priorMessages } : {},
8169
8513
  ...args.memoryTools !== void 0 && args.memoryTools.length > 0 ? { memoryTools: args.memoryTools } : {},
8170
8514
  ...args.personalityToolWhitelist !== void 0 ? { personalityToolWhitelist: args.personalityToolWhitelist } : {},
8171
- ...args.personalityName !== void 0 ? { personalityName: args.personalityName } : {}
8515
+ ...args.personalityName !== void 0 ? { personalityName: args.personalityName } : {},
8516
+ ...args.steerQueue !== void 0 ? { steerQueue: args.steerQueue } : {}
8172
8517
  };
8173
8518
  }
8174
8519
  async function createFixtureRunHelper(args) {
8175
- const sessionMessages = chunkLXG6VL6R_cjs.getSessionMessages(args.inputs.agentId);
8520
+ const sessionMessages = chunkFBIDOOJM_cjs.getSessionMessages(args.inputs.agentId);
8176
8521
  const projectMcpServers = args.inputs.settingSourcesIncludeProject ? await readProjectMcpServers(args.inputs.workspaceCwd) : {};
8177
8522
  return createLocalRun({
8178
8523
  agentId: args.inputs.agentId,
@@ -8191,7 +8536,7 @@ async function createFixtureRunHelper(args) {
8191
8536
  }
8192
8537
  async function dispatchLocalRun(args) {
8193
8538
  const apiKey = chunkRNXXYF22_cjs.resolveApiKey(args.inputs.options.apiKey);
8194
- if (chunkSNVYOX46_cjs.shouldUseRealLocalRuntime(apiKey)) {
8539
+ if (chunk3E3VSMB6_cjs.shouldUseRealLocalRuntime(apiKey)) {
8195
8540
  return createRealLocalRun(
8196
8541
  buildRealRunOptions({
8197
8542
  inputs: args.inputs,
@@ -8200,6 +8545,7 @@ async function dispatchLocalRun(args) {
8200
8545
  systemPrompt: args.systemPrompt,
8201
8546
  priorMessages: args.priorMessages,
8202
8547
  memoryTools: args.memoryTools,
8548
+ ...args.steerQueue !== void 0 ? { steerQueue: args.steerQueue } : {},
8203
8549
  ...args.activePreset?.tools !== void 0 ? { personalityToolWhitelist: args.activePreset.tools } : {},
8204
8550
  ...args.activePreset !== void 0 ? { personalityName: args.activePreset.name } : {}
8205
8551
  })
@@ -8252,177 +8598,6 @@ async function consumePending(agentId, pending, clear, refresh) {
8252
8598
  await applyDeferredInvalidation(agentId, pending, refresh);
8253
8599
  }
8254
8600
 
8255
- // src/internal/runtime/registry/live-agent-registry.ts
8256
- var DEFAULT_MAX_AGENTS = 100;
8257
- var DEFAULT_IDLE_TIMEOUT_MS = 30 * 60 * 1e3;
8258
- var DEFAULT_SWEEP_INTERVAL_MS = 6e4;
8259
- var LiveAgentRegistry = class {
8260
- #agents = /* @__PURE__ */ new Map();
8261
- #maxAgents = DEFAULT_MAX_AGENTS;
8262
- #idleTimeoutMs = DEFAULT_IDLE_TIMEOUT_MS;
8263
- #sweepIntervalMs = DEFAULT_SWEEP_INTERVAL_MS;
8264
- #onEvict;
8265
- #sweepTimer;
8266
- /**
8267
- * Reconfigure registry behavior. Process-wide singleton (D310) — last
8268
- * configure call wins for all subsequent operations.
8269
- */
8270
- configure(opts) {
8271
- if (opts.maxAgents !== void 0) this.#maxAgents = Math.max(0, opts.maxAgents);
8272
- if (opts.idleTimeoutMs !== void 0) this.#idleTimeoutMs = Math.max(0, opts.idleTimeoutMs);
8273
- if (opts.sweepIntervalMs !== void 0)
8274
- this.#sweepIntervalMs = Math.max(1e3, opts.sweepIntervalMs);
8275
- this.#onEvict = opts.onEvict;
8276
- this.#stopSweep();
8277
- if (this.#idleTimeoutMs > 0) this.#startSweep();
8278
- }
8279
- /**
8280
- * Lookup a cached agent. `get` is a use — refreshes `lastUsedAt` so the
8281
- * entry survives LRU eviction.
8282
- */
8283
- get(id) {
8284
- const entry = this.#agents.get(id);
8285
- if (entry === void 0) return void 0;
8286
- entry.lastUsedAt = Date.now();
8287
- return entry.agent;
8288
- }
8289
- /**
8290
- * Insert or overwrite an agent in the cache. Triggers fire-and-forget LRU
8291
- * eviction when `size > maxAgents`.
8292
- *
8293
- * EC-4: when `id` already maps to a DIFFERENT agent instance, dispose the
8294
- * old one before overwriting (race protection against two `getOrCreate`
8295
- * calls creating two agents but only the second being cached — the first
8296
- * would leak file handles + lifecycle controllers).
8297
- */
8298
- set(id, agent) {
8299
- if (this.#maxAgents === 0) return;
8300
- const existing = this.#agents.get(id);
8301
- if (existing !== void 0 && existing.agent !== agent) {
8302
- void existing.agent.dispose().catch(() => {
8303
- chunkRNXXYF22_cjs.diag(`[theokit-sdk] dispose during overwrite failed (${id})
8304
- `);
8305
- });
8306
- }
8307
- this.#agents.set(id, { agent, lastUsedAt: Date.now() });
8308
- if (this.#agents.size > this.#maxAgents) void this.#evictLRU();
8309
- }
8310
- /**
8311
- * Remove the entry from the cache WITHOUT calling `dispose()` or
8312
- * `onEvict`. Used by `LocalAgent.dispose()` itself so the disposed
8313
- * instance can never be returned by a subsequent `get(id)` (dispose-cache
8314
- * race fix). Idempotent — calling on an unknown id is a no-op.
8315
- *
8316
- * @internal
8317
- */
8318
- forget(id) {
8319
- this.#agents.delete(id);
8320
- }
8321
- /**
8322
- * Explicitly evict an agent by id. Returns `true` when the entry was
8323
- * present (false = already gone). Calls `agent.dispose()` + `onEvict`
8324
- * with reason `"explicit"`.
8325
- */
8326
- async evict(id) {
8327
- const entry = this.#agents.get(id);
8328
- if (entry === void 0) return false;
8329
- this.#agents.delete(id);
8330
- await this.#disposeAndNotify(id, entry.agent, "explicit");
8331
- return true;
8332
- }
8333
- /**
8334
- * Evict every cached agent. Used by graceful shutdown (`process.on('SIGTERM')`)
8335
- * or end-of-test cleanup.
8336
- */
8337
- async evictAll() {
8338
- const entries = Array.from(this.#agents.entries());
8339
- this.#agents.clear();
8340
- this.#stopSweep();
8341
- for (const [id, entry] of entries) {
8342
- await this.#disposeAndNotify(id, entry.agent, "explicit");
8343
- }
8344
- }
8345
- /** Number of currently cached agents. */
8346
- size() {
8347
- return this.#agents.size;
8348
- }
8349
- /** Ids of cached agents, newest first (by lastUsedAt). */
8350
- ids() {
8351
- return Array.from(this.#agents.entries()).sort((a, b) => b[1].lastUsedAt - a[1].lastUsedAt).map(([id]) => id);
8352
- }
8353
- /**
8354
- * LRU eviction: drop the entry with the smallest `lastUsedAt`. Runs only
8355
- * when `size > maxAgents`. Asynchronous because `dispose()` is a Promise;
8356
- * the hot-path caller (`set`) does not await.
8357
- *
8358
- * @internal
8359
- */
8360
- async #evictLRU() {
8361
- if (this.#agents.size <= this.#maxAgents) return;
8362
- let oldestId;
8363
- let oldestAt = Infinity;
8364
- for (const [id, entry2] of this.#agents) {
8365
- if (entry2.lastUsedAt < oldestAt) {
8366
- oldestAt = entry2.lastUsedAt;
8367
- oldestId = id;
8368
- }
8369
- }
8370
- if (oldestId === void 0) return;
8371
- const entry = this.#agents.get(oldestId);
8372
- if (entry === void 0) return;
8373
- this.#agents.delete(oldestId);
8374
- await this.#disposeAndNotify(oldestId, entry.agent, "lru");
8375
- }
8376
- /** Background sweep — drops entries whose `lastUsedAt < now - idleTimeoutMs`. */
8377
- async #sweepIdle() {
8378
- if (this.#idleTimeoutMs === 0) return;
8379
- const threshold = Date.now() - this.#idleTimeoutMs;
8380
- const toEvict = [];
8381
- for (const [id, entry] of this.#agents) {
8382
- if (entry.lastUsedAt < threshold) toEvict.push([id, entry]);
8383
- }
8384
- for (const [id, entry] of toEvict) {
8385
- const current = this.#agents.get(id);
8386
- if (current === void 0 || current.agent !== entry.agent) continue;
8387
- this.#agents.delete(id);
8388
- await this.#disposeAndNotify(id, entry.agent, "idle");
8389
- }
8390
- }
8391
- #startSweep() {
8392
- this.#sweepTimer = setInterval(() => void this.#sweepIdle(), this.#sweepIntervalMs);
8393
- this.#sweepTimer.unref?.();
8394
- }
8395
- #stopSweep() {
8396
- if (this.#sweepTimer !== void 0) {
8397
- clearInterval(this.#sweepTimer);
8398
- this.#sweepTimer = void 0;
8399
- }
8400
- }
8401
- /** Dispose + notify with errors swallowed (D309). Single chokepoint. */
8402
- async #disposeAndNotify(id, agent, reason) {
8403
- try {
8404
- await agent.dispose();
8405
- } catch (cause) {
8406
- const msg = cause instanceof Error ? cause.message : String(cause);
8407
- chunkRNXXYF22_cjs.diag(`[theokit-sdk] dispose during eviction failed (${id}): ${msg}
8408
- `);
8409
- }
8410
- if (this.#onEvict !== void 0) {
8411
- try {
8412
- this.#onEvict(id, reason);
8413
- } catch (cause) {
8414
- const msg = cause instanceof Error ? cause.message : String(cause);
8415
- chunkRNXXYF22_cjs.diag(`[theokit-sdk] onEvict listener threw (${id}): ${msg}
8416
- `);
8417
- }
8418
- }
8419
- }
8420
- };
8421
- var liveAgentRegistry = chunkNVXXWAU7_cjs.globalSingleton(
8422
- "theokit-sdk.runtime.live-agents",
8423
- () => new LiveAgentRegistry()
8424
- );
8425
-
8426
8601
  // src/internal/local-agent/local-agent-lifecycle.ts
8427
8602
  async function acquireLeaseIfPossible(store, agentId) {
8428
8603
  if (typeof store.acquire !== "function") return;
@@ -8445,18 +8620,18 @@ async function disposeSessionStore(store) {
8445
8620
  async function disposeLocalAgentSession(agent) {
8446
8621
  liveAgentRegistry.forget(agent.agentId);
8447
8622
  agent.lifecycleAbortController.abort();
8448
- await chunkZF2LDKQQ_cjs.withCwdMutex(`agent-send:${agent.agentId}`, () => Promise.resolve());
8623
+ await chunkU3DW3WDE_cjs.withCwdMutex(`agent-send:${agent.agentId}`, () => Promise.resolve());
8449
8624
  disposeSessionMcpClients(agent.agentId);
8450
- await chunkLXG6VL6R_cjs.flushSessionWrites();
8625
+ await chunkFBIDOOJM_cjs.flushSessionWrites();
8451
8626
  await flushRegistrySaves(agent.workspaceCwd);
8452
8627
  await disposeSessionStore(agent.sessionStore);
8453
- chunkLXG6VL6R_cjs.discardSession(agent.workspaceCwd, agent.agentId);
8628
+ chunkFBIDOOJM_cjs.discardSession(agent.workspaceCwd, agent.agentId);
8454
8629
  }
8455
8630
  async function reloadLocalAgent(agent) {
8456
8631
  if (agent.context !== void 0) await agent.context.refresh();
8457
8632
  if (agent.skillsManager !== void 0) await agent.skillsManager.refresh();
8458
8633
  if (agent.pluginsManager !== void 0) await agent.pluginsManager.refresh();
8459
- return await chunkWDVG5R2Q_cjs.loadSubagents(
8634
+ return await chunkAUH2EVWY_cjs.loadSubagents(
8460
8635
  agent.workspaceCwd,
8461
8636
  agent.settingSourcesIncludeProject,
8462
8637
  agent.options.agents
@@ -8702,7 +8877,7 @@ async function finalize(args, queryMode, result) {
8702
8877
  };
8703
8878
  args.cache?.set(args.userText, queryMode, result, tenantCtx);
8704
8879
  if (args.persistTranscripts === true && args.cwd !== void 0) {
8705
- await chunkRS7YQR4X_cjs.persistActiveMemoryTranscript(args.memoryRoot ?? chunkSDZ4XDWS_cjs.resolveMemoryRoot(args.cwd), {
8880
+ await chunkRS7YQR4X_cjs.persistActiveMemoryTranscript(args.memoryRoot ?? chunkVWYFGE27_cjs.resolveMemoryRoot(args.cwd), {
8706
8881
  runId: args.runId ?? `run-${Date.now()}`,
8707
8882
  startedAtMs: Date.now() - result.durationMs,
8708
8883
  userText: args.userText,
@@ -8805,7 +8980,7 @@ var openAiMemoryEmbeddingProviderAdapter = {
8805
8980
  transport: "remote",
8806
8981
  authProviderId: "openai",
8807
8982
  autoSelectPriority: 20,
8808
- create: (options) => chunkCGH4BCIY_cjs.createOpenAiCompatibleRuntime(
8983
+ create: (options) => chunkXE3CAY6Z_cjs.createOpenAiCompatibleRuntime(
8809
8984
  {
8810
8985
  id: "openai",
8811
8986
  defaultBaseUrl: "https://api.openai.com",
@@ -8827,7 +9002,7 @@ var azureOpenAiMemoryEmbeddingProviderAdapter = {
8827
9002
  transport: "remote",
8828
9003
  authProviderId: "azure-openai",
8829
9004
  autoSelectPriority: 25,
8830
- create: (options) => chunkCGH4BCIY_cjs.createOpenAiCompatibleRuntime(
9005
+ create: (options) => chunkXE3CAY6Z_cjs.createOpenAiCompatibleRuntime(
8831
9006
  {
8832
9007
  id: "azure-openai",
8833
9008
  defaultBaseUrl: "https://your-resource.openai.azure.com",
@@ -8863,7 +9038,7 @@ var cohereMemoryEmbeddingProviderAdapter = {
8863
9038
  transport: "remote",
8864
9039
  authProviderId: "cohere",
8865
9040
  autoSelectPriority: 30,
8866
- create: (options) => chunkCGH4BCIY_cjs.createOpenAiCompatibleRuntime(
9041
+ create: (options) => chunkXE3CAY6Z_cjs.createOpenAiCompatibleRuntime(
8867
9042
  {
8868
9043
  id: "cohere",
8869
9044
  defaultBaseUrl: "https://api.cohere.com",
@@ -8909,7 +9084,7 @@ var deepinfraMemoryEmbeddingProviderAdapter = {
8909
9084
  transport: "remote",
8910
9085
  authProviderId: "deepinfra",
8911
9086
  autoSelectPriority: 13,
8912
- create: (options) => chunkCGH4BCIY_cjs.createOpenAiCompatibleRuntime(
9087
+ create: (options) => chunkXE3CAY6Z_cjs.createOpenAiCompatibleRuntime(
8913
9088
  {
8914
9089
  id: "deepinfra",
8915
9090
  defaultBaseUrl: "https://api.deepinfra.com",
@@ -8935,7 +9110,7 @@ var geminiMemoryEmbeddingProviderAdapter = {
8935
9110
  transport: "remote",
8936
9111
  authProviderId: "gemini",
8937
9112
  autoSelectPriority: 30,
8938
- create: (options) => chunkCGH4BCIY_cjs.createOpenAiCompatibleRuntime(
9113
+ create: (options) => chunkXE3CAY6Z_cjs.createOpenAiCompatibleRuntime(
8939
9114
  {
8940
9115
  id: "gemini",
8941
9116
  defaultBaseUrl: "https://generativelanguage.googleapis.com",
@@ -8963,7 +9138,7 @@ var jinaMemoryEmbeddingProviderAdapter = {
8963
9138
  transport: "remote",
8964
9139
  authProviderId: "jina",
8965
9140
  autoSelectPriority: 35,
8966
- create: (options) => chunkCGH4BCIY_cjs.createOpenAiCompatibleRuntime(
9141
+ create: (options) => chunkXE3CAY6Z_cjs.createOpenAiCompatibleRuntime(
8967
9142
  {
8968
9143
  id: "jina",
8969
9144
  defaultBaseUrl: "https://api.jina.ai",
@@ -8986,7 +9161,7 @@ var mistralMemoryEmbeddingProviderAdapter = {
8986
9161
  transport: "remote",
8987
9162
  authProviderId: "mistral",
8988
9163
  autoSelectPriority: 18,
8989
- create: (options) => chunkCGH4BCIY_cjs.createOpenAiCompatibleRuntime(
9164
+ create: (options) => chunkXE3CAY6Z_cjs.createOpenAiCompatibleRuntime(
8990
9165
  {
8991
9166
  id: "mistral",
8992
9167
  defaultBaseUrl: "https://api.mistral.ai",
@@ -9028,7 +9203,7 @@ var ollamaMemoryEmbeddingProviderAdapter = {
9028
9203
  autoSelectPriority: 10,
9029
9204
  create: (options) => {
9030
9205
  const apiKey = options.apiKey ?? process.env.OLLAMA_API_KEY ?? OLLAMA_LOCAL_SENTINEL_KEY;
9031
- return chunkCGH4BCIY_cjs.createOpenAiCompatibleRuntime(
9206
+ return chunkXE3CAY6Z_cjs.createOpenAiCompatibleRuntime(
9032
9207
  {
9033
9208
  id: "ollama",
9034
9209
  defaultBaseUrl: "http://localhost:11434",
@@ -9056,7 +9231,7 @@ var openRouterMemoryEmbeddingProviderAdapter = {
9056
9231
  transport: "remote",
9057
9232
  authProviderId: "openrouter",
9058
9233
  autoSelectPriority: 15,
9059
- create: (options) => chunkCGH4BCIY_cjs.createOpenAiCompatibleRuntime(
9234
+ create: (options) => chunkXE3CAY6Z_cjs.createOpenAiCompatibleRuntime(
9060
9235
  {
9061
9236
  id: "openrouter",
9062
9237
  defaultBaseUrl: "https://openrouter.ai/api",
@@ -9084,7 +9259,7 @@ var voyageMemoryEmbeddingProviderAdapter = {
9084
9259
  transport: "remote",
9085
9260
  authProviderId: "voyage",
9086
9261
  autoSelectPriority: 14,
9087
- create: (options) => chunkCGH4BCIY_cjs.createOpenAiCompatibleRuntime(
9262
+ create: (options) => chunkXE3CAY6Z_cjs.createOpenAiCompatibleRuntime(
9088
9263
  {
9089
9264
  id: "voyage",
9090
9265
  defaultBaseUrl: "https://api.voyageai.com",
@@ -9293,7 +9468,7 @@ var LocalAgentMemory = class {
9293
9468
  const openOpts = { cwd: this.workspaceCwd, memoryRoot };
9294
9469
  if (embedding !== void 0) openOpts.embedding = embedding;
9295
9470
  if (cfg?.backend !== void 0) openOpts.backend = cfg.backend;
9296
- this.index = await chunkCWQPQTUZ_cjs.IndexManager.open(openOpts);
9471
+ this.index = await chunkNEH3BPFD_cjs.IndexManager.open(openOpts);
9297
9472
  await this.index.sync();
9298
9473
  this.toolsCache = [
9299
9474
  createMemorySearchTool({ index: this.index }),
@@ -9314,7 +9489,7 @@ var LocalAgentMemory = class {
9314
9489
  async runActiveMemoryIfEnabled(userText, priorMessages, telemetry) {
9315
9490
  const cfg = this.options.memory?.activeRecall;
9316
9491
  if (cfg?.enabled !== true || this.index === void 0) return void 0;
9317
- if (this.breaker === void 0) this.breaker = new chunkSNVYOX46_cjs.CircuitBreaker();
9492
+ if (this.breaker === void 0) this.breaker = new chunk3E3VSMB6_cjs.CircuitBreaker();
9318
9493
  if (this.cache === void 0) this.cache = new ActiveMemoryCache();
9319
9494
  const result = await runActiveMemory({
9320
9495
  userText,
@@ -9337,7 +9512,7 @@ var LocalAgentMemory = class {
9337
9512
  * and the active-memory transcript writer. Three separate resolutions is how they drifted (#463).
9338
9513
  */
9339
9514
  memoryRoot() {
9340
- this.memoryRootCache ??= chunkSDZ4XDWS_cjs.resolveMemoryRoot(this.workspaceCwd, this.options.memory);
9515
+ this.memoryRootCache ??= chunkVWYFGE27_cjs.resolveMemoryRoot(this.workspaceCwd, this.options.memory);
9341
9516
  return this.memoryRootCache;
9342
9517
  }
9343
9518
  buildActiveMemoryOptions(cfg) {
@@ -9452,7 +9627,7 @@ function createLocalAgentMemoryProvider(opts) {
9452
9627
  return { facts: [], systemPromptAdditions: summary };
9453
9628
  },
9454
9629
  async recordSessionSummary(args) {
9455
- await chunkSDZ4XDWS_cjs.writeSessionSummary(args);
9630
+ await chunkVWYFGE27_cjs.writeSessionSummary(args);
9456
9631
  },
9457
9632
  async sync(handle) {
9458
9633
  const state = handle[INTERNAL_LAM_KEY];
@@ -9620,7 +9795,7 @@ async function localAgentUsePersonality(agent, name, opts) {
9620
9795
  agent.personalityRegistry = await PersonalityRegistry.load(agent.workspaceCwd);
9621
9796
  }
9622
9797
  const registry = agent.personalityRegistry;
9623
- return chunkZF2LDKQQ_cjs.withCwdMutex(
9798
+ return chunkU3DW3WDE_cjs.withCwdMutex(
9624
9799
  `agent-send:${agent.agentId}`,
9625
9800
  () => performPersonalitySwitch({
9626
9801
  agentId: agent.agentId,
@@ -9629,8 +9804,8 @@ async function localAgentUsePersonality(agent, name, opts) {
9629
9804
  registry,
9630
9805
  store: agent.personalityStore,
9631
9806
  invalidateCache: (reason) => agent.invalidateCache(reason),
9632
- appendSessionMessage: (msg) => chunkLXG6VL6R_cjs.appendSessionMessage(agent.agentId, msg),
9633
- clearSession: () => chunkLXG6VL6R_cjs.clearSession(agent.agentId),
9807
+ appendSessionMessage: (msg) => chunkFBIDOOJM_cjs.appendSessionMessage(agent.agentId, msg),
9808
+ clearSession: () => chunkFBIDOOJM_cjs.clearSession(agent.agentId),
9634
9809
  opts: opts ?? {}
9635
9810
  })
9636
9811
  );
@@ -10141,6 +10316,14 @@ async function applyInputProcessors(inputs, message, rawUserText, options, sendM
10141
10316
  const effectiveMessage = typeof message === "string" ? res.value : { ...message, text: res.value };
10142
10317
  return { userText: res.value, effectiveMessage };
10143
10318
  }
10319
+ var lastSendAt = /* @__PURE__ */ new Map();
10320
+ function applyIdleReset(agentId, minutes) {
10321
+ const now = Date.now();
10322
+ const previous = lastSendAt.get(agentId);
10323
+ lastSendAt.set(agentId, now);
10324
+ if (minutes === void 0 || !Number.isFinite(minutes) || minutes <= 0) return;
10325
+ if (previous !== void 0 && now - previous > minutes * 6e4) chunkFBIDOOJM_cjs.clearSession(agentId);
10326
+ }
10144
10327
  async function executeSendLocked(inputs, message, options) {
10145
10328
  if (inputs.disposed) throw new chunkCEGU5AVD_cjs.AgentDisposedError(inputs.agentId);
10146
10329
  await consumePending(
@@ -10155,10 +10338,11 @@ async function executeSendLocked(inputs, message, options) {
10155
10338
  const gated = await applyInputProcessors(inputs, message, rawUserText, options, sendModel);
10156
10339
  if ("tripwireRun" in gated) return gated.tripwireRun;
10157
10340
  const { userText, effectiveMessage } = gated;
10341
+ applyIdleReset(inputs.agentId, inputs.options.sessionIdleResetMinutes);
10158
10342
  if (inputs.options.onBeforeSend !== void 0) {
10159
10343
  await inputs.options.onBeforeSend({
10160
10344
  conversationId: inputs.agentId,
10161
- previousMessageCount: chunkLXG6VL6R_cjs.getSessionMessages(inputs.agentId).length
10345
+ previousMessageCount: chunkFBIDOOJM_cjs.getSessionMessages(inputs.agentId).length
10162
10346
  });
10163
10347
  }
10164
10348
  await inputs.runPreHook(userText);
@@ -10170,8 +10354,8 @@ async function executeSendLocked(inputs, message, options) {
10170
10354
  userText,
10171
10355
  sendOptions: options
10172
10356
  });
10173
- const priorMessages = [...chunkLXG6VL6R_cjs.getSessionMessages(inputs.agentId)];
10174
- chunkLXG6VL6R_cjs.appendSessionMessage(inputs.agentId, { role: "user", text: userText });
10357
+ const priorMessages = [...chunkFBIDOOJM_cjs.getSessionMessages(inputs.agentId)];
10358
+ chunkFBIDOOJM_cjs.appendSessionMessage(inputs.agentId, { role: "user", text: userText });
10175
10359
  await persistMemoryFactIfWritePrompt(inputs.workspaceCwd, inputs.options.memory, userText);
10176
10360
  const memoryFacts = await readMemoryForSend(inputs.workspaceCwd, inputs.options.memory, userText);
10177
10361
  const memoryTools = void 0;
@@ -10340,6 +10524,43 @@ function reportUnknownLocalOptions(local) {
10340
10524
  }
10341
10525
  }
10342
10526
 
10527
+ // src/internal/local-agent/send-queue.ts
10528
+ var TurnSteerQueue = class {
10529
+ pending = [];
10530
+ closed = false;
10531
+ /** @returns false when the turn can no longer pick the message up. */
10532
+ push(text) {
10533
+ if (this.closed) return false;
10534
+ this.pending.push(text);
10535
+ return true;
10536
+ }
10537
+ drain() {
10538
+ const taken = this.pending;
10539
+ this.pending = [];
10540
+ return taken;
10541
+ }
10542
+ drainOrClose() {
10543
+ const taken = this.drain();
10544
+ if (taken.length === 0) this.closed = true;
10545
+ return taken;
10546
+ }
10547
+ /** Stop accepting and hand back what no loop iteration picked up. */
10548
+ closeAndTake() {
10549
+ this.closed = true;
10550
+ return this.drain();
10551
+ }
10552
+ };
10553
+ function joinCollected(messages) {
10554
+ if (messages.length === 1) return messages[0];
10555
+ const texts = messages.map((m) => typeof m === "string" ? m : m.text);
10556
+ const images = messages.flatMap((m) => typeof m === "string" ? [] : m.images ?? []);
10557
+ const text = texts.join("\n\n");
10558
+ return images.length > 0 ? { text, images } : text;
10559
+ }
10560
+ function hasImages(message) {
10561
+ return typeof message !== "string" && (message.images?.length ?? 0) > 0;
10562
+ }
10563
+
10343
10564
  // src/internal/local-agent/local-agent.ts
10344
10565
  var LocalAgent = class {
10345
10566
  /**
@@ -10388,6 +10609,9 @@ var LocalAgent = class {
10388
10609
  settingSourcesIncludePlugins;
10389
10610
  resolvedSubagents = {};
10390
10611
  disposed = false;
10612
+ activeTurn;
10613
+ inflight = 0;
10614
+ collectBatch;
10391
10615
  invalidationPending;
10392
10616
  skillsManager;
10393
10617
  pluginsManager;
@@ -10424,7 +10648,7 @@ var LocalAgent = class {
10424
10648
  this.options = options;
10425
10649
  this.workspaceCwd = resolveCwd(options.local?.cwd);
10426
10650
  this.transcriptBaseDir = resolveSessionDir(options.local);
10427
- this.sessionStore = options.local?.sessionStore ?? new chunk6OCJWGVD_cjs.FsSessionStore({ baseDir: this.transcriptBaseDir, cwd: this.workspaceCwd });
10651
+ this.sessionStore = options.local?.sessionStore ?? new chunkFTXY4D44_cjs.FsSessionStore({ baseDir: this.transcriptBaseDir, cwd: this.workspaceCwd });
10428
10652
  this.settingSourcesIncludeProject = includesSetting(options, "project");
10429
10653
  this.settingSourcesIncludePlugins = includesSetting(options, "plugins");
10430
10654
  const sub = bootstrapSubmanagers({
@@ -10476,7 +10700,7 @@ var LocalAgent = class {
10476
10700
  const codePlugins = chunkBV2MWEMV_cjs.extractCodePlugins(this.options.plugins);
10477
10701
  const manifestPlugins = await this.importManifestPlugins();
10478
10702
  await this.pluginManagerCode.initialize([...codePlugins, ...manifestPlugins]);
10479
- this.resolvedSubagents = await chunkWDVG5R2Q_cjs.loadSubagents(
10703
+ this.resolvedSubagents = await chunkAUH2EVWY_cjs.loadSubagents(
10480
10704
  this.workspaceCwd,
10481
10705
  this.settingSourcesIncludeProject,
10482
10706
  this.options.agents,
@@ -10484,7 +10708,7 @@ var LocalAgent = class {
10484
10708
  );
10485
10709
  await acquireLeaseIfPossible(this.sessionStore, this.agentId);
10486
10710
  try {
10487
- await chunkLXG6VL6R_cjs.hydrateSession(this.agentId, { store: this.sessionStore, cwd: this.workspaceCwd });
10711
+ await chunkFBIDOOJM_cjs.hydrateSession(this.agentId, { store: this.sessionStore, cwd: this.workspaceCwd });
10488
10712
  await this.personalityStore.hydrate(this.agentId);
10489
10713
  } catch (err) {
10490
10714
  await releaseLeaseIfPossible(this.sessionStore, this.agentId);
@@ -10512,10 +10736,48 @@ var LocalAgent = class {
10512
10736
  agentId: this.agentId,
10513
10737
  ...this.model?.id !== void 0 ? { model: this.model.id } : {}
10514
10738
  });
10739
+ return this.enqueueSend(message, options, sendSpan);
10740
+ }
10741
+ /** Queue one send behind the lock, or fold it into the running turn / pending batch. */
10742
+ enqueueSend(message, options, sendSpan) {
10743
+ const mode = options.queueMode ?? "followup";
10744
+ const text = typeof message === "string" ? message : message.text;
10745
+ const active = this.activeTurn;
10746
+ if (mode === "steer" && active !== void 0 && !hasImages(message) && active.steer.push(text)) {
10747
+ sendSpan.end();
10748
+ return active.run;
10749
+ }
10750
+ if (mode === "collect" && this.collectBatch !== void 0) {
10751
+ this.collectBatch.messages.push(message);
10752
+ sendSpan.end();
10753
+ return this.collectBatch.run;
10754
+ }
10755
+ const key = `agent-send:${this.agentId}`;
10756
+ this.inflight += 1;
10757
+ const release = () => {
10758
+ this.inflight -= 1;
10759
+ };
10760
+ if (mode === "collect" && this.inflight > 1) {
10761
+ const messages = [message];
10762
+ const run = new Promise((resolve, reject) => {
10763
+ void chunkU3DW3WDE_cjs.withCwdMutex(key, () => {
10764
+ this.collectBatch = void 0;
10765
+ return this.runLockedSendCycle(
10766
+ joinCollected(messages),
10767
+ options,
10768
+ sendSpan,
10769
+ resolve,
10770
+ reject
10771
+ ).finally(release);
10772
+ });
10773
+ });
10774
+ this.collectBatch = { messages, run };
10775
+ return run;
10776
+ }
10515
10777
  return new Promise((resolve, reject) => {
10516
- void chunkZF2LDKQQ_cjs.withCwdMutex(
10517
- `agent-send:${this.agentId}`,
10518
- () => this.runLockedSendCycle(message, options, sendSpan, resolve, reject)
10778
+ void chunkU3DW3WDE_cjs.withCwdMutex(
10779
+ key,
10780
+ () => this.runLockedSendCycle(message, options, sendSpan, resolve, reject).finally(release)
10519
10781
  );
10520
10782
  });
10521
10783
  }
@@ -10531,20 +10793,40 @@ var LocalAgent = class {
10531
10793
  const declared = this.model?.contextWindow;
10532
10794
  return declared !== void 0 ? { contextWindow: declared } : {};
10533
10795
  }
10796
+ /** A steered message the loop never picked up (run errored, was cancelled) still gets answered. */
10797
+ followUpUnsteered(leftover) {
10798
+ if (leftover.length === 0) return;
10799
+ this.send(leftover.join("\n\n")).catch(
10800
+ (err) => chunkRNXXYF22_cjs.diagFailure(`[theokit-sdk] steered message followup failed: ${String(err)}`)
10801
+ );
10802
+ }
10534
10803
  async runLockedSendCycle(message, options, sendSpan, resolve, reject) {
10535
10804
  const userText = typeof message === "string" ? message : message.text;
10536
10805
  let run;
10806
+ const steer = new TurnSteerQueue();
10807
+ let res = () => void 0;
10808
+ let rej = () => void 0;
10809
+ const turnRun = new Promise((a, b) => {
10810
+ res = a;
10811
+ rej = b;
10812
+ });
10813
+ turnRun.catch(() => void 0);
10814
+ this.activeTurn = { steer, run: turnRun };
10537
10815
  try {
10538
10816
  run = await this.sendLocked(message, options);
10539
10817
  } catch (err) {
10540
10818
  sendSpan.recordException(err);
10541
10819
  sendSpan.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
10542
10820
  sendSpan.end();
10821
+ this.activeTurn = void 0;
10822
+ rej(err);
10543
10823
  reject(err);
10544
10824
  return;
10545
10825
  }
10546
10826
  if (options.task !== void 0) registerRunAsTask(run, this.agentId, options.task, userText);
10547
- resolve(callerView(run, this.options.throwOnError));
10827
+ const view = callerView(run, this.options.throwOnError);
10828
+ res(view);
10829
+ resolve(view);
10548
10830
  try {
10549
10831
  await runPostRunLifecycle({
10550
10832
  run,
@@ -10568,6 +10850,8 @@ var LocalAgent = class {
10568
10850
  });
10569
10851
  } finally {
10570
10852
  sendSpan.end();
10853
+ this.activeTurn = void 0;
10854
+ this.followUpUnsteered(steer.closeAndTake());
10571
10855
  }
10572
10856
  }
10573
10857
  async sendLocked(message, options) {
@@ -10675,11 +10959,13 @@ var LocalAgent = class {
10675
10959
  memoryFacts,
10676
10960
  priorMessages,
10677
10961
  memoryTools,
10678
- activePreset: this.activePreset()
10962
+ activePreset: this.activePreset(),
10963
+ ...this.activeTurn !== void 0 ? { steerQueue: this.activeTurn.steer } : {}
10679
10964
  });
10680
10965
  }
10681
10966
  close() {
10682
10967
  this.disposed = true;
10968
+ liveAgentRegistry.forget(this.agentId);
10683
10969
  }
10684
10970
  async reload() {
10685
10971
  this.resolvedSubagents = await reloadLocalAgent(this);
@@ -10828,22 +11114,22 @@ async function maybeInjectHandoffTools(options) {
10828
11114
  };
10829
11115
  }
10830
11116
  function keyWillFlowToProvider(apiKey, provider) {
10831
- if (chunkSNVYOX46_cjs.isFixtureApiKey(apiKey)) return false;
10832
- if (chunkSNVYOX46_cjs.getConfiguredBaseUrl() !== void 0) return false;
11117
+ if (chunk3E3VSMB6_cjs.isFixtureApiKey(apiKey)) return false;
11118
+ if (chunk3E3VSMB6_cjs.getConfiguredBaseUrl() !== void 0) return false;
10833
11119
  if (provider === void 0) return false;
10834
- const profile = chunkR5UQL2R5_cjs.getProviderProfile(provider);
11120
+ const profile = chunkSPEN7RJU_cjs.getProviderProfile(provider);
10835
11121
  if (profile === void 0) return false;
10836
11122
  return profile.authType !== "none";
10837
11123
  }
10838
11124
  function missingApiKeyMessage() {
10839
- const present = chunkSNVYOX46_cjs.presentProviderCredentialEnvVars();
11125
+ const present = chunk3E3VSMB6_cjs.presentProviderCredentialEnvVars();
10840
11126
  const base = `Missing API key \u2014 set ${chunkRNXXYF22_cjs.API_KEY_ENV_VAR}, or pass \`apiKey\` to Agent.create()`;
10841
11127
  if (present.length === 0) return `${base}.`;
10842
11128
  return `${base}. ${present.join(" and ")} ${present.length === 1 ? "is" : "are"} set, but a provider credential is not read from the environment automatically \u2014 pass it explicitly, e.g. \`Agent.create({ apiKey: process.env.${present[0]}, ... })\`.`;
10843
11129
  }
10844
11130
  function providerNeedsCallerKey(provider) {
10845
11131
  if (provider === void 0) return true;
10846
- const profile = chunkR5UQL2R5_cjs.getProviderProfile(provider);
11132
+ const profile = chunkSPEN7RJU_cjs.getProviderProfile(provider);
10847
11133
  if (profile === void 0) return true;
10848
11134
  return profile.authType === "api_key";
10849
11135
  }
@@ -10856,7 +11142,7 @@ async function createLocalAgent(options) {
10856
11142
  }
10857
11143
  } else {
10858
11144
  const willFlowToProvider = keyWillFlowToProvider(apiKey, provider);
10859
- const shape = chunkSNVYOX46_cjs.validateApiKeyShape(apiKey, {
11145
+ const shape = chunk3E3VSMB6_cjs.validateApiKeyShape(apiKey, {
10860
11146
  strict: willFlowToProvider,
10861
11147
  ...willFlowToProvider ? { provider } : {}
10862
11148
  });
@@ -10875,15 +11161,15 @@ async function createCloudAgent(options) {
10875
11161
  code: "missing_api_key"
10876
11162
  });
10877
11163
  }
10878
- const shape = chunkSNVYOX46_cjs.validateApiKeyShape(apiKey);
11164
+ const shape = chunk3E3VSMB6_cjs.validateApiKeyShape(apiKey);
10879
11165
  if (shape.malformed) {
10880
11166
  throw new chunkCEGU5AVD_cjs.AuthenticationError(shape.message, { code: "malformed_api_key" });
10881
11167
  }
10882
- const baseUrl = chunkSNVYOX46_cjs.getConfiguredBaseUrl();
11168
+ const baseUrl = chunk3E3VSMB6_cjs.getConfiguredBaseUrl();
10883
11169
  if (baseUrl === void 0) {
10884
11170
  return new CloudAgent(options);
10885
11171
  }
10886
- const response = await chunkSNVYOX46_cjs.httpRequest("/v1/agents", {
11172
+ const response = await chunk3E3VSMB6_cjs.httpRequest("/v1/agents", {
10887
11173
  apiKey,
10888
11174
  method: "POST",
10889
11175
  body: {
@@ -10908,7 +11194,7 @@ function resolveAgentPersistenceCwd(options) {
10908
11194
  return process.cwd();
10909
11195
  }
10910
11196
  async function rehydrateExistingAgent(agentId, existing, options) {
10911
- await chunkSNVYOX46_cjs.discoverProviderPlugins();
11197
+ await chunk3E3VSMB6_cjs.discoverProviderPlugins();
10912
11198
  await validateRehydratedAgent(agentId, existing);
10913
11199
  const mergedLocal = options.local !== void 0 && existing.options.local !== void 0 ? { ...existing.options.local, ...options.local } : options.local ?? existing.options.local;
10914
11200
  const mergedMemory = mergeResumedMemory(existing.options.memory, options.memory);
@@ -10924,7 +11210,7 @@ async function rehydrateExistingAgent(agentId, existing, options) {
10924
11210
  mcpServers: void 0,
10925
11211
  agentId
10926
11212
  };
10927
- chunkSDZ4XDWS_cjs.resolveMaxFacts(mergedOptions.memory?.maxFacts);
11213
+ chunkVWYFGE27_cjs.resolveMaxFacts(mergedOptions.memory?.maxFacts);
10928
11214
  if (existing.runtime === "cloud") {
10929
11215
  return new CloudAgent(mergedOptions, agentId);
10930
11216
  }
@@ -11030,6 +11316,7 @@ function paginateByKey(all, keyOf, limit, cursor, sortByKey) {
11030
11316
 
11031
11317
  // src/agent.ts
11032
11318
  var streamObjectImport;
11319
+ var getOrCreateInFlight = /* @__PURE__ */ new Map();
11033
11320
  var Agent = class _Agent {
11034
11321
  constructor() {
11035
11322
  }
@@ -11068,7 +11355,7 @@ var Agent = class _Agent {
11068
11355
  pluginCount: enabledPluginNames(options.plugins).length
11069
11356
  });
11070
11357
  try {
11071
- await chunkSNVYOX46_cjs.discoverProviderPlugins();
11358
+ await chunk3E3VSMB6_cjs.discoverProviderPlugins();
11072
11359
  const agent = await runCreateUnderSpan(options, span);
11073
11360
  return agent;
11074
11361
  } catch (err) {
@@ -11214,7 +11501,7 @@ var Agent = class _Agent {
11214
11501
  * @public
11215
11502
  */
11216
11503
  static async batch(prompts, options) {
11217
- const { batchImpl } = await import('./batch-IZ5EDKJ5.cjs');
11504
+ const { batchImpl } = await import('./batch-VFR2MAUE.cjs');
11218
11505
  return batchImpl(prompts, options, { create: (opts) => _Agent.create(opts) });
11219
11506
  }
11220
11507
  /**
@@ -11244,18 +11531,27 @@ var Agent = class _Agent {
11244
11531
  * The agent-builder's M85 interrupt rotates the session id to work around a
11245
11532
  * constraint that does not exist.
11246
11533
  *
11247
- * - `close()` marks the handle disposed WITHOUT evicting the cache entry. It is
11248
- * internal and unused today; if it becomes reachable, this bullet stops being true
11249
- * for that path.
11534
+ * - `close()` marks the handle disposed AND drops its cache entry, so the next call
11535
+ * builds a fresh handle.
11250
11536
  *
11251
11537
  * @public
11252
11538
  */
11253
11539
  static async getOrCreate(agentId, options) {
11254
11540
  const cached = _Agent.registry.get(agentId);
11255
11541
  if (cached !== void 0) return cached;
11256
- const fresh = await getOrCreateUncached(agentId, options);
11257
- _Agent.registry.set(agentId, fresh);
11258
- return fresh;
11542
+ const inFlight = getOrCreateInFlight.get(agentId);
11543
+ if (inFlight !== void 0) return inFlight;
11544
+ const build = (async () => {
11545
+ const fresh = await getOrCreateUncached(agentId, options);
11546
+ _Agent.registry.set(agentId, fresh);
11547
+ return fresh;
11548
+ })();
11549
+ getOrCreateInFlight.set(agentId, build);
11550
+ try {
11551
+ return await build;
11552
+ } finally {
11553
+ if (getOrCreateInFlight.get(agentId) === build) getOrCreateInFlight.delete(agentId);
11554
+ }
11259
11555
  }
11260
11556
  /**
11261
11557
  * List agents (local or cloud). M107 — `cwd` is READ, not ignored. B-115 (2026-08-19) —
@@ -11366,9 +11662,9 @@ var Agent = class _Agent {
11366
11662
  */
11367
11663
  static async compact(agentId, options = {}) {
11368
11664
  const reg = await requireLocalAgent(agentId, "compact");
11369
- const { compactSessionTranscript, buildDefaultSummarizer: buildDefaultSummarizer2 } = await import('./compact-session-D2MQDB6G.cjs');
11665
+ const { compactSessionTranscript, buildDefaultSummarizer: buildDefaultSummarizer2 } = await import('./compact-session-CHBJOYWP.cjs');
11370
11666
  const { cwd, model, store } = await openLocalStore(reg);
11371
- return chunkLXG6VL6R_cjs.enqueueSessionWrite(
11667
+ return chunkFBIDOOJM_cjs.enqueueSessionWrite(
11372
11668
  cwd,
11373
11669
  agentId,
11374
11670
  () => compactSessionTranscript({
@@ -11396,7 +11692,7 @@ var Agent = class _Agent {
11396
11692
  */
11397
11693
  static async injectSessionTurn(agentId, turn) {
11398
11694
  const reg = await requireLocalAgent(agentId, "injectSessionTurn");
11399
- const { injectSessionTurn } = await import('./inject-session-3ICZIJ2N.cjs');
11695
+ const { injectSessionTurn } = await import('./inject-session-T4RXANG3.cjs');
11400
11696
  const { cwd, model, store } = await openLocalStore(reg);
11401
11697
  await injectSessionTurn({
11402
11698
  store,
@@ -11447,7 +11743,7 @@ var Agent = class _Agent {
11447
11743
  */
11448
11744
  static async describe(agentId) {
11449
11745
  const agent = await getRegisteredAgentOrThrow(agentId);
11450
- const { loadSubagents: loadSubagents2 } = await import('./subagents-loader-TXOA5EJJ.cjs');
11746
+ const { loadSubagents: loadSubagents2 } = await import('./subagents-loader-KLWF4QPD.cjs');
11451
11747
  const settingSources = agent.options.local?.settingSources;
11452
11748
  const subagents = await loadSubagents2(
11453
11749
  agent.cwd ?? process.cwd(),
@@ -11546,7 +11842,9 @@ async function openLocalStore(reg) {
11546
11842
  const cwd = reg.cwd ?? process.cwd();
11547
11843
  const optModel = reg.options.model;
11548
11844
  const model = reg.model?.id ?? (typeof optModel === "string" ? optModel : optModel?.id) ?? "unknown";
11549
- const { FsSessionStore: FsSessionStore2 } = await import('./fs-session-store-S2AXVJIX.cjs');
11845
+ const injected = reg.options.local?.sessionStore;
11846
+ if (injected !== void 0) return { cwd, model, store: injected };
11847
+ const { FsSessionStore: FsSessionStore2 } = await import('./fs-session-store-CYNTEPJZ.cjs');
11550
11848
  const { defaultBaseDir: defaultBaseDir2, expandTilde: expandTilde2 } = await import('./session-transcript-7TZ6HXSX.cjs');
11551
11849
  const configuredSessionDir = reg.options.local?.sessionDir ?? reg.options.local?.baseDir;
11552
11850
  const baseDir = configuredSessionDir !== void 0 ? expandTilde2(configuredSessionDir) : defaultBaseDir2();
@@ -11567,5 +11865,5 @@ exports.managedSettingsPathFor = managedSettingsPathFor;
11567
11865
  exports.openRouterMemoryEmbeddingProviderAdapter = openRouterMemoryEmbeddingProviderAdapter;
11568
11866
  exports.readManagedSettings = readManagedSettings;
11569
11867
  exports.resolveSessionDir = resolveSessionDir;
11570
- //# sourceMappingURL=chunk-2WY2OFSC.cjs.map
11571
- //# sourceMappingURL=chunk-2WY2OFSC.cjs.map
11868
+ //# sourceMappingURL=chunk-26UQG242.cjs.map
11869
+ //# sourceMappingURL=chunk-26UQG242.cjs.map