@sagmans/dsh-provider-extra 0.4.0 → 0.6.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.
package/README.md CHANGED
@@ -7,11 +7,28 @@ Extra provider routes for [DeepSeek Harness](https://github.com/deepseek-ai/deep
7
7
 
8
8
  Published on npm as [`@sagmans/dsh-provider-extra`](https://www.npmjs.com/package/@sagmans/dsh-provider-extra); every release carries a provenance attestation built by the tag workflow, and no npm token is stored. The code is [MIT licensed](LICENSE).
9
9
 
10
+ ## Opt-in canonical catalog
11
+
12
+ Provider-extra remains optional. With no `catalog` Config, existing additive behavior stays unchanged.
13
+ An opted-in profile can select ordered routes from any backend the installed pi-ai catalog provides, or from an endpoint you declare with its own protocol and base URL.
14
+ A route lists its models explicitly, or curates the installed source catalog with `include`/`exclude` patterns that keep every installed fact.
15
+ One validated snapshot owns listings, dispatch, and `agentDefaultModel`; managed settings overlays do not apply.
16
+
17
+ Read [catalog configuration and activation](docs/catalog.md) before adoption.
18
+ The [shape example](docs/catalog-v1.example.json) validates with synthetic model identifiers and illustrative metadata, not a real provider/model selection.
19
+ Keep your model selection in your own profile Config, not in the plugin package.
20
+ For source development, use the [clone-only setup command](docs/catalog.md#clone-only-development-setup) with an explicit private catalog file.
21
+ Only the adopted profile disables competing provider/default rows. TUI and ordinary profiles require no changes.
22
+
23
+ Canonical default saves use the host profile `configEditor` when available.
24
+ Unsupported hosts reject with `CONFIG_PERSISTENCE_UNAVAILABLE`, rather than writing legacy settings.
25
+ Catalog presence does not prove endpoint availability, pricing, or metadata accuracy.
26
+
10
27
  ## Requirements
11
28
 
12
29
  - Node.js 24 LTS (verified with 24.20.0).
13
30
  - pnpm 11.21.0 for this repository.
14
- - A DeepSeek Harness install on the supported line: `>=0.1.5-rc.1 <0.1.6` (verified against `0.1.5-rc.2`). The plugin declares that range as a peer dependency, so a profile resolves the harness copy it already has rather than a second framework instance.
31
+ - A DeepSeek Harness install on the supported line: `>=0.1.5-rc.1 <0.3.0`, verified against `0.1.5-rc.2`, `0.1.5-rc.3`, `0.1.7-rc.2`, and `0.2.0-rc.2` (see [RELEASE.md](RELEASE.md#harness-matrix)). The plugin's harness peers stay open, so a profile resolves the host copy it already has rather than a second framework instance; the range itself is declared in `dsh.compatibility.dsh`.
15
32
 
16
33
  ## Install
17
34
 
@@ -25,7 +42,7 @@ dsh plugin --profile tui add @sagmans/dsh-provider-extra
25
42
  A release of the harness CLI is installable without a launcher already on `PATH`:
26
43
 
27
44
  ```sh
28
- pnpm dlx @deepseek-ai/dsh@0.1.5-rc.2 plugin --profile web add @sagmans/dsh-provider-extra
45
+ pnpm dlx @deepseek-ai/dsh@0.2.0-rc.2 plugin --profile web add @sagmans/dsh-provider-extra
29
46
  ```
30
47
 
31
48
  The package declares `dsh.bundle.patch`. The CLI adds it to the profile's bundle list, and its patch loads the compiled plugin automatically. A bare `pnpm link` is not the registration procedure.
@@ -66,6 +83,11 @@ To customize them, add an ID-targeted override to `$DSH_HOME/profiles/web/cordis
66
83
  apiKeyEnv: OPENCODE_GO_API_KEY
67
84
  routeId: opencode-go-session
68
85
  displayName: OpenCode Go (session)
86
+ # extraModels: [...] # models served beside the installed catalog
87
+ # models: [...] # exact model IDs to serve, in this order
88
+ # codexExtraModels: [...] # the same two knobs for the Codex route
89
+ # codexModels: [...]
90
+ # codexTransport: sse # pin the Codex transport; unset keeps pi-ai's choice
69
91
  # codexEnabled: false
70
92
  # loginCommandEnabled: false
71
93
  # loginCommandName: dsh-provider-extra-login
@@ -93,44 +115,87 @@ Store the API key through the harness credential service, using the reference na
93
115
 
94
116
  The plugin reuses `PiAiAdapter` and pi-ai's `opencode-go` catalog. It injects the routing header on both `prepareCall()` and direct stream dispatch. The request's session ID takes precedence over `fallbackSessionId` and static headers. Without a request ID or configured fallback, the plugin sends no session header.
95
117
 
96
- The pinned catalog is extended with `deepseek-flash` (DeepSeek V4.1 Flash), cloned from `deepseek-v4-flash`. Add other models in `$DSH_HOME/settings.yaml` without rebuilding or restarting:
118
+ The pinned catalog is extended with `deepseek-flash` (DeepSeek V4.1 Flash), cloned from `deepseek-v4-flash`. Add other models to the profile override without rebuilding or restarting:
97
119
 
98
120
  ```yaml
99
- dsh-provider-extra:
100
- extraModels:
101
- - id: deepseek-flash
102
- name: DeepSeek V4.1 Flash
103
- template: deepseek-v4-flash
121
+ - id: dsh-provider-extra
122
+ config:
123
+ extraModels:
124
+ - id: example-go-model
125
+ name: Example Go model
126
+ template: example-go-template
127
+ models:
128
+ - example-go-model
129
+ - example-go-other-model
104
130
  ```
105
131
 
106
- Each entry clones wire behavior from its template. Later entries win by ID. A catalog-owned ID is not replaced. An unknown template becomes a model diagnostic without disabling the route.
132
+ These identifiers are placeholders. Replace them with models your provider serves and templates from the installed catalog.
133
+
134
+ Each entry clones wire behavior from its template. Later entries win by ID. A catalog-owned ID is not replaced. An unknown template becomes a model diagnostic without disabling the route. The entry owns definitions for a declared exact selection.
135
+
136
+ When models or codexModels declares an exact selection, that route resolves its models against the entry's extra-model declarations. An unknown selected ID rejects the entry before the route mounts. Later settings edits cannot replace or remove those selected model definitions.
137
+
138
+ `models` serves and advertises exactly its listed IDs, in order. Leave it out to serve all resolved models.
139
+ In additive mode, an empty declaration also means no selection; managed catalog arrays never have this expansion behavior.
107
140
 
108
141
  ## Codex models
109
142
 
110
143
  The Codex route serves pi-ai's installed `openai-codex` catalog for the signed-in subscription. Extend it the same way when the subscription serves an ID the installed catalog predates:
111
144
 
112
145
  ```yaml
113
- dsh-provider-extra:
114
- codexExtraModels:
115
- - id: gpt-6-luna
116
- name: GPT-6 Luna
117
- template: gpt-5.6-luna
146
+ - id: dsh-provider-extra
147
+ config:
148
+ codexExtraModels:
149
+ - id: example-codex-model
150
+ name: Example Codex model
151
+ template: example-codex-template
152
+ codexModels:
153
+ - example-codex-model
154
+ - example-codex-other-model
118
155
  ```
119
156
 
120
- Unlike the Go route, these entries must name their `template`: Codex ships no default sibling, so a declaration that names none is reported as a model diagnostic instead of cloned from another vendor's catalog. Later entries win by ID, a catalog-owned ID is not replaced, and an unknown template becomes a diagnostic without disabling the route. Both settings sections are read per request, so a committed change reaches the next turn with no restart.
157
+ These identifiers are placeholders, not model recommendations.
158
+
159
+ Unlike the Go route, these entries must name their `template`: Codex ships no default sibling, so a declaration that names none is reported as a model diagnostic instead of cloned from another vendor's catalog. Later entries win by ID, a catalog-owned ID is not replaced, and an unknown template becomes a diagnostic without disabling the route.
160
+
161
+ Routes without models or codexModels continue to read extraModels or codexExtraModels from the settings section on each operation. Settings additions, metadata changes, and removals reach those unselected routes without a restart. A declared selection keeps its entry-owned model definitions instead.
162
+
163
+ `codexTransport` pins the transport pi-ai uses for this route: `sse`, `websocket`, `websocket-cached`, or `auto`. Leave it out and pi-ai chooses, which on a network that never lets the subscription's websocket continue past the first answer leaves the reply printed and the process waiting; pin `sse` there.
121
164
 
122
165
  ## Provider sign-in
123
166
 
124
- Sign in from the profile you are already using: the plugin registers a command in the harness command palette, and it reaches every provider the installed pi-ai catalog ships a login for — the two routes here, and core's own.
167
+ Sign in from the profile you are already using. The plugin registers a command in the harness command palette.
168
+ In additive mode, it offers providers with an installed interactive login.
169
+ In managed mode, it offers only the routes and authentication methods selected by `catalog`.
125
170
 
126
171
  ```text
127
- /dsh-provider-extra-login # pick a provider, then run its sign-in
128
- /dsh-provider-extra-login openai-codex # skip the picker: that provider's subscription login
129
- /dsh-provider-extra-login anthropic key # that provider's API-key entry
130
- /dsh-provider-extra-login status # how each provider authenticates today
172
+ /dsh-provider-extra-login [<id> [oauth|key] | status]
131
173
  ```
132
174
 
133
- The command runs inside the server, so the credential lands in the store the routes read, and it serves the next request with no restart. A provider the profile never declared is declared in the `llm-pi-ai` settings as a bare catalog route, because a stored credential no route reads fails the first turn with `no adapter registered`; the write names one provider, so routes and overrides already configured are untouched, and the success message says when it happened. Subscription flows show the page or device code as a dialog question and then finish on their own; a provider that asks for an API key collects it in the same dialog and spends it on one minimal request before anything is written, so a key the provider refuses is reported and never stored, and the value stays out of the model's context either way. The API-key question's id ends in `:secret`, which is how a surface that understands the marker knows to keep the pasted value out of sight; a surface that does not is left with the wording. The command reports success only after reading the stored record back, so a flow that resolves without persisting is reported instead of passed off as a sign-in. Runs only in profiles that compose both the command registry and a session UI; set `loginCommandEnabled: false` to omit it.
175
+ Omit the ID to pick a provider. Set `loginCommandName` to rename the command.
176
+ Set `loginCommandEnabled: false` to disable it in either mode.
177
+ The command needs a command registry and a session UI to ask sign-in questions.
178
+
179
+ Managed IDs are exactly the `Config.catalog` route IDs, shown with their configured names.
180
+ Additive IDs remain installed source provider IDs, including `opencode-go` when its configured route is aliased.
181
+ With no method word, the command uses the only available method, or OAuth first when both are available.
182
+ Use `oauth` or `key` to select a method explicitly.
183
+ A managed `apiKeyRef` route offers only key entry, including XAI.
184
+
185
+ Managed sign-in writes the configured credential reference or source record.
186
+ It never declares routes or changes Config, defaults, settings, or membership.
187
+ Additive sign-in can declare an undeclared provider in `llm-pi-ai` settings.
188
+ Credentials serve the next request without a restart.
189
+
190
+ Missing or read-only credential stores refuse sign-in before any secret or OAuth prompt.
191
+ API-key entry uses a secret-marked question and verifies the pending key before storage.
192
+ A zero-model key route fails with `cannot verify this API key: no models are available for provider <route-id>`.
193
+ That failure stores nothing. Success requires a readback from the effective credential store.
194
+
195
+ Managed status prints `API key <ref> (not set|set from <source>)` for reference-backed routes.
196
+ It never substitutes a provider record for an unresolved reference.
197
+ Source-record mode reports `not signed in` or `signed in (api_key|oauth)` from `llm-pi-ai:<credentialProvider>`.
198
+ Status and OAuth persistence do not check endpoint availability or account entitlement.
134
199
 
135
200
  Without a command palette — a headless composition, or a sign-in for a server you are not attached to — use the shipped bin instead. It signs into the Codex route only, and needs the same `DSH_HOME` as the harness plus a profile that has booted at least once, because that is what installs the tree the bin resolves the harness packages through:
136
201
 
@@ -154,11 +219,13 @@ pnpm run check
154
219
  pnpm audit --audit-level high
155
220
  ```
156
221
 
157
- `check` runs type checking, 30 source tests, the build, three integration tests, the 22 release guard tests, and the package smoke. The plain-Node smoke test mounts both compiled routes in the real Cordis/LLM runtime. Two CLI tests exercise add, repeated add, profile overrides, and remove in disposable web/TUI profiles; they drive the registry CLI this repository develops against (`@deepseek-ai/dsh@0.1.5-rc.2`), so no harness checkout is needed.
222
+ `check` runs type checking, source tests, the harness matrix guard, the build, integration tests, release guards, and the package smoke. `node tools/harness-matrix.mjs` reads the declared range, the verified releases, and what every harness package declares, and fails when the three disagree; `pnpm run matrix` is the same check.
223
+ Package checks reject non-synthetic catalog/model declarations in shipped configuration and documentation.
224
+ Development setup tests use synthetic credentials-free profiles; the setup helper stays outside the npm package. The plain-Node smoke test mounts both compiled routes in the real Cordis/LLM runtime. Two CLI tests exercise add, repeated add, profile overrides, and remove in disposable web/TUI profiles; they drive the registry CLI this repository develops against (`@deepseek-ai/dsh@0.2.0-rc.2`), so no harness checkout is needed.
158
225
 
159
226
  Tests use a local mock gateway or seeded grants. They require no API key, OAuth login, or paid provider requests.
160
227
 
161
- CI installs from the registry with read-only permissions and no account credentials, verifies dependency signatures and attestations, and runs the same checks. New dependency releases must be at least seven days old, and `pnpm-workspace.yaml` limits which lifecycle scripts may run.
228
+ CI installs from the registry with read-only permissions and no account credentials, verifies dependency signatures and attestations, and runs the same checks. New dependency releases must be at least seven days old, and `pnpm-workspace.yaml` limits which lifecycle scripts may run; the harness vendor's own scope is excluded from that window, because a verified release is published inside it and the mount resolves that same vendor's packages (see [RELEASE.md](RELEASE.md#harness-matrix)).
162
229
 
163
230
  The package smoke test does not prove a real account can authenticate or a remote provider is available. To verify those, install a candidate into a profile built on the supported harness line and send one message through each configured route.
164
231
 
@@ -0,0 +1,39 @@
1
+ import { LlmError } from '@deepseek-ai/dsh-llm';
2
+ import { compileCatalog } from "./catalog.js";
3
+ const EDITOR_SERVICE = 'configEditor';
4
+ const PERSISTENCE_UNAVAILABLE = 'CONFIG_PERSISTENCE_UNAVAILABLE';
5
+ /** A detached selection prevents callers from mutating the catalog's default. */
6
+ export function catalogDefault(owner, snapshot, requireOwnership) {
7
+ return {
8
+ currentSelection() {
9
+ requireOwnership?.();
10
+ if (snapshot.selection === null) {
11
+ throw new LlmError('dsh-provider-extra: the catalog selects no default model', 'NO_DEFAULT_MODEL');
12
+ }
13
+ return { ...snapshot.selection };
14
+ },
15
+ async saveSelection(next) {
16
+ requireOwnership?.();
17
+ const selection = snapshot.resolveSelection(next);
18
+ // EntryTree.write may be a no-op or target a generated document; only the
19
+ // profile editor guarantees validation, locking, rollback and reconciliation.
20
+ const entry = owner.fiber.entry;
21
+ const editor = owner.get(EDITOR_SERVICE);
22
+ if (entry === undefined || typeof editor?.edit !== 'function') {
23
+ throw new LlmError('dsh-provider-extra: this host cannot persist catalog.default; edit the owning profile Config', PERSISTENCE_UNAVAILABLE);
24
+ }
25
+ await editor.edit(entry, (current) => {
26
+ requireOwnership?.();
27
+ // Revalidation inside the editor's lock prevents a stale picker from
28
+ // restoring membership removed by another profile edit.
29
+ const latest = compileCatalog(current.catalog);
30
+ if (latest === undefined) {
31
+ throw new LlmError('dsh-provider-extra: the owning Config no longer contains a catalog', 'CATALOG_OWNER_CHANGED');
32
+ }
33
+ const updated = { ...latest.config, default: latest.resolveSelection(selection) };
34
+ compileCatalog(updated);
35
+ return { ...current, catalog: updated };
36
+ });
37
+ },
38
+ };
39
+ }
@@ -0,0 +1,15 @@
1
+ import * as anthropicMessages from '@earendil-works/pi-ai/api/anthropic-messages';
2
+ import * as azureOpenAIResponses from '@earendil-works/pi-ai/api/azure-openai-responses';
3
+ import * as googleGenerativeAI from '@earendil-works/pi-ai/api/google-generative-ai';
4
+ import * as mistralConversations from '@earendil-works/pi-ai/api/mistral-conversations';
5
+ import * as openaiCompletions from '@earendil-works/pi-ai/api/openai-completions';
6
+ import * as openaiResponses from '@earendil-works/pi-ai/api/openai-responses';
7
+ /** Protocol id (also the model's `api`) to the streams that implement it. */
8
+ export const PROTOCOL_STREAMS = Object.freeze({
9
+ 'anthropic-messages': anthropicMessages,
10
+ 'azure-openai-responses': azureOpenAIResponses,
11
+ 'google-generative-ai': googleGenerativeAI,
12
+ 'mistral-conversations': mistralConversations,
13
+ 'openai-completions': openaiCompletions,
14
+ 'openai-responses': openaiResponses,
15
+ });
@@ -0,0 +1,374 @@
1
+ /** A route borrows an installed backend's protocol or declares its own; either way it owns its model facts. */
2
+ import { credentialRef } from '@deepseek-ai/dsh-credentials';
3
+ import { resolveRetryPolicy } from '@deepseek-ai/dsh-llm';
4
+ import { createProvider } from '@earendil-works/pi-ai';
5
+ import { builtinProviders } from '@earendil-works/pi-ai/providers/all';
6
+ import { PROTOCOL_STREAMS } from "./catalog-protocols.js";
7
+ const ERROR_PREFIX = 'dsh-provider-extra: catalog ';
8
+ const ROUTE_FIELDS = ['id', 'name', 'source', 'api', 'auth', 'models', 'filter', 'baseURL', 'headers', 'transport', 'fallbackSessionId'];
9
+ const MODEL_FIELDS = ['id', 'name', 'aliases', 'template', 'metadata', 'defaultMaxTokens'];
10
+ const METADATA_FIELDS = ['api', 'reasoning', 'input', 'cost', 'contextWindow', 'maxTokens', 'thinkingLevelMap', 'headers', 'compat'];
11
+ const REQUIRED_METADATA = ['api', 'reasoning', 'input', 'cost', 'contextWindow', 'maxTokens'];
12
+ const COST_FIELDS = ['input', 'output', 'cacheRead', 'cacheWrite'];
13
+ const THINKING_LEVELS = ['off', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'];
14
+ const TRANSPORTS = ['sse', 'websocket', 'websocket-cached', 'auto'];
15
+ const GO_SOURCE = 'opencode-go';
16
+ const CODEX_SOURCE = 'openai-codex';
17
+ const SESSION_HEADER = 'x-opencode-session';
18
+ const STREAM_IDLE_TIMEOUT_MS = 300_000;
19
+ const MAX_REQUEST_IMAGE_BYTES = 20 * 1024 * 1024;
20
+ const REQUEST_IMAGE_PIXEL_BUDGET = 2048 * 2048;
21
+ const REQUEST_IMAGE_MAX_BYTES = 1024 * 1024;
22
+ const HTTP_PROTOCOLS = ['http:', 'https:'];
23
+ const COMPLETIONS_API = 'openai-completions';
24
+ const RESPONSES_APIS = ['openai-responses', 'azure-openai-responses', 'openai-codex-responses'];
25
+ const ANTHROPIC_API = 'anthropic-messages';
26
+ const COMPLETIONS_FLAGS = ['supportsStore', 'supportsDeveloperRole', 'supportsReasoningEffort', 'supportsUsageInStreaming', 'supportsFinishReason', 'requiresToolResultName', 'requiresAssistantAfterToolResult', 'requiresThinkingAsText', 'requiresReasoningContentOnAssistantMessages', 'zaiToolStream', 'supportsThinkingTokenBudget', 'supportsOpenAIGrammarTools', 'supportsStrictMode', 'sendSessionAffinityHeaders', 'supportsLongCacheRetention'];
27
+ const RESPONSES_FLAGS = ['supportsDeveloperRole', 'supportsLongCacheRetention', 'supportsStrictMode', 'supportsOpenAIGrammarTools', 'supportsAdditionalTools', 'supportsToolSearch', 'supportsExplicitPromptCacheMode', 'supportsMaxOutputTokens'];
28
+ const ANTHROPIC_FLAGS = ['supportsEagerToolInputStreaming', 'supportsLongCacheRetention', 'sendSessionAffinityHeaders', 'supportsCacheControlOnTools', 'supportsTemperature', 'forceAdaptiveThinking', 'allowEmptySignature', 'supportsStrictTools', 'supportsMidConvoEffort', 'supportsToolReferences'];
29
+ const COMPAT_ENUMS = {
30
+ maxTokensField: ['max_completion_tokens', 'max_tokens'],
31
+ thinkingFormat: ['openai', 'openrouter', 'deepseek', 'together', 'baseten', 'zai', 'qwen', 'chat-template', 'qwen-chat-template', 'string-thinking', 'ant-ling'],
32
+ thinkingTokenBudgetField: ['thinking_token_budget', 'thinking_budget', 'thinking_budget_tokens'],
33
+ cacheControlFormat: ['anthropic'], deferredToolsMode: ['kimi'],
34
+ sessionAffinityFormat: ['openai', 'openai-nosession', 'openrouter'],
35
+ };
36
+ /** @internal Consistent paths make invalid declarations repairable before publication. */
37
+ export function catalogError(path, reason) {
38
+ throw new Error(ERROR_PREFIX + path + ': ' + reason);
39
+ }
40
+ /** @internal Unknown fields must fail rather than look applied. */
41
+ export function catalogRecord(value, fields, path) {
42
+ if (value === null || typeof value !== 'object' || Array.isArray(value)
43
+ || ![Object.prototype, null].includes(Object.getPrototypeOf(value)))
44
+ catalogError(path, 'expected an object');
45
+ for (const key of Reflect.ownKeys(value)) {
46
+ if (typeof key !== 'string' || (fields && !fields.includes(key)))
47
+ catalogError(path, 'unknown field ' + String(key));
48
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
49
+ if (!('value' in descriptor))
50
+ catalogError(path, 'accessors are not configuration values');
51
+ }
52
+ return value;
53
+ }
54
+ /** @internal IDs and labels cannot hide accidental whitespace or control characters. */
55
+ export function catalogString(value, path) {
56
+ if (typeof value !== 'string' || !value.trim() || value !== value.trim() || /[\u0000-\u001f\u007f]/u.test(value)) {
57
+ catalogError(path, 'expected a nonempty string without surrounding whitespace or control characters');
58
+ }
59
+ }
60
+ /** @internal Deep freezing protects old snapshots from callers retaining nested references. */
61
+ export function freezeCatalogValue(value) {
62
+ if (value !== null && typeof value === 'object' && !Object.isFrozen(value)) {
63
+ for (const member of Object.values(value))
64
+ freezeCatalogValue(member);
65
+ Object.freeze(value);
66
+ }
67
+ return value;
68
+ }
69
+ /** @internal A frozen Map still permits set(); a facade keeps its mutable storage private. */
70
+ export function catalogMap(entries) {
71
+ const map = new Map(entries);
72
+ const view = Object.freeze({
73
+ size: map.size,
74
+ get: (key) => map.get(key), has: (key) => map.has(key),
75
+ keys: () => map.keys(), values: () => map.values(), entries: () => map.entries(),
76
+ [Symbol.iterator]: () => map[Symbol.iterator](),
77
+ forEach: (callback, thisArg) => {
78
+ map.forEach((value, key) => callback.call(thisArg, value, key, view));
79
+ },
80
+ });
81
+ return view;
82
+ }
83
+ function number(value, path, positive = false) {
84
+ if (typeof value !== 'number' || !Number.isFinite(value) || value < 0 || (positive && (!Number.isSafeInteger(value) || value === 0))) {
85
+ catalogError(path, positive ? 'expected a positive safe integer' : 'expected a finite nonnegative number');
86
+ }
87
+ }
88
+ function strings(value, path) {
89
+ if (!Array.isArray(value))
90
+ catalogError(path, 'expected an array');
91
+ for (const item of value)
92
+ catalogString(item, path);
93
+ if (new Set(value).size !== value.length)
94
+ catalogError(path, 'duplicate entry');
95
+ return value;
96
+ }
97
+ function headers(value, path) {
98
+ for (const [key, member] of Object.entries(catalogRecord(value, undefined, path))) {
99
+ if (typeof member !== 'string')
100
+ catalogError(path, 'header values must be strings');
101
+ try {
102
+ new Headers({ [key]: member });
103
+ }
104
+ catch {
105
+ catalogError(path, 'invalid HTTP header');
106
+ }
107
+ }
108
+ }
109
+ function cost(value, path, tier = false) {
110
+ const fields = [...COST_FIELDS, ...(tier ? ['inputTokensAbove'] : ['tiers'])];
111
+ const data = catalogRecord(value, fields, path);
112
+ for (const key of COST_FIELDS)
113
+ number(data[key], path + '.' + key);
114
+ if (tier)
115
+ number(data.inputTokensAbove, path + '.inputTokensAbove');
116
+ else if ('tiers' in data) {
117
+ if (!Array.isArray(data.tiers))
118
+ catalogError(path, 'tiers must be an array');
119
+ for (const entry of data.tiers)
120
+ cost(entry, path + '.tiers', true);
121
+ }
122
+ }
123
+ /** Only metadata the managed protocols can honor belongs in configuration. */
124
+ function compat(value, api, path) {
125
+ const flags = api === COMPLETIONS_API ? COMPLETIONS_FLAGS : RESPONSES_APIS.includes(api) ? RESPONSES_FLAGS
126
+ : api === ANTHROPIC_API ? ANTHROPIC_FLAGS : [];
127
+ const enums = api === COMPLETIONS_API ? Object.keys(COMPAT_ENUMS) : RESPONSES_APIS.includes(api) ? ['sessionAffinityFormat'] : [];
128
+ const data = catalogRecord(value, [...flags, ...enums], path);
129
+ for (const [key, member] of Object.entries(data)) {
130
+ if (flags.includes(key)) {
131
+ if (typeof member !== 'boolean')
132
+ catalogError(path, key + ' must be boolean');
133
+ }
134
+ else if (!COMPAT_ENUMS[key].includes(member))
135
+ catalogError(path, 'invalid ' + key);
136
+ }
137
+ }
138
+ function metadata(value, api, path) {
139
+ const data = catalogRecord(value, METADATA_FIELDS, path);
140
+ for (const [key, member] of Object.entries(data)) {
141
+ if (key === 'api')
142
+ catalogString(member, path + '.api');
143
+ else if (key === 'reasoning') {
144
+ if (typeof member !== 'boolean')
145
+ catalogError(path, 'reasoning must be boolean');
146
+ }
147
+ else if (key === 'input') {
148
+ const modes = strings(member, path + '.input');
149
+ if (!modes.length || modes.some(mode => !['text', 'image'].includes(mode)))
150
+ catalogError(path, 'invalid input modalities');
151
+ }
152
+ else if (key === 'contextWindow' || key === 'maxTokens')
153
+ number(member, path + '.' + key, true);
154
+ else if (key === 'cost')
155
+ cost(member, path + '.cost');
156
+ else if (key === 'headers')
157
+ headers(member, path + '.headers');
158
+ else if (key === 'thinkingLevelMap') {
159
+ for (const level of Object.values(catalogRecord(member, THINKING_LEVELS, path))) {
160
+ if (level !== null)
161
+ catalogString(level, path);
162
+ }
163
+ }
164
+ else if (key === 'compat')
165
+ compat(member, data.api ?? api ?? '', path + '.compat');
166
+ }
167
+ }
168
+ /** Provider auth contains functions, so structuredClone cannot detach its declaration. */
169
+ function detachedAuth(value) {
170
+ if (Array.isArray(value))
171
+ return value.map(detachedAuth);
172
+ if (value !== null && typeof value === 'object') {
173
+ return Object.fromEntries(Object.entries(value).map(([key, member]) => [key, detachedAuth(member)]));
174
+ }
175
+ return value;
176
+ }
177
+ /** Case-insensitive merging prevents stale static session headers from competing with live identity. */
178
+ function routeOptions(options, config) {
179
+ if (!config.headers && !config.transport && config.source !== GO_SOURCE)
180
+ return options;
181
+ const headers = Object.fromEntries([...Object.entries(config.headers ?? {}), ...Object.entries(options?.headers ?? {})]
182
+ .map(([key, value]) => [key.toLowerCase(), value]));
183
+ const sessionId = options?.sessionId ?? config.fallbackSessionId;
184
+ if (config.source === GO_SOURCE && sessionId !== undefined)
185
+ headers[SESSION_HEADER] = sessionId;
186
+ return { ...options, headers, ...(config.transport === undefined ? {} : { transport: config.transport }) };
187
+ }
188
+ /** `*` is the only wildcard; every other character matches itself. */
189
+ function patterns(value, path) {
190
+ const list = strings(value, path);
191
+ if (list.length === 0)
192
+ catalogError(path, 'expected at least one pattern');
193
+ return list.map(pattern => new RegExp('^' + pattern.split('*').map(part => part.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('.*') + '$'));
194
+ }
195
+ /** Expansion keeps every installed fact, so curating a catalog costs no restatement. */
196
+ function filteredModels(filter, source, input, path) {
197
+ const data = catalogRecord(filter, ['include', 'exclude'], path);
198
+ const include = 'include' in data ? patterns(data.include, path + '.include') : undefined;
199
+ const exclude = 'exclude' in data ? patterns(data.exclude, path + '.exclude') : undefined;
200
+ if (include === undefined && exclude === undefined)
201
+ catalogError(path, 'declare include, exclude, or both');
202
+ return source.getModels()
203
+ .filter(model => (include === undefined || include.some(pattern => pattern.test(model.id)))
204
+ && !(exclude ?? []).some(pattern => pattern.test(model.id)))
205
+ .map(model => {
206
+ const baseUrl = input.baseURL ?? model.baseUrl ?? source.baseUrl;
207
+ if (baseUrl === undefined)
208
+ catalogError(path, 'model "' + model.id + '" publishes no endpoint; declare baseURL');
209
+ return structuredClone({ ...model, provider: input.id, baseUrl });
210
+ });
211
+ }
212
+ /** pi-ai requires auth semantics on every provider; the harness resolves this route's key before dispatch. */
213
+ function harnessApiKeyAuth(name) {
214
+ return {
215
+ name,
216
+ resolve: ({ credential }) => Promise.resolve({
217
+ auth: credential?.key === undefined ? {} : { apiKey: credential.key },
218
+ source: name,
219
+ }),
220
+ };
221
+ }
222
+ /** A standalone builder validates its complete declaration before constructing any adapter profile. */
223
+ export function buildCatalogProfile(input) {
224
+ const path = 'provider';
225
+ const raw = catalogRecord(input, ROUTE_FIELDS, path);
226
+ catalogString(raw.id, path + '.id');
227
+ catalogString(raw.name, path + '.name');
228
+ // No backend list gates a profile: `source` names an installed pi-ai provider and
229
+ // anything else is the user's own endpoint, whose protocol they declare.
230
+ const source = 'source' in raw ? (catalogString(raw.source, path + '.source'), builtinProviders().find(provider => provider.id === raw.source)) : undefined;
231
+ if ('source' in raw && source === undefined)
232
+ catalogError(path + '.source', 'unknown installed provider ' + raw.source);
233
+ const declaredApi = 'api' in raw ? (catalogString(raw.api, path + '.api'), raw.api) : undefined;
234
+ if (source === undefined) {
235
+ if (declaredApi === undefined)
236
+ catalogError(path + '.api', 'a route with no installed source must declare its protocol');
237
+ if (!(declaredApi in PROTOCOL_STREAMS))
238
+ catalogError(path + '.api', 'unsupported protocol ' + declaredApi + '; this build implements ' + Object.keys(PROTOCOL_STREAMS).join(', '));
239
+ }
240
+ else if (declaredApi !== undefined)
241
+ catalogError(path + '.api', 'api belongs to a route with no installed source');
242
+ const auth = 'auth' in raw ? catalogRecord(raw.auth, ['apiKeyRef', 'credentialProvider'], path + '.auth') : undefined;
243
+ if (auth !== undefined) {
244
+ if (Object.keys(auth).length !== 1)
245
+ catalogError(path + '.auth', 'choose exactly one credential mode');
246
+ if ('apiKeyRef' in auth) {
247
+ if (source?.id === CODEX_SOURCE)
248
+ catalogError(path + '.auth', 'openai-codex requires credentialProvider OAuth');
249
+ catalogString(auth.apiKeyRef, path + '.auth.apiKeyRef');
250
+ credentialRef(auth.apiKeyRef);
251
+ }
252
+ else if (source === undefined)
253
+ catalogError(path + '.auth', 'credentialProvider needs an installed source to own the grant');
254
+ else if (auth.credentialProvider !== source.id)
255
+ catalogError(path + '.auth', 'credentialProvider must equal source');
256
+ }
257
+ if ('baseURL' in raw) {
258
+ catalogString(raw.baseURL, path + '.baseURL');
259
+ let url;
260
+ try {
261
+ url = new URL(raw.baseURL);
262
+ }
263
+ catch {
264
+ catalogError(path, 'invalid baseURL');
265
+ }
266
+ if (!HTTP_PROTOCOLS.includes(url.protocol) || url.username || url.password || url.hash)
267
+ catalogError(path, 'invalid baseURL');
268
+ }
269
+ if ('headers' in raw)
270
+ headers(raw.headers, path + '.headers');
271
+ if ('transport' in raw && (!TRANSPORTS.includes(raw.transport) || source?.id !== CODEX_SOURCE)) {
272
+ catalogError(path + '.transport', 'transport requires openai-codex and a supported mode');
273
+ }
274
+ if ('fallbackSessionId' in raw) {
275
+ catalogString(raw.fallbackSessionId, path + '.fallbackSessionId');
276
+ if (source?.id !== GO_SOURCE)
277
+ catalogError(path, 'fallbackSessionId requires opencode-go source');
278
+ }
279
+ if (source === undefined && !('baseURL' in raw))
280
+ catalogError(path + '.baseURL', 'a route with no installed source must declare its endpoint');
281
+ if (('models' in raw) === ('filter' in raw))
282
+ catalogError(path, 'declare exactly one of models or filter');
283
+ const declarations = 'filter' in raw ? undefined : raw.models;
284
+ if (declarations !== undefined && !Array.isArray(declarations))
285
+ catalogError(path + '.models', 'expected an explicit array');
286
+ if ('filter' in raw && source === undefined)
287
+ catalogError(path + '.filter', 'filter expands the catalog of an installed source');
288
+ const installed = source?.getModels();
289
+ const names = new Set();
290
+ const configuredMaxTokens = new Map();
291
+ const models = declarations === undefined
292
+ ? filteredModels(raw.filter, source, input, path + '.filter')
293
+ : declarations.map((entry, index) => {
294
+ const declaration = path + ' "' + raw.id + '".models[' + index + ']';
295
+ const spec = catalogRecord(entry, MODEL_FIELDS, declaration);
296
+ catalogString(spec.id, declaration + '.id');
297
+ catalogString(spec.name, declaration + '.name');
298
+ // One refused declaration must be repairable from the message alone: an
299
+ // index into a catalog that runs to dozens of entries names neither the
300
+ // route nor the model, which is how a stale id a newer line's vendor
301
+ // dropped reached a reader as provider.models[5].
302
+ const location = declaration + ' "' + spec.id + '"';
303
+ const aliases = 'aliases' in spec ? strings(spec.aliases, location + '.aliases') : [];
304
+ for (const name of [spec.id, ...aliases]) {
305
+ if (names.has(name))
306
+ catalogError(location, 'duplicate model id or alias ' + name);
307
+ names.add(name);
308
+ }
309
+ if ('template' in spec)
310
+ catalogString(spec.template, location + '.template');
311
+ const template = installed?.find(model => model.id === (spec.template ?? spec.id));
312
+ if ('template' in spec && !template)
313
+ catalogError(location, 'unknown template ' + spec.template);
314
+ if ('metadata' in spec)
315
+ metadata(spec.metadata, template?.api ?? declaredApi, location + '.metadata');
316
+ const overrides = spec.metadata;
317
+ if (!template) {
318
+ for (const key of REQUIRED_METADATA) {
319
+ // A route with no installed source states the protocol once, for every model it serves.
320
+ if (key === 'api' && declaredApi !== undefined)
321
+ continue;
322
+ if (!overrides || !(key in overrides))
323
+ catalogError(location, 'unknown model requires complete metadata: missing ' + key);
324
+ }
325
+ }
326
+ if ('defaultMaxTokens' in spec) {
327
+ number(spec.defaultMaxTokens, location + '.defaultMaxTokens', true);
328
+ const limit = spec.defaultMaxTokens;
329
+ if (limit > (overrides?.maxTokens ?? template.maxTokens)) {
330
+ catalogError(location + '.defaultMaxTokens', 'exceeds model maxTokens');
331
+ }
332
+ configuredMaxTokens.set(spec.id, limit);
333
+ }
334
+ const api = overrides?.api ?? template?.api ?? declaredApi;
335
+ // Inherited compatibility and thinking metadata belong to the template's protocol.
336
+ if (template && api !== template.api)
337
+ catalogError(location + '.metadata.api', 'cannot change a template-backed protocol');
338
+ if (declaredApi !== undefined && api !== declaredApi)
339
+ catalogError(location + '.metadata.api', 'a route with no installed source speaks its declared protocol');
340
+ if (installed !== undefined && !installed.some(model => model.api === api))
341
+ catalogError(location, 'source does not describe API ' + api);
342
+ const baseUrl = input.baseURL ?? template?.baseUrl ?? source?.baseUrl;
343
+ if (baseUrl === undefined)
344
+ catalogError(location, 'unknown model requires provider baseURL');
345
+ return freezeCatalogValue(structuredClone({ ...template, ...overrides, id: spec.id, name: spec.name, api, provider: input.id, baseUrl }));
346
+ });
347
+ const config = freezeCatalogValue(structuredClone(input));
348
+ // A route with no installed source borrows no vendor behavior: pi-ai's own
349
+ // implementation for the declared protocol streams it, under this route's facts.
350
+ const routed = source === undefined
351
+ ? createProvider({
352
+ id: config.id, name: config.name, baseUrl: config.baseURL, headers: config.headers,
353
+ auth: { apiKey: harnessApiKeyAuth(config.name) },
354
+ models: freezeCatalogValue(models), api: PROTOCOL_STREAMS[declaredApi],
355
+ })
356
+ : {
357
+ id: config.id, name: config.name, baseUrl: config.baseURL ?? source.baseUrl,
358
+ auth: detachedAuth(source.auth),
359
+ getModels: () => freezeCatalogValue(models),
360
+ stream: (model, context, options) => source.stream(model, context, routeOptions(options, config)),
361
+ streamSimple: (model, context, options) => source.streamSimple(model, context, routeOptions(options, config)),
362
+ };
363
+ return freezeCatalogValue({
364
+ provider: config.id, displayName: config.name,
365
+ ...(config.auth !== undefined && 'apiKeyRef' in config.auth ? { apiKeyEnv: credentialRef(config.auth.apiKeyRef) } : {}),
366
+ ...(config.baseURL === undefined ? {} : { baseURL: config.baseURL }),
367
+ ...(config.headers === undefined ? {} : { headers: config.headers }),
368
+ ...(config.transport === undefined ? {} : { transport: config.transport }),
369
+ streamIdleTimeoutMs: STREAM_IDLE_TIMEOUT_MS, maxRequestImageBytes: MAX_REQUEST_IMAGE_BYTES,
370
+ requestImagePixelBudget: REQUEST_IMAGE_PIXEL_BUDGET, requestImageMaxBytes: REQUEST_IMAGE_MAX_BYTES,
371
+ retryPolicy: resolveRetryPolicy(undefined, ERROR_PREFIX + config.id),
372
+ modelErrors: catalogMap([]), configuredMaxTokens: catalogMap(configuredMaxTokens), piProvider: routed,
373
+ });
374
+ }