@mcowger/pi-plexus 1.3.10 → 1.4.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 (2) hide show
  1. package/dist/extension.js +138 -97
  2. package/package.json +5 -5
package/dist/extension.js CHANGED
@@ -307,9 +307,10 @@ function detectOpenAICompletionsCompat(providerName, baseUrl) {
307
307
  return compat;
308
308
  }
309
309
  var DEFAULT_MODELS_FETCH_TIMEOUT_MS = 1e4;
310
- async function fetchPlexusModels(apiKey, modelsUrl, timeoutMs = DEFAULT_MODELS_FETCH_TIMEOUT_MS, etag) {
310
+ async function fetchPlexusModels(apiKey, modelsUrl, timeoutMs = DEFAULT_MODELS_FETCH_TIMEOUT_MS, etag, signal) {
311
311
  const controller = new AbortController;
312
312
  const timer = setTimeout(() => controller.abort(), timeoutMs);
313
+ const requestSignal = signal ? AbortSignal.any([signal, controller.signal]) : controller.signal;
313
314
  try {
314
315
  const headers = { Accept: "application/json" };
315
316
  if (apiKey)
@@ -318,7 +319,7 @@ async function fetchPlexusModels(apiKey, modelsUrl, timeoutMs = DEFAULT_MODELS_F
318
319
  headers["If-None-Match"] = etag;
319
320
  const res = await fetch(modelsUrl, {
320
321
  headers,
321
- signal: controller.signal
322
+ signal: requestSignal
322
323
  });
323
324
  if (res.status === 304) {
324
325
  return { models: [], notModified: true };
@@ -330,6 +331,8 @@ async function fetchPlexusModels(apiKey, modelsUrl, timeoutMs = DEFAULT_MODELS_F
330
331
  const responseEtag = res.headers.get("etag") ?? undefined;
331
332
  return { models: raw.data ?? [], raw, etag: responseEtag };
332
333
  } catch (err) {
334
+ if (signal?.aborted)
335
+ throw err;
333
336
  if (err instanceof Error && err.name === "AbortError") {
334
337
  throw new Error(`Plexus models fetch timed out after ${timeoutMs}ms`);
335
338
  }
@@ -471,12 +474,88 @@ function getSuppressedModels() {
471
474
 
472
475
  // src/cache.ts
473
476
  import { mkdir as mkdir2, writeFile as writeFile2, readFile } from "fs/promises";
474
- import { existsSync as existsSync2 } from "fs";
477
+ import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
475
478
  import { join as join2 } from "path";
476
479
  import { getAgentDir as getAgentDir2 } from "@earendil-works/pi-coding-agent";
477
480
  var getCacheDir = () => join2(getAgentDir2(), "extensions", "plexus");
481
+ var getModelsCachePath = () => join2(getCacheDir(), "plexus-models-cache.json");
478
482
  var getRawResponsePath = () => join2(getCacheDir(), "plexus-models-response.json");
479
483
  var getEtagPath = () => join2(getCacheDir(), "plexus-models-etag.txt");
484
+ var getModelsStorePath = () => join2(getAgentDir2(), "models-store.json");
485
+ function parseCacheData(raw) {
486
+ try {
487
+ const parsed = JSON.parse(raw);
488
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
489
+ return null;
490
+ const obj = parsed;
491
+ if (!Array.isArray(obj["models"]))
492
+ return null;
493
+ return {
494
+ models: obj["models"],
495
+ timestamp: typeof obj["timestamp"] === "number" ? obj["timestamp"] : 0,
496
+ etag: typeof obj["etag"] === "string" ? obj["etag"] : undefined
497
+ };
498
+ } catch {
499
+ return null;
500
+ }
501
+ }
502
+ function parseModelsStoreData(raw) {
503
+ try {
504
+ const parsed = JSON.parse(raw);
505
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
506
+ return null;
507
+ const obj = parsed;
508
+ const plexusObj = obj["plexus"];
509
+ if (!plexusObj)
510
+ return null;
511
+ let modelsList = null;
512
+ let checkedAt = 0;
513
+ if (Array.isArray(plexusObj)) {
514
+ modelsList = plexusObj;
515
+ } else if (typeof plexusObj === "object" && plexusObj !== null) {
516
+ const pObj = plexusObj;
517
+ if (Array.isArray(pObj["models"])) {
518
+ modelsList = pObj["models"];
519
+ }
520
+ if (typeof pObj["checkedAt"] === "number") {
521
+ checkedAt = pObj["checkedAt"];
522
+ }
523
+ }
524
+ if (!modelsList)
525
+ return null;
526
+ return {
527
+ piModels: modelsList,
528
+ timestamp: checkedAt
529
+ };
530
+ } catch {
531
+ return null;
532
+ }
533
+ }
534
+ function readCachedModelsSync() {
535
+ try {
536
+ const cachePath = getModelsCachePath();
537
+ if (existsSync2(cachePath)) {
538
+ const cache = parseCacheData(readFileSync2(cachePath, "utf8"));
539
+ if (cache)
540
+ return cache;
541
+ }
542
+ const storePath = getModelsStorePath();
543
+ if (existsSync2(storePath)) {
544
+ const storeCache = parseModelsStoreData(readFileSync2(storePath, "utf8"));
545
+ if (storeCache)
546
+ return storeCache;
547
+ }
548
+ return null;
549
+ } catch {
550
+ return null;
551
+ }
552
+ }
553
+ async function writeCachedModels(models, etag) {
554
+ await mkdir2(getCacheDir(), { recursive: true });
555
+ const payload = { models, timestamp: Date.now(), etag };
556
+ await writeFile2(getModelsCachePath(), `${JSON.stringify(payload, null, 2)}
557
+ `, "utf8");
558
+ }
480
559
  async function writeRawResponse(data) {
481
560
  await mkdir2(getCacheDir(), { recursive: true });
482
561
  await writeFile2(getRawResponsePath(), `${JSON.stringify(data, null, 2)}
@@ -484,6 +563,9 @@ async function writeRawResponse(data) {
484
563
  }
485
564
  async function readCachedEtag() {
486
565
  try {
566
+ const cache = readCachedModelsSync();
567
+ if (cache?.etag)
568
+ return cache.etag;
487
569
  const p = getEtagPath();
488
570
  if (!existsSync2(p))
489
571
  return;
@@ -579,80 +661,6 @@ function descriptorToPiModel(descriptor) {
579
661
  };
580
662
  }
581
663
 
582
- // src/gemini-toolcall-id.ts
583
- var GEMINI_3_PATTERN = /gemini-(?:live-)?3(?:\.\d+)?[-.]/i;
584
- var GEMINI_3_ALIASES = new Set(["gemini-flash-latest", "gemini-flash-lite-latest"]);
585
- function isGemini3Model(modelId) {
586
- return GEMINI_3_ALIASES.has(modelId) || GEMINI_3_PATTERN.test(modelId);
587
- }
588
- function createGeminiToolCallIdFixer() {
589
- let functionCallIds = [];
590
- let functionResponseIds = [];
591
- function onContext(messages) {
592
- const calls = [];
593
- const responses = [];
594
- for (const msg of messages) {
595
- if (msg.role === "assistant" && Array.isArray(msg.content)) {
596
- for (const block of msg.content) {
597
- if (block?.type === "toolCall" && typeof block.id === "string") {
598
- calls.push(block.id);
599
- }
600
- }
601
- } else if (msg.role === "toolResult" && typeof msg.toolCallId === "string") {
602
- responses.push({ id: msg.toolCallId, name: msg.toolName ?? "" });
603
- }
604
- }
605
- functionCallIds = calls;
606
- functionResponseIds = responses;
607
- }
608
- function onBeforeProviderRequest(payload) {
609
- const google = payload;
610
- if (!google || typeof google !== "object" || !Array.isArray(google.contents)) {
611
- return payload;
612
- }
613
- if (typeof google.model !== "string" || !isGemini3Model(google.model)) {
614
- return payload;
615
- }
616
- let callCursor = 0;
617
- let responseCursor = 0;
618
- let missing = 0;
619
- for (const content of google.contents) {
620
- if (!Array.isArray(content?.parts))
621
- continue;
622
- for (const part of content.parts) {
623
- if (part.functionCall && part.functionCall.id === undefined) {
624
- const id = functionCallIds[callCursor++];
625
- if (id !== undefined) {
626
- part.functionCall.id = id;
627
- } else {
628
- missing++;
629
- }
630
- } else if (part.functionResponse && part.functionResponse.id === undefined) {
631
- const entry = functionResponseIds[responseCursor++];
632
- if (entry !== undefined) {
633
- part.functionResponse.id = entry.id;
634
- if (part.functionResponse.name === undefined && entry.name) {
635
- part.functionResponse.name = entry.name;
636
- }
637
- } else {
638
- missing++;
639
- }
640
- }
641
- }
642
- }
643
- if (missing > 0) {
644
- log("gemini-toolcall-id: fewer captured ids than parts", {
645
- model: google.model,
646
- missing,
647
- capturedCalls: functionCallIds.length,
648
- capturedResponses: functionResponseIds.length
649
- });
650
- }
651
- return payload;
652
- }
653
- return { onContext, onBeforeProviderRequest };
654
- }
655
-
656
664
  // src/gemini-malformed-retry.ts
657
665
  var MALFORMED_LEAK_PATTERN = /(?:print\()?call:\s*default_api[.:]|default_api\.\w+\s*\(/;
658
666
  var MALFORMED_DIAGNOSTIC_PATTERN = /\bmalformed[\s_-]?function[\s_-]?call\b/i;
@@ -699,13 +707,19 @@ var currentModels = [];
699
707
  function plexusExtension(pi) {
700
708
  const envApiKey = getEnvApiKey();
701
709
  const startupBaseUrl = getBaseUrl();
702
- log("startup", { baseUrl: startupBaseUrl, hasEnvApiKey: !!envApiKey });
703
- const geminiToolCallIdFixer = createGeminiToolCallIdFixer();
704
- pi.on("context", (event) => {
705
- geminiToolCallIdFixer.onContext(event.messages);
706
- });
707
- pi.on("before_provider_request", (event) => {
708
- return geminiToolCallIdFixer.onBeforeProviderRequest(event.payload);
710
+ const suppressPatterns = getSuppressedModels();
711
+ const cached = readCachedModelsSync();
712
+ let startupModels = [];
713
+ if (cached?.models && cached.models.length > 0) {
714
+ startupModels = convertDescriptors(cached.models, startupBaseUrl ?? PLACEHOLDER_BASE_URL, suppressPatterns).map(descriptorToPiModel);
715
+ } else if (cached?.piModels && cached.piModels.length > 0) {
716
+ startupModels = cached.piModels.filter((m) => !isModelSuppressed({ id: m.id, name: m.name }, suppressPatterns));
717
+ }
718
+ currentModels = startupModels;
719
+ log("startup", {
720
+ baseUrl: startupBaseUrl,
721
+ hasEnvApiKey: !!envApiKey,
722
+ cachedModelCount: startupModels.length
709
723
  });
710
724
  pi.on("message_end", (event) => normalizeMalformedFunctionCall(event.message, PROVIDER_NAME));
711
725
  pi.registerProvider(PROVIDER_NAME, {
@@ -713,7 +727,7 @@ function plexusExtension(pi) {
713
727
  ...envApiKey ? { apiKey: PROVIDER_API_KEY_TEMPLATE } : {},
714
728
  authHeader: true,
715
729
  baseUrl: startupBaseUrl ?? PLACEHOLDER_BASE_URL,
716
- models: [],
730
+ models: startupModels,
717
731
  refreshModels: refreshPlexusModels,
718
732
  oauth: createPlexusLoginProvider()
719
733
  });
@@ -758,34 +772,47 @@ async function refreshPlexusModels(context) {
758
772
  const modelsUrl = getModelsUrl();
759
773
  const apiKey = credentialApiKey(context.credential) ?? getEnvApiKey() ?? undefined;
760
774
  const suppress = getSuppressedModels();
761
- const storedEtag = await readCachedEtag();
762
775
  if (!context.allowNetwork || !apiKey || !modelsUrl || !baseUrl) {
763
776
  if (currentModels.length > 0) {
764
777
  const filteredCurrent = currentModels.filter((m) => !isModelSuppressed({ id: m.id, name: m.name }, suppress));
765
- currentModels = filteredCurrent;
766
- await context.store.write({ models: currentModels, checkedAt: Date.now() });
767
- return currentModels;
778
+ await context.publish({
779
+ persist: { models: filteredCurrent, checkedAt: Date.now() },
780
+ update: () => {
781
+ currentModels = filteredCurrent;
782
+ }
783
+ });
784
+ return filteredCurrent;
768
785
  }
769
786
  const restored = await restoreStoredModels(context);
770
787
  if (restored)
771
788
  return restored;
772
789
  throw new Error(!modelsUrl || !baseUrl ? "Plexus base URL not configured. Run /login plexus first." : "No Plexus API key configured. Run /login plexus first.");
773
790
  }
791
+ const storedEtag = await readCachedEtag();
774
792
  try {
775
- const { models: apiModels, raw, etag, notModified } = await fetchPlexusModels(apiKey, modelsUrl, undefined, storedEtag);
793
+ const { models: apiModels, raw, etag, notModified } = await fetchPlexusModels(apiKey, modelsUrl, undefined, storedEtag, context.signal);
776
794
  if (notModified) {
777
795
  log("refreshModels: not modified", { etag: storedEtag });
778
796
  const restored = await restoreStoredModels(context);
779
797
  if (restored)
780
798
  return restored;
781
799
  }
782
- const piModels = convertDescriptors(apiModels, baseUrl, suppress).map(descriptorToPiModel);
800
+ const descriptors = convertDescriptors(apiModels, baseUrl, suppress);
801
+ const piModels = descriptors.map(descriptorToPiModel);
802
+ const published = await context.publish({
803
+ persist: { models: piModels, checkedAt: Date.now() },
804
+ update: () => {
805
+ currentModels = piModels;
806
+ }
807
+ });
808
+ if (!published) {
809
+ log("refreshModels: publication superseded by a newer refresh", {});
810
+ }
783
811
  await Promise.all([
784
- context.store.write({ models: piModels, checkedAt: Date.now() }),
812
+ writeCachedModels(descriptors, etag),
785
813
  writeCachedEtag(etag),
786
814
  raw ? writeRawResponse(raw) : Promise.resolve()
787
815
  ]);
788
- currentModels = piModels;
789
816
  log("refreshModels: fetched", { count: piModels.length });
790
817
  return piModels;
791
818
  } catch (error) {
@@ -794,12 +821,16 @@ async function refreshPlexusModels(context) {
794
821
  }
795
822
  }
796
823
  async function restoreStoredModels(context) {
797
- const stored = await context.store.read();
824
+ const stored = context.stored;
798
825
  if (!stored || stored.models.length === 0)
799
826
  return;
800
827
  const suppress = getSuppressedModels();
801
828
  const models = stored.models.filter((m) => !isModelSuppressed({ id: m.id, name: m.name }, suppress));
802
- currentModels = models;
829
+ await context.publish({
830
+ update: () => {
831
+ currentModels = models;
832
+ }
833
+ });
803
834
  log("refreshModels: restored from store", { count: models.length });
804
835
  return models;
805
836
  }
@@ -831,7 +862,8 @@ function createPlexusLoginProvider() {
831
862
  plexusBaseUrl: baseUrl
832
863
  };
833
864
  },
834
- async refreshToken(credentials) {
865
+ async refreshToken(credentials, signal) {
866
+ signal.throwIfAborted();
835
867
  return { ...credentials, expires: PLEXUS_CREDENTIAL_EXPIRES_AT };
836
868
  },
837
869
  getApiKey(credentials) {
@@ -853,7 +885,16 @@ async function handleRefresh(ctx) {
853
885
  return;
854
886
  }
855
887
  ctx.ui.notify("Refreshing Plexus models\u2026", "info");
856
- await ctx.modelRegistry.refresh();
888
+ const result = await ctx.modelRegistry.refresh({ providers: [PROVIDER_NAME], force: true });
889
+ if (result.aborted) {
890
+ ctx.ui.notify("Plexus model refresh was cancelled.", "warning");
891
+ return;
892
+ }
893
+ const refreshError = result.errors.get(PROVIDER_NAME);
894
+ if (refreshError) {
895
+ ctx.ui.notify(`Plexus model refresh failed: ${refreshError.message}`, "error");
896
+ return;
897
+ }
857
898
  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");
858
899
  }
859
900
  async function handleSetDefaultModel(pi, ctx, requestedModelId) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mcowger/pi-plexus",
3
- "version": "1.3.10",
3
+ "version": "1.4.1",
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.81.0",
29
- "@earendil-works/pi-coding-agent": ">=0.81.0"
28
+ "@earendil-works/pi-ai": ">=0.84.0",
29
+ "@earendil-works/pi-coding-agent": ">=0.84.0"
30
30
  },
31
31
  "devDependencies": {
32
- "@earendil-works/pi-ai": "^0.81.0",
33
- "@earendil-works/pi-coding-agent": "^0.81.0",
32
+ "@earendil-works/pi-ai": "^0.84.0",
33
+ "@earendil-works/pi-coding-agent": "^0.84.0",
34
34
  "@types/bun": "latest"
35
35
  },
36
36
  "repository": {