pi-cache-optimizer 2.10.2 → 2.10.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -226,6 +226,7 @@ Notes:
226
226
  - Do not add `supportsPromptCacheKey` to `models.json`: Pi 1.0.3 does not define that compat field. Use `/cache-optimizer fix prompt-cache-key` to store an exact provider/model omit rule in the extension-owned config; it removes both key spellings, including a key supplied by Pi.
227
227
  - If you see `400 Unsupported parameter: prompt_cache_retention`, remove/avoid `supportsLongCacheRetention` for that channel. Keep `sendSessionAffinityHeaders` if supported. The extension detects the explicit error from response headers or the finalized assistant error message and strips the parameter from subsequent requests in the current process.
228
228
  - Use `/cache-optimizer compat` or `/cache-optimizer doctor` to see model-specific advice.
229
+ - If a compat warning keeps appearing after you edited `models.json`, check the spelling: Pi ignores unknown keys, so a typo such as `model0verrides` or `sendSessionAfinityHeaders` most likely has no effect. The warnings, `doctor` and `fix` point out keys that look like a misspelling of a known Pi 1.3 key (hint only; nothing is renamed).
229
230
  - DeepSeek model names select the `DS cache` adapter only; they do not prove a reasoning wire protocol. Generic cache/routing advice remains active for absent or non-DeepSeek formats. DeepSeek replay advice is shown only when effective `compat.thinkingFormat: "deepseek"` is explicitly configured; it never treats `thinkingFormat` as a missing fix key.
230
231
  - Do not add `thinkingFormat: "deepseek"` merely because a model id contains `deepseek`; `openai`, `qwen`, `openrouter`, `together`, or no explicit format are all valid catalog cases.
231
232
  - This extension's `doctor` and `compat` commands only advise; they do not modify `models.json`.
package/README.zh-CN.md CHANGED
@@ -226,6 +226,7 @@ Pi 0.84.1 还修复了内置 Fireworks 渠道对拒绝 `prompt_cache_retention`
226
226
  - 不要把 `supportsPromptCacheKey` 加入 `models.json`:Pi 1.0.3 没有定义这个 compat 字段。请使用 `/cache-optimizer fix prompt-cache-key` 在扩展自有配置中保存精确 provider/model 的 omit 规则;它会移除两种 key 写法,包括 Pi 提供的 key。
227
227
  - 如果出现 `400 Unsupported parameter: prompt_cache_retention`,请为该渠道移除 / 避免 `supportsLongCacheRetention`;如支持,可保留 `sendSessionAffinityHeaders`。扩展会从响应头或最终 assistant error message 中识别这条明确错误,并在当前进程的后续请求中移除该参数。
228
228
  - 使用 `/cache-optimizer compat` 或 `/cache-optimizer doctor` 查看当前模型的具体建议。
229
+ - 如果修改 `models.json` 后 compat 警告仍反复出现,请检查拼写:Pi 会忽略未知 key,`model0verrides`、`sendSessionAfinityHeaders` 这类拼错的 key 很可能不会生效。警告、`doctor` 和 `fix` 会指出疑似拼错的已知 Pi 1.3 key(仅提示,不会自动改名)。
229
230
  - DeepSeek 模型名只用于选择 `DS cache` adapter,不能证明 reasoning wire protocol。缺少或使用非 DeepSeek format 时仍保留通用缓存 / 路由建议;只有 effective `compat.thinkingFormat: "deepseek"` 被明确配置时,才显示 DeepSeek replay 建议,且不会把 `thinkingFormat` 列为缺失修复项。
230
231
  - 不要因为模型 id 含有 `deepseek` 就添加 `thinkingFormat: "deepseek"`;catalog 中也存在 `openai`、`qwen`、`openrouter`、`together` 或没有显式 format 的情况。
231
232
  - 本扩展的 `doctor` 和 `compat` 命令只给建议,不会修改 `models.json`。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-cache-optimizer",
3
- "version": "2.10.2",
3
+ "version": "2.10.4",
4
4
  "description": "Improve Pi prompt/KV cache hit rates with stable prompts, OpenAI-compatible cache keys, proxy compat warnings, and footer cache stats.",
