pi-cache-optimizer 2.10.1 → 2.10.3

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/index.ts CHANGED
@@ -1,10 +1,10 @@
1
1
  import { randomUUID } from "node:crypto";
2
- import { appendFile, mkdir } from "node:fs/promises";
2
+ import { appendFile, lstat, mkdir } from "node:fs/promises";
3
3
  import { basename, join } from "node:path";
4
4
  import {
5
5
  type ExtensionAPI, type ExtensionContext
6
6
  } from "@earendil-works/pi-coding-agent";
7
- import { LOG_PREFIX, type PiModel, asRecord, isNonEmptyString } from "./src/common.ts";
7
+ import { LOG_PREFIX, type PiModel, asRecord, getErrorCode, isNonEmptyString } from "./src/common.ts";
8
8
  import { FIX_RECEIPT_FILE_NAME, FIX_RECEIPT_PATH, MODELS_JSON_PATH, STATE_DIR } from "./src/paths.ts";
9
9
  import { type FixSuggestion } from "./src/fix-types.ts";
10
10
  import { deepEqualIgnoringKeys, findExistingCompatKeysInJsonc, locateModelOverrideInJsonc, locateProviderCompatInJsonc, parseJsonc, stripJsoncComments, stripJsoncTrailingCommas } from "./src/jsonc.ts";
@@ -1379,12 +1379,45 @@ export default function (pi: ExtensionAPI) {
1379
1379
  finally { rolloverPromise = undefined; }
1380
1380
  }
1381
1381
 
1382
+ /**
1383
+ * Retired shards whose closing write failed: counted from memory only, so
1384
+ * they would be lost when the process exits. The shutdown flush writes
1385
+ * each one once more (see retryUnpersistedRetiredShards).
1386
+ */
1387
+ const unpersistedRetiredShards = new Map<string, { shard: PersistedStatsShardV7; path: string; landed: boolean }>();
1388
+
1389
+ /**
1390
+ * One more closing write for each retired shard whose write failed, at
1391
+ * shutdown. Skipped once its retired copy is gone: compaction absorbed the
1392
+ * id (the archive counts it), or a file at least as new already landed.
1393
+ * Also skipped when an earlier write of the id had landed but its file is
1394
+ * gone now: compaction folded it into the archive and deleted it (a later
1395
+ * pass then forgets the id, so a refresh that missed the archive in
1396
+ * between still holds the retired copy). Writing it back would count it
1397
+ * twice. A second failure only warns: there is nothing left to retry with.
1398
+ */
1399
+ async function retryUnpersistedRetiredShards(): Promise<void> {
1400
+ for (const [id, { shard, path, landed }] of Array.from(unpersistedRetiredShards)) {
1401
+ unpersistedRetiredShards.delete(id);
1402
+ if (retiredShards.get(id) !== shard) continue;
1403
+ await enqueuePersist(async () => {
1404
+ try {
1405
+ if (landed && await lstat(path).then(() => false, (error) => getErrorCode(error) === "ENOENT")) return;
1406
+ await writeStatsShardV7(path, shard);
1407
+ } catch (error) {
1408
+ console.warn(`${LOG_PREFIX}: failed again to persist a retired stats shard at shutdown; its usage is lost`, error);
1409
+ }
1410
+ });
1411
+ }
1412
+ }
1413
+
1382
1414
  /**
1383
1415
  * Retire the current shard: snapshot it closed, keep that snapshot as its
1384
1416
  * retired copy, continue under a new id on `day`, and queue the snapshot's
1385
- * write (a failure only warns: the retired copy keeps counting it). The
1386
- * written and the retired copy are one object, so once its write lands
1387
- * the file (same updatedAt) replaces the retired copy. Synchronous up to
1417
+ * write (a failure warns and the retired copy keeps counting it; the
1418
+ * shutdown flush writes it once more). The written and the retired copy
1419
+ * are one object, so once its write lands the file (same updatedAt)
1420
+ * replaces the retired copy. Synchronous up to
1388
1421
  * the queued write, so usage recorded after this goes to the new id.
1389
1422
  */
