@mcowger/opencode-plexus 1.4.11 → 1.7.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 (4) hide show
  1. package/README.md +63 -153
  2. package/dist/index.js +362 -400
  3. package/package.json +6 -6
  4. package/server.js +1 -0
package/README.md CHANGED
@@ -7,13 +7,14 @@ 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` |
11
+ | `plexus-opencode-v2` | [OpenCode](https://github.com/anomalyco/opencode) V2 | `@mcowger/opencode-plexus` |
12
12
 
13
13
  ## Prerequisites
14
14
 
15
15
  - A running Plexus instance
16
- - pi 0.81.0 or later (for `plexus-pi`)
16
+ - pi 0.85.1 or later (for `plexus-pi`)
17
+ - OpenCode V2 (for `plexus-opencode-v2`)
17
18
 
18
19
  ## Installation
19
20
 
@@ -54,38 +55,6 @@ Then register the path in `~/.pi/agent/settings.json`:
54
55
 
55
56
  ---
56
57
 
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
58
  ### Oh My Pi
90
59
 
91
60
  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.
@@ -119,6 +88,28 @@ Then register the path in `~/.omp/agent/settings.json`:
119
88
  }
120
89
  ```
121
90
 
91
+ ### OpenCode (V2)
92
+
93
+ Add the plugin to `~/.config/opencode/opencode.jsonc`, either from npm or from a local clone (local plugins must point at the package directory, not a file):
94
+
95
+ ```jsonc
96
+ {
97
+ "plugins": ["@mcowger/opencode-plexus"]
98
+ // or: ["file:///home/you/code/plexus-agent-plugins/packages/plexus-opencode-v2"]
99
+ }
100
+ ```
101
+
102
+ If you use `experimental.policies` to restrict providers, policies are last-match-wins — put the `plexus` allow **after** any `"*"` deny:
103
+
104
+ ```jsonc
105
+ "policies": [
106
+ { "action": "provider.use", "resource": "*", "effect": "deny" },
107
+ { "action": "provider.use", "resource": "plexus", "effect": "allow" }
108
+ ]
109
+ ```
110
+
111
+ Restart the service (`opencode service stop && opencode service start`) after changing plugins.
112
+
122
113
  ---
123
114
 
124
115
  ## First-time setup
@@ -142,13 +133,14 @@ To force a model refresh:
142
133
  /plexus refresh
143
134
  ```
144
135
 
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:
136
+ Inspect the effective URL, authentication availability, and catalog source without exposing a credential:
146
137
 
147
138
  ```
148
- /plexus set-default-model
149
- /plexus set-default-model claude-sonnet-4-5
139
+ /plexus status
150
140
  ```
151
141
 
142
+ 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.
143
+
152
144
  Use `/login plexus` for setup and `/logout plexus` to remove stored credentials.
153
145
 
154
146
  ### Oh My Pi
@@ -159,108 +151,44 @@ Run inside Oh My Pi using the native login flow:
159
151
  /login plexus
160
152
  ```
161
153
 
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.
154
+ 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.
163
155
 
164
- ### OpenCode
156
+ ### OpenCode (V2)
165
157
 
166
- Run inside OpenCode:
158
+ Run `/connect` and pick **Plexus**. You will be prompted for the Plexus base URL and API key; models load immediately — no restart needed. Disconnecting, reconnecting, or rotating the key also reloads the model list.
167
159
 
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:
160
+ To force a model refresh:
173
161
 
174
162
  ```
175
163
  /plexus-refresh
176
164
  ```
177
165
 
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
- ---
166
+ `PLEXUS_API_URL` / `PLEXUS_BASE_URL` / `PLEXUS_API_KEY` env vars and plugin options (`plexusBaseURL`, `suppressModels`) are also honored. Until a URL is configured, the provider shows a single `plexus-unconfigured` placeholder. Plugin logs are written to `~/.local/share/opencode/plugins/plexus/plugin.log` (the OpenCode service discards plugin stdout).
226
167
 
227
168
  ## Configuration files
228
169
 
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
- ```
170
+ ### Connection state
238
171
 
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.
172
+ Each adapter stores only non-secret Plexus settings in its own `config.json`:
240
173
 
241
- ### Oh My Pi
242
-
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
174
+ ```text
175
+ <agent-dir>/extensions/plexus/config.json # base URL and optional model suppression
249
176
  ```
250
177
 
251
- Same layout as pi, rooted under `~/.omp/agent` instead of `~/.pi/agent` since Oh My Pi resolves its own agent directory.
178
+ 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
179
 
253
- ### OpenCode
180
+ At runtime, configuration resolves as follows:
254
181
 
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)
182
+ ```text
183
+ base URL: PLEXUS_API_URL → PLEXUS_BASE_URL → saved Plexus base URL
184
+ API key: host credential store → PLEXUS_API_KEY process fallback
185
+ catalog: host model store → live Plexus refresh
186
+ startup model: host model-picker preference
259
187
  ```
260
188
 
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.
189
+ `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
190
 
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.
191
+ 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
192
 
265
193
  ---
266
194
 
@@ -290,19 +218,6 @@ All plugin packages support suppressing models by name or pattern so undesired m
290
218
  }
291
219
  ```
292
220
 
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
221
  ---
307
222
 
308
223
  ## Package layout
@@ -319,29 +234,25 @@ packages/
319
234
  src/
320
235
  extension.ts # entry point: commands, session refresh, auth flow
321
236
  mapper.ts # PlexusModelDescriptor → pi ProviderModelConfig
322
- config.ts # base URL / default model config I/O
323
- cache.ts # model cache I/O
237
+ config.ts # base URL / suppression config I/O
238
+ cache.ts # Pi native model-store restore
324
239
  log.ts # append-only log
325
240
  package.json # declares pi.extensions entry point
326
241
  plexus-oh-my-pi/ # Oh My Pi host adapter (fork of pi; own runtime packages + catalog)
327
242
  src/
328
243
  extension.ts # entry point: commands, session refresh, auth flow
329
244
  mapper.ts # PlexusModelDescriptor → Oh My Pi ProviderModelConfig
330
- config.ts # base URL / default model config I/O
331
- cache.ts # model cache I/O
245
+ config.ts # base URL / suppression config I/O
332
246
  log.ts # append-only log
333
247
  package.json # declares omp.extensions entry point
334
- plexus-opencode/ # OpenCode plugin adapter
248
+ plexus-opencode-v2/ # OpenCode V2 provider plugin
335
249
  src/
336
- plugin.ts # Plugin export: config hook, provider hook, auth handler
337
- mapper.ts # PlexusApiModel → OpenCode ConfigModel
250
+ plugin.ts # entry point: provider/integration transforms, /plexus-refresh, credential watcher
251
+ mapper.ts # PlexusModelDescriptor → OpenCode Model.Info
252
+ config-store.ts # base URL / API key / suppression resolution
338
253
  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
254
+ log.ts # console + file log
255
+ server.js # root entrypoint required by OpenCode for directory plugins
345
256
  ```
346
257
 
347
258
  `plexus-models` has zero imports from any agent framework. Each host adapter imports it via a relative path.
