pi-cache-optimizer 2.10.3 → 2.10.5

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
@@ -64,7 +64,7 @@ Run `/reload` in Pi after install/update/remove so extension hooks refresh.
64
64
 
65
65
  On Pi 0.79.7 and newer, `pi update` updates Pi itself only. To update installed Pi packages such as this extension, run `pi update --extensions` (packages only) or `pi update --all` (Pi + packages).
66
66
 
67
- This extension requires Pi 0.82+ and is validated against Pi 1.3.0. It uses the official Pi package types directly for type-checking, along with extension hooks, `getAgentDir()`, and prompt options shared by those versions; it does not depend on Pi 0.83+ APIs such as `ctx.scopedModels` or the bundled TypeBox 1.3 aliases. Native virtual model support and codemode nested-call coalescing activate only on Pi 0.99+ hosts that produce them; older hosts keep the previous behavior. The local development baseline uses Node.js 22.19.0 or newer, matching Pi 1.0.3's engine requirement.
67
+ This extension requires Pi 0.82+ and is validated against Pi 1.5.0. It uses the official Pi package types directly for type-checking, along with extension hooks, `getAgentDir()`, and prompt options shared by those versions; it does not depend on Pi 0.83+ APIs such as `ctx.scopedModels` or the bundled TypeBox 1.3 aliases. Native virtual model support and codemode nested-call coalescing activate only on Pi 0.99+ hosts that produce them; older hosts keep the previous behavior. The local development baseline uses Node.js 22.19.0 or newer, matching Pi 1.0.3's engine requirement.
68
68
 
69
69
  ## Commands
70
70
 
@@ -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 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
@@ -64,7 +64,7 @@ pi remove npm:pi-deepseek-cache-optimizer && pi install npm:pi-cache-optimizer
64
64
 
65
65
  Pi 0.79.7 及之后,`pi update` 默认只更新 Pi 本体。若要更新已安装的 Pi package(包括本扩展),请运行 `pi update --extensions`(只更新 packages)或 `pi update --all`(Pi 与 packages 一起更新)。
66
66
 
67
- 本扩展要求 Pi 0.82+,并已使用 Pi 1.3.0 验证。TypeScript 校验直接使用官方 Pi package 类型,同时只使用这些版本共有的 extension hooks、`getAgentDir()` 和 prompt options;不依赖 Pi 0.83+ 专有 API(例如 `ctx.scopedModels` 或 bundled TypeBox 1.3 aliases)。原生虚拟模型支持与 codemode 嵌套工具调用合并只在会产生它们的 Pi 0.99+ 上生效,较早版本保持原有行为。本地开发基线需要 Node.js 22.19.0 或更高版本,与 Pi 1.0.3 的 engine 要求一致。
67
+ 本扩展要求 Pi 0.82+,并已使用 Pi 1.5.0 验证。TypeScript 校验直接使用官方 Pi package 类型,同时只使用这些版本共有的 extension hooks、`getAgentDir()` 和 prompt options;不依赖 Pi 0.83+ 专有 API(例如 `ctx.scopedModels` 或 bundled TypeBox 1.3 aliases)。原生虚拟模型支持与 codemode 嵌套工具调用合并只在会产生它们的 Pi 0.99+ 上生效,较早版本保持原有行为。本地开发基线需要 Node.js 22.19.0 或更高版本,与 Pi 1.0.3 的 engine 要求一致。
68
68
 
69
69
  ## 命令
70
70
 
@@ -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 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/index.ts CHANGED
@@ -23,7 +23,7 @@ import { decideZeroPriceWarming, readCacheWarmingMode } from "./src/cache-warmin
23
23
  import { LONG_CACHE_RETENTION_VALUE, PI_CACHE_RETENTION_BASELINE_SYMBOL, PI_CACHE_RETENTION_ENV, STARTUP_CACHE_RETENTION_ENV, captureCacheRetentionEnv, getOrCaptureCacheRetentionBaseline, decidePromptCacheRetention, recordPromptCacheRetentionDecision, requestLongCacheRetention, restoreCacheRetentionEnv, userRequestedLongCacheRetention } from "./src/retention.ts";
