@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,699 @@
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
+ import { E_POLARIS_INVALID_CONFIG, E_POLARIS_INVALID_REQUEST, E_POLARIS_INVALID_RESPONSE, E_POLARIS_PROVIDER_UNAVAILABLE, E_POLARIS_PROVIDER_UNREACHABLE, E_POLARIS_STREAM_INCOMPLETE, } from "../errors.js";
10
+ import { createResponse, isTokenCount, } from "../response.js";
11
+ import { serverSentData } from "../server-sent.js";
12
+ import { errorForStatus } from "./status.js";
13
+ const DEFAULT_NAME = "openai-compatible";
14
+ const DEFAULT_MAX_TOKENS = 16_000;
15
+ /** Statuses worth sending again besides 5xx: timeout, conflict, rate limit, Groq's capacity. */
16
+ const RETRYABLE = new Set([408, 409, 429, 498]);
17
+ const MAX_RETRY_DELAY = 60_000;
18
+ const BASE_RETRY_DELAY = 500;
19
+ /** Inputs per embedding request: well under OpenAI's 2048, for services that take fewer. */
20
+ const DEFAULT_EMBEDDING_BATCH = 128;
21
+ /**
22
+ * The most tool calls one reply is read with. Far above what a run lets
23
+ * through (`maxToolCalls`): this only stops a broken or hostile reply from
24
+ * growing without end while it is read.
25
+ */
26
+ const MAX_REPLY_TOOL_CALLS = 256;
27
+ /** The longest server-sent event read, in characters: a chunk is far shorter. */
28
+ const MAX_EVENT_LENGTH = 4 * 1024 * 1024;
29
+ /** A provider factory for an OpenAI-compatible endpoint. */
30
+ export function openaiCompatible(config) {
31
+ return () => new OpenAICompatibleDriver(config);
32
+ }
33
+ /** A tool call's fields polaris models; every other one is kept as it came. */
34
+ const MODELLED_CALL_FIELDS = new Set(["index", "id", "type", "function"]);
35
+ /** Copy the fields of `raw` polaris does not model into `extra`. */
36
+ function keepExtraFields(raw, extra) {
37
+ for (const [key, value] of Object.entries(raw)) {
38
+ if (!MODELLED_CALL_FIELDS.has(key))
39
+ extra[key] = value;
40
+ }
41
+ }
42
+ class OpenAICompatibleDriver {
43
+ provider;
44
+ features;
45
+ defaults;
46
+ /** The configured key and every header value: an `api-key`, a gateway token... */
47
+ secrets;
48
+ embed;
49
+ #config;
50
+ #base;
51
+ constructor(config) {
52
+ const base = typeof config.baseURL === "string" ? config.baseURL : "";
53
+ if (!URL.canParse(base) || !/^https?:$/.test(new URL(base).protocol)) {
54
+ throw new E_POLARIS_INVALID_CONFIG([
55
+ "the OpenAI-compatible driver needs a `baseURL` starting with http:// or https://",
56
+ ]);
57
+ }
58
+ if (typeof config.model !== "string" || config.model.trim() === "") {
59
+ throw new E_POLARIS_INVALID_CONFIG([
60
+ "the OpenAI-compatible driver needs a `model`",
61
+ ]);
62
+ }
63
+ if (config.maxTokens !== undefined && !isCount(config.maxTokens)) {
64
+ throw new E_POLARIS_INVALID_CONFIG([
65
+ "the OpenAI-compatible driver's `maxTokens` must be a positive integer",
66
+ ]);
67
+ }
68
+ if (config.embeddingBatchSize !== undefined &&
69
+ !isCount(config.embeddingBatchSize)) {
70
+ throw new E_POLARIS_INVALID_CONFIG([
71
+ "the OpenAI-compatible driver's `embeddingBatchSize` must be a positive integer",
72
+ ]);
73
+ }
74
+ if (config.maxRetries !== undefined &&
75
+ !(Number.isInteger(config.maxRetries) && config.maxRetries >= 0)) {
76
+ throw new E_POLARIS_INVALID_CONFIG([
77
+ "the OpenAI-compatible driver's `maxRetries` must be an integer, 0 or more",
78
+ ]);
79
+ }
80
+ this.#config = config;
81
+ this.#base = base.replace(/\/+$/, "");
82
+ this.provider = config.name ?? DEFAULT_NAME;
83
+ this.features = {
84
+ tools: true,
85
+ structuredOutput: true,
86
+ images: false,
87
+ ...config.features,
88
+ // The Chat Completions API has no server-side tools to send them to.
89
+ serverTools: false,
90
+ };
91
+ this.defaults = {
92
+ model: config.model,
93
+ embeddingModel: config.embeddingModel,
94
+ maxTokens: config.maxTokens ?? DEFAULT_MAX_TOKENS,
95
+ streamMaxTokens: config.maxTokens ?? DEFAULT_MAX_TOKENS,
96
+ };
97
+ this.secrets = [
98
+ ...(config.apiKey !== undefined ? [config.apiKey] : []),
99
+ ...Object.values(config.headers ?? {}),
100
+ ];
101
+ const embeddingModel = config.embeddingModel;
102
+ if (embeddingModel !== undefined) {
103
+ this.embed = (request, call) => this.#embed(embeddingModel, request, call);
104
+ }
105
+ }
106
+ async chat(request, call) {
107
+ const response = await this.#post("/chat/completions", this.#body(request, false), call);
108
+ const body = parseJson(await response.text(), this.provider);
109
+ return this.#toResponse(body, request);
110
+ }
111
+ async *stream(request, call) {
112
+ const response = await this.#post("/chat/completions", this.#body(request, true), call);
113
+ if (response.body === null) {
114
+ throw new E_POLARIS_STREAM_INCOMPLETE([this.provider]);
115
+ }
116
+ const state = {
117
+ id: "",
118
+ model: "",
119
+ text: "",
120
+ reasoning: "",
121
+ calls: new Map(),
122
+ finish: undefined,
123
+ usage: undefined,
124
+ done: false,
125
+ };
126
+ for await (const data of serverSentData(response.body, MAX_EVENT_LENGTH, () => new E_POLARIS_INVALID_RESPONSE([
127
+ this.provider,
128
+ `a server-sent event is longer than ${MAX_EVENT_LENGTH} characters`,
129
+ ]))) {
130
+ if (data === "[DONE]") {
131
+ state.done = true;
132
+ break;
133
+ }
134
+ yield* this.#readChunk(parseJson(data, this.provider), state);
135
+ }
136
+ if (!state.done && state.finish === undefined) {
137
+ throw new E_POLARIS_STREAM_INCOMPLETE([this.provider]);
138
+ }
139
+ const calls = [...state.calls.entries()]
140
+ .sort(([a], [b]) => a - b)
141
+ .map(([, partial]) => toToolCall(partial, this.provider));
142
+ for (const toolCall of calls)
143
+ yield { type: "tool_call", call: toolCall };
144
+ yield {
145
+ type: "done",
146
+ response: createResponse({
147
+ id: state.id,
148
+ provider: this.provider,
149
+ model: state.model || (request.model ?? this.#config.model),
150
+ content: assistantContent(state.reasoning, state.text, calls),
151
+ stopReason: toStopReason(state.finish, calls.length > 0),
152
+ usage: state.usage,
153
+ }),
154
+ };
155
+ }
156
+ *#readChunk(chunk, state) {
157
+ // Ollama reports an error met mid-stream in a data line, under a 200.
158
+ if (chunk.error !== undefined) {
159
+ throw new E_POLARIS_PROVIDER_UNAVAILABLE([
160
+ this.provider,
161
+ errorMessage(chunk) ?? "the stream reported an error",
162
+ ]);
163
+ }
164
+ if (typeof chunk.id === "string")
165
+ state.id = chunk.id;
166
+ if (typeof chunk.model === "string")
167
+ state.model = chunk.model;
168
+ if (isRecord(chunk.usage))
169
+ state.usage = toUsage(chunk.usage);
170
+ const choice = first(chunk.choices);
171
+ if (choice === undefined)
172
+ return;
173
+ if (typeof choice.finish_reason === "string") {
174
+ state.finish = choice.finish_reason;
175
+ }
176
+ const delta = isRecord(choice.delta) ? choice.delta : {};
177
+ const reasoning = reasoningOf(delta);
178
+ if (reasoning !== "") {
179
+ state.reasoning += reasoning;
180
+ yield { type: "reasoning", text: reasoning };
181
+ }
182
+ if (typeof delta.content === "string" && delta.content !== "") {
183
+ state.text += delta.content;
184
+ yield { type: "text", text: delta.content };
185
+ }
186
+ // A tool call arrives in fragments, joined by their `index`.
187
+ for (const fragment of list(delta.tool_calls)) {
188
+ if (!isRecord(fragment))
189
+ continue;
190
+ const index = typeof fragment.index === "number" ? fragment.index : 0;
191
+ if (!state.calls.has(index))
192
+ checkCallCount(state.calls.size + 1, this.provider);
193
+ const partial = state.calls.get(index) ?? {
194
+ id: "",
195
+ name: "",
196
+ arguments: "",
197
+ extra: {},
198
+ };
199
+ if (typeof fragment.id === "string")
200
+ partial.id = fragment.id;
201
+ keepExtraFields(fragment, partial.extra);
202
+ const fn = isRecord(fragment.function) ? fragment.function : {};
203
+ if (typeof fn.name === "string")
204
+ partial.name += fn.name;
205
+ if (typeof fn.arguments === "string")
206
+ partial.arguments += fn.arguments;
207
+ state.calls.set(index, partial);
208
+ }
209
+ }
210
+ /**
211
+ * Embed `request.inputs` in batches of `embeddingBatchSize`, one after the
212
+ * other, and join the vectors back in input order.
213
+ */
214
+ async #embed(defaultModel, request, call) {
215
+ const size = this.#config.embeddingBatchSize ?? DEFAULT_EMBEDDING_BATCH;
216
+ const vectors = [];
217
+ let inputTokens = 0;
218
+ let usageUnknown = false;
219
+ let model = request.model ?? defaultModel;
220
+ for (let start = 0; start < request.inputs.length; start += size) {
221
+ const batch = request.inputs.slice(start, start + size);
222
+ const answer = await this.#embedBatch(request.model ?? defaultModel, batch, request.dimensions, call);
223
+ if (answer.vectors.length !== batch.length) {
224
+ throw new E_POLARIS_INVALID_RESPONSE([
225
+ this.provider,
226
+ `${answer.vectors.length} vectors for a batch of ${batch.length} inputs`,
227
+ ]);
228
+ }
229
+ vectors.push(...answer.vectors);
230
+ if (isTokenCount(answer.inputTokens))
231
+ inputTokens += answer.inputTokens;
232
+ else
233
+ usageUnknown = true;
234
+ model = answer.model;
235
+ }
236
+ // polaris then checks that every vector has this length, across batches.
237
+ return {
238
+ provider: this.provider,
239
+ model,
240
+ dimensions: vectors[0]?.length ?? 0,
241
+ vectors,
242
+ usage: { inputTokens },
243
+ ...(usageUnknown ? { usageUnknown } : {}),
244
+ };
245
+ }
246
+ async #embedBatch(model, inputs, dimensions, call) {
247
+ const response = await this.#post("/embeddings", {
248
+ model,
249
+ input: [...inputs],
250
+ encoding_format: "float",
251
+ ...(dimensions !== undefined ? { dimensions } : {}),
252
+ }, call);
253
+ const body = parseJson(await response.text(), this.provider);
254
+ const rows = list(body.data)
255
+ .filter(isRecord)
256
+ .map((row, position) => ({
257
+ index: typeof row.index === "number" ? row.index : position,
258
+ embedding: list(row.embedding),
259
+ }))
260
+ .sort((a, b) => a.index - b.index);
261
+ const vectors = rows.map((row) => {
262
+ const numbers = row.embedding.filter((value) => typeof value === "number");
263
+ if (numbers.length !== row.embedding.length) {
264
+ throw new E_POLARIS_INVALID_RESPONSE([
265
+ this.provider,
266
+ "an embedding holds something other than numbers",
267
+ ]);
268
+ }
269
+ return Float32Array.from(numbers);
270
+ });
271
+ return {
272
+ model: typeof body.model === "string" ? body.model : model,
273
+ vectors,
274
+ // As reported: `#embed` adds it up only when it can be a count.
275
+ inputTokens: isRecord(body.usage) ? body.usage.prompt_tokens : undefined,
276
+ };
277
+ }
278
+ #body(request, streaming) {
279
+ const config = this.#config;
280
+ const tools = request.tools ?? [];
281
+ const output = request.output;
282
+ return {
283
+ ...providerOptions(request, this.provider),
284
+ model: request.model ?? config.model,
285
+ messages: toMessages(request, this.provider),
286
+ [config.maxTokensField ?? "max_tokens"]: request.maxTokens ?? config.maxTokens ?? DEFAULT_MAX_TOKENS,
287
+ // Sent either way: Infomaniak streams unless told not to.
288
+ stream: streaming,
289
+ ...(streaming && config.streamUsage !== false
290
+ ? { stream_options: { include_usage: true } }
291
+ : {}),
292
+ ...(tools.length > 0
293
+ ? {
294
+ tools: tools.map((tool) => ({
295
+ type: "function",
296
+ function: {
297
+ name: tool.name,
298
+ description: tool.description,
299
+ parameters: tool.inputSchema,
300
+ },
301
+ })),
302
+ }
303
+ : {}),
304
+ ...(request.toolChoice !== undefined
305
+ ? { tool_choice: request.toolChoice }
306
+ : {}),
307
+ ...(request.stopSequences !== undefined
308
+ ? { stop: [...request.stopSequences] }
309
+ : {}),
310
+ ...(request.effort !== undefined
311
+ ? { reasoning_effort: request.effort }
312
+ : {}),
313
+ ...(output !== undefined
314
+ ? {
315
+ response_format: {
316
+ type: "json_schema",
317
+ json_schema: {
318
+ name: output.name,
319
+ schema: output.schema,
320
+ ...(output.description !== undefined
321
+ ? { description: output.description }
322
+ : {}),
323
+ },
324
+ },
325
+ }
326
+ : {}),
327
+ };
328
+ }
329
+ /**
330
+ * POST `body`, retrying what is worth retrying, and hand back the first
331
+ * successful response. Every failure past the retries is a polaris error.
332
+ */
333
+ async #post(path, body, call) {
334
+ const config = this.#config;
335
+ const apiKey = call.apiKey ?? config.apiKey;
336
+ const headers = {
337
+ ...config.headers,
338
+ "content-type": "application/json",
339
+ accept: "application/json",
340
+ ...(apiKey !== undefined ? { authorization: `Bearer ${apiKey}` } : {}),
341
+ };
342
+ const retries = config.maxRetries ?? 2;
343
+ for (let attempt = 0;; attempt++) {
344
+ let response;
345
+ try {
346
+ response = await call.fetch(`${this.#base}${path}`, {
347
+ method: "POST",
348
+ headers,
349
+ body: JSON.stringify(body),
350
+ signal: call.signal,
351
+ });
352
+ }
353
+ catch (error) {
354
+ if (call.signal.aborted || isPolarisError(error))
355
+ throw error;
356
+ if (attempt < retries) {
357
+ await sleep(backoff(attempt, undefined), call.signal);
358
+ continue;
359
+ }
360
+ throw new E_POLARIS_PROVIDER_UNREACHABLE([
361
+ this.provider,
362
+ error instanceof Error ? error.message : String(error),
363
+ ], { cause: error });
364
+ }
365
+ if (response.ok)
366
+ return response;
367
+ const retryable = RETRYABLE.has(response.status) || response.status >= 500;
368
+ if (retryable && attempt < retries) {
369
+ await response.body?.cancel().catch(() => undefined);
370
+ await sleep(backoff(attempt, response.headers), call.signal);
371
+ continue;
372
+ }
373
+ throw await this.#failure(response);
374
+ }
375
+ }
376
+ async #failure(response) {
377
+ const text = await response.text().catch(() => "");
378
+ let message;
379
+ try {
380
+ const body = JSON.parse(text);
381
+ message = isRecord(body) ? errorMessage(body) : undefined;
382
+ }
383
+ catch {
384
+ message = undefined;
385
+ }
386
+ const detail = message ?? (text.slice(0, 300) || `HTTP ${response.status}`);
387
+ const id = response.headers.get("x-request-id");
388
+ return errorForStatus(this.provider, response.status, id ? `${detail} (request ${id})` : detail);
389
+ }
390
+ #toResponse(body, request) {
391
+ const choice = first(body.choices);
392
+ const message = choice !== undefined && isRecord(choice.message)
393
+ ? choice.message
394
+ : undefined;
395
+ if (message === undefined) {
396
+ throw new E_POLARIS_INVALID_RESPONSE([
397
+ this.provider,
398
+ "the reply has no message",
399
+ ]);
400
+ }
401
+ const rawCalls = list(message.tool_calls);
402
+ checkCallCount(rawCalls.length, this.provider);
403
+ const calls = rawCalls.filter(isRecord).map((raw) => {
404
+ const fn = isRecord(raw.function) ? raw.function : {};
405
+ const extra = {};
406
+ keepExtraFields(raw, extra);
407
+ return toToolCall({
408
+ id: typeof raw.id === "string" ? raw.id : "",
409
+ name: typeof fn.name === "string" ? fn.name : "",
410
+ arguments: typeof fn.arguments === "string" ? fn.arguments : "",
411
+ extra,
412
+ }, this.provider);
413
+ });
414
+ const text = typeof message.content === "string" ? message.content : "";
415
+ return createResponse({
416
+ id: typeof body.id === "string" ? body.id : "",
417
+ provider: this.provider,
418
+ model: typeof body.model === "string"
419
+ ? body.model
420
+ : (request.model ?? this.#config.model),
421
+ content: assistantContent(reasoningOf(message), text, calls),
422
+ stopReason: toStopReason(typeof choice?.finish_reason === "string"
423
+ ? choice.finish_reason
424
+ : undefined, calls.length > 0),
425
+ usage: toUsage(body.usage),
426
+ });
427
+ }
428
+ }
429
+ /** Reasoning, then text, then tool calls: the order a reply is written in. */
430
+ function assistantContent(reasoning, text, calls) {
431
+ const content = [];
432
+ if (reasoning !== "")
433
+ content.push({ type: "reasoning", text: reasoning });
434
+ if (text !== "")
435
+ content.push({ type: "text", text });
436
+ content.push(...calls);
437
+ return content;
438
+ }
439
+ /** The chat messages, the system prompt first. */
440
+ function toMessages(request, provider) {
441
+ const out = [];
442
+ if (request.system !== undefined) {
443
+ out.push({ role: "system", content: request.system });
444
+ }
445
+ for (const message of request.messages) {
446
+ out.push(...toMessage(message, provider));
447
+ }
448
+ return out;
449
+ }
450
+ /**
451
+ * The fields a tool call came with from `provider` and polaris does not
452
+ * model, to send back as they were; nothing for another provider's call.
453
+ */
454
+ function extraFieldsOf(part, provider) {
455
+ const origin = part.origin;
456
+ if (origin?.provider !== provider || !isRecord(origin.block))
457
+ return {};
458
+ const extra = {};
459
+ keepExtraFields(origin.block, extra);
460
+ return extra;
461
+ }
462
+ function toMessage(message, provider) {
463
+ if (message.role === "assistant") {
464
+ if (typeof message.content === "string") {
465
+ return [{ role: "assistant", content: message.content }];
466
+ }
467
+ // Reasoning and another provider's blocks have no place in this API's
468
+ // history: it rebuilds nothing from them.
469
+ const text = message.content
470
+ .map((part) => (part.type === "text" ? part.text : ""))
471
+ .join("");
472
+ const calls = message.content
473
+ .filter((part) => part.type === "tool_call")
474
+ .map((part) => ({
475
+ // First, so a kept field can never replace the call's own.
476
+ ...extraFieldsOf(part, provider),
477
+ id: part.id,
478
+ type: "function",
479
+ function: {
480
+ name: part.name,
481
+ arguments: JSON.stringify(part.input ?? {}),
482
+ },
483
+ }));
484
+ if (text === "" && calls.length === 0)
485
+ return [];
486
+ return [
487
+ {
488
+ role: "assistant",
489
+ content: text === "" ? null : text,
490
+ ...(calls.length > 0 ? { tool_calls: calls } : {}),
491
+ },
492
+ ];
493
+ }
494
+ if (typeof message.content === "string") {
495
+ return [{ role: "user", content: message.content }];
496
+ }
497
+ // A tool result is a message of its own here, and must follow the
498
+ // assistant turn that asked for it: results first, then the user's parts.
499
+ const results = message.content
500
+ .filter((part) => part.type === "tool_result")
501
+ .map((part) => ({
502
+ role: "tool",
503
+ tool_call_id: part.toolCallId,
504
+ content: part.content,
505
+ }));
506
+ const rest = message.content.filter((part) => part.type !== "tool_result");
507
+ if (rest.length === 0)
508
+ return results;
509
+ const content = rest.every((part) => part.type === "text")
510
+ ? rest.map((part) => (part.type === "text" ? part.text : "")).join("\n")
511
+ : rest.map((part) => part.type === "text"
512
+ ? { type: "text", text: part.text }
513
+ : {
514
+ type: "image_url",
515
+ image_url: { url: `data:${part.mediaType};base64,${part.data}` },
516
+ });
517
+ return [...results, { role: "user", content }];
518
+ }
519
+ function toToolCall(partial, provider) {
520
+ let input = {};
521
+ if (partial.arguments.trim() !== "") {
522
+ try {
523
+ input = JSON.parse(partial.arguments);
524
+ }
525
+ catch {
526
+ // Left as the string the model wrote: the application's validation
527
+ // refuses it, instead of polaris guessing what was meant.
528
+ input = partial.arguments;
529
+ }
530
+ }
531
+ const call = {
532
+ type: "tool_call",
533
+ id: partial.id,
534
+ name: partial.name,
535
+ input,
536
+ };
537
+ // Only a call that carries such fields gets an origin: the others stay as
538
+ // plain as every other provider's.
539
+ return Object.keys(partial.extra).length === 0
540
+ ? call
541
+ : { ...call, origin: { provider, block: partial.extra } };
542
+ }
543
+ /** Reasoning text where each service puts it: Groq and Ollama `reasoning`, Workers AI `reasoning_content`. */
544
+ function reasoningOf(value) {
545
+ if (typeof value.reasoning === "string")
546
+ return value.reasoning;
547
+ if (typeof value.reasoning_content === "string") {
548
+ return value.reasoning_content;
549
+ }
550
+ return "";
551
+ }
552
+ function toStopReason(reason, hasToolCalls) {
553
+ // Some servers (Ollama) finish a turn that calls tools with `stop`.
554
+ if (hasToolCalls)
555
+ return "tool_use";
556
+ switch (reason) {
557
+ case "stop":
558
+ return "end";
559
+ case "length":
560
+ return "max_tokens";
561
+ case "tool_calls":
562
+ case "function_call":
563
+ return "tool_use";
564
+ case "content_filter":
565
+ return "content_filter";
566
+ default:
567
+ return "other";
568
+ }
569
+ }
570
+ /**
571
+ * The usage of a reply, as reported: `createResponse` checks the counts, and
572
+ * marks the response's usage unknown when one cannot be right. A body with
573
+ * no `prompt_tokens` reported none.
574
+ */
575
+ function toUsage(usage) {
576
+ if (!isRecord(usage) || usage.prompt_tokens === undefined)
577
+ return undefined;
578
+ const details = isRecord(usage.prompt_tokens_details)
579
+ ? usage.prompt_tokens_details
580
+ : {};
581
+ // `prompt_tokens` counts the cached tokens too; polaris's input count does
582
+ // not. More cached tokens than prompt tokens leaves a negative count.
583
+ const cached = details.cached_tokens ?? 0;
584
+ return {
585
+ inputTokens: typeof usage.prompt_tokens === "number" && typeof cached === "number"
586
+ ? usage.prompt_tokens - cached
587
+ : usage.prompt_tokens,
588
+ outputTokens: usage.completion_tokens,
589
+ cacheReadTokens: cached,
590
+ cacheWriteTokens: 0,
591
+ };
592
+ }
593
+ /**
594
+ * The message of an error body: OpenAI's `{ error: { message } }`, Ollama's
595
+ * `{ error: "…" }`, Cloudflare's `{ errors: [{ message }] }`.
596
+ */
597
+ function errorMessage(body) {
598
+ if (typeof body.error === "string")
599
+ return body.error;
600
+ if (isRecord(body.error) && typeof body.error.message === "string") {
601
+ return body.error.message;
602
+ }
603
+ const firstError = first(body.errors);
604
+ if (firstError !== undefined && typeof firstError.message === "string") {
605
+ return firstError.message;
606
+ }
607
+ return undefined;
608
+ }
609
+ function providerOptions(request, provider) {
610
+ const value = request.providerOptions?.[provider];
611
+ if (value === undefined)
612
+ return {};
613
+ if (!isRecord(value)) {
614
+ throw new E_POLARIS_INVALID_REQUEST([
615
+ `providerOptions.${provider} must be an object of request fields`,
616
+ ]);
617
+ }
618
+ return { ...value };
619
+ }
620
+ function parseJson(text, provider) {
621
+ let value;
622
+ try {
623
+ value = JSON.parse(text);
624
+ }
625
+ catch {
626
+ throw new E_POLARIS_INVALID_RESPONSE([provider, "the reply is not JSON"]);
627
+ }
628
+ if (!isRecord(value)) {
629
+ throw new E_POLARIS_INVALID_RESPONSE([
630
+ provider,
631
+ "the reply is not a JSON object",
632
+ ]);
633
+ }
634
+ return value;
635
+ }
636
+ /**
637
+ * How long to wait before attempt `attempt + 1`: what the provider asked for
638
+ * (`retry-after-ms`, then `retry-after` in seconds or as a date), at most a
639
+ * minute; otherwise an exponential backoff with jitter.
640
+ */
641
+ function backoff(attempt, headers) {
642
+ const ms = Number(headers?.get("retry-after-ms"));
643
+ if (headers?.has("retry-after-ms") && Number.isFinite(ms) && ms >= 0) {
644
+ return Math.min(ms, MAX_RETRY_DELAY);
645
+ }
646
+ const after = headers?.get("retry-after");
647
+ if (after) {
648
+ const seconds = Number(after);
649
+ const wait = Number.isFinite(seconds)
650
+ ? seconds * 1000
651
+ : Date.parse(after) - Date.now();
652
+ if (Number.isFinite(wait) && wait >= 0) {
653
+ return Math.min(wait, MAX_RETRY_DELAY);
654
+ }
655
+ }
656
+ const exponential = BASE_RETRY_DELAY * 2 ** attempt;
657
+ return Math.min(exponential * (0.75 + Math.random() * 0.5), 8_000);
658
+ }
659
+ function sleep(ms, signal) {
660
+ if (signal.aborted)
661
+ return Promise.reject(signal.reason);
662
+ return new Promise((resolve, reject) => {
663
+ const onAbort = () => {
664
+ clearTimeout(timer);
665
+ reject(signal.reason);
666
+ };
667
+ const timer = setTimeout(() => {
668
+ signal.removeEventListener("abort", onAbort);
669
+ resolve();
670
+ }, ms);
671
+ signal.addEventListener("abort", onAbort, { once: true });
672
+ });
673
+ }
674
+ function isPolarisError(error) {
675
+ const code = error instanceof Error ? Reflect.get(error, "code") : undefined;
676
+ return typeof code === "string" && code.startsWith("E_POLARIS_");
677
+ }
678
+ function isRecord(value) {
679
+ return typeof value === "object" && value !== null && !Array.isArray(value);
680
+ }
681
+ function checkCallCount(count, provider) {
682
+ if (count > MAX_REPLY_TOOL_CALLS) {
683
+ throw new E_POLARIS_INVALID_RESPONSE([
684
+ provider,
685
+ `the reply calls more than ${MAX_REPLY_TOOL_CALLS} tools`,
686
+ ]);
687
+ }
688
+ }
689
+ function list(value) {
690
+ return Array.isArray(value) ? value : [];
691
+ }
692
+ function first(value) {
693
+ const head = list(value)[0];
694
+ return isRecord(head) ? head : undefined;
695
+ }
696
+ function isCount(value) {
697
+ return Number.isInteger(value) && value > 0;
698
+ }
699
+ //# sourceMappingURL=openai-compatible.js.map