@cortexkit/pi-magic-context 0.49.63 → 0.49.64

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-w4sqw9mf.js → index-67q9cz3f.js} +1 -1
  4. package/dist/{index-418za765.js → index-691zz6f4.js} +7 -7
  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 +486 -281
  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
@@ -154,7 +154,7 @@ import {
154
154
  registerTodoStateLifecycle,
155
155
  syncCtxMemoryToolEnabled,
156
156
  registerMagicContextTools
157
- } from "./index-418za765.js";
157
+ } from "./index-691zz6f4.js";
158
158
  import"./index-4knyh1kt.js";
159
159
  import {
160
160
  canonicalModelIdentity,
@@ -282,6 +282,7 @@ import {
282
282
  getTriggerTagTokenUpperBound2,
283
283
  updateTagInputByteSize2,
284
284
  updateTagTokenCount2,
285
+ setTagTokenCount2,
285
286
  getPersistedToolTagAccounting2,
286
287
  getAllStatusTagTokenTotalsFlat2,
287
288
  tryGetReasoningTokenEstimatesByMessage2,
@@ -403,7 +404,7 @@ import {
403
404
  setSessionWorkMetrics,
404
405
  getSessionWorkMetrics,
405
406
  resolveEpochFloorForPass
406
- } from "./index-8gvbskcm.js";
407
+ } from "./index-7vhbmjgv.js";
407
408
  import {
408
409
  textMentionsRecentCommit,
409
410
  hasMeaningfulUserText2,
@@ -454,7 +455,7 @@ import {
454
455
  openCurrentDatabase,
455
456
  openDatabaseAsync,
456
457
  closeDatabase
457
- } from "./index-w4sqw9mf.js";
458
+ } from "./index-67q9cz3f.js";
458
459
  import {
459
460
  LkgRecoveryFenceError,
460
461
  clearLkgFenceProcessState,
@@ -581,7 +582,7 @@ import {
581
582
  getSourceContents,
582
583
  recordSubagentInvocation,
583
584
  getLatestHistorianInvocationId
584
- } from "./index-zgsemyph.js";
585
+ } from "./index-6vmpw4z3.js";
585
586
  import {
586
587
  resolveOpenCodeDbPath,
587
588
  assertOpenCodeStoreGeneration,
@@ -647,7 +648,7 @@ import {
647
648
  getRawSessionTagKeysThrough2,
648
649
  getLegacyProtectedTailStartOrdinal2,
649
650
  readSessionChunk2
650
- } from "./index-xan5mt5f.js";
651
+ } from "./index-98e27fdt.js";
651
652
  import"./index-nvh6d3bz.js";
652
653
  import {
653
654
  formatSynapseLaneDescriptor
@@ -687,7 +688,7 @@ import {
687
688
  clearCompressionDepthRange,
688
689
  cleanSearchText,
689
690
  matchedSearchSnippet
690
- } from "./index-m6kszx0e.js";
691
+ } from "./index-renfmk50.js";
691
692
  import {
692
693
  rememberV1HiddenRun
693
694
  } from "./index-6x556c2q.js";
@@ -816,7 +817,7 @@ import {
816
817
  scheduleClearAndReindex,
817
818
  clearSessionTracking,
818
819
  createAutoSearchDiagnostics
819
- } from "./index-5hhhxck7.js";
820
+ } from "./index-8328rak2.js";
820
821
  import"./index-3s39a1md.js";
821
822
  import {
822
823
  DREAMER_PRIMER_INVESTIGATOR_ALLOWED_TOOLS,
@@ -845,11 +846,11 @@ import {
845
846
  drainPiTagSnapshotSession,
846
847
  assertPiTagSnapshotReady,
847
848
  ensurePiTagSnapshotReady
848
- } from "./index-fz4gexgk.js";
849
+ } from "./index-ye6b3dr4.js";
849
850
  import"./index-71rg8j43.js";
850
851
  import"./index-8d2z6503.js";
851
- import"./index-9cqfbdgb.js";
852
- import"./index-f4n7tnsf.js";
852
+ import"./index-vkcb1cg1.js";
853
+ import"./index-hja11zte.js";
853
854
  import {
854
855
  __toESM
855
856
  } from "./index-22jkk6wg.js";
