pi-cache-optimizer 2.10.9 → 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 +13 -0
- package/README.md +1 -1
- package/index.ts +33 -12
- 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/CHANGELOG.md
CHANGED
|
@@ -5,6 +5,19 @@ 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
|
+
|
|
8
21
|
## [2.10.9] - 2026-11-26
|
|
9
22
|
|
|
10
23
|
### 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";
|
|
@@ -183,6 +183,12 @@ export const __internals_for_tests = {
|
|
|
183
183
|
isNonEmptyString,
|
|
184
184
|
shouldInjectOpenAIPromptCacheKey,
|
|
185
185
|
shouldInjectOpenAIPromptCacheKeyForModel,
|
|
186
|
+
isRetryableProviderStatus,
|
|
187
|
+
isAwaitingProviderResponse,
|
|
188
|
+
RETRY_PENDING_WINDOW_MS,
|
|
189
|
+
isJsonContentType,
|
|
190
|
+
getPromptCacheKeyMode,
|
|
191
|
+
isPromptCacheKeyDisabledInModelsJson,
|
|
186
192
|
isOpenAICompatibleApi,
|
|
187
193
|
isAnthropicMessagesApi,
|
|
188
194
|
isOpenAICompatibleProxyApi,
|
|
@@ -1718,14 +1724,19 @@ export default function (pi: ExtensionAPI) {
|
|
|
1718
1724
|
hasExplicitLongRetentionOptIn(model),
|
|
1719
1725
|
promptCacheRetention400Models.has(key),
|
|
1720
1726
|
anthropicTtlOrderErrorModels.has(key),
|
|
1721
|
-
|
|
1722
|
-
//
|
|
1723
|
-
//
|
|
1724
|
-
// otherwise-equal candidates (PR #32).
|
|
1725
|
-
|
|
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),
|
|
1726
1732
|
]);
|
|
1727
1733
|
}
|
|
1728
1734
|
|
|
1735
|
+
function promptCacheKeyAction(model: PiModel): "omit" | "inject" | "none" {
|
|
1736
|
+
if (isPromptCacheKeyOmittedForModel(model)) return "omit";
|
|
1737
|
+
return shouldInjectOpenAIPromptCacheKey() && shouldInjectOpenAIPromptCacheKeyForModel(model) ? "inject" : "none";
|
|
1738
|
+
}
|
|
1739
|
+
|
|
1729
1740
|
pi.on("session_start", async (event, ctx) => {
|
|
1730
1741
|
if (runtimeOptimizerEnabled) requestLongCacheRetention();
|
|
1731
1742
|
// Do not block Pi's startup on historical stats (issue #28). The
|
|
@@ -2058,7 +2069,8 @@ export default function (pi: ExtensionAPI) {
|
|
|
2058
2069
|
});
|
|
2059
2070
|
|
|
2060
2071
|
pi.on("after_provider_response", async (event, ctx) => {
|
|
2061
|
-
const
|
|
2072
|
+
const now = Date.now();
|
|
2073
|
+
const pendingStates = providerRequestStates.filter((state) => isAwaitingProviderResponse(state, now));
|
|
2062
2074
|
let responseState: ProviderRequestState | undefined;
|
|
2063
2075
|
if (pendingStates.length === 1) {
|
|
2064
2076
|
responseState = pendingStates[0];
|
|
@@ -2075,7 +2087,14 @@ export default function (pi: ExtensionAPI) {
|
|
|
2075
2087
|
for (const state of pendingStates) state.correlationAmbiguous = true;
|
|
2076
2088
|
}
|
|
2077
2089
|
}
|
|
2078
|
-
|
|
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
|
+
}
|
|
2079
2098
|
// A native virtual request whose physical provider could not be pinned
|
|
2080
2099
|
// records no model-scoped header evidence; finalized assistant messages
|
|
2081
2100
|
// still carry exact provider/model identity.
|
|
@@ -2107,7 +2126,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
2107
2126
|
if (!warnedPromptCacheKeyRejectedModels.has(key)) {
|
|
2108
2127
|
warnedPromptCacheKeyRejectedModels.add(key);
|
|
2109
2128
|
ctx.ui.notify(
|
|
2110
|
-
`⚠️ ${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.`,
|
|
2111
2130
|
"warning",
|
|
2112
2131
|
);
|
|
2113
2132
|
}
|
|
@@ -2133,7 +2152,9 @@ export default function (pi: ExtensionAPI) {
|
|
|
2133
2152
|
}
|
|
2134
2153
|
|
|
2135
2154
|
// ── 403: proxy/CDN/WAF blocking ──
|
|
2136
|
-
|
|
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)) {
|
|
2137
2158
|
const key403 = modelKey(model);
|
|
2138
2159
|
|
|
2139
2160
|
// Case 1: Pi's custom session-affinity headers are enabled. Offer the
|
|
@@ -2235,7 +2256,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
2235
2256
|
if (!warnedPromptCacheKeyRejectedModels.has(key)) {
|
|
2236
2257
|
warnedPromptCacheKeyRejectedModels.add(key);
|
|
2237
2258
|
ctx.ui.notify(
|
|
2238
|
-
`⚠️ ${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.`,
|
|
2239
2260
|
"warning",
|
|
2240
2261
|
);
|
|
2241
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
|
+
}
|