@cortexkit/pi-magic-context 0.49.59 → 0.49.60

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -501,7 +501,8 @@ var PROVIDER_GEOMETRY = {
501
501
  anthropic: "shared_truncating",
502
502
  xai: "shared_truncating",
503
503
  google: "separate",
504
- "google-antigravity": "separate"
504
+ "google-antigravity": "separate",
505
+ "antigravity-cli": "separate"
505
506
  };
506
507
  var geometryClampLogSeen = new Set;
507
508
  function isFinitePositive(value) {
@@ -691,7 +692,11 @@ var MAX_SANE_LIMIT = 3000000;
691
692
  function isSaneLimit(limit) {
692
693
  return typeof limit === "number" && limit >= MIN_SANE_LIMIT && limit <= MAX_SANE_LIMIT;
693
694
  }
694
- var SEPARATE_OUTPUT_QUOTA_PROVIDERS = new Set(["google", "google-antigravity"]);
695
+ var SEPARATE_OUTPUT_QUOTA_PROVIDERS = new Set([
696
+ "google",
697
+ "google-antigravity",
698
+ "antigravity-cli"
699
+ ]);
695
700
  var MIN_PLAUSIBLE_CONTEXT_LIMIT2 = 1024;
696
701
  var OUTPUT_RESERVE_CAP_RATIO2 = 0.25;
697
702
  var outputReserveConfig;
package/dist/index.js CHANGED
@@ -154,7 +154,7 @@ import {
154
154
  registerTodoStateLifecycle,
155
155
  syncCtxMemoryToolEnabled,
156
156
  registerMagicContextTools
157
- } from "./index-2tk7e0bx.js";
157
+ } from "./index-418za765.js";
158
158
  import"./index-4knyh1kt.js";
