@leuduan/lagent 0.0.0-stage → 0.1.2

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 (327) hide show
  1. package/LICENSE +16 -0
  2. package/README.md +144 -2
  3. package/dist/chunks/2O7ZGEIT.js +1 -0
  4. package/dist/chunks/2OSESBIL.js +1 -0
  5. package/dist/chunks/34KW6VNQ.js +1 -0
  6. package/dist/chunks/37YOGDGY.js +1 -0
  7. package/dist/chunks/3LQHQRIU.js +6 -0
  8. package/dist/chunks/3QCW4WDJ.js +1 -0
  9. package/dist/chunks/4XVRUSCQ.js +1 -0
  10. package/dist/chunks/6ECI2GGV.js +1 -0
  11. package/dist/chunks/74HKUGRR.js +1 -0
  12. package/dist/chunks/ADHERZLW.js +2 -0
  13. package/dist/chunks/AP6Q4EPT.js +36 -0
  14. package/dist/chunks/BM3S37EZ.js +1 -0
  15. package/dist/chunks/C5LYCXJG.js +1 -0
  16. package/dist/chunks/CDQG7RKA.js +1 -0
  17. package/dist/chunks/D7E6EWIE.js +3 -0
  18. package/dist/chunks/DDANMY45.js +3 -0
  19. package/dist/chunks/DRYAN665.js +1 -0
  20. package/dist/chunks/DXFXAYDN.js +17 -0
  21. package/dist/chunks/EGZI4XQX.js +24 -0
  22. package/dist/chunks/ENWFSU27.js +41 -0
  23. package/dist/chunks/G6RXC3AL.js +1 -0
  24. package/dist/chunks/G74AGRAJ.js +15 -0
  25. package/dist/chunks/GQGNVSKB.js +1 -0
  26. package/dist/chunks/IJ2WNMD5.js +7 -0
  27. package/dist/chunks/J5S4URAW.js +1 -0
  28. package/dist/chunks/JPZFKSWT.js +1 -0
  29. package/dist/chunks/KESCTXGO.js +5 -0
  30. package/dist/chunks/L3N4FIEN.js +1 -0
  31. package/dist/chunks/NAOUTU7A.js +4 -0
  32. package/dist/chunks/NDIM7MEW.js +1 -0
  33. package/dist/chunks/O4PPOM5Z.js +2 -0
  34. package/dist/chunks/OVZFGILJ.js +1 -0
  35. package/dist/chunks/P5ZHHOOM.js +6 -0
  36. package/dist/chunks/PUSUPTAT.js +1 -0
  37. package/dist/chunks/QMMLQJBS.js +1 -0
  38. package/dist/chunks/RK3VP2Q4.js +3 -0
  39. package/dist/chunks/SGGMBSBA.js +1 -0
  40. package/dist/chunks/SL2YLB2F.js +1 -0
  41. package/dist/chunks/TOOIB6J2.js +1 -0
  42. package/dist/chunks/TYTQRLTX.js +1 -0
  43. package/dist/chunks/UC3FVVJ2.js +5 -0
  44. package/dist/chunks/UCTEU62F.js +1 -0
  45. package/dist/chunks/UD3VJER6.js +1 -0
  46. package/dist/chunks/UKXMCHHT.js +1 -0
  47. package/dist/chunks/WUUKTSRT.js +7 -0
  48. package/dist/chunks/X65X4KP5.js +7 -0
  49. package/dist/chunks/YIR5MYGU.js +1 -0
  50. package/dist/chunks/YLNJXQ3Z.js +1 -0
  51. package/dist/context.d.ts +101 -0
  52. package/dist/index.d.ts +47 -0
  53. package/dist/index.js +77 -0
  54. package/dist/journal/catalog.d.ts +112 -0
  55. package/dist/journal/forkChain.d.ts +16 -0
  56. package/dist/journal/index.d.ts +15 -0
  57. package/dist/journal/journal.d.ts +475 -0
  58. package/dist/journal/projection.d.ts +87 -0
  59. package/dist/journal/store.d.ts +181 -0
  60. package/dist/kit/claim.d.ts +13 -0
  61. package/dist/kit/drain.d.ts +10 -0
  62. package/dist/kit/extension.d.ts +180 -0
  63. package/dist/kit/grants.d.ts +9 -0
  64. package/dist/kit/modes.d.ts +65 -0
  65. package/dist/kit/retries.d.ts +25 -0
  66. package/dist/kit/scope.d.ts +32 -0
  67. package/dist/kit/service.d.ts +7 -0
  68. package/dist/kit/strategy.d.ts +10 -0
  69. package/dist/kit/timers.d.ts +43 -0
  70. package/dist/kit/tool.d.ts +72 -0
  71. package/dist/llm/client.d.ts +135 -0
  72. package/dist/llm/content.d.ts +52 -0
  73. package/dist/llm/door.d.ts +21 -0
  74. package/dist/llm/door.js +1 -0
  75. package/dist/llm/failure.d.ts +82 -0
  76. package/dist/llm/index.d.ts +16 -0
  77. package/dist/llm/primitives.d.ts +286 -0
  78. package/dist/llm/prompt.d.ts +21 -0
  79. package/dist/llm/provider.d.ts +63 -0
  80. package/dist/llm/readLedger.d.ts +24 -0
  81. package/dist/llm/request.d.ts +58 -0
  82. package/dist/loop/agent.d.ts +134 -0
  83. package/dist/loop/auxiliary.d.ts +54 -0
  84. package/dist/loop/chain.d.ts +46 -0
  85. package/dist/loop/chunks.d.ts +27 -0
  86. package/dist/loop/continuation.d.ts +166 -0
  87. package/dist/loop/decide.d.ts +64 -0
  88. package/dist/loop/errors.d.ts +162 -0
  89. package/dist/loop/forks.d.ts +61 -0
  90. package/dist/loop/holds.d.ts +104 -0
  91. package/dist/loop/hooks.d.ts +241 -0
  92. package/dist/loop/inbox.d.ts +188 -0
  93. package/dist/loop/index.d.ts +37 -0
  94. package/dist/loop/limits.d.ts +14 -0
  95. package/dist/loop/opening.d.ts +42 -0
  96. package/dist/loop/prepare.d.ts +30 -0
  97. package/dist/loop/projections.d.ts +307 -0
  98. package/dist/loop/replace.d.ts +33 -0
  99. package/dist/loop/requests.d.ts +129 -0
  100. package/dist/loop/route.d.ts +53 -0
  101. package/dist/loop/runtime.d.ts +85 -0
  102. package/dist/loop/state.d.ts +70 -0
  103. package/dist/loop/strategy.d.ts +71 -0
  104. package/dist/loop/summary.d.ts +3 -0
  105. package/dist/loop/surface.d.ts +153 -0
  106. package/dist/loop/threadState.d.ts +72 -0
  107. package/dist/loop/tool.d.ts +101 -0
  108. package/dist/loop/toolCalls.d.ts +42 -0
  109. package/dist/loop/wake.d.ts +32 -0
  110. package/dist/models/config/agent.d.ts +18 -0
  111. package/dist/models/config/prompt.d.ts +18 -0
  112. package/dist/models/door.d.ts +12 -0
  113. package/dist/models/door.js +1 -0
  114. package/dist/models/index.d.ts +7 -0
  115. package/dist/models/jsonSchema.d.ts +7 -0
  116. package/dist/models/wire/journal.d.ts +2772 -0
  117. package/dist/models/wire/primitives.d.ts +65 -0
  118. package/dist/plugin.d.ts +53 -0
  119. package/dist/plugin.js +1 -0
  120. package/dist/plugins/agentsMd.d.ts +76 -0
  121. package/dist/plugins/agentsMd.js +1 -0
  122. package/dist/plugins/ask/askQuestion.d.ts +9 -0
  123. package/dist/plugins/ask/index.d.ts +26 -0
  124. package/dist/plugins/ask/index.js +1 -0
  125. package/dist/plugins/ask/service.d.ts +125 -0
  126. package/dist/plugins/commands/background.d.ts +8 -0
  127. package/dist/plugins/commands/foreground.d.ts +4 -0
  128. package/dist/plugins/commands/index.d.ts +40 -0
  129. package/dist/plugins/commands/index.js +1 -0
  130. package/dist/plugins/commands/output.d.ts +115 -0
  131. package/dist/plugins/commands/record.d.ts +549 -0
  132. package/dist/plugins/commands/service.d.ts +314 -0
  133. package/dist/plugins/commands/shell.d.ts +25 -0
  134. package/dist/plugins/compaction/checkpoint.d.ts +91 -0
  135. package/dist/plugins/compaction/config.d.ts +133 -0
  136. package/dist/plugins/compaction/estimate.d.ts +29 -0
  137. package/dist/plugins/compaction/index.d.ts +2 -0
  138. package/dist/plugins/compaction/index.js +7 -0
  139. package/dist/plugins/compaction/log.d.ts +61 -0
  140. package/dist/plugins/compaction/planner.d.ts +207 -0
  141. package/dist/plugins/compaction/preset.d.ts +86 -0
  142. package/dist/plugins/compaction/prune.d.ts +9 -0
  143. package/dist/plugins/compaction/records.d.ts +227 -0
  144. package/dist/plugins/compaction/segments.d.ts +23 -0
  145. package/dist/plugins/compaction/shared.d.ts +14 -0
  146. package/dist/plugins/compaction/summarize.d.ts +13 -0
  147. package/dist/plugins/dateAndBranch.d.ts +47 -0
  148. package/dist/plugins/dateAndBranch.js +1 -0
  149. package/dist/plugins/delegations/answers.d.ts +39 -0
  150. package/dist/plugins/delegations/assignmentKey.d.ts +22 -0
  151. package/dist/plugins/delegations/cleanup.d.ts +161 -0
  152. package/dist/plugins/delegations/constraint.d.ts +76 -0
  153. package/dist/plugins/delegations/index.d.ts +39 -0
  154. package/dist/plugins/delegations/index.js +1 -0
  155. package/dist/plugins/delegations/notices.d.ts +261 -0
  156. package/dist/plugins/delegations/obligations.d.ts +210 -0
  157. package/dist/plugins/delegations/record.d.ts +632 -0
  158. package/dist/plugins/delegations/request.d.ts +381 -0
  159. package/dist/plugins/delegations/role.d.ts +30 -0
  160. package/dist/plugins/delegations/service.d.ts +562 -0
  161. package/dist/plugins/delegations/standing.d.ts +19 -0
  162. package/dist/plugins/delegations/stopCheck.d.ts +21 -0
  163. package/dist/plugins/delegations/testing.d.ts +16 -0
  164. package/dist/plugins/delegations/tools.d.ts +71 -0
  165. package/dist/plugins/delegations/waitBook.d.ts +116 -0
  166. package/dist/plugins/delegations/waits.d.ts +118 -0
  167. package/dist/plugins/diagnostics/digest.d.ts +14 -0
  168. package/dist/plugins/diagnostics/index.d.ts +68 -0
  169. package/dist/plugins/diagnostics/index.js +1 -0
  170. package/dist/plugins/historyRecall/history.d.ts +9 -0
  171. package/dist/plugins/historyRecall/index.d.ts +31 -0
  172. package/dist/plugins/historyRecall/index.js +1 -0
  173. package/dist/plugins/historyRecall/render.d.ts +34 -0
  174. package/dist/plugins/historyRecall/tools.d.ts +4 -0
  175. package/dist/plugins/mcp/catalog.d.ts +36 -0
  176. package/dist/plugins/mcp/config.d.ts +63 -0
  177. package/dist/plugins/mcp/connection.d.ts +53 -0
  178. package/dist/plugins/mcp/errors.d.ts +32 -0
  179. package/dist/plugins/mcp/index.d.ts +33 -0
  180. package/dist/plugins/mcp/index.js +5 -0
  181. package/dist/plugins/mcp/mount.d.ts +98 -0
  182. package/dist/plugins/mcp/names.d.ts +25 -0
  183. package/dist/plugins/mcp/render.d.ts +29 -0
  184. package/dist/plugins/mcp/slots.d.ts +15 -0
  185. package/dist/plugins/mcp/stdio.d.ts +49 -0
  186. package/dist/plugins/mcp/tool.d.ts +41 -0
  187. package/dist/plugins/providers/anthropic.d.ts +175 -0
  188. package/dist/plugins/providers/anthropicMessages.d.ts +65 -0
  189. package/dist/plugins/providers/codex.d.ts +60 -0
  190. package/dist/plugins/providers/codexAuth.d.ts +116 -0
  191. package/dist/plugins/providers/deepseek.d.ts +55 -0
  192. package/dist/plugins/providers/door.d.ts +61 -0
  193. package/dist/plugins/providers/door.js +1 -0
  194. package/dist/plugins/providers/failure.d.ts +23 -0
  195. package/dist/plugins/providers/gateway.d.ts +23 -0
  196. package/dist/plugins/providers/index.d.ts +6 -0
  197. package/dist/plugins/providers/openaiChat.d.ts +62 -0
  198. package/dist/plugins/providers/openaiResponses.d.ts +100 -0
  199. package/dist/plugins/providers/opencodeCopilot.d.ts +23 -0
  200. package/dist/plugins/providers/opencodeGo.d.ts +98 -0
  201. package/dist/plugins/providers/shared.d.ts +104 -0
  202. package/dist/plugins/providers/stream.d.ts +154 -0
  203. package/dist/plugins/routeContext.d.ts +22 -0
  204. package/dist/plugins/routeContext.js +1 -0
  205. package/dist/plugins/schedules/index.d.ts +21 -0
  206. package/dist/plugins/schedules/index.js +5 -0
  207. package/dist/plugins/schedules/record.d.ts +396 -0
  208. package/dist/plugins/schedules/service.d.ts +120 -0
  209. package/dist/plugins/schedules/time.d.ts +26 -0
  210. package/dist/plugins/schedules/tools.d.ts +6 -0
  211. package/dist/plugins/skills/discovery.d.ts +54 -0
  212. package/dist/plugins/skills/index.d.ts +31 -0
  213. package/dist/plugins/skills/index.js +1 -0
  214. package/dist/plugins/skills/tool.d.ts +11 -0
  215. package/dist/plugins/store/durableObject.d.ts +23 -0
  216. package/dist/plugins/store/durableObject.js +1 -0
  217. package/dist/plugins/store/durableObjectConnection.d.ts +27 -0
  218. package/dist/plugins/store/memory.d.ts +29 -0
  219. package/dist/plugins/store/sql.d.ts +59 -0
  220. package/dist/plugins/store/sqlite.d.ts +31 -0
  221. package/dist/plugins/store/sqlite.js +1 -0
  222. package/dist/plugins/subAgents/availableRoutes.d.ts +53 -0
  223. package/dist/plugins/subAgents/fork.d.ts +32 -0
  224. package/dist/plugins/subAgents/index.d.ts +67 -0
  225. package/dist/plugins/subAgents/index.js +1 -0
  226. package/dist/plugins/subAgents/tool.d.ts +38 -0
  227. package/dist/plugins/toolPolicy/index.d.ts +61 -0
  228. package/dist/plugins/toolPolicy/index.js +1 -0
  229. package/dist/plugins/tools/editFiles.d.ts +128 -0
  230. package/dist/plugins/tools/fsRead.d.ts +17 -0
  231. package/dist/plugins/tools/html.d.ts +23 -0
  232. package/dist/plugins/tools/index.d.ts +59 -0
  233. package/dist/plugins/tools/index.js +1 -0
  234. package/dist/plugins/tools/network.d.ts +23 -0
  235. package/dist/plugins/tools/ripgrep.d.ts +20 -0
  236. package/dist/plugins/tools/textEdit.d.ts +67 -0
  237. package/dist/plugins/tools/web.d.ts +32 -0
  238. package/dist/plugins/truncateToolOutput.d.ts +26 -0
  239. package/dist/plugins/truncateToolOutput.js +1 -0
  240. package/dist/plugins/usage/index.d.ts +24 -0
  241. package/dist/plugins/usage/index.js +1 -0
  242. package/dist/plugins/usage/tracker.d.ts +34 -0
  243. package/dist/plugins/verify/facts.d.ts +356 -0
  244. package/dist/plugins/verify/index.d.ts +75 -0
  245. package/dist/plugins/verify/index.js +1 -0
  246. package/dist/plugins/verify/service.d.ts +90 -0
  247. package/dist/plugins/workflows/assignment.d.ts +16 -0
  248. package/dist/plugins/workflows/bindings.d.ts +95 -0
  249. package/dist/plugins/workflows/cleanup.d.ts +38 -0
  250. package/dist/plugins/workflows/definition.d.ts +184 -0
  251. package/dist/plugins/workflows/fold.d.ts +373 -0
  252. package/dist/plugins/workflows/index.d.ts +28 -0
  253. package/dist/plugins/workflows/index.js +6 -0
  254. package/dist/plugins/workflows/observations.d.ts +81 -0
  255. package/dist/plugins/workflows/participants.d.ts +143 -0
  256. package/dist/plugins/workflows/policy.d.ts +112 -0
  257. package/dist/plugins/workflows/providers.d.ts +146 -0
  258. package/dist/plugins/workflows/record.d.ts +2863 -0
  259. package/dist/plugins/workflows/routing.d.ts +116 -0
  260. package/dist/plugins/workflows/schema.d.ts +26 -0
  261. package/dist/plugins/workflows/service.d.ts +477 -0
  262. package/dist/plugins/workflows/submit.d.ts +8 -0
  263. package/dist/plugins/workflows/view.d.ts +103 -0
  264. package/dist/plugins/workflows/work.d.ts +21 -0
  265. package/dist/plugins/workspaceContext.d.ts +38 -0
  266. package/dist/plugins/workspaceContext.js +1 -0
  267. package/dist/presets/agents.d.ts +7 -0
  268. package/dist/presets/base.d.ts +10 -0
  269. package/dist/presets/codex.d.ts +60 -0
  270. package/dist/presets/index.d.ts +4 -0
  271. package/dist/presets/prompts.d.ts +56 -0
  272. package/dist/sandbox/absent.d.ts +32 -0
  273. package/dist/sandbox/client.d.ts +39 -0
  274. package/dist/sandbox/files.d.ts +28 -0
  275. package/dist/sandbox/index.d.ts +49 -0
  276. package/dist/sandbox/index.js +4 -0
  277. package/dist/sandbox/mode.d.ts +57 -0
  278. package/dist/sandbox/policy.d.ts +86 -0
  279. package/dist/sandbox/protocol.d.ts +107 -0
  280. package/dist/sandbox/service.d.ts +143 -0
  281. package/dist/sandbox/worker.d.ts +12 -0
  282. package/dist/sandbox/worker.js +1 -0
  283. package/dist/services/admission.d.ts +174 -0
  284. package/dist/services/agents.d.ts +37 -0
  285. package/dist/services/birth.d.ts +220 -0
  286. package/dist/services/contributions.d.ts +73 -0
  287. package/dist/services/core.d.ts +34 -0
  288. package/dist/services/journal.d.ts +26 -0
  289. package/dist/services/launches.d.ts +104 -0
  290. package/dist/services/llm.d.ts +80 -0
  291. package/dist/services/owner.d.ts +367 -0
  292. package/dist/services/preset.d.ts +154 -0
  293. package/dist/services/presets.d.ts +139 -0
  294. package/dist/services/prompts.d.ts +67 -0
  295. package/dist/services/runEvents.d.ts +79 -0
  296. package/dist/services/thread.d.ts +267 -0
  297. package/dist/services/threadActivation.d.ts +100 -0
  298. package/dist/services/threadDirs.d.ts +38 -0
  299. package/dist/services/threadView.d.ts +92 -0
  300. package/dist/services/threads.d.ts +449 -0
  301. package/dist/services/tools.d.ts +41 -0
  302. package/dist/sys/environment.d.ts +47 -0
  303. package/dist/sys/git.d.ts +60 -0
  304. package/dist/sys/paths.d.ts +56 -0
  305. package/dist/sys/spawn.d.ts +176 -0
  306. package/dist/testing/clock.d.ts +17 -0
  307. package/dist/testing/fakeLlm.d.ts +74 -0
  308. package/dist/testing/fedLlm.d.ts +32 -0
  309. package/dist/testing/helpers.d.ts +344 -0
  310. package/dist/testing/index.d.ts +13 -0
  311. package/dist/testing/index.js +1 -0
  312. package/dist/testing/processes.d.ts +13 -0
  313. package/dist/testing/sandbox.d.ts +71 -0
  314. package/dist/testing/settlement.d.ts +6 -0
  315. package/dist/testing/tmpDirs.d.ts +17 -0
  316. package/dist/util/async.d.ts +8 -0
  317. package/dist/util/diff.d.ts +25 -0
  318. package/dist/util/dispatch.d.ts +8 -0
  319. package/dist/util/errors.d.ts +28 -0
  320. package/dist/util/foldState.d.ts +17 -0
  321. package/dist/util/freeze.d.ts +2 -0
  322. package/dist/util/ids.d.ts +2 -0
  323. package/dist/util/json.d.ts +37 -0
  324. package/dist/util/log.d.ts +6 -0
  325. package/dist/util/text.d.ts +21 -0
  326. package/dist/util/version.d.ts +2 -0
  327. package/package.json +175 -3
