@c9up/polaris 0.0.0-stage → 0.1.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 (128) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +542 -2
  3. package/dist/Polaris.d.ts +76 -0
  4. package/dist/Polaris.d.ts.map +1 -0
  5. package/dist/Polaris.js +194 -0
  6. package/dist/Polaris.js.map +1 -0
  7. package/dist/PolarisClient.d.ts +136 -0
  8. package/dist/PolarisClient.d.ts.map +1 -0
  9. package/dist/PolarisClient.js +408 -0
  10. package/dist/PolarisClient.js.map +1 -0
  11. package/dist/PolarisProvider.d.ts +35 -0
  12. package/dist/PolarisProvider.d.ts.map +1 -0
  13. package/dist/PolarisProvider.js +47 -0
  14. package/dist/PolarisProvider.js.map +1 -0
  15. package/dist/augmentations.d.ts +15 -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 +44 -0
  20. package/dist/budget.d.ts.map +1 -0
  21. package/dist/budget.js +67 -0
  22. package/dist/budget.js.map +1 -0
  23. package/dist/cost.d.ts +48 -0
  24. package/dist/cost.d.ts.map +1 -0
  25. package/dist/cost.js +126 -0
  26. package/dist/cost.js.map +1 -0
  27. package/dist/drivers/anthropic.d.ts +39 -0
  28. package/dist/drivers/anthropic.d.ts.map +1 -0
  29. package/dist/drivers/anthropic.js +394 -0
  30. package/dist/drivers/anthropic.js.map +1 -0
  31. package/dist/drivers/openai-compatible.d.ts +54 -0
  32. package/dist/drivers/openai-compatible.d.ts.map +1 -0
  33. package/dist/drivers/openai-compatible.js +663 -0
  34. package/dist/drivers/openai-compatible.js.map +1 -0
  35. package/dist/drivers/status.d.ts +8 -0
  36. package/dist/drivers/status.d.ts.map +1 -0
  37. package/dist/drivers/status.js +21 -0
  38. package/dist/drivers/status.js.map +1 -0
  39. package/dist/errors.d.ts +55 -0
  40. package/dist/errors.d.ts.map +1 -0
  41. package/dist/errors.js +62 -0
  42. package/dist/errors.js.map +1 -0
  43. package/dist/extract.d.ts +38 -0
  44. package/dist/extract.d.ts.map +1 -0
  45. package/dist/extract.js +144 -0
  46. package/dist/extract.js.map +1 -0
  47. package/dist/index.d.ts +19 -0
  48. package/dist/index.d.ts.map +1 -0
  49. package/dist/index.js +13 -0
  50. package/dist/index.js.map +1 -0
  51. package/dist/log.d.ts +47 -0
  52. package/dist/log.d.ts.map +1 -0
  53. package/dist/log.js +33 -0
  54. package/dist/log.js.map +1 -0
  55. package/dist/meter.d.ts +57 -0
  56. package/dist/meter.d.ts.map +1 -0
  57. package/dist/meter.js +91 -0
  58. package/dist/meter.js.map +1 -0
  59. package/dist/providers.d.ts +23 -0
  60. package/dist/providers.d.ts.map +1 -0
  61. package/dist/providers.js +21 -0
  62. package/dist/providers.js.map +1 -0
  63. package/dist/redact.d.ts +11 -0
  64. package/dist/redact.d.ts.map +1 -0
  65. package/dist/redact.js +76 -0
  66. package/dist/redact.js.map +1 -0
  67. package/dist/response.d.ts +21 -0
  68. package/dist/response.d.ts.map +1 -0
  69. package/dist/response.js +45 -0
  70. package/dist/response.js.map +1 -0
  71. package/dist/schema.d.ts +45 -0
  72. package/dist/schema.d.ts.map +1 -0
  73. package/dist/schema.js +43 -0
  74. package/dist/schema.js.map +1 -0
  75. package/dist/services/main.d.ts +23 -0
  76. package/dist/services/main.d.ts.map +1 -0
  77. package/dist/services/main.js +43 -0
  78. package/dist/services/main.js.map +1 -0
  79. package/dist/sse.d.ts +58 -0
  80. package/dist/sse.d.ts.map +1 -0
  81. package/dist/sse.js +91 -0
  82. package/dist/sse.js.map +1 -0
  83. package/dist/testing/FakeProvider.d.ts +85 -0
  84. package/dist/testing/FakeProvider.d.ts.map +1 -0
  85. package/dist/testing/FakeProvider.js +213 -0
  86. package/dist/testing/FakeProvider.js.map +1 -0
  87. package/dist/testing/index.d.ts +7 -0
  88. package/dist/testing/index.d.ts.map +1 -0
  89. package/dist/testing/index.js +7 -0
  90. package/dist/testing/index.js.map +1 -0
  91. package/dist/tools.d.ts +68 -0
  92. package/dist/tools.d.ts.map +1 -0
  93. package/dist/tools.js +107 -0
  94. package/dist/tools.js.map +1 -0
  95. package/dist/transport.d.ts +18 -0
  96. package/dist/transport.d.ts.map +1 -0
  97. package/dist/transport.js +68 -0
  98. package/dist/transport.js.map +1 -0
  99. package/dist/types.d.ts +293 -0
  100. package/dist/types.d.ts.map +1 -0
  101. package/dist/types.js +12 -0
  102. package/dist/types.js.map +1 -0
  103. package/package.json +76 -3
  104. package/src/Polaris.ts +280 -0
  105. package/src/PolarisClient.ts +591 -0
  106. package/src/PolarisProvider.ts +73 -0
  107. package/src/augmentations.ts +17 -0
  108. package/src/budget.ts +101 -0
  109. package/src/cost.ts +170 -0
  110. package/src/drivers/anthropic.ts +520 -0
  111. package/src/drivers/openai-compatible.ts +840 -0
  112. package/src/drivers/status.ts +30 -0
  113. package/src/errors.ts +161 -0
  114. package/src/extract.ts +214 -0
  115. package/src/index.ts +69 -0
  116. package/src/log.ts +84 -0
  117. package/src/meter.ts +188 -0
  118. package/src/providers.ts +25 -0
  119. package/src/redact.ts +78 -0
  120. package/src/response.ts +65 -0
  121. package/src/schema.ts +88 -0
  122. package/src/services/main.ts +49 -0
  123. package/src/sse.ts +128 -0
  124. package/src/testing/FakeProvider.ts +321 -0
  125. package/src/testing/index.ts +12 -0
  126. package/src/tools.ts +166 -0
  127. package/src/transport.ts +85 -0
  128. package/src/types.ts +328 -0
