@clinebot/llms 0.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (219) hide show
  1. package/README.md +198 -0
  2. package/dist/config-browser.d.ts +3 -0
  3. package/dist/config.d.ts +3 -0
  4. package/dist/index.browser.d.ts +4 -0
  5. package/dist/index.browser.js +1 -0
  6. package/dist/index.d.ts +5 -0
  7. package/dist/index.js +7 -0
  8. package/dist/models/generated-access.d.ts +4 -0
  9. package/dist/models/generated-provider-loaders.d.ts +13 -0
  10. package/dist/models/generated.d.ts +14 -0
  11. package/dist/models/index.d.ts +43 -0
  12. package/dist/models/models-dev-catalog.d.ts +32 -0
  13. package/dist/models/providers/aihubmix.d.ts +5 -0
  14. package/dist/models/providers/anthropic.d.ts +53 -0
  15. package/dist/models/providers/asksage.d.ts +5 -0
  16. package/dist/models/providers/baseten.d.ts +5 -0
  17. package/dist/models/providers/bedrock.d.ts +7 -0
  18. package/dist/models/providers/cerebras.d.ts +7 -0
  19. package/dist/models/providers/claude-code.d.ts +4 -0
  20. package/dist/models/providers/cline.d.ts +34 -0
  21. package/dist/models/providers/deepseek.d.ts +8 -0
  22. package/dist/models/providers/dify.d.ts +5 -0
  23. package/dist/models/providers/doubao.d.ts +7 -0
  24. package/dist/models/providers/fireworks.d.ts +8 -0
  25. package/dist/models/providers/gemini.d.ts +9 -0
  26. package/dist/models/providers/groq.d.ts +8 -0
  27. package/dist/models/providers/hicap.d.ts +5 -0
  28. package/dist/models/providers/huawei-cloud-maas.d.ts +5 -0
  29. package/dist/models/providers/huggingface.d.ts +6 -0
  30. package/dist/models/providers/index.d.ts +45 -0
  31. package/dist/models/providers/litellm.d.ts +5 -0
  32. package/dist/models/providers/lmstudio.d.ts +5 -0
  33. package/dist/models/providers/minimax.d.ts +7 -0
  34. package/dist/models/providers/mistral.d.ts +5 -0
  35. package/dist/models/providers/moonshot.d.ts +7 -0
  36. package/dist/models/providers/nebius.d.ts +7 -0
  37. package/dist/models/providers/nous-research.d.ts +7 -0
  38. package/dist/models/providers/oca.d.ts +9 -0
  39. package/dist/models/providers/ollama.d.ts +5 -0
  40. package/dist/models/providers/openai-codex.d.ts +10 -0
  41. package/dist/models/providers/openai.d.ts +9 -0
  42. package/dist/models/providers/opencode.d.ts +10 -0
  43. package/dist/models/providers/openrouter.d.ts +7 -0
  44. package/dist/models/providers/qwen-code.d.ts +7 -0
  45. package/dist/models/providers/qwen.d.ts +7 -0
  46. package/dist/models/providers/requesty.d.ts +6 -0
  47. package/dist/models/providers/sambanova.d.ts +7 -0
  48. package/dist/models/providers/sapaicore.d.ts +7 -0
  49. package/dist/models/providers/together.d.ts +8 -0
  50. package/dist/models/providers/vercel-ai-gateway.d.ts +5 -0
  51. package/dist/models/providers/vertex.d.ts +7 -0
  52. package/dist/models/providers/xai.d.ts +8 -0
  53. package/dist/models/providers/zai.d.ts +7 -0
  54. package/dist/models/query.d.ts +181 -0
  55. package/dist/models/registry.d.ts +123 -0
  56. package/dist/models/schemas/index.d.ts +7 -0
  57. package/dist/models/schemas/model.d.ts +340 -0
  58. package/dist/models/schemas/query.d.ts +191 -0
  59. package/dist/providers/handlers/ai-sdk-community.d.ts +46 -0
  60. package/dist/providers/handlers/ai-sdk-provider-base.d.ts +32 -0
  61. package/dist/providers/handlers/anthropic-base.d.ts +26 -0
  62. package/dist/providers/handlers/asksage.d.ts +12 -0
  63. package/dist/providers/handlers/auth.d.ts +5 -0
  64. package/dist/providers/handlers/base.d.ts +55 -0
  65. package/dist/providers/handlers/bedrock-base.d.ts +23 -0
  66. package/dist/providers/handlers/bedrock-client.d.ts +4 -0
  67. package/dist/providers/handlers/community-sdk.d.ts +97 -0
  68. package/dist/providers/handlers/fetch-base.d.ts +18 -0
  69. package/dist/providers/handlers/gemini-base.d.ts +25 -0
  70. package/dist/providers/handlers/index.d.ts +19 -0
  71. package/dist/providers/handlers/openai-base.d.ts +54 -0
  72. package/dist/providers/handlers/openai-responses.d.ts +64 -0
  73. package/dist/providers/handlers/providers.d.ts +43 -0
  74. package/dist/providers/handlers/r1-base.d.ts +62 -0
  75. package/dist/providers/handlers/registry.d.ts +106 -0
  76. package/dist/providers/handlers/vertex.d.ts +32 -0
  77. package/dist/providers/index.d.ts +100 -0
  78. package/dist/providers/public.browser.d.ts +2 -0
  79. package/dist/providers/public.d.ts +3 -0
  80. package/dist/providers/shared/openai-compatible.d.ts +10 -0
  81. package/dist/providers/transform/ai-sdk-community-format.d.ts +9 -0
  82. package/dist/providers/transform/anthropic-format.d.ts +24 -0
  83. package/dist/providers/transform/content-format.d.ts +3 -0
  84. package/dist/providers/transform/gemini-format.d.ts +19 -0
  85. package/dist/providers/transform/index.d.ts +10 -0
  86. package/dist/providers/transform/openai-format.d.ts +36 -0
  87. package/dist/providers/transform/r1-format.d.ts +26 -0
  88. package/dist/providers/types/config.d.ts +261 -0
  89. package/dist/providers/types/handler.d.ts +71 -0
  90. package/dist/providers/types/index.d.ts +11 -0
  91. package/dist/providers/types/messages.d.ts +139 -0
  92. package/dist/providers/types/model-info.d.ts +32 -0
  93. package/dist/providers/types/provider-ids.d.ts +63 -0
  94. package/dist/providers/types/settings.d.ts +308 -0
  95. package/dist/providers/types/stream.d.ts +106 -0
  96. package/dist/providers/utils/index.d.ts +7 -0
  97. package/dist/providers/utils/retry.d.ts +38 -0
  98. package/dist/providers/utils/stream-processor.d.ts +110 -0
  99. package/dist/providers/utils/tool-processor.d.ts +34 -0
  100. package/dist/sdk.d.ts +18 -0
  101. package/dist/types.d.ts +60 -0
  102. package/package.json +66 -0
  103. package/src/catalog.ts +20 -0
  104. package/src/config-browser.ts +11 -0
  105. package/src/config.ts +49 -0
  106. package/src/index.browser.ts +9 -0
  107. package/src/index.ts +10 -0
  108. package/src/live-providers.test.ts +137 -0
  109. package/src/models/generated-access.ts +41 -0
  110. package/src/models/generated-provider-loaders.ts +166 -0
  111. package/src/models/generated.ts +11997 -0
  112. package/src/models/index.ts +271 -0
  113. package/src/models/models-dev-catalog.test.ts +161 -0
  114. package/src/models/models-dev-catalog.ts +161 -0
  115. package/src/models/providers/aihubmix.ts +19 -0
  116. package/src/models/providers/anthropic.ts +60 -0
  117. package/src/models/providers/asksage.ts +19 -0
  118. package/src/models/providers/baseten.ts +21 -0
  119. package/src/models/providers/bedrock.ts +30 -0
  120. package/src/models/providers/cerebras.ts +24 -0
  121. package/src/models/providers/claude-code.ts +51 -0
  122. package/src/models/providers/cline.ts +25 -0
  123. package/src/models/providers/deepseek.ts +33 -0
  124. package/src/models/providers/dify.ts +17 -0
  125. package/src/models/providers/doubao.ts +33 -0
  126. package/src/models/providers/fireworks.ts +34 -0
  127. package/src/models/providers/gemini.ts +43 -0
  128. package/src/models/providers/groq.ts +33 -0
  129. package/src/models/providers/hicap.ts +18 -0
  130. package/src/models/providers/huawei-cloud-maas.ts +18 -0
  131. package/src/models/providers/huggingface.ts +22 -0
  132. package/src/models/providers/index.ts +162 -0
  133. package/src/models/providers/litellm.ts +19 -0
  134. package/src/models/providers/lmstudio.ts +22 -0
  135. package/src/models/providers/minimax.ts +34 -0
  136. package/src/models/providers/mistral.ts +19 -0
  137. package/src/models/providers/moonshot.ts +34 -0
  138. package/src/models/providers/nebius.ts +24 -0
  139. package/src/models/providers/nous-research.ts +21 -0
  140. package/src/models/providers/oca.ts +30 -0
  141. package/src/models/providers/ollama.ts +18 -0
  142. package/src/models/providers/openai-codex.ts +30 -0
  143. package/src/models/providers/openai.ts +43 -0
  144. package/src/models/providers/opencode.ts +28 -0
  145. package/src/models/providers/openrouter.ts +24 -0
  146. package/src/models/providers/qwen-code.ts +33 -0
  147. package/src/models/providers/qwen.ts +34 -0
  148. package/src/models/providers/requesty.ts +23 -0
  149. package/src/models/providers/sambanova.ts +23 -0
  150. package/src/models/providers/sapaicore.ts +34 -0
  151. package/src/models/providers/together.ts +35 -0
  152. package/src/models/providers/vercel-ai-gateway.ts +23 -0
  153. package/src/models/providers/vertex.ts +36 -0
  154. package/src/models/providers/xai.ts +34 -0
  155. package/src/models/providers/zai.ts +25 -0
  156. package/src/models/query.ts +407 -0
  157. package/src/models/registry.ts +511 -0
  158. package/src/models/schemas/index.ts +62 -0
  159. package/src/models/schemas/model.ts +308 -0
  160. package/src/models/schemas/query.ts +336 -0
  161. package/src/providers/browser.ts +4 -0
  162. package/src/providers/handlers/ai-sdk-community.ts +226 -0
  163. package/src/providers/handlers/ai-sdk-provider-base.ts +193 -0
  164. package/src/providers/handlers/anthropic-base.ts +372 -0
  165. package/src/providers/handlers/asksage.test.ts +103 -0
  166. package/src/providers/handlers/asksage.ts +138 -0
  167. package/src/providers/handlers/auth.test.ts +19 -0
  168. package/src/providers/handlers/auth.ts +121 -0
  169. package/src/providers/handlers/base.test.ts +46 -0
  170. package/src/providers/handlers/base.ts +160 -0
  171. package/src/providers/handlers/bedrock-base.ts +390 -0
  172. package/src/providers/handlers/bedrock-client.ts +100 -0
  173. package/src/providers/handlers/codex.test.ts +123 -0
  174. package/src/providers/handlers/community-sdk.test.ts +288 -0
  175. package/src/providers/handlers/community-sdk.ts +392 -0
  176. package/src/providers/handlers/fetch-base.ts +68 -0
  177. package/src/providers/handlers/gemini-base.ts +302 -0
  178. package/src/providers/handlers/index.ts +67 -0
  179. package/src/providers/handlers/openai-base.ts +277 -0
  180. package/src/providers/handlers/openai-responses.ts +598 -0
  181. package/src/providers/handlers/providers.test.ts +120 -0
  182. package/src/providers/handlers/providers.ts +563 -0
  183. package/src/providers/handlers/r1-base.ts +280 -0
  184. package/src/providers/handlers/registry.ts +185 -0
  185. package/src/providers/handlers/vertex.test.ts +124 -0
  186. package/src/providers/handlers/vertex.ts +292 -0
  187. package/src/providers/index.ts +534 -0
  188. package/src/providers/public.browser.ts +20 -0
  189. package/src/providers/public.ts +51 -0
  190. package/src/providers/shared/openai-compatible.ts +63 -0
  191. package/src/providers/transform/ai-sdk-community-format.test.ts +73 -0
  192. package/src/providers/transform/ai-sdk-community-format.ts +115 -0
  193. package/src/providers/transform/anthropic-format.ts +218 -0
  194. package/src/providers/transform/content-format.ts +34 -0
  195. package/src/providers/transform/format-conversion.test.ts +310 -0
  196. package/src/providers/transform/gemini-format.ts +167 -0
  197. package/src/providers/transform/index.ts +22 -0
  198. package/src/providers/transform/openai-format.ts +247 -0
  199. package/src/providers/transform/r1-format.ts +287 -0
  200. package/src/providers/types/config.ts +388 -0
  201. package/src/providers/types/handler.ts +87 -0
  202. package/src/providers/types/index.ts +120 -0
  203. package/src/providers/types/messages.ts +158 -0
  204. package/src/providers/types/model-info.test.ts +57 -0
  205. package/src/providers/types/model-info.ts +65 -0
  206. package/src/providers/types/provider-ids.test.ts +12 -0
  207. package/src/providers/types/provider-ids.ts +89 -0
  208. package/src/providers/types/settings.test.ts +49 -0
  209. package/src/providers/types/settings.ts +533 -0
  210. package/src/providers/types/stream.ts +117 -0
  211. package/src/providers/utils/index.ts +27 -0
  212. package/src/providers/utils/retry.test.ts +140 -0
  213. package/src/providers/utils/retry.ts +188 -0
  214. package/src/providers/utils/stream-processor.test.ts +232 -0
  215. package/src/providers/utils/stream-processor.ts +472 -0
  216. package/src/providers/utils/tool-processor.test.ts +34 -0
  217. package/src/providers/utils/tool-processor.ts +111 -0
  218. package/src/sdk.ts +264 -0
  219. package/src/types.ts +79 -0
