@cortexkit/pi-magic-context 0.44.3 → 0.44.4

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.
@@ -42,7 +42,7 @@ import {
42
42
  cleanUserText2,
43
43
  visitRawSessionMessages2,
44
44
  readSessionChunk2
45
- } from "./index-tckvezry.js";
45
+ } from "./index-npagr1cy.js";
46
46
  import {
47
47
  logSlowWriteTransaction
48
48
  } from "./index-97e5fzy3.js";
@@ -8801,6 +8801,8 @@ var dubiousOwnershipWarnedDirectories = new Set;
8801
8801
  var transientGitIdentityReuseLoggedDirectories = new Set;
8802
8802
  var sessionIdentityCache = new Map;
8803
8803
  var homeProjectPermission = false;
8804
+ var pausedIdentityReasons = new Map;
8805
+ var pausedIdentityLogged = new Set;
8804
8806
  function setHomeProjectPermission(allowed) {
8805
8807
  homeProjectPermission = allowed;
8806
8808
  }
@@ -8885,6 +8887,27 @@ function isGitTimeoutError(error) {
8885
8887
  const signal = getErrorSignal(error);
8886
8888
  return code === "ETIMEDOUT" || signal === "SIGTERM" || signal === "SIGKILL" || getErrorKilled(error);
8887
8889
  }
8890
+ function hasUnbornHead(directory) {
8891
+ const options = {
8892
+ cwd: directory,
8893
+ encoding: "utf8",
8894
+ env: { ...process.env, LC_ALL: "C", LANG: "C" },
8895
+ stdio: ["ignore", "pipe", "pipe"],
8896
+ timeout: GIT_TIMEOUT_MS,
8897
+ windowsHide: true
8898
+ };
8899
+ try {
8900
+ execFileSyncForIdentity("git", ["rev-parse", "--git-dir"], options);
8901
+ try {
8902
+ execFileSyncForIdentity("git", ["rev-parse", "--verify", "--quiet", "HEAD"], options);
8903
+ return false;
8904
+ } catch (error) {
8905
+ return !isGitTimeoutError(error) && typeof error === "object" && error !== null && "status" in error && error.status === 1 && getErrorStderr(error) === "";
8906
+ }
8907
+ } catch {
8908
+ return false;
8909
+ }
8910
+ }
8888
8911
  function classifyGitError(error, rawDirectory) {
8889
8912
  if (isGitTimeoutError(error)) {
8890
8913
  return new ProjectIdentityError("git_timeout", rawDirectory, `git rev-list timed out after ${GIT_TIMEOUT_MS}ms`, asError(error));
@@ -8927,7 +8950,11 @@ function resolveProjectIdentityStrict(directory, allowHomeProject = homeProjectP
8927
8950
  windowsHide: true
8928
8951
  });
8929
8952
  } catch (error) {
8930
- throw classifyGitError(error, directory);
8953
+ const classified = classifyGitError(error, directory);
8954
+ if (classified.errorClass === "not_git_repo" && hasUnbornHead(canonical)) {
8955
+ throw new ProjectIdentityError("no_commits", directory, "Git repository has no commits yet");
8956
+ }
8957
+ throw classified;
8931
8958
  }
8932
8959
  const rootCommit = output.split(`
8933
8960
  `).map((line) => line.trim().slice(0, 64)).filter((line) => /^[0-9a-f]{7,64}$/.test(line)).sort()[0];
