@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
@@ -1,7 +1,8 @@
1
1
  import { z } from 'zod';
2
2
  import { type PluginJournal } from '../../journal/index.js';
3
- import { type AnswerCheck } from '../../loop/index.js';
4
- import type { JournalEvent, Seq, ThreadOrigin, ThreadSummary, ToolResult, ToolResultPayloadInput, TurnEndReason } from '../../models/index.js';
3
+ import { type AnswerCheck } from '../../state/index.js';
4
+ import type { JournalEvent, Seq, ThreadOrigin, ThreadSummary, TurnEndReason } from '../../records/journal.js';
5
+ import type { ToolResult, ToolResultPayloadInput } from '../../records/toolResult.js';
5
6
  import type { DeepReadonly } from '../../util/json.js';
6
7
  import { type AssignmentOutcome } from './request.js';
7
8
  import type { ReadonlyState } from '../../util/foldState.js';
@@ -84,7 +85,7 @@ export declare const delegationRow: {
84
85
  } | {
85
86
  op: "stop_cleaned";
86
87
  task_id: string;
87
- }) => import("../../models/index.js").ExtensionRecord;
88
+ }) => import("../../records/journal.js").ExtensionRecord;
88
89
  parse: (value: {
89
90
  op: "started";
90
91
  task_id: string;
@@ -235,7 +236,7 @@ export declare const delegationRow: {
235
236
  task_id: string;
236
237
  } | undefined;
237
238
  contribution(message: {
238
- role?: import("../../models/index.js").InputRole;
239
+ role?: import("../../records/journal.js").InputRole;
239
240
  content: string | readonly import("../../llm/content.js").ContentPartInput[];
240
241
  }, value: {
241
242
  op: "started";
@@ -266,8 +267,8 @@ export declare const delegationRow: {
266
267
  task_id: string;
267
268
  }, options?: {
268
269
  sourceSeqs?: readonly Seq[];
269
- }): import("../../models/index.js").StepContribution;
270
- matchesSource(record: DeepReadonly<import("../../models/index.js").ExtensionRecord>): boolean;
270
+ }): import("../../records/journal.js").StepContribution;
271
+ matchesSource(record: DeepReadonly<import("../../records/journal.js").ExtensionRecord>): boolean;
271
272
  rejection(reason: string, value: {
272
273
  op: "started";
273
274
  task_id: string;
@@ -298,7 +299,7 @@ export declare const delegationRow: {
298
299
  }): {
299
300
  decision: "reject";
300
301
  reason: string;
301
- source: import("../../models/index.js").ExtensionRecord;
302
+ source: import("../../records/journal.js").ExtensionRecord;
302
303
  };
303
304
  readContribution: (event: JournalEvent) => {
304
305
  op: "started";
@@ -328,7 +329,7 @@ export declare const delegationRow: {
328
329
  op: "stop_cleaned";
329
330
  task_id: string;
330
331
  } | undefined;
331
- readSource: (source: DeepReadonly<import("../../models/index.js").ExtensionRecord> | null) => {
332
+ readSource: (source: DeepReadonly<import("../../records/journal.js").ExtensionRecord> | null) => {
332
333
  op: "started";
333
334
  task_id: string;
334
335
  origin: {
@@ -356,7 +357,7 @@ export declare const delegationRow: {
356
357
  op: "stop_cleaned";
357
358
  task_id: string;
358
359
  } | undefined;
359
- told: import("../../journal/projection.js").PluginProjection<import("../../kit/extension.js").ToldNotices<{
360
+ told: import("../../journal/projection.js").PluginProjection<import("../../services/extensionEvents.js").ToldNotices<{
360
361
  op: "started";
361
362
  task_id: string;
362
363
  origin: {
@@ -589,7 +590,7 @@ export declare const DELEGATIONS_OWNER = "lagent:delegations";
589
590
  */
590
591
  export declare const taskManaged: (summary: Pick<ThreadSummary, "requires">) => boolean;
591
592
  /** A managed thread's latest task, contributed to its catalog entry while delegations is mounted. */
592
- export declare const latestTask: import("../../services/contributions.js").ContributionDefinition<{
593
+ export declare const latestTask: import("../../services/catalogContributions.js").ContributionDefinition<{
593
594
  task_id: string;
594
595
  origin: {
595
596
  caller_thread_id: string;
@@ -1,11 +1,14 @@
1
1
  import type { Context } from '@leuduan/cordis';
2
2
  import { z } from 'zod';
3
- import type { ModelRoute } from '../../llm/index.js';
4
- import type { InvocationContext, ModelSelection, WriteRows } from '../../loop/index.js';
5
- import type { Seq, ThreadEnvironment, ToolResultPayloadInput, TurnEndReason } from '../../models/index.js';
3
+ import type { ModelRoute } from '../../llm/provider.js';
4
+ import type { InvocationContext } from '../../loop/index.js';
5
+ import type { ModelSelection } from '../../llm/provider.js';
6
+ import type { WriteRows } from '../../state/index.js';
7
+ import type { Seq, ThreadEnvironment, TurnEndReason } from '../../records/journal.js';
8
+ import type { ToolResultPayloadInput } from '../../records/toolResult.js';
6
9
  import type { DeepReadonly } from '../../util/json.js';
7
- import type { InitialInstallationInput } from '../../services/presets.js';
8
- import type { Thread } from '../../services/thread.js';
10
+ import type { InitialInstallationInput } from '../../services/presets/installations.js';
11
+ import type { Thread } from '../../services/threads/index.js';
9
12
  import type { StopBy, TaskRef, TaskSettlement } from './record.js';
10
13
  import type { RoleConfig } from './role.js';
11
14
  /**
@@ -23,7 +23,7 @@ export declare const ROLE_PRESET = "role";
23
23
  * here would stop existing children from ever activating once a root tool is renamed. The
24
24
  * delegations service checks them before creating a child.
25
25
  */
26
- export declare const rolePreset: import("../../services/preset.js").Preset<z.ZodObject<{
26
+ export declare const rolePreset: import("../../services/presets/definition.js").Preset<z.ZodObject<{
27
27
  id: z.ZodString;
28
28
  basePrompt: z.ZodString;
29
29
  tools: z.ZodArray<z.ZodString>;
@@ -1,9 +1,10 @@
1
1
  import { Service, type Context } from '@leuduan/cordis';
2
2
  import { z } from 'zod';
3
3
  import type { InvocationContext, WaitRequest } from '../../loop/index.js';
4
- import type { ThreadSummary, ToolResultPayloadInput } from '../../models/index.js';
4
+ import type { ThreadSummary } from '../../records/journal.js';
5
+ import type { ToolResultPayloadInput } from '../../records/toolResult.js';
5
6
  import type { AppendEntry, PluginJournal } from '../../journal/index.js';
6
- import type { ToolReply } from '../../kit/tool.js';
7
+ import type { ToolReply } from '../../services/tools.js';
7
8
  import { type StopOptions, type StopOutcome } from './cleanup.js';
8
9
  import { type TaskRef, type TaskState } from './record.js';
9
10
  import { type AdmissionRefused, type AssignmentOwner, type DelegationRequest, type AssignmentOwnerHandle } from './request.js';
@@ -16,7 +17,7 @@ declare module '@leuduan/cordis' {
16
17
  }
17
18
  export declare const DelegationsConfigSchema: z.ZodObject<{
18
19
  maxOpenTasks: z.ZodNumber;
19
- clock: z.ZodCustom<import("../../kit/timers.js").Clock, import("../../kit/timers.js").Clock>;
20
+ clock: z.ZodCustom<import("../../util/timers.js").Clock, import("../../util/timers.js").Clock>;
20
21
  }, z.core.$strict>;
21
22
  export type DelegationsConfig = z.input<typeof DelegationsConfigSchema>;
22
23
  /**
@@ -83,7 +84,7 @@ export type ReadOutcome = {
83
84
  * on its live owner's say, with no call, receipt or wait, and owes no notice. A blocking call suspends on a
84
85
  * durable wait (`waitFor`) that this service resolves with the task's answer; a background call
85
86
  * returns a receipt and `read_agent` waits the same way. The waits, slots and constraint are
86
- * described in `docs/delegation.md`. A call's task ends no later than its opening call's result, unless
87
+ * described in `docs/records/delegation.md`. A call's task ends no later than its opening call's result, unless
87
88
  * that result is its receipt:
88
89
  * the service watches `tool/result` rows, and one citing a task's opening call ends the task if it
89
90
  * is still open, however core answered the call, a deny, an unregistered tool, an aborted turn or a
@@ -149,9 +150,9 @@ export declare class DelegationsService extends Service<DelegationsConfig> {
149
150
  private readonly owners;
150
151
  /** Owners' tasks whose settling their owner was told of in this process. */
151
152
  private readonly settledTold;
152
- /** The task constraint's registration with the owner, through which the wait book resolves delegation waits. */
153
+ /** The task constraint's registration with the owner, through which the wait resolver resolves delegation waits. */
153
154
  private constraint;
154
- /** Every delegation wait, from its declaration to its call's answer, and when and with what it resolves (`waitBook.ts`). */
155
+ /** Every delegation wait, from its declaration to its call's answer, and when and with what it resolves (`waitResolver.ts`). */
155
156
  private readonly waits;
156
157
  private closing;
157
158
  constructor(ctx: Context, config: DelegationsConfig);
@@ -493,7 +494,7 @@ export declare class DelegationsService extends Service<DelegationsConfig> {
493
494
  /** Resolves once the run that served `task`, if still pending, is held or settled. */
494
495
  private runStopped;
495
496
  /**
496
- * Hands every row to the wait book, a turn's end and a receipt to the notice owner, and ends a task whose opening call was
497
+ * Hands every row to the wait resolver, a turn's end and a receipt to the notice owner, and ends a task whose opening call was
497
498
  * answered other than by its receipt. The stop is asked for here, synchronously, and the cleanup
498
499
  * owner queues its write before returning, so it lands before anything the caller writes after its
499
500
  * result.
@@ -539,7 +540,7 @@ export declare class DelegationsService extends Service<DelegationsConfig> {
539
540
  */
540
541
  private openTaskOf;
541
542
  /**
542
- * Stops the wait book deciding and lets each decision under way land; lets each call in flight,
543
+ * Stops the wait resolver deciding and lets each decision under way land; lets each call in flight,
543
544
  * opening its task, be answered on its aborted turn, so a result other than its receipt or its
544
545
  * wait stops its task, and each owner's start in flight finish, a new one being refused; then
545
546
  * waits for the stops and their cleanups while the journal still takes their rows. Tasks whose calls wait durably stay open, as
@@ -1,9 +1,9 @@
1
1
  import type { Context } from '@leuduan/cordis';
2
- import { type Clock } from '../../kit/timers.js';
3
- import type { JournalEvent } from '../../models/index.js';
4
- import type { OwnerHandle } from '../../services/owner.js';
2
+ import { type Clock } from '../../util/timers.js';
3
+ import type { JournalEvent } from '../../records/journal.js';
4
+ import type { OwnerHandle } from '../../services/threads/index.js';
5
5
  import type { NoticeDelivery } from './notices.js';
6
- import { type ReadWait, type ReadWhy } from './waits.js';
6
+ import { type ReadWait, type ReadWhy } from './waitContracts.js';
7
7
  /**
8
8
  * Why a read wait returns now, or `null` while it waits: a named task ended (`settled`); with
9
9
  * `activity`, a named child recorded a row after the read looked; nothing can advance a named open
@@ -12,8 +12,8 @@ import { type ReadWait, type ReadWhy } from './waits.js';
12
12
  * constraint. Read from the catalog and the owner, synchronously.
13
13
  */
14
14
  export declare function readCondition(ctx: Context, wait: ReadWait): ReadWhy | null;
15
- /** What the book is handed by the service that mounts it. */
16
- export type WaitBookOptions = {
15
+ /** What the resolver is handed by the service that mounts it. */
16
+ export type WaitResolverOptions = {
17
17
  /** The clock `read_agent`'s deadlines and the retries of failed decisions are kept on. */
18
18
  readonly clock: Clock;
19
19
  /** Resolves once the task state can be served: no decision is taken before. */
@@ -44,7 +44,7 @@ export type WaitBookOptions = {
44
44
  * satisfied while the process was down; the drain stops deciding at shutdown, leaving what is due to
45
45
  * the next startup's repair.
46
46
  */
47
- export declare class WaitBook {
47
+ export declare class WaitResolver {
48
48
  /** Every delegation wait whose call is not answered yet, by caller and call. */
49
49
  private readonly waits;
50
50
  /** The unresolved waits by each child they name. */
@@ -59,9 +59,9 @@ export declare class WaitBook {
59
59
  private closing;
60
60
  private readonly ctx;
61
61
  private readonly options;
62
- constructor(ctx: Context, options: WaitBookOptions);
62
+ constructor(ctx: Context, options: WaitResolverOptions);
63
63
  /**
64
- * What a row does to the book: a declaration naming delegations is booked; a resolution stops
64
+ * What a row does to the resolver: a declaration naming delegations is booked; a resolution stops
65
65
  * deciding its wait, and a result of a booked call forgets it, telling a blocking call's task's
66
66
  * child, whose authority the call was; any row of a child a wait names decides that wait again, so
67
67
  * `until: 'activity'` sees the row and a task that ended is seen at once.
@@ -1,4 +1,4 @@
1
- import type { ConversationMessage } from '../../llm/index.js';
1
+ import type { ConversationMessage } from '../../llm/primitives.js';
2
2
  import { type DeepReadonly } from '../../util/json.js';
3
3
  import type { SentModelRequest } from '../../loop/index.js';
4
4
  /** Enough of a fingerprint to tell one value from another across restarts. */
@@ -1,7 +1,7 @@
1
1
  import type { Plugin } from '@leuduan/cordis';
2
2
  import { z } from 'zod';
3
3
  import type { PluginJournal } from '../../journal/index.js';
4
- import type { RowRef } from '../../loop/index.js';
4
+ import type { RowRef } from '../../state/index.js';
5
5
  /**
6
6
  * How a fork's first request compares with its source's request at the cut: whether it sent the
7
7
  * same head and route, and extended the same messages. `unavailable` when there is nothing to
@@ -1 +1 @@
1
- import{b as q}from"../../chunks/DRYAN665.js";import{d as y}from"../../chunks/2OSESBIL.js";import"../../chunks/YLNJXQ3Z.js";import"../../chunks/DDANMY45.js";import{d as c}from"../../chunks/37YOGDGY.js";import"../../chunks/KESCTXGO.js";import"../../chunks/TYTQRLTX.js";import{A as _}from"../../chunks/D7E6EWIE.js";import{z as r}from"zod";import{createHash as I}from"node:crypto";var m=e=>I("sha256").update(e).digest("hex").slice(0,12);function b(e){let{messages:s,agentName:t,threadId:a,llmCallId:o,purpose:n,...u}=e;return m(c(u))}var f=e=>m(c(e));var S=r.strictObject({status:r.enum(["matched","mismatched","unavailable"]),differs:r.array(r.enum(["head","route","messages"])),replaced:r.number().int().positive().nullable()}),j=r.strictObject({purpose:r.enum(["step","auxiliary"]),system_prompt_chars:r.number().int().nonnegative(),system_prompt_digest:r.string(),head_digest:r.string(),messages_digest:r.string(),prefix_check:S.nullable()}),x=q({plugin:"lagent:diagnostics",kind:"request",version:1,schema:j}),L={name:"lagent:diagnostics",inject:["journal"],apply(e){y(e,"diagnostics"),e.on("lagent/llm/sent",async({request:s,row:t})=>{let a=_(s.systemPrompt),o=b(s),n=t.type==="llm/request"?E(e.journal,t,o,s.messages):null;await x.append(e.journal,{purpose:s.purpose,system_prompt_chars:a.length,system_prompt_digest:m(a),head_digest:o,messages_digest:f(s.messages),prefix_check:n},{threadId:t.thread_id,sourceSeqs:[t.seq]}),n?.status==="mismatched"&&n.replaced===null&&e.reportError(new Error(`Thread ${t.thread_id}: a fork's first request differs from its source's in ${n.differs.join(", ")}`))})}};function D(e,s){for(let t of e.rowsAfter(s.threadId,s.seq)){if(!t.source_seqs.includes(s.seq))continue;let a=x.read(t);if(a!==void 0)return a}}function E(e,s,t,a){let o=e.rows(s.thread_id),n=o[0];if(n?.type!=="thread/spawned"||n.data.fork===null||o.some(i=>i.type==="llm/request"&&i.seq!==s.seq))return null;let{thread_id:u,seq:v}=n.data.fork,d=e.lineage(u,v).findLast(i=>i.type==="llm/request");if(d===void 0||d.type!=="llm/request")return k;let p=D(e,{threadId:d.thread_id,seq:d.seq});if(p===void 0)return k;let l=[];t!==p.head_digest&&l.push("head"),c(s.data.route)!==c(d.data.route)&&l.push("route");let g=d.data.message_count,h=null;return(a.length<g||f(a.slice(0,g))!==p.messages_digest)&&(l.push("messages"),h=e.lineage(s.thread_id).find(i=>i.type==="surface/replaced"&&i.seq>d.seq&&i.seq<s.seq)?.seq??null),{status:l.length===0?"matched":"mismatched",differs:l,replaced:h}}var k={status:"unavailable",differs:[],replaced:null};export{S as PrefixCheckSchema,L as diagnostics,D as requestMeasures};
1
+ import{d as y}from"../../chunks/S34ZA2R6.js";import{b as q}from"../../chunks/6FRNHMCV.js";import"../../chunks/CUK7CGC7.js";import"../../chunks/BPRCULZH.js";import"../../chunks/DDANMY45.js";import{c}from"../../chunks/BBCW2FZK.js";import"../../chunks/MMNNZCBO.js";import"../../chunks/G44LG6VL.js";import{A as _}from"../../chunks/D4PQP5MA.js";import{z as r}from"zod";import{createHash as I}from"node:crypto";var m=e=>I("sha256").update(e).digest("hex").slice(0,12);function b(e){let{messages:s,agentName:t,threadId:a,llmCallId:o,purpose:n,...u}=e;return m(c(u))}var f=e=>m(c(e));var S=r.strictObject({status:r.enum(["matched","mismatched","unavailable"]),differs:r.array(r.enum(["head","route","messages"])),replaced:r.number().int().positive().nullable()}),j=r.strictObject({purpose:r.enum(["step","auxiliary"]),system_prompt_chars:r.number().int().nonnegative(),system_prompt_digest:r.string(),head_digest:r.string(),messages_digest:r.string(),prefix_check:S.nullable()}),x=q({plugin:"lagent:diagnostics",kind:"request",version:1,schema:j}),L={name:"lagent:diagnostics",inject:["journal"],apply(e){y(e,"diagnostics"),e.on("lagent/llm/sent",async({request:s,row:t})=>{let a=_(s.systemPrompt),o=b(s),n=t.type==="llm/request"?E(e.journal,t,o,s.messages):null;await x.append(e.journal,{purpose:s.purpose,system_prompt_chars:a.length,system_prompt_digest:m(a),head_digest:o,messages_digest:f(s.messages),prefix_check:n},{threadId:t.thread_id,sourceSeqs:[t.seq]}),n?.status==="mismatched"&&n.replaced===null&&e.reportError(new Error(`Thread ${t.thread_id}: a fork's first request differs from its source's in ${n.differs.join(", ")}`))})}};function D(e,s){for(let t of e.rowsAfter(s.threadId,s.seq)){if(!t.source_seqs.includes(s.seq))continue;let a=x.read(t);if(a!==void 0)return a}}function E(e,s,t,a){let o=e.rows(s.thread_id),n=o[0];if(n?.type!=="thread/spawned"||n.data.fork===null||o.some(i=>i.type==="llm/request"&&i.seq!==s.seq))return null;let{thread_id:u,seq:v}=n.data.fork,d=e.lineage(u,v).findLast(i=>i.type==="llm/request");if(d===void 0||d.type!=="llm/request")return k;let p=D(e,{threadId:d.thread_id,seq:d.seq});if(p===void 0)return k;let l=[];t!==p.head_digest&&l.push("head"),c(s.data.route)!==c(d.data.route)&&l.push("route");let g=d.data.message_count,h=null;return(a.length<g||f(a.slice(0,g))!==p.messages_digest)&&(l.push("messages"),h=e.lineage(s.thread_id).find(i=>i.type==="surface/replaced"&&i.seq>d.seq&&i.seq<s.seq)?.seq??null),{status:l.length===0?"matched":"mismatched",differs:l,replaced:h}}var k={status:"unavailable",differs:[],replaced:null};export{S as PrefixCheckSchema,L as diagnostics,D as requestMeasures};
@@ -0,0 +1,10 @@
1
+ import { z } from 'zod';
2
+ /**
3
+ * What the file tools are configured with, all of it the host's choice: the spawn environment and
4
+ * the trusted `rg` the search tools run (`rg: null` for none).
5
+ */
6
+ export declare const FileToolsConfigSchema: z.ZodObject<{
7
+ environment: z.ZodRecord<z.ZodString, z.ZodString>;
8
+ rg: z.ZodNullable<z.ZodString>;
9
+ }, z.core.$strict>;
10
+ export type FileToolsConfig = z.input<typeof FileToolsConfigSchema>;
@@ -1,7 +1,7 @@
1
- import type { Stats } from 'node:fs';
2
1
  import { z } from 'zod';
3
2
  import type { InvocationContext } from '../../loop/index.js';
4
- import type { ToolResultPayload } from '../../models/index.js';
3
+ import type { ToolResultPayload } from '../../records/toolResult.js';
4
+ import type { FileAccess } from '../../services/confinement/service.js';
5
5
  import { type UnifiedDiff } from '../../util/diff.js';
6
6
  /** The largest file `edit_files` reads, which bounds the memory one call takes. */
7
7
  export declare const MAX_EDIT_FILE_BYTES: number;
@@ -33,11 +33,14 @@ type Operation = z.infer<typeof OperationSchema>;
33
33
  /**
34
34
  * The one tool that changes files: creates, updates, deletes and moves, any number in one call.
35
35
  *
36
- * Everything is checked before anything is written: every path is placed inside the write roots
37
- * and outside every git directory, every file read, every hunk located, and the operations checked
38
- * against each other. Each file is then written to a temporary sibling and renamed over its target,
39
- * or hard-linked into place when it must not replace anything, so no reader sees half of it; a
40
- * filesystem without hard links gets no new file. There is no transaction across files: when one
36
+ * Everything is checked before anything is written: every path is judged by the call's file policy
37
+ * (read and write for what is changed or moved, write for what is created or moved to) and kept out
38
+ * of every git directory, every file read, every hunk located, and the operations checked against
39
+ * each other. Each file is then written to a temporary sibling and renamed over its target, or
40
+ * hard-linked into place when it must not replace anything, so no reader sees half of it; a
41
+ * filesystem without hard links gets no new file. The call touches files only through its
42
+ * operation's facade, which judges every step again as it happens, and never opens an existing file
43
+ * for writing. There is no transaction across files: when one
41
44
  * fails to commit, or the call is cancelled, the call stops there, before its next filesystem
42
45
  * change, and its result says which files were committed and which were not.
43
46
  *
@@ -46,25 +49,6 @@ type Operation = z.infer<typeof OperationSchema>;
46
49
  * change by anything else in between fails that file instead of being overwritten.
47
50
  */
48
51
  export declare const editFilesTool: import("../../loop/tool.js").Tool;
49
- /**
50
- * The filesystem calls `edit_files` makes, so a test can fail or delay one. Every other caller
51
- * passes {@link nodeEditFs}.
52
- */
53
- export type EditFs = {
54
- readFile(path: string): Promise<Buffer>;
55
- /** Creates `path`, which must not exist. */
56
- writeFile(path: string, data: Buffer, options: {
57
- mode?: number;
58
- }): Promise<void>;
59
- rename(from: string, to: string): Promise<void>;
60
- link(existing: string, created: string): Promise<void>;
61
- unlink(path: string): Promise<void>;
62
- stat(path: string): Promise<Stats>;
63
- lstat(path: string): Promise<Stats>;
64
- mkdir(path: string): Promise<void>;
65
- chmod(path: string, mode: number): Promise<void>;
66
- };
67
- export declare const nodeEditFs: EditFs;
68
52
  /** A path an operation names: as named, as shown, and where it really is. */
69
53
  type Target = {
70
54
  readonly named: string;
@@ -74,6 +58,8 @@ type Target = {
74
58
  readonly display: string;
75
59
  /** With its symbolic links resolved: what is read, written, compared and locked. */
76
60
  readonly real: string;
61
+ /** What the policy was asked to allow for it, and is asked again when it is committed. */
62
+ readonly access: readonly FileAccess[];
77
63
  };
78
64
  /** What a file was when it was read, to tell whether it changed before it is replaced. */
79
65
  type Snapshot = {
@@ -81,6 +67,9 @@ type Snapshot = {
81
67
  readonly mtimeMs: number;
82
68
  readonly hash: string;
83
69
  readonly mode: number;
70
+ /** Which file it was: a file replaced by another with the same content is not the one that was read. */
71
+ readonly dev: number;
72
+ readonly ino: number;
84
73
  };
85
74
  type Planned = {
86
75
  readonly kind: 'created';
@@ -124,5 +113,5 @@ export type EditedFile = {
124
113
  * Applies `operations` for a call: the whole of `edit_files` but its parameter parsing. See
125
114
  * {@link editFilesTool}.
126
115
  */
127
- export declare function applyFileOperations(operations: readonly Operation[], context: InvocationContext, fs: EditFs): Promise<ToolResultPayload>;
116
+ export declare function applyFileOperations(operations: readonly Operation[], context: InvocationContext): Promise<ToolResultPayload>;
128
117
  export {};
@@ -0,0 +1,9 @@
1
+ import type { FileScope } from '../../services/confinement/files.js';
2
+ import type { RepositoryLocation } from '../../sys/git.js';
3
+ /**
4
+ * The repository containing `path`: the nearest directory at or above it holding a `.git` entry, as
5
+ * `findRepository` finds it, with every file read through `files`. A path the policy refuses to be
6
+ * read rejects with its `FileAccessError`, since whether it is git's own cannot then be told; a file
7
+ * system error counts as not there.
8
+ */
9
+ export declare function findRepositoryThrough(files: FileScope, path: string): Promise<RepositoryLocation | null>;
@@ -0,0 +1,18 @@
1
+ import type { Plugin } from '@leuduan/cordis';
2
+ import { type FileToolsConfig } from './config.js';
3
+ export type { FileToolsConfig } from './config.js';
4
+ /** The file tools that read the workspace without changing it. */
5
+ export declare const READ_ONLY_TOOLS: readonly ["read_file", "list_dir", "rg_search", "rg_files"];
6
+ /** The file tools that run `rg`, provided only where the host has it (`rg` in the configuration). */
7
+ export declare const RG_TOOLS: readonly string[];
8
+ /**
9
+ * Registers `read_file`, `list_dir`, `rg_search`, `rg_files` and `edit_files` for the life of the
10
+ * plugin. A tool reaches files through `InvocationContext.operation`, so the confinement policy
11
+ * judges every path; the host names the spawn environment and the trusted `rg` the search tools
12
+ * run, and there is no default for either.
13
+ *
14
+ * Ungranted: `agents` choose which of them each agent sees. The web tools ship as `webTools`, the
15
+ * shell commands as `commands`, which owns their processes, and `ask_question` as the `lagent:ask`
16
+ * plugin, since it needs a host that can reach the user.
17
+ */
18
+ export declare const fileTools: Plugin.Object<FileToolsConfig>;
@@ -0,0 +1 @@
1
+ import{a,b,c}from"../../chunks/IAAEP6VL.js";import"../../chunks/VYMT4TXD.js";import"../../chunks/N6IXG2VL.js";import"../../chunks/6DRCKZ2C.js";import"../../chunks/7LI64H5X.js";import"../../chunks/3UMZMPWW.js";import"../../chunks/34KW6VNQ.js";import"../../chunks/JFX2MXBA.js";import"../../chunks/CUK7CGC7.js";import"../../chunks/BPRCULZH.js";import"../../chunks/FJLU4UH3.js";import"../../chunks/DDANMY45.js";import"../../chunks/BBCW2FZK.js";import"../../chunks/MMNNZCBO.js";import"../../chunks/G44LG6VL.js";import"../../chunks/D4PQP5MA.js";export{a as READ_ONLY_TOOLS,b as RG_TOOLS,c as fileTools};
@@ -0,0 +1,6 @@
1
+ import type { Tool } from '../../loop/index.js';
2
+ import type { FileToolsConfig } from './config.js';
3
+ /** What the model is told about the tools that need more than their description. */
4
+ export declare const guidance: Map<string, string>;
5
+ /** The file tools `config` provides: without `rg`, neither search tool; nothing searches by another means. */
6
+ export declare const fileToolsFor: (config: FileToolsConfig) => readonly Tool[];
@@ -1,5 +1,5 @@
1
1
  import type { Journal } from '../../journal/index.js';
2
- import type { Seq } from '../../models/index.js';
2
+ import type { Seq } from '../../records/journal.js';
3
3
  /**
4
4
  * Every message that has ever been on a thread's surface, numbered from 1 in lineage order, by the
5
5
  * row behind it. Stand-ins are not numbered, so a number never moves: not across compactions,
@@ -1 +1 @@
1
- import{a,b,c,d,e}from"../../chunks/UC3FVVJ2.js";import"../../chunks/NAOUTU7A.js";import"../../chunks/UKXMCHHT.js";import"../../chunks/2OSESBIL.js";import"../../chunks/YLNJXQ3Z.js";import"../../chunks/DDANMY45.js";import"../../chunks/37YOGDGY.js";import"../../chunks/KESCTXGO.js";import"../../chunks/TYTQRLTX.js";import"../../chunks/D7E6EWIE.js";export{b as HISTORY_RECALL_TOOLS,d as HistoryRecallConfigSchema,a as historyNumbers,e as historyRecall,c as renderRecall};
1
+ import{a,b,c,d,e}from"../../chunks/2GCIWSOA.js";import"../../chunks/JFX2MXBA.js";import"../../chunks/S34ZA2R6.js";import"../../chunks/CUK7CGC7.js";import"../../chunks/BPRCULZH.js";import"../../chunks/FJLU4UH3.js";import"../../chunks/DDANMY45.js";import"../../chunks/BBCW2FZK.js";import"../../chunks/MMNNZCBO.js";import"../../chunks/G44LG6VL.js";import"../../chunks/D4PQP5MA.js";export{b as HISTORY_RECALL_TOOLS,d as HistoryRecallConfigSchema,a as historyNumbers,e as historyRecall,c as renderRecall};
@@ -1,5 +1,5 @@
1
1
  import type { PluginJournal } from '../../journal/index.js';
2
- import { type MessageRole } from '../../llm/index.js';
2
+ import { type MessageRole } from '../../llm/primitives.js';
3
3
  /** One message that has been on a thread's surface, as recall shows it. */
4
4
  export type HistoryMessage = {
5
5
  /** Its history number: 1 for the first message the thread's conversation ever held. */
@@ -1,6 +1,6 @@
1
1
  import type { Client } from '@modelcontextprotocol/sdk/client/index.js';
2
2
  import { type Tool as RemoteTool } from '@modelcontextprotocol/sdk/types.js';
3
- import { type ToolSpec } from '../../llm/index.js';
3
+ import { type ToolSpec } from '../../llm/primitives.js';
4
4
  import type { McpConfig } from './config.js';
5
5
  import type { UnexposableTool } from './errors.js';
6
6
  /** One exposable tool: its lagent name, the definition the server listed, and the spec built from it. */
@@ -5,7 +5,7 @@ export type { McpConfig, McpConfigInput, McpTransportConfig, McpTransportFactory
5
5
  export { McpServerError } from './errors.js';
6
6
  export type { McpServerErrorKind, UnexposableTool } from './errors.js';
7
7
  export { MAX_TOOL_NAME_LENGTH, mcpToolName } from './names.js';
8
- export { CALL_META_KEY, SESSION_RESET_NOTE } from './tool.js';
8
+ export { CALL_META_KEY, SESSION_RESET_NOTE } from './tools.js';
9
9
  /**
10
10
  * Connects to one MCP server and exposes its tools as ordinary lagent tools named
11
11
  * `mcp__<server>__<tool>`, granted to `agents`. One mount is one server: a server that cannot be
@@ -28,6 +28,6 @@ export { CALL_META_KEY, SESSION_RESET_NOTE } from './tool.js';
28
28
  * })
29
29
  * ```
30
30
  *
31
- * The design and its reasons are in `docs/mcp.md`.
31
+ * The design and its reasons are in `docs/records/mcp.md`.
32
32
  */
33
33
  export declare const mcp: Plugin.Object<McpConfigInput>;
@@ -1,4 +1,4 @@
1
- import{a as Y}from"../../chunks/BM3S37EZ.js";import{b as z}from"../../chunks/RK3VP2Q4.js";import{a as B,b as W}from"../../chunks/NAOUTU7A.js";import"../../chunks/UKXMCHHT.js";import{a as v}from"../../chunks/34KW6VNQ.js";import{a as w}from"../../chunks/PUSUPTAT.js";import"../../chunks/CDQG7RKA.js";import{a as N,b as H}from"../../chunks/DXFXAYDN.js";import"../../chunks/DRYAN665.js";import{a as U}from"../../chunks/2OSESBIL.js";import"../../chunks/YLNJXQ3Z.js";import"../../chunks/DDANMY45.js";import{d as g}from"../../chunks/37YOGDGY.js";import"../../chunks/KESCTXGO.js";import"../../chunks/TYTQRLTX.js";import{m as A}from"../../chunks/D7E6EWIE.js";import{scopeOf as Fe}from"@leuduan/cordis";import{z as c}from"zod";var S=64,Z=/^(?!.*__)[A-Za-z0-9](?:[A-Za-z0-9_-]*[A-Za-z0-9-])?$/,V=/^[A-Za-z0-9_-]+$/,me=n=>n.replace(/[^A-Za-z0-9_-]/g,"_"),O=(n,e,t)=>`mcp__${n}__${t??me(e)}`;var D=24,pe=c.strictObject({kind:c.literal("stdio"),command:c.tuple([c.string().min(1)],c.string()),cwd:c.string().min(1),env:c.record(c.string(),c.string())}),fe=c.strictObject({kind:c.literal("streamable-http"),url:c.url({protocol:/^https?$/,error:"url must be an http or https URL"}),headers:c.record(c.string(),c.string()).default({})}),ge=c.strictObject({kind:c.literal("custom"),create:c.custom(n=>typeof n=="function","create must be a function")}),X=c.discriminatedUnion("kind",[pe,fe,ge]),we=c.union([c.string().min(1),c.strictObject({name:c.string().min(1),as:c.string().regex(V,"as must use A-Z a-z 0-9 _ -")})]),P=n=>c.number().positive().finite().default(n),k=c.strictObject({name:c.string().max(D).regex(Z,"name must use A-Z a-z 0-9 _ -, start with a letter or digit, never end with _, and never contain __"),transport:X,agents:U,confirm:c.union([c.literal("all"),c.literal("none"),c.strictObject({except:c.array(c.string())})]),onInterrupted:c.union([c.literal("report"),c.literal("annotations"),c.strictObject({rerun:c.array(c.string())})]),maxConcurrentCalls:c.union([c.number().int().positive(),c.literal("unbounded")]),tools:c.array(we).optional(),instructions:c.boolean().default(!1),connectTimeoutSeconds:P(30),callTimeoutSeconds:P(120),maxCallSeconds:P(600),maxContentBytes:c.number().int().nonnegative().default(1024*1024),signal:c.custom(n=>n instanceof AbortSignal,"signal must be an AbortSignal").optional()}).superRefine((n,e)=>{if(n.maxCallSeconds<n.callTimeoutSeconds&&e.addIssue({code:"custom",path:["maxCallSeconds"],message:"must be at least callTimeoutSeconds"}),n.tools===void 0)return;let t=n.tools.map(s=>typeof s=="string"?s:s.name),r=t.find((s,a)=>t.indexOf(s)!==a);if(r!==void 0&&e.addIssue({code:"custom",path:["tools"],message:`lists ${r} more than once`}),typeof n.confirm=="object")for(let s of n.confirm.except)t.includes(s)||e.addIssue({code:"custom",path:["confirm","except"],message:`${s} is not in tools`});if(typeof n.onInterrupted=="object")for(let s of n.onInterrupted.rerun)t.includes(s)||e.addIssue({code:"custom",path:["onInterrupted","rerun"],message:`${s} is not in tools`})});import{ListToolsResultSchema as be}from"@modelcontextprotocol/sdk/types.js";var K={entries:new Map,unexposable:[]};async function Q(n,e){let t=[],r=new Set,s;do{let a=await n.request({method:"tools/list",params:s===void 0?{}:{cursor:s}},be,{signal:e});if(t.push(...a.tools),s=a.nextCursor,s!==void 0){if(r.has(s))throw new Error(`the server repeated the pagination cursor ${s}`);r.add(s)}}while(s!==void 0);return t}function ee(n,e){let t=n.tools===void 0?void 0:new Map(n.tools.map(o=>typeof o=="string"?[o,void 0]:[o.name,o.as])),r=[],s=[];for(let o of e){if(t!==void 0&&!t.has(o.name))continue;let u=O(n.name,o.name,t?.get(o.name));s.push({remote:o,name:u,problem:ve(o,u)})}if(t!==void 0){let o=new Set(e.map(u=>u.name));for(let u of t.keys())o.has(u)||r.push({tool:u,reason:"the server does not offer it"})}let a=new Map;for(let o of s)a.set(o.name,[...a.get(o.name)??[],o]);let i=new Map;for(let o of s){let u=a.get(o.name);if(u.length>1){let p=u.filter(l=>l!==o).map(l=>l.remote.name);r.push({tool:o.remote.name,reason:`${o.name} collides with ${p.join(", ")}`});continue}if(o.problem!==null){r.push({tool:o.remote.name,reason:o.problem});continue}i.set(o.name,{name:o.name,remoteName:o.remote.name,definition:o.remote,spec:A.parse(te(o.remote,o.name)),fingerprint:g(o.remote)})}return{entries:i,unexposable:L(r)}}var J=(n,e)=>n<e?-1:n>e?1:0,te=(n,e)=>({name:e,description:n.description??n.title??"",input_schema:n.inputSchema});function ve(n,e){return e.length>64?`${e} is ${e.length} characters, over the ${64} a tool name may have`:n.execution?.taskSupport==="required"?"it requires task-augmented execution":A.safeParse(te(n,e)).success?null:"its input schema is not an object schema"}var L=n=>[...n].sort((e,t)=>J(e.tool,t.tool)||J(e.reason,t.reason)),ne=(n,e)=>g(n)===g(e);import{Client as Ee}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as oe,StreamableHTTPError as _e}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{ToolListChangedNotificationSchema as Me}from"@modelcontextprotocol/sdk/types.js";import Te from"@leuduan/lagent/package.json"with{type:"json"};function re(){return Te.version}import{ReadBuffer as xe,serializeMessage as Se}from"@modelcontextprotocol/sdk/shared/stdio.js";var ye=8*1024,b=class{onclose;onerror;onmessage;spawned=null;buffer=new xe;stderr="";exit=null;closed=!1;closedEarly=!1;options;constructor(e){this.options=e}get pid(){return this.spawned?.pid}get stderrTail(){return this.stderr}get exited(){return this.exit}async start(){if(this.spawned!==null)throw new Error("ContainedStdioTransport already started");let e=await H({command:this.options.command,cwd:this.options.cwd,env:this.options.env,signal:this.options.signal,killGraceMs:this.options.killGraceMs??N,stdio:"pipes"});if(this.spawned=e,this.closedEarly)throw await e.stop(),new Error("ContainedStdioTransport closed while starting");e.stdout.on("data",t=>this.receive(t)),e.stderr.setEncoding("utf8"),e.stderr.on("data",t=>{this.stderr=(this.stderr+t).slice(-ye),w.debug("MCP server '%s' stderr: %s",this.options.server,t.trimEnd())}),e.stdin.on("error",t=>this.onerror?.(t)),e.result.then(t=>{this.exit=t,this.closed=!0,this.onclose?.()})}receive(e){try{this.buffer.append(e)}catch(t){this.onerror?.(t instanceof Error?t:new Error(String(t)));return}for(;;){let t;try{t=this.buffer.readMessage()}catch(r){this.onerror?.(r instanceof Error?r:new Error(String(r)));continue}if(t===null)return;this.onmessage?.(t)}}async send(e){let t=this.spawned?.stdin;if(t===void 0||this.closed||t.destroyed)throw new Error("The MCP server is not running");t.write(Se(e))||await new Promise((r,s)=>{let a=()=>{t.off("close",i),r()},i=()=>{t.off("drain",a),s(new Error("The MCP server closed its input"))};t.once("drain",a),t.once("close",i)})}async close(){let e=this.spawned;if(e===null){this.closedEarly=!0;return}e.stdin.end();let t=this.options.killGraceMs??N,r,s=await Promise.race([e.result.then(()=>!0),new Promise(a=>r=setTimeout(()=>a(!1),t))]);clearTimeout(r),s?await e.result:await e.stop()}};var $e=5e3,y=class{live=null;count=0;disposed=!1;options;constructor(e){this.options=e}get current(){return this.live?.alive?this.live:null}async open(e,t){if(this.disposed)throw new Error("the mount is disposed");e.throwIfAborted();let r=new Ee({name:"lagent",version:re()},{capabilities:{}}),s={alive:!0},a={transport:null},i=null;r.onerror=l=>w.debug("MCP server '%s': %s",this.options.server,l),r.onclose=()=>{s.alive&&(s.alive=!1,i!==null&&(i.alive=!1),i!==null&&a.transport!==null&&!this.disposed&&this.options.onLost(i,this.describeClose(a.transport)))};let o=!1;r.setNotificationHandler(Me,async()=>{i===null?o=!0:i===this.current&&this.options.onToolsChanged(i)});let u=(async()=>{let l=Ce(await this.createTransport(e));if(a.transport=l,e.aborted)throw await T(l.close()),e.reason;await r.connect(l,{signal:e,timeout:t})})();try{if(await v(u,e),e.throwIfAborted(),this.disposed)throw new Error("the mount is disposed")}catch(l){throw s.alive=!1,await T(r.close()),se(l,a.transport)}let p=a.transport;if(i={number:this.count+1,client:r,transport:p,instructions:r.getInstructions()??null,get alive(){return s.alive},set alive(l){s.alive=l}},!s.alive)throw se(new Error("the connection closed during initialization"),p);return this.count=i.number,this.live=i,o&&this.options.onToolsChanged(i),i}async invalidate(e){e.alive&&(e.alive=!1,await T(e.client.close()))}async dispose(){this.disposed=!0;let e=this.live;this.live=null,!(e===null||!e.alive)&&(e.alive=!1,await T(e.client.close()))}async createTransport(e){let t=this.options.transport;switch(t.kind){case"stdio":return new b({server:this.options.server,command:t.command,cwd:t.cwd,env:t.env,signal:this.options.lifetime});case"streamable-http":return new oe(new URL(t.url),{requestInit:{headers:t.headers}});case"custom":return await t.create(e)}}describeClose(e){if(!(e instanceof b))return"the connection closed";let t=e.exited,r=t===null?"its connection closed":t.exitCode!==null?`it exited with code ${t.exitCode}`:`it was ended by ${t.exitSignal??"a signal"}`;return ae(`the server process ended: ${r}`,e)}},ie=n=>n instanceof _e&&n.code===404;function Ce(n){let e=n.close.bind(n),t;return n.close=()=>t??=(async()=>{try{n instanceof oe&&await T(n.terminateSession()),await e()}catch(r){w.debug("MCP transport close failed: %s",r)}})(),n}async function T(n){let e;await Promise.race([n.catch(t=>w.debug("MCP cleanup failed: %s",t)),new Promise(t=>e=setTimeout(t,$e))]),clearTimeout(e)}function ae(n,e){let t=e instanceof b?e.stderrTail.trim():"";return t?`${n}; its stderr ended with:
1
+ import{a as Y}from"../../chunks/ASSQZH3F.js";import{a as N,c as H}from"../../chunks/7LI64H5X.js";import{a as w}from"../../chunks/PUSUPTAT.js";import{a as v}from"../../chunks/34KW6VNQ.js";import"../../chunks/DDZ7YF26.js";import{b as z}from"../../chunks/EPYQ5M3B.js";import{b as B,c as W}from"../../chunks/JFX2MXBA.js";import"../../chunks/6FRNHMCV.js";import{c as U}from"../../chunks/CUK7CGC7.js";import"../../chunks/BPRCULZH.js";import"../../chunks/FJLU4UH3.js";import"../../chunks/DDANMY45.js";import{c as g}from"../../chunks/BBCW2FZK.js";import"../../chunks/MMNNZCBO.js";import"../../chunks/G44LG6VL.js";import{h as A}from"../../chunks/D4PQP5MA.js";import{scopeOf as Fe}from"@leuduan/cordis";import{z as c}from"zod";var S=64,Z=/^(?!.*__)[A-Za-z0-9](?:[A-Za-z0-9_-]*[A-Za-z0-9-])?$/,V=/^[A-Za-z0-9_-]+$/,me=n=>n.replace(/[^A-Za-z0-9_-]/g,"_"),O=(n,e,t)=>`mcp__${n}__${t??me(e)}`;var D=24,pe=c.strictObject({kind:c.literal("stdio"),command:c.tuple([c.string().min(1)],c.string()),cwd:c.string().min(1),env:c.record(c.string(),c.string())}),fe=c.strictObject({kind:c.literal("streamable-http"),url:c.url({protocol:/^https?$/,error:"url must be an http or https URL"}),headers:c.record(c.string(),c.string()).default({})}),ge=c.strictObject({kind:c.literal("custom"),create:c.custom(n=>typeof n=="function","create must be a function")}),X=c.discriminatedUnion("kind",[pe,fe,ge]),we=c.union([c.string().min(1),c.strictObject({name:c.string().min(1),as:c.string().regex(V,"as must use A-Z a-z 0-9 _ -")})]),P=n=>c.number().positive().finite().default(n),k=c.strictObject({name:c.string().max(D).regex(Z,"name must use A-Z a-z 0-9 _ -, start with a letter or digit, never end with _, and never contain __"),transport:X,agents:U,confirm:c.union([c.literal("all"),c.literal("none"),c.strictObject({except:c.array(c.string())})]),onInterrupted:c.union([c.literal("report"),c.literal("annotations"),c.strictObject({rerun:c.array(c.string())})]),maxConcurrentCalls:c.union([c.number().int().positive(),c.literal("unbounded")]),tools:c.array(we).optional(),instructions:c.boolean().default(!1),connectTimeoutSeconds:P(30),callTimeoutSeconds:P(120),maxCallSeconds:P(600),maxContentBytes:c.number().int().nonnegative().default(1024*1024),signal:c.custom(n=>n instanceof AbortSignal,"signal must be an AbortSignal").optional()}).superRefine((n,e)=>{if(n.maxCallSeconds<n.callTimeoutSeconds&&e.addIssue({code:"custom",path:["maxCallSeconds"],message:"must be at least callTimeoutSeconds"}),n.tools===void 0)return;let t=n.tools.map(s=>typeof s=="string"?s:s.name),r=t.find((s,a)=>t.indexOf(s)!==a);if(r!==void 0&&e.addIssue({code:"custom",path:["tools"],message:`lists ${r} more than once`}),typeof n.confirm=="object")for(let s of n.confirm.except)t.includes(s)||e.addIssue({code:"custom",path:["confirm","except"],message:`${s} is not in tools`});if(typeof n.onInterrupted=="object")for(let s of n.onInterrupted.rerun)t.includes(s)||e.addIssue({code:"custom",path:["onInterrupted","rerun"],message:`${s} is not in tools`})});import{ListToolsResultSchema as be}from"@modelcontextprotocol/sdk/types.js";var K={entries:new Map,unexposable:[]};async function Q(n,e){let t=[],r=new Set,s;do{let a=await n.request({method:"tools/list",params:s===void 0?{}:{cursor:s}},be,{signal:e});if(t.push(...a.tools),s=a.nextCursor,s!==void 0){if(r.has(s))throw new Error(`the server repeated the pagination cursor ${s}`);r.add(s)}}while(s!==void 0);return t}function ee(n,e){let t=n.tools===void 0?void 0:new Map(n.tools.map(o=>typeof o=="string"?[o,void 0]:[o.name,o.as])),r=[],s=[];for(let o of e){if(t!==void 0&&!t.has(o.name))continue;let u=O(n.name,o.name,t?.get(o.name));s.push({remote:o,name:u,problem:ve(o,u)})}if(t!==void 0){let o=new Set(e.map(u=>u.name));for(let u of t.keys())o.has(u)||r.push({tool:u,reason:"the server does not offer it"})}let a=new Map;for(let o of s)a.set(o.name,[...a.get(o.name)??[],o]);let i=new Map;for(let o of s){let u=a.get(o.name);if(u.length>1){let p=u.filter(l=>l!==o).map(l=>l.remote.name);r.push({tool:o.remote.name,reason:`${o.name} collides with ${p.join(", ")}`});continue}if(o.problem!==null){r.push({tool:o.remote.name,reason:o.problem});continue}i.set(o.name,{name:o.name,remoteName:o.remote.name,definition:o.remote,spec:A.parse(te(o.remote,o.name)),fingerprint:g(o.remote)})}return{entries:i,unexposable:L(r)}}var J=(n,e)=>n<e?-1:n>e?1:0,te=(n,e)=>({name:e,description:n.description??n.title??"",input_schema:n.inputSchema});function ve(n,e){return e.length>64?`${e} is ${e.length} characters, over the ${64} a tool name may have`:n.execution?.taskSupport==="required"?"it requires task-augmented execution":A.safeParse(te(n,e)).success?null:"its input schema is not an object schema"}var L=n=>[...n].sort((e,t)=>J(e.tool,t.tool)||J(e.reason,t.reason)),ne=(n,e)=>g(n)===g(e);import{Client as Ee}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as oe,StreamableHTTPError as _e}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{ToolListChangedNotificationSchema as Me}from"@modelcontextprotocol/sdk/types.js";import Te from"@leuduan/lagent/package.json"with{type:"json"};function re(){return Te.version}import{ReadBuffer as xe,serializeMessage as Se}from"@modelcontextprotocol/sdk/shared/stdio.js";var ye=8*1024,b=class{onclose;onerror;onmessage;spawned=null;buffer=new xe;stderr="";exit=null;closed=!1;closedEarly=!1;options;constructor(e){this.options=e}get pid(){return this.spawned?.pid}get stderrTail(){return this.stderr}get exited(){return this.exit}async start(){if(this.spawned!==null)throw new Error("ContainedStdioTransport already started");let e=await H({command:this.options.command,cwd:this.options.cwd,env:this.options.env,signal:this.options.signal,killGraceMs:this.options.killGraceMs??N,stdio:"pipes"});if(this.spawned=e,this.closedEarly)throw await e.stop(),new Error("ContainedStdioTransport closed while starting");e.stdout.on("data",t=>this.receive(t)),e.stderr.setEncoding("utf8"),e.stderr.on("data",t=>{this.stderr=(this.stderr+t).slice(-ye),w.debug("MCP server '%s' stderr: %s",this.options.server,t.trimEnd())}),e.stdin.on("error",t=>this.onerror?.(t)),e.result.then(t=>{this.exit=t,this.closed=!0,this.onclose?.()})}receive(e){try{this.buffer.append(e)}catch(t){this.onerror?.(t instanceof Error?t:new Error(String(t)));return}for(;;){let t;try{t=this.buffer.readMessage()}catch(r){this.onerror?.(r instanceof Error?r:new Error(String(r)));continue}if(t===null)return;this.onmessage?.(t)}}async send(e){let t=this.spawned?.stdin;if(t===void 0||this.closed||t.destroyed)throw new Error("The MCP server is not running");t.write(Se(e))||await new Promise((r,s)=>{let a=()=>{t.off("close",i),r()},i=()=>{t.off("drain",a),s(new Error("The MCP server closed its input"))};t.once("drain",a),t.once("close",i)})}async close(){let e=this.spawned;if(e===null){this.closedEarly=!0;return}e.stdin.end();let t=this.options.killGraceMs??N,r,s=await Promise.race([e.result.then(()=>!0),new Promise(a=>r=setTimeout(()=>a(!1),t))]);clearTimeout(r),s?await e.result:await e.stop()}};var $e=5e3,y=class{live=null;count=0;disposed=!1;options;constructor(e){this.options=e}get current(){return this.live?.alive?this.live:null}async open(e,t){if(this.disposed)throw new Error("the mount is disposed");e.throwIfAborted();let r=new Ee({name:"lagent",version:re()},{capabilities:{}}),s={alive:!0},a={transport:null},i=null;r.onerror=l=>w.debug("MCP server '%s': %s",this.options.server,l),r.onclose=()=>{s.alive&&(s.alive=!1,i!==null&&(i.alive=!1),i!==null&&a.transport!==null&&!this.disposed&&this.options.onLost(i,this.describeClose(a.transport)))};let o=!1;r.setNotificationHandler(Me,async()=>{i===null?o=!0:i===this.current&&this.options.onToolsChanged(i)});let u=(async()=>{let l=Ce(await this.createTransport(e));if(a.transport=l,e.aborted)throw await T(l.close()),e.reason;await r.connect(l,{signal:e,timeout:t})})();try{if(await v(u,e),e.throwIfAborted(),this.disposed)throw new Error("the mount is disposed")}catch(l){throw s.alive=!1,await T(r.close()),se(l,a.transport)}let p=a.transport;if(i={number:this.count+1,client:r,transport:p,instructions:r.getInstructions()??null,get alive(){return s.alive},set alive(l){s.alive=l}},!s.alive)throw se(new Error("the connection closed during initialization"),p);return this.count=i.number,this.live=i,o&&this.options.onToolsChanged(i),i}async invalidate(e){e.alive&&(e.alive=!1,await T(e.client.close()))}async dispose(){this.disposed=!0;let e=this.live;this.live=null,!(e===null||!e.alive)&&(e.alive=!1,await T(e.client.close()))}async createTransport(e){let t=this.options.transport;switch(t.kind){case"stdio":return new b({server:this.options.server,command:t.command,cwd:t.cwd,env:t.env,signal:this.options.lifetime});case"streamable-http":return new oe(new URL(t.url),{requestInit:{headers:t.headers}});case"custom":return await t.create(e)}}describeClose(e){if(!(e instanceof b))return"the connection closed";let t=e.exited,r=t===null?"its connection closed":t.exitCode!==null?`it exited with code ${t.exitCode}`:`it was ended by ${t.exitSignal??"a signal"}`;return ae(`the server process ended: ${r}`,e)}},ie=n=>n instanceof _e&&n.code===404;function Ce(n){let e=n.close.bind(n),t;return n.close=()=>t??=(async()=>{try{n instanceof oe&&await T(n.terminateSession()),await e()}catch(r){w.debug("MCP transport close failed: %s",r)}})(),n}async function T(n){let e;await Promise.race([n.catch(t=>w.debug("MCP cleanup failed: %s",t)),new Promise(t=>e=setTimeout(t,$e))]),clearTimeout(e)}function ae(n,e){let t=e instanceof b?e.stderrTail.trim():"";return t?`${n}; its stderr ended with:
2
2
  ${t}`:n}function se(n,e){let t=n instanceof Error?n:new Error(String(n)),r=e===null?t.message:ae(t.message||t.name,e);return r===t.message?t:new Error(r,{cause:t})}var h=class extends Error{name="McpServerError";server;kind;tools;constructor(e,t,r,s={}){super(`MCP server '${e}': ${r}`,s.cause===void 0?{}:{cause:s.cause}),this.server=e,this.kind=t,this.tools=s.tools??[]}},f=n=>n instanceof Error?n.message||n.name:String(n);var E=class{active=0;waiters=[];limit;constructor(e){this.limit=e}acquire(e){return e.throwIfAborted(),this.active<this.limit?(this.active+=1,Promise.resolve(this.releaser())):new Promise((t,r)=>{let s={grant:()=>{e.removeEventListener("abort",a),this.active+=1,t(this.releaser())}},a=()=>{let i=this.waiters.indexOf(s);i>=0&&this.waiters.splice(i,1),r(e.reason)};e.addEventListener("abort",a,{once:!0}),this.waiters.push(s)})}get waiting(){return this.waiters.length}releaser(){let e=!1;return()=>{e||(e=!0,this.active-=1,this.waiters.shift()?.grant())}}};import{CallToolResultSchema as Re,ErrorCode as le,McpError as I}from"@modelcontextprotocol/sdk/types.js";var Ae="The tool returned content addressed to the user only; nothing in it is for you.",Ne="The tool returned no content.",Oe=new Set(["image/png","image/jpeg","image/webp","image/gif"]),Pe=n=>{let e=n.trim().toLowerCase();return e==="image/jpg"?"image/jpeg":e};function ce(n,e){let t=[],r=[],s=[],a=[],i=e.maxContentBytes,o=l=>l>i?!1:(i-=l,!0);for(let l of n.content){if(!ke(l)){s.push(Le(l,o));continue}switch(l.type){case"text":a.push(l.text),t.push(l.text);break;case"image":{let m=_(l.data),d=Pe(l.mimeType);Oe.has(d)?o(m)?(r.push({type:"image",url:null,data:l.data,media_type:d,detail:"auto"}),t.push(`[image: ${d}, ${x(m)}]`)):t.push(`[image omitted: ${l.mimeType}, ${x(m)}, over this result's limit]`):t.push(`[image not shown: ${l.mimeType}, ${x(m)}; only PNG, JPEG, WebP and GIF are shown]`);break}case"audio":t.push(`[audio not shown: ${l.mimeType}, ${x(_(l.data))}]`);break;case"resource_link":t.push(`[resource link: ${l.name} <${l.uri}>${l.mimeType?` (${l.mimeType})`:""}]`);break;case"resource":{let m=l.resource;if("text"in m)t.push(`[resource: ${m.uri}]
3
3
  ${m.text}`);else{let d=m.mimeType?`${m.mimeType}, `:"";t.push(`[resource not shown: ${m.uri}, ${d}${x(_(m.blob))}]`)}break}}}let u=n.structuredContent;return u!==void 0&&!a.some(l=>Ie(l,u))&&t.push(JSON.stringify(u,null,2)),{output:t.join(`
4
4
  `)||(s.length>0?Ae:Ne),...r.length>0?{content:r}:{},is_error:n.isError===!0,notes:null,metadata:{mcp_server:e.server,mcp_tool:e.remoteName,...s.length>0?{user_content:s}:{}}}}function ke(n){let e=n.annotations?.audience;return e===void 0||e.includes("assistant")}function Le(n,e){let t=(r,s)=>{let a=_(r);return e(a)?{...s,data:r}:{...s,bytes:a,omitted:!0}};switch(n.type){case"text":return{type:"text",text:n.text};case"image":case"audio":return t(n.data,{type:n.type,mime_type:n.mimeType});case"resource_link":return{type:"resource_link",uri:n.uri,name:n.name,mime_type:n.mimeType??null};case"resource":return"text"in n.resource?{type:"resource",uri:n.resource.uri,text:n.resource.text}:t(n.resource.blob,{type:"resource",uri:n.resource.uri,mime_type:n.resource.mimeType??null})}}function Ie(n,e){try{return g(JSON.parse(n))===g(e)}catch{return!1}}function _(n){let e=n.endsWith("==")?2:n.endsWith("=")?1:0;return Math.max(0,Math.floor(n.length*3/4)-e)}function x(n){return n<1024?`${n} B`:n<1024*1024?`${(n/1024).toFixed(1)} KB`:`${(n/(1024*1024)).toFixed(1)} MB`}var ue="work.leuduan.lagent/call",R="The connection to this MCP server was re-established; any session state the server held may have been reset.";function je(n,e){if(n==="report")return"report";if(n==="annotations"){let t=e.definition.annotations;return t?.readOnlyHint===!0||t?.idempotentHint===!0?"rerun":"report"}return n.rerun.includes(e.remoteName)?"rerun":"report"}var de=(n,e)=>B({name:e.name,description:e.spec.description,parameters:{jsonSchema:e.spec.input_schema},onInterrupted:je(n.config.onInterrupted,e),executionMode:"parallel",execute:(t,r)=>Ge(n,e,t,r)});async function Ge(n,e,t,r){let s=d=>({output:d,is_error:!0,metadata:{mcp_server:n.server,mcp_tool:e.remoteName}}),{maxCallSeconds:a,callTimeoutSeconds:i,maxContentBytes:o}=n.config,u=AbortSignal.timeout(a*1e3),p=AbortSignal.any([r.signal,u]),l=d=>s(r.signal.aborted?`The call was cancelled ${d}; it was never sent to the MCP server.`:`The call's ${a} s deadline passed ${d}; it was never sent to the MCP server.`),m;try{m=await n.slots.acquire(p)}catch{return l("while it waited for a free slot")}try{let d;try{d=await n.ready(p)}catch(C){return p.aborted?l("while the connection was being re-established"):s(`The call was not sent. ${f(C)}`)}let $=n.entry(e.name);if($===void 0||$.fingerprint!==e.fingerprint)return s($===void 0?`The MCP server no longer offers ${e.remoteName}, so the call was not sent.`:`The MCP server changed the definition of ${e.remoteName}, so the call was not sent. Review the new definition and call again if it still fits.`);if(!d.alive)return s("The connection to the MCP server closed before the call was sent.");let G;try{G=await d.client.request({method:"tools/call",params:{name:e.remoteName,arguments:t,_meta:{[ue]:`${r.threadId}#${r.callSeq}`}}},Re,{signal:p,timeout:i*1e3,resetTimeoutOnProgress:!0,onprogress:()=>{}})}catch(C){return s(qe(n,C,d,r.signal,u))}let q=ce(G,{server:n.server,remoteName:e.remoteName,maxContentBytes:o}),F=n.takeSessionNote(d);return F===null?q:{...q,notes:[F]}}finally{m()}}function qe(n,e,t,r,s){let a="The server may or may not have run it.";return r.aborted?`The call was cancelled after it was sent. ${a}`:s.aborted?`The call's ${n.config.maxCallSeconds} s deadline passed after it was sent. ${a}`:ie(e)?(n.invalidate(t),"The MCP server had ended its session, so the call did not run. A new session opens with the next call."):e instanceof I&&e.code===le.RequestTimeout?`The MCP server sent no response or progress for ${n.config.callTimeoutSeconds} s. ${a}`:e instanceof I&&e.code===le.ConnectionClosed?`The connection to the MCP server was lost while the call was in flight. ${a}`:e instanceof I?`The MCP server answered with an error: ${f(e)}`:`The request to the MCP server failed: ${f(e)}. ${a}`}var M=class{server;slots;connection;lifetime=new AbortController;catalog=K;listedFrom=null;published=new Map;known=new Map;reported=[];started=!1;changedWhileStarting=!1;runningFor=null;disposed=!1;running=null;queued=null;reconnecting=null;noteOwedTo=null;cachedInstructions=null;ctx;config;constructor(e,t){this.ctx=e,this.config=t,this.server=t.name,this.slots=new E(t.maxConcurrentCalls==="unbounded"?1/0:t.maxConcurrentCalls),this.connection=new y({server:t.name,transport:t.transport,lifetime:this.lifetime.signal,onToolsChanged:()=>{this.started?this.refresh():this.changedWhileStarting=!0},onLost:(r,s)=>this.report(new h(this.server,"disconnect",s))})}get connectTimeoutMs(){return this.config.connectTimeoutSeconds*1e3}async start(){let e=[this.lifetime.signal,AbortSignal.timeout(this.connectTimeoutMs)];this.config.signal!==void 0&&e.push(this.config.signal);let t=AbortSignal.any(e);try{let s=await this.connection.open(t,this.connectTimeoutMs);this.cachedInstructions=s.instructions}catch(s){throw new h(this.server,"connect",`could not connect: ${f(s)}`,{cause:s})}let r=await this.refresh(t);if(!r.ok)throw r.error;this.started=!0,this.changedWhileStarting&&this.refresh()}async ready(e){let t=this.connection.current;if(t===null){if(this.disposed)throw new Error("the mount is disposed");this.reconnecting??=this.reconnect().finally(()=>{this.reconnecting=null}),t=await v(this.reconnecting,e)}if(this.listedFrom!==t.number){let r=this.running!==null&&this.runningFor===t?this.running:this.refresh(),s=await v(r,e);if(!s.ok)throw s.error;if(this.listedFrom!==t.number||!t.alive)throw new h(this.server,"refresh","the connection changed while its tools were being listed")}return t}async reconnect(){let e;try{let t=AbortSignal.any([this.lifetime.signal,AbortSignal.timeout(this.connectTimeoutMs)]);e=await this.connection.open(t,this.connectTimeoutMs)}catch(t){let r=new h(this.server,"connect",`could not reconnect: ${f(t)}`,{cause:t});throw this.report(r),r}return this.cachedInstructions=e.instructions,this.noteOwedTo=e.number,e}entry(e){return this.catalog.entries.get(e)}takeSessionNote(e){return this.noteOwedTo!==e.number?null:(this.noteOwedTo=null,R)}invalidate(e){e.alive&&(this.report(new h(this.server,"disconnect","the server ended its session")),this.connection.invalidate(e))}remoteNameOf(e){return this.known.get(e)}get instructions(){return this.cachedInstructions}refresh(e){return this.queued!==null?this.queued:this.running===null?this.run(e):(this.queued=this.running.then(()=>(this.queued=null,this.run())),this.queued)}run(e){let t=this.refreshOnce(e);return this.running=t,this.runningFor=this.connection.current,t.finally(()=>{this.running===t&&(this.running=null,this.runningFor=null)}),t}async refreshOnce(e){try{return await this.listAndPublish(e)}catch(t){let r=new h(this.server,"refresh",`could not publish its tools: ${f(t)}`,{cause:t});return this.report(r),{ok:!1,error:r}}}async listAndPublish(e){let t=this.connection.current;if(t===null)return{ok:!1,error:new h(this.server,"refresh","not connected")};let r;try{let o=e??AbortSignal.any([this.lifetime.signal,AbortSignal.timeout(this.connectTimeoutMs)]);r=ee(this.config,await Q(t.client,o))}catch(o){let u=new h(this.server,"refresh",`could not list its tools: ${f(o)}`,{cause:o});return this.started&&this.live(t)&&this.report(u),{ok:!1,error:u}}if(!this.live(t))return{ok:!1,error:new h(this.server,"refresh","the listing is out of date")};if(this.config.tools!==void 0&&r.unexposable.length>0&&!this.started)return{ok:!1,error:new h(this.server,"unexposable",j(r.unexposable),{tools:r.unexposable})};let a=this.publish(r),i=this.catalog.unexposable;return a.length>0&&this.config.tools!==void 0&&!this.started?{ok:!1,error:new h(this.server,"unexposable",j(i),{tools:i})}:(this.listedFrom=t.number,ne(i,this.reported)||(this.reported=i,i.length>0&&this.report(new h(this.server,"unexposable",j(i),{tools:i}))),{ok:!0})}live(e){return!this.disposed&&this.ctx.fiber.uid!==null&&e===this.connection.current}publish(e){let t=[];for(let[i,o]of this.published)e.entries.get(i)?.fingerprint!==o.entry.fingerprint&&(this.published.delete(i),o.withdraw());let r=this.ctx,s=this.config.agents;for(let i of e.entries.values()){if(this.published.has(i.name))continue;let o;try{o=W(r,de(this,i),{agents:s})}catch(u){t.push({tool:i.remoteName,reason:`${i.name} cannot be registered: ${f(u)}`});continue}this.published.set(i.name,{entry:i,withdraw:o}),this.known.set(i.name,i.remoteName)}let a=new Map([...e.entries].filter(([i])=>this.published.has(i)));return this.catalog={entries:a,unexposable:L([...e.unexposable,...t])},t}report(e){this.disposed||this.ctx.fiber.uid===null||this.ctx.reportError(e)}async dispose(){this.disposed=!0,await this.connection.dispose(),this.lifetime.abort()}},j=n=>`cannot expose ${n.map(e=>`${e.tool} (${e.reason})`).join("; ")}`;var he=new WeakMap;function Ue(n,e){let t=Fe(n),r=he.get(n.tools);r===void 0&&he.set(n.tools,r=new Map);let s=r.get(t);if(s===void 0&&r.set(t,s=new Set),s.has(e))throw new Error(`Another mcp mount in this layer already uses the server name '${e}'`);let a=s;n.effect(()=>(a.add(e),()=>a.delete(e)))}function He(n,e){if(n.confirm==="all")return"confirm";if(n.confirm!=="none")return n.confirm.except.includes(e)?void 0:"confirm"}var Rt={name:"lagent:mcp",inject:["tools","prompts"],async apply(n,e){let t=k.parse(e);Ue(n,t.name);let r=new M(n,t);n.effect(()=>()=>r.dispose()),await n.plugin(Y,{confirm:s=>{let a=r.remoteNameOf(s);return a!==void 0&&He(t,a)==="confirm"}}),t.instructions&&z(n,{tag:`mcp:${t.name}`,slot:"instruction",agents:t.agents,render:()=>{let s=r.instructions?.trim();return s?`Instructions from the MCP server "${t.name}" about its tools:
@@ -4,7 +4,7 @@ import type { McpConfig } from './config.js';
4
4
  import { type Generation } from './connection.js';
5
5
  import { McpServerError } from './errors.js';
6
6
  import { CallSlots } from './slots.js';
7
- import { type McpToolHost } from './tool.js';
7
+ import { type McpToolHost } from './tools.js';
8
8
  type RefreshOutcome = {
9
9
  readonly ok: true;
10
10
  } | {
@@ -86,7 +86,7 @@ export declare class McpMount implements McpToolHost {
86
86
  /** Whether `generation` is still the live one of a mount that has not been disposed. */
87
87
  private live;
88
88
  /**
89
- * Replaces the published tools with `catalog`'s. Each tool is one `provideTool` effect holding its
89
+ * Replaces the published tools with `catalog`'s. Each tool is one `registerTool` effect holding its
90
90
  * registration and its grant, so withdrawing it releases both. A name another tool in this layer
91
91
  * already holds cannot be registered; that tool is returned as unexposable.
92
92
  */
@@ -1,5 +1,5 @@
1
1
  import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js';
2
- import type { ToolResultPayload } from '../../models/index.js';
2
+ import type { ToolResultPayload } from '../../records/toolResult.js';
3
3
  /** Said when nothing is left for the model because every item was addressed to the user. */
4
4
  export declare const USER_ONLY_OUTPUT = "The tool returned content addressed to the user only; nothing in it is for you.";
5
5
  export declare const EMPTY_OUTPUT = "The tool returned no content.";
@@ -1,5 +1,5 @@
1
1
  import type { Tool } from '../../loop/index.js';
2
- import type { InterruptionPolicy } from '../../models/index.js';
2
+ import type { InterruptionPolicy } from '../../records/journal.js';
3
3
  import type { CatalogEntry } from './catalog.js';
4
4
  import type { McpConfig } from './config.js';
5
5
  import { type Generation } from './connection.js';
@@ -1,5 +1,5 @@
1
1
  import type { Plugin } from '@leuduan/cordis';
2
- import { type ModelRoute } from '../llm/index.js';
2
+ import { type ModelRoute } from '../llm/provider.js';
3
3
  /**
4
4
  * Tells an agent the route it runs on: provider, model and thinking effort.
5
5
  *
@@ -15,7 +15,7 @@ import { type ModelRoute } from '../llm/index.js';
15
15
  * does. Mounted on the root it tells every thread; mounted through `thread.ctx` it tells that thread
16
16
  * only.
17
17
  */
18
- export declare const routeContext: Plugin.Object<undefined>;
18
+ export declare const routeNotice: Plugin.Object<undefined>;
19
19
  /** What a thread is told: its route, and the one it replaces when the model can still see another. */
20
20
  export declare function renderRouteNotice(route: ModelRoute, told: ModelRoute | null): string;
21
21
  /** A route as a model reads it; an effort of `null` is the provider's default. */
@@ -0,0 +1 @@
1
+ import{a,b,c}from"../chunks/OCBPT7KE.js";import"../chunks/6FRNHMCV.js";import"../chunks/CUK7CGC7.js";import"../chunks/BPRCULZH.js";import"../chunks/DDANMY45.js";import"../chunks/BBCW2FZK.js";import"../chunks/MMNNZCBO.js";import"../chunks/G44LG6VL.js";import"../chunks/D4PQP5MA.js";export{c as renderRoute,b as renderRouteNotice,a as routeNotice};