pi-cache-optimizer 2.10.8 → 2.10.10
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 +20 -0
- package/README.md +1 -1
- package/index.ts +84 -25
- package/package.json +2 -2
- package/src/command.ts +7 -1
- package/src/models-json-lint.ts +7 -5
- package/src/request-payload.ts +32 -6
- package/src/request-state.ts +49 -0
- package/src/routing.ts +9 -3
package/CHANGELOG.md
CHANGED
|
@@ -5,6 +5,26 @@ last version Pi recorded for this package under "Extension Updates". Pi records
|
|
|
5
5
|
it sees this file, so notes start with the update after that.
|
|
6
6
|
Older history is in the [git log](https://github.com/jiangge/pi-cache-optimizer/commits/master).
|
|
7
7
|
|
|
8
|
+
## [2.10.10] - 2026-12-02
|
|
9
|
+
|
|
10
|
+
### Fixed
|
|
11
|
+
|
|
12
|
+
- `compat.promptCacheKeyMode: "disabled"` set in `models.json` now also stops this extension from adding its own `prompt_cache_key` when a provider extension supplies the model without it. Pi itself may still send a key for such a model, because it applies only `modelOverrides` compat to models an extension provider defines; `/cache-optimizer fix prompt-cache-key` now says so instead of reporting the key as already omitted. A mode other than `"auto"` or `"enabled"` from an extension provider is treated like `"disabled"`, as Pi does.
|
|
13
|
+
- Native virtual models: same-id providers are compared on the final `prompt_cache_key` action, so providers that all omit the key, or a mode difference while the cache-key fallback is off, no longer make the extension skip its other request changes.
|
|
14
|
+
- On Pi 1.6.1+, a rate-limited or server-error response that Pi retries (when `retry.provider.maxRetries` is set) no longer uses up the request's identity, so a later error notice and `/cache-optimizer fix` name the right model.
|
|
15
|
+
|
|
16
|
+
### Changed
|
|
17
|
+
|
|
18
|
+
- On Pi 1.6.1+, HTTP error diagnostics (`prompt_cache_key` or retention rejected with 400, proxy blocking with 403) also run for OpenAI-compatible providers, because Pi now reports their error responses to extensions. A 403 with a JSON body (for example no balance or a model not allowed) no longer triggers the 403 proxy-blocking advice (session-affinity headers or the OpenAI SDK's User-Agent).
|
|
19
|
+
- Validated against Pi 1.7.0. `compat.supportsReasoningReplay` is now a known `models.json` key.
|
|
20
|
+
|
|
21
|
+
## [2.10.9] - 2026-11-26
|
|
22
|
+
|
|
23
|
+
### Fixed
|
|
24
|
+
|
|
25
|
+
- Memory: the extension no longer keeps an ended session in memory (its extension instance and its last session context). Before, Pi kept every session ended by `/new`, `/resume` or `/fork` until `/reload`, and SDK hosts running several sessions kept every finished one. Thanks @o7w7o (#33).
|
|
26
|
+
- When one extension instance serves a second session after a shutdown, it publishes its prompt-cache hints for other extensions again.
|
|
27
|
+
|
|
8
28
|
## [2.10.8] - 2026-11-22
|
|
9
29
|
|
|
10
30
|
### Fixed
|
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.7.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
|
|
package/index.ts
CHANGED
|
@@ -26,7 +26,7 @@ import { LONG_CACHE_RETENTION_VALUE, PI_CACHE_RETENTION_BASELINE_SYMBOL, PI_CACH
|
|
|
26
26
|
import { isRuntimeOptimizerEnabled, isZeroPriceWarmingEnabled, setRuntimeOptimizerEnabled } from "./src/config.ts";
|
|
27
27
|
import { compareToolOrderEntries, getToolNameForPayload, isKnownToolOrderApi, isToolOrderingEligibleModel, isVerifiedToolForApi, normalizeToolsInPayload, sortToolsInPayload } from "./src/tool-ordering.ts";
|
|
28
28
|
import { SKILL_COMPRESSION_MIN_COUNT, SKILL_PATH_RULE_WORDINGS, compressSkillsInSystemPrompt, compressSkillsViaSection, formatSkillsForPrompt, formatSkillsForPromptCompressed, stripSessionOverviewChurn, explainSkillCompressionSkip, recordSkillCompressionOutcome, getLastSkillCompressionOutcome, describeSkillCompressionOutcome } from "./src/prompt-rewrite.ts";
|
|
29
|
-
import { addEffectiveSessionAffinityHeaders, addOpenAIPromptCacheKey, clampPromptCacheKey, collectAnthropicCacheControlsInWireOrder, downgradeAnthropicLongCacheControls, getEffectiveCompatValueSource, hasAnthropicCacheTtlOrderError, hasEffectivePromptCacheKey, isPromptCacheKeyOmittedForModel, normalizeAnthropicCacheControlTtlOrder, omitOpenAIPromptCacheKeys, shouldInjectOpenAIPromptCacheKeyForModel, withAnthropicCacheTtlRepair, withoutPromptCacheRetention, derivePromptCacheKey } from "./src/request-payload.ts";
|
|
29
|
+
import { addEffectiveSessionAffinityHeaders, addOpenAIPromptCacheKey, clampPromptCacheKey, collectAnthropicCacheControlsInWireOrder, downgradeAnthropicLongCacheControls, getEffectiveCompatValueSource, getPromptCacheKeyMode, isPromptCacheKeyDisabledInModelsJson, hasAnthropicCacheTtlOrderError, hasEffectivePromptCacheKey, isPromptCacheKeyOmittedForModel, normalizeAnthropicCacheControlTtlOrder, omitOpenAIPromptCacheKeys, shouldInjectOpenAIPromptCacheKeyForModel, withAnthropicCacheTtlRepair, withoutPromptCacheRetention, derivePromptCacheKey } from "./src/request-payload.ts";
|
|
30
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";
|
|
31
31
|
import { CONFIG_RECEIPT_PATH, applyPromptCacheKeyConfigFix, configReceiptBackupPath, parsePromptCacheKeyConfigReceipt, rollbackPromptCacheKeyConfig, writePromptCacheKeyConfigReceipt } from "./src/prompt-cache-key-config.ts";
|
|
32
32
|
import { buildDeepSeekCompatSuggestion, buildDeepSeekCompatWarningText, buildModelCompatOverride, buildOpenAIProxyCompatWarningText, buildProviderCompatOverride, buildSafeOpenAIProxyCompatSuggestion, describeMissingAdaptiveThinkingCompat, describeMissingCacheCompatForModel, describeMissingDeepSeekCompat, describeMissingOpenAICompatibleProxyCompat, getAgentDirDisplayPath, getModelsJsonDisplayPath, isAdaptiveThinkingCompatApplicable, isDeepSeekWireCompatApplicable } from "./src/compat-advice.ts";
|
|
@@ -41,7 +41,7 @@ import { type PiCacheHintSnapshot, getCacheHintsService, getSessionPromptCacheKe
|
|
|
41
41
|
import { isActionablePromptCacheKeyConfigReceipt, readPromptCacheKeyConfigReceipt, readPromptCacheKeyConfigReceiptSnapshot } from "./src/prompt-cache-key-config.ts";
|
|
42
42
|
import { formatOptimizerRuntimeMode, getOptimizerRuntimeModeLines, readPersistedFooterMode } from "./src/config.ts";
|
|
43
43
|
import { getCacheOptimizerArgumentCompletions } from "./src/command-completion.ts";
|
|
44
|
-
import { MAX_PROVIDER_REQUEST_STATES, pruneProviderRequestStates, snapshotProviderRequestModel } from "./src/request-state.ts";
|
|
44
|
+
import { MAX_PROVIDER_REQUEST_STATES, RETRY_PENDING_WINDOW_MS, isAwaitingProviderResponse, isJsonContentType, isRetryableProviderStatus, pruneProviderRequestStates, snapshotProviderRequestModel } from "./src/request-state.ts";
|
|
45
45
|
import { NO_PROMPT_REWRITE_ENV } from "./src/config.ts";
|
|
46
46
|
import { createCacheOptimizerCommandHandler } from "./src/command.ts";
|
|
47
47
|
import { type ProviderRequestState } from "./src/request-state.ts";
|
|
@@ -112,8 +112,15 @@ function notifyCacheCompatIfNeeded(
|
|
|
112
112
|
// this module. Tests await it after session_start; runtime code uses the
|
|
113
113
|
// per-instance promise instead.
|
|
114
114
|
let latestStatsRestoreForTests: Promise<void> = Promise.resolve();
|
|
115
|
-
/**
|
|
116
|
-
|
|
115
|
+
/**
|
|
116
|
+
* Per extension instance in this module: resolves once no footer refresh (or
|
|
117
|
+
* its publish) is in flight. Held weakly: Pi can call one loaded module's
|
|
118
|
+
* factory again (its factory cache, SDK hosts), and a strong reference here
|
|
119
|
+
* would keep every instance (and its last ctx) alive for the module's
|
|
120
|
+
* lifetime, including one that never saw session_shutdown. The instance's
|
|
121
|
+
* own handlers keep its drain function alive while the instance is.
|
|
122
|
+
*/
|
|
123
|
+
const statsRefreshSettledForTests = new Set<WeakRef<() => Promise<void>>>();
|
|
117
124
|
|
|
118
125
|
export const __internals_for_tests = {
|
|
119
126
|
parseGlobalPiSettingsText: (text: string): unknown => parseGlobalPiSettingsText(text),
|
|
@@ -125,7 +132,11 @@ export const __internals_for_tests = {
|
|
|
125
132
|
* asserting on what such a refresh publishes.
|
|
126
133
|
*/
|
|
127
134
|
statsRefreshSettled: async (): Promise<void> => {
|
|
128
|
-
for (const
|
|
135
|
+
for (const ref of Array.from(statsRefreshSettledForTests)) {
|
|
136
|
+
const settled = ref.deref();
|
|
137
|
+
if (settled) await settled();
|
|
138
|
+
else statsRefreshSettledForTests.delete(ref);
|
|
139
|
+
}
|
|
129
140
|
},
|
|
130
141
|
setStatsRefreshTestHooks,
|
|
131
142
|
setStatsReadFsForTests,
|
|
@@ -172,6 +183,12 @@ export const __internals_for_tests = {
|
|
|
172
183
|
isNonEmptyString,
|
|
173
184
|
shouldInjectOpenAIPromptCacheKey,
|
|
174
185
|
shouldInjectOpenAIPromptCacheKeyForModel,
|
|
186
|
+
isRetryableProviderStatus,
|
|
187
|
+
isAwaitingProviderResponse,
|
|
188
|
+
RETRY_PENDING_WINDOW_MS,
|
|
189
|
+
isJsonContentType,
|
|
190
|
+
getPromptCacheKeyMode,
|
|
191
|
+
isPromptCacheKeyDisabledInModelsJson,
|
|
175
192
|
isOpenAICompatibleApi,
|
|
176
193
|
isAnthropicMessagesApi,
|
|
177
194
|
isOpenAICompatibleProxyApi,
|
|
@@ -626,7 +643,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
626
643
|
}
|
|
627
644
|
}
|
|
628
645
|
|
|
629
|
-
const
|
|
646
|
+
const cacheHintsService = markOptimizerOwnedCacheHintsService({
|
|
630
647
|
version: 1,
|
|
631
648
|
getHints(input: PiCacheHintsInput): PiCacheHintsOutput | undefined {
|
|
632
649
|
if (!runtimeOptimizerEnabled || !featureEnabled("promptRewrite", NO_PROMPT_REWRITE_ENV, true)) return undefined;
|
|
@@ -645,7 +662,12 @@ export default function (pi: ExtensionAPI) {
|
|
|
645
662
|
cacheRetention: hint.cacheRetention,
|
|
646
663
|
};
|
|
647
664
|
},
|
|
648
|
-
})
|
|
665
|
+
});
|
|
666
|
+
/** Undefined once session_shutdown took the service out; the next session_start puts it back. */
|
|
667
|
+
let uninstallCacheHintsService: (() => void) | undefined = installCacheHints();
|
|
668
|
+
function installCacheHints(): () => void {
|
|
669
|
+
return installCacheHintsService(cacheHintsService, { discardPrevious: isOptimizerOwnedCacheHintsService });
|
|
670
|
+
}
|
|
649
671
|
|
|
650
672
|
/**
|
|
651
673
|
* Build a session-scoped stats key from the current session hash + model key.
|
|
@@ -1202,7 +1224,12 @@ export default function (pi: ExtensionAPI) {
|
|
|
1202
1224
|
if (backgroundStatsTasks.size === 0 && refreshScheduler.idle && !shardIndex.fullScanInFlight) return;
|
|
1203
1225
|
}
|
|
1204
1226
|
}
|
|
1205
|
-
|
|
1227
|
+
// drainStatsRefresh stays strongly reachable while this instance is: the
|
|
1228
|
+
// session_shutdown handler calls it, so it lives in the factory's shared
|
|
1229
|
+
// closure context. Keep it referenced from a handler if that call moves.
|
|
1230
|
+
const drainStatsRefreshRef = new WeakRef(drainStatsRefresh);
|
|
1231
|
+
for (const ref of statsRefreshSettledForTests) if (ref.deref() === undefined) statsRefreshSettledForTests.delete(ref);
|
|
1232
|
+
statsRefreshSettledForTests.add(drainStatsRefreshRef);
|
|
1206
1233
|
|
|
1207
1234
|
function buildCurrentStatsShard(state: "active" | "closed" = "active"): PersistedStatsShardV7 {
|
|
1208
1235
|
const now = Date.now();
|
|
@@ -1697,14 +1724,19 @@ export default function (pi: ExtensionAPI) {
|
|
|
1697
1724
|
hasExplicitLongRetentionOptIn(model),
|
|
1698
1725
|
promptCacheRetention400Models.has(key),
|
|
1699
1726
|
anthropicTtlOrderErrorModels.has(key),
|
|
1700
|
-
|
|
1701
|
-
//
|
|
1702
|
-
//
|
|
1703
|
-
// otherwise-equal candidates (PR #32).
|
|
1704
|
-
|
|
1727
|
+
// The hook's final prompt_cache_key action, not its inputs: omit wins,
|
|
1728
|
+
// then inject only while the fallback is on. "enabled", "auto" and an
|
|
1729
|
+
// unset mode all inject, so only an action difference splits
|
|
1730
|
+
// otherwise-equal candidates (PR #32). Non-proxy apis are always "none".
|
|
1731
|
+
promptCacheKeyAction(model),
|
|
1705
1732
|
]);
|
|
1706
1733
|
}
|
|
1707
1734
|
|
|
1735
|
+
function promptCacheKeyAction(model: PiModel): "omit" | "inject" | "none" {
|
|
1736
|
+
if (isPromptCacheKeyOmittedForModel(model)) return "omit";
|
|
1737
|
+
return shouldInjectOpenAIPromptCacheKey() && shouldInjectOpenAIPromptCacheKeyForModel(model) ? "inject" : "none";
|
|
1738
|
+
}
|
|
1739
|
+
|
|
1708
1740
|
pi.on("session_start", async (event, ctx) => {
|
|
1709
1741
|
if (runtimeOptimizerEnabled) requestLongCacheRetention();
|
|
1710
1742
|
// Do not block Pi's startup on historical stats (issue #28). The
|
|
@@ -1717,9 +1749,18 @@ export default function (pi: ExtensionAPI) {
|
|
|
1717
1749
|
// The same extension instance lives on across session switches
|
|
1718
1750
|
// (shutdown, then start): reopen what the shutdown closed.
|
|
1719
1751
|
refreshScheduler.open();
|
|
1752
|
+
statsRefreshSettledForTests.add(drainStatsRefreshRef);
|
|
1720
1753
|
latestStatsCtx = ctx;
|
|
1754
|
+
uninstallCacheHintsService ??= installCacheHints();
|
|
1721
1755
|
const tui = ctx.mode === "tui";
|
|
1722
|
-
if (sessionStartsHandled++ > 0)
|
|
1756
|
+
if (sessionStartsHandled++ > 0) {
|
|
1757
|
+
// The previous session's per-request state: its shutdown normally
|
|
1758
|
+
// clears it, but a start without one, or racing one, would inherit it.
|
|
1759
|
+
latestCacheHint = undefined;
|
|
1760
|
+
providerRequestStates.length = 0;
|
|
1761
|
+
delete getProtocolGlobal().__piCacheOptimizerCacheKey__;
|
|
1762
|
+
retireShardForSessionStart();
|
|
1763
|
+
}
|
|
1723
1764
|
resetStatsForSessionStart(event.reason, ctx);
|
|
1724
1765
|
const previousRestore = statsRestorePromise;
|
|
1725
1766
|
statsRestorePromise = previousRestore
|
|
@@ -1778,6 +1819,9 @@ export default function (pi: ExtensionAPI) {
|
|
|
1778
1819
|
});
|
|
1779
1820
|
|
|
1780
1821
|
pi.on("session_shutdown", async (_event, ctx) => {
|
|
1822
|
+
// A session_start on this instance while the shutdown awaited owns the
|
|
1823
|
+
// state from then on: the cleanup below must not undo it.
|
|
1824
|
+
const shutdownGeneration = statsRestoreGeneration;
|
|
1781
1825
|
try {
|
|
1782
1826
|
// Close the gate first (no new background refresh, watcher event or
|
|
1783
1827
|
// scan-triggered publish), then let what is in flight finish, then
|
|
@@ -1792,12 +1836,17 @@ export default function (pi: ExtensionAPI) {
|
|
|
1792
1836
|
await retryUnpersistedRetiredShards();
|
|
1793
1837
|
}
|
|
1794
1838
|
} finally {
|
|
1795
|
-
|
|
1796
|
-
|
|
1797
|
-
|
|
1798
|
-
|
|
1799
|
-
|
|
1800
|
-
|
|
1839
|
+
if (shutdownGeneration === statsRestoreGeneration) {
|
|
1840
|
+
closeStatsRefreshGate();
|
|
1841
|
+
statsRefreshSettledForTests.delete(drainStatsRefreshRef);
|
|
1842
|
+
latestStatsCtx = undefined;
|
|
1843
|
+
latestCacheHint = undefined;
|
|
1844
|
+
providerRequestStates.length = 0;
|
|
1845
|
+
delete getProtocolGlobal().__piCacheOptimizerCacheKey__;
|
|
1846
|
+
uninstallCacheHintsService?.();
|
|
1847
|
+
uninstallCacheHintsService = undefined;
|
|
1848
|
+
restoreCacheRetentionEnv(STARTUP_CACHE_RETENTION_ENV);
|
|
1849
|
+
}
|
|
1801
1850
|
}
|
|
1802
1851
|
});
|
|
1803
1852
|
|
|
@@ -2020,7 +2069,8 @@ export default function (pi: ExtensionAPI) {
|
|
|
2020
2069
|
});
|
|
2021
2070
|
|
|
2022
2071
|
pi.on("after_provider_response", async (event, ctx) => {
|
|
2023
|
-
const
|
|
2072
|
+
const now = Date.now();
|
|
2073
|
+
const pendingStates = providerRequestStates.filter((state) => isAwaitingProviderResponse(state, now));
|
|
2024
2074
|
let responseState: ProviderRequestState | undefined;
|
|
2025
2075
|
if (pendingStates.length === 1) {
|
|
2026
2076
|
responseState = pendingStates[0];
|
|
@@ -2037,7 +2087,14 @@ export default function (pi: ExtensionAPI) {
|
|
|
2037
2087
|
for (const state of pendingStates) state.correlationAmbiguous = true;
|
|
2038
2088
|
}
|
|
2039
2089
|
}
|
|
2040
|
-
|
|
2090
|
+
// Pi 1.6.1+ also fires this hook for HTTP error responses and for every
|
|
2091
|
+
// retried attempt, while before_provider_request fired once. A retryable
|
|
2092
|
+
// error is not the request's last response: keep its record pending so the
|
|
2093
|
+
// retry's response (and a concurrent request's) still correlates exactly.
|
|
2094
|
+
if (responseState) {
|
|
2095
|
+
if (isRetryableProviderStatus(event.status, event.headers)) responseState.retryableErrorAt = now;
|
|
2096
|
+
else responseState.responseReceived = true;
|
|
2097
|
+
}
|
|
2041
2098
|
// A native virtual request whose physical provider could not be pinned
|
|
2042
2099
|
// records no model-scoped header evidence; finalized assistant messages
|
|
2043
2100
|
// still carry exact provider/model identity.
|
|
@@ -2069,7 +2126,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
2069
2126
|
if (!warnedPromptCacheKeyRejectedModels.has(key)) {
|
|
2070
2127
|
warnedPromptCacheKeyRejectedModels.add(key);
|
|
2071
2128
|
ctx.ui.notify(
|
|
2072
|
-
`⚠️ ${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.`,
|
|
2129
|
+
`⚠️ ${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 modelOverrides). No configuration was changed automatically.`,
|
|
2073
2130
|
"warning",
|
|
2074
2131
|
);
|
|
2075
2132
|
}
|
|
@@ -2095,7 +2152,9 @@ export default function (pi: ExtensionAPI) {
|
|
|
2095
2152
|
}
|
|
2096
2153
|
|
|
2097
2154
|
// ── 403: proxy/CDN/WAF blocking ──
|
|
2098
|
-
|
|
2155
|
+
// A JSON 403 is an API-level refusal (no balance, model not allowed), not a
|
|
2156
|
+
// block page; Pi 1.6.1+ reports it for every OpenAI-compatible endpoint.
|
|
2157
|
+
if (event.status === 403 && !isJsonContentType(event.headers)) {
|
|
2099
2158
|
const key403 = modelKey(model);
|
|
2100
2159
|
|
|
2101
2160
|
// Case 1: Pi's custom session-affinity headers are enabled. Offer the
|
|
@@ -2197,7 +2256,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
2197
2256
|
if (!warnedPromptCacheKeyRejectedModels.has(key)) {
|
|
2198
2257
|
warnedPromptCacheKeyRejectedModels.add(key);
|
|
2199
2258
|
ctx.ui.notify(
|
|
2200
|
-
`⚠️ ${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.`,
|
|
2259
|
+
`⚠️ ${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 modelOverrides). No configuration was changed automatically.`,
|
|
2201
2260
|
"warning",
|
|
2202
2261
|
);
|
|
2203
2262
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-cache-optimizer",
|
|
3
|
-
"version": "2.10.
|
|
3
|
+
"version": "2.10.10",
|
|
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",
|
|
@@ -38,7 +38,7 @@
|
|
|
38
38
|
"check:modules": "node scripts/check-module-graph.mjs"
|
|
39
39
|
},
|
|
40
40
|
"devDependencies": {
|
|
41
|
-
"@earendil-works/pi-coding-agent": "^1.
|
|
41
|
+
"@earendil-works/pi-coding-agent": "^1.7.0",
|
|
42
42
|
"@earendil-works/pi-server": "^1.1.0",
|
|
43
43
|
"@types/node": "^22.0.0",
|
|
44
44
|
"jiti": "^2.7.0",
|
package/src/command.ts
CHANGED
|
@@ -18,7 +18,7 @@ import { isPiVersionAtLeast } from "./cache-warming.ts";
|
|
|
18
18
|
import { HOST_PI_VERSION } from "./host-pi.ts";
|
|
19
19
|
import { buildModelsJsonLintDoctorLines, buildModelsJsonTypoHintLines } from "./models-json-lint.ts";
|
|
20
20
|
import { applyPromptCacheKeyConfigFix, isActionablePromptCacheKeyConfigReceipt, readPromptCacheKeyConfigReceiptSnapshot, rollbackPromptCacheKeyConfig } from "./prompt-cache-key-config.ts";
|
|
21
|
-
import { getEffectiveCompatValueSource, getPromptCacheKeyMode, isPromptCacheKeyOmittedForModel } from "./request-payload.ts";
|
|
21
|
+
import { getEffectiveCompatValueSource, getPromptCacheKeyMode, isPromptCacheKeyDisabledInModelsJson, isPromptCacheKeyOmittedForModel } from "./request-payload.ts";
|
|
22
22
|
import { describeNativeVirtualRouteNote, resolveRouteModel } from "./routing.ts";
|
|
23
23
|
import { buildAllStatsOutput, buildContributorsStatsOutput, buildSessionStatsOutput } from "./stats-report.ts";
|
|
24
24
|
import { type FixSuggestion } from "./fix-types.ts";
|
|
@@ -427,6 +427,12 @@ export function createCacheOptimizerCommandHandler(runtime: CommandRuntime) {
|
|
|
427
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
428
|
return;
|
|
429
429
|
}
|
|
430
|
+
// models.json says "disabled" but Pi's runtime model does not: Pi drops
|
|
431
|
+
// provider/models[] compat for models an extension provider defines,
|
|
432
|
+
// so Pi itself may still send the key. Say so, then offer the omit rule.
|
|
433
|
+
if (isPromptCacheKeyDisabledInModelsJson(model) && isPiVersionAtLeast(HOST_PI_VERSION, PROMPT_CACHE_KEY_MODE_SINCE) === true) {
|
|
434
|
+
cmdCtx.ui.notify(`ℹ️ models.json sets compat.promptCacheKeyMode to "disabled" for "${modelKey(model)}", but Pi's model does not carry it (Pi applies only modelOverrides compat to models an extension provider defines), so Pi may still send prompt_cache_key. Move the setting to modelOverrides["${model.id}"].compat, or continue with this extension's omit rule.`, "info");
|
|
435
|
+
}
|
|
430
436
|
if (!cmdCtx.hasUI) {
|
|
431
437
|
cmdCtx.ui.notify(
|
|
432
438
|
"❌ Non-interactive terminal detected. Prompt cache key opt-out requires UI confirmation. No changes were made.\n" +
|
package/src/models-json-lint.ts
CHANGED
|
@@ -13,14 +13,16 @@ 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.
|
|
17
|
-
* 1.5.1 added compat promptCacheKeyMode, requiresNonNullAssistantContent, requiresToolsWithToolHistory and supportsMessageThreads;
|
|
16
|
+
* Known key sets are copied from Pi 1.7.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;
|
|
18
|
+
* 1.6.0 changed no keys; 1.6.1 added a Google compat schema whose only key, supportsStrictMode, was already known;
|
|
19
|
+
* 1.7.0 added compat supportsReasoningReplay):
|
|
18
20
|
* - @earendil-works/pi-coding-agent dist/core/model-config.js
|
|
19
21
|
* (ModelsConfigSchema, ProviderConfigSchema, ModelDefinitionSchema, ModelOverrideSchema)
|
|
20
22
|
* - @earendil-works/pi-ai dist/providers/compat-schema.js
|
|
21
23
|
* (ProviderCompatSchema = merged properties of every per-API compat schema)
|
|
22
24
|
*/
|
|
23
|
-
export const MODELS_JSON_SCHEMA_SOURCE_VERSION = "1.
|
|
25
|
+
export const MODELS_JSON_SCHEMA_SOURCE_VERSION = "1.7.0";
|
|
24
26
|
|
|
25
27
|
export const MODELS_JSON_ROOT_KEYS: readonly string[] = ["$schema", "providers"];
|
|
26
28
|
|
|
@@ -38,7 +40,7 @@ export const MODELS_JSON_MODEL_OVERRIDE_KEYS: readonly string[] = [
|
|
|
38
40
|
"contextWindow", "maxTokens", "samplingParams", "samplingParamsByThinkingLevel", "headers", "compat",
|
|
39
41
|
];
|
|
40
42
|
|
|
41
|
-
/** Object.keys(ProviderCompatSchema.properties) in Pi 1.
|
|
43
|
+
/** Object.keys(ProviderCompatSchema.properties) in Pi 1.7.0, sorted. */
|
|
42
44
|
export const MODELS_JSON_COMPAT_KEYS: readonly string[] = [
|
|
43
45
|
"allowEmptySignature", "allowedFallbackModels", "cacheControlFormat", "chatTemplateArgs", "chatTemplateKwargs",
|
|
44
46
|
"forceAdaptiveThinking", "imageInput", "maxTokensField", "openRouterRouting", "promptCacheKeyMode",
|
|
@@ -49,7 +51,7 @@ export const MODELS_JSON_COMPAT_KEYS: readonly string[] = [
|
|
|
49
51
|
"supportsEagerToolInputStreaming", "supportsExplicitPromptCacheMode", "supportsFinishReason",
|
|
50
52
|
"supportsLongCacheRetention", "supportsMaxOutputTokens", "supportsMessageThreads", "supportsMidConvoEffort",
|
|
51
53
|
"supportsMidConvoSystemMessages", "supportsMidConvoToolAdditions", "supportsMidConvoToolChanges",
|
|
52
|
-
"supportsOpenAIGrammarTools", "supportsReasoningEffort", "supportsStore", "supportsStrictMode",
|
|
54
|
+
"supportsOpenAIGrammarTools", "supportsReasoningEffort", "supportsReasoningReplay", "supportsStore", "supportsStrictMode",
|
|
53
55
|
"supportsStrictTools", "supportsTemperature", "supportsThinkingTokenBudget", "supportsToolSearch",
|
|
54
56
|
"supportsUsageInStreaming", "thinkingFormat", "thinkingTokenBudgetField", "vercelGatewayRouting", "vllmPriority",
|
|
55
57
|
"zaiToolStream",
|
package/src/request-payload.ts
CHANGED
|
@@ -98,10 +98,35 @@ export function addEffectiveSessionAffinityHeaders(
|
|
|
98
98
|
return changed;
|
|
99
99
|
}
|
|
100
100
|
|
|
101
|
-
|
|
101
|
+
function normalizePromptCacheKeyMode(mode: unknown): "auto" | "enabled" | "disabled" | undefined {
|
|
102
|
+
// Pi's transport reads `compat.promptCacheKeyMode ?? "auto"` and sends no key
|
|
103
|
+
// for any value other than "auto" or "enabled"; models.json is
|
|
104
|
+
// schema-validated, so only an extension provider can supply another value.
|
|
105
|
+
if (mode === undefined || mode === null) return undefined;
|
|
106
|
+
return mode === "auto" || mode === "enabled" ? mode : "disabled";
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Pi 1.5.1+ `compat.promptCacheKeyMode` as Pi's transport sees it: the runtime
|
|
111
|
+
* model's compat, into which Pi already merged models.json (provider compat and
|
|
112
|
+
* models[] for models.json models, modelOverrides for every model).
|
|
113
|
+
*/
|
|
102
114
|
export function getPromptCacheKeyMode(model: PiModel | undefined): "auto" | "enabled" | "disabled" | undefined {
|
|
103
|
-
|
|
104
|
-
|
|
115
|
+
return normalizePromptCacheKeyMode(asRecord(asRecord(model as unknown)?.compat)?.promptCacheKeyMode);
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* "disabled" set in models.json (modelOverrides > models[] > provider compat)
|
|
120
|
+
* for this provider/model. Pi drops provider and models[] compat for models an
|
|
121
|
+
* extension provider defines, so this can hold while getPromptCacheKeyMode does not.
|
|
122
|
+
*/
|
|
123
|
+
export function isPromptCacheKeyDisabledInModelsJson(model: PiModel | undefined): boolean {
|
|
124
|
+
if (!model) return false;
|
|
125
|
+
const layers = getEffectiveCompatSources(model, readEffectiveCompatConfig())
|
|
126
|
+
.filter(({ source }) => source !== "runtime")
|
|
127
|
+
.reverse();
|
|
128
|
+
const configured = layers.find(({ compat }) => Object.prototype.hasOwnProperty.call(compat, "promptCacheKeyMode"));
|
|
129
|
+
return configured !== undefined && normalizePromptCacheKeyMode(configured.compat.promptCacheKeyMode) === "disabled";
|
|
105
130
|
}
|
|
106
131
|
|
|
107
132
|
export function shouldInjectOpenAIPromptCacheKeyForModel(model: PiModel | undefined): boolean {
|
|
@@ -109,9 +134,10 @@ export function shouldInjectOpenAIPromptCacheKeyForModel(model: PiModel | undefi
|
|
|
109
134
|
// extension's fallback limited to openai-completions proxies, where Pi's
|
|
110
135
|
// provider extensions may not supply the session key.
|
|
111
136
|
if (!isOpenAICompatibleProxyApi(model?.api)) return false;
|
|
112
|
-
// Pi 1.5.1+:
|
|
113
|
-
//
|
|
114
|
-
|
|
137
|
+
// Pi 1.5.1+: "disabled" is the user's explicit choice for an endpoint that
|
|
138
|
+
// rejects the key; never put it back. models.json may only add that
|
|
139
|
+
// restriction, never lift a runtime "disabled".
|
|
140
|
+
return getPromptCacheKeyMode(model) !== "disabled" && !isPromptCacheKeyDisabledInModelsJson(model);
|
|
115
141
|
}
|
|
116
142
|
|
|
117
143
|
export function isPromptCacheKeyOmittedForModel(model: PiModel | undefined, config: PersistedCacheOptimizerConfig | PersistedCacheOptimizerConfigV3 = persistedCacheOptimizerConfig): boolean {
|
package/src/request-state.ts
CHANGED
|
@@ -96,7 +96,56 @@ export type ProviderRequestState = {
|
|
|
96
96
|
/** Whether that selection routed to a physical model for this request. */
|
|
97
97
|
virtualSelection: boolean;
|
|
98
98
|
responseReceived: boolean;
|
|
99
|
+
/** Date.now() of the latest retryable error response, while the record waits for a retry. */
|
|
100
|
+
retryableErrorAt?: number;
|
|
99
101
|
correlationAmbiguous: boolean;
|
|
100
102
|
// A native virtual request whose dispatched id matched several providers.
|
|
101
103
|
identityAmbiguous?: boolean;
|
|
102
104
|
};
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Whether Pi may retry a provider response with this status: mirrors pi-ai's
|
|
108
|
+
* retryProviderRequest policy (x-should-retry wins, else 408, 409, 429, 5xx).
|
|
109
|
+
* Pi 1.6.1+ reports each such attempt through after_provider_response. Pi
|
|
110
|
+
* retries only when `retry.provider.maxRetries` is above zero (unset by
|
|
111
|
+
* default), so such a response is often final: see RETRY_PENDING_WINDOW_MS.
|
|
112
|
+
*/
|
|
113
|
+
export function isRetryableProviderStatus(status: unknown, headers: unknown): boolean {
|
|
114
|
+
if (typeof status !== "number") return false;
|
|
115
|
+
const record = headers && typeof headers === "object" ? headers as Record<string, unknown> : undefined;
|
|
116
|
+
let shouldRetry: unknown;
|
|
117
|
+
if (record) {
|
|
118
|
+
for (const [name, value] of Object.entries(record)) {
|
|
119
|
+
if (name.toLowerCase() === "x-should-retry") shouldRetry = value;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
if (shouldRetry === "true") return true;
|
|
123
|
+
if (shouldRetry === "false") return false;
|
|
124
|
+
return status === 408 || status === 409 || status === 429 || status >= 500;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* How long a request record that got a retryable error keeps waiting for the
|
|
129
|
+
* retry's response: pi-ai caps a server-requested delay at 60s by default and
|
|
130
|
+
* its backoff at 8s. After that the error was final (Pi did not retry, as by
|
|
131
|
+
* default, or a cache-warming request that has no message_end), and the
|
|
132
|
+
* record no longer takes part in response correlation.
|
|
133
|
+
*/
|
|
134
|
+
export const RETRY_PENDING_WINDOW_MS = 75_000;
|
|
135
|
+
|
|
136
|
+
export function isAwaitingProviderResponse(
|
|
137
|
+
state: { responseReceived: boolean; retryableErrorAt?: number },
|
|
138
|
+
now: number,
|
|
139
|
+
): boolean {
|
|
140
|
+
if (state.responseReceived) return false;
|
|
141
|
+
return state.retryableErrorAt === undefined || now - state.retryableErrorAt <= RETRY_PENDING_WINDOW_MS;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** Whether a response's Content-Type names a JSON body (an API error rather than an HTML block page). */
|
|
145
|
+
export function isJsonContentType(headers: unknown): boolean {
|
|
146
|
+
if (!headers || typeof headers !== "object") return false;
|
|
147
|
+
for (const [name, value] of Object.entries(headers as Record<string, unknown>)) {
|
|
148
|
+
if (name.toLowerCase() === "content-type" && typeof value === "string" && /\bjson\b/i.test(value)) return true;
|
|
149
|
+
}
|
|
150
|
+
return false;
|
|
151
|
+
}
|
package/src/routing.ts
CHANGED
|
@@ -502,12 +502,18 @@ export function installCacheHintsService(
|
|
|
502
502
|
options: { discardPrevious?: (value: unknown) => boolean } = {},
|
|
503
503
|
): () => void {
|
|
504
504
|
const globals = getProtocolGlobal();
|
|
505
|
-
|
|
505
|
+
// Never hold a previous service that would be discarded anyway: it is
|
|
506
|
+
// another optimizer instance, and holding it would pin that instance (and,
|
|
507
|
+
// transitively, every one before it) for this instance's lifetime.
|
|
508
|
+
let previous: unknown = globals[PI_CACHE_HINTS_SYMBOL];
|
|
509
|
+
if (previous !== undefined && options.discardPrevious?.(previous)) previous = undefined;
|
|
506
510
|
globals[PI_CACHE_HINTS_SYMBOL] = service;
|
|
507
511
|
return () => {
|
|
512
|
+
const restore = previous;
|
|
513
|
+
previous = undefined;
|
|
508
514
|
if (globals[PI_CACHE_HINTS_SYMBOL] !== service) return;
|
|
509
|
-
if (
|
|
510
|
-
globals[PI_CACHE_HINTS_SYMBOL] =
|
|
515
|
+
if (restore !== undefined) {
|
|
516
|
+
globals[PI_CACHE_HINTS_SYMBOL] = restore;
|
|
511
517
|
} else {
|
|
512
518
|
delete globals[PI_CACHE_HINTS_SYMBOL];
|
|
513
519
|
}
|