@bismawy/pi-arnative 0.7.0 → 0.8.0-rc.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.
@@ -50,12 +50,19 @@ const activeTheme = () => getActiveTheme<Exclude<ActiveTheme, null>>();
50
50
  // (hardcoded in handleReloadCommand, no auto-hide). Patches Container.render
51
51
  // through the prototype chain (Container is not exported) and drops the whole box on match.
52
52
  const RELOAD_TEXT = "Reloading keybindings, extensions, skills, prompts, themes, and context files...";
53
+ /** The reload box is a fixed 5-child container (2 borders, 2 spacers, one 78-char line), so it
54
+ * renders at most ~9 rows even wrapped. Anything larger cannot be the box, and this predicate
55
+ * runs per frame on every plain Container — including a transcript of tens of thousands of
56
+ * lines, where the substring scan is the single most expensive arnative render patch. */
57
+ const RELOAD_BOX_MAX_LINES = 64;
53
58
  /**
54
59
  * True only for the box itself: border rows, blank spacers and (possibly wrapped) copy of the
55
60
  * message. The patch sits on every plain Container, so a bare substring test would blank a
56
- * whole chat the moment a transcript line mentioned the phrase.
61
+ * whole chat the moment a transcript line mentioned the phrase. Containers larger than
62
+ * {@link RELOAD_BOX_MAX_LINES} are refused before any scanning starts.
57
63
  */
