@marinoscar/platform-ai-providers 0.0.0-stage → 0.1.0-next.6

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 (264) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/LICENSE +21 -0
  3. package/README.md +102 -2
  4. package/dist/anthropic/anthropic-client.factory.d.ts +43 -0
  5. package/dist/anthropic/anthropic-client.factory.d.ts.map +1 -0
  6. package/dist/anthropic/anthropic-client.factory.js +77 -0
  7. package/dist/anthropic/anthropic-client.factory.js.map +1 -0
  8. package/dist/anthropic/anthropic-errors.d.ts +39 -0
  9. package/dist/anthropic/anthropic-errors.d.ts.map +1 -0
  10. package/dist/anthropic/anthropic-errors.js +179 -0
  11. package/dist/anthropic/anthropic-errors.js.map +1 -0
  12. package/dist/anthropic/anthropic-messages.mapper.d.ts +149 -0
  13. package/dist/anthropic/anthropic-messages.mapper.d.ts.map +1 -0
  14. package/dist/anthropic/anthropic-messages.mapper.js +562 -0
  15. package/dist/anthropic/anthropic-messages.mapper.js.map +1 -0
  16. package/dist/anthropic/anthropic-model-catalog.d.ts +93 -0
  17. package/dist/anthropic/anthropic-model-catalog.d.ts.map +1 -0
  18. package/dist/anthropic/anthropic-model-catalog.js +218 -0
  19. package/dist/anthropic/anthropic-model-catalog.js.map +1 -0
  20. package/dist/anthropic/anthropic-stream.mapper.d.ts +47 -0
  21. package/dist/anthropic/anthropic-stream.mapper.d.ts.map +1 -0
  22. package/dist/anthropic/anthropic-stream.mapper.js +208 -0
  23. package/dist/anthropic/anthropic-stream.mapper.js.map +1 -0
  24. package/dist/anthropic/anthropic.adapter.d.ts +102 -0
  25. package/dist/anthropic/anthropic.adapter.d.ts.map +1 -0
  26. package/dist/anthropic/anthropic.adapter.js +339 -0
  27. package/dist/anthropic/anthropic.adapter.js.map +1 -0
  28. package/dist/anthropic/index.d.ts +7 -0
  29. package/dist/anthropic/index.d.ts.map +1 -0
  30. package/dist/anthropic/index.js +24 -0
  31. package/dist/anthropic/index.js.map +1 -0
  32. package/dist/anthropic/testing/anthropic-fixtures.d.ts +61 -0
  33. package/dist/anthropic/testing/anthropic-fixtures.d.ts.map +1 -0
  34. package/dist/anthropic/testing/anthropic-fixtures.js +153 -0
  35. package/dist/anthropic/testing/anthropic-fixtures.js.map +1 -0
  36. package/dist/anthropic/testing/anthropic-mock-transport.d.ts +117 -0
  37. package/dist/anthropic/testing/anthropic-mock-transport.d.ts.map +1 -0
  38. package/dist/anthropic/testing/anthropic-mock-transport.js +221 -0
  39. package/dist/anthropic/testing/anthropic-mock-transport.js.map +1 -0
  40. package/dist/anthropic/testing/index.d.ts +3 -0
  41. package/dist/anthropic/testing/index.d.ts.map +1 -0
  42. package/dist/anthropic/testing/index.js +20 -0
  43. package/dist/anthropic/testing/index.js.map +1 -0
  44. package/dist/core/ai-error.d.ts +204 -0
  45. package/dist/core/ai-error.d.ts.map +1 -0
  46. package/dist/core/ai-error.js +267 -0
  47. package/dist/core/ai-error.js.map +1 -0
  48. package/dist/core/capabilities.d.ts +127 -0
  49. package/dist/core/capabilities.d.ts.map +1 -0
  50. package/dist/core/capabilities.js +112 -0
  51. package/dist/core/capabilities.js.map +1 -0
  52. package/dist/core/conversation.d.ts +16 -0
  53. package/dist/core/conversation.d.ts.map +1 -0
  54. package/dist/core/conversation.js +57 -0
  55. package/dist/core/conversation.js.map +1 -0
  56. package/dist/core/hosted-tools.d.ts +177 -0
  57. package/dist/core/hosted-tools.d.ts.map +1 -0
  58. package/dist/core/hosted-tools.js +293 -0
  59. package/dist/core/hosted-tools.js.map +1 -0
  60. package/dist/core/index.d.ts +14 -0
  61. package/dist/core/index.d.ts.map +1 -0
  62. package/dist/core/index.js +33 -0
  63. package/dist/core/index.js.map +1 -0
  64. package/dist/core/observability.d.ts +117 -0
  65. package/dist/core/observability.d.ts.map +1 -0
  66. package/dist/core/observability.js +72 -0
  67. package/dist/core/observability.js.map +1 -0
  68. package/dist/core/provider-adapter.interface.d.ts +261 -0
  69. package/dist/core/provider-adapter.interface.d.ts.map +1 -0
  70. package/dist/core/provider-adapter.interface.js +33 -0
  71. package/dist/core/provider-adapter.interface.js.map +1 -0
  72. package/dist/core/retry-after.d.ts +27 -0
  73. package/dist/core/retry-after.d.ts.map +1 -0
  74. package/dist/core/retry-after.js +64 -0
  75. package/dist/core/retry-after.js.map +1 -0
  76. package/dist/core/structured-output.d.ts +50 -0
  77. package/dist/core/structured-output.d.ts.map +1 -0
  78. package/dist/core/structured-output.js +83 -0
  79. package/dist/core/structured-output.js.map +1 -0
  80. package/dist/core/tools.d.ts +94 -0
  81. package/dist/core/tools.d.ts.map +1 -0
  82. package/dist/core/tools.js +76 -0
  83. package/dist/core/tools.js.map +1 -0
  84. package/dist/core/types/file-inputs.types.d.ts +103 -0
  85. package/dist/core/types/file-inputs.types.d.ts.map +1 -0
  86. package/dist/core/types/file-inputs.types.js +81 -0
  87. package/dist/core/types/file-inputs.types.js.map +1 -0
  88. package/dist/core/types/media.types.d.ts +617 -0
  89. package/dist/core/types/media.types.d.ts.map +1 -0
  90. package/dist/core/types/media.types.js +206 -0
  91. package/dist/core/types/media.types.js.map +1 -0
  92. package/dist/core/types/responses.types.d.ts +620 -0
  93. package/dist/core/types/responses.types.d.ts.map +1 -0
  94. package/dist/core/types/responses.types.js +60 -0
  95. package/dist/core/types/responses.types.js.map +1 -0
  96. package/dist/core/vocabulary.d.ts +29 -0
  97. package/dist/core/vocabulary.d.ts.map +1 -0
  98. package/dist/core/vocabulary.js +38 -0
  99. package/dist/core/vocabulary.js.map +1 -0
  100. package/dist/gemini/gemini-client.factory.d.ts +51 -0
  101. package/dist/gemini/gemini-client.factory.d.ts.map +1 -0
  102. package/dist/gemini/gemini-client.factory.js +98 -0
  103. package/dist/gemini/gemini-client.factory.js.map +1 -0
  104. package/dist/gemini/gemini-content.mapper.d.ts +177 -0
  105. package/dist/gemini/gemini-content.mapper.d.ts.map +1 -0
  106. package/dist/gemini/gemini-content.mapper.js +706 -0
  107. package/dist/gemini/gemini-content.mapper.js.map +1 -0
  108. package/dist/gemini/gemini-embeddings.mapper.d.ts +29 -0
  109. package/dist/gemini/gemini-embeddings.mapper.d.ts.map +1 -0
  110. package/dist/gemini/gemini-embeddings.mapper.js +86 -0
  111. package/dist/gemini/gemini-embeddings.mapper.js.map +1 -0
  112. package/dist/gemini/gemini-errors.d.ts +62 -0
  113. package/dist/gemini/gemini-errors.d.ts.map +1 -0
  114. package/dist/gemini/gemini-errors.js +212 -0
  115. package/dist/gemini/gemini-errors.js.map +1 -0
  116. package/dist/gemini/gemini-model-catalog.d.ts +87 -0
  117. package/dist/gemini/gemini-model-catalog.d.ts.map +1 -0
  118. package/dist/gemini/gemini-model-catalog.js +280 -0
  119. package/dist/gemini/gemini-model-catalog.js.map +1 -0
  120. package/dist/gemini/gemini-stream.mapper.d.ts +42 -0
  121. package/dist/gemini/gemini-stream.mapper.d.ts.map +1 -0
  122. package/dist/gemini/gemini-stream.mapper.js +123 -0
  123. package/dist/gemini/gemini-stream.mapper.js.map +1 -0
  124. package/dist/gemini/gemini.adapter.d.ts +110 -0
  125. package/dist/gemini/gemini.adapter.d.ts.map +1 -0
  126. package/dist/gemini/gemini.adapter.js +395 -0
  127. package/dist/gemini/gemini.adapter.js.map +1 -0
  128. package/dist/gemini/index.d.ts +8 -0
  129. package/dist/gemini/index.d.ts.map +1 -0
  130. package/dist/gemini/index.js +25 -0
  131. package/dist/gemini/index.js.map +1 -0
  132. package/dist/gemini/testing/gemini-fixtures.d.ts +176 -0
  133. package/dist/gemini/testing/gemini-fixtures.d.ts.map +1 -0
  134. package/dist/gemini/testing/gemini-fixtures.js +152 -0
  135. package/dist/gemini/testing/gemini-fixtures.js.map +1 -0
  136. package/dist/gemini/testing/gemini-mock-transport.d.ts +158 -0
  137. package/dist/gemini/testing/gemini-mock-transport.d.ts.map +1 -0
  138. package/dist/gemini/testing/gemini-mock-transport.js +358 -0
  139. package/dist/gemini/testing/gemini-mock-transport.js.map +1 -0
  140. package/dist/gemini/testing/index.d.ts +3 -0
  141. package/dist/gemini/testing/index.d.ts.map +1 -0
  142. package/dist/gemini/testing/index.js +20 -0
  143. package/dist/gemini/testing/index.js.map +1 -0
  144. package/dist/index.d.ts +2 -0
  145. package/dist/index.d.ts.map +1 -0
  146. package/dist/index.js +24 -0
  147. package/dist/index.js.map +1 -0
  148. package/dist/openai/azure/azure-openai-client.factory.d.ts +26 -0
  149. package/dist/openai/azure/azure-openai-client.factory.d.ts.map +1 -0
  150. package/dist/openai/azure/azure-openai-client.factory.js +73 -0
  151. package/dist/openai/azure/azure-openai-client.factory.js.map +1 -0
  152. package/dist/openai/azure/azure-openai-settings.d.ts +54 -0
  153. package/dist/openai/azure/azure-openai-settings.d.ts.map +1 -0
  154. package/dist/openai/azure/azure-openai-settings.js +78 -0
  155. package/dist/openai/azure/azure-openai-settings.js.map +1 -0
  156. package/dist/openai/azure/azure-openai.adapter.d.ts +79 -0
  157. package/dist/openai/azure/azure-openai.adapter.d.ts.map +1 -0
  158. package/dist/openai/azure/azure-openai.adapter.js +219 -0
  159. package/dist/openai/azure/azure-openai.adapter.js.map +1 -0
  160. package/dist/openai/compatible/openai-compatible-client.factory.d.ts +19 -0
  161. package/dist/openai/compatible/openai-compatible-client.factory.d.ts.map +1 -0
  162. package/dist/openai/compatible/openai-compatible-client.factory.js +58 -0
  163. package/dist/openai/compatible/openai-compatible-client.factory.js.map +1 -0
  164. package/dist/openai/compatible/openai-compatible-settings.d.ts +38 -0
  165. package/dist/openai/compatible/openai-compatible-settings.d.ts.map +1 -0
  166. package/dist/openai/compatible/openai-compatible-settings.js +48 -0
  167. package/dist/openai/compatible/openai-compatible-settings.js.map +1 -0
  168. package/dist/openai/compatible/openai-compatible.adapter.d.ts +79 -0
  169. package/dist/openai/compatible/openai-compatible.adapter.d.ts.map +1 -0
  170. package/dist/openai/compatible/openai-compatible.adapter.js +197 -0
  171. package/dist/openai/compatible/openai-compatible.adapter.js.map +1 -0
  172. package/dist/openai/index.d.ts +24 -0
  173. package/dist/openai/index.d.ts.map +1 -0
  174. package/dist/openai/index.js +44 -0
  175. package/dist/openai/index.js.map +1 -0
  176. package/dist/openai/openai-audio.mapper.d.ts +80 -0
  177. package/dist/openai/openai-audio.mapper.d.ts.map +1 -0
  178. package/dist/openai/openai-audio.mapper.js +290 -0
  179. package/dist/openai/openai-audio.mapper.js.map +1 -0
  180. package/dist/openai/openai-call-telemetry.d.ts +69 -0
  181. package/dist/openai/openai-call-telemetry.d.ts.map +1 -0
  182. package/dist/openai/openai-call-telemetry.js +136 -0
  183. package/dist/openai/openai-call-telemetry.js.map +1 -0
  184. package/dist/openai/openai-chat-completions-stream.mapper.d.ts +54 -0
  185. package/dist/openai/openai-chat-completions-stream.mapper.d.ts.map +1 -0
  186. package/dist/openai/openai-chat-completions-stream.mapper.js +178 -0
  187. package/dist/openai/openai-chat-completions-stream.mapper.js.map +1 -0
  188. package/dist/openai/openai-chat-completions.engine.d.ts +51 -0
  189. package/dist/openai/openai-chat-completions.engine.d.ts.map +1 -0
  190. package/dist/openai/openai-chat-completions.engine.js +171 -0
  191. package/dist/openai/openai-chat-completions.engine.js.map +1 -0
  192. package/dist/openai/openai-chat-completions.mapper.d.ts +67 -0
  193. package/dist/openai/openai-chat-completions.mapper.d.ts.map +1 -0
  194. package/dist/openai/openai-chat-completions.mapper.js +308 -0
  195. package/dist/openai/openai-chat-completions.mapper.js.map +1 -0
  196. package/dist/openai/openai-client.factory.d.ts +83 -0
  197. package/dist/openai/openai-client.factory.d.ts.map +1 -0
  198. package/dist/openai/openai-client.factory.js +95 -0
  199. package/dist/openai/openai-client.factory.js.map +1 -0
  200. package/dist/openai/openai-embeddings.mapper.d.ts +48 -0
  201. package/dist/openai/openai-embeddings.mapper.d.ts.map +1 -0
  202. package/dist/openai/openai-embeddings.mapper.js +91 -0
  203. package/dist/openai/openai-embeddings.mapper.js.map +1 -0
  204. package/dist/openai/openai-errors.d.ts +74 -0
  205. package/dist/openai/openai-errors.d.ts.map +1 -0
  206. package/dist/openai/openai-errors.js +274 -0
  207. package/dist/openai/openai-errors.js.map +1 -0
  208. package/dist/openai/openai-family-guards.d.ts +8 -0
  209. package/dist/openai/openai-family-guards.d.ts.map +1 -0
  210. package/dist/openai/openai-family-guards.js +23 -0
  211. package/dist/openai/openai-family-guards.js.map +1 -0
  212. package/dist/openai/openai-images.mapper.d.ts +42 -0
  213. package/dist/openai/openai-images.mapper.d.ts.map +1 -0
  214. package/dist/openai/openai-images.mapper.js +176 -0
  215. package/dist/openai/openai-images.mapper.js.map +1 -0
  216. package/dist/openai/openai-model-catalog.d.ts +53 -0
  217. package/dist/openai/openai-model-catalog.d.ts.map +1 -0
  218. package/dist/openai/openai-model-catalog.js +221 -0
  219. package/dist/openai/openai-model-catalog.js.map +1 -0
  220. package/dist/openai/openai-realtime.mapper.d.ts +43 -0
  221. package/dist/openai/openai-realtime.mapper.d.ts.map +1 -0
  222. package/dist/openai/openai-realtime.mapper.js +184 -0
  223. package/dist/openai/openai-realtime.mapper.js.map +1 -0
  224. package/dist/openai/openai-redirect-guard.d.ts +15 -0
  225. package/dist/openai/openai-redirect-guard.d.ts.map +1 -0
  226. package/dist/openai/openai-redirect-guard.js +67 -0
  227. package/dist/openai/openai-redirect-guard.js.map +1 -0
  228. package/dist/openai/openai-responses.engine.d.ts +68 -0
  229. package/dist/openai/openai-responses.engine.d.ts.map +1 -0
  230. package/dist/openai/openai-responses.engine.js +212 -0
  231. package/dist/openai/openai-responses.engine.js.map +1 -0
  232. package/dist/openai/openai-responses.mapper.d.ts +97 -0
  233. package/dist/openai/openai-responses.mapper.d.ts.map +1 -0
  234. package/dist/openai/openai-responses.mapper.js +594 -0
  235. package/dist/openai/openai-responses.mapper.js.map +1 -0
  236. package/dist/openai/openai-stream.mapper.d.ts +40 -0
  237. package/dist/openai/openai-stream.mapper.d.ts.map +1 -0
  238. package/dist/openai/openai-stream.mapper.js +144 -0
  239. package/dist/openai/openai-stream.mapper.js.map +1 -0
  240. package/dist/openai/openai.adapter.d.ts +99 -0
  241. package/dist/openai/openai.adapter.d.ts.map +1 -0
  242. package/dist/openai/openai.adapter.js +258 -0
  243. package/dist/openai/openai.adapter.js.map +1 -0
  244. package/dist/openai/testing/chat-completions-fixtures.d.ts +51 -0
  245. package/dist/openai/testing/chat-completions-fixtures.d.ts.map +1 -0
  246. package/dist/openai/testing/chat-completions-fixtures.js +79 -0
  247. package/dist/openai/testing/chat-completions-fixtures.js.map +1 -0
  248. package/dist/openai/testing/conformance-responders.d.ts +20 -0
  249. package/dist/openai/testing/conformance-responders.d.ts.map +1 -0
  250. package/dist/openai/testing/conformance-responders.js +77 -0
  251. package/dist/openai/testing/conformance-responders.js.map +1 -0
  252. package/dist/openai/testing/index.d.ts +5 -0
  253. package/dist/openai/testing/index.d.ts.map +1 -0
  254. package/dist/openai/testing/index.js +22 -0
  255. package/dist/openai/testing/index.js.map +1 -0
  256. package/dist/openai/testing/openai-fixtures.d.ts +125 -0
  257. package/dist/openai/testing/openai-fixtures.d.ts.map +1 -0
  258. package/dist/openai/testing/openai-fixtures.js +263 -0
  259. package/dist/openai/testing/openai-fixtures.js.map +1 -0
  260. package/dist/openai/testing/openai-mock-transport.d.ts +432 -0
  261. package/dist/openai/testing/openai-mock-transport.d.ts.map +1 -0
  262. package/dist/openai/testing/openai-mock-transport.js +570 -0
  263. package/dist/openai/testing/openai-mock-transport.js.map +1 -0
  264. package/package.json +94 -4
