@mcowger/pi-plexus 1.3.3 → 1.3.4

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 (2) hide show
  1. package/dist/extension.js +73 -96
  2. package/package.json +5 -5
package/dist/extension.js CHANGED
@@ -352,45 +352,11 @@ function getBaseUrl() {
352
352
  }
353
353
 
354
354
  // src/cache.ts
355
- import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
356
355
  import { mkdir as mkdir2, writeFile as writeFile2 } from "fs/promises";
357
356
  import { join as join2 } from "path";
358
357
  import { getAgentDir as getAgentDir2 } from "@earendil-works/pi-coding-agent";
359
358
  var getCacheDir = () => join2(getAgentDir2(), "extensions", "plexus");
360
- var getModelsCachePath = () => join2(getCacheDir(), "plexus-models-cache.json");
361
359
  var getRawResponsePath = () => join2(getCacheDir(), "plexus-models-response.json");
362
- function parseCacheData(raw) {
363
- try {
364
- const parsed = JSON.parse(raw);
365
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
366
- return null;
367
- const obj = parsed;
368
- if (!Array.isArray(obj["models"]))
369
- return null;
370
- return {
371
- models: obj["models"],
372
- timestamp: typeof obj["timestamp"] === "number" ? obj["timestamp"] : 0
373
- };
374
- } catch {
375
- return null;
376
- }
377
- }
378
- function readCachedModelsSync() {
379
- try {
380
- const p = getModelsCachePath();
381
- if (!existsSync2(p))
382
- return null;
383
- return parseCacheData(readFileSync2(p, "utf8"));
384
- } catch {
385
- return null;
386
- }
387
- }
388
- async function writeCachedModels(models) {
389
- await mkdir2(getCacheDir(), { recursive: true });
390
- const payload = { models, timestamp: Date.now() };
391
- await writeFile2(getModelsCachePath(), `${JSON.stringify(payload, null, 2)}
392
- `, "utf8");
393
- }
394
360
  async function writeRawResponse(data) {
395
361
  await mkdir2(getCacheDir(), { recursive: true });
396
362
  await writeFile2(getRawResponsePath(), `${JSON.stringify(data, null, 2)}
@@ -479,33 +445,33 @@ function descriptorToPiModel(descriptor) {
479
445
  var PROVIDER_NAME = "plexus";
480
446
  var PROVIDER_API_KEY_TEMPLATE = "${PLEXUS_API_KEY}";
481
447
  var PLEXUS_CREDENTIAL_EXPIRES_AT = 253402300799000;
448
+ var PLACEHOLDER_BASE_URL = "http://localhost/v1";
482
449
  var currentModels = [];
483
- function plexusExtension(pi) {
484
- const cached = readCachedModelsSync();
485
- const startupBaseUrl = getBaseUrl() ?? "http://localhost/v1";
486
- const startupModels = cached?.models.map(descriptorToPiModel) ?? [];
487
- log("startup", {
488
- cachedModelCount: startupModels.length,
489
- startupBaseUrl
490
- });
450
+ async function plexusExtension(pi) {
451
+ const envApiKey = getEnvApiKey();
452
+ const startupBaseUrl = getBaseUrl();
453
+ const modelsUrl = getModelsUrl();
454
+ log("startup", { baseUrl: startupBaseUrl, hasEnvApiKey: !!envApiKey });
455
+ let startupModels = [];
456
+ if (envApiKey && modelsUrl && startupBaseUrl && process.env.PI_OFFLINE === undefined) {
457
+ try {
458
+ const { models: apiModels, raw } = await fetchPlexusModels(envApiKey, modelsUrl);
459
+ startupModels = convertDescriptors(apiModels, startupBaseUrl).map(descriptorToPiModel);
460
+ currentModels = startupModels;
461
+ await writeRawResponse(raw);
462
+ log("startup: fetched", { count: startupModels.length });
463
+ } catch (error) {
464
+ log("startup: fetch failed", { error: String(error) });
465
+ }
466
+ }
491
467
  pi.registerProvider(PROVIDER_NAME, {
492
468
  api: "openai-completions",
493
- apiKey: PROVIDER_API_KEY_TEMPLATE,
469
+ ...envApiKey ? { apiKey: PROVIDER_API_KEY_TEMPLATE } : {},
494
470
  authHeader: true,
495
- baseUrl: startupBaseUrl,
471
+ baseUrl: startupBaseUrl ?? PLACEHOLDER_BASE_URL,
496
472
  models: startupModels,
497
- oauth: createPlexusLoginProvider(pi)
498
- });
499
- currentModels = startupModels;
500
- pi.on("session_start", async (_event, ctx) => {
501
- const apiKey = await ctx.modelRegistry.authStorage.getApiKey(PROVIDER_NAME) ?? getEnvApiKey();
502
- const baseUrl = getBaseUrl();
503
- log("session_start", { hasApiKey: !!apiKey, baseUrl });
504
- if (!apiKey || !baseUrl) {
505
- log("session_start: no auth configured, skipping refresh");
506
- return;
507
- }
508
- await doRefresh(pi, apiKey, ctx);
473
+ refreshModels: refreshPlexusModels,
474
+ oauth: createPlexusLoginProvider()
509
475
  });
510
476
  pi.registerCommand("plexus", {
511
477
  description: "Plexus provider commands: refresh, set-default-model (setup: /login plexus)",
@@ -532,7 +498,7 @@ function plexusExtension(pi) {
532
498
  const trimmed = args.trim();
533
499
  const sub = trimmed.toLowerCase();
534
500
  if (sub === "refresh" || sub === "") {
535
- await handleRefresh(pi, ctx);
501
+ await handleRefresh(ctx);
536
502
  return;
537
503
  }
538
504
  if (sub === "set-default-model" || sub.startsWith("set-default-model ")) {
@@ -543,7 +509,52 @@ function plexusExtension(pi) {
543
509
  }
544
510
  });
545
511
  }
546
- function createPlexusLoginProvider(pi) {
512
+ async function refreshPlexusModels(context) {
513
+ const baseUrl = getBaseUrl();
514
+ const modelsUrl = getModelsUrl();
515
+ const apiKey = credentialApiKey(context.credential) ?? getEnvApiKey() ?? undefined;
516
+ if (!context.allowNetwork || !apiKey || !modelsUrl || !baseUrl) {
517
+ if (currentModels.length > 0) {
518
+ await context.store.write({ models: currentModels, checkedAt: Date.now() });
519
+ return currentModels;
520
+ }
521
+ const restored = await restoreStoredModels(context);
522
+ if (restored)
523
+ return restored;
524
+ throw new Error(!modelsUrl || !baseUrl ? "Plexus base URL not configured. Run /login plexus first." : "No Plexus API key configured. Run /login plexus first.");
525
+ }
526
+ try {
527
+ const { models: apiModels, raw } = await fetchPlexusModels(apiKey, modelsUrl);
528
+ const piModels = convertDescriptors(apiModels, baseUrl).map(descriptorToPiModel);
529
+ await Promise.all([
530
+ context.store.write({ models: piModels, checkedAt: Date.now() }),
531
+ writeRawResponse(raw)
532
+ ]);
533
+ currentModels = piModels;
534
+ log("refreshModels: fetched", { count: piModels.length });
535
+ return piModels;
536
+ } catch (error) {
537
+ log("refreshModels: fetch failed", { error: String(error) });
538
+ throw error;
539
+ }
540
+ }
541
+ async function restoreStoredModels(context) {
542
+ const stored = await context.store.read();
543
+ if (!stored || stored.models.length === 0)
544
+ return;
545
+ const models = stored.models;
546
+ currentModels = models;
547
+ log("refreshModels: restored from store", { count: models.length });
548
+ return models;
549
+ }
550
+ function credentialApiKey(credential) {
551
+ if (!credential)
552
+ return;
553
+ if (credential.type === "api_key")
554
+ return credential.key || undefined;
555
+ return String(credential.access || credential.refresh || "") || undefined;
556
+ }
557
+ function createPlexusLoginProvider() {
547
558
  return {
548
559
  name: "Plexus",
549
560
  async login(callbacks) {
@@ -557,8 +568,6 @@ function createPlexusLoginProvider(pi) {
557
568
  if (!apiKey)
558
569
  throw new Error("Plexus API key is required.");
559
570
  await saveBaseUrl(baseUrl);
560
- callbacks.onProgress?.("Refreshing Plexus models...");
561
- await doRefresh(pi, apiKey, null);
562
571
  return {
563
572
  access: apiKey,
564
573
  refresh: apiKey,
@@ -581,14 +590,15 @@ function createPlexusLoginProvider(pi) {
581
590
  }
582
591
  };
583
592
  }
584
- async function handleRefresh(pi, ctx) {
585
- const apiKey = await ctx.modelRegistry.authStorage.getApiKey(PROVIDER_NAME) ?? getEnvApiKey();
593
+ async function handleRefresh(ctx) {
594
+ const apiKey = await ctx.modelRegistry.getApiKeyForProvider(PROVIDER_NAME);
586
595
  if (!apiKey) {
587
596
  ctx.ui.notify("No Plexus API key configured. Run /login plexus first.", "error");
588
597
  return;
589
598
  }
590
599
  ctx.ui.notify("Refreshing Plexus models\u2026", "info");
591
- await doRefresh(pi, apiKey, ctx);
600
+ await ctx.modelRegistry.refresh();
601
+ ctx.ui.notify(currentModels.length > 0 ? `Refreshed ${currentModels.length} Plexus models` : "Refresh finished but no Plexus models are available. Check the Plexus server and /login plexus.", currentModels.length > 0 ? "info" : "warning");
592
602
  }
593
603
  async function handleSetDefaultModel(pi, ctx, requestedModelId) {
594
604
  let modelId = requestedModelId;
@@ -614,39 +624,6 @@ async function handleSetDefaultModel(pi, ctx, requestedModelId) {
614
624
  const active = await pi.setModel(registryModel);
615
625
  ctx.ui.notify(active ? `Plexus model selected: ${model.id}.` : `Plexus model ${model.id} was saved but could not be selected in this session.`, active ? "info" : "warning");
616
626
  }
617
- async function doRefresh(pi, apiKey, ctx) {
618
- const modelsUrl = getModelsUrl();
619
- const baseUrl = getBaseUrl();
620
- if (!modelsUrl || !baseUrl) {
621
- if (ctx)
622
- ctx.ui.notify("Plexus base URL not configured. Run /login plexus first.", "warning");
623
- log("doRefresh: no base URL configured");
624
- return;
625
- }
626
- try {
627
- const { models: apiModels, raw } = await fetchPlexusModels(apiKey, modelsUrl);
628
- const descriptors = convertDescriptors(apiModels, baseUrl);
629
- const piModels = descriptors.map(descriptorToPiModel);
630
- await Promise.all([writeCachedModels(descriptors), writeRawResponse(raw)]);
631
- currentModels = piModels;
632
- pi.registerProvider(PROVIDER_NAME, {
633
- api: "openai-completions",
634
- apiKey: PROVIDER_API_KEY_TEMPLATE,
635
- authHeader: true,
636
- baseUrl,
637
- models: piModels,
638
- oauth: createPlexusLoginProvider(pi)
639
- });
640
- log("doRefresh: registered", { count: piModels.length });
641
- if (ctx)
642
- ctx.ui.notify(`Refreshed ${piModels.length} Plexus models`, "info");
643
- } catch (error) {
644
- log("doRefresh: failed", { error: String(error) });
645
- if (ctx) {
646
- ctx.ui.notify(`Refresh failed: ${error instanceof Error ? error.message : String(error)}`, "error");
647
- }
648
- }
649
- }
650
627
  export {
651
628
  plexusExtension as default
652
629
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mcowger/pi-plexus",
3
- "version": "1.3.3",
3
+ "version": "1.3.4",
4
4
  "description": "Plexus AI proxy plugin for the pi coding agent",
5
5
  "type": "module",
6
6
  "files": [
@@ -25,12 +25,12 @@
25
25
  "build": "bun run build.ts"
26
26
  },
27
27
  "peerDependencies": {
28
- "@earendil-works/pi-ai": ">=0.80.6",
29
- "@earendil-works/pi-coding-agent": ">=0.80.6"
28
+ "@earendil-works/pi-ai": ">=0.80.8",
29
+ "@earendil-works/pi-coding-agent": ">=0.80.8"
30
30
  },
31
31
  "devDependencies": {
32
- "@earendil-works/pi-ai": "^0.80.6",
33
- "@earendil-works/pi-coding-agent": "^0.80.6",
32
+ "@earendil-works/pi-ai": "^0.80.9",
33
+ "@earendil-works/pi-coding-agent": "^0.80.9",
34
34
  "@types/bun": "latest"
35
35
  },
36
36
  "repository": {