5
5
  "keywords": [
6
6
  "pi-package",
package/src/adapters.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { type ExtensionContext } from "@earendil-works/pi-coding-agent";
2
2
  import { type PiModel, isNonEmptyString } from "./common.ts";
3
- import { buildDeepSeekCompatWarningText, buildOpenAIProxyCompatWarningText, describeMissingCacheCompatForModel, describeMissingOpenAICompatibleProxyCompat, isDeepSeekWireCompatApplicable } from "./compat-advice.ts";
3
+ import { appendModelsJsonTypoHints, buildDeepSeekCompatWarningText, buildOpenAIProxyCompatWarningText, describeMissingCacheCompatForModel, describeMissingOpenAICompatibleProxyCompat, isDeepSeekWireCompatApplicable } from "./compat-advice.ts";
4
4
  import { getAssistantMessageModelTokenValues, getModelIdNameTokenValues, hasAnyTokenContaining } from "./model-detect.ts";
5
5
  import { ALEPH_MODEL_PATTERN, ARCTIC_MODEL_PATTERN, AYA_MODEL_PATTERN, DOUBAO_SEED_PATTERN, MIMO_MODEL_PATTERN, MPT_MODEL_PATTERN, NOVA_MODEL_PATTERN, ORION_MODEL_PATTERN, PHI_MODEL_PATTERN, PPLX_MODEL_PATTERN, XAI_MODEL_PATTERN, YI_MODEL_PATTERN, getAssistantRecord, getCompat, isAssistantMessage, isClaudeLikeAssistantMessage, isClaudeLikeModel, isDeepSeekLikeAssistantMessage, isDeepSeekLikeModel, isGeminiLikeAssistantMessage, isGeminiLikeModel, isNativeVirtualModel, isOpenAICompatibleApi, isOpenAIFamilyAssistantMessage, isOpenAIFamilyModel, isPiBuiltInLlamaCppModel, modelKey } from "./model-identity.ts";
6
6
  import { firstNonEmptyString, getRoutingRegistry, isRouterModel, resolveActiveRouteSnapshot } from "./routing.ts";
@@ -191,10 +191,12 @@ export const CACHE_PROVIDER_ADAPTERS: CacheProviderAdapter[] = [
191
191
  if (!isClaudeLikeModel(model) || !isOpenAICompatibleApi(model.api) || isPiBuiltInLlamaCppModel(model)) return undefined;
192
192
  if (getCompat(model).cacheControlFormat === "anthropic") return undefined;
193
193
 
194
- return (
194
+ const lines = [
195
195
  `💡 Cache optimizer: ${modelKey(model)} looks Claude/Anthropic-like but OpenAI-compatible compat lacks cacheControlFormat: "anthropic". ` +
196
- "Pi may not place Anthropic cache_control breakpoints unless this endpoint supports and enables that compat flag."
197
- );
196
+ "Pi may not place Anthropic cache_control breakpoints unless this endpoint supports and enables that compat flag.",
197
+ ];
198
+ appendModelsJsonTypoHints(lines, model.provider, model.id);
199
+ return lines.join("\n");
198
200
  },
199
201
  },
200
202
  {
@@ -1,4 +1,5 @@
1
1
  import { type PiModel, asRecord } from "./common.ts";
2
+ import { buildModelsJsonTypoHintLines } from "./models-json-lint.ts";
2
3
 
3
4
  /**
4
5
  * Diagnostics for Pi's native prompt-cache warming (Pi 0.86+, `cacheWarming`
@@ -123,6 +124,12 @@ export type CacheWarmingDiagnosisInput = {
123
124
  tier: "short" | "long";
124
125
  /** Whether the extension keeps warming running for zero-price models. */
125
126
  zeroPriceWarming?: boolean;
127
+ /**
128
+ * Append near-miss models.json key hints (issue #30). Default true;
129
+ * `/cache-optimizer doctor` passes false because it lists every typo in its
130
+ * own section.
131
+ */
132
+ typoHints?: boolean;
126
133
  };
127
134
 
128
135
  export type CacheWarmingDiagnosis = {
@@ -169,6 +176,10 @@ export function buildCacheWarmingDiagnosis(model: PiModel, input: CacheWarmingDi
169
176
  if (input.tier === "long" && suggested.long === undefined) {
170
177
  lines.push(" Only add a long lifetime your provider documents; use the conservative end of any range.");
171
178
  }
179
+ // A misspelled promptCache/modelOverrides key is accepted and ignored by Pi (issue #30).
180
+ if (input.typoHints !== false) {
181
+ for (const hint of buildModelsJsonTypoHintLines(model.provider, model.id)) lines.push(` ${hint}`);
182
+ }
172
183
  } else {
173
184
  lines.push(`- promptCache.${input.tier}: ${formatSeconds(ttl)}`);
174
185
  }
package/src/command.ts CHANGED
@@ -14,6 +14,7 @@ import { locateModelOverrideInJsonc, parseJsonc } from "./jsonc.ts";
14
14
  import { invalidateModelsConfigCache, isValidModelsConfigForEffectiveCompat, modelKey } from "./model-identity.ts";
15
15
  import { analyzeModelsJsonForMissingEntry, applyModelsJsonFixTransaction, chooseFixPlacement, composeFixInsertion, composeModelOverrideInsertion, composeProviderAffinityInsertion, createBaseUrlFixReceipt, createModelsJsonFixReceipt, createPromptCacheFixReceipt, formatCompatKeysForInsertion, formatMissingEntryManualSnippet, isActionableModelsJsonFixReceipt, locateModelInJsonc, markModelsJsonFixReceiptRolledBack, prepareModelsJsonRollback, readModelsJsonFixReceipt, readModelsJsonFixReceiptSnapshot, resolveExplicitCompatValue, selfCheckFix, selfCheckMissingEntryInsertion, validateModelsJsonRollback, writeModelsJsonFixReceipt } from "./models-json-fix.ts";
16
16
  import { MODELS_JSON_PATH } from "./paths.ts";
17
+ import { buildModelsJsonLintDoctorLines, buildModelsJsonTypoHintLines } from "./models-json-lint.ts";
17
18
  import { applyPromptCacheKeyConfigFix, isActionablePromptCacheKeyConfigReceipt, readPromptCacheKeyConfigReceiptSnapshot, rollbackPromptCacheKeyConfig } from "./prompt-cache-key-config.ts";
18
19
  import { getEffectiveCompatValueSource, isPromptCacheKeyOmittedForModel } from "./request-payload.ts";
19
20
  import { describeNativeVirtualRouteNote, resolveRouteModel } from "./routing.ts";
@@ -120,10 +121,12 @@ export function createCacheOptimizerCommandHandler(runtime: CommandRuntime) {
120
121
  mode: runtime.getCacheWarmingMode(),
121
122
  tier: process.env[PI_CACHE_RETENTION_ENV] === LONG_CACHE_RETENTION_VALUE ? "long" : "short",
122
123
  zeroPriceWarming: isZeroPriceWarmingEnabled(),
124
+ typoHints: false,
123
125
  }).lines