@@ -3601,7 +3602,7 @@ function startHostStallProfilerSwitch() {
3601
3602
  // package.json
3602
3603
  var package_default = {
3603
3604
  name: "@cortexkit/pi-magic-context",
3604
- version: "0.49.63",
3605
+ version: "0.49.64",
3605
3606
  type: "module",
3606
3607
  description: "Pi and OMP coding agent extension for Magic Context — cross-session memory and context management",
3607
3608
  main: "dist/index.js",
@@ -28857,6 +28858,9 @@ function tagTranscript(sessionId, transcript, tagger, db, options = {}) {
28857
28858
  timing.identity += performance.now() - identityStart;
28858
28859
  }
28859
28860
  existing.identityReusable &&= reuseIdentity;
28861
+ if (part.kind === "tool_result") {
28862
+ noteResultBlock(existing, part, text, tokenCacheKey);
28863
+ }
28860
28864
  applyToolPrefixAndTarget({
28861
28865
  skipPrefixInjection,
28862
28866
  part,
@@ -28885,6 +28889,8 @@ function tagTranscript(sessionId, transcript, tagger, db, options = {}) {
28885
28889
  occurrences: [{ message, part, kind: part.kind }],
28886
28890
  maxByteSize: reusableAccounting.byteSize,
28887
28891
  maxTokenCount: reusableAccounting.tokenCount ?? 0,
28892
+ resultImageTokens: 0,
28893
+ resultTexts: [],
28888
28894
  toolName: null,
28889
28895
  inputByteSize: reusableAccounting.inputByteSize,
28890
28896
  inputTokenCount: reusableAccounting.inputTokenCount,
@@ -28926,6 +28932,8 @@ function tagTranscript(sessionId, transcript, tagger, db, options = {}) {
28926
28932
  occurrences: [{ message, part, kind: part.kind }],
28927
28933
  maxByteSize: persistedAccounting?.byteSize ?? outputByteSize,
28928
28934
  maxTokenCount: persistedAccounting?.tokenCount ?? outputTokenCount,
28935
+ resultImageTokens: 0,
28936
+ resultTexts: [],
28929
28937
  toolName: accounting.toolName,
28930
28938
  inputByteSize: persistedAccounting?.inputByteSize ?? (part.kind === "tool_use" ? accounting.inputByteSize : 0),
28931
28939
  inputTokenCount: persistedAccounting?.inputTokenCount ?? (part.kind === "tool_use" ? firstInputTokenCount : null),
@@ -28951,6 +28959,8 @@ function tagTranscript(sessionId, transcript, tagger, db, options = {}) {
28951
28959
  toolAggregates.set(aggregateKey, aggregate);
28952
28960
  if (part.kind === "tool_use") {
28953
28961
  openToolAggregateKeysByCallId.set(callId, [...pendingKeys, aggregateKey]);
28962
+ } else {
28963
+ noteResultBlock(aggregate, part, text, tokenCacheKey);
28954
28964
  }
28955
28965
  applyToolPrefixAndTarget({
28956
28966
  skipPrefixInjection,
@@ -28969,6 +28979,16 @@ function tagTranscript(sessionId, transcript, tagger, db, options = {}) {
28969
28979
  }
28970
28980
  }
28971
28981
  }
28982
+ for (const aggregate of toolAggregates.values()) {
28983
+ applyImageResultAccounting({
28984
+ db,
28985
+ sessionId,
28986
+ tagger,
28987
+ aggregate,
28988
+ timing,
28989
+ tokenCache: options.toolTokenCache
28990
+ });
28991
+ }
28972
28992
  if (timing && options.onTiming) {
28973
28993
  options.onTiming("identity", timing.identity);
28974
28994
  options.onTiming("prefix", timing.prefix);
@@ -29000,10 +29020,36 @@ function applyGrownToolResultAccounting(args) {
29000
29020
  }
29001
29021
  args.aggregate.maxByteSize = args.byteSize;
29002
29022
  args.aggregate.maxTokenCount = tokenCount;
29023
+ args.aggregate.tokenCountGrewThisPass = true;
29003
29024
  updateTagByteSize2(args.db, args.sessionId, args.aggregate.tagId, args.byteSize);
29004
29025
  updateTagTokenCount2(args.db, args.sessionId, args.aggregate.tagId, tokenCount);
29005
29026
  syncToolAggregateAccounting(args.tagger, args.sessionId, args.aggregate);
29006
29027
  }
29028
+ function noteResultBlock(aggregate, part, text, tokenCacheKey) {
29029
+ const imageTokens = part.imageTokens?.() ?? 0;
29030
+ if (imageTokens > 0)
29031
+ aggregate.resultImageTokens += imageTokens;
29032
+ else if (text.length > 0)
29033
+ aggregate.resultTexts.push({ part, text, tokenCacheKey });
29034
+ }
29035
+ function applyImageResultAccounting(args) {
29036
+ const { aggregate } = args;
29037
+ if (aggregate.resultImageTokens === 0)
29038
+ return;
29039
+ const tokenStart = args.timing ? performance.now() : 0;
29040
+ let textTokens = 0;
29041
+ for (const block of aggregate.resultTexts) {
29042
+ textTokens = Math.max(textTokens, getCachedToolPartTokenCount(block.part, block.text, args.tokenCache, block.tokenCacheKey));
29043
+ }
29044
+ if (args.timing)
29045
+ args.timing.tokenCounting += performance.now() - tokenStart;
29046
+ const tokenCount = textTokens + aggregate.resultImageTokens;
29047
+ if (tokenCount === aggregate.maxTokenCount && !aggregate.tokenCountGrewThisPass)
29048
+ return;
29049
+ aggregate.maxTokenCount = tokenCount;
29050
+ setTagTokenCount2(args.db, args.sessionId, aggregate.tagId, tokenCount);
29051
+ syncToolAggregateAccounting(args.tagger, args.sessionId, aggregate);
29052
+ }
29007
29053
  function readAggregateToolAccounting(part, timing, tokenCache, tokenCacheKey, persisted) {
29008
29054
  const text = part.getText() ?? "";
29009
29055
  const byteSize = getToolPartByteSize(part, text);
@@ -29109,6 +29155,9 @@ function getToolPartByteSize(part, text) {
29109
29155
  function getToolPartTokenCount(part, text) {
29110
29156
  if (text.length > 0 || part.kind !== "tool_result")
29111
29157
  return estimateTokens(text);
29158
+ const imageTokens = part.imageTokens?.() ?? 0;
29159
+ if (imageTokens > 0)
29160
+ return imageTokens;
29112
29161
  const raw = part.rawByteSize?.();
29113
29162
  if (typeof raw === "number" && raw > 0) {
29114
29163
  const record = isRecord2(part) ? part : undefined;
@@ -30585,37 +30634,6 @@ function persistFilteredNoise(db, sessionId, chunk, eligibleEnd) {
30585
30634
  return saved;
30586
30635
  }
30587
30636
 
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
30637
  // src/system-entry-pi.ts
30620
30638
  function isPiSystemEntry(message) {
30621
30639
  return message !== null && typeof message === "object" && "role" in message && message.role === "system";
@@ -30764,6 +30782,198 @@ function adoptPiCompactionSystemSnapshot(messages, entries, compactionId, foldin
30764
30782
  }
30765
30783
  }
30766
30784
 
30785
+ // src/pi-history-cut.ts
30786
+ function isPiContextEmitEligible(entry) {
30787
+ if (!entry || typeof entry !== "object")
30788
+ return false;
30789
+ const row = entry;
30790
+ if (typeof row.id !== "string")
30791
+ return false;
30792
+ return row.type === "message" || row.type === "custom_message" || row.type === "branch_summary" && typeof row.summary === "string" && row.summary.length > 0;
30793
+ }
30794
+ function piCutMessageForEntry(entry) {
30795
+ if (!isPiContextEmitEligible(entry))
30796
+ return;
30797
+ const row = entry;
30798
+ if (row.type === "custom_message")
30799
+ return { role: "custom" };
30800
+ if (row.type === "branch_summary")
30801
+ return { role: "branchSummary" };
30802
+ return row.message && typeof row.message === "object" ? row.message : undefined;
30803
+ }
30804
+ function planPiHistoryCut(messages, cutoffIndex, promptReachesBoundary) {
30805
+ const remove = new Set;
30806
+ for (let i = 0;i <= cutoffIndex; i++) {
30807
+ if (!isPiSystemEntry(messages[i]))
30808
+ remove.add(i);
30809
+ }
30810
+ let changed = true;
30811
+ while (changed) {
30812
+ changed = false;
30813
+ const removedCallKeys = new Set;
30814
+ const removedResultKeys = new Set;
30815
+ for (const index of remove) {
30816
+ const msg = messages[index];
30817
+ if (!msg)
30818
+ continue;
30819
+ if (msg.role === "assistant") {
30820
+ for (const callId of getPiToolCallIds(msg)) {
30821
+ removedCallKeys.add(toolPairKey(callId, index));
30822
+ }
30823
+ } else if (msg.role === "toolResult") {
30824
+ const callId = getPiToolResultCallId(msg);
30825
+ const ownerIndex = callId ? findToolResultOwnerAssistantIndex(messages, index, callId) : null;
30826
+ if (callId && ownerIndex !== null) {
30827
+ removedResultKeys.add(toolPairKey(callId, ownerIndex));
30828
+ }
30829
+ }
30830
+ }
30831
+ for (let i = 0;i < messages.length; i++) {
30832
+ if (remove.has(i))
30833
+ continue;
30834
+ const msg = messages[i];
30835
+ if (!msg)
30836
+ continue;
30837
+ if (msg.role === "toolResult") {
30838
+ const callId = getPiToolResultCallId(msg);
30839
+ const ownerIndex = callId ? findToolResultOwnerAssistantIndex(messages, i, callId) : null;
30840
+ if (callId && ownerIndex !== null && removedCallKeys.has(toolPairKey(callId, ownerIndex))) {
30841
+ remove.add(i);
30842
+ changed = true;
30843
+ }
30844
+ continue;
30845
+ }
30846
+ if (msg.role === "assistant") {
30847
+ const callIds = getPiToolCallIds(msg);
30848
+ if (callIds.some((callId) => removedResultKeys.has(toolPairKey(callId, i)))) {
30849
+ remove.add(i);
30850
+ changed = true;
30851
+ }
30852
+ }
30853
+ }
30854
+ }
30855
+ const keptPrompt = keptPromptIndex(messages, cutoffIndex, remove, promptReachesBoundary);
30856
+ if (keptPrompt >= 0)
30857
+ remove.delete(keptPrompt);
30858
+ return remove;
30859
+ }
30860
+ function firstMessageKeptByPiHistoryCut(messages, remove) {
30861
+ for (let i = 0;i < messages.length; i++) {
30862
+ if (!remove.has(i) && !isPiSystemEntry(messages[i]))
30863
+ return i;
30864
+ }
30865
+ return -1;
30866
+ }
30867
+ function resolvePiMarkerKeptEntry(branchEntries, endMessageId) {
30868
+ const boundaryId = endMessageId.startsWith(SYNTH_USER_ID_PREFIX) ? endMessageId.slice(SYNTH_USER_ID_PREFIX.length) : endMessageId;
30869
+ if (boundaryId.length === 0)
30870
+ return { kind: "missing" };
30871
+ const messages = [];
30872
+ const ids = [];
30873
+ for (const entry of branchEntries) {
30874
+ const message = piCutMessageForEntry(entry);
30875
+ const id = entry.id;
30876
+ if (!message || id.length === 0)
30877
+ continue;
30878
+ messages.push(message);
30879
+ ids.push(id);
30880
+ }
30881
+ const cutoffIndex = ids.indexOf(boundaryId);
30882
+ if (cutoffIndex < 0)
30883
+ return { kind: "missing" };
30884
+ if (!messages.slice(cutoffIndex + 1).some((m) => !isPiSystemEntry(m)))
30885
+ return { kind: "waiting" };
30886
+ const kept = firstMessageKeptByPiHistoryCut(messages, planPiHistoryCut(messages, cutoffIndex));
30887
+ return kept < 0 ? { kind: "waiting" } : { kind: "resolved", entryId: ids[kept] };
30888
+ }
30889
+ function keptPromptIndex(messages, cutoffIndex, removed, promptReachesBoundary) {
30890
+ let promptIndex = -1;
30891
+ for (let i = cutoffIndex;i >= 0; i--) {
30892
+ if (messages[i]?.role === "user") {
30893
+ promptIndex = i;
30894
+ break;
30895
+ }
30896
+ }
30897
+ if (promptIndex < 0)
30898
+ return -1;
30899
+ for (let i = cutoffIndex + 1;i < messages.length; i++) {
30900
+ if (removed.has(i))
30901
+ continue;
30902
+ const message = messages[i];
30903
+ if (message?.role === "user")
30904
+ return -1;
30905
+ if (message?.role === "assistant" && message.stopReason !== "error")
30906
+ break;
30907
+ }
30908
+ if (promptReachesBoundary && !promptReachesBoundary(promptIndex))
30909
+ return -1;
30910
+ return promptIndex;
30911
+ }
30912
+ function toolPairKey(callId, assistantIndex) {
30913
+ return `${callId}\x00${assistantIndex}`;
30914
+ }
30915
+ function findToolResultOwnerAssistantIndex(messages, resultIndex, callId) {
30916
+ for (let i = resultIndex - 1;i >= 0; i--) {
30917
+ const msg = messages[i];
30918
+ if (msg?.role === "assistant" && getPiToolCallIds(msg).includes(callId)) {
30919
+ return i;
30920
+ }
30921
+ }
30922
+ for (let i = resultIndex + 1;i < messages.length; i++) {
30923
+ const msg = messages[i];
30924
+ if (msg?.role === "assistant" && getPiToolCallIds(msg).includes(callId)) {
30925
+ return i;
30926
+ }
30927
+ }
30928
+ return null;
30929
+ }
30930
+ function getPiToolCallIds(message) {
30931
+ if (!Array.isArray(message.content))
30932
+ return [];
30933
+ const ids = [];
30934
+ for (const part of message.content) {
30935
+ if (part && typeof part === "object" && part.type === "toolCall" && typeof part.id === "string") {
30936
+ ids.push(part.id);
30937
+ }
30938
+ }
30939
+ return ids;
30940
+ }
30941
+ function getPiToolResultCallId(message) {
30942
+ const callId = message.toolCallId;
30943
+ return typeof callId === "string" && callId.length > 0 ? callId : null;
30944
+ }
30945
+
30946
+ // src/pi-history-retirement.ts
30947
+ var KEY2 = "piHistorianRetirement";
30948
+ function readState2(db, sessionId) {
30949
+ const row = db.prepare("SELECT deferred_execute_state AS state FROM session_meta WHERE session_id = ?").get(sessionId);
30950
+ const state = row?.state ? JSON.parse(row.state) : {};
30951
+ if (!state || typeof state !== "object" || Array.isArray(state))
30952
+ throw new Error("Invalid session metadata JSON");
30953
+ return state;
30954
+ }
30955
+ function readPiHistoryRetirement(db, sessionId) {
30956
+ const target = readState2(db, sessionId)[KEY2];
30957
+ return typeof target === "string" && target.length > 0 ? target : null;
30958
+ }
30959
+ function queuePiHistoryRetirement(db, sessionId, throughMessageId) {
30960
+ ensureSessionMetaRow(db, sessionId);
30961
+ const state = readState2(db, sessionId);
30962
+ state[KEY2] = throughMessageId;
30963
+ db.prepare("UPDATE session_meta SET deferred_execute_state = ? WHERE session_id = ?").run(JSON.stringify(state), sessionId);
30964
+ }
30965
+ function acknowledgePiHistoryRetirement(db, sessionId, publishedEnd, ordinalOf) {
30966
+ const state = readState2(db, sessionId);
30967
+ const target = state[KEY2];
30968
+ if (typeof target !== "string")
30969
+ return;
30970
+ const ordinal = ordinalOf(target);
30971
+ if (ordinal === undefined || ordinal > publishedEnd)
30972
+ return;
30973
+ delete state[KEY2];
30974
+ db.prepare("UPDATE session_meta SET deferred_execute_state = ? WHERE session_id = ?").run(JSON.stringify(state), sessionId);
30975
+ }
30976
+
30767
30977
  // src/pi-historian-runner.ts
30768
30978
  var HISTORIAN_AGENT_NAME = "magic-context-historian";
30769
30979
  var DEFAULT_HISTORIAN_TIMEOUT_MS2 = 600000;
@@ -31487,9 +31697,7 @@ ${chunkText}`,
31487
31697
  let firstKeptEntryId = null;
31488
31698
  if (readBranchEntries) {
31489
31699
  try {
31490
- const branchEntries = readBranchEntries();
31491
- const alignment = resolvePiOrdinalAlignment(db, sessionId, branchEntries);
31492
- firstKeptEntryId = isPiOrdinalAlignmentUnanchored(alignment) ? null : findFirstKeptEntryId(branchEntries, lastNewEnd, alignment.offset);
31700
+ firstKeptEntryId = lastNewEndMessageId ? placePiMarkerKeptEntry(db, sessionId, readBranchEntries(), lastNewEndMessageId, lastNewEnd) : null;
31493
31701
  if (!firstKeptEntryId) {
31494
31702
  sessionLog2(sessionId, `historian: native compaction marker waiting; no resolvable firstKeptEntryId at or after ordinal ${lastNewEnd + 1}`);
31495
31703
  }
@@ -31801,6 +32009,17 @@ function buildPiCompactionSummary(compartments) {
31801
32009
  const shown = titles.slice(0, MAX_SUMMARY_TITLES).join("; ");
31802
32010
  return `Magic Context compacted ${titles.length} segments: ${shown}; …and ${titles.length - MAX_SUMMARY_TITLES} more`;
31803
32011
  }
32012
+ function placePiMarkerKeptEntry(db, sessionId, branchEntries, endMessageId, endOrdinal) {
32013
+ const alignment = resolvePiOrdinalAlignment(db, sessionId, branchEntries);
32014
+ if (isPiOrdinalAlignmentUnanchored(alignment))
32015
+ return null;
32016
+ const kept = resolvePiMarkerKeptEntry(branchEntries, endMessageId);
32017
+ if (kept.kind === "resolved")
32018
+ return kept.entryId;
32019
+ if (kept.kind === "waiting")
32020
+ return null;
32021
+ return findFirstKeptEntryId(branchEntries, endOrdinal, alignment.offset);
32022
+ }
31804
32023
  function findFirstKeptEntryId(entries, lastCompactedOrdinal, ordinalOffset = 0) {
31805
32024
  const boundary = resolvePiFirstKeptEntry(entries, lastCompactedOrdinal, ordinalOffset);
31806
32025
  return boundary.kind === "resolved" ? boundary.entryId : null;
@@ -31913,7 +32132,13 @@ function applyDeferredPiCompactionMarker(deps, sessionId, pending) {
31913
32132
  }
31914
32133
  const branchEntries = deps.readBranchEntries();
31915
32134
  let firstKeptEntryId = pending.firstKeptEntryId;
31916
- if (!firstKeptEntryId) {
32135
+ let placedByCut = false;
32136
+ const kept = resolvePiMarkerKeptEntry(branchEntries, pending.endMessageId);
32137
+ if (kept.kind !== "missing" && !isPiOrdinalAlignmentUnanchored(resolvePiOrdinalAlignment(deps.db, sessionId, branchEntries))) {
32138
+ placedByCut = true;
32139
+ firstKeptEntryId = kept.kind === "resolved" ? kept.entryId : null;
32140
+ }
32141
+ if (!placedByCut && !firstKeptEntryId) {
31917
32142
  const alignment = resolvePiOrdinalAlignment(deps.db, sessionId, branchEntries);
31918
32143
  if (isPiOrdinalAlignmentUnanchored(alignment)) {
31919
32144
  if (alignment.kind === "unanchored" && alignment.reason === "anchor-missing" && hasMergedSyntheticBoundary(branchEntries, pending.endMessageId)) {
@@ -34945,64 +35170,10 @@ function trimPiMessagesToBoundary(piMessages, entryIds, cutoffMessageId, trimMut
34945
35170
  }
34946
35171
  if (cutoffIndex < 0)
34947
35172
  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
- }
35173
+ const preserved = piMessages.slice(0, cutoffIndex + 1).filter((message) => isPiSystemEntry(message)).length;
34956
35174
  if (preserved > 0)
34957
35175
  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);
35176
+ const remove = planPiHistoryCut(piMessages, cutoffIndex, promptReachesBoundary);
35006
35177
  const retiredIds = new Set;
35007
35178
  if (retireDecisions) {
35008
35179
  for (const index of remove) {
@@ -35083,29 +35254,6 @@ function placeCutByBranchPosition(piMessages, entryIds, cutoffMessageId, session
35083
35254
  }
35084
35255
  };
35085
35256
  }
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
35257
  var idCutBoundaryByMessages = new WeakMap;
35110
35258
  var unplacedCutLoggedSessions = new Set;
35111
35259
  function resetPiUnplacedCutLog(sessionId) {
@@ -35117,39 +35265,6 @@ function logUnplacedCut(sessionId, boundaryMessageId, eventLength, reason, first
35117
35265
  unplacedCutLoggedSessions.add(sessionId);
35118
35266
  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
35267
  }
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
35268
  var PI_M1_PLACEHOLDER = "<session-history-since>(no new content since last materialization)</session-history-since>";
35154
35269
  var MAX_FORCED_MEMORIES_PER_DELTA = 10;
35155
35270
  var PI_M0_UPGRADE_STATE = "pi-m0m1-v2";
@@ -43550,6 +43665,160 @@ function safeJsonStringify2(value) {
43550
43665
  }
43551
43666
  }
43552
43667
 
43668
+ // src/strip-processed-images-pi.ts
43669
+ var STRIPPED_IMAGE_MARKER = "[image stripped]";
43670
+ function isLargeImagePart(value) {
43671
+ if (!value || typeof value !== "object")
43672
+ return false;
43673
+ const part = value;
43674
+ return part.type === "image" && typeof part.mimeType === "string" && part.mimeType.startsWith("image/") && typeof part.data === "string" && part.data.length > 200;
43675
+ }
43676
+ var PI_NON_VISION_TOOL_IMAGE_PLACEHOLDER = "(tool image omitted: model does not support images)";
43677
+ var PI_NON_VISION_USER_IMAGE_PLACEHOLDER = "(image omitted: model does not support images)";
43678
+ function piModelAcceptsImages(model) {
43679
+ const input = model?.input;
43680
+ return !Array.isArray(input) || input.includes("image");
43681
+ }
43682
+ function piImageWirePlaceholder(args) {
43683
+ if (args.block?.type !== "image")
43684
+ return;
43685
+ if (args.stripped && isLargeImagePart(args.block))
43686
+ return STRIPPED_IMAGE_MARKER;
43687
+ if (!args.modelAcceptsImages)
43688
+ return args.role === "toolResult" ? PI_NON_VISION_TOOL_IMAGE_PLACEHOLDER : PI_NON_VISION_USER_IMAGE_PLACEHOLDER;
43689
+ return;
43690
+ }
43691
+ function piToolImageWireTokens(args) {
43692
+ const placeholder = piImageWirePlaceholder({ ...args, role: "toolResult" });
43693
+ return placeholder === undefined ? PI_IMAGE_TOKENS : estimateTokens(placeholder);
43694
+ }
43695
+ function piMessagesWithWireImages(messages, args) {
43696
+ if (args.modelAcceptsImages && !args.strippedMessage)
43697
+ return messages;
43698
+ let changed = false;
43699
+ const sent = messages.map((raw, index) => {
43700
+ const message = raw;
43701
+ if (!message || typeof message !== "object")
43702
+ return raw;
43703
+ const content = message.content;
43704
+ if (!Array.isArray(content))
43705
+ return raw;
43706
+ let stripped;
43707
+ let replaced;
43708
+ for (let partIndex = 0;partIndex < content.length; partIndex++) {
43709
+ const block = content[partIndex];
43710
+ if (block?.type !== "image")
43711
+ continue;
43712
+ stripped ??= args.strippedMessage?.(raw, index) ?? false;
43713
+ const placeholder = piImageWirePlaceholder({
43714
+ block,
43715
+ role: message.role,
43716
+ stripped,
43717
+ modelAcceptsImages: args.modelAcceptsImages
43718
+ });
43719
+ if (placeholder === undefined)
43720
+ continue;
43721
+ replaced ??= content.slice();
43722
+ replaced[partIndex] = { type: "text", text: placeholder };
43723
+ }
43724
+ if (!replaced)
43725
+ return raw;
43726
+ changed = true;
43727
+ return { ...message, content: replaced };
43728
+ });
43729
+ return changed ? sent : messages;
43730
+ }
43731
+ function planPiProcessedImageIds(args, frozenIds) {
43732
+ if (!args.detect || args.watermark <= 0)
43733
+ return [];
43734
+ const ids = args.messages.map(args.stableId);
43735
+ const ownTags = ids.map((id) => id ? args.messageIdToMaxTag.get(id) ?? 0 : 0);
43736
+ const completeToolResults = new Set;
43737
+ const openCalls = new Map;
43738
+ for (let i = 0;i < args.messages.length; i++) {
43739
+ const message = args.messages[i];
43740
+ if (!message || typeof message !== "object")
43741
+ continue;
43742
+ if (message.role === "assistant" && Array.isArray(message.content)) {
43743
+ for (const part of message.content) {
43744
+ if (part?.type === "toolCall" && typeof part.id === "string") {
43745
+ openCalls.set(part.id, `${ids[i] ?? ""}\x00${part.id}`);
43746
+ }
43747
+ }
43748
+ } else if (message.role === "toolResult" && message.toolCallId) {
43749
+ const key = openCalls.get(message.toolCallId);
43750
+ if (key !== undefined && !args.protectedToolKeys?.has(key) && !args.protectedToolKeys?.has(message.toolCallId)) {
43751
+ completeToolResults.add(i);
43752
+ }
43753
+ openCalls.delete(message.toolCallId);
43754
+ }
43755
+ }
43756
+ const selected = [];
43757
+ let hasAssistantResponse = false;
43758
+ let nextTag;
43759
+ for (let i = args.messages.length - 1;i >= 0; i--) {
43760
+ const ownTag = ownTags[i];
43761
+ const positionTag = ownTag > 0 ? ownTag : nextTag;
43762
+ if (ownTag > 0)
43763
+ nextTag = ownTag;
43764
+ const raw = args.messages[i];
43765
+ if (!raw || typeof raw !== "object")
43766
+ continue;
43767
+ const message = raw;
43768
+ if (message.role === "assistant") {
43769
+ hasAssistantResponse = true;
43770
+ continue;
43771
+ }
43772
+ if (message.role !== "user" && message.role !== "toolResult" || message.role === "toolResult" && !completeToolResults.has(i) || !hasAssistantResponse || !Array.isArray(message.content) || !message.content.some(isLargeImagePart))
43773
+ continue;
43774
+ const id = ids[i];
43775
+ if (!id || frozenIds.has(id) || positionTag === undefined || positionTag > args.watermark)
43776
+ continue;
43777
+ if ((args.usagePercentage ?? 0) < 95 && positionTag >= (args.protectedCutoff ?? Infinity))
43778
+ continue;
43779
+ selected.push(id);
43780
+ }
43781
+ return selected;
43782
+ }
43783
+ function stripPiProcessedImages(args) {
43784
+ const frozenIds = getProcessedImageStrippedIds(args.db, args.sessionId);
43785
+ const newlyStrippedIds = planPiProcessedImageIds(args, frozenIds);
43786
+ if (newlyStrippedIds.length > 0) {
43787
+ const persisted = (args.addIds ?? addProcessedImageStrippedIds)(args.db, args.sessionId, newlyStrippedIds);
43788
+ if (persisted) {
43789
+ for (const id of newlyStrippedIds)
43790
+ frozenIds.add(id);
43791
+ } else {
43792
+ newlyStrippedIds.length = 0;
43793
+ sessionLog2(args.sessionId, "processed-image strip: persistence failed; leaving newly detected images intact");
43794
+ }
43795
+ }
43796
+ let stripped = 0;
43797
+ for (let i = 0;i < args.messages.length; i++) {
43798
+ const raw = args.messages[i];
43799
+ if (!raw || typeof raw !== "object")
43800
+ continue;
43801
+ const id = args.stableId(raw, i);
43802
+ if (!id || !frozenIds.has(id))
43803
+ continue;
43804
+ const message = raw;
43805
+ if (!Array.isArray(message.content))
43806
+ continue;
43807
+ for (let partIndex = 0;partIndex < message.content.length; partIndex++) {
43808
+ if (!isLargeImagePart(message.content[partIndex]))
43809
+ continue;
43810
+ if (newlyStrippedIds.includes(id))
43811
+ args.onFirstApplication?.(raw, i, partIndex);
43812
+ message.content[partIndex] = {
43813
+ type: "text",
43814
+ text: STRIPPED_IMAGE_MARKER
43815
+ };
43816
+ stripped++;
43817
+ }
43818
+ }
43819
+ return { stripped, newlyStrippedIds };
43820
+ }
43821
+
43553
43822
  // src/pi-raw-fallback.ts
43554
43823
  class PiStorageBusyError extends Error {
43555
43824
  code = "PI_STORAGE_BUSY";
@@ -43581,9 +43850,24 @@ function piFallbackRefusal(site, cause) {
43581
43850
  }
43582
43851
  return cause instanceof PiDegradedPassError ? cause : new PiDegradedPassError(site, { cause });
43583
43852
  }
43584
- function estimatePiOutgoingInputTokens(messages, observed, measuredPrefix, contextLimit, tokenCounts) {
43853
+ function piSentMessages(messages, observed) {
43854
+ return piMessagesWithWireImages(messages, {
43855
+ modelAcceptsImages: observed?.modelAcceptsImages !== false
43856
+ });
43857
+ }
43858
+ function piSentMeasuredPrefix(measuredPrefix, observed) {
43859
+ if (!measuredPrefix || observed?.modelAcceptsImages !== false)
43860
+ return measuredPrefix;
43861
+ return {
43862
+ ...measuredPrefix,
43863
+ appendedMessages: piSentMessages(measuredPrefix.appendedMessages, observed)
43864
+ };
43865
+ }
43866
+ function estimatePiOutgoingInputTokens(servedMessages, observed, servedMeasuredPrefix, contextLimit, tokenCounts) {
43585
43867
  if (!observed || !Number.isFinite(observed.systemTokens) || observed.systemTokens <= 0 || !Number.isFinite(observed.toolDefinitionTokens) || observed.toolDefinitionTokens < 0 || !hasTokenizerForFit())
43586
43868
  return { tokens: 0, trusted: false };
43869
+ const messages = piSentMessages(servedMessages, observed);
43870
+ const measuredPrefix = piSentMeasuredPrefix(servedMeasuredPrefix, observed);
43587
43871
  const knownRole = (message) => {
43588
43872
  if (!message || typeof message !== "object")
43589
43873
  return false;
@@ -43720,7 +44004,9 @@ function estimatePiOutgoingInputTokens(messages, observed, measuredPrefix, conte
43720
44004
  refusalBasis: refusalGrade ? measured ? "provider-prefix" : "calibrated" : undefined
43721
44005
  };
43722
44006
  }
43723
- function assertPiRawFallbackFits(messages, contextLimit, log, cause, observed, measuredPrefix) {
44007
+ function assertPiRawFallbackFits(servedMessages, contextLimit, log, cause, observed, servedMeasuredPrefix) {
44008
+ const messages = piSentMessages(servedMessages, observed);
44009
+ const measuredPrefix = piSentMeasuredPrefix(servedMeasuredPrefix, observed);
43724
44010
  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
44011
  log("raw_fallback_refused completeness=partial");
43726
44012
  throw piFallbackRefusal("fallback-metadata-incomplete", cause);
@@ -44660,7 +44946,8 @@ function readPiLkgFitEnvelope(ctx, pi, modelKey, frozen, wireSchema) {
44660
44946
  toolDefinitionsMeasured: refusalToolDefinitionTokens !== undefined,
44661
44947
  envelopeBytes: Buffer.byteLength(envelopeJson),
44662
44948
  envelopeSignature: activeNames ? createHash18("sha256").update(envelopeJson).update(JSON.stringify(activeNames)).digest("hex") : undefined,
44663
- calibration
44949
+ calibration,
44950
+ ...piModelAcceptsImages(ctx.model) ? {} : { modelAcceptsImages: false }
44664
44951
  };
44665
44952
  } catch {
44666
44953
  return;
@@ -45403,9 +45690,12 @@ function piToolResultImageTokens(messages, priceImage) {
45403
45690
  }
45404
45691
  return counts;
45405
45692
  }
45406
- function estimatePiOverflowRecoveryInputTokens(messages, envelope, options = {}) {
45693
+ function estimatePiOverflowRecoveryInputTokens(servedMessages, envelope, options = {}) {
45407
45694
  if (!envelope || !estimatePiOutgoingInputTokens([], envelope).trusted)
45408
45695
  return;
45696
+ const messages = piMessagesWithWireImages(servedMessages, {
45697
+ modelAcceptsImages: envelope.modelAcceptsImages !== false
45698
+ });
45409
45699
  const raw = tokenizePiMessages([...messages]);
45410
45700
  for (const value of messages) {
45411
45701
  if (!value || typeof value !== "object")
@@ -47106,105 +47396,6 @@ function stripPiDroppedPlaceholderMessages(args) {
47106
47396
  return { removed, discovered };
47107
47397
  }
47108
47398
 
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
47399
  // ../plugin/src/hooks/magic-context/system-prompt-dates.ts
47209
47400
  function replaceHostDates(prompt, replace) {
47210
47401
  const fields = /<(plugin-env|environment|env)>[\s\S]*?<\/\1>|Today's date: [^\r\n<]+/g;
@@ -47376,6 +47567,8 @@ function createPiTranscript(source, sessionId, entryIds, options = {}) {
47376
47567
  toolRemovals.set(working, removals);
47377
47568
  if (options.authorizeToolRemoval)
47378
47569
  toolRemovalAuthorization.set(working, options.authorizeToolRemoval);
47570
+ if (options.toolImageTokens)
47571
+ toolImageTokenCost.set(working, options.toolImageTokens);
47379
47572
  const emptyRemovedMessages = new Set;
47380
47573
  const toolInputChanges = new Map;
47381
47574
  const transcriptMessages = buildTranscriptView(working, sessionId, (messageIndex, toolCallId) => {
@@ -47847,7 +48040,10 @@ function createPiToolResultPart(working, messageIndex, partIndex, markDirty) {
47847
48040
  kind,
47848
48041
  id: msg.toolCallId,
47849
48042
  imageTokens() {
47850
- return working[messageIndex].content[partIndex]?.type === "image" ? PI_IMAGE_TOKENS : 0;
48043
+ if (working[messageIndex].content[partIndex]?.type !== "image")
48044
+ return 0;
48045
+ const cost = toolImageTokenCost.get(working);
48046
+ return cost ? cost(messageIndex, partIndex) : PI_IMAGE_TOKENS;
47851
48047
  },
47852
48048
  remove() {
47853
48049
  return markToolRemoval(working, messageIndex, partIndex);
@@ -47946,6 +48142,7 @@ function extractStableId(msg, index, entryIds) {
47946
48142
  }
47947
48143
  var toolRemovals = new WeakMap;
47948
48144
  var toolRemovalAuthorization = new WeakMap;
48145
+ var toolImageTokenCost = new WeakMap;
47949
48146
  function markToolRemoval(working, messageIndex, partIndex) {
47950
48147
  const removals = toolRemovals.get(working);
47951
48148
  if (!removals)
@@ -48737,14 +48934,6 @@ function addPiBranchEntryToLookup(lookup, entry) {
48737
48934
  else
48738
48935
  lookup.entryIdsByFingerprint.set(fingerprint, [row.id]);
48739
48936
  }
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
48937
  function buildPiAlignedEntryIds(entries) {
48749
48938
  const all = buildPiAlignedEntryIdsIncludingSystem(entries);
48750
48939
  return { all, visible: buildPiAlignedVisibleEntryIds(entries) };
@@ -50547,6 +50736,7 @@ function registerPiContextHandler(pi, baseOptions) {
50547
50736
  resolvedProviderID: ctx.model?.provider,
50548
50737
  resolvedModelID: ctx.model?.id,
50549
50738
  providerApi: ctx.model?.api,
50739
+ modelAcceptsImages: piModelAcceptsImages(ctx.model),
50550
50740
  canUseEmptySentinels,
50551
50741
  temporalAwareness: options.injection?.temporalAwareness === true,
50552
50742
  appendCompaction: guardedPiAppendCompaction(ctx, assertCurrentPass),
@@ -52506,6 +52696,12 @@ async function runPipeline(args) {
52506
52696
  }
52507
52697
  };
52508
52698
  const tTranscriptBuild = performance.now();
52699
+ let frozenImageMessageIds;
52700
+ const imageStrippedMessage = (message, index) => {
52701
+ const id = stableIdResolver(message, index);
52702
+ frozenImageMessageIds ??= getProcessedImageStrippedIds(args.db, args.sessionId);
52703
+ return id !== undefined && frozenImageMessageIds.has(id);
52704
+ };
52509
52705
  const transcript = createPiTranscript(args.messages, args.sessionId, args.messages.map(stableIdResolver), {
52510
52706
  preserveReasoningToolArcs: args.reasoningClearing?.preserveReasoningToolArcs,
52511
52707
  authorizeToolRemoval: (callId) => authorizePiToolRemoval({
@@ -52521,7 +52717,15 @@ async function runPipeline(args) {
52521
52717
  callIds,
52522
52718
  saved: nativeRemovalInputs,
52523
52719
  canApply: isCacheBustingPass
52524
- })
52720
+ }),
52721
+ toolImageTokens: (messageIndex, partIndex) => {
52722
+ const message = args.messages[messageIndex];
52723
+ return piToolImageWireTokens({
52724
+ block: Array.isArray(message?.content) ? message.content[partIndex] : undefined,
52725
+ stripped: imageStrippedMessage(message, messageIndex),
52726
+ modelAcceptsImages: args.modelAcceptsImages !== false
52727
+ });
52728
+ }
52525
52729
  });
52526
52730
  logTransformTiming(args.sessionId, "transcriptBuild", tTranscriptBuild);
52527
52731
  const workingMessages = transcript.getWorkingMessages();
@@ -52956,7 +53160,13 @@ async function runPipeline(args) {
52956
53160
  const emergencyPlannerMayRun = shouldRunHeuristics && args.heuristics !== undefined && args.forceMaterialization === true && args.emergencyCeilingTokens !== undefined && args.emergencyCeilingTokens > 0;
52957
53161
  const tagsNewerThanReading = emergencyPlannerMayRun ? tagsSinceReading(transcript.messages, newTargets) : undefined;
52958
53162
  const queuedDropTags = new Set(pendingOps.map((op) => op.tagId));
52959
- const emergencyToolImageTokens = () => args.providerOverflowRecovery === true ? piRecoveryToolImageTokens(workingMessages) : piToolImageCostTokens(workingMessages);
53163
+ const emergencyToolImageTokens = () => {
53164
+ const sent = piMessagesWithWireImages(workingMessages, {
53165
+ modelAcceptsImages: args.modelAcceptsImages !== false,
53166
+ strippedMessage: imageStrippedMessage
53167
+ });
53168
+ return args.providerOverflowRecovery === true ? piRecoveryToolImageTokens(sent) : piToolImageCostTokens(sent);
53169
+ };
52960
53170
  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
53171
  mutationGateObserverForTests?.({
52962
53172
  foldDue: foldDueDecision.value,
@@ -54230,25 +54440,20 @@ function makeMessage2(role, text) {
54230
54440
  }
54231
54441
 
54232
54442
  // 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);
54443
+ function placeFirstKeptEntryId(db, sessionId, branchEntries, last) {
54444
+ return placePiMarkerKeptEntry(db, sessionId, branchEntries, last.endMessageId, last.endMessage);
54238
54445
  }
54239
54446
  function stagePiRecompMarker(args) {
54240
54447
  const compartments = getCompartments(args.db, args.sessionId);
54241
54448
  const last = compartments[compartments.length - 1];
54242
- if (!last)
54449
+ if (!last || last.endMessageId.length === 0)
54243
54450
  return;
54244
54451
  let firstKeptEntryId = null;
54245
54452
  try {
54246
- firstKeptEntryId = placeFirstKeptEntryId(args.db, args.sessionId, args.branchEntries, last.endMessage);
54453
+ firstKeptEntryId = placeFirstKeptEntryId(args.db, args.sessionId, args.branchEntries, last);
54247
54454
  } catch {
54248
54455
  firstKeptEntryId = null;
54249
54456
  }
54250
- if (!firstKeptEntryId || last.endMessageId.length === 0)
54251
- return;
54252
54457
  setPendingPiCompactionMarkerState(args.db, args.sessionId, {
54253
54458
  firstKeptEntryId,
54254
54459
  endMessageId: last.endMessageId,