@sortedyuan/maybecode 0.3.2 → 0.5.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 (295) hide show
  1. package/README.md +166 -55
  2. package/README.zh-CN.md +267 -0
  3. package/dist/application.d.ts +40 -34
  4. package/dist/application.d.ts.map +1 -1
  5. package/dist/application.js +290 -170
  6. package/dist/application.js.map +1 -1
  7. package/dist/args.d.ts +2 -2
  8. package/dist/args.d.ts.map +1 -1
  9. package/dist/args.js +50 -27
  10. package/dist/args.js.map +1 -1
  11. package/dist/bin.js +82 -71
  12. package/dist/bin.js.map +4 -4
  13. package/dist/cli/chunk-3IORPKBL.js +3572 -0
  14. package/dist/cli/chunk-3IORPKBL.js.map +7 -0
  15. package/dist/cli/{chunk-LVTRXPDS.js → chunk-4B2Z6KW7.js} +1547 -1536
  16. package/dist/cli/chunk-4B2Z6KW7.js.map +7 -0
  17. package/dist/cli/{chunk-JT6VBKOM.js → chunk-4WG6JIJJ.js} +127 -33
  18. package/dist/cli/{chunk-JT6VBKOM.js.map → chunk-4WG6JIJJ.js.map} +3 -3
  19. package/dist/cli/{chunk-K5JWPNSY.js → chunk-5SLWALZK.js} +3521 -16164
  20. package/dist/cli/chunk-5SLWALZK.js.map +7 -0
  21. package/dist/cli/chunk-MNBYXL5Y.js +132 -0
  22. package/dist/cli/chunk-MNBYXL5Y.js.map +7 -0
  23. package/dist/cli/{chunk-F4XRPLUM.js → chunk-SLWLUEHQ.js} +226 -86
  24. package/dist/cli/chunk-SLWLUEHQ.js.map +7 -0
  25. package/dist/cli/chunk-UQDZ55LQ.js +199 -0
  26. package/dist/cli/chunk-UQDZ55LQ.js.map +7 -0
  27. package/dist/cli/{chunk-7ISOHFS7.js → chunk-WMSG5ZTR.js} +717 -388
  28. package/dist/cli/chunk-WMSG5ZTR.js.map +7 -0
  29. package/dist/cli/chunk-WVIRS76R.js +4057 -0
  30. package/dist/cli/chunk-WVIRS76R.js.map +7 -0
  31. package/dist/cli/{chunk-HOU5ITUK.js → chunk-XTEMRAQW.js} +1 -1
  32. package/dist/cli/chunk-XTEMRAQW.js.map +7 -0
  33. package/dist/cli/chunk-Z3BOPBVU.js +91 -0
  34. package/dist/cli/chunk-Z3BOPBVU.js.map +7 -0
  35. package/dist/cli/{configured-WHY3GGAJ.js → configured-ACNM6TRQ.js} +10 -9
  36. package/dist/cli/{file-type-R2T7TBHI.js → file-type-HLHPV7WC.js} +817 -13
  37. package/dist/cli/file-type-HLHPV7WC.js.map +7 -0
  38. package/dist/cli/mcp-auth-XD5U7WCV.js +74 -0
  39. package/dist/cli/mcp-auth-XD5U7WCV.js.map +7 -0
  40. package/dist/cli/onboarding-WQWCPYEO.js +530 -0
  41. package/dist/cli/onboarding-WQWCPYEO.js.map +7 -0
  42. package/dist/cli/onboarding-check-HRRI5OJ7.js +32 -0
  43. package/dist/cli/onboarding-check-HRRI5OJ7.js.map +7 -0
  44. package/dist/cli/{retained-tui-VJ3VX4R3.js → retained-tui-QF5VMYLC.js} +788 -332
  45. package/dist/cli/retained-tui-QF5VMYLC.js.map +7 -0
  46. package/dist/cli/{sixel-LWTCM76G.js → sixel-ISZ4FZ3U.js} +37 -37
  47. package/dist/cli/{sixel-LWTCM76G.js.map → sixel-ISZ4FZ3U.js.map} +1 -1
  48. package/dist/cli/{team-T7G7PPNN.js → team-O2I5BXHM.js} +7 -6
  49. package/dist/cli/{team-v2-JGBBQ7FR.js → team-v2-YYO2G7DJ.js} +816 -390
  50. package/dist/cli/team-v2-YYO2G7DJ.js.map +7 -0
  51. package/dist/cli/{web-server-FOMNPY7Q.js → web-server-SXMH6FGA.js} +55 -19
  52. package/dist/cli/web-server-SXMH6FGA.js.map +7 -0
  53. package/dist/cli/{web-ui-COB6PKC5.js → web-ui-UWQUFE4W.js} +7 -6
  54. package/dist/config-schema.json +337 -0
  55. package/dist/configured.d.ts +18 -11
  56. package/dist/configured.d.ts.map +1 -1
  57. package/dist/configured.js +213 -390
  58. package/dist/configured.js.map +1 -1
  59. package/dist/controller.d.ts +19 -18
  60. package/dist/controller.d.ts.map +1 -1
  61. package/dist/delegation-commands.d.ts +1 -1
  62. package/dist/delegation-commands.d.ts.map +1 -1
  63. package/dist/delegation-commands.js +8 -8
  64. package/dist/delegation-commands.js.map +1 -1
  65. package/dist/errors.d.ts +2 -1
  66. package/dist/errors.d.ts.map +1 -1
  67. package/dist/errors.js +2 -1
  68. package/dist/errors.js.map +1 -1
  69. package/dist/events.d.ts +8 -6
  70. package/dist/events.d.ts.map +1 -1
  71. package/dist/fork-picker.d.ts.map +1 -1
  72. package/dist/fork-picker.js +19 -5
  73. package/dist/fork-picker.js.map +1 -1
  74. package/dist/git-request.d.ts +6 -6
  75. package/dist/git-request.d.ts.map +1 -1
  76. package/dist/git-request.js +28 -15
  77. package/dist/git-request.js.map +1 -1
  78. package/dist/goal-commands.d.ts +1 -1
  79. package/dist/goal-commands.d.ts.map +1 -1
  80. package/dist/goal-commands.js +12 -5
  81. package/dist/goal-commands.js.map +1 -1
  82. package/dist/index.d.ts +5 -37
  83. package/dist/index.d.ts.map +1 -1
  84. package/dist/index.js +3 -36
  85. package/dist/index.js.map +1 -1
  86. package/dist/instructions.d.ts +2 -7
  87. package/dist/instructions.d.ts.map +1 -1
  88. package/dist/instructions.js +7 -15
  89. package/dist/instructions.js.map +1 -1
  90. package/dist/keymap.d.ts +2 -2
  91. package/dist/keymap.d.ts.map +1 -1
  92. package/dist/keymap.js +2 -2
  93. package/dist/keymap.js.map +1 -1
  94. package/dist/maybecode-config.schema.json +1765 -0
  95. package/dist/mcp-auth.d.ts +1 -1
  96. package/dist/mcp-auth.d.ts.map +1 -1
  97. package/dist/mcp-auth.js +11 -8
  98. package/dist/mcp-auth.js.map +1 -1
  99. package/dist/mcp-commands.d.ts.map +1 -1
  100. package/dist/mcp-commands.js +18 -4
  101. package/dist/mcp-commands.js.map +1 -1
  102. package/dist/mcp-interaction-ui.d.ts.map +1 -1
  103. package/dist/mcp-interaction-ui.js +11 -4
  104. package/dist/mcp-interaction-ui.js.map +1 -1
  105. package/dist/media-history.d.ts +1 -1
  106. package/dist/media-history.d.ts.map +1 -1
  107. package/dist/media-history.js +8 -2
  108. package/dist/media-history.js.map +1 -1
  109. package/dist/model-picker.d.ts.map +1 -1
  110. package/dist/model-picker.js +10 -11
  111. package/dist/model-picker.js.map +1 -1
  112. package/dist/model-transition.d.ts +11 -0
  113. package/dist/model-transition.d.ts.map +1 -0
  114. package/dist/model-transition.js +48 -0
  115. package/dist/model-transition.js.map +1 -0
  116. package/dist/model.d.ts +2 -2
  117. package/dist/model.d.ts.map +1 -1
  118. package/dist/model.js +8 -4
  119. package/dist/model.js.map +1 -1
  120. package/dist/onboarding-check.d.ts +3 -0
  121. package/dist/onboarding-check.d.ts.map +1 -0
  122. package/dist/onboarding-check.js +22 -0
  123. package/dist/onboarding-check.js.map +1 -0
  124. package/dist/onboarding.d.ts +6 -0
  125. package/dist/onboarding.d.ts.map +1 -0
  126. package/dist/onboarding.js +463 -0
  127. package/dist/onboarding.js.map +1 -0
  128. package/dist/plugins/application.d.ts +6 -4
  129. package/dist/plugins/application.d.ts.map +1 -1
  130. package/dist/plugins/application.js +106 -52
  131. package/dist/plugins/application.js.map +1 -1
  132. package/dist/plugins/instructions.d.ts +1 -1
  133. package/dist/plugins/instructions.d.ts.map +1 -1
  134. package/dist/plugins/instructions.js +24 -11
  135. package/dist/plugins/instructions.js.map +1 -1
  136. package/dist/plugins/resources.d.ts +2 -2
  137. package/dist/plugins/resources.d.ts.map +1 -1
  138. package/dist/plugins/resources.js +22 -12
  139. package/dist/plugins/resources.js.map +1 -1
  140. package/dist/policy.d.ts +1 -1
  141. package/dist/policy.d.ts.map +1 -1
  142. package/dist/policy.js +59 -11
  143. package/dist/policy.js.map +1 -1
  144. package/dist/run.d.ts +2 -0
  145. package/dist/run.d.ts.map +1 -1
  146. package/dist/run.js +38 -33
  147. package/dist/run.js.map +1 -1
  148. package/dist/runtime-instructions.d.ts +1 -1
  149. package/dist/runtime-instructions.d.ts.map +1 -1
  150. package/dist/runtime-instructions.js +15 -7
  151. package/dist/runtime-instructions.js.map +1 -1
  152. package/dist/session-navigation.d.ts +6 -0
  153. package/dist/session-navigation.d.ts.map +1 -0
  154. package/dist/session-navigation.js +64 -0
  155. package/dist/session-navigation.js.map +1 -0
  156. package/dist/session-picker.d.ts +1 -1
  157. package/dist/session-picker.d.ts.map +1 -1
  158. package/dist/session-picker.js +23 -32
  159. package/dist/session-picker.js.map +1 -1
  160. package/dist/settings.d.ts +718 -0
  161. package/dist/settings.d.ts.map +1 -0
  162. package/dist/settings.js +14 -0
  163. package/dist/settings.js.map +1 -0
  164. package/dist/skills.d.ts +1 -1
  165. package/dist/skills.d.ts.map +1 -1
  166. package/dist/skills.js +10 -12
  167. package/dist/skills.js.map +1 -1
  168. package/dist/slash-commands.d.ts +2 -2
  169. package/dist/slash-commands.d.ts.map +1 -1
  170. package/dist/slash-commands.js +149 -67
  171. package/dist/slash-commands.js.map +1 -1
  172. package/dist/team-execution.d.ts +10 -0
  173. package/dist/team-execution.d.ts.map +1 -0
  174. package/dist/team-execution.js +29 -0
  175. package/dist/team-execution.js.map +1 -0
  176. package/dist/team-patches.d.ts.map +1 -1
  177. package/dist/team-patches.js +149 -52
  178. package/dist/team-patches.js.map +1 -1
  179. package/dist/team-plan.d.ts +2 -2
  180. package/dist/team-plan.d.ts.map +1 -1
  181. package/dist/team-plan.js +115 -34
  182. package/dist/team-plan.js.map +1 -1
  183. package/dist/team-recovery.d.ts +1 -1
  184. package/dist/team-recovery.d.ts.map +1 -1
  185. package/dist/team-recovery.js +40 -10
  186. package/dist/team-recovery.js.map +1 -1
  187. package/dist/team-v2.d.ts.map +1 -1
  188. package/dist/team-v2.js +335 -104
  189. package/dist/team-v2.js.map +1 -1
  190. package/dist/team-verification.d.ts +4 -2
  191. package/dist/team-verification.d.ts.map +1 -1
  192. package/dist/team-verification.js +300 -97
  193. package/dist/team-verification.js.map +1 -1
  194. package/dist/team.d.ts +2 -2
  195. package/dist/team.d.ts.map +1 -1
  196. package/dist/team.js +172 -62
  197. package/dist/team.js.map +1 -1
  198. package/dist/terminal-web.d.ts +1 -0
  199. package/dist/terminal-web.d.ts.map +1 -1
  200. package/dist/terminal-web.js +28 -10
  201. package/dist/terminal-web.js.map +1 -1
  202. package/dist/ui/actions.d.ts.map +1 -1
  203. package/dist/ui/actions.js.map +1 -1
  204. package/dist/ui/retained-tui.d.ts.map +1 -1
  205. package/dist/ui/retained-tui.js +231 -173
  206. package/dist/ui/retained-tui.js.map +1 -1
  207. package/dist/ui/{prototype-view.d.ts → terminal-view.d.ts} +7 -7
  208. package/dist/ui/terminal-view.d.ts.map +1 -0
  209. package/dist/ui/{prototype-view.js → terminal-view.js} +185 -98
  210. package/dist/ui/terminal-view.js.map +1 -0
  211. package/dist/web-commands.d.ts.map +1 -1
  212. package/dist/web-commands.js +160 -57
  213. package/dist/web-commands.js.map +1 -1
  214. package/dist/web-extension.d.ts.map +1 -1
  215. package/dist/web-extension.js +14 -4
  216. package/dist/web-extension.js.map +1 -1
  217. package/dist/web-server.d.ts.map +1 -1
  218. package/dist/web-server.js +2 -1
  219. package/dist/web-server.js.map +1 -1
  220. package/dist/web-ui.d.ts.map +1 -1
  221. package/dist/web-ui.js +167 -40
  222. package/dist/web-ui.js.map +1 -1
  223. package/dist/workspace-configuration.d.ts +7 -0
  224. package/dist/workspace-configuration.d.ts.map +1 -0
  225. package/dist/workspace-configuration.js +134 -0
  226. package/dist/workspace-configuration.js.map +1 -0
  227. package/dist/workspace-state.d.ts +20 -0
  228. package/dist/workspace-state.d.ts.map +1 -0
  229. package/dist/workspace-state.js +2 -0
  230. package/dist/workspace-state.js.map +1 -0
  231. package/dist/workspace.d.ts +26 -43
  232. package/dist/workspace.d.ts.map +1 -1
  233. package/dist/workspace.js +261 -323
  234. package/dist/workspace.js.map +1 -1
  235. package/package.json +21 -31
  236. package/dist/cli/chunk-7ISOHFS7.js.map +0 -7
  237. package/dist/cli/chunk-F4XRPLUM.js.map +0 -7
  238. package/dist/cli/chunk-H7SNBFO4.js +0 -5522
  239. package/dist/cli/chunk-H7SNBFO4.js.map +0 -7
  240. package/dist/cli/chunk-HOU5ITUK.js.map +0 -7
  241. package/dist/cli/chunk-K5JWPNSY.js.map +0 -7
  242. package/dist/cli/chunk-LVTRXPDS.js.map +0 -7
  243. package/dist/cli/chunk-VAZMCNBB.js +0 -686
  244. package/dist/cli/chunk-VAZMCNBB.js.map +0 -7
  245. package/dist/cli/chunk-WOFEI42C.js +0 -7820
  246. package/dist/cli/chunk-WOFEI42C.js.map +0 -7
  247. package/dist/cli/file-type-R2T7TBHI.js.map +0 -7
  248. package/dist/cli/mcp-auth-UNRHSIKJ.js +0 -63
  249. package/dist/cli/mcp-auth-UNRHSIKJ.js.map +0 -7
  250. package/dist/cli/retained-tui-VJ3VX4R3.js.map +0 -7
  251. package/dist/cli/team-v2-JGBBQ7FR.js.map +0 -7
  252. package/dist/cli/tui-SA74DKMA.js +0 -1705
  253. package/dist/cli/tui-SA74DKMA.js.map +0 -7
  254. package/dist/cli/web-server-FOMNPY7Q.js.map +0 -7
  255. package/dist/delegation.d.ts +0 -2
  256. package/dist/delegation.d.ts.map +0 -1
  257. package/dist/delegation.js +0 -2
  258. package/dist/delegation.js.map +0 -1
  259. package/dist/history-memory.d.ts +0 -2
  260. package/dist/history-memory.d.ts.map +0 -1
  261. package/dist/history-memory.js +0 -2
  262. package/dist/history-memory.js.map +0 -1
  263. package/dist/subagent-budget.d.ts +0 -2
  264. package/dist/subagent-budget.d.ts.map +0 -1
  265. package/dist/subagent-budget.js +0 -2
  266. package/dist/subagent-budget.js.map +0 -1
  267. package/dist/subagent-files.d.ts +0 -2
  268. package/dist/subagent-files.d.ts.map +0 -1
  269. package/dist/subagent-files.js +0 -2
  270. package/dist/subagent-files.js.map +0 -1
  271. package/dist/subagent-host.d.ts +0 -2
  272. package/dist/subagent-host.d.ts.map +0 -1
  273. package/dist/subagent-host.js +0 -2
  274. package/dist/subagent-host.js.map +0 -1
  275. package/dist/subagent-instructions.d.ts +0 -2
  276. package/dist/subagent-instructions.d.ts.map +0 -1
  277. package/dist/subagent-instructions.js +0 -2
  278. package/dist/subagent-instructions.js.map +0 -1
  279. package/dist/subagents.d.ts +0 -2
  280. package/dist/subagents.d.ts.map +0 -1
  281. package/dist/subagents.js +0 -2
  282. package/dist/subagents.js.map +0 -1
  283. package/dist/summarizer.d.ts +0 -2
  284. package/dist/summarizer.d.ts.map +0 -1
  285. package/dist/summarizer.js +0 -2
  286. package/dist/summarizer.js.map +0 -1
  287. package/dist/tui.d.ts +0 -7
  288. package/dist/tui.d.ts.map +0 -1
  289. package/dist/tui.js +0 -1109
  290. package/dist/tui.js.map +0 -1
  291. package/dist/ui/prototype-view.d.ts.map +0 -1
  292. package/dist/ui/prototype-view.js.map +0 -1
  293. /package/dist/cli/{configured-WHY3GGAJ.js.map → configured-ACNM6TRQ.js.map} +0 -0
  294. /package/dist/cli/{team-T7G7PPNN.js.map → team-O2I5BXHM.js.map} +0 -0
  295. /package/dist/cli/{web-ui-COB6PKC5.js.map → web-ui-UWQUFE4W.js.map} +0 -0
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../packages/providers/src/capabilities.ts", "../../../../packages/providers/src/anthropic/anthropic-model.ts", "../../../../packages/providers/src/openai-compatible/http.ts", "../../../../packages/providers/src/anthropic/convert.ts", "../../../../packages/providers/src/anthropic/errors.ts", "../../../../packages/providers/src/anthropic/protocol.ts", "../../../../packages/providers/src/anthropic/stream.ts", "../../../../packages/providers/src/deepseek/index.ts", "../../../../packages/providers/src/openai-compatible/chat-model.ts", "../../../../packages/providers/src/openai-compatible/convert.ts", "../../../../packages/providers/src/openai-compatible/errors.ts", "../../../../packages/providers/src/openai-compatible/stream.ts", "../../../../packages/providers/src/kimi/index.ts", "../../../../packages/providers/src/openai/errors.ts", "../../../../packages/providers/src/openai/openai-responses-model.ts", "../../../../packages/providers/src/openai/convert.ts", "../../../../packages/providers/src/openai/protocol.ts", "../../../../packages/providers/src/openai/stream.ts", "../../../../packages/providers/src/openai-compatible/openai-chat-completions-model.ts", "../../../../packages/providers/src/zhipu/index.ts", "../../../../packages/providers/src/builtins.ts", "../../../../packages/providers/src/gemini/gemini-model.ts", "../../../../packages/providers/src/gemini/convert.ts", "../../../../packages/providers/src/gemini/errors.ts", "../../../../packages/providers/src/gemini/protocol.ts", "../../../../packages/providers/src/errors.ts", "../../../../packages/providers/src/options.ts", "../../../../packages/providers/src/capability-validated-model.ts", "../../../../packages/providers/src/validation.ts", "../../../../packages/providers/src/registry.ts", "../../../../packages/providers/src/retrying-model.ts", "../../../../packages/providers/src/selection.ts"],
4
+ "sourcesContent": ["import { createHash } from \"node:crypto\";\nimport {\n MODEL_CAPABILITY_KEYS,\n parseMayConfig,\n type ModelCapabilityDeclaration,\n type ModelCapabilitiesOverride,\n type ModelCapabilityKey,\n} from \"@sortedyuan/may/config\";\nimport { omitUndefined, type ModelRequest } from \"@sortedyuan/may/core\";\nimport type { ProviderModelSelection } from \"./types.js\";\n\nexport { MODEL_CAPABILITY_KEYS };\nexport type { ModelCapabilityKey, ModelCapabilityDeclaration };\n/** @experimental */\nexport type ModelCapabilitySource = \"user\" | \"provider\" | \"builtin\" | \"adapter\" | \"unknown\";\n/** @experimental */\nexport type ModelCapabilityLayer = \"model\" | \"adapter\" | \"connection\";\n/** @experimental */\nexport type CapabilityValue<T = ModelCapabilityDeclaration> =\n | { readonly status: \"known\"; readonly source: Exclude<ModelCapabilitySource, \"unknown\">; readonly value: T }\n | { readonly status: \"unsupported\"; readonly source: Exclude<ModelCapabilitySource, \"unknown\"> }\n | { readonly status: \"unknown\"; readonly source: \"unknown\" };\n/** @experimental */\nexport type ReasoningEffortCapabilities =\n | {\n readonly status: \"known\";\n readonly source: Exclude<ModelCapabilitySource, \"unknown\">;\n readonly efforts: readonly string[];\n readonly defaultEffort?: string;\n }\n | { readonly status: \"unsupported\"; readonly source: Exclude<ModelCapabilitySource, \"unknown\"> }\n | { readonly status: \"unknown\"; readonly source: \"unknown\" };\n/** @experimental */\nexport type ModelCapabilityFields = Readonly<Partial<Record<ModelCapabilityKey, CapabilityValue>>>;\n/** @experimental */\nexport interface ModelCapabilityDiagnostic {\n readonly discovery: string;\n readonly code: \"DISCOVERY_FAILED\";\n readonly observedAt: number;\n}\n/** @experimental */\nexport interface ModelCapabilities {\n readonly reasoningEffort: ReasoningEffortCapabilities;\n readonly fields?: ModelCapabilityFields;\n readonly layers?: Readonly<Record<ModelCapabilityLayer, ModelCapabilityFields>>;\n readonly version?: string;\n readonly observedAt?: number;\n readonly expiresAt?: number;\n readonly diagnostics?: readonly ModelCapabilityDiagnostic[];\n}\n/** @experimental */\nexport interface ModelCapabilityDiscovery {\n readonly name?: string;\n discoverReasoningEffort?(selection: ProviderModelSelection): Promise<ReasoningEffortCapabilities | undefined>;\n discoverCapabilities?(\n selection: ProviderModelSelection,\n fields?: readonly ModelCapabilityKey[],\n ): Promise<ModelCapabilityFields | undefined>;\n}\n/** @experimental */\nexport interface ModelCapabilityResolverOptions {\n readonly fetch?: typeof globalThis.fetch;\n readonly discoveries?: readonly ModelCapabilityDiscovery[];\n readonly cacheTtlMs?: number;\n readonly maxCacheEntries?: number;\n readonly maxVerificationRecords?: number;\n readonly adapterCapabilities?: Readonly<Record<string, ModelCapabilityFields>>;\n}\n/** @experimental */\nexport interface ResolveModelCapabilitiesOptions {\n readonly fields?: readonly ModelCapabilityKey[];\n readonly refresh?: boolean;\n}\n/** @experimental */\nexport interface ModelCapabilityVerificationRecord {\n readonly model: string;\n readonly adapter: string;\n readonly connectionId: string;\n readonly capability: ModelCapabilityKey;\n readonly observedAt: number;\n readonly success: boolean;\n readonly evidence: \"request-accepted\" | \"response-validated\" | \"failed\";\n readonly parameters: Readonly<Record<string, string | number | boolean>>;\n}\ninterface DiscoveryResult {\n readonly fields: ModelCapabilityFields;\n readonly reasoningEffort?: ReasoningEffortCapabilities;\n readonly observedAt: number;\n readonly expiresAt: number;\n readonly diagnostics: readonly ModelCapabilityDiagnostic[];\n}\n/** @experimental */\nexport class ModelCapabilityResolver {\n private readonly discoveries: readonly ModelCapabilityDiscovery[];\n private readonly ttl: number;\n private readonly maxEntries: number;\n private readonly maxRecords: number;\n private readonly adapters: Readonly<Record<string, ModelCapabilityFields>>;\n private readonly cache = new Map<string, DiscoveryResult>();\n private readonly pending = new Map<string, Promise<DiscoveryResult>>();\n private readonly records: ModelCapabilityVerificationRecord[] = [];\n\n constructor(options: ModelCapabilityResolverOptions = {}) {\n this.discoveries = options.discoveries ?? [new ModelListCapabilityDiscovery(options.fetch ?? globalThis.fetch)];\n this.ttl = positive(options.cacheTtlMs ?? 300_000, \"cacheTtlMs\");\n this.maxEntries = positive(options.maxCacheEntries ?? 128, \"maxCacheEntries\");\n this.maxRecords = positive(options.maxVerificationRecords ?? 256, \"maxVerificationRecords\");\n this.adapters = structuredClone(options.adapterCapabilities ?? {});\n for (const fields of Object.values(this.adapters)) assertCapabilityFields(fields);\n }\n async resolve(\n selection: ProviderModelSelection,\n options: ResolveModelCapabilitiesOptions = {},\n ): Promise<ModelCapabilities> {\n const requested = options.fields ?? MODEL_CAPABILITY_KEYS;\n for (const field of requested)\n if (!MODEL_CAPABILITY_KEYS.includes(field)) throw new TypeError(`Unknown capability field ${field}`);\n const explicit = declaredFields(selection.capabilities, \"user\");\n assertCapabilityFields(explicit);\n const explicitReasoning = declaredReasoning(selection.capabilities, \"user\");\n if (explicitReasoning !== undefined) assertReasoningCapabilities(explicitReasoning);\n const discovered = await this.discover(\n selection,\n options.refresh === true,\n explicitReasoning !== undefined,\n requested,\n );\n const model: Partial<Record<ModelCapabilityKey, CapabilityValue>> = {};\n const adapter = this.adapters[selection.adapter] ?? builtinAdapterCapabilities(selection.adapter);\n const connection = declaredFields(selection.providerConfig.capabilities, \"user\");\n assertCapabilityFields(connection);\n const connectionReasoning = declaredReasoning(selection.providerConfig.capabilities, \"user\");\n if (connectionReasoning !== undefined) assertReasoningCapabilities(connectionReasoning);\n const effective: Partial<Record<ModelCapabilityKey, CapabilityValue>> = {};\n for (const field of requested) {\n const value = explicit[field] ?? declaredLimit(selection, field) ?? discovered.fields[field] ?? UNKNOWN;\n model[field] = value;\n effective[field] = intersectCapability(field, [value, adapter[field], connection[field]]);\n }\n const reasoning = explicitReasoning ?? discovered.reasoningEffort ?? builtinReasoningEffort(selection) ?? UNKNOWN;\n const reasoningEffort = intersectReasoning(reasoning, connectionReasoning);\n const layers = { model, adapter, connection };\n return structuredClone({\n reasoningEffort,\n fields: effective,\n layers,\n version: digest({ reasoningEffort, fields: effective, layers }),\n observedAt: discovered.observedAt,\n expiresAt: discovered.expiresAt,\n diagnostics: discovered.diagnostics,\n });\n }\n invalidate(selection?: ProviderModelSelection): void {\n if (selection === undefined) {\n this.cache.clear();\n this.pending.clear();\n return;\n }\n const prefix = connectionIdentity(selection);\n for (const key of [...this.cache.keys(), ...this.pending.keys()]) {\n if (!key.startsWith(prefix)) continue;\n this.cache.delete(key);\n this.pending.delete(key);\n }\n }\n verificationRecords(selection?: ProviderModelSelection): readonly ModelCapabilityVerificationRecord[] {\n const connectionId = selection === undefined ? undefined : connectionIdentity(selection);\n return this.records\n .filter(\n (record) =>\n connectionId === undefined || (record.connectionId === connectionId && record.model === selection?.model),\n )\n .map((record) => ({ ...record, parameters: { ...record.parameters } }));\n }\n recordVerification(\n selection: ProviderModelSelection,\n request: ModelRequest,\n success: boolean,\n responseValidated = false,\n additionalCapabilities: readonly ModelCapabilityKey[] = [],\n ): void {\n const used = new Set<ModelCapabilityKey>(additionalCapabilities);\n for (const message of request.messages)\n for (const part of message.content) {\n if (part.type === \"text\" || part.type === \"json\") used.add(\"input.text\");\n if ([\"image\", \"audio\", \"file\", \"resource\"].includes(part.type))\n used.add(`input.${part.type}` as ModelCapabilityKey);\n }\n if (request.tools.length > 0) used.add(\"tools\");\n if (request.responseFormat !== undefined)\n used.add(request.responseFormat.type === \"json\" ? \"structuredOutput.json\" : \"structuredOutput.jsonSchema\");\n const thinking = selection.options.thinking;\n const activeThinking =\n thinking !== undefined && thinking !== \"disabled\" && !(isRecord(thinking) && thinking.type === \"disabled\");\n if (\n selection.options.reasoningEffort !== undefined ||\n activeThinking ||\n selection.options.reasoningSummary !== undefined\n )\n used.add(\"reasoning.modes\");\n const parameters: Record<string, string | number | boolean> = {};\n if (typeof selection.options.reasoningEffort === \"string\")\n parameters.reasoningEffort = selection.options.reasoningEffort;\n for (const key of [\"maxTokens\", \"maxOutputTokens\"] as const)\n if (typeof selection.options[key] === \"number\") parameters[key] = selection.options[key];\n if (\n parameters.maxTokens === undefined &&\n parameters.maxOutputTokens === undefined &&\n selection.limits?.maxOutputTokens !== undefined\n ) {\n parameters[\n [\"deepseek-chat\", \"kimi-chat\", \"zhipu-chat\", \"anthropic-messages\"].includes(selection.adapter)\n ? \"maxTokens\"\n : \"maxOutputTokens\"\n ] = selection.limits.maxOutputTokens;\n }\n if (typeof selection.options.reasoningSummary === \"string\")\n parameters.reasoningSummary = selection.options.reasoningSummary;\n if (typeof thinking === \"string\") parameters.thinkingType = thinking;\n else if (isRecord(thinking)) {\n if (typeof thinking.type === \"string\") parameters.thinkingType = thinking.type;\n if (typeof thinking.budgetTokens === \"number\") parameters.thinkingBudgetTokens = thinking.budgetTokens;\n }\n if (request.responseFormat?.type === \"jsonSchema\") {\n parameters.schemaVersion = digest(request.responseFormat.schema);\n parameters.strict = request.responseFormat.strict ?? false;\n }\n for (const capability of used) {\n const observed: Record<string, string | number | boolean> = { ...parameters };\n const parts = request.messages\n .flatMap((message) => message.content)\n .filter((part) =>\n capability === \"input.text\"\n ? part.type === \"text\" || part.type === \"json\"\n : capability === `input.${part.type}`,\n );\n if (capability.startsWith(\"input.\")) observed.count = parts.length;\n const media = parts.filter((part) => part.type === \"image\" || part.type === \"audio\" || part.type === \"file\");\n if (media.length > 0) {\n for (const source of [\"url\", \"base64\", \"file\"] as const)\n observed[`${source}Sources`] = media.filter((part) => part.source.type === source).length;\n const base64 = media.flatMap((part) => (part.source.type === \"base64\" ? [part.source] : []));\n const bytes = base64.map((source) => Buffer.byteLength(source.data, \"base64\"));\n observed.knownBytesCount = bytes.length;\n if (bytes.length > 0) {\n observed.minObservedBytes = Math.min(...bytes);\n observed.maxObservedBytes = Math.max(...bytes);\n }\n observed.mediaTypesVersion = digest([...new Set(base64.map((source) => source.mediaType))].sort());\n }\n if (capability === \"tools\") {\n observed.definitions = request.tools.length;\n observed.definitionsVersion = digest(request.tools);\n }\n const evidence = !success\n ? \"failed\"\n : capability.startsWith(\"structuredOutput.\") && responseValidated\n ? \"response-validated\"\n : \"request-accepted\";\n this.records.push({\n model: selection.model,\n adapter: selection.adapter,\n connectionId: connectionIdentity(selection),\n capability,\n observedAt: Date.now(),\n success,\n evidence,\n parameters: observed,\n });\n }\n if (this.records.length > this.maxRecords) this.records.splice(0, this.records.length - this.maxRecords);\n }\n private async discover(\n selection: ProviderModelSelection,\n refresh: boolean,\n skipReasoning: boolean,\n fields: readonly ModelCapabilityKey[],\n ): Promise<DiscoveryResult> {\n const key = `${connectionIdentity(selection)}:${digest({ model: selection.model, fields: [...fields].sort(), skipReasoning })}`;\n if (refresh) this.cache.delete(key);\n const cached = this.cache.get(key);\n if (cached !== undefined && cached.expiresAt > Date.now()) {\n this.cache.delete(key);\n this.cache.set(key, cached);\n return cached;\n }\n this.cache.delete(key);\n const active = this.pending.get(key);\n if (active !== undefined) return active;\n if (this.pending.size >= this.maxEntries) throw new RangeError(\"Capability discovery concurrency limit exceeded\");\n const operation = this.query(selection, skipReasoning, fields);\n this.pending.set(key, operation);\n try {\n const result = await operation;\n if (this.pending.get(key) === operation && result.diagnostics.length === 0) {\n this.cache.set(key, result);\n while (this.cache.size > this.maxEntries) this.cache.delete(this.cache.keys().next().value!);\n }\n return result;\n } finally {\n if (this.pending.get(key) === operation) this.pending.delete(key);\n }\n }\n private async query(\n selection: ProviderModelSelection,\n skipReasoning: boolean,\n requested: readonly ModelCapabilityKey[],\n ): Promise<DiscoveryResult> {\n const fields: Partial<Record<ModelCapabilityKey, CapabilityValue>> = {};\n let reasoningEffort: ReasoningEffortCapabilities | undefined;\n const diagnostics: ModelCapabilityDiagnostic[] = [];\n for (const [index, discovery] of this.discoveries.entries()) {\n let found: ModelCapabilityFields | undefined;\n let foundReasoning: ReasoningEffortCapabilities | undefined;\n try {\n found = await discovery.discoverCapabilities?.(selection, requested);\n if (!skipReasoning && reasoningEffort === undefined)\n foundReasoning = await discovery.discoverReasoningEffort?.(selection);\n } catch {\n diagnostics.push({\n discovery: discovery.name ?? `discovery-${index + 1}`,\n code: \"DISCOVERY_FAILED\",\n observedAt: Date.now(),\n });\n continue;\n }\n if (found !== undefined) assertCapabilityFields(found);\n if (foundReasoning !== undefined) assertReasoningCapabilities(foundReasoning);\n if (found !== undefined)\n for (const field of requested)\n if (fields[field] === undefined && found[field] !== undefined) fields[field] = found[field];\n reasoningEffort ??= foundReasoning;\n }\n const observedAt = Date.now();\n return omitUndefined({ fields, reasoningEffort, observedAt, expiresAt: observedAt + this.ttl, diagnostics });\n }\n}\n/** @experimental */\nexport function createModelCapabilityResolver(options: ModelCapabilityResolverOptions = {}): ModelCapabilityResolver {\n return new ModelCapabilityResolver(options);\n}\n/** @experimental */\nexport function connectionIdentity(selection: ProviderModelSelection): string {\n return digest({ provider: selection.provider, adapter: selection.adapter, config: selection.providerConfig });\n}\nconst UNKNOWN = { status: \"unknown\", source: \"unknown\" } as const;\nfunction known(value: ModelCapabilityDeclaration, source: Exclude<ModelCapabilitySource, \"unknown\">): CapabilityValue {\n return value === false ? { status: \"unsupported\", source } : { status: \"known\", source, value };\n}\nfunction declaredFields(\n overrides: ModelCapabilitiesOverride | undefined,\n source: Exclude<ModelCapabilitySource, \"unknown\">,\n): ModelCapabilityFields {\n return Object.fromEntries(\n Object.entries(overrides?.fields ?? {}).map(([field, value]) => [field, known(value, source)]),\n );\n}\nfunction declaredLimit(selection: ProviderModelSelection, field: ModelCapabilityKey): CapabilityValue | undefined {\n if (field !== \"contextWindowTokens\" && field !== \"maxOutputTokens\") return undefined;\n const value = selection.limits?.[field];\n return value === undefined ? undefined : known(value, \"user\");\n}\nfunction declaredReasoning(\n overrides: ModelCapabilitiesOverride | undefined,\n source: Exclude<ModelCapabilitySource, \"unknown\">,\n): ReasoningEffortCapabilities | undefined {\n const reasoning = overrides?.reasoning;\n if (reasoning === undefined) return undefined;\n if (reasoning === false || reasoning.efforts.length === 0) return { status: \"unsupported\", source };\n return omitUndefined({\n status: \"known\",\n source,\n efforts: [...reasoning.efforts],\n defaultEffort: reasoning.defaultEffort,\n });\n}\nfunction intersectReasoning(\n model: ReasoningEffortCapabilities,\n connection: ReasoningEffortCapabilities | undefined,\n): ReasoningEffortCapabilities {\n if (model.status === \"unsupported\") return model;\n if (connection?.status === \"unsupported\") return connection;\n if (model.status !== \"known\" || connection?.status === \"unknown\") return UNKNOWN;\n if (connection === undefined) return model;\n const efforts = model.efforts.filter((effort) => connection.efforts.includes(effort));\n if (efforts.length === 0) return { status: \"unsupported\", source: connection.source };\n const defaultEffort = connection.defaultEffort ?? model.defaultEffort;\n return {\n status: \"known\",\n source: connection.source,\n efforts,\n ...(defaultEffort !== undefined && efforts.includes(defaultEffort) ? { defaultEffort } : {}),\n };\n}\nfunction intersectCapability(\n field: ModelCapabilityKey,\n values: readonly (CapabilityValue | undefined)[],\n): CapabilityValue {\n const unsupported = values.find((value) => value?.status === \"unsupported\");\n if (unsupported !== undefined) return unsupported;\n if (values.some((value) => value?.status === \"unknown\")) return UNKNOWN;\n const concrete = values.filter(\n (value): value is Extract<CapabilityValue, { status: \"known\" }> => value?.status === \"known\",\n );\n if (concrete.length === 0) return UNKNOWN;\n let value = concrete[0]!.value;\n let source = concrete[0]!.source;\n for (const next of concrete.slice(1)) {\n const previous = JSON.stringify(value);\n if (typeof value === \"number\" && typeof next.value === \"number\") value = Math.min(value, next.value);\n else if (Array.isArray(value) && Array.isArray(next.value))\n value = value.filter((item) => (next.value as readonly string[]).includes(item));\n else if (field === \"parameters\" || field === \"structuredOutput.schemaConstraint\")\n value = { allOf: [value, next.value] };\n if (JSON.stringify(value) !== previous) source = next.source;\n }\n if (Array.isArray(value) && value.length === 0) return { status: \"unsupported\", source: concrete.at(-1)!.source };\n return { status: \"known\", source, value };\n}\n/** @experimental */\nexport function builtinAdapterCapabilities(adapter: string): ModelCapabilityFields {\n if (adapter === \"google-gemini\")\n return Object.fromEntries(\n Object.entries({\n \"input.text\": true,\n \"input.image\": true,\n \"input.audio\": true,\n \"input.file\": true,\n \"input.resource\": false,\n \"input.image.sources\": [\"url\", \"base64\"],\n \"input.audio.sources\": [\"url\", \"base64\"],\n \"input.file.sources\": [\"url\", \"base64\"],\n \"output.text\": true,\n \"output.image\": true,\n \"output.audio\": true,\n tools: true,\n \"structuredOutput.json\": true,\n \"structuredOutput.jsonSchema\": true,\n \"structuredOutput.schemaDialects\": [\"draft-07\", \"2020-12\"],\n contextCompaction: false,\n \"reasoning.modes\": [\"effort\", \"budget\"],\n }).map(([field, value]) => [field, known(value, \"adapter\")]),\n );\n if (\n ![\n \"openai-responses\",\n \"openai-chat-completions\",\n \"deepseek-chat\",\n \"kimi-chat\",\n \"zhipu-chat\",\n \"anthropic-messages\",\n ].includes(adapter)\n )\n return {};\n const responses = adapter === \"openai-responses\";\n const anthropic = adapter === \"anthropic-messages\";\n const openaiChat = adapter === \"openai-chat-completions\";\n const values: Partial<Record<ModelCapabilityKey, ModelCapabilityDeclaration>> = {\n \"input.text\": true,\n \"input.image\": true,\n \"input.audio\": false,\n \"input.file\": responses || anthropic,\n \"input.resource\": false,\n \"input.image.sources\": responses || anthropic ? [\"url\", \"base64\", \"file\"] : [\"url\", \"base64\"],\n \"input.file.sources\": responses || anthropic ? [\"url\", \"base64\", \"file\"] : false,\n \"output.text\": true,\n \"output.image\": responses,\n \"output.audio\": false,\n tools: true,\n \"structuredOutput.json\": responses || openaiChat,\n \"structuredOutput.jsonSchema\": responses || openaiChat,\n \"structuredOutput.schemaDialects\": responses || openaiChat ? [\"draft-07\", \"2020-12\"] : false,\n contextCompaction: responses,\n \"reasoning.modes\": anthropic\n ? [\"effort\", \"budget\", \"adaptive\"]\n : responses\n ? [\"effort\", \"summary\"]\n : openaiChat\n ? [\"effort\"]\n : [\"effort\", \"thinking\"],\n };\n return Object.fromEntries(Object.entries(values).map(([field, value]) => [field, known(value, \"adapter\")]));\n}\ninterface CatalogReasoningEffort {\n readonly efforts: readonly string[];\n readonly defaultEffort?: string;\n}\nconst BUILTIN_REASONING_EFFORTS = new Map<string, CatalogReasoningEffort>([\n ...[\"openai-responses\", \"openai-chat-completions\"].flatMap((adapter) =>\n [\"gpt-5.6\", \"gpt-5.6-sol\", \"gpt-5.6-terra\", \"gpt-5.6-luna\"].map(\n (model) =>\n [\n catalogKey(adapter, model),\n { efforts: [\"none\", \"low\", \"medium\", \"high\", \"xhigh\", \"max\"], defaultEffort: \"medium\" },\n ] as const,\n ),\n ),\n ...[\"deepseek-v4-flash\", \"deepseek-v4-pro\", \"deepseek-v4-flash-vision-exp\"].map(\n (model) =>\n [catalogKey(\"deepseek-chat\", model), { efforts: [\"low\", \"high\", \"max\"], defaultEffort: \"high\" }] as const,\n ),\n]);\nfunction builtinReasoningEffort(selection: ProviderModelSelection): ReasoningEffortCapabilities | undefined {\n const entry = BUILTIN_REASONING_EFFORTS.get(catalogKey(selection.adapter, selection.model));\n return entry === undefined\n ? undefined\n : omitUndefined({\n status: \"known\",\n source: \"builtin\",\n efforts: [...entry.efforts],\n defaultEffort: entry.defaultEffort,\n });\n}\nfunction catalogKey(adapter: string, model: string): string {\n return `${adapter}\\u0000${model}`;\n}\ninterface ModelEndpoint {\n readonly url: string;\n readonly headers: Record<string, string>;\n /** Selects the entry describing the requested model from the parsed response body. */\n readonly entry: (body: Record<string, unknown>) => unknown;\n}\nconst BEARER_DEFAULT_BASE_URLS: Readonly<Record<string, string>> = {\n \"openai-responses\": \"https://api.openai.com/v1\",\n \"openai-chat-completions\": \"https://api.openai.com/v1\",\n \"deepseek-chat\": \"https://api.deepseek.com\",\n \"kimi-chat\": \"https://api.moonshot.ai/v1\",\n \"zhipu-chat\": \"https://open.bigmodel.cn/api/paas/v4\",\n};\nfunction trimBaseURL(value: string): string {\n return value.replace(/\\/+$/u, \"\");\n}\n/** Finds `models[]` entries by `slug` (CLIProxyAPI's Codex catalog) and `data[]` entries by `id`. */\nfunction listEntry(model: string): (body: Record<string, unknown>) => unknown {\n return (body) =>\n Array.isArray(body.models)\n ? body.models.find((entry) => isRecord(entry) && entry.slug === model)\n : Array.isArray(body.data)\n ? body.data.find((entry) => isRecord(entry) && entry.id === model)\n : undefined;\n}\nfunction modelEndpoint(selection: ProviderModelSelection): ModelEndpoint | undefined {\n const { adapter, model, providerConfig, options } = selection;\n const apiKey =\n providerConfig.apiKey === undefined || providerConfig.apiKey.trim() === \"\" ? undefined : providerConfig.apiKey;\n const bearer = BEARER_DEFAULT_BASE_URLS[adapter];\n if (bearer !== undefined) {\n return {\n url: `${trimBaseURL(providerConfig.baseURL ?? bearer)}/models?client_version=may`,\n headers: apiKey === undefined ? {} : { Authorization: `Bearer ${apiKey}` },\n entry: listEntry(model),\n };\n }\n if (adapter === \"anthropic-messages\") {\n return {\n url: `${trimBaseURL(providerConfig.baseURL ?? \"https://api.anthropic.com\")}/v1/models?limit=1000`,\n headers: {\n \"anthropic-version\": typeof options.apiVersion === \"string\" ? options.apiVersion : \"2023-06-01\",\n ...(apiKey === undefined ? {} : { \"x-api-key\": apiKey }),\n },\n entry: listEntry(model),\n };\n }\n if (adapter === \"google-gemini\") {\n return {\n url: `${trimBaseURL(providerConfig.baseURL ?? \"https://generativelanguage.googleapis.com/v1beta\")}/models/${encodeURIComponent(model)}`,\n headers: apiKey === undefined ? {} : { \"x-goog-api-key\": apiKey },\n entry: (body) => body,\n };\n }\n return undefined;\n}\nfunction effortNames(levels: readonly unknown[]): string[] {\n return [\n ...new Set(\n levels.flatMap((level) => {\n const effort = typeof level === \"string\" ? level : isRecord(level) ? level.effort : undefined;\n return typeof effort === \"string\" && effort.trim() !== \"\" ? [effort] : [];\n }),\n ),\n ];\n}\n/** Reads `supported_reasoning_levels`, `reasoning_levels`, `effort.supported_levels` or Gemini's `thinking: false`. */\nfunction entryReasoningEffort(entry: Record<string, unknown>): ReasoningEffortCapabilities | undefined {\n const effort = isRecord(entry.effort) ? entry.effort : undefined;\n const levels = Array.isArray(entry.supported_reasoning_levels)\n ? entry.supported_reasoning_levels\n : Array.isArray(entry.reasoning_levels)\n ? entry.reasoning_levels\n : Array.isArray(effort?.supported_levels)\n ? effort.supported_levels\n : undefined;\n if (levels === undefined) return entry.thinking === false ? { status: \"unsupported\", source: \"provider\" } : undefined;\n const efforts = effortNames(levels);\n if (efforts.length === 0) return undefined;\n const defaultEffort = entry.default_reasoning_level ?? effort?.default_level;\n return {\n status: \"known\",\n source: \"provider\",\n efforts,\n ...(typeof defaultEffort === \"string\" && efforts.includes(defaultEffort) ? { defaultEffort } : {}),\n };\n}\n/** Reads reasoning levels from the model endpoint of every built-in adapter. */\nclass ModelListCapabilityDiscovery implements ModelCapabilityDiscovery {\n readonly name = \"model-list\";\n constructor(private readonly fetchImplementation: typeof globalThis.fetch) {}\n async discoverReasoningEffort(selection: ProviderModelSelection): Promise<ReasoningEffortCapabilities | undefined> {\n const endpoint = modelEndpoint(selection);\n if (endpoint === undefined) return undefined;\n const response = await this.fetchImplementation(endpoint.url, {\n signal: AbortSignal.timeout(10_000),\n headers: endpoint.headers,\n });\n if (response.status === 404) return undefined;\n if (!response.ok) throw new Error(\"Capability catalog request failed\");\n const value: unknown = await response.json();\n if (!isRecord(value)) return undefined;\n const entry = endpoint.entry(value);\n return isRecord(entry) ? entryReasoningEffort(entry) : undefined;\n }\n}\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\nfunction assertCapabilityFields(fields: ModelCapabilityFields): void {\n const declarations: Record<string, ModelCapabilityDeclaration> = {};\n for (const [field, capability] of Object.entries(fields)) {\n if (!MODEL_CAPABILITY_KEYS.includes(field as ModelCapabilityKey) || !isRecord(capability))\n throw new TypeError(\"Invalid discovered capability field\");\n if (capability.status === \"unknown\" && capability.source === \"unknown\") continue;\n if (![\"user\", \"provider\", \"builtin\", \"adapter\"].includes(String(capability.source)))\n throw new TypeError(\"Invalid capability source\");\n if (capability.status === \"unsupported\") declarations[field] = false;\n else if (capability.status === \"known\") {\n if (capability.value === false) throw new TypeError(\"False capability declarations require unsupported status\");\n declarations[field] = capability.value as ModelCapabilityDeclaration;\n } else throw new TypeError(\"Invalid capability status\");\n }\n parseMayConfig({\n providers: { metadata: { adapter: \"metadata\" } },\n models: { metadata: { provider: \"metadata\", model: \"metadata\", capabilities: { fields: declarations } } },\n });\n}\nfunction assertReasoningCapabilities(capability: ReasoningEffortCapabilities): void {\n if (capability.status === \"unknown\" && capability.source === \"unknown\") return;\n if (![\"user\", \"provider\", \"builtin\", \"adapter\"].includes(capability.source))\n throw new TypeError(\"Invalid reasoning capability source\");\n if (capability.status === \"unsupported\") return;\n if (capability.status !== \"known\") throw new TypeError(\"Invalid reasoning capability status\");\n parseMayConfig({\n providers: { metadata: { adapter: \"metadata\" } },\n models: {\n metadata: {\n provider: \"metadata\",\n model: \"metadata\",\n capabilities: {\n reasoning: omitUndefined({ efforts: capability.efforts, defaultEffort: capability.defaultEffort }),\n },\n },\n },\n });\n}\nfunction digest(value: unknown): string {\n return createHash(\"sha256\").update(JSON.stringify(value)).digest(\"hex\");\n}\nfunction positive(value: number, field: string): number {\n if (!Number.isSafeInteger(value) || value < 1) throw new RangeError(`${field} must be a positive safe integer`);\n return value;\n}\n", "import { executeRecordedRequest, requestEndpoint } from \"@sortedyuan/may/core\";\nimport type { Message, Model, ModelEvent, ModelRequest, ModelStreamOptions } from \"@sortedyuan/may/core\";\nimport { parseRetryAfterMs } from \"../openai-compatible/http.js\";\nimport { toAnthropicRequestParts, toAnthropicThinking, toAnthropicTools } from \"./convert.js\";\nimport { AnthropicApiError } from \"./errors.js\";\nimport type { AnthropicMessagesRequest, AnthropicReasoningEffort, AnthropicThinkingConfig } from \"./protocol.js\";\nimport { streamAnthropicResponse } from \"./stream.js\";\n\n/** @experimental */\nexport interface AnthropicModelOptions {\n promptCaching?: false | AnthropicPromptCachingOptions;\n apiKey: string;\n model: string;\n baseURL?: string;\n apiVersion?: string;\n maxTokens?: number;\n thinking?: Readonly<AnthropicThinkingConfig>;\n reasoningEffort?: AnthropicReasoningEffort;\n fetch?: typeof globalThis.fetch;\n}\n\n/** @experimental */\nexport interface AnthropicPromptCachingOptions {\n readonly ttl?: \"5m\" | \"1h\";\n readonly cacheInstructions?: boolean;\n}\n\nconst FILES_API_BETA = \"files-api-2025-04-14\";\n\n/** @experimental */\nexport class AnthropicModel implements Model {\n readonly supportsRequestRecording = true;\n private readonly apiKey: string;\n private readonly promptCaching: false | AnthropicPromptCachingOptions | undefined;\n private readonly model: string;\n private readonly baseURL: string;\n private readonly apiVersion: string;\n private readonly maxTokens: number;\n private readonly thinking: AnthropicThinkingConfig | undefined;\n private readonly reasoningEffort: AnthropicReasoningEffort | undefined;\n private readonly fetchImplementation: typeof globalThis.fetch;\n\n constructor(options: AnthropicModelOptions) {\n if (options.apiKey.trim() === \"\") {\n throw new TypeError(\"apiKey must not be empty\");\n }\n if (options.model.trim() === \"\") {\n throw new TypeError(\"model must not be empty\");\n }\n\n const maxTokens = options.maxTokens ?? 4096;\n if (!Number.isSafeInteger(maxTokens) || maxTokens < 1) {\n throw new RangeError(\"maxTokens must be a positive safe integer\");\n }\n if (options.apiVersion !== undefined && options.apiVersion.trim() === \"\") {\n throw new TypeError(\"apiVersion must not be empty\");\n }\n if (options.thinking?.type === \"enabled\") {\n if (!Number.isSafeInteger(options.thinking.budgetTokens) || options.thinking.budgetTokens < 1024) {\n throw new RangeError(\"thinking.budgetTokens must be a safe integer of at least 1024\");\n }\n if (options.thinking.budgetTokens >= maxTokens) {\n throw new RangeError(\"thinking.budgetTokens must be less than maxTokens\");\n }\n }\n\n this.apiKey = options.apiKey;\n if (options.promptCaching !== undefined && options.promptCaching !== false) {\n if (\n typeof options.promptCaching !== \"object\" ||\n options.promptCaching === null ||\n Array.isArray(options.promptCaching)\n ) {\n throw new TypeError(\"promptCaching must be false or an object\");\n }\n if (options.promptCaching.ttl !== undefined && ![\"5m\", \"1h\"].includes(options.promptCaching.ttl)) {\n throw new TypeError(\"promptCaching.ttl must be 5m or 1h\");\n }\n if (\n options.promptCaching.cacheInstructions !== undefined &&\n typeof options.promptCaching.cacheInstructions !== \"boolean\"\n ) {\n throw new TypeError(\"promptCaching.cacheInstructions must be a boolean\");\n }\n }\n this.promptCaching =\n options.promptCaching === undefined || options.promptCaching === false\n ? options.promptCaching\n : { ...options.promptCaching };\n this.model = options.model;\n this.baseURL = (options.baseURL ?? \"https://api.anthropic.com\").replace(/\\/+$/, \"\");\n this.apiVersion = options.apiVersion ?? \"2023-06-01\";\n this.maxTokens = maxTokens;\n this.thinking = cloneThinking(options.thinking);\n this.reasoningEffort = options.reasoningEffort;\n this.fetchImplementation = options.fetch ?? globalThis.fetch;\n }\n\n async *stream(request: ModelRequest, options: ModelStreamOptions): AsyncIterable<ModelEvent> {\n if (request.responseFormat !== undefined) throw new TypeError(\"Anthropic adapter does not support responseFormat\");\n const body = this.createRequest(request);\n yield* executeRecordedRequest(\n {\n version: 1,\n adapter: \"anthropic-messages\",\n purpose: \"generation\",\n endpoint: requestEndpoint(`${this.baseURL}/v1/messages`),\n request,\n body,\n protocol: {\n \"anthropic-version\": this.apiVersion,\n ...(usesFileId(request.messages) ? { \"anthropic-beta\": FILES_API_BETA } : {}),\n },\n },\n options.recordRequest,\n options.signal,\n (body) => this.execute(body, request, options),\n );\n }\n\n private async *execute(body: string, request: ModelRequest, options: ModelStreamOptions): AsyncIterable<ModelEvent> {\n const headers: Record<string, string> = {\n \"anthropic-version\": this.apiVersion,\n \"content-type\": \"application/json\",\n \"x-api-key\": this.apiKey,\n };\n if (usesFileId(request.messages)) {\n headers[\"anthropic-beta\"] = FILES_API_BETA;\n }\n const response = await this.fetchImplementation(`${this.baseURL}/v1/messages`, {\n method: \"POST\",\n headers,\n body,\n signal: options.signal,\n });\n\n if (!response.ok) throw await createApiError(response);\n yield* streamAnthropicResponse(response, options.signal);\n }\n\n private createRequest(request: ModelRequest): AnthropicMessagesRequest {\n const parts = toAnthropicRequestParts(request.messages);\n const body: AnthropicMessagesRequest = {\n model: this.model,\n max_tokens: this.maxTokens,\n messages: parts.messages,\n stream: true,\n };\n\n if (parts.system !== undefined) body.system = parts.system;\n if (request.tools.length > 0) {\n body.tools = toAnthropicTools(request.tools);\n }\n if (this.promptCaching) {\n const cacheControl = { type: \"ephemeral\" as const, ttl: this.promptCaching.ttl ?? \"5m\" };\n body.cache_control = cacheControl;\n if (this.promptCaching.cacheInstructions) {\n if (parts.system !== undefined)\n body.system = [{ type: \"text\", text: parts.system, cache_control: cacheControl }];\n const lastTool = body.tools?.at(-1);\n if (lastTool) lastTool.cache_control = cacheControl;\n }\n }\n if (this.thinking !== undefined) {\n body.thinking = toAnthropicThinking(this.thinking);\n }\n if (this.reasoningEffort !== undefined) {\n body.output_config = { effort: this.reasoningEffort };\n }\n return body;\n }\n}\n\nfunction usesFileId(messages: readonly Message[]): boolean {\n return messages.some((message) =>\n message.content.some((part) => (part.type === \"image\" || part.type === \"file\") && part.source.type === \"file\"),\n );\n}\n\nfunction cloneThinking(thinking: Readonly<AnthropicThinkingConfig> | undefined): AnthropicThinkingConfig | undefined {\n return thinking === undefined ? undefined : { ...thinking };\n}\n\nasync function createApiError(response: Response): Promise<AnthropicApiError> {\n const text = await response.text();\n let message = text || `Anthropic request failed with status ${response.status}`;\n let providerType: string | undefined;\n let requestId = response.headers.get(\"request-id\") ?? undefined;\n\n try {\n const parsed = JSON.parse(text) as {\n error?: { message?: unknown; type?: unknown };\n request_id?: unknown;\n };\n if (typeof parsed.error?.message === \"string\") {\n message = parsed.error.message;\n }\n if (typeof parsed.error?.type === \"string\") {\n providerType = parsed.error.type;\n }\n if (typeof parsed.request_id === \"string\") {\n requestId = parsed.request_id;\n }\n } catch {\n // Keep the response text as the error message when it is not JSON.\n }\n\n const options: ConstructorParameters<typeof AnthropicApiError>[0] = {\n status: response.status,\n message,\n };\n if (providerType !== undefined) options.providerType = providerType;\n if (requestId !== undefined) options.requestId = requestId;\n const retryAfterMs = parseRetryAfterMs(response.headers.get(\"retry-after\"));\n if (retryAfterMs !== undefined) options.retryAfterMs = retryAfterMs;\n return new AnthropicApiError(options);\n}\n", "import { createParser } from \"eventsource-parser\";\n\n/** @experimental */\nexport async function* readSseData(\n response: Response,\n signal: AbortSignal,\n protocolError: (message: string, options?: ErrorOptions) => Error,\n providerName: string,\n): AsyncGenerator<string> {\n if (!response.body) {\n throw protocolError(`${providerName} response has no body`);\n }\n\n const reader = response.body.getReader();\n const decoder = new TextDecoder();\n const dataEvents: string[] = [];\n const parser = createParser({\n onEvent: (event) => dataEvents.push(event.data),\n });\n const onAbort = () => {\n void reader.cancel(signal.reason).catch(() => undefined);\n };\n signal.addEventListener(\"abort\", onAbort, { once: true });\n\n try {\n while (true) {\n throwIfAborted(signal);\n const { done, value } = await reader.read();\n throwIfAborted(signal);\n if (done) {\n // \u6D41\u7ED3\u675F\u65F6\u8865\u5168\u4E8B\u4EF6\u7EC8\u6B62\u7B26\uFF0C\u4EE5\u652F\u6301\u6CA1\u6709\u7A7A\u767D\u884C\u7684\u6700\u540E\u4E00\u4E2A\u4E8B\u4EF6\u3002\n parser.feed(`${decoder.decode()}\\n\\n`);\n } else {\n parser.feed(decoder.decode(value, { stream: true }));\n }\n for (const data of dataEvents) {\n throwIfAborted(signal);\n yield data;\n }\n dataEvents.length = 0;\n if (done) break;\n }\n\n throwIfAborted(signal);\n } finally {\n signal.removeEventListener(\"abort\", onAbort);\n void reader.cancel().catch(() => undefined);\n reader.releaseLock();\n }\n}\n\n/** @experimental */\nexport function parseRetryAfterMs(value: string | null): number | undefined {\n if (value === null) return undefined;\n const seconds = Number(value);\n if (Number.isFinite(seconds) && seconds >= 0) {\n return Math.round(seconds * 1000);\n }\n const timestamp = Date.parse(value);\n return Number.isFinite(timestamp) ? Math.max(0, timestamp - Date.now()) : undefined;\n}\n\nfunction throwIfAborted(signal: AbortSignal): void {\n if (!signal.aborted) return;\n if (signal.reason instanceof Error) throw signal.reason;\n throw new DOMException(\"The operation was aborted\", \"AbortError\");\n}\n", "import type { ContentPart, MediaSource, Message, ModelState, ToolDefinition } from \"@sortedyuan/may/core\";\nimport { UnsupportedContentError } from \"@sortedyuan/may/core\";\nimport { AnthropicProtocolError } from \"./errors.js\";\nimport {\n ANTHROPIC_MODEL_STATE_TYPE,\n type AnthropicAssistantContentBlock,\n type AnthropicMessagesRequest,\n type AnthropicMediaSource,\n type AnthropicModelStateData,\n type AnthropicRequestMessage,\n type AnthropicTextBlock,\n type AnthropicUserContentBlock,\n type AnthropicThinkingConfig,\n type AnthropicToolDefinition,\n type AnthropicToolResultBlock,\n} from \"./protocol.js\";\n\nexport interface AnthropicRequestParts {\n messages: AnthropicRequestMessage[];\n system?: string;\n}\n\nexport function toAnthropicRequestParts(messages: readonly Message[]): AnthropicRequestParts {\n const system: string[] = [];\n const converted: AnthropicRequestMessage[] = [];\n\n for (const message of messages) {\n if (message.role === \"system\") {\n const text = serializeVisibleContent(message.content);\n if (text !== \"\") system.push(text);\n continue;\n }\n\n if (message.role === \"user\") {\n converted.push({\n role: \"user\",\n content: toUserBlocks(message.content),\n });\n continue;\n }\n\n if (message.role === \"tool\") {\n const toolResult: AnthropicToolResultBlock = {\n type: \"tool_result\",\n tool_use_id: message.toolCallId,\n content: hasMedia(message.content)\n ? toUserBlocks(message.content)\n : serializeVisibleContent(message.content, \"tool\"),\n };\n if (message.isError !== undefined) {\n toolResult.is_error = message.isError;\n }\n converted.push({ role: \"user\", content: [toolResult] });\n continue;\n }\n\n const nativeContent = getAnthropicStateContent(message.modelState);\n if (nativeContent !== undefined) {\n converted.push({ role: \"assistant\", content: nativeContent });\n continue;\n }\n\n const content: AnthropicAssistantContentBlock[] = [...toAssistantTextBlocks(message.content)];\n for (const call of message.toolCalls ?? []) {\n if (!isRecord(call.input)) {\n throw new AnthropicProtocolError(`Anthropic tool call \"${call.name}\" input must be an object`);\n }\n content.push({\n type: \"tool_use\",\n id: call.id,\n name: call.name,\n input: call.input,\n });\n }\n converted.push({ role: \"assistant\", content });\n }\n\n const result: AnthropicRequestParts = { messages: converted };\n if (system.length > 0) result.system = system.join(\"\\n\");\n return result;\n}\n\nexport function toAnthropicTools(tools: readonly ToolDefinition[]): AnthropicToolDefinition[] {\n return tools.map((tool) => ({\n name: tool.name,\n description: tool.description,\n input_schema: tool.inputSchema,\n }));\n}\n\nexport function toAnthropicThinking(\n thinking: AnthropicThinkingConfig,\n): NonNullable<AnthropicMessagesRequest[\"thinking\"]> {\n if (thinking.type === \"enabled\") {\n const converted: Extract<NonNullable<AnthropicMessagesRequest[\"thinking\"]>, { type: \"enabled\" }> = {\n type: \"enabled\",\n budget_tokens: thinking.budgetTokens,\n };\n if (thinking.display !== undefined) converted.display = thinking.display;\n return converted;\n }\n\n if (thinking.type === \"adaptive\") {\n const converted: Extract<NonNullable<AnthropicMessagesRequest[\"thinking\"]>, { type: \"adaptive\" }> = {\n type: \"adaptive\",\n };\n if (thinking.display !== undefined) converted.display = thinking.display;\n return converted;\n }\n\n return { type: \"disabled\" };\n}\n\nfunction getAnthropicStateContent(state: ModelState | undefined): AnthropicAssistantContentBlock[] | undefined {\n if (state?.type !== ANTHROPIC_MODEL_STATE_TYPE) return undefined;\n if (!isRecord(state.data) || !Array.isArray(state.data.content)) {\n throw new AnthropicProtocolError(\"Anthropic model state is malformed\");\n }\n\n return (state.data as unknown as AnthropicModelStateData).content;\n}\n\nfunction toAssistantTextBlocks(content: ContentPart[]): AnthropicTextBlock[] {\n return content.flatMap((part) => {\n if (part.type === \"reasoning\") return [];\n if (part.type !== \"text\" && part.type !== \"json\") {\n throw new UnsupportedContentError(\"Anthropic adapter\", part.type, \"assistant\");\n }\n return [\n {\n type: \"text\" as const,\n text: part.type === \"text\" ? part.text : serializeJson(part.value),\n },\n ];\n });\n}\n\nfunction toUserBlocks(content: ContentPart[]): AnthropicUserContentBlock[] {\n return content.flatMap<AnthropicUserContentBlock>((part) => {\n if (part.type === \"reasoning\") return [];\n if (part.type === \"text\") return [{ type: \"text\", text: part.text }];\n if (part.type === \"json\") {\n return [{ type: \"text\", text: serializeJson(part.value) }];\n }\n if (part.type === \"image\") {\n return [{ type: \"image\", source: toAnthropicSource(part.source) }];\n }\n if (part.type === \"file\") {\n return [{ type: \"document\", source: toAnthropicSource(part.source) }];\n }\n throw new UnsupportedContentError(\"Anthropic adapter\", part.type, \"user\");\n });\n}\n\nfunction serializeVisibleContent(content: ContentPart[], role: Message[\"role\"] = \"system\"): string {\n return content\n .filter((part) => part.type !== \"reasoning\")\n .map((part) => {\n if (part.type === \"text\") return part.text;\n if (part.type === \"json\") return serializeJson(part.value);\n throw new UnsupportedContentError(\"Anthropic adapter\", part.type, role);\n })\n .join(\"\\n\");\n}\n\nfunction hasMedia(content: readonly ContentPart[]): boolean {\n return content.some((part) => part.type === \"image\" || part.type === \"file\");\n}\n\nfunction toAnthropicSource(source: MediaSource): AnthropicMediaSource {\n if (source.type === \"url\") return { type: \"url\", url: source.url };\n if (source.type === \"file\") return { type: \"file\", file_id: source.fileId };\n return {\n type: \"base64\",\n media_type: source.mediaType,\n data: source.data,\n };\n}\n\nfunction serializeJson(value: unknown): string {\n const serialized = JSON.stringify(value);\n return serialized === undefined ? \"null\" : serialized;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n", "/** @experimental */\nexport class AnthropicError extends Error {\n readonly code: string;\n\n constructor(code: string, message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = new.target.name;\n this.code = code;\n }\n}\n\n/** @experimental */\nexport class AnthropicApiError extends AnthropicError {\n readonly status: number;\n readonly providerType: string | undefined;\n readonly requestId: string | undefined;\n readonly retryAfterMs: number | undefined;\n\n constructor(options: {\n status: number;\n message: string;\n providerType?: string;\n requestId?: string;\n retryAfterMs?: number;\n }) {\n super(\"ANTHROPIC_API_ERROR\", options.message);\n this.status = options.status;\n this.providerType = options.providerType;\n this.requestId = options.requestId;\n this.retryAfterMs = options.retryAfterMs;\n }\n}\n\n/** @experimental */\nexport class AnthropicStreamError extends AnthropicError {\n readonly providerType: string | undefined;\n readonly requestId: string | undefined;\n\n constructor(options: { message: string; providerType?: string; requestId?: string }) {\n super(\"ANTHROPIC_STREAM_ERROR\", options.message);\n this.providerType = options.providerType;\n this.requestId = options.requestId;\n }\n}\n\n/** @experimental */\nexport class AnthropicProtocolError extends AnthropicError {\n constructor(message: string, options?: ErrorOptions) {\n super(\"ANTHROPIC_PROTOCOL_ERROR\", message, options);\n }\n}\n\n/** @experimental */\nexport class AnthropicFinishReasonError extends AnthropicError {\n readonly finishReason: string;\n\n constructor(finishReason: string) {\n super(\"ANTHROPIC_INCOMPLETE_RESPONSE\", `Anthropic stopped with finish reason \"${finishReason}\"`);\n this.finishReason = finishReason;\n }\n}\n", "import type { JsonSchema } from \"@sortedyuan/may/core\";\n\n/** @experimental */\nexport const ANTHROPIC_MODEL_STATE_TYPE = \"@may/provider-anthropic/message-v1\";\n\n/**\n * Provider/model metadata determines concrete supported values.\n * @experimental\n */\nexport type AnthropicReasoningEffort = string;\n\n/** @experimental */\nexport type AnthropicThinkingConfig =\n | {\n type: \"enabled\";\n budgetTokens: number;\n display?: \"summarized\" | \"omitted\";\n }\n | {\n type: \"adaptive\";\n display?: \"summarized\" | \"omitted\";\n }\n | { type: \"disabled\" };\n\nexport interface AnthropicTextBlock {\n cache_control?: AnthropicCacheControl;\n type: \"text\";\n text: string;\n}\n\nexport type AnthropicMediaSource =\n | { type: \"url\"; url: string }\n | { type: \"base64\"; media_type: string; data: string }\n | { type: \"file\"; file_id: string };\n\nexport interface AnthropicImageBlock {\n type: \"image\";\n source: AnthropicMediaSource;\n}\n\nexport interface AnthropicDocumentBlock {\n type: \"document\";\n source: AnthropicMediaSource;\n}\n\nexport type AnthropicUserContentBlock = AnthropicTextBlock | AnthropicImageBlock | AnthropicDocumentBlock;\n\nexport interface AnthropicThinkingBlock {\n type: \"thinking\";\n thinking: string;\n signature: string;\n}\n\nexport interface AnthropicRedactedThinkingBlock {\n type: \"redacted_thinking\";\n data: string;\n}\n\nexport interface AnthropicToolUseBlock {\n type: \"tool_use\";\n id: string;\n name: string;\n input: Record<string, unknown>;\n}\n\nexport type AnthropicAssistantContentBlock =\n AnthropicTextBlock | AnthropicThinkingBlock | AnthropicRedactedThinkingBlock | AnthropicToolUseBlock;\n\nexport interface AnthropicToolResultBlock {\n type: \"tool_result\";\n tool_use_id: string;\n content: string | AnthropicUserContentBlock[];\n is_error?: boolean;\n}\n\nexport interface AnthropicRequestMessage {\n role: \"user\" | \"assistant\";\n content: Array<\n AnthropicAssistantContentBlock | AnthropicToolResultBlock | AnthropicImageBlock | AnthropicDocumentBlock\n >;\n}\n\nexport interface AnthropicToolDefinition {\n cache_control?: AnthropicCacheControl;\n name: string;\n description: string;\n input_schema: JsonSchema;\n}\n\n/** @experimental */\nexport interface AnthropicModelStateData {\n messageId: string;\n content: AnthropicAssistantContentBlock[];\n}\n\nexport interface AnthropicMessagesRequest {\n cache_control?: AnthropicCacheControl;\n model: string;\n max_tokens: number;\n messages: AnthropicRequestMessage[];\n stream: true;\n system?: string | AnthropicTextBlock[];\n tools?: AnthropicToolDefinition[];\n thinking?:\n | {\n type: \"enabled\";\n budget_tokens: number;\n display?: \"summarized\" | \"omitted\";\n }\n | {\n type: \"adaptive\";\n display?: \"summarized\" | \"omitted\";\n }\n | { type: \"disabled\" };\n output_config?: { effort: AnthropicReasoningEffort };\n}\n\nexport interface AnthropicCacheControl {\n readonly type: \"ephemeral\";\n readonly ttl?: \"5m\" | \"1h\";\n}\n", "import type { AssistantMessage, ModelEvent, ToolCall, Usage } from \"@sortedyuan/may/core\";\nimport { readSseData } from \"../openai-compatible/http.js\";\nimport { AnthropicFinishReasonError, AnthropicProtocolError, AnthropicStreamError } from \"./errors.js\";\nimport {\n ANTHROPIC_MODEL_STATE_TYPE,\n type AnthropicAssistantContentBlock,\n type AnthropicRedactedThinkingBlock,\n type AnthropicTextBlock,\n type AnthropicThinkingBlock,\n type AnthropicToolUseBlock,\n} from \"./protocol.js\";\n\ninterface PendingBase {\n stopped: boolean;\n}\n\ninterface PendingText extends PendingBase {\n kind: \"text\";\n block: AnthropicTextBlock;\n}\n\ninterface PendingThinking extends PendingBase {\n kind: \"thinking\";\n block: AnthropicThinkingBlock;\n}\n\ninterface PendingRedactedThinking extends PendingBase {\n kind: \"redacted_thinking\";\n block: AnthropicRedactedThinkingBlock;\n}\n\ninterface PendingToolUse extends PendingBase {\n kind: \"tool_use\";\n block: AnthropicToolUseBlock;\n partialJson: string;\n}\n\ntype PendingBlock = PendingText | PendingThinking | PendingRedactedThinking | PendingToolUse;\n\nexport async function* streamAnthropicResponse(response: Response, signal: AbortSignal): AsyncIterable<ModelEvent> {\n const blocks = new Map<number, PendingBlock>();\n let messageId: string | undefined;\n let sawMessageStart = false;\n let sawMessageStop = false;\n let stopReason: string | undefined;\n let inputTokens: number | undefined;\n let outputTokens: number | undefined;\n let cachedReadTokens: number | undefined;\n let cachedWriteTokens: number | undefined;\n const usageItems = new Map<string, NonNullable<Usage[\"items\"]>[number]>();\n\n for await (const data of readSseData(\n response,\n signal,\n (message, options) => new AnthropicProtocolError(message, options),\n \"Anthropic\",\n )) {\n const event = parseEvent(data);\n\n if (event.type === \"ping\") continue;\n if (event.type === \"error\") throw createStreamError(event);\n\n if (event.type === \"message_start\") {\n if (sawMessageStart) {\n throw new AnthropicProtocolError(\"Anthropic emitted more than one message_start event\");\n }\n const message = requireRecord(event.message, \"message_start.message\");\n messageId = requireString(message.id, \"message_start.message.id\");\n const usage = optionalRecord(message.usage);\n inputTokens = optionalTokenCount(usage?.input_tokens);\n outputTokens = optionalTokenCount(usage?.output_tokens);\n cachedReadTokens = optionalTokenCount(usage?.cache_read_input_tokens);\n cachedWriteTokens = optionalTokenCount(usage?.cache_creation_input_tokens);\n collectUsageItems(usage, usageItems);\n sawMessageStart = true;\n continue;\n }\n\n if (event.type === \"content_block_start\") {\n requireActiveMessage(sawMessageStart, sawMessageStop);\n const index = requireIndex(event.index);\n if (blocks.has(index)) {\n throw new AnthropicProtocolError(`Anthropic started content block ${index} more than once`);\n }\n blocks.set(index, createPendingBlock(event.content_block, index));\n continue;\n }\n\n if (event.type === \"content_block_delta\") {\n requireActiveMessage(sawMessageStart, sawMessageStop);\n const index = requireIndex(event.index);\n const block = requirePendingBlock(blocks, index);\n const delta = requireRecord(event.delta, `content block ${index} delta`);\n const deltaType = requireString(delta.type, `content block ${index} delta.type`);\n\n if (deltaType === \"text_delta\") {\n if (block.kind !== \"text\") throw mismatchedDelta(index, deltaType);\n const text = requireString(delta.text, `content block ${index} text`);\n block.block.text += text;\n if (text !== \"\") yield { type: \"text.delta\", delta: text };\n continue;\n }\n\n if (deltaType === \"thinking_delta\") {\n if (block.kind !== \"thinking\") throw mismatchedDelta(index, deltaType);\n const thinking = requireString(delta.thinking, `content block ${index} thinking`);\n block.block.thinking += thinking;\n if (thinking !== \"\") {\n yield { type: \"reasoning.delta\", delta: thinking };\n }\n continue;\n }\n\n if (deltaType === \"signature_delta\") {\n if (block.kind !== \"thinking\") throw mismatchedDelta(index, deltaType);\n block.block.signature += requireString(delta.signature, `content block ${index} signature`);\n continue;\n }\n\n if (deltaType === \"input_json_delta\") {\n if (block.kind !== \"tool_use\") throw mismatchedDelta(index, deltaType);\n block.partialJson += requireString(delta.partial_json, `content block ${index} partial_json`);\n }\n // Anthropic may add new delta types; unknown ones are ignored.\n continue;\n }\n\n if (event.type === \"content_block_stop\") {\n requireActiveMessage(sawMessageStart, sawMessageStop);\n const index = requireIndex(event.index);\n const block = requirePendingBlock(blocks, index);\n if (block.kind === \"tool_use\" && block.partialJson.trim() !== \"\") {\n block.block.input = parseToolInput(block.partialJson, index);\n }\n block.stopped = true;\n continue;\n }\n\n if (event.type === \"message_delta\") {\n requireActiveMessage(sawMessageStart, sawMessageStop);\n const delta = requireRecord(event.delta, \"message_delta.delta\");\n if (delta.stop_reason !== undefined && delta.stop_reason !== null) {\n stopReason = requireString(delta.stop_reason, \"message_delta.delta.stop_reason\");\n }\n const usage = optionalRecord(event.usage);\n inputTokens = optionalTokenCount(usage?.input_tokens) ?? inputTokens;\n outputTokens = optionalTokenCount(usage?.output_tokens) ?? outputTokens;\n cachedReadTokens = optionalTokenCount(usage?.cache_read_input_tokens) ?? cachedReadTokens;\n cachedWriteTokens = optionalTokenCount(usage?.cache_creation_input_tokens) ?? cachedWriteTokens;\n collectUsageItems(usage, usageItems);\n continue;\n }\n\n if (event.type === \"message_stop\") {\n requireActiveMessage(sawMessageStart, sawMessageStop);\n sawMessageStop = true;\n }\n // Unknown event types are ignored for forward compatibility.\n }\n\n if (!sawMessageStart || messageId === undefined) {\n throw new AnthropicProtocolError(\"Anthropic stream ended without a message_start event\");\n }\n if (!sawMessageStop) {\n throw new AnthropicProtocolError(\"Anthropic stream ended without a message_stop event\");\n }\n if (stopReason === undefined) {\n throw new AnthropicProtocolError(\"Anthropic stream ended without a stop_reason\");\n }\n if (stopReason !== \"end_turn\" && stopReason !== \"tool_use\") {\n throw new AnthropicFinishReasonError(stopReason);\n }\n\n const content = [...blocks.entries()]\n .sort(([left], [right]) => left - right)\n .map(([index, block]) => {\n if (!block.stopped) {\n throw new AnthropicProtocolError(`Anthropic content block ${index} did not stop`);\n }\n return block.block;\n });\n const message = toAssistantMessage(messageId, content);\n const calls = message.toolCalls ?? [];\n if (stopReason === \"tool_use\" && calls.length === 0) {\n throw new AnthropicProtocolError(\"Anthropic stopped for tool_use but emitted no tool calls\");\n }\n if (stopReason !== \"tool_use\" && calls.length > 0) {\n throw new AnthropicProtocolError(`Anthropic emitted tool calls with stop reason \"${stopReason}\"`);\n }\n\n const completed: Extract<ModelEvent, { type: \"response.completed\" }> = {\n type: \"response.completed\",\n message,\n };\n const usage = createUsage(inputTokens, outputTokens, cachedReadTokens, cachedWriteTokens, [...usageItems.values()]);\n if (usage !== undefined) completed.usage = usage;\n yield completed;\n}\n\nfunction parseEvent(data: string): Record<string, unknown> {\n try {\n const event: unknown = JSON.parse(data);\n const record = requireRecord(event, \"stream event\");\n requireString(record.type, \"stream event.type\");\n return record;\n } catch (error) {\n if (error instanceof AnthropicProtocolError) throw error;\n throw new AnthropicProtocolError(\"Anthropic emitted invalid SSE JSON\", { cause: error });\n }\n}\n\nfunction createPendingBlock(value: unknown, index: number): PendingBlock {\n const block = requireRecord(value, `content block ${index}`);\n const type = requireString(block.type, `content block ${index}.type`);\n\n if (type === \"text\") {\n return {\n kind: \"text\",\n stopped: false,\n block: {\n type,\n text: requireString(block.text, `content block ${index}.text`),\n },\n };\n }\n if (type === \"thinking\") {\n return {\n kind: \"thinking\",\n stopped: false,\n block: {\n type,\n thinking: requireString(block.thinking, `content block ${index}.thinking`),\n signature: requireString(block.signature, `content block ${index}.signature`),\n },\n };\n }\n if (type === \"redacted_thinking\") {\n return {\n kind: \"redacted_thinking\",\n stopped: false,\n block: {\n type,\n data: requireString(block.data, `content block ${index}.data`),\n },\n };\n }\n if (type === \"tool_use\") {\n return {\n kind: \"tool_use\",\n stopped: false,\n partialJson: \"\",\n block: {\n type,\n id: requireString(block.id, `content block ${index}.id`),\n name: requireString(block.name, `content block ${index}.name`),\n input: requireObject(block.input, `content block ${index}.input`),\n },\n };\n }\n\n throw new AnthropicProtocolError(`Anthropic emitted unsupported content block type \"${type}\"`);\n}\n\nfunction toAssistantMessage(messageId: string, blocks: AnthropicAssistantContentBlock[]): AssistantMessage {\n const message: AssistantMessage = {\n role: \"assistant\",\n content: [],\n modelState: {\n type: ANTHROPIC_MODEL_STATE_TYPE,\n data: { messageId, content: blocks },\n },\n };\n const calls: ToolCall[] = [];\n\n for (const block of blocks) {\n if (block.type === \"thinking\") {\n message.content.push({ type: \"reasoning\", text: block.thinking });\n } else if (block.type === \"text\") {\n if (block.text !== \"\") {\n message.content.push({ type: \"text\", text: block.text });\n }\n } else if (block.type === \"tool_use\") {\n calls.push({ id: block.id, name: block.name, input: block.input });\n }\n }\n\n if (calls.length > 0) message.toolCalls = calls;\n return message;\n}\n\nfunction createStreamError(event: Record<string, unknown>): AnthropicStreamError {\n const error = optionalRecord(event.error);\n const providerType = optionalString(error?.type);\n const requestId = optionalString(event.request_id);\n const message = optionalString(error?.message) ?? \"Anthropic stream failed\";\n const options: ConstructorParameters<typeof AnthropicStreamError>[0] = {\n message,\n };\n if (providerType !== undefined) options.providerType = providerType;\n if (requestId !== undefined) options.requestId = requestId;\n return new AnthropicStreamError(options);\n}\n\nfunction parseToolInput(input: string, index: number): Record<string, unknown> {\n try {\n return requireObject(JSON.parse(input), `content block ${index} tool input`);\n } catch (error) {\n if (error instanceof AnthropicProtocolError) throw error;\n throw new AnthropicProtocolError(`Anthropic emitted invalid tool input JSON at content block ${index}`, {\n cause: error,\n });\n }\n}\n\nfunction requireActiveMessage(started: boolean, stopped: boolean): void {\n if (!started) {\n throw new AnthropicProtocolError(\"Anthropic emitted content before message_start\");\n }\n if (stopped) {\n throw new AnthropicProtocolError(\"Anthropic emitted content after message_stop\");\n }\n}\n\nfunction requirePendingBlock(blocks: Map<number, PendingBlock>, index: number): PendingBlock {\n const block = blocks.get(index);\n if (!block) {\n throw new AnthropicProtocolError(`Anthropic referenced unknown content block ${index}`);\n }\n if (block.stopped) {\n throw new AnthropicProtocolError(`Anthropic emitted a delta after content block ${index} stopped`);\n }\n return block;\n}\n\nfunction mismatchedDelta(index: number, deltaType: string): AnthropicProtocolError {\n return new AnthropicProtocolError(`Anthropic emitted ${deltaType} for incompatible content block ${index}`);\n}\n\nfunction requireRecord(value: unknown, name: string): Record<string, unknown> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new AnthropicProtocolError(`Anthropic ${name} must be an object`);\n }\n return value as Record<string, unknown>;\n}\n\nfunction requireObject(value: unknown, name: string): Record<string, unknown> {\n return requireRecord(value, name);\n}\n\nfunction optionalRecord(value: unknown): Record<string, unknown> | undefined {\n return typeof value === \"object\" && value !== null && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined;\n}\n\nfunction requireString(value: unknown, name: string): string {\n if (typeof value !== \"string\") {\n throw new AnthropicProtocolError(`Anthropic ${name} must be a string`);\n }\n return value;\n}\n\nfunction optionalString(value: unknown): string | undefined {\n return typeof value === \"string\" ? value : undefined;\n}\n\nfunction requireIndex(value: unknown): number {\n if (!Number.isSafeInteger(value) || (value as number) < 0) {\n throw new AnthropicProtocolError(\"Anthropic content block index must be a non-negative safe integer\");\n }\n return value as number;\n}\n\nfunction optionalTokenCount(value: unknown): number | undefined {\n if (value === undefined) return undefined;\n if (!Number.isSafeInteger(value) || (value as number) < 0)\n throw new AnthropicProtocolError(\"Anthropic usage token count must be a non-negative safe integer\");\n return value as number;\n}\n\nfunction createUsage(\n inputTokens: number | undefined,\n outputTokens: number | undefined,\n cachedReadTokens: number | undefined,\n cachedWriteTokens: number | undefined,\n items: readonly NonNullable<Usage[\"items\"]>[number][],\n): Usage | undefined {\n if (\n inputTokens === undefined &&\n outputTokens === undefined &&\n cachedReadTokens === undefined &&\n cachedWriteTokens === undefined\n )\n return undefined;\n const usage: Usage = {};\n if (inputTokens !== undefined) usage.inputTokens = inputTokens;\n if (outputTokens !== undefined) usage.outputTokens = outputTokens;\n if (cachedReadTokens !== undefined) usage.cachedReadTokens = cachedReadTokens;\n if (cachedWriteTokens !== undefined) usage.cachedWriteTokens = cachedWriteTokens;\n if (items.length > 0) usage.items = items;\n if (cachedReadTokens !== undefined || cachedWriteTokens !== undefined)\n usage.tokenRelations = {\n ...(cachedReadTokens === undefined ? {} : { cachedRead: \"total\" }),\n ...(cachedWriteTokens === undefined ? {} : { cachedWrite: \"total\" }),\n };\n if (inputTokens !== undefined && outputTokens !== undefined) {\n usage.totalTokens = inputTokens + outputTokens + (cachedReadTokens ?? 0) + (cachedWriteTokens ?? 0);\n }\n if (inputTokens === undefined || outputTokens === undefined)\n usage.completeness = { status: \"partial\", reason: \"provider-token-components-missing\" };\n return usage;\n}\n\nfunction collectUsageItems(\n usage: Record<string, unknown> | undefined,\n items: Map<string, NonNullable<Usage[\"items\"]>[number]>,\n): void {\n if (usage === undefined) return;\n const cache =\n usage.cache_creation === undefined || usage.cache_creation === null\n ? undefined\n : requireRecord(usage.cache_creation, \"usage.cache_creation\");\n for (const [field, id] of [\n [\"ephemeral_5m_input_tokens\", \"cache-write-5m\"],\n [\"ephemeral_1h_input_tokens\", \"cache-write-1h\"],\n ] as const) {\n const quantity = optionalTokenCount(cache?.[field]);\n if (quantity !== undefined) items.set(id, { id, quantity, unit: \"tokens\", includedIn: \"cachedWrite\" });\n }\n const server =\n usage.server_tool_use === undefined || usage.server_tool_use === null\n ? undefined\n : requireRecord(usage.server_tool_use, \"usage.server_tool_use\");\n for (const [field, id] of [\n [\"web_search_requests\", \"web-search\"],\n [\"web_fetch_requests\", \"web-fetch\"],\n ] as const) {\n const quantity = optionalTokenCount(server?.[field]);\n if (quantity !== undefined) items.set(id, { id, quantity, unit: \"requests\", includedIn: \"none\" });\n }\n}\n", "import { omitUndefined } from \"@sortedyuan/may/core\";\nimport { OpenAICompatibleChatModel } from \"../openai-compatible/chat-model.js\";\n\n/**\n * Provider/model metadata determines concrete supported values.\n * @experimental\n */\nexport type DeepSeekReasoningEffort = string;\n\n/** @experimental */\nexport interface DeepSeekModelOptions {\n apiKey: string;\n model: string;\n baseURL?: string;\n thinking?: \"enabled\" | \"disabled\";\n reasoningEffort?: DeepSeekReasoningEffort;\n maxTokens?: number;\n fetch?: typeof globalThis.fetch;\n}\n\n/** @experimental */\nexport class DeepSeekModel extends OpenAICompatibleChatModel {\n constructor(options: DeepSeekModelOptions) {\n const { thinking, maxTokens, ...shared } = options;\n super(omitUndefined({ ...shared, maxOutputTokens: maxTokens }), {\n provider: \"DeepSeek\",\n adapter: \"deepseek-chat\",\n errorCodePrefix: \"DEEPSEEK\",\n defaultBaseURL: \"https://api.deepseek.com\",\n maxTokensField: \"max_tokens\",\n streamUsage: true,\n includeToolName: false,\n requireDone: false,\n supportsResponseFormat: false,\n ...(thinking === undefined\n ? {}\n : {\n extendRequest: (body) => {\n body.thinking = { type: thinking };\n },\n }),\n });\n }\n}\n", "import {\n assertModelResponseFormat,\n executeRecordedRequest,\n omitUndefined,\n requestEndpoint,\n validateStructuredModelResponse,\n type Model,\n type ModelEvent,\n type ModelRequest,\n type ModelStreamOptions,\n} from \"@sortedyuan/may/core\";\nimport { toOpenAICompatibleMessages, toOpenAICompatibleTools } from \"./convert.js\";\nimport {\n OpenAICompatibleApiError,\n OpenAICompatibleFinishReasonError,\n OpenAICompatibleProtocolError,\n} from \"./errors.js\";\nimport { parseRetryAfterMs } from \"./http.js\";\nimport type { OpenAICompatibleMessage, OpenAICompatibleToolDefinition } from \"./protocol.js\";\nimport { streamOpenAICompatibleResponse } from \"./stream.js\";\n\n/** @experimental */\nexport interface OpenAICompatibleChatRequest {\n model: string;\n messages: OpenAICompatibleMessage[];\n stream: true;\n stream_options?: { include_usage: true };\n tools?: OpenAICompatibleToolDefinition[];\n tool_stream?: true;\n max_tokens?: number;\n max_completion_tokens?: number;\n reasoning_effort?: string;\n store?: boolean;\n response_format?: Readonly<Record<string, unknown>>;\n thinking?: Readonly<Record<string, unknown>>;\n}\n\n/**\n * Differences between OpenAI-compatible chat endpoints.\n * @experimental\n */\nexport interface OpenAICompatibleDialect {\n /** Display name used in error messages. */\n readonly provider: string;\n /** Request recording adapter identifier. */\n readonly adapter: string;\n /** Prefix of error codes, for example `DEEPSEEK` in `DEEPSEEK_API_ERROR`. */\n readonly errorCodePrefix: string;\n readonly defaultBaseURL: string;\n readonly maxTokensField: \"max_tokens\" | \"max_completion_tokens\";\n readonly streamUsage: boolean;\n readonly includeToolName: boolean;\n readonly requireDone: boolean;\n readonly supportsResponseFormat: boolean;\n /** Add provider-specific request fields after the shared fields are set. */\n readonly extendRequest?: (body: OpenAICompatibleChatRequest, request: ModelRequest) => void;\n}\n\n/** @experimental */\nexport interface OpenAICompatibleChatModelOptions {\n apiKey: string;\n model: string;\n baseURL?: string;\n maxOutputTokens?: number;\n reasoningEffort?: string;\n fetch?: typeof globalThis.fetch;\n}\n\n/** @experimental */\nexport class OpenAICompatibleChatModel implements Model {\n readonly supportsRequestRecording = true;\n private readonly apiKey: string;\n private readonly model: string;\n private readonly baseURL: string;\n private readonly maxOutputTokens: number | undefined;\n private readonly reasoningEffort: string | undefined;\n private readonly fetchImplementation: typeof globalThis.fetch;\n\n constructor(\n options: OpenAICompatibleChatModelOptions,\n private readonly dialect: OpenAICompatibleDialect,\n ) {\n if (options.apiKey.trim() === \"\") throw new TypeError(\"apiKey must not be empty\");\n if (options.model.trim() === \"\") throw new TypeError(\"model must not be empty\");\n if (\n options.maxOutputTokens !== undefined &&\n (!Number.isSafeInteger(options.maxOutputTokens) || options.maxOutputTokens < 1)\n ) {\n throw new RangeError(\"Maximum output tokens must be a positive safe integer\");\n }\n this.apiKey = options.apiKey;\n this.model = options.model;\n this.baseURL = (options.baseURL ?? dialect.defaultBaseURL).replace(/\\/+$/, \"\");\n this.maxOutputTokens = options.maxOutputTokens;\n this.reasoningEffort = options.reasoningEffort;\n this.fetchImplementation = options.fetch ?? globalThis.fetch;\n }\n\n async *stream(request: ModelRequest, options: ModelStreamOptions): AsyncIterable<ModelEvent> {\n if (this.dialect.supportsResponseFormat) assertModelResponseFormat(request);\n else if (request.responseFormat !== undefined)\n throw new TypeError(`${this.dialect.provider} adapter does not support responseFormat`);\n yield* executeRecordedRequest(\n {\n version: 1,\n adapter: this.dialect.adapter,\n purpose: \"generation\",\n endpoint: requestEndpoint(`${this.baseURL}/chat/completions`),\n request,\n body: this.createRequest(request),\n },\n options.recordRequest,\n options.signal,\n (body) => this.execute(body, request, options),\n );\n }\n\n private async *execute(body: string, request: ModelRequest, options: ModelStreamOptions): AsyncIterable<ModelEvent> {\n const response = await this.fetchImplementation(`${this.baseURL}/chat/completions`, {\n method: \"POST\",\n headers: { authorization: `Bearer ${this.apiKey}`, \"content-type\": \"application/json\" },\n body,\n signal: options.signal,\n });\n if (!response.ok) throw await this.createApiError(response);\n const { provider, errorCodePrefix } = this.dialect;\n for await (const event of streamOpenAICompatibleResponse(response, {\n signal: options.signal,\n providerName: provider,\n requireDone: this.dialect.requireDone,\n protocolError: (message, errorOptions) =>\n new OpenAICompatibleProtocolError(provider, errorCodePrefix, message, errorOptions),\n finishReasonError: (finishReason) =>\n new OpenAICompatibleFinishReasonError(provider, errorCodePrefix, finishReason),\n })) {\n if (event.type === \"response.completed\" && this.dialect.supportsResponseFormat)\n validateStructuredModelResponse(event.message, request, event);\n yield event;\n }\n }\n\n private createRequest(request: ModelRequest): OpenAICompatibleChatRequest {\n const body: OpenAICompatibleChatRequest = {\n model: this.model,\n messages: toOpenAICompatibleMessages(request.messages, { includeToolName: this.dialect.includeToolName }),\n stream: true,\n };\n if (this.dialect.streamUsage) body.stream_options = { include_usage: true };\n if (request.tools.length > 0) body.tools = toOpenAICompatibleTools(request.tools);\n if (this.maxOutputTokens !== undefined) body[this.dialect.maxTokensField] = this.maxOutputTokens;\n if (this.reasoningEffort !== undefined) body.reasoning_effort = this.reasoningEffort;\n if (request.responseFormat !== undefined) {\n const format = request.responseFormat;\n body.response_format =\n format.type === \"json\"\n ? { type: \"json_object\" }\n : {\n type: \"json_schema\",\n json_schema: omitUndefined({ name: format.name, schema: format.schema, strict: format.strict }),\n };\n }\n this.dialect.extendRequest?.(body, request);\n return body;\n }\n\n private async createApiError(response: Response): Promise<OpenAICompatibleApiError> {\n const text = await response.text();\n let message = text || `${this.dialect.provider} request failed with status ${response.status}`;\n let providerType: string | undefined;\n let providerCode: string | number | undefined;\n let parsed: { error?: { message?: unknown; type?: unknown; code?: unknown } } | undefined;\n try {\n parsed = JSON.parse(text) as typeof parsed;\n } catch (error) {\n // Endpoints may return plain text errors; the response text is the message.\n if (!(error instanceof SyntaxError)) throw error;\n }\n if (typeof parsed?.error?.message === \"string\") message = parsed.error.message;\n if (typeof parsed?.error?.type === \"string\") providerType = parsed.error.type;\n if (typeof parsed?.error?.code === \"string\" || typeof parsed?.error?.code === \"number\")\n providerCode = parsed.error.code;\n const retryAfterMs = parseRetryAfterMs(response.headers.get(\"retry-after\"));\n return new OpenAICompatibleApiError(\n this.dialect.provider,\n this.dialect.errorCodePrefix,\n omitUndefined({\n status: response.status,\n message,\n providerType,\n providerCode,\n retryAfterMs,\n }),\n );\n }\n}\n", "import type { ContentPart, MediaSource, Message, ToolCall, ToolDefinition } from \"@sortedyuan/may/core\";\nimport { UnsupportedContentError, omitUndefined } from \"@sortedyuan/may/core\";\nimport type { OpenAICompatibleMessage, OpenAICompatibleToolCall, OpenAICompatibleToolDefinition } from \"./protocol.js\";\n\n/** @experimental */\nexport function toOpenAICompatibleMessages(\n messages: readonly Message[],\n options: { includeToolName?: boolean } = {},\n): OpenAICompatibleMessage[] {\n return messages.map((message) => {\n if (message.role === \"system\") {\n return {\n role: \"system\",\n content: serializeVisibleContent(message.content, \"system\"),\n };\n }\n\n if (message.role === \"user\") {\n return { role: \"user\", content: toUserContent(message.content) };\n }\n\n if (message.role === \"tool\") {\n const converted: Extract<OpenAICompatibleMessage, { role: \"tool\" }> = {\n role: \"tool\",\n tool_call_id: message.toolCallId,\n content: serializeVisibleContent(message.content, \"tool\"),\n };\n if (options.includeToolName) converted.name = message.name;\n return converted;\n }\n\n const converted: Extract<OpenAICompatibleMessage, { role: \"assistant\" }> = {\n role: \"assistant\",\n content: serializeVisibleContent(message.content, \"assistant\"),\n };\n const reasoningParts = message.content.filter((part) => part.type === \"reasoning\");\n\n if (reasoningParts.length > 0) {\n converted.reasoning_content = reasoningParts.map((part) => part.text).join(\"\");\n }\n if (message.toolCalls !== undefined) {\n converted.tool_calls = message.toolCalls.map(convertToolCall);\n }\n\n return converted;\n });\n}\n\n/** @experimental */\nexport function toOpenAICompatibleTools(tools: readonly ToolDefinition[]): OpenAICompatibleToolDefinition[] {\n return tools.map((tool) => ({\n type: \"function\",\n function: {\n name: tool.name,\n description: tool.description,\n parameters: tool.inputSchema,\n },\n }));\n}\n\nfunction convertToolCall(call: ToolCall): OpenAICompatibleToolCall {\n return {\n id: call.id,\n type: \"function\",\n function: {\n name: call.name,\n arguments: serializeJson(call.input),\n },\n };\n}\n\nfunction toUserContent(content: ContentPart[]): Extract<OpenAICompatibleMessage, { role: \"user\" }>[\"content\"] {\n const hasImages = content.some((part) => part.type === \"image\");\n if (!hasImages) return serializeVisibleContent(content, \"user\");\n\n return content.flatMap<\n { type: \"text\"; text: string } | { type: \"image_url\"; image_url: { url: string; detail?: string } }\n >((part) => {\n if (part.type === \"reasoning\") return [];\n if (part.type === \"text\") return [{ type: \"text\" as const, text: part.text }];\n if (part.type === \"json\") {\n return [{ type: \"text\" as const, text: serializeJson(part.value) }];\n }\n if (part.type === \"image\") {\n const imageUrl = imageSourceUrl(part.source);\n return [\n {\n type: \"image_url\" as const,\n image_url: omitUndefined({ url: imageUrl, detail: part.detail }),\n },\n ];\n }\n throw new UnsupportedContentError(\"OpenAI-compatible chat adapter\", part.type, \"user\");\n });\n}\n\nfunction serializeVisibleContent(content: ContentPart[], role: Message[\"role\"]): string {\n return content\n .filter((part) => part.type !== \"reasoning\")\n .map((part) => {\n if (part.type === \"text\") return part.text;\n if (part.type === \"json\") return serializeJson(part.value);\n throw new UnsupportedContentError(\"OpenAI-compatible chat adapter\", part.type, role);\n })\n .join(\"\\n\");\n}\n\nfunction imageSourceUrl(source: MediaSource): string {\n if (source.type === \"url\") return source.url;\n if (source.type === \"base64\") {\n return `data:${source.mediaType};base64,${source.data}`;\n }\n throw new UnsupportedContentError(\"OpenAI-compatible chat adapter\", \"image file-id source\", \"user\");\n}\n\nfunction serializeJson(value: unknown): string {\n const serialized = JSON.stringify(value);\n return serialized === undefined ? \"null\" : serialized;\n}\n", "/**\n * Errors from any OpenAI-compatible chat endpoint. `provider` names the dialect, `code` keeps its prefix.\n * @experimental\n */\nexport class OpenAICompatibleError extends Error {\n readonly code: string;\n readonly provider: string;\n\n constructor(provider: string, code: string, message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = new.target.name;\n this.provider = provider;\n this.code = code;\n }\n}\n\n/** @experimental */\nexport class OpenAICompatibleApiError extends OpenAICompatibleError {\n readonly status: number;\n readonly providerType: string | undefined;\n readonly providerCode: string | number | undefined;\n readonly retryAfterMs: number | undefined;\n\n constructor(\n provider: string,\n codePrefix: string,\n options: {\n status: number;\n message: string;\n providerType?: string;\n providerCode?: string | number;\n retryAfterMs?: number;\n },\n ) {\n super(provider, `${codePrefix}_API_ERROR`, options.message);\n this.status = options.status;\n this.providerType = options.providerType;\n this.providerCode = options.providerCode;\n this.retryAfterMs = options.retryAfterMs;\n }\n}\n\n/** @experimental */\nexport class OpenAICompatibleProtocolError extends OpenAICompatibleError {\n constructor(provider: string, codePrefix: string, message: string, options?: ErrorOptions) {\n super(provider, `${codePrefix}_PROTOCOL_ERROR`, message, options);\n }\n}\n\n/** @experimental */\nexport class OpenAICompatibleFinishReasonError extends OpenAICompatibleError {\n readonly finishReason: string;\n\n constructor(provider: string, codePrefix: string, finishReason: string) {\n super(provider, `${codePrefix}_INCOMPLETE_RESPONSE`, `${provider} stopped with finish reason \"${finishReason}\"`);\n this.finishReason = finishReason;\n }\n}\n", "import type { AssistantMessage, ModelEvent, ToolCall, Usage } from \"@sortedyuan/may/core\";\nimport type { OpenAICompatibleChunk, OpenAICompatibleToolCallDelta } from \"./protocol.js\";\nimport { readSseData } from \"./http.js\";\n\n/** @experimental */\nexport interface OpenAICompatibleStreamOptions {\n signal: AbortSignal;\n providerName: string;\n requireDone?: boolean;\n protocolError(message: string, options?: ErrorOptions): Error;\n finishReasonError(finishReason: string): Error;\n}\n\ninterface PendingToolCall {\n id: string;\n name: string;\n arguments: string;\n}\n\n/** @experimental */\nexport async function* streamOpenAICompatibleResponse(\n response: Response,\n options: OpenAICompatibleStreamOptions,\n): AsyncIterable<ModelEvent> {\n let text = \"\";\n let reasoning = \"\";\n let hasReasoningContent = false;\n let usage: Usage | undefined;\n let finishReason: string | undefined;\n let receivedDone = false;\n const pendingCalls = new Map<number, PendingToolCall>();\n\n for await (const data of readSseData(response, options.signal, options.protocolError, options.providerName)) {\n if (data === \"[DONE]\") {\n receivedDone = true;\n break;\n }\n const chunk = parseChunk(data, options);\n // \u670D\u52A1\u7AEF\u53EF\u80FD\u5728 HTTP 200 \u7684\u6D41\u4E2D\u62A5\u544A\u9519\u8BEF\uFF0C\u5FC5\u987B\u5728 [DONE] \u4E0E finish_reason \u5224\u5B9A\u4E4B\u524D\u5904\u7406\u3002\n if (chunk.error !== undefined) {\n throw options.protocolError(\n `${options.providerName} stream reported an error: ${describeStreamError(chunk.error)}`,\n );\n }\n\n if (chunk.usage) usage = convertUsage(chunk.usage, options);\n\n for (const choice of chunk.choices ?? []) {\n if (choice.index !== 0) continue;\n const delta = choice.delta;\n\n if (typeof delta?.reasoning_content === \"string\") {\n hasReasoningContent = true;\n if (delta.reasoning_content !== \"\") {\n reasoning += delta.reasoning_content;\n yield { type: \"reasoning.delta\", delta: delta.reasoning_content };\n }\n }\n\n if (delta?.content) {\n text += delta.content;\n yield { type: \"text.delta\", delta: delta.content };\n }\n\n if (delta?.refusal) {\n text += delta.refusal;\n yield { type: \"text.delta\", delta: delta.refusal };\n }\n\n for (const toolDelta of delta?.tool_calls ?? []) {\n mergeToolCall(pendingCalls, toolDelta);\n }\n\n if (choice.finish_reason !== null && choice.finish_reason !== undefined) {\n finishReason = choice.finish_reason;\n }\n }\n }\n\n if (options.requireDone && !receivedDone) {\n throw options.protocolError(`${options.providerName} stream ended without [DONE]`);\n }\n\n if (finishReason === undefined) {\n throw options.protocolError(`${options.providerName} stream ended without a finish_reason`);\n }\n if (finishReason !== \"stop\" && finishReason !== \"tool_calls\") {\n throw options.finishReasonError(finishReason);\n }\n\n const toolCalls = completeToolCalls(pendingCalls, options);\n if (finishReason === \"tool_calls\" && toolCalls.length === 0) {\n throw options.protocolError(`${options.providerName} finished with tool_calls but emitted no tool calls`);\n }\n\n const message: AssistantMessage = { role: \"assistant\", content: [] };\n if (hasReasoningContent) {\n message.content.push({ type: \"reasoning\", text: reasoning });\n }\n if (text !== \"\") message.content.push({ type: \"text\", text });\n if (toolCalls.length > 0) message.toolCalls = toolCalls;\n\n const completed: Extract<ModelEvent, { type: \"response.completed\" }> = {\n type: \"response.completed\",\n message,\n };\n if (usage !== undefined) completed.usage = usage;\n yield completed;\n}\n\nfunction parseChunk(data: string, options: OpenAICompatibleStreamOptions): OpenAICompatibleChunk {\n try {\n const value: unknown = JSON.parse(data);\n if (typeof value !== \"object\" || value === null) {\n throw new TypeError(\"chunk is not an object\");\n }\n return value as OpenAICompatibleChunk;\n } catch (error) {\n throw options.protocolError(`${options.providerName} emitted invalid SSE JSON`, { cause: error });\n }\n}\n\n/** \u53EA\u63D0\u53D6\u670D\u52A1\u7AEF error \u7684 message\u3001type\u3001code\uFF0C\u4E0D\u8F93\u51FA\u6574\u4E2A\u54CD\u5E94\u5185\u5BB9\u3002 */\nfunction describeStreamError(error: unknown): string {\n if (typeof error === \"string\") {\n return error.trim() === \"\" ? \"an empty error string\" : error;\n }\n if (typeof error === \"number\" || typeof error === \"boolean\") {\n return `a ${typeof error} error value ${String(error)}`;\n }\n if (error === null) return \"a null error value\";\n if (Array.isArray(error)) return \"an array error value\";\n if (typeof error !== \"object\") return `an unsupported ${typeof error} error value`;\n\n const payload = error as { message?: unknown; type?: unknown; code?: unknown };\n const details: string[] = [];\n const message = readText(payload.message);\n const type = readText(payload.type);\n const code = readText(payload.code) ?? readNumber(payload.code);\n if (message !== undefined) details.push(message);\n if (type !== undefined) details.push(`type: ${type}`);\n if (code !== undefined) details.push(`code: ${code}`);\n if (details.length === 0) return \"an error object without message, type, or code\";\n return details.join(\" \");\n}\n\nfunction readText(value: unknown): string | undefined {\n if (typeof value !== \"string\") return undefined;\n return value.trim() === \"\" ? undefined : value;\n}\n\nfunction readNumber(value: unknown): string | undefined {\n if (typeof value !== \"number\" || !Number.isFinite(value)) return undefined;\n return String(value);\n}\n\nfunction mergeToolCall(calls: Map<number, PendingToolCall>, delta: OpenAICompatibleToolCallDelta): void {\n const call = calls.get(delta.index) ?? { id: \"\", name: \"\", arguments: \"\" };\n if (delta.id !== undefined) call.id = delta.id;\n if (delta.function?.name !== undefined) call.name += delta.function.name;\n if (delta.function?.arguments !== undefined) {\n call.arguments += delta.function.arguments;\n }\n calls.set(delta.index, call);\n}\n\nfunction completeToolCalls(calls: Map<number, PendingToolCall>, options: OpenAICompatibleStreamOptions): ToolCall[] {\n return [...calls.entries()]\n .sort(([left], [right]) => left - right)\n .map(([index, call]) => {\n if (call.id === \"\" || call.name === \"\") {\n throw options.protocolError(`${options.providerName} emitted an incomplete tool call at index ${index}`);\n }\n\n return {\n id: call.id,\n name: call.name,\n input: parseToolInput(call.arguments, options),\n };\n });\n}\n\nfunction parseToolInput(input: string, options: OpenAICompatibleStreamOptions): unknown {\n if (input === \"\") return {};\n try {\n return JSON.parse(input);\n } catch {\n throw options.protocolError(`${options.providerName} emitted invalid tool argument JSON`);\n }\n}\n\nfunction convertUsage(\n usage: NonNullable<OpenAICompatibleChunk[\"usage\"]>,\n options: OpenAICompatibleStreamOptions,\n): Usage {\n const converted: Usage = {};\n const token = (value: unknown, field: string): number | undefined => {\n if (value === undefined) return undefined;\n if (!Number.isSafeInteger(value) || (value as number) < 0)\n throw options.protocolError(`${options.providerName} usage.${field} must be a non-negative safe integer`);\n return value as number;\n };\n if (usage.prompt_tokens !== undefined) {\n converted.inputTokens = token(usage.prompt_tokens, \"prompt_tokens\")!;\n }\n if (usage.completion_tokens !== undefined) {\n converted.outputTokens = token(usage.completion_tokens, \"completion_tokens\")!;\n }\n if (usage.total_tokens !== undefined) {\n converted.totalTokens = token(usage.total_tokens, \"total_tokens\")!;\n }\n const cachedReadTokens = token(\n usage.prompt_tokens_details?.cached_tokens ?? usage.prompt_cache_hit_tokens,\n \"cached_tokens\",\n );\n const cachedWriteTokens = token(usage.prompt_tokens_details?.cache_write_tokens, \"cache_write_tokens\");\n const reasoningTokens = token(usage.completion_tokens_details?.reasoning_tokens, \"reasoning_tokens\");\n if (cachedReadTokens !== undefined) converted.cachedReadTokens = cachedReadTokens;\n if (cachedWriteTokens !== undefined) converted.cachedWriteTokens = cachedWriteTokens;\n if (reasoningTokens !== undefined) converted.reasoningTokens = reasoningTokens;\n if (cachedReadTokens !== undefined || cachedWriteTokens !== undefined || reasoningTokens !== undefined)\n converted.tokenRelations = {\n ...(cachedReadTokens === undefined ? {} : { cachedRead: \"input\" }),\n ...(cachedWriteTokens === undefined ? {} : { cachedWrite: \"input\" }),\n ...(reasoningTokens === undefined ? {} : { reasoning: \"output\" }),\n };\n const items: NonNullable<Usage[\"items\"]>[number][] = [];\n const cachedMiss = token(usage.prompt_cache_miss_tokens, \"prompt_cache_miss_tokens\");\n if (\n cachedMiss !== undefined &&\n cachedReadTokens !== undefined &&\n converted.inputTokens !== undefined &&\n cachedReadTokens + cachedMiss !== converted.inputTokens\n )\n throw options.protocolError(`${options.providerName} cache token counts do not match prompt_tokens`);\n for (const [id, value] of [\n [\"input-audio\", usage.prompt_tokens_details?.audio_tokens],\n [\"output-audio\", usage.completion_tokens_details?.audio_tokens],\n ] as const) {\n const quantity = token(value, id);\n if (quantity !== undefined && quantity > 0)\n items.push({ id, quantity, unit: \"tokens\", includedIn: id === \"input-audio\" ? \"input\" : \"output\" });\n }\n if (items.length > 0) converted.items = items;\n if (converted.inputTokens === undefined || converted.outputTokens === undefined)\n converted.completeness = { status: \"partial\", reason: \"provider-token-components-missing\" };\n return converted;\n}\n", "import { omitUndefined } from \"@sortedyuan/may/core\";\nimport { OpenAICompatibleChatModel } from \"../openai-compatible/chat-model.js\";\n\n/**\n * Provider/model metadata determines concrete supported values.\n * @experimental\n */\nexport type KimiReasoningEffort = string;\n\n/** @experimental */\nexport interface KimiThinkingConfig {\n type: \"enabled\" | \"disabled\";\n keep?: \"all\" | null;\n}\n\n/** @experimental */\nexport interface KimiModelOptions {\n apiKey: string;\n model: string;\n baseURL?: string;\n thinking?: Readonly<KimiThinkingConfig>;\n reasoningEffort?: KimiReasoningEffort;\n maxTokens?: number;\n fetch?: typeof globalThis.fetch;\n}\n\n/** @experimental */\nexport class KimiModel extends OpenAICompatibleChatModel {\n constructor(options: KimiModelOptions) {\n const { thinking, maxTokens, ...shared } = options;\n const configured = thinking === undefined ? undefined : { ...thinking };\n super(omitUndefined({ ...shared, maxOutputTokens: maxTokens }), {\n provider: \"Kimi\",\n adapter: \"kimi-chat\",\n errorCodePrefix: \"KIMI\",\n defaultBaseURL: \"https://api.moonshot.ai/v1\",\n maxTokensField: \"max_completion_tokens\",\n streamUsage: true,\n includeToolName: true,\n requireDone: true,\n supportsResponseFormat: false,\n ...(configured === undefined\n ? {}\n : {\n extendRequest: (body) => {\n body.thinking = { ...configured };\n },\n }),\n });\n }\n}\n", "import { omitUndefined } from \"@sortedyuan/may/core\";\n\n/** @experimental */\nexport class OpenAIResponsesError extends Error {\n readonly status: number | undefined;\n readonly providerType: string | undefined;\n readonly providerCode: string | undefined;\n readonly requestId: string | undefined;\n readonly retryAfterMs: number | undefined;\n\n constructor(\n message: string,\n options: {\n status?: number;\n providerType?: string;\n providerCode?: string;\n requestId?: string;\n retryAfterMs?: number;\n cause?: unknown;\n } = {},\n ) {\n super(message, omitUndefined({ cause: options.cause }));\n this.name = \"OpenAIResponsesError\";\n this.status = options.status;\n this.providerType = options.providerType;\n this.providerCode = options.providerCode;\n this.requestId = options.requestId;\n this.retryAfterMs = options.retryAfterMs;\n }\n}\n\n/** @experimental */\nexport class OpenAIResponsesProtocolError extends OpenAIResponsesError {\n constructor(message: string, options: ErrorOptions = {}) {\n super(message, omitUndefined({ cause: options.cause }));\n this.name = \"OpenAIResponsesProtocolError\";\n }\n}\n", "import type {\n ContextSnapshot,\n Message,\n Model,\n ModelContextCompactor,\n ModelEvent,\n ModelRequest,\n ModelStreamOptions,\n} from \"@sortedyuan/may/core\";\nimport { parseRetryAfterMs } from \"../openai-compatible/http.js\";\nimport {\n executeRecordedRequest,\n executeRecordedOperation,\n requestEndpoint,\n type ModelRequestRecorder,\n} from \"@sortedyuan/may/core\";\nimport { assertModelResponseFormat, omitUndefined, validateStructuredModelResponse } from \"@sortedyuan/may/core\";\n\nimport { toOpenAIResponsesRequestParts, toOpenAIResponsesTools } from \"./convert.js\";\nimport { OpenAIResponsesError, OpenAIResponsesProtocolError } from \"./errors.js\";\nimport {\n OPENAI_RESPONSES_MODEL_STATE_TYPE,\n type OpenAIReasoningEffort,\n type OpenAIReasoningSummary,\n} from \"./protocol.js\";\nimport { parseUsage, streamOpenAIResponse } from \"./stream.js\";\n\n/** @experimental */\nexport interface OpenAIResponsesModelOptions {\n readonly apiKey: string;\n readonly model: string;\n readonly baseURL?: string;\n readonly maxOutputTokens?: number;\n readonly reasoningEffort?: OpenAIReasoningEffort;\n readonly reasoningSummary?: OpenAIReasoningSummary;\n readonly serverCompactThreshold?: number;\n readonly store?: boolean;\n readonly fetch?: typeof globalThis.fetch;\n}\n\n/** @experimental */\nexport class OpenAIResponsesModel implements Model {\n readonly supportsRequestRecording = true;\n readonly contextCompactor: ModelContextCompactor;\n\n private readonly apiKey: string;\n private readonly model: string;\n private readonly baseURL: string;\n private readonly maxOutputTokens: number | undefined;\n private readonly reasoningEffort: OpenAIReasoningEffort | undefined;\n private readonly reasoningSummary: OpenAIReasoningSummary | undefined;\n private readonly serverCompactThreshold: number | undefined;\n private readonly store: boolean;\n private readonly fetchImplementation: typeof globalThis.fetch;\n\n constructor(options: OpenAIResponsesModelOptions) {\n if (options.apiKey.trim() === \"\") throw new TypeError(\"apiKey must not be empty\");\n if (options.model.trim() === \"\") throw new TypeError(\"model must not be empty\");\n validateOptionalPositiveInteger(options.maxOutputTokens, \"maxOutputTokens\");\n validateOptionalPositiveInteger(options.serverCompactThreshold, \"serverCompactThreshold\");\n this.apiKey = options.apiKey;\n this.model = options.model;\n this.baseURL = (options.baseURL ?? \"https://api.openai.com/v1\").replace(/\\/+$/u, \"\");\n this.maxOutputTokens = options.maxOutputTokens;\n this.reasoningEffort = options.reasoningEffort;\n this.reasoningSummary = options.reasoningSummary;\n this.serverCompactThreshold = options.serverCompactThreshold;\n this.store = options.store ?? false;\n this.fetchImplementation = options.fetch ?? globalThis.fetch;\n this.contextCompactor = {\n name: \"openai-responses-compact\",\n compact: (snapshot, compactOptions) =>\n this.compact(snapshot, compactOptions.signal, compactOptions.recordRequest),\n };\n }\n\n async *stream(request: ModelRequest, options: ModelStreamOptions): AsyncIterable<ModelEvent> {\n assertModelResponseFormat(request);\n const parts = toOpenAIResponsesRequestParts(request.messages);\n const body: Record<string, unknown> = {\n model: this.model,\n input: parts.input,\n stream: true,\n store: this.store,\n include: [\"reasoning.encrypted_content\"],\n };\n if (parts.instructions !== undefined) body.instructions = parts.instructions;\n if (request.tools.length > 0) body.tools = toOpenAIResponsesTools(request.tools);\n if (request.responseFormat !== undefined) {\n const format = request.responseFormat;\n body.text = {\n format:\n format.type === \"json\"\n ? { type: \"json_object\" }\n : omitUndefined({ type: \"json_schema\", name: format.name, schema: format.schema, strict: format.strict }),\n };\n }\n if (this.maxOutputTokens !== undefined) {\n body.max_output_tokens = this.maxOutputTokens;\n }\n const reasoning = this.reasoningConfig();\n if (reasoning !== undefined) body.reasoning = reasoning;\n if (this.serverCompactThreshold !== undefined) {\n body.context_management = [\n {\n type: \"compaction\",\n compact_threshold: this.serverCompactThreshold,\n },\n ];\n }\n\n yield* executeRecordedRequest(\n {\n version: 1,\n adapter: \"openai-responses\",\n purpose: \"generation\",\n endpoint: requestEndpoint(`${this.baseURL}/responses`),\n request,\n body,\n },\n options.recordRequest,\n options.signal,\n (body) => this.execute(body, request, options),\n );\n }\n\n private async *execute(body: string, request: ModelRequest, options: ModelStreamOptions): AsyncIterable<ModelEvent> {\n const response = await this.fetch(\"/responses\", body, options.signal);\n for await (const event of streamOpenAIResponse(response, options.signal)) {\n if (event.type === \"response.completed\") validateStructuredModelResponse(event.message, request, event);\n yield event;\n }\n }\n\n private async compact(\n snapshot: Readonly<ContextSnapshot>,\n signal: AbortSignal | undefined,\n recorder?: ModelRequestRecorder,\n ) {\n const effectiveSignal = signal ?? new AbortController().signal;\n const parts = toOpenAIResponsesRequestParts(snapshot.messages, snapshot.instructions);\n const body: Record<string, unknown> = {\n model: this.model,\n input: parts.input,\n };\n if (parts.instructions !== undefined) body.instructions = parts.instructions;\n const request: ModelRequest = {\n messages:\n snapshot.instructions === undefined\n ? snapshot.messages\n : [{ role: \"system\", content: [{ type: \"text\", text: snapshot.instructions }] }, ...snapshot.messages],\n tools: [],\n };\n return executeRecordedOperation(\n {\n version: 1,\n adapter: \"openai-responses\",\n purpose: \"compaction\",\n endpoint: requestEndpoint(`${this.baseURL}/responses/compact`),\n request,\n body,\n },\n recorder,\n effectiveSignal,\n (serialized) => this.executeCompact(serialized, effectiveSignal),\n );\n }\n\n private async executeCompact(body: string, effectiveSignal: AbortSignal) {\n const response = await this.fetch(\"/responses/compact\", body, effectiveSignal);\n const value = await response.json().catch((error) => {\n throw new OpenAIResponsesProtocolError(\"OpenAI Responses compact returned invalid JSON\", { cause: error });\n });\n const compacted = requireRecord(value, \"compacted response\");\n if (compacted.object !== \"response.compaction\") {\n throw new OpenAIResponsesProtocolError(\"OpenAI Responses compact returned an unexpected object\");\n }\n if (!Array.isArray(compacted.output)) {\n throw new OpenAIResponsesProtocolError(\"OpenAI Responses compact output must be an array\");\n }\n if (\n !compacted.output.some(\n (item) => typeof item === \"object\" && item !== null && \"type\" in item && item.type === \"compaction\",\n )\n ) {\n throw new OpenAIResponsesProtocolError(\"OpenAI Responses compact output has no compaction item\");\n }\n const usage = parseUsage(compacted.usage);\n const messages: Message[] = [\n {\n role: \"assistant\",\n content: [],\n modelState: {\n type: OPENAI_RESPONSES_MODEL_STATE_TYPE,\n data: { items: compacted.output },\n },\n },\n ];\n return omitUndefined({\n messages,\n // \u538B\u7F29\u8BF7\u6C42\u672C\u8EAB\u5C31\u662F\u4E00\u6B21 provider \u8C03\u7528\uFF0C\u5B83\u7684 usage \u4E00\u5E76\u4E0A\u62A5\u7ED9\u8BA1\u8D26\u65B9\u3002\n usage,\n effectiveTokens: usage?.outputTokens,\n });\n }\n\n private reasoningConfig(): Record<string, unknown> | undefined {\n if (this.reasoningEffort === undefined && this.reasoningSummary === undefined) {\n return undefined;\n }\n return omitUndefined({\n effort: this.reasoningEffort,\n generate_summary: this.reasoningSummary,\n });\n }\n\n private async fetch(path: string, body: Record<string, unknown> | string, signal: AbortSignal): Promise<Response> {\n const response = await this.fetchImplementation(`${this.baseURL}${path}`, {\n method: \"POST\",\n headers: {\n authorization: `Bearer ${this.apiKey}`,\n \"content-type\": \"application/json\",\n },\n body: typeof body === \"string\" ? body : JSON.stringify(body),\n signal,\n });\n if (!response.ok) throw await createApiError(response);\n return response;\n }\n}\n\nasync function createApiError(response: Response): Promise<OpenAIResponsesError> {\n const text = await response.text();\n let message = text || `OpenAI request failed with status ${response.status}`;\n let providerType: string | undefined;\n let providerCode: string | undefined;\n let requestId = response.headers.get(\"x-request-id\") ?? undefined;\n try {\n const body = requireRecord(JSON.parse(text), \"error response\");\n const error = requireRecord(body.error, \"error response.error\");\n if (typeof error.message === \"string\") message = error.message;\n if (typeof error.type === \"string\") providerType = error.type;\n if (typeof error.code === \"string\") providerCode = error.code;\n if (typeof body.request_id === \"string\") requestId = body.request_id;\n } catch {\n // Preserve the HTTP response text when the body is not structured JSON.\n }\n const retryAfterMs = parseRetryAfterMs(response.headers.get(\"retry-after\"));\n return new OpenAIResponsesError(\n message,\n omitUndefined({\n status: response.status,\n providerType,\n providerCode,\n requestId,\n retryAfterMs,\n }),\n );\n}\n\nfunction requireRecord(value: unknown, field: string): Record<string, unknown> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new OpenAIResponsesProtocolError(`${field} must be an object`);\n }\n return value as Record<string, unknown>;\n}\n\nfunction validateOptionalPositiveInteger(value: number | undefined, name: string): void {\n if (value !== undefined && (!Number.isSafeInteger(value) || value < 1)) {\n throw new RangeError(`${name} must be a positive safe integer`);\n }\n}\n", "import type { ContentPart, MediaSource, Message, ModelState, ToolDefinition } from \"@sortedyuan/may/core\";\nimport { UnsupportedContentError, omitUndefined } from \"@sortedyuan/may/core\";\n\nimport { OpenAIResponsesProtocolError } from \"./errors.js\";\nimport { OPENAI_RESPONSES_MODEL_STATE_TYPE, type OpenAIResponsesModelStateData } from \"./protocol.js\";\n\nexport interface OpenAIResponsesRequestParts {\n readonly input: unknown[];\n readonly instructions?: string;\n}\n\nexport function toOpenAIResponsesRequestParts(\n messages: readonly Message[],\n baseInstructions?: string,\n): OpenAIResponsesRequestParts {\n const instructions: string[] = [];\n if (baseInstructions?.trim()) instructions.push(baseInstructions);\n const input: unknown[] = [];\n\n for (const message of messages) {\n if (message.role === \"system\") {\n const text = visibleText(message.content);\n if (text !== \"\") instructions.push(text);\n continue;\n }\n if (message.role === \"user\") {\n input.push({\n role: \"user\",\n content: toInputContent(message.content, \"user\"),\n });\n continue;\n }\n if (message.role === \"tool\") {\n input.push({\n type: \"function_call_output\",\n call_id: message.toolCallId,\n output: hasMedia(message.content)\n ? toInputContent(message.content, \"tool\")\n : visibleText(message.content, \"tool\"),\n });\n continue;\n }\n\n const native = nativeItems(message.modelState);\n if (native !== undefined) {\n input.push(...native);\n continue;\n }\n\n const text = visibleText(message.content, \"assistant\");\n if (text !== \"\") {\n input.push({\n type: \"message\",\n role: \"assistant\",\n status: \"completed\",\n content: [{ type: \"output_text\", text, annotations: [] }],\n });\n }\n for (const call of message.toolCalls ?? []) {\n input.push({\n type: \"function_call\",\n call_id: call.id,\n name: call.name,\n arguments: serializeJson(call.input),\n status: \"completed\",\n });\n }\n }\n\n return {\n input,\n ...(instructions.length === 0 ? {} : { instructions: instructions.join(\"\\n\\n\") }),\n };\n}\n\nexport function toOpenAIResponsesTools(tools: readonly ToolDefinition[]): unknown[] {\n return tools.map((tool) => ({\n type: \"function\",\n name: tool.name,\n description: tool.description,\n parameters: tool.inputSchema,\n strict: false,\n }));\n}\n\nfunction nativeItems(state: ModelState | undefined): unknown[] | undefined {\n if (state?.type !== OPENAI_RESPONSES_MODEL_STATE_TYPE) return undefined;\n if (!isRecord(state.data) || !Array.isArray(state.data.items)) {\n throw new OpenAIResponsesProtocolError(\"OpenAI Responses model state is malformed\");\n }\n return [...(state.data as unknown as OpenAIResponsesModelStateData).items];\n}\n\nfunction toInputContent(content: readonly ContentPart[], role: \"user\" | \"tool\"): unknown[] {\n return content.flatMap<unknown>((part) => {\n if (part.type === \"reasoning\") return [];\n if (part.type === \"text\") {\n return [{ type: \"input_text\", text: part.text }];\n }\n if (part.type === \"json\") {\n return [{ type: \"input_text\", text: serializeJson(part.value) }];\n }\n if (part.type === \"image\") {\n const source = toOpenAIImageSource(part.source);\n return [\n omitUndefined({\n type: \"input_image\",\n ...source,\n detail: part.detail,\n }),\n ];\n }\n if (part.type === \"file\") {\n return [{ type: \"input_file\", ...toOpenAIFileSource(part.source, part.name) }];\n }\n throw new UnsupportedContentError(\"OpenAI Responses adapter\", part.type, role);\n });\n}\n\nfunction visibleText(content: readonly ContentPart[], role: Message[\"role\"] = \"system\"): string {\n return content\n .filter((part) => part.type !== \"reasoning\")\n .map((part) => {\n if (part.type === \"text\") return part.text;\n if (part.type === \"json\") return serializeJson(part.value);\n throw new UnsupportedContentError(\"OpenAI Responses adapter\", part.type, role);\n })\n .join(\"\\n\");\n}\n\nfunction hasMedia(content: readonly ContentPart[]): boolean {\n return content.some((part) => part.type === \"image\" || part.type === \"file\");\n}\n\nfunction toOpenAIImageSource(source: MediaSource): { image_url: string } | { file_id: string } {\n if (source.type === \"url\") return { image_url: source.url };\n if (source.type === \"file\") return { file_id: source.fileId };\n return {\n image_url: `data:${source.mediaType};base64,${source.data}`,\n };\n}\n\nfunction toOpenAIFileSource(\n source: MediaSource,\n name: string | undefined,\n):\n | { file_url: string }\n | { file_id: string }\n | {\n filename: string;\n file_data: string;\n } {\n if (source.type === \"url\") return { file_url: source.url };\n if (source.type === \"file\") return { file_id: source.fileId };\n return {\n filename: name ?? \"file\",\n file_data: `data:${source.mediaType};base64,${source.data}`,\n };\n}\n\nfunction serializeJson(value: unknown): string {\n const serialized = JSON.stringify(value);\n return serialized === undefined ? \"null\" : serialized;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n", "/** @experimental */\nexport const OPENAI_RESPONSES_MODEL_STATE_TYPE = \"openai.responses.output.v1\";\n\n/**\n * Provider/model metadata determines concrete supported values.\n * @experimental\n */\nexport type OpenAIReasoningEffort = string;\n\n/** @experimental */\nexport type OpenAIReasoningSummary = \"auto\" | \"concise\" | \"detailed\";\n\n/** @experimental */\nexport interface OpenAIResponsesModelStateData {\n readonly items: readonly unknown[];\n}\n\n/** @experimental */\nexport interface OpenAIResponsesUsage {\n readonly input_tokens?: number;\n readonly output_tokens?: number;\n readonly total_tokens?: number;\n readonly input_tokens_details?: { readonly cached_tokens?: number };\n readonly output_tokens_details?: { readonly reasoning_tokens?: number };\n}\n", "import type { AssistantMessage, ContentPart, ModelEvent, ToolCall, Usage } from \"@sortedyuan/may/core\";\nimport { omitUndefined } from \"@sortedyuan/may/core\";\nimport { readSseData } from \"../openai-compatible/http.js\";\n\nimport { OpenAIResponsesError, OpenAIResponsesProtocolError } from \"./errors.js\";\nimport { OPENAI_RESPONSES_MODEL_STATE_TYPE, type OpenAIResponsesUsage } from \"./protocol.js\";\n\nexport async function* streamOpenAIResponse(response: Response, signal: AbortSignal): AsyncIterable<ModelEvent> {\n let completed: unknown;\n for await (const data of readSseData(\n response,\n signal,\n (message, options) => new OpenAIResponsesProtocolError(message, options),\n \"OpenAI Responses\",\n )) {\n if (data === \"[DONE]\") continue;\n const event = parseJson(data, \"stream event\");\n const type = requireString(event.type, \"stream event.type\");\n if (type === \"response.output_text.delta\") {\n const delta = requireString(event.delta, `${type}.delta`);\n if (delta !== \"\") yield { type: \"text.delta\", delta };\n continue;\n }\n if (type === \"response.refusal.delta\") {\n const delta = requireString(event.delta, `${type}.delta`);\n if (delta !== \"\") yield { type: \"text.delta\", delta };\n continue;\n }\n if (type === \"response.reasoning_summary_text.delta\") {\n const delta = requireString(event.delta, `${type}.delta`);\n if (delta !== \"\") yield { type: \"reasoning.delta\", delta };\n continue;\n }\n if (type === \"response.completed\") {\n if (completed !== undefined) {\n throw new OpenAIResponsesProtocolError(\"OpenAI Responses emitted more than one response.completed event\");\n }\n completed = event.response;\n continue;\n }\n if (type === \"response.failed\" || type === \"response.incomplete\") {\n throw responseFailure(event.response, type);\n }\n if (type === \"error\") throw streamError(event);\n }\n if (completed === undefined) {\n throw new OpenAIResponsesProtocolError(\"OpenAI Responses stream ended without response.completed\");\n }\n const parsed = parseCompletedOpenAIResponse(completed);\n yield omitUndefined({ type: \"response.completed\", message: parsed.message, usage: parsed.usage });\n}\n\nexport function parseCompletedOpenAIResponse(value: unknown): {\n message: AssistantMessage;\n usage?: Usage;\n} {\n const response = requireRecord(value, \"response.completed.response\");\n const output = requireArray(response.output, \"response.output\");\n const content: ContentPart[] = [];\n const toolCalls: ToolCall[] = [];\n\n for (const raw of output) {\n const item = requireRecord(raw, \"response.output item\");\n const type = requireString(item.type, \"response.output item.type\");\n if (type === \"image_generation_call\" && item.result != null) {\n const format = item.output_format ?? \"png\";\n if (format !== \"png\" && format !== \"jpeg\" && format !== \"webp\")\n throw new OpenAIResponsesProtocolError(\"Unsupported generated image format\");\n const data = requireString(item.result, \"image_generation_call.result\");\n if (data === \"\") throw new OpenAIResponsesProtocolError(\"Generated image is empty\");\n content.push({ type: \"image\", source: { type: \"base64\", mediaType: `image/${format}`, data } });\n continue;\n }\n if (type === \"reasoning\") {\n for (const rawSummary of optionalArray(item.summary) ?? []) {\n const summary = requireRecord(rawSummary, \"reasoning summary\");\n if (summary.type === \"summary_text\") {\n const text = requireString(summary.text, \"reasoning summary.text\");\n if (text !== \"\") content.push({ type: \"reasoning\", text });\n }\n }\n continue;\n }\n if (type === \"message\") {\n if (item.role !== \"assistant\") continue;\n for (const rawPart of requireArray(item.content, \"message.content\")) {\n const part = requireRecord(rawPart, \"message content part\");\n if (part.type === \"output_text\") {\n const text = requireString(part.text, \"output_text.text\");\n if (text !== \"\") content.push({ type: \"text\", text });\n }\n if (part.type === \"refusal\") {\n const refusal = requireString(part.refusal, \"refusal.refusal\");\n if (refusal !== \"\") content.push({ type: \"text\", text: refusal });\n }\n }\n continue;\n }\n if (type === \"function_call\") {\n const id = requireString(item.call_id, \"function_call.call_id\");\n const name = requireString(item.name, \"function_call.name\");\n const argumentsJson = requireString(item.arguments, \"function_call.arguments\");\n toolCalls.push({ id, name, input: parseArguments(argumentsJson, id) });\n }\n }\n\n const message: AssistantMessage = {\n role: \"assistant\",\n content,\n ...(toolCalls.length === 0 ? {} : { toolCalls }),\n modelState: {\n type: OPENAI_RESPONSES_MODEL_STATE_TYPE,\n data: { items: output },\n },\n };\n const usage = parseUsage(response.usage);\n return omitUndefined({ message, usage });\n}\n\n/** @experimental */\nexport function openAIResponseContent(message: AssistantMessage): readonly ContentPart[] {\n if (\n message.content.some((part) => part.type === \"image\") ||\n message.modelState?.type !== OPENAI_RESPONSES_MODEL_STATE_TYPE\n )\n return message.content;\n const state = requireRecord(message.modelState.data, \"modelState.data\");\n const items = requireArray(state.items, \"modelState.data.items\");\n if (\n !items.some(\n (item) => typeof item === \"object\" && item !== null && \"type\" in item && item.type === \"image_generation_call\",\n )\n )\n return message.content;\n return parseCompletedOpenAIResponse({ output: items }).message.content;\n}\n\nexport function parseUsage(value: unknown): Usage | undefined {\n if (value === undefined || value === null) return undefined;\n const usage = requireRecord(value, \"response.usage\") as OpenAIResponsesUsage;\n const inputTokens = optionalTokenCount(usage.input_tokens, \"input_tokens\");\n const outputTokens = optionalTokenCount(usage.output_tokens, \"output_tokens\");\n const totalTokens = optionalTokenCount(usage.total_tokens, \"total_tokens\");\n const inputDetails = optionalRecord(usage.input_tokens_details);\n const outputDetails = optionalRecord(usage.output_tokens_details);\n const cachedReadTokens = optionalTokenCount(inputDetails?.cached_tokens, \"input_tokens_details.cached_tokens\");\n const reasoningTokens = optionalTokenCount(outputDetails?.reasoning_tokens, \"output_tokens_details.reasoning_tokens\");\n if (\n inputTokens === undefined &&\n outputTokens === undefined &&\n totalTokens === undefined &&\n cachedReadTokens === undefined &&\n reasoningTokens === undefined\n ) {\n return undefined;\n }\n return omitUndefined({\n inputTokens,\n outputTokens,\n totalTokens,\n cachedReadTokens,\n reasoningTokens,\n ...(cachedReadTokens === undefined && reasoningTokens === undefined\n ? {}\n : {\n tokenRelations: {\n ...(cachedReadTokens === undefined ? {} : { cachedRead: \"input\" as const }),\n ...(reasoningTokens === undefined ? {} : { reasoning: \"output\" as const }),\n },\n }),\n ...(inputTokens === undefined || outputTokens === undefined\n ? { completeness: { status: \"partial\" as const, reason: \"provider-token-components-missing\" } }\n : {}),\n });\n}\n\nfunction parseArguments(value: string, callId: string): unknown {\n try {\n return JSON.parse(value === \"\" ? \"{}\" : value);\n } catch (error) {\n throw new OpenAIResponsesProtocolError(`OpenAI Responses function call \"${callId}\" has invalid arguments JSON`, {\n cause: error,\n });\n }\n}\n\nfunction responseFailure(value: unknown, type: string): Error {\n const response = requireRecord(value, type);\n const error = optionalRecord(response.error);\n const details = optionalRecord(response.incomplete_details);\n const message =\n typeof error?.message === \"string\"\n ? error.message\n : typeof details?.reason === \"string\"\n ? details.reason\n : `OpenAI Responses emitted ${type}`;\n return new OpenAIResponsesError(message, {\n ...(typeof error?.code === \"string\" ? { providerType: error.code } : {}),\n });\n}\n\nfunction streamError(event: Record<string, unknown>): Error {\n const error = optionalRecord(event.error) ?? event;\n return new OpenAIResponsesError(typeof error.message === \"string\" ? error.message : \"OpenAI Responses stream error\", {\n ...(typeof error.code === \"string\"\n ? { providerType: error.code }\n : typeof error.type === \"string\"\n ? { providerType: error.type }\n : {}),\n ...(typeof event.request_id === \"string\" ? { requestId: event.request_id } : {}),\n });\n}\n\nfunction parseJson(value: string, field: string): Record<string, unknown> {\n try {\n return requireRecord(JSON.parse(value), field);\n } catch (error) {\n if (error instanceof OpenAIResponsesProtocolError) throw error;\n throw new OpenAIResponsesProtocolError(`OpenAI Responses emitted invalid JSON for ${field}`, { cause: error });\n }\n}\n\nfunction optionalTokenCount(value: unknown, field: string): number | undefined {\n if (value === undefined) return undefined;\n if (!Number.isSafeInteger(value) || (value as number) < 0) {\n throw new OpenAIResponsesProtocolError(`response.usage.${field} is invalid`);\n }\n return value as number;\n}\n\nfunction requireRecord(value: unknown, field: string): Record<string, unknown> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new OpenAIResponsesProtocolError(`${field} must be an object`);\n }\n return value as Record<string, unknown>;\n}\n\nfunction optionalRecord(value: unknown): Record<string, unknown> | undefined {\n return value === undefined || value === null ? undefined : requireRecord(value, \"value\");\n}\n\nfunction requireArray(value: unknown, field: string): unknown[] {\n if (!Array.isArray(value)) {\n throw new OpenAIResponsesProtocolError(`${field} must be an array`);\n }\n return value;\n}\n\nfunction optionalArray(value: unknown): unknown[] | undefined {\n return value === undefined ? undefined : requireArray(value, \"value\");\n}\n\nfunction requireString(value: unknown, field: string): string {\n if (typeof value !== \"string\") {\n throw new OpenAIResponsesProtocolError(`${field} must be a string`);\n }\n return value;\n}\n", "import { OpenAICompatibleChatModel } from \"./chat-model.js\";\n\n/**\n * Provider/model metadata determines concrete supported values.\n * @experimental\n */\nexport type OpenAIChatCompletionsReasoningEffort = string;\n\n/** @experimental */\nexport interface OpenAIChatCompletionsModelOptions {\n apiKey: string;\n model: string;\n baseURL?: string;\n maxOutputTokens?: number;\n reasoningEffort?: OpenAIChatCompletionsReasoningEffort;\n store?: boolean;\n fetch?: typeof globalThis.fetch;\n}\n\n/** @experimental */\nexport class OpenAIChatCompletionsModel extends OpenAICompatibleChatModel {\n constructor(options: OpenAIChatCompletionsModelOptions) {\n const { store, ...shared } = options;\n super(shared, {\n provider: \"OpenAI-compatible chat\",\n adapter: \"openai-chat-completions\",\n errorCodePrefix: \"OPENAI_CHAT_COMPLETIONS\",\n defaultBaseURL: \"https://api.openai.com/v1\",\n maxTokensField: \"max_completion_tokens\",\n streamUsage: true,\n includeToolName: false,\n requireDone: true,\n supportsResponseFormat: true,\n ...(store === undefined\n ? {}\n : {\n extendRequest: (body) => {\n body.store = store;\n },\n }),\n });\n }\n}\n", "import { omitUndefined } from \"@sortedyuan/may/core\";\nimport { OpenAICompatibleChatModel } from \"../openai-compatible/chat-model.js\";\n\n/**\n * Provider/model metadata determines concrete supported values.\n * @experimental\n */\nexport type ZhipuReasoningEffort = string;\n\n/** @experimental */\nexport interface ZhipuModelOptions {\n apiKey: string;\n model: string;\n baseURL?: string;\n thinking?: \"enabled\" | \"disabled\";\n clearThinking?: boolean;\n reasoningEffort?: ZhipuReasoningEffort;\n maxTokens?: number;\n fetch?: typeof globalThis.fetch;\n}\n\n/** @experimental */\nexport class ZhipuModel extends OpenAICompatibleChatModel {\n constructor(options: ZhipuModelOptions) {\n const { thinking = \"enabled\", clearThinking = false, maxTokens, ...shared } = options;\n super(omitUndefined({ ...shared, maxOutputTokens: maxTokens }), {\n provider: \"Zhipu\",\n adapter: \"zhipu-chat\",\n errorCodePrefix: \"ZHIPU\",\n defaultBaseURL: \"https://open.bigmodel.cn/api/paas/v4\",\n maxTokensField: \"max_tokens\",\n streamUsage: false,\n includeToolName: false,\n requireDone: false,\n supportsResponseFormat: false,\n extendRequest: (body, request) => {\n body.thinking = thinking === \"enabled\" ? { type: thinking, clear_thinking: clearThinking } : { type: thinking };\n if (request.tools.length > 0) body.tool_stream = true;\n },\n });\n }\n}\n", "import { AnthropicModel, type AnthropicModelOptions, type AnthropicThinkingConfig } from \"./anthropic/index.js\";\nimport { DeepSeekModel, type DeepSeekModelOptions } from \"./deepseek/index.js\";\nimport { KimiModel, type KimiModelOptions, type KimiThinkingConfig } from \"./kimi/index.js\";\nimport { OpenAIResponsesModel, type OpenAIReasoningSummary, type OpenAIResponsesModelOptions } from \"./openai/index.js\";\nimport { OpenAIChatCompletionsModel, type OpenAIChatCompletionsModelOptions } from \"./openai-compatible/index.js\";\nimport { ZhipuModel, type ZhipuModelOptions } from \"./zhipu/index.js\";\nimport { omitUndefined, type Model } from \"@sortedyuan/may/core\";\nimport { GeminiModel, type GeminiModelOptions } from \"./gemini/index.js\";\n\nimport { ProviderConfigurationError } from \"./errors.js\";\nimport {\n attachModelLimits,\n modelOption,\n optionField,\n optionalBoolean,\n optionalEnum,\n optionalPositiveInteger,\n optionalString,\n providerField,\n requiredString,\n requireRecord,\n tuningOption,\n} from \"./options.js\";\nimport { ProviderAdapterRegistry } from \"./registry.js\";\nimport type { CapabilityValidatedModelOptions } from \"./capability-validated-model.js\";\nimport { createModelCapabilityResolver } from \"./capabilities.js\";\nimport type { ProviderAdapterFactory, ProviderModelSelection } from \"./types.js\";\n\nconst OPENAI_REASONING_SUMMARIES = new Set<OpenAIReasoningSummary>([\"auto\", \"concise\", \"detailed\"]);\nconst THINKING_TYPES = new Set([\"enabled\", \"disabled\"] as const);\nconst ANTHROPIC_THINKING_TYPES = new Set([\"enabled\", \"adaptive\", \"disabled\"] as const);\nconst THINKING_DISPLAYS = new Set([\"summarized\", \"omitted\"] as const);\nconst ANTHROPIC_CACHE_TTLS = new Set([\"5m\", \"1h\"] as const);\n\n/** @experimental */\nexport interface BuiltinProviderAdapterRegistryOptions extends CapabilityValidatedModelOptions {\n readonly fetch?: typeof globalThis.fetch;\n}\n\n/** @experimental */\nexport function createBuiltinProviderAdapterRegistry(\n options: BuiltinProviderAdapterRegistryOptions = {},\n): ProviderAdapterRegistry {\n const registry = new ProviderAdapterRegistry({\n ...options,\n validateRequests: true,\n resolver: options.resolver ?? createModelCapabilityResolver(omitUndefined({ fetch: options.fetch })),\n });\n const zhipu = factory((selection) => createZhipuModel(selection, options));\n registry\n .register(\n \"google-gemini\",\n factory((selection) => createGeminiModel(selection, options)),\n )\n .register(\n \"deepseek-chat\",\n factory((selection) => createDeepSeekModel(selection, options)),\n )\n .register(\"zhipu-chat\", zhipu)\n .register(\n \"kimi-chat\",\n factory((selection) => createKimiModel(selection, options)),\n )\n .register(\n \"anthropic-messages\",\n factory((selection) => createAnthropicModel(selection, options)),\n )\n .register(\n \"openai-responses\",\n factory((selection) => createOpenAIModel(selection, options)),\n )\n .register(\n \"openai-chat-completions\",\n factory((selection) => createOpenAIChatCompletionsModel(selection, options)),\n );\n return registry;\n}\n\n/** @experimental */\nexport function createBuiltinProviderModel(\n selection: ProviderModelSelection,\n options: BuiltinProviderAdapterRegistryOptions = {},\n): Model {\n return createBuiltinProviderAdapterRegistry(options).create(selection);\n}\n\nfunction createGeminiModel(\n selection: ProviderModelSelection,\n dependencies: BuiltinProviderAdapterRegistryOptions,\n): Model {\n const maxOutputTokens =\n optionalPositiveInteger(modelOption(selection, \"maxOutputTokens\"), optionField(selection, \"maxOutputTokens\")) ??\n selection.limits?.maxOutputTokens;\n const reasoningEffort = optionalString(\n tuningOption(selection, \"reasoningEffort\"),\n optionField(selection, \"reasoningEffort\"),\n );\n const includeThoughts = optionalBoolean(\n tuningOption(selection, \"includeThoughts\"),\n optionField(selection, \"includeThoughts\"),\n );\n const thinkingBudget = tuningOption(selection, \"thinkingBudget\");\n if (\n thinkingBudget !== undefined &&\n (typeof thinkingBudget !== \"number\" || !Number.isSafeInteger(thinkingBudget) || thinkingBudget < -1)\n )\n throw new ProviderConfigurationError(\n `${optionField(selection, \"thinkingBudget\")} must be an integer greater than or equal to -1`,\n );\n const baseURL = providerBaseURL(selection);\n const options: GeminiModelOptions = omitUndefined({\n ...credentials(selection),\n baseURL,\n maxOutputTokens,\n reasoningEffort,\n includeThoughts,\n thinkingBudget,\n fetch: dependencies.fetch,\n });\n return attachModelLimits(new GeminiModel(options), selection.limits, maxOutputTokens);\n}\n\nfunction createDeepSeekModel(\n selection: ProviderModelSelection,\n dependencies: BuiltinProviderAdapterRegistryOptions,\n): Model {\n const thinking = optionalEnum(\n tuningOption(selection, \"thinking\"),\n optionField(selection, \"thinking\"),\n THINKING_TYPES,\n );\n const reasoningEffort = optionalString(\n tuningOption(selection, \"reasoningEffort\"),\n optionField(selection, \"reasoningEffort\"),\n );\n const maxTokens =\n optionalPositiveInteger(tuningOption(selection, \"maxTokens\"), optionField(selection, \"maxTokens\")) ??\n selection.limits?.maxOutputTokens;\n const baseURL = providerBaseURL(selection);\n const options: DeepSeekModelOptions = omitUndefined({\n ...credentials(selection),\n baseURL,\n thinking,\n reasoningEffort,\n maxTokens,\n fetch: dependencies.fetch,\n });\n return attachModelLimits(new DeepSeekModel(options), selection.limits, maxTokens);\n}\n\nfunction createZhipuModel(\n selection: ProviderModelSelection,\n dependencies: BuiltinProviderAdapterRegistryOptions,\n): Model {\n const thinking = optionalEnum(\n tuningOption(selection, \"thinking\"),\n optionField(selection, \"thinking\"),\n THINKING_TYPES,\n );\n const clearThinking = optionalBoolean(\n tuningOption(selection, \"clearThinking\"),\n optionField(selection, \"clearThinking\"),\n );\n const reasoningEffort = optionalString(\n tuningOption(selection, \"reasoningEffort\"),\n optionField(selection, \"reasoningEffort\"),\n );\n const maxTokens =\n optionalPositiveInteger(tuningOption(selection, \"maxTokens\"), optionField(selection, \"maxTokens\")) ??\n selection.limits?.maxOutputTokens;\n const baseURL = providerBaseURL(selection);\n const options: ZhipuModelOptions = omitUndefined({\n ...credentials(selection),\n baseURL,\n thinking,\n clearThinking,\n reasoningEffort,\n maxTokens,\n fetch: dependencies.fetch,\n });\n return attachModelLimits(new ZhipuModel(options), selection.limits, maxTokens);\n}\n\nfunction createKimiModel(\n selection: ProviderModelSelection,\n dependencies: BuiltinProviderAdapterRegistryOptions,\n): Model {\n const thinking = optionalKimiThinking(tuningOption(selection, \"thinking\"), optionField(selection, \"thinking\"));\n const reasoningEffort = optionalString(\n tuningOption(selection, \"reasoningEffort\"),\n optionField(selection, \"reasoningEffort\"),\n );\n const maxTokens =\n optionalPositiveInteger(tuningOption(selection, \"maxTokens\"), optionField(selection, \"maxTokens\")) ??\n selection.limits?.maxOutputTokens;\n const baseURL = providerBaseURL(selection);\n const options: KimiModelOptions = omitUndefined({\n ...credentials(selection),\n baseURL,\n thinking,\n reasoningEffort,\n maxTokens,\n fetch: dependencies.fetch,\n });\n return attachModelLimits(new KimiModel(options), selection.limits, maxTokens);\n}\n\nfunction createAnthropicModel(\n selection: ProviderModelSelection,\n dependencies: BuiltinProviderAdapterRegistryOptions,\n): Model {\n const thinking = optionalAnthropicThinking(tuningOption(selection, \"thinking\"), optionField(selection, \"thinking\"));\n const reasoningEffort = optionalString(\n tuningOption(selection, \"reasoningEffort\"),\n optionField(selection, \"reasoningEffort\"),\n );\n const maxTokens =\n optionalPositiveInteger(tuningOption(selection, \"maxTokens\"), optionField(selection, \"maxTokens\")) ??\n selection.limits?.maxOutputTokens;\n const baseURL = providerBaseURL(selection);\n const apiVersion = optionalString(tuningOption(selection, \"apiVersion\"), optionField(selection, \"apiVersion\"));\n const caching = Object.hasOwn(selection.options, \"promptCaching\")\n ? tuningOption(selection, \"promptCaching\")\n : selection.providerConfig.options?.promptCaching;\n const cachingRecord =\n caching === undefined || caching === false\n ? undefined\n : requireRecord(caching, optionField(selection, \"promptCaching\"));\n const promptCaching =\n caching === false\n ? false\n : cachingRecord === undefined\n ? undefined\n : omitUndefined({\n ttl: optionalEnum(\n cachingRecord.ttl,\n `${optionField(selection, \"promptCaching\")}.ttl`,\n ANTHROPIC_CACHE_TTLS,\n ),\n cacheInstructions: optionalBoolean(\n cachingRecord.cacheInstructions,\n `${optionField(selection, \"promptCaching\")}.cacheInstructions`,\n ),\n });\n const options: AnthropicModelOptions = omitUndefined({\n ...credentials(selection),\n baseURL,\n apiVersion,\n promptCaching,\n thinking,\n reasoningEffort,\n maxTokens,\n fetch: dependencies.fetch,\n });\n return attachModelLimits(new AnthropicModel(options), selection.limits, maxTokens);\n}\n\nfunction createOpenAIModel(\n selection: ProviderModelSelection,\n dependencies: BuiltinProviderAdapterRegistryOptions,\n): Model {\n const maxOutputTokens =\n optionalPositiveInteger(modelOption(selection, \"maxOutputTokens\"), optionField(selection, \"maxOutputTokens\")) ??\n selection.limits?.maxOutputTokens;\n const reasoningEffort = optionalString(\n tuningOption(selection, \"reasoningEffort\"),\n optionField(selection, \"reasoningEffort\"),\n );\n const reasoningSummary = optionalEnum(\n tuningOption(selection, \"reasoningSummary\"),\n optionField(selection, \"reasoningSummary\"),\n OPENAI_REASONING_SUMMARIES,\n );\n const serverCompactThreshold = optionalPositiveInteger(\n tuningOption(selection, \"serverCompactThreshold\"),\n optionField(selection, \"serverCompactThreshold\"),\n );\n const store = optionalBoolean(tuningOption(selection, \"store\"), optionField(selection, \"store\"));\n const baseURL = providerBaseURL(selection);\n const options: OpenAIResponsesModelOptions = omitUndefined({\n ...credentials(selection),\n baseURL,\n maxOutputTokens,\n reasoningEffort,\n reasoningSummary,\n serverCompactThreshold,\n store,\n fetch: dependencies.fetch,\n });\n return attachModelLimits(new OpenAIResponsesModel(options), selection.limits, maxOutputTokens);\n}\n\nfunction createOpenAIChatCompletionsModel(\n selection: ProviderModelSelection,\n dependencies: BuiltinProviderAdapterRegistryOptions,\n): Model {\n const maxOutputTokens =\n optionalPositiveInteger(modelOption(selection, \"maxOutputTokens\"), optionField(selection, \"maxOutputTokens\")) ??\n selection.limits?.maxOutputTokens;\n const reasoningEffort = optionalString(\n tuningOption(selection, \"reasoningEffort\"),\n optionField(selection, \"reasoningEffort\"),\n );\n const store = optionalBoolean(tuningOption(selection, \"store\"), optionField(selection, \"store\"));\n const baseURL = providerBaseURL(selection);\n const options: OpenAIChatCompletionsModelOptions = omitUndefined({\n ...credentials(selection),\n baseURL,\n maxOutputTokens,\n reasoningEffort,\n store,\n fetch: dependencies.fetch,\n });\n return attachModelLimits(new OpenAIChatCompletionsModel(options), selection.limits, maxOutputTokens);\n}\n\nfunction credentials(selection: ProviderModelSelection): {\n apiKey: string;\n model: string;\n} {\n return {\n apiKey: requiredString(selection.providerConfig.apiKey, providerField(selection, \"apiKey\")),\n model: requiredString(selection.model, \"model\"),\n };\n}\n\nfunction providerBaseURL(selection: ProviderModelSelection): string | undefined {\n return optionalString(selection.providerConfig.baseURL, providerField(selection, \"baseURL\"));\n}\n\nfunction optionalKimiThinking(value: unknown, field: string): KimiThinkingConfig | undefined {\n if (value === undefined) return undefined;\n const record = requireRecord(value, field);\n const type = optionalEnum(record.type, `${field}.type`, THINKING_TYPES);\n if (type === undefined) {\n throw new ProviderConfigurationError(`${field}.type is required`);\n }\n const keep = record.keep;\n if (keep === undefined) return { type };\n if (keep !== \"all\" && keep !== null) {\n throw new ProviderConfigurationError(`${field}.keep must be \"all\" or null`);\n }\n return { type, keep };\n}\n\nfunction optionalAnthropicThinking(value: unknown, field: string): AnthropicThinkingConfig | undefined {\n if (value === undefined) return undefined;\n const record = requireRecord(value, field);\n const type = optionalEnum(record.type, `${field}.type`, ANTHROPIC_THINKING_TYPES);\n if (type === undefined) {\n throw new ProviderConfigurationError(`${field}.type is required`);\n }\n const display = optionalEnum(record.display, `${field}.display`, THINKING_DISPLAYS);\n if (type === \"enabled\") {\n const budgetTokens = optionalPositiveInteger(record.budgetTokens, `${field}.budgetTokens`);\n if (budgetTokens === undefined) {\n throw new ProviderConfigurationError(`${field}.budgetTokens is required when thinking is enabled`);\n }\n return omitUndefined({ type, budgetTokens, display });\n }\n return omitUndefined({ type, display: type === \"disabled\" ? undefined : display });\n}\n\nfunction factory(create: (selection: ProviderModelSelection) => Model): ProviderAdapterFactory {\n return { create };\n}\n", "import { randomUUID } from \"node:crypto\";\nimport { executeRecordedRequest, omitUndefined, requestEndpoint } from \"@sortedyuan/may/core\";\nimport {\n assertModelResponseFormat,\n validateStructuredModelResponse,\n type AssistantMessage,\n type Model,\n type ModelEvent,\n type ModelRequest,\n type ModelStreamOptions,\n type ToolCall,\n} from \"@sortedyuan/may/core\";\nimport { parseRetryAfterMs, readSseData } from \"../openai-compatible/http.js\";\nimport { convertGeminiUsage, isRecord, toGeminiRequestParts } from \"./convert.js\";\nimport { GeminiApiError, GeminiFinishReasonError, GeminiProtocolError } from \"./errors.js\";\nimport {\n GEMINI_MODEL_STATE_TYPE,\n type GeminiGenerateContentRequest,\n type GeminiPart,\n type GeminiUsageMetadata,\n} from \"./protocol.js\";\n\n/** @experimental */\nexport interface GeminiModelOptions {\n apiKey: string;\n model: string;\n baseURL?: string;\n maxOutputTokens?: number;\n reasoningEffort?: string;\n thinkingBudget?: number;\n includeThoughts?: boolean;\n fetch?: typeof globalThis.fetch;\n}\n\n/** @experimental */\nexport class GeminiModel implements Model {\n readonly supportsRequestRecording = true;\n private readonly baseURL: string;\n private readonly fetchImplementation: typeof globalThis.fetch;\n private readonly options: GeminiModelOptions;\n\n constructor(options: GeminiModelOptions) {\n if (typeof options.apiKey !== \"string\" || options.apiKey.trim() === \"\")\n throw new TypeError(\"apiKey must not be empty\");\n if (typeof options.model !== \"string\" || options.model.trim() === \"\")\n throw new TypeError(\"model must not be empty\");\n if (\n options.maxOutputTokens !== undefined &&\n (!Number.isSafeInteger(options.maxOutputTokens) || options.maxOutputTokens < 1)\n )\n throw new RangeError(\"maxOutputTokens must be a positive safe integer\");\n if (\n options.thinkingBudget !== undefined &&\n (!Number.isSafeInteger(options.thinkingBudget) || options.thinkingBudget < -1)\n )\n throw new RangeError(\"thinkingBudget must be an integer greater than or equal to -1\");\n if (\n options.reasoningEffort !== undefined &&\n (typeof options.reasoningEffort !== \"string\" || options.reasoningEffort.trim() === \"\")\n )\n throw new TypeError(\"reasoningEffort must not be empty\");\n if (options.reasoningEffort !== undefined && options.thinkingBudget !== undefined)\n throw new TypeError(\"reasoningEffort and thinkingBudget are mutually exclusive\");\n if (options.includeThoughts !== undefined && typeof options.includeThoughts !== \"boolean\")\n throw new TypeError(\"includeThoughts must be a boolean\");\n this.options = { ...options };\n this.baseURL = (options.baseURL ?? \"https://generativelanguage.googleapis.com/v1beta\").replace(/\\/+$/u, \"\");\n const url = new URL(this.baseURL);\n if (![\"https:\", \"http:\"].includes(url.protocol) || url.search || url.hash || url.username || url.password)\n throw new TypeError(\"baseURL must be an HTTP URL without credentials, query, or fragment\");\n this.fetchImplementation = options.fetch ?? globalThis.fetch;\n }\n\n async *stream(request: ModelRequest, options: ModelStreamOptions): AsyncIterable<ModelEvent> {\n assertModelResponseFormat(request);\n const body: GeminiGenerateContentRequest = toGeminiRequestParts(request.messages);\n if (body.contents.length === 0) throw new GeminiProtocolError(\"Gemini requires non-empty contents\");\n if (request.tools.length > 0)\n body.tools = [\n {\n functionDeclarations: request.tools.map((tool) => ({\n name: tool.name,\n description: tool.description,\n parametersJsonSchema: tool.inputSchema,\n })),\n },\n ];\n const config: NonNullable<GeminiGenerateContentRequest[\"generationConfig\"]> = {};\n if (this.options.maxOutputTokens !== undefined) config.maxOutputTokens = this.options.maxOutputTokens;\n if (\n this.options.reasoningEffort !== undefined ||\n this.options.thinkingBudget !== undefined ||\n this.options.includeThoughts !== undefined\n ) {\n config.thinkingConfig = omitUndefined({\n thinkingLevel: this.options.reasoningEffort,\n thinkingBudget: this.options.thinkingBudget,\n includeThoughts: this.options.includeThoughts,\n });\n }\n if (request.responseFormat !== undefined) {\n config.responseMimeType = \"application/json\";\n if (request.responseFormat.type === \"jsonSchema\") config.responseJsonSchema = request.responseFormat.schema;\n }\n if (Object.keys(config).length > 0) body.generationConfig = config;\n const model = this.options.model.replace(/^models\\//u, \"\");\n yield* executeRecordedRequest(\n {\n version: 1,\n adapter: \"gemini\",\n purpose: \"generation\",\n endpoint: requestEndpoint(`${this.baseURL}/models/${encodeURIComponent(model)}:streamGenerateContent`),\n request,\n body,\n protocol: { model, alt: \"sse\" },\n },\n options.recordRequest,\n options.signal,\n (body) => this.execute(body, model, request, options),\n );\n }\n\n private async *execute(\n body: string,\n model: string,\n request: ModelRequest,\n options: ModelStreamOptions,\n ): AsyncIterable<ModelEvent> {\n const response = await this.fetchImplementation(\n `${this.baseURL}/models/${encodeURIComponent(model)}:streamGenerateContent?alt=sse`,\n {\n method: \"POST\",\n headers: {\n \"x-goog-api-key\": this.options.apiKey,\n \"content-type\": \"application/json\",\n accept: \"text/event-stream\",\n },\n body,\n signal: options.signal,\n },\n );\n if (!response.ok)\n throw new GeminiApiError(\n response.status,\n await response.text(),\n parseRetryAfterMs(response.headers.get(\"retry-after\")),\n );\n\n const message: AssistantMessage = { role: \"assistant\", content: [] };\n const parts: GeminiPart[] = [];\n const toolCalls: ToolCall[] = [];\n let metadata: GeminiUsageMetadata | undefined;\n let finishReason: string | undefined;\n for await (const data of readSseData(\n response,\n options.signal,\n (message, cause) => new GeminiProtocolError(message, cause),\n \"Google Gemini\",\n )) {\n if (data === \"[DONE]\") break;\n const chunk: unknown = JSON.parse(data);\n if (!isRecord(chunk)) throw new GeminiProtocolError(\"Gemini stream chunk must be an object\");\n if (chunk.error !== undefined)\n throw new GeminiProtocolError(`Gemini stream error: ${describeError(chunk.error)}`);\n if (isRecord(chunk.promptFeedback) && chunk.promptFeedback.blockReason !== undefined)\n throw new GeminiFinishReasonError(String(chunk.promptFeedback.blockReason));\n if (chunk.usageMetadata !== undefined) {\n if (!isRecord(chunk.usageMetadata)) throw new GeminiProtocolError(\"Gemini usageMetadata must be an object\");\n metadata = { ...metadata, ...chunk.usageMetadata };\n convertGeminiUsage(metadata);\n }\n if (chunk.candidates === undefined) continue;\n if (!Array.isArray(chunk.candidates)) throw new GeminiProtocolError(\"Gemini candidates must be an array\");\n for (const candidate of chunk.candidates) {\n if (!isRecord(candidate)) throw new GeminiProtocolError(\"Gemini candidate must be an object\");\n if (candidate.index !== undefined && candidate.index !== 0) continue;\n if (candidate.finishReason !== undefined) {\n if (typeof candidate.finishReason !== \"string\")\n throw new GeminiProtocolError(\"Gemini finishReason must be a string\");\n if (finishReason !== undefined && finishReason !== candidate.finishReason)\n throw new GeminiProtocolError(\"Gemini emitted conflicting finish reasons\");\n finishReason = candidate.finishReason;\n }\n if (candidate.content === undefined) continue;\n if (!isRecord(candidate.content) || !Array.isArray(candidate.content.parts))\n throw new GeminiProtocolError(\"Gemini content.parts must be an array\");\n for (const rawPart of candidate.content.parts) {\n if (!isRecord(rawPart)) throw new GeminiProtocolError(\"Gemini part must be an object\");\n if (rawPart.thoughtSignature !== undefined && typeof rawPart.thoughtSignature !== \"string\")\n throw new GeminiProtocolError(\"Gemini thoughtSignature must be a string\");\n if (rawPart.thought !== undefined && typeof rawPart.thought !== \"boolean\")\n throw new GeminiProtocolError(\"Gemini thought must be a boolean\");\n const part = rawPart as GeminiPart;\n parts.push(structuredClone(part));\n if (part.text !== undefined) {\n if (typeof part.text !== \"string\") throw new GeminiProtocolError(\"Gemini text must be a string\");\n const type = part.thought ? \"reasoning\" : \"text\";\n message.content.push({ type, text: part.text });\n if (part.text !== \"\") yield { type: part.thought ? \"reasoning.delta\" : \"text.delta\", delta: part.text };\n } else if (part.functionCall !== undefined) {\n const call = part.functionCall;\n if (\n !isRecord(call) ||\n typeof call.name !== \"string\" ||\n call.name.trim() === \"\" ||\n (call.args !== undefined && !isRecord(call.args)) ||\n (call.id !== undefined && (typeof call.id !== \"string\" || call.id === \"\"))\n )\n throw new GeminiProtocolError(\"Malformed Gemini functionCall\");\n const id = call.id ?? randomUUID();\n if (toolCalls.some((existing) => existing.id === id))\n throw new GeminiProtocolError(\"Gemini emitted duplicate function call IDs\");\n toolCalls.push({ id, name: call.name, input: call.args ?? {} });\n } else if (part.inlineData !== undefined) {\n const media = part.inlineData;\n if (!isRecord(media) || typeof media.mimeType !== \"string\" || typeof media.data !== \"string\")\n throw new GeminiProtocolError(\"Malformed Gemini inlineData\");\n const type = media.mimeType.startsWith(\"image/\")\n ? \"image\"\n : media.mimeType.startsWith(\"audio/\")\n ? \"audio\"\n : \"file\";\n message.content.push({ type, source: { type: \"base64\", mediaType: media.mimeType, data: media.data } });\n } else if (part.thoughtSignature === undefined) {\n throw new GeminiProtocolError(\"Unsupported Gemini response part\");\n }\n }\n }\n }\n options.signal.throwIfAborted();\n if (finishReason === undefined) throw new GeminiProtocolError(\"Gemini stream ended without finishReason\");\n if (finishReason !== \"STOP\") throw new GeminiFinishReasonError(finishReason);\n if (parts.length === 0) throw new GeminiProtocolError(\"Gemini completed without content\");\n if (toolCalls.length > 0) message.toolCalls = toolCalls;\n message.modelState = {\n type: GEMINI_MODEL_STATE_TYPE,\n data: { parts, toolCallIds: toolCalls.map((call) => call.id) },\n };\n const event: Extract<ModelEvent, { type: \"response.completed\" }> = {\n type: \"response.completed\",\n message,\n ...(metadata === undefined ? {} : { usage: convertGeminiUsage(metadata) }),\n };\n validateStructuredModelResponse(message, request, event);\n yield event;\n }\n}\n\nfunction describeError(error: unknown): string {\n if (isRecord(error) && typeof error.message === \"string\") return error.message;\n if (typeof error === \"string\") return error;\n return \"The server returned an error without a message\";\n}\n", "import type { ContentPart, Message, Usage } from \"@sortedyuan/may/core\";\nimport { UnsupportedContentError, omitUndefined } from \"@sortedyuan/may/core\";\nimport { GeminiProtocolError } from \"./errors.js\";\nimport {\n GEMINI_MODEL_STATE_TYPE,\n type GeminiContent,\n type GeminiGenerateContentRequest,\n type GeminiModelStateData,\n type GeminiPart,\n type GeminiUsageMetadata,\n} from \"./protocol.js\";\n\n/** @experimental */\nexport function toGeminiRequestParts(\n messages: readonly Message[],\n): Pick<GeminiGenerateContentRequest, \"contents\" | \"systemInstruction\"> {\n const contents: GeminiContent[] = [];\n const system: GeminiPart[] = [];\n const nativeCalls = new Map<string, NonNullable<GeminiPart[\"functionCall\"]>>();\n for (const message of messages) {\n if (message.role === \"system\") {\n system.push(\n ...message.content.map((part) => {\n if (part.type === \"text\") return { text: part.text };\n if (part.type === \"json\") return { text: JSON.stringify(part.value) };\n throw new UnsupportedContentError(\"Google Gemini\", part.type, \"system\");\n }),\n );\n continue;\n }\n if (message.role === \"tool\") {\n const call = nativeCalls.get(message.toolCallId);\n if (call === undefined || call.name !== message.name)\n throw new GeminiProtocolError(`Unmatched Gemini tool result \"${message.toolCallId}\"`);\n const response: Record<string, unknown> = {\n [message.isError ? \"error\" : \"output\"]: message.content.map((part) => {\n if (part.type === \"text\") return part.text;\n if (part.type === \"json\") return part.value;\n throw new UnsupportedContentError(\"Google Gemini\", part.type, \"tool\");\n }),\n };\n appendContent(contents, \"user\", [\n { functionResponse: omitUndefined({ name: call.name, id: call.id, response }) },\n ]);\n continue;\n }\n if (message.role === \"assistant\") {\n let parts: GeminiPart[];\n if (message.modelState?.type === GEMINI_MODEL_STATE_TYPE) {\n const state = message.modelState.data as GeminiModelStateData;\n if (!isRecord(state) || !Array.isArray(state.parts) || !Array.isArray(state.toolCallIds))\n throw new GeminiProtocolError(\"Malformed Gemini model state\");\n parts = structuredClone(state.parts);\n let index = 0;\n for (const part of parts) {\n if (!isRecord(part)) throw new GeminiProtocolError(\"Malformed Gemini model state part\");\n if (part.functionCall === undefined) continue;\n if (\n !isRecord(part.functionCall) ||\n typeof part.functionCall.name !== \"string\" ||\n (part.functionCall.args !== undefined && !isRecord(part.functionCall.args))\n )\n throw new GeminiProtocolError(\"Malformed Gemini model state functionCall\");\n const functionCall = part.functionCall as NonNullable<GeminiPart[\"functionCall\"]>;\n const callId = state.toolCallIds[index++];\n const toolCall = message.toolCalls?.find((call) => call.id === callId);\n if (\n typeof callId !== \"string\" ||\n toolCall === undefined ||\n toolCall.name !== functionCall.name ||\n JSON.stringify(toolCall.input) !== JSON.stringify(functionCall.args ?? {})\n )\n throw new GeminiProtocolError(\"Gemini model state does not match tool calls\");\n nativeCalls.set(callId, functionCall);\n }\n if (index !== state.toolCallIds.length || index !== (message.toolCalls?.length ?? 0))\n throw new GeminiProtocolError(\"Gemini model state has inconsistent tool calls\");\n } else {\n parts = message.content.flatMap((part) => (part.type === \"reasoning\" ? [] : [toGeminiPart(part, \"assistant\")]));\n for (const call of message.toolCalls ?? []) {\n if (!isRecord(call.input)) throw new GeminiProtocolError(\"Gemini tool input must be an object\");\n const functionCall = { id: call.id, name: call.name, args: call.input };\n parts.push({ functionCall });\n nativeCalls.set(call.id, functionCall);\n }\n }\n appendContent(contents, \"model\", parts);\n continue;\n }\n appendContent(\n contents,\n \"user\",\n message.content.map((part) => toGeminiPart(part, \"user\")),\n );\n }\n return { contents, ...(system.length === 0 ? {} : { systemInstruction: { parts: system } }) };\n}\n\nfunction appendContent(contents: GeminiContent[], role: GeminiContent[\"role\"], parts: GeminiPart[]): void {\n if (parts.length === 0) return;\n const previous = contents.at(-1);\n if (previous?.role === role) previous.parts.push(...parts);\n else contents.push({ role, parts });\n}\n\nfunction toGeminiPart(part: ContentPart, role: Message[\"role\"]): GeminiPart {\n if (part.type === \"text\") return { text: part.text };\n if (part.type === \"json\") return { text: JSON.stringify(part.value) };\n if (part.type === \"image\" || part.type === \"audio\" || part.type === \"file\") {\n if (part.source.type === \"base64\")\n return { inlineData: { mimeType: part.source.mediaType, data: part.source.data } };\n if (part.source.type === \"url\") return { fileData: { fileUri: part.source.url } };\n }\n throw new UnsupportedContentError(\"Google Gemini\", part.type, role);\n}\n\n/** @experimental */\nexport function convertGeminiUsage(metadata: GeminiUsageMetadata): Usage {\n const input = tokenCount(metadata.promptTokenCount, \"promptTokenCount\");\n const candidates = tokenCount(metadata.candidatesTokenCount, \"candidatesTokenCount\");\n const reasoning = tokenCount(metadata.thoughtsTokenCount, \"thoughtsTokenCount\");\n const cached = tokenCount(metadata.cachedContentTokenCount, \"cachedContentTokenCount\");\n const total = tokenCount(metadata.totalTokenCount, \"totalTokenCount\");\n const toolPrompt = tokenCount(metadata.toolUsePromptTokenCount, \"toolUsePromptTokenCount\");\n const usage: Usage = { tokenRelations: { cachedRead: \"input\", reasoning: \"output\" } };\n if (input !== undefined) usage.inputTokens = input;\n if (candidates !== undefined || reasoning !== undefined)\n usage.outputTokens = tokenCount((candidates ?? 0) + (reasoning ?? 0), \"outputTokens\")!;\n if (reasoning !== undefined) usage.reasoningTokens = reasoning;\n if (cached !== undefined) usage.cachedReadTokens = cached;\n if (total !== undefined) usage.totalTokens = total;\n if (toolPrompt !== undefined && toolPrompt > 0)\n usage.items = [\n { id: \"gemini.toolUsePromptTokenCount\", quantity: toolPrompt, unit: \"token\", includedIn: \"unknown\" },\n ];\n if (input !== undefined && cached !== undefined && cached > input)\n throw new GeminiProtocolError(\"Gemini cachedContentTokenCount exceeds promptTokenCount\");\n if (input === undefined || usage.outputTokens === undefined || (toolPrompt ?? 0) > 0)\n usage.completeness = {\n status: \"partial\",\n reason: \"Gemini usage does not completely describe input and output tokens\",\n };\n return usage;\n}\n\nfunction tokenCount(value: number | undefined, field: string): number | undefined {\n if (value !== undefined && (!Number.isSafeInteger(value) || value < 0))\n throw new GeminiProtocolError(`${field} must be a non-negative safe integer`);\n return value;\n}\n\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n", "/** @experimental */\nexport class GeminiProtocolError extends Error {\n readonly code = \"GEMINI_PROTOCOL_ERROR\";\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = \"GeminiProtocolError\";\n }\n}\n\n/** @experimental */\nexport class GeminiApiError extends Error {\n readonly code = \"GEMINI_API_ERROR\";\n constructor(\n readonly status: number,\n message: string,\n readonly retryAfterMs?: number,\n ) {\n super(message);\n this.name = \"GeminiApiError\";\n }\n}\n\n/** @experimental */\nexport class GeminiFinishReasonError extends Error {\n readonly code = \"GEMINI_INCOMPLETE_RESPONSE\";\n constructor(readonly finishReason: string) {\n super(`Gemini stopped with finish reason \"${finishReason}\"`);\n this.name = \"GeminiFinishReasonError\";\n }\n}\n", "import type { JsonSchema } from \"@sortedyuan/may/core\";\n\n/** @experimental */\nexport const GEMINI_MODEL_STATE_TYPE = \"google-gemini.content.v1\";\n\n/** @experimental */\nexport interface GeminiPart {\n text?: string;\n thought?: boolean;\n thoughtSignature?: string;\n functionCall?: { id?: string; name: string; args?: Record<string, unknown> };\n functionResponse?: { id?: string; name: string; response: Record<string, unknown> };\n inlineData?: { mimeType: string; data: string };\n fileData?: { mimeType?: string; fileUri: string };\n}\n\n/** @experimental */\nexport interface GeminiContent {\n role: \"user\" | \"model\";\n parts: GeminiPart[];\n}\n\n/** @experimental */\nexport interface GeminiModelStateData {\n parts: GeminiPart[];\n toolCallIds: string[];\n}\n\n/** @experimental */\nexport interface GeminiUsageMetadata {\n promptTokenCount?: number;\n candidatesTokenCount?: number;\n thoughtsTokenCount?: number;\n cachedContentTokenCount?: number;\n totalTokenCount?: number;\n toolUsePromptTokenCount?: number;\n}\n\n/** @experimental */\nexport interface GeminiGenerateContentRequest {\n contents: GeminiContent[];\n systemInstruction?: { parts: GeminiPart[] };\n tools?: { functionDeclarations: { name: string; description: string; parametersJsonSchema: JsonSchema }[] }[];\n generationConfig?: {\n maxOutputTokens?: number;\n thinkingConfig?: { thinkingLevel?: string; thinkingBudget?: number; includeThoughts?: boolean };\n responseMimeType?: \"application/json\";\n responseJsonSchema?: JsonSchema;\n };\n}\n", "/** @experimental */\nexport class ProviderAdapterRegistryError extends Error {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = \"ProviderAdapterRegistryError\";\n }\n}\n\n/** @experimental */\nexport class ProviderConfigurationError extends ProviderAdapterRegistryError {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = \"ProviderConfigurationError\";\n }\n}\n", "import {\n omitUndefined,\n type Model,\n type ModelLimits,\n type ModelRequest,\n type ModelStreamOptions,\n} from \"@sortedyuan/may/core\";\n\nimport { ProviderConfigurationError } from \"./errors.js\";\nimport type { ProviderModelSelection } from \"./types.js\";\n\nexport function providerField(selection: ProviderModelSelection, name: string): string {\n return `providers.${selection.provider}.${name}`;\n}\n\nexport function tuningOption(selection: ProviderModelSelection, name: string): unknown {\n return selection.options[name];\n}\n\nexport function modelOption(selection: ProviderModelSelection, name: string): unknown {\n return Object.hasOwn(selection.options, name) ? selection.options[name] : undefined;\n}\n\nexport function optionField(selection: ProviderModelSelection, name: string): string {\n return `models.${selection.profile}.options.${name}`;\n}\n\nexport function requiredString(value: unknown, field: string): string {\n if (typeof value !== \"string\" || value.trim() === \"\") {\n throw new ProviderConfigurationError(`${field} must be a non-empty string`);\n }\n return value;\n}\n\nexport function optionalString(value: unknown, field: string): string | undefined {\n if (value === undefined) return undefined;\n return requiredString(value, field);\n}\n\nexport function optionalEnum<const Value extends string>(\n value: unknown,\n field: string,\n allowed: ReadonlySet<Value>,\n): Value | undefined {\n if (value === undefined) return undefined;\n if (typeof value !== \"string\" || !allowed.has(value as Value)) {\n throw new ProviderConfigurationError(`${field} must be one of: ${[...allowed].join(\", \")}`);\n }\n return value as Value;\n}\n\nexport function optionalPositiveInteger(value: unknown, field: string): number | undefined {\n if (value === undefined) return undefined;\n if (!Number.isSafeInteger(value) || (value as number) < 1) {\n throw new ProviderConfigurationError(`${field} must be a positive safe integer`);\n }\n return value as number;\n}\n\nexport function optionalBoolean(value: unknown, field: string): boolean | undefined {\n if (value === undefined) return undefined;\n if (typeof value !== \"boolean\") {\n throw new ProviderConfigurationError(`${field} must be a boolean`);\n }\n return value;\n}\n\nexport function requireRecord(value: unknown, field: string): Readonly<Record<string, unknown>> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new ProviderConfigurationError(`${field} must be an object`);\n }\n return value as Readonly<Record<string, unknown>>;\n}\n\nexport function attachModelLimits(model: Model, limits: ModelLimits | undefined, maxOutputTokens?: number): Model {\n const effectiveLimits = mergeLimits(limits, maxOutputTokens);\n if (effectiveLimits === undefined) return model;\n return {\n limits: effectiveLimits,\n supportsRequestRecording: model.supportsRequestRecording === true,\n reportsAttempts: model.reportsAttempts,\n capabilityVersion: model.capabilityVersion,\n configuration: model.configuration,\n contextCompactor: model.contextCompactor,\n ...(model.preflight === undefined\n ? {}\n : {\n preflight: (request: ModelRequest, streamOptions: ModelStreamOptions) =>\n model.preflight!(request, streamOptions),\n }),\n stream: (request, streamOptions) => model.stream(request, streamOptions),\n };\n}\n\nfunction mergeLimits(limits: ModelLimits | undefined, maxOutputTokens: number | undefined): ModelLimits | undefined {\n if (limits === undefined && maxOutputTokens === undefined) return undefined;\n const effectiveOutputTokens = maxOutputTokens ?? limits?.maxOutputTokens;\n return omitUndefined({\n contextWindowTokens: limits?.contextWindowTokens,\n maxOutputTokens: effectiveOutputTokens,\n });\n}\n", "import {\n ModelProtocolError,\n ModelResponseValidationError,\n assertModelResponseFormat,\n omitUndefined,\n type Model,\n type ModelContextCompactor,\n type ModelLimits,\n type ModelEvent,\n type ModelRequest,\n type ModelResponseFormat,\n type ModelStreamOptions,\n} from \"@sortedyuan/may/core\";\nimport { createModelCapabilityResolver, type ModelCapabilities, type ModelCapabilityResolver } from \"./capabilities.js\";\nimport {\n ModelRequestValidationError,\n validateModelRequest,\n validateStructuredModelResponse,\n type ModelRequestValidationOptions,\n type ModelRequestValidationResult,\n} from \"./validation.js\";\nimport type { ProviderModelSelection } from \"./types.js\";\n\n/** @experimental */\nexport interface CapabilityValidatedModelOptions extends ModelRequestValidationOptions {\n readonly resolver?: ModelCapabilityResolver;\n}\n/** @experimental */\nexport class CapabilityValidatedModel implements Model {\n readonly contextCompactor?: ModelContextCompactor;\n private readonly resolver: ModelCapabilityResolver;\n private capabilities: ModelCapabilities | undefined;\n private validation: ModelRequestValidationResult | undefined;\n private readonly selection: ProviderModelSelection;\n private readonly responseFormat: ModelResponseFormat | undefined;\n private readonly unknownPolicy: NonNullable<ModelRequestValidationOptions[\"unknownPolicy\"]>;\n constructor(\n private readonly model: Model,\n selection: ProviderModelSelection,\n private readonly options: CapabilityValidatedModelOptions = {},\n ) {\n this.resolver = options.resolver ?? createModelCapabilityResolver();\n this.selection = structuredClone(selection);\n const responseFormat = selection.options.responseFormat;\n if (responseFormat !== undefined) {\n if (\n typeof responseFormat !== \"object\" ||\n responseFormat === null ||\n !(\"type\" in responseFormat) ||\n (responseFormat.type !== \"json\" && responseFormat.type !== \"jsonSchema\")\n ) {\n throw new TypeError(\"options.responseFormat must be a JSON or JSON Schema response format\");\n }\n this.responseFormat = structuredClone(responseFormat) as ModelResponseFormat;\n assertModelResponseFormat({ messages: [], tools: [], responseFormat: this.responseFormat });\n }\n const unknownPolicy = options.unknownPolicy ?? selection.options.unknownCapabilityPolicy ?? \"allow\";\n if (unknownPolicy !== \"allow\" && unknownPolicy !== \"require-known\")\n throw new TypeError(\"unknownCapabilityPolicy must be allow or require-known\");\n this.unknownPolicy = unknownPolicy;\n const compactor = model.contextCompactor;\n if (compactor !== undefined)\n this.contextCompactor = {\n name: compactor.name,\n compact: async (snapshot, compactOptions) => {\n compactOptions.signal?.throwIfAborted();\n const capabilities = await this.getModelCapabilities();\n compactOptions.signal?.throwIfAborted();\n const capability = capabilities.fields?.contextCompaction;\n if (\n capability?.status === \"unsupported\" ||\n (this.unknownPolicy === \"require-known\" && capability?.status !== \"known\")\n ) {\n this.validation = {\n status: \"invalid\",\n issues: [\n {\n field: \"contextCompactor\",\n capability: \"contextCompaction\",\n code: capability?.status === \"unsupported\" ? \"unsupported\" : \"unknown\",\n message: \"Native Context compaction capability is unavailable\",\n },\n ],\n };\n throw new ModelRequestValidationError(this.validation);\n }\n const request: ModelRequest = {\n messages:\n snapshot.instructions === undefined\n ? snapshot.messages\n : [{ role: \"system\", content: [{ type: \"text\", text: snapshot.instructions }] }, ...snapshot.messages],\n tools: [],\n };\n this.validate(request, capabilities, { ...this.options, unknownPolicy: this.unknownPolicy });\n if (capability?.status !== \"known\")\n this.validation = {\n status: \"unknown\",\n issues: [\n ...this.validation!.issues,\n {\n field: \"contextCompactor\",\n capability: \"contextCompaction\",\n code: \"unknown\",\n message: \"Native Context compaction capability is unknown\",\n },\n ],\n };\n let success = false;\n try {\n const result = await compactor.compact(snapshot, compactOptions);\n success = true;\n return result;\n } finally {\n this.resolver.recordVerification(this.selection, request, success, false, [\"contextCompaction\"]);\n }\n },\n };\n }\n get limits(): ModelLimits | undefined {\n const limits: { contextWindowTokens?: number; maxOutputTokens?: number } = {};\n for (const key of [\"contextWindowTokens\", \"maxOutputTokens\"] as const) {\n const declarations = [\n this.model.limits?.[key],\n this.selection.capabilities?.fields?.[key],\n this.selection.providerConfig.capabilities?.fields?.[key],\n ];\n const resolved = [\n this.capabilities?.fields?.[key],\n ...Object.values(this.capabilities?.layers ?? {}).map((layer) => layer[key]),\n ].flatMap((capability) =>\n capability?.status === \"known\" && typeof capability.value === \"number\" ? [capability.value] : [],\n );\n const values = [...declarations, ...resolved].filter((value): value is number => typeof value === \"number\");\n if (values.length > 0) limits[key] = Math.min(...values);\n }\n return Object.keys(limits).length === 0 ? undefined : limits;\n }\n get reportsAttempts() {\n return this.model.reportsAttempts;\n }\n get supportsRequestRecording(): boolean {\n return this.model.supportsRequestRecording === true;\n }\n get capabilityVersion() {\n return this.capabilities?.version;\n }\n get configuration(): Readonly<Record<string, string | number | boolean>> {\n const reasoningEffort = this.selection.options.reasoningEffort;\n return omitUndefined({\n provider: this.selection.provider,\n adapter: this.selection.adapter,\n model: this.selection.model,\n profile: this.selection.profile,\n reasoningEffort: typeof reasoningEffort === \"string\" ? reasoningEffort : undefined,\n capabilityVersion: this.capabilityVersion,\n });\n }\n get lastValidation() {\n return this.validation;\n }\n async getModelCapabilities(): Promise<ModelCapabilities> {\n this.capabilities = await this.resolver.resolve(this.selection);\n return this.capabilities;\n }\n async refreshCapabilities(): Promise<ModelCapabilities> {\n this.capabilities = await this.resolver.resolve(this.selection, { refresh: true });\n return this.capabilities;\n }\n async preflight(request: ModelRequest, options: ModelStreamOptions): Promise<void> {\n request = this.effectiveRequest(request);\n options.signal.throwIfAborted();\n const capabilities = await this.getModelCapabilities();\n options.signal.throwIfAborted();\n const {\n responseFormat: configuredFormat,\n unknownCapabilityPolicy: configuredPolicy,\n ...configuredParameters\n } = this.selection.options;\n const parameters: Record<string, unknown> = configuredParameters;\n if (\n parameters.maxTokens === undefined &&\n parameters.maxOutputTokens === undefined &&\n this.selection.limits?.maxOutputTokens !== undefined\n ) {\n const key = [\"deepseek-chat\", \"kimi-chat\", \"zhipu-chat\", \"anthropic-messages\"].includes(this.selection.adapter)\n ? \"maxTokens\"\n : \"maxOutputTokens\";\n parameters[key] = this.selection.limits.maxOutputTokens;\n }\n this.validate(request, capabilities, {\n ...this.options,\n unknownPolicy: this.unknownPolicy,\n parameters: this.options.parameters ?? parameters,\n });\n }\n async *stream(request: ModelRequest, options: ModelStreamOptions): AsyncIterable<ModelEvent> {\n request = this.effectiveRequest(request);\n await this.preflight(request, options);\n const capabilities = this.capabilities!;\n let completed = false;\n let verified = false;\n let responseValidated = false;\n try {\n for await (const event of this.model.stream(request, options)) {\n if (event.type === \"response.completed\") {\n if (completed) throw new ModelProtocolError(\"Model emitted more than one response.completed event\");\n completed = true;\n validateStructuredModelResponse(event.message, request, event);\n responseValidated = request.responseFormat !== undefined && (event.message.toolCalls?.length ?? 0) === 0;\n const limits = [\n capabilities.fields?.[\"tools.maxCalls\"],\n ...Object.values(capabilities.layers ?? {}).map((layer) => layer[\"tools.maxCalls\"]),\n ].flatMap((limit) => (limit?.status === \"known\" && typeof limit.value === \"number\" ? [limit.value] : []));\n if (\n (event.message.toolCalls?.length ?? 0) > 0 &&\n capabilities.fields?.[\"tools.maxCalls\"]?.status === \"unsupported\"\n )\n throw new ModelResponseValidationError(\"Model response uses unsupported tools.maxCalls\", event);\n if (limits.length > 0 && (event.message.toolCalls?.length ?? 0) > Math.min(...limits)) {\n throw new ModelResponseValidationError(\"Model response exceeds tools.maxCalls\", event);\n }\n }\n yield event;\n }\n if (!completed) throw new ModelProtocolError(\"Model stream ended without a response.completed event\");\n verified = true;\n } finally {\n this.resolver.recordVerification(this.selection, request, verified, responseValidated);\n }\n }\n private validate(\n request: ModelRequest,\n capabilities: ModelCapabilities,\n options: ModelRequestValidationOptions,\n ): void {\n this.validation = validateModelRequest(request, capabilities, options);\n if (this.validation.status === \"invalid\") throw new ModelRequestValidationError(this.validation);\n }\n private effectiveRequest(request: ModelRequest): ModelRequest {\n return request.responseFormat === undefined && this.responseFormat !== undefined\n ? { ...request, responseFormat: this.responseFormat }\n : request;\n }\n}\n/** @experimental */\nexport function createCapabilityValidatedModel(\n model: Model,\n selection: ProviderModelSelection,\n options: CapabilityValidatedModelOptions = {},\n): CapabilityValidatedModel {\n return new CapabilityValidatedModel(model, selection, options);\n}\n", "import {\n assertModelResponseFormat,\n compileModelSchema,\n modelSchemaDialect,\n type ContentPart,\n type JsonSchema,\n type ModelRequest,\n} from \"@sortedyuan/may/core\";\nexport { validateStructuredModelResponse } from \"@sortedyuan/may/core\";\nimport type { CapabilityValue, ModelCapabilities, ModelCapabilityKey } from \"./capabilities.js\";\n\n/** @experimental */\nexport type UnknownCapabilityPolicy = \"allow\" | \"require-known\";\n/** @experimental */\nexport interface ModelRequestValidationIssue {\n readonly field: string;\n readonly capability: ModelCapabilityKey | \"reasoningEffort\";\n readonly code: \"unsupported\" | \"unknown\" | \"limit\" | \"parameter\" | \"schema\";\n readonly message: string;\n}\n/** @experimental */\nexport interface ModelRequestValidationResult {\n readonly status: \"valid\" | \"unknown\" | \"invalid\";\n readonly issues: readonly ModelRequestValidationIssue[];\n}\n/** @experimental */\nexport interface ModelRequestValidationOptions {\n readonly unknownPolicy?: UnknownCapabilityPolicy;\n readonly parameters?: Readonly<Record<string, unknown>>;\n readonly estimatedInputTokens?: number;\n readonly mediaMetadata?: (\n part: ContentPart,\n field: string,\n ) => { readonly bytes?: number; readonly mediaType?: string } | undefined;\n}\n/** @experimental */\nexport class ModelRequestValidationError extends TypeError {\n readonly code = \"MODEL_REQUEST_VALIDATION_FAILED\";\n constructor(readonly result: ModelRequestValidationResult) {\n super(result.issues.map((issue) => `${issue.field}: ${issue.message}`).join(\"; \"));\n this.name = \"ModelRequestValidationError\";\n }\n}\n\n/** @experimental */\nexport function validateModelRequest(\n request: ModelRequest,\n capabilities: ModelCapabilities,\n options: ModelRequestValidationOptions = {},\n): ModelRequestValidationResult {\n assertModelResponseFormat(request);\n if (\n options.unknownPolicy !== undefined &&\n options.unknownPolicy !== \"allow\" &&\n options.unknownPolicy !== \"require-known\"\n )\n throw new TypeError(\"unknownPolicy must be allow or require-known\");\n const issues: ModelRequestValidationIssue[] = [];\n const report = (\n field: string,\n capability: ModelRequestValidationIssue[\"capability\"],\n code: ModelRequestValidationIssue[\"code\"],\n message: string,\n ) => issues.push({ field, capability, code, message });\n const values = (key: ModelCapabilityKey): readonly CapabilityValue[] =>\n [capabilities.fields?.[key], ...Object.values(capabilities.layers ?? {}).map((layer) => layer[key])].filter(\n (value): value is CapabilityValue => value !== undefined,\n );\n const requireCapability = (key: ModelCapabilityKey, field: string) => {\n const candidates = values(key);\n if (candidates.some((value) => value.status === \"unsupported\"))\n report(field, key, \"unsupported\", `${key} is unsupported`);\n else if (capabilities.fields?.[key]?.status !== \"known\") report(field, key, \"unknown\", `${key} is unknown`);\n };\n const knownValues = (key: ModelCapabilityKey) =>\n values(key).flatMap((value) => (value.status === \"known\" ? [value.value] : []));\n const limit = (key: ModelCapabilityKey, amount: number, field: string) => {\n if (amount > 0 && values(key).some((value) => value.status === \"unsupported\"))\n report(field, key, \"unsupported\", `${key} is unsupported`);\n const limits = knownValues(key).filter((value): value is number => typeof value === \"number\");\n if (limits.length > 0 && amount > Math.min(...limits))\n report(field, key, \"limit\", `${key} must not exceed ${Math.min(...limits)}`);\n };\n let images = 0;\n let attachments = 0;\n request.messages.forEach((message, messageIndex) =>\n message.content.forEach((part, partIndex) => {\n const field = `messages.${messageIndex}.content.${partIndex}`;\n if (part.type === \"reasoning\") return;\n if (part.type === \"text\" || part.type === \"json\") {\n requireCapability(\"input.text\", field);\n return;\n }\n if (part.type === \"resource\") {\n requireCapability(\"input.resource\", field);\n return;\n }\n requireCapability(`input.${part.type}`, field);\n attachments += 1;\n if (part.type === \"image\") images += 1;\n const sourceKey = `input.${part.type}.sources` as ModelCapabilityKey;\n requireCapability(sourceKey, `${field}.source`);\n for (const allowed of knownValues(sourceKey)) {\n if (Array.isArray(allowed) && !allowed.includes(part.source.type))\n report(`${field}.source.type`, sourceKey, \"unsupported\", `${part.source.type} source is unsupported`);\n }\n const supplied = options.mediaMetadata?.(part, field);\n const bytes = part.source.type === \"base64\" ? Buffer.byteLength(part.source.data, \"base64\") : supplied?.bytes;\n const mediaType = part.source.type === \"base64\" ? part.source.mediaType : supplied?.mediaType;\n if (bytes !== undefined) {\n if (!Number.isSafeInteger(bytes) || bytes < 0)\n throw new TypeError(`${field} media bytes must be a non-negative safe integer`);\n limit(\"maxAttachmentBytes\", bytes, field);\n } else if (knownValues(\"maxAttachmentBytes\").length > 0)\n report(field, \"maxAttachmentBytes\", \"unknown\", \"Attachment size is unknown\");\n if (part.type === \"file\") {\n if (values(\"fileTypes\").some((value) => value.status === \"unsupported\"))\n report(field, \"fileTypes\", \"unsupported\", \"File media types are unsupported\");\n for (const allowed of knownValues(\"fileTypes\")) {\n if (!Array.isArray(allowed)) continue;\n if (mediaType === undefined) report(field, \"fileTypes\", \"unknown\", \"File media type is unknown\");\n else if (!allowed.includes(mediaType))\n report(field, \"fileTypes\", \"unsupported\", \"File media type is unsupported\");\n }\n }\n }),\n );\n limit(\"maxImages\", images, \"messages\");\n limit(\"maxAttachments\", attachments, \"messages\");\n if (request.tools.length > 0) requireCapability(\"tools\", \"tools\");\n const parameters = options.parameters ?? {};\n if (Object.keys(parameters).length > 0) requireCapability(\"parameters\", \"parameters\");\n const effort = parameters.reasoningEffort;\n const thinking = parameters.thinking;\n if (\n thinking !== undefined &&\n thinking !== \"disabled\" &&\n !(typeof thinking === \"object\" && thinking !== null && \"type\" in thinking && thinking.type === \"disabled\")\n ) {\n const mode =\n typeof thinking === \"object\" && thinking !== null && \"type\" in thinking && thinking.type === \"adaptive\"\n ? \"adaptive\"\n : typeof thinking === \"object\" && thinking !== null && \"budgetTokens\" in thinking\n ? \"budget\"\n : \"thinking\";\n requireCapability(\"reasoning.modes\", \"parameters.thinking\");\n for (const modes of knownValues(\"reasoning.modes\"))\n if (Array.isArray(modes) && !modes.includes(mode))\n report(\"parameters.thinking\", \"reasoning.modes\", \"unsupported\", `${mode} reasoning mode is unsupported`);\n }\n if (parameters.reasoningSummary !== undefined) {\n requireCapability(\"reasoning.modes\", \"parameters.reasoningSummary\");\n for (const modes of knownValues(\"reasoning.modes\"))\n if (Array.isArray(modes) && !modes.includes(\"summary\"))\n report(\n \"parameters.reasoningSummary\",\n \"reasoning.modes\",\n \"unsupported\",\n \"reasoning summary mode is unsupported\",\n );\n }\n if (effort !== undefined) {\n for (const modes of values(\"reasoning.modes\")) {\n if (\n modes.status === \"unsupported\" ||\n (modes.status === \"known\" && Array.isArray(modes.value) && !modes.value.includes(\"effort\"))\n )\n report(\"parameters.reasoningEffort\", \"reasoning.modes\", \"unsupported\", \"effort reasoning mode is unsupported\");\n }\n const reasoning = capabilities.reasoningEffort;\n if (reasoning.status === \"unsupported\")\n report(\"parameters.reasoningEffort\", \"reasoningEffort\", \"unsupported\", \"reasoning effort is unsupported\");\n else if (reasoning.status === \"unknown\")\n report(\"parameters.reasoningEffort\", \"reasoningEffort\", \"unknown\", \"reasoning effort is unknown\");\n else if (typeof effort !== \"string\" || !reasoning.efforts.includes(effort))\n report(\n \"parameters.reasoningEffort\",\n \"reasoningEffort\",\n \"parameter\",\n `reasoningEffort must be one of ${reasoning.efforts.join(\", \")}`,\n );\n }\n for (const key of [\"maxTokens\", \"maxOutputTokens\"] as const)\n if (parameters[key] !== undefined) {\n if (!Number.isSafeInteger(parameters[key]) || (parameters[key] as number) < 1)\n report(\n `parameters.${key}`,\n \"maxOutputTokens\",\n \"parameter\",\n \"Output token limit must be a positive safe integer\",\n );\n else limit(\"maxOutputTokens\", parameters[key] as number, `parameters.${key}`);\n }\n if (options.estimatedInputTokens !== undefined) {\n if (!Number.isSafeInteger(options.estimatedInputTokens) || options.estimatedInputTokens < 0)\n throw new TypeError(\"estimatedInputTokens must be a non-negative safe integer\");\n const outputTokens = parameters.maxOutputTokens ?? parameters.maxTokens;\n const reservedOutput =\n typeof outputTokens === \"number\" && Number.isSafeInteger(outputTokens) && outputTokens >= 0 ? outputTokens : 0;\n limit(\"contextWindowTokens\", options.estimatedInputTokens + reservedOutput, \"messages\");\n if (knownValues(\"contextWindowTokens\").length > 0 && outputTokens === undefined)\n report(\"parameters\", \"maxOutputTokens\", \"unknown\", \"Requested output token reservation is unknown\");\n } else if (knownValues(\"contextWindowTokens\").length > 0) {\n report(\"messages\", \"contextWindowTokens\", \"unknown\", \"Input token estimate is unavailable\");\n }\n for (const schema of knownValues(\"parameters\")) {\n const validator = compileModelSchema(schema as JsonSchema);\n if (!validator(parameters))\n report(\"parameters\", \"parameters\", \"parameter\", \"Parameters do not satisfy the declared constraints\");\n }\n const format = request.responseFormat;\n if (format !== undefined) {\n const key = format.type === \"json\" ? \"structuredOutput.json\" : \"structuredOutput.jsonSchema\";\n requireCapability(key, \"responseFormat\");\n if (format.type === \"jsonSchema\") {\n if (typeof format.name !== \"string\" || !/^[A-Za-z0-9_-]{1,64}$/u.test(format.name))\n report(\n \"responseFormat.name\",\n key,\n \"schema\",\n \"Schema name must contain 1 through 64 letters, digits, underscores, or hyphens\",\n );\n const dialect = modelSchemaDialect(format.schema);\n requireCapability(\"structuredOutput.schemaDialects\", \"responseFormat.schema\");\n requireCapability(\"structuredOutput.schemaConstraint\", \"responseFormat.schema\");\n for (const allowed of knownValues(\"structuredOutput.schemaDialects\"))\n if (Array.isArray(allowed) && !allowed.includes(dialect))\n report(\"responseFormat.schema\", \"structuredOutput.schemaDialects\", \"schema\", \"Schema dialect is unsupported\");\n for (const constraint of knownValues(\"structuredOutput.schemaConstraint\"))\n if (!compileModelSchema(constraint as JsonSchema)(format.schema))\n report(\n \"responseFormat.schema\",\n \"structuredOutput.schemaConstraint\",\n \"schema\",\n \"Schema exceeds the declared supported scope\",\n );\n compileModelSchema(format.schema);\n }\n }\n const unique = issues.filter(\n (issue, index) =>\n issues.findIndex(\n (other) => other.field === issue.field && other.capability === issue.capability && other.code === issue.code,\n ) === index,\n );\n const invalid =\n unique.some((issue) => issue.code !== \"unknown\") ||\n (options.unknownPolicy === \"require-known\" && unique.length > 0);\n return { status: invalid ? \"invalid\" : unique.length > 0 ? \"unknown\" : \"valid\", issues: unique };\n}\n\n/** @experimental */\nexport function assertModelRequestValid(\n request: ModelRequest,\n capabilities: ModelCapabilities,\n options: ModelRequestValidationOptions = {},\n): ModelRequestValidationResult {\n const result = validateModelRequest(request, capabilities, options);\n if (result.status === \"invalid\") throw new ModelRequestValidationError(result);\n return result;\n}\n", "import type { Model } from \"@sortedyuan/may/core\";\n\nimport { ProviderAdapterRegistryError } from \"./errors.js\";\nimport { createCapabilityValidatedModel, type CapabilityValidatedModelOptions } from \"./capability-validated-model.js\";\nimport type { ProviderAdapterFactory, ProviderModelSelection } from \"./types.js\";\n\n/** @experimental */\nexport class ProviderAdapterRegistry {\n private readonly factories = new Map<string, ProviderAdapterFactory>();\n\n constructor(\n private readonly validationOptions: CapabilityValidatedModelOptions & { readonly validateRequests?: boolean } = {},\n ) {}\n\n register(name: string, factory: ProviderAdapterFactory): this {\n validateAdapterName(name);\n if (typeof factory !== \"object\" || factory === null) {\n throw new TypeError(\"adapter factory must be an object\");\n }\n if (typeof factory.create !== \"function\") {\n throw new TypeError(\"adapter factory must define create(selection)\");\n }\n if (this.factories.has(name)) {\n throw new ProviderAdapterRegistryError(`Adapter \"${name}\" is already registered`);\n }\n this.factories.set(name, factory);\n return this;\n }\n\n has(name: string): boolean {\n return this.factories.has(name);\n }\n\n names(): readonly string[] {\n return [...this.factories.keys()];\n }\n\n create(selection: ProviderModelSelection): Model {\n const factory = this.factories.get(selection.adapter);\n if (factory === undefined) {\n const available = this.names();\n throw new ProviderAdapterRegistryError(\n `Unsupported adapter \"${selection.adapter}\"` +\n (available.length === 0 ? \"; no adapters are registered\" : `; available adapters: ${available.join(\", \")}`),\n );\n }\n const model = factory.create(selection);\n return this.validationOptions.validateRequests === true\n ? createCapabilityValidatedModel(model, selection, this.validationOptions)\n : model;\n }\n}\n\nfunction validateAdapterName(name: string): void {\n if (typeof name !== \"string\" || name.trim() === \"\") {\n throw new TypeError(\"adapter name must be a non-empty string\");\n }\n if (name !== name.trim()) {\n throw new TypeError(\"adapter name must not have surrounding whitespace\");\n }\n}\n", "import {\n serializeError,\n traceError,\n ModelProtocolError,\n ModelResponseValidationError,\n omitUndefined,\n type Model,\n type ModelContextCompactor,\n type ModelEvent,\n type ModelLimits,\n type ModelRequest,\n type ModelStreamOptions,\n} from \"@sortedyuan/may/core\";\n\nconst RETRYABLE_STATUSES = new Set([408, 409, 429]);\nconst RETRYABLE_CODES = new Set([\n \"ECONNABORTED\",\n \"ECONNREFUSED\",\n \"ECONNRESET\",\n \"EHOSTUNREACH\",\n \"ENETDOWN\",\n \"ENETRESET\",\n \"ENETUNREACH\",\n \"EPIPE\",\n \"ETIMEDOUT\",\n \"EAI_AGAIN\",\n \"UND_ERR_CONNECT_TIMEOUT\",\n \"UND_ERR_HEADERS_TIMEOUT\",\n \"UND_ERR_SOCKET\",\n]);\nconst RETRYABLE_PROVIDER_TYPES = new Set([\n \"api_error\",\n \"internal_error\",\n \"overloaded_error\",\n \"rate_limit_error\",\n \"server_error\",\n]);\n\n/** @experimental */\nexport interface ModelRetryContext {\n /** The attempt that just failed (one-based). */\n readonly attempt: number;\n readonly maxAttempts: number;\n readonly signal: AbortSignal;\n}\n\n/** @experimental */\nexport interface RetryingModelOptions {\n /** Total attempts, including the initial request. Defaults to 3. */\n readonly maxAttempts?: number;\n /** Delay before the second attempt. Defaults to 500ms. */\n readonly baseDelayMs?: number;\n /** Upper bound for calculated delays. Defaults to 8 seconds. */\n readonly maxDelayMs?: number;\n /** Random variation applied to calculated delays. Defaults to 0.2. */\n readonly jitterRatio?: number;\n readonly shouldRetry?: (error: unknown, context: ModelRetryContext) => boolean;\n /** Test or host hook for delay scheduling. */\n readonly sleep?: (delayMs: number, signal: AbortSignal) => Promise<void>;\n /** Test or host hook for jitter. Must return a value from 0 through 1. */\n readonly random?: () => number;\n}\n\n/**\n * Retries one model request at a time. It never wraps an entire agent run, so\n * completed tool calls are not replayed when a later model request fails.\n * Once a content delta has reached the consumer, the attempt is never retried\n * because the model stream has no reset or retraction event.\n * @experimental\n */\nexport class RetryingModel implements Model {\n get supportsRequestRecording(): boolean {\n return this.model.supportsRequestRecording === true;\n }\n readonly reportsAttempts = true;\n get capabilityVersion(): string | undefined {\n return this.model.capabilityVersion;\n }\n get configuration(): NonNullable<Model[\"configuration\"]> {\n return this.model.configuration ?? {};\n }\n get limits(): ModelLimits | undefined {\n return this.model.limits;\n }\n readonly contextCompactor?: ModelContextCompactor;\n private readonly maxAttempts: number;\n private readonly baseDelayMs: number;\n private readonly maxDelayMs: number;\n private readonly jitterRatio: number;\n private readonly shouldRetry: NonNullable<RetryingModelOptions[\"shouldRetry\"]>;\n private readonly sleep: NonNullable<RetryingModelOptions[\"sleep\"]>;\n private readonly random: NonNullable<RetryingModelOptions[\"random\"]>;\n\n constructor(\n private readonly model: Model,\n options: RetryingModelOptions = {},\n ) {\n if (model.contextCompactor !== undefined) {\n this.contextCompactor = model.contextCompactor;\n }\n this.maxAttempts = positiveInteger(options.maxAttempts ?? 3, \"maxAttempts\");\n this.baseDelayMs = nonNegativeNumber(options.baseDelayMs ?? 500, \"baseDelayMs\");\n this.maxDelayMs = nonNegativeNumber(options.maxDelayMs ?? 8_000, \"maxDelayMs\");\n if (this.baseDelayMs > this.maxDelayMs) {\n throw new RangeError(\"baseDelayMs cannot exceed maxDelayMs\");\n }\n this.jitterRatio = ratio(options.jitterRatio ?? 0.2, \"jitterRatio\");\n this.shouldRetry = options.shouldRetry ?? defaultShouldRetryModelError;\n this.sleep = options.sleep ?? abortableSleep;\n this.random = options.random ?? Math.random;\n }\n\n async preflight(request: ModelRequest, options: ModelStreamOptions): Promise<void> {\n await this.model.preflight?.(request, options);\n }\n\n async *stream(request: ModelRequest, options: ModelStreamOptions): AsyncIterable<ModelEvent> {\n await this.preflight(request, options);\n for (let attempt = 1; attempt <= this.maxAttempts; attempt++) {\n let completed = false;\n let emittedContent = false;\n let usage: import(\"@sortedyuan/may/core\").Usage | undefined;\n const telemetry = options.attemptObserver?.start(attempt);\n try {\n for await (const event of this.model.stream(request, {\n ...options,\n ...(telemetry?.traceContext === undefined ? {} : { traceContext: telemetry.traceContext }),\n })) {\n if (options.signal.aborted) throw abortReason(options.signal);\n if ((event.type === \"text.delta\" || event.type === \"reasoning.delta\") && event.delta.length > 0) {\n emittedContent = true;\n telemetry?.content(event.type === \"text.delta\" ? \"text\" : \"reasoning\");\n }\n if (event.type === \"response.completed\") {\n if (completed) throw new ModelProtocolError(\"Model emitted more than one response.completed event\");\n completed = true;\n usage = event.usage;\n if (event.message.content.some((part) => part.type === \"text\" && part.text.length > 0))\n telemetry?.content(\"text\");\n if ((event.message.toolCalls?.length ?? 0) > 0) telemetry?.content(\"tool\");\n if (event.message.content.some((part) => part.type !== \"text\")) telemetry?.content(\"other\");\n }\n yield event;\n }\n if (!completed) throw new ModelProtocolError(\"Model stream ended without a response.completed event\");\n telemetry?.end(omitUndefined({ status: \"ok\", completed, usage }));\n return;\n } catch (error) {\n if (error instanceof Error && \"code\" in error && error.code === \"RUN_CHECKPOINT_FAILED\") throw error;\n if (error instanceof ModelResponseValidationError) {\n completed = error.responseCompleted;\n usage = error.usage;\n }\n telemetry?.end(\n omitUndefined({\n status: options.signal.aborted ? \"cancelled\" : \"error\",\n error: traceError(error),\n completed,\n usage,\n }),\n );\n const context: ModelRetryContext = {\n attempt,\n maxAttempts: this.maxAttempts,\n signal: options.signal,\n };\n if (\n options.signal.aborted ||\n completed ||\n emittedContent ||\n attempt >= this.maxAttempts ||\n !this.shouldRetry(error, context)\n ) {\n throw error;\n }\n\n const delayMs = this.retryDelay(error, attempt);\n yield {\n type: \"retrying\",\n attempt: attempt + 1,\n maxAttempts: this.maxAttempts,\n delayMs,\n error: serializeError(error),\n };\n const waitStarted = performance.now();\n try {\n await this.sleep(delayMs, options.signal);\n } finally {\n options.attemptObserver?.retryWait?.(performance.now() - waitStarted);\n }\n } finally {\n telemetry?.end(omitUndefined({ status: options.signal.aborted ? \"cancelled\" : \"error\", completed, usage }));\n }\n }\n }\n\n private retryDelay(error: unknown, failedAttempt: number): number {\n const requested = retryAfterMs(error);\n if (requested !== undefined) {\n // Never retry earlier than requested. Fail rather than exceed the host backoff budget.\n if (requested > this.maxDelayMs) throw error;\n return requested;\n }\n\n const exponential = Math.min(this.baseDelayMs * 2 ** (failedAttempt - 1), this.maxDelayMs);\n if (exponential === 0 || this.jitterRatio === 0) return exponential;\n\n const random = this.random();\n if (!Number.isFinite(random) || random < 0 || random > 1) {\n throw new RangeError(\"random must return a number from 0 through 1\");\n }\n const factor = 1 - this.jitterRatio + random * this.jitterRatio * 2;\n return Math.round(Math.min(exponential * factor, this.maxDelayMs));\n }\n}\n\n/** @experimental */\nexport function withModelRetry(model: Model, options: RetryingModelOptions = {}): Model {\n return new RetryingModel(model, options);\n}\n\n/** @experimental */\nexport function defaultShouldRetryModelError(error: unknown): boolean {\n return classifyRetryable(error, new Set());\n}\n\nfunction classifyRetryable(error: unknown, seen: Set<unknown>): boolean {\n if (typeof error !== \"object\" || error === null || seen.has(error)) return false;\n seen.add(error);\n\n const candidate = error as Record<string, unknown>;\n if (candidate.name === \"AbortError\" || candidate.name === \"RunCancelledError\") {\n return false;\n }\n\n const status = candidate.status;\n if (typeof status === \"number\") {\n return RETRYABLE_STATUSES.has(status) || status >= 500;\n }\n\n for (const value of [candidate.code, candidate.errno]) {\n if (typeof value === \"string\" && RETRYABLE_CODES.has(value.toUpperCase())) {\n return true;\n }\n }\n\n if (\n typeof candidate.providerType === \"string\" &&\n RETRYABLE_PROVIDER_TYPES.has(candidate.providerType.toLowerCase())\n ) {\n return true;\n }\n if (candidate.name === \"TimeoutError\") return true;\n if (\n candidate.name === \"TypeError\" &&\n typeof candidate.message === \"string\" &&\n /fetch|network|socket|timed?\\s*out/i.test(candidate.message)\n ) {\n return true;\n }\n\n return classifyRetryable(candidate.cause, seen);\n}\n\nfunction retryAfterMs(error: unknown): number | undefined {\n if (typeof error !== \"object\" || error === null) return undefined;\n const value = (error as { retryAfterMs?: unknown }).retryAfterMs;\n return typeof value === \"number\" && Number.isFinite(value) && value >= 0 ? value : undefined;\n}\n\nfunction abortableSleep(delayMs: number, signal: AbortSignal): Promise<void> {\n if (signal.aborted) return Promise.reject(abortReason(signal));\n if (delayMs === 0) return Promise.resolve();\n\n return new Promise<void>((resolve, reject) => {\n const timer = setTimeout(() => {\n signal.removeEventListener(\"abort\", onAbort);\n resolve();\n }, delayMs);\n const onAbort = () => {\n clearTimeout(timer);\n reject(abortReason(signal));\n };\n signal.addEventListener(\"abort\", onAbort, { once: true });\n });\n}\n\nfunction abortReason(signal: AbortSignal): Error {\n if (signal.reason instanceof Error) return signal.reason;\n return new DOMException(\n typeof signal.reason === \"string\" ? signal.reason : \"The operation was aborted\",\n \"AbortError\",\n );\n}\n\nfunction positiveInteger(value: number, field: string): number {\n if (!Number.isSafeInteger(value) || value < 1) {\n throw new RangeError(`${field} must be a positive safe integer`);\n }\n return value;\n}\n\nfunction nonNegativeNumber(value: number, field: string): number {\n if (!Number.isFinite(value) || value < 0) {\n throw new RangeError(`${field} must be a non-negative finite number`);\n }\n return value;\n}\n\nfunction ratio(value: number, field: string): number {\n if (!Number.isFinite(value) || value < 0 || value > 1) {\n throw new RangeError(`${field} must be a number from 0 through 1`);\n }\n return value;\n}\n", "import { resolveModelProfile, type MayConfig, type ResolveProviderOptions } from \"@sortedyuan/may/config\";\nimport { omitUndefined, type ModelLimits } from \"@sortedyuan/may/core\";\n\nimport { ProviderConfigurationError } from \"./errors.js\";\nimport type { ProviderModelSelection, ModelProfileSelector } from \"./types.js\";\n\n/** @experimental */\nexport function selectProviderModel(\n config: MayConfig,\n selector: ModelProfileSelector = {},\n resolveOptions: ResolveProviderOptions = {},\n): ProviderModelSelection {\n const profileName = selector.model ?? config.defaultModel ?? onlyModel(config);\n const profile = resolveModelProfile(config, profileName, resolveOptions);\n return omitUndefined({\n profile: profile.name,\n provider: profile.provider,\n adapter: profile.adapter,\n model: profile.model,\n providerConfig: profile.providerConfig,\n options: profile.options,\n capabilities: profile.capabilities,\n limits: modelLimits(profile.contextWindowTokens, profile.maxOutputTokens),\n });\n}\n\nfunction modelLimits(\n contextWindowTokens: number | undefined,\n maxOutputTokens: number | undefined,\n): ModelLimits | undefined {\n if (contextWindowTokens === undefined && maxOutputTokens === undefined) return undefined;\n return omitUndefined({ contextWindowTokens, maxOutputTokens });\n}\n\nfunction onlyModel(config: MayConfig): string {\n const models = Object.keys(config.models);\n if (models.length === 0) {\n throw new ProviderConfigurationError(`No model profiles are configured in ${config.path}`);\n }\n if (models.length > 1) {\n throw new ProviderConfigurationError(\"Select a model with --model or configure defaultModel\");\n }\n return models[0]!;\n}\n"],
5
+ "mappings": ";;;;;;;;;AAAA,SAAS,kBAAkB;AAC3B,SACE,uBACA,sBAIK;AACP,SAAS,qBAAwC;AAoF3C,IAAO,0BAAP,MAA8B;EA5FpC,OA4FoC;;;EACjB;EACA;EACA;EACA;EACA;EACA,QAAQ,oBAAI,IAAG;EACf,UAAU,oBAAI,IAAG;EACjB,UAA+C,CAAA;EAEhE,YAAY,UAA0C,CAAA,GAAE;AACtD,SAAK,cAAc,QAAQ,eAAe,CAAC,IAAI,6BAA6B,QAAQ,SAAS,WAAW,KAAK,CAAC;AAC9G,SAAK,MAAM,SAAS,QAAQ,cAAc,KAAS,YAAY;AAC/D,SAAK,aAAa,SAAS,QAAQ,mBAAmB,KAAK,iBAAiB;AAC5E,SAAK,aAAa,SAAS,QAAQ,0BAA0B,KAAK,wBAAwB;AAC1F,SAAK,WAAW,gBAAgB,QAAQ,uBAAuB,CAAA,CAAE;AACjE,eAAW,UAAU,OAAO,OAAO,KAAK,QAAQ;AAAG,6BAAuB,MAAM;EAClF;EACA,MAAM,QACJ,WACA,UAA2C,CAAA,GAAE;AAE7C,UAAM,YAAY,QAAQ,UAAU;AACpC,eAAW,SAAS;AAClB,UAAI,CAAC,sBAAsB,SAAS,KAAK;AAAG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,KAAK,QAAQ,KAAK,QAAQ,GAAG;AACrD,UAAM,IAAI,WAAW,GAAG,KAAK,oCAAoC;EACnE;AACA,SAAO;AACT;AALS;;;ACrTT,SAAS,2BAAwE;AACjF,SAAS,iBAAAE,uBAAuC;AAM1C,SAAU,oBACd,QACA,WAAiC,CAAA,GACjC,iBAAyC,CAAA,GAAE;AAE3C,QAAM,cAAc,SAAS,SAAS,OAAO,gBAAgB,UAAU,MAAM;AAC7E,QAAM,UAAU,oBAAoB,QAAQ,aAAa,cAAc;AACvE,SAAOC,gBAAc;IACnB,SAAS,QAAQ;IACjB,UAAU,QAAQ;IAClB,SAAS,QAAQ;IACjB,OAAO,QAAQ;IACf,gBAAgB,QAAQ;IACxB,SAAS,QAAQ;IACjB,cAAc,QAAQ;IACtB,QAAQ,YAAY,QAAQ,qBAAqB,QAAQ,eAAe;GACzE;AACH;AAjBgB;AAmBhB,SAAS,YACP,qBACA,iBAAmC;AAEnC,MAAI,wBAAwB,UAAa,oBAAoB;AAAW,WAAO;AAC/E,SAAOA,gBAAc,EAAE,qBAAqB,gBAAe,CAAE;AAC/D;AANS;AAQT,SAAS,UAAU,QAAiB;AAClC,QAAM,SAAS,OAAO,KAAK,OAAO,MAAM;AACxC,MAAI,OAAO,WAAW,GAAG;AACvB,UAAM,IAAI,2BAA2B,uCAAuC,OAAO,IAAI,EAAE;EAC3F;AACA,MAAI,OAAO,SAAS,GAAG;AACrB,UAAM,IAAI,2BAA2B,uDAAuD;EAC9F;AACA,SAAO,OAAO,CAAC;AACjB;AATS;",
6
+ "names": ["value", "isRecord", "message", "usage", "body", "retryAfterMs", "omitUndefined", "executeRecordedRequest", "omitUndefined", "requestEndpoint", "UnsupportedContentError", "omitUndefined", "serializeVisibleContent", "converted", "serializeJson", "omitUndefined", "UnsupportedContentError", "parseToolInput", "executeRecordedRequest", "requestEndpoint", "omitUndefined", "retryAfterMs", "omitUndefined", "omitUndefined", "omitUndefined", "omitUndefined", "omitUndefined", "executeRecordedRequest", "requestEndpoint", "assertModelResponseFormat", "omitUndefined", "validateStructuredModelResponse", "UnsupportedContentError", "omitUndefined", "text", "hasMedia", "serializeJson", "isRecord", "omitUndefined", "UnsupportedContentError", "omitUndefined", "requireString", "omitUndefined", "requireRecord", "optionalTokenCount", "optionalRecord", "assertModelResponseFormat", "omitUndefined", "executeRecordedRequest", "requestEndpoint", "body", "validateStructuredModelResponse", "requireRecord", "createApiError", "retryAfterMs", "omitUndefined", "omitUndefined", "omitUndefined", "executeRecordedRequest", "omitUndefined", "requestEndpoint", "assertModelResponseFormat", "validateStructuredModelResponse", "UnsupportedContentError", "omitUndefined", "retryAfterMs", "UnsupportedContentError", "omitUndefined", "isRecord", "assertModelResponseFormat", "omitUndefined", "executeRecordedRequest", "requestEndpoint", "body", "message", "isRecord", "validateStructuredModelResponse", "omitUndefined", "optionalString", "requireRecord", "omitUndefined", "assertModelResponseFormat", "omitUndefined", "assertModelResponseFormat", "validateStructuredModelResponse", "assertModelResponseFormat", "assertModelResponseFormat", "omitUndefined", "validateStructuredModelResponse", "factory", "omitUndefined", "optionalString", "requireRecord", "ModelProtocolError", "ModelResponseValidationError", "omitUndefined", "ModelProtocolError", "omitUndefined", "ModelResponseValidationError", "omitUndefined", "omitUndefined"]
7
+ }