124
126
  : [];
125
127
  const kimiBaseUrlLines = buildKimiBaseUrlDoctorLines(model);
126
- const fullDiagnosis = [routeNote, diagnosis, kimiBaseUrlLines.length > 0 ? kimiBaseUrlLines.join("\n") : undefined, describeSkillCompressionOutcome(), describePromptCacheRetentionDecision(getLastPromptCacheRetentionDecision()), ...warmingLines, ...lowHitLines].filter((line) => line !== undefined).join("\n");
128
+ const modelsJsonLintLines = buildModelsJsonLintDoctorLines();
129
+ const fullDiagnosis = [routeNote, diagnosis, kimiBaseUrlLines.length > 0 ? kimiBaseUrlLines.join("\n") : undefined, modelsJsonLintLines.length > 0 ? modelsJsonLintLines.join("\n") : undefined, describeSkillCompressionOutcome(), describePromptCacheRetentionDecision(getLastPromptCacheRetentionDecision()), ...warmingLines, ...lowHitLines].filter((line) => line !== undefined).join("\n");
127
130
  cmdCtx.ui.notify(fullDiagnosis, "info");
128
131
  } else if (subcommand === "stats") {
129
132
  const aggregate = await refreshShardAggregate();
@@ -456,6 +459,9 @@ export function createCacheOptimizerCommandHandler(runtime: CommandRuntime) {
456
459
  cmdCtx.ui.notify(`✅ Nothing to fix for "${key}". Compat already configured.`, "info");
457
460
  return;
458
461
  }
462
+ // Issue #30: a misspelled key next to the target is silently ignored by
463
+ // Pi. Point it out in every fix output; never rename it automatically.
464
+ const typoNoteLines = buildFixTypoNoteLines(suggestion.providerLabel, suggestion.modelId);
459
465
 
460
466
  if (!cmdCtx.hasUI) {
461
467
  // No UI — refuse to write, show manual guidance instead.
@@ -507,6 +513,8 @@ export function createCacheOptimizerCommandHandler(runtime: CommandRuntime) {
507
513
  if (compatResult) {
508
514
  manualLines.push("", compatResult);
509
515
  }
516
+ // buildCompatDiagnosis already names the typos; avoid repeating them.
517
+ manualLines.push(...typoNoteLines.filter((line) => line === "" || !compatResult?.includes(line)));
510
518
  cmdCtx.ui.notify(manualLines.join("\n"), "warning");
511
519
  return;
512
520
  }
@@ -568,6 +576,7 @@ export function createCacheOptimizerCommandHandler(runtime: CommandRuntime) {
568
576
  `⚠️ This affects all models using this provider across all sessions; model-level overrides remain authoritative.`,
569
577
  `A timestamped backup will be written to: ${backupPath}`,
570
578
  "Run /reload or restart Pi for the change to take effect.",
579
+ ...typoNoteLines,
571
580
  "Apply these changes?",
572
581
  ].join("\n"));
573
582
  if (!confirmed) {
@@ -655,7 +664,7 @@ export function createCacheOptimizerCommandHandler(runtime: CommandRuntime) {
655
664
  "prompt_cache_retention parameter to this provider.",
656
665
  );
657
666
  }
658
- previewLines.push("", `Apply these changes?`);
667
+ previewLines.push(...typoNoteLines, "", `Apply these changes?`);
659
668
  const confirmed = await cmdCtx.ui.confirm(
660
669
  repairsExistingOverride ? "Cache Optimizer — Fix (model override)" : "Cache Optimizer — Fix (new override)",
661
670
  previewLines.join("\n"),
@@ -751,7 +760,7 @@ export function createCacheOptimizerCommandHandler(runtime: CommandRuntime) {
751
760
  "Add the following modelOverrides entry (keep existing auth):",
752
761
  );
753
762
  }
754
- adviceLines.push("", snippet, "", "Then save and run /reload.");
763
+ adviceLines.push("", snippet, "", "Then save and run /reload.", ...typoNoteLines);
755
764
  cmdCtx.ui.notify(adviceLines.join("\n"), "warning");
756
765
  return;
757
766
  }
@@ -872,7 +881,7 @@ export function createCacheOptimizerCommandHandler(runtime: CommandRuntime) {
872
881
  "prompt_cache_retention parameter to this provider.",
873
882
  );
874
883
  }
875
- previewLines.push("", `Apply these changes?`);
884
+ previewLines.push(...typoNoteLines, "", `Apply these changes?`);
876
885
 
