Skip to content
Source
Sign inSign up
TanStack/schemas
Open History to see the last commit

types.ts

792 lines30.1 KB

1import type { Activity } from '#/db/schema.ts'
2import type { ChatRequestMap } from './request-map.ts'
3​
4/**
5 * Provider registry types — ported from TanStack AI PR #622's
6 * `ProviderConfig`, adapted to Workers: no filesystem caching (fetchSpec
7 * returns parsed documents), and model listing is a first-class operation
8 * (the 15-minute poll tier).
9 */
10​
11/**
12 * How a schema's content was arrived at — a trust ladder, strongest first.
13 * Agents use it to weigh how much a schema can be relied on, and it makes a
14 * stale hand-written corner visible instead of invisible.
15 *
16 * - `upstream-spec` — extracted from a machine-readable document the
17 * provider itself publishes and we re-fetch every sync. Self-healing.
18 * - `generated` — derived at sync time from a provider-published
19 * artifact that is not a spec (BytePlus's Go SDK structs). Also
20 * self-healing, one inference step removed from the wire.
21 * - `probe-verified` — hand-written, but every field confirmed against live
22 * API calls on `verifiedAt`. Accurate as of that date; does not self-heal.
23 * - `docs-derived` — hand-written from prose documentation and NOT
24 * confirmed against the API. The weakest claim we make.
25 */
26export type Derivation =
27 | 'upstream-spec'
28 | 'generated'
29 | 'probe-verified'
30 | 'docs-derived'
31​
32/**
33 * Operation-level provenance annotation, read back by the sync engine —
34 * same trick as FAL's activity marker. Set it on an OpenAPI operation to
35 * override the provider's `defaultDerivation` for that one endpoint.
36 */
37export const PROVENANCE_MARKER = 'x-modelschemas-provenance'
38​
39export interface EndpointProvenance {
40 derivation: Derivation
41 /**
42 * `YYYY-MM-DD` the claim was last confirmed. Meaningful for
43 * `probe-verified`; omitted for the self-healing derivations, whose
44 * freshness is already the sync timestamp.
45 */
46 verifiedAt?: string
48​
49/** A parsed OpenAPI document (loosely typed; pure JSON manipulation). */
50export type OpenApiOperation = Record<string, unknown>
51​
52export interface OpenApiDocument {
53 openapi?: string
54 info?: Record<string, unknown>
55 servers?: Array<Record<string, unknown>>
56 paths?: Record<string, Record<string, OpenApiOperation>>
57 components?: { schemas?: Record<string, unknown> } & Record<string, unknown>
58 [key: string]: unknown
60​
61/** Secrets a provider may need; mirrors `providers.auth_env_var` values. */
62export interface ProviderSecrets {
63 OPENAI_API_KEY?: string
64 ANTHROPIC_API_KEY?: string
65 GEMINI_API_KEY?: string
66 XAI_API_KEY?: string
67 ELEVENLABS_API_KEY?: string
68 FAL_KEY?: string
69 /**
70 * BytePlus Ark data plane. Optional: it upgrades BytePlus's model catalog
71 * from the embedded one to Ark's live listing. Region-isolated — a key
72 * issued for ap-southeast does not work against the EU host.
73 */
74 ARK_API_KEY?: string
75 /**
76 * BytePlus Seed Speech (the voice host) — a separate product key from Ark;
77 * an Ark key there fails with `45000010 Invalid X-Api-Key`. Not consumed by
78 * the sync pipeline (Seed Speech exposes no spec or model-list endpoint);
79 * declared so local probe scripts share one canonical name.
80 */
81 SEED_SPEECH_API_KEY?: string
82 // Adapter-batch secrets (docs/providers-to-add.md). Optional: a missing
83 // key skips listModels; fetchSpec stays keyless whenever the spec is public.
84 MISTRAL_API_KEY?: string
85 REPLICATE_API_TOKEN?: string
86 GROQ_API_KEY?: string
87 FIREWORKS_API_KEY?: string
88 TOGETHER_API_KEY?: string
89 VOYAGE_API_KEY?: string
90 COHERE_API_KEY?: string
91 DEEPSEEK_API_KEY?: string
92 MOONSHOT_API_KEY?: string
93 DASHSCOPE_API_KEY?: string
94 DEEPGRAM_API_KEY?: string
95 ASSEMBLYAI_API_KEY?: string
96 RUNWAY_API_KEY?: string
97 CARTESIA_API_KEY?: string
98 PERPLEXITY_API_KEY?: string
99 CEREBRAS_API_KEY?: string
100 SAMBANOVA_API_KEY?: string
101 JINA_API_KEY?: string
102 STABILITY_API_KEY?: string
103 BFL_API_KEY?: string
104 KLING_API_KEY?: string
105 HYPERBOLIC_API_KEY?: string
106 NOVITA_API_KEY?: string
107 /**
108 * Baseten Model APIs. `GET https://inference.baseten.co/v1/models` is
109 * the catalog; it requires this key. Absent → listModels skips.
110 */
111 BASETEN_API_KEY?: string
112 /**
113 * Reactor (reactor.inc). Optional for sync/poll: `GET /pricing` is public
114 * and the spec is embedded. The key (`rk_...`) is the data-plane
115 * `Reactor-API-Key` header for `POST /tokens` and live sessions.
116 */
117 REACTOR_API_KEY?: string
118 /**
119 * PostHog project token (phc_…) for ingest failure events. Optional:
120 * absent means capture is a no-op. US cloud, project 643425.
121 */
122 POSTHOG_PROJECT_KEY?: string
123 /**
124 * Optional token for `api.github.com`. Workers share egress IPs, so the
125 * anonymous 60-requests-per-hour quota returns 403. Sent as
126 * `Authorization: Bearer` on that host only. Absent or blank: those
127 * requests stay anonymous. `raw.githubusercontent.com` never uses it.
128 */
129 GITHUB_TOKEN?: string
131​
132/** Provider secrets plus native documentation runtime bindings. */
133export interface ProviderEnvironment extends ProviderSecrets {
134 /** Cloudflare Browser Rendering reads native public documents; no AI extraction. */
135 BROWSER?: Pick<BrowserRun, 'quickAction'>
137​
138/**
139 * How one catalog fact was arrived at (issue #53). Strongest first:
140 * listing → docs-extracted → bound schema (`Derivation` rungs).
141 * `generated` schemas are not walked onto catalog rows.
142 */
143export type FactDerivation = Derivation | 'listing' | 'docs-extracted'
144​
145/** Provenance for one stored catalog field or capability flag. */
146export interface FactSource {
147 derivation: FactDerivation
148 sourceUrl?: string
149 sourceHash?: string
150 fetchedAt?: number
151 /** Bound generation route, when the winner is the schema. */
152 endpointId?: string
153 /** JSON pointer or field name in the source document. */
154 path?: string
156​
157/** Per-field (and per-flag) provenance for a catalog row. */
158export interface ModelFactSources {
159 schemaEndpointId?: FactSource
160 /** `normalized`: the id matched only after dots were read as hyphens. */
161 sameAs?: FactSource & { normalized?: true }
162 contextWindow?: FactSource
163 maxOutput?: FactSource
164 modalities?: FactSource
165 pricing?: FactSource
166 /**
167 * One source per flag in the stored map, for a `true` and a `false`
168 * alike. `path: 'unlisted'` on a `false` means the provider published the
169 * model's whole flag list and the flag is not in it.
170 */
171 capabilities?: Record<string, FactSource>
172 knowledgeCutoff?: FactSource
173 /** Covers `openWeights` and `weightsUrl`. */
174 openWeights?: FactSource
175 reasoning?: FactSource
176 /** Chat wire map read from this model's own request schema. */
177 requestMap?: FactSource
178 /** Field-specific evidence when a request map combines native sources. */
179 requestMapFields?: Partial<Record<keyof ChatRequestMap, FactSource>>
180 /** One source per tool type id in `serverTools`. */
181 serverTools?: Record<string, FactSource>
183​
184/**
185 * A provider's own statement of which upstream model a row is; kept even
186 * while that model has no catalog row.
187 */
188export interface UpstreamModelIdentity {
189 /** A provider id, or a name `provider_model_namespaces` maps to one. */
190 providerNamespace: string
191 rawId: string
192 source: FactSource
194​
195/**
196 * How a model's thinking is configured (issue #77). Null on a row means the
197 * model does not reason, or its source names no control for it.
198 *
199 * `mode` names the one control the request exposes:
200 * - `adaptive`: the model decides (Anthropic `thinking.type: adaptive`). A
201 * three-state switch with an `auto` value (`enabled | disabled | auto`)
202 * is `adaptive` too.
203 * - `budget`: a token budget (`thinking.budget_tokens`, Gemini 2.5
204 * `thinkingBudget`). A switch plus a budget is `budget`.
205 * - `effort`: a level (`reasoning_effort`, Gemini 3 `thinkingLevel`). A
206 * switch plus levels is `effort`.
207 * - `toggle`: an on/off switch and nothing else (`thinking.type: enabled |
208 * disabled`, `enable_thinking`, `reasoning_mode: think | no_think`). It
209 * says nothing about whether the model thinks when the field is omitted.
210 *
211 * `mandatory` has one meaning on every mode:
212 * - `true`: the provider's own source STATES thinking cannot be turned off
213 * for this model ("cannot be disabled", an upstream `mandatory` boolean).
214 * On a `toggle`: the model takes the switch and its off value is rejected,
215 * so send "on" or omit the field.
216 * - `false`: the source states it can be turned off: documented prose, or
217 * an off value (`none`, `disabled`, `off`, `no_think`) in this model's
218 * OWN request schema or level list.
219 * - `null`: unstated. Never read it as `false`: do not offer an off option
220 * from it, and do not claim thinking is forced. A schema SHARED by many
221 * models that lists an off value states nothing about one model, so it is
222 * `null`. A level list with no `none` is not a statement, so it is
223 * `null`. A probe (off returns 400) is not a source.
224 *
225 * `efforts`: the accepted effort values as published, an off value such as
226 * `none` included. Never present on `toggle`.
227 *
228 * No object is stored when the source names no request field for the model:
229 * a catalog flag alone, thinking picked by a model-id suffix or a prompt
230 * tag, or a model that always thinks and takes no parameter. The
231 * `reasoning` capability flag carries those. A `toggle` is stored only
232 * with a stated `mandatory`: `{ mode: 'toggle', mandatory: null }` is not a
233 * fact, and `reasoningViolation` refuses it.
234 *
235 * Many rows written before this rule infer `true` from a level list with
236 * no `none`; README "Releasing on npm" lists the providers.
237 */
238export interface ModelReasoning {
239 mode: 'adaptive' | 'budget' | 'effort' | 'toggle'
240 mandatory: boolean | null
241 efforts?: Array<string>
243​
244const REASONING_MODES = ['adaptive', 'budget', 'effort', 'toggle']
245​
246/**
247 * Why a value is not a storable `ModelReasoning`, or null when it is. The
248 * poller runs every listed row through this before the write.
249 */
250export function reasoningViolation(value: unknown): string | null {
251 if (typeof value !== 'object' || value === null) return 'not an object'
252 const { mode, mandatory, efforts } = value as Record<string, unknown>
253 if (typeof mode !== 'string' || !REASONING_MODES.includes(mode)) {
254 return `unknown mode ${JSON.stringify(mode)}`
255 }
256 if (mandatory !== null && typeof mandatory !== 'boolean') {
257 return 'mandatory is not true, false or null'
258 }
259 if (mode === 'toggle' && mandatory === null) {
260 return 'a toggle needs a stated mandatory'
261 }
262 if (efforts === undefined) return null
263 if (mode === 'toggle') return 'a toggle takes no efforts'
264 if (
265 !Array.isArray(efforts) ||
266 efforts.length === 0 ||
267 !efforts.every((effort) => typeof effort === 'string' && effort !== '')
268 ) {
269 return 'efforts is not a non-empty array of strings'
270 }
271 return null
273​
274/** `ModelInfo.knowledgeCutoff` as stored: a month or a day, nothing else. */
275export const KNOWLEDGE_CUTOFF =
276 /^\d{4}-(0[1-9]|1[0-2])(-(0[1-9]|[12]\d|3[01]))?$/
277​
278/** The stored model columns a listing fills; each can be marked absent. */
279export type ModelFact =
280 | 'displayName'
281 | 'activity'
282 | 'contextWindow'
283 | 'maxOutput'
284 | 'modalities'
285 | 'pricing'
286 | 'capabilities'
287 | 'reasoning'
288 | 'serverTools'
289 | 'requestMap'
290 | 'aliases'
291 | 'schemaEndpointId'
292 | 'releasedAt'
293 | 'knowledgeCutoff'
294 | 'openWeights'
295 | 'providerMetadata'
296​
297/**
298 * Why a listing carries no value for a fact, when the adapter knows why.
299 * The poller's whole contract for one fact (the table describes the code;
300 * the fills on a bare omission predate it and every provider relies on them):
301 *
302 * | listing | poller writes | signal |
303 * | ------------------ | -------------------------------------- | --------------- |
304 * | a value | the value | none |
305 * | nothing, no reason | pricing: the stored card. | pricing only: |
306 * | | capabilities, modalities: what the | `pricing_lost` |
307 * | | bound request schema states, else null.| and 1 failure |
308 * | | requestMap: the provider table's map, | |
309 * | | else null. Any other fact: null | |
310 * | `cleared` | null, and the schema does not refill | none |
311 * | | it. requestMap: still the provider | |
312 * | | table's map (no stored "no map") | |
313 * | `unavailable` | the stored value and source | the docs failure|
314 *
315 * - `cleared`: the source was read and has no value now (the Hugging Face
316 * default route publishes no price, a price moved to a subscription).
317 * Only say it for a value the source visibly lacks; a shape the parser
318 * cannot read must throw. The poller refuses a poll that clears most of
319 * a provider's prices at once (`refusesPriceClears`).
320 * - `unavailable`: the source could not be read this poll (`tryDocs`). A
321 * new row has nothing stored, so the fact is null.
322 * - A reason wins over a value the listing also carries.
323 *
324 * Only pricing keeps its stored value on a bare omission: a parser that
325 * misses one row must not null a good price. `factSources.<fact>.path:
326 * 'silent'` is not this. It is stored provenance for a null whose page was
327 * read, and the fact is written like any omission. `deprecated` is not a
328 * fact here: a stored `deprecatedAt` cannot tell "upstream flagged it"
329 * from "it dropped off the listing".
330 *
331 * The facts added after that table follow it, with one exception:
332 *
333 * | fact | nothing, no reason |
334 * | ------------------ | ------------------------------------------------ |
335 * | `releasedAt` | the stored date, no signal. A release date does |
336 * | | not stop being true when a listing stops stating |
337 * | | it, and `firstSeenAt` keeps its backdate the |
338 * | | same way. Only `cleared` nulls it |
339 * | `knowledgeCutoff` | null |
340 * | `openWeights` | null, and `weightsUrl` with it: the pair is one |
341 * | | fact, marked absent as `openWeights` |
342 * | `providerMetadata` | null |
343 *
344 * `cleared` nulls each of them and `unavailable` keeps the stored value and
345 * source, as for any fact. `capabilities` is the whole stored map: a bare
346 * omission, `cleared` or `unavailable` covers its `false` entries
347 * (`unsupportedCapabilities`) with its `true` ones. An `exactCapabilities`
348 * row's `false` entries are derived from its list every poll.
349 */
350export type FactAbsence = 'cleared' | 'unavailable'
351​
352/** Normalised model entry (maps onto the `models` table shape). */
353export interface ModelInfo {
354 rawId: string
355 displayName?: string | null
356 activity?: Activity | null
357 contextWindow?: number | null
358 maxOutput?: number | null
359 modalities?: unknown
360 pricing?: unknown
361 /**
362 * The flags the provider states the model supports, as a list. The
363 * poller joins it with `unsupportedCapabilities` into the stored map
364 * (`settleCapabilities`): listed here is `true`, listed there is `false`,
365 * in neither is left out. A stored map is also accepted, for a fact kept
366 * as `unavailable`. Anything else is refused.
367 */
368 capabilities?: unknown
369 /**
370 * True when `capabilities` is the model's whole flag list, read from its
371 * own branch of a request body other models share. The bound request
372 * schema then adds no flags: walked whole, it would give each model its
373 * siblings' fields.
374 */
375 exactCapabilities?: boolean
376 /**
377 * Flags the provider STATES this model does not support: the `false`
378 * entries of the stored map. Never a flag that is merely missing from a
379 * list that is not the model's whole one. Omit it on an
380 * `exactCapabilities` row: the poller derives it (`exactVocabulary`).
381 * Sources go in `factSources.capabilities`, keyed by flag. A flag also
382 * listed in `capabilities` is a bug: the poller refuses the row's flags.
383 */
384 unsupportedCapabilities?: Array<string> | null
385 /**
386 * The provider's own listing object, as published and not normalised
387 * (fal `category`, Ark `features`, ElevenLabs `languages`). Stored and
388 * served as `providerMetadata`. Nothing here is a capability flag until
389 * an adapter states it in `capabilities` / `unsupportedCapabilities`.
390 */
391 providerMetadata?: Record<string, unknown> | null
392 /** Thinking configuration; null when the model does not reason or docs are silent. */
393 reasoning?: ModelReasoning | null
394 /**
395 * Knowledge (training data) cutoff, `YYYY-MM` or `YYYY-MM-DD`: exactly as
396 * precise as the provider states it, never padded to a day. Null when the
397 * provider states none.
398 */
399 knowledgeCutoff?: string | null
400 /**
401 * True only when the provider itself states the weights can be openly
402 * downloaded, false only when it states they cannot. Never inferred from
403 * a model name, an id shape, or another provider's row. Null when unstated.
404 */
405 openWeights?: boolean | null
406 /** Where the provider says the weights are; stored only with `openWeights: true`. */
407 weightsUrl?: string | null
408 /**
409 * Provider-hosted tool type ids the model accepts in `tools`
410 * (`web_search_20250305`, `google_search`, …). Null when unknown.
411 */
412 serverTools?: Array<string> | null
413 /**
414 * Chat request wire map (issue #95). The poller fills this from
415 * `chatRequestMap`; listings do not invent it. Null when unverified.
416 * A listing sets it only from the model's own published request schema
417 * (Workers AI, Mistral's ChatCompletionRequest, Gemini's Discovery
418 * document); the poller then keeps that map.
419 */
420 requestMap?: ChatRequestMap | null
421 /**
422 * Per-field provenance for the facts this listing already filled.
423 * The poller defaults untagged listing fields to `derivation: listing`.
424 */
425 factSources?: ModelFactSources
426 /** Facts with no value this poll for a known reason; wins over a value. */
427 absent?: Partial<Record<ModelFact, FactAbsence>>
428 /**
429 * Generation route (public endpoint id) when it depends on listing data
430 * the read path cannot see — Gemini's `supportedGenerationMethods`.
431 * Omit to let the provider's `generationEndpointId` bind by activity.
432 */
433 schemaEndpointId?: string | null
434 /**
435 * Caller ids that resolve to this row (Anthropic `claude-opus-4-5` →
436 * the dated snapshot). Empty when the provider documents none.
437 */
438 aliases?: Array<string> | null
439 deprecated?: boolean
440 /**
441 * Upstream release/creation time (epoch seconds) when the provider reports
442 * one. Stored as `models.releasedAt`, and used to backdate
443 * `models.firstSeenAt` (issue #1). Null/absent when the provider has no
444 * date for the model.
445 */
446 releasedAt?: number | null
448​
449/** Provenance for one fetched spec document. */
450export interface SpecSource {
451 /** URL the document was fetched from. */
452 url: string
453 /**
454 * SHA-256 hex of the document as fetched — raw bytes when the upstream
455 * serves a file (reproducible with `curl <url> | shasum -a 256`),
456 * stable-stringified JSON for documents embedded in API responses (FAL),
457 * decompressed JSON for Stainless-bundled gzip specs (Anthropic, Groq).
458 */
459 hash: string
461​
462/**
463 * Already-extracted generation endpoint that is not an OpenAPI path
464 * (FAL WMA AsyncAPI). Merged into classifyAndBundle; not assembled into
465 * GET /v1/openapi/{provider}.
466 */
467export interface BundledEndpoint {
468 /** Logical schema identity; path remains the actual provider HTTP path. */
469 publicId?: string
470 path: string
471 activity: Activity
472 description: string | null
473 source: SpecSource
474 derivation: Derivation
475 verifiedAt?: string | null
476 input?: Record<string, unknown>
477 output?: Record<string, unknown>
478 /** Catalog `capabilities.asyncapi` and skip HTTP OpenAPI assembly. */
479 asyncapi?: boolean
481​
482export interface SpecFetchResult {
483 specs: Array<OpenApiDocument>
484 /** Explicitly rejected former sources, withdrawn only after a successful native fetch. */
485 withdrawnSchemaSources?: Array<string>
486 /** Per-document provenance, index-aligned with `specs`. */
487 sources: Array<SpecSource>
488 /**
489 * Output-schema derivation strategy (PR #622):
490 * - 'post-200': POST .responses["200"].content (most providers)
491 * - 'sibling-get': sibling GET `${path}/requests/{request_id}` (FAL —
492 * the POST returns a queue ack)
493 */
494 outputStrategy: 'post-200' | 'sibling-get'
495 /** Upstream revision identifier when one exists (e.g. the SHA-256 of a Stainless-bundled spec). */
496 specRevision?: string
497 /**
498 * Non-fatal problems encountered while fetching/derivating the documents —
499 * e.g. BytePlus falling back to its embedded Ark document when the Go SDK
500 * it generates from is unreachable. Surfaced on the sync outcome.
501 */
502 warnings?: Array<string>
503 /** Set when the provider was skipped (e.g. missing secret); specs will be empty. */
504 skipped?: string
505 /**
506 * Extra bundled endpoints (AsyncAPI) appended after OpenAPI classify.
507 */
508 bundledEndpoints?: Array<BundledEndpoint>
509 /**
510 * Listed model rawIds whose generation surface is AsyncAPI. Present
511 * (including `[]`) when the fetch evaluated that; omitted when skipped.
512 * Sync writes `capabilities.asyncapi` on matching catalog rows.
513 */
514 asyncApiRawIds?: Array<string>
516​
517/** One docs source `listModels` could not read this poll. */
518export interface DocsFailure {
519 /** The document's URL. */
520 source: string
521 error: string
522 /** How long the failed load took; a timeout shows as one. */
523 elapsedMs: number
525​
526/** What one poll's docs loads came to (`docsReport`). */
527export interface DocsFailures {
528 /** Documents whose load or parse threw. */
529 failed: number
530 /** Documents not attempted once the failure budget was spent. */
531 skipped: number
532 /** The first few failures; `failed` is the whole count. */
533 first: Array<DocsFailure>
535​
536export interface ListModelsResult {
537 models: Array<ModelInfo>
538 /**
539 * Docs sources that failed while the listing itself loaded (`tryDocs`).
540 * The poll goes on; rows mark the facts those sources supply
541 * `unavailable`. A failed listing still throws. An adapter that uses
542 * `tryDocs` always returns this, zeros included: that is what clears
543 * the provider's `docs-failing` record.
544 */
545 docsFailures?: DocsFailures
546 /** Set when the provider was skipped (e.g. missing secret); models will be empty. */
547 skipped?: string
549​
550/**
551 * How a provider's generation surface is addressed. `provider` — a handful
552 * of shared endpoints, model is a request field. `model` — one API per
553 * model (FAL); a combined OpenAPI document is not served.
554 */
555export type SpecGrain = 'provider' | 'model'
556​
557/** OpenAPI 3 security scheme subset we emit on assembled provider specs. */
558export type OpenApiSecurityScheme =
559 | {
560 type: 'http'
561 scheme: string
562 bearerFormat?: string
563 description?: string
564 }
565 | {
566 type: 'apiKey'
567 in: 'header' | 'query' | 'cookie'
568 name: string
569 description?: string
570 }
571​
572/**
573 * How to call this provider's data plane. Declared, not guessed from the
574 * upstream spec (those are often incomplete). Used to assemble
575 * `GET /v1/openapi/{provider}`.
576 */
577export interface ProviderConnect {
578 servers: Array<{ url: string; description?: string }>
579 securitySchemes: Record<string, OpenApiSecurityScheme>
580 security: Array<Record<string, Array<string>>>
581 /** Header name → const value (e.g. `anthropic-version`). */
582 requiredHeaders?: Record<string, string>
583 /**
584 * Include sibling `GET {path}/requests/{request_id}` carrying the output
585 * schema (FAL queue). The POST keeps the input schema only.
586 */
587 siblingGet?: boolean
589​
590export interface ProviderConfig {
591 /** Lowercase slug; matches `providers.id` and the seed data. */
592 id: string
593 displayName: string
594 /** Env var holding the API key; undefined for keyless providers. */
595 authEnvVar?: keyof ProviderSecrets
596 /**
597 * Seed metadata. Required on auto-registered adapters under
598 * `./adapters/`; optional on the original 8, which keep their rows in
599 * `seed-providers.ts`.
600 */
601 specSourceUrl?: string
602 modelsEndpoint?: string
603 /**
604 * Names other providers' model ids use for this provider (`google/…` →
605 * gemini). Stored in `provider_model_namespaces`; used only for sameAs.
606 */
607 modelNamespaces?: Array<string>
608 /**
609 * Upstream identity read from a raw id, using an id format this provider
610 * itself publishes; null when the id does not follow it. Never guess.
611 */
612 upstreamModelIdentity?: (rawId: string) => UpstreamModelIdentity | null
613 /**
614 * Derivation recorded for this provider's endpoints unless an operation
615 * carries its own {@link PROVENANCE_MARKER}. Providers that re-fetch a
616 * published spec every sync declare `upstream-spec`.
617 */
618 defaultDerivation: Derivation
619 /**
620 * How this provider's generation surface is addressed. Defaults to
621 * `provider` when omitted (adapters).
622 */
623 specGrain?: SpecGrain
624 /** How to call the provider; assembled into GET /v1/openapi/{id}. */
625 connect?: ProviderConnect
626 /**
627 * Per-activity override when one provider has multiple data planes
628 * (BytePlus Ark vs Seed Speech). Mixed selections drop overridden
629 * activities from the default document.
630 */
631 connectByActivity?: Partial<Record<Activity, ProviderConnect>>
632 /** Fetch + parse the provider's OpenAPI spec document(s). */
633 fetchSpec: (env: ProviderEnvironment) => Promise<SpecFetchResult>
634 /** List currently served models from the provider's cheap models endpoint. */
635 listModels: (
636 env: ProviderEnvironment,
637 kv?: KVNamespace,
638 ) => Promise<ListModelsResult>
639 /**
640 * Classify an endpoint to an activity group; `null` means platform/admin
641 * surface — dropped from schema generation.
642 */
643 classify: (path: string, op: OpenApiOperation) => Activity | null
644 /**
645 * Also classify GET operations. Off by default: many specs publish
646 * GETs on generation paths that are not the generation call. BytePlus
647 * video needs GET /contents/generations/tasks/{id}, which is where the
648 * video URL comes back.
649 */
650 classifyGets?: boolean
651 /**
652 * Drop a listed `schemaEndpointId` until its route has a synced input
653 * schema. For listings that name per-model routes the daily sync creates
654 * later (Replicate): a link to an unsynced route would 404.
655 */
656 bindSyncedRoutesOnly?: boolean
657 /** Bind a verified stored route even when its native source publishes no schemas. */
658 bindStoredRoutesWithoutSchemas?: boolean
659 /**
660 * Canonical generation route (public endpoint id) for a listed model.
661 * Grain=provider catalogs use this so a client can go model id → input
662 * schema without hardcoding `v1/images/generations`. Omitted providers
663 * have no model→route binding unless they are model-grained (the raw
664 * id *is* the endpoint id).
665 */
666 generationEndpointId?: (model: {
667 rawId: string
668 activity: Activity
669 capabilities?: unknown
670 }) => string | null
671 /**
672 * Capability flags the shared request schema carries but the provider
673 * says not every model supports (Perplexity: reasoning, tools). The
674 * schema walk leaves them off; a listing that states one still sets it.
675 */
676 perModelSchemaFlags?: Array<string>
678​
679/** Fetch a JSON or YAML OpenAPI document and hash the raw bytes. */
680export async function fetchOpenApi(url: string): Promise<{
681 spec: OpenApiDocument
682 text: string
683 hash: string
684}> {
685 const { parse } = await import('yaml')
686 const text = await fetchText(url)
687 const hash = await sha256Text(text)
688 const trimmed = text.trimStart()
689 const spec = (
690 trimmed.startsWith('{') || trimmed.startsWith('[')
691 ? JSON.parse(text)
692 : parse(text)
693 ) as OpenApiDocument
694 return { spec, text, hash }
696​
697export async function fetchJson(
698 url: string,
699 init?: RequestInit,
700): Promise<unknown> {
701 const response = await fetch(url, init)
702 if (!response.ok) {
703 throw new Error(
704 `fetch failed: ${url} → ${String(response.status)} ${response.statusText}`,
705 )
706 }
707 return response.json()
709​
710/** SHA-256 hex of raw fetched text (the `SpecSource.hash` for file specs). */
711export async function sha256Text(text: string): Promise<string> {
712 const digest = await crypto.subtle.digest(
713 'SHA-256',
714 new TextEncoder().encode(text),
715 )
716 return [...new Uint8Array(digest)]
717 .map((b) => b.toString(16).padStart(2, '0'))
718 .join('')
720​
721export async function fetchText(
722 url: string,
723 init?: RequestInit,
724): Promise<string> {
725 const response = await fetch(url, init)
726 if (!response.ok) {
727 throw new Error(
728 `fetch failed: ${url} → ${String(response.status)} ${response.statusText}`,
729 )
730 }
731 return response.text()
733​
734/**
735 * Read `openapi_spec_url` out of a Stainless SDK `.stats.yml`. The file is
736 * plain key-value YAML; we only need one field, so skip a full parse.
737 */
738export function stainlessSpecUrlFromStats(
739 text: string,
740 providerId: string,
741): string {
742 const url = text.match(/^openapi_spec_url:\s*(.+)$/m)?.[1]?.trim()
743 if (!url) {
744 throw new Error(`${providerId} .stats.yml: couldn't find openapi_spec_url`)
745 }
746 return url
748​
749/**
750 * Parse a gzipped OpenAPI JSON document bundled in a Stainless SDK repo
751 * (the mock-server spec — the real spec, now that `.stats.yml` no longer
752 * carries `openapi_spec_url`). Throws on non-gzip bytes, bad JSON, or a
753 * document without `openapi` + `paths`, so the provider stays degraded
754 * rather than serving a stale fallback. The decompressed JSON's hash is
755 * the specRevision.
756 */
757export async function parseGzippedOpenApi(
758 bytes: Uint8Array<ArrayBuffer>,
759 providerId: string,
760 url: string,
761): Promise<SpecFetchResult> {
762 let text: string
763 let spec: OpenApiDocument | null
764 try {
765 text = await new Response(
766 new Blob([bytes]).stream().pipeThrough(new DecompressionStream('gzip')),
767 ).text()
768 spec = JSON.parse(text) as OpenApiDocument | null
769 } catch (err) {
770 throw new Error(
771 `${providerId}: bundled spec at ${url} is not gzipped JSON (${String(err)})`,
772 )
773 }
774 if (typeof spec?.openapi !== 'string' || !spec.paths) {
775 throw new Error(`${providerId}: bundled spec at ${url} is not OpenAPI`)
776 }
777 const hash = await sha256Text(text)
778 return {
779 specs: [spec],
780 sources: [{ url, hash }],
781 outputStrategy: 'post-200',
782 specRevision: hash,
783 }
785​
786/** Standard skip result for providers whose secret is absent. */
787export function skippedResult(
788 providerId: string,
789 envVar: string,
790): { skipped: string } {
791 return { skipped: `${providerId}: ${envVar} not set — skipped` }