@mcowger/pi-plexus 1.12.0 → 1.13.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.
Files changed (2) hide show
  1. package/dist/extension.js +679 -550
  2. package/package.json +1 -1
package/dist/extension.js CHANGED
@@ -1,55 +1,10 @@
1
1
  // @bun
2
- // ../plexus-models/src/suppress.ts
3
- function parseSuppressionPatterns(raw) {
4
- if (!raw)
5
- return [];
6
- const items = Array.isArray(raw) ? raw : raw.split(/[\n,;]+/);
7
- return items.map((s) => s.trim()).filter((s) => s.length > 0);
8
- }
9
- function getEnvSuppressedModels() {
10
- const env = typeof process !== "undefined" && process?.env ? process.env : {};
11
- const raw = env.PLEXUS_SUPPRESS_MODELS ?? env.PLEXUS_EXCLUDE_MODELS;
12
- return parseSuppressionPatterns(raw);
13
- }
14
- function isModelSuppressed(model, patterns) {
15
- const envPatterns = getEnvSuppressedModels();
16
- const explicitPatterns = parseSuppressionPatterns(patterns);
17
- const allPatterns = [...envPatterns, ...explicitPatterns];
18
- if (allPatterns.length === 0)
19
- return false;
20
- const id = model.id.toLowerCase();
21
- const name = (model.name ?? "").toLowerCase();
22
- const shortId = id.includes("/") ? id.split("/").pop() : id.includes(":") ? id.split(":").pop() : id;
23
- for (const pattern of allPatterns) {
24
- if (matchesPattern(id, name, shortId, pattern)) {
25
- return true;
26
- }
27
- }
28
- return false;
29
- }
30
- function matchesPattern(id, name, shortId, pattern) {
31
- const p = pattern.toLowerCase();
32
- if (p.startsWith("regex:")) {
33
- try {
34
- const re = new RegExp(pattern.slice(6), "i");
35
- return re.test(id) || re.test(name) || re.test(shortId);
36
- } catch {
37
- return false;
38
- }
39
- }
40
- if (p.includes("*") || p.includes("?")) {
41
- const regexStr = "^" + p.replace(/([.+^${}()|[\]\\])/g, "\\$1").replace(/\*/g, ".*").replace(/\?/g, ".") + "$";
42
- try {
43
- const re = new RegExp(regexStr, "i");
44
- return re.test(id) || re.test(name) || re.test(shortId);
45
- } catch {
46
- return false;
47
- }
48
- }
49
- return id === p || name === p || shortId === p;
50
- }
51
2
  // ../plexus-models/src/convert.ts
52
- var REASONING_PARAMS = new Set(["reasoning", "include_reasoning", "reasoning_effort"]);
3
+ var REASONING_PARAMS = new Set([
4
+ "reasoning",
5
+ "include_reasoning",
6
+ "reasoning_effort"
7
+ ]);
53
8
  var NON_CHAT_PATTERN = /(?:^|[\W_])(?:embed(?:ding|dings)?|transcri(?:be[ds]?|ptions?)|whisper|speech[\W_]*to[\W_]*text|stt|text[\W_]*to[\W_]*speech|tts|image(?:[\W_]*(?:gen(?:eration)?|\d+))?|diffusion|dall[\W_]*e|stable[\W_]*diffusion|sdxl|dream)(?:$|[\W_])/i;
