@mcowger/pi-plexus 1.4.0 → 1.4.2

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 +139 -6
  2. package/package.json +1 -1
package/dist/extension.js CHANGED
@@ -474,12 +474,95 @@ function getSuppressedModels() {
474
474
 
475
475
  // src/cache.ts
476
476
  import { mkdir as mkdir2, writeFile as writeFile2, readFile } from "fs/promises";
477
- import { existsSync as existsSync2 } from "fs";
477
+ import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
478
478
  import { join as join2 } from "path";
479
479
  import { getAgentDir as getAgentDir2 } from "@earendil-works/pi-coding-agent";
480
480
  var getCacheDir = () => join2(getAgentDir2(), "extensions", "plexus");
481
+ var getModelsCachePath = () => join2(getCacheDir(), "plexus-models-cache.json");
481
482
  var getRawResponsePath = () => join2(getCacheDir(), "plexus-models-response.json");
482
483
  var getEtagPath = () => join2(getCacheDir(), "plexus-models-etag.txt");
484
+ var getModelsStorePath = () => join2(getAgentDir2(), "models-store.json");
485
+ function isPlexusModelDescriptor(value) {
486
+ if (!value || typeof value !== "object" || Array.isArray(value))
487
+ return false;
488
+ const model = value;
489
+ const cost = model["cost"];
490
+ return typeof model["id"] === "string" && typeof model["name"] === "string" && typeof model["preferredApi"] === "string" && model["provider"] === "plexus" && typeof model["baseUrl"] === "string" && typeof model["reasoning"] === "boolean" && Array.isArray(model["input"]) && typeof model["contextWindow"] === "number" && typeof model["maxTokens"] === "number" && !!cost && typeof cost === "object" && !Array.isArray(cost) && typeof cost["input"] === "number" && typeof cost["output"] === "number" && typeof cost["cacheRead"] === "number" && typeof cost["cacheWrite"] === "number";
491
+ }
492
+ function parseCacheData(raw) {
493
+ try {
494
+ const parsed = JSON.parse(raw);
495
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
496
+ return null;
497
+ const obj = parsed;
498
+ if (!Array.isArray(obj["models"]) || !obj["models"].every(isPlexusModelDescriptor))
499
+ return null;
500
+ return {
501
+ models: obj["models"],
502
+ timestamp: typeof obj["timestamp"] === "number" ? obj["timestamp"] : 0,
503
+ etag: typeof obj["etag"] === "string" ? obj["etag"] : undefined
504
+ };
505
+ } catch {
506
+ return null;
507
+ }
508
+ }
509
+ function parseModelsStoreData(raw) {
510
+ try {
511
+ const parsed = JSON.parse(raw);
512
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
513
+ return null;
514
+ const obj = parsed;
515
+ const plexusObj = obj["plexus"];
516
+ if (!plexusObj)
517
+ return null;
518
+ let modelsList = null;
519
+ let checkedAt = 0;
520
+ if (Array.isArray(plexusObj)) {
521
+ modelsList = plexusObj;
522
+ } else if (typeof plexusObj === "object" && plexusObj !== null) {
523
+ const pObj = plexusObj;
524
+ if (Array.isArray(pObj["models"])) {
525
+ modelsList = pObj["models"];
526
+ }
527
+ if (typeof pObj["checkedAt"] === "number") {
528
+ checkedAt = pObj["checkedAt"];
529
+ }
530
+ }
531
+ if (!modelsList)
532
+ return null;
533
+ return {
534
+ piModels: modelsList,
535
+ timestamp: checkedAt
536
+ };
537
+ } catch {
538
+ return null;
539
+ }
540
+ }
541
+ function readCachedModelsSync() {
542
+ try {
543
+ const cachePath = getModelsCachePath();
544
+ if (existsSync2(cachePath)) {
545
+ const cache = parseCacheData(readFileSync2(cachePath, "utf8"));
546
+ if (cache)
547
+ return cache;
548
+ }
549
+ const storePath = getModelsStorePath();
550
+ if (existsSync2(storePath)) {
551
+ const storeCache = parseModelsStoreData(readFileSync2(storePath, "utf8"));
552
+ if (storeCache)
553
+ return storeCache;
554
+ }
555
+ return null;
556
+ } catch {
557
+ return null;
558
+ }
559
+ }
560
+ async function writeCachedModels(models, etag) {
561
+ await mkdir2(getCacheDir(), { recursive: true });
562
+ const payload = { models, timestamp: Date.now(), etag };
563
+ await writeFile2(getModelsCachePath(), `${JSON.stringify(payload, null, 2)}
564
+ `, "utf8");
565
+ }
483
566
  async function writeRawResponse(data) {
484
567
  await mkdir2(getCacheDir(), { recursive: true });
485
568
  await writeFile2(getRawResponsePath(), `${JSON.stringify(data, null, 2)}
@@ -487,6 +570,9 @@ async function writeRawResponse(data) {
487
570
  }
488
571
  async function readCachedEtag() {
489
572
  try {
573
+ const cache = readCachedModelsSync();
574
+ if (cache?.etag)
575
+ return cache.etag;
490
576
  const p = getEtagPath();
491
577
  if (!existsSync2(p))
492
578
  return;
@@ -530,6 +616,7 @@ async function writeLogLine(message, data) {
530
616
 
531
617
  // src/mapper.ts
532
618
  import { getModel } from "@earendil-works/pi-ai/compat";
619
+ var MINIMUM_OUTPUT_TOKENS = 8192;
533
620
  function descriptorToPiModel(descriptor) {
534
621
  let builtinModel;
535
622
  if (descriptor.piProvider && descriptor.piModel) {
@@ -575,7 +662,7 @@ function descriptorToPiModel(descriptor) {
575
662
  input: descriptor.input,
576
663
  cost,
577
664
  contextWindow: descriptor.contextWindow,
578
- maxTokens: descriptor.maxTokens,
665
+ maxTokens: Math.max(descriptor.maxTokens, MINIMUM_OUTPUT_TOKENS),
579
666
  ...builtinModel?.thinkingLevelMap !== undefined ? { thinkingLevelMap: builtinModel.thinkingLevelMap } : {},
580
667
  ...builtinModel?.headers !== undefined ? { headers: builtinModel.headers } : {},
581
668
  ...compat !== undefined ? { compat } : {}
@@ -625,17 +712,59 @@ var PROVIDER_API_KEY_TEMPLATE = "${PLEXUS_API_KEY}";
625
712
  var PLEXUS_CREDENTIAL_EXPIRES_AT = 253402300799000;
626
713
  var PLACEHOLDER_BASE_URL = "http://localhost/v1";
627
714
  var currentModels = [];
715
+ function cachedDescriptorsToPiModels(descriptors, suppressPatterns) {
716
+ return descriptors.filter((descriptor) => !isModelSuppressed({ id: descriptor.id, name: descriptor.name }, suppressPatterns)).map(descriptorToPiModel);
717
+ }
718
+ function enforceMinimumOutputTokens(payload) {
719
+ if (!payload || typeof payload !== "object" || Array.isArray(payload))
720
+ return payload;
721
+ const next = { ...payload };
722
+ let changed = false;
723
+ for (const field of ["max_completion_tokens", "max_tokens", "max_output_tokens"]) {
724
+ const value = next[field];
725
+ if (typeof value === "number" && Number.isFinite(value) && value < MINIMUM_OUTPUT_TOKENS) {
726
+ next[field] = MINIMUM_OUTPUT_TOKENS;
727
+ changed = true;
728
+ }
729
+ }
730
+ const generationConfig = next["generationConfig"];
731
+ if (generationConfig && typeof generationConfig === "object" && !Array.isArray(generationConfig)) {
732
+ const maxOutputTokens = generationConfig["maxOutputTokens"];
733
+ if (typeof maxOutputTokens === "number" && Number.isFinite(maxOutputTokens) && maxOutputTokens < MINIMUM_OUTPUT_TOKENS) {
734
+ next["generationConfig"] = {
735
+ ...generationConfig,
736
+ maxOutputTokens: MINIMUM_OUTPUT_TOKENS
737
+ };
738
+ changed = true;
739
+ }
740
+ }
741
+ return changed ? next : payload;
742
+ }
628
743
  function plexusExtension(pi) {
629
744
  const envApiKey = getEnvApiKey();
630
745
  const startupBaseUrl = getBaseUrl();
631
- log("startup", { baseUrl: startupBaseUrl, hasEnvApiKey: !!envApiKey });
746
+ const suppressPatterns = getSuppressedModels();
747
+ const cached = readCachedModelsSync();
748
+ let startupModels = [];
749
+ if (cached?.models && cached.models.length > 0) {
750
+ startupModels = cachedDescriptorsToPiModels(cached.models, suppressPatterns);
751
+ } else if (cached?.piModels && cached.piModels.length > 0) {
752
+ startupModels = cached.piModels.filter((m) => !isModelSuppressed({ id: m.id, name: m.name }, suppressPatterns));
753
+ }
754
+ currentModels = startupModels;
755
+ pi.on("before_provider_request", (event, ctx) => ctx.model?.provider === PROVIDER_NAME ? enforceMinimumOutputTokens(event.payload) : undefined);
756
+ log("startup", {
757
+ baseUrl: startupBaseUrl,
758
+ hasEnvApiKey: !!envApiKey,
759
+ cachedModelCount: startupModels.length
760
+ });
632
761
  pi.on("message_end", (event) => normalizeMalformedFunctionCall(event.message, PROVIDER_NAME));
633
762
  pi.registerProvider(PROVIDER_NAME, {
634
763
  api: "openai-completions",
635
764
  ...envApiKey ? { apiKey: PROVIDER_API_KEY_TEMPLATE } : {},
636
765
  authHeader: true,
637
766
  baseUrl: startupBaseUrl ?? PLACEHOLDER_BASE_URL,
638
- models: [],
767
+ models: startupModels,
639
768
  refreshModels: refreshPlexusModels,
640
769
  oauth: createPlexusLoginProvider()
641
770
  });
@@ -705,7 +834,8 @@ async function refreshPlexusModels(context) {
705
834
  if (restored)
706
835
  return restored;
707
836
  }
708
- const piModels = convertDescriptors(apiModels, baseUrl, suppress).map(descriptorToPiModel);
837
+ const descriptors = convertDescriptors(apiModels, baseUrl, suppress);
838
+ const piModels = descriptors.map(descriptorToPiModel);
709
839
  const published = await context.publish({
710
840
  persist: { models: piModels, checkedAt: Date.now() },
711
841
  update: () => {
@@ -716,6 +846,7 @@ async function refreshPlexusModels(context) {
716
846
  log("refreshModels: publication superseded by a newer refresh", {});
717
847
  }
718
848
  await Promise.all([
849
+ writeCachedModels(descriptors, etag),
719
850
  writeCachedEtag(etag),
720
851
  raw ? writeRawResponse(raw) : Promise.resolve()
721
852
  ]);
@@ -828,5 +959,7 @@ async function handleSetDefaultModel(pi, ctx, requestedModelId) {
828
959
  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");
829
960
  }
830
961
  export {
831
- plexusExtension as default
962
+ enforceMinimumOutputTokens,
963
+ plexusExtension as default,
964
+ cachedDescriptorsToPiModels
832
965
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mcowger/pi-plexus",
3
- "version": "1.4.0",
3
+ "version": "1.4.2",
4
4
  "description": "Plexus AI proxy plugin for the pi coding agent",
5
5
  "type": "module",
6
6
  "files": [