@mcowger/pi-plexus 1.13.1 → 1.14.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/extension.js CHANGED
@@ -94,6 +94,7 @@ function resolvePricingTiers(model) {
94
94
  function convertToDescriptor(raw, baseUrl) {
95
95
  const preferredApi = mapPreferredApi(raw.preferred_api);
96
96
  const adjustedBaseUrl = adjustBaseUrl(baseUrl, preferredApi);
97
+ const shortName = typeof raw.short_name === "string" ? raw.short_name.trim() : "";
97
98
  const contextWindow = resolveContextWindow(raw);
98
99
  const maxTokens = resolveMaxTokens(raw);
99
100
  const tiers = resolvePricingTiers(raw);
@@ -115,6 +116,8 @@ function convertToDescriptor(raw, baseUrl) {
115
116
  contextWindow,
116
117
  maxTokens
117
118
  };
119
+ if (shortName)
120
+ descriptor.shortName = shortName;
118
121
  if (raw.pi_provider)
119
122
  descriptor.piProvider = raw.pi_provider;
120
123
  if (raw.pi_model)
@@ -555,8 +558,148 @@ function getSuppressedModels() {
555
558
  return [...envSuppressed, ...configSuppressed];
556
559
  }
557
560
 
558
- // src/context-policy.ts
559
- import { randomUUID } from "crypto";
561
+ // src/log.ts
562
+ import { appendFile, mkdir as mkdir2 } from "fs/promises";
563
+ import { join as join3 } from "path";
564
+ import { getAgentDir as getAgentDir3 } from "@earendil-works/pi-coding-agent";
565
+ var getCacheDir = () => join3(getAgentDir3(), "extensions", "plexus");
566
+ var getLogPath = () => join3(getCacheDir(), "plexus.log");
567
+ var dirEnsured = false;
568
+ function log(message, data) {
569
+ writeLogLine(message, data);
570
+ }
571
+ async function writeLogLine(message, data) {
572
+ try {
573
+ if (!dirEnsured) {
574
+ await mkdir2(getCacheDir(), { recursive: true });
575
+ dirEnsured = true;
576
+ }
577
+ const ts = new Date().toISOString();
578
+ const line = data !== undefined ? `${ts} ${message} ${JSON.stringify(data)}
579
+ ` : `${ts} ${message}
580
+ `;
581
+ await appendFile(getLogPath(), line, "utf8");
582
+ } catch {}
583
+ }
584
+
585
+ // src/gemini-malformed-retry.ts
586
+ var MALFORMED_LEAK_PATTERN = /(?:print\()?call:\s*default_api[.:]|default_api\.\w+\s*\(/;
587
+ var MALFORMED_DIAGNOSTIC_PATTERN = /\bmalformed[\s_-]?function[\s_-]?call\b/i;
588
+ var TRUNCATED_JSON_PATTERN = /\bUnexpected end of JSON input\b/i;
589
+ var PROVIDER_CONNECTION_CLOSED_PATTERN = /\bprovider connection closed\b/i;
590
+ var NORMALIZED_PREFIX = "MALFORMED_FUNCTION_CALL:";
591
+ var TRUNCATED_JSON_PREFIX = "TRUNCATED_JSON_RESPONSE:";
592
+ var PROVIDER_CONNECTION_CLOSED_PREFIX = "PROVIDER_CONNECTION_CLOSED:";
593
+ 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.`;
594
+ 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.`;
595
+ 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.`;
596
+ function hasLeakedFunctionCall(content) {
597
+ if (!Array.isArray(content))
598
+ return false;
599
+ for (const block of content) {
600
+ if (block?.type === "text" && typeof block.text === "string" && MALFORMED_LEAK_PATTERN.test(block.text)) {
601
+ return true;
602
+ }
603
+ }
604
+ return false;
605
+ }
606
+ function hasToolCall(content) {
607
+ return Array.isArray(content) && content.some((block) => block?.type === "toolCall");
608
+ }
609
+ function normalizeMalformedFunctionCall(message, providerName) {
610
+ if (message?.role !== "assistant" || message.provider !== providerName || message.stopReason !== "error") {
611
+ return;
612
+ }
613
+ if (typeof message.errorMessage === "string" && (message.errorMessage.startsWith(NORMALIZED_PREFIX) || message.errorMessage.startsWith(TRUNCATED_JSON_PREFIX) || message.errorMessage.startsWith(PROVIDER_CONNECTION_CLOSED_PREFIX))) {
614
+ return;
615
+ }
616
+ if (hasToolCall(message.content))
617
+ return;
618
+ if (typeof message.errorMessage === "string" && TRUNCATED_JSON_PATTERN.test(message.errorMessage)) {
619
+ log("retryable-error: retagged truncated JSON response for retry", {
620
+ model: message.model
621
+ });
622
+ return { message: { ...message, errorMessage: TRUNCATED_JSON_MESSAGE } };
623
+ }
624
+ if (typeof message.errorMessage === "string" && PROVIDER_CONNECTION_CLOSED_PATTERN.test(message.errorMessage)) {
625
+ log("retryable-error: retagged closed provider connection for retry", {
626
+ model: message.model
627
+ });
628
+ return {
629
+ message: { ...message, errorMessage: PROVIDER_CONNECTION_CLOSED_MESSAGE }
630
+ };
631
+ }
632
+ const via = hasLeakedFunctionCall(message.content) ? "leak" : typeof message.errorMessage === "string" && MALFORMED_DIAGNOSTIC_PATTERN.test(message.errorMessage) ? "diagnostic" : undefined;
633
+ if (!via)
634
+ return;
635
+ log("gemini-malformed-retry: retagged MALFORMED_FUNCTION_CALL for retry", {
636
+ model: message.model,
637
+ via
638
+ });
639
+ return { message: { ...message, errorMessage: NORMALIZED_MESSAGE } };
640
+ }
641
+
642
+ // src/mapper.ts
643
+ import {
644
+ getModel
645
+ } from "@earendil-works/pi-ai/compat";
646
+ var MINIMUM_OUTPUT_TOKENS = 8192;
647
+ function descriptorToPiModel(descriptor) {
648
+ let builtinModel;
649
+ if (descriptor.piProvider && descriptor.piModel) {
650
+ try {
651
+ builtinModel = getModel(descriptor.piProvider, descriptor.piModel);
652
+ } catch {
653
+ builtinModel = undefined;
654
+ }
655
+ }
656
+ const cost = {
657
+ input: descriptor.cost.input * 1e6,
658
+ output: descriptor.cost.output * 1e6,
659
+ cacheRead: descriptor.cost.cacheRead * 1e6,
660
+ cacheWrite: descriptor.cost.cacheWrite * 1e6,
661
+ ...descriptor.cost.tiers ? {
662
+ tiers: descriptor.cost.tiers.map((tier) => ({
663
+ inputTokensAbove: tier.inputTokensAbove,
664
+ input: tier.input * 1e6,
665
+ output: tier.output * 1e6,
666
+ cacheRead: tier.cacheRead * 1e6,
667
+ cacheWrite: tier.cacheWrite * 1e6
668
+ }))
669
+ } : {}
670
+ };
671
+ let compat;
672
+ if (descriptor.preferredApi === "openai-completions") {
673
+ const heuristic = detectOpenAICompletionsCompat(descriptor.piProvider ?? descriptor.provider, descriptor.baseUrl);
674
+ const builtinCompat = builtinModel?.compat;
675
+ const merged = {
676
+ ...heuristic,
677
+ ...builtinCompat ?? {},
678
+ ...descriptor.piOptions ?? {}
679
+ };
680
+ compat = merged;
681
+ } else if (descriptor.piOptions) {
682
+ compat = descriptor.piOptions;
683
+ } else if (builtinModel?.compat) {
684
+ compat = builtinModel.compat;
685
+ }
686
+ return {
687
+ id: descriptor.id,
688
+ name: descriptor.name,
689
+ ...descriptor.shortName !== undefined ? { plexusShortName: descriptor.shortName } : {},
690
+ api: descriptor.preferredApi,
691
+ provider: descriptor.provider,
692
+ baseUrl: descriptor.baseUrl,
693
+ reasoning: descriptor.reasoning,
694
+ input: descriptor.input,
695
+ cost,
696
+ contextWindow: descriptor.contextWindow,
697
+ maxTokens: Math.max(descriptor.maxTokens, MINIMUM_OUTPUT_TOKENS),
698
+ ...builtinModel?.thinkingLevelMap !== undefined ? { thinkingLevelMap: builtinModel.thinkingLevelMap } : {},
699
+ ...builtinModel?.headers !== undefined ? { headers: builtinModel.headers } : {},
700
+ ...compat !== undefined ? { compat } : {}
701
+ };
702
+ }
560
703
 
561
704
  // ../../node_modules/.bun/zod@4.6.5/node_modules/zod/v4/core/util.js
562
705
  function getEnumValues(entries) {
@@ -5766,6 +5909,14 @@ function object(shape, params) {
5766
5909
  };
5767
5910
  return new ZodObject(def);
5768
5911
  }
5912
+ function strictObject(shape, params) {
5913
+ return new ZodObject({
5914
+ type: "object",
5915
+ shape,
5916
+ catchall: never(),
5917
+ ...normalizeParams(params)
5918
+ });
5919
+ }
5769
5920
  var ZodUnion = /* @__PURE__ */ $constructor("ZodUnion", (inst, def) => {
5770
5921
  $ZodUnion.init(inst, def);
5771
5922
  ZodType.init(inst, def);
@@ -6029,434 +6180,797 @@ function refine(fn, _params = {}) {
6029
6180
  function superRefine(fn, params) {
6030
6181
  return _superRefine(fn, params);
6031
6182
  }
6032
- // src/context-policy.ts
6033
- var CONTEXT_POLICY_REQUEST_CHANNEL = "plexus:context-policy:request:v1";
6034
- var CONTEXT_POLICY_SNAPSHOT_CHANNEL = "plexus:context-policy:snapshot:v1";
6035
- var ContextPolicySchema = object({
6036
- provider: string2().min(1),
6037
- modelId: string2().min(1),
6038
- maxContextTokens: number2().int().positive().safe(),
6039
- shortContextBudgetTokens: number2().int().positive().safe(),
6040
- pricingThresholdInputTokens: number2().int().positive().safe().optional()
6041
- }).refine((policy) => policy.shortContextBudgetTokens <= policy.maxContextTokens);
6042
- var ContextPolicyRequestSchema = object({ version: literal(1), requestId: string2().min(1).max(1024) }).strict();
6043
- var ContextPolicySnapshotSchema = object({
6044
- version: literal(1),
6045
- publisherId: string2().uuid(),
6046
- revision: number2().int().positive().safe(),
6047
- requestId: string2().min(1).max(1024).optional(),
6048
- status: _enum(["ready", "loading", "unavailable"]),
6049
- policies: array(ContextPolicySchema),
6050
- fetchedAt: number2().int().nonnegative().safe().optional(),
6051
- cached: boolean2().optional(),
6052
- reason: string2().max(500).optional()
6053
- }).strict().superRefine((snapshot, ctx) => {
6054
- const pairs = new Set;
6055
- for (const policy of snapshot.policies) {
6056
- const pair = `${policy.provider}\x00${policy.modelId}`;
6057
- if (pairs.has(pair))
6058
- ctx.addIssue({
6059
- code: "custom",
6060
- message: "Duplicate provider/modelId policy"
6061
- });
6062
- pairs.add(pair);
6183
+ // src/paseo-control/protocol.ts
6184
+ var PROTOCOL_VERSION = 1;
6185
+ var NOTIFY_PREFIX = "plexuspi:v1:";
6186
+ var STATE_NOTIFY_PREFIX = "plexuspi:state:v1:";
6187
+ var CHILD_NOTIFY_PREFIX = "plexuspi:child:v1:";
6188
+ var COMMAND_NAME = "plexuspi-control";
6189
+ var CUSTOM_ENTRY_TYPE = "plexuspi-controls";
6190
+ var REWIND_ENTRY_TYPE = "plexuspi-rewind";
6191
+ var SUBAGENT_BRIDGE_CHANNEL = "plexuspi:subagent:v1";
6192
+ var SUBAGENT_BRIDGE_VERSION = 1;
6193
+ var ROOT_SIGNAL_CHANNEL = "plexuspi:root:v1";
6194
+ var ROOT_SIGNAL_VERSION = 1;
6195
+ var SESSION_KEY_ENV = "PLEXUSPI_SESSION_KEY";
6196
+ var TierSchema = string2().min(1).max(100);
6197
+ var NO_TIER = "default";
6198
+ var SettingsSchema = strictObject({
6199
+ tier: TierSchema,
6200
+ longContext: boolean2()
6201
+ });
6202
+ var OperationSchema = _enum([
6203
+ "hello",
6204
+ "get-state",
6205
+ "configure",
6206
+ "rewind",
6207
+ "reload"
6208
+ ]);
6209
+ var ConfigureDataSchema = strictObject({
6210
+ tier: TierSchema.optional(),
6211
+ longContext: boolean2().optional()
6212
+ });
6213
+ var RewindDataSchema = strictObject({
6214
+ targetEntryId: string2().min(1)
6215
+ });
6216
+ var RewindResultSchema = strictObject({
6217
+ cancelled: boolean2(),
6218
+ targetEntryId: string2().min(1),
6219
+ leafId: string2().optional(),
6220
+ settings: SettingsSchema,
6221
+ activeChildren: number2().int().nonnegative()
6222
+ });
6223
+ var RewindEntrySchema = strictObject({
6224
+ version: literal(PROTOCOL_VERSION),
6225
+ targetEntryId: string2().min(1),
6226
+ leafId: string2().nullable().optional(),
6227
+ timestamp: number2().int().nonnegative()
6228
+ });
6229
+ var SubagentBridgeRecordSchema = strictObject({
6230
+ version: literal(SUBAGENT_BRIDGE_VERSION),
6231
+ runId: string2().min(1),
6232
+ sequence: number2().int().positive(),
6233
+ type: _enum(["created", "activity", "terminal"]),
6234
+ parentRunId: string2().optional(),
6235
+ parentSessionId: string2().optional(),
6236
+ childSessionId: string2().optional(),
6237
+ toolCallId: string2().optional(),
6238
+ title: string2().optional(),
6239
+ timestamp: number2().optional(),
6240
+ transcriptPath: string2().optional(),
6241
+ cwd: string2().optional(),
6242
+ record: unknown().optional(),
6243
+ outcome: _enum(["completed", "steered", "canceled", "failed"]).optional(),
6244
+ result: unknown().optional(),
6245
+ reason: string2().optional(),
6246
+ omitted: boolean2().optional(),
6247
+ omittedBytes: number2().int().nonnegative().optional()
6248
+ });
6249
+ var ChildForwardSchema = strictObject({
6250
+ version: literal(SUBAGENT_BRIDGE_VERSION),
6251
+ sessionKey: string2(),
6252
+ record: SubagentBridgeRecordSchema
6253
+ });
6254
+ var PlexuspiRequestSchema = object({
6255
+ version: literal(PROTOCOL_VERSION),
6256
+ sessionKey: string2().min(1),
6257
+ requestId: string2().min(1),
6258
+ operation: OperationSchema,
6259
+ data: unknown().optional()
6260
+ });
6261
+ var ConflictSchema = strictObject({
6262
+ owner: string2().min(1),
6263
+ command: string2().min(1),
6264
+ resolution: string2().min(1)
6265
+ });
6266
+ var PlexuspiStateSchema = strictObject({
6267
+ capabilities: array(string2()),
6268
+ settings: SettingsSchema,
6269
+ contextWindow: number2().int().nonnegative().optional(),
6270
+ activeChildren: number2().int().nonnegative().optional(),
6271
+ sessionId: string2().optional(),
6272
+ origin: literal("root"),
6273
+ tiers: array(TierSchema),
6274
+ longContextTarget: number2().int().nonnegative().optional(),
6275
+ longContextAvailable: boolean2().optional(),
6276
+ shortContextBudgetTokens: number2().int().positive().optional(),
6277
+ pricingThresholdInputTokens: number2().int().positive().optional(),
6278
+ contextPolicyError: string2().optional(),
6279
+ modelBaselineContextWindow: number2().int().nonnegative().optional(),
6280
+ tierApplicable: boolean2(),
6281
+ conflicts: array(ConflictSchema),
6282
+ limitations: array(string2())
6283
+ });
6284
+ var PlexuspiReplySchema = strictObject({
6285
+ version: literal(PROTOCOL_VERSION),
6286
+ sessionKey: string2(),
6287
+ requestId: string2(),
6288
+ operation: OperationSchema,
6289
+ ok: boolean2(),
6290
+ data: unknown().optional(),
6291
+ error: string2().optional()
6292
+ });
6293
+ var ControlEntrySchema = strictObject({
6294
+ version: literal(PROTOCOL_VERSION),
6295
+ tier: TierSchema,
6296
+ longContext: boolean2(),
6297
+ contextWindow: number2().int().nonnegative().optional(),
6298
+ timestamp: number2().int().nonnegative()
6299
+ });
6300
+ function formatIssues(error) {
6301
+ return error.issues.map((issue) => `${issue.path.length > 0 ? `${issue.path.join(".")}: ` : ""}${issue.message}`).join("; ");
6302
+ }
6303
+ function decodeBase64Url(value) {
6304
+ return Buffer.from(value, "base64url").toString("utf8");
6305
+ }
6306
+ function parseRequestArg(args) {
6307
+ const fail = (error) => ({
6308
+ ok: false,
6309
+ error,
6310
+ sessionKey: "",
6311
+ requestId: "",
6312
+ operation: "hello"
6313
+ });
6314
+ const trimmed = args.trim();
6315
+ if (!trimmed)
6316
+ return fail("missing base64url-encoded request");
6317
+ let json;
6318
+ try {
6319
+ json = decodeBase64Url(trimmed);
6320
+ } catch {
6321
+ return fail("invalid base64url request");
6063
6322
  }
6064
- if (snapshot.status !== "ready" && snapshot.policies.length !== 0) {
6065
- ctx.addIssue({
6066
- code: "custom",
6067
- message: "Non-ready snapshots must have no policies"
6068
- });
6323
+ if (json.trim().length === 0)
6324
+ return fail("empty request payload");
6325
+ let parsed;
6326
+ try {
6327
+ parsed = JSON.parse(json);
6328
+ } catch {
6329
+ return fail("request payload is not valid JSON");
6069
6330
  }
6070
- }).transform((snapshot) => snapshot);
6071
- var MAX_SNAPSHOT_BYTES = 1024 * 1024;
6072
- var SAFE_REASON = "Context policy limits are not available from the committed Plexus catalog metadata.";
6331
+ const result = PlexuspiRequestSchema.safeParse(parsed);
6332
+ if (result.success)
6333
+ return { ok: true, request: result.data };
6334
+ const loose = parsed ?? {};
6335
+ const operation = OperationSchema.safeParse(loose.operation);
6336
+ return {
6337
+ ok: false,
6338
+ error: `invalid request: ${formatIssues(result.error)}`,
6339
+ sessionKey: typeof loose.sessionKey === "string" ? loose.sessionKey : "",
6340
+ requestId: typeof loose.requestId === "string" ? loose.requestId : "",
6341
+ operation: operation.success ? operation.data : "hello"
6342
+ };
6343
+ }
6073
6344
 
6074
- class ContextPolicyPublisher {
6075
- publisherId = randomUUID();
6076
- revision = 1;
6077
- state = Object.freeze({
6078
- version: 1,
6079
- publisherId: this.publisherId,
6080
- revision: 1,
6081
- status: "loading",
6082
- policies: Object.freeze([])
6083
- });
6084
- emit;
6085
- unsubscribe;
6086
- constructor(events) {
6087
- this.emit = events.emit.bind(events);
6088
- this.unsubscribe = events.on(CONTEXT_POLICY_REQUEST_CHANNEL, (data) => {
6089
- const request = ContextPolicyRequestSchema.safeParse(data);
6090
- if (request.success)
6091
- this.send(request.data.requestId);
6092
- });
6093
- }
6094
- getSnapshot() {
6095
- return this.state;
6096
- }
6097
- setCatalog(status, policies, metadata) {
6098
- const candidate = ContextPolicySnapshotSchema.safeParse({
6099
- version: 1,
6100
- publisherId: this.publisherId,
6101
- revision: this.revision,
6102
- status,
6103
- policies: [...policies],
6104
- ...metadata
6105
- });
6106
- const oversized = candidate.success && new TextEncoder().encode(JSON.stringify(candidate.data)).byteLength > MAX_SNAPSHOT_BYTES;
6107
- const reason = candidate.success && !oversized ? undefined : "Context policy snapshot could not be validated.";
6108
- let next = candidate.success && !oversized ? candidate.data : {
6109
- version: 1,
6110
- publisherId: this.publisherId,
6111
- revision: this.revision,
6112
- status: "unavailable",
6113
- policies: [],
6114
- reason
6115
- };
6116
- if (oversized)
6117
- next = {
6118
- ...next,
6119
- status: "unavailable",
6120
- policies: [],
6121
- reason: "Context policy snapshot exceeds the 1 MiB publication limit."
6122
- };
6123
- if (status !== "ready" && policies.length > 0)
6124
- next = {
6125
- ...next,
6126
- status: "unavailable",
6127
- policies: [],
6128
- reason: "Context policy metadata is unavailable."
6129
- };
6130
- const { revision: _revision, ...stateWithoutRevision } = this.state;
6131
- const { revision: _candidateRevision, ...nextWithoutRevision } = next;
6132
- if (JSON.stringify(stateWithoutRevision) === JSON.stringify(nextWithoutRevision))
6133
- return false;
6134
- this.revision++;
6135
- this.state = Object.freeze({
6136
- ...next,
6137
- revision: this.revision,
6138
- policies: Object.freeze([...next.policies])
6139
- });
6140
- this.send();
6141
- return true;
6345
+ // src/paseo-control/bridge.ts
6346
+ function createSubagentBridgeTracker(sessionKey) {
6347
+ const runs = new Map;
6348
+ return {
6349
+ accept(record) {
6350
+ const existing = runs.get(record.runId);
6351
+ if (existing) {
6352
+ if (existing.terminal)
6353
+ return;
6354
+ if (record.sequence <= existing.sequence)
6355
+ return;
6356
+ existing.sequence = record.sequence;
6357
+ if (record.type === "terminal")
6358
+ existing.terminal = true;
6359
+ } else {
6360
+ if (record.type !== "created")
6361
+ return;
6362
+ runs.set(record.runId, { sequence: record.sequence, terminal: false });
6363
+ }
6364
+ return { version: SUBAGENT_BRIDGE_VERSION, sessionKey, record };
6365
+ },
6366
+ activeChildren() {
6367
+ let count = 0;
6368
+ for (const run of runs.values()) {
6369
+ if (!run.terminal)
6370
+ count += 1;
6371
+ }
6372
+ return count;
6373
+ }
6374
+ };
6375
+ }
6376
+ function formatChildForward(forward) {
6377
+ return `${CHILD_NOTIFY_PREFIX}${JSON.stringify(forward)}`;
6378
+ }
6379
+
6380
+ // src/paseo-control/conflicts.ts
6381
+ var KNOWN_CONTROL_OWNERS = [
6382
+ {
6383
+ owner: "pi-microgpt",
6384
+ commands: ["fast", "flex", "long-context"],
6385
+ resolution: "Disable pi-microgpt's /fast, /flex, and /long-context commands for this Plexus root so plexus-pi owns tier and context selection."
6142
6386
  }
6143
- send(requestId) {
6144
- const snapshot = {
6145
- ...this.state,
6146
- ...requestId === undefined ? {} : { requestId }
6147
- };
6148
- let valid = ContextPolicySnapshotSchema.safeParse(snapshot);
6149
- if (!valid.success || new TextEncoder().encode(JSON.stringify(snapshot)).byteLength > MAX_SNAPSHOT_BYTES) {
6150
- valid = ContextPolicySnapshotSchema.safeParse({
6151
- version: 1,
6152
- publisherId: this.publisherId,
6153
- revision: this.revision,
6154
- status: "unavailable",
6155
- policies: [],
6156
- reason: "Context policy snapshot exceeds publication limits or is invalid.",
6157
- ...requestId === undefined ? {} : { requestId }
6387
+ ];
6388
+ function detectControlConflicts(commands) {
6389
+ const declared = new Set(commands.filter((command) => command.source === undefined || command.source === "extension").map((command) => command.name));
6390
+ const conflicts = [];
6391
+ for (const known of KNOWN_CONTROL_OWNERS) {
6392
+ const matched = known.commands.filter((command) => declared.has(command));
6393
+ if (matched.length > 0) {
6394
+ conflicts.push({
6395
+ owner: known.owner,
6396
+ command: matched.join(", "),
6397
+ resolution: known.resolution
6158
6398
  });
6159
6399
  }
6160
- if (valid.success)
6161
- this.emit(CONTEXT_POLICY_SNAPSHOT_CHANNEL, Object.freeze(valid.data));
6162
- }
6163
- dispose() {
6164
- this.unsubscribe();
6165
6400
  }
6401
+ return conflicts;
6166
6402
  }
6167
- var CONTEXT_POLICY_METADATA_UNAVAILABLE_REASON = SAFE_REASON;
6168
6403
 
6169
- // src/log.ts
6170
- import { appendFile, mkdir as mkdir2 } from "fs/promises";
6171
- import { join as join3 } from "path";
6172
- import { getAgentDir as getAgentDir3 } from "@earendil-works/pi-coding-agent";
6173
- var getCacheDir = () => join3(getAgentDir3(), "extensions", "plexus");
6174
- var getLogPath = () => join3(getCacheDir(), "plexus.log");
6175
- var dirEnsured = false;
6176
- function log(message, data) {
6177
- writeLogLine(message, data);
6404
+ // src/paseo-control/rewind.ts
6405
+ function findActiveBranchUserEntry(branch, targetEntryId) {
6406
+ const entry = branch.find((candidate) => candidate.id === targetEntryId);
6407
+ if (!entry)
6408
+ return { ok: false, error: "rewind target is not on the active branch" };
6409
+ if (entry.type !== "message" || entry.message?.role !== "user") {
6410
+ return {
6411
+ ok: false,
6412
+ error: "rewind target must be an active-branch user message"
6413
+ };
6414
+ }
6415
+ return { ok: true, entry };
6178
6416
  }
6179
- async function writeLogLine(message, data) {
6180
- try {
6181
- if (!dirEnsured) {
6182
- await mkdir2(getCacheDir(), { recursive: true });
6183
- dirEnsured = true;
6184
- }
6185
- const ts = new Date().toISOString();
6186
- const line = data !== undefined ? `${ts} ${message} ${JSON.stringify(data)}
6187
- ` : `${ts} ${message}
6188
- `;
6189
- await appendFile(getLogPath(), line, "utf8");
6190
- } catch {}
6417
+ function buildRewindEntry(targetEntryId, leafId, timestamp) {
6418
+ return {
6419
+ version: PROTOCOL_VERSION,
6420
+ targetEntryId,
6421
+ ...leafId !== null ? { leafId } : {},
6422
+ timestamp
6423
+ };
6424
+ }
6425
+ function navigationCancelled(result) {
6426
+ return Boolean(result && typeof result === "object" && result.cancelled === true);
6191
6427
  }
6192
6428
 
6193
- // src/gemini-malformed-retry.ts
6194
- var MALFORMED_LEAK_PATTERN = /(?:print\()?call:\s*default_api[.:]|default_api\.\w+\s*\(/;
6195
- var MALFORMED_DIAGNOSTIC_PATTERN = /\bmalformed[\s_-]?function[\s_-]?call\b/i;
6196
- var TRUNCATED_JSON_PATTERN = /\bUnexpected end of JSON input\b/i;
6197
- var PROVIDER_CONNECTION_CLOSED_PATTERN = /\bprovider connection closed\b/i;
6198
- var NORMALIZED_PREFIX = "MALFORMED_FUNCTION_CALL:";
6199
- var TRUNCATED_JSON_PREFIX = "TRUNCATED_JSON_RESPONSE:";
6200
- var PROVIDER_CONNECTION_CLOSED_PREFIX = "PROVIDER_CONNECTION_CLOSED:";
6201
- var NORMALIZED_MESSAGE = `${NORMALIZED_PREFIX} Gemini emitted a malformed tool call (its internal ` + `function-call syntax leaked as text). This is a transient model failure \u2014 ` + `please retry your request.`;
6202
- var TRUNCATED_JSON_MESSAGE = `${TRUNCATED_JSON_PREFIX} Unexpected end of JSON input. The upstream provider ` + `returned a truncated JSON response. This is a transient provider failure \u2014 ` + `please retry your request.`;
6203
- var PROVIDER_CONNECTION_CLOSED_MESSAGE = `${PROVIDER_CONNECTION_CLOSED_PREFIX} Provider connection closed. The upstream provider ` + `dropped the request. This is a transient provider failure \u2014 please retry your request.`;
6204
- function hasLeakedFunctionCall(content) {
6205
- if (!Array.isArray(content))
6206
- return false;
6207
- for (const block of content) {
6208
- if (block?.type === "text" && typeof block.text === "string" && MALFORMED_LEAK_PATTERN.test(block.text)) {
6209
- return true;
6210
- }
6211
- }
6212
- return false;
6429
+ // src/paseo-control/tier.ts
6430
+ function resolveSavedTier(tier, choices) {
6431
+ if (choices.includes(tier))
6432
+ return tier;
6433
+ const migrated = tier === "fast" ? "priority" : tier === "default" ? "auto" : tier;
6434
+ if (choices.includes(migrated))
6435
+ return migrated;
6436
+ if (choices.includes("auto"))
6437
+ return "auto";
6438
+ if (choices.includes("standard"))
6439
+ return "standard";
6440
+ return NO_TIER;
6441
+ }
6442
+ function isTierApplicable(model, tier, policy) {
6443
+ return model?.provider === "plexus" && policy?.provider === model.provider && policy.modelId === model.id && policy.serviceTiers.includes(tier);
6213
6444
  }
6214
- function hasToolCall(content) {
6215
- return Array.isArray(content) && content.some((block) => block?.type === "toolCall");
6445
+
6446
+ // src/paseo-control/control.ts
6447
+ var CAPABILITIES = [
6448
+ "hello",
6449
+ "get-state",
6450
+ "configure",
6451
+ "rewind",
6452
+ "reload"
6453
+ ];
6454
+ var LIMITATIONS = [
6455
+ "rewind restores Pi's active branch and appends a branch pin; it never writes files and never summarizes the abandoned future",
6456
+ "rewind is rejected while the root agent is busy, while a compaction is in progress, or while owned children are active",
6457
+ "the provider must clear its own queued input before asking the module to navigate",
6458
+ "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",
6459
+ "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",
6460
+ "host history replacement after rewind is the provider's supported-adapter concern, not a module-invented reset event",
6461
+ "active owned children are counted from the pi-subagents bridge; children not bridged are not visible",
6462
+ "advertised service tiers describe Plexus capabilities, not a routing or backend acceptance guarantee",
6463
+ "context budgets come from Plexus policy metadata; models without distinct short/max budgets have no long-context control"
6464
+ ];
6465
+ var APPLY_ERROR = "Pi could not apply the context policy budget.";
6466
+ function normalizeKey(value) {
6467
+ if (typeof value !== "string")
6468
+ return;
6469
+ const trimmed = value.trim();
6470
+ return trimmed.length > 0 ? trimmed : undefined;
6216
6471
  }
6217
- function normalizeMalformedFunctionCall(message, providerName) {
6218
- if (message?.role !== "assistant" || message.provider !== providerName || message.stopReason !== "error") {
6472
+ function readSessionId(ctx) {
6473
+ try {
6474
+ const id = ctx.sessionManager.getSessionId();
6475
+ return typeof id === "string" && id.length > 0 ? id : undefined;
6476
+ } catch {
6219
6477
  return;
6220
6478
  }
6221
- if (typeof message.errorMessage === "string" && (message.errorMessage.startsWith(NORMALIZED_PREFIX) || message.errorMessage.startsWith(TRUNCATED_JSON_PREFIX) || message.errorMessage.startsWith(PROVIDER_CONNECTION_CLOSED_PREFIX))) {
6479
+ }
6480
+ function readLeafId(ctx) {
6481
+ try {
6482
+ const id = ctx.sessionManager.getLeafId();
6483
+ return typeof id === "string" && id.length > 0 ? id : undefined;
6484
+ } catch {
6222
6485
  return;
6223
6486
  }
6224
- if (hasToolCall(message.content))
6225
- return;
6226
- if (typeof message.errorMessage === "string" && TRUNCATED_JSON_PATTERN.test(message.errorMessage)) {
6227
- log("retryable-error: retagged truncated JSON response for retry", {
6228
- model: message.model
6229
- });
6230
- return { message: { ...message, errorMessage: TRUNCATED_JSON_MESSAGE } };
6487
+ }
6488
+ function readBranch(ctx) {
6489
+ try {
6490
+ return ctx.sessionManager.getBranch();
6491
+ } catch {
6492
+ return [];
6231
6493
  }
6232
- if (typeof message.errorMessage === "string" && PROVIDER_CONNECTION_CLOSED_PATTERN.test(message.errorMessage)) {
6233
- log("retryable-error: retagged closed provider connection for retry", {
6234
- model: message.model
6235
- });
6494
+ }
6495
+ function createPlexuspiControl(pi, deps, options = {}) {
6496
+ const { policy, host } = deps;
6497
+ const now = options.now ?? (() => Date.now());
6498
+ const expectedSessionKey = normalizeKey(options.sessionKey ?? process.env[SESSION_KEY_ENV]);
6499
+ const bridgeTracker = createSubagentBridgeTracker(expectedSessionKey ?? "");
6500
+ let active = false;
6501
+ let closed = false;
6502
+ let latestCtx;
6503
+ let compactionActive = false;
6504
+ let desiredTier = NO_TIER;
6505
+ let desiredLongContext = false;
6506
+ let resolvedTier = NO_TIER;
6507
+ let suspendPersist = false;
6508
+ let persistedKey = "";
6509
+ let unsubscribeBridge;
6510
+ let unsubscribeView;
6511
+ const resolveIntent = (_model, advertisement) => {
6512
+ const choices = advertisement?.serviceTier?.serviceTiers ?? [];
6513
+ resolvedTier = resolveSavedTier(desiredTier, choices);
6514
+ if (choices.includes(desiredTier) || desiredTier === "fast" && resolvedTier === "priority" || desiredTier === NO_TIER && (resolvedTier === "auto" || resolvedTier === "standard")) {
6515
+ desiredTier = resolvedTier;
6516
+ }
6517
+ const context = advertisement?.context;
6518
+ const distinct = context !== undefined && context.shortContextBudgetTokens < context.maxContextTokens;
6519
+ if (!distinct && host.hasCatalogContextPolicy())
6520
+ desiredLongContext = false;
6521
+ return { longContext: desiredLongContext, serviceTier: resolvedTier };
6522
+ };
6523
+ function reportedSettings() {
6236
6524
  return {
6237
- message: { ...message, errorMessage: PROVIDER_CONNECTION_CLOSED_MESSAGE }
6525
+ tier: resolvedTier,
6526
+ longContext: policy.getView().selection.longContext
6238
6527
  };
6239
6528
  }
6240
- const via = hasLeakedFunctionCall(message.content) ? "leak" : typeof message.errorMessage === "string" && MALFORMED_DIAGNOSTIC_PATTERN.test(message.errorMessage) ? "diagnostic" : undefined;
6241
- if (!via)
6242
- return;
6243
- log("gemini-malformed-retry: retagged MALFORMED_FUNCTION_CALL for retry", {
6244
- model: message.model,
6245
- via
6246
- });
6247
- return { message: { ...message, errorMessage: NORMALIZED_MESSAGE } };
6248
- }
6249
-
6250
- // src/mapper.ts
6251
- import {
6252
- getModel
6253
- } from "@earendil-works/pi-ai/compat";
6254
- var MINIMUM_OUTPUT_TOKENS = 8192;
6255
- function descriptorToPiModel(descriptor) {
6256
- let builtinModel;
6257
- if (descriptor.piProvider && descriptor.piModel) {
6529
+ function plexusModel(model) {
6530
+ return model?.provider === "plexus" && typeof model.id === "string" ? { provider: "plexus", id: model.id } : undefined;
6531
+ }
6532
+ function advertisementFor(model) {
6533
+ const identity = plexusModel(model);
6534
+ return identity ? host.getAdvertisement(identity) : undefined;
6535
+ }
6536
+ function conflicts() {
6258
6537
  try {
6259
- builtinModel = getModel(descriptor.piProvider, descriptor.piModel);
6538
+ return detectControlConflicts(pi.getCommands());
6260
6539
  } catch {
6261
- builtinModel = undefined;
6540
+ return [];
6262
6541
  }
6263
6542
  }
6264
- const cost = {
6265
- input: descriptor.cost.input * 1e6,
6266
- output: descriptor.cost.output * 1e6,
6267
- cacheRead: descriptor.cost.cacheRead * 1e6,
6268
- cacheWrite: descriptor.cost.cacheWrite * 1e6,
6269
- ...descriptor.cost.tiers ? {
6270
- tiers: descriptor.cost.tiers.map((tier) => ({
6271
- inputTokensAbove: tier.inputTokensAbove,
6272
- input: tier.input * 1e6,
6273
- output: tier.output * 1e6,
6274
- cacheRead: tier.cacheRead * 1e6,
6275
- cacheWrite: tier.cacheWrite * 1e6
6276
- }))
6277
- } : {}
6278
- };
6279
- let compat;
6280
- if (descriptor.preferredApi === "openai-completions") {
6281
- const heuristic = detectOpenAICompletionsCompat(descriptor.piProvider ?? descriptor.provider, descriptor.baseUrl);
6282
- const builtinCompat = builtinModel?.compat;
6283
- const merged = {
6284
- ...heuristic,
6285
- ...builtinCompat ?? {},
6286
- ...descriptor.piOptions ?? {}
6543
+ function buildState(ctx) {
6544
+ const model = ctx.model;
6545
+ const identity = plexusModel(model);
6546
+ const advertisement = advertisementFor(model);
6547
+ const context = advertisement?.context;
6548
+ const settings = reportedSettings();
6549
+ const state = {
6550
+ capabilities: [...CAPABILITIES],
6551
+ settings,
6552
+ origin: "root",
6553
+ tiers: [...advertisement?.serviceTier?.serviceTiers ?? []],
6554
+ longContextAvailable: context !== undefined && context.shortContextBudgetTokens < context.maxContextTokens,
6555
+ tierApplicable: isTierApplicable(model, settings.tier, advertisement?.serviceTier),
6556
+ conflicts: conflicts(),
6557
+ limitations: [...LIMITATIONS],
6558
+ activeChildren: bridgeTracker.activeChildren()
6287
6559
  };
6288
- compat = merged;
6289
- } else if (descriptor.piOptions) {
6290
- compat = descriptor.piOptions;
6291
- } else if (builtinModel?.compat) {
6292
- compat = builtinModel.compat;
6560
+ if (typeof model?.contextWindow === "number")
6561
+ state.contextWindow = model.contextWindow;
6562
+ const sessionId = readSessionId(ctx);
6563
+ if (sessionId !== undefined)
6564
+ state.sessionId = sessionId;
6565
+ if (context) {
6566
+ state.longContextTarget = context.maxContextTokens;
6567
+ state.shortContextBudgetTokens = context.shortContextBudgetTokens;
6568
+ if (context.pricingThresholdInputTokens !== undefined)
6569
+ state.pricingThresholdInputTokens = context.pricingThresholdInputTokens;
6570
+ }
6571
+ const baseline = identity ? host.getCatalogContextWindow(identity) : undefined;
6572
+ if (baseline !== undefined)
6573
+ state.modelBaselineContextWindow = baseline;
6574
+ if (policy.getView().applyFailed)
6575
+ state.contextPolicyError = APPLY_ERROR;
6576
+ return PlexuspiStateSchema.parse(state);
6577
+ }
6578
+ function publishState(ctx) {
6579
+ if (!expectedSessionKey)
6580
+ return;
6581
+ ctx.ui.notify(`${STATE_NOTIFY_PREFIX}${JSON.stringify({ version: PROTOCOL_VERSION, sessionKey: expectedSessionKey, state: buildState(ctx) })}`, "info");
6293
6582
  }
6294
- return {
6295
- id: descriptor.id,
6296
- name: descriptor.name,
6297
- api: descriptor.preferredApi,
6298
- provider: descriptor.provider,
6299
- baseUrl: descriptor.baseUrl,
6300
- reasoning: descriptor.reasoning,
6301
- input: descriptor.input,
6302
- cost,
6303
- contextWindow: descriptor.contextWindow,
6304
- maxTokens: Math.max(descriptor.maxTokens, MINIMUM_OUTPUT_TOKENS),
6305
- ...builtinModel?.thinkingLevelMap !== undefined ? { thinkingLevelMap: builtinModel.thinkingLevelMap } : {},
6306
- ...builtinModel?.headers !== undefined ? { headers: builtinModel.headers } : {},
6307
- ...compat !== undefined ? { compat } : {}
6308
- };
6309
- }
6310
-
6311
- // src/models-control.ts
6312
- import { randomUUID as randomUUID2 } from "crypto";
6313
- var MODELS_REFRESH_CHANNEL = "plexus:models:refresh:v1";
6314
- var MODELS_STATE_CHANNEL = "plexus:models:state:v1";
6315
- var MAX_STATE_BYTES = 1024 * 1024;
6316
- var ModelsRefreshSchema = object({
6317
- version: literal(1),
6318
- requestId: string2().min(1).max(1024)
6319
- }).strict();
6320
- var ModelsStateSchema = object({
6321
- version: literal(1),
6322
- publisherId: string2().uuid(),
6323
- revision: number2().int().positive().safe(),
6324
- requestId: string2().min(1).max(1024).optional(),
6325
- status: _enum(["idle", "refreshing", "ready", "error"]),
6326
- modelCount: number2().int().nonnegative().safe().optional(),
6327
- reason: string2().max(500).optional()
6328
- }).strict();
6329
- var MODELS_REFRESH_FAILED_REASON = "The Plexus catalog refresh failed.";
6330
- var encoder = new TextEncoder;
6331
- function byteLength(value) {
6332
- return encoder.encode(JSON.stringify(value)).byteLength;
6333
- }
6334
- function freezeState(state) {
6335
- return Object.freeze({ ...state });
6336
- }
6337
- function freezeParsed(state) {
6338
- return Object.freeze({ ...state });
6339
- }
6340
- function statesEqual(current, next) {
6341
- return current.status === next.status && current.modelCount === next.modelCount && current.reason === next.reason;
6342
- }
6343
-
6344
- class ModelsControl {
6345
- host;
6346
- publisherId = randomUUID2();
6347
- revision = 1;
6348
- state;
6349
- inFlight;
6350
- emit;
6351
- unsubscribe;
6352
- constructor(events, host) {
6353
- this.host = host;
6354
- this.emit = events.emit.bind(events);
6355
- this.state = freezeState({
6356
- version: 1,
6357
- publisherId: this.publisherId,
6358
- revision: 1,
6359
- status: "idle"
6583
+ function emit(ctx, reply) {
6584
+ const validated = PlexuspiReplySchema.parse(reply);
6585
+ ctx.ui.notify(`${NOTIFY_PREFIX}${JSON.stringify(validated)}`, validated.ok ? "info" : "warning");
6586
+ }
6587
+ function base(request) {
6588
+ return {
6589
+ version: PROTOCOL_VERSION,
6590
+ sessionKey: request.sessionKey,
6591
+ requestId: request.requestId,
6592
+ operation: request.operation
6593
+ };
6594
+ }
6595
+ function controlKey() {
6596
+ return JSON.stringify({
6597
+ tier: desiredTier,
6598
+ longContext: reportedSettings().longContext
6360
6599
  });
6361
- this.unsubscribe = events.on(MODELS_REFRESH_CHANNEL, (data) => this.handleCommand(data));
6362
6600
  }
6363
- getState() {
6364
- return this.state;
6601
+ function persistIfChanged() {
6602
+ if (suspendPersist)
6603
+ return;
6604
+ const key = controlKey();
6605
+ if (key === persistedKey)
6606
+ return;
6607
+ persistedKey = key;
6608
+ const model = policy.getView().model;
6609
+ const baseline = model ? host.getCatalogContextWindow(model) : undefined;
6610
+ pi.appendEntry(CUSTOM_ENTRY_TYPE, {
6611
+ version: PROTOCOL_VERSION,
6612
+ tier: desiredTier,
6613
+ longContext: reportedSettings().longContext,
6614
+ ...baseline !== undefined ? { contextWindow: baseline } : {},
6615
+ timestamp: now()
6616
+ });
6617
+ }
6618
+ function onPolicyCommit() {
6619
+ if (!active || closed)
6620
+ return;
6621
+ persistIfChanged();
6622
+ if (latestCtx)
6623
+ publishState(latestCtx);
6624
+ }
6625
+ function latestControlEntry(ctx) {
6626
+ let latest;
6627
+ for (const entry of readBranch(ctx)) {
6628
+ if (entry.type !== "custom" || entry.customType !== CUSTOM_ENTRY_TYPE)
6629
+ continue;
6630
+ const parsed = ControlEntrySchema.safeParse(entry.data);
6631
+ if (parsed.success)
6632
+ latest = parsed.data;
6633
+ }
6634
+ return latest;
6365
6635
  }
6366
- dispose() {
6367
- this.unsubscribe();
6636
+ async function restore(ctx) {
6637
+ const entry = latestControlEntry(ctx);
6638
+ desiredTier = entry?.tier ?? NO_TIER;
6639
+ desiredLongContext = entry?.longContext ?? false;
6640
+ suspendPersist = true;
6641
+ try {
6642
+ await policy.reconcile();
6643
+ } finally {
6644
+ suspendPersist = false;
6645
+ }
6646
+ persistedKey = controlKey();
6368
6647
  }
6369
- async handleCommand(data) {
6370
- const parsed = ModelsRefreshSchema.safeParse(data);
6648
+ function forwardBridgeRecord(data) {
6649
+ if (!active || closed)
6650
+ return;
6651
+ const parsed = SubagentBridgeRecordSchema.safeParse(data);
6371
6652
  if (!parsed.success)
6372
6653
  return;
6373
- if (!this.inFlight) {
6374
- const run = this.runRefresh();
6375
- this.inFlight = run.finally(() => {
6376
- this.inFlight = undefined;
6654
+ const forward = bridgeTracker.accept(parsed.data);
6655
+ if (!forward || !latestCtx)
6656
+ return;
6657
+ latestCtx.ui.notify(formatChildForward(forward), "info");
6658
+ }
6659
+ function emitRootSignal(ctx) {
6660
+ const sessionId = readSessionId(ctx);
6661
+ if (sessionId === undefined)
6662
+ return;
6663
+ pi.events.emit(ROOT_SIGNAL_CHANNEL, {
6664
+ version: ROOT_SIGNAL_VERSION,
6665
+ sessionId
6666
+ });
6667
+ }
6668
+ async function activate(ctx) {
6669
+ latestCtx = ctx;
6670
+ if (active)
6671
+ return;
6672
+ active = true;
6673
+ policy.setResolver(resolveIntent);
6674
+ unsubscribeView = policy.subscribe(onPolicyCommit);
6675
+ unsubscribeBridge = pi.events.on(SUBAGENT_BRIDGE_CHANNEL, forwardBridgeRecord);
6676
+ await restore(ctx);
6677
+ emitRootSignal(ctx);
6678
+ }
6679
+ function rewindResult(cancelled, targetEntryId, ctx) {
6680
+ const leafId = readLeafId(ctx);
6681
+ return {
6682
+ cancelled,
6683
+ targetEntryId,
6684
+ ...leafId !== undefined ? { leafId } : {},
6685
+ settings: reportedSettings(),
6686
+ activeChildren: bridgeTracker.activeChildren()
6687
+ };
6688
+ }
6689
+ function handleHello(request, ctx) {
6690
+ const data = buildState(ctx);
6691
+ if (data.conflicts.length > 0) {
6692
+ const detail = data.conflicts.map((conflict) => `${conflict.owner} owns ${conflict.command}`).join("; ");
6693
+ const resolutions = data.conflicts.map((conflict) => conflict.resolution).join(" ");
6694
+ emit(ctx, {
6695
+ ...base(request),
6696
+ ok: false,
6697
+ data,
6698
+ error: `known control owner conflict: ${detail}. ${resolutions}`
6699
+ });
6700
+ return;
6701
+ }
6702
+ emit(ctx, { ...base(request), ok: true, data });
6703
+ }
6704
+ async function handleConfigure(request, ctx) {
6705
+ const parsed = ConfigureDataSchema.safeParse(request.data ?? {});
6706
+ if (!parsed.success) {
6707
+ emit(ctx, {
6708
+ ...base(request),
6709
+ ok: false,
6710
+ error: `invalid configure data: ${formatIssues(parsed.error)}`
6711
+ });
6712
+ return;
6713
+ }
6714
+ const advertisement = advertisementFor(ctx.model);
6715
+ const choices = advertisement?.serviceTier?.serviceTiers ?? [];
6716
+ const requestedTier = parsed.data.tier;
6717
+ const nextTier = requestedTier === undefined ? resolvedTier : choices.includes(requestedTier) ? requestedTier : requestedTier === "fast" ? "priority" : requestedTier === NO_TIER ? resolveSavedTier(requestedTier, choices) : requestedTier;
6718
+ if (requestedTier !== undefined && !choices.includes(nextTier)) {
6719
+ emit(ctx, {
6720
+ ...base(request),
6721
+ ok: false,
6722
+ data: buildState(ctx),
6723
+ error: `Service tier '${requestedTier}' is not advertised for the current model.`
6724
+ });
6725
+ return;
6726
+ }
6727
+ const nextLongContext = parsed.data.longContext ?? reportedSettings().longContext;
6728
+ const context = advertisement?.context;
6729
+ if (nextLongContext && (!context || context.shortContextBudgetTokens >= context.maxContextTokens)) {
6730
+ emit(ctx, {
6731
+ ...base(request),
6732
+ ok: false,
6733
+ data: buildState(ctx),
6734
+ error: "The current model has no distinct short and long context budgets."
6377
6735
  });
6736
+ return;
6737
+ }
6738
+ if (parsed.data.longContext !== undefined) {
6739
+ const previousLongContext = desiredLongContext;
6740
+ desiredLongContext = nextLongContext;
6741
+ await policy.reconcile();
6742
+ if (policy.getView().applyFailed) {
6743
+ desiredLongContext = previousLongContext;
6744
+ emit(ctx, {
6745
+ ...base(request),
6746
+ ok: false,
6747
+ data: buildState(ctx),
6748
+ error: APPLY_ERROR
6749
+ });
6750
+ return;
6751
+ }
6378
6752
  }
6379
- await this.inFlight;
6380
- this.emitState(this.state, parsed.data.requestId);
6753
+ if (requestedTier !== undefined) {
6754
+ desiredTier = nextTier;
6755
+ await policy.reconcile();
6756
+ }
6757
+ emit(ctx, { ...base(request), ok: true, data: buildState(ctx) });
6381
6758
  }
6382
- async runRefresh() {
6383
- this.commit({ status: "refreshing" });
6759
+ async function handleRewind(request, ctx) {
6760
+ const parsed = RewindDataSchema.safeParse(request.data ?? {});
6761
+ if (!parsed.success) {
6762
+ emit(ctx, {
6763
+ ...base(request),
6764
+ ok: false,
6765
+ error: `invalid rewind data: ${formatIssues(parsed.error)}`
6766
+ });
6767
+ return;
6768
+ }
6769
+ const { targetEntryId } = parsed.data;
6770
+ if (!ctx.isIdle()) {
6771
+ emit(ctx, {
6772
+ ...base(request),
6773
+ ok: false,
6774
+ data: buildState(ctx),
6775
+ error: "rewind requires an idle agent"
6776
+ });
6777
+ return;
6778
+ }
6779
+ if (compactionActive) {
6780
+ emit(ctx, {
6781
+ ...base(request),
6782
+ ok: false,
6783
+ data: buildState(ctx),
6784
+ error: "rewind is unavailable while a compaction is in progress"
6785
+ });
6786
+ return;
6787
+ }
6788
+ const activeChildren = bridgeTracker.activeChildren();
6789
+ if (activeChildren > 0) {
6790
+ emit(ctx, {
6791
+ ...base(request),
6792
+ ok: false,
6793
+ data: buildState(ctx),
6794
+ error: `rewind is unavailable while ${activeChildren} owned child session(s) are active`
6795
+ });
6796
+ return;
6797
+ }
6798
+ const target = findActiveBranchUserEntry(readBranch(ctx), targetEntryId);
6799
+ if (!target.ok) {
6800
+ emit(ctx, {
6801
+ ...base(request),
6802
+ ok: false,
6803
+ data: buildState(ctx),
6804
+ error: `invalid rewind target: ${target.error}`
6805
+ });
6806
+ return;
6807
+ }
6808
+ let result;
6384
6809
  try {
6385
- const result = await this.host.refresh();
6386
- this.commit({ status: "ready", modelCount: result.modelCount });
6810
+ result = await ctx.navigateTree(targetEntryId, { summarize: false });
6387
6811
  } catch (error) {
6388
- log("models:refresh failed", { error: String(error) });
6389
- this.commit({ status: "error", reason: MODELS_REFRESH_FAILED_REASON });
6812
+ const message = error instanceof Error ? error.message : String(error);
6813
+ emit(ctx, {
6814
+ ...base(request),
6815
+ ok: false,
6816
+ data: buildState(ctx),
6817
+ error: `rewind navigation failed: ${message}`
6818
+ });
6819
+ return;
6390
6820
  }
6391
- }
6392
- commit(next) {
6393
- if (statesEqual(this.state, next))
6821
+ if (navigationCancelled(result)) {
6822
+ emit(ctx, {
6823
+ ...base(request),
6824
+ ok: false,
6825
+ data: rewindResult(true, targetEntryId, ctx),
6826
+ error: "rewind was cancelled before navigation completed."
6827
+ });
6394
6828
  return;
6395
- this.revision++;
6396
- this.state = freezeState({
6397
- version: 1,
6398
- publisherId: this.publisherId,
6399
- revision: this.revision,
6400
- status: next.status,
6401
- ...next.modelCount === undefined ? {} : { modelCount: next.modelCount },
6402
- ...next.reason === undefined ? {} : { reason: next.reason }
6829
+ }
6830
+ const leafId = readLeafId(ctx) ?? null;
6831
+ pi.appendEntry(REWIND_ENTRY_TYPE, buildRewindEntry(targetEntryId, leafId, now()));
6832
+ latestCtx = ctx;
6833
+ await restore(ctx);
6834
+ emit(ctx, {
6835
+ ...base(request),
6836
+ ok: true,
6837
+ data: rewindResult(false, targetEntryId, ctx)
6403
6838
  });
6404
- this.emitState(this.state);
6405
6839
  }
6406
- emitState(state, requestId) {
6407
- const candidate = requestId === undefined ? state : { ...state, requestId };
6408
- const parsed = ModelsStateSchema.safeParse(candidate);
6409
- if (parsed.success && byteLength(parsed.data) <= MAX_STATE_BYTES) {
6410
- this.emit(MODELS_STATE_CHANNEL, freezeParsed(parsed.data));
6840
+ async function handleReload(request, ctx) {
6841
+ if (!ctx.isIdle()) {
6842
+ emit(ctx, {
6843
+ ...base(request),
6844
+ ok: false,
6845
+ data: buildState(ctx),
6846
+ error: "reload is unavailable while the agent is busy"
6847
+ });
6411
6848
  return;
6412
6849
  }
6413
- const fallback = ModelsStateSchema.safeParse({
6414
- version: 1,
6415
- publisherId: this.publisherId,
6416
- revision: this.revision,
6417
- ...requestId === undefined ? {} : { requestId },
6418
- status: "error",
6419
- reason: "Plexus catalog state is unavailable."
6420
- });
6421
- if (fallback.success)
6422
- this.emit(MODELS_STATE_CHANNEL, freezeParsed(fallback.data));
6850
+ if (compactionActive) {
6851
+ emit(ctx, {
6852
+ ...base(request),
6853
+ ok: false,
6854
+ data: buildState(ctx),
6855
+ error: "reload is unavailable while a compaction is in progress"
6856
+ });
6857
+ return;
6858
+ }
6859
+ const activeChildren = bridgeTracker.activeChildren();
6860
+ if (activeChildren > 0) {
6861
+ emit(ctx, {
6862
+ ...base(request),
6863
+ ok: false,
6864
+ data: buildState(ctx),
6865
+ error: `reload is unavailable while ${activeChildren} owned child session(s) are active`
6866
+ });
6867
+ return;
6868
+ }
6869
+ emit(ctx, { ...base(request), ok: true, data: buildState(ctx) });
6870
+ await ctx.reload();
6871
+ }
6872
+ async function handleArgs(args, ctx) {
6873
+ const parsed = parseRequestArg(args);
6874
+ if (!parsed.ok) {
6875
+ emit(ctx, {
6876
+ version: PROTOCOL_VERSION,
6877
+ sessionKey: parsed.sessionKey,
6878
+ requestId: parsed.requestId,
6879
+ operation: parsed.operation,
6880
+ ok: false,
6881
+ error: parsed.error
6882
+ });
6883
+ return;
6884
+ }
6885
+ const request = parsed.request;
6886
+ const refuse = (error) => emit(ctx, { ...base(request), ok: false, error });
6887
+ if (!expectedSessionKey) {
6888
+ refuse(`${SESSION_KEY_ENV} is not set for this process; refusing control request.`);
6889
+ return;
6890
+ }
6891
+ if (request.sessionKey !== expectedSessionKey) {
6892
+ refuse("session key mismatch; refusing control request.");
6893
+ return;
6894
+ }
6895
+ await activate(ctx);
6896
+ switch (request.operation) {
6897
+ case "hello":
6898
+ handleHello(request, ctx);
6899
+ return;
6900
+ case "get-state":
6901
+ emit(ctx, { ...base(request), ok: true, data: buildState(ctx) });
6902
+ return;
6903
+ case "configure":
6904
+ await handleConfigure(request, ctx);
6905
+ return;
6906
+ case "rewind":
6907
+ await handleRewind(request, ctx);
6908
+ return;
6909
+ case "reload":
6910
+ await handleReload(request, ctx);
6911
+ return;
6912
+ }
6423
6913
  }
6914
+ pi.registerCommand(COMMAND_NAME, {
6915
+ description: "Plexus control protocol (base64url-encoded JSON).",
6916
+ handler: (args, ctx) => handleArgs(args, ctx)
6917
+ });
6918
+ pi.on("session_start", (_event, ctx) => {
6919
+ if (!active || closed)
6920
+ return;
6921
+ latestCtx = ctx;
6922
+ return restore(ctx);
6923
+ });
6924
+ pi.on("session_tree", (_event, ctx) => {
6925
+ if (!active || closed)
6926
+ return;
6927
+ latestCtx = ctx;
6928
+ return restore(ctx);
6929
+ });
6930
+ pi.on("model_select", (_event, ctx) => {
6931
+ if (!active || closed)
6932
+ return;
6933
+ latestCtx = ctx;
6934
+ });
6935
+ pi.on("before_agent_start", async (_event, ctx) => {
6936
+ if (!active || closed)
6937
+ return;
6938
+ latestCtx = ctx;
6939
+ await policy.reconcile();
6940
+ if (policy.getView().applyFailed)
6941
+ throw new Error(APPLY_ERROR);
6942
+ });
6943
+ pi.on("session_before_compact", () => {
6944
+ compactionActive = true;
6945
+ });
6946
+ pi.on("session_compact", () => {
6947
+ compactionActive = false;
6948
+ });
6949
+ pi.on("session_compact_failed", () => {
6950
+ compactionActive = false;
6951
+ });
6952
+ pi.on("session_shutdown", () => {
6953
+ closed = true;
6954
+ compactionActive = false;
6955
+ unsubscribeBridge?.();
6956
+ unsubscribeBridge = undefined;
6957
+ unsubscribeView?.();
6958
+ unsubscribeView = undefined;
6959
+ if (active)
6960
+ policy.setResolver(undefined);
6961
+ latestCtx = undefined;
6962
+ });
6963
+ return {
6964
+ get active() {
6965
+ return active;
6966
+ },
6967
+ handleArgs,
6968
+ buildState,
6969
+ activeChildren: () => bridgeTracker.activeChildren()
6970
+ };
6424
6971
  }
6425
6972
 
6426
6973
  // src/policy.ts
6427
- import { randomUUID as randomUUID3 } from "crypto";
6428
- var POLICY_SET_CHANNEL = "plexus:policy:set:v1";
6429
- var POLICY_STATE_CHANNEL = "plexus:policy:state:v1";
6430
- var MAX_STATE_BYTES2 = 1024 * 1024;
6431
- var PolicySetSchema = object({
6432
- version: literal(1),
6433
- requestId: string2().min(1).max(1024),
6434
- longContext: boolean2().optional(),
6435
- serviceTier: string2().min(1).max(100).nullable().optional()
6436
- }).strict().refine((command) => command.longContext !== undefined || command.serviceTier !== undefined, { message: "At least one of longContext or serviceTier is required." });
6437
- var PolicyAppliedSchema = object({
6438
- longContext: boolean2(),
6439
- serviceTier: string2().min(1).max(100).nullable(),
6440
- contextWindow: number2().int().positive().safe().optional()
6441
- }).strict();
6442
- var PolicyAvailabilitySchema = object({
6443
- longContext: boolean2(),
6444
- serviceTier: boolean2()
6445
- }).strict();
6446
- var PolicyStateSchema = object({
6447
- version: literal(1),
6448
- publisherId: string2().uuid(),
6449
- revision: number2().int().positive().safe(),
6450
- requestId: string2().min(1).max(1024).optional(),
6451
- applied: PolicyAppliedSchema,
6452
- available: PolicyAvailabilitySchema,
6453
- reason: string2().max(500).optional()
6454
- }).strict();
6455
- var POLICY_UNAVAILABLE_REASON = "No Plexus context or service-tier policy is advertised for the active model.";
6456
- var DEFAULT_SELECTION = Object.freeze({
6457
- longContext: true,
6458
- serviceTier: null
6459
- });
6460
6974
  function policyAvailability(advertisement) {
6461
6975
  const context = advertisement?.context;
6462
6976
  return {
@@ -6480,99 +6994,50 @@ function injectServiceTier(payload, tier) {
6480
6994
  return payload;
6481
6995
  return { ...payload, service_tier: tier };
6482
6996
  }
6483
- var encoder2 = new TextEncoder;
6484
- function byteLength2(value) {
6485
- return encoder2.encode(JSON.stringify(value)).byteLength;
6486
- }
6487
- function freezeParsed2(state) {
6488
- return Object.freeze({
6489
- ...state,
6490
- applied: Object.freeze({ ...state.applied }),
6491
- available: Object.freeze({ ...state.available })
6492
- });
6493
- }
6494
- function freezePublished(state) {
6495
- return Object.freeze({
6496
- ...state,
6497
- applied: Object.freeze({ ...state.applied }),
6498
- available: Object.freeze({ ...state.available })
6499
- });
6500
- }
6501
- function selectionStatesEqual(current, next) {
6502
- const shape = (state) => JSON.stringify({
6503
- applied: state.applied,
6504
- available: state.available,
6505
- reason: state.reason ?? null
6506
- });
6507
- return shape(current) === shape(next);
6508
- }
6509
- function validateSelection(model, advertisement, command) {
6510
- if (model === undefined || advertisement === undefined || advertisement.context === undefined && advertisement.serviceTier === undefined) {
6511
- return POLICY_UNAVAILABLE_REASON;
6512
- }
6513
- if (command.longContext !== undefined) {
6514
- const context = advertisement.context;
6515
- if (context === undefined)
6516
- return "No context budget is advertised for the active model.";
6517
- if (context.shortContextBudgetTokens >= context.maxContextTokens) {
6518
- return "The active model has no distinct short and maximum context budget.";
6519
- }
6520
- }
6521
- if (command.serviceTier !== undefined && command.serviceTier !== null) {
6522
- const tiers = advertisement.serviceTier?.serviceTiers;
6523
- if (!tiers?.includes(command.serviceTier)) {
6524
- return "The requested service tier is not advertised for the active model.";
6525
- }
6526
- }
6527
- return;
6528
- }
6997
+ var TERMINAL_RESOLVER = () => ({
6998
+ longContext: true,
6999
+ serviceTier: null
7000
+ });
7001
+ function sameModel(a, b) {
7002
+ return a !== undefined && b !== undefined && a.provider === b.provider && a.id === b.id;
7003
+ }
7004
+ var EMPTY_VIEW = Object.freeze({
7005
+ model: undefined,
7006
+ selection: Object.freeze({ longContext: false, serviceTier: null }),
7007
+ available: Object.freeze({ longContext: false, serviceTier: false }),
7008
+ contextWindow: undefined,
7009
+ applyFailed: false
7010
+ });
6529
7011
 
6530
7012
  class PolicyController {
6531
7013
  host;
6532
- publisherId = randomUUID3();
6533
- revision = 1;
6534
- selection = { ...DEFAULT_SELECTION };
6535
- boundModel;
6536
- available = {
6537
- longContext: false,
6538
- serviceTier: false
6539
- };
6540
- contextWindow;
6541
- reason;
6542
- state;
6543
- emit;
6544
- unsubscribe;
7014
+ resolver;
7015
+ view = EMPTY_VIEW;
7016
+ listeners = new Set;
6545
7017
  chain = Promise.resolve();
6546
- constructor(events, host) {
7018
+ constructor(host) {
6547
7019
  this.host = host;
6548
- this.emit = events.emit.bind(events);
6549
- this.state = freezePublished({
6550
- version: 1,
6551
- publisherId: this.publisherId,
6552
- revision: 1,
6553
- applied: { longContext: true, serviceTier: null },
6554
- available: { longContext: false, serviceTier: false }
6555
- });
6556
- this.unsubscribe = events.on(POLICY_SET_CHANNEL, (data) => this.enqueue(() => this.handleSet(data)));
6557
7020
  }
6558
- getState() {
6559
- return this.state;
7021
+ getView() {
7022
+ return this.view;
7023
+ }
7024
+ setResolver(resolver) {
7025
+ this.resolver = resolver;
7026
+ }
7027
+ subscribe(listener) {
7028
+ this.listeners.add(listener);
7029
+ return () => {
7030
+ this.listeners.delete(listener);
7031
+ };
6560
7032
  }
6561
7033
  serviceTierFor(model) {
6562
- if (!model || !this.boundModel)
7034
+ if (!model || !sameModel(this.view.model, model))
6563
7035
  return null;
6564
- if (this.boundModel.provider !== model.provider || this.boundModel.id !== model.id)
6565
- return null;
6566
- if (!this.available.serviceTier)
6567
- return null;
6568
- return this.selection.serviceTier;
7036
+ return this.view.selection.serviceTier;
6569
7037
  }
6570
7038
  reconcile() {
6571
7039
  return this.enqueue(() => this.recompute());
6572
7040
  }
6573
- dispose() {
6574
- this.unsubscribe();
6575
- }
6576
7041
  enqueue(task) {
6577
7042
  const run = this.chain.then(task, task).catch(() => {
6578
7043
  return;
@@ -6582,84 +7047,41 @@ class PolicyController {
6582
7047
  }
6583
7048
  async recompute() {
6584
7049
  const model = this.host.getActiveModel();
6585
- if (model === undefined) {
6586
- this.commit({
6587
- selection: { ...DEFAULT_SELECTION },
6588
- boundModel: undefined,
6589
- available: { longContext: false, serviceTier: false },
6590
- contextWindow: undefined,
6591
- reason: POLICY_UNAVAILABLE_REASON
6592
- });
6593
- return;
6594
- }
6595
- const advertisement = this.host.getAdvertisement(model);
6596
- const sameModel = this.boundModel?.provider === model.provider && this.boundModel.id === model.id;
6597
- let selection = sameModel ? { ...this.selection } : { ...DEFAULT_SELECTION };
6598
- let reason;
7050
+ const advertisement = model === undefined ? undefined : this.host.getAdvertisement(model);
7051
+ const intent = (this.resolver ?? TERMINAL_RESOLVER)(model, advertisement);
6599
7052
  const available = policyAvailability(advertisement);
6600
- if (advertisement?.context === undefined) {
6601
- if (!selection.longContext) {
6602
- selection = { ...selection, longContext: true };
6603
- reason = "The active model no longer advertises a short context budget.";
6604
- }
6605
- } else if (!available.longContext && !selection.longContext) {
6606
- selection = { ...selection, longContext: true };
6607
- reason = "The active model no longer advertises a distinct short context budget.";
6608
- }
6609
- if (selection.serviceTier !== null) {
6610
- const tiers = advertisement?.serviceTier?.serviceTiers;
6611
- if (!tiers?.includes(selection.serviceTier)) {
6612
- selection = { ...selection, serviceTier: null };
6613
- reason = "The selected service tier is no longer advertised for the active model.";
7053
+ const tiers = advertisement?.serviceTier?.serviceTiers ?? [];
7054
+ const same = sameModel(this.view.model, model);
7055
+ let selection = {
7056
+ longContext: intent.longContext && available.longContext,
7057
+ serviceTier: intent.serviceTier !== null && tiers.includes(intent.serviceTier) ? intent.serviceTier : null
7058
+ };
7059
+ let contextWindow;
7060
+ let applyFailed = false;
7061
+ if (model !== undefined) {
7062
+ const applied = await this.applyContext(model, effectiveContextWindow(advertisement, selection));
7063
+ if (advertisement?.context !== undefined) {
7064
+ if (applied === undefined) {
7065
+ applyFailed = true;
7066
+ selection = {
7067
+ ...selection,
7068
+ longContext: same ? this.view.selection.longContext : false
7069
+ };
7070
+ contextWindow = same ? this.view.contextWindow : undefined;
7071
+ } else {
7072
+ contextWindow = applied;
7073
+ }
6614
7074
  }
6615
7075
  }
6616
- if (advertisement?.context === undefined && advertisement?.serviceTier === undefined) {
6617
- reason = POLICY_UNAVAILABLE_REASON;
6618
- }
6619
- const desired = effectiveContextWindow(advertisement, selection);
6620
- const appliedWindow = await this.applyContext(model, desired);
6621
- if (advertisement?.context !== undefined && appliedWindow === undefined) {
6622
- reason = "The session context window could not be updated.";
6623
- }
6624
- this.commit({
6625
- selection,
6626
- boundModel: model,
6627
- available,
6628
- contextWindow: advertisement?.context !== undefined ? appliedWindow : undefined,
6629
- reason
7076
+ this.view = Object.freeze({
7077
+ model,
7078
+ selection: Object.freeze(selection),
7079
+ available: Object.freeze(available),
7080
+ contextWindow,
7081
+ applyFailed
6630
7082
  });
6631
- }
6632
- async handleSet(data) {
6633
- const parsed = PolicySetSchema.safeParse(data);
6634
- if (!parsed.success)
6635
- return;
6636
- const command = parsed.data;
6637
- const model = this.host.getActiveModel();
6638
- const advertisement = model === undefined ? undefined : this.host.getAdvertisement(model);
6639
- const sameModel = model !== undefined && this.boundModel?.provider === model.provider && this.boundModel.id === model.id;
6640
- const current = sameModel ? { ...this.selection } : { ...DEFAULT_SELECTION };
6641
- const nextSelection = {
6642
- longContext: command.longContext ?? current.longContext,
6643
- serviceTier: command.serviceTier === undefined ? current.serviceTier : command.serviceTier
6644
- };
6645
- const rejection = validateSelection(model, advertisement, command);
6646
- if (rejection !== undefined) {
6647
- this.emitReply(command.requestId, rejection);
6648
- return;
6649
- }
6650
- const desired = effectiveContextWindow(advertisement, nextSelection);
6651
- const appliedWindow = model === undefined ? undefined : await this.applyContext(model, desired);
6652
- if (advertisement?.context !== undefined && appliedWindow === undefined) {
6653
- this.emitReply(command.requestId, "The session context window could not be updated.");
6654
- return;
6655
- }
6656
- this.commit({
6657
- selection: nextSelection,
6658
- boundModel: model,
6659
- available: policyAvailability(advertisement),
6660
- contextWindow: advertisement?.context !== undefined ? appliedWindow : undefined,
6661
- reason: undefined
6662
- }, command.requestId);
7083
+ for (const listener of [...this.listeners])
7084
+ listener();
6663
7085
  }
6664
7086
  async applyContext(model, contextWindow) {
6665
7087
  try {
@@ -6668,208 +7090,21 @@ class PolicyController {
6668
7090
  return;
6669
7091
  }
6670
7092
  }
6671
- commit(next, requestId) {
6672
- this.selection = next.selection;
6673
- this.boundModel = next.boundModel;
6674
- this.available = next.available;
6675
- this.contextWindow = next.contextWindow;
6676
- this.reason = next.reason;
6677
- const candidate = {
6678
- applied: {
6679
- longContext: next.selection.longContext,
6680
- serviceTier: next.selection.serviceTier,
6681
- ...next.contextWindow === undefined ? {} : { contextWindow: next.contextWindow }
6682
- },
6683
- available: { ...next.available },
6684
- ...next.reason === undefined ? {} : { reason: next.reason }
6685
- };
6686
- const changed = !selectionStatesEqual(this.state, candidate);
6687
- if (changed) {
6688
- this.revision++;
6689
- this.state = freezePublished({
6690
- version: 1,
6691
- publisherId: this.publisherId,
6692
- revision: this.revision,
6693
- ...candidate
6694
- });
6695
- this.emitState(this.state);
6696
- }
6697
- if (requestId !== undefined) {
6698
- this.emitState(this.state, requestId);
6699
- }
6700
- }
6701
- emitReply(requestId, reason) {
6702
- const parsed = PolicyStateSchema.safeParse({
6703
- ...this.state,
6704
- ...reason === undefined ? {} : { reason },
6705
- requestId
6706
- });
6707
- if (parsed.success && byteLength2(parsed.data) <= MAX_STATE_BYTES2) {
6708
- this.emit(POLICY_STATE_CHANNEL, freezeParsed2(parsed.data));
6709
- }
6710
- }
6711
- emitState(state, requestId) {
6712
- const candidate = requestId === undefined ? state : { ...state, requestId };
6713
- const parsed = PolicyStateSchema.safeParse(candidate);
6714
- if (parsed.success && byteLength2(parsed.data) <= MAX_STATE_BYTES2) {
6715
- this.emit(POLICY_STATE_CHANNEL, freezeParsed2(parsed.data));
6716
- return;
6717
- }
6718
- const fallback = PolicyStateSchema.safeParse({
6719
- version: 1,
6720
- publisherId: this.publisherId,
6721
- revision: this.revision,
6722
- ...requestId === undefined ? {} : { requestId },
6723
- applied: { longContext: true, serviceTier: null },
6724
- available: { longContext: false, serviceTier: false },
6725
- reason: "Plexus policy state is unavailable."
6726
- });
6727
- if (fallback.success)
6728
- this.emit(POLICY_STATE_CHANNEL, freezeParsed2(fallback.data));
6729
- }
6730
7093
  }
6731
7094
 
6732
7095
  // src/service-tiers.ts
6733
- import { randomUUID as randomUUID4 } from "crypto";
6734
- var SERVICE_TIERS_REQUEST_CHANNEL = "plexus:service-tiers:request:v1";
6735
- var SERVICE_TIERS_SNAPSHOT_CHANNEL = "plexus:service-tiers:snapshot:v1";
6736
7096
  var ServiceTierPolicySchema = object({
6737
7097
  provider: string2().min(1),
6738
7098
  modelId: string2().min(1),
6739
7099
  serviceTiers: array(string2().min(1).max(100)).min(1).max(64)
6740
7100
  }).strict().refine((policy) => new Set(policy.serviceTiers).size === policy.serviceTiers.length);
6741
- var ServiceTiersRequestSchema = object({
6742
- version: literal(1),
6743
- requestId: string2().min(1).max(1024)
6744
- }).strict();
6745
- var ServiceTiersSnapshotSchema = object({
6746
- version: literal(1),
6747
- publisherId: string2().uuid(),
6748
- revision: number2().int().positive().safe(),
6749
- requestId: string2().min(1).max(1024).optional(),
6750
- status: _enum(["ready", "loading", "unavailable"]),
6751
- policies: array(ServiceTierPolicySchema),
6752
- fetchedAt: number2().int().nonnegative().safe().optional(),
6753
- cached: boolean2().optional(),
6754
- reason: string2().max(500).optional()
6755
- }).strict().superRefine((snapshot, ctx) => {
6756
- const pairs = new Set;
6757
- for (const policy of snapshot.policies) {
6758
- const pair = `${policy.provider}\x00${policy.modelId}`;
6759
- if (pairs.has(pair))
6760
- ctx.addIssue({
6761
- code: "custom",
6762
- message: "Duplicate provider/modelId service-tier policy"
6763
- });
6764
- pairs.add(pair);
6765
- }
6766
- if (snapshot.status !== "ready" && snapshot.policies.length !== 0) {
6767
- ctx.addIssue({
6768
- code: "custom",
6769
- message: "Non-ready snapshots must have no policies"
6770
- });
6771
- }
6772
- });
6773
- var MAX_SNAPSHOT_BYTES2 = 1024 * 1024;
6774
- var SERVICE_TIERS_METADATA_UNAVAILABLE_REASON = "Service-tier metadata is not available from the committed Plexus catalog.";
6775
7101
 
6776
- class ServiceTiersPublisher {
6777
- publisherId = randomUUID4();
6778
- revision = 1;
6779
- state = Object.freeze({
6780
- version: 1,
6781
- publisherId: this.publisherId,
6782
- revision: 1,
6783
- status: "loading",
6784
- policies: Object.freeze([])
6785
- });
6786
- emit;
6787
- unsubscribe;
6788
- constructor(events) {
6789
- this.emit = events.emit.bind(events);
6790
- this.unsubscribe = events.on(SERVICE_TIERS_REQUEST_CHANNEL, (data) => {
6791
- const request = ServiceTiersRequestSchema.safeParse(data);
6792
- if (request.success)
6793
- this.send(request.data.requestId);
6794
- });
6795
- }
6796
- getSnapshot() {
6797
- return this.state;
6798
- }
6799
- setCatalog(status, policies, metadata) {
6800
- const candidate = ServiceTiersSnapshotSchema.safeParse({
6801
- version: 1,
6802
- publisherId: this.publisherId,
6803
- revision: this.revision,
6804
- status,
6805
- policies: [...policies],
6806
- ...metadata
6807
- });
6808
- const oversized = candidate.success && new TextEncoder().encode(JSON.stringify(candidate.data)).byteLength > MAX_SNAPSHOT_BYTES2;
6809
- let next = candidate.success && !oversized ? candidate.data : {
6810
- version: 1,
6811
- publisherId: this.publisherId,
6812
- revision: this.revision,
6813
- status: "unavailable",
6814
- policies: [],
6815
- reason: oversized ? "Service-tier snapshot exceeds the 1 MiB publication limit." : "Service-tier snapshot could not be validated."
6816
- };
6817
- if (status !== "ready" && policies.length > 0) {
6818
- next = {
6819
- ...next,
6820
- status: "unavailable",
6821
- policies: [],
6822
- reason: "Service-tier metadata is unavailable."
6823
- };
6824
- }
6825
- const { revision: _revision, ...stateWithoutRevision } = this.state;
6826
- const { revision: _candidateRevision, ...nextWithoutRevision } = next;
6827
- if (JSON.stringify(stateWithoutRevision) === JSON.stringify(nextWithoutRevision))
6828
- return false;
6829
- this.revision++;
6830
- this.state = Object.freeze({
6831
- ...next,
6832
- revision: this.revision,
6833
- policies: Object.freeze(next.policies.map((policy) => Object.freeze({
6834
- ...policy,
6835
- serviceTiers: Object.freeze([...policy.serviceTiers])
6836
- })))
6837
- });
6838
- this.send();
6839
- return true;
6840
- }
6841
- send(requestId) {
6842
- const snapshot = {
6843
- ...this.state,
6844
- ...requestId === undefined ? {} : { requestId }
6845
- };
6846
- let valid = ServiceTiersSnapshotSchema.safeParse(snapshot);
6847
- if (!valid.success || new TextEncoder().encode(JSON.stringify(snapshot)).byteLength > MAX_SNAPSHOT_BYTES2) {
6848
- valid = ServiceTiersSnapshotSchema.safeParse({
6849
- version: 1,
6850
- publisherId: this.publisherId,
6851
- revision: this.revision,
6852
- status: "unavailable",
6853
- policies: [],
6854
- reason: "Service-tier snapshot exceeds publication limits or is invalid.",
6855
- ...requestId === undefined ? {} : { requestId }
6856
- });
6857
- }
6858
- if (valid.success) {
6859
- const immutable = Object.freeze({
6860
- ...valid.data,
6861
- policies: Object.freeze(valid.data.policies.map((policy) => Object.freeze({
6862
- ...policy,
6863
- serviceTiers: Object.freeze([...policy.serviceTiers])
6864
- })))
6865
- });
6866
- this.emit(SERVICE_TIERS_SNAPSHOT_CHANNEL, immutable);
6867
- }
6868
- }
6869
- dispose() {
6870
- this.unsubscribe();
6871
- }
6872
- }
7102
+ // src/short-names.ts
7103
+ var ShortNameEntrySchema = object({
7104
+ provider: string2().min(1),
7105
+ modelId: string2().min(1),
7106
+ shortName: string2().min(1).max(200)
7107
+ }).strict();
6873
7108
 
6874
7109
  // src/extension.ts
6875
7110
  var PROVIDER_NAME = "plexus";
@@ -7102,8 +7337,11 @@ function createPolicyHost(deps) {
7102
7337
  ...serviceTier ? { serviceTier } : {}
7103
7338
  };
7104
7339
  },
7105
- getEffectiveContextWindow() {
7106
- return deps.getActiveModel()?.contextWindow;
7340
+ getCatalogContextWindow(model) {
7341
+ return deps.getRegistry()?.find(model.provider, model.id)?.contextWindow;
7342
+ },
7343
+ hasCatalogContextPolicy() {
7344
+ return deps.getModels().some((entry) => entry.plexusContextPolicy !== undefined);
7107
7345
  },
7108
7346
  async applyContextWindow(model, contextWindow) {
7109
7347
  const registry = deps.getRegistry();
@@ -7126,19 +7364,14 @@ function createPolicyHost(deps) {
7126
7364
  };
7127
7365
  }
7128
7366
  function plexusExtension(pi) {
7129
- const contextPolicies = new ContextPolicyPublisher(pi.events);
7130
- const serviceTiers = new ServiceTiersPublisher(pi.events);
7131
7367
  const state = {
7132
7368
  models: [],
7133
7369
  catalogSource: "none",
7134
- refreshSequence: 0,
7135
- contextPolicies,
7136
- serviceTiers,
7137
7370
  policy: undefined,
7138
7371
  activeModel: undefined,
7139
7372
  registry: undefined
7140
7373
  };
7141
- const policy = new PolicyController(pi.events, createPolicyHost({
7374
+ const host = createPolicyHost({
7142
7375
  getActiveModel: () => state.activeModel,
7143
7376
  getModels: () => state.models,
7144
7377
  getRegistry: () => state.registry,
@@ -7146,39 +7379,11 @@ function plexusExtension(pi) {
7146
7379
  setActiveModel: (model) => {
7147
7380
  state.activeModel = model;
7148
7381
  }
7149
- }));
7150
- state.policy = policy;
7151
- const modelsControl = new ModelsControl(pi.events, {
7152
- refresh: async () => {
7153
- const registry = state.registry;
7154
- if (!registry) {
7155
- const message = "Plexus model registry is unavailable before the session starts.";
7156
- log("models:refresh unavailable", { reason: message });
7157
- throw new Error(message);
7158
- }
7159
- const result = await registry.refresh({
7160
- providers: [PROVIDER_NAME],
7161
- force: true
7162
- });
7163
- if (result.aborted) {
7164
- log("models:refresh aborted", {});
7165
- throw new Error("Plexus model refresh was cancelled.");
7166
- }
7167
- const refreshError = result.errors.get(PROVIDER_NAME);
7168
- if (refreshError)
7169
- throw refreshError;
7170
- return { modelCount: state.models.length };
7171
- }
7172
7382
  });
7383
+ const policy = new PolicyController(host);
7384
+ state.policy = policy;
7385
+ createPlexuspiControl(pi, { policy, host });
7173
7386
  pi.on("session_shutdown", () => {
7174
- contextPolicies.dispose();
7175
- serviceTiers.dispose();
7176
- policy.dispose();
7177
- modelsControl.dispose();
7178
- if (state.contextPolicies === contextPolicies)
7179
- state.contextPolicies = undefined;
7180
- if (state.serviceTiers === serviceTiers)
7181
- state.serviceTiers = undefined;
7182
7387
  if (state.policy === policy)
7183
7388
  state.policy = undefined;
7184
7389
  });
@@ -7192,15 +7397,6 @@ function plexusExtension(pi) {
7192
7397
  const startupModels = (storedCatalog?.models ?? []).filter((model) => !isModelSuppressed({ id: model.id, name: model.name }, suppressPatterns));
7193
7398
  state.models = startupModels;
7194
7399
  state.catalogSource = startupModels.length > 0 ? "host store" : "none";
7195
- const startupPolicies = collectStoredContextPolicies(startupModels);
7196
- contextPolicies.setCatalog(startupPolicies.length > 0 ? "ready" : "unavailable", startupPolicies.map((entry) => entry.policy), startupPolicies.length > 0 ? { cached: true, fetchedAt: startupPolicies[0]?.fetchedAt } : { cached: true, reason: CONTEXT_POLICY_METADATA_UNAVAILABLE_REASON });
7197
- if (storedCatalog) {
7198
- const cachedTiers = collectStoredServiceTiers(startupModels);
7199
- serviceTiers.setCatalog(cachedTiers.complete ? "ready" : "unavailable", cachedTiers.policies, cachedTiers.complete ? {
7200
- cached: true,
7201
- ...cachedTiers.fetchedAt === undefined ? {} : { fetchedAt: cachedTiers.fetchedAt }
7202
- } : { cached: true, reason: SERVICE_TIERS_METADATA_UNAVAILABLE_REASON });
7203
- }
7204
7400
  policy.reconcile();
7205
7401
  pi.on("session_start", (_event, ctx) => {
7206
7402
  state.registry = ctx.modelRegistry;
@@ -7280,7 +7476,6 @@ function plexusExtension(pi) {
7280
7476
  });
7281
7477
  }
7282
7478
  async function refreshPlexusModels(state, context) {
7283
- const refreshId = ++state.refreshSequence;
7284
7479
  const baseUrl = getBaseUrl();
7285
7480
  const modelsUrl = getModelsUrl();
7286
7481
  const apiKey = resolveApiKey(credentialApiKey(context.credential));
@@ -7295,19 +7490,6 @@ async function refreshPlexusModels(state, context) {
7295
7490
  },
7296
7491
  update: () => {
7297
7492
  state.models = filteredCurrent;
7298
- const cachedTiers = collectStoredServiceTiers(filteredCurrent);
7299
- state.serviceTiers?.setCatalog(cachedTiers.complete ? "ready" : "unavailable", cachedTiers.policies, cachedTiers.complete ? {
7300
- cached: true,
7301
- ...cachedTiers.fetchedAt === undefined ? {} : { fetchedAt: cachedTiers.fetchedAt }
7302
- } : {
7303
- cached: true,
7304
- reason: SERVICE_TIERS_METADATA_UNAVAILABLE_REASON
7305
- });
7306
- const cachedPolicies = collectStoredContextPolicies(filteredCurrent);
7307
- state.contextPolicies?.setCatalog(cachedPolicies.length > 0 ? "ready" : "unavailable", cachedPolicies.map((entry) => entry.policy), cachedPolicies.length > 0 ? { cached: true, fetchedAt: cachedPolicies[0]?.fetchedAt } : {
7308
- cached: true,
7309
- reason: CONTEXT_POLICY_METADATA_UNAVAILABLE_REASON
7310
- });
7311
7493
  state.policy?.reconcile();
7312
7494
  }
7313
7495
  });
@@ -7316,11 +7498,8 @@ async function refreshPlexusModels(state, context) {
7316
7498
  const restored = await restoreStoredModels(state, context);
7317
7499
  if (restored)
7318
7500
  return restored;
7319
- if (refreshId === state.refreshSequence && state.serviceTiers?.getSnapshot().status === "loading") {
7320
- state.serviceTiers.setCatalog("unavailable", [], {
7321
- reason: "Plexus model metadata is not configured."
7322
- });
7323
- }
7501
+ if (!context.allowNetwork)
7502
+ return [];
7324
7503
  throw new Error(!modelsUrl || !baseUrl ? "Plexus base URL not configured. Run /login plexus first." : "No Plexus API key configured. Run /login plexus first.");
7325
7504
  }
7326
7505
  try {
@@ -7342,9 +7521,12 @@ async function refreshPlexusModels(state, context) {
7342
7521
  policy: serviceTierPolicyFromApiModel(model),
7343
7522
  fetchedAt
7344
7523
  };
7524
+ const shortName = shortNameEntryFromApiModel(model);
7525
+ if (shortName)
7526
+ piModel.plexusShortName = shortName.shortName;
7527
+ else
7528
+ delete piModel.plexusShortName;
7345
7529
  }
7346
- const committedPolicies = collectStoredContextPolicies(piModels);
7347
- const committedServiceTiers = collectStoredServiceTiers(piModels).policies;
7348
7530
  const published = await context.publish({
7349
7531
  persist: {
7350
7532
  models: piModels,
@@ -7353,10 +7535,6 @@ async function refreshPlexusModels(state, context) {
7353
7535
  update: () => {
7354
7536
  state.models = piModels;
7355
7537
  state.catalogSource = "live refresh";
7356
- state.serviceTiers?.setCatalog("ready", committedServiceTiers, {
7357
- fetchedAt
7358
- });
7359
- state.contextPolicies?.setCatalog(committedPolicies.length > 0 ? "ready" : "unavailable", committedPolicies.map((entry) => entry.policy), committedPolicies.length > 0 ? { fetchedAt } : { fetchedAt, reason: CONTEXT_POLICY_METADATA_UNAVAILABLE_REASON });
7360
7538
  state.policy?.reconcile();
7361
7539
  }
7362
7540
  });
@@ -7366,16 +7544,6 @@ async function refreshPlexusModels(state, context) {
7366
7544
  log("refreshModels: fetched", { count: piModels.length });
7367
7545
  return piModels;
7368
7546
  } catch (error) {
7369
- if (refreshId === state.refreshSequence && state.contextPolicies?.getSnapshot().status === "loading") {
7370
- state.contextPolicies.setCatalog("unavailable", [], {
7371
- reason: "Plexus model metadata could not be loaded."
7372
- });
7373
- }
7374
- if (refreshId === state.refreshSequence && state.serviceTiers?.getSnapshot().status === "loading") {
7375
- state.serviceTiers.setCatalog("unavailable", [], {
7376
- reason: "Plexus model metadata could not be loaded."
7377
- });
7378
- }
7379
7547
  log("refreshModels: fetch failed", { error: String(error) });
7380
7548
  throw error;
7381
7549
  }
@@ -7390,16 +7558,6 @@ async function restoreStoredModels(state, context) {
7390
7558
  update: () => {
7391
7559
  state.models = models;
7392
7560
  state.catalogSource = "host store";
7393
- const cachedTiers = collectStoredServiceTiers(models);
7394
- state.serviceTiers?.setCatalog(cachedTiers.complete ? "ready" : "unavailable", cachedTiers.policies, cachedTiers.complete ? {
7395
- cached: true,
7396
- ...cachedTiers.fetchedAt === undefined ? {} : { fetchedAt: cachedTiers.fetchedAt }
7397
- } : { cached: true, reason: SERVICE_TIERS_METADATA_UNAVAILABLE_REASON });
7398
- const cachedPolicies = collectStoredContextPolicies(models);
7399
- state.contextPolicies?.setCatalog(cachedPolicies.length > 0 ? "ready" : "unavailable", cachedPolicies.map((entry) => entry.policy), cachedPolicies.length > 0 ? { cached: true, fetchedAt: cachedPolicies[0]?.fetchedAt } : {
7400
- cached: true,
7401
- reason: CONTEXT_POLICY_METADATA_UNAVAILABLE_REASON
7402
- });
7403
7561
  state.policy?.reconcile();
7404
7562
  }
7405
7563
  });
@@ -7419,12 +7577,6 @@ function contextPolicyFromApiModel(model) {
7419
7577
  pricingThresholdInputTokens
7420
7578
  };
7421
7579
  }
7422
- function collectStoredContextPolicies(models) {
7423
- return models.flatMap((model) => {
7424
- const metadata = model.plexusContextPolicy;
7425
- return metadata ? [metadata] : [];
7426
- });
7427
- }
7428
7580
  function serviceTierPolicyFromApiModel(model) {
7429
7581
  const serviceTiers = model.service_tiers;
7430
7582
  if (!Array.isArray(serviceTiers) || serviceTiers.length === 0)
@@ -7437,15 +7589,16 @@ function serviceTierPolicyFromApiModel(model) {
7437
7589
  const parsed = ServiceTierPolicySchema.safeParse(candidate);
7438
7590
  return parsed.success ? parsed.data : undefined;
7439
7591
  }
7440
- function collectStoredServiceTiers(models) {
7441
- const metadata = models.map((model) => model.plexusServiceTiers);
7442
- const complete = models.length === 0 || metadata.every((entry) => entry !== undefined);
7443
- const stored = metadata.filter((entry) => entry !== undefined);
7444
- return {
7445
- policies: stored.flatMap((entry) => entry.policy ? [entry.policy] : []),
7446
- complete,
7447
- ...stored[0] ? { fetchedAt: stored[0].fetchedAt } : {}
7448
- };
7592
+ function shortNameEntryFromApiModel(model) {
7593
+ const shortName = typeof model.short_name === "string" ? model.short_name.trim() : "";
7594
+ if (!shortName)
7595
+ return;
7596
+ const parsed = ShortNameEntrySchema.safeParse({
7597
+ provider: PROVIDER_NAME,
7598
+ modelId: model.id,
7599
+ shortName
7600
+ });
7601
+ return parsed.success ? parsed.data : undefined;
7449
7602
  }
7450
7603
  function credentialApiKey(credential) {
7451
7604
  if (!credential)
@@ -7542,6 +7695,7 @@ export {
7542
7695
  enforceMinimumOutputTokens,
7543
7696
  normalizeGoogleThinkingConfig,
7544
7697
  serviceTierPolicyFromApiModel,
7698
+ shortNameEntryFromApiModel,
7545
7699
  usesGoogleThinkingLevel,
7546
7700
  withAuthoritativeApiKeyEnv
7547
7701
  };