@leuduan/lagent 0.1.2 → 44.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (353) hide show
  1. package/README.md +28 -15
  2. package/dist/chunks/{UC3FVVJ2.js → 2GCIWSOA.js} +2 -2
  3. package/dist/chunks/2P47AHNK.js +7 -0
  4. package/dist/chunks/3UMZMPWW.js +1 -0
  5. package/dist/chunks/5IRF47YB.js +1 -0
  6. package/dist/chunks/6DRCKZ2C.js +1 -0
  7. package/dist/chunks/6FRNHMCV.js +1 -0
  8. package/dist/chunks/7LI64H5X.js +17 -0
  9. package/dist/chunks/{SL2YLB2F.js → 7VAPNE3L.js} +1 -1
  10. package/dist/chunks/{BM3S37EZ.js → ASSQZH3F.js} +1 -1
  11. package/dist/chunks/B4FXK5ER.js +77 -0
  12. package/dist/chunks/{37YOGDGY.js → BBCW2FZK.js} +1 -1
  13. package/dist/chunks/BPRCULZH.js +1 -0
  14. package/dist/chunks/CANPZYTH.js +24 -0
  15. package/dist/chunks/CQEVREBT.js +1 -0
  16. package/dist/chunks/CUK7CGC7.js +1 -0
  17. package/dist/chunks/D4PQP5MA.js +3 -0
  18. package/dist/chunks/{CDQG7RKA.js → DDZ7YF26.js} +1 -1
  19. package/dist/chunks/EMRB4KCN.js +6 -0
  20. package/dist/chunks/EPYQ5M3B.js +3 -0
  21. package/dist/chunks/G44LG6VL.js +1 -0
  22. package/dist/chunks/GGSVIIWJ.js +2 -0
  23. package/dist/chunks/IAAEP6VL.js +30 -0
  24. package/dist/chunks/{AP6Q4EPT.js → JCTBX33H.js} +1 -1
  25. package/dist/chunks/JFX2MXBA.js +4 -0
  26. package/dist/chunks/JFZZXVWD.js +15 -0
  27. package/dist/chunks/KUZCL2SH.js +1 -0
  28. package/dist/chunks/MHC6VPB4.js +7 -0
  29. package/dist/chunks/MMNNZCBO.js +5 -0
  30. package/dist/chunks/{C5LYCXJG.js → MNJ4SRF7.js} +1 -1
  31. package/dist/chunks/N6IXG2VL.js +1 -0
  32. package/dist/chunks/OCBPT7KE.js +1 -0
  33. package/dist/chunks/OL5A6ITQ.js +1 -0
  34. package/dist/chunks/Q75FUN7D.js +2 -0
  35. package/dist/chunks/Q7S5LFGN.js +1 -0
  36. package/dist/chunks/RCIHV3KG.js +1 -0
  37. package/dist/chunks/S34ZA2R6.js +1 -0
  38. package/dist/chunks/SS3B5W34.js +12 -0
  39. package/dist/chunks/VYMT4TXD.js +1 -0
  40. package/dist/chunks/W57RW55W.js +1 -0
  41. package/dist/compositions/base.d.ts +11 -0
  42. package/dist/{presets → compositions}/codex.d.ts +12 -6
  43. package/dist/{presets/prompts.d.ts → compositions/codexPrompts.d.ts} +1 -1
  44. package/dist/context.d.ts +18 -10
  45. package/dist/index.d.ts +31 -23
  46. package/dist/index.js +1 -77
  47. package/dist/journal/catalog.d.ts +1 -1
  48. package/dist/journal/journal.d.ts +3 -3
  49. package/dist/journal/projection.d.ts +1 -1
  50. package/dist/journal/store.d.ts +3 -3
  51. package/dist/llm/index.d.ts +19 -13
  52. package/dist/llm/index.js +1 -0
  53. package/dist/llm/provider.d.ts +11 -0
  54. package/dist/loop/agent.d.ts +16 -132
  55. package/dist/loop/authorization.d.ts +41 -0
  56. package/dist/loop/auxiliary.d.ts +7 -3
  57. package/dist/loop/chunks.d.ts +3 -3
  58. package/dist/loop/completion.d.ts +17 -0
  59. package/dist/loop/errors.d.ts +6 -29
  60. package/dist/loop/hooks.d.ts +39 -6
  61. package/dist/loop/index.d.ts +7 -28
  62. package/dist/loop/runner.d.ts +134 -0
  63. package/dist/loop/runtime.d.ts +7 -16
  64. package/dist/loop/strategy.d.ts +12 -3
  65. package/dist/loop/{prepare.d.ts → surfacePrepare.d.ts} +2 -2
  66. package/dist/loop/tool.d.ts +11 -6
  67. package/dist/loop/toolCalls.d.ts +3 -10
  68. package/dist/plugin.d.ts +31 -34
  69. package/dist/plugin.js +1 -1
  70. package/dist/plugins/agentsMd.d.ts +24 -20
  71. package/dist/plugins/agentsMd.js +1 -1
  72. package/dist/plugins/ask/index.d.ts +2 -2
  73. package/dist/plugins/ask/index.js +1 -1
  74. package/dist/plugins/ask/service.d.ts +2 -2
  75. package/dist/plugins/commands/index.d.ts +5 -2
  76. package/dist/plugins/commands/index.js +1 -1
  77. package/dist/plugins/commands/output.d.ts +1 -1
  78. package/dist/plugins/commands/record.d.ts +31 -22
  79. package/dist/plugins/commands/service.d.ts +18 -11
  80. package/dist/plugins/commands/{background.d.ts → tools.d.ts} +2 -0
  81. package/dist/plugins/compaction/checkpoint.d.ts +4 -1
  82. package/dist/plugins/compaction/config.d.ts +3 -3
  83. package/dist/plugins/compaction/estimate.d.ts +9 -1
  84. package/dist/plugins/compaction/index.d.ts +87 -2
  85. package/dist/plugins/compaction/index.js +5 -5
  86. package/dist/plugins/compaction/{records.d.ts → record.d.ts} +36 -36
  87. package/dist/plugins/compaction/{log.d.ts → state.d.ts} +8 -1
  88. package/dist/plugins/dateAndBranch.js +1 -1
  89. package/dist/plugins/delegations/answers.d.ts +1 -1
  90. package/dist/plugins/delegations/assignmentKey.d.ts +1 -1
  91. package/dist/plugins/delegations/cleanup.d.ts +1 -1
  92. package/dist/plugins/delegations/index.js +1 -1
  93. package/dist/plugins/delegations/notices.d.ts +8 -8
  94. package/dist/plugins/delegations/obligations.d.ts +13 -13
  95. package/dist/plugins/delegations/record.d.ts +11 -10
  96. package/dist/plugins/delegations/request.d.ts +8 -5
  97. package/dist/plugins/delegations/role.d.ts +1 -1
  98. package/dist/plugins/delegations/service.d.ts +9 -8
  99. package/dist/plugins/delegations/{waitBook.d.ts → waitResolver.d.ts} +9 -9
  100. package/dist/plugins/diagnostics/digest.d.ts +1 -1
  101. package/dist/plugins/diagnostics/index.d.ts +1 -1
  102. package/dist/plugins/diagnostics/index.js +1 -1
  103. package/dist/plugins/fileTools/config.d.ts +10 -0
  104. package/dist/plugins/{tools → fileTools}/editFiles.d.ts +16 -27
  105. package/dist/plugins/fileTools/gitDiscovery.d.ts +9 -0
  106. package/dist/plugins/fileTools/index.d.ts +18 -0
  107. package/dist/plugins/fileTools/index.js +1 -0
  108. package/dist/plugins/fileTools/tools.d.ts +6 -0
  109. package/dist/plugins/historyRecall/history.d.ts +1 -1
  110. package/dist/plugins/historyRecall/index.js +1 -1
  111. package/dist/plugins/historyRecall/render.d.ts +1 -1
  112. package/dist/plugins/mcp/catalog.d.ts +1 -1
  113. package/dist/plugins/mcp/index.d.ts +2 -2
  114. package/dist/plugins/mcp/index.js +1 -1
  115. package/dist/plugins/mcp/mount.d.ts +2 -2
  116. package/dist/plugins/mcp/render.d.ts +1 -1
  117. package/dist/plugins/mcp/{tool.d.ts → tools.d.ts} +1 -1
  118. package/dist/plugins/{routeContext.d.ts → routeNotice.d.ts} +2 -2
  119. package/dist/plugins/routeNotice.js +1 -0
  120. package/dist/{sandbox → plugins/sandbox}/absent.d.ts +11 -10
  121. package/dist/{sandbox → plugins/sandbox}/index.d.ts +5 -2
  122. package/dist/plugins/sandbox/index.js +4 -0
  123. package/dist/{sandbox → plugins/sandbox}/mode.d.ts +5 -5
  124. package/dist/plugins/sandbox/policy.d.ts +163 -0
  125. package/dist/{sandbox → plugins/sandbox}/service.d.ts +23 -13
  126. package/dist/plugins/schedules/index.js +3 -3
  127. package/dist/plugins/schedules/record.d.ts +18 -18
  128. package/dist/plugins/schedules/service.d.ts +2 -2
  129. package/dist/plugins/skills/discovery.d.ts +38 -9
  130. package/dist/plugins/skills/index.d.ts +1 -1
  131. package/dist/plugins/skills/index.js +1 -1
  132. package/dist/plugins/subAgents/index.js +1 -1
  133. package/dist/plugins/subAgents/{fork.d.ts → tools.d.ts} +36 -1
  134. package/dist/plugins/threadDirs.d.ts +36 -0
  135. package/dist/plugins/threadDirs.js +1 -0
  136. package/dist/plugins/toolPolicy/index.d.ts +2 -2
  137. package/dist/plugins/toolPolicy/index.js +1 -1
  138. package/dist/plugins/truncateToolOutput.d.ts +14 -10
  139. package/dist/plugins/truncateToolOutput.js +6 -1
  140. package/dist/plugins/usage/index.d.ts +4 -2
  141. package/dist/plugins/usage/index.js +1 -1
  142. package/dist/plugins/usage/tracker.d.ts +1 -1
  143. package/dist/plugins/verify/index.d.ts +7 -55
  144. package/dist/plugins/verify/index.js +6 -1
  145. package/dist/plugins/verify/judgement.d.ts +16 -0
  146. package/dist/plugins/verify/record.d.ts +382 -0
  147. package/dist/plugins/verify/service.d.ts +7 -4
  148. package/dist/plugins/verify/state.d.ts +58 -0
  149. package/dist/plugins/webTools/index.d.ts +34 -0
  150. package/dist/plugins/webTools/index.js +1 -0
  151. package/dist/plugins/workflows/assignment.d.ts +6 -2
  152. package/dist/plugins/workflows/cleanup.d.ts +1 -1
  153. package/dist/plugins/workflows/definition.d.ts +2 -2
  154. package/dist/plugins/workflows/{bindings.d.ts → entryPlan.d.ts} +2 -2
  155. package/dist/plugins/workflows/{providers.d.ts → hostBindings.d.ts} +2 -2
  156. package/dist/plugins/workflows/index.d.ts +4 -4
  157. package/dist/plugins/workflows/index.js +10 -5
  158. package/dist/plugins/workflows/observations.d.ts +3 -3
  159. package/dist/plugins/workflows/participantModels.d.ts +28 -0
  160. package/dist/plugins/workflows/participants.d.ts +2 -2
  161. package/dist/plugins/workflows/policy.d.ts +2 -2
  162. package/dist/plugins/workflows/record.d.ts +51 -65
  163. package/dist/plugins/workflows/routing.d.ts +2 -2
  164. package/dist/plugins/workflows/service.d.ts +24 -24
  165. package/dist/plugins/workflows/{fold.d.ts → state.d.ts} +2 -2
  166. package/dist/plugins/workflows/stopCheck.d.ts +13 -0
  167. package/dist/plugins/workflows/tools.d.ts +13 -0
  168. package/dist/plugins/workflows/view.d.ts +2 -2
  169. package/dist/plugins/{workspaceContext.d.ts → workspaceNotice.d.ts} +5 -7
  170. package/dist/plugins/workspaceNotice.js +1 -0
  171. package/dist/{plugins/providers → providers}/anthropic.d.ts +6 -3
  172. package/dist/{plugins/providers → providers}/anthropicMessages.d.ts +2 -1
  173. package/dist/{plugins/providers → providers}/codex.d.ts +14 -3
  174. package/dist/{plugins/providers → providers}/deepseek.d.ts +6 -2
  175. package/dist/{plugins/providers → providers}/failure.d.ts +1 -1
  176. package/dist/{plugins/providers → providers}/gateway.d.ts +2 -1
  177. package/dist/providers/index.d.ts +18 -0
  178. package/dist/providers/index.js +6 -0
  179. package/dist/{plugins/providers → providers}/openaiChat.d.ts +13 -2
  180. package/dist/{plugins/providers → providers}/openaiResponses.d.ts +12 -3
  181. package/dist/{plugins/providers → providers}/opencodeCopilot.d.ts +2 -2
  182. package/dist/{plugins/providers → providers}/opencodeGo.d.ts +18 -7
  183. package/dist/{plugins/providers → providers}/shared.d.ts +9 -1
  184. package/dist/{plugins/providers → providers}/stream.d.ts +4 -2
  185. package/dist/{models/door.d.ts → records/index.d.ts} +8 -7
  186. package/dist/records/index.js +1 -0
  187. package/dist/{models/wire → records}/journal.d.ts +210 -14
  188. package/dist/{models/wire/primitives.d.ts → records/toolResult.d.ts} +1 -1
  189. package/dist/services/agents.d.ts +26 -1
  190. package/dist/services/confinement/files.d.ts +118 -0
  191. package/dist/services/confinement/service.d.ts +219 -0
  192. package/dist/services/core.d.ts +2 -8
  193. package/dist/{kit/extension.d.ts → services/extensionEvents.d.ts} +5 -4
  194. package/dist/services/journal.d.ts +1 -1
  195. package/dist/services/llm.d.ts +4 -2
  196. package/dist/{kit → services}/modes.d.ts +1 -1
  197. package/dist/services/plugins.d.ts +34 -0
  198. package/dist/services/{preset.d.ts → presets/definition.d.ts} +4 -4
  199. package/dist/services/{presets.d.ts → presets/installations.d.ts} +3 -3
  200. package/dist/services/prompts.d.ts +23 -5
  201. package/dist/services/{threadActivation.d.ts → threads/activation.d.ts} +3 -3
  202. package/dist/services/{admission.d.ts → threads/admission.d.ts} +3 -3
  203. package/dist/services/{birth.d.ts → threads/birth.d.ts} +9 -10
  204. package/dist/services/threads/index.d.ts +14 -0
  205. package/dist/services/{runEvents.d.ts → threads/runEvents.d.ts} +2 -2
  206. package/dist/services/{owner.d.ts → threads/runOwner.d.ts} +5 -4
  207. package/dist/services/{threads.d.ts → threads/service.d.ts} +9 -8
  208. package/dist/services/{thread.d.ts → threads/thread.d.ts} +8 -7
  209. package/dist/services/{threadView.d.ts → threads/view.d.ts} +7 -6
  210. package/dist/services/tools.d.ts +79 -2
  211. package/dist/{loop/opening.d.ts → state/birth.d.ts} +22 -2
  212. package/dist/{loop → state}/chain.d.ts +3 -3
  213. package/dist/state/confirmations.d.ts +64 -0
  214. package/dist/{loop → state}/continuation.d.ts +3 -2
  215. package/dist/{loop → state}/decide.d.ts +10 -2
  216. package/dist/state/dispatches.d.ts +54 -0
  217. package/dist/state/errors.d.ts +26 -0
  218. package/dist/{loop → state}/forks.d.ts +1 -1
  219. package/dist/{loop → state}/holds.d.ts +1 -1
  220. package/dist/{loop → state}/inbox.d.ts +2 -2
  221. package/dist/state/index.d.ts +31 -0
  222. package/dist/state/inputs.d.ts +58 -0
  223. package/dist/state/installations.d.ts +28 -0
  224. package/dist/state/prompt.d.ts +13 -0
  225. package/dist/state/recovery.d.ts +7 -0
  226. package/dist/{loop → state}/replace.d.ts +2 -2
  227. package/dist/{loop → state}/requests.d.ts +3 -3
  228. package/dist/{loop → state}/route.d.ts +10 -2
  229. package/dist/state/summary.d.ts +16 -0
  230. package/dist/{loop → state}/surface.d.ts +3 -3
  231. package/dist/state/surfaceRead.d.ts +20 -0
  232. package/dist/{loop/threadState.d.ts → state/thread.d.ts} +12 -11
  233. package/dist/state/turns.d.ts +87 -0
  234. package/dist/state/waits.d.ts +38 -0
  235. package/dist/{loop → state}/wake.d.ts +1 -1
  236. package/dist/stores/durableObject.js +1 -0
  237. package/dist/{plugins/store → stores}/memory.d.ts +2 -2
  238. package/dist/{plugins/store → stores}/sql.d.ts +2 -2
  239. package/dist/stores/sqlite.js +1 -0
  240. package/dist/sys/environment.d.ts +0 -5
  241. package/dist/sys/git.d.ts +0 -13
  242. package/dist/sys/paths.d.ts +0 -47
  243. package/dist/sys/spawn.d.ts +16 -6
  244. package/dist/testing/clock.d.ts +1 -1
  245. package/dist/testing/fakeLlm.d.ts +4 -2
  246. package/dist/testing/fedLlm.d.ts +3 -1
  247. package/dist/testing/helpers.d.ts +31 -13
  248. package/dist/testing/index.js +1 -1
  249. package/dist/testing/settlement.d.ts +1 -1
  250. package/package.json +36 -28
  251. package/dist/chunks/2O7ZGEIT.js +0 -1
  252. package/dist/chunks/2OSESBIL.js +0 -1
  253. package/dist/chunks/3LQHQRIU.js +0 -6
  254. package/dist/chunks/3QCW4WDJ.js +0 -1
  255. package/dist/chunks/4XVRUSCQ.js +0 -1
  256. package/dist/chunks/6ECI2GGV.js +0 -1
  257. package/dist/chunks/74HKUGRR.js +0 -1
  258. package/dist/chunks/ADHERZLW.js +0 -2
  259. package/dist/chunks/D7E6EWIE.js +0 -3
  260. package/dist/chunks/DRYAN665.js +0 -1
  261. package/dist/chunks/DXFXAYDN.js +0 -17
  262. package/dist/chunks/EGZI4XQX.js +0 -24
  263. package/dist/chunks/ENWFSU27.js +0 -41
  264. package/dist/chunks/G6RXC3AL.js +0 -1
  265. package/dist/chunks/G74AGRAJ.js +0 -15
  266. package/dist/chunks/GQGNVSKB.js +0 -1
  267. package/dist/chunks/IJ2WNMD5.js +0 -7
  268. package/dist/chunks/JPZFKSWT.js +0 -1
  269. package/dist/chunks/KESCTXGO.js +0 -5
  270. package/dist/chunks/L3N4FIEN.js +0 -1
  271. package/dist/chunks/NAOUTU7A.js +0 -4
  272. package/dist/chunks/NDIM7MEW.js +0 -1
  273. package/dist/chunks/O4PPOM5Z.js +0 -2
  274. package/dist/chunks/OVZFGILJ.js +0 -1
  275. package/dist/chunks/P5ZHHOOM.js +0 -6
  276. package/dist/chunks/QMMLQJBS.js +0 -1
  277. package/dist/chunks/RK3VP2Q4.js +0 -3
  278. package/dist/chunks/SGGMBSBA.js +0 -1
  279. package/dist/chunks/TOOIB6J2.js +0 -1
  280. package/dist/chunks/TYTQRLTX.js +0 -1
  281. package/dist/chunks/UCTEU62F.js +0 -1
  282. package/dist/chunks/UD3VJER6.js +0 -1
  283. package/dist/chunks/WUUKTSRT.js +0 -7
  284. package/dist/chunks/X65X4KP5.js +0 -7
  285. package/dist/chunks/YIR5MYGU.js +0 -1
  286. package/dist/chunks/YLNJXQ3Z.js +0 -1
  287. package/dist/kit/claim.d.ts +0 -13
  288. package/dist/kit/drain.d.ts +0 -10
  289. package/dist/kit/grants.d.ts +0 -9
  290. package/dist/kit/scope.d.ts +0 -32
  291. package/dist/kit/service.d.ts +0 -7
  292. package/dist/kit/strategy.d.ts +0 -10
  293. package/dist/kit/tool.d.ts +0 -72
  294. package/dist/llm/door.d.ts +0 -21
  295. package/dist/llm/door.js +0 -1
  296. package/dist/loop/projections.d.ts +0 -307
  297. package/dist/loop/state.d.ts +0 -70
  298. package/dist/loop/summary.d.ts +0 -3
  299. package/dist/models/config/agent.d.ts +0 -18
  300. package/dist/models/config/prompt.d.ts +0 -18
  301. package/dist/models/door.js +0 -1
  302. package/dist/models/index.d.ts +0 -7
  303. package/dist/plugins/commands/foreground.d.ts +0 -4
  304. package/dist/plugins/compaction/preset.d.ts +0 -86
  305. package/dist/plugins/compaction/shared.d.ts +0 -14
  306. package/dist/plugins/delegations/testing.d.ts +0 -16
  307. package/dist/plugins/providers/door.d.ts +0 -61
  308. package/dist/plugins/providers/door.js +0 -1
  309. package/dist/plugins/providers/index.d.ts +0 -6
  310. package/dist/plugins/routeContext.js +0 -1
  311. package/dist/plugins/store/durableObject.js +0 -1
  312. package/dist/plugins/store/sqlite.js +0 -1
  313. package/dist/plugins/subAgents/tool.d.ts +0 -38
  314. package/dist/plugins/tools/index.d.ts +0 -59
  315. package/dist/plugins/tools/index.js +0 -1
  316. package/dist/plugins/verify/facts.d.ts +0 -356
  317. package/dist/plugins/workflows/submit.d.ts +0 -8
  318. package/dist/plugins/workspaceContext.js +0 -1
  319. package/dist/presets/agents.d.ts +0 -7
  320. package/dist/presets/base.d.ts +0 -10
  321. package/dist/presets/index.d.ts +0 -4
  322. package/dist/sandbox/index.js +0 -4
  323. package/dist/sandbox/policy.d.ts +0 -86
  324. package/dist/services/launches.d.ts +0 -104
  325. package/dist/services/threadDirs.d.ts +0 -38
  326. package/dist/testing/sandbox.d.ts +0 -71
  327. /package/dist/chunks/{UKXMCHHT.js → FJLU4UH3.js} +0 -0
  328. /package/dist/chunks/{J5S4URAW.js → HK6ZSONF.js} +0 -0
  329. /package/dist/plugins/ask/{askQuestion.d.ts → tools.d.ts} +0 -0
  330. /package/dist/plugins/delegations/{waits.d.ts → waitContracts.d.ts} +0 -0
  331. /package/dist/plugins/{tools → fileTools}/fsRead.d.ts +0 -0
  332. /package/dist/plugins/{tools → fileTools}/ripgrep.d.ts +0 -0
  333. /package/dist/plugins/{tools → fileTools}/textEdit.d.ts +0 -0
  334. /package/dist/{util → plugins/mcp}/version.d.ts +0 -0
  335. /package/dist/{sandbox → plugins/sandbox}/client.d.ts +0 -0
  336. /package/dist/{sandbox → plugins/sandbox}/files.d.ts +0 -0
  337. /package/dist/{sandbox → plugins/sandbox}/protocol.d.ts +0 -0
  338. /package/dist/{sandbox → plugins/sandbox}/worker.d.ts +0 -0
  339. /package/dist/{sandbox → plugins/sandbox}/worker.js +0 -0
  340. /package/dist/plugins/skills/{tool.d.ts → tools.d.ts} +0 -0
  341. /package/dist/plugins/{tools → webTools}/html.d.ts +0 -0
  342. /package/dist/plugins/{tools → webTools}/network.d.ts +0 -0
  343. /package/dist/plugins/{tools → webTools}/web.d.ts +0 -0
  344. /package/dist/plugins/workflows/{work.d.ts → workStatus.d.ts} +0 -0
  345. /package/dist/{plugins/providers → providers}/codexAuth.d.ts +0 -0
  346. /package/dist/services/{contributions.d.ts → catalogContributions.d.ts} +0 -0
  347. /package/dist/{loop → state}/limits.d.ts +0 -0
  348. /package/dist/{plugins/store → stores}/durableObject.d.ts +0 -0
  349. /package/dist/{plugins/store → stores}/durableObjectConnection.d.ts +0 -0
  350. /package/dist/{plugins/store → stores}/sqlite.d.ts +0 -0
  351. /package/dist/{models → util}/jsonSchema.d.ts +0 -0
  352. /package/dist/{kit → util}/retries.d.ts +0 -0
  353. /package/dist/{kit → util}/timers.d.ts +0 -0
