@cortexkit/pi-magic-context 0.49.63 → 0.49.65

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 (25) hide show
  1. package/dist/auto-search-worker.js +1 -1
  2. package/dist/chunk-embedding-write-worker.js +1 -1
  3. package/dist/{index-418za765.js → index-1tkrgcdt.js} +56 -9
  4. package/dist/{index-w4sqw9mf.js → index-67q9cz3f.js} +1 -1
  5. package/dist/{index-zgsemyph.js → index-6vmpw4z3.js} +3 -3
  6. package/dist/{index-8gvbskcm.js → index-7vhbmjgv.js} +87 -44
  7. package/dist/{index-5hhhxck7.js → index-8328rak2.js} +1 -1
  8. package/dist/{index-xan5mt5f.js → index-98e27fdt.js} +1 -1
  9. package/dist/{index-f4n7tnsf.js → index-hja11zte.js} +1 -1
  10. package/dist/{index-m6kszx0e.js → index-renfmk50.js} +1 -1
  11. package/dist/{index-9cqfbdgb.js → index-vkcb1cg1.js} +3 -3
  12. package/dist/{index-fz4gexgk.js → index-ye6b3dr4.js} +1 -1
  13. package/dist/index.js +589 -305
  14. package/dist/{message-index-bounded-behq385r.js → message-index-bounded-b5vft8jk.js} +3 -3
  15. package/dist/migration-worker.js +1 -1
  16. package/dist/raw-ordinal-warmup-worker.js +4 -4
  17. package/dist/{read-session-chunk-ksh32zfv.js → read-session-chunk-nfkemn80.js} +2 -2
  18. package/dist/{render-2qed2svq.js → render-173bqp1y.js} +5 -5
  19. package/dist/{search-archive-qqj7j1w1.js → search-archive-7snt7cyv.js} +4 -4
  20. package/dist/{search-vmw1xbqx.js → search-ea9x8vxk.js} +4 -4
  21. package/dist/{storage-tags-s0m7e39a.js → storage-tags-n8q8jk1b.js} +3 -1
  22. package/dist/subagent-entry.js +9 -9
  23. package/dist/tag-snapshot-worker-pi.js +3 -3
  24. package/dist/{v2-archive-reader-cc7sx6dk.js → v2-archive-reader-5vmwk9y5.js} +1 -1
  25. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -124,6 +124,9 @@ import {
124
124
  renderHistorianMemoryBlock,
125
125
  DEFAULT_MEMORY_BUDGET_TOKENS,
126
126
  DEFAULT_USER_PROFILE_BUDGET_TOKENS,
127
+ resolveWorkspaceRenderContext,
128
+ sourceNamesForMemories,
129
+ readM0ProjectMemories,
127
130
  trimMemoriesToBudgetV2,
128
131
  trimWorkspaceMemoriesToBudgetV2,
129
132
  trimUserMemoriesToBudget,
@@ -154,7 +157,7 @@ import {
154
157
  registerTodoStateLifecycle,
155
158
  syncCtxMemoryToolEnabled,
156
159
  registerMagicContextTools
157
- } from "./index-418za765.js";
160
+ } from "./index-1tkrgcdt.js";
158
161
  import"./index-4knyh1kt.js";
159
162
  import {
160
163
  canonicalModelIdentity,
@@ -282,6 +285,7 @@ import {
282
285
  getTriggerTagTokenUpperBound2,
283
286
  updateTagInputByteSize2,
284
287
  updateTagTokenCount2,
288
+ setTagTokenCount2,
285
289
  getPersistedToolTagAccounting2,
286
290
  getAllStatusTagTokenTotalsFlat2,
287
291
  tryGetReasoningTokenEstimatesByMessage2,
@@ -403,7 +407,7 @@ import {
403
407
  setSessionWorkMetrics,
404
408
  getSessionWorkMetrics,
405
409
  resolveEpochFloorForPass
406
- } from "./index-8gvbskcm.js";
410
+ } from "./index-7vhbmjgv.js";
407
411
  import {
408
412
  textMentionsRecentCommit,
409
413
  hasMeaningfulUserText2,
@@ -454,7 +458,7 @@ import {
454
458
  openCurrentDatabase,
455
459
  openDatabaseAsync,
456
460
  closeDatabase
457
- } from "./index-w4sqw9mf.js";
461
+ } from "./index-67q9cz3f.js";
458
462
  import {
459
463
  LkgRecoveryFenceError,
460
464
  clearLkgFenceProcessState,
@@ -581,7 +585,7 @@ import {
581
585
  getSourceContents,
582
586
  recordSubagentInvocation,
583
587
  getLatestHistorianInvocationId
584
- } from "./index-zgsemyph.js";
588
+ } from "./index-6vmpw4z3.js";
585
589
  import {
586
590
  resolveOpenCodeDbPath,
587
591
  assertOpenCodeStoreGeneration,
@@ -647,7 +651,7 @@ import {
647
651
  getRawSessionTagKeysThrough2,
648
652
  getLegacyProtectedTailStartOrdinal2,
649
653
  readSessionChunk2
650
- } from "./index-xan5mt5f.js";
654
+ } from "./index-98e27fdt.js";
651
655
  import"./index-nvh6d3bz.js";
652
656
  import {
653
657
  formatSynapseLaneDescriptor
@@ -687,7 +691,7 @@ import {
687
691
  clearCompressionDepthRange,
688
692
  cleanSearchText,
689
693
  matchedSearchSnippet
690
- } from "./index-m6kszx0e.js";
694
+ } from "./index-renfmk50.js";
691
695
  import {
692
696
  rememberV1HiddenRun
693
697
  } from "./index-6x556c2q.js";
@@ -816,7 +820,7 @@ import {
816
820
  scheduleClearAndReindex,
817
821
  clearSessionTracking,
818
822
  createAutoSearchDiagnostics
819
- } from "./index-5hhhxck7.js";
823
+ } from "./index-8328rak2.js";
820
824
  import"./index-3s39a1md.js";
821
825
  import {
822
826
  DREAMER_PRIMER_INVESTIGATOR_ALLOWED_TOOLS,
@@ -845,11 +849,11 @@ import {
845
849
  drainPiTagSnapshotSession,
846
850
  assertPiTagSnapshotReady,
847
851
  ensurePiTagSnapshotReady
848
- } from "./index-fz4gexgk.js";
852
+ } from "./index-ye6b3dr4.js";
849
853
  import"./index-71rg8j43.js";
850
854
  import"./index-8d2z6503.js";
851
- import"./index-9cqfbdgb.js";
852
- import"./index-f4n7tnsf.js";
855
+ import"./index-vkcb1cg1.js";
856
+ import"./index-hja11zte.js";
853
857
  import {
854
858
  __toESM
855
859
  } from "./index-22jkk6wg.js";
