@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
package/src/meter.ts ADDED
@@ -0,0 +1,199 @@
1
+ /**
2
+ * Prices, budgets and the exchange log, around each provider call.
3
+ *
4
+ * Before the call: its price is found, the request's own ceiling (`maxCost`)
5
+ * checked, and its estimated cost reserved on the scope's budget; a refusal
6
+ * sends nothing. After it: the reservation is replaced by the real cost, the
7
+ * cost is put on the response, and the exchange is logged.
8
+ */
9
+
10
+ import {
11
+ type BudgetConfig,
12
+ type BudgetStore,
13
+ limitOf,
14
+ type Reservation,
15
+ reserve,
16
+ } from "./budget.js";
17
+ import {
18
+ add,
19
+ type Cost,
20
+ costOf,
21
+ exceeds,
22
+ type ModelPrice,
23
+ type Pricing,
24
+ priceFor,
25
+ } from "./cost.js";
26
+ import {
27
+ E_POLARIS_BUDGET_EXCEEDED,
28
+ E_POLARIS_INVALID_REQUEST,
29
+ E_POLARIS_UNKNOWN_PRICE,
30
+ } from "./errors.js";
31
+ import {
32
+ codeOf,
33
+ type ExchangeEntry,
34
+ type ExchangeLog,
35
+ writeLog,
36
+ } from "./log.js";
37
+ import type {
38
+ ChatRequest,
39
+ ChatResponse,
40
+ EmbedRequest,
41
+ EmbedResponse,
42
+ StopReason,
43
+ Usage,
44
+ } from "./types.js";
45
+
46
+ export interface MeterConfig {
47
+ readonly pricing?: Pricing;
48
+ readonly budget?: BudgetConfig & { readonly store: BudgetStore };
49
+ readonly log?: ExchangeLog;
50
+ }
51
+
52
+ /** What polaris needs to meter one call. */
53
+ export interface MeterInput {
54
+ readonly operation: ExchangeEntry["operation"];
55
+ readonly provider: string;
56
+ readonly request: ChatRequest | EmbedRequest;
57
+ /** The model the call is expected to run on: the request's, or the driver's default. */
58
+ readonly model: string | undefined;
59
+ /** Estimate the call's most expensive outcome at `price`, for a budget. */
60
+ estimate(price: ModelPrice): string;
61
+ readonly scope?: string;
62
+ readonly maxCost?: string;
63
+ }
64
+
65
+ /** How a metered call ended. */
66
+ export interface MeterOutcome {
67
+ readonly model: string;
68
+ readonly usage: Usage;
69
+ /**
70
+ * Whether the provider reported usage that can be priced. Without it the
71
+ * call has no cost, and its estimate stays on the budget: a missing count
72
+ * is not a free call.
73
+ */
74
+ readonly usageKnown: boolean;
75
+ readonly responseId?: string;
76
+ readonly stopReason?: StopReason;
77
+ readonly response: ChatResponse | EmbedResponse;
78
+ }
79
+
80
+ /** One metered call, opened before it is sent and closed once. */
81
+ export interface Ticket {
82
+ /** The call answered: settle the budget, log, and answer its cost. */
83
+ finish(outcome: MeterOutcome): Promise<Cost | undefined>;
84
+ /**
85
+ * The call failed. `spent` says whether the provider may have billed it
86
+ * (a stream cut after it started): its estimate is then kept on the budget.
87
+ */
88
+ fail(
89
+ error: unknown,
90
+ options: { cancelled: boolean; spent: boolean },
91
+ ): Promise<void>;
92
+ }
93
+
94
+ /** Open the meter of one call. Throws, before anything is sent, when its budget refuses it. */
95
+ export async function openTicket(
96
+ config: MeterConfig,
97
+ input: MeterInput,
98
+ ): Promise<Ticket> {
99
+ const started = Date.now();
100
+ const price = priceFor(config.pricing, input.model);
101
+ const limit =
102
+ input.scope !== undefined && config.budget !== undefined
103
+ ? await limitOf(config.budget, input.scope)
104
+ : undefined;
105
+ if (input.scope !== undefined && config.budget === undefined) {
106
+ throw new E_POLARIS_INVALID_REQUEST([
107
+ "`scope` was given, but the config declares no `budget`",
108
+ ]);
109
+ }
110
+
111
+ let reservation: Reservation | undefined;
112
+ if (limit !== undefined || input.maxCost !== undefined) {
113
+ // A budget cannot be kept without knowing what the model costs: refuse
114
+ // rather than let the call through unmetered.
115
+ if (price === undefined) {
116
+ throw new E_POLARIS_UNKNOWN_PRICE([input.model ?? "(no model)"]);
117
+ }
118
+ const estimate = input.estimate(price);
119
+ if (input.maxCost !== undefined && exceeds(estimate, input.maxCost)) {
120
+ throw new E_POLARIS_BUDGET_EXCEEDED(["this request", input.maxCost]);
121
+ }
122
+ if (input.scope !== undefined && config.budget !== undefined) {
123
+ reservation = await reserve(
124
+ config.budget.store,
125
+ input.scope,
126
+ limit,
127
+ estimate,
128
+ config.budget.period,
129
+ );
130
+ }
131
+ }
132
+
133
+ const entry = (status: ExchangeEntry["status"]): ExchangeEntry => ({
134
+ provider: input.provider,
135
+ model: input.model,
136
+ operation: input.operation,
137
+ status,
138
+ durationMs: Date.now() - started,
139
+ ...(input.scope !== undefined ? { scope: input.scope } : {}),
140
+ });
141
+
142
+ return {
143
+ async finish(outcome) {
144
+ const answered = priceFor(config.pricing, outcome.model) ?? price;
145
+ const amount =
146
+ answered !== undefined && outcome.usageKnown
147
+ ? costOf(answered, outcome.usage)
148
+ : undefined;
149
+ const cost =
150
+ amount !== undefined && config.pricing !== undefined
151
+ ? { amount, currency: config.pricing.currency }
152
+ : undefined;
153
+ // Without a price for the model that answered, or usage to price, the
154
+ // estimate stays.
155
+ if (reservation !== undefined && amount !== undefined) {
156
+ await reservation.settle(amount);
157
+ }
158
+ await writeLog(
159
+ config.log,
160
+ {
161
+ ...entry("ok"),
162
+ model: outcome.model,
163
+ usage: outcome.usage,
164
+ ...(cost !== undefined ? { cost } : {}),
165
+ ...(outcome.responseId !== undefined
166
+ ? { responseId: outcome.responseId }
167
+ : {}),
168
+ ...(outcome.stopReason !== undefined
169
+ ? { stopReason: outcome.stopReason }
170
+ : {}),
171
+ },
172
+ { request: input.request, response: outcome.response },
173
+ );
174
+ return cost;
175
+ },
176
+ async fail(error, options) {
177
+ if (reservation !== undefined && !options.spent)
178
+ await reservation.release();
179
+ await writeLog(
180
+ config.log,
181
+ {
182
+ ...entry(options.cancelled ? "cancelled" : "error"),
183
+ errorCode: codeOf(error),
184
+ },
185
+ { request: input.request },
186
+ );
187
+ },
188
+ };
189
+ }
190
+
191
+ /** Two costs added up, exactly, when both are known and in one currency. */
192
+ export function addCost(
193
+ a: Cost | undefined,
194
+ b: Cost | undefined,
195
+ ): Cost | undefined {
196
+ if (a === undefined) return b;
197
+ if (b === undefined || a.currency !== b.currency) return a;
198
+ return { amount: add(a.amount, b.amount), currency: a.currency };
199
+ }
@@ -0,0 +1,25 @@
1
+ /**
2
+ * One helper per provider polaris ships, as @adonisjs/mail's `transports`:
3
+ *
4
+ * defineConfig({
5
+ * default: 'claude',
6
+ * providers: {
7
+ * claude: providers.anthropic({ model: 'claude-opus-5-5' }),
8
+ * local: providers.openaiCompatible({ baseURL: 'http://localhost:11434/v1', model: 'qwen3' }),
9
+ * },
10
+ * })
11
+ *
12
+ * A helper returns a factory; the driver is built, and its SDK loaded, the
13
+ * first time the provider is used.
14
+ */
15
+
16
+ import { anthropic } from "./drivers/anthropic.js";
17
+ import { openaiCompatible } from "./drivers/openai-compatible.js";
18
+
19
+ export const providers = {
20
+ anthropic,
21
+ openaiCompatible,
22
+ };
23
+
24
+ export type { AnthropicConfig } from "./drivers/anthropic.js";
25
+ export type { OpenAICompatibleConfig } from "./drivers/openai-compatible.js";
package/src/redact.ts ADDED
@@ -0,0 +1,81 @@
1
+ import { E_POLARIS_PROVIDER_FAILED } from "./errors.js";
2
+
3
+ const REDACTED = "[redacted]";
4
+ /** How many values the scan visits before it assumes the worst. */
5
+ const MAX_VISITS = 2_000;
6
+ const MAX_DEPTH = 8;
7
+
8
+ /** Replace every occurrence of each secret in `text`. */
9
+ export function redact(text: string, secrets: readonly string[]): string {
10
+ let out = text;
11
+ for (const secret of secrets) out = out.split(secret).join(REDACTED);
12
+ return out;
13
+ }
14
+
15
+ /**
16
+ * Whether `value` holds one of `secrets` anywhere a logger or an error report
17
+ * could reach: its message, stack, cause, own properties, nested objects,
18
+ * arrays and `Headers`.
19
+ *
20
+ * A value too large or too deep to scan in full counts as holding one: the
21
+ * error it came from is then replaced, which loses detail but leaks nothing.
22
+ */
23
+ function holdsSecret(value: unknown, secrets: readonly string[]): boolean {
24
+ const seen = new Set<object>();
25
+ let visits = 0;
26
+
27
+ const visit = (current: unknown, depth: number): boolean => {
28
+ visits += 1;
29
+ if (visits > MAX_VISITS || depth > MAX_DEPTH) return true;
30
+ if (typeof current === "string") {
31
+ return secrets.some((secret) => current.includes(secret));
32
+ }
33
+ if (typeof current !== "object" || current === null) return false;
34
+ if (seen.has(current)) return false;
35
+ seen.add(current);
36
+
37
+ if (current instanceof Headers) {
38
+ for (const [, header] of current) {
39
+ if (visit(header, depth + 1)) return true;
40
+ }
41
+ return false;
42
+ }
43
+ if (current instanceof Error) {
44
+ if (visit(current.message, depth + 1)) return true;
45
+ if (visit(current.stack, depth + 1)) return true;
46
+ if (visit(current.cause, depth + 1)) return true;
47
+ }
48
+ if (Array.isArray(current)) {
49
+ return current.some((item) => visit(item, depth + 1));
50
+ }
51
+ for (const key of Object.keys(current)) {
52
+ if (visit(Reflect.get(current, key), depth + 1)) return true;
53
+ }
54
+ return false;
55
+ };
56
+
57
+ return visit(value, 0);
58
+ }
59
+
60
+ /**
61
+ * The error to raise for a failed call that was given `secrets`.
62
+ *
63
+ * An error that holds none of them is returned as it is. One that holds any is
64
+ * replaced by `E_POLARIS_PROVIDER_FAILED` (or what `replace` builds), whose
65
+ * message is the original one with the secrets taken out, and which keeps no
66
+ * reference to the original.
67
+ */
68
+ export function scrub(
69
+ error: unknown,
70
+ provider: string,
71
+ secrets: readonly (string | undefined)[],
72
+ replace: (provider: string, message: string) => Error = (name, message) =>
73
+ new E_POLARIS_PROVIDER_FAILED([name, message]),
74
+ ): unknown {
75
+ const live = secrets.filter(
76
+ (secret): secret is string => typeof secret === "string" && secret !== "",
77
+ );
78
+ if (live.length === 0 || !holdsSecret(error, live)) return error;
79
+ const message = error instanceof Error ? error.message : String(error);
80
+ return replace(provider, redact(message, live));
81
+ }
@@ -0,0 +1,85 @@
1
+ /**
2
+ * A budget store in Redis, shared by every instance that talks to the same
3
+ * server: what one instance reserves, the others see at once.
4
+ *
5
+ * Spend is kept as an integer count of billionths of the pricing currency, so
6
+ * that Redis adds it with `INCRBY`, exactly and atomically, where
7
+ * `INCRBYFLOAT` would add binary floats. A key's expiry is set in the same
8
+ * `MULTI` as the addition: a key is never left without one by a process that
9
+ * died between the two.
10
+ */
11
+
12
+ import { decimal } from "@c9up/atom";
13
+ import type { BudgetStore } from "./budget.js";
14
+
15
+ /** The commands of a `MULTI` the store queues. */
16
+ export interface RedisBudgetTransaction {
17
+ incrby(key: string, increment: string): RedisBudgetTransaction;
18
+ pexpireat(key: string, unixTimeMilliseconds: number): RedisBudgetTransaction;
19
+ exec(): Promise<[error: Error | null, result: unknown][] | null>;
20
+ }
21
+
22
+ /**
23
+ * What the store needs of a Redis client: an ioredis client and a
24
+ * `@c9up/quasar` connection both fit as they are.
25
+ */
26
+ export interface RedisBudgetClient {
27
+ multi(): RedisBudgetTransaction;
28
+ }
29
+
30
+ export interface RedisBudgetStoreOptions {
31
+ /** Put before every key, to share one database with others. Default: `polaris:budget:`. */
32
+ readonly prefix?: string;
33
+ }
34
+
35
+ /** Spend is counted in billionths of the currency. */
36
+ const DECIMALS = 9;
37
+ const UNIT = "1000000000";
38
+ const STEP = "0.000000001";
39
+
40
+ /**
41
+ * A budget store in Redis, for budgets shared by several instances:
42
+ *
43
+ * budget: { limit, period: 'month', store: redisBudgetStore(() => redis.connection()) }
44
+ *
45
+ * `client` is the client, or a function that answers it, called on each
46
+ * addition: a config file read before the Redis connections are booted can
47
+ * then name one.
48
+ *
49
+ * Amounts are rounded to nine decimals (half away from zero, so a release
50
+ * cancels its reservation exactly), and a key counts exactly up to about nine
51
+ * million units of the currency. The store declares those nine decimals: a
52
+ * reservation rounds its estimate and the final cost to them once each, so a
53
+ * request leaves exactly its rounded cost in the key.
54
+ */
55
+ export function redisBudgetStore(
56
+ client: RedisBudgetClient | (() => RedisBudgetClient),
57
+ options: RedisBudgetStoreOptions = {},
58
+ ): BudgetStore {
59
+ const prefix = options.prefix ?? "polaris:budget:";
60
+ return {
61
+ decimals: DECIMALS,
62
+ async add(key, amount, expiresAt) {
63
+ const name = prefix + key;
64
+ const increment = decimal(amount).times(UNIT).toFixed(0, "half-up");
65
+ const redis = typeof client === "function" ? client() : client;
66
+ let transaction = redis.multi().incrby(name, increment);
67
+ if (expiresAt !== undefined)
68
+ transaction = transaction.pexpireat(name, expiresAt);
69
+ const replies = await transaction.exec();
70
+ if (replies === null) {
71
+ throw new Error(
72
+ `[polaris] the budget transaction on '${name}' was aborted`,
73
+ );
74
+ }
75
+ const [error, total] = replies[0] ?? [null, undefined];
76
+ if (error !== null) throw error;
77
+ if (typeof total !== "number" || !Number.isSafeInteger(total)) {
78
+ throw new Error(
79
+ `[polaris] the spend under '${name}' is past what a budget counts exactly`,
80
+ );
81
+ }
82
+ return decimal(total).times(STEP).toString();
83
+ },
84
+ };
85
+ }
@@ -0,0 +1,143 @@
1
+ import type {
2
+ AssistantPart,
3
+ ChatResponse,
4
+ ServerContainer,
5
+ StopReason,
6
+ ToolCallPart,
7
+ Usage,
8
+ } from "./types.js";
9
+
10
+ export interface ResponseInput {
11
+ readonly id: string;
12
+ readonly provider: string;
13
+ readonly model: string;
14
+ readonly content: readonly AssistantPart[];
15
+ readonly stopReason: StopReason;
16
+ /**
17
+ * The token counts as the provider reported them, unchecked: leave it out
18
+ * when it reported none.
19
+ */
20
+ readonly usage?: { readonly [K in keyof Usage]?: unknown };
21
+ /** The provider's container the reply ran code in. */
22
+ readonly container?: ServerContainer;
23
+ }
24
+
25
+ /** Usage of nothing yet: what a sum of usages starts from. */
26
+ export const NO_USAGE: Usage = {
27
+ inputTokens: 0,
28
+ outputTokens: 0,
29
+ cacheReadTokens: 0,
30
+ cacheWriteTokens: 0,
31
+ };
32
+
33
+ /** Two usages added up: the cost of a run or of several attempts. */
34
+ export function addUsage(a: Usage, b: Usage): Usage {
35
+ const serverToolUse = addCounters(a.serverToolUse, b.serverToolUse);
36
+ return {
37
+ inputTokens: a.inputTokens + b.inputTokens,
38
+ outputTokens: a.outputTokens + b.outputTokens,
39
+ cacheReadTokens: a.cacheReadTokens + b.cacheReadTokens,
40
+ cacheWriteTokens: a.cacheWriteTokens + b.cacheWriteTokens,
41
+ ...(serverToolUse !== undefined ? { serverToolUse } : {}),
42
+ };
43
+ }
44
+
45
+ type Counters = NonNullable<Usage["serverToolUse"]>;
46
+
47
+ function addCounters(
48
+ a: Counters | undefined,
49
+ b: Counters | undefined,
50
+ ): Counters | undefined {
51
+ if (a === undefined) return b;
52
+ if (b === undefined) return a;
53
+ const sum: Record<string, number> = { ...a };
54
+ for (const [counter, count] of Object.entries(b)) {
55
+ sum[counter] = (sum[counter] ?? 0) + count;
56
+ }
57
+ return sum;
58
+ }
59
+
60
+ /** Whether `value` can be a count of tokens: a whole number, 0 or more. */
61
+ export function isTokenCount(value: unknown): value is number {
62
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
63
+ }
64
+
65
+ /** Whether every count of `usage` can be one. */
66
+ export function isUsage(usage: Usage): boolean {
67
+ return (
68
+ isTokenCount(usage.inputTokens) &&
69
+ isTokenCount(usage.outputTokens) &&
70
+ isTokenCount(usage.cacheReadTokens) &&
71
+ isTokenCount(usage.cacheWriteTokens)
72
+ );
73
+ }
74
+
75
+ /**
76
+ * Build a {@link ChatResponse} from what a provider returned: `text` and
77
+ * `toolCalls` are derived from `content`.
78
+ * Drivers build their responses with it, so the derived fields cannot drift
79
+ * from the content they summarize.
80
+ *
81
+ * Usage the provider did not report, reported without its input or output
82
+ * count, or with a count that cannot be one (negative, fractional, not a
83
+ * number), is marked `usageUnknown`: the wrong count is 0, and the call is
84
+ * not priced from it. Cache counts left out are 0. A count of 0 would
85
+ * otherwise settle the call's budget as free.
86
+ */
87
+ export function createResponse(input: ResponseInput): ChatResponse {
88
+ const text = input.content
89
+ .filter((part) => part.type === "text")
90
+ .map((part) => part.text)
91
+ .join("");
92
+ const toolCalls = input.content.filter(
93
+ (part): part is ToolCallPart => part.type === "tool_call",
94
+ );
95
+ return {
96
+ id: input.id,
97
+ provider: input.provider,
98
+ model: input.model,
99
+ message: { role: "assistant", content: input.content },
100
+ text,
101
+ toolCalls,
102
+ stopReason: input.stopReason,
103
+ ...readUsage(input.usage),
104
+ ...(input.container !== undefined ? { container: input.container } : {}),
105
+ };
106
+ }
107
+
108
+ function readUsage(
109
+ reported: ResponseInput["usage"],
110
+ ): Pick<ChatResponse, "usage" | "usageUnknown"> {
111
+ let unknown = reported === undefined;
112
+ // Input and output are always reported by a provider that reports usage:
113
+ // one left out (a gateway's `usage: {}`) would price the call as free. The
114
+ // cache counts are left out by providers without a cache.
115
+ const count = (value: unknown, required: boolean): number => {
116
+ if (value === undefined && !required) return 0;
117
+ if (isTokenCount(value)) return value;
118
+ unknown = true;
119
+ return 0;
120
+ };
121
+ let usage: Usage = {
122
+ inputTokens: count(reported?.inputTokens, true),
123
+ outputTokens: count(reported?.outputTokens, true),
124
+ cacheReadTokens: count(reported?.cacheReadTokens, false),
125
+ cacheWriteTokens: count(reported?.cacheWriteTokens, false),
126
+ };
127
+ const serverToolUse = readCounters(reported?.serverToolUse);
128
+ if (serverToolUse !== undefined) usage = { ...usage, serverToolUse };
129
+ return unknown ? { usage, usageUnknown: true } : { usage };
130
+ }
131
+
132
+ /**
133
+ * The server tool counters that can be counts. They price nothing, so one
134
+ * that cannot be a count is left out rather than marking the usage unknown.
135
+ */
136
+ function readCounters(reported: unknown): Counters | undefined {
137
+ if (typeof reported !== "object" || reported === null) return undefined;
138
+ const counters: Record<string, number> = {};
139
+ for (const [counter, count] of Object.entries(reported)) {
140
+ if (isTokenCount(count)) counters[counter] = count;
141
+ }
142
+ return Object.keys(counters).length > 0 ? counters : undefined;
143
+ }
package/src/schema.ts ADDED
@@ -0,0 +1,88 @@
1
+ /**
2
+ * The schemas polaris takes, for a tool's input and for a structured answer:
3
+ * anything that implements Standard Schema v1 (validation) and Standard JSON
4
+ * Schema v1 (its JSON Schema), as rune's validators do. polaris imports no
5
+ * validation library.
6
+ */
7
+
8
+ import { E_POLARIS_INVALID_REQUEST } from "./errors.js";
9
+ import type { JsonSchema } from "./types.js";
10
+
11
+ /** One problem a schema found in a value. */
12
+ export interface SchemaIssue {
13
+ readonly message: string;
14
+ readonly path?: readonly unknown[];
15
+ }
16
+
17
+ /** What a Standard Schema's `validate` answers. */
18
+ export type SchemaResult<Output> =
19
+ | { readonly value: Output; readonly issues?: undefined }
20
+ | { readonly issues: readonly SchemaIssue[] };
21
+
22
+ /** The slice of Standard Schema v1 and Standard JSON Schema v1 polaris uses. */
23
+ export interface StandardSchema<Output = unknown> {
24
+ readonly "~standard": {
25
+ readonly version: 1;
26
+ readonly vendor: string;
27
+ validate(
28
+ value: unknown,
29
+ ): SchemaResult<Output> | Promise<SchemaResult<Output>>;
30
+ readonly jsonSchema: {
31
+ input(options?: { readonly target?: string }): Record<string, unknown>;
32
+ };
33
+ };
34
+ }
35
+
36
+ /** The value a schema hands back once it accepted the input. */
37
+ export type SchemaOutput<S extends StandardSchema> = Extract<
38
+ Awaited<ReturnType<S["~standard"]["validate"]>>,
39
+ { readonly value: unknown }
40
+ >["value"];
41
+
42
+ /**
43
+ * The JSON Schema of what `schema` accepts, checked to describe an object
44
+ * (what providers take for a tool's input and a structured answer), without
45
+ * its `$schema` key, which some providers refuse.
46
+ */
47
+ export function objectJsonSchema(
48
+ schema: StandardSchema,
49
+ label: string,
50
+ ): JsonSchema {
51
+ const standard = schema["~standard"];
52
+ if (
53
+ standard?.version !== 1 ||
54
+ typeof standard.validate !== "function" ||
55
+ typeof standard.jsonSchema?.input !== "function"
56
+ ) {
57
+ throw new E_POLARIS_INVALID_REQUEST([
58
+ `the schema of ${label} must implement Standard Schema v1 and Standard JSON Schema v1 (a rune schema does)`,
59
+ ]);
60
+ }
61
+ const jsonSchema: JsonSchema = Object.fromEntries(
62
+ Object.entries(standard.jsonSchema.input()).filter(
63
+ ([key]) => key !== "$schema",
64
+ ),
65
+ );
66
+ if (jsonSchema.type !== "object") {
67
+ throw new E_POLARIS_INVALID_REQUEST([
68
+ `the schema of ${label} must describe an object`,
69
+ ]);
70
+ }
71
+ return jsonSchema;
72
+ }
73
+
74
+ /** `canton: too short; age: not a number`: issues as one line a model can act on. */
75
+ export function describeIssues(issues: readonly SchemaIssue[]): string {
76
+ return issues
77
+ .map((issue) => {
78
+ const path = (issue.path ?? [])
79
+ .map((segment) =>
80
+ typeof segment === "object" && segment !== null && "key" in segment
81
+ ? String(segment.key)
82
+ : String(segment),
83
+ )
84
+ .join(".");
85
+ return path === "" ? issue.message : `${path}: ${issue.message}`;
86
+ })
87
+ .join("; ");
88
+ }
@@ -0,0 +1,70 @@
1
+ /**
2
+ * The `data:` payloads of a server-sent event stream, lines rejoined across
3
+ * chunks. Linear in the stream's size: a line still open is kept in pieces,
4
+ * joined once its end arrives, and only the text just received is searched
5
+ * for a line end. An event longer than `maxLength` characters raises
6
+ * `tooLong()`: holding it would only feed a runaway or hostile stream.
7
+ */
8
+ export async function* serverSentData(
9
+ body: ReadableStream<Uint8Array>,
10
+ maxLength: number,
11
+ tooLong: () => Error,
12
+ ): AsyncGenerator<string> {
13
+ const reader = body.getReader();
14
+ const decoder = new TextDecoder();
15
+ let pending: string[] = [];
16
+ let data: string[] = [];
17
+ // Characters held for the event being read: its data lines and the open line.
18
+ let held = 0;
19
+ const hold = (length: number): void => {
20
+ held += length;
21
+ if (held > maxLength) throw tooLong();
22
+ };
23
+ // One whole line; the event's payload when the line ends it.
24
+ const line = (raw: string): string | undefined => {
25
+ const text = raw.endsWith("\r") ? raw.slice(0, -1) : raw;
26
+ if (text === "") {
27
+ const event = data.length > 0 ? data.join("\n") : undefined;
28
+ data = [];
29
+ held = 0;
30
+ return event;
31
+ }
32
+ if (text.startsWith("data:")) {
33
+ data.push(text.slice(text.startsWith("data: ") ? 6 : 5));
34
+ } else {
35
+ // A comment or another field: not part of the event's payload.
36
+ held -= raw.length;
37
+ }
38
+ return undefined;
39
+ };
40
+ const read = function* (text: string): Generator<string> {
41
+ let start = 0;
42
+ let newline = text.indexOf("\n");
43
+ while (newline !== -1) {
44
+ hold(newline - start);
45
+ pending.push(text.slice(start, newline));
46
+ const event = line(pending.join(""));
47
+ pending = [];
48
+ if (event !== undefined) yield event;
49
+ start = newline + 1;
50
+ newline = text.indexOf("\n", start);
51
+ }
52
+ if (start < text.length) {
53
+ hold(text.length - start);
54
+ pending.push(text.slice(start));
55
+ }
56
+ };
57
+ try {
58
+ while (true) {
59
+ const { value, done } = await reader.read();
60
+ if (done) break;
61
+ yield* read(decoder.decode(value, { stream: true }));
62
+ }
63
+ yield* read(decoder.decode());
64
+ // The stream may end without the blank line that closes its last event.
65
+ if (pending.length > 0) line(pending.join(""));
66
+ if (data.length > 0) yield data.join("\n");
67
+ } finally {
68
+ await reader.cancel().catch(() => undefined);
69
+ }
70
+ }