@@ -0,0 +1,32 @@
1
+ /**
2
+ * What an `mcp` mount reports. A rejected mount throws one, and every `ctx.reportError` raises one,
3
+ * so a host filters them from Cordis `internal/error` by class and `kind`. Named apart from the
4
+ * SDK's own `McpError`, which is a protocol error.
5
+ */
6
+ export type McpServerErrorKind =
7
+ /** A mount or reconnection that could not connect or initialize. */
8
+ 'connect'
9
+ /** A listing that failed; the last complete catalog stays published. */
10
+ | 'refresh'
11
+ /** Tools left out, each with its reason. */
12
+ | 'unexposable'
13
+ /** A connection that went away. */
14
+ | 'disconnect';
15
+ /** A remote tool that cannot be exposed, and why. */
16
+ export type UnexposableTool = {
17
+ readonly tool: string;
18
+ readonly reason: string;
19
+ };
20
+ export declare class McpServerError extends Error {
21
+ readonly name = "McpServerError";
22
+ readonly server: string;
23
+ readonly kind: McpServerErrorKind;
24
+ /** Set for `unexposable`. */
25
+ readonly tools: readonly UnexposableTool[];
26
+ constructor(server: string, kind: McpServerErrorKind, message: string, options?: {
27
+ cause?: unknown;
28
+ tools?: readonly UnexposableTool[];
29
+ });
30
+ }
31
+ /** A reason in one line, for messages and results. */
32
+ export declare const describeError: (error: unknown) => string;
@@ -0,0 +1,33 @@
1
+ import { type Plugin } from '@leuduan/cordis';
2
+ import { type McpConfigInput } from './config.js';
3
+ export { MAX_SERVER_NAME_LENGTH, McpConfigSchema, McpTransportSchema } from './config.js';
4
+ export type { McpConfig, McpConfigInput, McpTransportConfig, McpTransportFactory } from './config.js';
5
+ export { McpServerError } from './errors.js';
6
+ export type { McpServerErrorKind, UnexposableTool } from './errors.js';
7
+ export { MAX_TOOL_NAME_LENGTH, mcpToolName } from './names.js';
8
+ export { CALL_META_KEY, SESSION_RESET_NOTE } from './tool.js';
9
+ /**
10
+ * Connects to one MCP server and exposes its tools as ordinary lagent tools named
11
+ * `mcp__<server>__<tool>`, granted to `agents`. One mount is one server: a server that cannot be
12
+ * reached, or a tool listed in `tools` that cannot be exposed, rejects the mount with an
13
+ * `McpServerError` and leaves nothing registered. Tools found by discovery that cannot be exposed,
14
+ * a refresh that fails and a connection that goes away are reported through `ctx.reportError`.
15
+ *
16
+ * The plugin mounts no service, so the same mount works on the root, where one connection serves
17
+ * every thread, through `thread.ctx`, or inside a host preset. A failed mount stays in its owner's
18
+ * tree: an optional server is disposed when it fails, or a thread activation never becomes ready.
19
+ *
20
+ * ```ts
21
+ * await root.plugin(mcp, {
22
+ * name: 'docs',
23
+ * transport: { kind: 'stdio', command: ['node', 'server.js'], cwd: '/srv/docs', env: { PATH: '/usr/bin' } },
24
+ * agents: ['main'],
25
+ * confirm: 'all',
26
+ * onInterrupted: 'report',
27
+ * maxConcurrentCalls: 1,
28
+ * })
29
+ * ```
30
+ *
31
+ * The design and its reasons are in `docs/mcp.md`.
32
+ */
33
+ export declare const mcp: Plugin.Object<McpConfigInput>;
@@ -0,0 +1,5 @@
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:
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
+ ${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
+ `)||(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:
5
+ ${s}`:null}}),await r.start()}};export{ue as CALL_META_KEY,D as MAX_SERVER_NAME_LENGTH,S as MAX_TOOL_NAME_LENGTH,k as McpConfigSchema,h as McpServerError,X as McpTransportSchema,R as SESSION_RESET_NOTE,Rt as mcp,O as mcpToolName};
@@ -0,0 +1,98 @@
1
+ import type { Context } from '@leuduan/cordis';
2
+ import { type CatalogEntry } from './catalog.js';
3
+ import type { McpConfig } from './config.js';
4
+ import { type Generation } from './connection.js';
5
+ import { McpServerError } from './errors.js';
6
+ import { CallSlots } from './slots.js';
7
+ import { type McpToolHost } from './tool.js';
8
+ type RefreshOutcome = {
9
+ readonly ok: true;
10
+ } | {
11
+ readonly ok: false;
12
+ readonly error: McpServerError;
13
+ };
14
+ /**
15
+ * One server's mount: its connection, its catalog, and the tools published from it.
16
+ *
17
+ * Refreshes are serialized: one runs at a time and at most one more waits, shared by everyone who
18
+ * asks meanwhile, so a burst of `list_changed` notifications never overlaps listings and the latest
19
+ * one wins. A refresh publishes only a complete listing, only for the generation it listed from,
20
+ * and only while the mount lives; a failed one keeps the last catalog. Reconnection is lazy and
21
+ * single-flight: the next call opens a new generation and refreshes before it is sent.
22
+ */
23
+ export declare class McpMount implements McpToolHost {
24
+ readonly server: string;
25
+ readonly slots: CallSlots;
26
+ private readonly connection;
27
+ private readonly lifetime;
28
+ private catalog;
29
+ /** The generation the published catalog was listed from; calls never run against another's. */
30
+ private listedFrom;
31
+ private readonly published;
32
+ /** Every lagent name this mount ever published, with its remote name, for the confirmation vote. */
33
+ private readonly known;
34
+ private reported;
35
+ private started;
36
+ /** A `list_changed` arrived before the first listing finished, which may have missed it. */
37
+ private changedWhileStarting;
38
+ /** The generation the running refresh lists from, for a call to join instead of queueing another. */
39
+ private runningFor;
40
+ private disposed;
41
+ private running;
42
+ private queued;
43
+ private reconnecting;
44
+ /** The generation whose first result still owes the session-reset note. */
45
+ private noteOwedTo;
46
+ /** The instructions of the latest successful initialization, kept through an outage. */
47
+ private cachedInstructions;
48
+ private readonly ctx;
49
+ readonly config: McpConfig;
50
+ constructor(ctx: Context, config: McpConfig);
51
+ private get connectTimeoutMs();
52
+ /**
53
+ * Connects, lists every tool, and publishes them. Rejects, having published nothing, when the
54
+ * server cannot be reached or initialized, its listing fails, or a tool the host listed cannot be
55
+ * exposed.
56
+ */
57
+ start(): Promise<void>;
58
+ /**
59
+ * The live generation, with a catalog listed from it. A generation that went away is replaced
60
+ * once, single-flight; a catalog listed from another generation, after a reconnection whose
61
+ * listing failed, is listed again first. Either failing fails the call before it is sent.
62
+ */
63
+ ready(signal: AbortSignal): Promise<Generation>;
64
+ /** Opens a new generation. Listing its tools is `ready`'s, so a failed listing is retried by the next call. */
65
+ private reconnect;
66
+ entry(name: string): CatalogEntry | undefined;
67
+ takeSessionNote(generation: Generation): string | null;
68
+ invalidate(generation: Generation): void;
69
+ /** The remote name behind a lagent name this mount published at any time, for the confirmation vote. */
70
+ remoteNameOf(name: string): string | undefined;
71
+ /**
72
+ * The server's `initialize` instructions, from the latest successful initialization. Kept through
73
+ * an outage, so a prompt rendered while the server is unreachable still carries them.
74
+ */
75
+ get instructions(): string | null;
76
+ /**
77
+ * Lists again, serialized with every other refresh; the latest request always wins. `signal`
78
+ * bounds the listing when this call starts one; joining one already running or queued keeps its
79
+ * bound.
80
+ */
81
+ refresh(signal?: AbortSignal): Promise<RefreshOutcome>;
82
+ private run;
83
+ /** Never rejects: both callers, a notification and the queue, would leave a rejection unhandled. */
84
+ private refreshOnce;
85
+ private listAndPublish;
86
+ /** Whether `generation` is still the live one of a mount that has not been disposed. */
87
+ private live;
88
+ /**
89
+ * Replaces the published tools with `catalog`'s. Each tool is one `provideTool` effect holding its
90
+ * registration and its grant, so withdrawing it releases both. A name another tool in this layer
91
+ * already holds cannot be registered; that tool is returned as unexposable.
92
+ */
93
+ private publish;
94
+ private report;
95
+ /** Closes the connection; the published tools go with the mount's other effects. */
96
+ dispose(): Promise<void>;
97
+ }
98
+ export {};
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Lagent names for MCP tools: `mcp__<server>__<tool>`. The MCP spec allows `A-Z a-z 0-9 _ - .` and
3
+ * up to 128 characters in a tool name; OpenAI function names allow `A-Z a-z 0-9 _ -` and at most 64.
4
+ * A remote name is mapped onto the narrower set, never truncated or hashed: the model, the journal
5
+ * and the policy lists all read it, so it must stay readable and identical across restarts.
6
+ */
7
+ /** The longest tool name every supported provider accepts. */
8
+ export declare const MAX_TOOL_NAME_LENGTH = 64;
9
+ /**
10
+ * A server name: in the narrow set already, never containing `__`, and neither starting nor ending
11
+ * with `_`. The first `__` after `mcp__` then always ends the server name, so two servers can never
12
+ * map tools onto the same lagent name: `docs` with `_search` and `docs_` with `search` would both
13
+ * be `mcp__docs___search`.
14
+ */
15
+ export declare const SERVER_NAME: RegExp;
16
+ /** An alias for a tool segment, which must already be in the narrow set. */
17
+ export declare const TOOL_SEGMENT: RegExp;
18
+ /** The tool segment a remote name maps to: every character outside the narrow set becomes `_`. */
19
+ export declare const toolSegment: (remoteName: string) => string;
20
+ /**
21
+ * The lagent name of a server's tool, for a tool policy's lists and host UIs. `alias`
22
+ * replaces the tool segment only; the server prefix always applies, so an alias never lands on a
23
+ * builtin. The result may be longer than {@link MAX_TOOL_NAME_LENGTH}, which makes it unexposable.
24
+ */
25
+ export declare const mcpToolName: (server: string, remoteName: string, alias?: string) => string;
@@ -0,0 +1,29 @@
1
+ import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js';
2
+ import type { ToolResultPayload } from '../../models/index.js';
3
+ /** Said when nothing is left for the model because every item was addressed to the user. */
4
+ export declare const USER_ONLY_OUTPUT = "The tool returned content addressed to the user only; nothing in it is for you.";
5
+ export declare const EMPTY_OUTPUT = "The tool returned no content.";
6
+ /**
7
+ * The image types every provider lagent supports accepts as input: OpenAI takes PNG, JPEG, WebP
8
+ * and non-animated GIF. A part in any other type would be refused, and since the journal keeps it,
9
+ * every later request in the thread would be refused with it.
10
+ */
11
+ export declare const MODEL_IMAGE_TYPES: ReadonlySet<string>;
12
+ /** A MIME type as a part stores it: lowercased, and the common `image/jpg` as `image/jpeg`. */
13
+ export declare const imageMediaType: (mimeType: string) => string;
14
+ export type RenderOptions = {
15
+ readonly server: string;
16
+ readonly remoteName: string;
17
+ /** The most decoded bytes of non-text content the result keeps, for the model and the host. */
18
+ readonly maxContentBytes: number;
19
+ };
20
+ /**
21
+ * Renders a `tools/call` result as lagent's text-first payload. `output` is the canonical text;
22
+ * images become content parts within the byte budget; items whose audience excludes the assistant
23
+ * go to `metadata` for hosts and never reach the model. A result is not checked against the tool's
24
+ * output schema.
25
+ */
26
+ export declare function renderCallResult(result: CallToolResult, options: RenderOptions): ToolResultPayload;
27
+ /** The size of base64 data once decoded. */
28
+ export declare function decodedBytes(base64: string): number;
29
+ export declare function formatBytes(bytes: number): string;
@@ -0,0 +1,15 @@
1
+ /**
2
+ * The calls one server takes at once, in arrival order, shared by every thread its mount serves.
3
+ * A waiter whose signal aborts leaves the queue without ever holding a slot.
4
+ */
5
+ export declare class CallSlots {
6
+ private active;
7
+ private readonly waiters;
8
+ private readonly limit;
9
+ constructor(limit: number);
10
+ /** Resolves with the slot's release; rejects with the signal's reason if it aborts first. */
11
+ acquire(signal: AbortSignal): Promise<() => void>;
12
+ /** Calls queued for a slot. */
13
+ get waiting(): number;
14
+ private releaser;
15
+ }
@@ -0,0 +1,49 @@
1
+ import type { Transport } from '@modelcontextprotocol/sdk/shared/transport.js';
2
+ import type { JSONRPCMessage } from '@modelcontextprotocol/sdk/types.js';
3
+ import { type SpawnResult } from '../../sys/spawn.js';
4
+ export type StdioServerOptions = {
5
+ readonly server: string;
6
+ readonly command: readonly [string, ...string[]];
7
+ readonly cwd: string;
8
+ readonly env: Readonly<Record<string, string>>;
9
+ /** The owner: aborting it stops the server's process group within the bound. */
10
+ readonly signal: AbortSignal;
11
+ readonly killGraceMs?: number;
12
+ };
13
+ /**
14
+ * The SDK's `Transport` over a stdio server spawned through `sys/spawn`, so the server and
15
+ * everything it starts lead a process group that never outlives lagent. The SDK's own stdio
16
+ * transport spawns outside that containment.
17
+ *
18
+ * stdout carries newline-delimited JSON-RPC and nothing else. stderr is diagnostics: it is read
19
+ * from the start, since an unread pipe would block the server, and only a bounded tail is kept,
20
+ * for the host's errors and the debug log.
21
+ */
22
+ export declare class ContainedStdioTransport implements Transport {
23
+ onclose?: () => void;
24
+ onerror?: (error: Error) => void;
25
+ onmessage?: <T extends JSONRPCMessage>(message: T) => void;
26
+ private spawned;
27
+ private readonly buffer;
28
+ private stderr;
29
+ private exit;
30
+ private closed;
31
+ /** `close` came before the process existed: the process is stopped as soon as it does. */
32
+ private closedEarly;
33
+ private readonly options;
34
+ constructor(options: StdioServerOptions);
35
+ /** The server's pid, which is also its process group's id, once started. */
36
+ get pid(): number | undefined;
37
+ /** The last of what the server wrote to stderr. */
38
+ get stderrTail(): string;
39
+ /** How the server's process ended, once it has. */
40
+ get exited(): SpawnResult | null;
41
+ start(): Promise<void>;
42
+ private receive;
43
+ send(message: JSONRPCMessage): Promise<void>;
44
+ /**
45
+ * The spec's stdio shutdown: close the server's input, give it one grace period to exit, then
46
+ * stop its whole group, SIGTERM then SIGKILL, within `sys/spawn`'s bound.
47
+ */
48
+ close(): Promise<void>;
49
+ }
@@ -0,0 +1,41 @@
1
+ import type { Tool } from '../../loop/index.js';
2
+ import type { InterruptionPolicy } from '../../models/index.js';
3
+ import type { CatalogEntry } from './catalog.js';
4
+ import type { McpConfig } from './config.js';
5
+ import { type Generation } from './connection.js';
6
+ import type { CallSlots } from './slots.js';
7
+ /**
8
+ * The `_meta` key carrying a call's durable identity: the thread id, an opaque identifier with no
9
+ * meaning outside lagent's journal, and the `tool/call` sequence. Stable across a re-dispatch after
10
+ * a crash, so a server that chooses to can deduplicate; servers that do not know it ignore it.
11
+ */
12
+ export declare const CALL_META_KEY = "work.leuduan.lagent/call";
13
+ /** Told with the first result after a new session. */
14
+ export declare const SESSION_RESET_NOTE = "The connection to this MCP server was re-established; any session state the server held may have been reset.";
15
+ /** What a tool needs from the mount that published it. */
16
+ export interface McpToolHost {
17
+ readonly server: string;
18
+ readonly config: Pick<McpConfig, 'maxCallSeconds' | 'callTimeoutSeconds' | 'maxContentBytes' | 'onInterrupted'>;
19
+ readonly slots: CallSlots;
20
+ /** The live generation, reconnecting once first if the last one went away. */
21
+ ready(signal: AbortSignal): Promise<Generation>;
22
+ /** The current catalog's entry under a lagent name. */
23
+ entry(name: string): CatalogEntry | undefined;
24
+ /** The note owed to the first result of `generation`, once. */
25
+ takeSessionNote(generation: Generation): string | null;
26
+ /** Ends a generation whose session the server no longer has. */
27
+ invalidate(generation: Generation): void;
28
+ }
29
+ /**
30
+ * What a re-dispatch may do with a call to `entry` after an interruption, by the mount's
31
+ * `onInterrupted`: `'report'` for every tool, the listed remote names for `{ rerun }`, and for
32
+ * `'annotations'` the server's own `readOnlyHint` or `idempotentHint`, trusted only because the
33
+ * mount asked for that.
34
+ */
35
+ export declare function interruptionPolicyOf(onInterrupted: McpConfig['onInterrupted'], entry: Pick<CatalogEntry, 'remoteName' | 'definition'>): InterruptionPolicy;
36
+ /**
37
+ * One MCP tool as a lagent tool, bound to the definition it was published with. Arguments go to
38
+ * the server unchanged: validating them is the server's job. The mount's `onInterrupted` decides
39
+ * what a re-dispatch may do; the server's annotations count only when the mount says so.
40
+ */
41
+ export declare const mcpTool: (host: McpToolHost, entry: CatalogEntry) => Tool;
@@ -0,0 +1,175 @@
1
+ import type { ContentPart, ConversationMessage, FailureClassification, JsonObject, LLMStreamChunk, ModelResponse, ResponseFinish, ThinkingEffort, ToolChoice, ToolSpec } from '../../llm/index.js';
2
+ import type { DeepReadonly } from '../../util/json.js';
3
+ /** One Messages content block, as JSON. */
4
+ export type AnthropicBlock = Record<string, unknown>;
5
+ /** One Messages turn. Consecutive messages of one role are one turn. */
6
+ export type AnthropicMessage = {
7
+ role: 'user' | 'assistant';
8
+ content: AnthropicBlock[];
9
+ };
10
+ /**
11
+ * A call id as Messages accepts it: an id already in its alphabet as it is, any other (another
12
+ * provider's, such as Responses' `call_…|fc_…`) as a digest of itself. Deterministic, so a call and
13
+ * its result agree; never reversed, since only ids Messages wrote come back.
14
+ */
15
+ export declare const anthropicToolUseId: (id: string) => string;
16
+ /**
17
+ * The state an assistant message keeps for replay: its message id, and its thinking blocks with
18
+ * their signatures, which the API verifies and which only the model that wrote them can read.
19
+ */
20
+ export type AnthropicReplayState = {
21
+ id: string;
22
+ thinking: AnthropicBlock[];
23
+ };
24
+ /**
25
+ * A request's conversation as Messages turns.
26
+ *
27
+ * - A `tool` message is a `tool_result` block in the next user turn, and results lead their turn,
28
+ * as the API requires.
29
+ * - A `developer` or `system` message is user text inside `<system-reminder>`: Messages has no role
30
+ * for a notice in the conversation.
31
+ * - An assistant message replays its thinking first, from state `replayTag` wrote; another model's
32
+ * is dropped. A malformed tool call goes back with empty input, since Messages takes an object.
33
+ * - Empty text is dropped (the API refuses it), and a message left with nothing is dropped too.
34
+ */
35
+ export declare function toAnthropicMessages(messages: readonly DeepReadonly<ConversationMessage>[], options: {
36
+ readonly provider: string;
37
+ readonly replayTag: string;
38
+ }): AnthropicMessage[];
39
+ /**
40
+ * Content parts as Messages blocks: images by URL or base64, files as documents (a PDF by URL or
41
+ * base64, plain text inline). A file the provider holds by id is refused: that is another API's
42
+ * upload, which Messages cannot name.
43
+ */
44
+ export declare function contentBlocks(content: readonly DeepReadonly<ContentPart>[], provider: string): AnthropicBlock[];
45
+ /** Tool specs as Messages tools; the schema goes as it stands. */
46
+ export declare const toAnthropicTools: (tools: readonly DeepReadonly<ToolSpec>[]) => AnthropicBlock[];
47
+ /** A request's tool choice, with parallel calls off when the request says so. */
48
+ export declare function toAnthropicToolChoice(choice: DeepReadonly<ToolChoice>, parallel: boolean): AnthropicBlock;
49
+ /**
50
+ * The thinking fields for an effort: none sent for none named, so the model's own default stands;
51
+ * `none` disables thinking; any other is adaptive thinking at that effort, with its text summarized,
52
+ * since some models omit thinking text unless asked.
53
+ */
54
+ export declare function anthropicThinking(effort: ThinkingEffort | undefined): JsonObject;
55
+ /** One raw Messages stream event, as the API streams it. Only the fields read here are typed. */
56
+ export type AnthropicStreamEvent = {
57
+ type: 'message_start';
58
+ message: {
59
+ id: string;
60
+ model: string;
61
+ usage?: RawUsage;
62
+ };
63
+ } | {
64
+ type: 'content_block_start';
65
+ index: number;
66
+ content_block: AnthropicBlock;
67
+ } | {
68
+ type: 'content_block_delta';
69
+ index: number;
70
+ delta: AnthropicBlock;
71
+ } | {
72
+ type: 'content_block_stop';
73
+ index: number;
74
+ } | {
75
+ type: 'message_delta';
76
+ delta: {
77
+ stop_reason?: string | null;
78
+ stop_sequence?: string | null;
79
+ };
80
+ usage?: RawUsage;
81
+ } | {
82
+ type: 'message_stop';
83
+ } | {
84
+ type: 'ping';
85
+ } | {
86
+ type: 'error';
87
+ error: {
88
+ type?: string;
89
+ message?: string;
90
+ };
91
+ };
92
+ type RawUsage = {
93
+ input_tokens?: number | null;
94
+ output_tokens?: number | null;
95
+ cache_read_input_tokens?: number | null;
96
+ cache_creation_input_tokens?: number | null;
97
+ output_tokens_details?: {
98
+ thinking_tokens?: number | null;
99
+ } | null;
100
+ };
101
+ /** A failure the API reported, from a rejected request (with its status) or an `error` stream event. */
102
+ export declare class AnthropicAPIError extends Error {
103
+ readonly errorType: string | undefined;
104
+ readonly status?: number;
105
+ readonly headers?: Headers;
106
+ constructor(
107
+ /** The API's error type, such as `overloaded_error`. */
108
+ errorType: string | undefined, message: string,
109
+ /** The HTTP status of a rejected request; absent for a failure inside the stream. */
110
+ status?: number, headers?: Headers);
111
+ }
112
+ /**
113
+ * Whether a failure says the request exceeded the model's context window. The API names no code of
114
+ * its own for it, only `invalid_request_error`, so its wording decides, as `adapters.md` allows
115
+ * where a provider has no code: "prompt is too long", which a gateway may wrap in its own prose.
116
+ */
117
+ export declare const isAnthropicOverflow: (error: AnthropicAPIError) => boolean;
118
+ /**
119
+ * The kind of a failure from a Messages client, by structured evidence only: the API's error type
120
+ * where it names a kind (a `billing_error` is `quota` whatever status carries it), else the HTTP
121
+ * status as every protocol reads one (`statusKind`, 529 being Anthropic's overloaded). A failure
122
+ * inside the stream has no status, so its type is all there is; else socket codes.
123
+ * `retryAfterMs` comes from the `retry-after-ms` or `retry-after` header.
124
+ */
125
+ export declare function classifyAnthropicFailure(error: unknown, now?: number): FailureClassification;
126
+ /** `end_turn`, `tool_use` and `stop_sequence` finish a message; the output cap and window are `length`. */
127
+ export declare const anthropicFinish: (stopReason: string) => ResponseFinish;
128
+ export interface MessagesAssemblyOptions {
129
+ /** The tag the message's state is written under, which replays it. */
130
+ readonly replayTag: string;
131
+ /** The name a tool call reaches lagent under, from the name the model used. */
132
+ readonly toolName?: (name: string) => string;
133
+ }
134
+ /**
135
+ * One streamed Messages message, folded event by event. It owns the rule that a message is complete
136
+ * only once its stop reason arrived and `message_stop` followed, and hands back what arrived for a
137
+ * cut-off one: text and reasoning, never a tool call or state.
138
+ */
139
+ export declare class MessagesAssembly {
140
+ private id;
141
+ private model;
142
+ private readonly blocks;
143
+ private stopReason;
144
+ private stopSequence;
145
+ private stopped;
146
+ private usage;
147
+ private readonly options;
148
+ constructor(options: MessagesAssemblyOptions);
149
+ /** Folds one event and returns the chunk it adds, if any. An `error` event throws. */
150
+ apply(event: AnthropicStreamEvent): LLMStreamChunk | null;
151
+ /** Whether the message is complete: its stop reason arrived, and `message_stop` after it. */
152
+ get complete(): boolean;
153
+ /** The message's stop reason, once one arrived. */
154
+ get stop(): string | null;
155
+ private applyDelta;
156
+ private addUsage;
157
+ /**
158
+ * Usage as lagent counts it: Anthropic's `input_tokens` excludes the cached ones, so input is the
159
+ * sum of uncached, cache-read and cache-written tokens, with the cached ones also kept apart.
160
+ */
161
+ private normalizedUsage;
162
+ private ordered;
163
+ private text;
164
+ private reasoning;
165
+ /** What the message says about itself: observed, never sent back. */
166
+ metadata(): JsonObject;
167
+ /** The settled message, once complete; `undefined` before. */
168
+ settle(): ModelResponse | undefined;
169
+ /** What arrived so far: text and reasoning, never a tool call nobody finished asking for. */
170
+ partial(): {
171
+ message: ConversationMessage;
172
+ providerMetadata: JsonObject;
173
+ };
174
+ }
175
+ export {};
@@ -0,0 +1,65 @@
1
+ import { z } from 'zod';
2
+ import type { LLMClient, ModelRequest, StreamingLLMResponse } from '../../llm/index.js';
3
+ import { type AnthropicStreamEvent } from './anthropic.js';
4
+ import { type CallHeaders } from './stream.js';
5
+ declare const AnthropicMessagesConfigSchema: z.ZodObject<{
6
+ apiKey: z.ZodOptional<z.ZodString>;
7
+ baseURL: z.ZodString;
8
+ streamIdleTimeoutMs: z.ZodNullable<z.ZodNumber>;
9
+ authorization: z.ZodDefault<z.ZodEnum<{
10
+ "x-api-key": "x-api-key";
11
+ bearer: "bearer";
12
+ }>>;
13
+ defaultHeaders: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
14
+ thinkingEffort: z.ZodOptional<z.ZodEnum<{
15
+ low: "low";
16
+ high: "high";
17
+ none: "none";
18
+ medium: "medium";
19
+ max: "max";
20
+ }>>;
21
+ maxOutputTokens: z.ZodRecord<z.ZodString, z.ZodNumber>;
22
+ }, z.core.$strip>;
23
+ type AnthropicMessagesConfig = z.input<typeof AnthropicMessagesConfigSchema>;
24
+ type ParsedConfig = z.output<typeof AnthropicMessagesConfigSchema>;
25
+ type RequestPayload = Record<string, unknown>;
26
+ /**
27
+ * The Anthropic Messages adapter for a provider whose models answer on Messages (Go or Copilot),
28
+ * which names itself as `name`. It speaks over `fetch` with no SDK: the request goes as
29
+ * JSON and the server-sent events are read as they arrive, so nothing reads the process environment.
30
+ * `headers` adds headers to each call, over the client's own; it is the client's owner's, and
31
+ * nothing subclasses the client to say it.
32
+ *
33
+ * The prompt goes as `system` blocks, notices as user text, and thinking replays from
34
+ * `provider_state` to the model that wrote it. Provider-executed tools and non-text response
35
+ * formats are refused.
36
+ */
37
+ export declare class AnthropicMessagesLLMClient implements LLMClient {
38
+ readonly providerName: string;
39
+ protected readonly config: ParsedConfig;
40
+ private readonly fetchImpl;
41
+ private readonly callHeaders;
42
+ constructor(config: AnthropicMessagesConfig & {
43
+ name: string;
44
+ headers?: CallHeaders;
45
+ fetch?: typeof globalThis.fetch;
46
+ });
47
+ /** The tag replayable state is written and read under: one model's signed thinking is no other's. */
48
+ private replayTag;
49
+ /** The output cap of a request: its own, else the one configured for its model. */
50
+ private maxOutputTokens;
51
+ /** The headers of one call: the client's own, then the owner's for this call and its mapped request. */
52
+ private headers;
53
+ buildRequest(call: ModelRequest): RequestPayload;
54
+ chat(call: ModelRequest): Promise<StreamingLLMResponse>;
55
+ private open;
56
+ /** `error` as the overflow it is, when its fields say so, else unchanged. */
57
+ classified(error: unknown): unknown;
58
+ }
59
+ /**
60
+ * The events of a server-sent event stream, each `data` payload parsed as JSON. Lines end in CR, LF
61
+ * or CRLF, as the format allows; a CR at the end of a chunk waits for the next, which may bring its
62
+ * LF. The payload's own `type` names the event, so `event:` lines, ids and comments are not read.
63
+ */
64
+ export declare function serverSentEvents(body: AsyncIterable<Uint8Array>): AsyncGenerator<AnthropicStreamEvent>;
65
+ export {};