@@ -3601,7 +3605,7 @@ function startHostStallProfilerSwitch() {
3601
3605
  // package.json
3602
3606
  var package_default = {
3603
3607
  name: "@cortexkit/pi-magic-context",
3604
- version: "0.49.63",
3608
+ version: "0.49.65",
3605
3609
  type: "module",
3606
3610
  description: "Pi and OMP coding agent extension for Magic Context — cross-session memory and context management",
3607
3611
  main: "dist/index.js",
@@ -7367,11 +7371,11 @@ var USER_OBSERVATIONS_DISABLED_TOGGLE = `<user_observation_extraction>disabled</
7367
7371
  User-memory review is not running (the dreamer is disabled): do NOT emit a <user_observations> block.`;
7368
7372
  function buildCompartmentAgentPrompt(inputs) {
7369
7373
  const parts = [];
7374
+ parts.push(...readEnabledProjectMemories(inputs.memoryEnabled, () => inputs.projectMemory ? [inputs.projectMemory] : []));
7370
7375
  if (inputs.seedExamples)
7371
7376
  parts.push(inputs.seedExamples);
7372
7377
  if (inputs.sessionReferences)
7373
7378
  parts.push(inputs.sessionReferences);
7374
- parts.push(...readEnabledProjectMemories(inputs.memoryEnabled, () => inputs.projectMemory ? [inputs.projectMemory] : []));
7375
7379
  if (inputs.extractionFree) {
7376
7380
  parts.push(`<extraction>disabled</extraction>
7377
7381
  Structural recomp mode: emit compartments and <meta> only. Do NOT emit <facts>, <events>, <user_observations>, or <primer_candidates>.`);
@@ -7391,6 +7395,34 @@ Memory is disabled for this project: do NOT emit a <facts> block. Produce compar
7391
7395
 
7392
7396
  `);
7393
7397
  }
7398
+ function logHistorianPromptSizes(sessionId, system, prompt) {
7399
+ const sourceStart = prompt.indexOf(`<new_messages>
7400
+
7401
+ `);
7402
+ const sourceEnd = prompt.lastIndexOf(`
7403
+
7404
+ </new_messages>
7405
+
7406
+ ${HISTORIAN_TRANSCRIPT_GUARD}`);
7407
+ const hasSource = sourceStart !== -1 && sourceEnd > sourceStart;
7408
+ const blockBytes = (tag) => {
7409
+ if (!hasSource)
7410
+ return 0;
7411
+ const start = prompt.indexOf(`<${tag}>`);
7412
+ const close = `</${tag}>`;
7413
+ const end = prompt.indexOf(close, start + 1);
7414
+ return start >= 0 && end > start && end < sourceStart ? Buffer.byteLength(prompt.slice(start, end + close.length)) : 0;
7415
+ };
7416
+ const memoryBytes = blockBytes("project-memory");
7417
+ const seedBytes = blockBytes("compartment_examples_from_other_projects");
7418
+ const referenceBytes = blockBytes("session_references");
7419
+ const newMessageBytes = hasSource ? Buffer.byteLength(prompt.slice(sourceStart, sourceEnd + `
7420
+
7421
+ </new_messages>`.length)) : 0;
7422
+ const systemBytes = Buffer.byteLength(system);
7423
+ const userBytes = Buffer.byteLength(prompt);
7424
+ sessionLog2(sessionId, `historian request sizes: systemBytes=${systemBytes} userBytes=${userBytes} memoryBytes=${memoryBytes} seedBytes=${seedBytes} referenceBytes=${referenceBytes} newMessageBytes=${newMessageBytes}`);
7425
+ }
7394
7426
 
7395
7427
  // ../plugin/src/hooks/magic-context/compartment-runner-mapping.ts
7396
7428
  function tierFieldsOf(c) {
@@ -9463,9 +9495,9 @@ function fnv1a(input) {
9463
9495
  }
9464
9496
  return h >>> 0;
9465
9497
  }
9466
- function selectSeeds(sessionId, chunkStart, count = SEED_FLOOR) {
9498
+ function selectSeeds(sessionId, _chunkStart, count = SEED_FLOOR) {
9467
9499
  const bands = seedsByBand();
9468
- const seed = fnv1a(`${sessionId}:${chunkStart}`);
9500
+ const seed = fnv1a(sessionId);
9469
9501
  const picks = [];
9470
9502
  const bandOrder = [];
9471
9503
  for (let i = 0;i < SEED_BANDS.length; i++) {
@@ -9612,7 +9644,22 @@ function fitHistorianPrompt(args) {
9612
9644
  const requested = Math.max(0, Math.floor(args.requestedChunkTokens));
9613
9645
  const seeds = selectSeeds(args.sessionId, args.chunkStart);
9614
9646
  const references = selectSessionReferences(args.sessionCompartments, seeds, args.sessionId, args.chunkStart);
9615
- const memories = orderHistorianMemories(readEnabledProjectMemories(args.memoryEnabled, () => typeof args.memories === "function" ? args.memories() : args.memories));
9647
+ const memories = readEnabledProjectMemories(args.memoryEnabled, () => {
9648
+ const project = args.memoryProject;
9649
+ const projectPath = project?.projectPath;
9650
+ const workspace = project && resolveWorkspaceRenderContext(project);
9651
+ const rows = project ? projectPath && workspace ? readM0ProjectMemories(project.db, projectPath, workspace) : [] : (typeof args.memories === "function" ? args.memories() : args.memories) ?? [];
9652
+ const budget = args.memoryInjectionBudgetTokens ?? DEFAULT_MEMORY_BUDGET_TOKENS;
9653
+ const { selected } = workspace?.isWorkspaced ? trimWorkspaceMemoriesToBudgetV2(args.sessionId, rows, budget, workspace, {
9654
+ sourceNameByMemoryId: sourceNamesForMemories({
9655
+ memories: rows,
9656
+ projectPath,
9657
+ workspace
9658
+ })
9659
+ }) : trimMemoriesToBudgetV2(args.sessionId, rows, budget);
9660
+ const selectedIds = new Set(selected.map((memory) => memory.id));
9661
+ return orderHistorianMemories(rows.filter((memory) => selectedIds.has(memory.id)));
9662
+ });
9616
9663
  const render = (refs, memoryCount, seedCount) => ({
9617
9664
  seedExamples: renderSeedExamplesBlock(seeds.slice(0, seedCount)),
9618
9665
  sessionReferences: renderSessionReferencesBlock(references, refs),
@@ -10174,6 +10221,7 @@ async function runHistorianPrompt(args) {
10174
10221
  });
10175
10222
  if (failure)
10176
10223
  throw new Error(failure);
10224
+ logHistorianPromptSizes(parentSessionId, system, prompt);
10177
10225
  return executor.attempt(opened, request);
10178
10226
  }, { childSessionId: opened.childSessionId }),
10179
10227
  timeoutMs: timeoutMs ?? DEFAULT_HISTORIAN_TIMEOUT_MS,
@@ -26703,7 +26751,6 @@ function shouldWaitForNewHistorianHistory(snapshot, options = {}) {
26703
26751
  var PROACTIVE_TRIGGER_OFFSET_PERCENTAGE = 2;
26704
26752
  var POST_DROP_TARGET_RATIO = 0.75;
26705
26753
  var MIN_PROACTIVE_TAIL_TOKEN_ESTIMATE = 6000;
26706
- var MIN_PROACTIVE_TAIL_MESSAGE_COUNT = 12;
26707
26754
  var DEFAULT_MIN_COMMIT_CLUSTERS_FOR_TRIGGER = 3;
26708
26755
  var TAIL_SIZE_TRIGGER_MULTIPLIER = 3;
26709
26756
  var BLOCK_UNTIL_DONE_PERCENTAGE = 95;
@@ -26795,7 +26842,6 @@ var TAIL_INFO_DEFAULTS = {
26795
26842
  nextStartOrdinal: 1,
26796
26843
  hasNewRawHistory: false,
26797
26844
  hasProtectedEligibleHead: false,
26798
- isMeaningful: false,
26799
26845
  tokenEstimate: 0,
26800
26846
  chunkHasMore: false,
26801
26847
  trueRawEligibleTokens: 0,
@@ -26809,6 +26855,17 @@ function resolveBoundaryContextLimit(usage, fallbackContextLimit) {
26809
26855
  }
26810
26856
  return 128000;
26811
26857
  }
26858
+ function scanFormattedHead(db, sessionId, triggerBudget, offset, eligibleEnd) {
26859
+ const seed = sessionDecisionCalibration(db, sessionId);
26860
+ const sourceRatio = Math.max(seed.proseRatio, seed.toolsRatio);
26861
+ const scanBudget = Math.floor(Math.max(MIN_PROACTIVE_TAIL_TOKEN_ESTIMATE, triggerBudget * TAIL_SIZE_TRIGGER_MULTIPLIER) / sourceRatio);
26862
+ const chunk = readSessionChunk2(sessionId, scanBudget, offset, eligibleEnd);
26863
+ return {
26864
+ tokenEstimate: Math.ceil(chunk.tokenEstimate * sourceRatio),
26865
+ chunkHasMore: chunk.hasMore,
26866
+ commitClusterCount: chunk.commitClusterCount
26867
+ };
26868
+ }
26812
26869
  function getUnsummarizedTailInfo(db, sessionId, triggerBudget, usage, executeThresholdPercentage, contextLimit, inMemoryTail, taggerFloor = 0, liftLivePromptFloor = false) {
26813
26870
  return withRawSessionMessageCache2(() => {
26814
26871
  try {
@@ -26851,20 +26908,15 @@ function getUnsummarizedTailInfo(db, sessionId, triggerBudget, usage, executeThr
26851
26908
  boundarySnapshot: boundary
26852
26909
  };
26853
26910
  }
26854
- const seed = sessionDecisionCalibration(db, sessionId);
26855
- const sourceRatio = Math.max(seed.proseRatio, seed.toolsRatio);
26856
- const scanBudget = Math.floor(Math.max(MIN_PROACTIVE_TAIL_TOKEN_ESTIMATE, triggerBudget * TAIL_SIZE_TRIGGER_MULTIPLIER) / sourceRatio);
26857
- const chunk = readSessionChunk2(sessionId, scanBudget, rawEligibility.offset, boundary.eligibleEndOrdinal);
26858
- const isMeaningful = chunk.hasMore || boundary.trueRawEligibleTokens >= MIN_PROACTIVE_TAIL_TOKEN_ESTIMATE || Math.ceil(chunk.tokenEstimate * sourceRatio) >= MIN_PROACTIVE_TAIL_TOKEN_ESTIMATE || chunk.messageCount >= MIN_PROACTIVE_TAIL_MESSAGE_COUNT;
26911
+ const formatted = scanFormattedHead(db, sessionId, triggerBudget, rawEligibility.offset, boundary.eligibleEndOrdinal);
26912
+ const proactiveAdmission = formatted.chunkHasMore ? "has_more" : boundary.trueRawEligibleTokens >= MIN_PROACTIVE_TAIL_TOKEN_ESTIMATE ? "true_raw" : formatted.tokenEstimate >= MIN_PROACTIVE_TAIL_TOKEN_ESTIMATE ? "formatted" : undefined;
26859
26913
  return {
26860
26914
  nextStartOrdinal: rawEligibility.offset,
26861
26915
  hasNewRawHistory: true,
26862
26916
  hasProtectedEligibleHead,
26863
- isMeaningful,
26864
- tokenEstimate: Math.ceil(chunk.tokenEstimate * sourceRatio),
26865
- chunkHasMore: chunk.hasMore,
26917
+ proactiveAdmission,
26918
+ ...formatted,
26866
26919
  trueRawEligibleTokens: boundary.trueRawEligibleTokens,
26867
- commitClusterCount: chunk.commitClusterCount,
26868
26920
  boundarySnapshot: boundary
26869
26921
  };
26870
26922
  } catch (error) {
@@ -26980,8 +27032,12 @@ function checkCompartmentTrigger(db, sessionId, sessionMeta, usage, _previousPer
26980
27032
  sessionLog2(sessionId, `historian redundancy skip: summarizer not needed this pass — force band is ${forceMaterializationPercentage}%; queued/automatic drops are projected to reclaim to ${projectedPostDropPercentage.toFixed(1)}% (target ${relativePostDropTarget.toFixed(1)}%) on this pass (${rideLabel})`);
26981
27033
  return { shouldFire: false };
26982
27034
  }
26983
- sessionLog2(sessionId, `compartment trigger: force-firing at ${usage.percentage.toFixed(1)}% (projected post-drop ${formatProjectedPostDropPercentage(projectedPostDropPercentage)})`);
27035
+ const admittedBy = recovery ? "overflow_recovery" : usage.percentage >= BLOCK_UNTIL_DONE_PERCENTAGE ? "emergency_95" : "force_band";
27036
+ const logForceFire = (trueRawTokens, formattedTokens) => {
27037
+ sessionLog2(sessionId, `compartment trigger: force-firing at ${usage.percentage.toFixed(1)}% (projected post-drop ${formatProjectedPostDropPercentage(projectedPostDropPercentage)}) admittedBy=${admittedBy} trueRawTokens=${trueRawTokens} formattedTokens=${formattedTokens}`);
27038
+ };
26984
27039
  if (tailInfo.boundarySnapshot && hasRunnableCompartmentWindow(tailInfo.boundarySnapshot)) {
27040
+ logForceFire(tailInfo.trueRawEligibleTokens, tailInfo.tokenEstimate);
26985
27041
  return {
26986
27042
  shouldFire: true,
26987
27043
  reason: "force_band",
@@ -26997,7 +27053,7 @@ function checkCompartmentTrigger(db, sessionId, sessionMeta, usage, _previousPer
26997
27053
  absoluteMessageCount: resolvedInMemoryTail.absoluteMessageCount
26998
27054
  });
26999
27055
  }
27000
- return resolveOpenCodeProtectedTailBoundary({
27056
+ const boundary = resolveOpenCodeProtectedTailBoundary({
27001
27057
  db,
27002
27058
  sessionId,
27003
27059
  mode: "trigger",
@@ -27008,8 +27064,18 @@ function checkCompartmentTrigger(db, sessionId, sessionMeta, usage, _previousPer
27008
27064
  emergencyTailScale: scale,
27009
27065
  recovery
27010
27066
  });
27067
+ if (!hasRunnableCompartmentWindow(boundary))
27068
+ return null;
27069
+ let formattedTokens;
27070
+ try {
27071
+ formattedTokens = scanFormattedHead(db, sessionId, triggerBudget, boundary.offset, boundary.eligibleEndOrdinal).tokenEstimate;
27072
+ } catch {
27073
+ formattedTokens = "unavailable";
27074
+ }
27075
+ logForceFire(boundary.trueRawEligibleTokens, formattedTokens);
27076
+ return boundary;
27011
27077
  });
27012
- if (hasRunnableCompartmentWindow(scaledBoundary)) {
27078
+ if (scaledBoundary) {
27013
27079
  return { shouldFire: true, reason: "force_band", boundarySnapshot: scaledBoundary };
27014
27080
  }
27015
27081
  sessionLog2(sessionId, "compartment trigger: force_band skipped — no protected head meets summary admission after emergency tail scale");
@@ -27018,7 +27084,7 @@ function checkCompartmentTrigger(db, sessionId, sessionMeta, usage, _previousPer
27018
27084
  const clusterEnabled = commitClusterTrigger?.enabled ?? true;
27019
27085
  const minClusters = commitClusterTrigger?.min_clusters ?? DEFAULT_MIN_COMMIT_CLUSTERS_FOR_TRIGGER;
27020
27086
  if (clusterEnabled && tailInfo.commitClusterCount >= minClusters && tailInfo.tokenEstimate >= triggerBudget) {
27021
- sessionLog2(sessionId, `compartment trigger: commit-cluster fire — ${tailInfo.commitClusterCount} clusters (min=${minClusters}), ~${tailInfo.tokenEstimate} tokens in eligible prefix`);
27087
+ sessionLog2(sessionId, `compartment trigger: commit-cluster fire — ${tailInfo.commitClusterCount} clusters (min=${minClusters}) admittedBy=commit_clusters trueRawTokens=${tailInfo.trueRawEligibleTokens} formattedTokens=${tailInfo.tokenEstimate}`);
27022
27088
  return {
27023
27089
  shouldFire: true,
27024
27090
  reason: "commit_clusters",
@@ -27026,7 +27092,8 @@ function checkCompartmentTrigger(db, sessionId, sessionMeta, usage, _previousPer
27026
27092
  };
27027
27093
  }
27028
27094
  if (tailInfo.tokenEstimate >= triggerBudget * TAIL_SIZE_TRIGGER_MULTIPLIER || tailInfo.chunkHasMore && tailInfo.tokenEstimate > 0) {
27029
- sessionLog2(sessionId, `compartment trigger: tail-size fire — ~${tailInfo.tokenEstimate} TC-chunked tokens (hasMore=${tailInfo.chunkHasMore}, true-raw ~${tailInfo.trueRawEligibleTokens}) exceeds ${triggerBudget * TAIL_SIZE_TRIGGER_MULTIPLIER} budget threshold`);
27095
+ const admittedBy = tailInfo.chunkHasMore ? "has_more" : "formatted";
27096
+ sessionLog2(sessionId, `compartment trigger: tail-size fire — budget threshold ${triggerBudget * TAIL_SIZE_TRIGGER_MULTIPLIER} admittedBy=${admittedBy} trueRawTokens=${tailInfo.trueRawEligibleTokens} formattedTokens=${tailInfo.tokenEstimate}`);
27030
27097
  return {
27031
27098
  shouldFire: true,
27032
27099
  reason: "tail_size",
@@ -27042,13 +27109,13 @@ function checkCompartmentTrigger(db, sessionId, sessionMeta, usage, _previousPer
27042
27109
  sessionLog2(sessionId, `historian redundancy skip: summarizer not needed this pass — usage is ${usage.percentage.toFixed(1)}%; queued/automatic drops are projected to reclaim to ${projectedPostDropPercentage.toFixed(1)}% (target ${relativePostDropTarget.toFixed(1)}%) on this pass (${rideLabel})`);
27043
27110
  return { shouldFire: false };
27044
27111
  }
27045
- if (!tailInfo.hasProtectedEligibleHead || !tailInfo.isMeaningful) {
27112
+ if (!tailInfo.hasProtectedEligibleHead || !tailInfo.proactiveAdmission) {
27046
27113
  let floorOnly = false;
27047
27114
  const boundary = tailInfo.boundarySnapshot;
27048
27115
  const floor = boundary?.diagnostics?.livePromptFloor;
27049
27116
  if (!consumedFloorMark && floor?.ordinal && floor.from > floor.to) {
27050
27117
  const withoutFloor = getUnsummarizedTailInfo(db, sessionId, triggerBudget, usage, executeThresholdPercentage, contextLimit, resolvedInMemoryTail, taggerFloor, true);
27051
- floorOnly = withoutFloor.hasProtectedEligibleHead && withoutFloor.isMeaningful;
27118
+ floorOnly = withoutFloor.hasProtectedEligibleHead && withoutFloor.proactiveAdmission !== undefined;
27052
27119
  if (floorOnly && primaryExecute && usage.percentage >= executeThresholdPercentage && writeExecuteReclaimState(db, sessionId, {
27053
27120
  floorOrdinal: floor.ordinal,
27054
27121
  floorPromptId: floor.messageId ?? null
@@ -27060,7 +27127,7 @@ function checkCompartmentTrigger(db, sessionId, sessionMeta, usage, _previousPer
27060
27127
  sessionLog2(sessionId, `compartment trigger: not firing at ${usage.percentage.toFixed(1)}% — ${refusal}; offset=${tailInfo.nextStartOrdinal} protectedStart=${boundary?.protectedTailStart ?? "none"} eligibleEnd=${boundary?.eligibleEndOrdinal ?? "none"} rawTokens=${tailInfo.trueRawEligibleTokens} chunkTokens=${tailInfo.tokenEstimate}`);
27061
27128
  return { shouldFire: false };
27062
27129
  }
27063
- sessionLog2(sessionId, `compartment trigger: proactive fire at ${usage.percentage.toFixed(1)}% (floor=${proactiveTriggerPercentage}% projected post-drop=${formatProjectedPostDropPercentage(projectedPostDropPercentage)} target=${relativePostDropTarget.toFixed(1)}%)`);
27130
+ sessionLog2(sessionId, `compartment trigger: proactive fire at ${usage.percentage.toFixed(1)}% (floor=${proactiveTriggerPercentage}% projected post-drop=${formatProjectedPostDropPercentage(projectedPostDropPercentage)} target=${relativePostDropTarget.toFixed(1)}%) admittedBy=${tailInfo.proactiveAdmission} trueRawTokens=${tailInfo.trueRawEligibleTokens} formattedTokens=${tailInfo.tokenEstimate}`);
27064
27131
  return {
27065
27132
  shouldFire: true,
27066
27133
  reason: "projected_headroom",
@@ -28857,6 +28924,9 @@ function tagTranscript(sessionId, transcript, tagger, db, options = {}) {
28857
28924
  timing.identity += performance.now() - identityStart;
28858
28925
  }
28859
28926
  existing.identityReusable &&= reuseIdentity;
28927
+ if (part.kind === "tool_result") {
28928
+ noteResultBlock(existing, part, text, tokenCacheKey);
28929
+ }
28860
28930
  applyToolPrefixAndTarget({
28861
28931
  skipPrefixInjection,
28862
28932
  part,
@@ -28885,6 +28955,8 @@ function tagTranscript(sessionId, transcript, tagger, db, options = {}) {
28885
28955
  occurrences: [{ message, part, kind: part.kind }],
28886
28956
  maxByteSize: reusableAccounting.byteSize,
28887
28957
  maxTokenCount: reusableAccounting.tokenCount ?? 0,
28958
+ resultImageTokens: 0,
28959
+ resultTexts: [],
28888
28960
  toolName: null,
28889
28961
  inputByteSize: reusableAccounting.inputByteSize,
28890
28962
  inputTokenCount: reusableAccounting.inputTokenCount,
@@ -28926,6 +28998,8 @@ function tagTranscript(sessionId, transcript, tagger, db, options = {}) {
28926
28998
  occurrences: [{ message, part, kind: part.kind }],
28927
28999
  maxByteSize: persistedAccounting?.byteSize ?? outputByteSize,
28928
29000
  maxTokenCount: persistedAccounting?.tokenCount ?? outputTokenCount,
29001
+ resultImageTokens: 0,
29002
+ resultTexts: [],
28929
29003
  toolName: accounting.toolName,
28930
29004
  inputByteSize: persistedAccounting?.inputByteSize ?? (part.kind === "tool_use" ? accounting.inputByteSize : 0),
28931
29005
  inputTokenCount: persistedAccounting?.inputTokenCount ?? (part.kind === "tool_use" ? firstInputTokenCount : null),
@@ -28951,6 +29025,8 @@ function tagTranscript(sessionId, transcript, tagger, db, options = {}) {
28951
29025
  toolAggregates.set(aggregateKey, aggregate);
28952
29026
  if (part.kind === "tool_use") {
28953
29027
  openToolAggregateKeysByCallId.set(callId, [...pendingKeys, aggregateKey]);
29028
+ } else {
29029
+ noteResultBlock(aggregate, part, text, tokenCacheKey);
28954
29030
  }
28955
29031
  applyToolPrefixAndTarget({
28956
29032
  skipPrefixInjection,
@@ -28969,6 +29045,16 @@ function tagTranscript(sessionId, transcript, tagger, db, options = {}) {
28969
29045
  }
28970
29046
  }
28971
29047
  }
29048
+ for (const aggregate of toolAggregates.values()) {
29049
+ applyImageResultAccounting({
29050
+ db,
29051
+ sessionId,
29052
+ tagger,
29053
+ aggregate,
29054
+ timing,
29055
+ tokenCache: options.toolTokenCache
29056
+ });
29057
+ }
28972
29058
  if (timing && options.onTiming) {
28973
29059
  options.onTiming("identity", timing.identity);
28974
29060
  options.onTiming("prefix", timing.prefix);
@@ -29000,10 +29086,36 @@ function applyGrownToolResultAccounting(args) {
29000
29086
  }
29001
29087
  args.aggregate.maxByteSize = args.byteSize;
29002
29088
  args.aggregate.maxTokenCount = tokenCount;
29089
+ args.aggregate.tokenCountGrewThisPass = true;
29003
29090
  updateTagByteSize2(args.db, args.sessionId, args.aggregate.tagId, args.byteSize);
29004
29091
  updateTagTokenCount2(args.db, args.sessionId, args.aggregate.tagId, tokenCount);
29005
29092
  syncToolAggregateAccounting(args.tagger, args.sessionId, args.aggregate);
29006
29093
  }
29094
+ function noteResultBlock(aggregate, part, text, tokenCacheKey) {
29095
+ const imageTokens = part.imageTokens?.() ?? 0;
29096
+ if (imageTokens > 0)
29097
+ aggregate.resultImageTokens += imageTokens;
29098
+ else if (text.length > 0)
29099
+ aggregate.resultTexts.push({ part, text, tokenCacheKey });
29100
+ }
29101
+ function applyImageResultAccounting(args) {
29102
+ const { aggregate } = args;
29103
+ if (aggregate.resultImageTokens === 0)
29104
+ return;
29105
+ const tokenStart = args.timing ? performance.now() : 0;
29106
+ let textTokens = 0;
29107
+ for (const block of aggregate.resultTexts) {
29108
+ textTokens = Math.max(textTokens, getCachedToolPartTokenCount(block.part, block.text, args.tokenCache, block.tokenCacheKey));
29109
+ }
29110
+ if (args.timing)
29111
+ args.timing.tokenCounting += performance.now() - tokenStart;
29112
+ const tokenCount = textTokens + aggregate.resultImageTokens;
29113
+ if (tokenCount === aggregate.maxTokenCount && !aggregate.tokenCountGrewThisPass)
29114
+ return;
29115
+ aggregate.maxTokenCount = tokenCount;
29116
+ setTagTokenCount2(args.db, args.sessionId, aggregate.tagId, tokenCount);
29117
+ syncToolAggregateAccounting(args.tagger, args.sessionId, aggregate);
29118
+ }
29007
29119
  function readAggregateToolAccounting(part, timing, tokenCache, tokenCacheKey, persisted) {
29008
29120
  const text = part.getText() ?? "";
29009
29121
  const byteSize = getToolPartByteSize(part, text);
@@ -29109,6 +29221,9 @@ function getToolPartByteSize(part, text) {
29109
29221
  function getToolPartTokenCount(part, text) {
29110
29222
  if (text.length > 0 || part.kind !== "tool_result")
29111
29223
  return estimateTokens(text);
29224
+ const imageTokens = part.imageTokens?.() ?? 0;
29225
+ if (imageTokens > 0)
29226
+ return imageTokens;
29112
29227
  const raw = part.rawByteSize?.();
29113
29228
  if (typeof raw === "number" && raw > 0) {
29114
29229
  const record = isRecord2(part) ? part : undefined;
@@ -30585,37 +30700,6 @@ function persistFilteredNoise(db, sessionId, chunk, eligibleEnd) {
30585
30700
  return saved;
30586
30701
  }
30587
30702
 
30588
- // src/pi-history-retirement.ts
30589
- var KEY2 = "piHistorianRetirement";
30590
- function readState2(db, sessionId) {
30591
- const row = db.prepare("SELECT deferred_execute_state AS state FROM session_meta WHERE session_id = ?").get(sessionId);
30592
- const state = row?.state ? JSON.parse(row.state) : {};
30593
- if (!state || typeof state !== "object" || Array.isArray(state))
30594
- throw new Error("Invalid session metadata JSON");
30595
- return state;
30596
- }
30597
- function readPiHistoryRetirement(db, sessionId) {
30598
- const target = readState2(db, sessionId)[KEY2];
30599
- return typeof target === "string" && target.length > 0 ? target : null;
30600
- }
30601
- function queuePiHistoryRetirement(db, sessionId, throughMessageId) {
30602
- ensureSessionMetaRow(db, sessionId);
30603
- const state = readState2(db, sessionId);
30604
- state[KEY2] = throughMessageId;
30605
- db.prepare("UPDATE session_meta SET deferred_execute_state = ? WHERE session_id = ?").run(JSON.stringify(state), sessionId);
30606
- }
30607
- function acknowledgePiHistoryRetirement(db, sessionId, publishedEnd, ordinalOf) {
30608
- const state = readState2(db, sessionId);
30609
- const target = state[KEY2];
30610
- if (typeof target !== "string")
30611
- return;
30612
- const ordinal = ordinalOf(target);
30613
- if (ordinal === undefined || ordinal > publishedEnd)
30614
- return;
30615
- delete state[KEY2];
30616
- db.prepare("UPDATE session_meta SET deferred_execute_state = ? WHERE session_id = ?").run(JSON.stringify(state), sessionId);
30617
- }
30618
-
30619
30703
  // src/system-entry-pi.ts
30620
30704
  function isPiSystemEntry(message) {
30621
30705
  return message !== null && typeof message === "object" && "role" in message && message.role === "system";
@@ -30764,6 +30848,198 @@ function adoptPiCompactionSystemSnapshot(messages, entries, compactionId, foldin
30764
30848
  }
30765
30849
  }
30766
30850
 
30851
+ // src/pi-history-cut.ts
30852
+ function isPiContextEmitEligible(entry) {
30853
+ if (!entry || typeof entry !== "object")
30854
+ return false;
30855
+ const row = entry;
30856
+ if (typeof row.id !== "string")
30857
+ return false;
30858
+ return row.type === "message" || row.type === "custom_message" || row.type === "branch_summary" && typeof row.summary === "string" && row.summary.length > 0;
30859
+ }
30860
+ function piCutMessageForEntry(entry) {
30861
+ if (!isPiContextEmitEligible(entry))
30862
+ return;
30863
+ const row = entry;
30864
+ if (row.type === "custom_message")
30865
+ return { role: "custom" };
30866
+ if (row.type === "branch_summary")
30867
+ return { role: "branchSummary" };
30868
+ return row.message && typeof row.message === "object" ? row.message : undefined;
30869
+ }
30870
+ function planPiHistoryCut(messages, cutoffIndex, promptReachesBoundary) {
30871
+ const remove = new Set;
30872
+ for (let i = 0;i <= cutoffIndex; i++) {
30873
+ if (!isPiSystemEntry(messages[i]))
30874
+ remove.add(i);
30875
+ }
30876
+ let changed = true;
30877
+ while (changed) {
30878
+ changed = false;
30879
+ const removedCallKeys = new Set;
30880
+ const removedResultKeys = new Set;
30881
+ for (const index of remove) {
30882
+ const msg = messages[index];
30883
+ if (!msg)
30884
+ continue;
30885
+ if (msg.role === "assistant") {
30886
+ for (const callId of getPiToolCallIds(msg)) {
30887
+ removedCallKeys.add(toolPairKey(callId, index));
30888
+ }
30889
+ } else if (msg.role === "toolResult") {
30890
+ const callId = getPiToolResultCallId(msg);
30891
+ const ownerIndex = callId ? findToolResultOwnerAssistantIndex(messages, index, callId) : null;
30892
+ if (callId && ownerIndex !== null) {
30893
+ removedResultKeys.add(toolPairKey(callId, ownerIndex));
30894
+ }
30895
+ }
30896
+ }
30897
+ for (let i = 0;i < messages.length; i++) {
30898
+ if (remove.has(i))
30899
+ continue;
30900
+ const msg = messages[i];
30901
+ if (!msg)
30902
+ continue;
30903
+ if (msg.role === "toolResult") {
30904
+ const callId = getPiToolResultCallId(msg);
30905
+ const ownerIndex = callId ? findToolResultOwnerAssistantIndex(messages, i, callId) : null;
30906
+ if (callId && ownerIndex !== null && removedCallKeys.has(toolPairKey(callId, ownerIndex))) {
30907
+ remove.add(i);
30908
+ changed = true;
30909
+ }
30910
+ continue;
30911
+ }
30912
+ if (msg.role === "assistant") {
30913
+ const callIds = getPiToolCallIds(msg);
30914
+ if (callIds.some((callId) => removedResultKeys.has(toolPairKey(callId, i)))) {
30915
+ remove.add(i);
30916
+ changed = true;
30917
+ }
30918
+ }
30919
+ }
30920
+ }
30921
+ const keptPrompt = keptPromptIndex(messages, cutoffIndex, remove, promptReachesBoundary);
30922
+ if (keptPrompt >= 0)
30923
+ remove.delete(keptPrompt);
30924
+ return remove;
30925
+ }
30926
+ function firstMessageKeptByPiHistoryCut(messages, remove) {
30927
+ for (let i = 0;i < messages.length; i++) {
30928
+ if (!remove.has(i) && !isPiSystemEntry(messages[i]))
30929
+ return i;
30930
+ }
30931
+ return -1;
30932
+ }
30933
+ function resolvePiMarkerKeptEntry(branchEntries, endMessageId) {
30934
+ const boundaryId = endMessageId.startsWith(SYNTH_USER_ID_PREFIX) ? endMessageId.slice(SYNTH_USER_ID_PREFIX.length) : endMessageId;
30935
+ if (boundaryId.length === 0)
30936
+ return { kind: "missing" };
30937
+ const messages = [];
30938
+ const ids = [];
30939
+ for (const entry of branchEntries) {
30940
+ const message = piCutMessageForEntry(entry);
30941
+ const id = entry.id;
30942
+ if (!message || id.length === 0)
30943
+ continue;
30944
+ messages.push(message);
30945
+ ids.push(id);
30946
+ }
30947
+ const cutoffIndex = ids.indexOf(boundaryId);
30948
+ if (cutoffIndex < 0)
30949
+ return { kind: "missing" };
30950
+ if (!messages.slice(cutoffIndex + 1).some((m) => !isPiSystemEntry(m)))
30951
+ return { kind: "waiting" };
30952
+ const kept = firstMessageKeptByPiHistoryCut(messages, planPiHistoryCut(messages, cutoffIndex));
30953
+ return kept < 0 ? { kind: "waiting" } : { kind: "resolved", entryId: ids[kept] };
30954
+ }
30955
+ function keptPromptIndex(messages, cutoffIndex, removed, promptReachesBoundary) {
30956
+ let promptIndex = -1;
30957
+ for (let i = cutoffIndex;i >= 0; i--) {
30958
+ if (messages[i]?.role === "user") {
30959
+ promptIndex = i;
30960
+ break;
30961
+ }
30962
+ }
30963
+ if (promptIndex < 0)
30964
+ return -1;
30965
+ for (let i = cutoffIndex + 1;i < messages.length; i++) {
30966
+ if (removed.has(i))
30967
+ continue;
30968
+ const message = messages[i];
30969
+ if (message?.role === "user")
30970
+ return -1;
30971
+ if (message?.role === "assistant" && message.stopReason !== "error")
30972
+ break;
30973
+ }
30974
+ if (promptReachesBoundary && !promptReachesBoundary(promptIndex))
30975
+ return -1;
30976
+ return promptIndex;
30977
+ }
30978
+ function toolPairKey(callId, assistantIndex) {
30979
+ return `${callId}\x00${assistantIndex}`;
30980
+ }
30981
+ function findToolResultOwnerAssistantIndex(messages, resultIndex, callId) {
30982
+ for (let i = resultIndex - 1;i >= 0; i--) {
30983
+ const msg = messages[i];
30984
+ if (msg?.role === "assistant" && getPiToolCallIds(msg).includes(callId)) {
30985
+ return i;
30986
+ }
30987
+ }
30988
+ for (let i = resultIndex + 1;i < messages.length; i++) {
30989
+ const msg = messages[i];
30990
+ if (msg?.role === "assistant" && getPiToolCallIds(msg).includes(callId)) {
30991
+ return i;
30992
+ }
30993
+ }
30994
+ return null;
30995
+ }
30996
+ function getPiToolCallIds(message) {
30997
+ if (!Array.isArray(message.content))
30998
+ return [];
30999
+ const ids = [];
31000
+ for (const part of message.content) {
31001
+ if (part && typeof part === "object" && part.type === "toolCall" && typeof part.id === "string") {
31002
+ ids.push(part.id);
31003
+ }
31004
+ }
31005
+ return ids;
31006
+ }
31007
+ function getPiToolResultCallId(message) {
31008
+ const callId = message.toolCallId;
31009
+ return typeof callId === "string" && callId.length > 0 ? callId : null;
31010
+ }
31011
+
31012
+ // src/pi-history-retirement.ts
31013
+ var KEY2 = "piHistorianRetirement";
31014
+ function readState2(db, sessionId) {
31015
+ const row = db.prepare("SELECT deferred_execute_state AS state FROM session_meta WHERE session_id = ?").get(sessionId);
31016
+ const state = row?.state ? JSON.parse(row.state) : {};
31017
+ if (!state || typeof state !== "object" || Array.isArray(state))
31018
+ throw new Error("Invalid session metadata JSON");
31019
+ return state;
31020
+ }
31021
+ function readPiHistoryRetirement(db, sessionId) {
31022
+ const target = readState2(db, sessionId)[KEY2];
31023
+ return typeof target === "string" && target.length > 0 ? target : null;
31024
+ }
31025
+ function queuePiHistoryRetirement(db, sessionId, throughMessageId) {
31026
+ ensureSessionMetaRow(db, sessionId);
31027
+ const state = readState2(db, sessionId);
31028
+ state[KEY2] = throughMessageId;
31029
+ db.prepare("UPDATE session_meta SET deferred_execute_state = ? WHERE session_id = ?").run(JSON.stringify(state), sessionId);
31030
+ }
31031
+ function acknowledgePiHistoryRetirement(db, sessionId, publishedEnd, ordinalOf) {
31032
+ const state = readState2(db, sessionId);
31033
+ const target = state[KEY2];
31034
+ if (typeof target !== "string")
31035
+ return;
31036
+ const ordinal = ordinalOf(target);
31037
+ if (ordinal === undefined || ordinal > publishedEnd)
31038
+ return;
31039
+ delete state[KEY2];
31040
+ db.prepare("UPDATE session_meta SET deferred_execute_state = ? WHERE session_id = ?").run(JSON.stringify(state), sessionId);
31041
+ }
31042
+
30767
31043
  // src/pi-historian-runner.ts
30768
31044
  var HISTORIAN_AGENT_NAME = "magic-context-historian";
30769
31045
  var DEFAULT_HISTORIAN_TIMEOUT_MS2 = 600000;
@@ -30844,6 +31120,7 @@ async function runHistorianSubagentWithTransientRetriesGuarded(args) {
30844
31120
  if (failure)
30845
31121
  throw new Error(failure);
30846
31122
  args.onDispatch?.();
31123
+ logHistorianPromptSizes(args.sessionId, args.options.systemPrompt, args.options.userMessage);
30847
31124
  result = await args.runner.run({
30848
31125
  ...args.options,
30849
31126
  cacheTail: retryIndex > 0 ? "write" : args.options.cacheTail ?? "skip",
@@ -31148,7 +31425,8 @@ async function runPiHistorian(deps) {
31148
31425
  chunkStart: Math.max(1, offset),
31149
31426
  lastOrdinal: eligibleEndOrdinal - 1,
31150
31427
  sessionCompartments: priorCompartments,
31151
- memories: () => projectPath ? getMemoriesByProject2(db, projectPath, ["active", "permanent"]) : [],
31428
+ memoryProject: { db, projectPath: projectPath ?? undefined },
31429
+ memoryInjectionBudgetTokens: deps.memoryInjectionBudgetTokens,
31152
31430
  memoryEnabled: memoryEnabled !== false,
31153
31431
  userObservationsRequested
31154
31432
  });
@@ -31260,6 +31538,9 @@ async function runPiHistorian(deps) {
31260
31538
  if (chunkText !== chunk.text) {
31261
31539
  sessionLog2(sessionId, `historian pre-flight: truncated formatted input for ${chunk.startIndex}-${chunk.endIndex} to fit ${chunkTokens} tokens`);
31262
31540
  }
31541
+ if (deps.recoveryTriggerReason) {
31542
+ sessionLog2(sessionId, `historian recovery fire: admittedBy=${deps.recoveryTriggerReason} trueRawTokens=${boundarySnapshot.trueRawEligibleTokens} formattedChunkTokens=${chunk.tokenEstimate}`);
31543
+ }
31263
31544
  const prompt = buildCompartmentAgentPrompt({
31264
31545
  seedExamples: promptFit.seedExamples,
31265
31546
  sessionReferences: promptFit.sessionReferences,
@@ -31487,9 +31768,7 @@ ${chunkText}`,
31487
31768
  let firstKeptEntryId = null;
31488
31769
  if (readBranchEntries) {
31489
31770
  try {
31490
- const branchEntries = readBranchEntries();
31491
- const alignment = resolvePiOrdinalAlignment(db, sessionId, branchEntries);
31492
- firstKeptEntryId = isPiOrdinalAlignmentUnanchored(alignment) ? null : findFirstKeptEntryId(branchEntries, lastNewEnd, alignment.offset);
31771
+ firstKeptEntryId = lastNewEndMessageId ? placePiMarkerKeptEntry(db, sessionId, readBranchEntries(), lastNewEndMessageId, lastNewEnd) : null;
31493
31772
  if (!firstKeptEntryId) {
31494
31773
  sessionLog2(sessionId, `historian: native compaction marker waiting; no resolvable firstKeptEntryId at or after ordinal ${lastNewEnd + 1}`);
31495
31774
  }
@@ -31801,6 +32080,17 @@ function buildPiCompactionSummary(compartments) {
31801
32080
  const shown = titles.slice(0, MAX_SUMMARY_TITLES).join("; ");
31802
32081
  return `Magic Context compacted ${titles.length} segments: ${shown}; …and ${titles.length - MAX_SUMMARY_TITLES} more`;
31803
32082
  }
32083
+ function placePiMarkerKeptEntry(db, sessionId, branchEntries, endMessageId, endOrdinal) {
32084
+ const alignment = resolvePiOrdinalAlignment(db, sessionId, branchEntries);
32085
+ if (isPiOrdinalAlignmentUnanchored(alignment))
32086
+ return null;
32087
+ const kept = resolvePiMarkerKeptEntry(branchEntries, endMessageId);
32088
+ if (kept.kind === "resolved")
32089
+ return kept.entryId;
32090
+ if (kept.kind === "waiting")
32091
+ return null;
32092
+ return findFirstKeptEntryId(branchEntries, endOrdinal, alignment.offset);
32093
+ }
31804
32094
  function findFirstKeptEntryId(entries, lastCompactedOrdinal, ordinalOffset = 0) {
31805
32095
  const boundary = resolvePiFirstKeptEntry(entries, lastCompactedOrdinal, ordinalOffset);
31806
32096
  return boundary.kind === "resolved" ? boundary.entryId : null;
@@ -31913,7 +32203,13 @@ function applyDeferredPiCompactionMarker(deps, sessionId, pending) {
31913
32203
  }
31914
32204
  const branchEntries = deps.readBranchEntries();
31915
32205
  let firstKeptEntryId = pending.firstKeptEntryId;
31916
- if (!firstKeptEntryId) {
32206
+ let placedByCut = false;
32207
+ const kept = resolvePiMarkerKeptEntry(branchEntries, pending.endMessageId);
32208
+ if (kept.kind !== "missing" && !isPiOrdinalAlignmentUnanchored(resolvePiOrdinalAlignment(deps.db, sessionId, branchEntries))) {
32209
+ placedByCut = true;
32210
+ firstKeptEntryId = kept.kind === "resolved" ? kept.entryId : null;
32211
+ }
32212
+ if (!placedByCut && !firstKeptEntryId) {
31917
32213
  const alignment = resolvePiOrdinalAlignment(deps.db, sessionId, branchEntries);
31918
32214
  if (isPiOrdinalAlignmentUnanchored(alignment)) {
31919
32215
  if (alignment.kind === "unanchored" && alignment.reason === "anchor-missing" && hasMergedSyntheticBoundary(branchEntries, pending.endMessageId)) {
@@ -34945,64 +35241,10 @@ function trimPiMessagesToBoundary(piMessages, entryIds, cutoffMessageId, trimMut
34945
35241
  }
34946
35242
  if (cutoffIndex < 0)
34947
35243
  return 0;
34948
- const remove = new Set;
34949
- let preserved = 0;
34950
- for (let i = 0;i <= cutoffIndex; i++) {
34951
- if (isPiSystemEntry(piMessages[i]))
34952
- preserved++;
34953
- else
34954
- remove.add(i);
34955
- }
35244
+ const preserved = piMessages.slice(0, cutoffIndex + 1).filter((message) => isPiSystemEntry(message)).length;
34956
35245
  if (preserved > 0)
34957
35246
  sessionLog2(sessionId ?? "unknown", `pi system entries preserved across fold: ${preserved}`);
34958
- let changed = true;
34959
- while (changed) {
34960
- changed = false;
34961
- const removedCallKeys = new Set;
34962
- const removedResultKeys = new Set;
34963
- for (const index of remove) {
34964
- const msg = piMessages[index];
34965
- if (!msg)
34966
- continue;
34967
- if (msg.role === "assistant") {
34968
- for (const callId of getPiToolCallIds(msg)) {
34969
- removedCallKeys.add(toolPairKey(callId, index));
34970
- }
34971
- } else if (msg.role === "toolResult") {
34972
- const callId = getPiToolResultCallId(msg);
34973
- const ownerIndex = callId ? findToolResultOwnerAssistantIndex(piMessages, index, callId) : null;
34974
- if (callId && ownerIndex !== null) {
34975
- removedResultKeys.add(toolPairKey(callId, ownerIndex));
34976
- }
34977
- }
34978
- }
34979
- for (let i = 0;i < piMessages.length; i++) {
34980
- if (remove.has(i))
34981
- continue;
34982
- const msg = piMessages[i];
34983
- if (!msg)
34984
- continue;
34985
- if (msg.role === "toolResult") {
34986
- const callId = getPiToolResultCallId(msg);
34987
- const ownerIndex = callId ? findToolResultOwnerAssistantIndex(piMessages, i, callId) : null;
34988
- if (callId && ownerIndex !== null && removedCallKeys.has(toolPairKey(callId, ownerIndex))) {
34989
- remove.add(i);
34990
- changed = true;
34991
- }
34992
- continue;
34993
- }
34994
- if (msg.role === "assistant") {
34995
- const callIds = getPiToolCallIds(msg);
34996
- if (callIds.some((callId) => removedResultKeys.has(toolPairKey(callId, i)))) {
34997
- remove.add(i);
34998
- changed = true;
34999
- }
35000
- }
35001
- }
35002
- }
35003
- const keptPrompt = keptPromptIndex(piMessages, cutoffIndex, remove, promptReachesBoundary);
35004
- if (keptPrompt >= 0)
35005
- remove.delete(keptPrompt);
35247
+ const remove = planPiHistoryCut(piMessages, cutoffIndex, promptReachesBoundary);
35006
35248
  const retiredIds = new Set;
35007
35249
  if (retireDecisions) {
35008
35250
  for (const index of remove) {
@@ -35083,29 +35325,6 @@ function placeCutByBranchPosition(piMessages, entryIds, cutoffMessageId, session
35083
35325
  }
35084
35326
  };
35085
35327
  }
35086
- function keptPromptIndex(piMessages, cutoffIndex, removed, promptReachesBoundary) {
35087
- let promptIndex = -1;
35088
- for (let i = cutoffIndex;i >= 0; i--) {
35089
- if (piMessages[i]?.role === "user") {
35090
- promptIndex = i;
35091
- break;
35092
- }
35093
- }
35094
- if (promptIndex < 0)
35095
- return -1;
35096
- for (let i = cutoffIndex + 1;i < piMessages.length; i++) {
35097
- if (removed.has(i))
35098
- continue;
35099
- const message = piMessages[i];
35100
- if (message?.role === "user")
35101
- return -1;
35102
- if (message?.role === "assistant" && message.stopReason !== "error")
35103
- break;
35104
- }
35105
- if (promptReachesBoundary && !promptReachesBoundary(promptIndex))
35106
- return -1;
35107
- return promptIndex;
35108
- }
35109
35328
  var idCutBoundaryByMessages = new WeakMap;
35110
35329
  var unplacedCutLoggedSessions = new Set;
35111
35330
  function resetPiUnplacedCutLog(sessionId) {
@@ -35117,39 +35336,6 @@ function logUnplacedCut(sessionId, boundaryMessageId, eventLength, reason, first
35117
35336
  unplacedCutLoggedSessions.add(sessionId);
35118
35337
  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`);
35119
35338
  }
35120
- function toolPairKey(callId, assistantIndex) {
35121
- return `${callId}\x00${assistantIndex}`;
35122
- }
35123
- function findToolResultOwnerAssistantIndex(messages, resultIndex, callId) {
35124
- for (let i = resultIndex - 1;i >= 0; i--) {
35125
- const msg = messages[i];
35126
- if (msg?.role === "assistant" && getPiToolCallIds(msg).includes(callId)) {
35127
- return i;
35128
- }
35129
- }
35130
- for (let i = resultIndex + 1;i < messages.length; i++) {
35131
- const msg = messages[i];
35132
- if (msg?.role === "assistant" && getPiToolCallIds(msg).includes(callId)) {
35133
- return i;
35134
- }
35135
- }
35136
- return null;
35137
- }
35138
- function getPiToolCallIds(message) {
35139
- if (!Array.isArray(message.content))
35140
- return [];
35141
- const ids = [];
35142
- for (const part of message.content) {
35143
- if (part && typeof part === "object" && part.type === "toolCall" && typeof part.id === "string") {
35144
- ids.push(part.id);
35145
- }
35146
- }
35147
- return ids;
35148
- }
35149
- function getPiToolResultCallId(message) {
35150
- const callId = message.toolCallId;
35151
- return typeof callId === "string" && callId.length > 0 ? callId : null;
35152
- }
35153
35339
  var PI_M1_PLACEHOLDER = "<session-history-since>(no new content since last materialization)</session-history-since>";
35154
35340
  var MAX_FORCED_MEMORIES_PER_DELTA = 10;
35155
35341
  var PI_M0_UPGRADE_STATE = "pi-m0m1-v2";
@@ -43550,6 +43736,160 @@ function safeJsonStringify2(value) {
43550
43736
  }
43551
43737
  }
43552
43738
 
43739
+ // src/strip-processed-images-pi.ts
43740
+ var STRIPPED_IMAGE_MARKER = "[image stripped]";
43741
+ function isLargeImagePart(value) {
43742
+ if (!value || typeof value !== "object")
43743
+ return false;
43744
+ const part = value;
43745
+ return part.type === "image" && typeof part.mimeType === "string" && part.mimeType.startsWith("image/") && typeof part.data === "string" && part.data.length > 200;
43746
+ }
43747
+ var PI_NON_VISION_TOOL_IMAGE_PLACEHOLDER = "(tool image omitted: model does not support images)";
43748
+ var PI_NON_VISION_USER_IMAGE_PLACEHOLDER = "(image omitted: model does not support images)";
43749
+ function piModelAcceptsImages(model) {
43750
+ const input = model?.input;
43751
+ return !Array.isArray(input) || input.includes("image");
43752
+ }
43753
+ function piImageWirePlaceholder(args) {
43754
+ if (args.block?.type !== "image")
43755
+ return;
43756
+ if (args.stripped && isLargeImagePart(args.block))
43757
+ return STRIPPED_IMAGE_MARKER;
43758
+ if (!args.modelAcceptsImages)
43759
+ return args.role === "toolResult" ? PI_NON_VISION_TOOL_IMAGE_PLACEHOLDER : PI_NON_VISION_USER_IMAGE_PLACEHOLDER;
43760
+ return;
43761
+ }
43762
+ function piToolImageWireTokens(args) {
43763
+ const placeholder = piImageWirePlaceholder({ ...args, role: "toolResult" });
43764
+ return placeholder === undefined ? PI_IMAGE_TOKENS : estimateTokens(placeholder);
43765
+ }
43766
+ function piMessagesWithWireImages(messages, args) {
43767
+ if (args.modelAcceptsImages && !args.strippedMessage)
43768
+ return messages;
43769
+ let changed = false;
43770
+ const sent = messages.map((raw, index) => {
43771
+ const message = raw;
43772
+ if (!message || typeof message !== "object")
43773
+ return raw;
43774
+ const content = message.content;
43775
+ if (!Array.isArray(content))
43776
+ return raw;
43777
+ let stripped;
43778
+ let replaced;
43779
+ for (let partIndex = 0;partIndex < content.length; partIndex++) {
43780
+ const block = content[partIndex];
43781
+ if (block?.type !== "image")
43782
+ continue;
43783
+ stripped ??= args.strippedMessage?.(raw, index) ?? false;
43784
+ const placeholder = piImageWirePlaceholder({
43785
+ block,
43786
+ role: message.role,
43787
+ stripped,
43788
+ modelAcceptsImages: args.modelAcceptsImages
43789
+ });
43790
+ if (placeholder === undefined)
43791
+ continue;
43792
+ replaced ??= content.slice();
43793
+ replaced[partIndex] = { type: "text", text: placeholder };
43794
+ }
43795
+ if (!replaced)
43796
+ return raw;
43797
+ changed = true;
43798
+ return { ...message, content: replaced };
43799
+ });
43800
+ return changed ? sent : messages;
43801
+ }
43802
+ function planPiProcessedImageIds(args, frozenIds) {
43803
+ if (!args.detect || args.watermark <= 0)
43804
+ return [];
43805
+ const ids = args.messages.map(args.stableId);
43806
+ const ownTags = ids.map((id) => id ? args.messageIdToMaxTag.get(id) ?? 0 : 0);
43807
+ const completeToolResults = new Set;
43808
+ const openCalls = new Map;
43809
+ for (let i = 0;i < args.messages.length; i++) {
43810
+ const message = args.messages[i];
43811
+ if (!message || typeof message !== "object")
43812
+ continue;
43813
+ if (message.role === "assistant" && Array.isArray(message.content)) {
43814
+ for (const part of message.content) {
43815
+ if (part?.type === "toolCall" && typeof part.id === "string") {
43816
+ openCalls.set(part.id, `${ids[i] ?? ""}\x00${part.id}`);
43817
+ }
43818
+ }
43819
+ } else if (message.role === "toolResult" && message.toolCallId) {
43820
+ const key = openCalls.get(message.toolCallId);
43821
+ if (key !== undefined && !args.protectedToolKeys?.has(key) && !args.protectedToolKeys?.has(message.toolCallId)) {
43822
+ completeToolResults.add(i);
43823
+ }
43824
+ openCalls.delete(message.toolCallId);
43825
+ }
43826
+ }
43827
+ const selected = [];
43828
+ let hasAssistantResponse = false;
43829
+ let nextTag;
43830
+ for (let i = args.messages.length - 1;i >= 0; i--) {
43831
+ const ownTag = ownTags[i];
43832
+ const positionTag = ownTag > 0 ? ownTag : nextTag;
43833
+ if (ownTag > 0)
43834
+ nextTag = ownTag;
43835
+ const raw = args.messages[i];
43836
+ if (!raw || typeof raw !== "object")
43837
+ continue;
43838
+ const message = raw;
43839
+ if (message.role === "assistant") {
43840
+ hasAssistantResponse = true;
43841
+ continue;
43842
+ }
43843
+ if (message.role !== "user" && message.role !== "toolResult" || message.role === "toolResult" && !completeToolResults.has(i) || !hasAssistantResponse || !Array.isArray(message.content) || !message.content.some(isLargeImagePart))
43844
+ continue;
43845
+ const id = ids[i];
43846
+ if (!id || frozenIds.has(id) || positionTag === undefined || positionTag > args.watermark)
43847
+ continue;
43848
+ if ((args.usagePercentage ?? 0) < 95 && positionTag >= (args.protectedCutoff ?? Infinity))
43849
+ continue;
43850
+ selected.push(id);
43851
+ }
43852
+ return selected;
43853
+ }
43854
+ function stripPiProcessedImages(args) {
43855
+ const frozenIds = getProcessedImageStrippedIds(args.db, args.sessionId);
43856
+ const newlyStrippedIds = planPiProcessedImageIds(args, frozenIds);
43857
+ if (newlyStrippedIds.length > 0) {
43858
+ const persisted = (args.addIds ?? addProcessedImageStrippedIds)(args.db, args.sessionId, newlyStrippedIds);
43859
+ if (persisted) {
43860
+ for (const id of newlyStrippedIds)
43861
+ frozenIds.add(id);
43862
+ } else {
43863
+ newlyStrippedIds.length = 0;
43864
+ sessionLog2(args.sessionId, "processed-image strip: persistence failed; leaving newly detected images intact");
43865
+ }
43866
+ }
43867
+ let stripped = 0;
43868
+ for (let i = 0;i < args.messages.length; i++) {
43869
+ const raw = args.messages[i];
43870
+ if (!raw || typeof raw !== "object")
43871
+ continue;
43872
+ const id = args.stableId(raw, i);
43873
+ if (!id || !frozenIds.has(id))
43874
+ continue;
43875
+ const message = raw;
43876
+ if (!Array.isArray(message.content))
43877
+ continue;
43878
+ for (let partIndex = 0;partIndex < message.content.length; partIndex++) {
43879
+ if (!isLargeImagePart(message.content[partIndex]))
43880
+ continue;
43881
+ if (newlyStrippedIds.includes(id))
43882
+ args.onFirstApplication?.(raw, i, partIndex);
43883
+ message.content[partIndex] = {
43884
+ type: "text",
43885
+ text: STRIPPED_IMAGE_MARKER
43886
+ };
43887
+ stripped++;
43888
+ }
43889
+ }
43890
+ return { stripped, newlyStrippedIds };
43891
+ }
43892
+
43553
43893
  // src/pi-raw-fallback.ts
43554
43894
  class PiStorageBusyError extends Error {
43555
43895
  code = "PI_STORAGE_BUSY";
@@ -43581,9 +43921,24 @@ function piFallbackRefusal(site, cause) {
43581
43921
  }
43582
43922
  return cause instanceof PiDegradedPassError ? cause : new PiDegradedPassError(site, { cause });
43583
43923
  }
43584
- function estimatePiOutgoingInputTokens(messages, observed, measuredPrefix, contextLimit, tokenCounts) {
43924
+ function piSentMessages(messages, observed) {
43925
+ return piMessagesWithWireImages(messages, {
43926
+ modelAcceptsImages: observed?.modelAcceptsImages !== false
43927
+ });
43928
+ }
43929
+ function piSentMeasuredPrefix(measuredPrefix, observed) {
43930
+ if (!measuredPrefix || observed?.modelAcceptsImages !== false)
43931
+ return measuredPrefix;
43932
+ return {
43933
+ ...measuredPrefix,
43934
+ appendedMessages: piSentMessages(measuredPrefix.appendedMessages, observed)
43935
+ };
43936
+ }
43937
+ function estimatePiOutgoingInputTokens(servedMessages, observed, servedMeasuredPrefix, contextLimit, tokenCounts) {
43585
43938
  if (!observed || !Number.isFinite(observed.systemTokens) || observed.systemTokens <= 0 || !Number.isFinite(observed.toolDefinitionTokens) || observed.toolDefinitionTokens < 0 || !hasTokenizerForFit())
43586
43939
  return { tokens: 0, trusted: false };
43940
+ const messages = piSentMessages(servedMessages, observed);
43941
+ const measuredPrefix = piSentMeasuredPrefix(servedMeasuredPrefix, observed);
43587
43942
  const knownRole = (message) => {
43588
43943
  if (!message || typeof message !== "object")
43589
43944
  return false;
@@ -43720,7 +44075,9 @@ function estimatePiOutgoingInputTokens(messages, observed, measuredPrefix, conte
43720
44075
  refusalBasis: refusalGrade ? measured ? "provider-prefix" : "calibrated" : undefined
43721
44076
  };
43722
44077
  }
43723
- function assertPiRawFallbackFits(messages, contextLimit, log, cause, observed, measuredPrefix) {
44078
+ function assertPiRawFallbackFits(servedMessages, contextLimit, log, cause, observed, servedMeasuredPrefix) {
44079
+ const messages = piSentMessages(servedMessages, observed);
44080
+ const measuredPrefix = piSentMeasuredPrefix(servedMeasuredPrefix, observed);
43724
44081
  if (!contextLimit || !Number.isFinite(contextLimit) || !observed || !Number.isFinite(observed.systemTokens) || observed.systemTokens <= 0 || !Number.isFinite(observed.toolDefinitionTokens) || observed.toolDefinitionTokens < 0 || observed.envelopeBytes !== undefined && (!Number.isFinite(observed.envelopeBytes) || observed.envelopeBytes < 0)) {
43725
44082
  log("raw_fallback_refused completeness=partial");
43726
44083
  throw piFallbackRefusal("fallback-metadata-incomplete", cause);
@@ -44660,7 +45017,8 @@ function readPiLkgFitEnvelope(ctx, pi, modelKey, frozen, wireSchema) {
44660
45017
  toolDefinitionsMeasured: refusalToolDefinitionTokens !== undefined,
44661
45018
  envelopeBytes: Buffer.byteLength(envelopeJson),
44662
45019
  envelopeSignature: activeNames ? createHash18("sha256").update(envelopeJson).update(JSON.stringify(activeNames)).digest("hex") : undefined,
44663
- calibration
45020
+ calibration,
45021
+ ...piModelAcceptsImages(ctx.model) ? {} : { modelAcceptsImages: false }
44664
45022
  };
44665
45023
  } catch {
44666
45024
  return;
@@ -45403,9 +45761,12 @@ function piToolResultImageTokens(messages, priceImage) {
45403
45761
  }
45404
45762
  return counts;
45405
45763
  }
45406
- function estimatePiOverflowRecoveryInputTokens(messages, envelope, options = {}) {
45764
+ function estimatePiOverflowRecoveryInputTokens(servedMessages, envelope, options = {}) {
45407
45765
  if (!envelope || !estimatePiOutgoingInputTokens([], envelope).trusted)
45408
45766
  return;
45767
+ const messages = piMessagesWithWireImages(servedMessages, {
45768
+ modelAcceptsImages: envelope.modelAcceptsImages !== false
45769
+ });
45409
45770
  const raw = tokenizePiMessages([...messages]);
45410
45771
  for (const value of messages) {
45411
45772
  if (!value || typeof value !== "object")
@@ -47106,105 +47467,6 @@ function stripPiDroppedPlaceholderMessages(args) {
47106
47467
  return { removed, discovered };
47107
47468
  }
47108
47469
 
47109
- // src/strip-processed-images-pi.ts
47110
- var STRIPPED_IMAGE_MARKER = "[image stripped]";
47111
- function isLargeImagePart(value) {
47112
- if (!value || typeof value !== "object")
47113
- return false;
47114
- const part = value;
47115
- return part.type === "image" && typeof part.mimeType === "string" && part.mimeType.startsWith("image/") && typeof part.data === "string" && part.data.length > 200;
47116
- }
47117
- function planPiProcessedImageIds(args, frozenIds) {
47118
- if (!args.detect || args.watermark <= 0)
47119
- return [];
47120
- const ids = args.messages.map(args.stableId);
47121
- const ownTags = ids.map((id) => id ? args.messageIdToMaxTag.get(id) ?? 0 : 0);
47122
- const completeToolResults = new Set;
47123
- const openCalls = new Map;
47124
- for (let i = 0;i < args.messages.length; i++) {
47125
- const message = args.messages[i];
47126
- if (!message || typeof message !== "object")
47127
- continue;
47128
- if (message.role === "assistant" && Array.isArray(message.content)) {
47129
- for (const part of message.content) {
47130
- if (part?.type === "toolCall" && typeof part.id === "string") {
47131
- openCalls.set(part.id, `${ids[i] ?? ""}\x00${part.id}`);
47132
- }
47133
- }
47134
- } else if (message.role === "toolResult" && message.toolCallId) {
47135
- const key = openCalls.get(message.toolCallId);
47136
- if (key !== undefined && !args.protectedToolKeys?.has(key) && !args.protectedToolKeys?.has(message.toolCallId)) {
47137
- completeToolResults.add(i);
47138
- }
47139
- openCalls.delete(message.toolCallId);
47140
- }
47141
- }
47142
- const selected = [];
47143
- let hasAssistantResponse = false;
47144
- let nextTag;
47145
- for (let i = args.messages.length - 1;i >= 0; i--) {
47146
- const ownTag = ownTags[i];
47147
- const positionTag = ownTag > 0 ? ownTag : nextTag;
47148
- if (ownTag > 0)
47149
- nextTag = ownTag;
47150
- const raw = args.messages[i];
47151
- if (!raw || typeof raw !== "object")
47152
- continue;
47153
- const message = raw;
47154
- if (message.role === "assistant") {
47155
- hasAssistantResponse = true;
47156
- continue;
47157
- }
47158
- if (message.role !== "user" && message.role !== "toolResult" || message.role === "toolResult" && !completeToolResults.has(i) || !hasAssistantResponse || !Array.isArray(message.content) || !message.content.some(isLargeImagePart))
47159
- continue;
47160
- const id = ids[i];
47161
- if (!id || frozenIds.has(id) || positionTag === undefined || positionTag > args.watermark)
47162
- continue;
47163
- if ((args.usagePercentage ?? 0) < 95 && positionTag >= (args.protectedCutoff ?? Infinity))
47164
- continue;
47165
- selected.push(id);
47166
- }
47167
- return selected;
47168
- }
47169
- function stripPiProcessedImages(args) {
47170
- const frozenIds = getProcessedImageStrippedIds(args.db, args.sessionId);
47171
- const newlyStrippedIds = planPiProcessedImageIds(args, frozenIds);
47172
- if (newlyStrippedIds.length > 0) {
47173
- const persisted = (args.addIds ?? addProcessedImageStrippedIds)(args.db, args.sessionId, newlyStrippedIds);
47174
- if (persisted) {
47175
- for (const id of newlyStrippedIds)
47176
- frozenIds.add(id);
47177
- } else {
47178
- newlyStrippedIds.length = 0;
47179
- sessionLog2(args.sessionId, "processed-image strip: persistence failed; leaving newly detected images intact");
47180
- }
47181
- }
47182
- let stripped = 0;
47183
- for (let i = 0;i < args.messages.length; i++) {
47184
- const raw = args.messages[i];
47185
- if (!raw || typeof raw !== "object")
47186
- continue;
47187
- const id = args.stableId(raw, i);
47188
- if (!id || !frozenIds.has(id))
47189
- continue;
47190
- const message = raw;
47191
- if (!Array.isArray(message.content))
47192
- continue;
47193
- for (let partIndex = 0;partIndex < message.content.length; partIndex++) {
47194
- if (!isLargeImagePart(message.content[partIndex]))
47195
- continue;
47196
- if (newlyStrippedIds.includes(id))
47197
- args.onFirstApplication?.(raw, i, partIndex);
47198
- message.content[partIndex] = {
47199
- type: "text",
47200
- text: STRIPPED_IMAGE_MARKER
47201
- };
47202
- stripped++;
47203
- }
47204
- }
47205
- return { stripped, newlyStrippedIds };
47206
- }
47207
-
47208
47470
  // ../plugin/src/hooks/magic-context/system-prompt-dates.ts
47209
47471
  function replaceHostDates(prompt, replace) {
47210
47472
  const fields = /<(plugin-env|environment|env)>[\s\S]*?<\/\1>|Today's date: [^\r\n<]+/g;
@@ -47376,6 +47638,8 @@ function createPiTranscript(source, sessionId, entryIds, options = {}) {
47376
47638
  toolRemovals.set(working, removals);
47377
47639
  if (options.authorizeToolRemoval)
47378
47640
  toolRemovalAuthorization.set(working, options.authorizeToolRemoval);
47641
+ if (options.toolImageTokens)
47642
+ toolImageTokenCost.set(working, options.toolImageTokens);
47379
47643
  const emptyRemovedMessages = new Set;
47380
47644
  const toolInputChanges = new Map;
47381
47645
  const transcriptMessages = buildTranscriptView(working, sessionId, (messageIndex, toolCallId) => {
@@ -47847,7 +48111,10 @@ function createPiToolResultPart(working, messageIndex, partIndex, markDirty) {
47847
48111
  kind,
47848
48112
  id: msg.toolCallId,
47849
48113
  imageTokens() {
47850
- return working[messageIndex].content[partIndex]?.type === "image" ? PI_IMAGE_TOKENS : 0;
48114
+ if (working[messageIndex].content[partIndex]?.type !== "image")
48115
+ return 0;
48116
+ const cost = toolImageTokenCost.get(working);
48117
+ return cost ? cost(messageIndex, partIndex) : PI_IMAGE_TOKENS;
47851
48118
  },
47852
48119
  remove() {
47853
48120
  return markToolRemoval(working, messageIndex, partIndex);
@@ -47946,6 +48213,7 @@ function extractStableId(msg, index, entryIds) {
47946
48213
  }
47947
48214
  var toolRemovals = new WeakMap;
47948
48215
  var toolRemovalAuthorization = new WeakMap;
48216
+ var toolImageTokenCost = new WeakMap;
47949
48217
  function markToolRemoval(working, messageIndex, partIndex) {
47950
48218
  const removals = toolRemovals.get(working);
47951
48219
  if (!removals)
@@ -48737,14 +49005,6 @@ function addPiBranchEntryToLookup(lookup, entry) {
48737
49005
  else
48738
49006
  lookup.entryIdsByFingerprint.set(fingerprint, [row.id]);
48739
49007
  }
48740
- function isPiContextEmitEligible(entry) {
48741
- if (!entry || typeof entry !== "object")
48742
- return false;
48743
- const row = entry;
48744
- if (typeof row.id !== "string")
48745
- return false;
48746
- return row.type === "message" || row.type === "custom_message" || row.type === "branch_summary" && typeof row.summary === "string" && row.summary.length > 0;
48747
- }
48748
49008
  function buildPiAlignedEntryIds(entries) {
48749
49009
  const all = buildPiAlignedEntryIdsIncludingSystem(entries);
48750
49010
  return { all, visible: buildPiAlignedVisibleEntryIds(entries) };
@@ -50547,6 +50807,7 @@ function registerPiContextHandler(pi, baseOptions) {
50547
50807
  resolvedProviderID: ctx.model?.provider,
50548
50808
  resolvedModelID: ctx.model?.id,
50549
50809
  providerApi: ctx.model?.api,
50810
+ modelAcceptsImages: piModelAcceptsImages(ctx.model),
50550
50811
  canUseEmptySentinels,
50551
50812
  temporalAwareness: options.injection?.temporalAwareness === true,
50552
50813
  appendCompaction: guardedPiAppendCompaction(ctx, assertCurrentPass),
@@ -51651,6 +51912,8 @@ function spawnPiHistorianRun(args) {
51651
51912
  expandTools: historian.expandTools,
51652
51913
  thinkingLevel: historian.thinkingLevel,
51653
51914
  memoryEnabled: historian.memoryEnabled,
51915
+ memoryInjectionBudgetTokens: historian.memoryInjectionBudgetTokens,
51916
+ recoveryTriggerReason: args.recoveryTriggerReason,
51654
51917
  allowHomeProject: historian.allowHomeProject,
51655
51918
  autoPromote: historian.autoPromote,
51656
51919
  userMemoriesEnabled: historian.userMemoriesEnabled,
@@ -51908,6 +52171,7 @@ function maybeFireHistorian(args) {
51908
52171
  provider,
51909
52172
  unregister,
51910
52173
  boundarySnapshot: snapshot,
52174
+ recoveryTriggerReason: "history_retirement",
51911
52175
  refreshBoundarySnapshot: resolveRunnablePiBoundarySnapshot,
51912
52176
  currentContextLimit: boundaryContextLimit,
51913
52177
  fallbackModelId: modelKey
@@ -51938,6 +52202,7 @@ Historian previously failed ${failureCount} time(s), so Magic Context is retryin
51938
52202
  provider,
51939
52203
  unregister,
51940
52204
  boundarySnapshot: prepareRecoveryBoundary,
52205
+ recoveryTriggerReason: "startup_recovery",
51941
52206
  refreshBoundarySnapshot: resolveRunnablePiBoundarySnapshot,
51942
52207
  currentContextLimit: boundaryContextLimit,
51943
52208
  fallbackModelId: modelKey
@@ -52506,6 +52771,12 @@ async function runPipeline(args) {
52506
52771
  }
52507
52772
  };
52508
52773
  const tTranscriptBuild = performance.now();
52774
+ let frozenImageMessageIds;
52775
+ const imageStrippedMessage = (message, index) => {
52776
+ const id = stableIdResolver(message, index);
52777
+ frozenImageMessageIds ??= getProcessedImageStrippedIds(args.db, args.sessionId);
52778
+ return id !== undefined && frozenImageMessageIds.has(id);
52779
+ };
52509
52780
  const transcript = createPiTranscript(args.messages, args.sessionId, args.messages.map(stableIdResolver), {
52510
52781
  preserveReasoningToolArcs: args.reasoningClearing?.preserveReasoningToolArcs,
52511
52782
  authorizeToolRemoval: (callId) => authorizePiToolRemoval({
@@ -52521,7 +52792,15 @@ async function runPipeline(args) {
52521
52792
  callIds,
52522
52793
  saved: nativeRemovalInputs,
52523
52794
  canApply: isCacheBustingPass
52524
- })
52795
+ }),
52796
+ toolImageTokens: (messageIndex, partIndex) => {
52797
+ const message = args.messages[messageIndex];
52798
+ return piToolImageWireTokens({
52799
+ block: Array.isArray(message?.content) ? message.content[partIndex] : undefined,
52800
+ stripped: imageStrippedMessage(message, messageIndex),
52801
+ modelAcceptsImages: args.modelAcceptsImages !== false
52802
+ });
52803
+ }
52525
52804
  });
52526
52805
  logTransformTiming(args.sessionId, "transcriptBuild", tTranscriptBuild);
52527
52806
  const workingMessages = transcript.getWorkingMessages();
@@ -52956,7 +53235,13 @@ async function runPipeline(args) {
52956
53235
  const emergencyPlannerMayRun = shouldRunHeuristics && args.heuristics !== undefined && args.forceMaterialization === true && args.emergencyCeilingTokens !== undefined && args.emergencyCeilingTokens > 0;
52957
53236
  const tagsNewerThanReading = emergencyPlannerMayRun ? tagsSinceReading(transcript.messages, newTargets) : undefined;
52958
53237
  const queuedDropTags = new Set(pendingOps.map((op) => op.tagId));
52959
- const emergencyToolImageTokens = () => args.providerOverflowRecovery === true ? piRecoveryToolImageTokens(workingMessages) : piToolImageCostTokens(workingMessages);
53238
+ const emergencyToolImageTokens = () => {
53239
+ const sent = piMessagesWithWireImages(workingMessages, {
53240
+ modelAcceptsImages: args.modelAcceptsImages !== false,
53241
+ strippedMessage: imageStrippedMessage
53242
+ });
53243
+ return args.providerOverflowRecovery === true ? piRecoveryToolImageTokens(sent) : piToolImageCostTokens(sent);
53244
+ };
52960
53245
  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;
52961
53246
  mutationGateObserverForTests?.({
52962
53247
  foldDue: foldDueDecision.value,
@@ -54230,25 +54515,20 @@ function makeMessage2(role, text) {
54230
54515
  }
54231
54516
 
54232
54517
  // src/pi-recomp-marker.ts
54233
- function placeFirstKeptEntryId(db, sessionId, branchEntries, lastCompactedOrdinal) {
54234
- const alignment = resolvePiOrdinalAlignment(db, sessionId, branchEntries);
54235
- if (isPiOrdinalAlignmentUnanchored(alignment))
54236
- return null;
54237
- return findFirstKeptEntryId(branchEntries, lastCompactedOrdinal, alignment.offset);
54518
+ function placeFirstKeptEntryId(db, sessionId, branchEntries, last) {
54519
+ return placePiMarkerKeptEntry(db, sessionId, branchEntries, last.endMessageId, last.endMessage);
54238
54520
  }
54239
54521
  function stagePiRecompMarker(args) {
54240
54522
  const compartments = getCompartments(args.db, args.sessionId);
54241
54523
  const last = compartments[compartments.length - 1];
54242
- if (!last)
54524
+ if (!last || last.endMessageId.length === 0)
54243
54525
  return;
54244
54526
  let firstKeptEntryId = null;
54245
54527
  try {
54246
- firstKeptEntryId = placeFirstKeptEntryId(args.db, args.sessionId, args.branchEntries, last.endMessage);
54528
+ firstKeptEntryId = placeFirstKeptEntryId(args.db, args.sessionId, args.branchEntries, last);
54247
54529
  } catch {
54248
54530
  firstKeptEntryId = null;
54249
54531
  }
54250
- if (!firstKeptEntryId || last.endMessageId.length === 0)
54251
- return;
54252
54532
  setPendingPiCompactionMarkerState(args.db, args.sessionId, {
54253
54533
  firstKeptEntryId,
54254
54534
  endMessageId: last.endMessageId,
@@ -56851,6 +57131,7 @@ Chunk ${chunkIndex}: wrapping messages ${plan.snapshot.offset}-${plan.snapshot.e
56851
57131
  maxOutputTokens: deps.historianMaxOutputTokens,
56852
57132
  thinkingLevel: deps.historianThinkingLevel,
56853
57133
  memoryEnabled: deps.memoryEnabled,
57134
+ memoryInjectionBudgetTokens: deps.memoryInjectionBudgetTokens,
56854
57135
  autoPromote: deps.autoPromote,
56855
57136
  userMemoriesEnabled: deps.userMemoriesEnabled,
56856
57137
  userObservationsRequested: deps.userObservationsRequested,
@@ -58026,6 +58307,7 @@ function resolveHistorianFromConfig(config, harness = PI_HARNESS_KIND, modelRegi
58026
58307
  keepReasoningTokens: config.keep_reasoning_tokens,
58027
58308
  historyBudgetPercentage: config.history_budget_percentage,
58028
58309
  memoryEnabled: config.memory.enabled,
58310
+ memoryInjectionBudgetTokens: config.memory.injection_budget_tokens,
58029
58311
  autoPromote: config.memory.auto_promote,
58030
58312
  userMemoriesEnabled: userObservationCollectionEnabled(config.dreamer),
58031
58313
  userObservationsRequested: userObservationsRequested(config.dreamer),
@@ -58686,6 +58968,7 @@ async function startPiMagicContextRuntime(pi, database, dbPath) {
58686
58968
  ...buildPiHistorianCommandOptions(bootProjectDeps.historianConfig, bootProjectDeps.config),
58687
58969
  language: bootProjectDeps.config.language,
58688
58970
  memoryEnabled: bootProjectDeps.config.memory.enabled,
58971
+ memoryInjectionBudgetTokens: bootProjectDeps.config.memory.injection_budget_tokens,
58689
58972
  autoPromote: bootProjectDeps.config.memory.auto_promote,
58690
58973
  compactionOff,
58691
58974
  userMemoriesEnabled: userObservationCollectionEnabled(bootProjectDeps.config.dreamer),
@@ -58702,6 +58985,7 @@ async function startPiMagicContextRuntime(pi, database, dbPath) {
58702
58985
  ...buildPiHistorianCommandOptions(historian, current.config),
58703
58986
  language: current.config.language,
58704
58987
  memoryEnabled: current.config.memory.enabled,
58988
+ memoryInjectionBudgetTokens: current.config.memory.injection_budget_tokens,
58705
58989
  autoPromote: fresh.memory.auto_promote,
58706
58990
  compactionOff,
58707
58991
  userMemoriesEnabled: userObservationCollectionEnabled(current.config.dreamer),