@c9up/polaris 0.1.0 → 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 (217) hide show
  1. package/README.md +614 -10
  2. package/dist/Polaris.d.ts +6 -2
  3. package/dist/Polaris.d.ts.map +1 -1
  4. package/dist/Polaris.js +14 -0
  5. package/dist/Polaris.js.map +1 -1
  6. package/dist/PolarisClient.d.ts +51 -3
  7. package/dist/PolarisClient.d.ts.map +1 -1
  8. package/dist/PolarisClient.js +213 -45
  9. package/dist/PolarisClient.js.map +1 -1
  10. package/dist/PolarisProvider.d.ts +7 -2
  11. package/dist/PolarisProvider.d.ts.map +1 -1
  12. package/dist/PolarisProvider.js +34 -2
  13. package/dist/PolarisProvider.js.map +1 -1
  14. package/dist/augmentations.d.ts +4 -1
  15. package/dist/augmentations.d.ts.map +1 -1
  16. package/dist/augmentations.js +1 -1
  17. package/dist/budget.d.ts +39 -6
  18. package/dist/budget.d.ts.map +1 -1
  19. package/dist/budget.js +79 -12
  20. package/dist/budget.js.map +1 -1
  21. package/dist/catalog/catalog.d.ts +37 -0
  22. package/dist/catalog/catalog.d.ts.map +1 -0
  23. package/dist/catalog/catalog.js +145 -0
  24. package/dist/catalog/catalog.js.map +1 -0
  25. package/dist/catalog/discover.d.ts +64 -0
  26. package/dist/catalog/discover.d.ts.map +1 -0
  27. package/dist/catalog/discover.js +148 -0
  28. package/dist/catalog/discover.js.map +1 -0
  29. package/dist/catalog/index.d.ts +8 -0
  30. package/dist/catalog/index.d.ts.map +1 -0
  31. package/dist/catalog/index.js +8 -0
  32. package/dist/catalog/index.js.map +1 -0
  33. package/dist/commands/index.d.ts +82 -0
  34. package/dist/commands/index.d.ts.map +1 -0
  35. package/dist/commands/index.js +278 -0
  36. package/dist/commands/index.js.map +1 -0
  37. package/dist/cost.d.ts +3 -1
  38. package/dist/cost.d.ts.map +1 -1
  39. package/dist/cost.js +8 -3
  40. package/dist/cost.js.map +1 -1
  41. package/dist/drivers/anthropic.d.ts +6 -1
  42. package/dist/drivers/anthropic.d.ts.map +1 -1
  43. package/dist/drivers/anthropic.js +166 -21
  44. package/dist/drivers/anthropic.js.map +1 -1
  45. package/dist/drivers/openai-compatible.d.ts +1 -1
  46. package/dist/drivers/openai-compatible.d.ts.map +1 -1
  47. package/dist/drivers/openai-compatible.js +106 -70
  48. package/dist/drivers/openai-compatible.js.map +1 -1
  49. package/dist/errors.d.ts +24 -0
  50. package/dist/errors.d.ts.map +1 -1
  51. package/dist/errors.js +24 -0
  52. package/dist/errors.js.map +1 -1
  53. package/dist/index.d.ts +6 -4
  54. package/dist/index.d.ts.map +1 -1
  55. package/dist/index.js +3 -1
  56. package/dist/index.js.map +1 -1
  57. package/dist/json-schema.d.ts +33 -0
  58. package/dist/json-schema.d.ts.map +1 -0
  59. package/dist/json-schema.js +508 -0
  60. package/dist/json-schema.js.map +1 -0
  61. package/dist/log.d.ts.map +1 -1
  62. package/dist/log.js +3 -1
  63. package/dist/log.js.map +1 -1
  64. package/dist/mcp/client.d.ts +81 -0
  65. package/dist/mcp/client.d.ts.map +1 -0
  66. package/dist/mcp/client.js +401 -0
  67. package/dist/mcp/client.js.map +1 -0
  68. package/dist/mcp/endpoint.d.ts +54 -0
  69. package/dist/mcp/endpoint.d.ts.map +1 -0
  70. package/dist/mcp/endpoint.js +158 -0
  71. package/dist/mcp/endpoint.js.map +1 -0
  72. package/dist/mcp/host.d.ts +42 -0
  73. package/dist/mcp/host.d.ts.map +1 -0
  74. package/dist/mcp/host.js +111 -0
  75. package/dist/mcp/host.js.map +1 -0
  76. package/dist/mcp/http.d.ts +32 -0
  77. package/dist/mcp/http.d.ts.map +1 -0
  78. package/dist/mcp/http.js +190 -0
  79. package/dist/mcp/http.js.map +1 -0
  80. package/dist/mcp/index.d.ts +23 -0
  81. package/dist/mcp/index.d.ts.map +1 -0
  82. package/dist/mcp/index.js +21 -0
  83. package/dist/mcp/index.js.map +1 -0
  84. package/dist/mcp/manifest.d.ts +36 -0
  85. package/dist/mcp/manifest.d.ts.map +1 -0
  86. package/dist/mcp/manifest.js +40 -0
  87. package/dist/mcp/manifest.js.map +1 -0
  88. package/dist/mcp/rpc.d.ts +39 -0
  89. package/dist/mcp/rpc.d.ts.map +1 -0
  90. package/dist/mcp/rpc.js +149 -0
  91. package/dist/mcp/rpc.js.map +1 -0
  92. package/dist/mcp/stdio.d.ts +24 -0
  93. package/dist/mcp/stdio.d.ts.map +1 -0
  94. package/dist/mcp/stdio.js +157 -0
  95. package/dist/mcp/stdio.js.map +1 -0
  96. package/dist/mcp/worker-main.d.ts +6 -0
  97. package/dist/mcp/worker-main.d.ts.map +1 -0
  98. package/dist/mcp/worker-main.js +17 -0
  99. package/dist/mcp/worker-main.js.map +1 -0
  100. package/dist/mcp/worker.d.ts +54 -0
  101. package/dist/mcp/worker.d.ts.map +1 -0
  102. package/dist/mcp/worker.js +166 -0
  103. package/dist/mcp/worker.js.map +1 -0
  104. package/dist/meter.d.ts +6 -0
  105. package/dist/meter.d.ts.map +1 -1
  106. package/dist/meter.js +6 -3
  107. package/dist/meter.js.map +1 -1
  108. package/dist/redact.d.ts +4 -3
  109. package/dist/redact.d.ts.map +1 -1
  110. package/dist/redact.js +5 -4
  111. package/dist/redact.js.map +1 -1
  112. package/dist/redis-budget.d.ts +45 -0
  113. package/dist/redis-budget.d.ts.map +1 -0
  114. package/dist/redis-budget.js +56 -0
  115. package/dist/redis-budget.js.map +1 -0
  116. package/dist/response.d.ts +21 -3
  117. package/dist/response.d.ts.map +1 -1
  118. package/dist/response.js +71 -7
  119. package/dist/response.js.map +1 -1
  120. package/dist/server-sent.d.ts +9 -0
  121. package/dist/server-sent.d.ts.map +1 -0
  122. package/dist/server-sent.js +74 -0
  123. package/dist/server-sent.js.map +1 -0
  124. package/dist/server-tools.d.ts +12 -0
  125. package/dist/server-tools.d.ts.map +1 -0
  126. package/dist/server-tools.js +71 -0
  127. package/dist/server-tools.js.map +1 -0
  128. package/dist/services/catalog.d.ts +19 -0
  129. package/dist/services/catalog.d.ts.map +1 -0
  130. package/dist/services/catalog.js +37 -0
  131. package/dist/services/catalog.js.map +1 -0
  132. package/dist/skills/folder.d.ts +32 -0
  133. package/dist/skills/folder.d.ts.map +1 -0
  134. package/dist/skills/folder.js +170 -0
  135. package/dist/skills/folder.js.map +1 -0
  136. package/dist/skills/frontmatter.d.ts +15 -0
  137. package/dist/skills/frontmatter.d.ts.map +1 -0
  138. package/dist/skills/frontmatter.js +92 -0
  139. package/dist/skills/frontmatter.js.map +1 -0
  140. package/dist/skills/index.d.ts +18 -0
  141. package/dist/skills/index.d.ts.map +1 -0
  142. package/dist/skills/index.js +18 -0
  143. package/dist/skills/index.js.map +1 -0
  144. package/dist/skills/kit.d.ts +39 -0
  145. package/dist/skills/kit.d.ts.map +1 -0
  146. package/dist/skills/kit.js +124 -0
  147. package/dist/skills/kit.js.map +1 -0
  148. package/dist/skills/skill.d.ts +67 -0
  149. package/dist/skills/skill.d.ts.map +1 -0
  150. package/dist/skills/skill.js +114 -0
  151. package/dist/skills/skill.js.map +1 -0
  152. package/dist/sse.d.ts +43 -6
  153. package/dist/sse.d.ts.map +1 -1
  154. package/dist/sse.js +44 -18
  155. package/dist/sse.js.map +1 -1
  156. package/dist/testing/FakeProvider.d.ts.map +1 -1
  157. package/dist/testing/FakeProvider.js +1 -0
  158. package/dist/testing/FakeProvider.js.map +1 -1
  159. package/dist/tool-modules.d.ts +17 -0
  160. package/dist/tool-modules.d.ts.map +1 -0
  161. package/dist/tool-modules.js +43 -0
  162. package/dist/tool-modules.js.map +1 -0
  163. package/dist/tools.d.ts +69 -5
  164. package/dist/tools.d.ts.map +1 -1
  165. package/dist/tools.js +174 -31
  166. package/dist/tools.js.map +1 -1
  167. package/dist/transport.d.ts +8 -3
  168. package/dist/transport.d.ts.map +1 -1
  169. package/dist/transport.js +19 -4
  170. package/dist/transport.js.map +1 -1
  171. package/dist/types.d.ts +106 -2
  172. package/dist/types.d.ts.map +1 -1
  173. package/package.json +22 -1
  174. package/src/Polaris.ts +25 -1
  175. package/src/PolarisClient.ts +288 -51
  176. package/src/PolarisProvider.ts +40 -2
  177. package/src/augmentations.ts +4 -1
  178. package/src/budget.ts +115 -15
  179. package/src/catalog/catalog.ts +180 -0
  180. package/src/catalog/discover.ts +234 -0
  181. package/src/catalog/index.ts +19 -0
  182. package/src/commands/index.ts +412 -0
  183. package/src/cost.ts +9 -3
  184. package/src/drivers/anthropic.ts +203 -20
  185. package/src/drivers/openai-compatible.ts +143 -76
  186. package/src/errors.ts +41 -0
  187. package/src/index.ts +16 -0
  188. package/src/json-schema.ts +597 -0
  189. package/src/log.ts +3 -1
  190. package/src/mcp/client.ts +532 -0
  191. package/src/mcp/endpoint.ts +229 -0
  192. package/src/mcp/host.ts +140 -0
  193. package/src/mcp/http.ts +276 -0
  194. package/src/mcp/index.ts +51 -0
  195. package/src/mcp/manifest.ts +73 -0
  196. package/src/mcp/rpc.ts +197 -0
  197. package/src/mcp/stdio.ts +190 -0
  198. package/src/mcp/worker-main.ts +18 -0
  199. package/src/mcp/worker.ts +212 -0
  200. package/src/meter.ts +13 -2
  201. package/src/redact.ts +6 -3
  202. package/src/redis-budget.ts +85 -0
  203. package/src/response.ts +86 -8
  204. package/src/server-sent.ts +70 -0
  205. package/src/server-tools.ts +77 -0
  206. package/src/services/catalog.ts +43 -0
  207. package/src/skills/folder.ts +231 -0
  208. package/src/skills/frontmatter.ts +92 -0
  209. package/src/skills/index.ts +38 -0
  210. package/src/skills/kit.ts +163 -0
  211. package/src/skills/skill.ts +171 -0
  212. package/src/sse.ts +88 -22
  213. package/src/testing/FakeProvider.ts +1 -0
  214. package/src/tool-modules.ts +49 -0
  215. package/src/tools.ts +260 -27
  216. package/src/transport.ts +25 -3
  217. package/src/types.ts +108 -2