@@ -0,0 +1,533 @@
1
+ /**
2
+ * Settings Schema
3
+ *
4
+ * User-friendly settings interface with Zod validation.
5
+ * Converts to internal ProviderConfig for handler creation.
6
+ */
7
+
8
+ import { resolveProviderModelCatalogKeys } from "@clinebot/shared";
9
+ import { z } from "zod";
10
+ import { getGeneratedModelsForProvider } from "../../models/generated-access";
11
+ import {
12
+ DEFAULT_EXTERNAL_OCA_BASE_URL,
13
+ DEFAULT_INTERNAL_OCA_BASE_URL,
14
+ } from "../../models/providers/oca";
15
+ import { OPENAI_COMPATIBLE_PROVIDERS } from "../handlers/providers";
16
+ import type { ProviderCapability, ProviderConfig, ProviderId } from "./config";
17
+ import { normalizeProviderId } from "./provider-ids";
18
+
19
+ // =============================================================================
20
+ // Provider ID Schema
21
+ // =============================================================================
22
+
23
+ /**
24
+ * All supported provider IDs as a Zod enum
25
+ */
26
+ export const ProviderIdSchema = z
27
+ .string()
28
+ .min(1)
29
+ .regex(/^[a-z0-9][a-z0-9-]*$/i);
30
+
31
+ // =============================================================================
32
+ // Authentication Schema
33
+ // =============================================================================
34
+
35
+ /**
36
+ * Authentication settings
37
+ */
38
+ export const AuthSettingsSchema = z.object({
39
+ /** API key (most common) */
40
+ apiKey: z.string().optional(),
41
+ /** OAuth access token */
42
+ accessToken: z.string().optional(),
43
+ /** OAuth refresh token */
44
+ refreshToken: z.string().optional(),
45
+ /** OAuth access token expiry (unix epoch ms) */
46
+ expiresAt: z.number().int().positive().optional(),
47
+ /** Account ID (for account-based auth) */
48
+ accountId: z.string().optional(),
49
+ });
50
+
51
+ export type AuthSettings = z.infer<typeof AuthSettingsSchema>;
52
+
53
+ // =============================================================================
54
+ // Reasoning/Thinking Schema
55
+ // =============================================================================
56
+
57
+ /**
58
+ * Reasoning/thinking configuration
59
+ */
60
+ const ReasoningLevelSchema = z.enum(["none", "low", "medium", "high"]);
61
+
62
+ export const ReasoningSettingsSchema = z.object({
63
+ /** Enable thinking with provider/model defaults when supported */
64
+ enabled: z.boolean().optional(),
65
+ /** Unified reasoning/thinking level */
66
+ effort: ReasoningLevelSchema.optional(),
67
+ /** Extended thinking budget in tokens */
68
+ budgetTokens: z.number().int().positive().optional(),
69
+ });
70
+
71
+ export type ReasoningSettings = z.infer<typeof ReasoningSettingsSchema>;
72
+
73
+ // =============================================================================
74
+ // AWS/Bedrock Schema
75
+ // =============================================================================
76
+
77
+ /**
78
+ * AWS Bedrock configuration
79
+ */
80
+ export const AwsSettingsSchema = z.object({
81
+ accessKey: z.string().optional(),
82
+ secretKey: z.string().optional(),
83
+ sessionToken: z.string().optional(),
84
+ region: z.string().optional(),
85
+ profile: z.string().optional(),
86
+ authentication: z.enum(["iam", "api-key", "profile"]).optional(),
87
+ usePromptCache: z.boolean().optional(),
88
+ useCrossRegionInference: z.boolean().optional(),
89
+ useGlobalInference: z.boolean().optional(),
90
+ endpoint: z.string().url().optional(),
91
+ customModelBaseId: z.string().optional(),
92
+ });
93
+
94
+ export type AwsSettings = z.infer<typeof AwsSettingsSchema>;
95
+
96
+ // =============================================================================
97
+ // GCP/Vertex Schema
98
+ // =============================================================================
99
+
100
+ /**
101
+ * Google Cloud Vertex AI configuration
102
+ */
103
+ export const GcpSettingsSchema = z.object({
104
+ projectId: z.string().optional(),
105
+ region: z.string().optional(),
106
+ });
107
+
108
+ export type GcpSettings = z.infer<typeof GcpSettingsSchema>;
109
+
110
+ // =============================================================================
111
+ // Azure Schema
112
+ // =============================================================================
113
+
114
+ /**
115
+ * Azure OpenAI configuration
116
+ */
117
+ export const AzureSettingsSchema = z.object({
118
+ apiVersion: z.string().optional(),
119
+ useIdentity: z.boolean().optional(),
120
+ });
121
+
122
+ export type AzureSettings = z.infer<typeof AzureSettingsSchema>;
123
+
124
+ // =============================================================================
125
+ // SAP AI Core Schema
126
+ // =============================================================================
127
+
128
+ /**
129
+ * SAP AI Core configuration
130
+ */
131
+ export const SapSettingsSchema = z.object({
132
+ clientId: z.string().optional(),
133
+ clientSecret: z.string().optional(),
134
+ tokenUrl: z.string().url().optional(),
135
+ resourceGroup: z.string().optional(),
136
+ deploymentId: z.string().optional(),
137
+ useOrchestrationMode: z.boolean().optional(),
138
+ api: z.enum(["orchestration", "foundation-models"]).optional(),
139
+ defaultSettings: z.record(z.string(), z.unknown()).optional(),
140
+ });
141
+
142
+ export type SapSettings = z.infer<typeof SapSettingsSchema>;
143
+
144
+ // =============================================================================
145
+ // OCA Schema
146
+ // =============================================================================
147
+
148
+ /**
149
+ * Oracle Cloud AI configuration
150
+ */
151
+ export const OcaSettingsSchema = z.object({
152
+ mode: z.enum(["internal", "external"]).optional(),
153
+ usePromptCache: z.boolean().optional(),
154
+ });
155
+
156
+ export type OcaSettings = z.infer<typeof OcaSettingsSchema>;
157
+
158
+ // =============================================================================
159
+ // Model Catalog Schema
160
+ // =============================================================================
161
+
162
+ /**
163
+ * Runtime model catalog refresh configuration
164
+ */
165
+ export const ModelCatalogSettingsSchema = z.object({
166
+ /** Fetch latest catalog at handler initialization */
167
+ loadLatestOnInit: z.boolean().optional(),
168
+ /** Fetch provider-private models when auth is available */
169
+ loadPrivateOnAuth: z.boolean().optional(),
170
+ /** Catalog endpoint URL */
171
+ url: z.string().url().optional(),
172
+ /** Cache TTL for live catalog in milliseconds */
173
+ cacheTtlMs: z.number().int().positive().optional(),
174
+ /** Throw when live catalog refresh fails */
175
+ failOnError: z.boolean().optional(),
176
+ });
177
+
178
+ export type ModelCatalogSettings = z.infer<typeof ModelCatalogSettingsSchema>;
179
+
180
+ // =============================================================================
181
+ // Main Settings Schema
182
+ // =============================================================================
183
+
184
+ /**
185
+ * Main provider settings schema
186
+ *
187
+ * This is the user-friendly interface for configuring providers.
188
+ * Use `parseSettings()` or `toProviderConfig()` to convert to ProviderConfig.
189
+ */
190
+ export const ProviderSettingsSchema = z.object({
191
+ // =========================================================================
192
+ // Required
193
+ // =========================================================================
194
+
195
+ /** Provider ID - determines which handler to use */
196
+ provider: ProviderIdSchema,
197
+
198
+ // =========================================================================
199
+ // Authentication (can use shorthand or detailed)
200
+ // =========================================================================
201
+
202
+ /** API key (shorthand for auth.apiKey) */
203
+ apiKey: z.string().optional(),
204
+
205
+ /** Detailed authentication settings */
206
+ auth: AuthSettingsSchema.optional(),
207
+
208
+ // =========================================================================
209
+ // Model Configuration
210
+ // =========================================================================
211
+
212
+ /** Model identifier (uses provider default if not specified) */
213
+ model: z.string().optional(),
214
+
215
+ /** Maximum output tokens (overrides model default) */
216
+ maxTokens: z.number().int().positive().optional(),
217
+
218
+ /** Maximum context window tokens (overrides model default) */
219
+ contextWindow: z.number().int().positive().optional(),
220
+
221
+ // =========================================================================
222
+ // Endpoint Configuration
223
+ // =========================================================================
224
+
225
+ /** Base URL for the API (uses provider default if not specified) */
226
+ baseUrl: z.string().url().optional(),
227
+
228
+ /** Custom headers to include in requests */
229
+ headers: z.record(z.string(), z.string()).optional(),
230
+
231
+ /** Request timeout in milliseconds */
232
+ timeout: z.number().int().positive().optional(),
233
+
234
+ // =========================================================================
235
+ // Reasoning/Thinking Configuration
236
+ // =========================================================================
237
+
238
+ /** Reasoning/thinking settings */
239
+ reasoning: ReasoningSettingsSchema.optional(),
240
+
241
+ // =========================================================================
242
+ // Cloud Provider Configuration
243
+ // =========================================================================
244
+
245
+ /** AWS/Bedrock configuration */
246
+ aws: AwsSettingsSchema.optional(),
247
+
248
+ /** Google Cloud/Vertex configuration */
249
+ gcp: GcpSettingsSchema.optional(),
250
+
251
+ /** Azure OpenAI configuration */
252
+ azure: AzureSettingsSchema.optional(),
253
+
254
+ /** SAP AI Core configuration */
255
+ sap: SapSettingsSchema.optional(),
256
+
257
+ /** Oracle Cloud AI configuration */
258
+ oca: OcaSettingsSchema.optional(),
259
+
260
+ // =========================================================================
261
+ // Region Configuration
262
+ // =========================================================================
263
+
264
+ /** Cloud region */
265
+ region: z.string().optional(),
266
+
267
+ /** API line for region-specific routing (e.g., Qwen) */
268
+ apiLine: z.enum(["china", "international"]).optional(),
269
+
270
+ // =========================================================================
271
+ // Capabilities
272
+ // =========================================================================
273
+
274
+ /** Explicit capabilities (usually auto-detected from provider) */
275
+ capabilities: z
276
+ .array(
277
+ z.enum([
278
+ "reasoning",
279
+ "prompt-cache",
280
+ "streaming",
281
+ "tools",
282
+ "vision",
283
+ "computer-use",
284
+ "oauth",
285
+ ]),
286
+ )
287
+ .optional(),
288
+
289
+ /** Runtime model catalog refresh settings */
290
+ modelCatalog: ModelCatalogSettingsSchema.optional(),
291
+ });
292
+
293
+ export type ProviderSettings = z.infer<typeof ProviderSettingsSchema>;
294
+
295
+ // =============================================================================
296
+ // Validation and Conversion Functions
297
+ // =============================================================================
298
+
299
+ /**
300
+ * Parse and validate settings
301
+ *
302
+ * @param input - Raw settings input (unknown type)
303
+ * @returns Validated ProviderSettings
304
+ * @throws ZodError if validation fails
305
+ *
306
+ * @example
307
+ * ```typescript
308
+ * const settings = parseSettings({
309
+ * provider: "anthropic",
310
+ * apiKey: "sk-...",
311
+ * model: "claude-sonnet-4-20250514",
312
+ * })
313
+ * ```
314
+ */
315
+ export function parseSettings(input: unknown): ProviderSettings {
316
+ return ProviderSettingsSchema.parse(input);
317
+ }
318
+
319
+ /**
320
+ * Safely parse settings without throwing
321
+ *
322
+ * @param input - Raw settings input (unknown type)
323
+ * @returns SafeParseResult with success/error info
324
+ *
325
+ * @example
326
+ * ```typescript
327
+ * const result = safeParseSettings({ provider: "anthropic" })
328
+ * if (result.success) {
329
+ * console.log(result.data)
330
+ * } else {
331
+ * console.error(result.error.issues)
332
+ * }
333
+ * ```
334
+ */
335
+ export function safeParseSettings(
336
+ input: unknown,
337
+ ): ReturnType<typeof ProviderSettingsSchema.safeParse> {
338
+ return ProviderSettingsSchema.safeParse(input);
339
+ }
340
+
341
+ /**
342
+ * Convert validated settings to ProviderConfig
343
+ *
344
+ * This function takes validated ProviderSettings and converts them
345
+ * to the internal ProviderConfig format used by handlers.
346
+ *
347
+ * @param settings - Validated provider settings
348
+ * @returns ProviderConfig ready for handler creation
349
+ *
350
+ * @example
351
+ * ```typescript
352
+ * const settings = parseSettings({ provider: "openai", apiKey: "sk-..." })
353
+ * const config = toProviderConfig(settings)
354
+ * const handler = createHandler(config)
355
+ * ```
356
+ */
357
+ export function toProviderConfig(settings: ProviderSettings): ProviderConfig {
358
+ const providerId = settings.provider as ProviderId;
359
+ const normalizedProviderId = normalizeProviderId(providerId);
360
+ const unifiedReasoningLevel = settings.reasoning?.effort;
361
+ const reasoningEffort =
362
+ unifiedReasoningLevel && unifiedReasoningLevel !== "none"
363
+ ? unifiedReasoningLevel
364
+ : undefined;
365
+
366
+ // Get provider defaults if available
367
+ const providerDefaults = OPENAI_COMPATIBLE_PROVIDERS[normalizedProviderId];
368
+ const generatedKnownModels = Object.assign(
369
+ {},
370
+ ...resolveProviderModelCatalogKeys(normalizedProviderId).map((catalogKey) =>
371
+ getGeneratedModelsForProvider(catalogKey),
372
+ ),
373
+ );
374
+
375
+ // Resolve API key: OAuth access token wins (most recent), then shorthand apiKey, then auth.apiKey
376
+ const apiKey =
377
+ settings.auth?.accessToken ?? settings.apiKey ?? settings.auth?.apiKey;
378
+ const resolvedBaseUrl =
379
+ settings.baseUrl ??
380
+ (normalizedProviderId === "oca"
381
+ ? settings.oca?.mode === "internal"
382
+ ? DEFAULT_INTERNAL_OCA_BASE_URL
383
+ : DEFAULT_EXTERNAL_OCA_BASE_URL
384
+ : providerDefaults?.baseUrl);
385
+
386
+ // Build the config
387
+ const config: ProviderConfig = {
388
+ // Provider identification
389
+ providerId,
390
+
391
+ // Model configuration
392
+ modelId: settings.model ?? providerDefaults?.modelId ?? "default",
393
+ knownModels:
394
+ providerDefaults?.knownModels ??
395
+ (Object.keys(generatedKnownModels).length > 0
396
+ ? generatedKnownModels
397
+ : undefined),
398
+
399
+ // Authentication
400
+ apiKey,
401
+ accessToken: settings.auth?.accessToken,
402
+ refreshToken: settings.auth?.refreshToken,
403
+ accountId: settings.auth?.accountId,
404
+
405
+ // Endpoint configuration
406
+ baseUrl: resolvedBaseUrl,
407
+ headers: settings.headers,
408
+ timeoutMs: settings.timeout,
409
+
410
+ // Token limits
411
+ maxOutputTokens: settings.maxTokens,
412
+ maxContextTokens: settings.contextWindow,
413
+
414
+ // Reasoning configuration
415
+ thinking: settings.reasoning?.enabled,
416
+ reasoningEffort,
417
+ thinkingBudgetTokens: settings.reasoning?.budgetTokens,
418
+
419
+ // Region configuration
420
+ region: settings.region ?? settings.aws?.region ?? settings.gcp?.region,
421
+ apiLine: settings.apiLine,
422
+ useCrossRegionInference: settings.aws?.useCrossRegionInference,
423
+ useGlobalInference: settings.aws?.useGlobalInference,
424
+
425
+ // AWS configuration
426
+ aws: settings.aws
427
+ ? {
428
+ accessKey: settings.aws.accessKey,
429
+ secretKey: settings.aws.secretKey,
430
+ sessionToken: settings.aws.sessionToken,
431
+ authentication: settings.aws.authentication,
432
+ profile: settings.aws.profile,
433
+ usePromptCache: settings.aws.usePromptCache,
434
+ endpoint: settings.aws.endpoint,
435
+ customModelBaseId: settings.aws.customModelBaseId,
436
+ }
437
+ : undefined,
438
+
439
+ // GCP configuration
440
+ gcp: settings.gcp
441
+ ? {
442
+ projectId: settings.gcp.projectId,
443
+ region: settings.gcp.region,
444
+ }
445
+ : undefined,
446
+
447
+ // Azure configuration
448
+ azure: settings.azure,
449
+
450
+ // SAP configuration
451
+ sap: settings.sap,
452
+
453
+ // OCA configuration
454
+ oca: settings.oca,
455
+
456
+ // Capabilities
457
+ capabilities: (settings.capabilities ?? providerDefaults?.capabilities) as
458
+ | ProviderCapability[]
459
+ | undefined,
460
+
461
+ // Runtime model catalog refresh
462
+ modelCatalog: settings.modelCatalog
463
+ ? {
464
+ loadLatestOnInit: settings.modelCatalog.loadLatestOnInit,
465
+ loadPrivateOnAuth: settings.modelCatalog.loadPrivateOnAuth,
466
+ url: settings.modelCatalog.url,
467
+ cacheTtlMs: settings.modelCatalog.cacheTtlMs,
468
+ failOnError: settings.modelCatalog.failOnError,
469
+ }
470
+ : undefined,
471
+ };
472
+
473
+ // Remove undefined values for cleaner config
474
+ return Object.fromEntries(
475
+ Object.entries(config).filter(([_, v]) => v !== undefined),
476
+ ) as ProviderConfig;
477
+ }
478
+
479
+ /**
480
+ * Parse settings and convert to ProviderConfig in one step
481
+ *
482
+ * This is a convenience function that combines `parseSettings()` and `toProviderConfig()`.
483
+ *
484
+ * @param input - Raw settings input (unknown type)
485
+ * @returns ProviderConfig ready for handler creation
486
+ * @throws ZodError if validation fails
487
+ *
488
+ * @example
489
+ * ```typescript
490
+ * import { createHandler, createProviderConfig } from "@clinebot/providers"
491
+ *
492
+ * const config = createProviderConfig({
493
+ * provider: "anthropic",
494
+ * apiKey: process.env.ANTHROPIC_API_KEY,
495
+ * model: "claude-sonnet-4-20250514",
496
+ * reasoning: { effort: "high" },
497
+ * })
498
+ *
499
+ * const handler = createHandler(config)
500
+ * ```
501
+ */
502
+ export function createProviderConfig(input: unknown): ProviderConfig {
503
+ const settings = parseSettings(input);
504
+ return toProviderConfig(settings);
505
+ }
506
+
507
+ /**
508
+ * Safely create ProviderConfig without throwing
509
+ *
510
+ * @param input - Raw settings input
511
+ * @returns Object with either `config` on success or `error` on failure
512
+ *
513
+ * @example
514
+ * ```typescript
515
+ * const result = safeCreateProviderConfig({ provider: "openai" })
516
+ * if (result.success) {
517
+ * const handler = createHandler(result.config)
518
+ * } else {
519
+ * console.error("Invalid settings:", result.error.issues)
520
+ * }
521
+ * ```
522
+ */
523
+ export function safeCreateProviderConfig(
524
+ input: unknown,
525
+ ):
526
+ | { success: true; config: ProviderConfig }
527
+ | { success: false; error: z.ZodError } {
528
+ const result = safeParseSettings(input);
529
+ if (result.success) {
530
+ return { success: true, config: toProviderConfig(result.data) };
531
+ }
532
+ return { success: false, error: result.error };
533
+ }
@@ -0,0 +1,117 @@
1
+ /**
2
+ * API Stream Types
3
+ *
4
+ * Unified streaming response types that all providers yield.
5
+ * This provides a consistent interface regardless of the underlying provider.
6
+ */
7
+
8
+ /**
9
+ * The main stream type - an async generator that yields chunks
10
+ */
11
+ export type ApiStream = AsyncGenerator<ApiStreamChunk> & { id?: string };
12
+
13
+ /**
14
+ * Union of all possible chunk types
15
+ */
16
+ export type ApiStreamChunk =
17
+ | ApiStreamTextChunk
18
+ | ApiStreamReasoningChunk
19
+ | ApiStreamUsageChunk
20
+ | ApiStreamToolCallsChunk
21
+ | ApiStreamDoneChunk;
22
+
23
+ /**
24
+ * Text content chunk
25
+ */
26
+ export interface ApiStreamTextChunk {
27
+ type: "text";
28
+ /** Text content generated by the model */
29
+ text: string;
30
+ /** Response ID associated with this chunk */
31
+ id: string;
32
+ /** Thought signature (used by Gemini) */
33
+ signature?: string;
34
+ }
35
+
36
+ /**
37
+ * Reasoning/thinking content chunk
38
+ */
39
+ export interface ApiStreamReasoningChunk {
40
+ type: "reasoning";
41
+ /** The reasoning text generated by the model */
42
+ reasoning: string;
43
+ /** Additional reasoning details (provider-specific) */
44
+ details?: unknown;
45
+ /** Signature for the thinking block (Anthropic, Gemini) */
46
+ signature?: string;
47
+ /** Redacted reasoning data */
48
+ redacted_data?: string;
49
+ /** Response ID associated with this chunk */
50
+ id: string;
51
+ }
52
+
53
+ /**
54
+ * Usage/token count chunk
55
+ */
56
+ export interface ApiStreamUsageChunk {
57
+ type: "usage";
58
+ /** Number of input tokens (excluding cached) */
59
+ inputTokens: number;
60
+ /** Number of output tokens */
61
+ outputTokens: number;
62
+ /** Number of tokens written to cache */
63
+ cacheWriteTokens?: number;
64
+ /** Number of tokens read from cache */
65
+ cacheReadTokens?: number;
66
+ /** Number of thinking/reasoning tokens */
67
+ thoughtsTokenCount?: number;
68
+ /** Total cost in USD (if calculable) */
69
+ totalCost?: number;
70
+ /** Response ID */
71
+ id: string;
72
+ }
73
+
74
+ /**
75
+ * Tool call chunk
76
+ */
77
+ export interface ApiStreamToolCallsChunk {
78
+ type: "tool_calls";
79
+ /** The tool call information */
80
+ tool_call: ApiStreamToolCall;
81
+ /** Response ID */
82
+ id: string;
83
+ /** Thought signature (Gemini) */
84
+ signature?: string;
85
+ }
86
+
87
+ /**
88
+ * Tool call details
89
+ */
90
+ export interface ApiStreamToolCall {
91
+ /** Call ID for this tool invocation */
92
+ call_id?: string;
93
+ /** Function/tool information */
94
+ function: {
95
+ /** Tool call ID */
96
+ id?: string;
97
+ /** Name of the tool */
98
+ name?: string;
99
+ /** Arguments passed to the tool (can be string or parsed object) */
100
+ arguments?: string | Record<string, unknown>;
101
+ };
102
+ }
103
+
104
+ /**
105
+ * Stream completion chunk - indicates the stream has finished
106
+ */
107
+ export interface ApiStreamDoneChunk {
108
+ type: "done";
109
+ /** Whether the stream completed successfully */
110
+ success: boolean;
111
+ /** Error message if the stream failed */
112
+ error?: string;
113
+ /** Reason for incomplete response (e.g., "max_output_tokens") */
114
+ incompleteReason?: string;
115
+ /** Response ID */
116
+ id: string;
117
+ }
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Utils Index
3
+ */
4
+
5
+ export type { RetryOptions } from "./retry";
6
+ export {
7
+ calculateRetryDelay,
8
+ isRetriableError,
9
+ RetriableError,
10
+ retryAsync,
11
+ retryStream,
12
+ sleep,
13
+ } from "./retry";
14
+
15
+ export {
16
+ type AssistantContentBlock,
17
+ type AssistantRedactedThinkingBlock,
18
+ type AssistantTextBlock,
19
+ type AssistantThinkingBlock,
20
+ type AssistantToolUseBlock,
21
+ type ProcessedResponse,
22
+ type ReasoningDetailParam,
23
+ StreamResponseProcessor,
24
+ type UsageInfo,
25
+ } from "./stream-processor";
26
+
27
+ export { ToolCallProcessor } from "./tool-processor";