@mcowger/pi-plexus 1.12.0 → 1.13.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.
- package/dist/extension.js +820 -554
- 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([
|
|
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
|
|
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
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
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
|
|
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
|
|
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
|
|
171
|
+
if (!model?.id)
|
|
215
172
|
return false;
|
|
216
|
-
const patterns =
|
|
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 =
|
|
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/
|
|
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 {
|
|
358
|
-
|
|
359
|
-
|
|
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 (
|
|
436
|
-
cachedConfig = JSON.parse(
|
|
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 =
|
|
554
|
+
const configSuppressed = parseSuppressionPatterns2(config.suppressModels ?? config.suppress);
|
|
521
555
|
return [...envSuppressed, ...configSuppressed];
|
|
522
556
|
}
|
|
523
557
|
|
|
524
|
-
// src/
|
|
525
|
-
import {
|
|
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
|
-
//
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
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
|
-
|
|
560
|
-
|
|
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
|
-
|
|
574
|
-
|
|
575
|
-
|
|
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
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
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
|
|
650
|
-
return
|
|
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({
|
|
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({
|
|
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 = {
|
|
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 = {
|
|
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({
|
|
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 = {
|
|
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/
|
|
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
|
|
6274
|
-
var
|
|
6275
|
-
var
|
|
6276
|
-
|
|
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
|
|
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(["
|
|
6290
|
-
|
|
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()
|
|
6295
|
-
|
|
6296
|
-
|
|
6297
|
-
|
|
6298
|
-
|
|
6299
|
-
|
|
6300
|
-
|
|
6301
|
-
}
|
|
6302
|
-
|
|
6303
|
-
|
|
6304
|
-
}
|
|
6305
|
-
}
|
|
6306
|
-
|
|
6307
|
-
|
|
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
|
|
6344
|
+
class ModelsControl {
|
|
6345
|
+
host;
|
|
6310
6346
|
publisherId = randomUUID2();
|
|
6311
6347
|
revision = 1;
|
|
6312
|
-
state
|
|
6313
|
-
|
|
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.
|
|
6324
|
-
|
|
6325
|
-
|
|
6326
|
-
|
|
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
|
-
|
|
6363
|
+
getState() {
|
|
6330
6364
|
return this.state;
|
|
6331
6365
|
}
|
|
6332
|
-
|
|
6333
|
-
|
|
6366
|
+
dispose() {
|
|
6367
|
+
this.unsubscribe();
|
|
6368
|
+
}
|
|
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;
|
|
6377
|
+
});
|
|
6378
|
+
}
|
|
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 });
|
|
6390
|
+
}
|
|
6391
|
+
}
|
|
6392
|
+
commit(next) {
|
|
6393
|
+
if (statesEqual(this.state, next))
|
|
6394
|
+
return;
|
|
6395
|
+
this.revision++;
|
|
6396
|
+
this.state = freezeState({
|
|
6334
6397
|
version: 1,
|
|
6335
6398
|
publisherId: this.publisherId,
|
|
6336
6399
|
revision: this.revision,
|
|
6337
|
-
status,
|
|
6338
|
-
|
|
6339
|
-
...
|
|
6400
|
+
status: next.status,
|
|
6401
|
+
...next.modelCount === undefined ? {} : { modelCount: next.modelCount },
|
|
6402
|
+
...next.reason === undefined ? {} : { reason: next.reason }
|
|
6340
6403
|
});
|
|
6341
|
-
|
|
6342
|
-
|
|
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({
|
|
6343
6414
|
version: 1,
|
|
6344
6415
|
publisherId: this.publisherId,
|
|
6345
6416
|
revision: this.revision,
|
|
6346
|
-
|
|
6347
|
-
|
|
6348
|
-
reason:
|
|
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
|
-
})))
|
|
6417
|
+
...requestId === undefined ? {} : { requestId },
|
|
6418
|
+
status: "error",
|
|
6419
|
+
reason: "Plexus catalog state is unavailable."
|
|
6365
6420
|
});
|
|
6366
|
-
|
|
6367
|
-
|
|
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 }
|
|
6381
|
-
});
|
|
6382
|
-
}
|
|
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);
|
|
6392
|
-
}
|
|
6393
|
-
}
|
|
6394
|
-
dispose() {
|
|
6395
|
-
this.unsubscribe();
|
|
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
|
|
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({
|
|
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 {
|
|
@@ -6448,13 +6478,13 @@ function injectServiceTier(payload, tier) {
|
|
|
6448
6478
|
return payload;
|
|
6449
6479
|
if (!payload || typeof payload !== "object" || Array.isArray(payload))
|
|
6450
6480
|
return payload;
|
|
6451
|
-
return { ...payload, service_tier: tier };
|
|
6452
|
-
}
|
|
6453
|
-
var encoder = new TextEncoder;
|
|
6454
|
-
function byteLength(value) {
|
|
6455
|
-
return encoder.encode(JSON.stringify(value)).byteLength;
|
|
6481
|
+
return { ...payload, service_tier: tier };
|
|
6456
6482
|
}
|
|
6457
|
-
|
|
6483
|
+
var encoder2 = new TextEncoder;
|
|
6484
|
+
function byteLength2(value) {
|
|
6485
|
+
return encoder2.encode(JSON.stringify(value)).byteLength;
|
|
6486
|
+
}
|
|
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({
|
|
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
|
|
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 = {
|
|
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
|
|
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 &&
|
|
6671
|
-
this.emit(POLICY_STATE_CHANNEL,
|
|
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 &&
|
|
6678
|
-
this.emit(POLICY_STATE_CHANNEL,
|
|
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,
|
|
6728
|
+
this.emit(POLICY_STATE_CHANNEL, freezeParsed2(fallback.data));
|
|
6692
6729
|
}
|
|
6693
6730
|
}
|
|
6694
6731
|
|
|
6695
|
-
// src/
|
|
6732
|
+
// src/service-tiers.ts
|
|
6696
6733
|
import { randomUUID as randomUUID4 } from "crypto";
|
|
6697
|
-
var
|
|
6698
|
-
var
|
|
6699
|
-
var
|
|
6700
|
-
|
|
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
|
|
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(["
|
|
6710
|
-
|
|
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
|
-
|
|
6714
|
-
|
|
6715
|
-
|
|
6716
|
-
|
|
6717
|
-
|
|
6718
|
-
|
|
6719
|
-
|
|
6720
|
-
}
|
|
6721
|
-
|
|
6722
|
-
|
|
6723
|
-
|
|
6724
|
-
|
|
6725
|
-
|
|
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
|
|
6729
|
-
host;
|
|
6776
|
+
class ServiceTiersPublisher {
|
|
6730
6777
|
publisherId = randomUUID4();
|
|
6731
6778
|
revision = 1;
|
|
6732
|
-
state
|
|
6733
|
-
|
|
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
|
|
6737
|
-
this.host = host;
|
|
6788
|
+
constructor(events) {
|
|
6738
6789
|
this.emit = events.emit.bind(events);
|
|
6739
|
-
this.
|
|
6740
|
-
|
|
6741
|
-
|
|
6742
|
-
|
|
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
|
-
|
|
6796
|
+
getSnapshot() {
|
|
6748
6797
|
return this.state;
|
|
6749
6798
|
}
|
|
6750
|
-
|
|
6751
|
-
|
|
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
|
|
6784
|
-
|
|
6785
|
-
...
|
|
6804
|
+
status,
|
|
6805
|
+
policies: [...policies],
|
|
6806
|
+
...metadata
|
|
6786
6807
|
});
|
|
6787
|
-
|
|
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
|
-
|
|
6801
|
-
|
|
6802
|
-
reason: "
|
|
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
|
-
|
|
6805
|
-
|
|
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,40 +6875,170 @@ 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 [
|
|
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
|
|
6834
|
-
|
|
6835
|
-
|
|
6836
|
-
|
|
6837
|
-
|
|
6838
|
-
|
|
6839
|
-
|
|
6894
|
+
for (const configKey of ["generationConfig", "config"]) {
|
|
6895
|
+
const generationConfig = next[configKey];
|
|
6896
|
+
if (generationConfig && typeof generationConfig === "object" && !Array.isArray(generationConfig)) {
|
|
6897
|
+
const maxOutputTokens = generationConfig.maxOutputTokens;
|
|
6898
|
+
if (typeof maxOutputTokens === "number" && Number.isFinite(maxOutputTokens) && maxOutputTokens < MINIMUM_OUTPUT_TOKENS) {
|
|
6899
|
+
next[configKey] = {
|
|
6900
|
+
...generationConfig,
|
|
6901
|
+
maxOutputTokens: MINIMUM_OUTPUT_TOKENS
|
|
6902
|
+
};
|
|
6903
|
+
changed = true;
|
|
6904
|
+
}
|
|
6905
|
+
}
|
|
6906
|
+
}
|
|
6907
|
+
return changed ? next : payload;
|
|
6908
|
+
}
|
|
6909
|
+
var EXTENDED_THINKING_LEVELS = [
|
|
6910
|
+
"off",
|
|
6911
|
+
"minimal",
|
|
6912
|
+
"low",
|
|
6913
|
+
"medium",
|
|
6914
|
+
"high",
|
|
6915
|
+
"xhigh",
|
|
6916
|
+
"max"
|
|
6917
|
+
];
|
|
6918
|
+
var GOOGLE_THINKING_LEVELS = {
|
|
6919
|
+
minimal: "MINIMAL",
|
|
6920
|
+
low: "LOW",
|
|
6921
|
+
medium: "MEDIUM",
|
|
6922
|
+
high: "HIGH"
|
|
6923
|
+
};
|
|
6924
|
+
function getGeminiMajorVersion(modelId) {
|
|
6925
|
+
const match = modelId.toLowerCase().match(/^gemini(?:-live)?-(\d+)/);
|
|
6926
|
+
if (!match?.[1])
|
|
6927
|
+
return;
|
|
6928
|
+
return Number.parseInt(match[1], 10);
|
|
6929
|
+
}
|
|
6930
|
+
function usesGoogleThinkingLevel(model) {
|
|
6931
|
+
if (model.thinkingLevelMap && EXTENDED_THINKING_LEVELS.some((level) => level !== "off" && typeof model.thinkingLevelMap?.[level] === "string")) {
|
|
6932
|
+
return true;
|
|
6933
|
+
}
|
|
6934
|
+
const id = model.id.toLowerCase();
|
|
6935
|
+
const majorVersion = getGeminiMajorVersion(id);
|
|
6936
|
+
return majorVersion !== undefined && majorVersion >= 3 || id === "gemini-flash-latest" || id === "gemini-flash-lite-latest" || /gemma-?4/.test(id);
|
|
6937
|
+
}
|
|
6938
|
+
function getSupportedThinkingLevelsForModel(model) {
|
|
6939
|
+
if (!model.reasoning)
|
|
6940
|
+
return ["off"];
|
|
6941
|
+
return EXTENDED_THINKING_LEVELS.filter((level) => {
|
|
6942
|
+
const mapped = model.thinkingLevelMap?.[level];
|
|
6943
|
+
if (mapped === null)
|
|
6944
|
+
return false;
|
|
6945
|
+
if (level === "xhigh" || level === "max")
|
|
6946
|
+
return mapped !== undefined;
|
|
6947
|
+
return true;
|
|
6948
|
+
});
|
|
6949
|
+
}
|
|
6950
|
+
function clampModelThinkingLevel(model, level) {
|
|
6951
|
+
const availableLevels = getSupportedThinkingLevelsForModel(model);
|
|
6952
|
+
if (availableLevels.includes(level))
|
|
6953
|
+
return level;
|
|
6954
|
+
const requestedIndex = EXTENDED_THINKING_LEVELS.indexOf(level);
|
|
6955
|
+
if (requestedIndex === -1)
|
|
6956
|
+
return availableLevels[0] ?? "off";
|
|
6957
|
+
for (let i = requestedIndex;i < EXTENDED_THINKING_LEVELS.length; i++) {
|
|
6958
|
+
const candidate = EXTENDED_THINKING_LEVELS[i];
|
|
6959
|
+
if (candidate && availableLevels.includes(candidate))
|
|
6960
|
+
return candidate;
|
|
6961
|
+
}
|
|
6962
|
+
for (let i = requestedIndex - 1;i >= 0; i--) {
|
|
6963
|
+
const candidate = EXTENDED_THINKING_LEVELS[i];
|
|
6964
|
+
if (candidate && availableLevels.includes(candidate))
|
|
6965
|
+
return candidate;
|
|
6966
|
+
}
|
|
6967
|
+
return availableLevels[0] ?? "off";
|
|
6968
|
+
}
|
|
6969
|
+
function toGoogleThinkingLevel(model, level) {
|
|
6970
|
+
const clamped = clampModelThinkingLevel(model, level);
|
|
6971
|
+
if (clamped === "off")
|
|
6972
|
+
return;
|
|
6973
|
+
const mapped = model.thinkingLevelMap?.[clamped];
|
|
6974
|
+
const resolved = (typeof mapped === "string" ? mapped : clamped).trim().toLowerCase();
|
|
6975
|
+
return GOOGLE_THINKING_LEVELS[resolved];
|
|
6976
|
+
}
|
|
6977
|
+
function normalizeThinkingConfigObject(thinkingConfig, model, thinkingLevel) {
|
|
6978
|
+
if (thinkingConfig.thinkingLevel !== undefined)
|
|
6979
|
+
return thinkingConfig;
|
|
6980
|
+
if (thinkingConfig.thinkingBudget === -1) {
|
|
6981
|
+
const effectiveLevel = thinkingLevel && thinkingLevel !== "off" ? thinkingLevel : "high";
|
|
6982
|
+
const googleLevel = toGoogleThinkingLevel(model, effectiveLevel);
|
|
6983
|
+
if (!googleLevel)
|
|
6984
|
+
return thinkingConfig;
|
|
6985
|
+
const { thinkingBudget: _thinkingBudget, ...rest } = thinkingConfig;
|
|
6986
|
+
return {
|
|
6987
|
+
...rest,
|
|
6988
|
+
thinkingLevel: googleLevel
|
|
6989
|
+
};
|
|
6990
|
+
}
|
|
6991
|
+
if (thinkingConfig.thinkingBudget === 0) {
|
|
6992
|
+
const googleLevel = toGoogleThinkingLevel(model, "off");
|
|
6993
|
+
if (!googleLevel)
|
|
6994
|
+
return thinkingConfig;
|
|
6995
|
+
const { thinkingBudget: _thinkingBudget, ...rest } = thinkingConfig;
|
|
6996
|
+
return {
|
|
6997
|
+
...rest,
|
|
6998
|
+
thinkingLevel: googleLevel
|
|
6999
|
+
};
|
|
7000
|
+
}
|
|
7001
|
+
return thinkingConfig;
|
|
7002
|
+
}
|
|
7003
|
+
function normalizeGoogleThinkingConfig(payload, model, thinkingLevel) {
|
|
7004
|
+
if (!payload || typeof payload !== "object" || Array.isArray(payload))
|
|
7005
|
+
return payload;
|
|
7006
|
+
if (!model?.reasoning)
|
|
7007
|
+
return payload;
|
|
7008
|
+
if (model.api !== "google-generative-ai" && model.api !== "google-vertex")
|
|
7009
|
+
return payload;
|
|
7010
|
+
if (!usesGoogleThinkingLevel(model))
|
|
7011
|
+
return payload;
|
|
7012
|
+
const next = { ...payload };
|
|
7013
|
+
let changed = false;
|
|
7014
|
+
for (const configKey of ["config", "generationConfig"]) {
|
|
7015
|
+
const container = next[configKey];
|
|
7016
|
+
if (!container || typeof container !== "object" || Array.isArray(container))
|
|
7017
|
+
continue;
|
|
7018
|
+
const containerRecord = container;
|
|
7019
|
+
const thinkingConfig = containerRecord.thinkingConfig;
|
|
7020
|
+
if (!thinkingConfig || typeof thinkingConfig !== "object" || Array.isArray(thinkingConfig)) {
|
|
7021
|
+
continue;
|
|
7022
|
+
}
|
|
7023
|
+
const normalized = normalizeThinkingConfigObject(thinkingConfig, model, thinkingLevel);
|
|
7024
|
+
if (normalized !== thinkingConfig) {
|
|
7025
|
+
next[configKey] = {
|
|
7026
|
+
...containerRecord,
|
|
7027
|
+
thinkingConfig: normalized
|
|
6840
7028
|
};
|
|
6841
7029
|
changed = true;
|
|
6842
7030
|
}
|
|
6843
7031
|
}
|
|
6844
7032
|
return changed ? next : payload;
|
|
6845
7033
|
}
|
|
6846
|
-
function
|
|
7034
|
+
function getSessionThinkingLevel(pi) {
|
|
7035
|
+
try {
|
|
7036
|
+
return pi.getThinkingLevel?.();
|
|
7037
|
+
} catch {
|
|
7038
|
+
return;
|
|
7039
|
+
}
|
|
7040
|
+
}
|
|
7041
|
+
function withAuthoritativeApiKeyEnv(provider, envName, getHeaderModels = () => []) {
|
|
6847
7042
|
const apiKey = provider.auth.apiKey;
|
|
6848
7043
|
if (!apiKey)
|
|
6849
7044
|
return provider;
|
|
@@ -6932,31 +7127,47 @@ function createPolicyHost(deps) {
|
|
|
6932
7127
|
}
|
|
6933
7128
|
function plexusExtension(pi) {
|
|
6934
7129
|
const contextPolicies = new ContextPolicyPublisher(pi.events);
|
|
6935
|
-
activeContextPolicies = contextPolicies;
|
|
6936
7130
|
const serviceTiers = new ServiceTiersPublisher(pi.events);
|
|
6937
|
-
|
|
7131
|
+
const state = {
|
|
7132
|
+
models: [],
|
|
7133
|
+
catalogSource: "none",
|
|
7134
|
+
refreshSequence: 0,
|
|
7135
|
+
contextPolicies,
|
|
7136
|
+
serviceTiers,
|
|
7137
|
+
policy: undefined,
|
|
7138
|
+
activeModel: undefined,
|
|
7139
|
+
registry: undefined
|
|
7140
|
+
};
|
|
6938
7141
|
const policy = new PolicyController(pi.events, createPolicyHost({
|
|
6939
|
-
getActiveModel: () =>
|
|
6940
|
-
getModels: () =>
|
|
6941
|
-
getRegistry: () =>
|
|
7142
|
+
getActiveModel: () => state.activeModel,
|
|
7143
|
+
getModels: () => state.models,
|
|
7144
|
+
getRegistry: () => state.registry,
|
|
6942
7145
|
setModel: (model) => pi.setModel(model),
|
|
6943
7146
|
setActiveModel: (model) => {
|
|
6944
|
-
|
|
7147
|
+
state.activeModel = model;
|
|
6945
7148
|
}
|
|
6946
7149
|
}));
|
|
6947
|
-
|
|
7150
|
+
state.policy = policy;
|
|
6948
7151
|
const modelsControl = new ModelsControl(pi.events, {
|
|
6949
7152
|
refresh: async () => {
|
|
6950
|
-
const registry =
|
|
6951
|
-
if (!registry)
|
|
6952
|
-
|
|
6953
|
-
|
|
6954
|
-
|
|
7153
|
+
const registry = state.registry;
|
|
7154
|
+
if (!registry) {
|
|
7155
|
+
const message = "Plexus model registry is unavailable before the session starts.";
|
|
7156
|
+
log("models:refresh unavailable", { reason: message });
|
|
7157
|
+
throw new Error(message);
|
|
7158
|
+
}
|
|
7159
|
+
const result = await registry.refresh({
|
|
7160
|
+
providers: [PROVIDER_NAME],
|
|
7161
|
+
force: true
|
|
7162
|
+
});
|
|
7163
|
+
if (result.aborted) {
|
|
7164
|
+
log("models:refresh aborted", {});
|
|
6955
7165
|
throw new Error("Plexus model refresh was cancelled.");
|
|
7166
|
+
}
|
|
6956
7167
|
const refreshError = result.errors.get(PROVIDER_NAME);
|
|
6957
7168
|
if (refreshError)
|
|
6958
7169
|
throw refreshError;
|
|
6959
|
-
return { modelCount:
|
|
7170
|
+
return { modelCount: state.models.length };
|
|
6960
7171
|
}
|
|
6961
7172
|
});
|
|
6962
7173
|
pi.on("session_shutdown", () => {
|
|
@@ -6964,12 +7175,12 @@ function plexusExtension(pi) {
|
|
|
6964
7175
|
serviceTiers.dispose();
|
|
6965
7176
|
policy.dispose();
|
|
6966
7177
|
modelsControl.dispose();
|
|
6967
|
-
if (
|
|
6968
|
-
|
|
6969
|
-
if (
|
|
6970
|
-
|
|
6971
|
-
if (
|
|
6972
|
-
|
|
7178
|
+
if (state.contextPolicies === contextPolicies)
|
|
7179
|
+
state.contextPolicies = undefined;
|
|
7180
|
+
if (state.serviceTiers === serviceTiers)
|
|
7181
|
+
state.serviceTiers = undefined;
|
|
7182
|
+
if (state.policy === policy)
|
|
7183
|
+
state.policy = undefined;
|
|
6973
7184
|
});
|
|
6974
7185
|
const apiKeyEnvExplicit = isApiKeyEnvExplicit();
|
|
6975
7186
|
const explicitApiKey = apiKeyEnvExplicit ? resolveExplicitApiKey() : undefined;
|
|
@@ -6979,31 +7190,35 @@ function plexusExtension(pi) {
|
|
|
6979
7190
|
const suppressPatterns = getSuppressedModels();
|
|
6980
7191
|
const storedCatalog = readStoredModelsSync();
|
|
6981
7192
|
const startupModels = (storedCatalog?.models ?? []).filter((model) => !isModelSuppressed({ id: model.id, name: model.name }, suppressPatterns));
|
|
6982
|
-
|
|
6983
|
-
catalogSource = startupModels.length > 0 ? "host store" : "none";
|
|
7193
|
+
state.models = startupModels;
|
|
7194
|
+
state.catalogSource = startupModels.length > 0 ? "host store" : "none";
|
|
6984
7195
|
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]
|
|
7196
|
+
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
7197
|
if (storedCatalog) {
|
|
6987
7198
|
const cachedTiers = collectStoredServiceTiers(startupModels);
|
|
6988
|
-
serviceTiers.setCatalog(cachedTiers.complete ? "ready" : "unavailable", cachedTiers.policies, cachedTiers.complete ? {
|
|
7199
|
+
serviceTiers.setCatalog(cachedTiers.complete ? "ready" : "unavailable", cachedTiers.policies, cachedTiers.complete ? {
|
|
7200
|
+
cached: true,
|
|
7201
|
+
...cachedTiers.fetchedAt === undefined ? {} : { fetchedAt: cachedTiers.fetchedAt }
|
|
7202
|
+
} : { cached: true, reason: SERVICE_TIERS_METADATA_UNAVAILABLE_REASON });
|
|
6989
7203
|
}
|
|
6990
7204
|
policy.reconcile();
|
|
6991
7205
|
pi.on("session_start", (_event, ctx) => {
|
|
6992
|
-
|
|
6993
|
-
|
|
6994
|
-
|
|
7206
|
+
state.registry = ctx.modelRegistry;
|
|
7207
|
+
state.activeModel = ctx.model;
|
|
7208
|
+
state.policy?.reconcile();
|
|
6995
7209
|
});
|
|
6996
7210
|
pi.on("model_select", (event, ctx) => {
|
|
6997
|
-
|
|
6998
|
-
|
|
6999
|
-
|
|
7211
|
+
state.registry = ctx.modelRegistry;
|
|
7212
|
+
state.activeModel = event.model;
|
|
7213
|
+
state.policy?.reconcile();
|
|
7000
7214
|
});
|
|
7001
7215
|
pi.on("before_provider_request", (event, ctx) => {
|
|
7002
7216
|
if (ctx.model?.provider !== PROVIDER_NAME)
|
|
7003
7217
|
return;
|
|
7004
|
-
|
|
7005
|
-
const withTier = injectServiceTier(event.payload,
|
|
7006
|
-
const
|
|
7218
|
+
state.activeModel = ctx.model;
|
|
7219
|
+
const withTier = injectServiceTier(event.payload, state.policy?.serviceTierFor(ctx.model));
|
|
7220
|
+
const withThinking = normalizeGoogleThinkingConfig(withTier, ctx.model, ctx.thinkingLevel ?? getSessionThinkingLevel(pi));
|
|
7221
|
+
const next = enforceMinimumOutputTokens(withThinking);
|
|
7007
7222
|
return next === event.payload ? undefined : next;
|
|
7008
7223
|
});
|
|
7009
7224
|
log("startup", {
|
|
@@ -7018,7 +7233,7 @@ function plexusExtension(pi) {
|
|
|
7018
7233
|
authHeader: true,
|
|
7019
7234
|
baseUrl: startupBaseUrl ?? PLACEHOLDER_BASE_URL,
|
|
7020
7235
|
models: startupModels,
|
|
7021
|
-
refreshModels: refreshPlexusModels,
|
|
7236
|
+
refreshModels: (context) => refreshPlexusModels(state, context),
|
|
7022
7237
|
oauth: createPlexusLoginProvider()
|
|
7023
7238
|
});
|
|
7024
7239
|
if (apiKeyEnvExplicit) {
|
|
@@ -7030,57 +7245,81 @@ function plexusExtension(pi) {
|
|
|
7030
7245
|
if (!composed?.auth.apiKey) {
|
|
7031
7246
|
throw new Error("Plexus apiKeyEnv override failed: provider API-key auth is unavailable");
|
|
7032
7247
|
}
|
|
7033
|
-
pi.registerProvider(withAuthoritativeApiKeyEnv(composed, apiKeyEnvName));
|
|
7248
|
+
pi.registerProvider(withAuthoritativeApiKeyEnv(composed, apiKeyEnvName, () => state.models));
|
|
7034
7249
|
authOverrideApplied = true;
|
|
7035
|
-
log("auth: applied authoritative apiKeyEnv override", {
|
|
7250
|
+
log("auth: applied authoritative apiKeyEnv override", {
|
|
7251
|
+
apiKeyEnv: apiKeyEnvName
|
|
7252
|
+
});
|
|
7036
7253
|
});
|
|
7037
7254
|
}
|
|
7038
7255
|
pi.registerCommand("plexus", {
|
|
7039
7256
|
description: "Plexus provider commands: refresh, status (setup: /login plexus)",
|
|
7040
7257
|
getArgumentCompletions: (prefix) => {
|
|
7041
7258
|
const subcommands = [
|
|
7042
|
-
{
|
|
7043
|
-
|
|
7259
|
+
{
|
|
7260
|
+
value: "refresh",
|
|
7261
|
+
label: "refresh",
|
|
7262
|
+
description: "Refresh Plexus models from the API"
|
|
7263
|
+
},
|
|
7264
|
+
{
|
|
7265
|
+
value: "status",
|
|
7266
|
+
label: "status",
|
|
7267
|
+
description: "Show Plexus configuration and catalog status"
|
|
7268
|
+
}
|
|
7044
7269
|
];
|
|
7045
7270
|
return prefix.includes(" ") ? null : subcommands.filter((command) => command.value.startsWith(prefix));
|
|
7046
7271
|
},
|
|
7047
7272
|
handler: async (args, ctx) => {
|
|
7048
7273
|
const sub = args.trim().toLowerCase();
|
|
7049
7274
|
if (sub === "refresh" || sub === "")
|
|
7050
|
-
return handleRefresh(ctx);
|
|
7275
|
+
return handleRefresh(state, ctx);
|
|
7051
7276
|
if (sub === "status")
|
|
7052
|
-
return handleStatus(ctx);
|
|
7277
|
+
return handleStatus(state, ctx);
|
|
7053
7278
|
ctx.ui.notify(`Unknown sub-command: "${args}". Use /login plexus, /plexus refresh, or /plexus status.`, "warning");
|
|
7054
7279
|
}
|
|
7055
7280
|
});
|
|
7056
7281
|
}
|
|
7057
|
-
async function refreshPlexusModels(context) {
|
|
7058
|
-
const refreshId = ++refreshSequence;
|
|
7282
|
+
async function refreshPlexusModels(state, context) {
|
|
7283
|
+
const refreshId = ++state.refreshSequence;
|
|
7059
7284
|
const baseUrl = getBaseUrl();
|
|
7060
7285
|
const modelsUrl = getModelsUrl();
|
|
7061
7286
|
const apiKey = resolveApiKey(credentialApiKey(context.credential));
|
|
7062
7287
|
const suppress = getSuppressedModels();
|
|
7063
7288
|
if (!context.allowNetwork || !apiKey || !modelsUrl || !baseUrl) {
|
|
7064
|
-
if (
|
|
7065
|
-
const filteredCurrent =
|
|
7289
|
+
if (state.models.length > 0) {
|
|
7290
|
+
const filteredCurrent = state.models.filter((m) => !isModelSuppressed({ id: m.id, name: m.name }, suppress));
|
|
7066
7291
|
await context.publish({
|
|
7067
|
-
persist: {
|
|
7292
|
+
persist: {
|
|
7293
|
+
models: filteredCurrent,
|
|
7294
|
+
checkedAt: Date.now()
|
|
7295
|
+
},
|
|
7068
7296
|
update: () => {
|
|
7069
|
-
|
|
7297
|
+
state.models = filteredCurrent;
|
|
7070
7298
|
const cachedTiers = collectStoredServiceTiers(filteredCurrent);
|
|
7071
|
-
|
|
7299
|
+
state.serviceTiers?.setCatalog(cachedTiers.complete ? "ready" : "unavailable", cachedTiers.policies, cachedTiers.complete ? {
|
|
7300
|
+
cached: true,
|
|
7301
|
+
...cachedTiers.fetchedAt === undefined ? {} : { fetchedAt: cachedTiers.fetchedAt }
|
|
7302
|
+
} : {
|
|
7303
|
+
cached: true,
|
|
7304
|
+
reason: SERVICE_TIERS_METADATA_UNAVAILABLE_REASON
|
|
7305
|
+
});
|
|
7072
7306
|
const cachedPolicies = collectStoredContextPolicies(filteredCurrent);
|
|
7073
|
-
|
|
7074
|
-
|
|
7307
|
+
state.contextPolicies?.setCatalog(cachedPolicies.length > 0 ? "ready" : "unavailable", cachedPolicies.map((entry) => entry.policy), cachedPolicies.length > 0 ? { cached: true, fetchedAt: cachedPolicies[0]?.fetchedAt } : {
|
|
7308
|
+
cached: true,
|
|
7309
|
+
reason: CONTEXT_POLICY_METADATA_UNAVAILABLE_REASON
|
|
7310
|
+
});
|
|
7311
|
+
state.policy?.reconcile();
|
|
7075
7312
|
}
|
|
7076
7313
|
});
|
|
7077
7314
|
return filteredCurrent;
|
|
7078
7315
|
}
|
|
7079
|
-
const restored = await restoreStoredModels(context);
|
|
7316
|
+
const restored = await restoreStoredModels(state, context);
|
|
7080
7317
|
if (restored)
|
|
7081
7318
|
return restored;
|
|
7082
|
-
if (refreshId === refreshSequence &&
|
|
7083
|
-
|
|
7319
|
+
if (refreshId === state.refreshSequence && state.serviceTiers?.getSnapshot().status === "loading") {
|
|
7320
|
+
state.serviceTiers.setCatalog("unavailable", [], {
|
|
7321
|
+
reason: "Plexus model metadata is not configured."
|
|
7322
|
+
});
|
|
7084
7323
|
}
|
|
7085
7324
|
throw new Error(!modelsUrl || !baseUrl ? "Plexus base URL not configured. Run /login plexus first." : "No Plexus API key configured. Run /login plexus first.");
|
|
7086
7325
|
}
|
|
@@ -7099,18 +7338,26 @@ async function refreshPlexusModels(context) {
|
|
|
7099
7338
|
const policy = contextPolicyFromApiModel(model);
|
|
7100
7339
|
if (policy)
|
|
7101
7340
|
piModel.plexusContextPolicy = { policy, fetchedAt };
|
|
7102
|
-
piModel.plexusServiceTiers = {
|
|
7341
|
+
piModel.plexusServiceTiers = {
|
|
7342
|
+
policy: serviceTierPolicyFromApiModel(model),
|
|
7343
|
+
fetchedAt
|
|
7344
|
+
};
|
|
7103
7345
|
}
|
|
7104
7346
|
const committedPolicies = collectStoredContextPolicies(piModels);
|
|
7105
7347
|
const committedServiceTiers = collectStoredServiceTiers(piModels).policies;
|
|
7106
7348
|
const published = await context.publish({
|
|
7107
|
-
persist: {
|
|
7349
|
+
persist: {
|
|
7350
|
+
models: piModels,
|
|
7351
|
+
checkedAt: Date.now()
|
|
7352
|
+
},
|
|
7108
7353
|
update: () => {
|
|
7109
|
-
|
|
7110
|
-
catalogSource = "live refresh";
|
|
7111
|
-
|
|
7112
|
-
|
|
7113
|
-
|
|
7354
|
+
state.models = piModels;
|
|
7355
|
+
state.catalogSource = "live refresh";
|
|
7356
|
+
state.serviceTiers?.setCatalog("ready", committedServiceTiers, {
|
|
7357
|
+
fetchedAt
|
|
7358
|
+
});
|
|
7359
|
+
state.contextPolicies?.setCatalog(committedPolicies.length > 0 ? "ready" : "unavailable", committedPolicies.map((entry) => entry.policy), committedPolicies.length > 0 ? { fetchedAt } : { fetchedAt, reason: CONTEXT_POLICY_METADATA_UNAVAILABLE_REASON });
|
|
7360
|
+
state.policy?.reconcile();
|
|
7114
7361
|
}
|
|
7115
7362
|
});
|
|
7116
7363
|
if (!published) {
|
|
@@ -7119,17 +7366,21 @@ async function refreshPlexusModels(context) {
|
|
|
7119
7366
|
log("refreshModels: fetched", { count: piModels.length });
|
|
7120
7367
|
return piModels;
|
|
7121
7368
|
} catch (error) {
|
|
7122
|
-
if (refreshId === refreshSequence &&
|
|
7123
|
-
|
|
7369
|
+
if (refreshId === state.refreshSequence && state.contextPolicies?.getSnapshot().status === "loading") {
|
|
7370
|
+
state.contextPolicies.setCatalog("unavailable", [], {
|
|
7371
|
+
reason: "Plexus model metadata could not be loaded."
|
|
7372
|
+
});
|
|
7124
7373
|
}
|
|
7125
|
-
if (refreshId === refreshSequence &&
|
|
7126
|
-
|
|
7374
|
+
if (refreshId === state.refreshSequence && state.serviceTiers?.getSnapshot().status === "loading") {
|
|
7375
|
+
state.serviceTiers.setCatalog("unavailable", [], {
|
|
7376
|
+
reason: "Plexus model metadata could not be loaded."
|
|
7377
|
+
});
|
|
7127
7378
|
}
|
|
7128
7379
|
log("refreshModels: fetch failed", { error: String(error) });
|
|
7129
7380
|
throw error;
|
|
7130
7381
|
}
|
|
7131
7382
|
}
|
|
7132
|
-
async function restoreStoredModels(context) {
|
|
7383
|
+
async function restoreStoredModels(state, context) {
|
|
7133
7384
|
const stored = context.stored;
|
|
7134
7385
|
if (!stored || stored.models.length === 0)
|
|
7135
7386
|
return;
|
|
@@ -7137,13 +7388,19 @@ async function restoreStoredModels(context) {
|
|
|
7137
7388
|
const models = stored.models.filter((m) => !isModelSuppressed({ id: m.id, name: m.name }, suppress));
|
|
7138
7389
|
await context.publish({
|
|
7139
7390
|
update: () => {
|
|
7140
|
-
|
|
7141
|
-
catalogSource = "host store";
|
|
7391
|
+
state.models = models;
|
|
7392
|
+
state.catalogSource = "host store";
|
|
7142
7393
|
const cachedTiers = collectStoredServiceTiers(models);
|
|
7143
|
-
|
|
7394
|
+
state.serviceTiers?.setCatalog(cachedTiers.complete ? "ready" : "unavailable", cachedTiers.policies, cachedTiers.complete ? {
|
|
7395
|
+
cached: true,
|
|
7396
|
+
...cachedTiers.fetchedAt === undefined ? {} : { fetchedAt: cachedTiers.fetchedAt }
|
|
7397
|
+
} : { cached: true, reason: SERVICE_TIERS_METADATA_UNAVAILABLE_REASON });
|
|
7144
7398
|
const cachedPolicies = collectStoredContextPolicies(models);
|
|
7145
|
-
|
|
7146
|
-
|
|
7399
|
+
state.contextPolicies?.setCatalog(cachedPolicies.length > 0 ? "ready" : "unavailable", cachedPolicies.map((entry) => entry.policy), cachedPolicies.length > 0 ? { cached: true, fetchedAt: cachedPolicies[0]?.fetchedAt } : {
|
|
7400
|
+
cached: true,
|
|
7401
|
+
reason: CONTEXT_POLICY_METADATA_UNAVAILABLE_REASON
|
|
7402
|
+
});
|
|
7403
|
+
state.policy?.reconcile();
|
|
7147
7404
|
}
|
|
7148
7405
|
});
|
|
7149
7406
|
log("refreshModels: restored from store", { count: models.length });
|
|
@@ -7152,7 +7409,7 @@ async function restoreStoredModels(context) {
|
|
|
7152
7409
|
function contextPolicyFromApiModel(model) {
|
|
7153
7410
|
const maxContextTokens = model.context_length;
|
|
7154
7411
|
const pricingThresholdInputTokens = model.pricing?.tiers?.[0]?.input_tokens_above;
|
|
7155
|
-
if (!Number.isSafeInteger(maxContextTokens) || maxContextTokens <= 0 || !Number.isSafeInteger(pricingThresholdInputTokens) || pricingThresholdInputTokens <= 0 || pricingThresholdInputTokens > maxContextTokens)
|
|
7412
|
+
if (typeof maxContextTokens !== "number" || !Number.isSafeInteger(maxContextTokens) || maxContextTokens <= 0 || typeof pricingThresholdInputTokens !== "number" || !Number.isSafeInteger(pricingThresholdInputTokens) || pricingThresholdInputTokens <= 0 || pricingThresholdInputTokens > maxContextTokens)
|
|
7156
7413
|
return;
|
|
7157
7414
|
return {
|
|
7158
7415
|
provider: PROVIDER_NAME,
|
|
@@ -7172,7 +7429,11 @@ function serviceTierPolicyFromApiModel(model) {
|
|
|
7172
7429
|
const serviceTiers = model.service_tiers;
|
|
7173
7430
|
if (!Array.isArray(serviceTiers) || serviceTiers.length === 0)
|
|
7174
7431
|
return;
|
|
7175
|
-
const candidate = {
|
|
7432
|
+
const candidate = {
|
|
7433
|
+
provider: PROVIDER_NAME,
|
|
7434
|
+
modelId: model.id,
|
|
7435
|
+
serviceTiers
|
|
7436
|
+
};
|
|
7176
7437
|
const parsed = ServiceTierPolicySchema.safeParse(candidate);
|
|
7177
7438
|
return parsed.success ? parsed.data : undefined;
|
|
7178
7439
|
}
|
|
@@ -7231,7 +7492,7 @@ function createPlexusLoginProvider() {
|
|
|
7231
7492
|
}
|
|
7232
7493
|
};
|
|
7233
7494
|
}
|
|
7234
|
-
async function handleRefresh(ctx) {
|
|
7495
|
+
async function handleRefresh(state, ctx) {
|
|
7235
7496
|
let apiKey;
|
|
7236
7497
|
try {
|
|
7237
7498
|
apiKey = await ctx.modelRegistry.getApiKeyForProvider(PROVIDER_NAME);
|
|
@@ -7244,7 +7505,10 @@ async function handleRefresh(ctx) {
|
|
|
7244
7505
|
return;
|
|
7245
7506
|
}
|
|
7246
7507
|
ctx.ui.notify("Refreshing Plexus models\u2026", "info");
|
|
7247
|
-
const result = await ctx.modelRegistry.refresh({
|
|
7508
|
+
const result = await ctx.modelRegistry.refresh({
|
|
7509
|
+
providers: [PROVIDER_NAME],
|
|
7510
|
+
force: true
|
|
7511
|
+
});
|
|
7248
7512
|
if (result.aborted) {
|
|
7249
7513
|
ctx.ui.notify("Plexus model refresh was cancelled.", "warning");
|
|
7250
7514
|
return;
|
|
@@ -7254,9 +7518,9 @@ async function handleRefresh(ctx) {
|
|
|
7254
7518
|
ctx.ui.notify(`Plexus model refresh failed: ${refreshError.message}`, "error");
|
|
7255
7519
|
return;
|
|
7256
7520
|
}
|
|
7257
|
-
ctx.ui.notify(
|
|
7521
|
+
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
7522
|
}
|
|
7259
|
-
async function handleStatus(ctx) {
|
|
7523
|
+
async function handleStatus(state, ctx) {
|
|
7260
7524
|
const baseUrl = getBaseUrlResolution();
|
|
7261
7525
|
const apiKeyEnvName = getApiKeyEnvName();
|
|
7262
7526
|
const apiKey = await ctx.modelRegistry.getApiKeyForProvider(PROVIDER_NAME).catch(() => {
|
|
@@ -7266,7 +7530,7 @@ async function handleStatus(ctx) {
|
|
|
7266
7530
|
ctx.ui.notify([
|
|
7267
7531
|
`Plexus base URL: ${baseUrl.baseUrl ?? "not configured"} (${baseUrl.source})`,
|
|
7268
7532
|
`API key: ${apiKey ? explicitApiKey !== undefined ? `${apiKeyEnvName} (apiKeyEnv)` : getEnvApiKey() ? `host credential or ${apiKeyEnvName} fallback` : "host credential" : "not configured"}`,
|
|
7269
|
-
`Catalog: ${
|
|
7533
|
+
`Catalog: ${state.models.length} models (${state.catalogSource})`,
|
|
7270
7534
|
"Default model: managed by Pi. Use /model and save the selection there."
|
|
7271
7535
|
].join(`
|
|
7272
7536
|
`), "info");
|
|
@@ -7276,6 +7540,8 @@ export {
|
|
|
7276
7540
|
createPolicyHost,
|
|
7277
7541
|
plexusExtension as default,
|
|
7278
7542
|
enforceMinimumOutputTokens,
|
|
7543
|
+
normalizeGoogleThinkingConfig,
|
|
7279
7544
|
serviceTierPolicyFromApiModel,
|
|
7545
|
+
usesGoogleThinkingLevel,
|
|
7280
7546
|
withAuthoritativeApiKeyEnv
|
|
7281
7547
|
};
|