@c9up/polaris 0.0.0-stage → 0.1.1

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 (253) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1146 -2
  3. package/dist/Polaris.d.ts +80 -0
  4. package/dist/Polaris.d.ts.map +1 -0
  5. package/dist/Polaris.js +208 -0
  6. package/dist/Polaris.js.map +1 -0
  7. package/dist/PolarisClient.d.ts +184 -0
  8. package/dist/PolarisClient.d.ts.map +1 -0
  9. package/dist/PolarisClient.js +576 -0
  10. package/dist/PolarisClient.js.map +1 -0
  11. package/dist/PolarisProvider.d.ts +40 -0
  12. package/dist/PolarisProvider.d.ts.map +1 -0
  13. package/dist/PolarisProvider.js +79 -0
  14. package/dist/PolarisProvider.js.map +1 -0
  15. package/dist/augmentations.d.ts +18 -0
  16. package/dist/augmentations.d.ts.map +1 -0
  17. package/dist/augmentations.js +9 -0
  18. package/dist/augmentations.js.map +1 -0
  19. package/dist/budget.d.ts +77 -0
  20. package/dist/budget.d.ts.map +1 -0
  21. package/dist/budget.js +134 -0
  22. package/dist/budget.js.map +1 -0
  23. package/dist/catalog/catalog.d.ts +37 -0
  24. package/dist/catalog/catalog.d.ts.map +1 -0
  25. package/dist/catalog/catalog.js +145 -0
  26. package/dist/catalog/catalog.js.map +1 -0
  27. package/dist/catalog/discover.d.ts +64 -0
  28. package/dist/catalog/discover.d.ts.map +1 -0
  29. package/dist/catalog/discover.js +148 -0
  30. package/dist/catalog/discover.js.map +1 -0
  31. package/dist/catalog/index.d.ts +8 -0
  32. package/dist/catalog/index.d.ts.map +1 -0
  33. package/dist/catalog/index.js +8 -0
  34. package/dist/catalog/index.js.map +1 -0
  35. package/dist/commands/index.d.ts +82 -0
  36. package/dist/commands/index.d.ts.map +1 -0
  37. package/dist/commands/index.js +278 -0
  38. package/dist/commands/index.js.map +1 -0
  39. package/dist/cost.d.ts +50 -0
  40. package/dist/cost.d.ts.map +1 -0
  41. package/dist/cost.js +131 -0
  42. package/dist/cost.js.map +1 -0
  43. package/dist/drivers/anthropic.d.ts +44 -0
  44. package/dist/drivers/anthropic.d.ts.map +1 -0
  45. package/dist/drivers/anthropic.js +539 -0
  46. package/dist/drivers/anthropic.js.map +1 -0
  47. package/dist/drivers/openai-compatible.d.ts +54 -0
  48. package/dist/drivers/openai-compatible.d.ts.map +1 -0
  49. package/dist/drivers/openai-compatible.js +699 -0
  50. package/dist/drivers/openai-compatible.js.map +1 -0
  51. package/dist/drivers/status.d.ts +8 -0
  52. package/dist/drivers/status.d.ts.map +1 -0
  53. package/dist/drivers/status.js +21 -0
  54. package/dist/drivers/status.js.map +1 -0
  55. package/dist/errors.d.ts +79 -0
  56. package/dist/errors.d.ts.map +1 -0
  57. package/dist/errors.js +86 -0
  58. package/dist/errors.js.map +1 -0
  59. package/dist/extract.d.ts +38 -0
  60. package/dist/extract.d.ts.map +1 -0
  61. package/dist/extract.js +144 -0
  62. package/dist/extract.js.map +1 -0
  63. package/dist/index.d.ts +21 -0
  64. package/dist/index.d.ts.map +1 -0
  65. package/dist/index.js +15 -0
  66. package/dist/index.js.map +1 -0
  67. package/dist/json-schema.d.ts +33 -0
  68. package/dist/json-schema.d.ts.map +1 -0
  69. package/dist/json-schema.js +508 -0
  70. package/dist/json-schema.js.map +1 -0
  71. package/dist/log.d.ts +47 -0
  72. package/dist/log.d.ts.map +1 -0
  73. package/dist/log.js +35 -0
  74. package/dist/log.js.map +1 -0
  75. package/dist/mcp/client.d.ts +81 -0
  76. package/dist/mcp/client.d.ts.map +1 -0
  77. package/dist/mcp/client.js +401 -0
  78. package/dist/mcp/client.js.map +1 -0
  79. package/dist/mcp/endpoint.d.ts +54 -0
  80. package/dist/mcp/endpoint.d.ts.map +1 -0
  81. package/dist/mcp/endpoint.js +158 -0
  82. package/dist/mcp/endpoint.js.map +1 -0
  83. package/dist/mcp/host.d.ts +42 -0
  84. package/dist/mcp/host.d.ts.map +1 -0
  85. package/dist/mcp/host.js +111 -0
  86. package/dist/mcp/host.js.map +1 -0
  87. package/dist/mcp/http.d.ts +32 -0
  88. package/dist/mcp/http.d.ts.map +1 -0
  89. package/dist/mcp/http.js +190 -0
  90. package/dist/mcp/http.js.map +1 -0
  91. package/dist/mcp/index.d.ts +23 -0
  92. package/dist/mcp/index.d.ts.map +1 -0
  93. package/dist/mcp/index.js +21 -0
  94. package/dist/mcp/index.js.map +1 -0
  95. package/dist/mcp/manifest.d.ts +36 -0
  96. package/dist/mcp/manifest.d.ts.map +1 -0
  97. package/dist/mcp/manifest.js +40 -0
  98. package/dist/mcp/manifest.js.map +1 -0
  99. package/dist/mcp/rpc.d.ts +39 -0
  100. package/dist/mcp/rpc.d.ts.map +1 -0
  101. package/dist/mcp/rpc.js +149 -0
  102. package/dist/mcp/rpc.js.map +1 -0
  103. package/dist/mcp/stdio.d.ts +24 -0
  104. package/dist/mcp/stdio.d.ts.map +1 -0
  105. package/dist/mcp/stdio.js +157 -0
  106. package/dist/mcp/stdio.js.map +1 -0
  107. package/dist/mcp/worker-main.d.ts +6 -0
  108. package/dist/mcp/worker-main.d.ts.map +1 -0
  109. package/dist/mcp/worker-main.js +17 -0
  110. package/dist/mcp/worker-main.js.map +1 -0
  111. package/dist/mcp/worker.d.ts +54 -0
  112. package/dist/mcp/worker.d.ts.map +1 -0
  113. package/dist/mcp/worker.js +166 -0
  114. package/dist/mcp/worker.js.map +1 -0
  115. package/dist/meter.d.ts +63 -0
  116. package/dist/meter.d.ts.map +1 -0
  117. package/dist/meter.js +94 -0
  118. package/dist/meter.js.map +1 -0
  119. package/dist/providers.d.ts +23 -0
  120. package/dist/providers.d.ts.map +1 -0
  121. package/dist/providers.js +21 -0
  122. package/dist/providers.js.map +1 -0
  123. package/dist/redact.d.ts +12 -0
  124. package/dist/redact.d.ts.map +1 -0
  125. package/dist/redact.js +77 -0
  126. package/dist/redact.js.map +1 -0
  127. package/dist/redis-budget.d.ts +45 -0
  128. package/dist/redis-budget.d.ts.map +1 -0
  129. package/dist/redis-budget.js +56 -0
  130. package/dist/redis-budget.js.map +1 -0
  131. package/dist/response.d.ts +39 -0
  132. package/dist/response.d.ts.map +1 -0
  133. package/dist/response.js +109 -0
  134. package/dist/response.js.map +1 -0
  135. package/dist/schema.d.ts +45 -0
  136. package/dist/schema.d.ts.map +1 -0
  137. package/dist/schema.js +43 -0
  138. package/dist/schema.js.map +1 -0
  139. package/dist/server-sent.d.ts +9 -0
  140. package/dist/server-sent.d.ts.map +1 -0
  141. package/dist/server-sent.js +74 -0
  142. package/dist/server-sent.js.map +1 -0
  143. package/dist/server-tools.d.ts +12 -0
  144. package/dist/server-tools.d.ts.map +1 -0
  145. package/dist/server-tools.js +71 -0
  146. package/dist/server-tools.js.map +1 -0
  147. package/dist/services/catalog.d.ts +19 -0
  148. package/dist/services/catalog.d.ts.map +1 -0
  149. package/dist/services/catalog.js +37 -0
  150. package/dist/services/catalog.js.map +1 -0
  151. package/dist/services/main.d.ts +23 -0
  152. package/dist/services/main.d.ts.map +1 -0
  153. package/dist/services/main.js +43 -0
  154. package/dist/services/main.js.map +1 -0
  155. package/dist/skills/folder.d.ts +32 -0
  156. package/dist/skills/folder.d.ts.map +1 -0
  157. package/dist/skills/folder.js +170 -0
  158. package/dist/skills/folder.js.map +1 -0
  159. package/dist/skills/frontmatter.d.ts +15 -0
  160. package/dist/skills/frontmatter.d.ts.map +1 -0
  161. package/dist/skills/frontmatter.js +92 -0
  162. package/dist/skills/frontmatter.js.map +1 -0
  163. package/dist/skills/index.d.ts +18 -0
  164. package/dist/skills/index.d.ts.map +1 -0
  165. package/dist/skills/index.js +18 -0
  166. package/dist/skills/index.js.map +1 -0
  167. package/dist/skills/kit.d.ts +39 -0
  168. package/dist/skills/kit.d.ts.map +1 -0
  169. package/dist/skills/kit.js +124 -0
  170. package/dist/skills/kit.js.map +1 -0
  171. package/dist/skills/skill.d.ts +67 -0
  172. package/dist/skills/skill.d.ts.map +1 -0
  173. package/dist/skills/skill.js +114 -0
  174. package/dist/skills/skill.js.map +1 -0
  175. package/dist/sse.d.ts +95 -0
  176. package/dist/sse.d.ts.map +1 -0
  177. package/dist/sse.js +117 -0
  178. package/dist/sse.js.map +1 -0
  179. package/dist/testing/FakeProvider.d.ts +85 -0
  180. package/dist/testing/FakeProvider.d.ts.map +1 -0
  181. package/dist/testing/FakeProvider.js +214 -0
  182. package/dist/testing/FakeProvider.js.map +1 -0
  183. package/dist/testing/index.d.ts +7 -0
  184. package/dist/testing/index.d.ts.map +1 -0
  185. package/dist/testing/index.js +7 -0
  186. package/dist/testing/index.js.map +1 -0
  187. package/dist/tool-modules.d.ts +17 -0
  188. package/dist/tool-modules.d.ts.map +1 -0
  189. package/dist/tool-modules.js +43 -0
  190. package/dist/tool-modules.js.map +1 -0
  191. package/dist/tools.d.ts +132 -0
  192. package/dist/tools.d.ts.map +1 -0
  193. package/dist/tools.js +250 -0
  194. package/dist/tools.js.map +1 -0
  195. package/dist/transport.d.ts +23 -0
  196. package/dist/transport.d.ts.map +1 -0
  197. package/dist/transport.js +83 -0
  198. package/dist/transport.js.map +1 -0
  199. package/dist/types.d.ts +397 -0
  200. package/dist/types.d.ts.map +1 -0
  201. package/dist/types.js +12 -0
  202. package/dist/types.js.map +1 -0
  203. package/package.json +97 -3
  204. package/src/Polaris.ts +304 -0
  205. package/src/PolarisClient.ts +828 -0
  206. package/src/PolarisProvider.ts +111 -0
  207. package/src/augmentations.ts +20 -0
  208. package/src/budget.ts +201 -0
  209. package/src/catalog/catalog.ts +180 -0
  210. package/src/catalog/discover.ts +234 -0
  211. package/src/catalog/index.ts +19 -0
  212. package/src/commands/index.ts +412 -0
  213. package/src/cost.ts +176 -0
  214. package/src/drivers/anthropic.ts +703 -0
  215. package/src/drivers/openai-compatible.ts +907 -0
  216. package/src/drivers/status.ts +30 -0
  217. package/src/errors.ts +202 -0
  218. package/src/extract.ts +214 -0
  219. package/src/index.ts +85 -0
  220. package/src/json-schema.ts +597 -0
  221. package/src/log.ts +86 -0
  222. package/src/mcp/client.ts +532 -0
  223. package/src/mcp/endpoint.ts +229 -0
  224. package/src/mcp/host.ts +140 -0
  225. package/src/mcp/http.ts +276 -0
  226. package/src/mcp/index.ts +51 -0
  227. package/src/mcp/manifest.ts +73 -0
  228. package/src/mcp/rpc.ts +197 -0
  229. package/src/mcp/stdio.ts +190 -0
  230. package/src/mcp/worker-main.ts +18 -0
  231. package/src/mcp/worker.ts +212 -0
  232. package/src/meter.ts +199 -0
  233. package/src/providers.ts +25 -0
  234. package/src/redact.ts +81 -0
  235. package/src/redis-budget.ts +85 -0
  236. package/src/response.ts +143 -0
  237. package/src/schema.ts +88 -0
  238. package/src/server-sent.ts +70 -0
  239. package/src/server-tools.ts +77 -0
  240. package/src/services/catalog.ts +43 -0
  241. package/src/services/main.ts +49 -0
  242. package/src/skills/folder.ts +231 -0
  243. package/src/skills/frontmatter.ts +92 -0
  244. package/src/skills/index.ts +38 -0
  245. package/src/skills/kit.ts +163 -0
  246. package/src/skills/skill.ts +171 -0
  247. package/src/sse.ts +194 -0
  248. package/src/testing/FakeProvider.ts +322 -0
  249. package/src/testing/index.ts +12 -0
  250. package/src/tool-modules.ts +49 -0
  251. package/src/tools.ts +399 -0
  252. package/src/transport.ts +107 -0
  253. package/src/types.ts +434 -0
