@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,321 @@
1
+ /**
2
+ * A provider that answers from a script, for tests: no network, no key.
3
+ *
4
+ * const fake = polaris.fake()
5
+ * fake.reply('Bonjour')
6
+ * await myAssistant.answer('hi')
7
+ * fake.assertSent((request) => request.system?.includes('newcomer'))
8
+ * polaris.restore()
9
+ *
10
+ * Every provider of the manager answers from the fake until `restore()`. It
11
+ * records each call, and reports usage, so cost and budget code runs as it
12
+ * would against a provider.
13
+ */
14
+
15
+ import {
16
+ E_POLARIS_ASSERTION_FAILED,
17
+ E_POLARIS_FAKE_NO_REPLY,
18
+ } from "../errors.js";
19
+ import { createResponse } from "../response.js";
20
+ import type {
21
+ AssistantPart,
22
+ ChatRequest,
23
+ ChatResponse,
24
+ DriverCall,
25
+ DriverFeatures,
26
+ EmbedRequest,
27
+ EmbedResponse,
28
+ PolarisDriver,
29
+ StopReason,
30
+ StreamEvent,
31
+ ToolCallPart,
32
+ Usage,
33
+ } from "../types.js";
34
+
35
+ /** One scripted reply. */
36
+ export interface FakeReply {
37
+ readonly text?: string;
38
+ readonly reasoning?: string;
39
+ readonly toolCalls?: readonly {
40
+ readonly name: string;
41
+ readonly input: unknown;
42
+ readonly id?: string;
43
+ }[];
44
+ /** Default: `tool_use` when the reply calls tools, `end` otherwise. */
45
+ readonly stopReason?: StopReason;
46
+ readonly usage?: Partial<Usage>;
47
+ /** Default: the request's model, or the fake's. */
48
+ readonly model?: string;
49
+ /** How a stream sends the text. Default: the whole text in one event. */
50
+ readonly chunks?: readonly string[];
51
+ }
52
+
53
+ export interface FakeOptions {
54
+ /** What the fake provider supports. Default: everything. */
55
+ readonly features?: Partial<DriverFeatures>;
56
+ /** The model it answers with when a request names none. Default `fake-model`. */
57
+ readonly model?: string;
58
+ /** Its embedding model. Default `fake-embedding`. */
59
+ readonly embeddingModel?: string;
60
+ /** The length of the vectors it returns. Default 8. */
61
+ readonly dimensions?: number;
62
+ /** Its output limit for a request that sets none, for budget estimates. Default 1 000. */
63
+ readonly maxTokens?: number;
64
+ }
65
+
66
+ /** A call the fake received. */
67
+ export interface FakeCall {
68
+ readonly operation: "chat" | "stream" | "embed";
69
+ /** The provider's name in the config. */
70
+ readonly provider: string;
71
+ readonly request: ChatRequest | EmbedRequest;
72
+ /** The per-call key, if one was given. */
73
+ readonly apiKey: string | undefined;
74
+ }
75
+
76
+ type Step = (request: ChatRequest) => ChatResponse | Promise<never>;
77
+
78
+ export class FakeProvider {
79
+ readonly #options: FakeOptions;
80
+ readonly #steps: Step[] = [];
81
+ readonly #calls: FakeCall[] = [];
82
+ #embedding: (input: string) => readonly number[];
83
+
84
+ constructor(options: FakeOptions = {}) {
85
+ this.#options = options;
86
+ const dimensions = options.dimensions ?? 8;
87
+ this.#embedding = (input) => deterministicVector(input, dimensions);
88
+ }
89
+
90
+ /** Answer the next request with `reply`: a text, or a scripted reply. */
91
+ reply(reply: string | FakeReply): this {
92
+ const scripted: FakeReply =
93
+ typeof reply === "string" ? { text: reply } : reply;
94
+ this.#steps.push((request) => this.#response(request, scripted));
95
+ return this;
96
+ }
97
+
98
+ /**
99
+ * Answer the next request with `value` as structured output: as JSON text
100
+ * when the request asks for structured output, as a call to its tool when
101
+ * it asks through a tool.
102
+ */
103
+ replyJson(
104
+ value: unknown,
105
+ extra: Omit<FakeReply, "text" | "toolCalls"> = {},
106
+ ): this {
107
+ this.#steps.push((request) => {
108
+ const tool =
109
+ request.output === undefined ? request.tools?.[0] : undefined;
110
+ return this.#response(
111
+ request,
112
+ tool
113
+ ? { ...extra, toolCalls: [{ name: tool.name, input: value }] }
114
+ : { ...extra, text: JSON.stringify(value) },
115
+ );
116
+ });
117
+ return this;
118
+ }
119
+
120
+ /** Answer the next request with a call to the tool `name`. */
121
+ callTool(name: string, input: unknown, id?: string): this {
122
+ return this.reply({
123
+ toolCalls: [{ name, input, ...(id !== undefined ? { id } : {}) }],
124
+ });
125
+ }
126
+
127
+ /** Make the next request fail with `error`. */
128
+ fail(error: unknown): this {
129
+ this.#steps.push(() => Promise.reject(error));
130
+ return this;
131
+ }
132
+
133
+ /** Compute each input's vector with `embed` instead of the fake's own. */
134
+ embedWith(embed: (input: string) => readonly number[]): this {
135
+ this.#embedding = embed;
136
+ return this;
137
+ }
138
+
139
+ /** Every call received, in order. */
140
+ get calls(): readonly FakeCall[] {
141
+ return this.#calls;
142
+ }
143
+
144
+ /** The chat and stream requests received, in order. */
145
+ get requests(): readonly ChatRequest[] {
146
+ return this.#calls.flatMap((call) =>
147
+ call.operation === "embed" || !isChat(call.request) ? [] : [call.request],
148
+ );
149
+ }
150
+
151
+ /** Replies scripted and not used yet. */
152
+ get pending(): number {
153
+ return this.#steps.length;
154
+ }
155
+
156
+ /** Fail unless a chat or stream request matching `matches` was received. */
157
+ assertSent(matches: (request: ChatRequest) => boolean = () => true): void {
158
+ if (!this.requests.some(matches)) {
159
+ throw new E_POLARIS_ASSERTION_FAILED([
160
+ "assertSent",
161
+ `no request out of ${this.requests.length} matched`,
162
+ ]);
163
+ }
164
+ }
165
+
166
+ /** Fail if a chat or stream request matching `matches` was received. */
167
+ assertNotSent(matches: (request: ChatRequest) => boolean = () => true): void {
168
+ const count = this.requests.filter(matches).length;
169
+ if (count > 0) {
170
+ throw new E_POLARIS_ASSERTION_FAILED([
171
+ "assertNotSent",
172
+ `${count} requests matched`,
173
+ ]);
174
+ }
175
+ }
176
+
177
+ /** Fail unless exactly `count` chat and stream requests were received. */
178
+ assertSentCount(count: number): void {
179
+ if (this.requests.length !== count) {
180
+ throw new E_POLARIS_ASSERTION_FAILED([
181
+ "assertSentCount",
182
+ `expected ${count} requests, received ${this.requests.length}`,
183
+ ]);
184
+ }
185
+ }
186
+
187
+ /** The driver this fake stands in with, for the provider named `name`. */
188
+ driver(name: string): PolarisDriver {
189
+ const options = this.#options;
190
+ const record = (
191
+ operation: FakeCall["operation"],
192
+ request: ChatRequest | EmbedRequest,
193
+ call: DriverCall,
194
+ ) => this.#record(operation, name, request, call);
195
+ const next = (request: ChatRequest) => this.#next(request);
196
+ const chunksOf = (response: ChatResponse) => this.#chunks.get(response);
197
+ const embed = (request: EmbedRequest) => this.#embed(request);
198
+ return {
199
+ provider: "fake",
200
+ features: {
201
+ tools: true,
202
+ structuredOutput: true,
203
+ images: true,
204
+ ...options.features,
205
+ },
206
+ defaults: {
207
+ model: options.model ?? "fake-model",
208
+ embeddingModel: options.embeddingModel ?? "fake-embedding",
209
+ maxTokens: options.maxTokens ?? 1_000,
210
+ streamMaxTokens: options.maxTokens ?? 1_000,
211
+ },
212
+ async chat(request, call) {
213
+ record("chat", request, call);
214
+ return next(request);
215
+ },
216
+ async *stream(request, call) {
217
+ record("stream", request, call);
218
+ const response = await next(request);
219
+ yield* streamOf(response, chunksOf(response));
220
+ },
221
+ async embed(request, call) {
222
+ record("embed", request, call);
223
+ return embed(request);
224
+ },
225
+ };
226
+ }
227
+
228
+ /** The chunks a reply streams its text in, when it was scripted with some. */
229
+ readonly #chunks = new WeakMap<ChatResponse, readonly string[]>();
230
+
231
+ #record(
232
+ operation: FakeCall["operation"],
233
+ provider: string,
234
+ request: ChatRequest | EmbedRequest,
235
+ call: DriverCall,
236
+ ): void {
237
+ this.#calls.push({ operation, provider, request, apiKey: call.apiKey });
238
+ }
239
+
240
+ async #next(request: ChatRequest): Promise<ChatResponse> {
241
+ const step = this.#steps.shift();
242
+ if (step === undefined) throw new E_POLARIS_FAKE_NO_REPLY();
243
+ return step(request);
244
+ }
245
+
246
+ #response(request: ChatRequest, reply: FakeReply): ChatResponse {
247
+ const calls: ToolCallPart[] = (reply.toolCalls ?? []).map(
248
+ (call, index) => ({
249
+ type: "tool_call",
250
+ id: call.id ?? `call_${this.#calls.length}_${index}`,
251
+ name: call.name,
252
+ input: call.input,
253
+ }),
254
+ );
255
+ const content: AssistantPart[] = [];
256
+ if (reply.reasoning !== undefined)
257
+ content.push({ type: "reasoning", text: reply.reasoning });
258
+ if (reply.text !== undefined && reply.text !== "")
259
+ content.push({ type: "text", text: reply.text });
260
+ content.push(...calls);
261
+ const response = createResponse({
262
+ id: `fake_${this.#calls.length}`,
263
+ provider: "fake",
264
+ model:
265
+ reply.model ?? request.model ?? this.#options.model ?? "fake-model",
266
+ content,
267
+ stopReason: reply.stopReason ?? (calls.length > 0 ? "tool_use" : "end"),
268
+ usage: { inputTokens: 10, outputTokens: 10, ...reply.usage },
269
+ });
270
+ if (reply.chunks !== undefined) this.#chunks.set(response, reply.chunks);
271
+ return response;
272
+ }
273
+
274
+ #embed(request: EmbedRequest): EmbedResponse {
275
+ const vectors = request.inputs.map((input) =>
276
+ Float32Array.from(this.#embedding(input)),
277
+ );
278
+ return {
279
+ provider: "fake",
280
+ model: request.model ?? this.#options.embeddingModel ?? "fake-embedding",
281
+ dimensions: vectors[0]?.length ?? 0,
282
+ vectors,
283
+ usage: {
284
+ inputTokens: request.inputs.reduce(
285
+ (total, input) => total + input.length,
286
+ 0,
287
+ ),
288
+ },
289
+ };
290
+ }
291
+ }
292
+
293
+ /** The events a stream of `response` yields: reasoning, the text in chunks, the tool calls, done. */
294
+ function* streamOf(
295
+ response: ChatResponse,
296
+ chunks: readonly string[] | undefined,
297
+ ): Generator<StreamEvent> {
298
+ for (const part of response.message.content) {
299
+ if (part.type === "reasoning") yield { type: "reasoning", text: part.text };
300
+ }
301
+ for (const text of chunks ?? (response.text === "" ? [] : [response.text])) {
302
+ yield { type: "text", text };
303
+ }
304
+ for (const call of response.toolCalls) yield { type: "tool_call", call };
305
+ yield { type: "done", response };
306
+ }
307
+
308
+ /** A vector that depends only on the text: the same input always lands at the same place. */
309
+ function deterministicVector(input: string, dimensions: number): number[] {
310
+ const vector = new Array<number>(dimensions).fill(0);
311
+ for (let index = 0; index < input.length; index++) {
312
+ const slot = index % dimensions;
313
+ vector[slot] = ((vector[slot] ?? 0) + input.charCodeAt(index)) % 1_000;
314
+ }
315
+ const norm = Math.hypot(...vector) || 1;
316
+ return vector.map((value) => value / norm);
317
+ }
318
+
319
+ function isChat(request: ChatRequest | EmbedRequest): request is ChatRequest {
320
+ return "messages" in request;
321
+ }
@@ -0,0 +1,12 @@
1
+ /**
2
+ * `@c9up/polaris/testing`: the provider that answers from a script.
3
+ * `polaris.fake()` hands one out; build one yourself to declare it as a
4
+ * provider: `providers: { main: () => fake.driver('main') }`.
5
+ */
6
+
7
+ export {
8
+ type FakeCall,
9
+ type FakeOptions,
10
+ FakeProvider,
11
+ type FakeReply,
12
+ } from "./FakeProvider.js";
package/src/tools.ts ADDED
@@ -0,0 +1,166 @@
1
+ /**
2
+ * Tools the model may call, and the loop that runs them.
3
+ *
4
+ * A tool's input is described by a {@link StandardSchema}: a rune schema
5
+ * (`rune.create({...})`) is one.
6
+ */
7
+
8
+ import {
9
+ E_POLARIS_INVALID_REQUEST,
10
+ E_POLARIS_TOO_MANY_STEPS,
11
+ } from "./errors.js";
12
+ import {
13
+ describeIssues,
14
+ objectJsonSchema,
15
+ type SchemaOutput,
16
+ type SchemaResult,
17
+ type StandardSchema,
18
+ } from "./schema.js";
19
+ import type { ToolCallPart, ToolDefinition, ToolResultPart } from "./types.js";
20
+
21
+ /** What a tool's handler is given besides its input. */
22
+ export interface ToolContext {
23
+ /** The call's id, as the model gave it. */
24
+ readonly toolCallId: string;
25
+ /** Aborted when the run is cancelled or runs out of time. */
26
+ readonly signal: AbortSignal;
27
+ }
28
+
29
+ /**
30
+ * An error whose message the model may read. Throw it from a handler to tell
31
+ * the model what went wrong ("No canton named 'Genf'"); every other error
32
+ * reaches the model as a bare "the tool failed", so its message, stack and
33
+ * whatever secret it carries stay on the server.
34
+ */
35
+ export class ToolError extends Error {
36
+ constructor(message: string) {
37
+ super(message);
38
+ this.name = "ToolError";
39
+ }
40
+ }
41
+
42
+ /** A tool as `defineTool()` builds it. */
43
+ export interface PolarisTool {
44
+ readonly name: string;
45
+ /** What is sent to the model. */
46
+ readonly definition: ToolDefinition;
47
+ /** Validate the model's input, then run the handler. Never throws. */
48
+ execute(call: ToolCallPart, context: ToolContext): Promise<ToolOutcome>;
49
+ }
50
+
51
+ /** How one tool call went. */
52
+ export type ToolOutcome =
53
+ | { readonly ok: true; readonly content: string }
54
+ | {
55
+ readonly ok: false;
56
+ readonly content: string;
57
+ /** What failed, for the application's logs. Never shown to the model. */
58
+ readonly error: unknown;
59
+ };
60
+
61
+ export interface ToolSpec<S extends StandardSchema> {
62
+ readonly name: string;
63
+ readonly description: string;
64
+ readonly schema: S;
65
+ /**
66
+ * Runs once the input passed the schema. A string goes to the model as it
67
+ * is; anything else is sent as JSON.
68
+ */
69
+ run(input: SchemaOutput<S>, context: ToolContext): unknown;
70
+ }
71
+
72
+ const TOOL_NAME = /^[a-zA-Z0-9_-]{1,64}$/;
73
+ const FAILED = "The tool failed.";
74
+
75
+ /**
76
+ * Declare a tool. Its input is typed by its schema:
77
+ *
78
+ * const lookup = defineTool({
79
+ * name: 'canton_rule',
80
+ * description: 'Look up a tax rule for a Swiss canton',
81
+ * schema: rune.create({ canton: rune.string() }),
82
+ * run: async ({ canton }) => rules.find(canton),
83
+ * })
84
+ */
85
+ export function defineTool<S extends StandardSchema>(
86
+ spec: ToolSpec<S>,
87
+ ): PolarisTool {
88
+ if (!TOOL_NAME.test(spec.name)) {
89
+ throw new E_POLARIS_INVALID_REQUEST([
90
+ `a tool name is 1 to 64 letters, digits, '_' or '-'; '${spec.name}' is not`,
91
+ ]);
92
+ }
93
+ const standard = spec.schema["~standard"];
94
+ const inputSchema = objectJsonSchema(spec.schema, `tool '${spec.name}'`);
95
+
96
+ return {
97
+ name: spec.name,
98
+ definition: { name: spec.name, description: spec.description, inputSchema },
99
+ async execute(call, context) {
100
+ let result: SchemaResult<SchemaOutput<S>>;
101
+ try {
102
+ result = await standard.validate(call.input);
103
+ } catch (error) {
104
+ return { ok: false, content: FAILED, error };
105
+ }
106
+ if (result.issues !== undefined) {
107
+ return {
108
+ ok: false,
109
+ content: `Invalid input: ${describeIssues(result.issues)}`,
110
+ error: result.issues,
111
+ };
112
+ }
113
+ try {
114
+ return {
115
+ ok: true,
116
+ content: toContent(await spec.run(result.value, context)),
117
+ };
118
+ } catch (error) {
119
+ return {
120
+ ok: false,
121
+ content: error instanceof ToolError ? error.message : FAILED,
122
+ error,
123
+ };
124
+ }
125
+ },
126
+ };
127
+ }
128
+
129
+ function toContent(value: unknown): string {
130
+ if (typeof value === "string") return value;
131
+ if (value === undefined) return "";
132
+ return JSON.stringify(value);
133
+ }
134
+
135
+ /** Run every call of one turn, at once, and answer them in one message. */
136
+ export async function runToolCalls(
137
+ calls: readonly ToolCallPart[],
138
+ tools: ReadonlyMap<string, PolarisTool>,
139
+ signal: AbortSignal,
140
+ onToolError: ((error: unknown, call: ToolCallPart) => void) | undefined,
141
+ ): Promise<ToolResultPart[]> {
142
+ return Promise.all(
143
+ calls.map(async (call): Promise<ToolResultPart> => {
144
+ const tool = tools.get(call.name);
145
+ const outcome: ToolOutcome = tool
146
+ ? await tool.execute(call, { toolCallId: call.id, signal })
147
+ : {
148
+ ok: false,
149
+ content: `There is no tool named '${call.name}'.`,
150
+ error: new Error(`unknown tool '${call.name}'`),
151
+ };
152
+ if (!outcome.ok) onToolError?.(outcome.error, call);
153
+ return {
154
+ type: "tool_result",
155
+ toolCallId: call.id,
156
+ content: outcome.content,
157
+ ...(outcome.ok ? {} : { isError: true }),
158
+ };
159
+ }),
160
+ );
161
+ }
162
+
163
+ /** The error a run raises when it is still calling tools at its last step. */
164
+ export function tooManySteps(maxSteps: number): Error {
165
+ return new E_POLARIS_TOO_MANY_STEPS([maxSteps]);
166
+ }
@@ -0,0 +1,85 @@
1
+ import { E_POLARIS_RESPONSE_TOO_LARGE } from "./errors.js";
2
+ import type { Transport } from "./types.js";
3
+
4
+ /** Statuses whose response has no body by definition. */
5
+ const NULL_BODY_STATUSES = new Set([101, 103, 204, 205, 304]);
6
+
7
+ /**
8
+ * Wrap `base` so every request it sends carries `signal`, and no response body
9
+ * longer than `maxBytes` is read.
10
+ *
11
+ * The size is counted on the bytes as they arrive, not taken from
12
+ * `Content-Length` alone: a compressed or chunked body announces nothing true
13
+ * about what it will decode to. A declared length over the bound is refused
14
+ * before reading anything.
15
+ */
16
+ export function boundFetch(
17
+ base: Transport,
18
+ signal: AbortSignal,
19
+ maxBytes: number,
20
+ ): Transport {
21
+ return async (input, init) => {
22
+ const own = init?.signal;
23
+ const response = await base(input, {
24
+ ...init,
25
+ signal: own ? AbortSignal.any([signal, own]) : signal,
26
+ });
27
+
28
+ const declared = Number(response.headers.get("content-length"));
29
+ if (Number.isFinite(declared) && declared > maxBytes) {
30
+ await response.body?.cancel().catch(() => undefined);
31
+ throw new E_POLARIS_RESPONSE_TOO_LARGE([maxBytes]);
32
+ }
33
+ if (response.body === null || NULL_BODY_STATUSES.has(response.status)) {
34
+ return response;
35
+ }
36
+
37
+ let seen = 0;
38
+ const limited = response.body.pipeThrough(
39
+ new TransformStream<Uint8Array, Uint8Array>({
40
+ transform(chunk, controller) {
41
+ seen += chunk.byteLength;
42
+ if (seen > maxBytes) {
43
+ controller.error(new E_POLARIS_RESPONSE_TOO_LARGE([maxBytes]));
44
+ return;
45
+ }
46
+ controller.enqueue(chunk);
47
+ },
48
+ }),
49
+ );
50
+ return new Response(limited, {
51
+ status: response.status,
52
+ statusText: response.statusText,
53
+ headers: response.headers,
54
+ });
55
+ };
56
+ }
57
+
58
+ /**
59
+ * Settle with `promise`, or reject with `signal.reason` as soon as `signal`
60
+ * aborts — so a driver that ignores its signal still cannot outlive the
61
+ * deadline.
62
+ */
63
+ export function untilAborted<T>(
64
+ promise: Promise<T>,
65
+ signal: AbortSignal,
66
+ ): Promise<T> {
67
+ if (signal.aborted) {
68
+ promise.catch(() => undefined);
69
+ return Promise.reject(signal.reason);
70
+ }
71
+ return new Promise<T>((resolve, reject) => {
72
+ const onAbort = () => reject(signal.reason);
73
+ signal.addEventListener("abort", onAbort, { once: true });
74
+ promise.then(
75
+ (value) => {
76
+ signal.removeEventListener("abort", onAbort);
77
+ resolve(value);
78
+ },
79
+ (error: unknown) => {
80
+ signal.removeEventListener("abort", onAbort);
81
+ reject(error);
82
+ },
83
+ );
84
+ });
85
+ }