@leuduan/lagent 0.0.0-stage → 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 (328) hide show
  1. package/LICENSE +16 -0
  2. package/README.md +157 -2
  3. package/dist/chunks/2GCIWSOA.js +5 -0
  4. package/dist/chunks/2P47AHNK.js +7 -0
  5. package/dist/chunks/34KW6VNQ.js +1 -0
  6. package/dist/chunks/3UMZMPWW.js +1 -0
  7. package/dist/chunks/5IRF47YB.js +1 -0
  8. package/dist/chunks/6DRCKZ2C.js +1 -0
  9. package/dist/chunks/6FRNHMCV.js +1 -0
  10. package/dist/chunks/7LI64H5X.js +17 -0
  11. package/dist/chunks/7VAPNE3L.js +1 -0
  12. package/dist/chunks/ASSQZH3F.js +1 -0
  13. package/dist/chunks/B4FXK5ER.js +77 -0
  14. package/dist/chunks/BBCW2FZK.js +1 -0
  15. package/dist/chunks/BPRCULZH.js +1 -0
  16. package/dist/chunks/CANPZYTH.js +24 -0
  17. package/dist/chunks/CQEVREBT.js +1 -0
  18. package/dist/chunks/CUK7CGC7.js +1 -0
  19. package/dist/chunks/D4PQP5MA.js +3 -0
  20. package/dist/chunks/DDANMY45.js +3 -0
  21. package/dist/chunks/DDZ7YF26.js +1 -0
  22. package/dist/chunks/EMRB4KCN.js +6 -0
  23. package/dist/chunks/EPYQ5M3B.js +3 -0
  24. package/dist/chunks/FJLU4UH3.js +1 -0
  25. package/dist/chunks/G44LG6VL.js +1 -0
  26. package/dist/chunks/GGSVIIWJ.js +2 -0
  27. package/dist/chunks/HK6ZSONF.js +1 -0
  28. package/dist/chunks/IAAEP6VL.js +30 -0
  29. package/dist/chunks/JCTBX33H.js +36 -0
  30. package/dist/chunks/JFX2MXBA.js +4 -0
  31. package/dist/chunks/JFZZXVWD.js +15 -0
  32. package/dist/chunks/KUZCL2SH.js +1 -0
  33. package/dist/chunks/MHC6VPB4.js +7 -0
  34. package/dist/chunks/MMNNZCBO.js +5 -0
  35. package/dist/chunks/MNJ4SRF7.js +1 -0
  36. package/dist/chunks/N6IXG2VL.js +1 -0
  37. package/dist/chunks/OCBPT7KE.js +1 -0
  38. package/dist/chunks/OL5A6ITQ.js +1 -0
  39. package/dist/chunks/PUSUPTAT.js +1 -0
  40. package/dist/chunks/Q75FUN7D.js +2 -0
  41. package/dist/chunks/Q7S5LFGN.js +1 -0
  42. package/dist/chunks/RCIHV3KG.js +1 -0
  43. package/dist/chunks/S34ZA2R6.js +1 -0
  44. package/dist/chunks/SS3B5W34.js +12 -0
  45. package/dist/chunks/VYMT4TXD.js +1 -0
  46. package/dist/chunks/W57RW55W.js +1 -0
  47. package/dist/compositions/base.d.ts +11 -0
  48. package/dist/compositions/codex.d.ts +66 -0
  49. package/dist/compositions/codexPrompts.d.ts +56 -0
  50. package/dist/context.d.ts +109 -0
  51. package/dist/index.d.ts +55 -0
  52. package/dist/index.js +1 -0
  53. package/dist/journal/catalog.d.ts +112 -0
  54. package/dist/journal/forkChain.d.ts +16 -0
  55. package/dist/journal/index.d.ts +15 -0
  56. package/dist/journal/journal.d.ts +475 -0
  57. package/dist/journal/projection.d.ts +87 -0
  58. package/dist/journal/store.d.ts +181 -0
  59. package/dist/llm/client.d.ts +135 -0
  60. package/dist/llm/content.d.ts +52 -0
  61. package/dist/llm/failure.d.ts +82 -0
  62. package/dist/llm/index.d.ts +22 -0
  63. package/dist/llm/index.js +1 -0
  64. package/dist/llm/primitives.d.ts +286 -0
  65. package/dist/llm/prompt.d.ts +21 -0
  66. package/dist/llm/provider.d.ts +74 -0
  67. package/dist/llm/readLedger.d.ts +24 -0
  68. package/dist/llm/request.d.ts +58 -0
  69. package/dist/loop/agent.d.ts +18 -0
  70. package/dist/loop/authorization.d.ts +41 -0
  71. package/dist/loop/auxiliary.d.ts +58 -0
  72. package/dist/loop/chunks.d.ts +27 -0
  73. package/dist/loop/completion.d.ts +17 -0
  74. package/dist/loop/errors.d.ts +139 -0
  75. package/dist/loop/hooks.d.ts +274 -0
  76. package/dist/loop/index.d.ts +16 -0
  77. package/dist/loop/runner.d.ts +134 -0
  78. package/dist/loop/runtime.d.ts +76 -0
  79. package/dist/loop/strategy.d.ts +80 -0
  80. package/dist/loop/surfacePrepare.d.ts +30 -0
  81. package/dist/loop/tool.d.ts +106 -0
  82. package/dist/loop/toolCalls.d.ts +35 -0
  83. package/dist/plugin.d.ts +50 -0
  84. package/dist/plugin.js +1 -0
  85. package/dist/plugins/agentsMd.d.ts +80 -0
  86. package/dist/plugins/agentsMd.js +1 -0
  87. package/dist/plugins/ask/index.d.ts +26 -0
  88. package/dist/plugins/ask/index.js +1 -0
  89. package/dist/plugins/ask/service.d.ts +125 -0
  90. package/dist/plugins/ask/tools.d.ts +9 -0
  91. package/dist/plugins/commands/index.d.ts +43 -0
  92. package/dist/plugins/commands/index.js +1 -0
  93. package/dist/plugins/commands/output.d.ts +115 -0
  94. package/dist/plugins/commands/record.d.ts +558 -0
  95. package/dist/plugins/commands/service.d.ts +321 -0
  96. package/dist/plugins/commands/shell.d.ts +25 -0
  97. package/dist/plugins/commands/tools.d.ts +10 -0
  98. package/dist/plugins/compaction/checkpoint.d.ts +94 -0
  99. package/dist/plugins/compaction/config.d.ts +133 -0
  100. package/dist/plugins/compaction/estimate.d.ts +37 -0
  101. package/dist/plugins/compaction/index.d.ts +87 -0
  102. package/dist/plugins/compaction/index.js +7 -0
  103. package/dist/plugins/compaction/planner.d.ts +207 -0
  104. package/dist/plugins/compaction/prune.d.ts +9 -0
  105. package/dist/plugins/compaction/record.d.ts +227 -0
  106. package/dist/plugins/compaction/segments.d.ts +23 -0
  107. package/dist/plugins/compaction/state.d.ts +68 -0
  108. package/dist/plugins/compaction/summarize.d.ts +13 -0
  109. package/dist/plugins/dateAndBranch.d.ts +47 -0
  110. package/dist/plugins/dateAndBranch.js +1 -0
  111. package/dist/plugins/delegations/answers.d.ts +39 -0
  112. package/dist/plugins/delegations/assignmentKey.d.ts +22 -0
  113. package/dist/plugins/delegations/cleanup.d.ts +161 -0
  114. package/dist/plugins/delegations/constraint.d.ts +76 -0
  115. package/dist/plugins/delegations/index.d.ts +39 -0
  116. package/dist/plugins/delegations/index.js +1 -0
  117. package/dist/plugins/delegations/notices.d.ts +261 -0
  118. package/dist/plugins/delegations/obligations.d.ts +210 -0
  119. package/dist/plugins/delegations/record.d.ts +633 -0
  120. package/dist/plugins/delegations/request.d.ts +384 -0
  121. package/dist/plugins/delegations/role.d.ts +30 -0
  122. package/dist/plugins/delegations/service.d.ts +563 -0
  123. package/dist/plugins/delegations/standing.d.ts +19 -0
  124. package/dist/plugins/delegations/stopCheck.d.ts +21 -0
  125. package/dist/plugins/delegations/tools.d.ts +71 -0
  126. package/dist/plugins/delegations/waitContracts.d.ts +118 -0
  127. package/dist/plugins/delegations/waitResolver.d.ts +116 -0
  128. package/dist/plugins/diagnostics/digest.d.ts +14 -0
  129. package/dist/plugins/diagnostics/index.d.ts +68 -0
  130. package/dist/plugins/diagnostics/index.js +1 -0
  131. package/dist/plugins/fileTools/config.d.ts +10 -0
  132. package/dist/plugins/fileTools/editFiles.d.ts +117 -0
  133. package/dist/plugins/fileTools/fsRead.d.ts +17 -0
  134. package/dist/plugins/fileTools/gitDiscovery.d.ts +9 -0
  135. package/dist/plugins/fileTools/index.d.ts +18 -0
  136. package/dist/plugins/fileTools/index.js +1 -0
  137. package/dist/plugins/fileTools/ripgrep.d.ts +20 -0
  138. package/dist/plugins/fileTools/textEdit.d.ts +67 -0
  139. package/dist/plugins/fileTools/tools.d.ts +6 -0
  140. package/dist/plugins/historyRecall/history.d.ts +9 -0
  141. package/dist/plugins/historyRecall/index.d.ts +31 -0
  142. package/dist/plugins/historyRecall/index.js +1 -0
  143. package/dist/plugins/historyRecall/render.d.ts +34 -0
  144. package/dist/plugins/historyRecall/tools.d.ts +4 -0
  145. package/dist/plugins/mcp/catalog.d.ts +36 -0
  146. package/dist/plugins/mcp/config.d.ts +63 -0
  147. package/dist/plugins/mcp/connection.d.ts +53 -0
  148. package/dist/plugins/mcp/errors.d.ts +32 -0
  149. package/dist/plugins/mcp/index.d.ts +33 -0
  150. package/dist/plugins/mcp/index.js +5 -0
  151. package/dist/plugins/mcp/mount.d.ts +98 -0
  152. package/dist/plugins/mcp/names.d.ts +25 -0
  153. package/dist/plugins/mcp/render.d.ts +29 -0
  154. package/dist/plugins/mcp/slots.d.ts +15 -0
  155. package/dist/plugins/mcp/stdio.d.ts +49 -0
  156. package/dist/plugins/mcp/tools.d.ts +41 -0
  157. package/dist/plugins/mcp/version.d.ts +2 -0
  158. package/dist/plugins/routeNotice.d.ts +22 -0
  159. package/dist/plugins/routeNotice.js +1 -0
  160. package/dist/plugins/sandbox/absent.d.ts +33 -0
  161. package/dist/plugins/sandbox/client.d.ts +39 -0
  162. package/dist/plugins/sandbox/files.d.ts +28 -0
  163. package/dist/plugins/sandbox/index.d.ts +52 -0
  164. package/dist/plugins/sandbox/index.js +4 -0
  165. package/dist/plugins/sandbox/mode.d.ts +57 -0
  166. package/dist/plugins/sandbox/policy.d.ts +163 -0
  167. package/dist/plugins/sandbox/protocol.d.ts +107 -0
  168. package/dist/plugins/sandbox/service.d.ts +153 -0
  169. package/dist/plugins/sandbox/worker.d.ts +12 -0
  170. package/dist/plugins/sandbox/worker.js +1 -0
  171. package/dist/plugins/schedules/index.d.ts +21 -0
  172. package/dist/plugins/schedules/index.js +5 -0
  173. package/dist/plugins/schedules/record.d.ts +396 -0
  174. package/dist/plugins/schedules/service.d.ts +120 -0
  175. package/dist/plugins/schedules/time.d.ts +26 -0
  176. package/dist/plugins/schedules/tools.d.ts +6 -0
  177. package/dist/plugins/skills/discovery.d.ts +83 -0
  178. package/dist/plugins/skills/index.d.ts +31 -0
  179. package/dist/plugins/skills/index.js +1 -0
  180. package/dist/plugins/skills/tools.d.ts +11 -0
  181. package/dist/plugins/subAgents/availableRoutes.d.ts +53 -0
  182. package/dist/plugins/subAgents/index.d.ts +67 -0
  183. package/dist/plugins/subAgents/index.js +1 -0
  184. package/dist/plugins/subAgents/tools.d.ts +67 -0
  185. package/dist/plugins/threadDirs.d.ts +36 -0
  186. package/dist/plugins/threadDirs.js +1 -0
  187. package/dist/plugins/toolPolicy/index.d.ts +61 -0
  188. package/dist/plugins/toolPolicy/index.js +1 -0
  189. package/dist/plugins/truncateToolOutput.d.ts +30 -0
  190. package/dist/plugins/truncateToolOutput.js +6 -0
  191. package/dist/plugins/usage/index.d.ts +26 -0
  192. package/dist/plugins/usage/index.js +1 -0
  193. package/dist/plugins/usage/tracker.d.ts +34 -0
  194. package/dist/plugins/verify/index.d.ts +27 -0
  195. package/dist/plugins/verify/index.js +6 -0
  196. package/dist/plugins/verify/judgement.d.ts +16 -0
  197. package/dist/plugins/verify/record.d.ts +382 -0
  198. package/dist/plugins/verify/service.d.ts +93 -0
  199. package/dist/plugins/verify/state.d.ts +58 -0
  200. package/dist/plugins/webTools/html.d.ts +23 -0
  201. package/dist/plugins/webTools/index.d.ts +34 -0
  202. package/dist/plugins/webTools/index.js +1 -0
  203. package/dist/plugins/webTools/network.d.ts +23 -0
  204. package/dist/plugins/webTools/web.d.ts +32 -0
  205. package/dist/plugins/workflows/assignment.d.ts +20 -0
  206. package/dist/plugins/workflows/cleanup.d.ts +38 -0
  207. package/dist/plugins/workflows/definition.d.ts +184 -0
  208. package/dist/plugins/workflows/entryPlan.d.ts +95 -0
  209. package/dist/plugins/workflows/hostBindings.d.ts +146 -0
  210. package/dist/plugins/workflows/index.d.ts +28 -0
  211. package/dist/plugins/workflows/index.js +11 -0
  212. package/dist/plugins/workflows/observations.d.ts +81 -0
  213. package/dist/plugins/workflows/participantModels.d.ts +28 -0
  214. package/dist/plugins/workflows/participants.d.ts +143 -0
  215. package/dist/plugins/workflows/policy.d.ts +112 -0
  216. package/dist/plugins/workflows/record.d.ts +2849 -0
  217. package/dist/plugins/workflows/routing.d.ts +116 -0
  218. package/dist/plugins/workflows/schema.d.ts +26 -0
  219. package/dist/plugins/workflows/service.d.ts +477 -0
  220. package/dist/plugins/workflows/state.d.ts +373 -0
  221. package/dist/plugins/workflows/stopCheck.d.ts +13 -0
  222. package/dist/plugins/workflows/tools.d.ts +13 -0
  223. package/dist/plugins/workflows/view.d.ts +103 -0
  224. package/dist/plugins/workflows/workStatus.d.ts +21 -0
  225. package/dist/plugins/workspaceNotice.d.ts +36 -0
  226. package/dist/plugins/workspaceNotice.js +1 -0
  227. package/dist/providers/anthropic.d.ts +178 -0
  228. package/dist/providers/anthropicMessages.d.ts +66 -0
  229. package/dist/providers/codex.d.ts +71 -0
  230. package/dist/providers/codexAuth.d.ts +116 -0
  231. package/dist/providers/deepseek.d.ts +59 -0
  232. package/dist/providers/failure.d.ts +23 -0
  233. package/dist/providers/gateway.d.ts +24 -0
  234. package/dist/providers/index.d.ts +18 -0
  235. package/dist/providers/index.js +6 -0
  236. package/dist/providers/openaiChat.d.ts +73 -0
  237. package/dist/providers/openaiResponses.d.ts +109 -0
  238. package/dist/providers/opencodeCopilot.d.ts +23 -0
  239. package/dist/providers/opencodeGo.d.ts +109 -0
  240. package/dist/providers/shared.d.ts +112 -0
  241. package/dist/providers/stream.d.ts +156 -0
  242. package/dist/records/index.d.ts +13 -0
  243. package/dist/records/index.js +1 -0
  244. package/dist/records/journal.d.ts +2968 -0
  245. package/dist/records/toolResult.d.ts +65 -0
  246. package/dist/services/agents.d.ts +62 -0
  247. package/dist/services/catalogContributions.d.ts +73 -0
  248. package/dist/services/confinement/files.d.ts +118 -0
  249. package/dist/services/confinement/service.d.ts +219 -0
  250. package/dist/services/core.d.ts +28 -0
  251. package/dist/services/extensionEvents.d.ts +181 -0
  252. package/dist/services/journal.d.ts +26 -0
  253. package/dist/services/llm.d.ts +82 -0
  254. package/dist/services/modes.d.ts +65 -0
  255. package/dist/services/plugins.d.ts +34 -0
  256. package/dist/services/presets/definition.d.ts +154 -0
  257. package/dist/services/presets/installations.d.ts +139 -0
  258. package/dist/services/prompts.d.ts +85 -0
  259. package/dist/services/threads/activation.d.ts +100 -0
  260. package/dist/services/threads/admission.d.ts +174 -0
  261. package/dist/services/threads/birth.d.ts +219 -0
  262. package/dist/services/threads/index.d.ts +14 -0
  263. package/dist/services/threads/runEvents.d.ts +79 -0
  264. package/dist/services/threads/runOwner.d.ts +368 -0
  265. package/dist/services/threads/service.d.ts +450 -0
  266. package/dist/services/threads/thread.d.ts +268 -0
  267. package/dist/services/threads/view.d.ts +93 -0
  268. package/dist/services/tools.d.ts +118 -0
  269. package/dist/state/birth.d.ts +62 -0
  270. package/dist/state/chain.d.ts +46 -0
  271. package/dist/state/confirmations.d.ts +64 -0
  272. package/dist/state/continuation.d.ts +167 -0
  273. package/dist/state/decide.d.ts +72 -0
  274. package/dist/state/dispatches.d.ts +54 -0
  275. package/dist/state/errors.d.ts +26 -0
  276. package/dist/state/forks.d.ts +61 -0
  277. package/dist/state/holds.d.ts +104 -0
  278. package/dist/state/inbox.d.ts +188 -0
  279. package/dist/state/index.d.ts +31 -0
  280. package/dist/state/inputs.d.ts +58 -0
  281. package/dist/state/installations.d.ts +28 -0
  282. package/dist/state/limits.d.ts +14 -0
  283. package/dist/state/prompt.d.ts +13 -0
  284. package/dist/state/recovery.d.ts +7 -0
  285. package/dist/state/replace.d.ts +33 -0
  286. package/dist/state/requests.d.ts +129 -0
  287. package/dist/state/route.d.ts +61 -0
  288. package/dist/state/summary.d.ts +16 -0
  289. package/dist/state/surface.d.ts +153 -0
  290. package/dist/state/surfaceRead.d.ts +20 -0
  291. package/dist/state/thread.d.ts +73 -0
  292. package/dist/state/turns.d.ts +87 -0
  293. package/dist/state/waits.d.ts +38 -0
  294. package/dist/state/wake.d.ts +32 -0
  295. package/dist/stores/durableObject.d.ts +23 -0
  296. package/dist/stores/durableObject.js +1 -0
  297. package/dist/stores/durableObjectConnection.d.ts +27 -0
  298. package/dist/stores/memory.d.ts +29 -0
  299. package/dist/stores/sql.d.ts +59 -0
  300. package/dist/stores/sqlite.d.ts +31 -0
  301. package/dist/stores/sqlite.js +1 -0
  302. package/dist/sys/environment.d.ts +42 -0
  303. package/dist/sys/git.d.ts +47 -0
  304. package/dist/sys/paths.d.ts +9 -0
  305. package/dist/sys/spawn.d.ts +186 -0
  306. package/dist/testing/clock.d.ts +17 -0
  307. package/dist/testing/fakeLlm.d.ts +76 -0
  308. package/dist/testing/fedLlm.d.ts +34 -0
  309. package/dist/testing/helpers.d.ts +362 -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/settlement.d.ts +6 -0
  314. package/dist/testing/tmpDirs.d.ts +17 -0
  315. package/dist/util/async.d.ts +8 -0
  316. package/dist/util/diff.d.ts +25 -0
  317. package/dist/util/dispatch.d.ts +8 -0
  318. package/dist/util/errors.d.ts +28 -0
  319. package/dist/util/foldState.d.ts +17 -0
  320. package/dist/util/freeze.d.ts +2 -0
  321. package/dist/util/ids.d.ts +2 -0
  322. package/dist/util/json.d.ts +37 -0
  323. package/dist/util/jsonSchema.d.ts +7 -0
  324. package/dist/util/log.d.ts +6 -0
  325. package/dist/util/retries.d.ts +25 -0
  326. package/dist/util/text.d.ts +21 -0
  327. package/dist/util/timers.d.ts +43 -0
  328. package/package.json +183 -3
