@cortexkit/pi-magic-context 0.49.57 → 0.49.60

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.
Files changed (55) hide show
  1. package/dist/auto-search-worker.js +5 -5
  2. package/dist/chunk-embedding-write-worker.js +12 -12
  3. package/dist/{compaction-marker-candidates-9yhrstyb.js → compaction-marker-candidates-nxaamfej.js} +2 -2
  4. package/dist/compaction-marker-candidates-worker.js +1 -1
  5. package/dist/{compartment-chunk-embedding-wg7emg3z.js → compartment-chunk-embedding-avkyp2df.js} +7 -7
  6. package/dist/{embedding-backfill-qde2zywg.js → embedding-backfill-3g3cm51d.js} +12 -12
  7. package/dist/embedding-worker-process.js +1 -1
  8. package/dist/embedding-worker.js +4 -4
  9. package/dist/historian-calibration-extension.js +1 -1
  10. package/dist/{index-j0eagxkz.js → index-1ts77n1b.js} +1 -1
  11. package/dist/{index-xssjy4z9.js → index-3s39a1md.js} +1 -1
  12. package/dist/{index-tz8431zx.js → index-418za765.js} +26 -21
  13. package/dist/{index-xx1911hb.js → index-453s1hj6.js} +1 -1
  14. package/dist/{index-8ej7crnf.js → index-5hhhxck7.js} +10 -10
  15. package/dist/{index-qm139qq2.js → index-5rcjs14a.js} +2 -2
  16. package/dist/{index-yjgkjkjs.js → index-71rg8j43.js} +1 -1
  17. package/dist/{index-zxm7ckvc.js → index-79xfn84y.js} +2 -2
  18. package/dist/{index-xgkq843e.js → index-8gvbskcm.js} +4 -4
  19. package/dist/{index-15eq9z3a.js → index-9cqfbdgb.js} +3 -3
  20. package/dist/{index-ndg15t3x.js → index-cxczethe.js} +4 -4
  21. package/dist/{index-erkb5dee.js → index-e9wkbh8y.js} +8 -8
  22. package/dist/{index-prhdb9c5.js → index-f4n7tnsf.js} +2 -2
  23. package/dist/{index-mmwgmz8f.js → index-fz4gexgk.js} +2 -2
  24. package/dist/{index-d40ecdbn.js → index-gavj3e6h.js} +4 -4
  25. package/dist/{index-6d0bby9d.js → index-ghp32f9m.js} +2 -2
  26. package/dist/{index-v858d5d1.js → index-jhmz9tgv.js} +1 -1
  27. package/dist/{index-awpx91y5.js → index-k7a8x7ba.js} +1 -1
  28. package/dist/{index-15rx61th.js → index-m6kszx0e.js} +4 -4
  29. package/dist/{index-7y60kyea.js → index-pefn1gt5.js} +1 -1
  30. package/dist/{index-jnh7a6a3.js → index-qdy49kwk.js} +4 -4
  31. package/dist/{index-yxeg8zaa.js → index-tm11k42a.js} +9 -4
  32. package/dist/{index-hec3bwev.js → index-txcs0vnj.js} +2 -2
  33. package/dist/{index-0133ybm6.js → index-w4sqw9mf.js} +8 -8
  34. package/dist/{index-7mvsg371.js → index-xan5mt5f.js} +5 -5
  35. package/dist/{index-szn2tac8.js → index-xjhq27z9.js} +1 -1
  36. package/dist/{index-mbzqrp0s.js → index-zgsemyph.js} +10 -10
  37. package/dist/index.js +617 -284
  38. package/dist/{logger-hhgpkbx1.js → logger-93cnqyh0.js} +1 -1
  39. package/dist/{message-fts-rowid-map-tec2x7qe.js → message-fts-rowid-map-dtbragnt.js} +4 -4
  40. package/dist/{message-index-bounded-q6dyk780.js → message-index-bounded-behq385r.js} +9 -9
  41. package/dist/{message-time-backfill-krre2qnb.js → message-time-backfill-8zwv9byv.js} +2 -2
  42. package/dist/migration-worker.js +9 -9
  43. package/dist/{project-embedding-registry-qx2zjbgs.js → project-embedding-registry-63wsm3a8.js} +11 -11
  44. package/dist/raw-ordinal-warmup-worker.js +8 -8
  45. package/dist/{read-session-chunk-ksn2r664.js → read-session-chunk-ksh32zfv.js} +7 -7
  46. package/dist/{read-session-raw-75dcxtdy.js → read-session-raw-0tytrjye.js} +2 -2
  47. package/dist/{render-nejsk0az.js → render-2qed2svq.js} +16 -16
  48. package/dist/{safe-notification-target-8s1xg0q9.js → safe-notification-target-fkyrd95h.js} +2 -2
  49. package/dist/{search-archive-4yfsc0xb.js → search-archive-qqj7j1w1.js} +9 -9
  50. package/dist/{search-h61ec8kh.js → search-vmw1xbqx.js} +19 -19
  51. package/dist/{storage-tags-jfewemtk.js → storage-tags-s0m7e39a.js} +5 -5
  52. package/dist/subagent-entry.js +25 -25
  53. package/dist/tag-snapshot-worker-pi.js +11 -11
  54. package/dist/{v2-archive-reader-hveb3ajf.js → v2-archive-reader-cc7sx6dk.js} +1 -1
  55. package/package.json +2 -2
package/dist/index.js CHANGED
@@ -4,8 +4,8 @@ import {
4
4
  harnessOwnsOpenCodeStore2
5
5
  } from "./index-0h2mkab2.js";
6
6
  import {
7
+ getMagicContextHistorianSessionDir,
7
8
  ensureCortexKitArtifactGitignore,
8
- getProjectMagicContextHistorianDir,
9
9
  getMagicContextStorageDir,
10
10
  isMagicContextStorageOutsideEngram,
11
11
  claimStorageBackupWarningCheck,
@@ -15,7 +15,7 @@ import {
15
15
  log2,
16
16
  sessionLog2,
17
17
  flushLogger2
18
- } from "./index-yxeg8zaa.js";
18
+ } from "./index-tm11k42a.js";
19
19
  import {
20
20
  sanitizeDiagnosticText,
21
21
  hasShareabilitySensitiveText
@@ -154,7 +154,7 @@ import {
154
154
  registerTodoStateLifecycle,
155
155
  syncCtxMemoryToolEnabled,
156
156
  registerMagicContextTools
157
- } from "./index-tz8431zx.js";
157
+ } from "./index-418za765.js";
158
158
  import"./index-4knyh1kt.js";
159
159
  import {
160
160
  canonicalModelIdentity,
@@ -193,7 +193,7 @@ import {
193
193
  resolveProjectIdentityForSession,
194
194
  beginBootQuietPeriod,
195
195
  scheduleAfterBootQuiet
196
- } from "./index-xx1911hb.js";
196
+ } from "./index-453s1hj6.js";
197
197
  import {
198
198
  detectThinkingBindingMismatch,
199
199
  detectLatestTurnThinkingMismatch,
@@ -403,7 +403,7 @@ import {
403
403
  setSessionWorkMetrics,
404
404
  getSessionWorkMetrics,
405
405
  resolveEpochFloorForPass
406
- } from "./index-xgkq843e.js";
406
+ } from "./index-8gvbskcm.js";
407
407
  import {
408
408
  textMentionsRecentCommit,
409
409
  hasMeaningfulUserText2,
@@ -415,7 +415,7 @@ import {
415
415
  estimateTokens,
416
416
  estimateFixedPromptTokens,
417
417
  normalizeText
418
- } from "./index-7y60kyea.js";
418
+ } from "./index-pefn1gt5.js";
419
419
  import {
420
420
  stableStringify,
421
421
  BoundedSessionMap,
@@ -423,7 +423,7 @@ import {
423
423
  observeTemporalDecisions,
424
424
  freezeTemporalDecisions,
425
425
  tagIdentityRevisionKey
426
- } from "./index-v858d5d1.js";
426
+ } from "./index-jhmz9tgv.js";
427
427
  import {
428
428
  inRootAsyncContext2,
429
429
  Database2,
@@ -454,7 +454,7 @@ import {
454
454
  openCurrentDatabase,
455
455
  openDatabaseAsync,
456
456
  closeDatabase
457
- } from "./index-0133ybm6.js";
457
+ } from "./index-w4sqw9mf.js";
458
458
  import {
459
459
  LkgRecoveryFenceError,
460
460
  clearLkgFenceProcessState,
@@ -581,7 +581,7 @@ import {
581
581
  getSourceContents,
582
582
  recordSubagentInvocation,
583
583
  getLatestHistorianInvocationId
584
- } from "./index-mbzqrp0s.js";
584
+ } from "./index-zgsemyph.js";
585
585
  import {
586
586
  resolveOpenCodeDbPath,
587
587
  assertOpenCodeStoreGeneration,
@@ -599,7 +599,7 @@ import {
599
599
  } from "./index-x2n261wp.js";
600
600
  import {
601
601
  RAW_SUMMARY_TEXT_MAX_CHARS2
602
- } from "./index-szn2tac8.js";
602
+ } from "./index-xjhq27z9.js";
603
603
  import {
604
604
  askAnswerLines,
605
605
  removeUnsupportedCommitHashes,
@@ -647,12 +647,12 @@ import {
647
647
  getRawSessionTagKeysThrough2,
648
648
  getLegacyProtectedTailStartOrdinal2,
649
649
  readSessionChunk2
650
- } from "./index-7mvsg371.js";
650
+ } from "./index-xan5mt5f.js";
651
651
  import"./index-nvh6d3bz.js";
652
652
  import {
653
653
  formatSynapseLaneDescriptor
654
- } from "./index-qm139qq2.js";
655
- import"./index-6d0bby9d.js";
654
+ } from "./index-5rcjs14a.js";
655
+ import"./index-ghp32f9m.js";
656
656
  import {
657
657
  buildCanonicalChunkTextFromFts2,
658
658
  buildCompartmentSummaryFallbackText2,
@@ -662,7 +662,7 @@ import {
662
662
  replaceCompartmentChunkEmbeddings2,
663
663
  deleteChunkEmbedBackoffForSession2,
664
664
  chunkWindowSourceKey2
665
- } from "./index-ndg15t3x.js";
665
+ } from "./index-cxczethe.js";
666
666
  import {
667
667
  recordSessionProjectIdentity,
668
668
  GIT_SWEEP_LEASE_RENEWAL_MS,
@@ -671,7 +671,7 @@ import {
671
671
  markGitSweepSuccessAndRelease,
672
672
  parkGitSweepNonIndexable,
673
673
  releaseGitSweepLease
674
- } from "./index-zxm7ckvc.js";
674
+ } from "./index-79xfn84y.js";
675
675
  import {
676
676
  embedPauseBySession,
677
677
  embedRunStateBySession,
@@ -687,7 +687,7 @@ import {
687
687
  clearCompressionDepthRange,
688
688
  cleanSearchText,
689
689
  matchedSearchSnippet
690
- } from "./index-15rx61th.js";
690
+ } from "./index-m6kszx0e.js";
691
691
  import {
692
692
  rememberV1HiddenRun
693
693
  } from "./index-6x556c2q.js";
@@ -702,7 +702,7 @@ import {
702
702
  expandWorkspaceIdentitySetWithAliases,
703
703
  sourceNameForMemory,
704
704
  computeWorkspaceEpochFingerprint
705
- } from "./index-d40ecdbn.js";
705
+ } from "./index-gavj3e6h.js";
706
706
  import {
707
707
  configureContextDatabasePragmas2
708
708
  } from "./index-fapenpch.js";