159
159
  import {
160
160
  canonicalModelIdentity,
@@ -3601,7 +3601,7 @@ function startHostStallProfilerSwitch() {
3601
3601
  // package.json
3602
3602
  var package_default = {
3603
3603
  name: "@cortexkit/pi-magic-context",
3604
- version: "0.49.59",
3604
+ version: "0.49.60",
3605
3605
  type: "module",
3606
3606
  description: "Pi and OMP coding agent extension for Magic Context — cross-session memory and context management",
3607
3607
  main: "dist/index.js",
@@ -3630,7 +3630,7 @@ var package_default = {
3630
3630
  ],
3631
3631
  "//": "The build intentionally bundles typebox (no --external typebox) and keeps it a regular dependency. OMP's extension loader rewrites every bare `typebox` import to its own omptype-based shim, whose schemas are callable objects rather than JSON Schema; they fail structuredClone during tool registration, so an external typebox import stops Magic Context loading on OMP. src/typebox-bundling.test.ts guards this.",
3632
3632
  scripts: {
3633
- build: "bun ../../scripts/check-bun.mjs && tsc -p ../retina-local-fs/tsconfig.build.json && bun ../../scripts/clean-dist-chunks.mjs dist index.js subagent-entry.js historian-calibration-extension.js embedding-worker-process.js raw-ordinal-warmup-worker.js tag-snapshot-worker-pi.js transformers-web.js transformers-node-wasm.js && bun build ../plugin/src/features/magic-context/memory/transformers-web-entry.ts --outfile dist/transformers-web.js --target browser --format esm --external onnxruntime-web && bun ../plugin/scripts/build-transformers-node-wasm.ts dist && bun build src/index.ts src/tag-snapshot-worker-pi.ts src/subagent-entry.ts src/historian-calibration-extension.ts ../plugin/src/features/magic-context/memory/embedding-worker.ts ../plugin/src/features/magic-context/memory/embedding-worker-process.ts ../plugin/src/features/magic-context/migration-worker.ts ../plugin/src/hooks/magic-context/auto-search-worker.ts ../plugin/src/hooks/magic-context/raw-ordinal-warmup-worker.ts ../plugin/src/features/magic-context/compaction-marker-candidates-worker.ts ../plugin/src/features/magic-context/chunk-embedding-write-worker.ts --outdir dist --entry-naming '[name].[ext]' --target node --format esm --splitting --external @earendil-works/pi-coding-agent --external @oh-my-pi/pi-coding-agent --external @earendil-works/pi-tui --external onnxruntime-node --external onnxruntime-web --external sharp --external bun:ffi --external node:sqlite",
3633
+ build: "bun ../../scripts/check-bun.mjs && tsc -p ../retina-local-fs/tsconfig.build.json && bun ../../scripts/clean-dist-chunks.mjs dist index.js subagent-entry.js historian-calibration-extension.js embedding-worker-process.js raw-ordinal-warmup-worker.js tag-snapshot-worker-pi.js transformers-web.js transformers-node-wasm.js && bun build ../plugin/src/features/magic-context/memory/transformers-web-entry.ts --outfile dist/transformers-web.js --target browser --format esm --external onnxruntime-web && bun ../plugin/scripts/build-transformers-node-wasm.ts dist && bun build src/index.ts src/tag-snapshot-worker-pi.ts src/subagent-entry.ts src/historian-calibration-extension.ts ../plugin/src/features/magic-context/memory/embedding-worker.ts ../plugin/src/features/magic-context/memory/embedding-worker-process.ts ../plugin/src/features/magic-context/migration-worker.ts ../plugin/src/hooks/magic-context/auto-search-worker.ts ../plugin/src/hooks/magic-context/raw-ordinal-warmup-worker.ts ../plugin/src/features/magic-context/compaction-marker-candidates-worker.ts ../plugin/src/features/magic-context/chunk-embedding-write-worker.ts --outdir dist --entry-naming '[name].[ext]' --target node --format esm --splitting --external @earendil-works/pi-coding-agent --external @oh-my-pi/pi-coding-agent --external @earendil-works/pi-tui --external @earendil-works/pi-ai --external onnxruntime-node --external onnxruntime-web --external sharp --external bun:ffi --external node:sqlite",
3634
3634
  "build:e2e-argv": `bun ../../scripts/clean-dist-chunks.mjs ../../tests/docker/.generated subagent-runner-e2e.mjs && bun build src/subagent-runner.ts --outdir ../../tests/docker/.generated --entry-naming 'subagent-runner-e2e.mjs' --splitting --target node --format esm --external node:sqlite && node --input-type=module -e 'const { __test } = await import("../../tests/docker/.generated/subagent-runner-e2e.mjs"); if (typeof __test.buildArgs !== "function" || typeof __test.resolvePiInvocation !== "function") throw new Error("argv renderer exports missing"); console.log("Node argv renderer: 2 exports loaded")'`,
3635
3635
  typecheck: "tsc -p ../retina-local-fs/tsconfig.build.json && tsc --noEmit",
3636
3636
  test: "bun ../../scripts/check-bun.mjs && bun install --frozen-lockfile && MC_SLOW_TESTS=0 BUN_JSC_useOMGJIT=0 bun test --parallel=4 --timeout 30000",
@@ -33501,7 +33501,7 @@ function applyPiHeuristicCleanup(sessionId, db, targets, piMessages, config, pre
33501
33501
  const tMeasure = performance.now();
33502
33502
  const activeTags = tags.filter((t) => t.status === "active").map((tag) => {
33503
33503
  const target = targets.get(tag.tagNumber);
33504
- const imageTokens = emergency.serializedImageTokens?.get(tag.messageId) ?? 0;
33504
+ const imageTokens = emergency.toolImageTokens?.get(tag.messageId) ?? 0;
33505
33505
  const observation = target?.measureReclaim;
33506
33506
  const measuredTarget = imageTokens && observation ? {
33507
33507
  ...target,
@@ -33518,7 +33518,7 @@ function applyPiHeuristicCleanup(sessionId, db, targets, piMessages, config, pre
33518
33518
  return emergency.sinceReading?.has(tag.tagNumber) ? { ...measured, sinceReading: true } : measured;
33519
33519
  });
33520
33520
  const byTag = new Map(activeTags.map((tag) => [tag.tagNumber, tag]));
33521
- const removedThisPassTokens = emergency.servedBeforePass ? piServedMassRemovedSince(emergency.servedBeforePass, new Set(activeTags.map((tag) => tag.tagNumber)), targets, calibration, emergency.serializedImageTokens) : 0;
33521
+ const removedThisPassTokens = emergency.servedBeforePass ? piServedMassRemovedSince(emergency.servedBeforePass, new Set(activeTags.map((tag) => tag.tagNumber)), targets, calibration, emergency.toolImageTokens) : 0;
33522
33522
  const droppableTags = candidateTags.flatMap((tag) => {
33523
33523
  const measured = byTag.get(tag.tagNumber);
33524
33524
  return measured ? [measured] : [];
@@ -34905,28 +34905,27 @@ function trimPiMessagesToBoundary(piMessages, entryIds, cutoffMessageId, trimMut
34905
34905
  break;
34906
34906
  }
34907
34907
  }
34908
- if (cutoffIndex < 0 && sessionId && hasRawMessageProvider2(sessionId)) {
34908
+ let promptReachesBoundary;
34909
+ if (cutoffIndex >= 0) {
34910
+ idCutBoundaryByMessages.set(piMessages, cutoffMessageId);
34911
+ } else if (sessionId && piMessages.length > 0 && hasRawMessageProvider2(sessionId)) {
34912
+ let placement;
34909
34913
  try {
34910
- const branch = readRawSessionMessages2(sessionId);
34911
- const positions = new Map(branch.map((message, index) => [message.id, index]));
34912
- const boundaryPosition = positions.get(cutoffMessageId);
34913
- if (boundaryPosition === undefined)
34914
- return 0;
34915
- let previous = -1;
34916
- for (const [index, message] of piMessages.entries()) {
34917
- if (isPiSystemEntry(message))
34918
- continue;
34919
- const id = resolveStableId(message, index, entryIds);
34920
- const position = positions.get(id) ?? positions.get(`${SYNTH_USER_ID_PREFIX}${id}`);
34921
- if (position === undefined || position <= previous)
34922
- return 0;
34923
- previous = position;
34924
- if (position <= boundaryPosition)
34925
- cutoffIndex = index;
34926
- }
34927
- } catch {
34914
+ placement = placeCutByBranchPosition(piMessages, entryIds, cutoffMessageId, sessionId);
34915
+ } catch (error) {
34916
+ placement = {
34917
+ placed: false,
34918
+ reason: `the branch could not be read (${error instanceof Error ? error.message : String(error)})`,
34919
+ firstUnplacedRole: "unknown"
34920
+ };
34921
+ }
34922
+ if (!placement.placed) {
34923
+ if (idCutBoundaryByMessages.get(piMessages) !== cutoffMessageId)
34924
+ logUnplacedCut(sessionId, cutoffMessageId, piMessages.length, placement.reason, placement.firstUnplacedRole);
34928
34925
  return 0;
34929
34926
  }
34927
+ cutoffIndex = placement.cutoffIndex;
34928
+ promptReachesBoundary = placement.promptReachesBoundary;
34930
34929
  }
34931
34930
  if (cutoffIndex < 0)
34932
34931
  return 0;
@@ -34985,6 +34984,9 @@ function trimPiMessagesToBoundary(piMessages, entryIds, cutoffMessageId, trimMut
34985
34984
  }
34986
34985
  }
34987
34986
  }
34987
+ const keptPrompt = keptPromptIndex(piMessages, cutoffIndex, remove, promptReachesBoundary);
34988
+ if (keptPrompt >= 0)
34989
+ remove.delete(keptPrompt);
34988
34990
  const retiredIds = new Set;
34989
34991
  if (retireDecisions) {
34990
34992
  for (const index of remove) {
@@ -35005,6 +35007,100 @@ function trimPiMessagesToBoundary(piMessages, entryIds, cutoffMessageId, trimMut
35005
35007
  retireDecisions?.(retiredIds);
35006
35008
  return removed;
35007
35009
  }
35010
+ function placeCutByBranchPosition(piMessages, entryIds, cutoffMessageId, sessionId) {
35011
+ const branch = readRawSessionMessages2(sessionId);
35012
+ const positions = new Map(branch.map((message, index) => [message.id, index]));
35013
+ const eventPositions = new Map;
35014
+ let firstUnplacedRole;
35015
+ let contentMessages = 0;
35016
+ for (const [index, message] of piMessages.entries()) {
35017
+ if (isPiSystemEntry(message))
35018
+ continue;
35019
+ contentMessages++;
35020
+ const id = resolveStableId(message, index, entryIds);
35021
+ const position = positions.get(id) ?? positions.get(`${SYNTH_USER_ID_PREFIX}${id}`);
35022
+ if (position === undefined)
35023
+ firstUnplacedRole ??= String(message.role);
35024
+ else
35025
+ eventPositions.set(index, position);
35026
+ }
35027
+ const unplacedRole = firstUnplacedRole ?? "none";
35028
+ const boundaryPosition = positions.get(cutoffMessageId);
35029
+ if (boundaryPosition === undefined)
35030
+ return {
35031
+ placed: false,
35032
+ reason: "it is not on the active branch either",
35033
+ firstUnplacedRole: unplacedRole
35034
+ };
35035
+ if (contentMessages > 0 && eventPositions.size === 0)
35036
+ return {
35037
+ placed: false,
35038
+ reason: "none of them has a branch position",
35039
+ firstUnplacedRole: unplacedRole
35040
+ };
35041
+ let cutoffIndex = -1;
35042
+ let previous = -1;
35043
+ for (const [index, position] of eventPositions) {
35044
+ if (position <= previous)
35045
+ return {
35046
+ placed: false,
35047
+ reason: "the context messages are not in branch order",
35048
+ firstUnplacedRole: unplacedRole
35049
+ };
35050
+ previous = position;
35051
+ if (position <= boundaryPosition)
35052
+ cutoffIndex = index;
35053
+ }
35054
+ return {
35055
+ placed: true,
35056
+ cutoffIndex,
35057
+ promptReachesBoundary: (eventIndex) => {
35058
+ const promptPosition = eventPositions.get(eventIndex);
35059
+ if (promptPosition === undefined)
35060
+ return true;
35061
+ for (let p = promptPosition + 1;p <= boundaryPosition; p++) {
35062
+ const message = branch[p];
35063
+ if (message?.role === "user" && !message.id.startsWith(SYNTH_USER_ID_PREFIX))
35064
+ return false;
35065
+ }
35066
+ return true;
35067
+ }
35068
+ };
35069
+ }
35070
+ function keptPromptIndex(piMessages, cutoffIndex, removed, promptReachesBoundary) {
35071
+ let promptIndex = -1;
35072
+ for (let i = cutoffIndex;i >= 0; i--) {
35073
+ if (piMessages[i]?.role === "user") {
35074
+ promptIndex = i;
35075
+ break;
35076
+ }
35077
+ }
35078
+ if (promptIndex < 0)
35079
+ return -1;
35080
+ for (let i = cutoffIndex + 1;i < piMessages.length; i++) {
35081
+ if (removed.has(i))
35082
+ continue;
35083
+ const message = piMessages[i];
35084
+ if (message?.role === "user")
35085
+ return -1;
35086
+ if (message?.role === "assistant" && message.stopReason !== "error")
35087
+ break;
35088
+ }
35089
+ if (promptReachesBoundary && !promptReachesBoundary(promptIndex))
35090
+ return -1;
35091
+ return promptIndex;
35092
+ }
35093
+ var idCutBoundaryByMessages = new WeakMap;
35094
+ var unplacedCutLoggedSessions = new Set;
35095
+ function resetPiUnplacedCutLog(sessionId) {
35096
+ unplacedCutLoggedSessions.delete(sessionId);
35097
+ }
35098
+ function logUnplacedCut(sessionId, boundaryMessageId, eventLength, reason, firstUnplacedRole) {
35099
+ if (unplacedCutLoggedSessions.has(sessionId))
35100
+ return;
35101
+ unplacedCutLoggedSessions.add(sessionId);
35102
+ sessionLog2(sessionId, `pi history cut not placed: boundary ${boundaryMessageId} is not among the ${eventLength} context messages and ${reason}; first message without a branch position: ${firstUnplacedRole}; nothing was cut at this boundary`);
35103
+ }
35008
35104
  function toolPairKey(callId, assistantIndex) {
35009
35105
  return `${callId}\x00${assistantIndex}`;
35010
35106
  }
@@ -43345,6 +43441,20 @@ function piFitMessageBytes(raw) {
43345
43441
  const bytes = Buffer.byteLength(JSON.stringify(content ? { ...message, content } : raw));
43346
43442
  return bytes + (opaque ? 4 * opaqueThinkingCost(message.usage?.reasoning, message.usage?.output).tokens : 0);
43347
43443
  }
43444
+ function piFitMessageBytesPricingImages(raw, bytesPerImage = PI_IMAGE_TOKENS) {
43445
+ const message = raw;
43446
+ if (!Array.isArray(message?.content) || !message.content.some((part) => part && typeof part === "object" && part.type === "image"))
43447
+ return piFitMessageBytes(raw);
43448
+ let images = 0;
43449
+ const content = message.content.map((part) => {
43450
+ if (!part || typeof part !== "object" || part.type !== "image")
43451
+ return part;
43452
+ images += 1;
43453
+ const { data: _data, ...rest } = part;
43454
+ return rest;
43455
+ });
43456
+ return piFitMessageBytes({ ...message, content }) + images * bytesPerImage;
43457
+ }
43348
43458
  function tokenCacheFingerprintsEqual(left, right) {
43349
43459
  if (left.length !== right.length)
43350
43460
  return false;
@@ -43453,9 +43563,19 @@ function estimatePiOutgoingInputTokens(messages, observed, measuredPrefix, conte
43453
43563
  if (!knownRole(message))
43454
43564
  return false;
43455
43565
  const m = message;
43456
- return typeof m.content === "string" || Array.isArray(m.content) && m.content.every((p) => p && typeof p === "object" && ["text", "thinking", "redacted_thinking", "toolCall"].includes(String(p.type)));
43566
+ return typeof m.content === "string" || Array.isArray(m.content) && m.content.every((p) => p && typeof p === "object" && [
43567
+ "text",
43568
+ "thinking",
43569
+ "redacted_thinking",
43570
+ "toolCall",
43571
+ "image"
43572
+ ].includes(String(p.type)));
43457
43573
  };
43458
43574
  const complete = messages.every(countable);
43575
+ const hasImages = messages.some((message) => {
43576
+ const content = message?.content;
43577
+ return Array.isArray(content) && content.some((part) => part && typeof part === "object" && part.type === "image");
43578
+ });
43459
43579
  const measuredForBounds = measuredPrefix && measuredPrefix.modelKey === observed.modelKey && observed.envelopeSignature && measuredPrefix.envelopeSignature === observed.envelopeSignature && Number.isSafeInteger(measuredPrefix.inputTokens) && measuredPrefix.inputTokens > 0 ? measuredPrefix : undefined;
43460
43580
  if (contextLimit && Number.isFinite(contextLimit) && contextLimit > 0) {
43461
43581
  const priced = measuredForBounds?.appendedMessages ?? messages;
@@ -43496,7 +43616,7 @@ function estimatePiOutgoingInputTokens(messages, observed, measuredPrefix, conte
43496
43616
  tools: observed.toolDefinitionTokens
43497
43617
  }, observed.calibration ?? calibrationForModelKey(observed.modelKey), true);
43498
43618
  const fit = observed.calibration ?? calibrationForModelKey(observed.modelKey);
43499
- const upper = envelope + Math.max(UNKNOWN_FIT_RATIO, fit.toolsRatio, fit.proseRatio) * priced.reduce((sum, message) => sum + piFitMessageBytes(message), 0);
43619
+ const upper = envelope + Math.max(UNKNOWN_FIT_RATIO, fit.toolsRatio, fit.proseRatio) * priced.reduce((sum, message) => sum + piFitMessageBytesPricingImages(message), 0);
43500
43620
  if (upper <= contextLimit)
43501
43621
  return {
43502
43622
  tokens: upper,
@@ -43509,7 +43629,7 @@ function estimatePiOutgoingInputTokens(messages, observed, measuredPrefix, conte
43509
43629
  return {
43510
43630
  tokens: providerMass({
43511
43631
  system: observed.systemTokens,
43512
- tools: observed.toolDefinitionTokens + messages.reduce((sum, message) => sum + piFitMessageBytes(message), 0)
43632
+ tools: observed.toolDefinitionTokens + messages.reduce((sum, message) => sum + piFitMessageBytesPricingImages(message), 0)
43513
43633
  }, observed.calibration ?? calibrationForModelKey(observed.modelKey), true),
43514
43634
  trusted: true,
43515
43635
  refusalGrade: false
@@ -43530,7 +43650,7 @@ function estimatePiOutgoingInputTokens(messages, observed, measuredPrefix, conte
43530
43650
  return {
43531
43651
  tokens: providerMass({
43532
43652
  system: observed.systemTokens,
43533
- tools: observed.toolDefinitionTokens + messages.reduce((sum, message) => sum + piFitMessageBytes(message), 0)
43653
+ tools: observed.toolDefinitionTokens + messages.reduce((sum, message) => sum + piFitMessageBytesPricingImages(message), 0)
43534
43654
  }, observed.calibration ?? calibrationForModelKey(observed.modelKey), true),
43535
43655
  trusted: true,
43536
43656
  refusalGrade: false,
@@ -43544,7 +43664,7 @@ function estimatePiOutgoingInputTokens(messages, observed, measuredPrefix, conte
43544
43664
  tools: observed.toolDefinitionTokens + raw.toolCall,
43545
43665
  prose: raw.conversation
43546
43666
  }, calibration, true);
43547
- const refusalGrade = Number.isFinite(tokens) && messages.every((rawMessage) => {
43667
+ const refusalGrade = Number.isFinite(tokens) && !hasImages && messages.every((rawMessage) => {
43548
43668
  const content = rawMessage.content;
43549
43669
  if (typeof content === "string")
43550
43670
  return !tokenCountUsesByteBound(content);
@@ -43583,7 +43703,7 @@ function assertPiRawFallbackFits(messages, contextLimit, log, cause, observed, m
43583
43703
  let serializationFailed = false;
43584
43704
  try {
43585
43705
  for (const message of pricedMessages) {
43586
- bytes += piFitMessageBytes(message) + 1;
43706
+ bytes += piFitMessageBytesPricingImages(message, 4 * PI_IMAGE_TOKENS) + 1;
43587
43707
  if (baseInputTokens + Math.ceil(bytes / 4) > contextLimit)
43588
43708
  break;
43589
43709
  }
@@ -43599,7 +43719,13 @@ function assertPiRawFallbackFits(messages, contextLimit, log, cause, observed, m
43599
43719
  if (!message || typeof message !== "object")
43600
43720
  return false;
43601
43721
  const m = message;
43602
- return ["user", "assistant", "toolResult", "custom"].includes(m.role ?? "") && (typeof m.content === "string" || Array.isArray(m.content) && m.content.every((p) => p !== null && typeof p === "object" && ["text", "thinking", "redacted_thinking", "toolCall"].includes(String(p.type))));
43722
+ return ["user", "assistant", "toolResult", "custom"].includes(m.role ?? "") && (typeof m.content === "string" || Array.isArray(m.content) && m.content.every((p) => p !== null && typeof p === "object" && [
43723
+ "text",
43724
+ "thinking",
43725
+ "redacted_thinking",
43726
+ "toolCall",
43727
+ "image"
43728
+ ].includes(String(p.type))));
43603
43729
  });
43604
43730
  const raw = tokenizePiMessages([...pricedMessages]);
43605
43731
  if (!hasTokenizerForFit()) {
@@ -43611,9 +43737,17 @@ function assertPiRawFallbackFits(messages, contextLimit, log, cause, observed, m
43611
43737
  tools: (measured ? 0 : observed.toolDefinitionTokens) + raw.toolCall,
43612
43738
  prose: raw.conversation
43613
43739
  }, observed.calibration ?? calibrationForModelKey(observed.modelKey), true);
43614
- if (!complete || !Number.isFinite(tokens) || tokens <= 0 || tokens > contextLimit || serializationFailed || proxyTokens > contextLimit) {
43615
- log(`raw_fallback_over_context_limit proxy_bytes=${bytes} proxy_tokens=${proxyTokens} limit=${contextLimit} early_abort=true serialization_failed=${serializationFailed}`);
43616
- throw piFallbackRefusal(complete ? "fallback-over-context-limit" : "fallback-messages-incomplete", cause);
43740
+ if (!complete) {
43741
+ log("raw_fallback_refused completeness=partial messages=unpriceable");
43742
+ throw piFallbackRefusal("fallback-messages-incomplete", cause);
43743
+ }
43744
+ if (!Number.isFinite(tokens) || tokens <= 0) {
43745
+ log(`raw_fallback_refused count=unusable tokens=${tokens}`);
43746
+ throw piFallbackRefusal("fallback-over-context-limit", cause);
43747
+ }
43748
+ if (tokens > contextLimit) {
43749
+ log(`raw_fallback_over_context_limit tokens=${Math.ceil(tokens)} limit=${contextLimit} proxy_bytes=${bytes} proxy_tokens=${proxyTokens}`);
43750
+ throw piFallbackRefusal("fallback-over-context-limit", cause);
43617
43751
  }
43618
43752
  }
43619
43753
  function classifyPiOutgoingFit(estimate, limit) {
@@ -45215,6 +45349,12 @@ function piRecoveryFitCalibration(calibration) {
45215
45349
  return calibration.seeded ? calibration : { toolsRatio: UNKNOWN_FIT_RATIO, proseRatio: UNKNOWN_FIT_RATIO };
45216
45350
  }
45217
45351
  function piRecoveryToolImageTokens(messages) {
45352
+ return piToolResultImageTokens(messages, (part) => estimateTokens(JSON.stringify(part)));
45353
+ }
45354
+ function piToolImageCostTokens(messages) {
45355
+ return piToolResultImageTokens(messages, () => PI_IMAGE_TOKENS);
45356
+ }
45357
+ function piToolResultImageTokens(messages, priceImage) {
45218
45358
  const counts = new Map;
45219
45359
  const seen = new Set;
45220
45360
  for (const value of messages) {
@@ -45228,7 +45368,7 @@ function piRecoveryToolImageTokens(messages) {
45228
45368
  seen.add(message.toolCallId);
45229
45369
  for (const part of message.content) {
45230
45370
  if (part?.type === "image")
45231
- counts.set(message.toolCallId, (counts.get(message.toolCallId) ?? 0) + estimateTokens(JSON.stringify(part)));
45371
+ counts.set(message.toolCallId, (counts.get(message.toolCallId) ?? 0) + priceImage(part));
45232
45372
  }
45233
45373
  }
45234
45374
  return counts;
@@ -45329,6 +45469,8 @@ function extractAssistantUsage(message) {
45329
45469
  result.cacheWrite = u.cacheWrite;
45330
45470
  if (typeof u.totalTokens === "number")
45331
45471
  result.totalTokens = u.totalTokens;
45472
+ if (typeof u.contextTokens === "number")
45473
+ result.contextTokens = u.contextTokens;
45332
45474
  return result;
45333
45475
  }
45334
45476
  function computePiPressure(usage, contextLimit, absoluteWall) {
@@ -45347,9 +45489,12 @@ function piUsageInputTokens(usage) {
45347
45489
  const componentPromptTokens = input + cacheRead + cacheWrite;
45348
45490
  const totalPromptTokens = typeof usage.totalTokens === "number" && Number.isFinite(usage.totalTokens) && typeof usage.output === "number" && Number.isFinite(usage.output) ? Math.max(0, usage.totalTokens - usage.output) : undefined;
45349
45491
  const inputTokens = totalPromptTokens !== undefined && totalPromptTokens > 0 ? Math.min(componentPromptTokens, totalPromptTokens) : componentPromptTokens;
45350
- if (inputTokens <= 0 || !Number.isFinite(inputTokens))
45351
- return null;
45352
- return inputTokens;
45492
+ if (inputTokens > 0 && Number.isFinite(inputTokens))
45493
+ return inputTokens;
45494
+ return positiveContextTokens(usage.contextTokens);
45495
+ }
45496
+ function positiveContextTokens(value) {
45497
+ return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : null;
45353
45498
  }
45354
45499
  function resolvePiPressureSnapshot(args) {
45355
45500
  const persistedInputTokens = Number.isFinite(args.persistedInputTokens) && args.persistedInputTokens > 0 ? args.persistedInputTokens : 0;
@@ -45380,7 +45525,7 @@ function entryUsageTokens(usage) {
45380
45525
  return 0;
45381
45526
  const u = usage;
45382
45527
  const n = (value) => typeof value === "number" && Number.isFinite(value) ? value : 0;
45383
- return n(u.totalTokens) || n(u.input) + n(u.output) + n(u.cacheRead) + n(u.cacheWrite);
45528
+ return n(u.totalTokens) || n(u.input) + n(u.output) + n(u.cacheRead) + n(u.cacheWrite) || (positiveContextTokens(u.contextTokens) ?? 0);
45384
45529
  }
45385
45530
  function isPiLiveUsageRawBranchEstimate(branchEntries) {
45386
45531
  if (!branchEntries)
@@ -45981,6 +46126,22 @@ function reportBindingRecovery(sessionId, report, message) {
45981
46126
  else
45982
46127
  log2(`[magic-context][${sessionId}] ${message}`);
45983
46128
  }
46129
+ function armPiProviderOverflowRecovery(args) {
46130
+ recordOverflowDetected(args.db, args.sessionId, args.reportedLimit, args.modelKey, "provider_overflow", args.reportedLimitProvenance, args.reportedInputTokens);
46131
+ if (getHarness2() === "pi") {
46132
+ try {
46133
+ resetPiUpperEstimateReclaim(args.db, args.sessionId);
46134
+ } catch (error) {
46135
+ args.report?.(`upper-estimate reclaim reset deferred: ${String(error)}`);
46136
+ }
46137
+ }
46138
+ }
46139
+ function armPiRecoveryForHostOverflowCompaction(args) {
46140
+ if (getOverflowState(args.db, args.sessionId).needsEmergencyRecovery)
46141
+ return "already-armed";
46142
+ armPiProviderOverflowRecovery(args);
46143
+ return "armed";
46144
+ }
45984
46145
  function handlePiProviderFailure(args) {
45985
46146
  if (!args.message || typeof args.message !== "object")
45986
46147
  return { kind: "none" };
@@ -46010,19 +46171,21 @@ function handlePiProviderFailure(args) {
46010
46171
  if (args.compactionOff)
46011
46172
  return { kind: "none" };
46012
46173
  const overflow = detectOverflow(message.errorMessage);
46013
- if (!overflow.isOverflow)
46174
+ const hostOnly = !overflow.isOverflow && args.hostOverflowCheck?.(args.message) === true;
46175
+ if (!overflow.isOverflow && !hostOnly)
46014
46176
  return { kind: "none" };
46015
- const modelKey = provider && model ? `${provider}/${model}` : undefined;
46016
- recordOverflowDetected(args.db, args.sessionId, overflow.reportedLimit, modelKey, "provider_overflow", overflow.reportedLimitProvenance, overflow.reportedInputTokens);
46017
- if (getHarness2() === "pi") {
46018
- try {
46019
- resetPiUpperEstimateReclaim(args.db, args.sessionId);
46020
- } catch (error) {
46021
- args.report?.(`upper-estimate reclaim reset deferred: ${String(error)}`);
46022
- }
46023
- }
46177
+ armPiProviderOverflowRecovery({
46178
+ db: args.db,
46179
+ sessionId: args.sessionId,
46180
+ modelKey: provider && model ? `${provider}/${model}` : undefined,
46181
+ reportedLimit: overflow.reportedLimit,
46182
+ reportedLimitProvenance: overflow.reportedLimitProvenance,
46183
+ reportedInputTokens: overflow.reportedInputTokens,
46184
+ report: args.report
46185
+ });
46024
46186
  return {
46025
46187
  kind: "overflow",
46188
+ source: hostOnly ? "host" : "magic-context",
46026
46189
  ...overflow.reportedLimit !== undefined ? { reportedLimit: overflow.reportedLimit } : {},
46027
46190
  ...overflow.reportedLimitProvenance !== undefined ? { reportedLimitProvenance: overflow.reportedLimitProvenance } : {},
46028
46191
  ...overflow.matchedPattern !== undefined ? { matchedPattern: overflow.matchedPattern } : {}
@@ -49710,6 +49873,7 @@ function registerPiContextHandler(pi, baseOptions) {
49710
49873
  return;
49711
49874
  }
49712
49875
  sessionIdForError = sessionId;
49876
+ resetPiUnplacedCutLog(sessionId);
49713
49877
  try {
49714
49878
  const effectiveSystem = readHostSystemPrompt(ctx);
49715
49879
  if (effectiveSystem !== undefined)
@@ -52746,7 +52910,8 @@ async function runPipeline(args) {
52746
52910
  const emergencyPlannerMayRun = shouldRunHeuristics && args.heuristics !== undefined && args.forceMaterialization === true && args.emergencyCeilingTokens !== undefined && args.emergencyCeilingTokens > 0;
52747
52911
  const tagsNewerThanReading = emergencyPlannerMayRun ? tagsSinceReading(transcript.messages, newTargets) : undefined;
52748
52912
  const queuedDropTags = new Set(pendingOps.map((op) => op.tagId));
52749
- const emergencyServedBeforeDrain = emergencyPlannerMayRun && shouldApplyPendingOps && queuedDropTags.size > 0 ? snapshotPiEmergencyServedMass(getPiActiveTagSnapshotView(args.db, args.sessionId).filter((tag) => queuedDropTags.has(tag.tagNumber) && !tagsNewerThanReading?.has(tag.tagNumber)), newTargets, args.providerOverflowRecovery === true ? piRecoveryToolImageTokens(workingMessages) : undefined) : undefined;
52913
+ const emergencyToolImageTokens = () => args.providerOverflowRecovery === true ? piRecoveryToolImageTokens(workingMessages) : piToolImageCostTokens(workingMessages);
52914
+ const emergencyServedBeforeDrain = emergencyPlannerMayRun && shouldApplyPendingOps && queuedDropTags.size > 0 ? snapshotPiEmergencyServedMass(getPiActiveTagSnapshotView(args.db, args.sessionId).filter((tag) => queuedDropTags.has(tag.tagNumber) && !tagsNewerThanReading?.has(tag.tagNumber)), newTargets, emergencyToolImageTokens()) : undefined;
52750
52915
  mutationGateObserverForTests?.({
52751
52916
  foldDue: foldDueDecision.value,
52752
52917
  foldExecuted: foldExecutedThisPass,
@@ -52904,7 +53069,7 @@ async function runPipeline(args) {
52904
53069
  ceilingTokens: args.emergencyCeilingTokens,
52905
53070
  usagePercentage: args.contextUsage.percentage,
52906
53071
  passAlreadyPriced: independentMutationBeforeHeuristics,
52907
- serializedImageTokens: providerOverflow ? piRecoveryToolImageTokens(workingMessages) : undefined,
53072
+ toolImageTokens: emergencyToolImageTokens(),
52908
53073
  fitCalibration: providerOverflow ? piRecoveryFitCalibration(recoveryCalibration) : undefined,
52909
53074
  servedBeforePass: emergencyServedBeforeDrain,
52910
53075
  sinceReading: tagsNewerThanReading
@@ -53289,7 +53454,12 @@ async function runPipeline(args) {
53289
53454
  logTransformTiming(args.sessionId, "prepareCompartmentInjection", tInjection);
53290
53455
  logTransformTiming(args.sessionId, "compartmentPhase", tInjection);
53291
53456
  } catch (err) {
53292
- sessionLog2(args.sessionId, `compartment injection failed (continuing): ${err instanceof Error ? err.message : String(err)}`);
53457
+ sessionLog2(args.sessionId, `compartment injection failed; replaying the last good request or refusing the turn: ${err instanceof Error ? err.message : String(err)}`);
53458
+ if (isTransientPiStorageError(err))
53459
+ throw err;
53460
+ throw new PiDegradedPassError("m0-m1-injection-degradation", {
53461
+ cause: err
53462
+ });
53293
53463
  }
53294
53464
  }
53295
53465
  transcript.finalizeToolRemovals();
@@ -53829,6 +53999,7 @@ function clearContextHandlerSession(sessionId) {
53829
53999
  clearPiCompactionMarkerDrainLogState(sessionId);
53830
54000
  clearPiInjectionTokenCountCache(sessionId);
53831
54001
  clearPiMuralProcessCache(sessionId);
54002
+ resetPiUnplacedCutLog(sessionId);
53832
54003
  clearPiTailHygieneContentMemo();
53833
54004
  clearPiChannel1State(sessionId);
53834
54005
  lastHeuristicsTurnIdBySession.delete(sessionId);
@@ -56877,6 +57048,38 @@ function registerPiFailClosedSurface(pi, args) {
56877
57048
  };
56878
57049
  }
56879
57050
 
57051
+ // src/host-overflow-check-pi.ts
57052
+ var HOST_PI_AI_MODULE = "@earendil-works/pi-ai";
57053
+ var importHostModule = () => import("@earendil-works/pi-ai");
57054
+ var loadHostModule = importHostModule;
57055
+ var hostCheck;
57056
+ function loadPiHostOverflowCheck() {
57057
+ hostCheck ??= resolveHostOverflowCheck();
57058
+ return hostCheck;
57059
+ }
57060
+ async function resolveHostOverflowCheck() {
57061
+ let module;
57062
+ try {
57063
+ module = await loadHostModule();
57064
+ } catch (error) {
57065
+ log2(`[magic-context] host overflow check unavailable: ${HOST_PI_AI_MODULE} did not load (${error instanceof Error ? error.message : String(error)}); using Magic Context's overflow patterns only`);
57066
+ return;
57067
+ }
57068
+ const check = module?.isContextOverflow;
57069
+ if (typeof check !== "function") {
57070
+ log2(`[magic-context] host overflow check unavailable: ${HOST_PI_AI_MODULE} has no isContextOverflow export; using Magic Context's overflow patterns only`);
57071
+ return;
57072
+ }
57073
+ log2(`[magic-context] host overflow check: using isContextOverflow from ${HOST_PI_AI_MODULE}`);
57074
+ return (message) => {
57075
+ try {
57076
+ return check(message) === true;
57077
+ } catch {
57078
+ return false;
57079
+ }
57080
+ };
57081
+ }
57082
+
56880
57083
  // src/message-end-index-pi.ts
56881
57084
  var unpersistedMessageSeq = 0;
56882
57085
  function findEntryIdForMessage(branch, message) {
@@ -57360,6 +57563,23 @@ function signalPiDeferredCompactionMarkerDrain(sessionId) {
57360
57563
  }
57361
57564
  async function handlePiSessionBeforeCompact(args) {
57362
57565
  if (!args.compactionOff) {
57566
+ if (args.event?.reason === "overflow" && args.event.willRetry === true) {
57567
+ try {
57568
+ const sessionId = args.ctx.sessionManager?.getSessionId?.();
57569
+ if (typeof sessionId === "string" && sessionId.length > 0) {
57570
+ const provider = args.ctx.model?.provider;
57571
+ const model = args.ctx.model?.id;
57572
+ const outcome = armPiRecoveryForHostOverflowCompaction({
57573
+ db: args.db,
57574
+ sessionId,
57575
+ modelKey: typeof provider === "string" && typeof model === "string" ? `${provider}/${model}` : undefined
57576
+ });
57577
+ info(`session_before_compact: host compacting for overflow; provider-overflow recovery ${outcome}`);
57578
+ }
57579
+ } catch (err) {
57580
+ warn("session_before_compact: overflow recovery arm failed:", err);
57581
+ }
57582
+ }
57363
57583
  info("session_before_compact: cancelling — magic-context owns compaction");
57364
57584
  return { cancel: true };
57365
57585
  }
@@ -58695,7 +58915,7 @@ async function startPiMagicContextRuntime(pi, database, dbPath) {
58695
58915
  log2(`tool_result hook failed (continuing): ${err instanceof Error ? err.message : String(err)}`);
58696
58916
  }
58697
58917
  });
58698
- pi.on("session_before_compact", async (_event, ctx) => handlePiSessionBeforeCompact({ db, compactionOff, ctx }));
58918
+ pi.on("session_before_compact", async (event, ctx) => handlePiSessionBeforeCompact({ db, compactionOff, ctx, event }));
58699
58919
  if (PI_HARNESS_KIND !== "omp") {
58700
58920
  registerStreamTagPrefixStrip(pi, () => !compactionOff);
58701
58921
  } else {
@@ -58787,14 +59007,17 @@ async function startPiMagicContextRuntime(pi, database, dbPath) {
58787
59007
  const sessionId = sm?.getSessionId?.();
58788
59008
  if (typeof sessionId !== "string" || sessionId.length === 0)
58789
59009
  return;
59010
+ const failed = event.message;
59011
+ const hostOverflowCheck = !compactionOff && failed?.role === "assistant" && typeof failed.errorMessage === "string" && failed.errorMessage.length > 0 ? await loadPiHostOverflowCheck() : undefined;
58790
59012
  const recovery = handlePiProviderFailure({
58791
59013
  db,
58792
59014
  sessionId,
58793
59015
  message: event.message,
58794
- compactionOff
59016
+ compactionOff,
59017
+ hostOverflowCheck
58795
59018
  });
58796
59019
  if (recovery.kind === "overflow") {
58797
- log2(`[magic-context][${sessionId}] overflow detected: reportedLimit=${recovery.reportedLimit ?? "?"} provenance=${recovery.reportedLimitProvenance ?? "?"} pattern=${recovery.matchedPattern ?? "?"}`);
59020
+ log2(`[magic-context][${sessionId}] overflow detected: source=${recovery.source} reportedLimit=${recovery.reportedLimit ?? "?"} provenance=${recovery.reportedLimitProvenance ?? "?"} pattern=${recovery.matchedPattern ?? "?"}`);
58798
59021
  }
58799
59022
  } catch (err) {
58800
59023
  warn("message_end: provider failure classification failed:", err);
@@ -34,7 +34,7 @@ import {
34
34
  resolvePiHarnessKind,
35
35
  reportSubagentStartupError,
36
36
  registerMagicContextTools
37
- } from "./index-2tk7e0bx.js";
37
+ } from "./index-418za765.js";
38
38
  import"./index-vcegxfwg.js";
39
39
  import"./index-5rcjs14a.js";
40
40
  import"./index-cxczethe.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/pi-magic-context",
3
- "version": "0.49.59",
3
+ "version": "0.49.60",
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",
@@ -29,7 +29,7 @@
29
29
  ],
30
30
  "//": "The build intentionally bundles typebox (no --external typebox) and keeps it a regular dependency. OMP's extension loader rewrites every bare `typebox` import to its own omptype-based shim, whose schemas are callable objects rather than JSON Schema; they fail structuredClone during tool registration, so an external typebox import stops Magic Context loading on OMP. src/typebox-bundling.test.ts guards this.",
31
31
  "scripts": {
32
- "build": "bun ../../scripts/check-bun.mjs && tsc -p ../retina-local-fs/tsconfig.build.json && bun ../../scripts/clean-dist-chunks.mjs dist index.js subagent-entry.js historian-calibration-extension.js embedding-worker-process.js raw-ordinal-warmup-worker.js tag-snapshot-worker-pi.js transformers-web.js transformers-node-wasm.js && bun build ../plugin/src/features/magic-context/memory/transformers-web-entry.ts --outfile dist/transformers-web.js --target browser --format esm --external onnxruntime-web && bun ../plugin/scripts/build-transformers-node-wasm.ts dist && bun build src/index.ts src/tag-snapshot-worker-pi.ts src/subagent-entry.ts src/historian-calibration-extension.ts ../plugin/src/features/magic-context/memory/embedding-worker.ts ../plugin/src/features/magic-context/memory/embedding-worker-process.ts ../plugin/src/features/magic-context/migration-worker.ts ../plugin/src/hooks/magic-context/auto-search-worker.ts ../plugin/src/hooks/magic-context/raw-ordinal-warmup-worker.ts ../plugin/src/features/magic-context/compaction-marker-candidates-worker.ts ../plugin/src/features/magic-context/chunk-embedding-write-worker.ts --outdir dist --entry-naming '[name].[ext]' --target node --format esm --splitting --external @earendil-works/pi-coding-agent --external @oh-my-pi/pi-coding-agent --external @earendil-works/pi-tui --external onnxruntime-node --external onnxruntime-web --external sharp --external bun:ffi --external node:sqlite",
32
+ "build": "bun ../../scripts/check-bun.mjs && tsc -p ../retina-local-fs/tsconfig.build.json && bun ../../scripts/clean-dist-chunks.mjs dist index.js subagent-entry.js historian-calibration-extension.js embedding-worker-process.js raw-ordinal-warmup-worker.js tag-snapshot-worker-pi.js transformers-web.js transformers-node-wasm.js && bun build ../plugin/src/features/magic-context/memory/transformers-web-entry.ts --outfile dist/transformers-web.js --target browser --format esm --external onnxruntime-web && bun ../plugin/scripts/build-transformers-node-wasm.ts dist && bun build src/index.ts src/tag-snapshot-worker-pi.ts src/subagent-entry.ts src/historian-calibration-extension.ts ../plugin/src/features/magic-context/memory/embedding-worker.ts ../plugin/src/features/magic-context/memory/embedding-worker-process.ts ../plugin/src/features/magic-context/migration-worker.ts ../plugin/src/hooks/magic-context/auto-search-worker.ts ../plugin/src/hooks/magic-context/raw-ordinal-warmup-worker.ts ../plugin/src/features/magic-context/compaction-marker-candidates-worker.ts ../plugin/src/features/magic-context/chunk-embedding-write-worker.ts --outdir dist --entry-naming '[name].[ext]' --target node --format esm --splitting --external @earendil-works/pi-coding-agent --external @oh-my-pi/pi-coding-agent --external @earendil-works/pi-tui --external @earendil-works/pi-ai --external onnxruntime-node --external onnxruntime-web --external sharp --external bun:ffi --external node:sqlite",
33
33
  "build:e2e-argv": "bun ../../scripts/clean-dist-chunks.mjs ../../tests/docker/.generated subagent-runner-e2e.mjs && bun build src/subagent-runner.ts --outdir ../../tests/docker/.generated --entry-naming 'subagent-runner-e2e.mjs' --splitting --target node --format esm --external node:sqlite && node --input-type=module -e 'const { __test } = await import(\"../../tests/docker/.generated/subagent-runner-e2e.mjs\"); if (typeof __test.buildArgs !== \"function\" || typeof __test.resolvePiInvocation !== \"function\") throw new Error(\"argv renderer exports missing\"); console.log(\"Node argv renderer: 2 exports loaded\")'",
34
34
  "typecheck": "tsc -p ../retina-local-fs/tsconfig.build.json && tsc --noEmit",
35
35
  "test": "bun ../../scripts/check-bun.mjs && bun install --frozen-lockfile && MC_SLOW_TESTS=0 BUN_JSC_useOMGJIT=0 bun test --parallel=4 --timeout 30000",