@vidaiuk/pi-provider 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,79 @@
1
- # Temporary Holding Version
1
+ # Vidai for pi
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Use [pi](https://pi.dev) with every model your organisation offers through
4
+ [Vidai](https://vidai.uk), the governance-first AI control room. Your calls go
5
+ through your Vidai gateway, so your organisation's policies, guardrails, region
6
+ rules and budgets apply to them, and they show in Vidai's request logs and costs.
7
+
8
+ ## Install
9
+
10
+ ```bash
11
+ pi install npm:@vidaiuk/pi-provider
12
+ ```
13
+
14
+ Or try it once without installing:
15
+
16
+ ```bash
17
+ pi -e npm:@vidaiuk/pi-provider
18
+ ```
19
+
20
+ ## Set up
21
+
22
+ Set two variables, from your Vidai admin or the Vidai console (**API keys**):
23
+
24
+ ```bash
25
+ export VIDAI_BASE_URL=https://ai.example.com # your Vidai gateway, with or without /v1
26
+ export VIDAI_API_KEY=vk_... # your Vidai key
27
+ ```
28
+
29
+ Start pi and pick a model under **Vidai** in `/model`, or run
30
+ `pi --model vidai/<model>`. `pi --list-models vidai` lists them.
31
+
32
+ ## What you get
33
+
34
+ - **Your models only.** The list comes from your gateway with your key, so you
35
+ see the models your key may call, including your organisation's aliases.
36
+ - **Each provider's own format.** Claude models use Anthropic Messages, Gemini
37
+ models use the Gemini API, OpenAI's models use the Responses API, and the rest
38
+ use Chat Completions. Prompt caching and reasoning work as the provider made
39
+ them.
40
+ - **pi's model details.** Context window, output limit, image input and
41
+ reasoning come from pi's own model catalog. Models it doesn't know get safe
42
+ defaults.
43
+ - **Cost stays in Vidai.** pi shows $0 for Vidai models. Your organisation's real
44
+ cost for each call is in Vidai's **Cost** page and request logs.
45
+
46
+ ## If a model uses the wrong format
47
+
48
+ The package works out each model's format from its name. If your organisation
49
+ uses a name that doesn't say what the model is (an Azure deployment, an alias),
50
+ it uses Chat Completions, which your gateway translates. That works, but without
51
+ the provider's own prompt caching. You can set the format yourself:
52
+
53
+ ```bash
54
+ export VIDAI_MODEL_FORMATS="team-coder=anthropic-messages,prod-gpt=openai-responses"
55
+ ```
56
+
57
+ Formats: `anthropic-messages`, `openai-responses`, `google-generative-ai`,
58
+ `openai-completions`. Newer Vidai gateways report each model's provider, and the
59
+ package then uses that.
60
+
61
+ ## Troubleshooting
62
+
63
+ - **"vidai: couldn't list models … 401"**: the key is wrong or revoked. Check
64
+ `VIDAI_API_KEY`.
65
+ - **"… check VIDAI_BASE_URL"**: pi can't reach the gateway. Check the address and
66
+ that you're on the right network.
67
+ - **403 `model_not_allowed`**: your key isn't allowed that model. Ask your Vidai
68
+ admin.
69
+ - **Guardrail blocks**: your organisation's policy stopped the request. The
70
+ message says which rule; ask your Vidai admin.
71
+
72
+ ## Works with
73
+
74
+ Vidai 1.0.0-rc.3 and later, pi 1.4 and later. The source is short (three files in
75
+ [`src/`](src)); read it before installing, as with any pi extension.
76
+
77
+ ## Licence
78
+
79
+ Apache 2.0
package/package.json CHANGED
@@ -1,6 +1,48 @@
1
1
  {
2
2
  "name": "@vidaiuk/pi-provider",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Vidai as a model provider in pi: every model your Vidai key may call, governed by your organisation’s policies",
5
+ "scripts": {
6
+ "check": "tsc -p tsconfig.json",
7
+ "test": "vitest run"
8
+ },
9
+ "keywords": [
10
+ "pi-package",
11
+ "pi",
12
+ "vidai",
13
+ "ai-gateway",
14
+ "provider",
15
+ "governance"
16
+ ],
17
+ "license": "Apache-2.0",
18
+ "type": "module",
19
+ "devDependencies": {
20
+ "@earendil-works/pi-ai": "^1.7.0",
21
+ "@earendil-works/pi-coding-agent": "^1.7.0",
22
+ "@types/node": "^22.20.7",
23
+ "typescript": "^5.9.3",
24
+ "vitest": "^3.2.7"
25
+ },
26
+ "homepage": "https://github.com/vidaiUK/pi-provider#readme",
27
+ "repository": {
28
+ "type": "git",
29
+ "url": "git+https://github.com/vidaiUK/pi-provider.git"
30
+ },
31
+ "files": [
32
+ "src",
33
+ "README.md",
34
+ "LICENSE"
35
+ ],
36
+ "pi": {
37
+ "extensions": [
38
+ "./src/index.ts"
39
+ ]
40
+ },
41
+ "peerDependencies": {
42
+ "@earendil-works/pi-ai": "*",
43
+ "@earendil-works/pi-coding-agent": "*"
44
+ },
45
+ "publishConfig": {
46
+ "access": "public"
47
+ }
48
+ }
package/src/catalog.ts ADDED
@@ -0,0 +1,44 @@
1
+ // Looks a model up in pi's own model catalog (from @earendil-works/pi-ai, which pi ships).
2
+ import { getBuiltinModels, getBuiltinProviders } from "@earendil-works/pi-ai/providers/all";
3
+ import type { CatalogLookup, CatalogModel, PiApi } from "./models.js";
4
+
5
+ /** Catalogs to try first, by the format we'll speak; then every other provider pi knows. */
6
+ const PREFERRED: Record<PiApi, string[]> = {
7
+ "anthropic-messages": ["anthropic", "amazon-bedrock", "google-vertex"],
8
+ "openai-responses": ["openai", "azure"],
9
+ "google-generative-ai": ["google", "google-vertex"],
10
+ "openai-completions": ["openai", "groq", "openrouter", "together", "fireworks", "deepseek", "mistral", "xai"],
11
+ };
12
+
13
+ let index: Map<string, Map<string, CatalogModel>> | undefined;
14
+
15
+ function load(): Map<string, Map<string, CatalogModel>> {
16
+ if (index) return index;
17
+ index = new Map();
18
+ let providers: string[] = [];
19
+ try {
20
+ providers = getBuiltinProviders() as string[];
21
+ } catch {
22
+ providers = [];
23
+ }
24
+ for (const p of providers) {
25
+ const byId = new Map<string, CatalogModel>();
26
+ try {
27
+ for (const m of getBuiltinModels(p as never) as unknown as (CatalogModel & { id: string })[]) byId.set(m.id, m);
28
+ } catch {
29
+ continue;
30
+ }
31
+ index.set(p, byId);
32
+ }
33
+ return index;
34
+ }
35
+
36
+ export const lookupCatalog: CatalogLookup = (name, api) => {
37
+ const idx = load();
38
+ const order = [...PREFERRED[api], ...[...idx.keys()].filter((p) => !PREFERRED[api].includes(p))];
39
+ for (const p of order) {
40
+ const m = idx.get(p)?.get(name);
41
+ if (m) return m;
42
+ }
43
+ return undefined;
44
+ };
package/src/index.ts ADDED
@@ -0,0 +1,63 @@
1
+ // Vidai as a model provider in pi.
2
+ //
3
+ // VIDAI_BASE_URL https://<your-gateway> (with or without /v1)
4
+ // VIDAI_API_KEY a Vidai key (vk_...)
5
+ // VIDAI_MODEL_FORMATS optional: model=format,... to override the format chosen for a model
6
+ //
7
+ // Models come from the gateway's GET /v1/models with your key, so you see only the models your key
8
+ // may call. Each model is sent in its provider's own format where pi can tell what it is.
9
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
10
+ import { lookupCatalog } from "./catalog.js";
11
+ import { type GatewayModel, gatewayRoot, parseOverrides, type PiModel, toPiModels } from "./models.js";
12
+
13
+ const PROVIDER = "vidai";
14
+ const STARTUP_TIMEOUT_MS = 5_000;
15
+
16
+ async function fetchModels(root: string, key: string, signal: AbortSignal): Promise<GatewayModel[]> {
17
+ const res = await fetch(`${root}/v1/models`, {
18
+ headers: { Authorization: `Bearer ${key}`, Accept: "application/json" },
19
+ signal,
20
+ });
21
+ if (!res.ok) throw new Error(`Vidai gateway: GET /v1/models returned ${res.status}`);
22
+ const body = (await res.json()) as { data?: GatewayModel[] };
23
+ return Array.isArray(body.data) ? body.data : [];
24
+ }
25
+
26
+ export default async function vidai(pi: ExtensionAPI): Promise<void> {
27
+ const base = process.env.VIDAI_BASE_URL;
28
+ const key = process.env.VIDAI_API_KEY;
29
+ if (!base || !key) return; // nothing to register until both are set; pi starts normally
30
+ const root = gatewayRoot(base);
31
+ const overrides = parseOverrides(process.env.VIDAI_MODEL_FORMATS);
32
+ const build = (list: GatewayModel[]): PiModel[] => toPiModels(list, { root }, lookupCatalog, overrides);
33
+
34
+ let models: PiModel[] = [];
35
+ try {
36
+ models = build(await fetchModels(root, key, AbortSignal.timeout(STARTUP_TIMEOUT_MS)));
37
+ } catch (err) {
38
+ // Gateway unreachable at startup: refreshModels serves the last list pi saved.
39
+ const msg = err instanceof Error ? err.message : String(err);
40
+ const hint = / (401|403)$/.test(msg) ? " (check VIDAI_API_KEY)" : ` (check VIDAI_BASE_URL: ${root})`;
41
+ console.warn(`vidai: couldn't list models: ${msg}${hint}`);
42
+ }
43
+
44
+ pi.registerProvider(PROVIDER, {
45
+ name: "Vidai",
46
+ baseUrl: `${root}/v1`,
47
+ apiKey: "$VIDAI_API_KEY",
48
+ api: "openai-completions",
49
+ models,
50
+ async refreshModels(ctx) {
51
+ if (ctx.allowNetwork) {
52
+ try {
53
+ const fresh = build(await fetchModels(root, key, ctx.signal));
54
+ await ctx.publish({ persist: { models: fresh as never, checkedAt: Math.floor(Date.now() / 1000) } });
55
+ return fresh;
56
+ } catch {
57
+ // fall through to the saved list
58
+ }
59
+ }
60
+ return ((ctx.stored?.models ?? models) as unknown) as PiModel[];
61
+ },
62
+ });
63
+ }
package/src/models.ts ADDED
@@ -0,0 +1,223 @@
1
+ // Turns the gateway's GET /v1/models list into pi model definitions.
2
+ // Pure functions only (no pi runtime, no network), so they can be unit-tested.
3
+
4
+ export type PiApi = "anthropic-messages" | "openai-responses" | "google-generative-ai" | "openai-completions";
5
+
6
+ /** One entry of the gateway's GET /v1/models. Fields after `id` may be missing on older gateways. */
7
+ export interface GatewayModel {
8
+ id: string;
9
+ object?: string;
10
+ owned_by?: string;
11
+ /** The organisation's own name for the provider (not its kind). */
12
+ provider?: string;
13
+ source?: string;
14
+ /** For an alias: the model it points at. */
15
+ alias_of?: string;
16
+ /** Later gateways: the provider's protocol (openai, anthropic, azure, gemini, bedrock, vertex, ...). */
17
+ provider_type?: string;
18
+ /** Later gateways: the name the provider is called with (aliases resolved). */
19
+ upstream_model?: string;
20
+ }
21
+
22
+ /** Catalog details for a model, as pi's own catalog has them. */
23
+ export interface CatalogModel {
24
+ api?: string;
25
+ reasoning?: boolean;
26
+ input?: ("text" | "image")[];
27
+ contextWindow?: number;
28
+ maxTokens?: number;
29
+ thinkingLevelMap?: Record<string, string | null>;
30
+ promptCache?: { short?: number; long?: number };
31
+ compat?: Record<string, unknown>;
32
+ inputLimits?: Record<string, any>;
33
+ }
34
+
35
+ export type CatalogLookup = (name: string, api: PiApi) => CatalogModel | undefined;
36
+
37
+ export interface Endpoints {
38
+ /** https://<gateway> with no path. */
39
+ root: string;
40
+ }
41
+
42
+ export interface PiModel {
43
+ id: string;
44
+ name: string;
45
+ api: PiApi;
46
+ baseUrl: string;
47
+ reasoning: boolean;
48
+ input: ("text" | "image")[];
49
+ cost: { input: number; output: number; cacheRead: number; cacheWrite: number };
50
+ contextWindow: number;
51
+ maxTokens: number;
52
+ thinkingLevelMap?: Record<string, string | null>;
53
+ promptCache?: { short?: number; long?: number };
54
+ compat?: Record<string, unknown>;
55
+ inputLimits?: Record<string, any>;
56
+ }
57
+
58
+ /** Defaults for a model pi's catalog doesn't know. Conservative so requests aren't rejected. */
59
+ export const UNKNOWN_MODEL = { reasoning: false, input: ["text"] as ("text" | "image")[], contextWindow: 128_000, maxTokens: 16_384 };
60
+
61
+ /** Vidai is the source of truth for cost; pi's list prices would disagree with the organisation's rates. */
62
+ const NO_COST = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
63
+
64
+ /** Accepts https://gw, https://gw/, https://gw/v1, https://gw/v1beta and returns https://gw. */
65
+ export function gatewayRoot(baseUrl: string): string {
66
+ let u = baseUrl.trim().replace(/\/+$/, "");
67
+ u = u.replace(/\/(v1beta|v1)$/i, "");
68
+ return u;
69
+ }
70
+
71
+ export function baseUrlFor(api: PiApi, ep: Endpoints): string {
72
+ switch (api) {
73
+ case "anthropic-messages":
74
+ return ep.root; // pi adds /v1/messages
75
+ case "google-generative-ai":
76
+ return `${ep.root}/v1beta`;
77
+ default:
78
+ return `${ep.root}/v1`;
79
+ }
80
+ }
81
+
82
+ /** Models the gateway lists that aren't chat models. */
83
+ const NON_CHAT = /(embed|rerank|whisper|transcri|tts|speech|dall-e|gpt-image|imagen|moderation|stable-diffusion)/i;
84
+ export function isChatModel(m: GatewayModel): boolean {
85
+ return !NON_CHAT.test(m.upstream_model ?? m.alias_of ?? m.id);
86
+ }
87
+
88
+ /** The name that says what the model is: upstream name, else alias target, else id. */
89
+ export function realName(m: GatewayModel, byId: Map<string, GatewayModel>): string {
90
+ if (m.upstream_model) return m.upstream_model;
91
+ let cur = m;
92
+ for (let i = 0; i < 5 && cur.alias_of; i++) {
93
+ const next = byId.get(cur.alias_of);
94
+ if (!next) return cur.alias_of;
95
+ cur = next;
96
+ }
97
+ return cur.upstream_model ?? cur.id;
98
+ }
99
+
100
+ /**
101
+ * Candidate catalog names for a provider-specific model name, most specific first:
102
+ * us.anthropic.claude-sonnet-4-5-20250929-v1:0 -> claude-sonnet-4-5-20250929, claude-sonnet-4-5
103
+ * claude-sonnet-4-5@20250929 -> claude-sonnet-4-5-20250929, claude-sonnet-4-5
104
+ * p2/claude-sonnet-4-5 -> claude-sonnet-4-5
105
+ * models/gemini-2.5-pro -> gemini-2.5-pro
106
+ */
107
+ export function catalogNames(name: string): string[] {
108
+ const out: string[] = [];
109
+ const add = (s: string) => { if (s && !out.includes(s)) out.push(s); };
110
+ add(name);
111
+ let n = name.split("/").pop() ?? name;
112
+ add(n);
113
+ n = n.replace(/^(us|eu|apac|global|jp|au|ca)\./i, "").replace(/^(anthropic|amazon|meta|mistral|cohere|ai21|deepseek|qwen|openai)\./i, "");
114
+ n = n.replace(/-v\d+(:\d+)?$/i, "").replace(/:\d+$/, "");
115
+ n = n.replace(/@(\d{8})$/, "-$1").replace(/@latest$/i, "").replace(/@.*$/, "");
116
+ add(n);
117
+ add(n.replace(/-\d{8}$/, ""));
118
+ add(n.replace(/-latest$/i, ""));
119
+ return out;
120
+ }
121
+
122
+ type Family = "claude" | "gemini" | "gpt" | "other";
123
+ export function family(name: string): Family {
124
+ const last = (name.split("/").pop() ?? name).toLowerCase();
125
+ if (last.includes("claude")) return "claude";
126
+ if (last.includes("gemini")) return "gemini";
127
+ if (last.startsWith("gpt-oss")) return "other"; // open-weight, served by OpenAI-compatible hosts
128
+ if (/^(gpt-|chatgpt|o\d|codex)/.test(last)) return "gpt";
129
+ return "other";
130
+ }
131
+
132
+ /**
133
+ * Which of pi's formats to send this model in. Every choice works through the gateway (it
134
+ * translates); the right one keeps the provider's own prompt caching and reasoning settings.
135
+ */
136
+ export function chooseApi(m: GatewayModel, name: string, override?: PiApi): PiApi {
137
+ if (override) return override;
138
+ const f = family(name);
139
+ const t = m.provider_type?.toLowerCase();
140
+ if (t) {
141
+ switch (t) {
142
+ case "anthropic":
143
+ return "anthropic-messages";
144
+ case "gemini":
145
+ return "google-generative-ai";
146
+ case "openai_responses":
147
+ return "openai-responses";
148
+ case "bedrock":
149
+ case "vertex":
150
+ return f === "claude" ? "anthropic-messages" : f === "gemini" ? "google-generative-ai" : "openai-completions";
151
+ case "openai":
152
+ case "azure":
153
+ // also Groq, OpenRouter, vLLM, ...: Responses only for OpenAI's own models
154
+ return f === "gpt" ? "openai-responses" : "openai-completions";
155
+ default:
156
+ return "openai-completions";
157
+ }
158
+ }
159
+ if (f === "claude") return "anthropic-messages";
160
+ if (f === "gemini") return "google-generative-ai";
161
+ if (f === "gpt") return "openai-responses";
162
+ return "openai-completions";
163
+ }
164
+
165
+ /** Parses VIDAI_MODEL_FORMATS: "team-coder=anthropic-messages,prod-gpt=openai-responses". */
166
+ export function parseOverrides(spec: string | undefined): Map<string, PiApi> {
167
+ const ok = new Set<PiApi>(["anthropic-messages", "openai-responses", "google-generative-ai", "openai-completions"]);
168
+ const out = new Map<string, PiApi>();
169
+ for (const part of (spec ?? "").split(",")) {
170
+ const i = part.lastIndexOf("=");
171
+ if (i <= 0) continue;
172
+ const id = part.slice(0, i).trim();
173
+ const api = part.slice(i + 1).trim() as PiApi;
174
+ if (id && ok.has(api)) out.set(id, api);
175
+ }
176
+ return out;
177
+ }
178
+
179
+ export function toPiModels(
180
+ list: GatewayModel[],
181
+ ep: Endpoints,
182
+ lookup: CatalogLookup,
183
+ overrides: Map<string, PiApi> = new Map(),
184
+ ): PiModel[] {
185
+ const byId = new Map(list.map((m) => [m.id, m]));
186
+ const out: PiModel[] = [];
187
+ for (const m of list) {
188
+ if (!m.id || !isChatModel(m)) continue;
189
+ const name = realName(m, byId);
190
+ const api = chooseApi(m, name, overrides.get(m.id));
191
+ let cat: CatalogModel | undefined;
192
+ for (const n of catalogNames(name)) {
193
+ cat = lookup(n, api);
194
+ if (cat) break;
195
+ }
196
+ // Provider-specific tuning only applies when we speak the catalog entry's own format.
197
+ const native = cat?.api === api;
198
+ let thinking = cat?.thinkingLevelMap ? { ...cat.thinkingLevelMap } : undefined;
199
+ // OpenAI reasoning models reject "off" (400); their lowest setting is "minimal".
200
+ if (thinking && thinking.off === null && thinking.minimal) thinking.off = thinking.minimal;
201
+ let compat: Record<string, unknown> | undefined;
202
+ if (native && cat?.compat) {
203
+ const { allowedFallbackModels: _drop, ...rest } = cat.compat;
204
+ compat = rest;
205
+ }
206
+ out.push({
207
+ id: m.id,
208
+ name: m.alias_of ? `${m.id} (→ ${m.alias_of})` : m.id,
209
+ api,
210
+ baseUrl: baseUrlFor(api, ep),
211
+ reasoning: cat?.reasoning ?? UNKNOWN_MODEL.reasoning,
212
+ input: cat?.input ?? UNKNOWN_MODEL.input,
213
+ cost: NO_COST,
214
+ contextWindow: cat?.contextWindow ?? UNKNOWN_MODEL.contextWindow,
215
+ maxTokens: cat?.maxTokens ?? UNKNOWN_MODEL.maxTokens,
216
+ ...(cat?.reasoning && thinking ? { thinkingLevelMap: thinking } : {}),
217
+ ...(native && cat?.promptCache ? { promptCache: cat.promptCache } : {}),
218
+ ...(compat && Object.keys(compat).length ? { compat } : {}),
219
+ ...(cat?.inputLimits ? { inputLimits: cat.inputLimits } : {}),
220
+ });
221
+ }
222
+ return out;
223
+ }