@@ -727,7 +727,7 @@ import {
727
727
  createPrimer,
728
728
  updatePrimerSupport,
729
729
  updatePrimerAnswer
730
- } from "./index-awpx91y5.js";
730
+ } from "./index-k7a8x7ba.js";
731
731
  import {
732
732
  setEmbeddingSessionBusy2,
733
733
  isEmbeddingHostBusy2
@@ -761,7 +761,7 @@ import {
761
761
  } from "./index-q1yc6bs0.js";
762
762
  import {
763
763
  getCachedLocalEmbeddingPooling
764
- } from "./index-hec3bwev.js";
764
+ } from "./index-txcs0vnj.js";
765
765
  import {
766
766
  describeShadowBackfillWriteRefusal2,
767
767
  contentSha2562,
@@ -779,10 +779,10 @@ import {
779
779
  embedSessionCompartmentChunks2,
780
780
  getEmbeddingCoverageStatus2,
781
781
  getAutoEmbeddingSessionCoverage2
782
- } from "./index-erkb5dee.js";
782
+ } from "./index-e9wkbh8y.js";
783
783
  import {
784
784
  cosineSimilarity
785
- } from "./index-jnh7a6a3.js";
785
+ } from "./index-qdy49kwk.js";
786
786
  import {
787
787
  USER_FACING_FAILURES,
788
788
  renderUserFacingFailure,
@@ -816,8 +816,8 @@ import {
816
816
  scheduleClearAndReindex,
817
817
  clearSessionTracking,
818
818
  createAutoSearchDiagnostics
819
- } from "./index-8ej7crnf.js";
820
- import"./index-xssjy4z9.js";
819
+ } from "./index-5hhhxck7.js";
820
+ import"./index-3s39a1md.js";
821
821
  import {
822
822
  DREAMER_PRIMER_INVESTIGATOR_ALLOWED_TOOLS,
823
823
  buildHiddenAgentRegistrations,
@@ -845,11 +845,11 @@ import {
845
845
  drainPiTagSnapshotSession,
846
846
  assertPiTagSnapshotReady,
847
847
  ensurePiTagSnapshotReady
848
- } from "./index-mmwgmz8f.js";
849
- import"./index-yjgkjkjs.js";
848
+ } from "./index-fz4gexgk.js";
849
+ import"./index-71rg8j43.js";
850
850
  import"./index-8d2z6503.js";
851
- import"./index-15eq9z3a.js";
852
- import"./index-prhdb9c5.js";
851
+ import"./index-9cqfbdgb.js";
852
+ import"./index-f4n7tnsf.js";
853
853
  import {
854
854
  __toESM
855
855
  } from "./index-22jkk6wg.js";
@@ -869,7 +869,7 @@ import {
869
869
  import {
870
870
  logSlowWriteTransaction,
871
871
  WriteTransactionSteps
872
- } from "./index-j0eagxkz.js";
872
+ } from "./index-1ts77n1b.js";
873
873
  import {
874
874
  setStoragePrivatePermissionEnforcement,
875
875
  ensureStorageDirectorySync,
@@ -3601,7 +3601,7 @@ function startHostStallProfilerSwitch() {
3601
3601
  // package.json
3602
3602
  var package_default = {
3603
3603
  name: "@cortexkit/pi-magic-context",
3604
- version: "0.49.57",
3604
+ version: "0.49.60",
3605
3605
  type: "module",
3606
3606
  description: "Pi and OMP coding agent extension for Magic Context — cross-session memory and context management",
3607
3607
  main: "dist/index.js",
@@ -3630,7 +3630,7 @@ var package_default = {
3630
3630
  ],
3631
3631
  "//": "The build intentionally bundles typebox (no --external typebox) and keeps it a regular dependency. OMP's extension loader rewrites every bare `typebox` import to its own omptype-based shim, whose schemas are callable objects rather than JSON Schema; they fail structuredClone during tool registration, so an external typebox import stops Magic Context loading on OMP. src/typebox-bundling.test.ts guards this.",
3632
3632
  scripts: {
3633
- build: "bun ../../scripts/check-bun.mjs && tsc -p ../retina-local-fs/tsconfig.build.json && bun ../../scripts/clean-dist-chunks.mjs dist index.js subagent-entry.js historian-calibration-extension.js embedding-worker-process.js raw-ordinal-warmup-worker.js tag-snapshot-worker-pi.js transformers-web.js transformers-node-wasm.js && bun build ../plugin/src/features/magic-context/memory/transformers-web-entry.ts --outfile dist/transformers-web.js --target browser --format esm --external onnxruntime-web && bun ../plugin/scripts/build-transformers-node-wasm.ts dist && bun build src/index.ts src/tag-snapshot-worker-pi.ts src/subagent-entry.ts src/historian-calibration-extension.ts ../plugin/src/features/magic-context/memory/embedding-worker.ts ../plugin/src/features/magic-context/memory/embedding-worker-process.ts ../plugin/src/features/magic-context/migration-worker.ts ../plugin/src/hooks/magic-context/auto-search-worker.ts ../plugin/src/hooks/magic-context/raw-ordinal-warmup-worker.ts ../plugin/src/features/magic-context/compaction-marker-candidates-worker.ts ../plugin/src/features/magic-context/chunk-embedding-write-worker.ts --outdir dist --entry-naming '[name].[ext]' --target node --format esm --splitting --external @earendil-works/pi-coding-agent --external @oh-my-pi/pi-coding-agent --external @earendil-works/pi-tui --external onnxruntime-node --external onnxruntime-web --external sharp --external bun:ffi --external node:sqlite",
3633
+ build: "bun ../../scripts/check-bun.mjs && tsc -p ../retina-local-fs/tsconfig.build.json && bun ../../scripts/clean-dist-chunks.mjs dist index.js subagent-entry.js historian-calibration-extension.js embedding-worker-process.js raw-ordinal-warmup-worker.js tag-snapshot-worker-pi.js transformers-web.js transformers-node-wasm.js && bun build ../plugin/src/features/magic-context/memory/transformers-web-entry.ts --outfile dist/transformers-web.js --target browser --format esm --external onnxruntime-web && bun ../plugin/scripts/build-transformers-node-wasm.ts dist && bun build src/index.ts src/tag-snapshot-worker-pi.ts src/subagent-entry.ts src/historian-calibration-extension.ts ../plugin/src/features/magic-context/memory/embedding-worker.ts ../plugin/src/features/magic-context/memory/embedding-worker-process.ts ../plugin/src/features/magic-context/migration-worker.ts ../plugin/src/hooks/magic-context/auto-search-worker.ts ../plugin/src/hooks/magic-context/raw-ordinal-warmup-worker.ts ../plugin/src/features/magic-context/compaction-marker-candidates-worker.ts ../plugin/src/features/magic-context/chunk-embedding-write-worker.ts --outdir dist --entry-naming '[name].[ext]' --target node --format esm --splitting --external @earendil-works/pi-coding-agent --external @oh-my-pi/pi-coding-agent --external @earendil-works/pi-tui --external @earendil-works/pi-ai --external onnxruntime-node --external onnxruntime-web --external sharp --external bun:ffi --external node:sqlite",
3634
3634
  "build:e2e-argv": `bun ../../scripts/clean-dist-chunks.mjs ../../tests/docker/.generated subagent-runner-e2e.mjs && bun build src/subagent-runner.ts --outdir ../../tests/docker/.generated --entry-naming 'subagent-runner-e2e.mjs' --splitting --target node --format esm --external node:sqlite && node --input-type=module -e 'const { __test } = await import("../../tests/docker/.generated/subagent-runner-e2e.mjs"); if (typeof __test.buildArgs !== "function" || typeof __test.resolvePiInvocation !== "function") throw new Error("argv renderer exports missing"); console.log("Node argv renderer: 2 exports loaded")'`,
3635
3635
  typecheck: "tsc -p ../retina-local-fs/tsconfig.build.json && tsc --noEmit",
3636
3636
  test: "bun ../../scripts/check-bun.mjs && bun install --frozen-lockfile && MC_SLOW_TESTS=0 BUN_JSC_useOMGJIT=0 bun test --parallel=4 --timeout 30000",
@@ -9759,9 +9759,6 @@ function fitHistorianPrompt(args) {
9759
9759
  }
9760
9760
 
9761
9761
  // ../plugin/src/hooks/magic-context/compartment-runner-historian.ts
9762
- function historianResponseDumpDir(directory) {
9763
- return getProjectMagicContextHistorianDir(directory);
9764
- }
9765
9762
  var MAX_HISTORIAN_RETRIES = 2;
9766
9763
  var unknownProducerWindows = new Set;
9767
9764
  var HISTORIAN_REASONING_PART_TYPES = new Set(["reasoning", "thinking", "redacted_thinking"]);
@@ -10235,7 +10232,7 @@ async function runHistorianPrompt(args) {
10235
10232
  invocationId: invocationId ?? undefined
10236
10233
  };
10237
10234
  }
10238
- const dumpPath = dumpHistorianResponse(parentSessionId, sessionDirectory, dumpLabel ?? "historian-response", result);
10235
+ const dumpPath = dumpHistorianResponse(parentSessionId, dumpLabel ?? "historian-response", result);
10239
10236
  return { ok: true, result, dumpPath, invocationId: invocationId ?? undefined };
10240
10237
  } catch (modelError) {
10241
10238
  hiddenModelCooldowns.record(handle?.attemptedModel ?? toModelEntry(modelOverride)?.model, modelError);
@@ -10389,14 +10386,12 @@ function cleanupHistorianDump(sessionId, dumpPath) {
10389
10386
  });
10390
10387
  }
10391
10388
  }