@@ -9058,6 +9085,8 @@ function resolveProjectIdentity(directory, allowHomeProject = homeProjectPermiss
9058
9085
  } catch (error) {
9059
9086
  if (error instanceof ProjectIdentityError && shouldUseDirectoryFallback(error)) {
9060
9087
  const fallback = directoryFallback(canonical);
9088
+ if (error.errorClass === "no_commits")
9089
+ return fallback;
9061
9090
  const hasGitMetadata = hasGitDir(canonical);
9062
9091
  if (!hasGitMetadata) {
9063
9092
  if (error.errorClass === "permission_denied")
@@ -9169,9 +9198,18 @@ function resolveProjectIdentityForSession(directory, allowHomeProject = homeProj
9169
9198
  } catch (error) {
9170
9199
  if (!(error instanceof ProjectIdentityError))
9171
9200
  throw error;
9201
+ const reason = error.errorClass === "git_identity_unavailable" ? pausedIdentityReasons.get(resolvedDirectory) ?? error.errorClass : error.errorClass;
9202
+ pausedIdentityReasons.set(resolvedDirectory, reason);
9203
+ const logKey = `${resolvedDirectory}\x00${reason}`;
9204
+ if (!pausedIdentityLogged.has(logKey)) {
9205
+ pausedIdentityLogged.add(logKey);
9206
+ log(`[magic-context] memory features paused for ${resolvedDirectory}: ${reason}`);
9207
+ }
9172
9208
  identity = undefined;
9173
9209
  }
9174
9210
  }
9211
+ if (identity !== undefined)
9212
+ pausedIdentityReasons.delete(resolvedDirectory);
9175
9213
  sessionIdentityCache.set(cacheKey, {
9176
9214
  identity,
9177
9215
  revalidateAt: identity?.startsWith("git:") === true ? null : nowMs() + TRANSIENT_FAILURE_COOLDOWN_MS
@@ -15236,7 +15274,6 @@ var WINDOWS_CIM_PROBE_TIMEOUT_MS = 5000;
15236
15274
  var WINDOWS_PROCESS_SNAPSHOT_TTL_MS = 2000;
15237
15275
  var MAX_ANCESTOR_WALK_DEPTH = 16;
15238
15276
  var OPEN_CODE_COMMAND_MARKERS = ["opencode", "node", "bun", "electron"];
15239
- var TASKLIST_NO_TASKS_PATTERN = /^INFO:\s+No tasks are running which match the specified criteria\.?$/im;
15240
15277
  var WINDOWS_CIM_COMMAND = "Get-CimInstance Win32_Process | Select-Object ProcessId,ParentProcessId,Name,CommandLine,CreationDate | ConvertTo-Json -Compress";
15241
15278
  var PI_HARNESS_ARC_MARKERS = [
15242
15279
  "pi-coding-agent",
@@ -15330,18 +15367,14 @@ function parseCsvLine(line) {
15330
15367
  }
15331
15368
  function parseTasklistOutput(output) {
15332
15369
  const entries = [];
15333
- let sawHeader = false;
15334
15370
  for (const rawLine of output.split(/\r?\n/)) {
15335
15371
  const line = rawLine.trim();
15336
15372
  if (!line)
15337
15373
  continue;
15338
- if (TASKLIST_NO_TASKS_PATTERN.test(line))
15339
- return [];
15340
15374
  const fields = parseCsvLine(line);
15341
15375
  if (!fields)
15342
15376
  continue;
15343
15377
  if (fields[1]?.trim().toLowerCase() === "pid") {
15344
- sawHeader = true;
15345
15378
  continue;
15346
15379
  }
15347
15380
  const pid = Number(fields[1]);
@@ -15349,11 +15382,11 @@ function parseTasklistOutput(output) {
15349
15382
  continue;
15350
15383
  entries.push({ pid, command: fields[0] });
15351
15384
  }
15352
- return entries.length > 0 || sawHeader ? entries : null;
15385
+ return entries;
15353
15386
  }
15354
15387
  function readWindowsProcess(pid) {
15355
15388
  try {
15356
- const output = rpcIdentityExecFileSync("tasklist", ["/FO", "CSV", "/FI", `PID eq ${pid}`], {
15389
+ const output = rpcIdentityExecFileSync("tasklist", ["/FO", "CSV", "/NH", "/FI", `PID eq ${pid}`], {
15357
15390
  encoding: "utf8",
15358
15391
  timeout: PS_PROBE_TIMEOUT_MS,
15359
15392
  stdio: ["ignore", "pipe", "pipe"],
@@ -15590,7 +15623,11 @@ function tryReadWindowsCimSnapshot(exec) {
15590
15623
  }
15591
15624
  function tryReadWindowsTasklistSnapshot() {
15592
15625
  try {
15593
- const output = execProcessList(rpcProcessListExecFileSync, "tasklist", ["/FO", "CSV"]);
15626
+ const output = execProcessList(rpcProcessListExecFileSync, "tasklist", [
15627
+ "/FO",
15628
+ "CSV",
15629
+ "/NH"
15630
+ ]);
15594
15631
  const entries = parseTasklistOutput(output);
15595
15632
  if (entries === null)
15596
15633
  return null;
@@ -15799,7 +15836,7 @@ function inspectProcessesAsync(forceFresh = false) {
15799
15836
  snapshot = snapshotFromFacts(facts, "cim");
15800
15837
  } catch {}
15801
15838
  if (!snapshot) {
15802
- const entries = parseTasklistOutput(await asyncProcessExec("tasklist", ["/FO", "CSV"], PS_PROBE_TIMEOUT_MS));
15839
+ const entries = parseTasklistOutput(await asyncProcessExec("tasklist", ["/FO", "CSV", "/NH"], PS_PROBE_TIMEOUT_MS));
15803
15840
  if (entries)
15804
15841
  snapshot = snapshotFromFacts(entries.map(({ pid, command }) => ({
15805
15842
  pid,
@@ -15848,6 +15885,19 @@ function inspectProcessesAsync(forceFresh = false) {
15848
15885
  });
15849
15886
  return asyncInspection;
15850
15887
  }
15888
+ function inspectWindowsProcessesSync() {
15889
+ const snapshot = tryReadWindowsCimSnapshot(rpcProcessListExecFileSync) ?? tryReadWindowsTasklistSnapshot();
15890
+ const byPid = new Map(snapshot?.facts.map((fact) => [fact.pid, fact]));
15891
+ return {
15892
+ pi: snapshot ? classifyLivePiSnapshot(snapshot) : { state: "unreadable", processIds: [] },
15893
+ ...snapshot ? { processSnapshot: { source: snapshot.source, facts: snapshot.facts } } : {},
15894
+ evidence: (pid) => ({
15895
+ startTime: byPid.get(pid)?.startTime ?? null,
15896
+ commandLine: byPid.get(pid)?.commandLine ?? byPid.get(pid)?.imageName ?? null
15897
+ }),
15898
+ liveness: (pid) => byPid.has(pid) ? "alive" : snapshot ? "dead" : "inconclusive"
15899
+ };
15900
+ }
15851
15901
 
15852
15902
  // ../plugin/src/features/magic-context/context-authority.ts
15853
15903
  import { createHash as createHash6, randomUUID as randomUUID2 } from "node:crypto";
@@ -20411,7 +20461,9 @@ function classifyJunkDiscovery(portFile, raw, staleFiles) {
20411
20461
  log(`[magic-context] removing stale RPC discovery file ${portFile}: ${reason} record older than 10 minutes`);
20412
20462
  return null;
20413
20463
  }
20414
- function inspectRpcServerDiscovery(storageDir, processes) {
20464
+ function inspectRpcServerDiscovery(storageDir, processes, options) {
20465
+ const deadline = options?.deadlineMs === undefined ? Number.POSITIVE_INFINITY : Date.now() + options.deadlineMs;
20466
+ let progressAt = Date.now() + 3000;
20415
20467
  const rpcRoot = join3(storageDir, "rpc");
20416
20468
  let projectEntries;
20417
20469
  try {
@@ -20444,11 +20496,19 @@ function inspectRpcServerDiscovery(storageDir, processes) {
20444
20496
  if (portFiles.length === 0) {
20445
20497
  return { state: "absent", serverPids: [], staleFiles: [] };
20446
20498
  }
20499
+ if (!processes && process.platform === "win32")
20500
+ processes = inspectWindowsProcessesSync();
20447
20501
  const pids = new Set;
20448
20502
  const processByPid = new Map;
20449
20503
  const staleFiles = [];
20450
20504
  const inconclusivePids = new Set;
20451
- for (const portFile of portFiles) {
20505
+ for (const [index, portFile] of portFiles.entries()) {
20506
+ if (Date.now() >= deadline)
20507
+ throw new Error(`RPC holder inspection timed out after ${Math.round((options?.deadlineMs ?? 0) / 1000)} seconds (${index}/${portFiles.length} records checked). Close OpenCode and Pi, then retry.`);
20508
+ if (options?.onProgress && Date.now() >= progressAt) {
20509
+ options.onProgress(index, portFiles.length);
20510
+ progressAt = Date.now() + 3000;
20511
+ }
20452
20512
  let raw;
20453
20513
  try {
20454
20514
  raw = rpcDiscoveryFs.readFileSync(portFile, "utf8");
@@ -20486,7 +20546,7 @@ function inspectRpcServerDiscovery(storageDir, processes) {
20486
20546
  if (!previous || previous.kind === "process" && detected.kind !== "process") {
20487
20547
  processByPid.set(record.pid, detected);
20488
20548
  }
20489
- } else if (identity === "implausible") {
20549
+ } else if (identity === "implausible" && !((processes?.processSnapshot?.source === "cim" || processes?.processSnapshot?.source === "tasklist") && liveness === "alive")) {
20490
20550
  staleFiles.push(portFile);
20491
20551
  } else {
20492
20552
  inconclusivePids.add(record.pid);
@@ -20637,7 +20697,7 @@ function finishDatabaseOpen(db, dbPath, explicitDbPath, latestSupportedVersion)
20637
20697
  { readRawSessionMessagePage, readRawSessionMessages },
20638
20698
  { startMessageTimeBackfill }
20639
20699
  ] = await Promise.all([
20640
- import("./read-session-chunk-z2weg25w.js"),
20700
+ import("./read-session-chunk-w493f72c.js"),
20641
20701
  import("./message-time-backfill-5yrp95cx.js")
20642
20702
  ]);
20643
20703
  await startMessageTimeBackfill(db, Object.assign(readRawSessionMessages, {
@@ -25210,8 +25270,8 @@ function attachPiPartVersion(parts, version) {
25210
25270
  return part;
25211
25271
  });
25212
25272
  }
25213
- function convertEntriesToRawMessageRange(entries, afterOrdinal, limit, finalWatermark) {
25214
- const result = [];
25273
+ function* iterateEntriesToRawMessageRange(entries, afterOrdinal, limit, finalWatermark) {
25274
+ let emitted = 0;
25215
25275
  const normalizedAfter = Math.max(0, Math.floor(afterOrdinal));
25216
25276
  const normalizedLimit = Math.max(1, Math.floor(limit));
25217
25277
  const normalizedWatermark = Math.max(normalizedAfter, Math.floor(finalWatermark));
@@ -25221,19 +25281,20 @@ function convertEntriesToRawMessageRange(entries, afterOrdinal, limit, finalWate
25221
25281
  let pendingFirstRealId = "";
25222
25282
  let pendingFirstRealVersion = "";
25223
25283
  let pendingFirstCreatedAt = null;
25224
- const appendMessage = (id, role, version, createdAt, parts) => {
25284
+ const appendMessage = function* (id, role, version, createdAt, parts) {
25225
25285
  const ordinal = nextOrdinal++;
25226
25286
  if (ordinal > normalizedAfter && ordinal <= normalizedWatermark) {
25227
- result.push({
25287
+ emitted++;
25288
+ yield {
25228
25289
  ordinal,
25229
25290
  id,
25230
25291
  role,
25231
25292
  parts: parts(),
25232
25293
  version,
25233
25294
  ...createdAt === null ? {} : { createdAt }
25234
- });
25295
+ };
25235
25296
  }
25236
- return result.length >= normalizedLimit || nextOrdinal > normalizedWatermark;
25297
+ return emitted >= normalizedLimit || nextOrdinal > normalizedWatermark;
25237
25298
  };
25238
25299
  for (const entry of entries) {
25239
25300
  if (!isMessageEntry(entry))
@@ -25259,7 +25320,7 @@ function convertEntriesToRawMessageRange(entries, afterOrdinal, limit, finalWate
25259
25320
  if (role === "user") {
25260
25321
  const version = rawEntryVersion(entry);
25261
25322
  const bufferedToolParts = pendingToolParts;
25262
- const done = appendMessage(entry.id, "user", version, parsePiEntryTimestamp(entry), () => [
25323
+ const done = yield* appendMessage(entry.id, "user", version, parsePiEntryTimestamp(entry), () => [
25263
25324
  ...bufferedToolParts,
25264
25325
  ...attachPiPartVersion(synthesizeUserParts(msg), version)
25265
25326
  ]);
@@ -25277,7 +25338,7 @@ function convertEntriesToRawMessageRange(entries, afterOrdinal, limit, finalWate
25277
25338
  const bufferedToolParts = pendingToolParts;
25278
25339
  const pendingId = pendingFirstRealId;
25279
25340
  const pendingVersion = pendingFirstRealVersion;
25280
- const done = appendMessage(`${SYNTH_USER_ID_PREFIX}${pendingId}`, "user", pendingVersion, pendingFirstCreatedAt, () => bufferedToolParts);
25341
+ const done = yield* appendMessage(`${SYNTH_USER_ID_PREFIX}${pendingId}`, "user", pendingVersion, pendingFirstCreatedAt, () => bufferedToolParts);
25281
25342
  pendingToolParts = [];
25282
25343
  hasPendingToolParts = false;
25283
25344
  pendingFirstRealId = "";
@@ -25287,25 +25348,28 @@ function convertEntriesToRawMessageRange(entries, afterOrdinal, limit, finalWate
25287
25348
  break;
25288
25349
  }
25289
25350
  const version = rawEntryVersion(entry);
25290
- if (appendMessage(entry.id, "assistant", version, parsePiEntryTimestamp(entry), () => attachPiPartVersion(synthesizeAssistantParts(msg), version))) {
25351
+ if (yield* appendMessage(entry.id, "assistant", version, parsePiEntryTimestamp(entry), () => attachPiPartVersion(synthesizeAssistantParts(msg), version))) {
25291
25352
  break;
25292
25353
  }
25293
25354
  continue;
25294
25355
  }
25295
- if (appendMessage(entry.id, typeof role === "string" ? role : "unknown", rawEntryVersion(entry), parsePiEntryTimestamp(entry), () => [])) {
25356
+ if (yield* appendMessage(entry.id, typeof role === "string" ? role : "unknown", rawEntryVersion(entry), parsePiEntryTimestamp(entry), () => [])) {
25296
25357
  break;
25297
25358
  }
25298
25359
  }
25299
- if (hasPendingToolParts && result.length < normalizedLimit && nextOrdinal <= normalizedWatermark) {
25300
- appendMessage(`${SYNTH_USER_ID_PREFIX}${pendingFirstRealId}`, "user", pendingFirstRealVersion, pendingFirstCreatedAt, () => pendingToolParts);
25360
+ if (hasPendingToolParts && emitted < normalizedLimit && nextOrdinal <= normalizedWatermark) {
25361
+ yield* appendMessage(`${SYNTH_USER_ID_PREFIX}${pendingFirstRealId}`, "user", pendingFirstRealVersion, pendingFirstCreatedAt, () => pendingToolParts);
25301
25362
  }
25302
- return result;
25303
25363
  }
25304
25364
  function convertEntriesToRawMessages(entries) {
25305
- return convertEntriesToRawMessageRange(entries, 0, Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER);
25365
+ return [
25366
+ ...iterateEntriesToRawMessageRange(entries, 0, Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER)
25367
+ ];
25306
25368
  }
25307
25369
  function convertEntriesToRawMessagePage(entries, afterOrdinal, limit, finalWatermark) {
25308
- return convertEntriesToRawMessageRange(entries, afterOrdinal, limit, finalWatermark);
25370
+ return [
25371
+ ...iterateEntriesToRawMessageRange(entries, afterOrdinal, limit, finalWatermark)
25372
+ ];
25309
25373
  }
25310
25374
  function isMessageEntry(value) {
25311
25375
  if (value === null || typeof value !== "object")
@@ -27795,6 +27859,28 @@ function blockedEmbeddingEndpointReason(endpoint) {
27795
27859
  }
27796
27860
 
27797
27861
  // ../plugin/src/features/magic-context/memory/embedding-openai.ts
27862
+ function capEmbeddingInput(input, maxInputTokens, purpose) {
27863
+ const ratio = purpose === "query" ? CHUNK_WINDOW_SAFETY_RATIO : 1;
27864
+ const budget = Math.max(1, Math.floor(maxInputTokens * ratio));
27865
+ if (estimateTokens(input) <= budget)
27866
+ return input;
27867
+ let low = 0;
27868
+ let high = input.length;
27869
+ while (low < high) {
27870
+ const mid = Math.ceil((low + high) / 2);
27871
+ if (estimateTokens(input.slice(0, mid)) <= budget)
27872
+ low = mid;
27873
+ else
27874
+ high = mid - 1;
27875
+ }
27876
+ if (low > 0 && low < input.length) {
27877
+ const last = input.charCodeAt(low - 1);
27878
+ const next = input.charCodeAt(low);
27879
+ if (last >= 55296 && last <= 56319 && next >= 56320 && next <= 57343)
27880
+ low -= 1;
27881
+ }
27882
+ return input.slice(0, low);
27883
+ }
27798
27884
  function normalizeEndpoint3(endpoint) {
27799
27885
  return endpoint?.trim().replace(/\/+$/, "") ?? "";
27800
27886
  }
@@ -27821,6 +27907,7 @@ class OpenAICompatibleEmbeddingProvider {
27821
27907
  modelMismatchLogged = false;
27822
27908
  lastFailureReason = null;
27823
27909
  halfOpenProbeInFlight = false;
27910
+ queryTruncationLogged = false;
27824
27911
  constructor(options) {
27825
27912
  this.endpoint = normalizeEndpoint3(options.endpoint);
27826
27913
  this.model = options.model?.trim() ?? "";
@@ -27874,7 +27961,15 @@ class OpenAICompatibleEmbeddingProvider {
27874
27961
  return [];
27875
27962
  }
27876
27963
  const textPrefix = purpose === "query" ? this.queryPrefix : this.documentPrefix;
27877
- const requestTexts = texts.map((text) => `${textPrefix}${text.trim().length === 0 ? " " : text}`);
27964
+ const requestTexts = texts.map((text) => {
27965
+ const input = `${textPrefix}${text.trim().length === 0 ? " " : text}`;
27966
+ const capped = capEmbeddingInput(input, this.maxInputTokens, purpose);
27967
+ if (purpose === "query" && capped.length < input.length && !this.queryTruncationLogged) {
27968
+ log(`[magic-context] embedding query truncated from ${input.length} to ${capped.length} characters to fit max_input_tokens`);
27969
+ this.queryTruncationLogged = true;
27970
+ }
27971
+ return capped;
27972
+ });
27878
27973
  if (!await this.initialize()) {
27879
27974
  return Array.from({ length: texts.length }, () => null);
27880
27975
  }
@@ -38702,7 +38797,8 @@ var EPOCH_COMPONENT_PREFIX = "|compartment-render:";
38702
38797
  var MEMORY_EPOCH_COMPONENT_PREFIX = "|memory-render:";
38703
38798
  var MURAL_COMPONENT_PREFIX = "|mural-enabled:";
38704
38799
  var BUDGET_COMPONENT_PREFIX = "|render-budgets:";
38705
- function encodeCachedM0UpgradeIdentity(upgradeState, compartmentRenderEpoch = COMPARTMENT_RENDER_EPOCH, muralEnabled = null, renderBudgetIdentity = null, memoryRenderEpoch = MEMORY_RENDER_FORMAT_EPOCH) {
38800
+ var RENDERED_BUDGETS_COMPONENT_PREFIX = "|rendered-budgets:";
38801
+ function encodeCachedM0UpgradeIdentity(upgradeState, compartmentRenderEpoch = COMPARTMENT_RENDER_EPOCH, muralEnabled = null, renderBudgetIdentity = null, memoryRenderEpoch = MEMORY_RENDER_FORMAT_EPOCH, renderedBudgets = null) {
38706
38802
  let encoded = upgradeState ?? "";
38707
38803
  if (compartmentRenderEpoch !== null) {
38708
38804
  encoded += `${EPOCH_COMPONENT_PREFIX}${compartmentRenderEpoch}`;
@@ -38716,6 +38812,9 @@ function encodeCachedM0UpgradeIdentity(upgradeState, compartmentRenderEpoch = CO
38716
38812
  if (renderBudgetIdentity !== null) {
38717
38813
  encoded += `${BUDGET_COMPONENT_PREFIX}${renderBudgetIdentity}`;
38718
38814
  }
38815
+ if (renderedBudgets !== null) {
38816
+ encoded += `${RENDERED_BUDGETS_COMPONENT_PREFIX}${renderedBudgets}`;
38817
+ }
38719
38818
  return encoded.length > 0 ? encoded : null;
38720
38819
  }
38721
38820
  function component(value, prefix) {
@@ -38734,14 +38833,16 @@ function decodeCachedM0UpgradeIdentity(value) {
38734
38833
  compartmentRenderEpoch: null,
38735
38834
  memoryRenderEpoch: null,
38736
38835
  muralEnabled: null,
38737
- renderBudgetIdentity: null
38836
+ renderBudgetIdentity: null,
38837
+ renderedBudgets: null
38738
38838
  };
38739
38839
  }
38740
38840
  const componentIndexes = [
38741
38841
  value.indexOf(EPOCH_COMPONENT_PREFIX),
38742
38842
  value.indexOf(MEMORY_EPOCH_COMPONENT_PREFIX),
38743
38843
  value.indexOf(MURAL_COMPONENT_PREFIX),
38744
- value.indexOf(BUDGET_COMPONENT_PREFIX)
38844
+ value.indexOf(BUDGET_COMPONENT_PREFIX),
38845
+ value.indexOf(RENDERED_BUDGETS_COMPONENT_PREFIX)
38745
38846
  ].filter((index) => index >= 0);
38746
38847
  const identityEnd = componentIndexes.length > 0 ? Math.min(...componentIndexes) : value.length;
38747
38848
  const upgradeState = value.slice(0, identityEnd);
@@ -38751,9 +38852,36 @@ function decodeCachedM0UpgradeIdentity(value) {
38751
38852
  compartmentRenderEpoch: component(value, EPOCH_COMPONENT_PREFIX),
38752
38853
  memoryRenderEpoch: component(value, MEMORY_EPOCH_COMPONENT_PREFIX),
38753
38854
  muralEnabled: muralComponent === "1" ? true : muralComponent === "0" ? false : null,
38754
- renderBudgetIdentity: component(value, BUDGET_COMPONENT_PREFIX)
38855
+ renderBudgetIdentity: component(value, BUDGET_COMPONENT_PREFIX),
38856
+ renderedBudgets: component(value, RENDERED_BUDGETS_COMPONENT_PREFIX)
38755
38857
  };
38756
38858
  }
38859
+ function renderBudgetIdentityChanged(cached, current) {
38860
+ const legacy = /^(m[^-]+)-h\d+$/.exec(cached);
38861
+ if (legacy && current.startsWith("m") && current.includes("-hp")) {
38862
+ return legacy[1] !== current.slice(0, current.indexOf("-h"));
38863
+ }
38864
+ return cached !== current;
38865
+ }
38866
+ function renderedBudgetSnapshot(memoryTokens, historyTokens) {
38867
+ return `m${memoryTokens}-h${historyTokens}`;
38868
+ }
38869
+ function readRenderedBudgets(value) {
38870
+ const match = value?.match(/^m(\d+(?:\.\d+)?)-h(\d+(?:\.\d+)?)$/);
38871
+ if (!match)
38872
+ return null;
38873
+ const memory = Number(match[1]);
38874
+ const history = Number(match[2]);
38875
+ return Number.isFinite(memory) && Number.isFinite(history) ? { memory, history } : null;
38876
+ }
38877
+ function renderedBudgetShrinkReason(cached, current) {
38878
+ const before = readRenderedBudgets(cached);
38879
+ const after = readRenderedBudgets(current);
38880
+ if (!before || !after)
38881
+ return null;
38882
+ const shrunk = (oldTokens, newTokens) => oldTokens - newTokens > Math.max(64, oldTokens * 0.01);
38883
+ return shrunk(before.memory, after.memory) || shrunk(before.history, after.history) ? `render_config:budget_shrink(${cached}→${current})` : null;
38884
+ }
38757
38885
 
38758
38886
  // ../plugin/src/hooks/magic-context/decay-curve.ts
38759
38887
  var H50 = 24;
@@ -39604,4 +39732,4 @@ function registerMagicContextTools(pi, opts) {
39604
39732
  }
39605
39733
  }
39606
39734
 
39607
- export { COMPACTION_ENABLED_PATH, isDreamerRunnable, isCompactionEnabled, formatConfigParseStatusLine, formatConfigParseNotice, claimConfigParseFailuresOnce, parseJsoncRecovering, detectConfigFile, canonicalModelIdentity, piModelRefToCanonical, resolveModelRefForPi, modelRefLookupOrder, ompModelRefToCanonical, resolveModelRefForOmp, setStoragePrivatePermissionEnforcement, MIN_PLAUSIBLE_CONTEXT_LIMIT, catalogOutputReserve, reloadWindowOverlay, getWindowOverlay, resolveWindowOverlayFacts, deriveWindowGeometry, hasTrustedAbsoluteWall, applyProvenInputFloor, formatWindowDerivationLine, isSaneLimit, resolveOutputReserve, getSdkWindowGeometry, getSdkContextLimit, getSdkOutputLimit, getSdkInputLimit, cortexKitUserConfigBasePath, cortexKitProjectConfigBasePath, migrateMagicContextConfigLocations, withContentLanguageDirective, parseCron, nextOccurrence, nextDueAtMs, resolveModelConfigValue, DEFAULT_HISTORIAN_TIMEOUT_MS, DREAM_TASK_PROMOTION_DEFAULTS, LIVE_RELOAD_CONFIG_PATHS, getProtectedTokensTierOverrides, FAIL_CLOSED_DOCTOR_COMMAND, formatFailClosedBlockingMessage, createFailClosedBlockingError, isFailClosedBlockingError, shouldBypassFailClosedBlock, createFailClosedController, setHomeProjectPermission, ProjectIdentityError, resolveProjectIdentityStrict, isUserHomeDirectory, resolveProjectIdentity, isUsableProjectIdentity, resolveProjectIdentityForSession, beginBootQuietPeriod, scheduleAfterBootQuiet, clearCompressionDepth, clearCompressionDepthRange, formatSynapseLaneDescriptor, buildCanonicalChunkTextFromFts, buildCompartmentSummaryFallbackText, canonicalizeInMemoryChunkTextForEmbedding, chunkCanonicalText, chunkEmbeddingWindowsAreCurrent, replaceCompartmentChunkEmbeddings, deleteChunkEmbedBackoffForSession, readSessionActivity, observeSessionActivity, backfillSessionActivity, getMessageIndexSourceIdentity, isMessageIndexSourceCurrent, getLastIndexedOrdinal, getMessageIndexReconciliationStartOrdinal, isMessageIndexReconciledThrough, indexSingleMessage, indexMessagesAfterOrdinal, sweepOrphanedOpenCodeMessageIndexes, MAX_EXECUTE_THRESHOLD, escalationBands, HYGIENE_PROVIDER_UNITS_VERSION, sessionDecisionCalibration, transitionSessionHygieneUnits, computeProtectionWindow, readEpochFloorSnapshot, getProtectionWindowForSession, persistCachedM0, clearCachedM0M1, readReplayDocument, updateReplayDocument, isProviderOverflowFailClosedProven, describeProtectedTailDrainBudgetSkip, loadProtectedTailMeta, markProtectedTailPolicyV3Seeded, recordProtectedTailPublicationFloor, recordProtectedTailNoEligibleHead, getWrapupInProgressState, isWrapupInProgress, acquireWrapupInProgress, updateWrapupInProgress, releaseWrapupInProgress, resolveCompactionModeRecord, getCompactionModeRecord, setCompactionModeRecord, reserveProtectedTailDrainTokens, clearEmergencyDrainLatch, recordHistorianDrainFailure, clearHistorianDrainFailure, rollbackProtectedTailDrainReservation, clearPersistedReasoningWatermark, getEmergencyInputSample, setEmergencyDropSample, clearEmergencyDropSample, getLastNudgeUndropped, setLastNudgeUndropped, getChannel1NudgeState, setChannel1NudgeState, markChannel1PostReduceGracePending, captureChannel1PostReduceGraceBaseline, getChannel2NudgeState, getChannel2NudgeClaim, setChannel2NudgeState, casChannel2NudgeState, claimChannel2NudgeState, casChannel2NudgeClaim, getPersistedNoteNudge, setPersistedNoteNudgeTrigger, setPersistedNoteNudgeTriggerMessageId, getNoteNudgeAnchors, getAutoSearchHintDecisions, deliverNoteNudgeAtomic, appendAutoSearchHintDecision, pruneNoteNudgeAnchors, pruneAutoSearchHintDecisions, getPersistedTodoSyntheticAnchor, setPersistedTodoSyntheticAnchor, clearPersistedTodoSyntheticAnchor, getNoteLastReadAt, incrementHistorianFailure, clearHistorianFailureState, getOverflowState, recordOverflowDetected, clearEmergencyRecovery, clearDetectedContextLimit, getStrippedPlaceholderIds, applyStrippedPlaceholderDelta, THINKING_BINDING_RECOVERY_FROZEN_PREFIX, THINKING_BINDING_STRIP_ORDER_END_MARKER, thinkingBindingRecoveryFrozenId, getThinkingBindingRecoveryTarget, armThinkingBindingRecovery, clearThinkingBindingRecoveryIf, getMergedReasoningStrippedIds, addMergedReasoningStrippedIds, getProcessedImageStrippedIds, addProcessedImageStrippedIds, getPendingCompactionMarkerState, getCompactionMarkerHealth, clearPendingCompactionMarkerStateIf, getPendingPiCompactionMarkerState, setPendingPiCompactionMarkerState, clearPendingPiCompactionMarkerStateIf, getSessionsWithPendingPiMarker, setSessionWorkMetrics, getSessionWorkMetrics, resolveEpochFloorForPass, getOrCreateSessionMeta, updateSessionMeta, advanceToolReclaimWatermark, retryPendingSessionCleanups, retryPendingRustSessionCleanupsForProject, recordSessionProjectIdentity, embedPauseBySession, embedRunStateBySession, autoEmbedAttemptedBySession, autoEmbedIdentityBySession, invalidateAutoEmbedSession, getEmbedDrainUiStatus, piHarnessKindFromExecutable, COMPARTMENT_LEASE_RENEWAL_MS, acquireCompartmentLease, renewCompartmentLease, releaseCompartmentLease, releaseCompartmentLeaseBestEffort, isCompartmentLeaseHeld, isNoContentCompartment, HAS_COMPARTMENT_CONTENT_SQL, getCompartments, getLastCompartmentEndMessage, getLastCompartmentEndMessageId, getCompartmentsByEndMessageId, appendCompartments, saveRecompStagingPass, getRecompStaging, clearRecompStaging, getRecompPartialRange, setRecompPartialRange, escapeXmlAttr, escapeXmlContent, getModuleNoteEvaluationBridge, getContextStoreUuid, getAuthorityManagedMarker, drainMirrorPages, V2_MEMORY_CATEGORIES, parseCompartmentOutput, resolveWorkspaceShareCategories, resolveWorkspaceIdentitySet, expandWorkspaceIdentitySetWithAliases, sourceNameForMemory, computeWorkspaceEpochFingerprint, readProjectDocsCanonical, BoundedSessionMap, registerLkgPersistence, signatureForFields, lkgContentFields, lkgContentDigestFromFields, exactReusablePrefix, incrementalLkgContentDigests, captureSlot, getSlot, dropSlot, noteEntry, encodePiContentDecision, getPiContentDecisions, freezePiContentDecision, getNativeReplayState, saveNativeToolInputs, addNativeReasoningIds, copySessionStateForClone, getErrorMessage, describeError, getSchemaFenceRejection, getMigrationOnOpenRefusal, LATEST_SUPPORTED_VERSION, getDatabasePath, getPersistedSchemaVersion, setSqlitePragmaConfig, applySqliteTuningPragmas, runSqliteOptimize, openDatabase, openDatabaseAsync, closeDatabase, queueM0Mutation, getMaxM0MutationId, queueMemoryMutation, getMemoryMutationsForRender, getMemoryMutationsForRenderByProjects, getMaxMemoryMutationId, getMaxMemoryMutationIdForProjects, getNotes, getSessionNotes, getPendingSmartNotes, getReadySmartNotes, markNoteReady, markNoteChecked, queuePendingOp, getPendingOps, getPendingOpsCount, clearPendingOps, removePendingOp, PRIMER_CANDIDATE_TTL_MS, PRIMER_CANDIDATE_MAX_AGE_MS, primerOccurrenceKey, primerOccurrenceUtcDay, insertPrimerCandidates, updatePrimerCandidateEmbedding, getPrimerCandidatesByIds, getPrimerCandidatesForPromotion, countPrimerCandidatesForProject, getActivePrimers, createPrimer, updatePrimerSupport, updatePrimerAnswer, GLOBAL_USER_PROFILE_PROJECT_PATH, getProjectState, bumpProjectUserProfileVersion, saveSourceContent, getSourceContents, recordSubagentInvocation, getLatestHistorianInvocationId, noteTouchedAt, noteNudgePickIndex, formatNoteNudge, promptSurfaceHashMaterial, createPromptSurfaceRuntime, createPromptSurfaceGuidanceEpochCache, SYNTH_USER_ID_PREFIX, resolvePiStableId, readPiSessionSnapshot, readPiSessionMessages, readPiSessionMessagePage, findLastModelKeyFromBranch, convertEntriesToRawMessages, convertEntriesToRawMessagePage, computeCueContentHash, hasMuralCueColumns, getMuralCueState, memoryNeedsCue, setMuralCue, recordMuralCueRejection, invalidateMemory, computeNormalizedHash, hasMemoryShareableColumn, hasMemoryClassifiedAtColumn, getUnclassifiedMemoryIds, insertMemory, getMemoryByHash, getMemoriesByProject, getMemoriesByProjects, getMaxMemoryIdForProjects, getMemoryById, setMemoryClassification, archiveMemory, getMemoryCountsByStatus, USER_MEMORY_CANDIDATE_TTL_MS, insertUserMemoryCandidates, getUserMemoryCandidates, deleteUserMemoryCandidates, pruneExpiredUserMemoryCandidates, insertUserMemory, getActiveUserMemories, updateUserMemoryContent, dismissUserMemory, getTaskScheduleState, getFailingDreamTasks, getMostRecentTaskRunAt, pruneNonCanonicalTaskRows, deleteTaskScheduleRowsForProject, seedTaskScheduleState, writeTaskScheduleState, isRetrospectiveWindowProcessed, recordRetrospectiveWindowProcessed, curateCategoryForMemoryCategory, peekCurateCategoryScope, beginCurateCategoryRun, curateTaskStateAfterSuccess, cosineSimilarity, GIT_SWEEP_LEASE_RENEWAL_MS, acquireGitSweepLease, renewGitSweepLease, markGitSweepSuccessAndRelease, parkGitSweepNonIndexable, releaseGitSweepLease, describeShadowBackfillWriteRefusal, contentSha256, sweepStaleEmbeddingIdentitiesForProject, enqueueShadowEmbeddingItems, getProjectEmbeddingSnapshot, getProjectChunkEmbeddingModelId, getProjectEmbeddingMaxInputTokens, embedTextForProject, embedBatchForProject, embedItemsForProject, embedUnembeddedMemoriesForProject, drainCommitBacklogForProject, embedSessionCompartmentChunks, getEmbeddingCoverageStatus, getAutoEmbeddingSessionCoverage, promoteSessionFactsDurable, embedPromotedFacts, recordMemoryMapping, recordMemoryVerifications, getUnmappedMemoryIds, clearMemoryVerifications, getMemoryVerifications, resolveGitTopLevel, readGitHead, readGitChangedFilesSince, readGitFileChangeTimesSince, verificationFileExists, normalizeVerificationFiles, isDirectiveShapedProjectRule, takeCurateSafetyRefusalCount, wakePlaneStatus, indexCommitsForProject, embedUnembeddedCommits, loadPiConfig, loadPiConfigDetailed, unregisterPiProjectEmbeddings, ensureProjectRegisteredFromPiDirectory, resolvePiHarnessDetection, resolvePiHarnessKind, MEMORY_MURAL_BLOCK, buildMagicContextSection, resolveMuralWire, updateCompactionMarkerAfterPublication, COMPARTMENT_RENDER_EPOCH, MEMORY_RENDER_FORMAT_EPOCH, encodeCachedM0UpgradeIdentity, decodeCachedM0UpgradeIdentity, DEFAULT_HISTORY_BUDGET_TOKENS, renderCompartmentAtTier, renderDecayedCompartments, extractM0Block, TEMPORAL_MARKER_PATTERN, temporalMarkerPrefix, clearInjectionCache, getVisibleMemoryIds, renderHistorianMemoryBlock, DEFAULT_MEMORY_BUDGET_TOKENS, DEFAULT_USER_PROFILE_BUDGET_TOKENS, trimMemoriesToBudgetV2, trimWorkspaceMemoriesToBudgetV2, trimUserMemoriesToBudget, renderMemoryBlockV2, stripMemoryMuralBlock, unifiedSearch, rememberTodowriteToolCallTodos, parseTodos, setTodoSnapshot, registerTodoOverlay, registerTodoStateLifecycle, syncCtxMemoryToolEnabled, registerMagicContextTools };
39735
+ export { COMPACTION_ENABLED_PATH, isDreamerRunnable, isCompactionEnabled, formatConfigParseStatusLine, formatConfigParseNotice, claimConfigParseFailuresOnce, parseJsoncRecovering, detectConfigFile, canonicalModelIdentity, piModelRefToCanonical, resolveModelRefForPi, modelRefLookupOrder, ompModelRefToCanonical, resolveModelRefForOmp, setStoragePrivatePermissionEnforcement, MIN_PLAUSIBLE_CONTEXT_LIMIT, catalogOutputReserve, reloadWindowOverlay, getWindowOverlay, resolveWindowOverlayFacts, deriveWindowGeometry, hasTrustedAbsoluteWall, applyProvenInputFloor, formatWindowDerivationLine, isSaneLimit, resolveOutputReserve, getSdkWindowGeometry, getSdkContextLimit, getSdkOutputLimit, getSdkInputLimit, cortexKitUserConfigBasePath, cortexKitProjectConfigBasePath, migrateMagicContextConfigLocations, withContentLanguageDirective, parseCron, nextOccurrence, nextDueAtMs, resolveModelConfigValue, DEFAULT_HISTORIAN_TIMEOUT_MS, DREAM_TASK_PROMOTION_DEFAULTS, LIVE_RELOAD_CONFIG_PATHS, getProtectedTokensTierOverrides, FAIL_CLOSED_DOCTOR_COMMAND, formatFailClosedBlockingMessage, createFailClosedBlockingError, isFailClosedBlockingError, shouldBypassFailClosedBlock, createFailClosedController, setHomeProjectPermission, ProjectIdentityError, resolveProjectIdentityStrict, isUserHomeDirectory, resolveProjectIdentity, isUsableProjectIdentity, resolveProjectIdentityForSession, beginBootQuietPeriod, scheduleAfterBootQuiet, clearCompressionDepth, clearCompressionDepthRange, formatSynapseLaneDescriptor, buildCanonicalChunkTextFromFts, buildCompartmentSummaryFallbackText, canonicalizeInMemoryChunkTextForEmbedding, chunkCanonicalText, chunkEmbeddingWindowsAreCurrent, replaceCompartmentChunkEmbeddings, deleteChunkEmbedBackoffForSession, readSessionActivity, observeSessionActivity, backfillSessionActivity, getMessageIndexSourceIdentity, isMessageIndexSourceCurrent, getLastIndexedOrdinal, getMessageIndexReconciliationStartOrdinal, isMessageIndexReconciledThrough, indexSingleMessage, indexMessagesAfterOrdinal, sweepOrphanedOpenCodeMessageIndexes, MAX_EXECUTE_THRESHOLD, escalationBands, HYGIENE_PROVIDER_UNITS_VERSION, sessionDecisionCalibration, transitionSessionHygieneUnits, computeProtectionWindow, readEpochFloorSnapshot, getProtectionWindowForSession, persistCachedM0, clearCachedM0M1, readReplayDocument, updateReplayDocument, isProviderOverflowFailClosedProven, describeProtectedTailDrainBudgetSkip, loadProtectedTailMeta, markProtectedTailPolicyV3Seeded, recordProtectedTailPublicationFloor, recordProtectedTailNoEligibleHead, getWrapupInProgressState, isWrapupInProgress, acquireWrapupInProgress, updateWrapupInProgress, releaseWrapupInProgress, resolveCompactionModeRecord, getCompactionModeRecord, setCompactionModeRecord, reserveProtectedTailDrainTokens, clearEmergencyDrainLatch, recordHistorianDrainFailure, clearHistorianDrainFailure, rollbackProtectedTailDrainReservation, clearPersistedReasoningWatermark, getEmergencyInputSample, setEmergencyDropSample, clearEmergencyDropSample, getLastNudgeUndropped, setLastNudgeUndropped, getChannel1NudgeState, setChannel1NudgeState, markChannel1PostReduceGracePending, captureChannel1PostReduceGraceBaseline, getChannel2NudgeState, getChannel2NudgeClaim, setChannel2NudgeState, casChannel2NudgeState, claimChannel2NudgeState, casChannel2NudgeClaim, getPersistedNoteNudge, setPersistedNoteNudgeTrigger, setPersistedNoteNudgeTriggerMessageId, getNoteNudgeAnchors, getAutoSearchHintDecisions, deliverNoteNudgeAtomic, appendAutoSearchHintDecision, pruneNoteNudgeAnchors, pruneAutoSearchHintDecisions, getPersistedTodoSyntheticAnchor, setPersistedTodoSyntheticAnchor, clearPersistedTodoSyntheticAnchor, getNoteLastReadAt, incrementHistorianFailure, clearHistorianFailureState, getOverflowState, recordOverflowDetected, clearEmergencyRecovery, clearDetectedContextLimit, getStrippedPlaceholderIds, applyStrippedPlaceholderDelta, THINKING_BINDING_RECOVERY_FROZEN_PREFIX, THINKING_BINDING_STRIP_ORDER_END_MARKER, thinkingBindingRecoveryFrozenId, getThinkingBindingRecoveryTarget, armThinkingBindingRecovery, clearThinkingBindingRecoveryIf, getMergedReasoningStrippedIds, addMergedReasoningStrippedIds, getProcessedImageStrippedIds, addProcessedImageStrippedIds, getPendingCompactionMarkerState, getCompactionMarkerHealth, clearPendingCompactionMarkerStateIf, getPendingPiCompactionMarkerState, setPendingPiCompactionMarkerState, clearPendingPiCompactionMarkerStateIf, getSessionsWithPendingPiMarker, setSessionWorkMetrics, getSessionWorkMetrics, resolveEpochFloorForPass, getOrCreateSessionMeta, updateSessionMeta, advanceToolReclaimWatermark, retryPendingSessionCleanups, retryPendingRustSessionCleanupsForProject, recordSessionProjectIdentity, embedPauseBySession, embedRunStateBySession, autoEmbedAttemptedBySession, autoEmbedIdentityBySession, invalidateAutoEmbedSession, getEmbedDrainUiStatus, piHarnessKindFromExecutable, COMPARTMENT_LEASE_RENEWAL_MS, acquireCompartmentLease, renewCompartmentLease, releaseCompartmentLease, releaseCompartmentLeaseBestEffort, isCompartmentLeaseHeld, isNoContentCompartment, HAS_COMPARTMENT_CONTENT_SQL, getCompartments, getLastCompartmentEndMessage, getLastCompartmentEndMessageId, getCompartmentsByEndMessageId, appendCompartments, saveRecompStagingPass, getRecompStaging, clearRecompStaging, getRecompPartialRange, setRecompPartialRange, escapeXmlAttr, escapeXmlContent, getModuleNoteEvaluationBridge, getContextStoreUuid, getAuthorityManagedMarker, drainMirrorPages, V2_MEMORY_CATEGORIES, parseCompartmentOutput, resolveWorkspaceShareCategories, resolveWorkspaceIdentitySet, expandWorkspaceIdentitySetWithAliases, sourceNameForMemory, computeWorkspaceEpochFingerprint, readProjectDocsCanonical, BoundedSessionMap, registerLkgPersistence, signatureForFields, lkgContentFields, lkgContentDigestFromFields, exactReusablePrefix, incrementalLkgContentDigests, captureSlot, getSlot, dropSlot, noteEntry, encodePiContentDecision, getPiContentDecisions, freezePiContentDecision, getNativeReplayState, saveNativeToolInputs, addNativeReasoningIds, copySessionStateForClone, getErrorMessage, describeError, getSchemaFenceRejection, getMigrationOnOpenRefusal, LATEST_SUPPORTED_VERSION, getDatabasePath, getPersistedSchemaVersion, setSqlitePragmaConfig, applySqliteTuningPragmas, runSqliteOptimize, openDatabase, openDatabaseAsync, closeDatabase, queueM0Mutation, getMaxM0MutationId, queueMemoryMutation, getMemoryMutationsForRender, getMemoryMutationsForRenderByProjects, getMaxMemoryMutationId, getMaxMemoryMutationIdForProjects, getNotes, getSessionNotes, getPendingSmartNotes, getReadySmartNotes, markNoteReady, markNoteChecked, queuePendingOp, getPendingOps, getPendingOpsCount, clearPendingOps, removePendingOp, PRIMER_CANDIDATE_TTL_MS, PRIMER_CANDIDATE_MAX_AGE_MS, primerOccurrenceKey, primerOccurrenceUtcDay, insertPrimerCandidates, updatePrimerCandidateEmbedding, getPrimerCandidatesByIds, getPrimerCandidatesForPromotion, countPrimerCandidatesForProject, getActivePrimers, createPrimer, updatePrimerSupport, updatePrimerAnswer, GLOBAL_USER_PROFILE_PROJECT_PATH, getProjectState, bumpProjectUserProfileVersion, saveSourceContent, getSourceContents, recordSubagentInvocation, getLatestHistorianInvocationId, noteTouchedAt, noteNudgePickIndex, formatNoteNudge, promptSurfaceHashMaterial, createPromptSurfaceRuntime, createPromptSurfaceGuidanceEpochCache, SYNTH_USER_ID_PREFIX, resolvePiStableId, readPiSessionSnapshot, readPiSessionMessages, readPiSessionMessagePage, findLastModelKeyFromBranch, iterateEntriesToRawMessageRange, convertEntriesToRawMessages, convertEntriesToRawMessagePage, computeCueContentHash, hasMuralCueColumns, getMuralCueState, memoryNeedsCue, setMuralCue, recordMuralCueRejection, invalidateMemory, computeNormalizedHash, hasMemoryShareableColumn, hasMemoryClassifiedAtColumn, getUnclassifiedMemoryIds, insertMemory, getMemoryByHash, getMemoriesByProject, getMemoriesByProjects, getMaxMemoryIdForProjects, getMemoryById, setMemoryClassification, archiveMemory, getMemoryCountsByStatus, USER_MEMORY_CANDIDATE_TTL_MS, insertUserMemoryCandidates, getUserMemoryCandidates, deleteUserMemoryCandidates, pruneExpiredUserMemoryCandidates, insertUserMemory, getActiveUserMemories, updateUserMemoryContent, dismissUserMemory, getTaskScheduleState, getFailingDreamTasks, getMostRecentTaskRunAt, pruneNonCanonicalTaskRows, deleteTaskScheduleRowsForProject, seedTaskScheduleState, writeTaskScheduleState, isRetrospectiveWindowProcessed, recordRetrospectiveWindowProcessed, curateCategoryForMemoryCategory, peekCurateCategoryScope, beginCurateCategoryRun, curateTaskStateAfterSuccess, cosineSimilarity, GIT_SWEEP_LEASE_RENEWAL_MS, acquireGitSweepLease, renewGitSweepLease, markGitSweepSuccessAndRelease, parkGitSweepNonIndexable, releaseGitSweepLease, describeShadowBackfillWriteRefusal, contentSha256, sweepStaleEmbeddingIdentitiesForProject, enqueueShadowEmbeddingItems, getProjectEmbeddingSnapshot, getProjectChunkEmbeddingModelId, getProjectEmbeddingMaxInputTokens, embedTextForProject, embedBatchForProject, embedItemsForProject, embedUnembeddedMemoriesForProject, drainCommitBacklogForProject, embedSessionCompartmentChunks, getEmbeddingCoverageStatus, getAutoEmbeddingSessionCoverage, promoteSessionFactsDurable, embedPromotedFacts, recordMemoryMapping, recordMemoryVerifications, getUnmappedMemoryIds, clearMemoryVerifications, getMemoryVerifications, resolveGitTopLevel, readGitHead, readGitChangedFilesSince, readGitFileChangeTimesSince, verificationFileExists, normalizeVerificationFiles, isDirectiveShapedProjectRule, takeCurateSafetyRefusalCount, wakePlaneStatus, indexCommitsForProject, embedUnembeddedCommits, loadPiConfig, loadPiConfigDetailed, unregisterPiProjectEmbeddings, ensureProjectRegisteredFromPiDirectory, resolvePiHarnessDetection, resolvePiHarnessKind, MEMORY_MURAL_BLOCK, buildMagicContextSection, resolveMuralWire, updateCompactionMarkerAfterPublication, COMPARTMENT_RENDER_EPOCH, MEMORY_RENDER_FORMAT_EPOCH, encodeCachedM0UpgradeIdentity, decodeCachedM0UpgradeIdentity, renderBudgetIdentityChanged, renderedBudgetSnapshot, renderedBudgetShrinkReason, DEFAULT_HISTORY_BUDGET_TOKENS, renderCompartmentAtTier, renderDecayedCompartments, extractM0Block, TEMPORAL_MARKER_PATTERN, temporalMarkerPrefix, clearInjectionCache, getVisibleMemoryIds, renderHistorianMemoryBlock, DEFAULT_MEMORY_BUDGET_TOKENS, DEFAULT_USER_PROFILE_BUDGET_TOKENS, trimMemoriesToBudgetV2, trimWorkspaceMemoriesToBudgetV2, trimUserMemoriesToBudget, renderMemoryBlockV2, stripMemoryMuralBlock, unifiedSearch, rememberTodowriteToolCallTodos, parseTodos, setTodoSnapshot, registerTodoOverlay, registerTodoStateLifecycle, syncCtxMemoryToolEnabled, registerMagicContextTools };
@@ -2698,8 +2698,8 @@ function readRawSessionMessagesFromDb(db, sessionId) {
2698
2698
  };
2699
2699
  });
2700
2700
  }
2701
- function readRawSessionMessagePageFromDb(db, sessionId, afterOrdinal, limit, finalWatermark = Number.MAX_SAFE_INTEGER) {
2702
- const messageRows = readRawMessagePageRows(db, sessionId, afterOrdinal, limit, finalWatermark);
2701
+ function readRawSessionMessagePageFromDb(db, sessionId, afterOrdinal, limit, finalWatermark = Number.MAX_SAFE_INTEGER, after) {
2702
+ const messageRows = readRawMessagePageRows(db, sessionId, afterOrdinal, limit, finalWatermark, after);
2703
2703
  if (messageRows.length === 0)
2704
2704
  return [];
2705
2705
  const placeholders = messageRows.map(() => "?").join(", ");
@@ -2710,15 +2710,22 @@ function readRawSessionMessagePageFromDb(db, sessionId, afterOrdinal, limit, fin
2710
2710
  ORDER BY message_id ASC, time_created ASC, id ASC`).all(sessionId, ...messageRows.map((row) => row.id)).filter(isRawPartRow);
2711
2711
  return assembleRawMessagePage(messageRows, partRows);
2712
2712
  }
2713
- function readRawMessagePageRows(db, sessionId, afterOrdinal, limit, finalWatermark) {
2713
+ function readRawMessagePageRows(db, sessionId, afterOrdinal, limit, finalWatermark, after) {
2714
2714
  const remaining = Math.max(0, Math.floor(finalWatermark) - Math.floor(afterOrdinal));
2715
2715
  const pageSize = Math.min(Math.max(1, Math.floor(limit)), remaining);
2716
2716
  if (pageSize === 0)
2717
2717
  return [];
2718
+ const parameters = [sessionId];
2719
+ if (after)
2720
+ parameters.push(after.timeCreated, after.timeCreated, after.timeCreated, after.id);
2721
+ parameters.push(pageSize);
2722
+ if (!after)
2723
+ parameters.push(Math.max(0, Math.floor(afterOrdinal)));
2718
2724
  return db.prepare(`SELECT id, data, time_created, time_updated
2719
2725
  FROM message
2720
2726
  WHERE session_id = ?
2721
- AND NOT (
2727
+ ${after ? "AND time_created >= ? AND (time_created > ? OR (time_created = ? AND id > ?))" : ""}
2728
+ AND NOT (
2722
2729
  CASE WHEN json_valid(data) = 1
2723
2730
  THEN COALESCE(json_extract(data, '$.summary'), 0)
2724
2731
  ELSE 0 END = 1
@@ -2727,7 +2734,7 @@ function readRawMessagePageRows(db, sessionId, afterOrdinal, limit, finalWaterma
2727
2734
  ELSE '' END = 'stop'
2728
2735
  )
2729
2736
  ORDER BY time_created ASC, id ASC
2730
- LIMIT ? OFFSET ?`).all(sessionId, pageSize, Math.max(0, Math.floor(afterOrdinal))).filter(isRawMessageRow).map((row, index) => ({
2737
+ LIMIT ? ${after ? "" : "OFFSET ?"}`).all(...parameters).filter(isRawMessageRow).map((row, index) => ({
2731
2738
  ...row,
2732
2739
  ordinal: Math.floor(afterOrdinal) + index + 1
2733
2740
  }));
@@ -2780,8 +2787,8 @@ var RAW_SUMMARY_PART_DATA_SQL = `CASE
2780
2787
  )
2781
2788
  )
2782
2789
  END`;
2783
- function readRawSessionMessageSummaryPageFromDb(db, sessionId, afterOrdinal, limit, finalWatermark = Number.MAX_SAFE_INTEGER) {
2784
- const messageRows = readRawMessagePageRows(db, sessionId, afterOrdinal, limit, finalWatermark);
2790
+ function readRawSessionMessageSummaryPageFromDb(db, sessionId, afterOrdinal, limit, finalWatermark = Number.MAX_SAFE_INTEGER, after) {
2791
+ const messageRows = readRawMessagePageRows(db, sessionId, afterOrdinal, limit, finalWatermark, after);
2785
2792
  if (messageRows.length === 0)
2786
2793
  return [];
2787
2794
  const placeholders = messageRows.map(() => "?").join(", ");
@@ -3482,6 +3489,21 @@ function isFilePart(part) {
3482
3489
  return p.type === "file" && typeof p.url === "string";
3483
3490
  }
3484
3491
 
3492
+ // ../plugin/src/shared/user-answer.ts
3493
+ function hasUserAnswerMetadata(value) {
3494
+ if (!isRecord(value))
3495
+ return false;
3496
+ if (value.userAnswer === true)
3497
+ return true;
3498
+ if (Array.isArray(value.answers))
3499
+ return true;
3500
+ if (typeof value.answer === "string")
3501
+ return true;
3502
+ if (Array.isArray(value.selectedOptions) || typeof value.customInput === "string")
3503
+ return true;
3504
+ return Array.isArray(value.results) && value.results.some(hasUserAnswerMetadata);
3505
+ }
3506
+
3485
3507
  // ../plugin/src/features/magic-context/dreamer/token-budget.ts
3486
3508
  class DreamTokenBudgetExceeded extends Error {
3487
3509
  sessionId;
@@ -3979,6 +4001,20 @@ var tokenizer_calibration_seeds_default = [
3979
4001
  toolsRatio: 0.850953,
3980
4002
  proseRatio: 1.000017
3981
4003
  },
4004
+ {
4005
+ prefix: "openai/gpt-6-sol",
4006
+ systemRatio: 1.000278,
4007
+ toolsRatio: 0.850953,
4008
+ proseRatio: 1.000017,
4009
+ provenance: "Mirrored from openai/gpt-6-astra; prose inherited-unmeasured. Reported OAuth system/tools counts match GPT-5.5; no independent API-key measurement."
4010
+ },
4011
+ {
4012
+ prefix: "openai/gpt-6.1-sol",
4013
+ systemRatio: 1.000278,
4014
+ toolsRatio: 0.850953,
4015
+ proseRatio: 1.000017,
4016
+ provenance: "Mirrored from openai/gpt-6-astra; prose inherited-unmeasured. Reported OAuth system/tools counts match GPT-5.5; no independent API-key measurement."
4017
+ },
3982
4018
  {
3983
4019
  prefix: "openai/gpt-5",
3984
4020
  systemRatio: 1,
@@ -4082,7 +4118,7 @@ var tokenizer_calibration_seeds_default = [
4082
4118
  // ../plugin/src/hooks/magic-context/tokenizer-calibration.ts
4083
4119
  var CALIBRATION_TABLE = tokenizer_calibration_seeds_default;
4084
4120
  var NEUTRAL = { systemRatio: 1, toolsRatio: 1, proseRatio: 1 };
4085
- var CALIBRATION_TABLE_REVISION = "2026-09-23-model-id-generation-v2";
4121
+ var CALIBRATION_TABLE_REVISION = "2026-09-30-sol-tokenizer-seeds-v3";
4086
4122
  var UNKNOWN_FIT_RATIO = Math.max(2, ...CALIBRATION_TABLE.flatMap((entry) => [
4087
4123
  entry.systemRatio,
4088
4124
  entry.toolsRatio,
@@ -4419,6 +4455,8 @@ function getRawSessionMessageOrdinalCount2(sessionId) {
4419
4455
  var RAW_MESSAGE_RANGE_PAGE_SIZE = 100;
4420
4456
  function readRawSessionMessageRangeFromSource(sessionId, fromOrdinal, toOrdinal) {
4421
4457
  const provider = sessionProviders.get(sessionId);
4458
+ if (provider?.iterateMessageRange)
4459
+ return [...provider.iterateMessageRange(fromOrdinal, toOrdinal)];
4422
4460
  if (provider && !provider.readMessagePage) {
4423
4461
  return provider.readMessages().filter((message) => message.ordinal >= fromOrdinal && message.ordinal <= toOrdinal);
4424
4462
  }
@@ -4426,9 +4464,10 @@ function readRawSessionMessageRangeFromSource(sessionId, fromOrdinal, toOrdinal)
4426
4464
  return [];
4427
4465
  const messages = [];
4428
4466
  let afterOrdinal = fromOrdinal - 1;
4467
+ let after;
4429
4468
  while (afterOrdinal < toOrdinal) {
4430
4469
  const limit = Math.min(RAW_MESSAGE_RANGE_PAGE_SIZE, toOrdinal - afterOrdinal);
4431
- const page = provider?.readMessagePage ? provider.readMessagePage(afterOrdinal, limit, toOrdinal) : withReadOnlySessionDb((db) => readRawSessionMessagePageFromDb(db, sessionId, afterOrdinal, limit, toOrdinal));
4470
+ const page = provider?.readMessagePage ? provider.readMessagePage(afterOrdinal, limit, toOrdinal, after) : withReadOnlySessionDb((db) => readRawSessionMessagePageFromDb(db, sessionId, afterOrdinal, limit, toOrdinal, after));
4432
4471
  if (page.length === 0)
4433
4472
  break;
4434
4473
  let nextOrdinal = afterOrdinal;
@@ -4441,6 +4480,8 @@ function readRawSessionMessageRangeFromSource(sessionId, fromOrdinal, toOrdinal)
4441
4480
  if (nextOrdinal <= afterOrdinal)
4442
4481
  break;
4443
4482
  afterOrdinal = nextOrdinal;
4483
+ const last = page.at(-1);
4484
+ after = last ? { timeCreated: last.createdAt ?? 0, id: last.id } : undefined;
4444
4485
  }
4445
4486
  return messages;
4446
4487
  }
@@ -4451,6 +4492,13 @@ function visitRawSessionMessages2(sessionId, fromOrdinal, toOrdinal, visit, opti
4451
4492
  if (to < from)
4452
4493
  return;
4453
4494
  const provider = sessionProviders.get(sessionId);
4495
+ if (provider?.iterateMessageRange) {
4496
+ for (const message of provider.iterateMessageRange(from, to)) {
4497
+ if (!visit(message))
4498
+ return;
4499
+ }
4500
+ return;
4501
+ }
4454
4502
  if (provider && !provider.readMessagePage) {
4455
4503
  for (const message of provider.readMessages()) {
4456
4504
  if (message.ordinal < from || message.ordinal > to)
@@ -4464,10 +4512,11 @@ function visitRawSessionMessages2(sessionId, fromOrdinal, toOrdinal, visit, opti
4464
4512
  return;
4465
4513
  const pageSize = Math.max(1, Math.floor(options.pageSize ?? RAW_MESSAGE_VISIT_PAGE_SIZE));
4466
4514
  let afterOrdinal = from - 1;
4515
+ let after;
4467
4516
  while (afterOrdinal < to) {
4468
4517
  const limit = Math.min(pageSize, to - afterOrdinal);
4469
4518
  const cursor = afterOrdinal;
4470
- const page = provider?.readMessagePage ? provider.readMessagePage(cursor, limit, to) : withReadOnlySessionDb((db) => options.summary ? readRawSessionMessageSummaryPageFromDb(db, sessionId, cursor, limit, to) : readRawSessionMessagePageFromDb(db, sessionId, cursor, limit, to));
4519
+ const page = provider?.readMessagePage ? provider.readMessagePage(cursor, limit, to, after) : withReadOnlySessionDb((db) => options.summary ? readRawSessionMessageSummaryPageFromDb(db, sessionId, cursor, limit, to, after) : readRawSessionMessagePageFromDb(db, sessionId, cursor, limit, to, after));
4471
4520
  if (page.length === 0)
4472
4521
  return;
4473
4522
  let nextOrdinal = afterOrdinal;
@@ -4481,6 +4530,8 @@ function visitRawSessionMessages2(sessionId, fromOrdinal, toOrdinal, visit, opti
4481
4530
  if (nextOrdinal <= afterOrdinal)
4482
4531
  return;
4483
4532
  afterOrdinal = nextOrdinal;
4533
+ const last = page.at(-1);
4534
+ after = last ? { timeCreated: last.createdAt ?? 0, id: last.id } : undefined;
4484
4535
  }
4485
4536
  }
4486
4537
  function readRawSessionMessageRange2(sessionId, fromOrdinal, toOrdinal) {
@@ -5021,4 +5072,4 @@ function readSessionChunk2(sessionId, tokenBudget, offset = 1, eligibleEndOrdina
5021
5072
  toolResultBoundaries
5022
5073
  };
5023
5074
  }
5024
- export { registerSlowWriteReporter, detectSqliteRuntime, Database, withSqliteBackgroundWriter, withPrivilegedWriter, CTX_REDUCE_KEEP, newestCtxReduceTagNumbers, textMentionsRecentCommit, removeSystemReminders, hasMeaningfulUserText2, extractTexts2, extractToolCallSummaries, preloadTokenizer, estimateTokens, normalizeText, stripWellFormedLeadingTagPrefix, stripPersistedAssistantText, byteSize, stripTagPrefix, peelLeadingMcTagNotation, prependTag, isRecord, stableStringify, estimateImageTokensFromDataUrl, TODO_STATUSES, TODO_PRIORITIES, TITLE_DONE_STATUSES, normalizeTodoStateJson, buildSyntheticTodoPart, stripChannel1ReminderSpans, compareMeasuredTailPrefix, formatTailHygienePrefixMismatch, freezeTailHygieneMeasurement, effectiveTailHygiene, CHANNEL1_SENTINEL, CHANNEL1_FLOOR_TOKENS, decideChannel1, evaluateChannel2, reclaimableToolOutputCount, buildChannel2Reminder, buildChannel1Reminder, planEmergencyDrop, measureEmergencyTag, updateTagByteSize, getRecentTagOwnerMessageIds, AGE_RECLAIM_MIN_TOKENS, getOldestActiveUnprotectedToolTags, getActiveToolTagsForAgeReclaim, getTriggerTagTokenUpperBound, updateTagInputByteSize, updateTagTokenCount, getPersistedToolTagAccounting, getAllStatusTagTokenTotalsFlat, updateTagInputTokenCount, tagTokenCountIsNull, backfillTagTokenCounts, insertTag, updateTagStatus, getInertWhitespaceAssistantTags, updateTagDropMode, updateCavemanDepth, hasPiFallbackMessageTags, findAdoptableFallbackTags, hasPiFallbackToolOwnerTags, findPiFallbackToolOwnerTags, adoptPiFallbackToolOwnerTag, adoptPiFallbackMessageTag, getMaxTagNumberBySession, getTagNumberByMessageId, getAssignableTagNumberByMessageId, deriveTagLoadFloor, TAG_SELECT_COLUMNS, getTagsBySession, getActiveTagsBySession, getTagsForPendingOperations, getTagsByNumbers, getDroppedTagsByNumbers, getMaxDroppedTagNumber, getToolTagNumberByOwner, getNullOwnerToolTag, adoptNullOwnerToolTag, retreatPastHostUnservedRows, resolveOpenCodeDbPath, hasV1MessageTables, assertOpenCodeStoreGeneration, openCodeDbPathExists, getOpenCodeDbProbeDescriptions, recordOpenCodeDbReadFailure, clearOpenCodeDbReadFailure, claimOpenCodeDbDiagnosticOnce, closeQuietly, withReadOnlySessionDb, RAW_SUMMARY_TEXT_MAX_CHARS, completedToolArcCrossesBoundary, estimateTrueRawMessageTokens, buildToolArcs, fenceBoundaryForCompletedToolArcs, fenceBoundaryForToolArcs, buildTrueRawTokenIndex, computeRawRangeFingerprint, invalidateTrueRawTokenCache, DreamTokenBudgetExceeded, TOKEN_BUDGET_FINALIZE_MESSAGE, TOKEN_BUDGET_TOOL_REFUSAL, registerBudgetFinalizeChild, releaseBudgetFinalizeChild, createDreamTokenBudget, droppedInputMarker, createDroppedInputGuard, isEditTool, applyEditMarkerToInput, setDatabase, loadToolDefinitionMeasurements, resolveDecisionCalibration, providerMass, localBudget, calibrationForModelKey, historyLocalBudget, SKELETON_REAL_INPUT_MAX_BYTES, toolInputStringBytes, resolveHostServedBoundaryId2, hasRawMessageProvider2, setRawMessageProvider2, withRawMessageProvider2, cleanUserText2, withRawSessionMessageCache2, readRawSessionMessages2, readRawSessionMessagePage2, getRawSessionMessageOrdinalCount2, visitRawSessionMessages2, readRawSessionMessageRange2, primeTailRawMessageCache2, getCachedAbsoluteMessageCount2, primeInMemoryTailRawMessageCache2, readRawSessionMessageIdOrdinalsForRange2, hasRawSessionMessageById2, readRawSessionMessageOrdinalById2, compareRawSessionMessageOrder2, getRawSessionMessageCount2, getRawSessionTagKeysThrough2, getLegacyProtectedTailStartOrdinal2, readSessionChunk2 };
5075
+ export { registerSlowWriteReporter, detectSqliteRuntime, Database, withSqliteBackgroundWriter, withPrivilegedWriter, CTX_REDUCE_KEEP, newestCtxReduceTagNumbers, textMentionsRecentCommit, removeSystemReminders, hasMeaningfulUserText2, extractTexts2, extractToolCallSummaries, preloadTokenizer, estimateTokens, normalizeText, stripWellFormedLeadingTagPrefix, stripPersistedAssistantText, byteSize, stripTagPrefix, peelLeadingMcTagNotation, prependTag, isRecord, stableStringify, estimateImageTokensFromDataUrl, TODO_STATUSES, TODO_PRIORITIES, TITLE_DONE_STATUSES, normalizeTodoStateJson, buildSyntheticTodoPart, stripChannel1ReminderSpans, compareMeasuredTailPrefix, formatTailHygienePrefixMismatch, freezeTailHygieneMeasurement, effectiveTailHygiene, CHANNEL1_SENTINEL, CHANNEL1_FLOOR_TOKENS, decideChannel1, evaluateChannel2, reclaimableToolOutputCount, buildChannel2Reminder, buildChannel1Reminder, planEmergencyDrop, measureEmergencyTag, updateTagByteSize, getRecentTagOwnerMessageIds, AGE_RECLAIM_MIN_TOKENS, getOldestActiveUnprotectedToolTags, getActiveToolTagsForAgeReclaim, getTriggerTagTokenUpperBound, updateTagInputByteSize, updateTagTokenCount, getPersistedToolTagAccounting, getAllStatusTagTokenTotalsFlat, updateTagInputTokenCount, tagTokenCountIsNull, backfillTagTokenCounts, insertTag, updateTagStatus, getInertWhitespaceAssistantTags, updateTagDropMode, updateCavemanDepth, hasPiFallbackMessageTags, findAdoptableFallbackTags, hasPiFallbackToolOwnerTags, findPiFallbackToolOwnerTags, adoptPiFallbackToolOwnerTag, adoptPiFallbackMessageTag, getMaxTagNumberBySession, getTagNumberByMessageId, getAssignableTagNumberByMessageId, deriveTagLoadFloor, TAG_SELECT_COLUMNS, getTagsBySession, getActiveTagsBySession, getTagsForPendingOperations, getTagsByNumbers, getDroppedTagsByNumbers, getMaxDroppedTagNumber, getToolTagNumberByOwner, getNullOwnerToolTag, adoptNullOwnerToolTag, retreatPastHostUnservedRows, resolveOpenCodeDbPath, hasV1MessageTables, assertOpenCodeStoreGeneration, openCodeDbPathExists, getOpenCodeDbProbeDescriptions, recordOpenCodeDbReadFailure, clearOpenCodeDbReadFailure, claimOpenCodeDbDiagnosticOnce, closeQuietly, withReadOnlySessionDb, RAW_SUMMARY_TEXT_MAX_CHARS, completedToolArcCrossesBoundary, estimateTrueRawMessageTokens, buildToolArcs, fenceBoundaryForCompletedToolArcs, fenceBoundaryForToolArcs, buildTrueRawTokenIndex, computeRawRangeFingerprint, invalidateTrueRawTokenCache, hasUserAnswerMetadata, DreamTokenBudgetExceeded, TOKEN_BUDGET_FINALIZE_MESSAGE, TOKEN_BUDGET_TOOL_REFUSAL, registerBudgetFinalizeChild, releaseBudgetFinalizeChild, createDreamTokenBudget, droppedInputMarker, createDroppedInputGuard, isEditTool, applyEditMarkerToInput, setDatabase, loadToolDefinitionMeasurements, resolveDecisionCalibration, providerMass, localBudget, calibrationForModelKey, historyLocalBudget, SKELETON_REAL_INPUT_MAX_BYTES, toolInputStringBytes, resolveHostServedBoundaryId2, hasRawMessageProvider2, setRawMessageProvider2, withRawMessageProvider2, cleanUserText2, withRawSessionMessageCache2, readRawSessionMessages2, readRawSessionMessagePage2, getRawSessionMessageOrdinalCount2, visitRawSessionMessages2, readRawSessionMessageRange2, primeTailRawMessageCache2, getCachedAbsoluteMessageCount2, primeInMemoryTailRawMessageCache2, readRawSessionMessageIdOrdinalsForRange2, hasRawSessionMessageById2, readRawSessionMessageOrdinalById2, compareRawSessionMessageOrder2, getRawSessionMessageCount2, getRawSessionTagKeysThrough2, getLegacyProtectedTailStartOrdinal2, readSessionChunk2 };
package/dist/index.js CHANGED
@@ -304,6 +304,7 @@ import {
304
304
  readPiSessionMessages,
305
305
  readPiSessionMessagePage,
306
306
  findLastModelKeyFromBranch,
307
+ iterateEntriesToRawMessageRange,
307
308
  convertEntriesToRawMessages,
308
309
  convertEntriesToRawMessagePage,
309
310
  computeCueContentHash,
@@ -402,6 +403,9 @@ import {
402
403
  MEMORY_RENDER_FORMAT_EPOCH,
403
404
  encodeCachedM0UpgradeIdentity,
404
405
  decodeCachedM0UpgradeIdentity,
406
+ renderBudgetIdentityChanged,
407
+ renderedBudgetSnapshot,
408
+ renderedBudgetShrinkReason,
405
409
  DEFAULT_HISTORY_BUDGET_TOKENS,
406
410
  renderCompartmentAtTier,
407
411
  renderDecayedCompartments,
@@ -426,7 +430,7 @@ import {
426
430
  registerTodoStateLifecycle,
427
431
  syncCtxMemoryToolEnabled,
428
432
  registerMagicContextTools
429
- } from "./index-atb1ecv9.js";
433
+ } from "./index-5am7amy4.js";
430
434
  import {
431
435
  Database,
432
436
  withSqliteBackgroundWriter,
@@ -515,6 +519,7 @@ import {
515
519
  buildTrueRawTokenIndex,
516
520
  computeRawRangeFingerprint,
517
521
  invalidateTrueRawTokenCache,
522
+ hasUserAnswerMetadata,
518
523
  DreamTokenBudgetExceeded,
519
524
  TOKEN_BUDGET_FINALIZE_MESSAGE,
520
525
  TOKEN_BUDGET_TOOL_REFUSAL,
@@ -547,7 +552,7 @@ import {
547
552
  getRawSessionTagKeysThrough2,
548
553
  getLegacyProtectedTailStartOrdinal2,
549
554
  readSessionChunk2
550
- } from "./index-tckvezry.js";
555
+ } from "./index-npagr1cy.js";
551
556
  import {
552
557
  pushNotification2
553
558
  } from "./index-b3eqj1g6.js";
@@ -1758,7 +1763,7 @@ function countFailures(db) {
1758
1763
  function classifyBackfillError(error) {
1759
1764
  if (error instanceof ProjectIdentityError) {
1760
1765
  return {
1761
- errorClass: error.errorClass === "dubious_ownership" || error.errorClass === "home_project_disabled" || error.errorClass === "git_identity_unavailable" ? "unknown" : error.errorClass,
1766
+ errorClass: error.errorClass === "dubious_ownership" || error.errorClass === "home_project_disabled" || error.errorClass === "git_identity_unavailable" || error.errorClass === "no_commits" ? "unknown" : error.errorClass,
1762
1767
  errorMessage: error.message
1763
1768
  };
1764
1769
  }
@@ -10402,6 +10407,11 @@ async function mapOneBatch(args, batch, sliceMs, signal) {
10402
10407
  let agentSessionId = null;
10403
10408
  let promptSettled = false;
10404
10409
  const startedAt = Date.now();
10410
+ let budgetFinalized = false;
10411
+ const onBudgetUpdate = (state) => {
10412
+ budgetFinalized ||= state.finalizeFired;
10413
+ args.onBudgetUpdate?.(state);
10414
+ };
10405
10415
  try {
10406
10416
  const prompt = buildMapMemoriesPrompt(args.projectIdentity, batch);
10407
10417
  if (args.hiddenCompletionExecutor) {
@@ -10414,7 +10424,7 @@ async function mapOneBatch(args, batch, sliceMs, signal) {
10414
10424
  prompt,
10415
10425
  title: "magic-context-dream-map-memories",
10416
10426
  callContext: "dreamer:map-memories",
10417
- metadata: { tokenBudget: args.tokenBudget, onBudgetUpdate: args.onBudgetUpdate },
10427
+ metadata: { tokenBudget: args.tokenBudget, onBudgetUpdate },
10418
10428
  model: args.model,
10419
10429
  fallbackModels: args.fallbackModels,
10420
10430
  timeoutMs: sliceMs,
@@ -10425,9 +10435,12 @@ async function mapOneBatch(args, batch, sliceMs, signal) {
10425
10435
  status: "completed",
10426
10436
  messages: run.completion.messages ?? []
10427
10437
  });
10428
- const outcome = await applyParsedBatchMappings(args, batch, run.validated);
10438
+ const outcome = await applyParsedBatchMappings(args, batch, run.validated, budgetFinalized);
10429
10439
  const returnedIds = new Set(run.validated.map((entry) => entry.id));
10430
- return { ...outcome, requeue: batch.filter((memory) => !returnedIds.has(memory.id)) };
10440
+ return {
10441
+ ...outcome,
10442
+ requeue: budgetFinalized ? [] : batch.filter((memory) => !returnedIds.has(memory.id))
10443
+ };
10431
10444
  }
10432
10445
  const client = args.client;
10433
10446
  if (!client)
@@ -10457,7 +10470,7 @@ async function mapOneBatch(args, batch, sliceMs, signal) {
10457
10470
  }, {
10458
10471
  transport: createPromptAsyncTransport(client, agentSessionId, {
10459
10472
  tokenBudget: args.tokenBudget,
10460
- onBudgetUpdate: args.onBudgetUpdate
10473
+ onBudgetUpdate
10461
10474
  }),
10462
10475
  timeoutMs: sliceMs,
10463
10476
  signal,
@@ -10484,11 +10497,11 @@ async function mapOneBatch(args, batch, sliceMs, signal) {
10484
10497
  });
10485
10498
  promptSettled = true;
10486
10499
  recordInvocation2(args, startedAt, { status: "completed", messages: run.output });
10487
- const outcome = await applyParsedBatchMappings(args, batch, run.validated);
10500
+ const outcome = await applyParsedBatchMappings(args, batch, run.validated, budgetFinalized);
10488
10501
  const returnedIds = new Set(run.validated.filter((entry) => batch.some((memory) => memory.id === entry.id)).map((entry) => entry.id));
10489
10502
  return {
10490
10503
  ...outcome,
10491
- requeue: batch.filter((memory) => !returnedIds.has(memory.id))
10504
+ requeue: budgetFinalized ? [] : batch.filter((memory) => !returnedIds.has(memory.id))
10492
10505
  };
10493
10506
  } catch (error) {
10494
10507
  const desc = describeError(error);
@@ -10523,7 +10536,7 @@ async function mapOneBatch(args, batch, sliceMs, signal) {
10523
10536
  });
10524
10537
  }
10525
10538
  }
10526
- async function applyParsedBatchMappings(args, batch, parsed) {
10539
+ async function applyParsedBatchMappings(args, batch, parsed, budgetFinalized = false) {
10527
10540
  const batchIds = new Set(batch.map((memory) => memory.id));
10528
10541
  const valid = parsed.filter((entry) => batchIds.has(entry.id));
10529
10542
  const unknown = parsed.filter((entry) => !batchIds.has(entry.id));
@@ -10531,9 +10544,12 @@ async function applyParsedBatchMappings(args, batch, parsed) {
10531
10544
  log(`[dreamer] map-memories warning: dropping ${unknown.length} unknown mapping entr${unknown.length === 1 ? "y" : "ies"} outside the current batch (${unknown.map((entry) => entry.id).join(", ")})`);
10532
10545
  }
10533
10546
  assertNoDuplicateManifestIds(valid.map((entry) => entry.id), "mappings");
10534
- if (valid.length * 2 < batch.length) {
10547
+ if (!budgetFinalized && valid.length * 2 < batch.length) {
10535
10548
  throw new Error(`mappings manifest covers ${valid.length}/${batch.length} batch ids after filtering unknown entries; rejecting mostly-wrong manifest`);
10536
10549
  }
10550
+ if (budgetFinalized && valid.length < batch.length) {
10551
+ log(`[dreamer] map-memories: accepted partial manifest after token budget: ${valid.length}/${batch.length}`);
10552
+ }
10537
10553
  if (valid.length === 0)
10538
10554
  return { mapped: 0, independent: 0 };
10539
10555
  const planned = [];
@@ -12310,6 +12326,11 @@ async function verifyOneBatch(args, batch, sliceMs, signal) {
12310
12326
  let agentSessionId = null;
12311
12327
  let promptSettled = false;
12312
12328
  const startedAt = Date.now();
12329
+ let budgetFinalized = false;
12330
+ const onBudgetUpdate = (state) => {
12331
+ budgetFinalized ||= state.finalizeFired;
12332
+ args.onBudgetUpdate?.(state);
12333
+ };
12313
12334
  try {
12314
12335
  const headAtPrompt = await readGitHead(args.sessionDirectory);
12315
12336
  const evidence = !args.forceBroad && batch.every((m) => m.verifiedAt) ? await buildVerifyDiffEvidence(args.sessionDirectory, batch) : null;
@@ -12324,7 +12345,7 @@ async function verifyOneBatch(args, batch, sliceMs, signal) {
12324
12345
  prompt,
12325
12346
  title: "magic-context-dream-verify",
12326
12347
  callContext: "dreamer:verify",
12327
- metadata: { tokenBudget: args.tokenBudget, onBudgetUpdate: args.onBudgetUpdate },
12348
+ metadata: { tokenBudget: args.tokenBudget, onBudgetUpdate },
12328
12349
  model: args.model,
12329
12350
  fallbackModels: args.fallbackModels,
12330
12351
  language: args.language,
@@ -12341,7 +12362,7 @@ async function verifyOneBatch(args, batch, sliceMs, signal) {
12341
12362
  status: "completed",
12342
12363
  messages: run.completion.messages ?? []
12343
12364
  });
12344
- return applyParsedVerifyManifest(args, batch, run.validated, evidence?.head ?? headAtPrompt);
12365
+ return applyParsedVerifyManifest(args, batch, run.validated, evidence?.head ?? headAtPrompt, budgetFinalized);
12345
12366
  }
12346
12367
  const client = args.client;
12347
12368
  if (!client)
@@ -12371,7 +12392,7 @@ async function verifyOneBatch(args, batch, sliceMs, signal) {
12371
12392
  }, {
12372
12393
  transport: createPromptAsyncTransport(client, agentSessionId, {
12373
12394
  tokenBudget: args.tokenBudget,
12374
- onBudgetUpdate: args.onBudgetUpdate
12395
+ onBudgetUpdate
12375
12396
  }),
12376
12397
  timeoutMs: sliceMs,
12377
12398
  signal,
@@ -12401,7 +12422,7 @@ async function verifyOneBatch(args, batch, sliceMs, signal) {
12401
12422
  });
12402
12423
  promptSettled = true;
12403
12424
  recordInvocation4(args, startedAt, { status: "completed", messages: run.output });
12404
- return await applyParsedVerifyManifest(args, batch, run.validated, evidence?.head ?? headAtPrompt);
12425
+ return await applyParsedVerifyManifest(args, batch, run.validated, evidence?.head ?? headAtPrompt, budgetFinalized);
12405
12426
  } catch (error) {
12406
12427
  const desc = describeError(error);
12407
12428
  const providerFailure = error instanceof DreamerProviderOutputFailureError ? error : undefined;
@@ -12447,7 +12468,7 @@ async function verifyOneBatch(args, batch, sliceMs, signal) {
12447
12468
  });
12448
12469
  }
12449
12470
  }
12450
- async function applyParsedVerifyManifest(args, batch, parsed, headAtPrompt) {
12471
+ async function applyParsedVerifyManifest(args, batch, parsed, headAtPrompt, budgetFinalized = false) {
12451
12472
  const batchIds = new Set(batch.map((m) => m.id));
12452
12473
  const batchById = new Map(batch.map((memory) => [memory.id, memory]));
12453
12474
  const valid = {
@@ -12467,9 +12488,12 @@ async function applyParsedVerifyManifest(args, batch, parsed, headAtPrompt) {
12467
12488
  }
12468
12489
  const validIds = [...valid.verified, ...valid.updated, ...valid.archived, ...valid.skipped].map((entry) => entry.id);
12469
12490
  assertNoDuplicateManifestIds(validIds, "verify");
12470
- if (validIds.length * 2 < batch.length) {
12491
+ if (!budgetFinalized && validIds.length * 2 < batch.length) {
12471
12492
  throw new Error(`verify manifest covers ${validIds.length}/${batch.length} batch ids after filtering unknown entries; rejecting mostly-wrong manifest`);
12472
12493
  }
12494
+ if (budgetFinalized && validIds.length < batch.length) {
12495
+ log(`[dreamer] verify: accepted partial manifest after token budget: ${validIds.length}/${batch.length}`);
12496
+ }
12473
12497
  if (validIds.length === 0) {
12474
12498
  return { verified: 0, updated: 0, archived: 0, skipped: 0, refused: 0 };
12475
12499
  }
@@ -16875,6 +16899,9 @@ function createPiPrimerRawProviderFactory(deps = {}) {
16875
16899
  readMessages() {
16876
16900
  throw new Error("Pi primer history requires bounded pages");
16877
16901
  },
16902
+ iterateMessageRange(from, to) {
16903
+ return iterateEntriesToRawMessageRange(summaryEntries(path), from - 1, Number.MAX_SAFE_INTEGER, to);
16904
+ },
16878
16905
  readMessagePage(after, limit, watermark) {
16879
16906
  return convertEntriesToRawMessagePage(summaryEntries(path), after, Math.min(50, limit), watermark);
16880
16907
  }
@@ -18220,6 +18247,12 @@ function resolveTokensMatchWithKey(tokensConfig, modelKey) {
18220
18247
  }
18221
18248
  return;
18222
18249
  }
18250
+ function historyBudgetPolicyIdentity(historyBudgetPercentage, executeThresholdPercentage, modelKey, executeThresholdTokens) {
18251
+ if (!historyBudgetPercentage)
18252
+ return "pdefault";
18253
+ const threshold = resolveExecuteThresholdDetail(executeThresholdPercentage ?? 65, modelKey, 65, { tokensConfig: executeThresholdTokens, contextLimit: Number.MAX_SAFE_INTEGER });
18254
+ return `p${historyBudgetPercentage}:${threshold.mode}:${threshold.absoluteTokens ?? threshold.percentage}`;
18255
+ }
18223
18256
 
18224
18257
  // ../plugin/src/features/magic-context/scheduler.ts
18225
18258
  var TTL_PATTERN = /^(\d+)([smh])$/;
@@ -21511,7 +21544,7 @@ function buildAggregateTarget(tagId, occurrences, requiresToolArcSkeleton, conve
21511
21544
  }
21512
21545
  return any ? "truncated" : "absent";
21513
21546
  },
21514
- canDrop: complete,
21547
+ canDrop: () => complete() && !occurrences.some((occ) => occ.part.hasUserAnswer?.()),
21515
21548
  requiresToolArcSkeleton,
21516
21549
  readInput() {
21517
21550
  for (const occ of occurrences) {
@@ -21563,6 +21596,7 @@ function buildToolTarget(part, message, tagId) {
21563
21596
  return setToolContentOrText(part, `[dropped §${tagId}§]`) ? "truncated" : "absent";
21564
21597
  },
21565
21598
  cannotRemove: () => part.setToolInput !== undefined,
21599
+ ...part.hasUserAnswer?.() ? { canDrop: () => false } : {},
21566
21600
  inputStringBytes() {
21567
21601
  return part.setToolInput ? toolInputStringBytes(part.getToolInput?.() ?? null) : 0;
21568
21602
  },
@@ -25243,6 +25277,8 @@ function applyPiHeuristicCleanup(sessionId, db, targets, piMessages, config, pre
25243
25277
  if (!matched)
25244
25278
  continue;
25245
25279
  const target = targets.get(tag.tagNumber);
25280
+ if (target?.canDrop?.() === false)
25281
+ continue;
25246
25282
  const { result, mode } = applyNewToolDrop(target, { inWindow: false });
25247
25283
  if (result === "incomplete")
25248
25284
  continue;
@@ -25327,6 +25363,8 @@ function applyPiHeuristicCleanup(sessionId, db, targets, piMessages, config, pre
25327
25363
  for (let i = 0;i < group.length - 1; i++) {
25328
25364
  const tag = group[i];
25329
25365
  const target = targets.get(tag.tagNumber);
25366
+ if (target?.canDrop?.() === false)
25367
+ continue;
25330
25368
  const { result, mode } = applyNewToolDrop(target, {
25331
25369
  inWindow: false
25332
25370
  });
@@ -26370,7 +26408,7 @@ var EMPTY_PI_HARD_SIGNALS = {
26370
26408
  lastResponseTime: 0
26371
26409
  };
26372
26410
  function renderBudgetIdentityPi(state) {
26373
- return `m${state.injectionBudgetTokens ?? DEFAULT_MEMORY_BUDGET_TOKENS}-h${state.historyBudgetTokens ?? DEFAULT_HISTORY_BUDGET_TOKENS}`;
26411
+ return `m${state.injectionBudgetTokens ?? DEFAULT_MEMORY_BUDGET_TOKENS}-h${state.historyBudgetPolicyIdentity ?? state.historyBudgetTokens ?? DEFAULT_HISTORY_BUDGET_TOKENS}`;
26374
26412
  }
26375
26413
  function piMaterializeMismatch(reason, signal, cached, current) {
26376
26414
  return { value: true, reason, mismatch: { signal, cached, current } };
@@ -26505,7 +26543,8 @@ function getCachedMarkers(db, state, compartmentsForNormalization, metaOverride,
26505
26543
  modelKey: meta.cachedM0ModelKey ?? "",
26506
26544
  projectIdentity: meta.cachedM0ProjectIdentity ?? null,
26507
26545
  muralEnabled: cachedUpgradeIdentity.muralEnabled ?? false,
26508
- renderBudgetIdentity: cachedUpgradeIdentity.renderBudgetIdentity ?? ""
26546
+ renderBudgetIdentity: cachedUpgradeIdentity.renderBudgetIdentity ?? "",
26547
+ renderedBudgets: cachedUpgradeIdentity.renderedBudgets
26509
26548
  };
26510
26549
  }
26511
26550
  function lastBaselineEndMessageId(compartments) {
@@ -26540,7 +26579,8 @@ function readCurrentMarkersFromCompartments(db, state, compartments, projectDocs
26540
26579
  modelKey: piModelRefToCanonical((state.hardSignals ?? EMPTY_PI_HARD_SIGNALS).modelKey),
26541
26580
  projectIdentity: state.projectIdentity,
26542
26581
  muralEnabled: state.muralEnabled === true,
26543
- renderBudgetIdentity: renderBudgetIdentityPi(state)
26582
+ renderBudgetIdentity: renderBudgetIdentityPi(state),
26583
+ renderedBudgets: renderedBudgetSnapshot(state.injectionBudgetTokens ?? DEFAULT_MEMORY_BUDGET_TOKENS, state.historyBudgetTokens ?? DEFAULT_HISTORY_BUDGET_TOKENS)
26544
26584
  };
26545
26585
  }
26546
26586
  function mustMaterializePi(state, db, currentCompartmentsOverride, passSnapshot) {
@@ -26562,10 +26602,14 @@ function mustMaterializePi(state, db, currentCompartmentsOverride, passSnapshot)
26562
26602
  return piMaterializeMismatch("compartment_render_epoch", "compartmentRenderEpoch", cached.compartmentRenderEpoch, current.compartmentRenderEpoch);
26563
26603
  }
26564
26604
  if (cached.muralEnabled !== current.muralEnabled) {
26565
- return piMaterializeMismatch("render_config", "muralEnabled", cached.muralEnabled, current.muralEnabled);
26605
+ return piMaterializeMismatch(`render_config:mural(${cached.muralEnabled}→${current.muralEnabled})`, "muralEnabled", cached.muralEnabled, current.muralEnabled);
26566
26606
  }
26567
- if (cached.renderBudgetIdentity !== current.renderBudgetIdentity) {
26568
- return piMaterializeMismatch("render_config", "renderBudgetIdentity", cached.renderBudgetIdentity, current.renderBudgetIdentity);
26607
+ if (renderBudgetIdentityChanged(cached.renderBudgetIdentity, current.renderBudgetIdentity)) {
26608
+ return piMaterializeMismatch(`render_config:budget(${cached.renderBudgetIdentity}→${current.renderBudgetIdentity})`, "renderBudgetIdentity", cached.renderBudgetIdentity, current.renderBudgetIdentity);
26609
+ }
26610
+ const budgetShrinkReason = renderedBudgetShrinkReason(cached.renderedBudgets, current.renderedBudgets);
26611
+ if (budgetShrinkReason) {
26612
+ return piMaterializeMismatch(budgetShrinkReason, "renderedBudgets", cached.renderedBudgets ?? null, current.renderedBudgets ?? null);
26569
26613
  }
26570
26614
  const hard = state.hardSignals ?? EMPTY_PI_HARD_SIGNALS;
26571
26615
  const canonicalHardModelKey = piModelRefToCanonical(hard.modelKey);
@@ -26707,7 +26751,8 @@ function readFrozenM0InputsPi(state, db, docs = readProjectDocsForPiM0(state), m
26707
26751
  modelKey: piModelRefToCanonical((state.hardSignals ?? EMPTY_PI_HARD_SIGNALS).modelKey),
26708
26752
  projectIdentity: state.projectIdentity,
26709
26753
  muralEnabled: state.memoryEnabled !== false && state.muralEnabled === true,
26710
- renderBudgetIdentity: renderBudgetIdentityPi(state)
26754
+ renderBudgetIdentity: renderBudgetIdentityPi(state),
26755
+ renderedBudgets: renderedBudgetSnapshot(state.injectionBudgetTokens ?? DEFAULT_MEMORY_BUDGET_TOKENS, state.historyBudgetTokens ?? DEFAULT_HISTORY_BUDGET_TOKENS)
26711
26756
  };
26712
26757
  return { docs, markers, compartments, memories, userProfile, workspace };
26713
26758
  });
@@ -26797,7 +26842,7 @@ function materializeM0Pi(state, db, passSnapshot) {
26797
26842
  projectDocsHash: snapshotMarkers.projectDocsHash,
26798
26843
  materializedAt: snapshotMarkers.materializedAt,
26799
26844
  sessionFactsVersion: snapshotMarkers.sessionFactsVersion,
26800
- upgradeState: encodeCachedM0UpgradeIdentity(snapshotMarkers.upgradeState, snapshotMarkers.compartmentRenderEpoch, snapshotMarkers.muralEnabled, snapshotMarkers.renderBudgetIdentity, snapshotMarkers.memoryRenderEpoch),
26845
+ upgradeState: encodeCachedM0UpgradeIdentity(snapshotMarkers.upgradeState, snapshotMarkers.compartmentRenderEpoch, snapshotMarkers.muralEnabled, snapshotMarkers.renderBudgetIdentity, snapshotMarkers.memoryRenderEpoch, snapshotMarkers.renderedBudgets ?? null),
26801
26846
  systemHash: snapshotMarkers.systemHash,
26802
26847
  modelKey: snapshotMarkers.modelKey,
26803
26848
  projectIdentity: snapshotMarkers.projectIdentity
@@ -27057,7 +27102,8 @@ function markersFromCachedPiRow(row, compartmentsForNormalization) {
27057
27102
  modelKey: row.cached_m0_model_key ?? "",
27058
27103
  projectIdentity: row.cached_m0_project_identity ?? null,
27059
27104
  muralEnabled: cachedUpgradeIdentity.muralEnabled ?? false,
27060
- renderBudgetIdentity: cachedUpgradeIdentity.renderBudgetIdentity ?? ""
27105
+ renderBudgetIdentity: cachedUpgradeIdentity.renderBudgetIdentity ?? "",
27106
+ renderedBudgets: cachedUpgradeIdentity.renderedBudgets
27061
27107
  };
27062
27108
  }
27063
27109
  function cachedPiRowMatchesSnapshot(args) {
@@ -30454,6 +30500,9 @@ function createPiToolResultPart(working, messageIndex, partIndex, markDirty) {
30454
30500
  inputTokenCount: 0
30455
30501
  };
30456
30502
  },
30503
+ hasUserAnswer() {
30504
+ return hasUserAnswerMetadata(working[messageIndex].details);
30505
+ },
30457
30506
  replaceWithSentinel(sentinelText) {
30458
30507
  const current = working[messageIndex].content;
30459
30508
  const newContent = current.slice();
@@ -31762,6 +31811,7 @@ function registerPiContextHandler(pi, baseOptions) {
31762
31811
  injection: options.injection ? {
31763
31812
  ...options.injection,
31764
31813
  memoryEnabled: options.injection.memoryEnabled,
31814
+ historyBudgetPolicyIdentity: historyBudgetPolicyIdentity(options.historian?.historyBudgetPercentage, options.historian?.executeThresholdPercentage, liveModelBySession.get(sessionId), options.historian?.executeThresholdTokens),
31765
31815
  historyBudgetTokens: resolveHistoryBudgetTokensForPi({
31766
31816
  historyBudgetPercentage: options.historian?.historyBudgetPercentage,
31767
31817
  usagePercentage,
@@ -32637,6 +32687,7 @@ async function runCompactionOffPipeline(args) {
32637
32687
  injectDocs: args.injection.injectDocs,
32638
32688
  injectionBudgetTokens: args.injection.injectionBudgetTokens,
32639
32689
  historyBudgetTokens: args.injection.historyBudgetTokens,
32690
+ historyBudgetPolicyIdentity: args.injection.historyBudgetPolicyIdentity,
32640
32691
  muralEnabled: args.injection.muralEnabled === true,
32641
32692
  compactionOff: true
32642
32693
  }, args.db, args.messages, args.entryIds, false, args.injectionPassSnapshot);
@@ -32755,6 +32806,7 @@ async function runPipeline(args) {
32755
32806
  injectDocs: args.injection.injectDocs,
32756
32807
  injectionBudgetTokens: args.injection.injectionBudgetTokens,
32757
32808
  historyBudgetTokens: args.injection.historyBudgetTokens,
32809
+ historyBudgetPolicyIdentity: args.injection.historyBudgetPolicyIdentity,
32758
32810
  hardSignals: piHardSignals,
32759
32811
  muralEnabled: args.injection.muralEnabled === true,
32760
32812
  freezePrefixForPass: true,
@@ -35939,7 +35991,7 @@ function buildStatusView(source, options) {
35939
35991
  // package.json
35940
35992
  var package_default = {
35941
35993
  name: "@cortexkit/pi-magic-context",
35942
- version: "0.44.3",
35994
+ version: "0.44.4",
35943
35995
  type: "module",
35944
35996
  description: "Pi and OMP coding agent extension for Magic Context — cross-session memory and context management",
35945
35997
  main: "dist/index.js",
@@ -23,7 +23,7 @@ import {
23
23
  getRawSessionTagKeysThrough2,
24
24
  getLegacyProtectedTailStartOrdinal2,
25
25
  readSessionChunk2
26
- } from "./index-tckvezry.js";
26
+ } from "./index-npagr1cy.js";
27
27
  import"./index-59dmj4zs.js";
28
28
  export {
29
29
  cleanUserText2 as cleanUserText,
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  TOKEN_BUDGET_TOOL_REFUSAL
3
- } from "./index-tckvezry.js";
3
+ } from "./index-npagr1cy.js";
4
4
  import {
5
5
  setHarness,
6
6
  log
@@ -13,7 +13,7 @@ import {
13
13
  ensureProjectRegisteredFromPiDirectory,
14
14
  resolvePiHarnessKind,
15
15
  registerMagicContextTools
16
- } from "./index-atb1ecv9.js";
16
+ } from "./index-5am7amy4.js";
17
17
  import"./index-97e5fzy3.js";
18
18
 
19
19
  // src/subagent-entry.ts
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/pi-magic-context",
3
- "version": "0.44.3",
3
+ "version": "0.44.4",
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",