@@ -11,15 +11,26 @@ import {
11
11
  import { type ExtractRequest, type ExtractResult, extract } from "./extract.js";
12
12
  import { addCost, type MeterConfig, openTicket, type Ticket } from "./meter.js";
13
13
  import { scrub } from "./redact.js";
14
- import { addUsage, NO_USAGE } from "./response.js";
14
+ import { addUsage, isTokenCount, isUsage, NO_USAGE } from "./response.js";
15
15
  import type { SchemaOutput, StandardSchema } from "./schema.js";
16
+ import { serverSecrets, serverToolsProblem } from "./server-tools.js";
16
17
  import {
17
18
  ClientLeft,
19
+ encodeRunEvent,
20
+ encodeStreamEvent,
18
21
  pipeToSse,
19
22
  type SseSink,
23
+ type StreamRunToResult,
20
24
  type StreamToResult,
21
25
  } from "./sse.js";
22
- import { type PolarisTool, runToolCalls, tooManySteps } from "./tools.js";
26
+ import {
27
+ checkToolCalls,
28
+ type PolarisTool,
29
+ RunTools,
30
+ runToolCall,
31
+ runToolCalls,
32
+ tooManySteps,
33
+ } from "./tools.js";
23
34
  import { boundFetch, untilAborted } from "./transport.js";
24
35
  import type {
25
36
  ChatRequest,
@@ -32,6 +43,7 @@ import type {
32
43
  PolarisDriver,
33
44
  StreamEvent,
34
45
  ToolCallPart,
46
+ ToolResultPart,
35
47
  Transport,
36
48
  Usage,
37
49
  } from "./types.js";
@@ -60,11 +72,23 @@ export interface CallOptions {
60
72
  /** A request whose tools polaris runs itself. */
61
73
  export type RunRequest = Omit<ChatRequest, "tools"> & {
62
74
  readonly tools: readonly PolarisTool[];
75
+ /**
76
+ * Tools sent from the first request but not callable until a tool of the
77
+ * run adds them (`context.addTools`): the tools sent never change, so a
78
+ * cached prefix stays valid. A call to one before then is answered with a
79
+ * tool error.
80
+ */
81
+ readonly inactiveTools?: readonly PolarisTool[];
63
82
  };
64
83
 
65
84
  export interface RunOptions extends CallOptions {
66
85
  /** Requests sent at most, the first included. Default 8. */
67
86
  readonly maxSteps?: number;
87
+ /**
88
+ * Tool calls one reply may make. A reply with more is refused with
89
+ * `E_POLARIS_TOO_MANY_TOOL_CALLS` and none of its calls runs. Default 32.
90
+ */
91
+ readonly maxToolCalls?: number;
68
92
  /**
69
93
  * Told of every failed tool call: invalid input, an unknown tool, a handler
70
94
  * that threw. The model only reads a short message; this gets the error.
@@ -81,11 +105,28 @@ export interface RunResult {
81
105
  readonly steps: number;
82
106
  /** Tokens of every request of the run, added up. */
83
107
  readonly usage: Usage;
108
+ /** A request of the run reported no usage, or usage that cannot be right. */
109
+ readonly usageUnknown?: boolean;
84
110
  /** What every request of the run cost, added up, when each one is priced. */
85
111
  readonly cost?: Cost;
86
112
  }
87
113
 
114
+ /**
115
+ * What a streamed run yields: the events of every step as `stream()` gives
116
+ * them, but its `done`; one `tool_result` per tool call answered, as soon as
117
+ * it is; then one `done` holding what `run()` returns.
118
+ */
119
+ export type RunEvent =
120
+ | Exclude<StreamEvent, { readonly type: "done" }>
121
+ | {
122
+ readonly type: "tool_result";
123
+ readonly call: ToolCallPart;
124
+ readonly result: ToolResultPart;
125
+ }
126
+ | { readonly type: "done"; readonly result: RunResult };
127
+
88
128
  const DEFAULT_MAX_STEPS = 8;
129
+ const DEFAULT_MAX_TOOL_CALLS = 32;
89
130
 
90
131
  export interface StreamToOptions extends CallOptions {
91
132
  /** Put before every event name: `polaris.` sends `polaris.text`… Default none. */
@@ -132,7 +173,8 @@ interface PreparedCall {
132
173
  * Everything a request asks for is checked against what the driver declares
133
174
  * before anything is sent, so an unsupported feature fails the same way on
134
175
  * every provider. Every call runs under a deadline and a response size bound,
135
- * and an error that mentions the call's own key is replaced before it leaves.
176
+ * and an error that mentions a key the call sent (its own, the configured one,
177
+ * a credential header) is replaced before it leaves.
136
178
  */
137
179
  export class PolarisClient {
138
180
  readonly #name: string;
@@ -181,7 +223,7 @@ export class PolarisClient {
181
223
  prepared.call.signal,
182
224
  );
183
225
  } catch (error) {
184
- const translated = this.#translate(error, prepared, options);
226
+ const translated = this.#translate(error, prepared, options, request);
185
227
  await ticket.fail(translated, {
186
228
  cancelled: options.signal?.aborted === true,
187
229
  spent: false,
@@ -241,7 +283,7 @@ export class PolarisClient {
241
283
  }
242
284
  if (!finished) throw new E_POLARIS_STREAM_INCOMPLETE([driver.provider]);
243
285
  } catch (error) {
244
- const translated = this.#translate(error, prepared, options);
286
+ const translated = this.#translate(error, prepared, options, request);
245
287
  settled = true;
246
288
  await ticket.fail(translated, {
247
289
  cancelled: options.signal?.aborted === true,
@@ -269,59 +311,97 @@ export class PolarisClient {
269
311
  * returned as it is: its tool calls may be incomplete.
270
312
  */
271
313
  async run(request: RunRequest, options: RunOptions = {}): Promise<RunResult> {
272
- const maxSteps = options.maxSteps ?? DEFAULT_MAX_STEPS;
273
- if (!isCount(maxSteps)) {
274
- throw new E_POLARIS_INVALID_REQUEST([
275
- "`maxSteps` must be a positive integer",
276
- ]);
277
- }
278
- const tools = new Map(request.tools.map((tool) => [tool.name, tool]));
279
- const definitions = request.tools.map((tool) => tool.definition);
314
+ const { maxSteps, maxToolCalls } = limitsOf(options);
315
+ const tally = new RunTally(request);
316
+ const tools = tally.tools;
280
317
  const signal = options.signal ?? new AbortController().signal;
281
- const messages: Message[] = [...request.messages];
282
- let usage: Usage = NO_USAGE;
283
- let cost: Cost | undefined;
284
- let priced = true;
285
318
 
286
319
  for (let step = 1; step <= maxSteps; step++) {
287
- // A copy per request: the history grows after it is sent, and what a
288
- // request carried must stay what it was (a log, a driver keeping it).
289
- const response = await this.chat(
290
- { ...request, messages: [...messages], tools: definitions },
291
- options,
320
+ const response = await this.chat(tally.nextRequest(), options);
321
+ const calls = tally.add(response);
322
+ if (calls === "pause") continue;
323
+ if (calls.length === 0) return tally.result(response, step);
324
+ checkToolCalls(calls, maxToolCalls);
325
+ tally.answer(
326
+ await runToolCalls(calls, tools, signal, options.onToolError),
292
327
  );
293
- usage = addUsage(usage, response.usage);
294
- cost = addCost(cost, response.cost);
295
- priced = priced && response.cost !== undefined;
296
- messages.push(response.message);
297
-
298
- // A paused turn goes back as it is, and the provider carries on.
299
- if (response.stopReason === "pause") continue;
300
- if (
301
- response.stopReason !== "tool_use" ||
302
- response.toolCalls.length === 0
303
- ) {
304
- return {
305
- response,
306
- messages,
307
- steps: step,
308
- usage,
309
- ...(priced && cost !== undefined ? { cost } : {}),
310
- };
311
- }
312
- messages.push({
313
- role: "user",
314
- content: await runToolCalls(
315
- response.toolCalls,
316
- tools,
317
- signal,
318
- options.onToolError,
319
- ),
320
- });
321
328
  }
322
329
  throw tooManySteps(maxSteps);
323
330
  }
324
331
 
332
+ /**
333
+ * `run()`, streamed: each step's reply is read as it is written, and each
334
+ * tool result is announced as soon as it is known. The last event is a
335
+ * `done` holding what `run()` returns. Leaving the loop early cancels the
336
+ * provider request in flight and aborts the signal handed to the tools
337
+ * still running.
338
+ */
339
+ async *streamRun(
340
+ request: RunRequest,
341
+ options: RunOptions = {},
342
+ ): AsyncGenerator<RunEvent, void, undefined> {
343
+ const { maxSteps, maxToolCalls } = limitsOf(options);
344
+ const tally = new RunTally(request);
345
+ const tools = tally.tools;
346
+ const stop = new AbortController();
347
+ const signal = options.signal
348
+ ? AbortSignal.any([options.signal, stop.signal])
349
+ : stop.signal;
350
+ const stepOptions: RunOptions = { ...options, signal };
351
+
352
+ try {
353
+ for (let step = 1; step <= maxSteps; step++) {
354
+ let response: ChatResponse | undefined;
355
+ for await (const event of this.stream(
356
+ tally.nextRequest(),
357
+ stepOptions,
358
+ )) {
359
+ if (event.type === "done") response = event.response;
360
+ else yield event;
361
+ }
362
+ // `stream()` ends with its `done` or throws.
363
+ if (response === undefined) {
364
+ throw new E_POLARIS_STREAM_INCOMPLETE([this.#driver.provider]);
365
+ }
366
+ const calls = tally.add(response);
367
+ if (calls === "pause") continue;
368
+ if (calls.length === 0) {
369
+ yield { type: "done", result: tally.result(response, step) };
370
+ return;
371
+ }
372
+ checkToolCalls(calls, maxToolCalls);
373
+
374
+ // Each result is announced as soon as its tool is done; they go
375
+ // back to the model in the order of the calls.
376
+ const results: ToolResultPart[] = [];
377
+ const running = new Map(
378
+ calls.map((call, index) => [
379
+ index,
380
+ runToolCall(call, tools, signal, options.onToolError).then(
381
+ (result) => ({ index, result }),
382
+ ),
383
+ ]),
384
+ );
385
+ while (running.size > 0) {
386
+ const { index, result } = await untilAborted(
387
+ Promise.race(running.values()),
388
+ signal,
389
+ );
390
+ running.delete(index);
391
+ results[index] = result;
392
+ // `index` comes from `calls`, so the call is there.
393
+ const call = calls[index] as ToolCallPart;
394
+ yield { type: "tool_result", call, result };
395
+ }
396
+ tally.answer(results);
397
+ }
398
+ throw tooManySteps(maxSteps);
399
+ } finally {
400
+ // A consumer that left early, a failure: no tool keeps running for nobody.
401
+ stop.abort();
402
+ }
403
+ }
404
+
325
405
  /**
326
406
  * Ask for one value matching `schema`, and get it typed and validated.
327
407
  * The provider's structured-output mode is used when it has one, a tool
@@ -381,6 +461,37 @@ export class PolarisClient {
381
461
  sink,
382
462
  leave,
383
463
  options.prefix ?? "",
464
+ encodeStreamEvent,
465
+ );
466
+ }
467
+
468
+ /**
469
+ * `streamRun()` to the browser over an SSE stream, as `streamTo()` does
470
+ * for one reply. The events are `text`, `reasoning`, `tool_call`,
471
+ * `tool_result` (the call's id and name, and whether it failed: the result
472
+ * itself stays on the server), then `done` with the run's steps and
473
+ * tokens. When the client leaves, the provider request in flight is
474
+ * cancelled and the running tools' signal aborted. A failure sends an
475
+ * `error` event carrying only its polaris code. It never rejects.
476
+ */
477
+ async streamRunTo(
478
+ sink: SseSink,
479
+ request: RunRequest,
480
+ options: RunOptions & StreamToOptions = {},
481
+ ): Promise<StreamRunToResult> {
482
+ const leave = new AbortController();
483
+ sink.onClose(() => {
484
+ if (!leave.signal.aborted) leave.abort(new ClientLeft());
485
+ });
486
+ const signal = options.signal
487
+ ? AbortSignal.any([options.signal, leave.signal])
488
+ : leave.signal;
489
+ return pipeToSse(
490
+ this.streamRun(request, { ...options, signal }),
491
+ sink,
492
+ leave,
493
+ options.prefix ?? "",
494
+ encodeRunEvent,
384
495
  );
385
496
  }
386
497
 
@@ -446,6 +557,9 @@ export class PolarisClient {
446
557
  const cost = await ticket.finish({
447
558
  model: response.model,
448
559
  usage: { ...NO_USAGE, inputTokens: response.usage.inputTokens },
560
+ usageKnown:
561
+ response.usageUnknown !== true &&
562
+ isTokenCount(response.usage.inputTokens),
449
563
  response,
450
564
  });
451
565
  return cost !== undefined ? { ...response, cost } : response;
@@ -485,6 +599,8 @@ export class PolarisClient {
485
599
  const cost = await ticket.finish({
486
600
  model: response.model,
487
601
  usage: response.usage,
602
+ // A driver may build its response by hand: its counts are checked here too.
603
+ usageKnown: response.usageUnknown !== true && isUsage(response.usage),
488
604
  responseId: response.id,
489
605
  stopReason: response.stopReason,
490
606
  response,
@@ -524,6 +640,18 @@ export class PolarisClient {
524
640
  if (!features.images && sendsImages(request)) {
525
641
  throw new E_POLARIS_UNSUPPORTED([provider, "images"]);
526
642
  }
643
+ if (request.server !== undefined) {
644
+ if (features.serverTools !== true) {
645
+ throw new E_POLARIS_UNSUPPORTED([
646
+ provider,
647
+ "server-side tools (`server`: code execution, skills, MCP servers)",
648
+ ]);
649
+ }
650
+ const problem = serverToolsProblem(request.server);
651
+ if (problem !== undefined) {
652
+ throw new E_POLARIS_INVALID_REQUEST([problem]);
653
+ }
654
+ }
527
655
  }
528
656
 
529
657
  #prepare(options: CallOptions, stop: AbortSignal | undefined): PreparedCall {
@@ -559,6 +687,7 @@ export class PolarisClient {
559
687
  this.#options.fetch,
560
688
  signal,
561
689
  this.#options.maxResponseBytes,
690
+ this.#driver.provider,
562
691
  ),
563
692
  },
564
693
  };
@@ -569,11 +698,119 @@ export class PolarisClient {
569
698
  error: unknown,
570
699
  prepared: PreparedCall,
571
700
  options: CallOptions,
701
+ request?: ChatRequest,
572
702
  ): unknown {
573
703
  if (options.signal?.aborted) return options.signal.reason;
574
704
  if (prepared.deadline.aborted)
575
705
  return new E_POLARIS_TIMEOUT([prepared.timeout]);
576
- return scrub(error, this.#driver.provider, [prepared.call.apiKey]);
706
+ const secrets = [
707
+ prepared.call.apiKey,
708
+ ...(this.#driver.secrets ?? []),
709
+ ...serverSecrets(request?.server),
710
+ ];
711
+ return scrub(
712
+ error,
713
+ this.#driver.provider,
714
+ // Shorter than a key, a value (a header's `1`) would garble every message.
715
+ secrets.filter(
716
+ (secret) => secret !== undefined && secret.length >= MIN_KEY_LENGTH,
717
+ ),
718
+ );
719
+ }
720
+ }
721
+
722
+ /** The bounds of a run, checked. */
723
+ function limitsOf(options: RunOptions): {
724
+ maxSteps: number;
725
+ maxToolCalls: number;
726
+ } {
727
+ const maxSteps = options.maxSteps ?? DEFAULT_MAX_STEPS;
728
+ if (!isCount(maxSteps)) {
729
+ throw new E_POLARIS_INVALID_REQUEST([
730
+ "`maxSteps` must be a positive integer",
731
+ ]);
732
+ }
733
+ const maxToolCalls = options.maxToolCalls ?? DEFAULT_MAX_TOOL_CALLS;
734
+ if (!isCount(maxToolCalls)) {
735
+ throw new E_POLARIS_INVALID_REQUEST([
736
+ "`maxToolCalls` must be a positive integer",
737
+ ]);
738
+ }
739
+ return { maxSteps, maxToolCalls };
740
+ }
741
+
742
+ /** What a run has said and spent so far. */
743
+ class RunTally {
744
+ #request: ChatRequest;
745
+ /** The run's tools, which its handlers may add to. */
746
+ readonly tools: RunTools;
747
+ readonly #messages: Message[];
748
+ #usage: Usage = NO_USAGE;
749
+ #cost: Cost | undefined;
750
+ #priced = true;
751
+ #usageUnknown = false;
752
+
753
+ constructor(request: RunRequest) {
754
+ const { tools, inactiveTools, ...rest } = request;
755
+ this.#request = rest;
756
+ this.tools = new RunTools(tools, inactiveTools);
757
+ this.#messages = [...request.messages];
758
+ }
759
+
760
+ /**
761
+ * The next step's request. A copy of the history: it grows after it is
762
+ * sent, and what a request carried must stay what it was (a log, a driver
763
+ * keeping it).
764
+ */
765
+ nextRequest(): ChatRequest {
766
+ return {
767
+ ...this.#request,
768
+ messages: [...this.#messages],
769
+ tools: this.tools.definitions(),
770
+ };
771
+ }
772
+
773
+ /**
774
+ * Count a reply in, and say what comes next: `pause` when the provider
775
+ * paused its turn (it goes back as it is), the tool calls to answer, or
776
+ * none when the run is over. A reply cut at the output limit or refused
777
+ * ends the run: its calls may be incomplete.
778
+ */
779
+ add(response: ChatResponse): readonly ToolCallPart[] | "pause" {
780
+ this.#usage = addUsage(this.#usage, response.usage);
781
+ this.#cost = addCost(this.#cost, response.cost);
782
+ this.#priced = this.#priced && response.cost !== undefined;
783
+ this.#usageUnknown ||= response.usageUnknown === true;
784
+ this.#messages.push(response.message);
785
+ // The next step works in the same container: the files the reply made
786
+ // are there, and a paused turn resumes where it was. Skills from the
787
+ // driver's config make one too, so it is carried with no `server` set.
788
+ if (response.container !== undefined) {
789
+ this.#request = {
790
+ ...this.#request,
791
+ server: { ...this.#request.server, container: response.container.id },
792
+ };
793
+ }
794
+ if (response.stopReason === "pause") return "pause";
795
+ return response.stopReason === "tool_use" ? response.toolCalls : [];
796
+ }
797
+
798
+ /** Put the tools' answers in the history, in one message. */
799
+ answer(results: readonly ToolResultPart[]): void {
800
+ this.tools.commit();
801
+ this.#messages.push({ role: "user", content: [...results] });
802
+ }
803
+
804
+ result(response: ChatResponse, steps: number): RunResult {
805
+ const cost = this.#cost;
806
+ return {
807
+ response,
808
+ messages: this.#messages,
809
+ steps,
810
+ usage: this.#usage,
811
+ ...(this.#usageUnknown ? { usageUnknown: true } : {}),
812
+ ...(this.#priced && cost !== undefined ? { cost } : {}),
813
+ };
577
814
  }
578
815
  }
579
816
 
@@ -4,24 +4,33 @@
4
4
  * register() binds `polaris.manager`, built on first resolve, unless the
5
5
  * application bound its own first.
6
6
  * boot() builds it and publishes it to `@c9up/polaris/services/main`;
7
- * a missing or invalid config fails the boot here.
8
- * shutdown() releases the published manager, if it is still this one.
7
+ * a missing or invalid config fails the boot here. Reads the
8
+ * tool catalog (`polaris.json`, written by `ream polaris:index`),
9
+ * binds it as `polaris.catalog` and publishes it to
10
+ * `@c9up/polaris/services/catalog`.
11
+ * shutdown() releases what it published, if it is still its own.
9
12
  *
10
13
  * Typed against the slice of ream's `AppContext` it uses rather than importing
11
14
  * it, so ream stays an optional peer.
12
15
  */
13
16
 
17
+ import { resolve } from "node:path";
18
+ import { fileURLToPath } from "node:url";
14
19
  import "./augmentations.js";
20
+ import { Catalog } from "./catalog/catalog.js";
21
+ import { DEFAULT_MANIFEST } from "./catalog/discover.js";
15
22
  import { E_POLARIS_MISSING_CONFIG } from "./errors.js";
16
23
  import {
17
24
  type DeclaredProviders,
18
25
  Polaris,
19
26
  type PolarisService,
20
27
  } from "./Polaris.js";
28
+ import { clearCatalog, getCatalog, setCatalog } from "./services/catalog.js";
21
29
  import { clearPolaris, getPolaris, setPolaris } from "./services/main.js";
22
30
  import type { PolarisConfig } from "./types.js";
23
31
 
24
32
  const TOKEN = "polaris.manager";
33
+ const CATALOG_TOKEN = "polaris.catalog";
25
34
 
26
35
  interface ContainerLike {
27
36
  singleton(token: string | symbol, factory: () => unknown): void;
@@ -37,11 +46,14 @@ interface ConfigStoreLike {
37
46
  export interface PolarisAppContext {
38
47
  container: ContainerLike;
39
48
  config: ConfigStoreLike;
49
+ /** The application's root; the manifest's path is resolved from it. */
50
+ appRoot?: URL | undefined;
40
51
  }
41
52
 
42
53
  export default class PolarisProvider {
43
54
  readonly #app: PolarisAppContext;
44
55
  #owned: PolarisService | undefined;
56
+ #ownedCatalog: Catalog | undefined;
45
57
 
46
58
  constructor(app: PolarisAppContext) {
47
59
  this.#app = app;
@@ -62,6 +74,25 @@ export default class PolarisProvider {
62
74
  const manager = await this.#app.container.resolve<PolarisService>(TOKEN);
63
75
  this.#owned = manager;
64
76
  setPolaris(manager);
77
+
78
+ const config = this.#app.config.get<{ catalog?: unknown }>("polaris");
79
+ const options = config?.catalog;
80
+ if (options === false) return;
81
+ const manifest =
82
+ typeof options === "object" &&
83
+ options !== null &&
84
+ "manifest" in options &&
85
+ typeof options.manifest === "string"
86
+ ? options.manifest
87
+ : DEFAULT_MANIFEST;
88
+ const root =
89
+ this.#app.appRoot === undefined
90
+ ? process.cwd()
91
+ : fileURLToPath(this.#app.appRoot);
92
+ const catalog = await Catalog.read(resolve(root, manifest));
93
+ this.#ownedCatalog = catalog;
94
+ this.#app.container.singleton(CATALOG_TOKEN, () => catalog);
95
+ setCatalog(catalog);
65
96
  }
66
97
 
67
98
  async shutdown(): Promise<void> {
@@ -69,5 +100,12 @@ export default class PolarisProvider {
69
100
  clearPolaris();
70
101
  }
71
102
  this.#owned = undefined;
103
+ if (
104
+ this.#ownedCatalog !== undefined &&
105
+ getCatalog() === this.#ownedCatalog
106
+ ) {
107
+ clearCatalog();
108
+ }
109
+ this.#ownedCatalog = undefined;
72
110
  }
73
111
  }
@@ -1,17 +1,20 @@
1
1
  /**
2
2
  * Tell ream's `ContainerBindings` what `container.resolve('polaris.manager')`
3
- * returns. Loaded from the package barrel and from the provider, so an
3
+ * and `container.resolve('polaris.catalog')` return. Loaded from the package barrel and from the provider, so an
4
4
  * application writes no `declare module` of its own for it.
5
5
  *
6
6
  * Type-only: ream stays an optional peer.
7
7
  */
8
8
 
9
9
  import type {} from "@c9up/ream/types";
10
+ import type { Catalog } from "./catalog/catalog.js";
10
11
  import type { PolarisService } from "./Polaris.js";
11
12
 
12
13
  declare module "@c9up/ream/types" {
13
14
  interface ContainerBindings {
14
15
  /** The provider manager, bound by `PolarisProvider`. */
15
16
  "polaris.manager": PolarisService;
17
+ /** The tool and skill catalog, read from `polaris.json` by `PolarisProvider`. */
18
+ "polaris.catalog": Catalog;
16
19
  }
17
20
  }