10392
- function dumpHistorianResponse(sessionId, directory, label, text) {
10389
+ function dumpHistorianResponse(sessionId, label, text) {
10393
10390
  try {
10394
- const dumpDir = historianResponseDumpDir(directory);
10391
+ const dumpDir = getMagicContextHistorianSessionDir(sessionId);
10395
10392
  mkdirSync(dumpDir, { recursive: true });
10396
- ensureCortexKitArtifactGitignore(directory);
10397
- const safeSessionId = sanitizeDumpName(sessionId);
10398
10393
  const safeLabel = sanitizeDumpName(label);
10399
- const dumpPath = join7(dumpDir, `${safeSessionId}-${safeLabel}-${Date.now()}.xml`);
10394
+ const dumpPath = join7(dumpDir, `${safeLabel}-${Date.now()}.xml`);
10400
10395
  writeFileSync(dumpPath, text, "utf8");
10401
10396
  sessionLog2(sessionId, "compartment agent: historian response dumped", {
10402
10397
  label,
@@ -32028,6 +32023,230 @@ function recordPiTransformTiming(sample) {
32028
32023
  timingObserver?.(sample);
32029
32024
  }
32030
32025
 
32026
+ // src/pi-request-tools.ts
32027
+ var schemaDigests = {
32028
+ omp: new WeakMap,
32029
+ anthropic: new WeakMap,
32030
+ "anthropic-strict": new WeakMap,
32031
+ raw: new WeakMap
32032
+ };
32033
+ function anthropicWireSchema(parameters, strict) {
32034
+ const schema = typeof parameters === "object" && parameters !== null ? parameters : {};
32035
+ const legacy = {
32036
+ type: "object",
32037
+ properties: schema.properties ?? {},
32038
+ required: schema.required ?? []
32039
+ };
32040
+ return strict ? { ...schema, ...legacy } : legacy;
32041
+ }
32042
+ function schemaDigest(tool, mode, wireSchema) {
32043
+ const key = tool.parameters;
32044
+ const cacheable = typeof key === "object" && key !== null || typeof key === "function";
32045
+ const cache = schemaDigests[mode];
32046
+ if (cacheable) {
32047
+ const cached = cache.get(key);
32048
+ if (cached !== undefined)
32049
+ return cached;
32050
+ }
32051
+ const digest = requestToolSchemaDigest(mode === "omp" && wireSchema ? wireSchema(tool) : mode === "anthropic" || mode === "anthropic-strict" ? anthropicWireSchema(tool.parameters, mode === "anthropic-strict") : tool.parameters);
32052
+ if (cacheable)
32053
+ cache.set(key, digest);
32054
+ return digest;
32055
+ }
32056
+ var CLAUDE_CODE_TOOL_NAMES = new Map([
32057
+ "Read",
32058
+ "Write",
32059
+ "Edit",
32060
+ "Bash",
32061
+ "Grep",
32062
+ "Glob",
32063
+ "AskUserQuestion",
32064
+ "EnterPlanMode",
32065
+ "ExitPlanMode",
32066
+ "KillShell",
32067
+ "NotebookEdit",
32068
+ "Skill",
32069
+ "Task",
32070
+ "TaskOutput",
32071
+ "TodoWrite",
32072
+ "WebFetch",
32073
+ "WebSearch"
32074
+ ].map((name) => [name.toLowerCase(), name]));
32075
+ var identityName = (name) => name;
32076
+ var claudeCodeName = (name) => CLAUDE_CODE_TOOL_NAMES.get(name.toLowerCase()) ?? name;
32077
+ function compatFlag(model, flag) {
32078
+ const value = model?.compat?.[flag];
32079
+ return typeof value === "boolean" ? value : undefined;
32080
+ }
32081
+ function supportsToolReferences(model) {
32082
+ const declared = compatFlag(model, "supportsToolReferences");
32083
+ if (declared !== undefined)
32084
+ return declared;
32085
+ if (model.provider !== "anthropic" || typeof model.id !== "string")
32086
+ return false;
32087
+ if (model.id.includes("haiku"))
32088
+ return false;
32089
+ const version = model.id.match(/^claude-(?:opus|sonnet|fable)-(\d+)(?:-(\d+))?(?:-|$)/);
32090
+ if (!version)
32091
+ return false;
32092
+ const major = Number(version[1]);
32093
+ const minor = version[2] && version[2].length < 8 ? Number(version[2]) : 0;
32094
+ return major > 4 || major === 4 && minor >= 5;
32095
+ }
32096
+ function deferredAndReferencedNames(messages, normalizeName) {
32097
+ const deferred = new Set;
32098
+ const referenced = new Set;
32099
+ for (const message of messages) {
32100
+ const { role, content, addedToolNames } = message ?? {};
32101
+ if (role === "assistant" && Array.isArray(content)) {
32102
+ for (const block of content) {
32103
+ const { type, name } = block ?? {};
32104
+ if (type === "toolCall" && typeof name === "string")
32105
+ referenced.add(normalizeName(name));
32106
+ }
32107
+ } else if (role === "toolResult" && Array.isArray(addedToolNames)) {
32108
+ for (const name of addedToolNames) {
32109
+ if (typeof name !== "string")
32110
+ continue;
32111
+ const normalized = normalizeName(name);
32112
+ if (!referenced.has(normalized))
32113
+ deferred.add(normalized);
32114
+ }
32115
+ }
32116
+ }
32117
+ for (const name of deferred)
32118
+ referenced.add(name);
32119
+ return { deferred, referenced };
32120
+ }
32121
+ function calledToolNames(messages) {
32122
+ const names = new Set;
32123
+ for (const message of messages) {
32124
+ const content = message?.content;
32125
+ if (!Array.isArray(content))
32126
+ continue;
32127
+ for (const part of content) {
32128
+ const { type, name } = part ?? {};
32129
+ if (typeof type === "string" && type.toLowerCase().includes("tool") && typeof name === "string")
32130
+ names.add(name);
32131
+ }
32132
+ }
32133
+ return names;
32134
+ }
32135
+ function readPiRequestSendsTool(pi, name) {
32136
+ try {
32137
+ if (typeof pi.getAllTools !== "function" || typeof pi.getActiveTools !== "function")
32138
+ return;
32139
+ const active = pi.getActiveTools();
32140
+ if (!Array.isArray(active))
32141
+ return;
32142
+ if (!active.includes(name))
32143
+ return false;
32144
+ const all = pi.getAllTools();
32145
+ if (!Array.isArray(all))
32146
+ return;
32147
+ return all.some((tool) => typeof tool === "object" && tool !== null && tool.name === name);
32148
+ } catch {
32149
+ return;
32150
+ }
32151
+ }
32152
+ function readPiRequestToolsFingerprint(pi, wireSchema, messages, route = {}) {
32153
+ try {
32154
+ if (typeof pi.getAllTools !== "function" || typeof pi.getActiveTools !== "function")
32155
+ return;
32156
+ const all = pi.getAllTools();
32157
+ const active = pi.getActiveTools();
32158
+ if (!Array.isArray(all) || !Array.isArray(active))
32159
+ return;
32160
+ const registered = new Map;
32161
+ for (const tool of all) {
32162
+ if (!tool || typeof tool !== "object")
32163
+ return;
32164
+ const { name } = tool;
32165
+ if (typeof name !== "string")
32166
+ return;
32167
+ registered.set(name, tool);
32168
+ }
32169
+ const model = route.model;
32170
+ const anthropicWriter = route.host === "pi" && wireSchema === undefined && model?.api === "anthropic-messages";
32171
+ const mode = wireSchema ? "omp" : anthropicWriter ? compatFlag(model, "supportsStrictTools") === true ? "anthropic-strict" : "anthropic" : "raw";
32172
+ const normalizeName = anthropicWriter && route.oauth === true ? claudeCodeName : identityName;
32173
+ const sent = new Map;
32174
+ for (const name of active) {
32175
+ if (typeof name !== "string")
32176
+ return;
32177
+ const tool = registered.get(name);
32178
+ if (!tool)
32179
+ continue;
32180
+ sent.set(normalizeName(name), tool);
32181
+ }
32182
+ const split = anthropicWriter && model && supportsToolReferences(model) ? deferredAndReferencedNames(messages, normalizeName) : undefined;
32183
+ const anyImmediate = [...sent.keys()].some((name) => !split?.deferred.has(name));
32184
+ const tools = [];
32185
+ for (const [name, tool] of sent) {
32186
+ const description = typeof tool.description === "string" ? tool.description : "";
32187
+ tools.push({
32188
+ name,
32189
+ description,
32190
+ schemaDigest: schemaDigest({
32191
+ name: tool.name,
32192
+ description,
32193
+ parameters: tool.parameters
32194
+ }, mode, wireSchema),
32195
+ deferLoading: split ? anyImmediate && split.deferred.has(name) : tool.defer_loading === true || tool.deferLoading === true
32196
+ });
32197
+ }
32198
+ return requestToolsFingerprint(tools, () => split?.referenced ?? calledToolNames(messages));
32199
+ } catch {
32200
+ return;
32201
+ }
32202
+ }
32203
+
32204
+ // src/ctx-reduce-callable-pi.ts
32205
+ var CTX_REDUCE = "ctx_reduce";
32206
+ function piCtxReduceCallable(pi, compactionOff, session) {
32207
+ if (compactionOff)
32208
+ return false;
32209
+ const sent = readPiRequestSendsTool(pi, CTX_REDUCE);
32210
+ if (sent !== undefined)
32211
+ return sent;
32212
+ return session ? readServedPiCtxReduceCallable(session.db, session.sessionId) : true;
32213
+ }
32214
+ var NAMESPACE4 = "piCtxReduceCallable";
32215
+ var servedBySession = new BoundedSessionMap(1000);
32216
+ function readServedPiCtxReduceCallable(db, sessionId) {
32217
+ const cached = servedBySession.get(sessionId);
32218
+ if (cached !== undefined)
32219
+ return cached;
32220
+ let served = true;
32221
+ try {
32222
+ const stored = readReplayEnvelope(db, sessionId, "read")[NAMESPACE4];
32223
+ if (typeof stored === "boolean")
32224
+ served = stored;
32225
+ } catch (error) {
32226
+ sessionLog2(sessionId, "ctx_reduce served record unreadable:", error);
32227
+ }
32228
+ servedBySession.set(sessionId, served);
32229
+ return served;
32230
+ }
32231
+ function recordServedPiCtxReduceCallable(db, sessionId, callable) {
32232
+ if (readServedPiCtxReduceCallable(db, sessionId) === callable)
32233
+ return;
32234
+ servedBySession.set(sessionId, callable);
32235
+ const written = updateReplayDocument(db, sessionId, (doc) => {
32236
+ const stored = doc[NAMESPACE4];
32237
+ if ((typeof stored === "boolean" ? stored : true) === callable)
32238
+ return false;
32239
+ doc.version = 2;
32240
+ doc[NAMESPACE4] = callable;
32241
+ return true;
32242
+ });
32243
+ if (!written)
32244
+ sessionLog2(sessionId, "ctx_reduce served record not written");
32245
+ }
32246
+ function clearPiCtxReduceCallableSession(sessionId) {
32247
+ servedBySession.delete(sessionId);
32248
+ }
32249
+
32031
32250
  // src/ctx-reduce-nudge-pi.ts
32032
32251
  import { randomUUID as randomUUID3 } from "node:crypto";
32033
32252
 
@@ -33282,7 +33501,7 @@ function applyPiHeuristicCleanup(sessionId, db, targets, piMessages, config, pre
33282
33501
  const tMeasure = performance.now();
33283
33502
  const activeTags = tags.filter((t) => t.status === "active").map((tag) => {
33284
33503
  const target = targets.get(tag.tagNumber);
33285
- const imageTokens = emergency.serializedImageTokens?.get(tag.messageId) ?? 0;
33504
+ const imageTokens = emergency.toolImageTokens?.get(tag.messageId) ?? 0;
33286
33505
  const observation = target?.measureReclaim;
33287
33506
  const measuredTarget = imageTokens && observation ? {
33288
33507
  ...target,
@@ -33299,7 +33518,7 @@ function applyPiHeuristicCleanup(sessionId, db, targets, piMessages, config, pre
33299
33518
  return emergency.sinceReading?.has(tag.tagNumber) ? { ...measured, sinceReading: true } : measured;
33300
33519
  });
33301
33520
  const byTag = new Map(activeTags.map((tag) => [tag.tagNumber, tag]));
33302
- const removedThisPassTokens = emergency.servedBeforePass ? piServedMassRemovedSince(emergency.servedBeforePass, new Set(activeTags.map((tag) => tag.tagNumber)), targets, calibration, emergency.serializedImageTokens) : 0;
33521
+ const removedThisPassTokens = emergency.servedBeforePass ? piServedMassRemovedSince(emergency.servedBeforePass, new Set(activeTags.map((tag) => tag.tagNumber)), targets, calibration, emergency.toolImageTokens) : 0;
33303
33522
  const droppableTags = candidateTags.flatMap((tag) => {
33304
33523
  const measured = byTag.get(tag.tagNumber);
33305
33524
  return measured ? [measured] : [];
@@ -34686,28 +34905,27 @@ function trimPiMessagesToBoundary(piMessages, entryIds, cutoffMessageId, trimMut
34686
34905
  break;
34687
34906
  }
34688
34907
  }
34689
- if (cutoffIndex < 0 && sessionId && hasRawMessageProvider2(sessionId)) {
34908
+ let promptReachesBoundary;
34909
+ if (cutoffIndex >= 0) {
34910
+ idCutBoundaryByMessages.set(piMessages, cutoffMessageId);
34911
+ } else if (sessionId && piMessages.length > 0 && hasRawMessageProvider2(sessionId)) {
34912
+ let placement;
34690
34913
  try {
34691
- const branch = readRawSessionMessages2(sessionId);
34692
- const positions = new Map(branch.map((message, index) => [message.id, index]));
34693
- const boundaryPosition = positions.get(cutoffMessageId);
34694
- if (boundaryPosition === undefined)
34695
- return 0;
34696
- let previous = -1;
34697
- for (const [index, message] of piMessages.entries()) {
34698
- if (isPiSystemEntry(message))
34699
- continue;
34700
- const id = resolveStableId(message, index, entryIds);
34701
- const position = positions.get(id) ?? positions.get(`${SYNTH_USER_ID_PREFIX}${id}`);
34702
- if (position === undefined || position <= previous)
34703
- return 0;
34704
- previous = position;
34705
- if (position <= boundaryPosition)
34706
- cutoffIndex = index;
34707
- }
34708
- } catch {
34914
+ placement = placeCutByBranchPosition(piMessages, entryIds, cutoffMessageId, sessionId);
34915
+ } catch (error) {
34916
+ placement = {
34917
+ placed: false,
34918
+ reason: `the branch could not be read (${error instanceof Error ? error.message : String(error)})`,
34919
+ firstUnplacedRole: "unknown"
34920
+ };
34921
+ }
34922
+ if (!placement.placed) {
34923
+ if (idCutBoundaryByMessages.get(piMessages) !== cutoffMessageId)
34924
+ logUnplacedCut(sessionId, cutoffMessageId, piMessages.length, placement.reason, placement.firstUnplacedRole);
34709
34925
  return 0;
34710
34926
  }
34927
+ cutoffIndex = placement.cutoffIndex;
34928
+ promptReachesBoundary = placement.promptReachesBoundary;
34711
34929
  }
34712
34930
  if (cutoffIndex < 0)
34713
34931
  return 0;
@@ -34766,6 +34984,9 @@ function trimPiMessagesToBoundary(piMessages, entryIds, cutoffMessageId, trimMut
34766
34984
  }
34767
34985
  }
34768
34986
  }
34987
+ const keptPrompt = keptPromptIndex(piMessages, cutoffIndex, remove, promptReachesBoundary);
34988
+ if (keptPrompt >= 0)
34989
+ remove.delete(keptPrompt);
34769
34990
  const retiredIds = new Set;
34770
34991
  if (retireDecisions) {
34771
34992
  for (const index of remove) {
@@ -34786,6 +35007,100 @@ function trimPiMessagesToBoundary(piMessages, entryIds, cutoffMessageId, trimMut
34786
35007
  retireDecisions?.(retiredIds);
34787
35008
  return removed;
34788
35009
  }
35010
+ function placeCutByBranchPosition(piMessages, entryIds, cutoffMessageId, sessionId) {
35011
+ const branch = readRawSessionMessages2(sessionId);
35012
+ const positions = new Map(branch.map((message, index) => [message.id, index]));
35013
+ const eventPositions = new Map;
35014
+ let firstUnplacedRole;
35015
+ let contentMessages = 0;
35016
+ for (const [index, message] of piMessages.entries()) {
35017
+ if (isPiSystemEntry(message))
35018
+ continue;
35019
+ contentMessages++;
35020
+ const id = resolveStableId(message, index, entryIds);
35021
+ const position = positions.get(id) ?? positions.get(`${SYNTH_USER_ID_PREFIX}${id}`);
35022
+ if (position === undefined)
35023
+ firstUnplacedRole ??= String(message.role);
35024
+ else
35025
+ eventPositions.set(index, position);
35026
+ }
35027
+ const unplacedRole = firstUnplacedRole ?? "none";
35028
+ const boundaryPosition = positions.get(cutoffMessageId);
35029
+ if (boundaryPosition === undefined)
35030
+ return {
35031
+ placed: false,
35032
+ reason: "it is not on the active branch either",
35033
+ firstUnplacedRole: unplacedRole
35034
+ };
35035
+ if (contentMessages > 0 && eventPositions.size === 0)
35036
+ return {
35037
+ placed: false,
35038
+ reason: "none of them has a branch position",
35039
+ firstUnplacedRole: unplacedRole
35040
+ };
35041
+ let cutoffIndex = -1;
35042
+ let previous = -1;
35043
+ for (const [index, position] of eventPositions) {
35044
+ if (position <= previous)
35045
+ return {
35046
+ placed: false,
35047
+ reason: "the context messages are not in branch order",
35048
+ firstUnplacedRole: unplacedRole
35049
+ };
35050
+ previous = position;
35051
+ if (position <= boundaryPosition)
35052
+ cutoffIndex = index;
35053
+ }
35054
+ return {
35055
+ placed: true,
35056
+ cutoffIndex,
35057
+ promptReachesBoundary: (eventIndex) => {
35058
+ const promptPosition = eventPositions.get(eventIndex);
35059
+ if (promptPosition === undefined)
35060
+ return true;
35061
+ for (let p = promptPosition + 1;p <= boundaryPosition; p++) {
35062
+ const message = branch[p];
35063
+ if (message?.role === "user" && !message.id.startsWith(SYNTH_USER_ID_PREFIX))
35064
+ return false;
35065
+ }
35066
+ return true;
35067
+ }
35068
+ };
35069
+ }
35070
+ function keptPromptIndex(piMessages, cutoffIndex, removed, promptReachesBoundary) {
35071
+ let promptIndex = -1;
35072
+ for (let i = cutoffIndex;i >= 0; i--) {
35073
+ if (piMessages[i]?.role === "user") {
35074
+ promptIndex = i;
35075
+ break;
35076
+ }
35077
+ }
35078
+ if (promptIndex < 0)
35079
+ return -1;
35080
+ for (let i = cutoffIndex + 1;i < piMessages.length; i++) {
35081
+ if (removed.has(i))
35082
+ continue;
35083
+ const message = piMessages[i];
35084
+ if (message?.role === "user")
35085
+ return -1;
35086
+ if (message?.role === "assistant" && message.stopReason !== "error")
35087
+ break;
35088
+ }
35089
+ if (promptReachesBoundary && !promptReachesBoundary(promptIndex))
35090
+ return -1;
35091
+ return promptIndex;
35092
+ }
35093
+ var idCutBoundaryByMessages = new WeakMap;
35094
+ var unplacedCutLoggedSessions = new Set;
35095
+ function resetPiUnplacedCutLog(sessionId) {
35096
+ unplacedCutLoggedSessions.delete(sessionId);
35097
+ }
35098
+ function logUnplacedCut(sessionId, boundaryMessageId, eventLength, reason, firstUnplacedRole) {
35099
+ if (unplacedCutLoggedSessions.has(sessionId))
35100
+ return;
35101
+ unplacedCutLoggedSessions.add(sessionId);
35102
+ sessionLog2(sessionId, `pi history cut not placed: boundary ${boundaryMessageId} is not among the ${eventLength} context messages and ${reason}; first message without a branch position: ${firstUnplacedRole}; nothing was cut at this boundary`);
35103
+ }
34789
35104
  function toolPairKey(callId, assistantIndex) {
34790
35105
  return `${callId}\x00${assistantIndex}`;
34791
35106
  }
@@ -41663,6 +41978,16 @@ ${OMITTED_IMAGE}` : OMITTED_IMAGE : joined);
41663
41978
  return items;
41664
41979
  }
41665
41980
 
41981
+ // src/pi-provider-input.ts
41982
+ function piProviderInput(message) {
41983
+ if (!message || typeof message !== "object" || Array.isArray(message))
41984
+ return message;
41985
+ const descriptors = Object.getOwnPropertyDescriptors(message);
41986
+ delete descriptors.completedAt;
41987
+ delete descriptors.contextSnapshot;
41988
+ return Object.create(Object.getPrototypeOf(message), descriptors);
41989
+ }
41990
+
41666
41991
  // src/pi-dispatch-chain.ts
41667
41992
  function object13(value) {
41668
41993
  return value && typeof value === "object" && !Array.isArray(value) ? value : undefined;
@@ -41694,7 +42019,7 @@ function piPreparedHistory(messages, model) {
41694
42019
  for (const [index, message] of messages.entries()) {
41695
42020
  const source = object13(message);
41696
42021
  const identity = head >= 0 && (index === head || index === head + 1) ? Object.fromEntries(Object.entries(source ?? {}).filter(([key]) => key !== "timestamp")) : message;
41697
- const fields = lkgContentFields(identity);
42022
+ const fields = lkgContentFields(piProviderInput(identity));
41698
42023
  if (!fields)
41699
42024
  return;
41700
42025
  snapshots.push({ id: "", fields });
@@ -42352,14 +42677,6 @@ function omitsRootBookkeeping(args) {
42352
42677
  }
42353
42678
  return typeof api === "string" && bookkeepingOmittingApis.has(api);
42354
42679
  }
42355
- function piProviderInput(message) {
42356
- if (!message || typeof message !== "object" || Array.isArray(message))
42357
- return message;
42358
- const descriptors = Object.getOwnPropertyDescriptors(message);
42359
- delete descriptors.completedAt;
42360
- delete descriptors.contextSnapshot;
42361
- return Object.create(Object.getPrototypeOf(message), descriptors);
42362
- }
42363
42680
  function restorePiLkgInputForFit(snapshot, branchEntries) {
42364
42681
  if (!snapshot || snapshot.preparationFailure || !branchEntries || !snapshot.inputs.length)
42365
42682
  return;
@@ -43124,6 +43441,20 @@ function piFitMessageBytes(raw) {
43124
43441
  const bytes = Buffer.byteLength(JSON.stringify(content ? { ...message, content } : raw));
43125
43442
  return bytes + (opaque ? 4 * opaqueThinkingCost(message.usage?.reasoning, message.usage?.output).tokens : 0);
43126
43443
  }
43444
+ function piFitMessageBytesPricingImages(raw, bytesPerImage = PI_IMAGE_TOKENS) {
43445
+ const message = raw;
43446
+ if (!Array.isArray(message?.content) || !message.content.some((part) => part && typeof part === "object" && part.type === "image"))
43447
+ return piFitMessageBytes(raw);
43448
+ let images = 0;
43449
+ const content = message.content.map((part) => {
43450
+ if (!part || typeof part !== "object" || part.type !== "image")
43451
+ return part;
43452
+ images += 1;
43453
+ const { data: _data, ...rest } = part;
43454
+ return rest;
43455
+ });
43456
+ return piFitMessageBytes({ ...message, content }) + images * bytesPerImage;
43457
+ }
43127
43458
  function tokenCacheFingerprintsEqual(left, right) {
43128
43459
  if (left.length !== right.length)
43129
43460
  return false;
@@ -43232,9 +43563,19 @@ function estimatePiOutgoingInputTokens(messages, observed, measuredPrefix, conte
43232
43563
  if (!knownRole(message))
43233
43564
  return false;
43234
43565
  const m = message;
43235
- return typeof m.content === "string" || Array.isArray(m.content) && m.content.every((p) => p && typeof p === "object" && ["text", "thinking", "redacted_thinking", "toolCall"].includes(String(p.type)));
43566
+ return typeof m.content === "string" || Array.isArray(m.content) && m.content.every((p) => p && typeof p === "object" && [
43567
+ "text",
43568
+ "thinking",
43569
+ "redacted_thinking",
43570
+ "toolCall",
43571
+ "image"
43572
+ ].includes(String(p.type)));
43236
43573
  };
43237
43574
  const complete = messages.every(countable);
43575
+ const hasImages = messages.some((message) => {
43576
+ const content = message?.content;
43577
+ return Array.isArray(content) && content.some((part) => part && typeof part === "object" && part.type === "image");
43578
+ });
43238
43579
  const measuredForBounds = measuredPrefix && measuredPrefix.modelKey === observed.modelKey && observed.envelopeSignature && measuredPrefix.envelopeSignature === observed.envelopeSignature && Number.isSafeInteger(measuredPrefix.inputTokens) && measuredPrefix.inputTokens > 0 ? measuredPrefix : undefined;
43239
43580
  if (contextLimit && Number.isFinite(contextLimit) && contextLimit > 0) {
43240
43581
  const priced = measuredForBounds?.appendedMessages ?? messages;
@@ -43275,7 +43616,7 @@ function estimatePiOutgoingInputTokens(messages, observed, measuredPrefix, conte
43275
43616
  tools: observed.toolDefinitionTokens
43276
43617
  }, observed.calibration ?? calibrationForModelKey(observed.modelKey), true);
43277
43618
  const fit = observed.calibration ?? calibrationForModelKey(observed.modelKey);
43278
- const upper = envelope + Math.max(UNKNOWN_FIT_RATIO, fit.toolsRatio, fit.proseRatio) * priced.reduce((sum, message) => sum + piFitMessageBytes(message), 0);
43619
+ const upper = envelope + Math.max(UNKNOWN_FIT_RATIO, fit.toolsRatio, fit.proseRatio) * priced.reduce((sum, message) => sum + piFitMessageBytesPricingImages(message), 0);
43279
43620
  if (upper <= contextLimit)
43280
43621
  return {
43281
43622
  tokens: upper,
@@ -43288,7 +43629,7 @@ function estimatePiOutgoingInputTokens(messages, observed, measuredPrefix, conte
43288
43629
  return {
43289
43630
  tokens: providerMass({
43290
43631
  system: observed.systemTokens,
43291
- tools: observed.toolDefinitionTokens + messages.reduce((sum, message) => sum + piFitMessageBytes(message), 0)
43632
+ tools: observed.toolDefinitionTokens + messages.reduce((sum, message) => sum + piFitMessageBytesPricingImages(message), 0)
43292
43633
  }, observed.calibration ?? calibrationForModelKey(observed.modelKey), true),
43293
43634
  trusted: true,
43294
43635
  refusalGrade: false
@@ -43309,7 +43650,7 @@ function estimatePiOutgoingInputTokens(messages, observed, measuredPrefix, conte
43309
43650
  return {
43310
43651
  tokens: providerMass({
43311
43652
  system: observed.systemTokens,
43312
- tools: observed.toolDefinitionTokens + messages.reduce((sum, message) => sum + piFitMessageBytes(message), 0)
43653
+ tools: observed.toolDefinitionTokens + messages.reduce((sum, message) => sum + piFitMessageBytesPricingImages(message), 0)
43313
43654
  }, observed.calibration ?? calibrationForModelKey(observed.modelKey), true),
43314
43655
  trusted: true,
43315
43656
  refusalGrade: false,
@@ -43323,7 +43664,7 @@ function estimatePiOutgoingInputTokens(messages, observed, measuredPrefix, conte
43323
43664
  tools: observed.toolDefinitionTokens + raw.toolCall,
43324
43665
  prose: raw.conversation
43325
43666
  }, calibration, true);
43326
- const refusalGrade = Number.isFinite(tokens) && messages.every((rawMessage) => {
43667
+ const refusalGrade = Number.isFinite(tokens) && !hasImages && messages.every((rawMessage) => {
43327
43668
  const content = rawMessage.content;
43328
43669
  if (typeof content === "string")
43329
43670
  return !tokenCountUsesByteBound(content);
@@ -43362,7 +43703,7 @@ function assertPiRawFallbackFits(messages, contextLimit, log, cause, observed, m
43362
43703
  let serializationFailed = false;
43363
43704
  try {
43364
43705
  for (const message of pricedMessages) {
43365
- bytes += piFitMessageBytes(message) + 1;
43706
+ bytes += piFitMessageBytesPricingImages(message, 4 * PI_IMAGE_TOKENS) + 1;
43366
43707
  if (baseInputTokens + Math.ceil(bytes / 4) > contextLimit)
43367
43708
  break;
43368
43709
  }
@@ -43378,7 +43719,13 @@ function assertPiRawFallbackFits(messages, contextLimit, log, cause, observed, m
43378
43719
  if (!message || typeof message !== "object")
43379
43720
  return false;
43380
43721
  const m = message;
43381
- return ["user", "assistant", "toolResult", "custom"].includes(m.role ?? "") && (typeof m.content === "string" || Array.isArray(m.content) && m.content.every((p) => p !== null && typeof p === "object" && ["text", "thinking", "redacted_thinking", "toolCall"].includes(String(p.type))));
43722
+ return ["user", "assistant", "toolResult", "custom"].includes(m.role ?? "") && (typeof m.content === "string" || Array.isArray(m.content) && m.content.every((p) => p !== null && typeof p === "object" && [
43723
+ "text",
43724
+ "thinking",
43725
+ "redacted_thinking",
43726
+ "toolCall",
43727
+ "image"
43728
+ ].includes(String(p.type))));
43382
43729
  });
43383
43730
  const raw = tokenizePiMessages([...pricedMessages]);
43384
43731
  if (!hasTokenizerForFit()) {
@@ -43390,9 +43737,17 @@ function assertPiRawFallbackFits(messages, contextLimit, log, cause, observed, m
43390
43737
  tools: (measured ? 0 : observed.toolDefinitionTokens) + raw.toolCall,
43391
43738
  prose: raw.conversation
43392
43739
  }, observed.calibration ?? calibrationForModelKey(observed.modelKey), true);
43393
- if (!complete || !Number.isFinite(tokens) || tokens <= 0 || tokens > contextLimit || serializationFailed || proxyTokens > contextLimit) {
43394
- log(`raw_fallback_over_context_limit proxy_bytes=${bytes} proxy_tokens=${proxyTokens} limit=${contextLimit} early_abort=true serialization_failed=${serializationFailed}`);
43395
- throw piFallbackRefusal(complete ? "fallback-over-context-limit" : "fallback-messages-incomplete", cause);
43740
+ if (!complete) {
43741
+ log("raw_fallback_refused completeness=partial messages=unpriceable");
43742
+ throw piFallbackRefusal("fallback-messages-incomplete", cause);
43743
+ }
43744
+ if (!Number.isFinite(tokens) || tokens <= 0) {
43745
+ log(`raw_fallback_refused count=unusable tokens=${tokens}`);
43746
+ throw piFallbackRefusal("fallback-over-context-limit", cause);
43747
+ }
43748
+ if (tokens > contextLimit) {
43749
+ log(`raw_fallback_over_context_limit tokens=${Math.ceil(tokens)} limit=${contextLimit} proxy_bytes=${bytes} proxy_tokens=${proxyTokens}`);
43750
+ throw piFallbackRefusal("fallback-over-context-limit", cause);
43396
43751
  }
43397
43752
  }
43398
43753
  function classifyPiOutgoingFit(estimate, limit) {
@@ -44994,6 +45349,12 @@ function piRecoveryFitCalibration(calibration) {
44994
45349
  return calibration.seeded ? calibration : { toolsRatio: UNKNOWN_FIT_RATIO, proseRatio: UNKNOWN_FIT_RATIO };
44995
45350
  }
44996
45351
  function piRecoveryToolImageTokens(messages) {
45352
+ return piToolResultImageTokens(messages, (part) => estimateTokens(JSON.stringify(part)));
45353
+ }
45354
+ function piToolImageCostTokens(messages) {
45355
+ return piToolResultImageTokens(messages, () => PI_IMAGE_TOKENS);
45356
+ }
45357
+ function piToolResultImageTokens(messages, priceImage) {
44997
45358
  const counts = new Map;
44998
45359
  const seen = new Set;
44999
45360
  for (const value of messages) {
@@ -45007,7 +45368,7 @@ function piRecoveryToolImageTokens(messages) {
45007
45368
  seen.add(message.toolCallId);
45008
45369
  for (const part of message.content) {
45009
45370
  if (part?.type === "image")
45010
- counts.set(message.toolCallId, (counts.get(message.toolCallId) ?? 0) + estimateTokens(JSON.stringify(part)));
45371
+ counts.set(message.toolCallId, (counts.get(message.toolCallId) ?? 0) + priceImage(part));
45011
45372
  }
45012
45373
  }
45013
45374
  return counts;
@@ -45108,6 +45469,8 @@ function extractAssistantUsage(message) {
45108
45469
  result.cacheWrite = u.cacheWrite;
45109
45470
  if (typeof u.totalTokens === "number")
45110
45471
  result.totalTokens = u.totalTokens;
45472
+ if (typeof u.contextTokens === "number")
45473
+ result.contextTokens = u.contextTokens;
45111
45474
  return result;
45112
45475
  }
45113
45476
  function computePiPressure(usage, contextLimit, absoluteWall) {
@@ -45126,9 +45489,12 @@ function piUsageInputTokens(usage) {
45126
45489
  const componentPromptTokens = input + cacheRead + cacheWrite;
45127
45490
  const totalPromptTokens = typeof usage.totalTokens === "number" && Number.isFinite(usage.totalTokens) && typeof usage.output === "number" && Number.isFinite(usage.output) ? Math.max(0, usage.totalTokens - usage.output) : undefined;
45128
45491
  const inputTokens = totalPromptTokens !== undefined && totalPromptTokens > 0 ? Math.min(componentPromptTokens, totalPromptTokens) : componentPromptTokens;
45129
- if (inputTokens <= 0 || !Number.isFinite(inputTokens))
45130
- return null;
45131
- return inputTokens;
45492
+ if (inputTokens > 0 && Number.isFinite(inputTokens))
45493
+ return inputTokens;
45494
+ return positiveContextTokens(usage.contextTokens);
45495
+ }
45496
+ function positiveContextTokens(value) {
45497
+ return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : null;
45132
45498
  }
45133
45499
  function resolvePiPressureSnapshot(args) {
45134
45500
  const persistedInputTokens = Number.isFinite(args.persistedInputTokens) && args.persistedInputTokens > 0 ? args.persistedInputTokens : 0;
@@ -45159,7 +45525,7 @@ function entryUsageTokens(usage) {
45159
45525
  return 0;
45160
45526
  const u = usage;
45161
45527
  const n = (value) => typeof value === "number" && Number.isFinite(value) ? value : 0;
45162
- return n(u.totalTokens) || n(u.input) + n(u.output) + n(u.cacheRead) + n(u.cacheWrite);
45528
+ return n(u.totalTokens) || n(u.input) + n(u.output) + n(u.cacheRead) + n(u.cacheWrite) || (positiveContextTokens(u.contextTokens) ?? 0);
45163
45529
  }
45164
45530
  function isPiLiveUsageRawBranchEstimate(branchEntries) {
45165
45531
  if (!branchEntries)
@@ -45381,167 +45747,6 @@ function resolvePiProvenInputFloor(args) {
45381
45747
  return observed;
45382
45748
  }
45383
45749
 
45384
- // src/pi-request-tools.ts
45385
- var schemaDigests = {
45386
- omp: new WeakMap,
45387
- anthropic: new WeakMap,
45388
- "anthropic-strict": new WeakMap,
45389
- raw: new WeakMap
45390
- };
45391
- function anthropicWireSchema(parameters, strict) {
45392
- const schema = typeof parameters === "object" && parameters !== null ? parameters : {};
45393
- const legacy = {
45394
- type: "object",
45395
- properties: schema.properties ?? {},
45396
- required: schema.required ?? []
45397
- };
45398
- return strict ? { ...schema, ...legacy } : legacy;
45399
- }
45400
- function schemaDigest(tool, mode, wireSchema) {
45401
- const key = tool.parameters;
45402
- const cacheable = typeof key === "object" && key !== null || typeof key === "function";
45403
- const cache = schemaDigests[mode];
45404
- if (cacheable) {
45405
- const cached = cache.get(key);
45406
- if (cached !== undefined)
45407
- return cached;
45408
- }
45409
- const digest = requestToolSchemaDigest(mode === "omp" && wireSchema ? wireSchema(tool) : mode === "anthropic" || mode === "anthropic-strict" ? anthropicWireSchema(tool.parameters, mode === "anthropic-strict") : tool.parameters);
45410
- if (cacheable)
45411
- cache.set(key, digest);
45412
- return digest;
45413
- }
45414
- var CLAUDE_CODE_TOOL_NAMES = new Map([
45415
- "Read",
45416
- "Write",
45417
- "Edit",
45418
- "Bash",
45419
- "Grep",
45420
- "Glob",
45421
- "AskUserQuestion",
45422
- "EnterPlanMode",
45423
- "ExitPlanMode",
45424
- "KillShell",
45425
- "NotebookEdit",
45426
- "Skill",
45427
- "Task",
45428
- "TaskOutput",
45429
- "TodoWrite",
45430
- "WebFetch",
45431
- "WebSearch"
45432
- ].map((name) => [name.toLowerCase(), name]));
45433
- var identityName = (name) => name;
45434
- var claudeCodeName = (name) => CLAUDE_CODE_TOOL_NAMES.get(name.toLowerCase()) ?? name;
45435
- function compatFlag(model, flag) {
45436
- const value = model?.compat?.[flag];
45437
- return typeof value === "boolean" ? value : undefined;
45438
- }
45439
- function supportsToolReferences(model) {
45440
- const declared = compatFlag(model, "supportsToolReferences");
45441
- if (declared !== undefined)
45442
- return declared;
45443
- if (model.provider !== "anthropic" || typeof model.id !== "string")
45444
- return false;
45445
- if (model.id.includes("haiku"))
45446
- return false;
45447
- const version = model.id.match(/^claude-(?:opus|sonnet|fable)-(\d+)(?:-(\d+))?(?:-|$)/);
45448
- if (!version)
45449
- return false;
45450
- const major = Number(version[1]);
45451
- const minor = version[2] && version[2].length < 8 ? Number(version[2]) : 0;
45452
- return major > 4 || major === 4 && minor >= 5;
45453
- }
45454
- function deferredAndReferencedNames(messages, normalizeName) {
45455
- const deferred = new Set;
45456
- const referenced = new Set;
45457
- for (const message of messages) {
45458
- const { role, content, addedToolNames } = message ?? {};
45459
- if (role === "assistant" && Array.isArray(content)) {
45460
- for (const block of content) {
45461
- const { type, name } = block ?? {};
45462
- if (type === "toolCall" && typeof name === "string")
45463
- referenced.add(normalizeName(name));
45464
- }
45465
- } else if (role === "toolResult" && Array.isArray(addedToolNames)) {
45466
- for (const name of addedToolNames) {
45467
- if (typeof name !== "string")
45468
- continue;
45469
- const normalized = normalizeName(name);
45470
- if (!referenced.has(normalized))
45471
- deferred.add(normalized);
45472
- }
45473
- }
45474
- }
45475
- for (const name of deferred)
45476
- referenced.add(name);
45477
- return { deferred, referenced };
45478
- }
45479
- function calledToolNames(messages) {
45480
- const names = new Set;
45481
- for (const message of messages) {
45482
- const content = message?.content;
45483
- if (!Array.isArray(content))
45484
- continue;
45485
- for (const part of content) {
45486
- const { type, name } = part ?? {};
45487
- if (typeof type === "string" && type.toLowerCase().includes("tool") && typeof name === "string")
45488
- names.add(name);
45489
- }
45490
- }
45491
- return names;
45492
- }
45493
- function readPiRequestToolsFingerprint(pi, wireSchema, messages, route = {}) {
45494
- try {
45495
- if (typeof pi.getAllTools !== "function" || typeof pi.getActiveTools !== "function")
45496
- return;
45497
- const all = pi.getAllTools();
45498
- const active = pi.getActiveTools();
45499
- if (!Array.isArray(all) || !Array.isArray(active))
45500
- return;
45501
- const registered = new Map;
45502
- for (const tool of all) {
45503
- if (!tool || typeof tool !== "object")
45504
- return;
45505
- const { name } = tool;
45506
- if (typeof name !== "string")
45507
- return;
45508
- registered.set(name, tool);
45509
- }
45510
- const model = route.model;
45511
- const anthropicWriter = route.host === "pi" && wireSchema === undefined && model?.api === "anthropic-messages";
45512
- const mode = wireSchema ? "omp" : anthropicWriter ? compatFlag(model, "supportsStrictTools") === true ? "anthropic-strict" : "anthropic" : "raw";
45513
- const normalizeName = anthropicWriter && route.oauth === true ? claudeCodeName : identityName;
45514
- const sent = new Map;
45515
- for (const name of active) {
45516
- if (typeof name !== "string")
45517
- return;
45518
- const tool = registered.get(name);
45519
- if (!tool)
45520
- continue;
45521
- sent.set(normalizeName(name), tool);
45522
- }
45523
- const split = anthropicWriter && model && supportsToolReferences(model) ? deferredAndReferencedNames(messages, normalizeName) : undefined;
45524
- const anyImmediate = [...sent.keys()].some((name) => !split?.deferred.has(name));
45525
- const tools = [];
45526
- for (const [name, tool] of sent) {
45527
- const description = typeof tool.description === "string" ? tool.description : "";
45528
- tools.push({
45529
- name,
45530
- description,
45531
- schemaDigest: schemaDigest({
45532
- name: tool.name,
45533
- description,
45534
- parameters: tool.parameters
45535
- }, mode, wireSchema),
45536
- deferLoading: split ? anyImmediate && split.deferred.has(name) : tool.defer_loading === true || tool.deferLoading === true
45537
- });
45538
- }
45539
- return requestToolsFingerprint(tools, () => split?.referenced ?? calledToolNames(messages));
45540
- } catch {
45541
- return;
45542
- }
45543
- }
45544
-
45545
45750
  // src/pi-tag-identity-repair.ts
45546
45751
  var PI_TAG_IDENTITY_REPAIR_REASON = "tag_identity_repair";
45547
45752
  var unreadableLedgerLogged = new Set;
@@ -45921,6 +46126,22 @@ function reportBindingRecovery(sessionId, report, message) {
45921
46126
  else
45922
46127
  log2(`[magic-context][${sessionId}] ${message}`);
45923
46128
  }
46129
+ function armPiProviderOverflowRecovery(args) {
46130
+ recordOverflowDetected(args.db, args.sessionId, args.reportedLimit, args.modelKey, "provider_overflow", args.reportedLimitProvenance, args.reportedInputTokens);
46131
+ if (getHarness2() === "pi") {
46132
+ try {
46133
+ resetPiUpperEstimateReclaim(args.db, args.sessionId);
46134
+ } catch (error) {
46135
+ args.report?.(`upper-estimate reclaim reset deferred: ${String(error)}`);
46136
+ }
46137
+ }
46138
+ }
46139
+ function armPiRecoveryForHostOverflowCompaction(args) {
46140
+ if (getOverflowState(args.db, args.sessionId).needsEmergencyRecovery)
46141
+ return "already-armed";
46142
+ armPiProviderOverflowRecovery(args);
46143
+ return "armed";
46144
+ }
45924
46145
  function handlePiProviderFailure(args) {
45925
46146
  if (!args.message || typeof args.message !== "object")
45926
46147
  return { kind: "none" };
@@ -45950,19 +46171,21 @@ function handlePiProviderFailure(args) {
45950
46171
  if (args.compactionOff)
45951
46172
  return { kind: "none" };
45952
46173
  const overflow = detectOverflow(message.errorMessage);
45953
- if (!overflow.isOverflow)
46174
+ const hostOnly = !overflow.isOverflow && args.hostOverflowCheck?.(args.message) === true;
46175
+ if (!overflow.isOverflow && !hostOnly)
45954
46176
  return { kind: "none" };
45955
- const modelKey = provider && model ? `${provider}/${model}` : undefined;
45956
- recordOverflowDetected(args.db, args.sessionId, overflow.reportedLimit, modelKey, "provider_overflow", overflow.reportedLimitProvenance, overflow.reportedInputTokens);
45957
- if (getHarness2() === "pi") {
45958
- try {
45959
- resetPiUpperEstimateReclaim(args.db, args.sessionId);
45960
- } catch (error) {
45961
- args.report?.(`upper-estimate reclaim reset deferred: ${String(error)}`);
45962
- }
45963
- }
46177
+ armPiProviderOverflowRecovery({
46178
+ db: args.db,
46179
+ sessionId: args.sessionId,
46180
+ modelKey: provider && model ? `${provider}/${model}` : undefined,
46181
+ reportedLimit: overflow.reportedLimit,
46182
+ reportedLimitProvenance: overflow.reportedLimitProvenance,
46183
+ reportedInputTokens: overflow.reportedInputTokens,
46184
+ report: args.report
46185
+ });
45964
46186
  return {
45965
46187
  kind: "overflow",
46188
+ source: hostOnly ? "host" : "magic-context",
45966
46189
  ...overflow.reportedLimit !== undefined ? { reportedLimit: overflow.reportedLimit } : {},
45967
46190
  ...overflow.reportedLimitProvenance !== undefined ? { reportedLimitProvenance: overflow.reportedLimitProvenance } : {},
45968
46191
  ...overflow.matchedPattern !== undefined ? { matchedPattern: overflow.matchedPattern } : {}
@@ -49650,6 +49873,7 @@ function registerPiContextHandler(pi, baseOptions) {
49650
49873
  return;
49651
49874
  }
49652
49875
  sessionIdForError = sessionId;
49876
+ resetPiUnplacedCutLog(sessionId);
49653
49877
  try {
49654
49878
  const effectiveSystem = readHostSystemPrompt(ctx);
49655
49879
  if (effectiveSystem !== undefined)
@@ -49781,6 +50005,7 @@ function registerPiContextHandler(pi, baseOptions) {
49781
50005
  }
49782
50006
  }));
49783
50007
  assertCurrentPass();
50008
+ const historyHead = sessionMetaForUsage.isSubagent ? undefined : options.injection;
49784
50009
  updateSessionProjectTracking(sessionId, projectIdentity, options.db, projectDirectory);
49785
50010
  const lkgInputIdByRef = new Map;
49786
50011
  for (const input of lkgPassSnapshot.inputs)
@@ -49831,17 +50056,17 @@ function registerPiContextHandler(pi, baseOptions) {
49831
50056
  }
49832
50057
  }
49833
50058
  const tMeta = performance.now();
49834
- let piM0M1PassSnapshot = options.injection ? createPiM0M1PassSnapshot({
50059
+ let piM0M1PassSnapshot = historyHead ? createPiM0M1PassSnapshot({
49835
50060
  db: options.db,
49836
50061
  sessionId,
49837
50062
  compactionOff: options.compactionOff === true,
49838
50063
  sessionMeta: sessionMetaForUsage
49839
50064
  }) : undefined;
49840
50065
  logTransformTiming(sessionId, "getOrCreateSessionMeta", tMeta);
49841
- if (strictEntryIds && branchEntries && options.injection && !options.compactionOff && stripMcOwnedPiCompactionSummary(event.messages, strictEntryIds, branchEntries)) {
50066
+ if (strictEntryIds && branchEntries && historyHead && !options.compactionOff && stripMcOwnedPiCompactionSummary(event.messages, strictEntryIds, branchEntries)) {
49842
50067
  logTransformTiming(sessionId, "mcCompactionSummarySuppression", tEntryBranch);
49843
50068
  }
49844
- if (strictEntryIds && options.injection && !options.compactionOff) {
50069
+ if (strictEntryIds && historyHead && !options.compactionOff) {
49845
50070
  const removed = trimPiMessagesToCachedBoundary(options.db, sessionId, event.messages, strictEntryIds, piM0M1PassSnapshot);
49846
50071
  if (removed > 0) {
49847
50072
  logTransformTiming(sessionId, "cachedBoundaryEarlyTrim", tEntryBranch, `removed=${removed}`);
@@ -49903,7 +50128,7 @@ function registerPiContextHandler(pi, baseOptions) {
49903
50128
  clearPiInjectionTokenCountCache(sessionId);
49904
50129
  sessionMetaForUsage.cachedM0Bytes = null;
49905
50130
  sessionMetaForUsage.cachedM1Bytes = null;
49906
- piM0M1PassSnapshot = options.injection ? createPiM0M1PassSnapshot({
50131
+ piM0M1PassSnapshot = historyHead ? createPiM0M1PassSnapshot({
49907
50132
  db: options.db,
49908
50133
  sessionId,
49909
50134
  compactionOff: options.compactionOff === true,
@@ -50127,7 +50352,7 @@ function registerPiContextHandler(pi, baseOptions) {
50127
50352
  }
50128
50353
  assertCurrentPass();
50129
50354
  sessionMeta = getOrCreateSessionMeta(options.db, sessionId);
50130
- piM0M1PassSnapshot = options.injection ? createPiM0M1PassSnapshot({
50355
+ piM0M1PassSnapshot = historyHead ? createPiM0M1PassSnapshot({
50131
50356
  db: options.db,
50132
50357
  sessionId,
50133
50358
  compactionOff: false,
@@ -50171,7 +50396,7 @@ function registerPiContextHandler(pi, baseOptions) {
50171
50396
  recoveryArmed: emergencyRecoveryArmed || !!recovery.rebuildReason,
50172
50397
  forceMaterialization,
50173
50398
  imported: looksLikeImportedSession || usageInputTokens <= 0 && (isFirstContextPassForSession || lkgPassSnapshot?.replayFailure !== null),
50174
- coldInjection: !!options.injection && !sessionMeta.cachedM0Bytes,
50399
+ coldInjection: !!historyHead && !sessionMeta.cachedM0Bytes,
50175
50400
  cacheBusting: isCacheBusting,
50176
50401
  sessionId,
50177
50402
  appendedMessages: lkgPassSnapshot?.pristineTail ?? event.messages.slice(-1),
@@ -50193,7 +50418,13 @@ function registerPiContextHandler(pi, baseOptions) {
50193
50418
  }
50194
50419
  maintainExecuteFloorMark(options.db, sessionId, promptId, usagePercentage < effectiveExecuteThresholdPercentage);
50195
50420
  }
50421
+ const ctxReduceCallable = piCtxReduceCallable(pi, options.compactionOff === true, { db: options.db, sessionId });
50422
+ const servedCtxReduceCallable = options.compactionOff || budget.sideTurn ? ctxReduceCallable : readServedPiCtxReduceCallable(options.db, sessionId);
50423
+ if (!ctxReduceCallable && !budget.sideTurn)
50424
+ clearPiChannel1State(sessionId);
50196
50425
  const pipelineArgs = {
50426
+ ctxReduceCallable,
50427
+ servedCtxReduceCallable,
50197
50428
  providerOverflowRecovery: emergencyRecoveryArmed && historianStateForPass.emergencyRecoveryOrigin === "provider_overflow",
50198
50429
  dropBranchEntries: branchEntries ?? undefined,
50199
50430
  recoveryPrefix: recovery.prefix,
@@ -50218,9 +50449,9 @@ function registerPiContextHandler(pi, baseOptions) {
50218
50449
  reclaimUsableWindow: windowGeometry?.usableSoft ?? usageContextLimit ?? 0,
50219
50450
  heuristics: options.heuristics,
50220
50451
  emergencyCeilingTokens,
50221
- injection: options.injection ? {
50222
- ...options.injection,
50223
- memoryEnabled: options.injection.memoryEnabled,
50452
+ injection: historyHead ? {
50453
+ ...historyHead,
50454
+ memoryEnabled: historyHead.memoryEnabled,
50224
50455
  historyBudgetPolicyIdentity: historyBudgetPolicyIdentity(options.historian?.historyBudgetPercentage, options.historian?.executeThresholdPercentage, liveModelBySession.get(sessionId), options.historian?.executeThresholdTokens),
50225
50456
  historyBudgetTokens: resolveHistoryBudgetTokensForPi({
50226
50457
  historyBudgetPercentage: options.historian?.historyBudgetPercentage,
@@ -50241,7 +50472,7 @@ function registerPiContextHandler(pi, baseOptions) {
50241
50472
  schedulerDeferReason,
50242
50473
  forceMaterialization: forceMaterialization || isEmergency,
50243
50474
  forceMaterializationPercentage,
50244
- signedThinkingHold: requestToolsChange === null && resolvePiSignedThinkingHold({
50475
+ signedThinkingHold: requestToolsChange === null && ctxReduceCallable === servedCtxReduceCallable && resolvePiSignedThinkingHold({
50245
50476
  sessionId,
50246
50477
  db: options.db,
50247
50478
  messages: event.messages,
@@ -50304,7 +50535,7 @@ function registerPiContextHandler(pi, baseOptions) {
50304
50535
  if (!options.compactionOff)
50305
50536
  assertPiTagSnapshotReady(options.db, sessionId);
50306
50537
  let historianEvaluatedThisPass = false;
50307
- const historian = options.historian;
50538
+ const historian = sessionMeta.isSubagent ? undefined : options.historian;
50308
50539
  const scheduleHistorian = (result) => {
50309
50540
  if (historianEvaluatedThisPass)
50310
50541
  return;
@@ -50426,7 +50657,7 @@ function registerPiContextHandler(pi, baseOptions) {
50426
50657
  const todoAnchorBefore = JSON.stringify(getPersistedTodoSyntheticAnchor(options.db, sessionId));
50427
50658
  const tNoteNudges = performance.now();
50428
50659
  try {
50429
- if (!options.compactionOff) {
50660
+ if (!options.compactionOff && !sessionMeta.isSubagent) {
50430
50661
  outputMessages = applyNoteNudges({
50431
50662
  sessionId,
50432
50663
  db: options.db,
@@ -50445,7 +50676,7 @@ function registerPiContextHandler(pi, baseOptions) {
50445
50676
  logTransformTiming(sessionId, "noteNudges", tNoteNudges);
50446
50677
  const tAutoSearch = performance.now();
50447
50678
  budget.stage = "auto-search";
50448
- if (options.autoSearch?.enabled && !options.compactionOff && result.prefixMutationAllowed && budget.remainingWork() > PI_CONTEXT_BUDGET.searchMs) {
50679
+ if (options.autoSearch?.enabled && !options.compactionOff && !sessionMeta.isSubagent && result.prefixMutationAllowed && budget.remainingWork() > PI_CONTEXT_BUDGET.searchMs) {
50449
50680
  guardSqliteTransformPass2({
50450
50681
  assert: budget.assert,
50451
50682
  remainingMs: budget.remainingWork
@@ -50582,7 +50813,7 @@ function registerPiContextHandler(pi, baseOptions) {
50582
50813
  const tChannelAccounting = performance.now();
50583
50814
  try {
50584
50815
  const sessionMetaForCh1 = sessionMeta;
50585
- if (!options.compactionOff && !sessionMetaForCh1.isSubagent) {
50816
+ if (ctxReduceCallable) {
50586
50817
  const { tags, protectedTagNumbers, pendingDropTagNumbers } = result.channelBaselineSnapshot;
50587
50818
  const stableId = (message) => message && typeof message === "object" ? result.postCommitEntryIdByRef.get(message) : undefined;
50588
50819
  const hygieneCalibration = sessionDecisionCalibration(options.db, sessionId);
@@ -50849,7 +51080,7 @@ function registerPiContextHandler(pi, baseOptions) {
50849
51080
  upperEstimateOnly: !recoverUnknownUsage && fitCase === "upper-estimate-pressure",
50850
51081
  forceSignedRebuildForFit: fitCase === "over-window-proof",
50851
51082
  isCacheBusting: historyRefreshSessions.has(sessionId) || deferredHistoryRefreshSessions.has(sessionId),
50852
- injectionPassSnapshot: options.injection ? createPiM0M1PassSnapshot({
51083
+ injectionPassSnapshot: historyHead ? createPiM0M1PassSnapshot({
50853
51084
  db: options.db,
50854
51085
  sessionId,
50855
51086
  compactionOff: false,
@@ -51006,6 +51237,8 @@ function registerPiContextHandler(pi, baseOptions) {
51006
51237
  sessionLog2(sessionId, "request tools release not recorded: the end strip order could not be written");
51007
51238
  });
51008
51239
  afterCapture(sessionId, "served system hash record", recordServedSystemHash);
51240
+ if (!budget.sideTurn && !options.compactionOff)
51241
+ afterCapture(sessionId, "ctx_reduce served record", () => recordServedPiCtxReduceCallable(options.db, sessionId, ctxReduceCallable));
51009
51242
  return { messages: outputMessages };
51010
51243
  } catch (err) {
51011
51244
  if (budget.isCancelled(err))
@@ -52252,7 +52485,10 @@ async function runPipeline(args) {
52252
52485
  return findLatestUserMessageIdPi(args.messages, ids)?.messageId ?? null;
52253
52486
  })();
52254
52487
  const alreadyRanHeuristicsThisTurn = currentTurnId !== null && lastHeuristicsTurnIdBySession.get(args.sessionId) === currentTurnId;
52255
- const ctxReduceCallable = !args.sessionMeta.isSubagent;
52488
+ const ctxReduceCallable = args.ctxReduceCallable;
52489
+ const requestToolListChanged = args.ctxReduceCallable !== args.servedCtxReduceCallable;
52490
+ if (requestToolListChanged)
52491
+ sessionLog2(args.sessionId, `request tool list changed: ctx_reduce ${args.ctxReduceCallable ? "added; tag prefixes return" : "removed; tag prefixes stop"} on this rebuild`);
52256
52492
  const canConsumeDeferredLate = args.schedulerDecision === "execute" || args.forceMaterialization === true || args.contextUsage.percentage >= forceMaterializationPercentage;
52257
52493
  let deferredMaterializeEligible = canConsumeDeferredLate && deferredMaterializationSessions.has(args.sessionId) && !protectedSignedPrefix;
52258
52494
  const executePressureEligible = args.schedulerDecision === "execute" || emergencyDropEligible;
@@ -52267,7 +52503,7 @@ async function runPipeline(args) {
52267
52503
  const rideSignals = {
52268
52504
  executeReclaim: false,
52269
52505
  subagentExecute: args.sessionMeta.isSubagent && args.schedulerDecision === "execute",
52270
- hardFold: foldBustsServedPrefixThisPass || systemPrefixChangedThisPass || firstRenderBust || isCacheBustingPass,
52506
+ hardFold: foldBustsServedPrefixThisPass || systemPrefixChangedThisPass || requestToolListChanged || firstRenderBust || isCacheBustingPass,
52271
52507
  force: (args.forceMaterialization === true || emergencyDropEligible) && (args.contextUsage.percentage >= 95 || getEmergencyInputSample(args.db, args.sessionId) === 0),
52272
52508
  explicitFlush: !protectedSignedPrefix && (args.userFlushOrigin === true || hasPendingMaterializationOrigin(pendingMaterializationSessions, args.sessionId, "user_flush")),
52273
52509
  publishedHistory: !prefixPreflightContended && publishedM1RefreshedThisPass
@@ -52300,7 +52536,7 @@ async function runPipeline(args) {
52300
52536
  onRejectedProjectOverride: (warning) => sessionLog2(args.sessionId, warning)
52301
52537
  });
52302
52538
  let protectionFloorResolution = resolveProtectionFloor();
52303
- let shouldRunHeuristics = args.heuristics !== undefined && isCacheBustingPass && (rideSignals.publishedHistory || systemPrefixChangedThisPass || rideSignals.explicitFlush || args.forceMaterialization === true || hasPendingMaterializeSignal || deferredMaterializeEligible || foldBustsServedPrefixThisPass || firstRenderBust || args.recoveryRebuildReason !== undefined && isCacheBustingPass || rideSignals.subagentExecute || args.schedulerDecision === "execute" && !alreadyRanHeuristicsThisTurn);
52539
+ let shouldRunHeuristics = args.heuristics !== undefined && isCacheBustingPass && (rideSignals.publishedHistory || systemPrefixChangedThisPass || requestToolListChanged || rideSignals.explicitFlush || args.forceMaterialization === true || hasPendingMaterializeSignal || deferredMaterializeEligible || foldBustsServedPrefixThisPass || firstRenderBust || args.recoveryRebuildReason !== undefined && isCacheBustingPass || rideSignals.subagentExecute || args.schedulerDecision === "execute" && !alreadyRanHeuristicsThisTurn);
52304
52540
  let unavoidableCarriedIdentityRebuild = false;
52305
52541
  if (protectedSignedPrefix && readPiIdentityRebuilds(args.db, args.sessionId).length > 0) {
52306
52542
  args.tryReplayHeldIdentityRebuild?.();
@@ -52674,7 +52910,8 @@ async function runPipeline(args) {
52674
52910
  const emergencyPlannerMayRun = shouldRunHeuristics && args.heuristics !== undefined && args.forceMaterialization === true && args.emergencyCeilingTokens !== undefined && args.emergencyCeilingTokens > 0;
52675
52911
  const tagsNewerThanReading = emergencyPlannerMayRun ? tagsSinceReading(transcript.messages, newTargets) : undefined;
52676
52912
  const queuedDropTags = new Set(pendingOps.map((op) => op.tagId));
52677
- const emergencyServedBeforeDrain = emergencyPlannerMayRun && shouldApplyPendingOps && queuedDropTags.size > 0 ? snapshotPiEmergencyServedMass(getPiActiveTagSnapshotView(args.db, args.sessionId).filter((tag) => queuedDropTags.has(tag.tagNumber) && !tagsNewerThanReading?.has(tag.tagNumber)), newTargets, args.providerOverflowRecovery === true ? piRecoveryToolImageTokens(workingMessages) : undefined) : undefined;
52913
+ const emergencyToolImageTokens = () => args.providerOverflowRecovery === true ? piRecoveryToolImageTokens(workingMessages) : piToolImageCostTokens(workingMessages);
52914
+ const emergencyServedBeforeDrain = emergencyPlannerMayRun && shouldApplyPendingOps && queuedDropTags.size > 0 ? snapshotPiEmergencyServedMass(getPiActiveTagSnapshotView(args.db, args.sessionId).filter((tag) => queuedDropTags.has(tag.tagNumber) && !tagsNewerThanReading?.has(tag.tagNumber)), newTargets, emergencyToolImageTokens()) : undefined;
52678
52915
  mutationGateObserverForTests?.({
52679
52916
  foldDue: foldDueDecision.value,
52680
52917
  foldExecuted: foldExecutedThisPass,
@@ -52814,7 +53051,7 @@ async function runPipeline(args) {
52814
53051
  const tHeuristic = performance.now();
52815
53052
  const providerOverflow = args.providerOverflowRecovery === true;
52816
53053
  const recoveryCalibration = sessionDecisionCalibration(args.db, args.sessionId);
52817
- const independentMutationBeforeHeuristics = pendingOpsDidMutate || systemPrefixChangedThisPass || foldBustsServedPrefixThisPass || identityRebuild || firstRenderBust;
53054
+ const independentMutationBeforeHeuristics = pendingOpsDidMutate || systemPrefixChangedThisPass || requestToolListChanged || foldBustsServedPrefixThisPass || identityRebuild || firstRenderBust;
52818
53055
  if (args.forceMaterialization === true && independentMutationBeforeHeuristics && getEmergencyInputSample(args.db, args.sessionId) > 0) {
52819
53056
  clearEmergencyDropSample(args.db, args.sessionId);
52820
53057
  }
@@ -52832,7 +53069,7 @@ async function runPipeline(args) {
52832
53069
  ceilingTokens: args.emergencyCeilingTokens,
52833
53070
  usagePercentage: args.contextUsage.percentage,
52834
53071
  passAlreadyPriced: independentMutationBeforeHeuristics,
52835
- serializedImageTokens: providerOverflow ? piRecoveryToolImageTokens(workingMessages) : undefined,
53072
+ toolImageTokens: emergencyToolImageTokens(),
52836
53073
  fitCalibration: providerOverflow ? piRecoveryFitCalibration(recoveryCalibration) : undefined,
52837
53074
  servedBeforePass: emergencyServedBeforeDrain,
52838
53075
  sinceReading: tagsNewerThanReading
@@ -53217,7 +53454,12 @@ async function runPipeline(args) {
53217
53454
  logTransformTiming(args.sessionId, "prepareCompartmentInjection", tInjection);
53218
53455
  logTransformTiming(args.sessionId, "compartmentPhase", tInjection);
53219
53456
  } catch (err) {
53220
- sessionLog2(args.sessionId, `compartment injection failed (continuing): ${err instanceof Error ? err.message : String(err)}`);
53457
+ sessionLog2(args.sessionId, `compartment injection failed; replaying the last good request or refusing the turn: ${err instanceof Error ? err.message : String(err)}`);
53458
+ if (isTransientPiStorageError(err))
53459
+ throw err;
53460
+ throw new PiDegradedPassError("m0-m1-injection-degradation", {
53461
+ cause: err
53462
+ });
53221
53463
  }
53222
53464
  }
53223
53465
  transcript.finalizeToolRemovals();
@@ -53717,6 +53959,7 @@ function clearContextHandlerSession(sessionId) {
53717
53959
  dropServedRecord(sessionId, "session_cleared");
53718
53960
  cancelPiTagSnapshotSession(sessionId);
53719
53961
  lastServedSystemHashBySession.delete(sessionId);
53962
+ clearPiCtxReduceCallableSession(sessionId);
53720
53963
  clearPiHistoryBoundaryRepairSession(sessionId);
53721
53964
  clearPiUpperReclaimSession(sessionId);
53722
53965
  invalidateTrueRawTokenCache({ sessionId, reason: "pi.branch.changed" });
@@ -53756,6 +53999,7 @@ function clearContextHandlerSession(sessionId) {
53756
53999
  clearPiCompactionMarkerDrainLogState(sessionId);
53757
54000
  clearPiInjectionTokenCountCache(sessionId);
53758
54001
  clearPiMuralProcessCache(sessionId);
54002
+ resetPiUnplacedCutLog(sessionId);
53759
54003
  clearPiTailHygieneContentMemo();
53760
54004
  clearPiChannel1State(sessionId);
53761
54005
  lastHeuristicsTurnIdBySession.delete(sessionId);
@@ -56804,6 +57048,38 @@ function registerPiFailClosedSurface(pi, args) {
56804
57048
  };
56805
57049
  }
56806
57050
 
57051
+ // src/host-overflow-check-pi.ts
57052
+ var HOST_PI_AI_MODULE = "@earendil-works/pi-ai";
57053
+ var importHostModule = () => import("@earendil-works/pi-ai");
57054
+ var loadHostModule = importHostModule;
57055
+ var hostCheck;
57056
+ function loadPiHostOverflowCheck() {
57057
+ hostCheck ??= resolveHostOverflowCheck();
57058
+ return hostCheck;
57059
+ }
57060
+ async function resolveHostOverflowCheck() {
57061
+ let module;
57062
+ try {
57063
+ module = await loadHostModule();
57064
+ } catch (error) {
57065
+ log2(`[magic-context] host overflow check unavailable: ${HOST_PI_AI_MODULE} did not load (${error instanceof Error ? error.message : String(error)}); using Magic Context's overflow patterns only`);
57066
+ return;
57067
+ }
57068
+ const check = module?.isContextOverflow;
57069
+ if (typeof check !== "function") {
57070
+ log2(`[magic-context] host overflow check unavailable: ${HOST_PI_AI_MODULE} has no isContextOverflow export; using Magic Context's overflow patterns only`);
57071
+ return;
57072
+ }
57073
+ log2(`[magic-context] host overflow check: using isContextOverflow from ${HOST_PI_AI_MODULE}`);
57074
+ return (message) => {
57075
+ try {
57076
+ return check(message) === true;
57077
+ } catch {
57078
+ return false;
57079
+ }
57080
+ };
57081
+ }
57082
+
56807
57083
  // src/message-end-index-pi.ts
56808
57084
  var unpersistedMessageSeq = 0;
56809
57085
  function findEntryIdForMessage(branch, message) {
@@ -56836,6 +57112,34 @@ function schedulePiAssistantIndexOnMessageEnd(db, sessionId, endedMessage, sessi
56836
57112
  });
56837
57113
  }
56838
57114
 
57115
+ // src/pi-agent-identity.ts
57116
+ var checkedSessions = new BoundedSessionMap(1000);
57117
+ function readAgentKind(ctx) {
57118
+ try {
57119
+ return ctx?.agent?.kind;
57120
+ } catch {
57121
+ return;
57122
+ }
57123
+ }
57124
+ function recordPiSpawnedSession(db, sessionId, ctx) {
57125
+ if (checkedSessions.has(sessionId))
57126
+ return;
57127
+ checkedSessions.set(sessionId, true);
57128
+ if (readAgentKind(ctx) !== "sub")
57129
+ return;
57130
+ if (getOrCreateSessionMeta(db, sessionId).isSubagent)
57131
+ return;
57132
+ if (hasCompartments(db, sessionId)) {
57133
+ sessionLog2(sessionId, "Oh My Pi spawned session (agent kind sub) has compartments from its source session: kept primary");
57134
+ return;
57135
+ }
57136
+ updateSessionMeta(db, sessionId, { isSubagent: true });
57137
+ sessionLog2(sessionId, "Oh My Pi spawned session (agent kind sub): recorded as a subagent");
57138
+ }
57139
+ function hasCompartments(db, sessionId) {
57140
+ return db.prepare("SELECT 1 AS present FROM compartments WHERE session_id = ? LIMIT 1").get(sessionId) != null;
57141
+ }
57142
+
56839
57143
  // ../plugin/src/plugin/boot-deadline.ts
56840
57144
  async function runBootPhaseWithDeadline(phase, operation, timeoutMs, report, deadlineDescription = `its ${timeoutMs}ms deadline`) {
56841
57145
  const startedAt = performance.now();
@@ -57259,6 +57563,23 @@ function signalPiDeferredCompactionMarkerDrain(sessionId) {
57259
57563
  }
57260
57564
  async function handlePiSessionBeforeCompact(args) {
57261
57565
  if (!args.compactionOff) {
57566
+ if (args.event?.reason === "overflow" && args.event.willRetry === true) {
57567
+ try {
57568
+ const sessionId = args.ctx.sessionManager?.getSessionId?.();
57569
+ if (typeof sessionId === "string" && sessionId.length > 0) {
57570
+ const provider = args.ctx.model?.provider;
57571
+ const model = args.ctx.model?.id;
57572
+ const outcome = armPiRecoveryForHostOverflowCompaction({
57573
+ db: args.db,
57574
+ sessionId,
57575
+ modelKey: typeof provider === "string" && typeof model === "string" ? `${provider}/${model}` : undefined
57576
+ });
57577
+ info(`session_before_compact: host compacting for overflow; provider-overflow recovery ${outcome}`);
57578
+ }
57579
+ } catch (err) {
57580
+ warn("session_before_compact: overflow recovery arm failed:", err);
57581
+ }
57582
+ }
57262
57583
  info("session_before_compact: cancelling — magic-context owns compaction");
57263
57584
  return { cancel: true };
57264
57585
  }
@@ -58169,6 +58490,8 @@ async function startPiMagicContextRuntime(pi, database, dbPath) {
58169
58490
  onInherited: (sessionId) => prewarmPiTagSnapshot(db, sessionId, "pass")
58170
58491
  });
58171
58492
  const sessionId = resolveSessionId(ctx);
58493
+ if (sessionId)
58494
+ recordPiSpawnedSession(db, sessionId, ctx);
58172
58495
  if (!piMarkerRehydrationLogged && pendingPiMarkerSessions.length > 0 && sessionId) {
58173
58496
  log2(formatPiMarkerRehydrationLine(pendingPiMarkerSessions, sessionId));
58174
58497
  piMarkerRehydrationLogged = true;
@@ -58431,6 +58754,7 @@ async function startPiMagicContextRuntime(pi, database, dbPath) {
58431
58754
  }
58432
58755
  }
58433
58756
  if (sessionId) {
58757
+ recordPiSpawnedSession(db, sessionId, ctx);
58434
58758
  trackSessionForProject(currentProject.projectIdentity, sessionId);
58435
58759
  try {
58436
58760
  const smForDrain = sm;
@@ -58458,7 +58782,7 @@ async function startPiMagicContextRuntime(pi, database, dbPath) {
58458
58782
  memoryEnabled: effectiveConfig.memory.enabled,
58459
58783
  includeGuidance: true,
58460
58784
  protectedTags: effectiveConfig.protected_tags,
58461
- ctxReduceCallable: !compactionOff,
58785
+ ctxReduceCallable: piCtxReduceCallable(pi, compactionOff, sessionId ? { db, sessionId } : undefined),
58462
58786
  dreamerEnabled: effectiveProjectDeps.dreamerEnabled,
58463
58787
  smartNotesEnabled: config.smart_notes.enabled,
58464
58788
  temporalAwarenessEnabled: effectiveConfig.temporal_awareness ?? false,
@@ -58513,8 +58837,12 @@ async function startPiMagicContextRuntime(pi, database, dbPath) {
58513
58837
  const lastAssistant = Array.isArray(msgs) ? [...msgs].reverse().find((m) => m?.role === "assistant") : undefined;
58514
58838
  if (lastAssistant?.stopReason === "stop") {
58515
58839
  const sessionId = ctx.sessionManager?.getSessionId?.();
58516
- if (sessionId && db && !compactionOff)
58517
- maybeDeliverChannel2Pi(pi, db, sessionId);
58840
+ if (sessionId && db) {
58841
+ if (piCtxReduceCallable(pi, compactionOff, { db, sessionId }))
58842
+ maybeDeliverChannel2Pi(pi, db, sessionId);
58843
+ else
58844
+ clearPiChannel1State(sessionId);
58845
+ }
58518
58846
  }
58519
58847
  } catch (err) {
58520
58848
  log2(`agent_end: channel2 delivery skipped: ${String(err)}`);
@@ -58568,8 +58896,10 @@ async function startPiMagicContextRuntime(pi, database, dbPath) {
58568
58896
  const sessionId = ctx.sessionManager.getSessionId();
58569
58897
  if (typeof sessionId !== "string" || sessionId.length === 0)
58570
58898
  return;
58571
- if (compactionOff)
58899
+ if (!piCtxReduceCallable(pi, compactionOff, db ? { db, sessionId } : undefined)) {
58900
+ clearPiChannel1State(sessionId);
58572
58901
  return;
58902
+ }
58573
58903
  const block = maybeChannel1ReminderForToolResult({
58574
58904
  db,
58575
58905
  sessionId,
@@ -58585,7 +58915,7 @@ async function startPiMagicContextRuntime(pi, database, dbPath) {
58585
58915
  log2(`tool_result hook failed (continuing): ${err instanceof Error ? err.message : String(err)}`);
58586
58916
  }
58587
58917
  });
58588
- pi.on("session_before_compact", async (_event, ctx) => handlePiSessionBeforeCompact({ db, compactionOff, ctx }));
58918
+ pi.on("session_before_compact", async (event, ctx) => handlePiSessionBeforeCompact({ db, compactionOff, ctx, event }));
58589
58919
  if (PI_HARNESS_KIND !== "omp") {
58590
58920
  registerStreamTagPrefixStrip(pi, () => !compactionOff);
58591
58921
  } else {
@@ -58677,14 +59007,17 @@ async function startPiMagicContextRuntime(pi, database, dbPath) {
58677
59007
  const sessionId = sm?.getSessionId?.();
58678
59008
  if (typeof sessionId !== "string" || sessionId.length === 0)
58679
59009
  return;
59010
+ const failed = event.message;
59011
+ const hostOverflowCheck = !compactionOff && failed?.role === "assistant" && typeof failed.errorMessage === "string" && failed.errorMessage.length > 0 ? await loadPiHostOverflowCheck() : undefined;
58680
59012
  const recovery = handlePiProviderFailure({
58681
59013
  db,
58682
59014
  sessionId,
58683
59015
  message: event.message,
58684
- compactionOff
59016
+ compactionOff,
59017
+ hostOverflowCheck
58685
59018
  });
58686
59019
  if (recovery.kind === "overflow") {
58687
- log2(`[magic-context][${sessionId}] overflow detected: reportedLimit=${recovery.reportedLimit ?? "?"} provenance=${recovery.reportedLimitProvenance ?? "?"} pattern=${recovery.matchedPattern ?? "?"}`);
59020
+ log2(`[magic-context][${sessionId}] overflow detected: source=${recovery.source} reportedLimit=${recovery.reportedLimit ?? "?"} provenance=${recovery.reportedLimitProvenance ?? "?"} pattern=${recovery.matchedPattern ?? "?"}`);
58688
59021
  }
58689
59022
  } catch (err) {
58690
59023
  warn("message_end: provider failure classification failed:", err);