package/CHANGELOG.md ADDED
@@ -0,0 +1,7 @@
1
+ # @marinoscar/platform-ai-providers
2
+
3
+ ## 0.1.0-next.6
4
+
5
+ ### Minor Changes
6
+
7
+ - e1ca08c: New package `@marinoscar/platform-ai-providers` (#991): the five AI provider adapters (OpenAI, OpenAI-compatible, Azure OpenAI, Anthropic, Gemini) and the provider-agnostic core they implement, runnable in a plain Node process (no Nest, no database, no OpenTelemetry SDK). Subpaths: `.` (core types, `AiProviderAdapter` and its ports, `AiError` and its codes, capabilities, structured output, tools, hosted tools, conversation helpers, media and file-input types, `parseRetryAfterMs`, and the structural `AiLogger` and `AiTracer` ports), `./openai`, `./anthropic`, `./gemini`, and `./<provider>/testing` (mock transports and fixtures). `zod` is a required peer; each SDK is an optional peer loaded only by its subpath. Each adapter is built with `create*Adapter({ clients?, logger?, tracer? })`; without a tracer no span is started. API: `@marinoscar/platform-api/ai` keeps every exported name and type: it re-exports the core, its provider classes are now Nest subclasses of the lean adapters and client factories (same constructors, injection tokens, logger names and `ai.provider.call` spans), and `AiError` is still an `HttpException` with `toRateLimitError()` (the platform splices `HttpException` into its prototype chain when `ai/core/ai-error` loads). `parseRetryAfterMs` moved to the new package and `@marinoscar/platform-api/jobs` re-exports it. The `ai-no-sdk-leak` suite gains `aiProvidersPackageSdkDirs` and accepts a list of `sdkOwner` manifests; the platform package's own provider folders now import no SDK. Back-compat: no route, shape, id or behaviour changes; the platform package still depends on the three SDKs so an app gets them installed.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 marinoscar
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,103 @@
1
- # Temporary Holding Version
1
+ # @marinoscar/platform-ai-providers
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ ## Purpose and scope
4
+
5
+ The AI provider adapters of the platform (OpenAI, OpenAI-compatible, Azure OpenAI, Anthropic, Google Gemini) and the provider-agnostic core types they implement (`AiProviderAdapter` and its ports, `AiError`, capabilities, structured output, tools, hosted tools, conversation helpers, media and file-input types). It runs in a plain Node process: no Nest, no database, no OpenTelemetry SDK. `@marinoscar/platform-api/ai` builds its Nest provider modules on these classes and re-exports the core unchanged: an app that wants the adapters without Nest, a database or OpenTelemetry (a CLI, a worker, another service) installs this package alone.
6
+
7
+ ## Install and peer dependencies
8
+
9
+ ```bash
10
+ npm install @marinoscar/platform-ai-providers zod
11
+ npm install openai # for ./openai (OpenAI, OpenAI-compatible, Azure OpenAI)
12
+ npm install @anthropic-ai/sdk # for ./anthropic
13
+ npm install @google/genai # for ./gemini
14
+ ```
15
+
16
+ `zod` is a required peer. Each provider SDK is an optional peer, loaded only by its own subpath: install only the ones you import. The root entry loads no SDK. CommonJS, Node 24 or newer.
17
+
18
+ | Subpath | Optional peer needed |
19
+ |---|---|
20
+ | `.` | none |
21
+ | `./openai`, `./openai/testing` | `openai` |
22
+ | `./anthropic`, `./anthropic/testing` | `@anthropic-ai/sdk` |
23
+ | `./gemini`, `./gemini/testing` | `@google/genai` |
24
+
25
+ ## Quick start
26
+
27
+ A plain Node script, no Nest and no database:
28
+
29
+ ```ts
30
+ import { createOpenAiAdapter } from '@marinoscar/platform-ai-providers/openai';
31
+
32
+ const adapter = createOpenAiAdapter({ logger: console });
33
+ const ctx = { apiKey: process.env.MY_KEY!, requestId: 'r1' };
34
+
35
+ for await (const event of adapter.responses.stream({ model: 'gpt-4o', input: 'Hello' }, ctx)) {
36
+ if (event.type === 'output_text.delta') process.stdout.write(event.delta);
37
+ }
38
+ ```
39
+
40
+ `adapter.responses.create(req, ctx)` returns the whole `AiResponse` instead. A failure is always an `AiError` with a stable `code`.
41
+
42
+ ### Subpaths
43
+
44
+ | Import | Holds |
45
+ |---|---|
46
+ | `@marinoscar/platform-ai-providers` | The core: `AiProviderAdapter` and its ports, `AiError` and its codes, capabilities, structured output, tools, hosted tools, conversation helpers, media and file-input types, `parseRetryAfterMs`, the `AiLogger` and `AiTracer` ports |
47
+ | `.../openai` | `createOpenAiAdapter`, `createOpenAiCompatibleAdapter`, `createAzureOpenAiAdapter`, the engines and mappers, the redirect and family guards |
48
+ | `.../anthropic` | `createAnthropicAdapter` (Messages API) |
49
+ | `.../gemini` | `createGeminiAdapter` (generateContent, embeddings) |
50
+ | `.../<provider>/testing` | The provider's mock transport and fixtures, for tests |
51
+
52
+ ### Relation to `@marinoscar/platform-api/ai`
53
+
54
+ `@marinoscar/platform-api/ai` depends on this package and re-exports every name from it. Its provider classes are Nest subclasses of these adapters (same constructors, injection tokens, logger names and spans), and its `AiError` is this package's, with `HttpException` spliced into the prototype. Provider registration, key resolution, usage and policy stay there; this package has no registry.
55
+
56
+ ## Configuration
57
+
58
+ Each `create*Adapter(options)` takes optional `clients` (the SDK client factory), `logger` (an `AiLogger`, which Nest's `Logger` and `console` satisfy) and `tracer` (an `AiTracer`, which an OpenTelemetry `Tracer` satisfies). The key, base URL and provider settings travel per call in `AiCallContext` (`apiKey`, `baseUrl`, `providerSettings`, `signal`, `requestId`); an adapter never holds a key between calls.
59
+
60
+ ## Extension-point catalog
61
+
62
+ None. The package is a library of adapters; the platform's provider registry (`registerAiProvider`) is the extension point and lives in `@marinoscar/platform-api/ai`.
63
+
64
+ ## Data
65
+
66
+ None. The package stores nothing; every call is stateless.
67
+
68
+ ## Permissions and settings
69
+
70
+ None. Keys and provider settings are passed per call by the caller.
71
+
72
+ ## UI
73
+
74
+ None. Server-side only: a provider key must never reach a browser.
75
+
76
+ ## Infra
77
+
78
+ None. No environment variable is read; every SDK option that could be read from the environment is pinned.
79
+
80
+ ## Observability
81
+
82
+ `AiTracer` is a structural port that an OpenTelemetry `Tracer` satisfies, but the package imports no OpenTelemetry SDK. Without a tracer no span is started; with one, each provider call runs inside one `ai.provider.call` span carrying `ai.provider`, `ai.model`, `ai.operation` and `ai.status`. Without a logger nothing is logged.
83
+
84
+ ## Security notes
85
+
86
+ The key is passed per call and never stored, logged, put on a span or carried by an `AiError`; an `AiError`'s `cause` is non-enumerable and never serialised. The SDK clients are built with redirects refused (`noRedirectFetch` and the redirect guard in `./openai`), so a key is never replayed to a redirect target, and the family guards refuse a request the Azure and OpenAI-compatible adapters cannot serve (a hosted tool) before any call. No environment variable is read.
87
+
88
+ ## Conformance suite
89
+
90
+ None in this package. `@marinoscar/platform-api/ai/testing` runs the adapter conformance kit and the `ai-no-sdk-leak` suite over it.
91
+
92
+ ## Upgrade notes
93
+
94
+ New in 0.1.0-next.5: extracted from `@marinoscar/platform-api/ai`, whose public API is unchanged.
95
+
96
+ ## Troubleshooting
97
+
98
+ None yet. A missing SDK surfaces as a module-not-found error when its subpath is imported: install that optional peer.
99
+
100
+ ## Links
101
+
102
+ - [AI platform spec](../../docs/specs/ai-platform.md)
103
+ - [`@marinoscar/platform-api/ai`](../platform-api/src/ai/README.md)
@@ -0,0 +1,43 @@
1
+ import { Anthropic } from '@anthropic-ai/sdk';
2
+ import type { AiCallContext } from '../core/index';
3
+ /**
4
+ * The Anthropic API root used when the provider settings name no `baseUrl`.
5
+ *
6
+ * @stability experimental
7
+ */
8
+ export declare const ANTHROPIC_DEFAULT_BASE_URL = "https://api.anthropic.com";
9
+ /**
10
+ * A generous ceiling for one request; long extended-thinking turns take minutes.
11
+ *
12
+ * @stability experimental
13
+ */
14
+ export declare const ANTHROPIC_DEFAULT_TIMEOUT_MS: number;
15
+ /**
16
+ * The `fetch` the SDK uses. Tests inject a mocked one; production uses the global.
17
+ *
18
+ * @stability experimental
19
+ */
20
+ export type AnthropicFetch = (input: string | URL | Request, init?: RequestInit) => Promise<Response>;
21
+ /**
22
+ * Options for {@link AnthropicClientFactory}; tests inject a mocked `fetch`.
23
+ *
24
+ * @stability experimental
25
+ */
26
+ export interface AnthropicClientOptions {
27
+ /** The `fetch` the SDK uses; the global one when absent. */
28
+ fetch?: AnthropicFetch;
29
+ /** Per-request timeout in milliseconds; {@link ANTHROPIC_DEFAULT_TIMEOUT_MS} when absent. */
30
+ timeoutMs?: number;
31
+ }
32
+ /**
33
+ * Builds one Anthropic SDK client per call from that call's key and base URL, with every option pinned (no retries, no environment reads).
34
+ *
35
+ * @stability experimental
36
+ */
37
+ export declare class AnthropicClientFactory {
38
+ private readonly options;
39
+ constructor(options?: AnthropicClientOptions);
40
+ /** The SDK client for one call. Throws `AI_KEY_INVALID` for an empty key. */
41
+ create(ctx: AiCallContext): Anthropic;
42
+ }
43
+ //# sourceMappingURL=anthropic-client.factory.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"anthropic-client.factory.d.ts","sourceRoot":"","sources":["../../src/anthropic/anthropic-client.factory.ts"],"names":[],"mappings":"AA2BA,OAAO,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAG9C,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AAGnD;;;;GAIG;AACH,eAAO,MAAM,0BAA0B,8BAA8B,CAAC;AAEtE;;;;GAIG;AACH,eAAO,MAAM,4BAA4B,QAAiB,CAAC;AAE3D;;;;GAIG;AACH,MAAM,MAAM,cAAc,GAAG,CAAC,KAAK,EAAE,MAAM,GAAG,GAAG,GAAG,OAAO,EAAE,IAAI,CAAC,EAAE,WAAW,KAAK,OAAO,CAAC,QAAQ,CAAC,CAAC;AAEtG;;;;GAIG;AACH,MAAM,WAAW,sBAAsB;IACrC,4DAA4D;IAC5D,KAAK,CAAC,EAAE,cAAc,CAAC;IACvB,6FAA6F;IAC7F,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB;AAED;;;;GAIG;AACH,qBAAa,sBAAsB;IACjC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAyB;gBAErC,OAAO,CAAC,EAAE,sBAAsB;IAI5C,6EAA6E;IAC7E,MAAM,CAAC,GAAG,EAAE,aAAa,GAAG,SAAS;CAoBtC"}
@@ -0,0 +1,77 @@
1
+ "use strict";
2
+ // =============================================================================
3
+ // Anthropic SDK client factory (issue #446, epic #421)
4
+ // =============================================================================
5
+ //
6
+ // One client PER CALL, built from that call's `AiCallContext` — the same
7
+ // shape as `OpenAiClientFactory`, for the same reason: the key is resolved
8
+ // per call (org key or the user's own), so a long-lived client holding one
9
+ // key would be the wrong shape.
10
+ //
11
+ // Every credential and endpoint the SDK would otherwise discover on its own
12
+ // is pinned explicitly. There is no `ANTHROPIC_API_KEY` / `ANTHROPIC_BASE_URL`
13
+ // configuration in this application (docs/specs/ai-platform.md §2.1), and the
14
+ // SDK's credential chain (`ANTHROPIC_AUTH_TOKEN`, an `ant auth login` profile,
15
+ // workload identity federation) must never silently decide which account a
16
+ // call bills: passing `apiKey` explicitly short-circuits that whole chain
17
+ // (the SDK resolves no default credentials once `apiKey` is set), and
18
+ // `authToken: null` keeps an ambient bearer token off the request.
19
+ //
20
+ // `maxRetries: 0` — retries are the caller's job (the queue for a job, the
21
+ // user for an interactive call); the SDK retrying a 429/529 underneath would
22
+ // multiply every attempt and hide the throttle from `toRateLimitError()`.
23
+ //
24
+ // An explicit `timeout` also disables the SDK's "streaming is required"
25
+ // pre-check for a large non-streaming `max_tokens`: the adapter sizes
26
+ // `max_tokens` itself (see `anthropic-model-catalog.ts`).
27
+ // =============================================================================
28
+ Object.defineProperty(exports, "__esModule", { value: true });
29
+ exports.AnthropicClientFactory = exports.ANTHROPIC_DEFAULT_TIMEOUT_MS = exports.ANTHROPIC_DEFAULT_BASE_URL = void 0;
30
+ const sdk_1 = require("@anthropic-ai/sdk");
31
+ const index_1 = require("../core/index");
32
+ const anthropic_errors_1 = require("./anthropic-errors");
33
+ /**
34
+ * The Anthropic API root used when the provider settings name no `baseUrl`.
35
+ *
36
+ * @stability experimental
37
+ */
38
+ exports.ANTHROPIC_DEFAULT_BASE_URL = 'https://api.anthropic.com';
39
+ /**
40
+ * A generous ceiling for one request; long extended-thinking turns take minutes.
41
+ *
42
+ * @stability experimental
43
+ */
44
+ exports.ANTHROPIC_DEFAULT_TIMEOUT_MS = 10 * 60 * 1000;
45
+ /**
46
+ * Builds one Anthropic SDK client per call from that call's key and base URL, with every option pinned (no retries, no environment reads).
47
+ *
48
+ * @stability experimental
49
+ */
50
+ class AnthropicClientFactory {
51
+ options;
52
+ constructor(options) {
53
+ this.options = options ?? {};
54
+ }
55
+ /** The SDK client for one call. Throws `AI_KEY_INVALID` for an empty key. */
56
+ create(ctx) {
57
+ if (!ctx.apiKey || ctx.apiKey.trim().length === 0) {
58
+ throw new index_1.AiError('AI_KEY_INVALID', 'No Anthropic API key was supplied.', {
59
+ details: { provider: anthropic_errors_1.ANTHROPIC_PROVIDER_ID },
60
+ });
61
+ }
62
+ return new sdk_1.Anthropic({
63
+ apiKey: ctx.apiKey,
64
+ authToken: null,
65
+ webhookKey: null,
66
+ baseURL: ctx.baseUrl ?? exports.ANTHROPIC_DEFAULT_BASE_URL,
67
+ maxRetries: 0,
68
+ timeout: this.options.timeoutMs ?? exports.ANTHROPIC_DEFAULT_TIMEOUT_MS,
69
+ // The SDK's own logger writes to the console and, at debug level, the
70
+ // request — never let an ambient ANTHROPIC_LOG turn that on.
71
+ logLevel: 'off',
72
+ ...(this.options.fetch ? { fetch: this.options.fetch } : {}),
73
+ });
74
+ }
75
+ }
76
+ exports.AnthropicClientFactory = AnthropicClientFactory;
77
+ //# sourceMappingURL=anthropic-client.factory.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"anthropic-client.factory.js","sourceRoot":"","sources":["../../src/anthropic/anthropic-client.factory.ts"],"names":[],"mappings":";AAAA,gFAAgF;AAChF,uDAAuD;AACvD,gFAAgF;AAChF,EAAE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AAQ,EAAE,KAAK;YACf,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;SAC7D,CAAC,CAAC;IACL,CAAC;CACF;AA5BD,wDA4BC"}
@@ -0,0 +1,39 @@
1
+ import { AiError, AiErrorCode } from '../core/index';
2
+ /**
3
+ * The provider id of the Anthropic adapter.
4
+ *
5
+ * @stability experimental
6
+ */
7
+ export declare const ANTHROPIC_PROVIDER_ID = "anthropic";
8
+ /**
9
+ * The generic, secret-free message this adapter uses for `code`.
10
+ *
11
+ * @stability experimental
12
+ */
13
+ export declare function anthropicErrorMessage(code: AiErrorCode): string;
14
+ /**
15
+ * Classifies an Anthropic error `type` (from a body or a stream `error` frame).
16
+ *
17
+ * @stability experimental
18
+ */
19
+ export declare function classifyAnthropicErrorType(type: string | null | undefined): AiErrorCode;
20
+ /**
21
+ * The provider's requested back-off, from the standard `retry-after` header.
22
+ *
23
+ * @stability experimental
24
+ */
25
+ export declare function anthropicRetryAfter(headers: Headers | undefined): number | undefined;
26
+ /**
27
+ * Which `AiErrorCode` an SDK error means. Pure — exported for the table spec.
28
+ *
29
+ * @stability experimental
30
+ */
31
+ export declare function anthropicErrorCode(err: unknown): AiErrorCode;
32
+ /**
33
+ * Turns anything an Anthropic call threw into an `AiError`. An `AiError` is
34
+ * returned unchanged (the mapper's own `AI_CAPABILITY_UNSUPPORTED`, for one).
35
+ *
36
+ * @stability experimental
37
+ */
38
+ export declare function mapAnthropicError(err: unknown): AiError;
39
+ //# sourceMappingURL=anthropic-errors.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"anthropic-errors.d.ts","sourceRoot":"","sources":["../../src/anthropic/anthropic-errors.ts"],"names":[],"mappings":"AAyCA,OAAO,EAAE,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAGrD;;;;GAIG;AACH,eAAO,MAAM,qBAAqB,cAAc,CAAC;AAoBjD;;;;GAIG;AACH,wBAAgB,qBAAqB,CAAC,IAAI,EAAE,WAAW,GAAG,MAAM,CAE/D;AAED;;;;GAIG;AACH,wBAAgB,0BAA0B,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,GAAG,WAAW,CAiBvF;AAED;;;;GAIG;AACH,wBAAgB,mBAAmB,CAAC,OAAO,EAAE,OAAO,GAAG,SAAS,GAAG,MAAM,GAAG,SAAS,CAEpF;AAED;;;;GAIG;AACH,wBAAgB,kBAAkB,CAAC,GAAG,EAAE,OAAO,GAAG,WAAW,CA2B5D;AAMD;;;;;GAKG;AACH,wBAAgB,iBAAiB,CAAC,GAAG,EAAE,OAAO,GAAG,OAAO,CA0BvD"}
@@ -0,0 +1,179 @@
1
+ "use strict";
2
+ // =============================================================================
3
+ // Anthropic SDK error -> AiError (issue #446, epic #421)
4
+ // =============================================================================
5
+ //
6
+ // The one place an Anthropic SDK failure becomes an `AiError` — the exact
7
+ // counterpart of `openai-errors.ts`, and for the same reasons: every `catch`
8
+ // in this adapter funnels through `mapAnthropicError`, so a raw SDK exception
9
+ // never crosses the `AiProviderAdapter` boundary (the conformance kit asserts
10
+ // it) and one provider condition cannot surface as two codes.
11
+ //
12
+ // ⚠ SECRETS. The SDK's own `message` is never copied into the `AiError`: it
13
+ // is the provider's text, and a provider's text can echo request details.
14
+ // What travels in `details` is short machine-readable metadata only — the
15
+ // HTTP status, Anthropic's error `type` (`rate_limit_error`, ...) and its
16
+ // request id. The SDK error is kept as the non-enumerable `cause`.
17
+ //
18
+ // THE TABLE (pinned by `anthropic-errors.spec.ts`):
19
+ //
20
+ // 401 authentication_error AI_KEY_INVALID
21
+ // 403 permission_error AI_MODEL_NOT_REACHABLE (the key may not use it)
22
+ // 404 not_found_error AI_MODEL_NOT_REACHABLE (Messages' only 404 is the model)
23
+ // 402 billing_error AI_RATE_LIMITED (OpenAI's `insufficient_quota` precedent)
24
+ // 429 rate_limit_error AI_RATE_LIMITED, with `retry-after`
25
+ // 529 overloaded_error / 5xx / 408 AI_PROVIDER_UNAVAILABLE (with `retry-after` when named)
26
+ // 400/409/413/422 AI_INVALID_REQUEST
27
+ // abort (APIUserAbortError) AI_PROVIDER_UNAVAILABLE, details.aborted — as OpenAI's
28
+ // connection / timeout AI_PROVIDER_UNAVAILABLE, details.transport
29
+ //
30
+ // A mid-stream `event: error` frame has no HTTP status; the SDK raises it as a
31
+ // status-less `APIError` whose `type` is the body's `error.type`, classified by
32
+ // the same table.
33
+ // =============================================================================
34
+ Object.defineProperty(exports, "__esModule", { value: true });
35
+ exports.ANTHROPIC_PROVIDER_ID = void 0;
36
+ exports.anthropicErrorMessage = anthropicErrorMessage;
37
+ exports.classifyAnthropicErrorType = classifyAnthropicErrorType;
38
+ exports.anthropicRetryAfter = anthropicRetryAfter;
39
+ exports.anthropicErrorCode = anthropicErrorCode;
40
+ exports.mapAnthropicError = mapAnthropicError;
41
+ const sdk_1 = require("@anthropic-ai/sdk");
42
+ const index_1 = require("../core/index");
43
+ const index_2 = require("../core/index");
44
+ /**
45
+ * The provider id of the Anthropic adapter.
46
+ *
47
+ * @stability experimental
48
+ */
49
+ exports.ANTHROPIC_PROVIDER_ID = 'anthropic';
50
+ const MESSAGES = {
51
+ AI_DISABLED: 'AI is disabled.',
52
+ AI_PROVIDER_DISABLED: 'The AI provider is disabled.',
53
+ AI_KEY_REQUIRED: 'An API key is required for this AI provider.',
54
+ AI_KEY_INVALID: 'The Anthropic API key was rejected.',
55
+ AI_MODEL_NOT_ENABLED: 'The model is not enabled.',
56
+ AI_MODEL_NOT_REACHABLE: 'The Anthropic model is not reachable with this API key.',
57
+ AI_CAPABILITY_UNSUPPORTED: 'The request uses a capability Anthropic does not support here.',
58
+ AI_TOOL_DISABLED: 'The requested tool is not enabled in this deployment.',
59
+ AI_REALTIME_DISABLED: 'Realtime sessions are not enabled in this deployment.',
60
+ AI_RATE_LIMITED: 'Anthropic rate-limited the request.',
61
+ AI_PROVIDER_UNAVAILABLE: 'Anthropic is unavailable or the request failed.',
62
+ AI_CONTENT_FILTERED: 'Anthropic refused the request.',
63
+ AI_INVALID_REQUEST: 'Anthropic rejected the request as invalid.',
64
+ AI_STRUCTURED_OUTPUT_INVALID: 'The model output does not match the requested schema.',
65
+ AI_STORAGE_UNAVAILABLE: 'Object storage is unavailable.',
66
+ };
67
+ /**
68
+ * The generic, secret-free message this adapter uses for `code`.
69
+ *
70
+ * @stability experimental
71
+ */
72
+ function anthropicErrorMessage(code) {
73
+ return MESSAGES[code];
74
+ }
75
+ /**
76
+ * Classifies an Anthropic error `type` (from a body or a stream `error` frame).
77
+ *
78
+ * @stability experimental
79
+ */
80
+ function classifyAnthropicErrorType(type) {
81
+ switch (type) {
82
+ case 'authentication_error':
83
+ return 'AI_KEY_INVALID';
84
+ case 'permission_error':
85
+ case 'not_found_error':
86
+ return 'AI_MODEL_NOT_REACHABLE';
87
+ case 'rate_limit_error':
88
+ case 'billing_error':
89
+ return 'AI_RATE_LIMITED';
90
+ case 'invalid_request_error':
91
+ case 'request_too_large':
92
+ return 'AI_INVALID_REQUEST';
93
+ default:
94
+ // overloaded_error, api_error, timeout_error, anything unknown.
95
+ return 'AI_PROVIDER_UNAVAILABLE';
96
+ }
97
+ }
98
+ /**
99
+ * The provider's requested back-off, from the standard `retry-after` header.
100
+ *
101
+ * @stability experimental
102
+ */
103
+ function anthropicRetryAfter(headers) {
104
+ return (0, index_2.parseRetryAfterMs)(headers?.get('retry-after') ?? null) ?? undefined;
105
+ }
106
+ /**
107
+ * Which `AiErrorCode` an SDK error means. Pure — exported for the table spec.
108
+ *
109
+ * @stability experimental
110
+ */
111
+ function anthropicErrorCode(err) {
112
+ if (err instanceof index_1.AiError)
113
+ return err.code;
114
+ // Subclasses before their parents: both extend APIError.
115
+ if (err instanceof sdk_1.APIUserAbortError)
116
+ return 'AI_PROVIDER_UNAVAILABLE';
117
+ if (err instanceof sdk_1.APIConnectionError)
118
+ return 'AI_PROVIDER_UNAVAILABLE';
119
+ if (err instanceof sdk_1.APIError) {
120
+ const status = err.status;
121
+ if (typeof status === 'number') {
122
+ if (status === 401)
123
+ return 'AI_KEY_INVALID';
124
+ if (status === 402)
125
+ return 'AI_RATE_LIMITED';
126
+ if (status === 403 || status === 404)
127
+ return 'AI_MODEL_NOT_REACHABLE';
128
+ if (status === 429)
129
+ return 'AI_RATE_LIMITED';
130
+ if (status === 408 || status >= 500)
131
+ return 'AI_PROVIDER_UNAVAILABLE';
132
+ if (status >= 400)
133
+ return 'AI_INVALID_REQUEST';
134
+ }
135
+ return classifyAnthropicErrorType(err.type);
136
+ }
137
+ // Any other SDK error (a malformed SSE frame, "streaming required", ...),
138
+ // a fetch/socket failure, anything else.
139
+ if (err instanceof sdk_1.AnthropicError)
140
+ return 'AI_PROVIDER_UNAVAILABLE';
141
+ return 'AI_PROVIDER_UNAVAILABLE';
142
+ }
143
+ function stringOrUndefined(value) {
144
+ return typeof value === 'string' && value.length > 0 ? value : undefined;
145
+ }
146
+ /**
147
+ * Turns anything an Anthropic call threw into an `AiError`. An `AiError` is
148
+ * returned unchanged (the mapper's own `AI_CAPABILITY_UNSUPPORTED`, for one).
149
+ *
150
+ * @stability experimental
151
+ */
152
+ function mapAnthropicError(err) {
153
+ if (err instanceof index_1.AiError)
154
+ return err;
155
+ const code = anthropicErrorCode(err);
156
+ const details = { provider: exports.ANTHROPIC_PROVIDER_ID };
157
+ let retryAfterMs;
158
+ if (err instanceof sdk_1.APIUserAbortError) {
159
+ details.aborted = true;
160
+ }
161
+ else if (err instanceof sdk_1.APIConnectionError) {
162
+ details.transport = err instanceof sdk_1.APIConnectionTimeoutError ? 'timeout' : 'connection';
163
+ }
164
+ else if (err instanceof sdk_1.APIError) {
165
+ if (typeof err.status === 'number')
166
+ details.status = err.status;
167
+ const providerType = stringOrUndefined(err.type);
168
+ const providerRequestId = stringOrUndefined(err.requestID);
169
+ if (providerType)
170
+ details.providerType = providerType;
171
+ if (providerRequestId)
172
+ details.providerRequestId = providerRequestId;
173
+ if (code === 'AI_RATE_LIMITED' || code === 'AI_PROVIDER_UNAVAILABLE') {
174
+ retryAfterMs = anthropicRetryAfter(err.headers);
175
+ }
176
+ }
177
+ return new index_1.AiError(code, anthropicErrorMessage(code), { cause: err, details, retryAfterMs });
178
+ }
179
+ //# sourceMappingURL=anthropic-errors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"anthropic-errors.js","sourceRoot":"","sources":["../../src/anthropic/anthropic-errors.ts"],"names":[],"mappings":";AAAA,gFAAgF;AAChF,yDAAyD;AACzD,gFAAgF;AAChF,EAAE;AACF,0EAA0E;AAC1E,6EAA6E;AAC7E,8EAA8E;AAC9E,8EAA8E;AAC9E,8DAA8D;AAC9D,EAAE;AACF,4EAA4E;AAC5E,0EAA0E;AAC1E,0EAA0E;AAC1E,0EAA0E;AAC1E,mEAAmE;AACnE,EAAE;AACF,oDAAoD;AACpD,EAAE;AACF,oDAAoD;AACpD,sFAAsF;AACtF,+FAA+F;AAC/F,uGAAuG;AACvG,yEAAyE;AACzE,6FAA6F;AAC7F,wDAAwD;AACxD,4FAA4F;AAC5F,gFAAgF;AAChF,EAAE;AACF,+EAA+E;AAC/E,gFAAgF;AAChF,kBAAkB;AAClB,gFAAgF;;;AA2ChF,sDAEC;AAOD,gEAiBC;AAOD,kDAEC;AAOD,gDA2BC;AAYD,8CA0BC;AApJD,2CAM2B;AAE3B,yCAAqD;AACrD,yCAAkD;AAElD;;;;GAIG;AACU,QAAA,qBAAqB,GAAG,WAAW,CAAC;AAEjD,MAAM,QAAQ,GAAgC;IAC5C,WAAW,EAAE,iBAAiB;IAC9B,oBAAoB,EAAE,8BAA8B;IACpD,eAAe,EAAE,8CAA8C;IAC/D,cAAc,EAAE,qCAAqC;IACrD,oBAAoB,EAAE,2BAA2B;IACjD,sBAAsB,EAAE,yDAAyD;IACjF,yBAAyB,EAAE,gEAAgE;IAC3F,gBAAgB,EAAE,uDAAuD;IACzE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AC7C,OAAO,CAAC,SAAS,GAAG,GAAG,YAAY,+BAAyB,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,YAAY,CAAC;IAC1F,CAAC;SAAM,IAAI,GAAG,YAAY,cAAQ,EAAE,CAAC;QACnC,IAAI,OAAO,GAAG,CAAC,MAAM,KAAK,QAAQ;YAAE,OAAO,CAAC,MAAM,GAAG,GAAG,CAAC,MAAM,CAAC;QAEhE,MAAM,YAAY,GAAG,iBAAiB,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;QACjD,MAAM,iBAAiB,GAAG,iBAAiB,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC;QAE3D,IAAI,YAAY;YAAE,OAAO,CAAC,YAAY,GAAG,YAAY,CAAC;QACtD,IAAI,iBAAiB;YAAE,OAAO,CAAC,iBAAiB,GAAG,iBAAiB,CAAC;QAErE,IAAI,IAAI,KAAK,iBAAiB,IAAI,IAAI,KAAK,yBAAyB,EAAE,CAAC;YACrE,YAAY,GAAG,mBAAmB,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;QAClD,CAAC;IACH,CAAC;IAED,OAAO,IAAI,eAAO,CAAC,IAAI,EAAE,qBAAqB,CAAC,IAAI,CAAC,EAAE,EAAE,KAAK,EAAE,GAAG,EAAE,OAAO,EAAE,YAAY,EAAE,CAAC,CAAC;AAC/F,CAAC"}
@@ -0,0 +1,149 @@
1
+ import type { ContentBlock, Message, MessageCreateParamsBase, RedactedThinkingBlockParam, StopReason, ThinkingBlockParam, Usage } from '@anthropic-ai/sdk/resources/messages/messages';
2
+ import type { AiStorageInputModality } from '../core/index';
3
+ import { type AiOutputItem, type AiReasoningItem, type AiResponse, type AiResponseRequest, type AiUsage } from '../core/index';
4
+ import { type AnthropicModelProfile } from './anthropic-model-catalog';
5
+ /**
6
+ * The request body minus `stream`, which the port sets.
7
+ *
8
+ * @stability experimental
9
+ */
10
+ export type AnthropicRequestBody = Omit<MessageCreateParamsBase, 'stream'>;
11
+ /**
12
+ * The signed / encrypted thinking blocks a reasoning item replays.
13
+ *
14
+ * @stability experimental
15
+ */
16
+ export type AnthropicThinkingBlock = ThinkingBlockParam | RedactedThinkingBlockParam;
17
+ /**
18
+ * What `AI_PROVIDER_STATE.data` holds for an Anthropic reasoning item.
19
+ *
20
+ * @stability experimental
21
+ */
22
+ export interface AnthropicReasoningState {
23
+ /** The thinking blocks to replay, in order. */
24
+ blocks: AnthropicThinkingBlock[];
25
+ }
26
+ /**
27
+ * How one storage-object input reached Anthropic (#441): a presigned URL
28
+ * Anthropic fetches (images), or the bytes inline (documents). ⚠ `url` may be
29
+ * presigned — it goes into the request body and nowhere else.
30
+ *
31
+ * @stability experimental
32
+ */
33
+ export interface AnthropicStorageDelivery {
34
+ /** Whether the object is an image or a document. */
35
+ modality: AiStorageInputModality;
36
+ /** The object's MIME type. */
37
+ mimeType: string;
38
+ /** The object's file name. */
39
+ filename: string;
40
+ /** A presigned URL the provider fetches, for delivery by URL. */
41
+ url?: string;
42
+ /** The object's bytes, for inline delivery. */
43
+ data?: Uint8Array;
44
+ }
45
+ /**
46
+ * Deliveries keyed by storage object id.
47
+ *
48
+ * @stability experimental
49
+ */
50
+ export type AnthropicStorageDeliveries = ReadonlyMap<string, AnthropicStorageDelivery>;
51
+ /**
52
+ * What the request mapper decided that the response mapper must know: the
53
+ * name of the forced structured-output tool, when that path was taken.
54
+ *
55
+ * @stability experimental
56
+ */
57
+ export interface AnthropicRequestPlan {
58
+ /** The Messages API request body. */
59
+ body: AnthropicRequestBody;
60
+ /** The forced tool that carries structured output, when the model has no native structured output. */
61
+ structuredToolName?: string;
62
+ }
63
+ /**
64
+ * Every storage object id `req` names, in order, each once.
65
+ *
66
+ * @stability experimental
67
+ */
68
+ export declare function anthropicStorageObjectIds(req: AiResponseRequest): string[];
69
+ /**
70
+ * The thinking blocks an Anthropic reasoning item carries, or `[]`.
71
+ *
72
+ * @stability experimental
73
+ */
74
+ export declare function anthropicReasoningBlocks(item: AiReasoningItem): AnthropicThinkingBlock[];
75
+ /**
76
+ * Builds the Anthropic request body for `req`.
77
+ *
78
+ * `profile` is the model's classifier profile (or `null` when unclassified);
79
+ * `storage` is what the adapter delivered for each storage-object part.
80
+ * Throws `AiError` (never an SDK error): see the file header.
81
+ *
82
+ * @stability experimental
83
+ */
84
+ export declare function toAnthropicRequest(req: AiResponseRequest, profile: AnthropicModelProfile | null, storage?: AnthropicStorageDeliveries): AnthropicRequestPlan;
85
+ /**
86
+ * A reasoning item for replayable thinking blocks: summary text out, signature in the symbol state.
87
+ *
88
+ * @stability experimental
89
+ */
90
+ export declare function anthropicReasoningItem(block: AnthropicThinkingBlock): AiReasoningItem;
91
+ /**
92
+ * Maps one content block. `null` for a block type this contract does not
93
+ * model (server-tool blocks, which this adapter never requests).
94
+ *
95
+ * @stability experimental
96
+ */
97
+ export declare function fromAnthropicContentBlock(block: ContentBlock, structuredTool?: string): AiOutputItem | null;
98
+ /**
99
+ * Usage, normalised: `inputTokens` includes cached tokens, as OpenAI's does.
100
+ *
101
+ * @stability experimental
102
+ */
103
+ export declare function anthropicUsage(usage: Partial<Pick<Usage, 'input_tokens' | 'output_tokens' | 'cache_read_input_tokens' | 'cache_creation_input_tokens' | 'output_tokens_details'>> | null | undefined): AiUsage;
104
+ /**
105
+ * What {@link fromAnthropicMessage} needs besides the SDK message.
106
+ *
107
+ * @stability experimental
108
+ */
109
+ export interface FromAnthropicOptions {
110
+ /** The originating request; its `structuredOutput` drives `parsed`. */
111
+ request: AiResponseRequest;
112
+ /** The `request-id` Anthropic answered with. */
113
+ providerRequestId?: string | null;
114
+ }
115
+ /**
116
+ * The parts of an Anthropic answer, mapped to the neutral shape, from which a response is assembled.
117
+ *
118
+ * @stability experimental
119
+ */
120
+ export interface AnthropicResponseParts {
121
+ /** The provider's message id. */
122
+ id: string;
123
+ /** The model that answered. */
124
+ model: string;
125
+ /** The neutral output items. */
126
+ output: AiOutputItem[];
127
+ /** Why the model stopped, as Anthropic reported it. */
128
+ stopReason: StopReason | null | undefined;
129
+ /** Token usage. */
130
+ usage: AiUsage;
131
+ }
132
+ /**
133
+ * The `AiResponse` for mapped parts — shared by `create` and the stream. When
134
+ * the request asked for structured output and the model finished its turn,
135
+ * the text is validated with `parseStructured` (a mismatch throws
136
+ * `AI_STRUCTURED_OUTPUT_INVALID`).
137
+ *
138
+ * @stability experimental
139
+ */
140
+ export declare function finishAnthropicResponse(parts: AnthropicResponseParts, opts: FromAnthropicOptions): AiResponse;
141
+ /**
142
+ * Maps a finished SDK `Message` to an `AiResponse`.
143
+ *
144
+ * @stability experimental
145
+ */
146
+ export declare function fromAnthropicMessage(message: Message, opts: FromAnthropicOptions & {
147
+ structuredToolName?: string;
148
+ }): AiResponse;
149
+ //# sourceMappingURL=anthropic-messages.mapper.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"anthropic-messages.mapper.d.ts","sourceRoot":"","sources":["../../src/anthropic/anthropic-messages.mapper.ts"],"names":[],"mappings":"AA8DA,OAAO,KAAK,EACV,YAAY,EAIZ,OAAO,EACP,uBAAuB,EAEvB,0BAA0B,EAC1B,UAAU,EAEV,kBAAkB,EAGlB,KAAK,EACN,MAAM,+CAA+C,CAAC;AAGvD,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,eAAe,CAAC;AAE5D,OAAO,EAKL,KAAK,YAAY,EAEjB,KAAK,eAAe,EACpB,KAAK,UAAU,EACf,KAAK,iBAAiB,EAGtB,KAAK,OAAO,EACb,MAAM,eAAe,CAAC;AAEvB,OAAO,EAKL,KAAK,qBAAqB,EAC3B,MAAM,2BAA2B,CAAC;AAEnC;;;;GAIG;AACH,MAAM,MAAM,oBAAoB,GAAG,IAAI,CAAC,uBAAuB,EAAE,QAAQ,CAAC,CAAC;AAE3E;;;;GAIG;AACH,MAAM,MAAM,sBAAsB,GAAG,kBAAkB,GAAG,0BAA0B,CAAC;AAErF;;;;GAIG;AACH,MAAM,WAAW,uBAAuB;IACtC,+CAA+C;IAC/C,MAAM,EAAE,s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