@mcowger/opencode-plexus 1.4.12 → 1.7.1

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 +377 -407
  3. package/package.json +6 -6
  4. package/server.js +1 -0
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;
@@ -167,50 +151,70 @@ async function fetchPlexusModels(apiKey, modelsUrl, timeoutMs = DEFAULT_MODELS_F
167
151
  import { mkdir, readFile, writeFile } from "fs/promises";
168
152
  import { homedir } from "os";
169
153
  import { join } from "path";
154
+
155
+ // src/constants.ts
156
+ var PLEXUS_PROVIDER_ID = "plexus";
157
+ var PLEXUS_PROVIDER_NAME = "Plexus";
158
+ var PLEXUS_PLUGIN_ID = "@mcowger/opencode-plexus";
159
+ var PLEXUS_INTEGRATION_ID = "plexus";
160
+ var OPENAI_COMPATIBLE_PKG = "aisdk:@ai-sdk/openai-compatible";
161
+ var ANTHROPIC_PKG = "aisdk:@ai-sdk/anthropic";
162
+ var GOOGLE_PKG = "aisdk:@ai-sdk/google";
163
+ var OPENAI_RESPONSES_PKG = "aisdk:@ai-sdk/openai";
164
+ var PLEXUS_BASE_URL_OPTION = "plexusBaseURL";
165
+ var ENV_BASE_URL = "PLEXUS_BASE_URL";
166
+ var ENV_API_URL = "PLEXUS_API_URL";
167
+ var ENV_API_KEY = "PLEXUS_API_KEY";
168
+ var PLEXUS_SUPPRESS_MODELS_OPTION = "suppressModels";
169
+ var MODELS_FETCH_TIMEOUT_MS = 1e4;
170
+ var REFRESH_TTL_MS = 60000;
171
+ var CACHE_VERSION = 2;
172
+ var PLACEHOLDER_MODEL_ID = "plexus-unconfigured";
173
+ var PLEXUS_REFRESH_COMMAND = "plexus-refresh";
174
+
175
+ // src/cache.ts
170
176
  var PLUGIN_SUBDIR = join("plugins", "plexus");
171
- var CACHE_FILE = "models-cache.json";
177
+ var CACHE_FILE = "models-cache-v2.json";
172
178
  var RAW_FILE = "models-raw.json";
173
- function fallbackDir() {
174
- return join(homedir(), ".local", "share", "opencode", PLUGIN_SUBDIR);
175
- }
176
179
  function getDir() {
177
- return fallbackDir();
180
+ const dataHome = process.env.XDG_DATA_HOME || join(homedir(), ".local", "share");
181
+ return join(dataHome, "opencode", PLUGIN_SUBDIR);
178
182
  }
179
183
  function filterCachedModels(models, suppress) {
180
- return Object.fromEntries(Object.entries(models).filter(([, model]) => {
184
+ return models.filter((model) => {
181
185
  if (isModelSuppressed({ id: model.id, name: model.name }, suppress))
182
186
  return false;
183
187
  return isChatModel({
184
188
  id: model.id,
185
189
  name: model.name,
186
190
  architecture: {
187
- input_modalities: model.modalities.input,
188
- output_modalities: model.modalities.output
191
+ input_modalities: model.capabilities.input,
192
+ output_modalities: model.capabilities.output
189
193
  }
190
194
  });
191
- }));
195
+ });
192
196
  }
193
- async function readCachedModels(_client, suppress) {
197
+ async function readCachedModels(suppress) {
194
198
  try {
195
- const dir = getDir();
196
- const content = await readFile(join(dir, CACHE_FILE), "utf8");
199
+ const content = await readFile(join(getDir(), CACHE_FILE), "utf8");
197
200
  const parsed = JSON.parse(content);
198
- if (parsed && typeof parsed.models === "object" && !Array.isArray(parsed.models)) {
199
- return {
200
- models: filterCachedModels(parsed.models, suppress),
201
- etag: typeof parsed.etag === "string" ? parsed.etag : undefined
202
- };
203
- }
204
- return null;
201
+ if (!parsed || !Array.isArray(parsed.models))
202
+ return null;
203
+ if (parsed.version !== CACHE_VERSION)
204
+ return null;
205
+ return {
206
+ models: filterCachedModels(parsed.models, suppress),
207
+ etag: typeof parsed.etag === "string" ? parsed.etag : undefined
208
+ };
205
209
  } catch {
206
210
  return null;
207
211
  }
208
212
  }
209
- async function writeCache(_client, models, raw, etag) {
213
+ async function writeCache(models, raw, etag) {
210
214
  try {
211
215
  const dir = getDir();
212
216
  await mkdir(dir, { recursive: true });
213
- const cache = { models, timestamp: Date.now(), etag };
217
+ const cache = { version: CACHE_VERSION, models, timestamp: Date.now(), etag };
214
218
  await writeFile(join(dir, CACHE_FILE), JSON.stringify(cache, null, 2) + `
215
219
  `, "utf8");
216
220
  if (raw !== undefined) {
@@ -220,11 +224,6 @@ async function writeCache(_client, models, raw, etag) {
220
224
  } catch {}
221
225
  }
222
226
 
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";
227
-
228
227
  // src/url.ts
229
228
  function trimURL(s) {
230
229
  return s.trim().replace(/\/+$/, "");
@@ -249,22 +248,6 @@ function modelsUrl(baseURL) {
249
248
  // src/config-store.ts
250
249
  var ENV_VAR_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
251
250
  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
251
  function resolveConfigTemplate(value) {
269
252
  let result = "";
270
253
  let index = 0;
@@ -321,37 +304,55 @@ function resolveStringOption(value) {
321
304
  const resolved = resolveConfigTemplate(value)?.trim();
322
305
  return resolved || undefined;
323
306
  }
324
- function resolveConfig(provider, authMetadata) {
307
+ function metadataBaseURL(credential) {
308
+ if (!credential)
309
+ return;
310
+ const fromMetadata = resolveStringOption(credential.metadata?.[PLEXUS_BASE_URL_OPTION]);
311
+ if (fromMetadata)
312
+ return fromMetadata;
313
+ const rawConfig = credential.configuration?.[PLEXUS_BASE_URL_OPTION];
314
+ return typeof rawConfig === "string" ? resolveStringOption(rawConfig) : undefined;
315
+ }
316
+ function resolveConfig(options, credential) {
325
317
  const envBaseURL = process.env[ENV_API_URL] ?? process.env[ENV_BASE_URL];
326
318
  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;
319
+ const metaBaseURL = credential ? metadataBaseURL(credential) : undefined;
320
+ const optBaseURL = resolveStringOption(options?.[PLEXUS_BASE_URL_OPTION]);
321
+ const optApiKey = resolveStringOption(options?.["apiKey"]);
322
+ const baseURL = (envBaseURL ? rootURL(envBaseURL) : undefined) || (metaBaseURL ? rootURL(metaBaseURL) : undefined) || (optBaseURL ? rootURL(optBaseURL) : undefined) || undefined;
323
+ const apiKey = (envApiKey ? envApiKey.trim() : undefined) || credential?.key?.trim() || optApiKey || undefined;
337
324
  return {
338
325
  baseURL: baseURL || undefined,
339
- apiKey: apiKey || undefined,
340
- ...suppressModels.length > 0 ? { suppressModels } : {}
326
+ apiKey: apiKey || undefined
341
327
  };
342
328
  }
343
- function getSuppressedModels(provider) {
329
+ function getSuppressedModels(options) {
344
330
  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"]);
331
+ const opt = options?.["suppressModels"] ?? options?.["suppress"] ?? options?.["suppress_models"];
332
+ const optSuppressed = parseSuppressionPatterns(opt);
348
333
  return [...envSuppressed, ...optSuppressed];
349
334
  }
350
335
 
351
336
  // src/log.ts
352
- function createLogger(client) {
337
+ import { appendFileSync, mkdirSync } from "fs";
338
+ import { join as join2 } from "path";
339
+ function createLogger(prefix = "plexus") {
353
340
  function log(level, message) {
354
- client.app.log({ body: { service: PLEXUS_LOG_SERVICE, level, message } }).catch(() => {});
341
+ const line = `[${prefix}] ${message}`;
342
+ try {
343
+ if (level === "error")
344
+ console.error(line);
345
+ else if (level === "warn")
346
+ console.warn(line);
347
+ else
348
+ console.log(line);
349
+ } catch {}
350
+ try {
351
+ const dir = getDir();
352
+ mkdirSync(dir, { recursive: true });
353
+ appendFileSync(join2(dir, "plugin.log"), `${new Date().toISOString()} ${level.toUpperCase()} ${message}
354
+ `);
355
+ } catch {}
355
356
  }
356
357
  return {
357
358
  info: (message) => log("info", message),
@@ -384,27 +385,27 @@ function buildReasoningVariants(model, preferredApi, hasReasoning) {
384
385
  const effortOption = model.reasoning_options?.find((option) => option.type === "effort");
385
386
  if (!effortOption)
386
387
  return;
387
- return Object.fromEntries(effortOption.values.map((value) => {
388
+ return effortOption.values.map((value) => {
388
389
  const effort = normalizeReasoningEffort(value);
389
- return [effort, reasoningVariantSettings(preferredApi, effort)];
390
- }));
390
+ return { id: effort, settings: reasoningVariantSettings(preferredApi, effort) };
391
+ });
391
392
  }
392
- function resolveModelProvider(model, baseURL) {
393
- const preferredApi = mapPreferredApi(model.preferred_api);
394
- const api = adjustBaseUrl(baseURL, preferredApi, "versioned");
393
+ function resolveModelPackage(preferredApi) {
395
394
  switch (preferredApi) {
396
395
  case "anthropic-messages":
397
- return { npm: "@ai-sdk/anthropic", api };
396
+ return ANTHROPIC_PKG;
398
397
  case "google-generative-ai":
399
- return { npm: "@ai-sdk/google", api };
398
+ return GOOGLE_PKG;
400
399
  case "openai-responses":
401
- return { npm: "@ai-sdk/openai", api };
400
+ return OPENAI_RESPONSES_PKG;
402
401
  case "openai-completions":
403
- return { api };
404
402
  default:
405
- return { api };
403
+ return;
406
404
  }
407
405
  }
406
+ function resolveModelBaseURL(preferredApi, apiBaseURL) {
407
+ return adjustBaseUrl(apiBaseURL, preferredApi, "versioned");
408
+ }
408
409
  function parsePrice(value) {
409
410
  if (!value)
410
411
  return 0;
@@ -418,13 +419,15 @@ function buildPricingTiers(model) {
418
419
  const tiers = pricing.tiers.flatMap((tier) => {
419
420
  if (!Number.isFinite(tier.input_tokens_above) || tier.input_tokens_above < 0)
420
421
  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
- }];
422
+ return [
423
+ {
424
+ inputTokensAbove: tier.input_tokens_above,
425
+ input: parsePrice(tier.prompt ?? pricing.prompt),
426
+ output: parsePrice(tier.completion ?? pricing.completion),
427
+ cacheRead: parsePrice(tier.input_cache_read ?? pricing.input_cache_read),
428
+ cacheWrite: parsePrice(tier.input_cache_write ?? pricing.input_cache_write)
429
+ }
430
+ ];
428
431
  });
429
432
  return tiers.length > 0 ? tiers : undefined;
430
433
  }
@@ -445,15 +448,14 @@ function mapModality(m) {
445
448
  return null;
446
449
  }
447
450
  }
448
- function releaseDate(created) {
451
+ function releaseTime(created) {
449
452
  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);
453
+ return 0;
454
+ return Math.floor(created * 1000);
453
455
  }
454
- function interleavedReasoning(model, preferredApi) {
456
+ function reasoningCompatibility(model, preferredApi) {
455
457
  if (preferredApi === "openai-completions" && model.id.toLowerCase().includes("deepseek")) {
456
- return { field: "reasoning_content" };
458
+ return { reasoningField: "reasoning_content" };
457
459
  }
458
460
  return;
459
461
  }
@@ -475,19 +477,22 @@ function buildOutputModalities(model) {
475
477
  function orderModelsByApiBase(models) {
476
478
  const current = [];
477
479
  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
- }
480
+ for (const model of models) {
481
+ const api = (model.settings?.baseURL ?? "").trim().replace(/\/+$/, "");
482
+ if (api.endsWith("/v1beta"))
483
+ beta.push(model);
484
+ else
485
+ current.push(model);
485
486
  }
486
- return Object.fromEntries([...current, ...beta]);
487
+ return [...current, ...beta];
487
488
  }
488
- function buildModels(models, baseURL, suppress) {
489
- const result = {};
489
+ function buildModels(models, apiBaseURL, suppress) {
490
+ const result = [];
490
491
  for (const m of models) {
492
+ if (!m.id || typeof m.id !== "string")
493
+ continue;
494
+ if (m.id.includes("/"))
495
+ continue;
491
496
  if (!isChatModel(m))
492
497
  continue;
493
498
  if (isModelSuppressed(m, suppress))
@@ -503,162 +508,119 @@ function buildModels(models, baseURL, suppress) {
503
508
  const completionPrice = parsePrice(m.pricing?.completion);
504
509
  const cacheReadPrice = parsePrice(m.pricing?.input_cache_read);
505
510
  const cacheWritePrice = parsePrice(m.pricing?.input_cache_write);
506
- const hasCachePricing = cacheReadPrice > 0 || cacheWritePrice > 0;
507
511
  const pricingTiers = buildPricingTiers(m);
508
- const hasNonTextInput = inputModalities.some((mod) => mod !== "text");
509
512
  const preferredApi = mapPreferredApi(m.preferred_api);
510
- const provider = resolveModelProvider(m, baseURL);
511
- const created = releaseDate(m.created);
512
- const interleaved = interleavedReasoning(m, preferredApi);
513
+ const pkg = resolveModelPackage(preferredApi);
514
+ const compatibility = reasoningCompatibility(m, preferredApi);
513
515
  const hasReasoning = params.some((p) => REASONING_PARAMS2.has(p));
514
516
  const variants = buildReasoningVariants(m, preferredApi, hasReasoning);
515
- const entry = {
517
+ const cost = [];
518
+ if (promptPrice > 0 || completionPrice > 0) {
519
+ cost.push({
520
+ input: promptPrice,
521
+ output: completionPrice,
522
+ cache: { read: cacheReadPrice, write: cacheWritePrice }
523
+ });
524
+ }
525
+ for (const tier of pricingTiers ?? []) {
526
+ cost.push({
527
+ tier: { type: "context", size: tier.inputTokensAbove },
528
+ input: tier.input,
529
+ output: tier.output,
530
+ cache: { read: tier.cacheRead, write: tier.cacheWrite }
531
+ });
532
+ }
533
+ result.push({
516
534
  id: m.id,
535
+ modelID: m.id,
536
+ providerID: "plexus",
517
537
  name: m.name ?? m.id,
518
- provider,
519
- limit: {
520
- context: contextLength,
521
- output: maxOutput
522
- },
523
- modalities: {
538
+ ...compatibility ? { compatibility } : {},
539
+ ...pkg ? { package: pkg } : {},
540
+ settings: { baseURL: resolveModelBaseURL(preferredApi, apiBaseURL) },
541
+ capabilities: {
542
+ tools: params.includes("tools"),
524
543
  input: inputModalities,
525
544
  output: outputModalities
526
545
  },
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;
546
+ variants: variants ?? [],
547
+ time: { released: releaseTime(m.created) },
548
+ cost,
549
+ status: "active",
550
+ enabled: true,
551
+ limit: {
552
+ context: contextLength,
553
+ output: maxOutput
554
+ }
555
+ });
544
556
  }
545
557
  return orderModelsByApiBase(result);
546
558
  }
559
+ function placeholderModel() {
560
+ return {
561
+ id: "plexus-unconfigured",
562
+ modelID: "plexus-unconfigured",
563
+ providerID: "plexus",
564
+ name: "Plexus (run /connect to configure)",
565
+ settings: {},
566
+ capabilities: { tools: false, input: ["text"], output: ["text"] },
567
+ variants: [],
568
+ time: { released: 0 },
569
+ cost: [],
570
+ status: "active",
571
+ enabled: true,
572
+ limit: { context: 1024, output: 1024 }
573
+ };
574
+ }
547
575
 
548
576
  // src/plugin.ts
549
577
  var lastRefresh = null;
550
578
  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
- };
579
+ function toModelInfo(models) {
580
+ return models;
575
581
  }
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 } : {}
582
+ async function resolveConnectionCredential(ctx, log) {
583
+ try {
584
+ const connection = await ctx.integration.connection.active(PLEXUS_INTEGRATION_ID);
585
+ if (!connection)
586
+ return { connection: undefined, credential: undefined };
587
+ const resolved = await ctx.integration.connection.resolve(connection);
588
+ if (!resolved || resolved.type !== "key") {
589
+ return { connection, credential: undefined };
590
+ }
591
+ return {
592
+ connection,
593
+ credential: {
594
+ key: resolved.key,
595
+ metadata: resolved.metadata ?? undefined,
596
+ configuration: resolved.configuration ?? undefined
597
+ }
613
598
  };
599
+ } catch (e) {
600
+ log.warn(`Integration connection lookup failed: ${String(e)}`);
601
+ return { connection: undefined, credential: undefined };
614
602
  }
615
- return orderModelsByApiBase(result);
616
603
  }
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
- }
638
- function refreshModels(client, baseURL, log, apiKey, force = false, suppress) {
604
+ function refreshModels(baseURL, log, apiKey, force = false, suppress) {
639
605
  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)`);
606
+ log.info(`Using in-memory plexus model cache (${lastRefresh.models.length} models)`);
641
607
  return Promise.resolve(lastRefresh.models);
642
608
  }
643
609
  if (inFlightRefresh)
644
610
  return inFlightRefresh;
645
611
  const run = async () => {
646
612
  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);
613
+ const cached = await readCachedModels(suppress);
614
+ const { models: apiModels, raw, etag, notModified } = await fetchPlexusModels(apiKey ?? "", url, MODELS_FETCH_TIMEOUT_MS, cached?.etag);
649
615
  if (notModified && cached?.models) {
650
616
  log.info(`Plexus models not modified (etag: ${cached.etag})`);
651
617
  lastRefresh = { at: Date.now(), models: cached.models };
652
618
  return cached.models;
653
619
  }
654
620
  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
- }
621
+ log.info(`Fetched ${built.length} plexus models from ${baseURL}`);
660
622
  lastRefresh = { at: Date.now(), models: built };
661
- writeCache(client, built, raw, etag).catch(() => {});
623
+ writeCache(built, raw, etag).catch(() => {});
662
624
  return built;
663
625
  };
664
626
  inFlightRefresh = run().finally(() => {
@@ -666,197 +628,205 @@ function refreshModels(client, baseURL, log, apiKey, force = false, suppress) {
666
628
  });
667
629
  return inFlightRefresh;
668
630
  }
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"
631
+ async function loadSource(ctx, log, options, force) {
632
+ const suppress = getSuppressedModels(options);
633
+ const { connection, credential } = await resolveConnectionCredential(ctx, log);
634
+ const { baseURL, apiKey } = resolveConfig(options, credential);
635
+ log.info(`Resolved plexus config: baseURL=${baseURL ?? "(missing)"} apiKey=${apiKey ? "present" : "missing"}`);
636
+ if (!baseURL) {
637
+ log.info("Plexus baseURL not configured; using cache or placeholder");
638
+ const cached = await readCachedModels(suppress);
639
+ if (cached && cached.models.length > 0) {
640
+ log.info(`Loaded plexus cache with ${cached.models.length} models`);
641
+ return { models: cached.models, baseURL, apiKey, connection };
642
+ }
643
+ return { models: [placeholderModel()], baseURL, apiKey, connection };
644
+ }
645
+ try {
646
+ const models = await refreshModels(baseURL, log, apiKey, force, suppress);
647
+ if (models.length === 0) {
648
+ log.warn("Live fetch returned no models; falling back to cache or placeholder");
649
+ const cached = await readCachedModels(suppress);
650
+ return {
651
+ models: cached && cached.models.length > 0 ? cached.models : [placeholderModel()],
652
+ baseURL,
653
+ apiKey,
654
+ connection
718
655
  };
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)}`);
656
+ }
657
+ return { models, baseURL, apiKey, connection };
658
+ } catch (e) {
659
+ log.warn(`Live plexus refresh failed, using cache: ${String(e)}`);
660
+ const cached = await readCachedModels(suppress);
661
+ if (cached && cached.models.length > 0) {
662
+ return { models: cached.models, baseURL, apiKey, connection };
663
+ }
664
+ return { models: [placeholderModel()], baseURL, apiKey, connection };
665
+ }
666
+ }
667
+ function providerInfo(source) {
668
+ const providerID = Provider.ID.make(PLEXUS_PROVIDER_ID);
669
+ const info = {
670
+ ...Provider.Info.empty(providerID),
671
+ name: PLEXUS_PROVIDER_NAME,
672
+ activation: "enabled",
673
+ package: OPENAI_COMPATIBLE_PKG,
674
+ integrationID: PLEXUS_INTEGRATION_ID,
675
+ settings: {
676
+ ...source.baseURL ? { baseURL: apiBase(source.baseURL) } : {},
677
+ ...source.apiKey ? { apiKey: source.apiKey } : {}
678
+ }
679
+ };
680
+ return info;
681
+ }
682
+ var plugin_default = Plugin.define({
683
+ id: PLEXUS_PLUGIN_ID,
684
+ async setup(ctx) {
685
+ const log = createLogger();
686
+ const options = ctx.options ?? {};
687
+ const source = { models: [], baseURL: undefined, apiKey: undefined, connection: undefined };
688
+ const reloadSource = async (force) => {
689
+ const next = await loadSource(ctx, log, options, force);
690
+ source.models = next.models;
691
+ source.baseURL = next.baseURL;
692
+ source.apiKey = next.apiKey;
693
+ source.connection = next.connection;
694
+ };
695
+ await reloadSource(false);
696
+ const providerID = Provider.ID.make(PLEXUS_PROVIDER_ID);
697
+ await ctx.provider.transform((editor) => {
698
+ const existing = editor.get(providerID);
699
+ if (existing)
700
+ editor.remove(providerID);
701
+ editor.add({
702
+ info: providerInfo(source),
703
+ models: toModelInfo(source.models),
704
+ ...source.connection ? { sourceConnection: source.connection } : {}
705
+ });
706
+ log.info(`Provider transform: registered ${PLEXUS_PROVIDER_ID} with ${source.models.length} models (present=${Boolean(editor.get(providerID))})`);
707
+ });
708
+ await ctx.provider.transform((editor) => {
709
+ editor.update(providerID, (provider) => {
710
+ const settings = provider.settings ?? {};
711
+ if (source.baseURL)
712
+ settings["baseURL"] = apiBase(source.baseURL);
713
+ else
714
+ delete settings["baseURL"];
715
+ if (source.apiKey)
716
+ settings["apiKey"] = source.apiKey;
717
+ else
718
+ delete settings["apiKey"];
719
+ provider.settings = settings;
720
+ });
721
+ });
722
+ try {
723
+ await ctx.integration.transform((editor) => {
724
+ editor.update(PLEXUS_INTEGRATION_ID, (ref) => {
725
+ ref.name = PLEXUS_PROVIDER_NAME;
726
+ });
727
+ editor.method.update({
728
+ integrationID: PLEXUS_INTEGRATION_ID,
729
+ method: {
730
+ type: "key",
731
+ label: "Plexus API key",
732
+ form: [
733
+ {
734
+ type: "string",
735
+ key: PLEXUS_BASE_URL_OPTION,
736
+ title: "Plexus base URL",
737
+ description: "Plexus root URL (https://host or https://host/v1)",
738
+ placeholder: "https://plexus.example.com",
739
+ required: true
740
+ }
741
+ ]
742
+ }
743
+ });
744
+ });
745
+ } catch (e) {
746
+ log.warn(`Integration transform failed (non-fatal): ${String(e)}`);
747
+ }
748
+ await ctx.command.transform((editor) => {
749
+ editor.add({
750
+ name: PLEXUS_REFRESH_COMMAND,
751
+ description: "Refresh Plexus models from the live server",
752
+ execute: async ({ sessionID, delivery }) => {
753
+ lastRefresh = null;
754
+ await reloadSource(true);
755
+ await ctx.provider.reload();
756
+ const count = source.models.length;
757
+ const placeholderOnly = count === 1 && source.models[0]?.id === PLACEHOLDER_MODEL_ID;
758
+ 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}.`;
759
+ log.info(text);
760
+ await ctx.session.synthetic({
761
+ sessionID,
762
+ text,
763
+ description: text,
764
+ delivery,
765
+ resume: false
755
766
  });
756
767
  }
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
- }
768
+ });
769
+ });
770
+ (async () => {
771
+ let pending = null;
772
+ for await (const event of ctx.event.subscribe()) {
773
+ const type = event.type;
774
+ if (type !== "credential.updated" && type !== "credential.switched")
775
+ continue;
776
+ if (pending)
777
+ continue;
778
+ pending = (async () => {
779
+ try {
817
780
  lastRefresh = null;
818
- return {
819
- type: "success",
820
- provider: PLEXUS_PROVIDER_ID,
821
- key: apiKey,
822
- metadata: { [AUTH_METADATA_BASE_URL]: baseURL }
823
- };
781
+ await reloadSource(true);
782
+ await ctx.provider.reload();
783
+ log.info(`Credentials changed (${type}); reloaded ${source.models.length} model(s)`);
784
+ } catch (e) {
785
+ log.warn(`Reload after credential change failed: ${String(e)}`);
786
+ } finally {
787
+ pending = null;
824
788
  }
825
- }
826
- ]
827
- }
828
- };
829
- };
789
+ })();
790
+ }
791
+ })().catch((e) => log.warn(`Credential watcher stopped: ${String(e)}`));
792
+ log.info(`Plexus V2 plugin ready: ${source.models.length} model(s)${source.baseURL ? ` from ${source.baseURL}` : " (unconfigured)"}`);
793
+ }
794
+ });
830
795
 
831
796
  // src/index.ts
832
- var plugin2 = {
833
- id: PLEXUS_PLUGIN_ID,
834
- server: PlexusProviderPlugin
835
- };
836
- var src_default = plugin2;
797
+ var src_default = plugin_default;
837
798
  export {
838
- CONFIG_HOOK_REFRESH_BUDGET_MS,
799
+ ANTHROPIC_PKG,
800
+ CACHE_VERSION,
839
801
  ENV_API_KEY,
840
802
  ENV_API_URL,
841
803
  ENV_BASE_URL,
842
- ENV_EXCLUDE_MODELS,
843
- ENV_IGNORE_MODELS,
844
- ENV_SUPPRESSED_MODELS,
845
- ENV_SUPPRESS_MODELS,
804
+ GOOGLE_PKG,
846
805
  MODELS_FETCH_TIMEOUT_MS,
847
- OPENAI_COMPATIBLE_NPM,
806
+ OPENAI_COMPATIBLE_PKG,
807
+ OPENAI_RESPONSES_PKG,
848
808
  PLACEHOLDER_MODEL_ID,
849
809
  PLEXUS_BASE_URL_OPTION,
850
- PLEXUS_LOG_SERVICE,
810
+ PLEXUS_INTEGRATION_ID,
851
811
  PLEXUS_PLUGIN_ID,
852
812
  PLEXUS_PROVIDER_ID,
853
813
  PLEXUS_PROVIDER_NAME,
854
814
  PLEXUS_REFRESH_COMMAND,
855
815
  PLEXUS_SUPPRESS_MODELS_OPTION,
856
- PlexusProviderPlugin,
857
816
  REFRESH_TTL_MS,
817
+ apiBase,
858
818
  buildModels,
859
819
  src_default as default,
820
+ filterCachedModels,
821
+ getDir,
822
+ getSuppressedModels,
823
+ modelsUrl,
860
824
  orderModelsByApiBase,
861
- toRuntimeModels
825
+ placeholderModel,
826
+ readCachedModels,
827
+ resolveConfig,
828
+ resolveConfigTemplate,
829
+ rootURL,
830
+ trimURL,
831
+ writeCache
862
832
  };