@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
package/README.md CHANGED
@@ -17,7 +17,9 @@ import { resolve } from 'node:path'
17
17
  import { Context } from '@leuduan/cordis'
18
18
  import { base, core, heldOrSettled, registerProvider, waitForRun } from '@leuduan/lagent'
19
19
  import { codexAuthPath, codexProvider } from '@leuduan/lagent/providers'
20
- import { SqliteJournalStore } from '@leuduan/lagent/sqlite'
20
+ import { threadDirs } from '@leuduan/lagent/plugins/threadDirs'
21
+ import { truncateToolOutput } from '@leuduan/lagent/plugins/truncateToolOutput'
22
+ import { SqliteJournalStore } from '@leuduan/lagent/stores/sqlite'
21
23
 
22
24
  const root = new Context()
23
25
  const cwd = process.cwd()
@@ -27,10 +29,11 @@ try {
27
29
  await root.plugin(core, {
28
30
  store: new SqliteJournalStore(`${dataDir}/journal`, { lockDirectory: `${dataDir}/locks`, busyTimeoutMs: 1_000 }),
29
31
  cwd,
30
- dataDir,
31
32
  retention: 'retire',
32
33
  chainLimit: 10,
33
34
  })
35
+ // Where each thread keeps files of its own; a host with no file system mounts none.
36
+ await root.plugin(threadDirs, { dataDir })
34
37
  registerProvider(
35
38
  root,
36
39
  codexProvider({
@@ -41,6 +44,7 @@ try {
41
44
  { retry: { maxAttempts: 3, baseDelayMs: 500, maxDelayMs: 10_000 } },
42
45
  )
43
46
  await root.plugin(base)
47
+ await root.plugin(truncateToolOutput, { spill: true })
44
48
  // Nothing runs before this: every plugin a thread needs is mounted.
45
49
  await root.threads.start({ resume: 'none', startLimit: 4 })
46
50
 
@@ -66,7 +70,7 @@ try {
66
70
 
67
71
  `base` supplies plumbing and a `main` agent with no granted tools. For coding, the host registers
68
72
  workspace, command and other capability plugins, then installs `codexPreset` on a thread, or mounts
69
- it on the root for an agent selector, to grant them to that thread's agent. Composition and required host configuration are explained in [Plugin authoring](docs/plugins.md).
73
+ it on the root for an agent selector, to grant them to that thread's agent. Composition and required host configuration are explained in [Plugin authoring](docs/guides/plugins.md).
70
74
 
71
75
  ## Core model
72
76
 
@@ -86,6 +90,9 @@ Tools and grants are live registrations. Prompts are rendered once after readine
86
90
  plugin guidance uses that same prompt. Rebuild explicitly when a conversation should receive new
87
91
  instructions. Dynamic thread facts enter the conversation as sourced notices.
88
92
 
93
+ Tool results render as `<tool:output success="true">` or `<tool:output success="false">`, with
94
+ optional notes in a following `<tool:notes>` section. Non-text payloads accompany the rendered text.
95
+
89
96
  ## Reading and driving threads
90
97
 
91
98
  ```ts
@@ -102,28 +109,34 @@ execution finishes is carried to a successor request, so after the wait the answ
102
109
  the run `thread.summary.pending_run` then names, which is the one to wait for next.
103
110
 
104
111
  The host records what a person did, presents confirmations, failures and background work from
105
- `threads.inspect` and run events, and decides when to `start`. [Threads and recovery](docs/lifecycle.md)
112
+ `threads.inspect` and run events, and decides when to `start`. [Threads and recovery](docs/guides/threads.md)
106
113
  explains holds, cancellation, input ordering, forks, read lifetimes and recovery.
107
114
 
108
115
  The host supplies environment-dependent configuration. Lagent does not choose a workspace,
109
116
  credential file, skill root or subprocess environment from its own process, and refuses a relative
110
- core `cwd`, `dataDir`, thread `cwd` or read root rather than resolve it against the process directory. Core's
111
- `dataDir` is required either way; `null` turns thread directories off for a host without a filesystem of its
112
- own, and the plugins that need them (`truncateToolOutput`, `commands`, `sandbox`) then refuse to mount. One process holds one
117
+ core `cwd`, thread-directories `dataDir` or thread `cwd` rather than resolve it against the process
118
+ directory. Core has no data directory: a host with a file system mounts `threadDirs` with one, and the
119
+ plugins that keep files there (`commands`, and `truncateToolOutput` with `spill: true`) stay pending until it
120
+ is. A host without one, such as a Durable Object, mounts none and gives truncation `spill: false`. One process holds one
113
121
  journal; incompatible journal formats and extension payloads are refused rather than migrated.
114
122
 
123
+ The package's major version is the journal version (`JOURNAL_VERSION` in `src/journal/store.ts`): whenever it
124
+ increases, bump the major version in `package.json` to match, with minor and patch reset to zero.
125
+
115
126
  ## Imports
116
127
 
117
- Use the explicit [package entry points](package.json). The root serves applications;
118
- `@leuduan/lagent/plugin` serves plugin authors; `llm` and `models` expose their contracts, the provider
119
- contract included; `providers` holds the shipped providers; `sqlite` holds the SQLite store, the one
120
- door that needs `node:sqlite`; `durable-object` holds the store over a Cloudflare Durable Object's SQLite storage; `sandbox` holds the optional OS sandbox for shell commands, the launch handler of `ctx.launches`, whose
128
+ Use the explicit [package entry points](package.json). The root serves applications, including the
129
+ processes a host owns (`spawnCommand`, `runToCompletion`; a tool never uses them);
130
+ `@leuduan/lagent/plugin` serves plugin authors; `llm` and `records` expose their contracts, the provider
131
+ contract included; `providers` holds the shipped providers; `stores/sqlite` holds the SQLite store, the one
132
+ door that needs `node:sqlite`; `stores/durableObject` holds the store over a Cloudflare Durable Object's SQLite storage; `plugins/sandbox` holds the optional OS sandbox, the confinement handler of `ctx.confinement` for commands and, through one policy, for file access, whose
121
133
  worker thread is the one module that loads `@anthropic-ai/sandbox-runtime`; `plugins/<name>` exposes a feature; `testing` holds test helpers. Each
122
134
  door lists its names; implementation subpaths are private.
123
135
 
124
- In Cloudflare Workers with `nodejs_compat`, every door imports except `sandbox`, which also needs
136
+ In Cloudflare Workers with `nodejs_compat`, every door imports except `plugins/sandbox`, which also needs
125
137
  `new_module_registry`. Features that need a filesystem outside `/tmp`, processes or `node:sqlite` fail
126
- when used. The Workers tests run in workerd with `pnpm -F @leuduan/lagent run test:workers`.
138
+ when used. A Workers composition is core, `base` and `truncateToolOutput` with `spill: false`, plus tools that work there:
139
+ no `threadDirs`, `commands` or sandbox. The Workers tests run one in workerd with `pnpm -F @leuduan/lagent run test:workers`.
127
140
 
128
141
  MCP clients identify themselves with the version statically imported from the package metadata,
129
142
  so bundled hosts carry the same version as source and `dist/` consumers.
@@ -131,8 +144,8 @@ so bundled hosts carry the same version as source and `dist/` consumers.
131
144
  ## Guides
132
145
 
133
146
  Start with the [documentation map](docs/README.md). It distinguishes usage contracts from the design
134
- records explaining decisions. [Architecture](docs/architecture.md) gives the ownership model.
135
- The Works host is an application example, documented in [its guide](../../apps/works/docs/agent.md).
147
+ records explaining decisions. [Architecture](docs/guides/architecture.md) gives the ownership model.
148
+ The lagentic host is an application example, documented in [its guide](../../apps/lagentic/docs/lagentic.md).
136
149
 
137
150
  ## Scripts
138
151
 
@@ -1,5 +1,5 @@
1
- import{a as S,b as P}from"./NAOUTU7A.js";import{a as j,d as H}from"./2OSESBIL.js";import{h as N,i as k,o as q}from"./YLNJXQ3Z.js";import{a as E,b as L,c as x}from"./KESCTXGO.js";import{q as C,w as O}from"./D7E6EWIE.js";import{z as ne}from"zod";import{z as p}from"zod";function M(e,n){let s=new Map;for(let t of e.lineage(n))N(t)&&s.set(t.seq,s.size+1);return s}function I(e,n){let s=M(e,n),t=new Set;for(let r of e.state(q,n).surface.entries)r.type!=="surface/replaced"&&t.add(r.row.seq);let o=[];for(let r of e.lineage(n)){let c=s.get(r.seq),d=c===void 0?null:k(r);c===void 0||d===null||o.push({number:c,role:d.role,name:r.type==="tool/result"?r.data.result.name:null,body:K(d),condensed:!t.has(r.seq)})}return o}var z=e=>E("message",L(e.body,["message"]),{attrs:{number:String(e.number),role:e.role,...e.name===null?{}:{name:e.name}}}),X=e=>`Message ${e.number} (${e.role}${e.name===null?"":` ${e.name}`})`;function K(e){let n=[],s=O(e);s.length>0&&n.push(s);for(let t of e.content){let o=Q(t);o!==null&&n.push(o)}for(let t of e.tool_calls)n.push(`-> call ${t.name} ${C(t)}`);for(let t of e.provider_calls)n.push(`-> ${t.name??t.type}${t.summary===null?"":`: ${t.summary}`}`);return n.length>0?n.join(`
1
+ import{b as S,c as P}from"./JFX2MXBA.js";import{d as H}from"./S34ZA2R6.js";import{c as j}from"./CUK7CGC7.js";import{o as N,p as k,s as q}from"./BPRCULZH.js";import{a as E,b as L,c as x}from"./MMNNZCBO.js";import{l as C,r as O}from"./D4PQP5MA.js";import{z as ne}from"zod";import{z as p}from"zod";function M(e,n){let s=new Map;for(let t of e.lineage(n))N(t)&&s.set(t.seq,s.size+1);return s}function I(e,n){let s=M(e,n),t=new Set;for(let r of e.state(q,n).surface.entries)r.type!=="surface/replaced"&&t.add(r.row.seq);let o=[];for(let r of e.lineage(n)){let c=s.get(r.seq),d=c===void 0?null:k(r);c===void 0||d===null||o.push({number:c,role:d.role,name:r.type==="tool/result"?r.data.result.name:null,body:K(d),condensed:!t.has(r.seq)})}return o}var z=e=>E("message",L(e.body,["message"]),{attrs:{number:String(e.number),role:e.role,...e.name===null?{}:{name:e.name}}}),X=e=>`Message ${e.number} (${e.role}${e.name===null?"":` ${e.name}`})`;function K(e){let n=[],s=O(e);s.length>0&&n.push(s);for(let t of e.content){let o=Q(t);o!==null&&n.push(o)}for(let t of e.tool_calls)n.push(`-> call ${t.name} ${C(t)}`);for(let t of e.provider_calls)n.push(`-> ${t.name??t.type}${t.summary===null?"":`: ${t.summary}`}`);return n.length>0?n.join(`
2
2
  `):"(no text)"}var Q=e=>{switch(e.type){case"text":return null;case"image":return`[image${e.media_type===null?"":`: ${e.media_type}`}, not shown]`;case"file":return`[file${e.filename===null?"":`: ${e.filename}`}${e.media_type===null?"":` (${e.media_type})`}, not shown]`}};var b=["history_read","history_search"],V=3e4,R=20,F=60,f=(e,n,s=null)=>({output:e,is_error:!1,notes:s,metadata:n});function Y(e){let n=I(e.ctx.journal,e.threadId);return{total:n.length,messages:n,condensed:n.filter(s=>s.condensed)}}var v=(e,n,s)=>e===1?n:s,B=e=>`Nothing has been condensed: all ${e} ${v(e,"message","messages")} of this conversation ${v(e,"is","are")} still in it.`,D=(e,n)=>`There is no message ${e}: this conversation has ${n} ${v(n,"message","messages")}.`;function W(e){let n=[];for(let s=0;s<e.length;){let t=s;for(;e[t+1]===e[t]+1;)t+=1;n.push(t===s?`${e[s]}`:`${e[s]} to ${e[t]}`),s=t+1}return n.length===1?n[0]:`${n.slice(0,-1).join(", ")} and ${n.at(-1)}`}var U=(e,n)=>`No message from ${n} on has been condensed. ${A(e,n)??""}`.trim();function A(e,n){let s=e.messages.filter(t=>!t.condensed&&t.number>=n).map(t=>t.number);return s.length===0?null:s.length===1?`Message ${s[0]} is still in the conversation.`:`Messages ${W(s)} are still in the conversation.`}var Z=p.strictObject({from:p.number().int().min(1).default(1).describe("Message number to start from; the condensed messages from it on are shown."),offset:p.number().int().min(0).default(0).describe("Characters to skip in the transcript from `from`, which begins with the first condensed message at or after it. To continue a page, pass the `from` and `offset` it names.")}),G=S({name:"history_read",description:"Read back messages of this conversation that were condensed into a checkpoint, as a plain transcript by message number; a long one is paged, and each page names the `from` and `offset` that continue it. A message condensed in the meantime, after the one a page continues at, can still shift where it ends.",parameters:Z,onInterrupted:"rerun",executionMode:"parallel",async execute(e,n){let{from:s,offset:t}=e,o=Y(n),r={from:s,offset:t,total_messages:o.total,no_truncation:!0};if(o.condensed.length===0)return f(B(o.total),r);if(s>o.total)return f(D(s,o.total),r);let c=o.condensed.filter(m=>m.number>=s),d=A(o,s);if(c.length===0)return f(U(o,s),r);let l=[],a="";for(let m of c){a.length>0&&(a+=`
3
3
 
4
4
  `);let _=z(m);l.push({number:m.number,start:a.length,end:a.length+_.length}),a+=_}if(t>=a.length)return f(`Offset ${t} is past the end: the transcript from message ${s} is ${a.length} characters long.`,{...r,total_chars:a.length});let i=Math.min(t+V,a.length),T=x(a,i,"end");T>t&&(i=T);let g=i<a.length,$=l.filter(m=>m.end>t&&m.start<i),y=$[0].number,h=$.at(-1).number,u=[y===h?`This page covers condensed message ${y}.`:`This page covers condensed messages ${y} to ${h}.`],w=null;if(g){let m=l.findLast(_=>_.start<=i);w={from:m.number,offset:i-m.start},u.push(`Showing characters ${t}-${i} of ${a.length} of the transcript from message ${s}; continue with from=${w.from}, offset=${w.offset}.`)}return d!==null&&u.push(d),f(a.slice(t,i),{...r,total_chars:a.length,truncated:g,next:w},u)}}),ee=p.strictObject({query:p.string().min(1).describe("Text to find: literal, not a pattern, and not case-sensitive."),from:p.number().int().min(1).default(1).describe("Message number to start from; earlier messages are not searched.")}),J=S({name:"history_search",description:`Search messages of this conversation that were condensed into a checkpoint for some text. Lists up to ${R} matching message numbers with a snippet each; read one in full with history_read.`,parameters:ee,onInterrupted:"rerun",executionMode:"parallel",async execute(e,n){let{query:s,from:t}=e,o=Y(n),r={query:s,from:t,total_messages:o.total};if(o.condensed.length===0)return f(B(o.total),r);if(t>o.total)return f(D(t,o.total),r);let c=o.condensed.filter(h=>h.number>=t);if(c.length===0)return f(U(o,t),r);let d=new RegExp(s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"iu"),l=[],a=0,i=null;for(let h of c){a+=1;let u=d.exec(h.body);if(u!==null&&(l.push(`${X(h)}: ${te(h.body,u.index,u[0].length)}`),l.length>=R&&a<c.length)){i=h.number;break}}let g=[`Scanned ${a} of ${c.length} condensed message${c.length===1?"":"s"} from message ${t}; ${l.length} matched.`];i!==null&&g.push(`Stopped after ${R} matches, so later messages were not scanned; continue with from=${i+1}.`);let $=A(o,t);$!==null&&g.push(`${$} A search does not look at messages the conversation still holds.`);let y=l.length>0?l.join(`
5
- `):`No condensed message matches "${s}".`;return f(y,{...r,scanned:a,matched:l.length,stopped_early:i!==null},g)}});function te(e,n,s){let t=x(e,Math.max(0,n-F),"start"),o=x(e,Math.min(e.length,n+s+F),"end"),r=e.slice(t,o).replace(/\s+/g," ").trim();return`${t>0?"\u2026":""}${r}${o<e.length?"\u2026":""}`}var we=(e,n)=>n===1?`Read it whole with ${b[0]} (from: ${e}), or search it with ${b[1]}.`:`Read any of them whole with ${b[0]} (from: ${e}), or search them with ${b[1]}.`,se=ne.strictObject({agents:j}),_e={name:"lagent:history-recall",inject:["tools"],apply(e,n){H(e,"historyRecall");let{agents:s}=se.parse(n);for(let t of[G,J])P(e,t,{agents:s})}};export{M as a,b,we as c,se as d,_e as e};
5
+ `):`No condensed message matches "${s}".`;return f(y,{...r,scanned:a,matched:l.length,stopped_early:i!==null},g)}});function te(e,n,s){let t=x(e,Math.max(0,n-F),"start"),o=x(e,Math.min(e.length,n+s+F),"end"),r=e.slice(t,o).replace(/\s+/g," ").trim();return`${t>0?"\u2026":""}${r}${o<e.length?"\u2026":""}`}var _e=(e,n)=>n===1?`Read it whole with ${b[0]} (from: ${e}), or search it with ${b[1]}.`:`Read any of them whole with ${b[0]} (from: ${e}), or search them with ${b[1]}.`,se=ne.strictObject({agents:j}),xe={name:"lagent:history-recall",inject:["tools"],apply(e,n){H(e,"historyRecall");let{agents:s}=se.parse(n);for(let t of[G,J])P(e,t,{agents:s})}};export{M as a,b,_e as c,se as d,xe as e};
@@ -0,0 +1,7 @@
1
+ import{b as I}from"./VYMT4TXD.js";import{a as x}from"./3UMZMPWW.js";import{a as M}from"./34KW6VNQ.js";import{b as z,c as B}from"./JFX2MXBA.js";import{d as W}from"./S34ZA2R6.js";import{c as P}from"./CUK7CGC7.js";import{a as _,d as O}from"./DDANMY45.js";import{a as F}from"./MMNNZCBO.js";import{isAbsolute as fe}from"node:path";import{scopeOf as de}from"@leuduan/cordis";import{z as L}from"zod";import{join as R,resolve as X}from"node:path";import{parse as V}from"yaml";var Z=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?/;function ee(e){let t=Z.exec(e);if(t===null)return{frontmatter:{},body:e};let r=V(t[1])??{};return{frontmatter:r!==null&&typeof r=="object"&&!Array.isArray(r)?r:{},body:e.slice(t[0].length)}}var K=[".claude/skills",".agents/skills"],te=e=>[R(e,".claude","skills")];function oe(e,t){return[...t.workspace.map(r=>X(e,r)),...t.host]}var v=e=>typeof e=="string"?e.trim():"",re=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):[],G=4*1024*1024,b=class extends Error{constructor(t,r){super(t,r),this.name="SkillDocumentError"}};async function N(e,t,r){let o=await e.open(t),i;try{let s=await o.stat();if(!s.isFile())throw new b("not a regular file");if(s.size>G)throw new b(`larger than ${G} bytes`);i=(await o.readAll()).toString("utf8")}finally{await o.close()}let h;try{h=ee(i)}catch(s){throw new b(s instanceof Error?s.message:String(s),{cause:s})}let{frontmatter:a,body:u}=h;return{name:v(a.name)||r,directoryName:r,path:t,description:v(a.description),whenToUse:v(a.when_to_use)||v(a.whenToUse),aliases:re(a.aliases),body:u,frontmatter:a}}var ne=e=>[e.name,e.directoryName,...e.aliases].map(t=>t.toLowerCase());async function se(e,t,r=()=>{},o=new AbortController().signal){let i=[],h=new Set,a=new Set,u=(y,m)=>{o.throwIfAborted(),r({path:y,reason:m instanceof Error?m.message:String(m)})},s=async y=>{let m=X(y),c;try{if(!(await e.stat(m)).isDirectory())return;c=await e.realpath(m)}catch(f){o.throwIfAborted(),O(f,"ENOENT","ENOTDIR")||u(m,f);return}if(a.has(c))return;a.add(c);let p;try{p=(await e.readdir(m)).entries}catch(f){u(m,f);return}if(p.find(f=>f.name==="SKILL.md"&&!f.isDirectory&&!f.isSymbolicLink)!==void 0){let f=R(m,"SKILL.md"),n;try{n=await N(e,f,ie(m))}catch(l){u(f,l);return}let d=ne(n);if(d.some(l=>h.has(l)))a.delete(c);else{for(let l of d)h.add(l);i.push(n)}return}for(let f of p)(f.isDirectory||f.isSymbolicLink)&&await s(R(m,f.name))};for(let y of t)await s(y);return i}async function Y(e,t,r,o,i,h){let a=oe(t,r);return{workspaceRoot:t,roots:a,skills:await se(e,a,i,h),...o,unavailable:null}}var q=(e,t,r)=>({workspaceRoot:e,roots:[],skills:[],identity:"",epoch:t,unavailable:r}),ie=e=>e.split(/[\\/]/).filter(Boolean).pop()??e,ae=e=>e.split(`
2
+ `).map(r=>r.trim()).find(r=>r.length>0&&!r.startsWith("#"))??"";function T({skills:e,workspaceRoot:t,roots:r}){return e.length===0?r.length>0?`No skills were discovered in:
3
+ ${r.map(i=>`- ${I(t,i)}`).join(`
4
+ `)}`:"No skills were discovered.":[...e].sort((o,i)=>o.name.toLowerCase().localeCompare(i.name.toLowerCase())).map(o=>{let i=o.description||ae(o.body);o.whenToUse&&(i=i?`${i} When to use: ${o.whenToUse}`:`When to use: ${o.whenToUse}`);let h=o.aliases.length>0?` (aliases: ${o.aliases.join(", ")})`:"";return`- ${o.name}${h}: ${i} [${I(t,o.path)}]`}).join(`
5
+ `)}import{dirname as le}from"node:path";import{z as H}from"zod";var A="skill",ce=H.strictObject({skill:H.string().nullable().default(null).describe("Skill name to load; omit to list the available skills.")}),J=e=>z({name:A,description:"List filesystem-backed skills, or load one by name to get its full instructions.",parameters:ce,onInterrupted:"rerun",executionMode:"parallel",async execute(t,r){let o=e(r.threadId);if(o===void 0)throw new Error("This thread has no skill catalog yet: skills was mounted after it was activated");if(o.unavailable!==null)throw new Error(`Skills are unavailable for this thread: ${o.unavailable}`);let{files:i}=r.operation,h=await i.identity()===o.identity&&r.ctx.confinement.epoch===o.epoch,a=[];for(let c of o.skills)try{h?(await i.stat(c.path),a.push(c)):a.push(await N(i,c.path,c.directoryName))}catch(p){if(p instanceof x||p instanceof b||O(p,"ENOENT","ENOTDIR"))continue;throw p}if(t.skill===null)return{output:T({...o,skills:a}),metadata:{skill_count:a.length}};let u=t.skill.toLowerCase(),s=a.find(c=>c.name.toLowerCase()===u||c.directoryName.toLowerCase()===u||c.aliases.some(p=>p.toLowerCase()===u));if(s===void 0){let c=a.map(p=>p.name).join(", ")||"(none)";throw new Error(`Unknown skill '${t.skill}'. Available: ${c}`)}let y=le(s.path),{body:m}=s;return{output:`Skill directory: ${y}
6
+
7
+ ${m.trim()}`,metadata:{skill:s.name,path:s.path,directory:y,no_truncation:!0}}}});var me=L.strictObject({roots:L.array(L.string().refine(fe,"a skill root the host names must be absolute")),workspaceRoots:L.array(L.string()).default([...K]),agents:P.optional(),autoload:L.boolean().default(!0)}),Ue={name:"lagent:skills",inject:["tools","prompts","confinement"],apply(e,t){W(e,"skills");let{roots:r,workspaceRoots:o,agents:i,autoload:h}=me.parse(t),a={workspace:o,host:r},u=new Map,s=new Map;B(e,J(n=>u.get(n)),i===void 0?{}:{agents:i});let y=new Set,m=({path:n,reason:d})=>{let l=`${n}\0${d}`;y.has(l)||(y.add(l),e.reportError(new Error(`Skipped the skill at ${n}: ${d}`)))},c=new Set;e.effect(()=>()=>{for(let n of[...c])n()});let p=new AbortController;e.effect(()=>()=>p.abort(new Error("The skills plugin was unmounted")));let D=async(n,d,l)=>{let S=e.confinement.open(n,p.signal);try{if(await S.files.identity()!==l.identity)throw new Error("what this thread may read changed while its skills were being read");return await Y(S.files,d,a,l,m,p.signal)}finally{await S.end()}};e.on("lagent/thread/activate",async(n,d)=>{let l=n.environment.cwd,S=e.confinement.open(n.id,d),w,g,k;try{let E=e.confinement.epoch,U=await S.files.identity();if(w=[l,U,E].join("\0"),s.get(w)===void 0){let C={catalog:D(n.id,l,{identity:U,epoch:E}),holders:0};C.catalog.catch(()=>{s.get(w)===C&&s.delete(w)}),s.set(w,C)}g=s.get(w),g.holders+=1,k=await M(g.catalog,d)}catch(E){g!==void 0&&w!==void 0&&f(w,g),g=void 0,d.aborted||e.reportError(new Error(`No skills for thread ${n.id}: ${_(E)}`)),k=q(l,e.confinement.epoch,_(E))}finally{await S.end()}u.set(n.id,k);let Q=h?e.prompts.contribute(de(n.ctx),pe(e,k)):()=>{},j=n.ctx.effect(()=>()=>{c.delete(j),Q(),u.get(n.id)===k&&u.delete(n.id),g!==void 0&&w!==void 0&&f(w,g)});c.add(j)}),e.on("lagent/llm/request",(n,d)=>{let l=u.get(n.threadId),w=l!==void 0&&l.unavailable===null&&l.epoch===e.confinement.epoch&&l.skills.length>0?F($,T(l)):null,g=n.systemPrompt;return g.some(k=>k.tag===$)&&(n.systemPrompt=g.flatMap(k=>k.tag!==$?[k]:w===null?[]:[{...k,text:w}])),d()});let f=(n,d)=>{d.holders-=1,d.holders===0&&s.get(n)===d&&s.delete(n)}}},$="availableSkills",pe=(e,t)=>({tag:$,slot:"instruction",agents:"all",render:({tools:r})=>t.unavailable===null&&t.epoch===e.confinement.epoch&&t.skills.length>0&&r.some(o=>o.name===A)?T(t):null});export{K as a,te as b,A as c,Ue as d};
@@ -0,0 +1 @@
1
+ import{d as q}from"./DDANMY45.js";import{constants as u,realpath as Y}from"node:fs";import*as d from"node:fs/promises";import{lstat as b,open as R,readdir as K,stat as M}from"node:fs/promises";import{basename as C,dirname as I,isAbsolute as W,join as g,resolve as _}from"node:path";import{promisify as z}from"node:util";var f=class extends Error{constructor(w){super(w),this.name="FileAccessError"}},X=z(Y.native);async function m(o){try{return await X(o)}catch(h){if(!q(h,"ENOENT","ENOTDIR"))throw h}let w=I(o);return w===o?o:g(await m(w),C(o))}var F=(o,w)=>o.dev===w.dev&&o.ino===w.ino,A=["read"],O=["write"],j=["read","write"];function Z(o){let w=!1,h=new Set,L=new Set,k=new Map,T=new Map,l=t=>{if(w)return Promise.reject(new Error("This file access has ended: files may be used only during the call that was given them"));let r=t();h.add(r);let e=()=>{h.delete(r)};return r.then(e,e),r},c=()=>{if(w)throw new Error("This file access has ended");o.signal().throwIfAborted()},y=async t=>{let r=await t;return c(),r},P=async t=>{let r=await b(t.resolved).catch(()=>null);r!==null&&r.isFile()&&F(r,t.identity)&&await d.unlink(t.resolved)},E=t=>{let r=T.get(t);if(r!==void 0)return r;if(!L.delete(t))return Promise.resolve();let e=t.close();T.set(t,e);let a=()=>{T.delete(t)};return e.then(a,a),e},N=async(t,r,e,a=A)=>{if(!W(t))throw new Error(`File paths are absolute here, not ${t}`);let n=_(t);if(c(),r===null)return{requested:n,resolved:n,identity:null};let s=e==="follow"?await m(n):g(await m(I(n)),C(n)),i=await b(s).catch(v=>{if(q(v,"ENOENT","ENOTDIR"))return null;throw v});c();for(let v of new Set([n,s]))for(let D of a){let $=r.check(v,D);if(!$.allowed)throw new f(v===n?$.reason:`${$.reason} (${n} resolves to ${s})`)}return{requested:n,resolved:s,identity:i}},S=async(t,r,e)=>N(t,await o.policy(),r,e?.access??A),p=async(t,r,e)=>{let a=await N(t,r,"keep",e),n=await b(a.resolved).catch(s=>{if(q(s,"ENOENT","ENOTDIR"))return null;throw s});if(c(),n===null||n.isFile())return a;if(n.isSymbolicLink()){let s=await d.readlink(a.resolved).catch(()=>"?");throw new f(`${a.requested} is a symbolic link to ${s}; nothing is changed through a link, so name its target instead`)}throw new f(`${a.requested} is ${n.isDirectory()?"a directory":"not a regular file"}; only regular files are renamed, removed or changed here`)},x=t=>{let r=e=>l(async()=>(c(),y(e())));return{write:e=>r(async()=>{let a=0;for(;a<e.length;){let{bytesWritten:n}=await t.write(e,a,e.length-a,null);a+=n,c()}}),sync:()=>r(()=>t.sync()),stat:()=>r(()=>t.stat()),close:()=>E(t)}},B=t=>{let r=e=>l(async()=>(c(),y(e())));return{read:(e,a)=>r(async()=>{let n=Buffer.alloc(a),{bytesRead:s}=await t.read(n,0,a,e);return n.subarray(0,s)}),readAll:()=>r(()=>t.readFile()),stat:()=>r(()=>t.stat()),close:()=>E(t)}};return{identity:()=>l(async()=>(await o.policy())?.identity??"unrestricted"),open:t=>l(async()=>{let r=await o.policy(),e=await N(t,r,"follow"),a=r===null?await R(e.requested,u.O_RDONLY|u.O_NONBLOCK):await R(e.resolved,u.O_RDONLY|u.O_NOFOLLOW|u.O_NONBLOCK);L.add(a);try{if(c(),r!==null){let n=await a.stat();if(e.identity===null||!F(n,e.identity))throw new f(`${e.requested} changed while it was being opened; it was not read`);if(await m(e.requested)!==e.resolved)throw new f(`${e.requested} no longer leads to ${e.resolved}, which was checked; it was not read`);c()}}catch(n){throw await E(a).catch(()=>{}),n}return B(a)}),readdir:t=>l(async()=>{let r=await o.policy(),e=await N(t,r,"follow"),a=await y(K(e.resolved,{withFileTypes:!0}));if(r===null)return{entries:a.map(i=>({name:i.name,isDirectory:i.isDirectory(),isSymbolicLink:i.isSymbolicLink()})),hidden:0};let n=[],s=0;for(let i of a){c();let v=g(e.requested,i.name),D=i.isSymbolicLink()?await y(m(g(e.resolved,i.name))):g(e.resolved,i.name);[v,D].every(H=>r.check(H,"read").allowed)?n.push({name:i.name,isDirectory:i.isDirectory(),isSymbolicLink:i.isSymbolicLink()}):s+=1}return{entries:n,hidden:s}}),stat:(t,r)=>l(async()=>{let e=await S(t,"follow",r);return c(),y(M(e.resolved))}),lstat:(t,r)=>l(async()=>{let e=await S(t,"keep",r);return c(),y(b(e.resolved))}),realpath:(t,r)=>l(async()=>{let e=await o.policy(),a=await N(t,e,"follow",r?.access??A);return e===null?y(m(a.requested)):a.resolved}),create:(t,r)=>l(async()=>{let e=await o.policy(),a=await p(t,e,O),n=await R(a.resolved,u.O_WRONLY|u.O_CREAT|u.O_EXCL|u.O_NOFOLLOW,r?.mode??438);L.add(n);let s=null;try{if(s={resolved:a.resolved,identity:await n.stat()},c(),e!==null){if(g(await m(I(a.requested)),C(a.requested))!==a.resolved)throw new f(`${a.requested} no longer leads to ${a.resolved}, which was checked; nothing was kept`);c()}}catch(i){throw await E(n).catch(()=>{}),s!==null&&await P(s).catch(()=>{}),i}return r?.temporary===!0&&k.set(a.requested,s),x(n)}),mkdir:t=>l(async()=>{let r=await S(t,"follow",{access:O});c(),await d.mkdir(r.resolved,{recursive:!0})}),link:(t,r)=>l(async()=>{let e=await o.policy(),a=await p(t,e,j),n=await p(r,e,O);await d.link(a.resolved,n.resolved)}),rename:(t,r)=>l(async()=>{let e=await o.policy(),a=await p(t,e,j),n=await p(r,e,O);await d.rename(a.resolved,n.resolved)}),unlink:t=>l(async()=>{if(W(t)){let e=k.get(_(t));if(e!==void 0){let a=await b(e.resolved).catch(()=>null);if(a===null)throw Object.assign(new Error(`ENOENT: ${t} is gone`),{code:"ENOENT"});if(!F(a,e.identity))throw new f(`${t} is no longer the file this operation created, so it was left alone`);k.delete(_(t)),await d.unlink(e.resolved);return}}let r=await p(t,await o.policy(),O);await d.unlink(r.resolved)}),chmod:(t,r)=>l(async()=>{let e=await p(t,await o.policy(),O);await d.chmod(e.resolved,r)}),async end(){w=!0,await Promise.allSettled(h),await Promise.allSettled([...L].map(E)),await Promise.allSettled(T.values()),await Promise.allSettled([...k.values()].map(P)),k.clear()}}}export{f as a,Z as b};
@@ -0,0 +1 @@
1
+ import{B as q,e as g,f as w,s as a}from"./BPRCULZH.js";import{w as d}from"./BBCW2FZK.js";var f=200;function h(e,r,m){let c=e.rows(r),n=e.state(a,r).threadRecord;if(n===null)throw new Error(`Thread ${r} has no spawn row`);let o=e.state(a,r).turnBoundary,{inbox:s,threadRoute:p,requests:i,lastAnswer:R,waits:v}=e.state(a,r);if(p===null)throw new Error(`Thread ${r} has no route`);let{pending:l,latestSettlement:u,latestUserCancel:_}=i;return{thread_id:r,spawn_seq:n.seq,through_seq:c.at(-1)?.seq??n.seq,agent_name:n.agent_name,metadata:n.metadata,fork:n.fork,origin:n.origin,environment:n.environment,has_work:o.turnOpen||q(e,r,m),turn_open:o.turnOpen,last_reason:o.lastReason,route:p,queued_input:s["next-turn"].length+s["next-step"].length,queued_for_turn:s["next-turn"].length,unanswered_confirmations:w(e.state(a,r).confirmations,r).map(t=>({request_id:t.request_id,target:t.target,tool_name:t.tool_call.name,reason:t.reason.slice(0,f)})),waits:g(v).map(({declaration:t,value:E})=>({call_seq:t.call_seq,owner:t.owner,deadline_at:t.deadline_at,reason:t.reason.slice(0,f),resolved:E!==null})),pending_run:l===null?null:{run_id:l.runId,newest_cause_at:l.causes.at(-1)?.at??null,releasing:l.causes.some(t=>t.releases),cancelled:i.pendingCancel?.runId===l.runId},latest_settlement:u===null?null:{run_id:u.runId,outcome:u.outcome,reason:u.reason,error_text:u.errorText},latest_user_cancel:_===null?null:{seq:_.seq,released:i.latestReleasing!==null&&i.latestReleasing>_.seq},requires:[...n.requires],answered_at:R}}var A={name:"lagent:journal",async apply(e,r){let{store:m,limits:c}=r,n=new d(m,{summarize:(o,s)=>h(o,s,c),onListenerError:o=>e.reportError(o),coreFolds:[a]});n.onRevoked(o=>{e.parallel("lagent/journal/revoked",o).catch(s=>e.reportError(s))}),await n.open(),e.provide("journal",n),e.effect(()=>()=>n.close())}},b=e=>e.journal;export{h as a,A as b,b as c};
@@ -0,0 +1 @@
1
+ import{b as u,c as p}from"./7LI64H5X.js";import{b as v}from"./3UMZMPWW.js";import{Service as R}from"@leuduan/cordis";import{z as w}from"zod";var A=w.strictObject({launcher:w.string().min(1),version:w.string().min(1),policy:w.string().min(1)}),I="unconfined";function x(i){return"shell"in i?["/bin/sh","-c",i.shell]:i.argv}var C=i=>`thread:${i}`,S=1e3,y=new WeakMap,k=(i,e,t)=>({launch:i,files:e,end:t}),b=class extends R{root;changes=0;holdReads=null;constructor(e){super(e,"confinement");let t=e.reflect.target,n=y.get(t);n===void 0&&y.set(t,n={current:null}),this.root=n}handle(e){if(this.root.current!==null&&!this.root.current.closed)throw new Error("A confinement handler is already live");let t={handler:e,controller:new AbortController,operations:new Set,closed:!1,stopFailed:!1,released:null};return this.root.current=t,this.changes+=1,{release:n=>this.release(t,n),changed:()=>{this.changes+=1}}}get epoch(){return this.changes}open(e,t){let n=null,o=()=>n??=this.takeSnapshot(e,t),r=new AbortController,s=AbortSignal.any([t,r.signal]),a=Promise.withResolvers(),d=null,h=v({async policy(){let{registration:l,snapshot:c}=await o();return l!==null&&d===null&&(d=l,l.operations.add(a.promise),s=AbortSignal.any([t,r.signal,l.controller.signal])),c===null?null:c.files},signal:()=>s}),m=null;return k(async(l,c)=>{let{registration:f,snapshot:g}=await o();return f===null||g===null?this.spawnPlain(l,c):this.launchThrough(f,g,l,c)},h,()=>m??=(async()=>{r.abort(new Error("The operation ended"));try{await h.end()}finally{d?.operations.delete(a.promise),a.resolve()}})())}async retainReads(e){return await this.holdReads?.(e)??null}holdReadsWith(e){return this.holdReads=e,()=>{this.holdReads===e&&(this.holdReads=null)}}async takeSnapshot(e,t){let n=this.root.current;if(n===null)return{registration:null,snapshot:null};this.requireLive(n);let o=Promise.withResolvers();n.operations.add(o.promise);try{let r=AbortSignal.any([t,n.controller.signal]);r.throwIfAborted();let s=await this.retainReads(e),a;try{r.throwIfAborted(),a=await n.handler.snapshot(e)}finally{s?.release()}if(r.throwIfAborted(),n.closed)throw new Error("The confinement handler stopped while it took this snapshot");return{registration:n,snapshot:a}}catch(r){throw new u(r,{stopFailed:!1})}finally{n.operations.delete(o.promise),o.resolve()}}requireLive(e){if(e.closed)throw new u(new Error("Nothing can run: the handler that confines commands, searches and file access has stopped (released or failed), and nothing runs unconfined"),{stopFailed:!1})}async launchThrough(e,t,n,o){this.requireLive(e);let r=Promise.withResolvers();e.operations.add(r.promise);let s=this.spawnThrough(e,t,n,o);return s.then(a=>a.diagnostics,()=>{}).finally(()=>{e.operations.delete(r.promise),r.resolve()}),s}async spawnPlain(e,t){let{beforeRelease:n}=t,o={cwd:e.workdir,env:e.environment,signal:e.signal,...t.timeoutMs===void 0?{}:{timeoutMs:t.timeoutMs},killGraceMs:t.killGraceMs,...n===void 0?{}:{beforeRelease:s=>n(s,null)}};return{spawned:"shell"in e.program?await p({...o,command:e.program.shell}):await p({...o,command:e.program.argv,stdio:"pipes"}),cwd:e.workdir,launch:null,diagnostics:Promise.resolve(null)}}async spawnThrough(e,t,n,o){let r=AbortSignal.any([n.signal,e.controller.signal]),s,a;try{if(r.throwIfAborted(),s=await t.prepare({...n,signal:r}),r.throwIfAborted(),e.closed)throw new Error("The confinement handler stopped while it prepared this launch");a=A.parse(s.provenance)}catch(l){throw new u(l,{stopFailed:!1})}let{beforeRelease:d}=o,h;try{let l={command:s.argv,cwd:s.cwd,env:s.env,signal:r,...o.timeoutMs===void 0?{}:{timeoutMs:o.timeoutMs},killGraceMs:o.killGraceMs,...d===void 0?{}:{beforeRelease:c=>d(c,a)}};h=await p({...l,stdio:"shell"in n.program?"joined":"pipes"})}catch(l){throw l instanceof u&&l.stopFailed&&(e.stopFailed=!0),l}let m=h.result.then(l=>(l.stopFailed&&(e.stopFailed=!0),P(()=>s.violations())));return{spawned:h,cwd:s.cwd,launch:a,diagnostics:m}}release(e,t){if(e.released!==null)return e.released;e.closed=!0,this.changes+=1;let n=Promise.withResolvers();return e.released=n.promise,e.controller.abort(new Error("The confinement handler was released")),n.resolve(this.settle(e,t)),e.released}async settle(e,t){let n,o=await Promise.race([Promise.allSettled([...e.operations]).then(()=>"settled"),new Promise(r=>{n=setTimeout(()=>r("overran"),t)})]);return clearTimeout(n),o==="settled"&&!e.stopFailed}};async function P(i){let e;try{return await Promise.race([Promise.resolve().then(i).catch(()=>null),new Promise(t=>{e=setTimeout(()=>t(null),S)})])}finally{clearTimeout(e)}}export{A as a,I as b,x as c,C as d,S as e,b as f};
@@ -0,0 +1 @@
1
+ import{d as x}from"./CUK7CGC7.js";import{_ as b}from"./BPRCULZH.js";import{h}from"./BBCW2FZK.js";import{g as y,m as S}from"./MMNNZCBO.js";import{isDeepStrictEqual as _}from"node:util";var g=class extends Error{record;supportedVersion;constructor(n,i){super(`Unsupported ${n.plugin}/${n.kind} payload version ${n.version}; expected ${i}`),this.record=n,this.supportedVersion=i,this.name="ExtensionVersionError"}};function $(r){let n=y.omit({data:!0}).parse({plugin:r.plugin,instance_id:r.instanceId,kind:r.kind,version:r.version});r.policyState===!0&&b(n);let i=e=>e.plugin===n.plugin&&e.instance_id===n.instance_id&&e.kind===n.kind,d=e=>e.type==="ext"&&i(e.data),p=e=>{if(e.version!==n.version)throw new g(e,n.version);return r.schema.parse(structuredClone(e.data))},o=e=>y.parse({...n,data:r.schema.parse(e)}),a=e=>e!==null&&i(e)?p(e):void 0,l=e=>e.type==="input/message"?a(e.data.source):void 0,m=h({key:`told:${JSON.stringify([n.plugin,n.instance_id,n.kind])}`,init:()=>({notices:[]}),apply(e,t){let s=e.notices;if(t.type==="surface/replaced"){let k=null;for(let f of s)f.visible&&(k??=new Set(t.source_seqs),k.has(f.row.seq)&&(f.visible=!1));return e}let c=l(t);return c===void 0||s.push({row:{threadId:t.thread_id,seq:t.seq},value:c,visible:!0}),e}}),u=(e,t)=>({type:"ext",data:o(e),options:t});return{record:o,parse:e=>r.schema.parse(e),entry:u,append(e,t,s){let c=u(t,s);return e.append(c.type,c.data,c.options)},read(e){return d(e)?p(e.data):void 0},contribution(e,t,s={}){return S({...e,source:o(t),source_seqs:[...s.sourceSeqs??[]]})},matchesSource(e){return i(e)},rejection(e,t){return{decision:"reject",reason:e,source:o(t)}},readContribution:l,readSource:a,told:m,projection(e){return h({key:JSON.stringify([n.plugin,n.instance_id,n.kind,e.key]),init:e.init,onFork:e.onFork,apply:(t,s)=>d(s)?e.apply(t,p(s.data),s):t})}}}function C(r){return r.notices.at(-1)??null}function q(r){for(let n=r.notices.length-1;n>=0;n-=1){let i=r.notices[n];if(i.visible)return i.value}return null}function N(r,n){let{event:i,agents:d,rank:p}=n;r.on("lagent/llm/step",o=>{if(d!==void 0){let t=r.journal.summary(o.threadId);if(t===void 0||!x(d,t.agent_name))return}let a=n.current(o);if(a===void 0)return;let l=i.parse(a),m=r.journal.state(i.told,o.threadId),u=q(m);if(u!==null&&_(u,l))return;let e=n.render(l,u,{step:o,notices:m});e!==null&&o.contribute(i.contribution({content:e},a),p)})}export{g as a,$ as b,C as c,q as d,N as e};
@@ -0,0 +1,17 @@
1
+ import{a as P,c as b,d as D}from"./DDANMY45.js";import{c as T}from"./MMNNZCBO.js";import{spawn as C}from"node:child_process";import{StringDecoder as $}from"node:string_decoder";var _=3e3,E=class extends Error{stopFailed;code;constructor(e,s){super(P(e),{cause:e}),this.name="CommandStartFailure",this.stopFailed=s.stopFailed,this.code=b(e)}},A="IFS= read -r go <&3 || exit 125; exec 3<&-; ",F="exec 2>&1; ";async function G(t){let e=t.stdio==="pipes",s=e?A:A+F,n=typeof t.command=="string"?["-c",`${s}exec /bin/sh -c "$1"`,"sh",t.command]:["-c",`${s}exec "$@"`,"sh",...t.command],r;try{if(t.signal.throwIfAborted(),t.env===void 0||t.env===null)throw new TypeError("spawnCommand needs an env");r=C("/bin/sh",n,{cwd:t.cwd,detached:!0,env:t.env,stdio:e?["pipe","pipe","pipe","pipe"]:["ignore","pipe","ignore","pipe"]})}catch(a){throw new E(a,{stopFailed:!1})}let l=r.stdio[3];l.on("error",()=>{});let o=r.pid;if(o===void 0)throw new E(await new Promise(a=>r.once("error",a)),{stopFailed:!1});r.on("error",()=>{});let u=new Promise(a=>r.once("exit",(h,i)=>a({code:h,signal:i}))),c=e?[r.stdout,r.stderr]:[r.stdout];for(let a of[...c,...e?[r.stdin]:[]])a.on("error",()=>{});let p=Promise.all(c.map(a=>new Promise(h=>a.once("close",h)))).then(()=>{}),f=Date.now();try{await L.register(o),t.signal.throwIfAborted(),await t.beforeRelease?.(o),t.signal.throwIfAborted()}catch(a){l.destroy(),y(o,"SIGKILL");let h=await R(o,t.killGraceMs??_);for(let i of c)i.destroy();throw e&&r.stdin.destroy(),h?L.unregister(o):L.watchUntilEmpty(o),new E(a,{stopFailed:!h})}l.end(`go
2
+ `);let g={readables:c,stdin:e?r.stdin:null},w=new I({pid:o,streams:g,exited:u,outputClosed:p,startedAt:f},t);return e?Object.assign(w,{stdin:r.stdin,stdout:r.stdout,stderr:r.stderr}):Object.assign(w,{output:r.stdout})}async function B(t){let e=await G(t),s=new $("utf8"),n="";return e.output.on("data",l=>{n+=s.write(l)}),{...await e.result,output:n+s.end()}}var K=4096;async function J(t,e){let{onLine:s,maxLineChars:n,delimiter:r}=e;t.stdin.end();let l="",o=new $("utf8");t.stderr.on("data",i=>{l=(l+o.write(i)).slice(-K)});let u=new $("utf8"),c="",p=!1,f=!1,g=i=>{if(p)return;let d=n-c.length;if(i.length<=d){c+=i;return}c+=i.slice(0,T(i,d,"end")),p=!0},w=()=>{let i=c,d=p;c="",p=!1,s(i,d)===!1&&(f=!0,t.stop())},a=i=>{let d=0;for(;!f;){let m=i.indexOf(r,d);if(m===-1){g(i.slice(d));return}g(i.slice(d,m)),w(),d=m+1}};t.stdout.on("data",i=>{f||a(u.write(i))});let h=await t.result;return f||(a(u.end()),!f&&(c.length>0||p)&&w()),{...h,stderr:l+o.end()}}var I=class{pid;result;requestStop;constructor({pid:e,streams:s,exited:n,outputClosed:r,startedAt:l},o){this.pid=e;let u=o.killGraceMs??_,c=Promise.withResolvers();this.requestStop=c.resolve;let p=()=>c.resolve("abort");o.signal.addEventListener("abort",p,{once:!0});let f=o.timeoutMs===void 0?void 0:setTimeout(()=>c.resolve("timeout"),o.timeoutMs),g=async()=>{let w=await Promise.race([n.then(x=>({kind:"exit",exit:x})),c.promise.then(x=>({kind:"stop",cause:x}))]);clearTimeout(f),o.signal.removeEventListener("abort",p);let a=null,h=!1,i=!0,d;w.kind==="stop"?(a=w.cause,d=Date.now()+2*u,i=await R(e,u)):v(e)?(h=!0,d=Date.now()+2*u,i=await R(e,u)):d=Date.now()+u;let m=await M(n,d-Date.now());i&&await M(r,Math.min(u,d-Date.now()));for(let x of s.readables)x.destroy();return s.stdin?.destroy(),i?L.unregister(e):L.watchUntilEmpty(e),{exitCode:m?.code??null,exitSignal:m?.signal??null,stoppedBy:a,leftoversStopped:h,stopFailed:!i,durationMs:Date.now()-l}};this.result=g()}stop(){return this.requestStop("stop"),this.result}};function v(t){try{return process.kill(-t,0),!0}catch(e){return D(e,"EPERM")}}function y(t,e){try{process.kill(-t,e)}catch{}}var O=50;async function R(t,e){let s=Date.now(),n=!1;for(y(t,"SIGTERM");v(t);){let r=Date.now()-s;if(!n&&r>=e)y(t,"SIGKILL"),n=!0;else if(n&&r>=2*e)return!1;await U(O)}return!0}var U=t=>new Promise(e=>setTimeout(e,t));async function M(t,e){let s,n=new Promise(r=>s=setTimeout(()=>r(void 0),Math.max(0,e)));try{return await Promise.race([t,n])}finally{clearTimeout(s)}}var q=`trap '' INT TERM HUP
3
+ groups=' '
4
+ while IFS= read -r line; do
5
+ g=\${line#?}
6
+ case $line in
7
+ +*) case $groups in *" $g "*) ;; *) groups="$groups$g " ;; esac ;;
8
+ -*) case $groups in *" $g "*) groups="\${groups%% $g *} \${groups#* $g }" ;; esac ;;
9
+ esac
10
+ done
11
+ [ "$groups" = ' ' ] && exit 0
12
+ for g in $groups; do kill -TERM -$g 2>/dev/null; done
13
+ sleep 1
14
+ for g in $groups; do kill -KILL -$g 2>/dev/null; done
15
+ `,S=class{child;stdin;exited=!1;constructor(e,s){this.child=C("/bin/sh",["-c",q],{detached:!0,stdio:["pipe","ignore","ignore"]}),this.stdin=this.child.stdin,this.stdin.on("error",()=>{});let n=()=>{this.exited||(this.exited=!0,s(this))};this.child.once("exit",n),this.child.once("error",n),this.child.unref(),this.stdin.unref?.();for(let r of e)this.stdin.write(`+${r}
16
+ `)}get pid(){return this.child.pid}write(e){return this.exited?Promise.reject(new Error("The process reaper has exited")):new Promise((s,n)=>this.stdin.write(`${e}
17
+ `,r=>r?n(r):s()))}kill(){this.child.kill("SIGKILL")}},k=class{groups=new Set;stuck=new Set;reaper;exitListener=!1;watcher;async register(e){this.installExitListener(),this.groups.add(e);let s;for(let n=0;n<2;n++){let r=this.ensureReaper();try{await r.write(`+${e}`);return}catch(l){s=l,this.reaper===r&&(this.reaper=void 0)}}throw this.groups.delete(e),new Error("Could not register the command with the process reaper",{cause:s})}unregister(e){this.stuck.delete(e),this.groups.delete(e)&&this.reaper?.write(`-${e}`).catch(()=>{})}watchUntilEmpty(e){this.groups.add(e),this.stuck.add(e),this.watcher===void 0&&(this.watcher=setInterval(()=>{for(let s of this.stuck)v(s)||this.unregister(s);this.stuck.size===0&&(clearInterval(this.watcher),this.watcher=void 0)},1e3),this.watcher.unref())}tracked(){return[...this.groups]}reaperPid(){return this.reaper?.pid}killReaper(){this.reaper?.kill()}ensureReaper(){return this.reaper??=new S(this.groups,e=>this.onReaperExit(e)),this.reaper}onReaperExit(e){this.reaper===e&&(this.reaper=void 0,this.groups.size>0&&e.pid!==void 0&&this.ensureReaper())}installExitListener(){this.exitListener||(this.exitListener=!0,process.on("exit",()=>{for(let e of this.groups)y(e,"SIGKILL")}))}},L=new k;export{_ as a,E as b,G as c,B as d,J as e};
@@ -1 +1 @@
1
- import{b as m}from"./74HKUGRR.js";import{b as v}from"./DDANMY45.js";import{z as p}from"zod";function w(d){let{key:s,schema:a,version:o,applies:u,compute:l}=d;if(!Number.isInteger(o))throw new TypeError(`Contribution ${s}: its version must be an integer`);let f=p.strictObject({v:p.literal(o),value:a}),b=e=>({status:"available",value:e}),i=e=>({status:"unavailable",reason:e});return{key:s,register(e){let r=Promise.resolve([]);return e.effect(()=>{let t=m(e).contribute(s,(n,c)=>u(c)?{v:o,value:a.parse(l(e.journal,n))}:void 0,{refresh:n=>u(n)&&!f.safeParse(n.contributions[s]).success});return r=t.refreshed,t.withdraw}),{refreshed:r}},read(e,r){let t=e.summary(r);if(t===void 0)return i(`thread ${r} is not in the catalog`);if(!u(t))return{status:"not-applicable"};if(e.isLoaded(r))try{return b(a.parse(l(e,r)))}catch(c){return i(v(c))}if(!Object.hasOwn(t.contributions,s))return i("it is not loaded and its catalog entry carries no value for it");let n=f.safeParse(t.contributions[s]);return n.success?b(n.data.value):i("its catalog entry is of another version or shape")}}}export{w as a};
1
+ import{c as m}from"./5IRF47YB.js";import{b as v}from"./DDANMY45.js";import{z as p}from"zod";function w(d){let{key:s,schema:a,version:o,applies:u,compute:l}=d;if(!Number.isInteger(o))throw new TypeError(`Contribution ${s}: its version must be an integer`);let f=p.strictObject({v:p.literal(o),value:a}),b=e=>({status:"available",value:e}),i=e=>({status:"unavailable",reason:e});return{key:s,register(e){let r=Promise.resolve([]);return e.effect(()=>{let t=m(e).contribute(s,(n,c)=>u(c)?{v:o,value:a.parse(l(e.journal,n))}:void 0,{refresh:n=>u(n)&&!f.safeParse(n.contributions[s]).success});return r=t.refreshed,t.withdraw}),{refreshed:r}},read(e,r){let t=e.summary(r);if(t===void 0)return i(`thread ${r} is not in the catalog`);if(!u(t))return{status:"not-applicable"};if(e.isLoaded(r))try{return b(a.parse(l(e,r)))}catch(c){return i(v(c))}if(!Object.hasOwn(t.contributions,s))return i("it is not loaded and its catalog entry carries no value for it");let n=f.safeParse(t.contributions[s]);return n.success?b(n.data.value):i("its catalog entry is of another version or shape")}}}export{w as a};
@@ -1 +1 @@
1
- import{a as y}from"./CDQG7RKA.js";import{b as m,c as p,e as v}from"./DRYAN665.js";import{b as c}from"./2OSESBIL.js";import{z as h}from"zod";var g=new WeakMap;function j(o){let i=g.get(o);return i===void 0&&(i=m({plugin:"lagent:tool-policy",instanceId:o.name,kind:"mode-notice",version:1,schema:h.strictObject({mode:h.enum(o.modes)})}),g.set(o,i)),i}var z={name:"lagent:tool-policy",inject:["journal","threads"],apply(o,i){let{agents:r,confirm:l,approve:a,deny:u,modes:d,rules:s,notice:E}=i,w=e=>r===void 0||c(r,e),f=e=>o.on("lagent/tool/authorize",({toolCall:n,agent:t,threadId:_})=>w(t.name)?e(n.name,_):void 0);if(l!==void 0){let e=typeof l=="function"?l:n=>l.includes(n);f(n=>e(n)?"confirm":void 0)}if(a!==void 0&&f(e=>a==="all"||a.includes(e)?"approve":void 0),u!==void 0&&f(e=>u.includes(e)?"deny":void 0),d===void 0)return;for(let e of d.modes)if(!Object.hasOwn(s,e)||s[e]===void 0)throw new Error(`toolPolicy: modes ${d.name} have no rules for ${e}`);let O=j(d);f((e,n)=>{let t=s[d.of(o,n)];return t.allow!==void 0&&!t.allow.includes(e)?t.denial===void 0?"deny":{decision:"deny",reason:t.denial}:t.approve==="all"?"approve":void 0}),v(o,{event:O,...r===void 0?{}:{agents:r},rank:1,current:e=>{try{return{mode:d.of(o,e.threadId)}}catch(n){if(n instanceof y)return;throw n}},render:({mode:e},n,{notices:t})=>E(e,{seen:n?.mode??null,last:p(t)?.value.mode??null})})}},A=["run_command","start_command","edit_files"];export{z as a,A as b};
1
+ import{a as y}from"./DDZ7YF26.js";import{b as m,c as p,e as v}from"./6FRNHMCV.js";import{d as c}from"./CUK7CGC7.js";import{z as h}from"zod";var g=new WeakMap;function j(o){let i=g.get(o);return i===void 0&&(i=m({plugin:"lagent:tool-policy",instanceId:o.name,kind:"mode-notice",version:1,schema:h.strictObject({mode:h.enum(o.modes)})}),g.set(o,i)),i}var z={name:"lagent:tool-policy",inject:["journal","threads"],apply(o,i){let{agents:r,confirm:l,approve:a,deny:u,modes:d,rules:s,notice:E}=i,w=e=>r===void 0||c(r,e),f=e=>o.on("lagent/tool/authorize",({toolCall:n,agent:t,threadId:_})=>w(t.name)?e(n.name,_):void 0);if(l!==void 0){let e=typeof l=="function"?l:n=>l.includes(n);f(n=>e(n)?"confirm":void 0)}if(a!==void 0&&f(e=>a==="all"||a.includes(e)?"approve":void 0),u!==void 0&&f(e=>u.includes(e)?"deny":void 0),d===void 0)return;for(let e of d.modes)if(!Object.hasOwn(s,e)||s[e]===void 0)throw new Error(`toolPolicy: modes ${d.name} have no rules for ${e}`);let O=j(d);f((e,n)=>{let t=s[d.of(o,n)];return t.allow!==void 0&&!t.allow.includes(e)?t.denial===void 0?"deny":{decision:"deny",reason:t.denial}:t.approve==="all"?"approve":void 0}),v(o,{event:O,...r===void 0?{}:{agents:r},rank:1,current:e=>{try{return{mode:d.of(o,e.threadId)}}catch(n){if(n instanceof y)return;throw n}},render:({mode:e},n,{notices:t})=>E(e,{seen:n?.mode??null,last:p(t)?.value.mode??null})})}},A=["run_command","start_command","edit_files"];export{z as a,A as b};
@@ -0,0 +1,77 @@
1
+ import{a as m}from"./SS3B5W34.js";import{a as u,b as le}from"./IAAEP6VL.js";import{a as de}from"./OCBPT7KE.js";import{c as l}from"./2P47AHNK.js";import{a as ce}from"./MHC6VPB4.js";import{a as re,b as _,c as ne,d as R}from"./EMRB4KCN.js";import{e as ae}from"./RCIHV3KG.js";import{b as he}from"./2GCIWSOA.js";import{b as se}from"./GGSVIIWJ.js";import{e as Z,y as ie}from"./CANPZYTH.js";import{e as P}from"./JFZZXVWD.js";import{b as oe}from"./N6IXG2VL.js";import{f as K}from"./6DRCKZ2C.js";import{a as H}from"./Q75FUN7D.js";import{b as E}from"./34KW6VNQ.js";import{a as X,c as J}from"./CQEVREBT.js";import{a as Q,b as T}from"./EPYQ5M3B.js";import{b as $}from"./5IRF47YB.js";import{a as z}from"./OL5A6ITQ.js";import{a as ee,e as te}from"./JFX2MXBA.js";import{a as V}from"./CUK7CGC7.js";import{k as b}from"./BPRCULZH.js";import{h as O}from"./DDANMY45.js";import{k as Y,l as F,n as j,o as c,p as B,r as k,s as v}from"./BBCW2FZK.js";import{a as G,d as U}from"./MMNNZCBO.js";import{c as C,e as W,f as q}from"./G44LG6VL.js";import{f as D}from"./D4PQP5MA.js";import{Service as qe}from"@leuduan/cordis";import{z as p}from"zod";var ue={maxStepsPerTurn:4096,maxThreadDepth:8,maxParallelToolCalls:8},me=(n={})=>{let e={...ue,...n};for(let t of Object.keys(ue)){let o=t==="maxThreadDepth"?0:1,r=e[t];if(!Number.isFinite(r)||!Number.isInteger(r)||r<o)throw new RangeError(`${t} must be a finite integer >= ${o}; received ${String(r)}`)}return e};var Ge=p.strictObject({maxAttempts:p.number().int().min(1).max(100),baseDelayMs:p.number().int().min(0).max(E),maxDelayMs:p.number().int().min(0).max(E)}).refine(n=>n.baseDelayMs<=n.maxDelayMs,{message:"baseDelayMs must not exceed maxDelayMs"}),Ue=new Set(["rate_limit","overloaded","transport","timeout","empty"]),pe=Symbol("register"),pt=(n,e,t)=>{let o=Ge.parse(t.retry);return n.effect(()=>n.llm[pe](e,o))},f=class extends qe{providers=new Map;policies=new Map;clients=new Map;constructor(e){super(e,"llm"),e.effect(()=>()=>this.disposeClients(this.detachClients(()=>!0)))}get providerNames(){return U(this.providers.keys())}[pe](e,t){if(this.providers.has(e.name))throw new Error(`LLM provider already registered for name: ${e.name}`);return this.providers.set(e.name,e),this.policies.set(e.name,t),async()=>{this.providers.get(e.name)===e&&(this.providers.delete(e.name),this.policies.delete(e.name),await this.disposeClients(this.detachClients(o=>o===e.name)))}}provider(e){let t=this.providers.get(e);if(t===void 0)throw new b({provider:e});return t}unavailable(e){return this.providers.has(e.provider)?null:new b(e).message}resolveRoute(e,t){let o=e.thinkingEffort,r=o==null?o:D.parse(o);if(e.provider===void 0||e.provider===t.provider)return this.provider(t.provider),{provider:t.provider,model:e.model??t.model,thinking_effort:r===void 0?t.thinking_effort:r};let a=C(this.provider(e.provider),e.model,r??void 0);return r===null?{...a,thinking_effort:null}:a}capacity(e){return this.provider(e.provider).capacity(e.model)}clientFor(e){let t=this.provider(e.provider),o=this.clients.get(t.name);return o===void 0&&(o=new x(t,t.createClient(),this.policies.get(t.name)),this.clients.set(t.name,o)),o}detachClients(e){let t=[];for(let[o,r]of this.clients)e(o)&&(this.clients.delete(o),t.push(r));return t}async disposeClients(e){let o=(await Promise.allSettled(e.map(async({inner:r})=>r.dispose?.()))).flatMap(r=>r.status==="rejected"?[r.reason]:[]);if(o.length)throw new AggregateError(o,"LLM client cleanup failed")}},x=class{providerName;provider;inner;policy;constructor(e,t,o){this.provider=e,this.inner=t,this.policy=o,this.providerName=t.providerName}call(e){return new I(this,e)}failure(e,t){let{kind:o,retryAfterMs:r}=q(this.provider,e);return new W(this.provider.name,o,t,r??null,{cause:e})}},I=class{response;calls=0;current;yielded=!1;claimed=!1;entered=!1;ledger=new H;outcome;client;request;constructor(e,t){this.client=e,this.request=t,this.response=this.attempt().then(o=>(this.current=o,this))}get attempts(){return this.calls}[Symbol.asyncIterator](){this.claim();let e=this.read(!0),t,o=()=>this.entered?Promise.resolve():(t??=(async()=>{try{await this.current?.[Symbol.asyncIterator]().return?.()}catch(r){let a=this.final(r);throw this.outcome={error:a},a}finally{this.ledger.finish()}})(),t);return{next:()=>this.ledger.operation(()=>e.next()),return:r=>this.ledger.operation(async()=>{let a=e.return(r);return await o(),a}),throw:r=>this.ledger.operation(async()=>{let a=e.throw(r);return a.catch(()=>{}),await o(),a})}}claim(){if(this.claimed)throw new Error("A model call is read once: it has been claimed already");this.claimed=!0}async*read(e){this.entered=!0;try{for(;;)try{for await(let t of this.current)e&&(this.yielded=!0,yield t);this.outcome={response:await this.current.completed()};return}catch(t){try{await this.recover(t),this.current=await this.attempt()}catch(o){throw this.outcome={error:o},o}}}finally{this.ledger.finish()}}async completed(){if(this.claimed){if(!this.ledger.ended)throw new Error("A model call is settled before its read or after it, not while the read is under way")}else{this.claim();for await(let e of this.read(!1));}if(this.outcome!==void 0){if("error"in this.outcome)throw this.outcome.error;return this.outcome.response}try{let e=await this.current.completed();return this.outcome={response:e},e}catch(e){let t=this.final(e);throw this.outcome={error:t},t}}final(e){return O(this.request.signal,e)?e:this.client.failure(e,this.calls)}async attempt(){for(;;){this.request.signal.throwIfAborted(),this.calls+=1;try{return await this.client.inner.chat(this.request)}catch(e){await this.recover(e)}}}async recover(e){let{signal:t}=this.request;if(O(t,e))throw e;let o=this.calls,r=this.client.failure(e,o),{maxAttempts:a,baseDelayMs:s,maxDelayMs:i}=this.client.policy;if(!(!t.aborted&&!this.yielded&&this.request.providerTools.length===0&&Ue.has(r.kind)&&o<a&&(r.retryAfterMs===null||r.retryAfterMs<=i)))throw r;let h=Math.min(i,s*2**(o-1));await Ye(r.retryAfterMs??Math.floor(Math.random()*(h+1)),t)}};function Ye(n,e){return new Promise((t,o)=>{if(e.aborted){o(e.reason);return}let r=()=>{clearTimeout(a),o(e.reason)},a=setTimeout(()=>{e.removeEventListener("abort",r),t()},n);e.addEventListener("abort",r,{once:!0})})}var _t={name:"lagent:core",async apply(n,e){let t=me(e.limits);await n.plugin($,{store:e.store,limits:t}),await n.plugin(f),await n.plugin(V),await n.plugin(ee),await n.plugin(Q),await n.plugin(K),await n.plugin(X),await n.plugin(Z,{cwd:e.cwd,limits:t,retention:e.retention,chainLimit:e.chainLimit})}};var fe="You are a coding agent working in the user's workspace. You and the user share its files: with the tools you are given, you read, search and change them and run commands there. Your job is to carry the user's task through to a result they can review.",we=`- Carry the task through to the end within the turn: understand it, make the change, validate it, and report. Do not stop at analysis, a proposal or a half-finished fix.
2
+ - Unless the user asks a question, asks for a plan or a review, or is brainstorming, assume they want the change made, and make it rather than describe it.
3
+ - When you hit a blocker, try to work through it yourself first. Ask the user, with ask_question, only when the answer changes what you would do and you cannot find it out yourself.
4
+ - Do not guess or make up an answer: read the code, run the command, look it up.
5
+ - Messages may arrive while you work. When they conflict, the newest one steers; otherwise honour every request since your last answer, and make sure your final answer responds to the newest.`,ge='Before a group of related tool calls, write one short line saying what you are about to do, and after the first, how it follows from what you found; for example "The loader is in src/config.ts; now checking its callers." Group related calls under one line instead of narrating each, and write none before a trivial read. Before a large edit, say what you are changing.',S=`- Read the code you are about to change, and let it show you how to change it: follow the repository's existing patterns, helpers and style.
6
+ - Fix the problem at its root cause rather than patching the symptom, and keep the solution as simple as the problem allows. Add an abstraction only when it removes real complexity.
7
+ - Follow the AGENTS.md files you are told for the files you touch. Each governs its directory's tree and the deeper one wins on a conflict; the user's direct instructions beat any of them. Working below your working directory, look for AGENTS.md there too.
8
+ - Keep the change to what the task needs. Do not fix unrelated bugs or failing tests; mention them in your final answer.
9
+ - Update the documentation your change makes wrong.
10
+ - Default to ASCII in files, and add a comment only where the code does not explain itself.
11
+ - Never add copyright or licence headers unless asked. Do not commit or create branches unless asked.`,w="- Make every change to a file with edit_files: creating, updating, moving or deleting it. Never write a file through a command, such as a shell heredoc, `echo >`, `sed -i` or a script; running the project's own formatter or code generator is fine.\n- Read the lines you change before editing them: an edit's old text must match the file as it is now.\n- edit_files answers with the diff it applied. Trust it, and do not re-read the file to check.\n- If an edit is interrupted, or applies only some of its files, re-read the files it named before editing them again.",g="The worktree may hold changes you did not make. Assume they are the user's, and never revert them unless asked.\n- Leave changes unrelated to your task alone.\n- In files you are working on, read the changes carefully and work with them.\n- Never run `git reset --hard`, `git checkout --`, `git restore`, `git clean` or anything else that discards changes unless the user clearly asked for that operation; when the request is ambiguous, ask first.\n- If those changes make your task impossible, ask the user how to proceed.",N=`- When the project can be built or tested, use that to check your work. Start with the tests closest to what you changed, then widen as you gain confidence.
12
+ - Let coverage scale with risk: focused for a narrow change, broader when the change touches shared behaviour, contracts between modules, or what users do.
13
+ - Add a test where the codebase has an obvious place for one. Do not add a test suite or a formatter to a repository that has none, and do not write tests that only mirror the implementation.
14
+ - Run the project's formatter and linter on the files you changed when it has them.
15
+ - A failure your change did not cause is not yours to fix: mention it.`,ye=`- Independent tool calls can run in parallel: make every call that does not need another's result in the same response. When a call depends on an earlier one's output, wait for that result first.
16
+ - Hand work to a sub-agent when you do not need to see its steps, so your conversation keeps only its outcome:
17
+ - explore: find and understand things in the workspace, such as where something is handled, how a module works or what a change would affect. It only reads.
18
+ - delegate: a self-contained task that needs nothing from this conversation but the task you write, including one that changes files or runs commands, such as updating every call site of a function and making the tests pass, or finding out why a command fails and fixing it.
19
+ - fork: a task of several steps that needs your context: answering a question by experiment, working out why something fails, checking whether an approach works.
20
+ - review: a second reading of a change, or of any code, when the user asks for one or a change is large or subtle enough that one helps; never as a routine step. Its findings are evidence: weigh each against the code before acting on it. To get them fixed, delegate the findings with their evidence. Check the repository's status before asking for a review of uncommitted work: an empty change still starts a reviewer.
21
+ - Work directly when one or two calls will do, when you need the raw output yourself (the exact lines you are about to edit, command output you must reason over), when the next step waits on a decision, or when the answer is already in the conversation.
22
+ - Give independent parts separate calls in one response, so they run concurrently. Write each task as an outcome: what to find out or do, and what to return, such as "the function that validates tokens, with its file and line" rather than "look at the auth code". Explore, delegate and review see only the task you write; a fork sees your conversation too. Either way, name the target (for a review, "the uncommitted changes", "the current work against main", "commit abc123" or the code to read), the outcome you expect, the constraints, and which files you or other sub-agents are changing and which commands share outputs, such as test discovery, a build directory or a server port.
23
+ - Start a review only after the work it reviews has settled, in a later response than the calls that make that work: a waiting call does not stop the others in its response.
24
+ - In a forked task, do the work yourself rather than forking again.`,M="A long task can outgrow your context. The conversation may then be compacted: a checkpoint stands in for the messages it condensed. Compaction does not end the task. Continue from the checkpoint without restarting or redoing finished work, and keep the original objective together with every correction the user made since.",ke="When you need the exact text of something condensed, such as the user's wording or a command's output, read it back with history_read or find it with history_search rather than reconstructing it.",y=`- Your file tools and commands work under the confinement the application sets. Do not go looking through the rest of the machine, such as other projects or the home directory, unless the task needs it.
25
+ - Avoid destructive or irreversible commands, such as deleting what you did not create, force-pushing or dropping data, unless the user asked for them.
26
+ - Do not push, publish, deploy or send anything to others unless asked.
27
+ - Do not search for, print or copy out secrets such as credentials, API keys and tokens.`,ve=`- For a task with no prior context, where the user is starting something new, be ambitious and show creativity in the implementation.
28
+ - In an existing codebase, do exactly what the user asks with surgical precision. Treat the surrounding code with respect and do not overstep, for example by renaming files or variables unnecessarily, while still being proactive enough to finish the task well.
29
+ - Use judicious initiative to choose the right level of detail and complexity for the user's needs: high-value, creative touches when the scope is vague; surgical, targeted work when it is tightly specified; no gold-plating either way.`,be=`- Lead with the outcome, then give what the user needs to trust it and act on it, like a concise teammate handing off work.
30
+ - Size the answer by the change: a sentence or two for a small fix, a short walkthrough grouped by theme for a large one, a plain conversational reply to a casual question. Even a large one keeps to the points that matter, well under fifty lines.
31
+ - Say what you ran to validate the work, and what you did not run and why.
32
+ - Point to code as \`path:line\`, with the path relative to the working directory and a single line rather than a range.
33
+ - Do not paste before-and-after code or the contents of files you wrote: the user has the files. Never ask them to save or copy anything.
34
+ - Mention the problems you noticed but left alone, and anything you could not do.
35
+ - When there is an obvious next step, such as running the wider test suite, committing, or building the next piece, offer it as a short question rather than doing it unasked.`,Oe=`- Write in English unless the user asks for another language.
36
+ - Be direct and concise, and state the assumptions you made. Leave out flattery, filler and needless apologies.
37
+ - Use plain characters: no emoji unless asked, and no look-alike or invisible Unicode, such as an en dash for a hyphen.`,Ee=`- Answer in Markdown, with only as much structure as helps: short paragraphs by default, flat lists for parallel items, and a heading only when a long answer has distinct parts.
38
+ - Put code, commands and multi-line output in fenced code blocks labelled with their language.
39
+ - Wrap file paths, commands, environment variables and code identifiers in backticks.`,Te=n=>{let e=n("rg_search"),t=n("rg_files");return`You are an exploration sub-agent: you investigate the workspace to answer the task you are given, and report what you found without changing anything.
40
+
41
+ Use read_file${e?" and rg_search to inspect and search":" to inspect"} code; read_file reads by line, so read the part you need.
42
+ Use ${t?"rg_files to find files by name pattern, and ":""}list_dir to see what a directory holds or for an overview of the workspace.
43
+ Request only the output you need, since tool output may be truncated, and make several targeted calls rather than one broad one.
44
+ Answer with your findings, pointing to code as \`path:line\`, and say what you looked for but could not find.`},_e="Sub-agent that explores the workspace without changing it: codebase exploration, file discovery and code understanding. It reports its findings.",Re="Fork yourself to execute one sub-task in isolation. The forked thread gets a clone of your current conversation context, executes the task independently, and its result is returned to you. Use this when you want to 'clone yourself' to do a sub-task without polluting your main conversation thread. Call this tool once per task; several calls in one response run concurrently.",Pe="Sub-agents inherit your permissions and share your working directory. Give sub-agents that run at the same time disjoint files to write, or let only one of them write; disjoint files still share test discovery, build output and ports, so do not run tests or builds in two of them at once.",Fe="You are a sub-agent: another agent handed you one task, which you carry out in the user's workspace with the tools you are given, reading, searching and changing its files and running commands there. You do not see the conversation that led to the task: the task is all you know of it. Your answer goes back to the agent that asked, not to the user.",xe=`- Where these instructions say to ask the user, you cannot: stop there, and put the question in your answer, with what you found and what each answer would change.
45
+ - Before you answer, wait for every background command whose result you rely on, and stop every background command you started.`,je=`Your answer is all the agent that asked gets back, so make it complete on its own:
46
+ - Lead with the outcome: what you did, or what you found.
47
+ - Point to code as \`path:line\`, with the path relative to the working directory.
48
+ - Say what you ran to check it, each command exactly, and what it showed.
49
+ - Say what is left undone, what you could not do, and what you are unsure of.`,Be="You are a code review sub-agent: another agent asked you for a second reading of code in the user's workspace, a change or code as it stands, and you report the problems you find, with their evidence. You do not see the conversation that led to the task: the task names what to review and anything to focus on. Your answer goes back to the agent that asked, not to the user.",Ve="- Read the change with git through run_command: a diff of the uncommitted changes, of the current work against a branch's merge base, or of one commit, with the repository's status and log. Note which commits you compared. Read the code around each change, and the code that depends on it, as far as you need to judge it. When the task names code rather than a change, review that code as it stands.\n- Review and report; do not fix. Run a command only when a finding needs the evidence: an existing test, the type checker, a linter, or a small reproduction. Prefer existing tests.\n- When a check needs a file inside the repository, create a new, uniquely named file with edit_files. Never change a file that existed before you started, the user's untracked files included.\n- Clean up what you created. Just before deleting a temporary file, read it again, and delete it only if it is still exactly what you wrote. Never restore the workspace wholesale, such as with `git checkout`, `git restore`, `git stash` or `git clean`.\n- Running tests writes caches and build output, which is fine: what you keep intact is the user's work.\n- When the target is a commit, or anything but the current work, your commands run on the checkout, not on the reviewed revision. Say which HEAD and which local changes they ran on, and do not claim that a check passing there shows the reviewed revision passes.\n- If files your findings rely on change while you review, check those findings again, or mark them uncertain.",$e=`Flag a problem only when all of these hold:
50
+ - It meaningfully affects the correctness, performance, security or maintainability of the code.
51
+ - It is discrete and actionable: one issue, not a remark about the codebase in general or several issues together.
52
+ - When the task names a change, the change introduced it: problems that were there before are not flagged. When it names code, the problem is in that code.
53
+ - You can show it from the code or from what you ran. Speculating that something may break elsewhere is not enough: name the code that is affected. It must not rest on assumptions about the codebase or the author's intent that you have not stated.
54
+ - It is clearly not a deliberate choice, and the author would fix it if they knew.
55
+ - Fixing it does not demand more rigour than the rest of the codebase shows.
56
+
57
+ Ignore style, formatting, naming and typos unless they hide a bug or break a rule the repository's AGENTS.md files state. When a rule supports a finding, cite the AGENTS.md file and line it comes from.
58
+
59
+ Report every finding the author would want to fix, not only the first; when nothing clearly qualifies, report none. For each finding:
60
+ - A short title tagged with its priority: [P0] blocks a release or major use, whatever the inputs; [P1] urgent, for the next cycle; [P2] normal, to fix eventually; [P3] low, nice to have.
61
+ - Its location as \`path:line\` in the reviewed code, with the path relative to the repository, keeping the range as short as possible.
62
+ - One short paragraph saying why it is a problem and the inputs, scenarios or environments it needs, so its severity is clear, and the evidence: what you read or ran. Claim no more severity than it has, quote no more than three lines of code, and keep the tone matter-of-fact, with no praise.
63
+
64
+ When the task asks for a design assessment, alternatives or improvements, give them after the findings, under a heading of their own, apart from the problems you showed. When it asks for a severity scale or an output format, follow it instead of these.
65
+
66
+ End with:
67
+ - the scope you reviewed, and for a git target the commits you compared;
68
+ - the checks you ran, each command exactly, with its result;
69
+ - every experiment, what it left behind, and where its reproduction is kept, with how to run it;
70
+ - the limits of the review: what you did not read or could not check.
71
+ Then a one-line verdict: whether the reviewed code is correct, meaning existing code and tests will not break and it has no blocking problem. Non-blocking issues such as style do not count against it. "No qualifying findings" is not a guarantee of correctness: when you found none, say so plainly, with what you covered.
72
+
73
+ Answer in plain text, not JSON. The task may narrow what to look at, and the repository's AGENTS.md files may add rules; both take precedence over these guidelines.`,Ie=(n,e)=>[n,...e.map(([t,o])=>G(t,o))].join(`
74
+
75
+ `),Se=Ie(Fe,[["codebase",S],["editing",w],["dirtyWorktree",g],["validation",N],["safety",y],["subAgent",xe],["answer",je]]),Ne=Ie(Be,[["evidence",Ve],["editing",w],["dirtyWorktree",g],["safety",y],["subAgent",xe],["rubric",$e]]),Me="Sub-agent that carries out one self-contained task in the workspace with a fresh context: it reads, changes files, runs commands, and reports what it did and found. It sees only the task you write, not this conversation, so state the target, the outcome you expect and any constraints.",Ae="Sub-agent that reviews code in the workspace with a fresh context: a change (the uncommitted changes, the current work against a branch such as main, or one commit) or code as it stands. It may run tests and reproductions to gather evidence, changes nothing of yours, and reports the problems it can show, each tagged [P0] to [P3] at a file and line. Name the target and any focus in the task.";import{z as A}from"zod";var Kt={drop:["*KEY*","*SECRET*","*TOKEN*"],set:{...oe,LANG:"C.UTF-8"}},De=["edit_files"],Ke=[...u,...De,...P,...m,l,...ie],He=[{tool:l,plugin:"skills"}],ze=[{tag:"autonomy",render:()=>we},{tag:"preambles",render:()=>ge},{tag:"codebase",render:()=>S},{tag:"editing",render:()=>w},{tag:"dirtyWorktree",render:()=>g},{tag:"validation",render:()=>N},{tag:"delegation",render:()=>ye},{tag:"forking",render:()=>Pe},{tag:"longWork",render:({tools:n})=>he.every(e=>n.some(t=>t.name===e))?`${M}
76
+
77
+ ${ke}`:M},{tag:"safety",render:()=>y},{tag:"ambitionPrecision",render:()=>ve},{tag:"finalAnswer",render:()=>be},{tag:"communication",render:()=>Oe},{tag:"formatting",render:()=>Ee}],Xe=A.strictObject({explore:A.strictObject({web:A.boolean().default(!1)}).prefault({}),agentsMd:re}),Je="codex.explore",Qe="codex.general",Ze="codex.review",Ce=[...le,"web_search"],et=(n,e)=>[...u,...n?m:[]].filter(t=>e(t)||!Ce.includes(t)),Le=n=>[...u,...De,...P,...m,l].filter(e=>n(e)||!Ce.includes(e)),Ht=z({id:"codex#2",placement:"thread",schema:Xe,inject:["tools","prompts","journal","confinement"],async setup(n,{explore:e,agentsMd:t},o){let r=[o.thread.agentName];if(n.get("presets")?.has(_)!==!0)throw new Error("codex hands down agents-md, which is not registered: register agentsMdPreset at startup");for(let{tool:i,plugin:d}of He)if(!n.tools.has(void 0,i))throw new Error(`codex grants ${i}, which is not registered: mount the ${d} plugin on the root`);for(let i of Ke)te(n,i,r);T(n,{tag:"base",slot:"base",agents:r,render:()=>fe}),ze.forEach(({tag:i,render:d},h)=>T(n,{tag:i,slot:"instruction",agents:r,order:h,render:d}));let a;o.kind==="installation"?(a=R(n,{holder:`codex in installation ${o.installationId}`,...t},o.thread.id),J(n,{presetId:_,config:t,installationId:ne})):a=R(n,{holder:"codex for its agents",...t},o.thread.id),await n.plugin(de),await n.plugin(ae,{agents:r});let s=i=>n.tools.has(void 0,i);await n.plugin(ce,{endpoints:[{toolName:"explore",callers:r,description:_e,target:{kind:"role",id:Je,basePrompt:Te(s),tools:et(e.web,s)}},{toolName:"delegate",callers:r,description:Me,target:{kind:"role",id:Qe,basePrompt:Se,tools:Le(s)}},{toolName:"fork",callers:r,description:Re,target:{kind:"fork"}},{toolName:"review",callers:r,description:Ae,target:{kind:"role",id:Ze,basePrompt:Ne,tools:Le(s)}}]}),await n.plugin(se,{agents:r}),await a}});import{randomUUID as tt}from"node:crypto";var We=class extends Y{rows=[];index=[];threadIndex=new Map;catalog=new Map;attempts=new Map;writer;get size(){return this.rows.length}async acquireWriter(){if(this.writer!==void 0)throw new F(this.constructor.name);let e=tt();return this.writer=e,{identity:this.constructor.name,acquisitionId:e,release:async()=>{this.writer===e&&(this.writer=void 0)}}}async doOpen(){}async doClose(){}async doHead(){return this.headSeq()}async doAppend(e,t){let o=this.attempts.get(e.id);if(o!==void 0){if(o===t)return"duplicate";throw new B(e.id)}if(this.writer!==e.writer)throw new c(e.writer);let r=this.headSeq();if(r!==e.baseHead)throw new j(e.baseHead,r);let a=e.rows[0],s=this.threadIndex.get(a.thread_id);if(s===void 0&&a.type!=="thread/spawned")throw new Error(`Thread ${a.thread_id} is not in the store; its first row must be its spawn row`);if(e.rows.some(h=>h.type==="thread/spawned"&&(s!==void 0||h!==a)))throw new Error(`Thread ${a.thread_id} already has a spawn row`);let i=e.rows.map(h=>this.serialize(h));for(let[h,L]of e.rows.entries())this.rows.push(i[h]),this.index.push({seq:L.seq,threadId:L.thread_id});let d=e.rows.at(-1).seq;return this.threadIndex.set(a.thread_id,{spawnSeq:s?.spawnSeq??a.seq,lastSeq:d}),this.attempts.set(e.id,t),"appended"}async doRead(e){let t=[];for(let[o,r]of this.index.entries())r.threadId===e&&t.push(k(this.rows[o]));return t}async doRowAt(e){let t=this.index.findIndex(o=>o.seq===e);return t<0?void 0:k(this.rows[t])}async doThreads(){return[...this.threadIndex].map(([e,t])=>({threadId:e,...t})).sort((e,t)=>e.spawnSeq-t.spawnSeq)}async doSummaries(){return[...this.catalog.values()].map(e=>v(e)).sort((e,t)=>e.spawn_seq-t.spawn_seq)}async doPutSummaries(e,t){if(this.writer!==t)throw new c(t);let o=e.map(r=>[r,this.serializeSummary(r)]);for(let[r,a]of o){let s=this.catalog.get(r.thread_id);s!==void 0&&v(s).through_seq>r.through_seq||this.catalog.set(r.thread_id,a)}}async doReplaceCatalog(e,t){if(this.writer!==t)throw new c(t);let o=e.map(r=>[r.thread_id,this.serializeSummary(r)]);this.catalog.clear();for(let[r,a]of o)this.catalog.set(r,a)}headSeq(){return this.index.at(-1)?.seq??0}};export{me as a,pt as b,_t as c,Oe as d,Ee as e,Kt as f,Ht as g,We as h};
@@ -1 +1 @@
1
- import{q as y,r as J,t as z}from"./KESCTXGO.js";var m=class extends Error{origin;reason;constructor(e,t){let{caller_thread_id:s,source_seq:r}=e,i={"unknown-caller":`thread ${s} is not in the journal`,"source-missing":`row ${r} does not exist`,"source-off-lineage":`row ${r} is not a row of thread ${s} or of a thread it forks from`,"source-not-a-call":`row ${r} is not a tool call, which a call cause cites`};super(`Invalid origin under thread ${s}: ${i[t]}`),this.name="InvalidOriginError",this.origin=e,this.reason=t}},b=class{summaries=new Map;ranks=new Map;children=new Map;nextRank=0;origins={callers:e=>this.callers(e),root:e=>this.callers(e).threads.at(-1),subtree:(e,t)=>this.subtree(e,t.self),isUnder:(e,t)=>this.callers(e).threads.some(s=>s.thread_id===t),requiredOwners:e=>this.requiredOwners(e)};get(e){return this.summaries.get(e)}has(e){return this.summaries.has(e)}keys(){return this.summaries.keys()}values(){return this.summaries.values()}view(){return this.summaries}set(e,t){if(!this.summaries.has(e)&&(this.ranks.set(e,this.nextRank++),t.origin!==null)){let s=t.origin.caller_thread_id,r=this.children.get(s);r===void 0?this.children.set(s,new Set([e])):r.add(e)}this.summaries.set(e,t)}delete(e){let t=this.summaries.get(e);if(t!==void 0){if(t.origin!==null){let s=this.children.get(t.origin.caller_thread_id);s?.delete(e),s?.size===0&&this.children.delete(t.origin.caller_thread_id)}this.summaries.delete(e),this.ranks.delete(e)}}reset(e){this.summaries.clear(),this.ranks.clear(),this.children.clear(),this.nextRank=0;for(let t of e)this.set(t.thread_id,t)}callers(e){let t=[],s=new Set;for(let r=this.summaries.get(e);r!==void 0&&(s.add(r.thread_id),t.push(r),r.origin!==null);){let i=r.origin.caller_thread_id,n=this.summaries.get(i);if(n===void 0)return{threads:t,chain:{broken:"missing",at:r.thread_id}};if(s.has(i))return{threads:t,chain:{broken:"cycle",at:r.thread_id}};r=n}return{threads:t,chain:"complete"}}subtree(e,t){let s=this.summaries.get(e);if(s===void 0)return[];let r=new Set([e]),i=[e];for(let c=i.pop();c!==void 0;c=i.pop())for(let l of this.children.get(c)??[])r.has(l)||(r.add(l),i.push(l));r.delete(e);let a=[...r].sort((c,l)=>this.ranks.get(c)-this.ranks.get(l)).map(c=>this.summaries.get(c));return t?[s,...a]:a}requiredOwners(e){let t=new Map,s=(i,n)=>{let a=t.get(i);a===void 0&&t.set(i,a=[]),n!==null&&!a.includes(n)&&a.push(n)},r;if(typeof e=="string")r=this.callers(e);else{for(let n of e.requires)s(n,null);let i=e.origin?.caller_thread_id;i===void 0?r={threads:[],chain:"complete"}:this.summaries.has(i)?r=this.callers(i):r={threads:[],chain:{broken:"missing",at:null}}}for(let i of r.threads)for(let n of i.requires)s(n,i.thread_id);return{owners:[...t].map(([i,n])=>({owner:i,introducedBy:n})),chain:r.chain}}};function te(o,e){let t=[],s=new Set;for(let r=o.get(e);r!==void 0&&!s.has(r.thread_id);)s.add(r.thread_id),t.push(r),r=r.fork===null?void 0:o.get(r.fork.thread_id);return t}import{z as G}from"zod";function L(o){return Array.isArray(o)?`[${o.map(e=>L(e)).join(",")}]`:o!==null&&typeof o=="object"?`{${Object.entries(o).filter(([,t])=>t!==void 0).sort(([t],[s])=>t<s?-1:t>s?1:0).map(([t,s])=>`${JSON.stringify(t)}:${L(s)}`).join(",")}}`:JSON.stringify(o)}var F=G.json();function P(o){return Array.isArray(o)?o.map(e=>P(e)):typeof o=="object"&&o!==null?Object.fromEntries(Object.entries(o).map(([e,t])=>[e,P(t)])):o}function N(o,e){let{key:t,init:s,apply:r}=e;return e.onFork!=="reset"?{key:t,failureMode:o,init:s,apply:r}:{key:t,failureMode:o,init:s,apply:(i,n)=>J(n)?s():r(i,n)}}var ne=o=>Object.freeze(N("isolate",o)),ae=o=>N("fatal",o),k=class extends Error{projectionKey;threadId;cause;constructor(e,t,s){super(`Projection '${e}' failed on thread ${t}`),this.projectionKey=e,this.threadId=t,this.cause=s,this.name="ProjectionFailedError"}};import{createHash as Q}from"node:crypto";import{z as U}from"zod";var C=class{opened=!1;get isOpen(){return this.opened}async open(){this.opened||(await this.doOpen(),this.opened=!0)}async close(){this.opened&&(await this.doClose(),this.opened=!1)}async head(){return this.requireOpen(),this.doHead()}async append(e){if(this.requireOpen(),e.rows.length===0)throw new Error("An attempt holds at least one row");let t=e.rows[0].thread_id,s=e.baseHead;for(let r of e.rows){if(r.thread_id!==t)throw new Error("An attempt holds rows of one thread");if(r.seq<=s)throw new Error(`Row ${r.seq} does not follow ${s} in attempt ${e.id}`);s=r.seq}return this.doAppend(e,X(e))}async read(e){return this.requireOpen(),this.doRead(e)}async rowAt(e){return this.requireOpen(),this.doRowAt(e)}async threads(){return this.requireOpen(),this.doThreads()}async summaries(){return this.requireOpen(),this.doSummaries()}async putSummaries(e,t){this.requireOpen(),e.length>0&&await this.doPutSummaries(e,t)}async replaceCatalog(e,t){this.requireOpen(),await this.doReplaceCatalog(e,t)}serialize(e){return JSON.stringify(e)}serializeSummary(e){return JSON.stringify(e)}requireOpen(){if(!this.opened)throw new Error(`${this.constructor.name} is not open`)}};function X(o){return Q("sha256").update(JSON.stringify([o.baseHead,o.writer,o.rows])).digest("hex")}var B=class extends Error{location;constructor(e){super(`Journal is busy: ${e}. Close its current writer before opening another.`),this.location=e,this.name="JournalBusyError"}},H=class extends Error{location;waitedMs;constructor(e,t){super(`Journal store ${e} stayed locked by another connection for ${t} ms`),this.location=e,this.waitedMs=t,this.name="StoreBusyError"}},W=class extends Error{expected;actual;constructor(e,t){super(`The journal's head is ${t}, not ${e}; another write landed first`),this.expected=e,this.actual=t,this.name="JournalConflictError"}},x=class extends Error{acquisitionId;constructor(e){super(`Writer ${e} no longer holds the journal`),this.acquisitionId=e,this.name="WriterLostError"}},D=class extends Error{attemptId;constructor(e){super(`Attempt ${e} was already written with different rows`),this.attemptId=e,this.name="AttemptMismatchError"}},q=class extends Error{payload;cause;constructor(e,t){super(`Unparsable journal row: ${e.slice(0,200)}`),this.payload=e,this.cause=t,this.name="CorruptJournalError"}};function fe(o,e=t=>t){try{return y(e(JSON.parse(o)))}catch(t){throw t instanceof SyntaxError||t instanceof U.ZodError?new q(o,t):t}}function de(o){try{return z.parse(JSON.parse(o))}catch(e){throw e instanceof SyntaxError||e instanceof U.ZodError?new q(o,e):e}}var V=38,O=class extends Error{found;location;constructor(e,t){super(`Journal at ${t} is ${e===0?"unstamped":`format v${e}`}; this build reads v${V}. Start a new journal directory; the existing journal has been preserved.`),this.found=e,this.location=t,this.name="IncompatibleJournalError"}};function pe(o,e,t){if(!(o===V||!e))throw new O(o,t)}import{randomUUID as I}from"node:crypto";function R(o,e,t){for(let s of o)try{let r=s(e);Y(r)&&Promise.resolve(r).catch(t)}catch(r){t(r)}}var Y=o=>(typeof o=="object"||typeof o=="function")&&o!==null&&typeof o.then=="function";function w(o){if(o!==null&&typeof o=="object"&&!Object.isFrozen(o)){Object.freeze(o);for(let e of Object.values(o))w(e)}return o}function S(o,e){let t=o.get(e);return t===void 0&&o.set(e,t=new Map),t}var Z=o=>o.type==="thread/spawned"?o.data.fork:null,K=class{projections=new Map;coreFolds;states=new Map;failures=new Map;pendingReports=[];dirty=new Set;listeners=new Set;revokedListeners=new Set;contributors=new Map;catalog=new b;loaded=new Map;loading=new Map;rowReads=new Map;generations=new Map;bySeq=new Map;holds=new Map;folded=new Set;summarizer;onListenerError;lease;ownsStore=!1;seq=0;writable=!0;revokedBy;queue=Promise.resolve();writing=!1;closing=!1;store;constructor(e,t){this.store=e,this.summarizer=t.summarize,this.onListenerError=t.onListenerError??(s=>{console.error(s)}),this.coreFolds=new Set(t.coreFolds);for(let s of this.coreFolds)this.register(s)}revokeWrites(){this.writable=!1}onRevoked(e){return this.revokedListeners.add(e),()=>this.revokedListeners.delete(e)}async open(){this.lease=await this.store.acquireWriter();try{this.store.isOpen||(await this.store.open(),this.ownsStore=!0),this.seq=await this.store.head(),this.catalog.reset((await this.store.summaries()).map(i=>w(i))),this.loaded.clear(),this.bySeq.clear(),this.folded.clear(),this.states.clear(),this.failures.clear(),this.pendingReports.length=0,this.dirty.clear();let e=await this.store.threads(),t=e.filter(({threadId:i,lastSeq:n})=>this.catalog.get(i)?.through_seq!==n),s=new Set(e.map(({threadId:i})=>i)),r=[...this.catalog.keys()].some(i=>!s.has(i));(t.length>0||r)&&await this.repair(e,new Set(t.map(({threadId:i})=>i)),{replace:r,opening:!0})}catch(e){throw await this.close(),e}}async close(){this.closing=!0,await this.queue,this.writable=!1;let e=this.lease;this.lease=void 0;try{await e?.release()}finally{this.ownsStore&&await this.store.close(),this.ownsStore=!1}}get head(){return this.seq}summary(e){return this.catalog.get(e)}summaries(){return[...this.catalog.values()]}summaryMap(){return this.catalog.view()}origins={...this.catalog.origins,validate:async e=>{let{caller_thread_id:t,source_seq:s,cause:r}=e;if(!this.catalog.has(t))throw new m(e,"unknown-caller");let i=await this.readRow(s);if(i===void 0)throw new m(e,"source-missing");if(!this.inLineage(t,i))throw new m(e,"source-off-lineage");if(r.kind==="call"&&i.type!=="tool/call")throw new m(e,"source-not-a-call")}};contribute(e,t,s={}){if(this.contributors.has(e))throw new TypeError(`Duplicate summary contributor: ${e}`);this.contributors.set(e,t);let r=s.refresh??(n=>!Object.hasOwn(n.contributions,e)),i=this.enqueue(async()=>{if(this.requireWritable(),this.contributors.get(e)!==t)return[];let n=await this.store.threads(),a=new Set;for(let{threadId:c}of n){let l=this.catalog.get(c);l!==void 0&&r(l)&&a.add(c)}return a.size===0?[]:await this.repair(n,a,{replace:!1,opening:!1})});return i.catch(n=>{n instanceof g||this.reportError(n)}),{withdraw:()=>{this.contributors.get(e)===t&&this.contributors.delete(e)},refreshed:i}}rebuildCatalog(){return this.enqueue(async()=>{this.requireWritable();let e=await this.store.threads();await this.repair(e,new Set(e.map(({threadId:t})=>t)),{replace:!0,opening:!1})})}async repair(e,t,s){let{replace:r,opening:i}=s,n=new Map(this.catalog.view()),a=new Set(this.loaded.keys()),c=new Set,l=u=>(a.has(u)||c.add(u),this.loadRows(u)),d=[];this.writing=!0;try{if(i)for(let h of t)this.catalog.delete(h);for(let h of t)await l(h);for(let h of t)for(let p of this.hops(h,1/0))await l(p.threadId);let u=new Map;for(let{threadId:h}of e)if(t.has(h))try{this.ensureFolded(h),u.set(h,w(structuredClone(this.summarize(h))))}catch(p){this.pendingReports.push(new A(h,p)),d.push(h);let T=n.get(h);T!==void 0&&u.set(h,this.withRegisteredContributions(T))}let f=new Map;for(let{threadId:h}of e){let p=u.get(h)??n.get(h);p!==void 0&&f.set(h,p)}let $=[...this.dirty].flatMap(h=>{let p=u.has(h)?void 0:this.catalog.get(h);return p===void 0?[]:[p]});try{r?await this.store.replaceCatalog([...f.values()],this.writer()):await this.store.putSummaries([...u.values(),...$],this.writer()),this.dirty.clear()}catch(h){throw i?h:this.revoke("(catalog)",h)}this.catalog.reset(f.values())}catch(u){throw this.catalog.reset(n.values()),u}finally{for(let u of c)this.unload(u);this.writing=!1}return this.flushReports(),d}withRegisteredContributions(e){let t=Object.entries(e.contributions).filter(([s])=>this.contributors.has(s));return w({...e,contributions:Object.fromEntries(t)})}requireWritable(){if(!this.writable||this.closing)throw new g(this.revokedBy)}loadedThreads(){return[...this.loaded.keys()]}flush(){return this.queue.then(()=>{})}hold(e){for(let s of e)this.holds.set(s,(this.holds.get(s)??0)+1);let t=!1;return()=>{if(!t){t=!0;for(let s of e){let r=(this.holds.get(s)??1)-1;r>0?this.holds.set(s,r):this.holds.delete(s)}}}}load(e){if(this.folded.has(e)||!this.catalog.has(e))return Promise.resolve();let t=this.loading.get(e);return t===void 0&&(t=(async()=>{let s=this.hops(e,1/0).map(i=>i.threadId),r=this.hold(s);try{for(let i of s)await this.loadRows(i);this.ensureFolded(e)}finally{r()}this.flushReports()})().finally(()=>this.loading.delete(e)),this.loading.set(e,t)),t}isLoaded(e){return this.folded.has(e)}unload(e){if(this.holds.has(e))return!1;let t=[...this.loaded.keys()].filter(s=>s!==e&&this.hops(s,1/0).some(r=>r.threadId===e));if(t.some(s=>this.holds.has(s)))return!1;this.drop(e);for(let s of t)this.drop(s);return!0}drop(e){this.generations.set(e,(this.generations.get(e)??0)+1);let t=this.loaded.get(e);if(t!==void 0)for(let s of t)this.bySeq.delete(s.seq);this.loaded.delete(e),this.folded.delete(e),this.dropStates(e)}eventAt(e){let t=this.bySeq.get(e);if(t===void 0&&e>=1&&e<=this.seq)throw new j(e);return t}async readRow(e){let t=this.bySeq.get(e);if(t!==void 0)return t;let s=await this.store.rowAt(e);return s===void 0?void 0:w(s)}rows(e,t=1/0){let s=this.own(e);return t===1/0?s:s.slice(0,this.firstAfter(s,t))}rowsAfter(e,t){let s=this.own(e);return s.slice(this.firstAfter(s,t))}lineage(e,t=1/0){return this.hops(e,t).reverse().flatMap(s=>this.rows(s.threadId,s.upTo))}inLineage(e,t){return this.hops(e,1/0).some(s=>s.threadId===t.thread_id&&t.seq<=s.upTo)}stateAt(e,t,s){let r=e.init();for(let i of this.lineage(t,s))r=e.apply(r,i);return r}hops(e,t){let s=[],r={threadId:e,upTo:t};for(;r!==void 0;){s.push(r);let i=this.spawnOf(r.threadId);r=i===void 0||i.fork===null||i.seq>r.upTo?void 0:{threadId:i.fork.thread_id,upTo:Math.min(i.fork.seq,r.upTo)}}return s}spawnOf(e){let t=this.catalog.get(e);if(t!==void 0)return{seq:t.spawn_seq,fork:t.fork};let s=this.loaded.get(e)?.[0];if(s?.type==="thread/spawned")return{seq:s.seq,fork:s.data.fork}}own(e){let t=this.loaded.get(e);if(t!==void 0)return t;if(this.catalog.has(e))throw new E(e);return[]}loadRows(e){if(this.loaded.has(e))return Promise.resolve();let t=this.rowReads.get(e);return t===void 0&&(t=this.readRows(e).finally(()=>this.rowReads.delete(e)),this.rowReads.set(e,t)),t}async readRows(e){for(;;){let t=this.generations.get(e)??0,s=await this.store.read(e);if(this.loaded.has(e))return;if((this.generations.get(e)??0)===t){for(let r of s)w(r);this.loaded.set(e,s);for(let r of s)this.bySeq.set(r.seq,r);return}}}firstAfter(e,t){let s=0,r=e.length;for(;s<r;){let i=s+r>>>1;e[i].seq<=t?s=i+1:r=i}return s}async append(e,t,s){let[r]=await this.appendAll([{type:e,data:t,options:s}]);return r}appendAll(e){if(e.length===0)return!this.writable||this.closing?Promise.reject(new g(this.revokedBy)):Promise.resolve([]);if(this.closing)return Promise.reject(new g(this.revokedBy));let t=e[0].options.threadId;return this.enqueue(()=>this.write(t,()=>({rows:e,value:void 0}),s=>s))}transact(e,t){return this.closing?Promise.reject(new g(this.revokedBy)):this.enqueue(()=>this.write(e,t,(s,r)=>({events:s,value:r})))}enqueue(e){let t=this.queue.then(e);return this.queue=t.catch(()=>{}),t}async write(e,t,s){if(!this.writable)throw new g(this.revokedBy);let r=this.hold([e]);try{return await this.writeHeld(e,t,s)}finally{r()}}async writeHeld(e,t,s){let r=this.catalog.has(e);r&&await this.load(e);let i=t();if(typeof i.then=="function")throw new TypeError("A transact callback is synchronous: it may not await, since it runs inside the write queue");let{rows:n,value:a}=i;if(n.length===0)return s([],a);if(n.some(f=>f.options.threadId!==e))throw new Error(`A group holds rows of one thread, ${e}`);let c=n.filter(f=>f.type==="thread/spawned").length;if(!r&&(n[0].type!=="thread/spawned"||c!==1))throw new Error(`Thread ${e} does not exist: its first group must begin with its one spawn row`);if(r&&c>0)throw new Error(`Thread ${e} already exists; a second spawn row is refused`);let l=n.map((f,$)=>w(y({seq:this.seq+$+1,type:f.type,thread_id:e,data:JSON.parse(JSON.stringify(f.data)),source_seqs:f.options.sourceSeqs??[]}))),d=Z(l[0]);if(d!==null){if(d.seq>=l[0].seq)throw new Error(`A fork's spawn row must name an earlier row, not ${d.seq}`);await this.load(d.thread_id)}let u=d===null?()=>{}:this.hold([d.thread_id]);try{return s(await this.commit(e,r,l),a)}finally{u()}}async commit(e,t,s){t||(this.loaded.set(e,[]),this.folded.delete(e));try{this.ensureFolded(e)}catch(r){throw t||this.drop(e),r}this.writing=!0;try{try{await this.store.append({id:I(),baseHead:this.seq,writer:this.writer(),rows:s})}catch(n){throw t||this.drop(e),this.revoke(e,n)}this.seq=s.at(-1).seq;let r;try{let n=this.loaded.get(e);for(let a of s)n.push(a),this.bySeq.set(a.seq,a),this.fold(a);r=w(structuredClone(this.summarize(e)))}catch(n){throw this.drop(e),this.revoke(e,n)}this.catalog.set(e,r);for(let n of s)this.publish(n);this.dirty.add(e);let i=[...this.dirty].flatMap(n=>{let a=this.catalog.get(n);return a===void 0?[]:[a]});try{await this.store.putSummaries(i,this.writer()),this.dirty.clear()}catch(n){if(n instanceof x)throw this.revoke(e,n);this.pendingReports.push(new v([...this.dirty],n))}}finally{this.writing=!1}return this.flushReports(),s}writer(){if(this.lease===void 0)throw new Error("The journal is not open");return this.lease.acquisitionId}revoke(e,t){let s=new _(e,t);return this.writable=!1,this.revokedBy=s,R(this.revokedListeners,s,r=>this.reportError(r)),s}publish(e){R(this.listeners,e,t=>this.reportError(t))}summarize(e){let t=this.summarizer(this,e),s={};for(let[r,i]of this.contributors)try{let n=i(e,t);n!==void 0&&(s[r]=F.parse(n))}catch(n){this.pendingReports.push(new M(r,e,n))}return{...t,contributions:s}}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}register(e){let t=e;if(t.failureMode==="fatal"&&!this.coreFolds.has(t))throw new TypeError(`Projection '${t.key}' is fatal but is not one of the journal's core folds; a plugin's fold isolates`);let s=this.projections.get(t.key);if(s===t)return()=>{};if(s!==void 0)throw new TypeError(`Duplicate projection key: ${t.key}`);this.projections.set(t.key,t);let r=()=>{if(this.projections.get(t.key)===t){this.projections.delete(t.key);for(let i of this.states.values())i.delete(t.key);for(let i of this.failures.values())i.delete(t.key)}};try{for(let i of this.folded)this.foldLineage(t,i,this.lineage(i))}catch(i){throw r(),i}return this.flushReports(),r}state(e,t){if(this.register(e),!this.folded.has(t))if(this.loaded.has(t))this.ensureFolded(t);else{if(this.catalog.has(t))throw new E(t);return e.init()}let s=this.failures.get(t)?.get(e.key);if(s!==void 0)throw s;let r=S(this.states,t);if(!r.has(e.key))try{r.set(e.key,e.init())}catch(i){let n=this.failProjection(e,t,i);throw this.flushReports(),n}return r.get(e.key)}ensureFolded(e){if(!this.folded.has(e)){try{let t=this.lineage(e);for(let s of this.projections.values())this.foldLineage(s,e,t)}catch(t){throw this.dropStates(e),this.holds.has(e)||this.drop(e),t}this.folded.add(e)}}dropStates(e){this.states.delete(e),this.failures.delete(e)}foldLineage(e,t,s){try{let r=e.init();for(let i of s)r=e.apply(r,i);S(this.states,t).set(e.key,r)}catch(r){this.failProjection(e,t,r)}}fold(e){for(let t of this.projections.values())this.foldOne(t,e)}foldOne(e,t){let s=t.thread_id;if(this.failures.get(s)?.has(e.key)===!0)return;let r=S(this.states,s);try{if(Z(t)!==null){this.foldLineage(e,s,this.lineage(s,t.seq));return}let i=r.has(e.key)?r.get(e.key):e.init();r.set(e.key,e.apply(i,t))}catch(i){this.failProjection(e,s,i)}}failProjection(e,t,s){if(e.failureMode!=="isolate")throw s;let r=new k(e.key,t,s);return S(this.failures,t).set(e.key,r),this.states.get(t)?.delete(e.key),this.pendingReports.push(r),r}flushReports(){if(!this.writing)for(let e of this.pendingReports.splice(0))this.reportError(e)}reportError(e){try{this.onListenerError(e)}catch(t){console.error(t)}}},_=class extends Error{threadId;cause;constructor(e,t){super(`A group on thread ${e} could not be committed; the journal refuses every later write and the owner must exit`),this.threadId=e,this.cause=t,this.name="JournalCommitError"}},g=class extends Error{cause;constructor(e){super(e===void 0?"Journal writes have been revoked":`Journal writes have been revoked: ${e.message}`),this.cause=e,this.name="JournalRevokedError"}},E=class extends Error{threadId;constructor(e){super(`Thread ${e} is not loaded; read it inside thread.read or a retention`),this.threadId=e,this.name="ThreadNotLoadedError"}},j=class extends Error{seq;constructor(e){super(`Row ${e} belongs to a thread that is not loaded`),this.seq=e,this.name="RowNotLoadedError"}},v=class extends Error{threadIds;cause;constructor(e,t){super(`The catalog could not record the summaries of ${e.join(", ")}; the next write carries them`),this.threadIds=e,this.cause=t,this.name="CatalogWriteError"}},A=class extends Error{threadId;cause;constructor(e,t){super(`The summary of thread ${e} could not be recomputed from its rows`),this.threadId=e,this.cause=t,this.name="RepairError"}},M=class extends Error{key;threadId;cause;constructor(e,t,s){super(`Summary contributor '${e}' failed on thread ${t}`),this.key=e,this.threadId=t,this.cause=s,this.name="ContributionError"}};export{w as a,m as b,te as c,L as d,F as e,P as f,R as g,ne as h,ae as i,k as j,C as k,B as l,H as m,W as n,x as o,D as p,q,fe as r,de as s,V as t,O as u,pe as v,K as w,_ as x,g as y,E as z,j as A};
1
+ import{q as y,r as J,t as z}from"./MMNNZCBO.js";var m=class extends Error{origin;reason;constructor(e,t){let{caller_thread_id:s,source_seq:r}=e,i={"unknown-caller":`thread ${s} is not in the journal`,"source-missing":`row ${r} does not exist`,"source-off-lineage":`row ${r} is not a row of thread ${s} or of a thread it forks from`,"source-not-a-call":`row ${r} is not a tool call, which a call cause cites`};super(`Invalid origin under thread ${s}: ${i[t]}`),this.name="InvalidOriginError",this.origin=e,this.reason=t}},b=class{summaries=new Map;ranks=new Map;children=new Map;nextRank=0;origins={callers:e=>this.callers(e),root:e=>this.callers(e).threads.at(-1),subtree:(e,t)=>this.subtree(e,t.self),isUnder:(e,t)=>this.callers(e).threads.some(s=>s.thread_id===t),requiredOwners:e=>this.requiredOwners(e)};get(e){return this.summaries.get(e)}has(e){return this.summaries.has(e)}keys(){return this.summaries.keys()}values(){return this.summaries.values()}view(){return this.summaries}set(e,t){if(!this.summaries.has(e)&&(this.ranks.set(e,this.nextRank++),t.origin!==null)){let s=t.origin.caller_thread_id,r=this.children.get(s);r===void 0?this.children.set(s,new Set([e])):r.add(e)}this.summaries.set(e,t)}delete(e){let t=this.summaries.get(e);if(t!==void 0){if(t.origin!==null){let s=this.children.get(t.origin.caller_thread_id);s?.delete(e),s?.size===0&&this.children.delete(t.origin.caller_thread_id)}this.summaries.delete(e),this.ranks.delete(e)}}reset(e){this.summaries.clear(),this.ranks.clear(),this.children.clear(),this.nextRank=0;for(let t of e)this.set(t.thread_id,t)}callers(e){let t=[],s=new Set;for(let r=this.summaries.get(e);r!==void 0&&(s.add(r.thread_id),t.push(r),r.origin!==null);){let i=r.origin.caller_thread_id,n=this.summaries.get(i);if(n===void 0)return{threads:t,chain:{broken:"missing",at:r.thread_id}};if(s.has(i))return{threads:t,chain:{broken:"cycle",at:r.thread_id}};r=n}return{threads:t,chain:"complete"}}subtree(e,t){let s=this.summaries.get(e);if(s===void 0)return[];let r=new Set([e]),i=[e];for(let c=i.pop();c!==void 0;c=i.pop())for(let l of this.children.get(c)??[])r.has(l)||(r.add(l),i.push(l));r.delete(e);let a=[...r].sort((c,l)=>this.ranks.get(c)-this.ranks.get(l)).map(c=>this.summaries.get(c));return t?[s,...a]:a}requiredOwners(e){let t=new Map,s=(i,n)=>{let a=t.get(i);a===void 0&&t.set(i,a=[]),n!==null&&!a.includes(n)&&a.push(n)},r;if(typeof e=="string")r=this.callers(e);else{for(let n of e.requires)s(n,null);let i=e.origin?.caller_thread_id;i===void 0?r={threads:[],chain:"complete"}:this.summaries.has(i)?r=this.callers(i):r={threads:[],chain:{broken:"missing",at:null}}}for(let i of r.threads)for(let n of i.requires)s(n,i.thread_id);return{owners:[...t].map(([i,n])=>({owner:i,introducedBy:n})),chain:r.chain}}};function te(o,e){let t=[],s=new Set;for(let r=o.get(e);r!==void 0&&!s.has(r.thread_id);)s.add(r.thread_id),t.push(r),r=r.fork===null?void 0:o.get(r.fork.thread_id);return t}import{z as G}from"zod";function L(o){return Array.isArray(o)?`[${o.map(e=>L(e)).join(",")}]`:o!==null&&typeof o=="object"?`{${Object.entries(o).filter(([,t])=>t!==void 0).sort(([t],[s])=>t<s?-1:t>s?1:0).map(([t,s])=>`${JSON.stringify(t)}:${L(s)}`).join(",")}}`:JSON.stringify(o)}var F=G.json();function P(o){return Array.isArray(o)?o.map(e=>P(e)):typeof o=="object"&&o!==null?Object.fromEntries(Object.entries(o).map(([e,t])=>[e,P(t)])):o}function N(o,e){let{key:t,init:s,apply:r}=e;return e.onFork!=="reset"?{key:t,failureMode:o,init:s,apply:r}:{key:t,failureMode:o,init:s,apply:(i,n)=>J(n)?s():r(i,n)}}var ne=o=>Object.freeze(N("isolate",o)),ae=o=>N("fatal",o),k=class extends Error{projectionKey;threadId;cause;constructor(e,t,s){super(`Projection '${e}' failed on thread ${t}`),this.projectionKey=e,this.threadId=t,this.cause=s,this.name="ProjectionFailedError"}};import{createHash as Q}from"node:crypto";import{z as U}from"zod";var C=class{opened=!1;get isOpen(){return this.opened}async open(){this.opened||(await this.doOpen(),this.opened=!0)}async close(){this.opened&&(await this.doClose(),this.opened=!1)}async head(){return this.requireOpen(),this.doHead()}async append(e){if(this.requireOpen(),e.rows.length===0)throw new Error("An attempt holds at least one row");let t=e.rows[0].thread_id,s=e.baseHead;for(let r of e.rows){if(r.thread_id!==t)throw new Error("An attempt holds rows of one thread");if(r.seq<=s)throw new Error(`Row ${r.seq} does not follow ${s} in attempt ${e.id}`);s=r.seq}return this.doAppend(e,X(e))}async read(e){return this.requireOpen(),this.doRead(e)}async rowAt(e){return this.requireOpen(),this.doRowAt(e)}async threads(){return this.requireOpen(),this.doThreads()}async summaries(){return this.requireOpen(),this.doSummaries()}async putSummaries(e,t){this.requireOpen(),e.length>0&&await this.doPutSummaries(e,t)}async replaceCatalog(e,t){this.requireOpen(),await this.doReplaceCatalog(e,t)}serialize(e){return JSON.stringify(e)}serializeSummary(e){return JSON.stringify(e)}requireOpen(){if(!this.opened)throw new Error(`${this.constructor.name} is not open`)}};function X(o){return Q("sha256").update(JSON.stringify([o.baseHead,o.writer,o.rows])).digest("hex")}var B=class extends Error{location;constructor(e){super(`Journal is busy: ${e}. Close its current writer before opening another.`),this.location=e,this.name="JournalBusyError"}},H=class extends Error{location;waitedMs;constructor(e,t){super(`Journal store ${e} stayed locked by another connection for ${t} ms`),this.location=e,this.waitedMs=t,this.name="StoreBusyError"}},W=class extends Error{expected;actual;constructor(e,t){super(`The journal's head is ${t}, not ${e}; another write landed first`),this.expected=e,this.actual=t,this.name="JournalConflictError"}},x=class extends Error{acquisitionId;constructor(e){super(`Writer ${e} no longer holds the journal`),this.acquisitionId=e,this.name="WriterLostError"}},D=class extends Error{attemptId;constructor(e){super(`Attempt ${e} was already written with different rows`),this.attemptId=e,this.name="AttemptMismatchError"}},q=class extends Error{payload;cause;constructor(e,t){super(`Unparsable journal row: ${e.slice(0,200)}`),this.payload=e,this.cause=t,this.name="CorruptJournalError"}};function fe(o,e=t=>t){try{return y(e(JSON.parse(o)))}catch(t){throw t instanceof SyntaxError||t instanceof U.ZodError?new q(o,t):t}}function de(o){try{return z.parse(JSON.parse(o))}catch(e){throw e instanceof SyntaxError||e instanceof U.ZodError?new q(o,e):e}}var V=44,O=class extends Error{found;location;constructor(e,t){super(`Journal at ${t} is ${e===0?"unstamped":`format v${e}`}; this build reads v${V}. Start a new journal directory; the existing journal has been preserved.`),this.found=e,this.location=t,this.name="IncompatibleJournalError"}};function pe(o,e,t){if(!(o===V||!e))throw new O(o,t)}import{randomUUID as I}from"node:crypto";function R(o,e,t){for(let s of o)try{let r=s(e);Y(r)&&Promise.resolve(r).catch(t)}catch(r){t(r)}}var Y=o=>(typeof o=="object"||typeof o=="function")&&o!==null&&typeof o.then=="function";function w(o){if(o!==null&&typeof o=="object"&&!Object.isFrozen(o)){Object.freeze(o);for(let e of Object.values(o))w(e)}return o}function S(o,e){let t=o.get(e);return t===void 0&&o.set(e,t=new Map),t}var Z=o=>o.type==="thread/spawned"?o.data.fork:null,K=class{projections=new Map;coreFolds;states=new Map;failures=new Map;pendingReports=[];dirty=new Set;listeners=new Set;revokedListeners=new Set;contributors=new Map;catalog=new b;loaded=new Map;loading=new Map;rowReads=new Map;generations=new Map;bySeq=new Map;holds=new Map;folded=new Set;summarizer;onListenerError;lease;ownsStore=!1;seq=0;writable=!0;revokedBy;queue=Promise.resolve();writing=!1;closing=!1;store;constructor(e,t){this.store=e,this.summarizer=t.summarize,this.onListenerError=t.onListenerError??(s=>{console.error(s)}),this.coreFolds=new Set(t.coreFolds);for(let s of this.coreFolds)this.register(s)}revokeWrites(){this.writable=!1}onRevoked(e){return this.revokedListeners.add(e),()=>this.revokedListeners.delete(e)}async open(){this.lease=await this.store.acquireWriter();try{this.store.isOpen||(await this.store.open(),this.ownsStore=!0),this.seq=await this.store.head(),this.catalog.reset((await this.store.summaries()).map(i=>w(i))),this.loaded.clear(),this.bySeq.clear(),this.folded.clear(),this.states.clear(),this.failures.clear(),this.pendingReports.length=0,this.dirty.clear();let e=await this.store.threads(),t=e.filter(({threadId:i,lastSeq:n})=>this.catalog.get(i)?.through_seq!==n),s=new Set(e.map(({threadId:i})=>i)),r=[...this.catalog.keys()].some(i=>!s.has(i));(t.length>0||r)&&await this.repair(e,new Set(t.map(({threadId:i})=>i)),{replace:r,opening:!0})}catch(e){throw await this.close(),e}}async close(){this.closing=!0,await this.queue,this.writable=!1;let e=this.lease;this.lease=void 0;try{await e?.release()}finally{this.ownsStore&&await this.store.close(),this.ownsStore=!1}}get head(){return this.seq}summary(e){return this.catalog.get(e)}summaries(){return[...this.catalog.values()]}summaryMap(){return this.catalog.view()}origins={...this.catalog.origins,validate:async e=>{let{caller_thread_id:t,source_seq:s,cause:r}=e;if(!this.catalog.has(t))throw new m(e,"unknown-caller");let i=await this.readRow(s);if(i===void 0)throw new m(e,"source-missing");if(!this.inLineage(t,i))throw new m(e,"source-off-lineage");if(r.kind==="call"&&i.type!=="tool/call")throw new m(e,"source-not-a-call")}};contribute(e,t,s={}){if(this.contributors.has(e))throw new TypeError(`Duplicate summary contributor: ${e}`);this.contributors.set(e,t);let r=s.refresh??(n=>!Object.hasOwn(n.contributions,e)),i=this.enqueue(async()=>{if(this.requireWritable(),this.contributors.get(e)!==t)return[];let n=await this.store.threads(),a=new Set;for(let{threadId:c}of n){let l=this.catalog.get(c);l!==void 0&&r(l)&&a.add(c)}return a.size===0?[]:await this.repair(n,a,{replace:!1,opening:!1})});return i.catch(n=>{n instanceof g||this.reportError(n)}),{withdraw:()=>{this.contributors.get(e)===t&&this.contributors.delete(e)},refreshed:i}}rebuildCatalog(){return this.enqueue(async()=>{this.requireWritable();let e=await this.store.threads();await this.repair(e,new Set(e.map(({threadId:t})=>t)),{replace:!0,opening:!1})})}async repair(e,t,s){let{replace:r,opening:i}=s,n=new Map(this.catalog.view()),a=new Set(this.loaded.keys()),c=new Set,l=u=>(a.has(u)||c.add(u),this.loadRows(u)),d=[];this.writing=!0;try{if(i)for(let h of t)this.catalog.delete(h);for(let h of t)await l(h);for(let h of t)for(let p of this.hops(h,1/0))await l(p.threadId);let u=new Map;for(let{threadId:h}of e)if(t.has(h))try{this.ensureFolded(h),u.set(h,w(structuredClone(this.summarize(h))))}catch(p){this.pendingReports.push(new A(h,p)),d.push(h);let T=n.get(h);T!==void 0&&u.set(h,this.withRegisteredContributions(T))}let f=new Map;for(let{threadId:h}of e){let p=u.get(h)??n.get(h);p!==void 0&&f.set(h,p)}let $=[...this.dirty].flatMap(h=>{let p=u.has(h)?void 0:this.catalog.get(h);return p===void 0?[]:[p]});try{r?await this.store.replaceCatalog([...f.values()],this.writer()):await this.store.putSummaries([...u.values(),...$],this.writer()),this.dirty.clear()}catch(h){throw i?h:this.revoke("(catalog)",h)}this.catalog.reset(f.values())}catch(u){throw this.catalog.reset(n.values()),u}finally{for(let u of c)this.unload(u);this.writing=!1}return this.flushReports(),d}withRegisteredContributions(e){let t=Object.entries(e.contributions).filter(([s])=>this.contributors.has(s));return w({...e,contributions:Object.fromEntries(t)})}requireWritable(){if(!this.writable||this.closing)throw new g(this.revokedBy)}loadedThreads(){return[...this.loaded.keys()]}flush(){return this.queue.then(()=>{})}hold(e){for(let s of e)this.holds.set(s,(this.holds.get(s)??0)+1);let t=!1;return()=>{if(!t){t=!0;for(let s of e){let r=(this.holds.get(s)??1)-1;r>0?this.holds.set(s,r):this.holds.delete(s)}}}}load(e){if(this.folded.has(e)||!this.catalog.has(e))return Promise.resolve();let t=this.loading.get(e);return t===void 0&&(t=(async()=>{let s=this.hops(e,1/0).map(i=>i.threadId),r=this.hold(s);try{for(let i of s)await this.loadRows(i);this.ensureFolded(e)}finally{r()}this.flushReports()})().finally(()=>this.loading.delete(e)),this.loading.set(e,t)),t}isLoaded(e){return this.folded.has(e)}unload(e){if(this.holds.has(e))return!1;let t=[...this.loaded.keys()].filter(s=>s!==e&&this.hops(s,1/0).some(r=>r.threadId===e));if(t.some(s=>this.holds.has(s)))return!1;this.drop(e);for(let s of t)this.drop(s);return!0}drop(e){this.generations.set(e,(this.generations.get(e)??0)+1);let t=this.loaded.get(e);if(t!==void 0)for(let s of t)this.bySeq.delete(s.seq);this.loaded.delete(e),this.folded.delete(e),this.dropStates(e)}eventAt(e){let t=this.bySeq.get(e);if(t===void 0&&e>=1&&e<=this.seq)throw new j(e);return t}async readRow(e){let t=this.bySeq.get(e);if(t!==void 0)return t;let s=await this.store.rowAt(e);return s===void 0?void 0:w(s)}rows(e,t=1/0){let s=this.own(e);return t===1/0?s:s.slice(0,this.firstAfter(s,t))}rowsAfter(e,t){let s=this.own(e);return s.slice(this.firstAfter(s,t))}lineage(e,t=1/0){return this.hops(e,t).reverse().flatMap(s=>this.rows(s.threadId,s.upTo))}inLineage(e,t){return this.hops(e,1/0).some(s=>s.threadId===t.thread_id&&t.seq<=s.upTo)}stateAt(e,t,s){let r=e.init();for(let i of this.lineage(t,s))r=e.apply(r,i);return r}hops(e,t){let s=[],r={threadId:e,upTo:t};for(;r!==void 0;){s.push(r);let i=this.spawnOf(r.threadId);r=i===void 0||i.fork===null||i.seq>r.upTo?void 0:{threadId:i.fork.thread_id,upTo:Math.min(i.fork.seq,r.upTo)}}return s}spawnOf(e){let t=this.catalog.get(e);if(t!==void 0)return{seq:t.spawn_seq,fork:t.fork};let s=this.loaded.get(e)?.[0];if(s?.type==="thread/spawned")return{seq:s.seq,fork:s.data.fork}}own(e){let t=this.loaded.get(e);if(t!==void 0)return t;if(this.catalog.has(e))throw new E(e);return[]}loadRows(e){if(this.loaded.has(e))return Promise.resolve();let t=this.rowReads.get(e);return t===void 0&&(t=this.readRows(e).finally(()=>this.rowReads.delete(e)),this.rowReads.set(e,t)),t}async readRows(e){for(;;){let t=this.generations.get(e)??0,s=await this.store.read(e);if(this.loaded.has(e))return;if((this.generations.get(e)??0)===t){for(let r of s)w(r);this.loaded.set(e,s);for(let r of s)this.bySeq.set(r.seq,r);return}}}firstAfter(e,t){let s=0,r=e.length;for(;s<r;){let i=s+r>>>1;e[i].seq<=t?s=i+1:r=i}return s}async append(e,t,s){let[r]=await this.appendAll([{type:e,data:t,options:s}]);return r}appendAll(e){if(e.length===0)return!this.writable||this.closing?Promise.reject(new g(this.revokedBy)):Promise.resolve([]);if(this.closing)return Promise.reject(new g(this.revokedBy));let t=e[0].options.threadId;return this.enqueue(()=>this.write(t,()=>({rows:e,value:void 0}),s=>s))}transact(e,t){return this.closing?Promise.reject(new g(this.revokedBy)):this.enqueue(()=>this.write(e,t,(s,r)=>({events:s,value:r})))}enqueue(e){let t=this.queue.then(e);return this.queue=t.catch(()=>{}),t}async write(e,t,s){if(!this.writable)throw new g(this.revokedBy);let r=this.hold([e]);try{return await this.writeHeld(e,t,s)}finally{r()}}async writeHeld(e,t,s){let r=this.catalog.has(e);r&&await this.load(e);let i=t();if(typeof i.then=="function")throw new TypeError("A transact callback is synchronous: it may not await, since it runs inside the write queue");let{rows:n,value:a}=i;if(n.length===0)return s([],a);if(n.some(f=>f.options.threadId!==e))throw new Error(`A group holds rows of one thread, ${e}`);let c=n.filter(f=>f.type==="thread/spawned").length;if(!r&&(n[0].type!=="thread/spawned"||c!==1))throw new Error(`Thread ${e} does not exist: its first group must begin with its one spawn row`);if(r&&c>0)throw new Error(`Thread ${e} already exists; a second spawn row is refused`);let l=n.map((f,$)=>w(y({seq:this.seq+$+1,type:f.type,thread_id:e,data:JSON.parse(JSON.stringify(f.data)),source_seqs:f.options.sourceSeqs??[]}))),d=Z(l[0]);if(d!==null){if(d.seq>=l[0].seq)throw new Error(`A fork's spawn row must name an earlier row, not ${d.seq}`);await this.load(d.thread_id)}let u=d===null?()=>{}:this.hold([d.thread_id]);try{return s(await this.commit(e,r,l),a)}finally{u()}}async commit(e,t,s){t||(this.loaded.set(e,[]),this.folded.delete(e));try{this.ensureFolded(e)}catch(r){throw t||this.drop(e),r}this.writing=!0;try{try{await this.store.append({id:I(),baseHead:this.seq,writer:this.writer(),rows:s})}catch(n){throw t||this.drop(e),this.revoke(e,n)}this.seq=s.at(-1).seq;let r;try{let n=this.loaded.get(e);for(let a of s)n.push(a),this.bySeq.set(a.seq,a),this.fold(a);r=w(structuredClone(this.summarize(e)))}catch(n){throw this.drop(e),this.revoke(e,n)}this.catalog.set(e,r);for(let n of s)this.publish(n);this.dirty.add(e);let i=[...this.dirty].flatMap(n=>{let a=this.catalog.get(n);return a===void 0?[]:[a]});try{await this.store.putSummaries(i,this.writer()),this.dirty.clear()}catch(n){if(n instanceof x)throw this.revoke(e,n);this.pendingReports.push(new v([...this.dirty],n))}}finally{this.writing=!1}return this.flushReports(),s}writer(){if(this.lease===void 0)throw new Error("The journal is not open");return this.lease.acquisitionId}revoke(e,t){let s=new _(e,t);return this.writable=!1,this.revokedBy=s,R(this.revokedListeners,s,r=>this.reportError(r)),s}publish(e){R(this.listeners,e,t=>this.reportError(t))}summarize(e){let t=this.summarizer(this,e),s={};for(let[r,i]of this.contributors)try{let n=i(e,t);n!==void 0&&(s[r]=F.parse(n))}catch(n){this.pendingReports.push(new M(r,e,n))}return{...t,contributions:s}}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}register(e){let t=e;if(t.failureMode==="fatal"&&!this.coreFolds.has(t))throw new TypeError(`Projection '${t.key}' is fatal but is not one of the journal's core folds; a plugin's fold isolates`);let s=this.projections.get(t.key);if(s===t)return()=>{};if(s!==void 0)throw new TypeError(`Duplicate projection key: ${t.key}`);this.projections.set(t.key,t);let r=()=>{if(this.projections.get(t.key)===t){this.projections.delete(t.key);for(let i of this.states.values())i.delete(t.key);for(let i of this.failures.values())i.delete(t.key)}};try{for(let i of this.folded)this.foldLineage(t,i,this.lineage(i))}catch(i){throw r(),i}return this.flushReports(),r}state(e,t){if(this.register(e),!this.folded.has(t))if(this.loaded.has(t))this.ensureFolded(t);else{if(this.catalog.has(t))throw new E(t);return e.init()}let s=this.failures.get(t)?.get(e.key);if(s!==void 0)throw s;let r=S(this.states,t);if(!r.has(e.key))try{r.set(e.key,e.init())}catch(i){let n=this.failProjection(e,t,i);throw this.flushReports(),n}return r.get(e.key)}ensureFolded(e){if(!this.folded.has(e)){try{let t=this.lineage(e);for(let s of this.projections.values())this.foldLineage(s,e,t)}catch(t){throw this.dropStates(e),this.holds.has(e)||this.drop(e),t}this.folded.add(e)}}dropStates(e){this.states.delete(e),this.failures.delete(e)}foldLineage(e,t,s){try{let r=e.init();for(let i of s)r=e.apply(r,i);S(this.states,t).set(e.key,r)}catch(r){this.failProjection(e,t,r)}}fold(e){for(let t of this.projections.values())this.foldOne(t,e)}foldOne(e,t){let s=t.thread_id;if(this.failures.get(s)?.has(e.key)===!0)return;let r=S(this.states,s);try{if(Z(t)!==null){this.foldLineage(e,s,this.lineage(s,t.seq));return}let i=r.has(e.key)?r.get(e.key):e.init();r.set(e.key,e.apply(i,t))}catch(i){this.failProjection(e,s,i)}}failProjection(e,t,s){if(e.failureMode!=="isolate")throw s;let r=new k(e.key,t,s);return S(this.failures,t).set(e.key,r),this.states.get(t)?.delete(e.key),this.pendingReports.push(r),r}flushReports(){if(!this.writing)for(let e of this.pendingReports.splice(0))this.reportError(e)}reportError(e){try{this.onListenerError(e)}catch(t){console.error(t)}}},_=class extends Error{threadId;cause;constructor(e,t){super(`A group on thread ${e} could not be committed; the journal refuses every later write and the owner must exit`),this.threadId=e,this.cause=t,this.name="JournalCommitError"}},g=class extends Error{cause;constructor(e){super(e===void 0?"Journal writes have been revoked":`Journal writes have been revoked: ${e.message}`),this.cause=e,this.name="JournalRevokedError"}},E=class extends Error{threadId;constructor(e){super(`Thread ${e} is not loaded; read it inside thread.read or a retention`),this.threadId=e,this.name="ThreadNotLoadedError"}},j=class extends Error{seq;constructor(e){super(`Row ${e} belongs to a thread that is not loaded`),this.seq=e,this.name="RowNotLoadedError"}},v=class extends Error{threadIds;cause;constructor(e,t){super(`The catalog could not record the summaries of ${e.join(", ")}; the next write carries them`),this.threadIds=e,this.cause=t,this.name="CatalogWriteError"}},A=class extends Error{threadId;cause;constructor(e,t){super(`The summary of thread ${e} could not be recomputed from its rows`),this.threadId=e,this.cause=t,this.name="RepairError"}},M=class extends Error{key;threadId;cause;constructor(e,t,s){super(`Summary contributor '${e}' failed on thread ${t}`),this.key=e,this.threadId=t,this.cause=s,this.name="ContributionError"}};export{m as a,te as b,L as c,F as d,P as e,R as f,w as g,ne as h,ae as i,k as j,C as k,B as l,H as m,W as n,x as o,D as p,q,fe as r,de as s,V as t,O as u,pe as v,K as w,_ as x,g as y,E as z,j as A};