@cortexkit/pi-magic-context 0.49.72 → 0.49.73

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.
@@ -70,7 +70,7 @@ import {
70
70
  renderMessageByOrdinal2,
71
71
  renderVerboseRange2,
72
72
  renderItemByTag2
73
- } from "./index-kqekqrzw.js";
73
+ } from "./index-tygcydj7.js";
74
74
  import {
75
75
  getLastIndexedOrdinal
76
76
  } from "./index-mm9y1m77.js";
@@ -140,8 +140,8 @@ async function serveV2ArchiveReads2(port, openConnections) {
140
140
  import("./store-reader-mmfw2h48.js"),
141
141
  import("./store-grcwn6hs.js"),
142
142
  import("./read-session-chunk-ygwyfvtr.js"),
143
- import("./render-bsdcxgaq.js"),
144
- import("./search-archive-3hh7ycvm.js"),
143
+ import("./render-cm4572er.js"),
144
+ import("./search-archive-8kcsmnzt.js"),
145
145
  import("./expand-attachments-8sxeyj26.js")
146
146
  ]);
147
147
  const pool = new V2StoreReaderPool;
@@ -1505,11 +1505,33 @@ function pendingMaterializationOrigin(sessions, sessionId) {
1505
1505
  function hasPendingMaterializationOrigin(sessions, sessionId, origin) {
1506
1506
  return sessions.has(sessionId) && causes.get(sessions)?.get(sessionId)?.has(origin) === true;
1507
1507
  }
1508
+ function hasExplicitRefreshRequest(sessions, sessionId) {
1509
+ return hasPendingMaterializationOrigin(sessions, sessionId, "user_flush") || hasPendingMaterializationOrigin(sessions, sessionId, "user_wrapup");
1510
+ }
1508
1511
  function clearPendingMaterialization(sessions, sessionId) {
1509
1512
  sessions.delete(sessionId);
1510
1513
  origins.get(sessions)?.delete(sessionId);
1511
1514
  causes.get(sessions)?.delete(sessionId);
1512
1515
  }
1516
+ function clearReclaimedMaterialization(sessions, sessionId) {
1517
+ const wrapupPending = hasPendingMaterializationOrigin(sessions, sessionId, "user_wrapup");
1518
+ clearPendingMaterialization(sessions, sessionId);
1519
+ if (wrapupPending)
1520
+ requestPendingMaterialization(sessions, sessionId, "user_wrapup");
1521
+ }
1522
+ function clearPendingMaterializationOrigin(sessions, sessionId, origin) {
1523
+ const pendingCauses = causes.get(sessions)?.get(sessionId);
1524
+ if (!sessions.has(sessionId) || !pendingCauses?.has(origin))
1525
+ return;
1526
+ pendingCauses.delete(origin);
1527
+ const [next] = pendingCauses;
1528
+ if (next === undefined) {
1529
+ clearPendingMaterialization(sessions, sessionId);
1530
+ return;
1531
+ }
1532
+ if (origins.get(sessions)?.get(sessionId) === origin)
1533
+ origins.get(sessions)?.set(sessionId, next);
1534
+ }
1513
1535
  function hasOnlySystemHashMaterialization(sessions, sessionId) {
1514
1536
  const pendingCauses = causes.get(sessions)?.get(sessionId);
1515
1537
  return sessions.has(sessionId) && pendingCauses?.size === 1 && pendingCauses.has("system_hash");
@@ -4703,4 +4725,4 @@ function renderItemByTag2(db, sessionId, number, textIndexDomain = "part", attac
4703
4725
  return selected ? renderPartFull(selected) ?? "" : `Tag ${number}'s original text part is no longer in stored history.`;
4704
4726
  }
4705
4727
 
4706
- export { LkgRecoveryFenceError, clearLkgFenceProcessState, lkgFenceRequiresRebuild, lkgRecoveryFenceUnclean, ownsLkgDirtyFence, invalidateCleanLkgRecoveryFence, markLkgRecoveryDirty, rememberUnpublishedAutoSearchNoHint, getUnpublishedAutoSearchNoHint, forgetUnpublishedAutoSearchNoHint, registerAutoSearchWork, cancelAutoSearchWork, PI_IDENTITY_FOLD_GUARD_LIMIT, readPiIdentityFoldGuards, writePiIdentityFoldGuards, readSessionActivity, observeSessionActivity, backfillSessionActivity, readSessionMeta, getOrCreateSessionMeta, updateSessionMeta, advanceToolReclaimWatermark, retryPendingSessionCleanups, retryPendingRustSessionCleanupsForProject, COMPARTMENT_LEASE_RENEWAL_MS, acquireCompartmentLease, renewCompartmentLease, releaseCompartmentLease, releaseCompartmentLeaseBestEffort, isCompartmentLeaseHeld, isNoContentCompartment, HAS_COMPARTMENT_CONTENT_SQL, queueM0Mutation, getMaxM0MutationId, getCompartments, getLastCompartmentEndMessage, getLastCompartmentEndMessageId, getCompartmentsByEndMessageId, appendCompartments, saveRecompStagingPass, getRecompStaging, clearRecompStaging, getRecompPartialRange, setRecompPartialRange, escapeXmlAttr, escapeXmlContent, getUncoveredCompartmentEndThrough, getUncoveredCompartmentEndsThrough, readProjectDocsCanonical, providerResponseFailed, isSuccessfulProviderCompletion, requestPendingMaterialization, pendingMaterializationOrigin, hasPendingMaterializationOrigin, clearPendingMaterialization, recordSystemRefreshOwnership, recordSystemPromptForRequest, recordHeldHeadForRequest, bindSystemPromptResponse, acknowledgeSystemPromptDelivery, deferDeliveredSystemRefresh, clearSystemPromptDelivery, saveLkgSlotToDb, loadPersistedLkgSlot, drainStaleLkgSlots, createDbLkgPersistence, replayLkg, beginServedRequest, noteServedPassPermission, noteServedReplay, countServedRefusal, dropServedRecord, commitServedRequest, registerLkgPersistence, LKG_SNAPSHOT_ARRAY, LKG_SNAPSHOT_OBJECT, LKG_SNAPSHOT_KEY, LKG_SNAPSHOT_STRING, LKG_SNAPSHOT_NUMBER, LKG_SNAPSHOT_BOOLEAN, LKG_SNAPSHOT_NULL, LKG_SNAPSHOT_UNDEFINED, contentSnapshotValue, signatureForFields, lkgContentFields, lkgContentDigestFromFields, isLegacyLkgDigest, legacyLkgDigestFromFields, lkgFieldsMatchDigest, exactReusablePrefix, incrementalLkgContentDigests, lkgSlotRejection, captureSlot, getInMemorySlot, getSlot, dropSlot, TOOL_SWEEP_SCOPED_MARKER, encodePiContentDecision, decodePiContentDecision, getPiContentDecisions, freezePiContentDecision, withNativeReplayWriteBarrier, getNativeReplayState, saveNativeToolInputs, addNativeReasoningIds, copySessionStateForClone, externalHistorianFailureReason, subprocessExitHistorianFailureReason, countHistorianRuns, getRecentFailedHistorianRunTimes, recordHistorianRun, summarizeImportance, tallyFactsByCategory, queueMemoryMutation, getMemoryMutationsForRender, getMemoryMutationsForRenderByProjects, getMaxMemoryMutationId, getMaxMemoryMutationIdForProjects, GLOBAL_USER_PROFILE_PROJECT_PATH, getProjectState, bumpProjectUserProfileVersion, saveSourceContent, getSourceContents, recordSubagentInvocation, getLatestHistorianInvocationId, renderMessageByOrdinal2, renderVerboseRange2, renderVerboseRangeForTool2, renderItemByTag2 };
4728
+ export { LkgRecoveryFenceError, clearLkgFenceProcessState, lkgFenceRequiresRebuild, lkgRecoveryFenceUnclean, ownsLkgDirtyFence, invalidateCleanLkgRecoveryFence, markLkgRecoveryDirty, rememberUnpublishedAutoSearchNoHint, getUnpublishedAutoSearchNoHint, forgetUnpublishedAutoSearchNoHint, registerAutoSearchWork, cancelAutoSearchWork, PI_IDENTITY_FOLD_GUARD_LIMIT, readPiIdentityFoldGuards, writePiIdentityFoldGuards, readSessionActivity, observeSessionActivity, backfillSessionActivity, readSessionMeta, getOrCreateSessionMeta, updateSessionMeta, advanceToolReclaimWatermark, retryPendingSessionCleanups, retryPendingRustSessionCleanupsForProject, COMPARTMENT_LEASE_RENEWAL_MS, acquireCompartmentLease, renewCompartmentLease, releaseCompartmentLease, releaseCompartmentLeaseBestEffort, isCompartmentLeaseHeld, isNoContentCompartment, HAS_COMPARTMENT_CONTENT_SQL, queueM0Mutation, getMaxM0MutationId, getCompartments, getLastCompartmentEndMessage, getLastCompartmentEndMessageId, getCompartmentsByEndMessageId, appendCompartments, saveRecompStagingPass, getRecompStaging, clearRecompStaging, getRecompPartialRange, setRecompPartialRange, escapeXmlAttr, escapeXmlContent, getUncoveredCompartmentEndThrough, getUncoveredCompartmentEndsThrough, readProjectDocsCanonical, providerResponseFailed, isSuccessfulProviderCompletion, requestPendingMaterialization, pendingMaterializationOrigin, hasPendingMaterializationOrigin, hasExplicitRefreshRequest, clearPendingMaterialization, clearReclaimedMaterialization, clearPendingMaterializationOrigin, recordSystemRefreshOwnership, recordSystemPromptForRequest, recordHeldHeadForRequest, bindSystemPromptResponse, acknowledgeSystemPromptDelivery, deferDeliveredSystemRefresh, clearSystemPromptDelivery, saveLkgSlotToDb, loadPersistedLkgSlot, drainStaleLkgSlots, createDbLkgPersistence, replayLkg, beginServedRequest, noteServedPassPermission, noteServedReplay, countServedRefusal, dropServedRecord, commitServedRequest, registerLkgPersistence, LKG_SNAPSHOT_ARRAY, LKG_SNAPSHOT_OBJECT, LKG_SNAPSHOT_KEY, LKG_SNAPSHOT_STRING, LKG_SNAPSHOT_NUMBER, LKG_SNAPSHOT_BOOLEAN, LKG_SNAPSHOT_NULL, LKG_SNAPSHOT_UNDEFINED, contentSnapshotValue, signatureForFields, lkgContentFields, lkgContentDigestFromFields, isLegacyLkgDigest, legacyLkgDigestFromFields, lkgFieldsMatchDigest, exactReusablePrefix, incrementalLkgContentDigests, lkgSlotRejection, captureSlot, getInMemorySlot, getSlot, dropSlot, TOOL_SWEEP_SCOPED_MARKER, encodePiContentDecision, decodePiContentDecision, getPiContentDecisions, freezePiContentDecision, withNativeReplayWriteBarrier, getNativeReplayState, saveNativeToolInputs, addNativeReasoningIds, copySessionStateForClone, externalHistorianFailureReason, subprocessExitHistorianFailureReason, countHistorianRuns, getRecentFailedHistorianRunTimes, recordHistorianRun, summarizeImportance, tallyFactsByCategory, queueMemoryMutation, getMemoryMutationsForRender, getMemoryMutationsForRenderByProjects, getMaxMemoryMutationId, getMaxMemoryMutationIdForProjects, GLOBAL_USER_PROFILE_PROJECT_PATH, getProjectState, bumpProjectUserProfileVersion, saveSourceContent, getSourceContents, recordSubagentInvocation, getLatestHistorianInvocationId, renderMessageByOrdinal2, renderVerboseRange2, renderVerboseRangeForTool2, renderItemByTag2 };
package/dist/index.js CHANGED
@@ -158,7 +158,7 @@ import {
158
158
  registerTodoStateLifecycle,
159
159
  syncCtxMemoryToolEnabled,
160
160
  registerMagicContextTools
161
- } from "./index-dw9x7k2b.js";
161
+ } from "./index-6t4m64m1.js";
162
162
  import"./index-4knyh1kt.js";
163
163
  import {
164
164
  canonicalModelIdentity,
@@ -516,7 +516,10 @@ import {
516
516
  requestPendingMaterialization,
517
517
  pendingMaterializationOrigin,
518
518
  hasPendingMaterializationOrigin,
519
+ hasExplicitRefreshRequest,
519
520
  clearPendingMaterialization,
521
+ clearReclaimedMaterialization,
522
+ clearPendingMaterializationOrigin,
520
523
  recordSystemRefreshOwnership,
521
524
  recordSystemPromptForRequest,
522
525
  recordHeldHeadForRequest,
@@ -587,7 +590,7 @@ import {
587
590
  getSourceContents,
588
591
  recordSubagentInvocation,
589
592
  getLatestHistorianInvocationId
590
- } from "./index-kqekqrzw.js";
593
+ } from "./index-tygcydj7.js";
591
594
  import {
592
595
  resolveOpenCodeDbPath,
593
596
  assertOpenCodeStoreGeneration,
@@ -854,7 +857,7 @@ import {
854
857
  } from "./index-wmkkxwvf.js";
855
858
  import"./index-71rg8j43.js";
856
859
  import"./index-8d2z6503.js";
857
- import"./index-r4qt07th.js";
860
+ import"./index-mtpsqxev.js";
858
861
  import"./index-cyzsn2hb.js";
859
862
  import {
860
863
  __toESM
@@ -3607,7 +3610,7 @@ function startHostStallProfilerSwitch() {
3607
3610
  // package.json
3608
3611
  var package_default = {
3609
3612
  name: "@cortexkit/pi-magic-context",
3610
- version: "0.49.72",
3613
+ version: "0.49.73",
3611
3614
  type: "module",
3612
3615
  description: "Pi and OMP coding agent extension for Magic Context — cross-session memory and context management",
3613
3616
  main: "dist/index.js",
@@ -24248,6 +24251,15 @@ import * as crypto3 from "node:crypto";
24248
24251
 
24249
24252
  // ../plugin/src/hooks/magic-context/event-resolvers.ts
24250
24253
  var DEFAULT_CONTEXT_LIMIT = 200000;
24254
+ var WRAPUP_WINDOW_UNAVAILABLE = "Cannot run /ctx-wrapup: the model's context window is unknown. Select a model with a configured context window or send a message with that model, then retry.";
24255
+ function readPersistedWrapupWindow(db, sessionId, modelKey) {
24256
+ const { lastUsageContextLimit, lastObservedModelKey } = getOrCreateSessionMeta(db, sessionId);
24257
+ if (!isSaneLimit(lastUsageContextLimit) || !lastObservedModelKey)
24258
+ return;
24259
+ if (modelKey && piModelRefToCanonical(modelKey) !== piModelRefToCanonical(lastObservedModelKey))
24260
+ return;
24261
+ return { contextLimit: lastUsageContextLimit, modelKey: lastObservedModelKey };
24262
+ }
24251
24263
  var clampWarnSeen = new Set;
24252
24264
  function isFinitePositive(v) {
24253
24265
  return typeof v === "number" && Number.isFinite(v) && v > 0;
@@ -24799,6 +24811,7 @@ var canonicalReasons = new Set([
24799
24811
  "ttl_idle",
24800
24812
  "explicit_flush",
24801
24813
  "user_flush",
24814
+ "user_wrapup",
24802
24815
  "fit_retry",
24803
24816
  "pending_materialization",
24804
24817
  "variant_change",
@@ -36568,7 +36581,7 @@ function injectM0M1Pi(state, db, piMessages, entryIds, recomputeM1ThisPass = fal
36568
36581
  const m1HasContent = m1 !== PI_M1_PLACEHOLDER;
36569
36582
  const { m0Tokens, m1Tokens } = cachedInjectionTokenCounts(state.sessionId, m0, m1);
36570
36583
  const m1OverAbsoluteCap = m1HasContent && m1Tokens > m1AbsoluteBudget;
36571
- if (!materialized && !contentionExhausted && m1Recomputed && recomputeM1ThisPass && (memoryUpdateCount > 40 || m1OverAbsoluteCap || m1HasContent && m0Tokens >= M0_DRIFT_RATIO_FLOOR_TOKENS && m1Tokens > m0Tokens * M1_DRIFT_RATIO)) {
36584
+ if (!materialized && !contentionExhausted && m1Recomputed && recomputeM1ThisPass && !state.skipPressureRefold && (memoryUpdateCount > 40 || m1OverAbsoluteCap || m1HasContent && m0Tokens >= M0_DRIFT_RATIO_FLOOR_TOKENS && m1Tokens > m0Tokens * M1_DRIFT_RATIO)) {
36572
36585
  decision = { value: true, reason: "drift" };
36573
36586
  try {
36574
36587
  const result = materializeM0PiWithRetry(state, db, 3, snapshot);
@@ -48761,11 +48774,6 @@ function clearSystemPromptRefresh(sessionId) {
48761
48774
  function hasPendingMaterialization(sessionId) {
48762
48775
  return pendingMaterializationSessions.has(sessionId);
48763
48776
  }
48764
- function consumePendingMaterialization(sessionId) {
48765
- const wasSet = pendingMaterializationSessions.has(sessionId);
48766
- clearPendingMaterialization(pendingMaterializationSessions, sessionId);
48767
- return wasSet;
48768
- }
48769
48777
  function resolveSessionId2(ctx) {
48770
48778
  const sm = ctx.sessionManager;
48771
48779
  if (sm === undefined)
@@ -50907,7 +50915,7 @@ function registerPiContextHandler(pi, baseOptions) {
50907
50915
  inputTokens: usageInputTokens
50908
50916
  },
50909
50917
  isCacheBusting,
50910
- userFlushOrigin: hasPendingMaterializationOrigin(pendingMaterializationSessions, sessionId, "user_flush"),
50918
+ userFlushOrigin: hasExplicitRefreshRequest(pendingMaterializationSessions, sessionId),
50911
50919
  reasoningClearing: {
50912
50920
  keepReasoningTokens: resolveKeepReasoningTokens(options.heuristics?.keepReasoningTokens, resolvePiContextModelKey(ctx)),
50913
50921
  nativeReasoningMayClear: canClearNativeReasoning(ctx.model),
@@ -52323,7 +52331,7 @@ Historian previously failed ${failureCount} time(s), so Magic Context is retryin
52323
52331
  const trigger = checkCompartmentTrigger(db, sessionId, sessionMeta, usage, 0, triggerInputs.executeThresholdPercentage, triggerInputs.triggerBudget, triggerInputs.keepReasoningTokens, triggerInputs.commitClusterTrigger, args.activeTags, boundaryContextLimit, () => readPiHistorianTail(db, sessionId, provider), args.taggerFloor, { canClearReasoning: true }, {
52324
52332
  hardFold: false,
52325
52333
  force: usage.percentage >= historianForceMaterializationPercentage && (usage.percentage >= 95 || getEmergencyInputSample(db, sessionId) === 0),
52326
- explicitFlush: hasPendingMaterializationOrigin(pendingMaterializationSessions, sessionId, "user_flush"),
52334
+ explicitFlush: hasExplicitRefreshRequest(pendingMaterializationSessions, sessionId),
52327
52335
  publishedHistory: args.publishedHistoryRide,
52328
52336
  permission: {
52329
52337
  signedThinkingHold: args.signedThinkingHeld === true,
@@ -52771,6 +52779,9 @@ async function runPipeline(args) {
52771
52779
  let publishedM1RefreshedThisPass = false;
52772
52780
  let prefixPreflightContended = false;
52773
52781
  const softRefreshOpportunity = args.schedulerDecision === "execute";
52782
+ const wrapupPending = hasPendingMaterializationOrigin(pendingMaterializationSessions, args.sessionId, "user_wrapup");
52783
+ if (piM0State)
52784
+ piM0State.skipPressureRefold = wrapupPending;
52774
52785
  const cachedPrefixBeforePreflight = piM0State && (foldDueDecision.value || softRefreshOpportunity) && !emergencyDropEligible ? prepareCachedM0M1PiReplay(piM0State, args.db, injectionPassSnapshot?.cachedRow) : undefined;
52775
52786
  let preFoldInjectionResult = null;
52776
52787
  const persistedM0BeforeFold = injectionPassSnapshot?.sessionMeta ?? args.sessionMeta;
@@ -52940,7 +52951,7 @@ async function runPipeline(args) {
52940
52951
  subagentExecute: args.sessionMeta.isSubagent && args.schedulerDecision === "execute",
52941
52952
  hardFold: foldBustsServedPrefixThisPass || systemPrefixChangedThisPass || requestToolListChanged || firstRenderBust || isCacheBustingPass,
52942
52953
  force: (args.forceMaterialization === true || emergencyDropEligible) && (args.contextUsage.percentage >= 95 || getEmergencyInputSample(args.db, args.sessionId) === 0),
52943
- explicitFlush: !protectedSignedPrefix && (args.userFlushOrigin === true || hasPendingMaterializationOrigin(pendingMaterializationSessions, args.sessionId, "user_flush")),
52954
+ explicitFlush: !protectedSignedPrefix && (args.userFlushOrigin === true || hasExplicitRefreshRequest(pendingMaterializationSessions, args.sessionId)),
52944
52955
  publishedHistory: !prefixPreflightContended && publishedM1RefreshedThisPass
52945
52956
  };
52946
52957
  const ridePermissionGate = {
@@ -53386,7 +53397,7 @@ async function runPipeline(args) {
53386
53397
  if (hasPendingMaterializeSignal) {
53387
53398
  if (args.heuristics === undefined) {
53388
53399
  if (!pendingOps.some((op) => newTargets.get(op.tagId)?.thinkingDropProtected))
53389
- consumePendingMaterialization(args.sessionId);
53400
+ clearReclaimedMaterialization(pendingMaterializationSessions, args.sessionId);
53390
53401
  }
53391
53402
  }
53392
53403
  } catch (err) {
@@ -53558,7 +53569,7 @@ async function runPipeline(args) {
53558
53569
  executedWorkThisPass = true;
53559
53570
  if (hasPendingMaterializeSignal) {
53560
53571
  if (!pendingOps.some((op) => newTargets.get(op.tagId)?.thinkingDropProtected))
53561
- consumePendingMaterialization(args.sessionId);
53572
+ clearReclaimedMaterialization(pendingMaterializationSessions, args.sessionId);
53562
53573
  }
53563
53574
  if (currentTurnId !== null) {
53564
53575
  lastHeuristicsTurnIdBySession.set(args.sessionId, currentTurnId);
@@ -53884,6 +53895,10 @@ async function runPipeline(args) {
53884
53895
  }
53885
53896
  }
53886
53897
  if (!heldHeadReleasedForSystemChange) {
53898
+ if (wrapupPending && isCacheBustingPass && !protectedSignedPrefix && wireInjectionResult.injected && !wireInjectionResult.contentionExhausted) {
53899
+ clearPendingMaterializationOrigin(pendingMaterializationSessions, args.sessionId, "user_wrapup");
53900
+ historyWasConsumedThisPass = true;
53901
+ }
53887
53902
  if (args.isCacheBusting && prefixMutationAllowed) {
53888
53903
  historyRefreshSessions.delete(args.sessionId);
53889
53904
  historyWasConsumedThisPass = true;
@@ -57058,8 +57073,12 @@ The stored history boundaries no longer match this session branch (${ordinalAlig
57058
57073
  const unregister = setRawMessageProvider2(sessionId, provider);
57059
57074
  let holderId = "";
57060
57075
  try {
57061
- const contextLimit = resolvePiContextLimit(ctx, deps.db, sessionId);
57062
- const modelKey = ctx.model ? `${ctx.model.provider}/${ctx.model.id}` : undefined;
57076
+ const window = resolvePiWrapupWindow(ctx, deps.db, sessionId);
57077
+ if (!window)
57078
+ return `## Magic Wrapup — Skipped
57079
+
57080
+ ${WRAPUP_WINDOW_UNAVAILABLE}`;
57081
+ const { contextLimit, modelKey } = window;
57063
57082
  const executeThresholdPercentage = resolveExecuteThreshold(deps.executeThresholdPercentage ?? 65, modelKey, 65, {
57064
57083
  tokensConfig: deps.executeThresholdTokens,
57065
57084
  contextLimit,
@@ -57289,9 +57308,14 @@ Wrapped up ${messagesWrapped} messages into ${compartmentsCreated} compartments;
57289
57308
  try {
57290
57309
  clearEmergencyRecovery(deps.db, sessionId);
57291
57310
  } catch {}
57292
- return `## Magic Wrapup
57311
+ let message = `## Magic Wrapup
57293
57312
 
57294
- Wrapped up ${messagesWrapped} messages into ${compartmentsCreated} compartments. The compacted history is queued and materializes on your next message.`;
57313
+ Wrapped up ${messagesWrapped} messages into ${compartmentsCreated} compartments.`;
57314
+ if (compartmentsCreated > 0) {
57315
+ signalPiPendingMaterialization(sessionId, "user_wrapup");
57316
+ message += " The compacted history applies on your next message, or on the next rebuild if the host restarts first.";
57317
+ }
57318
+ return message;
57295
57319
  } finally {
57296
57320
  clearInterval(renewal);
57297
57321
  deps.shutdownSignal?.removeEventListener("abort", stopRenewal);
@@ -57301,20 +57325,28 @@ Wrapped up ${messagesWrapped} messages into ${compartmentsCreated} compartments.
57301
57325
  unregister();
57302
57326
  }
57303
57327
  }
57304
- function resolvePiContextLimit(ctx, db, sessionId) {
57305
- const usage = ctx.getContextUsage?.();
57306
- let detectedContextLimit;
57307
- try {
57308
- const detected = getOverflowState(db, sessionId).detectedContextLimit;
57309
- if (detected > 0)
57310
- detectedContextLimit = detected;
57311
- } catch {}
57312
- return resolvePiUsableContextLimit({
57313
- rawContextWindow: usage?.contextWindow ?? ctx.model?.contextWindow,
57314
- rawContextWindowSource: "catalog",
57315
- model: ctx.model,
57316
- detectedContextLimit
57317
- }) ?? 128000;
57328
+ function resolvePiWrapupWindow(ctx, db, sessionId) {
57329
+ const model = ctx.model;
57330
+ if (!model)
57331
+ return readPersistedWrapupWindow(db, sessionId);
57332
+ const modelKey = `${model.provider}/${model.id}`;
57333
+ const overflow = getOverflowState(db, sessionId, modelKey);
57334
+ const window = {
57335
+ model,
57336
+ detectedContextLimit: overflow.detectedContextLimit
57337
+ };
57338
+ const provenInputTokens = resolvePiProvenInputFloor({
57339
+ db,
57340
+ sessionId,
57341
+ modelKey,
57342
+ readBranch: () => ctx.sessionManager.getBranch(),
57343
+ providerInputLimit: piPressureEvidenceLimit(resolvePiWindowGeometry(window))
57344
+ });
57345
+ const contextLimit = resolvePiUsableContextLimit({
57346
+ ...window,
57347
+ provenInputTokens: provenInputTokens || undefined
57348
+ });
57349
+ return contextLimit === undefined ? readPersistedWrapupWindow(db, sessionId, modelKey) : { contextLimit, modelKey };
57318
57350
  }
57319
57351
  async function acquireCompartmentLeaseEventually(db, sessionId, renewWrapupMarker, maxWaitMs, signal) {
57320
57352
  const waitStartedAt = Date.now();
@@ -19,7 +19,7 @@ serveWorkerJobs(async (input, port) => {
19
19
  await main();
20
20
  async function main() {
21
21
  if (input.v2ArchiveReader) {
22
- const { serveV2ArchiveReads } = await import("./v2-archive-reader-b7spmyqa.js");
22
+ const { serveV2ArchiveReads } = await import("./v2-archive-reader-ycw2nxf1.js");
23
23
  await serveV2ArchiveReads(port, openConnections);
24
24
  return;
25
25
  }
@@ -51,7 +51,7 @@ serveWorkerJobs(async (input, port) => {
51
51
  await runMessageFtsRowidMapBackfill(db);
52
52
  reply = { kind: "fts-rowid-backfill" };
53
53
  } else if (input.searchArchive) {
54
- const { renderSearchArchive } = await import("./search-archive-3hh7ycvm.js");
54
+ const { renderSearchArchive } = await import("./search-archive-8kcsmnzt.js");
55
55
  const { readRawSessionMessageIdOrdinalsForRangeFromDb } = await import("./read-session-raw-0tytrjye.js");
56
56
  const archive = input.searchArchive;
57
57
  let raw;
@@ -3,7 +3,7 @@ import {
3
3
  renderVerboseRange2,
4
4
  renderVerboseRangeForTool2,
5
5
  renderItemByTag2
6
- } from "./index-kqekqrzw.js";
6
+ } from "./index-tygcydj7.js";
7
7
  import"./index-k7a8x7ba.js";
8
8
  import"./index-mm9y1m77.js";
9
9
  import"./index-hgd00nas.js";
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  renderSearchArchive2
3
3
  } from "./index-cyzsn2hb.js";
4
- import"./index-r4qt07th.js";
4
+ import"./index-mtpsqxev.js";
5
5
  import"./index-8d2z6503.js";
6
6
  import"./index-apff8dej.js";
7
7
  import"./index-6gwasf0v.js";
@@ -34,7 +34,7 @@ import {
34
34
  resolvePiHarnessKind,
35
35
  reportSubagentStartupError,
36
36
  registerMagicContextTools
37
- } from "./index-dw9x7k2b.js";
37
+ } from "./index-6t4m64m1.js";
38
38
  import"./index-vcegxfwg.js";
39
39
  import"./index-5rcjs14a.js";
40
40
  import"./index-cxczethe.js";
@@ -45,14 +45,14 @@ import"./index-9p40dgkm.js";
45
45
  import"./index-79xfn84y.js";
46
46
  import"./index-yhzhdp3m.js";
47
47
  import"./index-cevw58nn.js";
48
- import"./index-kqekqrzw.js";
48
+ import"./index-tygcydj7.js";
49
49
  import"./index-mm9y1m77.js";
50
50
  import"./index-6gwasf0v.js";
51
51
  import"./index-6x556c2q.js";
52
52
  import"./index-nvh6d3bz.js";
53
53
  import"./index-k7a8x7ba.js";
54
54
  import"./index-8d2z6503.js";
55
- import"./index-r4qt07th.js";
55
+ import"./index-mtpsqxev.js";
56
56
  import"./index-cyzsn2hb.js";
57
57
  import"./index-w2snpk0j.js";
58
58
  import"./index-29nw7n1r.js";
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  readV2ArchiveOffThread2,
3
3
  serveV2ArchiveReads2
4
- } from "./index-r4qt07th.js";
4
+ } from "./index-mtpsqxev.js";
5
5
  import"./index-8sqebjzk.js";
6
6
  import"./index-2qtx0q6h.js";
7
7
  import"./index-x2n261wp.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/pi-magic-context",
3
- "version": "0.49.72",
3
+ "version": "0.49.73",
4
4
  "type": "module",
5
5
  "description": "Pi and OMP coding agent extension for Magic Context — cross-session memory and context management",
6
6
  "main": "dist/index.js",