@@ -0,0 +1,6 @@
1
+ import{b as xe,c as ye,d as Ee,e as C,f as R,g as S,h as I,i as ke,j as y,k as $,l as N,m as we,n as u,o as H,p as q,q as E,r as Oe,s as A,t as ve,u as Y,v as tt,w as Te,x as be,y as Ce}from"../chunks/Q75FUN7D.js";import{a as ge}from"../chunks/PUSUPTAT.js";import"../chunks/34KW6VNQ.js";import{h as _e}from"../chunks/DDANMY45.js";import{A as F,d as j,e as g,l as U,n as fe,p as x,r as O,u as p,v as B}from"../chunks/D4PQP5MA.js";import{createHash as ft}from"node:crypto";import{isAbsolute as _t}from"node:path";import{promisify as Ae}from"node:util";import*as L from"node:zlib";import"openai";import{z as P}from"zod";import"openai";import{z as Re}from"zod";var Z=class extends Error{constructor(e){super(`The model returned output items lagent cannot execute: ${e.join(", ")}`),this.name="UnsupportedResponseOutputError"}},ot=new Set(["file_search_call","web_search_call","code_interpreter_call","mcp_call","mcp_list_tools","mcp_approval_response","image_generation_call","computer_call_output","function_call_output","local_shell_call_output","exec","reasoning_summary","item_reference","custom_tool_call_output"]),nt=new Set(["file_search_call","web_search_call","code_interpreter_call","mcp_call","image_generation_call"]);function Ie(o){if(!nt.has(o.type))return;let e=o,t=e.action,n=e.status;return fe.parse({id:e.id??o.type,type:o.type,name:e.name??e.server_label??null,status:n==="in_progress"||n==="failed"?n:"completed",summary:t?.query??e.code??null})}var st=new Set(["apply_patch_call","computer_call","custom_tool_call","local_shell_call","mcp_approval_request","shell_call"]),ee="openai-responses",te="gpt-5.4",J=["low","medium","high","max"],oe=[{id:"gpt-6-sol",description:"Workhorse for coding and everyday work",thinkingEfforts:J},{id:"gpt-6-astra",description:"Frontier intelligence for the most demanding work",thinkingEfforts:J},{id:"gpt-6-luna",description:"Fast and affordable, for easier tasks",thinkingEfforts:J}],it={"gpt-6-sol":258400,"gpt-6-astra":258400,"gpt-6-luna":258400,[te]:258400},Ne=E.extend({baseURL:Re.string().default(q),defaultModel:Re.string().default(te)}),m=class{providerName;client;callHeaders;replayByModel;thinkingEffort;extraBody;streamIdleTimeoutMs;constructor(e){let t=Ne.parse(e);this.providerName=e.name??ee,this.callHeaders=e.headers,this.replayByModel=e.replayByModel??!1,this.streamIdleTimeoutMs=t.streamIdleTimeoutMs,this.thinkingEffort=t.thinkingEffort??"none",this.extraBody=t.extraBody??{},this.client=A("OpenAI Responses",t,e.client)}buildRequest(e){let t=F(e.systemPrompt),n=e.thinkingEffort??this.thinkingEffort,s={...this.extraBody,model:e.model,...t?{instructions:t}:{},input:pt(e.messages,this.replayTag(e.model)),stream:!0,store:!1,include:["reasoning.encrypted_content"],reasoning:n==="none"?{effort:n}:{effort:n,summary:"auto"}};e.maxOutputTokens!==void 0&&(s.max_output_tokens=e.maxOutputTokens);let r=at(e.responseFormat);return r!==void 0&&(s.text={format:r}),(e.tools.length>0||e.providerTools.length>0)&&(s.tools=[...e.tools.map(lt),...e.providerTools],s.tool_choice=rt(e.toolChoice),s.parallel_tool_calls=e.parallelToolCalls),s}replayTag(e){return this.replayByModel?`${this.providerName}/${e}`:this.providerName}async openStream(e,t,n){return await this.client.responses.create(e,{signal:n,headers:t,...H})}async chat(e){let t=this.buildRequest(e),n=this.callHeaders?.(e,t)??{},{lifetime:s,opened:r}=await S(this.providerName,e.signal,this.streamIdleTimeoutMs,i=>this.openStream(t,n,i),i=>N(this.providerName,i,a=>this.isContextOverflow(a),e.signal));return new Q(s.events(r),this.providerName,this.replayTag(e.model),i=>this.isContextOverflow(i),e.signal,s)}isContextOverflow(e){return e.code===$}},rt=o=>typeof o=="string"?o:{type:"function",name:o.name},at=o=>{switch(o.kind){case"text":return;case"json_object":return{type:"json_object"};case"json_schema":return{type:"json_schema",name:o.name,schema:o.schema,strict:o.strict}}},lt=o=>({type:"function",name:o.name,description:o.description,parameters:o.input_schema,strict:!1}),Se=o=>o.every(e=>e.type==="text")?j(o):o.map(e=>{switch(e.type){case"text":return{type:"input_text",text:e.text};case"image":return{type:"input_image",detail:e.detail,...e.url?{image_url:e.url}:e.data?{image_url:`data:${e.media_type??"image/png"};base64,${e.data}`}:{}};case"file":return{type:"input_file",...e.file_id?{file_id:e.file_id}:{},...e.url?{file_url:e.url}:{},...e.data?{file_data:e.data}:{},...e.filename?{filename:e.filename}:{}}}});function pt(o,e=ee){let t=[];for(let n of o){if(n.role==="tool"){t.push({type:"function_call_output",call_id:n.tool_call_id??"",output:Se(n.content)});continue}if(n.role!=="assistant"){t.push({role:n.role,content:Se(n.content)});continue}if(n.provider_state?.provider===e&&Array.isArray(n.provider_state.data.output)){t.push(...n.provider_state.data.output);continue}let s=O(n);s&&t.push({role:"assistant",content:s});for(let r of n.tool_calls)t.push({type:"function_call",call_id:r.call_id,name:r.name,arguments:U(r)})}return t}function dt(o){let e=o.usage,t=e?.input_tokens_details;return{input_tokens:e?.input_tokens??0,output_tokens:e?.output_tokens??0,cache_read_input_tokens:t?.cached_tokens??0,cache_write_input_tokens:t?.cache_write_tokens??0,reasoning_output_tokens:e?.output_tokens_details?.reasoning_tokens??0}}function ct(o,e=ee){let t=[],n=[],s=[],r=[];for(let i of o.output??[])switch(i.type){case"message":{for(let a of i.content??[])a.type==="output_text"?t.push(a.text):a.type==="refusal"&&t.push(a.refusal);break}case"reasoning":{for(let a of i.content??[])n.push(a.text);for(let a of i.summary??[])n.push(a.text);break}case"function_call":{s.push(R(i.call_id,i.name,i.arguments));break}default:{let a=i.type;(st.has(a)||!ot.has(a))&&r.push(a)}}if(r.length>0)throw new Z([...new Set(r)]);return x.parse({role:"assistant",content:t.join("")||null,reasoning_content:n.join(`
2
+ `)||null,tool_calls:s,provider_calls:(o.output??[]).map(Ie).filter(i=>i!==void 0),usage:dt(o),provider_state:{provider:e,data:{output:o.output??[]}}})}var ut=o=>o.status==="completed"?"completed":o.status==="incomplete"&&o.incomplete_details?.reason==="max_output_tokens"?"length":"other",mt=o=>({response_id:o.id,model:o.model,status:o.status??null,...o.service_tier?{service_tier:o.service_tier}:{},...o.incomplete_details?{incomplete_details:o.incomplete_details}:{}}),Q=class extends I{response;itemsByIndex=new Map;text="";reasoning="";events;replayTag;isContextOverflow;constructor(e,t,n,s,r,i){super(t,r,i),this.events=e,this.replayTag=n,this.isContextOverflow=s}async*read(){try{yield*this.readEvents()}catch(e){throw N(this.providerName,e,this.isContextOverflow,this.signal)}}failure(e,t){let n=new we(e,t);return this.isContextOverflow(e)?new B(this.providerName,{cause:n}):n}async*readEvents(){for await(let e of this.events)switch(e.type){case"response.output_text.delta":this.text+=e.delta,yield{text_delta:e.delta,reasoning_delta:"",provider_call:null};break;case"response.reasoning_summary_text.delta":case"response.reasoning_text.delta":this.reasoning+=e.delta,yield{text_delta:"",reasoning_delta:e.delta,provider_call:null};break;case"response.output_item.done":{this.itemsByIndex.set(e.output_index,e.item);let t=Ie(e.item);t!==void 0&&(yield{text_delta:"",reasoning_delta:"",provider_call:t});break}case"response.completed":case"response.incomplete":this.response=this.withOutput(e.response);return;case"response.failed":throw this.failure(e.response.error??{},"The model request failed");case"error":throw this.failure(e,"The model stream reported an error");default:break}}withOutput(e){if(e.output&&e.output.length>0)return e;let t=[...this.itemsByIndex.entries()].sort(([n],[s])=>n-s).map(([,n])=>n);return{...e,output:t}}settle(){if(this.response!==void 0)return{message:ct(this.response,this.replayTag),finish:ut(this.response),provider_metadata:mt(this.response)}}partial(){return{message:x.parse({role:"assistant",content:this.text||null,reasoning_content:this.reasoning||null}),providerMetadata:{}}}},ht=o=>{let e=Ne.parse(o);return{name:"openai-responses",defaultModel:e.defaultModel||te,defaultThinkingEffort:e.thinkingEffort,models:oe,capacity:t=>({contextWindow:y(it,t),providerTools:!0,toolResultImages:!0}),createClient:()=>new m(o),classify:t=>u(t)}};var se="codex",ie="gpt-5.6-luna",K=["low","medium","high","max"],gt=[{id:"gpt-6.1-sol",description:"Latest workhorse for coding and everyday work",thinkingEfforts:K},...oe,{id:"gpt-5.6-sol",description:"Older workhorse generation",thinkingEfforts:K},{id:"gpt-5.6-terra",description:"Older balanced model for straightforward work",thinkingEfforts:K},{id:ie,description:"Older fast and efficient model",thinkingEfforts:K}],xt={"gpt-6.1-sol":475e3,"gpt-6-astra":258400,"gpt-6-sol":258400,"gpt-6-luna":258400,"gpt-reserve":258400,"gpt-5.6-sol":258400,"gpt-5.6-terra":258400,"gpt-5.6-luna":258400,"codex-auto-review":258400},Me=P.object({authPath:P.string().refine(_t,"the Codex login file must be an absolute path").optional(),refreshTimeoutMs:P.number().int().positive().optional(),streamIdleTimeoutMs:C,baseURL:P.string().default(ve),defaultModel:P.string().default(ie),thinkingEffort:P.enum(g).default("high"),extraBody:ke.optional()}),ne=class extends m{credentials;constructor(e){let t=Me.parse(e),n=e.credentials;if(n===void 0&&t.authPath!==void 0){if(t.refreshTimeoutMs===void 0)throw new Error("Codex needs a `refreshTimeoutMs` with its `authPath`: the host bounds how long a refresh may take");n=Te(t.authPath,{refreshTimeoutMs:t.refreshTimeoutMs})}if(n===void 0)throw new Error("Codex needs an `authPath`: lagent reads no environment, so the host names the login file");super({name:se,headers:(s,r)=>{let i=Et(r);return ge.debug(`codex session_id=${i} model=${String(r.model)} input_items=${Array.isArray(r.input)?r.input.length:0}`),{session_id:i}},streamIdleTimeoutMs:t.streamIdleTimeoutMs,thinkingEffort:t.thinkingEffort,extraBody:t.extraBody,client:e.client??Ce({credentials:n,baseURL:t.baseURL,fetch:yt(e.fetch)})}),this.credentials=n}openStream(e,t,n){return be(this.credentials,n,()=>super.openStream(e,t,n))}},Pe=typeof L.zstdCompress=="function"?{name:"zstd",compress:Ae(L.zstdCompress)}:{name:"gzip",compress:Ae(L.gzip)},yt=(o=globalThis.fetch)=>async(e,t)=>{if(typeof t?.body!="string")return o(e,t);let n=new Headers(t.headers);return n.set("Content-Encoding",Pe.name),n.delete("Content-Length"),o(e,{...t,headers:n,body:await Pe.compress(t.body)})},Et=o=>ft("sha256").update(JSON.stringify([o.model,o.instructions??null,o.tools??null])).digest("hex").slice(0,32),kt=o=>{let e=Me.parse(o);return{name:se,defaultModel:e.defaultModel||ie,defaultThinkingEffort:e.thinkingEffort,models:gt,capacity:t=>({contextWindow:y(xt,t),providerTools:!0,toolResultImages:!0}),createClient:()=>new ne(o),classify:t=>t instanceof Y?{kind:"auth"}:u(t)}};import{z as De}from"zod";var wt="https://api.deepseek.com",Le="deepseek-responses",z="deepseek-flash",We=["low","high","max"],Ot=[{id:z,description:"Fast frontier coding model with image input",thinkingEfforts:We},{id:"deepseek-v4-pro",description:"Most capable DeepSeek model, for the hardest work",thinkingEfforts:We}],vt={[z]:996147,"deepseek-v4-pro":996147},Tt=/maximum context length is \d+ tokens/i,je=E.extend({baseURL:De.string().default(wt),defaultModel:De.string().default(z)}),re=class extends m{constructor(e){let t=je.parse(e);if(t.apiKey===void 0&&e.client===void 0)throw new Error("DeepSeek needs an `apiKey`: lagent reads no environment, so the host resolves the credential");let n={...t,client:e.client,name:Le};super(n)}buildRequest(e){if(e.providerTools.length>0)throw new p(this.providerName,"provider-executed tools");if(e.messages.some(n=>n.content.some(s=>s.type==="file")))throw new p(this.providerName,"file inputs");let t=super.buildRequest(e);return delete t.include,t}isContextOverflow(e){return super.isContextOverflow(e)?!0:typeof e.message=="string"&&Tt.test(e.message)}},bt=o=>{let e=je.parse(o);return{name:"deepseek-responses",defaultModel:e.defaultModel||z,defaultThinkingEffort:e.thinkingEffort,models:Ot,capacity:t=>({contextWindow:y(vt,t),providerTools:!1,toolResultImages:!1}),createClient:()=>new re(o),classify:t=>u(t)}};import"openai";import{z as M}from"zod";var Ue="openai-chat-completions",Be="gpt-5.4",Fe=E.extend({baseURL:M.string().default(q),defaultModel:M.string().default(Be),systemRole:M.enum(["system","developer"]).default("system"),contextWindows:M.record(M.string(),M.number().int().positive()).optional()}),v=class{providerName;client;callHeaders;thinkingEffort;extraBody;systemRole;streamIdleTimeoutMs;constructor(e){let t=Fe.parse(e);this.providerName=e.name??Ue,this.callHeaders=e.headers,this.streamIdleTimeoutMs=t.streamIdleTimeoutMs,this.thinkingEffort=t.thinkingEffort,this.extraBody=t.extraBody??{},this.systemRole=t.systemRole,this.client=A("OpenAI Chat Completions",t,e.client)}buildRequest(e){if(e.providerTools.length>0)throw new p(this.providerName,"provider-executed tools");let t=F(e.systemPrompt),n=e.thinkingEffort??this.thinkingEffort,s={...this.extraBody,model:e.model,messages:[...t?[{role:this.systemRole,content:t}]:[],...e.messages.map(i=>At(i,this.providerName))],stream:!0,stream_options:{include_usage:!0}};n!==void 0&&(s.reasoning_effort=n),e.maxOutputTokens!==void 0&&(s.max_completion_tokens=e.maxOutputTokens);let r=St(e.responseFormat);return r!==void 0&&(s.response_format=r),e.tools.length>0&&(s.tools=e.tools.map(It),s.tool_choice=Rt(e.toolChoice),s.parallel_tool_calls=e.parallelToolCalls),s}async openStream(e,t,n){return await this.client.chat.completions.create(e,{signal:n,headers:t,...H})}async chat(e){let t=this.buildRequest(e),n=this.callHeaders?.(e,t)??{},{lifetime:s,opened:r}=await S(this.providerName,e.signal,this.streamIdleTimeoutMs,i=>this.openStream(t,n,i),i=>N(this.providerName,i,$e,e.signal));return new ae(s.events(r),this.providerName,e.signal,s)}},$e=o=>o.code===$,Ct=o=>{switch(o){case"stop":case"tool_calls":case"function_call":return"completed";case"length":return"length";default:return"other"}},Rt=o=>typeof o=="string"?o:{type:"function",function:{name:o.name}},St=o=>{switch(o.kind){case"text":return;case"json_object":return{type:"json_object"};case"json_schema":return{type:"json_schema",json_schema:{name:o.name,schema:o.schema,strict:o.strict}}}},It=o=>({type:"function",function:{name:o.name,description:o.description,parameters:o.input_schema,strict:!1}}),Nt=(o,e)=>o.every(t=>t.type==="text")?j(o):o.map(t=>{switch(t.type){case"text":return{type:"text",text:t.text};case"image":return{type:"image_url",image_url:{url:t.url||`data:${t.media_type??"image/png"};base64,${t.data??""}`,detail:t.detail}};case"file":{if(!t.file_id&&!t.data)throw new p(e,"files by URL \u2014 upload the file or inline its data");return{type:"file",file:{...t.file_id?{file_id:t.file_id}:{},...t.data?{file_data:t.data}:{},...t.filename?{filename:t.filename}:{}}}}}});function At(o,e=Ue){switch(o.role){case"tool":{let t=o.content.find(n=>n.type!=="text");if(t!==void 0)throw new p(e,`a ${t.type} in a tool result`);return{role:"tool",tool_call_id:o.tool_call_id??"",content:O(o)}}case"assistant":{let t={role:"assistant",content:O(o)||null};return o.tool_calls.length>0&&(t.tool_calls=o.tool_calls.map(n=>({id:n.call_id,type:"function",function:{name:n.name,arguments:U(n)}}))),o.reasoning_content!==null&&(t.reasoning_content=o.reasoning_content),t}default:return{role:o.role,content:Nt(o.content,e)}}}var ae=class extends I{toolCalls=new Map;lastToolCallKey;text="";reasoning="";finishReason=null;usage=null;metadata={};events;constructor(e,t,n,s){super(t,n,s),this.events=e}async*read(){try{yield*this.readEvents()}catch(e){throw N(this.providerName,e,$e,this.signal)}}async*readEvents(){for await(let e of this.events){this.recordMetadata(e);let t=Pt(e);t!==null&&(this.usage=t);let n=e.choices[0];if(n===void 0)continue;n.finish_reason&&(this.finishReason=n.finish_reason);let s=n.delta,r=new Set;for(let d of s.tool_calls??[])this.recordToolCall(d,r);let i=s.content??"",a=s.reasoning_content||s.reasoning||"";this.text+=i,this.reasoning+=a,(i||a)&&(yield{text_delta:i,reasoning_delta:a,provider_call:null})}}recordMetadata(e){if(Object.keys(this.metadata).length>0)return;let t=e;this.metadata={response_id:e.id,model:e.model,...e.system_fingerprint?{system_fingerprint:e.system_fingerprint}:{},...t.service_tier?{service_tier:t.service_tier}:{}}}recordToolCall(e,t){let n=this.toolCallKey(e,t),s=this.toolCalls.get(n)??{order:this.toolCalls.size,id:"",name:"",arguments:""};this.toolCalls.set(n,{order:e.index??s.order,id:e.id??s.id,name:e.function?.name??s.name,arguments:s.arguments+(e.function?.arguments??"")}),this.lastToolCallKey=n}toolCallKey(e,t){if(e.index!==void 0&&e.index!==null)return`index:${e.index}`;if(e.id){let n=t.has(e.id)?`id:${e.id}#${this.toolCalls.size}`:`id:${e.id}`;return t.add(e.id),n}return this.lastToolCallKey??"index:0"}settle(){if(this.finishReason===null)return;let e=[...this.toolCalls.values()].sort((n,s)=>n.order-s.order).map(n=>R(n.id,n.name,n.arguments));return{message:x.parse({role:"assistant",content:this.text||null,reasoning_content:this.reasoning||null,tool_calls:e,usage:this.usage}),finish:Ct(this.finishReason),provider_metadata:{...this.metadata,finish_reason:this.finishReason}}}partial(){return{message:x.parse({role:"assistant",content:this.text||null,reasoning_content:this.reasoning||null,usage:this.usage}),providerMetadata:{...this.metadata,finish_reason:"incomplete"}}}};function Pt(o){let e=o;if(o.usage)return{input_tokens:o.usage.prompt_tokens,output_tokens:o.usage.completion_tokens,cache_read_input_tokens:o.usage.prompt_tokens_details?.cached_tokens??0,cache_write_input_tokens:0,reasoning_output_tokens:o.usage.completion_tokens_details?.reasoning_tokens??0};let t=e.normalizedUsage;if(t===void 0)return null;let n=s=>Number(t[s]??0)||0;return{input_tokens:n("inputTokens"),output_tokens:n("outputTokens"),cache_read_input_tokens:n("cacheReadTokens"),cache_write_input_tokens:n("cacheWriteTokens"),reasoning_output_tokens:0}}var Mt=o=>{let e=Fe.parse(o);return{name:"openai-chat-completions",defaultModel:e.defaultModel||Be,defaultThinkingEffort:e.thinkingEffort,capacity:t=>({contextWindow:y(e.contextWindows??{},t),providerTools:!1,toolResultImages:!1}),createClient:()=>new v(o),classify:t=>u(t)}};import{readFile as Jt}from"node:fs/promises";import{isAbsolute as Zt}from"node:path";import{z as l}from"zod";import{createHash as Dt}from"node:crypto";var Wt=/^[a-zA-Z0-9_-]+$/,qe=o=>Wt.test(o)?o:`lg_${Dt("sha256").update(o).digest("base64url").slice(0,32)}`;function Lt(o,e){let t=o.provider_state;return t?.provider!==e||!Array.isArray(t.data.thinking)?[]:t.data.thinking.filter(n=>n.type==="thinking"?typeof n.signature=="string"&&n.signature!=="":n.type==="redacted_thinking"&&typeof n.data=="string")}function Ke(o,e){let t=[],n=(s,r)=>{if(r.length===0)return;let i=t.at(-1);i?.role===s?i.content.push(...r):t.push({role:s,content:r})};for(let s of o)switch(s.role){case"assistant":n("assistant",Ut(s,e.replayTag));break;case"tool":n("user",[Bt(s,e.provider)]);break;case"user":n("user",le(s.content,e.provider));break;default:n("user",Ft(s.content,e.provider))}for(let s of t)s.role==="user"&&(s.content=jt(s.content));return t}var jt=o=>[...o.filter(e=>e.type==="tool_result"),...o.filter(e=>e.type!=="tool_result")];function Ut(o,e){let t=[...Lt(o,e)],n=O(o);n!==""&&t.push({type:"text",text:n});for(let s of o.tool_calls)t.push({type:"tool_use",id:qe(s.call_id),name:s.name,input:s.arguments??{}});return t}function Bt(o,e){let t=le(o.content,e);if(t.find(s=>s.type==="document")!==void 0)throw new p(e,"a file in a tool result");return{type:"tool_result",tool_use_id:qe(o.tool_call_id??""),...t.length===0?{}:{content:t}}}function Ft(o,e){let t=le(o,e);return t.length===0?[]:[{type:"text",text:"<system-reminder>"},...t,{type:"text",text:"</system-reminder>"}]}function le(o,e){let t=[];for(let n of o)switch(n.type){case"text":n.text!==""&&t.push({type:"text",text:n.text});break;case"image":t.push({type:"image",source:n.url?{type:"url",url:n.url}:{type:"base64",media_type:n.media_type??"image/png",data:n.data??""}});break;case"file":t.push($t(n,e))}return t}function $t(o,e){let t=o.filename?{title:o.filename}:{};if(o.url)return{type:"document",source:{type:"url",url:o.url},...t};if(o.data&&o.media_type==="application/pdf")return{type:"document",source:{type:"base64",media_type:"application/pdf",data:o.data},...t};if(o.data&&o.media_type==="text/plain")return{type:"document",source:{type:"text",media_type:"text/plain",data:Buffer.from(o.data,"base64").toString("utf8")},...t};throw new p(e,o.file_id?"files by provider id":`a file of type '${o.media_type??"unknown"}'`)}var ze=o=>o.map(e=>({name:e.name,...e.description?{description:e.description}:{},input_schema:e.input_schema}));function Ge(o,e){let t=e?{}:{disable_parallel_tool_use:!0};return o==="none"?{type:"none"}:o==="auto"?{type:"auto",...t}:o==="required"?{type:"any",...t}:{type:"tool",name:o.name,...t}}function Ve(o){return o===void 0?{}:o==="none"?{thinking:{type:"disabled"}}:{thinking:{type:"adaptive",display:"summarized"},output_config:{effort:o}}}var h=class extends Error{errorType;status;headers;constructor(e,t,n,s){super(t),this.errorType=e,this.status=n,this.headers=s,this.name="AnthropicAPIError"}},Xe=o=>o.errorType==="invalid_request_error"&&/prompt is too long/i.test(o.message),He={rate_limit_error:"rate_limit",overloaded_error:"overloaded",api_error:"transport",timeout_error:"timeout",authentication_error:"auth",permission_error:"auth",billing_error:"quota"};function V(o,e=Date.now()){if(!(o instanceof h))return{kind:Ee(o)};let t=o.errorType!==void 0&&Object.hasOwn(He,o.errorType)?He[o.errorType]:void 0,{status:n}=o;return n===void 0?{kind:t??"other"}:ye(t??xe(n)??"other",o.headers,e)}var Ht=o=>{switch(o){case"end_turn":case"tool_use":case"stop_sequence":return"completed";case"max_tokens":case"model_context_window_exceeded":return"length";default:return"other"}},G=class{id=null;model=null;blocks=new Map;stopReason=null;stopSequence=null;stopped=!1;usage=null;options;constructor(e){this.options=e}apply(e){switch(e.type){case"message_start":return this.id=e.message.id,this.model=e.message.model,this.addUsage(e.message.usage),null;case"content_block_start":return this.blocks.set(e.index,qt(e.content_block)),null;case"content_block_delta":return this.applyDelta(e.index,e.delta);case"message_delta":return e.delta.stop_reason&&(this.stopReason=e.delta.stop_reason),e.delta.stop_sequence&&(this.stopSequence=e.delta.stop_sequence),this.addUsage(e.usage),null;case"message_stop":return this.stopped=!0,null;case"error":throw new h(e.error.type,e.error.message??"The stream reported an error");default:return null}}get complete(){return this.stopReason!==null&&this.stopped}get stop(){return this.stopReason}applyDelta(e,t){let n=this.blocks.get(e);return n===void 0?null:n.type==="text"&&t.type==="text_delta"&&typeof t.text=="string"?(n.text+=t.text,{text_delta:t.text,reasoning_delta:"",provider_call:null}):n.type==="thinking"&&t.type==="thinking_delta"&&typeof t.thinking=="string"?(n.thinking+=t.thinking,{text_delta:"",reasoning_delta:t.thinking,provider_call:null}):(n.type==="thinking"&&t.type==="signature_delta"&&typeof t.signature=="string"?n.signature+=t.signature:n.type==="tool_use"&&t.type==="input_json_delta"&&typeof t.partial_json=="string"&&(n.json+=t.partial_json),null)}addUsage(e){if(e==null)return;let t=Object.fromEntries(Object.entries(e).filter(([,n])=>n!==null));this.usage={...this.usage,...t}}normalizedUsage(){if(this.usage===null)return null;let e=this.usage.cache_read_input_tokens??0,t=this.usage.cache_creation_input_tokens??0;return{input_tokens:(this.usage.input_tokens??0)+e+t,output_tokens:this.usage.output_tokens??0,cache_read_input_tokens:e,cache_write_input_tokens:t,reasoning_output_tokens:this.usage.output_tokens_details?.thinking_tokens??0}}ordered(){return[...this.blocks.entries()].sort(([e],[t])=>e-t).map(([,e])=>e)}text(){return this.ordered().flatMap(e=>e.type==="text"?[e.text]:[]).join("")}reasoning(){return this.ordered().flatMap(e=>e.type==="thinking"&&e.thinking!==""?[e.thinking]:[]).join(`
3
+
4
+ `)}metadata(){return{...this.id===null?{}:{message_id:this.id},...this.model===null?{}:{model:this.model},stop_reason:this.stopReason??"incomplete",...this.stopSequence===null?{}:{stop_sequence:this.stopSequence}}}settle(){if(!this.complete)return;let e=this.options.toolName??(i=>i),t=[],n=[];for(let i of this.ordered())i.type==="thinking"?t.push({type:"thinking",thinking:i.thinking,signature:i.signature}):i.type==="redacted_thinking"?t.push({type:"redacted_thinking",data:i.data}):i.type==="tool_use"&&n.push(R(i.id,e(i.name),i.json===""?i.input:i.json));let s={id:this.id??"",thinking:t};return{message:x.parse({role:"assistant",content:this.text()||null,reasoning_content:this.reasoning()||null,tool_calls:n,usage:this.normalizedUsage(),provider_state:{provider:this.options.replayTag,data:s}}),finish:Ht(this.stopReason),provider_metadata:this.metadata()}}partial(){return{message:x.parse({role:"assistant",content:this.text()||null,reasoning_content:this.reasoning()||null,usage:this.normalizedUsage()}),providerMetadata:this.metadata()}}};function qt(o){switch(o.type){case"text":return{type:"text",text:typeof o.text=="string"?o.text:""};case"thinking":return{type:"thinking",thinking:typeof o.thinking=="string"?o.thinking:"",signature:typeof o.signature=="string"?o.signature:""};case"redacted_thinking":return{type:"redacted_thinking",data:typeof o.data=="string"?o.data:""};case"tool_use":return{type:"tool_use",id:String(o.id??""),name:String(o.name??""),json:"",input:o.input};default:return{type:"other",raw:o}}}import{z as f}from"zod";var Kt="2023-06-01",zt=f.object({apiKey:f.string().min(1).optional(),baseURL:f.string().min(1),streamIdleTimeoutMs:C,authorization:f.enum(["x-api-key","bearer"]).default("x-api-key"),defaultHeaders:f.record(f.string(),f.string()).optional(),thinkingEffort:f.enum(g).optional(),maxOutputTokens:f.record(f.string(),f.number().int().positive())}),Gt=o=>o.type!=="thinking"&&o.type!=="redacted_thinking";function Vt(o,e){let t=s=>{for(let r=s.length-1;r>=0;r--)if(Gt(s[r])){s[r]={...s[r],cache_control:{type:"ephemeral"}};return}};t(o);let n=e.at(-1);n!==void 0&&t(n.content)}var D=class{providerName;config;fetchImpl;callHeaders;constructor(e){this.providerName=e.name,this.config=zt.parse(e),this.fetchImpl=e.fetch??globalThis.fetch,this.callHeaders=e.headers}replayTag(e){return`${this.providerName}/${e}`}maxOutputTokens(e){if(e.maxOutputTokens!==void 0)return e.maxOutputTokens;let t=this.config.maxOutputTokens;if(Object.hasOwn(t,e.model))return t[e.model];throw new p(this.providerName,`model '${e.model}' with no output cap \u2014 name it in the provider's \`maxOutputTokens\``)}headers(e,t){let{apiKey:n,authorization:s}=this.config;if(n===void 0)throw new Error(`${this.providerName} needs an \`apiKey\`: lagent reads no environment, so the host resolves the credential`);return{...this.config.defaultHeaders,...s==="bearer"?{Authorization:`Bearer ${n}`}:{"x-api-key":n},"anthropic-version":Kt,"content-type":"application/json",accept:"text/event-stream",...this.callHeaders?.(e,t)}}buildRequest(e){if(e.providerTools.length>0)throw new p(this.providerName,"provider-executed tools");if(e.responseFormat.kind!=="text")throw new p(this.providerName,`response format '${e.responseFormat.kind}'`);let t=e.thinkingEffort??this.config.thinkingEffort;if(e.toolChoice!=="auto"&&e.toolChoice!=="none"&&t!==void 0&&t!=="none"&&e.tools.length>0)throw new p(this.providerName,"a forced tool choice while thinking");let s=e.systemPrompt.filter(a=>a.text!=="").map(a=>({type:"text",text:a.text})),r=Ke(e.messages,{provider:this.providerName,replayTag:this.replayTag(e.model)});Vt(s,r);let i={model:e.model,max_tokens:this.maxOutputTokens(e),messages:r,stream:!0,...Ve(t)};return s.length>0&&(i.system=s),e.tools.length>0&&(i.tools=ze(e.tools),i.tool_choice=Ge(e.toolChoice,e.parallelToolCalls)),i}async chat(e){let t=this.buildRequest(e),n=this.headers(e,t),{lifetime:s,opened:r}=await S(this.providerName,e.signal,this.config.streamIdleTimeoutMs,a=>this.open(t,n,a),a=>_e(e.signal,a)?e.signal.reason:this.classified(a)),i=new G({replayTag:this.replayTag(e.model)});return new pe(s.events(Yt(r)),i,this,e.signal,s)}async open(e,t,n){let s=await this.fetchImpl(`${this.config.baseURL.replace(/\/+$/,"")}/messages`,{method:"POST",headers:t,body:JSON.stringify(e),signal:n});if(!s.ok||s.body===null)throw await Xt(s);return s.body}classified(e){return e instanceof h&&Xe(e)?new B(this.providerName,{cause:e}):e}};async function Xt(o){let e=await o.text().catch(()=>""),t;try{t=JSON.parse(e).error}catch{t=void 0}let n=typeof t?.message=="string"&&t.message!==""?t.message:e||o.statusText;return new h(typeof t?.type=="string"?t.type:void 0,`${o.status} ${n}`,o.status,o.headers)}async function*Yt(o){let e=new TextDecoder,t="",n=[];for await(let s of o){t+=e.decode(s,{stream:!0});let r;for(;(r=t.search(/[\r\n]/))>=0&&!(t[r]==="\r"&&r===t.length-1);){let i=t.slice(0,r);t=t.slice(t.startsWith(`\r
5
+ `,r)?r+2:r+1),i===""?(n.length>0&&(yield JSON.parse(n.join(`
6
+ `))),n=[]):i.startsWith("data:")&&n.push(i.slice(5).replace(/^ /,""))}}}var pe=class extends I{events;assembly;client;constructor(e,t,n,s,r){super(n.providerName,s,r),this.events=e,this.assembly=t,this.client=n}async*read(){try{for await(let e of this.events){let t=this.assembly.apply(e);if(t!==null&&(yield t),this.assembly.complete)return}}catch(e){throw this.client.classified(e)}}settle(){return this.assembly.settle()}partial(){return this.assembly.partial()}};var W=class{providerName;prepare;adapters;constructor(e,t,n){this.providerName=e,this.prepare=t,this.adapters=n}async chat(e){let t=this.prepare(e);return this.adapters[t.protocol].chat(t.call)}};var k="opencode-copilot",Qt="https://api.githubcopilot.com",de={"User-Agent":"opencode/2.0.26","X-GitHub-Api-Version":"2026-08-01"},eo=l.strictObject({authPath:l.string().refine(Zt,"authPath must be an absolute path"),streamIdleTimeoutMs:C,defaultModel:l.string().min(1).optional(),thinkingEffort:l.enum(g).optional()}),to=l.object({"github-copilot":l.object({type:l.literal("oauth"),access:l.string().min(1),metadata:l.object({apiEndpoint:l.url().optional()}).optional()})}),oo=l.object({id:l.string().min(1),name:l.string().optional(),model_picker_enabled:l.boolean().optional(),policy:l.object({state:l.string().optional()}).optional(),supported_endpoints:l.array(l.string()).optional(),capabilities:l.object({type:l.string().optional(),limits:l.object({max_context_window_tokens:l.number().int().positive().optional(),max_prompt_tokens:l.number().int().positive(),max_output_tokens:l.number().int().positive()}),supports:l.object({streaming:l.boolean().optional(),tool_calls:l.boolean(),vision:l.boolean().optional(),reasoning_effort:l.array(l.string()).optional(),adaptive_thinking:l.boolean().optional(),min_thinking_budget:l.number().int().positive().optional(),max_thinking_budget:l.number().int().positive().optional()})})});function no(o){let e=o.supported_endpoints;if(e?.includes("/v1/messages"))return"messages";if(e?.includes("/responses"))return"responses";if(e?.includes("/chat/completions"))return"chat";if(e?.length)return;if(o.id.startsWith("claude-"))return"messages";let t=/^gpt-(\d+)/.exec(o.id);return t&&Number(t[1])>=5&&!o.id.startsWith("gpt-5-mini")||o.id.startsWith("grok-")||o.id.startsWith("mai-code-")?"responses":"chat"}function so(o){let e=l.object({data:l.array(l.unknown())}).safeParse(o);if(!e.success)throw new Error("Copilot model discovery returned an invalid catalog");let t=new Map;for(let n of e.data.data){let s=oo.safeParse(n);if(!s.success)continue;let r=s.data;if(r.policy?.state==="disabled"||r.capabilities.supports.streaming===!1||r.capabilities.type!==void 0&&r.capabilities.type!=="chat")continue;let i=no(r);if(i===void 0)continue;let a=r.capabilities.supports,d=a.reasoning_effort?.filter(w=>g.some(X=>X===w)),c=i==="messages"&&!a.adaptive_thinking&&a.max_thinking_budget?["none","high","max"]:d?.length?d:a.adaptive_thinking?void 0:["none"];t.set(r.id,{...r,protocol:i,...c?{thinkingEfforts:c}:{}})}if(t.size===0)throw new Error("Copilot model discovery returned no usable models");return new Map([...t].sort((n,s)=>+!!s[1].model_picker_enabled-+!!n[1].model_picker_enabled))}var io=o=>({"Openai-Intent":"conversation-edits","X-Interaction-Type":o.purpose==="auxiliary"?"conversation-background":"conversation-agent","X-Interaction-Id":o.threadId,"x-initiator":o.purpose==="step"&&o.messages.at(-1)?.role==="user"?"user":"agent",...o.messages.some(e=>e.content.some(t=>t.type==="image"))?{"Copilot-Vision-Request":"true"}:{}}),ce=class extends m{buildRequest(e){let t=super.buildRequest(e);return e.thinkingEffort===void 0&&delete t.reasoning,t}},ue=class extends D{models;constructor(e,t){super(e),this.models=t}buildRequest(e){let t=super.buildRequest(e),n=this.models.get(e.model).capabilities.supports;if(!n.adaptive_thinking&&e.thinkingEffort&&e.thinkingEffort!=="none"){let s=n.max_thinking_budget;if(s===void 0)throw new p(this.providerName,`thinking on '${e.model}'`);let r=e.thinkingEffort==="max"?s-1:Math.floor(s/2),i=Math.min(r,Number(t.max_tokens)-1);if(i<(n.min_thinking_budget??1))throw new p(this.providerName,`thinking budget above the output cap for '${e.model}'`);t.thinking={type:"enabled",budget_tokens:i},delete t.output_config}return t}},me=class extends W{constructor(e,t,n,s){let r=Oe({apiKey:n,baseURL:s,defaultHeaders:de}),i={name:k,headers:io,streamIdleTimeoutMs:e.streamIdleTimeoutMs},a={...i,client:r};super(k,d=>{let c=t.get(d.model);if(!c)throw new p(k,`undiscovered model '${d.model}'`);if(d.providerTools.length)throw new p(k,"provider-executed tools");if(d.tools.length&&!c.capabilities.supports.tool_calls)throw new p(k,`tools on '${d.model}'`);let w=d.thinkingEffort??e.thinkingEffort;if(w!==void 0&&c.thinkingEfforts&&!c.thinkingEfforts.includes(w))throw new p(k,`thinking effort '${w}' on '${d.model}'`);let X=c.thinkingEfforts?.some(et=>et!=="none")??!0,{thinkingEffort:ko,...Qe}=d;return{protocol:c.protocol,call:{...Qe,...w===void 0||!X?{}:{thinkingEffort:w}}}},{responses:new ce({...a,replayByModel:!0}),chat:new v(a),messages:new ue({...i,apiKey:n,authorization:"bearer",baseURL:`${s}/v1`,defaultHeaders:{...de,"anthropic-beta":"interleaved-thinking-2025-05-14"},maxOutputTokens:Object.fromEntries([...t].map(([d,c])=>[d,c.capabilities.limits.max_output_tokens]))},t)})}},ro=async o=>{let e=eo.parse(o),t;try{t=to.parse(JSON.parse(await Jt(e.authPath,"utf8")))["github-copilot"]}catch{throw new Error(`opencode-copilot needs an OAuth login in ${e.authPath}; run opencode auth login`)}let n=(t.metadata?.apiEndpoint??Qt).replace(/\/+$/,""),s=await fetch(`${n}/models`,{headers:{...de,Authorization:`Bearer ${t.access}`},signal:AbortSignal.timeout(5e3)});if(!s.ok)throw new Error(`Copilot model discovery failed: HTTP ${s.status}`);let r=so(await s.json()),i=e.defaultModel??(r.has("gpt-6-luna")?"gpt-6-luna":r.keys().next().value);if(!r.has(i))throw new Error(`Copilot default model '${i}' is unavailable`);return{name:k,defaultModel:i,...e.thinkingEffort===void 0?{}:{defaultThinkingEffort:e.thinkingEffort},models:[...r.values()].map(a=>({id:a.id,...a.name?{description:a.name}:{},...a.thinkingEfforts?{thinkingEfforts:a.thinkingEfforts}:{}})),capacity:a=>{let d=r.get(a),c=d?.capabilities.limits;return{contextWindow:c?Math.min(c.max_prompt_tokens,c.max_context_window_tokens??c.max_prompt_tokens):null,providerTools:!1,toolResultImages:d?.protocol!=="chat"&&d?.capabilities.supports.vision===!0}},createClient:()=>new me(e,r,t.access,n),classify:a=>a instanceof h?V(a):u(a)}};import{z as _}from"zod";var ao="https://opencode.ai/zen/go/v1",b="opencode-go",lo="deepseek-v4.1-flash",po="x-opencode-session",T=["low","medium","high","max"],Ye=["low","medium","high"],co={"grok-4.7":{protocol:"responses",contextWindow:5e5,thinkingEfforts:Ye},"gpt-6-luna":{protocol:"responses",contextWindow:922e3},"gpt-5.6-luna":{protocol:"responses",contextWindow:1e6},"muse-spark-1.3-contributor":{protocol:"responses",contextWindow:1048576,thinkingEfforts:T},"muse-spark-1.2-contributor":{protocol:"responses",contextWindow:1048576,thinkingEfforts:Ye},"claude-haiku-5-5":{protocol:"messages",contextWindow:1e6,maxOutputTokens:128e3},"minimax-m3":{protocol:"messages",contextWindow:1e6,maxOutputTokens:131072},"minimax-m2.7":{protocol:"messages",contextWindow:204800,thinkingEfforts:T,maxOutputTokens:131072},"qwen3.8-max":{protocol:"messages",contextWindow:1e6,maxOutputTokens:131072},"qwen3.8-flash":{protocol:"messages",contextWindow:1e6,maxOutputTokens:131072},"qwen3.7-plus":{protocol:"messages",contextWindow:1e6,maxOutputTokens:65536},"glm-5.3-flash":{protocol:"chat",contextWindow:1e6,developerRole:"system"},"glm-5.3":{protocol:"chat",contextWindow:1e6,thinkingEfforts:T},"glm-5.2":{protocol:"chat",contextWindow:1e6,thinkingEfforts:T},"kimi-k3.1-pro":{protocol:"chat",contextWindow:1048576,developerRole:"system"},"kimi-k3":{protocol:"chat",contextWindow:1048576},"kimi-k2.7-code":{protocol:"chat",contextWindow:262144,thinkingEfforts:T,developerRole:"system"},"longcat-2.5-preview-free":{protocol:"chat",contextWindow:1e6,thinkingEfforts:T},"longcat-2.0":{protocol:"chat"},"step-5-preview":{protocol:"chat"},"step-5-preview-free":{protocol:"chat",contextWindow:1e6,thinkingEfforts:T},"beam-free":{protocol:"chat"},"deepseek-v4.1-flash":{protocol:"chat",contextWindow:1e6},"deepseek-v4-pro":{protocol:"chat",contextWindow:1048576},"deepseek-v4-flash-vision-exp":{protocol:"chat",contextWindow:1e6},"mimo-v2.6-flash":{protocol:"chat",contextWindow:1048576},"mimo-v2.6-pro":{protocol:"chat",contextWindow:1048576},"mimo-v2.5":{protocol:"chat",contextWindow:1e6},"mimo-v2.5-pro":{protocol:"chat"},"minimax-m3.1-flash":{protocol:"chat"},"hy4-preview":{protocol:"chat"},hy3:{protocol:"chat"}},uo=_.strictObject({protocol:_.enum(["responses","chat","messages"]),contextWindow:_.number().int().positive().optional(),thinkingEfforts:_.array(_.enum(g)).min(1).optional(),maxOutputTokens:_.number().int().positive().optional(),developerRole:_.enum(["developer","system"]).optional()}),mo=o=>Object.entries(o??{}).some(([e,t])=>e.toLowerCase()==="user-agent"&&t.trim()!==""),ho=E.extend({baseURL:_.string().default(ao),defaultModel:_.string().default(lo),models:_.record(_.string(),uo).optional()}).refine(o=>mo(o.defaultHeaders),{message:"OpenCode Go needs a `User-Agent` in `defaultHeaders` naming the application, such as `my-agent/1.0`",path:["defaultHeaders"]}),fo=o=>{let e={...co};for(let[t,n]of Object.entries(o.models??{})){let s=Object.hasOwn(e,t)?e[t]:void 0;e[t]={...s,protocol:n.protocol,...n.contextWindow===void 0?{}:{contextWindow:n.contextWindow},...n.thinkingEfforts===void 0?{}:{thinkingEfforts:n.thinkingEfforts},...n.maxOutputTokens===void 0?{}:{maxOutputTokens:n.maxOutputTokens},...n.developerRole===void 0?{}:{developerRole:n.developerRole}}}return e};function Je(o){let e=ho.parse(o),t=fo(e);return Ze(t,e.defaultModel),{config:e,table:t}}function Ze(o,e){let t=Object.hasOwn(o,e)?o[e]:void 0;if(t===void 0)throw new p(b,`model '${e}', whose protocol is unknown \u2014 name it in the provider's \`models\``);if(t.protocol==="messages"&&t.maxOutputTokens===void 0)throw new p(b,`Messages model '${e}' with no output cap \u2014 name its \`maxOutputTokens\` in the provider's \`models\``);return t.protocol}var _o=o=>Object.entries(o).map(([e,t])=>t.thinkingEfforts===void 0?{id:e}:{id:e,thinkingEfforts:t.thinkingEfforts}),go=(o,e)=>(Object.hasOwn(o,e)?o[e].contextWindow:void 0)??null,xo=(o,e)=>e!=="system"||!o.messages.some(t=>t.role==="developer")?o:{...o,messages:o.messages.map(t=>t.role==="developer"?{...t,role:e}:t)},yo=o=>({[po]:o.threadId}),he=class extends W{constructor(e){let{config:t,table:n}=Je(e),s=A("OpenCode Go",t,e.client),r={name:b,headers:yo,streamIdleTimeoutMs:t.streamIdleTimeoutMs,...t.thinkingEffort===void 0?{}:{thinkingEffort:t.thinkingEffort}},i={...r,client:s,...t.extraBody===void 0?{}:{extraBody:t.extraBody}};super(b,a=>{let d=Ze(n,a.model);if(a.providerTools.length>0)throw new p(b,"provider-executed tools");return{protocol:d,call:d==="chat"?xo(a,n[a.model].developerRole):a}},{responses:new m({...i,replayByModel:!0}),chat:new v(i),messages:new D({...r,...t.apiKey===void 0?{}:{apiKey:t.apiKey},baseURL:t.baseURL,...t.defaultHeaders===void 0?{}:{defaultHeaders:t.defaultHeaders},maxOutputTokens:Object.fromEntries(Object.entries(n).flatMap(([a,d])=>d.maxOutputTokens===void 0?[]:[[a,d.maxOutputTokens]])),...e.fetch===void 0?{}:{fetch:e.fetch}})})}},Eo=o=>{let{config:e,table:t}=Je(o);return{name:b,defaultModel:e.defaultModel,defaultThinkingEffort:e.thinkingEffort,models:_o(t),capacity:n=>({contextWindow:go(t,n),providerTools:!1,toolResultImages:!1}),createClient:()=>new he(o),classify:n=>n instanceof h?V(n):u(n)}};export{se as CODEX_PROVIDER_NAME,Y as CodexCredentialError,Le as DEEPSEEK_RESPONSES_PROVIDER_NAME,k as OPENCODE_COPILOT_PROVIDER_NAME,b as OPENCODE_GO_PROVIDER_NAME,tt as codexAuthPath,kt as codexProvider,bt as deepseekProvider,Mt as openaiChatProvider,ht as openaiResponsesProvider,ro as opencodeCopilotProvider,Eo as opencodeGoProvider};
@@ -0,0 +1,73 @@
1
+ import OpenAI from 'openai';
2
+ import type { ChatCompletionChunk } from 'openai/resources/chat/completions';
3
+ import { z } from 'zod';
4
+ import type { ConversationMessage } from '../llm/primitives.js';
5
+ import type { LLMClient, StreamingLLMResponse } from '../llm/client.js';
6
+ import type { ModelRequest } from '../llm/request.js';
7
+ import type { LLMProvider } from '../llm/provider.js';
8
+ import type { DeepReadonly } from '../util/json.js';
9
+ import { type WithCredential } from './shared.js';
10
+ import { type CallHeaders } from './stream.js';
11
+ export declare const OPENAI_CHAT_DEFAULT_MODEL = "gpt-5.4";
12
+ export declare const OpenAIChatConfigSchema: z.ZodObject<{
13
+ apiKey: z.ZodOptional<z.ZodString>;
14
+ streamIdleTimeoutMs: z.ZodNullable<z.ZodNumber>;
15
+ defaultHeaders: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
16
+ extraBody: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
17
+ thinkingEffort: z.ZodOptional<z.ZodEnum<{
18
+ low: "low";
19
+ high: "high";
20
+ none: "none";
21
+ medium: "medium";
22
+ max: "max";
23
+ }>>;
24
+ baseURL: z.ZodDefault<z.ZodString>;
25
+ defaultModel: z.ZodDefault<z.ZodString>;
26
+ systemRole: z.ZodDefault<z.ZodEnum<{
27
+ system: "system";
28
+ developer: "developer";
29
+ }>>;
30
+ contextWindows: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodNumber>>;
31
+ }, z.core.$strip>;
32
+ export type OpenAIChatConfig = z.input<typeof OpenAIChatConfigSchema>;
33
+ type RequestPayload = Record<string, unknown>;
34
+ /**
35
+ * LLM client for the OpenAI Chat Completions API, and for the many gateways that speak it.
36
+ *
37
+ * What it cannot do is the reason it is not the direction: Chat Completions has no field for a
38
+ * model's opaque reasoning state. Reasoning text goes back as the `reasoning_content` vendor
39
+ * extension, which models that read it accept, but this client writes no `provider_state`.
40
+ * Provider-executed tools are refused outright rather than silently dropped.
41
+ */
42
+ export declare class OpenAIChatLLMClient implements LLMClient {
43
+ readonly providerName: string;
44
+ protected readonly client: OpenAI;
45
+ private readonly callHeaders;
46
+ /** Absent sends no effort, leaving it to the model; a named one, `none` included, is sent. */
47
+ private readonly thinkingEffort;
48
+ private readonly extraBody;
49
+ private readonly systemRole;
50
+ private readonly streamIdleTimeoutMs;
51
+ /**
52
+ * `name` is the provider the client speaks for (a gateway's); `headers` adds headers to each call.
53
+ * Both are the client's owner's: nothing subclasses the client to say them.
54
+ */
55
+ constructor(config: OpenAIChatConfig & {
56
+ client?: OpenAI;
57
+ name?: string;
58
+ headers?: CallHeaders;
59
+ });
60
+ buildRequest(call: ModelRequest): RequestPayload;
61
+ /** The one SDK call of this protocol; `headers` are the call's own, over the client's defaults. */
62
+ protected openStream(request: RequestPayload, headers: Record<string, string>, signal: AbortSignal): Promise<AsyncIterable<ChatCompletionChunk>>;
63
+ chat(call: ModelRequest): Promise<StreamingLLMResponse>;
64
+ }
65
+ export declare function toChatMessage(message: DeepReadonly<ConversationMessage>, provider?: string): unknown;
66
+ /**
67
+ * The OpenAI Chat Completions provider, and with a `baseURL` any gateway that speaks it. It declares
68
+ * no models and no windows of its own: a gateway serves whatever ids its operator configured, so the
69
+ * windows it declares are the ones `contextWindows` configures. It replays reasoning text but no
70
+ * opaque reasoning state, and provider-executed tools are refused.
71
+ */
72
+ export declare const openaiChatProvider: (config: WithCredential<OpenAIChatConfig>) => LLMProvider;
73
+ export {};
@@ -0,0 +1,109 @@
1
+ import OpenAI from 'openai';
2
+ import type { Response, ResponseInputItem, ResponseStreamEvent } from 'openai/resources/responses/responses';
3
+ import { z } from 'zod';
4
+ import type { ConversationMessage } from '../llm/primitives.js';
5
+ import type { LLMClient, ModelOption, StreamingLLMResponse } from '../llm/client.js';
6
+ import type { ModelRequest } from '../llm/request.js';
7
+ import type { LLMProvider } from '../llm/provider.js';
8
+ import type { DeepReadonly } from '../util/json.js';
9
+ import { type ProviderErrorFields, type WithCredential } from './shared.js';
10
+ import { type CallHeaders } from './stream.js';
11
+ export declare class UnsupportedResponseOutputError extends Error {
12
+ constructor(types: readonly string[]);
13
+ }
14
+ export declare const OPENAI_RESPONSES_DEFAULT_MODEL = "gpt-5.4";
15
+ /**
16
+ * The models agents are told about, with the efforts lagent can send. From the list the Codex
17
+ * backend serves, which marks them available in the API (checked 2026-09-26).
18
+ */
19
+ export declare const OPENAI_RESPONSES_MODELS: readonly ModelOption[];
20
+ /**
21
+ * The usable context window of each model this provider declares one for, in tokens.
22
+ *
23
+ * The `gpt-6-*` figures come from the Codex CLI's model cache for the same models on the Codex
24
+ * backend: a `context_window` of 272,000 with its `effective_context_window_percent` of 95 applied,
25
+ * 258,400 (`~/.codex/models_cache.json`, checked 2026-10-03). `gpt-5.4`, the default, is not in
26
+ * that cache; it is given the same 258,400 as the conservative figure for the family. The raw figure
27
+ * is itself conservative: the Codex backend accepted 285,889 input tokens on a model it lists at
28
+ * 272,000 (measured 2026-10-03). A model not listed here has no window.
29
+ */
30
+ export declare const OPENAI_RESPONSES_CONTEXT_WINDOWS: Readonly<Record<string, number>>;
31
+ export declare const OpenAIResponsesConfigSchema: z.ZodObject<{
32
+ apiKey: z.ZodOptional<z.ZodString>;
33
+ streamIdleTimeoutMs: z.ZodNullable<z.ZodNumber>;
34
+ defaultHeaders: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
35
+ extraBody: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
36
+ thinkingEffort: z.ZodOptional<z.ZodEnum<{
37
+ low: "low";
38
+ high: "high";
39
+ none: "none";
40
+ medium: "medium";
41
+ max: "max";
42
+ }>>;
43
+ baseURL: z.ZodDefault<z.ZodString>;
44
+ defaultModel: z.ZodDefault<z.ZodString>;
45
+ }, z.core.$strip>;
46
+ export type OpenAIResponsesConfig = z.input<typeof OpenAIResponsesConfigSchema>;
47
+ type RequestPayload = Record<string, unknown>;
48
+ /**
49
+ * LLM client for the OpenAI Responses API. History is application-managed (`store: false`) and
50
+ * provider-owned output items round-trip through `ConversationMessage.provider_state`, so
51
+ * encrypted reasoning survives across turns.
52
+ */
53
+ export declare class OpenAIResponsesLLMClient implements LLMClient {
54
+ readonly providerName: string;
55
+ protected readonly client: OpenAI;
56
+ private readonly callHeaders;
57
+ private readonly replayByModel;
58
+ private readonly thinkingEffort;
59
+ private readonly extraBody;
60
+ private readonly streamIdleTimeoutMs;
61
+ /**
62
+ * `name` is the provider the client speaks for (Codex's, a gateway's); `headers` adds headers to
63
+ * each call; `replayByModel` narrows replayable state to the model that wrote it, for a gateway
64
+ * serving several vendors under one name. All are the client's owner's: nothing subclasses the
65
+ * client to say them.
66
+ */
67
+ constructor(config: OpenAIResponsesConfig & {
68
+ client?: OpenAI;
69
+ name?: string;
70
+ headers?: CallHeaders;
71
+ replayByModel?: boolean;
72
+ });
73
+ buildRequest(call: ModelRequest): RequestPayload;
74
+ /**
75
+ * Whose output a request may splice back verbatim, and the tag its own output is written under:
76
+ * the client's name, so another backend's state is rebuilt from the normalized fields; with
77
+ * `replayByModel`, the name and the model.
78
+ */
79
+ private replayTag;
80
+ /** The one SDK call of this protocol; `headers` are the call's own, over the client's defaults. */
81
+ protected openStream(request: RequestPayload, headers: Record<string, string>, signal: AbortSignal): Promise<AsyncIterable<ResponseStreamEvent>>;
82
+ chat(call: ModelRequest): Promise<StreamingLLMResponse>;
83
+ /**
84
+ * Whether a provider error says the request exceeded the model's context window: the structured
85
+ * code `context_length_exceeded`, on a rejected request and inside the stream alike (where the
86
+ * Codex backend reported it, with type `invalid_request_error`, param `input` and no count;
87
+ * measured 2026-10-03). A variant whose backend has no code for it overrides this.
88
+ */
89
+ protected isContextOverflow(fields: ProviderErrorFields): boolean;
90
+ }
91
+ /**
92
+ * Maps the conversation to Responses input items. An assistant message carrying **this client's**
93
+ * own state is spliced back verbatim; anything else is synthesized from the normalized fields.
94
+ *
95
+ * The tag is the client's replay tag (its name unless it narrows it) rather than this module's,
96
+ * because a credential variant talks to a different backend: Codex's encrypted reasoning is not
97
+ * something `api.openai.com` can read, so whichever client did not write it rebuilds the message from
98
+ * the normalized fields instead.
99
+ */
100
+ export declare function toResponsesInput(messages: readonly DeepReadonly<ConversationMessage>[], replayTag?: string): ResponseInputItem[];
101
+ /** Normalizes a completed response into a `ConversationMessage`, tagged for the client that got it. */
102
+ export declare function responseToMessage(response: Response, replayTag?: string): ConversationMessage;
103
+ /**
104
+ * The OpenAI Responses provider, at OpenAI's endpoint unless `baseURL` names another. Building one
105
+ * registers nothing, so a host can read its defaults and models first (see `defaultRoute`);
106
+ * `registerProvider(ctx, openaiResponsesProvider(config), { retry })` registers it.
107
+ */
108
+ export declare const openaiResponsesProvider: (config: WithCredential<OpenAIResponsesConfig>) => LLMProvider;
109
+ export {};
@@ -0,0 +1,23 @@
1
+ import { z } from 'zod';
2
+ import type { LLMProvider } from '../llm/provider.js';
3
+ export declare const OPENCODE_COPILOT_PROVIDER_NAME = "opencode-copilot";
4
+ declare const ConfigSchema: z.ZodObject<{
5
+ authPath: z.ZodString;
6
+ streamIdleTimeoutMs: z.ZodNullable<z.ZodNumber>;
7
+ defaultModel: z.ZodOptional<z.ZodString>;
8
+ thinkingEffort: z.ZodOptional<z.ZodEnum<{
9
+ low: "low";
10
+ high: "high";
11
+ none: "none";
12
+ medium: "medium";
13
+ max: "max";
14
+ }>>;
15
+ }, z.core.$strict>;
16
+ export type OpenCodeCopilotConfig = z.input<typeof ConfigSchema>;
17
+ /**
18
+ * Initialize before registration. Reads the OpenCode login at `authPath`, then discovers models;
19
+ * any startup failure rejects, so no provider is offered without a live catalog. No login or refresh.
20
+ * Protocols and headers follow anomalyco/opencode's github-copilot plugin (checked 2026-10-14).
21
+ */
22
+ export declare const opencodeCopilotProvider: (config: OpenCodeCopilotConfig) => Promise<LLMProvider>;
23
+ export {};
@@ -0,0 +1,109 @@
1
+ import type OpenAI from 'openai';
2
+ import { z } from 'zod';
3
+ import type { ModelOption } from '../llm/client.js';
4
+ import type { LLMProvider } from '../llm/provider.js';
5
+ import type { ThinkingEffort } from '../llm/primitives.js';
6
+ import { GatewayLLMClient, type GatewayProtocol } from './gateway.js';
7
+ import { type WithCredential } from './shared.js';
8
+ export declare const OPENCODE_GO_BASE_URL = "https://opencode.ai/zen/go/v1";
9
+ export declare const OPENCODE_GO_PROVIDER_NAME = "opencode-go";
10
+ export declare const OPENCODE_GO_DEFAULT_MODEL = "deepseek-v4.1-flash";
11
+ /**
12
+ * A model Go serves: the protocol it answers on, its context window when one is known, the efforts
13
+ * it accepts when it was found to refuse some, for a Messages model, which needs one on every
14
+ * request, its output cap, and for a Chat model that refuses the `developer` role, the role its
15
+ * notices go as instead.
16
+ */
17
+ type GoModel = {
18
+ readonly protocol: GatewayProtocol;
19
+ readonly contextWindow?: number;
20
+ readonly thinkingEfforts?: readonly ThinkingEffort[];
21
+ readonly maxOutputTokens?: number;
22
+ readonly developerRole?: DeveloperRole;
23
+ };
24
+ /** The role a Chat model is sent lagent's notices as: `developer` as they are, or `system`, in place. */
25
+ type DeveloperRole = 'developer' | 'system';
26
+ type GoModelTable = Readonly<Record<string, GoModel>>;
27
+ /**
28
+ * Go's documented Responses, Chat Completions and Messages models, plus retained legacy ids.
29
+ * Google-native Gemini is not supported. Protocols from https://opencode.ai/v2/docs/console/go,
30
+ * with additions confirmed by https://opencode.ai/inference/go/v1/models (checked 2026-10-24).
31
+ * Windows in tokens come from the `opencode-go` entry of https://models.dev/api.json: its `input`
32
+ * limit where given, else `context`, undiscounted (original entries checked 2026-10-11, additions
33
+ * 2026-10-24). Missing limits stay unknown. A Messages model's output cap is that entry's `output`
34
+ * limit (checked 2026-10-12). `GET /models` lists ids but no protocol; discovery is not done at runtime.
35
+ */
36
+ export declare const OPENCODE_GO_MODEL_TABLE: GoModelTable;
37
+ export declare const OpenCodeGoConfigSchema: z.ZodObject<{
38
+ apiKey: z.ZodOptional<z.ZodString>;
39
+ streamIdleTimeoutMs: z.ZodNullable<z.ZodNumber>;
40
+ defaultHeaders: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
41
+ extraBody: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
42
+ thinkingEffort: z.ZodOptional<z.ZodEnum<{
43
+ low: "low";
44
+ high: "high";
45
+ none: "none";
46
+ medium: "medium";
47
+ max: "max";
48
+ }>>;
49
+ baseURL: z.ZodDefault<z.ZodString>;
50
+ defaultModel: z.ZodDefault<z.ZodString>;
51
+ models: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodObject<{
52
+ protocol: z.ZodEnum<{
53
+ messages: "messages";
54
+ responses: "responses";
55
+ chat: "chat";
56
+ }>;
57
+ contextWindow: z.ZodOptional<z.ZodNumber>;
58
+ thinkingEfforts: z.ZodOptional<z.ZodArray<z.ZodEnum<{
59
+ low: "low";
60
+ high: "high";
61
+ none: "none";
62
+ medium: "medium";
63
+ max: "max";
64
+ }>>>;
65
+ maxOutputTokens: z.ZodOptional<z.ZodNumber>;
66
+ developerRole: z.ZodOptional<z.ZodEnum<{
67
+ system: "system";
68
+ developer: "developer";
69
+ }>>;
70
+ }, z.core.$strict>>>;
71
+ }, z.core.$strip>;
72
+ export type OpenCodeGoConfig = z.input<typeof OpenCodeGoConfigSchema>;
73
+ type ParsedConfig = z.output<typeof OpenCodeGoConfigSchema>;
74
+ /**
75
+ * Go's configuration, parsed, with its default model checked to be one lagent can speak to: a model
76
+ * whose protocol nobody named, or a Messages model with no output cap, fails here rather than on the
77
+ * first turn.
78
+ */
79
+ export declare function parseOpenCodeGoConfig(config: OpenCodeGoConfig): {
80
+ readonly config: ParsedConfig;
81
+ readonly table: GoModelTable;
82
+ };
83
+ /** The models agents are told about: every model shipped and configured. */
84
+ export declare const openCodeGoModels: (table: GoModelTable) => readonly ModelOption[];
85
+ /** The declared window of `model`, `null` where neither the table nor the configuration gives one. */
86
+ export declare const openCodeGoWindow: (table: GoModelTable, model: string) => number | null;
87
+ /**
88
+ * The OpenCode Go gateway: one credential and one endpoint in front of models that each answer on
89
+ * one protocol. Each call goes to the adapter for its model's protocol, Responses, Chat Completions
90
+ * or Anthropic Messages, never tried on another endpoint. Responses and Chat share one SDK client;
91
+ * Messages goes over `fetch`, with the key as `x-api-key`. Every request carries its thread as Go's
92
+ * session header. Go serves several vendors' models under one name, and one vendor's encrypted
93
+ * reasoning or signed thinking is nothing another can read: output replays only to the model that
94
+ * wrote it, and a thread changing model is rebuilt from the normalized fields.
95
+ */
96
+ export declare class OpenCodeGoLLMClient extends GatewayLLMClient {
97
+ constructor(config: OpenCodeGoConfig & {
98
+ client?: OpenAI;
99
+ fetch?: typeof globalThis.fetch;
100
+ });
101
+ }
102
+ /**
103
+ * The OpenCode Go gateway (`https://opencode.ai/zen/go/v1`): one subscription key in front of many
104
+ * vendors' models, each answering on one protocol: OpenAI Responses, Chat Completions or Anthropic
105
+ * Messages, each served by its own client. The host names itself with a
106
+ * `User-Agent` in `defaultHeaders`; each request carries its thread as Go's session header.
107
+ */
108
+ export declare const opencodeGoProvider: (config: WithCredential<OpenCodeGoConfig>) => LLMProvider;
109
+ export {};
@@ -0,0 +1,112 @@
1
+ import OpenAI from 'openai';
2
+ import { z } from 'zod';
3
+ import type { FailureClassification } from '../llm/failure.js';
4
+ /**
5
+ * A provider's configuration with its credential named: the host resolves it, from wherever it keeps
6
+ * it, and says so even when it has none. A provider without one can still be described, its defaults
7
+ * and models read; building a client for it then fails, naming what is missing.
8
+ */
9
+ export type WithCredential<Config> = Config & {
10
+ readonly apiKey: string | undefined;
11
+ };
12
+ /** Extra top-level request fields merged into every call (vendor extensions), minus the refused ones. */
13
+ export declare const ExtraBodySchema: z.ZodRecord<z.ZodString, z.ZodUnknown>;
14
+ /**
15
+ * A provider's declared context windows, by model id. A model with no entry has no window: `null`,
16
+ * never a guess.
17
+ */
18
+ export declare const contextWindowOf: (windows: Readonly<Record<string, number>>, model: string) => number | null;
19
+ /** The structured fields of a provider error, wherever it arrived: a rejected request or the stream. */
20
+ export type ProviderErrorFields = {
21
+ readonly code?: unknown;
22
+ readonly type?: unknown;
23
+ readonly message?: unknown;
24
+ };
25
+ /** The OpenAI-shaped code for a request over the model's context window. */
26
+ export declare const CONTEXT_LENGTH_EXCEEDED = "context_length_exceeded";
27
+ /**
28
+ * A credential problem the transport found while authorizing a request. The SDK wraps whatever a
29
+ * custom `fetch` throws in its connection error, so {@link classifyProviderError} hands it back as
30
+ * itself: a login that cannot be used reads as that login's problem, not as a failed connection.
31
+ */
32
+ export declare class TransportCredentialError extends Error {
33
+ }
34
+ /**
35
+ * `error` as the failure it is, else unchanged. An SDK `APIError` has fields to read: a rejected
36
+ * request, or an error event the SDK raised while reading the stream. When `isOverflow` recognizes
37
+ * them it is the overflow, with the message the provider's own, without the SDK's status prefix.
38
+ * The SDK's own abort error, once the request's `signal` fired, is that signal's reason: the
39
+ * caller's cancellation, as the engine recognises it, whatever the SDK names its class. A connection
40
+ * error that carries a {@link TransportCredentialError} is that error.
41
+ */
42
+ export declare function classifyProviderError(provider: string, error: unknown, isOverflow: (fields: ProviderErrorFields) => boolean, signal: AbortSignal | undefined): unknown;
43
+ /**
44
+ * A failure a provider reported inside its stream (a `response.failed` or `error` event), with the
45
+ * structured fields it gave. There is no HTTP status: the request had already succeeded.
46
+ */
47
+ export declare class ProviderStreamError extends Error {
48
+ readonly code: unknown;
49
+ readonly type: unknown;
50
+ constructor(fields: ProviderErrorFields, fallback: string);
51
+ }
52
+ /**
53
+ * The failure kind of an error from an OpenAI-shaped client, by structured evidence only: the HTTP
54
+ * status and error code of a rejected request, the code of a stream's error event, the SDK's
55
+ * transport errors, and socket error codes. A spent quota or usage limit is `quota` whether its name
56
+ * comes in the code or the type, on any status or on a failure with none; otherwise a status is read
57
+ * as every protocol reads it (`statusKind`). `retryAfterMs` is read from the
58
+ * `retry-after-ms` or `retry-after` header, never from prose. Anything unrecognised is `other`.
59
+ */
60
+ export declare function classifyOpenAIFailure(error: unknown, now?: number): FailureClassification;
61
+ /**
62
+ * The request option every model request carries, an injected SDK client's included: the SDK retries
63
+ * nothing. Retrying is the engine's (`ctx.llm`), once, before any output, by the failure's kind.
64
+ */
65
+ export declare const NO_SDK_RETRIES: {
66
+ readonly maxRetries: 0;
67
+ };
68
+ /** The OpenAI API's public endpoint: the protocol default of the providers that speak to OpenAI. */
69
+ export declare const OPENAI_API_BASE_URL = "https://api.openai.com/v1";
70
+ /**
71
+ * What every OpenAI-shaped provider is configured with. Each one extends it with its own
72
+ * `defaultModel`, its endpoint's default, and whatever its API alone has. The credential is the
73
+ * host's to resolve: lagent reads no environment variable for it.
74
+ */
75
+ export declare const OpenAICommonConfigSchema: z.ZodObject<{
76
+ apiKey: z.ZodOptional<z.ZodString>;
77
+ streamIdleTimeoutMs: z.ZodNullable<z.ZodNumber>;
78
+ baseURL: z.ZodOptional<z.ZodString>;
79
+ defaultHeaders: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
80
+ extraBody: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
81
+ thinkingEffort: z.ZodOptional<z.ZodEnum<{
82
+ low: "low";
83
+ high: "high";
84
+ none: "none";
85
+ medium: "medium";
86
+ max: "max";
87
+ }>>;
88
+ }, z.core.$strip>;
89
+ /**
90
+ * The SDK client for an OpenAI-shaped endpoint, the one constructor every provider here uses. The
91
+ * SDK fills an option left out from the process environment (`OPENAI_API_KEY`, `OPENAI_BASE_URL`,
92
+ * `OPENAI_ORG_ID`, `OPENAI_PROJECT_ID`, `OPENAI_ADMIN_KEY`, `OPENAI_WEBHOOK_SECRET`, `OPENAI_LOG`),
93
+ * so each is given here: the credential and endpoint the caller's, the log level the SDK's default,
94
+ * the rest, which lagent never uses, none. Its `OPENAI_CUSTOM_HEADERS` merge is undone, so a request
95
+ * carries the SDK's own headers, its authorization and the caller's `defaultHeaders`, and nothing
96
+ * from the environment.
97
+ */
98
+ export declare function openAIClient(options: {
99
+ readonly apiKey: string;
100
+ readonly baseURL: string;
101
+ readonly defaultHeaders?: Record<string, string>;
102
+ readonly fetch?: typeof globalThis.fetch;
103
+ }): OpenAI;
104
+ /**
105
+ * The client a provider's adapter sends with: the one injected, else one built from its
106
+ * configuration, which then has to carry the credential.
107
+ */
108
+ export declare function adapterClient(provider: string, config: {
109
+ readonly apiKey?: string | undefined;
110
+ readonly baseURL: string;
111
+ readonly defaultHeaders?: Record<string, string> | undefined;
112
+ }, injected: OpenAI | undefined): OpenAI;