@@ -0,0 +1,907 @@
1
+ /**
2
+ * The OpenAI-compatible driver: every endpoint that speaks OpenAI's chat
3
+ * completions API (Groq, Cloudflare Workers AI, Infomaniak, a local Ollama,
4
+ * OpenAI itself), over plain `fetch`.
5
+ *
6
+ * What a given model can do varies from one service to the next, so the
7
+ * provider config declares it; polaris refuses the rest before sending.
8
+ */
9
+
10
+ import {
11
+ E_POLARIS_INVALID_CONFIG,
12
+ E_POLARIS_INVALID_REQUEST,
13
+ E_POLARIS_INVALID_RESPONSE,
14
+ E_POLARIS_PROVIDER_UNAVAILABLE,
15
+ E_POLARIS_PROVIDER_UNREACHABLE,
16
+ E_POLARIS_STREAM_INCOMPLETE,
17
+ } from "../errors.js";
18
+ import {
19
+ createResponse,
20
+ isTokenCount,
21
+ type ResponseInput,
22
+ } from "../response.js";
23
+ import { serverSentData } from "../server-sent.js";
24
+ import type {
25
+ AssistantPart,
26
+ ChatRequest,
27
+ ChatResponse,
28
+ DriverCall,
29
+ DriverDefaults,
30
+ DriverFeatures,
31
+ EmbedRequest,
32
+ EmbedResponse,
33
+ Message,
34
+ PolarisDriver,
35
+ ProviderFactory,
36
+ StopReason,
37
+ StreamEvent,
38
+ ToolCallPart,
39
+ UserPart,
40
+ } from "../types.js";
41
+ import { errorForStatus } from "./status.js";
42
+
43
+ const DEFAULT_NAME = "openai-compatible";
44
+ const DEFAULT_MAX_TOKENS = 16_000;
45
+ /** Statuses worth sending again besides 5xx: timeout, conflict, rate limit, Groq's capacity. */
46
+ const RETRYABLE = new Set([408, 409, 429, 498]);
47
+ const MAX_RETRY_DELAY = 60_000;
48
+ const BASE_RETRY_DELAY = 500;
49
+ /** Inputs per embedding request: well under OpenAI's 2048, for services that take fewer. */
50
+ const DEFAULT_EMBEDDING_BATCH = 128;
51
+ /**
52
+ * The most tool calls one reply is read with. Far above what a run lets
53
+ * through (`maxToolCalls`): this only stops a broken or hostile reply from
54
+ * growing without end while it is read.
55
+ */
56
+ const MAX_REPLY_TOOL_CALLS = 256;
57
+ /** The longest server-sent event read, in characters: a chunk is far shorter. */
58
+ const MAX_EVENT_LENGTH = 4 * 1024 * 1024;
59
+
60
+ export interface OpenAICompatibleConfig {
61
+ /** The API's base URL, up to and including `/v1`: `http://localhost:11434/v1`. */
62
+ readonly baseURL: string;
63
+ /** The chat model every request uses unless it names another. */
64
+ readonly model: string;
65
+ /** Sent as a bearer token. Leave it out for a local server that needs none. */
66
+ readonly apiKey?: string;
67
+ /**
68
+ * The provider's name in responses and in `providerOptions` (`groq`,
69
+ * `ollama`…). Default `openai-compatible`.
70
+ */
71
+ readonly name?: string;
72
+ /** The embedding model. Without it, the provider does not embed. */
73
+ readonly embeddingModel?: string;
74
+ /**
75
+ * Inputs sent per embedding request; a longer list is split into batches
76
+ * sent one after the other, its order kept. Default 128.
77
+ */
78
+ readonly embeddingBatchSize?: number;
79
+ /**
80
+ * What the model supports. Default: tools and structured output on,
81
+ * images off. Declare what your model does, and polaris refuses the rest
82
+ * before sending.
83
+ */
84
+ readonly features?: Partial<Omit<DriverFeatures, "serverTools">>;
85
+ /** Output limit when a request sets none. Default 16 000. */
86
+ readonly maxTokens?: number;
87
+ /**
88
+ * The field the output limit is sent in. Default `max_tokens`, which Ollama
89
+ * and Workers AI read; Infomaniak reads only `max_completion_tokens`.
90
+ */
91
+ readonly maxTokensField?: "max_tokens" | "max_completion_tokens";
92
+ /**
93
+ * Ask a stream for its token usage (`stream_options.include_usage`).
94
+ * Default true; turn it off for a service that rejects the field.
95
+ */
96
+ readonly streamUsage?: boolean;
97
+ /** Retries of a rate-limited, overloaded or failed request. Default 2. */
98
+ readonly maxRetries?: number;
99
+ /** Further headers sent with every request. */
100
+ readonly headers?: Readonly<Record<string, string>>;
101
+ }
102
+
103
+ /** A provider factory for an OpenAI-compatible endpoint. */
104
+ export function openaiCompatible(
105
+ config: OpenAICompatibleConfig,
106
+ ): ProviderFactory {
107
+ return () => new OpenAICompatibleDriver(config);
108
+ }
109
+
110
+ interface PartialCall {
111
+ id: string;
112
+ name: string;
113
+ arguments: string;
114
+ /**
115
+ * The call's fields polaris does not model, such as Gemini's
116
+ * `extra_content.google.thought_signature`, which the service requires
117
+ * back on the next turn.
118
+ */
119
+ extra: Record<string, unknown>;
120
+ }
121
+
122
+ /** A tool call's fields polaris models; every other one is kept as it came. */
123
+ const MODELLED_CALL_FIELDS = new Set(["index", "id", "type", "function"]);
124
+
125
+ /** Copy the fields of `raw` polaris does not model into `extra`. */
126
+ function keepExtraFields(
127
+ raw: Record<string, unknown>,
128
+ extra: Record<string, unknown>,
129
+ ): void {
130
+ for (const [key, value] of Object.entries(raw)) {
131
+ if (!MODELLED_CALL_FIELDS.has(key)) extra[key] = value;
132
+ }
133
+ }
134
+
135
+ interface StreamState {
136
+ id: string;
137
+ model: string;
138
+ text: string;
139
+ reasoning: string;
140
+ calls: Map<number, PartialCall>;
141
+ finish: string | undefined;
142
+ usage: ResponseInput["usage"];
143
+ done: boolean;
144
+ }
145
+
146
+ class OpenAICompatibleDriver implements PolarisDriver {
147
+ readonly provider: string;
148
+ readonly features: DriverFeatures;
149
+ readonly defaults: DriverDefaults;
150
+ /** The configured key and every header value: an `api-key`, a gateway token... */
151
+ readonly secrets: readonly string[];
152
+ readonly embed?: (
153
+ request: EmbedRequest,
154
+ call: DriverCall,
155
+ ) => Promise<EmbedResponse>;
156
+ readonly #config: OpenAICompatibleConfig;
157
+ readonly #base: string;
158
+
159
+ constructor(config: OpenAICompatibleConfig) {
160
+ const base = typeof config.baseURL === "string" ? config.baseURL : "";
161
+ if (!URL.canParse(base) || !/^https?:$/.test(new URL(base).protocol)) {
162
+ throw new E_POLARIS_INVALID_CONFIG([
163
+ "the OpenAI-compatible driver needs a `baseURL` starting with http:// or https://",
164
+ ]);
165
+ }
166
+ if (typeof config.model !== "string" || config.model.trim() === "") {
167
+ throw new E_POLARIS_INVALID_CONFIG([
168
+ "the OpenAI-compatible driver needs a `model`",
169
+ ]);
170
+ }
171
+ if (config.maxTokens !== undefined && !isCount(config.maxTokens)) {
172
+ throw new E_POLARIS_INVALID_CONFIG([
173
+ "the OpenAI-compatible driver's `maxTokens` must be a positive integer",
174
+ ]);
175
+ }
176
+ if (
177
+ config.embeddingBatchSize !== undefined &&
178
+ !isCount(config.embeddingBatchSize)
179
+ ) {
180
+ throw new E_POLARIS_INVALID_CONFIG([
181
+ "the OpenAI-compatible driver's `embeddingBatchSize` must be a positive integer",
182
+ ]);
183
+ }
184
+ if (
185
+ config.maxRetries !== undefined &&
186
+ !(Number.isInteger(config.maxRetries) && config.maxRetries >= 0)
187
+ ) {
188
+ throw new E_POLARIS_INVALID_CONFIG([
189
+ "the OpenAI-compatible driver's `maxRetries` must be an integer, 0 or more",
190
+ ]);
191
+ }
192
+ this.#config = config;
193
+ this.#base = base.replace(/\/+$/, "");
194
+ this.provider = config.name ?? DEFAULT_NAME;
195
+ this.features = {
196
+ tools: true,
197
+ structuredOutput: true,
198
+ images: false,
199
+ ...config.features,
200
+ // The Chat Completions API has no server-side tools to send them to.
201
+ serverTools: false,
202
+ };
203
+ this.defaults = {
204
+ model: config.model,
205
+ embeddingModel: config.embeddingModel,
206
+ maxTokens: config.maxTokens ?? DEFAULT_MAX_TOKENS,
207
+ streamMaxTokens: config.maxTokens ?? DEFAULT_MAX_TOKENS,
208
+ };
209
+ this.secrets = [
210
+ ...(config.apiKey !== undefined ? [config.apiKey] : []),
211
+ ...Object.values(config.headers ?? {}),
212
+ ];
213
+ const embeddingModel = config.embeddingModel;
214
+ if (embeddingModel !== undefined) {
215
+ this.embed = (request, call) =>
216
+ this.#embed(embeddingModel, request, call);
217
+ }
218
+ }
219
+
220
+ async chat(request: ChatRequest, call: DriverCall): Promise<ChatResponse> {
221
+ const response = await this.#post(
222
+ "/chat/completions",
223
+ this.#body(request, false),
224
+ call,
225
+ );
226
+ const body = parseJson(await response.text(), this.provider);
227
+ return this.#toResponse(body, request);
228
+ }
229
+
230
+ async *stream(
231
+ request: ChatRequest,
232
+ call: DriverCall,
233
+ ): AsyncGenerator<StreamEvent, void, undefined> {
234
+ const response = await this.#post(
235
+ "/chat/completions",
236
+ this.#body(request, true),
237
+ call,
238
+ );
239
+ if (response.body === null) {
240
+ throw new E_POLARIS_STREAM_INCOMPLETE([this.provider]);
241
+ }
242
+
243
+ const state: StreamState = {
244
+ id: "",
245
+ model: "",
246
+ text: "",
247
+ reasoning: "",
248
+ calls: new Map(),
249
+ finish: undefined,
250
+ usage: undefined,
251
+ done: false,
252
+ };
253
+ for await (const data of serverSentData(
254
+ response.body,
255
+ MAX_EVENT_LENGTH,
256
+ () =>
257
+ new E_POLARIS_INVALID_RESPONSE([
258
+ this.provider,
259
+ `a server-sent event is longer than ${MAX_EVENT_LENGTH} characters`,
260
+ ]),
261
+ )) {
262
+ if (data === "[DONE]") {
263
+ state.done = true;
264
+ break;
265
+ }
266
+ yield* this.#readChunk(parseJson(data, this.provider), state);
267
+ }
268
+ if (!state.done && state.finish === undefined) {
269
+ throw new E_POLARIS_STREAM_INCOMPLETE([this.provider]);
270
+ }
271
+
272
+ const calls = [...state.calls.entries()]
273
+ .sort(([a], [b]) => a - b)
274
+ .map(([, partial]) => toToolCall(partial, this.provider));
275
+ for (const toolCall of calls) yield { type: "tool_call", call: toolCall };
276
+
277
+ yield {
278
+ type: "done",
279
+ response: createResponse({
280
+ id: state.id,
281
+ provider: this.provider,
282
+ model: state.model || (request.model ?? this.#config.model),
283
+ content: assistantContent(state.reasoning, state.text, calls),
284
+ stopReason: toStopReason(state.finish, calls.length > 0),
285
+ usage: state.usage,
286
+ }),
287
+ };
288
+ }
289
+
290
+ *#readChunk(
291
+ chunk: Record<string, unknown>,
292
+ state: StreamState,
293
+ ): Generator<StreamEvent> {
294
+ // Ollama reports an error met mid-stream in a data line, under a 200.
295
+ if (chunk.error !== undefined) {
296
+ throw new E_POLARIS_PROVIDER_UNAVAILABLE([
297
+ this.provider,
298
+ errorMessage(chunk) ?? "the stream reported an error",
299
+ ]);
300
+ }
301
+ if (typeof chunk.id === "string") state.id = chunk.id;
302
+ if (typeof chunk.model === "string") state.model = chunk.model;
303
+ if (isRecord(chunk.usage)) state.usage = toUsage(chunk.usage);
304
+
305
+ const choice = first(chunk.choices);
306
+ if (choice === undefined) return;
307
+ if (typeof choice.finish_reason === "string") {
308
+ state.finish = choice.finish_reason;
309
+ }
310
+ const delta = isRecord(choice.delta) ? choice.delta : {};
311
+ const reasoning = reasoningOf(delta);
312
+ if (reasoning !== "") {
313
+ state.reasoning += reasoning;
314
+ yield { type: "reasoning", text: reasoning };
315
+ }
316
+ if (typeof delta.content === "string" && delta.content !== "") {
317
+ state.text += delta.content;
318
+ yield { type: "text", text: delta.content };
319
+ }
320
+ // A tool call arrives in fragments, joined by their `index`.
321
+ for (const fragment of list(delta.tool_calls)) {
322
+ if (!isRecord(fragment)) continue;
323
+ const index = typeof fragment.index === "number" ? fragment.index : 0;
324
+ if (!state.calls.has(index))
325
+ checkCallCount(state.calls.size + 1, this.provider);
326
+ const partial = state.calls.get(index) ?? {
327
+ id: "",
328
+ name: "",
329
+ arguments: "",
330
+ extra: {},
331
+ };
332
+ if (typeof fragment.id === "string") partial.id = fragment.id;
333
+ keepExtraFields(fragment, partial.extra);
334
+ const fn = isRecord(fragment.function) ? fragment.function : {};
335
+ if (typeof fn.name === "string") partial.name += fn.name;
336
+ if (typeof fn.arguments === "string") partial.arguments += fn.arguments;
337
+ state.calls.set(index, partial);
338
+ }
339
+ }
340
+
341
+ /**
342
+ * Embed `request.inputs` in batches of `embeddingBatchSize`, one after the
343
+ * other, and join the vectors back in input order.
344
+ */
345
+ async #embed(
346
+ defaultModel: string,
347
+ request: EmbedRequest,
348
+ call: DriverCall,
349
+ ): Promise<EmbedResponse> {
350
+ const size = this.#config.embeddingBatchSize ?? DEFAULT_EMBEDDING_BATCH;
351
+ const vectors: Float32Array[] = [];
352
+ let inputTokens = 0;
353
+ let usageUnknown = false;
354
+ let model = request.model ?? defaultModel;
355
+ for (let start = 0; start < request.inputs.length; start += size) {
356
+ const batch = request.inputs.slice(start, start + size);
357
+ const answer = await this.#embedBatch(
358
+ request.model ?? defaultModel,
359
+ batch,
360
+ request.dimensions,
361
+ call,
362
+ );
363
+ if (answer.vectors.length !== batch.length) {
364
+ throw new E_POLARIS_INVALID_RESPONSE([
365
+ this.provider,
366
+ `${answer.vectors.length} vectors for a batch of ${batch.length} inputs`,
367
+ ]);
368
+ }
369
+ vectors.push(...answer.vectors);
370
+ if (isTokenCount(answer.inputTokens)) inputTokens += answer.inputTokens;
371
+ else usageUnknown = true;
372
+ model = answer.model;
373
+ }
374
+ // polaris then checks that every vector has this length, across batches.
375
+ return {
376
+ provider: this.provider,
377
+ model,
378
+ dimensions: vectors[0]?.length ?? 0,
379
+ vectors,
380
+ usage: { inputTokens },
381
+ ...(usageUnknown ? { usageUnknown } : {}),
382
+ };
383
+ }
384
+
385
+ async #embedBatch(
386
+ model: string,
387
+ inputs: readonly string[],
388
+ dimensions: number | undefined,
389
+ call: DriverCall,
390
+ ): Promise<{ model: string; vectors: Float32Array[]; inputTokens: unknown }> {
391
+ const response = await this.#post(
392
+ "/embeddings",
393
+ {
394
+ model,
395
+ input: [...inputs],
396
+ encoding_format: "float",
397
+ ...(dimensions !== undefined ? { dimensions } : {}),
398
+ },
399
+ call,
400
+ );
401
+ const body = parseJson(await response.text(), this.provider);
402
+ const rows = list(body.data)
403
+ .filter(isRecord)
404
+ .map((row, position) => ({
405
+ index: typeof row.index === "number" ? row.index : position,
406
+ embedding: list(row.embedding),
407
+ }))
408
+ .sort((a, b) => a.index - b.index);
409
+ const vectors = rows.map((row) => {
410
+ const numbers = row.embedding.filter(
411
+ (value): value is number => typeof value === "number",
412
+ );
413
+ if (numbers.length !== row.embedding.length) {
414
+ throw new E_POLARIS_INVALID_RESPONSE([
415
+ this.provider,
416
+ "an embedding holds something other than numbers",
417
+ ]);
418
+ }
419
+ return Float32Array.from(numbers);
420
+ });
421
+ return {
422
+ model: typeof body.model === "string" ? body.model : model,
423
+ vectors,
424
+ // As reported: `#embed` adds it up only when it can be a count.
425
+ inputTokens: isRecord(body.usage) ? body.usage.prompt_tokens : undefined,
426
+ };
427
+ }
428
+
429
+ #body(request: ChatRequest, streaming: boolean): Record<string, unknown> {
430
+ const config = this.#config;
431
+ const tools = request.tools ?? [];
432
+ const output = request.output;
433
+ return {
434
+ ...providerOptions(request, this.provider),
435
+ model: request.model ?? config.model,
436
+ messages: toMessages(request, this.provider),
437
+ [config.maxTokensField ?? "max_tokens"]:
438
+ request.maxTokens ?? config.maxTokens ?? DEFAULT_MAX_TOKENS,
439
+ // Sent either way: Infomaniak streams unless told not to.
440
+ stream: streaming,
441
+ ...(streaming && config.streamUsage !== false
442
+ ? { stream_options: { include_usage: true } }
443
+ : {}),
444
+ ...(tools.length > 0
445
+ ? {
446
+ tools: tools.map((tool) => ({
447
+ type: "function",
448
+ function: {
449
+ name: tool.name,
450
+ description: tool.description,
451
+ parameters: tool.inputSchema,
452
+ },
453
+ })),
454
+ }
455
+ : {}),
456
+ ...(request.toolChoice !== undefined
457
+ ? { tool_choice: request.toolChoice }
458
+ : {}),
459
+ ...(request.stopSequences !== undefined
460
+ ? { stop: [...request.stopSequences] }
461
+ : {}),
462
+ ...(request.effort !== undefined
463
+ ? { reasoning_effort: request.effort }
464
+ : {}),
465
+ ...(output !== undefined
466
+ ? {
467
+ response_format: {
468
+ type: "json_schema",
469
+ json_schema: {
470
+ name: output.name,
471
+ schema: output.schema,
472
+ ...(output.description !== undefined
473
+ ? { description: output.description }
474
+ : {}),
475
+ },
476
+ },
477
+ }
478
+ : {}),
479
+ };
480
+ }
481
+
482
+ /**
483
+ * POST `body`, retrying what is worth retrying, and hand back the first
484
+ * successful response. Every failure past the retries is a polaris error.
485
+ */
486
+ async #post(
487
+ path: string,
488
+ body: Record<string, unknown>,
489
+ call: DriverCall,
490
+ ): Promise<Response> {
491
+ const config = this.#config;
492
+ const apiKey = call.apiKey ?? config.apiKey;
493
+ const headers: Record<string, string> = {
494
+ ...config.headers,
495
+ "content-type": "application/json",
496
+ accept: "application/json",
497
+ ...(apiKey !== undefined ? { authorization: `Bearer ${apiKey}` } : {}),
498
+ };
499
+ const retries = config.maxRetries ?? 2;
500
+
501
+ for (let attempt = 0; ; attempt++) {
502
+ let response: Response;
503
+ try {
504
+ response = await call.fetch(`${this.#base}${path}`, {
505
+ method: "POST",
506
+ headers,
507
+ body: JSON.stringify(body),
508
+ signal: call.signal,
509
+ });
510
+ } catch (error) {
511
+ if (call.signal.aborted || isPolarisError(error)) throw error;
512
+ if (attempt < retries) {
513
+ await sleep(backoff(attempt, undefined), call.signal);
514
+ continue;
515
+ }
516
+ throw new E_POLARIS_PROVIDER_UNREACHABLE(
517
+ [
518
+ this.provider,
519
+ error instanceof Error ? error.message : String(error),
520
+ ],
521
+ { cause: error },
522
+ );
523
+ }
524
+ if (response.ok) return response;
525
+
526
+ const retryable =
527
+ RETRYABLE.has(response.status) || response.status >= 500;
528
+ if (retryable && attempt < retries) {
529
+ await response.body?.cancel().catch(() => undefined);
530
+ await sleep(backoff(attempt, response.headers), call.signal);
531
+ continue;
532
+ }
533
+ throw await this.#failure(response);
534
+ }
535
+ }
536
+
537
+ async #failure(response: Response): Promise<Error> {
538
+ const text = await response.text().catch(() => "");
539
+ let message: string | undefined;
540
+ try {
541
+ const body: unknown = JSON.parse(text);
542
+ message = isRecord(body) ? errorMessage(body) : undefined;
543
+ } catch {
544
+ message = undefined;
545
+ }
546
+ const detail = message ?? (text.slice(0, 300) || `HTTP ${response.status}`);
547
+ const id = response.headers.get("x-request-id");
548
+ return errorForStatus(
549
+ this.provider,
550
+ response.status,
551
+ id ? `${detail} (request ${id})` : detail,
552
+ );
553
+ }
554
+
555
+ #toResponse(
556
+ body: Record<string, unknown>,
557
+ request: ChatRequest,
558
+ ): ChatResponse {
559
+ const choice = first(body.choices);
560
+ const message =
561
+ choice !== undefined && isRecord(choice.message)
562
+ ? choice.message
563
+ : undefined;
564
+ if (message === undefined) {
565
+ throw new E_POLARIS_INVALID_RESPONSE([
566
+ this.provider,
567
+ "the reply has no message",
568
+ ]);
569
+ }
570
+ const rawCalls = list(message.tool_calls);
571
+ checkCallCount(rawCalls.length, this.provider);
572
+ const calls = rawCalls.filter(isRecord).map((raw) => {
573
+ const fn = isRecord(raw.function) ? raw.function : {};
574
+ const extra: Record<string, unknown> = {};
575
+ keepExtraFields(raw, extra);
576
+ return toToolCall(
577
+ {
578
+ id: typeof raw.id === "string" ? raw.id : "",
579
+ name: typeof fn.name === "string" ? fn.name : "",
580
+ arguments: typeof fn.arguments === "string" ? fn.arguments : "",
581
+ extra,
582
+ },
583
+ this.provider,
584
+ );
585
+ });
586
+ const text = typeof message.content === "string" ? message.content : "";
587
+ return createResponse({
588
+ id: typeof body.id === "string" ? body.id : "",
589
+ provider: this.provider,
590
+ model:
591
+ typeof body.model === "string"
592
+ ? body.model
593
+ : (request.model ?? this.#config.model),
594
+ content: assistantContent(reasoningOf(message), text, calls),
595
+ stopReason: toStopReason(
596
+ typeof choice?.finish_reason === "string"
597
+ ? choice.finish_reason
598
+ : undefined,
599
+ calls.length > 0,
600
+ ),
601
+ usage: toUsage(body.usage),
602
+ });
603
+ }
604
+ }
605
+
606
+ /** Reasoning, then text, then tool calls: the order a reply is written in. */
607
+ function assistantContent(
608
+ reasoning: string,
609
+ text: string,
610
+ calls: readonly ToolCallPart[],
611
+ ): AssistantPart[] {
612
+ const content: AssistantPart[] = [];
613
+ if (reasoning !== "") content.push({ type: "reasoning", text: reasoning });
614
+ if (text !== "") content.push({ type: "text", text });
615
+ content.push(...calls);
616
+ return content;
617
+ }
618
+
619
+ /** The chat messages, the system prompt first. */
620
+ function toMessages(
621
+ request: ChatRequest,
622
+ provider: string,
623
+ ): Record<string, unknown>[] {
624
+ const out: Record<string, unknown>[] = [];
625
+ if (request.system !== undefined) {
626
+ out.push({ role: "system", content: request.system });
627
+ }
628
+ for (const message of request.messages) {
629
+ out.push(...toMessage(message, provider));
630
+ }
631
+ return out;
632
+ }
633
+
634
+ /**
635
+ * The fields a tool call came with from `provider` and polaris does not
636
+ * model, to send back as they were; nothing for another provider's call.
637
+ */
638
+ function extraFieldsOf(
639
+ part: ToolCallPart,
640
+ provider: string,
641
+ ): Record<string, unknown> {
642
+ const origin = part.origin;
643
+ if (origin?.provider !== provider || !isRecord(origin.block)) return {};
644
+ const extra: Record<string, unknown> = {};
645
+ keepExtraFields(origin.block, extra);
646
+ return extra;
647
+ }
648
+
649
+ function toMessage(
650
+ message: Message,
651
+ provider: string,
652
+ ): Record<string, unknown>[] {
653
+ if (message.role === "assistant") {
654
+ if (typeof message.content === "string") {
655
+ return [{ role: "assistant", content: message.content }];
656
+ }
657
+ // Reasoning and another provider's blocks have no place in this API's
658
+ // history: it rebuilds nothing from them.
659
+ const text = message.content
660
+ .map((part) => (part.type === "text" ? part.text : ""))
661
+ .join("");
662
+ const calls = message.content
663
+ .filter((part): part is ToolCallPart => part.type === "tool_call")
664
+ .map((part) => ({
665
+ // First, so a kept field can never replace the call's own.
666
+ ...extraFieldsOf(part, provider),
667
+ id: part.id,
668
+ type: "function",
669
+ function: {
670
+ name: part.name,
671
+ arguments: JSON.stringify(part.input ?? {}),
672
+ },
673
+ }));
674
+ if (text === "" && calls.length === 0) return [];
675
+ return [
676
+ {
677
+ role: "assistant",
678
+ content: text === "" ? null : text,
679
+ ...(calls.length > 0 ? { tool_calls: calls } : {}),
680
+ },
681
+ ];
682
+ }
683
+
684
+ if (typeof message.content === "string") {
685
+ return [{ role: "user", content: message.content }];
686
+ }
687
+ // A tool result is a message of its own here, and must follow the
688
+ // assistant turn that asked for it: results first, then the user's parts.
689
+ const results = message.content
690
+ .filter((part) => part.type === "tool_result")
691
+ .map((part) => ({
692
+ role: "tool",
693
+ tool_call_id: part.toolCallId,
694
+ content: part.content,
695
+ }));
696
+ const rest = message.content.filter(
697
+ (part): part is Exclude<UserPart, { type: "tool_result" }> =>
698
+ part.type !== "tool_result",
699
+ );
700
+ if (rest.length === 0) return results;
701
+ const content = rest.every((part) => part.type === "text")
702
+ ? rest.map((part) => (part.type === "text" ? part.text : "")).join("\n")
703
+ : rest.map((part) =>
704
+ part.type === "text"
705
+ ? { type: "text", text: part.text }
706
+ : {
707
+ type: "image_url",
708
+ image_url: { url: `data:${part.mediaType};base64,${part.data}` },
709
+ },
710
+ );
711
+ return [...results, { role: "user", content }];
712
+ }
713
+
714
+ function toToolCall(partial: PartialCall, provider: string): ToolCallPart {
715
+ let input: unknown = {};
716
+ if (partial.arguments.trim() !== "") {
717
+ try {
718
+ input = JSON.parse(partial.arguments);
719
+ } catch {
720
+ // Left as the string the model wrote: the application's validation
721
+ // refuses it, instead of polaris guessing what was meant.
722
+ input = partial.arguments;
723
+ }
724
+ }
725
+ const call: ToolCallPart = {
726
+ type: "tool_call",
727
+ id: partial.id,
728
+ name: partial.name,
729
+ input,
730
+ };
731
+ // Only a call that carries such fields gets an origin: the others stay as
732
+ // plain as every other provider's.
733
+ return Object.keys(partial.extra).length === 0
734
+ ? call
735
+ : { ...call, origin: { provider, block: partial.extra } };
736
+ }
737
+
738
+ /** Reasoning text where each service puts it: Groq and Ollama `reasoning`, Workers AI `reasoning_content`. */
739
+ function reasoningOf(value: Record<string, unknown>): string {
740
+ if (typeof value.reasoning === "string") return value.reasoning;
741
+ if (typeof value.reasoning_content === "string") {
742
+ return value.reasoning_content;
743
+ }
744
+ return "";
745
+ }
746
+
747
+ function toStopReason(
748
+ reason: string | undefined,
749
+ hasToolCalls: boolean,
750
+ ): StopReason {
751
+ // Some servers (Ollama) finish a turn that calls tools with `stop`.
752
+ if (hasToolCalls) return "tool_use";
753
+ switch (reason) {
754
+ case "stop":
755
+ return "end";
756
+ case "length":
757
+ return "max_tokens";
758
+ case "tool_calls":
759
+ case "function_call":
760
+ return "tool_use";
761
+ case "content_filter":
762
+ return "content_filter";
763
+ default:
764
+ return "other";
765
+ }
766
+ }
767
+
768
+ /**
769
+ * The usage of a reply, as reported: `createResponse` checks the counts, and
770
+ * marks the response's usage unknown when one cannot be right. A body with
771
+ * no `prompt_tokens` reported none.
772
+ */
773
+ function toUsage(usage: unknown): ResponseInput["usage"] {
774
+ if (!isRecord(usage) || usage.prompt_tokens === undefined) return undefined;
775
+ const details = isRecord(usage.prompt_tokens_details)
776
+ ? usage.prompt_tokens_details
777
+ : {};
778
+ // `prompt_tokens` counts the cached tokens too; polaris's input count does
779
+ // not. More cached tokens than prompt tokens leaves a negative count.
780
+ const cached = details.cached_tokens ?? 0;
781
+ return {
782
+ inputTokens:
783
+ typeof usage.prompt_tokens === "number" && typeof cached === "number"
784
+ ? usage.prompt_tokens - cached
785
+ : usage.prompt_tokens,
786
+ outputTokens: usage.completion_tokens,
787
+ cacheReadTokens: cached,
788
+ cacheWriteTokens: 0,
789
+ };
790
+ }
791
+
792
+ /**
793
+ * The message of an error body: OpenAI's `{ error: { message } }`, Ollama's
794
+ * `{ error: "…" }`, Cloudflare's `{ errors: [{ message }] }`.
795
+ */
796
+ function errorMessage(body: Record<string, unknown>): string | undefined {
797
+ if (typeof body.error === "string") return body.error;
798
+ if (isRecord(body.error) && typeof body.error.message === "string") {
799
+ return body.error.message;
800
+ }
801
+ const firstError = first(body.errors);
802
+ if (firstError !== undefined && typeof firstError.message === "string") {
803
+ return firstError.message;
804
+ }
805
+ return undefined;
806
+ }
807
+
808
+ function providerOptions(
809
+ request: ChatRequest,
810
+ provider: string,
811
+ ): Record<string, unknown> {
812
+ const value: unknown = request.providerOptions?.[provider];
813
+ if (value === undefined) return {};
814
+ if (!isRecord(value)) {
815
+ throw new E_POLARIS_INVALID_REQUEST([
816
+ `providerOptions.${provider} must be an object of request fields`,
817
+ ]);
818
+ }
819
+ return { ...value };
820
+ }
821
+
822
+ function parseJson(text: string, provider: string): Record<string, unknown> {
823
+ let value: unknown;
824
+ try {
825
+ value = JSON.parse(text);
826
+ } catch {
827
+ throw new E_POLARIS_INVALID_RESPONSE([provider, "the reply is not JSON"]);
828
+ }
829
+ if (!isRecord(value)) {
830
+ throw new E_POLARIS_INVALID_RESPONSE([
831
+ provider,
832
+ "the reply is not a JSON object",
833
+ ]);
834
+ }
835
+ return value;
836
+ }
837
+
838
+ /**
839
+ * How long to wait before attempt `attempt + 1`: what the provider asked for
840
+ * (`retry-after-ms`, then `retry-after` in seconds or as a date), at most a
841
+ * minute; otherwise an exponential backoff with jitter.
842
+ */
843
+ function backoff(attempt: number, headers: Headers | undefined): number {
844
+ const ms = Number(headers?.get("retry-after-ms"));
845
+ if (headers?.has("retry-after-ms") && Number.isFinite(ms) && ms >= 0) {
846
+ return Math.min(ms, MAX_RETRY_DELAY);
847
+ }
848
+ const after = headers?.get("retry-after");
849
+ if (after) {
850
+ const seconds = Number(after);
851
+ const wait = Number.isFinite(seconds)
852
+ ? seconds * 1000
853
+ : Date.parse(after) - Date.now();
854
+ if (Number.isFinite(wait) && wait >= 0) {
855
+ return Math.min(wait, MAX_RETRY_DELAY);
856
+ }
857
+ }
858
+ const exponential = BASE_RETRY_DELAY * 2 ** attempt;
859
+ return Math.min(exponential * (0.75 + Math.random() * 0.5), 8_000);
860
+ }
861
+
862
+ function sleep(ms: number, signal: AbortSignal): Promise<void> {
863
+ if (signal.aborted) return Promise.reject(signal.reason);
864
+ return new Promise((resolve, reject) => {
865
+ const onAbort = () => {
866
+ clearTimeout(timer);
867
+ reject(signal.reason);
868
+ };
869
+ const timer = setTimeout(() => {
870
+ signal.removeEventListener("abort", onAbort);
871
+ resolve();
872
+ }, ms);
873
+ signal.addEventListener("abort", onAbort, { once: true });
874
+ });
875
+ }
876
+
877
+ function isPolarisError(error: unknown): boolean {
878
+ const code: unknown =
879
+ error instanceof Error ? Reflect.get(error, "code") : undefined;
880
+ return typeof code === "string" && code.startsWith("E_POLARIS_");
881
+ }
882
+
883
+ function isRecord(value: unknown): value is Record<string, unknown> {
884
+ return typeof value === "object" && value !== null && !Array.isArray(value);
885
+ }
886
+
887
+ function checkCallCount(count: number, provider: string): void {
888
+ if (count > MAX_REPLY_TOOL_CALLS) {
889
+ throw new E_POLARIS_INVALID_RESPONSE([
890
+ provider,
891
+ `the reply calls more than ${MAX_REPLY_TOOL_CALLS} tools`,
892
+ ]);
893
+ }
894
+ }
895
+
896
+ function list(value: unknown): unknown[] {
897
+ return Array.isArray(value) ? value : [];
898
+ }
899
+
900
+ function first(value: unknown): Record<string, unknown> | undefined {
901
+ const head: unknown = list(value)[0];
902
+ return isRecord(head) ? head : undefined;
903
+ }
904
+
905
+ function isCount(value: number): boolean {
906
+ return Number.isInteger(value) && value > 0;
907
+ }