877
886
  const confirmed = await cmdCtx.ui.confirm("Cache Optimizer — Fix", previewLines.join("\n"));
878
887
  if (!confirmed) {
@@ -1042,6 +1051,20 @@ export function createCacheOptimizerCommandHandler(runtime: CommandRuntime) {
1042
1051
  }
1043
1052
  }
1044
1053
 
1054
+ /**
1055
+ * Fix-output note for near-miss models.json keys on the target provider/model
1056
+ * (issue #30). Hint only: the fix never renames or removes a user's key.
1057
+ */
1058
+ export function buildFixTypoNoteLines(providerLabel: string, modelId: string): string[] {
1059
+ const hints = buildModelsJsonTypoHintLines(providerLabel, modelId);
1060
+ if (hints.length === 0) return [];
1061
+ return [
1062
+ "",
1063
+ ...hints,
1064
+ " This fix does not rename or remove misspelled keys; correct or delete them by hand.",
1065
+ ];
1066
+ }
1067
+
1045
1068
  function declaredPromptCacheTier(model: PiModel, tier: "short" | "long"): number | undefined {
1046
1069
  const value = asRecord(asRecord(model as unknown)?.promptCache)?.[tier];
1047
1070
  return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : undefined;
@@ -1061,8 +1084,9 @@ async function runPromptCacheFix(cmdCtx: ExtensionCommandContext, model: PiModel
1061
1084
  return;
1062
1085
  }
1063
1086
  const choice = choosePromptCacheLifetimes(model, tier);
1087
+ const typoNoteLines = buildFixTypoNoteLines(model.provider, model.id);
1064
1088
  if ("error" in choice) {
1065
- cmdCtx.ui.notify(`ℹ️ ${choice.error} No changes were made.`, "warning");
1089
+ cmdCtx.ui.notify([`ℹ️ ${choice.error} No changes were made.`, ...typoNoteLines].join("\n"), "warning");
1066
1090
  return;
1067
1091
  }
1068
1092
  const snippet = `"promptCache": ${JSON.stringify(choice.promptCache)}`;
@@ -1072,6 +1096,7 @@ async function runPromptCacheFix(cmdCtx: ExtensionCommandContext, model: PiModel
1072
1096
  `Add this to the model entry in ${getModelsJsonDisplayPath()} (custom models) or under`,
1073
1097
  `providers["${model.provider}"].modelOverrides["${model.id}"] (built-in models), then run /reload:`,
1074
1098
  ` ${snippet}`,
1099
+ ...typoNoteLines,
1075
1100
  ].join("\n");
1076
1101
 
1077
1102
  if (!cmdCtx.hasUI) {
@@ -1109,6 +1134,7 @@ async function runPromptCacheFix(cmdCtx: ExtensionCommandContext, model: PiModel
1109
1134
  ? `⚠️ This replaces the rollback receipt of the earlier fix for ${pendingReceipt.provider}/${pendingReceipt.modelId}; its backup ${pendingReceipt.backupFile} stays on disk.`
1110
1135
  : "",
1111
1136
  "Run /reload or restart Pi for the change to take effect.",
1137
+ ...typoNoteLines,
1112
1138
  "",
1113
1139
  "Apply this change?",
1114
1140
  ].filter((line, index, lines) => line !== "" || lines[index - 1] !== "").join("\n"));
@@ -1,6 +1,7 @@
1
1
  import { type PiModel, isNonEmptyString, lower } from "./common.ts";
2
2
  import { isAdaptiveGenerationModel, isKimiCodingAdaptiveModel } from "./model-detect.ts";
3
3
  import { getCompat, isDeepSeekLikeModel, isKimiCodingEmptySignatureModel, isKnownThirdPartyOpenAIEndpoint, isOpenAICompatibleProxyApi, isThirdPartyOpenAIProxyEndpoint, isOpenAIFamilyModel, isPiBuiltInLlamaCppModel, isRoutedFallbackModel } from "./model-identity.ts";
4
+ import { buildModelsJsonTypoHintLines } from "./models-json-lint.ts";
4
5
  import { getAgentDir } from "@earendil-works/pi-coding-agent";
5
6
  import { homedir } from "node:os";
6
7
 
@@ -123,6 +124,11 @@ export function buildSafeOpenAIProxyCompatSuggestion(missing: string[]): Record<
123
124
  export type CompatAdvicePlacement = {
124
125
  providerLabel?: string;
125
126
  modelId?: string;
127
+ /**
128
+ * Append near-miss models.json key hints for this provider/model (issue #30).
129
+ * Default true; `/cache-optimizer doctor` lists every typo in its own section.
130
+ */
131
+ typoHints?: boolean;
126
132
  };
127
133
 
128
134
  export function buildProviderCompatOverride(providerLabel: string, compat: Record<string, unknown>): Record<string, unknown> {
@@ -150,6 +156,25 @@ export function buildModelCompatOverride(providerLabel: string, modelId: string,
150
156
  }
151
157
 
152
158
  export function appendCredentialSafeProviderGuidance(lines: string[], placement: CompatAdvicePlacement, compatSuggestion: Record<string, unknown>): void {
159
+ appendProviderGuidanceBody(lines, placement, compatSuggestion);
160
+ if (placement.providerLabel && placement.typoHints !== false) {
161
+ appendModelsJsonTypoHints(lines, placement.providerLabel, placement.modelId);
162
+ }
163
+ }
164
+
165
+ /**
166
+ * Explain why a compat key the user believes they set is still missing: Pi
167
+ * accepts and ignores unknown keys, so `model0verrides` or
168
+ * `sendSessionAfinityHeaders` never takes effect. Hint only; never throws.
169
+ */
170
+ export function appendModelsJsonTypoHints(lines: string[], providerLabel: string | undefined, modelId?: string): void {
171
+ const hints = buildModelsJsonTypoHintLines(providerLabel, modelId);
172
+ if (hints.length === 0) return;
173
+ lines.push("");
174
+ lines.push(...hints);
175
+ }
176
+
177
+ function appendProviderGuidanceBody(lines: string[], placement: CompatAdvicePlacement, compatSuggestion: Record<string, unknown>): void {
153
178
  const providerLabel = placement.providerLabel;
154
179
  if (!providerLabel) return;
155
180
 
@@ -450,12 +450,12 @@ export function buildDoctorDiagnosis(model: PiModel, options: { promptCacheReten
450
450
  const modelsJsonPath = getModelsJsonDisplayPath();
451
451
  lines.push(`Edit ${modelsJsonPath} -> providers["${providerLabel}"] -> compat (same level as baseUrl/api/apiKey/models).`);
452
452
  if (adaptiveThinkingApplicable) {
453
- appendAdaptiveThinkingCompatAdviceLines(lines, missing, { providerLabel, modelId: model.id });
453
+ appendAdaptiveThinkingCompatAdviceLines(lines, missing, { providerLabel, modelId: model.id, typoHints: false });
454
454
  } else if (deepSeekCompatApplicable) {
455
- appendDeepSeekCompatAdviceLines(lines, missing, { providerLabel, modelId: model.id });
455
+ appendDeepSeekCompatAdviceLines(lines, missing, { providerLabel, modelId: model.id, typoHints: false });
456
456
  appendOptionalOpenAIProxyCompatAdviceLines(lines, optionalOpenAIProxyCompat);
457
457
  } else {
458
- appendOpenAIProxyCompatAdviceLines(lines, missing, { providerLabel, modelId: model.id });
458
+ appendOpenAIProxyCompatAdviceLines(lines, missing, { providerLabel, modelId: model.id, typoHints: false });
459
459
  appendOptionalOpenAIProxyCompatAdviceLines(lines, optionalOpenAIProxyCompat);
460
460
  }
461
461
  } else if (adaptiveThinkingApplicable || deepSeekCompatApplicable || isCompatCheckApplicable(model)) {
@@ -0,0 +1,301 @@
1
+ import { readFileSync, statSync } from "node:fs";
2
+ import { type UnknownRecord, asRecord } from "./common.ts";
3
+ import { parseJsonc } from "./jsonc.ts";
4
+ import { MODELS_JSON_PATH } from "./paths.ts";
5
+
6
+ /**
7
+ * Near-miss key lint for models.json (issue #30).
8
+ *
9
+ * Pi's ModelsConfigSchema does not set `additionalProperties: false`, so a
10
+ * misspelled key such as `model0verrides` or `sendSessionAfinityHeaders` is
11
+ * accepted and silently ignored. The compat warnings then keep firing with no
12
+ * hint why. This module reports only keys that look like a typo of a known
13
+ * key; unknown keys that resemble nothing are left alone so newer Pi fields
14
+ * and personal annotations never produce noise. It never edits the file.
15
+ *
16
+ * Known key sets are copied from Pi 1.3.0:
17
+ * - @earendil-works/pi-coding-agent dist/core/model-config.js
18
+ * (ModelsConfigSchema, ProviderConfigSchema, ModelDefinitionSchema, ModelOverrideSchema)
19
+ * - @earendil-works/pi-ai dist/providers/compat-schema.js
20
+ * (ProviderCompatSchema = merged properties of every per-API compat schema)
21
+ */
22
+ export const MODELS_JSON_SCHEMA_SOURCE_VERSION = "1.3.0";
23
+
24
+ export const MODELS_JSON_ROOT_KEYS: readonly string[] = ["$schema", "providers"];
25
+
26
+ export const MODELS_JSON_PROVIDER_KEYS: readonly string[] = [
27
+ "name", "baseUrl", "apiKey", "api", "oauth", "headers", "compat", "authHeader", "models", "modelOverrides",
28
+ ];
29
+
30
+ export const MODELS_JSON_MODEL_DEFINITION_KEYS: readonly string[] = [
31
+ "id", "name", "api", "baseUrl", "reasoning", "thinkingLevelMap", "input", "inputLimits", "cost", "promptCache",
32
+ "contextWindow", "maxTokens", "samplingParams", "samplingParamsByThinkingLevel", "headers", "compat",
33
+ ];
34
+
35
+ export const MODELS_JSON_MODEL_OVERRIDE_KEYS: readonly string[] = [
36
+ "name", "reasoning", "thinkingLevelMap", "input", "inputLimits", "cost", "promptCache",
37
+ "contextWindow", "maxTokens", "samplingParams", "samplingParamsByThinkingLevel", "headers", "compat",
38
+ ];
39
+
40
+ /** Object.keys(ProviderCompatSchema.properties) in Pi 1.3.0, sorted. */
41
+ export const MODELS_JSON_COMPAT_KEYS: readonly string[] = [
42
+ "allowEmptySignature", "allowedFallbackModels", "cacheControlFormat", "chatTemplateArgs", "chatTemplateKwargs",
43
+ "forceAdaptiveThinking", "maxTokensField", "openRouterRouting", "requiresAssistantAfterToolResult",
44
+ "requiresReasoningContentOnAssistantMessages", "requiresThinkingAsText", "requiresToolResultName",
45
+ "sendSessionAffinityHeaders", "sessionAffinityFormat", "supportsAdditionalTools", "supportsCacheControlOnTools",
46
+ "supportsDeveloperRole", "supportsEagerToolInputStreaming", "supportsExplicitPromptCacheMode", "supportsFinishReason",
47
+ "supportsLongCacheRetention", "supportsMaxOutputTokens", "supportsMidConvoEffort", "supportsMidConvoSystemMessages",
48
+ "supportsMidConvoToolAdditions", "supportsMidConvoToolChanges", "supportsOpenAIGrammarTools", "supportsReasoningEffort",
49
+ "supportsStore", "supportsStrictMode", "supportsStrictTools", "supportsTemperature", "supportsThinkingTokenBudget",
50
+ "supportsToolSearch", "supportsUsageInStreaming", "thinkingFormat", "thinkingTokenBudgetField", "vercelGatewayRouting",
51
+ "vllmPriority", "zaiToolStream",
52
+ ];
53
+
54
+ export type ModelsJsonKeyLevel =
55
+ | "root"
56
+ | "provider"
57
+ | "providerCompat"
58
+ | "model"
59
+ | "modelCompat"
60
+ | "modelOverride"
61
+ | "modelOverrideCompat";
62
+
63
+ export interface ModelsJsonKeyTypo {
64
+ /** Display path, e.g. `providers["opencode-go"].model0verrides`. */
65
+ path: string;
66
+ /** The key as written in models.json. */
67
+ key: string;
68
+ /** The known key it most likely meant. */
69
+ suggestion: string;
70
+ level: ModelsJsonKeyLevel;
71
+ providerId?: string;
72
+ /** models[].id or the modelOverrides entry name, for model-scoped levels. */
73
+ modelId?: string;
74
+ }
75
+
76
+ /** Lowercase, read 0 as o and 1 as l, drop `-` and `_`. */
77
+ export function normalizeModelsJsonKey(key: string): string {
78
+ return key.toLowerCase().replace(/0/g, "o").replace(/1/g, "l").replace(/[-_]/g, "");
79
+ }
80
+
81
+ /** Optimal-string-alignment (restricted Damerau-Levenshtein) distance, capped: returns > max early. */
82
+ export function damerauLevenshtein(a: string, b: string, max = Number.POSITIVE_INFINITY): number {
83
+ if (a === b) return 0;
84
+ if (Math.abs(a.length - b.length) > max) return max + 1;
85
+ const rows = a.length + 1;
86
+ const cols = b.length + 1;
87
+ const d: number[][] = Array.from({ length: rows }, (_, i) => {
88
+ const row = new Array<number>(cols).fill(0);
89
+ row[0] = i;
90
+ return row;
91
+ });
92
+ for (let j = 0; j < cols; j++) d[0][j] = j;
93
+ for (let i = 1; i < rows; i++) {
94
+ let rowMin = Number.POSITIVE_INFINITY;
95
+ for (let j = 1; j < cols; j++) {
96
+ const cost = a[i - 1] === b[j - 1] ? 0 : 1;
97
+ let value = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost);
98
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
99
+ value = Math.min(value, d[i - 2][j - 2] + 1);
100
+ }
101
+ d[i][j] = value;
102
+ if (value < rowMin) rowMin = value;
103
+ }
104
+ if (rowMin > max) return max + 1;
105
+ }
106
+ return d[a.length][b.length];
107
+ }
108
+
109
+ const MAX_TYPO_DISTANCE = 2;
110
+ const MIN_DISTANCE_KEY_LENGTH = 6;
111
+
112
+ /**
113
+ * Return the known key `key` most likely meant, or undefined when it is an
114
+ * exact known key or does not resemble one closely enough.
115
+ */
116
+ export function suggestKnownKey(key: string, known: readonly string[]): string | undefined {
117
+ if (known.includes(key)) return undefined;
118
+ const normalized = normalizeModelsJsonKey(key);
119
+ for (const candidate of known) {
120
+ if (normalizeModelsJsonKey(candidate) === normalized) return candidate;
121
+ }
122
+ if (key.length < MIN_DISTANCE_KEY_LENGTH) return undefined;
123
+ let best: string | undefined;
124
+ let bestDistance = MAX_TYPO_DISTANCE + 1;
125
+ const lowered = key.toLowerCase();
126
+ for (const candidate of known) {
127
+ const distance = Math.min(
128
+ damerauLevenshtein(lowered, candidate.toLowerCase(), MAX_TYPO_DISTANCE),
129
+ damerauLevenshtein(normalized, normalizeModelsJsonKey(candidate), MAX_TYPO_DISTANCE),
130
+ );
131
+ if (distance < bestDistance) {
132
+ best = candidate;
133
+ bestDistance = distance;
134
+ }
135
+ }
136
+ return best;
137
+ }
138
+
139
+ function propertyPath(base: string, key: string): string {
140
+ const segment = /^[A-Za-z_$][\w$]*$/.test(key) ? `.${key}` : `[${JSON.stringify(key)}]`;
141
+ return base ? `${base}${segment}` : (segment.startsWith(".") ? key : segment);
142
+ }
143
+
144
+ function lintObject(
145
+ record: UnknownRecord,
146
+ known: readonly string[],
147
+ basePath: string,
148
+ level: ModelsJsonKeyLevel,
149
+ out: ModelsJsonKeyTypo[],
150
+ scope: { providerId?: string; modelId?: string },
151
+ ): void {
152
+ for (const key of Object.keys(record)) {
153
+ const suggestion = suggestKnownKey(key, known);
154
+ if (suggestion === undefined) continue;
155
+ out.push({ path: propertyPath(basePath, key), key, suggestion, level, ...scope });
156
+ }
157
+ }
158
+
159
+ /**
160
+ * Lint an already-parsed models.json value. Pure and non-throwing; anything
161
+ * that is not shaped like an object at a given level is skipped.
162
+ */
163
+ export function lintModelsJsonKeys(config: unknown): ModelsJsonKeyTypo[] {
164
+ const out: ModelsJsonKeyTypo[] = [];
165
+ try {
166
+ const root = asRecord(config);
167
+ if (!root) return out;
168
+ lintObject(root, MODELS_JSON_ROOT_KEYS, "", "root", out, {});
169
+ const providers = asRecord(root.providers);
170
+ if (!providers) return out;
171
+ for (const [providerId, providerValue] of Object.entries(providers)) {
172
+ const provider = asRecord(providerValue);
173
+ if (!provider) continue;
174
+ const providerPath = `providers[${JSON.stringify(providerId)}]`;
175
+ lintObject(provider, MODELS_JSON_PROVIDER_KEYS, providerPath, "provider", out, { providerId });
176
+ const providerCompat = asRecord(provider.compat);
177
+ if (providerCompat) {
178
+ lintObject(providerCompat, MODELS_JSON_COMPAT_KEYS, `${providerPath}.compat`, "providerCompat", out, { providerId });
179
+ }
180
+ if (Array.isArray(provider.models)) {
181
+ provider.models.forEach((modelValue, index) => {
182
+ const model = asRecord(modelValue);
183
+ if (!model) return;
184
+ const modelId = typeof model.id === "string" ? model.id : undefined;
185
+ const modelPath = `${providerPath}.models[${index}]`;
186
+ lintObject(model, MODELS_JSON_MODEL_DEFINITION_KEYS, modelPath, "model", out, { providerId, modelId });
187
+ const compat = asRecord(model.compat);
188
+ if (compat) lintObject(compat, MODELS_JSON_COMPAT_KEYS, `${modelPath}.compat`, "modelCompat", out, { providerId, modelId });
189
+ });
190
+ }
191
+ const overrides = asRecord(provider.modelOverrides);
192
+ if (overrides) {
193
+ for (const [modelId, overrideValue] of Object.entries(overrides)) {
194
+ const override = asRecord(overrideValue);
195
+ if (!override) continue;
196
+ const overridePath = `${providerPath}.modelOverrides[${JSON.stringify(modelId)}]`;
197
+ lintObject(override, MODELS_JSON_MODEL_OVERRIDE_KEYS, overridePath, "modelOverride", out, { providerId, modelId });
198
+ const compat = asRecord(override.compat);
199
+ if (compat) lintObject(compat, MODELS_JSON_COMPAT_KEYS, `${overridePath}.compat`, "modelOverrideCompat", out, { providerId, modelId });
200
+ }
201
+ }
202
+ }
203
+ } catch {
204
+ // Linting is advisory; a hostile or exotic value must never break callers.
205
+ }
206
+ return out;
207
+ }
208
+
209
+ /** Parse JSONC text and lint it. Returns [] when the text does not parse. */
210
+ export function lintModelsJsonText(text: string): ModelsJsonKeyTypo[] {
211
+ try {
212
+ return lintModelsJsonKeys(parseJsonc(text.replace(/^\uFEFF/, "")));
213
+ } catch {
214
+ return [];
215
+ }
216
+ }
217
+
218
+ const fileCache = new Map<string, { signature: string; typos: ModelsJsonKeyTypo[] }>();
219
+
220
+ function fileSignature(path: string): string | undefined {
221
+ try {
222
+ const info = statSync(path);
223
+ if (!info.isFile()) return undefined;
224
+ return `${info.dev}:${info.ino}:${info.size}:${info.mtimeMs}:${info.ctimeMs}`;
225
+ } catch {
226
+ return undefined;
227
+ }
228
+ }
229
+
230
+ /**
231
+ * Near-miss keys in models.json on disk. Cached by file identity, size and
232
+ * mtime/ctime, so repeated calls from per-request warning paths cost one
233
+ * stat. Never throws: a missing, unreadable or malformed file yields [].
234
+ */
235
+ export function readModelsJsonKeyTypos(path: string = MODELS_JSON_PATH): ModelsJsonKeyTypo[] {
236
+ try {
237
+ const signature = fileSignature(path);
238
+ if (signature === undefined) {
239
+ fileCache.delete(path);
240
+ return [];
241
+ }
242
+ const cached = fileCache.get(path);
243
+ if (cached?.signature === signature) return cached.typos;
244
+ let typos: ModelsJsonKeyTypo[] = [];
245
+ try {
246
+ typos = lintModelsJsonText(readFileSync(path, "utf8"));
247
+ } catch {
248
+ typos = [];
249
+ }
250
+ fileCache.set(path, { signature, typos });
251
+ return typos;
252
+ } catch {
253
+ return [];
254
+ }
255
+ }
256
+
257
+ export function clearModelsJsonLintCacheForTests(): void {
258
+ fileCache.clear();
259
+ }
260
+
261
+ /**
262
+ * Typos that can explain a setting not taking effect for one provider (and
263
+ * optionally one model): root typos, every provider-level typo, and model
264
+ * typos for the matching models[] entry or modelOverrides entry.
265
+ */
266
+ export function selectModelsJsonKeyTyposForTarget(
267
+ typos: readonly ModelsJsonKeyTypo[],
268
+ providerId: string | undefined,
269
+ modelId?: string,
270
+ ): ModelsJsonKeyTypo[] {
271
+ return typos.filter((typo) => {
272
+ if (typo.level === "root") return true;
273
+ if (providerId === undefined || typo.providerId !== providerId) return false;
274
+ if (typo.level === "provider" || typo.level === "providerCompat") return true;
275
+ return modelId !== undefined && typo.modelId === modelId;
276
+ });
277
+ }
278
+
279
+ export function formatModelsJsonKeyTypo(typo: ModelsJsonKeyTypo): string {
280
+ return `⚠️ ${typo.path} is not a known Pi 1.3 key and looks like a typo of ${JSON.stringify(typo.suggestion)}; Pi ignores unknown keys, so it most likely has no effect.`;
281
+ }
282
+
283
+ /** Formatted hint lines for one provider/model, read from models.json on disk. Never throws. */
284
+ export function buildModelsJsonTypoHintLines(providerId: string | undefined, modelId?: string, path: string = MODELS_JSON_PATH): string[] {
285
+ try {
286
+ return selectModelsJsonKeyTyposForTarget(readModelsJsonKeyTypos(path), providerId, modelId).map(formatModelsJsonKeyTypo);
287
+ } catch {
288
+ return [];
289
+ }
290
+ }
291
+
292
+ /** `/cache-optimizer doctor` section listing every suspected typo; empty when there are none. */
293
+ export function buildModelsJsonLintDoctorLines(path: string = MODELS_JSON_PATH): string[] {
294
+ const typos = readModelsJsonKeyTypos(path);
295
+ if (typos.length === 0) return [];
296
+ return [
297
+ "",
298
+ `🔤 models.json key check: ${typos.length} suspected typo${typos.length === 1 ? "" : "s"} (hint only; nothing was renamed):`,
299
+ ...typos.map((typo) => ` ${formatModelsJsonKeyTypo(typo)}`),
300
+ ];
301
+ }
@@ -182,6 +182,12 @@ export function compressSkillsInSystemPrompt(
182
182
  * position and `<skills>` wrapper. Returns true only when Pi's re-rendered prompt
183
183
  * really contains the compressed list; otherwise the section is restored and the
184
184
  * caller falls back to the string substitution.
185
+ *
186
+ * A custom base prompt (`customPrompt`) can hold its own copy of the verbose
187
+ * list: pi-subagents passes the parent's rendered prompt there, and an idle
188
+ * parent renders its unedited base options. That copy is compressed in place
189
+ * too; otherwise the re-render still contains the verbose list, the section edit
190
+ * is rolled back, and the string fallback forces the prompt.
185
191
  */
186
192
  export function compressSkillsViaSection(event: {
187
193
  readonly systemPrompt: string;
@@ -199,11 +205,23 @@ export function compressSkillsViaSection(event: {
199
205
  const compressed = formatSkillsForPromptCompressed(options.skills, skillFileReadTool(options) ?? "read").trim();
200
206
  if (!compressed || compressed.length >= verbose.length) return false;
201
207
 
208
+ const previousCustom = options.customPrompt;
209
+ const customHasVerbose = typeof previousCustom === "string" && previousCustom.includes(verbose);
210
+ if (customHasVerbose) options.customPrompt = previousCustom.split(verbose).join(compressed);
211
+ // Only the custom prompt held the list (Pi renders no skills section of its own, e.g. no
212
+ // read/bash tool): done, and no `<skills>` section is added where Pi renders none.
213
+ if (customHasVerbose && !event.systemPrompt.includes(verbose)) {
214
+ if (event.systemPrompt.includes(compressed)) return true;
215
+ options.customPrompt = previousCustom;
216
+ return false;
217
+ }
218
+
202
219
  const previous = sections.skills;
203
220
  sections.skills = compressed;
204
221
  if (event.systemPrompt.includes(compressed) && !event.systemPrompt.includes(verbose)) return true;
205
222
  if (previous === undefined) delete sections.skills;
206
223
  else sections.skills = previous;
224
+ options.customPrompt = previousCustom;
207
225
  return false;
208
226
  }
209
227