@cortexkit/pi-magic-context 0.36.1 → 0.37.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -87,6 +87,7 @@ import {
87
87
  deleteUserMemoryCandidates,
88
88
  deliverNoteNudgeAtomic,
89
89
  deriveTagLoadFloor,
90
+ deriveWindowGeometry,
90
91
  describeError,
91
92
  dismissUserMemory,
92
93
  drainCommitBacklogForProject,
@@ -113,6 +114,7 @@ import {
113
114
  findAdoptableFallbackTags,
114
115
  findLastModelKeyFromBranch,
115
116
  findPiFallbackToolOwnerTags,
117
+ formatWindowDerivationLine,
116
118
  getActivePrimers,
117
119
  getActiveTagTokenAggregate,
118
120
  getActiveTagsBySession,
@@ -205,6 +207,7 @@ import {
205
207
  getUnmappedMemoryIds,
206
208
  getUserMemoryCandidates,
207
209
  getVisibleMemoryIds,
210
+ getWindowOverlay,
208
211
  getWrapupInProgressState,
209
212
  hasMeaningfulUserText,
210
213
  hasMemoryClassifiedAtColumn,
@@ -242,6 +245,7 @@ import {
242
245
  markProtectedTailPolicyV3Seeded,
243
246
  memoryNeedsCue,
244
247
  migrateMagicContextConfigLocations,
248
+ modelRefLookupOrder,
245
249
  nextDueAtMs,
246
250
  nextOccurrence,
247
251
  normalizeText,
@@ -275,7 +279,6 @@ import {
275
279
  readGitChangedFilesSince,
276
280
  readGitFileChangeTimesSince,
277
281
  readGitHead,
278
- readNewMemoriesForM1Union,
279
282
  readPiSessionMessages,
280
283
  readProjectDocsCanonical,
281
284
  readRawSessionMessages,
@@ -310,7 +313,6 @@ import {
310
313
  resetLastNudgeCycleIfTailShrank,
311
314
  resolveCompactionModeRecord,
312
315
  resolveGitTopLevel,
313
- resolveLimit,
314
316
  resolveModelConfigOrDefault,
315
317
  resolveModelRefForOmp,
316
318
  resolveModelRefForPi,
@@ -319,6 +321,7 @@ import {
319
321
  resolveProjectIdentity,
320
322
  resolveProjectIdentityForSession,
321
323
  resolveProjectIdentityStrict,
324
+ resolveWindowOverlayFacts,
322
325
  resolveWorkspaceIdentitySet,
323
326
  resolveWorkspaceShareCategories,
324
327
  retryPendingSessionCleanups,
@@ -373,11 +376,12 @@ import {
373
376
  updateUserMemoryContent,
374
377
  updateWrapupInProgress,
375
378
  verificationFileExists,
379
+ wakePlaneStatus,
376
380
  withContentLanguageDirective,
377
381
  withMigrationLanguageDirective,
378
382
  withRawMessageProvider,
379
383
  withRawSessionMessageCache
380
- } from "./index-zxgbtsnj.js";
384
+ } from "./index-kvttksef.js";
381
385
  import {
382
386
  pushNotification
383
387
  } from "./index-hw34xmzk.js";
@@ -389,7 +393,7 @@ import {
389
393
  log,
390
394
  sessionLog,
391
395
  setHarness
392
- } from "./index-npnqc564.js";
396
+ } from "./index-hk6sj7dn.js";
393
397
  import {
394
398
  __require,
395
399
  __toESM
@@ -887,7 +891,7 @@ var LIMIT_EXTRACTION_PATTERNS = [
887
891
  pattern: /too large for model with (\d+) maximum context length/i,
888
892
  provenance: "combined"
889
893
  },
890
- { pattern: /context size.*(\d+) tokens?/i, provenance: "combined" },
894
+ { pattern: /context size[^0-9]{0,40}(\d{4,})\s*tokens?/i, provenance: "combined" },
891
895
  { pattern: /exceeds? the context length of (\d+)/i, provenance: "combined" },
892
896
  {
893
897
  pattern: />\s*(\d+)\s*(?:tokens?\s*)?(?:maximum|max|limit)\b/i,
@@ -1510,11 +1514,13 @@ function isFinitePositive(v) {
1510
1514
  }
1511
1515
  function* modelKeyLookupOrder(modelKey) {
1512
1516
  const slash = modelKey.indexOf("/");
1513
- const provider = slash >= 0 ? modelKey.slice(0, slash) : "";
1517
+ const providerRefs = slash >= 0 ? modelRefLookupOrder(modelKey) : [];
1514
1518
  let modelId = slash >= 0 ? modelKey.slice(slash + 1) : modelKey;
1515
1519
  while (modelId.length > 0) {
1516
- if (provider)
1517
- yield `${provider}/${modelId}`;
1520
+ for (const providerRef of providerRefs) {
1521
+ const providerSlash = providerRef.indexOf("/");
1522
+ yield `${providerRef.slice(0, providerSlash)}/${modelId}`;
1523
+ }
1518
1524
  yield modelId;
1519
1525
  const lastDash = modelId.lastIndexOf("-");
1520
1526
  if (lastDash <= 0)
@@ -3761,7 +3767,7 @@ async function sendIgnoredMessageNow(client, sessionId, text, params, forcePersi
3761
3767
  queueIgnoredNotification({ client, sessionId, text, params, forcePersist });
3762
3768
  return "queued";
3763
3769
  }
3764
- const { waitForSafeNotificationTarget } = await import("./safe-notification-target-0s6j4m9f.js");
3770
+ const { waitForSafeNotificationTarget } = await import("./safe-notification-target-7n7s6xv7.js");
3765
3771
  if (await waitForSafeNotificationTarget(client, sessionId) === "skip") {
3766
3772
  sessionLog(sessionId, "notification skipped (session not titled yet)");
3767
3773
  return "skipped";
@@ -7272,6 +7278,9 @@ var DEFAULT_MAX_CHECKS = 10;
7272
7278
  var DEFAULT_SWEEP_BUDGET_MS = 15000;
7273
7279
  var MAX_FAILURES_BEFORE_REAUTHOR = 3;
7274
7280
  async function runDueCompiledSmartNoteChecks(args) {
7281
+ if (await wakePlaneStatus() === "present") {
7282
+ return { ran: 0, surfaced: 0, failed: 0, networkFailed: 0 };
7283
+ }
7275
7284
  const startedAt = Date.now();
7276
7285
  const now = args.now ?? startedAt;
7277
7286
  const due = getDueCompiledSmartNoteChecks(args.db, args.projectIdentity, now, args.maxChecks ?? DEFAULT_MAX_CHECKS, args.retinaHandoff);
@@ -7401,6 +7410,11 @@ function createPromptAbortSignal(parent, timeoutMs, timeoutMessage) {
7401
7410
  };
7402
7411
  }
7403
7412
  async function evaluateSmartNotes(args) {
7413
+ if (await wakePlaneStatus() === "present") {
7414
+ const pending = getPendingSmartNotes(args.db, args.projectIdentity).length;
7415
+ log("[dreamer] evaluate-smart-notes: skipped (wake plane active)");
7416
+ return { surfaced: 0, pending, ran: false };
7417
+ }
7404
7418
  const projectRoot = args.sessionDirectory ?? args.projectIdentity;
7405
7419
  const moduleBridge = getModuleNoteEvaluationBridge(args.projectIdentity);
7406
7420
  await moduleBridge?.sync();
@@ -16370,6 +16384,7 @@ function getPiToolResultCallId(message) {
16370
16384
  return typeof callId === "string" && callId.length > 0 ? callId : null;
16371
16385
  }
16372
16386
  var PI_M1_PLACEHOLDER = "<session-history-since>(no new content since last materialization)</session-history-since>";
16387
+ var MAX_FORCED_MEMORIES_PER_DELTA = 10;
16373
16388
  var PI_M0_UPGRADE_STATE = "pi-m0m1-v2";
16374
16389
  var EMPTY_MAX_COMPARTMENT_SEQ = -1;
16375
16390
  function historySliceTokensPi(m0Text) {
@@ -16600,7 +16615,7 @@ function readCurrentMarkersFromCompartments(db, state2, compartments, projectDoc
16600
16615
  compartmentRenderEpoch: COMPARTMENT_RENDER_EPOCH,
16601
16616
  lastBaselineEndMessageId: lastBaselineEndMessageId(compartments),
16602
16617
  systemHash: (state2.hardSignals ?? EMPTY_PI_HARD_SIGNALS).systemHash,
16603
- modelKey: (state2.hardSignals ?? EMPTY_PI_HARD_SIGNALS).modelKey,
16618
+ modelKey: piModelRefToCanonical((state2.hardSignals ?? EMPTY_PI_HARD_SIGNALS).modelKey),
16604
16619
  projectIdentity: state2.projectIdentity,
16605
16620
  muralEnabled: state2.muralEnabled === true,
16606
16621
  renderBudgetIdentity: renderBudgetIdentityPi(state2)
@@ -16628,7 +16643,9 @@ function mustMaterializePi(state2, db, currentCompartmentsOverride) {
16628
16643
  return { value: true, reason: "render_config" };
16629
16644
  }
16630
16645
  const hard = state2.hardSignals ?? EMPTY_PI_HARD_SIGNALS;
16631
- if (hard.modelKey !== "" && hard.modelKey !== (meta.cachedM0ModelKey ?? "")) {
16646
+ const canonicalHardModelKey = piModelRefToCanonical(hard.modelKey);
16647
+ const canonicalCachedModelKey = piModelRefToCanonical(meta.cachedM0ModelKey ?? "");
16648
+ if (canonicalHardModelKey !== "" && canonicalHardModelKey !== canonicalCachedModelKey) {
16632
16649
  return { value: true, reason: "model_change" };
16633
16650
  }
16634
16651
  if (hard.systemHash !== "" && hard.systemHash !== (meta.cachedM0SystemHash ?? "")) {
@@ -16763,7 +16780,7 @@ function readFrozenM0InputsPi(state2, db, docs = readProjectDocsForPiM0(state2),
16763
16780
  compartmentRenderEpoch: COMPARTMENT_RENDER_EPOCH,
16764
16781
  lastBaselineEndMessageId: lastBaselineEndMessageId(compartments),
16765
16782
  systemHash: (state2.hardSignals ?? EMPTY_PI_HARD_SIGNALS).systemHash,
16766
- modelKey: (state2.hardSignals ?? EMPTY_PI_HARD_SIGNALS).modelKey,
16783
+ modelKey: piModelRefToCanonical((state2.hardSignals ?? EMPTY_PI_HARD_SIGNALS).modelKey),
16767
16784
  projectIdentity: state2.projectIdentity,
16768
16785
  muralEnabled: state2.muralEnabled === true,
16769
16786
  renderBudgetIdentity: renderBudgetIdentityPi(state2)
@@ -16889,49 +16906,74 @@ function materializeM0PiWithRetry(state2, db, maxRetries = 3) {
16889
16906
  throw lastError ?? new PiMaterializeContentionError("materialization contention exhausted");
16890
16907
  }
16891
16908
  function renderMemoryUpdatesBlockPi(args) {
16892
- if (args.renderedMemoryIds.length === 0)
16893
- return { block: "", count: 0 };
16894
16909
  const renderedIds = new Set(args.renderedMemoryIds);
16895
16910
  const mutations = args.workspace.isWorkspaced ? getMemoryMutationsForRenderByProjects(args.db, args.workspace.expandedIdentities, args.afterId, args.renderedMemoryIds) : getMemoryMutationsForRender(args.db, args.projectPath, args.afterId, args.renderedMemoryIds);
16896
- if (mutations.length === 0)
16897
- return { block: "", count: 0 };
16911
+ if (mutations.length === 0) {
16912
+ return { block: "", count: 0, forcedMemoryIds: [] };
16913
+ }
16914
+ const forcedIds = new Set;
16898
16915
  const lines = [
16899
16916
  "These memories changed since the snapshot below — trust these:"
16900
16917
  ];
16901
16918
  for (const mutation of mutations) {
16902
- if (mutation.mutationType === "update") {
16903
- lines.push(` <updated id="${mutation.targetMemoryId}">${escapeXmlContent(mutation.newContent ?? "")}</updated>`);
16904
- continue;
16905
- }
16906
16919
  if (mutation.mutationType === "superseded") {
16907
- if (mutation.supersededById !== null && renderedIds.has(mutation.supersededById)) {
16908
- lines.push(` <superseded id="${mutation.targetMemoryId}" by="${mutation.supersededById}"/>`);
16920
+ const replacementId = mutation.supersededById;
16921
+ if (replacementId !== null && !renderedIds.has(replacementId) && args.eligibleMemoryIds.has(replacementId)) {
16922
+ forcedIds.add(replacementId);
16923
+ }
16924
+ if (!renderedIds.has(mutation.targetMemoryId))
16925
+ continue;
16926
+ if (replacementId !== null && args.eligibleMemoryIds.has(replacementId)) {
16927
+ lines.push(` <superseded id="${mutation.targetMemoryId}" by="${replacementId}"/>`);
16909
16928
  } else {
16910
16929
  lines.push(` <removed id="${mutation.targetMemoryId}"/>`);
16911
16930
  }
16912
16931
  continue;
16913
16932
  }
16933
+ if (!renderedIds.has(mutation.targetMemoryId)) {
16934
+ if (mutation.visibilityChanged && args.eligibleMemoryIds.has(mutation.targetMemoryId)) {
16935
+ forcedIds.add(mutation.targetMemoryId);
16936
+ }
16937
+ continue;
16938
+ }
16939
+ if (!args.eligibleMemoryIds.has(mutation.targetMemoryId)) {
16940
+ lines.push(` <removed id="${mutation.targetMemoryId}"/>`);
16941
+ continue;
16942
+ }
16943
+ if (mutation.visibilityChanged && mutation.newContent === null)
16944
+ continue;
16945
+ if (mutation.mutationType === "update") {
16946
+ lines.push(` <updated id="${mutation.targetMemoryId}">${escapeXmlContent(mutation.newContent ?? "")}</updated>`);
16947
+ continue;
16948
+ }
16914
16949
  lines.push(` <removed id="${mutation.targetMemoryId}"/>`);
16915
16950
  }
16951
+ const forcedMemoryIds = [...forcedIds].sort((left, right) => left - right).slice(0, MAX_FORCED_MEMORIES_PER_DELTA);
16952
+ if (lines.length === 1)
16953
+ return { block: "", count: 0, forcedMemoryIds };
16916
16954
  return {
16917
16955
  block: `<memory-updates>
16918
16956
  ${lines.join(`
16919
16957
  `)}
16920
16958
  </memory-updates>`,
16921
- count: mutations.length
16959
+ count: lines.length - 1,
16960
+ forcedMemoryIds
16922
16961
  };
16923
16962
  }
16924
16963
  function renderM1PiWithMetadata(state2, db, markers, renderedMemoryIds, compartmentsOverride) {
16925
16964
  const sections = [];
16926
16965
  const workspace = resolveWorkspaceRenderContextPi(state2, db);
16927
16966
  const memPath = memoryProjectPath(state2);
16967
+ const eligibleMemories = memPath ? workspace.isWorkspaced ? getMemoriesByProjects(db, workspace.expandedIdentities, ["active", "permanent"], markers.materializedAt, workspace.ownIdentities, workspace.shareCategories) : getMemoriesByProject(db, memPath, ["active", "permanent"], markers.materializedAt) : [];
16968
+ const eligibleMemoryIds = new Set(eligibleMemories.map((memory) => memory.id));
16928
16969
  const memoryUpdates = memPath ? renderMemoryUpdatesBlockPi({
16929
16970
  db,
16930
16971
  projectPath: memPath,
16931
16972
  workspace,
16932
16973
  afterId: markers.maxMemoryMutationId,
16933
- renderedMemoryIds
16934
- }) : { block: undefined, count: 0 };
16974
+ renderedMemoryIds,
16975
+ eligibleMemoryIds
16976
+ }) : { block: undefined, count: 0, forcedMemoryIds: [] };
16935
16977
  if (memoryUpdates.block)
16936
16978
  sections.push(memoryUpdates.block);
16937
16979
  const newCompartments = (compartmentsOverride ?? getRenderableCompartmentsPi(db, state2)).filter((compartment) => compartment.sequence > markers.maxCompartmentSeq);
@@ -16943,21 +16985,24 @@ function renderM1PiWithMetadata(state2, db, markers, renderedMemoryIds, compartm
16943
16985
  ${body}
16944
16986
  </new-compartments>`);
16945
16987
  }
16946
- const newMemories = memPath ? workspace.isWorkspaced ? readNewMemoriesForM1Union(db, workspace.expandedIdentities, markers.maxMemoryId, markers.materializedAt, workspace.ownIdentities, workspace.shareCategories) : getMemoriesByProject(db, memPath, ["active", "permanent"], markers.materializedAt).filter((memory) => memory.id > markers.maxMemoryId) : [];
16947
- if (newMemories.length > 0) {
16948
- const memoryBudget = state2.injectionBudgetTokens ?? DEFAULT_MEMORY_BUDGET_TOKENS;
16949
- const memoryRenderOptions = {
16950
- sourceNameByMemoryId: sourceNamesForPiMemories({
16951
- memories: newMemories,
16952
- projectPath: memPath,
16953
- workspace
16954
- })
16955
- };
16956
- const trimmedNewMemories = trimMemoriesToBudgetV2(state2.sessionId, newMemories, Math.max(1, Math.floor(memoryBudget * 0.25)), memoryRenderOptions).renderOrder;
16957
- const newMemoriesBlock = renderMemoryBlockV2(trimmedNewMemories, "new-memories", memoryRenderOptions);
16958
- if (newMemoriesBlock)
16959
- sections.push(newMemoriesBlock);
16960
- }
16988
+ const forcedMemoryIds = new Set(memoryUpdates.forcedMemoryIds);
16989
+ const newMemories = eligibleMemories.filter((memory) => memory.id > markers.maxMemoryId && !forcedMemoryIds.has(memory.id));
16990
+ const memoryBudget = state2.injectionBudgetTokens ?? DEFAULT_MEMORY_BUDGET_TOKENS;
16991
+ const memoryRenderOptions = {
16992
+ sourceNameByMemoryId: sourceNamesForPiMemories({
16993
+ memories: eligibleMemories,
16994
+ projectPath: memPath,
16995
+ workspace
16996
+ })
16997
+ };
16998
+ const trimmedNewMemories = trimMemoriesToBudgetV2(state2.sessionId, newMemories, Math.max(1, Math.floor(memoryBudget * 0.25)), memoryRenderOptions).renderOrder;
16999
+ const deltaMemories = [
17000
+ ...trimmedNewMemories,
17001
+ ...eligibleMemories.filter((memory) => forcedMemoryIds.has(memory.id))
17002
+ ];
17003
+ const newMemoriesBlock = renderMemoryBlockV2(deltaMemories, "new-memories", memoryRenderOptions);
17004
+ if (newMemoriesBlock)
17005
+ sections.push(newMemoriesBlock);
16961
17006
  const currentUserProfileVersion = getProjectState(db, GLOBAL_USER_PROFILE_PROJECT_PATH)?.projectUserProfileVersion ?? 0;
16962
17007
  if (currentUserProfileVersion !== markers.projectUserProfileVersion) {
16963
17008
  const profileBudget = state2.userProfileBudgetTokens ?? DEFAULT_USER_PROFILE_BUDGET_TOKENS;
@@ -17072,7 +17117,7 @@ function cachedPiRowMatchesSnapshot(args) {
17072
17117
  const rowMarkers = markersFromCachedPiRow(args.row, args.compartmentsForNormalization);
17073
17118
  if (!rowMarkers)
17074
17119
  return false;
17075
- return bufferEqualsNullable(args.row.cached_m0_bytes, args.m0Bytes) && rowMarkers.projectMemoryEpoch === args.markers.projectMemoryEpoch && rowMarkers.projectUserProfileVersion === args.markers.projectUserProfileVersion && rowMarkers.maxCompartmentSeq === args.markers.maxCompartmentSeq && rowMarkers.maxMemoryId === args.markers.maxMemoryId && rowMarkers.maxMutationId === args.markers.maxMutationId && rowMarkers.maxMemoryMutationId === args.markers.maxMemoryMutationId && rowMarkers.materializedAt === args.markers.materializedAt && rowMarkers.sessionFactsVersion === args.markers.sessionFactsVersion && (rowMarkers.upgradeState ?? null) === (args.markers.upgradeState ?? null) && rowMarkers.compartmentRenderEpoch === args.markers.compartmentRenderEpoch && (rowMarkers.systemHash ?? "") === (args.markers.systemHash ?? "") && (rowMarkers.modelKey ?? "") === (args.markers.modelKey ?? "") && (rowMarkers.projectIdentity ?? null) === (args.markers.projectIdentity ?? null) && (rowMarkers.workspaceFingerprint ?? null) === (args.markers.workspaceFingerprint ?? null);
17120
+ return bufferEqualsNullable(args.row.cached_m0_bytes, args.m0Bytes) && rowMarkers.projectMemoryEpoch === args.markers.projectMemoryEpoch && rowMarkers.projectUserProfileVersion === args.markers.projectUserProfileVersion && rowMarkers.maxCompartmentSeq === args.markers.maxCompartmentSeq && rowMarkers.maxMemoryId === args.markers.maxMemoryId && rowMarkers.maxMutationId === args.markers.maxMutationId && rowMarkers.maxMemoryMutationId === args.markers.maxMemoryMutationId && rowMarkers.materializedAt === args.markers.materializedAt && rowMarkers.sessionFactsVersion === args.markers.sessionFactsVersion && (rowMarkers.upgradeState ?? null) === (args.markers.upgradeState ?? null) && rowMarkers.compartmentRenderEpoch === args.markers.compartmentRenderEpoch && (rowMarkers.systemHash ?? "") === (args.markers.systemHash ?? "") && piModelRefToCanonical(rowMarkers.modelKey ?? "") === piModelRefToCanonical(args.markers.modelKey ?? "") && (rowMarkers.projectIdentity ?? null) === (args.markers.projectIdentity ?? null) && (rowMarkers.workspaceFingerprint ?? null) === (args.markers.workspaceFingerprint ?? null);
17076
17121
  }
17077
17122
  function adoptCachedPiProjectIdentity(db, state2) {
17078
17123
  db.prepare("UPDATE session_meta SET cached_m0_project_identity = ? WHERE session_id = ? AND cached_m0_project_identity IS NULL").run(state2.projectIdentity, state2.sessionId);
@@ -17386,13 +17431,44 @@ function isSentinelPart(part) {
17386
17431
  }
17387
17432
 
17388
17433
  // src/pi-context-limit.ts
17389
- function resolvePiUsableContextLimit(args) {
17390
- const rawContext = isSaneLimit(args.rawContextWindow) ? args.rawContextWindow : undefined;
17391
- const detected = typeof args.detectedContextLimit === "number" && Number.isFinite(args.detectedContextLimit) && args.detectedContextLimit >= 1024 ? args.detectedContextLimit : undefined;
17392
- const context = rawContext !== undefined && detected !== undefined ? Math.min(rawContext, detected) : rawContext ?? detected;
17393
- if (context === undefined)
17434
+ var MIN_SANE_LIMIT = 16000;
17435
+ var MAX_SANE_LIMIT = 1e7;
17436
+ function isSaneLimit2(value) {
17437
+ return typeof value === "number" && Number.isFinite(value) && value >= MIN_SANE_LIMIT && value <= MAX_SANE_LIMIT;
17438
+ }
17439
+ function resolvePiWindowGeometry(args) {
17440
+ const runtimeWindow = isSaneLimit2(args.rawContextWindow) ? args.rawContextWindow : isSaneLimit2(args.model?.contextWindow) ? args.model.contextWindow : undefined;
17441
+ const persistedUsable = isSaneLimit2(args.persistedInputTokens) && typeof args.persistedPercentage === "number" && Number.isFinite(args.persistedPercentage) && args.persistedPercentage > 0 ? args.persistedInputTokens / (args.persistedPercentage / 100) : undefined;
17442
+ const persistedWindow = isSaneLimit2(args.persistedInputTokens) && typeof args.persistedPercentage === "number" && Number.isFinite(args.persistedPercentage) && args.persistedPercentage > 0 ? args.persistedInputTokens / (args.persistedPercentage / 100) : undefined;
17443
+ const context = runtimeWindow ?? persistedWindow;
17444
+ if (!isSaneLimit2(context))
17394
17445
  return;
17395
- return resolveLimit({ context, output: args.model?.maxTokens }, args.model?.provider ?? "unknown", args.model?.id ?? "unknown");
17446
+ const providerID = args.model?.provider ?? "unknown";
17447
+ const modelID = args.model?.id ?? "unknown";
17448
+ const result = deriveWindowGeometry(providerID, modelID, {
17449
+ context,
17450
+ output: args.model?.maxTokens
17451
+ }, {
17452
+ overlay: resolveWindowOverlayFacts(providerID, modelID, getWindowOverlay()),
17453
+ contextCap: isSaneLimit2(args.detectedContextLimit) ? args.detectedContextLimit : undefined,
17454
+ reserveConfig: args.reserveConfig,
17455
+ harness: "pi"
17456
+ });
17457
+ if (!result || !isSaneLimit2(persistedUsable))
17458
+ return result;
17459
+ const usableSoft = Math.round(persistedUsable);
17460
+ return {
17461
+ ...result,
17462
+ usableSoft,
17463
+ usableHard: Math.max(usableSoft, result.usableHard),
17464
+ derivation: {
17465
+ ...result.derivation,
17466
+ reserve: Math.max(0, result.derivation.window - usableSoft)
17467
+ }
17468
+ };
17469
+ }
17470
+ function resolvePiUsableContextLimit(args) {
17471
+ return resolvePiWindowGeometry(args)?.usableSoft;
17396
17472
  }
17397
17473
 
17398
17474
  // src/pi-historian-runner.ts
@@ -22796,6 +22872,9 @@ function extractStableId(msg, index, entryIds) {
22796
22872
  // src/context-handler.ts
22797
22873
  var EMERGENCY_BLOCK_PERCENTAGE = 95;
22798
22874
  var FORWARD_PRESSURE_LIMIT_FACTOR = 0.85;
22875
+ function isPiHardCacheExpired(lastResponseTime, ttlMs, now) {
22876
+ return lastResponseTime > 0 && now - lastResponseTime > ttlMs;
22877
+ }
22799
22878
  function applyForwardPressureFloor(trailingPercentage, trailingInputTokens, piUsageTokens, correctedLimit) {
22800
22879
  const forwardTokens = typeof piUsageTokens === "number" && piUsageTokens > 0 ? piUsageTokens : 0;
22801
22880
  if (forwardTokens === 0 || !isSaneLimit(correctedLimit)) {
@@ -23632,7 +23711,7 @@ function registerPiContextHandler(pi, baseOptions) {
23632
23711
  }
23633
23712
  const previousModelKey = liveModelBySession.get(sessionId);
23634
23713
  const currentModelKey = resolvePiContextModelKey(ctx);
23635
- const modelChanged = previousModelKey !== undefined && currentModelKey !== undefined && previousModelKey !== currentModelKey;
23714
+ const modelChanged = previousModelKey !== undefined && currentModelKey !== undefined && piModelRefToCanonical(previousModelKey) !== piModelRefToCanonical(currentModelKey);
23636
23715
  if (currentModelKey !== undefined) {
23637
23716
  liveModelBySession.set(sessionId, currentModelKey);
23638
23717
  }
@@ -23731,11 +23810,12 @@ function registerPiContextHandler(pi, baseOptions) {
23731
23810
  usageContextLimit = modelWindow;
23732
23811
  }
23733
23812
  }
23734
- usageContextLimit = resolvePiUsableContextLimit({
23813
+ const windowGeometry = resolvePiWindowGeometry({
23735
23814
  rawContextWindow: usageContextLimit,
23736
23815
  model: ctx.model,
23737
23816
  detectedContextLimit
23738
23817
  });
23818
+ usageContextLimit = windowGeometry?.usableSoft;
23739
23819
  const effectiveExecuteThresholdPercentage = resolveExecuteThreshold(schedulerConfig.executeThresholdPercentage, modelKey, 65, {
23740
23820
  tokensConfig: schedulerConfig.executeThresholdTokens,
23741
23821
  contextLimit: usageContextLimit,
@@ -23807,7 +23887,9 @@ function registerPiContextHandler(pi, baseOptions) {
23807
23887
  schedulerDecision = midTurnAdjustedSchedulerDecision;
23808
23888
  sessionLog(sessionId, `[boundary-exec] base=${schedulerDecisionEarly} bypass=${bypassReason} midTurn=${midTurn} effective=${midTurnAdjustedSchedulerDecision} sideEffect=${sideEffect}`);
23809
23889
  const forceMaterialization = !options.compactionOff && usagePercentage >= forceMaterializationPercentage;
23810
- const isEmergency = !options.compactionOff && usagePercentage >= EMERGENCY_BLOCK_PERCENTAGE;
23890
+ const hardUsagePercentage = needsEmergencyBump ? Math.max(EMERGENCY_BLOCK_PERCENTAGE, usagePercentage) : windowGeometry?.usableHard && usageInputTokens > 0 ? usageInputTokens / windowGeometry.usableHard * 100 : usagePercentage;
23891
+ const emergencyPercentage = ctx.model ? hardUsagePercentage : usagePercentage;
23892
+ const isEmergency = !options.compactionOff && emergencyPercentage >= EMERGENCY_BLOCK_PERCENTAGE;
23811
23893
  if (isEmergency) {
23812
23894
  const lastNotifiedAt = lastEmergencyNotificationAtMs.get(sessionId) ?? 0;
23813
23895
  const now = Date.now();
@@ -24618,7 +24700,7 @@ async function runPipeline(args) {
24618
24700
  return {
24619
24701
  systemHash: typeof hardMeta.systemPromptHash === "string" ? hardMeta.systemPromptHash : "",
24620
24702
  modelKey: liveModelBySession.get(args.sessionId) ?? "",
24621
- cacheExpired: hardMeta.lastResponseTime > 0 && Date.now() - hardMeta.lastResponseTime >= piTtlMs,
24703
+ cacheExpired: isPiHardCacheExpired(hardMeta.lastResponseTime, piTtlMs, Date.now()),
24622
24704
  lastResponseTime: hardMeta.lastResponseTime
24623
24705
  };
24624
24706
  })() : undefined;
@@ -24689,8 +24771,9 @@ async function runPipeline(args) {
24689
24771
  }
24690
24772
  const deferredMaterializationWasPending = deferredMaterializationSessions.has(args.sessionId);
24691
24773
  const deferredHistoryRefreshWasPending = deferredHistoryWasPendingAtPassStart;
24692
- const pendingOps = getPendingOps(args.db, args.sessionId);
24693
- const pendingOperationTags = getTagsForPendingOperations(args.db, args.sessionId, pendingOps.map((operation) => operation.tagId), args.protectedTags, RECENT_TOOL_SKELETON_WINDOW);
24774
+ const shouldReadPendingOps = !args.compactionOff && (args.schedulerDecision === "execute" || args.forceMaterialization || hasPendingMaterializeSignal || m0HardFoldThisPass || historianRunning);
24775
+ const pendingOps = shouldReadPendingOps ? getPendingOps(args.db, args.sessionId) : [];
24776
+ const pendingOperationTags = pendingOps.length > 0 ? getTagsForPendingOperations(args.db, args.sessionId, pendingOps.map((operation) => operation.tagId), args.protectedTags, RECENT_TOOL_SKELETON_WINDOW) : [];
24694
24777
  const baseShouldApplyPendingOps = args.schedulerDecision === "execute" || args.forceMaterialization || hasPendingMaterializeSignal || m0HardFoldThisPass;
24695
24778
  const deferredMaterialize = canConsumeDeferredLate && deferredMaterializationWasPending;
24696
24779
  const deferredHistoryRefresh = canConsumeDeferredLate && deferredHistoryRefreshWasPending;
@@ -27542,7 +27625,7 @@ function formatExecuteThreshold(detail, contextLimit) {
27542
27625
  }
27543
27626
  return `${percentage}%${clampNote}`;
27544
27627
  }
27545
- function executeStatus(db, sessionId, protectedTags, executeThresholdPercentageConfig = DEFAULT_EXECUTE_THRESHOLD_PERCENTAGE, liveModelKey, historyBudgetPercentage, commitClusterTrigger, executeThresholdTokens, contextLimit, dreamer) {
27628
+ function executeStatus(db, sessionId, protectedTags, executeThresholdPercentageConfig = DEFAULT_EXECUTE_THRESHOLD_PERCENTAGE, liveModelKey, historyBudgetPercentage, commitClusterTrigger, executeThresholdTokens, contextLimit, dreamer, windowGeometry) {
27546
27629
  const thresholdDetail = resolveExecuteThresholdDetail(executeThresholdPercentageConfig, liveModelKey, DEFAULT_EXECUTE_THRESHOLD_PERCENTAGE, {
27547
27630
  tokensConfig: executeThresholdTokens,
27548
27631
  contextLimit,
@@ -27603,7 +27686,7 @@ function executeStatus(db, sessionId, protectedTags, executeThresholdPercentageC
27603
27686
  ] : [], ...formatDreamTaskBacklogs(dreamer.backlog).split("\\n"));
27604
27687
  }
27605
27688
  if (meta.lastContextPercentage > 0 || meta.lastInputTokens > 0) {
27606
- lines.push("", "### Context Usage", `- Last percentage: ${meta.lastContextPercentage.toFixed(1)}%`, `- Last input tokens: ${meta.lastInputTokens.toLocaleString()}`, `- Resolved context limit: ${displayContextLimit > 0 ? displayContextLimit.toLocaleString() : "unknown"}`, `- Proactive compartment evaluation: ${proactiveCompartmentTrigger}%`, `- Post-drop target for historian: ${(executeThresholdPercentage * POST_DROP_TARGET_RATIO).toFixed(0)}% (${executeThresholdPercentage}% * ${POST_DROP_TARGET_RATIO})`, `- Commit cluster trigger: ${commitClusterTrigger?.enabled !== false ? `enabled (min ${commitClusterTrigger?.min_clusters ?? 3} clusters)` : "disabled"}, tail-size trigger: > 3x compartment budget`);
27689
+ lines.push("", "### Context Usage", `- Last percentage: ${meta.lastContextPercentage.toFixed(1)}%`, `- Last input tokens: ${meta.lastInputTokens.toLocaleString()}`, `- Resolved context limit: ${displayContextLimit > 0 ? displayContextLimit.toLocaleString() : "unknown"}`, ...windowGeometry ? [`- ${formatWindowDerivationLine(meta.lastInputTokens, windowGeometry)}`] : [], `- Proactive compartment evaluation: ${proactiveCompartmentTrigger}%`, `- Post-drop target for historian: ${(executeThresholdPercentage * POST_DROP_TARGET_RATIO).toFixed(0)}% (${executeThresholdPercentage}% * ${POST_DROP_TARGET_RATIO})`, `- Commit cluster trigger: ${commitClusterTrigger?.enabled !== false ? `enabled (min ${commitClusterTrigger?.min_clusters ?? 3} clusters)` : "disabled"}, tail-size trigger: > 3x compartment budget`);
27607
27690
  }
27608
27691
  const compartments = getCompartments(db, sessionId);
27609
27692
  let historyBlockTokens = 0;
@@ -27704,7 +27787,7 @@ ${c.content}
27704
27787
  // package.json
27705
27788
  var package_default = {
27706
27789
  name: "@cortexkit/pi-magic-context",
27707
- version: "0.36.1",
27790
+ version: "0.37.0",
27708
27791
  type: "module",
27709
27792
  description: "Pi and OMP coding agent extension for Magic Context — cross-session memory and context management",
27710
27793
  main: "dist/index.js",
@@ -27744,6 +27827,7 @@ var package_default = {
27744
27827
  prepublishOnly: "bun run build"
27745
27828
  },
27746
27829
  dependencies: {
27830
+ "@cortexkit/subc-client": "0.4.1",
27747
27831
  "@huggingface/transformers": "^4.1.0",
27748
27832
  "@jitl/quickjs-singlefile-cjs-release-asyncify": "0.32.0",
27749
27833
  "ai-tokenizer": "^1.0.6",
@@ -27871,6 +27955,9 @@ function renderInner(s, theme, innerWidth) {
27871
27955
  lines.push(`${theme.fg("accent", theme.bold("⚡ Magic Context Status"))} ${theme.fg("muted", `v${package_default.version}`)}`);
27872
27956
  lines.push("");
27873
27957
  lines.push(`Context ${theme.fg(pctColor, theme.bold(`${s.usagePercentage.toFixed(1)}%`))} · ${fmt2(s.inputTokens)} / ${s.contextLimit > 0 ? fmt2(s.contextLimit) : "?"} tokens`);
27958
+ if (s.windowGeometry) {
27959
+ lines.push(formatWindowDerivationLine(s.inputTokens, s.windowGeometry));
27960
+ }
27874
27961
  lines.push(`Work tokens ${fmt2(s.newWorkTokens)} new · ${fmt2(s.totalInputTokens)} total input`);
27875
27962
  lines.push(renderBar(s, innerWidth));
27876
27963
  for (const seg of breakdownSegments(s)) {
@@ -27931,18 +28018,22 @@ function drawBorder(inner, width, theme) {
27931
28018
  function buildPiStatusDetail(pi, ctx, deps, sessionId) {
27932
28019
  const usage = ctx.getContextUsage?.();
27933
28020
  const meta = getOrCreateSessionMeta(deps.db, sessionId);
27934
- const inputTokens = typeof usage?.tokens === "number" ? usage.tokens : meta.lastInputTokens;
28021
+ const hasPersistedPressure = meta.lastInputTokens > 0 && meta.lastContextPercentage > 0;
28022
+ const inputTokens = hasPersistedPressure ? meta.lastInputTokens : typeof usage?.tokens === "number" ? usage.tokens : 0;
27935
28023
  let detectedContextLimit;
27936
28024
  try {
27937
28025
  const detected = getOverflowState(deps.db, sessionId).detectedContextLimit;
27938
28026
  if (detected > 0)
27939
28027
  detectedContextLimit = detected;
27940
28028
  } catch {}
27941
- const contextLimit = resolvePiUsableContextLimit({
28029
+ const windowGeometry = resolvePiWindowGeometry({
27942
28030
  rawContextWindow: usage?.contextWindow ?? ctx.model?.contextWindow,
27943
28031
  model: ctx.model,
27944
- detectedContextLimit
27945
- }) ?? (meta.lastContextPercentage > 0 ? Math.round(inputTokens / (meta.lastContextPercentage / 100)) : 0);
28032
+ detectedContextLimit,
28033
+ persistedInputTokens: meta.lastInputTokens,
28034
+ persistedPercentage: meta.lastContextPercentage
28035
+ });
28036
+ const contextLimit = windowGeometry?.usableSoft ?? 0;
27946
28037
  const usagePercentage = contextLimit > 0 && inputTokens > 0 ? inputTokens / contextLimit * 100 : meta.lastContextPercentage;
27947
28038
  const compartments = getCompartments(deps.db, sessionId);
27948
28039
  const metaRow = readSessionMetaRow(deps.db, sessionId);
@@ -28036,6 +28127,7 @@ ${safeStringify(tool.parameters)}`);
28036
28127
  lastTransformError: meta.lastTransformError,
28037
28128
  isSubagent: meta.isSubagent,
28038
28129
  contextLimit,
28130
+ windowGeometry,
28039
28131
  executeThreshold: threshold.percentage,
28040
28132
  executeThresholdMode: threshold.mode,
28041
28133
  executeThresholdClamped: threshold.clamped,
@@ -28223,14 +28315,18 @@ No active Pi session is available.`,
28223
28315
  if (detected > 0)
28224
28316
  detectedContextLimit = detected;
28225
28317
  } catch {}
28226
- const usableContextLimit = resolvePiUsableContextLimit({
28318
+ const meta = getOrCreateSessionMeta(currentDeps.db, sessionId);
28319
+ const windowGeometry = resolvePiWindowGeometry({
28227
28320
  rawContextWindow: usage?.contextWindow ?? ctx.model?.contextWindow,
28228
28321
  model: ctx.model,
28229
- detectedContextLimit
28322
+ detectedContextLimit,
28323
+ persistedInputTokens: meta.lastInputTokens,
28324
+ persistedPercentage: meta.lastContextPercentage
28230
28325
  });
28326
+ const usableContextLimit = windowGeometry?.usableSoft;
28231
28327
  const statusText = executeStatus(currentDeps.db, sessionId, currentDeps.protectedTags ?? 20, currentDeps.executeThresholdPercentage, modelKey, currentDeps.historyBudgetPercentage, currentDeps.commitClusterTrigger, currentDeps.executeThresholdTokens, usableContextLimit, {
28232
28328
  backlog: getDreamTaskBacklogs(currentDeps.db, currentDeps.projectIdentity, CANONICAL_DREAM_TASKS)
28233
- });
28329
+ }, windowGeometry);
28234
28330
  const details = buildStatusDetails(currentDeps, sessionId);
28235
28331
  sendCtxStatusMessage(pi, { title: "/ctx-status", text: statusText, level: "info" }, details);
28236
28332
  } catch (error) {
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  log
3
- } from "./index-npnqc564.js";
3
+ } from "./index-hk6sj7dn.js";
4
4
  import"./index-wckvcay0.js";
5
5
 
6
6
  // ../plugin/src/shared/safe-notification-target.ts
@@ -5,11 +5,11 @@ import {
5
5
  registerMagicContextTools,
6
6
  resolveProjectIdentityForSession,
7
7
  setStoragePrivatePermissionEnforcement
8
- } from "./index-zxgbtsnj.js";
8
+ } from "./index-kvttksef.js";
9
9
  import {
10
10
  log,
11
11
  setHarness
12
- } from "./index-npnqc564.js";
12
+ } from "./index-hk6sj7dn.js";
13
13
  import"./index-wckvcay0.js";
14
14
 
15
15
  // src/subagent-entry.ts
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/pi-magic-context",
3
- "version": "0.36.1",
3
+ "version": "0.37.0",
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",
@@ -40,6 +40,7 @@
40
40
  "prepublishOnly": "bun run build"
41
41
  },
42
42
  "dependencies": {
43
+ "@cortexkit/subc-client": "0.4.1",
43
44
  "@huggingface/transformers": "^4.1.0",
44
45
  "@jitl/quickjs-singlefile-cjs-release-asyncify": "0.32.0",
45
46
  "ai-tokenizer": "^1.0.6",