@mcowger/pi-plexus 1.9.0 → 1.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -176,21 +176,21 @@ To force a model refresh:
176
176
  /plexus-refresh
177
177
  ```
178
178
 
179
- `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).
179
+ `PLEXUS_API_URL` / `PLEXUS_BASE_URL` / `PLEXUS_API_KEY` env vars and plugin options (`plexusBaseURL`, `apiKey`, `apiKeyEnv`, `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).
180
180
 
181
181
  ## Configuration files
182
182
 
183
183
  ### Connection state
184
184
 
185
- Each adapter stores only non-secret Plexus settings in its own `config.json`:
185
+ Pi and OMP store only non-secret Plexus settings in their own `config.json`:
186
186
 
187
187
  ```text
188
- <agent-dir>/extensions/plexus/config.json # base URL and optional model suppression
188
+ <agent-dir>/extensions/plexus/config.json # base URL, apiKeyEnv, model suppression
189
189
  ```
190
190
 
191
191
  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.
192
192
 
193
- At runtime, configuration resolves as follows:
193
+ With `apiKeyEnv` omitted, Pi resolves configuration as follows:
194
194
 
195
195
  ```text
196
196
  base URL: PLEXUS_API_URL → PLEXUS_BASE_URL → saved Plexus base URL
@@ -199,10 +199,73 @@ catalog: host model store → live Plexus refresh
199
199
  startup model: host model-picker preference
200
200
  ```
201
201
 
202
- `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.
202
+ OMP uses the same URL precedence, but its registered `PLEXUS_API_KEY` environment reference is a native config-key override, ahead of saved credentials. If that variable isn't set, OMP uses its host credential resolver. OpenCode uses `PLEXUS_API_KEY` before the saved `/connect` credential and plugin `apiKey` option.
203
+
204
+ `PLEXUS_API_URL` and `PLEXUS_BASE_URL` are process-only URL overrides; environment API keys aren't persisted. `/plexus status` reports the effective URL source, whether auth is available, and catalog state without exposing credentials.
203
205
 
204
206
  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`.
205
207
 
208
+ ### Separate API-key environment variables
209
+
210
+ Set `apiKeyEnv` to the **name** of an environment variable, not its value or a `$VAR` template. The default is `PLEXUS_API_KEY`; no client-specific name is built in.
211
+
212
+ For Pi, edit `~/.pi/agent/extensions/plexus/config.json` (or `<agent-dir>/extensions/plexus/config.json` when using a custom agent directory):
213
+
214
+ ```json
215
+ {
216
+ "baseUrl": "https://plexus.example.com",
217
+ "apiKeyEnv": "AIHOME_PI_API_KEY"
218
+ }
219
+ ```
220
+
221
+ For OMP, edit `~/.omp/agent/extensions/plexus/config.json` (under the active profile's agent directory when using profiles):
222
+
223
+ ```json
224
+ {
225
+ "baseUrl": "https://plexus.example.com",
226
+ "apiKeyEnv": "AIHOME_OMP_API_KEY"
227
+ }
228
+ ```
229
+
230
+ For OpenCode V2, put `apiKeyEnv` in the plugin's `options` in `~/.config/opencode/opencode.jsonc` (or your project `opencode.jsonc`):
231
+
232
+ ```jsonc
233
+ {
234
+ "plugins": [
235
+ {
236
+ "package": "@mcowger/opencode-plexus",
237
+ "options": {
238
+ "plexusBaseURL": "https://plexus.example.com",
239
+ "apiKeyEnv": "AIHOME_OPENCODE_API_KEY"
240
+ }
241
+ }
242
+ ]
243
+ }
244
+ ```
245
+
246
+ Set the named variable in the process environment that launches the client. Restart Pi/OMP after editing their config; restart the OpenCode service after editing plugin options or changing its environment.
247
+
248
+ Credential precedence:
249
+
250
+ | Client | `apiKeyEnv` omitted | `apiKeyEnv` explicitly set |
251
+ |---|---|---|
252
+ | Pi | Saved host credential, then `PLEXUS_API_KEY` fallback | Only the named environment variable, ahead of saved credentials |
253
+ | OMP | Registered `PLEXUS_API_KEY` env override, then host credentials | Only the named environment variable, ahead of saved credentials |
254
+ | OpenCode V2 | `PLEXUS_API_KEY`, then saved `/connect` credential, then plugin `apiKey` option | Only the named environment variable, ahead of both saved credentials and `apiKey` |
255
+
256
+ An explicit setting is authoritative even when it names `PLEXUS_API_KEY`. If the selected variable is missing, empty, or whitespace-only, the plugin reports an error naming the variable without showing its value. It does not fall back to a saved key, OpenCode's `apiKey` option, or the shared `PLEXUS_API_KEY`. Saved credentials remain stored; remove `apiKeyEnv` to restore the default precedence.
257
+
258
+ ### Native login with `apiKeyEnv`
259
+
260
+ `apiKeyEnv` changes which key authenticates requests, not the native login UI:
261
+
262
+ - Pi and OMP: `/login plexus` still prompts for the base URL and API key, and saves both through the normal configuration and credential stores.
263
+ - OpenCode V2: `/connect` still stores the Plexus base URL and API key normally.
264
+
265
+ With an explicit `apiKeyEnv`, discovery and model requests use the named environment variable rather than the key entered during login. OMP's immediate post-login refresh also uses the environment key. Login remains useful for configuring the base URL, but entering a different key won't override the environment setting.
266
+
267
+ If the named variable is missing or empty at startup, the plugin fails to load. Native login cannot repair that setting: set the variable in the launching process environment or remove `apiKeyEnv`, then restart. Removing the setting restores the default precedence above without deleting saved credentials.
268
+
206
269
  ---
207
270
 
208
271
  ## Model suppression
package/dist/extension.js CHANGED
@@ -462,6 +462,47 @@ function getBaseUrlResolution() {
462
462
  const saved = resolveStringOption(config.baseUrl);
463
463
  return { baseUrl: saved ?? null, source: saved ? "saved" : "none" };
464
464
  }
465
+ function resolveApiKeyEnvSetting() {
466
+ const raw = getConfigSync().apiKeyEnv;
467
+ if (raw === undefined || raw === null)
468
+ return { name: ENV_API_KEY, explicit: false };
469
+ const name = typeof raw === "string" ? raw.trim() : "";
470
+ if (!ENV_VAR_NAME_RE.test(name)) {
471
+ throw new Error("Invalid apiKeyEnv: expected an environment variable name");
472
+ }
473
+ return { name, explicit: true };
474
+ }
475
+ function getApiKeyEnvName() {
476
+ return resolveApiKeyEnvSetting().name;
477
+ }
478
+ function isApiKeyEnvExplicit() {
479
+ return resolveApiKeyEnvSetting().explicit;
480
+ }
481
+ function requireApiKeyEnvValue(name, raw) {
482
+ const value = raw?.trim();
483
+ if (!value) {
484
+ throw new Error(`apiKeyEnv environment variable "${name}" is missing or empty`);
485
+ }
486
+ return value;
487
+ }
488
+ async function resolveExplicitApiKeyFromEnv(readEnv) {
489
+ const { name, explicit } = resolveApiKeyEnvSetting();
490
+ if (!explicit)
491
+ return;
492
+ return requireApiKeyEnvValue(name, await readEnv(name));
493
+ }
494
+ function resolveExplicitApiKey() {
495
+ const { name, explicit } = resolveApiKeyEnvSetting();
496
+ if (!explicit)
497
+ return;
498
+ return requireApiKeyEnvValue(name, process.env[name]);
499
+ }
500
+ function resolveApiKey(storedKey) {
501
+ const explicit = resolveExplicitApiKey();
502
+ if (explicit)
503
+ return explicit;
504
+ return storedKey || getEnvApiKey() || undefined;
505
+ }
465
506
  function getEnvApiKey() {
466
507
  return resolveStringOption(process.env[ENV_API_KEY]) ?? null;
467
508
  }
@@ -758,7 +799,6 @@ function buildServiceTierNotification(input) {
758
799
 
759
800
  // src/extension.ts
760
801
  var PROVIDER_NAME = "plexus";
761
- var PROVIDER_API_KEY_TEMPLATE = "${PLEXUS_API_KEY}";
762
802
  var PLEXUS_CREDENTIAL_EXPIRES_AT = 253402300799000;
763
803
  var PLACEHOLDER_BASE_URL = "http://localhost/v1";
764
804
  var currentModels = [];
@@ -788,8 +828,54 @@ function enforceMinimumOutputTokens(payload) {
788
828
  }
789
829
  return changed ? next : payload;
790
830
  }
831
+ function withAuthoritativeApiKeyEnv(provider, envName, getHeaderModels = () => currentModels) {
832
+ const apiKey = provider.auth.apiKey;
833
+ if (!apiKey)
834
+ return provider;
835
+ const withModelHeaders = (models) => {
836
+ const headersById = new Map;
837
+ for (const model of getHeaderModels()) {
838
+ if (model.headers)
839
+ headersById.set(model.id, model.headers);
840
+ }
841
+ if (headersById.size === 0)
842
+ return [...models];
843
+ return models.map((model) => {
844
+ const headers = headersById.get(model.id);
845
+ return headers ? { ...model, headers: { ...model.headers, ...headers } } : model;
846
+ });
847
+ };
848
+ return {
849
+ ...provider,
850
+ auth: {
851
+ ...provider.auth,
852
+ apiKey: {
853
+ ...apiKey,
854
+ resolve: async (input) => {
855
+ const explicit = await resolveExplicitApiKeyFromEnv((name) => input.ctx.env(name));
856
+ if (explicit === undefined)
857
+ return apiKey.resolve(input);
858
+ const result = await apiKey.resolve({
859
+ ...input,
860
+ credential: {
861
+ type: "api_key",
862
+ key: explicit,
863
+ ...input.credential?.env ? { env: input.credential.env } : {}
864
+ }
865
+ });
866
+ return result ? { ...result, source: `${envName} (apiKeyEnv)` } : result;
867
+ }
868
+ }
869
+ },
870
+ getModels: () => withModelHeaders(provider.getModels()),
871
+ getAllModels: () => withModelHeaders(provider.getAllModels?.() ?? provider.getModels())
872
+ };
873
+ }
791
874
  function plexusExtension(pi) {
792
- const envApiKey = getEnvApiKey();
875
+ const apiKeyEnvExplicit = isApiKeyEnvExplicit();
876
+ const explicitApiKey = apiKeyEnvExplicit ? resolveExplicitApiKey() : undefined;
877
+ const apiKeyEnvName = getApiKeyEnvName();
878
+ const envApiKey = explicitApiKey ?? getEnvApiKey();
793
879
  const startupBaseUrl = getBaseUrl();
794
880
  const suppressPatterns = getSuppressedModels();
795
881
  const storedCatalog = readStoredModelsSync();
@@ -815,13 +901,27 @@ function plexusExtension(pi) {
815
901
  pi.on("message_end", (event) => normalizeMalformedFunctionCall(event.message, PROVIDER_NAME));
816
902
  pi.registerProvider(PROVIDER_NAME, {
817
903
  api: "openai-completions",
818
- ...envApiKey ? { apiKey: PROVIDER_API_KEY_TEMPLATE } : {},
904
+ ...envApiKey ? { apiKey: `\${${apiKeyEnvName}}` } : {},
819
905
  authHeader: true,
820
906
  baseUrl: startupBaseUrl ?? PLACEHOLDER_BASE_URL,
821
907
  models: startupModels,
822
908
  refreshModels: refreshPlexusModels,
823
909
  oauth: createPlexusLoginProvider()
824
910
  });
911
+ if (apiKeyEnvExplicit) {
912
+ let authOverrideApplied = false;
913
+ pi.on("session_start", (_event, ctx) => {
914
+ if (authOverrideApplied)
915
+ return;
916
+ const composed = ctx.modelRegistry.getProvider(PROVIDER_NAME);
917
+ if (!composed?.auth.apiKey) {
918
+ throw new Error("Plexus apiKeyEnv override failed: provider API-key auth is unavailable");
919
+ }
920
+ pi.registerProvider(withAuthoritativeApiKeyEnv(composed, apiKeyEnvName));
921
+ authOverrideApplied = true;
922
+ log("auth: applied authoritative apiKeyEnv override", { apiKeyEnv: apiKeyEnvName });
923
+ });
924
+ }
825
925
  pi.registerCommand("plexus", {
826
926
  description: "Plexus provider commands: refresh, status (setup: /login plexus)",
827
927
  getArgumentCompletions: (prefix) => {
@@ -885,7 +985,7 @@ function notifyServiceTier(ctx, tier, success) {
885
985
  async function refreshPlexusModels(context) {
886
986
  const baseUrl = getBaseUrl();
887
987
  const modelsUrl = getModelsUrl();
888
- const apiKey = credentialApiKey(context.credential) ?? getEnvApiKey() ?? undefined;
988
+ const apiKey = resolveApiKey(credentialApiKey(context.credential));
889
989
  const suppress = getSuppressedModels();
890
990
  if (!context.allowNetwork || !apiKey || !modelsUrl || !baseUrl) {
891
991
  if (currentModels.length > 0) {
@@ -972,7 +1072,8 @@ function createPlexusLoginProvider() {
972
1072
  return { ...credentials, expires: PLEXUS_CREDENTIAL_EXPIRES_AT };
973
1073
  },
974
1074
  getApiKey(credentials) {
975
- return String(credentials.access || credentials.refresh || "");
1075
+ const stored = String(credentials.access || credentials.refresh || "");
1076
+ return resolveExplicitApiKey() ?? stored;
976
1077
  },
977
1078
  modifyModels(models, credentials) {
978
1079
  const baseUrl = credentials.plexusBaseUrl;
@@ -984,7 +1085,13 @@ function createPlexusLoginProvider() {
984
1085
  };
985
1086
  }
986
1087
  async function handleRefresh(ctx) {
987
- const apiKey = await ctx.modelRegistry.getApiKeyForProvider(PROVIDER_NAME);
1088
+ let apiKey;
1089
+ try {
1090
+ apiKey = await ctx.modelRegistry.getApiKeyForProvider(PROVIDER_NAME);
1091
+ } catch (error) {
1092
+ ctx.ui.notify(`Plexus API key resolution failed: ${error instanceof Error ? error.message : String(error)}`, "error");
1093
+ return;
1094
+ }
988
1095
  if (!apiKey) {
989
1096
  ctx.ui.notify("No Plexus API key configured. Run /login plexus first.", "error");
990
1097
  return;
@@ -1004,10 +1111,14 @@ async function handleRefresh(ctx) {
1004
1111
  }
1005
1112
  async function handleStatus(ctx) {
1006
1113
  const baseUrl = getBaseUrlResolution();
1007
- const apiKey = await ctx.modelRegistry.getApiKeyForProvider(PROVIDER_NAME);
1114
+ const apiKeyEnvName = getApiKeyEnvName();
1115
+ const apiKey = await ctx.modelRegistry.getApiKeyForProvider(PROVIDER_NAME).catch(() => {
1116
+ return;
1117
+ });
1118
+ const explicitApiKey = apiKey ? resolveExplicitApiKey() : undefined;
1008
1119
  ctx.ui.notify([
1009
1120
  `Plexus base URL: ${baseUrl.baseUrl ?? "not configured"} (${baseUrl.source})`,
1010
- `API key: ${apiKey ? getEnvApiKey() ? "host credential or PLEXUS_API_KEY fallback" : "host credential" : "not configured"}`,
1121
+ `API key: ${apiKey ? explicitApiKey !== undefined ? `${apiKeyEnvName} (apiKeyEnv)` : getEnvApiKey() ? `host credential or ${apiKeyEnvName} fallback` : "host credential" : "not configured"}`,
1011
1122
  `Catalog: ${currentModels.length} models (${catalogSource})`,
1012
1123
  "Default model: managed by Pi. Use /model and save the selection there."
1013
1124
  ].join(`
@@ -1015,5 +1126,6 @@ async function handleStatus(ctx) {
1015
1126
  }
1016
1127
  export {
1017
1128
  plexusExtension as default,
1018
- enforceMinimumOutputTokens
1129
+ enforceMinimumOutputTokens,
1130
+ withAuthoritativeApiKeyEnv
1019
1131
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mcowger/pi-plexus",
3
- "version": "1.9.0",
3
+ "version": "1.10.0",
4
4
  "description": "Plexus AI proxy plugin for the pi coding agent",
5
5
  "type": "module",
6
6
  "files": [