pi-cache-optimizer 2.8.10 → 2.8.11

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
@@ -61,7 +61,7 @@ Run `/reload` in Pi after install/update/remove so extension hooks refresh.
61
61
 
62
62
  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).
63
63
 
64
- This extension requires Pi 0.82+ and is validated against Pi 0.85.1. 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.
64
+ This extension requires Pi 0.82+ and is validated against Pi 0.87.1. 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.
65
65
 
66
66
  ## Commands
67
67
 
@@ -134,7 +134,7 @@ The explicit setting is stored in `pi-cache-optimizer-config.json` under Pi's ag
134
134
 
135
135
  ## Per-model `prompt_cache_key` opt-out
136
136
 
137
- Some OpenAI-compatible endpoints reject `prompt_cache_key` with HTTP 400 even though the same field is valid for other providers. Pi 0.85.1 has no native `supportsPromptCacheKey` compat field; do **not** add that unknown field to `models.json`. `supportsLongCacheRetention` is not an equivalent switch and should not be used for this purpose.
137
+ Some OpenAI-compatible endpoints reject `prompt_cache_key` with HTTP 400 even though the same field is valid for other providers. Pi 0.87.1 has no native `supportsPromptCacheKey` compat field; do **not** add that unknown field to `models.json`. `supportsLongCacheRetention` is not an equivalent switch and should not be used for this purpose.
138
138
 
139
139
  When the extension observes an explicit field-level `prompt_cache_key` unsupported error for the exact provider/model, ordinary `/cache-optimizer fix` offers a confirmed model-scoped repair. Value-validation failures and conditional restrictions such as “not allowed when temperature is set” do not qualify. If concurrent responses from different models cannot be correlated because Pi provides no request ID, header-only evidence is ignored unless the finalized assistant message supplies exact provider/model identity. If you already know that the endpoint rejects the field, use the explicit command:
140
140
 