@@ -0,0 +1,520 @@
1
+ /**
2
+ * The Anthropic driver: Claude through the official SDK (`@anthropic-ai/sdk`,
3
+ * an optional peer, loaded on the first request).
4
+ *
5
+ * Requests go through the SDK's beta namespace, which is the general one plus
6
+ * the beta features (server-side refusal fallbacks among them): one request
7
+ * shape and one response shape whether or not a beta is turned on.
8
+ */
9
+
10
+ import type Anthropic from "@anthropic-ai/sdk";
11
+ import type { BetaMessageStreamParams } from "@anthropic-ai/sdk/resources/beta/messages/messages";
12
+ import {
13
+ E_POLARIS_INVALID_CONFIG,
14
+ E_POLARIS_INVALID_REQUEST,
15
+ E_POLARIS_PROVIDER_UNREACHABLE,
16
+ E_POLARIS_RESPONSE_TOO_LARGE,
17
+ } from "../errors.js";
18
+ import { MAX_TIMEOUT } from "../PolarisClient.js";
19
+
20
+ import { createResponse } from "../response.js";
21
+ import type {
22
+ AssistantPart,
23
+ ChatRequest,
24
+ ChatResponse,
25
+ DriverCall,
26
+ DriverDefaults,
27
+ DriverFeatures,
28
+ JsonSchema,
29
+ Message,
30
+ Origin,
31
+ PolarisDriver,
32
+ ProviderFactory,
33
+ StopReason,
34
+ StreamEvent,
35
+ ToolCallPart,
36
+ } from "../types.js";
37
+ import { errorForStatus } from "./status.js";
38
+
39
+ type Sdk = typeof Anthropic;
40
+ /** The request fields shared by a streamed and a one-shot request. */
41
+ type Params = BetaMessageStreamParams;
42
+ type BlockParam = Anthropic.Beta.BetaContentBlockParam;
43
+ type Block = Anthropic.Beta.BetaContentBlock;
44
+ type MessageParam = Anthropic.Beta.BetaMessageParam;
45
+
46
+ const PROVIDER = "anthropic";
47
+ /** What the server-side refusal fallback needs turned on. */
48
+ const FALLBACK_BETA = "server-side-fallback-2026-07-01";
49
+ /** Output limits when the request sets none: the SDK's own guidance. */
50
+ const DEFAULT_MAX_TOKENS = 16_000;
51
+ const DEFAULT_STREAM_MAX_TOKENS = 64_000;
52
+
53
+ export interface AnthropicConfig {
54
+ /** The model every request uses unless it names another. */
55
+ readonly model: string;
56
+ /**
57
+ * The API key. Without one, the SDK reads `ANTHROPIC_API_KEY` (or another
58
+ * credential it knows) from the environment. A per-call key overrides it.
59
+ */
60
+ readonly apiKey?: string;
61
+ /** Another endpoint speaking the Anthropic API. */
62
+ readonly baseURL?: string;
63
+ /** Output limit when a request sets none. Default 16 000, 64 000 for a stream. */
64
+ readonly maxTokens?: number;
65
+ /**
66
+ * Retries of a rate-limited, overloaded or failed request, honouring the
67
+ * provider's `retry-after`, all within the call's deadline. Default 2.
68
+ */
69
+ readonly maxRetries?: number;
70
+ /**
71
+ * Server-side fallback when the model declines a request: `'default'` lets
72
+ * the API pick the fallback model, or name them. Turns on its beta.
73
+ */
74
+ readonly fallbacks?: "default" | readonly { readonly model: string }[];
75
+ /** Further `anthropic-beta` flags sent with every request. */
76
+ readonly betas?: readonly string[];
77
+ }
78
+
79
+ const FEATURES: DriverFeatures = {
80
+ tools: true,
81
+ structuredOutput: true,
82
+ images: true,
83
+ };
84
+
85
+ /** A provider factory for Claude: `providers: { claude: anthropic({ model }) }`. */
86
+ export function anthropic(config: AnthropicConfig): ProviderFactory {
87
+ return () => new AnthropicDriver(config);
88
+ }
89
+
90
+ /** What the driver loads from the SDK on its first request. */
91
+ interface Loaded {
92
+ readonly Anthropic: Sdk;
93
+ /**
94
+ * The SDK's own rewrite of a JSON Schema into what Claude's structured
95
+ * output accepts: `additionalProperties: false` on every object, and the
96
+ * constraints it does not enforce (`minLength`, `minimum`…) moved into the
97
+ * description. polaris checks the answer against the full schema after.
98
+ */
99
+ readonly strictSchema: (
100
+ schema: Record<string, unknown>,
101
+ ) => Record<string, unknown>;
102
+ }
103
+
104
+ let loading: Promise<Loaded> | undefined;
105
+
106
+ function loadSdk(): Promise<Loaded> {
107
+ loading ??= Promise.all([
108
+ import("@anthropic-ai/sdk"),
109
+ import("@anthropic-ai/sdk/lib/transform-json-schema"),
110
+ ]).then(
111
+ ([sdk, transform]) => ({
112
+ Anthropic: sdk.default,
113
+ strictSchema: (schema) => transform.transformJSONSchema(schema),
114
+ }),
115
+ (cause: unknown) => {
116
+ loading = undefined;
117
+ throw new E_POLARIS_INVALID_CONFIG(
118
+ [
119
+ "the Anthropic driver needs @anthropic-ai/sdk; install it next to @c9up/polaris",
120
+ ],
121
+ { cause },
122
+ );
123
+ },
124
+ );
125
+ return loading;
126
+ }
127
+
128
+ class AnthropicDriver implements PolarisDriver {
129
+ readonly provider = PROVIDER;
130
+ readonly features = FEATURES;
131
+ readonly defaults: DriverDefaults;
132
+ readonly #config: AnthropicConfig;
133
+
134
+ constructor(config: AnthropicConfig) {
135
+ if (typeof config.model !== "string" || config.model.trim() === "") {
136
+ throw new E_POLARIS_INVALID_CONFIG([
137
+ "the Anthropic driver needs a `model`",
138
+ ]);
139
+ }
140
+ if (config.maxTokens !== undefined && !isCount(config.maxTokens)) {
141
+ throw new E_POLARIS_INVALID_CONFIG([
142
+ "the Anthropic driver's `maxTokens` must be a positive integer",
143
+ ]);
144
+ }
145
+ if (
146
+ config.maxRetries !== undefined &&
147
+ !(Number.isInteger(config.maxRetries) && config.maxRetries >= 0)
148
+ ) {
149
+ throw new E_POLARIS_INVALID_CONFIG([
150
+ "the Anthropic driver's `maxRetries` must be an integer, 0 or more",
151
+ ]);
152
+ }
153
+ this.#config = config;
154
+ this.defaults = {
155
+ model: config.model,
156
+ maxTokens: config.maxTokens ?? DEFAULT_MAX_TOKENS,
157
+ streamMaxTokens: config.maxTokens ?? DEFAULT_STREAM_MAX_TOKENS,
158
+ };
159
+ }
160
+
161
+ async chat(request: ChatRequest, call: DriverCall): Promise<ChatResponse> {
162
+ const { Anthropic: sdk, strictSchema } = await loadSdk();
163
+ const client = this.#client(sdk, call);
164
+ try {
165
+ const message = await client.beta.messages.create(
166
+ { ...this.#params(request, false, strictSchema), stream: false },
167
+ { signal: call.signal },
168
+ );
169
+ return toResponse(message);
170
+ } catch (error) {
171
+ throw toPolarisError(sdk, error);
172
+ }
173
+ }
174
+
175
+ async *stream(
176
+ request: ChatRequest,
177
+ call: DriverCall,
178
+ ): AsyncGenerator<StreamEvent, void, undefined> {
179
+ const { Anthropic: sdk, strictSchema } = await loadSdk();
180
+ const client = this.#client(sdk, call);
181
+ const stream = client.beta.messages.stream(
182
+ this.#params(request, true, strictSchema),
183
+ {
184
+ signal: call.signal,
185
+ },
186
+ );
187
+ let ended = false;
188
+ try {
189
+ for await (const event of stream) {
190
+ if (event.type === "content_block_delta") {
191
+ if (event.delta.type === "text_delta") {
192
+ yield { type: "text", text: event.delta.text };
193
+ } else if (event.delta.type === "thinking_delta") {
194
+ yield { type: "reasoning", text: event.delta.thinking };
195
+ }
196
+ } else if (event.type === "content_block_stop") {
197
+ // The SDK has parsed the tool's arguments by the time its block
198
+ // closes; before that they are a partial JSON string.
199
+ const block = stream.currentMessage?.content[event.index];
200
+ if (block?.type === "tool_use") {
201
+ yield { type: "tool_call", call: toToolCall(block) };
202
+ }
203
+ }
204
+ }
205
+ const response = toResponse(await stream.finalMessage());
206
+ ended = true;
207
+ yield { type: "done", response };
208
+ } catch (error) {
209
+ throw toPolarisError(sdk, error);
210
+ } finally {
211
+ if (!ended) stream.abort();
212
+ }
213
+ }
214
+
215
+ /** One client per call: the call's own key and its bounded `fetch`. */
216
+ #client(sdk: Sdk, call: DriverCall): Anthropic {
217
+ return new sdk({
218
+ apiKey: call.apiKey ?? this.#config.apiKey,
219
+ baseURL: this.#config.baseURL,
220
+ fetch: call.fetch,
221
+ maxRetries: this.#config.maxRetries ?? 2,
222
+ // polaris enforces the call's deadline through its signal. Set
223
+ // explicitly so the SDK does not refuse a long non-streamed request
224
+ // on a timeout of its own.
225
+ timeout: MAX_TIMEOUT,
226
+ });
227
+ }
228
+
229
+ #params(
230
+ request: ChatRequest,
231
+ streaming: boolean,
232
+ strictSchema: Loaded["strictSchema"],
233
+ ): Params {
234
+ const config = this.#config;
235
+ const extra = providerOptions(request);
236
+ const betas = [
237
+ ...(config.betas ?? []),
238
+ ...(config.fallbacks !== undefined ? [FALLBACK_BETA] : []),
239
+ ];
240
+ const outputConfig: Anthropic.Beta.BetaOutputConfig = {
241
+ ...(request.effort !== undefined ? { effort: request.effort } : {}),
242
+ ...(request.output !== undefined
243
+ ? {
244
+ format: {
245
+ type: "json_schema",
246
+ schema: outputSchema(strictSchema, request.output.schema),
247
+ },
248
+ }
249
+ : {}),
250
+ };
251
+ const tools = request.tools ?? [];
252
+
253
+ return {
254
+ ...extra,
255
+ model: request.model ?? config.model,
256
+ max_tokens:
257
+ request.maxTokens ??
258
+ config.maxTokens ??
259
+ (streaming ? DEFAULT_STREAM_MAX_TOKENS : DEFAULT_MAX_TOKENS),
260
+ messages: toMessageParams(request.messages),
261
+ ...(request.system !== undefined ? { system: request.system } : {}),
262
+ ...(tools.length > 0
263
+ ? {
264
+ tools: tools.map((tool) => ({
265
+ name: tool.name,
266
+ description: tool.description,
267
+ input_schema: inputSchema(tool.name, tool.inputSchema),
268
+ })),
269
+ }
270
+ : {}),
271
+ ...(request.toolChoice !== undefined
272
+ ? { tool_choice: { type: request.toolChoice } }
273
+ : {}),
274
+ ...(request.stopSequences !== undefined
275
+ ? { stop_sequences: [...request.stopSequences] }
276
+ : {}),
277
+ ...(Object.keys(outputConfig).length > 0
278
+ ? { output_config: outputConfig }
279
+ : {}),
280
+ ...(config.fallbacks !== undefined
281
+ ? {
282
+ fallbacks:
283
+ config.fallbacks === "default"
284
+ ? "default"
285
+ : config.fallbacks.map((fallback) => ({
286
+ model: fallback.model,
287
+ })),
288
+ }
289
+ : {}),
290
+ ...(betas.length > 0 ? { betas } : {}),
291
+ };
292
+ }
293
+ }
294
+
295
+ /** A structured output's schema as Claude takes it; a schema it cannot take is the request's fault. */
296
+ function outputSchema(
297
+ strictSchema: Loaded["strictSchema"],
298
+ schema: JsonSchema,
299
+ ): Record<string, unknown> {
300
+ try {
301
+ return strictSchema({ ...schema });
302
+ } catch (cause) {
303
+ throw new E_POLARIS_INVALID_REQUEST(
304
+ [
305
+ `the output schema cannot be sent to Claude: ${cause instanceof Error ? cause.message : String(cause)}`,
306
+ ],
307
+ { cause },
308
+ );
309
+ }
310
+ }
311
+
312
+ /** `providerOptions.anthropic`: raw request fields, sent as they are. */
313
+ function providerOptions(request: ChatRequest): Record<string, unknown> {
314
+ const value: unknown = request.providerOptions?.[PROVIDER];
315
+ if (value === undefined) return {};
316
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
317
+ throw new E_POLARIS_INVALID_REQUEST([
318
+ "providerOptions.anthropic must be an object of request fields",
319
+ ]);
320
+ }
321
+ return { ...value };
322
+ }
323
+
324
+ function inputSchema(
325
+ name: string,
326
+ schema: JsonSchema,
327
+ ): Anthropic.Beta.BetaTool.InputSchema {
328
+ if (schema.type !== undefined && schema.type !== "object") {
329
+ throw new E_POLARIS_INVALID_REQUEST([
330
+ `the input schema of tool '${name}' must describe an object`,
331
+ ]);
332
+ }
333
+ return { ...schema, type: "object" };
334
+ }
335
+
336
+ function toMessageParams(messages: readonly Message[]): MessageParam[] {
337
+ const params: MessageParam[] = [];
338
+ for (const message of messages) {
339
+ if (message.role === "user") {
340
+ params.push({
341
+ role: "user",
342
+ content:
343
+ typeof message.content === "string"
344
+ ? message.content
345
+ : message.content.map((part): BlockParam => {
346
+ if (part.type === "text")
347
+ return { type: "text", text: part.text };
348
+ if (part.type === "image") {
349
+ return {
350
+ type: "image",
351
+ source: {
352
+ type: "base64",
353
+ media_type: part.mediaType,
354
+ data: part.data,
355
+ },
356
+ };
357
+ }
358
+ return {
359
+ type: "tool_result",
360
+ tool_use_id: part.toolCallId,
361
+ content: part.content,
362
+ ...(part.isError ? { is_error: true } : {}),
363
+ };
364
+ }),
365
+ });
366
+ continue;
367
+ }
368
+
369
+ if (typeof message.content === "string") {
370
+ params.push({ role: "assistant", content: message.content });
371
+ continue;
372
+ }
373
+ const content = message.content.flatMap(toAssistantBlock);
374
+ // A turn left empty (only another provider's blocks) is dropped rather
375
+ // than sent empty, which the API refuses.
376
+ if (content.length > 0) params.push({ role: "assistant", content });
377
+ }
378
+ return params;
379
+ }
380
+
381
+ /** An assistant part as Claude takes it back: its own block when it has one. */
382
+ function toAssistantBlock(part: AssistantPart): BlockParam[] {
383
+ const own = ownBlock(part.origin);
384
+ if (own !== undefined) return [own];
385
+ switch (part.type) {
386
+ case "text":
387
+ return [{ type: "text", text: part.text }];
388
+ case "tool_call":
389
+ return [
390
+ { type: "tool_use", id: part.id, name: part.name, input: part.input },
391
+ ];
392
+ // Reasoning without Claude's signature, and another provider's blocks,
393
+ // cannot be sent: Claude would reject them.
394
+ case "reasoning":
395
+ case "provider":
396
+ return [];
397
+ }
398
+ }
399
+
400
+ /**
401
+ * The block an origin holds, when it is one this driver produced. It came
402
+ * from a Claude response, which the API takes back as a request block as it
403
+ * is; only its shape can be checked here.
404
+ */
405
+ function ownBlock(origin: Origin | undefined): BlockParam | undefined {
406
+ if (origin === undefined || origin.provider !== PROVIDER) return undefined;
407
+ return isBlockParam(origin.block) ? origin.block : undefined;
408
+ }
409
+
410
+ function isBlockParam(value: unknown): value is BlockParam {
411
+ return (
412
+ typeof value === "object" &&
413
+ value !== null &&
414
+ typeof Reflect.get(value, "type") === "string"
415
+ );
416
+ }
417
+
418
+ function toResponse(message: Anthropic.Beta.BetaMessage): ChatResponse {
419
+ return createResponse({
420
+ id: message.id,
421
+ provider: PROVIDER,
422
+ model: message.model,
423
+ content: message.content.map(toPart),
424
+ stopReason: toStopReason(message.stop_reason),
425
+ usage: {
426
+ inputTokens: message.usage.input_tokens,
427
+ outputTokens: message.usage.output_tokens,
428
+ cacheReadTokens: message.usage.cache_read_input_tokens ?? 0,
429
+ cacheWriteTokens: message.usage.cache_creation_input_tokens ?? 0,
430
+ },
431
+ });
432
+ }
433
+
434
+ function toPart(block: Block): AssistantPart {
435
+ const origin: Origin = { provider: PROVIDER, block };
436
+ switch (block.type) {
437
+ case "text":
438
+ return { type: "text", text: block.text, origin };
439
+ case "thinking":
440
+ return { type: "reasoning", text: block.thinking, origin };
441
+ case "redacted_thinking":
442
+ return { type: "reasoning", text: "", origin };
443
+ case "tool_use":
444
+ return toToolCall(block);
445
+ default:
446
+ return { type: "provider", origin };
447
+ }
448
+ }
449
+
450
+ function toToolCall(block: Anthropic.Beta.BetaToolUseBlock): ToolCallPart {
451
+ return {
452
+ type: "tool_call",
453
+ id: block.id,
454
+ name: block.name,
455
+ input: block.input,
456
+ origin: { provider: PROVIDER, block },
457
+ };
458
+ }
459
+
460
+ function toStopReason(
461
+ reason: Anthropic.Beta.BetaStopReason | null,
462
+ ): StopReason {
463
+ switch (reason) {
464
+ case "end_turn":
465
+ return "end";
466
+ case "max_tokens":
467
+ case "model_context_window_exceeded":
468
+ return "max_tokens";
469
+ case "stop_sequence":
470
+ return "stop_sequence";
471
+ case "tool_use":
472
+ return "tool_use";
473
+ case "pause_turn":
474
+ case "compaction":
475
+ return "pause";
476
+ case "refusal":
477
+ return "refusal";
478
+ default:
479
+ return "other";
480
+ }
481
+ }
482
+
483
+ /** The polaris error for what the SDK raised. */
484
+ function toPolarisError(sdk: Sdk, error: unknown): unknown {
485
+ // polaris's own bounds, which the SDK wraps when they fire inside `fetch`.
486
+ const bound = findCause(error, E_POLARIS_RESPONSE_TOO_LARGE);
487
+ if (bound !== undefined) return bound;
488
+ // A cancelled call: polaris reports it from the signal.
489
+ if (error instanceof sdk.APIUserAbortError) return error;
490
+
491
+ if (error instanceof sdk.APIConnectionError) {
492
+ return new E_POLARIS_PROVIDER_UNREACHABLE([PROVIDER, error.message], {
493
+ cause: error,
494
+ });
495
+ }
496
+ if (error instanceof sdk.APIError) {
497
+ const detail =
498
+ error.requestID != null
499
+ ? `${error.message} (request ${error.requestID})`
500
+ : error.message;
501
+ return errorForStatus(PROVIDER, error.status ?? 0, detail, error);
502
+ }
503
+ return error;
504
+ }
505
+
506
+ function findCause<T>(
507
+ error: unknown,
508
+ type: abstract new (...args: never[]) => T,
509
+ ): T | undefined {
510
+ let current: unknown = error;
511
+ for (let depth = 0; depth < 5 && current !== undefined; depth++) {
512
+ if (current instanceof type) return current;
513
+ current = current instanceof Error ? current.cause : undefined;
514
+ }
515
+ return undefined;
516
+ }
517
+
518
+ function isCount(value: number): boolean {
519
+ return Number.isInteger(value) && value > 0;
520
+ }