@mcowger/opencode-plexus 1.12.0 → 1.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +597 -73
  2. package/package.json +2 -2
package/dist/index.js CHANGED
@@ -2,57 +2,12 @@
2
2
  // src/plugin.ts
3
3
  import { Plugin, Provider } from "@opencode/plugin";
4
4
 
5
- // ../plexus-models/src/suppress.ts
6
- function parseSuppressionPatterns(raw) {
7
- if (!raw)
8
- return [];
9
- const items = Array.isArray(raw) ? raw : raw.split(/[\n,;]+/);
10
- return items.map((s) => s.trim()).filter((s) => s.length > 0);
11
- }
12
- function getEnvSuppressedModels() {
13
- const env = typeof process !== "undefined" && process?.env ? process.env : {};
14
- const raw = env.PLEXUS_SUPPRESS_MODELS ?? env.PLEXUS_EXCLUDE_MODELS;
15
- return parseSuppressionPatterns(raw);
16
- }
17
- function isModelSuppressed(model, patterns) {
18
- const envPatterns = getEnvSuppressedModels();
19
- const explicitPatterns = parseSuppressionPatterns(patterns);
20
- const allPatterns = [...envPatterns, ...explicitPatterns];
21
- if (allPatterns.length === 0)
22
- return false;
23
- const id = model.id.toLowerCase();
24
- const name = (model.name ?? "").toLowerCase();
25
- const shortId = id.includes("/") ? id.split("/").pop() : id.includes(":") ? id.split(":").pop() : id;
26
- for (const pattern of allPatterns) {
27
- if (matchesPattern(id, name, shortId, pattern)) {
28
- return true;
29
- }
30
- }
31
- return false;
32
- }
33
- function matchesPattern(id, name, shortId, pattern) {
34
- const p = pattern.toLowerCase();
35
- if (p.startsWith("regex:")) {
36
- try {
37
- const re = new RegExp(pattern.slice(6), "i");
38
- return re.test(id) || re.test(name) || re.test(shortId);
39
- } catch {
40
- return false;
41
- }
42
- }
43
- if (p.includes("*") || p.includes("?")) {
44
- const regexStr = "^" + p.replace(/([.+^${}()|[\]\\])/g, "\\$1").replace(/\*/g, ".*").replace(/\?/g, ".") + "$";
45
- try {
46
- const re = new RegExp(regexStr, "i");
47
- return re.test(id) || re.test(name) || re.test(shortId);
48
- } catch {
49
- return false;
50
- }
51
- }
52
- return id === p || name === p || shortId === p;
53
- }
54
5
  // ../plexus-models/src/convert.ts
55
- var REASONING_PARAMS = new Set(["reasoning", "include_reasoning", "reasoning_effort"]);
6
+ var REASONING_PARAMS = new Set([
7
+ "reasoning",
8
+ "include_reasoning",
9
+ "reasoning_effort"
10
+ ]);
56
11
  var NON_CHAT_PATTERN = /(?:^|[\W_])(?:embed(?:ding|dings)?|transcri(?:be[ds]?|ptions?)|whisper|speech[\W_]*to[\W_]*text|stt|text[\W_]*to[\W_]*speech|tts|image(?:[\W_]*(?:gen(?:eration)?|\d+))?|diffusion|dall[\W_]*e|stable[\W_]*diffusion|sdxl|dream)(?:$|[\W_])/i;
57
12
  var API_DIALECT_MAP = {
58
13
  chat_completions: "openai-completions",
@@ -147,6 +102,56 @@ async function fetchPlexusModels(apiKey, modelsUrl, timeoutMs = DEFAULT_MODELS_F
147
102
  clearTimeout(timer);
148
103
  }
149
104
  }
105
+ // ../plexus-models/src/suppress.ts
106
+ function parseSuppressionPatterns(raw) {
107
+ if (!raw)
108
+ return [];
109
+ const items = Array.isArray(raw) ? raw : raw.split(/[\n,;]+/);
110
+ return items.map((s) => s.trim()).filter((s) => s.length > 0);
111
+ }
112
+ function getEnvSuppressedModels() {
113
+ const env = typeof process !== "undefined" && process?.env ? process.env : {};
114
+ const raw = env.PLEXUS_SUPPRESS_MODELS ?? env.PLEXUS_EXCLUDE_MODELS;
115
+ return parseSuppressionPatterns(raw);
116
+ }
117
+ function isModelSuppressed(model, patterns) {
118
+ const envPatterns = getEnvSuppressedModels();
119
+ const explicitPatterns = parseSuppressionPatterns(patterns);
120
+ const allPatterns = [...envPatterns, ...explicitPatterns];
121
+ if (allPatterns.length === 0)
122
+ return false;
123
+ const id = model.id.toLowerCase();
124
+ const name = (model.name ?? "").toLowerCase();
125
+ const separator = id.includes("/") ? "/" : id.includes(":") ? ":" : undefined;
126
+ const shortId = separator === undefined ? id : id.split(separator).pop() ?? id;
127
+ for (const pattern of allPatterns) {
128
+ if (matchesPattern(id, name, shortId, pattern)) {
129
+ return true;
130
+ }
131
+ }
132
+ return false;
133
+ }
134
+ function matchesPattern(id, name, shortId, pattern) {
135
+ const p = pattern.toLowerCase();
136
+ if (p.startsWith("regex:")) {
137
+ try {
138
+ const re = new RegExp(pattern.slice(6), "i");
139
+ return re.test(id) || re.test(name) || re.test(shortId);
140
+ } catch {
141
+ return false;
142
+ }
143
+ }
144
+ if (p.includes("*") || p.includes("?")) {
145
+ const regexStr = "^" + p.replace(/([.+^${}()|[\]\\])/g, "\\$1").replace(/\*/g, ".*").replace(/\?/g, ".") + "$";
146
+ try {
147
+ const re = new RegExp(regexStr, "i");
148
+ return re.test(id) || re.test(name) || re.test(shortId);
149
+ } catch {
150
+ return false;
151
+ }
152
+ }
153
+ return id === p || name === p || shortId === p;
154
+ }
150
155
  // src/cache.ts