@@ -355,9 +266,8 @@ The `/v1/models` endpoint returns an OpenRouter-style list. These fields drive h
355
266
  | `preferred_api` | String or array. First recognized value selects the host API dialect. |
356
267
  | `supported_parameters` | `reasoning`, `include_reasoning`, or `reasoning_effort` enables reasoning support. |
357
268
  | `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
269
  | `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. |
270
+ | `pricing.tiers` | Alternate rates above `input_tokens_above`; mapped to native pi context pricing tiers. |
361
271
  | `top_provider` | Supplies context and output token limits when present. |
362
272
  | `pi_provider` / `pi_model` | Lets the pi adapter reuse built-in pi compat, headers, and thinking-level metadata. |
363
273
  | `pi_options` | pi compat overrides. These win over heuristic and built-in metadata. |
@@ -367,11 +277,7 @@ Models with a falsy `id` are skipped. Missing metadata falls back to safe defaul
367
277
  ## Adapter behavior
368
278
 
369
279
  - **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.
280
+ - The active adapters convert Plexus's per-token base and tier rates to the per-million-token units expected by their host.
375
281
 
376
282
  ## Development
377
283
 
@@ -381,6 +287,10 @@ After cloning, install dependencies to set up the pre-commit hook:
381
287
  bun install
382
288
  ```
383
289
 
384
- The pre-commit hook (via lefthook) rebuilds both dist artifacts automatically whenever source files change. After committing, reload/restart your agent.
290
+ The pre-commit hook (via lefthook) rebuilds the active dist artifacts automatically whenever source files change. After committing, reload/restart your agent.
291
+
292
+ ## Archived adapters
293
+
294
+ `packages/deprecated/plexus-opencode` (the OpenCode V1 adapter) is preserved for reference but is archived. It is private and excluded from builds, tests, hooks, version sync, and publishing. It is superseded by `plexus-opencode-v2`.
385
295
 
386
296
  To add support for a new host agent, see [AGENTS.md](AGENTS.md).
package/dist/index.js CHANGED
@@ -1,24 +1,6 @@
1
1
  // @bun
2
- // src/constants.ts
3
- var PLEXUS_PROVIDER_ID = "plexus";
4
- var PLEXUS_PROVIDER_NAME = "Plexus";
5
- var PLEXUS_PLUGIN_ID = "@mcowger/opencode-plexus";
6
- var PLEXUS_LOG_SERVICE = "opencode-plexus";
7
- var OPENAI_COMPATIBLE_NPM = "@ai-sdk/openai-compatible";
8
- var PLEXUS_BASE_URL_OPTION = "plexusBaseURL";
9
- var ENV_BASE_URL = "PLEXUS_BASE_URL";
10
- var ENV_API_URL = "PLEXUS_API_URL";
11
- var ENV_API_KEY = "PLEXUS_API_KEY";
12
- var ENV_SUPPRESS_MODELS = "PLEXUS_SUPPRESS_MODELS";
13
- var ENV_SUPPRESSED_MODELS = "PLEXUS_SUPPRESSED_MODELS";
14
- var ENV_EXCLUDE_MODELS = "PLEXUS_EXCLUDE_MODELS";
15
- var ENV_IGNORE_MODELS = "PLEXUS_IGNORE_MODELS";
16
- var PLEXUS_SUPPRESS_MODELS_OPTION = "suppressModels";
17
- var MODELS_FETCH_TIMEOUT_MS = 1e4;
18
- var REFRESH_TTL_MS = 60000;
19
- var CONFIG_HOOK_REFRESH_BUDGET_MS = 3000;
20
- var PLACEHOLDER_MODEL_ID = "plexus-unconfigured";
21
- var PLEXUS_REFRESH_COMMAND = "plexus-refresh";
2
+ // src/plugin.ts
3
+ import { Plugin, Provider } from "@opencode/plugin";
22
4
 
23
5
  // ../plexus-models/src/suppress.ts
24
6
  function parseSuppressionPatterns(raw) {
@@ -107,6 +89,8 @@ function adjustBaseUrl(baseUrl, preferredApi, anthropicBaseStyle = "root") {
107
89
  function isChatModel(model) {
108
90
  if (!model.id)
109
91
  return false;
92
+ if (model.type !== undefined && model.type !== "text")
93
+ return false;
110
94
  const inputModalities = model.architecture?.input_modalities;
111
95
  if (inputModalities !== undefined && inputModalities.length > 0 && !inputModalities.includes("text")) {
112
96
  return false;
@@ -168,34 +152,31 @@ import { mkdir, readFile, writeFile } from "fs/promises";
168
152
  import { homedir } from "os";
169
153
  import { join } from "path";
170
154
  var PLUGIN_SUBDIR = join("plugins", "plexus");
171
- var CACHE_FILE = "models-cache.json";
155
+ var CACHE_FILE = "models-cache-v2.json";
172
156
  var RAW_FILE = "models-raw.json";
173
- function fallbackDir() {
174
- return join(homedir(), ".local", "share", "opencode", PLUGIN_SUBDIR);
175
- }
176
157
  function getDir() {
177
- return fallbackDir();
158
+ const dataHome = process.env.XDG_DATA_HOME || join(homedir(), ".local", "share");
159
+ return join(dataHome, "opencode", PLUGIN_SUBDIR);
178
160
  }
179
161
  function filterCachedModels(models, suppress) {
180
- return Object.fromEntries(Object.entries(models).filter(([, model]) => {
162
+ return models.filter((model) => {
181
163
  if (isModelSuppressed({ id: model.id, name: model.name }, suppress))
182
164
  return false;
183
165
  return isChatModel({
184
166
  id: model.id,
185
167
  name: model.name,
186
168
  architecture: {
187
- input_modalities: model.modalities.input,
188
- output_modalities: model.modalities.output
169
+ input_modalities: model.capabilities.input,
170
+ output_modalities: model.capabilities.output
189
171
  }
190
172
  });
191
- }));
173
+ });
192
174
  }
193
- async function readCachedModels(_client, suppress) {
175
+ async function readCachedModels(suppress) {
194
176
  try {
195
- const dir = getDir();
196
- const content = await readFile(join(dir, CACHE_FILE), "utf8");
177
+ const content = await readFile(join(getDir(), CACHE_FILE), "utf8");
197
178
  const parsed = JSON.parse(content);
198
- if (parsed && typeof parsed.models === "object" && !Array.isArray(parsed.models)) {
179
+ if (parsed && Array.isArray(parsed.models)) {
199
180
  return {
200
181
  models: filterCachedModels(parsed.models, suppress),
201
182
  etag: typeof parsed.etag === "string" ? parsed.etag : undefined
@@ -206,7 +187,7 @@ async function readCachedModels(_client, suppress) {
206
187
  return null;
207
188
  }
208
189
  }
209
- async function writeCache(_client, models, raw, etag) {
190
+ async function writeCache(models, raw, etag) {
210
191
  try {
211
192
  const dir = getDir();
212
193
  await mkdir(dir, { recursive: true });
@@ -220,10 +201,23 @@ async function writeCache(_client, models, raw, etag) {
220
201
  } catch {}
221
202
  }
222
203
 
223
- // src/config-store.ts
224
- import { readFile as readFile2 } from "fs/promises";
225
- import { homedir as homedir2 } from "os";
226
- import { join as join2 } from "path";
204
+ // src/constants.ts
205
+ var PLEXUS_PROVIDER_ID = "plexus";
206
+ var PLEXUS_PROVIDER_NAME = "Plexus";
207
+ var PLEXUS_PLUGIN_ID = "@mcowger/opencode-plexus";
208
+ var PLEXUS_INTEGRATION_ID = "plexus";
209
+ var OPENAI_COMPATIBLE_PKG = "aisdk:@ai-sdk/openai-compatible";
210
+ var ANTHROPIC_PKG = "aisdk:@ai-sdk/anthropic";
211
+ var GOOGLE_PKG = "aisdk:@ai-sdk/google";
212
+ var PLEXUS_BASE_URL_OPTION = "plexusBaseURL";
213
+ var ENV_BASE_URL = "PLEXUS_BASE_URL";
214
+ var ENV_API_URL = "PLEXUS_API_URL";
215
+ var ENV_API_KEY = "PLEXUS_API_KEY";
216
+ var PLEXUS_SUPPRESS_MODELS_OPTION = "suppressModels";
217
+ var MODELS_FETCH_TIMEOUT_MS = 1e4;
218
+ var REFRESH_TTL_MS = 60000;
219
+ var PLACEHOLDER_MODEL_ID = "plexus-unconfigured";
220
+ var PLEXUS_REFRESH_COMMAND = "plexus-refresh";
227
221
 
228
222
  // src/url.ts
229
223
  function trimURL(s) {
@@ -249,22 +243,6 @@ function modelsUrl(baseURL) {
249
243
  // src/config-store.ts
250
244
  var ENV_VAR_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
251
245
  var ENV_VAR_NAME_PREFIX_RE = /^[A-Za-z_][A-Za-z0-9_]*/;
252
- var AUTH_METADATA_BASE_URL = "plexusBaseURL";
253
- async function readStoredAuth() {
254
- const dataHome = process.env.XDG_DATA_HOME || join2(homedir2(), ".local", "share");
255
- const file = join2(dataHome, "opencode", "auth.json");
256
- try {
257
- const content = await readFile2(file, "utf8");
258
- const parsed = JSON.parse(content);
259
- const entry = parsed[PLEXUS_PROVIDER_ID];
260
- if (typeof entry === "object" && entry !== null && entry.type === "api" && typeof entry.key === "string") {
261
- return entry;
262
- }
263
- return;
264
- } catch {
265
- return;
266
- }
267
- }
268
246
  function resolveConfigTemplate(value) {
269
247
  let result = "";
270
248
  let index = 0;
@@ -321,37 +299,55 @@ function resolveStringOption(value) {
321
299
  const resolved = resolveConfigTemplate(value)?.trim();
322
300
  return resolved || undefined;
323
301
  }
324
- function resolveConfig(provider, authMetadata) {
302
+ function metadataBaseURL(credential) {
303
+ if (!credential)
304
+ return;
305
+ const fromMetadata = resolveStringOption(credential.metadata?.[PLEXUS_BASE_URL_OPTION]);
306
+ if (fromMetadata)
307
+ return fromMetadata;
308
+ const rawConfig = credential.configuration?.[PLEXUS_BASE_URL_OPTION];
309
+ return typeof rawConfig === "string" ? resolveStringOption(rawConfig) : undefined;
310
+ }
311
+ function resolveConfig(options, credential) {
325
312
  const envBaseURL = process.env[ENV_API_URL] ?? process.env[ENV_BASE_URL];
326
313
  const envApiKey = process.env[ENV_API_KEY];
327
- const authBaseURL = resolveStringOption(authMetadata?.[AUTH_METADATA_BASE_URL]);
328
- const optBaseURL = resolveStringOption(provider?.options?.[PLEXUS_BASE_URL_OPTION]);
329
- const legacyBaseURL = resolveStringOption(provider?.options?.baseURL);
330
- const optApiKey = resolveStringOption(provider?.options?.apiKey);
331
- const optSuppress = provider?.options?.["suppressModels"] ?? provider?.options?.["suppress"] ?? provider?.options?.["suppress_models"];
332
- const envSuppress = getEnvSuppressedModels();
333
- const configSuppress = parseSuppressionPatterns(optSuppress);
334
- const suppressModels = [...envSuppress, ...configSuppress];
335
- const baseURL = (envBaseURL ? rootURL(envBaseURL) : undefined) || (authBaseURL ? rootURL(authBaseURL) : undefined) || (optBaseURL ? rootURL(optBaseURL) : undefined) || (legacyBaseURL ? rootURL(legacyBaseURL) : undefined) || undefined;
336
- const apiKey = (envApiKey ? envApiKey.trim() : undefined) || optApiKey || undefined;
314
+ const metaBaseURL = credential ? metadataBaseURL(credential) : undefined;
315
+ const optBaseURL = resolveStringOption(options?.[PLEXUS_BASE_URL_OPTION]);
316
+ const optApiKey = resolveStringOption(options?.["apiKey"]);
317
+ const baseURL = (envBaseURL ? rootURL(envBaseURL) : undefined) || (metaBaseURL ? rootURL(metaBaseURL) : undefined) || (optBaseURL ? rootURL(optBaseURL) : undefined) || undefined;
318
+ const apiKey = (envApiKey ? envApiKey.trim() : undefined) || credential?.key?.trim() || optApiKey || undefined;
337
319
  return {
338
320
  baseURL: baseURL || undefined,
339
- apiKey: apiKey || undefined,
340
- ...suppressModels.length > 0 ? { suppressModels } : {}
321
+ apiKey: apiKey || undefined
341
322
  };
342
323
  }
343
- function getSuppressedModels(provider) {
324
+ function getSuppressedModels(options) {
344
325
  const envSuppressed = getEnvSuppressedModels();
345
- const providerObj = provider ?? {};
346
- const providerOptions = typeof providerObj["options"] === "object" && providerObj["options"] !== null ? providerObj["options"] : {};
347
- const optSuppressed = parseSuppressionPatterns(providerOptions["suppressModels"] ?? providerOptions["suppress"] ?? providerObj["suppressModels"] ?? providerObj["suppress"]);
326
+ const opt = options?.["suppressModels"] ?? options?.["suppress"] ?? options?.["suppress_models"];
327
+ const optSuppressed = parseSuppressionPatterns(opt);
348
328
  return [...envSuppressed, ...optSuppressed];
349
329
  }
350
330
 
351
331
  // src/log.ts
352
- function createLogger(client) {
332
+ import { appendFileSync, mkdirSync } from "fs";
333
+ import { join as join2 } from "path";
334
+ function createLogger(prefix = "plexus") {
353
335
  function log(level, message) {
354
- client.app.log({ body: { service: PLEXUS_LOG_SERVICE, level, message } }).catch(() => {});
336
+ const line = `[${prefix}] ${message}`;
337
+ try {
338
+ if (level === "error")
339
+ console.error(line);
340
+ else if (level === "warn")
341
+ console.warn(line);
342
+ else
343
+ console.log(line);
344
+ } catch {}
345
+ try {
346
+ const dir = getDir();
347
+ mkdirSync(dir, { recursive: true });
348
+ appendFileSync(join2(dir, "plugin.log"), `${new Date().toISOString()} ${level.toUpperCase()} ${message}
349
+ `);
350
+ } catch {}
355
351
  }
356
352
  return {
357
353
  info: (message) => log("info", message),
@@ -384,27 +380,26 @@ function buildReasoningVariants(model, preferredApi, hasReasoning) {
384
380
  const effortOption = model.reasoning_options?.find((option) => option.type === "effort");
385
381
  if (!effortOption)
386
382
  return;
387
- return Object.fromEntries(effortOption.values.map((value) => {
383
+ return effortOption.values.map((value) => {
388
384
  const effort = normalizeReasoningEffort(value);
389
- return [effort, reasoningVariantSettings(preferredApi, effort)];
390
- }));
385
+ return { id: effort, settings: reasoningVariantSettings(preferredApi, effort) };
386
+ });
391
387
  }
392
- function resolveModelProvider(model, baseURL) {
393
- const preferredApi = mapPreferredApi(model.preferred_api);
394
- const api = adjustBaseUrl(baseURL, preferredApi, "versioned");
388
+ function resolveModelPackage(preferredApi) {
395
389
  switch (preferredApi) {
396
390
  case "anthropic-messages":
397
- return { npm: "@ai-sdk/anthropic", api };
391
+ return ANTHROPIC_PKG;
398
392
  case "google-generative-ai":
399
- return { npm: "@ai-sdk/google", api };
400
- case "openai-responses":
401
- return { npm: "@ai-sdk/openai", api };
393
+ return GOOGLE_PKG;
402
394
  case "openai-completions":
403
- return { api };
395
+ case "openai-responses":
404
396
  default:
405
- return { api };
397
+ return;
406
398
  }
407
399
  }
400
+ function resolveModelBaseURL(preferredApi, apiBaseURL) {
401
+ return adjustBaseUrl(apiBaseURL, preferredApi, "versioned");
402
+ }
408
403
  function parsePrice(value) {
409
404
  if (!value)
410
405
  return 0;
@@ -418,13 +413,15 @@ function buildPricingTiers(model) {
418
413
  const tiers = pricing.tiers.flatMap((tier) => {
419
414
  if (!Number.isFinite(tier.input_tokens_above) || tier.input_tokens_above < 0)
420
415
  return [];
421
- return [{
422
- inputTokensAbove: tier.input_tokens_above,
423
- input: parsePrice(tier.prompt ?? pricing.prompt),
424
- output: parsePrice(tier.completion ?? pricing.completion),
425
- cacheRead: parsePrice(tier.input_cache_read ?? pricing.input_cache_read),
426
- cacheWrite: parsePrice(tier.input_cache_write ?? pricing.input_cache_write)
427
- }];
416
+ return [
417
+ {
418
+ inputTokensAbove: tier.input_tokens_above,
419
+ input: parsePrice(tier.prompt ?? pricing.prompt),
420
+ output: parsePrice(tier.completion ?? pricing.completion),
421
+ cacheRead: parsePrice(tier.input_cache_read ?? pricing.input_cache_read),
422
+ cacheWrite: parsePrice(tier.input_cache_write ?? pricing.input_cache_write)
423
+ }
424
+ ];
428
425
  });
429
426
  return tiers.length > 0 ? tiers : undefined;
430
427
  }
@@ -445,15 +442,14 @@ function mapModality(m) {
445
442
  return null;
446
443
  }
447
444
  }
448
- function releaseDate(created) {
445
+ function releaseTime(created) {
449
446
  if (typeof created !== "number" || !Number.isFinite(created) || created <= 0)
450
- return;
451
- const date = new Date(created * 1000);
452
- return Number.isNaN(date.getTime()) ? undefined : date.toISOString().slice(0, 10);
447
+ return 0;
448
+ return Math.floor(created * 1000);
453
449
  }
454
- function interleavedReasoning(model, preferredApi) {
450
+ function reasoningCompatibility(model, preferredApi) {
455
451
  if (preferredApi === "openai-completions" && model.id.toLowerCase().includes("deepseek")) {
456
- return { field: "reasoning_content" };
452
+ return { reasoningField: "reasoning_content" };
457
453
  }
458
454
  return;
459
455
  }
@@ -475,19 +471,22 @@ function buildOutputModalities(model) {
475
471
  function orderModelsByApiBase(models) {
476
472
  const current = [];
477
473
  const beta = [];
478
- for (const entry of Object.entries(models)) {
479
- const api = (entry[1].provider?.api ?? entry[1].api?.url ?? "").trim().replace(/\/+$/, "");
480
- if (api.endsWith("/v1beta")) {
481
- beta.push(entry);
482
- } else {
483
- current.push(entry);
484
- }
474
+ for (const model of models) {
475
+ const api = (model.settings?.baseURL ?? "").trim().replace(/\/+$/, "");
476
+ if (api.endsWith("/v1beta"))
477
+ beta.push(model);
478
+ else
479
+ current.push(model);
485
480
  }
486
- return Object.fromEntries([...current, ...beta]);
481
+ return [...current, ...beta];
487
482
  }
488
- function buildModels(models, baseURL, suppress) {
489
- const result = {};
483
+ function buildModels(models, apiBaseURL, suppress) {
484
+ const result = [];
490
485
  for (const m of models) {
486
+ if (!m.id || typeof m.id !== "string")
487
+ continue;
488
+ if (m.id.includes("/"))
489
+ continue;
491
490
  if (!isChatModel(m))
492
491
  continue;
493
492
  if (isModelSuppressed(m, suppress))
@@ -503,162 +502,119 @@ function buildModels(models, baseURL, suppress) {
503
502
  const completionPrice = parsePrice(m.pricing?.completion);
504
503
  const cacheReadPrice = parsePrice(m.pricing?.input_cache_read);
505
504
  const cacheWritePrice = parsePrice(m.pricing?.input_cache_write);
506
- const hasCachePricing = cacheReadPrice > 0 || cacheWritePrice > 0;
507
505
  const pricingTiers = buildPricingTiers(m);
508
- const hasNonTextInput = inputModalities.some((mod) => mod !== "text");
509
506
  const preferredApi = mapPreferredApi(m.preferred_api);
510
- const provider = resolveModelProvider(m, baseURL);
511
- const created = releaseDate(m.created);
512
- const interleaved = interleavedReasoning(m, preferredApi);
507
+ const pkg = resolveModelPackage(preferredApi);
508
+ const compatibility = reasoningCompatibility(m, preferredApi);
513
509
  const hasReasoning = params.some((p) => REASONING_PARAMS2.has(p));
514
510
  const variants = buildReasoningVariants(m, preferredApi, hasReasoning);
515
- const entry = {
511
+ const cost = [];
512
+ if (promptPrice > 0 || completionPrice > 0) {
513
+ cost.push({
514
+ input: promptPrice,
515
+ output: completionPrice,
516
+ cache: { read: cacheReadPrice, write: cacheWritePrice }
517
+ });
518
+ }
519
+ for (const tier of pricingTiers ?? []) {
520
+ cost.push({
521
+ tier: { type: "context", size: tier.inputTokensAbove },
522
+ input: tier.input,
523
+ output: tier.output,
524
+ cache: { read: tier.cacheRead, write: tier.cacheWrite }
525
+ });
526
+ }
527
+ result.push({
516
528
  id: m.id,
529
+ modelID: m.id,
530
+ providerID: "plexus",
517
531
  name: m.name ?? m.id,
518
- provider,
519
- limit: {
520
- context: contextLength,
521
- output: maxOutput
522
- },
523
- modalities: {
532
+ ...compatibility ? { compatibility } : {},
533
+ ...pkg ? { package: pkg } : {},
534
+ settings: { baseURL: resolveModelBaseURL(preferredApi, apiBaseURL) },
535
+ capabilities: {
536
+ tools: params.includes("tools"),
524
537
  input: inputModalities,
525
538
  output: outputModalities
526
539
  },
527
- ...promptPrice > 0 || completionPrice > 0 ? {
528
- cost: {
529
- input: promptPrice,
530
- output: completionPrice,
531
- ...hasCachePricing ? { cache_read: cacheReadPrice, cache_write: cacheWritePrice } : {}
532
- }
533
- } : {},
534
- ...params.includes("tools") ? { tool_call: true } : {},
535
- ...hasReasoning ? { reasoning: true } : {},
536
- ...params.includes("temperature") ? { temperature: true } : {},
537
- ...hasNonTextInput ? { attachment: true } : {},
538
- ...pricingTiers ? { pricingTiers } : {},
539
- ...created ? { release_date: created } : {},
540
- ...interleaved ? { interleaved } : {},
541
- ...variants ? { variants } : {}
542
- };
543
- result[m.id] = entry;
540
+ variants: variants ?? [],
541
+ time: { released: releaseTime(m.created) },
542
+ cost,
543
+ status: "active",
544
+ enabled: true,
545
+ limit: {
546
+ context: contextLength,
547
+ output: maxOutput
548
+ }
549
+ });
544
550
  }
545
551
  return orderModelsByApiBase(result);
546
552
  }
553
+ function placeholderModel() {
554
+ return {
555
+ id: "plexus-unconfigured",
556
+ modelID: "plexus-unconfigured",
557
+ providerID: "plexus",
558
+ name: "Plexus (run /connect to configure)",
559
+ settings: {},
560
+ capabilities: { tools: false, input: ["text"], output: ["text"] },
561
+ variants: [],
562
+ time: { released: 0 },
563
+ cost: [],
564
+ status: "active",
565
+ enabled: true,
566
+ limit: { context: 1024, output: 1024 }
567
+ };
568
+ }
547
569
 
548
570
  // src/plugin.ts
549
571
  var lastRefresh = null;
550
572
  var inFlightRefresh = null;
551
- function toRuntimeCapabilities(model) {
552
- const input = new Set(model.modalities.input);
553
- const output = new Set(model.modalities.output);
554
- return {
555
- temperature: model.temperature ?? false,
556
- reasoning: model.reasoning ?? false,
557
- attachment: model.attachment ?? false,
558
- toolcall: model.tool_call ?? false,
559
- input: {
560
- text: input.has("text"),
561
- audio: input.has("audio"),
562
- image: input.has("image"),
563
- video: input.has("video"),
564
- pdf: input.has("pdf")
565
- },
566
- output: {
567
- text: output.has("text"),
568
- audio: output.has("audio"),
569
- image: output.has("image"),
570
- video: output.has("video"),
571
- pdf: output.has("pdf")
572
- },
573
- interleaved: model.interleaved ?? false
574
- };
573
+ function toModelInfo(models) {
574
+ return models;
575
575
  }
576
- function toRuntimeModels(models, provider) {
577
- const result = {};
578
- const providerNpm = typeof provider.options?.["npm"] === "string" ? provider.options["npm"] : OPENAI_COMPATIBLE_NPM;
579
- const providerApi = typeof provider.options?.[PLEXUS_BASE_URL_OPTION] === "string" ? apiBase(provider.options[PLEXUS_BASE_URL_OPTION]) : "";
580
- for (const [id, model] of Object.entries(models)) {
581
- result[id] = {
582
- id: model.id,
583
- providerID: provider.id,
584
- api: {
585
- id: model.id,
586
- url: model.provider?.api ?? providerApi,
587
- npm: model.provider?.npm ?? providerNpm
588
- },
589
- name: model.name,
590
- capabilities: toRuntimeCapabilities(model),
591
- cost: {
592
- input: model.cost?.input ?? 0,
593
- output: model.cost?.output ?? 0,
594
- cache: {
595
- read: model.cost?.cache_read ?? 0,
596
- write: model.cost?.cache_write ?? 0
597
- },
598
- ...model.pricingTiers ? {
599
- tiers: model.pricingTiers.map((tier) => ({
600
- input: tier.input,
601
- output: tier.output,
602
- cache: { read: tier.cacheRead, write: tier.cacheWrite },
603
- tier: { type: "context", size: tier.inputTokensAbove }
604
- }))
605
- } : {}
606
- },
607
- limit: model.limit,
608
- status: "active",
609
- options: {},
610
- headers: {},
611
- release_date: model.release_date ?? "",
612
- ...model.variants ? { variants: model.variants } : {}
576
+ async function resolveConnectionCredential(ctx, log) {
577
+ try {
578
+ const connection = await ctx.integration.connection.active(PLEXUS_INTEGRATION_ID);
579
+ if (!connection)
580
+ return { connection: undefined, credential: undefined };
581
+ const resolved = await ctx.integration.connection.resolve(connection);
582
+ if (!resolved || resolved.type !== "key") {
583
+ return { connection, credential: undefined };
584
+ }
585
+ return {
586
+ connection,
587
+ credential: {
588
+ key: resolved.key,
589
+ metadata: resolved.metadata ?? undefined,
590
+ configuration: resolved.configuration ?? undefined
591
+ }
613
592
  };
593
+ } catch (e) {
594
+ log.warn(`Integration connection lookup failed: ${String(e)}`);
595
+ return { connection: undefined, credential: undefined };
614
596
  }
615
- return orderModelsByApiBase(result);
616
- }
617
- function toConfigModels(models) {
618
- return orderModelsByApiBase(Object.fromEntries(Object.entries(models).map(([id, model]) => {
619
- const { pricingTiers: _pricingTiers, ...configModel } = model;
620
- return [id, configModel];
621
- })));
622
- }
623
- function authMetadata(auth) {
624
- return auth?.type === "api" ? auth.metadata : undefined;
625
- }
626
- function raceWithTimeout(promise, timeoutMs) {
627
- return new Promise((resolve) => {
628
- const timer = setTimeout(() => resolve({ status: "timed-out" }), timeoutMs);
629
- promise.then((value) => {
630
- clearTimeout(timer);
631
- resolve({ status: "resolved", value });
632
- }, (error) => {
633
- clearTimeout(timer);
634
- resolve({ status: "rejected", error });
635
- });
636
- });
637
597
  }
638
- function refreshModels(client, baseURL, log, apiKey, force = false, suppress) {
598
+ function refreshModels(baseURL, log, apiKey, force = false, suppress) {
639
599
  if (!force && lastRefresh && Date.now() - lastRefresh.at < REFRESH_TTL_MS) {
640
- log.info(`Using in-memory plexus model cache (${Object.keys(lastRefresh.models).length} models)`);
600
+ log.info(`Using in-memory plexus model cache (${lastRefresh.models.length} models)`);
641
601
  return Promise.resolve(lastRefresh.models);
642
602
  }
643
603
  if (inFlightRefresh)
644
604
  return inFlightRefresh;
645
605
  const run = async () => {
646
606
  const url = modelsUrl(baseURL);
647
- const cached = await readCachedModels(client, suppress);
648
- const { models: apiModels, raw, etag, notModified } = await fetchPlexusModels(apiKey ?? "", url, undefined, cached?.etag);
607
+ const cached = await readCachedModels(suppress);
608
+ const { models: apiModels, raw, etag, notModified } = await fetchPlexusModels(apiKey ?? "", url, MODELS_FETCH_TIMEOUT_MS, cached?.etag);
649
609
  if (notModified && cached?.models) {
650
610
  log.info(`Plexus models not modified (etag: ${cached.etag})`);
651
611
  lastRefresh = { at: Date.now(), models: cached.models };
652
612
  return cached.models;
653
613
  }
654
614
  const built = buildModels(apiModels, apiBase(baseURL), suppress);
655
- for (const [id, model] of Object.entries(built)) {
656
- const providerNpm = model.provider?.npm ?? OPENAI_COMPATIBLE_NPM;
657
- const providerApi = model.provider?.api ?? "(missing)";
658
- log.info(`Model mapping ${id}: npm=${providerNpm} api=${providerApi}`);
659
- }
615
+ log.info(`Fetched ${built.length} plexus models from ${baseURL}`);
660
616
  lastRefresh = { at: Date.now(), models: built };
661
- writeCache(client, built, raw, etag).catch(() => {});
617
+ writeCache(built, raw, etag).catch(() => {});
662
618
  return built;
663
619
  };
664
620
  inFlightRefresh = run().finally(() => {
@@ -666,197 +622,203 @@ function refreshModels(client, baseURL, log, apiKey, force = false, suppress) {
666
622
  });
667
623
  return inFlightRefresh;
668
624
  }
669
- var PlexusProviderPlugin = async (ctx) => {
670
- const { client } = ctx;
671
- const log = createLogger(client);
672
- return {
673
- config: async (cfg) => {
674
- cfg.provider ??= {};
675
- const existing = cfg.provider[PLEXUS_PROVIDER_ID] ?? {};
676
- const existingOptions = typeof existing["options"] === "object" && existing["options"] !== null ? existing["options"] : {};
677
- const existingModels = typeof existing["models"] === "object" && existing["models"] !== null ? existing["models"] : null;
678
- const suppress = getSuppressedModels(existing);
679
- const { baseURL, apiKey } = resolveConfig(existing);
680
- log.info(`Resolved plexus config: baseURL=${baseURL ?? "(missing)"} apiKey=${apiKey ? "present" : "missing"}`);
681
- if (typeof existingOptions["baseURL"] === "string") {
682
- log.info(`Using provider.options.baseURL=${String(existingOptions["baseURL"])} as input-only OpenChamber compatibility config`);
683
- }
684
- const cachedAsync = await readCachedModels(client, suppress);
685
- if (cachedAsync) {
686
- log.info(`Loaded plexus cache with ${Object.keys(cachedAsync.models).length} models`);
687
- }
688
- const effectiveExistingModels = existingModels ? filterCachedModels(existingModels, suppress) : null;
689
- const merged = {
690
- ...existing,
691
- name: existing["name"] ?? PLEXUS_PROVIDER_NAME,
692
- npm: existing["npm"] ?? OPENAI_COMPATIBLE_NPM,
693
- options: {
694
- ...existingOptions,
695
- ...baseURL ? { [PLEXUS_BASE_URL_OPTION]: baseURL } : {},
696
- ...apiKey ? { apiKey } : {}
697
- },
698
- models: (effectiveExistingModels && Object.keys(effectiveExistingModels).length > 0 ? effectiveExistingModels : null) ?? (cachedAsync ? toConfigModels(cachedAsync.models) : null) ?? {
699
- [PLACEHOLDER_MODEL_ID]: {
700
- id: PLACEHOLDER_MODEL_ID,
701
- name: "Plexus (run /connect to configure)",
702
- limit: { context: 1024, output: 1024 },
703
- modalities: { input: ["text"], output: ["text"] }
704
- }
705
- }
706
- };
707
- const mergedOptions = merged["options"];
708
- delete mergedOptions["baseURL"];
709
- if (baseURL) {
710
- log.info("Plexus baseURL configured; run /plexus-refresh to force a live model refresh");
711
- } else {
712
- log.info("Plexus baseURL not configured; skipping live refresh");
713
- }
714
- cfg.command ??= {};
715
- cfg.command[PLEXUS_REFRESH_COMMAND] ??= {
716
- template: "Refreshing Plexus models from the live server...",
717
- description: "Force a live refresh of Plexus models and rewrite the on-disk cache"
625
+ async function loadSource(ctx, log, options, force) {
626
+ const suppress = getSuppressedModels(options);
627
+ const { connection, credential } = await resolveConnectionCredential(ctx, log);
628
+ const { baseURL, apiKey } = resolveConfig(options, credential);
629
+ log.info(`Resolved plexus config: baseURL=${baseURL ?? "(missing)"} apiKey=${apiKey ? "present" : "missing"}`);
630
+ if (!baseURL) {
631
+ log.info("Plexus baseURL not configured; using cache or placeholder");
632
+ const cached = await readCachedModels(suppress);
633
+ if (cached && cached.models.length > 0) {
634
+ log.info(`Loaded plexus cache with ${cached.models.length} models`);
635
+ return { models: cached.models, baseURL, apiKey, connection };
636
+ }
637
+ return { models: [placeholderModel()], baseURL, apiKey, connection };
638
+ }
639
+ try {
640
+ const models = await refreshModels(baseURL, log, apiKey, force, suppress);
641
+ if (models.length === 0) {
642
+ log.warn("Live fetch returned no models; falling back to cache or placeholder");
643
+ const cached = await readCachedModels(suppress);
644
+ return {
645
+ models: cached && cached.models.length > 0 ? cached.models : [placeholderModel()],
646
+ baseURL,
647
+ apiKey,
648
+ connection
718
649
  };
719
- try {
720
- const mergedModels = merged["models"];
721
- for (const id of ["gemini-3.5-flash", "claude-haiku-4-5", "small-fast"]) {
722
- const m = mergedModels?.[id];
723
- if (!m)
724
- continue;
725
- log.info(`Merged model ${id}: provider.npm=${m.provider?.npm ?? "(unset)"} provider.api=${m.provider?.api ?? "(unset)"}`);
726
- }
727
- } catch {}
728
- cfg.provider[PLEXUS_PROVIDER_ID] = merged;
729
- },
730
- provider: {
731
- id: PLEXUS_PROVIDER_ID,
732
- models: async (provider, hookCtx) => {
733
- const suppress = getSuppressedModels(provider);
734
- const authKey = hookCtx.auth?.type === "api" ? hookCtx.auth.key : undefined;
735
- const { baseURL, apiKey } = resolveConfig(provider, authMetadata(hookCtx.auth));
736
- const key = authKey ?? apiKey;
737
- if (!baseURL) {
738
- log.info("Provider hook skipped live refresh; baseURL missing");
739
- const cached = await readCachedModels(client, suppress);
740
- return cached ? toRuntimeModels(cached.models, provider) : {};
741
- }
742
- const refreshPromise = refreshModels(client, baseURL, log, key, false, suppress);
743
- const race = await raceWithTimeout(refreshPromise, CONFIG_HOOK_REFRESH_BUDGET_MS);
744
- if (race.status === "resolved") {
745
- log.info(`Provider hook loaded ${Object.keys(race.value).length} plexus models from ${baseURL}`);
746
- return toRuntimeModels(race.value, provider);
747
- }
748
- const cached = await readCachedModels(client, suppress);
749
- if (race.status === "rejected") {
750
- log.warn(`Provider hook live refresh failed, using cache: ${String(race.error)}`);
751
- } else {
752
- log.info(`Provider hook refresh still pending after ${CONFIG_HOOK_REFRESH_BUDGET_MS}ms; using cache and continuing in background`);
753
- refreshPromise.catch((e) => {
754
- log.warn(`Background plexus model refresh failed: ${String(e)}`);
650
+ }
651
+ return { models, baseURL, apiKey, connection };
652
+ } catch (e) {
653
+ log.warn(`Live plexus refresh failed, using cache: ${String(e)}`);
654
+ const cached = await readCachedModels(suppress);
655
+ if (cached && cached.models.length > 0) {
656
+ return { models: cached.models, baseURL, apiKey, connection };
657
+ }
658
+ return { models: [placeholderModel()], baseURL, apiKey, connection };
659
+ }
660
+ }
661
+ function providerInfo(source) {
662
+ const providerID = Provider.ID.make(PLEXUS_PROVIDER_ID);
663
+ const info = {
664
+ ...Provider.Info.empty(providerID),
665
+ name: PLEXUS_PROVIDER_NAME,
666
+ activation: "enabled",
667
+ package: OPENAI_COMPATIBLE_PKG,
668
+ integrationID: PLEXUS_INTEGRATION_ID,
669
+ settings: {
670
+ ...source.baseURL ? { baseURL: apiBase(source.baseURL) } : {},
671
+ ...source.apiKey ? { apiKey: source.apiKey } : {}
672
+ }
673
+ };
674
+ return info;
675
+ }
676
+ var plugin_default = Plugin.define({
677
+ id: PLEXUS_PLUGIN_ID,
678
+ async setup(ctx) {
679
+ const log = createLogger();
680
+ const options = ctx.options ?? {};
681
+ const source = { models: [], baseURL: undefined, apiKey: undefined, connection: undefined };
682
+ const reloadSource = async (force) => {
683
+ const next = await loadSource(ctx, log, options, force);
684
+ source.models = next.models;
685
+ source.baseURL = next.baseURL;
686
+ source.apiKey = next.apiKey;
687
+ source.connection = next.connection;
688
+ };
689
+ await reloadSource(false);
690
+ const providerID = Provider.ID.make(PLEXUS_PROVIDER_ID);
691
+ await ctx.provider.transform((editor) => {
692
+ const existing = editor.get(providerID);
693
+ if (existing)
694
+ editor.remove(providerID);
695
+ editor.add({
696
+ info: providerInfo(source),
697
+ models: toModelInfo(source.models),
698
+ ...source.connection ? { sourceConnection: source.connection } : {}
699
+ });
700
+ log.info(`Provider transform: registered ${PLEXUS_PROVIDER_ID} with ${source.models.length} models (present=${Boolean(editor.get(providerID))})`);
701
+ });
702
+ await ctx.provider.transform((editor) => {
703
+ editor.update(providerID, (provider) => {
704
+ const settings = provider.settings ?? {};
705
+ if (source.baseURL)
706
+ settings["baseURL"] = apiBase(source.baseURL);
707
+ else
708
+ delete settings["baseURL"];
709
+ if (source.apiKey)
710
+ settings["apiKey"] = source.apiKey;
711
+ else
712
+ delete settings["apiKey"];
713
+ provider.settings = settings;
714
+ });
715
+ });
716
+ try {
717
+ await ctx.integration.transform((editor) => {
718
+ editor.update(PLEXUS_INTEGRATION_ID, (ref) => {
719
+ ref.name = PLEXUS_PROVIDER_NAME;
720
+ });
721
+ editor.method.update({
722
+ integrationID: PLEXUS_INTEGRATION_ID,
723
+ method: {
724
+ type: "key",
725
+ label: "Plexus API key",
726
+ form: [
727
+ {
728
+ type: "string",
729
+ key: PLEXUS_BASE_URL_OPTION,
730
+ title: "Plexus base URL",
731
+ description: "Plexus root URL (https://host or https://host/v1)",
732
+ placeholder: "https://plexus.example.com",
733
+ required: true
734
+ }
735
+ ]
736
+ }
737
+ });
738
+ });
739
+ } catch (e) {
740
+ log.warn(`Integration transform failed (non-fatal): ${String(e)}`);
741
+ }
742
+ await ctx.command.transform((editor) => {
743
+ editor.add({
744
+ name: PLEXUS_REFRESH_COMMAND,
745
+ description: "Refresh Plexus models from the live server",
746
+ execute: async ({ sessionID, delivery }) => {
747
+ lastRefresh = null;
748
+ await reloadSource(true);
749
+ await ctx.provider.reload();
750
+ const count = source.models.length;
751
+ const placeholderOnly = count === 1 && source.models[0]?.id === PLACEHOLDER_MODEL_ID;
752
+ const text = !source.baseURL ? "Plexus refresh failed: no base URL configured. Run /connect first (plexus integration)." : placeholderOnly ? `Plexus refresh from ${source.baseURL} returned no usable models. Existing state left untouched.` : `Plexus models refreshed: ${count} models from ${source.baseURL}.`;
753
+ log.info(text);
754
+ await ctx.session.synthetic({
755
+ sessionID,
756
+ text,
757
+ description: text,
758
+ delivery,
759
+ resume: false
755
760
  });
756
761
  }
757
- return cached ? toRuntimeModels(cached.models, provider) : {};
758
- }
759
- },
760
- "command.execute.before": async (input) => {
761
- if (input.command !== PLEXUS_REFRESH_COMMAND)
762
- return;
763
- const configResponse = await client.config.get();
764
- const provider = configResponse.data?.provider?.[PLEXUS_PROVIDER_ID];
765
- const suppress = getSuppressedModels(provider);
766
- const storedAuth = await readStoredAuth();
767
- const { baseURL, apiKey } = resolveConfig(provider, storedAuth?.metadata);
768
- const key = storedAuth?.key ?? apiKey;
769
- if (!baseURL) {
770
- throw new Error("Plexus refresh failed: no baseURL configured. Run /connect first.");
771
- }
772
- let models;
773
- try {
774
- models = await refreshModels(client, baseURL, log, key, true, suppress);
775
- } catch (e) {
776
- throw new Error(`Plexus refresh failed: ${String(e)}. Existing cache left untouched.`);
777
- }
778
- throw new Error(`Plexus models refreshed: ${Object.keys(models).length} models fetched from ${baseURL} and cached. Restart OpenCode to pick up the new model list.`);
779
- },
780
- auth: {
781
- provider: PLEXUS_PROVIDER_ID,
782
- async loader(getAuth, providerInfo) {
783
- const auth = await getAuth();
784
- const authMetadataValue = auth?.type === "api" ? auth.metadata : undefined;
785
- const { baseURL, apiKey } = resolveConfig(providerInfo, authMetadataValue);
786
- const key = (auth?.type === "api" ? auth.key : undefined) ?? apiKey;
787
- log.info(`Auth loader resolved plexus config: baseURL=${baseURL ?? "(missing)"} apiKey=${key ? "present" : "missing"}`);
788
- return {
789
- ...key ? { apiKey: key } : {}
790
- };
791
- },
792
- methods: [
793
- {
794
- type: "api",
795
- label: "Plexus API key",
796
- prompts: [
797
- {
798
- type: "text",
799
- key: "baseURL",
800
- message: "Plexus base URL",
801
- placeholder: "https://plexus.example.com",
802
- validate: (v) => trimURL(v) ? undefined : "URL is required"
803
- }
804
- ],
805
- async authorize(inputs = {}) {
806
- const baseURL = rootURL(inputs["baseURL"] ?? "");
807
- const apiKey = (inputs["apiKey"] ?? "").trim();
808
- if (!baseURL || !apiKey)
809
- return { type: "failed" };
810
- try {
811
- const url = modelsUrl(baseURL);
812
- await fetchPlexusModels("", url);
813
- } catch (e) {
814
- log.error(`Plexus URL probe failed at ${baseURL}: ${String(e)}`);
815
- return { type: "failed" };
816
- }
762
+ });
763
+ });
764
+ (async () => {
765
+ let pending = null;
766
+ for await (const event of ctx.event.subscribe()) {
767
+ const type = event.type;
768
+ if (type !== "credential.updated" && type !== "credential.switched")
769
+ continue;
770
+ if (pending)
771
+ continue;
772
+ pending = (async () => {
773
+ try {
817
774
  lastRefresh = null;
818
- return {
819
- type: "success",
820
- provider: PLEXUS_PROVIDER_ID,
821
- key: apiKey,
822
- metadata: { [AUTH_METADATA_BASE_URL]: baseURL }
823
- };
775
+ await reloadSource(true);
776
+ await ctx.provider.reload();
777
+ log.info(`Credentials changed (${type}); reloaded ${source.models.length} model(s)`);
778
+ } catch (e) {
779
+ log.warn(`Reload after credential change failed: ${String(e)}`);
780
+ } finally {
781
+ pending = null;
824
782
  }
825
- }
826
- ]
827
- }
828
- };
829
- };
783
+ })();
784
+ }
785
+ })().catch((e) => log.warn(`Credential watcher stopped: ${String(e)}`));
786
+ log.info(`Plexus V2 plugin ready: ${source.models.length} model(s)${source.baseURL ? ` from ${source.baseURL}` : " (unconfigured)"}`);
787
+ }
788
+ });
830
789
 
831
790
  // src/index.ts
832
- var plugin2 = {
833
- id: PLEXUS_PLUGIN_ID,
834
- server: PlexusProviderPlugin
835
- };
836
- var src_default = plugin2;
791
+ var src_default = plugin_default;
837
792
  export {
838
- CONFIG_HOOK_REFRESH_BUDGET_MS,
793
+ ANTHROPIC_PKG,
839
794
  ENV_API_KEY,
840
795
  ENV_API_URL,
841
796
  ENV_BASE_URL,
842
- ENV_EXCLUDE_MODELS,
843
- ENV_IGNORE_MODELS,
844
- ENV_SUPPRESSED_MODELS,
845
- ENV_SUPPRESS_MODELS,
797
+ GOOGLE_PKG,
846
798
  MODELS_FETCH_TIMEOUT_MS,
847
- OPENAI_COMPATIBLE_NPM,
799
+ OPENAI_COMPATIBLE_PKG,
848
800
  PLACEHOLDER_MODEL_ID,
849
801
  PLEXUS_BASE_URL_OPTION,
850
- PLEXUS_LOG_SERVICE,
802
+ PLEXUS_INTEGRATION_ID,
851
803
  PLEXUS_PLUGIN_ID,
852
804
  PLEXUS_PROVIDER_ID,
853
805
  PLEXUS_PROVIDER_NAME,
854
806
  PLEXUS_REFRESH_COMMAND,
855
807
  PLEXUS_SUPPRESS_MODELS_OPTION,
856
- PlexusProviderPlugin,
857
808
  REFRESH_TTL_MS,
809
+ apiBase,
858
810
  buildModels,
859
811
  src_default as default,
812
+ filterCachedModels,
813
+ getDir,
814
+ getSuppressedModels,
815
+ modelsUrl,
860
816
  orderModelsByApiBase,
861
- toRuntimeModels
817
+ placeholderModel,
818
+ readCachedModels,
819
+ resolveConfig,
820
+ resolveConfigTemplate,
821
+ rootURL,
822
+ trimURL,
823
+ writeCache
862
824
  };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@mcowger/opencode-plexus",
3
- "version": "1.4.11",
4
- "description": "OpenCode plugin: Plexus provider with dynamic model discovery",
3
+ "version": "1.7.0",
4
+ "description": "Plexus AI proxy plugin for OpenCode V2 with dynamic model discovery",
5
5
  "type": "module",
6
6
  "module": "./dist/index.js",
7
7
  "main": "./dist/index.js",
@@ -11,6 +11,7 @@
11
11
  },
12
12
  "files": [
13
13
  "dist/index.js",
14
+ "server.js",
14
15
  "package.json",
15
16
  "README.md"
16
17
  ],
@@ -26,11 +27,10 @@
26
27
  "build": "bun run build.ts"
27
28
  },
28
29
  "dependencies": {
29
- "@opencode-ai/plugin": "^1.17.18",
30
- "@opencode-ai/sdk": "^1.17.18"
30
+ "@opencode/plugin": "^2.0.19"
31
31
  },
32
32
  "peerDependencies": {
33
- "typescript": "^5"
33
+ "typescript": "^7.0.2"
34
34
  },
35
35
  "devDependencies": {
36
36
  "@types/bun": "latest"
@@ -41,7 +41,7 @@
41
41
  "repository": {
42
42
  "type": "git",
43
43
  "url": "https://github.com/mcowger/plexus-agent-plugins.git",
44
- "directory": "packages/plexus-opencode"
44
+ "directory": "packages/plexus-opencode-v2"
45
45
  },
46
46
  "license": "MIT"
47
47
  }
package/server.js ADDED
@@ -0,0 +1 @@
1
+ export { default } from "./dist/index.js";