@@ -0,0 +1 @@
1
+ import{a as I,f as P,g as Fe,h as F}from"./DDANMY45.js";import{A as De,f as ve,g as b,i as ze,x as Pe,y as Be}from"./BBCW2FZK.js";import{f as Re,g as Ae,k as Ee,l as je,m as me,p as Oe,q as Ne,r as Me,s as te}from"./MMNNZCBO.js";import{e as D,g as O}from"./G44LG6VL.js";import{b as Se,k as Te,q as j,r as ee,w as he,y as Ce}from"./D4PQP5MA.js";var re=class extends Error{threadId;route;constructor(t,r,n){super(`Thread ${t} runs on ${we(r)}: ${n}`),this.threadId=t,this.route=r,this.name="RouteConflictError"}},J=class extends Error{route;constructor(t){super(`Provider '${t.provider}' is not registered`),this.route=t,this.name="RouteUnavailableError"}},Je=(e,t)=>e.provider===t.provider&&e.model===t.model&&e.thinking_effort===t.thinking_effort,we=e=>`${e.provider}/${e.model}${e.thinking_effort===null?"":` (${e.thinking_effort})`}`;function Ue(e,t,r){let n=r.target(e);if("expect"in t){if(n.blocked!==null)throw new J(n.route);if(!Je(t.expect,n.route))throw new re(e,n.route,`expected ${we(t.expect)}`);return null}let s=r.resolve(t.select,n.route);if(Je(s,n.route))return null;if(!n.selectable)throw new re(e,n.route,`it cannot change to ${we(s)} while its pending request can run or is running`);return s}var Le={init:()=>null,apply(e,t){return t.type==="thread/spawned"||t.type==="run/cause"?t.data.route??e:e}};var U=class extends ReferenceError{threadId;constructor(t){super(`Unknown thread: ${t}`),this.threadId=t,this.name="UnknownThreadError"}},C=class extends Error{threadId;seq;constructor(t,r,n){super(`Cannot fork thread ${t} at row ${r}: ${n}`),this.threadId=t,this.seq=r,this.name="ForkCutError"}},ne=class extends Error{index;rule;constructor(t,r,n){super(t),this.index=r,this.rule=n,this.name="ReplacementRefusedError"}};var We=class extends ReferenceError{agentName;constructor(t){super(`Unknown agent: ${t}`),this.agentName=t,this.name="UnknownAgentError"}},Ve=class extends Error{threadId;holding;constructor(t,r){super(r==="release"?`Thread ${t} is being released`:r==="cancel"?`Thread ${t} is being cancelled`:r==="configure"?`Thread ${t} is being configured`:r==="rebuild"?`Thread ${t} is rebuilding its prompt`:r==="compact"?`A compaction is running on thread ${t}`:`A turn is already running on thread ${t}`),this.threadId=t,this.holding=r,this.name="ThreadBusyError"}},Ge=class extends Error{threadId;constructor(t,r){super(`Thread ${t} is configured as asked, but its plugins could not be restored: ${r instanceof Error?r.message:String(r)}`,{cause:r}),this.threadId=t,this.name="RestoreFailedError"}},He=class extends Error{threadId;limit;constructor(t,r){super(`Delegation is ${r} levels deep; ${t} was not started`),this.threadId=t,this.limit=r,this.name="DepthExceededError"}},T=class extends Error{constructor(){super("The thread's plugins changed under the turn"),this.name="StaleActivation"}},N=class extends Error{constructor(){super("The facts or registrations the answer's stop checks judged under changed"),this.name="JudgmentInvalidated"}},H=class extends Error{cause;constructor(t){super("Turn failed; its ending is recorded"),this.cause=t,this.name="RecordedTurnFailure"}},Ke=class extends Error{threadId;conflicts;constructor(t,r){let n=r.map(({field:u})=>u),s=r.find(({field:u})=>u==="agent"),o=r.find(({field:u})=>u==="kind"),a=[...s===void 0?[]:[`belongs to ${String(s.recorded)}, not ${String(s.requested)}`],...o===void 0?[]:[`already exists and is ${o.recorded==="fork"?"a":"not a"} fork`],...n.includes("cut")?["was forked with a different source or cut"]:[],...n.filter(u=>!["agent","kind","cut"].includes(u)).length===0?[]:[`was created with a different ${n.filter(u=>!["agent","kind","cut"].includes(u)).join(", ")}`]];super(`Thread ${t} ${a.join("; ")}`),this.threadId=t,this.conflicts=r,this.name="BirthConflictError"}},Ye=class extends Error{refusal;operation;constructor(t,r){super(t.message),this.refusal=t,this.operation=r,this.name="WriteRefusedError"}},Qe=class extends Error{threadId;constructor(t){super(`Thread ${t} is activating; await thread.whenReady(), or close the thread, first`),this.threadId=t,this.name="ThreadActivatingError"}},Xe=class extends Error{threadId;requestId;decision;constructor(t,r,n){super(`Confirmation request_id=${r} on thread ${t} was already ${n.approved?"approved":"rejected"}`),this.threadId=t,this.requestId=r,this.decision=n,this.name="ConfirmationAnsweredError"}},L=class extends Error{threadId;constructor(t,r){super(`Thread ${t} is not settled: ${r}`),this.threadId=t,this.name="ThreadUnsettledError"}},Ze=class extends Error{threadId;row;reason;constructor(t,r,n){super(`Thread ${t} cannot be continued: its surface refused surface/replaced row ${r.seq} of thread ${r.threadId} (${n}); it can be read, and forked before that row`),this.threadId=t,this.row=r,this.reason=n,this.name="CorruptHistoryError"}},M=class extends Error{constructor(t){super(t),this.name="AuxiliaryRefusedError"}};var _=(e,t)=>({call_id:e.call_id,name:e.name,output:t,is_error:!0,notes:null,metadata:{}}),Pr=e=>({kind:"wait",...e}),W=e=>"kind"in e&&e.kind==="wait";var ge=new WeakMap;function Dr(e,t,r){let n=ge.get(e.root);n===void 0&&(n=new Map,ge.set(e.root,n));let s=n.get(t);if(s!==void 0)throw new Error(`Thread ${t} already runs the ${s.name} strategy; a thread runs one strategy. Mount strategies on the root with disjoint agent selectors, or install one per thread, never two.`);let o=n;e.effect(()=>(o.set(t,r),()=>{o.get(t)===r&&o.delete(t)}))}function Fr(e,t){return ge.get(e.root)?.get(t)}var et=class{listeners=new Set;report;constructor(t){this.report=t}emit(t){this.listeners.size!==0&&ve(this.listeners,b(structuredClone(t)),this.report)}subscribe(t){return this.listeners.add(t),()=>this.listeners.delete(t)}};import{isDeepStrictEqual as ke}from"node:util";var tt={init:()=>({lastTurn:0,step:0,lastReason:null,turnOpen:!1,concludedTurn:null}),apply(e,t){return t.type==="turn/start"?(e.lastTurn=t.data.turn,e.step=0,e.lastReason=null,e.turnOpen=!0):t.type==="step/start"?e.step+=1:t.type==="turn/end"?(e.lastReason=t.data.reason,e.turnOpen=!1):t.type==="input/message"?e.concludedTurn=null:t.type==="tool/result"&&t.data.result.concludes_turn===!0&&(e.concludedTurn=e.lastTurn),e}},se={init:()=>({status:"none"}),apply(e,t){switch(t.type){case"assistant/message":{if(t.data.interrupted)return e;let r=t.data.response.message;return r.tool_calls.length>0?{status:"none"}:{status:"pending",seq:t.seq,kind:"reply",text:ee(r),finish:t.data.response.finish}}case"tool/result":return t.data.result.concludes_turn!==!0?e:{status:"pending",seq:t.seq,kind:"concluded",text:t.data.result.output};case"input/message":return{status:"none"};case"turn/end":{if(e.status!=="pending")return e;let{kind:r}=t.data.reason;return r==="completed"?{...e,status:"accepted"}:r==="rejected"?{...e,status:"rejected"}:e}default:return e}}};function Gr(e,t,r){let n=se.init(),s=null;for(let o of e.rowsAfter(t,r))if(n=se.apply(n,o),o.type==="turn/end"&&(s=o.data.reason,n.status==="accepted"||Qt(s)))break;return n.status!=="accepted"?{reason:s,output:"",answered:!1}:{reason:s,output:n.text,answered:!0}}var Qt=e=>e!==null&&(e.kind==="error"||e.kind==="aborted"||e.kind==="max-steps"||e.kind==="rejected");var rt={init:()=>new Map,apply(e,t){if(t.type==="wait/declared"){let{data:r}=t;e.has(r.call_seq)||e.set(r.call_seq,{declaration:{seq:t.seq,turn:r.turn,step:r.step,call_id:r.call_id,call_seq:r.call_seq,owner:r.owner,dependency:r.dependency,deadline_at:r.deadline_at,reason:r.reason},value:null,answered:!1})}else if(t.type==="wait/resolved"){let r=e.get(t.data.call_seq);r!==void 0&&r.value===null&&!r.answered&&(r.value=t.data.value)}else if(t.type==="tool/result"){let r=e.get(t.source_seqs[0]??0);r!==void 0&&(r.answered=!0)}return e}},nt=e=>e!==void 0&&e.value===null&&!e.answered,oe=e=>e!==void 0&&!e.answered,Kr=e=>[...e.values()].filter(t=>!t.answered);var st={init:()=>new Map,apply(e,t){if(t.type==="confirm/requested"){let{request_id:r,tool_call:n,reason:s,target:o}=t.data;e.set(r,{request_id:r,thread_id:t.thread_id,target:o,tool_call:n,reason:s,resolution:null})}else if(t.type==="confirm/resolved"){let r=e.get(t.data.request_id);r!==void 0&&(r.resolution={approved:t.data.approved,rejection_message:t.data.rejection_message})}return e}},ot={init:()=>new Map,apply(e,t){if(t.type==="execution/requested")e.set(t.seq,{seq:t.seq,request:t.data,authorization:null,result:null});else if(t.type==="execution/authorization"){let r=e.get(t.data.request_seq);r!==void 0&&(r.authorization={seq:t.seq,data:t.data})}else if(t.type==="execution/result"){let r=e.get(t.data.request_seq);r!==void 0&&(r.result={seq:t.seq,value:t.data.result})}return e}},K=(e,t)=>[...e.values()].filter(r=>r.resolution===null&&r.thread_id===t),at=(e,t,r)=>{let n=new Set;for(let s of K(e,r))s.target.kind==="model"&&n.add(s.target.seq);for(let s of t.values())nt(s)&&n.add(s.declaration.call_seq);return n},Y=(e,t)=>{for(let r of e.values())if(r.thread_id===t.threadId&&r.target.kind===t.target.kind&&r.target.seq===t.target.seq)return r},it={init:()=>null,apply:(e,t)=>t.type==="confirm/resolved"?t.seq:e};function Xr(e,t){return[...e.confirmations.values()].filter(r=>{if(r.thread_id!==t||r.resolution?.approved===!1)return!1;if(r.target.kind==="runtime"){let s=e.executions.get(r.target.seq);return s?.result===null&&e.answerCheck.status==="pending"&&e.answerCheck.seq===s.request.candidate_seq}return e.dispatchedCalls.get(r.tool_call.call_id)===r.target.seq})}var ut={init:()=>new Map,apply(e,t){return t.type==="tool/call"?e.set(t.data.call_id,t.seq):t.type==="tool/result"&&e.delete(t.data.result.call_id),e}},dt={init:()=>new Map,apply(e,t){switch(t.type){case"tool/call":e.delete(t.data.call_id);break;case"tool/authorization":{let{call_id:r,call_seq:n,turn:s,decision:o,policy:a}=t.data;e.set(r,{seq:t.seq,call_seq:n,turn:s,decision:o,policy:a});break}case"tool/result":e.delete(t.data.result.call_id);break;default:break}return e}};function lt(e,t,r,n,s){let o=e.get(r);if(!(o===void 0||o.call_seq!==n)&&!(o.decision!=="allow"||o.turn>=s||oe(t.get(n))))return o}function ae(e){for(let t=e.length-1;t>=0;t-=1){let r=e[t];if(r.role!=="assistant"||r.tool_calls.length===0)continue;let n=new Set;for(let s of e.slice(t+1))s.role==="tool"&&s.tool_call_id!==null&&n.add(s.tool_call_id);return r.tool_calls.filter(s=>!n.has(s.call_id))}return[]}var ct={init:()=>null,apply(e,t){return t.type==="thread/spawned"?{thread_id:t.thread_id,agent_name:t.data.agent_name,metadata:t.data.metadata,fork:t.data.fork,origin:t.data.origin,environment:t.data.environment,requires:t.data.requires,seq:t.seq}:e}};var pt={init:()=>({"next-turn":[],"next-step":[]}),apply(e,t){if(t.type==="inbox/spliced"){let{target:r,start:n,removed:s,inserted:o}=t.data;return e[r].splice(n,s.length,...o),e}if(t.type==="input/message"&&t.data.input_id!==null)for(let r of["next-turn","next-step"]){let n=e[r].findIndex(s=>s.id===t.data.input_id);n>=0&&e[r].splice(n,1)}return e}},ft={init:()=>new Map,apply(e,t){if(t.type==="inbox/spliced")for(let r of t.data.inserted)e.has(r.id)||e.set(r.id,{queuedAt:t.seq,claimedAt:null});else if(t.type==="input/message"&&t.data.input_id!==null){let r=e.get(t.data.input_id);r!==void 0&&r.claimedAt===null&&e.set(t.data.input_id,{...r,claimedAt:t.seq})}return e}};function nn(e,t){let r=e.inputs.get(t);if(r===void 0)return{state:"unknown"};let{queuedAt:n,claimedAt:s}=r;if(s!==null)return{state:"claimed",queuedAt:n,claimedAt:s};for(let o of["next-step","next-turn"])if(e.inbox[o].some(a=>a.id===t))return{state:"queued",queuedAt:n,target:o};return{state:"discarded",queuedAt:n}}var ht={init:()=>({spawnSeq:null,unclaimed:!1}),apply(e,t){return t.type==="inbox/spliced"&&e.spawnSeq!==null&&t.source_seqs.includes(e.spawnSeq)?{...e,unclaimed:!0}:t.type==="input/message"?{spawnSeq:null,unclaimed:!1}:e}};var mt=(e,t,r)=>{e.current.set(t.installation_id,{installationId:t.installation_id,presetId:t.preset_id,config:t.config,lifetime:r}),e.used.add(t.installation_id)},wt={init:()=>({current:new Map,used:new Set}),apply(e,t){if(t.type==="thread/spawned")for(let{lifetime:r,...n}of t.data.installations)mt(e,n,r);else t.type==="installation/applied"?mt(e,t.data,"configurable"):t.type==="installation/removed"&&e.current.delete(t.data.installation_id);return e}};var gt={init:()=>null,apply:(e,t)=>t.type==="thread/prompt"?t.data.blocks:e},yt={init:()=>null,apply:(e,t)=>t.type==="thread/tools"?t.data.tools:e};var xt={reactive:0,fresh:1,person:2},_t={init:()=>({byInput:new Map,inputless:[],open:null,count:0}),apply(e,t){switch(t.type){case"run/cause":{let{input_id:r,run_id:n,chain:s}=t.data;return r!==null?e.byInput.set(r,s):e.inputless=[...e.inputless,{seq:t.seq,runId:n,chain:s}],e}case"run/requested":return e.inputless.some(r=>r.runId===null)&&(e.inputless=e.inputless.map(r=>r.runId===null?{...r,runId:t.data.run_id}:r)),e;case"run/settled":{let r=new Set(t.data.residual);return e.inputless=e.inputless.flatMap(n=>n.runId!==t.data.run_id?[n]:r.has(n.seq)?[{...n,runId:null}]:[]),e}case"turn/start":{kt(e),e.open={turn:t.data.turn,class:null};let r=t.data.run_id;for(let n of e.inputless)n.runId===r&&qt(e,n.chain);return e.inputless=e.inputless.filter(n=>n.runId!==r),e}case"inbox/spliced":for(let r of t.data.removed)e.byInput.delete(r);return e;case"input/message":{let r=t.data.input_id;if(r===null)return e;let n=e.byInput.get(r);return n===void 0||(e.byInput.delete(r),e.open!==null&&qt(e,n)),e}case"turn/end":return kt(e),e;default:return e}}};function qt(e,t){let r=e.open;(r.class===null||xt[t]>xt[r.class])&&(e.open={...r,class:t}),t!=="reactive"&&(e.count=0)}function kt(e){e.open?.class==="reactive"&&(e.count+=1),e.open=null}function un(e,t){let r=e.count+(e.open?.class==="reactive"?1:0);return{personTurn:e.open?.class==="person",turns:r,atLimit:r>=t}}var bt={init:()=>({pending:null,pendingCancel:null,latestSettlement:null,latestUserCancel:null,latestReleasing:null,runs:new Map,latestTurn:null,interruptions:0,carried:[],inconsistencies:[]}),apply(e,t){switch(t.type){case"run/requested":return Xt(e,t);case"run/cause":return Zt(e,t);case"run/settled":return er(e,t);case"turn/start":return e.pending?.runId!==t.data.run_id&&e.inconsistencies.push(`turn/start ${t.seq} serves ${t.data.run_id}, which is not pending`),e.latestTurn={seq:t.seq,runId:t.data.run_id,attemptCutoff:t.data.attempt_cutoff},e;case"turn/end":{let{reason:r}=t.data;return r.kind!=="interrupted"?e.interruptions=0:r.cause!=="abandoned"&&(e.interruptions+=1),e}case"thread/cancel":{let r={seq:t.seq,cancelId:t.data.cancel_id,intent:t.data.intent,runId:t.data.run_id,reason:t.data.reason};return r.intent==="user"&&(e.latestUserCancel=r),e.pendingCancel===null&&r.runId!==null&&r.runId===e.pending?.runId&&(e.pendingCancel=r),e}default:return e}}};function Xt(e,t){let r=t.data.run_id;return e.pending!==null||e.runs.has(r)?(e.inconsistencies.push(`run/requested ${t.seq} opens ${r} while ${e.pending?.runId??r} exists`),e):(e.pending={runId:r,requestedAt:t.seq,causes:e.carried},e.carried=[],e.runs.set(r,{requestedAt:t.seq,settlement:null}),e)}function Zt(e,t){let{pending:r}=e;if(r===null||r.runId!==t.data.run_id)return e.inconsistencies.push(`run/cause ${t.seq} names ${t.data.run_id}, which is not pending`),e;let n={seq:t.seq,at:t.timestamp,inputId:t.data.input_id,releases:t.data.releases,chain:t.data.chain};return e.pending={...r,causes:[...r.causes,n]},n.releases&&(e.latestReleasing=t.seq,e.interruptions=0),e}function er(e,t){let{pending:r}=e,{data:n}=t;if(r===null||r.runId!==n.run_id)return e.inconsistencies.push(`run/settled ${t.seq} names ${n.run_id}, which is not pending`),e;let s={runId:n.run_id,seq:t.seq,outcome:n.outcome,reason:n.reason,errorText:n.error_text,through:n.through,residual:n.residual},o=new Set(n.residual);return e.carried=r.causes.filter(a=>o.has(a.seq)),e.pending=null,e.pendingCancel=null,e.interruptions=0,e.latestSettlement=s,e.runs.get(n.run_id).settlement=s,e}function ln(e,t){let r=e.runs.get(t);return r===void 0?{state:"unknown"}:r.settlement===null?{state:"pending"}:{state:"settled",settlement:r.settlement}}function cn(e,t,r){if(t.reason==="obsolete")return[];let n=t.reason==="cancel"?t.cancelSeq??t.attemptCutoff:t.attemptCutoff,s=t.outcome==="failed";return e.causes.filter(o=>o.inputId!==null&&r(o.inputId)!=="queued"?!1:o.seq>n&&(o.releases||!s)).map(o=>o.seq)}var $t={init:()=>({entries:[],refused:[]}),apply(e,t){if(t.type==="surface/replaced"){let n=Ct(e.entries,t);return n.accepted?Rt(e.entries,t,n):e.refused.push({row:ye(t),refusal:n}),e}let r=rr(t);return r!==null&&e.entries.push(r),e}};function St(e,t){let r=[...e];for(let[n,s]of t.entries()){let o=Ct(r,s);if(!o.accepted)return{index:n,refusal:o};Rt(r,s,o)}return null}var Tt=e=>te(e)&&!(e.type==="assistant/message"&&e.data.interrupted);function tr(e){if(!te(e)||!Tt(e))return null;switch(e.type){case"input/message":return j({role:e.data.role,content:e.data.content});case"assistant/message":return e.data.response.message;case"tool/result":return j({role:"tool",content:Re(e.data.result),tool_call_id:e.data.result.call_id})}}function rr(e){return!te(e)||!Tt(e)?null:b({row:ye(e),type:e.type,directDeveloperInput:e.type==="input/message"&&e.data.role==="developer"&&e.data.source===null,message:tr(e)})}function Ct(e,t){let{data:r,source_seqs:n}=t;if(r.kind==="span"&&n.length===0)return v("empty","A span replaces at least one message");if(r.kind==="rewrite"&&n.length!==1)return v("empty",`A rewrite replaces exactly one message, not ${n.length}`);let s=e.findIndex(u=>u.row.seq===n[0]);if(s<0)return v("not-current",`Row ${n[0]} is not behind a message on the current surface`);for(let u=1;u<n.length;u+=1)if(e[s+u]?.row.seq!==n[u])return v("not-current",`The cited rows are not a contiguous run of the current surface: row ${n[u]} does not follow row ${n[u-1]}`);let o=s+n.length,a=e.slice(s,o).find(u=>u.directDeveloperInput);if(a!==void 0)return v("developer-input",`Row ${a.row.seq} is developer input a host sent, which nothing replaces`);if(r.kind==="rewrite"){let u=e[s];return nr(u)?{accepted:!0,start:s,count:1}:v("rewrite-target",`A rewrite replaces a tool result, a user message or a rewrite's stand-in, not ${sr(u)}`)}return o===e.length?v("newest-message","A span never replaces the newest message"):!ie(e,s)||!ie(e,o)?v("unbalanced","A span may not separate a tool call from its result, nor end just before a tool result"):{accepted:!0,start:s,count:n.length}}var v=(e,t)=>({accepted:!1,rule:e,message:t}),nr=e=>e.type==="tool/result"||e.type==="input/message"&&e.message.role==="user"||e.type==="surface/replaced"&&e.kind==="rewrite",sr=e=>e.type==="surface/replaced"?`a ${e.kind}'s stand-in`:`a ${e.message.role} message`;function ie(e,t){if(!Number.isInteger(t)||t<0||t>e.length)throw new RangeError(`A cut is at 0 to ${e.length}, not ${t}`);for(let r=t;r<e.length;r+=1){let{message:n}=e[r];if(n.role==="tool")return!1;if(It(n))break}for(let r=t-1;r>=0;r-=1){let{message:n}=e[r];if(!It(n))continue;let s=new Set;for(let o=r+1;o<t;o+=1){let a=e[o].message;a.role==="tool"&&a.tool_call_id!==null&&s.add(a.tool_call_id)}return n.tool_calls.every(o=>s.has(o.call_id))}return!0}var It=e=>e.role==="assistant"&&e.tool_calls.length>0;function Rt(e,t,r){let n=ye(t),{data:s}=t;if(s.kind==="span"){e.splice(r.start,r.count,b({row:n,type:"surface/replaced",kind:"span",directDeveloperInput:!1,message:j({role:s.stand_in.role,content:s.stand_in.content})}));return}let o=e[r.start].message;e[r.start]=b({row:n,type:"surface/replaced",kind:"rewrite",directDeveloperInput:!1,message:j({role:o.role,content:s.stand_in.content,tool_call_id:o.tool_call_id})})}function gn(e,t){let r=[],n=[t];for(;n.length>0;){let s=n.pop(),o=e.eventAt(s.seq);if(o===void 0)throw new RangeError(`The journal has no row ${s.seq}`);if(o.type!=="surface/replaced"){r.push(s);continue}for(let a=o.source_seqs.length-1;a>=0;a-=1){let u=o.source_seqs[a],i=e.eventAt(u);if(i===void 0)throw new RangeError(`Row ${o.seq} cites row ${u}, which no thread holds`);n.push({threadId:i.thread_id,seq:u})}}return r}var ye=e=>({threadId:e.thread_id,seq:e.seq});var ue={surface:$t,turnBoundary:tt,answerCheck:se,dispatchedCalls:ut,dispatchAttempts:dt,waits:rt,confirmations:st,executions:ot,threadRecord:ct,threadRoute:Le,threadPrompt:gt,threadTools:yt,forkTask:ht,inbox:pt,inputs:ft,installations:wt,lastAnswer:it,requests:bt,chain:_t},or={surface:"inherit",turnBoundary:e=>({...e,step:0,lastReason:null,turnOpen:!1}),answerCheck:"reset",dispatchedCalls:"reset",dispatchAttempts:"reset",waits:"reset",confirmations:"reset",executions:"reset",threadRecord:"inherit",threadRoute:"inherit",threadPrompt:"inherit",threadTools:"inherit",forkTask:(e,t)=>({spawnSeq:t.seq,unclaimed:!1}),inbox:"reset",inputs:"reset",installations:"inherit",lastAnswer:"reset",requests:"reset",chain:"reset"},At=Object.keys(ue);function Et(e,t,r){let n=ue[e],s=t;if(Me(r)){let o=or[e];o==="reset"?s=n.init():o!=="inherit"&&(s=o(s,r))}return n.apply(s,r)}var m=ze({key:"threadState",init:()=>Object.fromEntries(At.map(e=>[e,ue[e].init()])),apply(e,t){let r=e;for(let n of At)r[n]=Et(n,r[n],t);return e}});function Q(e){return{init:()=>ue[e].init(),apply:(t,r)=>Et(e,t,r)}}import{randomUUID as ar}from"node:crypto";var z=e=>`${e}_${ar()}`;function jt(e,t,r,n,s){let o=null;if(r.route!==void 0){if(s===void 0)throw new Error(`This write on thread ${e} takes no route statement`);o=Ue(e,r.route,s)}let a=t?.runId??z("run"),u=r.releases??!0,i=r.chain??"person",l={type:"run/cause",data:{run_id:a,input_id:n,releases:u,chain:i,route:o},options:{threadId:e}};return{runId:a,rows:t===null?[{type:"run/requested",data:{run_id:a},options:{threadId:e}},l]:[l]}}var Ot=e=>!Array.isArray(e);function ir(e){let[t]=e;if(t===void 0)return[];if(t.source===null)return[t];let r=e.findIndex(n=>n.source===null);return e.slice(0,r===-1?e.length:r)}var V=class{journal;threadId;constructor(t,r){this.journal=t,this.threadId=r}get queues(){return this.journal.state(m,this.threadId).inbox}get state(){return this.journal.state(m,this.threadId)}get nextTurn(){return this.queues["next-turn"]}get nextStep(){return this.queues["next-step"]}queuedAt(t){return this.journal.state(m,this.threadId).inputs.get(t)?.queuedAt}get pending(){return[...this.nextStep,...this.nextTurn].sort((t,r)=>(this.queuedAt(t.id)??0)-(this.queuedAt(r.id)??0))}async send(t,r,n={},s){if(n.source!==void 0&&n.id===void 0)throw new Error(`Input from ${n.source.plugin} needs an id: a redelivery must queue nothing twice`);let o=n.source??null,a=n.id??z("in"),{events:u,value:i}=await this.journal.transact(this.threadId,()=>{let l=this.queuedAt(a);if(l!==void 0)return{rows:[],value:{status:"known",inputId:a,queuedAt:l}};let f=n.target??r(),d=this.spliceEntry(f,this.queues[f].length,0,[je(t,a,o)]),{wake:h}=n,p=h===void 0?null:jt(this.threadId,this.state.requests.pending,h,a,s),c=p?.runId??null,g=n.rows?.({kind:"send",threadId:this.threadId,target:f,runId:c,inputId:a})??[];return Ot(g)?{rows:[],value:{status:"refused",refusal:g.refuse}}:{rows:[d,...p?.rows??[],...g],value:{runId:c}}});return"runId"in i?{status:"queued",inputId:a,queuedAt:u[0].seq,runId:i.runId}:i}async withdraw(t,r={}){let{value:n}=await this.journal.transact(this.threadId,()=>{let s;for(let a of["next-step","next-turn"]){let u=this.queues[a].findIndex(i=>i.id===t);u>=0&&(s=this.spliceEntry(a,u,1,[]))}let o=r.rows?.({threadId:this.threadId,withdrawn:s!==void 0})??[];return Ot(o)?{rows:[],value:{status:"refused",refusal:o.refuse}}:{rows:[...s===void 0?[]:[s],...o],value:{status:s===void 0?"not-queued":"withdrawn"}}});return n}clearRows(){return[this.spliceEntry("next-step",0,this.nextStep.length,[]),this.spliceEntry("next-turn",0,this.nextTurn.length,[])].filter(t=>t!==void 0)}peek(t,r=!1){let n=[...this.nextStep];(t==="next-turn"||r)&&n.push(...ir(this.nextTurn));let s=n.map(o=>{let a=this.queuedAt(o.id);if(a===void 0)throw new Error(`Missing queued sequence for input ${o.id} on thread ${this.threadId}`);return{input:o,seq:a}});return s.sort((o,a)=>o.seq-a.seq),s.map(({input:o})=>o)}spliceEntry(t,r,n,s){let o=this.queues[t],a=Math.min(Math.max(Math.trunc(r)||0,0),o.length),u=Math.min(Math.max(Math.trunc(n)||0,0),o.length-a);if(!(u===0&&s.length===0))return{type:"inbox/spliced",data:{target:t,start:a,removed:o.slice(a,a+u).map(i=>i.id),inserted:s},options:{threadId:this.threadId}}}};function X(e,t){if(e.parked.length>0)return{kind:"end",reason:{kind:"blocked"}};let r=e.step>=t.maxStepsPerTurn;return e.unanswered.length>0?r?{kind:"end",reason:{kind:"max-steps",limit:t.maxStepsPerTurn}}:{kind:"answer-calls",calls:e.unanswered}:e.provisional!==null&&(e.concluded||e.queued.length===0)?{kind:"check"}:e.concluded?{kind:"end",reason:{kind:"completed"}}:e.queued.length>0||e.owed?r?{kind:"end",reason:{kind:"max-steps",limit:t.maxStepsPerTurn}}:{kind:"ask-model",claim:e.queued}:{kind:"end",reason:{kind:"completed"}}}var ur=(e,t)=>X(e,t).kind!=="end";function B(e,t,r,n,s,o=!1){let a=e.state(m,t).surface.entries.map(p=>p.message),u=ae(a),i=at(e.state(m,t).confirmations,e.state(m,t).waits,t),l=a.at(-1),f=e.state(m,t).turnBoundary,d=e.state(m,t).answerCheck,h=e.state(m,t).dispatchedCalls;return{unanswered:u,parked:[...u.filter(p=>i.has(h.get(p.call_id)??0)),...K(e.state(m,t).confirmations,t).filter(p=>p.target.kind==="runtime").map(p=>p.tool_call)],queued:u.length>0?[]:new V(e,t).peek(r,o),owed:!e.state(m,t).forkTask.unclaimed&&(dr(l)||l?.role==="tool"&&f.concludedTurn===null),concluded:f.concludedTurn===s,provisional:d.status==="pending"?d.seq:null,step:n}}var dr=e=>e!==void 0&&Ee.includes(e.role);function Kn(e,t,r){let n=e.state(m,t).turnBoundary.lastTurn+1;return ur(B(e,t,"next-turn",0,n),r)}var Nt=["thread/spawned","turn/start","llm/request","turn/end","surface/replaced"];function Mt(e,t){return ae(e.map(r=>r.message)).length>0?"the conversation there has tool calls without results":t.status==="pending"?"its answer is still owed its stop checks; resume the thread first":null}function ts(e,t,r){let n=typeof r=="number"?r:r.seq,s;try{s=e.eventAt(n)}catch(u){throw u instanceof De?new C(t,n,`the row is not on thread ${t}'s lineage`):u}if(s===void 0)throw new C(t,n,"no thread has that row");if(typeof r!="number"&&s.thread_id!==r.threadId)throw new C(t,n,`the row belongs to thread ${s.thread_id}, not ${r.threadId}`);if(!Nt.includes(s.type))throw new C(t,n,`a ${s.type} row is not a cut; cut at ${Nt.join(", ")}`);if(!e.inLineage(t,s))throw new C(t,n,"the row is not part of this thread's conversation");let o=s.thread_id,a=Mt(e.stateAt(Q("surface"),o,n).entries,e.stateAt(Q("answerCheck"),o,n));if(a!==null)throw new C(t,n,a);return{threadId:o,seq:n}}function rs(e,t,r,n){let s=typeof r=="number"?r:r.seq,o=e.lineage(t),a=o.findIndex(f=>f.seq===s),u=o[a];if(u===void 0)throw new C(t,s,"the row is not part of this thread's conversation");if(typeof r!="number"&&u.thread_id!==r.threadId)throw new C(t,s,`the row belongs to thread ${u.thread_id}, not ${r.threadId}`);let i=lr(o,a);if(i===void 0)throw new C(t,s,"the row is not inside a turn");if(n)return Z(o[i]);let l=o[i].thread_id;for(let f=i+1;f<o.length;f+=1){let d=o[f];if(d.type==="turn/end"&&d.thread_id===l)return Z(d);if(d.type==="thread/spawned")break}throw new C(t,s,"its turn has not ended")}function lr(e,t){for(let r=t;r>=0;r-=1){let n=e[r];if(n.type==="turn/start")return r;if(n.type==="thread/spawned"||n.type==="turn/end"&&r!==t)return}}function ns(e,t){let r=[],n=Q("surface"),s=Q("answerCheck"),o=n.init(),a=s.init(),u=null;for(let i of e.lineage(t))o=n.apply(o,i),a=s.apply(a,i),i.type==="turn/end"&&(u=i.data.turn),Mt(o.entries,a)===null&&(i.type==="turn/end"?r.push({...Z(i),kind:"turn/end",turn:i.data.turn,reason:i.data.reason}):i.type==="surface/replaced"&&i.data.turn===null&&!pr(o,i.seq)&&r.push({...Z(i),kind:"surface/replaced",afterTurn:u}));return r}function cr(e,t){let r=e.rows(t.threadId),n=r.length-1;for(;n>=0&&r[n].seq>t.seq;)n-=1;let s=r[n];if(s?.seq!==t.seq||s.type!=="assistant/message")return null;for(let o=n-1;o>=0;o-=1){let a=r[o];if(a.type==="llm/request"&&a.data.llm_call_id===s.data.llm_call_id)return Z(a)}return null}function vt(e,t){let r=xe(e,t);return r===null?null:cr(e,r)}function xe(e,t){let{entries:r}=e.state(m,t).surface;for(let n=r.length-1;n>=0;n-=1)if(r[n].type==="assistant/message")return r[n].row;return null}var pr=(e,t)=>e.refused.some(r=>r.row.seq===t),Z=e=>({threadId:e.thread_id,seq:e.seq});async function qe(e,t,r){await e.transact(t,()=>{let{lastTurn:n,turnOpen:s,step:o}=e.state(m,t).turnBoundary;if(!s)return{rows:[],value:void 0};let a=X(B(e,t,"next-step",o,n),r),u=a.kind==="end"?a.reason:{kind:"interrupted",cause:"abandoned"};return{rows:[{type:"turn/end",data:{turn:n,reason:u},options:{threadId:t}}],value:void 0}})}async function zt(e,t,r,n){if(n.length===0)return[];let s=n.map(({source_seqs:a,auxiliary_request_seq:u,...i})=>({type:"surface/replaced",data:{...i,trigger:r.trigger,turn:r.turn,step:r.step,auxiliary_request_seq:u??null},options:{threadId:t,sourceSeqs:a}})),{events:o}=await e.transact(t,()=>{if(e.summary(t)===void 0)throw new U(t);let a=e.head,u=s.map((l,f)=>Ne({seq:a+f+1,type:l.type,thread_id:t,data:l.data,source_seqs:l.options.sourceSeqs})),i=St(e.state(m,t).surface.entries,u);if(i!==null)throw new ne(i.refusal.message,i.index,i.refusal.rule);return{rows:s,value:void 0}});return o.map(a=>({threadId:t,seq:a.seq}))}var fr=["deny","confirm","approve"];async function Pt(e,t,r){let n=b(structuredClone(t)),s=await e.ctx.collect(e.target,"lagent/tool/authorize",n),o=s.map(hr);return o.includes("deny")?{decision:"deny",confirmedBy:null,reasons:mr(s)}:o.includes("confirm")?r.userApproved?{decision:"allow",confirmedBy:"user"}:o.includes("approve")?{decision:"allow",confirmedBy:"policy"}:{decision:"confirm",confirmedBy:null}:{decision:"allow",confirmedBy:null}}function hr(e){if(e!==void 0){if(typeof e=="string"&&fr.includes(e))return e;if(Bt(e))return"deny";throw new TypeError("A tool policy returned an invalid authorization decision")}}function Bt(e){if(typeof e!="object"||e===null)return!1;let{decision:t,reason:r}=e;return t==="deny"&&typeof r=="string"&&r.trim()!==""}var mr=e=>[...new Set(e.filter(Bt).map(t=>t.reason.trim()))];function wr(e){if(e===void 0||e===0)return 0;if(typeof e!="number"||!Number.isFinite(e))throw new TypeError(`A step contribution rank must be a finite number, not ${String(e)}`);return e}function Dt(e,t){let r=[],n=!0,s=Object.freeze({threadId:t.threadId,turn:t.turn,step:t.step,route:b(structuredClone(t.route)),claimed:b(structuredClone(t.claimed)),contribute(o,a){if(!n)throw new Error("A step contribution arrived after its lagent/llm/step dispatch returned");let u=wr(a),i=me(o),l=r.find(p=>ke(p.contribution,i));if(l===void 0){r.push({contribution:i,rank:u});return}if(l.rank===u)return;let{plugin:f,kind:d,instance_id:h}=i.source;throw new Error(`Step contribution ${f}/${d}/${h} was made at rank ${l.rank} and at rank ${u}; identical contributions must share one rank`)}});try{e.ctx.emit(e.target,"lagent/llm/step",s)}finally{n=!1}return r.sort((o,a)=>o.rank-a.rank).map(o=>o.contribution)}async function Ft(e,t,r){let{signal:n,...s}=t,o=!0,a=Object.freeze({...b(structuredClone(s)),signal:n,observe(d){if(!o)throw new Error("A stop check declared an observation after its judgment ended");let h=null;try{h=d()}catch{}r.push({read:d,value:h})}}),u;try{u=await e.ctx.collect(e.target,"lagent/turn/stop",a)}catch(d){throw d instanceof AggregateError?new Error(`A stop check failed: ${d.errors.map(I).join("; ")}`,{cause:d}):d}finally{o=!1}let i=new Map,l=[],f=new Map;for(let d of u)if(d!==void 0)if(d.decision==="continue")l.push(me(d.message));else if(d.decision==="reject"&&typeof d.reason=="string"&&d.reason.trim()!==""){let h={reason:d.reason.trim(),source:Ae.parse(d.source)};i.set(JSON.stringify(h),h)}else if(d.decision==="prepare"){let h=d.request;if(!h.owner||!h.key||!h.operation?.name)throw new TypeError("Invalid completion request");let p=JSON.stringify([h.owner,h.key]),c=f.get(p);if(c!==void 0&&!ke(c,h))throw new TypeError("Conflicting completion requests");f.set(p,b(structuredClone(h)))}else throw new TypeError("A stop check returned an invalid verdict");return i.size>0?{kind:"reject",rejections:[...i.values()]}:l.length>0?{kind:"continue",messages:l}:f.size>0?{kind:"prepare",requests:[...f.values()]}:{kind:"accept"}}async function de(e,t,r,n){let s=e.ctx.confinement.open(t,r);try{return await n(s)}finally{await s.end()}}var le=async(e,t,r)=>{let n=await e.ctx.waterfall(e.target,"lagent/tool/execute",t,()=>(t.context.signal.throwIfAborted(),r()));return W(n)||n.call_id===t.call.call_id?n:{..._(t.call,`Tool "${t.toolName}" answered call ${n.call_id} instead of ${t.call.call_id}`),notes:n.notes,metadata:{stray_output:n.output,stray_metadata:n.metadata}}};function gr(e,t){let{signal:r,...n}=e,s=t,o={};for(let[a,u]of Object.entries(n))o[a]=u===s[a]?u:yr(u,s[a]);return Object.freeze({...o,signal:r})}var yr=(e,t)=>{if(!Array.isArray(e)||!Array.isArray(t))return b(structuredClone(e));let r=new Set(t);return Object.freeze(e.map(n=>r.has(n)?n:b(structuredClone(n))))};function xr(e,t){let r=["model","thinkingEffort","agentName","threadId","llmCallId","purpose","signal"];for(let n of[...r,...t])Object.defineProperty(e,n,{value:e[n],enumerable:!0,writable:!1,configurable:!1});return e}function ce(e,t){let{threadId:r,agentName:n,route:s}=t;return{model:s.model,tools:e.toolsFor(n).map(o=>o.spec),providerTools:[],parallelToolCalls:!0,responseFormat:{kind:"text"},...s.thinking_effort===null?{}:{thinkingEffort:s.thinking_effort},systemPrompt:e.journal.state(m,r).threadPrompt??[],signal:t.signal,agentName:n,threadId:r,llmCallId:t.llmCallId,purpose:t.purpose}}function pe(e,t,r,n,s=[]){let o,a;return{get row(){return o},get attempts(){return a?.attempts??0},call(u){let{signal:i,...l}=u,f=b(l),d=xr({...f,signal:i},s),h=()=>{e.signal.throwIfAborted(),i.throwIfAborted()};return e.ctx.waterfall(e.target,"lagent/llm/request",d,async()=>{h();let p=gr(d,f),c={threadId:p.threadId},g={type:r,data:{...n,llm_call_id:p.llmCallId,model:p.model,message_count:p.messages.length},options:c},{events:w}=await e.journal.transact(p.threadId,()=>{let x=e.journal.state(m,p.threadId).threadTools,q=JSON.parse(JSON.stringify(p.tools));return ke(q,x)?{rows:[g],value:void 0}:{rows:[{type:"thread/tools",data:{tools:p.tools},options:c},g],value:void 0}});return o=w.at(-1),await qr(e,p,o),h(),a=t.call(p),a.response})}}}async function qr(e,t,r){let{signal:n,...s}=t,o=Object.freeze({request:Object.freeze(s),row:r});try{await e.ctx.parallel(e.target,"lagent/llm/sent",o)}catch(a){for(let u of a instanceof AggregateError?a.errors:[a])e.ctx.reportError(u)}}function Jt(e,t){e.ctx.reportError(t)}import{z as _e}from"zod";var ks=_e.strictObject({name:_e.string(),basePrompt:_e.string().default("")});async function fe(e){let{runtime:t,request:r,signal:n}=e,{journal:s}=t;for(let o=0;o<kr;o+=1){await s.flush();let a=s.head,u=e.approval();if(u?.approved===!1)return{kind:"rejected",reason:u.rejection_message};let i=await Pt(t,r,{userApproved:u?.approved===!0});if(n.aborted||t.stale())return{kind:"unstarted"};let{events:l}=await s.transact(r.threadId,()=>(e.validate?.(),n.aborted||t.stale()||Ir(s,r.threadId,a)?{rows:[],value:void 0}:{rows:e.record(i),value:void 0}));if(l.length>0)return{kind:"decided",authorization:i,attemptSeq:l[0].seq};if(n.aborted||t.stale())return{kind:"unstarted"}}throw new Error("Execution was not started: permissions kept changing while it was authorized")}var kr=5,Ut=new Set,Lt=e=>JSON.stringify([e.plugin,e.instance_id??null,e.kind]);function _r(e){Ut.add(Lt(e))}var br=e=>e.type==="confirm/resolved"||e.type==="ext"&&Ut.has(Lt(e.data));function Ir(e,t,r){return e.origins.callers(t).threads.some(n=>n.through_seq>r&&(!e.isLoaded(n.thread_id)||e.rowsAfter(n.thread_id,r).some(br)))}async function Vt(e,t,r){let{journal:n}=e,{threadId:s,signal:o}=t,a,u=!1;try{o.throwIfAborted();let{entries:i}=n.state(m,s).surface,l=i.findIndex(y=>y.row.seq===r.through);if(l<0)throw new M(`Row ${r.through} is not behind a message on the current surface`);if(!ie(i,l+1))throw new M(`A prefix ending on row ${r.through} separates a tool call from its result; end it on a balanced cut`);if(r.instructions.length===0)throw new M("An auxiliary call needs an instruction");let f=r.instructions.map(y=>Se.parse(y)),d=$r(e,t.route,r.route),h=e.client(d),p=i.slice(0,l+1).map(y=>y.message),c=z("llm"),g={messages:[...p,...f.map(y=>b(j({role:"user",content:y})))],toolChoice:structuredClone(r.toolChoice??"auto"),...r.maxOutputTokens===void 0?{}:{maxOutputTokens:r.maxOutputTokens},...ce(e,{threadId:s,agentName:t.agentName,route:d,signal:o,llmCallId:c,purpose:"auxiliary"})};a=pe(e,h,"auxiliary/request",{turn:t.turn,step:t.step,route:d,surface_message_count:p.length,instructions:f},["toolChoice","maxOutputTokens"]);let w=await a.call(g),x=a.row;if(x===void 0)throw new Error("Request middleware answered an auxiliary call itself; an auxiliary call goes to its route");let q=await w.completed();o.throwIfAborted();let S=ee(q.message),R=q.message.usage;u=!0;let E=await Wt(e,t,x,c,{usage:R,text:S,finish:q.finish,tool_calls:q.message.tool_calls,provider_calls:q.message.provider_calls,error_text:null,error_kind:null,attempts:a.attempts});return{requestSeq:x.seq,resultSeq:E.seq,message:q.message,text:S,finish:q.finish,usage:R}}catch(i){let l=a?.row;if(l!==void 0&&!u){u=!0;let f=F(o,i),d=O(i,D);await Wt(e,t,l,l.data.llm_call_id,{usage:null,text:null,finish:null,error_text:f?`aborted: ${I(o.reason)}`:P(i),error_kind:f?"aborted":d?.kind??"other",attempts:d?.attempts??a?.attempts??0})}throw i}}var $r=(e,t,r)=>r===void 0?t:e.resolveRoute(r,t);async function Wt(e,t,r,n,s){if(r===void 0)throw new Error("An auxiliary result needs its request row");return e.journal.append("auxiliary/result",{turn:t.turn,step:t.step,llm_call_id:n,...s},{threadId:t.threadId,sourceSeqs:[r.seq]})}async function Ht(e,t){let{threadId:r,signal:n,lease:s}=t,o=e.strategy();if(o===void 0)return{outcome:{committed:[],ended:"skipped",reason:"no strategy prepares this thread"},error:void 0};let a=Object.freeze({threadId:r,turn:t.turn,step:t.step,route:b(structuredClone(t.route)),trigger:t.trigger,queued:b(structuredClone(t.queued)),options:b(structuredClone(t.options)),signal:n}),u=()=>{if(n.throwIfAborted(),!s.held)throw new Error(`Thread ${r}'s lease passed to another holder while it was prepared`)};try{let i=await o.plan(a),l,f=null;if(i.kind==="ask"){u();let h;try{let p=await Vt(e,{threadId:r,agentName:t.agentName,turn:t.turn,step:t.step,route:t.route,signal:n},i.call);f=p.requestSeq,h={reply:p}}catch(p){if(Gt(p)||O(p,M)!==void 0)throw p;if(F(n,p))throw n.reason;h={failure:p}}u(),l=await i.finish(h)}else l=i;if(u(),l.kind==="skip")return{outcome:{committed:[],ended:"skipped",reason:l.reason},error:void 0};if(l.kind==="fail")return l.facts!==void 0&&l.facts.length>0&&await e.journal.appendAll(l.facts.map(h=>({type:"ext",data:h,options:{threadId:r}}))),n.aborted?{outcome:be([],n),error:void 0}:{outcome:{committed:[],ended:"failed",reason:l.reason},error:void 0};if(l.replacements.length===0)throw new TypeError("A replace plan names no replacement; a plan with nothing to replace is a skip");for(let h of l.replacements){let p=h.auxiliary_request_seq;if(p!=null&&p!==f)throw new TypeError(`Row ${p} is not the auxiliary request this plan made`)}let d=await zt(e.journal,r,t,l.replacements);return n.aborted?{outcome:be(d,n),error:void 0}:{outcome:{committed:d,ended:"completed",...l.reason===void 0?{}:{reason:l.reason}},error:void 0}}catch(i){if(Gt(i))throw i;return n.aborted&&Fe(n,i)?{outcome:be([],n),error:void 0}:{outcome:{committed:[],ended:"failed",reason:P(i)},error:i}}}var Gt=e=>e instanceof Pe||e instanceof Be,be=(e,t)=>({committed:e,ended:"cancelled",reason:I(t.reason)});var Sr=(e,t)=>({..._(e,`Tool "${e.name}" was interrupted before its result was recorded, so whether it took effect is unknown. Check what became of it before repeating it; do not simply call it again.`),metadata:{interrupted:!0,attempt_seq:t.seq}}),Tr=e=>({..._(e,`Tool "${e.name}" was not run: its arguments are not a JSON object (${e.malformed.error}). Received: ${e.malformed.raw.slice(0,500)}`),metadata:{malformed_arguments:!0}});function Cr(e,t){let r=[];for(let n of e){let s=t(n.name)==="exclusive",o=r.at(-1);s||o===void 0||o.exclusive?r.push({calls:[n],exclusive:s}):o.calls.push(n)}return r}async function Kt(e){let{runtime:t,threadId:r,agentName:n,turn:s,step:o,calls:a,signal:u}=e,{journal:i}=t,l=xe(i,r),f={...e,requestSeq:vt(i,r)?.seq??null},d=y=>t.tool(n,y)?.tool.executionMode??"parallel",h=new Map,p=!1,c=()=>{let y=i.state(m,r).dispatchedCalls;return a.filter($=>!y.has($.call_id))};await i.transact(r,()=>({rows:c().map(y=>({type:"tool/call",data:{turn:s,step:o,call_id:y.call_id,name:y.name},options:{threadId:r,sourceSeqs:l===null?[]:[l.seq]}})),value:void 0}));let g=i.state(m,r).dispatchedCalls;for(let y of a)h.set(y.call_id,g.get(y.call_id));let w=y=>h.get(y.call_id),x=new Map;for(let y of a){let{dispatchAttempts:$,waits:A}=i.state(m,r),k=lt($,A,y.call_id,w(y),s);k?.policy==="report"&&x.set(y.call_id,{result:Sr(y,k),attempt:k})}let q=y=>i.state(m,r).dispatchedCalls.get(y.call_id)===w(y),S=y=>oe(i.state(m,r).waits.get(w(y))),R=async(y,$,A=[])=>{await i.transact(r,()=>({rows:q(y)&&!(u.aborted&&S(y))?[{type:"tool/result",data:{turn:s,step:o,result:$},options:{threadId:r,sourceSeqs:[w(y),...A]}}]:[],value:void 0}))},E=(y,$)=>{let A=x.get(y.call_id);return R(y,$,A===void 0?[]:[A.attempt.seq])};for(let y of Cr(a,d)){if(p||u.aborted||t.stale())break;let $=await Rr(y,f,x,E);p||=$.stopLater}if(u.aborted)for(let y of a){let $=x.get(y.call_id);$!==void 0?await R(y,$.result,[$.attempt.seq]):await R(y,_(y,"Tool call aborted before dispatch"))}}async function Rr(e,t,r,n){let{runtime:s,signal:o}=t,a=e.exclusive?1:Math.max(s.limits.maxParallelToolCalls,1),u=Array.from({length:e.calls.length}),i=new Map,l=0,f=0,d=!1,h=!1,p=async()=>{for(;f<e.calls.length;){let g=u[f];if(g===void 0)break;g.kind==="result"?await n(e.calls[f],g.result):g.kind==="confirm"?d=h=!0:g.kind==="wait"&&(h=!0),f+=1}},c=()=>{for(;l<e.calls.length&&i.size<a&&!o.aborted&&!d&&!s.stale();){let g=l++,w=e.calls[g];i.set(g,Ar(w,t,r.get(w.call_id)).then(x=>(u[g]=x,g)))}};c();try{for(;i.size>0;){let g=await Promise.race(i.values());i.delete(g),await p(),c()}await p()}catch(g){throw await Promise.allSettled(i.values()),g}return{stopLater:h}}async function Ar(e,t,r){if(r!==void 0)return{kind:"result",result:r.result};if(!Te(e))return{kind:"result",result:Tr(e)};let{runtime:n,threadId:s,agentName:o,environment:a,route:u,signal:i,requestSeq:l}=t,{journal:f}=n,d=n.tool(o,e.name);if(d===void 0)return{kind:"result",result:_(e,`No such tool named "${e.name}"`)};let h=f.state(m,s).dispatchedCalls.get(e.call_id);if(h===void 0)return{kind:"result",result:_(e,`Call ${e.call_id} was dispatched before it was recorded`)};let p=f.state(m,s).waits.get(h),c=p?.value==null||p.answered?null:{dependency:p.declaration.dependency,value:p.value},g=await Er(e,d.tool.onInterrupted,h,c!==null,t);if(g.kind!=="decided")return g;let{authorization:w,attemptSeq:x}=g;if(w.decision==="deny"){let{reasons:q}=w,S=q.length===0?`Tool "${e.name}" was denied.`:`Tool "${e.name}" was denied: ${q.join(" ")}`;return{kind:"result",result:_(e,S)}}if(w.decision==="confirm")return{kind:"confirm"};try{let q=await de(n,s,i,S=>{let R={tool:d.tool,call:e,context:{ctx:n.ctx,signal:i,agentName:o,threadId:s,callId:e.call_id,callSeq:h,requestSeq:l,environment:a,route:u,wait:c,operation:S},toolName:d.name,threadId:s};return le(n,R,()=>R.tool.invoke(R.call,R.context))});if(W(q)){let S=await jr(t,e,h,x,q);return S===null?{kind:"wait"}:{kind:"result",result:_(e,S)}}return{kind:"result",result:q}}catch(q){return i.aborted&&q===i.reason?{kind:"result",result:_(e,`The call was cancelled: ${I(q)}`)}:{kind:"result",result:_(e,I(q))}}}async function Er(e,t,r,n,s){let{runtime:o,threadId:a,agentName:u,turn:i,step:l,signal:f}=s;try{let d=await fe({runtime:o,request:{toolCall:e,agent:o.agent(u),threadId:a},signal:f,approval:()=>Y(o.journal.state(m,a).confirmations,{threadId:a,target:{kind:"model",seq:r}})?.resolution??void 0,record:h=>[{type:"tool/authorization",data:{turn:i,step:l,call_id:e.call_id,call_seq:r,decision:h.decision,confirmed_by:h.confirmedBy,policy:t},options:{threadId:a,sourceSeqs:[r]}},...h.decision==="confirm"?[{type:"confirm/requested",data:{turn:i,step:l,request_id:`cf_${r}`,target:{kind:"model",seq:r},tool_call:e,reason:`Tool '${e.name}' requires user confirmation`},options:{threadId:a,sourceSeqs:[r]}}]:[]]});return d.kind==="rejected"?{kind:"result",result:_(e,d.reason===null?`Tool "${e.name}" was rejected by the user.`:`Tool "${e.name}" was rejected by the user with message: ${d.reason}`)}:d.kind==="unstarted"&&f.aborted&&!n?{kind:"result",result:_(e,"Tool call aborted before dispatch")}:d}catch(d){let h=d instanceof AggregateError?d.errors.map(I).join("; "):I(d);return{kind:"result",result:_(e,`Tool authorization failed: ${h}`)}}}async function jr(e,t,r,n,s){let{runtime:o,threadId:a,turn:u,step:i,signal:l}=e,{journal:f}=o,d=Oe["wait/declared"].safeParse({turn:u,step:i,call_id:t.call_id,call_seq:r,owner:s.owner,dependency:s.dependency,deadline_at:s.deadlineAt,reason:s.reason});if(!d.success)return`Tool "${t.name}" asked to wait with a declaration that is not valid: ${d.error.message}`;let{value:h}=await f.transact(a,()=>{let p=null;return l.aborted?p="Tool call aborted before its wait was recorded":o.waitOwner(s.owner)?f.state(m,a).waits.has(r)&&(p=`Tool "${t.name}" asked to wait again for a call that already waited`):p=`Tool "${t.name}" cannot wait: nothing registered as ${s.owner} would resolve it`,p!==null?{rows:[],value:p}:{rows:[{type:"wait/declared",data:d.data,options:{threadId:a,sourceSeqs:[r,n]}}],value:null}});return h}async function Yt(e){let{runtime:t,threadId:r,agentName:n,environment:s,route:o,turn:a,candidateSeq:u,request:i,signal:l,validate:f}=e,{journal:d}=t,{events:h,value:p}=await d.transact(r,()=>{l.throwIfAborted(),f();let k=[...d.state(m,r).executions.values()].find(G=>G.request.candidate_seq===u&&G.request.owner===i.owner&&G.request.key===i.key);if(k!==void 0){if(JSON.stringify(k.request.operation)!==JSON.stringify(i.operation))throw new Error("Completion request identity changed operation");return{rows:[],value:k.seq}}return{rows:[{type:"execution/requested",data:{turn:a,candidate_seq:u,owner:i.owner,key:i.key,operation:i.operation},options:{threadId:r,sourceSeqs:[u]}}],value:null}}),c=p??h[0].seq,g=d.state(m,r).executions.get(c);if(g.result!==null||g.authorization?.data.decision==="allow")return"settled";let w={call_id:`runtime_${c}`,name:i.operation.name,arguments:i.operation.arguments},x=async k=>(await d.transact(r,()=>({rows:d.state(m,r).executions.get(c).result!==null?[]:[{type:"execution/result",data:{request_seq:c,result:k},options:{threadId:r,sourceSeqs:[c]}}],value:void 0})),"settled"),q=t.tool(n,w.name);if(q===void 0)return x({..._(w,`Runtime ${i.owner}: tool ${w.name} is unavailable or not granted.`),metadata:{runtime_denied:!0}});let S={kind:"runtime",seq:c};if(Y(d.state(m,r).confirmations,{threadId:r,target:S})?.resolution===null)return"blocked";if(g.authorization?.data.decision==="deny")return x({..._(w,`Runtime execution denied: ${g.authorization.data.reasons.join(" ")}`),metadata:{runtime_denied:!0}});let E;try{E=await fe({runtime:t,request:{toolCall:w,agent:t.agent(n),threadId:r,origin:{owner:i.owner,candidateSeq:u,requestSeq:c}},signal:l,validate:f,approval:()=>Y(d.state(m,r).confirmations,{threadId:r,target:S})?.resolution??void 0,record:k=>[{type:"execution/authorization",data:{turn:a,request_seq:c,decision:k.decision,confirmed_by:k.confirmedBy,reasons:"reasons"in k?k.reasons:[]},options:{threadId:r,sourceSeqs:[c]}},...k.decision==="confirm"?[{type:"confirm/requested",data:{turn:a,step:d.state(m,r).turnBoundary.step,request_id:`runtime_${c}`,tool_call:w,target:S,reason:`Runtime ${i.owner} requires confirmation before ${w.name}`},options:{threadId:r,sourceSeqs:[c]}}]:[]]})}catch(k){if(k instanceof T||k instanceof N)throw k;return x(_(w,`Runtime authorization failed: ${I(k)}`))}if(E.kind==="unstarted")throw l.throwIfAborted(),new T;if(E.kind==="rejected")return x({..._(w,E.reason??"Runtime execution was rejected by the person."),metadata:{runtime_denied:!0}});let{authorization:y}=E;if(y.decision==="deny")return x({..._(w,`Runtime execution denied: ${y.reasons.join(" ")||w.name}`),metadata:{runtime_denied:!0}});if(y.decision==="confirm")return"blocked";let $=l.aborted?"cancelled":t.stale()?"activation-changed":null;if($!==null){if(await x({..._(w,$==="cancelled"?`Runtime preparation cancelled before execution: ${I(l.reason)}`:"Runtime preparation was not dispatched because the activation changed."),metadata:{not_dispatched:!0}}),$==="activation-changed")throw new T;return"settled"}let A;try{let k=await de(t,r,l,G=>{let $e={tool:q.tool,call:w,toolName:w.name,threadId:r,context:{ctx:t.ctx,signal:l,agentName:n,threadId:r,callId:w.call_id,callSeq:c,requestSeq:null,environment:s,route:o,wait:null,operation:G}};return le(t,$e,()=>q.tool.invoke(w,$e.context))});A=W(k)?_(w,"Completion operations cannot suspend on a tool dependency."):k}catch(k){if(k instanceof T||k instanceof N)throw k;A=_(w,`Runtime execution interrupted: ${I(k)}`)}return x(A)}function Or(e){try{return e.value===null||e.read()!==e.value}catch{return!0}}var Ie=class{runtime;threadId;agentName;inbox;constructor(t){this.runtime=t.runtime,this.threadId=t.threadId,this.agentName=t.agentName,this.inbox=new V(t.runtime.journal,t.threadId)}stepsTaken(){return this.runtime.journal.state(m,this.threadId).turnBoundary.step}async run(t){let{signal:r,lease:n,served:s}=t;r.throwIfAborted();try{let{journal:o,limits:a}=this.runtime;for(await qe(o,this.threadId,a);;){let u=await this.turn(r,n,s);if(r.aborted||this.runtime.stale())break;let i=o.state(m,this.threadId).turnBoundary.lastReason;if(i===null||!s.continueAfter(i,u))break}}catch(o){if(!(o instanceof H))throw o}}async turn(t,r,n){let{journal:s,limits:o}=this.runtime,a=s.state(m,this.threadId).turnBoundary.lastTurn+1,u=await this.openTurn(a,t,n),i={turn:a,signal:t,route:u.route,lease:r},l,f=null,d="next-turn",h=!1,p=!1;try{for(;;){t.throwIfAborted();let c=X(B(s,this.threadId,d,this.stepsTaken(),a,p),o);if(c.kind==="end"){l=c.reason;break}if(this.runtime.stale()){l={kind:"interrupted",cause:"activation-changed"};break}if(c.kind==="check"){let w=s.state(m,this.threadId).answerCheck;if(w.status!=="pending")throw new Error("Completion has no pending candidate");f={registrations:this.runtime.requiredRegistrations(this.threadId),candidateSeq:w.seq,observations:[]};let x=await this.judge(i,f);if(x!==null){l=x;break}f=null,h&&(p=!0),d="next-step";continue}let g=this.stepsTaken()+1;await s.append("step/start",{turn:a,step:g},{threadId:this.threadId});try{c.kind==="ask-model"?await this.askModel(i,g,c.claim):await this.answerCalls(i,g,c.calls)}finally{await s.append("step/end",{turn:a,step:g},{threadId:this.threadId})}d==="next-turn"&&c.kind==="answer-calls"&&(h=!0),d="next-step"}}catch(c){if((c instanceof T||c instanceof N)&&!t.aborted){let w=c instanceof T?"activation-changed":"judgment-invalidated";return await s.append("turn/end",{turn:a,reason:{kind:"interrupted",cause:w}},{threadId:this.threadId}),u.seq}let g=O(c,D);if(l=t.aborted?{kind:"aborted",reason:I(t.reason)}:{kind:"error",error_text:P(c),failure_kind:g?.kind??"other",retry_after_ms:g?.retryAfterMs??null},t.aborted||f===null)await s.append("turn/end",{turn:a,reason:l},{threadId:this.threadId});else if((await this.endJudged(a,l,f)).kind==="interrupted")return u.seq;throw new H(c)}return f===null?await s.append("turn/end",{turn:a,reason:l},{threadId:this.threadId}):await this.endJudged(a,l,f),u.seq}fenced(t){if(this.runtime.stale())return"activation-changed";let r=this.runtime.journal.state(m,this.threadId).answerCheck;if(r.status!=="pending"||r.seq!==t.candidateSeq)return"judgment-invalidated";let n=this.runtime.requiredRegistrations(this.threadId);return t.registrations===null||n!==t.registrations||t.observations.some(Or)?"judgment-invalidated":null}async endJudged(t,r,n){let s=this.threadId,{value:o}=await this.runtime.journal.transact(s,()=>{let a=this.fenced(n),u=a===null?r:{kind:"interrupted",cause:a};return{rows:[{type:"turn/end",data:{turn:t,reason:u},options:{threadId:s}}],value:u}});return o}async openTurn(t,r,n){let{journal:s}=this.runtime,{events:o,value:a}=await s.transact(this.threadId,()=>{r.throwIfAborted();let u=this.threadRoute();if(this.runtime.unavailable(u)!==null)throw new J(u);return{rows:[{type:"turn/start",data:{turn:t,route:u,run_id:n.id,attempt_cutoff:n.attemptCutoff},options:{threadId:this.threadId}}],value:u}});return{route:a,seq:o[0].seq}}threadRoute(){let t=this.runtime.journal.state(m,this.threadId).threadRoute;if(t===null)throw new Error(`Thread ${this.threadId} has no route`);return t}async compact(t){let{journal:r,limits:n}=this.runtime,s=this.threadId;await qe(r,s,n);let{lastTurn:o}=r.state(m,s).turnBoundary;if(B(r,s,"next-turn",0,o+1).unanswered.length>0)throw new L(s,"it has tool calls without results");if(K(r.state(m,s).confirmations,s).length>0)throw new L(s,"a confirmation is open");if(r.state(m,s).answerCheck.status==="pending")throw new L(s,"its answer is still owed its stop checks");if(t.signal.aborted)return{committed:[],ended:"cancelled",reason:I(t.signal.reason)};let a=this.threadRoute();if(this.runtime.unavailable(a)!==null)throw new J(a);let{outcome:u}=await this.prepare({turn:null,step:null,route:a,trigger:"request",queued:[],options:t.options,signal:t.signal,lease:t.lease});return u}prepare(t){return Ht(this.runtime,{...t,threadId:this.threadId,agentName:this.agentName})}async judge(t,r){let{turn:n,signal:s,route:o}=t,{journal:a,limits:u}=this.runtime,i=this.threadId,l=a.state(m,i).answerCheck;if(l.status!=="pending")throw new Error(`Thread ${i} has no answer to judge`);let f=new Set;for(;;){let d=await Ft(this.runtime,{threadId:i,turn:n,answer:l.kind==="reply"?{seq:l.seq,kind:l.kind,text:l.text,finish:l.finish}:{seq:l.seq,kind:l.kind,text:l.text},stepsLeft:Math.max(0,u.maxStepsPerTurn-this.stepsTaken()),signal:s},r.observations);if(s.throwIfAborted(),d.kind==="prepare"){let p=()=>{if(this.runtime.stale())throw new T;let x=a.state(m,i).answerCheck;if(x.status!=="pending"||x.seq!==l.seq||this.fenced(r)!==null)throw new N},c=d.requests[0],g=JSON.stringify([c.owner,c.key]);if(f.has(g))throw new Error(`Completion checker ${c.owner} repeated its settled preparation`);f.add(g);let w=await Yt({runtime:this.runtime,threadId:i,agentName:this.agentName,environment:a.state(m,i).threadRecord.environment,route:o,turn:n,candidateSeq:l.seq,request:c,signal:s,validate:p});if(s.throwIfAborted(),w==="blocked")return{kind:"blocked"};if(this.runtime.stale())throw new T;r.registrations=this.runtime.requiredRegistrations(i),r.observations.length=0;continue}if(d.kind==="accept")return{kind:"completed"};if(d.kind==="reject")return{kind:"rejected",rejections:d.rejections};let{value:h}=await a.transact(i,()=>{let p=this.fenced(r);return p!==null?{rows:[],value:p}:{rows:d.messages.map(c=>({type:"input/message",data:{turn:n,role:c.role,content:c.content,source:c.source},options:{threadId:i,sourceSeqs:c.source_seqs}})),value:null}});if(h==="activation-changed")throw new T;if(h!==null)throw new N;return null}}async askModel(t,r,n){let{turn:s,signal:o,route:a}=t,u=this.threadId,i=await this.prepare({turn:s,step:r,route:a,trigger:"pressure",queued:n,options:null,signal:o,lease:t.lease});if(this.reportFailedDispatch(i),o.throwIfAborted(),this.runtime.stale())throw new T;let{value:l}=await this.runtime.journal.transact(u,()=>{let f=new Set(this.inbox.pending.map(c=>c.id)),d=n.filter(c=>f.has(c.id));return d.length===0&&!B(this.runtime.journal,u,"next-step",r,s).owed?{rows:[],value:!1}:{rows:[...Dt(this.runtime,{threadId:u,turn:s,step:r,route:a,claimed:d}).map(c=>({type:"input/message",data:{turn:s,role:c.role,content:c.content,source:c.source},options:{threadId:u,sourceSeqs:c.source_seqs}})),...d.map(c=>({type:"input/message",data:{turn:s,role:c.role,content:c.content,input_id:c.id,source:c.source},options:{threadId:u}}))],value:!0}});l&&await this.callModel(t,r)}reportFailedDispatch({outcome:t,error:r}){t.ended==="failed"&&Jt(this.runtime,r??new Error(`Thread ${this.threadId}: preparing the surface failed: ${t.reason??"no reason given"}`))}answerCalls(t,r,n){let{turn:s,signal:o,route:a}=t,u=this.runtime.journal.state(m,this.threadId).threadRecord;if(u===null)throw new U(this.threadId);return Kt({runtime:this.runtime,threadId:this.threadId,agentName:this.agentName,environment:u.environment,route:a,turn:s,step:r,calls:n,signal:o})}async callModel(t,r){let{turn:n,signal:s,route:o}=t,{journal:a}=this.runtime,u=z("llm"),i=!1,l,f=()=>l?.attempts??0;try{let d=this.runtime.client(o),h={messages:a.state(m,this.threadId).surface.entries.map(q=>q.message),toolChoice:"auto",...ce(this.runtime,{threadId:this.threadId,agentName:this.agentName,route:o,signal:s,llmCallId:u,purpose:"step"})};l=pe(this.runtime,d,"llm/request",{turn:n,step:r,route:o});let p=await l.call(h);for await(let q of p){if(s.aborted){i=!0;break}this.runtime.chunks.emit({threadId:this.threadId,llmCallId:u,turn:n,step:r,chunk:q})}s.aborted&&(i=!0);let{message:c,finish:g,provider_metadata:w}=await p.completed();i||Nr(o.provider,c,w,f());let x=i&&c.tool_calls.length>0?{...c,tool_calls:[]}:c;await a.append("assistant/message",{turn:n,step:r,llm_call_id:u,response:{message:x,finish:i?"other":g,provider_metadata:w},usage:x.usage,interrupted:i,attempts:f()},{threadId:this.threadId}),i&&s.throwIfAborted()}catch(d){if(F(s,d))throw d;let h=O(d,D),p=h?.kind??"other",c=h?.attempts??f(),g=h?.retryAfterMs??null,w=O(d,he)??O(d,Ce);w!==void 0&&w.partial!==null&&await a.append("assistant/message",{turn:n,step:r,llm_call_id:u,response:{message:w.partial,finish:"other",provider_metadata:w.providerMetadata},usage:w.partial.usage,interrupted:!0,attempts:c},{threadId:this.threadId});let x=P(d);if(await a.append("assistant/attempt",{turn:n,step:r,llm_call_id:u,error_text:x,failure_kind:p,attempts:c,retry_after_ms:g},{threadId:this.threadId}),p==="overflow"&&!s.aborted){let q=await this.prepare({turn:n,step:r,route:o,trigger:"overflow",queued:[],options:null,signal:s,lease:t.lease});if(this.reportFailedDispatch(q),s.throwIfAborted(),q.outcome.committed.length>0)return}throw await a.append("error",{turn:n,step:r,llm_call_id:u,error_text:x,failure_kind:p},{threadId:this.threadId}),d}}};function Nr(e,t,r,n){let s=new Set,o=new Set;for(let i of t.tool_calls)(s.has(i.call_id)?o:s).add(i.call_id);if(o.size===0)return;let a=j({role:"assistant",content:t.content,reasoning_content:t.reasoning_content,usage:t.usage}),u=new he(e,"invalid",a,r,`'${e}' asked for tool calls that share an id: ${[...o].join(", ")}`);throw new D(e,"invalid",n,null,{cause:u})}export{se as a,Gr as b,nt as c,oe as d,Kr as e,K as f,Xr as g,ae as h,nn as i,re as j,J as k,un as l,ln as m,cn as n,Tt as o,tr as p,ie as q,gn as r,m as s,Q as t,U as u,C as v,ne as w,z as x,jt as y,Ot as z,V as A,Kn as B,ts as C,rs as D,ns as E,cr as F,qe as G,zt as H,et as I,We as J,Ve as K,Ge as L,He as M,Ke as N,Ye as O,Qe as P,Xe as Q,L as R,Ze as S,M as T,_ as U,Pr as V,W,ks as X,Dr as Y,Fr as Z,_r as _,Ie as $};
@@ -0,0 +1,24 @@
1
+ import{c as Q}from"./VYMT4TXD.js";import{a as Hn}from"./MNJ4SRF7.js";import{d as le}from"./JFZZXVWD.js";import{a as ae}from"./34KW6VNQ.js";import{a as lt,b as vn}from"./KUZCL2SH.js";import{b as Ln}from"./CQEVREBT.js";import{a as Wn,d as Fn}from"./HK6ZSONF.js";import{a as Oe}from"./7VAPNE3L.js";import{c as In}from"./5IRF47YB.js";import{a as Nn}from"./OL5A6ITQ.js";import{b as oe,d as Mn,e as Dn}from"./JFX2MXBA.js";import{b as qe,c as H,d as Pn}from"./S34ZA2R6.js";import{b as M}from"./6FRNHMCV.js";import{b as Cn,e as K}from"./CUK7CGC7.js";import{$ as An,A as $e,B as mn,C as wn,D as kn,E as bn,F as _n,G as yn,I as xn,K as L,L as Tn,M as jn,N as Se,O as $n,P as Sn,Q as qn,R as On,S as dt,V as ut,W as En,Z as Rn,a as ot,b as ln,c as xe,d as dn,e as un,f as I,g as W,h as Te,i as Y,k as cn,l as hn,m as fn,n as pn,r as gn,s as p,t as ie,u as P,x as N,y as F,z as je}from"./BPRCULZH.js";import{a as T,f as ct}from"./DDANMY45.js";import{b as en,c as $,e as tn,f as ye,g as E,h as ve,z as on}from"./BBCW2FZK.js";import{l as an,n as se}from"./MMNNZCBO.js";import{a as at}from"./G44LG6VL.js";import{d as nn,f as rn,r as sn}from"./D4PQP5MA.js";var Un=(s,e)=>$(s)===$(e),Bn=s=>s.reason==="wait"||s.reason==="constraint"||s.reason==="rejudge"?s.text:null;function ht(s){let e=[];s.approval&&e.push({reason:"approval"}),s.failed&&e.push({reason:"failure"}),s.cancelled&&e.push({reason:"cancellation"}),s.startupDeclined&&e.push({reason:"startup"}),s.missing.length>0&&e.push({reason:"missing"});let t=s.unresolvedWait;return t!==null&&e.push({reason:"wait",callSeq:t.callSeq,owner:t.owner,ownerRegistered:t.registered,deadline:t.deadlineAt,text:Yr(t)}),e}function Yr(s){return s.registered?s.reason:`${s.reason} (its owner ${s.owner} is not registered)`}function Ee(s){let e=s.pending?.causes.some(t=>t.releases)??!1;return s.latestSettlement?.outcome==="failed"&&!e}function X(s){let e=s.latestUserCancel;return e!==null&&(s.latestReleasing===null||s.latestReleasing<e.seq)}var de=s=>s==="user"?"cancelled":"superseded",R=(s,e)=>({kind:"settle",outcome:s,reason:e}),Kr=1,Gn=s=>Math.max(0,Kr+1-Math.max(1,s.interruptions)),Qr={reason:"rejudge",text:"the facts or registrations the answer's stop checks judged under kept changing; it is judged again on the next releasing cause"};function zn(s){let[e]=s.holds.filter(t=>!(s.answeredUnder&&t.reason==="approval"));return e!==void 0?e:s.constraint.kind==="hold"?Re(s.constraint):null}function Re(s){let{owner:e,reason:t,code:n,data:r}=s;return E({reason:"constraint",owner:e,...n===void 0?{}:{code:n},...r===void 0?{}:{data:tn(r)},text:t})}function Vn(s){if(s.cancel!==null)return R(de(s.cancel),"cancel");if(s.constraint.kind==="obsolete")return R("superseded","obsolete");let{ending:e,work:t}=s,n=s.holds.some(a=>a.reason==="approval"),r;switch(e?.kind){case void 0:r=R("completed","nothing");break;case"aborted":return{kind:"hold",hold:{reason:"shutdown"}};case"interrupted":{if(e.cause==="abandoned"){r=R("completed","nothing");break}let a=zn(s);return a!==null?{kind:"hold",hold:a}:s.repairsLeft>0&&t.hasWork?{kind:"repair"}:e.cause==="activation-changed"?R("failed","turn"):{kind:"hold",hold:Qr}}case"error":return R("failed","turn");case"max-steps":case"rejected":if(r=R("failed","turn"),!t.nextStepQueued)return r;break;case"blocked":if(n&&!s.answeredUnder)return{kind:"hold",hold:{reason:"approval"}};r=R("completed","nothing");break;case"completed":if(r=R("completed","answered"),!t.anyQueued)return r;break}let i=zn(s);if(i!==null)return{kind:"hold",hold:i};if(t.hasWork)return{kind:"advance"};if(n)return{kind:"hold",hold:{reason:"approval"}};if(e?.kind==="blocked"&&t.unanswered)throw new Error("A blocked turn left calls that nothing holds and none of which can be dispatched");return r}function Yn(s,e){return s===null||s.runId===e?null:s.runId}function ft(s,e){let{requests:t,turnBoundary:n}=s,r=t.latestTurn;return r?.runId!==e||n.turnOpen||n.lastReason===null?null:{ending:n.lastReason,start:r.seq,attemptCutoff:r.attemptCutoff}}function Xr(s,e){let t=ft(s,e);if(t===null)return null;let{kind:n}=t.ending;if(n==="aborted"||n==="interrupted"&&t.ending.cause==="abandoned")return null;if(n==="completed"||n==="blocked"||n==="interrupted"){let{pending:r}=s.requests;if(r?.causes.some(i=>i.releases&&i.seq>t.start))return null}return t}function Ae(s){let{pending:e,latestTurn:t}=s.requests,n=e===null?null:Xr(s,e.runId);return{resumed:n,ending:n?.ending??null,start:n?.start??t?.seq??null}}import{z as ue}from"zod";var Kn=ue.strictObject({id:ue.string().refine(K,"A role id must contain a dot, such as codex.explore"),basePrompt:ue.string(),tools:ue.array(ue.string())}),Ce="role",Qn=Nn({id:Ce,placement:"creation",schema:Kn,inject:["agents","tools"],definesAgent:s=>s.id,setup(s,e){Cn(s,{name:e.id,basePrompt:e.basePrompt});for(let t of e.tools)Dn(s,t,[e.id])}});import{Service as Er}from"@leuduan/cordis";import{z as Rr}from"zod";import{Service as ns}from"@leuduan/cordis";var Ie=class{admitted=new Map;cancels=new Map;listeners=new Set;closing;report;constructor(e,t){this.closing=e,this.report=t}requireFree(e){this.closing.throwIfAborted();let t=this.admitted.get(e);if(t!==void 0)throw new L(e,t.kind)}admit(e,t,n={}){this.closing.throwIfAborted(),n.signal?.throwIfAborted(),this.requireFree(e);let r=Promise.withResolvers(),i=this.operation(e,t,r,n);return this.admitted.set(e,i),this.publish({thread_id:e,kind:t,phase:"admitted"}),i}operation(e,t,n,r){let i=new AbortController,a=this.admitted,o={threadId:e,kind:t,runId:r.runId??null,controller:i,signal:AbortSignal.any([this.closing,i.signal,...r.signal?[r.signal]:[]]),settled:n.promise,settle:n.resolve,releasing:t==="configure",releasingStarted:Promise.withResolvers(),cancelIntent:null,settlementBuilt:!1,lease:{get held(){return a.get(e)===o}}};return o}async hold(e,t,n={}){let r=this.holding(e),i=!1;try{return await t()}catch(a){throw i=!0,a}finally{try{let d=n.cleanup?.();d!==void 0&&await d}catch(d){this.report(d)}if(n.finalize!==void 0)for(this.setReleasing(r,!0);;){let d=r.cancelIntent;if(await Promise.resolve().then(n.finalize).catch(this.report),r.cancelIntent===d)break}let{threadId:a}=r;this.admitted.get(a)===r&&this.admitted.delete(a);let o=this.cancels.get(a);o?.captured===r&&(o.captured=null,o.writes>0&&this.holdForCancel(a,o)),r.settle();let l=r.kind!=="release"&&r.signal.aborted?"cancelled":i?"failed":"completed";this.publish({thread_id:a,kind:r.kind,phase:"settled",ended:l}),o?.operation!=null&&this.publish({thread_id:a,kind:"cancel",phase:"admitted"}),o!==void 0&&this.finishCancel(a,o)}}setReleasing(e,t){let n=this.holding(e);n.releasing!==t&&(n.releasing=t,t?n.releasingStarted.resolve():n.releasingStarted=Promise.withResolvers())}cancel(e,t,n){let r=this.cancels.get(e);r===void 0&&(r={captured:null,writes:0,operation:null,failed:!1,done:Promise.withResolvers()},this.cancels.set(e,r));let i=this.admitted.get(e),a=i===void 0;a?this.holdForCancel(e,r):i!==r.operation&&(r.captured=i,i.cancelIntent??=n),r.writes+=1;let o=r,l=o.captured;return{capturedRunId:l?.runId??null,settled:o.done.promise,capturedSettles:()=>l!==null&&!l.settlementBuilt,wrote:d=>{d.then(()=>this.wroteCancel(e,o,!1),()=>this.wroteCancel(e,o,!0)),a&&this.publish({thread_id:e,kind:"cancel",phase:"admitted"}),l!==null&&l.kind!=="release"&&l.controller.abort(new Error(t))}}}cancelIntent(e){return e.cancelIntent}settlementBuilt(e){e.settlementBuilt=!0}holdForCancel(e,t){let n=this.operation(e,"cancel",t.done,{});t.operation=n,this.admitted.set(e,n)}wroteCancel(e,t,n){t.writes-=1,n&&(t.failed=!0),this.finishCancel(e,t)}finishCancel(e,t){if(t.writes>0||t.captured!==null)return;this.cancels.get(e)===t&&this.cancels.delete(e);let{operation:n}=t;if(n!==null&&this.admitted.get(e)===n&&this.admitted.delete(e),t.done.resolve(),n===null)return;let r=t.failed?"failed":"completed";this.publish({thread_id:e,kind:"cancel",phase:"settled",ended:r})}holder(e){let t=this.admitted.get(e);return t===void 0?null:Object.freeze({kind:t.kind,runId:t.runId})}isAdmitted(e){return this.admitted.has(e)}isRunning(e){let t=this.admitted.get(e)?.kind;return t==="run"||t==="compact"}isReleasing(e){let t=this.admitted.get(e);return t?.kind==="release"||t?.releasing===!0}inputTarget(e){let t=this.admitted.get(e);return t?.kind==="run"&&!t.signal.aborted&&!t.releasing?"next-step":"next-turn"}settlement(e){return this.admitted.get(e)?.settled??Promise.resolve()}async whenSettled(e){for(;;){let t=this.admitted.get(e);if(t===void 0||this.isReleasing(e))return;await Promise.race([t.settled,t.releasingStarted.promise])}}async drain(){for(;;){let e=[...[...this.admitted.values()].map(t=>t.settled),...[...this.cancels.values()].map(t=>t.done.promise)];if(e.length===0)return;await Promise.all(e)}}onOperation(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}holding(e){let t=this.admitted.get(e.threadId);if(t!==e)throw new Error(`The operation does not hold thread ${e.threadId}`);return t}publish(e){this.listeners.size!==0&&ye(this.listeners,E(structuredClone(e)),this.report)}};function Xn(s){if(s.durable.state==="unknown")return null;if(s.executing)return{state:"running"};if(s.durable.state==="settled"){let{outcome:e,reason:t,errorText:n}=s.durable.settlement;return{state:"settled",outcome:e,reason:t,errorText:n}}return s.held===null?{state:"requested"}:{state:"held",...s.held}}var Pe=class extends Error{threadId;runId;constructor(e,t){super(`Run ${t} of thread ${e} is unknown to the catalog`),this.threadId=e,this.runId=t,this.name="UnknownRunError"}};function pt(s,e,t,n,r){return new Promise((i,a)=>{let o=!1,l=h=>{o||(o=!0,c(),r?.removeEventListener("abort",u),h())},d=()=>{try{let h=s.runState(e,t);h===null?l(()=>a(new Pe(e,t))):n(h)&&l(()=>i(h))}catch(h){l(()=>a(h))}},u=()=>l(()=>a(r.reason)),c=s.onRunEvent(h=>{h.threadId===e&&h.runId===t&&d()});if(r?.aborted)return u();r?.addEventListener("abort",u,{once:!0}),d()})}var gt=s=>s.state==="held"||s.state==="settled";var Ne=class{started=!1;starting;limit=Number.POSITIVE_INFINITY;counted=0;startupDeclined=new Set;owners=new Map;nextSerial=0;dirty=new Set;scheduled=!1;admitting=new Set;preparations=new Set;executing=new Map;waiting=[];holds=new Map;listeners=new Set;preparation=new Map;host;limits;constructor(e,t){this.host=e,this.limits=t}async start(e){if(this.starting!==void 0)throw new Error("ctx.threads.start was already called");let{resume:t,startLimit:n}=e;if(!Number.isSafeInteger(n)||n<1)throw new Error("startLimit must be a positive integer");let r=Promise.withResolvers();this.starting=r.promise,this.limit=n,await Promise.all([...this.owners.values()].map(a=>this.repair(a))),await this.host.journal.flush();let i=Date.now();for(let a of this.host.journal.summaries()){let o=a.pending_run;o!==null&&Jr(t,o.newest_cause_at,i)&&this.startupDeclined.add(a.thread_id)}this.started=!0,r.resolve();for(let a of this.host.journal.summaries())a.pending_run!==null&&this.schedule(a.thread_id)}registerOwner(e){if(this.owners.has(e.owner))throw new Error(`An owner is already registered for ${e.owner}`);let t={registration:e,serial:this.nextSerial+=1,state:e.repair===void 0?"ready":"repairing"};this.owners.set(e.owner,t),this.scheduleRequiring(e.owner),this.starting!==void 0&&this.starting.then(()=>this.repair(t));let n=()=>this.owners.get(e.owner)===t;return{changed:r=>{n()&&(this.holds.delete(r),this.forgetPreparation(r),this.schedule(r))},resolveWait:(r,i)=>n()?this.resolveWait(e.owner,n,r,i):Promise.reject(new Error(`The registration for ${e.owner} was disposed`)),dispose:()=>{if(n()){this.owners.delete(e.owner),this.scheduleRequiring(e.owner);for(let[r,i]of this.holds)i.hold.reason==="constraint"&&i.hold.owner===e.owner&&(this.holds.delete(r),this.schedule(r))}}}}async repair(e){let{registration:t}=e;if(t.repair===void 0)e.state="ready";else{e.state="repairing";try{await t.repair(),e.state="ready"}catch(n){this.host.report(n),e.state={failed:T(n)}}}this.scheduleRequiring(t.owner)}scheduleRequiring(e){let{journal:t}=this.host,n=new Set;for(let r of t.summaries()){if(!n.has(r.thread_id)&&r.requires.includes(e))for(let a of t.origins.subtree(r.thread_id,{self:!0}))n.add(a.thread_id);!r.waits.some(a=>a.owner===e)&&!n.has(r.thread_id)||(this.forgetDecided(r.thread_id,"missing"),this.forgetDecided(r.thread_id,"constraint"),this.forgetDecided(r.thread_id,"wait"),this.forgetPreparation(r.thread_id),this.schedule(r.thread_id))}}isRegistered(e){return this.owners.has(e)}async resolveWait(e,t,{threadId:n,callSeq:r},i){let{journal:a}=this.host;if(a.summary(n)===void 0)return{status:"unknown"};let{value:o}=await a.transact(n,()=>{if(!t())throw new Error(`The registration for ${e} was disposed`);let l=a.state(p,n),d=l.waits.get(r);if(d===void 0||d.declaration.owner!==e)return{rows:[],value:{status:"unknown"}};if(d.value!==null)return{rows:[],value:{status:"resolved-before",value:d.value}};if(d.answered)return{rows:[],value:{status:"closed"}};let u=i(d.declaration);if(u===null)return{rows:[],value:{status:"declined"}};let c={releases:!1,chain:u.chain??"reactive"};return{rows:[{type:"wait/resolved",data:{call_seq:r,value:u.value},options:{threadId:n,sourceSeqs:[d.declaration.seq,...u.evidence??[]]}},...F(n,l.requests.pending,c,null).rows],value:{status:"resolved"}}});return o}onRow(e,t){if(t.type==="run/cause"&&t.data.releases){this.forgetPreparation(e);for(let n of this.host.journal.origins.subtree(e,{self:!0}))this.startupDeclined.delete(n.thread_id)&&(this.forgetDecided(n.thread_id,"startup"),this.forgetPreparation(n.thread_id),this.schedule(n.thread_id))}if(t.type==="run/requested"&&this.publish({threadId:e,runId:t.data.run_id,state:"requested"}),t.type==="run/settled"){let n=t.data.run_id;this.executing.get(e)?.runId!==n&&this.publishState(e,n)}for(let n of this.host.journal.origins.callers(e).threads)this.holds.delete(n.thread_id),this.schedule(n.thread_id)}onSettled(e,t){let n=this.executing.get(e);t==="run"&&n!==void 0&&(this.executing.delete(e),this.afterExecution(e,n)),this.schedule(e)}async whenIdle(){await Promise.all([...this.preparations])}close(){for(let e of[...this.preparation.keys()])this.forgetPreparation(e);for(let e of this.host.journal.summaries()){let t=e.pending_run;t!==null&&this.executing.get(e.thread_id)?.runId!==t.run_id&&this.publish({threadId:e.thread_id,runId:t.run_id,state:"held",hold:{reason:"shutdown"},basis:"catalog"})}}onRunEvent(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}runState(e,t){if(this.executing.get(e)?.runId===t)return{state:"running"};let n=this.durable(e,t);if(n.state==="pending"&&this.host.signal.aborted)return{state:"held",hold:{reason:"shutdown"},basis:"catalog"};let r=n.state==="pending"?this.host.journal.summary(e):void 0,i=r===void 0?null:this.idleHold(r,t,this.approvalBlocked(r));return Xn({durable:n,executing:!1,held:i})}inspect(e,t){let n=this.host.journal.summary(e);if(n===void 0)return null;t==="loaded"&&this.requireLoaded(e);let r=this.host.admission.holder(e),i=r===null||r.kind==="run"?null:r.kind,a=this.approvalBlocked(n),o=(u,c=null)=>({state:u,operation:i,hold:c,missing:c?.reason==="missing"?this.missingDetail(e):null,approvalBlocked:a,basis:t});if(this.executing.has(e))return o("running");let l=n.pending_run;if(l===null)return o("idle");let d=t==="loaded"?this.loadedHold(n,l.run_id):this.idleHold(n,l.run_id,a)?.hold??null;return d===null?o("requested"):o("held",d)}requireLoaded(e){let{journal:t}=this.host;for(let{thread_id:n}of t.origins.callers(e).threads)if(!t.isLoaded(n))throw new Error(`Thread ${e} cannot be inspected on the loaded basis: thread ${n} is not loaded`)}loadedHold(e,t){if(e.pending_run?.run_id!==t||this.admitting.has(e.thread_id))return null;let n=this.entryDecision(e.thread_id);return n.kind==="hold"?n.hold:null}approvalBlocked(e){return e.last_reason?.kind!=="blocked"?!1:this.host.journal.origins.subtree(e.thread_id,{self:!0}).some(t=>t.unanswered_confirmations.length>0)}idleHold(e,t,n){let r=e.thread_id,i=this.holds.get(r);if(i?.runId===t)return{hold:i.hold,basis:i.basis};if(e.pending_run?.run_id!==t||this.admitting.has(r))return null;let a=this.verdict(e);if(a.kind==="obsolete"||e.pending_run.cancelled)return null;let o=this.catalogHold(e,n);return o!==null?{hold:o,basis:"catalog"}:a.kind==="hold"?{hold:Re(a),basis:"catalog"}:null}declined(e){return this.startupDeclined.has(e)}missing(e){let{owners:t,chain:n}=this.missingDetail(e);return[...n==="complete"?[]:[`the callers above ${n.at??e} cannot be read`],...t.map(({owner:i,state:a})=>a==="absent"?`${i} is not registered`:a==="repairing"?`${i} is repairing`:`${i} failed to repair: ${a.failed}`)]}missingDetail(e){let{owners:t,chain:n}=this.host.journal.origins.requiredOwners(e);return{chain:n,owners:t.flatMap(({owner:r,introducedBy:i})=>{let a=this.owners.get(r)?.state;return a==="ready"?[]:[{owner:r,state:a??"absent",introducedBy:i}]})}}requiredRegistrations(e){if(this.missing(e).length>0)return null;let{owners:t}=this.host.journal.origins.requiredOwners(e);return JSON.stringify(t.map(({owner:n})=>n).sort().map(n=>[n,this.owners.get(n).serial]))}verdict(e){let t=null;for(let{registration:n,state:r}of this.owners.values()){if(r!=="ready")continue;let i;try{let{constraint:a}=n;if(a?.applies(e)!==!0)continue;i=a.evaluate(e.thread_id)}catch(a){i={kind:"hold",reason:`${n.owner} could not decide: ${T(a)}`}}if(i.kind==="obsolete")return i;i.kind==="hold"&&(t??={...i,owner:n.owner})}return t??{kind:"allow"}}decide(e,{cancel:t,ending:n,start:r}){let{journal:i}=this.host,a=i.summary(e);if(a===void 0)throw new P(e);let o=i.state(p,e),l=o.requests.pending;if(l===null)throw new Error(`Thread ${e} has no pending run to decide for`);let d=i.origins.subtree(e,{self:!0}),u=o.requests.pendingCancel,c=o.inbox;return Vn({pending:l,ending:n,repairsLeft:Gn(o.requests),work:{hasWork:mn(i,e,this.limits),nextStepQueued:c["next-step"].length>0,anyQueued:c["next-step"].length+c["next-turn"].length>0,unanswered:Te(o.surface.entries.map(h=>h.message)).length>0},answeredUnder:r!==null&&d.some(h=>h.answered_at!==null&&h.answered_at>r),holds:this.derivedHolds(e,o,d),constraint:this.verdict(a),cancel:t??(u?.runId===l.runId?u.intent:null)})}entryDecision(e){return this.decide(e,{cancel:null,...Ae(this.host.journal.state(p,e))})}derivedHolds(e,t,n){let r=[...t.waits.values()].find(xe)?.declaration;return ht({approval:t.turnBoundary.lastReason?.kind==="blocked"&&n.some(i=>i.unanswered_confirmations.length>0),failed:Ee(t.requests),cancelled:X(t.requests),startupDeclined:this.declined(e),missing:this.missing(e),unresolvedWait:r===void 0?null:{callSeq:r.call_seq,reason:r.reason,owner:r.owner,deadlineAt:r.deadline_at,registered:this.isRegistered(r.owner)}})}schedule(e){this.dirty.add(e),!this.scheduled&&(this.scheduled=!0,queueMicrotask(()=>{this.scheduled=!1;let t=[...this.dirty];this.dirty.clear();for(let n of t)this.consider(n)}))}consider(e){if(!this.started||this.host.signal.aborted||this.admitting.has(e)||this.executing.has(e))return;let t=this.host.journal.summary(e),n=t?.pending_run??null;if(t===void 0||n===null){this.holds.delete(e),this.forgetPreparation(e);return}if(this.preparation.get(e)?.runId!==n.run_id&&this.forgetPreparation(e),this.host.admission.isAdmitted(e))return;let r=this.verdict(t);if(!(r.kind==="obsolete"||n.cancelled)){let o=this.catalogHold(t,this.approvalBlocked(t));if(o!==null&&o.reason!=="approval")return this.hold(e,n.run_id,o,{decided:!1});if(o===null&&r.kind==="hold")return this.hold(e,n.run_id,Re(r),{decided:!1});let l=this.holds.get(e);if(l?.runId===n.run_id&&l.decided)return}if(this.holds.delete(e),this.preparation.get(e)?.retryAt!=null)return;if(this.counted>=this.limit){this.waiting.includes(e)||this.waiting.push(e);return}if(this.host.signal.aborted)return;let a=this.admit(e).catch(o=>this.host.report(o));this.preparations.add(a),a.then(()=>this.preparations.delete(a))}catalogHold(e,t){let n=e.pending_run;if(n===null)return null;let r=e.waits.find(a=>!a.resolved),[i]=ht({approval:t,failed:e.latest_settlement?.outcome==="failed"&&!n.releasing,cancelled:e.latest_user_cancel!==null&&!e.latest_user_cancel.released,startupDeclined:this.startupDeclined.has(e.thread_id),missing:this.missing(e.thread_id),unresolvedWait:r===void 0?null:{callSeq:r.call_seq,reason:r.reason,owner:r.owner,deadlineAt:r.deadline_at,registered:this.isRegistered(r.owner)}});return i??null}async admit(e){let{admission:t,journal:n}=this.host;this.admitting.add(e),this.counted+=1;let r,i;try{if(r=await this.host.retain(e),this.host.signal.aborted||t.isAdmitted(e))return;let a=n.state(p,e).requests.pending;if(a===null){this.forgetPreparation(e);return}let o=this.entryDecision(e);if(this.forgetPreparation(e),o.kind==="hold"){o.hold.reason!=="shutdown"&&this.hold(e,a.runId,o.hold,{decided:!0});return}this.holds.delete(e),this.admitting.delete(e);let l;i={runId:a.runId,attemptCutoff:n.head,final:null,errorText:null,decide:h=>this.decide(e,{cancel:l===void 0?null:t.cancelIntent(l),...h})},this.executing.set(e,i),l=t.admit(e,"run",{runId:a.runId});let d=l,u=i,c=t.hold(d,()=>this.host.execute(u,d),{finalize:()=>this.finalize(d,u),cleanup:()=>this.host.cleanup(d)});this.publish({threadId:e,runId:a.runId,state:"running"}),await c.catch(h=>this.host.report(h))}catch(a){this.host.report(a),i===void 0&&this.retryLater(e)}finally{this.admitting.delete(e),i!==void 0&&this.executing.get(e)===i&&(this.executing.delete(e),this.afterExecution(e,i)),this.counted-=1,r?.release(),i!==void 0&&this.schedule(e),this.drain()}}async finalize(e,t){let{admission:n,journal:r}=this.host,{threadId:i}=e;if(!r.isLoaded(i)){n.settlementBuilt(e);return}await r.transact(i,()=>{n.settlementBuilt(e);let a=r.state(p,i),o=a.requests.pending;if(o?.runId!==t.runId)return{rows:[],value:void 0};let l=a.requests.pendingCancel?.runId===o.runId?a.requests.pendingCancel:null,d=n.cancelIntent(e)??l?.intent??null,u=d===null?t.final:{kind:"settle",outcome:de(d),reason:"cancel"};if(u?.kind!=="settle")return{rows:[],value:void 0};let c=pn(o,{outcome:u.outcome,reason:u.reason,attemptCutoff:t.attemptCutoff,cancelSeq:l?.seq??null},h=>Y(a,h).state);return{rows:[{type:"run/settled",data:{run_id:o.runId,outcome:u.outcome,reason:u.reason,error_text:u.reason==="setup"?t.errorText??"the run failed before a turn":null,through:r.head,residual:c},options:{threadId:i}},...c.length===0?[]:[{type:"run/requested",data:{run_id:N("run")},options:{threadId:i}}]],value:void 0}})}retryLater(e){let t=this.host.journal.summary(e)?.pending_run?.run_id;if(this.host.signal.aborted||t===void 0)return;let n=this.preparation.get(e);n?.timer!=null&&clearTimeout(n.timer);let r=n?.runId===t?n.attempts+1:1,i=Math.min(6e4,500*2**(r-1)),a={runId:t,attempts:r,retryAt:Date.now()+i,timer:null};a.timer=setTimeout(()=>{this.preparation.get(e)===a&&(a.retryAt=null,a.timer=null,this.schedule(e))},i),a.timer.unref?.(),this.preparation.set(e,a)}forgetPreparation(e){let t=this.preparation.get(e);t!==void 0&&(t.timer!==null&&clearTimeout(t.timer),this.preparation.delete(e))}afterExecution(e,{runId:t,final:n}){let r=this.durable(e,t);if(r.state==="settled")return this.publishState(e,t);if(r.state!=="pending")return;if(this.host.signal.aborted)return this.publish({threadId:e,runId:t,state:"held",hold:{reason:"shutdown"},basis:"catalog"});if(n?.kind==="hold"&&n.hold.reason!=="shutdown")return this.hold(e,t,n.hold,{decided:!1,always:!0,basis:"loaded"});let i;try{i=this.entryDecision(e)}catch(a){this.host.report(a);return}i.kind==="hold"&&i.hold.reason!=="shutdown"&&this.hold(e,t,i.hold,{decided:!0,always:!0})}hold(e,t,n,r){let i=this.holds.get(e),a=r.basis??(r.decided?"loaded":"catalog");this.holds.set(e,{runId:t,hold:n,decided:r.decided,basis:a}),!(r.always!==!0&&i?.runId===t&&Un(i.hold,n))&&this.publish({threadId:e,runId:t,state:"held",hold:n,basis:a})}forgetDecided(e,t){let n=this.holds.get(e);n?.decided===!0&&n.hold.reason===t&&this.holds.delete(e)}drain(){for(;this.counted<this.limit&&this.waiting.length>0;){let e=this.waiting.shift();this.consider(e)}}durable(e,t){let{journal:n}=this.host;if(n.isLoaded(e))return fn(n.state(p,e).requests,t);let r=n.summary(e);if(r?.pending_run?.run_id===t)return{state:"pending"};let i=r?.latest_settlement;return i?.run_id!==t||i===void 0||i===null?{state:"unknown"}:{state:"settled",settlement:{runId:t,seq:0,outcome:i.outcome,reason:i.reason,errorText:i.error_text,through:0,residual:[]}}}publishState(e,t){let n=this.runState(e,t);n!==null&&this.publish({threadId:e,runId:t,...n})}publish(e){ye([...this.listeners],Object.freeze(e),t=>this.host.report(t))}};function Jr(s,e,t){return s==="all"?!1:s==="none"||e===null?!0:t-Date.parse(e)>s.newerThanMs}var ce=(s,e)=>$(s)===$(e),he=s=>[...new Set(s??[])].sort();function Le(s,e){let{agent:t,origin:n,birth:r,reuse:i}=e;if(r.from==="exact"){let{spec:d}=r;return{agent:t,origin:n,spec:{route:at.parse(d.route),environment:{cwd:Q(d.environment.cwd,"A thread cwd")},installations:s.presets.initialInstallations(d.installations.map(({installation_id:u,preset_id:c,config:h,lifetime:f})=>({presetId:c,config:h,installationId:u,lifetime:f})),t),requires:he(d.requires)}}}let a=r.installations??[];if(i==="configuration"){let d=a.find(u=>u.installationId===void 0);if(d!==void 0)throw new Error(`A creation reused by configuration must name its installations: ${d.presetId} has no id`)}let o=r.from==="caller"&&n!==null?s.journal.summary(n.caller_thread_id):void 0,l=s.presets.initialInstallations(a,t);return{agent:t,origin:n,spec:{route:at.parse(r.route),environment:{cwd:Q(r.environment?.cwd??o?.environment.cwd??s.defaultCwd,"A thread cwd")},installations:r.from==="caller"&&n!==null?[...l,...s.handedDown(t,l,n.caller_thread_id)]:l,requires:he(r.requires)}}}function Jn(s,e){return{environment:{cwd:Q(e.environment?.cwd??s.environment.cwd,"A thread cwd")},requires:he(e.requires)}}function Zn(s,e){let t=s.stateAt(ie("threadRoute"),e.threadId,e.seq);if(t===null)throw new Error(`Thread ${e.threadId} has no route at row ${e.seq}`);let{current:n}=s.stateAt(ie("installations"),e.threadId,e.seq);return{route:t,installations:[...n.values()].map(({installationId:r,presetId:i,config:a,lifetime:o})=>({installation_id:r,preset_id:i,config:a,lifetime:o}))}}function er(s,e){if(s.kind==="fresh"){let{agent:o,origin:l,spec:d}=s.opening;return{agent_name:o,metadata:e,origin:l,environment:{cwd:d.environment.cwd},installations:d.installations.map(u=>({...u})),requires:[...d.requires],route:{...d.route}}}let{agent:t,origin:n,cut:r,environment:i,requires:a}=s.opening;return{agent_name:t,metadata:e,fork:{thread_id:r.threadId,seq:r.seq},origin:n,environment:i,requires:a,route:null}}function Me(s,e){let t=[],n=s.fork===null?"fresh":"fork";if(n!==e.kind&&t.push({field:"kind",recorded:n,requested:e.kind}),s.agent_name!==e.agent&&t.push({field:"agent",recorded:s.agent_name,requested:e.agent}),ce(s.origin,e.origin)||t.push({field:"origin",recorded:s.origin,requested:e.origin}),s.fork!==null&&e.cut!==void 0){let r={threadId:s.fork.thread_id,seq:s.fork.seq};ce(r,e.cut)||t.push({field:"cut",recorded:r,requested:e.cut})}return t}function tr(s,e){let t=[],n=(r,i,a)=>{ce(i,a)||t.push({field:r,recorded:i,requested:a})};return n("route",s.route,e.route),n("environment",s.environment,e.environment),n("installations",s.installations??[],e.installations),n("requires",he(s.requires),e.requires),t}function nr(s,e){let t=[];return ce(s.environment,e.environment)||t.push({field:"environment",recorded:s.environment,requested:e.environment}),ce(he(s.requires),e.requires)||t.push({field:"requires",recorded:[...s.requires],requested:e.requires}),t}function fe(s,e){if(e.length>0)throw new Se(s,e)}var Zr={releases:!1,chain:"person"},De=class{inbox;service;admission;id;journal;constructor(e,t,n,r){this.service=e,this.admission=t,this.id=n,this.journal=r,this.inbox=new $e(r,n)}async read(e){let t=await this.service.retain(()=>[this.id],{lastRelease:"keep"});try{let n=e(this.service.view(this.id));if(typeof n?.then=="function")throw new TypeError("thread.read takes a synchronous reader; to read across awaits, hold the thread with ctx.threads.retain");return n}finally{t.release()}}get ctx(){return this.service.contextOf(this.id)}get signal(){return this.service.signalOf(this.id)}whenReady(){return this.service.whenReady(this.id)}configure(e){return this.service.configure(this.id,e)}close(){return this.service.close(this.id)}get summary(){let e=this.journal.summary(this.id);if(e===void 0)throw new ReferenceError(`Unknown thread: ${this.id}`);return e}get agentName(){return this.summary.agent_name}get metadata(){return this.summary.metadata}get origin(){return this.summary.origin}get depth(){return this.journal.origins.callers(this.id).threads.filter(e=>e.origin!==null).length}get originRoot(){let{threads:e,chain:t}=this.journal.origins.callers(this.id);return t==="complete"&&e.length>0?e[e.length-1].thread_id:null}get environment(){return this.summary.environment}get forkedFrom(){let{fork:e}=this.summary;return e===null?null:{threadId:e.thread_id,seq:e.seq}}get lineageRoot(){return en(this.journal.summaryMap(),this.id).at(-1)?.thread_id??this.id}lastOutcome(){return this.summary.last_reason}fork(e){return this.service.fork(this.id,e)}rebuildPrompt(){return this.service.rebuildPrompt(this.id)}on(e){return this.journal.subscribe(t=>t.thread_id===this.id?e(t):void 0)}onChunk(e){return this.service.chunks.subscribe(t=>{t.threadId===this.id&&e(t)})}send(e,t={}){return this.inbox.send(e,()=>this.admission.inputTarget(this.id),t,this.service.routes)}withdraw(e,t={}){return this.inbox.withdraw(e,t)}async answer(e,t={}){await this.journal.transact(this.id,()=>{let{confirmations:n}=this.journal.state(p,this.id),r=new Set(I(n,this.id).map(o=>o.request_id)),i=new Set;for(let{request_id:o}of e){if(i.has(o))throw new Error(`A batch of answers names request_id=${o} twice on thread ${this.id}`);if(i.add(o),r.has(o))continue;let l=n.get(o)?.resolution;throw l!=null?new qn(this.id,o,l):new Error(`Unknown pending confirmation request_id=${o} on thread ${this.id}`)}let a=t.wake===!0?F(this.id,this.pendingRun(),Zr,null).rows:[];return{rows:[...mt(this.id,e),...a],value:void 0}})}async resume(e={}){let t=e.route===void 0?{}:{route:e.route},{value:n}=await this.journal.transact(this.id,()=>{let r=F(this.id,this.pendingRun(),t,null,this.service.routes);return{rows:r.rows,value:r.runId}});return n}closeWaitRows(e){return un(this.journal.state(p,this.id).waits).map(({declaration:t})=>{let n=this.journal.eventAt(t.call_seq);if(n?.type!=="tool/call")throw new Error(`The wait at ${t.seq} on thread ${this.id} cites no call at ${t.call_seq}`);return{type:"tool/result",data:{turn:t.turn,step:t.step,result:{call_id:t.call_id,name:n.data.name,output:`The call was cancelled while it waited: ${e}`,is_error:!0,notes:null,metadata:{wait_cancelled:!0}}},options:{threadId:this.id,sourceSeqs:[t.call_seq,t.seq]}}})}pendingRun(){return this.journal.state(p,this.id).requests.pending}async revokeApprovals(e,t=null){await this.journal.transact(this.id,()=>{if(this.admission.isRunning(this.id))throw new L(this.id);let n=new Map(W(this.journal.state(p,this.id),this.id).map(i=>[i.request_id,i])),r=[...new Set(e)];for(let i of r)if(n.get(i)?.resolution?.approved!==!0)throw new Error(`No approved, unfinished confirmation request_id=${i} on thread ${this.id}`);return{rows:mt(this.id,r.map(i=>({request_id:i,approved:!1,rejection_message:t}))),value:void 0}})}compact(e={}){return this.service.compact(this.id,e)}async cancel(e,t){let{intent:n}=t,r=this.admission.cancel(this.id,e,n),i=this.journal.transact(this.id,()=>{let a=Yn(this.pendingRun(),r.capturedSettles()?r.capturedRunId:null),o=this.journal.state(p,this.id),l=I(o.confirmations,this.id).filter(u=>u.target.kind==="runtime");return{rows:[{type:"thread/cancel",data:{cancel_id:N("cancel"),intent:n,run_id:r.capturedRunId,reason:e},options:{threadId:this.id}},...this.inbox.clearRows(),...mt(this.id,l.map(u=>({request_id:u.request_id,approved:!1,rejection_message:`Runtime preparation cancelled: ${e}`}))),...[...o.executions.values()].flatMap(u=>u.result!==null||u.authorization?.data.decision==="allow"?[]:[{type:"execution/result",data:{request_seq:u.seq,result:{call_id:`runtime_${u.seq}`,name:u.request.operation.name,output:`Runtime preparation cancelled before execution: ${e}`,is_error:!0,notes:null,metadata:{not_dispatched:!0}}},options:{threadId:this.id,sourceSeqs:[u.seq]}}]),...this.closeWaitRows(e),...t.rows?.(this.id)??[],...a===null?[]:[{type:"run/settled",data:{run_id:a,outcome:de(n),reason:"cancel",error_text:null,through:this.journal.head,residual:[]},options:{threadId:this.id}}]],value:void 0}});if(r.wrote(i),t.until==="recorded"){await i;return}try{await i}finally{await r.settled}}},mt=(s,e)=>e.map(t=>({type:"confirm/resolved",data:{request_id:t.request_id,approved:t.approved,rejection_message:t.rejection_message??null},options:{threadId:s}}));import{createScope as es,FiberState as wt,scopeTarget as ts}from"@leuduan/cordis";var We=class{scope;target;runtime;loop;readiness;controller=new AbortController;failed=!1;prepared=!1;readyTree;staleBecause;draining=!1;closingDone;service;admission;thread;released;constructor(e,t,n,r,i,a){this.service=e,this.admission=t,this.thread=r,this.released=a,this.scope=es(n),this.target=ts(this.scope.ctx),this.runtime={...i(this.scope.key),ctx:this.scope.ctx,target:this.target,signal:this.controller.signal,stale:()=>this.isStale(),strategy:()=>Rn(this.scope.ctx,r.id)},this.loop=new An({runtime:this.runtime,threadId:r.id,agentName:r.agentName});let o=this.scope.ctx.fiber;o.beforeUnload(()=>(this.controller.abort(new Error(`Thread ${r.id} context is closing`)),this.admission.whenSettled(r.id))),this.readiness=this.observe(Promise.resolve().then(async()=>{await o.await(),this.controller.signal.throwIfAborted(),await this.service.load(r.id),this.controller.signal.throwIfAborted();let l=n.parallel(this.target,"lagent/thread/activate",r,this.controller.signal);await Promise.resolve();let u=(await Promise.allSettled([l,n.presets.restore(r)])).flatMap(h=>h.status==="fulfilled"?[]:h.reason instanceof AggregateError?h.reason.errors:[h.reason]);if(u.length===1)throw u[0];if(u.length>1)throw new AggregateError(u,`Thread ${r.id} could not be activated`);let c=await this.settle();this.prepared=!0,this.watchTree(c)}))}watchTree(e){this.readyTree=e;for(let t of e.slice(1))t.beforeUnload(()=>this.markStale(`plugin ${t.name} was unloaded`))}markStale(e){this.staleBecause??=e}isStale(){if(this.staleBecause!==void 0)return!0;if(this.readyTree===void 0||this.closingDone!==void 0)return!1;let t=this.scope.ctx.fiber.tree().filter(r=>!this.readyTree.includes(r));if(t.length===0)return!1;let n=t.map(r=>r.name).join(", ");return this.markStale(`${n} mounted after it was ready`),this.scope.ctx.reportError(new Error(`Thread ${this.thread.id}: ${n} mounted through thread.ctx after the thread was ready; a thread's plugins come from its activate listeners and installations, so its next operation activates it afresh without them`)),!0}get activating(){return this.failed?!1:this.prepared?this.scope.ctx.fiber.tree().some(e=>e.transition!==void 0):!0}observe(e){return e.catch(t=>{if(this.failed=!0,!this.admission.isAdmitted(this.thread.id)&&!this.draining){let n=this.scope.ctx.fiber.tree().some(r=>r.state===wt.FAILED&&r.error===t);!this.controller.signal.aborted&&!n&&this.scope.ctx.reportError(t),this.service.releaseFailed(this.thread.id).catch(r=>this.scope.ctx.reportError(r))}}),e}get signal(){return this.controller.signal}get hasFailed(){return this.failed}get closed(){return this.closingDone}async settle(){let e=await this.scope.ctx.fiber.awaitTree();this.controller.signal.throwIfAborted();for(let t of e)if(t.state!==wt.ACTIVE)throw new Error(`Thread ${this.thread.id}: required plugin ${t.name} is ${wt[t.state]}`);return e}async run(e){let t=AbortSignal.any([this.controller.signal,e.signal]);t.throwIfAborted(),await this.ready(t),await this.loop.run({...e,signal:t})}async compact(e){let{lease:t}=e,n=AbortSignal.any([this.controller.signal,e.signal]);try{await this.ready(n)}catch(r){if(!(n.aborted&&Object.is(r,n.reason)))throw r;return{committed:[],ended:"cancelled",reason:T(n.reason)}}return this.loop.compact({signal:n,lease:t,options:e.options??null})}async ready(e){await ae(this.readiness,e),e.throwIfAborted(),this.runtime.agent(this.thread.agentName),await this.service.load(this.thread.id),await this.service.recordPromptOnce(this.scope.key)}async whenReady(){await this.readiness,await this.service.load(this.thread.id)}stop(e){this.draining=!0,this.controller.abort(e)}async whenIdle(){await this.readiness.catch(()=>{}),await this.scope.ctx.fiber.awaitTree().catch(()=>{})}release(){if(this.closingDone!==void 0)return this.closingDone;let e=Promise.withResolvers();return this.closingDone=e.promise,this.controller.abort(new Error(`Thread ${this.thread.id} context released`)),(async()=>{try{await this.whenIdle(),await this.scope.dispose()}finally{this.released()}})().then(e.resolve,e.reject),this.closingDone}};var Fe=class{inbox;journal;threadId;targetOf;constructor(e,t,n){this.journal=e,this.threadId=t,this.targetOf=n,this.inbox=new $e(e,t)}target(){return E(structuredClone(this.targetOf(this.threadId)))}transcript(){return this.journal.state(p,this.threadId).surface.entries.map(e=>e.message)}messageSeqs(){return this.journal.state(p,this.threadId).surface.entries.map(e=>e.row)}requestBehind(e){return _n(this.journal,e)}originalsBehind(e){return gn(this.journal,e)}forkPoints(){return bn(this.journal,this.threadId)}finalMessage(){return vn(this.journal,this.threadId)}outcomeSince(e){return ln(this.journal,this.threadId,e)}prompt(){return this.journal.state(p,this.threadId).threadPrompt??[]}requestTools(e){if(!this.journal.inLineage(this.threadId,e))throw new Error(`Row ${e.seq} is not part of thread ${this.threadId}'s lineage`);return this.journal.stateAt(ie("threadTools"),e.thread_id,e.seq)??[]}pendingConfirmations(){return E(structuredClone(I(this.journal.state(p,this.threadId).confirmations,this.threadId)))}waits(e={}){let{owner:t}=e,n=[...this.journal.state(p,this.threadId).waits.values()];return E(structuredClone(t===void 0?n:n.filter(r=>r.declaration.owner===t)))}replay(){return this.journal.rows(this.threadId)}replayLineage(){return this.journal.lineage(this.threadId)}queued(){return this.inbox.pending}input(e){return Y(this.journal.state(p,this.threadId),e)}installations(){let{current:e}=this.journal.state(p,this.threadId).installations;return E([...e.values()].map(t=>structuredClone(t)))}};var kt=(s,e)=>s.signal.aborted&&Object.is(e,s.signal.reason),bt=class extends ns{static inject=["journal","agents","tools","llm","prompts","confinement","presets"];chunks;limits;defaultCwd;live=new Map;retentions=new Set;retiring=new Map;admission;owner;retention;chainLimit;handles=new Map;reportedCorrupt=new Set;controller=new AbortController;closing;constructor(e,t){super(e,"threads");let n=r=>e.reportError(r);if(this.chunks=new xn(n),this.admission=new Ie(this.controller.signal,n),this.retention=t.retention,!Number.isInteger(t.chainLimit)||t.chainLimit<1)throw new Error(`chainLimit must be a positive integer, not ${t.chainLimit}`);this.chainLimit=t.chainLimit,this.owner=new Ne({journal:this.journal,admission:this.admission,signal:this.controller.signal,execute:(r,i)=>this.execute(r,i),cleanup:r=>this.cleanup(r),retain:r=>this.retainExecutionReads(r,{retiring:!0}),report:n},t.limits),e.effect(()=>e.confinement.holdReadsWith(async r=>this.journal.summary(r)===void 0?null:this.retain(()=>this.readSet(r),{lastRelease:"keep",waitOn:[r]}))),e.effect(()=>e.journal.subscribe(r=>this.owner.onRow(r.thread_id,r))),e.effect(()=>this.admission.onOperation(r=>{r.phase==="settled"&&this.owner.onSettled(r.thread_id,r.kind)})),this.limits=t.limits,this.defaultCwd=Q(t.cwd,"The core cwd"),qe(e,()=>this.shutdown()),e.effect(()=>this.journal.onRevoked(()=>{this.shutdown().catch(r=>e.reportError(r))}))}get signal(){return this.controller.signal}shutdown(){if(this.closing!==void 0)return this.closing;let e=Promise.withResolvers();this.closing=e.promise;let t=new Error("lagent is closing");this.controller.abort(t),this.owner.close();let n=[...this.live.values()];for(let r of n)r.stop(t);return(async()=>{await this.owner.whenIdle(),await this.admission.drain(),await Promise.all(n.map(r=>r.whenIdle())),await Promise.all(n.map(r=>r.release()))})().then(e.resolve,e.reject),this.closing}list(e={}){let t=e.under===void 0?void 0:this.subtreeIds(e.under),n=e.origin===void 0?void 0:$(e.origin);return this.journal.summaries().filter(r=>!(e.agentName!==void 0&&r.agent_name!==e.agentName||e.callerThreadId!==void 0&&r.origin?.caller_thread_id!==e.callerThreadId||n!==void 0&&$(r.origin)!==n||t!==void 0&&!t.has(r.thread_id))).map(r=>this.handle(r.thread_id))}get(e){return this.journal.summary(e)!==void 0?this.handle(e):void 0}liveThreads(){return[...this.live.keys()].map(e=>this.handle(e))}start(e){return this.owner.start(e)}inspect(e,{basis:t}){return this.owner.inspect(e,t)}onRunEvent(e){return this.owner.onRunEvent(e)}runState(e,t){return this.owner.runState(e,t)}chain(e){return hn(this.journal.state(p,e).chain,this.chainLimit)}registerOwner(e){return this.owner.registerOwner(e)}async releaseUnder(e,t){let n=this.admission.admit(e,"release");await this.under(n,async()=>{await this.settledLive(e),await this.live.get(e)?.release(),await t?.()})}async retain(e,t){let n=[...e()];for(let u of n)this.requireThread(u);let r={members:e};this.retentions.add(r);let i=this.journal.hold(n),a=!1,o=()=>{if(!a&&(a=!0,this.retentions.delete(r),i(),!(t.lastRelease!=="retire"||this.closing!==void 0)))try{for(let u of new Set([...n,...e()]))this.retire(u)}catch(u){this.ctx.reportError(u)}};await Promise.all((t.waitOn??n).map(u=>this.retiring.get(u)));let d=(await Promise.allSettled(n.map(u=>this.load(u)))).find(u=>u.status==="rejected");if(d!==void 0)throw o(),d.reason;return{release:o}}view(e){return new Fe(this.journal,e,t=>this.target(t))}covered(){let e=new Set;for(let t of this.retentions)for(let n of t.members())e.add(n);return e}retire(e){if(this.retiring.has(e)||this.closing!==void 0||!this.journal.isLoaded(e)||this.covered().has(e))return;let t=(async()=>{for(;this.admission.isAdmitted(e);)await this.admission.settlement(e);this.covered().has(e)||await this.close(e)})().catch(n=>{n instanceof L||this.ctx.reportError(n)}).finally(()=>{this.retiring.get(e)===t&&this.retiring.delete(e)});this.retiring.set(e,t)}async close(e){if(this.requireThread(e),this.closing!==void 0){await this.closing,this.journal.unload(e);return}await this.releaseUnder(e,()=>{let t=this.journal.hold([...this.covered()]);try{this.journal.unload(e)}finally{t()}})}async fork(e,t){rr(t.id);let n=this.journal.hold([e]);try{return await this.forkHeld(e,t)}finally{n()}}async forkHeld(e,t){this.controller.signal.throwIfAborted();let{journal:n}=this,r=n.summaryMap();if(!r.has(e))throw new P(e);if(t.before===!0&&t.input===void 0)throw new Error("A fork before a turn needs an input");await n.load(e);let i=t.atTurn===void 0?t.at:kn(n,e,t.atTurn,t.before??!1),a=wn(n,e,i),o=t.id,l=r.get(a.threadId),d=r.get(e),u=t.origin??null,c={kind:"fork",agent:l.agent_name,origin:u,cut:a},h=()=>Jn(d,t),f=r.get(o);if(f!==void 0)return this.reuseFork(f,c,h,t.reuse);let g=sr(o,t),w=await this.originFor(o,t.origin),m={kind:"fork",opening:{agent:l.agent_name,origin:w,cut:a,...h(),inherits:Zn(n,a)}},{value:j}=await n.transact(o,()=>{let C=n.summary(o);return C!==void 0?{rows:[],value:C}:{rows:this.openingGroup(o,m,g,t),value:void 0}});return j===void 0?this.handle(o):this.reuseFork(j,c,h,t.reuse)}reuseFork(e,t,n,r){return fe(e.thread_id,Me(e,t)),r==="configuration"&&fe(e.thread_id,nr(e,n())),this.handle(e.thread_id)}openingGroup(e,t,n,r){let{wake:i}=r,a=i===void 0?null:F(e,null,i,n?.id??null),o=this.journal.head+1,l="next-turn",d=er(t,r.metadata??{}),u={threadId:e,target:l,runId:a?.runId??null,inputId:n?.id??null},c=r.rows?.(t.kind==="fresh"?{kind:"create",...u,opening:E(structuredClone(t.opening))}:{kind:"fork",...u,opening:E(structuredClone(t.opening))})??[];if(je(c))throw new $n(c.refuse,t.kind==="fresh"?"create":"fork");return[{type:"thread/spawned",data:d,options:{threadId:e}},...n===null?[]:[{type:"inbox/spliced",data:{target:l,start:0,inserted:[n]},options:{threadId:e,sourceSeqs:[o]}}],...a?.rows??[],...c]}async create(e,t){let n=rr(t.id);this.controller.signal.throwIfAborted();let{journal:r}=this,i=r.summary(n);if(i!==void 0)return this.reuseFresh(i,e,t);this.requireGlobalAgent(e);let a=await this.originFor(n,t.origin),o=Le(this.birthContext(n),{agent:e,origin:a,birth:t.birth,reuse:t.reuse}),l=sr(n,t),{value:d}=await r.transact(n,()=>{let u=r.summary(n);return u!==void 0?{rows:[],value:u}:{rows:this.openingGroup(n,{kind:"fresh",opening:o},l,t),value:void 0}});return d===void 0?this.handle(n):this.reuseFresh(d,e,t)}birthContext(e){return{journal:this.journal,presets:this.ctx.presets,defaultCwd:this.defaultCwd,handedDown:(t,n,r)=>this.handedDown(e,t,n,r)}}async reuseFresh(e,t,n){let r=n.origin??null;if(fe(e.thread_id,Me(e,{kind:"fresh",agent:t,origin:r})),n.reuse==="configuration"){let i=Le(this.birthContext(e.thread_id),{agent:t,origin:r,birth:n.birth,reuse:"configuration"});fe(e.thread_id,await this.specConflictsOf(e,i.spec))}return this.handle(e.thread_id)}async specConflictsOf(e,t){let n=await this.journal.readRow(e.spawn_seq);if(n?.type!=="thread/spawned")throw new Error(`Row ${e.spawn_seq} is not thread ${e.thread_id}'s spawn`);return tr(n.data,t)}async birthConflicts(e,t){let n=this.requireThread(e),r=Le(this.birthContext(e),{agent:t.agent,origin:n.origin,birth:{from:"exact",spec:t.spec},reuse:"configuration"}),i=Me(n,{kind:"fresh",agent:t.agent,origin:n.origin});return i.length>0?i:this.specConflictsOf(n,r.spec)}async pendingConfirmations(e={}){await this.journal.flush();let t=e.under===void 0?void 0:this.subtreeIds(e.under),n=this.journal.summaries().filter(i=>i.unanswered_confirmations.length>0&&(t===void 0||t.has(i.thread_id))).map(i=>i.thread_id),r=await this.retain(()=>n,{lastRelease:"keep"});try{return Object.freeze(n.flatMap(i=>this.view(i).pendingConfirmations()))}finally{r.release()}}async load(e){let t=this.readSet(e),r=(await Promise.allSettled(t.map(i=>this.journal.load(i)))).find(i=>i.status==="rejected");if(r!==void 0)throw r.reason;this.reportCorrupt(t)}reportCorrupt(e){for(let t of e){if(this.reportedCorrupt.has(t)||!this.journal.isLoaded(t))continue;let n=lt(this.journal,t);n!==null&&(this.reportedCorrupt.add(t),this.ctx.reportError(new dt(t,n.row,n.refusal.message)))}}requireExecutable(e){let t=lt(this.journal,e);if(t!==null)throw new dt(e,t.row,t.refusal.message)}readSet(e){return this.journal.origins.callers(e).threads.map(t=>t.thread_id)}async retainExecutionReads(e,{retiring:t}){this.requireThread(e);let n=this.readSet(e),r=()=>{if(!(!t||this.retention!=="retire")){if(this.admission.isAdmitted(e)){this.admission.settlement(e).then(r);return}try{this.retire(e)}catch(o){this.ctx.reportError(o)}}},i;try{i=await this.retain(()=>n,{lastRelease:"keep",waitOn:[e]})}catch(o){throw r(),o}let a=!1;return{release:()=>{a||(a=!0,i.release(),r())}}}onChunk(e){return this.chunks.subscribe(e)}subtreeIds(e){return new Set(this.journal.origins.subtree(e,{self:!0}).map(t=>t.thread_id))}handedDown(e,t,n,r){let i=this.live.get(r);if(i===void 0||i.closed!==void 0||this.admission.isReleasing(r))throw new Error(`Thread ${e} cannot be created with an origin on thread ${r}, which has no live activation: a child is created by a call running in its caller`);return this.ctx.presets.handedDown(i.scope.key,e,t,n)}async configure(e,t){this.requireThread(e);let n=this.ctx.presets.installationsFor(t.apply??[],"change"),r=[...t.remove??[]],i=t.rebuildPrompt===!0;if(this.admission.requireFree(e),this.live.get(e)?.activating===!0)throw new Sn(e);let a=this.admission.admit(e,"configure");return this.under(a,async()=>{let o=this.journal.hold([e]);try{await this.journal.load(e),a.signal.throwIfAborted();let l=this.ctx.presets.plan(e,n,r),d=()=>({applied:l.applied,removed:l.removed});if(l.rows.length===0)return d();this.refuseRecording(e);let u=this.live.get(e),c=u!==void 0&&u.closed===void 0&&!u.hasFailed||i&&this.journal.state(p,e).threadPrompt!==null;await this.settledLive(e),await this.live.get(e)?.release();let{value:h}=await this.journal.transact(e,()=>{a.signal.throwIfAborted(),this.refuseRecording(e);let f=this.ctx.presets.plan(e,n,r);return{rows:[...f.rows],value:f}});if(l=h,this.admission.setReleasing(a,!1),!c)return d();try{let f=this.activate(e);if(await ae(f.whenReady(),a.signal),i&&this.journal.state(p,e).threadPrompt!==null){a.signal.throwIfAborted();let g=this.renderPrompt(f.scope.key,e);await this.journal.append("thread/prompt",{blocks:g},{threadId:e})}}catch(f){if(kt(a,f))return d();throw new Tn(e,f)}return d()}finally{o()}})}refuseRecording(e){this.controller.signal.throwIfAborted();let t=W(this.journal.state(p,e),e);if(t.length>0){let n=t.map(r=>r.request_id).join(", ");throw new On(e,`it has unfinished confirmations (${n}); answer them, let their calls run, or revoke their approvals first`)}}requireGlobalAgent(e){K(e)||this.ctx.agents.require(void 0,e)}async originFor(e,t){if(t===void 0)return null;let n=se.parse(t);if(this.journal.summary(n.caller_thread_id)===void 0)throw new P(n.caller_thread_id);if(this.handle(n.caller_thread_id).depth+1>this.limits.maxThreadDepth)throw new jn(e,this.limits.maxThreadDepth);return await this.journal.origins.validate(n),n}renderPrompt(e,t){let n=this.journal.summary(t);if(n===void 0)throw new P(t);return this.ctx.prompts.render(e,n.agent_name,{environment:n.environment})}async recordPromptOnce(e){let t=[...this.live.values()].find(r=>r.scope.key===e);if(t===void 0)return;let n=t.thread.id;await this.journal.transact(n,()=>({rows:this.journal.state(p,n).threadPrompt!==null?[]:[{type:"thread/prompt",data:{blocks:this.renderPrompt(e,n)},options:{threadId:n}}],value:void 0}))}async rebuildPrompt(e){this.requireThread(e);let t=this.admission.admit(e,"rebuild");return this.under(t,async()=>{let n=await this.activationFor(e,t);await ae(n.whenReady(),t.signal),t.signal.throwIfAborted();let r=this.renderPrompt(n.scope.key,e);return await this.journal.append("thread/prompt",{blocks:r},{threadId:e}),r})}async whenReady(e){for(this.requireThread(e);;){await this.settledLive(e);let n=this.admission.holder(e);if(n?.kind==="release"||n?.kind==="configure"){await this.admission.settlement(e);continue}let r=this.live.get(e);if(r?.closed===void 0){if(r?.isStale()===!0){n===null?await this.releaseUnder(e):await this.admission.settlement(e);continue}break}}let t=this.activate(e);try{await t.whenReady()}catch(n){throw await this.releaseFailed(e),n}}contextOf(e){return this.activate(e).scope.ctx}signalOf(e){return this.activate(e).signal}activate(e){let t=this.live.get(e);if(t?.closed!==void 0)throw new L(e,"release");if(t===void 0){this.controller.signal.throwIfAborted();let n=this.admission.holder(e);if(n!==null&&this.admission.isReleasing(e))throw new L(e,n.kind);if(this.journal.summary(e)===void 0)throw new P(e);let r=new We(this,this.admission,this.ctx,this.handle(e),i=>this.loopServices(i),()=>{this.live.get(e)===r&&this.live.delete(e)});this.live.set(e,r),t=r}return t}async execute(e,t){let{threadId:n}=t,{decide:r}=e,i;try{if(this.requireExecutable(n),this.requireGlobalAgent(this.requireThread(n).agent_name),i=this.journal.state(p,n).turnBoundary.lastTurn,await this.settledLive(n),this.live.has(n)?await this.journal.flush():await yn(this.journal,n,this.limits),t.signal.throwIfAborted(),this.journal.state(p,n).requests.pending?.runId!==e.runId)return;let a=Ae(this.journal.state(p,n)),o=r(a);if(e.final=o,o.kind!=="advance"&&o.kind!=="repair"){a.resumed!==null&&(e.attemptCutoff=a.resumed.attemptCutoff);return}let l={id:e.runId,attemptCutoff:e.attemptCutoff,continueAfter:(d,u)=>r({ending:d,start:u}).kind==="advance"};for(;o.kind==="advance"||o.kind==="repair";){await(await this.activationFor(n,t)).run({signal:t.signal,lease:t.lease,served:l}),t.signal.throwIfAborted();let u=ft(this.journal.state(p,n),e.runId);o=r({ending:u?.ending??null,start:u?.start??null}),e.final=o}}catch(a){if(kt(t,a)){this.journal.isLoaded(n)&&(e.final=r({ending:{kind:"aborted"},start:null}));return}if(a instanceof cn){e.final={kind:"settle",outcome:"failed",reason:"setup"},e.errorText=ct(a);return}let o=this.journal.isLoaded(n)?this.journal.state(p,n).turnBoundary:null;if(i===void 0||o?.lastTurn===i){e.final={kind:"settle",outcome:"failed",reason:"setup"},e.errorText=ct(a);return}throw e.final={kind:"settle",outcome:"failed",reason:"turn"},a}}target(e){let{threadRoute:t,requests:n}=this.journal.state(p,e);if(t===null)throw new Error(`Thread ${e} has no route`);let r=this.ctx.llm.unavailable(t),{pending:i}=n,a=this.admission.holder(e);return a?.kind==="run"&&i!==null&&a.runId===i.runId?{route:t,blocked:r,selectable:!1}:i===null||r!==null?{route:t,blocked:r,selectable:!0}:{route:t,blocked:r,selectable:Ee(n)||X(n)}}routes={target:e=>this.target(e),resolve:(e,t)=>this.ctx.llm.resolveRoute(e,t)};async compact(e,t){let n=this.requireThread(e);this.requireGlobalAgent(n.agent_name);let r=t;if(t.signal?.aborted===!0)return this.admission.requireFree(e),{committed:[],ended:"cancelled",reason:T(t.signal.reason)};let i=this.admission.admit(e,"compact",{signal:t.signal}),a,o;try{o=await this.under(i,async()=>{try{return a=await this.retainExecutionReads(e,{retiring:!1}),i.signal.throwIfAborted(),this.requireExecutable(e),await(await this.activationFor(e,i)).compact({...r,signal:i.signal,lease:i.lease})}catch(l){if(!kt(i,l))throw l;return{committed:[],ended:"cancelled",reason:T(i.signal.reason)}}})}finally{a?.release()}return!i.signal.aborted||o.ended==="cancelled"||o.ended==="failed"?o:{committed:o.committed,ended:"cancelled",reason:T(i.signal.reason)}}async releaseFailed(e){if(this.closing!==void 0)return;let t=this.admission.holder(e);if(t!==null){t.kind==="release"&&await this.admission.settlement(e);return}let n=this.live.get(e);n===void 0||!n.hasFailed||await this.releaseUnder(e)}async activationFor(e,t){await this.settledLive(e);let n=this.live.get(e);if(n!==void 0&&n.isStale()){this.admission.setReleasing(t,!0);try{await n.release()}finally{this.admission.setReleasing(t,!1)}}return this.activate(e)}async settledLive(e){let t=this.live.get(e)?.closed;t!==void 0&&await t.catch(()=>{})}loopServices(e){let{ctx:t}=this;return{journal:this.journal,chunks:this.chunks,limits:this.limits,unavailable:n=>t.llm.unavailable(n),resolveRoute:(n,r)=>t.llm.resolveRoute(n,r),client:n=>t.llm.clientFor(n),agent:n=>t.agents.require(e,n),toolsFor:n=>t.tools.toolsFor(e,n),tool:(n,r)=>t.tools.toolFor(e,n,r),waitOwner:n=>this.owner.isRegistered(n),requiredRegistrations:n=>this.owner.requiredRegistrations(n)}}get journal(){return In(this.ctx)}under(e,t){return this.admission.hold(e,t,{cleanup:()=>this.cleanup(e)})}cleanup(e){let t=this.live.get(e.threadId);if(!(!(t!==void 0&&(t.hasFailed||t.isStale()))||e.kind==="release"||this.closing!==void 0))return this.admission.setReleasing(e,!0),t.release()}requireThread(e){let t=this.journal.summary(e);if(t===void 0)throw new P(e);return t}handle(e){let t=this.handles.get(e);return t===void 0&&(t=new De(this,this.admission,e,this.journal),this.handles.set(e,t)),t}};function rr(s){if(typeof s!="string"||s.length===0)throw new TypeError("A non-empty thread id is required");return s}function sr(s,e){if(e.input!==void 0)return an(e.input,e.inputId??N("in"));if(e.inputId!==void 0)throw new Error(`Thread ${s} was given an input id but no input`);return null}import{z as _t}from"zod";var ir=_t.strictObject({assignment:_t.string().min(1),generation:_t.number().int().positive()}),pe=class extends Error{constructor(e){super(`Not a delegated assignment cause: ${e}`),this.name="AssignmentKeyError"}};function ar(s,e){return{kind:"assignment",owner:s,key:ir.parse(e)}}function He(s){if(s.kind!=="assignment")throw new pe("the cause is a call");let e=ir.safeParse(s.key);if(!e.success)throw new pe(`${s.owner}'s key is invalid: ${e.error.message}`);return e.data}var rs=s=>s.length<=2e3?s:`\u2026${s.slice(s.length-2e3+1)}`;function J(s){switch(s.kind){case"completed":return{status:"completed",output:s.output};case"failed":{let e=s.latestText;return{status:"failed",output:e===null?s.why:`${s.why}
2
+
3
+ The agent's latest text:
4
+ ${rs(e)}`}}case"stopped":return{status:"failed",output:`The task was stopped: ${s.reason}`}}}function yt(s){let e=s.output.trimStart().split(`
5
+ `,1)[0]??"",t=e.length>200?`${e.slice(0,199)}\u2026`:e;return`the call that opened it was answered${s.is_error?" with an error":""}: ${t}`}function or(s,e,t){let n=`Cannot give an agent another task: ${e.length} of the ${s} task slots of this conversation are in use.`,r=e.filter(a=>a.callerId===t);if(r.length===0)return`${n} None of them is one of your agents: the capacity is held elsewhere. Finish the work with the agents at hand.`;let i=r.map(a=>`thread_id=${a.childId} (task ${a.taskId}, ${a.why})`);return`${n} Your agents holding slots: ${i.join("; ")}. Wait for one with read_agent, or stop one you no longer need with stop_agent, then try again.`}function lr(s){return`Cannot give an agent a task now: the task state of ${s.map(t=>`thread_id=${t.childId} (${t.error})`).join("; ")} cannot be read, so how many task slots are in use is unknown.`}var dr="Cannot give an agent a task now: the conversation this thread belongs to cannot be found, so how many task slots are in use is unknown.";import{z as y}from"zod";import{z as ge}from"zod";var vt=(s,e)=>`${s}/${e}/0`,Ue=(s,e)=>`in_${s}/${e}/0`;function me(s){if(!s.startsWith("in_")||!s.endsWith("/0"))return null;let e=s.slice(3,-2),t=e.lastIndexOf("/"),n=e.slice(0,t),r=Number(e.slice(t+1));return t<=0||!Number.isSafeInteger(r)||r<=0?null:Ue(n,r)===s?{callerThreadId:n,callSeq:r}:null}function ur(s,e,t){for(let r of[s,...e])if(r!==null&&(typeof r!="string"||r.length===0))throw new TypeError("An assignment identity names each of its parts");if(!Number.isSafeInteger(t)||t<=0)throw new TypeError(`A participant generation is a positive integer, not ${t}`);let n=e.map(r=>r===null?"":encodeURIComponent(r));return`${s}/${n.join(":")}:${t}`}var xt=s=>`in_${ur(s.instance,[s.owner,s.attempt,s.assignment],s.generation)}`,Tt=s=>ur(s.instance,[s.owner,s.participant,s.attempt],s.generation),cr=(s,e)=>`${jt(s)}${e}/0`;function ss(s){return me(s.startsWith("steer_")?`in_${s.slice(6)}`:s)}var jt=s=>`steer_${s}/`;function Z(s,e,t){let n=s.threads.get(t);return n===void 0?`No agent ${t}`:n.origin?.caller_thread_id!==e?`Thread ${t} was not started by this thread`:n}function $t(s){let e=s.origin?.cause;return e?.kind!=="assignment"?null:`thread_id=${s.id} works on assignments of ${e.owner}, which alone gives it work, so it cannot be continued or steered; read it with read_agent, or stop it with stop_agent.`}var U="message_agent",D=s=>{switch(s?.kind){case"error":return`Agent error: ${s.error_text}`;case"max-steps":return"Agent reached its step limit without finishing";case"interrupted":return"Agent was interrupted before it finished";case"aborted":return"Agent was cancelled";case"rejected":return`Agent's answer was rejected ${s.rejections.map(e=>`by ${e.source.plugin}: ${e.reason}`).join("; ")}`;default:return"Agent stopped without finishing"}},hr=ge.boolean().default(!1).describe("Run the agent in the background: the call returns at once with its thread_id, a notice tells you when it ends, and meanwhile you check on it with read_agent, message it with message_agent and stop it with stop_agent. Omit to wait for its answer."),is={background:hr,provider:ge.string().nullable().default(null).describe("Optional model provider to run the sub-agent on, from the available routes you were told. Omit to keep the provider: a new sub-agent's is yours, a continued one's its own."),model:ge.string().nullable().default(null).describe("Optional model to run the sub-agent on, such as a cheaper one for simple work; the available routes list each provider's models. Omit to keep the thread's model."),thinking_effort:rn.nullable().default(null).describe("Optional thinking effort for the sub-agent; the available routes list a model's efforts where known. Omit to keep the thread's effort.")};function St(s){let e=ge.object({...s,...is}),t=new Set(Object.entries(e.shape).flatMap(([n,r])=>r.safeParse(null).success?[n]:[]));return ge.preprocess(n=>typeof n!="object"||n===null?n:Object.fromEntries(Object.entries(n).map(([r,i])=>[r,t.has(r)&&typeof i=="string"&&i.trim()===""?null:i])),e)}var qt=s=>({...s.provider===null?{}:{provider:s.provider},...s.model===null?{}:{model:s.model},...s.thinking_effort===null?{}:{thinkingEffort:s.thinking_effort}}),Ot="role";function fr(s,e){let t=e.tools.filter(n=>!s.tools.has(void 0,n));return t.length===0?null:`Role ${e.id} names tools that are not registered: ${t.join(", ")}`}var as=y.discriminatedUnion("op",[y.strictObject({op:y.literal("started"),task_id:y.string().min(1),origin:se,background:y.boolean(),notice:y.boolean(),run_id:y.string().min(1),task:y.string()}),y.strictObject({op:y.literal("stopped"),task_id:y.string().min(1),by:y.enum(["caller","host","ancestor"]),reason:y.string(),call_seq:y.number().int().positive().nullable()}),y.strictObject({op:y.literal("stop_cleaned"),task_id:y.string().min(1)})]),B=M({plugin:"lagent:delegations",kind:"delegation",version:5,schema:as}),z=s=>s.cause.kind==="call"?s.source_seq:null,G=s=>s.cause.kind==="assignment"?s.cause:null;function Be(s,e){let t=null;for(let n of s.byId.values())n.startedSeq<e&&(t===null||n.startedSeq>t.startedSeq)&&(t=n);return t}var Et=s=>s.kind==="completed"||s.kind==="error"||s.kind==="max-steps"||s.kind==="rejected",_=ve({key:"lagent:delegations/tasks",onFork:"reset",init:()=>({byId:new Map,latest:null}),apply(s,e){let t=B.read(e);if(t!==void 0)return os(s,t,e.seq);let n=s.latest;if(n===null||n.settlement!==null)return s;if(e.type==="thread/cancel"&&e.data.intent==="user"&&n.started.origin.cause.kind==="assignment"){let r=`a person cancelled it: ${e.data.reason}`;return n.stop={by:"person",reason:r,call_seq:null},n.settlement={kind:"stopped",reason:r},s}if(e.type==="run/requested")return n.runId=e.data.run_id,s;if(e.type==="run/settled"){let r=e.data;return r.run_id===n.runId&&r.outcome==="failed"&&r.residual.length===0&&(n.settlement=ds(n,r)),s}return e.type==="turn/end"&&(n.ending=e.data.reason),n.claimSeq===null?(e.type==="input/message"&&e.data.input_id===n.started.task_id&&(n.claimSeq=e.seq),e.type==="inbox/spliced"&&e.data.removed.includes(n.started.task_id)&&(n.settlement={kind:"stopped",reason:"its input was discarded before the agent took it"}),s):(ls(n,e),s)}});function os(s,e,t){if(e.op==="started"){let r={started:e,startedSeq:t,runId:e.run_id,claimSeq:null,settlement:null,stop:null,cleaned:!1,answer:ot.init(),latestText:null,ending:null};return s.byId.set(e.task_id,r),s.latest=r,s}let n=s.byId.get(e.task_id);return n===void 0||(e.op==="stopped"?(n.stop=e,n.settlement??={kind:"stopped",reason:e.reason}):n.cleaned=!0),s}function ls(s,e){if(s.answer=ot.apply(s.answer,e),e.type==="assistant/message"&&!e.data.interrupted){let n=sn(e.data.response.message).trim();n!==""&&(s.latestText=n)}if(e.type!=="turn/end")return;let{reason:t}=e.data;s.answer.status==="accepted"?s.settlement={kind:"completed",output:s.answer.text}:t.kind!=="completed"&&Et(t)&&(s.settlement={kind:"failed",why:D(t),latestText:s.latestText})}function ds(s,e){let t=e.error_text??(s.ending===null?null:D(s.ending)),n=t===null?"":` (${t})`;return{kind:"failed",why:s.claimSeq===null?`The task was not delivered${n}. Send it again to retry it.`:`The agent stopped before finishing the task${n}.`,latestText:s.latestText}}function gr(s,e,t){for(let n of s.rowsAfter(e,t))if(n.type==="tool/result"&&n.source_seqs[0]===t)return n.data.result;return null}function mr(s,e,t){return{output:`${s===null?`Gave thread_id=${e} its next task in the background as task_id=${t}.`:`Started ${s} in the background as thread_id=${e}, task_id=${t}.`} Check on it with read_agent, message it with message_agent, stop it with stop_agent.`,metadata:{delegation:{task_id:t,receipt:!0}}}}function we(s,e){let t=s.metadata.delegation;if(s.is_error||typeof t!="object"||t===null||Array.isArray(t))return!1;let n=t;return n.task_id===e&&n.receipt===!0}function ze(s,e){let t=s.state(p,e);return t.turnBoundary.lastReason?.kind==="blocked"?!0:Te(t.surface.entries.map(n=>n.message)).length>0}function Rt(s,e,t){let n=s.state(_,t.childId).byId.get(t.taskId);if(n===void 0||G(n.started.origin)?.owner!==e)return null;let{stop:r}=n;return{settlement:n.settlement,stop:r===null?null:{by:r.by,reason:r.reason},latestText:n.latestText}}function us(s,e){return s.state(_,e.childId).byId.get(e.taskId)?.started.origin??null}function cs(s,e){return s.state(_,e).latest?.startedSeq??null}var hs=y.object({task_id:y.string(),origin:se,run_id:y.string(),background:y.boolean(),notice:y.boolean(),state:y.enum(["open","completed","failed","stopped"]),cleanup_pending:y.boolean(),first_line:y.string()}),pr=120,fs=s=>{let e=s.trimStart().split(`
6
+ `,1)[0].trimEnd();return e.length<=pr?e:`${e.slice(0,pr-1)}\u2026`},S="lagent:delegations",A=s=>s.requires.includes(S),At=Oe({key:"delegation",version:1,schema:hs.nullable(),applies:A,compute(s,e){let t=s.state(_,e).latest;if(t===null)return null;let n=t.settlement?.kind??"open";return{task_id:t.started.task_id,origin:t.started.origin,run_id:t.runId,background:t.started.background,notice:t.started.notice,state:n,cleanup_pending:t.stop!==null&&!t.cleaned,first_line:fs(t.started.task)}}});function V(s,e){let t=k(s,e.thread_id);return t===null||t.state==="unavailable"||t.state==="open"?!1:e.pending_run?.run_id===t.run_id}function k(s,e){let t=At.read(s,e);switch(t.status){case"available":return t.value;case"not-applicable":return null;case"unavailable":return{state:"unavailable",error:t.reason}}}function Ct(s,e){let[t,...n]=s.origins.subtree(e,{self:!0});if(t===void 0)return!1;let r=a=>a.last_reason?.kind==="blocked",i=new Map([[e,{summary:t,parked:r(t)}]]);for(let a of n){let o=a.origin===null?void 0:i.get(a.origin.caller_thread_id);if(o===void 0)continue;let l=k(s,a.thread_id);l===null||l.state!=="open"||l.background&&!o.parked||i.set(a.thread_id,{summary:a,parked:r(a)})}return[...i.values()].some(({summary:a})=>a.unanswered_confirmations.length>0)}var ps=5,It="The task was stopped",gs="an agent it ran under was stopped",wr="the agent that asked for this was stopped",kr={by:"ancestor",reason:"an agent above it was stopped",callSeq:null},Ge=class{stopping=new Set;cleanups=new Map;walks=new Map;validated=new Set;ctx;ready;constructor(e,t){this.ctx=e,this.ready=t}stop(e,t,n){return this.decide(e,t,n,!0)}whenWalked(e){let t=this.walks.get(e)?.walk;return t==null?Promise.resolve():t.catch(()=>{})}blocksOpening(e){return this.walks.has(e)||this.cleanups.has(e)}stopsAffecting(e){return[...this.stopping].filter(t=>t.taskId===e.taskId||t.childId!==e.childId&&this.ctx.journal.origins.isUnder(e.childId,t.childId)).map(t=>t.done)}resume(e){let t=[],n=[],r=this.ctx.journal.origins.subtree(e,{self:!1});for(let i of r){let a=k(this.ctx.journal,i.thread_id);if(a===null||a.state!=="stopped"||!a.cleanup_pending&&this.validated.has(a.task_id)||t.some(l=>this.ctx.journal.origins.isUnder(i.thread_id,l)))continue;t.push(i.thread_id);let o={by:"host",reason:"resuming its cleanup",callSeq:null};n.push(this.stop(i.thread_id,a.task_id,o))}return n}async drain(){await Promise.allSettled([...this.stopping].map(t=>t.done));let e=[...this.walks.values()].flatMap(t=>t.walk===null?[]:[t.walk]);await Promise.allSettled([...e,...this.cleanups.values()])}decide(e,t,n,r){let{journal:i}=this.ctx,a=i.transact(e,()=>{let d=i.state(_,e),u=d.byId.get(t);if(u===void 0)return{rows:[],value:{outcome:null,walk:!1,serving:!1}};let c=u.settlement,h=i.state(p,e).requests.pending?.runId===u.runId,f=this.walks.get(e),g=r&&d.latest===u&&(c===null||c.kind==="stopped")&&(f===void 0||f.taskId===t);if(g&&f===void 0&&this.walks.set(e,{taskId:t,walk:null}),c!==null){let m={taskId:t,childId:e,state:c.kind,cleanupPending:u.stop!==null&&!u.cleaned};return{rows:[],value:{outcome:m,walk:g,serving:h}}}let w={op:"stopped",task_id:t,by:n.by,reason:n.reason,call_seq:n.callSeq};return{rows:[B.entry(w,{threadId:e})],value:{outcome:{taskId:t,childId:e,state:"stopped",cleanupPending:!0},walk:g,serving:h}}}),o=(async()=>{let d;try{d=(await a).value}catch(c){throw this.walks.get(e)?.walk===null&&this.walks.delete(e),c}let{outcome:u}=d;return u===null?null:(d.serving&&this.ctx.threads.get(e)?.cancel(It,{intent:"cleanup"}).catch(c=>{this.ctx.reportError(c)}),d.walk&&this.cleanUp(e),u)})(),l={childId:e,taskId:t,done:o};return this.stopping.add(l),o.finally(()=>this.stopping.delete(l)).catch(()=>{}),o}cleanUp(e){let t=this.walks.get(e);return t===void 0?Promise.resolve():(t.walk??=this.walk(e,t.taskId).then(n=>{n&&this.markValidated(e)}).finally(()=>this.walks.delete(e)),t.walk.catch(n=>this.ctx.reportError(n)),t.walk)}markValidated(e){for(let t of this.ctx.journal.origins.subtree(e,{self:!0})){let n=k(this.ctx.journal,t.thread_id);n!==null&&n.state==="stopped"&&!n.cleanup_pending&&this.validated.add(n.task_id)}}async walk(e,t){await this.ready,await this.ctx.journal.flush();let n=this.ctx.journal.summary(e),r=n===void 0?null:k(this.ctx.journal,n.thread_id);if(r===null||r.state==="unavailable"||r.task_id!==t)return!1;let i=this.workset(e);for(let a of i.flat())this.signal(a);for(let a of i)await Promise.all(a.map(o=>this.quietThread(o)));return!0}workset(e){let t=new Map([[e,0]]),n=[[e]],r=this.ctx.journal.origins.subtree(e,{self:!1});for(let i of r){let a=i.origin===null?void 0:t.get(i.origin.caller_thread_id);a!==void 0&&(t.set(i.thread_id,a+1),this.toQuiet(i)&&(n[a+1]??=[]).push(i.thread_id))}return n.filter(i=>i!==void 0).reverse()}toQuiet(e){let t=k(this.ctx.journal,e.thread_id);return t!==null&&(t.state==="unavailable"||t.state==="open"||t.cleanup_pending)?!0:this.holdsWork(e)||e.has_work||e.turn_open}holdsWork(e){return this.busy(e.thread_id)||e.queued_input>0||e.unanswered_confirmations.length>0}busy(e){let t=this.ctx.threads.inspect(e,{basis:"catalog"});return t!==null&&(t.state==="running"||t.operation!==null)}signal(e){let t=this.ctx.journal.summary(e),n=t===void 0?null:k(this.ctx.journal,t.thread_id),r=i=>this.ctx.reportError(i);n!==null&&n.state==="open"&&this.decide(e,n.task_id,kr,!1).catch(r),this.cancellable(e)&&this.ctx.threads.get(e)?.cancel(It,{intent:"cleanup"}).catch(r)}cancellable(e){let t=this.ctx.journal.summary(e);return t===void 0?!1:this.busy(e)||t.pending_run!==null||t.queued_input>0}quietThread(e){let t=this.cleanups.get(e);if(t!==void 0)return t;let n=this.quiet(e).finally(()=>this.cleanups.delete(e));return this.cleanups.set(e,n),n}async quiet(e){let t=this.ctx.threads.get(e);if(t===void 0)return;let n=await this.ctx.threads.retain(()=>this.ctx.journal.origins.subtree(e,{self:!0}).map(r=>r.thread_id),{lastRelease:"keep"});try{for(let r=1;;r+=1){if(await this.stopOwnTask(e),this.cancellable(e)&&await t.cancel(It,{intent:"cleanup"}),await this.settleConfirmations(t),await this.stopCommands(e),await this.acknowledge(e))return;if(r===ps){let{draining:i,unresolved:a}=le(this.ctx,e,{descendants:!0}),o=[...i,...a],l=o.length===0?"":`: its commands have not ended: ${o.join("; ")}`;throw new Error(`Thread ${e} did not go quiet after a stop${l}`)}}}finally{n.release()}}async stopOwnTask(e){let t=[...this.stopping].filter(i=>i.childId===e).map(i=>i.done);await Promise.allSettled(t);let{journal:n}=this.ctx,r=n.state(_,e).latest;r===null||r.settlement!==null||await this.decide(e,r.started.task_id,kr,!1)}async stopCommands(e){let t=this.ctx.get("commands");if(t===void 0)return;let n=this.ctx.journal.origins.subtree(e,{self:!0});await Promise.all(n.map(r=>t.stopAll({threadId:r.thread_id},gs)))}async settleConfirmations(e){let{journal:t}=this.ctx;for(let n=1;;n+=1){let r=I(t.state(p,e.id).confirmations,e.id),i=W(t.state(p,e.id),e.id).filter(a=>a.resolution?.approved===!0);try{r.length>0&&await e.answer(r.map(a=>({request_id:a.request_id,approved:!1,rejection_message:wr}))),i.length>0&&await e.revokeApprovals(i.map(a=>a.request_id),wr);return}catch(a){if(n===2)throw a}}}async acknowledge(e){let{journal:t}=this.ctx,{value:n}=await t.transact(e,()=>{let r=t.state(p,e),i=r.inbox["next-turn"].length+r.inbox["next-step"].length,a=I(r.confirmations,e).length+W(t.state(p,e),e).length;if(this.busy(e)||i+a>0)return{rows:[],value:!1};if(!this.quietUnder(e))return{rows:[],value:!1};let o=le(this.ctx,e,{descendants:!0});return o.draining.length+o.unresolved.length>0?{rows:[],value:!1}:{rows:[...t.state(_,e).byId.values()].filter(l=>l.stop!==null&&!l.cleaned).map(l=>B.entry({op:"stop_cleaned",task_id:l.started.task_id},{threadId:e})),value:!0}});return n}quietUnder(e){let t=this.ctx.journal.origins.subtree(e,{self:!1});for(let n of t){let r=k(this.ctx.journal,n.thread_id);if(r!==null&&(r.state==="unavailable"||r.state==="open"||r.cleanup_pending)||this.holdsWork(n))return!1}return!0}};var Pt={kind:"allow"};function Nt(s){let{reading:e,authority:t}=s;if(e===null||e.state==="unavailable")return{kind:"hold",reason:e===null?"the task is not recorded":`its task state is unavailable (${e.error})`};if(e.task_id!==s.taskId||e.state!=="open"&&!s.draining)return{kind:"obsolete",reason:"the task has ended"};if(s.stoppedAbove!==null)return{kind:"hold",reason:s.stoppedAbove.why};if(s.obligated||s.stopOnItsWay)return{kind:"hold",reason:"the task, or a thread above it, is being stopped"};if(t.kind==="assignment")return t.verdict.kind==="allow"?Pt:t.verdict;let n=t.background||t.callRunsHere||t.callSuspended,r={kind:"hold",reason:"its call is not waiting for it: it runs once the call is dispatched again"};return e.state!=="open"?n?Pt:r:t.opening==="answered"?{kind:"obsolete",reason:"its call was answered"}:t.background&&t.opening!=="receipt"&&!t.callRunsHere?{kind:"hold",reason:"its receipt is not durable yet"}:n?Pt:r}import{z as ke}from"zod";var _r=120,br=8e3,ms=ke.strictObject({task_id:ke.string().min(1),thread_id:ke.string().min(1),status:ke.enum(["completed","failed"]),summary:ke.string().min(1).max(_r)}),Dt=M({plugin:"lagent:delegations",kind:"notice",version:1,schema:ms}),Ye=s=>Dt.readSource(s),yr=s=>`notice_${s}`,Lt=s=>s.replaceAll("&","&amp;").replaceAll('"',"&quot;").replaceAll("<","&lt;"),ws=(s,e)=>{let t=s.replace(/\s+/g," ").trim();return t.length<=e?t:`${t.slice(0,e-1)}\u2026`};function ks(s){let{childId:e,taskId:t,agent:n,status:r,output:i}=s,a=i.length<=br?i:`${i.slice(0,br-1)}\u2026
7
+ (cut here: read_agent with full: true shows the whole ${r==="completed"?"answer":"failure"})`,o=s.continuable?`
8
+
9
+ To follow up with this agent, message it with message_agent, thread_id "${e}" and kind "continue".`:"",l=`<agent_notification thread_id="${Lt(e)}" task_id="${Lt(t)}" agent="${Lt(n)}" status="${r}">`;return{callerId:s.callerId,callSeq:s.callSeq,taskId:t,text:`${l}
10
+ ${a}${o}
11
+ </agent_notification>`,source:Dt.parse({task_id:t,thread_id:e,status:r,summary:ws(`${n} ${e} ${r}`,_r)})}}function Mt(s,e){let{callerId:t,callSeq:n,taskId:r}=e,i=gr(s,t,n);if(i===null)return"pending-receipt";if(!we(i,r))return"unowed";let a=s.state(p,t);if(s.summary(t)?.origin!=null){let o=Be(s.state(_,t),n);if(o===null||o.settlement!==null)return"unowed"}switch(Y(a,yr(r)).state){case"unknown":return"unsent";case"queued":return"queued";case"claimed":return"claimed";case"discarded":return"spent"}}function ee(s,e,t){let n=me(t);return n?.callerThreadId!==e?null:Mt(s,{callerId:e,callSeq:n.callSeq,taskId:t})}var Wt=s=>s==="unsent"||s==="queued",bs=s=>s==="unowed"||s==="claimed"||s==="spent",Ve=class{noticed=new Set;ctx;constructor(e){this.ctx=e}afterEnding(e){let t=this.ctx.journal.summary(e);if(t===void 0||!A(t))return;let n=k(this.ctx.journal,t.thread_id);if(n===null||n.state==="unavailable"||n.state==="open")return;n.notice&&n.state!=="stopped"&&this.deliver(e,n.task_id).catch(i=>this.ctx.reportError(i));let r;try{r=this.expired(e)}catch(i){this.ctx.reportError(i);return}for(let i of r)this.ctx.threads.get(e)?.withdraw(i).catch(a=>this.ctx.reportError(a))}deliver(e,t){if(this.noticed.has(t))return Promise.resolve();let n=()=>this.noticeOf(e,t);try{return this.send(n())}catch(i){if(!(i instanceof on))return Promise.reject(i)}let r=this.ctx.threads.get(e);return r===void 0?Promise.resolve():r.read(n).then(i=>this.send(i))}async deliverLatest(e){let t=await this.ctx.threads.get(e).read(()=>{let n=this.ctx.journal.state(_,e).latest;return n===null?null:this.noticeOf(e,n.started.task_id)});return t===null?null:(await this.deliver(e,t.taskId),this.ctx.threads.get(t.callerId).read(()=>Mt(this.ctx.journal,t)))}async withdrawExpired(e){let t=this.ctx.threads.get(e);if(t===void 0)return;let n=await t.read(()=>this.expired(e));await Promise.all(n.map(r=>t.withdraw(r)))}async durable(e){let t=e.filter(({state:n})=>n==="completed"||n==="failed"||n==="superseded");await Promise.all(t.map(({task:n})=>this.deliver(n.childId,n.taskId).catch(r=>this.ctx.reportError(r)))),await this.ctx.journal.flush()}resume(e){let t=i=>this.ctx.reportError(i),n=[];for(let i of this.ctx.threads.list({under:e}))i.origin===null||i.summary.queued_input===0||n.push(this.withdrawExpired(i.id).catch(t));let r=this.ctx.journal.origins.subtree(e,{self:!1});for(let i of r){let a=k(this.ctx.journal,i.thread_id);a!==null&&(a.state==="unavailable"&&n.push(this.deliverLatest(i.thread_id).catch(t)),!(a.state!=="completed"&&a.state!=="failed")&&(!a.notice||this.noticed.has(a.task_id)||n.push(this.deliver(i.thread_id,a.task_id).catch(t))))}return n}expired(e){let{inbox:t}=this.ctx.journal.state(p,e),n=this.ctx.journal.state(_,e).latest,r=n?.settlement?.kind==="failed"&&n.claimSeq===null?n.started.task_id:null;return[...t["next-step"],...t["next-turn"]].flatMap(i=>{if(i.id===r)return[i.id];let a=Ye(i.source);return(a===void 0?null:ee(this.ctx.journal,e,a.task_id))==="unowed"?[i.id]:[]})}noticeOf(e,t){let{journal:n}=this.ctx,r=n.state(_,e).byId.get(t);if(r===void 0||!r.started.notice)return null;let i=r.settlement;if(i===null||i.kind==="stopped")return null;let a=n.summary(e);if(a===void 0||!A(a))return null;let o=z(r.started.origin);return o===null?null:ks({callerId:r.started.origin.caller_thread_id,callSeq:o,childId:e,taskId:t,agent:a.agent_name,status:i.kind,output:J(i).output,continuable:!ze(n,e)})}async send(e){if(e===null)return;let t=this.ctx.threads.get(e.callerId);if(t===void 0)return;let n="unsent";((await t.send({role:"developer",content:e.text},{id:yr(e.taskId),source:Dt.record(e.source),wake:{releases:!1,chain:"reactive"},target:"next-step",rows:()=>(n=Mt(this.ctx.journal,e),n==="unsent"?[]:{refuse:{message:`The notice of task ${e.taskId} is not owed (${n})`}})})).status!=="refused"||bs(n))&&this.noticed.add(e.taskId)}};import{z as x}from"zod";var _s=x.discriminatedUnion("op",[x.strictObject({op:x.literal("stop_requested"),obligation_id:x.string().min(1),reason:x.string(),targets:x.array(x.strictObject({task_id:x.string().min(1),child_id:x.string().min(1)}))}),x.strictObject({op:x.literal("stop_completed"),obligation_id:x.string().min(1)})]),be=M({plugin:"lagent:delegations",kind:"stop-obligation",version:1,schema:_s});function Ft(s,e,t){let n={op:"stop_requested",obligation_id:N("stop"),reason:e,targets:t.map(r=>({task_id:r.taskId,child_id:r.childId}))};return be.entry(n,{threadId:s})}var Ke=ve({key:"lagent:delegations/stop-obligations",onFork:"reset",init:()=>new Map,apply(s,e){let t=be.read(e);return t===void 0?s:t.op==="stop_completed"?(s.delete(t.obligation_id),s):(s.set(t.obligation_id,{id:t.obligation_id,seq:e.seq,reason:t.reason,targets:t.targets.map(n=>({taskId:n.task_id,childId:n.child_id}))}),s)}}),Ht=Oe({key:"delegation_stops",version:1,schema:x.array(x.strictObject({obligation_id:x.string(),seq:x.number().int().positive(),reason:x.string(),targets:x.array(x.strictObject({task_id:x.string(),child_id:x.string()}))})),applies:()=>!0,compute:(s,e)=>[...s.state(Ke,e).values()].map(t=>({obligation_id:t.id,seq:t.seq,reason:t.reason,targets:t.targets.map(n=>({task_id:n.taskId,child_id:n.childId}))}))});function te(s,e){let t=Ht.read(s,e);return t.status!=="available"?[]:t.value.map(n=>({id:n.obligation_id,seq:n.seq,reason:n.reason,targets:n.targets.map(r=>({taskId:r.task_id,childId:r.child_id}))}))}function ne(s,e){let t=s.journal.summary(e.childId),n=t===void 0?null:k(s.journal,t.thread_id);return n===null||n.state==="unavailable"?"unavailable":n.task_id===e.taskId?n.state:"superseded"}function Qe(s,e){return e.map(t=>({task:t,state:ne(s,t)})).filter(({state:t})=>t!=="open")}async function Xe(s,e,t){let n={taskId:e.taskId,childId:e.childId};if(t==="open"||t==="unavailable")return{...n,state:t,outcome:null};let i=await s.threads.get(e.childId).read(()=>{let a=s.journal.state(_,e.childId).byId.get(e.taskId);return a===void 0?null:a.settlement});return i===null?{...n,state:"unavailable",outcome:null}:{...n,state:i.kind,outcome:J(i)}}function Je(s,e){let t=s.threads.inspect(e.childId,{basis:"catalog"});if(t?.state==="held"){let{hold:i,missing:a}=t,o=a===null?Bn(i):[...a.chain==="complete"?[]:["its callers cannot be read"],...a.owners.map(({owner:l})=>`${l} is not ready`)].join("; ");return o===null?`it is held (${i.reason})`:`it is held (${i.reason}: ${o})`}let n=s.journal.summary(e.childId),r=n?.latest_settlement??null;return r?.reason==="setup"&&r.error_text!==null?r.error_text:r?.outcome==="failed"&&n?.last_reason!=null?D(n.last_reason):"nothing asks it to run"}import{z as b}from"zod";var vr=b.strictObject({task_id:b.string().min(1),child_id:b.string().min(1)}),xr=b.strictObject({v:b.literal(1),kind:b.literal("task"),...vr.shape}),Tr=b.strictObject({v:b.literal(1),kind:b.literal("read"),tasks:b.array(vr).min(1),until:b.enum(["settled","activity"]),since:b.record(b.string(),b.number().int().nonnegative())}),jr=b.discriminatedUnion("kind",[xr,Tr]),ys=b.strictObject({v:b.literal(1),kind:b.literal("task"),outcome:b.strictObject({status:b.enum(["completed","failed"]),output:b.string()}),run_id:b.string().min(1),state:b.enum(["settled","held"]),reason:b.string(),error_text:b.string().nullable()}),vs=b.enum(["settled","activity","no_progress","timeout"]),xs=b.strictObject({v:b.literal(1),kind:b.literal("read"),why:vs}),$r=s=>({v:1,kind:"task",task_id:s.taskId,child_id:s.childId}),Sr=(s,e)=>({v:1,kind:"task",outcome:{status:s.status,output:s.output},run_id:e.runId,state:e.state,reason:e.reason,error_text:e.errorText}),Ut=s=>s.kind==="task"?[s.child_id]:s.tasks.map(e=>e.child_id),Ze=s=>s.tasks.map(e=>({taskId:e.task_id,childId:e.child_id}));function qr(s){let e=xr.parse(s.dependency),t=ys.parse(s.value);return{childId:e.child_id,outcome:t.outcome}}function Or(s){let e=Tr.parse(s.dependency);return{tasks:Ze(e),why:xs.parse(s.value).why}}var Ts=new Set(["approval","wait","startup","missing","constraint"]);function zt(s,e){let t=Ze(e);return t.map(i=>ne(s,i)).some(i=>i!=="open")?"settled":e.until==="activity"&&t.some(i=>(s.journal.summary(i.childId)?.through_seq??0)>(e.since[i.childId]??0))?"activity":t.some(i=>{let a=s.threads.inspect(i.childId,{basis:"catalog"});return a===null?!1:a.state==="running"||a.state==="requested"?!0:a.state==="held"&&Ts.has(a.hold.reason)})?null:"no_progress"}var Bt=(s,e)=>`${s}:${e}`,et=class{waits=new Map;waitsOn=new Map;checking=new Map;recheck=new Set;retries;deadlines;closing=!1;ctx;options;constructor(e,t){this.ctx=e,this.options=t,this.deadlines=Fn(t.clock,n=>e.reportError(n)),this.retries=Hn(t.clock,n=>e.reportError(n)),e.effect(()=>()=>{this.deadlines.dispose(),this.retries.dispose()})}onRow(e){if(e.type==="wait/declared"){e.data.owner===S&&this.book(e.thread_id,e.data,!1);return}e.type==="wait/resolved"?this.resolved(Bt(e.thread_id,e.data.call_seq)):e.type==="tool/result"&&this.answered(Bt(e.thread_id,e.source_seqs[0]??0)),this.checkWaitsOn(e.thread_id)}onRunEvent(e){this.checkWaitsOn(e)}async repair(){let e=this.ctx.journal.summaries().filter(n=>n.waits.some(r=>r.owner===S));for(let n of e)try{let r=await this.ctx.threads.get(n.thread_id).read(i=>i.waits({owner:S}).filter(dn));for(let i of r)this.book(n.thread_id,i.declaration,!xe(i))}catch(r){this.ctx.reportError(new Error(`The waits of thread ${n.thread_id} cannot be read`,{cause:r}))}let t=[...this.waits].filter(([,n])=>!n.resolved).map(([n])=>n);await Promise.all(t.map(n=>this.check(n)))}async drain(){this.closing=!0,await Promise.allSettled([...this.checking.values()])}book(e,t,n){let r=Bt(e,t.call_seq);if(this.waits.has(r))return;let i=jr.safeParse(t.dependency);if(!i.success){this.ctx.reportError(new Error(`The wait of call ${t.call_seq} on ${e} cannot be read: ${i.error.message}`));return}let a=i.data,o=t.deadline_at,l={callerId:e,callSeq:t.call_seq,dependency:a,resolved:n,overdue:o!==null&&o<=this.options.clock.now()};if(this.waits.set(r,l),!n){for(let d of Ut(a)){let u=this.waitsOn.get(d)??new Set;u.add(r),this.waitsOn.set(d,u)}a.kind==="task"&&this.options.constraint()?.changed(a.child_id),o!==null&&!l.overdue&&this.deadlines.set(r,o,()=>{l.overdue=!0,this.check(r)}),this.check(r)}}resolved(e){let t=this.waits.get(e);t===void 0||t.resolved||(t.resolved=!0,this.stopDeciding(e,t))}answered(e){let t=this.waits.get(e);t!==void 0&&(this.waits.delete(e),t.resolved||this.stopDeciding(e,t),t.dependency.kind==="task"&&this.options.constraint()?.changed(t.dependency.child_id))}stopDeciding(e,t){this.deadlines.delete(e),this.retries.clear(e);for(let n of Ut(t.dependency)){let r=this.waitsOn.get(n);r?.delete(e),r?.size===0&&this.waitsOn.delete(n)}}checkWaitsOn(e){for(let t of this.waitsOn.get(e)??[])this.check(t)}check(e){if(this.closing)return Promise.resolve();let t=this.checking.get(e);if(t!==void 0)return this.recheck.add(e),t;let n=this.resolveIfDue(e).then(()=>this.retries.succeeded(e),r=>{this.ctx.reportError(r),this.retryLater(e)}).finally(()=>{this.checking.delete(e),this.recheck.delete(e)&&this.check(e)});return this.checking.set(e,n),n}async resolveIfDue(e){let t=this.waits.get(e),n=this.options.constraint();if(t===void 0||t.resolved||n===void 0)return;await this.options.ready;let{dependency:r}=t,i={threadId:t.callerId,callSeq:t.callSeq};if(r.kind==="task"){let l={taskId:r.task_id,childId:r.child_id},d=this.taskRun(l);if(d===null)return;let u=await this.taskOutcome(l,d);await n.resolveWait(i,()=>{let c=this.taskRun(l);return c?.runId===d.runId&&c.state===d.state?{value:Sr(u,d)}:null});return}let a=()=>zt(this.ctx,r)??(t.overdue?"timeout":null),o=a();o!==null&&(o==="settled"&&await this.options.notices.durable(Qe(this.ctx,Ze(r))),await n.resolveWait(i,()=>a()===o?{value:{v:1,kind:"read",why:o}}:null))}retryLater(e){let t=this.waits.get(e);this.closing||t===void 0||t.resolved||this.retries.failed(e,()=>{this.check(e)})}taskRun(e){let t=this.ctx.journal.summary(e.childId),n=t===void 0?null:k(this.ctx.journal,t.thread_id);if(n===null||n.state==="unavailable"||n.task_id!==e.taskId)return null;let r=n.run_id,i=this.ctx.threads.runState(e.childId,r);if(i?.state==="settled")return{runId:r,state:"settled",reason:i.reason,errorText:i.errorText};if(i?.state==="held"){let{reason:a}=i.hold;if(a==="cancellation"||a==="failure")return{runId:r,state:"held",reason:a,errorText:null}}return null}async taskOutcome(e,t){if(t.state==="held")return{status:"failed",output:`The agent stopped before finishing the task: ${t.reason==="cancellation"?"a person cancelled the agent":`its run is held (${t.reason})`}.`};let n=await Xe(this.ctx,e,ne(this.ctx,e));if(n.outcome!==null)return n.outcome;if(t.reason==="cancel")return{status:"failed",output:D({kind:"aborted",reason:"cancelled"})};let r=await this.ctx.threads.get(e.childId).read(()=>this.ctx.journal.state(_,e.childId).byId.get(e.taskId)?.claimSeq!=null),i=t.reason==="setup"&&t.errorText!==null?t.errorText:Je(this.ctx,e);return{status:"failed",output:r?`The agent stopped before finishing the task (${i}).`:`The task was not delivered (${i}). Send it again to retry it.`}}};var js=Rr.strictObject({maxOpenTasks:Rr.number().int().min(1),clock:Wn});function $s(s){return s.atLimit?`This conversation has run ${s.turns} turns in a row without a message from the user, so no agent starts from it now. Finish with the agents you have and answer.`:null}var Ss=s=>`This conversation has run ${s.turns} turns in a row without a message from the user, so this read did not wait. Finish with what you have and answer.`,Ar=s=>s===null||Object.values(s).every(e=>e===void 0)?{releases:!0,chain:"fresh"}:{releases:!0,chain:"fresh",route:{select:s}};function Gt(s){if(s.kind==="call"){let{context:e}=s;return{caller_thread_id:e.threadId,source_seq:e.callSeq,cause:{kind:"call"}}}return{caller_thread_id:s.callerThreadId,source_seq:s.grantedSeq,cause:ar(s.registration.owner.name,{assignment:s.assignment,generation:s.generation})}}function Cr(s){let e=s.installations.find(t=>t.lifetime!=="defining"||t.installationId===void 0);return e===void 0?null:`The configuration pinned for an assignment child installs ${e.presetId}, which must be defining and name its id`}var Vt=s=>({kind:"discard",reason:`The ${s.authority.kind==="call"?"call":"start"} was cancelled: ${T(s.signal.reason)}`}),qs=s=>({provider:s.route.provider,model:s.route.model,thinkingEffort:s.route.thinking_effort}),Yt=s=>s.disposed?`Owner ${s.owner.name} was withdrawn, so its assignment opens no task`:null,tt=class extends Er{static inject=["threads","journal","llm","presets","agents"];config;ready=Promise.withResolvers();refreshed=Promise.resolve([]);obligationsRefreshed=Promise.resolve([]);reservations=new Map;openingCalls=new Set;openingResults=new Map;indexedCallers=new Set;carrying=new Map;cleanup;notices;starts=new Map;admitting=new Map;owners=new Map;settledTold=new Set;constraint;waits;closing;constructor(e,t){super(e,"delegations"),this.config=js.parse(t),this.ready.promise.catch(()=>{}),this.cleanup=new Ge(e,this.ready.promise),this.notices=new Ve(e),this.waits=new et(e,{clock:this.config.clock,ready:this.ready.promise,notices:this.notices,constraint:()=>this.constraint}),e.effect(()=>e.journal.register(_)),e.effect(()=>e.journal.register(Ke)),this.obligationsRefreshed=Ht.register(e).refreshed,this.refreshed=At.register(e).refreshed,e.effect(()=>e.journal.subscribe(n=>this.onRow(n))),e.effect(()=>e.threads.onRunEvent(n=>this.onRunEvent(n))),e.effect(()=>{let n=e.threads.registerOwner({owner:S,constraint:{applies:A,evaluate:r=>this.evaluate(r)},repair:()=>this.repair()});return this.constraint=n,n.dispose}),qe(e,()=>this.shutdown())}async[Er.init](){try{await this.refreshed;for(let e of await this.obligationsRefreshed)this.ctx.reportError(new Error(`The stop obligations of thread ${e} could not be recomputed`));this.ready.resolve()}catch(e){throw this.ready.reject(e),e}}delegate(e,t){return this.track(this.runCall(e,t),e.threadId)}track(e,t){return this.starts.set(e,t),e.finally(()=>this.starts.delete(e)).catch(()=>{}),e}registerOwner(e){if(this.owners.has(e.name))throw new Error(`An owner named ${e.name} is already registered`);let t={owner:e,disposed:!1};return this.owners.set(e.name,t),this.ownerChanged(e.name),queueMicrotask(()=>{for(let n of this.ctx.journal.summaries())this.tellSettled(n.thread_id)}),{start:n=>this.startAssignment(t,n),outcome:n=>this.outcome(e.name,n),changed:n=>this.constraint?.changed(n),dispose:()=>{t.disposed||(t.disposed=!0,this.owners.get(e.name)===t&&this.owners.delete(e.name),this.ownerChanged(e.name))}}}ownerChanged(e){for(let t of this.ctx.journal.summaries()){let n=k(this.ctx.journal,t.thread_id);n===null||n.state==="unavailable"||G(n.origin)?.owner===e&&this.constraint?.changed(t.thread_id)}}startAssignment(e,t){let n=e.owner.name,{callerThreadId:r,instance:i,attempt:a,assignment:o,participant:l,generation:d}=t,u=Yt(e)??(this.closing===void 0?null:`Delegations is shutting down, so assignment ${o} opens no task`);if(u!==null)return Promise.resolve({kind:"hold",reason:u});let c={authority:{kind:"assignment",registration:e,callerThreadId:r,assignment:o,generation:d,grantedSeq:t.grantedSeq,configuration:t.configuration},childId:Tt({owner:n,instance:i,participant:l,attempt:t.lifetime==="attempt"?a:null,generation:d}),taskId:xt({owner:n,instance:i,attempt:a,assignment:o,generation:d}),task:t.task,rows:t.rows??null,signal:t.signal};return this.track(this.admit(c),r)}async outcome(e,t){await this.ready.promise;let n=this.ctx.threads.get(t.childId);return n===void 0?null:n.read(()=>Rt(this.ctx.journal,e,t))}tasks(e){return"callerThreadId"in e?this.entriesOf(this.ctx.threads.list({callerThreadId:e.callerThreadId}).map(t=>t.summary)):Nr(this.ctx.journal,e.under)}stopTargets(e){return this.tasks({under:e}).flatMap(t=>t.state!=="unavailable"&&(t.state==="open"||t.draining||t.cleanupPending)?[{taskId:t.taskId,childId:t.childId}]:[])}stopObligationRows(e){return t=>{let n=this.stopTargets(t);return n.length===0?[]:[Ft(t,e,n)]}}async retryStops(e){await this.ready.promise,await Promise.all(te(this.ctx.journal,e).map(t=>this.carryOut(e,t)))}async read(e,t){if(await this.ready.promise,e.wait!==null){let{tasks:c,why:h}=Or(e.wait);return this.readOutcome(c,h,null)}let{tasks:n,until:r,waitSeconds:i}=t,a=Object.fromEntries(n.map(c=>[c.childId,this.ctx.journal.summary(c.childId)?.through_seq??0])),o={v:1,kind:"read",tasks:n.map(c=>({task_id:c.taskId,child_id:c.childId})),until:r,since:a};if(i===0)return this.readOutcome(n,null,null);let l=zt(this.ctx,o);if(l!==null)return this.readOutcome(n,l,null);let{threadId:d}=e,u=await this.ctx.threads.get(d).read(()=>this.ctx.threads.chain(d));return u.atLimit?this.readOutcome(n,null,Ss(u)):ut({owner:S,dependency:o,deadlineAt:this.config.clock.now()+i*1e3,reason:`waiting on ${n.length} agent${n.length===1?"":"s"}`})}async readOutcome(e,t,n){let r=Qe(this.ctx,e);return r.length>0&&await this.notices.durable(r),{tasks:await Promise.all(e.map(i=>Xe(this.ctx,i,ne(this.ctx,i)))),noProgress:t==="no_progress"?e.map(i=>`${i.taskId}: ${Je(this.ctx,i)}`):null,note:n}}async repair(){await this.ready.promise,await this.ctx.journal.flush();let e=this.ctx.journal.summaries().filter(t=>t.origin===null);for(let t of e)await this.repairUnder(t.thread_id);await this.waits.repair()}async repairUnder(e){await this.ready.promise,await this.ctx.journal.flush();let t=i=>this.ctx.reportError(i),n=this.cleanup.resume(e).map(i=>i.catch(t));for(let i of te(this.ctx.journal,e))n.push(this.carryOut(e,i));let r=new Set([e]);for(let i of this.tasks({under:e}))(i.state==="unavailable"||i.state==="open"||i.draining)&&r.add(i.callerId);for(let i of r)await this.reconcile(i).catch(t);n.push(...this.notices.resume(e)),await Promise.all(n)}async stop(e,t){await this.ready.promise;let n=this.childHolding(e)??await this.findChild(e),r=await this.cleanup.stop(n,e,t);if(r===null)throw new Error(`Thread ${n} holds no task ${e}`);return r}async steer(e,t){let{threadId:n,callSeq:r,signal:i}=e,{childId:a,taskId:o,message:l}=t,d=cr(n,r),u=f=>({...f,metadata:{...f.metadata,thread_id:a}}),c=f=>u({output:f,is_error:!0}),h=this.ctx.journal.hold([a]);try{i.throwIfAborted(),await this.ready.promise;let f=this.ctx.threads.get(a),g=$t(f);if(g!==null)return c(g);let w=await f.read(j=>j.input(d));if(w.state!=="unknown")return u({output:Ir(a,w.state)});if(o===null)return c(`thread_id=${a} has no task this call can steer.`);i.throwIfAborted();let m=await f.send(l,{id:d,rows:this.steerRows(a,o)});if(m.status==="refused")return c(m.refusal.message);if(m.status==="known"){let j=await f.read(C=>C.input(d));if(j.state!=="unknown")return u({output:Ir(a,j.state)})}return u({output:`Sent your message to thread_id=${a}, into its running task ${o}: it reads it at its next step. Wait for its answer with read_agent.`})}catch(f){return c(`The message was not sent: ${T(f)}`)}finally{h()}}steerRows(e,t){return({target:n})=>{let{journal:r}=this.ctx,i=r.state(_,e).byId.get(t);if(i===void 0)return{refuse:{message:`thread_id=${e} holds no task ${t}`}};let a=i.settlement,o=`Task ${t} of thread_id=${e}`;return a!==null?{refuse:{message:`${o} has already ended (${a.kind}), so there is nothing running to steer. To give the agent more work, message it with kind "continue".`}}:n==="next-step"?[]:{refuse:{message:`${o} is open, but ${this.notRunning(e)}`}}}}notRunning(e){if(Ct(this.ctx.journal,e))return"it is waiting for an approval, so a steer cannot reach it now: wait for it with read_agent, or stop it with stop_agent.";let t=this.ctx.threads.inspect(e,{basis:"catalog"});return t?.state==="requested"?"its run has not started yet, so a steer cannot reach it now: try again later, wait for it with read_agent, or stop it with stop_agent.":t!==null&&t.operation!==null?"another operation holds the agent, so a steer cannot reach the task: wait for it with read_agent, or stop it with stop_agent.":"nothing is running it now, so a steer cannot reach it: wait for it with read_agent, or stop it with stop_agent."}async runCall(e,t){let{ctx:n,threadId:r,callSeq:i,signal:a}=e,{child:o,selection:l={},background:d=!1}=t,u=o.kind==="start"?o.target:null,c=o.kind==="continue"?o.threadId:vt(r,i),{threads:h}=this.ctx,f=v=>({output:v,is_error:!0}),g=v=>{try{return t.answer?.(v)??(v.status==="failed"?f(v.output):{output:v.output})}catch(re){return this.ctx.reportError(re),f(`Could not format the agent's answer: ${T(re)}`)}},w=v=>({...v,notes:[...v.notes??[],`thread_id=${c}`],metadata:{...v.metadata,thread_id:c}}),m=v=>h.get(c)===void 0?v:w(v),j=v=>w(mr(u===null?null:this.toolNameOf(i)??"the agent",c,v.taskId));if(e.wait!==null)try{return w(g(qr(e.wait).outcome))}catch(v){return w(f(`The recorded answer could not be read: ${T(v)}`))}let C=this.ctx.journal.hold([c]);try{if(await this.ready.promise,a.aborted)return m(f(`The call was cancelled: ${T(a.reason)}`));let v=u===null?Z(n,r,c):null;if(typeof v=="string")return f(v);let re=v===null?null:$t(v);if(re!==null)return w(f(re));let _e=await this.admit({authority:{kind:"call",context:e,target:u,selection:l,background:d},childId:c,taskId:Ue(r,i),task:t.task,rows:t.rows??null,signal:a});if(_e.kind!=="opened")return m(f(_e.reason));let{task:O}=_e;if(_e.replayed){if(O.background)return O.outcome===null&&this.handOff(O),j(O);if(O.outcome!==null&&this.ctx.threads.runState(c,O.runId)?.state==="settled")return w(g(O.outcome));this.openingCalls.add(O.taskId)}if(a.aborted)return w(f(`The call was cancelled: ${T(a.reason)}`));if(this.constraint?.changed(O.childId),O.background)return j(O);let Vr=u===null?U:this.toolNameOf(i)??"the agent";return ut({owner:S,dependency:$r(O),deadlineAt:null,reason:`waiting for ${Vr} on thread_id=${c}`})}catch(v){return m(g({status:"failed",output:T(v)}))}finally{C()}}handOff(e){this.openingCalls.add(e.taskId),this.constraint?.changed(e.childId)}toolNameOf(e){try{let t=this.ctx.journal.eventAt(e);return t?.type==="tool/call"?t.data.name:null}catch{return null}}admit(e){let{authority:t,taskId:n}=e;if(t.kind==="call")return this.admitOnce(e);let r=$({origin:Gt(t),childId:e.childId,task:e.task,configuration:t.configuration}),i=this.admitting.get(n);if(i?.key===r)return i.admission;let o=(i===void 0?Promise.resolve():i.admission.then(()=>{},()=>{})).then(()=>this.admitOnce(e)),l={key:r,admission:o};return this.admitting.set(n,l),o.finally(()=>{this.admitting.get(n)===l&&this.admitting.delete(n)}).catch(()=>{}),o}async admitOnce(e){let{authority:t,childId:n,taskId:r,signal:i}=e,a=Gt(t),o=a.caller_thread_id;if(await this.ready.promise,i.aborted)return Vt(e);let l=t.kind==="assignment"?Yt(t.registration):null;if(l!==null)return{kind:"hold",reason:l};let d=this.ctx.threads.get(n),u=d===void 0?null:await d.read(()=>this.recordedTask(n,r));if(u!==null)return this.replay(e,u,a);await this.ctx.journal.origins.validate(a);let c=t.kind==="call"?this.callReach(t,d):await this.ownerReach(t,n,d);if(!("create"in c))return c;if(t.kind==="call"){let f=await this.ctx.threads.get(o).read(()=>$s(this.ctx.threads.chain(o)));if(f!==null)return{kind:"refusal",reason:f}}let h=this.reserveSlot({taskId:r,childId:n,callerId:o});if(!("release"in h))return h;try{if(i.aborted)return Vt(e);if(d!==void 0){let f=await this.notices.deliverLatest(n);if(f==="pending-receipt"||f==="unsent")return{kind:"wait",on:"predecessor",reason:`Thread ${n} ended its previous task, but its result has not reached this conversation yet, so it takes no new task now: message it again in a later step.`};await this.notices.withdrawExpired(n)}return t.kind==="call"&&this.openingCalls.add(r),await this.open(e,a,c.create)}finally{h.release()}}async replay(e,t,n){let{taskId:r,childId:i}=t.task,a=l=>({kind:"conflict",reason:`Thread ${i} records task ${r} with another ${l}`});if($(t.started.origin)!==$(n))return a("origin");let{authority:o}=e;if(o.kind==="assignment"){if(t.started.task!==e.task)return a("task input");let{configuration:l}=o,d=Cr(l);if(d!==null)return{kind:"refusal",reason:d};let u=this.unbound(i,l);if(u!==null)return{kind:"hold",reason:u};let c=await this.birthConflicts(i,l);if(c!==null)return{kind:"conflict",reason:c}}return{kind:"opened",task:t.task,replayed:!0}}callReach(e,t){let{context:n,target:r,selection:i}=e;if(r!==null&&t!==void 0)return{kind:"conflict",reason:`Thread ${t.id} exists without the task this call opened`};let a=r===null||r.kind==="fork"?null:this.ctx.llm.resolveRoute(i,n.route);if(t!==void 0&&this.ctx.llm.resolveRoute(i,t.summary.route),r?.kind==="fork"&&this.ctx.llm.resolveRoute({},n.route),r?.kind==="role"){let o=fr(this.ctx,r.role);if(o!==null)return{kind:"refusal",reason:o}}return{create:r===null?null:o=>this.createChild(e,r,a,o)}}unbound(e,t){let n=`The configuration pinned for thread ${e}`;try{this.ctx.llm.resolveRoute({},t.route)}catch(i){return`${n} cannot run now: ${T(i)}`}let r=t.installations.filter(i=>!this.ctx.presets.has(i.presetId));return r.length>0?`${n} installs presets that are not registered: ${r.map(i=>i.presetId).join(", ")}`:!K(t.agent)&&!this.ctx.agents.has(void 0,t.agent)?`${n} names agent ${t.agent}, which is not registered`:null}async ownerReach(e,t,n){let{configuration:r,registration:i,callerThreadId:a,generation:o}=e,l=i.owner.name,d=Cr(r);if(d!==null)return{kind:"refusal",reason:d};let u=this.unbound(t,r);if(u!==null)return{kind:"hold",reason:u};if(n===void 0)return{create:f=>this.ctx.threads.create(r.agent,{...f,reuse:"configuration",birth:{from:"exact",spec:this.pinnedSpec(r)}})};let c=n.origin?.cause;if(n.origin?.caller_thread_id!==a||c?.kind!=="assignment"||c.owner!==l||He(c).generation!==o)return{kind:"conflict",reason:`Thread ${t} is not ${l}'s conversation for generation ${o} under thread ${a}`};let h=await this.birthConflicts(t,r);return h===null?{create:null}:{kind:"conflict",reason:h}}pinnedSpec(e){return{route:e.route,environment:e.environment,installations:this.ctx.presets.initialInstallations(e.installations,e.agent),requires:[S,...e.requires]}}async birthConflicts(e,t){let n=await this.ctx.threads.birthConflicts(e,{agent:t.agent,spec:this.pinnedSpec(t)});return n.length===0?null:`Thread ${e} was created with a different ${n.map(({field:r})=>r).join(", ")}`}recordedTask(e,t){let n=this.ctx.journal.state(_,e).byId.get(t);if(n===void 0)return null;let{started:r,settlement:i}=n;return{started:r,task:{taskId:t,childId:e,callerId:r.origin.caller_thread_id,background:r.background,runId:n.runId,outcome:i===null?null:J(i)}}}async open(e,t,n){let{childId:r,taskId:i,authority:a}=e,o=a.kind==="call"?a.background:!0,l=a.kind==="call"&&a.background,d=null,u=null,c=m=>{if(d=null,u=null,m.runId===null)throw new Error(`Task ${i} was opened without the run that assigns it`);if(u=e.authority.kind==="assignment"&&e.signal.aborted?Vt(e):this.admissionCheck(t,m.threadId)??this.ownerCheck(e),u!==null)return{refuse:{message:u.reason}};let j=e.rows?.(m)??[];if(je(j))return u={kind:"vetoed",reason:j.refuse.message},j;let C={op:"started",task_id:i,origin:t,background:o,notice:l,run_id:m.runId,task:e.task};return d=m.runId,[B.entry(C,{threadId:m.threadId}),...j]},h=m=>({kind:"opened",replayed:!1,task:{taskId:i,childId:r,callerId:t.caller_thread_id,background:o,runId:m,outcome:null}}),f=async m=>{let j=await this.ctx.threads.get(r).read(()=>this.recordedTask(r,i));return j===null?{kind:"conflict",reason:m}:this.replay(e,j,t)};if(n!==null){try{await n({id:r,origin:t,input:e.task,inputId:i,rows:c,wake:Ar(null)})}catch(m){if(u!==null)return u;if(m instanceof Se)return{kind:"conflict",reason:m.message};throw m}return d!==null?h(d):f(`Thread ${r} exists without the task this call opened`)}let g=await this.ctx.threads.retain(()=>this.ctx.journal.origins.subtree(r,{self:!0}).map(m=>m.thread_id),{lastRelease:"keep"}),w;try{let m=a.kind==="call"?a.selection:qs(a.configuration);w=await this.ctx.threads.get(r).send(e.task,{id:i,rows:c,wake:Ar(m)})}finally{g.release()}return w.status==="refused"?u??{kind:"refusal",reason:w.refusal.message}:w.status==="queued"&&w.runId!==null?h(w.runId):f(`Thread ${r} holds no task ${i}`)}createChild(e,t,n,r){let{threads:i}=this.ctx,a=()=>{if(n===null)throw new Error("A new sub-agent needs the route it is born on");return n};switch(t.kind){case"agent":return i.create(t.name,{...r,reuse:"identity",birth:{from:"caller",route:a(),requires:[S]}});case"role":return i.create(t.role.id,{...r,reuse:"identity",birth:{from:"caller",route:a(),requires:[S],installations:[{presetId:Ce,config:t.role,installationId:Ot,lifetime:"defining"}]}});case"fork":{let{context:o}=e;if(o.requestSeq===null)throw new Error("This call has no recorded request to fork at");return i.fork(o.threadId,{...r,reuse:"identity",at:o.requestSeq,requires:[S]})}}}ownerCheck(e){let{authority:t}=e;if(t.kind==="call")return null;let{registration:n}=t,r=Yt(n);if(r!==null)return{kind:"hold",reason:r};let i=this.unbound(e.childId,t.configuration);if(i!==null)return{kind:"hold",reason:i};let a=n.owner.authorize(this.assignmentTask(e.taskId,e.childId,Gt(t)),"opening");return a.kind==="allow"?null:a}assignmentTask(e,t,n){let r=G(n);if(r===null)throw new Error(`Task ${e} was not opened by an assignment`);let{assignment:i,generation:a}=He(r);return{taskId:e,childId:t,callerThreadId:n.caller_thread_id,assignment:i,generation:a,grantedSeq:n.source_seq}}admissionCheck(e,t){let n=e.caller_thread_id,r=this.stoppedAbove(n);if(r!==null)return{kind:r.kind==="unreadable"?"hold":"discard",reason:r.why};let i=this.obligationOver(n,e.source_seq);if(i!==null)return{kind:"discard",reason:i};let a=this.ctx.journal.summary(n),o=a===void 0?null:k(this.ctx.journal,a.thread_id);return o!==null&&o.state!=="open"?o.state==="unavailable"?{kind:"hold",reason:`This thread's own task state is unavailable (${o.error}); it cannot start new work`}:{kind:"discard",reason:`This thread's own task has ended (${o.state}); it cannot start new work`}:this.ctx.journal.summary(t)===void 0?null:this.continuation(t)}continuation(e){let t=this.ctx.journal.summary(e);if(t===void 0)throw new Error(`Unknown thread: ${e}`);let n=a=>({kind:"wait",on:"predecessor",reason:a});if(!A(t))return{kind:"refusal",reason:`Thread ${e} was not started as an agent, so it cannot take a task`};if(X(this.ctx.journal.state(p,e).requests))return{kind:"refusal",reason:`Thread ${e} was stopped by a person and cannot be given more work; start a new sub-agent`};let r=k(this.ctx.journal,t.thread_id);if(r?.state==="unavailable")return{kind:"hold",reason:`Thread ${e}'s task state is unavailable (${r.error}); it cannot take a new task`};if(r?.state==="open")return n(`Thread ${e} is busy: its task ${r.task_id} has not ended. Steer it with message_agent and kind "steer", wait for it with read_agent, or stop it with stop_agent`);if(r?.cleanup_pending===!0)return n(`Thread ${e} is busy: its task ${r.task_id} was stopped and it is still going quiet; try again once it has`);if(this.cleanup.blocksOpening(e))return n(`Thread ${e} is busy: it is still going quiet after a stop; try again once it has`);if(t.pending_run!==null)return n(`Thread ${e} is busy: its last task has ended, but its run has not finished. Wait with read_agent and until "activity", or stop it with stop_agent, which ends that run`);if(ze(this.ctx.journal,e))return{kind:"refusal",reason:`Thread ${e} stopped before finishing its last task and cannot be continued; start a new sub-agent`};let i=le(this.ctx,e,{descendants:!0});return i.unresolved.length>0?{kind:"refusal",reason:`Thread ${e} cannot be given more work: commands it or an agent under it started have no established end (${i.unresolved.join("; ")}); start a new sub-agent`}:i.draining.length>0?n(`Thread ${e} is busy: commands it or an agent under it started are still ending (${i.draining.join("; ")}); try again once they have`):null}stoppedAbove(e){for(let t of this.ctx.journal.origins.callers(e).threads){let n=k(this.ctx.journal,t.thread_id),r=t.thread_id!==e;if(n?.state==="unavailable"){if(r)return{kind:"unreadable",why:`The task state of thread ${t.thread_id} above it cannot be read (${n.error})`}}else{if(n?.cleanup_pending===!0)return{kind:"stopping",why:`Thread ${t.thread_id} is being stopped; nothing new starts under it`};if(r&&n?.state==="stopped")return{kind:"stopping",why:`Thread ${t.thread_id} was stopped; nothing new starts under it`}}}return null}obligationOver(e,t){let n=this.ctx.threads.get(e)?.originRoot??null;if(n===null)return null;for(let r of te(this.ctx.journal,n))if(e===n?t<r.seq:this.covers(r,e))return`Thread ${e} is being stopped; nothing new starts under it`;return null}covers(e,t){return e.targets.some(n=>n.childId===t||this.ctx.journal.origins.isUnder(t,n.childId))}obligated(e){let t=this.ctx.threads.get(e)?.originRoot??null;return t!==null&&te(this.ctx.journal,t).some(n=>this.covers(n,e))}reserveSlot(e){let t=this.config.maxOpenTasks,n=this.ctx.threads.get(e.callerId)?.originRoot??null;if(n===null)return{kind:"hold",reason:dr};let{holders:r,unreadable:i}=this.slotHolders(n);return i.length>0?{kind:"hold",reason:lr(i)}:r.length>=t?{kind:"wait",on:"capacity",reason:or(t,r,e.callerId)}:(this.reservations.set(e.taskId,e),{release:()=>this.reservations.delete(e.taskId)})}slotHolders(e){let t=this.ctx.journal.origins.subtree(e,{self:!0}),n=new Set(t.map(a=>a.thread_id)),r=new Map,i=[];for(let a of this.entriesOf(t)){if(a.state==="unavailable"){i.push(a);continue}let o=a.state==="open"?a.blocked?"waiting for an approval":"open":a.cleanupPending?"being stopped":a.draining?"running a late turn":null;o!==null&&r.set(a.taskId,{taskId:a.taskId,childId:a.childId,callerId:a.callerId,why:o})}for(let[a,{childId:o,callerId:l}]of this.reservations)n.has(l)&&!r.has(a)&&r.set(a,{taskId:a,childId:o,callerId:l,why:"starting"});return{holders:[...r.values()],unreadable:i}}entriesOf(e){return Pr(this.ctx.journal,e)}evaluate(e){let t=this.ctx.journal.summary(e);if(t===void 0)return{kind:"hold",reason:`thread ${e} does not exist`};let n=k(this.ctx.journal,t.thread_id);if(n===null||n.state==="unavailable")return{kind:"hold",reason:n===null?"the task is not recorded":`its task state is unavailable (${n.error})`};let r={taskId:n.task_id,reading:n,stoppedAbove:this.stoppedAbove(e),stopOnItsWay:this.cleanup.stopsAffecting({taskId:n.task_id,childId:e}).length>0,obligated:this.obligated(e),draining:V(this.ctx.journal,t)},i=z(n.origin);if(i===null){let o=this.ownerVerdict(this.assignmentTask(n.task_id,e,n.origin),n.origin);return Nt({...r,authority:{kind:"assignment",verdict:o}})}let a={taskId:n.task_id,childId:e,callerId:n.origin.caller_thread_id,callSeq:i,background:n.background,runId:n.run_id};return Nt({...r,authority:{kind:"call",background:a.background,opening:this.openingOf(a),callRunsHere:this.openingCalls.has(a.taskId),callSuspended:this.ctx.journal.summary(a.callerId)?.waits.some(o=>o.call_seq===a.callSeq)===!0}})}ownerVerdict(e,t){let n=G(t).owner,r=this.owners.get(n);if(r===void 0)return{kind:"hold",reason:`the owner ${n} that assigned it is not registered`};let i;try{i=r.owner.authorize(e,"running")}catch(a){return this.ctx.reportError(a),{kind:"hold",reason:`its owner ${n} could not judge it: ${T(a)}`}}return i.kind==="allow"?i:{kind:"hold",reason:i.reason}}openingOf(e){let t=this.openingResults.get(e.taskId);return t!==void 0?t.result.kind:this.indexedCallers.has(e.callerId)?"none":"unknown"}openingNeeded(e,t){let n=this.ctx.journal.summary(t),r=n===void 0?null:k(this.ctx.journal,n.thread_id);return n===void 0||r===null?!1:r.state==="unavailable"?!0:r.task_id===e&&(r.state==="open"||V(this.ctx.journal,n))}rememberOpening(e,t,n){t.some(r=>this.openingNeeded(e,r))&&this.openingResults.set(e,{childIds:t,result:n})}evictOpening(e){for(let[t,n]of this.openingResults)n.childIds.includes(e)&&(n.childIds.some(r=>this.openingNeeded(t,r))||this.openingResults.delete(t))}indexCaller(e,t){if(!this.indexedCallers.has(e)){if(t.size>0)for(let n of this.ctx.journal.rowsAfter(e,Math.min(...t.keys()))){if(n.type!=="tool/result")continue;let r=t.get(n.source_seqs[0]??0);r!==void 0&&this.rememberOpening(r.taskId,[r.childId],we(n.data.result,r.taskId)?{kind:"receipt"}:{kind:"answered",reason:yt(n.data.result)})}this.indexedCallers.add(e);for(let n of t.values())this.constraint?.changed(n.childId)}}childHolding(e){for(let t of this.ctx.journal.summaries()){let n=k(this.ctx.journal,t.thread_id);if(n!==null&&n.state!=="unavailable"&&n.task_id===e)return t.thread_id}}async findChild(e){let t=me(e)?.callerThreadId,n=t===void 0?this.ctx.threads.list().filter(r=>r.origin?.cause.kind==="assignment"):this.ctx.threads.list({callerThreadId:t});for(let r of n)if(await r.read(()=>this.ctx.journal.state(_,r.id).byId.has(e)))return r.id;throw new Error(`No thread holds task ${e}`)}carryOut(e,t){let n=this.carrying.get(t.id);if(n!==void 0)return n;let r=a=>this.ctx.reportError(a),i=Promise.all(t.targets.map(a=>this.cleanup.stop(a.childId,a.taskId,{by:"host",reason:t.reason,callSeq:null}).catch(r))).then(()=>{});return this.carrying.set(t.id,i),i.then(()=>this.acknowledgeObligation(e,t)).catch(r).finally(()=>this.carrying.delete(t.id)),i}async acknowledgeObligation(e,t){await Promise.all(t.targets.map(async r=>{await this.cleanup.whenWalked(r.childId),await this.runStopped(r)}));let{journal:n}=this.ctx;await n.transact(e,()=>n.state(Ke,e).has(t.id)?t.targets.some(i=>{let a=n.summary(i.childId),o=a===void 0?null:k(this.ctx.journal,a.thread_id);return o?.state==="unavailable"?!0:o?.task_id!==i.taskId?!1:o.cleanup_pending||a?.pending_run?.run_id===o.run_id})?{rows:[],value:void 0}:{rows:[be.entry({op:"stop_completed",obligation_id:t.id},{threadId:e})],value:void 0}:{rows:[],value:void 0})}async runStopped(e){let t=this.ctx.journal.summary(e.childId),n=t===void 0?null:k(this.ctx.journal,t.thread_id);n===null||n.state==="unavailable"||n.task_id!==e.taskId||await pt(this.ctx.threads,e.childId,n.run_id,gt).catch(()=>{})}onRow(e){this.waits.onRow(e),e.type==="thread/cancel"&&e.data.intent==="user"&&this.personCancelled(e.thread_id),this.tellSettled(e.thread_id);let t=B.read(e);if((t!==void 0||e.type==="run/settled")&&this.evictOpening(e.thread_id),t!==void 0&&t.op!=="started")for(let d of this.ctx.journal.origins.subtree(e.thread_id,{self:!0}))this.constraint?.changed(d.thread_id);if(e.type==="turn/end"||e.type==="run/settled")return this.notices.afterEnding(e.thread_id);let n=be.read(e);if(n?.op==="stop_requested"){let d={id:n.obligation_id,seq:e.seq,reason:n.reason},u=n.targets.map(c=>({taskId:c.task_id,childId:c.child_id}));this.carryOut(e.thread_id,{...d,targets:u});return}if(e.type!=="tool/result")return;let r=e.source_seqs[0];if(r===void 0)return;let i=e.thread_id,a=Ue(i,r);if(this.openingCalls.delete(a),we(e.data.result,a)){this.rememberOpening(a,this.childrenHolding(i,r,a),{kind:"receipt"});let d=this.childHolding(a);if(d===void 0)return;this.constraint?.changed(d),this.notices.deliver(d,a).catch(u=>this.ctx.reportError(u));return}let o=yt(e.data.result),l=this.childrenHolding(i,r,a);l.length>0&&this.rememberOpening(a,l,{kind:"answered",reason:o});for(let d of l)this.cleanup.stop(d,a,{by:"caller",reason:o,callSeq:null}).catch(u=>this.ctx.reportError(u))}personCancelled(e){let t=this.ctx.journal.summary(e),n=t===void 0?null:k(this.ctx.journal,t.thread_id);if(!(n===null||n.state!=="stopped"||!n.cleanup_pending)&&G(n.origin)!==null){for(let r of this.ctx.journal.origins.subtree(e,{self:!0}))this.constraint?.changed(r.thread_id);this.cleanup.stop(e,n.task_id,{by:"host",reason:"a person cancelled it",callSeq:null}).catch(r=>this.ctx.reportError(r))}}tellSettled(e){let t=this.ctx.journal.summary(e),n=t===void 0?null:k(this.ctx.journal,t.thread_id);if(n===null||n.state==="unavailable"||n.state==="open")return;let r=G(n.origin),i=r===null?void 0:this.owners.get(r.owner);if(!(i===void 0||this.settledTold.has(n.task_id))){this.settledTold.add(n.task_id);try{i.owner.settled(this.assignmentTask(n.task_id,e,n.origin))}catch(a){this.ctx.reportError(a)}}}childrenHolding(e,t,n){let{journal:r}=this.ctx,i=r.summary(vt(e,t));if(i?.origin?.caller_thread_id===e&&z(i.origin)===t){let l=k(this.ctx.journal,i.thread_id);return l?.state==="unavailable"||l?.task_id===n&&(l.state==="open"||V(this.ctx.journal,i))?[i.thread_id]:[]}let a;try{a=r.eventAt(t)}catch{return[]}if(a?.type!=="tool/call"||a.data.name!==U)return[];let o=[];for(let l of this.ctx.threads.list({callerThreadId:e})){let d=k(this.ctx.journal,l.summary.thread_id);if(d?.state==="unavailable")o.push(l.id);else if(d?.task_id===n)return d.state==="open"||V(this.ctx.journal,l.summary)?[l.id]:[]}return o}onRunEvent(e){this.waits.onRunEvent(e.threadId),e.state==="running"&&this.repairUnder(e.threadId).catch(t=>this.ctx.reportError(t))}async reconcile(e){await this.ready.promise,await this.ctx.journal.flush();let t=await this.openTasksOf(e);if(t.size===0)return;let n=await this.ctx.threads.retain(()=>[e],{lastRelease:"keep"});try{this.indexCaller(e,t);let r=[];for(let i of t.values()){let a=this.openingResults.get(i.taskId)?.result;a?.kind==="answered"&&r.push(this.cleanup.stop(i.childId,i.taskId,{by:"caller",reason:a.reason,callSeq:null}).catch(o=>this.ctx.reportError(o)))}await Promise.all(r)}finally{n.release()}}async openTasksOf(e){let t=new Map,n=[];for(let r of this.ctx.threads.list({callerThreadId:e})){let i=k(this.ctx.journal,r.summary.thread_id);if(i?.state==="unavailable"&&n.push(r.id),i===null||i.state==="unavailable"||i.state!=="open"&&!V(this.ctx.journal,r.summary))continue;let a=i.origin.caller_thread_id===e?z(i.origin):null;a!==null&&t.set(a,{taskId:i.task_id,childId:r.id,callerId:e,callSeq:a,background:i.background,runId:i.run_id})}for(let r of n)try{let i=await this.openTaskOf(r);if(i===null)continue;let{task_id:a,origin:o,background:l}=i.started,d=o.caller_thread_id===e?z(o):null;if(d===null)continue;t.set(d,{taskId:a,childId:r,callerId:e,callSeq:d,background:l,runId:i.runId})}catch(i){this.ctx.reportError(new Error(`The task record of thread ${r} cannot be read`,{cause:i}))}return t}openTaskOf(e){return this.ctx.threads.get(e).read(()=>{let t=this.ctx.journal.state(_,e).latest;if(t===null)return null;let n=this.ctx.journal.state(p,e).requests.pending?.runId===t.runId;return t.settlement===null||n?t:null})}shutdown(){return this.closing??=(async()=>{await Promise.allSettled([this.waits.drain(),...this.starts.keys()]),await this.cleanup.drain()})(),this.closing}};function Ir(s,e){switch(e){case"queued":return`Your message to thread_id=${s} is queued: the agent has not read it yet. Wait for its answer with read_agent.`;case"claimed":return`Your message reached thread_id=${s}: the agent has read it. Wait for its answer with read_agent.`;case"discarded":return`Your message to thread_id=${s} was discarded before the agent read it: its run was cancelled or stopped.`}}function Pr(s,e){let t=[];for(let n of e){if(n.origin===null)continue;let r=k(s,n.thread_id);if(r===null)continue;let i={childId:n.thread_id,callerId:n.origin.caller_thread_id};if(r.state==="unavailable"){t.push({...i,state:"unavailable",error:r.error});continue}t.push({...i,taskId:r.task_id,background:r.background,notice:r.notice,state:r.state,blocked:r.state==="open"&&Ct(s,n.thread_id),cleanupPending:r.cleanup_pending,firstLine:r.first_line,draining:V(s,n)})}return t}function Nr(s,e){let t=s.origins.subtree(e,{self:!1});return Pr(s,t)}import{z as q}from"zod";var Kt="list_agents",Qt="read_agent",Xt="stop_agent",Os=[U,Kt,Qt,Xt],nt=s=>({output:s,is_error:!0}),Lr="message_agent requires a non-empty message",Es=["background","provider","model","thinking_effort"],Rs=St({thread_id:q.string().min(1,"message_agent requires the thread_id of an agent this thread started").describe("The agent to message: the thread_id the result of the tool that started it named."),kind:q.enum(["continue","steer"]).describe('"continue" gives an agent whose task has ended its next task, after its own history. "steer" sends a correction into the task it is running now, which it reads at its next step; a steer never starts a task.'),message:q.string({error:Lr}).refine(s=>s.trim().length>0,Lr).describe("What to tell the agent: its next task or a question about its answer, or a correction to its running task.")}).superRefine((s,e)=>{if(s.kind!=="steer")return;let t=Es.filter(n=>n==="background"?s.background:s[n]!==null);t.length!==0&&e.addIssue({code:"custom",path:[t[0]],message:`kind "steer" takes no ${t.join(", ")}: a running agent keeps its route, and a steer has no answer to wait for`})}),As='Messages an agent this thread started, by its thread_id, whichever tool started it. With kind "continue", the message is its next task: it sees everything it did before, then your message, which may be a new task or a question about its answer, and the call returns its answer, or a receipt with background. With kind "steer", the message is a correction to the task it is running now: it joins that task at its next step, and the call returns at once.',Wr=oe({name:U,description:As,parameters:Rs,onInterrupted:"rerun",executionMode:"parallel",async execute(s,e){let t=H(e.ctx,"delegations",U);if(s.kind==="continue")return t.delegate(e,{child:{kind:"continue",threadId:s.thread_id},selection:qt(s),background:s.background,task:s.message});let n=Z(e.ctx,e.threadId,s.thread_id);if(typeof n=="string")return nt(n);let{task:r,newer:i}=await rt(e,n),a=await t.steer(e,{childId:n.id,taskId:r?.started.task_id??null,message:s.message});return a.is_error===!0&&i?{...a,output:`${a.output} Note: ${st}.`}:a}});function rt(s,e){return e.read(()=>{let t=s.ctx.journal.state(_,e.id);return{task:Be(t,s.callSeq),newer:t.latest!==null&&t.latest.startedSeq>=s.callSeq}})}var st="a newer task was opened on it by a call in this reply; read it again in a later step to see that one",Fr=s=>s?"background":"blocking";function Cs(s){return s.state==="open"?s.blocked?"open, waiting for an approval":"open":s.cleanupPending?`${s.state}, still going quiet`:s.draining?`${s.state}, still running a late turn`:s.state}function Jt(s,e){let t=s.ctx.threads.inspect(e,{basis:"catalog"});if(t===null)return"idle";switch(t.state){case"running":return"running";case"requested":return"about to run";case"held":return t.hold.reason==="approval"?"blocked on an approval":`held (${t.hold.reason})`;case"idle":return"idle"}}var Hr=oe({name:Kt,description:"Lists the agents this thread started, however they were started: each one's thread_id and agent, whether it is running, idle or blocked on an approval now, and its latest task: the task id, whether it runs in the background, its state and its first line.",parameters:q.strictObject({}),onInterrupted:"rerun",executionMode:"parallel",async execute(s,e){let t=e.ctx.threads.list({callerThreadId:e.threadId});if(t.length===0)return{output:"You have not started any agents."};let n=H(e.ctx,"delegations",Kt),r=new Map(n.tasks({callerThreadId:e.threadId}).map(a=>[a.childId,a])),i=t.map(a=>{let o=`- thread_id=${a.id} (${a.agentName}), ${Jt(e,a.id)} now`,l=r.get(a.id);return l===void 0?`${o}; no task`:l.state==="unavailable"?`${o}; its task state cannot be read: ${l.error}`:`${o}; task ${l.taskId} (${Fr(l.background)}): ${Cs(l)}. "${l.firstLine}"`});return{output:[`Agents you started (${t.length}):`,...i].join(`
12
+ `)}}}),Is=3600,Ps=q.strictObject({thread_ids:q.array(q.string().min(1)).min(1).describe("The agents to read, by the thread_id the tool that started each one named."),wait_seconds:q.number().min(0).max(Is).default(0).describe(`Seconds to wait, until any named agent's task settles, or with until "activity" until any of them does anything; 0 reads at once.`),until:q.enum(["settled","activity"]).default("settled").describe('"settled" returns once any named task has ended; "activity" also once any named agent records anything.'),full:q.boolean().default(!1).describe("Show each ended task's answer in full, even a background task's answer already given to you in an agent_notification.")}),Mr=1e3,Ns=8;function Ls(s,e,t){return e.read(()=>{let{journal:n}=s.ctx,r=n.state(_,e.id).byId.get(t);if(r?.claimSeq==null)return"It has not taken the task yet.";let i=n.rowsAfter(e.id,r.claimSeq).flatMap(l=>l.type==="tool/call"?[l.data.name]:[]).slice(-Ns),a=r.latestText,o=[i.length===0?"No tool calls yet.":`Recent tool calls: ${i.join(", ")}.`];if(a!==null){let l=a.length<=Mr?a:`\u2026${a.slice(-Mr+1)}`;o.push(`Its latest text:
13
+ ${l}`)}return o.join(`
14
+ `)})}var Dr=60;function Ms(s,e,t){return e.read(n=>{let{journal:r}=s.ctx,i=jt(s.threadId),a=[...r.state(_,e.id).byId.values()].find(d=>d.startedSeq>t.startedSeq)?.startedSeq??Number.POSITIVE_INFINITY,o=new Map;for(let d of r.rowsAfter(e.id,t.startedSeq))if(!(d.type!=="inbox/spliced"||d.seq>=a))for(let u of d.data.inserted)u.id.startsWith(i)&&o.set(u.id,nn(u.content));return o.size===0?null:`Messages you steered into this task: ${[...o].map(([d,u])=>{let c=u.trim().split(`
15
+ `,1)[0],h=c.length<=Dr?c:`${c.slice(0,Dr-1)}\u2026`,{state:f}=n.input(d);return`"${h}" (${f==="claimed"?"read":f==="queued"?"not read yet":"discarded unread"})`}).join(", ")}.`})}function Ds(s,e,t,n){if(n||!t.notice||t.state!=="completed"&&t.state!=="failed")return null;let r=ee(s.ctx.journal,s.threadId,e);if(r===null)return null;switch(r){case"queued":return"Its answer is queued for you as an agent_notification, normally right after this result; read_agent with full: true repeats it.";case"pending-receipt":return"Its agent_notification waits for the call that started it to record its background receipt; read_agent with full: true shows the answer now.";case"claimed":return"You were given its answer in an agent_notification; read_agent with full: true shows it again.";case"unsent":return"Its agent_notification could not be delivered; read_agent with full: true shows its answer.";case"spent":case"unowed":return null}}async function Ws(s,e,t,n,r){let i=`thread_id=${e.id}, task ${t.taskId} (${Fr(n.started.background)})`,a=`the agent is ${Jt(s,e.id)} now`,o=await Ms(s,e,n),l=d=>o===null?d:`${d}
16
+ ${o}`;switch(t.state){case"open":return l(`${i}: not finished; ${a}.
17
+ ${await Ls(s,e,t.taskId)}`);case"unavailable":return l(`${i}: its task state cannot be read; ${a}.`);default:{let d=Ds(s,t.taskId,{notice:n.started.notice,state:t.state},r);return l(`${i}: ${t.state}; ${a}.
18
+ ${d??t.outcome?.output??""}`.trimEnd())}}}var Ur=oe({name:Qt,description:"Reads what agents this thread started are doing: for each, the state of its task and, once the task has ended, its answer or why it failed (a background task's answer comes to you as an agent_notification, so it is left out while that notice is on its way or was read; full: true shows it again); before that, its recent tool calls and latest text, and whether it is running now. Can wait for the first named task to end.",parameters:Ps,onInterrupted:"rerun",executionMode:"parallel",async execute({thread_ids:s,wait_seconds:e,until:t,full:n},r){let i=H(r.ctx,"delegations",Qt),a=[...new Set(s)].map(g=>Z(r.ctx,r.threadId,g)),o=a.filter(g=>typeof g=="string");if(o.length>0)return nt(o.join(`
19
+ `));let l=await Promise.all(a.map(async g=>({child:g,...await rt(r,g)}))),d=async()=>(await Promise.all(l.map(async({child:g})=>({child:g,...await rt(r,g)})))).flatMap(({child:g,task:w,newer:m})=>w===null?[`thread_id=${g.id} has no task this call can read${m?`: ${st}`:""}.`]:m?[`thread_id=${g.id}: ${st}.`]:[]),u=l.flatMap(({child:g,task:w})=>w===null?[]:[{child:g,task:w}]);if(u.length===0)return{output:(await d()).join(`
20
+ `)};let c=await i.read(r,{tasks:u.map(({child:g,task:w})=>({taskId:w.started.task_id,childId:g.id})),until:t,waitSeconds:e});if(En(c))return c;let f=[...await Promise.all(c.tasks.map((g,w)=>Ws(r,u[w].child,g,u[w].task,n)))];return c.noProgress!==null&&f.push(`Nothing can advance these tasks now (${c.noProgress.join("; ")}). Waiting will not end them: stop them with stop_agent, then answer.`),c.note!==null&&f.push(c.note),{output:[...f,...await d()].join(`
21
+
22
+ `)}}}),Fs=q.strictObject({thread_id:q.string().min(1).describe("The agent to stop, by the thread_id the tool that started it named."),reason:q.string().nullable().default(null).describe("Optional: why, recorded with the stop.")});function Hs(s){return s.stop===null?"its input was discarded before the agent took it":`by ${{caller:"the agent that started it",host:"the host",ancestor:"an agent above it",person:"a person"}[s.stop.by]}: ${s.stop.reason}`}var Br=oe({name:Xt,description:"Stops the task of an agent this thread started, by its thread_id: the agent is cancelled and will not answer. A task that has already ended keeps its outcome.",parameters:Fs,onInterrupted:"rerun",executionMode:"parallel",async execute({thread_id:s,reason:e},t){let n=Z(t.ctx,t.threadId,s);if(typeof n=="string")return nt(n);let{task:r,newer:i}=await rt(t,n);if(r===null)return nt(`thread_id=${n.id} has no task to stop${i?`: ${st}`:""}.`);let a=r.started.task_id,o=await H(t.ctx,"delegations",Xt).stop(a,{by:"caller",reason:e?.trim()||"stopped by the agent that started it",callSeq:t.callSeq}),l=await n.read(()=>t.ctx.journal.state(_,n.id).byId.get(a)),d=`task ${a} of thread_id=${n.id}`;return{output:`${o.state!=="stopped"?`The ${d} had already ended (${o.state}) before this call; nothing was stopped, and any turn it was still running after that was cut off.`:l.stop?.call_seq===t.callSeq?`Stopped the ${d}. It will not answer, and may take a moment to go quiet.`:`The ${d} was already stopped, ${Hs(l)}.`} The agent is ${Jt(t,n.id)} now.`,metadata:{thread_id:n.id,delegation:{task_id:a,state:o.state}}}}});import{z as Zt}from"zod";var zr=M({plugin:"lagent:delegations",kind:"own_tasks",version:1,schema:Zt.strictObject({thread_ids:Zt.array(Zt.string())})}),it=s=>s.length===1?s[0]:`${s.slice(0,-1).join(", ")} and ${s.at(-1)}`;function Us(s,e,t){if(t.state!=="completed"&&t.state!=="failed"||!t.notice)return!1;let n=ee(s.journal,e,t.taskId);return n!==null&&Wt(n)}function Bs(s,e){let{inbox:t}=s.journal.state(p,e);return[...t["next-step"],...t["next-turn"]].flatMap(n=>{let r=Ye(n.source),i=r===void 0?null:ee(s.journal,e,r.task_id);return r!==void 0&&i!==null&&Wt(i)?[r.thread_id]:[]})}function Gr(s,e){let t=r=>{let i=s.journal.summary(r);return i!==void 0&&A(i)},n=r=>{let i=e.tasks({callerThreadId:r}),a=i.flatMap(o=>Us(s,r,o)?[o.childId]:[]);return{unreadable:i.flatMap(o=>o.state==="unavailable"?[{childId:o.childId,error:o.error}]:[]),open:i.flatMap(o=>o.state==="open"?[{childId:o.childId,blocked:o.blocked}]:[]),unread:[...new Set([...a,...Bs(s,r)])]}};s.on("lagent/turn/stop",({threadId:r,observe:i})=>{if(!t(r))return;i(()=>JSON.stringify(n(r)));let{unreadable:a,open:o,unread:l}=n(r);if(a.length>0){let g=a.map(m=>m.childId),w=a.map(m=>`${m.childId}: ${m.error}`).join("; ");return zr.rejection(`The task state of your agent${g.length===1?"":"s"} ${it(g)} cannot be read (${w}), so this answer cannot be accepted while ${g.length===1?"it":"they"} may still be working.`,{thread_ids:g})}if(o.length===0&&l.length===0)return;let d=o.map(g=>g.childId),u=o.filter(g=>g.blocked).map(g=>g.childId),c=u.length===0?"":` (${it(u)} ${u.length===1?"is":"are"} waiting for an approval)`,h=[];d.length>0&&h.push(`Your agent${d.length===1?"":"s"} ${it(d)} ${d.length===1?"has":"have"} not finished${c}. Wait for them with read_agent and until "settled", or stop the ones you no longer need with stop_agent, then answer.`),l.length>0&&h.push(`Your agent${l.length===1?"":"s"} ${it(l)} finished, and ${l.length===1?"its notice has":"their notices have"} not reached you yet: read ${l.length===1?"it":"them"} before you answer.`);let f=h.join(" ");return{decision:"continue",message:zr.contribution({content:f},{thread_ids:[...d,...l]})}}),s.effect(()=>s.journal.subscribe(r=>{let i=r.type==="turn/end"&&Et(r.data.reason)?`ended its turn (${r.data.reason.kind})`:r.type==="run/settled"&&r.data.outcome==="failed"&&r.data.residual.length===0?`failed (${r.data.reason})`:null;if(i===null||!t(r.thread_id))return;let a=`the agent that started it ${i} without waiting for it`;for(let o of e.tasks({callerThreadId:r.thread_id}))o.state==="open"&&e.stop(o.taskId,{by:"caller",reason:a,callSeq:null}).catch(l=>s.reportError(l))}))}var zs=new Map([["message_agent",["Continue an agent you started rather than starting a new one when its earlier work is the context the next task needs, or to ask about what it answered; start a new one for unrelated work.","An agent keeps the route it last ran on unless a continuation names another.","An agent that stopped part-way through its last task cannot be continued; start a new one instead. One whose task has not ended can be steered, waited for with read_agent, or stopped with stop_agent.","Steer only an agent whose task is running now: a steer reaches it at its next step, and one sent while nothing runs it is refused; read_agent shows whether it has read your message."].join(`
23
+ `)],["read_agent",["An agent you started in the background tells you when it ends: its answer, or why it failed, is queued for you as an agent_notification, which you read at your next step or turn. Go on with other work meanwhile; with nothing else to do, you may end your turn, and the notification wakes you.","read_agent reports where a task stands. It leaves out an answer an agent_notification gives you, or already gave you; read it there, or call read_agent with full: true to see it again.",'When your answer depends on an agent you started in the background, wait for it with read_agent and until "settled"; with several, name them all, and it returns as soon as any one ends. Never poll it in a loop.',"A task that nothing can advance will not end by waiting: stop it with stop_agent if you no longer need it, then answer.","Stop the agents you no longer need with stop_agent before your final answer. When you work for another agent, you cannot answer while an agent you started is still working."].join(`
24
+ `)]]),Xo={name:"lagent:delegations",inject:["prompts","tools","threads","journal","llm","presets","agents"],async apply(s,e){Pn(s,"delegations"),Ln(s,Qn),await s.plugin(tt,e),Gr(s,H(s,"delegations","delegations")),Mn(s,[Wr,Hr,Ur,Br],{tag:"delegations",guidance:zs})}};export{X as a,Pe as b,pt as c,gt as d,bt as e,Kn as f,Ce as g,pe as h,He as i,xt as j,Tt as k,ss as l,D as m,hr as n,St as o,qt as p,Ot as q,Rt as r,us as s,cs as t,Ye as u,Ft as v,te as w,Nr as x,Os as y,Xo as z};
@@ -0,0 +1 @@
1
+ import{c as h}from"./5IRF47YB.js";import{c as I,d as $,e as y,f as p}from"./OL5A6ITQ.js";import{s as f,x as m}from"./BPRCULZH.js";import{a as g}from"./DDANMY45.js";import{c,g as w}from"./BBCW2FZK.js";import{h as u}from"./MMNNZCBO.js";import{ScopeLayers as E,Service as _,scopeOf as v}from"@leuduan/cordis";var b=class extends _{static inject=["journal"];registry=new Map;handDowns=new E(()=>[]);constructor(e){super(e,"presets")}register(e){if(this.registry.has(e.id))throw new Error(`Preset already registered: ${e.id}`);return this.registry.set(e.id,e),()=>{this.registry.get(e.id)===e&&this.registry.delete(e.id)}}has(e){return this.registry.has(e)}installationsFor(e,t,i){let r=new Set;return e.map(o=>{let s=this.requireRegistered(o.presetId);if(s.placement==="creation"&&t==="change")throw new Error(`Preset ${s.id} is recorded only when a thread is created; it cannot be applied later`);let n=y(s,o.config);p(s,n,`Preset ${s.id}: its schema must parse its own output back unchanged`);let a=o.installationId??m("preset");if(a==="")throw new Error("An installation id must be non-empty");if(r.has(a))throw new Error(`Installation id ${a} is given twice`);r.add(a);let l=i===void 0?void 0:s.definesAgent?.(n);if(l!==void 0&&l!==i)throw new Error(`Installation ${a} defines agent ${l}, but the thread runs on ${i}`);return{installation_id:a,preset_id:s.id,config:n}})}initialInstallations(e,t){let i=e.map(r=>u.parse(r.lifetime));return this.installationsFor(e,"creation",t).map((r,o)=>{let s=i[o];if(s!=="defining"&&this.requireRegistered(r.preset_id).placement==="creation")throw new Error(`Preset ${r.preset_id} is recorded only when a thread is created; it must be defining`);return{...r,lifetime:s}})}plan(e,t,i){let r=h(this.ctx).state(f,e).installations,o=[],s=[];for(let n of new Set(i)){let a=r.current.get(n);if(a?.lifetime==="defining")throw new Error(`Installation ${n} on thread ${e} defines the thread and cannot be removed`);a!==void 0&&(o.push({type:"installation/removed",data:{installation_id:n},options:{threadId:e}}),s.push(n))}for(let n of t){if(s.includes(n.installation_id))throw new Error(`Installation id ${n.installation_id} is removed by this change and cannot be reused`);this.alreadyApplied(r,e,n)||o.push({type:"installation/applied",data:n,options:{threadId:e}})}return{rows:o,applied:t.map(n=>n.installation_id),removed:s}}handDown(e,t){if(e===void 0)throw new Error(`Preset ${t.presetId} cannot be handed down from the global layer: only a thread's own scope hands down`);let[i]=this.installationsFor([t],"creation"),r=this.handDowns.layer(e),o=r.find(n=>n.installationId===t.installationId);if(o!==void 0)throw new Error(`Installation id ${t.installationId} is already handed down from this scope, by preset ${o.presetId}`);let s={presetId:t.presetId,config:i.config,installationId:t.installationId};return r.push(s),()=>{let n=r.indexOf(s);n>=0&&r.splice(n,1)}}handedDown(e,t,i,r){let o=new Map;for(let n of this.handDowns.closestFirst(e))for(let a of n)o.has(a.installationId)||o.set(a.installationId,a);if(o.size===0)return[];let s=new Set(r.map(n=>n.installation_id));for(let n of o.keys())if(s.has(n))throw new Error(`Thread ${t} is created with installation ${n}, which its caller's scope also hands down`);return this.initialInstallations([...o.values()].map(n=>({...n,lifetime:"defining"})),i)}async restore(e){let{signal:t}=e;for(let i of[...h(this.ctx).state(f,e.id).installations.current.values()]){t.throwIfAborted();let r=this.requireRegistered(i.presetId);p(r,i.config,`Installation ${i.installationId} on thread ${e.id} no longer validates`);let o=e.ctx.plugin($(r),I(w(structuredClone(i.config)),{thread:e,installationId:i.installationId,lifetime:i.lifetime,signal:t}));await x(o,i.installationId,e.id)}t.throwIfAborted()}requireRegistered(e){let t=this.registry.get(e);if(t===void 0)throw new Error(`Unknown preset: ${e}`);return t}alreadyApplied(e,t,i){let{installation_id:r}=i,o=e.current.get(r);if(o===void 0){if(e.used.has(r))throw new Error(`Installation id ${r} was removed from thread ${t} and cannot be reused`);return!1}if(o.presetId!==i.preset_id)throw new Error(`Installation ${r} on thread ${t} is preset ${o.presetId}, not ${i.preset_id}`);if(c(o.config)!==c(i.config))throw new Error(`Installation ${r} on thread ${t} was applied with a different configuration`);return!0}};async function x(d,e,t){try{await d.awaitTree()}catch(i){throw new Error(`Installation ${e} on thread ${t} could not be mounted: ${g(i)}`,{cause:i})}}var j=(d,e)=>d.effect(()=>d.presets.register(e));function z(d,e){let t=d.get("presets");return d.effect(()=>t.handDown(v(d),e))}export{b as a,j as b,z as c};
@@ -0,0 +1 @@
1
+ import{J as f,X as u}from"./BPRCULZH.js";import{d as l}from"./MMNNZCBO.js";import{scopeOf as c,ScopeLayers as d,Service as p}from"@leuduan/cordis";import{z as a}from"zod";var g=class extends p{layers=new d(()=>new Map);constructor(e){super(e,"agents")}names(e){return l(this.all(e).map(t=>t.name))}all(e){let t=new Map;for(let r of this.layers.globalFirst(e))for(let[o,{agent:s}]of r)t.set(o,s);return[...t.values()]}has(e,t){return this.resolve(e,t)!==void 0}get(e,t){return this.resolve(e,t)?.agent}require(e,t){let r=this.get(e,t);if(r===void 0)throw new f(t);return r}resolve(e,t){for(let r of this.layers.closestFirst(e)){let o=r.get(t);if(o!==void 0)return o}}register(e,t){let r=u.parse(t),o=m(r.name);if(e===void 0&&o)throw new Error(`Agent ${r.name} is registered globally, so its name must not contain a dot`);if(e!==void 0&&!o)throw new Error(`Agent ${r.name} is registered in a scope, so its name must contain a dot`);let s=this.layers.layer(e);if(s.has(r.name))throw new Error(`Agent already registered for name: ${r.name}`);let i={agent:r,layer:e};return s.set(r.name,i),()=>{s.get(r.name)===i&&s.delete(r.name)}}},v=(n,e)=>n.effect(()=>n.agents.register(c(n),e)),x=a.union([a.array(a.string()),a.literal("global"),a.literal("all")]),E=(n,e)=>n==="all"?!0:n==="global"?!m(e):n.includes(e),m=n=>n.includes(".");export{g as a,v as b,x as c,E as d,m as e};
@@ -0,0 +1,3 @@
1
+ import{z as o}from"zod";var u=(...t)=>t.some(r=>r!==null&&r!==""),y=o.discriminatedUnion("type",[o.object({type:o.literal("text"),text:o.string()}),o.object({type:o.literal("image"),url:o.string().nullable().default(null),data:o.string().nullable().default(null),media_type:o.string().nullable().default(null),detail:o.enum(["auto","low","high"]).default("auto")}).refine(t=>u(t.url,t.data),{message:"An image part needs a url or base64 data"}),o.object({type:o.literal("file"),file_id:o.string().nullable().default(null),url:o.string().nullable().default(null),data:o.string().nullable().default(null),filename:o.string().nullable().default(null),media_type:o.string().nullable().default(null)}).refine(t=>u(t.file_id,t.url,t.data),{message:"A file part needs a file_id, a url or base64 data"})]),d=o.preprocess(t=>t==null?[]:typeof t=="string"?[{type:"text",text:t}]:t,o.array(y).default([])),A=t=>({type:"text",text:t}),c=t=>t.filter(r=>r.type==="text").map(r=>r.text).join("");import{z as e}from"zod";var j=["none","low","medium","high","max"],$=e.enum(j),l=e.record(e.string(),e.unknown()),p=()=>({type:"object",properties:{},additionalProperties:!0}),L=e.object({name:e.string(),description:e.string().default(""),input_schema:l.default(p)}).transform((t,r)=>{let n={...t.input_schema};if(Object.keys(n).length===0)return{...t,input_schema:p()};if(n.type!=="object")return r.addIssue({code:"custom",message:"ToolSpec.input_schema must describe an object"}),e.NEVER;let s=n.properties;if(s==null)n.properties={};else if(typeof s!="object"||Array.isArray(s))return r.addIssue({code:"custom",message:"ToolSpec.input_schema.properties must be a mapping"}),e.NEVER;let a=n.required;return a!=null&&!Array.isArray(a)?(r.addIssue({code:"custom",message:"ToolSpec.input_schema.required must be a list when present"}),e.NEVER):{...t,input_schema:n}}),E=e.looseObject({call_id:e.string(),name:e.string(),arguments:l.default({})}),v=e.looseObject({call_id:e.string(),name:e.string(),arguments:e.null(),malformed:e.strictObject({raw:e.string(),error:e.string()})}),T=e.union([E,v]),q=t=>t.arguments!==null,F=t=>t.arguments===null?t.malformed.raw:JSON.stringify(t.arguments),k=e.object({input_tokens:e.number().int().default(0),output_tokens:e.number().int().default(0),cache_read_input_tokens:e.number().int().default(0),cache_write_input_tokens:e.number().int().default(0),reasoning_output_tokens:e.number().int().default(0)});var m=e.looseObject({id:e.string(),type:e.string(),name:e.string().nullable().default(null),status:e.enum(["in_progress","completed","failed"]).default("completed"),summary:e.string().nullable().default(null)}),V=e.object({text_delta:e.string().default(""),reasoning_delta:e.string().default(""),provider_call:m.nullable().default(null)}),M=e.object({provider:e.string(),data:l.default({})}),P=["system","developer","user","assistant","tool"],f=e.object({role:e.enum(P),content:d,reasoning_content:e.string().nullable().default(null),tool_calls:e.array(T).default([]),provider_calls:e.array(m).default([]),tool_call_id:e.string().nullable().default(null),usage:k.nullable().default(null),provider_state:M.nullable().default(null)}),z=t=>f.parse(t),U=t=>c(t.content),C=["completed","length","other"],O=e.enum(C),B=e.object({message:f,finish:O,provider_metadata:l.default({})}).refine(t=>t.message.role==="assistant",{message:"ModelResponse.message must have role assistant"});var g=class extends Error{provider;feature;constructor(r,n){super(`Provider '${r}' cannot do ${n}`),this.provider=r,this.feature=n,this.name="ProviderUnsupportedError"}},h=class extends Error{provider;constructor(r,n){super(`Provider '${r}' refused the request: it exceeds the model's context window`,n),this.provider=r,this.name="ContextOverflowError"}},x=class extends Error{provider;kind;partial;providerMetadata;constructor(r,n,s,a,S){super(`${n}: ${S}`),this.provider=r,this.kind=n,this.partial=s,this.providerMetadata=a,this.name="ResponseSettlementError"}},b=class extends Error{provider;idleMs;constructor(r,n){super(`'${r}' sent nothing for ${n} ms`),this.provider=r,this.idleMs=n,this.name="StreamIdleError"}},_=class extends Error{provider;partial;providerMetadata;constructor(r,n,s,a){super(`the response of '${r}' failed after it had begun`,a),this.provider=r,this.partial=n,this.providerMetadata=s,this.name="ResponseInterruptedError"}};import{z as i}from"zod";var K=i.object({kind:i.enum(["base","instruction","context"]),tag:i.string().nullable(),text:i.string()}),D=t=>t.map(r=>r.text).join(`
2
+
3
+ `);export{y as a,d as b,A as c,c as d,j as e,$ as f,l as g,L as h,E as i,T as j,q as k,F as l,k as m,m as n,V as o,f as p,z as q,U as r,O as s,B as t,g as u,h as v,x as w,b as x,_ as y,K as z,D as A};
@@ -1 +1 @@
1
- import{b as l}from"./DRYAN665.js";import{z as p}from"zod";var m=class extends Error{constructor(s,d){super(`Thread ${s} has no conversation root to read its ${d} mode from`)}},w=new Set;function $(e){if(w.has(e.name))throw new Error(`Modes ${e.name} are already defined`);if(w.add(e.name),!e.modes.includes(e.initial))throw new Error(`Modes ${e.name}: the initial mode ${e.initial} is not one of them`);let s=p.enum(e.modes),d=l({plugin:"lagent:modes",instanceId:e.name,kind:"mode-changed",version:1,policyState:!0,schema:p.strictObject({mode:s})}),i=d.projection({key:"mode",init:()=>null,apply:(r,{mode:o})=>o}),u=(r,o)=>r.state(i,o),c=(r,o)=>{if(e.authority==="thread")return o;let t=r.threads.get(o);if(t===void 0)return o;let n=t.originRoot;if(n===null)throw new m(o,e.name);return n},h=(r,o)=>u(r.journal,c(r,o))??e.initial;return{...e,of:h,authorityOf:c,recorded:u,async set(r,o,t){let n=s.parse(t),a=c(r,o);if(r.journal.summary(a)===void 0)throw new Error(`Unknown thread: ${a}`);await r.journal.transact(a,()=>({rows:n===h(r,a)?[]:[d.entry({mode:n},{threadId:a})],value:void 0}))},opening(r){let o=s.parse(r);return t=>{if(t.kind==="send")throw new Error(`Modes ${e.name}: opening rows only open a thread`);let{threadId:n,opening:a}=t;if(e.authority==="conversation"&&a.origin!==null)throw new Error(`Modes ${e.name}: thread ${n} is in its conversation's mode`);return[d.entry({mode:o},{threadId:n})]}}}}export{m as a,$ as b};
1
+ import{b as l}from"./6FRNHMCV.js";import{z as p}from"zod";var m=class extends Error{constructor(s,d){super(`Thread ${s} has no conversation root to read its ${d} mode from`)}},w=new Set;function $(e){if(w.has(e.name))throw new Error(`Modes ${e.name} are already defined`);if(w.add(e.name),!e.modes.includes(e.initial))throw new Error(`Modes ${e.name}: the initial mode ${e.initial} is not one of them`);let s=p.enum(e.modes),d=l({plugin:"lagent:modes",instanceId:e.name,kind:"mode-changed",version:1,policyState:!0,schema:p.strictObject({mode:s})}),i=d.projection({key:"mode",init:()=>null,apply:(r,{mode:o})=>o}),u=(r,o)=>r.state(i,o),c=(r,o)=>{if(e.authority==="thread")return o;let t=r.threads.get(o);if(t===void 0)return o;let n=t.originRoot;if(n===null)throw new m(o,e.name);return n},h=(r,o)=>u(r.journal,c(r,o))??e.initial;return{...e,of:h,authorityOf:c,recorded:u,async set(r,o,t){let n=s.parse(t),a=c(r,o);if(r.journal.summary(a)===void 0)throw new Error(`Unknown thread: ${a}`);await r.journal.transact(a,()=>({rows:n===h(r,a)?[]:[d.entry({mode:n},{threadId:a})],value:void 0}))},opening(r){let o=s.parse(r);return t=>{if(t.kind==="send")throw new Error(`Modes ${e.name}: opening rows only open a thread`);let{threadId:n,opening:a}=t;if(e.authority==="conversation"&&a.origin!==null)throw new Error(`Modes ${e.name}: thread ${n} is in its conversation's mode`);return[d.entry({mode:o},{threadId:n})]}}}}export{m as a,$ as b};
@@ -0,0 +1,6 @@
1
+ import{a as h}from"./PUSUPTAT.js";import{c as _}from"./CQEVREBT.js";import{a as T}from"./OL5A6ITQ.js";import{a as S}from"./S34ZA2R6.js";import{b as $,c as b}from"./6FRNHMCV.js";import{d as N}from"./DDANMY45.js";import{m as E}from"./MMNNZCBO.js";import{basename as G,join as x}from"node:path";import{scopeOf as C}from"@leuduan/cordis";import{z as l}from"zod";var P=l.string().min(1).refine(t=>G(t)===t&&t!=="."&&t!=="..","A name, not a path"),z=l.strictObject({fileNames:l.array(P).min(1),maxBytes:l.number().int().positive()}),k="agents-md",F="agents-md",L=l.strictObject({discovery:l.strictObject({file_names:l.array(l.string()),max_bytes:l.number().int().positive()}),file:l.strictObject({path:l.string(),bytes:l.number().int().nonnegative(),told_bytes:l.number().int().nonnegative()}).nullable()}),v=$({plugin:"lagent:agents-md",kind:"agents-md-notice",version:5,schema:L}),q=["ENOENT","ENOTDIR"],A=(t,e)=>t.max_bytes===e.maxBytes&&U(t.file_names,e.fileNames),U=(t,e)=>t.length===e.length&&t.every((n,o)=>n===e[o]);function j(t,e,n){let{holder:o,fileNames:r,maxBytes:d}=e,c=C(t);if(c===void 0)throw new Error(`${o} tells one thread: mount it in that thread's scope`);S(t,"agents-md",c,o,i=>`This thread is already told its AGENTS.md by ${i}; a thread has one agents-md, not ${o} too`);let s=new AbortController;t.effect(()=>()=>s.abort(new Error("The agents-md briefing was unmounted")));let a=null,m=null,p=()=>{let i=b(t.journal.state(v.told,n));return i!==null&&A(i.value.discovery,e)},y=()=>(m??=(async()=>{try{let i=t.journal.summary(n)?.environment.cwd;if(i===void 0)return;let w=t.confinement.epoch,u=await W(t,n,i,r,d,s.signal);u!==M&&(a={epoch:w,cwd:i,file:u})}catch(i){h.warn("Reading no AGENTS.md: it could not be prepared",i)}finally{m=null}})(),m);return t.on("lagent/llm/step",i=>{let{threadId:w}=i,u=b(t.journal.state(v.told,w));if(u!==null&&A(u.value.discovery,e)){u.visible||J(t.journal,i,u.row.seq);return}let g=t.journal.summary(w)?.environment.cwd;if(g===void 0)return;if(a===null||a.epoch!==t.confinement.epoch||a.cwd!==g){a=null,y();return}let{file:f}=a,D=f===null?V(g,r):Q(f,r),I=f===null?null:{path:f.path,bytes:f.bytes,told_bytes:f.told_bytes},R={file_names:[...r],max_bytes:d};i.contribute(v.contribution({content:D},{discovery:R,file:I}))}),p()?Promise.resolve():y()}var at=T({id:k,placement:"thread",schema:z,inject:["journal","confinement"],async setup(t,e,n){if(n.kind==="selected"){await j(t,{holder:"agents-md for its agents",...e},n.thread.id);return}let o=j(t,{holder:`agents-md installation ${n.installationId}`,...e},n.thread.id);_(t,{presetId:k,config:e,installationId:F}),await o}});function J(t,e,n){let o=t.eventAt(n);if(o?.type!=="input/message"||o.data.source===null)throw new Error(`Row ${n} is not the AGENTS.md notice it was folded from`);let{role:r,content:d,source:c}=o.data;e.contribute(E({role:r,content:d,source:c,source_seqs:[o.seq]}))}var M=Symbol("refused");async function W(t,e,n,o,r,d){let c=t.confinement.open(e,d);try{try{await c.files.identity()}catch(s){return h.warn("Reading no AGENTS.md: the confinement refused the read",s),M}for(let s of o){let a=await H(c.files,x(n,s),r);if(a!==null)return a}return null}finally{await c.end()}}async function H(t,e,n){let o;try{o=await t.open(e)}catch(r){return N(r,...q)||h.warn(`Skipping ${e}`,r),null}try{let r=await o.stat();if(!r.isFile())return h.warn(`Skipping ${e}`,new Error("not a regular file")),null;let d=Math.min(r.size,n)+1,c=[],s=0;for(;s<d;){let i=await o.read(s,d-s);if(i.length===0)break;c.push(i),s+=i.length}let a=Buffer.concat(c,s),m=s>n,p=m?a.subarray(0,K(a,n)):a,y=p.toString("utf8");return!m&&y.trim()===""?null:{path:e,bytes:Math.max(r.size,s),told_bytes:p.byteLength,text:y}}catch(r){return h.warn(`Skipping ${e}`,r),null}finally{await o.close()}}function K(t,e){let n=e;for(;n>0&&(t[n]&192)===128;)n-=1;return n}var O=t=>t.length===1?t[0]:`${t.slice(0,-1).join(", ")} or ${t.at(-1)}`,B=t=>`When you work in a directory below the working directory, look there for ${O(t)} and follow it within that directory's tree.`;function Q(t,e){let n=["The following workspace instructions may be relevant to your work. Use them as guidance when applicable.",`They are the instruction file in the working directory. It governs the directory tree it is in. System, developer and direct user instructions take precedence over it. ${B(e)}`].join(`
2
+ `),o=`<agents_md path=${JSON.stringify(t.path)}>
3
+ ${t.text}
4
+ </agents_md>`,r=t.told_bytes>=t.bytes?[]:[`[Truncated: ${t.path} was cut after ${t.told_bytes} of its ${t.bytes} bytes. Read the rest with read_file.]`];return[n,o,...r].join(`
5
+
6
+ `)}function V(t,e){return`There is no ${O(e)} in ${t}: this workspace gives no instructions of its own. ${B(e)}`}export{z as a,k as b,F as c,j as d,at as e};
@@ -0,0 +1,3 @@
1
+ import{d}from"./CUK7CGC7.js";import{J as m}from"./BPRCULZH.js";import{a as u}from"./MMNNZCBO.js";import{Service as P,scopeOf as k,scopeParentOf as w,ScopeLayers as S}from"@leuduan/cordis";var g=class extends P{static inject=["agents","tools"];layers=new S(()=>[]);constructor(t){super(t,"prompts")}contribute(t,o){let i=this.layers.layer(t);return i.push(o),()=>{let n=i.indexOf(o);n>=0&&i.splice(n,1)}}render(t,o,i){let n=this.ctx.agents.resolve(t,o);if(n===void 0)throw new m(o);let{agent:r}=n,x={agent:r,thread:i,tools:this.ctx.tools.toolsFor(t,o)},a={base:r.basePrompt?[{tag:"base",content:r.basePrompt}]:[],instruction:[],context:[]},b=new Set(n.layer===void 0?[]:this.layers.closestFirst(w(n.layer)));for(let l of this.layers.globalFirst(t)){let h=l.filter(e=>d(e.agents,o)).filter(e=>e.slot!=="base"||!b.has(l)).sort((e,c)=>(e.order??0)-(c.order??0)||e.tag.localeCompare(c.tag));for(let e of h){let c=a[e.slot],f=e.render(x),p=c.findIndex(y=>y.tag===e.tag);f===null?p>=0&&c.splice(p,1):p>=0?c[p]={tag:e.tag,content:f}:c.push({tag:e.tag,content:f})}}return F({basePrompt:a.base.map(l=>l.content).join(`
2
+
3
+ `),instructions:a.instruction,contextSections:a.context})}},A=(s,t)=>s.effect(()=>s.prompts.contribute(k(s),t));function F(s){let t=[];s.basePrompt.trim()&&t.push({kind:"base",tag:null,text:s.basePrompt.trim()});let o=(i,n)=>i.filter(r=>r.content.trim().length>0).map(r=>({kind:n,tag:r.tag,text:u(r.tag,r.content.trim())}));return t.push(...o(s.instructions,"instruction")),t.push(...o(s.contextSections,"context")),t}export{g as a,A as b};