1390
1423
  function retireCurrentShard(day: string, ctx?: ExtensionContext): Promise<void> {
@@ -1394,6 +1427,7 @@ export default function (pi: ExtensionAPI) {
1394
1427
  }
1395
1428
  const closed = buildCurrentStatsShard("closed");
1396
1429
  const closedPath = instanceShardPath;
1430
+ const landed = persistedOwnShards.length > 0;
1397
1431
  retiredShards.set(instanceId, closed);
1398
1432
  instanceId = randomUUID();
1399
1433
  instanceShardPath = join(SHARD_FILES_DIR, `${instanceId}.json`);
@@ -1404,6 +1438,7 @@ export default function (pi: ExtensionAPI) {
1404
1438
  try {
1405
1439
  await writeStatsShardV7(closedPath, closed);
1406
1440
  } catch (error) {
1441
+ unpersistedRetiredShards.set(closed.instanceId, { shard: closed, path: closedPath, landed });
1407
1442
  console.warn(`${LOG_PREFIX}: failed to persist a retired stats shard`, error);
1408
1443
  if (!persistenceWarningShown) {
1409
1444
  persistenceWarningShown = true;
@@ -1699,7 +1734,12 @@ export default function (pi: ExtensionAPI) {
1699
1734
  closeStatsRefreshGate();
1700
1735
  await waitForStatsRestore();
1701
1736
  await drainStatsRefresh();
1702
- await flushPersistCacheStats(ctx, "closed");
1737
+ try {
1738
+ await flushPersistCacheStats(ctx, "closed");
1739
+ } finally {
1740
+ // Also when the flush failed (e.g. its rollover's refresh threw).
1741
+ await retryUnpersistedRetiredShards();
1742
+ }
1703
1743
  } finally {
1704
1744
  closeStatsRefreshGate();
1705
1745
  latestCacheHint = undefined;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-cache-optimizer",
3
- "version": "2.10.1",
3
+ "version": "2.10.3",
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",
@@ -182,6 +182,12 @@ export function compressSkillsInSystemPrompt(
182
182
  * position and `<skills>` wrapper. Returns true only when Pi's re-rendered prompt
183
183
  * really contains the compressed list; otherwise the section is restored and the
184
184
  * caller falls back to the string substitution.
185
+ *
186
+ * A custom base prompt (`customPrompt`) can hold its own copy of the verbose
187
+ * list: pi-subagents passes the parent's rendered prompt there, and an idle
188
+ * parent renders its unedited base options. That copy is compressed in place
189
+ * too; otherwise the re-render still contains the verbose list, the section edit
190
+ * is rolled back, and the string fallback forces the prompt.
185
191
  */
186
192
  export function compressSkillsViaSection(event: {
187
193
  readonly systemPrompt: string;
@@ -199,11 +205,23 @@ export function compressSkillsViaSection(event: {
199
205
  const compressed = formatSkillsForPromptCompressed(options.skills, skillFileReadTool(options) ?? "read").trim();
200
206
  if (!compressed || compressed.length >= verbose.length) return false;
201
207
 
208
+ const previousCustom = options.customPrompt;
209
+ const customHasVerbose = typeof previousCustom === "string" && previousCustom.includes(verbose);
210
+ if (customHasVerbose) options.customPrompt = previousCustom.split(verbose).join(compressed);
211
+ // Only the custom prompt held the list (Pi renders no skills section of its own, e.g. no
212
+ // read/bash tool): done, and no `<skills>` section is added where Pi renders none.
213
+ if (customHasVerbose && !event.systemPrompt.includes(verbose)) {
214
+ if (event.systemPrompt.includes(compressed)) return true;
215
+ options.customPrompt = previousCustom;
216
+ return false;
217
+ }
218
+
202
219
  const previous = sections.skills;
203
220
  sections.skills = compressed;
204
221
  if (event.systemPrompt.includes(compressed) && !event.systemPrompt.includes(verbose)) return true;
205
222
  if (previous === undefined) delete sections.skills;
206
223
  else sections.skills = previous;
224
+ options.customPrompt = previousCustom;
207
225
  return false;
208
226
  }
209
227