@voltojs/providers 0.0.0-stage → 0.2.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 (63) hide show
  1. package/LICENSE +21 -0
  2. package/dist/anthropic/index.d.ts +5 -0
  3. package/dist/anthropic/index.d.ts.map +1 -0
  4. package/dist/anthropic/index.js +3 -0
  5. package/dist/anthropic/index.js.map +1 -0
  6. package/dist/anthropic/model-port.d.ts +34 -0
  7. package/dist/anthropic/model-port.d.ts.map +1 -0
  8. package/dist/anthropic/model-port.js +337 -0
  9. package/dist/anthropic/model-port.js.map +1 -0
  10. package/dist/anthropic/stream-normalize.d.ts +27 -0
  11. package/dist/anthropic/stream-normalize.d.ts.map +1 -0
  12. package/dist/anthropic/stream-normalize.js +140 -0
  13. package/dist/anthropic/stream-normalize.js.map +1 -0
  14. package/dist/embedder-openai/embedder.d.ts +18 -0
  15. package/dist/embedder-openai/embedder.d.ts.map +1 -0
  16. package/dist/embedder-openai/embedder.js +44 -0
  17. package/dist/embedder-openai/embedder.js.map +1 -0
  18. package/dist/embedder-openai/index.d.ts +3 -0
  19. package/dist/embedder-openai/index.d.ts.map +1 -0
  20. package/dist/embedder-openai/index.js +2 -0
  21. package/dist/embedder-openai/index.js.map +1 -0
  22. package/dist/openai/index.d.ts +5 -0
  23. package/dist/openai/index.d.ts.map +1 -0
  24. package/dist/openai/index.js +3 -0
  25. package/dist/openai/index.js.map +1 -0
  26. package/dist/openai/model-port.d.ts +37 -0
  27. package/dist/openai/model-port.d.ts.map +1 -0
  28. package/dist/openai/model-port.js +330 -0
  29. package/dist/openai/model-port.js.map +1 -0
  30. package/dist/openai/stream-normalize.d.ts +70 -0
  31. package/dist/openai/stream-normalize.d.ts.map +1 -0
  32. package/dist/openai/stream-normalize.js +185 -0
  33. package/dist/openai/stream-normalize.js.map +1 -0
  34. package/dist/pi-ai/catalog.d.ts +40 -0
  35. package/dist/pi-ai/catalog.d.ts.map +1 -0
  36. package/dist/pi-ai/catalog.js +38 -0
  37. package/dist/pi-ai/catalog.js.map +1 -0
  38. package/dist/pi-ai/collection.d.ts +133 -0
  39. package/dist/pi-ai/collection.d.ts.map +1 -0
  40. package/dist/pi-ai/collection.js +532 -0
  41. package/dist/pi-ai/collection.js.map +1 -0
  42. package/dist/pi-ai/context.d.ts +15 -0
  43. package/dist/pi-ai/context.d.ts.map +1 -0
  44. package/dist/pi-ai/context.js +414 -0
  45. package/dist/pi-ai/context.js.map +1 -0
  46. package/dist/pi-ai/index.d.ts +8 -0
  47. package/dist/pi-ai/index.d.ts.map +1 -0
  48. package/dist/pi-ai/index.js +4 -0
  49. package/dist/pi-ai/index.js.map +1 -0
  50. package/dist/pi-ai/model-port.d.ts +45 -0
  51. package/dist/pi-ai/model-port.d.ts.map +1 -0
  52. package/dist/pi-ai/model-port.js +168 -0
  53. package/dist/pi-ai/model-port.js.map +1 -0
  54. package/dist/pi-ai/replay.d.ts +46 -0
  55. package/dist/pi-ai/replay.d.ts.map +1 -0
  56. package/dist/pi-ai/replay.js +99 -0
  57. package/dist/pi-ai/replay.js.map +1 -0
  58. package/dist/pi-ai/stream-normalize.d.ts +13 -0
  59. package/dist/pi-ai/stream-normalize.d.ts.map +1 -0
  60. package/dist/pi-ai/stream-normalize.js +118 -0
  61. package/dist/pi-ai/stream-normalize.js.map +1 -0
  62. package/package.json +48 -3
  63. package/README.md +0 -3