54
9
  var API_DIALECT_MAP = {
55
10
  chat_completions: "openai-completions",
@@ -104,13 +59,13 @@ function parsePrice(raw) {
104
59
  if (raw === undefined)
105
60
  return 0;
106
61
  const n = parseFloat(raw);
107
- return isFinite(n) && n >= 0 ? n : 0;
62
+ return Number.isFinite(n) && n >= 0 ? n : 0;
108
63
  }
109
64
  function resolveContextWindow(model) {
110
65
  const v = model.context_length ?? model.top_provider?.context_length ?? null;
111
66
  return v != null && v > 0 ? v : 8192;
112
67
  }
113
- function resolveMaxTokens(model, contextWindow) {
68
+ function resolveMaxTokens(model) {
114
69
  const v = model.top_provider?.max_completion_tokens ?? null;
115
70
  if (v == null || v < 100) {
116
71
  return 32768;
@@ -124,13 +79,15 @@ function resolvePricingTiers(model) {
124
79
  const tiers = pricing.tiers.flatMap((tier) => {
125
80
  if (!Number.isFinite(tier.input_tokens_above) || tier.input_tokens_above < 0)
126
81
  return [];
127
- return [{
128
- inputTokensAbove: tier.input_tokens_above,
129
- input: parsePrice(tier.prompt ?? pricing.prompt),
130
- output: parsePrice(tier.completion ?? pricing.completion),
131
- cacheRead: parsePrice(tier.input_cache_read ?? pricing.input_cache_read),
132
- cacheWrite: parsePrice(tier.input_cache_write ?? pricing.input_cache_write)
133
- }];
82
+ return [
83
+ {
84
+ inputTokensAbove: tier.input_tokens_above,
85
+ input: parsePrice(tier.prompt ?? pricing.prompt),
86
+ output: parsePrice(tier.completion ?? pricing.completion),
87
+ cacheRead: parsePrice(tier.input_cache_read ?? pricing.input_cache_read),
88
+ cacheWrite: parsePrice(tier.input_cache_write ?? pricing.input_cache_write)
89
+ }
90
+ ];
134
91
  });
135
92
  return tiers.length > 0 ? tiers : undefined;
136
93
  }
@@ -138,7 +95,7 @@ function convertToDescriptor(raw, baseUrl) {
138
95
  const preferredApi = mapPreferredApi(raw.preferred_api);
139
96
  const adjustedBaseUrl = adjustBaseUrl(baseUrl, preferredApi);
140
97
  const contextWindow = resolveContextWindow(raw);
141
- const maxTokens = resolveMaxTokens(raw, contextWindow);
98
+ const maxTokens = resolveMaxTokens(raw);
142
99
  const tiers = resolvePricingTiers(raw);
143
100
  const descriptor = {
144
101
  id: raw.id,
@@ -192,7 +149,7 @@ function isChatModel(model) {
192
149
  const apiHints = Array.isArray(model.preferred_api) ? model.preferred_api.join(" ") : model.preferred_api ?? "";
193
150
  return !NON_CHAT_PATTERN.test(`${model.id} ${model.name ?? ""} ${apiHints}`);
194
151
  }
195
- function parseSuppressionPatterns2(input) {
152
+ function parseSuppressionPatterns(input) {
196
153
  if (!input)
197
154
  return [];
198
155
  const rawItems = Array.isArray(input) ? input : [input];
@@ -211,9 +168,9 @@ function parseSuppressionPatterns2(input) {
211
168
  return patterns;
212
169
  }
213
170
  function isSuppressedModel(model, suppress) {
214
- if (!model || !model.id)
171
+ if (!model?.id)
215
172
  return false;
216
- const patterns = parseSuppressionPatterns2(suppress);
173
+ const patterns = parseSuppressionPatterns(suppress);
217
174
  if (patterns.length === 0)
218
175
  return false;
219
176
  const idLower = model.id.toLowerCase();
@@ -237,7 +194,7 @@ function isSuppressedModel(model, suppress) {
237
194
  if (pattern.includes("*") || pattern.includes("?")) {
238
195
  try {
239
196
  const escaped = patternLower.replace(/[.+^$()|[{}]\\]/g, "\\$&");
240
- const regexStr = "^" + escaped.replace(/\*/g, ".*").replace(/\?/g, ".") + "$";
197
+ const regexStr = `^${escaped.replace(/\*/g, ".*").replace(/\?/g, ".")}$`;
241
198
  const globRe = new RegExp(regexStr, "i");
242
199
  if (globRe.test(model.id) || model.name && globRe.test(model.name)) {
243
200
  return true;
@@ -350,13 +307,90 @@ async function fetchPlexusModels(apiKey, modelsUrl, timeoutMs = DEFAULT_MODELS_F
350
307
  clearTimeout(timer);
351
308
  }
352
309
  }
353
- // src/config.ts
310
+ // ../plexus-models/src/suppress.ts
311
+ function parseSuppressionPatterns2(raw) {
312
+ if (!raw)
313
+ return [];
314
+ const items = Array.isArray(raw) ? raw : raw.split(/[\n,;]+/);
315
+ return items.map((s) => s.trim()).filter((s) => s.length > 0);
316
+ }
317
+ function getEnvSuppressedModels() {
318
+ const env = typeof process !== "undefined" && process?.env ? process.env : {};
319
+ const raw = env.PLEXUS_SUPPRESS_MODELS ?? env.PLEXUS_EXCLUDE_MODELS;
320
+ return parseSuppressionPatterns2(raw);
321
+ }
322
+ function isModelSuppressed(model, patterns) {
323
+ const envPatterns = getEnvSuppressedModels();
324
+ const explicitPatterns = parseSuppressionPatterns2(patterns);
325
+ const allPatterns = [...envPatterns, ...explicitPatterns];
326
+ if (allPatterns.length === 0)
327
+ return false;
328
+ const id = model.id.toLowerCase();
329
+ const name = (model.name ?? "").toLowerCase();
330
+ const separator = id.includes("/") ? "/" : id.includes(":") ? ":" : undefined;
331
+ const shortId = separator === undefined ? id : id.split(separator).pop() ?? id;
332
+ for (const pattern of allPatterns) {
333
+ if (matchesPattern(id, name, shortId, pattern)) {
334
+ return true;
335
+ }
336
+ }
337
+ return false;
338
+ }
339
+ function matchesPattern(id, name, shortId, pattern) {
340
+ const p = pattern.toLowerCase();
341
+ if (p.startsWith("regex:")) {
342
+ try {
343
+ const re = new RegExp(pattern.slice(6), "i");
344
+ return re.test(id) || re.test(name) || re.test(shortId);
345
+ } catch {
346
+ return false;
347
+ }
348
+ }
349
+ if (p.includes("*") || p.includes("?")) {
350
+ const regexStr = "^" + p.replace(/([.+^${}()|[\]\\])/g, "\\$1").replace(/\*/g, ".*").replace(/\?/g, ".") + "$";
351
+ try {
352
+ const re = new RegExp(regexStr, "i");
353
+ return re.test(id) || re.test(name) || re.test(shortId);
354
+ } catch {
355
+ return false;
356
+ }
357
+ }
358
+ return id === p || name === p || shortId === p;
359
+ }
360
+ // src/cache.ts
354
361
  import { existsSync, readFileSync } from "fs";
355
- import { mkdir, writeFile } from "fs/promises";
356
362
  import { join } from "path";
357
- import { getAgentDir } from "@earendil-works/pi-coding-agent";
358
- var getConfigDir = () => join(getAgentDir(), "extensions", "plexus");
359
- var getConfigPath = () => join(getConfigDir(), "config.json");
363
+ import {
364
+ getAgentDir
365
+ } from "@earendil-works/pi-coding-agent";
366
+ function readStoredModelsSync() {
367
+ try {
368
+ const path = join(getAgentDir(), "models-store.json");
369
+ if (!existsSync(path))
370
+ return null;
371
+ const data = JSON.parse(readFileSync(path, "utf8"));
372
+ const plexus = data.plexus;
373
+ if (!plexus || typeof plexus !== "object" || Array.isArray(plexus))
374
+ return null;
375
+ const catalog = plexus;
376
+ if (!Array.isArray(catalog.models))
377
+ return null;
378
+ return {
379
+ models: catalog.models,
380
+ checkedAt: typeof catalog.checkedAt === "number" ? catalog.checkedAt : 0
381
+ };
382
+ } catch {
383
+ return null;
384
+ }
385
+ }
386
+
387
+ // src/config.ts
388
+ import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
389
+ import { mkdir, writeFile } from "fs/promises";
390
+ import { join as join2 } from "path";
391
+ import { getAgentDir as getAgentDir2 } from "@earendil-works/pi-coding-agent";
392
+ var getConfigDir = () => join2(getAgentDir2(), "extensions", "plexus");
393
+ var getConfigPath = () => join2(getConfigDir(), "config.json");
360
394
  var ENV_BASE_URL = "PLEXUS_BASE_URL";
361
395
  var ENV_API_URL = "PLEXUS_API_URL";
362
396
  var ENV_API_KEY = "PLEXUS_API_KEY";
@@ -432,8 +466,8 @@ function getConfigSync() {
432
466
  if (cachedConfig)
433
467
  return cachedConfig;
434
468
  try {
435
- if (existsSync(getConfigPath())) {
436
- cachedConfig = JSON.parse(readFileSync(getConfigPath(), "utf8"));
469
+ if (existsSync2(getConfigPath())) {
470
+ cachedConfig = JSON.parse(readFileSync2(getConfigPath(), "utf8"));
437
471
  return cachedConfig;
438
472
  }
439
473
  } catch {}
@@ -517,203 +551,44 @@ function getBaseUrl() {
517
551
  function getSuppressedModels() {
518
552
  const config = getConfigSync();
519
553
  const envSuppressed = getEnvSuppressedModels();
520
- const configSuppressed = parseSuppressionPatterns(config.suppressModels ?? config.suppress);
554
+ const configSuppressed = parseSuppressionPatterns2(config.suppressModels ?? config.suppress);
521
555
  return [...envSuppressed, ...configSuppressed];
522
556
  }
523
557
 
524
- // src/cache.ts
525
- import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
526
- import { join as join2 } from "path";
527
- import { getAgentDir as getAgentDir2 } from "@earendil-works/pi-coding-agent";
528
- function readStoredModelsSync() {
529
- try {
530
- const path = join2(getAgentDir2(), "models-store.json");
531
- if (!existsSync2(path))
532
- return null;
533
- const data = JSON.parse(readFileSync2(path, "utf8"));
534
- const plexus = data["plexus"];
535
- if (!plexus || typeof plexus !== "object" || Array.isArray(plexus))
536
- return null;
537
- const catalog = plexus;
538
- if (!Array.isArray(catalog["models"]))
539
- return null;
540
- return {
541
- models: catalog["models"],
542
- checkedAt: typeof catalog["checkedAt"] === "number" ? catalog["checkedAt"] : 0
543
- };
544
- } catch {
545
- return null;
546
- }
547
- }
558
+ // src/context-policy.ts
559
+ import { randomUUID } from "crypto";
548
560
 
549
- // src/log.ts
550
- import { mkdir as mkdir2, appendFile } from "fs/promises";
551
- import { join as join3 } from "path";
552
- import { getAgentDir as getAgentDir3 } from "@earendil-works/pi-coding-agent";
553
- var getCacheDir = () => join3(getAgentDir3(), "extensions", "plexus");
554
- var getLogPath = () => join3(getCacheDir(), "plexus.log");
555
- var dirEnsured = false;
556
- function log(message, data) {
557
- writeLogLine(message, data);
561
+ // ../../node_modules/.bun/zod@4.6.5/node_modules/zod/v4/core/util.js
562
+ function getEnumValues(entries) {
563
+ const numericValues = Object.values(entries).filter((v) => typeof v === "number");
564
+ const values = Object.entries(entries).filter(([k, _]) => numericValues.indexOf(+k) === -1).map(([_, v]) => v);
565
+ return values;
558
566
  }
559
- async function writeLogLine(message, data) {
560
- try {
561
- if (!dirEnsured) {
562
- await mkdir2(getCacheDir(), { recursive: true });
563
- dirEnsured = true;
564
- }
565
- const ts = new Date().toISOString();
566
- const line = data !== undefined ? `${ts} ${message} ${JSON.stringify(data)}
567
- ` : `${ts} ${message}
568
- `;
569
- await appendFile(getLogPath(), line, "utf8");
570
- } catch {}
567
+ function joinValues(array, separator = "|") {
568
+ return array.map((val) => stringifyPrimitive(val)).join(separator);
571
569
  }
572
-
573
- // src/mapper.ts
574
- import { getModel } from "@earendil-works/pi-ai/compat";
575
- var MINIMUM_OUTPUT_TOKENS = 8192;
576
- function descriptorToPiModel(descriptor) {
577
- let builtinModel;
578
- if (descriptor.piProvider && descriptor.piModel) {
579
- try {
580
- builtinModel = getModel(descriptor.piProvider, descriptor.piModel);
581
- } catch {
582
- builtinModel = undefined;
583
- }
584
- }
585
- const cost = {
586
- input: descriptor.cost.input * 1e6,
587
- output: descriptor.cost.output * 1e6,
588
- cacheRead: descriptor.cost.cacheRead * 1e6,
589
- cacheWrite: descriptor.cost.cacheWrite * 1e6,
590
- ...descriptor.cost.tiers ? {
591
- tiers: descriptor.cost.tiers.map((tier) => ({
592
- inputTokensAbove: tier.inputTokensAbove,
593
- input: tier.input * 1e6,
594
- output: tier.output * 1e6,
595
- cacheRead: tier.cacheRead * 1e6,
596
- cacheWrite: tier.cacheWrite * 1e6
597
- }))
598
- } : {}
599
- };
600
- let compat;
601
- if (descriptor.preferredApi === "openai-completions") {
602
- const heuristic = detectOpenAICompletionsCompat(descriptor.piProvider ?? descriptor.provider, descriptor.baseUrl);
603
- const builtinCompat = builtinModel?.compat;
604
- const merged = { ...heuristic, ...builtinCompat ?? {}, ...descriptor.piOptions ?? {} };
605
- compat = merged;
606
- } else if (descriptor.piOptions) {
607
- compat = descriptor.piOptions;
608
- } else if (builtinModel?.compat) {
609
- compat = builtinModel.compat;
610
- }
611
- return {
612
- id: descriptor.id,
613
- name: descriptor.name,
614
- api: descriptor.preferredApi,
615
- provider: descriptor.provider,
616
- baseUrl: descriptor.baseUrl,
617
- reasoning: descriptor.reasoning,
618
- input: descriptor.input,
619
- cost,
620
- contextWindow: descriptor.contextWindow,
621
- maxTokens: Math.max(descriptor.maxTokens, MINIMUM_OUTPUT_TOKENS),
622
- ...builtinModel?.thinkingLevelMap !== undefined ? { thinkingLevelMap: builtinModel.thinkingLevelMap } : {},
623
- ...builtinModel?.headers !== undefined ? { headers: builtinModel.headers } : {},
624
- ...compat !== undefined ? { compat } : {}
625
- };
570
+ function jsonStringifyReplacer(_, value) {
571
+ if (typeof value === "bigint")
572
+ return value.toString();
573
+ return value;
626
574
  }
627
575
 
628
- // src/gemini-malformed-retry.ts
629
- var MALFORMED_LEAK_PATTERN = /(?:print\()?call:\s*default_api[.:]|default_api\.\w+\s*\(/;
630
- var MALFORMED_DIAGNOSTIC_PATTERN = /\bmalformed[\s_-]?function[\s_-]?call\b/i;
631
- var TRUNCATED_JSON_PATTERN = /\bUnexpected end of JSON input\b/i;
632
- var PROVIDER_CONNECTION_CLOSED_PATTERN = /\bprovider connection closed\b/i;
633
- var NORMALIZED_PREFIX = "MALFORMED_FUNCTION_CALL:";
634
- var TRUNCATED_JSON_PREFIX = "TRUNCATED_JSON_RESPONSE:";
635
- var PROVIDER_CONNECTION_CLOSED_PREFIX = "PROVIDER_CONNECTION_CLOSED:";
636
- var NORMALIZED_MESSAGE = `${NORMALIZED_PREFIX} Gemini emitted a malformed tool call (its internal ` + `function-call syntax leaked as text). This is a transient model failure \u2014 ` + `please retry your request.`;
637
- var TRUNCATED_JSON_MESSAGE = `${TRUNCATED_JSON_PREFIX} Unexpected end of JSON input. The upstream provider ` + `returned a truncated JSON response. This is a transient provider failure \u2014 ` + `please retry your request.`;
638
- var PROVIDER_CONNECTION_CLOSED_MESSAGE = `${PROVIDER_CONNECTION_CLOSED_PREFIX} Provider connection closed. The upstream provider ` + `dropped the request. This is a transient provider failure \u2014 please retry your request.`;
639
- function hasLeakedFunctionCall(content) {
640
- if (!Array.isArray(content))
641
- return false;
642
- for (const block of content) {
643
- if (block?.type === "text" && typeof block.text === "string" && MALFORMED_LEAK_PATTERN.test(block.text)) {
644
- return true;
576
+ class Cached {
577
+ constructor(getter) {
578
+ this._getter = getter;
579
+ this._value = undefined;
580
+ }
581
+ get value() {
582
+ const getter = this._getter;
583
+ if (getter !== undefined) {
584
+ this._value = getter();
585
+ this._getter = undefined;
645
586
  }
587
+ return this._value;
646
588
  }
647
- return false;
648
589
  }
649
- function hasToolCall(content) {
650
- return Array.isArray(content) && content.some((block) => block?.type === "toolCall");
651
- }
652
- function normalizeMalformedFunctionCall(message, providerName) {
653
- if (!message || message.role !== "assistant" || message.provider !== providerName || message.stopReason !== "error") {
654
- return;
655
- }
656
- if (typeof message.errorMessage === "string" && (message.errorMessage.startsWith(NORMALIZED_PREFIX) || message.errorMessage.startsWith(TRUNCATED_JSON_PREFIX) || message.errorMessage.startsWith(PROVIDER_CONNECTION_CLOSED_PREFIX))) {
657
- return;
658
- }
659
- if (hasToolCall(message.content))
660
- return;
661
- if (typeof message.errorMessage === "string" && TRUNCATED_JSON_PATTERN.test(message.errorMessage)) {
662
- log("retryable-error: retagged truncated JSON response for retry", {
663
- model: message.model
664
- });
665
- return { message: { ...message, errorMessage: TRUNCATED_JSON_MESSAGE } };
666
- }
667
- if (typeof message.errorMessage === "string" && PROVIDER_CONNECTION_CLOSED_PATTERN.test(message.errorMessage)) {
668
- log("retryable-error: retagged closed provider connection for retry", {
669
- model: message.model
670
- });
671
- return { message: { ...message, errorMessage: PROVIDER_CONNECTION_CLOSED_MESSAGE } };
672
- }
673
- const via = hasLeakedFunctionCall(message.content) ? "leak" : typeof message.errorMessage === "string" && MALFORMED_DIAGNOSTIC_PATTERN.test(message.errorMessage) ? "diagnostic" : undefined;
674
- if (!via)
675
- return;
676
- log("gemini-malformed-retry: retagged MALFORMED_FUNCTION_CALL for retry", {
677
- model: message.model,
678
- via
679
- });
680
- return { message: { ...message, errorMessage: NORMALIZED_MESSAGE } };
681
- }
682
-
683
- // src/context-policy.ts
684
- import { randomUUID } from "crypto";
685
-
686
- // ../../node_modules/.bun/zod@4.6.5/node_modules/zod/v4/core/util.js
687
- function getEnumValues(entries) {
688
- const numericValues = Object.values(entries).filter((v) => typeof v === "number");
689
- const values = Object.entries(entries).filter(([k, _]) => numericValues.indexOf(+k) === -1).map(([_, v]) => v);
690
- return values;
691
- }
692
- function joinValues(array, separator = "|") {
693
- return array.map((val) => stringifyPrimitive(val)).join(separator);
694
- }
695
- function jsonStringifyReplacer(_, value) {
696
- if (typeof value === "bigint")
697
- return value.toString();
698
- return value;
699
- }
700
-
701
- class Cached {
702
- constructor(getter) {
703
- this._getter = getter;
704
- this._value = undefined;
705
- }
706
- get value() {
707
- const getter = this._getter;
708
- if (getter !== undefined) {
709
- this._value = getter();
710
- this._getter = undefined;
711
- }
712
- return this._value;
713
- }
714
- }
715
- function cached(getter) {
716
- return new Cached(getter);
590
+ function cached(getter) {
591
+ return new Cached(getter);
717
592
  }
718
593
  function nullish(input) {
719
594
  return input === null || input === undefined;
@@ -6180,11 +6055,17 @@ var ContextPolicySnapshotSchema = object({
6180
6055
  for (const policy of snapshot.policies) {
6181
6056
  const pair = `${policy.provider}\x00${policy.modelId}`;
6182
6057
  if (pairs.has(pair))
6183
- ctx.addIssue({ code: "custom", message: "Duplicate provider/modelId policy" });
6058
+ ctx.addIssue({
6059
+ code: "custom",
6060
+ message: "Duplicate provider/modelId policy"
6061
+ });
6184
6062
  pairs.add(pair);
6185
6063
  }
6186
6064
  if (snapshot.status !== "ready" && snapshot.policies.length !== 0) {
6187
- ctx.addIssue({ code: "custom", message: "Non-ready snapshots must have no policies" });
6065
+ ctx.addIssue({
6066
+ code: "custom",
6067
+ message: "Non-ready snapshots must have no policies"
6068
+ });
6188
6069
  }
6189
6070
  }).transform((snapshot) => snapshot);
6190
6071
  var MAX_SNAPSHOT_BYTES = 1024 * 1024;
@@ -6233,20 +6114,37 @@ class ContextPolicyPublisher {
6233
6114
  reason
6234
6115
  };
6235
6116
  if (oversized)
6236
- next = { ...next, status: "unavailable", policies: [], reason: "Context policy snapshot exceeds the 1 MiB publication limit." };
6117
+ next = {
6118
+ ...next,
6119
+ status: "unavailable",
6120
+ policies: [],
6121
+ reason: "Context policy snapshot exceeds the 1 MiB publication limit."
6122
+ };
6237
6123
  if (status !== "ready" && policies.length > 0)
6238
- next = { ...next, status: "unavailable", policies: [], reason: "Context policy metadata is unavailable." };
6124
+ next = {
6125
+ ...next,
6126
+ status: "unavailable",
6127
+ policies: [],
6128
+ reason: "Context policy metadata is unavailable."
6129
+ };
6239
6130
  const { revision: _revision, ...stateWithoutRevision } = this.state;
6240
6131
  const { revision: _candidateRevision, ...nextWithoutRevision } = next;
6241
6132
  if (JSON.stringify(stateWithoutRevision) === JSON.stringify(nextWithoutRevision))
6242
6133
  return false;
6243
6134
  this.revision++;
6244
- this.state = Object.freeze({ ...next, revision: this.revision, policies: Object.freeze([...next.policies]) });
6135
+ this.state = Object.freeze({
6136
+ ...next,
6137
+ revision: this.revision,
6138
+ policies: Object.freeze([...next.policies])
6139
+ });
6245
6140
  this.send();
6246
6141
  return true;
6247
6142
  }
6248
6143
  send(requestId) {
6249
- const snapshot = { ...this.state, ...requestId === undefined ? {} : { requestId } };
6144
+ const snapshot = {
6145
+ ...this.state,
6146
+ ...requestId === undefined ? {} : { requestId }
6147
+ };
6250
6148
  let valid = ContextPolicySnapshotSchema.safeParse(snapshot);
6251
6149
  if (!valid.success || new TextEncoder().encode(JSON.stringify(snapshot)).byteLength > MAX_SNAPSHOT_BYTES) {
6252
6150
  valid = ContextPolicySnapshotSchema.safeParse({
@@ -6268,131 +6166,260 @@ class ContextPolicyPublisher {
6268
6166
  }
6269
6167
  var CONTEXT_POLICY_METADATA_UNAVAILABLE_REASON = SAFE_REASON;
6270
6168
 
6271
- // src/service-tiers.ts
6169
+ // src/log.ts
6170
+ import { appendFile, mkdir as mkdir2 } from "fs/promises";
6171
+ import { join as join3 } from "path";
6172
+ import { getAgentDir as getAgentDir3 } from "@earendil-works/pi-coding-agent";
6173
+ var getCacheDir = () => join3(getAgentDir3(), "extensions", "plexus");
6174
+ var getLogPath = () => join3(getCacheDir(), "plexus.log");
6175
+ var dirEnsured = false;
6176
+ function log(message, data) {
6177
+ writeLogLine(message, data);
6178
+ }
6179
+ async function writeLogLine(message, data) {
6180
+ try {
6181
+ if (!dirEnsured) {
6182
+ await mkdir2(getCacheDir(), { recursive: true });
6183
+ dirEnsured = true;
6184
+ }
6185
+ const ts = new Date().toISOString();
6186
+ const line = data !== undefined ? `${ts} ${message} ${JSON.stringify(data)}
6187
+ ` : `${ts} ${message}
6188
+ `;
6189
+ await appendFile(getLogPath(), line, "utf8");
6190
+ } catch {}
6191
+ }
6192
+
6193
+ // src/gemini-malformed-retry.ts
6194
+ var MALFORMED_LEAK_PATTERN = /(?:print\()?call:\s*default_api[.:]|default_api\.\w+\s*\(/;
6195
+ var MALFORMED_DIAGNOSTIC_PATTERN = /\bmalformed[\s_-]?function[\s_-]?call\b/i;
6196
+ var TRUNCATED_JSON_PATTERN = /\bUnexpected end of JSON input\b/i;
6197
+ var PROVIDER_CONNECTION_CLOSED_PATTERN = /\bprovider connection closed\b/i;
6198
+ var NORMALIZED_PREFIX = "MALFORMED_FUNCTION_CALL:";
6199
+ var TRUNCATED_JSON_PREFIX = "TRUNCATED_JSON_RESPONSE:";
6200
+ var PROVIDER_CONNECTION_CLOSED_PREFIX = "PROVIDER_CONNECTION_CLOSED:";
6201
+ var NORMALIZED_MESSAGE = `${NORMALIZED_PREFIX} Gemini emitted a malformed tool call (its internal ` + `function-call syntax leaked as text). This is a transient model failure \u2014 ` + `please retry your request.`;
6202
+ var TRUNCATED_JSON_MESSAGE = `${TRUNCATED_JSON_PREFIX} Unexpected end of JSON input. The upstream provider ` + `returned a truncated JSON response. This is a transient provider failure \u2014 ` + `please retry your request.`;
6203
+ var PROVIDER_CONNECTION_CLOSED_MESSAGE = `${PROVIDER_CONNECTION_CLOSED_PREFIX} Provider connection closed. The upstream provider ` + `dropped the request. This is a transient provider failure \u2014 please retry your request.`;
6204
+ function hasLeakedFunctionCall(content) {
6205
+ if (!Array.isArray(content))
6206
+ return false;
6207
+ for (const block of content) {
6208
+ if (block?.type === "text" && typeof block.text === "string" && MALFORMED_LEAK_PATTERN.test(block.text)) {
6209
+ return true;
6210
+ }
6211
+ }
6212
+ return false;
6213
+ }
6214
+ function hasToolCall(content) {
6215
+ return Array.isArray(content) && content.some((block) => block?.type === "toolCall");
6216
+ }
6217
+ function normalizeMalformedFunctionCall(message, providerName) {
6218
+ if (message?.role !== "assistant" || message.provider !== providerName || message.stopReason !== "error") {
6219
+ return;
6220
+ }
6221
+ if (typeof message.errorMessage === "string" && (message.errorMessage.startsWith(NORMALIZED_PREFIX) || message.errorMessage.startsWith(TRUNCATED_JSON_PREFIX) || message.errorMessage.startsWith(PROVIDER_CONNECTION_CLOSED_PREFIX))) {
6222
+ return;
6223
+ }
6224
+ if (hasToolCall(message.content))
6225
+ return;
6226
+ if (typeof message.errorMessage === "string" && TRUNCATED_JSON_PATTERN.test(message.errorMessage)) {
6227
+ log("retryable-error: retagged truncated JSON response for retry", {
6228
+ model: message.model
6229
+ });
6230
+ return { message: { ...message, errorMessage: TRUNCATED_JSON_MESSAGE } };
6231
+ }
6232
+ if (typeof message.errorMessage === "string" && PROVIDER_CONNECTION_CLOSED_PATTERN.test(message.errorMessage)) {
6233
+ log("retryable-error: retagged closed provider connection for retry", {
6234
+ model: message.model
6235
+ });
6236
+ return {
6237
+ message: { ...message, errorMessage: PROVIDER_CONNECTION_CLOSED_MESSAGE }
6238
+ };
6239
+ }
6240
+ const via = hasLeakedFunctionCall(message.content) ? "leak" : typeof message.errorMessage === "string" && MALFORMED_DIAGNOSTIC_PATTERN.test(message.errorMessage) ? "diagnostic" : undefined;
6241
+ if (!via)
6242
+ return;
6243
+ log("gemini-malformed-retry: retagged MALFORMED_FUNCTION_CALL for retry", {
6244
+ model: message.model,
6245
+ via
6246
+ });
6247
+ return { message: { ...message, errorMessage: NORMALIZED_MESSAGE } };
6248
+ }
6249
+
6250
+ // src/mapper.ts
6251
+ import {
6252
+ getModel
6253
+ } from "@earendil-works/pi-ai/compat";
6254
+ var MINIMUM_OUTPUT_TOKENS = 8192;
6255
+ function descriptorToPiModel(descriptor) {
6256
+ let builtinModel;
6257
+ if (descriptor.piProvider && descriptor.piModel) {
6258
+ try {
6259
+ builtinModel = getModel(descriptor.piProvider, descriptor.piModel);
6260
+ } catch {
6261
+ builtinModel = undefined;
6262
+ }
6263
+ }
6264
+ const cost = {
6265
+ input: descriptor.cost.input * 1e6,
6266
+ output: descriptor.cost.output * 1e6,
6267
+ cacheRead: descriptor.cost.cacheRead * 1e6,
6268
+ cacheWrite: descriptor.cost.cacheWrite * 1e6,
6269
+ ...descriptor.cost.tiers ? {
6270
+ tiers: descriptor.cost.tiers.map((tier) => ({
6271
+ inputTokensAbove: tier.inputTokensAbove,
6272
+ input: tier.input * 1e6,
6273
+ output: tier.output * 1e6,
6274
+ cacheRead: tier.cacheRead * 1e6,
6275
+ cacheWrite: tier.cacheWrite * 1e6
6276
+ }))
6277
+ } : {}
6278
+ };
6279
+ let compat;
6280
+ if (descriptor.preferredApi === "openai-completions") {
6281
+ const heuristic = detectOpenAICompletionsCompat(descriptor.piProvider ?? descriptor.provider, descriptor.baseUrl);
6282
+ const builtinCompat = builtinModel?.compat;
6283
+ const merged = {
6284
+ ...heuristic,
6285
+ ...builtinCompat ?? {},
6286
+ ...descriptor.piOptions ?? {}
6287
+ };
6288
+ compat = merged;
6289
+ } else if (descriptor.piOptions) {
6290
+ compat = descriptor.piOptions;
6291
+ } else if (builtinModel?.compat) {
6292
+ compat = builtinModel.compat;
6293
+ }
6294
+ return {
6295
+ id: descriptor.id,
6296
+ name: descriptor.name,
6297
+ api: descriptor.preferredApi,
6298
+ provider: descriptor.provider,
6299
+ baseUrl: descriptor.baseUrl,
6300
+ reasoning: descriptor.reasoning,
6301
+ input: descriptor.input,
6302
+ cost,
6303
+ contextWindow: descriptor.contextWindow,
6304
+ maxTokens: Math.max(descriptor.maxTokens, MINIMUM_OUTPUT_TOKENS),
6305
+ ...builtinModel?.thinkingLevelMap !== undefined ? { thinkingLevelMap: builtinModel.thinkingLevelMap } : {},
6306
+ ...builtinModel?.headers !== undefined ? { headers: builtinModel.headers } : {},
6307
+ ...compat !== undefined ? { compat } : {}
6308
+ };
6309
+ }
6310
+
6311
+ // src/models-control.ts
6272
6312
  import { randomUUID as randomUUID2 } from "crypto";
6273
- var SERVICE_TIERS_REQUEST_CHANNEL = "plexus:service-tiers:request:v1";
6274
- var SERVICE_TIERS_SNAPSHOT_CHANNEL = "plexus:service-tiers:snapshot:v1";
6275
- var ServiceTierPolicySchema = object({
6276
- provider: string2().min(1),
6277
- modelId: string2().min(1),
6278
- serviceTiers: array(string2().min(1).max(100)).min(1).max(64)
6279
- }).strict().refine((policy) => new Set(policy.serviceTiers).size === policy.serviceTiers.length);
6280
- var ServiceTiersRequestSchema = object({
6313
+ var MODELS_REFRESH_CHANNEL = "plexus:models:refresh:v1";
6314
+ var MODELS_STATE_CHANNEL = "plexus:models:state:v1";
6315
+ var MAX_STATE_BYTES = 1024 * 1024;
6316
+ var ModelsRefreshSchema = object({
6281
6317
  version: literal(1),
6282
6318
  requestId: string2().min(1).max(1024)
6283
6319
  }).strict();
6284
- var ServiceTiersSnapshotSchema = object({
6320
+ var ModelsStateSchema = object({
6285
6321
  version: literal(1),
6286
6322
  publisherId: string2().uuid(),
6287
6323
  revision: number2().int().positive().safe(),
6288
6324
  requestId: string2().min(1).max(1024).optional(),
6289
- status: _enum(["ready", "loading", "unavailable"]),
6290
- policies: array(ServiceTierPolicySchema),
6291
- fetchedAt: number2().int().nonnegative().safe().optional(),
6292
- cached: boolean2().optional(),
6325
+ status: _enum(["idle", "refreshing", "ready", "error"]),
6326
+ modelCount: number2().int().nonnegative().safe().optional(),
6293
6327
  reason: string2().max(500).optional()
6294
- }).strict().superRefine((snapshot, ctx) => {
6295
- const pairs = new Set;
6296
- for (const policy of snapshot.policies) {
6297
- const pair = `${policy.provider}\x00${policy.modelId}`;
6298
- if (pairs.has(pair))
6299
- ctx.addIssue({ code: "custom", message: "Duplicate provider/modelId service-tier policy" });
6300
- pairs.add(pair);
6301
- }
6302
- if (snapshot.status !== "ready" && snapshot.policies.length !== 0) {
6303
- ctx.addIssue({ code: "custom", message: "Non-ready snapshots must have no policies" });
6304
- }
6305
- });
6306
- var MAX_SNAPSHOT_BYTES2 = 1024 * 1024;
6307
- var SERVICE_TIERS_METADATA_UNAVAILABLE_REASON = "Service-tier metadata is not available from the committed Plexus catalog.";
6328
+ }).strict();
6329
+ var MODELS_REFRESH_FAILED_REASON = "The Plexus catalog refresh failed.";
6330
+ var encoder = new TextEncoder;
6331
+ function byteLength(value) {
6332
+ return encoder.encode(JSON.stringify(value)).byteLength;
6333
+ }
6334
+ function freezeState(state) {
6335
+ return Object.freeze({ ...state });
6336
+ }
6337
+ function freezeParsed(state) {
6338
+ return Object.freeze({ ...state });
6339
+ }
6340
+ function statesEqual(current, next) {
6341
+ return current.status === next.status && current.modelCount === next.modelCount && current.reason === next.reason;
6342
+ }
6308
6343
 
6309
- class ServiceTiersPublisher {
6344
+ class ModelsControl {
6345
+ host;
6310
6346
  publisherId = randomUUID2();
6311
6347
  revision = 1;
6312
- state = Object.freeze({
6313
- version: 1,
6314
- publisherId: this.publisherId,
6315
- revision: 1,
6316
- status: "loading",
6317
- policies: Object.freeze([])
6318
- });
6348
+ state;
6349
+ inFlight;
6319
6350
  emit;
6320
6351
  unsubscribe;
6321
- constructor(events) {
6352
+ constructor(events, host) {
6353
+ this.host = host;
6322
6354
  this.emit = events.emit.bind(events);
6323
- this.unsubscribe = events.on(SERVICE_TIERS_REQUEST_CHANNEL, (data) => {
6324
- const request = ServiceTiersRequestSchema.safeParse(data);
6325
- if (request.success)
6326
- this.send(request.data.requestId);
6355
+ this.state = freezeState({
6356
+ version: 1,
6357
+ publisherId: this.publisherId,
6358
+ revision: 1,
6359
+ status: "idle"
6327
6360
  });
6361
+ this.unsubscribe = events.on(MODELS_REFRESH_CHANNEL, (data) => this.handleCommand(data));
6328
6362
  }
6329
- getSnapshot() {
6363
+ getState() {
6330
6364
  return this.state;
6331
6365
  }
6332
- setCatalog(status, policies, metadata) {
6333
- const candidate = ServiceTiersSnapshotSchema.safeParse({
6334
- version: 1,
6335
- publisherId: this.publisherId,
6336
- revision: this.revision,
6337
- status,
6338
- policies: [...policies],
6339
- ...metadata
6340
- });
6341
- const oversized = candidate.success && new TextEncoder().encode(JSON.stringify(candidate.data)).byteLength > MAX_SNAPSHOT_BYTES2;
6342
- let next = candidate.success && !oversized ? candidate.data : {
6343
- version: 1,
6344
- publisherId: this.publisherId,
6345
- revision: this.revision,
6346
- status: "unavailable",
6347
- policies: [],
6348
- reason: oversized ? "Service-tier snapshot exceeds the 1 MiB publication limit." : "Service-tier snapshot could not be validated."
6349
- };
6350
- if (status !== "ready" && policies.length > 0) {
6351
- next = { ...next, status: "unavailable", policies: [], reason: "Service-tier metadata is unavailable." };
6352
- }
6353
- const { revision: _revision, ...stateWithoutRevision } = this.state;
6354
- const { revision: _candidateRevision, ...nextWithoutRevision } = next;
6355
- if (JSON.stringify(stateWithoutRevision) === JSON.stringify(nextWithoutRevision))
6356
- return false;
6357
- this.revision++;
6358
- this.state = Object.freeze({
6359
- ...next,
6360
- revision: this.revision,
6361
- policies: Object.freeze(next.policies.map((policy) => Object.freeze({
6362
- ...policy,
6363
- serviceTiers: Object.freeze([...policy.serviceTiers])
6364
- })))
6365
- });
6366
- this.send();
6367
- return true;
6366
+ dispose() {
6367
+ this.unsubscribe();
6368
6368
  }
6369
- send(requestId) {
6370
- const snapshot = { ...this.state, ...requestId === undefined ? {} : { requestId } };
6371
- let valid = ServiceTiersSnapshotSchema.safeParse(snapshot);
6372
- if (!valid.success || new TextEncoder().encode(JSON.stringify(snapshot)).byteLength > MAX_SNAPSHOT_BYTES2) {
6373
- valid = ServiceTiersSnapshotSchema.safeParse({
6374
- version: 1,
6375
- publisherId: this.publisherId,
6376
- revision: this.revision,
6377
- status: "unavailable",
6378
- policies: [],
6379
- reason: "Service-tier snapshot exceeds publication limits or is invalid.",
6380
- ...requestId === undefined ? {} : { requestId }
6369
+ async handleCommand(data) {
6370
+ const parsed = ModelsRefreshSchema.safeParse(data);
6371
+ if (!parsed.success)
6372
+ return;
6373
+ if (!this.inFlight) {
6374
+ const run = this.runRefresh();
6375
+ this.inFlight = run.finally(() => {
6376
+ this.inFlight = undefined;
6381
6377
  });
6382
6378
  }
6383
- if (valid.success) {
6384
- const immutable = Object.freeze({
6385
- ...valid.data,
6386
- policies: Object.freeze(valid.data.policies.map((policy) => Object.freeze({
6387
- ...policy,
6388
- serviceTiers: Object.freeze([...policy.serviceTiers])
6389
- })))
6390
- });
6391
- this.emit(SERVICE_TIERS_SNAPSHOT_CHANNEL, immutable);
6379
+ await this.inFlight;
6380
+ this.emitState(this.state, parsed.data.requestId);
6381
+ }
6382
+ async runRefresh() {
6383
+ this.commit({ status: "refreshing" });
6384
+ try {
6385
+ const result = await this.host.refresh();
6386
+ this.commit({ status: "ready", modelCount: result.modelCount });
6387
+ } catch (error) {
6388
+ log("models:refresh failed", { error: String(error) });
6389
+ this.commit({ status: "error", reason: MODELS_REFRESH_FAILED_REASON });
6392
6390
  }
6393
6391
  }
6394
- dispose() {
6395
- this.unsubscribe();
6392
+ commit(next) {
6393
+ if (statesEqual(this.state, next))
6394
+ return;
6395
+ this.revision++;
6396
+ this.state = freezeState({
6397
+ version: 1,
6398
+ publisherId: this.publisherId,
6399
+ revision: this.revision,
6400
+ status: next.status,
6401
+ ...next.modelCount === undefined ? {} : { modelCount: next.modelCount },
6402
+ ...next.reason === undefined ? {} : { reason: next.reason }
6403
+ });
6404
+ this.emitState(this.state);
6405
+ }
6406
+ emitState(state, requestId) {
6407
+ const candidate = requestId === undefined ? state : { ...state, requestId };
6408
+ const parsed = ModelsStateSchema.safeParse(candidate);
6409
+ if (parsed.success && byteLength(parsed.data) <= MAX_STATE_BYTES) {
6410
+ this.emit(MODELS_STATE_CHANNEL, freezeParsed(parsed.data));
6411
+ return;
6412
+ }
6413
+ const fallback = ModelsStateSchema.safeParse({
6414
+ version: 1,
6415
+ publisherId: this.publisherId,
6416
+ revision: this.revision,
6417
+ ...requestId === undefined ? {} : { requestId },
6418
+ status: "error",
6419
+ reason: "Plexus catalog state is unavailable."
6420
+ });
6421
+ if (fallback.success)
6422
+ this.emit(MODELS_STATE_CHANNEL, freezeParsed(fallback.data));
6396
6423
  }
6397
6424
  }
6398
6425
 
@@ -6400,7 +6427,7 @@ class ServiceTiersPublisher {
6400
6427
  import { randomUUID as randomUUID3 } from "crypto";
6401
6428
  var POLICY_SET_CHANNEL = "plexus:policy:set:v1";
6402
6429
  var POLICY_STATE_CHANNEL = "plexus:policy:state:v1";
6403
- var MAX_STATE_BYTES = 1024 * 1024;
6430
+ var MAX_STATE_BYTES2 = 1024 * 1024;
6404
6431
  var PolicySetSchema = object({
6405
6432
  version: literal(1),
6406
6433
  requestId: string2().min(1).max(1024),
@@ -6426,7 +6453,10 @@ var PolicyStateSchema = object({
6426
6453
  reason: string2().max(500).optional()
6427
6454
  }).strict();
6428
6455
  var POLICY_UNAVAILABLE_REASON = "No Plexus context or service-tier policy is advertised for the active model.";
6429
- var DEFAULT_SELECTION = Object.freeze({ longContext: true, serviceTier: null });
6456
+ var DEFAULT_SELECTION = Object.freeze({
6457
+ longContext: true,
6458
+ serviceTier: null
6459
+ });
6430
6460
  function policyAvailability(advertisement) {
6431
6461
  const context = advertisement?.context;
6432
6462
  return {
@@ -6450,11 +6480,11 @@ function injectServiceTier(payload, tier) {
6450
6480
  return payload;
6451
6481
  return { ...payload, service_tier: tier };
6452
6482
  }
6453
- var encoder = new TextEncoder;
6454
- function byteLength(value) {
6455
- return encoder.encode(JSON.stringify(value)).byteLength;
6483
+ var encoder2 = new TextEncoder;
6484
+ function byteLength2(value) {
6485
+ return encoder2.encode(JSON.stringify(value)).byteLength;
6456
6486
  }
6457
- function freezeParsed(state) {
6487
+ function freezeParsed2(state) {
6458
6488
  return Object.freeze({
6459
6489
  ...state,
6460
6490
  applied: Object.freeze({ ...state.applied }),
@@ -6469,7 +6499,11 @@ function freezePublished(state) {
6469
6499
  });
6470
6500
  }
6471
6501
  function selectionStatesEqual(current, next) {
6472
- const shape = (state) => JSON.stringify({ applied: state.applied, available: state.available, reason: state.reason ?? null });
6502
+ const shape = (state) => JSON.stringify({
6503
+ applied: state.applied,
6504
+ available: state.available,
6505
+ reason: state.reason ?? null
6506
+ });
6473
6507
  return shape(current) === shape(next);
6474
6508
  }
6475
6509
  function validateSelection(model, advertisement, command) {
@@ -6486,7 +6520,7 @@ function validateSelection(model, advertisement, command) {
6486
6520
  }
6487
6521
  if (command.serviceTier !== undefined && command.serviceTier !== null) {
6488
6522
  const tiers = advertisement.serviceTier?.serviceTiers;
6489
- if (!tiers || !tiers.includes(command.serviceTier)) {
6523
+ if (!tiers?.includes(command.serviceTier)) {
6490
6524
  return "The requested service tier is not advertised for the active model.";
6491
6525
  }
6492
6526
  }
@@ -6499,7 +6533,10 @@ class PolicyController {
6499
6533
  revision = 1;
6500
6534
  selection = { ...DEFAULT_SELECTION };
6501
6535
  boundModel;
6502
- available = { longContext: false, serviceTier: false };
6536
+ available = {
6537
+ longContext: false,
6538
+ serviceTier: false
6539
+ };
6503
6540
  contextWindow;
6504
6541
  reason;
6505
6542
  state;
@@ -6571,7 +6608,7 @@ class PolicyController {
6571
6608
  }
6572
6609
  if (selection.serviceTier !== null) {
6573
6610
  const tiers = advertisement?.serviceTier?.serviceTiers;
6574
- if (!tiers || !tiers.includes(selection.serviceTier)) {
6611
+ if (!tiers?.includes(selection.serviceTier)) {
6575
6612
  selection = { ...selection, serviceTier: null };
6576
6613
  reason = "The selected service tier is no longer advertised for the active model.";
6577
6614
  }
@@ -6667,15 +6704,15 @@ class PolicyController {
6667
6704
  ...reason === undefined ? {} : { reason },
6668
6705
  requestId
6669
6706
  });
6670
- if (parsed.success && byteLength(parsed.data) <= MAX_STATE_BYTES) {
6671
- this.emit(POLICY_STATE_CHANNEL, freezeParsed(parsed.data));
6707
+ if (parsed.success && byteLength2(parsed.data) <= MAX_STATE_BYTES2) {
6708
+ this.emit(POLICY_STATE_CHANNEL, freezeParsed2(parsed.data));
6672
6709
  }
6673
6710
  }
6674
6711
  emitState(state, requestId) {
6675
6712
  const candidate = requestId === undefined ? state : { ...state, requestId };
6676
6713
  const parsed = PolicyStateSchema.safeParse(candidate);
6677
- if (parsed.success && byteLength(parsed.data) <= MAX_STATE_BYTES) {
6678
- this.emit(POLICY_STATE_CHANNEL, freezeParsed(parsed.data));
6714
+ if (parsed.success && byteLength2(parsed.data) <= MAX_STATE_BYTES2) {
6715
+ this.emit(POLICY_STATE_CHANNEL, freezeParsed2(parsed.data));
6679
6716
  return;
6680
6717
  }
6681
6718
  const fallback = PolicyStateSchema.safeParse({
@@ -6688,121 +6725,149 @@ class PolicyController {
6688
6725
  reason: "Plexus policy state is unavailable."
6689
6726
  });
6690
6727
  if (fallback.success)
6691
- this.emit(POLICY_STATE_CHANNEL, freezeParsed(fallback.data));
6728
+ this.emit(POLICY_STATE_CHANNEL, freezeParsed2(fallback.data));
6692
6729
  }
6693
6730
  }
6694
6731
 
6695
- // src/models-control.ts
6732
+ // src/service-tiers.ts
6696
6733
  import { randomUUID as randomUUID4 } from "crypto";
6697
- var MODELS_REFRESH_CHANNEL = "plexus:models:refresh:v1";
6698
- var MODELS_STATE_CHANNEL = "plexus:models:state:v1";
6699
- var MAX_STATE_BYTES2 = 1024 * 1024;
6700
- var ModelsRefreshSchema = object({
6734
+ var SERVICE_TIERS_REQUEST_CHANNEL = "plexus:service-tiers:request:v1";
6735
+ var SERVICE_TIERS_SNAPSHOT_CHANNEL = "plexus:service-tiers:snapshot:v1";
6736
+ var ServiceTierPolicySchema = object({
6737
+ provider: string2().min(1),
6738
+ modelId: string2().min(1),
6739
+ serviceTiers: array(string2().min(1).max(100)).min(1).max(64)
6740
+ }).strict().refine((policy) => new Set(policy.serviceTiers).size === policy.serviceTiers.length);
6741
+ var ServiceTiersRequestSchema = object({
6701
6742
  version: literal(1),
6702
6743
  requestId: string2().min(1).max(1024)
6703
6744
  }).strict();
6704
- var ModelsStateSchema = object({
6745
+ var ServiceTiersSnapshotSchema = object({
6705
6746
  version: literal(1),
6706
6747
  publisherId: string2().uuid(),
6707
6748
  revision: number2().int().positive().safe(),
6708
6749
  requestId: string2().min(1).max(1024).optional(),
6709
- status: _enum(["idle", "refreshing", "ready", "error"]),
6710
- modelCount: number2().int().nonnegative().safe().optional(),
6750
+ status: _enum(["ready", "loading", "unavailable"]),
6751
+ policies: array(ServiceTierPolicySchema),
6752
+ fetchedAt: number2().int().nonnegative().safe().optional(),
6753
+ cached: boolean2().optional(),
6711
6754
  reason: string2().max(500).optional()
6712
- }).strict();
6713
- var MODELS_REFRESH_FAILED_REASON = "The Plexus catalog refresh failed.";
6714
- var encoder2 = new TextEncoder;
6715
- function byteLength2(value) {
6716
- return encoder2.encode(JSON.stringify(value)).byteLength;
6717
- }
6718
- function freezeState(state) {
6719
- return Object.freeze({ ...state });
6720
- }
6721
- function freezeParsed2(state) {
6722
- return Object.freeze({ ...state });
6723
- }
6724
- function statesEqual(current, next) {
6725
- return current.status === next.status && current.modelCount === next.modelCount && current.reason === next.reason;
6726
- }
6755
+ }).strict().superRefine((snapshot, ctx) => {
6756
+ const pairs = new Set;
6757
+ for (const policy of snapshot.policies) {
6758
+ const pair = `${policy.provider}\x00${policy.modelId}`;
6759
+ if (pairs.has(pair))
6760
+ ctx.addIssue({
6761
+ code: "custom",
6762
+ message: "Duplicate provider/modelId service-tier policy"
6763
+ });
6764
+ pairs.add(pair);
6765
+ }
6766
+ if (snapshot.status !== "ready" && snapshot.policies.length !== 0) {
6767
+ ctx.addIssue({
6768
+ code: "custom",
6769
+ message: "Non-ready snapshots must have no policies"
6770
+ });
6771
+ }
6772
+ });
6773
+ var MAX_SNAPSHOT_BYTES2 = 1024 * 1024;
6774
+ var SERVICE_TIERS_METADATA_UNAVAILABLE_REASON = "Service-tier metadata is not available from the committed Plexus catalog.";
6727
6775
 
6728
- class ModelsControl {
6729
- host;
6776
+ class ServiceTiersPublisher {
6730
6777
  publisherId = randomUUID4();
6731
6778
  revision = 1;
6732
- state;
6733
- inFlight;
6779
+ state = Object.freeze({
6780
+ version: 1,
6781
+ publisherId: this.publisherId,
6782
+ revision: 1,
6783
+ status: "loading",
6784
+ policies: Object.freeze([])
6785
+ });
6734
6786
  emit;
6735
6787
  unsubscribe;
6736
- constructor(events, host) {
6737
- this.host = host;
6788
+ constructor(events) {
6738
6789
  this.emit = events.emit.bind(events);
6739
- this.state = freezeState({
6740
- version: 1,
6741
- publisherId: this.publisherId,
6742
- revision: 1,
6743
- status: "idle"
6790
+ this.unsubscribe = events.on(SERVICE_TIERS_REQUEST_CHANNEL, (data) => {
6791
+ const request = ServiceTiersRequestSchema.safeParse(data);
6792
+ if (request.success)
6793
+ this.send(request.data.requestId);
6744
6794
  });
6745
- this.unsubscribe = events.on(MODELS_REFRESH_CHANNEL, (data) => this.handleCommand(data));
6746
6795
  }
6747
- getState() {
6796
+ getSnapshot() {
6748
6797
  return this.state;
6749
6798
  }
6750
- dispose() {
6751
- this.unsubscribe();
6752
- }
6753
- async handleCommand(data) {
6754
- const parsed = ModelsRefreshSchema.safeParse(data);
6755
- if (!parsed.success)
6756
- return;
6757
- if (!this.inFlight) {
6758
- const run = this.runRefresh();
6759
- this.inFlight = run.finally(() => {
6760
- this.inFlight = undefined;
6761
- });
6762
- }
6763
- await this.inFlight;
6764
- this.emitState(this.state, parsed.data.requestId);
6765
- }
6766
- async runRefresh() {
6767
- this.commit({ status: "refreshing" });
6768
- try {
6769
- const result = await this.host.refresh();
6770
- this.commit({ status: "ready", modelCount: result.modelCount });
6771
- } catch {
6772
- this.commit({ status: "error", reason: MODELS_REFRESH_FAILED_REASON });
6773
- }
6774
- }
6775
- commit(next) {
6776
- if (statesEqual(this.state, next))
6777
- return;
6778
- this.revision++;
6779
- this.state = freezeState({
6799
+ setCatalog(status, policies, metadata) {
6800
+ const candidate = ServiceTiersSnapshotSchema.safeParse({
6780
6801
  version: 1,
6781
6802
  publisherId: this.publisherId,
6782
6803
  revision: this.revision,
6783
- status: next.status,
6784
- ...next.modelCount === undefined ? {} : { modelCount: next.modelCount },
6785
- ...next.reason === undefined ? {} : { reason: next.reason }
6804
+ status,
6805
+ policies: [...policies],
6806
+ ...metadata
6786
6807
  });
6787
- this.emitState(this.state);
6788
- }
6789
- emitState(state, requestId) {
6790
- const candidate = requestId === undefined ? state : { ...state, requestId };
6791
- const parsed = ModelsStateSchema.safeParse(candidate);
6792
- if (parsed.success && byteLength2(parsed.data) <= MAX_STATE_BYTES2) {
6793
- this.emit(MODELS_STATE_CHANNEL, freezeParsed2(parsed.data));
6794
- return;
6795
- }
6796
- const fallback = ModelsStateSchema.safeParse({
6808
+ const oversized = candidate.success && new TextEncoder().encode(JSON.stringify(candidate.data)).byteLength > MAX_SNAPSHOT_BYTES2;
6809
+ let next = candidate.success && !oversized ? candidate.data : {
6797
6810
  version: 1,
6798
6811
  publisherId: this.publisherId,
6799
6812
  revision: this.revision,
6800
- ...requestId === undefined ? {} : { requestId },
6801
- status: "error",
6802
- reason: "Plexus catalog state is unavailable."
6813
+ status: "unavailable",
6814
+ policies: [],
6815
+ reason: oversized ? "Service-tier snapshot exceeds the 1 MiB publication limit." : "Service-tier snapshot could not be validated."
6816
+ };
6817
+ if (status !== "ready" && policies.length > 0) {
6818
+ next = {
6819
+ ...next,
6820
+ status: "unavailable",
6821
+ policies: [],
6822
+ reason: "Service-tier metadata is unavailable."
6823
+ };
6824
+ }
6825
+ const { revision: _revision, ...stateWithoutRevision } = this.state;
6826
+ const { revision: _candidateRevision, ...nextWithoutRevision } = next;
6827
+ if (JSON.stringify(stateWithoutRevision) === JSON.stringify(nextWithoutRevision))
6828
+ return false;
6829
+ this.revision++;
6830
+ this.state = Object.freeze({
6831
+ ...next,
6832
+ revision: this.revision,
6833
+ policies: Object.freeze(next.policies.map((policy) => Object.freeze({
6834
+ ...policy,
6835
+ serviceTiers: Object.freeze([...policy.serviceTiers])
6836
+ })))
6803
6837
  });
6804
- if (fallback.success)
6805
- this.emit(MODELS_STATE_CHANNEL, freezeParsed2(fallback.data));
6838
+ this.send();
6839
+ return true;
6840
+ }
6841
+ send(requestId) {
6842
+ const snapshot = {
6843
+ ...this.state,
6844
+ ...requestId === undefined ? {} : { requestId }
6845
+ };
6846
+ let valid = ServiceTiersSnapshotSchema.safeParse(snapshot);
6847
+ if (!valid.success || new TextEncoder().encode(JSON.stringify(snapshot)).byteLength > MAX_SNAPSHOT_BYTES2) {
6848
+ valid = ServiceTiersSnapshotSchema.safeParse({
6849
+ version: 1,
6850
+ publisherId: this.publisherId,
6851
+ revision: this.revision,
6852
+ status: "unavailable",
6853
+ policies: [],
6854
+ reason: "Service-tier snapshot exceeds publication limits or is invalid.",
6855
+ ...requestId === undefined ? {} : { requestId }
6856
+ });
6857
+ }
6858
+ if (valid.success) {
6859
+ const immutable = Object.freeze({
6860
+ ...valid.data,
6861
+ policies: Object.freeze(valid.data.policies.map((policy) => Object.freeze({
6862
+ ...policy,
6863
+ serviceTiers: Object.freeze([...policy.serviceTiers])
6864
+ })))
6865
+ });
6866
+ this.emit(SERVICE_TIERS_SNAPSHOT_CHANNEL, immutable);
6867
+ }
6868
+ }
6869
+ dispose() {
6870
+ this.unsubscribe();
6806
6871
  }
6807
6872
  }
6808
6873
 
@@ -6810,31 +6875,27 @@ class ModelsControl {
6810
6875
  var PROVIDER_NAME = "plexus";
6811
6876
  var PLEXUS_CREDENTIAL_EXPIRES_AT = 253402300799000;
6812
6877
  var PLACEHOLDER_BASE_URL = "http://localhost/v1";
6813
- var currentModels = [];
6814
- var activeContextPolicies;
6815
- var activeServiceTiers;
6816
- var activePolicy;
6817
- var activePolicyModel;
6818
- var policyModelRegistry;
6819
- var refreshSequence = 0;
6820
- var catalogSource = "none";
6821
6878
  function enforceMinimumOutputTokens(payload) {
6822
6879
  if (!payload || typeof payload !== "object" || Array.isArray(payload))
6823
6880
  return payload;
6824
6881
  const next = { ...payload };
6825
6882
  let changed = false;
6826
- for (const field of ["max_completion_tokens", "max_tokens", "max_output_tokens"]) {
6883
+ for (const field of [
6884
+ "max_completion_tokens",
6885
+ "max_tokens",
6886
+ "max_output_tokens"
6887
+ ]) {
6827
6888
  const value = next[field];
6828
6889
  if (typeof value === "number" && Number.isFinite(value) && value < MINIMUM_OUTPUT_TOKENS) {
6829
6890
  next[field] = MINIMUM_OUTPUT_TOKENS;
6830
6891
  changed = true;
6831
6892
  }
6832
6893
  }
6833
- const generationConfig = next["generationConfig"];
6894
+ const generationConfig = next.generationConfig;
6834
6895
  if (generationConfig && typeof generationConfig === "object" && !Array.isArray(generationConfig)) {
6835
- const maxOutputTokens = generationConfig["maxOutputTokens"];
6896
+ const maxOutputTokens = generationConfig.maxOutputTokens;
6836
6897
  if (typeof maxOutputTokens === "number" && Number.isFinite(maxOutputTokens) && maxOutputTokens < MINIMUM_OUTPUT_TOKENS) {
6837
- next["generationConfig"] = {
6898
+ next.generationConfig = {
6838
6899
  ...generationConfig,
6839
6900
  maxOutputTokens: MINIMUM_OUTPUT_TOKENS
6840
6901
  };
@@ -6843,7 +6904,7 @@ function enforceMinimumOutputTokens(payload) {
6843
6904
  }
6844
6905
  return changed ? next : payload;
6845
6906
  }
6846
- function withAuthoritativeApiKeyEnv(provider, envName, getHeaderModels = () => currentModels) {
6907
+ function withAuthoritativeApiKeyEnv(provider, envName, getHeaderModels = () => []) {
6847
6908
  const apiKey = provider.auth.apiKey;
6848
6909
  if (!apiKey)
6849
6910
  return provider;
@@ -6932,31 +6993,47 @@ function createPolicyHost(deps) {
6932
6993
  }
6933
6994
  function plexusExtension(pi) {
6934
6995
  const contextPolicies = new ContextPolicyPublisher(pi.events);
6935
- activeContextPolicies = contextPolicies;
6936
6996
  const serviceTiers = new ServiceTiersPublisher(pi.events);
6937
- activeServiceTiers = serviceTiers;
6997
+ const state = {
6998
+ models: [],
6999
+ catalogSource: "none",
7000
+ refreshSequence: 0,
7001
+ contextPolicies,
7002
+ serviceTiers,
7003
+ policy: undefined,
7004
+ activeModel: undefined,
7005
+ registry: undefined
7006
+ };
6938
7007
  const policy = new PolicyController(pi.events, createPolicyHost({
6939
- getActiveModel: () => activePolicyModel,
6940
- getModels: () => currentModels,
6941
- getRegistry: () => policyModelRegistry,
7008
+ getActiveModel: () => state.activeModel,
7009
+ getModels: () => state.models,
7010
+ getRegistry: () => state.registry,
6942
7011
  setModel: (model) => pi.setModel(model),
6943
7012
  setActiveModel: (model) => {
6944
- activePolicyModel = model;
7013
+ state.activeModel = model;
6945
7014
  }
6946
7015
  }));
6947
- activePolicy = policy;
7016
+ state.policy = policy;
6948
7017
  const modelsControl = new ModelsControl(pi.events, {
6949
7018
  refresh: async () => {
6950
- const registry = policyModelRegistry;
6951
- if (!registry)
6952
- throw new Error("Plexus model registry is unavailable before the session starts.");
6953
- const result = await registry.refresh({ providers: [PROVIDER_NAME], force: true });
6954
- if (result.aborted)
7019
+ const registry = state.registry;
7020
+ if (!registry) {
7021
+ const message = "Plexus model registry is unavailable before the session starts.";
7022
+ log("models:refresh unavailable", { reason: message });
7023
+ throw new Error(message);
7024
+ }
7025
+ const result = await registry.refresh({
7026
+ providers: [PROVIDER_NAME],
7027
+ force: true
7028
+ });
7029
+ if (result.aborted) {
7030
+ log("models:refresh aborted", {});
6955
7031
  throw new Error("Plexus model refresh was cancelled.");
7032
+ }
6956
7033
  const refreshError = result.errors.get(PROVIDER_NAME);
6957
7034
  if (refreshError)
6958
7035
  throw refreshError;
6959
- return { modelCount: currentModels.length };
7036
+ return { modelCount: state.models.length };
6960
7037
  }
6961
7038
  });
6962
7039
  pi.on("session_shutdown", () => {
@@ -6964,12 +7041,12 @@ function plexusExtension(pi) {
6964
7041
  serviceTiers.dispose();
6965
7042
  policy.dispose();
6966
7043
  modelsControl.dispose();
6967
- if (activeContextPolicies === contextPolicies)
6968
- activeContextPolicies = undefined;
6969
- if (activeServiceTiers === serviceTiers)
6970
- activeServiceTiers = undefined;
6971
- if (activePolicy === policy)
6972
- activePolicy = undefined;
7044
+ if (state.contextPolicies === contextPolicies)
7045
+ state.contextPolicies = undefined;
7046
+ if (state.serviceTiers === serviceTiers)
7047
+ state.serviceTiers = undefined;
7048
+ if (state.policy === policy)
7049
+ state.policy = undefined;
6973
7050
  });
6974
7051
  const apiKeyEnvExplicit = isApiKeyEnvExplicit();
6975
7052
  const explicitApiKey = apiKeyEnvExplicit ? resolveExplicitApiKey() : undefined;
@@ -6979,30 +7056,33 @@ function plexusExtension(pi) {
6979
7056
  const suppressPatterns = getSuppressedModels();
6980
7057
  const storedCatalog = readStoredModelsSync();
6981
7058
  const startupModels = (storedCatalog?.models ?? []).filter((model) => !isModelSuppressed({ id: model.id, name: model.name }, suppressPatterns));
6982
- currentModels = startupModels;
6983
- catalogSource = startupModels.length > 0 ? "host store" : "none";
7059
+ state.models = startupModels;
7060
+ state.catalogSource = startupModels.length > 0 ? "host store" : "none";
6984
7061
  const startupPolicies = collectStoredContextPolicies(startupModels);
6985
- contextPolicies.setCatalog(startupPolicies.length > 0 ? "ready" : "unavailable", startupPolicies.map((entry) => entry.policy), startupPolicies.length > 0 ? { cached: true, fetchedAt: startupPolicies[0].fetchedAt } : { cached: true, reason: CONTEXT_POLICY_METADATA_UNAVAILABLE_REASON });
7062
+ contextPolicies.setCatalog(startupPolicies.length > 0 ? "ready" : "unavailable", startupPolicies.map((entry) => entry.policy), startupPolicies.length > 0 ? { cached: true, fetchedAt: startupPolicies[0]?.fetchedAt } : { cached: true, reason: CONTEXT_POLICY_METADATA_UNAVAILABLE_REASON });
6986
7063
  if (storedCatalog) {
6987
7064
  const cachedTiers = collectStoredServiceTiers(startupModels);
6988
- serviceTiers.setCatalog(cachedTiers.complete ? "ready" : "unavailable", cachedTiers.policies, cachedTiers.complete ? { cached: true, ...cachedTiers.fetchedAt === undefined ? {} : { fetchedAt: cachedTiers.fetchedAt } } : { cached: true, reason: SERVICE_TIERS_METADATA_UNAVAILABLE_REASON });
7065
+ serviceTiers.setCatalog(cachedTiers.complete ? "ready" : "unavailable", cachedTiers.policies, cachedTiers.complete ? {
7066
+ cached: true,
7067
+ ...cachedTiers.fetchedAt === undefined ? {} : { fetchedAt: cachedTiers.fetchedAt }
7068
+ } : { cached: true, reason: SERVICE_TIERS_METADATA_UNAVAILABLE_REASON });
6989
7069
  }
6990
7070
  policy.reconcile();
6991
7071
  pi.on("session_start", (_event, ctx) => {
6992
- policyModelRegistry = ctx.modelRegistry;
6993
- activePolicyModel = ctx.model;
6994
- activePolicy?.reconcile();
7072
+ state.registry = ctx.modelRegistry;
7073
+ state.activeModel = ctx.model;
7074
+ state.policy?.reconcile();
6995
7075
  });
6996
7076
  pi.on("model_select", (event, ctx) => {
6997
- policyModelRegistry = ctx.modelRegistry;
6998
- activePolicyModel = event.model;
6999
- activePolicy?.reconcile();
7077
+ state.registry = ctx.modelRegistry;
7078
+ state.activeModel = event.model;
7079
+ state.policy?.reconcile();
7000
7080
  });
7001
7081
  pi.on("before_provider_request", (event, ctx) => {
7002
7082
  if (ctx.model?.provider !== PROVIDER_NAME)
7003
7083
  return;
7004
- activePolicyModel = ctx.model;
7005
- const withTier = injectServiceTier(event.payload, activePolicy?.serviceTierFor(ctx.model));
7084
+ state.activeModel = ctx.model;
7085
+ const withTier = injectServiceTier(event.payload, state.policy?.serviceTierFor(ctx.model));
7006
7086
  const next = enforceMinimumOutputTokens(withTier);
7007
7087
  return next === event.payload ? undefined : next;
7008
7088
  });
@@ -7018,7 +7098,7 @@ function plexusExtension(pi) {
7018
7098
  authHeader: true,
7019
7099
  baseUrl: startupBaseUrl ?? PLACEHOLDER_BASE_URL,
7020
7100
  models: startupModels,
7021
- refreshModels: refreshPlexusModels,
7101
+ refreshModels: (context) => refreshPlexusModels(state, context),
7022
7102
  oauth: createPlexusLoginProvider()
7023
7103
  });
7024
7104
  if (apiKeyEnvExplicit) {
@@ -7030,57 +7110,81 @@ function plexusExtension(pi) {
7030
7110
  if (!composed?.auth.apiKey) {
7031
7111
  throw new Error("Plexus apiKeyEnv override failed: provider API-key auth is unavailable");
7032
7112
  }
7033
- pi.registerProvider(withAuthoritativeApiKeyEnv(composed, apiKeyEnvName));
7113
+ pi.registerProvider(withAuthoritativeApiKeyEnv(composed, apiKeyEnvName, () => state.models));
7034
7114
  authOverrideApplied = true;
7035
- log("auth: applied authoritative apiKeyEnv override", { apiKeyEnv: apiKeyEnvName });
7115
+ log("auth: applied authoritative apiKeyEnv override", {
7116
+ apiKeyEnv: apiKeyEnvName
7117
+ });
7036
7118
  });
7037
7119
  }
7038
7120
  pi.registerCommand("plexus", {
7039
7121
  description: "Plexus provider commands: refresh, status (setup: /login plexus)",
7040
7122
  getArgumentCompletions: (prefix) => {
7041
7123
  const subcommands = [
7042
- { value: "refresh", label: "refresh", description: "Refresh Plexus models from the API" },
7043
- { value: "status", label: "status", description: "Show Plexus configuration and catalog status" }
7124
+ {
7125
+ value: "refresh",
7126
+ label: "refresh",
7127
+ description: "Refresh Plexus models from the API"
7128
+ },
7129
+ {
7130
+ value: "status",
7131
+ label: "status",
7132
+ description: "Show Plexus configuration and catalog status"
7133
+ }
7044
7134
  ];
7045
7135
  return prefix.includes(" ") ? null : subcommands.filter((command) => command.value.startsWith(prefix));
7046
7136
  },
7047
7137
  handler: async (args, ctx) => {
7048
7138
  const sub = args.trim().toLowerCase();
7049
7139
  if (sub === "refresh" || sub === "")
7050
- return handleRefresh(ctx);
7140
+ return handleRefresh(state, ctx);
7051
7141
  if (sub === "status")
7052
- return handleStatus(ctx);
7142
+ return handleStatus(state, ctx);
7053
7143
  ctx.ui.notify(`Unknown sub-command: "${args}". Use /login plexus, /plexus refresh, or /plexus status.`, "warning");
7054
7144
  }
7055
7145
  });
7056
7146
  }
7057
- async function refreshPlexusModels(context) {
7058
- const refreshId = ++refreshSequence;
7147
+ async function refreshPlexusModels(state, context) {
7148
+ const refreshId = ++state.refreshSequence;
7059
7149
  const baseUrl = getBaseUrl();
7060
7150
  const modelsUrl = getModelsUrl();
7061
7151
  const apiKey = resolveApiKey(credentialApiKey(context.credential));
7062
7152
  const suppress = getSuppressedModels();
7063
7153
  if (!context.allowNetwork || !apiKey || !modelsUrl || !baseUrl) {
7064
- if (currentModels.length > 0) {
7065
- const filteredCurrent = currentModels.filter((m) => !isModelSuppressed({ id: m.id, name: m.name }, suppress));
7154
+ if (state.models.length > 0) {
7155
+ const filteredCurrent = state.models.filter((m) => !isModelSuppressed({ id: m.id, name: m.name }, suppress));
7066
7156
  await context.publish({
7067
- persist: { models: filteredCurrent, checkedAt: Date.now() },
7157
+ persist: {
7158
+ models: filteredCurrent,
7159
+ checkedAt: Date.now()
7160
+ },
7068
7161
  update: () => {
7069
- currentModels = filteredCurrent;
7162
+ state.models = filteredCurrent;
7070
7163
  const cachedTiers = collectStoredServiceTiers(filteredCurrent);
7071
- activeServiceTiers?.setCatalog(cachedTiers.complete ? "ready" : "unavailable", cachedTiers.policies, cachedTiers.complete ? { cached: true, ...cachedTiers.fetchedAt === undefined ? {} : { fetchedAt: cachedTiers.fetchedAt } } : { cached: true, reason: SERVICE_TIERS_METADATA_UNAVAILABLE_REASON });
7164
+ state.serviceTiers?.setCatalog(cachedTiers.complete ? "ready" : "unavailable", cachedTiers.policies, cachedTiers.complete ? {
7165
+ cached: true,
7166
+ ...cachedTiers.fetchedAt === undefined ? {} : { fetchedAt: cachedTiers.fetchedAt }
7167
+ } : {
7168
+ cached: true,
7169
+ reason: SERVICE_TIERS_METADATA_UNAVAILABLE_REASON
7170
+ });
7072
7171
  const cachedPolicies = collectStoredContextPolicies(filteredCurrent);
7073
- activeContextPolicies?.setCatalog(cachedPolicies.length > 0 ? "ready" : "unavailable", cachedPolicies.map((entry) => entry.policy), cachedPolicies.length > 0 ? { cached: true, fetchedAt: cachedPolicies[0].fetchedAt } : { cached: true, reason: CONTEXT_POLICY_METADATA_UNAVAILABLE_REASON });
7074
- activePolicy?.reconcile();
7172
+ state.contextPolicies?.setCatalog(cachedPolicies.length > 0 ? "ready" : "unavailable", cachedPolicies.map((entry) => entry.policy), cachedPolicies.length > 0 ? { cached: true, fetchedAt: cachedPolicies[0]?.fetchedAt } : {
7173
+ cached: true,
7174
+ reason: CONTEXT_POLICY_METADATA_UNAVAILABLE_REASON
7175
+ });
7176
+ state.policy?.reconcile();
7075
7177
  }
7076
7178
  });
7077
7179
  return filteredCurrent;
7078
7180
  }
7079
- const restored = await restoreStoredModels(context);
7181
+ const restored = await restoreStoredModels(state, context);
7080
7182
  if (restored)
7081
7183
  return restored;
7082
- if (refreshId === refreshSequence && activeServiceTiers?.getSnapshot().status === "loading") {
7083
- activeServiceTiers.setCatalog("unavailable", [], { reason: "Plexus model metadata is not configured." });
7184
+ if (refreshId === state.refreshSequence && state.serviceTiers?.getSnapshot().status === "loading") {
7185
+ state.serviceTiers.setCatalog("unavailable", [], {
7186
+ reason: "Plexus model metadata is not configured."
7187
+ });
7084
7188
  }
7085
7189
  throw new Error(!modelsUrl || !baseUrl ? "Plexus base URL not configured. Run /login plexus first." : "No Plexus API key configured. Run /login plexus first.");
7086
7190
  }
@@ -7099,18 +7203,26 @@ async function refreshPlexusModels(context) {
7099
7203
  const policy = contextPolicyFromApiModel(model);
7100
7204
  if (policy)
7101
7205
  piModel.plexusContextPolicy = { policy, fetchedAt };
7102
- piModel.plexusServiceTiers = { policy: serviceTierPolicyFromApiModel(model), fetchedAt };
7206
+ piModel.plexusServiceTiers = {
7207
+ policy: serviceTierPolicyFromApiModel(model),
7208
+ fetchedAt
7209
+ };
7103
7210
  }
7104
7211
  const committedPolicies = collectStoredContextPolicies(piModels);
7105
7212
  const committedServiceTiers = collectStoredServiceTiers(piModels).policies;
7106
7213
  const published = await context.publish({
7107
- persist: { models: piModels, checkedAt: Date.now() },
7214
+ persist: {
7215
+ models: piModels,
7216
+ checkedAt: Date.now()
7217
+ },
7108
7218
  update: () => {
7109
- currentModels = piModels;
7110
- catalogSource = "live refresh";
7111
- activeServiceTiers?.setCatalog("ready", committedServiceTiers, { fetchedAt });
7112
- activeContextPolicies?.setCatalog(committedPolicies.length > 0 ? "ready" : "unavailable", committedPolicies.map((entry) => entry.policy), committedPolicies.length > 0 ? { fetchedAt } : { fetchedAt, reason: CONTEXT_POLICY_METADATA_UNAVAILABLE_REASON });
7113
- activePolicy?.reconcile();
7219
+ state.models = piModels;
7220
+ state.catalogSource = "live refresh";
7221
+ state.serviceTiers?.setCatalog("ready", committedServiceTiers, {
7222
+ fetchedAt
7223
+ });
7224
+ state.contextPolicies?.setCatalog(committedPolicies.length > 0 ? "ready" : "unavailable", committedPolicies.map((entry) => entry.policy), committedPolicies.length > 0 ? { fetchedAt } : { fetchedAt, reason: CONTEXT_POLICY_METADATA_UNAVAILABLE_REASON });
7225
+ state.policy?.reconcile();
7114
7226
  }
7115
7227
  });
7116
7228
  if (!published) {
@@ -7119,17 +7231,21 @@ async function refreshPlexusModels(context) {
7119
7231
  log("refreshModels: fetched", { count: piModels.length });
7120
7232
  return piModels;
7121
7233
  } catch (error) {
7122
- if (refreshId === refreshSequence && activeContextPolicies?.getSnapshot().status === "loading") {
7123
- activeContextPolicies.setCatalog("unavailable", [], { reason: "Plexus model metadata could not be loaded." });
7234
+ if (refreshId === state.refreshSequence && state.contextPolicies?.getSnapshot().status === "loading") {
7235
+ state.contextPolicies.setCatalog("unavailable", [], {
7236
+ reason: "Plexus model metadata could not be loaded."
7237
+ });
7124
7238
  }
7125
- if (refreshId === refreshSequence && activeServiceTiers?.getSnapshot().status === "loading") {
7126
- activeServiceTiers.setCatalog("unavailable", [], { reason: "Plexus model metadata could not be loaded." });
7239
+ if (refreshId === state.refreshSequence && state.serviceTiers?.getSnapshot().status === "loading") {
7240
+ state.serviceTiers.setCatalog("unavailable", [], {
7241
+ reason: "Plexus model metadata could not be loaded."
7242
+ });
7127
7243
  }
7128
7244
  log("refreshModels: fetch failed", { error: String(error) });
7129
7245
  throw error;
7130
7246
  }
7131
7247
  }
7132
- async function restoreStoredModels(context) {
7248
+ async function restoreStoredModels(state, context) {
7133
7249
  const stored = context.stored;
7134
7250
  if (!stored || stored.models.length === 0)
7135
7251
  return;
@@ -7137,13 +7253,19 @@ async function restoreStoredModels(context) {
7137
7253
  const models = stored.models.filter((m) => !isModelSuppressed({ id: m.id, name: m.name }, suppress));
7138
7254
  await context.publish({
7139
7255
  update: () => {
7140
- currentModels = models;
7141
- catalogSource = "host store";
7256
+ state.models = models;
7257
+ state.catalogSource = "host store";
7142
7258
  const cachedTiers = collectStoredServiceTiers(models);
7143
- activeServiceTiers?.setCatalog(cachedTiers.complete ? "ready" : "unavailable", cachedTiers.policies, cachedTiers.complete ? { cached: true, ...cachedTiers.fetchedAt === undefined ? {} : { fetchedAt: cachedTiers.fetchedAt } } : { cached: true, reason: SERVICE_TIERS_METADATA_UNAVAILABLE_REASON });
7259
+ state.serviceTiers?.setCatalog(cachedTiers.complete ? "ready" : "unavailable", cachedTiers.policies, cachedTiers.complete ? {
7260
+ cached: true,
7261
+ ...cachedTiers.fetchedAt === undefined ? {} : { fetchedAt: cachedTiers.fetchedAt }
7262
+ } : { cached: true, reason: SERVICE_TIERS_METADATA_UNAVAILABLE_REASON });
7144
7263
  const cachedPolicies = collectStoredContextPolicies(models);
7145
- activeContextPolicies?.setCatalog(cachedPolicies.length > 0 ? "ready" : "unavailable", cachedPolicies.map((entry) => entry.policy), cachedPolicies.length > 0 ? { cached: true, fetchedAt: cachedPolicies[0].fetchedAt } : { cached: true, reason: CONTEXT_POLICY_METADATA_UNAVAILABLE_REASON });
7146
- activePolicy?.reconcile();
7264
+ state.contextPolicies?.setCatalog(cachedPolicies.length > 0 ? "ready" : "unavailable", cachedPolicies.map((entry) => entry.policy), cachedPolicies.length > 0 ? { cached: true, fetchedAt: cachedPolicies[0]?.fetchedAt } : {
7265
+ cached: true,
7266
+ reason: CONTEXT_POLICY_METADATA_UNAVAILABLE_REASON
7267
+ });
7268
+ state.policy?.reconcile();
7147
7269
  }
7148
7270
  });
7149
7271
  log("refreshModels: restored from store", { count: models.length });
@@ -7152,7 +7274,7 @@ async function restoreStoredModels(context) {
7152
7274
  function contextPolicyFromApiModel(model) {
7153
7275
  const maxContextTokens = model.context_length;
7154
7276
  const pricingThresholdInputTokens = model.pricing?.tiers?.[0]?.input_tokens_above;
7155
- if (!Number.isSafeInteger(maxContextTokens) || maxContextTokens <= 0 || !Number.isSafeInteger(pricingThresholdInputTokens) || pricingThresholdInputTokens <= 0 || pricingThresholdInputTokens > maxContextTokens)
7277
+ if (typeof maxContextTokens !== "number" || !Number.isSafeInteger(maxContextTokens) || maxContextTokens <= 0 || typeof pricingThresholdInputTokens !== "number" || !Number.isSafeInteger(pricingThresholdInputTokens) || pricingThresholdInputTokens <= 0 || pricingThresholdInputTokens > maxContextTokens)
7156
7278
  return;
7157
7279
  return {
7158
7280
  provider: PROVIDER_NAME,
@@ -7172,7 +7294,11 @@ function serviceTierPolicyFromApiModel(model) {
7172
7294
  const serviceTiers = model.service_tiers;
7173
7295
  if (!Array.isArray(serviceTiers) || serviceTiers.length === 0)
7174
7296
  return;
7175
- const candidate = { provider: PROVIDER_NAME, modelId: model.id, serviceTiers };
7297
+ const candidate = {
7298
+ provider: PROVIDER_NAME,
7299
+ modelId: model.id,
7300
+ serviceTiers
7301
+ };
7176
7302
  const parsed = ServiceTierPolicySchema.safeParse(candidate);
7177
7303
  return parsed.success ? parsed.data : undefined;
7178
7304
  }
@@ -7231,7 +7357,7 @@ function createPlexusLoginProvider() {
7231
7357
  }
7232
7358
  };
7233
7359
  }
7234
- async function handleRefresh(ctx) {
7360
+ async function handleRefresh(state, ctx) {
7235
7361
  let apiKey;
7236
7362
  try {
7237
7363
  apiKey = await ctx.modelRegistry.getApiKeyForProvider(PROVIDER_NAME);
@@ -7244,7 +7370,10 @@ async function handleRefresh(ctx) {
7244
7370
  return;
7245
7371
  }
7246
7372
  ctx.ui.notify("Refreshing Plexus models\u2026", "info");
7247
- const result = await ctx.modelRegistry.refresh({ providers: [PROVIDER_NAME], force: true });
7373
+ const result = await ctx.modelRegistry.refresh({
7374
+ providers: [PROVIDER_NAME],
7375
+ force: true
7376
+ });
7248
7377
  if (result.aborted) {
7249
7378
  ctx.ui.notify("Plexus model refresh was cancelled.", "warning");
7250
7379
  return;
@@ -7254,9 +7383,9 @@ async function handleRefresh(ctx) {
7254
7383
  ctx.ui.notify(`Plexus model refresh failed: ${refreshError.message}`, "error");
7255
7384
  return;
7256
7385
  }
7257
- 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");
7386
+ ctx.ui.notify(state.models.length > 0 ? `Refreshed ${state.models.length} Plexus models` : "Refresh finished but no Plexus models are available. Check the Plexus server and /login plexus.", state.models.length > 0 ? "info" : "warning");
7258
7387
  }
7259
- async function handleStatus(ctx) {
7388
+ async function handleStatus(state, ctx) {
7260
7389
  const baseUrl = getBaseUrlResolution();
7261
7390
  const apiKeyEnvName = getApiKeyEnvName();
7262
7391
  const apiKey = await ctx.modelRegistry.getApiKeyForProvider(PROVIDER_NAME).catch(() => {
@@ -7266,7 +7395,7 @@ async function handleStatus(ctx) {
7266
7395
  ctx.ui.notify([
7267
7396
  `Plexus base URL: ${baseUrl.baseUrl ?? "not configured"} (${baseUrl.source})`,
7268
7397
  `API key: ${apiKey ? explicitApiKey !== undefined ? `${apiKeyEnvName} (apiKeyEnv)` : getEnvApiKey() ? `host credential or ${apiKeyEnvName} fallback` : "host credential" : "not configured"}`,
7269
- `Catalog: ${currentModels.length} models (${catalogSource})`,
7398
+ `Catalog: ${state.models.length} models (${state.catalogSource})`,
7270
7399
  "Default model: managed by Pi. Use /model and save the selection there."
7271
7400
  ].join(`
7272
7401
  `), "info");