pi-cache-optimizer 2.10.4 → 2.10.6
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 +59 -0
- package/README.md +5 -5
- package/README.zh-CN.md +5 -5
- package/index.ts +53 -6
- package/package.json +4 -3
- package/src/cache-warming.ts +136 -11
- package/src/command.ts +18 -5
- package/src/host-pi.ts +18 -0
- package/src/models-json-lint.ts +16 -12
- package/src/prompt-rewrite.ts +84 -26
- package/src/request-payload.ts +10 -1
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
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.6] - 2026-11-13
|
|
9
|
+
|
|
10
|
+
### Changed
|
|
11
|
+
|
|
12
|
+
- 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).
|
|
13
|
+
- 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.
|
|
14
|
+
- 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.
|
|
15
|
+
- 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.
|
|
16
|
+
- `models.json` key hints know the Pi 1.5.1 compat keys `promptCacheKeyMode`, `requiresNonNullAssistantContent`, `requiresToolsWithToolHistory` and `supportsMessageThreads`.
|
|
17
|
+
- Validated against Pi 1.5.2.
|
|
18
|
+
|
|
19
|
+
## [2.10.5] - 2026-11-04
|
|
20
|
+
|
|
21
|
+
### Fixed
|
|
22
|
+
|
|
23
|
+
- 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.
|
|
24
|
+
- 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.
|
|
25
|
+
|
|
26
|
+
### Changed
|
|
27
|
+
|
|
28
|
+
- `models.json` key hints know the Pi 1.4 compat keys `imageInput` and `sendImageOptInHeader`, and the hint text no longer names a Pi version.
|
|
29
|
+
- Validated against Pi 1.5.0.
|
|
30
|
+
|
|
31
|
+
## [2.10.4] - 2026-10-20
|
|
32
|
+
|
|
33
|
+
### Added
|
|
34
|
+
|
|
35
|
+
- 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)).
|
|
36
|
+
|
|
37
|
+
## [2.10.3] - 2026-10-20
|
|
38
|
+
|
|
39
|
+
### Fixed
|
|
40
|
+
|
|
41
|
+
- 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).
|
|
42
|
+
|
|
43
|
+
## [2.10.2] - 2026-10-18
|
|
44
|
+
|
|
45
|
+
### Fixed
|
|
46
|
+
|
|
47
|
+
- A session's usage is no longer lost on exit when its final stats write failed; the write is retried once at shutdown.
|
|
48
|
+
|
|
49
|
+
## [2.10.1] - 2026-10-18
|
|
50
|
+
|
|
51
|
+
### Fixed
|
|
52
|
+
|
|
53
|
+
- 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`).
|
|
54
|
+
|
|
55
|
+
## [2.10.0] - 2026-10-18
|
|
56
|
+
|
|
57
|
+
### Changed
|
|
58
|
+
|
|
59
|
+
- 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.
|
|
67
|
+
This extension requires Pi 0.82+ and is validated against Pi 1.5.2. 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,18 +226,18 @@ 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
|
|
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).
|
|
230
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.
|
|
231
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.
|
|
232
232
|
- This extension's `doctor` and `compat` commands only advise; they do not modify `models.json`.
|
|
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`
|
|
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.
|
|
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.
|
|
67
|
+
本扩展要求 Pi 0.82+,并已使用 Pi 1.5.2 验证。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,18 +226,18 @@ 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
|
|
229
|
+
- 如果修改 `models.json` 后 compat 警告仍反复出现,请检查拼写:Pi 会忽略未知 key,`model0verrides`、`sendSessionAfinityHeaders` 这类拼错的 key 很可能不会生效。警告、`doctor` 和 `fix` 会指出疑似拼错的已知 Pi key(仅提示,不会自动改名)。
|
|
230
230
|
- DeepSeek 模型名只用于选择 `DS cache` adapter,不能证明 reasoning wire protocol。缺少或使用非 DeepSeek format 时仍保留通用缓存 / 路由建议;只有 effective `compat.thinkingFormat: "deepseek"` 被明确配置时,才显示 DeepSeek replay 建议,且不会把 `thinkingFormat` 列为缺失修复项。
|
|
231
231
|
- 不要因为模型 id 含有 `deepseek` 就添加 `thinkingFormat: "deepseek"`;catalog 中也存在 `openai`、`qwen`、`openrouter`、`together` 或没有显式 format 的情况。
|
|
232
232
|
- 本扩展的 `doctor` 和 `compat` 命令只给建议,不会修改 `models.json`。
|
|
233
233
|
|
|
234
234
|
## Prompt cache 保温(Pi 0.86+)
|
|
235
235
|
|
|
236
|
-
Pi 自带缓存保温:在缓存条目过期前,用一个 token 的输出上限原样重放上一次请求(全局设置 `cacheWarming`:`off`、`streaming
|
|
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
|
|
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
|
|
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,11 +20,12 @@ 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 {
|
|
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";
|
|
26
|
-
import { SKILL_COMPRESSION_MIN_COUNT, compressSkillsInSystemPrompt, compressSkillsViaSection, formatSkillsForPrompt, formatSkillsForPromptCompressed, stripSessionOverviewChurn, explainSkillCompressionSkip, recordSkillCompressionOutcome, getLastSkillCompressionOutcome, describeSkillCompressionOutcome } from "./src/prompt-rewrite.ts";
|
|
28
|
+
import { SKILL_COMPRESSION_MIN_COUNT, SKILL_PATH_RULE_WORDINGS, compressSkillsInSystemPrompt, compressSkillsViaSection, formatSkillsForPrompt, formatSkillsForPromptCompressed, stripSessionOverviewChurn, explainSkillCompressionSkip, recordSkillCompressionOutcome, getLastSkillCompressionOutcome, describeSkillCompressionOutcome } from "./src/prompt-rewrite.ts";
|
|
27
29
|
import { addEffectiveSessionAffinityHeaders, addOpenAIPromptCacheKey, clampPromptCacheKey, collectAnthropicCacheControlsInWireOrder, downgradeAnthropicLongCacheControls, getEffectiveCompatValueSource, hasAnthropicCacheTtlOrderError, hasEffectivePromptCacheKey, isPromptCacheKeyOmittedForModel, normalizeAnthropicCacheControlTtlOrder, omitOpenAIPromptCacheKeys, shouldInjectOpenAIPromptCacheKeyForModel, withAnthropicCacheTtlRepair, withoutPromptCacheRetention, derivePromptCacheKey } from "./src/request-payload.ts";
|
|
28
30
|
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
31
|
import { CONFIG_RECEIPT_PATH, applyPromptCacheKeyConfigFix, configReceiptBackupPath, parsePromptCacheKeyConfigReceipt, rollbackPromptCacheKeyConfig, writePromptCacheKeyConfigReceipt } from "./src/prompt-cache-key-config.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
|
|
@@ -152,6 +156,9 @@ export const __internals_for_tests = {
|
|
|
152
156
|
formatSkillsForPromptCompressed,
|
|
153
157
|
compressSkillsInSystemPrompt,
|
|
154
158
|
SKILL_COMPRESSION_MIN_COUNT,
|
|
159
|
+
SKILL_PATH_RULE_WORDINGS,
|
|
160
|
+
compressSkillsViaSection,
|
|
161
|
+
explainSkillCompressionSkip,
|
|
155
162
|
NO_PROMPT_REWRITE_ENV,
|
|
156
163
|
isEnabledEnv,
|
|
157
164
|
featureEnabled,
|
|
@@ -445,7 +452,41 @@ export const __internals_for_tests = {
|
|
|
445
452
|
appendAdaptiveThinkingCompatAdviceLines,
|
|
446
453
|
};
|
|
447
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
|
+
|
|
448
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
|
+
});
|
|
449
490
|
const warnedModels = new Set<string>();
|
|
450
491
|
const promptCacheRetention400Models = new Set<string>();
|
|
451
492
|
const warnedPromptCacheRetention400Models = new Set<string>();
|
|
@@ -1713,7 +1754,13 @@ export default function (pi: ExtensionAPI) {
|
|
|
1713
1754
|
// "cache economics unavailable". Older hosts never emit this event.
|
|
1714
1755
|
pi.on("cache_warming_decision", (event, ctx) => {
|
|
1715
1756
|
if (!isZeroPriceWarmingEnabled()) return undefined;
|
|
1716
|
-
|
|
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 });
|
|
1717
1764
|
return action ? { action } : undefined;
|
|
1718
1765
|
});
|
|
1719
1766
|
|
|
@@ -2018,7 +2065,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
2018
2065
|
if (!warnedPromptCacheKeyRejectedModels.has(key)) {
|
|
2019
2066
|
warnedPromptCacheKeyRejectedModels.add(key);
|
|
2020
2067
|
ctx.ui.notify(
|
|
2021
|
-
`⚠️ ${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.`,
|
|
2022
2069
|
"warning",
|
|
2023
2070
|
);
|
|
2024
2071
|
}
|
|
@@ -2146,7 +2193,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
2146
2193
|
if (!warnedPromptCacheKeyRejectedModels.has(key)) {
|
|
2147
2194
|
warnedPromptCacheKeyRejectedModels.add(key);
|
|
2148
2195
|
ctx.ui.notify(
|
|
2149
|
-
`⚠️ ${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.`,
|
|
2150
2197
|
"warning",
|
|
2151
2198
|
);
|
|
2152
2199
|
}
|
|
@@ -2356,7 +2403,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
2356
2403
|
getCurrentSessionHash: () => currentSessionHash,
|
|
2357
2404
|
getLastStatusText: () => lastStatusText,
|
|
2358
2405
|
clearLastStatusText: () => { lastStatusText = undefined; },
|
|
2359
|
-
|
|
2406
|
+
getCacheWarmingSetting: () => readHostCacheWarmingSetting(),
|
|
2360
2407
|
});
|
|
2361
2408
|
|
|
2362
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.
|
|
3
|
+
"version": "2.10.6",
|
|
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.
|
|
41
|
+
"@earendil-works/pi-coding-agent": "^1.5.2",
|
|
41
42
|
"@earendil-works/pi-server": "^1.1.0",
|
|
42
43
|
"@types/node": "^22.0.0",
|
|
43
44
|
"jiti": "^2.7.0",
|
package/src/cache-warming.ts
CHANGED
|
@@ -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
|
-
*
|
|
38
|
-
*
|
|
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
|
|
41
|
-
if (typeof getSettings !== "function") return "unsupported";
|
|
42
|
-
let
|
|
103
|
+
export function readCacheWarmingSetting(sources: CacheWarmingSettingsSources): CacheWarmingSetting | "unsupported" {
|
|
104
|
+
if (typeof sources.getSettings !== "function") return "unsupported";
|
|
105
|
+
let merged: unknown;
|
|
43
106
|
try {
|
|
44
|
-
|
|
107
|
+
merged = sources.getSettings();
|
|
45
108
|
} catch {
|
|
46
109
|
return "unsupported";
|
|
47
110
|
}
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
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
|
-
|
|
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
|
|
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
|
-
|
|
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
|
|
124
|
+
const warmingSetting = runtime.getCacheWarmingSetting?.();
|
|
125
|
+
const warmingLines = warmingSetting !== undefined
|
|
120
126
|
? buildCacheWarmingDiagnosis(model, {
|
|
121
|
-
mode:
|
|
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
|
+
}
|
package/src/models-json-lint.ts
CHANGED
|
@@ -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.
|
|
16
|
+
* Known key sets are copied from Pi 1.5.2 (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):
|
|
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.
|
|
23
|
+
export const MODELS_JSON_SCHEMA_SOURCE_VERSION = "1.5.2";
|
|
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.
|
|
41
|
+
/** Object.keys(ProviderCompatSchema.properties) in Pi 1.5.2, sorted. */
|
|
41
42
|
export const MODELS_JSON_COMPAT_KEYS: readonly string[] = [
|
|
42
43
|
"allowEmptySignature", "allowedFallbackModels", "cacheControlFormat", "chatTemplateArgs", "chatTemplateKwargs",
|
|
43
|
-
"forceAdaptiveThinking", "maxTokensField", "openRouterRouting", "
|
|
44
|
+
"forceAdaptiveThinking", "imageInput", "maxTokensField", "openRouterRouting", "promptCacheKeyMode",
|
|
45
|
+
"requiresAssistantAfterToolResult", "requiresNonNullAssistantContent",
|
|
44
46
|
"requiresReasoningContentOnAssistantMessages", "requiresThinkingAsText", "requiresToolResultName",
|
|
45
|
-
"
|
|
46
|
-
"
|
|
47
|
-
"
|
|
48
|
-
"
|
|
49
|
-
"
|
|
50
|
-
"
|
|
51
|
-
"
|
|
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 =
|
|
@@ -277,7 +281,7 @@ export function selectModelsJsonKeyTyposForTarget(
|
|
|
277
281
|
}
|
|
278
282
|
|
|
279
283
|
export function formatModelsJsonKeyTypo(typo: ModelsJsonKeyTypo): string {
|
|
280
|
-
return `⚠️ ${typo.path} is not a known Pi
|
|
284
|
+
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
285
|
}
|
|
282
286
|
|
|
283
287
|
/** Formatted hint lines for one provider/model, read from models.json on disk. Never throws. */
|
package/src/prompt-rewrite.ts
CHANGED
|
@@ -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
|
-
/**
|
|
37
|
-
|
|
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
|
-
|
|
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
|
|
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
|
|
166
|
-
|
|
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
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
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
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
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
|
-
|
|
221
|
-
|
|
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
|
|
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";
|
package/src/request-payload.ts
CHANGED
|
@@ -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
|
-
|
|
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 {
|