@mcowger/pi-plexus 1.4.12 → 1.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.
Files changed (3) hide show
  1. package/README.md +29 -163
  2. package/dist/extension.js +68 -200
  3. package/package.json +5 -5
package/README.md CHANGED
@@ -7,13 +7,12 @@ Exposes models from a self-hosted [Plexus](https://github.com/mcowger/plexus) AI
7
7
  | Package | Agent | npm |
8
8
  |---|---|---|
9
9
  | `plexus-pi` | [pi](https://github.com/earendil-works/pi) | `@mcowger/pi-plexus` |
10
- | `plexus-opencode` | [OpenCode](https://opencode.ai) | `@mcowger/opencode-plexus` |
11
10
  | `plexus-oh-my-pi` | [Oh My Pi](https://github.com/can1357/oh-my-pi) | `@mcowger/oh-my-pi-plexus` |
12
11
 
13
12
  ## Prerequisites
14
13
 
15
14
  - A running Plexus instance
16
- - pi 0.81.0 or later (for `plexus-pi`)
15
+ - pi 0.85.1 or later (for `plexus-pi`)
17
16
 
18
17
  ## Installation
19
18
 
@@ -54,38 +53,6 @@ Then register the path in `~/.pi/agent/settings.json`:
54
53
 
55
54
  ---
56
55
 
57
- ### OpenCode
58
-
59
- #### Option 1 — npm (recommended)
60
-
61
- ```sh
62
- npm install -g @mcowger/opencode-plexus
63
- ```
64
-
65
- Then add the plugin to your `opencode.json`:
66
-
67
- ```json
68
- {
69
- "plugins": ["@mcowger/opencode-plexus"]
70
- }
71
- ```
72
-
73
- #### Option 2 — path reference
74
-
75
- ```sh
76
- git clone https://github.com/mcowger/plexus-agent-plugins ~/code/plexus-agent-plugins
77
- ```
78
-
79
- Then reference the built artifact in `opencode.json`:
80
-
81
- ```json
82
- {
83
- "plugins": ["~/code/plexus-agent-plugins/packages/plexus-opencode/dist/index.js"]
84
- }
85
- ```
86
-
87
- ---
88
-
89
56
  ### Oh My Pi
90
57
 
91
58
  Oh My Pi is a fork of pi and is **not** wire-compatible with `plexus-pi` in every respect (different runtime packages, extension manifest field, and built-in model registry — see [AGENTS.md](AGENTS.md)), so it has its own adapter package.
@@ -142,13 +109,14 @@ To force a model refresh:
142
109
  /plexus refresh
143
110
  ```
144
111
 
145
- Select a Plexus model explicitly for the current session. With no model ID, Pi opens a selector; you can also pass the exact Plexus model ID directly. This explicit choice is not applied automatically when starting a new session:
112
+ Inspect the effective URL, authentication availability, and catalog source without exposing a credential:
146
113
 
147
114
  ```
148
- /plexus set-default-model
149
- /plexus set-default-model claude-sonnet-4-5
115
+ /plexus status
150
116
  ```
151
117
 
118
+ Select a Plexus model in `/model`. Save its startup default with the host's normal model-picker action; Plexus does not maintain a separate default-model setting.
119
+
152
120
  Use `/login plexus` for setup and `/logout plexus` to remove stored credentials.
153
121
 
154
122
  ### Oh My Pi
@@ -159,108 +127,32 @@ Run inside Oh My Pi using the native login flow:
159
127
  /login plexus
160
128
  ```
161
129
 
162
- Same prompts and `/plexus refresh` / `/plexus set-default-model` commands as pi (see above) — `plexus-oh-my-pi` mirrors the pi adapter's behavior, adjusted for Oh My Pi's own runtime packages and built-in model registry.
163
-
164
- ### OpenCode
165
-
166
- Run inside OpenCode:
167
-
168
- ```
169
- /connect
170
- ```
171
-
172
- Select **Plexus** and enter your base URL and API key. OpenCode has no live model-discovery hook for custom providers, so the model list is seeded from the on-disk cache at startup. Run `/plexus-refresh` to force a live fetch from Plexus and rewrite the cache, then restart OpenCode to pick up the refreshed list:
173
-
174
- ```
175
- /plexus-refresh
176
- ```
177
-
178
- You may enter either the Plexus root URL or the `/v1` API base URL:
179
-
180
- ```text
181
- https://plexus.example.com
182
- https://plexus.example.com/v1
183
- ```
184
-
185
- The plugins normalize either form to the Plexus root URL for storage and derive `/v1` paths when calling the API.
186
-
187
- OpenCode stores the API key in its native auth store and stores the Plexus base URL as auth metadata on that connection. Existing `provider.plexus.options.plexusBaseURL` config is still honored as a fallback.
188
-
189
- `provider.plexus.options.baseURL` is also accepted as input-only compatibility config. Some external clients read OpenCode config files directly and only recognize `options.baseURL`. The plugin normalizes that value for Plexus discovery and then removes it from OpenCode's in-memory provider options, so individual models keep their own `/v1` or `/v1beta` endpoints instead of being overridden by a provider-wide URL.
190
-
191
- For an OpenChamber-compatible OpenCode config, omit `options.apiKey` and authenticate through `/connect`:
192
-
193
- ```json
194
- {
195
- "provider": {
196
- "plexus": {
197
- "options": {
198
- "baseURL": "https://plexus.example.com/v1"
199
- }
200
- }
201
- }
202
- }
203
- ```
204
-
205
- Then run `/connect`, select **Plexus**, and authenticate against the same Plexus server. A raw unresolved `options.apiKey` value in this file can override the resolved runtime credential used by OpenChamber, including OpenCode `{env:NAME}` templates that OpenChamber does not expand when extra characters follow the template.
206
-
207
- The plugin publishes models with `/v1` endpoints before `/v1beta` models. This ordering helps OpenChamber versions that derive a provider-wide endpoint from the first runtime model; it does not change model endpoints or OpenCode routing. Gemini models still use `/v1beta` through `@ai-sdk/google`.
208
-
209
- The OpenCode plugin respects each model's `preferred_api` value and routes models through the matching SDK/API shape:
210
-
211
- - `chat_completions` / `openai-completions` → OpenAI-compatible chat completions
212
- - `responses` / `openai-responses` → OpenAI Responses API
213
- - `messages` / `anthropic-messages` → Anthropic Messages API
214
- - `gemini` / `google-generative-ai` → Google Gemini API
215
-
216
- You can also pre-configure via environment variables:
217
-
218
- ```sh
219
- export PLEXUS_API_URL=https://plexus.example.com
220
- export PLEXUS_API_KEY=your-api-key
221
- ```
222
-
223
- `PLEXUS_BASE_URL` is also accepted for compatibility; `PLEXUS_API_URL` wins when both are set.
224
-
225
- ---
130
+ Same prompts and `/plexus refresh` / `/plexus status` commands as pi (see above). Save the selected startup model through OMP's normal `/model` or `/models` flow.
226
131
 
227
132
  ## Configuration files
228
133
 
229
- ### pi
230
-
231
- ```
232
- ~/.pi/agent/extensions/plexus/
233
- config.json # base URL and model preference metadata
234
- plexus-models-cache.json # last-fetched model list (startup cache)
235
- plexus-models-response.json # raw API response (diagnostics)
236
- plexus.log # extension activity log
237
- ```
238
-
239
- The API key is stored through pi's own auth storage. `PLEXUS_API_URL` or `PLEXUS_BASE_URL` can be used as an environment override.
134
+ ### Connection state
240
135
 
241
- ### Oh My Pi
136
+ Each adapter stores only non-secret Plexus settings in its own `config.json`:
242
137
 
243
- ```
244
- ~/.omp/agent/extensions/plexus/
245
- config.json # base URL and model preference metadata
246
- plexus-models-cache.json # last-fetched model list (startup cache)
247
- plexus-models-response.json # raw API response (diagnostics)
248
- plexus.log # extension activity log
138
+ ```text
139
+ <agent-dir>/extensions/plexus/config.json # base URL and optional model suppression
249
140
  ```
250
141
 
251
- Same layout as pi, rooted under `~/.omp/agent` instead of `~/.pi/agent` since Oh My Pi resolves its own agent directory.
142
+ Credentials stay in the host credential store (`auth.json` for Pi, `agent.db` for OMP). Model catalogs stay in the host model registry/store. The extension no longer writes a second model cache, ETag file, raw API response, or default-model preference.
252
143
 
253
- ### OpenCode
144
+ At runtime, configuration resolves as follows:
254
145
 
255
- ```
256
- ~/.local/share/opencode/plugins/plexus/
257
- models-cache.json # last-fetched model list (startup cache)
258
- models-raw.json # raw API response (diagnostics)
146
+ ```text
147
+ base URL: PLEXUS_API_URL → PLEXUS_BASE_URL → saved Plexus base URL
148
+ API key: host credential store → PLEXUS_API_KEY process fallback
149
+ catalog: host model store → live Plexus refresh
150
+ startup model: host model-picker preference
259
151
  ```
260
152
 
261
- The API key is stored through OpenCode's auth flow, and the Plexus base URL is stored as auth metadata. `PLEXUS_API_URL`, `PLEXUS_BASE_URL`, and `PLEXUS_API_KEY` can be used as environment overrides.
153
+ `PLEXUS_API_URL` and `PLEXUS_BASE_URL` are process-only URL overrides; `PLEXUS_API_KEY` is a process-only credential fallback. None are persisted. `/plexus status` reports the effective URL source, whether auth is available, and catalog state without exposing credentials.
262
154
 
263
- Both adapters also accept pi-style environment interpolation in configured strings, such as `${PLEXUS_API_URL}` or `$PLEXUS_API_KEY`. This is useful when checking non-secret config into an agent config file while keeping the actual values in the environment.
155
+ Plexus accepts a root URL or a `/v1` API URL. The adapter normalizes that only for the Plexus discovery request. Each model then receives its own API-specific base URL: OpenAI stays on `/v1`, Anthropic uses the root, and Google uses `/v1beta`.
264
156
 
265
157
  ---
266
158
 
@@ -290,19 +182,6 @@ All plugin packages support suppressing models by name or pattern so undesired m
290
182
  }
291
183
  ```
292
184
 
293
- - **OpenCode config**: Add `suppressModels` (or `suppress`) under `provider.plexus.options` in `opencode.json`:
294
- ```json
295
- {
296
- "provider": {
297
- "plexus": {
298
- "options": {
299
- "suppressModels": ["gpt-3.5*", "claude-2*"]
300
- }
301
- }
302
- }
303
- }
304
- ```
305
-
306
185
  ---
307
186
 
308
187
  ## Package layout
@@ -319,29 +198,17 @@ packages/
319
198
  src/
320
199
  extension.ts # entry point: commands, session refresh, auth flow
321
200
  mapper.ts # PlexusModelDescriptor → pi ProviderModelConfig
322
- config.ts # base URL / default model config I/O
323
- cache.ts # model cache I/O
201
+ config.ts # base URL / suppression config I/O
202
+ cache.ts # Pi native model-store restore
324
203
  log.ts # append-only log
325
204
  package.json # declares pi.extensions entry point
326
205
  plexus-oh-my-pi/ # Oh My Pi host adapter (fork of pi; own runtime packages + catalog)
327
206
  src/
328
207
  extension.ts # entry point: commands, session refresh, auth flow
329
208
  mapper.ts # PlexusModelDescriptor → Oh My Pi ProviderModelConfig
330
- config.ts # base URL / default model config I/O
331
- cache.ts # model cache I/O
209
+ config.ts # base URL / suppression config I/O
332
210
  log.ts # append-only log
333
211
  package.json # declares omp.extensions entry point
334
- plexus-opencode/ # OpenCode plugin adapter
335
- src/
336
- plugin.ts # Plugin export: config hook, provider hook, auth handler
337
- mapper.ts # PlexusApiModel → OpenCode ConfigModel
338
- cache.ts # model cache I/O
339
- config-store.ts # resolveConfig, readStoredAuth
340
- log.ts # logger via OpenCode SDK
341
- constants.ts # provider ID, env var names, timeouts
342
- url.ts # URL helpers (trimURL, apiBase, modelsUrl)
343
- index.ts # barrel export
344
- package.json # npm package manifest
345
212
  ```
346
213
 
347
214
  `plexus-models` has zero imports from any agent framework. Each host adapter imports it via a relative path.
@@ -355,9 +222,8 @@ The `/v1/models` endpoint returns an OpenRouter-style list. These fields drive h
355
222
  | `preferred_api` | String or array. First recognized value selects the host API dialect. |
356
223
  | `supported_parameters` | `reasoning`, `include_reasoning`, or `reasoning_effort` enables reasoning support. |
357
224
  | `architecture.input_modalities` | Enables text/image/audio/video/pdf support where the host supports it. |
358
- | `architecture.output_modalities` | Non-text-only output models are filtered from OpenCode chat providers. |
359
225
  | `pricing` | Converted into host per-million-token cost metadata. Plexus returns per-token prices. |
360
- | `pricing.tiers` | Alternate rates above `input_tokens_above`; mapped to native pi and OpenCode context pricing tiers. |
226
+ | `pricing.tiers` | Alternate rates above `input_tokens_above`; mapped to native pi context pricing tiers. |
361
227
  | `top_provider` | Supplies context and output token limits when present. |
362
228
  | `pi_provider` / `pi_model` | Lets the pi adapter reuse built-in pi compat, headers, and thinking-level metadata. |
363
229
  | `pi_options` | pi compat overrides. These win over heuristic and built-in metadata. |
@@ -367,11 +233,7 @@ Models with a falsy `id` are skipped. Missing metadata falls back to safe defaul
367
233
  ## Adapter behavior
368
234
 
369
235
  - **pi** refreshes on session start and through `/plexus refresh`, without changing the model selected for the session. It accepts either root URLs or URLs ending in `/v1` and normalizes them before calling Plexus.
370
- - **OpenCode** seeds the provider from the on-disk cache (or a placeholder model) once, during config loading — OpenCode's `provider.models` hook never fires for custom providers, so there is no live discovery at startup. Run `/plexus-refresh` to force a live fetch and rewrite the cache; because OpenCode has no way to hot-reload a custom provider's model list mid-session, a restart is required afterward to see the refreshed models in the picker.
371
- - OpenCode models retain their upstream model ID, SDK dialect, release date, and reasoning metadata so OpenCode can generate its native GPT, Claude, Gemini, and OpenAI-compatible variants and apply its current request transforms. DeepSeek models also preserve `reasoning_content` across tool-call turns.
372
- - OpenCode uses a 250K-token context window when Plexus supplies no context metadata; its output fallback remains 20% of that window.
373
- - OpenCode moves `/v1beta` models after `/v1` models in published model order. Model endpoints and per-model SDK selection are unchanged.
374
- - Both adapters convert Plexus's per-token base and tier rates to the per-million-token units expected by their host.
236
+ - The active adapters convert Plexus's per-token base and tier rates to the per-million-token units expected by their host.
375
237
 
376
238
  ## Development
377
239
 
@@ -381,6 +243,10 @@ After cloning, install dependencies to set up the pre-commit hook:
381
243
  bun install
382
244
  ```
383
245
 
384
- The pre-commit hook (via lefthook) rebuilds both dist artifacts automatically whenever source files change. After committing, reload/restart your agent.
246
+ The pre-commit hook (via lefthook) rebuilds the active dist artifacts automatically whenever source files change. After committing, reload/restart your agent.
247
+
248
+ ## Archived adapters
249
+
250
+ `packages/deprecated/plexus-opencode` is preserved for reference but is archived. It is private and excluded from builds, tests, hooks, version sync, and publishing. In my testing, OpenCode was notably slower and less token-efficient than pi and Oh My Pi.
385
251
 
386
252
  To add support for a new host agent, see [AGENTS.md](AGENTS.md).
package/dist/extension.js CHANGED
@@ -421,7 +421,7 @@ var normalizeConfigBaseUrl = (raw) => {
421
421
  const root = normalizeRoot(raw);
422
422
  return root.endsWith("/v1") ? root.slice(0, -3) : root;
423
423
  };
424
- var normalizeApiBase = (raw) => {
424
+ var toPlexusApiBase = (raw) => {
425
425
  const root = normalizeConfigBaseUrl(raw);
426
426
  return root ? `${root}/v1` : "";
427
427
  };
@@ -438,39 +438,38 @@ function getConfigSync() {
438
438
  cachedConfig = {};
439
439
  return cachedConfig;
440
440
  }
441
- async function saveBaseUrl(baseUrl, defaultModel) {
441
+ async function saveBaseUrl(baseUrl) {
442
442
  await mkdir(getConfigDir(), { recursive: true });
443
- const existing = getConfigSync();
443
+ const { defaultModel: _defaultModel, ...existing } = getConfigSync();
444
444
  const config = {
445
445
  ...existing,
446
- baseUrl: normalizeConfigBaseUrl(baseUrl),
447
- ...defaultModel !== undefined && { defaultModel }
446
+ baseUrl: normalizeConfigBaseUrl(baseUrl)
448
447
  };
449
448
  await writeFile(getConfigPath(), `${JSON.stringify(config, null, 2)}
450
449
  `, "utf8");
451
450
  cachedConfig = config;
452
451
  }
453
- async function saveDefaultModel(defaultModel) {
454
- await mkdir(getConfigDir(), { recursive: true });
455
- const config = { ...getConfigSync(), defaultModel };
456
- await writeFile(getConfigPath(), `${JSON.stringify(config, null, 2)}
457
- `, "utf8");
458
- cachedConfig = config;
459
- }
460
- function getRawBaseUrl() {
452
+ function getBaseUrlResolution() {
461
453
  const config = getConfigSync();
462
- return resolveStringOption(process.env[ENV_API_URL]) ?? resolveStringOption(process.env[ENV_BASE_URL]) ?? resolveStringOption(config.baseUrl) ?? null;
454
+ const apiUrl = resolveStringOption(process.env[ENV_API_URL]);
455
+ if (apiUrl)
456
+ return { baseUrl: apiUrl, source: ENV_API_URL };
457
+ const baseUrl = resolveStringOption(process.env[ENV_BASE_URL]);
458
+ if (baseUrl)
459
+ return { baseUrl, source: ENV_BASE_URL };
460
+ const saved = resolveStringOption(config.baseUrl);
461
+ return { baseUrl: saved ?? null, source: saved ? "saved" : "none" };
463
462
  }
464
463
  function getEnvApiKey() {
465
464
  return resolveStringOption(process.env[ENV_API_KEY]) ?? null;
466
465
  }
467
466
  function getModelsUrl() {
468
- const raw = getRawBaseUrl();
469
- return raw ? `${normalizeApiBase(raw)}/models` : null;
467
+ const { baseUrl } = getBaseUrlResolution();
468
+ return baseUrl ? `${toPlexusApiBase(baseUrl)}/models` : null;
470
469
  }
471
470
  function getBaseUrl() {
472
- const raw = getRawBaseUrl();
473
- return raw ? normalizeApiBase(raw) : null;
471
+ const { baseUrl } = getBaseUrlResolution();
472
+ return baseUrl ? toPlexusApiBase(baseUrl) : null;
474
473
  }
475
474
  function getSuppressedModels() {
476
475
  const config = getConfigSync();
@@ -480,129 +479,36 @@ function getSuppressedModels() {
480
479
  }
481
480
 
482
481
  // src/cache.ts
483
- import { mkdir as mkdir2, writeFile as writeFile2, readFile } from "fs/promises";
484
482
  import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
485
483
  import { join as join2 } from "path";
486
484
  import { getAgentDir as getAgentDir2 } from "@earendil-works/pi-coding-agent";
487
- var getCacheDir = () => join2(getAgentDir2(), "extensions", "plexus");
488
- var getModelsCachePath = () => join2(getCacheDir(), "plexus-models-cache.json");
489
- var getRawResponsePath = () => join2(getCacheDir(), "plexus-models-response.json");
490
- var getEtagPath = () => join2(getCacheDir(), "plexus-models-etag.txt");
491
- var getModelsStorePath = () => join2(getAgentDir2(), "models-store.json");
492
- function isPlexusModelDescriptor(value) {
493
- if (!value || typeof value !== "object" || Array.isArray(value))
494
- return false;
495
- const model = value;
496
- const cost = model["cost"];
497
- return typeof model["id"] === "string" && typeof model["name"] === "string" && typeof model["preferredApi"] === "string" && model["provider"] === "plexus" && typeof model["baseUrl"] === "string" && typeof model["reasoning"] === "boolean" && Array.isArray(model["input"]) && typeof model["contextWindow"] === "number" && typeof model["maxTokens"] === "number" && !!cost && typeof cost === "object" && !Array.isArray(cost) && typeof cost["input"] === "number" && typeof cost["output"] === "number" && typeof cost["cacheRead"] === "number" && typeof cost["cacheWrite"] === "number";
498
- }
499
- function parseCacheData(raw) {
500
- try {
501
- const parsed = JSON.parse(raw);
502
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
503
- return null;
504
- const obj = parsed;
505
- if (!Array.isArray(obj["models"]) || !obj["models"].every(isPlexusModelDescriptor))
506
- return null;
507
- return {
508
- models: obj["models"],
509
- timestamp: typeof obj["timestamp"] === "number" ? obj["timestamp"] : 0,
510
- etag: typeof obj["etag"] === "string" ? obj["etag"] : undefined
511
- };
512
- } catch {
513
- return null;
514
- }
515
- }
516
- function parseModelsStoreData(raw) {
485
+ function readStoredModelsSync() {
517
486
  try {
518
- const parsed = JSON.parse(raw);
519
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
487
+ const path = join2(getAgentDir2(), "models-store.json");
488
+ if (!existsSync2(path))
520
489
  return null;
521
- const obj = parsed;
522
- const plexusObj = obj["plexus"];
523
- if (!plexusObj)
490
+ const data = JSON.parse(readFileSync2(path, "utf8"));
491
+ const plexus = data["plexus"];
492
+ if (!plexus || typeof plexus !== "object" || Array.isArray(plexus))
524
493
  return null;
525
- let modelsList = null;
526
- let checkedAt = 0;
527
- if (Array.isArray(plexusObj)) {
528
- modelsList = plexusObj;
529
- } else if (typeof plexusObj === "object" && plexusObj !== null) {
530
- const pObj = plexusObj;
531
- if (Array.isArray(pObj["models"])) {
532
- modelsList = pObj["models"];
533
- }
534
- if (typeof pObj["checkedAt"] === "number") {
535
- checkedAt = pObj["checkedAt"];
536
- }
537
- }
538
- if (!modelsList)
494
+ const catalog = plexus;
495
+ if (!Array.isArray(catalog["models"]))
539
496
  return null;
540
497
  return {
541
- piModels: modelsList,
542
- timestamp: checkedAt
498
+ models: catalog["models"],
499
+ checkedAt: typeof catalog["checkedAt"] === "number" ? catalog["checkedAt"] : 0
543
500
  };
544
501
  } catch {
545
502
  return null;
546
503
  }
547
504
  }
548
- function readCachedModelsSync() {
549
- try {
550
- const cachePath = getModelsCachePath();
551
- if (existsSync2(cachePath)) {
552
- const cache = parseCacheData(readFileSync2(cachePath, "utf8"));
553
- if (cache)
554
- return cache;
555
- }
556
- const storePath = getModelsStorePath();
557
- if (existsSync2(storePath)) {
558
- const storeCache = parseModelsStoreData(readFileSync2(storePath, "utf8"));
559
- if (storeCache)
560
- return storeCache;
561
- }
562
- return null;
563
- } catch {
564
- return null;
565
- }
566
- }
567
- async function writeCachedModels(models, etag) {
568
- await mkdir2(getCacheDir(), { recursive: true });
569
- const payload = { models, timestamp: Date.now(), etag };
570
- await writeFile2(getModelsCachePath(), `${JSON.stringify(payload, null, 2)}
571
- `, "utf8");
572
- }
573
- async function writeRawResponse(data) {
574
- await mkdir2(getCacheDir(), { recursive: true });
575
- await writeFile2(getRawResponsePath(), `${JSON.stringify(data, null, 2)}
576
- `, "utf8");
577
- }
578
- async function readCachedEtag() {
579
- try {
580
- const cache = readCachedModelsSync();
581
- if (cache?.etag)
582
- return cache.etag;
583
- const p = getEtagPath();
584
- if (!existsSync2(p))
585
- return;
586
- return (await readFile(p, "utf8")).trim();
587
- } catch {
588
- return;
589
- }
590
- }
591
- async function writeCachedEtag(etag) {
592
- if (!etag)
593
- return;
594
- try {
595
- await mkdir2(getCacheDir(), { recursive: true });
596
- await writeFile2(getEtagPath(), etag, "utf8");
597
- } catch {}
598
- }
599
505
 
600
506
  // src/log.ts
601
- import { mkdir as mkdir3, appendFile } from "fs/promises";
507
+ import { mkdir as mkdir2, appendFile } from "fs/promises";
602
508
  import { join as join3 } from "path";
603
509
  import { getAgentDir as getAgentDir3 } from "@earendil-works/pi-coding-agent";
604
- var getCacheDir2 = () => join3(getAgentDir3(), "extensions", "plexus");
605
- var getLogPath = () => join3(getCacheDir2(), "plexus.log");
510
+ var getCacheDir = () => join3(getAgentDir3(), "extensions", "plexus");
511
+ var getLogPath = () => join3(getCacheDir(), "plexus.log");
606
512
  var dirEnsured = false;
607
513
  function log(message, data) {
608
514
  writeLogLine(message, data);
@@ -610,7 +516,7 @@ function log(message, data) {
610
516
  async function writeLogLine(message, data) {
611
517
  try {
612
518
  if (!dirEnsured) {
613
- await mkdir3(getCacheDir2(), { recursive: true });
519
+ await mkdir2(getCacheDir(), { recursive: true });
614
520
  dirEnsured = true;
615
521
  }
616
522
  const ts = new Date().toISOString();
@@ -680,10 +586,13 @@ function descriptorToPiModel(descriptor) {
680
586
  var MALFORMED_LEAK_PATTERN = /(?:print\()?call:\s*default_api[.:]|default_api\.\w+\s*\(/;
681
587
  var MALFORMED_DIAGNOSTIC_PATTERN = /\bmalformed[\s_-]?function[\s_-]?call\b/i;
682
588
  var TRUNCATED_JSON_PATTERN = /\bUnexpected end of JSON input\b/i;
589
+ var PROVIDER_CONNECTION_CLOSED_PATTERN = /\bprovider connection closed\b/i;
683
590
  var NORMALIZED_PREFIX = "MALFORMED_FUNCTION_CALL:";
684
591
  var TRUNCATED_JSON_PREFIX = "TRUNCATED_JSON_RESPONSE:";
592
+ var PROVIDER_CONNECTION_CLOSED_PREFIX = "PROVIDER_CONNECTION_CLOSED:";
685
593
  var NORMALIZED_MESSAGE = `${NORMALIZED_PREFIX} Gemini emitted a malformed tool call (its internal ` + `function-call syntax leaked as text). This is a transient model failure \u2014 ` + `please retry your request.`;
686
594
  var TRUNCATED_JSON_MESSAGE = `${TRUNCATED_JSON_PREFIX} Unexpected end of JSON input. The upstream provider ` + `returned a truncated JSON response. This is a transient provider failure \u2014 ` + `please retry your request.`;
595
+ var PROVIDER_CONNECTION_CLOSED_MESSAGE = `${PROVIDER_CONNECTION_CLOSED_PREFIX} Provider connection closed. The upstream provider ` + `dropped the request. This is a transient provider failure \u2014 please retry your request.`;
687
596
  function hasLeakedFunctionCall(content) {
688
597
  if (!Array.isArray(content))
689
598
  return false;
@@ -701,7 +610,7 @@ function normalizeMalformedFunctionCall(message, providerName) {
701
610
  if (!message || message.role !== "assistant" || message.provider !== providerName || message.stopReason !== "error") {
702
611
  return;
703
612
  }
704
- if (typeof message.errorMessage === "string" && (message.errorMessage.startsWith(NORMALIZED_PREFIX) || message.errorMessage.startsWith(TRUNCATED_JSON_PREFIX))) {
613
+ if (typeof message.errorMessage === "string" && (message.errorMessage.startsWith(NORMALIZED_PREFIX) || message.errorMessage.startsWith(TRUNCATED_JSON_PREFIX) || message.errorMessage.startsWith(PROVIDER_CONNECTION_CLOSED_PREFIX))) {
705
614
  return;
706
615
  }
707
616
  if (hasToolCall(message.content))
@@ -712,6 +621,12 @@ function normalizeMalformedFunctionCall(message, providerName) {
712
621
  });
713
622
  return { message: { ...message, errorMessage: TRUNCATED_JSON_MESSAGE } };
714
623
  }
624
+ if (typeof message.errorMessage === "string" && PROVIDER_CONNECTION_CLOSED_PATTERN.test(message.errorMessage)) {
625
+ log("retryable-error: retagged closed provider connection for retry", {
626
+ model: message.model
627
+ });
628
+ return { message: { ...message, errorMessage: PROVIDER_CONNECTION_CLOSED_MESSAGE } };
629
+ }
715
630
  const via = hasLeakedFunctionCall(message.content) ? "leak" : typeof message.errorMessage === "string" && MALFORMED_DIAGNOSTIC_PATTERN.test(message.errorMessage) ? "diagnostic" : undefined;
716
631
  if (!via)
717
632
  return;
@@ -728,9 +643,7 @@ var PROVIDER_API_KEY_TEMPLATE = "${PLEXUS_API_KEY}";
728
643
  var PLEXUS_CREDENTIAL_EXPIRES_AT = 253402300799000;
729
644
  var PLACEHOLDER_BASE_URL = "http://localhost/v1";
730
645
  var currentModels = [];
731
- function cachedDescriptorsToPiModels(descriptors, suppressPatterns) {
732
- return descriptors.filter((descriptor) => !isModelSuppressed({ id: descriptor.id, name: descriptor.name }, suppressPatterns)).map(descriptorToPiModel);
733
- }
646
+ var catalogSource = "none";
734
647
  function enforceMinimumOutputTokens(payload) {
735
648
  if (!payload || typeof payload !== "object" || Array.isArray(payload))
736
649
  return payload;
@@ -760,19 +673,15 @@ function plexusExtension(pi) {
760
673
  const envApiKey = getEnvApiKey();
761
674
  const startupBaseUrl = getBaseUrl();
762
675
  const suppressPatterns = getSuppressedModels();
763
- const cached = readCachedModelsSync();
764
- let startupModels = [];
765
- if (cached?.models && cached.models.length > 0) {
766
- startupModels = cachedDescriptorsToPiModels(cached.models, suppressPatterns);
767
- } else if (cached?.piModels && cached.piModels.length > 0) {
768
- startupModels = cached.piModels.filter((m) => !isModelSuppressed({ id: m.id, name: m.name }, suppressPatterns));
769
- }
676
+ const storedCatalog = readStoredModelsSync();
677
+ const startupModels = (storedCatalog?.models ?? []).filter((model) => !isModelSuppressed({ id: model.id, name: model.name }, suppressPatterns));
770
678
  currentModels = startupModels;
679
+ catalogSource = startupModels.length > 0 ? "host store" : "none";
771
680
  pi.on("before_provider_request", (event, ctx) => ctx.model?.provider === PROVIDER_NAME ? enforceMinimumOutputTokens(event.payload) : undefined);
772
681
  log("startup", {
773
682
  baseUrl: startupBaseUrl,
774
683
  hasEnvApiKey: !!envApiKey,
775
- cachedModelCount: startupModels.length
684
+ hostStoredModelCount: startupModels.length
776
685
  });
777
686
  pi.on("message_end", (event) => normalizeMalformedFunctionCall(event.message, PROVIDER_NAME));
778
687
  pi.registerProvider(PROVIDER_NAME, {
@@ -785,38 +694,21 @@ function plexusExtension(pi) {
785
694
  oauth: createPlexusLoginProvider()
786
695
  });
787
696
  pi.registerCommand("plexus", {
788
- description: "Plexus provider commands: refresh, set-default-model (setup: /login plexus)",
697
+ description: "Plexus provider commands: refresh, status (setup: /login plexus)",
789
698
  getArgumentCompletions: (prefix) => {
790
699
  const subcommands = [
791
700
  { value: "refresh", label: "refresh", description: "Refresh Plexus models from the API" },
792
- { value: "set-default-model", label: "set-default-model", description: "Choose the model Pi should use by default" }
701
+ { value: "status", label: "status", description: "Show Plexus configuration and catalog status" }
793
702
  ];
794
- if (!prefix.includes(" ")) {
795
- return subcommands.filter((command) => command.value.startsWith(prefix));
796
- }
797
- const [subcommand, ...rest] = prefix.split(/\s+/);
798
- if (subcommand !== "set-default-model")
799
- return null;
800
- const modelPrefix = rest.join(" ");
801
- const choices = currentModels.map((model) => ({
802
- value: model.id,
803
- label: model.name === model.id ? model.id : `${model.name} (${model.id})`
804
- }));
805
- const filtered = choices.filter((choice) => choice.value.toLowerCase().startsWith(modelPrefix.toLowerCase()));
806
- return filtered.length > 0 ? filtered : null;
703
+ return prefix.includes(" ") ? null : subcommands.filter((command) => command.value.startsWith(prefix));
807
704
  },
808
705
  handler: async (args, ctx) => {
809
- const trimmed = args.trim();
810
- const sub = trimmed.toLowerCase();
811
- if (sub === "refresh" || sub === "") {
812
- await handleRefresh(ctx);
813
- return;
814
- }
815
- if (sub === "set-default-model" || sub.startsWith("set-default-model ")) {
816
- await handleSetDefaultModel(pi, ctx, trimmed.slice("set-default-model".length).trim());
817
- return;
818
- }
819
- ctx.ui.notify(`Unknown sub-command: "${args}". Use /login plexus, /plexus refresh, or /plexus set-default-model.`, "warning");
706
+ const sub = args.trim().toLowerCase();
707
+ if (sub === "refresh" || sub === "")
708
+ return handleRefresh(ctx);
709
+ if (sub === "status")
710
+ return handleStatus(ctx);
711
+ ctx.ui.notify(`Unknown sub-command: "${args}". Use /login plexus, /plexus refresh, or /plexus status.`, "warning");
820
712
  }
821
713
  });
822
714
  }
@@ -841,31 +733,20 @@ async function refreshPlexusModels(context) {
841
733
  return restored;
842
734
  throw new Error(!modelsUrl || !baseUrl ? "Plexus base URL not configured. Run /login plexus first." : "No Plexus API key configured. Run /login plexus first.");
843
735
  }
844
- const storedEtag = await readCachedEtag();
845
736
  try {
846
- const { models: apiModels, raw, etag, notModified } = await fetchPlexusModels(apiKey, modelsUrl, undefined, storedEtag, context.signal);
847
- if (notModified) {
848
- log("refreshModels: not modified", { etag: storedEtag });
849
- const restored = await restoreStoredModels(context);
850
- if (restored)
851
- return restored;
852
- }
737
+ const { models: apiModels } = await fetchPlexusModels(apiKey, modelsUrl, undefined, undefined, context.signal);
853
738
  const descriptors = convertDescriptors(apiModels, baseUrl, suppress);
854
739
  const piModels = descriptors.map(descriptorToPiModel);
855
740
  const published = await context.publish({
856
741
  persist: { models: piModels, checkedAt: Date.now() },
857
742
  update: () => {
858
743
  currentModels = piModels;
744
+ catalogSource = "live refresh";
859
745
  }
860
746
  });
861
747
  if (!published) {
862
748
  log("refreshModels: publication superseded by a newer refresh", {});
863
749
  }
864
- await Promise.all([
865
- writeCachedModels(descriptors, etag),
866
- writeCachedEtag(etag),
867
- raw ? writeRawResponse(raw) : Promise.resolve()
868
- ]);
869
750
  log("refreshModels: fetched", { count: piModels.length });
870
751
  return piModels;
871
752
  } catch (error) {
@@ -882,6 +763,7 @@ async function restoreStoredModels(context) {
882
763
  await context.publish({
883
764
  update: () => {
884
765
  currentModels = models;
766
+ catalogSource = "host store";
885
767
  }
886
768
  });
887
769
  log("refreshModels: restored from store", { count: models.length });
@@ -950,32 +832,18 @@ async function handleRefresh(ctx) {
950
832
  }
951
833
  ctx.ui.notify(currentModels.length > 0 ? `Refreshed ${currentModels.length} Plexus models` : "Refresh finished but no Plexus models are available. Check the Plexus server and /login plexus.", currentModels.length > 0 ? "info" : "warning");
952
834
  }
953
- async function handleSetDefaultModel(pi, ctx, requestedModelId) {
954
- let modelId = requestedModelId;
955
- if (!modelId) {
956
- if (currentModels.length === 0) {
957
- ctx.ui.notify("No Plexus models are available. Run /plexus refresh first.", "warning");
958
- return;
959
- }
960
- const choices = currentModels.map((model) => model.name === model.id ? model.id : `${model.name} (${model.id})`);
961
- const selected = await ctx.ui.select("Select the Plexus default model:", choices);
962
- if (!selected)
963
- return;
964
- const selectedIndex = choices.indexOf(selected);
965
- modelId = currentModels[selectedIndex]?.id ?? "";
966
- }
967
- const model = currentModels.find((candidate) => candidate.id === modelId);
968
- if (!model) {
969
- ctx.ui.notify(`Plexus model not found: "${modelId}". Run /plexus refresh and choose a model from the available list.`, "error");
970
- return;
971
- }
972
- await saveDefaultModel(model.id);
973
- const registryModel = ctx.modelRegistry.find(PROVIDER_NAME, model.id) ?? model;
974
- const active = await pi.setModel(registryModel);
975
- ctx.ui.notify(active ? `Plexus model selected: ${model.id}.` : `Plexus model ${model.id} was saved but could not be selected in this session.`, active ? "info" : "warning");
835
+ async function handleStatus(ctx) {
836
+ const baseUrl = getBaseUrlResolution();
837
+ const apiKey = await ctx.modelRegistry.getApiKeyForProvider(PROVIDER_NAME);
838
+ ctx.ui.notify([
839
+ `Plexus base URL: ${baseUrl.baseUrl ?? "not configured"} (${baseUrl.source})`,
840
+ `API key: ${apiKey ? getEnvApiKey() ? "host credential or PLEXUS_API_KEY fallback" : "host credential" : "not configured"}`,
841
+ `Catalog: ${currentModels.length} models (${catalogSource})`,
842
+ "Default model: managed by Pi. Use /model and save the selection there."
843
+ ].join(`
844
+ `), "info");
976
845
  }
977
846
  export {
978
- cachedDescriptorsToPiModels,
979
847
  plexusExtension as default,
980
848
  enforceMinimumOutputTokens
981
849
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mcowger/pi-plexus",
3
- "version": "1.4.12",
3
+ "version": "1.6.0",
4
4
  "description": "Plexus AI proxy plugin for the pi coding agent",
5
5
  "type": "module",
6
6
  "files": [
@@ -25,12 +25,12 @@
25
25
  "build": "bun run build.ts"
26
26
  },
27
27
  "peerDependencies": {
28
- "@earendil-works/pi-ai": ">=0.84.3",
29
- "@earendil-works/pi-coding-agent": ">=0.84.3"
28
+ "@earendil-works/pi-ai": ">=0.85.1",
29
+ "@earendil-works/pi-coding-agent": ">=0.85.1"
30
30
  },
31
31
  "devDependencies": {
32
- "@earendil-works/pi-ai": "^0.84.3",
33
- "@earendil-works/pi-coding-agent": "^0.84.3",
32
+ "@earendil-works/pi-ai": "^0.85.1",
33
+ "@earendil-works/pi-coding-agent": "^0.85.1",
34
34
  "@types/bun": "latest"
35
35
  },
36
36
  "repository": {