24
24
  import { isRuntimeOptimizerEnabled, isZeroPriceWarmingEnabled, setRuntimeOptimizerEnabled } from "./src/config.ts";
25
25
  import { compareToolOrderEntries, getToolNameForPayload, isKnownToolOrderApi, isToolOrderingEligibleModel, isVerifiedToolForApi, normalizeToolsInPayload, sortToolsInPayload } from "./src/tool-ordering.ts";
26
- import { SKILL_COMPRESSION_MIN_COUNT, compressSkillsInSystemPrompt, compressSkillsViaSection, formatSkillsForPrompt, formatSkillsForPromptCompressed, stripSessionOverviewChurn, explainSkillCompressionSkip, recordSkillCompressionOutcome, getLastSkillCompressionOutcome, describeSkillCompressionOutcome } from "./src/prompt-rewrite.ts";
26
+ import { SKILL_COMPRESSION_MIN_COUNT, SKILL_PATH_RULE_WORDINGS, compressSkillsInSystemPrompt, compressSkillsViaSection, formatSkillsForPrompt, formatSkillsForPromptCompressed, stripSessionOverviewChurn, explainSkillCompressionSkip, recordSkillCompressionOutcome, getLastSkillCompressionOutcome, describeSkillCompressionOutcome } from "./src/prompt-rewrite.ts";
27
27
  import { addEffectiveSessionAffinityHeaders, addOpenAIPromptCacheKey, clampPromptCacheKey, collectAnthropicCacheControlsInWireOrder, downgradeAnthropicLongCacheControls, getEffectiveCompatValueSource, hasAnthropicCacheTtlOrderError, hasEffectivePromptCacheKey, isPromptCacheKeyOmittedForModel, normalizeAnthropicCacheControlTtlOrder, omitOpenAIPromptCacheKeys, shouldInjectOpenAIPromptCacheKeyForModel, withAnthropicCacheTtlRepair, withoutPromptCacheRetention, derivePromptCacheKey } from "./src/request-payload.ts";
28
28
  import { PI_CACHE_HINTS_SYMBOL, PI_ROUTING_REGISTRY_SYMBOL, type PiCacheHintsInput, type PiCacheHintsOutput, applyConfiguredTransportToModel, canRewriteNativeVirtualPrompt, describeNativeVirtualRouteNote, ensureRoutingRegistry, findModelInRegistry, findNativeVirtualDispatches, getProtocolGlobal, getProviderPayloadModelId, getRoutingRegistry, hashSessionId, installCacheHintsService, nativeVirtualDispatchFromMessage, nativeVirtualDispatchToModel, parseRouteSnapshot, resolveActiveRouteSnapshot, resolveNativeVirtualRequestModel, resolveNativeVirtualRouteModel, resolveRouteModel, routeSnapshotToPiModel, sessionHashFromContext } from "./src/routing.ts";
29
29
  import { CONFIG_RECEIPT_PATH, applyPromptCacheKeyConfigFix, configReceiptBackupPath, parsePromptCacheKeyConfigReceipt, rollbackPromptCacheKeyConfig, writePromptCacheKeyConfigReceipt } from "./src/prompt-cache-key-config.ts";
@@ -152,6 +152,9 @@ export const __internals_for_tests = {
152
152
  formatSkillsForPromptCompressed,
153
153
  compressSkillsInSystemPrompt,
154
154
  SKILL_COMPRESSION_MIN_COUNT,
155
+ SKILL_PATH_RULE_WORDINGS,
156
+ compressSkillsViaSection,
157
+ explainSkillCompressionSkip,
155
158
  NO_PROMPT_REWRITE_ENV,
156
159
  isEnabledEnv,
157
160
  featureEnabled,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-cache-optimizer",
3
- "version": "2.10.3",
3
+ "version": "2.10.5",
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",
@@ -37,7 +37,7 @@
37
37
  "check:modules": "node scripts/check-module-graph.mjs"
38
38
  },
