@mcowger/pi-plexus 0.2.5 → 0.5.3

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.
@@ -0,0 +1,429 @@
1
+ // @bun
2
+ // src/extension.ts
3
+ import * as os from "os";
4
+ import * as path4 from "path";
5
+
6
+ // ../plexus-models/src/convert.ts
7
+ var REASONING_PARAMS = new Set(["reasoning", "include_reasoning", "reasoning_effort"]);
8
+ var API_DIALECT_MAP = {
9
+ chat_completions: "openai-completions",
10
+ messages: "anthropic-messages",
11
+ gemini: "google-generative-ai",
12
+ responses: "openai-responses"
13
+ };
14
+ function mapPreferredApi(raw) {
15
+ if (raw === undefined)
16
+ return "openai-completions";
17
+ const candidates = Array.isArray(raw) ? raw : [raw];
18
+ for (const candidate of candidates) {
19
+ const mapped = API_DIALECT_MAP[candidate];
20
+ if (mapped !== undefined)
21
+ return mapped;
22
+ }
23
+ return "openai-completions";
24
+ }
25
+ function adjustBaseUrl(baseUrl, preferredApi) {
26
+ const stripped = baseUrl.replace(/\/+$/, "");
27
+ switch (preferredApi) {
28
+ case "anthropic-messages":
29
+ return stripped.endsWith("/v1") ? stripped.slice(0, -3) : stripped;
30
+ case "google-generative-ai":
31
+ return stripped.endsWith("/v1") ? `${stripped.slice(0, -3)}/v1beta` : stripped;
32
+ default:
33
+ return stripped;
34
+ }
35
+ }
36
+ function mapInputModalities(model) {
37
+ const raw = model.architecture?.input_modalities;
38
+ if (!raw || raw.length === 0)
39
+ return ["text"];
40
+ const result = [];
41
+ for (const m of raw) {
42
+ if (m === "text" || m === "image")
43
+ result.push(m);
44
+ }
45
+ return result.length > 0 ? result : ["text"];
46
+ }
47
+ function inferReasoning(model) {
48
+ const params = model.supported_parameters;
49
+ if (!params)
50
+ return false;
51
+ return params.some((p) => REASONING_PARAMS.has(p));
52
+ }
53
+ function parsePrice(raw) {
54
+ if (raw === undefined)
55
+ return 0;
56
+ const n = parseFloat(raw);
57
+ return isFinite(n) && n >= 0 ? n : 0;
58
+ }
59
+ function resolveContextWindow(model) {
60
+ const v = model.context_length ?? model.top_provider?.context_length ?? null;
61
+ return v != null && v > 0 ? v : 8192;
62
+ }
63
+ function resolveMaxTokens(model, contextWindow) {
64
+ const v = model.top_provider?.max_completion_tokens ?? null;
65
+ return v != null && v > 0 ? v : contextWindow;
66
+ }
67
+ function convertToDescriptor(raw, baseUrl) {
68
+ const preferredApi = mapPreferredApi(raw.preferred_api);
69
+ const adjustedBaseUrl = adjustBaseUrl(baseUrl, preferredApi);
70
+ const contextWindow = resolveContextWindow(raw);
71
+ const maxTokens = resolveMaxTokens(raw, contextWindow);
72
+ const descriptor = {
73
+ id: raw.id,
74
+ name: raw.name ?? raw.id,
75
+ preferredApi,
76
+ provider: "plexus",
77
+ baseUrl: adjustedBaseUrl,
78
+ reasoning: inferReasoning(raw),
79
+ input: mapInputModalities(raw),
80
+ cost: {
81
+ input: parsePrice(raw.pricing?.prompt),
82
+ output: parsePrice(raw.pricing?.completion),
83
+ cacheRead: parsePrice(raw.pricing?.input_cache_read),
84
+ cacheWrite: parsePrice(raw.pricing?.input_cache_write)
85
+ },
86
+ contextWindow,
87
+ maxTokens
88
+ };
89
+ if (raw.pi_provider)
90
+ descriptor.piProvider = raw.pi_provider;
91
+ if (raw.pi_model)
92
+ descriptor.piModel = raw.pi_model;
93
+ if (raw.pi_options && Object.keys(raw.pi_options).length > 0)
94
+ descriptor.piOptions = raw.pi_options;
95
+ return descriptor;
96
+ }
97
+ function convertDescriptors(models, baseUrl) {
98
+ const result = [];
99
+ for (const m of models) {
100
+ if (!m.id)
101
+ continue;
102
+ result.push(convertToDescriptor(m, baseUrl));
103
+ }
104
+ return result;
105
+ }
106
+ function detectOpenAICompletionsCompat(providerName, baseUrl) {
107
+ const name = providerName.toLowerCase();
108
+ let host = "";
109
+ try {
110
+ host = new URL(baseUrl).hostname.toLowerCase();
111
+ } catch {}
112
+ const isCerebras = name === "cerebras" || host.includes("cerebras");
113
+ const isChutes = name === "chutes.ai" || host.includes("chutes.ai");
114
+ const isXai = name === "xai" || host === "api.x.ai";
115
+ const isZai = name === "zai" || host === "api.zai.com" || host.includes("z.ai");
116
+ const isMoonshot = name === "moonshotai" || name === "moonshotai-cn" || host.includes("moonshot") || host.includes("kimi");
117
+ const isOpencode = name === "opencode" || host.includes("opencode");
118
+ const isCloudflareWorkers = host.includes("workers.cloudflare.com") || host.includes("ai.cloudflare.com");
119
+ const isCloudflareGateway = host.includes("gateway.ai.cloudflare.com");
120
+ const isCloudflare = isCloudflareWorkers || isCloudflareGateway;
121
+ const isDeepSeek = name === "deepseek" || host.includes("deepseek");
122
+ const isOpenRouter = name === "openrouter" || host.includes("openrouter.ai");
123
+ const isNonStandard = isCerebras || isChutes || isXai || isZai || isMoonshot || isOpencode || isCloudflare || isDeepSeek;
124
+ const supportsStore = !isNonStandard;
125
+ const supportsDeveloperRole = !isNonStandard;
126
+ const supportsReasoningEffort = !isXai && !isZai && !isMoonshot && !isCloudflareGateway;
127
+ let maxTokensField = "max_completion_tokens";
128
+ if (isChutes || isMoonshot || isCloudflareGateway) {
129
+ maxTokensField = "max_tokens";
130
+ }
131
+ let thinkingFormat = "openai";
132
+ if (isDeepSeek)
133
+ thinkingFormat = "deepseek";
134
+ else if (isZai)
135
+ thinkingFormat = "zai";
136
+ else if (isOpenRouter)
137
+ thinkingFormat = "openrouter";
138
+ const requiresReasoningContentOnAssistantMessages = isDeepSeek;
139
+ const cacheControlFormat = isOpenRouter ? "anthropic" : undefined;
140
+ const supportsStrictMode = !isMoonshot && !isCloudflareGateway;
141
+ const supportsLongCacheRetention = !isCloudflare;
142
+ const compat = {
143
+ supportsStore,
144
+ supportsDeveloperRole,
145
+ supportsReasoningEffort,
146
+ supportsUsageInStreaming: true,
147
+ maxTokensField,
148
+ requiresToolResultName: false,
149
+ requiresAssistantAfterToolResult: false,
150
+ requiresThinkingAsText: false,
151
+ requiresReasoningContentOnAssistantMessages,
152
+ thinkingFormat,
153
+ openRouterRouting: {},
154
+ vercelGatewayRouting: {},
155
+ zaiToolStream: false,
156
+ supportsStrictMode,
157
+ sendSessionAffinityHeaders: false,
158
+ supportsLongCacheRetention
159
+ };
160
+ if (cacheControlFormat !== undefined) {
161
+ compat.cacheControlFormat = cacheControlFormat;
162
+ }
163
+ return compat;
164
+ }
165
+ async function fetchPlexusModels(apiKey, modelsUrl) {
166
+ const res = await fetch(modelsUrl, {
167
+ headers: {
168
+ Authorization: `Bearer ${apiKey}`,
169
+ Accept: "application/json"
170
+ }
171
+ });
172
+ if (!res.ok) {
173
+ throw new Error(`Plexus models fetch failed: ${res.status} ${res.statusText}`);
174
+ }
175
+ const raw = await res.json();
176
+ return { models: raw.data ?? [], raw };
177
+ }
178
+ // ../plexus-models/src/config.ts
179
+ import * as fs from "fs";
180
+ import * as path from "path";
181
+ var PLEXUS_DIR = "extensions/plexus";
182
+ var CONFIG_FILE = "config.json";
183
+ function getConfigPath(agentDir) {
184
+ return path.join(agentDir, PLEXUS_DIR, CONFIG_FILE);
185
+ }
186
+ function getConfigSync(agentDir) {
187
+ try {
188
+ const raw = fs.readFileSync(getConfigPath(agentDir), "utf8");
189
+ const parsed = JSON.parse(raw);
190
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
191
+ return parsed;
192
+ }
193
+ return {};
194
+ } catch {
195
+ return {};
196
+ }
197
+ }
198
+ async function saveBaseUrl(agentDir, baseUrl, defaultModel) {
199
+ const configPath = getConfigPath(agentDir);
200
+ const dir = path.dirname(configPath);
201
+ await fs.promises.mkdir(dir, { recursive: true });
202
+ const existing = getConfigSync(agentDir);
203
+ const updated = {
204
+ ...existing,
205
+ baseUrl: baseUrl.replace(/\/+$/, "")
206
+ };
207
+ if (defaultModel !== undefined) {
208
+ updated.defaultModel = defaultModel;
209
+ }
210
+ await fs.promises.writeFile(configPath, JSON.stringify(updated, null, 2) + `
211
+ `, "utf8");
212
+ }
213
+ function getRawBaseUrl(agentDir) {
214
+ const cfg = getConfigSync(agentDir);
215
+ const raw = cfg.baseUrl ?? process.env["PLEXUS_BASE_URL"] ?? null;
216
+ if (!raw)
217
+ return null;
218
+ return raw.replace(/\/+$/, "");
219
+ }
220
+ function getBaseUrl(agentDir) {
221
+ const raw = getRawBaseUrl(agentDir);
222
+ return raw ? `${raw}/v1` : null;
223
+ }
224
+ function getModelsUrl(agentDir) {
225
+ const raw = getRawBaseUrl(agentDir);
226
+ return raw ? `${raw}/v1/models` : null;
227
+ }
228
+ // ../plexus-models/src/cache.ts
229
+ import * as fs2 from "fs";
230
+ import * as path2 from "path";
231
+ var PLEXUS_DIR2 = "extensions/plexus";
232
+ var CACHE_FILE = "plexus-models-cache.json";
233
+ var RAW_RESPONSE_FILE = "plexus-models-response.json";
234
+ function getCachePath(agentDir) {
235
+ return path2.join(agentDir, PLEXUS_DIR2, CACHE_FILE);
236
+ }
237
+ function getRawResponsePath(agentDir) {
238
+ return path2.join(agentDir, PLEXUS_DIR2, RAW_RESPONSE_FILE);
239
+ }
240
+ function parseCacheData(raw) {
241
+ try {
242
+ const parsed = JSON.parse(raw);
243
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
244
+ return null;
245
+ const obj = parsed;
246
+ if (!Array.isArray(obj["models"]))
247
+ return null;
248
+ return {
249
+ models: obj["models"],
250
+ timestamp: typeof obj["timestamp"] === "number" ? obj["timestamp"] : 0
251
+ };
252
+ } catch {
253
+ return null;
254
+ }
255
+ }
256
+ function readCachedModelsSync(agentDir) {
257
+ try {
258
+ const raw = fs2.readFileSync(getCachePath(agentDir), "utf8");
259
+ return parseCacheData(raw);
260
+ } catch {
261
+ return null;
262
+ }
263
+ }
264
+ async function writeCachedModels(agentDir, models) {
265
+ const cachePath = getCachePath(agentDir);
266
+ await fs2.promises.mkdir(path2.dirname(cachePath), { recursive: true });
267
+ const payload = { models, timestamp: Date.now() };
268
+ await fs2.promises.writeFile(cachePath, JSON.stringify(payload, null, 2) + `
269
+ `, "utf8");
270
+ }
271
+ async function writeRawResponse(agentDir, data) {
272
+ const rawPath = getRawResponsePath(agentDir);
273
+ await fs2.promises.mkdir(path2.dirname(rawPath), { recursive: true });
274
+ await fs2.promises.writeFile(rawPath, JSON.stringify(data, null, 2) + `
275
+ `, "utf8");
276
+ }
277
+ // ../plexus-models/src/log.ts
278
+ import * as fs3 from "fs";
279
+ import * as path3 from "path";
280
+ var PLEXUS_DIR3 = "extensions/plexus";
281
+ var LOG_FILE = "plexus.log";
282
+ function log(agentDir, message, data) {
283
+ try {
284
+ const logPath = path3.join(agentDir, PLEXUS_DIR3, LOG_FILE);
285
+ const dir = path3.dirname(logPath);
286
+ fs3.mkdirSync(dir, { recursive: true });
287
+ const ts = new Date().toISOString();
288
+ const line = data !== undefined ? `${ts} ${message} ${JSON.stringify(data)}
289
+ ` : `${ts} ${message}
290
+ `;
291
+ fs3.appendFileSync(logPath, line, "utf8");
292
+ } catch {}
293
+ }
294
+ // src/mapper.ts
295
+ function descriptorToPiModel(descriptor) {
296
+ const cost = {
297
+ input: descriptor.cost.input * 1e6,
298
+ output: descriptor.cost.output * 1e6,
299
+ cacheRead: descriptor.cost.cacheRead * 1e6,
300
+ cacheWrite: descriptor.cost.cacheWrite * 1e6
301
+ };
302
+ let compat;
303
+ if (descriptor.preferredApi === "openai-completions") {
304
+ const heuristic = detectOpenAICompletionsCompat(descriptor.provider, descriptor.baseUrl);
305
+ const merged = descriptor.piOptions ? { ...heuristic, ...descriptor.piOptions } : heuristic;
306
+ compat = merged;
307
+ } else if (descriptor.piOptions) {
308
+ compat = descriptor.piOptions;
309
+ }
310
+ return {
311
+ id: descriptor.id,
312
+ name: descriptor.name,
313
+ api: descriptor.preferredApi,
314
+ baseUrl: descriptor.baseUrl,
315
+ reasoning: descriptor.reasoning,
316
+ input: descriptor.input,
317
+ cost,
318
+ contextWindow: descriptor.contextWindow,
319
+ maxTokens: descriptor.maxTokens,
320
+ ...compat !== undefined ? { compat } : {}
321
+ };
322
+ }
323
+
324
+ // src/extension.ts
325
+ var PROVIDER_NAME = "plexus";
326
+ function getAgentDir() {
327
+ const override = process.env["PI_CODING_AGENT_DIR"];
328
+ if (override)
329
+ return path4.resolve(override);
330
+ const configDir = process.env["PI_CONFIG_DIR"] || ".pi";
331
+ return path4.join(os.homedir(), configDir, "agent");
332
+ }
333
+ function getApiKey() {
334
+ return process.env["PLEXUS_API_KEY"];
335
+ }
336
+ function plexusExtension(pi) {
337
+ const agentDir = getAgentDir();
338
+ const key = getApiKey();
339
+ if (key) {
340
+ const cached = readCachedModelsSync(agentDir);
341
+ if (cached && cached.models.length > 0) {
342
+ const baseUrl = getBaseUrl(agentDir);
343
+ if (baseUrl) {
344
+ pi.registerProvider(PROVIDER_NAME, {
345
+ baseUrl,
346
+ apiKey: key,
347
+ api: "openai-completions",
348
+ authHeader: true,
349
+ models: cached.models.map(descriptorToPiModel)
350
+ });
351
+ log(agentDir, "startup: registered from cache", { count: cached.models.length });
352
+ }
353
+ }
354
+ }
355
+ pi.on("session_start", async () => {
356
+ await doRefresh(pi, agentDir, null);
357
+ });
358
+ pi.registerCommand("plexus", {
359
+ description: "Manage Plexus AI model proxy. Sub-commands: login, refresh",
360
+ async handler(args, ctx) {
361
+ const sub = args.trim().toLowerCase();
362
+ if (sub === "login" || sub === "") {
363
+ await handleLogin(pi, ctx, agentDir);
364
+ } else if (sub === "refresh") {
365
+ await handleRefresh(pi, ctx, agentDir);
366
+ } else {
367
+ ctx.ui.notify(`Unknown sub-command: "${args}". Use: /plexus login | /plexus refresh`, "warning");
368
+ }
369
+ }
370
+ });
371
+ }
372
+ async function handleLogin(pi, ctx, agentDir) {
373
+ if (!getApiKey()) {
374
+ ctx.ui.notify("PLEXUS_API_KEY env var is not set. Set it and restart omp.", "error");
375
+ return;
376
+ }
377
+ const baseUrlInput = await ctx.ui.input("Plexus base URL", "https://plexus.example.com");
378
+ if (!baseUrlInput) {
379
+ ctx.ui.notify("Login cancelled.", "info");
380
+ return;
381
+ }
382
+ const defaultModelInput = await ctx.ui.input("Default model (optional \u2014 Enter to skip)", "");
383
+ await saveBaseUrl(agentDir, baseUrlInput.trim(), defaultModelInput?.trim() || undefined);
384
+ ctx.ui.notify("Plexus config saved. Refreshing models\u2026", "info");
385
+ await doRefresh(pi, agentDir, ctx);
386
+ }
387
+ async function handleRefresh(pi, ctx, agentDir) {
388
+ ctx.ui.notify("Refreshing Plexus models\u2026", "info");
389
+ await doRefresh(pi, agentDir, ctx);
390
+ }
391
+ async function doRefresh(pi, agentDir, notify) {
392
+ const modelsUrl = getModelsUrl(agentDir);
393
+ const baseUrl = getBaseUrl(agentDir);
394
+ const key = getApiKey();
395
+ if (!key) {
396
+ if (notify)
397
+ notify.ui.notify("PLEXUS_API_KEY env var is not set.", "error");
398
+ return;
399
+ }
400
+ if (!modelsUrl || !baseUrl) {
401
+ if (notify)
402
+ notify.ui.notify("Plexus base URL not configured. Run /plexus login first.", "warning");
403
+ return;
404
+ }
405
+ try {
406
+ const { models: raw, raw: rawResponse } = await fetchPlexusModels(key, modelsUrl);
407
+ const descriptors = convertDescriptors(raw, baseUrl);
408
+ await writeCachedModels(agentDir, descriptors);
409
+ await writeRawResponse(agentDir, rawResponse);
410
+ pi.registerProvider(PROVIDER_NAME, {
411
+ baseUrl,
412
+ apiKey: key,
413
+ api: "openai-completions",
414
+ authHeader: true,
415
+ models: descriptors.map(descriptorToPiModel)
416
+ });
417
+ log(agentDir, "refresh: ok", { count: descriptors.length });
418
+ if (notify)
419
+ notify.ui.notify(`Plexus: loaded ${descriptors.length} models.`, "info");
420
+ } catch (err) {
421
+ const message = err instanceof Error ? err.message : String(err);
422
+ log(agentDir, "refresh: error", { error: message });
423
+ if (notify)
424
+ notify.ui.notify(`Plexus refresh failed: ${message}`, "error");
425
+ }
426
+ }
427
+ export {
428
+ plexusExtension as default
429
+ };
package/package.json CHANGED
@@ -1,62 +1,31 @@
1
1
  {
2
2
  "name": "@mcowger/pi-plexus",
3
- "author": "Matt Cowger",
4
- "version": "0.2.5",
5
- "description": "Plexus AI provider extension package for pi",
6
- "license": "MIT",
3
+ "version": "0.5.3",
4
+ "description": "Plexus AI proxy plugin for pi and oh-my-pi coding agents",
7
5
  "type": "module",
8
- "keywords": [
9
- "pi-package",
10
- "pi",
11
- "pi-extension",
12
- "plexus",
13
- "provider"
14
- ],
15
- "engines": {
16
- "bun": ">=1.0"
17
- },
6
+ "main": "./dist/extension.js",
18
7
  "files": [
19
- "index.ts",
20
- "src/",
21
- "README.md",
22
- "LICENSE"
8
+ "dist/extension.js",
9
+ "package.json"
23
10
  ],
11
+ "pi": {
12
+ "extensions": [
13
+ "dist/extension.js"
14
+ ]
15
+ },
24
16
  "scripts": {
25
- "postinstall": "command -v lefthook >/dev/null 2>&1 && lefthook install || true",
26
- "check": "bunx tsc --noEmit",
27
- "test": "bun test",
28
- "format": "biome format --write .",
29
- "format:check": "biome format .",
30
- "lint": "biome lint .",
31
- "pack:dry-run": "bun pack --dry-run"
17
+ "build": "bun run build.ts"
32
18
  },
33
- "devDependencies": {
34
- "@biomejs/biome": "2.4.15",
35
- "lefthook": "2.1.8"
19
+ "dependencies": {
20
+ "plexus-models": "workspace:*"
36
21
  },
37
- "peerDependencies": {
38
- "@earendil-works/pi-ai": "0.75.4",
39
- "@earendil-works/pi-coding-agent": "0.75.4",
40
- "@oh-my-pi/pi-ai": ">=15.0.0",
41
- "@oh-my-pi/pi-coding-agent": ">=15.0.0"
22
+ "devDependencies": {
23
+ "@types/bun": "latest"
42
24
  },
43
- "peerDependenciesMeta": {
44
- "@oh-my-pi/pi-ai": {
45
- "optional": true
46
- },
47
- "@oh-my-pi/pi-coding-agent": {
48
- "optional": true
49
- },
50
- "@earendil-works/pi-ai": {
51
- "optional": true
52
- },
53
- "@earendil-works/pi-coding-agent": {
54
- "optional": true
55
- }
25
+ "repository": {
26
+ "type": "git",
27
+ "url": "https://github.com/mcowger/plexus-agent-plugins.git",
28
+ "directory": "packages/plexus-pi"
56
29
  },
57
- "pi": {
58
- "extensions": [
59
- "./index.ts"
60
- ]
61
- }
30
+ "license": "MIT"
62
31
  }
package/README.md DELETED
@@ -1,81 +0,0 @@
1
- # pi-plexus
2
-
3
- A [pi](https://github.com/earendil-works/pi-mono) extension that adds [Plexus](https://github.com/mcowger/plexus) as a provider, dynamically discovering models from your Plexus instance.
4
-
5
- ## Requirements
6
-
7
- - pi `0.74.0` or later
8
- - A running Plexus instance with a valid API key
9
-
10
- ## Installation
11
-
12
- ### Via npm (recommended)
13
-
14
- ```bash
15
- pi install npm:@mcowger/pi-plexus
16
- ```
17
-
18
- ### Via git
19
-
20
- ```bash
21
- pi install git:github.com/mcowger/pi-plexus
22
- ```
23
-
24
- ## Configuration
25
-
26
- Once installed, run the login command inside pi:
27
-
28
- ```
29
- /plexus login
30
- ```
31
-
32
- You will be prompted for:
33
- 1. **Base URL** — the root URL of your Plexus instance, e.g. `https://plexus.example.com` (no `/v1` suffix needed)
34
- 2. **API key** — your Plexus API key
35
- 3. **Default model** (optional) — the model ID to use by default, e.g. `glm-5.1` (use the raw model name, not the `plexus/` prefix)
36
-
37
- Credentials are stored in `~/.pi/agent/auth.json` (API key, managed by pi) and `~/.pi/agent/extensions/plexus/config.json` (base URL and default model).
38
-
39
- ### Environment variables
40
-
41
- As an alternative to `/plexus login`, you can set environment variables before starting pi:
42
-
43
- ```bash
44
- export PLEXUS_BASE_URL=https://plexus.example.com
45
- export PLEXUS_API_KEY=sk-...
46
- ```
47
-
48
- ## Commands
49
-
50
- | Command | Description |
51
- |---|---|
52
- | `/plexus login` | Configure base URL and API key |
53
- | `/plexus refresh` | Re-fetch the model list from your Plexus instance and update the local cache |
54
-
55
- ## How it works
56
-
57
- On startup, the extension loads a cached model list from `~/.pi/agent/extensions/plexus/plexus-models-cache.json` so models are available immediately. On each session start it attempts a live refresh from `/v1/models` to pick up any new or removed models.
58
-
59
- Models are registered under the `plexus` provider and appear in `/model` alongside all other configured providers.
60
-
61
- ### Provider-specific model fidelity via `pi_provider` / `pi_model`
62
-
63
- Many models require provider-specific compatibility settings (e.g. DeepSeek needs `system` role instead of `developer`, Qwen uses a different thinking format, etc.). pi already knows these settings for built-in providers, but when models are proxied through Plexus, pi can't auto-detect them because the provider and base URL belong to Plexus, not the original provider.
64
-
65
- To solve this, configure Plexus to expose `pi_provider` and `pi_model` in its `/v1/models` response. When these fields are set, the extension looks up the full model definition from pi's built-in MODELS registry and uses it for maximum fidelity — picking up the correct `api`, `compat`, `thinkingLevelMap`, `reasoning`, `contextWindow`, `maxTokens`, and `input` modalities, all sourced from pi's curated configuration rather than inferred from Plexus fields.
66
-
67
- In your Plexus model configuration, enable the **pi Provider** and **pi Model** fields:
68
-
69
- ![Plexus pi model configuration](docs/PlexusPiModel.png)
70
-
71
- For example, a DeepSeek V4 Flash entry configured with `pi_provider: deepseek` and `pi_model: deepseek-v4-flash` will automatically get the correct compat settings (including `supportsDeveloperRole: false` and `thinkingFormat: deepseek`), ensuring requests are formatted correctly for DeepSeek even though they're routed through Plexus.
72
-
73
- If `pi_provider` / `pi_model` are not set for a model, the extension falls back to inferring settings from the Plexus API fields (preferred_api, supported_parameters, architecture, etc.) — which works fine for simpler models but won't include provider-specific compat overrides.
74
-
75
- ## Troubleshooting
76
-
77
- The extension writes a debug log to `~/.pi/agent/extensions/plexus/plexus.log`. If models are missing or requests are failing, check that file first:
78
-
79
- ```bash
80
- cat ~/.pi/agent/extensions/plexus/plexus.log
81
- ```
package/index.ts DELETED
@@ -1,182 +0,0 @@
1
- import type { ExtensionAPI, ProviderConfig } from "@earendil-works/pi-coding-agent";
2
- import type { Api } from "@earendil-works/pi-ai";
3
- import { readCachedModelsSync, writeCachedModels, writeRawResponse } from "./src/plexus-cache.js";
4
- import { getBaseUrl, getBaseUrlSync, getDefaultModel, getModelsUrl, saveBaseUrl } from "./src/plexus-config.js";
5
- import { log } from "./src/plexus-log.js";
6
- import { convertModels, fetchPlexusModels } from "./src/plexus-models.js";
7
- import type { PiModel } from "./src/plexus-models.js";
8
-
9
- const PLEXUS_PROVIDER = "plexus";
10
-
11
- const createProviderConfig = (models: PiModel[], baseUrl: string): ProviderConfig => ({
12
- api: "openai-completions" as Api,
13
- apiKey: "PLEXUS_API_KEY",
14
- authHeader: true,
15
- baseUrl,
16
- models,
17
- });
18
-
19
- // Store current models globally for use by setDefaultModel
20
- let currentModels: PiModel[] = [];
21
-
22
- const attemptLiveRefresh = async (pi: ExtensionAPI, apiKey: string, setDefault = true): Promise<void> => {
23
- const baseUrl = getBaseUrl();
24
- const modelsUrl = getModelsUrl();
25
-
26
- log("attemptLiveRefresh", { hasApiKey: !!apiKey, baseUrl, modelsUrl });
27
-
28
- if (!baseUrl || !modelsUrl) {
29
- log("attemptLiveRefresh: missing baseUrl, skipping");
30
- return;
31
- }
32
-
33
- try {
34
- const { models: apiModels, raw } = await fetchPlexusModels(apiKey, modelsUrl);
35
- const models = convertModels(apiModels, baseUrl);
36
-
37
- log("attemptLiveRefresh: fetched models", { count: models.length, sampleModelBaseUrl: models[0]?.baseUrl });
38
-
39
- await Promise.all([writeCachedModels(models), writeRawResponse(raw)]);
40
- currentModels = models;
41
- pi.registerProvider(PLEXUS_PROVIDER, createProviderConfig(models, baseUrl));
42
- log("attemptLiveRefresh: provider registered");
43
-
44
- // Set default model after registering new provider
45
- if (setDefault) {
46
- await setDefaultModel(pi, models);
47
- }
48
- } catch (error) {
49
- log("attemptLiveRefresh: fetch failed", { error: String(error) });
50
- }
51
- };
52
-
53
- const setDefaultModel = async (pi: ExtensionAPI, models?: PiModel[]): Promise<void> => {
54
- const defaultModelId = getDefaultModel();
55
- if (!defaultModelId) return;
56
-
57
- // Use provided models or fall back to currentModels (set during refresh)
58
- const modelList = models ?? currentModels;
59
- if (!modelList || modelList.length === 0) {
60
- log("setDefaultModel: no models available", { defaultModelId });
61
- return;
62
- }
63
-
64
- log("setDefaultModel: searching for model", {
65
- defaultModelId,
66
- availableModels: modelList.slice(0, 5).map(m => m.id),
67
- });
68
-
69
- // Find model by ID in our list
70
- const model = modelList.find(m => m.id === defaultModelId);
71
-
72
- if (!model) {
73
- log("setDefaultModel: model not found in list", { defaultModelId });
74
- return;
75
- }
76
-
77
- const success = await pi.setModel(model);
78
- log("setDefaultModel", { defaultModelId, success });
79
- };
80
-
81
- export default function plexusExtension(pi: ExtensionAPI) {
82
- const cached = readCachedModelsSync();
83
- const startupBaseUrl = getBaseUrlSync() ?? "http://localhost/v1";
84
- const startupModels = cached?.models ?? [];
85
-
86
- log("startup", {
87
- cachedModelCount: startupModels.length,
88
- startupBaseUrl,
89
- sampleCachedModelBaseUrl: startupModels[0]?.baseUrl,
90
- });
91
-
92
- pi.registerProvider(PLEXUS_PROVIDER, createProviderConfig(startupModels, startupBaseUrl));
93
- currentModels = startupModels;
94
-
95
- pi.on("session_start", async (_event, ctx) => {
96
- const apiKey = await ctx.modelRegistry.authStorage.getApiKey(PLEXUS_PROVIDER);
97
- const baseUrl = getBaseUrl();
98
-
99
- log("session_start", { hasApiKey: !!apiKey, baseUrl });
100
-
101
- if (!apiKey || !baseUrl) {
102
- log("session_start: no auth configured, skipping refresh");
103
- // Still try to set default model even without auth
104
- await setDefaultModel(pi, startupModels);
105
- return;
106
- }
107
-
108
- await attemptLiveRefresh(pi, apiKey, true);
109
- });
110
-
111
- pi.registerCommand("plexus", {
112
- description: "Plexus provider commands: login, refresh",
113
- getArgumentCompletions: () => [
114
- { value: "login", label: "login", description: "Configure Plexus base URL and API key" },
115
- { value: "refresh", label: "refresh", description: "Refresh Plexus models from the API" },
116
- ],
117
- handler: async (args, ctx) => {
118
- const sub = args.trim();
119
-
120
- if (sub === "login") {
121
- const baseUrl = await ctx.ui.input("Plexus base URL", "https://plexus.example.com");
122
- if (!baseUrl) return;
123
-
124
- const apiKey = await ctx.ui.input("Plexus API key");
125
- if (!apiKey) return;
126
-
127
- // Prompt for default model (optional)
128
- const defaultModel = await ctx.ui.input("Default model (optional)", "");
129
- const defaultModelTrimmed = defaultModel?.trim() || undefined;
130
-
131
- await saveBaseUrl(baseUrl.trim(), defaultModelTrimmed);
132
- ctx.modelRegistry.authStorage.set(PLEXUS_PROVIDER, { type: "api_key", key: apiKey.trim() });
133
-
134
- log("login: saved", { baseUrl: baseUrl.trim(), defaultModel: defaultModelTrimmed });
135
- ctx.ui.notify("Plexus credentials saved", "info");
136
-
137
- await attemptLiveRefresh(pi, apiKey.trim(), false);
138
-
139
- // Set default model after refresh (attemptLiveRefresh handles it when setDefault=true)
140
- return;
141
- }
142
-
143
- if (sub === "refresh") {
144
- const apiKey = await ctx.modelRegistry.authStorage.getApiKey(PLEXUS_PROVIDER);
145
- const baseUrl = getBaseUrl();
146
- const modelsUrl = getModelsUrl();
147
-
148
- log("refresh command", { hasApiKey: !!apiKey, baseUrl });
149
-
150
- if (!apiKey) {
151
- ctx.ui.notify("No Plexus API key configured. Run /plexus login first.", "error");
152
- return;
153
- }
154
- if (!baseUrl || !modelsUrl) {
155
- ctx.ui.notify("No Plexus base URL configured. Run /plexus login first.", "error");
156
- return;
157
- }
158
-
159
- try {
160
- ctx.ui.notify("Fetching Plexus models...", "info");
161
- const { models: apiModels, raw } = await fetchPlexusModels(apiKey, modelsUrl);
162
- const models = convertModels(apiModels, baseUrl);
163
-
164
- await Promise.all([writeCachedModels(models), writeRawResponse(raw)]);
165
- pi.registerProvider(PLEXUS_PROVIDER, createProviderConfig(models, baseUrl));
166
-
167
- log("refresh command: done", { count: models.length });
168
- ctx.ui.notify(`Refreshed ${models.length} Plexus models`, "info");
169
-
170
- // Re-apply default model after refresh
171
- await setDefaultModel(pi, currentModels);
172
- } catch (error) {
173
- log("refresh command: failed", { error: String(error) });
174
- ctx.ui.notify(`Refresh failed: ${error instanceof Error ? error.message : String(error)}`, "error");
175
- }
176
- return;
177
- }
178
-
179
- ctx.ui.notify("Usage: /plexus login | /plexus refresh", "info");
180
- },
181
- });
182
- }
package/src/pi-compat.ts DELETED
@@ -1,34 +0,0 @@
1
- /**
2
- * Dual-compat layer: works with both oh-my-pi and upstream pi.
3
- *
4
- * oh-my-pi uses @oh-my-pi/* packages and getAgentDir() returns ~/.omp/agent.
5
- * Upstream pi uses @earendil-works/* packages and getAgentDir() returns ~/.pi/agent.
6
- *
7
- * All path differences are handled automatically by getAgentDir() —
8
- * no hardcoded ~/.pi or ~/.omp paths needed.
9
- */
10
-
11
- // Runtime resolution — try oh-my-pi first, fall back to upstream pi.
12
- // Bun's resolver will only find one of these installed since they conflict.
13
- let _getAgentDir: (() => string) | undefined;
14
- // biome-ignore lint/suspicious/noExplicitAny: getModel/getBundledModel use branded generic types
15
- let _lookupModel: ((...args: any[]) => any) | undefined;
16
-
17
- try {
18
- // @ts-expect-error — optional peer, only present under oh-my-pi
19
- const codingAgent = await import("@oh-my-pi/pi-coding-agent");
20
- _getAgentDir = codingAgent.getAgentDir;
21
- // @ts-expect-error — optional peer, only present under oh-my-pi
22
- const ai = await import("@oh-my-pi/pi-ai");
23
- _lookupModel = ai.getBundledModel; // oh-my-pi name
24
- } catch {
25
- const codingAgent = await import("@earendil-works/pi-coding-agent");
26
- _getAgentDir = codingAgent.getAgentDir;
27
- const ai = await import("@earendil-works/pi-ai");
28
- _lookupModel = ai.getModel; // upstream pi name
29
- }
30
-
31
- // biome-ignore lint/style/noNonNullAssertion: one of the two import paths is guaranteed to succeed
32
- export const getAgentDir = _getAgentDir!;
33
- // biome-ignore lint/style/noNonNullAssertion: one of the two import paths is guaranteed to succeed
34
- export const lookupModel = _lookupModel!;
@@ -1,52 +0,0 @@
1
- import { existsSync, readFileSync } from "node:fs";
2
- import { mkdir, readFile, writeFile } from "node:fs/promises";
3
- import { join } from "node:path";
4
- import { getAgentDir } from "./pi-compat.js";
5
- import type { PlexusApiResponse } from "./plexus-models.js";
6
- import type { PiModel } from "./plexus-models.js";
7
-
8
- const getCacheDir = (): string => join(getAgentDir(), "extensions", "plexus");
9
-
10
- const getModelsCachePath = (): string => join(getCacheDir(), "plexus-models-cache.json");
11
-
12
- const getResponseCachePath = (): string => join(getCacheDir(), "plexus-models-response.json");
13
-
14
- interface ModelCache {
15
- models: PiModel[];
16
- timestamp: number;
17
- }
18
-
19
- export const readCachedModels = async (): Promise<ModelCache | null> => {
20
- try {
21
- const content = await readFile(getModelsCachePath(), "utf8");
22
- const cache = JSON.parse(content) as ModelCache;
23
- if (!Array.isArray(cache.models)) return null;
24
- return cache;
25
- } catch {
26
- return null;
27
- }
28
- };
29
-
30
- export const readCachedModelsSync = (): ModelCache | null => {
31
- try {
32
- const path = getModelsCachePath();
33
- if (!existsSync(path)) return null;
34
- const content = readFileSync(path, "utf8");
35
- const cache = JSON.parse(content) as ModelCache;
36
- if (!Array.isArray(cache.models)) return null;
37
- return cache;
38
- } catch {
39
- return null;
40
- }
41
- };
42
-
43
- export const writeCachedModels = async (models: PiModel[]): Promise<void> => {
44
- const cache: ModelCache = { models, timestamp: Date.now() };
45
- await mkdir(getCacheDir(), { recursive: true });
46
- await writeFile(getModelsCachePath(), `${JSON.stringify(cache, null, 2)}\n`, "utf8");
47
- };
48
-
49
- export const writeRawResponse = async (data: PlexusApiResponse): Promise<void> => {
50
- await mkdir(getCacheDir(), { recursive: true });
51
- await writeFile(getResponseCachePath(), `${JSON.stringify(data, null, 2)}\n`, "utf8");
52
- };
@@ -1,58 +0,0 @@
1
- import { mkdir, writeFile } from "node:fs/promises";
2
- import { existsSync, readFileSync } from "node:fs";
3
- import { join } from "node:path";
4
- import { getAgentDir } from "./pi-compat.js";
5
-
6
- const getConfigDir = (): string => join(getAgentDir(), "extensions", "plexus");
7
- const getConfigPath = (): string => join(getConfigDir(), "config.json");
8
-
9
- interface PlexusConfig {
10
- baseUrl?: string;
11
- defaultModel?: string;
12
- }
13
-
14
- const normalizeRoot = (raw: string): string => raw.replace(/\/+$/, "");
15
-
16
- export const getConfigSync = (): PlexusConfig => {
17
- try {
18
- if (existsSync(getConfigPath())) {
19
- return JSON.parse(readFileSync(getConfigPath(), "utf8")) as PlexusConfig;
20
- }
21
- } catch {}
22
- return {};
23
- };
24
-
25
- export const saveBaseUrl = async (baseUrl: string, defaultModel?: string): Promise<void> => {
26
- await mkdir(getConfigDir(), { recursive: true });
27
- const existing = getConfigSync();
28
- const config: PlexusConfig = {
29
- ...existing,
30
- baseUrl: normalizeRoot(baseUrl),
31
- ...(defaultModel !== undefined && { defaultModel }),
32
- };
33
- await writeFile(getConfigPath(), `${JSON.stringify(config, null, 2)}\n`, "utf8");
34
- };
35
-
36
- export const getRawBaseUrl = (): string | null => {
37
- const config = getConfigSync();
38
- if (config.baseUrl) return config.baseUrl;
39
- return process.env.PLEXUS_BASE_URL ?? null;
40
- };
41
-
42
- export const getModelsUrl = (): string | null => {
43
- const raw = getRawBaseUrl();
44
- return raw ? `${normalizeRoot(raw)}/v1/models` : null;
45
- };
46
-
47
- export const getBaseUrlSync = (): string | null => {
48
- const raw = getRawBaseUrl();
49
- return raw ? `${normalizeRoot(raw)}/v1` : null;
50
- };
51
-
52
- // Alias for backward compatibility
53
- export const getBaseUrl = getBaseUrlSync;
54
-
55
- export const getDefaultModel = (): string | null => {
56
- const config = getConfigSync();
57
- return config.defaultModel ?? null;
58
- };
package/src/plexus-log.ts DELETED
@@ -1,17 +0,0 @@
1
- import { appendFileSync, mkdirSync } from "node:fs";
2
- import { join } from "node:path";
3
- import { getAgentDir } from "./pi-compat.js";
4
-
5
- const getLogPath = (): string => join(getAgentDir(), "extensions", "plexus", "plexus.log");
6
-
7
- const getCacheDir = (): string => join(getAgentDir(), "extensions", "plexus");
8
-
9
- export const log = (message: string, data?: Record<string, unknown>): void => {
10
- try {
11
- mkdirSync(getCacheDir(), { recursive: true });
12
- const line = `${new Date().toISOString()} ${message}${data ? ` ${JSON.stringify(data)}` : ""}\n`;
13
- appendFileSync(getLogPath(), line, "utf8");
14
- } catch {
15
- // never throw from logging
16
- }
17
- };
@@ -1,317 +0,0 @@
1
- import { lookupModel } from "./pi-compat.js";
2
- import type {
3
- Api,
4
- Model,
5
- OpenAICompletionsCompat,
6
- OpenAIResponsesCompat,
7
- AnthropicMessagesCompat,
8
- } from "@earendil-works/pi-ai";
9
-
10
- export interface PlexusModelArchitecture {
11
- modality?: string;
12
- input_modalities?: string[];
13
- output_modalities?: string[];
14
- tokenizer?: string;
15
- instruct_type?: string | null;
16
- }
17
-
18
- export interface PlexusModelPricing {
19
- prompt?: string;
20
- completion?: string;
21
- input_cache_read?: string;
22
- input_cache_write?: string;
23
- }
24
-
25
- export interface PlexusTopProvider {
26
- context_length?: number | null;
27
- max_completion_tokens?: number | null;
28
- is_moderated?: boolean;
29
- }
30
-
31
- export interface PlexusApiModel {
32
- id: string;
33
- object?: string;
34
- created?: number;
35
- owned_by?: string;
36
- preferred_api?: string | string[];
37
- name?: string;
38
- description?: string;
39
- context_length?: number | null;
40
- architecture?: PlexusModelArchitecture;
41
- pricing?: PlexusModelPricing;
42
- supported_parameters?: string[];
43
- top_provider?: PlexusTopProvider;
44
- /** When set, look up the full model definition from pi's MODELS for maximum fidelity. */
45
- pi_provider?: string;
46
- pi_model?: string;
47
- }
48
-
49
- export interface PlexusApiResponse {
50
- object: string;
51
- data: PlexusApiModel[];
52
- }
53
-
54
- export type PiModel = Model<Api>;
55
-
56
- const DEFAULT_CONTEXT_WINDOW = 8192;
57
- const REASONING_PARAMS = new Set(["reasoning", "include_reasoning", "reasoning_effort"]);
58
-
59
- const parsePrice = (value: string | undefined): number => {
60
- if (!value) return 0;
61
- const parsed = parseFloat(value);
62
- return Number.isNaN(parsed) ? 0 : parsed;
63
- };
64
-
65
- const mapPreferredApi = (preferred_api: string | string[] | undefined): Api => {
66
- const SUPPORTED_MAP: Record<string, Api> = {
67
- chat_completions: "openai-completions",
68
- messages: "anthropic-messages",
69
- gemini: "google-generative-ai",
70
- responses: "openai-responses",
71
- };
72
-
73
- if (!preferred_api) return "openai-completions";
74
-
75
- const candidates = Array.isArray(preferred_api) ? preferred_api : [preferred_api];
76
-
77
- for (const candidate of candidates) {
78
- const mapped = SUPPORTED_MAP[candidate];
79
- if (mapped) return mapped;
80
- }
81
-
82
- return "openai-completions";
83
- };
84
-
85
- const mapInputModalities = (architecture: PlexusModelArchitecture | undefined): ("text" | "image")[] => {
86
- const modalities = architecture?.input_modalities ?? [];
87
- const result: ("text" | "image")[] = [];
88
-
89
- if (modalities.includes("text")) result.push("text");
90
- if (modalities.includes("image")) result.push("image");
91
-
92
- return result.length > 0 ? result : ["text"];
93
- };
94
-
95
- const inferReasoning = (supported_parameters: string[] | undefined): boolean => {
96
- if (!supported_parameters) return false;
97
- return supported_parameters.some((p) => REASONING_PARAMS.has(p));
98
- };
99
-
100
- /**
101
- * Attempt to look up a model definition from pi's built-in MODELS registry
102
- * using the pi_provider and pi_model hints from the plexus API.
103
- * Returns null if either hint is missing or the model isn't found.
104
- */
105
- const lookupPiModel = (piProvider?: string, piModel?: string): Model<Api> | null => {
106
- if (!piProvider || !piModel) return null;
107
-
108
- // lookupModel is shimmed to call getModel (upstream) or getBundledModel (oh-my-pi).
109
- // biome-ignore lint/suspicious/noExplicitAny: dynamic string args don't satisfy generic constraints
110
- return (lookupModel as any)(piProvider, piModel) ?? null;
111
- };
112
-
113
- /**
114
- * Detect OpenAI completions compat settings from the provider and baseUrl of a
115
- * pi model definition. This mirrors the internal detectCompat() in pi's
116
- * openai-completions provider so that we can produce a fully-resolved compat
117
- * object for plexus-proxied models.
118
- *
119
- * Without this, providers like deepseek that are proxied through plexus won't
120
- * get the correct implied compat (e.g. supportsDeveloperRole: false) because
121
- * pi's runtime auto-detection checks model.provider and model.baseUrl, which
122
- * are "plexus" and the plexus URL — not the original provider.
123
- */
124
- const detectOpenAICompletionsCompat = (piModel: Model<Api>): OpenAICompletionsCompat => {
125
- const provider = piModel.provider;
126
- const baseUrl = piModel.baseUrl;
127
-
128
- const isZai = provider === "zai" || baseUrl.includes("api.z.ai");
129
- const isMoonshot = provider === "moonshotai" || provider === "moonshotai-cn" || baseUrl.includes("api.moonshot.");
130
- const isCloudflareWorkersAI = provider === "cloudflare-workers-ai" || baseUrl.includes("api.cloudflare.com");
131
- const isCloudflareAiGateway = provider === "cloudflare-ai-gateway" || baseUrl.includes("gateway.ai.cloudflare.com");
132
- const isNonStandard =
133
- provider === "cerebras" ||
134
- baseUrl.includes("cerebras.ai") ||
135
- provider === "xai" ||
136
- baseUrl.includes("api.x.ai") ||
137
- baseUrl.includes("chutes.ai") ||
138
- baseUrl.includes("deepseek.com") ||
139
- isZai ||
140
- isMoonshot ||
141
- provider === "opencode" ||
142
- baseUrl.includes("opencode.ai") ||
143
- isCloudflareWorkersAI ||
144
- isCloudflareAiGateway;
145
- const useMaxTokens = baseUrl.includes("chutes.ai") || isMoonshot || isCloudflareAiGateway;
146
- const isGrok = provider === "xai" || baseUrl.includes("api.x.ai");
147
- const isDeepSeek = provider === "deepseek" || baseUrl.includes("deepseek.com");
148
- const cacheControlFormat = provider === "openrouter" && piModel.id.startsWith("anthropic/") ? "anthropic" : undefined;
149
-
150
- const detected: OpenAICompletionsCompat = {
151
- supportsStore: !isNonStandard,
152
- supportsDeveloperRole: !isNonStandard,
153
- supportsReasoningEffort: !isGrok && !isZai && !isMoonshot && !isCloudflareAiGateway,
154
- supportsUsageInStreaming: true,
155
- maxTokensField: useMaxTokens ? "max_tokens" : "max_completion_tokens",
156
- requiresToolResultName: false,
157
- requiresAssistantAfterToolResult: false,
158
- requiresThinkingAsText: false,
159
- requiresReasoningContentOnAssistantMessages: isDeepSeek,
160
- thinkingFormat: isDeepSeek
161
- ? "deepseek"
162
- : isZai
163
- ? "zai"
164
- : provider === "openrouter" || baseUrl.includes("openrouter.ai")
165
- ? "openrouter"
166
- : "openai",
167
- openRouterRouting: {},
168
- vercelGatewayRouting: {},
169
- zaiToolStream: false,
170
- supportsStrictMode: !isMoonshot && !isCloudflareAiGateway,
171
- cacheControlFormat,
172
- sendSessionAffinityHeaders: false,
173
- supportsLongCacheRetention: !(isCloudflareWorkersAI || isCloudflareAiGateway),
174
- };
175
-
176
- return detected;
177
- };
178
-
179
- /**
180
- * Resolve a fully-specified compat object for a plexus-proxied model by
181
- * merging the pi model's stored compat overrides onto the detected defaults
182
- * from the pi model's original provider/baseUrl.
183
- *
184
- * This produces the same result that pi's getCompat() would compute for the
185
- * original model, ensuring that implied compat fields (like
186
- * supportsDeveloperRole: false for deepseek) are correct even though the
187
- * plexus model has provider="plexus" and a plexus baseUrl.
188
- */
189
- const resolveCompat = (
190
- piModel: Model<Api>,
191
- ): OpenAICompletionsCompat | OpenAIResponsesCompat | AnthropicMessagesCompat | undefined => {
192
- if (piModel.api === "openai-completions") {
193
- const detected = detectOpenAICompletionsCompat(piModel);
194
- const overrides = piModel.compat as OpenAICompletionsCompat | undefined;
195
- if (!overrides) return detected;
196
- return {
197
- supportsStore: overrides.supportsStore ?? detected.supportsStore,
198
- supportsDeveloperRole: overrides.supportsDeveloperRole ?? detected.supportsDeveloperRole,
199
- supportsReasoningEffort: overrides.supportsReasoningEffort ?? detected.supportsReasoningEffort,
200
- supportsUsageInStreaming: overrides.supportsUsageInStreaming ?? detected.supportsUsageInStreaming,
201
- maxTokensField: overrides.maxTokensField ?? detected.maxTokensField,
202
- requiresToolResultName: overrides.requiresToolResultName ?? detected.requiresToolResultName,
203
- requiresAssistantAfterToolResult:
204
- overrides.requiresAssistantAfterToolResult ?? detected.requiresAssistantAfterToolResult,
205
- requiresThinkingAsText: overrides.requiresThinkingAsText ?? detected.requiresThinkingAsText,
206
- requiresReasoningContentOnAssistantMessages:
207
- overrides.requiresReasoningContentOnAssistantMessages ?? detected.requiresReasoningContentOnAssistantMessages,
208
- thinkingFormat: overrides.thinkingFormat ?? detected.thinkingFormat,
209
- openRouterRouting: overrides.openRouterRouting ?? detected.openRouterRouting,
210
- vercelGatewayRouting: overrides.vercelGatewayRouting ?? detected.vercelGatewayRouting,
211
- zaiToolStream: overrides.zaiToolStream ?? detected.zaiToolStream,
212
- supportsStrictMode: overrides.supportsStrictMode ?? detected.supportsStrictMode,
213
- cacheControlFormat: overrides.cacheControlFormat ?? detected.cacheControlFormat,
214
- sendSessionAffinityHeaders: overrides.sendSessionAffinityHeaders ?? detected.sendSessionAffinityHeaders,
215
- supportsLongCacheRetention: overrides.supportsLongCacheRetention ?? detected.supportsLongCacheRetention,
216
- };
217
- }
218
-
219
- // For other APIs, fall back to the stored compat as-is.
220
- // At runtime, pi's provider will still merge with detected defaults,
221
- // but the plexus baseUrl won't match any known provider patterns,
222
- // so defaults are generally safe for anthropic-messages and openai-responses.
223
- return piModel.compat;
224
- };
225
-
226
- const adjustBaseUrl = (baseUrl: string, api: Api): string => {
227
- if (api === "anthropic-messages") {
228
- return baseUrl.replace(/\/v1\/?$/, "");
229
- }
230
- if (api === "google-generative-ai") {
231
- return baseUrl.replace(/\/v1\/?$/, "/v1beta");
232
- }
233
- return baseUrl;
234
- };
235
-
236
- export const convertToPiModel = (apiModel: PlexusApiModel, baseUrl: string): PiModel => {
237
- const piModelDef = lookupPiModel(apiModel.pi_provider, apiModel.pi_model);
238
-
239
- // When pi's MODELS has this model, use its curated definition for maximum fidelity,
240
- // overriding with plexus-specific fields (id, provider, baseUrl, cost from plexus pricing).
241
- if (piModelDef) {
242
- const resolvedCompat = resolveCompat(piModelDef);
243
- return {
244
- id: apiModel.id,
245
- name: apiModel.name ?? piModelDef.name ?? apiModel.id,
246
- api: piModelDef.api,
247
- provider: "plexus",
248
- baseUrl: adjustBaseUrl(baseUrl, piModelDef.api),
249
- reasoning: piModelDef.reasoning,
250
- ...(piModelDef.thinkingLevelMap && { thinkingLevelMap: piModelDef.thinkingLevelMap }),
251
- input: piModelDef.input,
252
- cost: {
253
- input: parsePrice(apiModel.pricing?.prompt) || piModelDef.cost.input,
254
- output: parsePrice(apiModel.pricing?.completion) || piModelDef.cost.output,
255
- cacheRead: parsePrice(apiModel.pricing?.input_cache_read) || piModelDef.cost.cacheRead,
256
- cacheWrite: parsePrice(apiModel.pricing?.input_cache_write) || piModelDef.cost.cacheWrite,
257
- },
258
- contextWindow: piModelDef.contextWindow,
259
- maxTokens: piModelDef.maxTokens,
260
- ...(resolvedCompat && { compat: resolvedCompat }),
261
- };
262
- }
263
-
264
- // No pi MODELS match – fall back to parsing the plexus API fields.
265
- const contextWindow = apiModel.context_length ?? apiModel.top_provider?.context_length ?? DEFAULT_CONTEXT_WINDOW;
266
-
267
- const maxTokens = apiModel.top_provider?.max_completion_tokens ?? contextWindow;
268
- const fallbackApi = mapPreferredApi(apiModel.preferred_api);
269
-
270
- return {
271
- id: apiModel.id,
272
- name: apiModel.name ?? apiModel.id,
273
- api: fallbackApi,
274
- provider: "plexus",
275
- baseUrl: adjustBaseUrl(baseUrl, fallbackApi),
276
- reasoning: inferReasoning(apiModel.supported_parameters),
277
- input: mapInputModalities(apiModel.architecture),
278
- cost: {
279
- input: parsePrice(apiModel.pricing?.prompt),
280
- output: parsePrice(apiModel.pricing?.completion),
281
- cacheRead: parsePrice(apiModel.pricing?.input_cache_read),
282
- cacheWrite: parsePrice(apiModel.pricing?.input_cache_write),
283
- },
284
- contextWindow,
285
- maxTokens,
286
- };
287
- };
288
-
289
- export const fetchPlexusModels = async (
290
- apiKey: string,
291
- modelsUrl: string,
292
- ): Promise<{ models: PlexusApiModel[]; raw: PlexusApiResponse }> => {
293
- const response = await fetch(modelsUrl, {
294
- headers: {
295
- Accept: "application/json",
296
- Authorization: `Bearer ${apiKey}`,
297
- },
298
- });
299
-
300
- if (!response.ok) {
301
- throw new Error(`Plexus API error: ${response.status} ${response.statusText}`);
302
- }
303
-
304
- const raw = (await response.json()) as PlexusApiResponse;
305
- return { models: raw.data ?? [], raw };
306
- };
307
-
308
- export const convertModels = (apiModels: PlexusApiModel[], baseUrl: string): PiModel[] => {
309
- const result: PiModel[] = [];
310
-
311
- for (const apiModel of apiModels) {
312
- if (!apiModel.id) continue;
313
- result.push(convertToPiModel(apiModel, baseUrl));
314
- }
315
-
316
- return result;
317
- };