151
156
  import { mkdir, readFile, writeFile } from "fs/promises";
152
157
  import { homedir } from "os";
@@ -169,9 +174,11 @@ var ENV_API_KEY = "PLEXUS_API_KEY";
169
174
  var PLEXUS_SUPPRESS_MODELS_OPTION = "suppressModels";
170
175
  var MODELS_FETCH_TIMEOUT_MS = 1e4;
171
176
  var REFRESH_TTL_MS = 60000;
172
- var CACHE_VERSION = 2;
177
+ var CACHE_VERSION = 3;
173
178
  var PLACEHOLDER_MODEL_ID = "plexus-unconfigured";
174
179
  var PLEXUS_REFRESH_COMMAND = "plexus-refresh";
180
+ var PLEXUS_TIER_COMMAND = "plexus-tier";
181
+ var PLEXUS_CONTEXT_COMMAND = "plexus-context";
175
182
 
176
183
  // src/cache.ts
177
184
  var PLUGIN_SUBDIR = join("plugins", "plexus");
@@ -215,11 +222,16 @@ async function writeCache(models, raw, etag) {
215
222
  try {
216
223
  const dir = getDir();
217
224
  await mkdir(dir, { recursive: true });
218
- const cache = { version: CACHE_VERSION, models, timestamp: Date.now(), etag };
219
- await writeFile(join(dir, CACHE_FILE), JSON.stringify(cache, null, 2) + `
225
+ const cache = {
226
+ version: CACHE_VERSION,
227
+ models,
228
+ timestamp: Date.now(),
229
+ etag
230
+ };
231
+ await writeFile(join(dir, CACHE_FILE), `${JSON.stringify(cache, null, 2)}
220
232
  `, "utf8");
221
233
  if (raw !== undefined) {
222
- await writeFile(join(dir, RAW_FILE), JSON.stringify(raw, null, 2) + `
234
+ await writeFile(join(dir, RAW_FILE), `${JSON.stringify(raw, null, 2)}
223
235
  `, "utf8");
224
236
  }
225
237
  } catch {}
@@ -334,7 +346,7 @@ function resolveConfig(options, credential) {
334
346
  const envApiKey = process.env[ENV_API_KEY];
335
347
  const metaBaseURL = credential ? metadataBaseURL(credential) : undefined;
336
348
  const optBaseURL = resolveStringOption(options?.[PLEXUS_BASE_URL_OPTION]);
337
- const optApiKey = resolveStringOption(options?.["apiKey"]);
349
+ const optApiKey = resolveStringOption(options?.apiKey);
338
350
  const baseURL = (envBaseURL ? rootURL(envBaseURL) : undefined) || (metaBaseURL ? rootURL(metaBaseURL) : undefined) || (optBaseURL ? rootURL(optBaseURL) : undefined) || undefined;
339
351
  const apiKey = explicitApiKey || (envApiKey ? envApiKey.trim() : undefined) || credential?.key?.trim() || optApiKey || undefined;
340
352
  return {
@@ -344,7 +356,7 @@ function resolveConfig(options, credential) {
344
356
  }
345
357
  function getSuppressedModels(options) {
346
358
  const envSuppressed = getEnvSuppressedModels();
347
- const opt = options?.["suppressModels"] ?? options?.["suppress"] ?? options?.["suppress_models"];
359
+ const opt = options?.suppressModels ?? options?.suppress ?? options?.suppress_models;
348
360
  const optSuppressed = parseSuppressionPatterns(opt);
349
361
  return [...envSuppressed, ...optSuppressed];
350
362
  }
@@ -377,8 +389,327 @@ function createLogger(prefix = "plexus") {
377
389
  };
378
390
  }
379
391
 
392
+ // src/session-policy.ts
393
+ var CONTEXT_BUDGET_OPTION = "plexusContextBudget";
394
+ var DEFAULT_SELECTION = Object.freeze({
395
+ longContext: true,
396
+ serviceTier: null
397
+ });
398
+ function defaultSelection() {
399
+ return { ...DEFAULT_SELECTION };
400
+ }
401
+ function isPositiveSafeInt(value) {
402
+ return typeof value === "number" && Number.isSafeInteger(value) && value > 0;
403
+ }
404
+ function validServiceTiers(raw) {
405
+ if (!Array.isArray(raw) || raw.length === 0 || raw.length > 64)
406
+ return;
407
+ const tiers = [];
408
+ for (const entry of raw) {
409
+ if (typeof entry !== "string" || entry.length === 0 || entry.length > 100)
410
+ return;
411
+ tiers.push(entry);
412
+ }
413
+ if (new Set(tiers).size !== tiers.length)
414
+ return;
415
+ return tiers;
416
+ }
417
+ function policyAdvertisementFromApiModel(model) {
418
+ const serviceTiers = validServiceTiers(model.service_tiers);
419
+ const maxContextTokens = model.context_length;
420
+ const shortBudget = model.pricing?.tiers?.[0]?.input_tokens_above;
421
+ const contextValid = isPositiveSafeInt(maxContextTokens) && isPositiveSafeInt(shortBudget) && shortBudget <= maxContextTokens;
422
+ if (serviceTiers === undefined && !contextValid)
423
+ return;
424
+ return {
425
+ serviceTiers: serviceTiers ?? [],
426
+ ...contextValid ? {
427
+ shortContextBudgetTokens: shortBudget,
428
+ maxContextTokens
429
+ } : {}
430
+ };
431
+ }
432
+ function policyAvailability(policy) {
433
+ return {
434
+ longContext: policy !== undefined && policy.shortContextBudgetTokens !== undefined && policy.maxContextTokens !== undefined && policy.shortContextBudgetTokens < policy.maxContextTokens,
435
+ serviceTier: (policy?.serviceTiers.length ?? 0) > 0
436
+ };
437
+ }
438
+ function effectiveContextWindow(policy, selection) {
439
+ if (policy?.shortContextBudgetTokens === undefined || policy.maxContextTokens === undefined)
440
+ return;
441
+ if (!selection.longContext && policy.shortContextBudgetTokens < policy.maxContextTokens) {
442
+ return policy.shortContextBudgetTokens;
443
+ }
444
+ return policy.maxContextTokens;
445
+ }
446
+ function injectServiceTier(payload, tier) {
447
+ if (tier === null || tier === undefined)
448
+ return payload;
449
+ if (!payload || typeof payload !== "object" || Array.isArray(payload))
450
+ return payload;
451
+ return { ...payload, service_tier: tier };
452
+ }
453
+ function injectServiceTierIntoBody(bodyText, tier) {
454
+ let parsed;
455
+ try {
456
+ parsed = JSON.parse(bodyText);
457
+ } catch {
458
+ return;
459
+ }
460
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
461
+ return;
462
+ if (parsed.service_tier === tier)
463
+ return;
464
+ return JSON.stringify(injectServiceTier(parsed, tier));
465
+ }
466
+ async function withServiceTier(request, tier) {
467
+ if (tier === null)
468
+ return;
469
+ if (request.method === "GET" || request.method === "HEAD")
470
+ return;
471
+ const contentType = request.headers.get("content-type");
472
+ if (!contentType?.includes("application/json"))
473
+ return;
474
+ let text;
475
+ try {
476
+ text = await request.clone().text();
477
+ } catch {
478
+ return;
479
+ }
480
+ if (text === "")
481
+ return;
482
+ const replacement = injectServiceTierIntoBody(text, tier);
483
+ if (replacement === undefined)
484
+ return;
485
+ const headers = new Headers(request.headers);
486
+ headers.delete("content-length");
487
+ return new Request(request.url, {
488
+ method: request.method,
489
+ headers,
490
+ body: replacement
491
+ });
492
+ }
493
+ function formatTiers(policy) {
494
+ if (!policy || policy.serviceTiers.length === 0)
495
+ return "no service tiers";
496
+ return policy.serviceTiers.join(", ");
497
+ }
498
+ function formatBudget(policy) {
499
+ if (policy?.shortContextBudgetTokens === undefined || policy.maxContextTokens === undefined)
500
+ return "no context budget";
501
+ return `short ${policy.shortContextBudgetTokens} / max ${policy.maxContextTokens}`;
502
+ }
503
+ function formatTierStatus(modelID, selection, policy) {
504
+ const active = selection.serviceTier ?? "default (provider default)";
505
+ return `Plexus service tier for ${modelID} (this session): ${active}. ` + `Advertised tiers: ${formatTiers(policy)}. ` + `Change with /plexus-tier <tier|default>.`;
506
+ }
507
+ function formatContextStatus(modelID, selection, policy, effectiveWindow) {
508
+ const mode = selection.longContext ? "max" : "short";
509
+ const window = effectiveWindow === undefined ? "unknown" : String(effectiveWindow);
510
+ return `Plexus context for ${modelID} (this session): ${mode} (${window} tokens). ` + `Advertised budget: ${formatBudget(policy)}. ` + `Change with /plexus-context <short|max>.`;
511
+ }
512
+ function firstToken(text) {
513
+ return (text ?? "").trim().split(/\s+/)[0] ?? "";
514
+ }
515
+ function parseTierCommand(text) {
516
+ const arg = firstToken(text);
517
+ if (arg === "" || arg.toLowerCase() === "status")
518
+ return { kind: "status" };
519
+ if (arg.toLowerCase() === "default")
520
+ return { kind: "clear" };
521
+ return { kind: "select", tier: arg };
522
+ }
523
+ function parseContextCommand(text) {
524
+ const arg = firstToken(text);
525
+ if (arg === "" || arg.toLowerCase() === "status")
526
+ return { kind: "status" };
527
+ if (arg.toLowerCase() === "short")
528
+ return { kind: "short" };
529
+ if (arg.toLowerCase() === "max")
530
+ return { kind: "max" };
531
+ return { kind: "invalid", value: arg };
532
+ }
533
+ function sameModel(a, b) {
534
+ return a.providerID === b.providerID && a.id === b.id;
535
+ }
536
+ function validateSelection(policy, patch) {
537
+ if (patch.longContext === false) {
538
+ if (policy?.shortContextBudgetTokens === undefined || policy.maxContextTokens === undefined)
539
+ return "No context budget is advertised for the active model.";
540
+ if (policy.shortContextBudgetTokens >= policy.maxContextTokens) {
541
+ return "The active model has no distinct short and maximum context budget.";
542
+ }
543
+ }
544
+ if (patch.serviceTier !== undefined && patch.serviceTier !== null) {
545
+ if (!policy?.serviceTiers.includes(patch.serviceTier)) {
546
+ return "The requested service tier is not advertised for the active model.";
547
+ }
548
+ }
549
+ return;
550
+ }
551
+
552
+ class SessionPolicyStore {
553
+ catalog = new Map;
554
+ sessions = new Map;
555
+ setCatalog(models) {
556
+ const previous = this.catalog;
557
+ const next = new Map;
558
+ for (const model of models) {
559
+ if (model.policy)
560
+ next.set(model.id, model.policy);
561
+ }
562
+ this.catalog = next;
563
+ return this.reconcile(previous);
564
+ }
565
+ policyFor(modelID) {
566
+ return this.catalog.get(modelID);
567
+ }
568
+ lastBoundModel(sessionID) {
569
+ const entry = this.sessions.get(sessionID);
570
+ return entry ? { ...entry.boundModel } : undefined;
571
+ }
572
+ ensureBound(sessionID, model) {
573
+ const entry = this.sessions.get(sessionID);
574
+ if (!entry) {
575
+ this.sessions.set(sessionID, {
576
+ boundModel: { providerID: model.providerID, id: model.id },
577
+ selection: defaultSelection()
578
+ });
579
+ return false;
580
+ }
581
+ if (sameModel(entry.boundModel, model))
582
+ return false;
583
+ entry.boundModel = { providerID: model.providerID, id: model.id };
584
+ entry.selection = defaultSelection();
585
+ return true;
586
+ }
587
+ select(sessionID, model, patch) {
588
+ this.ensureBound(sessionID, model);
589
+ const entry = this.sessions.get(sessionID);
590
+ if (!entry) {
591
+ const selection = defaultSelection();
592
+ return { ok: false, reason: "No session selection.", selection };
593
+ }
594
+ const policy = this.catalog.get(entry.boundModel.id);
595
+ const reason = validateSelection(policy, patch);
596
+ if (reason !== undefined) {
597
+ return { ok: false, reason, selection: { ...entry.selection } };
598
+ }
599
+ if (patch.longContext !== undefined)
600
+ entry.selection.longContext = patch.longContext;
601
+ if (patch.serviceTier !== undefined)
602
+ entry.selection.serviceTier = patch.serviceTier;
603
+ return { ok: true, selection: { ...entry.selection } };
604
+ }
605
+ status(sessionID, model) {
606
+ const reset = this.ensureBound(sessionID, model);
607
+ const entry = this.sessions.get(sessionID);
608
+ const selection = entry ? { ...entry.selection } : defaultSelection();
609
+ const policy = this.catalog.get(model.id);
610
+ return {
611
+ selection,
612
+ policy,
613
+ available: policyAvailability(policy),
614
+ effectiveWindow: effectiveContextWindow(policy, selection),
615
+ reset
616
+ };
617
+ }
618
+ tierForRequest(sessionID, model) {
619
+ try {
620
+ this.ensureBound(sessionID, model);
621
+ const entry = this.sessions.get(sessionID);
622
+ if (!entry || !sameModel(entry.boundModel, model))
623
+ return null;
624
+ const policy = this.catalog.get(entry.boundModel.id);
625
+ if (!policy || policy.serviceTiers.length === 0)
626
+ return null;
627
+ const tier = entry.selection.serviceTier;
628
+ if (tier === null || !policy.serviceTiers.includes(tier))
629
+ return null;
630
+ return tier;
631
+ } catch {
632
+ return null;
633
+ }
634
+ }
635
+ contextBudgetForRequest(sessionID, model) {
636
+ try {
637
+ this.ensureBound(sessionID, model);
638
+ const entry = this.sessions.get(sessionID);
639
+ if (!entry || !sameModel(entry.boundModel, model))
640
+ return;
641
+ return effectiveContextWindow(this.catalog.get(entry.boundModel.id), entry.selection);
642
+ } catch {
643
+ return;
644
+ }
645
+ }
646
+ applyToOptions(options, sessionID, model) {
647
+ const budget = this.contextBudgetForRequest(sessionID, model);
648
+ if (budget === undefined)
649
+ delete options[CONTEXT_BUDGET_OPTION];
650
+ else
651
+ options[CONTEXT_BUDGET_OPTION] = budget;
652
+ }
653
+ reconcile(previous) {
654
+ const changes = [];
655
+ for (const [sessionID, entry] of this.sessions) {
656
+ const policy = this.catalog.get(entry.boundModel.id);
657
+ const before = { ...entry.selection };
658
+ const beforeWindow = effectiveContextWindow(previous?.get(entry.boundModel.id) ?? policy, before);
659
+ let reason;
660
+ if (policy?.shortContextBudgetTokens === undefined) {
661
+ if (!entry.selection.longContext) {
662
+ entry.selection.longContext = true;
663
+ reason = "The active model no longer advertises a short context budget.";
664
+ }
665
+ } else if (policy.shortContextBudgetTokens >= policy.maxContextTokens && !entry.selection.longContext) {
666
+ entry.selection.longContext = true;
667
+ reason = "The active model no longer advertises a distinct short context budget.";
668
+ }
669
+ if (entry.selection.serviceTier !== null) {
670
+ if (!policy?.serviceTiers.includes(entry.selection.serviceTier)) {
671
+ entry.selection.serviceTier = null;
672
+ reason = "The selected service tier is no longer advertised for the active model.";
673
+ }
674
+ }
675
+ const afterWindow = effectiveContextWindow(policy, entry.selection);
676
+ const tierChanged = entry.selection.serviceTier !== before.serviceTier;
677
+ const contextChanged = entry.selection.longContext !== before.longContext;
678
+ if (tierChanged) {
679
+ changes.push({
680
+ sessionID,
681
+ modelID: entry.boundModel.id,
682
+ kind: "tier-cleared",
683
+ detail: reason ?? "Service tier selection cleared."
684
+ });
685
+ }
686
+ if (contextChanged) {
687
+ changes.push({
688
+ sessionID,
689
+ modelID: entry.boundModel.id,
690
+ kind: "context-reset-max",
691
+ detail: reason ?? "Context selection reset to the maximum budget."
692
+ });
693
+ }
694
+ if (!entry.selection.longContext && beforeWindow !== undefined && afterWindow !== undefined && afterWindow !== beforeWindow) {
695
+ changes.push({
696
+ sessionID,
697
+ modelID: entry.boundModel.id,
698
+ kind: "short-lowered",
699
+ detail: `Short context budget changed ${beforeWindow} -> ${afterWindow}; re-applied.`
700
+ });
701
+ }
702
+ }
703
+ return changes;
704
+ }
705
+ }
706
+
380
707
  // src/mapper.ts
381
- var REASONING_PARAMS2 = new Set(["reasoning", "include_reasoning", "reasoning_effort"]);
708
+ var REASONING_PARAMS2 = new Set([
709
+ "reasoning",
710
+ "include_reasoning",
711
+ "reasoning_effort"
712
+ ]);
382
713
  var OPEN_CODE_NONE = "none";
383
714
  var DEFAULT_CONTEXT = 250000;
384
715
  var PER_TOKEN_TO_PER_MILLION = 1e6;
@@ -390,7 +721,9 @@ function reasoningVariantSettings(preferredApi, effort) {
390
721
  case "anthropic-messages":
391
722
  return { effort };
392
723
  case "google-generative-ai":
393
- return { thinkingConfig: { includeThoughts: true, thinkingLevel: effort } };
724
+ return {
725
+ thinkingConfig: { includeThoughts: true, thinkingLevel: effort }
726
+ };
394
727
  default:
395
728
  return { reasoningEffort: effort };
396
729
  }
@@ -403,7 +736,10 @@ function buildReasoningVariants(model, preferredApi, hasReasoning) {
403
736
  return;
404
737
  return effortOption.values.map((value) => {
405
738
  const effort = normalizeReasoningEffort(value);
406
- return { id: effort, settings: reasoningVariantSettings(preferredApi, effort) };
739
+ return {
740
+ id: effort,
741
+ settings: reasoningVariantSettings(preferredApi, effort)
742
+ };
407
743
  });
408
744
  }
409
745
  function resolveModelPackage(preferredApi) {
@@ -414,7 +750,6 @@ function resolveModelPackage(preferredApi) {
414
750
  return GOOGLE_PKG;
415
751
  case "openai-responses":
416
752
  return OPENAI_RESPONSES_PKG;
417
- case "openai-completions":
418
753
  default:
419
754
  return;
420
755
  }
@@ -528,6 +863,7 @@ function buildModels(models, apiBaseURL, suppress) {
528
863
  const preferredApi = mapPreferredApi(m.preferred_api);
529
864
  const pkg = resolveModelPackage(preferredApi);
530
865
  const compatibility = reasoningCompatibility(m, preferredApi);
866
+ const policy = policyAdvertisementFromApiModel(m);
531
867
  const hasReasoning = params.some((p) => REASONING_PARAMS2.has(p));
532
868
  const variants = buildReasoningVariants(m, preferredApi, hasReasoning);
533
869
  const cost = [];
@@ -553,6 +889,7 @@ function buildModels(models, apiBaseURL, suppress) {
553
889
  name: m.name ?? m.id,
554
890
  ...compatibility ? { compatibility } : {},
555
891
  ...pkg ? { package: pkg } : {},
892
+ ...policy ? { policy } : {},
556
893
  settings: { baseURL: resolveModelBaseURL(preferredApi, apiBaseURL) },
557
894
  capabilities: {
558
895
  tools: params.includes("tools"),
@@ -604,7 +941,7 @@ async function resolveConnectionCredential(ctx, log) {
604
941
  if (!connection)
605
942
  return { connection: undefined, credential: undefined };
606
943
  const resolved = await ctx.integration.connection.resolve(connection);
607
- if (!resolved || resolved.type !== "key") {
944
+ if (resolved?.type !== "key") {
608
945
  return { connection, credential: undefined };
609
946
  }
610
947
  return {
@@ -630,7 +967,12 @@ function refreshModels(baseURL, log, apiKey, force = false, suppress) {
630
967
  const run = async () => {
631
968
  const url = modelsUrl(baseURL);
632
969
  const cached = await readCachedModels(suppress);
633
- const { models: apiModels, raw, etag, notModified } = await fetchPlexusModels(apiKey ?? "", url, MODELS_FETCH_TIMEOUT_MS, cached?.etag);
970
+ const {
971
+ models: apiModels,
972
+ raw,
973
+ etag,
974
+ notModified
975
+ } = await fetchPlexusModels(apiKey ?? "", url, MODELS_FETCH_TIMEOUT_MS, cached?.etag);
634
976
  if (notModified && cached?.models) {
635
977
  log.info(`Plexus models not modified (etag: ${cached.etag})`);
636
978
  lastRefresh = { at: Date.now(), models: cached.models };
@@ -657,9 +999,21 @@ async function loadSource(ctx, log, options, force) {
657
999
  const cached = await readCachedModels(suppress);
658
1000
  if (cached && cached.models.length > 0) {
659
1001
  log.info(`Loaded plexus cache with ${cached.models.length} models`);
660
- return { models: cached.models, baseURL, apiKey, connection };
1002
+ return {
1003
+ models: cached.models,
1004
+ baseURL,
1005
+ apiKey,
1006
+ connection,
1007
+ fresh: false
1008
+ };
661
1009
  }
662
- return { models: [placeholderModel()], baseURL, apiKey, connection };
1010
+ return {
1011
+ models: [placeholderModel()],
1012
+ baseURL,
1013
+ apiKey,
1014
+ connection,
1015
+ fresh: false
1016
+ };
663
1017
  }
664
1018
  try {
665
1019
  const models = await refreshModels(baseURL, log, apiKey, force, suppress);
@@ -670,17 +1024,30 @@ async function loadSource(ctx, log, options, force) {
670
1024
  models: cached && cached.models.length > 0 ? cached.models : [placeholderModel()],
671
1025
  baseURL,
672
1026
  apiKey,
673
- connection
1027
+ connection,
1028
+ fresh: true
674
1029
  };
675
1030
  }
676
- return { models, baseURL, apiKey, connection };
1031
+ return { models, baseURL, apiKey, connection, fresh: true };
677
1032
  } catch (e) {
678
1033
  log.warn(`Live plexus refresh failed, using cache: ${String(e)}`);
679
1034
  const cached = await readCachedModels(suppress);
680
1035
  if (cached && cached.models.length > 0) {
681
- return { models: cached.models, baseURL, apiKey, connection };
1036
+ return {
1037
+ models: cached.models,
1038
+ baseURL,
1039
+ apiKey,
1040
+ connection,
1041
+ fresh: false
1042
+ };
682
1043
  }
683
- return { models: [placeholderModel()], baseURL, apiKey, connection };
1044
+ return {
1045
+ models: [placeholderModel()],
1046
+ baseURL,
1047
+ apiKey,
1048
+ connection,
1049
+ fresh: false
1050
+ };
684
1051
  }
685
1052
  }
686
1053
  function providerInfo(source) {
@@ -698,18 +1065,61 @@ function providerInfo(source) {
698
1065
  };
699
1066
  return info;
700
1067
  }
1068
+ async function resolveCommandModel(ctx, policyStore, sessionID) {
1069
+ try {
1070
+ const session = ctx.session;
1071
+ if (typeof session.get === "function") {
1072
+ const result = await session.get({ sessionID });
1073
+ const envelope = result;
1074
+ const info = envelope?.data ?? result;
1075
+ const model = info?.model;
1076
+ if (model && typeof model.providerID === "string" && typeof model.id === "string") {
1077
+ if (model.providerID === PLEXUS_PROVIDER_ID) {
1078
+ return {
1079
+ kind: "plexus",
1080
+ ref: { providerID: model.providerID, id: model.id }
1081
+ };
1082
+ }
1083
+ return {
1084
+ kind: "other",
1085
+ providerID: model.providerID,
1086
+ id: model.id
1087
+ };
1088
+ }
1089
+ }
1090
+ } catch {}
1091
+ const bound = policyStore.lastBoundModel(sessionID);
1092
+ if (bound && bound.providerID === PLEXUS_PROVIDER_ID)
1093
+ return { kind: "plexus", ref: bound };
1094
+ if (bound)
1095
+ return { kind: "other", providerID: bound.providerID, id: bound.id };
1096
+ return { kind: "unknown" };
1097
+ }
701
1098
  var plugin_default = Plugin.define({
702
1099
  id: PLEXUS_PLUGIN_ID,
703
1100
  async setup(ctx) {
704
1101
  const log = createLogger();
705
1102
  const options = ctx.options ?? {};
706
- const source = { models: [], baseURL: undefined, apiKey: undefined, connection: undefined };
1103
+ const source = {
1104
+ models: [],
1105
+ baseURL: undefined,
1106
+ apiKey: undefined,
1107
+ connection: undefined,
1108
+ fresh: false
1109
+ };
1110
+ const policyStore = new SessionPolicyStore;
707
1111
  const reloadSource = async (force) => {
708
1112
  const next = await loadSource(ctx, log, options, force);
709
1113
  source.models = next.models;
710
1114
  source.baseURL = next.baseURL;
711
1115
  source.apiKey = next.apiKey;
712
1116
  source.connection = next.connection;
1117
+ if (next.fresh) {
1118
+ const changes = policyStore.setCatalog(source.models);
1119
+ for (const change of changes) {
1120
+ log.info(`Session policy reconciled (session ${change.sessionID} / ${change.modelID}): ${change.detail}`);
1121
+ }
1122
+ }
713
1123
  };
714
1124
  try {
715
1125
  await reloadSource(false);
@@ -733,13 +1143,13 @@ var plugin_default = Plugin.define({
733
1143
  editor.update(providerID, (provider) => {
734
1144
  const settings = provider.settings ?? {};
735
1145
  if (source.baseURL)
736
- settings["baseURL"] = apiBase(source.baseURL);
1146
+ settings.baseURL = apiBase(source.baseURL);
737
1147
  else
738
- delete settings["baseURL"];
1148
+ delete settings.baseURL;
739
1149
  if (source.apiKey)
740
- settings["apiKey"] = source.apiKey;
1150
+ settings.apiKey = source.apiKey;
741
1151
  else
742
- delete settings["apiKey"];
1152
+ delete settings.apiKey;
743
1153
  provider.settings = settings;
744
1154
  });
745
1155
  });
@@ -803,7 +1213,107 @@ var plugin_default = Plugin.define({
803
1213
  });
804
1214
  }
805
1215
  });
1216
+ editor.add({
1217
+ name: PLEXUS_TIER_COMMAND,
1218
+ description: "Select the Plexus service tier for this session (tier|default|status)",
1219
+ execute: async ({ sessionID, prompt, delivery }) => {
1220
+ const reply = async (text) => {
1221
+ await ctx.session.synthetic({
1222
+ sessionID,
1223
+ text,
1224
+ description: text,
1225
+ delivery,
1226
+ resume: false
1227
+ });
1228
+ };
1229
+ const resolved = await resolveCommandModel(ctx, policyStore, sessionID);
1230
+ if (resolved.kind !== "plexus") {
1231
+ await reply(resolved.kind === "other" ? `/plexus-tier applies to Plexus models; this session uses ${resolved.providerID}/${resolved.id}.` : "No active Plexus model for this session yet; select a Plexus model first, then retry.");
1232
+ return;
1233
+ }
1234
+ const ref = resolved.ref;
1235
+ const command = parseTierCommand(typeof prompt?.text === "string" ? prompt.text : undefined);
1236
+ if (command.kind === "status") {
1237
+ const state = policyStore.status(sessionID, ref);
1238
+ await reply(formatTierStatus(ref.id, state.selection, state.policy));
1239
+ return;
1240
+ }
1241
+ if (command.kind === "clear") {
1242
+ policyStore.select(sessionID, ref, { serviceTier: null });
1243
+ log.info(`Session ${sessionID} cleared plexus tier for ${ref.id}`);
1244
+ await reply(`Plexus service tier for ${ref.id} (this session): default (provider default).`);
1245
+ return;
1246
+ }
1247
+ const result = policyStore.select(sessionID, ref, {
1248
+ serviceTier: command.tier
1249
+ });
1250
+ if (result.ok) {
1251
+ log.info(`Session ${sessionID} selected plexus tier ${command.tier} for ${ref.id}`);
1252
+ await reply(`Plexus service tier for ${ref.id} (this session): ${command.tier}. Applies to subsequent requests in this session.`);
1253
+ } else {
1254
+ const state = policyStore.status(sessionID, ref);
1255
+ await reply(`Plexus tier not changed: ${result.reason} ` + formatTierStatus(ref.id, state.selection, state.policy));
1256
+ }
1257
+ }
1258
+ });
1259
+ editor.add({
1260
+ name: PLEXUS_CONTEXT_COMMAND,
1261
+ description: "Select the Plexus context budget for this session (short|max|status)",
1262
+ execute: async ({ sessionID, prompt, delivery }) => {
1263
+ const reply = async (text) => {
1264
+ await ctx.session.synthetic({
1265
+ sessionID,
1266
+ text,
1267
+ description: text,
1268
+ delivery,
1269
+ resume: false
1270
+ });
1271
+ };
1272
+ const resolved = await resolveCommandModel(ctx, policyStore, sessionID);
1273
+ if (resolved.kind !== "plexus") {
1274
+ await reply(resolved.kind === "other" ? `/plexus-context applies to Plexus models; this session uses ${resolved.providerID}/${resolved.id}.` : "No active Plexus model for this session yet; select a Plexus model first, then retry.");
1275
+ return;
1276
+ }
1277
+ const ref = resolved.ref;
1278
+ const command = parseContextCommand(typeof prompt?.text === "string" ? prompt.text : undefined);
1279
+ if (command.kind === "status") {
1280
+ const state = policyStore.status(sessionID, ref);
1281
+ await reply(formatContextStatus(ref.id, state.selection, state.policy, state.effectiveWindow));
1282
+ return;
1283
+ }
1284
+ if (command.kind === "invalid") {
1285
+ await reply(`Unknown context selection "${command.value}". Usage: /plexus-context <short|max|status>.`);
1286
+ return;
1287
+ }
1288
+ const result = policyStore.select(sessionID, ref, {
1289
+ longContext: command.kind === "max"
1290
+ });
1291
+ if (result.ok) {
1292
+ log.info(`Session ${sessionID} selected plexus context ${command.kind} for ${ref.id}`);
1293
+ const state = policyStore.status(sessionID, ref);
1294
+ await reply(formatContextStatus(ref.id, state.selection, state.policy, state.effectiveWindow));
1295
+ } else {
1296
+ const state = policyStore.status(sessionID, ref);
1297
+ await reply(`Plexus context not changed: ${result.reason} ` + formatContextStatus(ref.id, state.selection, state.policy, state.effectiveWindow));
1298
+ }
1299
+ }
1300
+ });
806
1301
  });
1302
+ const plexusScope = { providerID: PLEXUS_PROVIDER_ID };
1303
+ await ctx.session.hook("context", (event) => {
1304
+ policyStore.applyToOptions(event.options, event.sessionID, event.model);
1305
+ }, plexusScope);
1306
+ await ctx.session.hook("compaction", (event) => {
1307
+ policyStore.applyToOptions(event.options, event.sessionID, event.model);
1308
+ }, plexusScope);
1309
+ await ctx.session.hook("http.request", async (event) => {
1310
+ const tier = policyStore.tierForRequest(event.sessionID, event.model);
1311
+ if (tier === null)
1312
+ return;
1313
+ const replacement = await withServiceTier(event.request, tier);
1314
+ if (replacement)
1315
+ event.request = replacement;
1316
+ }, plexusScope);
807
1317
  (async () => {
808
1318
  let pending = null;
809
1319
  for await (const event of ctx.event.subscribe()) {
@@ -835,6 +1345,7 @@ var src_default = plugin_default;
835
1345
  export {
836
1346
  ANTHROPIC_PKG,
837
1347
  CACHE_VERSION,
1348
+ CONTEXT_BUDGET_OPTION,
838
1349
  ENV_API_KEY,
839
1350
  ENV_API_URL,
840
1351
  ENV_BASE_URL,
@@ -845,22 +1356,34 @@ export {
845
1356
  PLACEHOLDER_MODEL_ID,
846
1357
  PLEXUS_API_KEY_ENV_OPTION,
847
1358
  PLEXUS_BASE_URL_OPTION,
1359
+ PLEXUS_CONTEXT_COMMAND,
848
1360
  PLEXUS_INTEGRATION_ID,
849
1361
  PLEXUS_PLUGIN_ID,
850
1362
  PLEXUS_PROVIDER_ID,
851
1363
  PLEXUS_PROVIDER_NAME,
852
1364
  PLEXUS_REFRESH_COMMAND,
853
1365
  PLEXUS_SUPPRESS_MODELS_OPTION,
1366
+ PLEXUS_TIER_COMMAND,
854
1367
  REFRESH_TTL_MS,
1368
+ SessionPolicyStore,
855
1369
  apiBase,
856
1370
  buildModels,
857
1371
  src_default as default,
1372
+ effectiveContextWindow,
858
1373
  filterCachedModels,
1374
+ formatContextStatus,
1375
+ formatTierStatus,
859
1376
  getDir,
860
1377
  getSuppressedModels,
1378
+ injectServiceTier,
1379
+ injectServiceTierIntoBody,
861
1380
  modelsUrl,
862
1381
  orderModelsByApiBase,
1382
+ parseContextCommand,
1383
+ parseTierCommand,
863
1384
  placeholderModel,
1385
+ policyAdvertisementFromApiModel,
1386
+ policyAvailability,
864
1387
  providerInfo,
865
1388
  readCachedModels,
866
1389
  resolveConfig,
@@ -868,5 +1391,6 @@ export {
868
1391
  resolveExplicitApiKey,
869
1392
  rootURL,
870
1393
  trimURL,
1394
+ withServiceTier,
871
1395
  writeCache
872
1396
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mcowger/opencode-plexus",
3
- "version": "1.12.0",
3
+ "version": "1.13.0",
4
4
  "description": "Plexus AI proxy plugin for OpenCode V2 with dynamic model discovery",
5
5
  "type": "module",
6
6
  "module": "./dist/index.js",
@@ -27,7 +27,7 @@
27
27
  "build": "bun run build.ts"
28
28
  },
29
29
  "dependencies": {
30
- "@opencode/plugin": "^2.0.19"
30
+ "@opencode/plugin": "^2.0.26"
31
31
  },
32
32
  "peerDependencies": {
33
33
  "typescript": "^7.0.2"