@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
package/src/Polaris.ts ADDED
@@ -0,0 +1,280 @@
1
+ import { memoryBudgetStore } from "./budget.js";
2
+ import { checkPricing } from "./cost.js";
3
+ import {
4
+ E_POLARIS_INVALID_CONFIG,
5
+ E_POLARIS_NO_DEFAULT_PROVIDER,
6
+ E_POLARIS_UNKNOWN_PROVIDER,
7
+ } from "./errors.js";
8
+ import type { ExtractRequest, ExtractResult } from "./extract.js";
9
+ import {
10
+ type CallOptions,
11
+ type ClientOptions,
12
+ type ExtractOptions,
13
+ isTimeout,
14
+ MAX_TIMEOUT,
15
+ PolarisClient,
16
+ type RunOptions,
17
+ type RunRequest,
18
+ type RunResult,
19
+ type StreamToOptions,
20
+ } from "./PolarisClient.js";
21
+ import type { SchemaOutput, StandardSchema } from "./schema.js";
22
+ import type { SseSink, StreamToResult } from "./sse.js";
23
+ import { type FakeOptions, FakeProvider } from "./testing/FakeProvider.js";
24
+ import type {
25
+ ChatRequest,
26
+ ChatResponse,
27
+ EmbedRequest,
28
+ EmbedResponse,
29
+ PolarisConfig,
30
+ PolarisDriver,
31
+ ProviderFactory,
32
+ ProvidersList,
33
+ StreamEvent,
34
+ } from "./types.js";
35
+
36
+ const DEFAULT_TIMEOUT = 600_000;
37
+ const DEFAULT_MAX_RESPONSE_BYTES = 32 * 1024 * 1024;
38
+
39
+ /**
40
+ * Declare the providers an application talks to.
41
+ *
42
+ * const polarisConfig = defineConfig({
43
+ * default: 'claude',
44
+ * providers: {
45
+ * claude: providers.anthropic({ apiKey: env.get('ANTHROPIC_API_KEY'), model: 'claude-opus-5-5' }),
46
+ * },
47
+ * })
48
+ * export default polarisConfig
49
+ *
50
+ * declare module '@c9up/polaris/types' {
51
+ * interface ProvidersList extends InferProviders<typeof polarisConfig> {}
52
+ * }
53
+ *
54
+ * The shape is @adonisjs/mail's (`default`, named entries built by helpers,
55
+ * a list interface the application augments). Adonis has no LLM package.
56
+ *
57
+ * NAMED DEVIATION: it returns the config itself, where @adonisjs/mail wraps it
58
+ * in a `ConfigProvider` resolved at boot. A provider factory needs nothing
59
+ * from the application, and the other packages of this cohort (rover, nova)
60
+ * return plain config the same way.
61
+ */
62
+ export function defineConfig<
63
+ KnownProviders extends Record<string, ProviderFactory>,
64
+ >(config: PolarisConfig<KnownProviders>): PolarisConfig<KnownProviders> {
65
+ return config;
66
+ }
67
+
68
+ /**
69
+ * The providers the application declared in {@link ProvidersList}, as an
70
+ * object type `Polaris` can take. A mapped type, because an interface carries
71
+ * no index signature and is never assignable to a `Record`.
72
+ */
73
+ export type DeclaredProviders = {
74
+ [K in keyof ProvidersList & string]: Extract<
75
+ ProvidersList[K],
76
+ ProviderFactory
77
+ >;
78
+ };
79
+
80
+ /** The manager `@c9up/polaris/services/main` and the container hand out. */
81
+ export type PolarisService = Polaris<DeclaredProviders>;
82
+
83
+ /**
84
+ * The provider manager: builds each declared provider the first time it is
85
+ * used and keeps it for the life of the process.
86
+ */
87
+ export class Polaris<KnownProviders extends Record<string, ProviderFactory>> {
88
+ readonly #providers: Record<string, ProviderFactory>;
89
+ readonly #default: string | undefined;
90
+ readonly #options: ClientOptions;
91
+ readonly #clients = new Map<string, PolarisClient>();
92
+ #fake:
93
+ | {
94
+ readonly provider: FakeProvider;
95
+ readonly clients: Map<string, PolarisClient>;
96
+ }
97
+ | undefined;
98
+
99
+ constructor(config: PolarisConfig<KnownProviders>) {
100
+ const providers: Record<string, ProviderFactory> = config.providers;
101
+ const declared = Object.keys(providers);
102
+ if (declared.length === 0) {
103
+ throw new E_POLARIS_INVALID_CONFIG(["`providers` declares none"]);
104
+ }
105
+ for (const name of declared) {
106
+ if (typeof providers[name] !== "function") {
107
+ throw new E_POLARIS_INVALID_CONFIG([
108
+ `providers.${name} is not a provider factory`,
109
+ ]);
110
+ }
111
+ }
112
+ if (
113
+ config.default !== undefined &&
114
+ !Object.hasOwn(providers, config.default)
115
+ ) {
116
+ throw new E_POLARIS_INVALID_CONFIG([
117
+ `default names '${config.default}', which is not in providers (${declared.join(", ")})`,
118
+ ]);
119
+ }
120
+
121
+ const timeout = config.timeout ?? DEFAULT_TIMEOUT;
122
+ if (!isTimeout(timeout)) {
123
+ throw new E_POLARIS_INVALID_CONFIG([
124
+ `timeout must be a positive integer of ms, at most ${MAX_TIMEOUT}`,
125
+ ]);
126
+ }
127
+ const maxResponseBytes =
128
+ config.maxResponseBytes ?? DEFAULT_MAX_RESPONSE_BYTES;
129
+ if (!Number.isSafeInteger(maxResponseBytes) || maxResponseBytes <= 0) {
130
+ throw new E_POLARIS_INVALID_CONFIG([
131
+ "maxResponseBytes must be a positive integer",
132
+ ]);
133
+ }
134
+ if (config.fetch !== undefined && typeof config.fetch !== "function") {
135
+ throw new E_POLARIS_INVALID_CONFIG(["fetch must be a function"]);
136
+ }
137
+
138
+ if (config.pricing !== undefined) checkPricing(config.pricing);
139
+ if (config.budget !== undefined && config.pricing === undefined) {
140
+ throw new E_POLARIS_INVALID_CONFIG([
141
+ "a `budget` needs a `pricing` table to know what requests cost",
142
+ ]);
143
+ }
144
+
145
+ this.#providers = providers;
146
+ this.#default = config.default;
147
+ this.#options = {
148
+ timeout,
149
+ maxResponseBytes,
150
+ fetch: config.fetch ?? ((input, init) => fetch(input, init)),
151
+ meter: {
152
+ ...(config.pricing !== undefined ? { pricing: config.pricing } : {}),
153
+ ...(config.budget !== undefined
154
+ ? {
155
+ // One store for every provider of this manager: a scope's spend
156
+ // is its spend, whichever provider it went to.
157
+ budget: {
158
+ ...config.budget,
159
+ store: config.budget.store ?? memoryBudgetStore(),
160
+ },
161
+ }
162
+ : {}),
163
+ ...(config.log !== undefined ? { log: config.log } : {}),
164
+ },
165
+ };
166
+ }
167
+
168
+ /**
169
+ * The provider declared under `name`, or the `default` one. Built on first
170
+ * use, then the same instance every time.
171
+ */
172
+ use<K extends keyof KnownProviders & string>(name?: K): PolarisClient {
173
+ const selected: string | undefined = name ?? this.#default;
174
+ if (selected === undefined) throw new E_POLARIS_NO_DEFAULT_PROVIDER();
175
+
176
+ const factory = Object.hasOwn(this.#providers, selected)
177
+ ? this.#providers[selected]
178
+ : undefined;
179
+ if (factory === undefined) {
180
+ throw new E_POLARIS_UNKNOWN_PROVIDER([
181
+ selected,
182
+ `Declared: ${Object.keys(this.#providers).join(", ")}.`,
183
+ ]);
184
+ }
185
+
186
+ const fake = this.#fake;
187
+ if (fake !== undefined) {
188
+ const faked =
189
+ fake.clients.get(selected) ??
190
+ new PolarisClient(
191
+ selected,
192
+ fake.provider.driver(selected),
193
+ this.#options,
194
+ );
195
+ fake.clients.set(selected, faked);
196
+ return faked;
197
+ }
198
+
199
+ const cached = this.#clients.get(selected);
200
+ if (cached) return cached;
201
+ const driver: unknown = factory();
202
+ if (!isDriver(driver)) {
203
+ throw new E_POLARIS_INVALID_CONFIG([
204
+ `providers.${selected} did not build a driver (provider, features and chat() are required)`,
205
+ ]);
206
+ }
207
+ const client = new PolarisClient(selected, driver, this.#options);
208
+ this.#clients.set(selected, client);
209
+ return client;
210
+ }
211
+
212
+ /**
213
+ * Answer every request from a script instead of the providers, until
214
+ * `restore()`: for tests. Prices, budgets and the log apply as usual.
215
+ *
216
+ * const fake = polaris.fake()
217
+ * fake.reply('Bonjour')
218
+ */
219
+ fake(options?: FakeOptions): FakeProvider {
220
+ const provider = new FakeProvider(options);
221
+ this.#fake = { provider, clients: new Map() };
222
+ return provider;
223
+ }
224
+
225
+ /** Back to the real providers after `fake()`. */
226
+ restore(): void {
227
+ this.#fake = undefined;
228
+ }
229
+
230
+ /** `use().chat()`: the default provider. */
231
+ chat(request: ChatRequest, options?: CallOptions): Promise<ChatResponse> {
232
+ return this.use().chat(request, options);
233
+ }
234
+
235
+ /** `use().stream()`: the default provider. */
236
+ stream(
237
+ request: ChatRequest,
238
+ options?: CallOptions,
239
+ ): AsyncGenerator<StreamEvent, void, undefined> {
240
+ return this.use().stream(request, options);
241
+ }
242
+
243
+ /** `use().run()`: the default provider. */
244
+ run(request: RunRequest, options?: RunOptions): Promise<RunResult> {
245
+ return this.use().run(request, options);
246
+ }
247
+
248
+ /** `use().streamTo()`: the default provider. */
249
+ streamTo(
250
+ sink: SseSink,
251
+ request: ChatRequest,
252
+ options?: StreamToOptions,
253
+ ): Promise<StreamToResult> {
254
+ return this.use().streamTo(sink, request, options);
255
+ }
256
+
257
+ /** `use().extract()`: the default provider. */
258
+ extract<S extends StandardSchema>(
259
+ request: ExtractRequest<S>,
260
+ options?: ExtractOptions,
261
+ ): Promise<ExtractResult<SchemaOutput<S>>> {
262
+ return this.use().extract(request, options);
263
+ }
264
+
265
+ /** `use().embed()`: the default provider. */
266
+ embed(request: EmbedRequest, options?: CallOptions): Promise<EmbedResponse> {
267
+ return this.use().embed(request, options);
268
+ }
269
+ }
270
+
271
+ function isDriver(value: unknown): value is PolarisDriver {
272
+ if (typeof value !== "object" || value === null) return false;
273
+ const features: unknown = Reflect.get(value, "features");
274
+ return (
275
+ typeof Reflect.get(value, "provider") === "string" &&
276
+ typeof Reflect.get(value, "chat") === "function" &&
277
+ typeof features === "object" &&
278
+ features !== null
279
+ );
280
+ }