pi-cache-optimizer 2.10.5 → 2.10.7

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/CHANGELOG.md ADDED
@@ -0,0 +1,69 @@
1
+ # Changelog
2
+
3
+ On Pi 1.5+, after `pi update --extensions` (or `--all`), the next fresh interactive launch shows entries newer than the
4
+ last version Pi recorded for this package under "Extension Updates". Pi records the version silently the first time
5
+ it sees this file, so notes start with the update after that.
6
+ Older history is in the [git log](https://github.com/jiangge/pi-cache-optimizer/commits/master).
7
+
8
+ ## [2.10.7] - 2026-11-21
9
+
10
+ ### Fixed
11
+
12
+ - Pi 1.6.0's built-in llama.cpp models are recognised again, so they no longer get proxy and session-affinity advice meant for third-party OpenAI-compatible gateways. Pi 1.6.0 stopped setting `compat.supportsDeveloperRole: false` on them. A same-id `llama.cpp` provider that sets cache or routing overrides (`promptCacheKeyMode`, `cacheControlFormat`, `openRouterRouting`, `vercelGatewayRouting`) is no longer treated as the built-in one.
13
+
14
+ ### Changed
15
+
16
+ - Validated against Pi 1.6.0. Its `models.json` compat keys are unchanged.
17
+
18
+ ## [2.10.6] - 2026-11-13
19
+
20
+ ### Changed
21
+
22
+ - Supports Pi 1.5.1 and 1.5.2, whose default `cacheWarming` is now `idle`. `/cache-optimizer doctor` reports Pi's actual default, reads the mode from global settings as Pi does, and notes when only project settings set `cacheWarming` (Pi ignores it there).
23
+ - Zero-price warming (the `warm` answer for models whose prices are all zero) now covers refreshes between agent runs only when you set `"cacheWarming": "idle"` in global settings yourself. With Pi's new idle default it covers agent runs only, as before, so upgrading Pi does not start paid idle refreshes on channels that bill despite zero prices.
24
+ - A model whose `compat.promptCacheKeyMode` is `"disabled"` (Pi 1.5.1+) no longer gets a `prompt_cache_key` from this extension, and the 400-error hint recommends that setting. `/cache-optimizer fix prompt-cache-key` makes no change for such a model.
25
+ - Pi's global `settings.json` is read the way Pi reads it (strict JSON, BOM stripped; an unreadable or invalid file means Pi's defaults), so a comment in the file no longer counts as an explicit `cacheWarming` choice.
26
+ - `models.json` key hints know the Pi 1.5.1 compat keys `promptCacheKeyMode`, `requiresNonNullAssistantContent`, `requiresToolsWithToolHistory` and `supportsMessageThreads`.
27
+ - Validated against Pi 1.5.2.
28
+
29
+ ## [2.10.5] - 2026-11-04
30
+
31
+ ### Fixed
32
+
33
+ - Skill-list compression works on Pi 1.5. Pi 1.5 reworded the path rule in its skills preamble, so the verbose `<available_skills>` list was no longer recognised and compression silently stopped (`/cache-optimizer doctor` only reported an unrecognised format). Both the Pi 1.5 wording and the earlier wording are recognised, and the compressed preamble keeps the wording Pi rendered.
34
+ - A subagent whose inherited prompt was rendered by a different Pi version (one copy of the skill list in each wording) no longer ends up with a forced system prompt: every copy is compressed as a section edit.
35
+
36
+ ### Changed
37
+
38
+ - `models.json` key hints know the Pi 1.4 compat keys `imageInput` and `sendImageOptInHeader`, and the hint text no longer names a Pi version.
39
+ - Validated against Pi 1.5.0.
40
+
41
+ ## [2.10.4] - 2026-10-20
42
+
43
+ ### Added
44
+
45
+ - Misspelled `models.json` keys (for example `model0verrides`), which Pi silently ignores, are flagged in compat warnings, `/cache-optimizer doctor` and `fix`, with the key they probably meant. Hint only; nothing is renamed ([#30](https://github.com/jiangge/pi-cache-optimizer/issues/30)).
46
+
47
+ ## [2.10.3] - 2026-10-20
48
+
49
+ ### Fixed
50
+
51
+ - The verbose skill list is also compressed inside an inherited `customPrompt`, so subagents of an idle parent are no longer forced onto a full system prompt ([#31](https://github.com/jiangge/pi-cache-optimizer/pull/31), thanks @xulongwu4).
52
+
53
+ ## [2.10.2] - 2026-10-18
54
+
55
+ ### Fixed
56
+
57
+ - A session's usage is no longer lost on exit when its final stats write failed; the write is retried once at shutdown.
58
+
59
+ ## [2.10.1] - 2026-10-18
60
+
61
+ ### Fixed
62
+
63
+ - Footer stats no longer lose the previous session's usage for the day when a host keeps one extension instance across sessions (a second `session_start`).
64
+
65
+ ## [2.10.0] - 2026-10-18
66
+
67
+ ### Changed
68
+
69
+ - Incremental footer refresh: a tiered shard index and a non-blocking, coalesced refresh, so footer refreshes after tool calls and messages no longer block Pi ([#28](https://github.com/jiangge/pi-cache-optimizer/issues/28)). Turn it off with `/cache-optimizer config stats-incremental off` or `PI_CACHE_OPTIMIZER_STATS_INCREMENTAL=0`.
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.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.
67
+ This extension requires Pi 0.82+ and is validated against Pi 1.6.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
 
@@ -233,11 +233,11 @@ Notes:
233
233
 
234
234
  ## Prompt cache warming (Pi 0.86+)
235
235
 
236
- Pi itself can keep a prompt cache alive by re-sending the last request with a one-token output cap shortly before the entry expires (the global `cacheWarming` setting: `off`, `streaming` (default), or `idle`; change it with `/settings` → Cache warming or `"cacheWarming"` in `~/.pi/agent/settings.json`). This extension does not run a keepalive timer of its own: a second warmer would pay for duplicate refreshes and cannot replay Pi's exact request.
236
+ Pi itself can keep a prompt cache alive by re-sending the last request with a one-token output cap shortly before the entry expires (the global `cacheWarming` setting: `off`, `streaming`, or `idle`; the default is `idle` since Pi 1.5.1 and `streaming` before; change it with `/settings` → Cache warming or `"cacheWarming"` in `~/.pi/agent/settings.json`; Pi ignores a `cacheWarming` in project settings). This extension does not run a keepalive timer of its own: a second warmer would pay for duplicate refreshes and cannot replay Pi's exact request.
237
237
 
238
- Pi only warms a model that declares a cache lifetime for the retention tier in use, has input/cache prices, and is replayable (Anthropic budget-based thinking is not). Custom proxy models in `models.json` often lack the first two, so warming never starts. For models whose prices are all zero, Pi stops with "cache economics unavailable"; this extension answers Pi's `cache_warming_decision` with `warm` in that case only, since a refresh is just a cache read plus one output token. Models with real prices keep Pi's own decision, and Pi's mode, lifetime, replayability and time limits still apply. Each refresh is a real request, so a channel that does bill despite the zero prices pays for it. Pi's `/session` still shows "cache economics unavailable" between refreshes, and if another extension also handles `cache_warming_decision`, the one Pi runs last wins. Two zeros are not treated as free: OpenRouter router models (ids starting with `openrouter/`, such as `openrouter/auto`), whose -1 placeholder price Pi 1.2.0+ shows as 0 although the routed model is billed, and models whose Pi 1.2.0 `cost.tiers` carry a positive price. Turn it off with `/cache-optimizer config zero-price-warming off` or `PI_CACHE_OPTIMIZER_NO_ZERO_PRICE_WARMING=1`. `/cache-optimizer doctor` now reports the mode, the tier, and what is missing, with a snippet such as `"promptCache": {"short":300,"long":3600}` for `anthropic-messages` models. Put it on the model entry (custom models) or under the provider's `modelOverrides` (built-in models), or run `/cache-optimizer fix prompt-cache` to have it written for you: it previews the edit, asks for confirmation, keeps a timestamped backup and comments, and records a receipt so `/cache-optimizer rollback` removes exactly that `promptCache` object (or restores the whole file if nothing else changed). It writes `{"short":300,"long":3600}` for `anthropic-messages` models (Anthropic's documented 5m/1h, the values Pi ships for its own Claude models) and `{"short":300}` elsewhere; when the long tier is in use and no long lifetime is documented for the API, it refuses rather than guessing. It never merges into or overwrites an existing `promptCache`, and it does not create a provider entry that models.json lacks.
238
+ Pi only warms a model that declares a cache lifetime for the retention tier in use, has input/cache prices, and is replayable (Anthropic budget-based thinking is not). Custom proxy models in `models.json` often lack the first two, so warming never starts. For models whose prices are all zero, Pi stops with "cache economics unavailable"; this extension answers Pi's `cache_warming_decision` with `warm` in that case only, since a refresh is just a cache read plus one output token. Models with real prices keep Pi's own decision, and Pi's mode, lifetime, replayability and time limits still apply. Each refresh is a real request, so a channel that does bill despite the zero prices pays for it. For that reason the override covers refreshes between agent runs only when you set `"cacheWarming": "idle"` in global settings yourself; with Pi 1.5.1+'s idle default it covers agent runs only, as before. Pi's `/session` still shows "cache economics unavailable" between refreshes, and if another extension also handles `cache_warming_decision`, the one Pi runs last wins. Two zeros are not treated as free: OpenRouter router models (ids starting with `openrouter/`, such as `openrouter/auto`), whose -1 placeholder price Pi 1.2.0+ shows as 0 although the routed model is billed, and models whose Pi 1.2.0 `cost.tiers` carry a positive price. Turn it off with `/cache-optimizer config zero-price-warming off` or `PI_CACHE_OPTIMIZER_NO_ZERO_PRICE_WARMING=1`. `/cache-optimizer doctor` now reports the mode, the tier, and what is missing, with a snippet such as `"promptCache": {"short":300,"long":3600}` for `anthropic-messages` models. Put it on the model entry (custom models) or under the provider's `modelOverrides` (built-in models), or run `/cache-optimizer fix prompt-cache` to have it written for you: it previews the edit, asks for confirmation, keeps a timestamped backup and comments, and records a receipt so `/cache-optimizer rollback` removes exactly that `promptCache` object (or restores the whole file if nothing else changed). It writes `{"short":300,"long":3600}` for `anthropic-messages` models (Anthropic's documented 5m/1h, the values Pi ships for its own Claude models) and `{"short":300}` elsewhere; when the long tier is in use and no long lifetime is documented for the API, it refuses rather than guessing. It never merges into or overwrites an existing `promptCache`, and it does not create a provider entry that models.json lacks.
239
239
 
240
- Streaming warming stops 60 minutes after the real request and idle warming after 30 minutes. With this extension's 1-hour retention, the refresh would fire at 54 minutes, so `idle` adds nothing; the 1-hour lifetime already covers breaks under an hour. Keep the default `streaming` unless you use 5-minute caches and often return within half an hour.
240
+ Streaming warming stops 60 minutes after the real request and idle warming after 30 minutes. With this extension's 1-hour retention, the refresh would fire at 54 minutes, so `idle` adds nothing; the 1-hour lifetime already covers breaks under an hour. `streaming` is enough unless you use 5-minute caches and often return within half an hour; Pi 1.5.1+ defaults to `idle`, which only warms between runs when Pi expects the refresh to pay for itself.
241
241
 
242
242
  ## Anthropic cache TTL compatibility
243
243
 
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.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 要求一致。
67
+ 本扩展要求 Pi 0.82+,并已使用 Pi 1.6.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
 
@@ -233,11 +233,11 @@ Pi 0.84.1 还修复了内置 Fireworks 渠道对拒绝 `prompt_cache_retention`
233
233
 
234
234
  ## Prompt cache 保温(Pi 0.86+)
235
235
 
236
- Pi 自带缓存保温:在缓存条目过期前,用一个 token 的输出上限原样重放上一次请求(全局设置 `cacheWarming`:`off`、`streaming`(默认)或 `idle`;在 `/settings` → Cache warming 中修改,或在 `~/.pi/agent/settings.json` 中设置 `"cacheWarming"`)。本扩展不自行运行保活定时器:第二个保温器会重复计费,而且无法精确重放 Pi 的请求。
236
+ Pi 自带缓存保温:在缓存条目过期前,用一个 token 的输出上限原样重放上一次请求(全局设置 `cacheWarming`:`off`、`streaming` 或 `idle`;Pi 1.5.1 起默认 `idle`,之前默认 `streaming`;在 `/settings` → Cache warming 中修改,或在 `~/.pi/agent/settings.json` 中设置 `"cacheWarming"`;项目设置里的 `cacheWarming` 会被 Pi 忽略)。本扩展不自行运行保活定时器:第二个保温器会重复计费,而且无法精确重放 Pi 的请求。
237
237
 
238
- Pi 只会为满足以下条件的模型保温:为当前保留档位声明了缓存时长、有输入/缓存价格、请求可重放(Anthropic 基于 budget 的 thinking 不可重放)。`models.json` 里的自定义代理模型常常缺前两项,保温根本不会启动。对价格全为 0 的模型,Pi 会以 “cache economics unavailable” 停止保温;本扩展仅在这种情况下通过 `cache_warming_decision` 返回 `warm`,因为一次刷新只是一次缓存读取加一个输出 token。有真实价格的模型仍按 Pi 自己的判断,Pi 的模式、缓存时长、可重放性和时间上限也照常生效。每次刷新都是一次真实请求,若渠道价格写 0 但实际计费,会产生费用。刷新间隔里 Pi 的 `/session` 仍会显示 “cache economics unavailable”;若其他扩展也处理 `cache_warming_decision`,以 Pi 最后执行的那个为准。有两种 0 不算免费:OpenRouter 路由模型(ID 以 `openrouter/` 开头,如 `openrouter/auto`),其 -1 占位价格在 Pi 1.2.0+ 显示为 0,但实际按路由到的模型计费;以及 Pi 1.2.0 `cost.tiers` 中有正价格的模型。可用 `/cache-optimizer config zero-price-warming off` 或 `PI_CACHE_OPTIMIZER_NO_ZERO_PRICE_WARMING=1` 关闭。`/cache-optimizer doctor` 现在会显示保温模式、档位和缺失项,并给出片段,例如 `anthropic-messages` 模型的 `"promptCache": {"short":300,"long":3600}`。自定义模型写在该模型条目中,内置模型写在 provider 的 `modelOverrides` 下;也可以运行 `/cache-optimizer fix prompt-cache` 一键写入:先预览、需确认、保留带时间戳的备份和注释,并记录 receipt,`/cache-optimizer rollback` 只会删除这次加入的 `promptCache` 对象(若文件之后没有改动则整文件恢复)。`anthropic-messages` 模型写入 `{"short":300,"long":3600}`(Anthropic 文档的 5 分钟/1 小时,与 Pi 内置 Claude 模型一致),其他 API 写入 `{"short":300}`;若当前使用长档位而该 API 没有文档化的长时长,则拒绝写入而不是猜测。已有 `promptCache` 时不会合并或覆盖,models.json 中不存在的 provider 条目也不会被创建。
238
+ Pi 只会为满足以下条件的模型保温:为当前保留档位声明了缓存时长、有输入/缓存价格、请求可重放(Anthropic 基于 budget 的 thinking 不可重放)。`models.json` 里的自定义代理模型常常缺前两项,保温根本不会启动。对价格全为 0 的模型,Pi 会以 “cache economics unavailable” 停止保温;本扩展仅在这种情况下通过 `cache_warming_decision` 返回 `warm`,因为一次刷新只是一次缓存读取加一个输出 token。有真实价格的模型仍按 Pi 自己的判断,Pi 的模式、缓存时长、可重放性和时间上限也照常生效。每次刷新都是一次真实请求,若渠道价格写 0 但实际计费,会产生费用。因此只有你在全局设置里自己写了 `"cacheWarming": "idle"`,覆盖才延伸到两次运行之间;使用 Pi 1.5.1+ 的 idle 默认值时,覆盖仍只作用于 agent 运行期间,与以前一致。刷新间隔里 Pi 的 `/session` 仍会显示 “cache economics unavailable”;若其他扩展也处理 `cache_warming_decision`,以 Pi 最后执行的那个为准。有两种 0 不算免费:OpenRouter 路由模型(ID 以 `openrouter/` 开头,如 `openrouter/auto`),其 -1 占位价格在 Pi 1.2.0+ 显示为 0,但实际按路由到的模型计费;以及 Pi 1.2.0 `cost.tiers` 中有正价格的模型。可用 `/cache-optimizer config zero-price-warming off` 或 `PI_CACHE_OPTIMIZER_NO_ZERO_PRICE_WARMING=1` 关闭。`/cache-optimizer doctor` 现在会显示保温模式、档位和缺失项,并给出片段,例如 `anthropic-messages` 模型的 `"promptCache": {"short":300,"long":3600}`。自定义模型写在该模型条目中,内置模型写在 provider 的 `modelOverrides` 下;也可以运行 `/cache-optimizer fix prompt-cache` 一键写入:先预览、需确认、保留带时间戳的备份和注释,并记录 receipt,`/cache-optimizer rollback` 只会删除这次加入的 `promptCache` 对象(若文件之后没有改动则整文件恢复)。`anthropic-messages` 模型写入 `{"short":300,"long":3600}`(Anthropic 文档的 5 分钟/1 小时,与 Pi 内置 Claude 模型一致),其他 API 写入 `{"short":300}`;若当前使用长档位而该 API 没有文档化的长时长,则拒绝写入而不是猜测。已有 `promptCache` 时不会合并或覆盖,models.json 中不存在的 provider 条目也不会被创建。
239
239
 
240
- streaming 保温在真实请求后 60 分钟停止,idle 保温在 30 分钟后停止。本扩展使用 1 小时保留时,刷新会在第 54 分钟才触发,所以 `idle` 没有额外作用;1 小时的缓存本身已覆盖一小时内的中断。除非你使用 5 分钟缓存且经常在半小时内回来,否则保持默认的 `streaming` 即可。
240
+ streaming 保温在真实请求后 60 分钟停止,idle 保温在 30 分钟后停止。本扩展使用 1 小时保留时,刷新会在第 54 分钟才触发,所以 `idle` 没有额外作用;1 小时的缓存本身已覆盖一小时内的中断。除非你使用 5 分钟缓存且经常在半小时内回来,否则 `streaming` 就够了;Pi 1.5.1 起默认 `idle`,只在 Pi 估计刷新划算时才在两次运行之间保温。
241
241
 
242
242
  ## Anthropic 缓存 TTL 兼容
243
243
 
package/index.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import { appendFile, lstat, mkdir } from "node:fs/promises";
3
3
  import { basename, join } from "node:path";
4
+ import { readFileSync } from "node:fs";
4
5
  import {
5
6
  type ExtensionAPI, type ExtensionContext
6
7
  } from "@earendil-works/pi-coding-agent";
@@ -19,7 +20,8 @@ import { countingStatsReadFs, setStatsReadFsForTests, statsReadFs } from "./src/
19
20
  import { PI_VIRTUAL_MODEL_API, getCompat, isAnthropicMessagesApi, isKimiCodingEmptySignatureModel, isKnownThirdPartyOpenAIEndpoint, isMistralConversationsApi, isNativeVirtualModel, isOfficialOpenAIBaseUrl, isOpenAICompatibleApi, isOpenAICompatibleProxyApi, isOpenAIFamilyAssistantMessage, isOpenAIFamilyModel, isOpenAIFamilyToken, isPiBuiltInLlamaCppModel, isResponsesPromptRewriteBypassApi, isRoutedFallbackModel, isValidModelsConfigForEffectiveCompat, modelKey, readEffectiveCompatConfig } from "./src/model-identity.ts";
20
21
  import { STATS_INCREMENTAL_ENV, STATS_TIMING_ENV, STATS_VERIFY_ENV, isStatsIncrementalEnabled, isStatsVerifyEnabled, statsTimingLogPath } from "./src/config.ts";
21
22
  import { CONFIG_FILE_PATH, VIRTUAL_REWRITE_ENV, FOOTER_MODE_ENV, TOOL_ORDER_ENV, featureEnabled, footerStatsMode, isEnabledEnv, isToolOrderEnabled, parseFooterStatsMode, parsePersistedCacheOptimizerConfig, readPersistedCacheOptimizerConfig, resolveFooterStatsMode, runtimeOptimizerEnabled, setPersistedCacheOptimizerConfig, shouldInjectOpenAIPromptCacheKey, writePersistedCacheOptimizerConfig, writePersistedFeature, writePersistedFooterMode } from "./src/config.ts";
22
- import { decideZeroPriceWarming, readCacheWarmingMode } from "./src/cache-warming.ts";
23
+ import { HOST_PI_VERSION, readHostCacheWarmingDefault } from "./src/host-pi.ts";
24
+ import { decideZeroPriceWarming, isIdleWarmingDecision, readCacheWarmingSetting } from "./src/cache-warming.ts";
23
25
  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
26
  import { isRuntimeOptimizerEnabled, isZeroPriceWarmingEnabled, setRuntimeOptimizerEnabled } from "./src/config.ts";
25
27
  import { compareToolOrderEntries, getToolNameForPayload, isKnownToolOrderApi, isToolOrderingEligibleModel, isVerifiedToolForApi, normalizeToolsInPayload, sortToolsInPayload } from "./src/tool-ordering.ts";
@@ -114,6 +116,8 @@ let latestStatsRestoreForTests: Promise<void> = Promise.resolve();
114
116
  const statsRefreshSettledForTests = new Set<() => Promise<void>>();
115
117
 
116
118
  export const __internals_for_tests = {
119
+ parseGlobalPiSettingsText: (text: string): unknown => parseGlobalPiSettingsText(text),
120
+ readHostCacheWarmingDefault: (): unknown => readHostCacheWarmingDefault(),
117
121
  waitForStatsRestore: (): Promise<void> => latestStatsRestoreForTests,
118
122
  /**
119
123
  * Footer refreshes after tool_execution_end, agent_settled and message_end
@@ -448,7 +452,41 @@ export const __internals_for_tests = {
448
452
  appendAdaptiveThinkingCompatAdviceLines,
449
453
  };
450
454
 
455
+ /**
456
+ * Pi's global settings, the only source it reads `cacheWarming` from, parsed
457
+ * the way Pi parses them: strict JSON after stripping a BOM; a missing, empty
458
+ * unreadable or unparsable file counts as no settings, so Pi's default applies.
459
+ */
460
+ function readGlobalPiSettings(): unknown {
461
+ let text: string;
462
+ try {
463
+ text = readFileSync(join(STATE_DIR, "settings.json"), "utf8");
464
+ } catch {
465
+ // Pi treats an unreadable global settings file as no settings, so its default applies.
466
+ return {};
467
+ }
468
+ return parseGlobalPiSettingsText(text);
469
+ }
470
+
471
+ function parseGlobalPiSettingsText(text: string): unknown {
472
+ const body = text.charCodeAt(0) === 0xfeff ? text.slice(1) : text;
473
+ if (body.trim() === "") return {};
474
+ try {
475
+ const parsed: unknown = JSON.parse(body);
476
+ return asRecord(parsed) ?? {};
477
+ } catch {
478
+ return {};
479
+ }
480
+ }
481
+
482
+
451
483
  export default function (pi: ExtensionAPI) {
484
+ const readHostCacheWarmingSetting = () => readCacheWarmingSetting({
485
+ getSettings: typeof pi.getSettings === "function" ? () => pi.getSettings() : undefined,
486
+ readGlobalSettings: readGlobalPiSettings,
487
+ hostDefaultMode: readHostCacheWarmingDefault,
488
+ piVersion: HOST_PI_VERSION,
489
+ });
452
490
  const warnedModels = new Set<string>();
453
491
  const promptCacheRetention400Models = new Set<string>();
454
492
  const warnedPromptCacheRetention400Models = new Set<string>();
@@ -1716,7 +1754,13 @@ export default function (pi: ExtensionAPI) {
1716
1754
  // "cache economics unavailable". Older hosts never emit this event.
1717
1755
  pi.on("cache_warming_decision", (event, ctx) => {
1718
1756
  if (!isZeroPriceWarmingEnabled()) return undefined;
1719
- const action = decideZeroPriceWarming(event, ctx.model);
1757
+ // Between runs, only a user-chosen idle mode extends the override (Pi 1.5.1 made idle the default).
1758
+ let idleExplicit = false;
1759
+ if (isIdleWarmingDecision(event)) {
1760
+ const setting = readHostCacheWarmingSetting();
1761
+ idleExplicit = setting !== "unsupported" && setting.explicit && setting.mode === "idle";
1762
+ }
1763
+ const action = decideZeroPriceWarming(event, ctx.model, { idleExplicit });
1720
1764
  return action ? { action } : undefined;
1721
1765
  });
1722
1766
 
@@ -2021,7 +2065,7 @@ export default function (pi: ExtensionAPI) {
2021
2065
  if (!warnedPromptCacheKeyRejectedModels.has(key)) {
2022
2066
  warnedPromptCacheKeyRejectedModels.add(key);
2023
2067
  ctx.ui.notify(
2024
- `⚠️ ${LOG_PREFIX}: ${key} rejected prompt_cache_key. Run /cache-optimizer fix to review a precise model-scoped repair. No configuration was changed automatically.`,
2068
+ `⚠️ ${LOG_PREFIX}: ${key} rejected prompt_cache_key. Run /cache-optimizer fix to review a precise model-scoped repair (on Pi 1.5.1+ you can instead set compat.promptCacheKeyMode to \"disabled\" for this model in models.json). No configuration was changed automatically.`,
2025
2069
  "warning",
2026
2070
  );
2027
2071
  }
@@ -2149,7 +2193,7 @@ export default function (pi: ExtensionAPI) {
2149
2193
  if (!warnedPromptCacheKeyRejectedModels.has(key)) {
2150
2194
  warnedPromptCacheKeyRejectedModels.add(key);
2151
2195
  ctx.ui.notify(
2152
- `⚠️ ${LOG_PREFIX}: ${key} rejected prompt_cache_key. Run /cache-optimizer fix to review a precise model-scoped repair. No configuration was changed automatically.`,
2196
+ `⚠️ ${LOG_PREFIX}: ${key} rejected prompt_cache_key. Run /cache-optimizer fix to review a precise model-scoped repair (on Pi 1.5.1+ you can instead set compat.promptCacheKeyMode to \"disabled\" for this model in models.json). No configuration was changed automatically.`,
2153
2197
  "warning",
2154
2198
  );
2155
2199
  }
@@ -2359,7 +2403,7 @@ export default function (pi: ExtensionAPI) {
2359
2403
  getCurrentSessionHash: () => currentSessionHash,
2360
2404
  getLastStatusText: () => lastStatusText,
2361
2405
  clearLastStatusText: () => { lastStatusText = undefined; },
2362
- getCacheWarmingMode: () => readCacheWarmingMode(typeof pi.getSettings === "function" ? () => pi.getSettings() : undefined),
2406
+ getCacheWarmingSetting: () => readHostCacheWarmingSetting(),
2363
2407
  });
2364
2408
 
2365
2409
  pi.registerCommand("cache-optimizer", {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-cache-optimizer",
3
- "version": "2.10.5",
3
+ "version": "2.10.7",
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",
@@ -17,7 +17,8 @@
17
17
  "license": "MIT",
18
18
  "files": [
19
19
  "index.ts",
20
- "src"
20
+ "src",
21
+ "CHANGELOG.md"
21
22
  ],
22
23
  "pi": {
23
24
  "extensions": [
@@ -37,7 +38,7 @@
37
38
  "check:modules": "node scripts/check-module-graph.mjs"
38
39
  },
39
40
  "devDependencies": {
40
- "@earendil-works/pi-coding-agent": "^1.5.0",
41
+ "@earendil-works/pi-coding-agent": "^1.6.0",
41
42
  "@earendil-works/pi-server": "^1.1.0",
42
43
  "@types/node": "^22.0.0",
43
44
  "jiti": "^2.7.0",
@@ -21,7 +21,10 @@ import { buildModelsJsonTypoHintLines } from "./models-json-lint.ts";
21
21
 
22
22
  export type CacheWarmingMode = "off" | "streaming" | "idle";
23
23
 
24
+ /** Pi's default before 1.5.1. */
24
25
  export const CACHE_WARMING_DEFAULT_MODE: CacheWarmingMode = "streaming";
26
+ /** Pi 1.5.1 changed the `cacheWarming` default from "streaming" to "idle". */
27
+ export const CACHE_WARMING_IDLE_DEFAULT_SINCE = "1.5.1";
25
28
  export const CACHE_WARMING_STREAMING_MAX_MS = 60 * 60_000;
26
29
  export const CACHE_WARMING_IDLE_MAX_MS = 30 * 60_000;
27
30
 
@@ -31,23 +34,108 @@ export function cacheWarmingRefreshDelayMs(ttlMs: number): number | undefined {
31
34
  return Math.max(1, Math.floor(Math.min(ttlMs * 0.9, ttlMs - 10_000)));
32
35
  }
33
36
 
37
+ function parseVersionCore(version: string | undefined): [number, number, number] | undefined {
38
+ const match = typeof version === "string" ? /^v?(\d+)\.(\d+)\.(\d+)/.exec(version.trim()) : null;
39
+ return match ? [Number(match[1]), Number(match[2]), Number(match[3])] : undefined;
40
+ }
41
+
42
+ /**
43
+ * The mode Pi uses when global settings name none: "idle" from Pi 1.5.1,
44
+ * "streaming" before. An unknown host version keeps the older default.
45
+ */
46
+ export function cacheWarmingDefaultMode(piVersion: string | undefined): CacheWarmingMode {
47
+ const atLeast = isPiVersionAtLeast(piVersion, CACHE_WARMING_IDLE_DEFAULT_SINCE);
48
+ if (atLeast === undefined) return CACHE_WARMING_DEFAULT_MODE;
49
+ return atLeast ? "idle" : "streaming";
50
+ }
51
+
52
+ /** Whether `piVersion` is at least `minimum` (major.minor.patch); undefined when it cannot be parsed. */
53
+ export function isPiVersionAtLeast(piVersion: string | undefined, minimum: string): boolean | undefined {
54
+ const host = parseVersionCore(piVersion);
55
+ const since = parseVersionCore(minimum);
56
+ if (!host || !since) return undefined;
57
+ for (let i = 0; i < 3; i++) {
58
+ if (host[i] !== since[i]) return host[i] > since[i];
59
+ }
60
+ return true;
61
+ }
62
+
34
63
  export type CacheWarmingSettingsReader = () => unknown;
35
64
 
65
+ function parseMode(value: unknown): CacheWarmingMode | undefined {
66
+ return value === "off" || value === "streaming" || value === "idle" ? value : undefined;
67
+ }
68
+
69
+ export type CacheWarmingSetting = {
70
+ /** The mode Pi actually uses. */
71
+ mode: CacheWarmingMode;
72
+ /** True when the user's global settings name a valid mode; false when Pi falls back to its default. */
73
+ explicit: boolean;
74
+ /**
75
+ * A valid `cacheWarming` that only project settings (or SDK overrides) carry.
76
+ * Pi reads warming from global settings only (warming costs money), so it is ignored.
77
+ */
78
+ ignoredProjectMode?: CacheWarmingMode;
79
+ };
80
+
81
+ export type CacheWarmingSettingsSources = {
82
+ /**
83
+ * Pi's own default, from the host (`SettingsManager.inMemory().getCacheWarmingMode()`).
84
+ * Preferred over the version comparison, which is the fallback.
85
+ */
86
+ hostDefaultMode?: () => unknown;
87
+ /** `pi.getSettings()`: global and project settings merged (Pi 0.86+). */
88
+ getSettings?: CacheWarmingSettingsReader;
89
+ /**
90
+ * Global settings only, the source Pi reads warming from. Returns undefined
91
+ * when they cannot be read; then the merged settings are used instead.
92
+ */
93
+ readGlobalSettings?: CacheWarmingSettingsReader;
94
+ /** Host Pi version, which decides the default. */
95
+ piVersion?: string;
96
+ };
97
+
36
98
  /**
37
- * Read the `cacheWarming` mode from `pi.getSettings()` (Pi 0.86+). Returns
38
- * undefined when the host has no settings API or no warming support.
99
+ * Resolve the `cacheWarming` mode the way Pi does: the global setting when it
100
+ * is valid, else the host version's default. Returns "unsupported" when the
101
+ * host has no settings API (no warming support).
39
102
  */
40
- export function readCacheWarmingMode(getSettings: CacheWarmingSettingsReader | undefined): CacheWarmingMode | "unsupported" {
41
- if (typeof getSettings !== "function") return "unsupported";
42
- let settings: unknown;
103
+ export function readCacheWarmingSetting(sources: CacheWarmingSettingsSources): CacheWarmingSetting | "unsupported" {
104
+ if (typeof sources.getSettings !== "function") return "unsupported";
105
+ let merged: unknown;
43
106
  try {
44
- settings = getSettings();
107
+ merged = sources.getSettings();
45
108
  } catch {
46
109
  return "unsupported";
47
110
  }
48
- const value = asRecord(settings)?.cacheWarming;
49
- if (value === "off" || value === "streaming" || value === "idle") return value;
50
- return CACHE_WARMING_DEFAULT_MODE;
111
+ let hostDefault: CacheWarmingMode | undefined;
112
+ try {
113
+ hostDefault = parseMode(sources.hostDefaultMode?.());
114
+ } catch {
115
+ hostDefault = undefined;
116
+ }
117
+ const fallback = hostDefault ?? cacheWarmingDefaultMode(sources.piVersion);
118
+ const mergedMode = parseMode(asRecord(merged)?.cacheWarming);
119
+
120
+ let global: unknown;
121
+ try {
122
+ global = sources.readGlobalSettings?.();
123
+ } catch {
124
+ global = undefined;
125
+ }
126
+ if (global === undefined) {
127
+ return mergedMode ? { mode: mergedMode, explicit: true } : { mode: fallback, explicit: false };
128
+ }
129
+ const globalMode = parseMode(asRecord(global)?.cacheWarming);
130
+ const setting: CacheWarmingSetting = globalMode ? { mode: globalMode, explicit: true } : { mode: fallback, explicit: false };
131
+ if (mergedMode !== undefined && mergedMode !== globalMode) setting.ignoredProjectMode = mergedMode;
132
+ return setting;
133
+ }
134
+
135
+ /** Compatibility wrapper: the mode alone, from merged settings and the pre-1.5.1 default. */
136
+ export function readCacheWarmingMode(getSettings: CacheWarmingSettingsReader | undefined, piVersion?: string): CacheWarmingMode | "unsupported" {
137
+ const setting = readCacheWarmingSetting({ getSettings, piVersion });
138
+ return setting === "unsupported" ? setting : setting.mode;
51
139
  }
52
140
 
53
141
  export function suggestedPromptCacheLifetimes(model: PiModel): { short: number; long?: number } {
@@ -120,6 +208,13 @@ function isReplayableForWarming(model: PiModel): boolean {
120
208
 
121
209
  export type CacheWarmingDiagnosisInput = {
122
210
  mode: CacheWarmingMode | "unsupported";
211
+ /**
212
+ * Whether global settings name the mode. Undefined keeps the old reading:
213
+ * the mode equal to CACHE_WARMING_DEFAULT_MODE is shown as the default.
214
+ */
215
+ explicit?: boolean;
216
+ /** A project-only `cacheWarming` that Pi ignores. */
217
+ ignoredProjectMode?: CacheWarmingMode;
123
218
  /** Retention tier Pi uses for this request ("long" when PI_CACHE_RETENTION=long). */
124
219
  tier: "short" | "long";
125
220
  /** Whether the extension keeps warming running for zero-price models. */
@@ -153,7 +248,11 @@ export function buildCacheWarmingDiagnosis(model: PiModel, input: CacheWarmingDi
153
248
  return { eligible: false, issues: ["unsupported"], lines };
154
249
  }
155
250
 
156
- lines.push(`- Mode: ${input.mode}${input.mode === CACHE_WARMING_DEFAULT_MODE ? " (default)" : ""} — global setting, change with /settings → Cache warming or ~/.pi/agent/settings.json`);
251
+ const isDefault = input.explicit === undefined ? input.mode === CACHE_WARMING_DEFAULT_MODE : !input.explicit;
252
+ lines.push(`- Mode: ${input.mode}${isDefault ? " (Pi default)" : ""} — global setting, change with /settings → Cache warming or ~/.pi/agent/settings.json`);
253
+ if (input.ignoredProjectMode !== undefined) {
254
+ lines.push(`- Note: project settings (or SDK overrides) set cacheWarming to "${input.ignoredProjectMode}", but Pi reads warming from global settings only, so it has no effect.`);
255
+ }
157
256
  lines.push(`- Retention tier in use: ${input.tier}`);
158
257
 
159
258
  if (input.mode === "off") {
@@ -187,6 +286,9 @@ export function buildCacheWarmingDiagnosis(model: PiModel, input: CacheWarmingDi
187
286
  if (!hasPricing(model)) {
188
287
  if (input.zeroPriceWarming && isZeroPriced(model)) {
189
288
  lines.push("- The model has no input/cache prices. Pi would skip warming; this extension overrides that (config zero-price-warming on).");
289
+ if (input.mode === "idle" && input.explicit === false) {
290
+ lines.push(" The override covers agent runs only: idle is Pi's default here, and refreshes between runs are billed by the proxy. Set cacheWarming to \"idle\" in global settings to extend it between runs.");
291
+ }
190
292
  } else if (isOpenRouterRouterModel(model)) {
191
293
  issues.push("pricing_unknown");
192
294
  lines.push("- ⚠️ OpenRouter router models list a placeholder price that Pi shows as 0, but the routed model is billed at its own price. Pi cannot estimate savings and skips warming; zero-price warming does not apply.");
@@ -220,10 +322,25 @@ export function buildCacheWarmingDiagnosis(model: PiModel, input: CacheWarmingDi
220
322
 
221
323
  export type CacheWarmingDecisionLike = {
222
324
  action?: unknown;
325
+ /** Not sent by Pi 1.5.x hooks; honoured if a future Pi adds it. */
326
+ phase?: unknown;
327
+ /** 1 during an agent run; Pi's idle estimate (below 1) between runs. */
328
+ continuationProbability?: unknown;
223
329
  warmCost?: unknown;
224
330
  missCost?: unknown;
225
331
  };
226
332
 
333
+ /**
334
+ * Whether a `cache_warming_decision` event is for a refresh between runs.
335
+ * Pi's hook event carries no phase; Pi sets continuationProbability to exactly
336
+ * 1 while streaming and to its idle estimate (below 1) between runs.
337
+ */
338
+ export function isIdleWarmingDecision(event: CacheWarmingDecisionLike): boolean {
339
+ if (event.phase === "idle") return true;
340
+ if (event.phase === "streaming") return false;
341
+ return typeof event.continuationProbability === "number" && event.continuationProbability < 1;
342
+ }
343
+
227
344
  /**
228
345
  * `cache_warming_decision` policy: Pi stops warming when it cannot price the
229
346
  * refresh ("cache economics unavailable"), which is every model whose cost
@@ -232,9 +349,17 @@ export type CacheWarmingDecisionLike = {
232
349
  * the cache, so keep warming for those models. Pi's own decision stands
233
350
  * whenever the model has real prices, and Pi's mode, lifetime, replayability
234
351
  * and 60m/30m safety limits still apply.
352
+ *
353
+ * Between runs (phase "idle") the override applies only when the user chose
354
+ * `cacheWarming: "idle"` in global settings. Pi 1.5.1 made idle the default,
355
+ * and zero prices on proxy channels usually mean "not configured", not free:
356
+ * refreshing an idle session every few minutes for half an hour bills real
357
+ * money with no estimate of whether the user comes back. With the default
358
+ * mode the override keeps its pre-1.5.1 reach, agent runs only.
235
359
  */
236
- export function decideZeroPriceWarming(event: CacheWarmingDecisionLike, model: PiModel | undefined): "warm" | undefined {
360
+ export function decideZeroPriceWarming(event: CacheWarmingDecisionLike, model: PiModel | undefined, options: { idleExplicit?: boolean } = {}): "warm" | undefined {
237
361
  if (!model || event.action !== "stop") return undefined;
362
+ if (isIdleWarmingDecision(event) && options.idleExplicit !== true) return undefined;
238
363
  if (event.warmCost !== 0 || event.missCost !== 0) return undefined;
239
364
  if (!isZeroPriced(model)) return undefined;
240
365
  return "warm";
package/src/command.ts CHANGED
@@ -14,9 +14,11 @@ 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 { isPiVersionAtLeast } from "./cache-warming.ts";
18
+ import { HOST_PI_VERSION } from "./host-pi.ts";
17
19
  import { buildModelsJsonLintDoctorLines, buildModelsJsonTypoHintLines } from "./models-json-lint.ts";
18
20
  import { applyPromptCacheKeyConfigFix, isActionablePromptCacheKeyConfigReceipt, readPromptCacheKeyConfigReceiptSnapshot, rollbackPromptCacheKeyConfig } from "./prompt-cache-key-config.ts";
19
- import { getEffectiveCompatValueSource, isPromptCacheKeyOmittedForModel } from "./request-payload.ts";
21
+ import { getEffectiveCompatValueSource, getPromptCacheKeyMode, isPromptCacheKeyOmittedForModel } from "./request-payload.ts";
20
22
  import { describeNativeVirtualRouteNote, resolveRouteModel } from "./routing.ts";
21
23
  import { buildAllStatsOutput, buildContributorsStatsOutput, buildSessionStatsOutput } from "./stats-report.ts";
22
24
  import { type FixSuggestion } from "./fix-types.ts";
@@ -25,7 +27,10 @@ import { type CacheStats, type ShardAggregate } from "./stats-store.ts";
25
27
  import { type CacheUsageSample } from "./stats-report.ts";
26
28
  import { describeSkillCompressionOutcome } from "./prompt-rewrite.ts";
27
29
  import { describePromptCacheRetentionDecision, getLastPromptCacheRetentionDecision, LONG_CACHE_RETENTION_VALUE, PI_CACHE_RETENTION_ENV } from "./retention.ts";
28
- import { buildCacheWarmingDiagnosis, type CacheWarmingMode } from "./cache-warming.ts";
30
+ import { buildCacheWarmingDiagnosis, type CacheWarmingSetting } from "./cache-warming.ts";
31
+
32
+ /** First Pi version that honours compat.promptCacheKeyMode. */
33
+ const PROMPT_CACHE_KEY_MODE_SINCE = "1.5.1";
29
34
 
30
35
  /**
31
36
  * Everything the command needs from the extension instance. The extension keeps this state in closures
@@ -55,7 +60,7 @@ export type CommandRuntime = {
55
60
  getLastStatusText(): string | undefined;
56
61
  clearLastStatusText(): void;
57
62
  /** Pi `cacheWarming` mode, or "unsupported" on hosts without the settings API. */
58
- getCacheWarmingMode?(): CacheWarmingMode | "unsupported";
63
+ getCacheWarmingSetting?(): CacheWarmingSetting | "unsupported";
59
64
  };
60
65
 
61
66
  export function createCacheOptimizerCommandHandler(runtime: CommandRuntime) {
@@ -116,9 +121,12 @@ export function createCacheOptimizerCommandHandler(runtime: CommandRuntime) {
116
121
  const samples = sk ? getRecentSamples(sk) : [];
117
122
  const lowHitLines = buildLowHitDiagnosis(model, adapter, statsState, samples);
118
123
  const routeNote = describeNativeVirtualRouteNote(selectedModel, model);
119
- const warmingLines = runtime.getCacheWarmingMode
124
+ const warmingSetting = runtime.getCacheWarmingSetting?.();
125
+ const warmingLines = warmingSetting !== undefined
120
126
  ? buildCacheWarmingDiagnosis(model, {
121
- mode: runtime.getCacheWarmingMode(),
127
+ mode: warmingSetting === "unsupported" ? "unsupported" : warmingSetting.mode,
128
+ explicit: warmingSetting === "unsupported" ? undefined : warmingSetting.explicit,
129
+ ignoredProjectMode: warmingSetting === "unsupported" ? undefined : warmingSetting.ignoredProjectMode,
122
130
  tier: process.env[PI_CACHE_RETENTION_ENV] === LONG_CACHE_RETENTION_VALUE ? "long" : "short",
123
131
  zeroPriceWarming: isZeroPriceWarmingEnabled(),
124
132
  typoHints: false,
@@ -414,6 +422,11 @@ export function createCacheOptimizerCommandHandler(runtime: CommandRuntime) {
414
422
  cmdCtx.ui.notify(`✅ prompt_cache_key is already omitted for "${modelKey(model)}".`, "info");
415
423
  return;
416
424
  }
425
+ // Only Pi 1.5.1+ honours promptCacheKeyMode; older hosts still send the key themselves.
426
+ if (getPromptCacheKeyMode(model) === "disabled" && isPiVersionAtLeast(HOST_PI_VERSION, PROMPT_CACHE_KEY_MODE_SINCE) === true) {
427
+ cmdCtx.ui.notify(`✅ prompt_cache_key is already omitted for "${modelKey(model)}": its compat.promptCacheKeyMode is "disabled" (Pi 1.5.1+), and this extension does not add the key back. No changes were made.`, "info");
428
+ return;
429
+ }
417
430
  if (!cmdCtx.hasUI) {
418
431
  cmdCtx.ui.notify(
419
432
  "❌ Non-interactive terminal detected. Prompt cache key opt-out requires UI confirmation. No changes were made.\n" +
package/src/host-pi.ts ADDED
@@ -0,0 +1,18 @@
1
+ import * as piCodingAgent from "@earendil-works/pi-coding-agent";
2
+
3
+ /** Host Pi version; undefined when the host does not export it. */
4
+ export const HOST_PI_VERSION: string | undefined = (() => {
5
+ const version = (piCodingAgent as Record<string, unknown>).VERSION;
6
+ return typeof version === "string" ? version : undefined;
7
+ })();
8
+
9
+ /** Pi's own `cacheWarming` default from the host, independent of version strings. */
10
+ export function readHostCacheWarmingDefault(): unknown {
11
+ const settingsManager: unknown = (piCodingAgent as Record<string, unknown>).SettingsManager;
12
+ const inMemory = typeof settingsManager === "function" ? (settingsManager as { inMemory?: unknown }).inMemory : undefined;
13
+ if (typeof inMemory !== "function") return undefined;
14
+ const instance: unknown = inMemory.call(settingsManager, {});
15
+ if (typeof instance !== "object" || instance === null) return undefined;
16
+ const getMode = (instance as { getCacheWarmingMode?: unknown }).getCacheWarmingMode;
17
+ return typeof getMode === "function" ? getMode.call(instance) : undefined;
18
+ }
@@ -266,16 +266,23 @@ export function isPiBuiltInLlamaCppModel(model: PiModel | undefined): boolean {
266
266
  // cache/routing overrides, so provider id alone must never imply exemption.
267
267
  // supportsUsageInStreaming is deliberately not part of the fingerprint: Pi
268
268
  // 0.82.x sets it false and Pi 0.83+ sets it true after fixing streamed usage,
269
- // and it carries no routing or cache configuration.
269
+ // and it carries no routing or cache configuration. supportsDeveloperRole is
270
+ // false up to Pi 1.5.x; Pi 1.6.0 dropped it (developer role became
271
+ // api.openai.com-only by default), so absent is accepted too, but true is not.
270
272
  const compat = getCompat(model);
271
273
  return compat.supportsStore === false
272
- && compat.supportsDeveloperRole === false
274
+ && (compat.supportsDeveloperRole === false || compat.supportsDeveloperRole === undefined)
273
275
  && compat.supportsReasoningEffort === false
274
276
  && compat.supportsStrictMode === false
275
277
  && compat.maxTokensField === "max_tokens"
276
278
  && compat.sendSessionAffinityHeaders === undefined
277
279
  && compat.sessionAffinityFormat === undefined
278
- && compat.supportsLongCacheRetention === undefined;
280
+ && compat.supportsLongCacheRetention === undefined
281
+ // Cache/routing overrides Pi's built-in provider never sets.
282
+ && (compat as Record<string, unknown>).promptCacheKeyMode === undefined
283
+ && (compat as Record<string, unknown>).cacheControlFormat === undefined
284
+ && (compat as Record<string, unknown>).openRouterRouting === undefined
285
+ && (compat as Record<string, unknown>).vercelGatewayRouting === undefined;
279
286
  }
280
287
 
281
288
  export function isResponsesPromptRewriteBypassApi(api: unknown): boolean {
@@ -13,13 +13,14 @@ import { MODELS_JSON_PATH } from "./paths.ts";
13
13
  * key; unknown keys that resemble nothing are left alone so newer Pi fields
14
14
  * and personal annotations never produce noise. It never edits the file.
15
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):
16
+ * Known key sets are copied from Pi 1.6.0 (1.4.0 added compat imageInput and sendImageOptInHeader; 1.5.0 changed no keys;
17
+ * 1.5.1 added compat promptCacheKeyMode, requiresNonNullAssistantContent, requiresToolsWithToolHistory and supportsMessageThreads; 1.6.0 changed no keys):
17
18
  * - @earendil-works/pi-coding-agent dist/core/model-config.js
18
19
  * (ModelsConfigSchema, ProviderConfigSchema, ModelDefinitionSchema, ModelOverrideSchema)
19
20
  * - @earendil-works/pi-ai dist/providers/compat-schema.js
20
21
  * (ProviderCompatSchema = merged properties of every per-API compat schema)
21
22
  */
22
- export const MODELS_JSON_SCHEMA_SOURCE_VERSION = "1.5.0";
23
+ export const MODELS_JSON_SCHEMA_SOURCE_VERSION = "1.6.0";
23
24
 
24
25
  export const MODELS_JSON_ROOT_KEYS: readonly string[] = ["$schema", "providers"];
25
26
 
@@ -37,18 +38,21 @@ export const MODELS_JSON_MODEL_OVERRIDE_KEYS: readonly string[] = [
37
38
  "contextWindow", "maxTokens", "samplingParams", "samplingParamsByThinkingLevel", "headers", "compat",
38
39
  ];
39
40
 
40
- /** Object.keys(ProviderCompatSchema.properties) in Pi 1.5.0, sorted. */
41
+ /** Object.keys(ProviderCompatSchema.properties) in Pi 1.6.0, sorted. */
41
42
  export const MODELS_JSON_COMPAT_KEYS: readonly string[] = [
42
43
  "allowEmptySignature", "allowedFallbackModels", "cacheControlFormat", "chatTemplateArgs", "chatTemplateKwargs",
43
- "forceAdaptiveThinking", "imageInput", "maxTokensField", "openRouterRouting", "requiresAssistantAfterToolResult",
44
+ "forceAdaptiveThinking", "imageInput", "maxTokensField", "openRouterRouting", "promptCacheKeyMode",
45
+ "requiresAssistantAfterToolResult", "requiresNonNullAssistantContent",
44
46
  "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",
47
+ "requiresToolsWithToolHistory", "sendImageOptInHeader", "sendSessionAffinityHeaders", "sessionAffinityFormat",
48
+ "supportsAdditionalTools", "supportsCacheControlOnTools", "supportsDeveloperRole",
49
+ "supportsEagerToolInputStreaming", "supportsExplicitPromptCacheMode", "supportsFinishReason",
50
+ "supportsLongCacheRetention", "supportsMaxOutputTokens", "supportsMessageThreads", "supportsMidConvoEffort",
51
+ "supportsMidConvoSystemMessages", "supportsMidConvoToolAdditions", "supportsMidConvoToolChanges",
52
+ "supportsOpenAIGrammarTools", "supportsReasoningEffort", "supportsStore", "supportsStrictMode",
53
+ "supportsStrictTools", "supportsTemperature", "supportsThinkingTokenBudget", "supportsToolSearch",
54
+ "supportsUsageInStreaming", "thinkingFormat", "thinkingTokenBudgetField", "vercelGatewayRouting", "vllmPriority",
55
+ "zaiToolStream",
52
56
  ];
53
57
 
54
58
  export type ModelsJsonKeyLevel =
@@ -98,11 +98,20 @@ export function addEffectiveSessionAffinityHeaders(
98
98
  return changed;
99
99
  }
100
100
 
101
+ /** Pi 1.5.1+ `compat.promptCacheKeyMode` as merged into the model (provider compat, model compat, modelOverrides). */
102
+ export function getPromptCacheKeyMode(model: PiModel | undefined): "auto" | "enabled" | "disabled" | undefined {
103
+ const mode = asRecord(asRecord(model as unknown)?.compat)?.promptCacheKeyMode;
104
+ return mode === "auto" || mode === "enabled" || mode === "disabled" ? mode : undefined;
105
+ }
106
+
101
107
  export function shouldInjectOpenAIPromptCacheKeyForModel(model: PiModel | undefined): boolean {
102
108
  // Pi 1.0+ owns prompt_cache_key for Responses/Codex transports. Keep this
103
109
  // extension's fallback limited to openai-completions proxies, where Pi's
104
110
  // provider extensions may not supply the session key.
105
- return isOpenAICompatibleProxyApi(model?.api);
111
+ if (!isOpenAICompatibleProxyApi(model?.api)) return false;
112
+ // Pi 1.5.1+: compat.promptCacheKeyMode "disabled" is the user's explicit
113
+ // choice for an endpoint that rejects the key; never put it back.
114
+ return getPromptCacheKeyMode(model) !== "disabled";
106
115
  }
107
116
 
108
117
  export function isPromptCacheKeyOmittedForModel(model: PiModel | undefined, config: PersistedCacheOptimizerConfig | PersistedCacheOptimizerConfigV3 = persistedCacheOptimizerConfig): boolean {