@@ -0,0 +1,532 @@
1
+ import { createModels, createProvider, getSupportedThinkingLevels, } from "@earendil-works/pi-ai";
2
+ import { openAICompletionsApi } from "@earendil-works/pi-ai/api/openai-completions.lazy";
3
+ import { openAIResponsesApi } from "@earendil-works/pi-ai/api/openai-responses.lazy";
4
+ import { anthropicMessagesApi } from "@earendil-works/pi-ai/api/anthropic-messages.lazy";
5
+ import { builtinProviders } from "@earendil-works/pi-ai/providers/all";
6
+ const PROVIDER_PROTOCOLS = [
7
+ "openai-completions",
8
+ "openai-responses",
9
+ "anthropic-messages",
10
+ ];
11
+ export function isProviderProtocol(value) {
12
+ return typeof value === "string"
13
+ && PROVIDER_PROTOCOLS.includes(value);
14
+ }
15
+ /**
16
+ * Resolve one model's protocol without side effects.
17
+ *
18
+ * Priority: model override > provider default > catalog api > custom default.
19
+ * `auto` at the provider level means "follow the catalog"; custom providers
20
+ * have no catalog entry, so they fall back to openai-completions.
21
+ */
22
+ export function resolveProviderProtocol(config, model, catalogApi) {
23
+ const configured = config.kind === "catalog"
24
+ ? config.modelProtocols?.[model] ?? config.protocol
25
+ : config.models.find((entry) => entry.code === model)?.protocol ?? config.protocol;
26
+ if (configured !== undefined && configured !== "auto") {
27
+ if (!isProviderProtocol(configured)) {
28
+ throw new Error(`pi-ai: unknown protocol "${String(configured)}" for provider "${config.id}" model "${model}"`);
29
+ }
30
+ return configured;
31
+ }
32
+ if (catalogApi !== undefined) {
33
+ // Catalog providers outside the three first-class protocols keep their
34
+ // own API (Google, Bedrock, ...). `undefined` means "preserve catalog".
35
+ return isProviderProtocol(catalogApi) ? catalogApi : undefined;
36
+ }
37
+ return "openai-completions";
38
+ }
39
+ /** Fallbacks used only because hand-declared config models lack a real catalog entry. */
40
+ const DEFAULT_CONTEXT_WINDOW = 128_000;
41
+ const DEFAULT_MAX_TOKENS = 4096;
42
+ /**
43
+ * Plain fixed-key auth. Deliberately not `envApiKeyAuth`: that helper reads
44
+ * `process.env` inside pi-ai, reintroducing the env-var fallback this repo's
45
+ * phase-one work removed. `resolve()` ignores `ctx`/`credential` and always
46
+ * returns the configured key.
47
+ */
48
+ function fixedApiKeyAuth(providerId, apiKey) {
49
+ return {
50
+ name: `${providerId} API key`,
51
+ resolve: async () => ({ auth: { apiKey } }),
52
+ };
53
+ }
54
+ /**
55
+ * Normalize a configured base URL the way the old `provider-openai` port did:
56
+ * strip trailing slashes, then append `/v1` unless the URL already ends in
57
+ * `/v1`. pi-ai does no normalization of its own — it hands `model.baseUrl`
58
+ * straight to the OpenAI SDK, which appends `/chat/completions` — so without
59
+ * this, `https://api.openai.com` (no `/v1`) 404s and every pre-existing
60
+ * `https://gateway.example` style config breaks.
61
+ */
62
+ function normalizeBaseUrl(baseUrl, protocol) {
63
+ const trimmed = baseUrl.replace(/\/+$/, "");
64
+ // The OpenAI SDK appends /chat/completions (or /responses) after /v1. The
65
+ // Anthropic SDK appends /v1/messages itself, so an Anthropic-compatible
66
+ // gateway must keep its configured path verbatim (e.g. Qwen's
67
+ // /apps/anthropic endpoint).
68
+ if (protocol === "anthropic-messages")
69
+ return trimmed;
70
+ return trimmed.endsWith("/v1") ? trimmed : `${trimmed}/v1`;
71
+ }
72
+ /**
73
+ * Input knowledge that `Model.input` alone cannot express.
74
+ *
75
+ * pi-ai reads `Model.input` on the wire path to decide whether to actually
76
+ * attach images, and that value is binary-per-value — it cannot express
77
+ * "the config never said". A hand-declared model with no `input` therefore
78
+ * ships image-capable (spec §7: UNKNOWN is not text-only). Catalog models
79
+ * are authoritative from their (possibly overridden) `Model.input`; custom
80
+ * and synthesized models are registered here so `describeModelInfo` can
81
+ * leave `input` absent when the config never said.
82
+ */
83
+ const inputDeclarations = new WeakMap();
84
+ /**
85
+ * Build the pi-ai `Model` for one hand-declared config entry. `reasoning`
86
+ * comes straight from the config flag (default `false`, unchanged from phase
87
+ * two); `thinkingLevelMap` is deliberately left unset even when
88
+ * `reasoning: true` — `getSupportedThinkingLevels()` already yields a
89
+ * sensible default level set (off/minimal/low/medium/high, `xhigh`/`max`
90
+ * excluded) for a `reasoning: true` model with no explicit map
91
+ * (dist/models.js:551-562), which is the best a generic hand-declared
92
+ * OpenAI-completions gateway can claim without per-model level metadata.
93
+ *
94
+ * `baseUrl` must be set here, on the model itself: pi-ai only ever rewrites a
95
+ * model's base URL from `auth.baseUrl` inside `applyAuth`
96
+ * (dist/models.js:375), which we don't populate; `provider.baseUrl` is stored
97
+ * but never read on the request path. pi-ai's own built-in OpenAI provider
98
+ * confirms this is the intended shape (dist/providers/openai.js:9 sets
99
+ * `baseUrl` on the model, not just the provider).
100
+ */
101
+ function buildModel(providerId, providerBaseUrl, entry, protocol) {
102
+ const model = {
103
+ id: entry.code,
104
+ name: entry.name ?? entry.code,
105
+ api: protocol,
106
+ provider: providerId,
107
+ baseUrl: normalizeBaseUrl(providerBaseUrl, protocol),
108
+ reasoning: entry.reasoning ?? false,
109
+ // Three-state, per spec §7 / D3: an undeclared custom model stays
110
+ // image-capable on the wire — treating UNKNOWN as text-only would
111
+ // silently disable images for every gateway that cannot describe its
112
+ // own models. The declaration truth lives in inputDeclarations below.
113
+ // Spread copies: core's ModelInputValue is readonly, pi-ai's Model.input
114
+ // is mutable — same elements, fresh array.
115
+ input: [...(entry.input ?? ["text", "image"])],
116
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
117
+ contextWindow: entry.contextWindow ?? DEFAULT_CONTEXT_WINDOW,
118
+ maxTokens: entry.maxOutputTokens ?? DEFAULT_MAX_TOKENS,
119
+ };
120
+ inputDeclarations.set(model, entry.input);
121
+ return model;
122
+ }
123
+ /**
124
+ * Whether pi-ai's `developer` system role is safe for one catalog model.
125
+ *
126
+ * pi-ai sends the system prompt as `role: "developer"` whenever the model is
127
+ * reasoning-capable and `compat.supportsDeveloperRole` is not explicitly
128
+ * false — and `detectCompat` defaults that to true for any provider it does
129
+ * not recognize. `developer` is an OpenAI-specific role: a third-party
130
+ * OpenAI-compatible gateway that does not implement it takes the message but
131
+ * does not treat it as a system instruction, so the whole system prompt is
132
+ * silently demoted (observed with `xiaomi-token-plan-cn`, which pi-ai 0.85.1
133
+ * does not flag).
134
+ *
135
+ * Inverting the default is the safer error: a provider that DOES support
136
+ * `developer` still honours `system`, while one that does not silently drops
137
+ * the instructions. So only the providers known to implement it keep it.
138
+ */
139
+ function supportsDeveloperRole(piProvider, modelId) {
140
+ if (piProvider === "openai")
141
+ return true;
142
+ // OpenRouter proxies the upstream role through for these two families;
143
+ // matches pi-ai's own `isOpenRouterDeveloperRoleModel` rule.
144
+ if (piProvider === "openrouter") {
145
+ return modelId.startsWith("openai/") || modelId.startsWith("anthropic/");
146
+ }
147
+ return false;
148
+ }
149
+ /**
150
+ * Wrap one of pi-ai's built-in catalog providers as a `Provider` registered
151
+ * under pi-ai's own provider id, restricted to the user's selected model
152
+ * codes.
153
+ *
154
+ * `baseUrl` on each model is left exactly as pi-ai's catalog gives it — no
155
+ * `normalizeBaseUrl` — per rule 1 in the task brief: that helper exists only
156
+ * for hand-declared gateways where phase two found pi-ai does no
157
+ * normalization of its own; applying it to an already-correct catalog
158
+ * address would corrupt it.
159
+ *
160
+ * `config.baseURL`, when set, replaces that address on the provider AND on
161
+ * every model (pi-ai reads the model's own `baseUrl` on the request path —
162
+ * see {@link buildModel}). It too is used verbatim: catalog addresses differ
163
+ * per provider in both shape (`https://api.openai.com/v1` vs
164
+ * `https://api.deepseek.com`) and API dialect, so the openai-completions
165
+ * `/v1` rule cannot be applied to an override for an arbitrary one.
166
+ *
167
+ * `model.provider` is left as pi-ai's own provider id, and the provider is
168
+ * registered under that same id rather than volto's config id. Both must
169
+ * agree — `Models.stream`/`streamSimple` resolve the owning provider via
170
+ * `model.provider` looked up in the map `setProvider` populates
171
+ * (dist/models.js: `requireProvider` reads `this.providers.get(
172
+ * model.provider)`). Keeping pi-ai's id on both sides is what preserves
173
+ * `detectCompat`, which decides the wire format (system role, max-tokens
174
+ * field name, thinking-block format) from `model.provider` first and
175
+ * `model.baseUrl` second: rewriting the id to volto's own left only the URL
176
+ * check standing, and a configured `baseURL` override knocks that out too —
177
+ * silently switching providers like `xai`/`openrouter`/`cerebras` onto the
178
+ * wrong wire format. The cost is that one pi-ai provider can be configured
179
+ * only once per collection; `buildModels` rejects a duplicate rather than
180
+ * letting the second registration silently replace the first (including its
181
+ * API key).
182
+ *
183
+ * `auth` is deliberately rebuilt as a `fixedApiKeyAuth`, NOT the original
184
+ * catalog provider's own `ProviderAuth`. pi-ai's `resolveProviderAuthWithSignal`
185
+ * (dist/auth/resolve.js) only takes the `overrides.apiKey` branch when
186
+ * `options.apiKey` is defined; when a catalog provider is configured with no
187
+ * key (`config.apiKey === undefined`), it falls through to stored
188
+ * credentials and then to the provider's own ambient auth — for built-in
189
+ * providers like deepseek that is `envApiKeyAuth(...)`, which reads
190
+ * `process.env` inside pi-ai. Keeping `source.auth` here would silently
191
+ * reintroduce an env-var fallback, violating this repo's "nothing is read
192
+ * from the environment" invariant (see comments at top of this file and
193
+ * apps/gateway/src/wiring.ts). Using a fixed-key auth here — the
194
+ * same helper the custom-provider path uses — makes the no-env-fallback
195
+ * behavior structural rather than dependent on the UI always supplying a key.
196
+ */
197
+ /**
198
+ * One catalog model entry the user enabled whose code is not in this build's
199
+ * pi-ai catalog (a newly released model, or a typo). Synthesized only when
200
+ * the user also declared `reasoning: true` or a per-model `input` override —
201
+ * otherwise the code simply is not in the Models collection, same as before.
202
+ *
203
+ * `inputOverride`, when present, is the user's stored input declaration: it
204
+ * lands on the synthesized `Model.input` (so pi-ai's transformMessages honors
205
+ * it on the wire) AND in `inputDeclarations` (so `describeModelInfo` answers
206
+ * it). Absent, both stay as they were before this parameter existed: the
207
+ * declaration map records `undefined` (UNKNOWN) and the template/stub's own
208
+ * `input` stands on the wire.
209
+ *
210
+ * Template choice:
211
+ * - First reasoning-capable catalog model → inherit its thinkingLevelMap
212
+ * (real efforts for that provider family).
213
+ * - No reasoning model in the catalog at all → take any catalog model as a
214
+ * structural template, force `reasoning: true` and drop `thinkingLevelMap`
215
+ * so `getSupportedThinkingLevels` yields the same default level set a
216
+ * hand-declared custom model gets (minimal/low/medium/high).
217
+ */
218
+ function synthesizeUnknownCatalogModel(source, code, piProvider, baseURL, inputOverride, protocol) {
219
+ const catalogModels = source.getModels();
220
+ const reasoningTemplate = catalogModels.find((m) => m.reasoning);
221
+ const structural = reasoningTemplate ?? catalogModels[0];
222
+ if (structural) {
223
+ const synthesized = {
224
+ ...structural,
225
+ id: code,
226
+ name: code,
227
+ api: protocol,
228
+ ...(protocol !== structural.api ? { compat: undefined } : {}),
229
+ reasoning: true,
230
+ // No reasoning template: drop any inherited map so the default level
231
+ // set applies. `undefined` is equivalent to absent for the optional
232
+ // access in getSupportedThinkingLevels.
233
+ ...(reasoningTemplate ? {} : { thinkingLevelMap: undefined }),
234
+ ...(baseURL ? { baseUrl: baseURL } : {}),
235
+ // Same reasoning as inputDeclarations below: the template's
236
+ // inputLimits are directory facts about the TEMPLATE, not about a
237
+ // code the catalog does not know. Clear them so describeModelInfo's
238
+ // `!== undefined` gate reports absence (spec §4.1 / D5: "absent for
239
+ // custom/synthesized models") instead of fabricating a known fact.
240
+ inputLimits: undefined,
241
+ // User declaration wins; spread copy (core's ModelInputValue is
242
+ // readonly, pi-ai's Model.input is mutable). Without an override the
243
+ // template's inherited `input` stands on the wire while the
244
+ // declaration below keeps describeModelInfo at UNKNOWN.
245
+ ...(inputOverride !== undefined ? { input: [...inputOverride] } : {}),
246
+ };
247
+ // Inherited `input` alone is structural, not a statement about this
248
+ // unknown code — leave input UNKNOWN rather than trusting the template,
249
+ // unless the user explicitly declared one (which must stick everywhere).
250
+ inputDeclarations.set(synthesized, inputOverride);
251
+ return synthesized;
252
+ }
253
+ // Empty catalog — degrade to a custom-like OpenAI-completions stub.
254
+ const stub = {
255
+ id: code,
256
+ name: code,
257
+ api: protocol,
258
+ provider: piProvider,
259
+ baseUrl: baseURL ?? source.baseUrl ?? "https://api.openai.com",
260
+ reasoning: true,
261
+ // Same override semantics as the structural branch above: a stored
262
+ // declaration replaces the stub default, absence keeps UNKNOWN via the
263
+ // declaration map while the wire value stays the stub's `["text"]`.
264
+ input: inputOverride !== undefined ? [...inputOverride] : ["text"],
265
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
266
+ contextWindow: DEFAULT_CONTEXT_WINDOW,
267
+ maxTokens: DEFAULT_MAX_TOKENS,
268
+ };
269
+ inputDeclarations.set(stub, inputOverride);
270
+ return stub;
271
+ }
272
+ const PROTOCOL_API = {
273
+ "openai-completions": openAICompletionsApi,
274
+ "openai-responses": openAIResponsesApi,
275
+ "anthropic-messages": anthropicMessagesApi,
276
+ };
277
+ /** One implementation per protocol actually used by this provider. */
278
+ function protocolApiMap(models) {
279
+ const used = new Set(models.map((model) => model.api).filter(isProviderProtocol));
280
+ const out = {};
281
+ for (const protocol of used) {
282
+ out[protocol] = PROTOCOL_API[protocol]();
283
+ }
284
+ return out;
285
+ }
286
+ function buildCatalogProvider(config) {
287
+ const source = builtinProviders().find((provider) => provider.id === config.piProvider);
288
+ if (!source) {
289
+ throw new Error(`pi-ai: unknown catalog provider "${config.piProvider}"`);
290
+ }
291
+ const selected = new Set(config.modelCodes);
292
+ const catalogModels = source.getModels();
293
+ const knownIds = new Set(catalogModels.map((m) => m.id));
294
+ const originalApis = new Map(catalogModels.map((model) => [model.id, model.api]));
295
+ const models = catalogModels
296
+ .filter((model) => selected.has(model.id))
297
+ .map((model) => {
298
+ // Local so `!== undefined` narrows the possibly-undefined indexed
299
+ // read (noUncheckedIndexedAccess does not narrow element access).
300
+ const inputOverride = config.inputOverrides?.[model.id];
301
+ const protocol = resolveProviderProtocol(config, model.id, model.api);
302
+ return {
303
+ ...model,
304
+ ...(protocol !== undefined ? { api: protocol } : {}),
305
+ // A protocol override invalidates the catalog model's compat shape:
306
+ // OpenAI compat keys do not describe an Anthropic request. Let pi-ai
307
+ // auto-detect instead of carrying the old dialect's compat across.
308
+ ...(protocol !== undefined && protocol !== model.api
309
+ ? { compat: undefined }
310
+ : model.api === "openai-completions" || model.api === "openai-responses"
311
+ ? {
312
+ compat: {
313
+ ...model.compat,
314
+ supportsDeveloperRole: supportsDeveloperRole(config.piProvider, model.id),
315
+ },
316
+ }
317
+ : {}),
318
+ // User override wins over the catalog's own flag. Setting `reasoning:
319
+ // true` on a catalog model that declares none still yields the default
320
+ // thinking-level set via getSupportedThinkingLevels (see buildModel).
321
+ ...(config.reasoningOverrides?.[model.id] !== undefined
322
+ ? { reasoning: config.reasoningOverrides[model.id] }
323
+ : {}),
324
+ // Same override semantics as reasoning: absent keeps the catalog's
325
+ // own modalities. Landing on `Model.input` also drives pi-ai's
326
+ // transformMessages image stripping, so the declaration sticks on
327
+ // the wire, not just in describeModelInfo. Spread copies: core's
328
+ // ModelInputValue is readonly, pi-ai's Model.input is mutable.
329
+ ...(inputOverride !== undefined ? { input: [...inputOverride] } : {}),
330
+ ...(config.baseURL ? { baseUrl: config.baseURL } : {}),
331
+ };
332
+ });
333
+ // Enabled codes the catalog does not know: synthesize an entry when the
334
+ // user declared anything about it (forced reasoning OR a stored input
335
+ // override) so describeModel / effort validation / the input backstop keep
336
+ // working instead of dropping the user's declared intent on the floor.
337
+ for (const code of config.modelCodes) {
338
+ if (knownIds.has(code))
339
+ continue;
340
+ const inputOverride = config.inputOverrides?.[code];
341
+ if (config.reasoningOverrides?.[code] !== true && inputOverride === undefined)
342
+ continue;
343
+ models.push(synthesizeUnknownCatalogModel(source, code, config.piProvider, config.baseURL, inputOverride, resolveProviderProtocol(config, code, source.getModels()[0]?.api) ?? "openai-completions"));
344
+ }
345
+ const apis = protocolApiMap(models);
346
+ // Catalog models outside the three first-class protocols keep the catalog
347
+ // provider's own implementation; supported models dispatch through the
348
+ // selected API implementation. A manual Provider keeps that fallback
349
+ // available (createProvider's API map has no per-model fallback).
350
+ const dispatch = (model, run, fallback) => {
351
+ // Untouched catalog models keep the built-in provider wrapper (opencode's
352
+ // session header, cloudflare's URL placeholders, …). Only a model whose
353
+ // protocol was actually overridden needs a different API implementation.
354
+ if (originalApis.get(model.id) === model.api)
355
+ return fallback();
356
+ const streams = apis[model.api];
357
+ return streams !== undefined ? run(streams) : fallback();
358
+ };
359
+ return {
360
+ id: config.piProvider,
361
+ name: source.name,
362
+ baseUrl: config.baseURL ?? source.baseUrl,
363
+ auth: { apiKey: fixedApiKeyAuth(config.id, config.apiKey) },
364
+ getModels: () => models,
365
+ stream: (model, context, options) => dispatch(model, (streams) => streams.stream(model, context, options), () => source.stream(model, context, options)),
366
+ streamSimple: (model, context, options) => dispatch(model, (streams) => streams.streamSimple(model, context, options), () => source.streamSimple(model, context, options)),
367
+ };
368
+ }
369
+ /**
370
+ * Assemble a pi-ai `Models` collection from volto's configured providers.
371
+ * `kind: "custom"` entries become a hand-declared gateway via
372
+ * `createProvider`, exactly as in phase two. `kind: "catalog"` entries
373
+ * register a restricted view of one of pi-ai's built-in providers — see
374
+ * {@link buildCatalogProvider}.
375
+ */
376
+ /**
377
+ * The id one configured provider is registered under in the `Models`
378
+ * collection, which is what `getModel`/`describeModelInfo` must be called
379
+ * with — pi-ai's own provider id for catalog entries (see
380
+ * {@link buildCatalogProvider}), the config id for hand-declared ones.
381
+ */
382
+ export function registryProviderId(providers, configId) {
383
+ const config = providers.find((p) => p.id === configId);
384
+ if (config === undefined)
385
+ return configId;
386
+ return config.kind === "catalog" ? config.piProvider : config.id;
387
+ }
388
+ export function buildModels(providers) {
389
+ for (const provider of providers) {
390
+ if (provider.kind === "catalog") {
391
+ if (provider.protocol !== undefined && provider.protocol !== "auto"
392
+ && !isProviderProtocol(provider.protocol)) {
393
+ throw new Error(`pi-ai: unknown protocol "${String(provider.protocol)}" for provider "${provider.id}"`);
394
+ }
395
+ for (const code of provider.modelCodes) {
396
+ resolveProviderProtocol(provider, code);
397
+ }
398
+ }
399
+ else {
400
+ if (provider.protocol !== undefined && !isProviderProtocol(provider.protocol)) {
401
+ throw new Error(`pi-ai: unknown protocol "${String(provider.protocol)}" for provider "${provider.id}"`);
402
+ }
403
+ for (const model of provider.models) {
404
+ resolveProviderProtocol(provider, model.code);
405
+ }
406
+ }
407
+ }
408
+ const models = createModels();
409
+ // setProvider silently replaces an existing registration, so a collision
410
+ // would drop one provider's models AND its API key without a word. Both
411
+ // kinds share one namespace because a hand-declared provider registers
412
+ // under its config id, which could equal some pi-ai provider id.
413
+ const registered = new Map();
414
+ const claim = (key, configId) => {
415
+ const owner = registered.get(key);
416
+ if (owner !== undefined) {
417
+ throw new Error(`pi-ai: provider "${key}" is already configured (by "${owner}"); ` +
418
+ `configure each built-in provider at most once.`);
419
+ }
420
+ registered.set(key, configId);
421
+ };
422
+ for (const config of providers) {
423
+ if (config.kind === "catalog") {
424
+ claim(config.piProvider, config.id);
425
+ models.setProvider(buildCatalogProvider(config));
426
+ continue;
427
+ }
428
+ claim(config.id, config.id);
429
+ const builtModels = config.models.map((entry) => buildModel(config.id, config.baseURL, entry, resolveProviderProtocol(config, entry.code) ?? "openai-completions"));
430
+ const apis = protocolApiMap(builtModels);
431
+ // An empty custom provider is valid while the user is still adding
432
+ // models; pi-ai still requires one API implementation at construction.
433
+ if (Object.keys(apis).length === 0)
434
+ apis["openai-completions"] = openAICompletionsApi();
435
+ const provider = createProvider({
436
+ id: config.id,
437
+ name: config.name,
438
+ baseUrl: config.baseURL,
439
+ auth: { apiKey: fixedApiKeyAuth(config.id, config.apiKey) },
440
+ models: builtModels,
441
+ api: apis,
442
+ });
443
+ models.setProvider(provider);
444
+ }
445
+ return models;
446
+ }
447
+ /**
448
+ * API key to inject on each `streamSimple`/`stream` request for a configured
449
+ * provider. Catalog providers use per-request injection (rule 2): the key is
450
+ * read straight from the live config on every call, never baked into an auth
451
+ * object. Custom providers already bake their key into a `fixedApiKeyAuth`
452
+ * at `buildModels()` time, so this returns `undefined` for them and the
453
+ * caller simply omits the request-level `apiKey` option.
454
+ */
455
+ export function resolveConfiguredApiKey(providers, providerId) {
456
+ const config = providers.find((p) => p.id === providerId);
457
+ return config?.kind === "catalog" ? config.apiKey : undefined;
458
+ }
459
+ /** Capitalize a pi-ai thinking-level id for display, e.g. "high" -> "High". */
460
+ function displayName(level) {
461
+ return level.length === 0 ? level : level[0].toUpperCase() + level.slice(1);
462
+ }
463
+ /** Cache support implied by the wire protocol and pi-ai's promptCache metadata. */
464
+ export function cacheCapability(model) {
465
+ if (model.api === "anthropic-messages") {
466
+ return {
467
+ mode: "explicit",
468
+ minTokens: 1024,
469
+ maxMarkers: 4,
470
+ blockWindow: 20,
471
+ ...(model.promptCache?.short !== undefined ? { ttlSeconds: model.promptCache.short } : {}),
472
+ writeUsageField: "cache_creation_input_tokens",
473
+ };
474
+ }
475
+ if (model.api === "openai-completions" || model.api === "openai-responses") {
476
+ return {
477
+ mode: "implicit",
478
+ ...(model.promptCache?.short !== undefined ? { minTokens: 1024 } : {}),
479
+ };
480
+ }
481
+ return { mode: "none" };
482
+ }
483
+ /**
484
+ * Resolve capability metadata for one exact model. `reasoning` is present
485
+ * only when the model is flagged `reasoning: true` and
486
+ * `getSupportedThinkingLevels()` yields at least one non-"off" level; never a
487
+ * synthesized off-only list (an off-only control would be byte-identical to
488
+ * omitting the option entirely).
489
+ *
490
+ * `input` is a tri-state: catalog models publish the catalog's own
491
+ * `input` modalities (a fact either way); custom and synthesized models
492
+ * publish only an explicit config declaration — absence stays UNKNOWN.
493
+ */
494
+ export function describeModelInfo(models, providerId, code) {
495
+ const model = models.getModel(providerId, code);
496
+ if (!model) {
497
+ throw new Error(`pi-ai: unknown model "${code}" for provider "${providerId}"`);
498
+ }
499
+ const info = {
500
+ model: code,
501
+ api: model.api,
502
+ cache: cacheCapability(model),
503
+ contextWindow: model.contextWindow,
504
+ };
505
+ if (model.reasoning) {
506
+ const levels = getSupportedThinkingLevels(model).filter((level) => level !== "off");
507
+ if (levels.length > 0) {
508
+ const reasoning = {
509
+ efforts: levels.map((level) => ({
510
+ id: level, // branded type: effort id is published verbatim from pi-ai; core never interprets it
511
+ name: displayName(level),
512
+ })),
513
+ };
514
+ info.reasoning = reasoning;
515
+ }
516
+ }
517
+ // Tri-state input (spec D2): custom/synthesized models answer from
518
+ // inputDeclarations (absent = UNKNOWN → field omitted); catalog and
519
+ // test-injected models answer from their own Model.input, a fact.
520
+ const input = inputDeclarations.has(model)
521
+ ? inputDeclarations.get(model)
522
+ : model.input;
523
+ if (input !== undefined) {
524
+ info.input = input;
525
+ }
526
+ // Directory fact, read-only (D5): custom/synthesized models have none.
527
+ if (model.inputLimits !== undefined) {
528
+ info.inputLimits = model.inputLimits;
529
+ }
530
+ return info;
531
+ }
532
+ //# sourceMappingURL=collection.js.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AC,GAAG,CAAC,KAAK,CAAC;QACxC,CAAC,CAAC,iBAAiB,CAAC,GAAG,CAAC,KAAK,CAAC;QAC9B,CAAC,CAAC,KAAK,CAAC,KAAK,CAAC;IAChB,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;QACxB,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;IACrB,CAAC;IACD,uEAAuE;IACvE,IAAI,KAAK,CAAC,WAAW,KAAK,SAAS,EAAE,CAAC;QACpC,IAAI,CAAC,WAAW,GAAG,KAAK,CAAC,WAAW,CAAC;IACvC,CAAC;IAED,OAAO,IAAI,CAAC;AACd,CAAC"}
@@ -0,0 +1,15 @@
1
+ import type { Api as PiApi, Context as PiContext, Model as PiModel } from "@earendil-works/pi-ai";
2
+ import type { ModelRequest } from "@voltojs/core";
3
+ /**
4
+ * Translate core's neutral Message[] (and tool definitions) into a pi-ai
5
+ * Context ready to hand to Models.stream/streamSimple.
6
+ *
7
+ * `model` is the current route's resolved pi-ai Model. Its `id` is passed
8
+ * through to `readReplayEnvelope` so a message produced by a different model
9
+ * degrades to unsigned content instead of replaying a foreign provider's
10
+ * signatures; its `api`/`provider`/`id` are also stamped onto outgoing
11
+ * assistant messages so pi-ai's own `transformMessages` isSameModel check
12
+ * (which gates whether signed thinking/tool-call blocks survive) passes.
13
+ */
14
+ export declare function toPiContext(req: ModelRequest, model: PiModel<PiApi>): PiContext;
15
+ //# sourceMappingURL=context.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"context.d.ts","sourceRoot":"","sources":["../../src/pi-ai/context.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,GAAG,IAAI,KAAK,EAEZ,OAAO,IAAI,SAAS,EAKpB,KAAK,IAAI,OAAO,EAQjB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,KAAK,EAIV,YAAY,EAGb,MAAM,eAAe,CAAC;AAGvB;;;;;;;;;;GAUG;AACH,wBAAgB,WAAW,CAAC,GAAG,EAAE,YAAY,EAAE,KAAK,EAAE,OAAO,CAAC,KAAK,CAAC,GAAG,SAAS,CA0C/E"}