pi-cache-optimizer 2.10.4 → 2.10.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/README.zh-CN.md +2 -2
- package/index.ts +4 -1
- package/package.json +2 -2
- package/src/models-json-lint.ts +6 -6
- package/src/prompt-rewrite.ts +84 -26
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.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
|
|
|
@@ -226,7 +226,7 @@ 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`.
|
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.0 验证。TypeScript 校验直接使用官方 Pi package 类型,同时只使用这些版本共有的 extension hooks、`getAgentDir()` 和 prompt options;不依赖 Pi 0.83+ 专有 API(例如 `ctx.scopedModels` 或 bundled TypeBox 1.3 aliases)。原生虚拟模型支持与 codemode 嵌套工具调用合并只在会产生它们的 Pi 0.99+ 上生效,较早版本保持原有行为。本地开发基线需要 Node.js 22.19.0 或更高版本,与 Pi 1.0.3 的 engine 要求一致。
|
|
68
68
|
|
|
69
69
|
## 命令
|
|
70
70
|
|
|
@@ -226,7 +226,7 @@ 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`。
|
package/index.ts
CHANGED
|
@@ -23,7 +23,7 @@ import { decideZeroPriceWarming, readCacheWarmingMode } from "./src/cache-warmin
|
|
|
23
23
|
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
24
|
import { isRuntimeOptimizerEnabled, isZeroPriceWarmingEnabled, setRuntimeOptimizerEnabled } from "./src/config.ts";
|
|
25
25
|
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";
|
|
26
|
+
import { SKILL_COMPRESSION_MIN_COUNT, SKILL_PATH_RULE_WORDINGS, compressSkillsInSystemPrompt, compressSkillsViaSection, formatSkillsForPrompt, formatSkillsForPromptCompressed, stripSessionOverviewChurn, explainSkillCompressionSkip, recordSkillCompressionOutcome, getLastSkillCompressionOutcome, describeSkillCompressionOutcome } from "./src/prompt-rewrite.ts";
|
|
27
27
|
import { addEffectiveSessionAffinityHeaders, addOpenAIPromptCacheKey, clampPromptCacheKey, collectAnthropicCacheControlsInWireOrder, downgradeAnthropicLongCacheControls, getEffectiveCompatValueSource, hasAnthropicCacheTtlOrderError, hasEffectivePromptCacheKey, isPromptCacheKeyOmittedForModel, normalizeAnthropicCacheControlTtlOrder, omitOpenAIPromptCacheKeys, shouldInjectOpenAIPromptCacheKeyForModel, withAnthropicCacheTtlRepair, withoutPromptCacheRetention, derivePromptCacheKey } from "./src/request-payload.ts";
|
|
28
28
|
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
29
|
import { CONFIG_RECEIPT_PATH, applyPromptCacheKeyConfigFix, configReceiptBackupPath, parsePromptCacheKeyConfigReceipt, rollbackPromptCacheKeyConfig, writePromptCacheKeyConfigReceipt } from "./src/prompt-cache-key-config.ts";
|
|
@@ -152,6 +152,9 @@ export const __internals_for_tests = {
|
|
|
152
152
|
formatSkillsForPromptCompressed,
|
|
153
153
|
compressSkillsInSystemPrompt,
|
|
154
154
|
SKILL_COMPRESSION_MIN_COUNT,
|
|
155
|
+
SKILL_PATH_RULE_WORDINGS,
|
|
156
|
+
compressSkillsViaSection,
|
|
157
|
+
explainSkillCompressionSkip,
|
|
155
158
|
NO_PROMPT_REWRITE_ENV,
|
|
156
159
|
isEnabledEnv,
|
|
157
160
|
featureEnabled,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-cache-optimizer",
|
|
3
|
-
"version": "2.10.
|
|
3
|
+
"version": "2.10.5",
|
|
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",
|
|
@@ -37,7 +37,7 @@
|
|
|
37
37
|
"check:modules": "node scripts/check-module-graph.mjs"
|
|
38
38
|
},
|
|
39
39
|
"devDependencies": {
|
|
40
|
-
"@earendil-works/pi-coding-agent": "^1.
|
|
40
|
+
"@earendil-works/pi-coding-agent": "^1.5.0",
|
|
41
41
|
"@earendil-works/pi-server": "^1.1.0",
|
|
42
42
|
"@types/node": "^22.0.0",
|
|
43
43
|
"jiti": "^2.7.0",
|
package/src/models-json-lint.ts
CHANGED
|
@@ -13,13 +13,13 @@ 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.0 (1.4.0 added compat imageInput and sendImageOptInHeader; 1.5.0 changed no keys):
|
|
17
17
|
* - @earendil-works/pi-coding-agent dist/core/model-config.js
|
|
18
18
|
* (ModelsConfigSchema, ProviderConfigSchema, ModelDefinitionSchema, ModelOverrideSchema)
|
|
19
19
|
* - @earendil-works/pi-ai dist/providers/compat-schema.js
|
|
20
20
|
* (ProviderCompatSchema = merged properties of every per-API compat schema)
|
|
21
21
|
*/
|
|
22
|
-
export const MODELS_JSON_SCHEMA_SOURCE_VERSION = "1.
|
|
22
|
+
export const MODELS_JSON_SCHEMA_SOURCE_VERSION = "1.5.0";
|
|
23
23
|
|
|
24
24
|
export const MODELS_JSON_ROOT_KEYS: readonly string[] = ["$schema", "providers"];
|
|
25
25
|
|
|
@@ -37,12 +37,12 @@ export const MODELS_JSON_MODEL_OVERRIDE_KEYS: readonly string[] = [
|
|
|
37
37
|
"contextWindow", "maxTokens", "samplingParams", "samplingParamsByThinkingLevel", "headers", "compat",
|
|
38
38
|
];
|
|
39
39
|
|
|
40
|
-
/** Object.keys(ProviderCompatSchema.properties) in Pi 1.
|
|
40
|
+
/** Object.keys(ProviderCompatSchema.properties) in Pi 1.5.0, sorted. */
|
|
41
41
|
export const MODELS_JSON_COMPAT_KEYS: readonly string[] = [
|
|
42
42
|
"allowEmptySignature", "allowedFallbackModels", "cacheControlFormat", "chatTemplateArgs", "chatTemplateKwargs",
|
|
43
|
-
"forceAdaptiveThinking", "maxTokensField", "openRouterRouting", "requiresAssistantAfterToolResult",
|
|
43
|
+
"forceAdaptiveThinking", "imageInput", "maxTokensField", "openRouterRouting", "requiresAssistantAfterToolResult",
|
|
44
44
|
"requiresReasoningContentOnAssistantMessages", "requiresThinkingAsText", "requiresToolResultName",
|
|
45
|
-
"sendSessionAffinityHeaders", "sessionAffinityFormat", "supportsAdditionalTools", "supportsCacheControlOnTools",
|
|
45
|
+
"sendImageOptInHeader", "sendSessionAffinityHeaders", "sessionAffinityFormat", "supportsAdditionalTools", "supportsCacheControlOnTools",
|
|
46
46
|
"supportsDeveloperRole", "supportsEagerToolInputStreaming", "supportsExplicitPromptCacheMode", "supportsFinishReason",
|
|
47
47
|
"supportsLongCacheRetention", "supportsMaxOutputTokens", "supportsMidConvoEffort", "supportsMidConvoSystemMessages",
|
|
48
48
|
"supportsMidConvoToolAdditions", "supportsMidConvoToolChanges", "supportsOpenAIGrammarTools", "supportsReasoningEffort",
|
|
@@ -277,7 +277,7 @@ export function selectModelsJsonKeyTyposForTarget(
|
|
|
277
277
|
}
|
|
278
278
|
|
|
279
279
|
export function formatModelsJsonKeyTypo(typo: ModelsJsonKeyTypo): string {
|
|
280
|
-
return `⚠️ ${typo.path} is not a known Pi
|
|
280
|
+
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
281
|
}
|
|
282
282
|
|
|
283
283
|
/** 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";
|