@@ -148,7 +148,7 @@ The preview explains that the setting is stored in the extension-owned `pi-cache
148
148
 
149
149
  Third-party `openai-completions` proxies (LiteLLM / OneAPI / NewAPI / OpenRouter-like channels) often route one session across multiple upstream backends. That splits provider-side prompt caches.
150
150
 
151
- Pi 0.84.1 also fixes built-in Fireworks compatibility for models that reject `prompt_cache_retention`; the extension avoids provider-name special cases and resolves exact provider/model compat from `models.json` plus the runtime model. Pi 0.81+ also has a built-in `llama.cpp` provider using an OpenAI-shaped transport. Pi 0.82+ core generates a session `prompt_cache_key` for it when cache retention is enabled, so this extension preserves that key and may add the same conservative fallback when missing. The built-in provider's explicit compat fingerprint is excluded from generic proxy routing/session-affinity advice, but a custom or overridden provider that merely reuses the id `llama.cpp` is treated like any other OpenAI-compatible channel. `prompt_cache_retention` remains subject to the normal safety rule: keep it only for official OpenAI or an explicit effective `supportsLongCacheRetention: true` opt-in in `models.json`; otherwise strip it before sending. Pi 0.85.1 has no native `supportsPromptCacheKey` compat field, so the per-model key opt-out is stored in this extension's `pi-cache-optimizer-config.json` instead of `models.json`. The extension config is independent of Pi's compat precedence and only affects the exact provider/model listed there.
151
+ Pi 0.84.1 also fixes built-in Fireworks compatibility for models that reject `prompt_cache_retention`; the extension avoids provider-name special cases and resolves exact provider/model compat from `models.json` plus the runtime model. Pi 0.81+ also has a built-in `llama.cpp` provider using an OpenAI-shaped transport. Pi 0.82+ core generates a session `prompt_cache_key` for it when cache retention is enabled, so this extension preserves that key and may add the same conservative fallback when missing. The built-in provider's explicit compat fingerprint is excluded from generic proxy routing/session-affinity advice, but a custom or overridden provider that merely reuses the id `llama.cpp` is treated like any other OpenAI-compatible channel. `prompt_cache_retention` remains subject to the normal safety rule: keep it only for official OpenAI or an explicit effective `supportsLongCacheRetention: true` opt-in in `models.json`; otherwise strip it before sending. Pi 0.87.1 has no native `supportsPromptCacheKey` compat field, so the per-model key opt-out is stored in this extension's `pi-cache-optimizer-config.json` instead of `models.json`. The extension config is independent of Pi's compat precedence and only affects the exact provider/model listed there.
152
152
 
153
153
  For real proxies, start with session affinity:
154
154
 
@@ -174,7 +174,7 @@ Notes:
174
174
 
175
175
  - `sendSessionAffinityHeaders: true` is the safe default when your proxy supports sticky routing.
176
176
  - `supportsLongCacheRetention: true` is optional. Add it only when the endpoint explicitly supports OpenAI long prompt cache retention.
177
- - Do not add `supportsPromptCacheKey` to `models.json`: Pi 0.85.1 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.
177
+ - Do not add `supportsPromptCacheKey` to `models.json`: Pi 0.87.1 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.
178
178
  - 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.
179
179
  - Use `/cache-optimizer compat` or `/cache-optimizer doctor` to see model-specific advice.
180
180
  - 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.
@@ -262,7 +262,7 @@ Pi 0.80.9+ already includes Kimi K3 in built-in Kimi Coding, Moonshot AI / China
262
262
  - DeepSeek Pi Mono replay compat (`requiresReasoningContentOnAssistantMessages: true` only when `thinkingFormat: "deepseek"` is already explicit; `/fix` never invents that format)
263
263
  - OpenAI-compatible proxy session affinity (`sendSessionAffinityHeaders: true` for `openai-completions`). Pi 0.80.7+ controls `openai-responses` header shape with `sessionAffinityFormat` and auto-detects its default; this extension no longer writes the removed `sendSessionIdHeader` field.
264
264
 
265
- **Scope:** only the currently active model. Other channels require switching models and running `fix` again.
265
+ **Scope:** the fix starts from the currently active model. An affinity-only repair can write provider-level compat once for all applicable models on that provider, including models absent from `models[]` when the provider entry already exists and no higher-priority setting shadows it. Explicit per-model `false` remains an opt-out. Other or ambiguous repairs stay model-scoped.
266
266
 
267
267
  **Safety:**
268
268
 
@@ -275,15 +275,15 @@ Pi 0.80.9+ already includes Kimi K3 in built-in Kimi Coding, Moonshot AI / China
275
275
  7. Writes a privacy-safe, versioned receipt atomically only after a successful write; the receipt contains transaction/model identity, placement, scalar compat before/after values, file hashes, backup filename, timestamps/status, and no credentials or request data
276
276
  8. Uses unique, non-overwriting backup names and falls back to manual guidance if the JSONC scanner cannot confidently locate the target
277
277
 
278
- Existing `modelOverrides[modelId]` entries have Pi's highest precedence, so `fix` repairs them directly. For built-in or API-login models without a custom `models[]` entry, `fix` creates a compat-only `modelOverrides` entry instead of inventing a custom model definition. Runtime-observed provider failures are always written to that highest-precedence model override so extension-provided runtime compat cannot shadow the repair. Self-validation checks the full provider → custom model → runtime model → modelOverride result and rejects an ineffective lower-layer edit.
278
+ Existing `modelOverrides[modelId]` entries have Pi's highest precedence, so `fix` repairs them directly. For built-in or API-login models without a custom `models[]` entry, an affinity-only fix prefers provider-level compat when the existing provider is safely locatable and no higher-priority explicit/runtime value shadows it; otherwise `fix` creates a compat-only `modelOverrides` entry instead of inventing a custom model definition. Runtime-observed provider failures are always written to that highest-precedence model override so extension-provided runtime compat cannot shadow the repair. Self-validation checks the full provider → custom model → runtime model → modelOverride result and rejects an ineffective lower-layer edit.
279
279
 
280
280
  **Non-interactive mode:** refuses to write; shows manual edit guidance instead.
281
281
 
282
- **Run:** `/cache-optimizer fix` when the active model has detected compat issues. The command shows "nothing to fix" when compat is already complete.
282
+ **Run:** `/cache-optimizer fix` when the active model has detected compat issues. Affinity-only missing-compat notifications are shown once per provider per extension instance and point to this confirmed command; model-specific warnings remain separate. The command shows "nothing to fix" when compat is already complete.
283
283
 
284
284
  ## `/cache-optimizer rollback`
285
285
 
286
- Rollback is available through completion, direct execution, and the interactive menu. It always requires UI confirmation; without an interactive UI it gives manual-review guidance and does not write. The command selects the latest unapplied receipt for the active provider/model, validates the recorded backup and current file hashes, creates a new access-mode-preserving rollback backup, and uses temp-file + atomic rename. Fix and rollback transactions are serialized across extension instances; rollback also binds the receipt transaction id/hash from preview through commit and refuses if another transaction replaces it.
286
+ Rollback is available through completion, direct execution, and the interactive menu. It always requires UI confirmation; without an interactive UI it gives manual-review guidance and does not write. The command selects the latest unapplied receipt for the active provider/model (or any active model on that provider for a provider-level receipt), validates the recorded backup and current file hashes, creates a new access-mode-preserving rollback backup, and uses temp-file + atomic rename. Fix and rollback transactions are serialized across extension instances; rollback also binds the receipt transaction id/hash from preview through commit and refuses if another transaction replaces it.
287
287
 
288
288
  If `models.json` is unchanged since the fix, rollback can restore the exact pre-fix JSONC. If the file changed, it never blindly replaces it: it may restore only receipt-owned scalar compat keys whose recorded post-fix values are still present, preserving later user changes. If a receipt-owned key changed, the target was removed/moved, or the fix created a new target entry, it refuses and points to the recorded backup for manual review. Successful rollback marks the receipt and requires `/reload` or a restart.
289
289
 
package/README.zh-CN.md CHANGED
@@ -61,7 +61,7 @@ pi remove npm:pi-deepseek-cache-optimizer && pi install npm:pi-cache-optimizer
61
61
 
62
62
  Pi 0.79.7 及之后,`pi update` 默认只更新 Pi 本体。若要更新已安装的 Pi package(包括本扩展),请运行 `pi update --extensions`(只更新 packages)或 `pi update --all`(Pi 与 packages 一起更新)。
63
63
 
64
- 本扩展要求 Pi 0.82+,并已使用 Pi 0.85.1 验证。TypeScript 校验直接使用官方 Pi package 类型,同时只使用这些版本共有的 extension hooks、`getAgentDir()` 和 prompt options;不依赖 Pi 0.83+ 专有 API(例如 `ctx.scopedModels` 或 bundled TypeBox 1.3 aliases)。
64
+ 本扩展要求 Pi 0.82+,并已使用 Pi 0.87.1 验证。TypeScript 校验直接使用官方 Pi package 类型,同时只使用这些版本共有的 extension hooks、`getAgentDir()` 和 prompt options;不依赖 Pi 0.83+ 专有 API(例如 `ctx.scopedModels` 或 bundled TypeBox 1.3 aliases)。
65
65
 
66
66
  ## 命令
67
67
 
@@ -134,7 +134,7 @@ Footer 默认使用 `session`,避免另一个并行 Pi 终端使用相同 prov
134
134
 
135
135
  ## 按模型关闭 `prompt_cache_key`
136
136
 
137
- 某些 OpenAI-compatible endpoint 会因 `prompt_cache_key` 返回 HTTP 400,但同一个字段对其他 provider 可能有效。Pi 0.85.1 没有原生的 `supportsPromptCacheKey` compat 字段,**不要**把这个未知字段加入 `models.json`。`supportsLongCacheRetention` 也不是等价开关,不应借用来实现此目的。
137
+ 某些 OpenAI-compatible endpoint 会因 `prompt_cache_key` 返回 HTTP 400,但同一个字段对其他 provider 可能有效。Pi 0.87.1 没有原生的 `supportsPromptCacheKey` compat 字段,**不要**把这个未知字段加入 `models.json`。`supportsLongCacheRetention` 也不是等价开关,不应借用来实现此目的。
138
138
 
139
139
  当扩展观察到精确 provider/model 对 `prompt_cache_key` 的明确字段级拒绝后,普通 `/cache-optimizer fix` 会提供经过确认的模型级修复。参数值校验失败,以及“设置 temperature 时不允许”这类条件限制都不构成证据。若不同模型的响应并发交错,而 Pi 又没有提供 request ID,扩展会忽略无法安全关联的 response-header 证据;只有最终 assistant message 提供精确 provider/model 身份时才恢复归因。如果你已经确定 endpoint 不支持该字段,可以主动执行:
140
140
 
@@ -148,7 +148,7 @@ Footer 默认使用 `session`,避免另一个并行 Pi 终端使用相同 prov
148
148
 
149
149
  LiteLLM / OneAPI / NewAPI / 类 OpenRouter 渠道等第三方 `openai-completions` 代理,常会把同一个 session 分散到多个上游后端,导致 provider 侧 prompt cache 被拆散。
150
150
 
151
- Pi 0.84.1 还修复了内置 Fireworks 渠道对拒绝 `prompt_cache_retention` 的模型兼容性;本扩展不按 provider 名称增加特殊分支,而是结合 `models.json` 与 runtime model,按精确 provider/model 解析有效 compat。Pi 0.81+ 也内置了使用 OpenAI-shaped transport 的 `llama.cpp` provider。Pi 0.82+ core 在启用 cache retention 时会为它生成 session `prompt_cache_key`,因此本扩展会保留该 key,并在缺失时使用同样的保守 fallback。只有符合 Pi 内置 provider 明确 compat 指纹的模型会跳过通用 proxy 路由 / session-affinity 建议;仅复用 `llama.cpp` id 的自定义或覆盖 provider 仍按普通 OpenAI-compatible 渠道处理。`prompt_cache_retention` 继续遵循统一安全规则:仅官方 OpenAI 或 `models.json` 中有效配置为 `supportsLongCacheRetention: true` 时保留,否则发送前移除。Pi 0.85.1 没有原生的 `supportsPromptCacheKey` compat 字段,因此按模型关闭 key 的策略保存在本扩展的 `pi-cache-optimizer-config.json` 中,而不是 `models.json`。扩展配置独立于 Pi 的 compat 优先级,只影响其中列出的精确 provider/model。
151
+ Pi 0.84.1 还修复了内置 Fireworks 渠道对拒绝 `prompt_cache_retention` 的模型兼容性;本扩展不按 provider 名称增加特殊分支,而是结合 `models.json` 与 runtime model,按精确 provider/model 解析有效 compat。Pi 0.81+ 也内置了使用 OpenAI-shaped transport 的 `llama.cpp` provider。Pi 0.82+ core 在启用 cache retention 时会为它生成 session `prompt_cache_key`,因此本扩展会保留该 key,并在缺失时使用同样的保守 fallback。只有符合 Pi 内置 provider 明确 compat 指纹的模型会跳过通用 proxy 路由 / session-affinity 建议;仅复用 `llama.cpp` id 的自定义或覆盖 provider 仍按普通 OpenAI-compatible 渠道处理。`prompt_cache_retention` 继续遵循统一安全规则:仅官方 OpenAI 或 `models.json` 中有效配置为 `supportsLongCacheRetention: true` 时保留,否则发送前移除。Pi 0.87.1 没有原生的 `supportsPromptCacheKey` compat 字段,因此按模型关闭 key 的策略保存在本扩展的 `pi-cache-optimizer-config.json` 中,而不是 `models.json`。扩展配置独立于 Pi 的 compat 优先级,只影响其中列出的精确 provider/model。
152
152
 
153
153
  对真正的代理,建议先启用 session affinity:
154
154
 
@@ -174,7 +174,7 @@ Pi 0.84.1 还修复了内置 Fireworks 渠道对拒绝 `prompt_cache_retention`
174
174
 
175
175
  - `sendSessionAffinityHeaders: true` 是安全默认项,前提是你的代理支持 sticky routing。
176
176
  - `supportsLongCacheRetention: true` 是可选项。只有 endpoint 明确支持 OpenAI long prompt cache retention 时才添加。
177
- - 不要把 `supportsPromptCacheKey` 加入 `models.json`:Pi 0.85.1 没有定义这个 compat 字段。请使用 `/cache-optimizer fix prompt-cache-key` 在扩展自有配置中保存精确 provider/model 的 omit 规则;它会移除两种 key 写法,包括 Pi 提供的 key。
177
+ - 不要把 `supportsPromptCacheKey` 加入 `models.json`:Pi 0.87.1 没有定义这个 compat 字段。请使用 `/cache-optimizer fix prompt-cache-key` 在扩展自有配置中保存精确 provider/model 的 omit 规则;它会移除两种 key 写法,包括 Pi 提供的 key。
178
178
  - 如果出现 `400 Unsupported parameter: prompt_cache_retention`,请为该渠道移除 / 避免 `supportsLongCacheRetention`;如支持,可保留 `sendSessionAffinityHeaders`。扩展会从响应头或最终 assistant error message 中识别这条明确错误,并在当前进程的后续请求中移除该参数。
179
179
  - 使用 `/cache-optimizer compat` 或 `/cache-optimizer doctor` 查看当前模型的具体建议。
180
180
  - DeepSeek 模型名只用于选择 `DS cache` adapter,不能证明 reasoning wire protocol。缺少或使用非 DeepSeek format 时仍保留通用缓存 / 路由建议;只有 effective `compat.thinkingFormat: "deepseek"` 被明确配置时,才显示 DeepSeek replay 建议,且不会把 `thinkingFormat` 列为缺失修复项。
@@ -262,7 +262,7 @@ Pi 0.80.9+ 已在内置 Kimi Coding、Moonshot AI / 中国区、OpenRouter 和 V
262
262
  - DeepSeek Pi Mono replay compat(仅当已明确配置 `thinkingFormat: "deepseek"` 时使用 `requiresReasoningContentOnAssistantMessages: true`;`/fix` 不会自行推断该 format)
263
263
  - OpenAI-compatible proxy session affinity(`openai-completions` 使用 `sendSessionAffinityHeaders: true`)。Pi 0.80.7+ 使用 `sessionAffinityFormat` 控制 `openai-responses` header 形式并自动检测默认值;本扩展不再写入已移除的 `sendSessionIdHeader`。
264
264
 
265
- **范围:** 仅当前 active model。其他渠道需切换模型后再次运行 `fix`。
265
+ **范围:** 从当前 active model 发起修复。仅缺少 affinity 时,如 provider 已有配置项且无更高优先级配置遮挡,可一次写入 provider 级 compat,覆盖其适用模型(包括不在 `models[]` 中的模型);模型级显式 `false` 仍为 opt-out。其他或有歧义的修复仍按模型处理。
266
266
 
267
267
  **安全机制:**
268
268
 
@@ -274,15 +274,15 @@ Pi 0.80.9+ 已在内置 Kimi Coding、Moonshot AI / 中国区、OpenRouter 和 V
274
274
  6. 完全保留 `models.json` 原有访问权限,不主动收紧或放宽(例如 `0600` 保持 `0600`,`0644` 保持 `0644`)
275
275
  7. 备份名唯一且不会覆盖已有备份;如果 JSONC 扫描器无法置信定位目标,则回退到手动修改指引
276
276
 
277
- 已有的 `modelOverrides[modelId]` 具有 Pi 的最高优先级,因此 `fix` 会直接修复该 entry。对于没有自定义 `models[]` entry 的内置模型或 API-login 模型,`fix` 会创建仅含 compat 的 `modelOverrides` entry,而不会凭空添加自定义模型定义。运行时观察到的 provider 失败也始终写入这一最高优先级 model override,避免 extension-provided runtime compat 遮挡修复。自检会验证完整的 provider → custom model → runtime model → modelOverride 结果;无效的低层写入会被拒绝。
277
+ 已有的 `modelOverrides[modelId]` 具有 Pi 的最高优先级,因此 `fix` 会直接修复该 entry。对于没有自定义 `models[]` entry 的内置模型或 API-login 模型,若现有 provider 可安全使用 provider 级 affinity 修复,则优先写入 provider compat;否则 `fix` 会创建仅含 compat 的 `modelOverrides` entry,而不会凭空添加自定义模型定义。运行时观察到的 provider 失败也始终写入这一最高优先级 model override,避免 extension-provided runtime compat 遮挡修复。自检会验证完整的 provider → custom model → runtime model → modelOverride 结果;无效的低层写入会被拒绝。
278
278
 
279
279
  **非交互模式:** 拒绝写入,显示手动编辑指引。
280
280
 
281
- **运行:** 当 active model 检测到 compat 问题时执行 `/cache-optimizer fix`。compat 已完整时,命令显示"无需修复"。
281
+ **运行:** 当 active model 检测到 compat 问题时执行 `/cache-optimizer fix`。仅缺少 affinity 的提醒按 provider 在当前扩展实例内去重,并指向这一确认式命令;模型专属提醒仍单独显示。compat 已完整时,命令显示"无需修复"。
282
282
 
283
283
  ## `/cache-optimizer rollback`
284
284
 
285
- Rollback 可通过补全、直接命令和交互菜单使用,并始终需要 UI 确认。命令会选择匹配当前 provider/model 的最新未回滚 receipt,验证备份与文件 hash,创建新的保留访问权限的 rollback backup,并使用临时文件 + 原子替换。Fix 与 rollback 在多个 extension instance 间串行执行;rollback 还会把预览时的 receipt transaction id/hash 绑定到提交阶段,若另一事务替换 receipt 就安全拒绝。没有交互式 UI 时只提供手动恢复指引,不会写入文件。
285
+ Rollback 可通过补全、直接命令和交互菜单使用,并始终需要 UI 确认。命令会选择匹配当前 provider/model(provider 级 receipt 可从同 provider 任一模型操作)的最新未回滚 receipt,验证备份与文件 hash,创建新的保留访问权限的 rollback backup,并使用临时文件 + 原子替换。Fix 与 rollback 在多个 extension instance 间串行执行;rollback 还会把预览时的 receipt transaction id/hash 绑定到提交阶段,若另一事务替换 receipt 就安全拒绝。没有交互式 UI 时只提供手动恢复指引,不会写入文件。
286
286
 
287
287
  如果 `models.json` 自 fix 后没有变化,rollback 可以恢复完整的 pre-fix JSONC;如果文件发生变化,则绝不会盲目替换整个文件,只会在 receipt-owned scalar key 仍等于记录的 post-fix 值时撤销该 key,并保留之后的用户修改。如果 receipt-owned key 已变化、目标被删除/移动,或 fix 新建了目标项,命令会安全拒绝并指向记录的 backup 供手动检查。成功后 receipt 会标记为已回滚,并需要 `/reload` 或重启。
288
288
 
package/index.ts CHANGED
@@ -2602,7 +2602,7 @@ function isPiBuiltInLlamaCppModel(model: PiModel | undefined): boolean {
2602
2602
  }
2603
2603
 
2604
2604
  function shouldInjectOpenAIPromptCacheKeyForModel(model: PiModel | undefined): boolean {
2605
- // Pi 0.85.1 has no native supportsPromptCacheKey compat field. Per-model
2605
+ // Pi 0.87.1 has no native supportsPromptCacheKey compat field. Per-model
2606
2606
  // opt-out is owned by this extension's promptCacheKey.omit configuration;
2607
2607
  // this helper only exposes the transport API gate for fixture consumers.
2608
2608
  return isOpenAICompatibleApi(model?.api);
@@ -4200,7 +4200,7 @@ function buildOpenAIProxyCompatWarningText(key: string, missing: string[]): stri
4200
4200
  const modelsJsonPath = getModelsJsonDisplayPath();
4201
4201
  const lines: string[] = [
4202
4202
  `💡 pi-cache-optimizer: ${key} is a third-party OpenAI-compatible proxy but merged compat lacks ${missing.join(" and ")}.`,
4203
- `Edit ${modelsJsonPath} -> providers["${providerLabel}"] -> compat (at the same level as baseUrl/api/apiKey/models).`,
4203
+ `Run /cache-optimizer fix to preview a confirmed repair (or edit ${modelsJsonPath} -> providers["${providerLabel}"] -> compat manually).`,
4204
4204
  ``,
4205
4205
  ];
4206
4206
 
@@ -5312,7 +5312,12 @@ function notifyCacheCompatIfNeeded(
5312
5312
  const text = adapter?.warningText?.(model);
5313
5313
  if (!adapter || !text) return;
5314
5314
 
5315
- const key = `${adapter.id}:${modelKey(model)}`;
5315
+ const affinityOnly = adapter.warningText !== undefined &&
5316
+ describeMissingOpenAICompatibleProxyCompat(model).length === 1 &&
5317
+ describeMissingCacheCompatForModel(model).length === 1;
5318
+ const key = affinityOnly
5319
+ ? `proxy-affinity:${model.provider}`
5320
+ : `${adapter.id}:${modelKey(model)}`;
5316
5321
  if (warnedModels.has(key)) return;
5317
5322
  warnedModels.add(key);
5318
5323
 
@@ -7425,6 +7430,50 @@ interface ModelOverrideNodeLocation {
7425
7430
  modelOverrideCompatEnd: number;
7426
7431
  }
7427
7432
 
7433
+ interface ProviderCompatNodeLocation {
7434
+ providerObjectBrace: number;
7435
+ providerObjectEnd: number;
7436
+ providerCompatBrace: number;
7437
+ providerCompatEnd: number;
7438
+ }
7439
+
7440
+ /** Locate a unique provider and its direct compat object without requiring models[]. */
7441
+ function locateProviderCompatInJsonc(
7442
+ text: string,
7443
+ providerLabel: string,
7444
+ ): ProviderCompatNodeLocation | undefined {
7445
+ const clean = stripJsoncComments(text);
7446
+ const rootBrace = skipJsonWhitespace(clean, 0);
7447
+ if (clean[rootBrace] !== "{") return undefined;
7448
+ const providersKey = findJsonObjectKey(clean, rootBrace, "providers");
7449
+ if (!providersKey || providersKey.count !== 1) return undefined;
7450
+ const providersBrace = skipJsonWhitespace(clean, providersKey.valueStart);
7451
+ if (clean[providersBrace] !== "{") return undefined;
7452
+ const providersEnd = findMatchingBracket(clean, providersBrace);
7453
+ if (providersEnd === undefined) return undefined;
7454
+ const providerKey = findJsonObjectKey(clean, providersBrace, providerLabel);
7455
+ if (!providerKey || providerKey.count !== 1 || providerKey.keyStart > providersEnd) return undefined;
7456
+ const providerObjectBrace = skipJsonWhitespace(clean, providerKey.valueStart);
7457
+ if (clean[providerObjectBrace] !== "{") return undefined;
7458
+ const providerObjectEnd = findMatchingBracket(clean, providerObjectBrace);
7459
+ if (providerObjectEnd === undefined || providerObjectEnd > providersEnd) return undefined;
7460
+
7461
+ for (const key of ["models", "modelOverrides"]) {
7462
+ const child = findJsonObjectKey(clean, providerObjectBrace, key);
7463
+ if (child?.count && child.count > 1) return undefined;
7464
+ }
7465
+ const compatKey = findJsonObjectKey(clean, providerObjectBrace, "compat");
7466
+ if (compatKey?.count && compatKey.count > 1) return undefined;
7467
+ if (!compatKey) {
7468
+ return { providerObjectBrace, providerObjectEnd, providerCompatBrace: -1, providerCompatEnd: -1 };
7469
+ }
7470
+ const providerCompatBrace = skipJsonWhitespace(clean, compatKey.valueStart);
7471
+ if (clean[providerCompatBrace] !== "{") return undefined;
7472
+ const providerCompatEnd = findMatchingBracket(clean, providerCompatBrace);
7473
+ if (providerCompatEnd === undefined || providerCompatEnd > providerObjectEnd) return undefined;
7474
+ return { providerObjectBrace, providerObjectEnd, providerCompatBrace, providerCompatEnd };
7475
+ }
7476
+
7428
7477
  /** Locate a provider and optional modelOverrides entry without requiring models[]. */
7429
7478
  function locateModelOverrideInJsonc(
7430
7479
  text: string,
@@ -8383,9 +8432,44 @@ function chooseFixPlacement(
8383
8432
  return decision;
8384
8433
  }
8385
8434
 
8435
+ type CompatInsertionLocation = Pick<ModelNodeLocation,
8436
+ | "modelObjectBrace"
8437
+ | "compatObjectBrace"
8438
+ | "compatObjectEnd"
8439
+ | "providerObjectBrace"
8440
+ | "providerCompatBrace"
8441
+ | "providerCompatEnd"
8442
+ | "modelOverrideObjectBrace"
8443
+ | "modelOverrideCompatBrace"
8444
+ | "modelOverrideCompatEnd"
8445
+ >;
8446
+
8447
+ function composeProviderAffinityInsertion(
8448
+ original: string,
8449
+ providerLabel: string,
8450
+ ): { modifiedText: string; placementLabel: string } | undefined {
8451
+ const location = locateProviderCompatInJsonc(original, providerLabel);
8452
+ if (!location) return undefined;
8453
+ const node: CompatInsertionLocation = {
8454
+ modelObjectBrace: -1,
8455
+ compatObjectBrace: -1,
8456
+ compatObjectEnd: -1,
8457
+ providerObjectBrace: location.providerObjectBrace,
8458
+ providerCompatBrace: location.providerCompatBrace,
8459
+ providerCompatEnd: location.providerCompatEnd,
8460
+ modelOverrideObjectBrace: -1,
8461
+ modelOverrideCompatBrace: -1,
8462
+ modelOverrideCompatEnd: -1,
8463
+ };
8464
+ return {
8465
+ modifiedText: composeFixInsertion(original, node, { sendSessionAffinityHeaders: true }, "provider"),
8466
+ placementLabel: `providers["${providerLabel}"] -> compat (provider level)`,
8467
+ };
8468
+ }
8469
+
8386
8470
  function composeFixInsertion(
8387
8471
  original: string,
8388
- location: ModelNodeLocation,
8472
+ location: CompatInsertionLocation,
8389
8473
  compatKeys: Record<string, unknown>,
8390
8474
  placement: "provider" | "model" | "modelOverride" = "model",
8391
8475
  ): string {
@@ -9464,20 +9548,27 @@ function locateReceiptCompatTarget(
9464
9548
  };
9465
9549
  }
9466
9550
 
9551
+ if (placement === "provider") {
9552
+ const location = locateProviderCompatInJsonc(text, provider);
9553
+ if (!location) return undefined;
9554
+ return {
9555
+ targetExists: true,
9556
+ compatBrace: location.providerCompatBrace,
9557
+ compatEnd: location.providerCompatEnd,
9558
+ };
9559
+ }
9467
9560
  const location = locateModelInJsonc(text, provider, modelId);
9468
9561
  if (!location || location.providerKeyCount !== 1) return undefined;
9469
- // A changed-file surgical rollback cannot tell which duplicate model object
9470
- // was the receipt's target. Refuse that ambiguity instead of touching a
9471
- // later user-added definition. Provider-level changes do not need to inspect
9472
- // model compat, but duplicate target ids still make the receipt identity
9473
- // ambiguous and are rejected for both placements.
9562
+ // A changed-file model-scoped rollback cannot tell which duplicate model
9563
+ // object was the receipt's target. Refuse that ambiguity instead of touching
9564
+ // a later user-added definition. Provider-level receipts returned above do
9565
+ // not depend on model-array identity.
9474
9566
  if (location.allModelIds.filter((id) => id === modelId).length !== 1) return undefined;
9475
- if (placement === "provider" && location.providerCompatKeyCount > 1) return undefined;
9476
- if (placement === "model" && location.modelCompatKeyCount > 1) return undefined;
9567
+ if (location.modelCompatKeyCount > 1) return undefined;
9477
9568
  return {
9478
9569
  targetExists: location.modelObjectBrace >= 0,
9479
- compatBrace: placement === "provider" ? location.providerCompatBrace : location.compatObjectBrace,
9480
- compatEnd: placement === "provider" ? location.providerCompatEnd : location.compatObjectEnd,
9570
+ compatBrace: location.compatObjectBrace,
9571
+ compatEnd: location.compatObjectEnd,
9481
9572
  };
9482
9573
  }
9483
9574
 
@@ -10163,11 +10254,13 @@ export const __internals_for_tests = {
10163
10254
  hasExplicitLongRetentionOptInFromConfig,
10164
10255
  locateModelInJsonc,
10165
10256
  locateModelOverrideInJsonc,
10257
+ locateProviderCompatInJsonc,
10166
10258
  composeFixInsertion,
10167
10259
  selfCheckFix,
10168
10260
  analyzeModelsJsonForMissingEntry,
10169
10261
  composeMissingEntryInsertion,
10170
10262
  composeModelOverrideInsertion,
10263
+ composeProviderAffinityInsertion,
10171
10264
  selfCheckMissingEntryInsertion,
10172
10265
  decideFixPlacement,
10173
10266
  chooseFixPlacement,
@@ -10277,7 +10370,12 @@ export default function (pi: ExtensionAPI) {
10277
10370
  };
10278
10371
  }
10279
10372
  if (isSessionAffinity403Applicable(model) && sendSessionAffinityHeaders403Models.has(key)) {
10280
- return { providerLabel, modelId: model.id, compatKeys: { sendSessionAffinityHeaders: false } };
10373
+ return {
10374
+ providerLabel,
10375
+ modelId: model.id,
10376
+ compatKeys: { sendSessionAffinityHeaders: false },
10377
+ forceModelLevel: true,
10378
+ };
10281
10379
  }
10282
10380
  return undefined;
10283
10381
  }
@@ -11462,7 +11560,8 @@ export default function (pi: ExtensionAPI) {
11462
11560
  const useConfigReceipt = isActionablePromptCacheKeyConfigReceipt(configReceipt) &&
11463
11561
  configReceipt.provider === model.provider &&
11464
11562
  configReceipt.modelId === model.id &&
11465
- (!isActionableModelsJsonFixReceipt(modelsReceipt) || modelsReceipt.provider !== model.provider || modelsReceipt.modelId !== model.id || configReceipt.appliedAt >= modelsReceipt.appliedAt);
11563
+ (!isActionableModelsJsonFixReceipt(modelsReceipt) || modelsReceipt.provider !== model.provider ||
11564
+ (modelsReceipt.placement !== "provider" && modelsReceipt.modelId !== model.id) || configReceipt.appliedAt >= modelsReceipt.appliedAt);
11466
11565
  if (useConfigReceipt) {
11467
11566
  if (!cmdCtx.hasUI) {
11468
11567
  cmdCtx.ui.notify("❌ Rollback requires interactive confirmation. No changes were made.\nRun /cache-optimizer rollback in Pi's interactive UI to restore the prompt-cache-key setting.", "warning");
@@ -11505,7 +11604,7 @@ export default function (pi: ExtensionAPI) {
11505
11604
  cmdCtx.ui.notify("ℹ️ No unapplied /cache-optimizer fix receipt was found.", "info");
11506
11605
  return;
11507
11606
  }
11508
- if (receipt.provider !== model.provider || receipt.modelId !== model.id) {
11607
+ if (receipt.provider !== model.provider || (receipt.placement !== "provider" && receipt.modelId !== model.id)) {
11509
11608
  cmdCtx.ui.notify(
11510
11609
  `ℹ️ The latest fix receipt is for ${receipt.provider}/${receipt.modelId}, not the active model ${model.provider}/${model.id}. ` +
11511
11610
  "Switch to the matching model before running rollback. No changes were made.",
@@ -11743,6 +11842,79 @@ export default function (pi: ExtensionAPI) {
11743
11842
  const location = locateModelInJsonc(originalText, suggestion.providerLabel, suggestion.modelId);
11744
11843
  if (!location) {
11745
11844
  const diagnosis = analyzeModelsJsonForMissingEntry(originalText, suggestion.providerLabel, suggestion.modelId);
11845
+ const parsedOriginal = (() => { try { return parseJsonc(originalText); } catch { return undefined; } })();
11846
+ const provider = asRecord(asRecord(parsedOriginal)?.providers)?.[suggestion.providerLabel];
11847
+ const explicit = resolveExplicitCompatValue(parsedOriginal, suggestion.providerLabel, suggestion.modelId, "sendSessionAffinityHeaders");
11848
+ const targetOverrideLocation = locateModelOverrideInJsonc(
11849
+ originalText, suggestion.providerLabel, suggestion.modelId,
11850
+ );
11851
+ const hasTargetOverride = (targetOverrideLocation?.modelOverrideObjectBrace ?? -1) >= 0;
11852
+ const providerPlan = diagnosis && diagnosis.scenario !== "provider_missing" &&
11853
+ isValidModelsConfigForEffectiveCompat(parsedOriginal) && asRecord(provider) &&
11854
+ Object.keys(suggestion.compatKeys).length === 1 && suggestion.compatKeys.sendSessionAffinityHeaders === true &&
11855
+ !suggestion.forceModelLevel && !hasTargetOverride && explicit === undefined &&
11856
+ getEffectiveCompatValueSource(model, parsedOriginal, "sendSessionAffinityHeaders") === undefined
11857
+ ? composeProviderAffinityInsertion(originalText, suggestion.providerLabel)
11858
+ : undefined;
11859
+ if (providerPlan) {
11860
+ const checkProvider = (writtenText: string): string | null => {
11861
+ try {
11862
+ const changed = parseJsonc(writtenText);
11863
+ if (!isValidModelsConfigForEffectiveCompat(changed)) return "provider config is invalid";
11864
+ if (resolveEffectiveCompatFromConfig(model, changed).sendSessionAffinityHeaders !== true) return "affinity flag is not effective";
11865
+ const reverted = JSON.parse(JSON.stringify(changed)) as Record<string, unknown>;
11866
+ const target = asRecord(asRecord(reverted.providers)?.[suggestion.providerLabel]);
11867
+ const compat = asRecord(target?.compat);
11868
+ if (!target || !compat || compat.sendSessionAffinityHeaders !== true) return "provider affinity key is missing";
11869
+ delete compat.sendSessionAffinityHeaders;
11870
+ const originalCompat = asRecord(asRecord(provider)?.compat);
11871
+ if (!originalCompat) delete target.compat;
11872
+ return JSON.stringify(reverted) === JSON.stringify(parsedOriginal) ? null : "unrelated configuration was altered";
11873
+ } catch { return "invalid provider JSONC"; }
11874
+ };
11875
+ const checkError = checkProvider(providerPlan.modifiedText);
11876
+ if (checkError) {
11877
+ cmdCtx.ui.notify(`❌ Provider-level self-check failed: ${checkError}. No changes were made.`, "error");
11878
+ return;
11879
+ }
11880
+ const backupPath = `${MODELS_JSON_PATH}.backup-cache-optimizer-${backupTimestamp()}`;
11881
+ const confirmed = await cmdCtx.ui.confirm("Cache Optimizer — Fix provider affinity", [
11882
+ `📝 Preview of changes to ${getModelsJsonDisplayPath()}:`,
11883
+ `Location: ${providerPlan.placementLabel}`,
11884
+ `Compat JSON to write: ${JSON.stringify(suggestion.compatKeys)}`,
11885
+ `⚠️ This affects all models using this provider across all sessions; model-level overrides remain authoritative.`,
11886
+ `A timestamped backup will be written to: ${backupPath}`,
11887
+ "Run /reload or restart Pi for the change to take effect.",
11888
+ "Apply these changes?",
11889
+ ].join("\n"));
11890
+ if (!confirmed) {
11891
+ cmdCtx.ui.notify("No changes were made. Canceled by user.", "info");
11892
+ return;
11893
+ }
11894
+ const receipt = createModelsJsonFixReceipt(
11895
+ originalText, providerPlan.modifiedText, suggestion.providerLabel, suggestion.modelId,
11896
+ "provider", suggestion.compatKeys, true, backupPath,
11897
+ );
11898
+ if (!receipt) {
11899
+ cmdCtx.ui.notify("❌ Could not create a privacy-safe fix receipt. No changes were made.", "error");
11900
+ return;
11901
+ }
11902
+ try {
11903
+ const result = await applyModelsJsonFixTransaction(providerPlan.modifiedText, backupPath, checkProvider, {
11904
+ expectedCurrentHash: hashText(originalText), purpose: "fix",
11905
+ onCommitted: async () => writeModelsJsonFixReceipt(receipt),
11906
+ });
11907
+ if ("postCheckError" in result) {
11908
+ cmdCtx.ui.notify(`❌ Post-write self-check failed: ${result.postCheckError}. Backup restored.`, "error");
11909
+ return;
11910
+ }
11911
+ invalidateModelsConfigCache();
11912
+ cmdCtx.ui.notify(`✅ Fix applied to ${getModelsJsonDisplayPath()}.\nBackup saved to: ${backupPath}\nRun /reload or restart Pi.`, "info");
11913
+ } catch (error) {
11914
+ cmdCtx.ui.notify(`❌ Write failed: ${error instanceof Error ? error.message : String(error)}. Backup may be at: ${backupPath}`, "error");
11915
+ }
11916
+ return;
11917
+ }
11746
11918
  if (diagnosis && cmdCtx.hasUI) {
11747
11919
  const overrideLocation = locateModelOverrideInJsonc(
11748
11920
  originalText, suggestion.providerLabel, suggestion.modelId,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-cache-optimizer",
3
- "version": "2.8.10",
3
+ "version": "2.8.11",
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",
@@ -35,8 +35,8 @@
35
35
  "check": "npm run typecheck && npm test && npm run check:diff && npm run check:pack"
36
36
  },
37
37
  "devDependencies": {
38
- "@earendil-works/pi-coding-agent": "^0.85.1",
39
- "@earendil-works/pi-server": "0.85.1",
38
+ "@earendil-works/pi-coding-agent": "^0.87.1",
39
+ "@earendil-works/pi-server": "0.87.1",
40
40
  "@types/node": "^22.0.0",
41
41
  "jiti": "^2.7.0",
42
42
  "typescript": "^5.8.3"