39
39
  "devDependencies": {
40
- "@earendil-works/pi-coding-agent": "^1.3.0",
40
+ "@earendil-works/pi-coding-agent": "^1.5.0",
41
41
  "@earendil-works/pi-server": "^1.1.0",
42
42
  "@types/node": "^22.0.0",
43
43
  "jiti": "^2.7.0",
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.5.0 (1.4.0 added compat imageInput and sendImageOptInHeader; 1.5.0 changed no keys):
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.5.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.5.0, sorted. */
41
+ export const MODELS_JSON_COMPAT_KEYS: readonly string[] = [
42
+ "allowEmptySignature", "allowedFallbackModels", "cacheControlFormat", "chatTemplateArgs", "chatTemplateKwargs",
43
+ "forceAdaptiveThinking", "imageInput", "maxTokensField", "openRouterRouting", "requiresAssistantAfterToolResult",
44
+ "requiresReasoningContentOnAssistantMessages", "requiresThinkingAsText", "requiresToolResultName",
45
+ "sendImageOptInHeader", "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 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
+ }
@@ -33,8 +33,28 @@ export function skillFileReadTool(opts: Pick<BuildSystemPromptOptions, "selected
33
33
  (readers.some((tool) => selected.includes(tool)) ? "indirect" : undefined);
34
34
  }
35
35
 
36
- /** Byte-for-byte copy of Pi's formatter (contract-tested against the installed Pi for every tool wording). */
37
- export function formatSkillsForPrompt(skills: NonNullable<BuildSystemPromptOptions["skills"]>, fileReadTool: SkillFileReadTool = "read"): string {
36
+ /**
37
+ * The path-resolution sentence of Pi's skill-list preamble, newest first. Pi 1.5.0 tightened it; older Pi
38
+ * (still supported by the peer range) emits the legacy wording. Compression matches the verbose list under
39
+ * each wording and keeps the matched wording in its own preamble, so the model reads what that Pi wrote.
40
+ */
41
+ export const SKILL_PATH_RULE_WORDINGS = [
42
+ "Resolve relative paths against the skill's directory (parent of SKILL.md). Use absolute paths in tool calls.",
43
+ "When a skill file references a relative path, resolve it against the skill directory (parent of SKILL.md / dirname of the path) and use that absolute path in tool commands.",
44
+ ] as const;
45
+
46
+ export type SkillPathRuleWording = (typeof SKILL_PATH_RULE_WORDINGS)[number];
47
+
48
+ /**
49
+ * Byte-for-byte copy of Pi's formatter (contract-tested against the installed Pi for every tool wording, and
50
+ * against a Pi 1.4.0 fixture for the legacy wording). `pathRule` defaults to the newest Pi wording for tests;
51
+ * production callers always pass the wording they matched (see skillListVariants).
52
+ */
53
+ export function formatSkillsForPrompt(
54
+ skills: NonNullable<BuildSystemPromptOptions["skills"]>,
55
+ fileReadTool: SkillFileReadTool = "read",
56
+ pathRule: SkillPathRuleWording = SKILL_PATH_RULE_WORDINGS[0],
57
+ ): string {
38
58
  const visibleSkills = skills.filter((skill) => !skill.disableModelInvocation);
39
59
  if (visibleSkills.length === 0) return "";
40
60
 
@@ -45,7 +65,7 @@ export function formatSkillsForPrompt(skills: NonNullable<BuildSystemPromptOptio
45
65
  : fileReadTool === "bash"
46
66
  ? "Use bash to load a skill's file when the task matches its description."
47
67
  : "Load a skill's file when the task matches its description.",
48
- "When a skill file references a relative path, resolve it against the skill directory (parent of SKILL.md / dirname of the path) and use that absolute path in tool commands.",
68
+ pathRule,
49
69
  "",
50
70
  "<available_skills>",
51
71
  ];
@@ -88,6 +108,7 @@ export function formatSkillsForPrompt(skills: NonNullable<BuildSystemPromptOptio
88
108
  export function formatSkillsForPromptCompressed(
89
109
  skills: NonNullable<BuildSystemPromptOptions["skills"]>,
90
110
  fileReadTool: SkillFileReadTool = "read",
111
+ pathRule: SkillPathRuleWording = SKILL_PATH_RULE_WORDINGS[0],
91
112
  ): string {
92
113
  const visibleSkills = skills.filter((skill) => !skill.disableModelInvocation);
93
114
  if (visibleSkills.length === 0) return "";
@@ -112,7 +133,7 @@ export function formatSkillsForPromptCompressed(
112
133
  }
113
134
 
114
135
  const compare = (a: string, b: string): number => (a < b ? -1 : a > b ? 1 : 0);
115
- const header = formatSkillsForPrompt(skills, fileReadTool);
136
+ const header = formatSkillsForPrompt(skills, fileReadTool, pathRule);
116
137
  const preamble = header.slice(0, header.indexOf("<available_skills>")).trim();
117
138
 
118
139
  const lines: string[] = [preamble];
@@ -132,6 +153,39 @@ export function formatSkillsForPromptCompressed(
132
153
  return lines.join("\n");
133
154
  }
134
155
 
156
+ /** Pi's verbose skill list and our compressed form of it, both trimmed, under one known Pi wording. */
157
+ export type SkillListVariant = { pathRule: SkillPathRuleWording; verbose: string; compressed: string };
158
+
159
+ /**
160
+ * The verbose/compressed pair for every known Pi wording, newest first, keeping only pairs where compression
161
+ * actually shortens the list. A prompt can hold copies in more than one wording (an inherited customPrompt
162
+ * rendered by another Pi version), so callers handle every variant rather than the first match.
163
+ */
164
+ export function skillListVariants(
165
+ skills: NonNullable<BuildSystemPromptOptions["skills"]>,
166
+ fileReadTool: SkillFileReadTool,
167
+ ): SkillListVariant[] {
168
+ return SKILL_PATH_RULE_WORDINGS
169
+ .map((pathRule) => ({
170
+ pathRule,
171
+ verbose: formatSkillsForPrompt(skills, fileReadTool, pathRule).trim(),
172
+ compressed: formatSkillsForPromptCompressed(skills, fileReadTool, pathRule).trim(),
173
+ }))
174
+ .filter((variant) => variant.verbose.length > 0 && variant.compressed.length > 0);
175
+ }
176
+
177
+ function containsAnyVerbose(text: string, variants: readonly SkillListVariant[]): boolean {
178
+ return variants.some((variant) => text.includes(variant.verbose));
179
+ }
180
+
181
+ function replaceEveryVerbose(text: string, variants: readonly SkillListVariant[]): string {
182
+ let out = text;
183
+ for (const variant of variants) {
184
+ if (variant.compressed.length < variant.verbose.length) out = out.split(variant.verbose).join(variant.compressed);
185
+ }
186
+ return out;
187
+ }
188
+
135
189
  /**
136
190
  * Replace pi's verbose `<available_skills>` block in `prompt` with the
137
191
  * compressed grouped form. Idempotent: if the verbose form is not
@@ -142,8 +196,8 @@ export function formatSkillsForPromptCompressed(
142
196
  *
143
197
  * Pre-conditions for compression to fire:
144
198
  * - opts.skills present and visible-skill count >= SKILL_COMPRESSION_MIN_COUNT
145
- * - Verbose block (built from the same `opts.skills`) is found in
146
- * `prompt` (substring match, no regex). This anchors the substitution
199
+ * - Verbose block (built from the same `opts.skills`, under one of the
200
+ * known Pi wordings) is found in `prompt` (substring match, no regex). This anchors the substitution
147
201
  * to pi's own emitter; if pi changes the format, we no-op rather
148
202
  * than mangle.
149
203
  *
@@ -162,13 +216,9 @@ export function compressSkillsInSystemPrompt(
162
216
  const visible = opts.skills.filter((skill) => !skill.disableModelInvocation);
163
217
  if (visible.length < SKILL_COMPRESSION_MIN_COUNT) return prompt;
164
218
 
165
- const verbose = formatSkillsForPrompt(opts.skills, skillFileReadTool(opts) ?? "read").trim();
166
- if (!verbose || !prompt.includes(verbose)) return prompt;
167
-
168
- const compressed = formatSkillsForPromptCompressed(opts.skills, skillFileReadTool(opts) ?? "read").trim();
169
- if (!compressed || compressed.length >= verbose.length) return prompt;
170
-
171
- return prompt.replace(verbose, () => compressed);
219
+ const variants = skillListVariants(opts.skills, skillFileReadTool(opts) ?? "read");
220
+ // Every copy under every known wording; split/join is literal, so `$` in a description is safe.
221
+ return replaceEveryVerbose(prompt, variants);
172
222
  }
173
223
 
174
224
  /**
@@ -200,25 +250,33 @@ export function compressSkillsViaSection(event: {
200
250
  if (!sections || typeof sections !== "object" || options.forceSystemPrompt !== undefined) return false;
201
251
  if (!options.skills || options.skills.filter((skill) => !skill.disableModelInvocation).length < SKILL_COMPRESSION_MIN_COUNT) return false;
202
252
 
203
- const verbose = formatSkillsForPrompt(options.skills, skillFileReadTool(options) ?? "read").trim();
204
- if (!verbose || !event.systemPrompt.includes(verbose)) return false;
205
- const compressed = formatSkillsForPromptCompressed(options.skills, skillFileReadTool(options) ?? "read").trim();
206
- if (!compressed || compressed.length >= verbose.length) return false;
253
+ const variants = skillListVariants(options.skills, skillFileReadTool(options) ?? "read");
254
+ const shrinking = variants.filter((variant) => variant.compressed.length < variant.verbose.length);
255
+ if (shrinking.length === 0 || !containsAnyVerbose(event.systemPrompt, shrinking)) return false;
256
+ // Success means no verbose copy under ANY wording is left; otherwise the string fallback would still force the prompt.
257
+ const done = (): boolean => !containsAnyVerbose(event.systemPrompt, shrinking) &&
258
+ shrinking.some((variant) => event.systemPrompt.includes(variant.compressed));
207
259
 
208
260
  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;
261
+ if (typeof previousCustom === "string") {
262
+ const nextCustom = replaceEveryVerbose(previousCustom, shrinking);
263
+ if (nextCustom !== previousCustom) options.customPrompt = nextCustom;
264
+ }
265
+ // Only the custom prompt held lists (Pi renders no skills section of its own, e.g. no read/bash tool): done,
266
+ // and no `<skills>` section is added where Pi renders none.
267
+ if (options.customPrompt !== previousCustom && !containsAnyVerbose(event.systemPrompt, shrinking)) {
268
+ if (done()) return true;
215
269
  options.customPrompt = previousCustom;
216
270
  return false;
217
271
  }
218
272
 
273
+ // What remains is Pi's own section; compress it under the wording it was rendered with.
274
+ const remaining = shrinking.find((variant) => event.systemPrompt.includes(variant.verbose));
219
275
  const previous = sections.skills;
220
- sections.skills = compressed;
221
- if (event.systemPrompt.includes(compressed) && !event.systemPrompt.includes(verbose)) return true;
276
+ if (remaining) {
277
+ sections.skills = remaining.compressed;
278
+ if (done()) return true;
279
+ }
222
280
  if (previous === undefined) delete sections.skills;
223
281
  else sections.skills = previous;
224
282
  options.customPrompt = previousCustom;
@@ -305,7 +363,7 @@ export function explainSkillCompressionSkip(prompt: string, opts: BuildSystemPro
305
363
  if (!prompt.includes("<available_skills>")) {
306
364
  return "the prompt has no skill list (no read tool selected, or another extension replaced it)";
307
365
  }
308
- if (!prompt.includes(formatSkillsForPrompt(opts.skills ?? [], skillFileReadTool(opts) ?? "read").trim())) {
366
+ if (!containsAnyVerbose(prompt, skillListVariants(opts.skills ?? [], skillFileReadTool(opts) ?? "read"))) {
309
367
  return "Pi's skill list format was not recognised; Pi may have changed it (please report this)";
310
368
  }
311
369
  return "the compressed list would not be shorter";