58
64
  export function shouldHideReloadBox(lines: readonly string[]): boolean {
65
+ if (lines.length > RELOAD_BOX_MAX_LINES) return false;
59
66
  if (!lines.some((l) => l.includes("Reloading keybindings"))) return false;
60
67
  const rows = lines.map((l) => stripAnsi(l).trim());
61
68
  return rows.every((r) => r === "" || /^[─-]+$/.test(r) || RELOAD_TEXT.includes(r));
@@ -373,6 +380,10 @@ if (isMain(import.meta.url)) {
373
380
  assert(shouldHideReloadBox(["────", "", " Reloading keybindings, extensions,", " skills, prompts, themes, and context files...", "", "────"]) === true, "wrapped reload box detected");
374
381
  assert(shouldHideReloadBox(["hello", "the log says Reloading keybindings", "world"]) === false, "chat lines that mention the phrase stay visible");
375
382
  assert(shouldHideReloadBox(["hello", "world"]) === false, "normal lines pass through");
383
+ assert(
384
+ shouldHideReloadBox([...Array(RELOAD_BOX_MAX_LINES + 1).fill(""), " Reloading keybindings, extensions, skills, prompts, themes, and context files... "]) === false,
385
+ "a container larger than any reload box is refused before scanning",
386
+ );
376
387
 
377
388
  // selection: reverse video replaced with explicit colors (bg selectedBg + fg text)
378
389
  assert(
@@ -501,7 +501,7 @@ if (isMain(import.meta.url)) {
501
501
  mkdirSync(join(fixture, "sessions", "ui"), { recursive: true });
502
502
  const freeAsstOf = (provider: string, model: string, input: number) =>
503
503
  JSON.stringify({ message: { role: "assistant", provider, model, usage: { input, output: 5, cacheRead: 1, cost: { total: 0 } } } });
504
- const freeAsst = (model: string, input: number) => freeAsstOf("wally", model, input);
504
+ const freeAsst = (model: string, input: number) => freeAsstOf("alpha", model, input);
505
505
  writeFileSync(
506
506
  join(fixture, "sessions", "ui", "rows.jsonl"),
507
507
  [
@@ -509,50 +509,50 @@ if (isMain(import.meta.url)) {
509
509
  freeAsst("other-model", 7),
510
510
  // The shipped shape of the collision: a bare id and, on another provider, a path id
511
511
  // that merely ENDS with it. Suffix matching folded the second into the first, so a first
512
- // run under `river/…` showed wally+yarz's 29.5M/3.2M/360.5M as if it were its own.
512
+ // run under a shared alias showed two providers' usage as if it were one provider's own.
513
513
  freeAsst("deepseek-v4.1-flash", 300),
514
- freeAsstOf("9router", "river/deepseek-ai/DeepSeek-V4.1-Flash", 200),
514
+ freeAsstOf("shared", "team/deepseek-ai/DeepSeek-V4.1-Flash", 200),
515
515
  ].join(String.fromCharCode(10)),
516
516
  );
517
517
  collectUsageSummary(true);
518
518
 
519
519
  // Per-id totals: a model id reports its own tokens only, whatever it is a suffix of.
520
520
  assert(getModelAllTimeUsage("deepseek-v4.1-flash").input === 300, "a bare id does not absorb a longer id that ends with it");
521
- assert(getModelAllTimeUsage("river/deepseek-ai/DeepSeek-V4.1-Flash").input === 200, "a path id counts its own provider's tokens only");
522
- assert(getModelAllTimeUsage("RIVER/DeepSeek-AI/deepseek-V4.1-Flash").input === 200, "case still does not split one model's history");
521
+ assert(getModelAllTimeUsage("team/deepseek-ai/DeepSeek-V4.1-Flash").input === 200, "a path id counts its own provider's tokens only");
522
+ assert(getModelAllTimeUsage("TEAM/DeepSeek-AI/deepseek-V4.1-Flash").input === 200, "case still does not split one model's history");
523
523
  assert(getModelAllTimeUsage("deepseek-v4.1-flash:free").input === 300, "a route tag folds into the model it tags");
524
524
 
525
525
  // Cost estimation: unpriced pairs use rates declared automatically in models.json.
526
526
  assert(loadPriceTable() !== null && Object.keys(loadPriceTable()).length === 0, "no models.json rates means an empty table");
527
- assert(!hasPrice("wally", "gemini-3.8-flash"), "a pair absent from models.json has no price");
528
- assert(estimateCost(1000, 100, 0, "gemini-3.8-flash", "wally") === null, "an unknown pair estimates nothing");
527
+ assert(!hasPrice("alpha", "gemini-3.8-flash"), "a pair absent from models.json has no price");
528
+ assert(estimateCost(1000, 100, 0, "gemini-3.8-flash", "alpha") === null, "an unknown pair estimates nothing");
529
529
  assert(collectUsageSummary(true).totals.estimatedCost === 0, "nothing is estimated without rates");
530
- assert(estimateCost(1000, 100, 0, "other-model", "wally") === null, "a second unpriced pair estimates nothing either");
530
+ assert(estimateCost(1000, 100, 0, "other-model", "alpha") === null, "a second unpriced pair estimates nothing either");
531
531
 
532
532
  writeFileSync(
533
533
  join(fixture, "models.json"),
534
534
  JSON.stringify({
535
535
  providers: {
536
- wally: { models: [{ id: "gemini-3.8-flash", cost: { input: 1, output: 2, cacheRead: 0.1 } }] },
537
- yarz: { models: [{ id: "gemini-3.8-flash", cost: { input: 10, output: 20 } }] },
536
+ alpha: { models: [{ id: "gemini-3.8-flash", cost: { input: 1, output: 2, cacheRead: 0.1 } }] },
537
+ beta: { models: [{ id: "gemini-3.8-flash", cost: { input: 10, output: 20 } }] },
538
538
  },
539
539
  }),
540
540
  );
541
- assert(hasPrice("wally", "gemini-3.8-flash"), "a priced provider+model is found in the table");
541
+ assert(hasPrice("alpha", "gemini-3.8-flash"), "a priced provider+model is found in the table");
542
542
  assert(!hasPrice("enclave", "gemini-3.8-flash"), "another provider with no entry is not priced");
543
- assert(estimateCost(1_000_000, 0, 0, "gemini-3.8-flash", "wally") === 1, "1M input tokens at wally's $1/M costs $1");
543
+ assert(estimateCost(1_000_000, 0, 0, "gemini-3.8-flash", "alpha") === 1, "1M input tokens at alpha's $1/M costs $1");
544
544
  assert(
545
- estimateCost(1_000_000, 0, 0, "gemini-3.8-flash", "yarz") === 10,
546
- "the SAME model at yarz costs 10x (rates are per provider, not per model)",
545
+ estimateCost(1_000_000, 0, 0, "gemini-3.8-flash", "beta") === 10,
546
+ "the SAME model at beta costs 10x (rates are per provider, not per model)",
547
547
  );
548
- assert(estimateCost(0, 1_000_000, 0, "gemini-3.8-flash", "wally") === 2, "1M output tokens at $2/M costs $2");
549
- assert(Math.abs(estimateCost(0, 0, 1_000_000, "gemini-3.8-flash", "wally")! - 0.1) < 1e-9, "cache reads use their own rate");
550
- assert(estimateCost(1_000_000, 0, 0, "vendor/gemini-3.8-flash", "wally") === 1, "a vendor/my-model id matches the model rate");
548
+ assert(estimateCost(0, 1_000_000, 0, "gemini-3.8-flash", "alpha") === 2, "1M output tokens at $2/M costs $2");
549
+ assert(Math.abs(estimateCost(0, 0, 1_000_000, "gemini-3.8-flash", "alpha")! - 0.1) < 1e-9, "cache reads use their own rate");
550
+ assert(estimateCost(1_000_000, 0, 0, "vendor/gemini-3.8-flash", "alpha") === 1, "a vendor/my-model id matches the model rate");
551
551
  const withPrices = collectUsageSummary(true);
552
552
  assert(withPrices.totals.estimatedCost > 0, "models.json rates produce an estimate");
553
553
  assert(withPrices.totals.reportedCost === 0, "the reported total stays at the provider's own number");
554
554
  assert(withPrices.totals.cost === withPrices.totals.reportedCost, "the headline cost never absorbs the estimate");
555
- assert(estimateCost(1_000_000, 0, 0, "other-model", "wally") === null, "a pair with no rate stays unpriced even when others are priced");
555
+ assert(estimateCost(1_000_000, 0, 0, "other-model", "alpha") === null, "a pair with no rate stays unpriced even when others are priced");
556
556
 
557
557
  const fakeTheme = {
558
558
  fg: (_c: string, t: string) => `\x1b[38;2;100;100;100m${t}\x1b[39m`,
@@ -661,7 +661,7 @@ if (isMain(import.meta.url)) {
661
661
  // The unpriced notice is gone: the `-` in Cost already says it.
662
662
  assert(!body.includes("unpriced"), "the unpriced notice line is removed");
663
663
  // Provider rows are capitalized so they read as names, not raw ids.
664
- assert(plain(lines[firstRow]!).includes("Wally") || plain(lines[firstRow]!).includes("Google"), "provider rows are capitalized");
664
+ assert(plain(lines[firstRow]!).includes("Alpha") || plain(lines[firstRow]!).includes("Google"), "provider rows are capitalized");
665
665
 
666
666
  // Thinking level -> theme slot is unit-tested in lib/ansi.ts (one definition); here we
667
667
  // only prove the box border actually takes its color from that slot at render time.
@@ -776,20 +776,20 @@ if (isMain(import.meta.url)) {
776
776
  join(fixture, "models.json"),
777
777
  JSON.stringify({
778
778
  providers: {
779
- wally: { models: [{ id: "gemini-3.8-flash", cost: { input: 0.28, output: 0.42, cacheRead: 0.028 } }] },
780
- yarz: { models: [{ id: "gemini-3.8-flash" }] },
779
+ alpha: { models: [{ id: "gemini-3.8-flash", cost: { input: 0.28, output: 0.42, cacheRead: 0.028 } }] },
780
+ beta: { models: [{ id: "gemini-3.8-flash" }] },
781
781
  },
782
782
  }),
783
783
  );
784
784
  const fromModels = collectUsageSummary(true);
785
- const wally = fromModels.providers.find((p) => p.name === "wally")!;
785
+ const alpha = fromModels.providers.find((p) => p.name === "alpha")!;
786
786
  const expected = (100 / 1e6) * 0.28 + (5 / 1e6) * 0.42 + (1 / 1e6) * 0.028;
787
- assert(Math.abs(wally.estimatedCost - expected) < 1e-12, `models.json cost prices the provider, got ${wally.estimatedCost}`);
787
+ assert(Math.abs(alpha.estimatedCost - expected) < 1e-12, `models.json cost prices the provider, got ${alpha.estimatedCost}`);
788
788
  assert(
789
- Math.abs(wally.models.reduce((n, m) => n + m.estimatedCost, 0) - wally.estimatedCost) < 1e-9,
789
+ Math.abs(alpha.models.reduce((n, m) => n + m.estimatedCost, 0) - alpha.estimatedCost) < 1e-9,
790
790
  "a provider's estimate is the sum of its models' estimates",
791
791
  );
792
- assert(wally.models.find((m) => m.name === "other-model")!.estimatedCost === 0, "a model without a declared cost stays unpriced");
792
+ assert(alpha.models.find((m) => m.name === "other-model")!.estimatedCost === 0, "a model without a declared cost stays unpriced");
793
793
  writeFileSync(join(fixture, "models.json"), "{}", "utf8");
794
794
  collectUsageSummary(true);
795
795
 
@@ -800,7 +800,7 @@ if (isMain(import.meta.url)) {
800
800
  (estModal as unknown as { summary: unknown }).summary = {
801
801
  providers: [
802
802
  {
803
- name: "wally", sessions: 1, msgs: 2, input: 1_000_000, output: 500_000, cacheRead: 2_000_000,
803
+ name: "alpha", sessions: 1, msgs: 2, input: 1_000_000, output: 500_000, cacheRead: 2_000_000,
804
804
  totalTokens: 1_500_000, cost: 0, estimatedCost: 0.546,
805
805
  models: [{ name: "deepseek-v4.1-flash", sessions: 1, msgs: 2, input: 1_000_000, output: 500_000, cacheRead: 2_000_000, totalTokens: 1_500_000, cost: 0, estimatedCost: 0.546 }],
806
806
  },
@@ -812,14 +812,14 @@ if (isMain(import.meta.url)) {
812
812
  ],
813
813
  totals: { sessions: 2, msgs: 3, input: 3_200_000, output: 1_126_000, cacheRead: 2_000_000, totalTokens: 4_326_000, cost: 0.65, reportedCost: 0.65, estimatedCost: 0.546 },
814
814
  };
815
- (estModal as unknown as { expandedProviders: Set<string> }).expandedProviders = new Set(["wally"]);
815
+ (estModal as unknown as { expandedProviders: Set<string> }).expandedProviders = new Set(["alpha"]);
816
816
  const estLines = estModal.render(90);
817
817
  const estBody = estLines.map(plain).join("\n");
818
818
  assert(estBody.includes("~$0.55"), "a row with a rate but no reported cost shows the estimate with `~`");
819
819
  assert(estBody.includes("$0.65") && !estBody.includes("~$0.65"), "a reported cost is shown as-is, never with `~`");
820
820
  assert(estBody.includes("estimated (models.json)"), "the estimate line names models.json");
821
821
  // Only the two table rows — the detail line also carries the estimate.
822
- const estRows = estLines.map(plain).filter((l) => /^\u2502 [\u25be\u25b8 ] (Wally|deepseek)/.test(l));
822
+ const estRows = estLines.map(plain).filter((l) => /^\u2502 [\u25be\u25b8 ] (Alpha|deepseek)/.test(l));
823
823
  assert(estRows.length === 2 && estRows.every((l) => l.includes("~$0.55")), `the estimate shows on the provider row and its model row, got ${JSON.stringify(estRows)}`);
824
824
 
825
825
  // Cost must survive every width: a clipped `$5` is worse than a dropped column.
package/lib/compat.ts ADDED
@@ -0,0 +1,415 @@
1
+ /**
2
+ * Compat flags for a provider the wizard writes — ported from pi-auto-compat, minus its
3
+ * background machinery. Nothing here watches models.json or repairs it later: the flags
4
+ * are computed once, from the model list the wizard already fetched, and written by
5
+ * `withProviderModels` in provider.ts (one writer, one moment).
6
+ *
7
+ * Two things ride along with the same probe: the real `contextWindow`/`maxTokens`, and
8
+ * (on demand) which `reasoning_effort` names the channel accepts.
9
+ */
10
+ import { assert, isMain } from "./check.ts";
11
+
12
+ export type Compat = Record<string, unknown>;
13
+
14
+ /** The fields a compat decision depends on — a merged registry model, or the pieces the
15
+ * wizard holds while it writes a provider. */
16
+ export interface CompatModel {
17
+ provider: string;
18
+ id: string;
19
+ name?: string;
20
+ api?: string;
21
+ baseUrl?: string;
22
+ reasoning?: boolean;
23
+ compat?: Compat;
24
+ }
25
+
26
+ const lower = (v: unknown): string => String(v ?? "").toLowerCase();
27
+ const tokensOf = (m: CompatModel): string[] => [m.id, m.name].map(lower).filter(Boolean);
28
+
29
+ const isOpenAICompatible = (api: unknown): boolean => {
30
+ const v = lower(api);
31
+ return v === "openai-completions" || v === "openai-responses";
32
+ };
33
+
34
+ // Claude Opus/Sonnet >= 4.6, Fable >= 5 — the generations that need adaptive thinking.
35
+ const ADAPTIVE_RE =
36
+ /(?:^|[/\s:_-])(?:opus-4[.-][6-9]|opus-4-[1-9][0-9]|opus-(?:[5-9]|[1-9][0-9])|sonnet-4[.-][6-9]|sonnet-4-[1-9][0-9]|sonnet-(?:[5-9]|[1-9][0-9])|fable-(?:[5-9]|[1-9][0-9]))(?:$|[-_.:/\s[])/i;
37
+
38
+ const isKimiCoding = (m: CompatModel): boolean => lower(m.provider).includes("kimi-coding") || lower(m.baseUrl).includes("api.kimi.com/coding");
39
+ const isKimiK3 = (m: CompatModel): boolean =>
40
+ isKimiCoding(m) &&
41
+ tokensOf(m).some((t) => t === "k3" || t.includes("kimi-k3") || t.includes("kimi k3") || t.includes("kimi-for-coding") || t.includes("kimi for coding"));
42
+
43
+ /** pi's built-in llama.cpp provider declares this exact compat set; every rule skips it. */
44
+ function isPiLlamaCpp(m: CompatModel): boolean {
45
+ if (lower(m.provider) !== "llama.cpp" || lower(m.api) !== "openai-completions") return false;
46
+ const c = m.compat ?? {};
47
+ return (
48
+ c.supportsStore === false &&
49
+ c.supportsDeveloperRole === false &&
50
+ c.supportsReasoningEffort === false &&
51
+ c.supportsUsageInStreaming === false &&
52
+ c.supportsStrictMode === false &&
53
+ c.maxTokensField === "max_tokens" &&
54
+ c.sendSessionAffinityHeaders === undefined &&
55
+ c.sessionAffinityFormat === undefined &&
56
+ c.supportsLongCacheRetention === undefined
57
+ );
58
+ }
59
+
60
+ function isOfficialOpenAI(m: CompatModel): boolean {
61
+ const value = String(m.baseUrl ?? "").trim().toLowerCase();
62
+ if (!value) return lower(m.provider) === "openai";
63
+ try {
64
+ return new URL(value).hostname === "api.openai.com";
65
+ } catch {
66
+ return value === "api.openai.com" || value.startsWith("api.openai.com/");
67
+ }
68
+ }
69
+
70
+ const isOpenRouter = (m: CompatModel): boolean => lower(m.provider) === "openrouter" || lower(m.baseUrl).includes("openrouter.ai");
71
+
72
+ /** Flags a model needs, in pi's own priority order. Only keys the stored entry leaves
73
+ * undefined are returned, so an explicit user value — even `false` — always wins. */
74
+ export function suggestCompat(m: CompatModel): Compat {
75
+ const api = lower(m.api);
76
+ const compat = m.compat ?? {};
77
+ const tokens = tokensOf(m);
78
+ const out: Compat = {};
79
+
80
+ // pi defaults long retention to true when undeclared, and some relays 400 on the
81
+ // parameter (Fireworks caches automatically) — declare it either way.
82
+ if (compat.supportsLongCacheRetention === undefined) out.supportsLongCacheRetention = api === "anthropic-messages" || isOfficialOpenAI(m);
83
+
84
+ // Third-party routers reject role "developer" with `messages.0.role: Invalid option`;
85
+ // every OpenAI-compatible channel accepts "system". First-party APIs keep the role.
86
+ if (m.reasoning === true && isOpenAICompatible(api) && compat.supportsDeveloperRole === undefined && !isOfficialOpenAI(m) && !isOpenRouter(m)) {
87
+ out.supportsDeveloperRole = false;
88
+ }
89
+
90
+ if (api === "anthropic-messages" && (tokens.some((t) => ADAPTIVE_RE.test(t)) || isKimiK3(m))) {
91
+ if (compat.forceAdaptiveThinking !== true) out.forceAdaptiveThinking = true;
92
+ if (isKimiK3(m) && compat.allowEmptySignature !== true) out.allowEmptySignature = true;
93
+ return out;
94
+ }
95
+
96
+ if (tokens.some((t) => t.includes("deepseek")) && isOpenAICompatible(api) && !isPiLlamaCpp(m)) {
97
+ if (api === "openai-completions" && compat.sendSessionAffinityHeaders === undefined) out.sendSessionAffinityHeaders = true;
98
+ if (compat.requiresReasoningContentOnAssistantMessages !== true) out.requiresReasoningContentOnAssistantMessages = true;
99
+ if (compat.thinkingFormat !== "deepseek") out.thinkingFormat = "deepseek";
100
+ return out;
101
+ }
102
+
103
+ if (tokens.some((t) => t.includes("anthropic") || t.includes("claude")) && isOpenAICompatible(api) && !isPiLlamaCpp(m) && compat.cacheControlFormat !== "anthropic") {
104
+ out.cacheControlFormat = "anthropic";
105
+ }
106
+
107
+ if (api === "openai-completions" && !isOfficialOpenAI(m) && !isPiLlamaCpp(m) && compat.sendSessionAffinityHeaders === undefined) out.sendSessionAffinityHeaders = true;
108
+
109
+ return out;
110
+ }
111
+
112
+ // ------------------------------------------------------------ metadata
113
+
114
+ export interface ModelMeta {
115
+ contextWindow?: number;
116
+ maxTokens?: number;
117
+ }
118
+
119
+ // Widest window first: max_model_len / max_input_tokens are upstream limits, not the
120
+ // served window, and some channels only publish the input side.
121
+ const CONTEXT_KEYS = ["context_length", "context_window", "max_context_length", "max_model_len", "max_context_window", "max_input_tokens", "max_input_length", "context_size"];
122
+ const OUTPUT_KEYS = ["max_output_tokens", "max_completion_tokens", "max_output_length", "max_tokens"];
123
+
124
+ const positiveInt = (value: unknown): number | undefined => {
125
+ const n = typeof value === "string" && value.trim() ? Number(value.trim()) : value;
126
+ return typeof n === "number" && Number.isFinite(n) && n > 0 ? Math.floor(n) : undefined;
127
+ };
128
+
129
+ /** Numeric limits from one catalog entry. */
130
+ export function parseMeta(entry: unknown): ModelMeta {
131
+ const rec = (entry ?? {}) as Record<string, unknown>;
132
+ const out: ModelMeta = {};
133
+ for (const key of CONTEXT_KEYS) {
134
+ const value = positiveInt(rec[key]);
135
+ if (value !== undefined) {
136
+ out.contextWindow = value;
137
+ break;
138
+ }
139
+ }
140
+ for (const key of OUTPUT_KEYS) {
141
+ const value = positiveInt(rec[key]);
142
+ if (value === undefined) continue;
143
+ // A "max_tokens" equal to the whole window is the context length, not a cap.
144
+ if (out.contextWindow !== undefined && value >= out.contextWindow) continue;
145
+ out.maxTokens = value;
146
+ break;
147
+ }
148
+ return out;
149
+ }
150
+
151
+ /** Every model's limits from one `/models` body — the same response the id list comes
152
+ * from, so the metadata costs no extra request. */
153
+ export function parseModelMeta(body: unknown): Map<string, ModelMeta> {
154
+ const out = new Map<string, ModelMeta>();
155
+ if (typeof body !== "object" || body === null) return out;
156
+ const record = body as Record<string, unknown>;
157
+ const list = Array.isArray(record.data) ? record.data : Array.isArray(record.models) ? record.models : [];
158
+ for (const item of list) {
159
+ if (typeof item !== "object" || item === null) continue;
160
+ const rec = item as Record<string, unknown>;
161
+ const raw = typeof rec.id === "string" ? rec.id : typeof rec.name === "string" ? rec.name.replace(/^models\//, "") : undefined;
162
+ if (!raw) continue;
163
+ const meta = parseMeta(rec);
164
+ if (meta.contextWindow !== undefined || meta.maxTokens !== undefined) out.set(raw, meta);
165
+ }
166
+ return out;
167
+ }
168
+
169
+ /** Keep a real API correction, reject unit anomalies: an order of magnitude below the
170
+ * stored window is a per-request number, not the served window. */
171
+ export function contextWindowAccepted(candidate: number, existing: number | undefined): boolean {
172
+ if (existing === undefined || candidate === existing) return true;
173
+ return candidate > existing || candidate * 5 >= existing;
174
+ }
175
+
176
+ /** Merge a freshly probed limit into a stored one; undefined means "keep what is there". */
177
+ export function mergeMeta(prev: ModelMeta | undefined, next: ModelMeta): ModelMeta {
178
+ const out: ModelMeta = { ...prev };
179
+ const ctx = next.contextWindow;
180
+ if (ctx !== undefined && contextWindowAccepted(ctx, prev?.contextWindow)) out.contextWindow = ctx;
181
+ const effective = ctx ?? prev?.contextWindow;
182
+ if (next.maxTokens !== undefined && (prev?.maxTokens === undefined || next.maxTokens > prev.maxTokens)) {
183
+ out.maxTokens = effective !== undefined && next.maxTokens > effective ? effective : next.maxTokens;
184
+ }
185
+ return out;
186
+ }
187
+
188
+ // ------------------------------------------------------- thinking effort
189
+
190
+ // pi's levels in clamp order; `off` has no wire name of its own.
191
+ export const THINKING_LEVELS = ["off", "minimal", "low", "medium", "high", "xhigh", "max"] as const;
192
+ const EFFORT_RANK = ["none", "minimal", "low", "medium", "high", "xhigh", "max"];
193
+ const PROBED = new Set(EFFORT_RANK);
194
+ const IDENTITY: Record<string, string> = { low: "low", medium: "medium", high: "high", xhigh: "xhigh" };
195
+ const LEVEL_TIMEOUT_MS = 30_000;
196
+ const PROBE_TOKENS = 16;
197
+ const RETRY_PAUSE_MS = 1000;
198
+ // Only a parameter rejection indicts the level. Auth, quota and transport errors say
199
+ // nothing, and marking a level accepted without an answer would be a lie.
200
+ const REJECTION_RE = /provider.?error|invalid.?request|http 400|400[.:]|reasoning.?effort|thinking|unsupported|not supported|invalid (?:value|option|parameter|enum)|bad request/i;
201
+
202
+ /** A reasoning model on a relay that expects `reasoning_effort` and does not publish its
203
+ * own level support — the only case a probe can fix. */
204
+ export function isEffortProbeable(m: CompatModel & { compat?: Compat }, channelCompat: Compat = {}): boolean {
205
+ if (m.reasoning !== true || !isOpenAICompatible(m.api)) return false;
206
+ if (isOfficialOpenAI(m) || isOpenRouter(m) || isPiLlamaCpp(m)) return false;
207
+ const compat = { ...channelCompat, ...(m.compat ?? {}) };
208
+ if (compat.supportsReasoningEffort === false) return false;
209
+ return !["openrouter", "chat-template", "qwen-chat-template", "ant-ling"].includes(String(compat.thinkingFormat ?? ""));
210
+ }
211
+
212
+ /** The non-effort half of pi's request, so the probe tests the level like a real turn
213
+ * would: a channel that needs `thinking:{type:enabled}` must not report that as a failure. */
214
+ export function thinkingPayload(compat: Compat, enabled: boolean): Record<string, unknown> | undefined {
215
+ switch (compat.thinkingFormat) {
216
+ case "deepseek":
217
+ return { thinking: { type: enabled ? "enabled" : "disabled" } };
218
+ case "zai":
219
+ return { thinking: enabled ? { type: "enabled", clear_thinking: false } : { type: "disabled" } };
220
+ case "qwen":
221
+ return { enable_thinking: enabled };
222
+ case "together":
223
+ return { reasoning: { enabled } };
224
+ case "openrouter":
225
+ return enabled ? { reasoning: { effort: "medium" } } : undefined;
226
+ default:
227
+ return undefined;
228
+ }
229
+ }
230
+
231
+ /** Nearest accepted effort, up first (pi's clamp order), ties down. */
232
+ export function nearestEffort(level: string, accepted: Set<string>): string | undefined {
233
+ const idx = EFFORT_RANK.indexOf(level);
234
+ if (idx === -1) return undefined;
235
+ let best: string | undefined;
236
+ let bestDistance = Number.POSITIVE_INFINITY;
237
+ for (const candidate of accepted) {
238
+ const cIdx = EFFORT_RANK.indexOf(candidate);
239
+ if (cIdx === -1) continue;
240
+ const distance = cIdx >= idx ? cIdx - idx : (idx - cIdx) * 1.01;
241
+ if (distance < bestDistance) {
242
+ bestDistance = distance;
243
+ best = candidate;
244
+ }
245
+ }
246
+ return best;
247
+ }
248
+
249
+ /** A map that remaps or drops a level was shaped by the user, not by a probe. */
250
+ export function carriesRemap(map: Record<string, string | null> | undefined): boolean {
251
+ if (!map) return false;
252
+ for (const [level, value] of Object.entries(map)) {
253
+ if (value === null) return true;
254
+ if (value !== level && IDENTITY[level] !== undefined) return true;
255
+ }
256
+ return false;
257
+ }
258
+
259
+ /** Probe results → `thinkingLevelMap`. A rejected level maps to the nearest accepted one;
260
+ * a level that works stays unmapped, so nothing is pinned that need not be. Undefined when
261
+ * nothing answered or nothing changed. */
262
+ export function buildEffortMap(current: Record<string, string | null> | undefined, supported: string[]): Record<string, string | null> | undefined {
263
+ const accepted = new Set(supported);
264
+ if (accepted.size === 0) return undefined;
265
+ const out: Record<string, string | null> = {};
266
+ let changed = false;
267
+ for (const level of THINKING_LEVELS) {
268
+ const existing = current?.[level];
269
+ const optIn = level === "off" || level === "xhigh" || level === "max";
270
+ if (optIn) {
271
+ if (existing === undefined) continue; // not offered → not the probe's call
272
+ if (existing === null || !PROBED.has(existing)) {
273
+ out[level] = existing;
274
+ continue;
275
+ }
276
+ const from = level === "off" ? "minimal" : level;
277
+ const value = accepted.has(existing) ? existing : level === "off" && accepted.has("none") ? "none" : nearestEffort(from, accepted);
278
+ if (!value) {
279
+ out[level] = null;
280
+ changed = true;
281
+ continue;
282
+ }
283
+ if (value !== existing) changed = true;
284
+ out[level] = value;
285
+ continue;
286
+ }
287
+ if (existing !== undefined && existing !== level) {
288
+ out[level] = existing; // offered under another name: deliberate
289
+ continue;
290
+ }
291
+ if (existing === null) {
292
+ out[level] = null;
293
+ continue;
294
+ }
295
+ if (accepted.has(level)) continue;
296
+ out[level] = nearestEffort(level, accepted) ?? null;
297
+ changed = true;
298
+ }
299
+ return changed ? out : undefined;
300
+ }
301
+
302
+ export interface EffortProbeOptions {
303
+ baseUrl: string;
304
+ key?: string;
305
+ headers?: Record<string, string>;
306
+ fetchImpl?: typeof fetch;
307
+ /** Called after each level, for a progress row. */
308
+ onLevel?: (level: string, accepted: boolean | undefined, index: number) => void;
309
+ }
310
+
311
+ /** A status that names a rejected parameter rather than a broken endpoint. */
312
+ function isParamRejection(status: number, body: string): boolean {
313
+ if (status === 400 || status === 404 || status === 422) return true;
314
+ if (status !== 500 && status !== 502 && status !== 503) return false;
315
+ return REJECTION_RE.test(body);
316
+ }
317
+
318
+ const sleep = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));
319
+
320
+ /** Every effort name the channel accepts, found with one tiny completion per level.
321
+ * `[]` means nothing answered — never call that "nothing supported". */
322
+ export async function probeEffort(model: CompatModel, options: EffortProbeOptions): Promise<string[]> {
323
+ const fetchImpl = options.fetchImpl ?? fetch;
324
+ const url = `${options.baseUrl.replace(/\/+$/, "")}/chat/completions`;
325
+ const headers: Record<string, string> = { "content-type": "application/json", accept: "application/json", ...options.headers };
326
+ if (options.key) headers.authorization = `Bearer ${options.key}`;
327
+ const accepted: string[] = [];
328
+
329
+ for (const [index, level] of EFFORT_RANK.entries()) {
330
+ const body = JSON.stringify({
331
+ model: model.id,
332
+ messages: [{ role: "user", content: "ping" }],
333
+ max_tokens: PROBE_TOKENS,
334
+ stream: false,
335
+ ...(thinkingPayload(model.compat ?? {}, true) ?? {}),
336
+ reasoning_effort: level,
337
+ });
338
+ let verdict: boolean | undefined;
339
+ // Two attempts per level: a first 400 can be an upstream flake, a second confirms it.
340
+ for (let attempt = 0; attempt < 2 && verdict === undefined; attempt++) {
341
+ let status: number;
342
+ let text: string;
343
+ try {
344
+ const response = await fetchImpl(url, { method: "POST", headers, body, signal: AbortSignal.timeout(LEVEL_TIMEOUT_MS) });
345
+ status = response.status;
346
+ text = (await response.text()).slice(0, 4000);
347
+ } catch {
348
+ break; // network/timeout: inconclusive
349
+ }
350
+ if (status < 300) {
351
+ verdict = true;
352
+ break;
353
+ }
354
+ if (status === 429) {
355
+ await sleep(RETRY_PAUSE_MS);
356
+ continue;
357
+ }
358
+ if (!isParamRejection(status, text)) break; // 401/403/5xx without a hint: unknown
359
+ verdict = false;
360
+ }
361
+ if (verdict) accepted.push(level);
362
+ options.onLevel?.(level, verdict, index);
363
+ }
364
+ return accepted;
365
+ }
366
+
367
+ // ----------------------------------------------------------- self-check
368
+
369
+ if (isMain(import.meta.url)) {
370
+ const base = { provider: "r", id: "m", api: "openai-completions", baseUrl: "https://relay.x/v1" };
371
+ assert(suggestCompat(base).supportsLongCacheRetention === false, "a third-party relay declares retention false");
372
+ assert(suggestCompat(base).sendSessionAffinityHeaders === true, "an openai-compatible relay gets affinity headers");
373
+ assert(suggestCompat({ ...base, baseUrl: "https://api.openai.com/v1" }).supportsLongCacheRetention === true, "official OpenAI keeps long retention");
374
+ assert(suggestCompat({ ...base, reasoning: true }).supportsDeveloperRole === false, "a reasoning model on a relay opts out of the developer role");
375
+ assert(suggestCompat({ ...base, reasoning: true, compat: { supportsDeveloperRole: true } }).supportsDeveloperRole === undefined, "an explicit value is never overwritten");
376
+ assert(suggestCompat({ ...base, id: "deepseek-v4" }).thinkingFormat === "deepseek", "a deepseek id gets the deepseek thinking format");
377
+ assert(suggestCompat({ ...base, api: "anthropic-messages", id: "claude-opus-4-6" }).forceAdaptiveThinking === true, "Opus 4.6 needs adaptive thinking");
378
+ assert(suggestCompat({ ...base, id: "claude-sonnet-4-5" }).cacheControlFormat === "anthropic", "Claude on a proxy gets anthropic cache control");
379
+ assert(suggestCompat({ ...base, provider: "llama.cpp", compat: { supportsStore: false, supportsDeveloperRole: false, supportsReasoningEffort: false, supportsUsageInStreaming: false, supportsStrictMode: false, maxTokensField: "max_tokens" } }).sendSessionAffinityHeaders === undefined, "pi's built-in llama.cpp is left alone");
380
+
381
+ const meta = parseModelMeta({ data: [{ id: "a", context_length: 1_000_000, max_output_tokens: 64_000 }, { id: "b", max_model_len: 262_144, max_tokens: 262_144 }] });
382
+ assert(meta.get("a")?.contextWindow === 1_000_000 && meta.get("a")?.maxTokens === 64_000, "a catalog entry yields window and cap");
383
+ assert(meta.get("b")?.maxTokens === undefined, "a max_tokens equal to the window is not an output cap");
384
+ assert(parseModelMeta({ models: [{ name: "models/gemini-x", context_window: 128_000 }] }).get("gemini-x")?.contextWindow === 128_000, "a gemini-shaped list parses too");
385
+ assert(contextWindowAccepted(1_048_576, 131_072), "growth is accepted");
386
+ assert(!contextWindowAccepted(8192, 1_000_000), "a per-request number is rejected");
387
+ assert(mergeMeta({ maxTokens: 4096 }, { maxTokens: 8192 }).maxTokens === 8192, "an output cap only grows");
388
+ assert(mergeMeta({ contextWindow: 1024 }, { maxTokens: 8192 }).maxTokens === 1024, "a cap above the window clamps to the window");
389
+
390
+ assert(nearestEffort("medium", new Set(["low", "high"])) === "high", "a rejected level moves up first");
391
+ assert(nearestEffort("high", new Set(["low", "medium"])) === "medium", "with no level above it moves down");
392
+ assert(buildEffortMap(undefined, ["minimal", "low", "high"])?.medium === "high", "a rejected level is remapped");
393
+ assert(buildEffortMap(undefined, ["minimal", "low", "high"])?.xhigh === undefined, "an opt-in level is not invented");
394
+ assert(buildEffortMap({ medium: null, high: "high" }, ["high"])?.medium === null, "a deliberate null survives");
395
+ assert(buildEffortMap({ medium: "high" }, ["high"])?.medium === "high", "a deliberate remap is preserved");
396
+ assert(carriesRemap({ medium: "high" }) && carriesRemap({ low: null }) && !carriesRemap({ low: "low" }), "only a shaped map counts as deliberate");
397
+ assert(thinkingPayload({ thinkingFormat: "zai" }, true)?.thinking !== undefined, "a channel that needs a thinking block gets one");
398
+ assert(isEffortProbeable({ ...base, reasoning: true }), "a reasoning model on a relay is probeable");
399
+ assert(!isEffortProbeable({ ...base, reasoning: true, baseUrl: "https://api.openai.com/v1" }), "a first-party API is not probed");
400
+ assert(!isEffortProbeable({ ...base, reasoning: true, compat: { supportsReasoningEffort: false } }), "a channel that sends no effort is not probed");
401
+
402
+ // The probe loop itself: a channel that takes none/minimal/low/high and 400s medium.
403
+ const fakeFetch = (async (_url: string, init?: { body?: string }) => {
404
+ const level = JSON.parse(init?.body ?? "{}").reasoning_effort as string;
405
+ const ok = ["none", "minimal", "low", "high"].includes(level);
406
+ return { status: ok ? 200 : 400, text: async () => (ok ? "" : "invalid reasoning_effort") };
407
+ }) as unknown as typeof fetch;
408
+ const supported = await probeEffort({ ...base, id: "relay-model", reasoning: true }, { baseUrl: base.baseUrl, fetchImpl: fakeFetch });
409
+ assert(supported.join() === "none,minimal,low,high", "the probe reports exactly the accepted levels");
410
+ assert(buildEffortMap(undefined, supported)?.medium === "high", "a rejected level is remapped to the nearest accepted one");
411
+ const deadFetch = (async () => ({ status: 401, text: async () => "unauthorized" })) as unknown as typeof fetch;
412
+ assert((await probeEffort({ ...base, reasoning: true }, { baseUrl: base.baseUrl, fetchImpl: deadFetch })).length === 0, "a credential failure answers nothing, so nothing is written");
413
+
414
+ console.log("compat.ts self-check OK");
415
+ }
@@ -24,6 +24,8 @@ export const INPUT_LEGEND = "[Enter] Save [Esc] Cancel";
24
24
  export interface ListRow {
25
25
  label: string;
26
26
  note?: string;
27
+ /** The saved value among the choices, marked with a green ✓ at the end of the row. */
28
+ chosen?: boolean;
27
29
  }
28
30
 
29
31
  /** One row as a flat string — the headless/RPC `ctx.ui.select` fallback, which has no columns. */
@@ -202,6 +204,7 @@ export class ListPicker implements Component {
202
204
  const pad = " ".repeat(Math.max(0, column - visibleWidth(item.label)));
203
205
  const noteText = this.hooks.note?.(item.label) ?? item.note;
204
206
  const note = noteText ? `${th.fg("dim", ROW_DIVIDER)}${th.fg("dim", noteText)}` : "";
207
+ const chosen = item.chosen ? th.fg("success", " ✓") : "";
205
208
  // A checked state marker is chrome like the cursor: `[x]` accent, `[ ]` dim.
206
209
  const mark = this.hooks.marked
207
210
  ? this.hooks.marked(item.label)
@@ -212,7 +215,7 @@ export class ListPicker implements Component {
212
215
  const suffix = /(\(.*\))$/.exec(item.label)?.[1] ?? "";
213
216
  const head = suffix ? item.label.slice(0, item.label.length - suffix.length) : item.label;
214
217
  const tail = suffix ? th.fg("dim", suffix) : "";
215
- const content = `${isSelected ? th.fg("accent", "→ ") : " "}${mark}${paint(head)}${tail}${pad}${note}`;
218
+ const content = `${isSelected ? th.fg("accent", "→ ") : " "}${mark}${paint(head)}${tail}${pad}${note}${chosen}`;
216
219
  body.push(truncateToWidth(content, width - 4, ""));
217
220
  }
218
221
  // Hidden rows are announced, never silently cut (an empty line is still a row).
@@ -323,6 +326,19 @@ if (isMain(import.meta.url)) {
323
326
  assert(lines.every((l) => visibleWidth(l) === 50), "picker lines fit width 50");
324
327
  assert(lines.some((l) => l.includes("→ a")), "the cursor marks the selection");
325
328
 
329
+ // The chosen marker: ✓ ends the saved row only, colored by the theme's success slot.
330
+ const chosenPicker = new ListPicker(
331
+ fakeTheme,
332
+ [{ label: "a" }, { label: "b", note: "nb", chosen: true }],
333
+ "b",
334
+ { preview: quiet, revert: quiet, done: quiet, requestRender: quiet },
335
+ { title: screenTitle("Test"), description: "d", legend: "l" },
336
+ false,
337
+ );
338
+ const chosenLines = chosenPicker.render(50);
339
+ assert(chosenLines.some((l) => l.includes("nb ✓")), "a chosen row ends with the ✓ marker");
340
+ assert(chosenLines.every((l) => !l.includes("a ✓")), "unchosen rows carry no marker");
341
+
326
342
  // `←` behavior is owned by the screen: a parent gets the back call, `false` swallows
327
343
  // the key (a fill screen keeps its work), and a root menu closes like Esc.
328
344
  const keyLeft = "\x1b[D";