@mcowger/pi-plexus 1.14.0 → 1.14.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +46 -47
- package/dist/extension.js +1017 -1069
- package/package.json +2 -7
- package/context-policy.md +0 -64
- package/models-control.md +0 -51
- package/policy-control.md +0 -97
- package/service-tiers.md +0 -57
- package/short-names.md +0 -59
package/dist/extension.js
CHANGED
|
@@ -1,4 +1,29 @@
|
|
|
1
1
|
// @bun
|
|
2
|
+
// ../plexus-models/src/auth.ts
|
|
3
|
+
var DEFAULT_API_KEY_ENV = "PLEXUS_API_KEY";
|
|
4
|
+
var ENV_VAR_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
5
|
+
function resolveApiKeyEnvSetting(raw) {
|
|
6
|
+
if (raw === undefined || raw === null)
|
|
7
|
+
return { name: DEFAULT_API_KEY_ENV, explicit: false };
|
|
8
|
+
const name = typeof raw === "string" ? raw.trim() : "";
|
|
9
|
+
if (!ENV_VAR_NAME_RE.test(name)) {
|
|
10
|
+
throw new Error("Invalid apiKeyEnv: expected an environment variable name");
|
|
11
|
+
}
|
|
12
|
+
return { name, explicit: true };
|
|
13
|
+
}
|
|
14
|
+
function resolveApiKeyEnvValue(setting, raw) {
|
|
15
|
+
const value = raw?.trim();
|
|
16
|
+
if (!value && setting.explicit) {
|
|
17
|
+
throw new Error(`apiKeyEnv environment variable "${setting.name}" is missing or empty`);
|
|
18
|
+
}
|
|
19
|
+
return value || undefined;
|
|
20
|
+
}
|
|
21
|
+
function resolvePlexusApiKey(setting, envValue, storedKey) {
|
|
22
|
+
const envKey = resolveApiKeyEnvValue(setting, envValue);
|
|
23
|
+
if (envKey !== undefined)
|
|
24
|
+
return envKey;
|
|
25
|
+
return storedKey || undefined;
|
|
26
|
+
}
|
|
2
27
|
// ../plexus-models/src/convert.ts
|
|
3
28
|
var REASONING_PARAMS = new Set([
|
|
4
29
|
"reasoning",
|
|
@@ -396,8 +421,7 @@ var getConfigDir = () => join2(getAgentDir2(), "extensions", "plexus");
|
|
|
396
421
|
var getConfigPath = () => join2(getConfigDir(), "config.json");
|
|
397
422
|
var ENV_BASE_URL = "PLEXUS_BASE_URL";
|
|
398
423
|
var ENV_API_URL = "PLEXUS_API_URL";
|
|
399
|
-
var
|
|
400
|
-
var ENV_VAR_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
424
|
+
var ENV_VAR_NAME_RE2 = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
401
425
|
var ENV_VAR_NAME_PREFIX_RE = /^[A-Za-z_][A-Za-z0-9_]*/;
|
|
402
426
|
var normalizeRoot = (raw) => raw.trim().replace(/\/+$/, "");
|
|
403
427
|
function resolveConfigTemplate(value) {
|
|
@@ -424,7 +448,7 @@ function resolveConfigTemplate(value) {
|
|
|
424
448
|
continue;
|
|
425
449
|
}
|
|
426
450
|
const name = value.slice(dollarIndex + 2, endIndex);
|
|
427
|
-
if (!
|
|
451
|
+
if (!ENV_VAR_NAME_RE2.test(name)) {
|
|
428
452
|
result += value.slice(dollarIndex, endIndex + 1);
|
|
429
453
|
index = endIndex + 1;
|
|
430
454
|
continue;
|
|
@@ -499,49 +523,15 @@ function getBaseUrlResolution() {
|
|
|
499
523
|
const saved = resolveStringOption(config.baseUrl);
|
|
500
524
|
return { baseUrl: saved ?? null, source: saved ? "saved" : "none" };
|
|
501
525
|
}
|
|
502
|
-
function
|
|
503
|
-
|
|
504
|
-
if (raw === undefined || raw === null)
|
|
505
|
-
return { name: ENV_API_KEY, explicit: false };
|
|
506
|
-
const name = typeof raw === "string" ? raw.trim() : "";
|
|
507
|
-
if (!ENV_VAR_NAME_RE.test(name)) {
|
|
508
|
-
throw new Error("Invalid apiKeyEnv: expected an environment variable name");
|
|
509
|
-
}
|
|
510
|
-
return { name, explicit: true };
|
|
511
|
-
}
|
|
512
|
-
function getApiKeyEnvName() {
|
|
513
|
-
return resolveApiKeyEnvSetting().name;
|
|
514
|
-
}
|
|
515
|
-
function isApiKeyEnvExplicit() {
|
|
516
|
-
return resolveApiKeyEnvSetting().explicit;
|
|
517
|
-
}
|
|
518
|
-
function requireApiKeyEnvValue(name, raw) {
|
|
519
|
-
const value = raw?.trim();
|
|
520
|
-
if (!value) {
|
|
521
|
-
throw new Error(`apiKeyEnv environment variable "${name}" is missing or empty`);
|
|
522
|
-
}
|
|
523
|
-
return value;
|
|
524
|
-
}
|
|
525
|
-
async function resolveExplicitApiKeyFromEnv(readEnv) {
|
|
526
|
-
const { name, explicit } = resolveApiKeyEnvSetting();
|
|
527
|
-
if (!explicit)
|
|
528
|
-
return;
|
|
529
|
-
return requireApiKeyEnvValue(name, await readEnv(name));
|
|
526
|
+
function resolveApiKeyEnvSetting2() {
|
|
527
|
+
return resolveApiKeyEnvSetting(getConfigSync().apiKeyEnv);
|
|
530
528
|
}
|
|
531
|
-
function
|
|
532
|
-
|
|
533
|
-
if (!explicit)
|
|
534
|
-
return;
|
|
535
|
-
return requireApiKeyEnvValue(name, process.env[name]);
|
|
529
|
+
function getApiKeyEnvSetting() {
|
|
530
|
+
return resolveApiKeyEnvSetting2();
|
|
536
531
|
}
|
|
537
532
|
function resolveApiKey(storedKey) {
|
|
538
|
-
const
|
|
539
|
-
|
|
540
|
-
return explicit;
|
|
541
|
-
return storedKey || getEnvApiKey() || undefined;
|
|
542
|
-
}
|
|
543
|
-
function getEnvApiKey() {
|
|
544
|
-
return resolveStringOption(process.env[ENV_API_KEY]) ?? null;
|
|
533
|
+
const setting = resolveApiKeyEnvSetting2();
|
|
534
|
+
return resolvePlexusApiKey(setting, process.env[setting.name], storedKey);
|
|
545
535
|
}
|
|
546
536
|
function getModelsUrl() {
|
|
547
537
|
const { baseUrl } = getBaseUrlResolution();
|
|
@@ -558,8 +548,148 @@ function getSuppressedModels() {
|
|
|
558
548
|
return [...envSuppressed, ...configSuppressed];
|
|
559
549
|
}
|
|
560
550
|
|
|
561
|
-
// src/
|
|
562
|
-
import {
|
|
551
|
+
// src/log.ts
|
|
552
|
+
import { appendFile, mkdir as mkdir2 } from "fs/promises";
|
|
553
|
+
import { join as join3 } from "path";
|
|
554
|
+
import { getAgentDir as getAgentDir3 } from "@earendil-works/pi-coding-agent";
|
|
555
|
+
var getCacheDir = () => join3(getAgentDir3(), "extensions", "plexus");
|
|
556
|
+
var getLogPath = () => join3(getCacheDir(), "plexus.log");
|
|
557
|
+
var dirEnsured = false;
|
|
558
|
+
function log(message, data) {
|
|
559
|
+
writeLogLine(message, data);
|
|
560
|
+
}
|
|
561
|
+
async function writeLogLine(message, data) {
|
|
562
|
+
try {
|
|
563
|
+
if (!dirEnsured) {
|
|
564
|
+
await mkdir2(getCacheDir(), { recursive: true });
|
|
565
|
+
dirEnsured = true;
|
|
566
|
+
}
|
|
567
|
+
const ts = new Date().toISOString();
|
|
568
|
+
const line = data !== undefined ? `${ts} ${message} ${JSON.stringify(data)}
|
|
569
|
+
` : `${ts} ${message}
|
|
570
|
+
`;
|
|
571
|
+
await appendFile(getLogPath(), line, "utf8");
|
|
572
|
+
} catch {}
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
// src/gemini-malformed-retry.ts
|
|
576
|
+
var MALFORMED_LEAK_PATTERN = /(?:print\()?call:\s*default_api[.:]|default_api\.\w+\s*\(/;
|
|
577
|
+
var MALFORMED_DIAGNOSTIC_PATTERN = /\bmalformed[\s_-]?function[\s_-]?call\b/i;
|
|
578
|
+
var TRUNCATED_JSON_PATTERN = /\bUnexpected end of JSON input\b/i;
|
|
579
|
+
var PROVIDER_CONNECTION_CLOSED_PATTERN = /\bprovider connection closed\b/i;
|
|
580
|
+
var NORMALIZED_PREFIX = "MALFORMED_FUNCTION_CALL:";
|
|
581
|
+
var TRUNCATED_JSON_PREFIX = "TRUNCATED_JSON_RESPONSE:";
|
|
582
|
+
var PROVIDER_CONNECTION_CLOSED_PREFIX = "PROVIDER_CONNECTION_CLOSED:";
|
|
583
|
+
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.`;
|
|
584
|
+
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.`;
|
|
585
|
+
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.`;
|
|
586
|
+
function hasLeakedFunctionCall(content) {
|
|
587
|
+
if (!Array.isArray(content))
|
|
588
|
+
return false;
|
|
589
|
+
for (const block of content) {
|
|
590
|
+
if (block?.type === "text" && typeof block.text === "string" && MALFORMED_LEAK_PATTERN.test(block.text)) {
|
|
591
|
+
return true;
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
return false;
|
|
595
|
+
}
|
|
596
|
+
function hasToolCall(content) {
|
|
597
|
+
return Array.isArray(content) && content.some((block) => block?.type === "toolCall");
|
|
598
|
+
}
|
|
599
|
+
function normalizeMalformedFunctionCall(message, providerName) {
|
|
600
|
+
if (message?.role !== "assistant" || message.provider !== providerName || message.stopReason !== "error") {
|
|
601
|
+
return;
|
|
602
|
+
}
|
|
603
|
+
if (typeof message.errorMessage === "string" && (message.errorMessage.startsWith(NORMALIZED_PREFIX) || message.errorMessage.startsWith(TRUNCATED_JSON_PREFIX) || message.errorMessage.startsWith(PROVIDER_CONNECTION_CLOSED_PREFIX))) {
|
|
604
|
+
return;
|
|
605
|
+
}
|
|
606
|
+
if (hasToolCall(message.content))
|
|
607
|
+
return;
|
|
608
|
+
if (typeof message.errorMessage === "string" && TRUNCATED_JSON_PATTERN.test(message.errorMessage)) {
|
|
609
|
+
log("retryable-error: retagged truncated JSON response for retry", {
|
|
610
|
+
model: message.model
|
|
611
|
+
});
|
|
612
|
+
return { message: { ...message, errorMessage: TRUNCATED_JSON_MESSAGE } };
|
|
613
|
+
}
|
|
614
|
+
if (typeof message.errorMessage === "string" && PROVIDER_CONNECTION_CLOSED_PATTERN.test(message.errorMessage)) {
|
|
615
|
+
log("retryable-error: retagged closed provider connection for retry", {
|
|
616
|
+
model: message.model
|
|
617
|
+
});
|
|
618
|
+
return {
|
|
619
|
+
message: { ...message, errorMessage: PROVIDER_CONNECTION_CLOSED_MESSAGE }
|
|
620
|
+
};
|
|
621
|
+
}
|
|
622
|
+
const via = hasLeakedFunctionCall(message.content) ? "leak" : typeof message.errorMessage === "string" && MALFORMED_DIAGNOSTIC_PATTERN.test(message.errorMessage) ? "diagnostic" : undefined;
|
|
623
|
+
if (!via)
|
|
624
|
+
return;
|
|
625
|
+
log("gemini-malformed-retry: retagged MALFORMED_FUNCTION_CALL for retry", {
|
|
626
|
+
model: message.model,
|
|
627
|
+
via
|
|
628
|
+
});
|
|
629
|
+
return { message: { ...message, errorMessage: NORMALIZED_MESSAGE } };
|
|
630
|
+
}
|
|
631
|
+
|
|
632
|
+
// src/mapper.ts
|
|
633
|
+
import {
|
|
634
|
+
getModel
|
|
635
|
+
} from "@earendil-works/pi-ai/compat";
|
|
636
|
+
var MINIMUM_OUTPUT_TOKENS = 8192;
|
|
637
|
+
function descriptorToPiModel(descriptor) {
|
|
638
|
+
let builtinModel;
|
|
639
|
+
if (descriptor.piProvider && descriptor.piModel) {
|
|
640
|
+
try {
|
|
641
|
+
builtinModel = getModel(descriptor.piProvider, descriptor.piModel);
|
|
642
|
+
} catch {
|
|
643
|
+
builtinModel = undefined;
|
|
644
|
+
}
|
|
645
|
+
}
|
|
646
|
+
const cost = {
|
|
647
|
+
input: descriptor.cost.input * 1e6,
|
|
648
|
+
output: descriptor.cost.output * 1e6,
|
|
649
|
+
cacheRead: descriptor.cost.cacheRead * 1e6,
|
|
650
|
+
cacheWrite: descriptor.cost.cacheWrite * 1e6,
|
|
651
|
+
...descriptor.cost.tiers ? {
|
|
652
|
+
tiers: descriptor.cost.tiers.map((tier) => ({
|
|
653
|
+
inputTokensAbove: tier.inputTokensAbove,
|
|
654
|
+
input: tier.input * 1e6,
|
|
655
|
+
output: tier.output * 1e6,
|
|
656
|
+
cacheRead: tier.cacheRead * 1e6,
|
|
657
|
+
cacheWrite: tier.cacheWrite * 1e6
|
|
658
|
+
}))
|
|
659
|
+
} : {}
|
|
660
|
+
};
|
|
661
|
+
let compat;
|
|
662
|
+
if (descriptor.preferredApi === "openai-completions") {
|
|
663
|
+
const heuristic = detectOpenAICompletionsCompat(descriptor.piProvider ?? descriptor.provider, descriptor.baseUrl);
|
|
664
|
+
const builtinCompat = builtinModel?.compat;
|
|
665
|
+
const merged = {
|
|
666
|
+
...heuristic,
|
|
667
|
+
...builtinCompat ?? {},
|
|
668
|
+
...descriptor.piOptions ?? {}
|
|
669
|
+
};
|
|
670
|
+
compat = merged;
|
|
671
|
+
} else if (descriptor.piOptions) {
|
|
672
|
+
compat = descriptor.piOptions;
|
|
673
|
+
} else if (builtinModel?.compat) {
|
|
674
|
+
compat = builtinModel.compat;
|
|
675
|
+
}
|
|
676
|
+
return {
|
|
677
|
+
id: descriptor.id,
|
|
678
|
+
name: descriptor.name,
|
|
679
|
+
...descriptor.shortName !== undefined ? { plexusShortName: descriptor.shortName } : {},
|
|
680
|
+
api: descriptor.preferredApi,
|
|
681
|
+
provider: descriptor.provider,
|
|
682
|
+
baseUrl: descriptor.baseUrl,
|
|
683
|
+
reasoning: descriptor.reasoning,
|
|
684
|
+
input: descriptor.input,
|
|
685
|
+
cost,
|
|
686
|
+
contextWindow: descriptor.contextWindow,
|
|
687
|
+
maxTokens: Math.max(descriptor.maxTokens, MINIMUM_OUTPUT_TOKENS),
|
|
688
|
+
...builtinModel?.thinkingLevelMap !== undefined ? { thinkingLevelMap: builtinModel.thinkingLevelMap } : {},
|
|
689
|
+
...builtinModel?.headers !== undefined ? { headers: builtinModel.headers } : {},
|
|
690
|
+
...compat !== undefined ? { compat } : {}
|
|
691
|
+
};
|
|
692
|
+
}
|
|
563
693
|
|
|
564
694
|
// ../../node_modules/.bun/zod@4.6.5/node_modules/zod/v4/core/util.js
|
|
565
695
|
function getEnumValues(entries) {
|
|
@@ -5769,6 +5899,14 @@ function object(shape, params) {
|
|
|
5769
5899
|
};
|
|
5770
5900
|
return new ZodObject(def);
|
|
5771
5901
|
}
|
|
5902
|
+
function strictObject(shape, params) {
|
|
5903
|
+
return new ZodObject({
|
|
5904
|
+
type: "object",
|
|
5905
|
+
shape,
|
|
5906
|
+
catchall: never(),
|
|
5907
|
+
...normalizeParams(params)
|
|
5908
|
+
});
|
|
5909
|
+
}
|
|
5772
5910
|
var ZodUnion = /* @__PURE__ */ $constructor("ZodUnion", (inst, def) => {
|
|
5773
5911
|
$ZodUnion.init(inst, def);
|
|
5774
5912
|
ZodType.init(inst, def);
|
|
@@ -6032,435 +6170,797 @@ function refine(fn, _params = {}) {
|
|
|
6032
6170
|
function superRefine(fn, params) {
|
|
6033
6171
|
return _superRefine(fn, params);
|
|
6034
6172
|
}
|
|
6035
|
-
// src/
|
|
6036
|
-
var
|
|
6037
|
-
var
|
|
6038
|
-
var
|
|
6039
|
-
|
|
6040
|
-
|
|
6041
|
-
|
|
6042
|
-
|
|
6043
|
-
|
|
6044
|
-
|
|
6045
|
-
var
|
|
6046
|
-
var
|
|
6047
|
-
|
|
6048
|
-
|
|
6049
|
-
|
|
6050
|
-
|
|
6051
|
-
|
|
6052
|
-
|
|
6053
|
-
|
|
6054
|
-
|
|
6055
|
-
|
|
6056
|
-
|
|
6057
|
-
|
|
6058
|
-
|
|
6059
|
-
|
|
6060
|
-
|
|
6061
|
-
|
|
6062
|
-
|
|
6063
|
-
|
|
6064
|
-
|
|
6065
|
-
|
|
6173
|
+
// src/paseo-control/protocol.ts
|
|
6174
|
+
var PROTOCOL_VERSION = 1;
|
|
6175
|
+
var NOTIFY_PREFIX = "plexuspi:v1:";
|
|
6176
|
+
var STATE_NOTIFY_PREFIX = "plexuspi:state:v1:";
|
|
6177
|
+
var CHILD_NOTIFY_PREFIX = "plexuspi:child:v1:";
|
|
6178
|
+
var COMMAND_NAME = "plexuspi-control";
|
|
6179
|
+
var CUSTOM_ENTRY_TYPE = "plexuspi-controls";
|
|
6180
|
+
var REWIND_ENTRY_TYPE = "plexuspi-rewind";
|
|
6181
|
+
var SUBAGENT_BRIDGE_CHANNEL = "plexuspi:subagent:v1";
|
|
6182
|
+
var SUBAGENT_BRIDGE_VERSION = 1;
|
|
6183
|
+
var ROOT_SIGNAL_CHANNEL = "plexuspi:root:v1";
|
|
6184
|
+
var ROOT_SIGNAL_VERSION = 1;
|
|
6185
|
+
var SESSION_KEY_ENV = "PLEXUSPI_SESSION_KEY";
|
|
6186
|
+
var TierSchema = string2().min(1).max(100);
|
|
6187
|
+
var NO_TIER = "default";
|
|
6188
|
+
var SettingsSchema = strictObject({
|
|
6189
|
+
tier: TierSchema,
|
|
6190
|
+
longContext: boolean2()
|
|
6191
|
+
});
|
|
6192
|
+
var OperationSchema = _enum([
|
|
6193
|
+
"hello",
|
|
6194
|
+
"get-state",
|
|
6195
|
+
"configure",
|
|
6196
|
+
"rewind",
|
|
6197
|
+
"reload"
|
|
6198
|
+
]);
|
|
6199
|
+
var ConfigureDataSchema = strictObject({
|
|
6200
|
+
tier: TierSchema.optional(),
|
|
6201
|
+
longContext: boolean2().optional()
|
|
6202
|
+
});
|
|
6203
|
+
var RewindDataSchema = strictObject({
|
|
6204
|
+
targetEntryId: string2().min(1)
|
|
6205
|
+
});
|
|
6206
|
+
var RewindResultSchema = strictObject({
|
|
6207
|
+
cancelled: boolean2(),
|
|
6208
|
+
targetEntryId: string2().min(1),
|
|
6209
|
+
leafId: string2().optional(),
|
|
6210
|
+
settings: SettingsSchema,
|
|
6211
|
+
activeChildren: number2().int().nonnegative()
|
|
6212
|
+
});
|
|
6213
|
+
var RewindEntrySchema = strictObject({
|
|
6214
|
+
version: literal(PROTOCOL_VERSION),
|
|
6215
|
+
targetEntryId: string2().min(1),
|
|
6216
|
+
leafId: string2().nullable().optional(),
|
|
6217
|
+
timestamp: number2().int().nonnegative()
|
|
6218
|
+
});
|
|
6219
|
+
var SubagentBridgeRecordSchema = strictObject({
|
|
6220
|
+
version: literal(SUBAGENT_BRIDGE_VERSION),
|
|
6221
|
+
runId: string2().min(1),
|
|
6222
|
+
sequence: number2().int().positive(),
|
|
6223
|
+
type: _enum(["created", "activity", "terminal"]),
|
|
6224
|
+
parentRunId: string2().optional(),
|
|
6225
|
+
parentSessionId: string2().optional(),
|
|
6226
|
+
childSessionId: string2().optional(),
|
|
6227
|
+
toolCallId: string2().optional(),
|
|
6228
|
+
title: string2().optional(),
|
|
6229
|
+
timestamp: number2().optional(),
|
|
6230
|
+
transcriptPath: string2().optional(),
|
|
6231
|
+
cwd: string2().optional(),
|
|
6232
|
+
record: unknown().optional(),
|
|
6233
|
+
outcome: _enum(["completed", "steered", "canceled", "failed"]).optional(),
|
|
6234
|
+
result: unknown().optional(),
|
|
6235
|
+
reason: string2().optional(),
|
|
6236
|
+
omitted: boolean2().optional(),
|
|
6237
|
+
omittedBytes: number2().int().nonnegative().optional()
|
|
6238
|
+
});
|
|
6239
|
+
var ChildForwardSchema = strictObject({
|
|
6240
|
+
version: literal(SUBAGENT_BRIDGE_VERSION),
|
|
6241
|
+
sessionKey: string2(),
|
|
6242
|
+
record: SubagentBridgeRecordSchema
|
|
6243
|
+
});
|
|
6244
|
+
var PlexuspiRequestSchema = object({
|
|
6245
|
+
version: literal(PROTOCOL_VERSION),
|
|
6246
|
+
sessionKey: string2().min(1),
|
|
6247
|
+
requestId: string2().min(1),
|
|
6248
|
+
operation: OperationSchema,
|
|
6249
|
+
data: unknown().optional()
|
|
6250
|
+
});
|
|
6251
|
+
var ConflictSchema = strictObject({
|
|
6252
|
+
owner: string2().min(1),
|
|
6253
|
+
command: string2().min(1),
|
|
6254
|
+
resolution: string2().min(1)
|
|
6255
|
+
});
|
|
6256
|
+
var PlexuspiStateSchema = strictObject({
|
|
6257
|
+
capabilities: array(string2()),
|
|
6258
|
+
settings: SettingsSchema,
|
|
6259
|
+
contextWindow: number2().int().nonnegative().optional(),
|
|
6260
|
+
activeChildren: number2().int().nonnegative().optional(),
|
|
6261
|
+
sessionId: string2().optional(),
|
|
6262
|
+
origin: literal("root"),
|
|
6263
|
+
tiers: array(TierSchema),
|
|
6264
|
+
longContextTarget: number2().int().nonnegative().optional(),
|
|
6265
|
+
longContextAvailable: boolean2().optional(),
|
|
6266
|
+
shortContextBudgetTokens: number2().int().positive().optional(),
|
|
6267
|
+
pricingThresholdInputTokens: number2().int().positive().optional(),
|
|
6268
|
+
contextPolicyError: string2().optional(),
|
|
6269
|
+
modelBaselineContextWindow: number2().int().nonnegative().optional(),
|
|
6270
|
+
tierApplicable: boolean2(),
|
|
6271
|
+
conflicts: array(ConflictSchema),
|
|
6272
|
+
limitations: array(string2())
|
|
6273
|
+
});
|
|
6274
|
+
var PlexuspiReplySchema = strictObject({
|
|
6275
|
+
version: literal(PROTOCOL_VERSION),
|
|
6276
|
+
sessionKey: string2(),
|
|
6277
|
+
requestId: string2(),
|
|
6278
|
+
operation: OperationSchema,
|
|
6279
|
+
ok: boolean2(),
|
|
6280
|
+
data: unknown().optional(),
|
|
6281
|
+
error: string2().optional()
|
|
6282
|
+
});
|
|
6283
|
+
var ControlEntrySchema = strictObject({
|
|
6284
|
+
version: literal(PROTOCOL_VERSION),
|
|
6285
|
+
tier: TierSchema,
|
|
6286
|
+
longContext: boolean2(),
|
|
6287
|
+
contextWindow: number2().int().nonnegative().optional(),
|
|
6288
|
+
timestamp: number2().int().nonnegative()
|
|
6289
|
+
});
|
|
6290
|
+
function formatIssues(error) {
|
|
6291
|
+
return error.issues.map((issue) => `${issue.path.length > 0 ? `${issue.path.join(".")}: ` : ""}${issue.message}`).join("; ");
|
|
6292
|
+
}
|
|
6293
|
+
function decodeBase64Url(value) {
|
|
6294
|
+
return Buffer.from(value, "base64url").toString("utf8");
|
|
6295
|
+
}
|
|
6296
|
+
function parseRequestArg(args) {
|
|
6297
|
+
const fail = (error) => ({
|
|
6298
|
+
ok: false,
|
|
6299
|
+
error,
|
|
6300
|
+
sessionKey: "",
|
|
6301
|
+
requestId: "",
|
|
6302
|
+
operation: "hello"
|
|
6303
|
+
});
|
|
6304
|
+
const trimmed = args.trim();
|
|
6305
|
+
if (!trimmed)
|
|
6306
|
+
return fail("missing base64url-encoded request");
|
|
6307
|
+
let json;
|
|
6308
|
+
try {
|
|
6309
|
+
json = decodeBase64Url(trimmed);
|
|
6310
|
+
} catch {
|
|
6311
|
+
return fail("invalid base64url request");
|
|
6066
6312
|
}
|
|
6067
|
-
if (
|
|
6068
|
-
|
|
6069
|
-
|
|
6070
|
-
|
|
6071
|
-
|
|
6313
|
+
if (json.trim().length === 0)
|
|
6314
|
+
return fail("empty request payload");
|
|
6315
|
+
let parsed;
|
|
6316
|
+
try {
|
|
6317
|
+
parsed = JSON.parse(json);
|
|
6318
|
+
} catch {
|
|
6319
|
+
return fail("request payload is not valid JSON");
|
|
6072
6320
|
}
|
|
6073
|
-
|
|
6074
|
-
|
|
6075
|
-
|
|
6321
|
+
const result = PlexuspiRequestSchema.safeParse(parsed);
|
|
6322
|
+
if (result.success)
|
|
6323
|
+
return { ok: true, request: result.data };
|
|
6324
|
+
const loose = parsed ?? {};
|
|
6325
|
+
const operation = OperationSchema.safeParse(loose.operation);
|
|
6326
|
+
return {
|
|
6327
|
+
ok: false,
|
|
6328
|
+
error: `invalid request: ${formatIssues(result.error)}`,
|
|
6329
|
+
sessionKey: typeof loose.sessionKey === "string" ? loose.sessionKey : "",
|
|
6330
|
+
requestId: typeof loose.requestId === "string" ? loose.requestId : "",
|
|
6331
|
+
operation: operation.success ? operation.data : "hello"
|
|
6332
|
+
};
|
|
6333
|
+
}
|
|
6076
6334
|
|
|
6077
|
-
|
|
6078
|
-
|
|
6079
|
-
|
|
6080
|
-
|
|
6081
|
-
|
|
6082
|
-
|
|
6083
|
-
|
|
6084
|
-
|
|
6085
|
-
|
|
6086
|
-
|
|
6087
|
-
|
|
6088
|
-
|
|
6089
|
-
|
|
6090
|
-
|
|
6091
|
-
|
|
6092
|
-
|
|
6093
|
-
|
|
6094
|
-
|
|
6095
|
-
|
|
6096
|
-
|
|
6097
|
-
|
|
6098
|
-
|
|
6099
|
-
|
|
6100
|
-
|
|
6101
|
-
|
|
6102
|
-
|
|
6103
|
-
|
|
6104
|
-
|
|
6105
|
-
|
|
6106
|
-
|
|
6107
|
-
|
|
6108
|
-
|
|
6109
|
-
|
|
6110
|
-
|
|
6111
|
-
|
|
6112
|
-
|
|
6113
|
-
|
|
6114
|
-
|
|
6115
|
-
|
|
6116
|
-
|
|
6117
|
-
|
|
6118
|
-
};
|
|
6119
|
-
if (oversized)
|
|
6120
|
-
next = {
|
|
6121
|
-
...next,
|
|
6122
|
-
status: "unavailable",
|
|
6123
|
-
policies: [],
|
|
6124
|
-
reason: "Context policy snapshot exceeds the 1 MiB publication limit."
|
|
6125
|
-
};
|
|
6126
|
-
if (status !== "ready" && policies.length > 0)
|
|
6127
|
-
next = {
|
|
6128
|
-
...next,
|
|
6129
|
-
status: "unavailable",
|
|
6130
|
-
policies: [],
|
|
6131
|
-
reason: "Context policy metadata is unavailable."
|
|
6132
|
-
};
|
|
6133
|
-
const { revision: _revision, ...stateWithoutRevision } = this.state;
|
|
6134
|
-
const { revision: _candidateRevision, ...nextWithoutRevision } = next;
|
|
6135
|
-
if (JSON.stringify(stateWithoutRevision) === JSON.stringify(nextWithoutRevision))
|
|
6136
|
-
return false;
|
|
6137
|
-
this.revision++;
|
|
6138
|
-
this.state = Object.freeze({
|
|
6139
|
-
...next,
|
|
6140
|
-
revision: this.revision,
|
|
6141
|
-
policies: Object.freeze([...next.policies])
|
|
6142
|
-
});
|
|
6143
|
-
this.send();
|
|
6144
|
-
return true;
|
|
6335
|
+
// src/paseo-control/bridge.ts
|
|
6336
|
+
function createSubagentBridgeTracker(sessionKey) {
|
|
6337
|
+
const runs = new Map;
|
|
6338
|
+
return {
|
|
6339
|
+
accept(record) {
|
|
6340
|
+
const existing = runs.get(record.runId);
|
|
6341
|
+
if (existing) {
|
|
6342
|
+
if (existing.terminal)
|
|
6343
|
+
return;
|
|
6344
|
+
if (record.sequence <= existing.sequence)
|
|
6345
|
+
return;
|
|
6346
|
+
existing.sequence = record.sequence;
|
|
6347
|
+
if (record.type === "terminal")
|
|
6348
|
+
existing.terminal = true;
|
|
6349
|
+
} else {
|
|
6350
|
+
if (record.type !== "created")
|
|
6351
|
+
return;
|
|
6352
|
+
runs.set(record.runId, { sequence: record.sequence, terminal: false });
|
|
6353
|
+
}
|
|
6354
|
+
return { version: SUBAGENT_BRIDGE_VERSION, sessionKey, record };
|
|
6355
|
+
},
|
|
6356
|
+
activeChildren() {
|
|
6357
|
+
let count = 0;
|
|
6358
|
+
for (const run of runs.values()) {
|
|
6359
|
+
if (!run.terminal)
|
|
6360
|
+
count += 1;
|
|
6361
|
+
}
|
|
6362
|
+
return count;
|
|
6363
|
+
}
|
|
6364
|
+
};
|
|
6365
|
+
}
|
|
6366
|
+
function formatChildForward(forward) {
|
|
6367
|
+
return `${CHILD_NOTIFY_PREFIX}${JSON.stringify(forward)}`;
|
|
6368
|
+
}
|
|
6369
|
+
|
|
6370
|
+
// src/paseo-control/conflicts.ts
|
|
6371
|
+
var KNOWN_CONTROL_OWNERS = [
|
|
6372
|
+
{
|
|
6373
|
+
owner: "pi-microgpt",
|
|
6374
|
+
commands: ["fast", "flex", "long-context"],
|
|
6375
|
+
resolution: "Disable pi-microgpt's /fast, /flex, and /long-context commands for this Plexus root so plexus-pi owns tier and context selection."
|
|
6145
6376
|
}
|
|
6146
|
-
|
|
6147
|
-
|
|
6148
|
-
|
|
6149
|
-
|
|
6150
|
-
|
|
6151
|
-
|
|
6152
|
-
if (
|
|
6153
|
-
|
|
6154
|
-
|
|
6155
|
-
|
|
6156
|
-
|
|
6157
|
-
status: "unavailable",
|
|
6158
|
-
policies: [],
|
|
6159
|
-
reason: "Context policy snapshot exceeds publication limits or is invalid.",
|
|
6160
|
-
...requestId === undefined ? {} : { requestId }
|
|
6377
|
+
];
|
|
6378
|
+
function detectControlConflicts(commands) {
|
|
6379
|
+
const declared = new Set(commands.filter((command) => command.source === undefined || command.source === "extension").map((command) => command.name));
|
|
6380
|
+
const conflicts = [];
|
|
6381
|
+
for (const known of KNOWN_CONTROL_OWNERS) {
|
|
6382
|
+
const matched = known.commands.filter((command) => declared.has(command));
|
|
6383
|
+
if (matched.length > 0) {
|
|
6384
|
+
conflicts.push({
|
|
6385
|
+
owner: known.owner,
|
|
6386
|
+
command: matched.join(", "),
|
|
6387
|
+
resolution: known.resolution
|
|
6161
6388
|
});
|
|
6162
6389
|
}
|
|
6163
|
-
if (valid.success)
|
|
6164
|
-
this.emit(CONTEXT_POLICY_SNAPSHOT_CHANNEL, Object.freeze(valid.data));
|
|
6165
|
-
}
|
|
6166
|
-
dispose() {
|
|
6167
|
-
this.unsubscribe();
|
|
6168
6390
|
}
|
|
6391
|
+
return conflicts;
|
|
6169
6392
|
}
|
|
6170
|
-
var CONTEXT_POLICY_METADATA_UNAVAILABLE_REASON = SAFE_REASON;
|
|
6171
6393
|
|
|
6172
|
-
// src/
|
|
6173
|
-
|
|
6174
|
-
|
|
6175
|
-
|
|
6176
|
-
|
|
6177
|
-
|
|
6178
|
-
|
|
6179
|
-
|
|
6180
|
-
|
|
6394
|
+
// src/paseo-control/rewind.ts
|
|
6395
|
+
function findActiveBranchUserEntry(branch, targetEntryId) {
|
|
6396
|
+
const entry = branch.find((candidate) => candidate.id === targetEntryId);
|
|
6397
|
+
if (!entry)
|
|
6398
|
+
return { ok: false, error: "rewind target is not on the active branch" };
|
|
6399
|
+
if (entry.type !== "message" || entry.message?.role !== "user") {
|
|
6400
|
+
return {
|
|
6401
|
+
ok: false,
|
|
6402
|
+
error: "rewind target must be an active-branch user message"
|
|
6403
|
+
};
|
|
6404
|
+
}
|
|
6405
|
+
return { ok: true, entry };
|
|
6181
6406
|
}
|
|
6182
|
-
|
|
6183
|
-
|
|
6184
|
-
|
|
6185
|
-
|
|
6186
|
-
|
|
6187
|
-
|
|
6188
|
-
|
|
6189
|
-
|
|
6190
|
-
|
|
6191
|
-
|
|
6192
|
-
await appendFile(getLogPath(), line, "utf8");
|
|
6193
|
-
} catch {}
|
|
6407
|
+
function buildRewindEntry(targetEntryId, leafId, timestamp) {
|
|
6408
|
+
return {
|
|
6409
|
+
version: PROTOCOL_VERSION,
|
|
6410
|
+
targetEntryId,
|
|
6411
|
+
...leafId !== null ? { leafId } : {},
|
|
6412
|
+
timestamp
|
|
6413
|
+
};
|
|
6414
|
+
}
|
|
6415
|
+
function navigationCancelled(result) {
|
|
6416
|
+
return Boolean(result && typeof result === "object" && result.cancelled === true);
|
|
6194
6417
|
}
|
|
6195
6418
|
|
|
6196
|
-
// src/
|
|
6197
|
-
|
|
6198
|
-
|
|
6199
|
-
|
|
6200
|
-
|
|
6201
|
-
|
|
6202
|
-
|
|
6203
|
-
|
|
6204
|
-
|
|
6205
|
-
|
|
6206
|
-
|
|
6207
|
-
|
|
6208
|
-
|
|
6209
|
-
|
|
6210
|
-
|
|
6211
|
-
if (block?.type === "text" && typeof block.text === "string" && MALFORMED_LEAK_PATTERN.test(block.text)) {
|
|
6212
|
-
return true;
|
|
6213
|
-
}
|
|
6214
|
-
}
|
|
6215
|
-
return false;
|
|
6419
|
+
// src/paseo-control/tier.ts
|
|
6420
|
+
function resolveSavedTier(tier, choices) {
|
|
6421
|
+
if (choices.includes(tier))
|
|
6422
|
+
return tier;
|
|
6423
|
+
const migrated = tier === "fast" ? "priority" : tier === "default" ? "auto" : tier;
|
|
6424
|
+
if (choices.includes(migrated))
|
|
6425
|
+
return migrated;
|
|
6426
|
+
if (choices.includes("auto"))
|
|
6427
|
+
return "auto";
|
|
6428
|
+
if (choices.includes("standard"))
|
|
6429
|
+
return "standard";
|
|
6430
|
+
return NO_TIER;
|
|
6431
|
+
}
|
|
6432
|
+
function isTierApplicable(model, tier, policy) {
|
|
6433
|
+
return model?.provider === "plexus" && policy?.provider === model.provider && policy.modelId === model.id && policy.serviceTiers.includes(tier);
|
|
6216
6434
|
}
|
|
6217
|
-
|
|
6218
|
-
|
|
6435
|
+
|
|
6436
|
+
// src/paseo-control/control.ts
|
|
6437
|
+
var CAPABILITIES = [
|
|
6438
|
+
"hello",
|
|
6439
|
+
"get-state",
|
|
6440
|
+
"configure",
|
|
6441
|
+
"rewind",
|
|
6442
|
+
"reload"
|
|
6443
|
+
];
|
|
6444
|
+
var LIMITATIONS = [
|
|
6445
|
+
"rewind restores Pi's active branch and appends a branch pin; it never writes files and never summarizes the abandoned future",
|
|
6446
|
+
"rewind is rejected while the root agent is busy, while a compaction is in progress, or while owned children are active",
|
|
6447
|
+
"the provider must clear its own queued input before asking the module to navigate",
|
|
6448
|
+
"reload is accepted while idle and the ok reply is emitted before reloading, so ok means started rather than finished; the provider confirms completion by re-reading state and commands",
|
|
6449
|
+
"reload re-reads settings, extensions, skills, prompts, themes, and context files without touching the session history; files that arrive after reload starts are not picked up",
|
|
6450
|
+
"host history replacement after rewind is the provider's supported-adapter concern, not a module-invented reset event",
|
|
6451
|
+
"active owned children are counted from the pi-subagents bridge; children not bridged are not visible",
|
|
6452
|
+
"advertised service tiers describe Plexus capabilities, not a routing or backend acceptance guarantee",
|
|
6453
|
+
"context budgets come from Plexus policy metadata; models without distinct short/max budgets have no long-context control"
|
|
6454
|
+
];
|
|
6455
|
+
var APPLY_ERROR = "Pi could not apply the context policy budget.";
|
|
6456
|
+
function normalizeKey(value) {
|
|
6457
|
+
if (typeof value !== "string")
|
|
6458
|
+
return;
|
|
6459
|
+
const trimmed = value.trim();
|
|
6460
|
+
return trimmed.length > 0 ? trimmed : undefined;
|
|
6219
6461
|
}
|
|
6220
|
-
function
|
|
6221
|
-
|
|
6462
|
+
function readSessionId(ctx) {
|
|
6463
|
+
try {
|
|
6464
|
+
const id = ctx.sessionManager.getSessionId();
|
|
6465
|
+
return typeof id === "string" && id.length > 0 ? id : undefined;
|
|
6466
|
+
} catch {
|
|
6222
6467
|
return;
|
|
6223
6468
|
}
|
|
6224
|
-
|
|
6469
|
+
}
|
|
6470
|
+
function readLeafId(ctx) {
|
|
6471
|
+
try {
|
|
6472
|
+
const id = ctx.sessionManager.getLeafId();
|
|
6473
|
+
return typeof id === "string" && id.length > 0 ? id : undefined;
|
|
6474
|
+
} catch {
|
|
6225
6475
|
return;
|
|
6226
6476
|
}
|
|
6227
|
-
|
|
6228
|
-
|
|
6229
|
-
|
|
6230
|
-
|
|
6231
|
-
|
|
6232
|
-
|
|
6233
|
-
return { message: { ...message, errorMessage: TRUNCATED_JSON_MESSAGE } };
|
|
6477
|
+
}
|
|
6478
|
+
function readBranch(ctx) {
|
|
6479
|
+
try {
|
|
6480
|
+
return ctx.sessionManager.getBranch();
|
|
6481
|
+
} catch {
|
|
6482
|
+
return [];
|
|
6234
6483
|
}
|
|
6235
|
-
|
|
6236
|
-
|
|
6237
|
-
|
|
6238
|
-
|
|
6484
|
+
}
|
|
6485
|
+
function createPlexuspiControl(pi, deps, options = {}) {
|
|
6486
|
+
const { policy, host } = deps;
|
|
6487
|
+
const now = options.now ?? (() => Date.now());
|
|
6488
|
+
const expectedSessionKey = normalizeKey(options.sessionKey ?? process.env[SESSION_KEY_ENV]);
|
|
6489
|
+
const bridgeTracker = createSubagentBridgeTracker(expectedSessionKey ?? "");
|
|
6490
|
+
let active = false;
|
|
6491
|
+
let closed = false;
|
|
6492
|
+
let latestCtx;
|
|
6493
|
+
let compactionActive = false;
|
|
6494
|
+
let desiredTier = NO_TIER;
|
|
6495
|
+
let desiredLongContext = false;
|
|
6496
|
+
let resolvedTier = NO_TIER;
|
|
6497
|
+
let suspendPersist = false;
|
|
6498
|
+
let persistedKey = "";
|
|
6499
|
+
let unsubscribeBridge;
|
|
6500
|
+
let unsubscribeView;
|
|
6501
|
+
const resolveIntent = (_model, advertisement) => {
|
|
6502
|
+
const choices = advertisement?.serviceTier?.serviceTiers ?? [];
|
|
6503
|
+
resolvedTier = resolveSavedTier(desiredTier, choices);
|
|
6504
|
+
if (choices.includes(desiredTier) || desiredTier === "fast" && resolvedTier === "priority" || desiredTier === NO_TIER && (resolvedTier === "auto" || resolvedTier === "standard")) {
|
|
6505
|
+
desiredTier = resolvedTier;
|
|
6506
|
+
}
|
|
6507
|
+
const context = advertisement?.context;
|
|
6508
|
+
const distinct = context !== undefined && context.shortContextBudgetTokens < context.maxContextTokens;
|
|
6509
|
+
if (!distinct && host.hasCatalogContextPolicy())
|
|
6510
|
+
desiredLongContext = false;
|
|
6511
|
+
return { longContext: desiredLongContext, serviceTier: resolvedTier };
|
|
6512
|
+
};
|
|
6513
|
+
function reportedSettings() {
|
|
6239
6514
|
return {
|
|
6240
|
-
|
|
6515
|
+
tier: resolvedTier,
|
|
6516
|
+
longContext: policy.getView().selection.longContext
|
|
6241
6517
|
};
|
|
6242
6518
|
}
|
|
6243
|
-
|
|
6244
|
-
|
|
6245
|
-
|
|
6246
|
-
|
|
6247
|
-
|
|
6248
|
-
|
|
6249
|
-
}
|
|
6250
|
-
|
|
6251
|
-
}
|
|
6252
|
-
|
|
6253
|
-
// src/mapper.ts
|
|
6254
|
-
import {
|
|
6255
|
-
getModel
|
|
6256
|
-
} from "@earendil-works/pi-ai/compat";
|
|
6257
|
-
var MINIMUM_OUTPUT_TOKENS = 8192;
|
|
6258
|
-
function descriptorToPiModel(descriptor) {
|
|
6259
|
-
let builtinModel;
|
|
6260
|
-
if (descriptor.piProvider && descriptor.piModel) {
|
|
6519
|
+
function plexusModel(model) {
|
|
6520
|
+
return model?.provider === "plexus" && typeof model.id === "string" ? { provider: "plexus", id: model.id } : undefined;
|
|
6521
|
+
}
|
|
6522
|
+
function advertisementFor(model) {
|
|
6523
|
+
const identity = plexusModel(model);
|
|
6524
|
+
return identity ? host.getAdvertisement(identity) : undefined;
|
|
6525
|
+
}
|
|
6526
|
+
function conflicts() {
|
|
6261
6527
|
try {
|
|
6262
|
-
|
|
6528
|
+
return detectControlConflicts(pi.getCommands());
|
|
6263
6529
|
} catch {
|
|
6264
|
-
|
|
6530
|
+
return [];
|
|
6265
6531
|
}
|
|
6266
6532
|
}
|
|
6267
|
-
|
|
6268
|
-
|
|
6269
|
-
|
|
6270
|
-
|
|
6271
|
-
|
|
6272
|
-
|
|
6273
|
-
|
|
6274
|
-
|
|
6275
|
-
|
|
6276
|
-
|
|
6277
|
-
|
|
6278
|
-
|
|
6279
|
-
|
|
6280
|
-
|
|
6281
|
-
|
|
6282
|
-
|
|
6283
|
-
if (descriptor.preferredApi === "openai-completions") {
|
|
6284
|
-
const heuristic = detectOpenAICompletionsCompat(descriptor.piProvider ?? descriptor.provider, descriptor.baseUrl);
|
|
6285
|
-
const builtinCompat = builtinModel?.compat;
|
|
6286
|
-
const merged = {
|
|
6287
|
-
...heuristic,
|
|
6288
|
-
...builtinCompat ?? {},
|
|
6289
|
-
...descriptor.piOptions ?? {}
|
|
6533
|
+
function buildState(ctx) {
|
|
6534
|
+
const model = ctx.model;
|
|
6535
|
+
const identity = plexusModel(model);
|
|
6536
|
+
const advertisement = advertisementFor(model);
|
|
6537
|
+
const context = advertisement?.context;
|
|
6538
|
+
const settings = reportedSettings();
|
|
6539
|
+
const state = {
|
|
6540
|
+
capabilities: [...CAPABILITIES],
|
|
6541
|
+
settings,
|
|
6542
|
+
origin: "root",
|
|
6543
|
+
tiers: [...advertisement?.serviceTier?.serviceTiers ?? []],
|
|
6544
|
+
longContextAvailable: context !== undefined && context.shortContextBudgetTokens < context.maxContextTokens,
|
|
6545
|
+
tierApplicable: isTierApplicable(model, settings.tier, advertisement?.serviceTier),
|
|
6546
|
+
conflicts: conflicts(),
|
|
6547
|
+
limitations: [...LIMITATIONS],
|
|
6548
|
+
activeChildren: bridgeTracker.activeChildren()
|
|
6290
6549
|
};
|
|
6291
|
-
|
|
6292
|
-
|
|
6293
|
-
|
|
6294
|
-
|
|
6295
|
-
|
|
6550
|
+
if (typeof model?.contextWindow === "number")
|
|
6551
|
+
state.contextWindow = model.contextWindow;
|
|
6552
|
+
const sessionId = readSessionId(ctx);
|
|
6553
|
+
if (sessionId !== undefined)
|
|
6554
|
+
state.sessionId = sessionId;
|
|
6555
|
+
if (context) {
|
|
6556
|
+
state.longContextTarget = context.maxContextTokens;
|
|
6557
|
+
state.shortContextBudgetTokens = context.shortContextBudgetTokens;
|
|
6558
|
+
if (context.pricingThresholdInputTokens !== undefined)
|
|
6559
|
+
state.pricingThresholdInputTokens = context.pricingThresholdInputTokens;
|
|
6560
|
+
}
|
|
6561
|
+
const baseline = identity ? host.getCatalogContextWindow(identity) : undefined;
|
|
6562
|
+
if (baseline !== undefined)
|
|
6563
|
+
state.modelBaselineContextWindow = baseline;
|
|
6564
|
+
if (policy.getView().applyFailed)
|
|
6565
|
+
state.contextPolicyError = APPLY_ERROR;
|
|
6566
|
+
return PlexuspiStateSchema.parse(state);
|
|
6567
|
+
}
|
|
6568
|
+
function publishState(ctx) {
|
|
6569
|
+
if (!expectedSessionKey)
|
|
6570
|
+
return;
|
|
6571
|
+
ctx.ui.notify(`${STATE_NOTIFY_PREFIX}${JSON.stringify({ version: PROTOCOL_VERSION, sessionKey: expectedSessionKey, state: buildState(ctx) })}`, "info");
|
|
6296
6572
|
}
|
|
6297
|
-
|
|
6298
|
-
|
|
6299
|
-
|
|
6300
|
-
|
|
6301
|
-
|
|
6302
|
-
|
|
6303
|
-
|
|
6304
|
-
|
|
6305
|
-
|
|
6306
|
-
|
|
6307
|
-
|
|
6308
|
-
|
|
6309
|
-
|
|
6310
|
-
|
|
6311
|
-
|
|
6312
|
-
|
|
6313
|
-
}
|
|
6314
|
-
|
|
6315
|
-
|
|
6316
|
-
|
|
6317
|
-
|
|
6318
|
-
|
|
6319
|
-
|
|
6320
|
-
|
|
6321
|
-
|
|
6322
|
-
|
|
6323
|
-
|
|
6324
|
-
|
|
6325
|
-
|
|
6326
|
-
|
|
6327
|
-
|
|
6328
|
-
|
|
6329
|
-
|
|
6330
|
-
modelCount: number2().int().nonnegative().safe().optional(),
|
|
6331
|
-
reason: string2().max(500).optional()
|
|
6332
|
-
}).strict();
|
|
6333
|
-
var MODELS_REFRESH_FAILED_REASON = "The Plexus catalog refresh failed.";
|
|
6334
|
-
var encoder = new TextEncoder;
|
|
6335
|
-
function byteLength(value) {
|
|
6336
|
-
return encoder.encode(JSON.stringify(value)).byteLength;
|
|
6337
|
-
}
|
|
6338
|
-
function freezeState(state) {
|
|
6339
|
-
return Object.freeze({ ...state });
|
|
6340
|
-
}
|
|
6341
|
-
function freezeParsed(state) {
|
|
6342
|
-
return Object.freeze({ ...state });
|
|
6343
|
-
}
|
|
6344
|
-
function statesEqual(current, next) {
|
|
6345
|
-
return current.status === next.status && current.modelCount === next.modelCount && current.reason === next.reason;
|
|
6346
|
-
}
|
|
6347
|
-
|
|
6348
|
-
class ModelsControl {
|
|
6349
|
-
host;
|
|
6350
|
-
publisherId = randomUUID2();
|
|
6351
|
-
revision = 1;
|
|
6352
|
-
state;
|
|
6353
|
-
inFlight;
|
|
6354
|
-
emit;
|
|
6355
|
-
unsubscribe;
|
|
6356
|
-
constructor(events, host) {
|
|
6357
|
-
this.host = host;
|
|
6358
|
-
this.emit = events.emit.bind(events);
|
|
6359
|
-
this.state = freezeState({
|
|
6360
|
-
version: 1,
|
|
6361
|
-
publisherId: this.publisherId,
|
|
6362
|
-
revision: 1,
|
|
6363
|
-
status: "idle"
|
|
6573
|
+
function emit(ctx, reply) {
|
|
6574
|
+
const validated = PlexuspiReplySchema.parse(reply);
|
|
6575
|
+
ctx.ui.notify(`${NOTIFY_PREFIX}${JSON.stringify(validated)}`, validated.ok ? "info" : "warning");
|
|
6576
|
+
}
|
|
6577
|
+
function base(request) {
|
|
6578
|
+
return {
|
|
6579
|
+
version: PROTOCOL_VERSION,
|
|
6580
|
+
sessionKey: request.sessionKey,
|
|
6581
|
+
requestId: request.requestId,
|
|
6582
|
+
operation: request.operation
|
|
6583
|
+
};
|
|
6584
|
+
}
|
|
6585
|
+
function controlKey() {
|
|
6586
|
+
return JSON.stringify({
|
|
6587
|
+
tier: desiredTier,
|
|
6588
|
+
longContext: reportedSettings().longContext
|
|
6589
|
+
});
|
|
6590
|
+
}
|
|
6591
|
+
function persistIfChanged() {
|
|
6592
|
+
if (suspendPersist)
|
|
6593
|
+
return;
|
|
6594
|
+
const key = controlKey();
|
|
6595
|
+
if (key === persistedKey)
|
|
6596
|
+
return;
|
|
6597
|
+
persistedKey = key;
|
|
6598
|
+
const model = policy.getView().model;
|
|
6599
|
+
const baseline = model ? host.getCatalogContextWindow(model) : undefined;
|
|
6600
|
+
pi.appendEntry(CUSTOM_ENTRY_TYPE, {
|
|
6601
|
+
version: PROTOCOL_VERSION,
|
|
6602
|
+
tier: desiredTier,
|
|
6603
|
+
longContext: reportedSettings().longContext,
|
|
6604
|
+
...baseline !== undefined ? { contextWindow: baseline } : {},
|
|
6605
|
+
timestamp: now()
|
|
6364
6606
|
});
|
|
6365
|
-
this.unsubscribe = events.on(MODELS_REFRESH_CHANNEL, (data) => this.handleCommand(data));
|
|
6366
6607
|
}
|
|
6367
|
-
|
|
6368
|
-
|
|
6608
|
+
function onPolicyCommit() {
|
|
6609
|
+
if (!active || closed)
|
|
6610
|
+
return;
|
|
6611
|
+
persistIfChanged();
|
|
6612
|
+
if (latestCtx)
|
|
6613
|
+
publishState(latestCtx);
|
|
6614
|
+
}
|
|
6615
|
+
function latestControlEntry(ctx) {
|
|
6616
|
+
let latest;
|
|
6617
|
+
for (const entry of readBranch(ctx)) {
|
|
6618
|
+
if (entry.type !== "custom" || entry.customType !== CUSTOM_ENTRY_TYPE)
|
|
6619
|
+
continue;
|
|
6620
|
+
const parsed = ControlEntrySchema.safeParse(entry.data);
|
|
6621
|
+
if (parsed.success)
|
|
6622
|
+
latest = parsed.data;
|
|
6623
|
+
}
|
|
6624
|
+
return latest;
|
|
6369
6625
|
}
|
|
6370
|
-
|
|
6371
|
-
|
|
6626
|
+
async function restore(ctx) {
|
|
6627
|
+
const entry = latestControlEntry(ctx);
|
|
6628
|
+
desiredTier = entry?.tier ?? NO_TIER;
|
|
6629
|
+
desiredLongContext = entry?.longContext ?? false;
|
|
6630
|
+
suspendPersist = true;
|
|
6631
|
+
try {
|
|
6632
|
+
await policy.reconcile();
|
|
6633
|
+
} finally {
|
|
6634
|
+
suspendPersist = false;
|
|
6635
|
+
}
|
|
6636
|
+
persistedKey = controlKey();
|
|
6372
6637
|
}
|
|
6373
|
-
|
|
6374
|
-
|
|
6638
|
+
function forwardBridgeRecord(data) {
|
|
6639
|
+
if (!active || closed)
|
|
6640
|
+
return;
|
|
6641
|
+
const parsed = SubagentBridgeRecordSchema.safeParse(data);
|
|
6375
6642
|
if (!parsed.success)
|
|
6376
6643
|
return;
|
|
6377
|
-
|
|
6378
|
-
|
|
6379
|
-
|
|
6380
|
-
|
|
6644
|
+
const forward = bridgeTracker.accept(parsed.data);
|
|
6645
|
+
if (!forward || !latestCtx)
|
|
6646
|
+
return;
|
|
6647
|
+
latestCtx.ui.notify(formatChildForward(forward), "info");
|
|
6648
|
+
}
|
|
6649
|
+
function emitRootSignal(ctx) {
|
|
6650
|
+
const sessionId = readSessionId(ctx);
|
|
6651
|
+
if (sessionId === undefined)
|
|
6652
|
+
return;
|
|
6653
|
+
pi.events.emit(ROOT_SIGNAL_CHANNEL, {
|
|
6654
|
+
version: ROOT_SIGNAL_VERSION,
|
|
6655
|
+
sessionId
|
|
6656
|
+
});
|
|
6657
|
+
}
|
|
6658
|
+
async function activate(ctx) {
|
|
6659
|
+
latestCtx = ctx;
|
|
6660
|
+
if (active)
|
|
6661
|
+
return;
|
|
6662
|
+
active = true;
|
|
6663
|
+
policy.setResolver(resolveIntent);
|
|
6664
|
+
unsubscribeView = policy.subscribe(onPolicyCommit);
|
|
6665
|
+
unsubscribeBridge = pi.events.on(SUBAGENT_BRIDGE_CHANNEL, forwardBridgeRecord);
|
|
6666
|
+
await restore(ctx);
|
|
6667
|
+
emitRootSignal(ctx);
|
|
6668
|
+
}
|
|
6669
|
+
function rewindResult(cancelled, targetEntryId, ctx) {
|
|
6670
|
+
const leafId = readLeafId(ctx);
|
|
6671
|
+
return {
|
|
6672
|
+
cancelled,
|
|
6673
|
+
targetEntryId,
|
|
6674
|
+
...leafId !== undefined ? { leafId } : {},
|
|
6675
|
+
settings: reportedSettings(),
|
|
6676
|
+
activeChildren: bridgeTracker.activeChildren()
|
|
6677
|
+
};
|
|
6678
|
+
}
|
|
6679
|
+
function handleHello(request, ctx) {
|
|
6680
|
+
const data = buildState(ctx);
|
|
6681
|
+
if (data.conflicts.length > 0) {
|
|
6682
|
+
const detail = data.conflicts.map((conflict) => `${conflict.owner} owns ${conflict.command}`).join("; ");
|
|
6683
|
+
const resolutions = data.conflicts.map((conflict) => conflict.resolution).join(" ");
|
|
6684
|
+
emit(ctx, {
|
|
6685
|
+
...base(request),
|
|
6686
|
+
ok: false,
|
|
6687
|
+
data,
|
|
6688
|
+
error: `known control owner conflict: ${detail}. ${resolutions}`
|
|
6689
|
+
});
|
|
6690
|
+
return;
|
|
6691
|
+
}
|
|
6692
|
+
emit(ctx, { ...base(request), ok: true, data });
|
|
6693
|
+
}
|
|
6694
|
+
async function handleConfigure(request, ctx) {
|
|
6695
|
+
const parsed = ConfigureDataSchema.safeParse(request.data ?? {});
|
|
6696
|
+
if (!parsed.success) {
|
|
6697
|
+
emit(ctx, {
|
|
6698
|
+
...base(request),
|
|
6699
|
+
ok: false,
|
|
6700
|
+
error: `invalid configure data: ${formatIssues(parsed.error)}`
|
|
6701
|
+
});
|
|
6702
|
+
return;
|
|
6703
|
+
}
|
|
6704
|
+
const advertisement = advertisementFor(ctx.model);
|
|
6705
|
+
const choices = advertisement?.serviceTier?.serviceTiers ?? [];
|
|
6706
|
+
const requestedTier = parsed.data.tier;
|
|
6707
|
+
const nextTier = requestedTier === undefined ? resolvedTier : choices.includes(requestedTier) ? requestedTier : requestedTier === "fast" ? "priority" : requestedTier === NO_TIER ? resolveSavedTier(requestedTier, choices) : requestedTier;
|
|
6708
|
+
if (requestedTier !== undefined && !choices.includes(nextTier)) {
|
|
6709
|
+
emit(ctx, {
|
|
6710
|
+
...base(request),
|
|
6711
|
+
ok: false,
|
|
6712
|
+
data: buildState(ctx),
|
|
6713
|
+
error: `Service tier '${requestedTier}' is not advertised for the current model.`
|
|
6714
|
+
});
|
|
6715
|
+
return;
|
|
6716
|
+
}
|
|
6717
|
+
const nextLongContext = parsed.data.longContext ?? reportedSettings().longContext;
|
|
6718
|
+
const context = advertisement?.context;
|
|
6719
|
+
if (nextLongContext && (!context || context.shortContextBudgetTokens >= context.maxContextTokens)) {
|
|
6720
|
+
emit(ctx, {
|
|
6721
|
+
...base(request),
|
|
6722
|
+
ok: false,
|
|
6723
|
+
data: buildState(ctx),
|
|
6724
|
+
error: "The current model has no distinct short and long context budgets."
|
|
6381
6725
|
});
|
|
6726
|
+
return;
|
|
6382
6727
|
}
|
|
6383
|
-
|
|
6384
|
-
|
|
6728
|
+
if (parsed.data.longContext !== undefined) {
|
|
6729
|
+
const previousLongContext = desiredLongContext;
|
|
6730
|
+
desiredLongContext = nextLongContext;
|
|
6731
|
+
await policy.reconcile();
|
|
6732
|
+
if (policy.getView().applyFailed) {
|
|
6733
|
+
desiredLongContext = previousLongContext;
|
|
6734
|
+
emit(ctx, {
|
|
6735
|
+
...base(request),
|
|
6736
|
+
ok: false,
|
|
6737
|
+
data: buildState(ctx),
|
|
6738
|
+
error: APPLY_ERROR
|
|
6739
|
+
});
|
|
6740
|
+
return;
|
|
6741
|
+
}
|
|
6742
|
+
}
|
|
6743
|
+
if (requestedTier !== undefined) {
|
|
6744
|
+
desiredTier = nextTier;
|
|
6745
|
+
await policy.reconcile();
|
|
6746
|
+
}
|
|
6747
|
+
emit(ctx, { ...base(request), ok: true, data: buildState(ctx) });
|
|
6385
6748
|
}
|
|
6386
|
-
async
|
|
6387
|
-
|
|
6749
|
+
async function handleRewind(request, ctx) {
|
|
6750
|
+
const parsed = RewindDataSchema.safeParse(request.data ?? {});
|
|
6751
|
+
if (!parsed.success) {
|
|
6752
|
+
emit(ctx, {
|
|
6753
|
+
...base(request),
|
|
6754
|
+
ok: false,
|
|
6755
|
+
error: `invalid rewind data: ${formatIssues(parsed.error)}`
|
|
6756
|
+
});
|
|
6757
|
+
return;
|
|
6758
|
+
}
|
|
6759
|
+
const { targetEntryId } = parsed.data;
|
|
6760
|
+
if (!ctx.isIdle()) {
|
|
6761
|
+
emit(ctx, {
|
|
6762
|
+
...base(request),
|
|
6763
|
+
ok: false,
|
|
6764
|
+
data: buildState(ctx),
|
|
6765
|
+
error: "rewind requires an idle agent"
|
|
6766
|
+
});
|
|
6767
|
+
return;
|
|
6768
|
+
}
|
|
6769
|
+
if (compactionActive) {
|
|
6770
|
+
emit(ctx, {
|
|
6771
|
+
...base(request),
|
|
6772
|
+
ok: false,
|
|
6773
|
+
data: buildState(ctx),
|
|
6774
|
+
error: "rewind is unavailable while a compaction is in progress"
|
|
6775
|
+
});
|
|
6776
|
+
return;
|
|
6777
|
+
}
|
|
6778
|
+
const activeChildren = bridgeTracker.activeChildren();
|
|
6779
|
+
if (activeChildren > 0) {
|
|
6780
|
+
emit(ctx, {
|
|
6781
|
+
...base(request),
|
|
6782
|
+
ok: false,
|
|
6783
|
+
data: buildState(ctx),
|
|
6784
|
+
error: `rewind is unavailable while ${activeChildren} owned child session(s) are active`
|
|
6785
|
+
});
|
|
6786
|
+
return;
|
|
6787
|
+
}
|
|
6788
|
+
const target = findActiveBranchUserEntry(readBranch(ctx), targetEntryId);
|
|
6789
|
+
if (!target.ok) {
|
|
6790
|
+
emit(ctx, {
|
|
6791
|
+
...base(request),
|
|
6792
|
+
ok: false,
|
|
6793
|
+
data: buildState(ctx),
|
|
6794
|
+
error: `invalid rewind target: ${target.error}`
|
|
6795
|
+
});
|
|
6796
|
+
return;
|
|
6797
|
+
}
|
|
6798
|
+
let result;
|
|
6388
6799
|
try {
|
|
6389
|
-
|
|
6390
|
-
this.commit({ status: "ready", modelCount: result.modelCount });
|
|
6800
|
+
result = await ctx.navigateTree(targetEntryId, { summarize: false });
|
|
6391
6801
|
} catch (error) {
|
|
6392
|
-
|
|
6393
|
-
|
|
6802
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
6803
|
+
emit(ctx, {
|
|
6804
|
+
...base(request),
|
|
6805
|
+
ok: false,
|
|
6806
|
+
data: buildState(ctx),
|
|
6807
|
+
error: `rewind navigation failed: ${message}`
|
|
6808
|
+
});
|
|
6809
|
+
return;
|
|
6394
6810
|
}
|
|
6395
|
-
|
|
6396
|
-
|
|
6397
|
-
|
|
6811
|
+
if (navigationCancelled(result)) {
|
|
6812
|
+
emit(ctx, {
|
|
6813
|
+
...base(request),
|
|
6814
|
+
ok: false,
|
|
6815
|
+
data: rewindResult(true, targetEntryId, ctx),
|
|
6816
|
+
error: "rewind was cancelled before navigation completed."
|
|
6817
|
+
});
|
|
6398
6818
|
return;
|
|
6399
|
-
|
|
6400
|
-
|
|
6401
|
-
|
|
6402
|
-
|
|
6403
|
-
|
|
6404
|
-
|
|
6405
|
-
...
|
|
6406
|
-
|
|
6819
|
+
}
|
|
6820
|
+
const leafId = readLeafId(ctx) ?? null;
|
|
6821
|
+
pi.appendEntry(REWIND_ENTRY_TYPE, buildRewindEntry(targetEntryId, leafId, now()));
|
|
6822
|
+
latestCtx = ctx;
|
|
6823
|
+
await restore(ctx);
|
|
6824
|
+
emit(ctx, {
|
|
6825
|
+
...base(request),
|
|
6826
|
+
ok: true,
|
|
6827
|
+
data: rewindResult(false, targetEntryId, ctx)
|
|
6407
6828
|
});
|
|
6408
|
-
this.emitState(this.state);
|
|
6409
6829
|
}
|
|
6410
|
-
|
|
6411
|
-
|
|
6412
|
-
|
|
6413
|
-
|
|
6414
|
-
|
|
6830
|
+
async function handleReload(request, ctx) {
|
|
6831
|
+
if (!ctx.isIdle()) {
|
|
6832
|
+
emit(ctx, {
|
|
6833
|
+
...base(request),
|
|
6834
|
+
ok: false,
|
|
6835
|
+
data: buildState(ctx),
|
|
6836
|
+
error: "reload is unavailable while the agent is busy"
|
|
6837
|
+
});
|
|
6415
6838
|
return;
|
|
6416
6839
|
}
|
|
6417
|
-
|
|
6418
|
-
|
|
6419
|
-
|
|
6420
|
-
|
|
6421
|
-
|
|
6422
|
-
|
|
6423
|
-
|
|
6424
|
-
|
|
6425
|
-
|
|
6426
|
-
|
|
6840
|
+
if (compactionActive) {
|
|
6841
|
+
emit(ctx, {
|
|
6842
|
+
...base(request),
|
|
6843
|
+
ok: false,
|
|
6844
|
+
data: buildState(ctx),
|
|
6845
|
+
error: "reload is unavailable while a compaction is in progress"
|
|
6846
|
+
});
|
|
6847
|
+
return;
|
|
6848
|
+
}
|
|
6849
|
+
const activeChildren = bridgeTracker.activeChildren();
|
|
6850
|
+
if (activeChildren > 0) {
|
|
6851
|
+
emit(ctx, {
|
|
6852
|
+
...base(request),
|
|
6853
|
+
ok: false,
|
|
6854
|
+
data: buildState(ctx),
|
|
6855
|
+
error: `reload is unavailable while ${activeChildren} owned child session(s) are active`
|
|
6856
|
+
});
|
|
6857
|
+
return;
|
|
6858
|
+
}
|
|
6859
|
+
emit(ctx, { ...base(request), ok: true, data: buildState(ctx) });
|
|
6860
|
+
await ctx.reload();
|
|
6861
|
+
}
|
|
6862
|
+
async function handleArgs(args, ctx) {
|
|
6863
|
+
const parsed = parseRequestArg(args);
|
|
6864
|
+
if (!parsed.ok) {
|
|
6865
|
+
emit(ctx, {
|
|
6866
|
+
version: PROTOCOL_VERSION,
|
|
6867
|
+
sessionKey: parsed.sessionKey,
|
|
6868
|
+
requestId: parsed.requestId,
|
|
6869
|
+
operation: parsed.operation,
|
|
6870
|
+
ok: false,
|
|
6871
|
+
error: parsed.error
|
|
6872
|
+
});
|
|
6873
|
+
return;
|
|
6874
|
+
}
|
|
6875
|
+
const request = parsed.request;
|
|
6876
|
+
const refuse = (error) => emit(ctx, { ...base(request), ok: false, error });
|
|
6877
|
+
if (!expectedSessionKey) {
|
|
6878
|
+
refuse(`${SESSION_KEY_ENV} is not set for this process; refusing control request.`);
|
|
6879
|
+
return;
|
|
6880
|
+
}
|
|
6881
|
+
if (request.sessionKey !== expectedSessionKey) {
|
|
6882
|
+
refuse("session key mismatch; refusing control request.");
|
|
6883
|
+
return;
|
|
6884
|
+
}
|
|
6885
|
+
await activate(ctx);
|
|
6886
|
+
switch (request.operation) {
|
|
6887
|
+
case "hello":
|
|
6888
|
+
handleHello(request, ctx);
|
|
6889
|
+
return;
|
|
6890
|
+
case "get-state":
|
|
6891
|
+
emit(ctx, { ...base(request), ok: true, data: buildState(ctx) });
|
|
6892
|
+
return;
|
|
6893
|
+
case "configure":
|
|
6894
|
+
await handleConfigure(request, ctx);
|
|
6895
|
+
return;
|
|
6896
|
+
case "rewind":
|
|
6897
|
+
await handleRewind(request, ctx);
|
|
6898
|
+
return;
|
|
6899
|
+
case "reload":
|
|
6900
|
+
await handleReload(request, ctx);
|
|
6901
|
+
return;
|
|
6902
|
+
}
|
|
6427
6903
|
}
|
|
6904
|
+
pi.registerCommand(COMMAND_NAME, {
|
|
6905
|
+
description: "Plexus control protocol (base64url-encoded JSON).",
|
|
6906
|
+
handler: (args, ctx) => handleArgs(args, ctx)
|
|
6907
|
+
});
|
|
6908
|
+
pi.on("session_start", (_event, ctx) => {
|
|
6909
|
+
if (!active || closed)
|
|
6910
|
+
return;
|
|
6911
|
+
latestCtx = ctx;
|
|
6912
|
+
return restore(ctx);
|
|
6913
|
+
});
|
|
6914
|
+
pi.on("session_tree", (_event, ctx) => {
|
|
6915
|
+
if (!active || closed)
|
|
6916
|
+
return;
|
|
6917
|
+
latestCtx = ctx;
|
|
6918
|
+
return restore(ctx);
|
|
6919
|
+
});
|
|
6920
|
+
pi.on("model_select", (_event, ctx) => {
|
|
6921
|
+
if (!active || closed)
|
|
6922
|
+
return;
|
|
6923
|
+
latestCtx = ctx;
|
|
6924
|
+
});
|
|
6925
|
+
pi.on("before_agent_start", async (_event, ctx) => {
|
|
6926
|
+
if (!active || closed)
|
|
6927
|
+
return;
|
|
6928
|
+
latestCtx = ctx;
|
|
6929
|
+
await policy.reconcile();
|
|
6930
|
+
if (policy.getView().applyFailed)
|
|
6931
|
+
throw new Error(APPLY_ERROR);
|
|
6932
|
+
});
|
|
6933
|
+
pi.on("session_before_compact", () => {
|
|
6934
|
+
compactionActive = true;
|
|
6935
|
+
});
|
|
6936
|
+
pi.on("session_compact", () => {
|
|
6937
|
+
compactionActive = false;
|
|
6938
|
+
});
|
|
6939
|
+
pi.on("session_compact_failed", () => {
|
|
6940
|
+
compactionActive = false;
|
|
6941
|
+
});
|
|
6942
|
+
pi.on("session_shutdown", () => {
|
|
6943
|
+
closed = true;
|
|
6944
|
+
compactionActive = false;
|
|
6945
|
+
unsubscribeBridge?.();
|
|
6946
|
+
unsubscribeBridge = undefined;
|
|
6947
|
+
unsubscribeView?.();
|
|
6948
|
+
unsubscribeView = undefined;
|
|
6949
|
+
if (active)
|
|
6950
|
+
policy.setResolver(undefined);
|
|
6951
|
+
latestCtx = undefined;
|
|
6952
|
+
});
|
|
6953
|
+
return {
|
|
6954
|
+
get active() {
|
|
6955
|
+
return active;
|
|
6956
|
+
},
|
|
6957
|
+
handleArgs,
|
|
6958
|
+
buildState,
|
|
6959
|
+
activeChildren: () => bridgeTracker.activeChildren()
|
|
6960
|
+
};
|
|
6428
6961
|
}
|
|
6429
6962
|
|
|
6430
6963
|
// src/policy.ts
|
|
6431
|
-
import { randomUUID as randomUUID3 } from "crypto";
|
|
6432
|
-
var POLICY_SET_CHANNEL = "plexus:policy:set:v1";
|
|
6433
|
-
var POLICY_STATE_CHANNEL = "plexus:policy:state:v1";
|
|
6434
|
-
var MAX_STATE_BYTES2 = 1024 * 1024;
|
|
6435
|
-
var PolicySetSchema = object({
|
|
6436
|
-
version: literal(1),
|
|
6437
|
-
requestId: string2().min(1).max(1024),
|
|
6438
|
-
longContext: boolean2().optional(),
|
|
6439
|
-
serviceTier: string2().min(1).max(100).nullable().optional()
|
|
6440
|
-
}).strict().refine((command) => command.longContext !== undefined || command.serviceTier !== undefined, { message: "At least one of longContext or serviceTier is required." });
|
|
6441
|
-
var PolicyAppliedSchema = object({
|
|
6442
|
-
longContext: boolean2(),
|
|
6443
|
-
serviceTier: string2().min(1).max(100).nullable(),
|
|
6444
|
-
contextWindow: number2().int().positive().safe().optional()
|
|
6445
|
-
}).strict();
|
|
6446
|
-
var PolicyAvailabilitySchema = object({
|
|
6447
|
-
longContext: boolean2(),
|
|
6448
|
-
serviceTier: boolean2()
|
|
6449
|
-
}).strict();
|
|
6450
|
-
var PolicyStateSchema = object({
|
|
6451
|
-
version: literal(1),
|
|
6452
|
-
publisherId: string2().uuid(),
|
|
6453
|
-
revision: number2().int().positive().safe(),
|
|
6454
|
-
requestId: string2().min(1).max(1024).optional(),
|
|
6455
|
-
applied: PolicyAppliedSchema,
|
|
6456
|
-
available: PolicyAvailabilitySchema,
|
|
6457
|
-
reason: string2().max(500).optional()
|
|
6458
|
-
}).strict();
|
|
6459
|
-
var POLICY_UNAVAILABLE_REASON = "No Plexus context or service-tier policy is advertised for the active model.";
|
|
6460
|
-
var DEFAULT_SELECTION = Object.freeze({
|
|
6461
|
-
longContext: true,
|
|
6462
|
-
serviceTier: null
|
|
6463
|
-
});
|
|
6464
6964
|
function policyAvailability(advertisement) {
|
|
6465
6965
|
const context = advertisement?.context;
|
|
6466
6966
|
return {
|
|
@@ -6484,99 +6984,50 @@ function injectServiceTier(payload, tier) {
|
|
|
6484
6984
|
return payload;
|
|
6485
6985
|
return { ...payload, service_tier: tier };
|
|
6486
6986
|
}
|
|
6487
|
-
var
|
|
6488
|
-
|
|
6489
|
-
|
|
6490
|
-
}
|
|
6491
|
-
function
|
|
6492
|
-
return
|
|
6493
|
-
|
|
6494
|
-
|
|
6495
|
-
|
|
6496
|
-
})
|
|
6497
|
-
}
|
|
6498
|
-
|
|
6499
|
-
|
|
6500
|
-
|
|
6501
|
-
applied: Object.freeze({ ...state.applied }),
|
|
6502
|
-
available: Object.freeze({ ...state.available })
|
|
6503
|
-
});
|
|
6504
|
-
}
|
|
6505
|
-
function selectionStatesEqual(current, next) {
|
|
6506
|
-
const shape = (state) => JSON.stringify({
|
|
6507
|
-
applied: state.applied,
|
|
6508
|
-
available: state.available,
|
|
6509
|
-
reason: state.reason ?? null
|
|
6510
|
-
});
|
|
6511
|
-
return shape(current) === shape(next);
|
|
6512
|
-
}
|
|
6513
|
-
function validateSelection(model, advertisement, command) {
|
|
6514
|
-
if (model === undefined || advertisement === undefined || advertisement.context === undefined && advertisement.serviceTier === undefined) {
|
|
6515
|
-
return POLICY_UNAVAILABLE_REASON;
|
|
6516
|
-
}
|
|
6517
|
-
if (command.longContext !== undefined) {
|
|
6518
|
-
const context = advertisement.context;
|
|
6519
|
-
if (context === undefined)
|
|
6520
|
-
return "No context budget is advertised for the active model.";
|
|
6521
|
-
if (context.shortContextBudgetTokens >= context.maxContextTokens) {
|
|
6522
|
-
return "The active model has no distinct short and maximum context budget.";
|
|
6523
|
-
}
|
|
6524
|
-
}
|
|
6525
|
-
if (command.serviceTier !== undefined && command.serviceTier !== null) {
|
|
6526
|
-
const tiers = advertisement.serviceTier?.serviceTiers;
|
|
6527
|
-
if (!tiers?.includes(command.serviceTier)) {
|
|
6528
|
-
return "The requested service tier is not advertised for the active model.";
|
|
6529
|
-
}
|
|
6530
|
-
}
|
|
6531
|
-
return;
|
|
6532
|
-
}
|
|
6987
|
+
var TERMINAL_RESOLVER = () => ({
|
|
6988
|
+
longContext: true,
|
|
6989
|
+
serviceTier: null
|
|
6990
|
+
});
|
|
6991
|
+
function sameModel(a, b) {
|
|
6992
|
+
return a !== undefined && b !== undefined && a.provider === b.provider && a.id === b.id;
|
|
6993
|
+
}
|
|
6994
|
+
var EMPTY_VIEW = Object.freeze({
|
|
6995
|
+
model: undefined,
|
|
6996
|
+
selection: Object.freeze({ longContext: false, serviceTier: null }),
|
|
6997
|
+
available: Object.freeze({ longContext: false, serviceTier: false }),
|
|
6998
|
+
contextWindow: undefined,
|
|
6999
|
+
applyFailed: false
|
|
7000
|
+
});
|
|
6533
7001
|
|
|
6534
7002
|
class PolicyController {
|
|
6535
7003
|
host;
|
|
6536
|
-
|
|
6537
|
-
|
|
6538
|
-
|
|
6539
|
-
boundModel;
|
|
6540
|
-
available = {
|
|
6541
|
-
longContext: false,
|
|
6542
|
-
serviceTier: false
|
|
6543
|
-
};
|
|
6544
|
-
contextWindow;
|
|
6545
|
-
reason;
|
|
6546
|
-
state;
|
|
6547
|
-
emit;
|
|
6548
|
-
unsubscribe;
|
|
7004
|
+
resolver;
|
|
7005
|
+
view = EMPTY_VIEW;
|
|
7006
|
+
listeners = new Set;
|
|
6549
7007
|
chain = Promise.resolve();
|
|
6550
|
-
constructor(
|
|
7008
|
+
constructor(host) {
|
|
6551
7009
|
this.host = host;
|
|
6552
|
-
this.emit = events.emit.bind(events);
|
|
6553
|
-
this.state = freezePublished({
|
|
6554
|
-
version: 1,
|
|
6555
|
-
publisherId: this.publisherId,
|
|
6556
|
-
revision: 1,
|
|
6557
|
-
applied: { longContext: true, serviceTier: null },
|
|
6558
|
-
available: { longContext: false, serviceTier: false }
|
|
6559
|
-
});
|
|
6560
|
-
this.unsubscribe = events.on(POLICY_SET_CHANNEL, (data) => this.enqueue(() => this.handleSet(data)));
|
|
6561
7010
|
}
|
|
6562
|
-
|
|
6563
|
-
return this.
|
|
7011
|
+
getView() {
|
|
7012
|
+
return this.view;
|
|
7013
|
+
}
|
|
7014
|
+
setResolver(resolver) {
|
|
7015
|
+
this.resolver = resolver;
|
|
7016
|
+
}
|
|
7017
|
+
subscribe(listener) {
|
|
7018
|
+
this.listeners.add(listener);
|
|
7019
|
+
return () => {
|
|
7020
|
+
this.listeners.delete(listener);
|
|
7021
|
+
};
|
|
6564
7022
|
}
|
|
6565
7023
|
serviceTierFor(model) {
|
|
6566
|
-
if (!model || !this.
|
|
6567
|
-
return null;
|
|
6568
|
-
if (this.boundModel.provider !== model.provider || this.boundModel.id !== model.id)
|
|
7024
|
+
if (!model || !sameModel(this.view.model, model))
|
|
6569
7025
|
return null;
|
|
6570
|
-
|
|
6571
|
-
return null;
|
|
6572
|
-
return this.selection.serviceTier;
|
|
7026
|
+
return this.view.selection.serviceTier;
|
|
6573
7027
|
}
|
|
6574
7028
|
reconcile() {
|
|
6575
7029
|
return this.enqueue(() => this.recompute());
|
|
6576
7030
|
}
|
|
6577
|
-
dispose() {
|
|
6578
|
-
this.unsubscribe();
|
|
6579
|
-
}
|
|
6580
7031
|
enqueue(task) {
|
|
6581
7032
|
const run = this.chain.then(task, task).catch(() => {
|
|
6582
7033
|
return;
|
|
@@ -6586,84 +7037,41 @@ class PolicyController {
|
|
|
6586
7037
|
}
|
|
6587
7038
|
async recompute() {
|
|
6588
7039
|
const model = this.host.getActiveModel();
|
|
6589
|
-
|
|
6590
|
-
|
|
6591
|
-
selection: { ...DEFAULT_SELECTION },
|
|
6592
|
-
boundModel: undefined,
|
|
6593
|
-
available: { longContext: false, serviceTier: false },
|
|
6594
|
-
contextWindow: undefined,
|
|
6595
|
-
reason: POLICY_UNAVAILABLE_REASON
|
|
6596
|
-
});
|
|
6597
|
-
return;
|
|
6598
|
-
}
|
|
6599
|
-
const advertisement = this.host.getAdvertisement(model);
|
|
6600
|
-
const sameModel = this.boundModel?.provider === model.provider && this.boundModel.id === model.id;
|
|
6601
|
-
let selection = sameModel ? { ...this.selection } : { ...DEFAULT_SELECTION };
|
|
6602
|
-
let reason;
|
|
7040
|
+
const advertisement = model === undefined ? undefined : this.host.getAdvertisement(model);
|
|
7041
|
+
const intent = (this.resolver ?? TERMINAL_RESOLVER)(model, advertisement);
|
|
6603
7042
|
const available = policyAvailability(advertisement);
|
|
6604
|
-
|
|
6605
|
-
|
|
6606
|
-
|
|
6607
|
-
|
|
6608
|
-
|
|
6609
|
-
}
|
|
6610
|
-
|
|
6611
|
-
|
|
6612
|
-
|
|
6613
|
-
|
|
6614
|
-
|
|
6615
|
-
|
|
6616
|
-
|
|
6617
|
-
|
|
7043
|
+
const tiers = advertisement?.serviceTier?.serviceTiers ?? [];
|
|
7044
|
+
const same = sameModel(this.view.model, model);
|
|
7045
|
+
let selection = {
|
|
7046
|
+
longContext: intent.longContext && available.longContext,
|
|
7047
|
+
serviceTier: intent.serviceTier !== null && tiers.includes(intent.serviceTier) ? intent.serviceTier : null
|
|
7048
|
+
};
|
|
7049
|
+
let contextWindow;
|
|
7050
|
+
let applyFailed = false;
|
|
7051
|
+
if (model !== undefined) {
|
|
7052
|
+
const applied = await this.applyContext(model, effectiveContextWindow(advertisement, selection));
|
|
7053
|
+
if (advertisement?.context !== undefined) {
|
|
7054
|
+
if (applied === undefined) {
|
|
7055
|
+
applyFailed = true;
|
|
7056
|
+
selection = {
|
|
7057
|
+
...selection,
|
|
7058
|
+
longContext: same ? this.view.selection.longContext : false
|
|
7059
|
+
};
|
|
7060
|
+
contextWindow = same ? this.view.contextWindow : undefined;
|
|
7061
|
+
} else {
|
|
7062
|
+
contextWindow = applied;
|
|
7063
|
+
}
|
|
6618
7064
|
}
|
|
6619
7065
|
}
|
|
6620
|
-
|
|
6621
|
-
|
|
6622
|
-
|
|
6623
|
-
|
|
6624
|
-
|
|
6625
|
-
|
|
6626
|
-
reason = "The session context window could not be updated.";
|
|
6627
|
-
}
|
|
6628
|
-
this.commit({
|
|
6629
|
-
selection,
|
|
6630
|
-
boundModel: model,
|
|
6631
|
-
available,
|
|
6632
|
-
contextWindow: advertisement?.context !== undefined ? appliedWindow : undefined,
|
|
6633
|
-
reason
|
|
7066
|
+
this.view = Object.freeze({
|
|
7067
|
+
model,
|
|
7068
|
+
selection: Object.freeze(selection),
|
|
7069
|
+
available: Object.freeze(available),
|
|
7070
|
+
contextWindow,
|
|
7071
|
+
applyFailed
|
|
6634
7072
|
});
|
|
6635
|
-
|
|
6636
|
-
|
|
6637
|
-
const parsed = PolicySetSchema.safeParse(data);
|
|
6638
|
-
if (!parsed.success)
|
|
6639
|
-
return;
|
|
6640
|
-
const command = parsed.data;
|
|
6641
|
-
const model = this.host.getActiveModel();
|
|
6642
|
-
const advertisement = model === undefined ? undefined : this.host.getAdvertisement(model);
|
|
6643
|
-
const sameModel = model !== undefined && this.boundModel?.provider === model.provider && this.boundModel.id === model.id;
|
|
6644
|
-
const current = sameModel ? { ...this.selection } : { ...DEFAULT_SELECTION };
|
|
6645
|
-
const nextSelection = {
|
|
6646
|
-
longContext: command.longContext ?? current.longContext,
|
|
6647
|
-
serviceTier: command.serviceTier === undefined ? current.serviceTier : command.serviceTier
|
|
6648
|
-
};
|
|
6649
|
-
const rejection = validateSelection(model, advertisement, command);
|
|
6650
|
-
if (rejection !== undefined) {
|
|
6651
|
-
this.emitReply(command.requestId, rejection);
|
|
6652
|
-
return;
|
|
6653
|
-
}
|
|
6654
|
-
const desired = effectiveContextWindow(advertisement, nextSelection);
|
|
6655
|
-
const appliedWindow = model === undefined ? undefined : await this.applyContext(model, desired);
|
|
6656
|
-
if (advertisement?.context !== undefined && appliedWindow === undefined) {
|
|
6657
|
-
this.emitReply(command.requestId, "The session context window could not be updated.");
|
|
6658
|
-
return;
|
|
6659
|
-
}
|
|
6660
|
-
this.commit({
|
|
6661
|
-
selection: nextSelection,
|
|
6662
|
-
boundModel: model,
|
|
6663
|
-
available: policyAvailability(advertisement),
|
|
6664
|
-
contextWindow: advertisement?.context !== undefined ? appliedWindow : undefined,
|
|
6665
|
-
reason: undefined
|
|
6666
|
-
}, command.requestId);
|
|
7073
|
+
for (const listener of [...this.listeners])
|
|
7074
|
+
listener();
|
|
6667
7075
|
}
|
|
6668
7076
|
async applyContext(model, contextWindow) {
|
|
6669
7077
|
try {
|
|
@@ -6672,342 +7080,21 @@ class PolicyController {
|
|
|
6672
7080
|
return;
|
|
6673
7081
|
}
|
|
6674
7082
|
}
|
|
6675
|
-
commit(next, requestId) {
|
|
6676
|
-
this.selection = next.selection;
|
|
6677
|
-
this.boundModel = next.boundModel;
|
|
6678
|
-
this.available = next.available;
|
|
6679
|
-
this.contextWindow = next.contextWindow;
|
|
6680
|
-
this.reason = next.reason;
|
|
6681
|
-
const candidate = {
|
|
6682
|
-
applied: {
|
|
6683
|
-
longContext: next.selection.longContext,
|
|
6684
|
-
serviceTier: next.selection.serviceTier,
|
|
6685
|
-
...next.contextWindow === undefined ? {} : { contextWindow: next.contextWindow }
|
|
6686
|
-
},
|
|
6687
|
-
available: { ...next.available },
|
|
6688
|
-
...next.reason === undefined ? {} : { reason: next.reason }
|
|
6689
|
-
};
|
|
6690
|
-
const changed = !selectionStatesEqual(this.state, candidate);
|
|
6691
|
-
if (changed) {
|
|
6692
|
-
this.revision++;
|
|
6693
|
-
this.state = freezePublished({
|
|
6694
|
-
version: 1,
|
|
6695
|
-
publisherId: this.publisherId,
|
|
6696
|
-
revision: this.revision,
|
|
6697
|
-
...candidate
|
|
6698
|
-
});
|
|
6699
|
-
this.emitState(this.state);
|
|
6700
|
-
}
|
|
6701
|
-
if (requestId !== undefined) {
|
|
6702
|
-
this.emitState(this.state, requestId);
|
|
6703
|
-
}
|
|
6704
|
-
}
|
|
6705
|
-
emitReply(requestId, reason) {
|
|
6706
|
-
const parsed = PolicyStateSchema.safeParse({
|
|
6707
|
-
...this.state,
|
|
6708
|
-
...reason === undefined ? {} : { reason },
|
|
6709
|
-
requestId
|
|
6710
|
-
});
|
|
6711
|
-
if (parsed.success && byteLength2(parsed.data) <= MAX_STATE_BYTES2) {
|
|
6712
|
-
this.emit(POLICY_STATE_CHANNEL, freezeParsed2(parsed.data));
|
|
6713
|
-
}
|
|
6714
|
-
}
|
|
6715
|
-
emitState(state, requestId) {
|
|
6716
|
-
const candidate = requestId === undefined ? state : { ...state, requestId };
|
|
6717
|
-
const parsed = PolicyStateSchema.safeParse(candidate);
|
|
6718
|
-
if (parsed.success && byteLength2(parsed.data) <= MAX_STATE_BYTES2) {
|
|
6719
|
-
this.emit(POLICY_STATE_CHANNEL, freezeParsed2(parsed.data));
|
|
6720
|
-
return;
|
|
6721
|
-
}
|
|
6722
|
-
const fallback = PolicyStateSchema.safeParse({
|
|
6723
|
-
version: 1,
|
|
6724
|
-
publisherId: this.publisherId,
|
|
6725
|
-
revision: this.revision,
|
|
6726
|
-
...requestId === undefined ? {} : { requestId },
|
|
6727
|
-
applied: { longContext: true, serviceTier: null },
|
|
6728
|
-
available: { longContext: false, serviceTier: false },
|
|
6729
|
-
reason: "Plexus policy state is unavailable."
|
|
6730
|
-
});
|
|
6731
|
-
if (fallback.success)
|
|
6732
|
-
this.emit(POLICY_STATE_CHANNEL, freezeParsed2(fallback.data));
|
|
6733
|
-
}
|
|
6734
7083
|
}
|
|
6735
7084
|
|
|
6736
7085
|
// src/service-tiers.ts
|
|
6737
|
-
import { randomUUID as randomUUID4 } from "crypto";
|
|
6738
|
-
var SERVICE_TIERS_REQUEST_CHANNEL = "plexus:service-tiers:request:v1";
|
|
6739
|
-
var SERVICE_TIERS_SNAPSHOT_CHANNEL = "plexus:service-tiers:snapshot:v1";
|
|
6740
7086
|
var ServiceTierPolicySchema = object({
|
|
6741
7087
|
provider: string2().min(1),
|
|
6742
7088
|
modelId: string2().min(1),
|
|
6743
7089
|
serviceTiers: array(string2().min(1).max(100)).min(1).max(64)
|
|
6744
7090
|
}).strict().refine((policy) => new Set(policy.serviceTiers).size === policy.serviceTiers.length);
|
|
6745
|
-
var ServiceTiersRequestSchema = object({
|
|
6746
|
-
version: literal(1),
|
|
6747
|
-
requestId: string2().min(1).max(1024)
|
|
6748
|
-
}).strict();
|
|
6749
|
-
var ServiceTiersSnapshotSchema = object({
|
|
6750
|
-
version: literal(1),
|
|
6751
|
-
publisherId: string2().uuid(),
|
|
6752
|
-
revision: number2().int().positive().safe(),
|
|
6753
|
-
requestId: string2().min(1).max(1024).optional(),
|
|
6754
|
-
status: _enum(["ready", "loading", "unavailable"]),
|
|
6755
|
-
policies: array(ServiceTierPolicySchema),
|
|
6756
|
-
fetchedAt: number2().int().nonnegative().safe().optional(),
|
|
6757
|
-
cached: boolean2().optional(),
|
|
6758
|
-
reason: string2().max(500).optional()
|
|
6759
|
-
}).strict().superRefine((snapshot, ctx) => {
|
|
6760
|
-
const pairs = new Set;
|
|
6761
|
-
for (const policy of snapshot.policies) {
|
|
6762
|
-
const pair = `${policy.provider}\x00${policy.modelId}`;
|
|
6763
|
-
if (pairs.has(pair))
|
|
6764
|
-
ctx.addIssue({
|
|
6765
|
-
code: "custom",
|
|
6766
|
-
message: "Duplicate provider/modelId service-tier policy"
|
|
6767
|
-
});
|
|
6768
|
-
pairs.add(pair);
|
|
6769
|
-
}
|
|
6770
|
-
if (snapshot.status !== "ready" && snapshot.policies.length !== 0) {
|
|
6771
|
-
ctx.addIssue({
|
|
6772
|
-
code: "custom",
|
|
6773
|
-
message: "Non-ready snapshots must have no policies"
|
|
6774
|
-
});
|
|
6775
|
-
}
|
|
6776
|
-
});
|
|
6777
|
-
var MAX_SNAPSHOT_BYTES2 = 1024 * 1024;
|
|
6778
|
-
var SERVICE_TIERS_METADATA_UNAVAILABLE_REASON = "Service-tier metadata is not available from the committed Plexus catalog.";
|
|
6779
|
-
|
|
6780
|
-
class ServiceTiersPublisher {
|
|
6781
|
-
publisherId = randomUUID4();
|
|
6782
|
-
revision = 1;
|
|
6783
|
-
state = Object.freeze({
|
|
6784
|
-
version: 1,
|
|
6785
|
-
publisherId: this.publisherId,
|
|
6786
|
-
revision: 1,
|
|
6787
|
-
status: "loading",
|
|
6788
|
-
policies: Object.freeze([])
|
|
6789
|
-
});
|
|
6790
|
-
emit;
|
|
6791
|
-
unsubscribe;
|
|
6792
|
-
constructor(events) {
|
|
6793
|
-
this.emit = events.emit.bind(events);
|
|
6794
|
-
this.unsubscribe = events.on(SERVICE_TIERS_REQUEST_CHANNEL, (data) => {
|
|
6795
|
-
const request = ServiceTiersRequestSchema.safeParse(data);
|
|
6796
|
-
if (request.success)
|
|
6797
|
-
this.send(request.data.requestId);
|
|
6798
|
-
});
|
|
6799
|
-
}
|
|
6800
|
-
getSnapshot() {
|
|
6801
|
-
return this.state;
|
|
6802
|
-
}
|
|
6803
|
-
setCatalog(status, policies, metadata) {
|
|
6804
|
-
const candidate = ServiceTiersSnapshotSchema.safeParse({
|
|
6805
|
-
version: 1,
|
|
6806
|
-
publisherId: this.publisherId,
|
|
6807
|
-
revision: this.revision,
|
|
6808
|
-
status,
|
|
6809
|
-
policies: [...policies],
|
|
6810
|
-
...metadata
|
|
6811
|
-
});
|
|
6812
|
-
const oversized = candidate.success && new TextEncoder().encode(JSON.stringify(candidate.data)).byteLength > MAX_SNAPSHOT_BYTES2;
|
|
6813
|
-
let next = candidate.success && !oversized ? candidate.data : {
|
|
6814
|
-
version: 1,
|
|
6815
|
-
publisherId: this.publisherId,
|
|
6816
|
-
revision: this.revision,
|
|
6817
|
-
status: "unavailable",
|
|
6818
|
-
policies: [],
|
|
6819
|
-
reason: oversized ? "Service-tier snapshot exceeds the 1 MiB publication limit." : "Service-tier snapshot could not be validated."
|
|
6820
|
-
};
|
|
6821
|
-
if (status !== "ready" && policies.length > 0) {
|
|
6822
|
-
next = {
|
|
6823
|
-
...next,
|
|
6824
|
-
status: "unavailable",
|
|
6825
|
-
policies: [],
|
|
6826
|
-
reason: "Service-tier metadata is unavailable."
|
|
6827
|
-
};
|
|
6828
|
-
}
|
|
6829
|
-
const { revision: _revision, ...stateWithoutRevision } = this.state;
|
|
6830
|
-
const { revision: _candidateRevision, ...nextWithoutRevision } = next;
|
|
6831
|
-
if (JSON.stringify(stateWithoutRevision) === JSON.stringify(nextWithoutRevision))
|
|
6832
|
-
return false;
|
|
6833
|
-
this.revision++;
|
|
6834
|
-
this.state = Object.freeze({
|
|
6835
|
-
...next,
|
|
6836
|
-
revision: this.revision,
|
|
6837
|
-
policies: Object.freeze(next.policies.map((policy) => Object.freeze({
|
|
6838
|
-
...policy,
|
|
6839
|
-
serviceTiers: Object.freeze([...policy.serviceTiers])
|
|
6840
|
-
})))
|
|
6841
|
-
});
|
|
6842
|
-
this.send();
|
|
6843
|
-
return true;
|
|
6844
|
-
}
|
|
6845
|
-
send(requestId) {
|
|
6846
|
-
const snapshot = {
|
|
6847
|
-
...this.state,
|
|
6848
|
-
...requestId === undefined ? {} : { requestId }
|
|
6849
|
-
};
|
|
6850
|
-
let valid = ServiceTiersSnapshotSchema.safeParse(snapshot);
|
|
6851
|
-
if (!valid.success || new TextEncoder().encode(JSON.stringify(snapshot)).byteLength > MAX_SNAPSHOT_BYTES2) {
|
|
6852
|
-
valid = ServiceTiersSnapshotSchema.safeParse({
|
|
6853
|
-
version: 1,
|
|
6854
|
-
publisherId: this.publisherId,
|
|
6855
|
-
revision: this.revision,
|
|
6856
|
-
status: "unavailable",
|
|
6857
|
-
policies: [],
|
|
6858
|
-
reason: "Service-tier snapshot exceeds publication limits or is invalid.",
|
|
6859
|
-
...requestId === undefined ? {} : { requestId }
|
|
6860
|
-
});
|
|
6861
|
-
}
|
|
6862
|
-
if (valid.success) {
|
|
6863
|
-
const immutable = Object.freeze({
|
|
6864
|
-
...valid.data,
|
|
6865
|
-
policies: Object.freeze(valid.data.policies.map((policy) => Object.freeze({
|
|
6866
|
-
...policy,
|
|
6867
|
-
serviceTiers: Object.freeze([...policy.serviceTiers])
|
|
6868
|
-
})))
|
|
6869
|
-
});
|
|
6870
|
-
this.emit(SERVICE_TIERS_SNAPSHOT_CHANNEL, immutable);
|
|
6871
|
-
}
|
|
6872
|
-
}
|
|
6873
|
-
dispose() {
|
|
6874
|
-
this.unsubscribe();
|
|
6875
|
-
}
|
|
6876
|
-
}
|
|
6877
7091
|
|
|
6878
7092
|
// src/short-names.ts
|
|
6879
|
-
import { randomUUID as randomUUID5 } from "crypto";
|
|
6880
|
-
var SHORT_NAMES_REQUEST_CHANNEL = "plexus:short-names:request:v1";
|
|
6881
|
-
var SHORT_NAMES_SNAPSHOT_CHANNEL = "plexus:short-names:snapshot:v1";
|
|
6882
7093
|
var ShortNameEntrySchema = object({
|
|
6883
7094
|
provider: string2().min(1),
|
|
6884
7095
|
modelId: string2().min(1),
|
|
6885
7096
|
shortName: string2().min(1).max(200)
|
|
6886
7097
|
}).strict();
|
|
6887
|
-
var ShortNamesRequestSchema = object({
|
|
6888
|
-
version: literal(1),
|
|
6889
|
-
requestId: string2().min(1).max(1024)
|
|
6890
|
-
}).strict();
|
|
6891
|
-
var ShortNamesSnapshotSchema = object({
|
|
6892
|
-
version: literal(1),
|
|
6893
|
-
publisherId: string2().uuid(),
|
|
6894
|
-
revision: number2().int().positive().safe(),
|
|
6895
|
-
requestId: string2().min(1).max(1024).optional(),
|
|
6896
|
-
status: _enum(["ready", "loading", "unavailable"]),
|
|
6897
|
-
names: array(ShortNameEntrySchema),
|
|
6898
|
-
fetchedAt: number2().int().nonnegative().safe().optional(),
|
|
6899
|
-
cached: boolean2().optional(),
|
|
6900
|
-
reason: string2().max(500).optional()
|
|
6901
|
-
}).strict().superRefine((snapshot, ctx) => {
|
|
6902
|
-
const pairs = new Set;
|
|
6903
|
-
for (const entry of snapshot.names) {
|
|
6904
|
-
const pair = `${entry.provider}\x00${entry.modelId}`;
|
|
6905
|
-
if (pairs.has(pair))
|
|
6906
|
-
ctx.addIssue({
|
|
6907
|
-
code: "custom",
|
|
6908
|
-
message: "Duplicate provider/modelId short-name entry"
|
|
6909
|
-
});
|
|
6910
|
-
pairs.add(pair);
|
|
6911
|
-
}
|
|
6912
|
-
if (snapshot.status !== "ready" && snapshot.names.length !== 0) {
|
|
6913
|
-
ctx.addIssue({
|
|
6914
|
-
code: "custom",
|
|
6915
|
-
message: "Non-ready snapshots must have no names"
|
|
6916
|
-
});
|
|
6917
|
-
}
|
|
6918
|
-
});
|
|
6919
|
-
var MAX_SNAPSHOT_BYTES3 = 1024 * 1024;
|
|
6920
|
-
class ShortNamesPublisher {
|
|
6921
|
-
publisherId = randomUUID5();
|
|
6922
|
-
revision = 1;
|
|
6923
|
-
state = Object.freeze({
|
|
6924
|
-
version: 1,
|
|
6925
|
-
publisherId: this.publisherId,
|
|
6926
|
-
revision: 1,
|
|
6927
|
-
status: "loading",
|
|
6928
|
-
names: Object.freeze([])
|
|
6929
|
-
});
|
|
6930
|
-
emit;
|
|
6931
|
-
unsubscribe;
|
|
6932
|
-
constructor(events) {
|
|
6933
|
-
this.emit = events.emit.bind(events);
|
|
6934
|
-
this.unsubscribe = events.on(SHORT_NAMES_REQUEST_CHANNEL, (data) => {
|
|
6935
|
-
const request = ShortNamesRequestSchema.safeParse(data);
|
|
6936
|
-
if (request.success)
|
|
6937
|
-
this.send(request.data.requestId);
|
|
6938
|
-
});
|
|
6939
|
-
}
|
|
6940
|
-
getSnapshot() {
|
|
6941
|
-
return this.state;
|
|
6942
|
-
}
|
|
6943
|
-
setCatalog(status, names, metadata) {
|
|
6944
|
-
const candidate = ShortNamesSnapshotSchema.safeParse({
|
|
6945
|
-
version: 1,
|
|
6946
|
-
publisherId: this.publisherId,
|
|
6947
|
-
revision: this.revision,
|
|
6948
|
-
status,
|
|
6949
|
-
names: [...names],
|
|
6950
|
-
...metadata
|
|
6951
|
-
});
|
|
6952
|
-
const oversized = candidate.success && new TextEncoder().encode(JSON.stringify(candidate.data)).byteLength > MAX_SNAPSHOT_BYTES3;
|
|
6953
|
-
let next = candidate.success && !oversized ? candidate.data : {
|
|
6954
|
-
version: 1,
|
|
6955
|
-
publisherId: this.publisherId,
|
|
6956
|
-
revision: this.revision,
|
|
6957
|
-
status: "unavailable",
|
|
6958
|
-
names: [],
|
|
6959
|
-
reason: oversized ? "Short-name snapshot exceeds the 1 MiB publication limit." : "Short-name snapshot could not be validated."
|
|
6960
|
-
};
|
|
6961
|
-
if (status !== "ready" && names.length > 0) {
|
|
6962
|
-
next = {
|
|
6963
|
-
...next,
|
|
6964
|
-
status: "unavailable",
|
|
6965
|
-
names: [],
|
|
6966
|
-
reason: "Short-name metadata is unavailable."
|
|
6967
|
-
};
|
|
6968
|
-
}
|
|
6969
|
-
const { revision: _revision, ...stateWithoutRevision } = this.state;
|
|
6970
|
-
const { revision: _candidateRevision, ...nextWithoutRevision } = next;
|
|
6971
|
-
if (JSON.stringify(stateWithoutRevision) === JSON.stringify(nextWithoutRevision))
|
|
6972
|
-
return false;
|
|
6973
|
-
this.revision++;
|
|
6974
|
-
this.state = Object.freeze({
|
|
6975
|
-
...next,
|
|
6976
|
-
revision: this.revision,
|
|
6977
|
-
names: Object.freeze(next.names.map((entry) => Object.freeze({ ...entry })))
|
|
6978
|
-
});
|
|
6979
|
-
this.send();
|
|
6980
|
-
return true;
|
|
6981
|
-
}
|
|
6982
|
-
send(requestId) {
|
|
6983
|
-
const snapshot = {
|
|
6984
|
-
...this.state,
|
|
6985
|
-
...requestId === undefined ? {} : { requestId }
|
|
6986
|
-
};
|
|
6987
|
-
let valid = ShortNamesSnapshotSchema.safeParse(snapshot);
|
|
6988
|
-
if (!valid.success || new TextEncoder().encode(JSON.stringify(snapshot)).byteLength > MAX_SNAPSHOT_BYTES3) {
|
|
6989
|
-
valid = ShortNamesSnapshotSchema.safeParse({
|
|
6990
|
-
version: 1,
|
|
6991
|
-
publisherId: this.publisherId,
|
|
6992
|
-
revision: this.revision,
|
|
6993
|
-
status: "unavailable",
|
|
6994
|
-
names: [],
|
|
6995
|
-
reason: "Short-name snapshot exceeds publication limits or is invalid.",
|
|
6996
|
-
...requestId === undefined ? {} : { requestId }
|
|
6997
|
-
});
|
|
6998
|
-
}
|
|
6999
|
-
if (valid.success) {
|
|
7000
|
-
const immutable = Object.freeze({
|
|
7001
|
-
...valid.data,
|
|
7002
|
-
names: Object.freeze(valid.data.names.map((entry) => Object.freeze({ ...entry })))
|
|
7003
|
-
});
|
|
7004
|
-
this.emit(SHORT_NAMES_SNAPSHOT_CHANNEL, immutable);
|
|
7005
|
-
}
|
|
7006
|
-
}
|
|
7007
|
-
dispose() {
|
|
7008
|
-
this.unsubscribe();
|
|
7009
|
-
}
|
|
7010
|
-
}
|
|
7011
7098
|
|
|
7012
7099
|
// src/extension.ts
|
|
7013
7100
|
var PROVIDER_NAME = "plexus";
|
|
@@ -7176,7 +7263,7 @@ function getSessionThinkingLevel(pi) {
|
|
|
7176
7263
|
return;
|
|
7177
7264
|
}
|
|
7178
7265
|
}
|
|
7179
|
-
function withAuthoritativeApiKeyEnv(provider,
|
|
7266
|
+
function withAuthoritativeApiKeyEnv(provider, setting, getHeaderModels = () => []) {
|
|
7180
7267
|
const apiKey = provider.auth.apiKey;
|
|
7181
7268
|
if (!apiKey)
|
|
7182
7269
|
return provider;
|
|
@@ -7200,18 +7287,19 @@ function withAuthoritativeApiKeyEnv(provider, envName, getHeaderModels = () => [
|
|
|
7200
7287
|
apiKey: {
|
|
7201
7288
|
...apiKey,
|
|
7202
7289
|
resolve: async (input) => {
|
|
7203
|
-
const
|
|
7204
|
-
|
|
7290
|
+
const envValue = await input.ctx.env(setting.name);
|
|
7291
|
+
const envKey = resolveApiKeyEnvValue(setting, envValue);
|
|
7292
|
+
if (envKey === undefined)
|
|
7205
7293
|
return apiKey.resolve(input);
|
|
7206
7294
|
const result = await apiKey.resolve({
|
|
7207
7295
|
...input,
|
|
7208
7296
|
credential: {
|
|
7209
7297
|
type: "api_key",
|
|
7210
|
-
key:
|
|
7298
|
+
key: envKey,
|
|
7211
7299
|
...input.credential?.env ? { env: input.credential.env } : {}
|
|
7212
7300
|
}
|
|
7213
7301
|
});
|
|
7214
|
-
return result ? { ...result, source: `${
|
|
7302
|
+
return result ? { ...result, source: `${setting.name} (apiKeyEnv)` } : result;
|
|
7215
7303
|
}
|
|
7216
7304
|
}
|
|
7217
7305
|
},
|
|
@@ -7240,8 +7328,11 @@ function createPolicyHost(deps) {
|
|
|
7240
7328
|
...serviceTier ? { serviceTier } : {}
|
|
7241
7329
|
};
|
|
7242
7330
|
},
|
|
7243
|
-
|
|
7244
|
-
return deps.
|
|
7331
|
+
getCatalogContextWindow(model) {
|
|
7332
|
+
return deps.getRegistry()?.find(model.provider, model.id)?.contextWindow;
|
|
7333
|
+
},
|
|
7334
|
+
hasCatalogContextPolicy() {
|
|
7335
|
+
return deps.getModels().some((entry) => entry.plexusContextPolicy !== undefined);
|
|
7245
7336
|
},
|
|
7246
7337
|
async applyContextWindow(model, contextWindow) {
|
|
7247
7338
|
const registry = deps.getRegistry();
|
|
@@ -7264,21 +7355,14 @@ function createPolicyHost(deps) {
|
|
|
7264
7355
|
};
|
|
7265
7356
|
}
|
|
7266
7357
|
function plexusExtension(pi) {
|
|
7267
|
-
const contextPolicies = new ContextPolicyPublisher(pi.events);
|
|
7268
|
-
const serviceTiers = new ServiceTiersPublisher(pi.events);
|
|
7269
|
-
const shortNames = new ShortNamesPublisher(pi.events);
|
|
7270
7358
|
const state = {
|
|
7271
7359
|
models: [],
|
|
7272
7360
|
catalogSource: "none",
|
|
7273
|
-
refreshSequence: 0,
|
|
7274
|
-
contextPolicies,
|
|
7275
|
-
serviceTiers,
|
|
7276
|
-
shortNames,
|
|
7277
7361
|
policy: undefined,
|
|
7278
7362
|
activeModel: undefined,
|
|
7279
7363
|
registry: undefined
|
|
7280
7364
|
};
|
|
7281
|
-
const
|
|
7365
|
+
const host = createPolicyHost({
|
|
7282
7366
|
getActiveModel: () => state.activeModel,
|
|
7283
7367
|
getModels: () => state.models,
|
|
7284
7368
|
getRegistry: () => state.registry,
|
|
@@ -7286,68 +7370,23 @@ function plexusExtension(pi) {
|
|
|
7286
7370
|
setActiveModel: (model) => {
|
|
7287
7371
|
state.activeModel = model;
|
|
7288
7372
|
}
|
|
7289
|
-
}));
|
|
7290
|
-
state.policy = policy;
|
|
7291
|
-
const modelsControl = new ModelsControl(pi.events, {
|
|
7292
|
-
refresh: async () => {
|
|
7293
|
-
const registry = state.registry;
|
|
7294
|
-
if (!registry) {
|
|
7295
|
-
const message = "Plexus model registry is unavailable before the session starts.";
|
|
7296
|
-
log("models:refresh unavailable", { reason: message });
|
|
7297
|
-
throw new Error(message);
|
|
7298
|
-
}
|
|
7299
|
-
const result = await registry.refresh({
|
|
7300
|
-
providers: [PROVIDER_NAME],
|
|
7301
|
-
force: true
|
|
7302
|
-
});
|
|
7303
|
-
if (result.aborted) {
|
|
7304
|
-
log("models:refresh aborted", {});
|
|
7305
|
-
throw new Error("Plexus model refresh was cancelled.");
|
|
7306
|
-
}
|
|
7307
|
-
const refreshError = result.errors.get(PROVIDER_NAME);
|
|
7308
|
-
if (refreshError)
|
|
7309
|
-
throw refreshError;
|
|
7310
|
-
return { modelCount: state.models.length };
|
|
7311
|
-
}
|
|
7312
7373
|
});
|
|
7374
|
+
const policy = new PolicyController(host);
|
|
7375
|
+
state.policy = policy;
|
|
7376
|
+
createPlexuspiControl(pi, { policy, host });
|
|
7313
7377
|
pi.on("session_shutdown", () => {
|
|
7314
|
-
contextPolicies.dispose();
|
|
7315
|
-
serviceTiers.dispose();
|
|
7316
|
-
shortNames.dispose();
|
|
7317
|
-
policy.dispose();
|
|
7318
|
-
modelsControl.dispose();
|
|
7319
|
-
if (state.contextPolicies === contextPolicies)
|
|
7320
|
-
state.contextPolicies = undefined;
|
|
7321
|
-
if (state.serviceTiers === serviceTiers)
|
|
7322
|
-
state.serviceTiers = undefined;
|
|
7323
|
-
if (state.shortNames === shortNames)
|
|
7324
|
-
state.shortNames = undefined;
|
|
7325
7378
|
if (state.policy === policy)
|
|
7326
7379
|
state.policy = undefined;
|
|
7327
7380
|
});
|
|
7328
|
-
const
|
|
7329
|
-
const
|
|
7330
|
-
const
|
|
7331
|
-
const envApiKey = explicitApiKey ?? getEnvApiKey();
|
|
7381
|
+
const apiKeySetting = getApiKeyEnvSetting();
|
|
7382
|
+
const apiKeyEnvName = apiKeySetting.name;
|
|
7383
|
+
const envApiKey = resolveApiKeyEnvValue(apiKeySetting, process.env[apiKeyEnvName]);
|
|
7332
7384
|
const startupBaseUrl = getBaseUrl();
|
|
7333
7385
|
const suppressPatterns = getSuppressedModels();
|
|
7334
7386
|
const storedCatalog = readStoredModelsSync();
|
|
7335
7387
|
const startupModels = (storedCatalog?.models ?? []).filter((model) => !isModelSuppressed({ id: model.id, name: model.name }, suppressPatterns));
|
|
7336
7388
|
state.models = startupModels;
|
|
7337
7389
|
state.catalogSource = startupModels.length > 0 ? "host store" : "none";
|
|
7338
|
-
const startupPolicies = collectStoredContextPolicies(startupModels);
|
|
7339
|
-
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 });
|
|
7340
|
-
if (storedCatalog) {
|
|
7341
|
-
const cachedTiers = collectStoredServiceTiers(startupModels);
|
|
7342
|
-
serviceTiers.setCatalog(cachedTiers.complete ? "ready" : "unavailable", cachedTiers.policies, cachedTiers.complete ? {
|
|
7343
|
-
cached: true,
|
|
7344
|
-
...cachedTiers.fetchedAt === undefined ? {} : { fetchedAt: cachedTiers.fetchedAt }
|
|
7345
|
-
} : { cached: true, reason: SERVICE_TIERS_METADATA_UNAVAILABLE_REASON });
|
|
7346
|
-
shortNames.setCatalog("ready", collectStoredShortNames(startupModels), {
|
|
7347
|
-
cached: true,
|
|
7348
|
-
...storedCatalog.checkedAt ? { fetchedAt: storedCatalog.checkedAt } : {}
|
|
7349
|
-
});
|
|
7350
|
-
}
|
|
7351
7390
|
policy.reconcile();
|
|
7352
7391
|
pi.on("session_start", (_event, ctx) => {
|
|
7353
7392
|
state.registry = ctx.modelRegistry;
|
|
@@ -7383,20 +7422,17 @@ function plexusExtension(pi) {
|
|
|
7383
7422
|
refreshModels: (context) => refreshPlexusModels(state, context),
|
|
7384
7423
|
oauth: createPlexusLoginProvider()
|
|
7385
7424
|
});
|
|
7386
|
-
if (
|
|
7425
|
+
if (envApiKey !== undefined) {
|
|
7387
7426
|
let authOverrideApplied = false;
|
|
7388
7427
|
pi.on("session_start", (_event, ctx) => {
|
|
7389
7428
|
if (authOverrideApplied)
|
|
7390
7429
|
return;
|
|
7391
7430
|
const composed = ctx.modelRegistry.getProvider(PROVIDER_NAME);
|
|
7392
7431
|
if (!composed?.auth.apiKey) {
|
|
7393
|
-
throw new Error("Plexus
|
|
7432
|
+
throw new Error("Plexus API-key auth is unavailable");
|
|
7394
7433
|
}
|
|
7395
|
-
pi.registerProvider(withAuthoritativeApiKeyEnv(composed,
|
|
7434
|
+
pi.registerProvider(withAuthoritativeApiKeyEnv(composed, apiKeySetting, () => state.models));
|
|
7396
7435
|
authOverrideApplied = true;
|
|
7397
|
-
log("auth: applied authoritative apiKeyEnv override", {
|
|
7398
|
-
apiKeyEnv: apiKeyEnvName
|
|
7399
|
-
});
|
|
7400
7436
|
});
|
|
7401
7437
|
}
|
|
7402
7438
|
pi.registerCommand("plexus", {
|
|
@@ -7427,10 +7463,10 @@ function plexusExtension(pi) {
|
|
|
7427
7463
|
});
|
|
7428
7464
|
}
|
|
7429
7465
|
async function refreshPlexusModels(state, context) {
|
|
7430
|
-
const refreshId = ++state.refreshSequence;
|
|
7431
7466
|
const baseUrl = getBaseUrl();
|
|
7432
7467
|
const modelsUrl = getModelsUrl();
|
|
7433
|
-
const
|
|
7468
|
+
const setting = getApiKeyEnvSetting();
|
|
7469
|
+
const apiKey = resolvePlexusApiKey(setting, process.env[setting.name], credentialApiKey(context.credential));
|
|
7434
7470
|
const suppress = getSuppressedModels();
|
|
7435
7471
|
if (!context.allowNetwork || !apiKey || !modelsUrl || !baseUrl) {
|
|
7436
7472
|
if (state.models.length > 0) {
|
|
@@ -7442,20 +7478,6 @@ async function refreshPlexusModels(state, context) {
|
|
|
7442
7478
|
},
|
|
7443
7479
|
update: () => {
|
|
7444
7480
|
state.models = filteredCurrent;
|
|
7445
|
-
const cachedTiers = collectStoredServiceTiers(filteredCurrent);
|
|
7446
|
-
state.serviceTiers?.setCatalog(cachedTiers.complete ? "ready" : "unavailable", cachedTiers.policies, cachedTiers.complete ? {
|
|
7447
|
-
cached: true,
|
|
7448
|
-
...cachedTiers.fetchedAt === undefined ? {} : { fetchedAt: cachedTiers.fetchedAt }
|
|
7449
|
-
} : {
|
|
7450
|
-
cached: true,
|
|
7451
|
-
reason: SERVICE_TIERS_METADATA_UNAVAILABLE_REASON
|
|
7452
|
-
});
|
|
7453
|
-
const cachedPolicies = collectStoredContextPolicies(filteredCurrent);
|
|
7454
|
-
state.contextPolicies?.setCatalog(cachedPolicies.length > 0 ? "ready" : "unavailable", cachedPolicies.map((entry) => entry.policy), cachedPolicies.length > 0 ? { cached: true, fetchedAt: cachedPolicies[0]?.fetchedAt } : {
|
|
7455
|
-
cached: true,
|
|
7456
|
-
reason: CONTEXT_POLICY_METADATA_UNAVAILABLE_REASON
|
|
7457
|
-
});
|
|
7458
|
-
state.shortNames?.setCatalog("ready", collectStoredShortNames(filteredCurrent), { cached: true });
|
|
7459
7481
|
state.policy?.reconcile();
|
|
7460
7482
|
}
|
|
7461
7483
|
});
|
|
@@ -7464,16 +7486,8 @@ async function refreshPlexusModels(state, context) {
|
|
|
7464
7486
|
const restored = await restoreStoredModels(state, context);
|
|
7465
7487
|
if (restored)
|
|
7466
7488
|
return restored;
|
|
7467
|
-
if (
|
|
7468
|
-
|
|
7469
|
-
reason: "Plexus model metadata is not configured."
|
|
7470
|
-
});
|
|
7471
|
-
}
|
|
7472
|
-
if (refreshId === state.refreshSequence && state.shortNames?.getSnapshot().status === "loading") {
|
|
7473
|
-
state.shortNames.setCatalog("unavailable", [], {
|
|
7474
|
-
reason: "Plexus model metadata is not configured."
|
|
7475
|
-
});
|
|
7476
|
-
}
|
|
7489
|
+
if (!context.allowNetwork)
|
|
7490
|
+
return [];
|
|
7477
7491
|
throw new Error(!modelsUrl || !baseUrl ? "Plexus base URL not configured. Run /login plexus first." : "No Plexus API key configured. Run /login plexus first.");
|
|
7478
7492
|
}
|
|
7479
7493
|
try {
|
|
@@ -7501,9 +7515,6 @@ async function refreshPlexusModels(state, context) {
|
|
|
7501
7515
|
else
|
|
7502
7516
|
delete piModel.plexusShortName;
|
|
7503
7517
|
}
|
|
7504
|
-
const committedPolicies = collectStoredContextPolicies(piModels);
|
|
7505
|
-
const committedServiceTiers = collectStoredServiceTiers(piModels).policies;
|
|
7506
|
-
const committedShortNames = collectStoredShortNames(piModels);
|
|
7507
7518
|
const published = await context.publish({
|
|
7508
7519
|
persist: {
|
|
7509
7520
|
models: piModels,
|
|
@@ -7512,13 +7523,6 @@ async function refreshPlexusModels(state, context) {
|
|
|
7512
7523
|
update: () => {
|
|
7513
7524
|
state.models = piModels;
|
|
7514
7525
|
state.catalogSource = "live refresh";
|
|
7515
|
-
state.serviceTiers?.setCatalog("ready", committedServiceTiers, {
|
|
7516
|
-
fetchedAt
|
|
7517
|
-
});
|
|
7518
|
-
state.shortNames?.setCatalog("ready", committedShortNames, {
|
|
7519
|
-
fetchedAt
|
|
7520
|
-
});
|
|
7521
|
-
state.contextPolicies?.setCatalog(committedPolicies.length > 0 ? "ready" : "unavailable", committedPolicies.map((entry) => entry.policy), committedPolicies.length > 0 ? { fetchedAt } : { fetchedAt, reason: CONTEXT_POLICY_METADATA_UNAVAILABLE_REASON });
|
|
7522
7526
|
state.policy?.reconcile();
|
|
7523
7527
|
}
|
|
7524
7528
|
});
|
|
@@ -7528,21 +7532,6 @@ async function refreshPlexusModels(state, context) {
|
|
|
7528
7532
|
log("refreshModels: fetched", { count: piModels.length });
|
|
7529
7533
|
return piModels;
|
|
7530
7534
|
} catch (error) {
|
|
7531
|
-
if (refreshId === state.refreshSequence && state.contextPolicies?.getSnapshot().status === "loading") {
|
|
7532
|
-
state.contextPolicies.setCatalog("unavailable", [], {
|
|
7533
|
-
reason: "Plexus model metadata could not be loaded."
|
|
7534
|
-
});
|
|
7535
|
-
}
|
|
7536
|
-
if (refreshId === state.refreshSequence && state.serviceTiers?.getSnapshot().status === "loading") {
|
|
7537
|
-
state.serviceTiers.setCatalog("unavailable", [], {
|
|
7538
|
-
reason: "Plexus model metadata could not be loaded."
|
|
7539
|
-
});
|
|
7540
|
-
}
|
|
7541
|
-
if (refreshId === state.refreshSequence && state.shortNames?.getSnapshot().status === "loading") {
|
|
7542
|
-
state.shortNames.setCatalog("unavailable", [], {
|
|
7543
|
-
reason: "Plexus model metadata could not be loaded."
|
|
7544
|
-
});
|
|
7545
|
-
}
|
|
7546
7535
|
log("refreshModels: fetch failed", { error: String(error) });
|
|
7547
7536
|
throw error;
|
|
7548
7537
|
}
|
|
@@ -7557,19 +7546,6 @@ async function restoreStoredModels(state, context) {
|
|
|
7557
7546
|
update: () => {
|
|
7558
7547
|
state.models = models;
|
|
7559
7548
|
state.catalogSource = "host store";
|
|
7560
|
-
const cachedTiers = collectStoredServiceTiers(models);
|
|
7561
|
-
state.serviceTiers?.setCatalog(cachedTiers.complete ? "ready" : "unavailable", cachedTiers.policies, cachedTiers.complete ? {
|
|
7562
|
-
cached: true,
|
|
7563
|
-
...cachedTiers.fetchedAt === undefined ? {} : { fetchedAt: cachedTiers.fetchedAt }
|
|
7564
|
-
} : { cached: true, reason: SERVICE_TIERS_METADATA_UNAVAILABLE_REASON });
|
|
7565
|
-
const cachedPolicies = collectStoredContextPolicies(models);
|
|
7566
|
-
state.contextPolicies?.setCatalog(cachedPolicies.length > 0 ? "ready" : "unavailable", cachedPolicies.map((entry) => entry.policy), cachedPolicies.length > 0 ? { cached: true, fetchedAt: cachedPolicies[0]?.fetchedAt } : {
|
|
7567
|
-
cached: true,
|
|
7568
|
-
reason: CONTEXT_POLICY_METADATA_UNAVAILABLE_REASON
|
|
7569
|
-
});
|
|
7570
|
-
state.shortNames?.setCatalog("ready", collectStoredShortNames(models), {
|
|
7571
|
-
cached: true
|
|
7572
|
-
});
|
|
7573
7549
|
state.policy?.reconcile();
|
|
7574
7550
|
}
|
|
7575
7551
|
});
|
|
@@ -7589,12 +7565,6 @@ function contextPolicyFromApiModel(model) {
|
|
|
7589
7565
|
pricingThresholdInputTokens
|
|
7590
7566
|
};
|
|
7591
7567
|
}
|
|
7592
|
-
function collectStoredContextPolicies(models) {
|
|
7593
|
-
return models.flatMap((model) => {
|
|
7594
|
-
const metadata = model.plexusContextPolicy;
|
|
7595
|
-
return metadata ? [metadata] : [];
|
|
7596
|
-
});
|
|
7597
|
-
}
|
|
7598
7568
|
function serviceTierPolicyFromApiModel(model) {
|
|
7599
7569
|
const serviceTiers = model.service_tiers;
|
|
7600
7570
|
if (!Array.isArray(serviceTiers) || serviceTiers.length === 0)
|
|
@@ -7618,29 +7588,6 @@ function shortNameEntryFromApiModel(model) {
|
|
|
7618
7588
|
});
|
|
7619
7589
|
return parsed.success ? parsed.data : undefined;
|
|
7620
7590
|
}
|
|
7621
|
-
function collectStoredShortNames(models) {
|
|
7622
|
-
return models.flatMap((model) => {
|
|
7623
|
-
const shortName = model.plexusShortName;
|
|
7624
|
-
if (typeof shortName !== "string" || !shortName.trim())
|
|
7625
|
-
return [];
|
|
7626
|
-
const parsed = ShortNameEntrySchema.safeParse({
|
|
7627
|
-
provider: PROVIDER_NAME,
|
|
7628
|
-
modelId: model.id,
|
|
7629
|
-
shortName: shortName.trim()
|
|
7630
|
-
});
|
|
7631
|
-
return parsed.success ? [parsed.data] : [];
|
|
7632
|
-
});
|
|
7633
|
-
}
|
|
7634
|
-
function collectStoredServiceTiers(models) {
|
|
7635
|
-
const metadata = models.map((model) => model.plexusServiceTiers);
|
|
7636
|
-
const complete = models.length === 0 || metadata.every((entry) => entry !== undefined);
|
|
7637
|
-
const stored = metadata.filter((entry) => entry !== undefined);
|
|
7638
|
-
return {
|
|
7639
|
-
policies: stored.flatMap((entry) => entry.policy ? [entry.policy] : []),
|
|
7640
|
-
complete,
|
|
7641
|
-
...stored[0] ? { fetchedAt: stored[0].fetchedAt } : {}
|
|
7642
|
-
};
|
|
7643
|
-
}
|
|
7644
7591
|
function credentialApiKey(credential) {
|
|
7645
7592
|
if (!credential)
|
|
7646
7593
|
return;
|
|
@@ -7674,8 +7621,9 @@ function createPlexusLoginProvider() {
|
|
|
7674
7621
|
return { ...credentials, expires: PLEXUS_CREDENTIAL_EXPIRES_AT };
|
|
7675
7622
|
},
|
|
7676
7623
|
getApiKey(credentials) {
|
|
7624
|
+
const setting = getApiKeyEnvSetting();
|
|
7677
7625
|
const stored = String(credentials.access || credentials.refresh || "");
|
|
7678
|
-
return
|
|
7626
|
+
return resolvePlexusApiKey(setting, process.env[setting.name], stored) ?? "";
|
|
7679
7627
|
},
|
|
7680
7628
|
modifyModels(models, credentials) {
|
|
7681
7629
|
const baseUrl = credentials.plexusBaseUrl;
|
|
@@ -7716,14 +7664,14 @@ async function handleRefresh(state, ctx) {
|
|
|
7716
7664
|
}
|
|
7717
7665
|
async function handleStatus(state, ctx) {
|
|
7718
7666
|
const baseUrl = getBaseUrlResolution();
|
|
7719
|
-
const apiKeyEnvName =
|
|
7667
|
+
const apiKeyEnvName = getApiKeyEnvSetting().name;
|
|
7720
7668
|
const apiKey = await ctx.modelRegistry.getApiKeyForProvider(PROVIDER_NAME).catch(() => {
|
|
7721
7669
|
return;
|
|
7722
7670
|
});
|
|
7723
|
-
const
|
|
7671
|
+
const effectiveApiKey = resolveApiKey(apiKey);
|
|
7724
7672
|
ctx.ui.notify([
|
|
7725
7673
|
`Plexus base URL: ${baseUrl.baseUrl ?? "not configured"} (${baseUrl.source})`,
|
|
7726
|
-
`API key: ${
|
|
7674
|
+
`API key: ${effectiveApiKey ? `${apiKeyEnvName} or host credential` : "not configured"}`,
|
|
7727
7675
|
`Catalog: ${state.models.length} models (${state.catalogSource})`,
|
|
7728
7676
|
"Default model: managed by Pi. Use /model and save the selection there."
|
|
7729
7677
|
].join(`
|